Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-harness/blob/main/cli/src/agent.ts # omega-harness Agent skills for operating, encoding and communicating in Omega (.om) and the AIEN repositories Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-harness / cli / src / agent.ts` 539 lines · 17266 bytes Raw Blame History 1 import fs from 'node:fs'; 2 import path from 'node:path'; 3 import { GoogleGenAI, type Content, type FunctionCall, type Part } from '@google/genai'; 4 import { getConfigDir, type ProviderKind } from './config.js'; 5 import { 6 TOOL_DECLARATIONS, 7 VALID_TOOL_NAMES, 8 executeTool, 9 formatToolArgsPreview, 10 needsApproval, 11 type ToolContext, 12 } from './tools.js'; 13 import { 14 callInklingChat, 15 probeInkling, 16 type InklingMessage, 17 } from './inkling.js'; 18 import { SessionState } from './state.js'; 19 20 export interface TokenUsage { 21 promptTokens: number; 22 outputTokens: number; 23 totalTokens: number; 24 } 25 26 export interface ToolEvent { 27 id: string; 28 name: string; 29 args: Record; 30 argsPreview: string; 31 status: 'pending' | 'running' | 'success' | 'error' | 'denied'; 32 preview?: string; 33 } 34 35 export type ApprovalDecision = 'allow' | 'always' | 'deny'; 36 37 export interface AgentCallbacks { 38 onTextDelta: (chunk: string) => void; 39 onToolStart: (event: ToolEvent) => void; 40 onToolUpdate: (event: ToolEvent) => void; 41 onRequestApproval: (event: ToolEvent) => Promise; 42 onUsageUpdate?: (usage: TokenUsage) => void; 43 } 44 45 /** 46 * Expands @path tokens in user prompts into attached file context blocks. 47 */ 48 export function expandAtMentions(prompt: string, cwd: string): { expanded: string; attachedFiles: string[] } { 49 const attachedFiles: string[] = []; 50 const attachments: string[] = []; 51 const regex = /(^|\s)@([^\s@]+)/g; 52 53 for (const match of prompt.matchAll(regex)) { 54 const rawTarget = match[2].replace(/[.,;:!?)]+$/, ''); 55 const fullPath = path.isAbsolute(rawTarget) ? rawTarget : path.resolve(cwd, rawTarget); 56 if (!fs.existsSync(fullPath)) continue; 57 try { 58 const stat = fs.statSync(fullPath); 59 if (!stat.isFile() || stat.size > 512 * 1024) continue; 60 const content = fs.readFileSync(fullPath, 'utf8'); 61 attachedFiles.push(rawTarget); 62 attachments.push(`\n${content}\n`); 63 } catch { 64 // ignore unreadable 65 } 66 } 67 68 if (attachments.length === 0) { 69 return { expanded: prompt, attachedFiles }; 70 } 71 return { 72 expanded: `${prompt}\n\n${attachments.join('\n\n')}`, 73 attachedFiles, 74 }; 75 } 76 77 export class OmegaAgent { 78 private ai: GoogleGenAI | null = null; 79 private geminiHistory: Content[] = []; 80 private inklingHistory: InklingMessage[] = []; 81 private sessionAlwaysAllowed = new Set(); 82 private subagentInstances = new Map(); 83 public state: SessionState; 84 public usage: TokenUsage = { promptTokens: 0, outputTokens: 0, totalTokens: 0 }; 85 public toolCallCount = 0; 86 87 constructor(apiKey?: string, state?: SessionState) { 88 if (apiKey) { 89 this.ai = new GoogleGenAI({ apiKey }); 90 } 91 this.state = state || new SessionState(); 92 } 93 94 setApiKey(apiKey: string): void { 95 this.ai = new GoogleGenAI({ apiKey }); 96 } 97 98 clearHistory(): void { 99 this.geminiHistory = []; 100 this.inklingHistory = []; 101 } 102 103 saveSession(name = 'latest'): string { 104 const dir = path.join(getConfigDir(), 'sessions'); 105 fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); 106 const file = path.join(dir, `${name.replace(/[^a-zA-Z0-9_-]/g, '_')}.json`); 107 const payload = { 108 savedAt: new Date().toISOString(), 109 inklingHistory: this.inklingHistory, 110 geminiHistory: this.geminiHistory, 111 usage: this.usage, 112 todos: this.state.todos, 113 }; 114 fs.writeFileSync(file, JSON.stringify(payload, null, 2) + '\n', { mode: 0o600 }); 115 return file; 116 } 117 118 loadSession(name = 'latest'): { ok: boolean; turns: number; savedAt?: string } { 119 const file = path.join(getConfigDir(), 'sessions', `${name.replace(/[^a-zA-Z0-9_-]/g, '_')}.json`); 120 try { 121 const raw = fs.readFileSync(file, 'utf8'); 122 const data = JSON.parse(raw) as { 123 savedAt?: string; 124 inklingHistory?: InklingMessage[]; 125 geminiHistory?: Content[]; 126 usage?: TokenUsage; 127 todos?: Array<{ id: string; title: string; status: 'pending' | 'in_progress' | 'completed' }>; 128 }; 129 if (Array.isArray(data.inklingHistory)) this.inklingHistory = data.inklingHistory; 130 if (Array.isArray(data.geminiHistory)) this.geminiHistory = data.geminiHistory; 131 if (data.usage) this.usage = data.usage; 132 if (Array.isArray(data.todos)) this.state.setTodos(data.todos); 133 return { ok: true, turns: this.getTurnCount(), savedAt: data.savedAt }; 134 } catch { 135 return { ok: false, turns: 0 }; 136 } 137 } 138 139 getTurnCount(): number { 140 return Math.max( 141 this.geminiHistory.filter((c) => c.role === 'user').length, 142 this.inklingHistory.filter((m) => m.role === 'user').length 143 ); 144 } 145 146 async compactHistory(opts: { 147 provider: ProviderKind; 148 model: string; 149 endpoint: string; 150 apiKey?: string; 151 }): Promise { 152 if (opts.provider === 'inkling') { 153 if (this.inklingHistory.length < 4) { 154 return 'Conversation is already short; nothing to compact.'; 155 } 156 const recent = this.inklingHistory.slice(-4); 157 this.inklingHistory = recent; 158 return `Kept last ${recent.length} messages in Inkling session context.`; 159 } 160 161 if (!this.ai || this.geminiHistory.length < 4) { 162 return 'Conversation is already short; nothing to compact.'; 163 } 164 const summaryPrompt: Content = { 165 role: 'user', 166 parts: [ 167 { 168 text: 'Summarize our session so far in concise bullet points: goals, files inspected or modified, compiler/test results, and next steps.', 169 }, 170 ], 171 }; 172 const resp = await this.ai.models.generateContent({ 173 model: opts.model, 174 contents: [...this.geminiHistory, summaryPrompt], 175 }); 176 const summary = resp.text || 'Session compacted.'; 177 this.geminiHistory = [ 178 { role: 'user', parts: [{ text: '[Compacted session context]' }] }, 179 { role: 'model', parts: [{ text: summary }] }, 180 ]; 181 return summary; 182 } 183 184 async sendTurn( 185 userPrompt: string, 186 opts: { 187 provider: ProviderKind; 188 endpoint: string; 189 apiKey?: string; 190 model: string; 191 systemInstruction: string; 192 toolContext: ToolContext; 193 callbacks: AgentCallbacks; 194 signal?: AbortSignal; 195 depth?: number; 196 } 197 ): Promise { 198 const depth = opts.depth ?? 0; 199 200 // Bind autonomous subagent runner onto this session's state 201 const boundState = opts.toolContext.state || this.state; 202 if (depth < 2) { 203 boundState.runSubagent = async (req) => { 204 let sub = req.existingId ? this.subagentInstances.get(req.existingId) : undefined; 205 if (!sub) { 206 sub = new OmegaAgent(opts.apiKey, new SessionState()); 207 this.subagentInstances.set(req.id, sub); 208 } 209 const subSystem = 210 `You are subagent "${req.role}" (${req.id}) spawned by Ω Omega Harness.\n` + 211 `Mode: ${req.mode}. Focus strictly on the assigned task and return a concise, factual report with evidence.\n` + 212 opts.systemInstruction; 213 214 const subStartCalls = sub.toolCallCount; 215 const text = await sub.sendTurn(req.task, { 216 provider: opts.provider, 217 endpoint: opts.endpoint, 218 apiKey: opts.apiKey, 219 model: opts.model, 220 systemInstruction: subSystem, 221 toolContext: { 222 ...opts.toolContext, 223 state: sub.state, 224 readOnlyOnly: req.mode === 'read-only', 225 }, 226 signal: opts.signal, 227 depth: depth + 1, 228 callbacks: { 229 onTextDelta: () => {}, 230 onToolStart: (ev) => 231 opts.callbacks.onToolStart({ 232 ...ev, 233 name: `${req.id}:${ev.name}`, 234 }), 235 onToolUpdate: (ev) => 236 opts.callbacks.onToolUpdate({ 237 ...ev, 238 name: `${req.id}:${ev.name}`, 239 }), 240 onRequestApproval: opts.callbacks.onRequestApproval, 241 onUsageUpdate: opts.callbacks.onUsageUpdate, 242 }, 243 }); 244 return { text, toolCalls: sub.toolCallCount - subStartCalls }; 245 }; 246 } 247 248 const toolContext: ToolContext = { 249 ...opts.toolContext, 250 state: boundState, 251 }; 252 253 if (opts.provider === 'inkling') { 254 return this.sendInklingTurn(userPrompt, { ...opts, toolContext }); 255 } 256 return this.sendGeminiTurn(userPrompt, { ...opts, toolContext }); 257 } 258 259 private async runToolWithApproval( 260 name: string, 261 args: Record, 262 toolContext: ToolContext, 263 callbacks: AgentCallbacks 264 ): Promise<{ approved: boolean; ok: boolean; output: string }> { 265 const event: ToolEvent = { 266 id: `${Date.now()}-${Math.random().toString(36).slice(2, 7)}`, 267 name, 268 args, 269 argsPreview: formatToolArgsPreview(name, args), 270 status: 'pending', 271 }; 272 this.toolCallCount += 1; 273 callbacks.onToolStart(event); 274 275 const requiresPrompt = 276 needsApproval(name, toolContext.approvalMode) && 277 !this.sessionAlwaysAllowed.has(name); 278 279 let approved = true; 280 if (requiresPrompt) { 281 const decision = await callbacks.onRequestApproval(event); 282 if (decision === 'always') { 283 this.sessionAlwaysAllowed.add(name); 284 } else if (decision === 'deny') { 285 approved = false; 286 } 287 } 288 289 if (!approved) { 290 callbacks.onToolUpdate({ 291 ...event, 292 status: 'denied', 293 preview: 'Denied by operator', 294 }); 295 return { approved: false, ok: false, output: 'Tool execution denied by operator.' }; 296 } 297 298 callbacks.onToolUpdate({ ...event, status: 'running' }); 299 const result = await executeTool(name, args, toolContext); 300 callbacks.onToolUpdate({ 301 ...event, 302 status: result.ok ? 'success' : 'error', 303 preview: result.preview, 304 }); 305 return { approved: true, ok: result.ok, output: result.output }; 306 } 307 308 private async sendInklingTurn( 309 userPrompt: string, 310 opts: { 311 endpoint: string; 312 apiKey?: string; 313 model: string; 314 systemInstruction: string; 315 toolContext: ToolContext; 316 callbacks: AgentCallbacks; 317 signal?: AbortSignal; 318 } 319 ): Promise { 320 const health = await probeInkling(opts.endpoint, opts.apiKey); 321 if (!health.online) { 322 throw new Error( 323 `Cannot reach Inkling server at ${opts.endpoint} (${health.error || 'offline'}). ` + 324 `Run \`omega up\` to boot Inkling-2-Mini + Arboris on Spark.` 325 ); 326 } 327 328 const { expanded } = expandAtMentions(userPrompt, opts.toolContext.cwd); 329 this.inklingHistory.push({ role: 'user', content: expanded }); 330 331 const engine = health.engine === 'inkling2-serve' ? 'inkling2-serve' : 'openai-compat'; 332 let fullAssistantText = ''; 333 const maxRounds = engine === 'inkling2-serve' ? 10 : 24; 334 const seenSignatures = new Set(); 335 336 for (let round = 0; round < maxRounds; round++) { 337 if (opts.signal?.aborted) throw new Error('Cancelled by user'); 338 339 const messages: InklingMessage[] = [ 340 { role: 'system', content: opts.systemInstruction }, 341 ...this.inklingHistory, 342 ]; 343 344 const { parsed, rawContent, usage } = await callInklingChat({ 345 endpoint: opts.endpoint, 346 model: opts.model, 347 messages, 348 tools: TOOL_DECLARATIONS, 349 apiKey: opts.apiKey, 350 engine, 351 signal: opts.signal, 352 onTextDelta: opts.callbacks.onTextDelta, 353 }); 354 355 if (usage) { 356 this.usage = { 357 promptTokens: this.usage.promptTokens + usage.promptTokens, 358 outputTokens: this.usage.outputTokens + usage.outputTokens, 359 totalTokens: this.usage.totalTokens + usage.totalTokens, 360 }; 361 opts.callbacks.onUsageUpdate?.(this.usage); 362 } 363 364 // Filter to valid registered tool names 365 const validCalls = parsed.toolCalls.filter((tc) => VALID_TOOL_NAMES.has(tc.name)); 366 367 if (parsed.text) { 368 fullAssistantText += (fullAssistantText ? '\n' : '') + parsed.text; 369 } 370 371 this.inklingHistory.push({ 372 role: 'assistant', 373 content: parsed.text, 374 ...(engine === 'inkling2-serve' ? { rawAssistantOutput: rawContent } : {}), 375 ...(validCalls.length > 0 376 ? { 377 tool_calls: validCalls.map((tc) => ({ 378 id: tc.id, 379 type: 'function' as const, 380 function: { name: tc.name, arguments: JSON.stringify(tc.args) }, 381 })), 382 } 383 : {}), 384 }); 385 386 if (validCalls.length === 0) { 387 break; 388 } 389 390 let executedAnyNew = false; 391 for (const tc of validCalls) { 392 const sig = `${tc.name}:${JSON.stringify(tc.args)}`; 393 if (seenSignatures.has(sig)) { 394 // Loop breaker: do not execute identical tool call twice in the same turn 395 this.inklingHistory.push({ 396 role: 'tool', 397 name: tc.name, 398 tool_call_id: tc.id, 399 content: `Already executed ${tc.name} with those exact args above. Do NOT call it again; answer the user now.`, 400 }); 401 continue; 402 } 403 seenSignatures.add(sig); 404 executedAnyNew = true; 405 const res = await this.runToolWithApproval( 406 tc.name, 407 tc.args, 408 opts.toolContext, 409 opts.callbacks 410 ); 411 this.inklingHistory.push({ 412 role: 'tool', 413 name: tc.name, 414 tool_call_id: tc.id, 415 content: res.output, 416 }); 417 } 418 419 if (!executedAnyNew) { 420 // Model attempted only duplicate calls — break cleanly after reporting last tool result 421 const lastObs = [...this.inklingHistory].reverse().find((m) => m.role === 'tool' && !m.content.startsWith('Already executed')); 422 if (!fullAssistantText.trim() && lastObs) { 423 fullAssistantText = lastObs.content; 424 opts.callbacks.onTextDelta(lastObs.content); 425 } 426 break; 427 } 428 } 429 430 return fullAssistantText; 431 } 432 433 private async sendGeminiTurn( 434 userPrompt: string, 435 opts: { 436 apiKey?: string; 437 model: string; 438 systemInstruction: string; 439 toolContext: ToolContext; 440 callbacks: AgentCallbacks; 441 signal?: AbortSignal; 442 } 443 ): Promise { 444 if (!this.ai) { 445 if (opts.apiKey) { 446 this.ai = new GoogleGenAI({ apiKey: opts.apiKey }); 447 } else { 448 throw new Error('No Gemini API key configured. Run `/auth ` or switch to `/provider inkling`.'); 449 } 450 } 451 452 const { expanded } = expandAtMentions(userPrompt, opts.toolContext.cwd); 453 this.geminiHistory.push({ role: 'user', parts: [{ text: expanded }] }); 454 455 let fullAssistantText = ''; 456 const maxRounds = 24; 457 458 for (let round = 0; round < maxRounds; round++) { 459 if (opts.signal?.aborted) { 460 throw new Error('Cancelled by user'); 461 } 462 463 const stream = await this.ai.models.generateContentStream({ 464 model: opts.model, 465 contents: this.geminiHistory, 466 config: { 467 systemInstruction: opts.systemInstruction, 468 tools: [{ functionDeclarations: TOOL_DECLARATIONS }], 469 }, 470 }); 471 472 let roundText = ''; 473 const collectedCalls: FunctionCall[] = []; 474 const modelParts: Part[] = []; 475 476 for await (const chunk of stream) { 477 if (opts.signal?.aborted) { 478 throw new Error('Cancelled by user'); 479 } 480 481 if (chunk.usageMetadata) { 482 const p = chunk.usageMetadata.promptTokenCount ?? 0; 483 const o = chunk.usageMetadata.candidatesTokenCount ?? 0; 484 const t = chunk.usageMetadata.totalTokenCount ?? p + o; 485 if (t > 0) { 486 this.usage = { 487 promptTokens: this.usage.promptTokens + p, 488 outputTokens: this.usage.outputTokens + o, 489 totalTokens: this.usage.totalTokens + t, 490 }; 491 opts.callbacks.onUsageUpdate?.(this.usage); 492 } 493 } 494 495 const candidate = chunk.candidates?.[0]; 496 const parts = candidate?.content?.parts || []; 497 for (const part of parts) { 498 if (part.text) { 499 roundText += part.text; 500 fullAssistantText += part.text; 501 opts.callbacks.onTextDelta(part.text); 502 } 503 if (part.functionCall) { 504 collectedCalls.push(part.functionCall); 505 modelParts.push(part); 506 } 507 } 508 } 509 510 if (roundText) { 511 modelParts.unshift({ text: roundText }); 512 } 513 if (modelParts.length > 0) { 514 this.geminiHistory.push({ role: 'model', parts: modelParts }); 515 } 516 517 if (collectedCalls.length === 0) { 518 break; 519 } 520 521 const responseParts: Part[] = []; 522 for (const call of collectedCalls) { 523 const name = call.name || 'unknown'; 524 const args = (call.args || {}) as Record; 525 const res = await this.runToolWithApproval(name, args, opts.toolContext, opts.callbacks); 526 responseParts.push({ 527 functionResponse: { 528 name, 529 response: res.approved ? { ok: res.ok, output: res.output } : { ok: false, error: res.output }, 530 }, 531 }); 532 } 533 534 this.geminiHistory.push({ role: 'user', parts: responseParts }); 535 } 536 537 return fullAssistantText; 538 } 539 }