@kolisachint/hoocode-agent 0.4.95 → 0.4.97

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/cli/args.d.ts +2 -0
  3. package/dist/cli/args.d.ts.map +1 -1
  4. package/dist/cli/args.js +7 -0
  5. package/dist/cli/args.js.map +1 -1
  6. package/dist/core/agent-session.d.ts.map +1 -1
  7. package/dist/core/agent-session.js +2 -0
  8. package/dist/core/agent-session.js.map +1 -1
  9. package/dist/core/settings-defaults.d.ts +1 -0
  10. package/dist/core/settings-defaults.d.ts.map +1 -1
  11. package/dist/core/settings-defaults.js +1 -0
  12. package/dist/core/settings-defaults.js.map +1 -1
  13. package/dist/core/settings-manager.d.ts +3 -0
  14. package/dist/core/settings-manager.d.ts.map +1 -1
  15. package/dist/core/settings-manager.js +8 -0
  16. package/dist/core/settings-manager.js.map +1 -1
  17. package/dist/core/tools/browser-flow.d.ts +2 -0
  18. package/dist/core/tools/browser-flow.d.ts.map +1 -1
  19. package/dist/core/tools/browser-flow.js +51 -1
  20. package/dist/core/tools/browser-flow.js.map +1 -1
  21. package/dist/core/tools/browsertools-shared.d.ts +9 -0
  22. package/dist/core/tools/browsertools-shared.d.ts.map +1 -1
  23. package/dist/core/tools/browsertools-shared.js +7 -0
  24. package/dist/core/tools/browsertools-shared.js.map +1 -1
  25. package/dist/core/tools/grep.d.ts.map +1 -1
  26. package/dist/core/tools/grep.js +7 -1
  27. package/dist/core/tools/grep.js.map +1 -1
  28. package/dist/main.d.ts.map +1 -1
  29. package/dist/main.js +7 -0
  30. package/dist/main.js.map +1 -1
  31. package/dist/utils/tools-manager.d.ts.map +1 -1
  32. package/dist/utils/tools-manager.js +9 -0
  33. package/dist/utils/tools-manager.js.map +1 -1
  34. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  35. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  36. package/examples/extensions/sandbox/package.json +1 -1
  37. package/examples/extensions/with-deps/package.json +1 -1
  38. package/package.json +4 -4
@@ -83,12 +83,20 @@ export interface BrowsertoolsToolOptions {
83
83
  requestTimeoutMs?: number;
84
84
  /** Extra args appended after `serve` (mainly for tests). */
85
85
  serveArgs?: string[];
86
+ /** Launch a real on-screen Chromium window instead of headless (sets
87
+ * `BROWSERTOOLS_HEADFUL=1` on the serve process). */
88
+ headful?: boolean;
89
+ /** Default the streamed live viewer on for every flow (the per-call `live_view`
90
+ * param still overrides). Set by the --enable-browser-live-preview flag. */
91
+ liveView?: boolean;
86
92
  }
87
93
  /** Resolve effective options from explicit overrides, then env, then defaults. */
88
94
  export declare function resolveBrowsertoolsOptions(options?: BrowsertoolsToolOptions): Required<Pick<BrowsertoolsToolOptions, "idleTimeoutMs" | "maxParentRounds" | "requestTimeoutMs">> & {
89
95
  binaryPath?: string;
90
96
  browserPath?: string;
91
97
  serveArgs: string[];
98
+ headful: boolean;
99
+ liveView: boolean;
92
100
  };
93
101
  /** Resolve the `browsertools` binary path (explicit override, else download/PATH). */
94
102
  export declare function resolveBrowsertoolsBinary(options?: BrowsertoolsToolOptions): Promise<string>;
@@ -116,6 +124,7 @@ export declare class BrowsertoolsServeClient {
116
124
  browserPath?: string;
117
125
  serveArgs: string[];
118
126
  requestTimeoutMs: number;
127
+ headful?: boolean;
119
128
  });
120
129
  private onStdout;
121
130
  private onLine;
