@wraith-ai/core 0.1.0 → 0.1.1

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 (153) hide show
  1. package/README.md +1 -1
  2. package/dist/{attempt-BeB7EltG.d.mts → attempt-HgararU3.d.mts} +2 -1
  3. package/dist/attempt-HgararU3.d.mts.map +1 -0
  4. package/dist/{capabilities-BPb5HSH6.d.mts → capabilities-CNsPrkB7.d.mts} +2 -1
  5. package/dist/capabilities-CNsPrkB7.d.mts.map +1 -0
  6. package/dist/index.d.mts +6 -5
  7. package/dist/index.d.mts.map +1 -0
  8. package/dist/index.mjs +11 -9
  9. package/dist/index.mjs.map +1 -0
  10. package/dist/{methods-CZp6XGn8.mjs → methods-7Ryz6zbd.mjs} +4 -2
  11. package/dist/methods-7Ryz6zbd.mjs.map +1 -0
  12. package/dist/{model-B6tJ9kX_.mjs → model-C16NUwXW.mjs} +2 -0
  13. package/dist/model-C16NUwXW.mjs.map +1 -0
  14. package/dist/{model-D6LQSveS.d.mts → model-_wqePNTL.d.mts} +4 -3
  15. package/dist/model-_wqePNTL.d.mts.map +1 -0
  16. package/dist/{models-dev-Y0ZikMBQ.d.mts → models-dev-DNgymZy3.d.mts} +3 -2
  17. package/dist/models-dev-DNgymZy3.d.mts.map +1 -0
  18. package/dist/{openai-codex-BhtZvNpm.mjs → openai-codex-Bz1EFPEi.mjs} +3 -1
  19. package/dist/openai-codex-Bz1EFPEi.mjs.map +1 -0
  20. package/dist/{openai-codex-Bk-iG7MZ.mjs → openai-codex-uvjhVoVy.mjs} +6 -4
  21. package/dist/openai-codex-uvjhVoVy.mjs.map +1 -0
  22. package/dist/{openai-compatible-hkXv-P74.mjs → openai-compatible-DBppnQ_N.mjs} +4 -2
  23. package/dist/openai-compatible-DBppnQ_N.mjs.map +1 -0
  24. package/dist/{openrouter-BflQBug2.mjs → openrouter-D8nTOAQo.mjs} +5 -3
  25. package/dist/openrouter-D8nTOAQo.mjs.map +1 -0
  26. package/dist/providers/openai-codex.d.mts +4 -3
  27. package/dist/providers/openai-codex.d.mts.map +1 -0
  28. package/dist/providers/openai-codex.mjs +1 -1
  29. package/dist/providers/openai-compatible.d.mts +3 -2
  30. package/dist/providers/openai-compatible.d.mts.map +1 -0
  31. package/dist/providers/openai-compatible.mjs +1 -1
  32. package/dist/providers/openrouter.d.mts +3 -2
  33. package/dist/providers/openrouter.d.mts.map +1 -0
  34. package/dist/providers/openrouter.mjs +1 -1
  35. package/dist/{shared-8d7RsyPH.mjs → shared-BIJaPhMm.mjs} +3 -1
  36. package/dist/shared-BIJaPhMm.mjs.map +1 -0
  37. package/dist/snapshot.d.mts +3 -2
  38. package/dist/snapshot.d.mts.map +1 -0
  39. package/dist/snapshot.mjs +4999 -4977
  40. package/dist/snapshot.mjs.map +1 -0
  41. package/dist/{turn-effort-DquDDwdE.mjs → turn-effort-C61L4JIt.mjs} +2 -0
  42. package/dist/turn-effort-C61L4JIt.mjs.map +1 -0
  43. package/package.json +3 -2
  44. package/src/agent/agent.ts +90 -0
  45. package/src/agent/attachments.ts +195 -0
  46. package/src/agent/classifier.ts +525 -0
  47. package/src/agent/compact.ts +384 -0
  48. package/src/agent/conversation.ts +300 -0
  49. package/src/agent/cost.ts +164 -0
  50. package/src/agent/inbox.ts +80 -0
  51. package/src/agent/instructions.ts +62 -0
  52. package/src/agent/loop.ts +675 -0
  53. package/src/agent/messages.ts +252 -0
  54. package/src/agent/on-demand.ts +58 -0
  55. package/src/agent/prompts.ts +35 -0
  56. package/src/agent/request-images.ts +94 -0
  57. package/src/agent/stop.ts +37 -0
  58. package/src/agent/title.ts +122 -0
  59. package/src/agent/tool-groups.ts +186 -0
  60. package/src/agent/tools.ts +106 -0
  61. package/src/app.ts +67 -0
  62. package/src/config/credential-file-store.ts +66 -0
  63. package/src/config/environment.ts +105 -0
  64. package/src/config/instructions.ts +157 -0
  65. package/src/config/load.ts +667 -0
  66. package/src/config/locked-file.ts +85 -0
  67. package/src/config/paths.ts +368 -0
  68. package/src/config/schema.ts +363 -0
  69. package/src/config/subagents.ts +156 -0
  70. package/src/config/trust.ts +53 -0
  71. package/src/config/write.ts +241 -0
  72. package/src/errors.ts +85 -0
  73. package/src/events/types.ts +258 -0
  74. package/src/glob.ts +161 -0
  75. package/src/index.ts +681 -0
  76. package/src/logger.ts +47 -0
  77. package/src/paths.ts +143 -0
  78. package/src/permissions/chain.ts +42 -0
  79. package/src/permissions/command.ts +233 -0
  80. package/src/permissions/layered.ts +77 -0
  81. package/src/permissions/match.ts +80 -0
  82. package/src/permissions/modes.ts +48 -0
  83. package/src/permissions/policy.ts +160 -0
  84. package/src/permissions/types.ts +159 -0
  85. package/src/providers/cache.ts +107 -0
  86. package/src/providers/capabilities.ts +77 -0
  87. package/src/providers/catalog-view.ts +91 -0
  88. package/src/providers/catalog.ts +65 -0
  89. package/src/providers/errors.ts +108 -0
  90. package/src/providers/factories/index.ts +15 -0
  91. package/src/providers/factories/openai-codex.ts +382 -0
  92. package/src/providers/factories/openai-compatible.ts +81 -0
  93. package/src/providers/factories/openrouter.ts +165 -0
  94. package/src/providers/factories/shared.ts +22 -0
  95. package/src/providers/model.ts +197 -0
  96. package/src/providers/models-dev.ts +355 -0
  97. package/src/providers/oauth/methods.ts +10 -0
  98. package/src/providers/oauth/openai-codex.ts +228 -0
  99. package/src/providers/oauth.ts +177 -0
  100. package/src/providers/openai-codex.ts +7 -0
  101. package/src/providers/openai-compatible.ts +2 -0
  102. package/src/providers/openrouter.ts +2 -0
  103. package/src/providers/registry.ts +464 -0
  104. package/src/providers/turn-effort.ts +156 -0
  105. package/src/providers/types.ts +83 -0
  106. package/src/session/backend.ts +44 -0
  107. package/src/session/file-store.ts +278 -0
  108. package/src/session/format.ts +1037 -0
  109. package/src/session/memory-store.ts +73 -0
  110. package/src/session/session.ts +153 -0
  111. package/src/session/store.ts +219 -0
  112. package/src/sign-in/attempt.ts +166 -0
  113. package/src/sign-in/loopback.ts +74 -0
  114. package/src/snapshot/data.json +8936 -0
  115. package/src/snapshot/index.ts +37 -0
  116. package/src/tools/bin.ts +364 -0
  117. package/src/tools/builtin.ts +48 -0
  118. package/src/tools/change.ts +88 -0
  119. package/src/tools/define.ts +267 -0
  120. package/src/tools/describe.ts +96 -0
  121. package/src/tools/fs/edit-file.ts +129 -0
  122. package/src/tools/fs/glob.ts +75 -0
  123. package/src/tools/fs/grep.ts +212 -0
  124. package/src/tools/fs/line-endings.ts +17 -0
  125. package/src/tools/fs/list-dir.ts +85 -0
  126. package/src/tools/fs/read-file.ts +230 -0
  127. package/src/tools/fs/ripgrep.ts +211 -0
  128. package/src/tools/fs/write-file.ts +97 -0
  129. package/src/tools/job.ts +252 -0
  130. package/src/tools/mcp/auth-store.ts +127 -0
  131. package/src/tools/mcp/command.ts +151 -0
  132. package/src/tools/mcp/config.ts +168 -0
  133. package/src/tools/mcp/servers.ts +463 -0
  134. package/src/tools/mcp/sign-in.ts +226 -0
  135. package/src/tools/mcp/stdio.ts +204 -0
  136. package/src/tools/mcp/tools.ts +173 -0
  137. package/src/tools/on-demand.ts +184 -0
  138. package/src/tools/registry.ts +935 -0
  139. package/src/tools/shell/bash.ts +217 -0
  140. package/src/tools/shell/find-bash.ts +162 -0
  141. package/src/tools/source.ts +35 -0
  142. package/src/tools/spill.ts +127 -0
  143. package/src/tools/subagents.ts +597 -0
  144. package/src/tools/tasks.ts +603 -0
  145. package/src/tools/to-model.ts +33 -0
  146. package/src/tools/web/address.ts +95 -0
  147. package/src/tools/web/exa.ts +163 -0
  148. package/src/tools/web/fetch.ts +373 -0
  149. package/src/tools/web/html.ts +173 -0
  150. package/src/tools/web/search.ts +111 -0
  151. package/src/tools/web/source.ts +51 -0
  152. package/src/units.ts +18 -0
  153. package/src/version.ts +23 -0
