fascicle 0.13.0 → 0.14.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 (43) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +20 -1
  3. package/dist/acp.d.ts +226 -0
  4. package/dist/acp.js +1886 -0
  5. package/dist/acp.js.map +1 -0
  6. package/dist/adapters.js +1 -2
  7. package/dist/agents.d.ts +1 -1
  8. package/dist/agents.js +1 -1
  9. package/dist/{core-B-M7nAkg.js → core-CDrz0NM1.js} +184 -53
  10. package/dist/core-CDrz0NM1.js.map +1 -0
  11. package/dist/diagram_bin.js +5 -2
  12. package/dist/diagram_bin.js.map +1 -1
  13. package/dist/{engine-BRzVcTBB.js → engine-BDWB2jdn.js} +12 -333
  14. package/dist/engine-BDWB2jdn.js.map +1 -0
  15. package/dist/index.d.ts +485 -623
  16. package/dist/index.js +20 -12
  17. package/dist/index.js.map +1 -1
  18. package/dist/{invoke-CIdhjChw.js → invoke-tjTjZLHj.js} +3 -3
  19. package/dist/{invoke-CIdhjChw.js.map → invoke-tjTjZLHj.js.map} +1 -1
  20. package/dist/json_schema_to_standard-r21kW2LI.js +288 -0
  21. package/dist/json_schema_to_standard-r21kW2LI.js.map +1 -0
  22. package/dist/leading_system-BQe_405V.js +330 -0
  23. package/dist/leading_system-BQe_405V.js.map +1 -0
  24. package/dist/mcp.d.ts +17 -16
  25. package/dist/mcp.js +2 -266
  26. package/dist/mcp.js.map +1 -1
  27. package/dist/search-CqH5hmuF.js +563 -0
  28. package/dist/search-CqH5hmuF.js.map +1 -0
  29. package/dist/search_worker.d.ts +1 -0
  30. package/dist/search_worker.js +19 -0
  31. package/dist/search_worker.js.map +1 -0
  32. package/dist/stdio.js +1 -1
  33. package/dist/testing.d.ts +1 -1
  34. package/dist/testing.js +3 -2
  35. package/dist/testing.js.map +1 -1
  36. package/dist/{types-CZ83Q5nm.d.ts → types-C_Rmcgck.d.ts} +7 -1
  37. package/dist/viewer-app/assets/index-Fnh5HKSU.js +2 -0
  38. package/dist/viewer-app/index.html +1 -1
  39. package/dist/viewer.js +1 -1
  40. package/package.json +30 -19
  41. package/dist/core-B-M7nAkg.js.map +0 -1
  42. package/dist/engine-BRzVcTBB.js.map +0 -1
  43. package/dist/viewer-app/assets/index-DXsB0byD.js +0 -2
