fascicle 0.15.0 → 0.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +121 -0
- package/README.md +8 -8
- package/dist/acp.d.ts +9 -2
- package/dist/acp.js +1538 -1472
- 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-ha9xmgwE.js → engine-CR8q2IqV.js} +173 -67
- 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-px31fffH.js → invoke-COaeZ-vy.js} +6 -5
- package/dist/invoke-COaeZ-vy.js.map +1 -0
- package/dist/{json_schema_to_standard-BTWD0J6p.js → json_schema_to_standard-C4F4lXHE.js} +9 -12
- package/dist/json_schema_to_standard-C4F4lXHE.js.map +1 -0
- package/dist/{leading_system-DfJLqpGi.js → leading_system-PoHzNHuV.js} +28 -8
- package/dist/leading_system-PoHzNHuV.js.map +1 -0
- package/dist/mcp.d.ts +3 -2
- package/dist/mcp.js +8 -4
- package/dist/mcp.js.map +1 -1
- package/dist/otel.js +10 -10
- package/dist/otel.js.map +1 -1
- package/dist/{search-CA_OqFeW.js → search-CpCJYMUm.js} +53 -6
- 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-De-TVQxS.d.ts → types-Sw0oHW-_.d.ts} +6 -7
- 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 +5 -5
- package/dist/adapters-DNnzeLxr.js.map +0 -1
- package/dist/core-CDrz0NM1.js.map +0 -1
- package/dist/engine-ha9xmgwE.js.map +0 -1
- package/dist/invoke-px31fffH.js.map +0 -1
- package/dist/json_schema_to_standard-BTWD0J6p.js.map +0 -1
- package/dist/leading_system-DfJLqpGi.js.map +0 -1
- package/dist/search-CA_OqFeW.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,15 +1,16 @@
|
|
|
1
|
-
import { E as run, k as aborted_error } from "./core-
|
|
2
|
-
import { t as as_record } from "./records-1HU7mWXf.js";
|
|
3
|
-
import { t as json_schema_to_standard } from "./json_schema_to_standard-
|
|
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
|
|
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";
|
|
5
6
|
import { randomUUID } from "node:crypto";
|
|
6
7
|
import { mkdir, open, stat, writeFile } from "node:fs/promises";
|
|
7
8
|
import { dirname, resolve } from "node:path";
|
|
8
9
|
import { constants } from "node:os";
|
|
9
10
|
import { spawn } from "node:child_process";
|
|
10
11
|
import { isUtf8 } from "node:buffer";
|
|
11
|
-
import { Readable, Writable } from "node:stream";
|
|
12
12
|
import { StringDecoder } from "node:string_decoder";
|
|
13
|
+
import { Readable, Writable } from "node:stream";
|
|
13
14
|
/** The id of the config option that carries the mode, the only option this agent has. */
|
|
14
15
|
const MODE_CONFIG_ID = "mode";
|
|
15
16
|
/** Every mode, in the order a client lists them. */
|
|
@@ -150,1768 +151,1833 @@ function take_preview(session, tool_call_id) {
|
|
|
150
151
|
return store_of(session).get(tool_call_id)?.shift();
|
|
151
152
|
}
|
|
152
153
|
//#endregion
|
|
153
|
-
//#region src/acp/
|
|
154
|
+
//#region src/acp/tools/write_file.ts
|
|
154
155
|
/**
|
|
155
|
-
*
|
|
156
|
-
*
|
|
156
|
+
* write_file: create a text file in the workspace, or replace everything one
|
|
157
|
+
* holds.
|
|
157
158
|
*
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
*
|
|
161
|
-
*
|
|
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.
|
|
159
|
+
* Every write is worked out before it happens, as the file's whole text
|
|
160
|
+
* before and after, so the client can be shown the change as a diff before
|
|
161
|
+
* anything reaches the disk. `edit_file` builds its change from the same
|
|
162
|
+
* pieces, so the two tools agree on what they refuse and how they write.
|
|
166
163
|
*
|
|
167
|
-
*
|
|
168
|
-
*
|
|
169
|
-
*
|
|
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.
|
|
164
|
+
* A write lands at the path's real location, which `contain` placed inside a
|
|
165
|
+
* root, and creates the directories it needs there, so a model writing
|
|
166
|
+
* `src/new/thing.ts` doesn't need a command to make `src/new` first.
|
|
182
167
|
*/
|
|
183
|
-
function shown(session, path) {
|
|
184
|
-
return shown_path(session, absolute(session, path));
|
|
185
|
-
}
|
|
186
168
|
/**
|
|
187
|
-
* The
|
|
188
|
-
*
|
|
189
|
-
*
|
|
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.
|
|
190
172
|
*/
|
|
191
|
-
|
|
192
|
-
if (typeof limit === "number") return ` (${first} - ${first + limit - 1})`;
|
|
193
|
-
if (typeof offset === "number") return ` (from line ${offset})`;
|
|
194
|
-
return "";
|
|
195
|
-
}
|
|
173
|
+
const CHANGE_LIMIT_BYTES = 1e6;
|
|
196
174
|
/**
|
|
197
|
-
*
|
|
198
|
-
* the line the read starts on.
|
|
175
|
+
* Read the call's path and content out of its input.
|
|
199
176
|
*/
|
|
200
|
-
function
|
|
201
|
-
|
|
202
|
-
|
|
177
|
+
function write_request(input) {
|
|
178
|
+
const { path, content } = as_record(input) ?? {};
|
|
179
|
+
if (typeof path !== "string" || typeof content !== "string") throw new Error("write_file needs a path and the content to write, as strings");
|
|
203
180
|
return {
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
path: absolute(session, path),
|
|
207
|
-
line: first
|
|
208
|
-
}]
|
|
181
|
+
path,
|
|
182
|
+
content
|
|
209
183
|
};
|
|
210
184
|
}
|
|
211
185
|
/**
|
|
212
|
-
*
|
|
213
|
-
*
|
|
214
|
-
*
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
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.
|
|
186
|
+
* The text a write would replace, or `null` when no file is there yet.
|
|
187
|
+
* Anything but a regular UTF-8 text file is refused, because the change is
|
|
188
|
+
* shown as a diff of text, and rewriting a file in another encoding would
|
|
189
|
+
* change bytes outside the edit. A file with other hard links is refused too:
|
|
190
|
+
* a write changes the file under every name it has, and real paths can't say
|
|
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.
|
|
235
194
|
*/
|
|
236
|
-
function
|
|
237
|
-
const
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
195
|
+
async function current_text(real, shown, tool) {
|
|
196
|
+
const info = await stat(real).catch((err) => {
|
|
197
|
+
if (error_code(err) === "ENOENT") return void 0;
|
|
198
|
+
throw err;
|
|
199
|
+
});
|
|
200
|
+
if (info === void 0) return null;
|
|
201
|
+
if (info.isDirectory()) throw new Error(`${shown} is a directory; ${tool} changes a file, so name one inside it`);
|
|
202
|
+
if (!info.isFile()) throw new Error(`${shown} isn't a regular file, so ${tool} can't change it`);
|
|
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`);
|
|
205
|
+
const handle = await open(real);
|
|
206
|
+
try {
|
|
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`);
|
|
208
|
+
const bytes = await handle.readFile();
|
|
209
|
+
if (!isUtf8(bytes)) throw new Error(`${shown} isn't UTF-8 text, so ${tool} won't change it`);
|
|
210
|
+
return bytes.toString("utf8");
|
|
211
|
+
} finally {
|
|
212
|
+
await handle.close();
|
|
213
|
+
}
|
|
242
214
|
}
|
|
243
215
|
/**
|
|
244
|
-
*
|
|
216
|
+
* Write a change's new text where it lands, creating the directories it
|
|
217
|
+
* needs first. A turn cancelled while the change was worked out stops here,
|
|
218
|
+
* before anything is written. A new file is created exclusively, so a file or
|
|
219
|
+
* a symlink that appeared at its path since then stops the write instead of
|
|
220
|
+
* taking it.
|
|
245
221
|
*/
|
|
246
|
-
function
|
|
247
|
-
|
|
222
|
+
async function apply_change(change, abort) {
|
|
223
|
+
abort.throwIfAborted();
|
|
224
|
+
await mkdir(dirname(change.real), { recursive: true });
|
|
225
|
+
await writeFile(change.real, change.new_text, change.old_text === null ? { flag: "wx" } : {});
|
|
248
226
|
}
|
|
249
227
|
/**
|
|
250
|
-
*
|
|
251
|
-
*
|
|
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`.
|
|
228
|
+
* Leave a change that landed in the session's preview store, for the card
|
|
229
|
+
* of the call that made it to show as a diff.
|
|
288
230
|
*/
|
|
289
|
-
function
|
|
290
|
-
|
|
291
|
-
|
|
231
|
+
function record_change(session, tool_call_id, change) {
|
|
232
|
+
record_preview(session, tool_call_id, {
|
|
233
|
+
kind: "change",
|
|
234
|
+
path: change.path,
|
|
235
|
+
old_text: change.old_text,
|
|
236
|
+
new_text: change.new_text,
|
|
237
|
+
line: change.line
|
|
238
|
+
});
|
|
292
239
|
}
|
|
293
240
|
/**
|
|
294
|
-
* The
|
|
295
|
-
*
|
|
241
|
+
* The change a `write_file` call would make, worked out without writing: its
|
|
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.
|
|
296
245
|
*/
|
|
297
|
-
function
|
|
246
|
+
async function write_file_change(session, input) {
|
|
247
|
+
const request = write_request(input);
|
|
248
|
+
const target = await contain_writable(session, request.path, "write_file");
|
|
249
|
+
const old_text = await current_text(target.real, request.path, "write_file");
|
|
298
250
|
return {
|
|
299
|
-
|
|
300
|
-
|
|
251
|
+
...target,
|
|
252
|
+
old_text,
|
|
253
|
+
new_text: request.content
|
|
301
254
|
};
|
|
302
255
|
}
|
|
303
256
|
/**
|
|
304
|
-
*
|
|
305
|
-
*
|
|
257
|
+
* The `write_file` tool for one session: a file inside its workspace,
|
|
258
|
+
* created or replaced whole. The model reads back a line saying which, since
|
|
259
|
+
* it already has the text it sent.
|
|
306
260
|
*/
|
|
307
|
-
function
|
|
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 };
|
|
261
|
+
function write_file_tool(session) {
|
|
311
262
|
return {
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
263
|
+
name: "write_file",
|
|
264
|
+
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.",
|
|
265
|
+
input_schema: json_schema_to_standard({
|
|
266
|
+
type: "object",
|
|
267
|
+
properties: {
|
|
268
|
+
path: {
|
|
269
|
+
type: "string",
|
|
270
|
+
description: "The file to write, absolute or relative to the workspace root"
|
|
271
|
+
},
|
|
272
|
+
content: {
|
|
273
|
+
type: "string",
|
|
274
|
+
description: "The file's whole text"
|
|
275
|
+
}
|
|
276
|
+
},
|
|
277
|
+
required: ["path", "content"],
|
|
278
|
+
additionalProperties: false
|
|
279
|
+
}),
|
|
280
|
+
execute: async (input, ctx) => {
|
|
281
|
+
const change = await write_file_change(session, input);
|
|
282
|
+
await apply_change(change, ctx.abort);
|
|
283
|
+
record_change(session, ctx.tool_call_id, change);
|
|
284
|
+
return `${change.old_text === null ? "created" : "overwrote"} ${shown_path(session, change.path)}`;
|
|
285
|
+
}
|
|
315
286
|
};
|
|
316
287
|
}
|
|
288
|
+
//#endregion
|
|
289
|
+
//#region src/acp/tools/edit_file.ts
|
|
317
290
|
/**
|
|
318
|
-
*
|
|
319
|
-
*
|
|
320
|
-
*
|
|
291
|
+
* Read the call's path, texts, and `replace_all` out of its input, refusing
|
|
292
|
+
* an `old_text` that's empty, which matches everywhere, or the same as
|
|
293
|
+
* `new_text`, which changes nothing.
|
|
321
294
|
*/
|
|
322
|
-
function
|
|
323
|
-
const
|
|
324
|
-
if (
|
|
325
|
-
|
|
295
|
+
function edit_request(input) {
|
|
296
|
+
const { path, old_text, new_text, replace_all = false } = as_record(input) ?? {};
|
|
297
|
+
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");
|
|
298
|
+
if (old_text === "") throw new Error("old_text is empty, so there's nothing to find; write_file writes a whole file");
|
|
299
|
+
if (old_text === new_text) throw new Error("old_text and new_text are the same, so the edit would change nothing");
|
|
300
|
+
return {
|
|
301
|
+
path,
|
|
302
|
+
old_text,
|
|
303
|
+
new_text,
|
|
304
|
+
replace_all
|
|
305
|
+
};
|
|
326
306
|
}
|
|
327
307
|
/**
|
|
328
|
-
*
|
|
308
|
+
* The change an `edit_file` call would make, worked out without writing: the
|
|
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`.
|
|
329
312
|
*/
|
|
330
|
-
function
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
|
|
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;
|
|
313
|
+
async function edit_file_change(session, input) {
|
|
314
|
+
const request = edit_request(input);
|
|
315
|
+
const target = await contain_writable(session, request.path, "edit_file");
|
|
316
|
+
const text = await current_text(target.real, request.path, "edit_file");
|
|
317
|
+
if (text === null) throw new Error(`${request.path} doesn't exist; write_file creates a file`);
|
|
318
|
+
const pieces = text.split(request.old_text);
|
|
319
|
+
const matches = pieces.length - 1;
|
|
320
|
+
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`);
|
|
321
|
+
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`);
|
|
322
|
+
const before = text.slice(0, text.indexOf(request.old_text));
|
|
347
323
|
return {
|
|
348
|
-
...
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
}] }
|
|
324
|
+
...target,
|
|
325
|
+
old_text: text,
|
|
326
|
+
new_text: pieces.join(request.new_text),
|
|
327
|
+
line: before.split("\n").length,
|
|
328
|
+
matches
|
|
354
329
|
};
|
|
355
330
|
}
|
|
356
331
|
/**
|
|
357
|
-
*
|
|
358
|
-
*
|
|
359
|
-
*
|
|
332
|
+
* The `edit_file` tool for one session: an exact match replaced in a file
|
|
333
|
+
* inside its workspace. The model reads back where the edit landed rather
|
|
334
|
+
* than the file again.
|
|
360
335
|
*/
|
|
361
|
-
function
|
|
362
|
-
const longest = Math.max(2, ...Array.from(text.matchAll(/^`+/gm), ([run]) => run.length));
|
|
363
|
-
const fence = "`".repeat(longest + 1);
|
|
336
|
+
function edit_file_tool(session) {
|
|
364
337
|
return {
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
338
|
+
name: "edit_file",
|
|
339
|
+
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.",
|
|
340
|
+
input_schema: json_schema_to_standard({
|
|
341
|
+
type: "object",
|
|
342
|
+
properties: {
|
|
343
|
+
path: {
|
|
344
|
+
type: "string",
|
|
345
|
+
description: "The file to edit, absolute or relative to the workspace root"
|
|
346
|
+
},
|
|
347
|
+
old_text: {
|
|
348
|
+
type: "string",
|
|
349
|
+
minLength: 1,
|
|
350
|
+
description: "The exact text to replace"
|
|
351
|
+
},
|
|
352
|
+
new_text: {
|
|
353
|
+
type: "string",
|
|
354
|
+
description: "The text to put in its place"
|
|
355
|
+
},
|
|
356
|
+
replace_all: {
|
|
357
|
+
type: "boolean",
|
|
358
|
+
description: "Replace every match of old_text, rather than exactly one; default: false"
|
|
359
|
+
}
|
|
360
|
+
},
|
|
361
|
+
required: [
|
|
362
|
+
"path",
|
|
363
|
+
"old_text",
|
|
364
|
+
"new_text"
|
|
365
|
+
],
|
|
366
|
+
additionalProperties: false
|
|
367
|
+
}),
|
|
368
|
+
execute: async (input, ctx) => {
|
|
369
|
+
const change = await edit_file_change(session, input);
|
|
370
|
+
await apply_change(change, ctx.abort);
|
|
371
|
+
record_change(session, ctx.tool_call_id, change);
|
|
372
|
+
const shown = shown_path(session, change.path);
|
|
373
|
+
return change.matches === 1 ? `edited ${shown} at line ${change.line}` : `edited ${shown} in ${change.matches} places, the first at line ${change.line}`;
|
|
369
374
|
}
|
|
370
375
|
};
|
|
371
376
|
}
|
|
377
|
+
//#endregion
|
|
378
|
+
//#region src/acp/tools/run_command.ts
|
|
372
379
|
/**
|
|
373
|
-
*
|
|
374
|
-
*
|
|
375
|
-
*
|
|
376
|
-
*
|
|
380
|
+
* run_command: run a shell command in the workspace and hand back what it
|
|
381
|
+
* printed and how it ended.
|
|
382
|
+
*
|
|
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.
|
|
387
|
+
*
|
|
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.
|
|
396
|
+
*
|
|
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).
|
|
377
402
|
*/
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
403
|
+
/** The shell every command runs in. */
|
|
404
|
+
const SHELL = "/bin/sh";
|
|
405
|
+
/**
|
|
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.
|
|
408
|
+
*/
|
|
409
|
+
const MAX_TIMER_MS = 2147483647;
|
|
410
|
+
/**
|
|
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.
|
|
415
|
+
*/
|
|
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;
|
|
384
422
|
}
|
|
385
423
|
/**
|
|
386
|
-
*
|
|
387
|
-
*
|
|
388
|
-
*
|
|
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.
|
|
389
428
|
*/
|
|
390
|
-
function
|
|
391
|
-
|
|
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");
|
|
392
433
|
return {
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
signal: null
|
|
434
|
+
command,
|
|
435
|
+
timeout_ms
|
|
396
436
|
};
|
|
397
437
|
}
|
|
398
438
|
/**
|
|
399
|
-
*
|
|
400
|
-
* the
|
|
401
|
-
*
|
|
402
|
-
*
|
|
403
|
-
* text.
|
|
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.
|
|
404
443
|
*/
|
|
405
|
-
function
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
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
|
-
}];
|
|
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);
|
|
430
451
|
}
|
|
431
452
|
/**
|
|
432
|
-
*
|
|
433
|
-
*
|
|
434
|
-
*
|
|
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.
|
|
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.
|
|
437
456
|
*/
|
|
438
|
-
function
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
if (
|
|
442
|
-
|
|
443
|
-
if (shows === "change") return [close_change(closing, preview)];
|
|
444
|
-
return close_command(session, card, chunk, closing, preview);
|
|
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 !== "");
|
|
445
462
|
}
|
|
446
|
-
//#endregion
|
|
447
|
-
//#region src/acp/tools/write_file.ts
|
|
448
463
|
/**
|
|
449
|
-
*
|
|
450
|
-
*
|
|
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.
|
|
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.
|
|
460
466
|
*/
|
|
467
|
+
function ending(child) {
|
|
468
|
+
return child.exitCode === null ? `[ended by ${String(child.signalCode)}]` : `[exit code ${child.exitCode}]`;
|
|
469
|
+
}
|
|
461
470
|
/**
|
|
462
|
-
*
|
|
463
|
-
*
|
|
464
|
-
*
|
|
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.
|
|
465
474
|
*/
|
|
466
|
-
|
|
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
|
+
}
|
|
467
480
|
/**
|
|
468
|
-
*
|
|
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.
|
|
469
483
|
*/
|
|
470
|
-
function
|
|
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");
|
|
484
|
+
function command_preview({ capture, child }) {
|
|
473
485
|
return {
|
|
474
|
-
|
|
475
|
-
|
|
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
|
-
}
|
|
486
|
+
kind: "command",
|
|
487
|
+
output: capture.total === 0 ? "" : printed(capture).join("\n"),
|
|
488
|
+
exit_code: child.exitCode,
|
|
489
|
+
signal: child.signalCode
|
|
490
|
+
};
|
|
507
491
|
}
|
|
508
492
|
/**
|
|
509
|
-
*
|
|
510
|
-
*
|
|
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.
|
|
493
|
+
* The error a call that ran past its timeout fails with, carrying what the
|
|
494
|
+
* command printed before it was killed.
|
|
514
495
|
*/
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
await mkdir(dirname(change.real), { recursive: true });
|
|
518
|
-
await writeFile(change.real, change.new_text, change.old_text === null ? { flag: "wx" } : {});
|
|
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")}`);
|
|
519
498
|
}
|
|
520
499
|
/**
|
|
521
|
-
*
|
|
522
|
-
*
|
|
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.
|
|
523
504
|
*/
|
|
524
|
-
function
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
new_text: change.new_text,
|
|
530
|
-
line: change.line
|
|
531
|
-
});
|
|
505
|
+
function kill_group(child) {
|
|
506
|
+
if (child.pid === void 0) return;
|
|
507
|
+
try {
|
|
508
|
+
process.kill(-child.pid, "SIGKILL");
|
|
509
|
+
} catch {}
|
|
532
510
|
}
|
|
533
511
|
/**
|
|
534
|
-
*
|
|
535
|
-
*
|
|
536
|
-
* the
|
|
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.
|
|
537
520
|
*/
|
|
538
|
-
async function
|
|
539
|
-
|
|
540
|
-
const
|
|
541
|
-
const
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
521
|
+
async function run_shell(request, cwd, settings, abort) {
|
|
522
|
+
abort.throwIfAborted();
|
|
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;
|
|
545
|
+
const on_abort = () => {
|
|
546
|
+
kill_group(child);
|
|
547
|
+
reject(abort.reason);
|
|
548
|
+
};
|
|
549
|
+
for (const stream of [child.stdout, child.stderr]) {
|
|
550
|
+
stream.setEncoding("utf8");
|
|
551
|
+
stream.on("data", (chunk) => {
|
|
552
|
+
take(capture, chunk);
|
|
553
|
+
});
|
|
554
|
+
}
|
|
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();
|
|
546
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);
|
|
587
|
+
try {
|
|
588
|
+
return await promise;
|
|
589
|
+
} finally {
|
|
590
|
+
settled = true;
|
|
591
|
+
clearTimeout(timer);
|
|
592
|
+
clearTimeout(grace);
|
|
593
|
+
abort.removeEventListener("abort", on_abort);
|
|
594
|
+
}
|
|
547
595
|
}
|
|
548
596
|
/**
|
|
549
|
-
* The `
|
|
550
|
-
*
|
|
551
|
-
* it
|
|
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.
|
|
552
601
|
*/
|
|
553
|
-
function
|
|
602
|
+
function run_command_tool(session, settings) {
|
|
554
603
|
return {
|
|
555
|
-
name: "
|
|
556
|
-
description:
|
|
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(" "),
|
|
557
614
|
input_schema: json_schema_to_standard({
|
|
558
615
|
type: "object",
|
|
559
616
|
properties: {
|
|
560
|
-
|
|
617
|
+
command: {
|
|
561
618
|
type: "string",
|
|
562
|
-
description: "The
|
|
619
|
+
description: "The command line, as you would type it in a POSIX shell"
|
|
563
620
|
},
|
|
564
|
-
|
|
565
|
-
type: "
|
|
566
|
-
|
|
621
|
+
timeout_ms: {
|
|
622
|
+
type: "integer",
|
|
623
|
+
minimum: 1,
|
|
624
|
+
description: `How long the command may run, in milliseconds; default: ${settings.timeout_ms}`
|
|
567
625
|
}
|
|
568
626
|
},
|
|
569
|
-
required: ["
|
|
627
|
+
required: ["command"],
|
|
570
628
|
additionalProperties: false
|
|
571
629
|
}),
|
|
572
630
|
execute: async (input, ctx) => {
|
|
573
|
-
|
|
574
|
-
await
|
|
575
|
-
|
|
576
|
-
return
|
|
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);
|
|
577
635
|
}
|
|
578
636
|
};
|
|
579
637
|
}
|
|
580
638
|
//#endregion
|
|
581
|
-
//#region src/acp/
|
|
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;
|
|
582
652
|
/**
|
|
583
|
-
*
|
|
584
|
-
*
|
|
585
|
-
*
|
|
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.
|
|
586
656
|
*/
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
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();
|
|
660
|
+
/**
|
|
661
|
+
* The inputs the session's gated workspace tools were asked about, made
|
|
662
|
+
* empty the first time it's asked for.
|
|
663
|
+
*/
|
|
664
|
+
function asked_of(session) {
|
|
665
|
+
const inputs = asked.get(session) ?? /* @__PURE__ */ new WeakSet();
|
|
666
|
+
asked.set(session, inputs);
|
|
667
|
+
return inputs;
|
|
598
668
|
}
|
|
599
669
|
/**
|
|
600
|
-
*
|
|
601
|
-
*
|
|
602
|
-
* `old_text` isn't there, or is there more than once and the call doesn't set
|
|
603
|
-
* `replace_all`.
|
|
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.
|
|
604
672
|
*/
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
673
|
+
function is_workspace_tool(session, name) {
|
|
674
|
+
return built.get(session)?.has(name) === true;
|
|
675
|
+
}
|
|
676
|
+
/**
|
|
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.
|
|
680
|
+
*/
|
|
681
|
+
function is_workspace_call(session, input) {
|
|
682
|
+
return is_record(input) && asked.get(session)?.has(input) === true;
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
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.
|
|
689
|
+
*/
|
|
690
|
+
function gated(tool, session, action) {
|
|
615
691
|
return {
|
|
616
|
-
...
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
692
|
+
...tool,
|
|
693
|
+
needs_approval: (input) => {
|
|
694
|
+
if (is_record(input)) asked_of(session).add(input);
|
|
695
|
+
return asks_before(session.mode(), action);
|
|
696
|
+
}
|
|
621
697
|
};
|
|
622
698
|
}
|
|
623
699
|
/**
|
|
624
|
-
* The
|
|
625
|
-
*
|
|
626
|
-
*
|
|
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.
|
|
627
706
|
*/
|
|
628
|
-
function
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
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
|
-
};
|
|
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;
|
|
668
723
|
}
|
|
669
724
|
//#endregion
|
|
670
|
-
//#region src/acp/
|
|
725
|
+
//#region src/acp/presentation.ts
|
|
671
726
|
/**
|
|
672
|
-
*
|
|
673
|
-
*
|
|
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 `|`.
|
|
727
|
+
* presentation: how a workspace tool's call looks in the client, matching
|
|
728
|
+
* what Zed's Claude Agent sends for its own tools.
|
|
684
729
|
*
|
|
685
|
-
*
|
|
686
|
-
*
|
|
687
|
-
*
|
|
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.
|
|
688
738
|
*
|
|
689
|
-
*
|
|
690
|
-
* and
|
|
691
|
-
*
|
|
692
|
-
*
|
|
693
|
-
*
|
|
694
|
-
*
|
|
695
|
-
*
|
|
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.
|
|
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.
|
|
712
746
|
*/
|
|
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
747
|
/**
|
|
725
|
-
* A
|
|
748
|
+
* A path the call names, made absolute under the client's `cwd`, which is
|
|
749
|
+
* how a location and a diff carry it.
|
|
726
750
|
*/
|
|
727
|
-
function
|
|
728
|
-
return
|
|
729
|
-
recorded: 0,
|
|
730
|
-
sent: 0,
|
|
731
|
-
moved: Promise.withResolvers(),
|
|
732
|
-
cards: /* @__PURE__ */ new Map()
|
|
733
|
-
};
|
|
751
|
+
function absolute(session, path) {
|
|
752
|
+
return resolve(session.cwd, path);
|
|
734
753
|
}
|
|
735
754
|
/**
|
|
736
|
-
*
|
|
737
|
-
*
|
|
738
|
-
* runner's default logger gives 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.
|
|
739
757
|
*/
|
|
740
|
-
function
|
|
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
|
-
};
|
|
758
|
+
function shown(session, path) {
|
|
759
|
+
return shown_path(session, absolute(session, path));
|
|
756
760
|
}
|
|
757
761
|
/**
|
|
758
|
-
* The
|
|
759
|
-
*
|
|
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.
|
|
760
765
|
*/
|
|
761
|
-
function
|
|
762
|
-
if (
|
|
763
|
-
|
|
764
|
-
return
|
|
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 "";
|
|
765
770
|
}
|
|
766
771
|
/**
|
|
767
|
-
*
|
|
772
|
+
* A `read_file` card: `Read <path>` with the lines it covers, pointing at
|
|
773
|
+
* the line the read starts on.
|
|
768
774
|
*/
|
|
769
|
-
function
|
|
770
|
-
|
|
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
|
+
}]
|
|
784
|
+
};
|
|
771
785
|
}
|
|
772
786
|
/**
|
|
773
|
-
*
|
|
774
|
-
*
|
|
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.
|
|
775
790
|
*/
|
|
776
|
-
function
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
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
|
-
};
|
|
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;
|
|
801
796
|
}
|
|
802
797
|
/**
|
|
803
|
-
*
|
|
804
|
-
*
|
|
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.
|
|
798
|
+
* A `list_files` card: `Find` with the directory and the pattern in code
|
|
799
|
+
* spans, each when the call names it.
|
|
807
800
|
*/
|
|
808
|
-
function
|
|
809
|
-
const
|
|
810
|
-
if (typeof
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
const subject = args.find((arg) => !arg.startsWith("-"));
|
|
814
|
-
return subject === void 0 ? program : [program, subject].join(" ");
|
|
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(" ") };
|
|
815
806
|
}
|
|
816
807
|
/**
|
|
817
|
-
*
|
|
808
|
+
* A `search` card, titled the way the grep command line that does the same
|
|
809
|
+
* search reads.
|
|
818
810
|
*/
|
|
819
|
-
function
|
|
820
|
-
|
|
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(" ") };
|
|
821
817
|
}
|
|
822
818
|
/**
|
|
823
|
-
*
|
|
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.
|
|
819
|
+
* A `run_command` card, titled with the command line itself.
|
|
826
820
|
*/
|
|
827
|
-
|
|
828
|
-
|
|
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
|
-
}
|
|
821
|
+
function describe_command({ command }) {
|
|
822
|
+
return typeof command === "string" ? { title: command } : void 0;
|
|
839
823
|
}
|
|
840
824
|
/**
|
|
841
|
-
*
|
|
842
|
-
* the
|
|
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.
|
|
825
|
+
* The workspace tools by name. The key takes `undefined` too, so a card
|
|
826
|
+
* whose opening the mapper never saw simply finds nothing.
|
|
845
827
|
*/
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
}
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
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
|
+
]);
|
|
871
860
|
/**
|
|
872
|
-
*
|
|
873
|
-
*
|
|
874
|
-
*
|
|
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.
|
|
875
864
|
*/
|
|
876
|
-
|
|
877
|
-
|
|
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
|
-
};
|
|
865
|
+
function presenter_of(session, name) {
|
|
866
|
+
return is_workspace_tool(session, name) ? PRESENTERS.get(name) : void 0;
|
|
890
867
|
}
|
|
891
868
|
/**
|
|
892
|
-
* Whether the
|
|
893
|
-
*
|
|
869
|
+
* Whether the client draws a command's output in a terminal from Zed's
|
|
870
|
+
* `_meta` extension, which it says in `initialize`.
|
|
894
871
|
*/
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
if (outcome.optionId !== "allow_always" || always === void 0) return false;
|
|
899
|
-
await always.grant();
|
|
900
|
-
return true;
|
|
872
|
+
function renders_terminals(session) {
|
|
873
|
+
const { _meta: meta } = session.client_capabilities;
|
|
874
|
+
return meta?.["terminal_output"] === true;
|
|
901
875
|
}
|
|
902
876
|
/**
|
|
903
|
-
*
|
|
904
|
-
*
|
|
877
|
+
* The terminal a card shows, under the card's own id, as Claude Agent names
|
|
878
|
+
* its terminals.
|
|
905
879
|
*/
|
|
906
|
-
function
|
|
907
|
-
|
|
880
|
+
function terminal(card) {
|
|
881
|
+
return {
|
|
882
|
+
type: "terminal",
|
|
883
|
+
terminalId: card
|
|
884
|
+
};
|
|
908
885
|
}
|
|
909
886
|
/**
|
|
910
|
-
*
|
|
911
|
-
*
|
|
912
|
-
* Accept edits leaves a session that has moved past Manual since the call
|
|
913
|
-
* asked where it is.
|
|
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.
|
|
914
889
|
*/
|
|
915
|
-
function
|
|
916
|
-
if (
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
}
|
|
921
|
-
};
|
|
922
|
-
if (key === void 0) return void 0;
|
|
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 };
|
|
923
895
|
return {
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
}
|
|
896
|
+
kind: presenter.kind,
|
|
897
|
+
content: [terminal(card)],
|
|
898
|
+
_meta: { terminal_info: { terminal_id: card } }
|
|
928
899
|
};
|
|
929
900
|
}
|
|
930
901
|
/**
|
|
931
|
-
*
|
|
932
|
-
*
|
|
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.
|
|
933
905
|
*/
|
|
934
|
-
function
|
|
935
|
-
if (
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
optionId: "allow_always",
|
|
940
|
-
name: always.name,
|
|
941
|
-
kind: "allow_always"
|
|
942
|
-
},
|
|
943
|
-
REJECT_ONCE
|
|
944
|
-
];
|
|
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) ?? {};
|
|
945
911
|
}
|
|
946
912
|
/**
|
|
947
|
-
*
|
|
948
|
-
* "always" grants for the life of the session.
|
|
913
|
+
* A file change as a diff, which a client shows as the file's hunks.
|
|
949
914
|
*/
|
|
950
|
-
function
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
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
|
-
}
|
|
915
|
+
function diff_of(change) {
|
|
916
|
+
return {
|
|
917
|
+
type: "diff",
|
|
918
|
+
path: change.path,
|
|
919
|
+
oldText: change.old_text,
|
|
920
|
+
newText: change.new_text
|
|
970
921
|
};
|
|
971
922
|
}
|
|
972
|
-
//#endregion
|
|
973
|
-
//#region src/acp/to_session_updates.ts
|
|
974
923
|
/**
|
|
975
|
-
*
|
|
976
|
-
*
|
|
977
|
-
*
|
|
978
|
-
*
|
|
979
|
-
*
|
|
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.
|
|
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.
|
|
989
929
|
*/
|
|
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
|
+
};
|
|
940
|
+
}
|
|
990
941
|
/**
|
|
991
|
-
*
|
|
992
|
-
*
|
|
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.
|
|
993
945
|
*/
|
|
994
|
-
function
|
|
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);
|
|
995
949
|
return {
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
950
|
+
type: "content",
|
|
951
|
+
content: {
|
|
952
|
+
type: "text",
|
|
953
|
+
text: `${fence}${info}\n${text}\n${fence}`
|
|
954
|
+
}
|
|
1001
955
|
};
|
|
1002
956
|
}
|
|
1003
957
|
/**
|
|
1004
|
-
*
|
|
1005
|
-
*
|
|
1006
|
-
*
|
|
1007
|
-
*
|
|
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.
|
|
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.
|
|
1010
962
|
*/
|
|
1011
|
-
function
|
|
1012
|
-
|
|
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), "")]
|
|
968
|
+
};
|
|
1013
969
|
}
|
|
1014
970
|
/**
|
|
1015
|
-
*
|
|
1016
|
-
*
|
|
1017
|
-
*
|
|
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.
|
|
1018
974
|
*/
|
|
1019
|
-
function
|
|
1020
|
-
|
|
1021
|
-
|
|
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
|
|
981
|
+
};
|
|
1022
982
|
}
|
|
1023
983
|
/**
|
|
1024
|
-
*
|
|
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.
|
|
1025
989
|
*/
|
|
1026
|
-
function
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
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 [];
|
|
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
|
+
}];
|
|
1101
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
|
+
}];
|
|
1102
1015
|
}
|
|
1103
1016
|
/**
|
|
1104
|
-
*
|
|
1105
|
-
*
|
|
1106
|
-
* nothing
|
|
1107
|
-
|
|
1108
|
-
|
|
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.
|
|
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.
|
|
1116
1022
|
*/
|
|
1117
|
-
function
|
|
1118
|
-
if (
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
if (typeof step_id !== "string" || !is_stream_chunk(chunk)) return [];
|
|
1126
|
-
return map_chunk(chunk, step_id, state);
|
|
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);
|
|
1127
1031
|
}
|
|
1128
1032
|
//#endregion
|
|
1129
|
-
//#region src/acp/
|
|
1033
|
+
//#region src/acp/approve.ts
|
|
1130
1034
|
/**
|
|
1131
|
-
*
|
|
1132
|
-
*
|
|
1133
|
-
*
|
|
1134
|
-
*
|
|
1135
|
-
* the
|
|
1136
|
-
*
|
|
1137
|
-
*
|
|
1035
|
+
* approve: ask the client before a workspace tool edits a file or runs a
|
|
1036
|
+
* command, through `session/request_permission`.
|
|
1037
|
+
*
|
|
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 `|`.
|
|
1048
|
+
*
|
|
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.
|
|
1053
|
+
*
|
|
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.
|
|
1138
1065
|
*/
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
}
|
|
1148
|
-
|
|
1149
|
-
|
|
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
|
+
]);
|
|
1150
1077
|
/**
|
|
1151
|
-
*
|
|
1152
|
-
*
|
|
1078
|
+
* Shell syntax that runs, chains, or redirects something past the
|
|
1079
|
+
* command's own program: `;`, `&`, `|`, `>`, `<`, a backtick, `$(`, and a
|
|
1080
|
+
* newline.
|
|
1153
1081
|
*/
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
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
|
+
};
|
|
1158
1093
|
/**
|
|
1159
|
-
*
|
|
1160
|
-
* at all for a flow that returns nothing.
|
|
1094
|
+
* A fresh count for a turn that has recorded and sent nothing yet.
|
|
1161
1095
|
*/
|
|
1162
|
-
function
|
|
1163
|
-
return
|
|
1096
|
+
function fresh_progress() {
|
|
1097
|
+
return {
|
|
1098
|
+
recorded: 0,
|
|
1099
|
+
sent: 0,
|
|
1100
|
+
moved: Promise.withResolvers(),
|
|
1101
|
+
cards: /* @__PURE__ */ new Map()
|
|
1102
|
+
};
|
|
1164
1103
|
}
|
|
1165
1104
|
/**
|
|
1166
|
-
*
|
|
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.
|
|
1167
1108
|
*/
|
|
1168
|
-
function
|
|
1109
|
+
function counting_logger(inner, count) {
|
|
1169
1110
|
return {
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
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();
|
|
1174
1123
|
}
|
|
1175
1124
|
};
|
|
1176
1125
|
}
|
|
1177
1126
|
/**
|
|
1178
|
-
*
|
|
1179
|
-
*
|
|
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.
|
|
1127
|
+
* The raw id of the call a `tool_call_start` chunk opens, or `undefined`
|
|
1128
|
+
* for any other event.
|
|
1184
1129
|
*/
|
|
1185
|
-
function
|
|
1186
|
-
if (
|
|
1187
|
-
|
|
1188
|
-
|
|
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;
|
|
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;
|
|
1192
1134
|
}
|
|
1193
1135
|
/**
|
|
1194
|
-
*
|
|
1195
|
-
* text the client was sent, when there was any. A cancelled turn marks
|
|
1196
|
-
* whichever of the two came last.
|
|
1136
|
+
* Whether an update opens a card.
|
|
1197
1137
|
*/
|
|
1198
|
-
function
|
|
1199
|
-
|
|
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
|
-
});
|
|
1138
|
+
function opens_card(update) {
|
|
1139
|
+
return update.sessionUpdate === "tool_call";
|
|
1213
1140
|
}
|
|
1214
1141
|
/**
|
|
1215
|
-
*
|
|
1216
|
-
*
|
|
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.
|
|
1217
1144
|
*/
|
|
1218
|
-
function
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
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;
|
|
1153
|
+
});
|
|
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
|
+
};
|
|
1226
1170
|
}
|
|
1227
1171
|
/**
|
|
1228
|
-
*
|
|
1229
|
-
*
|
|
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.
|
|
1230
1177
|
*/
|
|
1231
|
-
function
|
|
1232
|
-
|
|
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;
|
|
1233
1183
|
}
|
|
1234
1184
|
/**
|
|
1235
|
-
*
|
|
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.
|
|
1185
|
+
* The message a failure carries, whatever was thrown.
|
|
1238
1186
|
*/
|
|
1239
|
-
|
|
1240
|
-
|
|
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
|
-
}
|
|
1187
|
+
function message_of(err) {
|
|
1188
|
+
return err instanceof Error ? err.message : String(err);
|
|
1254
1189
|
}
|
|
1255
1190
|
/**
|
|
1256
|
-
*
|
|
1257
|
-
*
|
|
1258
|
-
*
|
|
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.
|
|
1259
1194
|
*/
|
|
1260
|
-
async function
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
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);
|
|
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);
|
|
1276
1200
|
};
|
|
1277
|
-
|
|
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);
|
|
1201
|
+
abort.addEventListener("abort", on_abort);
|
|
1285
1202
|
try {
|
|
1286
|
-
await
|
|
1287
|
-
|
|
1288
|
-
|
|
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;
|
|
1203
|
+
return await Promise.race([work(), aborted]);
|
|
1204
|
+
} finally {
|
|
1205
|
+
abort.removeEventListener("abort", on_abort);
|
|
1297
1206
|
}
|
|
1298
|
-
record_exchange(record.history, turn.text, reply.text, cancelled.aborted);
|
|
1299
|
-
return { stopReason: cancelled.aborted ? "cancelled" : "end_turn" };
|
|
1300
1207
|
}
|
|
1301
1208
|
/**
|
|
1302
|
-
*
|
|
1303
|
-
* the
|
|
1304
|
-
*
|
|
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.
|
|
1305
1213
|
*/
|
|
1306
|
-
async function
|
|
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
|
-
};
|
|
1214
|
+
async function change_fields(change, session, input) {
|
|
1314
1215
|
try {
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
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
|
+
}] };
|
|
1327
1237
|
}
|
|
1328
1238
|
}
|
|
1329
1239
|
/**
|
|
1330
|
-
*
|
|
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.
|
|
1331
1243
|
*/
|
|
1332
|
-
function
|
|
1333
|
-
|
|
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
|
+
};
|
|
1334
1258
|
}
|
|
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
1259
|
/**
|
|
1354
|
-
*
|
|
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.
|
|
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.
|
|
1367
1262
|
*/
|
|
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
|
+
}
|
|
1368
1270
|
/**
|
|
1369
|
-
*
|
|
1370
|
-
*
|
|
1371
|
-
* not installed.
|
|
1271
|
+
* Say on stderr that a permission request failed, since the call was
|
|
1272
|
+
* refused without the user ever seeing it.
|
|
1372
1273
|
*/
|
|
1373
|
-
|
|
1374
|
-
|
|
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
|
-
}
|
|
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`);
|
|
1379
1276
|
}
|
|
1380
|
-
//#endregion
|
|
1381
|
-
//#region src/acp/acp_agent.ts
|
|
1382
1277
|
/**
|
|
1383
|
-
*
|
|
1384
|
-
*
|
|
1385
|
-
*
|
|
1386
|
-
*
|
|
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.
|
|
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.
|
|
1418
1282
|
*/
|
|
1419
|
-
function
|
|
1420
|
-
|
|
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;
|
|
1291
|
+
return {
|
|
1292
|
+
name: `Always allow \`${key}\` this session`,
|
|
1293
|
+
grant: async () => {
|
|
1294
|
+
granted.add(key);
|
|
1295
|
+
}
|
|
1296
|
+
};
|
|
1421
1297
|
}
|
|
1422
1298
|
/**
|
|
1423
|
-
* The
|
|
1424
|
-
*
|
|
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`.
|
|
1425
1301
|
*/
|
|
1426
|
-
function
|
|
1427
|
-
if (
|
|
1428
|
-
|
|
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
|
+
];
|
|
1429
1313
|
}
|
|
1430
1314
|
/**
|
|
1431
|
-
*
|
|
1432
|
-
*
|
|
1315
|
+
* Create the approvals for one session's calls, holding its commands'
|
|
1316
|
+
* "always" grants for the life of the session.
|
|
1433
1317
|
*/
|
|
1434
|
-
|
|
1435
|
-
const
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
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);
|
|
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);
|
|
1504
1326
|
try {
|
|
1505
|
-
|
|
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);
|
|
1506
1334
|
} catch (err) {
|
|
1507
|
-
|
|
1335
|
+
if (!request.abort.aborted) warn_failed(request.tool_name, err);
|
|
1336
|
+
return false;
|
|
1508
1337
|
}
|
|
1509
|
-
}
|
|
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
|
-
});
|
|
1338
|
+
};
|
|
1524
1339
|
}
|
|
1525
1340
|
//#endregion
|
|
1526
|
-
//#region src/acp/
|
|
1341
|
+
//#region src/acp/to_session_updates.ts
|
|
1527
1342
|
/**
|
|
1528
|
-
*
|
|
1343
|
+
* Maps a run's events onto ACP `session/update` payloads.
|
|
1529
1344
|
*
|
|
1530
|
-
* `
|
|
1531
|
-
*
|
|
1532
|
-
*
|
|
1533
|
-
*
|
|
1534
|
-
*
|
|
1535
|
-
*
|
|
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.
|
|
1536
1354
|
*
|
|
1537
|
-
*
|
|
1538
|
-
*
|
|
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.
|
|
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.
|
|
1541
1357
|
*/
|
|
1542
1358
|
/**
|
|
1543
|
-
*
|
|
1544
|
-
*
|
|
1545
|
-
* active run has been aborted.
|
|
1359
|
+
* Create the state for one prompt turn's events, routing every model call's
|
|
1360
|
+
* text to the reply unless `stream` says otherwise.
|
|
1546
1361
|
*/
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
}
|
|
1555
|
-
await connection.closed;
|
|
1556
|
-
await config.engine?.dispose();
|
|
1362
|
+
function create_acp_mapper_state(options = {}) {
|
|
1363
|
+
return {
|
|
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()
|
|
1369
|
+
};
|
|
1557
1370
|
}
|
|
1558
|
-
//#endregion
|
|
1559
|
-
//#region src/acp/serve_acp.ts
|
|
1560
1371
|
/**
|
|
1561
|
-
*
|
|
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.
|
|
1372
|
+
* Build the session-unique ACP id for an engine tool call id.
|
|
1575
1373
|
*
|
|
1576
|
-
*
|
|
1577
|
-
*
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
* Route the console's stdout methods to stderr, leaving stdout to the
|
|
1581
|
-
* protocol alone.
|
|
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.
|
|
1582
1378
|
*/
|
|
1583
|
-
function
|
|
1584
|
-
|
|
1585
|
-
log: console.error,
|
|
1586
|
-
info: console.error,
|
|
1587
|
-
debug: console.error
|
|
1588
|
-
});
|
|
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}`;
|
|
1589
1381
|
}
|
|
1590
1382
|
/**
|
|
1591
|
-
*
|
|
1592
|
-
*
|
|
1593
|
-
*
|
|
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.
|
|
1594
1386
|
*/
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
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]);
|
|
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);
|
|
1616
1390
|
}
|
|
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
1391
|
/**
|
|
1658
|
-
*
|
|
1392
|
+
* Wrap streamed text as the update its route names, or nothing for `'none'`.
|
|
1659
1393
|
*/
|
|
1660
|
-
function
|
|
1661
|
-
|
|
1394
|
+
function text_updates(route, text) {
|
|
1395
|
+
const content = {
|
|
1396
|
+
type: "text",
|
|
1397
|
+
text
|
|
1398
|
+
};
|
|
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 [];
|
|
1662
1408
|
}
|
|
1663
1409
|
/**
|
|
1664
|
-
*
|
|
1665
|
-
*
|
|
1666
|
-
*
|
|
1667
|
-
* the model rather than something the loop enforces.
|
|
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.
|
|
1668
1413
|
*/
|
|
1669
|
-
function
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
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
|
+
};
|
|
1673
1427
|
return {
|
|
1674
|
-
|
|
1675
|
-
|
|
1428
|
+
sessionUpdate: "tool_call_update",
|
|
1429
|
+
toolCallId: tool_call_id,
|
|
1430
|
+
status: "completed",
|
|
1431
|
+
rawOutput: chunk.output
|
|
1676
1432
|
};
|
|
1677
1433
|
}
|
|
1678
1434
|
/**
|
|
1679
|
-
*
|
|
1680
|
-
*
|
|
1681
|
-
* being read past the limit, since a command blocked on a full pipe would
|
|
1682
|
-
* never finish.
|
|
1435
|
+
* Map one engine `StreamChunk` from the model call `step_id` to the session
|
|
1436
|
+
* updates it produces.
|
|
1683
1437
|
*/
|
|
1684
|
-
function
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
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
|
+
}
|
|
1691
1470
|
}
|
|
1692
1471
|
/**
|
|
1693
|
-
*
|
|
1694
|
-
*
|
|
1695
|
-
*
|
|
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.
|
|
1696
1475
|
*/
|
|
1697
|
-
function
|
|
1698
|
-
|
|
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 !== "");
|
|
1476
|
+
function is_stream_chunk(value) {
|
|
1477
|
+
return typeof value === "object" && value !== null;
|
|
1702
1478
|
}
|
|
1703
1479
|
/**
|
|
1704
|
-
*
|
|
1705
|
-
*
|
|
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.
|
|
1706
1484
|
*/
|
|
1707
|
-
function
|
|
1708
|
-
|
|
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);
|
|
1709
1495
|
}
|
|
1496
|
+
//#endregion
|
|
1497
|
+
//#region src/acp/prompt_turn.ts
|
|
1710
1498
|
/**
|
|
1711
|
-
*
|
|
1712
|
-
*
|
|
1713
|
-
*
|
|
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.
|
|
1714
1506
|
*/
|
|
1715
|
-
function
|
|
1716
|
-
const
|
|
1717
|
-
|
|
1718
|
-
|
|
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");
|
|
1719
1517
|
}
|
|
1720
1518
|
/**
|
|
1721
|
-
*
|
|
1722
|
-
*
|
|
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.
|
|
1723
1521
|
*/
|
|
1724
|
-
function
|
|
1725
|
-
return
|
|
1726
|
-
|
|
1727
|
-
output: capture.total === 0 ? "" : printed(capture).join("\n"),
|
|
1728
|
-
exit_code: child.exitCode,
|
|
1729
|
-
signal: child.signalCode
|
|
1730
|
-
};
|
|
1522
|
+
function turn_input(config, turn) {
|
|
1523
|
+
if (config.to_input !== void 0) return config.to_input(turn);
|
|
1524
|
+
return turn.text;
|
|
1731
1525
|
}
|
|
1732
1526
|
/**
|
|
1733
|
-
* The
|
|
1734
|
-
*
|
|
1527
|
+
* The default `to_text`: a string as-is, anything else as JSON, and nothing
|
|
1528
|
+
* at all for a flow that returns nothing.
|
|
1735
1529
|
*/
|
|
1736
|
-
function
|
|
1737
|
-
return
|
|
1530
|
+
function default_to_text(output) {
|
|
1531
|
+
return typeof output === "string" ? output : JSON.stringify(output) ?? "";
|
|
1738
1532
|
}
|
|
1739
1533
|
/**
|
|
1740
|
-
*
|
|
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.
|
|
1534
|
+
* Wrap a turn's final text as the message update that carries it.
|
|
1744
1535
|
*/
|
|
1745
|
-
function
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1536
|
+
function agent_message(text) {
|
|
1537
|
+
return {
|
|
1538
|
+
sessionUpdate: "agent_message_chunk",
|
|
1539
|
+
content: {
|
|
1540
|
+
type: "text",
|
|
1541
|
+
text
|
|
1542
|
+
}
|
|
1543
|
+
};
|
|
1750
1544
|
}
|
|
1751
1545
|
/**
|
|
1752
|
-
*
|
|
1753
|
-
*
|
|
1754
|
-
*
|
|
1755
|
-
*
|
|
1756
|
-
*
|
|
1757
|
-
*
|
|
1758
|
-
* runs out. However the call ends, its timers and the abort listener go
|
|
1759
|
-
* with it.
|
|
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.
|
|
1760
1552
|
*/
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
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);
|
|
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
|
|
1809
1572
|
});
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1573
|
+
else history.push({
|
|
1574
|
+
role: "user",
|
|
1575
|
+
text: user_text
|
|
1576
|
+
}, {
|
|
1577
|
+
role: "agent",
|
|
1578
|
+
text: reply_text,
|
|
1579
|
+
...stop
|
|
1817
1580
|
});
|
|
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
1581
|
}
|
|
1827
1582
|
/**
|
|
1828
|
-
*
|
|
1829
|
-
*
|
|
1830
|
-
* settings give it, its whole process tree killed when the turn is
|
|
1831
|
-
* cancelled. POSIX only: on Windows every call is refused.
|
|
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.
|
|
1832
1585
|
*/
|
|
1833
|
-
function
|
|
1834
|
-
return {
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
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);
|
|
1866
1619
|
}
|
|
1867
|
-
|
|
1620
|
+
record.cards.sent(event, updates);
|
|
1621
|
+
}
|
|
1868
1622
|
}
|
|
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
1623
|
/**
|
|
1884
|
-
*
|
|
1885
|
-
*
|
|
1886
|
-
*
|
|
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.
|
|
1887
1627
|
*/
|
|
1888
|
-
function
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
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);
|
|
1892
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" };
|
|
1893
1668
|
}
|
|
1894
1669
|
/**
|
|
1895
|
-
*
|
|
1896
|
-
* and
|
|
1897
|
-
*
|
|
1898
|
-
* `run_command`. The writes and the command ask before they run as the
|
|
1899
|
-
* session's mode says.
|
|
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.
|
|
1900
1673
|
*/
|
|
1901
|
-
function
|
|
1902
|
-
const
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
}
|
|
1914
|
-
|
|
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]);
|
|
1915
1981
|
}
|
|
1916
1982
|
//#endregion
|
|
1917
1983
|
export { acp_agent, acp_sdk_missing_error, create_acp_mapper_state, serve_acp, to_session_updates, workspace_tools };
|