@@ -0,0 +1,37 @@
1
+ import type { ModelInfo } from "../providers/capabilities";
2
+ import type { CapabilityIndex } from "../providers/models-dev";
3
+ import data from "./data.json";
4
+
5
+ /**
6
+ * The model catalog baked in at build time, the floor under the file cache.
7
+ *
8
+ * A JSON module: a file import would yield a path that needs `Bun.file()` or
9
+ * `node:fs`, which the core forbids. Its own export subpath, which
10
+ * `models-dev.ts` does not import; the CLI passes it in through
11
+ * `createModelsDevCapabilities({ snapshot })`.
12
+ *
13
+ * Generated at build time, not committed: the committed stub keeps a checkout
14
+ * type-checking and behaves as with no snapshot. A stale committed snapshot
15
+ * can only add knowledge; added silently, it is how this can hurt.
16
+ */
17
+
18
+ interface SnapshotFile {
19
+ /** ISO date the build fetched it. Empty in the committed stub. */
20
+ fetchedAt: string;
21
+ byModel: Record<string, ModelInfo>;
22
+ }
23
+
24
+ // Through `unknown`: the committed stub and a generated file of a
25
+ // few thousand models have wildly different inferred literal types, and a cast
26
+ // that only compiles for one of them would break the build that fills it in.
27
+ const file = data as unknown as SnapshotFile;
28
+
29
+ /** When the catalog was fetched, or "" when this build has no snapshot. */
30
+ export const SNAPSHOT_FETCHED_AT: string = file.fetchedAt;
31
+
32
+ export const snapshotIndex: CapabilityIndex = { byProvider: {}, byModel: file.byModel };
33
+
34
+ /** Absent rather than empty, so a caller can tell "no snapshot" from "no models". */
35
+ export function capabilitySnapshot(): CapabilityIndex | undefined {
36
+ return Object.keys(file.byModel).length === 0 ? undefined : snapshotIndex;
37
+ }
@@ -0,0 +1,364 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { spawn, spawnSync, type SpawnOptions } from "node:child_process";
3
+ import { AgentError } from "../errors";
4
+ import { JOB_CANNOT_START, jobRunner, windowsCommandLine } from "./job";
5
+
6
+ /**
7
+ * Runs an external program with a timeout and a cap on the output it keeps.
8
+ *
9
+ * The binary is found by name, through PATH, which the OS resolves. Uses
10
+ * `node:child_process`, not `Bun.spawn`. A missing binary (ENOENT) becomes a
11
+ * readable error. Only the config loader may read `process.env`.
12
+ *
13
+ * Stopping kills the whole process family, not only the spawned process:
14
+ * killing a parent alone leaves its children running.
15
+ */
16
+
17
+ export interface RunProcessOptions {
18
+ command: string;
19
+ args?: readonly string[];
20
+ cwd: string;
21
+ signal?: AbortSignal;
22
+ /** Absent: no timer, and only `signal` stops the process. */
23
+ timeoutMs?: number;
24
+ maxOutputBytes: number;
25
+ /** Run through the platform shell. Only the `bash` tool wants this. */
26
+ shell?: boolean;
27
+ /** Named in the error when the program is missing. */
28
+ install?: string;
29
+ /**
30
+ * Which end of an over-long stream comes back: `head` unless told, and `tail`
31
+ * for a shell, where the error is at the end.
32
+ */
33
+ keep?: "head" | "tail";
34
+ /**
35
+ * Receives all output, from the first byte, both streams in arrival order,
36
+ * once either passes `maxOutputBytes`. Output that fits is never passed.
37
+ */
38
+ overflow?: { write(chunk: Buffer): void };
39
+ /** Every chunk of both streams as it arrives, from the first byte. */
40
+ onOutput?: (chunk: Buffer) => void;
41
+ /**
42
+ * On Windows, run inside a job object, so a stop takes everything the command
43
+ * started. For a shell; `dir` is where the helper is kept.
44
+ */
45
+ contain?: { dir?: string };
46
+ }
47
+
48
+ export interface ProcessResult {
49
+ code: number | null;
50
+ stdout: string;
51
+ stderr: string;
52
+ /** True when either stream hit `maxOutputBytes` and was cut short. */
53
+ truncated: boolean;
54
+ timedOut: boolean;
55
+ durationMs: number;
56
+ }
57
+
58
+ /** How long a process group gets to go quietly before SIGKILL. */
59
+ const GRACE_MS = 2_000;
60
+
61
+ /** How long output already on its way may take to arrive after `exit`. */
62
+ const FLUSH_MS = 100;
63
+
64
+ const onWindows = process.platform === "win32";
65
+
66
+ /** How to stop each process still running, for a host that is leaving. */
67
+ const running = new Set<(wait?: boolean) => void>();
68
+
69
+ /**
70
+ * Stops every process `runProcess` started that has not finished.
71
+ *
72
+ * For a host about to exit without cancelling first. On Windows a child does
73
+ * not end with its parent, and a kill still on its way when the host exits
74
+ * never lands, so this one waits for it.
75
+ */
76
+ export function stopRunningProcesses(): void {
77
+ for (const stop of running) stop(true);
78
+ running.clear();
79
+ }
80
+
81
+ export function runProcess(options: RunProcessOptions): Promise<ProcessResult> {
82
+ if (!onWindows || options.contain === undefined || options.shell === true) return start(options);
83
+ return jobRunner(options.contain.dir).then((runner) =>
84
+ start(options, runner.mode === "on" ? runner.path : undefined),
85
+ );
86
+ }
87
+
88
+ function start(options: RunProcessOptions, helper?: string): Promise<ProcessResult> {
89
+ const started = Date.now();
90
+
91
+ return new Promise((resolve, reject) => {
92
+ if (options.signal?.aborted === true) {
93
+ reject(cancelled(options.command));
94
+ return;
95
+ }
96
+
97
+ // No `signal` here: the runtime would register its own abort handler first
98
+ // and kill only the direct child, so `taskkill /t` would find no tree.
99
+ const spawnOptions: SpawnOptions = {
100
+ cwd: options.cwd,
101
+ shell: options.shell ?? false,
102
+ stdio: ["ignore", "pipe", "pipe"],
103
+ windowsHide: true,
104
+ // Makes the child a process-group leader, so one signal reaches whatever
105
+ // it started. Not on Windows, where it would open a console window;
106
+ // `taskkill /t` walks the tree there.
107
+ detached: !onWindows,
108
+ };
109
+
110
+ const child =
111
+ helper === undefined
112
+ ? spawn(options.command, [...(options.args ?? [])], spawnOptions)
113
+ : spawn(helper, [String(process.pid), windowsCommandLine(options.command, options.args ?? [])], spawnOptions);
114
+
115
+ const stdout = new OutputBuffer(options.maxOutputBytes, options.keep ?? "head");
116
+ const stderr = new OutputBuffer(options.maxOutputBytes, options.keep ?? "head");
117
+ let timedOut = false;
118
+ let aborted = false;
119
+ let settled = false;
120
+
121
+ // One way to stop, reached from both roads: the timeout below and the
122
+ // caller's signal.
123
+ const stop = (wait = false): void => {
124
+ const pid = child.pid;
125
+ if (pid === undefined) return;
126
+
127
+ // The helper alone: its job closes with it and takes the rest.
128
+ if (helper !== undefined) {
129
+ child.kill();
130
+ return;
131
+ }
132
+ if (onWindows && wait) {
133
+ spawnSync("taskkill", ["/pid", String(pid), "/t", "/f"], { stdio: "ignore", windowsHide: true });
134
+ return;
135
+ }
136
+ if (onWindows) {
137
+ // Present since XP. A failure here leaves the tree alive, which is
138
+ // where we started, so it is not worth failing the call over.
139
+ spawn("taskkill", ["/pid", String(pid), "/t", "/f"], {
140
+ stdio: "ignore",
141
+ windowsHide: true,
142
+ }).on("error", () => child.kill());
143
+ return;
144
+ }
145
+
146
+ try {
147
+ process.kill(-pid, "SIGTERM");
148
+ } catch {
149
+ // ESRCH: the group is already gone. Anything else — a runtime without
150
+ // group signals — still has the single-process kill as a floor.
151
+ child.kill();
152
+ return;
153
+ }
154
+
155
+ const hard = setTimeout(() => {
156
+ try {
157
+ process.kill(-pid, "SIGKILL");
158
+ } catch {
159
+ /* it went quietly */
160
+ }
161
+ }, GRACE_MS);
162
+ hard.unref();
163
+ };
164
+
165
+ const onAbort = (): void => {
166
+ aborted = true;
167
+ stop();
168
+ };
169
+ options.signal?.addEventListener("abort", onAbort, { once: true });
170
+ running.add(stop);
171
+ // A signal outlives the call — the run's lasts the whole turn — and a late
172
+ // abort would `taskkill` a PID the system may have handed to someone else.
173
+ const detach = (): void => {
174
+ options.signal?.removeEventListener("abort", onAbort);
175
+ running.delete(stop);
176
+ };
177
+
178
+ const timer =
179
+ options.timeoutMs === undefined
180
+ ? undefined
181
+ : setTimeout(() => {
182
+ timedOut = true;
183
+ stop();
184
+ }, options.timeoutMs);
185
+
186
+ // Held back until a stream overflows: at most the two limits, and the only
187
+ // way the saved copy can start at the first byte.
188
+ let held: Buffer[] | undefined = [];
189
+ const take = (buffer: OutputBuffer, chunk: Buffer): void => {
190
+ options.onOutput?.(chunk);
191
+ buffer.push(chunk);
192
+ const overflow = options.overflow;
193
+ if (overflow === undefined) return;
194
+
195
+ if (held === undefined) {
196
+ overflow.write(chunk);
197
+ return;
198
+ }
199
+ held.push(chunk);
200
+ if (!buffer.truncated) return;
201
+ for (const earlier of held) overflow.write(earlier);
202
+ held = undefined;
203
+ };
204
+
205
+ child.stdout?.on("data", (chunk: Buffer) => take(stdout, chunk));
206
+ child.stderr?.on("data", (chunk: Buffer) => take(stderr, chunk));
207
+
208
+ child.on("error", (error: Error & { code?: string }) => {
209
+ detach();
210
+ if (settled) return;
211
+ settled = true;
212
+ clearTimeout(timer);
213
+ reject(error.code === "ENOENT" ? missingBinary(options.command, options.install) : error);
214
+ });
215
+
216
+ const finish = (code: number | null): void => {
217
+ detach();
218
+ if (settled) return;
219
+ settled = true;
220
+ clearTimeout(timer);
221
+ if (aborted) {
222
+ reject(cancelled(options.command));
223
+ return;
224
+ }
225
+ const notStarted = helper === undefined ? undefined : startFailure(code, stderr.text());
226
+ if (notStarted !== undefined) {
227
+ // What a plain spawn would have said: ENOENT reads the same either way.
228
+ reject(
229
+ notStarted === 2 || notStarted === 3
230
+ ? missingBinary(options.command, options.install)
231
+ : new AgentError("tool/failed", `Could not start "${options.command}" (Windows error ${String(notStarted)}).`, {
232
+ details: { command: options.command },
233
+ }),
234
+ );
235
+ return;
236
+ }
237
+ resolve({
238
+ code,
239
+ stdout: stdout.text(),
240
+ stderr: stderr.text(),
241
+ truncated: stdout.truncated || stderr.truncated,
242
+ timedOut,
243
+ durationMs: Date.now() - started,
244
+ });
245
+ };
246
+
247
+ child.on("close", finish);
248
+
249
+ /**
250
+ * The process ending settles the call, not `close`, which waits for every
251
+ * inheritor of the pipes, possibly processes we cannot reach. A short
252
+ * window lets output already on its way arrive.
253
+ */
254
+ child.on("exit", (code) => {
255
+ detach();
256
+ const flush = setTimeout(() => finish(code), FLUSH_MS);
257
+ flush.unref();
258
+ });
259
+ });
260
+ }
261
+
262
+ /** The Win32 error the helper met starting the command, when the command never ran. */
263
+ function startFailure(code: number | null, stderr: string): number | undefined {
264
+ const said = code === 127 ? JOB_CANNOT_START.exec(stderr)?.[1] : undefined;
265
+ return said === undefined ? undefined : Number(said);
266
+ }
267
+
268
+ function cancelled(command: string): AgentError {
269
+ return new AgentError("run/aborted", "The command was cancelled.", {
270
+ details: { command },
271
+ });
272
+ }
273
+
274
+ export function missingBinary(name: string, install?: string): AgentError {
275
+ const hint = install === undefined ? "" : ` ${install}`;
276
+ return new AgentError(
277
+ "tool/missing-binary",
278
+ `Could not find "${name}" on PATH.${hint}`,
279
+ { details: { binary: name } },
280
+ );
281
+ }
282
+
283
+ /** A partial first line shorter than this is dropped, so the tail starts on a line. */
284
+ const PARTIAL_LINE_BYTES = 2_000;
285
+
286
+ /** Keeps at most a fixed number of bytes, from one end, and remembers that it dropped some. */
287
+ class OutputBuffer {
288
+ private readonly chunks: Buffer[] = [];
289
+ private size = 0;
290
+ truncated = false;
291
+
292
+ constructor(
293
+ private readonly limit: number,
294
+ private readonly keep: "head" | "tail",
295
+ ) {}
296
+
297
+ push(chunk: Buffer): void {
298
+ if (this.keep === "tail") {
299
+ this.pushTail(chunk);
300
+ return;
301
+ }
302
+
303
+ const room = this.limit - this.size;
304
+ if (room <= 0) {
305
+ this.truncated = true;
306
+ return;
307
+ }
308
+ if (chunk.length > room) {
309
+ this.chunks.push(chunk.subarray(0, room));
310
+ this.size = this.limit;
311
+ this.truncated = true;
312
+ return;
313
+ }
314
+ this.chunks.push(chunk);
315
+ this.size += chunk.length;
316
+ }
317
+
318
+ /** The last byte thrown away, which says whether what is left starts on a line. */
319
+ private dropped: number | undefined;
320
+
321
+ /** Whole chunks go as soon as the rest still fills the limit; the exact cut waits for `text()`. */
322
+ private pushTail(chunk: Buffer): void {
323
+ // One chunk bigger than the limit is only ever worth its own end.
324
+ const from = Math.max(0, chunk.length - this.limit);
325
+ if (from > 0) {
326
+ this.dropped = chunk[from - 1];
327
+ this.truncated = true;
328
+ }
329
+
330
+ this.chunks.push(chunk.subarray(from));
331
+ this.size += chunk.length - from;
332
+ if (this.size > this.limit) this.truncated = true;
333
+
334
+ for (;;) {
335
+ const first = this.chunks[0];
336
+ if (first === undefined || this.chunks.length === 1 || this.size - first.length < this.limit) break;
337
+ this.chunks.shift();
338
+ this.size -= first.length;
339
+ this.dropped = first[first.length - 1];
340
+ }
341
+ }
342
+
343
+ text(): string {
344
+ const all = Buffer.concat(this.chunks);
345
+ if (this.keep === "head" || !this.truncated) return all.toString("utf8");
346
+
347
+ // Wherever the kept part begins — here or at a dropped chunk — it is a cut.
348
+ const cut = Math.max(0, all.length - this.limit);
349
+ let start = cut;
350
+ // It may land inside a character, whose leftover bytes would read as U+FFFD.
351
+ while (start < all.length && ((all[start] ?? 0) & 0xc0) === 0x80) start += 1;
352
+
353
+ // And inside a line: half a line reads as a different one, so a short
354
+ // partial line is dropped. A long one is all there is to show.
355
+ const before = start > cut ? undefined : cut > 0 ? all[cut - 1] : this.dropped;
356
+ if (before !== 0x0a) {
357
+ const newline = all.indexOf(0x0a, start);
358
+ if (newline !== -1 && newline - start < PARTIAL_LINE_BYTES && newline + 1 < all.length) {
359
+ start = newline + 1;
360
+ }
361
+ }
362
+ return all.subarray(start).toString("utf8");
363
+ }
364
+ }
@@ -0,0 +1,48 @@
1
+ import type { AgentTool } from "./define";
2
+ import { editFileTool } from "./fs/edit-file";
3
+ import { globTool } from "./fs/glob";
4
+ import { createGrepTool, type GrepToolOptions } from "./fs/grep";
5
+ import { listDirTool } from "./fs/list-dir";
6
+ import { readFileTool } from "./fs/read-file";
7
+ import { writeFileTool } from "./fs/write-file";
8
+ import { createBashTool, type BashToolOptions } from "./shell/bash";
9
+ import { BUILTIN_SOURCE_ID, type ToolSource } from "./source";
10
+
11
+ export interface BuiltinToolOptions extends BashToolOptions, GrepToolOptions {
12
+ /** Replaces the whole set. */
13
+ tools?: readonly AgentTool[];
14
+ }
15
+
16
+ /**
17
+ * The starting set a coding agent grows out of. A new tool takes three steps:
18
+ * write the file, add it here, write its test.
19
+ *
20
+ * Settings for one tool belong in `BuiltinToolOptions`, not on `ToolContext`,
21
+ * which every tool receives. Bash reads `tools.bashPath`; ripgrep reads
22
+ * `tools.ripgrepPath` plus whatever copy the host has compiled in. Each factory
23
+ * reads only its own fields from the whole object: matching setting names to
24
+ * tools would be a string comparison that nothing type-checks.
25
+ */
26
+ function toolSet(options: BuiltinToolOptions): readonly AgentTool[] {
27
+ return [
28
+ readFileTool,
29
+ writeFileTool,
30
+ editFileTool,
31
+ listDirTool,
32
+ globTool,
33
+ createGrepTool(options),
34
+ createBashTool(options),
35
+ ];
36
+ }
37
+
38
+ /** The set an unconfigured host gets: for listings and for describing stored calls. */
39
+ export const builtinTools: readonly AgentTool[] = toolSet({});
40
+
41
+ export function builtinToolSource(options: BuiltinToolOptions = {}): ToolSource {
42
+ const tools = options.tools ?? toolSet(options);
43
+
44
+ return {
45
+ id: BUILTIN_SOURCE_ID,
46
+ list: async () => [...tools],
47
+ };
48
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * What a write did to a file, for a screen to draw as a diff.
3
+ *
4
+ * Never part of a tool's `output`: that goes to the model, and a diff there
5
+ * would put the file into the context on every edit. It travels beside the
6
+ * output instead — in the approval request, the `tool-result` event and a
7
+ * `change` record — none of which reaches the model.
8
+ */
9
+
10
+ /** A write as its tool sees it: the whole file, before and after. */
11
+ export interface FileEdit {
12
+ path: string;
13
+ before: string;
14
+ after: string;
15
+ }
16
+
17
+ /**
18
+ * The same write cut down to the region that changed: the shape every screen
19
+ * draws and the log keeps, rather than two copies of the file.
20
+ */
21
+ export interface FileChange extends FileEdit {
22
+ /** Line in the file where `before` and `after` start, 1-based. */
23
+ startLine: number;
24
+ /** Lines past the cap were dropped from both sides. */
25
+ cut?: boolean;
26
+ /**
27
+ * Lines just above the fragment, never shown. A highlighter reads them first,
28
+ * or it cannot know the fragment starts inside a comment, a string or a
29
+ * `<style>` block.
30
+ */
31
+ lead?: string;
32
+ }
33
+
34
+ /** Unchanged lines kept on each side of the change. */
35
+ const CONTEXT_LINES = 3;
36
+ /** Per side; a screen shows far fewer, the log keeps enough to scroll. */
37
+ const MAX_LINES = 200;
38
+ /** Enough to reach the opening of most blocks, cheap enough to keep with every write. */
39
+ const LEAD_LINES = 40;
40
+
41
+ export function compactChange(edit: FileEdit): FileChange {
42
+ // A CR would return the cursor mid-line and overwrite the frame.
43
+ const before = splitLines(edit.before.replace(/\r\n/g, "\n"));
44
+ const after = splitLines(edit.after.replace(/\r\n/g, "\n"));
45
+
46
+ let head = 0;
47
+ while (head < before.length && head < after.length && before[head] === after[head]) head += 1;
48
+
49
+ let tail = 0;
50
+ while (
51
+ tail < before.length - head &&
52
+ tail < after.length - head &&
53
+ before[before.length - 1 - tail] === after[after.length - 1 - tail]
54
+ ) {
55
+ tail += 1;
56
+ }
57
+
58
+ const from = Math.max(0, head - CONTEXT_LINES);
59
+ const dropped = Math.max(0, tail - CONTEXT_LINES);
60
+ let keptBefore = before.slice(from, before.length - dropped);
61
+ let keptAfter = after.slice(from, after.length - dropped);
62
+
63
+ const cut = keptBefore.length > MAX_LINES || keptAfter.length > MAX_LINES;
64
+ if (cut) {
65
+ keptBefore = keptBefore.slice(0, MAX_LINES);
66
+ keptAfter = keptAfter.slice(0, MAX_LINES);
67
+ }
68
+
69
+ // Above `from` both sides are the same text, so either one serves as the lead.
70
+ const lead = before.slice(Math.max(0, from - LEAD_LINES), from);
71
+
72
+ return {
73
+ path: edit.path,
74
+ startLine: from + 1,
75
+ before: keptBefore.join("\n"),
76
+ after: keptAfter.join("\n"),
77
+ ...(cut ? { cut: true } : {}),
78
+ ...(lead.length === 0 ? {} : { lead: lead.join("\n") }),
79
+ };
80
+ }
81
+
82
+ /** A trailing newline ends the last line rather than starting an empty one. */
83
+ function splitLines(text: string): string[] {
84
+ if (text === "") return [];
85
+ const lines = text.split("\n");
86
+ if (lines[lines.length - 1] === "") lines.pop();
87
+ return lines;
88
+ }