@@ -1 +1 @@
1
- {"version":3,"file":"browsertools-shared.d.ts","sourceRoot":"","sources":["../../../src/core/tools/browsertools-shared.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AASH,iFAAiF;AACjF,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC;AAEjC,sFAAsF;AACtF,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC;AAEhC;;;;GAIG;AACH,MAAM,WAAW,aAAa;IAC7B,OAAO,EAAE,gBAAgB,GAAG,eAAe,GAAG,kBAAkB,GAAG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IACtB,MAAM,EAAE,uBAAuB,CAAC;IAChC,iEAAiE;IACjE,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,UAAU,CAAC,OAAO,UAAU,CAAC,CAAC;IACzC,aAAa,EAAE,MAAM,CAAC;CACtB;AAID;;;GAGG;AACH,wBAAgB,WAAW,CAC1B,KAAK,EAAE,WAAW,EAClB,MAAM,EAAE,uBAAuB,EAC/B,MAAM,EAAE,MAAM,EACd,aAAa,EAAE,MAAM,GACnB,IAAI,CAeN;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,WAAW,GAAG,aAAa,GAAG,SAAS,CAMzE;AAED,mEAAmE;AACnE,wBAAgB,kBAAkB,IAAI,IAAI,CAMzC;AAED,mEAAmE;AACnE,wBAAgB,kBAAkB,IAAI,MAAM,CAE3C","sourcesContent":["/**\n * Shared plumbing for the `browser_flow` and `browser_resume` tools.\n *\n * Unlike `webtools` (one-shot fetch/search subprocesses), `browsertools` drives\n * a *stateful* parent-in-the-loop protocol: a single long-lived `browsertools\n * serve` process holds the live Chromium and the paused-flow state in memory,\n * and the parent (hoocode) talks to it over newline-delimited JSON-RPC on\n * stdin/stdout. A flow can suspend mid-replay with `Outcome::NeedsParent`,\n * yielding a typed `ParentRequest` + `ResumeToken`; the parent reasons about it\n * (often by looking at a screenshot) and calls `flow_resume(token, response)` to\n * continue. See https://github.com/kolisachint/browsertools (contract.rs).\n *\n * Because that single serve process must survive *between* the `browser_flow`\n * call that starts the flow and the `browser_resume` call that answers a\n * `NeedsParent`, this module owns a process-wide {@link sessionRegistry} keyed by\n * `ResumeToken`. Each paused session keeps its serve client alive and is reaped\n * after an idle timeout so an abandoned flow never leaks a Chromium forever.\n *\n * This module owns:\n * - the persistent JSON-RPC serve client (id-correlated request/response),\n * - the locked contract types (mirrors browsertools `src/contract.rs`),\n * - the paused-session registry + lifecycle (idle reap, round cap, teardown),\n * - binary + browser-path resolution.\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { ensureTool } from \"../../utils/tools-manager.js\";\n\n// ============================================================================\n// Contract types (locked against browsertools `src/contract.rs`)\n// ============================================================================\n\n/** Opaque token identifying a paused flow, returned with every `NeedsParent`. */\nexport type ResumeToken = string;\n\n/** Reference to bytes (e.g. a screenshot) the parent can fetch via `get_resource`. */\nexport type ResourceId = string;\n\n/**\n * A typed request the engine yields when replay hits ambiguity only an LLM can\n * resolve. The `request` discriminant matches the serde tag in contract.rs.\n * Fields beyond the discriminant are passed through verbatim to the model.\n */\nexport interface ParentRequest {\n\trequest: \"classify_state\" | \"verify_visual\" | \"extract_semantic\" | \"decide_next_action\" | \"reidentify_element\";\n\t/** Resource id of the screenshot captured at the suspension point, if any. */\n\tscreenshot_ref?: ResourceId;\n\t[key: string]: unknown;\n}\n\n/** Result of a `flow_start` / `flow_resume` RPC (the `result` field's `outcome`). */\nexport type FlowOutcome =\n\t| { outcome: \"complete\"; result?: unknown }\n\t| { outcome: \"needs_parent\"; request: ParentRequest; token: ResumeToken }\n\t| { outcome: \"failed\"; step_id?: string; kind?: string; detail?: string };\n\n/** Result of a `get_resource` RPC. */\nexport interface GetResourceResult {\n\tref: ResourceId;\n\tmime: string;\n\tlen: number;\n\tpng_base64: string;\n}\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\n/** Default per-request RPC timeout. Flow steps drive a real browser, so this is\n * generous relative to webtools' 15s. */\nexport const BROWSERTOOLS_REQUEST_TIMEOUT_MS = 120_000;\n\n/** Default idle window a paused flow may sit in the registry before it is reaped\n * (killing its serve process + Chromium). Reset on every resume round. The\n * parent may reason / look at a screenshot / make other tool calls between\n * rounds, so this is minutes, not seconds. */\nexport const BROWSERTOOLS_DEFAULT_IDLE_MS = 5 * 60 * 1000;\n\n/** Default hard cap on `NeedsParent` rounds for a single flow, bounding a runaway\n * suspend/resume loop. */\nexport const BROWSERTOOLS_DEFAULT_MAX_ROUNDS = 12;\n\n/** Options threaded into the browser tools by their factories (tests/overrides). */\nexport interface BrowsertoolsToolOptions {\n\t/** Explicit path to the `browsertools` binary; otherwise resolved via {@link ensureTool}. */\n\tbinaryPath?: string;\n\t/** Chromium/Chrome executable path forwarded to the serve process. */\n\tbrowserPath?: string;\n\t/** Idle reap window for paused sessions (ms). */\n\tidleTimeoutMs?: number;\n\t/** Hard cap on NeedsParent rounds per flow. */\n\tmaxParentRounds?: number;\n\t/** Per-request RPC timeout (ms). */\n\trequestTimeoutMs?: number;\n\t/** Extra args appended after `serve` (mainly for tests). */\n\tserveArgs?: string[];\n}\n\nfunction envNumber(name: string): number | undefined {\n\tconst raw = process.env[name];\n\tif (!raw) return undefined;\n\tconst n = Number(raw);\n\treturn Number.isFinite(n) && n > 0 ? n : undefined;\n}\n\n/** Resolve effective options from explicit overrides, then env, then defaults. */\nexport function resolveBrowsertoolsOptions(options?: BrowsertoolsToolOptions): Required<\n\tPick<BrowsertoolsToolOptions, \"idleTimeoutMs\" | \"maxParentRounds\" | \"requestTimeoutMs\">\n> & {\n\tbinaryPath?: string;\n\tbrowserPath?: string;\n\tserveArgs: string[];\n} {\n\treturn {\n\t\tbinaryPath: options?.binaryPath,\n\t\tbrowserPath: options?.browserPath ?? (process.env.HOOCODE_BROWSERTOOLS_BROWSER_PATH?.trim() || undefined),\n\t\tidleTimeoutMs:\n\t\t\toptions?.idleTimeoutMs ?? envNumber(\"HOOCODE_BROWSERTOOLS_IDLE_MS\") ?? BROWSERTOOLS_DEFAULT_IDLE_MS,\n\t\tmaxParentRounds:\n\t\t\toptions?.maxParentRounds ?? envNumber(\"HOOCODE_BROWSERTOOLS_MAX_ROUNDS\") ?? BROWSERTOOLS_DEFAULT_MAX_ROUNDS,\n\t\trequestTimeoutMs:\n\t\t\toptions?.requestTimeoutMs ??\n\t\t\tenvNumber(\"HOOCODE_BROWSERTOOLS_REQUEST_TIMEOUT_MS\") ??\n\t\t\tBROWSERTOOLS_REQUEST_TIMEOUT_MS,\n\t\tserveArgs: options?.serveArgs ?? [],\n\t};\n}\n\nconst BINARY_MISSING_MESSAGE =\n\t\"browsertools binary unavailable and could not be downloaded — the browser tools require the `browsertools` CLI on PATH or a published release for this platform\";\n\n/** Resolve the `browsertools` binary path (explicit override, else download/PATH). */\nexport async function resolveBrowsertoolsBinary(options?: BrowsertoolsToolOptions): Promise<string> {\n\tif (options?.binaryPath) return options.binaryPath;\n\tconst binaryPath = await ensureTool(\"browsertools\", true);\n\tif (!binaryPath) throw new Error(BINARY_MISSING_MESSAGE);\n\treturn binaryPath;\n}\n\n// ============================================================================\n// Persistent JSON-RPC serve client\n// ============================================================================\n\ninterface PendingRequest {\n\tresolve: (value: unknown) => void;\n\treject: (error: Error) => void;\n\ttimer: ReturnType<typeof setTimeout>;\n}\n\n/**\n * A live `browsertools serve` process spoken to over newline-delimited JSON-RPC.\n *\n * Wire format (browsertools `src/serve.rs`):\n * request: `{ \"id\": <n>, \"method\": <string>, \"params\": <object> }\\n`\n * response: `{ \"id\": <n>, \"result\": <value> }` or `{ \"id\": <n>, \"error\": <RpcError> }`\\n\n *\n * Responses are correlated by `id`, so concurrent requests are safe, though the\n * tools drive it sequentially.\n */\nexport class BrowsertoolsServeClient {\n\tprivate readonly proc: ChildProcess;\n\tprivate readonly pending = new Map<number, PendingRequest>();\n\tprivate readonly requestTimeoutMs: number;\n\tprivate buffer = \"\";\n\tprivate nextId = 1;\n\tprivate closed = false;\n\tprivate exitError: Error | undefined;\n\tprivate stderrTail = \"\";\n\n\tconstructor(\n\t\tbinaryPath: string,\n\t\topts: { cwd?: string; browserPath?: string; serveArgs: string[]; requestTimeoutMs: number },\n\t) {\n\t\tthis.requestTimeoutMs = opts.requestTimeoutMs;\n\t\t// The exact CLI flag for the browser path is not part of the locked RPC\n\t\t// contract; v0.1.3 added a \"configurable browser path\". We forward it via\n\t\t// env vars the binary is likely to read. Passing extra env is harmless if\n\t\t// the binary ignores them, and centralizing it here makes it a one-line\n\t\t// change once the exact mechanism is confirmed.\n\t\tconst env = { ...process.env };\n\t\tif (opts.browserPath) {\n\t\t\tenv.BROWSERTOOLS_BROWSER_PATH = opts.browserPath;\n\t\t\tenv.CHROME_PATH = opts.browserPath;\n\t\t}\n\t\t// Run the serve process in the project cwd so relative flow paths and the\n\t\t// evidence store resolve the same way the user expects.\n\t\tthis.proc = spawn(binaryPath, [\"serve\", ...opts.serveArgs], {\n\t\t\tcwd: opts.cwd,\n\t\t\tshell: false,\n\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t\tenv,\n\t\t});\n\t\tthis.proc.stdout?.setEncoding(\"utf8\");\n\t\tthis.proc.stdout?.on(\"data\", (chunk: string) => this.onStdout(chunk));\n\t\tthis.proc.stderr?.setEncoding(\"utf8\");\n\t\tthis.proc.stderr?.on(\"data\", (chunk: string) => {\n\t\t\t// Keep only a bounded tail so a chatty serve can't grow unbounded; it is\n\t\t\t// surfaced in the error when the process dies unexpectedly.\n\t\t\tthis.stderrTail = (this.stderrTail + chunk).slice(-4000);\n\t\t});\n\t\tthis.proc.on(\"error\", (err) => this.fail(err instanceof Error ? err : new Error(String(err))));\n\t\tthis.proc.on(\"exit\", (code, sig) => {\n\t\t\tif (this.closed) return;\n\t\t\tconst detail = this.stderrTail.trim();\n\t\t\tthis.fail(\n\t\t\t\tnew Error(\n\t\t\t\t\t`browsertools serve exited unexpectedly (code=${code ?? \"null\"}, signal=${sig ?? \"null\"})` +\n\t\t\t\t\t\t(detail ? `: ${detail}` : \"\"),\n\t\t\t\t),\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate onStdout(chunk: string): void {\n\t\tthis.buffer += chunk;\n\t\tlet newlineIndex = this.buffer.indexOf(\"\\n\");\n\t\twhile (newlineIndex !== -1) {\n\t\t\tconst line = this.buffer.slice(0, newlineIndex).trim();\n\t\t\tthis.buffer = this.buffer.slice(newlineIndex + 1);\n\t\t\tif (line) this.onLine(line);\n\t\t\tnewlineIndex = this.buffer.indexOf(\"\\n\");\n\t\t}\n\t}\n\n\tprivate onLine(line: string): void {\n\t\tlet message: { id?: unknown; result?: unknown; error?: unknown };\n\t\ttry {\n\t\t\tmessage = JSON.parse(line);\n\t\t} catch {\n\t\t\t// Non-JSON noise on stdout (shouldn't happen; logs go to stderr). Skip it\n\t\t\t// rather than corrupt id correlation.\n\t\t\treturn;\n\t\t}\n\t\tconst id = typeof message.id === \"number\" ? message.id : undefined;\n\t\tif (id === undefined) return;\n\t\tconst entry = this.pending.get(id);\n\t\tif (!entry) return;\n\t\tthis.pending.delete(id);\n\t\tclearTimeout(entry.timer);\n\t\tif (message.error !== undefined && message.error !== null) {\n\t\t\tentry.reject(new Error(`browsertools ${describeRpcError(message.error)}`));\n\t\t} else {\n\t\t\tentry.resolve(message.result);\n\t\t}\n\t}\n\n\t/** Reject all in-flight requests and mark the client dead. Idempotent. */\n\tprivate fail(error: Error): void {\n\t\tif (this.closed) return;\n\t\tthis.exitError = error;\n\t\tfor (const [, entry] of this.pending) {\n\t\t\tclearTimeout(entry.timer);\n\t\t\tentry.reject(error);\n\t\t}\n\t\tthis.pending.clear();\n\t}\n\n\t/** Send a JSON-RPC request and resolve with its `result` (or reject on `error`). */\n\trequest<T = unknown>(method: string, params: Record<string, unknown>): Promise<T> {\n\t\tif (this.closed) {\n\t\t\treturn Promise.reject(this.exitError ?? new Error(\"browsertools serve client is closed\"));\n\t\t}\n\t\tconst id = this.nextId++;\n\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tif (this.pending.delete(id)) {\n\t\t\t\t\treject(new Error(`browsertools ${method} timed out after ${this.requestTimeoutMs}ms`));\n\t\t\t\t}\n\t\t\t}, this.requestTimeoutMs);\n\t\t\tthis.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });\n\t\t\tconst payload = `${JSON.stringify({ id, method, params })}\\n`;\n\t\t\tthis.proc.stdin?.write(payload, (err) => {\n\t\t\t\tif (err && this.pending.delete(id)) {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\treject(err);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\t/** Kill the serve process and reject any outstanding requests. Idempotent. */\n\tdispose(): void {\n\t\tif (this.closed) return;\n\t\tthis.fail(new Error(\"browsertools serve client disposed\"));\n\t\tthis.closed = true;\n\t\t// Best-effort graceful shutdown, then ensure the process is gone.\n\t\ttry {\n\t\t\tthis.proc.stdin?.write(`${JSON.stringify({ id: this.nextId++, method: \"shutdown\", params: {} })}\\n`);\n\t\t} catch {\n\t\t\t// stdin may already be closed; fall through to kill.\n\t\t}\n\t\tthis.proc.stdin?.end();\n\t\tthis.proc.kill(\"SIGTERM\");\n\t\tconst proc = this.proc;\n\t\tsetTimeout(() => {\n\t\t\tif (proc.exitCode === null && proc.signalCode === null) proc.kill(\"SIGKILL\");\n\t\t}, 3000).unref?.();\n\t}\n}\n\nfunction describeRpcError(error: unknown): string {\n\tif (error && typeof error === \"object\") {\n\t\tconst message = (error as { message?: unknown }).message;\n\t\tif (typeof message === \"string\" && message) return message;\n\t}\n\tif (typeof error === \"string\" && error) return error;\n\treturn `RPC error: ${JSON.stringify(error)}`;\n}\n\n// ============================================================================\n// Paused-session registry (process-wide, keyed by ResumeToken)\n// ============================================================================\n\ninterface PausedSession {\n\tclient: BrowsertoolsServeClient;\n\t/** Number of NeedsParent rounds yielded so far for this flow. */\n\trounds: number;\n\tidleTimer: ReturnType<typeof setTimeout>;\n\tidleTimeoutMs: number;\n}\n\nconst sessionRegistry = new Map<ResumeToken, PausedSession>();\n\n/**\n * Park a paused flow's live serve client under its resume token and arm the idle\n * reaper. Any previous entry for the token is disposed first.\n */\nexport function parkSession(\n\ttoken: ResumeToken,\n\tclient: BrowsertoolsServeClient,\n\trounds: number,\n\tidleTimeoutMs: number,\n): void {\n\tconst existing = sessionRegistry.get(token);\n\tif (existing && existing.client !== client) {\n\t\tclearTimeout(existing.idleTimer);\n\t\texisting.client.dispose();\n\t}\n\tconst idleTimer = setTimeout(() => {\n\t\tconst session = sessionRegistry.get(token);\n\t\tif (session) {\n\t\t\tsessionRegistry.delete(token);\n\t\t\tsession.client.dispose();\n\t\t}\n\t}, idleTimeoutMs);\n\tidleTimer.unref?.();\n\tsessionRegistry.set(token, { client, rounds, idleTimer, idleTimeoutMs });\n}\n\n/**\n * Remove a paused session from the registry and return it, stopping its idle\n * timer. The caller now owns the client (to resume or dispose). Returns\n * undefined if the token is unknown (expired/reaped/already completed).\n */\nexport function takeSession(token: ResumeToken): PausedSession | undefined {\n\tconst session = sessionRegistry.get(token);\n\tif (!session) return undefined;\n\tclearTimeout(session.idleTimer);\n\tsessionRegistry.delete(token);\n\treturn session;\n}\n\n/** Dispose every parked session. Used on shutdown and in tests. */\nexport function disposeAllSessions(): void {\n\tfor (const [, session] of sessionRegistry) {\n\t\tclearTimeout(session.idleTimer);\n\t\tsession.client.dispose();\n\t}\n\tsessionRegistry.clear();\n}\n\n/** Number of currently parked sessions (for tests/diagnostics). */\nexport function pausedSessionCount(): number {\n\treturn sessionRegistry.size;\n}\n"]}
1
+ {"version":3,"file":"browsertools-shared.d.ts","sourceRoot":"","sources":["../../../src/core/tools/browsertools-shared.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AASH,iFAAiF;AACjF,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC;AAEjC,sFAAsF;AACtF,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC;AAEhC;;;;GAIG;AACH,MAAM,WAAW,aAAa;IAC7B,OAAO,EAAE,gBAAgB,GAAG,eAAe,GAAG,kBAAkB,GAAG,oBAAoB,GAAG,oBAAoB,CAAC;IAC/G,8EAA8E;IAC9E,cAAc,CAAC,EAAE,UAAU,CAAC;IAC5B,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACvB;AAED,qFAAqF;AACrF,MAAM,MAAM,WAAW,GACpB;IAAE,OAAO,EAAE,UAAU,CAAC;IAAC,MAAM,CAAC,EAAE,OAAO,CAAA;CAAE,GACzC;IAAE,OAAO,EAAE,cAAc,CAAC;I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UAAU,CAAC,OAAO,UAAU,CAAC,CAAC;IACzC,aAAa,EAAE,MAAM,CAAC;CACtB;AAID;;;GAGG;AACH,wBAAgB,WAAW,CAC1B,KAAK,EAAE,WAAW,EAClB,MAAM,EAAE,uBAAuB,EAC/B,MAAM,EAAE,MAAM,EACd,aAAa,EAAE,MAAM,GACnB,IAAI,CAeN;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,WAAW,GAAG,aAAa,GAAG,SAAS,CAMzE;AAED,mEAAmE;AACnE,wBAAgB,kBAAkB,IAAI,IAAI,CAMzC;AAED,mEAAmE;AACnE,wBAAgB,kBAAkB,IAAI,MAAM,CAE3C","sourcesContent":["/**\n * Shared plumbing for the `browser_flow` and `browser_resume` tools.\n *\n * Unlike `webtools` (one-shot fetch/search subprocesses), `browsertools` drives\n * a *stateful* parent-in-the-loop protocol: a single long-lived `browsertools\n * serve` process holds the live Chromium and the paused-flow state in memory,\n * and the parent (hoocode) talks to it over newline-delimited JSON-RPC on\n * stdin/stdout. A flow can suspend mid-replay with `Outcome::NeedsParent`,\n * yielding a typed `ParentRequest` + `ResumeToken`; the parent reasons about it\n * (often by looking at a screenshot) and calls `flow_resume(token, response)` to\n * continue. See https://github.com/kolisachint/browsertools (contract.rs).\n *\n * Because that single serve process must survive *between* the `browser_flow`\n * call that starts the flow and the `browser_resume` call that answers a\n * `NeedsParent`, this module owns a process-wide {@link sessionRegistry} keyed by\n * `ResumeToken`. Each paused session keeps its serve client alive and is reaped\n * after an idle timeout so an abandoned flow never leaks a Chromium forever.\n *\n * This module owns:\n * - the persistent JSON-RPC serve client (id-correlated request/response),\n * - the locked contract types (mirrors browsertools `src/contract.rs`),\n * - the paused-session registry + lifecycle (idle reap, round cap, teardown),\n * - binary + browser-path resolution.\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { ensureTool } from \"../../utils/tools-manager.js\";\n\n// ============================================================================\n// Contract types (locked against browsertools `src/contract.rs`)\n// ============================================================================\n\n/** Opaque token identifying a paused flow, returned with every `NeedsParent`. */\nexport type ResumeToken = string;\n\n/** Reference to bytes (e.g. a screenshot) the parent can fetch via `get_resource`. */\nexport type ResourceId = string;\n\n/**\n * A typed request the engine yields when replay hits ambiguity only an LLM can\n * resolve. The `request` discriminant matches the serde tag in contract.rs.\n * Fields beyond the discriminant are passed through verbatim to the model.\n */\nexport interface ParentRequest {\n\trequest: \"classify_state\" | \"verify_visual\" | \"extract_semantic\" | \"decide_next_action\" | \"reidentify_element\";\n\t/** Resource id of the screenshot captured at the suspension point, if any. */\n\tscreenshot_ref?: ResourceId;\n\t[key: string]: unknown;\n}\n\n/** Result of a `flow_start` / `flow_resume` RPC (the `result` field's `outcome`). */\nexport type FlowOutcome =\n\t| { outcome: \"complete\"; result?: unknown }\n\t| { outcome: \"needs_parent\"; request: ParentRequest; token: ResumeToken }\n\t| { outcome: \"failed\"; step_id?: string; kind?: string; detail?: string };\n\n/** Result of a `get_resource` RPC. */\nexport interface GetResourceResult {\n\tref: ResourceId;\n\tmime: string;\n\tlen: number;\n\tpng_base64: string;\n}\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\n/** Default per-request RPC timeout. Flow steps drive a real browser, so this is\n * generous relative to webtools' 15s. */\nexport const BROWSERTOOLS_REQUEST_TIMEOUT_MS = 120_000;\n\n/** Default idle window a paused flow may sit in the registry before it is reaped\n * (killing its serve process + Chromium). Reset on every resume round. The\n * parent may reason / look at a screenshot / make other tool calls between\n * rounds, so this is minutes, not seconds. */\nexport const BROWSERTOOLS_DEFAULT_IDLE_MS = 5 * 60 * 1000;\n\n/** Default hard cap on `NeedsParent` rounds for a single flow, bounding a runaway\n * suspend/resume loop. */\nexport const BROWSERTOOLS_DEFAULT_MAX_ROUNDS = 12;\n\n/** Options threaded into the browser tools by their factories (tests/overrides). */\nexport interface BrowsertoolsToolOptions {\n\t/** Explicit path to the `browsertools` binary; otherwise resolved via {@link ensureTool}. */\n\tbinaryPath?: string;\n\t/** Chromium/Chrome executable path forwarded to the serve process. */\n\tbrowserPath?: string;\n\t/** Idle reap window for paused sessions (ms). */\n\tidleTimeoutMs?: number;\n\t/** Hard cap on NeedsParent rounds per flow. */\n\tmaxParentRounds?: number;\n\t/** Per-request RPC timeout (ms). */\n\trequestTimeoutMs?: number;\n\t/** Extra args appended after `serve` (mainly for tests). */\n\tserveArgs?: string[];\n\t/** Launch a real on-screen Chromium window instead of headless (sets\n\t * `BROWSERTOOLS_HEADFUL=1` on the serve process). */\n\theadful?: boolean;\n\t/** Default the streamed live viewer on for every flow (the per-call `live_view`\n\t * param still overrides). Set by the --enable-browser-live-preview flag. */\n\tliveView?: boolean;\n}\n\nfunction envNumber(name: string): number | undefined {\n\tconst raw = process.env[name];\n\tif (!raw) return undefined;\n\tconst n = Number(raw);\n\treturn Number.isFinite(n) && n > 0 ? n : undefined;\n}\n\n/** Resolve effective options from explicit overrides, then env, then defaults. */\nexport function resolveBrowsertoolsOptions(options?: BrowsertoolsToolOptions): Required<\n\tPick<BrowsertoolsToolOptions, \"idleTimeoutMs\" | \"maxParentRounds\" | \"requestTimeoutMs\">\n> & {\n\tbinaryPath?: string;\n\tbrowserPath?: string;\n\tserveArgs: string[];\n\theadful: boolean;\n\tliveView: boolean;\n} {\n\treturn {\n\t\tbinaryPath: options?.binaryPath,\n\t\tbrowserPath: options?.browserPath ?? (process.env.HOOCODE_BROWSERTOOLS_BROWSER_PATH?.trim() || undefined),\n\t\theadful: options?.headful ?? false,\n\t\tliveView: options?.liveView ?? false,\n\t\tidleTimeoutMs:\n\t\t\toptions?.idleTimeoutMs ?? envNumber(\"HOOCODE_BROWSERTOOLS_IDLE_MS\") ?? BROWSERTOOLS_DEFAULT_IDLE_MS,\n\t\tmaxParentRounds:\n\t\t\toptions?.maxParentRounds ?? envNumber(\"HOOCODE_BROWSERTOOLS_MAX_ROUNDS\") ?? BROWSERTOOLS_DEFAULT_MAX_ROUNDS,\n\t\trequestTimeoutMs:\n\t\t\toptions?.requestTimeoutMs ??\n\t\t\tenvNumber(\"HOOCODE_BROWSERTOOLS_REQUEST_TIMEOUT_MS\") ??\n\t\t\tBROWSERTOOLS_REQUEST_TIMEOUT_MS,\n\t\tserveArgs: options?.serveArgs ?? [],\n\t};\n}\n\nconst BINARY_MISSING_MESSAGE =\n\t\"browsertools binary unavailable and could not be downloaded — the browser tools require the `browsertools` CLI on PATH or a published release for this platform\";\n\n/** Resolve the `browsertools` binary path (explicit override, else download/PATH). */\nexport async function resolveBrowsertoolsBinary(options?: BrowsertoolsToolOptions): Promise<string> {\n\tif (options?.binaryPath) return options.binaryPath;\n\tconst binaryPath = await ensureTool(\"browsertools\", true);\n\tif (!binaryPath) throw new Error(BINARY_MISSING_MESSAGE);\n\treturn binaryPath;\n}\n\n// ============================================================================\n// Persistent JSON-RPC serve client\n// ============================================================================\n\ninterface PendingRequest {\n\tresolve: (value: unknown) => void;\n\treject: (error: Error) => void;\n\ttimer: ReturnType<typeof setTimeout>;\n}\n\n/**\n * A live `browsertools serve` process spoken to over newline-delimited JSON-RPC.\n *\n * Wire format (browsertools `src/serve.rs`):\n * request: `{ \"id\": <n>, \"method\": <string>, \"params\": <object> }\\n`\n * response: `{ \"id\": <n>, \"result\": <value> }` or `{ \"id\": <n>, \"error\": <RpcError> }`\\n\n *\n * Responses are correlated by `id`, so concurrent requests are safe, though the\n * tools drive it sequentially.\n */\nexport class BrowsertoolsServeClient {\n\tprivate readonly proc: ChildProcess;\n\tprivate readonly pending = new Map<number, PendingRequest>();\n\tprivate readonly requestTimeoutMs: number;\n\tprivate buffer = \"\";\n\tprivate nextId = 1;\n\tprivate closed = false;\n\tprivate exitError: Error | undefined;\n\tprivate stderrTail = \"\";\n\n\tconstructor(\n\t\tbinaryPath: string,\n\t\topts: {\n\t\t\tcwd?: string;\n\t\t\tbrowserPath?: string;\n\t\t\tserveArgs: string[];\n\t\t\trequestTimeoutMs: number;\n\t\t\theadful?: boolean;\n\t\t},\n\t) {\n\t\tthis.requestTimeoutMs = opts.requestTimeoutMs;\n\t\t// The exact CLI flag for the browser path is not part of the locked RPC\n\t\t// contract; v0.1.3 added a \"configurable browser path\". We forward it via\n\t\t// env vars the binary is likely to read. Passing extra env is harmless if\n\t\t// the binary ignores them, and centralizing it here makes it a one-line\n\t\t// change once the exact mechanism is confirmed.\n\t\tconst env = { ...process.env };\n\t\tif (opts.browserPath) {\n\t\t\tenv.BROWSERTOOLS_BROWSER_PATH = opts.browserPath;\n\t\t\tenv.CHROME_PATH = opts.browserPath;\n\t\t}\n\t\t// Opt into a real on-screen Chromium window. The serve process reads this\n\t\t// in `Driver::launch`; harmless if an older binary ignores it.\n\t\tif (opts.headful) {\n\t\t\tenv.BROWSERTOOLS_HEADFUL = \"1\";\n\t\t}\n\t\t// Run the serve process in the project cwd so relative flow paths and the\n\t\t// evidence store resolve the same way the user expects.\n\t\tthis.proc = spawn(binaryPath, [\"serve\", ...opts.serveArgs], {\n\t\t\tcwd: opts.cwd,\n\t\t\tshell: false,\n\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t\tenv,\n\t\t});\n\t\tthis.proc.stdout?.setEncoding(\"utf8\");\n\t\tthis.proc.stdout?.on(\"data\", (chunk: string) => this.onStdout(chunk));\n\t\tthis.proc.stderr?.setEncoding(\"utf8\");\n\t\tthis.proc.stderr?.on(\"data\", (chunk: string) => {\n\t\t\t// Keep only a bounded tail so a chatty serve can't grow unbounded; it is\n\t\t\t// surfaced in the error when the process dies unexpectedly.\n\t\t\tthis.stderrTail = (this.stderrTail + chunk).slice(-4000);\n\t\t});\n\t\tthis.proc.on(\"error\", (err) => this.fail(err instanceof Error ? err : new Error(String(err))));\n\t\tthis.proc.on(\"exit\", (code, sig) => {\n\t\t\tif (this.closed) return;\n\t\t\tconst detail = this.stderrTail.trim();\n\t\t\tthis.fail(\n\t\t\t\tnew Error(\n\t\t\t\t\t`browsertools serve exited unexpectedly (code=${code ?? \"null\"}, signal=${sig ?? \"null\"})` +\n\t\t\t\t\t\t(detail ? `: ${detail}` : \"\"),\n\t\t\t\t),\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate onStdout(chunk: string): void {\n\t\tthis.buffer += chunk;\n\t\tlet newlineIndex = this.buffer.indexOf(\"\\n\");\n\t\twhile (newlineIndex !== -1) {\n\t\t\tconst line = this.buffer.slice(0, newlineIndex).trim();\n\t\t\tthis.buffer = this.buffer.slice(newlineIndex + 1);\n\t\t\tif (line) this.onLine(line);\n\t\t\tnewlineIndex = this.buffer.indexOf(\"\\n\");\n\t\t}\n\t}\n\n\tprivate onLine(line: string): void {\n\t\tlet message: { id?: unknown; result?: unknown; error?: unknown };\n\t\ttry {\n\t\t\tmessage = JSON.parse(line);\n\t\t} catch {\n\t\t\t// Non-JSON noise on stdout (shouldn't happen; logs go to stderr). Skip it\n\t\t\t// rather than corrupt id correlation.\n\t\t\treturn;\n\t\t}\n\t\tconst id = typeof message.id === \"number\" ? message.id : undefined;\n\t\tif (id === undefined) return;\n\t\tconst entry = this.pending.get(id);\n\t\tif (!entry) return;\n\t\tthis.pending.delete(id);\n\t\tclearTimeout(entry.timer);\n\t\tif (message.error !== undefined && message.error !== null) {\n\t\t\tentry.reject(new Error(`browsertools ${describeRpcError(message.error)}`));\n\t\t} else {\n\t\t\tentry.resolve(message.result);\n\t\t}\n\t}\n\n\t/** Reject all in-flight requests and mark the client dead. Idempotent. */\n\tprivate fail(error: Error): void {\n\t\tif (this.closed) return;\n\t\tthis.exitError = error;\n\t\tfor (const [, entry] of this.pending) {\n\t\t\tclearTimeout(entry.timer);\n\t\t\tentry.reject(error);\n\t\t}\n\t\tthis.pending.clear();\n\t}\n\n\t/** Send a JSON-RPC request and resolve with its `result` (or reject on `error`). */\n\trequest<T = unknown>(method: string, params: Record<string, unknown>): Promise<T> {\n\t\tif (this.closed) {\n\t\t\treturn Promise.reject(this.exitError ?? new Error(\"browsertools serve client is closed\"));\n\t\t}\n\t\tconst id = this.nextId++;\n\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tif (this.pending.delete(id)) {\n\t\t\t\t\treject(new Error(`browsertools ${method} timed out after ${this.requestTimeoutMs}ms`));\n\t\t\t\t}\n\t\t\t}, this.requestTimeoutMs);\n\t\t\tthis.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });\n\t\t\tconst payload = `${JSON.stringify({ id, method, params })}\\n`;\n\t\t\tthis.proc.stdin?.write(payload, (err) => {\n\t\t\t\tif (err && this.pending.delete(id)) {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\treject(err);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\t/** Kill the serve process and reject any outstanding requests. Idempotent. */\n\tdispose(): void {\n\t\tif (this.closed) return;\n\t\tthis.fail(new Error(\"browsertools serve client disposed\"));\n\t\tthis.closed = true;\n\t\t// Best-effort graceful shutdown, then ensure the process is gone.\n\t\ttry {\n\t\t\tthis.proc.stdin?.write(`${JSON.stringify({ id: this.nextId++, method: \"shutdown\", params: {} })}\\n`);\n\t\t} catch {\n\t\t\t// stdin may already be closed; fall through to kill.\n\t\t}\n\t\tthis.proc.stdin?.end();\n\t\tthis.proc.kill(\"SIGTERM\");\n\t\tconst proc = this.proc;\n\t\tsetTimeout(() => {\n\t\t\tif (proc.exitCode === null && proc.signalCode === null) proc.kill(\"SIGKILL\");\n\t\t}, 3000).unref?.();\n\t}\n}\n\nfunction describeRpcError(error: unknown): string {\n\tif (error && typeof error === \"object\") {\n\t\tconst message = (error as { message?: unknown }).message;\n\t\tif (typeof message === \"string\" && message) return message;\n\t}\n\tif (typeof error === \"string\" && error) return error;\n\treturn `RPC error: ${JSON.stringify(error)}`;\n}\n\n// ============================================================================\n// Paused-session registry (process-wide, keyed by ResumeToken)\n// ============================================================================\n\ninterface PausedSession {\n\tclient: BrowsertoolsServeClient;\n\t/** Number of NeedsParent rounds yielded so far for this flow. */\n\trounds: number;\n\tidleTimer: ReturnType<typeof setTimeout>;\n\tidleTimeoutMs: number;\n}\n\nconst sessionRegistry = new Map<ResumeToken, PausedSession>();\n\n/**\n * Park a paused flow's live serve client under its resume token and arm the idle\n * reaper. Any previous entry for the token is disposed first.\n */\nexport function parkSession(\n\ttoken: ResumeToken,\n\tclient: BrowsertoolsServeClient,\n\trounds: number,\n\tidleTimeoutMs: number,\n): void {\n\tconst existing = sessionRegistry.get(token);\n\tif (existing && existing.client !== client) {\n\t\tclearTimeout(existing.idleTimer);\n\t\texisting.client.dispose();\n\t}\n\tconst idleTimer = setTimeout(() => {\n\t\tconst session = sessionRegistry.get(token);\n\t\tif (session) {\n\t\t\tsessionRegistry.delete(token);\n\t\t\tsession.client.dispose();\n\t\t}\n\t}, idleTimeoutMs);\n\tidleTimer.unref?.();\n\tsessionRegistry.set(token, { client, rounds, idleTimer, idleTimeoutMs });\n}\n\n/**\n * Remove a paused session from the registry and return it, stopping its idle\n * timer. The caller now owns the client (to resume or dispose). Returns\n * undefined if the token is unknown (expired/reaped/already completed).\n */\nexport function takeSession(token: ResumeToken): PausedSession | undefined {\n\tconst session = sessionRegistry.get(token);\n\tif (!session) return undefined;\n\tclearTimeout(session.idleTimer);\n\tsessionRegistry.delete(token);\n\treturn session;\n}\n\n/** Dispose every parked session. Used on shutdown and in tests. */\nexport function disposeAllSessions(): void {\n\tfor (const [, session] of sessionRegistry) {\n\t\tclearTimeout(session.idleTimer);\n\t\tsession.client.dispose();\n\t}\n\tsessionRegistry.clear();\n}\n\n/** Number of currently parked sessions (for tests/diagnostics). */\nexport function pausedSessionCount(): number {\n\treturn sessionRegistry.size;\n}\n"]}
@@ -50,6 +50,8 @@ export function resolveBrowsertoolsOptions(options) {
50
50
  return {
51
51
  binaryPath: options?.binaryPath,
52
52
  browserPath: options?.browserPath ?? (process.env.HOOCODE_BROWSERTOOLS_BROWSER_PATH?.trim() || undefined),
53
+ headful: options?.headful ?? false,
54
+ liveView: options?.liveView ?? false,
53
55
  idleTimeoutMs: options?.idleTimeoutMs ?? envNumber("HOOCODE_BROWSERTOOLS_IDLE_MS") ?? BROWSERTOOLS_DEFAULT_IDLE_MS,
54
56
  maxParentRounds: options?.maxParentRounds ?? envNumber("HOOCODE_BROWSERTOOLS_MAX_ROUNDS") ?? BROWSERTOOLS_DEFAULT_MAX_ROUNDS,
55
57
  requestTimeoutMs: options?.requestTimeoutMs ??
@@ -99,6 +101,11 @@ export class BrowsertoolsServeClient {
99
101
  env.BROWSERTOOLS_BROWSER_PATH = opts.browserPath;
100
102
  env.CHROME_PATH = opts.browserPath;
101
103
  }
104
+ // Opt into a real on-screen Chromium window. The serve process reads this
105
+ // in `Driver::launch`; harmless if an older binary ignores it.
106
+ if (opts.headful) {
107
+ env.BROWSERTOOLS_HEADFUL = "1";
108
+ }
102
109
  // Run the serve process in the project cwd so relative flow paths and the
103
110
  // evidence store resolve the same way the user expects.
104
111
  this.proc = spawn(binaryPath, ["serve", ...opts.serveArgs], {
@@ -1 +1 @@
1
- {"version":3,"file":"browsertools-shared.js","sourceRoot":"","sources":["../../../src/core/tools/browsertools-shared.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAqB,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAsC1D,+EAA+E;AAC/E,gBAAgB;AAChB,+EAA+E;AAE/E;0CAC0C;AAC1C,MAAM,CAAC,MAAM,+BAA+B,GAAG,OAAO,CAAC;AAEvD;;;+CAG+C;AAC/C,MAAM,CAAC,MAAM,4BAA4B,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AAE1D;2BAC2B;AAC3B,MAAM,CAAC,MAAM,+BAA+B,GAAG,EAAE,CAAC;AAkBlD,SAAS,SAAS,CAAC,IAAY,EAAsB;IACpD,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAC9B,IAAI,CAAC,GAAG;QAAE,OAAO,SAAS,CAAC;IAC3B,MAAM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AAC;IAC3C,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IAC/B,YAAY,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAChC,eAAe,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAC9B,OAAO,OAAO,CAAC;AAAA,CACf;AAED,mEAAmE;AACnE,MAAM,UAAU,kBAAkB,GAAS;IAC1C,KAAK,MAAM,CAAC,EAAE,OAAO,CAAC,IAAI,eAAe,EAAE,CAAC;QAC3C,YAAY,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QAChC,OAAO,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;IAC1B,CAAC;IACD,eAAe,CAAC,KAAK,EAAE,CAAC;AAAA,CACxB;AAED,mEAAmE;AACnE,MAAM,UAAU,kBAAkB,GAAW;IAC5C,OAAO,eAAe,CAAC,IAAI,CAAC;AAAA,CAC5B","sourcesContent":["/**\n * Shared plumbing for the `browser_flow` and `browser_resume` tools.\n *\n * Unlike `webtools` (one-shot fetch/search subprocesses), `browsertools` drives\n * a *stateful* parent-in-the-loop protocol: a single long-lived `browsertools\n * serve` process holds the live Chromium and the paused-flow state in memory,\n * and the parent (hoocode) talks to it over newline-delimited JSON-RPC on\n * stdin/stdout. A flow can suspend mid-replay with `Outcome::NeedsParent`,\n * yielding a typed `ParentRequest` + `ResumeToken`; the parent reasons about it\n * (often by looking at a screenshot) and calls `flow_resume(token, response)` to\n * continue. See https://github.com/kolisachint/browsertools (contract.rs).\n *\n * Because that single serve process must survive *between* the `browser_flow`\n * call that starts the flow and the `browser_resume` call that answers a\n * `NeedsParent`, this module owns a process-wide {@link sessionRegistry} keyed by\n * `ResumeToken`. Each paused session keeps its serve client alive and is reaped\n * after an idle timeout so an abandoned flow never leaks a Chromium forever.\n *\n * This module owns:\n * - the persistent JSON-RPC serve client (id-correlated request/response),\n * - the locked contract types (mirrors browsertools `src/contract.rs`),\n * - the paused-session registry + lifecycle (idle reap, round cap, teardown),\n * - binary + browser-path resolution.\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { ensureTool } from \"../../utils/tools-manager.js\";\n\n// ============================================================================\n// Contract types (locked against browsertools `src/contract.rs`)\n// ============================================================================\n\n/** Opaque token identifying a paused flow, returned with every `NeedsParent`. */\nexport type ResumeToken = string;\n\n/** Reference to bytes (e.g. a screenshot) the parent can fetch via `get_resource`. */\nexport type ResourceId = string;\n\n/**\n * A typed request the engine yields when replay hits ambiguity only an LLM can\n * resolve. The `request` discriminant matches the serde tag in contract.rs.\n * Fields beyond the discriminant are passed through verbatim to the model.\n */\nexport interface ParentRequest {\n\trequest: \"classify_state\" | \"verify_visual\" | \"extract_semantic\" | \"decide_next_action\" | \"reidentify_element\";\n\t/** Resource id of the screenshot captured at the suspension point, if any. */\n\tscreenshot_ref?: ResourceId;\n\t[key: string]: unknown;\n}\n\n/** Result of a `flow_start` / `flow_resume` RPC (the `result` field's `outcome`). */\nexport type FlowOutcome =\n\t| { outcome: \"complete\"; result?: unknown }\n\t| { outcome: \"needs_parent\"; request: ParentRequest; token: ResumeToken }\n\t| { outcome: \"failed\"; step_id?: string; kind?: string; detail?: string };\n\n/** Result of a `get_resource` RPC. */\nexport interface GetResourceResult {\n\tref: ResourceId;\n\tmime: string;\n\tlen: number;\n\tpng_base64: string;\n}\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\n/** Default per-request RPC timeout. Flow steps drive a real browser, so this is\n * generous relative to webtools' 15s. */\nexport const BROWSERTOOLS_REQUEST_TIMEOUT_MS = 120_000;\n\n/** Default idle window a paused flow may sit in the registry before it is reaped\n * (killing its serve process + Chromium). Reset on every resume round. The\n * parent may reason / look at a screenshot / make other tool calls between\n * rounds, so this is minutes, not seconds. */\nexport const BROWSERTOOLS_DEFAULT_IDLE_MS = 5 * 60 * 1000;\n\n/** Default hard cap on `NeedsParent` rounds for a single flow, bounding a runaway\n * suspend/resume loop. */\nexport const BROWSERTOOLS_DEFAULT_MAX_ROUNDS = 12;\n\n/** Options threaded into the browser tools by their factories (tests/overrides). */\nexport interface BrowsertoolsToolOptions {\n\t/** Explicit path to the `browsertools` binary; otherwise resolved via {@link ensureTool}. */\n\tbinaryPath?: string;\n\t/** Chromium/Chrome executable path forwarded to the serve process. */\n\tbrowserPath?: string;\n\t/** Idle reap window for paused sessions (ms). */\n\tidleTimeoutMs?: number;\n\t/** Hard cap on NeedsParent rounds per flow. */\n\tmaxParentRounds?: number;\n\t/** Per-request RPC timeout (ms). */\n\trequestTimeoutMs?: number;\n\t/** Extra args appended after `serve` (mainly for tests). */\n\tserveArgs?: string[];\n}\n\nfunction envNumber(name: string): number | undefined {\n\tconst raw = process.env[name];\n\tif (!raw) return undefined;\n\tconst n = Number(raw);\n\treturn Number.isFinite(n) && n > 0 ? n : undefined;\n}\n\n/** Resolve effective options from explicit overrides, then env, then defaults. */\nexport function resolveBrowsertoolsOptions(options?: BrowsertoolsToolOptions): Required<\n\tPick<BrowsertoolsToolOptions, \"idleTimeoutMs\" | \"maxParentRounds\" | \"requestTimeoutMs\">\n> & {\n\tbinaryPath?: string;\n\tbrowserPath?: string;\n\tserveArgs: string[];\n} {\n\treturn {\n\t\tbinaryPath: options?.binaryPath,\n\t\tbrowserPath: options?.browserPath ?? (process.env.HOOCODE_BROWSERTOOLS_BROWSER_PATH?.trim() || undefined),\n\t\tidleTimeoutMs:\n\t\t\toptions?.idleTimeoutMs ?? envNumber(\"HOOCODE_BROWSERTOOLS_IDLE_MS\") ?? BROWSERTOOLS_DEFAULT_IDLE_MS,\n\t\tmaxParentRounds:\n\t\t\toptions?.maxParentRounds ?? envNumber(\"HOOCODE_BROWSERTOOLS_MAX_ROUNDS\") ?? BROWSERTOOLS_DEFAULT_MAX_ROUNDS,\n\t\trequestTimeoutMs:\n\t\t\toptions?.requestTimeoutMs ??\n\t\t\tenvNumber(\"HOOCODE_BROWSERTOOLS_REQUEST_TIMEOUT_MS\") ??\n\t\t\tBROWSERTOOLS_REQUEST_TIMEOUT_MS,\n\t\tserveArgs: options?.serveArgs ?? [],\n\t};\n}\n\nconst BINARY_MISSING_MESSAGE =\n\t\"browsertools binary unavailable and could not be downloaded — the browser tools require the `browsertools` CLI on PATH or a published release for this platform\";\n\n/** Resolve the `browsertools` binary path (explicit override, else download/PATH). */\nexport async function resolveBrowsertoolsBinary(options?: BrowsertoolsToolOptions): Promise<string> {\n\tif (options?.binaryPath) return options.binaryPath;\n\tconst binaryPath = await ensureTool(\"browsertools\", true);\n\tif (!binaryPath) throw new Error(BINARY_MISSING_MESSAGE);\n\treturn binaryPath;\n}\n\n// ============================================================================\n// Persistent JSON-RPC serve client\n// ============================================================================\n\ninterface PendingRequest {\n\tresolve: (value: unknown) => void;\n\treject: (error: Error) => void;\n\ttimer: ReturnType<typeof setTimeout>;\n}\n\n/**\n * A live `browsertools serve` process spoken to over newline-delimited JSON-RPC.\n *\n * Wire format (browsertools `src/serve.rs`):\n * request: `{ \"id\": <n>, \"method\": <string>, \"params\": <object> }\\n`\n * response: `{ \"id\": <n>, \"result\": <value> }` or `{ \"id\": <n>, \"error\": <RpcError> }`\\n\n *\n * Responses are correlated by `id`, so concurrent requests are safe, though the\n * tools drive it sequentially.\n */\nexport class BrowsertoolsServeClient {\n\tprivate readonly proc: ChildProcess;\n\tprivate readonly pending = new Map<number, PendingRequest>();\n\tprivate readonly requestTimeoutMs: number;\n\tprivate buffer = \"\";\n\tprivate nextId = 1;\n\tprivate closed = false;\n\tprivate exitError: Error | undefined;\n\tprivate stderrTail = \"\";\n\n\tconstructor(\n\t\tbinaryPath: string,\n\t\topts: { cwd?: string; browserPath?: string; serveArgs: string[]; requestTimeoutMs: number },\n\t) {\n\t\tthis.requestTimeoutMs = opts.requestTimeoutMs;\n\t\t// The exact CLI flag for the browser path is not part of the locked RPC\n\t\t// contract; v0.1.3 added a \"configurable browser path\". We forward it via\n\t\t// env vars the binary is likely to read. Passing extra env is harmless if\n\t\t// the binary ignores them, and centralizing it here makes it a one-line\n\t\t// change once the exact mechanism is confirmed.\n\t\tconst env = { ...process.env };\n\t\tif (opts.browserPath) {\n\t\t\tenv.BROWSERTOOLS_BROWSER_PATH = opts.browserPath;\n\t\t\tenv.CHROME_PATH = opts.browserPath;\n\t\t}\n\t\t// Run the serve process in the project cwd so relative flow paths and the\n\t\t// evidence store resolve the same way the user expects.\n\t\tthis.proc = spawn(binaryPath, [\"serve\", ...opts.serveArgs], {\n\t\t\tcwd: opts.cwd,\n\t\t\tshell: false,\n\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t\tenv,\n\t\t});\n\t\tthis.proc.stdout?.setEncoding(\"utf8\");\n\t\tthis.proc.stdout?.on(\"data\", (chunk: string) => this.onStdout(chunk));\n\t\tthis.proc.stderr?.setEncoding(\"utf8\");\n\t\tthis.proc.stderr?.on(\"data\", (chunk: string) => {\n\t\t\t// Keep only a bounded tail so a chatty serve can't grow unbounded; it is\n\t\t\t// surfaced in the error when the process dies unexpectedly.\n\t\t\tthis.stderrTail = (this.stderrTail + chunk).slice(-4000);\n\t\t});\n\t\tthis.proc.on(\"error\", (err) => this.fail(err instanceof Error ? err : new Error(String(err))));\n\t\tthis.proc.on(\"exit\", (code, sig) => {\n\t\t\tif (this.closed) return;\n\t\t\tconst detail = this.stderrTail.trim();\n\t\t\tthis.fail(\n\t\t\t\tnew Error(\n\t\t\t\t\t`browsertools serve exited unexpectedly (code=${code ?? \"null\"}, signal=${sig ?? \"null\"})` +\n\t\t\t\t\t\t(detail ? `: ${detail}` : \"\"),\n\t\t\t\t),\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate onStdout(chunk: string): void {\n\t\tthis.buffer += chunk;\n\t\tlet newlineIndex = this.buffer.indexOf(\"\\n\");\n\t\twhile (newlineIndex !== -1) {\n\t\t\tconst line = this.buffer.slice(0, newlineIndex).trim();\n\t\t\tthis.buffer = this.buffer.slice(newlineIndex + 1);\n\t\t\tif (line) this.onLine(line);\n\t\t\tnewlineIndex = this.buffer.indexOf(\"\\n\");\n\t\t}\n\t}\n\n\tprivate onLine(line: string): void {\n\t\tlet message: { id?: unknown; result?: unknown; error?: unknown };\n\t\ttry {\n\t\t\tmessage = JSON.parse(line);\n\t\t} catch {\n\t\t\t// Non-JSON noise on stdout (shouldn't happen; logs go to stderr). Skip it\n\t\t\t// rather than corrupt id correlation.\n\t\t\treturn;\n\t\t}\n\t\tconst id = typeof message.id === \"number\" ? message.id : undefined;\n\t\tif (id === undefined) return;\n\t\tconst entry = this.pending.get(id);\n\t\tif (!entry) return;\n\t\tthis.pending.delete(id);\n\t\tclearTimeout(entry.timer);\n\t\tif (message.error !== undefined && message.error !== null) {\n\t\t\tentry.reject(new Error(`browsertools ${describeRpcError(message.error)}`));\n\t\t} else {\n\t\t\tentry.resolve(message.result);\n\t\t}\n\t}\n\n\t/** Reject all in-flight requests and mark the client dead. Idempotent. */\n\tprivate fail(error: Error): void {\n\t\tif (this.closed) return;\n\t\tthis.exitError = error;\n\t\tfor (const [, entry] of this.pending) {\n\t\t\tclearTimeout(entry.timer);\n\t\t\tentry.reject(error);\n\t\t}\n\t\tthis.pending.clear();\n\t}\n\n\t/** Send a JSON-RPC request and resolve with its `result` (or reject on `error`). */\n\trequest<T = unknown>(method: string, params: Record<string, unknown>): Promise<T> {\n\t\tif (this.closed) {\n\t\t\treturn Promise.reject(this.exitError ?? new Error(\"browsertools serve client is closed\"));\n\t\t}\n\t\tconst id = this.nextId++;\n\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tif (this.pending.delete(id)) {\n\t\t\t\t\treject(new Error(`browsertools ${method} timed out after ${this.requestTimeoutMs}ms`));\n\t\t\t\t}\n\t\t\t}, this.requestTimeoutMs);\n\t\t\tthis.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });\n\t\t\tconst payload = `${JSON.stringify({ id, method, params })}\\n`;\n\t\t\tthis.proc.stdin?.write(payload, (err) => {\n\t\t\t\tif (err && this.pending.delete(id)) {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\treject(err);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\t/** Kill the serve process and reject any outstanding requests. Idempotent. */\n\tdispose(): void {\n\t\tif (this.closed) return;\n\t\tthis.fail(new Error(\"browsertools serve client disposed\"));\n\t\tthis.closed = true;\n\t\t// Best-effort graceful shutdown, then ensure the process is gone.\n\t\ttry {\n\t\t\tthis.proc.stdin?.write(`${JSON.stringify({ id: this.nextId++, method: \"shutdown\", params: {} })}\\n`);\n\t\t} catch {\n\t\t\t// stdin may already be closed; fall through to kill.\n\t\t}\n\t\tthis.proc.stdin?.end();\n\t\tthis.proc.kill(\"SIGTERM\");\n\t\tconst proc = this.proc;\n\t\tsetTimeout(() => {\n\t\t\tif (proc.exitCode === null && proc.signalCode === null) proc.kill(\"SIGKILL\");\n\t\t}, 3000).unref?.();\n\t}\n}\n\nfunction describeRpcError(error: unknown): string {\n\tif (error && typeof error === \"object\") {\n\t\tconst message = (error as { message?: unknown }).message;\n\t\tif (typeof message === \"string\" && message) return message;\n\t}\n\tif (typeof error === \"string\" && error) return error;\n\treturn `RPC error: ${JSON.stringify(error)}`;\n}\n\n// ============================================================================\n// Paused-session registry (process-wide, keyed by ResumeToken)\n// ============================================================================\n\ninterface PausedSession {\n\tclient: BrowsertoolsServeClient;\n\t/** Number of NeedsParent rounds yielded so far for this flow. */\n\trounds: number;\n\tidleTimer: ReturnType<typeof setTimeout>;\n\tidleTimeoutMs: number;\n}\n\nconst sessionRegistry = new Map<ResumeToken, PausedSession>();\n\n/**\n * Park a paused flow's live serve client under its resume token and arm the idle\n * reaper. Any previous entry for the token is disposed first.\n */\nexport function parkSession(\n\ttoken: ResumeToken,\n\tclient: BrowsertoolsServeClient,\n\trounds: number,\n\tidleTimeoutMs: number,\n): void {\n\tconst existing = sessionRegistry.get(token);\n\tif (existing && existing.client !== client) {\n\t\tclearTimeout(existing.idleTimer);\n\t\texisting.client.dispose();\n\t}\n\tconst idleTimer = setTimeout(() => {\n\t\tconst session = sessionRegistry.get(token);\n\t\tif (session) {\n\t\t\tsessionRegistry.delete(token);\n\t\t\tsession.client.dispose();\n\t\t}\n\t}, idleTimeoutMs);\n\tidleTimer.unref?.();\n\tsessionRegistry.set(token, { client, rounds, idleTimer, idleTimeoutMs });\n}\n\n/**\n * Remove a paused session from the registry and return it, stopping its idle\n * timer. The caller now owns the client (to resume or dispose). Returns\n * undefined if the token is unknown (expired/reaped/already completed).\n */\nexport function takeSession(token: ResumeToken): PausedSession | undefined {\n\tconst session = sessionRegistry.get(token);\n\tif (!session) return undefined;\n\tclearTimeout(session.idleTimer);\n\tsessionRegistry.delete(token);\n\treturn session;\n}\n\n/** Dispose every parked session. Used on shutdown and in tests. */\nexport function disposeAllSessions(): void {\n\tfor (const [, session] of sessionRegistry) {\n\t\tclearTimeout(session.idleTimer);\n\t\tsession.client.dispose();\n\t}\n\tsessionRegistry.clear();\n}\n\n/** Number of currently parked sessions (for tests/diagnostics). */\nexport function pausedSessionCount(): number {\n\treturn sessionRegistry.size;\n}\n"]}
1
+ {"version":3,"file":"browsertools-shared.js","sourceRoot":"","sources":["../../../src/core/tools/browsertools-shared.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAqB,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAsC1D,+EAA+E;AAC/E,gBAAgB;AAChB,+EAA+E;AAE/E;0CAC0C;AAC1C,MAAM,CAAC,MAAM,+BAA+B,GAAG,OAAO,CAAC;AAEvD;;;+CAG+C;AAC/C,MAAM,CAAC,MAAM,4BAA4B,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AAE1D;2BAC2B;AAC3B,MAAM,CAAC,MAAM,+BAA+B,GAAG,EAAE,CAAC;AAwBlD,SAAS,SAAS,CAAC,IAAY,EAAsB;IACpD,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,I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E,aAAa,CAAC,CAAC;IAClB,SAAS,CAAC,KAAK,EAAE,EAAE,CAAC;IACpB,eAAe,CAAC,GAAG,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,aAAa,EAAE,CAAC,CAAC;AAAA,CACzE;AAED;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAC,KAAkB,EAA6B;IAC1E,MAAM,OAAO,GAAG,eAAe,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC3C,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IAC/B,YAAY,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAChC,eAAe,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAC9B,OAAO,OAAO,CAAC;AAAA,CACf;AAED,mEAAmE;AACnE,MAAM,UAAU,kBAAkB,GAAS;IAC1C,KAAK,MAAM,CAAC,EAAE,OAAO,CAAC,IAAI,eAAe,EAAE,CAAC;QAC3C,YAAY,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QAChC,OAAO,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;IAC1B,CAAC;IACD,eAAe,CAAC,KAAK,EAAE,CAAC;AAAA,CACxB;AAED,mEAAmE;AACnE,MAAM,UAAU,kBAAkB,GAAW;IAC5C,OAAO,eAAe,CAAC,IAAI,CAAC;AAAA,CAC5B","sourcesContent":["/**\n * Shared plumbing for the `browser_flow` and `browser_resume` tools.\n *\n * Unlike `webtools` (one-shot fetch/search subprocesses), `browsertools` drives\n * a *stateful* parent-in-the-loop protocol: a single long-lived `browsertools\n * serve` process holds the live Chromium and the paused-flow state in memory,\n * and the parent (hoocode) talks to it over newline-delimited JSON-RPC on\n * stdin/stdout. A flow can suspend mid-replay with `Outcome::NeedsParent`,\n * yielding a typed `ParentRequest` + `ResumeToken`; the parent reasons about it\n * (often by looking at a screenshot) and calls `flow_resume(token, response)` to\n * continue. See https://github.com/kolisachint/browsertools (contract.rs).\n *\n * Because that single serve process must survive *between* the `browser_flow`\n * call that starts the flow and the `browser_resume` call that answers a\n * `NeedsParent`, this module owns a process-wide {@link sessionRegistry} keyed by\n * `ResumeToken`. Each paused session keeps its serve client alive and is reaped\n * after an idle timeout so an abandoned flow never leaks a Chromium forever.\n *\n * This module owns:\n * - the persistent JSON-RPC serve client (id-correlated request/response),\n * - the locked contract types (mirrors browsertools `src/contract.rs`),\n * - the paused-session registry + lifecycle (idle reap, round cap, teardown),\n * - binary + browser-path resolution.\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { ensureTool } from \"../../utils/tools-manager.js\";\n\n// ============================================================================\n// Contract types (locked against browsertools `src/contract.rs`)\n// ============================================================================\n\n/** Opaque token identifying a paused flow, returned with every `NeedsParent`. */\nexport type ResumeToken = string;\n\n/** Reference to bytes (e.g. a screenshot) the parent can fetch via `get_resource`. */\nexport type ResourceId = string;\n\n/**\n * A typed request the engine yields when replay hits ambiguity only an LLM can\n * resolve. The `request` discriminant matches the serde tag in contract.rs.\n * Fields beyond the discriminant are passed through verbatim to the model.\n */\nexport interface ParentRequest {\n\trequest: \"classify_state\" | \"verify_visual\" | \"extract_semantic\" | \"decide_next_action\" | \"reidentify_element\";\n\t/** Resource id of the screenshot captured at the suspension point, if any. */\n\tscreenshot_ref?: ResourceId;\n\t[key: string]: unknown;\n}\n\n/** Result of a `flow_start` / `flow_resume` RPC (the `result` field's `outcome`). */\nexport type FlowOutcome =\n\t| { outcome: \"complete\"; result?: unknown }\n\t| { outcome: \"needs_parent\"; request: ParentRequest; token: ResumeToken }\n\t| { outcome: \"failed\"; step_id?: string; kind?: string; detail?: string };\n\n/** Result of a `get_resource` RPC. */\nexport interface GetResourceResult {\n\tref: ResourceId;\n\tmime: string;\n\tlen: number;\n\tpng_base64: string;\n}\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\n/** Default per-request RPC timeout. Flow steps drive a real browser, so this is\n * generous relative to webtools' 15s. */\nexport const BROWSERTOOLS_REQUEST_TIMEOUT_MS = 120_000;\n\n/** Default idle window a paused flow may sit in the registry before it is reaped\n * (killing its serve process + Chromium). Reset on every resume round. The\n * parent may reason / look at a screenshot / make other tool calls between\n * rounds, so this is minutes, not seconds. */\nexport const BROWSERTOOLS_DEFAULT_IDLE_MS = 5 * 60 * 1000;\n\n/** Default hard cap on `NeedsParent` rounds for a single flow, bounding a runaway\n * suspend/resume loop. */\nexport const BROWSERTOOLS_DEFAULT_MAX_ROUNDS = 12;\n\n/** Options threaded into the browser tools by their factories (tests/overrides). */\nexport interface BrowsertoolsToolOptions {\n\t/** Explicit path to the `browsertools` binary; otherwise resolved via {@link ensureTool}. */\n\tbinaryPath?: string;\n\t/** Chromium/Chrome executable path forwarded to the serve process. */\n\tbrowserPath?: string;\n\t/** Idle reap window for paused sessions (ms). */\n\tidleTimeoutMs?: number;\n\t/** Hard cap on NeedsParent rounds per flow. */\n\tmaxParentRounds?: number;\n\t/** Per-request RPC timeout (ms). */\n\trequestTimeoutMs?: number;\n\t/** Extra args appended after `serve` (mainly for tests). */\n\tserveArgs?: string[];\n\t/** Launch a real on-screen Chromium window instead of headless (sets\n\t * `BROWSERTOOLS_HEADFUL=1` on the serve process). */\n\theadful?: boolean;\n\t/** Default the streamed live viewer on for every flow (the per-call `live_view`\n\t * param still overrides). Set by the --enable-browser-live-preview flag. */\n\tliveView?: boolean;\n}\n\nfunction envNumber(name: string): number | undefined {\n\tconst raw = process.env[name];\n\tif (!raw) return undefined;\n\tconst n = Number(raw);\n\treturn Number.isFinite(n) && n > 0 ? n : undefined;\n}\n\n/** Resolve effective options from explicit overrides, then env, then defaults. */\nexport function resolveBrowsertoolsOptions(options?: BrowsertoolsToolOptions): Required<\n\tPick<BrowsertoolsToolOptions, \"idleTimeoutMs\" | \"maxParentRounds\" | \"requestTimeoutMs\">\n> & {\n\tbinaryPath?: string;\n\tbrowserPath?: string;\n\tserveArgs: string[];\n\theadful: boolean;\n\tliveView: boolean;\n} {\n\treturn {\n\t\tbinaryPath: options?.binaryPath,\n\t\tbrowserPath: options?.browserPath ?? (process.env.HOOCODE_BROWSERTOOLS_BROWSER_PATH?.trim() || undefined),\n\t\theadful: options?.headful ?? false,\n\t\tliveView: options?.liveView ?? false,\n\t\tidleTimeoutMs:\n\t\t\toptions?.idleTimeoutMs ?? envNumber(\"HOOCODE_BROWSERTOOLS_IDLE_MS\") ?? BROWSERTOOLS_DEFAULT_IDLE_MS,\n\t\tmaxParentRounds:\n\t\t\toptions?.maxParentRounds ?? envNumber(\"HOOCODE_BROWSERTOOLS_MAX_ROUNDS\") ?? BROWSERTOOLS_DEFAULT_MAX_ROUNDS,\n\t\trequestTimeoutMs:\n\t\t\toptions?.requestTimeoutMs ??\n\t\t\tenvNumber(\"HOOCODE_BROWSERTOOLS_REQUEST_TIMEOUT_MS\") ??\n\t\t\tBROWSERTOOLS_REQUEST_TIMEOUT_MS,\n\t\tserveArgs: options?.serveArgs ?? [],\n\t};\n}\n\nconst BINARY_MISSING_MESSAGE =\n\t\"browsertools binary unavailable and could not be downloaded — the browser tools require the `browsertools` CLI on PATH or a published release for this platform\";\n\n/** Resolve the `browsertools` binary path (explicit override, else download/PATH). */\nexport async function resolveBrowsertoolsBinary(options?: BrowsertoolsToolOptions): Promise<string> {\n\tif (options?.binaryPath) return options.binaryPath;\n\tconst binaryPath = await ensureTool(\"browsertools\", true);\n\tif (!binaryPath) throw new Error(BINARY_MISSING_MESSAGE);\n\treturn binaryPath;\n}\n\n// ============================================================================\n// Persistent JSON-RPC serve client\n// ============================================================================\n\ninterface PendingRequest {\n\tresolve: (value: unknown) => void;\n\treject: (error: Error) => void;\n\ttimer: ReturnType<typeof setTimeout>;\n}\n\n/**\n * A live `browsertools serve` process spoken to over newline-delimited JSON-RPC.\n *\n * Wire format (browsertools `src/serve.rs`):\n * request: `{ \"id\": <n>, \"method\": <string>, \"params\": <object> }\\n`\n * response: `{ \"id\": <n>, \"result\": <value> }` or `{ \"id\": <n>, \"error\": <RpcError> }`\\n\n *\n * Responses are correlated by `id`, so concurrent requests are safe, though the\n * tools drive it sequentially.\n */\nexport class BrowsertoolsServeClient {\n\tprivate readonly proc: ChildProcess;\n\tprivate readonly pending = new Map<number, PendingRequest>();\n\tprivate readonly requestTimeoutMs: number;\n\tprivate buffer = \"\";\n\tprivate nextId = 1;\n\tprivate closed = false;\n\tprivate exitError: Error | undefined;\n\tprivate stderrTail = \"\";\n\n\tconstructor(\n\t\tbinaryPath: string,\n\t\topts: {\n\t\t\tcwd?: string;\n\t\t\tbrowserPath?: string;\n\t\t\tserveArgs: string[];\n\t\t\trequestTimeoutMs: number;\n\t\t\theadful?: boolean;\n\t\t},\n\t) {\n\t\tthis.requestTimeoutMs = opts.requestTimeoutMs;\n\t\t// The exact CLI flag for the browser path is not part of the locked RPC\n\t\t// contract; v0.1.3 added a \"configurable browser path\". We forward it via\n\t\t// env vars the binary is likely to read. Passing extra env is harmless if\n\t\t// the binary ignores them, and centralizing it here makes it a one-line\n\t\t// change once the exact mechanism is confirmed.\n\t\tconst env = { ...process.env };\n\t\tif (opts.browserPath) {\n\t\t\tenv.BROWSERTOOLS_BROWSER_PATH = opts.browserPath;\n\t\t\tenv.CHROME_PATH = opts.browserPath;\n\t\t}\n\t\t// Opt into a real on-screen Chromium window. The serve process reads this\n\t\t// in `Driver::launch`; harmless if an older binary ignores it.\n\t\tif (opts.headful) {\n\t\t\tenv.BROWSERTOOLS_HEADFUL = \"1\";\n\t\t}\n\t\t// Run the serve process in the project cwd so relative flow paths and the\n\t\t// evidence store resolve the same way the user expects.\n\t\tthis.proc = spawn(binaryPath, [\"serve\", ...opts.serveArgs], {\n\t\t\tcwd: opts.cwd,\n\t\t\tshell: false,\n\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t\tenv,\n\t\t});\n\t\tthis.proc.stdout?.setEncoding(\"utf8\");\n\t\tthis.proc.stdout?.on(\"data\", (chunk: string) => this.onStdout(chunk));\n\t\tthis.proc.stderr?.setEncoding(\"utf8\");\n\t\tthis.proc.stderr?.on(\"data\", (chunk: string) => {\n\t\t\t// Keep only a bounded tail so a chatty serve can't grow unbounded; it is\n\t\t\t// surfaced in the error when the process dies unexpectedly.\n\t\t\tthis.stderrTail = (this.stderrTail + chunk).slice(-4000);\n\t\t});\n\t\tthis.proc.on(\"error\", (err) => this.fail(err instanceof Error ? err : new Error(String(err))));\n\t\tthis.proc.on(\"exit\", (code, sig) => {\n\t\t\tif (this.closed) return;\n\t\t\tconst detail = this.stderrTail.trim();\n\t\t\tthis.fail(\n\t\t\t\tnew Error(\n\t\t\t\t\t`browsertools serve exited unexpectedly (code=${code ?? \"null\"}, signal=${sig ?? \"null\"})` +\n\t\t\t\t\t\t(detail ? `: ${detail}` : \"\"),\n\t\t\t\t),\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate onStdout(chunk: string): void {\n\t\tthis.buffer += chunk;\n\t\tlet newlineIndex = this.buffer.indexOf(\"\\n\");\n\t\twhile (newlineIndex !== -1) {\n\t\t\tconst line = this.buffer.slice(0, newlineIndex).trim();\n\t\t\tthis.buffer = this.buffer.slice(newlineIndex + 1);\n\t\t\tif (line) this.onLine(line);\n\t\t\tnewlineIndex = this.buffer.indexOf(\"\\n\");\n\t\t}\n\t}\n\n\tprivate onLine(line: string): void {\n\t\tlet message: { id?: unknown; result?: unknown; error?: unknown };\n\t\ttry {\n\t\t\tmessage = JSON.parse(line);\n\t\t} catch {\n\t\t\t// Non-JSON noise on stdout (shouldn't happen; logs go to stderr). Skip it\n\t\t\t// rather than corrupt id correlation.\n\t\t\treturn;\n\t\t}\n\t\tconst id = typeof message.id === \"number\" ? message.id : undefined;\n\t\tif (id === undefined) return;\n\t\tconst entry = this.pending.get(id);\n\t\tif (!entry) return;\n\t\tthis.pending.delete(id);\n\t\tclearTimeout(entry.timer);\n\t\tif (message.error !== undefined && message.error !== null) {\n\t\t\tentry.reject(new Error(`browsertools ${describeRpcError(message.error)}`));\n\t\t} else {\n\t\t\tentry.resolve(message.result);\n\t\t}\n\t}\n\n\t/** Reject all in-flight requests and mark the client dead. Idempotent. */\n\tprivate fail(error: Error): void {\n\t\tif (this.closed) return;\n\t\tthis.exitError = error;\n\t\tfor (const [, entry] of this.pending) {\n\t\t\tclearTimeout(entry.timer);\n\t\t\tentry.reject(error);\n\t\t}\n\t\tthis.pending.clear();\n\t}\n\n\t/** Send a JSON-RPC request and resolve with its `result` (or reject on `error`). */\n\trequest<T = unknown>(method: string, params: Record<string, unknown>): Promise<T> {\n\t\tif (this.closed) {\n\t\t\treturn Promise.reject(this.exitError ?? new Error(\"browsertools serve client is closed\"));\n\t\t}\n\t\tconst id = this.nextId++;\n\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tif (this.pending.delete(id)) {\n\t\t\t\t\treject(new Error(`browsertools ${method} timed out after ${this.requestTimeoutMs}ms`));\n\t\t\t\t}\n\t\t\t}, this.requestTimeoutMs);\n\t\t\tthis.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });\n\t\t\tconst payload = `${JSON.stringify({ id, method, params })}\\n`;\n\t\t\tthis.proc.stdin?.write(payload, (err) => {\n\t\t\t\tif (err && this.pending.delete(id)) {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\treject(err);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\t/** Kill the serve process and reject any outstanding requests. Idempotent. */\n\tdispose(): void {\n\t\tif (this.closed) return;\n\t\tthis.fail(new Error(\"browsertools serve client disposed\"));\n\t\tthis.closed = true;\n\t\t// Best-effort graceful shutdown, then ensure the process is gone.\n\t\ttry {\n\t\t\tthis.proc.stdin?.write(`${JSON.stringify({ id: this.nextId++, method: \"shutdown\", params: {} })}\\n`);\n\t\t} catch {\n\t\t\t// stdin may already be closed; fall through to kill.\n\t\t}\n\t\tthis.proc.stdin?.end();\n\t\tthis.proc.kill(\"SIGTERM\");\n\t\tconst proc = this.proc;\n\t\tsetTimeout(() => {\n\t\t\tif (proc.exitCode === null && proc.signalCode === null) proc.kill(\"SIGKILL\");\n\t\t}, 3000).unref?.();\n\t}\n}\n\nfunction describeRpcError(error: unknown): string {\n\tif (error && typeof error === \"object\") {\n\t\tconst message = (error as { message?: unknown }).message;\n\t\tif (typeof message === \"string\" && message) return message;\n\t}\n\tif (typeof error === \"string\" && error) return error;\n\treturn `RPC error: ${JSON.stringify(error)}`;\n}\n\n// ============================================================================\n// Paused-session registry (process-wide, keyed by ResumeToken)\n// ============================================================================\n\ninterface PausedSession {\n\tclient: BrowsertoolsServeClient;\n\t/** Number of NeedsParent rounds yielded so far for this flow. */\n\trounds: number;\n\tidleTimer: ReturnType<typeof setTimeout>;\n\tidleTimeoutMs: number;\n}\n\nconst sessionRegistry = new Map<ResumeToken, PausedSession>();\n\n/**\n * Park a paused flow's live serve client under its resume token and arm the idle\n * reaper. Any previous entry for the token is disposed first.\n */\nexport function parkSession(\n\ttoken: ResumeToken,\n\tclient: BrowsertoolsServeClient,\n\trounds: number,\n\tidleTimeoutMs: number,\n): void {\n\tconst existing = sessionRegistry.get(token);\n\tif (existing && existing.client !== client) {\n\t\tclearTimeout(existing.idleTimer);\n\t\texisting.client.dispose();\n\t}\n\tconst idleTimer = setTimeout(() => {\n\t\tconst session = sessionRegistry.get(token);\n\t\tif (session) {\n\t\t\tsessionRegistry.delete(token);\n\t\t\tsession.client.dispose();\n\t\t}\n\t}, idleTimeoutMs);\n\tidleTimer.unref?.();\n\tsessionRegistry.set(token, { client, rounds, idleTimer, idleTimeoutMs });\n}\n\n/**\n * Remove a paused session from the registry and return it, stopping its idle\n * timer. The caller now owns the client (to resume or dispose). Returns\n * undefined if the token is unknown (expired/reaped/already completed).\n */\nexport function takeSession(token: ResumeToken): PausedSession | undefined {\n\tconst session = sessionRegistry.get(token);\n\tif (!session) return undefined;\n\tclearTimeout(session.idleTimer);\n\tsessionRegistry.delete(token);\n\treturn session;\n}\n\n/** Dispose every parked session. Used on shutdown and in tests. */\nexport function disposeAllSessions(): void {\n\tfor (const [, session] of sessionRegistry) {\n\t\tclearTimeout(session.idleTimer);\n\t\tsession.client.dispose();\n\t}\n\tsessionRegistry.clear();\n}\n\n/** Number of currently parked sessions (for tests/diagnostics). */\nexport function pausedSessionCount(): number {\n\treturn sessionRegistry.size;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"grep.d.ts","sourceRoot":"","sources":["../../../src/core/tools/grep.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AAKjE,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAG5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAKtF,OAAO,EAIN,KAAK,gBAAgB,EAGrB,MAAM,eAAe,CAAC;AAEvB,QAAA,MAAM,UAAU;;;;;;;;EAYd,CAAC;AAEH,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAGtD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,cAAc,CAAC,EAAE,OAAO,CAAC;CACzB;AAED;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC9B,mEAAmE;IACnE,WAAW,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;IAClE,2CAA2C;IAC3C,QAAQ,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;CAC7D;AAOD,MAAM,WAAW,eAAe;IAC/B,yEAAyE;IACzE,UAAU,CAAC,EAAE,cAAc,CAAC;CAC5B;AAyDD,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC,CAoRhE;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAEnG","sourcesContent":["import { createInterface } from \"node:readline\";\nimport type { AgentTool } from \"@kolisachint/hoocode-agent-core\";\nimport { Text } from \"@kolisachint/hoocode-tui\";\nimport { spawn } from \"child_process\";\nimport { readFileSync, statSync } from \"fs\";\nimport path from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.js\";\nimport { ensureTool } from \"../../utils/tools-manager.js\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.js\";\nimport { compressGrepOutput } from \"./output-compression.js\";\nimport { resolveToCwd } from \"./path-utils.js\";\nimport { getTextOutput, invalidArgText, shortenPath, str } from \"./render-utils.js\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.js\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tformatSize,\n\tGREP_MAX_LINE_LENGTH,\n\ttype TruncationResult,\n\ttruncateHead,\n\ttruncateLine,\n} from \"./truncate.js\";\n\nconst grepSchema = Type.Object({\n\tpattern: Type.String({ description: \"Search pattern (regex or literal string)\" }),\n\tpath: Type.Optional(Type.String({ description: \"Directory or file to search (default: current directory)\" })),\n\tglob: Type.Optional(Type.String({ description: \"Filter files by glob pattern, e.g. '*.ts' or '**/*.spec.ts'\" })),\n\tignoreCase: Type.Optional(Type.Boolean({ description: \"Case-insensitive search (default: false)\" })),\n\tliteral: Type.Optional(\n\t\tType.Boolean({ description: \"Treat pattern as literal string instead of regex (default: false)\" }),\n\t),\n\tcontext: Type.Optional(\n\t\tType.Number({ description: \"Number of lines to show before and after each match (default: 0)\" }),\n\t),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of matches to return (default: 100)\" })),\n});\n\nexport type GrepToolInput = Static<typeof grepSchema>;\nconst DEFAULT_LIMIT = 100;\n\nexport interface GrepToolDetails {\n\ttruncation?: TruncationResult;\n\tmatchLimitReached?: number;\n\tlinesTruncated?: boolean;\n}\n\n/**\n * Pluggable operations for the grep tool.\n * Override these to delegate search to remote systems (for example SSH).\n */\nexport interface GrepOperations {\n\t/** Check if path is a directory. Throws if path does not exist. */\n\tisDirectory: (absolutePath: string) => Promise<boolean> | boolean;\n\t/** Read file contents for context lines */\n\treadFile: (absolutePath: string) => Promise<string> | string;\n}\n\nconst defaultGrepOperations: GrepOperations = {\n\tisDirectory: (p) => statSync(p).isDirectory(),\n\treadFile: (p) => readFileSync(p, \"utf-8\"),\n};\n\nexport interface GrepToolOptions {\n\t/** Custom operations for grep. Default: local filesystem plus ripgrep */\n\toperations?: GrepOperations;\n}\n\nfunction formatGrepCall(\n\targs: { pattern: string; path?: string; glob?: string; limit?: number } | undefined,\n\ttheme: typeof import(\"../../modes/interactive/theme/theme.js\").theme,\n): string {\n\tconst pattern = str(args?.pattern);\n\tconst rawPath = str(args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath || \".\") : null;\n\tconst glob = str(args?.glob);\n\tconst limit = args?.limit;\n\tconst invalidArg = invalidArgText(theme);\n\tlet text =\n\t\ttheme.fg(\"toolTitle\", theme.bold(\"grep\")) +\n\t\t\" \" +\n\t\t(pattern === null ? invalidArg : theme.fg(\"accent\", `/${pattern || \"\"}/`)) +\n\t\ttheme.fg(\"toolOutput\", ` in ${path === null ? invalidArg : path}`);\n\tif (glob) text += theme.fg(\"toolOutput\", ` (${glob})`);\n\tif (limit !== undefined) text += theme.fg(\"toolOutput\", ` limit ${limit}`);\n\treturn text;\n}\n\nfunction formatGrepResult(\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: GrepToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\ttheme: typeof import(\"../../modes/interactive/theme/theme.js\").theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 15;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")})`;\n\t\t}\n\t}\n\n\tconst matchLimit = result.details?.matchLimitReached;\n\tconst truncation = result.details?.truncation;\n\tconst linesTruncated = result.details?.linesTruncated;\n\tif (matchLimit || truncation?.truncated || linesTruncated) {\n\t\tconst warnings: string[] = [];\n\t\tif (matchLimit) warnings.push(`${matchLimit} matches limit`);\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\tif (linesTruncated) warnings.push(\"some lines truncated\");\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\n\nexport function createGrepToolDefinition(\n\tcwd: string,\n\toptions?: GrepToolOptions,\n): ToolDefinition<typeof grepSchema, GrepToolDetails | undefined> {\n\tconst customOps = options?.operations;\n\treturn {\n\t\tname: \"grep\",\n\t\tlabel: \"grep\",\n\t\tdescription: `Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to ${DEFAULT_LIMIT} matches or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Long lines are truncated to ${GREP_MAX_LINE_LENGTH} chars.`,\n\t\tpromptSnippet: \"Search file contents for patterns (respects .gitignore)\",\n\t\tparameters: grepSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{\n\t\t\t\tpattern,\n\t\t\t\tpath: searchDir,\n\t\t\t\tglob,\n\t\t\t\tignoreCase,\n\t\t\t\tliteral,\n\t\t\t\tcontext,\n\t\t\t\tlimit,\n\t\t\t}: {\n\t\t\t\tpattern: string;\n\t\t\t\tpath?: string;\n\t\t\t\tglob?: string;\n\t\t\t\tignoreCase?: boolean;\n\t\t\t\tliteral?: boolean;\n\t\t\t\tcontext?: number;\n\t\t\t\tlimit?: number;\n\t\t\t},\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet settled = false;\n\t\t\t\tconst settle = (fn: () => void) => {\n\t\t\t\t\tif (!settled) {\n\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\tfn();\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst rgPath = await ensureTool(\"rg\", true);\n\t\t\t\t\t\tif (!rgPath) {\n\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\treject(\n\t\t\t\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t\t\t\t\"ripgrep (rg) unavailable and could not be downloaded — use the bash tool to run grep/rg instead\",\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst searchPath = resolveToCwd(searchDir || \".\", cwd);\n\t\t\t\t\t\tconst ops = customOps ?? defaultGrepOperations;\n\t\t\t\t\t\tlet isDirectory: boolean;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tisDirectory = await ops.isDirectory(searchPath);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Path not found: ${searchPath}`)));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst contextValue = context && context > 0 ? context : 0;\n\t\t\t\t\t\tconst effectiveLimit = Math.max(1, limit ?? DEFAULT_LIMIT);\n\t\t\t\t\t\tconst formatPath = (filePath: string): string => {\n\t\t\t\t\t\t\tif (isDirectory) {\n\t\t\t\t\t\t\t\tconst relative = path.relative(searchPath, filePath);\n\t\t\t\t\t\t\t\tif (relative && !relative.startsWith(\"..\")) {\n\t\t\t\t\t\t\t\t\treturn relative.replace(/\\\\/g, \"/\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn path.basename(filePath);\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst fileCache = new Map<string, string[]>();\n\t\t\t\t\t\tconst getFileLines = async (filePath: string): Promise<string[]> => {\n\t\t\t\t\t\t\tlet lines = fileCache.get(filePath);\n\t\t\t\t\t\t\tif (!lines) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tconst content = await ops.readFile(filePath);\n\t\t\t\t\t\t\t\t\tlines = content.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\").split(\"\\n\");\n\t\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t\tlines = [];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tfileCache.set(filePath, lines);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn lines;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst args: string[] = [\"--json\", \"--line-number\", \"--color=never\", \"--hidden\"];\n\t\t\t\t\t\tif (ignoreCase) args.push(\"--ignore-case\");\n\t\t\t\t\t\tif (literal) args.push(\"--fixed-strings\");\n\t\t\t\t\t\tif (glob) args.push(\"--glob\", glob);\n\t\t\t\t\t\targs.push(\"--\", pattern, searchPath);\n\n\t\t\t\t\t\tconst child = spawn(rgPath, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n\t\t\t\t\t\tconst rl = createInterface({ input: child.stdout });\n\t\t\t\t\t\tlet stderr = \"\";\n\t\t\t\t\t\tlet matchCount = 0;\n\t\t\t\t\t\tlet matchLimitReached = false;\n\t\t\t\t\t\tlet linesTruncated = false;\n\t\t\t\t\t\tlet aborted = false;\n\t\t\t\t\t\tlet killedDueToLimit = false;\n\t\t\t\t\t\tconst outputLines: string[] = [];\n\n\t\t\t\t\t\tconst cleanup = () => {\n\t\t\t\t\t\t\trl.close();\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst stopChild = (dueToLimit = false) => {\n\t\t\t\t\t\t\tif (!child.killed) {\n\t\t\t\t\t\t\t\tkilledDueToLimit = dueToLimit;\n\t\t\t\t\t\t\t\tchild.kill();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t\t\taborted = true;\n\t\t\t\t\t\t\tstopChild();\n\t\t\t\t\t\t};\n\t\t\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t\t\tchild.stderr?.on(\"data\", (chunk) => {\n\t\t\t\t\t\t\tstderr += chunk.toString();\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\t// Format a context block around a match line. Path is omitted (emitted once per file).\n\t\t\t\t\t\tconst formatBlock = async (filePath: string, lineNumber: number): Promise<string[]> => {\n\t\t\t\t\t\t\tconst lines = await getFileLines(filePath);\n\t\t\t\t\t\t\tif (!lines.length) return [` ${lineNumber}: (unable to read file)`];\n\t\t\t\t\t\t\tconst block: string[] = [];\n\t\t\t\t\t\t\tconst start = contextValue > 0 ? Math.max(1, lineNumber - contextValue) : lineNumber;\n\t\t\t\t\t\t\tconst end = contextValue > 0 ? Math.min(lines.length, lineNumber + contextValue) : lineNumber;\n\t\t\t\t\t\t\tfor (let current = start; current <= end; current++) {\n\t\t\t\t\t\t\t\tconst lineText = lines[current - 1] ?? \"\";\n\t\t\t\t\t\t\t\tconst sanitized = lineText.replace(/\\r/g, \"\");\n\t\t\t\t\t\t\t\tconst isMatchLine = current === lineNumber;\n\t\t\t\t\t\t\t\t// Truncate long lines so grep output stays compact.\n\t\t\t\t\t\t\t\tconst { text: truncatedText, wasTruncated } = truncateLine(sanitized);\n\t\t\t\t\t\t\t\tif (wasTruncated) linesTruncated = true;\n\t\t\t\t\t\t\t\tif (isMatchLine) block.push(`${current}: ${truncatedText}`);\n\t\t\t\t\t\t\t\telse block.push(`${current}- ${truncatedText}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn block;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t// Collect matches during streaming, then format them after rg exits.\n\t\t\t\t\t\tconst matches: Array<{ filePath: string; lineNumber: number; lineText?: string }> = [];\n\t\t\t\t\t\trl.on(\"line\", (line) => {\n\t\t\t\t\t\t\tif (!line.trim() || matchCount >= effectiveLimit) return;\n\t\t\t\t\t\t\tlet event: any;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tevent = JSON.parse(line);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (event.type === \"match\") {\n\t\t\t\t\t\t\t\tmatchCount++;\n\t\t\t\t\t\t\t\tconst filePath = event.data?.path?.text;\n\t\t\t\t\t\t\t\tconst lineNumber = event.data?.line_number;\n\t\t\t\t\t\t\t\tconst lineText = event.data?.lines?.text;\n\t\t\t\t\t\t\t\tif (filePath && typeof lineNumber === \"number\")\n\t\t\t\t\t\t\t\t\tmatches.push({ filePath, lineNumber, lineText });\n\t\t\t\t\t\t\t\tif (matchCount >= effectiveLimit) {\n\t\t\t\t\t\t\t\t\tmatchLimitReached = true;\n\t\t\t\t\t\t\t\t\tstopChild(true);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tchild.on(\"error\", (error) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Failed to run ripgrep: ${error.message}`)));\n\t\t\t\t\t\t});\n\t\t\t\t\t\tchild.on(\"close\", async (code) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tif (aborted) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!killedDueToLimit && code !== 0 && code !== 1) {\n\t\t\t\t\t\t\t\tconst errorMsg = stderr.trim() || `ripgrep exited with code ${code}`;\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(errorMsg)));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (matchCount === 0) {\n\t\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: \"No matches found\" }], details: undefined }),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Group matches by file path, showing filename once per file.\n\t\t\t\t\t\t\tconst fileGroups = new Map<string, typeof matches>();\n\t\t\t\t\t\t\tfor (const match of matches) {\n\t\t\t\t\t\t\t\tlet group = fileGroups.get(match.filePath);\n\t\t\t\t\t\t\t\tif (!group) {\n\t\t\t\t\t\t\t\t\tgroup = [];\n\t\t\t\t\t\t\t\t\tfileGroups.set(match.filePath, group);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tgroup.push(match);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfor (const [filePath, fileMatches] of fileGroups) {\n\t\t\t\t\t\t\t\tconst relativePath = formatPath(filePath);\n\t\t\t\t\t\t\t\toutputLines.push(relativePath);\n\t\t\t\t\t\t\t\tfor (const match of fileMatches) {\n\t\t\t\t\t\t\t\t\tif (contextValue === 0 && match.lineText !== undefined) {\n\t\t\t\t\t\t\t\t\t\tconst sanitized = match.lineText\n\t\t\t\t\t\t\t\t\t\t\t.replace(/\\r\\n/g, \"\\n\")\n\t\t\t\t\t\t\t\t\t\t\t.replace(/\\r/g, \"\")\n\t\t\t\t\t\t\t\t\t\t\t.replace(/\\n$/, \"\");\n\t\t\t\t\t\t\t\t\t\tconst { text: truncatedText, wasTruncated } = truncateLine(sanitized);\n\t\t\t\t\t\t\t\t\t\tif (wasTruncated) linesTruncated = true;\n\t\t\t\t\t\t\t\t\t\toutputLines.push(`${match.lineNumber}: ${truncatedText}`);\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tconst block = await formatBlock(match.filePath, match.lineNumber);\n\t\t\t\t\t\t\t\t\t\toutputLines.push(...block);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst rawOutput = outputLines.join(\"\\n\");\n\t\t\t\t\t\t\t// Apply lossless compression then byte truncation.\n\t\t\t\t\t\t\tconst compressedOutput = compressGrepOutput(rawOutput);\n\t\t\t\t\t\t\t// Apply byte truncation. There is no line limit here because the match limit already capped rows.\n\t\t\t\t\t\t\tconst truncation = truncateHead(compressedOutput, { maxLines: Number.MAX_SAFE_INTEGER });\n\t\t\t\t\t\t\tlet output = truncation.content;\n\t\t\t\t\t\t\tconst details: GrepToolDetails = {};\n\t\t\t\t\t\t\t// Build actionable notices for truncation and match limits.\n\t\t\t\t\t\t\tconst notices: string[] = [];\n\t\t\t\t\t\t\tif (matchLimitReached) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`${effectiveLimit} matches limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.matchLimitReached = effectiveLimit;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\t\t\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t\t\t\t\t\t\tdetails.truncation = truncation;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (linesTruncated) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`Some lines truncated to ${GREP_MAX_LINE_LENGTH} chars. Use read tool to see full lines`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.linesTruncated = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (notices.length > 0) output += `\\n\\n[${notices.join(\". \")}]`;\n\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: output }],\n\t\t\t\t\t\t\t\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tsettle(() => reject(err as Error));\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatGrepCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatGrepResult(result as any, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createGrepTool(cwd: string, options?: GrepToolOptions): AgentTool<typeof grepSchema> {\n\treturn wrapToolDefinition(createGrepToolDefinition(cwd, options));\n}\n"]}
1
+ {"version":3,"file":"grep.d.ts","sourceRoot":"","sources":["../../../src/core/tools/grep.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AAKjE,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAG5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAKtF,OAAO,EAIN,KAAK,gBAAgB,EAGrB,MAAM,eAAe,CAAC;AAEvB,QAAA,MAAM,UAAU;;;;;;;;EAYd,CAAC;AAEH,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAGtD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,cAAc,CAAC,EAAE,OAAO,CAAC;CACzB;AAED;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC9B,mEAAmE;IACnE,WAAW,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;IAClE,2CAA2C;IAC3C,QAAQ,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;CAC7D;AAOD,MAAM,WAAW,eAAe;IAC/B,yEAAyE;IACzE,UAAU,CAAC,EAAE,cAAc,CAAC;CAC5B;AAyDD,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC,CA0RhE;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAEnG","sourcesContent":["import { createInterface } from \"node:readline\";\nimport type { AgentTool } from \"@kolisachint/hoocode-agent-core\";\nimport { Text } from \"@kolisachint/hoocode-tui\";\nimport { spawn } from \"child_process\";\nimport { readFileSync, statSync } from \"fs\";\nimport path from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.js\";\nimport { ensureTool } from \"../../utils/tools-manager.js\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.js\";\nimport { compressGrepOutput } from \"./output-compression.js\";\nimport { resolveToCwd } from \"./path-utils.js\";\nimport { getTextOutput, invalidArgText, shortenPath, str } from \"./render-utils.js\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.js\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tformatSize,\n\tGREP_MAX_LINE_LENGTH,\n\ttype TruncationResult,\n\ttruncateHead,\n\ttruncateLine,\n} from \"./truncate.js\";\n\nconst grepSchema = Type.Object({\n\tpattern: Type.String({ description: \"Search pattern (regex or literal string)\" }),\n\tpath: Type.Optional(Type.String({ description: \"Directory or file to search (default: current directory)\" })),\n\tglob: Type.Optional(Type.String({ description: \"Filter files by glob pattern, e.g. '*.ts' or '**/*.spec.ts'\" })),\n\tignoreCase: Type.Optional(Type.Boolean({ description: \"Case-insensitive search (default: false)\" })),\n\tliteral: Type.Optional(\n\t\tType.Boolean({ description: \"Treat pattern as literal string instead of regex (default: false)\" }),\n\t),\n\tcontext: Type.Optional(\n\t\tType.Number({ description: \"Number of lines to show before and after each match (default: 0)\" }),\n\t),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of matches to return (default: 100)\" })),\n});\n\nexport type GrepToolInput = Static<typeof grepSchema>;\nconst DEFAULT_LIMIT = 100;\n\nexport interface GrepToolDetails {\n\ttruncation?: TruncationResult;\n\tmatchLimitReached?: number;\n\tlinesTruncated?: boolean;\n}\n\n/**\n * Pluggable operations for the grep tool.\n * Override these to delegate search to remote systems (for example SSH).\n */\nexport interface GrepOperations {\n\t/** Check if path is a directory. Throws if path does not exist. */\n\tisDirectory: (absolutePath: string) => Promise<boolean> | boolean;\n\t/** Read file contents for context lines */\n\treadFile: (absolutePath: string) => Promise<string> | string;\n}\n\nconst defaultGrepOperations: GrepOperations = {\n\tisDirectory: (p) => statSync(p).isDirectory(),\n\treadFile: (p) => readFileSync(p, \"utf-8\"),\n};\n\nexport interface GrepToolOptions {\n\t/** Custom operations for grep. Default: local filesystem plus ripgrep */\n\toperations?: GrepOperations;\n}\n\nfunction formatGrepCall(\n\targs: { pattern: string; path?: string; glob?: string; limit?: number } | undefined,\n\ttheme: typeof import(\"../../modes/interactive/theme/theme.js\").theme,\n): string {\n\tconst pattern = str(args?.pattern);\n\tconst rawPath = str(args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath || \".\") : null;\n\tconst glob = str(args?.glob);\n\tconst limit = args?.limit;\n\tconst invalidArg = invalidArgText(theme);\n\tlet text =\n\t\ttheme.fg(\"toolTitle\", theme.bold(\"grep\")) +\n\t\t\" \" +\n\t\t(pattern === null ? invalidArg : theme.fg(\"accent\", `/${pattern || \"\"}/`)) +\n\t\ttheme.fg(\"toolOutput\", ` in ${path === null ? invalidArg : path}`);\n\tif (glob) text += theme.fg(\"toolOutput\", ` (${glob})`);\n\tif (limit !== undefined) text += theme.fg(\"toolOutput\", ` limit ${limit}`);\n\treturn text;\n}\n\nfunction formatGrepResult(\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: GrepToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\ttheme: typeof import(\"../../modes/interactive/theme/theme.js\").theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 15;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")})`;\n\t\t}\n\t}\n\n\tconst matchLimit = result.details?.matchLimitReached;\n\tconst truncation = result.details?.truncation;\n\tconst linesTruncated = result.details?.linesTruncated;\n\tif (matchLimit || truncation?.truncated || linesTruncated) {\n\t\tconst warnings: string[] = [];\n\t\tif (matchLimit) warnings.push(`${matchLimit} matches limit`);\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\tif (linesTruncated) warnings.push(\"some lines truncated\");\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\n\nexport function createGrepToolDefinition(\n\tcwd: string,\n\toptions?: GrepToolOptions,\n): ToolDefinition<typeof grepSchema, GrepToolDetails | undefined> {\n\tconst customOps = options?.operations;\n\treturn {\n\t\tname: \"grep\",\n\t\tlabel: \"grep\",\n\t\tdescription: `Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to ${DEFAULT_LIMIT} matches or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Long lines are truncated to ${GREP_MAX_LINE_LENGTH} chars.`,\n\t\tpromptSnippet: \"Search file contents for patterns (respects .gitignore)\",\n\t\tparameters: grepSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{\n\t\t\t\tpattern,\n\t\t\t\tpath: searchDir,\n\t\t\t\tglob,\n\t\t\t\tignoreCase,\n\t\t\t\tliteral,\n\t\t\t\tcontext,\n\t\t\t\tlimit,\n\t\t\t}: {\n\t\t\t\tpattern: string;\n\t\t\t\tpath?: string;\n\t\t\t\tglob?: string;\n\t\t\t\tignoreCase?: boolean;\n\t\t\t\tliteral?: boolean;\n\t\t\t\tcontext?: number;\n\t\t\t\tlimit?: number;\n\t\t\t},\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet settled = false;\n\t\t\t\tconst settle = (fn: () => void) => {\n\t\t\t\t\tif (!settled) {\n\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\tfn();\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst rgPath = await ensureTool(\"rg\", true);\n\t\t\t\t\t\tif (!rgPath) {\n\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\treject(\n\t\t\t\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t\t\t\t\"ripgrep (rg) unavailable and could not be downloaded — use the bash tool to run grep/rg instead\",\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst searchPath = resolveToCwd(searchDir || \".\", cwd);\n\t\t\t\t\t\tconst ops = customOps ?? defaultGrepOperations;\n\t\t\t\t\t\tlet isDirectory: boolean;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tisDirectory = await ops.isDirectory(searchPath);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Path not found: ${searchPath}`)));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst contextValue = context && context > 0 ? context : 0;\n\t\t\t\t\t\tconst effectiveLimit = Math.max(1, limit ?? DEFAULT_LIMIT);\n\t\t\t\t\t\tconst formatPath = (filePath: string): string => {\n\t\t\t\t\t\t\tif (isDirectory) {\n\t\t\t\t\t\t\t\tconst relative = path.relative(searchPath, filePath);\n\t\t\t\t\t\t\t\tif (relative && !relative.startsWith(\"..\")) {\n\t\t\t\t\t\t\t\t\treturn relative.replace(/\\\\/g, \"/\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn path.basename(filePath);\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst fileCache = new Map<string, string[]>();\n\t\t\t\t\t\tconst getFileLines = async (filePath: string): Promise<string[]> => {\n\t\t\t\t\t\t\tlet lines = fileCache.get(filePath);\n\t\t\t\t\t\t\tif (!lines) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tconst content = await ops.readFile(filePath);\n\t\t\t\t\t\t\t\t\tlines = content.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\").split(\"\\n\");\n\t\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t\tlines = [];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tfileCache.set(filePath, lines);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn lines;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst args: string[] = [\"--json\", \"--line-number\", \"--color=never\", \"--hidden\"];\n\t\t\t\t\t\tif (ignoreCase) args.push(\"--ignore-case\");\n\t\t\t\t\t\tif (literal) args.push(\"--fixed-strings\");\n\t\t\t\t\t\tif (glob) args.push(\"--glob\", glob);\n\t\t\t\t\t\targs.push(\"--\", pattern, searchPath);\n\n\t\t\t\t\t\tconst child = spawn(rgPath, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n\t\t\t\t\t\tconst rl = createInterface({ input: child.stdout });\n\t\t\t\t\t\tlet stderr = \"\";\n\t\t\t\t\t\tlet matchCount = 0;\n\t\t\t\t\t\tlet matchLimitReached = false;\n\t\t\t\t\t\tlet linesTruncated = false;\n\t\t\t\t\t\tlet aborted = false;\n\t\t\t\t\t\tlet killedDueToLimit = false;\n\t\t\t\t\t\tconst outputLines: string[] = [];\n\n\t\t\t\t\t\tconst cleanup = () => {\n\t\t\t\t\t\t\trl.close();\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst stopChild = (dueToLimit = false) => {\n\t\t\t\t\t\t\tif (!child.killed) {\n\t\t\t\t\t\t\t\tkilledDueToLimit = dueToLimit;\n\t\t\t\t\t\t\t\tchild.kill();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t\t\taborted = true;\n\t\t\t\t\t\t\tstopChild();\n\t\t\t\t\t\t};\n\t\t\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t\t\tchild.stderr?.on(\"data\", (chunk) => {\n\t\t\t\t\t\t\tstderr += chunk.toString();\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\t// Format a context block around a match line. Path is omitted (emitted once per file).\n\t\t\t\t\t\tconst formatBlock = async (filePath: string, lineNumber: number): Promise<string[]> => {\n\t\t\t\t\t\t\tconst lines = await getFileLines(filePath);\n\t\t\t\t\t\t\tif (!lines.length) return [` ${lineNumber}: (unable to read file)`];\n\t\t\t\t\t\t\tconst block: string[] = [];\n\t\t\t\t\t\t\tconst start = contextValue > 0 ? Math.max(1, lineNumber - contextValue) : lineNumber;\n\t\t\t\t\t\t\tconst end = contextValue > 0 ? Math.min(lines.length, lineNumber + contextValue) : lineNumber;\n\t\t\t\t\t\t\tfor (let current = start; current <= end; current++) {\n\t\t\t\t\t\t\t\tconst lineText = lines[current - 1] ?? \"\";\n\t\t\t\t\t\t\t\tconst sanitized = lineText.replace(/\\r/g, \"\");\n\t\t\t\t\t\t\t\tconst isMatchLine = current === lineNumber;\n\t\t\t\t\t\t\t\t// Truncate long lines so grep output stays compact.\n\t\t\t\t\t\t\t\tconst { text: truncatedText, wasTruncated } = truncateLine(sanitized);\n\t\t\t\t\t\t\t\tif (wasTruncated) linesTruncated = true;\n\t\t\t\t\t\t\t\tif (isMatchLine) block.push(`${current}: ${truncatedText}`);\n\t\t\t\t\t\t\t\telse block.push(`${current}- ${truncatedText}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn block;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t// Collect matches during streaming, then format them after rg exits.\n\t\t\t\t\t\tconst matches: Array<{ filePath: string; lineNumber: number; lineText?: string }> = [];\n\t\t\t\t\t\trl.on(\"line\", (line) => {\n\t\t\t\t\t\t\tif (!line.trim() || matchCount >= effectiveLimit) return;\n\t\t\t\t\t\t\tlet event: any;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tevent = JSON.parse(line);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (event.type === \"match\") {\n\t\t\t\t\t\t\t\tmatchCount++;\n\t\t\t\t\t\t\t\tconst filePath = event.data?.path?.text;\n\t\t\t\t\t\t\t\tconst lineNumber = event.data?.line_number;\n\t\t\t\t\t\t\t\tconst lineText = event.data?.lines?.text;\n\t\t\t\t\t\t\t\tif (filePath && typeof lineNumber === \"number\")\n\t\t\t\t\t\t\t\t\tmatches.push({ filePath, lineNumber, lineText });\n\t\t\t\t\t\t\t\tif (matchCount >= effectiveLimit) {\n\t\t\t\t\t\t\t\t\tmatchLimitReached = true;\n\t\t\t\t\t\t\t\t\tstopChild(true);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tchild.on(\"error\", (error) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Failed to run ripgrep: ${error.message}`)));\n\t\t\t\t\t\t});\n\t\t\t\t\t\tchild.on(\"close\", async (code) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tif (aborted) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!killedDueToLimit && code !== 0 && code !== 1) {\n\t\t\t\t\t\t\t\tconst trimmedStderr = stderr.trim();\n\t\t\t\t\t\t\t\tlet errorMsg = trimmedStderr || `ripgrep exited with code ${code}`;\n\t\t\t\t\t\t\t\t// A regex parse error means the pattern is not a valid regex. Point the\n\t\t\t\t\t\t\t\t// caller at the `literal` option so they can search the text verbatim.\n\t\t\t\t\t\t\t\tif (!literal && /regex parse error/i.test(trimmedStderr)) {\n\t\t\t\t\t\t\t\t\terrorMsg += `\\n\\nThe pattern is not a valid regex. To search for it as plain text, pass literal: true (or escape the regex metacharacters).`;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(errorMsg)));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (matchCount === 0) {\n\t\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: \"No matches found\" }], details: undefined }),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Group matches by file path, showing filename once per file.\n\t\t\t\t\t\t\tconst fileGroups = new Map<string, typeof matches>();\n\t\t\t\t\t\t\tfor (const match of matches) {\n\t\t\t\t\t\t\t\tlet group = fileGroups.get(match.filePath);\n\t\t\t\t\t\t\t\tif (!group) {\n\t\t\t\t\t\t\t\t\tgroup = [];\n\t\t\t\t\t\t\t\t\tfileGroups.set(match.filePath, group);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tgroup.push(match);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfor (const [filePath, fileMatches] of fileGroups) {\n\t\t\t\t\t\t\t\tconst relativePath = formatPath(filePath);\n\t\t\t\t\t\t\t\toutputLines.push(relativePath);\n\t\t\t\t\t\t\t\tfor (const match of fileMatches) {\n\t\t\t\t\t\t\t\t\tif (contextValue === 0 && match.lineText !== undefined) {\n\t\t\t\t\t\t\t\t\t\tconst sanitized = match.lineText\n\t\t\t\t\t\t\t\t\t\t\t.replace(/\\r\\n/g, \"\\n\")\n\t\t\t\t\t\t\t\t\t\t\t.replace(/\\r/g, \"\")\n\t\t\t\t\t\t\t\t\t\t\t.replace(/\\n$/, \"\");\n\t\t\t\t\t\t\t\t\t\tconst { text: truncatedText, wasTruncated } = truncateLine(sanitized);\n\t\t\t\t\t\t\t\t\t\tif (wasTruncated) linesTruncated = true;\n\t\t\t\t\t\t\t\t\t\toutputLines.push(`${match.lineNumber}: ${truncatedText}`);\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tconst block = await formatBlock(match.filePath, match.lineNumber);\n\t\t\t\t\t\t\t\t\t\toutputLines.push(...block);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst rawOutput = outputLines.join(\"\\n\");\n\t\t\t\t\t\t\t// Apply lossless compression then byte truncation.\n\t\t\t\t\t\t\tconst compressedOutput = compressGrepOutput(rawOutput);\n\t\t\t\t\t\t\t// Apply byte truncation. There is no line limit here because the match limit already capped rows.\n\t\t\t\t\t\t\tconst truncation = truncateHead(compressedOutput, { maxLines: Number.MAX_SAFE_INTEGER });\n\t\t\t\t\t\t\tlet output = truncation.content;\n\t\t\t\t\t\t\tconst details: GrepToolDetails = {};\n\t\t\t\t\t\t\t// Build actionable notices for truncation and match limits.\n\t\t\t\t\t\t\tconst notices: string[] = [];\n\t\t\t\t\t\t\tif (matchLimitReached) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`${effectiveLimit} matches limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.matchLimitReached = effectiveLimit;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\t\t\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t\t\t\t\t\t\tdetails.truncation = truncation;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (linesTruncated) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`Some lines truncated to ${GREP_MAX_LINE_LENGTH} chars. Use read tool to see full lines`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.linesTruncated = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (notices.length > 0) output += `\\n\\n[${notices.join(\". \")}]`;\n\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: output }],\n\t\t\t\t\t\t\t\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tsettle(() => reject(err as Error));\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatGrepCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatGrepResult(result as any, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createGrepTool(cwd: string, options?: GrepToolOptions): AgentTool<typeof grepSchema> {\n\treturn wrapToolDefinition(createGrepToolDefinition(cwd, options));\n}\n"]}
@@ -228,7 +228,13 @@ export function createGrepToolDefinition(cwd, options) {
228
228
  return;
229
229
  }
230
230
  if (!killedDueToLimit && code !== 0 && code !== 1) {
231
- const errorMsg = stderr.trim() || `ripgrep exited with code ${code}`;
231
+ const trimmedStderr = stderr.trim();
232
+ let errorMsg = trimmedStderr || `ripgrep exited with code ${code}`;
233
+ // A regex parse error means the pattern is not a valid regex. Point the
234
+ // caller at the `literal` option so they can search the text verbatim.
235
+ if (!literal && /regex parse error/i.test(trimmedStderr)) {
236
+ errorMsg += `\n\nThe pattern is not a valid regex. To search for it as plain text, pass literal: true (or escape the regex metacharacters).`;
237
+ }
232
238
  settle(() => reject(new Error(errorMsg)));
233
239
  return;
234
240
  }
@@ -1 +1 @@
1
- {"version":3,"file":"grep.js","sourceRoot":"","sources":["../../../src/core/tools/grep.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAEhD,OAAO,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AAC5C,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AACjF,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAE1D,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACpF,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EACN,iBAAiB,EACjB,UAAU,EACV,oBAAoB,EAEpB,YAAY,EACZ,YAAY,GACZ,MAAM,eAAe,CAAC;AAEvB,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC;IAC9B,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,0CAA0C,EAAE,CAAC;IACjF,IAAI,EAAE,IAAI,CAAC,QAAQ,CA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AC7C,MAAM,IAAI,GAAI,OAAO,CAAC,aAAkC,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/E,IAAI,CAAC,OAAO,CAAC,gBAAgB,CAAC,MAAa,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC;YAClF,OAAO,IAAI,CAAC;QAAA,CACZ;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB,EAAgC;IACpG,OAAO,kBAAkB,CAAC,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CAClE","sourcesContent":["import { createInterface } from \"node:readline\";\nimport type { AgentTool } from \"@kolisachint/hoocode-agent-core\";\nimport { Text } from \"@kolisachint/hoocode-tui\";\nimport { spawn } from \"child_process\";\nimport { readFileSync, statSync } from \"fs\";\nimport path from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.js\";\nimport { ensureTool } from \"../../utils/tools-manager.js\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.js\";\nimport { compressGrepOutput } from \"./output-compression.js\";\nimport { resolveToCwd } from \"./path-utils.js\";\nimport { getTextOutput, invalidArgText, shortenPath, str } from \"./render-utils.js\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.js\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tformatSize,\n\tGREP_MAX_LINE_LENGTH,\n\ttype TruncationResult,\n\ttruncateHead,\n\ttruncateLine,\n} from \"./truncate.js\";\n\nconst grepSchema = Type.Object({\n\tpattern: Type.String({ description: \"Search pattern (regex or literal string)\" }),\n\tpath: Type.Optional(Type.String({ description: \"Directory or file to search (default: current directory)\" })),\n\tglob: Type.Optional(Type.String({ description: \"Filter files by glob pattern, e.g. '*.ts' or '**/*.spec.ts'\" })),\n\tignoreCase: Type.Optional(Type.Boolean({ description: \"Case-insensitive search (default: false)\" })),\n\tliteral: Type.Optional(\n\t\tType.Boolean({ description: \"Treat pattern as literal string instead of regex (default: false)\" }),\n\t),\n\tcontext: Type.Optional(\n\t\tType.Number({ description: \"Number of lines to show before and after each match (default: 0)\" }),\n\t),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of matches to return (default: 100)\" })),\n});\n\nexport type GrepToolInput = Static<typeof grepSchema>;\nconst DEFAULT_LIMIT = 100;\n\nexport interface GrepToolDetails {\n\ttruncation?: TruncationResult;\n\tmatchLimitReached?: number;\n\tlinesTruncated?: boolean;\n}\n\n/**\n * Pluggable operations for the grep tool.\n * Override these to delegate search to remote systems (for example SSH).\n */\nexport interface GrepOperations {\n\t/** Check if path is a directory. Throws if path does not exist. */\n\tisDirectory: (absolutePath: string) => Promise<boolean> | boolean;\n\t/** Read file contents for context lines */\n\treadFile: (absolutePath: string) => Promise<string> | string;\n}\n\nconst defaultGrepOperations: GrepOperations = {\n\tisDirectory: (p) => statSync(p).isDirectory(),\n\treadFile: (p) => readFileSync(p, \"utf-8\"),\n};\n\nexport interface GrepToolOptions {\n\t/** Custom operations for grep. Default: local filesystem plus ripgrep */\n\toperations?: GrepOperations;\n}\n\nfunction formatGrepCall(\n\targs: { pattern: string; path?: string; glob?: string; limit?: number } | undefined,\n\ttheme: typeof import(\"../../modes/interactive/theme/theme.js\").theme,\n): string {\n\tconst pattern = str(args?.pattern);\n\tconst rawPath = str(args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath || \".\") : null;\n\tconst glob = str(args?.glob);\n\tconst limit = args?.limit;\n\tconst invalidArg = invalidArgText(theme);\n\tlet text =\n\t\ttheme.fg(\"toolTitle\", theme.bold(\"grep\")) +\n\t\t\" \" +\n\t\t(pattern === null ? invalidArg : theme.fg(\"accent\", `/${pattern || \"\"}/`)) +\n\t\ttheme.fg(\"toolOutput\", ` in ${path === null ? invalidArg : path}`);\n\tif (glob) text += theme.fg(\"toolOutput\", ` (${glob})`);\n\tif (limit !== undefined) text += theme.fg(\"toolOutput\", ` limit ${limit}`);\n\treturn text;\n}\n\nfunction formatGrepResult(\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: GrepToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\ttheme: typeof import(\"../../modes/interactive/theme/theme.js\").theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 15;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")})`;\n\t\t}\n\t}\n\n\tconst matchLimit = result.details?.matchLimitReached;\n\tconst truncation = result.details?.truncation;\n\tconst linesTruncated = result.details?.linesTruncated;\n\tif (matchLimit || truncation?.truncated || linesTruncated) {\n\t\tconst warnings: string[] = [];\n\t\tif (matchLimit) warnings.push(`${matchLimit} matches limit`);\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\tif (linesTruncated) warnings.push(\"some lines truncated\");\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\n\nexport function createGrepToolDefinition(\n\tcwd: string,\n\toptions?: GrepToolOptions,\n): ToolDefinition<typeof grepSchema, GrepToolDetails | undefined> {\n\tconst customOps = options?.operations;\n\treturn {\n\t\tname: \"grep\",\n\t\tlabel: \"grep\",\n\t\tdescription: `Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to ${DEFAULT_LIMIT} matches or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Long lines are truncated to ${GREP_MAX_LINE_LENGTH} chars.`,\n\t\tpromptSnippet: \"Search file contents for patterns (respects .gitignore)\",\n\t\tparameters: grepSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{\n\t\t\t\tpattern,\n\t\t\t\tpath: searchDir,\n\t\t\t\tglob,\n\t\t\t\tignoreCase,\n\t\t\t\tliteral,\n\t\t\t\tcontext,\n\t\t\t\tlimit,\n\t\t\t}: {\n\t\t\t\tpattern: string;\n\t\t\t\tpath?: string;\n\t\t\t\tglob?: string;\n\t\t\t\tignoreCase?: boolean;\n\t\t\t\tliteral?: boolean;\n\t\t\t\tcontext?: number;\n\t\t\t\tlimit?: number;\n\t\t\t},\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet settled = false;\n\t\t\t\tconst settle = (fn: () => void) => {\n\t\t\t\t\tif (!settled) {\n\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\tfn();\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst rgPath = await ensureTool(\"rg\", true);\n\t\t\t\t\t\tif (!rgPath) {\n\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\treject(\n\t\t\t\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t\t\t\t\"ripgrep (rg) unavailable and could not be downloaded — use the bash tool to run grep/rg instead\",\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst searchPath = resolveToCwd(searchDir || \".\", cwd);\n\t\t\t\t\t\tconst ops = customOps ?? defaultGrepOperations;\n\t\t\t\t\t\tlet isDirectory: boolean;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tisDirectory = await ops.isDirectory(searchPath);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Path not found: ${searchPath}`)));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst contextValue = context && context > 0 ? context : 0;\n\t\t\t\t\t\tconst effectiveLimit = Math.max(1, limit ?? DEFAULT_LIMIT);\n\t\t\t\t\t\tconst formatPath = (filePath: string): string => {\n\t\t\t\t\t\t\tif (isDirectory) {\n\t\t\t\t\t\t\t\tconst relative = path.relative(searchPath, filePath);\n\t\t\t\t\t\t\t\tif (relative && !relative.startsWith(\"..\")) {\n\t\t\t\t\t\t\t\t\treturn relative.replace(/\\\\/g, \"/\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn path.basename(filePath);\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst fileCache = new Map<string, string[]>();\n\t\t\t\t\t\tconst getFileLines = async (filePath: string): Promise<string[]> => {\n\t\t\t\t\t\t\tlet lines = fileCache.get(filePath);\n\t\t\t\t\t\t\tif (!lines) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tconst content = await ops.readFile(filePath);\n\t\t\t\t\t\t\t\t\tlines = content.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\").split(\"\\n\");\n\t\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t\tlines = [];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tfileCache.set(filePath, lines);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn lines;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst args: string[] = [\"--json\", \"--line-number\", \"--color=never\", \"--hidden\"];\n\t\t\t\t\t\tif (ignoreCase) args.push(\"--ignore-case\");\n\t\t\t\t\t\tif (literal) args.push(\"--fixed-strings\");\n\t\t\t\t\t\tif (glob) args.push(\"--glob\", glob);\n\t\t\t\t\t\targs.push(\"--\", pattern, searchPath);\n\n\t\t\t\t\t\tconst child = spawn(rgPath, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n\t\t\t\t\t\tconst rl = createInterface({ input: child.stdout });\n\t\t\t\t\t\tlet stderr = \"\";\n\t\t\t\t\t\tlet matchCount = 0;\n\t\t\t\t\t\tlet matchLimitReached = false;\n\t\t\t\t\t\tlet linesTruncated = false;\n\t\t\t\t\t\tlet aborted = false;\n\t\t\t\t\t\tlet killedDueToLimit = false;\n\t\t\t\t\t\tconst outputLines: string[] = [];\n\n\t\t\t\t\t\tconst cleanup = () => {\n\t\t\t\t\t\t\trl.close();\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst stopChild = (dueToLimit = false) => {\n\t\t\t\t\t\t\tif (!child.killed) {\n\t\t\t\t\t\t\t\tkilledDueToLimit = dueToLimit;\n\t\t\t\t\t\t\t\tchild.kill();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t\t\taborted = true;\n\t\t\t\t\t\t\tstopChild();\n\t\t\t\t\t\t};\n\t\t\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t\t\tchild.stderr?.on(\"data\", (chunk) => {\n\t\t\t\t\t\t\tstderr += chunk.toString();\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\t// Format a context block around a match line. Path is omitted (emitted once per file).\n\t\t\t\t\t\tconst formatBlock = async (filePath: string, lineNumber: number): Promise<string[]> => {\n\t\t\t\t\t\t\tconst lines = await getFileLines(filePath);\n\t\t\t\t\t\t\tif (!lines.length) return [` ${lineNumber}: (unable to read file)`];\n\t\t\t\t\t\t\tconst block: string[] = [];\n\t\t\t\t\t\t\tconst start = contextValue > 0 ? Math.max(1, lineNumber - contextValue) : lineNumber;\n\t\t\t\t\t\t\tconst end = contextValue > 0 ? Math.min(lines.length, lineNumber + contextValue) : lineNumber;\n\t\t\t\t\t\t\tfor (let current = start; current <= end; current++) {\n\t\t\t\t\t\t\t\tconst lineText = lines[current - 1] ?? \"\";\n\t\t\t\t\t\t\t\tconst sanitized = lineText.replace(/\\r/g, \"\");\n\t\t\t\t\t\t\t\tconst isMatchLine = current === lineNumber;\n\t\t\t\t\t\t\t\t// Truncate long lines so grep output stays compact.\n\t\t\t\t\t\t\t\tconst { text: truncatedText, wasTruncated } = truncateLine(sanitized);\n\t\t\t\t\t\t\t\tif (wasTruncated) linesTruncated = true;\n\t\t\t\t\t\t\t\tif (isMatchLine) block.push(`${current}: ${truncatedText}`);\n\t\t\t\t\t\t\t\telse block.push(`${current}- ${truncatedText}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn block;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t// Collect matches during streaming, then format them after rg exits.\n\t\t\t\t\t\tconst matches: Array<{ filePath: string; lineNumber: number; lineText?: string }> = [];\n\t\t\t\t\t\trl.on(\"line\", (line) => {\n\t\t\t\t\t\t\tif (!line.trim() || matchCount >= effectiveLimit) return;\n\t\t\t\t\t\t\tlet event: any;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tevent = JSON.parse(line);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (event.type === \"match\") {\n\t\t\t\t\t\t\t\tmatchCount++;\n\t\t\t\t\t\t\t\tconst filePath = event.data?.path?.text;\n\t\t\t\t\t\t\t\tconst lineNumber = event.data?.line_number;\n\t\t\t\t\t\t\t\tconst lineText = event.data?.lines?.text;\n\t\t\t\t\t\t\t\tif (filePath && typeof lineNumber === \"number\")\n\t\t\t\t\t\t\t\t\tmatches.push({ filePath, lineNumber, lineText });\n\t\t\t\t\t\t\t\tif (matchCount >= effectiveLimit) {\n\t\t\t\t\t\t\t\t\tmatchLimitReached = true;\n\t\t\t\t\t\t\t\t\tstopChild(true);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tchild.on(\"error\", (error) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Failed to run ripgrep: ${error.message}`)));\n\t\t\t\t\t\t});\n\t\t\t\t\t\tchild.on(\"close\", async (code) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tif (aborted) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!killedDueToLimit && code !== 0 && code !== 1) {\n\t\t\t\t\t\t\t\tconst errorMsg = stderr.trim() || `ripgrep exited with code ${code}`;\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(errorMsg)));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (matchCount === 0) {\n\t\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: \"No matches found\" }], details: undefined }),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Group matches by file path, showing filename once per file.\n\t\t\t\t\t\t\tconst fileGroups = new Map<string, typeof matches>();\n\t\t\t\t\t\t\tfor (const match of matches) {\n\t\t\t\t\t\t\t\tlet group = fileGroups.get(match.filePath);\n\t\t\t\t\t\t\t\tif (!group) {\n\t\t\t\t\t\t\t\t\tgroup = [];\n\t\t\t\t\t\t\t\t\tfileGroups.set(match.filePath, group);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tgroup.push(match);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfor (const [filePath, fileMatches] of fileGroups) {\n\t\t\t\t\t\t\t\tconst relativePath = formatPath(filePath);\n\t\t\t\t\t\t\t\toutputLines.push(relativePath);\n\t\t\t\t\t\t\t\tfor (const match of fileMatches) {\n\t\t\t\t\t\t\t\t\tif (contextValue === 0 && match.lineText !== undefined) {\n\t\t\t\t\t\t\t\t\t\tconst sanitized = match.lineText\n\t\t\t\t\t\t\t\t\t\t\t.replace(/\\r\\n/g, \"\\n\")\n\t\t\t\t\t\t\t\t\t\t\t.replace(/\\r/g, \"\")\n\t\t\t\t\t\t\t\t\t\t\t.replace(/\\n$/, \"\");\n\t\t\t\t\t\t\t\t\t\tconst { text: truncatedText, wasTruncated } = truncateLine(sanitized);\n\t\t\t\t\t\t\t\t\t\tif (wasTruncated) linesTruncated = true;\n\t\t\t\t\t\t\t\t\t\toutputLines.push(`${match.lineNumber}: ${truncatedText}`);\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tconst block = await formatBlock(match.filePath, match.lineNumber);\n\t\t\t\t\t\t\t\t\t\toutputLines.push(...block);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst rawOutput = outputLines.join(\"\\n\");\n\t\t\t\t\t\t\t// Apply lossless compression then byte truncation.\n\t\t\t\t\t\t\tconst compressedOutput = compressGrepOutput(rawOutput);\n\t\t\t\t\t\t\t// Apply byte truncation. There is no line limit here because the match limit already capped rows.\n\t\t\t\t\t\t\tconst truncation = truncateHead(compressedOutput, { maxLines: Number.MAX_SAFE_INTEGER });\n\t\t\t\t\t\t\tlet output = truncation.content;\n\t\t\t\t\t\t\tconst details: GrepToolDetails = {};\n\t\t\t\t\t\t\t// Build actionable notices for truncation and match limits.\n\t\t\t\t\t\t\tconst notices: string[] = [];\n\t\t\t\t\t\t\tif (matchLimitReached) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`${effectiveLimit} matches limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.matchLimitReached = effectiveLimit;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\t\t\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t\t\t\t\t\t\tdetails.truncation = truncation;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (linesTruncated) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`Some lines truncated to ${GREP_MAX_LINE_LENGTH} chars. Use read tool to see full lines`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.linesTruncated = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (notices.length > 0) output += `\\n\\n[${notices.join(\". \")}]`;\n\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: output }],\n\t\t\t\t\t\t\t\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tsettle(() => reject(err as Error));\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatGrepCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatGrepResult(result as any, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createGrepTool(cwd: string, options?: GrepToolOptions): AgentTool<typeof grepSchema> {\n\treturn wrapToolDefinition(createGrepToolDefinition(cwd, options));\n}\n"]}
1
+ {"version":3,"file":"grep.js","sourceRoot":"","sources":["../../../src/core/tools/grep.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAEhD,OAAO,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AAC5C,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AACjF,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAE1D,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACpF,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EACN,iBAAiB,EACjB,UAAU,EACV,oBAAoB,EAEpB,YAAY,EACZ,YAAY,GACZ,MAAM,eAAe,CAAC;AAEvB,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC;IAC9B,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,0CAA0C,EAAE,CAAC;IACjF,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,0DAA0D,EAAE,CAAC,CAAC;IAC7G,IAAI,EAAE,IAAI,CAAC,QAAQ,C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AI,CAAC;QAAA,CACZ;QACD,YAAY,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE;YAC7C,MAAM,IAAI,GAAI,OAAO,CAAC,aAAkC,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/E,IAAI,CAAC,OAAO,CAAC,gBAAgB,CAAC,MAAa,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC;YAClF,OAAO,IAAI,CAAC;QAAA,CACZ;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB,EAAgC;IACpG,OAAO,kBAAkB,CAAC,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CAClE","sourcesContent":["import { createInterface } from \"node:readline\";\nimport type { AgentTool } from \"@kolisachint/hoocode-agent-core\";\nimport { Text } from \"@kolisachint/hoocode-tui\";\nimport { spawn } from \"child_process\";\nimport { readFileSync, statSync } from \"fs\";\nimport path from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.js\";\nimport { ensureTool } from \"../../utils/tools-manager.js\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.js\";\nimport { compressGrepOutput } from \"./output-compression.js\";\nimport { resolveToCwd } from \"./path-utils.js\";\nimport { getTextOutput, invalidArgText, shortenPath, str } from \"./render-utils.js\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.js\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tformatSize,\n\tGREP_MAX_LINE_LENGTH,\n\ttype TruncationResult,\n\ttruncateHead,\n\ttruncateLine,\n} from \"./truncate.js\";\n\nconst grepSchema = Type.Object({\n\tpattern: Type.String({ description: \"Search pattern (regex or literal string)\" }),\n\tpath: Type.Optional(Type.String({ description: \"Directory or file to search (default: current directory)\" })),\n\tglob: Type.Optional(Type.String({ description: \"Filter files by glob pattern, e.g. '*.ts' or '**/*.spec.ts'\" })),\n\tignoreCase: Type.Optional(Type.Boolean({ description: \"Case-insensitive search (default: false)\" })),\n\tliteral: Type.Optional(\n\t\tType.Boolean({ description: \"Treat pattern as literal string instead of regex (default: false)\" }),\n\t),\n\tcontext: Type.Optional(\n\t\tType.Number({ description: \"Number of lines to show before and after each match (default: 0)\" }),\n\t),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of matches to return (default: 100)\" })),\n});\n\nexport type GrepToolInput = Static<typeof grepSchema>;\nconst DEFAULT_LIMIT = 100;\n\nexport interface GrepToolDetails {\n\ttruncation?: TruncationResult;\n\tmatchLimitReached?: number;\n\tlinesTruncated?: boolean;\n}\n\n/**\n * Pluggable operations for the grep tool.\n * Override these to delegate search to remote systems (for example SSH).\n */\nexport interface GrepOperations {\n\t/** Check if path is a directory. Throws if path does not exist. */\n\tisDirectory: (absolutePath: string) => Promise<boolean> | boolean;\n\t/** Read file contents for context lines */\n\treadFile: (absolutePath: string) => Promise<string> | string;\n}\n\nconst defaultGrepOperations: GrepOperations = {\n\tisDirectory: (p) => statSync(p).isDirectory(),\n\treadFile: (p) => readFileSync(p, \"utf-8\"),\n};\n\nexport interface GrepToolOptions {\n\t/** Custom operations for grep. Default: local filesystem plus ripgrep */\n\toperations?: GrepOperations;\n}\n\nfunction formatGrepCall(\n\targs: { pattern: string; path?: string; glob?: string; limit?: number } | undefined,\n\ttheme: typeof import(\"../../modes/interactive/theme/theme.js\").theme,\n): string {\n\tconst pattern = str(args?.pattern);\n\tconst rawPath = str(args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath || \".\") : null;\n\tconst glob = str(args?.glob);\n\tconst limit = args?.limit;\n\tconst invalidArg = invalidArgText(theme);\n\tlet text =\n\t\ttheme.fg(\"toolTitle\", theme.bold(\"grep\")) +\n\t\t\" \" +\n\t\t(pattern === null ? invalidArg : theme.fg(\"accent\", `/${pattern || \"\"}/`)) +\n\t\ttheme.fg(\"toolOutput\", ` in ${path === null ? invalidArg : path}`);\n\tif (glob) text += theme.fg(\"toolOutput\", ` (${glob})`);\n\tif (limit !== undefined) text += theme.fg(\"toolOutput\", ` limit ${limit}`);\n\treturn text;\n}\n\nfunction formatGrepResult(\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: GrepToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\ttheme: typeof import(\"../../modes/interactive/theme/theme.js\").theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 15;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")})`;\n\t\t}\n\t}\n\n\tconst matchLimit = result.details?.matchLimitReached;\n\tconst truncation = result.details?.truncation;\n\tconst linesTruncated = result.details?.linesTruncated;\n\tif (matchLimit || truncation?.truncated || linesTruncated) {\n\t\tconst warnings: string[] = [];\n\t\tif (matchLimit) warnings.push(`${matchLimit} matches limit`);\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\tif (linesTruncated) warnings.push(\"some lines truncated\");\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\n\nexport function createGrepToolDefinition(\n\tcwd: string,\n\toptions?: GrepToolOptions,\n): ToolDefinition<typeof grepSchema, GrepToolDetails | undefined> {\n\tconst customOps = options?.operations;\n\treturn {\n\t\tname: \"grep\",\n\t\tlabel: \"grep\",\n\t\tdescription: `Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to ${DEFAULT_LIMIT} matches or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Long lines are truncated to ${GREP_MAX_LINE_LENGTH} chars.`,\n\t\tpromptSnippet: \"Search file contents for patterns (respects .gitignore)\",\n\t\tparameters: grepSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{\n\t\t\t\tpattern,\n\t\t\t\tpath: searchDir,\n\t\t\t\tglob,\n\t\t\t\tignoreCase,\n\t\t\t\tliteral,\n\t\t\t\tcontext,\n\t\t\t\tlimit,\n\t\t\t}: {\n\t\t\t\tpattern: string;\n\t\t\t\tpath?: string;\n\t\t\t\tglob?: string;\n\t\t\t\tignoreCase?: boolean;\n\t\t\t\tliteral?: boolean;\n\t\t\t\tcontext?: number;\n\t\t\t\tlimit?: number;\n\t\t\t},\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet settled = false;\n\t\t\t\tconst settle = (fn: () => void) => {\n\t\t\t\t\tif (!settled) {\n\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\tfn();\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst rgPath = await ensureTool(\"rg\", true);\n\t\t\t\t\t\tif (!rgPath) {\n\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\treject(\n\t\t\t\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t\t\t\t\"ripgrep (rg) unavailable and could not be downloaded — use the bash tool to run grep/rg instead\",\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst searchPath = resolveToCwd(searchDir || \".\", cwd);\n\t\t\t\t\t\tconst ops = customOps ?? defaultGrepOperations;\n\t\t\t\t\t\tlet isDirectory: boolean;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tisDirectory = await ops.isDirectory(searchPath);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Path not found: ${searchPath}`)));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst contextValue = context && context > 0 ? context : 0;\n\t\t\t\t\t\tconst effectiveLimit = Math.max(1, limit ?? DEFAULT_LIMIT);\n\t\t\t\t\t\tconst formatPath = (filePath: string): string => {\n\t\t\t\t\t\t\tif (isDirectory) {\n\t\t\t\t\t\t\t\tconst relative = path.relative(searchPath, filePath);\n\t\t\t\t\t\t\t\tif (relative && !relative.startsWith(\"..\")) {\n\t\t\t\t\t\t\t\t\treturn relative.replace(/\\\\/g, \"/\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn path.basename(filePath);\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst fileCache = new Map<string, string[]>();\n\t\t\t\t\t\tconst getFileLines = async (filePath: string): Promise<string[]> => {\n\t\t\t\t\t\t\tlet lines = fileCache.get(filePath);\n\t\t\t\t\t\t\tif (!lines) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tconst content = await ops.readFile(filePath);\n\t\t\t\t\t\t\t\t\tlines = content.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\").split(\"\\n\");\n\t\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t\tlines = [];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tfileCache.set(filePath, lines);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn lines;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst args: string[] = [\"--json\", \"--line-number\", \"--color=never\", \"--hidden\"];\n\t\t\t\t\t\tif (ignoreCase) args.push(\"--ignore-case\");\n\t\t\t\t\t\tif (literal) args.push(\"--fixed-strings\");\n\t\t\t\t\t\tif (glob) args.push(\"--glob\", glob);\n\t\t\t\t\t\targs.push(\"--\", pattern, searchPath);\n\n\t\t\t\t\t\tconst child = spawn(rgPath, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n\t\t\t\t\t\tconst rl = createInterface({ input: child.stdout });\n\t\t\t\t\t\tlet stderr = \"\";\n\t\t\t\t\t\tlet matchCount = 0;\n\t\t\t\t\t\tlet matchLimitReached = false;\n\t\t\t\t\t\tlet linesTruncated = false;\n\t\t\t\t\t\tlet aborted = false;\n\t\t\t\t\t\tlet killedDueToLimit = false;\n\t\t\t\t\t\tconst outputLines: string[] = [];\n\n\t\t\t\t\t\tconst cleanup = () => {\n\t\t\t\t\t\t\trl.close();\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst stopChild = (dueToLimit = false) => {\n\t\t\t\t\t\t\tif (!child.killed) {\n\t\t\t\t\t\t\t\tkilledDueToLimit = dueToLimit;\n\t\t\t\t\t\t\t\tchild.kill();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t\t\taborted = true;\n\t\t\t\t\t\t\tstopChild();\n\t\t\t\t\t\t};\n\t\t\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t\t\tchild.stderr?.on(\"data\", (chunk) => {\n\t\t\t\t\t\t\tstderr += chunk.toString();\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\t// Format a context block around a match line. Path is omitted (emitted once per file).\n\t\t\t\t\t\tconst formatBlock = async (filePath: string, lineNumber: number): Promise<string[]> => {\n\t\t\t\t\t\t\tconst lines = await getFileLines(filePath);\n\t\t\t\t\t\t\tif (!lines.length) return [` ${lineNumber}: (unable to read file)`];\n\t\t\t\t\t\t\tconst block: string[] = [];\n\t\t\t\t\t\t\tconst start = contextValue > 0 ? Math.max(1, lineNumber - contextValue) : lineNumber;\n\t\t\t\t\t\t\tconst end = contextValue > 0 ? Math.min(lines.length, lineNumber + contextValue) : lineNumber;\n\t\t\t\t\t\t\tfor (let current = start; current <= end; current++) {\n\t\t\t\t\t\t\t\tconst lineText = lines[current - 1] ?? \"\";\n\t\t\t\t\t\t\t\tconst sanitized = lineText.replace(/\\r/g, \"\");\n\t\t\t\t\t\t\t\tconst isMatchLine = current === lineNumber;\n\t\t\t\t\t\t\t\t// Truncate long lines so grep output stays compact.\n\t\t\t\t\t\t\t\tconst { text: truncatedText, wasTruncated } = truncateLine(sanitized);\n\t\t\t\t\t\t\t\tif (wasTruncated) linesTruncated = true;\n\t\t\t\t\t\t\t\tif (isMatchLine) block.push(`${current}: ${truncatedText}`);\n\t\t\t\t\t\t\t\telse block.push(`${current}- ${truncatedText}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn block;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t// Collect matches during streaming, then format them after rg exits.\n\t\t\t\t\t\tconst matches: Array<{ filePath: string; lineNumber: number; lineText?: string }> = [];\n\t\t\t\t\t\trl.on(\"line\", (line) => {\n\t\t\t\t\t\t\tif (!line.trim() || matchCount >= effectiveLimit) return;\n\t\t\t\t\t\t\tlet event: any;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tevent = JSON.parse(line);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (event.type === \"match\") {\n\t\t\t\t\t\t\t\tmatchCount++;\n\t\t\t\t\t\t\t\tconst filePath = event.data?.path?.text;\n\t\t\t\t\t\t\t\tconst lineNumber = event.data?.line_number;\n\t\t\t\t\t\t\t\tconst lineText = event.data?.lines?.text;\n\t\t\t\t\t\t\t\tif (filePath && typeof lineNumber === \"number\")\n\t\t\t\t\t\t\t\t\tmatches.push({ filePath, lineNumber, lineText });\n\t\t\t\t\t\t\t\tif (matchCount >= effectiveLimit) {\n\t\t\t\t\t\t\t\t\tmatchLimitReached = true;\n\t\t\t\t\t\t\t\t\tstopChild(true);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tchild.on(\"error\", (error) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Failed to run ripgrep: ${error.message}`)));\n\t\t\t\t\t\t});\n\t\t\t\t\t\tchild.on(\"close\", async (code) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tif (aborted) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!killedDueToLimit && code !== 0 && code !== 1) {\n\t\t\t\t\t\t\t\tconst trimmedStderr = stderr.trim();\n\t\t\t\t\t\t\t\tlet errorMsg = trimmedStderr || `ripgrep exited with code ${code}`;\n\t\t\t\t\t\t\t\t// A regex parse error means the pattern is not a valid regex. Point the\n\t\t\t\t\t\t\t\t// caller at the `literal` option so they can search the text verbatim.\n\t\t\t\t\t\t\t\tif (!literal && /regex parse error/i.test(trimmedStderr)) {\n\t\t\t\t\t\t\t\t\terrorMsg += `\\n\\nThe pattern is not a valid regex. To search for it as plain text, pass literal: true (or escape the regex metacharacters).`;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(errorMsg)));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (matchCount === 0) {\n\t\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: \"No matches found\" }], details: undefined }),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Group matches by file path, showing filename once per file.\n\t\t\t\t\t\t\tconst fileGroups = new Map<string, typeof matches>();\n\t\t\t\t\t\t\tfor (const match of matches) {\n\t\t\t\t\t\t\t\tlet group = fileGroups.get(match.filePath);\n\t\t\t\t\t\t\t\tif (!group) {\n\t\t\t\t\t\t\t\t\tgroup = [];\n\t\t\t\t\t\t\t\t\tfileGroups.set(match.filePath, group);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tgroup.push(match);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfor (const [filePath, fileMatches] of fileGroups) {\n\t\t\t\t\t\t\t\tconst relativePath = formatPath(filePath);\n\t\t\t\t\t\t\t\toutputLines.push(relativePath);\n\t\t\t\t\t\t\t\tfor (const match of fileMatches) {\n\t\t\t\t\t\t\t\t\tif (contextValue === 0 && match.lineText !== undefined) {\n\t\t\t\t\t\t\t\t\t\tconst sanitized = match.lineText\n\t\t\t\t\t\t\t\t\t\t\t.replace(/\\r\\n/g, \"\\n\")\n\t\t\t\t\t\t\t\t\t\t\t.replace(/\\r/g, \"\")\n\t\t\t\t\t\t\t\t\t\t\t.replace(/\\n$/, \"\");\n\t\t\t\t\t\t\t\t\t\tconst { text: truncatedText, wasTruncated } = truncateLine(sanitized);\n\t\t\t\t\t\t\t\t\t\tif (wasTruncated) linesTruncated = true;\n\t\t\t\t\t\t\t\t\t\toutputLines.push(`${match.lineNumber}: ${truncatedText}`);\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tconst block = await formatBlock(match.filePath, match.lineNumber);\n\t\t\t\t\t\t\t\t\t\toutputLines.push(...block);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst rawOutput = outputLines.join(\"\\n\");\n\t\t\t\t\t\t\t// Apply lossless compression then byte truncation.\n\t\t\t\t\t\t\tconst compressedOutput = compressGrepOutput(rawOutput);\n\t\t\t\t\t\t\t// Apply byte truncation. There is no line limit here because the match limit already capped rows.\n\t\t\t\t\t\t\tconst truncation = truncateHead(compressedOutput, { maxLines: Number.MAX_SAFE_INTEGER });\n\t\t\t\t\t\t\tlet output = truncation.content;\n\t\t\t\t\t\t\tconst details: GrepToolDetails = {};\n\t\t\t\t\t\t\t// Build actionable notices for truncation and match limits.\n\t\t\t\t\t\t\tconst notices: string[] = [];\n\t\t\t\t\t\t\tif (matchLimitReached) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`${effectiveLimit} matches limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.matchLimitReached = effectiveLimit;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\t\t\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t\t\t\t\t\t\tdetails.truncation = truncation;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (linesTruncated) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`Some lines truncated to ${GREP_MAX_LINE_LENGTH} chars. Use read tool to see full lines`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.linesTruncated = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (notices.length > 0) output += `\\n\\n[${notices.join(\". \")}]`;\n\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: output }],\n\t\t\t\t\t\t\t\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tsettle(() => reject(err as Error));\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatGrepCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatGrepResult(result as any, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createGrepTool(cwd: string, options?: GrepToolOptions): AgentTool<typeof grepSchema> {\n\treturn wrapToolDefinition(createGrepToolDefinition(cwd, options));\n}\n"]}