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