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/tools.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 / tools.ts` 1034 lines · 38845 bytes Raw Blame History 1 import fs from 'node:fs'; 2 import path from 'node:path'; 3 import { execFileSync, execSync, spawnSync } from 'node:child_process'; 4 import { Type, type FunctionDeclaration } from '@google/genai'; 5 import type { ApprovalMode } from './config.js'; 6 import { 7 compileAndRunOmFile, 8 compileOmFile, 9 discoverSkills, 10 readPinInfo, 11 readSkillContent, 12 } from './harness.js'; 13 import { 14 SessionState, 15 formatMemories, 16 saveMemory, 17 type TodoItem, 18 } from './state.js'; 19 20 export interface ToolContext { 21 cwd: string; 22 harnessRoot: string; 23 omcPath?: string; 24 approvalMode: ApprovalMode; 25 state?: SessionState; 26 readOnlyOnly?: boolean; 27 } 28 29 export interface ToolExecutionResult { 30 ok: boolean; 31 output: string; 32 preview: string; 33 } 34 35 export const READ_ONLY_TOOLS = new Set([ 36 'read_file', 37 'list_dir', 38 'glob_files', 39 'grep_search', 40 'git_status', 41 'git_diff', 42 'git_log', 43 'web_fetch', 44 'web_search', 45 'todo_read', 46 'todo_write', 47 'memory_read', 48 'memory_save', 49 'list_subagents', 50 'spawn_subagent', 51 'spawn_parallel_subagents', 52 'message_subagent', 53 'list_skills', 54 'load_skill', 55 'omega_pin', 56 'omc_compile', 57 ]); 58 59 export const EDIT_TOOLS = new Set(['write_file', 'edit_file', 'delete_file']); 60 61 export function needsApproval(toolName: string, mode: ApprovalMode): boolean { 62 if (mode === 'yolo') return false; 63 if (READ_ONLY_TOOLS.has(toolName)) return false; 64 if (mode === 'auto-edit' && EDIT_TOOLS.has(toolName)) return false; 65 if (mode === 'omega-only' && EDIT_TOOLS.has(toolName)) return false; 66 return true; 67 } 68 69 export const TOOL_DECLARATIONS: FunctionDeclaration[] = [ 70 // File & Code tools 71 { 72 name: 'read_file', 73 description: 'Read a text file from disk with optional 1-based start_line and end_line.', 74 parameters: { 75 type: Type.OBJECT, 76 properties: { 77 path: { type: Type.STRING, description: 'Absolute or workspace-relative file path' }, 78 start_line: { type: Type.INTEGER, description: '1-based start line (optional)' }, 79 end_line: { type: Type.INTEGER, description: '1-based inclusive end line (optional)' }, 80 }, 81 required: ['path'], 82 }, 83 }, 84 { 85 name: 'write_file', 86 description: 'Create or overwrite a file with the given content. Creates parent directories automatically.', 87 parameters: { 88 type: Type.OBJECT, 89 properties: { 90 path: { type: Type.STRING, description: 'Absolute or workspace-relative file path' }, 91 content: { type: Type.STRING, description: 'Full file contents to write' }, 92 }, 93 required: ['path', 'content'], 94 }, 95 }, 96 { 97 name: 'edit_file', 98 description: 'Replace an exact contiguous block of text in an existing file.', 99 parameters: { 100 type: Type.OBJECT, 101 properties: { 102 path: { type: Type.STRING, description: 'Absolute or workspace-relative file path' }, 103 target: { type: Type.STRING, description: 'Exact existing text to replace' }, 104 replacement: { type: Type.STRING, description: 'Replacement text' }, 105 }, 106 required: ['path', 'target', 'replacement'], 107 }, 108 }, 109 { 110 name: 'delete_file', 111 description: 'Delete a file from disk.', 112 parameters: { 113 type: Type.OBJECT, 114 properties: { 115 path: { type: Type.STRING, description: 'File path to delete' }, 116 }, 117 required: ['path'], 118 }, 119 }, 120 { 121 name: 'list_dir', 122 description: 'List files and subdirectories in a directory.', 123 parameters: { 124 type: Type.OBJECT, 125 properties: { 126 path: { type: Type.STRING, description: 'Directory path (defaults to cwd)' }, 127 }, 128 }, 129 }, 130 { 131 name: 'glob_files', 132 description: 'Find files matching a wildcard pattern (e.g. "*.om", "src/**/*.ts").', 133 parameters: { 134 type: Type.OBJECT, 135 properties: { 136 pattern: { type: Type.STRING, description: 'Glob pattern' }, 137 dir: { type: Type.STRING, description: 'Base directory (defaults to cwd)' }, 138 }, 139 required: ['pattern'], 140 }, 141 }, 142 { 143 name: 'grep_search', 144 description: 'Search for text or regex across workspace files.', 145 parameters: { 146 type: Type.OBJECT, 147 properties: { 148 query: { type: Type.STRING, description: 'Search text or regex' }, 149 dir: { type: Type.STRING, description: 'Directory to search (defaults to cwd)' }, 150 glob: { type: Type.STRING, description: 'Optional filename filter (e.g. "*.om")' }, 151 }, 152 required: ['query'], 153 }, 154 }, 155 156 // Execution & Git tools 157 { 158 name: 'run_shell', 159 description: 'Execute a shell command in cwd and return exit code, stdout, and stderr.', 160 parameters: { 161 type: Type.OBJECT, 162 properties: { 163 command: { type: Type.STRING, description: 'Shell command to run' }, 164 timeout_ms: { type: Type.INTEGER, description: 'Timeout in ms (default 30000)' }, 165 }, 166 required: ['command'], 167 }, 168 }, 169 { 170 name: 'git_status', 171 description: 'Show git branch and short working-tree status.', 172 parameters: { type: Type.OBJECT, properties: {} }, 173 }, 174 { 175 name: 'git_diff', 176 description: 'Show git diff for unstaged or staged changes.', 177 parameters: { 178 type: Type.OBJECT, 179 properties: { 180 path: { type: Type.STRING, description: 'Optional file path filter' }, 181 staged: { type: Type.BOOLEAN, description: 'If true, show staged diff (--cached)' }, 182 }, 183 }, 184 }, 185 { 186 name: 'git_log', 187 description: 'Show recent git commit history.', 188 parameters: { 189 type: Type.OBJECT, 190 properties: { 191 count: { type: Type.INTEGER, description: 'Number of commits (default 10)' }, 192 }, 193 }, 194 }, 195 { 196 name: 'git_commit', 197 description: 'Stage specified files (or all modified files) and create a git commit.', 198 parameters: { 199 type: Type.OBJECT, 200 properties: { 201 message: { type: Type.STRING, description: 'Commit message' }, 202 files: { 203 type: Type.ARRAY, 204 items: { type: Type.STRING }, 205 description: 'Optional list of file paths to stage (defaults to git add -u)', 206 }, 207 }, 208 required: ['message'], 209 }, 210 }, 211 212 // Web tools 213 { 214 name: 'web_fetch', 215 description: 'Fetch a URL over HTTP/HTTPS and return clean readable text.', 216 parameters: { 217 type: Type.OBJECT, 218 properties: { 219 url: { type: Type.STRING, description: 'HTTP or HTTPS URL to fetch' }, 220 max_chars: { type: Type.INTEGER, description: 'Max characters to return (default 8000)' }, 221 }, 222 required: ['url'], 223 }, 224 }, 225 { 226 name: 'web_search', 227 description: 'Search the web and return top results with titles, URLs, and snippets.', 228 parameters: { 229 type: Type.OBJECT, 230 properties: { 231 query: { type: Type.STRING, description: 'Search query' }, 232 max_results: { type: Type.INTEGER, description: 'Max results (default 5)' }, 233 }, 234 required: ['query'], 235 }, 236 }, 237 238 // Task Planning & Persistent Memory tools 239 { 240 name: 'todo_write', 241 description: 'Create or update the session task checklist.', 242 parameters: { 243 type: Type.OBJECT, 244 properties: { 245 items: { 246 type: Type.ARRAY, 247 items: { 248 type: Type.OBJECT, 249 properties: { 250 id: { type: Type.STRING }, 251 title: { type: Type.STRING }, 252 status: { type: Type.STRING, description: 'pending | in_progress | completed' }, 253 }, 254 required: ['title'], 255 }, 256 description: 'List of todo items', 257 }, 258 }, 259 required: ['items'], 260 }, 261 }, 262 { 263 name: 'todo_read', 264 description: 'Read the current session task checklist.', 265 parameters: { type: Type.OBJECT, properties: {} }, 266 }, 267 { 268 name: 'memory_save', 269 description: 'Save a persistent key-value memory across sessions.', 270 parameters: { 271 type: Type.OBJECT, 272 properties: { 273 key: { type: Type.STRING, description: 'Short memory key' }, 274 value: { type: Type.STRING, description: 'Fact or preference to remember' }, 275 }, 276 required: ['key', 'value'], 277 }, 278 }, 279 { 280 name: 'memory_read', 281 description: 'Read one or all persistent memories.', 282 parameters: { 283 type: Type.OBJECT, 284 properties: { 285 key: { type: Type.STRING, description: 'Optional specific memory key' }, 286 }, 287 }, 288 }, 289 290 // Subagent & Multi-Agent Delegation tools (runs Inkling-2-Mini subagents!) 291 { 292 name: 'spawn_subagent', 293 description: 'Spin up an autonomous subagent using the same model (Inkling-2-Mini / Gemini) in an isolated context to research, audit, or execute a subtask and return its result.', 294 parameters: { 295 type: Type.OBJECT, 296 properties: { 297 role: { type: Type.STRING, description: 'Short role title (e.g. "Codebase Researcher", "Verifier")' }, 298 task: { type: Type.STRING, description: 'Clear actionable instructions for the subagent' }, 299 mode: { type: Type.STRING, description: '"read-only" (default) or "full"' }, 300 }, 301 required: ['role', 'task'], 302 }, 303 }, 304 { 305 name: 'spawn_parallel_subagents', 306 description: 'Launch multiple subagents concurrently (leveraging inkling2-serve N=8 KV slots) and aggregate all results.', 307 parameters: { 308 type: Type.OBJECT, 309 properties: { 310 tasks: { 311 type: Type.ARRAY, 312 items: { 313 type: Type.OBJECT, 314 properties: { 315 role: { type: Type.STRING }, 316 task: { type: Type.STRING }, 317 mode: { type: Type.STRING }, 318 }, 319 required: ['role', 'task'], 320 }, 321 description: 'Array of subagent specifications to execute in parallel', 322 }, 323 }, 324 required: ['tasks'], 325 }, 326 }, 327 { 328 name: 'list_subagents', 329 description: 'List all subagents spawned in this session with their status and summaries.', 330 parameters: { type: Type.OBJECT, properties: {} }, 331 }, 332 { 333 name: 'message_subagent', 334 description: 'Send a follow-up task or question to an existing subagent by ID.', 335 parameters: { 336 type: Type.OBJECT, 337 properties: { 338 id: { type: Type.STRING, description: 'Subagent ID from spawn_subagent or list_subagents' }, 339 message: { type: Type.STRING, description: 'Follow-up prompt for the subagent' }, 340 }, 341 required: ['id', 'message'], 342 }, 343 }, 344 345 // Omega Harness Native tools 346 { 347 name: 'list_skills', 348 description: 'List all available Omega Harness skills and their descriptions.', 349 parameters: { type: Type.OBJECT, properties: {} }, 350 }, 351 { 352 name: 'load_skill', 353 description: 'Load the full instructions of an Omega Harness skill by name.', 354 parameters: { 355 type: Type.OBJECT, 356 properties: { 357 name: { type: Type.STRING, description: 'Skill name' }, 358 }, 359 required: ['name'], 360 }, 361 }, 362 { 363 name: 'omc_compile', 364 description: 'Compile an Omega (.om) source file with local omc and enrich error N from reference.tsv.', 365 parameters: { 366 type: Type.OBJECT, 367 properties: { 368 path: { type: Type.STRING, description: 'Path to .om file' }, 369 output: { type: Type.STRING, description: 'Optional output binary path' }, 370 }, 371 required: ['path'], 372 }, 373 }, 374 { 375 name: 'omc_run', 376 description: 'Compile and execute an Omega (.om) file, returning exit code, stdout, and stderr.', 377 parameters: { 378 type: Type.OBJECT, 379 properties: { 380 path: { type: Type.STRING, description: 'Path to .om file' }, 381 stdin: { type: Type.STRING, description: 'Optional stdin string' }, 382 timeout_ms: { type: Type.INTEGER, description: 'Execution timeout in ms (default 10000)' }, 383 }, 384 required: ['path'], 385 }, 386 }, 387 { 388 name: 'omega_pin', 389 description: 'Inspect omega-harness PIN and compare it against local omc sha256.', 390 parameters: { type: Type.OBJECT, properties: {} }, 391 }, 392 ]; 393 394 export const VALID_TOOL_NAMES = new Set(TOOL_DECLARATIONS.map((d) => d.name || '')); 395 396 function resolvePath(cwd: string, p?: string): string { 397 if (!p) return cwd; 398 if (p.startsWith('~/')) { 399 return path.join(process.env.HOME || '', p.slice(2)); 400 } 401 return path.isAbsolute(p) ? p : path.resolve(cwd, p); 402 } 403 404 function makePreview(text: string, maxLines = 4, maxChars = 260): string { 405 const trimmed = text.trim(); 406 if (!trimmed) return '(empty output)'; 407 const lines = trimmed.split(/\r?\n/); 408 const head = lines.slice(0, maxLines).join('\n'); 409 const truncated = head.length > maxChars ? head.slice(0, maxChars) + '…' : head; 410 if (lines.length > maxLines) { 411 return `${truncated}\n… (+${lines.length - maxLines} more lines)`; 412 } 413 return truncated; 414 } 415 416 function isAllowedInOmegaOnly(filePath: string): boolean { 417 const base = path.basename(filePath); 418 return base.endsWith('.om') || base === 'NOTES.md'; 419 } 420 421 function formatOmcCompileFeedback(res: ReturnType): string { 422 if (res.ok) { 423 return `omc compile PASS (${res.binarySize ?? 0} bytes${res.outputPath ? `, out=${res.outputPath}` : ''})`; 424 } 425 const parts = [`omc compile FAIL (exit ${res.exitCode}): ${res.stderr}`]; 426 if (res.errorDoc) { 427 parts.push(`error ${res.errorDoc.code} meaning: ${res.errorDoc.meaning}`); 428 if (res.errorDoc.cause) parts.push(`cause: ${res.errorDoc.cause}`); 429 if (res.errorDoc.fix) parts.push(`fix: ${res.errorDoc.fix}`); 430 } 431 return parts.join('\n'); 432 } 433 434 function globToRegex(pattern: string): RegExp { 435 const escaped = pattern 436 .replace(/[.+^${}()|[\]\\]/g, '\\$&') 437 .replace(/\*\*/g, '___GLOBSTAR___') 438 .replace(/\*/g, '[^/]*') 439 .replace(/___GLOBSTAR___/g, '.*') 440 .replace(/\?/g, '[^/]'); 441 return new RegExp(`^${escaped}$`); 442 } 443 444 function walkFiles(baseDir: string, maxFiles = 2000): string[] { 445 const out: string[] = []; 446 const skip = new Set(['.git', 'node_modules', 'dist', 'build', '.next', 'target']); 447 448 function visit(dir: string) { 449 if (out.length >= maxFiles) return; 450 let entries: fs.Dirent[]; 451 try { 452 entries = fs.readdirSync(dir, { withFileTypes: true }); 453 } catch { 454 return; 455 } 456 for (const entry of entries) { 457 if (out.length >= maxFiles) return; 458 if (skip.has(entry.name)) continue; 459 const full = path.join(dir, entry.name); 460 if (entry.isDirectory()) { 461 visit(full); 462 } else if (entry.isFile()) { 463 out.push(path.relative(baseDir, full)); 464 } 465 } 466 } 467 468 visit(baseDir); 469 return out; 470 } 471 472 export function stripHtmlToText(html: string): string { 473 return html 474 .replace(//gi, ' ') 475 .replace(//gi, ' ') 476 .replace(/<[^>]+>/g, ' ') 477 .replace(/&/g, '&') 478 .replace(/</g, '<') 479 .replace(/>/g, '>') 480 .replace(/"/g, '"') 481 .replace(/'/g, "'") 482 .replace(/ /g, ' ') 483 .replace(/\s+/g, ' ') 484 .trim(); 485 } 486 487 export function parseDuckDuckGoHtml(html: string, maxResults = 5): Array<{ title: string; url: string; snippet: string }> { 488 const results: Array<{ title: string; url: string; snippet: string }> = []; 489 const linkRe = /]+class="[^"]*result__a[^"]*"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/gi; 490 const snippetRe = /]+class="[^"]*result__snippet[^"]*"[^>]*>([\s\S]*?)<\/a>|]+class="[^"]*result__snippet[^"]*"[^>]*>([\s\S]*?)<\/div>/gi; 491 492 const links: Array<{ url: string; title: string }> = []; 493 for (const m of html.matchAll(linkRe)) { 494 let url = m[1]; 495 const uddg = url.match(/uddg=([^&]+)/); 496 if (uddg) { 497 try { 498 url = decodeURIComponent(uddg[1]); 499 } catch { 500 // keep original 501 } 502 } 503 links.push({ url, title: stripHtmlToText(m[2]) }); 504 if (links.length >= maxResults) break; 505 } 506 507 const snippets: string[] = []; 508 for (const m of html.matchAll(snippetRe)) { 509 snippets.push(stripHtmlToText(m[1] || m[2] || '')); 510 if (snippets.length >= maxResults) break; 511 } 512 513 for (let i = 0; i < links.length; i++) { 514 results.push({ 515 title: links[i].title, 516 url: links[i].url, 517 snippet: snippets[i] || '', 518 }); 519 } 520 return results; 521 } 522 523 export function formatToolArgsPreview(name: string, args: Record): string { 524 const pick = (k: string) => (args[k] !== undefined ? String(args[k]) : undefined); 525 switch (name) { 526 case 'read_file': 527 case 'write_file': 528 case 'edit_file': 529 case 'delete_file': 530 case 'omc_compile': 531 case 'omc_run': 532 return pick('path') || ''; 533 case 'run_shell': { 534 const cmd = pick('command') || ''; 535 return cmd.length > 72 ? cmd.slice(0, 69) + '...' : cmd; 536 } 537 case 'grep_search': 538 return `"${pick('query') || ''}"${args.dir ? ` in ${pick('dir')}` : ''}`; 539 case 'glob_files': 540 return pick('pattern') || ''; 541 case 'load_skill': 542 return pick('name') || ''; 543 case 'list_dir': 544 return pick('path') || '.'; 545 case 'web_fetch': 546 return pick('url') || ''; 547 case 'web_search': 548 return `"${pick('query') || ''}"`; 549 case 'spawn_subagent': 550 return `${pick('role') || 'worker'}: ${(pick('task') || '').slice(0, 50)}`; 551 case 'spawn_parallel_subagents': { 552 const n = Array.isArray(args.tasks) ? args.tasks.length : 0; 553 return `${n} parallel subagents`; 554 } 555 case 'message_subagent': 556 return `${pick('id') || ''}: ${(pick('message') || '').slice(0, 40)}`; 557 case 'git_commit': 558 return `"${(pick('message') || '').slice(0, 50)}"`; 559 case 'memory_save': 560 return `${pick('key') || ''}`; 561 default: 562 return Object.keys(args).length ? JSON.stringify(args).slice(0, 60) : ''; 563 } 564 } 565 566 export async function executeTool( 567 name: string, 568 args: Record, 569 ctx: ToolContext 570 ): Promise { 571 if (ctx.readOnlyOnly && !READ_ONLY_TOOLS.has(name)) { 572 const msg = `REFUSED: read-only subagent cannot invoke mutating tool "${name}".`; 573 return { ok: false, output: msg, preview: msg }; 574 } 575 576 try { 577 switch (name) { 578 case 'read_file': { 579 const target = resolvePath(ctx.cwd, String(args.path || '')); 580 if (!fs.existsSync(target)) { 581 return { ok: false, output: `File not found: ${target}`, preview: `File not found: ${target}` }; 582 } 583 const stat = fs.statSync(target); 584 if (stat.isDirectory()) { 585 return { ok: false, output: `Path is a directory: ${target}`, preview: `Path is a directory` }; 586 } 587 const content = fs.readFileSync(target, 'utf8'); 588 const lines = content.split(/\r?\n/); 589 const start = Math.max(1, Number(args.start_line || 1)); 590 const end = Math.min(lines.length, Number(args.end_line || Math.min(lines.length, start + 199))); 591 const slice = lines.slice(start - 1, end).map((l, idx) => `${start + idx}: ${l}`).join('\n'); 592 const header = `File: ${target} (lines ${start}-${end} of ${lines.length})\n`; 593 const output = header + slice; 594 return { ok: true, output, preview: `Read ${end - start + 1} lines of ${path.basename(target)}` }; 595 } 596 597 case 'write_file': { 598 const target = resolvePath(ctx.cwd, String(args.path || '')); 599 if (ctx.approvalMode === 'omega-only' && !isAllowedInOmegaOnly(target)) { 600 const msg = `REFUSED (omega-only mode): Only .om files and NOTES.md may be written. Blocked: ${target}`; 601 return { ok: false, output: msg, preview: msg }; 602 } 603 const content = String(args.content ?? ''); 604 fs.mkdirSync(path.dirname(target), { recursive: true }); 605 fs.writeFileSync(target, content, 'utf8'); 606 const lineCount = content.split(/\r?\n/).length; 607 let output = `Wrote ${target} (${lineCount} lines, ${Buffer.byteLength(content, 'utf8')} bytes).`; 608 609 if (target.endsWith('.om') && ctx.omcPath) { 610 const comp = compileOmFile(target, { omcPath: ctx.omcPath, harnessRoot: ctx.harnessRoot }); 611 if (comp.outputPath) { 612 try { fs.unlinkSync(comp.outputPath); } catch { /* ignore */ } 613 } 614 output += '\n' + formatOmcCompileFeedback(comp); 615 } 616 return { ok: true, output, preview: makePreview(output, 3) }; 617 } 618 619 case 'edit_file': { 620 const target = resolvePath(ctx.cwd, String(args.path || '')); 621 if (ctx.approvalMode === 'omega-only' && !isAllowedInOmegaOnly(target)) { 622 const msg = `REFUSED (omega-only mode): Only .om files and NOTES.md may be edited. Blocked: ${target}`; 623 return { ok: false, output: msg, preview: msg }; 624 } 625 if (!fs.existsSync(target)) { 626 return { ok: false, output: `File not found: ${target}`, preview: `File not found` }; 627 } 628 const oldText = fs.readFileSync(target, 'utf8'); 629 const needle = String(args.target ?? ''); 630 const repl = String(args.replacement ?? ''); 631 if (!needle || !oldText.includes(needle)) { 632 return { 633 ok: false, 634 output: `Target block not found in ${target}. Read the file first to verify exact text.`, 635 preview: 'Target block not found', 636 }; 637 } 638 const occurrences = oldText.split(needle).length - 1; 639 const newText = oldText.split(needle).join(repl); 640 fs.writeFileSync(target, newText, 'utf8'); 641 let output = `Edited ${target} (${occurrences} replacement${occurrences === 1 ? '' : 's'}).`; 642 643 if (target.endsWith('.om') && ctx.omcPath) { 644 const comp = compileOmFile(target, { omcPath: ctx.omcPath, harnessRoot: ctx.harnessRoot }); 645 if (comp.outputPath) { 646 try { fs.unlinkSync(comp.outputPath); } catch { /* ignore */ } 647 } 648 output += '\n' + formatOmcCompileFeedback(comp); 649 } 650 return { ok: true, output, preview: makePreview(output, 3) }; 651 } 652 653 case 'delete_file': { 654 const target = resolvePath(ctx.cwd, String(args.path || '')); 655 if (!fs.existsSync(target)) { 656 return { ok: false, output: `File not found: ${target}`, preview: 'File not found' }; 657 } 658 fs.unlinkSync(target); 659 const msg = `Deleted ${target}`; 660 return { ok: true, output: msg, preview: msg }; 661 } 662 663 case 'list_dir': { 664 const dir = resolvePath(ctx.cwd, args.path ? String(args.path) : undefined); 665 const entries = fs.readdirSync(dir, { withFileTypes: true }); 666 const rows = entries 667 .sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name)) 668 .map((e) => (e.isDirectory() ? `${e.name}/` : e.name)); 669 const limit = 60; 670 const shown = rows.slice(0, limit); 671 const suffix = rows.length > limit ? `\n... (+${rows.length - limit} more entries; use glob_files to filter)` : ''; 672 const output = (shown.join('\n') + suffix) || '(empty directory)'; 673 return { ok: true, output, preview: `${rows.length} entries in ${path.basename(dir) || dir}` }; 674 } 675 676 case 'glob_files': { 677 const base = resolvePath(ctx.cwd, args.dir ? String(args.dir) : undefined); 678 const pattern = String(args.pattern || '*'); 679 const regex = globToRegex(pattern.includes('/') ? pattern : `**/${pattern}`); 680 const baseRegex = globToRegex(pattern); 681 const files = walkFiles(base).filter((f) => regex.test(f) || baseRegex.test(f) || baseRegex.test(path.basename(f))); 682 const output = files.slice(0, 200).join('\n') || '(no matches)'; 683 return { ok: true, output, preview: `${files.length} file${files.length === 1 ? '' : 's'} matched` }; 684 } 685 686 case 'grep_search': { 687 const base = resolvePath(ctx.cwd, args.dir ? String(args.dir) : undefined); 688 const query = String(args.query || ''); 689 const glob = args.glob ? String(args.glob) : undefined; 690 const rgArgs = ['-n', '--max-count', '50', '--max-filesize', '2M']; 691 if (glob) rgArgs.push('-g', glob); 692 rgArgs.push(query, base); 693 const rg = spawnSync('rg', rgArgs, { encoding: 'utf8', timeout: 15_000, maxBuffer: 8 * 1024 * 1024 }); 694 if (!rg.error) { 695 const out = (rg.stdout || '').trim(); 696 const lines = out ? out.split(/\r?\n/) : []; 697 const capped = lines.slice(0, 40).join('\n') || '(no matches)'; 698 return { ok: true, output: capped, preview: `${lines.length} match${lines.length === 1 ? '' : 'es'}` }; 699 } 700 const files = walkFiles(base, 1000); 701 const re = new RegExp(query, 'i'); 702 const hits: string[] = []; 703 for (const rel of files) { 704 if (hits.length >= 120) break; 705 if (glob && !globToRegex(glob).test(path.basename(rel))) continue; 706 try { 707 const text = fs.readFileSync(path.join(base, rel), 'utf8'); 708 const lines = text.split(/\r?\n/); 709 for (let i = 0; i < lines.length; i++) { 710 if (re.test(lines[i])) { 711 hits.push(`${rel}:${i + 1}:${lines[i]}`); 712 if (hits.length >= 120) break; 713 } 714 } 715 } catch { /* ignore */ } 716 } 717 const output = hits.join('\n') || '(no matches)'; 718 return { ok: true, output, preview: `${hits.length} match${hits.length === 1 ? '' : 'es'}` }; 719 } 720 721 case 'run_shell': { 722 const command = String(args.command || ''); 723 const timeout = Math.min(300_000, Math.max(1000, Number(args.timeout_ms || 30_000))); 724 try { 725 const stdout = execSync(command, { 726 cwd: ctx.cwd, 727 encoding: 'utf8', 728 timeout, 729 maxBuffer: 16 * 1024 * 1024, 730 stdio: ['ignore', 'pipe', 'pipe'], 731 }); 732 const output = stdout.trim() || '(command exited 0 with no output)'; 733 return { ok: true, output, preview: makePreview(output, 4) }; 734 } catch (err: unknown) { 735 const e = err as { status?: number; stdout?: string; stderr?: string; message?: string }; 736 const combined = [ 737 `Exit code: ${e.status ?? 1}`, 738 e.stdout ? `STDOUT:\n${String(e.stdout).trim()}` : '', 739 e.stderr ? `STDERR:\n${String(e.stderr).trim()}` : '', 740 ] 741 .filter(Boolean) 742 .join('\n'); 743 return { ok: false, output: combined || String(e.message || err), preview: makePreview(combined, 4) }; 744 } 745 } 746 747 case 'git_status': { 748 const out = execFileSync('git', ['status', '-sb'], { cwd: ctx.cwd, encoding: 'utf8', timeout: 10_000 }).trim(); 749 return { ok: true, output: out || '(clean)', preview: makePreview(out, 3) }; 750 } 751 752 case 'git_diff': { 753 const gArgs = ['diff']; 754 if (args.staged) gArgs.push('--cached'); 755 if (args.path) gArgs.push('--', String(args.path)); 756 const out = execFileSync('git', gArgs, { cwd: ctx.cwd, encoding: 'utf8', timeout: 10_000, maxBuffer: 8 * 1024 * 1024 }).trim(); 757 const capped = out.length > 16000 ? out.slice(0, 16000) + '\n...[diff truncated]...' : out || '(no diff)'; 758 return { ok: true, output: capped, preview: makePreview(capped, 4) }; 759 } 760 761 case 'git_log': { 762 const n = Math.min(50, Math.max(1, Number(args.count || 10))); 763 const out = execFileSync('git', ['log', `-n`, String(n), '--oneline'], { cwd: ctx.cwd, encoding: 'utf8', timeout: 10_000 }).trim(); 764 return { ok: true, output: out || '(no commits)', preview: makePreview(out, 4) }; 765 } 766 767 case 'git_commit': { 768 const msg = String(args.message || '').trim(); 769 if (!msg) return { ok: false, output: 'Commit message is required.', preview: 'Missing commit message' }; 770 if (Array.isArray(args.files) && args.files.length > 0) { 771 execFileSync('git', ['add', ...args.files.map(String)], { cwd: ctx.cwd, encoding: 'utf8', timeout: 10_000 }); 772 } else { 773 execFileSync('git', ['add', '-u'], { cwd: ctx.cwd, encoding: 'utf8', timeout: 10_000 }); 774 } 775 const out = execFileSync('git', ['commit', '-m', msg], { cwd: ctx.cwd, encoding: 'utf8', timeout: 15_000 }).trim(); 776 return { ok: true, output: out, preview: makePreview(out, 3) }; 777 } 778 779 case 'web_fetch': { 780 const url = String(args.url || '').trim(); 781 if (!/^https?:\/\//i.test(url)) { 782 return { ok: false, output: `Invalid URL: ${url}`, preview: 'Invalid URL' }; 783 } 784 const maxChars = Math.min(24_000, Math.max(200, Number(args.max_chars || 8000))); 785 const res = await fetch(url, { 786 headers: { 'User-Agent': 'Omega-Harness-CLI/0.1' }, 787 signal: AbortSignal.timeout(15_000), 788 }); 789 const ct = res.headers.get('content-type') || ''; 790 const raw = await res.text(); 791 const cleaned = ct.includes('html') ? stripHtmlToText(raw) : raw; 792 const body = cleaned.slice(0, maxChars); 793 const output = `HTTP ${res.status} (${url})\n${body}`; 794 return { ok: res.ok, output, preview: `HTTP ${res.status} · ${body.length} chars` }; 795 } 796 797 case 'web_search': { 798 const query = String(args.query || '').trim(); 799 const maxResults = Math.min(10, Math.max(1, Number(args.max_results || 5))); 800 const url = `https://html.duckduckgo.com/html/?q=${encodeURIComponent(query)}`; 801 const res = await fetch(url, { 802 headers: { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) OmegaHarness/0.1' }, 803 signal: AbortSignal.timeout(15_000), 804 }); 805 if (!res.ok) { 806 return { ok: false, output: `Search HTTP ${res.status}`, preview: `Search HTTP ${res.status}` }; 807 } 808 const html = await res.text(); 809 const items = parseDuckDuckGoHtml(html, maxResults); 810 if (items.length === 0) { 811 return { ok: true, output: '(no search results found)', preview: '0 results' }; 812 } 813 const output = items 814 .map((r, i) => `${i + 1}. ${r.title}\n ${r.url}${r.snippet ? `\n ${r.snippet}` : ''}`) 815 .join('\n'); 816 return { ok: true, output, preview: `${items.length} results for "${query}"` }; 817 } 818 819 case 'todo_write': { 820 if (!ctx.state) return { ok: false, output: 'Session state unavailable', preview: 'No state' }; 821 const items = Array.isArray(args.items) ? (args.items as TodoItem[]) : []; 822 ctx.state.setTodos(items); 823 const out = ctx.state.formatTodos(); 824 return { ok: true, output: out, preview: `${items.length} tasks updated` }; 825 } 826 827 case 'todo_read': { 828 if (!ctx.state) return { ok: false, output: '(no tasks)', preview: '0 tasks' }; 829 const out = ctx.state.formatTodos(); 830 return { ok: true, output: out, preview: `${ctx.state.todos.length} tasks` }; 831 } 832 833 case 'memory_save': { 834 const key = String(args.key || '').trim(); 835 const val = String(args.value || '').trim(); 836 if (!key || !val) return { ok: false, output: 'Both key and value are required.', preview: 'Missing args' }; 837 saveMemory(key, val); 838 return { ok: true, output: `Saved memory "${key}".`, preview: `Saved memory "${key}"` }; 839 } 840 841 case 'memory_read': { 842 const out = formatMemories(args.key ? String(args.key) : undefined); 843 return { ok: true, output: out, preview: makePreview(out, 3) }; 844 } 845 846 case 'spawn_subagent': { 847 if (!ctx.state?.runSubagent) { 848 return { ok: false, output: 'Subagent runner is not initialized.', preview: 'No subagent runner' }; 849 } 850 const role = String(args.role || 'Worker'); 851 const task = String(args.task || ''); 852 const mode: 'read-only' | 'full' = args.mode === 'full' && !ctx.readOnlyOnly ? 'full' : 'read-only'; 853 const id = ctx.state.nextSubagentId(role); 854 const rec = { 855 id, 856 role, 857 task, 858 mode, 859 status: 'running' as const, 860 startedAt: Date.now(), 861 toolCalls: 0, 862 }; 863 ctx.state.registerSubagent(rec); 864 try { 865 const res = await ctx.state.runSubagent({ id, role, task, mode }); 866 ctx.state.registerSubagent({ 867 ...rec, 868 status: 'completed', 869 finishedAt: Date.now(), 870 toolCalls: res.toolCalls, 871 result: res.text, 872 }); 873 const out = `[Subagent ${id} (${role}) completed, ${res.toolCalls} tool calls]\n${res.text}`; 874 return { ok: true, output: out, preview: `${id} done (${res.toolCalls} tools)` }; 875 } catch (err: unknown) { 876 const errMsg = err instanceof Error ? err.message : String(err); 877 ctx.state.registerSubagent({ 878 ...rec, 879 status: 'failed', 880 finishedAt: Date.now(), 881 error: errMsg, 882 }); 883 return { ok: false, output: `[Subagent ${id} failed]: ${errMsg}`, preview: `${id} failed` }; 884 } 885 } 886 887 case 'spawn_parallel_subagents': { 888 if (!ctx.state?.runSubagent) { 889 return { ok: false, output: 'Subagent runner is not initialized.', preview: 'No subagent runner' }; 890 } 891 const specs = Array.isArray(args.tasks) 892 ? (args.tasks as Array<{ role?: string; task?: string; mode?: string }>) 893 : []; 894 if (specs.length === 0) { 895 return { ok: false, output: 'No tasks provided to spawn_parallel_subagents.', preview: '0 tasks' }; 896 } 897 const results = await Promise.all( 898 specs.map((s) => 899 executeTool( 900 'spawn_subagent', 901 { role: s.role || 'Worker', task: s.task || '', mode: s.mode || 'read-only' }, 902 ctx 903 ) 904 ) 905 ); 906 const combined = results.map((r, i) => `### Subagent ${i + 1}\n${r.output}`).join('\n\n'); 907 const okCount = results.filter((r) => r.ok).length; 908 return { 909 ok: okCount > 0, 910 output: combined, 911 preview: `${okCount}/${results.length} parallel subagents completed`, 912 }; 913 } 914 915 case 'list_subagents': { 916 if (!ctx.state) return { ok: true, output: '(no subagents)', preview: '0 subagents' }; 917 const out = ctx.state.formatSubagents(); 918 return { ok: true, output: out, preview: `${ctx.state.subagents.size} subagents` }; 919 } 920 921 case 'message_subagent': { 922 if (!ctx.state?.runSubagent) { 923 return { ok: false, output: 'Subagent runner is not initialized.', preview: 'No subagent runner' }; 924 } 925 const id = String(args.id || ''); 926 const existing = ctx.state.subagents.get(id); 927 if (!existing) { 928 return { ok: false, output: `Subagent "${id}" not found.`, preview: 'Subagent not found' }; 929 } 930 const message = String(args.message || ''); 931 const res = await ctx.state.runSubagent({ 932 id, 933 existingId: id, 934 role: existing.role, 935 task: message, 936 mode: existing.mode, 937 }); 938 ctx.state.registerSubagent({ 939 ...existing, 940 status: 'completed', 941 finishedAt: Date.now(), 942 toolCalls: existing.toolCalls + res.toolCalls, 943 result: res.text, 944 }); 945 return { ok: true, output: `[Subagent ${id} reply]\n${res.text}`, preview: `${id} replied` }; 946 } 947 948 case 'list_skills': { 949 const skills = discoverSkills(ctx.harnessRoot); 950 const output = skills.map((s) => `- ${s.name}: ${s.description}`).join('\n') || '(no skills found)'; 951 return { ok: true, output, preview: `${skills.length} skills available` }; 952 } 953 954 case 'load_skill': { 955 const skillName = String(args.name || ''); 956 const loaded = readSkillContent(ctx.harnessRoot, skillName); 957 if (!loaded) { 958 const avail = discoverSkills(ctx.harnessRoot).map((s) => s.name).join(', '); 959 return { 960 ok: false, 961 output: `Skill "${skillName}" not found. Available: ${avail}`, 962 preview: `Skill "${skillName}" not found`, 963 }; 964 } 965 return { 966 ok: true, 967 output: `# Skill: ${loaded.meta.name} (${loaded.meta.filePath})\n\n${loaded.content}`, 968 preview: `Loaded skill ${loaded.meta.name} (${loaded.content.length} chars)`, 969 }; 970 } 971 972 case 'omc_compile': { 973 const target = resolvePath(ctx.cwd, String(args.path || '')); 974 const outPath = args.output ? resolvePath(ctx.cwd, String(args.output)) : undefined; 975 const res = compileOmFile(target, { 976 omcPath: ctx.omcPath, 977 harnessRoot: ctx.harnessRoot, 978 outputPath: outPath, 979 }); 980 if (!outPath && res.outputPath) { 981 try { fs.unlinkSync(res.outputPath); } catch { /* ignore */ } 982 } 983 const output = formatOmcCompileFeedback(res); 984 return { ok: res.ok, output, preview: makePreview(output, 3) }; 985 } 986 987 case 'omc_run': { 988 const target = resolvePath(ctx.cwd, String(args.path || '')); 989 const res = compileAndRunOmFile(target, { 990 omcPath: ctx.omcPath, 991 harnessRoot: ctx.harnessRoot, 992 stdin: args.stdin !== undefined ? String(args.stdin) : '', 993 timeoutMs: Number(args.timeout_ms || 10_000), 994 }); 995 if (!res.compile.ok) { 996 const msg = formatOmcCompileFeedback(res.compile); 997 return { ok: false, output: msg, preview: makePreview(msg, 3) }; 998 } 999 const parts = [ 1000 `compile: PASS (${res.compile.binarySize} bytes)`, 1001 `run: exit=${res.exitCode ?? 'null'}${res.signal ? ` signal=${res.signal}` : ''}${res.timedOut ? ' TIMED_OUT' : ''}`, 1002 ]; 1003 if (res.stdout) parts.push(`STDOUT:\n${res.stdout}`); 1004 if (res.stderr) parts.push(`STDERR:\n${res.stderr}`); 1005 const output = parts.join('\n'); 1006 return { 1007 ok: res.exitCode === 0 && !res.timedOut, 1008 output, 1009 preview: makePreview(output, 4), 1010 }; 1011 } 1012 1013 case 'omega_pin': { 1014 const pin = readPinInfo(ctx.harnessRoot, ctx.omcPath); 1015 const lines = [ 1016 `harness root: ${ctx.harnessRoot}`, 1017 `PIN omega-mv: ${pin.omegaMvCommit || '(missing)'}`, 1018 `PIN omc-sha256: ${pin.omcSha256 || '(missing)'}`, 1019 `local omc: ${pin.localOmcPath || '(not found)'}`, 1020 `local omc sha256: ${pin.localOmcSha256 || '(n/a)'}`, 1021 `pin match: ${pin.pinMatches === undefined ? 'unknown' : pin.pinMatches ? 'EXACT MATCH' : 'DIFFERENT (local/macOS build)'}`, 1022 ]; 1023 const output = lines.join('\n'); 1024 return { ok: true, output, preview: `PIN ${pin.omegaMvCommit?.slice(0, 8) || '?'} · omc ${pin.localOmcPath ? 'found' : 'missing'}` }; 1025 } 1026 1027 default: 1028 return { ok: false, output: `Unknown tool: ${name}`, preview: `Unknown tool: ${name}` }; 1029 } 1030 } catch (err: unknown) { 1031 const msg = err instanceof Error ? err.message : String(err); 1032 return { ok: false, output: `Tool error (${name}): ${msg}`, preview: msg }; 1033 } 1034 }