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