@arhan-w/ibex 0.0.0-stage → 3.6.0

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 (167) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +295 -2
  3. package/npm-package/LICENSE +21 -0
  4. package/npm-package/README.md +176 -0
  5. package/npm-package/bin/goat.js +3 -0
  6. package/npm-package/bin/ibex.js +77 -0
  7. package/npm-package/package.json +58 -0
  8. package/npm-package/scripts/install-binary.js +168 -0
  9. package/package.json +69 -6
  10. package/src/agent.ts +695 -0
  11. package/src/agents/loader.ts +110 -0
  12. package/src/ambient.d.ts +2 -0
  13. package/src/code/extract.ts +292 -0
  14. package/src/code/find.ts +244 -0
  15. package/src/code/grammars.ts +88 -0
  16. package/src/code/indexer.ts +242 -0
  17. package/src/code/semantic.ts +253 -0
  18. package/src/code/slash.ts +88 -0
  19. package/src/code/tool.ts +40 -0
  20. package/src/collab/client.ts +141 -0
  21. package/src/collab/handlers.ts +141 -0
  22. package/src/collab/invite.ts +39 -0
  23. package/src/collab/relay.ts +106 -0
  24. package/src/collab/sync.ts +131 -0
  25. package/src/commands.tsx +943 -0
  26. package/src/computer.ts +629 -0
  27. package/src/config.ts +318 -0
  28. package/src/constants.ts +18 -0
  29. package/src/context.ts +73 -0
  30. package/src/data/providers.json +2342 -0
  31. package/src/diff.ts +50 -0
  32. package/src/doctor.ts +443 -0
  33. package/src/errors.ts +139 -0
  34. package/src/gflash.ts +170 -0
  35. package/src/hooks.ts +133 -0
  36. package/src/ide/assets.gen.ts +3 -0
  37. package/src/ide/index.html +844 -0
  38. package/src/ide/server.ts +506 -0
  39. package/src/ide/vendor/marked.umd.js +80 -0
  40. package/src/ide/vendor/vs/base/browser/ui/codicons/codicon/codicon.ttf +0 -0
  41. package/src/ide/vendor/vs/base/worker/workerMain.js +31 -0
  42. package/src/ide/vendor/vs/basic-languages/abap/abap.js +10 -0
  43. package/src/ide/vendor/vs/basic-languages/apex/apex.js +10 -0
  44. package/src/ide/vendor/vs/basic-languages/azcli/azcli.js +10 -0
  45. package/src/ide/vendor/vs/basic-languages/bat/bat.js +10 -0
  46. package/src/ide/vendor/vs/basic-languages/bicep/bicep.js +11 -0
  47. package/src/ide/vendor/vs/basic-languages/cameligo/cameligo.js +10 -0
  48. package/src/ide/vendor/vs/basic-languages/clojure/clojure.js +10 -0
  49. package/src/ide/vendor/vs/basic-languages/coffee/coffee.js +10 -0
  50. package/src/ide/vendor/vs/basic-languages/cpp/cpp.js +10 -0
  51. package/src/ide/vendor/vs/basic-languages/csharp/csharp.js +10 -0
  52. package/src/ide/vendor/vs/basic-languages/csp/csp.js +10 -0
  53. package/src/ide/vendor/vs/basic-languages/css/css.js +12 -0
  54. package/src/ide/vendor/vs/basic-languages/cypher/cypher.js +10 -0
  55. package/src/ide/vendor/vs/basic-languages/dart/dart.js +10 -0
  56. package/src/ide/vendor/vs/basic-languages/dockerfile/dockerfile.js +10 -0
  57. package/src/ide/vendor/vs/basic-languages/ecl/ecl.js +10 -0
  58. package/src/ide/vendor/vs/basic-languages/elixir/elixir.js +10 -0
  59. package/src/ide/vendor/vs/basic-languages/flow9/flow9.js +10 -0
  60. package/src/ide/vendor/vs/basic-languages/freemarker2/freemarker2.js +12 -0
  61. package/src/ide/vendor/vs/basic-languages/fsharp/fsharp.js +10 -0
  62. package/src/ide/vendor/vs/basic-languages/go/go.js +10 -0
  63. package/src/ide/vendor/vs/basic-languages/graphql/graphql.js +10 -0
  64. package/src/ide/vendor/vs/basic-languages/handlebars/handlebars.js +10 -0
  65. package/src/ide/vendor/vs/basic-languages/hcl/hcl.js +10 -0
  66. package/src/ide/vendor/vs/basic-languages/html/html.js +10 -0
  67. package/src/ide/vendor/vs/basic-languages/ini/ini.js +10 -0
  68. package/src/ide/vendor/vs/basic-languages/java/java.js +10 -0
  69. package/src/ide/vendor/vs/basic-languages/javascript/javascript.js +10 -0
  70. package/src/ide/vendor/vs/basic-languages/julia/julia.js +10 -0
  71. package/src/ide/vendor/vs/basic-languages/kotlin/kotlin.js +10 -0
  72. package/src/ide/vendor/vs/basic-languages/less/less.js +11 -0
  73. package/src/ide/vendor/vs/basic-languages/lexon/lexon.js +10 -0
  74. package/src/ide/vendor/vs/basic-languages/liquid/liquid.js +10 -0
  75. package/src/ide/vendor/vs/basic-languages/lua/lua.js +10 -0
  76. package/src/ide/vendor/vs/basic-languages/m3/m3.js +10 -0
  77. package/src/ide/vendor/vs/basic-languages/markdown/markdown.js +10 -0
  78. package/src/ide/vendor/vs/basic-languages/mdx/mdx.js +10 -0
  79. package/src/ide/vendor/vs/basic-languages/mips/mips.js +10 -0
  80. package/src/ide/vendor/vs/basic-languages/msdax/msdax.js +10 -0
  81. package/src/ide/vendor/vs/basic-languages/mysql/mysql.js +10 -0
  82. package/src/ide/vendor/vs/basic-languages/objective-c/objective-c.js +10 -0
  83. package/src/ide/vendor/vs/basic-languages/pascal/pascal.js +10 -0
  84. package/src/ide/vendor/vs/basic-languages/pascaligo/pascaligo.js +10 -0
  85. package/src/ide/vendor/vs/basic-languages/perl/perl.js +10 -0
  86. package/src/ide/vendor/vs/basic-languages/pgsql/pgsql.js +10 -0
  87. package/src/ide/vendor/vs/basic-languages/php/php.js +10 -0
  88. package/src/ide/vendor/vs/basic-languages/pla/pla.js +10 -0
  89. package/src/ide/vendor/vs/basic-languages/postiats/postiats.js +10 -0
  90. package/src/ide/vendor/vs/basic-languages/powerquery/powerquery.js +10 -0
  91. package/src/ide/vendor/vs/basic-languages/powershell/powershell.js +10 -0
  92. package/src/ide/vendor/vs/basic-languages/protobuf/protobuf.js +11 -0
  93. package/src/ide/vendor/vs/basic-languages/pug/pug.js +10 -0
  94. package/src/ide/vendor/vs/basic-languages/python/python.js +10 -0
  95. package/src/ide/vendor/vs/basic-languages/qsharp/qsharp.js +10 -0
  96. package/src/ide/vendor/vs/basic-languages/r/r.js +10 -0
  97. package/src/ide/vendor/vs/basic-languages/razor/razor.js +10 -0
  98. package/src/ide/vendor/vs/basic-languages/redis/redis.js +10 -0
  99. package/src/ide/vendor/vs/basic-languages/redshift/redshift.js +10 -0
  100. package/src/ide/vendor/vs/basic-languages/restructuredtext/restructuredtext.js +10 -0
  101. package/src/ide/vendor/vs/basic-languages/ruby/ruby.js +10 -0
  102. package/src/ide/vendor/vs/basic-languages/rust/rust.js +10 -0
  103. package/src/ide/vendor/vs/basic-languages/sb/sb.js +10 -0
  104. package/src/ide/vendor/vs/basic-languages/scala/scala.js +10 -0
  105. package/src/ide/vendor/vs/basic-languages/scheme/scheme.js +10 -0
  106. package/src/ide/vendor/vs/basic-languages/scss/scss.js +12 -0
  107. package/src/ide/vendor/vs/basic-languages/shell/shell.js +10 -0
  108. package/src/ide/vendor/vs/basic-languages/solidity/solidity.js +10 -0
  109. package/src/ide/vendor/vs/basic-languages/sophia/sophia.js +10 -0
  110. package/src/ide/vendor/vs/basic-languages/sparql/sparql.js +10 -0
  111. package/src/ide/vendor/vs/basic-languages/sql/sql.js +10 -0
  112. package/src/ide/vendor/vs/basic-languages/st/st.js +10 -0
  113. package/src/ide/vendor/vs/basic-languages/swift/swift.js +13 -0
  114. package/src/ide/vendor/vs/basic-languages/systemverilog/systemverilog.js +10 -0
  115. package/src/ide/vendor/vs/basic-languages/tcl/tcl.js +10 -0
  116. package/src/ide/vendor/vs/basic-languages/twig/twig.js +10 -0
  117. package/src/ide/vendor/vs/basic-languages/typescript/typescript.js +10 -0
  118. package/src/ide/vendor/vs/basic-languages/typespec/typespec.js +10 -0
  119. package/src/ide/vendor/vs/basic-languages/vb/vb.js +10 -0
  120. package/src/ide/vendor/vs/basic-languages/wgsl/wgsl.js +307 -0
  121. package/src/ide/vendor/vs/basic-languages/xml/xml.js +10 -0
  122. package/src/ide/vendor/vs/basic-languages/yaml/yaml.js +10 -0
  123. package/src/ide/vendor/vs/editor/editor.main.css +8 -0
  124. package/src/ide/vendor/vs/editor/editor.main.js +798 -0
  125. package/src/ide/vendor/vs/language/css/cssMode.js +13 -0
  126. package/src/ide/vendor/vs/language/css/cssWorker.js +77 -0
  127. package/src/ide/vendor/vs/language/html/htmlMode.js +13 -0
  128. package/src/ide/vendor/vs/language/html/htmlWorker.js +454 -0
  129. package/src/ide/vendor/vs/language/json/jsonMode.js +19 -0
  130. package/src/ide/vendor/vs/language/json/jsonWorker.js +42 -0
  131. package/src/ide/vendor/vs/language/typescript/tsMode.js +20 -0
  132. package/src/ide/vendor/vs/language/typescript/tsWorker.js +51328 -0
  133. package/src/ide/vendor/vs/loader.js +11 -0
  134. package/src/index-shared.ts +117 -0
  135. package/src/index.ts +586 -0
  136. package/src/llm.ts +721 -0
  137. package/src/logger.ts +39 -0
  138. package/src/mcp/client.ts +121 -0
  139. package/src/mcp/types.ts +27 -0
  140. package/src/oauth.ts +205 -0
  141. package/src/onboarding.ts +140 -0
  142. package/src/palette.tsx +199 -0
  143. package/src/permissions.ts +123 -0
  144. package/src/plugins/loader.ts +120 -0
  145. package/src/plugins/marketplace.ts +252 -0
  146. package/src/plugins/sandbox.ts +303 -0
  147. package/src/plugins/tar.ts +241 -0
  148. package/src/pricing.ts +78 -0
  149. package/src/protocol/client.ts +102 -0
  150. package/src/protocol/rpc.ts +43 -0
  151. package/src/protocol/serve.ts +136 -0
  152. package/src/providers.ts +402 -0
  153. package/src/rate-limiter.ts +101 -0
  154. package/src/refs.ts +97 -0
  155. package/src/runtime.ts +144 -0
  156. package/src/session.ts +401 -0
  157. package/src/skills/loader.ts +136 -0
  158. package/src/statusline.ts +70 -0
  159. package/src/system-prompt.ts +28 -0
  160. package/src/tools.ts +1280 -0
  161. package/src/tui.tsx +1355 -0
  162. package/src/update.ts +236 -0
  163. package/src/vendor/flashServer.ts +2 -0
  164. package/src/vendor/gemini-web2api/gemini_web2api.py +1136 -0
  165. package/src/virtual-list.tsx +125 -0
  166. package/src/window.ts +31 -0
  167. package/tsconfig.json +16 -0