package/dist/acp.js ADDED
@@ -0,0 +1,1886 @@
1
+ import { E as run, k as aborted_error } from "./core-CDrz0NM1.js";
2
+ import { n as as_record, t as json_schema_to_standard } from "./json_schema_to_standard-r21kW2LI.js";
3
+ import { a as read_file_tool, c as resolve_roots, i as is_binary, l as shown_path, n as search_tool, o as contain, r as list_files_tool, s as error_code } from "./search-CqH5hmuF.js";
4
+ import { randomUUID } from "node:crypto";
5
+ import { mkdir, open, stat, writeFile } from "node:fs/promises";
6
+ import { dirname, resolve } from "node:path";
7
+ import { constants } from "node:os";
8
+ import { spawn } from "node:child_process";
9
+ import { isUtf8 } from "node:buffer";
10
+ import { Readable, Writable } from "node:stream";
11
+ import { StringDecoder } from "node:string_decoder";
12
+ /** The id of the config option that carries the mode, the only option this agent has. */
13
+ const MODE_CONFIG_ID = "mode";
14
+ /** Every mode, in the order a client lists them. */
15
+ const MODES = {
16
+ manual: {
17
+ name: "Manual",
18
+ description: "Ask before every edit and every command",
19
+ asks: {
20
+ edit: true,
21
+ command: true
22
+ }
23
+ },
24
+ accept_edits: {
25
+ name: "Accept edits",
26
+ description: "Edit files without asking, and ask before every command",
27
+ asks: {
28
+ edit: false,
29
+ command: true
30
+ }
31
+ },
32
+ auto: {
33
+ name: "Auto",
34
+ description: "Edit files and run commands without asking, for a container or a throwaway worktree",
35
+ asks: {
36
+ edit: false,
37
+ command: false
38
+ }
39
+ }
40
+ };
41
+ /**
42
+ * Whether `id` names one of the modes. An own-key check, so an id such as
43
+ * `toString` that every object answers to isn't taken for one.
44
+ */
45
+ function is_acp_mode(id) {
46
+ return typeof id === "string" && Object.hasOwn(MODES, id);
47
+ }
48
+ /**
49
+ * The refusal for a mode id the agent doesn't know, naming the ones it does.
50
+ */
51
+ function unknown_mode_message(id) {
52
+ return `unknown mode ${JSON.stringify(id)}; choose one of ${Object.keys(MODES).join(", ")}`;
53
+ }
54
+ /**
55
+ * Whether a session in `mode` asks the client before a tool does `action`.
56
+ */
57
+ function asks_before(mode, action) {
58
+ return MODES[mode].asks[action];
59
+ }
60
+ /**
61
+ * Every mode as ACP lists one: its id, its name, and what it asks.
62
+ */
63
+ function available_modes() {
64
+ return Object.entries(MODES).map(([id, { name, description }]) => ({
65
+ id,
66
+ name,
67
+ description
68
+ }));
69
+ }
70
+ /**
71
+ * The session's modes as `session/new` reports them in `modes`.
72
+ */
73
+ function mode_state(mode) {
74
+ return {
75
+ currentModeId: mode,
76
+ availableModes: available_modes()
77
+ };
78
+ }
79
+ /**
80
+ * The session's config options, the mode as a select being the only one, as
81
+ * `session/new` and `session/set_config_option` report them.
82
+ */
83
+ function config_options(mode) {
84
+ return [{
85
+ id: MODE_CONFIG_ID,
86
+ name: "Mode",
87
+ description: "When the agent asks before it edits a file or runs a command",
88
+ category: "mode",
89
+ type: "select",
90
+ currentValue: mode,
91
+ options: Object.entries(MODES).map(([value, { name, description }]) => ({
92
+ value,
93
+ name,
94
+ description
95
+ }))
96
+ }];
97
+ }
98
+ /**
99
+ * Hold a session's mode, starting at `initial`. A switch takes effect before
100
+ * the client hears of it, so a tool call that asks after the switch reads
101
+ * the new mode, and the two updates go out in order through `send`.
102
+ */
103
+ function session_modes(initial, send) {
104
+ let mode = initial;
105
+ return {
106
+ current: () => mode,
107
+ switch_to: async (next) => {
108
+ mode = next;
109
+ await send({
110
+ sessionUpdate: "current_mode_update",
111
+ currentModeId: next
112
+ });
113
+ await send({
114
+ sessionUpdate: "config_option_update",
115
+ configOptions: config_options(next)
116
+ });
117
+ }
118
+ };
119
+ }
120
+ //#endregion
121
+ //#region src/acp/tools/previews.ts
122
+ const stores = /* @__PURE__ */ new WeakMap();
123
+ /**
124
+ * The session's store, made empty the first time it's asked for.
125
+ */
126
+ function store_of(session) {
127
+ const store = stores.get(session) ?? /* @__PURE__ */ new Map();
128
+ stores.set(session, store);
129
+ return store;
130
+ }
131
+ /**
132
+ * Empty the session's store as a turn starts.
133
+ */
134
+ function reset_previews(session) {
135
+ stores.set(session, /* @__PURE__ */ new Map());
136
+ }
137
+ /**
138
+ * Leave a call's preview at the back of its raw id's queue.
139
+ */
140
+ function record_preview(session, tool_call_id, preview) {
141
+ const store = store_of(session);
142
+ store.set(tool_call_id, [...store.get(tool_call_id) ?? [], preview]);
143
+ }
144
+ /**
145
+ * Take the oldest preview waiting under a raw id, or `undefined` when none
146
+ * is.
147
+ */
148
+ function take_preview(session, tool_call_id) {
149
+ return store_of(session).get(tool_call_id)?.shift();
150
+ }
151
+ //#endregion
152
+ //#region src/acp/presentation.ts
153
+ /**
154
+ * presentation: how a workspace tool's call looks in the client, matching
155
+ * what Zed's Claude Agent sends for its own tools.
156
+ *
157
+ * Each card gets the kind that picks its icon, a title that reads like the
158
+ * call (`Read src/a.ts (1 - 40)`, `grep "todo" src`, the command line) with
159
+ * its paths relative to `cwd`, and the places it touches as locations, whose
160
+ * lines count from 1 as Claude Agent's do. A write's or an edit's card shows
161
+ * its diff once the call lands, and a command's shows what it printed: in a
162
+ * terminal when the client advertises Zed's terminal extension
163
+ * (`_meta.terminal_output`), and as a `console` code block otherwise.
164
+ *
165
+ * It's keyed by tool name, since nothing ACP-specific may reach the engine's
166
+ * `Tool` type, and it does no I/O: the file reads behind a diff happen in
167
+ * the tools, which leave each call's preview in the session's store for its
168
+ * card to take when the call's result arrives.
169
+ */
170
+ /**
171
+ * A path the call names, made absolute under the client's `cwd`, which is
172
+ * how a location and a diff carry it.
173
+ */
174
+ function absolute(session, path) {
175
+ return resolve(session.cwd, path);
176
+ }
177
+ /**
178
+ * A path as a title shows it: relative to `cwd` when it's under it, and
179
+ * absolute otherwise, the way the tools show paths to the model.
180
+ */
181
+ function shown(session, path) {
182
+ return shown_path(session, absolute(session, path));
183
+ }
184
+ /**
185
+ * The lines a read covers, as its title says them: a range when the call
186
+ * sets a limit, where it starts when it sets only an offset, and nothing
187
+ * when it reads from the top.
188
+ */
189
+ function read_range(first, offset, limit) {
190
+ if (typeof limit === "number") return ` (${first} - ${first + limit - 1})`;
191
+ if (typeof offset === "number") return ` (from line ${offset})`;
192
+ return "";
193
+ }
194
+ /**
195
+ * A `read_file` card: `Read <path>` with the lines it covers, pointing at
196
+ * the line the read starts on.
197
+ */
198
+ function describe_read({ path, offset, limit }, session) {
199
+ if (typeof path !== "string") return void 0;
200
+ const first = typeof offset === "number" ? offset : 1;
201
+ return {
202
+ title: `Read ${shown(session, path)}${read_range(first, offset, limit)}`,
203
+ locations: [{
204
+ path: absolute(session, path),
205
+ line: first
206
+ }]
207
+ };
208
+ }
209
+ /**
210
+ * A `write_file` or `edit_file` card: the verb and the path, pointing at
211
+ * the file. The line an edit lands on comes with its preview, once the
212
+ * edit has found it.
213
+ */
214
+ function describe_change(verb) {
215
+ return ({ path }, session) => typeof path === "string" ? {
216
+ title: `${verb} ${shown(session, path)}`,
217
+ locations: [{ path: absolute(session, path) }]
218
+ } : void 0;
219
+ }
220
+ /**
221
+ * A `list_files` card: `Find` with the directory and the pattern in code
222
+ * spans, each when the call names it.
223
+ */
224
+ function describe_find({ pattern, path }, session) {
225
+ const parts = ["Find"];
226
+ if (typeof path === "string") parts.push(`\`${shown(session, path)}\``);
227
+ if (typeof pattern === "string") parts.push(`\`${pattern}\``);
228
+ return { title: parts.join(" ") };
229
+ }
230
+ /**
231
+ * A `search` card, titled the way the grep command line that does the same
232
+ * search reads.
233
+ */
234
+ function describe_grep({ pattern, path, glob }, session) {
235
+ const parts = ["grep"];
236
+ if (typeof glob === "string") parts.push(`--include="${glob}"`);
237
+ if (typeof pattern === "string") parts.push(`"${pattern}"`);
238
+ if (typeof path === "string") parts.push(shown(session, path));
239
+ return { title: parts.join(" ") };
240
+ }
241
+ /**
242
+ * A `run_command` card, titled with the command line itself.
243
+ */
244
+ function describe_command({ command }) {
245
+ return typeof command === "string" ? { title: command } : void 0;
246
+ }
247
+ /**
248
+ * The workspace tools by name. The key takes `undefined` too, so a card
249
+ * whose opening the mapper never saw simply finds nothing.
250
+ */
251
+ const PRESENTERS = /* @__PURE__ */ new Map([
252
+ ["read_file", {
253
+ kind: "read",
254
+ describe: describe_read
255
+ }],
256
+ ["list_files", {
257
+ kind: "search",
258
+ describe: describe_find
259
+ }],
260
+ ["search", {
261
+ kind: "search",
262
+ describe: describe_grep
263
+ }],
264
+ ["write_file", {
265
+ kind: "edit",
266
+ describe: describe_change("Write"),
267
+ shows: "change"
268
+ }],
269
+ ["edit_file", {
270
+ kind: "edit",
271
+ describe: describe_change("Edit"),
272
+ shows: "change"
273
+ }],
274
+ ["run_command", {
275
+ kind: "execute",
276
+ describe: describe_command,
277
+ shows: "command"
278
+ }]
279
+ ]);
280
+ /**
281
+ * Whether the client draws a command's output in a terminal from Zed's
282
+ * `_meta` extension, which it says in `initialize`.
283
+ */
284
+ function renders_terminals(session) {
285
+ const { _meta: meta } = session.client_capabilities;
286
+ return meta?.["terminal_output"] === true;
287
+ }
288
+ /**
289
+ * The terminal a card shows, under the card's own id, as Claude Agent names
290
+ * its terminals.
291
+ */
292
+ function terminal(card) {
293
+ return {
294
+ type: "terminal",
295
+ terminalId: card
296
+ };
297
+ }
298
+ /**
299
+ * What a workspace tool's card opens with: its kind, and for a command in a
300
+ * client that draws terminals, the terminal its output will land in.
301
+ */
302
+ function opening_fields(session, name, card) {
303
+ const presenter = PRESENTERS.get(name);
304
+ if (session === void 0 || presenter === void 0) return {};
305
+ if (presenter.shows !== "command" || !renders_terminals(session)) return { kind: presenter.kind };
306
+ return {
307
+ kind: presenter.kind,
308
+ content: [terminal(card)],
309
+ _meta: { terminal_info: { terminal_id: card } }
310
+ };
311
+ }
312
+ /**
313
+ * What a workspace tool call's complete input adds to its card: its title
314
+ * and locations. An input that lacks what they need leaves the card as it
315
+ * opened.
316
+ */
317
+ function input_fields(session, name, input) {
318
+ const presenter = PRESENTERS.get(name);
319
+ if (session === void 0 || presenter === void 0) return {};
320
+ return presenter.describe(as_record(input) ?? {}, session) ?? {};
321
+ }
322
+ /**
323
+ * A file change as a diff, which a client shows as the file's hunks.
324
+ */
325
+ function diff_of(change) {
326
+ return {
327
+ type: "diff",
328
+ path: change.path,
329
+ oldText: change.old_text,
330
+ newText: change.new_text
331
+ };
332
+ }
333
+ /**
334
+ * Close a write's or an edit's card with the change it made, and for an
335
+ * edit, the line its first match starts on. The closing update replaces the
336
+ * card's content, so it carries the diff again rather than dropping one the
337
+ * card already shows. A call that failed, or left no change behind, closes
338
+ * as it stands.
339
+ */
340
+ function close_change(closing, preview) {
341
+ if (preview?.kind !== "change") return closing;
342
+ return {
343
+ ...closing,
344
+ content: [diff_of(preview)],
345
+ ...preview.line === void 0 ? {} : { locations: [{
346
+ path: preview.path,
347
+ line: preview.line
348
+ }] }
349
+ };
350
+ }
351
+ /**
352
+ * Text in a `console` code block, its fence longer than any run of
353
+ * backticks that opens one of its lines, so nothing the command printed
354
+ * can close the block early.
355
+ */
356
+ function console_block(text) {
357
+ const longest = Math.max(2, ...Array.from(text.matchAll(/^`+/gm), ([run]) => run.length));
358
+ const fence = "`".repeat(longest + 1);
359
+ return {
360
+ type: "content",
361
+ content: {
362
+ type: "text",
363
+ text: `${fence}console\n${text}\n${fence}`
364
+ }
365
+ };
366
+ }
367
+ /**
368
+ * How a command's terminal ends: what it printed and how it exited, or, for
369
+ * a call that failed or left nothing behind, the error text and no exit
370
+ * code.
371
+ */
372
+ function ran(chunk, preview) {
373
+ if (preview?.kind === "command") return preview;
374
+ return {
375
+ output: chunk.error?.message ?? "",
376
+ exit_code: null,
377
+ signal: null
378
+ };
379
+ }
380
+ /**
381
+ * Close a command's card. A client that draws terminals gets the output on
382
+ * the terminal the card opened with, then the exit and the status, as
383
+ * Claude Agent sends them. Any other client gets what the model read, its
384
+ * exit code included, in a `console` block; a failed call keeps its error
385
+ * text.
386
+ */
387
+ function close_command(session, card, chunk, closing, preview) {
388
+ if (!renders_terminals(session)) {
389
+ if (chunk.error !== void 0) return [closing];
390
+ return [{
391
+ ...closing,
392
+ content: [console_block(String(chunk.output))]
393
+ }];
394
+ }
395
+ const { output, exit_code, signal } = ran(chunk, preview);
396
+ return [{
397
+ sessionUpdate: "tool_call_update",
398
+ toolCallId: card,
399
+ _meta: { terminal_output: {
400
+ terminal_id: card,
401
+ data: output
402
+ } }
403
+ }, {
404
+ ...closing,
405
+ content: [terminal(card)],
406
+ _meta: { terminal_exit: {
407
+ terminal_id: card,
408
+ exit_code,
409
+ signal
410
+ } }
411
+ }];
412
+ }
413
+ /**
414
+ * The updates that close a tool call's card, starting from the plain
415
+ * `closing` update. A successful call of a tool that leaves a preview takes
416
+ * it from the session's store whatever the card then does with it, which
417
+ * keeps each raw id's queue in step with its results.
418
+ */
419
+ function closing_updates(session, name, card, chunk, closing) {
420
+ const shows = PRESENTERS.get(name)?.shows;
421
+ if (session === void 0 || shows === void 0) return [closing];
422
+ const preview = chunk.error === void 0 ? take_preview(session, chunk.id) : void 0;
423
+ if (shows === "change") return [close_change(closing, preview)];
424
+ return close_command(session, card, chunk, closing, preview);
425
+ }
426
+ //#endregion
427
+ //#region src/acp/tools/write_file.ts
428
+ /**
429
+ * write_file: create a text file in the workspace, or replace everything one
430
+ * holds.
431
+ *
432
+ * Every write is worked out before it happens, as the file's whole text
433
+ * before and after, so the client can be shown the change as a diff before
434
+ * anything reaches the disk. `edit_file` builds its change from the same
435
+ * pieces, so the two tools agree on what they refuse and how they write.
436
+ *
437
+ * A write lands at the path's real location, which `contain` placed inside a
438
+ * root, and creates the directories it needs there, so a model writing
439
+ * `src/new/thing.ts` doesn't need a command to make `src/new` first.
440
+ */
441
+ /**
442
+ * Read the call's path and content out of its input.
443
+ */
444
+ function write_request(input) {
445
+ const { path, content } = as_record(input) ?? {};
446
+ if (typeof path !== "string" || typeof content !== "string") throw new Error("write_file needs a path and the content to write, as strings");
447
+ return {
448
+ path,
449
+ content
450
+ };
451
+ }
452
+ /**
453
+ * The text a write would replace, or `null` when no file is there yet.
454
+ * Anything but a regular UTF-8 text file is refused, because the change is
455
+ * shown as a diff of text, and rewriting a file in another encoding would
456
+ * change bytes outside the edit. A file with other hard links is refused too:
457
+ * a write changes the file under every name it has, and real paths can't say
458
+ * where the other names lie. `shown` is the path as the model gave it, and
459
+ * `tool` names the tool asking, for the refusals.
460
+ */
461
+ async function current_text(real, shown, tool) {
462
+ const info = await stat(real).catch((err) => {
463
+ if (error_code(err) === "ENOENT") return void 0;
464
+ throw err;
465
+ });
466
+ if (info === void 0) return null;
467
+ if (info.isDirectory()) throw new Error(`${shown} is a directory; ${tool} changes a file, so name one inside it`);
468
+ if (!info.isFile()) throw new Error(`${shown} isn't a regular file, so ${tool} can't change it`);
469
+ if (info.nlink > 1) throw new Error(`${shown} is one of ${info.nlink} hard links to the same file, and the rest may lie outside the workspace, so ${tool} won't change it`);
470
+ const handle = await open(real);
471
+ try {
472
+ if (await is_binary(handle)) throw new Error(`${shown} is a binary file (it has a NUL byte in its first 8 KB), so ${tool} won't change it`);
473
+ const bytes = await handle.readFile();
474
+ if (!isUtf8(bytes)) throw new Error(`${shown} isn't UTF-8 text, so ${tool} won't change it`);
475
+ return bytes.toString("utf8");
476
+ } finally {
477
+ await handle.close();
478
+ }
479
+ }
480
+ /**
481
+ * Write a change's new text where it lands, creating the directories it
482
+ * needs first. A turn cancelled while the change was worked out stops here,
483
+ * before anything is written. A new file is created exclusively, so a file or
484
+ * a symlink that appeared at its path since then stops the write instead of
485
+ * taking it.
486
+ */
487
+ async function apply_change(change, abort) {
488
+ abort.throwIfAborted();
489
+ await mkdir(dirname(change.real), { recursive: true });
490
+ await writeFile(change.real, change.new_text, change.old_text === null ? { flag: "wx" } : {});
491
+ }
492
+ /**
493
+ * Leave a change that landed in the session's preview store, for the card
494
+ * of the call that made it to show as a diff.
495
+ */
496
+ function record_change(session, tool_call_id, change) {
497
+ record_preview(session, tool_call_id, {
498
+ kind: "change",
499
+ path: change.path,
500
+ old_text: change.old_text,
501
+ new_text: change.new_text,
502
+ line: change.line
503
+ });
504
+ }
505
+ /**
506
+ * The change a `write_file` call would make, worked out without writing: its
507
+ * path checked against the session's roots, the text it would replace, and
508
+ * the content that replaces it.
509
+ */
510
+ async function write_file_change(session, input) {
511
+ const request = write_request(input);
512
+ const target = await contain(session, request.path);
513
+ const old_text = await current_text(target.real, request.path, "write_file");
514
+ return {
515
+ ...target,
516
+ old_text,
517
+ new_text: request.content
518
+ };
519
+ }
520
+ /**
521
+ * The `write_file` tool for one session: a file inside its workspace,
522
+ * created or replaced whole. The model reads back a line saying which, since
523
+ * it already has the text it sent.
524
+ */
525
+ function write_file_tool(session) {
526
+ return {
527
+ name: "write_file",
528
+ description: "Write a text file in the workspace: create it, along with any directories it needs, or replace everything it holds. content is the file's whole text; to change part of a file, use edit_file. The path is absolute or relative to the workspace root.",
529
+ input_schema: json_schema_to_standard({
530
+ type: "object",
531
+ properties: {
532
+ path: {
533
+ type: "string",
534
+ description: "The file to write, absolute or relative to the workspace root"
535
+ },
536
+ content: {
537
+ type: "string",
538
+ description: "The file's whole text"
539
+ }
540
+ },
541
+ required: ["path", "content"],
542
+ additionalProperties: false
543
+ }),
544
+ execute: async (input, ctx) => {
545
+ const change = await write_file_change(session, input);
546
+ await apply_change(change, ctx.abort);
547
+ record_change(session, ctx.tool_call_id, change);
548
+ return `${change.old_text === null ? "created" : "overwrote"} ${shown_path(session, change.path)}`;
549
+ }
550
+ };
551
+ }
552
+ //#endregion
553
+ //#region src/acp/tools/edit_file.ts
554
+ /**
555
+ * Read the call's path, texts, and `replace_all` out of its input, refusing
556
+ * an `old_text` that's empty, which matches everywhere, or the same as
557
+ * `new_text`, which changes nothing.
558
+ */
559
+ function edit_request(input) {
560
+ const { path, old_text, new_text, replace_all = false } = as_record(input) ?? {};
561
+ if (typeof path !== "string" || typeof old_text !== "string" || typeof new_text !== "string" || typeof replace_all !== "boolean") throw new Error("edit_file needs path, old_text, and new_text as strings, and takes replace_all as true or false");
562
+ if (old_text === "") throw new Error("old_text is empty, so there's nothing to find; write_file writes a whole file");
563
+ if (old_text === new_text) throw new Error("old_text and new_text are the same, so the edit would change nothing");
564
+ return {
565
+ path,
566
+ old_text,
567
+ new_text,
568
+ replace_all
569
+ };
570
+ }
571
+ /**
572
+ * The change an `edit_file` call would make, worked out without writing: the
573
+ * file's whole text before, and after `old_text` is replaced. It fails when
574
+ * `old_text` isn't there, or is there more than once and the call doesn't set
575
+ * `replace_all`.
576
+ */
577
+ async function edit_file_change(session, input) {
578
+ const request = edit_request(input);
579
+ const target = await contain(session, request.path);
580
+ const text = await current_text(target.real, request.path, "edit_file");
581
+ if (text === null) throw new Error(`${request.path} doesn't exist; write_file creates a file`);
582
+ const pieces = text.split(request.old_text);
583
+ const matches = pieces.length - 1;
584
+ if (matches === 0) throw new Error(`old_text doesn't appear in ${request.path}; it has to match the file exactly, whitespace included, so read the lines again and copy them without their numbers`);
585
+ if (matches > 1 && !request.replace_all) throw new Error(`old_text appears ${matches} times in ${request.path}; include more of the lines around it so it matches once, or set replace_all to replace every one`);
586
+ const before = text.slice(0, text.indexOf(request.old_text));
587
+ return {
588
+ ...target,
589
+ old_text: text,
590
+ new_text: pieces.join(request.new_text),
591
+ line: before.split("\n").length,
592
+ matches
593
+ };
594
+ }
595
+ /**
596
+ * The `edit_file` tool for one session: an exact match replaced in a file
597
+ * inside its workspace. The model reads back where the edit landed rather
598
+ * than the file again.
599
+ */
600
+ function edit_file_tool(session) {
601
+ return {
602
+ name: "edit_file",
603
+ description: "Edit a text file in the workspace by replacing old_text with new_text. old_text has to match the file exactly, whitespace and line breaks included, and appear in it once, unless replace_all is set to replace every match. Copy it from read_file without the line number and tab that read_file puts before each line. The path is absolute or relative to the workspace root.",
604
+ input_schema: json_schema_to_standard({
605
+ type: "object",
606
+ properties: {
607
+ path: {
608
+ type: "string",
609
+ description: "The file to edit, absolute or relative to the workspace root"
610
+ },
611
+ old_text: {
612
+ type: "string",
613
+ minLength: 1,
614
+ description: "The exact text to replace"
615
+ },
616
+ new_text: {
617
+ type: "string",
618
+ description: "The text to put in its place"
619
+ },
620
+ replace_all: {
621
+ type: "boolean",
622
+ description: "Replace every match of old_text, rather than exactly one; default: false"
623
+ }
624
+ },
625
+ required: [
626
+ "path",
627
+ "old_text",
628
+ "new_text"
629
+ ],
630
+ additionalProperties: false
631
+ }),
632
+ execute: async (input, ctx) => {
633
+ const change = await edit_file_change(session, input);
634
+ await apply_change(change, ctx.abort);
635
+ record_change(session, ctx.tool_call_id, change);
636
+ const shown = shown_path(session, change.path);
637
+ return change.matches === 1 ? `edited ${shown} at line ${change.line}` : `edited ${shown} in ${change.matches} places, the first at line ${change.line}`;
638
+ }
639
+ };
640
+ }
641
+ //#endregion
642
+ //#region src/acp/approve.ts
643
+ /**
644
+ * approve: ask the client before a workspace tool edits a file or runs a
645
+ * command, through `session/request_permission`.
646
+ *
647
+ * The request shows the card the client already draws for the call, and
648
+ * for an edit, the change worked out on disk first, so the user approves
649
+ * the diff itself. It offers Allow, Reject, and an "always" that lives in
650
+ * memory for the session. For an edit, "always" switches the session to
651
+ * Accept edits, as Claude Agent's does, and tells the client both ways so
652
+ * its mode picker follows. For a command, it covers the program and its
653
+ * first argument that isn't a flag (`pnpm test`). A command with shell
654
+ * control syntax is never covered and never offered one, since anything
655
+ * can follow a `;` or a `|`.
656
+ *
657
+ * A permission check that fails open isn't a check, so anything short of
658
+ * an allow denies the call: a rejection, a `cancelled` outcome, an option
659
+ * the request never offered, and a request that fails for any reason.
660
+ *
661
+ * The engine asks with its raw call id, which can repeat inside a turn,
662
+ * and the turn's consumer can still be sending earlier updates when it
663
+ * asks. So the request waits until the consumer has sent everything the
664
+ * run had recorded by then, the card's opening included, and points at the
665
+ * latest card the client was sent for that raw id. The consumer never
666
+ * waits on an approval, so the wait can't deadlock, and the turn's abort
667
+ * ends it.
668
+ */
669
+ const GATES = /* @__PURE__ */ new Map([
670
+ ["write_file", {
671
+ action: "edit",
672
+ change: write_file_change
673
+ }],
674
+ ["edit_file", {
675
+ action: "edit",
676
+ change: edit_file_change
677
+ }],
678
+ ["run_command", { action: "command" }]
679
+ ]);
680
+ /**
681
+ * Shell syntax that runs, chains, or redirects something past the
682
+ * command's own program: `;`, `&`, `|`, `>`, `<`, a backtick, `$(`, and a
683
+ * newline.
684
+ */
685
+ const CONTROL_SYNTAX = /[;&|<>`\n]|\$\(/;
686
+ const ALLOW_ONCE = {
687
+ optionId: "allow_once",
688
+ name: "Allow",
689
+ kind: "allow_once"
690
+ };
691
+ const REJECT_ONCE = {
692
+ optionId: "reject_once",
693
+ name: "Reject",
694
+ kind: "reject_once"
695
+ };
696
+ /**
697
+ * A fresh count for a turn that has recorded and sent nothing yet.
698
+ */
699
+ function fresh_progress() {
700
+ return {
701
+ recorded: 0,
702
+ sent: 0,
703
+ moved: Promise.withResolvers(),
704
+ cards: /* @__PURE__ */ new Map()
705
+ };
706
+ }
707
+ /**
708
+ * `inner`, or nothing, with `count` called after each call that queues an
709
+ * event. Without an inner logger, a span gets an id of its own, as the
710
+ * runner's default logger gives one.
711
+ */
712
+ function counting_logger(inner, count) {
713
+ return {
714
+ record: (event) => {
715
+ inner?.record(event);
716
+ count();
717
+ },
718
+ start_span: (name, meta) => {
719
+ const id = inner?.start_span(name, meta) ?? `${name}:${randomUUID()}`;
720
+ count();
721
+ return id;
722
+ },
723
+ end_span: (id, meta) => {
724
+ inner?.end_span(id, meta);
725
+ count();
726
+ }
727
+ };
728
+ }
729
+ /**
730
+ * The raw id of the call a `tool_call_start` chunk opens, or `undefined`
731
+ * for any other event.
732
+ */
733
+ function started_call(event) {
734
+ if (event.kind !== "model_chunk") return void 0;
735
+ const chunk = as_record(event["chunk"]);
736
+ return chunk?.["kind"] === "tool_call_start" && typeof chunk["id"] === "string" ? chunk["id"] : void 0;
737
+ }
738
+ /**
739
+ * Whether an update opens a card.
740
+ */
741
+ function opens_card(update) {
742
+ return update.sessionUpdate === "tool_call";
743
+ }
744
+ /**
745
+ * Create the sync between a session's turns and its approvals. Turns in a
746
+ * session never overlap, so one sync serves them all, a turn at a time.
747
+ */
748
+ function create_card_sync() {
749
+ let turn = fresh_progress();
750
+ return {
751
+ start: (inner) => {
752
+ const started = fresh_progress();
753
+ turn = started;
754
+ return counting_logger(inner, () => {
755
+ started.recorded += 1;
756
+ });
757
+ },
758
+ sent: (event, updates) => {
759
+ const raw_id = started_call(event);
760
+ const card = updates.find(opens_card);
761
+ if (raw_id !== void 0 && card !== void 0) turn.cards.set(raw_id, card.toolCallId);
762
+ turn.sent += 1;
763
+ turn.moved.resolve();
764
+ turn.moved = Promise.withResolvers();
765
+ },
766
+ caught_up: async () => {
767
+ const waiting = turn;
768
+ const target = waiting.recorded;
769
+ while (waiting.sent < target) await waiting.moved.promise;
770
+ },
771
+ card_for: (raw_id) => turn.cards.get(raw_id)
772
+ };
773
+ }
774
+ /**
775
+ * What an "always" grant for a command covers: its program and its first
776
+ * argument that isn't a flag (`git status`, `pnpm test`; `ls -la` is
777
+ * `ls`). A command with shell control syntax has none, so no grant ever
778
+ * covers it, and neither does one that isn't a string or names no program.
779
+ */
780
+ function command_key(input) {
781
+ const command = as_record(input)?.["command"];
782
+ if (typeof command !== "string" || CONTROL_SYNTAX.test(command)) return void 0;
783
+ const [program, ...args] = command.trim().split(/\s+/);
784
+ if (program === "") return void 0;
785
+ const subject = args.find((arg) => !arg.startsWith("-"));
786
+ return subject === void 0 ? program : [program, subject].join(" ");
787
+ }
788
+ /**
789
+ * The message a failure carries, whatever was thrown.
790
+ */
791
+ function message_of$1(err) {
792
+ return err instanceof Error ? err.message : String(err);
793
+ }
794
+ /**
795
+ * Start `work` and settle with it, or reject with the abort's reason as
796
+ * soon as `abort` fires, so a turn's cancel never waits on the client. A
797
+ * turn already cancelled starts nothing, so no request goes out for it.
798
+ */
799
+ async function unless_aborted(abort, work) {
800
+ abort.throwIfAborted();
801
+ const { promise: aborted, reject } = Promise.withResolvers();
802
+ const on_abort = () => {
803
+ reject(abort.reason);
804
+ };
805
+ abort.addEventListener("abort", on_abort);
806
+ try {
807
+ return await Promise.race([work(), aborted]);
808
+ } finally {
809
+ abort.removeEventListener("abort", on_abort);
810
+ }
811
+ }
812
+ /**
813
+ * What a change adds to the request's card: its diff, and for an edit,
814
+ * the line its first match starts on. A change that can't be worked out
815
+ * shows why instead, which is what the call will fail with if it's
816
+ * allowed, so the user isn't asked to approve a change they can't see.
817
+ */
818
+ async function change_fields(change, session, input) {
819
+ try {
820
+ const { path, old_text, new_text, line } = await change(session, input);
821
+ return {
822
+ content: [{
823
+ type: "diff",
824
+ path,
825
+ oldText: old_text,
826
+ newText: new_text
827
+ }],
828
+ ...line === void 0 ? {} : { locations: [{
829
+ path,
830
+ line
831
+ }] }
832
+ };
833
+ } catch (err) {
834
+ return { content: [{
835
+ type: "content",
836
+ content: {
837
+ type: "text",
838
+ text: message_of$1(err)
839
+ }
840
+ }] };
841
+ }
842
+ }
843
+ /**
844
+ * The card a request shows: the one the client already draws for the call
845
+ * under `card`, as its tool's presentation describes it, with the change
846
+ * for a write or an edit.
847
+ */
848
+ async function permission_card(session, request, card, gate) {
849
+ const { tool_name: name, input } = request;
850
+ const fields = {
851
+ toolCallId: card,
852
+ title: name,
853
+ kind: opening_fields(session, name, card).kind ?? "other",
854
+ rawInput: input,
855
+ ...input_fields(session, name, input)
856
+ };
857
+ if (gate?.change === void 0) return fields;
858
+ return {
859
+ ...fields,
860
+ ...await change_fields(gate.change, session, input)
861
+ };
862
+ }
863
+ /**
864
+ * Whether the user's answer allows the call, granting the "always" first
865
+ * when that's what they chose. Only an option the request offered counts.
866
+ */
867
+ async function allowed(outcome, always) {
868
+ if (outcome.outcome !== "selected") return false;
869
+ if (outcome.optionId === ALLOW_ONCE.optionId) return true;
870
+ if (outcome.optionId !== "allow_always" || always === void 0) return false;
871
+ await always.grant();
872
+ return true;
873
+ }
874
+ /**
875
+ * Say on stderr that a permission request failed, since the call was
876
+ * refused without the user ever seeing it.
877
+ */
878
+ function warn_failed(tool_name, err) {
879
+ process.stderr.write(`fascicle/acp: asking the client to approve ${tool_name} failed (${message_of$1(err)}), so the call was refused; check that the client answers session/request_permission\n`);
880
+ }
881
+ /**
882
+ * The "always" a call is offered: Accept edits for an edit, and a grant of
883
+ * its key for a command that has one. Any other call gets none. Choosing
884
+ * Accept edits leaves a session that has moved past Manual since the call
885
+ * asked where it is.
886
+ */
887
+ function always_for(gate, key, modes, granted) {
888
+ if (gate?.action === "edit") return {
889
+ name: "Allow all edits this session",
890
+ grant: async () => {
891
+ if (asks_before(modes.current(), "edit")) await modes.switch_to("accept_edits");
892
+ }
893
+ };
894
+ if (key === void 0) return void 0;
895
+ return {
896
+ name: `Always allow \`${key}\` this session`,
897
+ grant: async () => {
898
+ granted.add(key);
899
+ }
900
+ };
901
+ }
902
+ /**
903
+ * The options a request offers. Allow is always among them, since some
904
+ * hosts answer every request on their own by choosing `allow_once`.
905
+ */
906
+ function options_for(always) {
907
+ if (always === void 0) return [ALLOW_ONCE, REJECT_ONCE];
908
+ return [
909
+ ALLOW_ONCE,
910
+ {
911
+ optionId: "allow_always",
912
+ name: always.name,
913
+ kind: "allow_always"
914
+ },
915
+ REJECT_ONCE
916
+ ];
917
+ }
918
+ /**
919
+ * Create the approvals for one session's calls, holding its commands'
920
+ * "always" grants for the life of the session.
921
+ */
922
+ function session_approver({ modes, cards, ask }) {
923
+ const granted = /* @__PURE__ */ new Set();
924
+ return async (session, request) => {
925
+ const gate = GATES.get(request.tool_name);
926
+ const key = gate?.action === "command" ? command_key(request.input) : void 0;
927
+ if (key !== void 0 && granted.has(key)) return true;
928
+ const always = always_for(gate, key, modes, granted);
929
+ const options = options_for(always);
930
+ try {
931
+ await unless_aborted(request.abort, cards.caught_up);
932
+ const toolCall = await permission_card(session, request, cards.card_for(request.tool_call_id) ?? randomUUID(), gate);
933
+ return await allowed((await unless_aborted(request.abort, () => ask({
934
+ sessionId: session.id,
935
+ toolCall,
936
+ options
937
+ }, request.abort))).outcome, always);
938
+ } catch (err) {
939
+ if (!request.abort.aborted) warn_failed(request.tool_name, err);
940
+ return false;
941
+ }
942
+ };
943
+ }
944
+ //#endregion
945
+ //#region src/acp/to_session_updates.ts
946
+ /**
947
+ * Maps a run's events onto ACP `session/update` payloads.
948
+ *
949
+ * Under `run.stream`, each `model_call` records `model_chunk` events carrying
950
+ * the engine's `StreamChunk`, the same source fascicle/ui reads. This half of
951
+ * a prompt turn does no I/O and holds no SDK value, so a flow author can wrap
952
+ * `to_session_updates` in their own `to_updates` and add to what it returns,
953
+ * as long as every event still reaches it: each `span_start` advances the
954
+ * state's count of how many times a step has run, and a workspace tool's
955
+ * result takes its call's preview from the session's store. Spans, `cost`,
956
+ * and `emit` events map to nothing; an `emit` never becomes chat output
957
+ * implicitly, because output that changes with a value's shape is a trap.
958
+ *
959
+ * Every tool gets a plain card here. Given the turn's session, the workspace
960
+ * tools' cards also take the look `presentation.ts` gives them.
961
+ */
962
+ /**
963
+ * Create the state for one prompt turn's events, routing every model call's
964
+ * text to the reply unless `stream` says otherwise.
965
+ */
966
+ function create_acp_mapper_state(options = {}) {
967
+ return {
968
+ turn_id: options.turn_id ?? randomUUID(),
969
+ stream: options.stream ?? (() => "message"),
970
+ runs: /* @__PURE__ */ new Map(),
971
+ session: options.session,
972
+ tools: /* @__PURE__ */ new Map()
973
+ };
974
+ }
975
+ /**
976
+ * Build the session-unique ACP id for an engine tool call id.
977
+ *
978
+ * Raw ids repeat across model calls, turns, and runs of one model call
979
+ * (Ollama has none on the wire, so the engine numbers them
980
+ * `ollama_call_<step>_<n>` afresh on every generate call), and a repeated id
981
+ * would make the client update an old card instead of opening a new one.
982
+ */
983
+ function acp_tool_call_id(state, step_id, raw_id) {
984
+ return `${state.turn_id}:${step_id}:${state.runs.get(step_id) ?? 0}:${raw_id}`;
985
+ }
986
+ /**
987
+ * Count one more run of the step a `span_start` opens, by the `id` its span
988
+ * carries. Counting starts rather than finishes covers a retry whose first
989
+ * attempt failed before it finished.
990
+ */
991
+ function count_run(event, state) {
992
+ const id = event["id"];
993
+ if (typeof id === "string") state.runs.set(id, (state.runs.get(id) ?? 0) + 1);
994
+ }
995
+ /**
996
+ * Wrap streamed text as the update its route names, or nothing for `'none'`.
997
+ */
998
+ function text_updates(route, text) {
999
+ const content = {
1000
+ type: "text",
1001
+ text
1002
+ };
1003
+ if (route === "message") return [{
1004
+ sessionUpdate: "agent_message_chunk",
1005
+ content
1006
+ }];
1007
+ if (route === "thought") return [{
1008
+ sessionUpdate: "agent_thought_chunk",
1009
+ content
1010
+ }];
1011
+ return [];
1012
+ }
1013
+ /**
1014
+ * Close a tool card: `completed` with the raw output, or `failed` with the
1015
+ * error text as the card's content, since that text is what the user needs
1016
+ * to see.
1017
+ */
1018
+ function tool_result_update(tool_call_id, chunk) {
1019
+ if (chunk.error !== void 0) return {
1020
+ sessionUpdate: "tool_call_update",
1021
+ toolCallId: tool_call_id,
1022
+ status: "failed",
1023
+ content: [{
1024
+ type: "content",
1025
+ content: {
1026
+ type: "text",
1027
+ text: chunk.error.message
1028
+ }
1029
+ }]
1030
+ };
1031
+ return {
1032
+ sessionUpdate: "tool_call_update",
1033
+ toolCallId: tool_call_id,
1034
+ status: "completed",
1035
+ rawOutput: chunk.output
1036
+ };
1037
+ }
1038
+ /**
1039
+ * Map one engine `StreamChunk` from the model call `step_id` to the session
1040
+ * updates it produces.
1041
+ */
1042
+ function map_chunk(chunk, step_id, state) {
1043
+ switch (chunk.kind) {
1044
+ case "text": return text_updates(state.stream(step_id), chunk.text);
1045
+ case "reasoning": return text_updates("thought", chunk.text);
1046
+ case "tool_call_start": {
1047
+ const card = acp_tool_call_id(state, step_id, chunk.id);
1048
+ state.tools.set(card, chunk.name);
1049
+ return [{
1050
+ sessionUpdate: "tool_call",
1051
+ toolCallId: card,
1052
+ title: chunk.name,
1053
+ kind: "other",
1054
+ status: "pending",
1055
+ ...opening_fields(state.session, chunk.name, card)
1056
+ }];
1057
+ }
1058
+ case "tool_call_end": {
1059
+ const card = acp_tool_call_id(state, step_id, chunk.id);
1060
+ return [{
1061
+ sessionUpdate: "tool_call_update",
1062
+ toolCallId: card,
1063
+ status: "in_progress",
1064
+ rawInput: chunk.input,
1065
+ ...input_fields(state.session, state.tools.get(card), chunk.input)
1066
+ }];
1067
+ }
1068
+ case "tool_result": {
1069
+ const card = acp_tool_call_id(state, step_id, chunk.id);
1070
+ return closing_updates(state.session, state.tools.get(card), card, chunk, tool_result_update(card, chunk));
1071
+ }
1072
+ default: return [];
1073
+ }
1074
+ }
1075
+ /**
1076
+ * Narrow the loose `chunk` field of a `model_chunk` event. model_call records
1077
+ * only real StreamChunks there, and map_chunk maps a kind it doesn't know to
1078
+ * nothing, so ruling out a missing or null value is enough.
1079
+ */
1080
+ function is_stream_chunk(value) {
1081
+ return typeof value === "object" && value !== null;
1082
+ }
1083
+ /**
1084
+ * Map one run event to zero or more ACP session updates. Only `model_chunk`
1085
+ * events produce any. A `span_start` advances the state's run count, a
1086
+ * card's opening records its tool, and a workspace tool's result takes its
1087
+ * preview; the function does no I/O.
1088
+ */
1089
+ function to_session_updates(event, state) {
1090
+ if (event.kind === "span_start") {
1091
+ count_run(event, state);
1092
+ return [];
1093
+ }
1094
+ if (event.kind !== "model_chunk") return [];
1095
+ const step_id = event["step_id"];
1096
+ const chunk = event["chunk"];
1097
+ if (typeof step_id !== "string" || !is_stream_chunk(chunk)) return [];
1098
+ return map_chunk(chunk, step_id, state);
1099
+ }
1100
+ //#endregion
1101
+ //#region src/acp/prompt_turn.ts
1102
+ /**
1103
+ * Join a prompt's blocks into the text a flow reads. Text blocks join as the
1104
+ * client split them, and a resource link or an embedded resource reads as
1105
+ * its URI where it sat. Each embedded resource's text follows the prompt in
1106
+ * a `<context>` block naming that URI, the form Claude Agent uses, so a file
1107
+ * the user @-mentioned reaches the model without splitting the sentence that
1108
+ * mentions it. Image and audio blocks stay in `turn.prompt` only, since the
1109
+ * agent advertises neither.
1110
+ */
1111
+ function turn_text(prompt) {
1112
+ const inline = [];
1113
+ const context = [];
1114
+ for (const block of prompt) if (block.type === "text") inline.push(block.text);
1115
+ else if (block.type === "resource_link") inline.push(block.uri);
1116
+ else if (block.type === "resource") {
1117
+ inline.push(block.resource.uri);
1118
+ if ("text" in block.resource) context.push(`<context ref="${block.resource.uri}">\n${block.resource.text}\n</context>`);
1119
+ }
1120
+ return [inline.join(""), ...context].join("\n\n");
1121
+ }
1122
+ /**
1123
+ * The flow's input for a turn: the config's `to_input`, or the turn's text,
1124
+ * which `ServeAcpConfig` allows only when the flow takes a string.
1125
+ */
1126
+ function turn_input(config, turn) {
1127
+ if (config.to_input !== void 0) return config.to_input(turn);
1128
+ return turn.text;
1129
+ }
1130
+ /**
1131
+ * The default `to_text`: a string as-is, anything else as JSON, and nothing
1132
+ * at all for a flow that returns nothing.
1133
+ */
1134
+ function default_to_text(output) {
1135
+ return typeof output === "string" ? output : JSON.stringify(output) ?? "";
1136
+ }
1137
+ /**
1138
+ * Wrap a turn's final text as the message update that carries it.
1139
+ */
1140
+ function agent_message(text) {
1141
+ return {
1142
+ sessionUpdate: "agent_message_chunk",
1143
+ content: {
1144
+ type: "text",
1145
+ text
1146
+ }
1147
+ };
1148
+ }
1149
+ /**
1150
+ * Count a message update the client was sent toward the turn's reply. Only
1151
+ * text joins the reply's text, but any message counts as a reply, so a flow
1152
+ * that sent an image doesn't get a `to_text` message after it.
1153
+ */
1154
+ function note_reply(reply, update) {
1155
+ if (update.sessionUpdate !== "agent_message_chunk") return;
1156
+ reply.sent = true;
1157
+ if (update.content.type === "text") reply.text += update.content.text;
1158
+ }
1159
+ /**
1160
+ * Append a turn to the session's history: the user's text, then the reply
1161
+ * text the client was sent, when there was any. A cancelled turn marks
1162
+ * whichever of the two came last.
1163
+ */
1164
+ function record_exchange(history, user_text, reply_text, cancelled) {
1165
+ const stop = cancelled ? { cancelled: true } : {};
1166
+ if (reply_text === "") history.push({
1167
+ role: "user",
1168
+ text: user_text,
1169
+ ...stop
1170
+ });
1171
+ else history.push({
1172
+ role: "user",
1173
+ text: user_text
1174
+ }, {
1175
+ role: "agent",
1176
+ text: reply_text,
1177
+ ...stop
1178
+ });
1179
+ }
1180
+ /**
1181
+ * Settle a run's result into a value, so a run that fails while the turn is
1182
+ * still sending never surfaces as an unhandled rejection.
1183
+ */
1184
+ function settle(result) {
1185
+ return result.then((output) => ({
1186
+ ok: true,
1187
+ output
1188
+ }), (error) => ({
1189
+ ok: false,
1190
+ error
1191
+ }));
1192
+ }
1193
+ /**
1194
+ * Say on stderr that the run outran the client and dropped events, since the
1195
+ * reply the client shows is missing text from that point on.
1196
+ */
1197
+ function warn_dropped(event) {
1198
+ process.stderr.write(`fascicle/acp: the client read updates slower than the run produced them, so ${String(event["count"])} run events were dropped and the reply is missing text from that point; send the prompt again for the whole reply\n`);
1199
+ }
1200
+ /**
1201
+ * Send each run event's updates in order, and tell the session's card sync
1202
+ * once all of an event's updates have gone out. Once the turn is cancelled
1203
+ * nothing more is sent, and leaving the loop closes the run's event stream.
1204
+ */
1205
+ async function forward(events, config, record, cancelled, send) {
1206
+ const state = create_acp_mapper_state({
1207
+ stream: config.stream,
1208
+ session: record.session
1209
+ });
1210
+ const to_updates = config.to_updates ?? to_session_updates;
1211
+ for await (const event of events) {
1212
+ if (event.kind === "events_dropped") warn_dropped(event);
1213
+ const updates = to_updates(event, state);
1214
+ for (const update of updates) {
1215
+ if (cancelled.aborted) return;
1216
+ await send(update);
1217
+ }
1218
+ record.cards.sent(event, updates);
1219
+ }
1220
+ }
1221
+ /**
1222
+ * Run the flow for one turn, forward its updates, and record the exchange.
1223
+ * The run has always settled by the time this returns or throws, so a turn
1224
+ * never leaves a run behind.
1225
+ */
1226
+ async function run_turn(config, record, prompt, cancelled, send) {
1227
+ const turn = {
1228
+ session_id: record.session.id,
1229
+ cwd: record.session.cwd,
1230
+ text: turn_text(prompt),
1231
+ prompt,
1232
+ history: [...record.history]
1233
+ };
1234
+ const reply = {
1235
+ sent: false,
1236
+ text: ""
1237
+ };
1238
+ const send_update = async (update) => {
1239
+ await send(update);
1240
+ note_reply(reply, update);
1241
+ };
1242
+ const stop = new AbortController();
1243
+ reset_previews(record.session);
1244
+ const handle = run.stream(record.flow, turn_input(config, turn), {
1245
+ abort: AbortSignal.any([cancelled, stop.signal]),
1246
+ install_signal_handlers: false,
1247
+ trajectory: record.cards.start(config.trajectory)
1248
+ });
1249
+ const outcome = settle(handle.result);
1250
+ try {
1251
+ await forward(handle.events, config, record, cancelled, send_update);
1252
+ const result = await outcome;
1253
+ if (!cancelled.aborted) {
1254
+ if (!result.ok) throw result.error;
1255
+ const final_text = (config.to_text ?? default_to_text)(result.output);
1256
+ if (!reply.sent && final_text !== "") await send_update(agent_message(final_text));
1257
+ }
1258
+ } catch (err) {
1259
+ stop.abort(new aborted_error("the prompt turn failed before its run finished"));
1260
+ await outcome;
1261
+ if (!cancelled.aborted) throw err;
1262
+ }
1263
+ record_exchange(record.history, turn.text, reply.text, cancelled.aborted);
1264
+ return { stopReason: cancelled.aborted ? "cancelled" : "end_turn" };
1265
+ }
1266
+ /**
1267
+ * Run one prompt turn and answer with its stop reason. A new prompt cancels
1268
+ * the session's turn in flight and waits for it to settle first, so it sees
1269
+ * that turn in its history and never runs beside it.
1270
+ */
1271
+ async function prompt_turn(config, record, prompt, request_signal, send) {
1272
+ const previous = record.last_turn;
1273
+ const cancel = new AbortController();
1274
+ const { promise: settled, resolve: settle_turn } = Promise.withResolvers();
1275
+ record.last_turn = {
1276
+ cancel,
1277
+ settled
1278
+ };
1279
+ try {
1280
+ if (previous !== null) {
1281
+ previous.cancel.abort(new aborted_error("a new prompt replaced the turn"));
1282
+ await previous.settled;
1283
+ }
1284
+ const signals = [
1285
+ cancel.signal,
1286
+ request_signal,
1287
+ ...config.abort === void 0 ? [] : [config.abort]
1288
+ ];
1289
+ return await run_turn(config, record, prompt, AbortSignal.any(signals), send);
1290
+ } finally {
1291
+ settle_turn();
1292
+ }
1293
+ }
1294
+ /**
1295
+ * Cancel the session's latest turn on the client's `session/cancel`.
1296
+ */
1297
+ function cancel_turn(record) {
1298
+ record.last_turn?.cancel.abort(new aborted_error("the ACP client cancelled the turn"));
1299
+ }
1300
+ //#endregion
1301
+ //#region src/acp/errors.ts
1302
+ /**
1303
+ * Typed errors for the ACP adapter.
1304
+ *
1305
+ * Listed alongside src/mcp/errors.ts in the `no-class` rule ignores:
1306
+ * `instanceof` branching is how callers tell a missing optional peer apart
1307
+ * from a failure inside a prompt turn.
1308
+ */
1309
+ var acp_sdk_missing_error = class extends Error {
1310
+ kind = "acp_sdk_missing_error";
1311
+ constructor(message = "@agentclientprotocol/sdk is required for fascicle/acp; install it with its zod peer: pnpm add @agentclientprotocol/sdk zod") {
1312
+ super(message);
1313
+ this.name = "acp_sdk_missing_error";
1314
+ }
1315
+ };
1316
+ //#endregion
1317
+ //#region src/acp/sdk_loader.ts
1318
+ /**
1319
+ * Lazy loader for the optional `@agentclientprotocol/sdk` peer.
1320
+ *
1321
+ * The adapter needs SDK values (the `agent()` builder, `ndJsonStream`,
1322
+ * `RequestError`), so it imports the SDK dynamically rather than statically:
1323
+ * a consumer can import `fascicle/acp` without the SDK installed and only pays
1324
+ * for it when they serve a flow. A missing peer surfaces as a typed
1325
+ * `acp_sdk_missing_error` with install guidance, mirroring
1326
+ * src/mcp/sdk_loader.ts.
1327
+ *
1328
+ * The package root is the SDK's stable protocol v1 entry; v2 sits under its
1329
+ * `experimental/` subpaths and stays out of this build. The SDK imports
1330
+ * `zod/v4` at runtime as its own peer, so a missing zod fails here too, and
1331
+ * the error names both installs.
1332
+ */
1333
+ /**
1334
+ * Dynamically imports the `@agentclientprotocol/sdk` v1 entry, throwing a
1335
+ * typed `acp_sdk_missing_error` when the optional peer (or its zod peer) is
1336
+ * not installed.
1337
+ */
1338
+ async function load_acp_sdk() {
1339
+ try {
1340
+ return await import("@agentclientprotocol/sdk");
1341
+ } catch (err) {
1342
+ throw new acp_sdk_missing_error(`@agentclientprotocol/sdk is required for fascicle/acp; install it with its zod peer: pnpm add @agentclientprotocol/sdk zod (cause: ${err instanceof Error ? err.message : String(err)})`);
1343
+ }
1344
+ }
1345
+ //#endregion
1346
+ //#region src/acp/acp_agent.ts
1347
+ /**
1348
+ * acp_agent: the ACP agent app that answers each prompt turn by running a
1349
+ * flow.
1350
+ *
1351
+ * It registers the protocol v1 handlers and holds the sessions, and connects
1352
+ * to anything the SDK can: `serve_acp`'s stdio streams, or an in-process
1353
+ * `client()` in a test. It doesn't own the process, so it leaves the console
1354
+ * and the engine alone; `serve_acp` handles both.
1355
+ */
1356
+ /**
1357
+ * The message a failure carries, whatever was thrown.
1358
+ */
1359
+ function message_of(err) {
1360
+ return err instanceof Error ? err.message : String(err);
1361
+ }
1362
+ /**
1363
+ * Turn a failure inside a handler into a JSON-RPC error that carries its
1364
+ * message. The SDK reports a plain thrown `Error` as a bare "Internal error",
1365
+ * which tells the user in the client nothing about what went wrong.
1366
+ */
1367
+ function internal_error(sdk, err) {
1368
+ return sdk.RequestError.internalError(void 0, message_of(err));
1369
+ }
1370
+ /**
1371
+ * A function that sends one update to the client for one session.
1372
+ */
1373
+ function sender(sdk, client, sessionId) {
1374
+ return (update) => client.notify(sdk.methods.client.session.update, {
1375
+ sessionId,
1376
+ update
1377
+ });
1378
+ }
1379
+ /**
1380
+ * A function that asks the client to approve one tool call. The SDK
1381
+ * withdraws the request with `$/cancel_request` once `cancel` fires, which
1382
+ * is the turn's abort, so a cancelled turn takes its prompt down with it.
1383
+ */
1384
+ function permission_asker(sdk, client) {
1385
+ return (request, cancel) => client.request(sdk.methods.client.session.requestPermission, request, { cancellationSignal: cancel });
1386
+ }
1387
+ /**
1388
+ * The mode a client asked for, or an invalid-params error naming the modes
1389
+ * there are. `field` is the param the id arrived in, for the error's data.
1390
+ */
1391
+ function requested_mode(sdk, id, field) {
1392
+ if (is_acp_mode(id)) return id;
1393
+ throw sdk.RequestError.invalidParams({ [field]: id }, unknown_mode_message(id));
1394
+ }
1395
+ /**
1396
+ * Build the ACP agent app that answers each prompt turn by running the
1397
+ * config's flow, with its handlers registered and not yet connected.
1398
+ */
1399
+ async function acp_agent(config) {
1400
+ const sdk = await load_acp_sdk();
1401
+ const sessions = /* @__PURE__ */ new Map();
1402
+ let client_capabilities = {};
1403
+ const session_of = (sessionId) => {
1404
+ const record = sessions.get(sessionId);
1405
+ if (record !== void 0) return record;
1406
+ throw sdk.RequestError.invalidParams({ sessionId }, `unknown session ${sessionId}; start one with session/new first`);
1407
+ };
1408
+ return sdk.agent().onRequest("initialize", (ctx) => {
1409
+ client_capabilities = ctx.params.clientCapabilities ?? {};
1410
+ return {
1411
+ protocolVersion: sdk.PROTOCOL_VERSION,
1412
+ agentInfo: {
1413
+ name: config.name,
1414
+ version: config.version ?? "0.0.0"
1415
+ },
1416
+ agentCapabilities: {
1417
+ loadSession: false,
1418
+ promptCapabilities: { embeddedContext: true },
1419
+ sessionCapabilities: { additionalDirectories: {} }
1420
+ },
1421
+ authMethods: []
1422
+ };
1423
+ }).onRequest("authenticate", () => ({})).onRequest("session/new", async (ctx) => {
1424
+ const { cwd, additionalDirectories: additional_directories = [] } = ctx.params;
1425
+ const roots = await resolve_roots([cwd, ...additional_directories]).catch((err) => {
1426
+ throw sdk.RequestError.invalidParams({
1427
+ cwd,
1428
+ additionalDirectories: additional_directories
1429
+ }, message_of(err));
1430
+ });
1431
+ const id = randomUUID();
1432
+ const modes = session_modes(config.default_mode ?? "manual", sender(sdk, ctx.client, id));
1433
+ const cards = create_card_sync();
1434
+ const approver = session_approver({
1435
+ modes,
1436
+ cards,
1437
+ ask: permission_asker(sdk, ctx.client)
1438
+ });
1439
+ const session = {
1440
+ id,
1441
+ cwd,
1442
+ additional_directories,
1443
+ roots,
1444
+ client_capabilities,
1445
+ mode: modes.current,
1446
+ approve: (request) => approver(session, request)
1447
+ };
1448
+ try {
1449
+ const flow = typeof config.flow === "function" ? config.flow(session) : config.flow;
1450
+ sessions.set(id, {
1451
+ session,
1452
+ flow,
1453
+ history: [],
1454
+ cards,
1455
+ last_turn: null,
1456
+ modes
1457
+ });
1458
+ } catch (err) {
1459
+ throw internal_error(sdk, err);
1460
+ }
1461
+ return {
1462
+ sessionId: id,
1463
+ modes: mode_state(modes.current()),
1464
+ configOptions: config_options(modes.current())
1465
+ };
1466
+ }).onRequest("session/prompt", async (ctx) => {
1467
+ const { sessionId, prompt } = ctx.params;
1468
+ const record = session_of(sessionId);
1469
+ try {
1470
+ return await prompt_turn(config, record, prompt, ctx.signal, sender(sdk, ctx.client, sessionId));
1471
+ } catch (err) {
1472
+ throw internal_error(sdk, err);
1473
+ }
1474
+ }).onRequest("session/set_mode", async (ctx) => {
1475
+ const { sessionId, modeId } = ctx.params;
1476
+ const { modes } = session_of(sessionId);
1477
+ await modes.switch_to(requested_mode(sdk, modeId, "modeId"));
1478
+ return {};
1479
+ }).onRequest("session/set_config_option", async (ctx) => {
1480
+ const { sessionId, configId, value } = ctx.params;
1481
+ const { modes } = session_of(sessionId);
1482
+ if (configId !== "mode") throw sdk.RequestError.invalidParams({ configId }, `unknown config option ${configId}; the only one is ${MODE_CONFIG_ID}`);
1483
+ await modes.switch_to(requested_mode(sdk, value, "value"));
1484
+ return { configOptions: config_options(modes.current()) };
1485
+ }).onNotification("session/cancel", (ctx) => {
1486
+ const record = sessions.get(ctx.params.sessionId);
1487
+ if (record !== void 0) cancel_turn(record);
1488
+ });
1489
+ }
1490
+ //#endregion
1491
+ //#region src/acp/serve_streams.ts
1492
+ /**
1493
+ * The ACP agent's serving loop, minus the process.
1494
+ *
1495
+ * `serve_streams` is everything `serve_acp` does once the console and the
1496
+ * signals are handled: connect `acp_agent` to a pair of ndjson byte streams,
1497
+ * hold the connection until the client hangs up or `shutdown` fires, then
1498
+ * dispose the engine. It takes its streams as arguments, mirroring
1499
+ * `execute_stdio` under `run_stdio`, so the disconnect path is unit-tested
1500
+ * here and the thin glue in `serve_acp.ts` owns the real stdin and stdout.
1501
+ *
1502
+ * Closing the connection is what aborts the runs: the SDK aborts every
1503
+ * in-flight request's signal as it closes, and each prompt turn's run
1504
+ * listens on its request's signal. So by the time `closed` resolves, every
1505
+ * active run has seen its abort, and only then is the engine disposed.
1506
+ */
1507
+ /**
1508
+ * Serve the config's flow as an ACP agent over `io` until the client
1509
+ * disconnects or `io.shutdown` fires, then dispose the engine once every
1510
+ * active run has been aborted.
1511
+ */
1512
+ async function serve_streams(config, io) {
1513
+ const sdk = await load_acp_sdk();
1514
+ const connection = (await acp_agent(config)).connect(sdk.ndJsonStream(io.output, io.input));
1515
+ const { shutdown } = io;
1516
+ if (shutdown !== void 0) {
1517
+ if (shutdown.aborted) connection.close(shutdown.reason);
1518
+ else shutdown.addEventListener("abort", () => connection.close(shutdown.reason));
1519
+ }
1520
+ await connection.closed;
1521
+ await config.engine?.dispose();
1522
+ }
1523
+ //#endregion
1524
+ //#region src/acp/serve_acp.ts
1525
+ /**
1526
+ * Process glue for serving a flow as an ACP agent over stdio.
1527
+ *
1528
+ * Binds `serve_streams` to the real process: ndjson in on stdin, the
1529
+ * protocol out on stdout, and nothing else on stdout ever. A stray log line
1530
+ * from a flow or a dependency would corrupt the protocol stream, so
1531
+ * `console.log`, `console.info`, and `console.debug` go to stderr for the life
1532
+ * of the process.
1533
+ *
1534
+ * SIGTERM and SIGINT abort every active run, dispose the engine, and exit.
1535
+ * A host that ends the agent with a signal instead of closing stdin would
1536
+ * otherwise leave a run's work going after the editor has closed, since each
1537
+ * turn runs with the runner's own signal handlers off. The handlers are
1538
+ * one-shot, so a second Ctrl-C falls through to Node's default and kills the
1539
+ * process outright when a shutdown hangs.
1540
+ *
1541
+ * Excluded from mutation testing as process glue (see stryker.config.mjs);
1542
+ * the spawn tests in `__tests__/e2e/` exercise it for real.
1543
+ */
1544
+ /**
1545
+ * Route the console's stdout methods to stderr, leaving stdout to the
1546
+ * protocol alone.
1547
+ */
1548
+ function route_console_to_stderr() {
1549
+ Object.assign(console, {
1550
+ log: console.error,
1551
+ info: console.error,
1552
+ debug: console.error
1553
+ });
1554
+ }
1555
+ /**
1556
+ * Serve a flow as an ACP agent over stdin and stdout until the client
1557
+ * disconnects, disposing the engine once every active run has been aborted.
1558
+ * A SIGTERM or SIGINT does the same, then exits with the signal's code.
1559
+ */
1560
+ async function serve_acp(config) {
1561
+ route_console_to_stderr();
1562
+ const shutdown = new AbortController();
1563
+ let received = null;
1564
+ const on_signal = (signal) => {
1565
+ received = signal;
1566
+ shutdown.abort(new aborted_error(`received ${signal}`, { reason: { signal } }));
1567
+ };
1568
+ process.once("SIGTERM", on_signal);
1569
+ process.once("SIGINT", on_signal);
1570
+ try {
1571
+ await serve_streams(config, {
1572
+ input: Readable.toWeb(process.stdin),
1573
+ output: Writable.toWeb(process.stdout),
1574
+ shutdown: shutdown.signal
1575
+ });
1576
+ } finally {
1577
+ process.off("SIGTERM", on_signal);
1578
+ process.off("SIGINT", on_signal);
1579
+ }
1580
+ if (received !== null) process.exit(128 + constants.signals[received]);
1581
+ }
1582
+ //#endregion
1583
+ //#region src/acp/tools/run_command.ts
1584
+ /**
1585
+ * run_command: run a shell command in the workspace and hand back what it
1586
+ * printed and how it ended.
1587
+ *
1588
+ * The command is a string the model wrote in POSIX shell, so it runs as
1589
+ * `/bin/sh -c`, which behaves the same on every host and needs no read of
1590
+ * the user's `$SHELL`. Windows has neither that shell nor POSIX process
1591
+ * groups, so there the tool refuses and the file tools carry on.
1592
+ *
1593
+ * Each command leads a process group of its own, so the whole tree it starts
1594
+ * dies together: when the turn is cancelled, when it runs past its timeout,
1595
+ * and when the shell exits, which stops whatever it left running in the
1596
+ * background. Without that last kill, a job left behind would outlive the
1597
+ * call, and then the agent, since nothing would ever abort it. A command
1598
+ * that moves work into a group of its own (`set -m` in an interactive
1599
+ * shell, or a daemon that starts its own session) takes that work out of
1600
+ * reach, as it would from a terminal's Ctrl-C.
1601
+ *
1602
+ * The file tools' containment doesn't bind a command: the shell reaches
1603
+ * anything the user can.
1604
+ *
1605
+ * This is the one file in `src/acp/` that may import `node:child_process`
1606
+ * (rules/no-child-process-outside-run-command.yml).
1607
+ */
1608
+ /** The shell every command runs in. */
1609
+ const SHELL = "/bin/sh";
1610
+ /**
1611
+ * The longest delay a Node timer keeps. A longer one fires after 1 ms
1612
+ * instead, so a longer timeout is held to this, about 24.8 days.
1613
+ */
1614
+ const MAX_TIMER_MS = 2147483647;
1615
+ /**
1616
+ * How long the output may stay open once the shell has exited and its group
1617
+ * has been killed. The group's processes are gone by then, so only
1618
+ * something moved out of the group can be holding it, and that could hold
1619
+ * it for good.
1620
+ */
1621
+ const OUTPUT_GRACE_MS = 1e3;
1622
+ /**
1623
+ * Whether a value counts milliseconds: a whole number of at least 1.
1624
+ */
1625
+ function is_millis(value) {
1626
+ return Number.isInteger(value) && Number(value) >= 1;
1627
+ }
1628
+ /**
1629
+ * Read the call's command and timeout out of its input. The tool loop has
1630
+ * already checked the types against the schema, but a flow that wraps the
1631
+ * tool can call `execute` directly, and the schema's `minimum` is advice to
1632
+ * the model rather than something the loop enforces.
1633
+ */
1634
+ function command_request(input) {
1635
+ const { command, timeout_ms } = as_record(input) ?? {};
1636
+ if (typeof command !== "string") throw new Error("run_command needs a command, as a string");
1637
+ if (timeout_ms !== void 0 && !is_millis(timeout_ms)) throw new Error("run_command counts timeout_ms in milliseconds, so it has to be a whole number of at least 1");
1638
+ return {
1639
+ command,
1640
+ timeout_ms
1641
+ };
1642
+ }
1643
+ /**
1644
+ * Keep a chunk of output while the capture has room, cutting the chunk that
1645
+ * crosses the limit, and count every byte either way. The output goes on
1646
+ * being read past the limit, since a command blocked on a full pipe would
1647
+ * never finish.
1648
+ */
1649
+ function take(capture, chunk) {
1650
+ const size = Buffer.byteLength(chunk);
1651
+ const room = capture.limit - capture.kept;
1652
+ capture.total += size;
1653
+ if (room <= 0) return;
1654
+ capture.parts.push(new StringDecoder().write(Buffer.from(chunk).subarray(0, room)));
1655
+ capture.kept += Math.min(size, room);
1656
+ }
1657
+ /**
1658
+ * What a command printed as the model reads it, without its trailing
1659
+ * whitespace, with a marker when it was cut, and a line saying so when it
1660
+ * printed nothing at all.
1661
+ */
1662
+ function printed(capture) {
1663
+ if (capture.total === 0) return ["[no output]"];
1664
+ const lines = [capture.parts.join("").trimEnd()];
1665
+ if (capture.total > capture.kept) lines.push(`[output cut at ${capture.limit} bytes of ${capture.total}; pipe the command through tail, head, or grep to see the part you need]`);
1666
+ return lines.filter((line) => line !== "");
1667
+ }
1668
+ /**
1669
+ * How a finished command ended, as its report's last line: its exit code,
1670
+ * or the signal that ended it. Node sets exactly one of the two.
1671
+ */
1672
+ function ending(child) {
1673
+ return child.exitCode === null ? `[ended by ${String(child.signalCode)}]` : `[exit code ${child.exitCode}]`;
1674
+ }
1675
+ /**
1676
+ * A finished command's report: what it printed, then how it ended, and a
1677
+ * note when something it moved out of its group held its output open and
1678
+ * was left running.
1679
+ */
1680
+ function report({ capture, child, held }) {
1681
+ const lines = [...printed(capture), ending(child)];
1682
+ if (held) lines.push("[the command exited, but something it moved out of its process group held its output open, so run_command stopped reading and left that running]");
1683
+ return lines.join("\n");
1684
+ }
1685
+ /**
1686
+ * A finished command as its card shows it: what it printed, with nothing in
1687
+ * place of an empty output, and its exit code or the signal that ended it.
1688
+ */
1689
+ function command_preview({ capture, child }) {
1690
+ return {
1691
+ kind: "command",
1692
+ output: capture.total === 0 ? "" : printed(capture).join("\n"),
1693
+ exit_code: child.exitCode,
1694
+ signal: child.signalCode
1695
+ };
1696
+ }
1697
+ /**
1698
+ * The error a call that ran past its timeout fails with, carrying what the
1699
+ * command printed before it was killed.
1700
+ */
1701
+ function timeout_error(capture, timeout_ms) {
1702
+ return /* @__PURE__ */ new Error(`the command didn't finish within ${timeout_ms / 1e3} s, so run_command killed it and everything it started; pass a larger timeout_ms if it needs longer, but a server or a watch mode never finishes, so run it in a way that does. What it printed before then:\n${printed(capture).join("\n")}`);
1703
+ }
1704
+ /**
1705
+ * Kill a command's whole process group with SIGKILL, the one signal no
1706
+ * command can ignore. The turn's abort can be the agent's last act before
1707
+ * `serve_acp` exits, which leaves no later moment to follow a gentler
1708
+ * signal with this one.
1709
+ */
1710
+ function kill_group(child) {
1711
+ if (child.pid === void 0) return;
1712
+ try {
1713
+ process.kill(-child.pid, "SIGKILL");
1714
+ } catch {}
1715
+ }
1716
+ /**
1717
+ * Run one command to its end in its own process group. A command that ends
1718
+ * on its own is a result, whatever its exit code; a timeout and a shell that
1719
+ * won't start are errors, and the turn's abort rejects with its reason. The
1720
+ * timeout and the abort kill the group, and the shell's exit kills whatever
1721
+ * it left behind. Each reads on to the end of the output, so what the
1722
+ * command printed last isn't lost, until the grace after the shell's exit
1723
+ * runs out. However the call ends, its timers and the abort listener go
1724
+ * with it.
1725
+ */
1726
+ async function run_shell(request, cwd, settings, abort) {
1727
+ abort.throwIfAborted();
1728
+ const timeout_ms = request.timeout_ms ?? settings.timeout_ms;
1729
+ const capture = {
1730
+ limit: settings.output_limit_bytes,
1731
+ parts: [],
1732
+ kept: 0,
1733
+ total: 0
1734
+ };
1735
+ const child = spawn(SHELL, ["-c", request.command], {
1736
+ cwd,
1737
+ env: settings.env === void 0 ? void 0 : { ...settings.env },
1738
+ detached: true,
1739
+ stdio: [
1740
+ "ignore",
1741
+ "pipe",
1742
+ "pipe"
1743
+ ]
1744
+ });
1745
+ const { promise, resolve, reject } = Promise.withResolvers();
1746
+ let timed_out = false;
1747
+ let held = false;
1748
+ let grace;
1749
+ const on_abort = () => {
1750
+ kill_group(child);
1751
+ reject(abort.reason);
1752
+ };
1753
+ for (const stream of [child.stdout, child.stderr]) {
1754
+ stream.setEncoding("utf8");
1755
+ stream.on("data", (chunk) => {
1756
+ take(capture, chunk);
1757
+ });
1758
+ }
1759
+ const timer = setTimeout(() => {
1760
+ timed_out = true;
1761
+ kill_group(child);
1762
+ }, Math.min(timeout_ms, MAX_TIMER_MS));
1763
+ child.once("error", (err) => {
1764
+ reject(new Error(`run_command couldn't start ${SHELL} in ${cwd} (${err.message}); the workspace may have been moved or deleted`, { cause: err }));
1765
+ });
1766
+ child.once("exit", () => {
1767
+ clearTimeout(timer);
1768
+ kill_group(child);
1769
+ grace = setTimeout(() => {
1770
+ held = true;
1771
+ child.stdout.destroy();
1772
+ child.stderr.destroy();
1773
+ }, OUTPUT_GRACE_MS);
1774
+ });
1775
+ child.once("close", () => {
1776
+ if (timed_out) reject(timeout_error(capture, timeout_ms));
1777
+ else resolve({
1778
+ capture,
1779
+ child,
1780
+ held
1781
+ });
1782
+ });
1783
+ abort.addEventListener("abort", on_abort);
1784
+ try {
1785
+ return await promise;
1786
+ } finally {
1787
+ clearTimeout(timer);
1788
+ clearTimeout(grace);
1789
+ abort.removeEventListener("abort", on_abort);
1790
+ }
1791
+ }
1792
+ /**
1793
+ * The `run_command` tool for one session: a command run through the shell
1794
+ * in its `cwd`, with a timeout, an output cap, and the environment the
1795
+ * settings give it, its whole process tree killed when the turn is
1796
+ * cancelled. POSIX only: on Windows every call is refused.
1797
+ */
1798
+ function run_command_tool(session, settings) {
1799
+ return {
1800
+ name: "run_command",
1801
+ description: [
1802
+ `Run a shell command with ${SHELL} -c in the workspace root, and return what it printed (stdout and stderr together) and its exit code.`,
1803
+ "Each call starts a fresh shell there, so a cd lasts for its own command only.",
1804
+ `The command is stopped after ${settings.timeout_ms / 1e3} s unless timeout_ms says otherwise,`,
1805
+ `and output past ${settings.output_limit_bytes} bytes is cut, with a note that says so; run it again through tail, head, or grep for the part you need.`,
1806
+ "Give the command plainly, without 2>&1 or a pipe to trim output that may well fit:",
1807
+ "the user can allow a plain command for the rest of the session, but never one that holds a pipe, a redirect, &&, or ;.",
1808
+ "It gets no input, and anything it starts is stopped once it exits, so it can't leave a server or a watcher running."
1809
+ ].join(" "),
1810
+ input_schema: json_schema_to_standard({
1811
+ type: "object",
1812
+ properties: {
1813
+ command: {
1814
+ type: "string",
1815
+ description: "The command line, as you would type it in a POSIX shell"
1816
+ },
1817
+ timeout_ms: {
1818
+ type: "integer",
1819
+ minimum: 1,
1820
+ description: `How long the command may run, in milliseconds; default: ${settings.timeout_ms}`
1821
+ }
1822
+ },
1823
+ required: ["command"],
1824
+ additionalProperties: false
1825
+ }),
1826
+ execute: async (input, ctx) => {
1827
+ if (process.platform === "win32") throw new Error(`run_command runs commands through ${SHELL} in a process group of their own, which Windows doesn't have, so it can only refuse here; read_file, list_files, search, write_file, and edit_file still work`);
1828
+ const finished = await run_shell(command_request(input), session.cwd, settings, ctx.abort);
1829
+ record_preview(session, ctx.tool_call_id, command_preview(finished));
1830
+ return report(finished);
1831
+ }
1832
+ };
1833
+ }
1834
+ //#endregion
1835
+ //#region src/acp/workspace_tools.ts
1836
+ /** The most lines one `read_file` call returns unless the options say otherwise. */
1837
+ const READ_LIMIT_LINES = 2e3;
1838
+ /** The names `list_files` and `search` skip unless the options say otherwise. */
1839
+ const IGNORE = [".git", "node_modules"];
1840
+ /**
1841
+ * How long one `search` may run, its worker's start included, before it's
1842
+ * stopped. Long enough to read a large repository, and short enough that a
1843
+ * pattern stuck backtracking comes back as an error the model can act on.
1844
+ */
1845
+ const SEARCH_BUDGET_MS = 3e4;
1846
+ /** How long one `run_command` call may run unless the options or the call say otherwise. */
1847
+ const COMMAND_TIMEOUT_MS = 12e4;
1848
+ /** The most output one `run_command` call returns unless the options say otherwise. */
1849
+ const OUTPUT_LIMIT_BYTES = 32e3;
1850
+ /**
1851
+ * `tool`, asking for approval before each call when the session's mode asks
1852
+ * before `action`. The mode is read at each call, not once, so a switch the
1853
+ * client makes mid-turn holds from the next call on.
1854
+ */
1855
+ function gated(tool, session, action) {
1856
+ return {
1857
+ ...tool,
1858
+ needs_approval: () => asks_before(session.mode(), action)
1859
+ };
1860
+ }
1861
+ /**
1862
+ * The workspace tools for one session: the reads (`read_file`, `list_files`,
1863
+ * and `search`), then the writes (`write_file` and `edit_file`), each
1864
+ * confined to the session's `cwd` and additional directories, then
1865
+ * `run_command`. The writes and the command ask before they run as the
1866
+ * session's mode says.
1867
+ */
1868
+ function workspace_tools(session, options = {}) {
1869
+ const ignore = options.ignore ?? IGNORE;
1870
+ return [
1871
+ read_file_tool(session, options.read_limit_lines ?? READ_LIMIT_LINES),
1872
+ list_files_tool(session, ignore),
1873
+ search_tool(session, ignore, SEARCH_BUDGET_MS),
1874
+ gated(write_file_tool(session), session, "edit"),
1875
+ gated(edit_file_tool(session), session, "edit"),
1876
+ gated(run_command_tool(session, {
1877
+ timeout_ms: options.command_timeout_ms ?? COMMAND_TIMEOUT_MS,
1878
+ output_limit_bytes: options.output_limit_bytes ?? OUTPUT_LIMIT_BYTES,
1879
+ env: options.command_env
1880
+ }), session, "command")
1881
+ ];
1882
+ }
1883
+ //#endregion
1884
+ export { acp_agent, acp_sdk_missing_error, create_acp_mapper_state, serve_acp, to_session_updates, workspace_tools };
1885
+
1886
+ //# sourceMappingURL=acp.js.map