package/src/tools.ts ADDED
@@ -0,0 +1,1280 @@
1
+ /**
2
+ * Agent tools: read, write, edit, bash, undo, tasks, glob, grep, webfetch,
3
+ * websearch, screenshot, computer — sandboxed to project root, with a
4
+ * permission callback for mutating ops. Write/edit snapshot the file first
5
+ * so /undo can revert; bash supports background:true for long-running jobs;
6
+ * screenshot/computer drive the real desktop (see computer.ts). External
7
+ * tools (MCP servers) register through the same dispatch table.
8
+ */
9
+ import { spawn } from "node:child_process";
10
+ import { existsSync, readdirSync, readFileSync, statSync, writeFileSync, mkdirSync, unlinkSync } from "node:fs";
11
+ import { open } from "node:fs/promises";
12
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
13
+ import { decide } from "./permissions.ts";
14
+ import { fireHooks, type HooksConfig } from "./hooks.ts";
15
+ import { log } from "./logger.ts";
16
+ import { MAX_WEBFETCH_BYTES, WEBFETCH_TIMEOUT_MS } from "./constants.ts";
17
+ import { desktop, type DesktopBackend } from "./computer.ts";
18
+ import type { ContentPart, ToolSpec } from "./llm.ts";
19
+ import { ToolError, PermissionError, GoatError, formatError } from "./errors.ts";
20
+
21
+ /** SSRF guard: refuse loopback / private / link-local / cloud-metadata hosts.
22
+ * Pattern-based (literal IPs + reserved suffixes); hostnames that resolve to
23
+ * private addresses are not caught — same tradeoff as most CLI fetch tools. */
24
+ export async function isPrivateHost(host: string): Promise<boolean> {
25
+ const h = host.toLowerCase().replace(/^\[|\]$/g, "");
26
+ if (h === "localhost" || h.endsWith(".localhost") || h.endsWith(".internal") || h.endsWith(".local")) return true;
27
+ if (/^0+$/.test(h.replace(/\./g, ""))) return true;
28
+ if (/^(fe80|fc|fd|::1)/i.test(h)) return true; // link-local / ULA / IPv6 loopback
29
+ const m = h.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
30
+ if (m) {
31
+ const [a, b] = [Number(m[1]), Number(m[2])];
32
+ if (a === 127 || a === 10 || a === 0) return true;
33
+ if (a === 172 && b >= 16 && b <= 31) return true;
34
+ if (a === 192 && b === 168) return true;
35
+ if (a === 169 && b === 254) return true; // cloud metadata
36
+ if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT
37
+ }
38
+ return false;
39
+ }
40
+
41
+ export const MAX_READ_BYTES = 128_000;
42
+ export const MAX_BASH_OUTPUT = 32_000;
43
+ /** Per-call cap for live-streamed bash output forwarded to the UI. */
44
+ export const MAX_BASH_STREAM = 64_000;
45
+ export const BASH_TIMEOUT = 120;
46
+ export const GREP_MAX_RESULTS = 200;
47
+ export const GLOB_MAX_RESULTS = 300;
48
+ export const MAX_UNDO = 50;
49
+ export const MAX_SNAP_BYTES = 512_000;
50
+ export const MAX_IMAGE_BYTES = 5_000_000;
51
+ export const IMAGE_TYPES: Record<string, string> = {
52
+ ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
53
+ ".gif": "image/gif", ".webp": "image/webp",
54
+ };
55
+
56
+ /** Strip HTML tags + entities (search result text). */
57
+ function stripTags(html: string): string {
58
+ return html
59
+ .replace(/<[^>]+>/g, "")
60
+ .replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">")
61
+ .replace(/&quot;/g, '"').replace(/&#x27;|&apos;/g, "'").replace(/&nbsp;/g, " ");
62
+ }
63
+
64
+ /** Streaming read of a line range [startLine, endLine) (0-based, exclusive end). */
65
+ export async function readLineRange(filePath: string, startLine: number, endLine: number): Promise<string> {
66
+ const fd = await open(filePath, "r");
67
+ try {
68
+ const chunks: Buffer[] = [];
69
+ let bytesRead = 0;
70
+ const chunkSize = 64_000;
71
+ const stat = await fd.stat();
72
+ const maxBytes = Math.min(stat.size, MAX_READ_BYTES);
73
+ while (bytesRead < maxBytes) {
74
+ const remaining = Math.min(chunkSize, maxBytes - bytesRead);
75
+ const buf = Buffer.alloc(remaining);
76
+ const { bytesRead: n } = await fd.read(buf, 0, remaining, bytesRead);
77
+ if (n === 0) break;
78
+ chunks.push(buf.subarray(0, n));
79
+ bytesRead += n;
80
+ }
81
+ const text = Buffer.concat(chunks).toString("utf8");
82
+ const lines = text.split("\n");
83
+ return lines.slice(startLine, endLine).join("\n");
84
+ } finally {
85
+ await fd.close();
86
+ }
87
+ }
88
+
89
+ /** Count total lines in a file efficiently (reads in chunks, counts newlines). */
90
+ export async function countLines(filePath: string): Promise<number> {
91
+ const fd = await open(filePath, "r");
92
+ try {
93
+ let lines = 0;
94
+ const chunkSize = 64_000;
95
+ const stat = await fd.stat();
96
+ const maxBytes = Math.min(stat.size, MAX_READ_BYTES);
97
+ let bytesRead = 0;
98
+ while (bytesRead < maxBytes) {
99
+ const remaining = Math.min(chunkSize, maxBytes - bytesRead);
100
+ const buf = Buffer.alloc(remaining);
101
+ const { bytesRead: n } = await fd.read(buf, 0, remaining, bytesRead);
102
+ if (n === 0) break;
103
+ for (let i = 0; i < n; i++) { if (buf[i] === 10) lines++; } // newline char
104
+ bytesRead += n;
105
+ }
106
+ return lines;
107
+ } finally {
108
+ await fd.close();
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Detect real image type from magic bytes — never trust the extension.
114
+ * Returns a media type, or null if the buffer isn't a supported image.
115
+ */
116
+ export function sniffImage(buf: Buffer): string | null {
117
+ if (buf.length < 12) return null;
118
+ if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) return "image/png";
119
+ if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return "image/jpeg";
120
+ const sig = buf.subarray(0, 6).toString("latin1");
121
+ if (sig === "GIF87a" || sig === "GIF89a") return "image/gif";
122
+ if (buf.subarray(0, 4).toString("latin1") === "RIFF" && buf.subarray(8, 12).toString("latin1") === "WEBP") return "image/webp";
123
+ return null;
124
+ }
125
+ export const SKIP_DIRS = new Set([
126
+ ".git", "node_modules", "__pycache__", ".venv", "venv", "dist",
127
+ "build", ".next", ".cache", "target", ".tox", ".mypy_cache", ".goat",
128
+ ]);
129
+
130
+ export interface ToolResult {
131
+ ok: boolean;
132
+ output: string;
133
+ /** Multimodal payload (e.g. read on an image) — carried into the tool message. */
134
+ content?: ContentPart[];
135
+ }
136
+
137
+ export type PermissionFn = (tool: string, args: Record<string, unknown>) => Promise<boolean> | boolean;
138
+
139
+ /** Live tool telemetry streamed to the UI (see ToolKit.toolEvent). */
140
+ export interface ToolEvent {
141
+ kind: "start" | "output" | "end";
142
+ /** Stable id per tool invocation (deltas attach to their start). */
143
+ callId: string;
144
+ tool: string;
145
+ args?: Record<string, unknown>;
146
+ /** "output": incremental stdout/stderr chunk (truncated lines). */
147
+ text?: string;
148
+ /** "end": overall success. */
149
+ ok?: boolean;
150
+ /** "end": final result (capped). */
151
+ result?: string;
152
+ /** Which subagent (forkIndex) emitted this, if any. */
153
+ forkIndex?: number;
154
+ }
155
+
156
+ export interface ExternalTool {
157
+ spec: ToolSpec;
158
+ run: (args: Record<string, unknown>, signal?: AbortSignal) => Promise<ToolResult>;
159
+ /** true = needs the permission prompt like write/edit/bash */
160
+ mutating?: boolean;
161
+ }
162
+
163
+ /** One captured file mutation. path is ABSOLUTE; existed=false means the
164
+ * mutation created the file, so undo deletes it instead of restoring. */
165
+ export type SnapRecord = { path: string; existed: boolean; before: string; after: string };
166
+
167
+ /** Agent-maintained plan step (Claude Code TodoWrite analogue, same schema). */
168
+ export interface Todo {
169
+ /** Imperative form: "Run tests". */
170
+ content: string;
171
+ /** Present continuous shown while running: "Running tests". */
172
+ activeForm: string;
173
+ status: "pending" | "in_progress" | "completed";
174
+ }
175
+
176
+ /** glob (**, *, ?) -> anchored regex */
177
+ export function fnmatch(rel: string, pattern: string): boolean {
178
+ let rx = "";
179
+ for (let i = 0; i < pattern.length; i++) {
180
+ const c = pattern[i];
181
+ if (c === "*") {
182
+ if (pattern[i + 1] === "*") { rx += ".*"; i++; if (pattern[i + 1] === "/") i++; }
183
+ else rx += "[^/]*";
184
+ } else if (c === "?") rx += "[^/]";
185
+ else if ("\\^$.|+()[]{}".includes(c)) rx += "\\" + c;
186
+ else rx += c;
187
+ }
188
+ return new RegExp("^" + rx + "$").test(rel);
189
+ }
190
+
191
+ /**
192
+ * Membership, not string-prefix: "/root" prefixes "/rootkit" but isn't its
193
+ * parent. Throws if path escapes base. Absolute inputs are honored (so an
194
+ * existing absolute path round-trips); relative resolve against base.
195
+ */
196
+ export function insideRoot(base: string, path: string): string {
197
+ const p = resolve(base, path);
198
+ if (p !== base) {
199
+ const rel = relative(base, p);
200
+ if (rel === "" || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel))
201
+ throw new Error(`path escapes project root: ${path}`);
202
+ }
203
+ return p;
204
+ }
205
+
206
+ function walk(root: string, onFile: (abs: string, rel: string) => boolean | void): void {
207
+ let entries;
208
+ try { entries = readdirSync(root, { withFileTypes: true }); } catch { return; }
209
+ for (const e of entries) {
210
+ if (e.isDirectory()) {
211
+ if (!SKIP_DIRS.has(e.name)) walk(join(root, e.name), onFile);
212
+ } else if (e.isFile()) {
213
+ const abs = join(root, e.name);
214
+ if (onFile(abs, relative(root, abs).replaceAll("\\", "/")) === false) return;
215
+ }
216
+ }
217
+ }
218
+
219
+ export interface BgTask {
220
+ id: string;
221
+ cmd: string;
222
+ status: string;
223
+ started: number;
224
+ }
225
+
226
+ export class ToolKit {
227
+ root: string;
228
+ /** Multi-repo workspace: name -> absolute repo root. Empty = single-root v2 mode. */
229
+ roots = new Map<string, string>();
230
+ permission: PermissionFn | null;
231
+ autoApprove: boolean;
232
+ /** GOAT MODE: no sandbox, no rules, no prompts — every tool fully unchained. */
233
+ goat = false;
234
+ readonly = false;
235
+ /** settings.json-style allow/deny rules, consulted before the prompt. */
236
+ rules: { allow: string[]; deny: string[] } | undefined;
237
+ /** Claude-compatible hooks (set from config per turn; undefined = off). */
238
+ hooks: HooksConfig | undefined;
239
+ sessionId = "goat";
240
+ private hookAllowNext = false;
241
+ external = new Map<string, ExternalTool>();
242
+ /**
243
+ * Live tool telemetry, wired by the UI layers (TUI/web IDE). Receives
244
+ * start/end plus streaming output deltas from long-running tools (bash).
245
+ * Never set by the agent loop itself.
246
+ */
247
+ toolEvent: ((ev: ToolEvent) => void) | null = null;
248
+
249
+ private snaps: SnapRecord[] = [];
250
+ private bg = new Map<string, BgTask>();
251
+ private todos: Todo[] = [];
252
+
253
+ /** Sub-agent fork metadata (set by Agent.spawnSubagent). */
254
+ parentSessionId: string | undefined;
255
+ forkIndex = 0;
256
+
257
+ constructor(root: string, opts: { permission?: PermissionFn; autoApprove?: boolean; goat?: boolean; readonly?: boolean; rules?: { allow: string[]; deny: string[] }; roots?: Record<string, string> } = {}) {
258
+ this.root = resolve(root);
259
+ this.permission = opts.permission ?? null;
260
+ this.autoApprove = opts.autoApprove ?? false;
261
+ this.goat = opts.goat ?? false;
262
+ this.readonly = opts.readonly ?? false;
263
+ this.rules = opts.rules;
264
+ if (opts.roots) for (const [n, r] of Object.entries(opts.roots)) this.roots.set(n, resolve(r));
265
+ }
266
+
267
+ /**
268
+ * Produce an isolated copy of this ToolKit for subagent execution.
269
+ *
270
+ * What is shared (read-only references):
271
+ * - root / roots : path strings are immutable; the Map is shallow-copied
272
+ * - permission : the callback is not mutated
273
+ * - external : MCP server registry is shared (registration happens on the parent)
274
+ * - hooks / rules : config objects are read-only at dispatch time
275
+ *
276
+ * What is isolated (fresh empty state):
277
+ * - snaps, bg, todos : subagent mutations do not leak into the parent
278
+ * - checkpoints : undo boundaries are independent
279
+ * - hookAllowNext : per-instance flag
280
+ *
281
+ * The returned clone inherits this.sessionId so hooks can attribute
282
+ * subagent tool calls to the parent session unless the caller overrides it.
283
+ */
284
+ clone(): ToolKit {
285
+ const kit = new ToolKit(this.root, {
286
+ permission: this.permission ?? undefined,
287
+ autoApprove: this.autoApprove,
288
+ goat: this.goat,
289
+ readonly: this.readonly,
290
+ rules: this.rules ? { ...this.rules } : undefined,
291
+ roots: Object.fromEntries(this.roots),
292
+ });
293
+ // inherit shared read-only references
294
+ kit.hooks = this.hooks;
295
+ kit.external = this.external;
296
+ kit.sessionId = this.sessionId;
297
+ kit.parentSessionId = this.sessionId;
298
+ return kit;
299
+ }
300
+
301
+ get multiRepo(): boolean { return this.roots.size > 0; }
302
+
303
+ /**
304
+ * Every path form a rule might reference for a resolved file: repo-prefixed
305
+ * display path, absolute, and repo-relative (so deny Edit(src/**) covers
306
+ * every repo's src/, not just the primary root's).
307
+ */
308
+ ruleForms(abs: string): string[] {
309
+ const forms = [this.displayPath(abs), abs];
310
+ for (const r of [...this.roots.values(), this.root]) {
311
+ const rel = relative(r, abs);
312
+ if (rel && !rel.startsWith("..") && !isAbsolute(rel)) forms.push(rel.replaceAll("\\", "/"));
313
+ }
314
+ return forms;
315
+ }
316
+
317
+ /** Display form for a tool path: repo/rel inside a workspace, plain rel otherwise. */
318
+ displayPath(abs: string): string {
319
+ for (const [name, r] of this.roots) {
320
+ const rel = relative(r, abs);
321
+ if (rel === "" || (!isAbsolute(rel) && !rel.startsWith("..") && rel !== "..")) {
322
+ const suffix = rel.replaceAll("\\", "/");
323
+ return suffix ? `${name}/${suffix}` : name;
324
+ }
325
+ }
326
+ const rel = relative(this.root, abs).replaceAll("\\", "/");
327
+ return rel === "" || rel.startsWith("..") ? abs.replaceAll("\\", "/") : rel;
328
+ }
329
+
330
+ /**
331
+ * Resolve a tool path to an absolute path, sandboxed.
332
+ * inside("api/src/x.ts") → repo api's root/src/x.ts (workspace mode)
333
+ * inside("x.ts", "api") → same, explicit repo arg
334
+ * inside("x.ts") → this.root/x.ts (single-root, v2 behavior)
335
+ * A leading known repo name wins; plain paths fall back to this.root.
336
+ */
337
+ inside(path: string, repo?: string): string {
338
+ if (this.goat) {
339
+ // GOAT MODE: absolute paths and ../ escapes resolve free — no jail.
340
+ const base = (repo ? this.roots.get(repo) : undefined) ?? this.root;
341
+ if (repo && !base) throw new Error(`unknown repo "${repo}" — workspace has: ${[...this.roots.keys()].join(", ")}`);
342
+ return resolve(base, path);
343
+ }
344
+ if (repo) {
345
+ const base = this.roots.get(repo);
346
+ if (!base) throw new Error(`unknown repo "${repo}" — workspace has: ${[...this.roots.keys()].join(", ")}`);
347
+ return insideRoot(base, path);
348
+ }
349
+ if (this.roots.size) {
350
+ const norm = path.replaceAll("\\", "/");
351
+ const slash = norm.indexOf("/");
352
+ const head = slash > 0 ? norm.slice(0, slash) : norm;
353
+ const base = this.roots.get(head);
354
+ if (base) return insideRoot(base, slash > 0 ? norm.slice(slash + 1) : ".");
355
+ }
356
+ return insideRoot(this.root, path);
357
+ }
358
+
359
+ registerExternal(tool: ExternalTool): void {
360
+ this.external.set(tool.spec.name, tool);
361
+ }
362
+
363
+ unregisterExternal(prefix: string): void {
364
+ for (const name of [...this.external.keys()])
365
+ if (name.startsWith(prefix)) this.external.delete(name);
366
+ }
367
+
368
+ specs(): ToolSpec[] {
369
+ return [...builtinSpecs(), ...[...this.external.values()].map((t) => t.spec)];
370
+ }
371
+
372
+ async dispatch(name: string, args: Record<string, unknown>, signal?: AbortSignal): Promise<ToolResult> {
373
+ const callId = `call_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 7)}`;
374
+ this.currentCallId = callId;
375
+ this.emitToolEvent({ kind: "start", callId, tool: name, args, forkIndex: this.forkIndex });
376
+ try {
377
+ const ext = this.external.get(name);
378
+ // Claude wire-compat: file tools report their arg as file_path
379
+ const hookArgs = { ...args };
380
+ if ((name === "read" || name === "write" || name === "edit" || name === "multiedit") && args.path !== undefined)
381
+ hookArgs.file_path = args.path;
382
+ const hookPayload = () => ({
383
+ session_id: this.sessionId, transcript_path: "", cwd: this.root,
384
+ hook_event_name: "PreToolUse" as const, hookEventName: "PreToolUse" as const,
385
+ tool_name: name, tool_input: hookArgs,
386
+ });
387
+ // PreToolUse hooks: exit-2 blocks; permissionDecision can skip the prompt
388
+ this.hookAllowNext = false;
389
+ if (this.hooks?.PreToolUse?.length) {
390
+ const hr = await fireHooks(this.hooks, "PreToolUse", hookPayload(), this.sessionId);
391
+ if (hr.blocked) return this.endToolEvent(callId, name, { ok: false, output: `blocked by PreToolUse hook: ${hr.reason ?? "(no reason)"}` });
392
+ if (hr.decision === "deny") return this.endToolEvent(callId, name, { ok: false, output: `denied by PreToolUse hook: ${hr.reason ?? ""}` });
393
+ if (hr.decision === "allow") this.hookAllowNext = true;
394
+ if (hr.updatedInput) { args = hr.updatedInput; } // hook rewrote the tool input
395
+ }
396
+ let result: ToolResult;
397
+ if (ext) {
398
+ if (ext.mutating && !this.hookAllowNext) {
399
+ const denied = await this.ask(name, args);
400
+ if (denied) return this.endToolEvent(callId, name, denied);
401
+ }
402
+ result = await ext.run(args, signal);
403
+ } else {
404
+ const handler = (this as any)[`tool_${name}`];
405
+ if (!handler) result = { ok: false, output: `unknown tool: ${name}` };
406
+ else result = await handler.call(this, args, signal);
407
+ }
408
+ // PostToolUse hooks (informational + exit-2 blocking of a completed call's use)
409
+ if (this.hooks?.PostToolUse?.length) {
410
+ const hr = await fireHooks(this.hooks, "PostToolUse", {
411
+ ...hookPayload(), hook_event_name: "PostToolUse",
412
+ tool_response: { stdout: result.output.slice(0, 30_000), stderr: "", interrupted: false },
413
+ }, this.sessionId);
414
+ if (hr.blocked) result = { ok: false, output: `PostToolUse hook flagged output: ${hr.reason ?? "(exit 2)"}` };
415
+ }
416
+ return this.endToolEvent(callId, name, result);
417
+ } catch (e: any) {
418
+ const err = e instanceof GoatError ? e : Object.assign(new Error(), e, { code: 'ERR_GENERIC' });
419
+ return this.endToolEvent(callId, name, { ok: false, output: formatError(err) });
420
+ }
421
+ }
422
+
423
+ private emitToolEvent(ev: ToolEvent): void {
424
+ try { this.toolEvent?.(ev); } catch { /* telemetry must never break the tool */ }
425
+ }
426
+
427
+ /** dispatch() assigns the per-call id; tools that stream their own output
428
+ * deltas (bash) reuse it so the UI can attach every chunk to the right row. */
429
+ private currentCallId: string | null = null;
430
+
431
+ /** Attach ok/result to a finished dispatch and emit the end event. */
432
+ private endToolEvent(callId: string, tool: string, result: ToolResult): ToolResult {
433
+ this.emitToolEvent({ kind: "end", callId, tool, ok: result.ok, result: result.output.slice(0, 4_000), forkIndex: this.forkIndex });
434
+ return result;
435
+ }
436
+
437
+ private async ask(tool: string, args: Record<string, unknown>): Promise<ToolResult | null> {
438
+ // GOAT MODE: no rules, no prompts — the user said "unchained"
439
+ if (this.goat) return null;
440
+ // plan mode: mutating tools never run — explain how to leave the mode
441
+ if (this.readonly)
442
+ return { ok: false, output: `${tool} blocked by plan mode (read-only). Shift+tab to switch to default/accept-edits mode, or present the plan and let the user approve it.` };
443
+ // settings-style rules: deny beats allow beats asking
444
+ const verdict = decide(this.rules, tool, args);
445
+ if (verdict === "deny") return { ok: false, output: `${tool} denied by permission rule (see "permissions.deny" in config)` };
446
+ if (verdict === "allow" || this.hookAllowNext) return null;
447
+ if (this.autoApprove) return null;
448
+ if (!this.permission)
449
+ return { ok: false, output: `permission required but no prompt available for ${tool}` };
450
+ const approved = await this.permission(tool, args);
451
+ if (!approved)
452
+ return { ok: false, output: `user denied ${tool} for ${String(args.path ?? args.command ?? "")}` };
453
+ return null;
454
+ }
455
+
456
+ // ---- undo / snapshots ---------------------------------------------------
457
+
458
+ private checkpoints: number[] = []; // snaps.length at each turn boundary
459
+
460
+ /** Mark the start of a turn; undoCheckpoint() later reverts everything after it. */
461
+ beginCheckpoint(): void {
462
+ this.checkpoints.push(this.snaps.length);
463
+ }
464
+
465
+ private snap(absPath: string, existed: boolean, before: string, after: string): void {
466
+ if (before.length > MAX_SNAP_BYTES || after.length > MAX_SNAP_BYTES) return; // too big to snapshot
467
+ this.snaps.push({ path: absPath, existed, before, after });
468
+ if (this.snaps.length > MAX_UNDO) {
469
+ this.snaps.shift();
470
+ // keep turn boundaries aligned with the evicted index
471
+ this.checkpoints = this.checkpoints.map((c) => Math.max(0, c - 1));
472
+ }
473
+ }
474
+
475
+ /** Revert the most recent snapshot. Returns the record (path is absolute). */
476
+ undo(): SnapRecord | null {
477
+ const rec = this.snaps.pop() ?? null;
478
+ if (!rec) return null;
479
+ this.restore(rec);
480
+ return rec;
481
+ }
482
+
483
+ /** Revert every snapshot taken since the last beginCheckpoint(). Returns count. */
484
+ undoCheckpoint(): number {
485
+ const boundary = this.checkpoints.pop();
486
+ if (boundary === undefined) return this.snaps.length ? this.undoAll().length : 0;
487
+ let n = 0;
488
+ while (this.snaps.length > boundary) { this.undo(); n++; }
489
+ return n;
490
+ }
491
+
492
+ /**
493
+ * Rewind to the checkpoint taken at turn `turnIndex` (0-based): revert every
494
+ * snapshot from that turn onward and drop the consumed checkpoints.
495
+ * Returns {files} restored, or null when the index is out of range.
496
+ */
497
+ rewindTo(turnIndex: number): { files: number } | null {
498
+ if (turnIndex < 0 || turnIndex > this.checkpoints.length) return null;
499
+ const boundary = this.checkpoints[turnIndex] ?? this.snaps.length;
500
+ let n = 0;
501
+ while (this.snaps.length > boundary) { this.undo(); n++; }
502
+ this.checkpoints.length = turnIndex;
503
+ return { files: n };
504
+ }
505
+
506
+ get turnCount(): number { return this.checkpoints.length; }
507
+
508
+ /** Newest snapshot taken since the last beginCheckpoint() — the diff source
509
+ * for the inline edit/write preview. Null when nothing was snapshotted. */
510
+ lastSnap(): SnapRecord | null {
511
+ const boundary = this.checkpoints.length ? this.checkpoints[this.checkpoints.length - 1] : 0;
512
+ return this.snaps.length > boundary ? this.snaps[this.snaps.length - 1] : null;
513
+ }
514
+
515
+ /** Every snapshot captured this session, oldest first (for /diff). */
516
+ allSnaps(): SnapRecord[] {
517
+ return [...this.snaps];
518
+ }
519
+
520
+ undoAll(): SnapRecord[] {
521
+ const out: SnapRecord[] = [];
522
+ while (this.snaps.length) out.push(this.undo()!);
523
+ return out;
524
+ }
525
+
526
+ private restore(rec: SnapRecord): void {
527
+ try {
528
+ if (rec.existed) writeFileSync(rec.path, rec.before, "utf8");
529
+ else if (existsSync(rec.path)) unlinkSync(rec.path);
530
+ } catch { /* best-effort */ }
531
+ }
532
+
533
+ // ---- background bash ----------------------------------------------------
534
+
535
+ private nextId(): string {
536
+ return `bg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 7)}`;
537
+ }
538
+
539
+ private startBg(cmd: string, timeout: number): BgTask {
540
+ const id = this.nextId();
541
+ const task: BgTask = { id, cmd, status: "running", started: Date.now() };
542
+ this.bg.set(id, task);
543
+ const shell = process.platform === "win32" ? (process.env.COMSPEC || "cmd.exe") : "/bin/bash";
544
+ const child = spawn(shell, process.platform === "win32" ? ["/c", cmd] : ["-c", cmd], {
545
+ cwd: this.root, env: process.env,
546
+ });
547
+ let out = "", err = "";
548
+ const timer = setTimeout(() => { child.kill(); }, timeout);
549
+ child.stdout.on("data", (d) => { out += d; });
550
+ child.stderr.on("data", (d) => { err += d; });
551
+ child.on("close", (code) => {
552
+ clearTimeout(timer);
553
+ const combined = out + (err ? `\n[stderr]\n${err}` : "");
554
+ const tail = code === 0 ? "" : `\n[exit code ${code}]`;
555
+ this.bg.set(id, { ...task, status: `${(combined.trim() || "(no output)").slice(0, MAX_BASH_OUTPUT)}${tail}`, started: task.started });
556
+ });
557
+ child.on("error", (e) => {
558
+ clearTimeout(timer);
559
+ this.bg.set(id, { ...task, status: `spawn failed: ${e.message}`, started: task.started });
560
+ });
561
+ return task;
562
+ }
563
+
564
+ backgroundTasks(): BgTask[] {
565
+ return [...this.bg.values()];
566
+ }
567
+
568
+ // ---- implementations --------------------------------------------------
569
+
570
+ async tool_read(args: Record<string, any>): Promise<ToolResult> {
571
+ const p = this.inside(String(args.path), args.repo ? String(args.repo) : undefined);
572
+ if (!existsSync(p) || !statSync(p).isFile()) return { ok: false, output: `not a file: ${args.path}` };
573
+ const ext = p.toLowerCase().slice(p.lastIndexOf("."));
574
+ if (IMAGE_TYPES[ext]) {
575
+ // vision input: sniff magic bytes — the extension is only a hint
576
+ const size = statSync(p).size;
577
+ if (size > MAX_IMAGE_BYTES)
578
+ return { ok: false, output: `image too large (${size} bytes; max ${MAX_IMAGE_BYTES})` };
579
+ const buf = readFileSync(p);
580
+ const mediaType = sniffImage(buf);
581
+ if (!mediaType)
582
+ return { ok: false, output: `${args.path} has an image extension but isn't a png/jpeg/gif/webp file` };
583
+ return {
584
+ ok: true,
585
+ output: `read image ${args.path} (${mediaType}, ${size} bytes)`,
586
+ content: [{ type: "text", text: `[image ${args.path}]` }, { type: "image", data: buf.toString("base64"), mediaType }],
587
+ };
588
+ }
589
+ const size = statSync(p).size;
590
+ // Streaming read for large files (>100KB): reads in 64KB chunks
591
+ if (size > 100_000) {
592
+ return this._toolReadStreaming(p, args);
593
+ }
594
+ let text: string;
595
+ try { text = readFileSync(p, "utf8"); } catch { return { ok: false, output: `${args.path} is not UTF-8 text` }; }
596
+ const lines = text.split("\n");
597
+ const offset = Math.max(1, Number(args.offset ?? 1));
598
+ const limit = Math.max(1, Number(args.limit ?? 2000));
599
+ const chunk = lines.slice(offset - 1, offset - 1 + limit);
600
+ let out = chunk.map((ln, i) => `${String(offset + i).padStart(5)}\t${ln}`).join("\n");
601
+ const remaining = Math.max(0, lines.length - (offset - 1) - chunk.length);
602
+ if (remaining || text.length > MAX_READ_BYTES) out += `\n... [${remaining} more lines]`;
603
+ return { ok: true, output: out || "(empty file)" };
604
+ }
605
+
606
+ private async _toolReadStreaming(p: string, args: Record<string, any>): Promise<ToolResult> {
607
+ const fd = await open(p, "r");
608
+ try {
609
+ const chunks: Buffer[] = [];
610
+ let bytesRead = 0;
611
+ const chunkSize = 64_000;
612
+ const stat = await fd.stat();
613
+ const maxBytes = Math.min(stat.size, MAX_READ_BYTES);
614
+ while (bytesRead < maxBytes) {
615
+ const remaining = Math.min(chunkSize, maxBytes - bytesRead);
616
+ const buf = Buffer.alloc(remaining);
617
+ const { bytesRead: n } = await fd.read(buf, 0, remaining, bytesRead);
618
+ if (n === 0) break;
619
+ chunks.push(buf.subarray(0, n));
620
+ bytesRead += n;
621
+ }
622
+ const text = Buffer.concat(chunks).toString("utf8");
623
+ const lines = text.split("\n");
624
+ const offset = Math.max(1, Number(args.offset ?? 1));
625
+ const limit = Math.max(1, Number(args.limit ?? 2000));
626
+ const chunk = lines.slice(offset - 1, offset - 1 + limit);
627
+ let out = chunk.map((ln, i) => `${String(offset + i).padStart(5)}\t${ln}`).join("\n");
628
+ const remaining = Math.max(0, lines.length - (offset - 1) - chunk.length);
629
+ if (remaining || stat.size > MAX_READ_BYTES) out += `\n... [${remaining} more lines]`;
630
+ return { ok: true, output: out || "(empty file)" };
631
+ } finally {
632
+ await fd.close();
633
+ }
634
+ }
635
+
636
+ async tool_write(args: Record<string, any>): Promise<ToolResult> {
637
+ let p: string;
638
+ try { p = this.inside(String(args.path), args.repo ? String(args.repo) : undefined); }
639
+ catch (e: any) { return { ok: false, output: e.message }; }
640
+ // Rules match the raw arg AND the resolved display path (repo/...) — a
641
+ // deny like Edit(src/**) must not be defeated by workspace repo prefixes.
642
+ const denied = await this.ask("write", { ...args, _rulePaths: this.ruleForms(p) });
643
+ if (denied) return denied;
644
+ mkdirSync(dirname(p), { recursive: true });
645
+ const existed = existsSync(p);
646
+ const before = existed ? readFileSync(p, "utf8") : "";
647
+ const content = String(args.content ?? "");
648
+ // Streaming write for large files (>500KB): write in 128KB chunks via fd.write
649
+ if (content.length > 500_000) {
650
+ const fd = await open(p, "w");
651
+ try {
652
+ const chunkSize = 128_000;
653
+ for (let i = 0; i < content.length; i += chunkSize) {
654
+ await fd.write(content.slice(i, i + chunkSize));
655
+ }
656
+ } finally {
657
+ await fd.close();
658
+ }
659
+ } else {
660
+ writeFileSync(p, content, "utf8");
661
+ }
662
+ this.snap(p, existed, before, content);
663
+ const n = content.split("\n").length;
664
+ return { ok: true, output: `${existed ? "updated" : "created"} ${args.path} (${n} lines)` };
665
+ }
666
+
667
+ async tool_edit(args: Record<string, any>): Promise<ToolResult> {
668
+ let p: string;
669
+ try { p = this.inside(String(args.path), args.repo ? String(args.repo) : undefined); }
670
+ catch (e: any) { return { ok: false, output: e.message }; }
671
+ const denied = await this.ask("edit", { ...args, _rulePaths: this.ruleForms(p) });
672
+ if (denied) return denied;
673
+ if (!existsSync(p)) return { ok: false, output: `not a file: ${args.path}` };
674
+ const size = statSync(p).size;
675
+ // Streaming edit for large files (>100KB): read only relevant line range around the match
676
+ if (size > 100_000) {
677
+ const totalLines = await countLines(p);
678
+ // Find the match position by reading in chunks to locate old_string
679
+ const fd = await open(p, "r");
680
+ let text: string;
681
+ try {
682
+ const chunks: Buffer[] = [];
683
+ let bytesRead = 0;
684
+ const chunkSize = 64_000;
685
+ const maxBytes = Math.min(size, MAX_READ_BYTES);
686
+ while (bytesRead < maxBytes) {
687
+ const remaining = Math.min(chunkSize, maxBytes - bytesRead);
688
+ const buf = Buffer.alloc(remaining);
689
+ const { bytesRead: n } = await fd.read(buf, 0, remaining, bytesRead);
690
+ if (n === 0) break;
691
+ chunks.push(buf.subarray(0, n));
692
+ bytesRead += n;
693
+ }
694
+ text = Buffer.concat(chunks).toString("utf8");
695
+ } finally {
696
+ await fd.close();
697
+ }
698
+ const old = String(args.old_string ?? ""), neu = String(args.new_string ?? "");
699
+ const count = text.split(old).length - 1;
700
+ if (count === 0) return { ok: false, output: "old_string not found in file" };
701
+ if (count > 1) return { ok: false, output: `old_string matches ${count} times; make it unique` };
702
+ const after = text.replace(old, neu);
703
+ // Stream write the result
704
+ if (after.length > 500_000) {
705
+ const wfd = await open(p, "w");
706
+ try {
707
+ const chunkSize = 128_000;
708
+ for (let i = 0; i < after.length; i += chunkSize) {
709
+ await wfd.write(after.slice(i, i + chunkSize));
710
+ }
711
+ } finally {
712
+ await wfd.close();
713
+ }
714
+ } else {
715
+ writeFileSync(p, after, "utf8");
716
+ }
717
+ this.snap(p, true, text, after);
718
+ return { ok: true, output: `edited ${args.path}` };
719
+ }
720
+ const text = readFileSync(p, "utf8");
721
+ const old = String(args.old_string ?? ""), neu = String(args.new_string ?? "");
722
+ const count = text.split(old).length - 1;
723
+ if (count === 0) return { ok: false, output: "old_string not found in file" };
724
+ if (count > 1) return { ok: false, output: `old_string matches ${count} times; make it unique` };
725
+ const after = text.replace(old, neu);
726
+ writeFileSync(p, after, "utf8");
727
+ this.snap(p, true, text, after);
728
+ return { ok: true, output: `edited ${args.path}` };
729
+ }
730
+
731
+ /**
732
+ * Atomic multi-hunk edit: applies every {old_string,new_string} pair to one
733
+ * file in order, all-or-nothing — if any hunk fails to match (or matches
734
+ * non-uniquely) NOTHING is written. Hunks apply sequentially, so a later
735
+ * hunk may match text an earlier hunk produced. Single undo record covers
736
+ * the whole batch.
737
+ */
738
+ async tool_multiedit(args: Record<string, any>): Promise<ToolResult> {
739
+ let p: string;
740
+ try { p = this.inside(String(args.path), args.repo ? String(args.repo) : undefined); }
741
+ catch (e: any) { return { ok: false, output: e.message }; }
742
+ const denied = await this.ask("multiedit", { ...args, _rulePaths: this.ruleForms(p) });
743
+ if (denied) return denied;
744
+ if (!existsSync(p)) return { ok: false, output: `not a file: ${args.path}` };
745
+ const edits = Array.isArray(args.edits) ? args.edits : [];
746
+ if (!edits.length) return { ok: false, output: "edits must be a non-empty array of {old_string, new_string}" };
747
+ if (edits.length > 200) return { ok: false, output: `too many edits (${edits.length}); split across multiple multiedit calls` };
748
+
749
+ const original = readFileSync(p, "utf8");
750
+ let text = original;
751
+ const applied: Array<{ old: string; neu: string }> = [];
752
+ for (let i = 0; i < edits.length; i++) {
753
+ const e = edits[i];
754
+ if (!e || typeof e !== "object") return { ok: false, output: `edits[${i}] is not an object` };
755
+ const old = String(e.old_string ?? "");
756
+ const neu = String(e.new_string ?? "");
757
+ if (!old) return { ok: false, output: `edits[${i}].old_string is empty (use the write tool to replace a whole file)` };
758
+ const count = text.split(old).length - 1;
759
+ if (count === 0)
760
+ return { ok: false, output: `edits[${i}]: old_string not found — NOTHING was written (all-or-nothing). Read the file and retry with corrected hunks.` };
761
+ if (count > 1 && e.replace_all !== true)
762
+ return { ok: false, output: `edits[${i}]: old_string matches ${count} times — make it unique or pass replace_all:true. NOTHING was written.` };
763
+ text = e.replace_all === true ? text.split(old).join(neu) : text.replace(old, neu);
764
+ applied.push({ old, neu });
765
+ }
766
+ if (text === original) return { ok: true, output: `multiedit ${args.path}: no changes (all hunks were no-ops)` };
767
+ writeFileSync(p, text, "utf8");
768
+ this.snap(p, true, original, text);
769
+ return { ok: true, output: `multiedit ${args.path}: ${applied.length} edit${applied.length === 1 ? "" : "s"} applied` };
770
+ }
771
+
772
+ tool_bash(args: Record<string, any>): Promise<ToolResult> {
773
+ return new Promise(async (done) => {
774
+ const denied = await this.ask("bash", args);
775
+ if (denied) return done(denied);
776
+ const cmd = String(args.command ?? "");
777
+ const timeout = Math.min(Number(args.timeout ?? BASH_TIMEOUT), 600) * 1000;
778
+ if (args.background === true) {
779
+ const task = this.startBg(cmd, timeout);
780
+ return done({ ok: true, output: `started background task ${task.id} (${cmd}) — check with the tasks tool or ctrl+t` });
781
+ }
782
+ const shell = process.platform === "win32" ? (process.env.COMSPEC || "cmd.exe") : "/bin/bash";
783
+ const child = spawn(shell, process.platform === "win32" ? ["/c", cmd] : ["-c", cmd], {
784
+ cwd: this.root, env: process.env,
785
+ });
786
+ let out = "", err = "";
787
+ // live output: forward merged stdout/stderr to toolEvent subscribers as
788
+ // line-delimited chunks so long builds render progressively in the UI.
789
+ // Deltas reuse dispatch's callId so the UI attaches them to the right row.
790
+ let lineBuf = "";
791
+ let streamed = 0;
792
+ const bashCallId = this.currentCallId ?? `bash_${Date.now().toString(36)}`;
793
+ const streamOut = (chunk: string) => {
794
+ lineBuf += chunk;
795
+ let nl: number;
796
+ while ((nl = lineBuf.indexOf("\n")) >= 0) {
797
+ const line = lineBuf.slice(0, nl + 1);
798
+ lineBuf = lineBuf.slice(nl + 1);
799
+ streamed += line.length;
800
+ if (streamed <= MAX_BASH_STREAM) this.emitToolEvent({ kind: "output", callId: bashCallId, tool: "bash", text: line });
801
+ }
802
+ };
803
+ const timer = setTimeout(() => { child.kill(); done({ ok: false, output: `command timed out after ${timeout / 1000}s` }); }, timeout);
804
+ child.stdout.on("data", (d) => { out += d; streamOut(d.toString()); });
805
+ child.stderr.on("data", (d) => { err += d; streamOut(d.toString()); });
806
+ child.on("close", (code) => {
807
+ clearTimeout(timer);
808
+ if (lineBuf) streamOut("\n");
809
+ const combined = out + (err ? `\n[stderr]\n${err}` : "");
810
+ // keep head AND tail: for builds/tests the actionable error is at the end
811
+ const capped = combined.length > MAX_BASH_OUTPUT
812
+ ? combined.slice(0, MAX_BASH_OUTPUT * 0.6) +
813
+ `\n\n… ${(combined.length - MAX_BASH_OUTPUT * 0.7) | 0} bytes elided (tail kept) …\n\n` +
814
+ combined.slice(-MAX_BASH_OUTPUT * 0.4)
815
+ : combined;
816
+ const tail = code === 0 ? "" : `\n[exit code ${code}]`;
817
+ done({ ok: code === 0, output: (capped.trim() || "(no output)") + tail });
818
+ });
819
+ child.on("error", (e) => {
820
+ clearTimeout(timer);
821
+ done({ ok: false, output: `spawn failed: ${e.message}` });
822
+ });
823
+ });
824
+ }
825
+
826
+ async tool_webfetch(args: Record<string, any>): Promise<ToolResult> {
827
+ const raw = String(args.url ?? "");
828
+ let url: URL;
829
+ try { url = new URL(raw); } catch { return { ok: false, output: `invalid url: ${raw}` }; }
830
+ if (url.protocol !== "http:" && url.protocol !== "https:")
831
+ return { ok: false, output: `only http(s) allowed, got ${url.protocol}` };
832
+ // SSRF guard: block private/localhost targets (GOAT MODE lifts it too)
833
+ const host = url.hostname.toLowerCase();
834
+ if (!this.goat && await isPrivateHost(host))
835
+ return { ok: false, output: `refused private/loopback address: ${host}` };
836
+ const denied = await this.ask("webfetch", args); // WebFetch(domain:x) rules apply
837
+ if (denied) return denied;
838
+ try {
839
+ const res = await fetch(url.toString(), {
840
+ redirect: "follow", signal: AbortSignal.timeout(WEBFETCH_TIMEOUT_MS),
841
+ headers: { "user-agent": "goatcode/2.0 (+https://github.com/Arhan-w/GoatCode)" },
842
+ });
843
+ if (!res.ok) return { ok: false, output: `HTTP ${res.status} ${res.statusText}` };
844
+ const ct = res.headers.get("content-type") ?? "";
845
+ if (!/text|json|xml|markdown|html/.test(ct))
846
+ return { ok: false, output: `unsupported content-type: ${ct}` };
847
+ let text = await res.text();
848
+ if (ct.includes("html")) {
849
+ text = text
850
+ .replace(/<script[\s\S]*?<\/script>|<style[\s\S]*?<\/style>|<!--[\s\S]*?-->/gi, " ")
851
+ .replace(/<[^>]+>/g, " ")
852
+ .replace(/&amp;|&#38;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">")
853
+ .replace(/&quot;/g, '"').replace(/&#39;|&apos;/g, "'").replace(/&nbsp;/g, " ")
854
+ .replace(/[ \t]+/g, " ").replace(/\n{3,}/g, "\n\n").trim();
855
+ }
856
+ const clipped = text.slice(0, MAX_WEBFETCH_BYTES);
857
+ const more = text.length > clipped.length ? `\n... [truncated from ${text.length} bytes]` : "";
858
+ const ask = args.prompt ? `\n\n[Look for: ${String(args.prompt).slice(0, 300)}]` : "";
859
+ return { ok: true, output: `# ${url.hostname} — ${ct.split(";")[0]}\n${clipped}${more}${ask}` };
860
+ } catch (e: any) {
861
+ return { ok: false, output: `fetch failed: ${e?.message ?? e}` };
862
+ }
863
+ }
864
+
865
+ /** Keyless web search via DuckDuckGo's HTML endpoint (also lite fallback). */
866
+ async tool_websearch(args: Record<string, any>): Promise<ToolResult> {
867
+ const query = String(args.query ?? "").trim();
868
+ if (!query) return { ok: false, output: "websearch requires a query" };
869
+ const denied = await this.ask("websearch", args);
870
+ if (denied) return denied;
871
+ const max = Math.min(15, Math.max(1, Number(args.max_results ?? 8)));
872
+ try {
873
+ const res = await fetch("https://html.duckduckgo.com/html/", {
874
+ method: "POST",
875
+ headers: {
876
+ "content-type": "application/x-www-form-urlencoded",
877
+ "user-agent": "Mozilla/5.0 (X11; Linux x86_64) goatcode/2.0",
878
+ },
879
+ body: new URLSearchParams({ q: query, kl: "wt-wat" } as any).toString(),
880
+ redirect: "follow",
881
+ signal: AbortSignal.timeout(WEBFETCH_TIMEOUT_MS),
882
+ });
883
+ if (!res.ok) return { ok: false, output: `search failed: HTTP ${res.status}` };
884
+ const html = await res.text();
885
+ // result anchors: <a rel="nofollow" class="result__a" href="...">Title</a>
886
+ // + snippet: <a class="result__snippet">...</a>
887
+ const results: { title: string; url: string; snippet: string }[] = [];
888
+ const linkRe = /<a[^>]*class="result__a"[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/g;
889
+ const snipRe = /<a[^>]*class="result__snippet"[^>]*>([\s\S]*?)<\/a>/g;
890
+ const snippets: string[] = [];
891
+ for (const s of html.matchAll(snipRe)) snippets.push(stripTags(s[1]).trim());
892
+ let k = 0;
893
+ for (const m of html.matchAll(linkRe)) {
894
+ if (results.length >= max) break;
895
+ let url = m[1];
896
+ // ddg wraps links: //duckduckgo.com/l/?uddg=<encoded>&rut=...
897
+ const um = url.match(/[?&]uddg=([^&]+)/);
898
+ if (um) { try { url = decodeURIComponent(um[1]); } catch { /* keep raw */ } }
899
+ results.push({ title: stripTags(m[2]).trim(), url, snippet: snippets[k++] ?? "" });
900
+ }
901
+ if (!results.length) return { ok: false, output: `no results for "${query}" (search endpoint may be rate-limited — try webfetch on a known URL)` };
902
+ const lines = results.map((r, i) =>
903
+ `${i + 1}. ${r.title}\n ${r.url}${r.snippet ? `\n ${r.snippet.slice(0, 240)}` : ""}`);
904
+ return { ok: true, output: `# results for: ${query}\n${lines.join("\n")}\n\n[Use webfetch to read a result in full.]` };
905
+ } catch (e: any) {
906
+ return { ok: false, output: `search failed: ${e?.message ?? e}` };
907
+ }
908
+ }
909
+
910
+ // ---- desktop control ----------------------------------------------------
911
+
912
+ /** Capture the real screen; attach the PNG so vision models can see it. */
913
+ async tool_screenshot(args: Record<string, any>): Promise<ToolResult> {
914
+ const denied = await this.ask("computer", { action: "screenshot" });
915
+ if (denied) return denied;
916
+ try {
917
+ const out = join(this.root, ".goat", `screen-${Date.now()}.png`);
918
+ mkdirSync(dirname(out), { recursive: true });
919
+ const shot = await desktop.screenshot(out);
920
+ const rel = relative(this.root, out).replaceAll("\\", "/");
921
+ const dims = shot.width ? ` ${shot.width}x${shot.height}px` : "";
922
+ if (args.path) { // save a copy somewhere the user asked for
923
+ try { writeFileSync(this.inside(String(args.path)), shot.png); } catch { /* non-sandbox save */ }
924
+ }
925
+ return {
926
+ ok: true,
927
+ output: `screen captured (${dims}, ${shot.png.length} bytes) → ${rel}`,
928
+ content: [
929
+ { type: "text", text: `[screenshot${dims} — saved to ${rel}; click coordinates are screen pixels]` },
930
+ { type: "image", data: shot.png.toString("base64"), mediaType: "image/png" },
931
+ ],
932
+ };
933
+ } catch (e: any) {
934
+ return { ok: false, output: `screenshot failed: ${e?.message ?? e} (backend: ${await desktop.detect()})` };
935
+ }
936
+ }
937
+
938
+ /** One tool for every desktop action: click / type / key / scroll / launch / windows / clipboard. */
939
+ async tool_computer(args: Record<string, any>): Promise<ToolResult> {
940
+ const action = String(args.action ?? "");
941
+ if (!action) return { ok: false, output: "computer requires an action" };
942
+ const denied = await this.ask("computer", args);
943
+ if (denied) return denied;
944
+ try {
945
+ const msg = await desktop.act(action, args);
946
+ const backend = desktop.backend as DesktopBackend;
947
+ return { ok: true, output: `[${backend}] ${msg}` };
948
+ } catch (e: any) {
949
+ return { ok: false, output: `computer ${action} failed: ${e?.message ?? e}` };
950
+ }
951
+ }
952
+
953
+ tool_undo(): ToolResult {
954
+ if (this.readonly)
955
+ return { ok: false, output: "undo blocked by plan mode — the user can still run /undo from the prompt" };
956
+ const rec = this.undo();
957
+ if (!rec) return { ok: false, output: "nothing to undo" };
958
+ const shown = this.displayPath(rec.path);
959
+ return { ok: true, output: `reverted ${shown}${rec.existed ? "" : " (deleted — file was created this session)"}` };
960
+ }
961
+
962
+ tool_tasks(): ToolResult {
963
+ const rows = this.backgroundTasks();
964
+ if (!rows.length) return { ok: true, output: "(no background tasks)" };
965
+ return {
966
+ ok: true,
967
+ output: rows.map((r) =>
968
+ `${r.id}\t${new Date(r.started).toISOString().slice(11, 19)}\t${r.cmd.slice(0, 60)}\t=> ${r.status.slice(0, 400)}`,
969
+ ).join("\n"),
970
+ };
971
+ }
972
+
973
+ /** Current plan (for UI rendering). */
974
+ plan(): Todo[] {
975
+ return this.todos.map((t) => ({ ...t }));
976
+ }
977
+
978
+ tool_todo(args: Record<string, any>): ToolResult {
979
+ const raw = Array.isArray(args.todos) ? args.todos : [];
980
+ const todos: Todo[] = [];
981
+ for (const t of raw.slice(0, 64)) {
982
+ if (!t || typeof t !== "object") continue;
983
+ const content = String(t.content ?? "").slice(0, 500);
984
+ if (!content) continue;
985
+ const activeForm = String(t.activeForm ?? t.active_form ?? content).slice(0, 500);
986
+ const s = t.status === "completed" || t.status === "in_progress" ? t.status : "pending";
987
+ todos.push({ content, activeForm, status: s });
988
+ }
989
+ if (!todos.length) return { ok: false, output: "todos must be a non-empty array of {content, activeForm, status}" };
990
+ this.todos = todos;
991
+ const done = todos.filter((t) => t.status === "completed").length;
992
+ return { ok: true, output: `plan updated: ${done}/${todos.length} completed` };
993
+ }
994
+
995
+ tool_glob(args: Record<string, any>): ToolResult {
996
+ let pattern = String(args.pattern ?? "");
997
+ const matches: string[] = [];
998
+ const seen = new Set<string>();
999
+ // repo-prefixed pattern narrows to that repo: "api/src/**/*.ts"
1000
+ let bases: Array<{ disp: string; root: string }>; // display prefix + search root
1001
+ const slash = pattern.indexOf("/");
1002
+ const head = slash > 0 ? pattern.slice(0, slash) : "";
1003
+ if (this.roots.size && head && this.roots.has(head)) {
1004
+ bases = [{ disp: head + "/", root: this.roots.get(head)! }];
1005
+ pattern = pattern.slice(slash + 1);
1006
+ } else if (this.roots.size) {
1007
+ bases = [{ disp: "", root: this.root }, ...[...this.roots].map(([n, r]) => ({ disp: n + "/", root: r }))];
1008
+ } else {
1009
+ bases = [{ disp: "", root: this.root }];
1010
+ }
1011
+ for (const { disp, root: base } of bases) {
1012
+ const walkAbs = (dir: string) => {
1013
+ let entries;
1014
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
1015
+ for (const e of entries) {
1016
+ if (matches.length >= GLOB_MAX_RESULTS) return;
1017
+ const abs = join(dir, e.name);
1018
+ if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name)) walkAbs(abs); }
1019
+ else {
1020
+ // Dedupe by absolute path: a repo nested under the primary root is
1021
+ // reached by both the root walk and the per-repo walk.
1022
+ if (seen.has(abs)) continue;
1023
+ const rel = relative(base, abs).replaceAll("\\", "/");
1024
+ if (fnmatch(rel, pattern) || fnmatch(e.name, pattern)) {
1025
+ seen.add(abs);
1026
+ matches.push(disp + rel);
1027
+ }
1028
+ }
1029
+ }
1030
+ };
1031
+ walkAbs(base);
1032
+ }
1033
+ return { ok: true, output: matches.sort().join("\n") + (matches.length >= GLOB_MAX_RESULTS ? "\n... (truncated)" : "") || "(no matches)" };
1034
+ }
1035
+
1036
+ tool_grep(args: Record<string, any>): ToolResult {
1037
+ let rx: RegExp;
1038
+ try { rx = new RegExp(String(args.pattern)); }
1039
+ catch (e: any) { return { ok: false, output: `invalid regex: ${e.message}` }; }
1040
+ const glob = args.glob ? String(args.glob) : null;
1041
+ const results: string[] = [];
1042
+ const seenAbs = new Set<string>();
1043
+ // scope: explicit repo arg, or ALL roots when multiRepo and no path given
1044
+ let scope: Array<{ root: string }>;
1045
+ const pathArg = args.path ? String(args.path) : null;
1046
+ if (args.repo) {
1047
+ const r = this.roots.get(String(args.repo));
1048
+ if (!r) return { ok: false, output: `unknown repo "${args.repo}"` };
1049
+ scope = [{ root: pathArg ? insideRoot(r, pathArg) : r }];
1050
+ } else if (pathArg) {
1051
+ const base = this.inside(pathArg);
1052
+ scope = [{ root: base }];
1053
+ } else if (this.roots.size) {
1054
+ // root + every repo; files in a repo nested under root are reached twice —
1055
+ // seenAbs dedupes them (and displayPath names each once, repo-prefixed).
1056
+ scope = [{ root: this.root }, ...[...this.roots].map(([, r]) => ({ root: r }))];
1057
+ } else {
1058
+ scope = [{ root: this.root }];
1059
+ }
1060
+ for (const { root } of scope) {
1061
+ const scan = (dir: string) => {
1062
+ let entries;
1063
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
1064
+ for (const e of entries) {
1065
+ if (results.length >= GREP_MAX_RESULTS) return;
1066
+ const abs = join(dir, e.name);
1067
+ if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name)) scan(abs); }
1068
+ else {
1069
+ if (seenAbs.has(abs)) continue;
1070
+ if (glob && !fnmatch(e.name, glob)) continue;
1071
+ let text: string;
1072
+ try {
1073
+ if (statSync(abs).size > 2_000_000) continue;
1074
+ text = readFileSync(abs, "utf8");
1075
+ if (text.includes("\0")) continue; // binary
1076
+ } catch { continue; }
1077
+ seenAbs.add(abs);
1078
+ text.split("\n").forEach((line, i) => {
1079
+ if (results.length >= GREP_MAX_RESULTS) return;
1080
+ if (rx.test(line)) {
1081
+ results.push(`${this.displayPath(abs)}:${i + 1}:${line.slice(0, 200)}`);
1082
+ }
1083
+ });
1084
+ }
1085
+ }
1086
+ };
1087
+ scan(root);
1088
+ }
1089
+ return { ok: true, output: results.join("\n") + (results.length >= GREP_MAX_RESULTS ? "\n... (truncated)" : "") || "(no matches)" };
1090
+ }
1091
+ }
1092
+
1093
+ /** Dependency resolver: maps tool name → read/write set functions.
1094
+ * Used by the parallel scheduler in agent.ts to detect conflicts. */
1095
+ interface ToolDeps {
1096
+ readSet: (args: Record<string, unknown>) => string[];
1097
+ writeSet: (args: Record<string, unknown>) => string[];
1098
+ }
1099
+
1100
+ const TOOL_DEPS: Record<string, ToolDeps> = {
1101
+ read: {
1102
+ readSet: (args) => [`file:${String(args.path ?? "")}`],
1103
+ writeSet: () => [],
1104
+ },
1105
+ write: {
1106
+ readSet: () => [],
1107
+ writeSet: (args) => [`file:${String(args.path ?? "")}`],
1108
+ },
1109
+ edit: {
1110
+ readSet: () => [],
1111
+ writeSet: (args) => [`file:${String(args.path ?? "")}`],
1112
+ },
1113
+ multiedit: {
1114
+ readSet: () => [],
1115
+ writeSet: (args) => [`file:${String(args.path ?? "")}`],
1116
+ },
1117
+ bash: {
1118
+ readSet: (args) => [`cmd:${String(args.command ?? "").slice(0, 64)}`],
1119
+ writeSet: (args) => [`cmd:${String(args.command ?? "").slice(0, 64)}`],
1120
+ },
1121
+ undo: {
1122
+ readSet: () => [],
1123
+ writeSet: () => ["__undo__"],
1124
+ },
1125
+ tasks: {
1126
+ readSet: () => ["__tasks__"],
1127
+ writeSet: () => [],
1128
+ },
1129
+ glob: {
1130
+ readSet: () => ["__filesystem__"],
1131
+ writeSet: () => [],
1132
+ },
1133
+ grep: {
1134
+ readSet: () => ["__filesystem__"],
1135
+ writeSet: () => [],
1136
+ },
1137
+ task: {
1138
+ readSet: () => [],
1139
+ writeSet: () => [],
1140
+ },
1141
+ webfetch: {
1142
+ readSet: (args) => [`url:${String(args.url ?? "")}`],
1143
+ writeSet: () => [],
1144
+ },
1145
+ screenshot: {
1146
+ readSet: () => ["__screen__"],
1147
+ writeSet: (args) => args.path ? [`file:${String(args.path)}`] : [],
1148
+ },
1149
+ websearch: {
1150
+ readSet: () => ["__network__"],
1151
+ writeSet: () => [],
1152
+ },
1153
+ computer: {
1154
+ readSet: () => ["__screen__", "__input__"],
1155
+ writeSet: () => ["__screen__", "__input__"],
1156
+ },
1157
+ todo: {
1158
+ readSet: () => ["__todos__"],
1159
+ writeSet: () => ["__todos__"],
1160
+ },
1161
+ };
1162
+
1163
+ /** Resolve a tool's read/write dependency sets from its name + arguments.
1164
+ * Returns empty sets for unknown tools (falls back to sequential execution). */
1165
+ export function getToolSpec(name: string, args: Record<string, unknown> = {}): { readSet: string[]; writeSet: string[] } {
1166
+ const deps = TOOL_DEPS[name];
1167
+ if (!deps) return { readSet: [], writeSet: [] };
1168
+ return {
1169
+ readSet: deps.readSet(args),
1170
+ writeSet: deps.writeSet(args),
1171
+ };
1172
+ }
1173
+
1174
+ function builtinSpecs(): ToolSpec[] {
1175
+ const repoDesc = { type: "string", description: "Workspace repo name (optional; plain paths can also start with repoName/)" };
1176
+ return [
1177
+ { name: "read", description: "Read a file from the project. Text files return numbered lines; images (png/jpg/gif/webp) are shown to the model visually. Files >100KB use streaming chunk reads.",
1178
+ parameters: { type: "object", properties: {
1179
+ path: { type: "string", description: "File path relative to project root (repo-prefixed in workspaces: api/src/x.ts)" },
1180
+ repo: repoDesc,
1181
+ offset: { type: "integer", description: "1-based start line (optional)" },
1182
+ limit: { type: "integer", description: "Max lines to read (optional)" },
1183
+ streaming: { type: "boolean", description: "Force streaming mode for large files (auto-enabled for files >100KB)" },
1184
+ }, required: ["path"] } },
1185
+ { name: "write", description: "Create or overwrite a file with exact content. The change can be reverted with undo. Files >500KB use streaming chunk writes.",
1186
+ parameters: { type: "object", properties: {
1187
+ path: { type: "string" },
1188
+ repo: repoDesc,
1189
+ content: { type: "string", description: "Full file content" },
1190
+ streaming: { type: "boolean", description: "Force streaming mode for large content (auto-enabled for content >500KB)" },
1191
+ }, required: ["path", "content"] } },
1192
+ { name: "edit", description: "Replace one exact string in a file (must match once). The change can be reverted with undo. Files >100KB use streaming line-based diff.",
1193
+ parameters: { type: "object", properties: {
1194
+ path: { type: "string" },
1195
+ repo: repoDesc,
1196
+ old_string: { type: "string", description: "Exact text to replace, unique in file" },
1197
+ new_string: { type: "string" },
1198
+ streaming: { type: "boolean", description: "Force streaming mode for large files (auto-enabled for files >100KB)" },
1199
+ }, required: ["path", "old_string", "new_string"] } },
1200
+ { name: "multiedit", description: "Apply several exact string replacements to ONE file in order, atomically — if any hunk fails, nothing is written and one undo reverts the whole batch. Later hunks see earlier hunks' output. Prefer this over repeated edit calls on the same file. Pass replace_all:true on a hunk to replace every occurrence.",
1201
+ parameters: { type: "object", properties: {
1202
+ path: { type: "string" },
1203
+ repo: repoDesc,
1204
+ edits: { type: "array", description: "Ordered hunks", items: {
1205
+ type: "object", properties: {
1206
+ old_string: { type: "string", description: "Exact text to replace, unique in the current file state" },
1207
+ new_string: { type: "string" },
1208
+ replace_all: { type: "boolean", description: "Replace every occurrence instead of requiring uniqueness" },
1209
+ }, required: ["old_string", "new_string"] } },
1210
+ }, required: ["path", "edits"] } },
1211
+ { name: "bash", description: "Run a shell command in the project directory. Set background=true for long jobs; poll results with the tasks tool.",
1212
+ parameters: { type: "object", properties: {
1213
+ command: { type: "string" },
1214
+ timeout: { type: "integer", description: `Seconds, default ${BASH_TIMEOUT}` },
1215
+ background: { type: "boolean", description: "Run detached, return a task id immediately" },
1216
+ }, required: ["command"] } },
1217
+ { name: "undo", description: "Revert the most recent write/edit made in this session.",
1218
+ parameters: { type: "object", properties: {} } },
1219
+ { name: "tasks", description: "List background bash tasks and their status.",
1220
+ parameters: { type: "object", properties: {} } },
1221
+ { name: "glob", description: "Find files by pattern, e.g. 'src/**/*.ts'. In a workspace, scans ALL repos and returns repoName/ paths (prefix the pattern with a repo name to narrow).",
1222
+ parameters: { type: "object", properties: { pattern: { type: "string" } }, required: ["pattern"] } },
1223
+ { name: "grep", description: "Search file contents by regex. Returns path:line:text. In a workspace with no path/repo arg, scans ALL repos. Always prefer this over bash grep/find.",
1224
+ parameters: { type: "object", properties: {
1225
+ pattern: { type: "string", description: "Regex" },
1226
+ path: { type: "string", description: "Subdirectory to search (default .)" },
1227
+ repo: { type: "string", description: "Limit to a workspace repo" },
1228
+ glob: { type: "string", description: "Filename filter, e.g. '*.py'" },
1229
+ }, required: ["pattern"] } },
1230
+ { name: "task", description:
1231
+ "Launch a focused sub-agent with a fresh context that shares your tools. It has ZERO knowledge of this conversation — brief it completely. EMIT MULTIPLE task calls in ONE message to fan them out in parallel (up to 8 at once). Use for research/exploration (subagent_type 'explore' = read-only), self-contained multi-step work ('general' = full tools), or a custom agent type (listed in the system prompt) for its specialized persona.",
1232
+ parameters: { type: "object", properties: {
1233
+ description: { type: "string", description: "3-5 word label" },
1234
+ prompt: { type: "string", description: "Full task brief for the sub-agent" },
1235
+ subagent_type: { type: "string", description: "'explore' (read-only), 'general' (full tools, default), or a custom agent name" },
1236
+ }, required: ["description", "prompt"] } },
1237
+ { name: "webfetch", description: "Fetch a URL and return readable text. Blocked for private/localhost addresses.",
1238
+ parameters: { type: "object", properties: {
1239
+ url: { type: "string", description: "http(s) URL" },
1240
+ prompt: { type: "string", description: "What to look for (returned alongside the text; text is truncated to 200 KB)" },
1241
+ }, required: ["url"] } },
1242
+ { name: "screenshot", description:
1243
+ "Capture the real desktop screen and SEE it (the image is attached to your next turn on vision models). Coordinates for the computer tool are screen pixels from this image. Optional path saves a copy into the project.",
1244
+ parameters: { type: "object", properties: {
1245
+ path: { type: "string", description: "Optional project-relative path to save the PNG" },
1246
+ } } },
1247
+ { name: "websearch", description:
1248
+ "Search the web (DuckDuckGo) and get titles, URLs, snippets. No API key needed. Use for current events, library docs, error messages. Then webfetch the best result for details.",
1249
+ parameters: { type: "object", properties: {
1250
+ query: { type: "string", description: "Search query" },
1251
+ max_results: { type: "integer", description: "1-15 results (default 8)" },
1252
+ }, required: ["query"] } },
1253
+ { name: "computer", description:
1254
+ "Control the user's desktop like a person: click, type, press keys, scroll, launch apps, list windows, read/write the clipboard. Workflow: screenshot first to see the screen -> act with coordinates from that image -> screenshot again to verify. Background-first when a driver is installed (no focus steal). NEVER click permission/payment/password dialogs or type secrets; stop and ask the user instead.",
1255
+ parameters: { type: "object", properties: {
1256
+ action: { type: "string", enum: ["click", "double_click", "right_click", "type", "key", "scroll", "launch", "windows", "clipboard"],
1257
+ description: "What to do" },
1258
+ x: { type: "integer", description: "Screen x pixel (click/scroll) from the last screenshot" },
1259
+ y: { type: "integer", description: "Screen y pixel" },
1260
+ text: { type: "string", description: "Text to type, or clipboard content to set" },
1261
+ combo: { type: "string", description: "key action: e.g. 'ctrl+s', 'alt+tab', 'enter'" },
1262
+ direction: { type: "string", enum: ["up", "down", "left", "right"], description: "scroll direction" },
1263
+ amount: { type: "integer", description: "scroll ticks (default 3)" },
1264
+ app: { type: "string", description: "launch: app name or full path" },
1265
+ pid: { type: "integer", description: "Target process id (from the windows action) — required for type on Windows via driver; clicks route to the window under the point" },
1266
+ window_title: { type: "string", description: "Alternative to pid: case-insensitive substring of the window title to target (type/key)" },
1267
+ }, required: ["action"] } },
1268
+ { name: "todo", description:
1269
+ "Create and manage a structured task list for the current work. Use proactively for multi-step tasks (3+ steps); update statuses in real time — mark a task in_progress BEFORE starting it and completed IMMEDIATELY after, exactly one in_progress at a time. Skip it for single trivial tasks. Do not batch completions. The list is shown live to the user.",
1270
+ parameters: { type: "object", properties: {
1271
+ todos: { type: "array", description: "The FULL replacement list (send the whole plan every time)", items: {
1272
+ type: "object", properties: {
1273
+ content: { type: "string", description: "Imperative form, e.g. 'Run tests'" },
1274
+ activeForm: { type: "string", description: "Present continuous shown while running, e.g. 'Running tests'" },
1275
+ status: { type: "string", enum: ["pending", "in_progress", "completed"] },
1276
+ }, required: ["content", "activeForm", "status"] },
1277
+ },
1278
+ }, required: ["todos"] } },
1279
+ ];
1280
+ }