fascicle 0.16.0 → 0.16.2
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 +19 -0
- package/dist/acp.d.ts +19 -1
- package/dist/acp.js +91 -46
- package/dist/acp.js.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## v0.16.2 — 2026-10-19
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- **`ServeAcpConfig` takes `additional_directories`, so an agent can keep each session to `cwd`.** An agent always advertised `sessionCapabilities.additionalDirectories` and took every directory that a client sent with `session/new`, so an agent whose tools and checks look at `cwd` alone had to narrow the session itself, and a narrowed copy of the session lost the diffs, the terminals, and the "always" that 0.16.0 gave its cards and prompts. With `additional_directories: false`, `initialize` leaves the capability out, so a client that follows the protocol sends no additional directories. A `session/new` that sends some anyway is refused with invalid params that carry the list as it was sent, before the agent resolves a root or builds a flow, and an empty list counts as none. Every session then has `cwd` as its one root, and the file tools, the prompts, and the cards follow from the session with no change. A config that leaves the option out, or sets `true`, behaves as it did.
|
|
8
|
+
|
|
9
|
+
- **`ServeAcpConfig` takes `modes`, so an agent that runs on the host can leave Auto out.** Every session offered Manual, Accept edits, and Auto, and both setters took any of the three, so an agent that runs outside a container had to replace `run_command`'s approval check to keep a command from running unasked in Auto, and a prompt from the replaced check came out plain, with no command line and no "always" to grant. `modes: ['manual', 'accept_edits']` lists only those two in `session/new`, in `modes` and in the `mode` config option alike, and `session/set_mode` and `session/set_config_option` refuse Auto as they refuse a mode they don't know, with invalid params that list the modes on offer, nothing sent to the client, and the mode left as it was. Every command then asks through the check that it already has. An edit's prompt offers **Allow all edits this session** only when the agent offers Accept edits, since that's the mode the grant switches to, and otherwise offers Allow and Reject. The offered modes keep the order Manual, Accept edits, Auto whatever order `modes` lists them in, a mode listed twice counts once, and a session starts in `default_mode`, or in the first mode offered when the config sets none. An empty `modes`, an entry that isn't a mode, and a `default_mode` that the agent doesn't offer each reject `acp_agent` with an error that names the problem, before it loads the SDK, so `serve_acp` fails at launch. That last check is new for a config that leaves `modes` out as well, so a `default_mode` outside the three modes, which a caller with no types could pass before and which failed only at the first gated tool call, now fails as the agent is built. A config that sets neither field behaves as it did.
|
|
10
|
+
|
|
11
|
+
### Internal
|
|
12
|
+
|
|
13
|
+
- `docs/acp.md`, `docs/api-reference.md`, and `SECURITY.md` cover both options. Each passage says what every ACP client gets before it says what Zed does, and it names the Zed commit that the Zed behavior was read from. Three checks by hand in Zed 1.24.3 confirmed it.
|
|
14
|
+
|
|
15
|
+
## v0.16.1 — 2026-10-19
|
|
16
|
+
|
|
17
|
+
### Internal
|
|
18
|
+
|
|
19
|
+
- The roadmap's Shipped list is up to date with v0.16.0. Near-Term now starts with durable runs across hosts, which covers a shipped store that holds across hosts, a compare-and-set in the store contract, and fixes for the suspend and resume bugs under Known Issues. Known Issues gains two entries: the late-resume windows that v0.16.0 left open, and `throughput()` reading far too high on Ollama.
|
|
20
|
+
- checkride moved to 0.15.0, whose `security` slot counts the advisories that the audit report lists rather than its per-severity totals. The braces advisory, which is patched and ignored, no longer keeps `pnpm check:security` red on pnpm 11.
|
|
21
|
+
|
|
3
22
|
## v0.16.0 — 2026-10-19
|
|
4
23
|
|
|
5
24
|
### Added
|
package/dist/acp.d.ts
CHANGED
|
@@ -146,8 +146,26 @@ type ServeAcpCommon<i, o> = {
|
|
|
146
146
|
readonly name: string;
|
|
147
147
|
/** Reported to the client as `agentInfo.version`; default: `'0.0.0'`. */
|
|
148
148
|
readonly version?: string | undefined;
|
|
149
|
-
/**
|
|
149
|
+
/**
|
|
150
|
+
* The modes a session offers, which the client's mode picker lists in the
|
|
151
|
+
* order Manual, Accept edits, Auto, whatever order they're given in; default:
|
|
152
|
+
* all three. An agent that runs on the host, outside a container or a
|
|
153
|
+
* throwaway worktree, leaves out `'auto'`.
|
|
154
|
+
*/
|
|
155
|
+
readonly modes?: ReadonlyArray<AcpMode> | undefined;
|
|
156
|
+
/**
|
|
157
|
+
* The mode each session starts in until the client picks another, one of
|
|
158
|
+
* `modes`; default: the first mode the agent offers, which is `'manual'`
|
|
159
|
+
* whenever it offers Manual.
|
|
160
|
+
*/
|
|
150
161
|
readonly default_mode?: AcpMode | undefined;
|
|
162
|
+
/**
|
|
163
|
+
* Whether a client may widen a session's workspace past `cwd`, which the
|
|
164
|
+
* agent advertises as `sessionCapabilities.additionalDirectories`; default:
|
|
165
|
+
* `true`. An agent that works in `cwd` alone sets `false`, and a
|
|
166
|
+
* `session/new` that sends additional directories anyway is refused.
|
|
167
|
+
*/
|
|
168
|
+
readonly additional_directories?: boolean | undefined;
|
|
151
169
|
/**
|
|
152
170
|
* The turn's reply when the flow streamed no message text; default: a
|
|
153
171
|
* string as-is, anything else as JSON.
|
package/dist/acp.js
CHANGED
|
@@ -11,6 +11,7 @@ import { spawn } from "node:child_process";
|
|
|
11
11
|
import { isUtf8 } from "node:buffer";
|
|
12
12
|
import { StringDecoder } from "node:string_decoder";
|
|
13
13
|
import { Readable, Writable } from "node:stream";
|
|
14
|
+
//#region src/acp/modes.ts
|
|
14
15
|
/** The id of the config option that carries the mode, the only option this agent has. */
|
|
15
16
|
const MODE_CONFIG_ID = "mode";
|
|
16
17
|
/** Every mode, in the order a client lists them. */
|
|
@@ -47,11 +48,33 @@ const MODES = {
|
|
|
47
48
|
function is_acp_mode(id) {
|
|
48
49
|
return typeof id === "string" && Object.hasOwn(MODES, id);
|
|
49
50
|
}
|
|
51
|
+
/** Every mode's id, as the refusals list them. */
|
|
52
|
+
const MODE_NAMES = Object.keys(MODES).join(", ");
|
|
53
|
+
/**
|
|
54
|
+
* The modes an agent offers and where its sessions start, from the config's
|
|
55
|
+
* `modes` (default: all three) and `default_mode` (default: the first mode
|
|
56
|
+
* offered). Throws an `Error` that names the problem for an empty `modes`,
|
|
57
|
+
* an entry that isn't a mode, or a `default_mode` the agent doesn't offer,
|
|
58
|
+
* so `acp_agent` fails as it's built rather than at every `session/new`.
|
|
59
|
+
*/
|
|
60
|
+
function mode_offer(config) {
|
|
61
|
+
const listed = config.modes ?? Object.keys(MODES);
|
|
62
|
+
if (listed.length === 0) throw new Error(`acp_agent: modes is empty; list at least one of ${MODE_NAMES}, or leave modes out to offer all three`);
|
|
63
|
+
for (const entry of listed) if (!is_acp_mode(entry)) throw new Error(`acp_agent: modes lists ${JSON.stringify(entry)}, which isn't a mode; use one of ${MODE_NAMES}`);
|
|
64
|
+
const modes = Object.keys(MODES).filter((id) => listed.includes(id));
|
|
65
|
+
const wanted = config.default_mode ?? modes[0];
|
|
66
|
+
const default_mode = modes.find((mode) => mode === wanted);
|
|
67
|
+
if (default_mode === void 0) throw new Error(`acp_agent: default_mode ${JSON.stringify(config.default_mode)} isn't one of the modes this agent offers (${modes.join(", ")}); add it to modes or leave default_mode out`);
|
|
68
|
+
return {
|
|
69
|
+
modes,
|
|
70
|
+
default_mode
|
|
71
|
+
};
|
|
72
|
+
}
|
|
50
73
|
/**
|
|
51
|
-
* The refusal for a mode id the agent doesn't
|
|
74
|
+
* The refusal for a mode id the agent doesn't offer, naming the ones it does.
|
|
52
75
|
*/
|
|
53
|
-
function unknown_mode_message(id) {
|
|
54
|
-
return `unknown mode ${JSON.stringify(id)}; choose one of ${
|
|
76
|
+
function unknown_mode_message(id, offer) {
|
|
77
|
+
return `unknown mode ${JSON.stringify(id)}; choose one of ${offer.modes.join(", ")}`;
|
|
55
78
|
}
|
|
56
79
|
/**
|
|
57
80
|
* Whether a session in `mode` asks the client before a tool does `action`.
|
|
@@ -60,29 +83,29 @@ function asks_before(mode, action) {
|
|
|
60
83
|
return MODES[mode].asks[action];
|
|
61
84
|
}
|
|
62
85
|
/**
|
|
63
|
-
* Every mode as ACP lists one
|
|
86
|
+
* Every mode the agent offers as ACP lists one, in the table's order.
|
|
64
87
|
*/
|
|
65
|
-
function available_modes() {
|
|
66
|
-
return
|
|
88
|
+
function available_modes(offer) {
|
|
89
|
+
return offer.modes.map((id) => ({
|
|
67
90
|
id,
|
|
68
|
-
name,
|
|
69
|
-
description
|
|
91
|
+
name: MODES[id].name,
|
|
92
|
+
description: MODES[id].description
|
|
70
93
|
}));
|
|
71
94
|
}
|
|
72
95
|
/**
|
|
73
96
|
* The session's modes as `session/new` reports them in `modes`.
|
|
74
97
|
*/
|
|
75
|
-
function mode_state(mode) {
|
|
98
|
+
function mode_state(offer, mode) {
|
|
76
99
|
return {
|
|
77
100
|
currentModeId: mode,
|
|
78
|
-
availableModes: available_modes()
|
|
101
|
+
availableModes: available_modes(offer)
|
|
79
102
|
};
|
|
80
103
|
}
|
|
81
104
|
/**
|
|
82
105
|
* The session's config options, the mode as a select being the only one, as
|
|
83
106
|
* `session/new` and `session/set_config_option` report them.
|
|
84
107
|
*/
|
|
85
|
-
function config_options(mode) {
|
|
108
|
+
function config_options(offer, mode) {
|
|
86
109
|
return [{
|
|
87
110
|
id: MODE_CONFIG_ID,
|
|
88
111
|
name: "Mode",
|
|
@@ -90,22 +113,25 @@ function config_options(mode) {
|
|
|
90
113
|
category: "mode",
|
|
91
114
|
type: "select",
|
|
92
115
|
currentValue: mode,
|
|
93
|
-
options:
|
|
94
|
-
value,
|
|
116
|
+
options: available_modes(offer).map(({ id, name, description }) => ({
|
|
117
|
+
value: id,
|
|
95
118
|
name,
|
|
96
119
|
description
|
|
97
120
|
}))
|
|
98
121
|
}];
|
|
99
122
|
}
|
|
100
123
|
/**
|
|
101
|
-
* Hold a session's mode, starting at `
|
|
102
|
-
* the client hears of it, so a tool call that asks after
|
|
103
|
-
* the new mode, and the two updates go out in order through
|
|
124
|
+
* Hold a session's mode, starting at the offer's `default_mode`. A switch
|
|
125
|
+
* takes effect before the client hears of it, so a tool call that asks after
|
|
126
|
+
* the switch reads the new mode, and the two updates go out in order through
|
|
127
|
+
* `send`.
|
|
104
128
|
*/
|
|
105
|
-
function session_modes(
|
|
106
|
-
let mode =
|
|
129
|
+
function session_modes(offer, send) {
|
|
130
|
+
let mode = offer.default_mode;
|
|
131
|
+
const offered = offer.modes;
|
|
107
132
|
return {
|
|
108
133
|
current: () => mode,
|
|
134
|
+
offers: (candidate) => offered.includes(candidate),
|
|
109
135
|
switch_to: async (next) => {
|
|
110
136
|
mode = next;
|
|
111
137
|
await send({
|
|
@@ -114,7 +140,7 @@ function session_modes(initial, send) {
|
|
|
114
140
|
});
|
|
115
141
|
await send({
|
|
116
142
|
sessionUpdate: "config_option_update",
|
|
117
|
-
configOptions: config_options(next)
|
|
143
|
+
configOptions: config_options(offer, next)
|
|
118
144
|
});
|
|
119
145
|
}
|
|
120
146
|
};
|
|
@@ -1040,11 +1066,12 @@ function closing_updates(session, name, card, chunk, closing) {
|
|
|
1040
1066
|
* the diff itself. It offers Allow, Reject, and an "always" that lives in
|
|
1041
1067
|
* memory for the session. For an edit, "always" switches the session to
|
|
1042
1068
|
* Accept edits, as Claude Agent's does, and tells the client both ways so
|
|
1043
|
-
* its mode picker follows.
|
|
1044
|
-
*
|
|
1045
|
-
*
|
|
1046
|
-
*
|
|
1047
|
-
*
|
|
1069
|
+
* its mode picker follows. An edit is offered one only when the agent
|
|
1070
|
+
* offers Accept edits, since that's the mode it switches to. For a
|
|
1071
|
+
* command, it covers that exact command line and nothing else, since one
|
|
1072
|
+
* flag can turn a listing into a delete (`find . -name '*.ts'` and
|
|
1073
|
+
* `find . -delete`). A command with shell control syntax is never covered
|
|
1074
|
+
* and never offered one, since anything can follow a `;` or a `|`.
|
|
1048
1075
|
*
|
|
1049
1076
|
* Only the session's own workspace tools get the diff and the "always",
|
|
1050
1077
|
* known by the input their `needs_approval` marked rather than by name. A
|
|
@@ -1275,18 +1302,21 @@ function warn_failed(tool_name, err) {
|
|
|
1275
1302
|
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`);
|
|
1276
1303
|
}
|
|
1277
1304
|
/**
|
|
1278
|
-
* The "always" a call is offered: Accept edits for an edit,
|
|
1279
|
-
* its key for a command that has one. Any
|
|
1280
|
-
* Accept edits leaves a session that has
|
|
1281
|
-
* asked where it is.
|
|
1305
|
+
* The "always" a call is offered: Accept edits for an edit, when the agent
|
|
1306
|
+
* offers that mode, and a grant of its key for a command that has one. Any
|
|
1307
|
+
* other call gets none. Choosing Accept edits leaves a session that has
|
|
1308
|
+
* moved past Manual since the call asked where it is.
|
|
1282
1309
|
*/
|
|
1283
1310
|
function always_for(gate, key, modes, granted) {
|
|
1284
|
-
if (gate?.action === "edit")
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1311
|
+
if (gate?.action === "edit") {
|
|
1312
|
+
if (!modes.offers("accept_edits")) return void 0;
|
|
1313
|
+
return {
|
|
1314
|
+
name: "Allow all edits this session",
|
|
1315
|
+
grant: async () => {
|
|
1316
|
+
if (asks_before(modes.current(), "edit")) await modes.switch_to("accept_edits");
|
|
1317
|
+
}
|
|
1318
|
+
};
|
|
1319
|
+
}
|
|
1290
1320
|
if (key === void 0) return void 0;
|
|
1291
1321
|
return {
|
|
1292
1322
|
name: `Always allow \`${key}\` this session`,
|
|
@@ -1784,11 +1814,24 @@ function permission_asker(sdk, client) {
|
|
|
1784
1814
|
}
|
|
1785
1815
|
/**
|
|
1786
1816
|
* The mode a client asked for, or an invalid-params error naming the modes
|
|
1787
|
-
*
|
|
1817
|
+
* the agent offers, for a mode it doesn't know and one it leaves out alike.
|
|
1818
|
+
* `field` is the param the id arrived in, for the error's data.
|
|
1819
|
+
*/
|
|
1820
|
+
function requested_mode(sdk, offer, modes, id, field) {
|
|
1821
|
+
if (modes.offers(id)) return id;
|
|
1822
|
+
throw sdk.RequestError.invalidParams({ [field]: id }, unknown_mode_message(id, offer));
|
|
1823
|
+
}
|
|
1824
|
+
/**
|
|
1825
|
+
* The additional directories a client sent with a session request, or, from
|
|
1826
|
+
* an agent whose config sets `additional_directories: false`, an
|
|
1827
|
+
* invalid-params error refusing them. Every session request that carries
|
|
1828
|
+
* `additionalDirectories` goes through this check before its roots resolve,
|
|
1829
|
+
* so each one refuses them the same way. The protocol reads an empty list as
|
|
1830
|
+
* none, so an empty list passes.
|
|
1788
1831
|
*/
|
|
1789
|
-
function
|
|
1790
|
-
if (
|
|
1791
|
-
throw sdk.RequestError.invalidParams({
|
|
1832
|
+
function requested_directories(sdk, config, method, directories = []) {
|
|
1833
|
+
if (config.additional_directories !== false || directories.length === 0) return directories;
|
|
1834
|
+
throw sdk.RequestError.invalidParams({ additionalDirectories: directories }, `this agent works in cwd alone and takes no additional directories; send ${method} without additionalDirectories`);
|
|
1792
1835
|
}
|
|
1793
1836
|
/**
|
|
1794
1837
|
* Build the ACP agent app that answers each prompt turn by running the
|
|
@@ -1801,6 +1844,7 @@ function requested_mode(sdk, id, field) {
|
|
|
1801
1844
|
* before it can overwrite the first client's capabilities.
|
|
1802
1845
|
*/
|
|
1803
1846
|
async function acp_agent(config) {
|
|
1847
|
+
const offer = mode_offer(config);
|
|
1804
1848
|
const sdk = await load_acp_sdk();
|
|
1805
1849
|
const sessions = /* @__PURE__ */ new Map();
|
|
1806
1850
|
let client_capabilities = {};
|
|
@@ -1827,12 +1871,13 @@ async function acp_agent(config) {
|
|
|
1827
1871
|
agentCapabilities: {
|
|
1828
1872
|
loadSession: false,
|
|
1829
1873
|
promptCapabilities: { embeddedContext: true },
|
|
1830
|
-
sessionCapabilities: { additionalDirectories: {} }
|
|
1874
|
+
sessionCapabilities: config.additional_directories === false ? {} : { additionalDirectories: {} }
|
|
1831
1875
|
},
|
|
1832
1876
|
authMethods: []
|
|
1833
1877
|
};
|
|
1834
1878
|
}).onRequest("authenticate", () => ({})).onRequest("session/new", async (ctx) => {
|
|
1835
|
-
const { cwd
|
|
1879
|
+
const { cwd } = ctx.params;
|
|
1880
|
+
const additional_directories = requested_directories(sdk, config, "session/new", ctx.params.additionalDirectories);
|
|
1836
1881
|
const roots = await resolve_roots([cwd, ...additional_directories]).catch((err) => {
|
|
1837
1882
|
throw sdk.RequestError.invalidParams({
|
|
1838
1883
|
cwd,
|
|
@@ -1840,7 +1885,7 @@ async function acp_agent(config) {
|
|
|
1840
1885
|
}, message_of(err));
|
|
1841
1886
|
});
|
|
1842
1887
|
const id = randomUUID();
|
|
1843
|
-
const modes = session_modes(
|
|
1888
|
+
const modes = session_modes(offer, sender(sdk, ctx.client, id));
|
|
1844
1889
|
const cards = create_card_sync();
|
|
1845
1890
|
const approver = session_approver({
|
|
1846
1891
|
modes,
|
|
@@ -1871,8 +1916,8 @@ async function acp_agent(config) {
|
|
|
1871
1916
|
}
|
|
1872
1917
|
return {
|
|
1873
1918
|
sessionId: id,
|
|
1874
|
-
modes: mode_state(modes.current()),
|
|
1875
|
-
configOptions: config_options(modes.current())
|
|
1919
|
+
modes: mode_state(offer, modes.current()),
|
|
1920
|
+
configOptions: config_options(offer, modes.current())
|
|
1876
1921
|
};
|
|
1877
1922
|
}).onRequest("session/prompt", async (ctx) => {
|
|
1878
1923
|
const { sessionId, prompt } = ctx.params;
|
|
@@ -1885,14 +1930,14 @@ async function acp_agent(config) {
|
|
|
1885
1930
|
}).onRequest("session/set_mode", async (ctx) => {
|
|
1886
1931
|
const { sessionId, modeId } = ctx.params;
|
|
1887
1932
|
const { modes } = session_of(sessionId);
|
|
1888
|
-
await modes.switch_to(requested_mode(sdk, modeId, "modeId"));
|
|
1933
|
+
await modes.switch_to(requested_mode(sdk, offer, modes, modeId, "modeId"));
|
|
1889
1934
|
return {};
|
|
1890
1935
|
}).onRequest("session/set_config_option", async (ctx) => {
|
|
1891
1936
|
const { sessionId, configId, value } = ctx.params;
|
|
1892
1937
|
const { modes } = session_of(sessionId);
|
|
1893
1938
|
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()) };
|
|
1939
|
+
await modes.switch_to(requested_mode(sdk, offer, modes, value, "value"));
|
|
1940
|
+
return { configOptions: config_options(offer, modes.current()) };
|
|
1896
1941
|
}).onNotification("session/cancel", (ctx) => {
|
|
1897
1942
|
const record = sessions.get(ctx.params.sessionId);
|
|
1898
1943
|
if (record !== void 0) cancel_turn(record);
|
package/dist/acp.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"acp.js","names":[],"sources":["../src/acp/modes.ts","../src/acp/tools/previews.ts","../src/acp/tools/write_file.ts","../src/acp/tools/edit_file.ts","../src/acp/tools/run_command.ts","../src/acp/workspace_tools.ts","../src/acp/presentation.ts","../src/acp/approve.ts","../src/acp/to_session_updates.ts","../src/acp/prompt_turn.ts","../src/acp/errors.ts","../src/acp/sdk_loader.ts","../src/acp/acp_agent.ts","../src/acp/serve_streams.ts","../src/acp/serve_acp.ts"],"sourcesContent":["/**\n * modes: the three ways a coding session runs, and when each asks the\n * client before a workspace tool acts.\n *\n * Reads and searches never ask. Manual asks before every edit and every\n * command, Accept edits only before a command, and Auto never asks. That is\n * the contract Claude Agent set and Zed's mode picker presents. Auto runs\n * commands with nobody watching, so it belongs in a container or a\n * throwaway worktree.\n *\n * ACP reports a session's mode two ways, as `modes` and as a config option\n * in the `mode` category, and a client reads one or the other. Both come\n * from the one table here, and every change sends both updates, so the two\n * can't disagree in front of the user.\n */\n\nimport type { SessionConfigOption, SessionMode, SessionModeState, SessionUpdate } from '@agentclientprotocol/sdk'\nimport type { AcpMode } from './types.js'\n\n/** The mode a session starts in unless `ServeAcpConfig.default_mode` says otherwise. */\nexport const DEFAULT_MODE: AcpMode = 'manual'\n\n/** The id of the config option that carries the mode, the only option this agent has. */\nexport const MODE_CONFIG_ID = 'mode'\n\n/** What a workspace tool does that a mode may want to ask about first. */\nexport type GatedAction = 'edit' | 'command'\n\ntype ModeEntry = {\n readonly name: string\n readonly description: string\n readonly asks: Readonly<Record<GatedAction, boolean>>\n}\n\n/** Every mode, in the order a client lists them. */\nconst MODES: Readonly<Record<AcpMode, ModeEntry>> = {\n manual: {\n name: 'Manual',\n description: 'Ask before every edit and every command',\n asks: { edit: true, command: true },\n },\n accept_edits: {\n name: 'Accept edits',\n description: 'Edit files without asking, and ask before every command',\n asks: { edit: false, command: true },\n },\n auto: {\n name: 'Auto',\n description: 'Edit files and run commands without asking, for a container or a throwaway worktree',\n asks: { edit: false, command: false },\n },\n}\n\n/**\n * Whether `id` names one of the modes. An own-key check, so an id such as\n * `toString` that every object answers to isn't taken for one.\n */\nexport function is_acp_mode(id: unknown): id is AcpMode {\n return typeof id === 'string' && Object.hasOwn(MODES, id)\n}\n\n/**\n * The refusal for a mode id the agent doesn't know, naming the ones it does.\n */\nexport function unknown_mode_message(id: unknown): string {\n return `unknown mode ${JSON.stringify(id)}; choose one of ${Object.keys(MODES).join(', ')}`\n}\n\n/**\n * Whether a session in `mode` asks the client before a tool does `action`.\n */\nexport function asks_before(mode: AcpMode, action: GatedAction): boolean {\n return MODES[mode].asks[action]\n}\n\n/**\n * Every mode as ACP lists one: its id, its name, and what it asks.\n */\nfunction available_modes(): SessionMode[] {\n return Object.entries(MODES).map(([id, { name, description }]) => ({ id, name, description }))\n}\n\n/**\n * The session's modes as `session/new` reports them in `modes`.\n */\nexport function mode_state(mode: AcpMode): SessionModeState {\n return { currentModeId: mode, availableModes: available_modes() }\n}\n\n/**\n * The session's config options, the mode as a select being the only one, as\n * `session/new` and `session/set_config_option` report them.\n */\nexport function config_options(mode: AcpMode): SessionConfigOption[] {\n return [\n {\n id: MODE_CONFIG_ID,\n name: 'Mode',\n description: 'When the agent asks before it edits a file or runs a command',\n category: 'mode',\n type: 'select',\n currentValue: mode,\n options: Object.entries(MODES).map(([value, { name, description }]) => ({ value, name, description })),\n },\n ]\n}\n\n/**\n * A session's mode as the agent holds it: what it is now, and the one way\n * to change it, which tells the client both ways it may be reading it.\n */\nexport type SessionModes = {\n readonly current: () => AcpMode\n readonly switch_to: (mode: AcpMode) => Promise<void>\n}\n\n/**\n * Hold a session's mode, starting at `initial`. A switch takes effect before\n * the client hears of it, so a tool call that asks after the switch reads\n * the new mode, and the two updates go out in order through `send`.\n */\nexport function session_modes(initial: AcpMode, send: (update: SessionUpdate) => Promise<void>): SessionModes {\n let mode = initial\n return {\n current: () => mode,\n switch_to: async (next) => {\n mode = next\n await send({ sessionUpdate: 'current_mode_update', currentModeId: next })\n await send({ sessionUpdate: 'config_option_update', configOptions: config_options(next) })\n },\n }\n}\n","/**\n * The preview store: what each workspace tool call changed or ran, kept for\n * the client's card that shows it.\n *\n * A write's card shows its diff and a command's shows its output and exit\n * code, but the model reads back a single line, so the call's result can't\n * carry them. Each tool leaves its call's preview here once the call\n * succeeds, under the engine's raw call id, and `to_session_updates` takes\n * it when that call's result arrives. The file reads behind a diff happen\n * in the tool, before it writes, so the mapper itself stays free of I/O.\n *\n * Raw ids repeat across model calls (Ollama numbers its calls afresh on\n * each one), and the turn's consumer can fall behind the engine, so each id\n * holds a queue, taken oldest first. The engine runs a turn's calls one\n * after another, which keeps each queue in the order its results arrive.\n * Only a call that succeeded leaves a preview, and only a successful result\n * takes one, so a call refused before it ran can't take a later call's.\n *\n * The store belongs to the session and is keyed by the session object, so\n * `AcpSession` carries nothing for it. Each turn starts it empty, so what a\n * cancelled turn left behind never reaches the next.\n */\n\nimport type { AcpSession } from '../types.js'\n\n/**\n * A file change that landed: the path in the client's terms, the text\n * before (`null` for a new file) and after, and for an edit, the line where\n * its first match starts, counting from 1 (a write has none).\n */\nexport type ChangePreview = {\n readonly kind: 'change'\n readonly path: string\n readonly old_text: string | null\n readonly new_text: string\n readonly line: number | undefined\n}\n\n/**\n * A command that ran to its end: what it printed, and its exit code or the\n * signal that ended it.\n */\nexport type CommandPreview = {\n readonly kind: 'command'\n readonly output: string\n readonly exit_code: number | null\n readonly signal: string | null\n}\n\nexport type ToolPreview = ChangePreview | CommandPreview\n\nconst stores = new WeakMap<AcpSession, Map<string, ToolPreview[]>>()\n\n/**\n * The session's store, made empty the first time it's asked for.\n */\nfunction store_of(session: AcpSession): Map<string, ToolPreview[]> {\n const store = stores.get(session) ?? new Map<string, ToolPreview[]>()\n stores.set(session, store)\n return store\n}\n\n/**\n * Empty the session's store as a turn starts.\n */\nexport function reset_previews(session: AcpSession): void {\n stores.set(session, new Map())\n}\n\n/**\n * Leave a call's preview at the back of its raw id's queue.\n */\nexport function record_preview(session: AcpSession, tool_call_id: string, preview: ToolPreview): void {\n const store = store_of(session)\n store.set(tool_call_id, [...(store.get(tool_call_id) ?? []), preview])\n}\n\n/**\n * Take the oldest preview waiting under a raw id, or `undefined` when none\n * is.\n */\nexport function take_preview(session: AcpSession, tool_call_id: string): ToolPreview | undefined {\n return store_of(session).get(tool_call_id)?.shift()\n}\n","/**\n * write_file: create a text file in the workspace, or replace everything one\n * holds.\n *\n * Every write is worked out before it happens, as the file's whole text\n * before and after, so the client can be shown the change as a diff before\n * anything reaches the disk. `edit_file` builds its change from the same\n * pieces, so the two tools agree on what they refuse and how they write.\n *\n * A write lands at the path's real location, which `contain` placed inside a\n * root, and creates the directories it needs there, so a model writing\n * `src/new/thing.ts` doesn't need a command to make `src/new` first.\n */\n\nimport { isUtf8 } from 'node:buffer'\nimport { mkdir, open, stat, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\nimport type { Tool } from '#engine'\nimport { as_record, json_schema_to_standard } from '#schema'\nimport type { AcpSession } from '../types.js'\nimport { contain_writable, error_code, shown_path } from './containment.js'\nimport type { ContainedPath } from './containment.js'\nimport { record_preview } from './previews.js'\nimport { is_binary } from './read_file.js'\n\n/**\n * A write worked out before anything is written: the file both ways\n * `contain` names it, and its whole text before and after. `old_text` is\n * `null` only when the write creates the file.\n */\nexport type FileChange = ContainedPath & {\n readonly old_text: string | null\n readonly new_text: string\n}\n\n/** A file change as a card or a permission request shows it, with the line an edit lands on. */\nexport type ShownChange = FileChange & { readonly line?: number }\n\n/**\n * The largest file a change reads, in bytes. A change is shown as a diff,\n * which carries the file's whole text twice, as its text before and after,\n * and the closing card update carries it again.\n */\nconst CHANGE_LIMIT_BYTES = 1_000_000\n\n/** One write as the model asked for it. */\ntype WriteRequest = {\n readonly path: string\n readonly content: string\n}\n\n/**\n * Read the call's path and content out of its input.\n */\nfunction write_request(input: unknown): WriteRequest {\n const fields: Record<string, unknown> = as_record(input) ?? {}\n const { path, content } = fields\n if (typeof path !== 'string' || typeof content !== 'string') {\n throw new Error('write_file needs a path and the content to write, as strings')\n }\n return { path, content }\n}\n\n/**\n * The text a write would replace, or `null` when no file is there yet.\n * Anything but a regular UTF-8 text file is refused, because the change is\n * shown as a diff of text, and rewriting a file in another encoding would\n * change bytes outside the edit. A file with other hard links is refused too:\n * a write changes the file under every name it has, and real paths can't say\n * where the other names lie. A file over CHANGE_LIMIT_BYTES is refused from\n * its size, before it's opened. `shown` is the path as the model gave it,\n * and `tool` names the tool asking, for the refusals.\n */\nexport async function current_text(real: string, shown: string, tool: string): Promise<string | null> {\n const info = await stat(real).catch((err: unknown) => {\n if (error_code(err) === 'ENOENT') return undefined\n throw err\n })\n if (info === undefined) return null\n if (info.isDirectory()) throw new Error(`${shown} is a directory; ${tool} changes a file, so name one inside it`)\n if (!info.isFile()) throw new Error(`${shown} isn't a regular file, so ${tool} can't change it`)\n if (info.nlink > 1) {\n throw new Error(\n `${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`,\n )\n }\n if (info.size > CHANGE_LIMIT_BYTES) {\n throw new Error(\n `${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`,\n )\n }\n const handle = await open(real)\n try {\n if (await is_binary(handle)) {\n throw new Error(`${shown} is a binary file (it has a NUL byte in its first 8 KB), so ${tool} won't change it`)\n }\n // The binary check reads at an explicit position, which leaves the\n // handle's own position at the top, where readFile starts.\n const bytes = await handle.readFile()\n if (!isUtf8(bytes)) throw new Error(`${shown} isn't UTF-8 text, so ${tool} won't change it`)\n return bytes.toString('utf8')\n } finally {\n await handle.close()\n }\n}\n\n/**\n * Write a change's new text where it lands, creating the directories it\n * needs first. A turn cancelled while the change was worked out stops here,\n * before anything is written. A new file is created exclusively, so a file or\n * a symlink that appeared at its path since then stops the write instead of\n * taking it.\n */\nexport async function apply_change(change: FileChange, abort: AbortSignal): Promise<void> {\n abort.throwIfAborted()\n await mkdir(dirname(change.real), { recursive: true })\n await writeFile(change.real, change.new_text, change.old_text === null ? { flag: 'wx' } : {})\n}\n\n/**\n * Leave a change that landed in the session's preview store, for the card\n * of the call that made it to show as a diff.\n */\nexport function record_change(\n session: AcpSession,\n tool_call_id: string,\n change: ShownChange,\n): void {\n record_preview(session, tool_call_id, {\n kind: 'change',\n path: change.path,\n old_text: change.old_text,\n new_text: change.new_text,\n line: change.line,\n })\n}\n\n/**\n * The change a `write_file` call would make, worked out without writing: its\n * path checked against the session's roots and kept out of `.git` and\n * `node_modules`, the text it would replace, and the content that replaces\n * it.\n */\nexport async function write_file_change(session: AcpSession, input: unknown): Promise<FileChange> {\n const request = write_request(input)\n const target = await contain_writable(session, request.path, 'write_file')\n const old_text = await current_text(target.real, request.path, 'write_file')\n return { ...target, old_text, new_text: request.content }\n}\n\n/**\n * The `write_file` tool for one session: a file inside its workspace,\n * created or replaced whole. The model reads back a line saying which, since\n * it already has the text it sent.\n */\nexport function write_file_tool(session: AcpSession): Tool {\n return {\n name: 'write_file',\n description:\n 'Write a text file in the workspace: create it, along with any directories it needs, or replace everything it holds. ' +\n \"content is the file's whole text; to change part of a file, use edit_file. \" +\n 'The path is absolute or relative to the workspace root.',\n input_schema: json_schema_to_standard({\n type: 'object',\n properties: {\n path: { type: 'string', description: 'The file to write, absolute or relative to the workspace root' },\n content: { type: 'string', description: \"The file's whole text\" },\n },\n required: ['path', 'content'],\n additionalProperties: false,\n }),\n execute: async (input, ctx) => {\n const change = await write_file_change(session, input)\n await apply_change(change, ctx.abort)\n record_change(session, ctx.tool_call_id, change)\n return `${change.old_text === null ? 'created' : 'overwrote'} ${shown_path(session, change.path)}`\n },\n }\n}\n","/**\n * edit_file: replace an exact match in a text file in the workspace.\n *\n * The match has to be exact and, unless the call sets `replace_all`, the only\n * one, so the model names enough of the file to say which place it means. A\n * looser match could change a place it never looked at. The change is worked\n * out first, the way `write_file`'s is, as the whole file before and after,\n * with the line where the first match starts for the client to point at.\n */\n\nimport type { Tool } from '#engine'\nimport { as_record, json_schema_to_standard } from '#schema'\nimport type { AcpSession } from '../types.js'\nimport { contain_writable, shown_path } from './containment.js'\nimport { apply_change, current_text, record_change } from './write_file.js'\nimport type { FileChange } from './write_file.js'\n\n/**\n * A change `edit_file` would make. The file exists, so `old_text` is always\n * its text. `line` is where the first match starts, counting from 1, and\n * `matches` is how many places the edit replaces.\n */\nexport type EditChange = FileChange & {\n readonly old_text: string\n readonly line: number\n readonly matches: number\n}\n\n/** One edit as the model asked for it. */\ntype EditRequest = {\n readonly path: string\n readonly old_text: string\n readonly new_text: string\n readonly replace_all: boolean\n}\n\n/**\n * Read the call's path, texts, and `replace_all` out of its input, refusing\n * an `old_text` that's empty, which matches everywhere, or the same as\n * `new_text`, which changes nothing.\n */\nfunction edit_request(input: unknown): EditRequest {\n const fields: Record<string, unknown> = as_record(input) ?? {}\n const { path, old_text, new_text, replace_all = false } = fields\n if (\n typeof path !== 'string' ||\n typeof old_text !== 'string' ||\n typeof new_text !== 'string' ||\n typeof replace_all !== 'boolean'\n ) {\n throw new Error('edit_file needs path, old_text, and new_text as strings, and takes replace_all as true or false')\n }\n if (old_text === '') throw new Error(\"old_text is empty, so there's nothing to find; write_file writes a whole file\")\n if (old_text === new_text) throw new Error('old_text and new_text are the same, so the edit would change nothing')\n return { path, old_text, new_text, replace_all }\n}\n\n/**\n * The change an `edit_file` call would make, worked out without writing: the\n * file's whole text before, and after `old_text` is replaced. It fails on a\n * path that `contain_writable` refuses, when `old_text` isn't there, or when\n * it's there more than once and the call doesn't set `replace_all`.\n */\nexport async function edit_file_change(session: AcpSession, input: unknown): Promise<EditChange> {\n const request = edit_request(input)\n const target = await contain_writable(session, request.path, 'edit_file')\n const text = await current_text(target.real, request.path, 'edit_file')\n if (text === null) throw new Error(`${request.path} doesn't exist; write_file creates a file`)\n // Splitting on the match, where String.replace would read its replacement\n // as a pattern, keeps a `$&` or `$$` in new_text as the model wrote it.\n const pieces = text.split(request.old_text)\n const matches = pieces.length - 1\n if (matches === 0) {\n throw new Error(\n `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`,\n )\n }\n if (matches > 1 && !request.replace_all) {\n throw new Error(\n `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`,\n )\n }\n const before = text.slice(0, text.indexOf(request.old_text))\n return {\n ...target,\n old_text: text,\n new_text: pieces.join(request.new_text),\n line: before.split('\\n').length,\n matches,\n }\n}\n\n/**\n * The `edit_file` tool for one session: an exact match replaced in a file\n * inside its workspace. The model reads back where the edit landed rather\n * than the file again.\n */\nexport function edit_file_tool(session: AcpSession): Tool {\n return {\n name: 'edit_file',\n description:\n 'Edit a text file in the workspace by replacing old_text with new_text. ' +\n 'old_text has to match the file exactly, whitespace and line breaks included, ' +\n 'and appear in it once, unless replace_all is set to replace every match. ' +\n 'Copy it from read_file without the line number and tab that read_file puts before each line. ' +\n 'The path is absolute or relative to the workspace root.',\n input_schema: json_schema_to_standard({\n type: 'object',\n properties: {\n path: { type: 'string', description: 'The file to edit, absolute or relative to the workspace root' },\n old_text: { type: 'string', minLength: 1, description: 'The exact text to replace' },\n new_text: { type: 'string', description: 'The text to put in its place' },\n replace_all: {\n type: 'boolean',\n description: 'Replace every match of old_text, rather than exactly one; default: false',\n },\n },\n required: ['path', 'old_text', 'new_text'],\n additionalProperties: false,\n }),\n execute: async (input, ctx) => {\n const change = await edit_file_change(session, input)\n await apply_change(change, ctx.abort)\n record_change(session, ctx.tool_call_id, change)\n const shown = shown_path(session, change.path)\n return change.matches === 1\n ? `edited ${shown} at line ${change.line}`\n : `edited ${shown} in ${change.matches} places, the first at line ${change.line}`\n },\n }\n}\n","/**\n * run_command: run a shell command in the workspace and hand back what it\n * printed and how it ended.\n *\n * The command is a string the model wrote in POSIX shell, so it runs as\n * `/bin/sh -c`, which behaves the same on every host and needs no read of\n * the user's `$SHELL`. Windows has neither that shell nor POSIX process\n * groups, so there the tool refuses and the file tools carry on.\n *\n * Each command leads a process group of its own, so the whole tree it starts\n * dies together: when the turn is cancelled, when it runs past its timeout,\n * and when the shell exits, which stops whatever it left running in the\n * background. Without that last kill, a job left behind would outlive the\n * call, and then the agent, since nothing would ever abort it. A command\n * that moves work into a group of its own (`set -m` in an interactive\n * shell, or a daemon that starts its own session) takes that work out of\n * reach, as it would from a terminal's Ctrl-C.\n *\n * The file tools' containment doesn't bind a command: the shell reaches\n * anything the user can.\n *\n * This is the one file in `src/acp/` that may import `node:child_process`\n * (rules/no-child-process-outside-run-command.yml).\n */\n\nimport { spawn } from 'node:child_process'\nimport type { ChildProcess } from 'node:child_process'\nimport { StringDecoder } from 'node:string_decoder'\nimport type { Tool } from '#engine'\nimport { as_record, json_schema_to_standard } from '#schema'\nimport type { AcpSession } from '../types.js'\nimport { record_preview } from './previews.js'\nimport type { CommandPreview } from './previews.js'\n\n/** The shell every command runs in. */\nconst SHELL = '/bin/sh'\n\n/**\n * The longest delay a Node timer keeps. A longer one fires after 1 ms\n * instead, so a longer timeout is held to this, about 24.8 days.\n */\nconst MAX_TIMER_MS = 2_147_483_647\n\n/**\n * How long the output may stay open once the shell has exited and its group\n * has been killed. The group's processes are gone by then, so only\n * something moved out of the group can be holding it, and that could hold\n * it for good.\n */\nconst OUTPUT_GRACE_MS = 1000\n\n/** How `run_command` runs one session's commands, from `workspace_tools`' options. */\nexport type CommandSettings = {\n /** How long a call may run, unless it sets its own `timeout_ms`. */\n readonly timeout_ms: number\n /** The most output a call returns, in bytes. */\n readonly output_limit_bytes: number\n /** The whole environment commands run with, or `undefined` to inherit the agent's. */\n readonly env: Readonly<Record<string, string>> | undefined\n}\n\n/** One command as the model asked for it. */\ntype CommandRequest = {\n readonly command: string\n readonly timeout_ms: number | undefined\n}\n\n/**\n * What a command printed, stdout and stderr together in the order they\n * arrived, up to `limit` bytes: the parts kept, the bytes they account\n * for, and every byte the command printed.\n */\ntype Capture = {\n readonly limit: number\n readonly parts: string[]\n kept: number\n total: number\n}\n\n/**\n * Whether a value counts milliseconds: a whole number of at least 1.\n */\nfunction is_millis(value: unknown): value is number {\n return Number.isInteger(value) && Number(value) >= 1\n}\n\n/**\n * Read the call's command and timeout out of its input. The tool loop has\n * already checked the types against the schema, but a flow that wraps the\n * tool can call `execute` directly, and the schema's `minimum` is advice to\n * the model rather than something the loop enforces.\n */\nfunction command_request(input: unknown): CommandRequest {\n const fields: Record<string, unknown> = as_record(input) ?? {}\n const { command, timeout_ms } = fields\n if (typeof command !== 'string') throw new Error('run_command needs a command, as a string')\n if (timeout_ms !== undefined && !is_millis(timeout_ms)) {\n throw new Error('run_command counts timeout_ms in milliseconds, so it has to be a whole number of at least 1')\n }\n return { command, timeout_ms }\n}\n\n/**\n * Keep a chunk of output while the capture has room, cutting the chunk that\n * crosses the limit, and count every byte either way. The output goes on\n * being read past the limit, since a command blocked on a full pipe would\n * never finish.\n */\nfunction take(capture: Capture, chunk: string): void {\n const size = Buffer.byteLength(chunk)\n const room = capture.limit - capture.kept\n capture.total += size\n // Stryker disable next-line ConditionalExpression,EqualityOperator: with no room left the cut below keeps an empty string and counts no bytes, so going on reads the same; the return only spares a copy of every chunk past the cap.\n if (room <= 0) return\n // A chunk that fits comes through whole. One cut at the limit can end\n // inside a character, whose partial bytes the decoder holds back.\n capture.parts.push(new StringDecoder().write(Buffer.from(chunk).subarray(0, room)))\n capture.kept += Math.min(size, room)\n}\n\n/**\n * What a command printed as the model reads it, without its trailing\n * whitespace, with a marker when it was cut, and a line saying so when it\n * printed nothing at all.\n */\nfunction printed(capture: Capture): string[] {\n if (capture.total === 0) return ['[no output]']\n const lines = [capture.parts.join('').trimEnd()]\n if (capture.total > capture.kept) {\n lines.push(\n `[output cut at ${capture.limit} bytes of ${capture.total}; pipe the command through tail, head, or grep to see the part you need]`,\n )\n }\n return lines.filter((line) => line !== '')\n}\n\n/**\n * How a finished command ended, as its report's last line: its exit code,\n * or the signal that ended it. Node sets exactly one of the two.\n */\nfunction ending(child: ChildProcess): string {\n return child.exitCode === null ? `[ended by ${String(child.signalCode)}]` : `[exit code ${child.exitCode}]`\n}\n\n/**\n * A command that ran to its end: what it printed, its process, and whether\n * something it moved out of its group held its output open.\n */\ntype Finished = {\n readonly capture: Capture\n readonly child: ChildProcess\n readonly held: boolean\n}\n\n/**\n * A finished command's report: what it printed, then how it ended, and a\n * note when something it moved out of its group held its output open and\n * was left running.\n */\nfunction report({ capture, child, held }: Finished): string {\n const lines = [...printed(capture), ending(child)]\n if (held) {\n lines.push(\n '[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]',\n )\n }\n return lines.join('\\n')\n}\n\n/**\n * A finished command as its card shows it: what it printed, with nothing in\n * place of an empty output, and its exit code or the signal that ended it.\n */\nfunction command_preview({ capture, child }: Finished): CommandPreview {\n return {\n kind: 'command',\n output: capture.total === 0 ? '' : printed(capture).join('\\n'),\n exit_code: child.exitCode,\n signal: child.signalCode,\n }\n}\n\n/**\n * The error a call that ran past its timeout fails with, carrying what the\n * command printed before it was killed.\n */\nfunction timeout_error(capture: Capture, timeout_ms: number): Error {\n return new Error(\n `the command didn't finish within ${timeout_ms / 1000} s, so run_command killed it and everything it started; ` +\n '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. ' +\n `What it printed before then:\\n${printed(capture).join('\\n')}`,\n )\n}\n\n/**\n * Kill a command's whole process group with SIGKILL, the one signal no\n * command can ignore. The turn's abort can be the agent's last act before\n * `serve_acp` exits, which leaves no later moment to follow a gentler\n * signal with this one.\n */\nfunction kill_group(child: ChildProcess): void {\n // Stryker disable next-line ConditionalExpression: without a pid, process.kill throws on the NaN it's handed, and the catch below takes that the same way.\n if (child.pid === undefined) return\n try {\n process.kill(-child.pid, 'SIGKILL')\n } catch {\n // The group is gone: every process in it has exited.\n }\n}\n\n/**\n * Run one command to its end in its own process group. A command that ends\n * on its own is a result, whatever its exit code; a timeout and a shell that\n * won't start are errors, and the turn's abort rejects with its reason. The\n * timeout and the abort kill the group, and the shell's exit kills whatever\n * it left behind. Each reads on to the end of the output, so what the\n * command printed last isn't lost, until the grace after the shell's exit\n * runs out. However the call ends, its timers and the abort listener go\n * with it.\n */\nasync function run_shell(\n request: CommandRequest,\n cwd: string,\n settings: CommandSettings,\n abort: AbortSignal,\n): Promise<Finished> {\n abort.throwIfAborted()\n const timeout_ms = request.timeout_ms ?? settings.timeout_ms\n const capture: Capture = { limit: settings.output_limit_bytes, parts: [], kept: 0, total: 0 }\n const child = spawn(SHELL, ['-c', request.command], {\n cwd,\n env: settings.env === undefined ? undefined : { ...settings.env },\n detached: true,\n stdio: ['ignore', 'pipe', 'pipe'],\n })\n const { promise, resolve, reject } = Promise.withResolvers<Finished>()\n let timed_out = false\n let held = false\n let settled = false\n let grace: NodeJS.Timeout | undefined\n const on_abort = (): void => {\n kill_group(child)\n reject(abort.reason)\n }\n for (const stream of [child.stdout, child.stderr]) {\n // Stryker disable next-line StringLiteral: Node reads an empty encoding name as UTF-8.\n stream.setEncoding('utf8')\n stream.on('data', (chunk: string) => {\n take(capture, chunk)\n })\n }\n const timer = setTimeout(() => {\n timed_out = true\n kill_group(child)\n }, Math.min(timeout_ms, MAX_TIMER_MS))\n child.once('error', (err) => {\n reject(\n new Error(`run_command couldn't start ${SHELL} in ${cwd} (${err.message}); the workspace may have been moved or deleted`, {\n cause: err,\n }),\n )\n })\n const stop_reading = (): void => {\n child.stdout.destroy()\n child.stderr.destroy()\n }\n child.once('exit', () => {\n clearTimeout(timer)\n kill_group(child)\n // A call the abort has already settled reads nothing more, so its output\n // closes at once, rather than on a grace timer that would outlive it.\n if (settled) {\n stop_reading()\n return\n }\n // Stopping the reads closes the call even while something still holds\n // the other end of the output open.\n grace = setTimeout(() => {\n held = true\n stop_reading()\n }, OUTPUT_GRACE_MS)\n })\n child.once('close', () => {\n if (timed_out) reject(timeout_error(capture, timeout_ms))\n else resolve({ capture, child, held })\n })\n abort.addEventListener('abort', on_abort)\n try {\n return await promise\n } finally {\n settled = true\n clearTimeout(timer)\n clearTimeout(grace)\n abort.removeEventListener('abort', on_abort)\n }\n}\n\n/**\n * The `run_command` tool for one session: a command run through the shell\n * in its `cwd`, with a timeout, an output cap, and the environment the\n * settings give it, its whole process tree killed when the turn is\n * cancelled. POSIX only: on Windows every call is refused.\n */\nexport function run_command_tool(session: AcpSession, settings: CommandSettings): Tool {\n return {\n name: 'run_command',\n description: [\n `Run a shell command with ${SHELL} -c in the workspace root, and return what it printed (stdout and stderr together) and its exit code.`,\n 'Each call starts a fresh shell there, so a cd lasts for its own command only.',\n `The command is stopped after ${settings.timeout_ms / 1000} s unless timeout_ms says otherwise,`,\n `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.`,\n 'Give the command plainly, without 2>&1 or a pipe to trim output that may well fit:',\n 'the user can allow a plain command for the rest of the session, but never one that holds a pipe, a redirect, &&, or ;.',\n \"It gets no input, and anything it starts is stopped once it exits, so it can't leave a server or a watcher running.\",\n ].join(' '),\n input_schema: json_schema_to_standard({\n type: 'object',\n properties: {\n command: { type: 'string', description: 'The command line, as you would type it in a POSIX shell' },\n timeout_ms: {\n type: 'integer',\n minimum: 1,\n description: `How long the command may run, in milliseconds; default: ${settings.timeout_ms}`,\n },\n },\n required: ['command'],\n additionalProperties: false,\n }),\n execute: async (input, ctx) => {\n if (process.platform === 'win32') {\n throw new Error(\n `run_command runs commands through ${SHELL} in a process group of their own, which Windows doesn't have, ` +\n 'so it can only refuse here; read_file, list_files, search, write_file, and edit_file still work',\n )\n }\n const finished = await run_shell(command_request(input), session.cwd, settings, ctx.abort)\n record_preview(session, ctx.tool_call_id, command_preview(finished))\n return report(finished)\n },\n }\n}\n","/**\n * workspace_tools: the tools a coding agent served over ACP needs, confined\n * to its session's workspace.\n *\n * They run in-process against the files on disk and in a shell of their\n * own, never through the client's `fs/*` or `terminal/*` methods, which\n * Claude Agent stopped using and the ACP v2 draft drops. They're plain\n * `Tool` values, so a flow can filter them (a read-only critic takes the\n * reads), set its own beside them, or wrap them. Each file tool checks every\n * path it's handed against the session's roots; a command starts in `cwd`\n * and reaches whatever the user can.\n *\n * The writes and `run_command` ask for approval when the session's mode\n * says to, and the reads never do.\n *\n * A flow or an MCP server can hand a model a tool of its own under one of\n * these names, and a name is all the engine tells the approval and the\n * cards. So each session keeps what it built: the names, which pick the\n * cards it draws, and every validated input that its gated tools were\n * asked about, which is how the approval knows its own calls. The engine\n * hands `needs_approval` and the approval handler the same input object,\n * so a same-named tool's call never passes for one of these.\n */\n\nimport type { Tool } from '#engine'\nimport { is_record } from '#schema'\nimport { asks_before } from './modes.js'\nimport type { GatedAction } from './modes.js'\nimport { edit_file_tool } from './tools/edit_file.js'\nimport { list_files_tool } from './tools/list_files.js'\nimport { read_file_tool } from './tools/read_file.js'\nimport { run_command_tool } from './tools/run_command.js'\nimport { search_tool } from './tools/search.js'\nimport { write_file_tool } from './tools/write_file.js'\nimport type { AcpSession, WorkspaceToolsOptions } from './types.js'\n\n/** The most lines one `read_file` call returns unless the options say otherwise. */\nconst READ_LIMIT_LINES = 2000\n\n/** The most paths one `list_files` call returns, so a very large repository's listing can't fill the context. */\nconst LIST_LIMIT = 1000\n\n/** The names `list_files` and `search` skip unless the options say otherwise. */\nconst IGNORE: ReadonlyArray<string> = ['.git', 'node_modules']\n\n/** How long one `search` may run unless the options say otherwise. */\nconst SEARCH_TIMEOUT_MS = 30_000\n\n/** How long one `run_command` call may run unless the options or the call say otherwise. */\nconst COMMAND_TIMEOUT_MS = 120_000\n\n/** The most output one `run_command` call returns unless the options say otherwise. */\nconst OUTPUT_LIMIT_BYTES = 32_000\n\n/**\n * The names each session's `workspace_tools` built. The set takes\n * `undefined` too, so a card whose opening the mapper never saw simply\n * finds nothing.\n */\nconst built = new WeakMap<AcpSession, ReadonlySet<string | undefined>>()\n\n/** The validated inputs each session's gated workspace tools were asked about. */\nconst asked = new WeakMap<AcpSession, WeakSet<object>>()\n\n/**\n * The inputs the session's gated workspace tools were asked about, made\n * empty the first time it's asked for.\n */\nfunction asked_of(session: AcpSession): WeakSet<object> {\n const inputs = asked.get(session) ?? new WeakSet<object>()\n asked.set(session, inputs)\n return inputs\n}\n\n/**\n * Whether the session's `workspace_tools` built a tool named `name`, so its\n * calls take the card that tool's presentation gives it.\n */\nexport function is_workspace_tool(session: AcpSession, name: string | undefined): boolean {\n return built.get(session)?.has(name) === true\n}\n\n/**\n * Whether one of the session's gated workspace tools was asked about this\n * very input, which makes the call one of theirs rather than a call to a\n * tool that only shares a name with one.\n */\nexport function is_workspace_call(session: AcpSession, input: unknown): boolean {\n return is_record(input) && asked.get(session)?.has(input) === true\n}\n\n/**\n * `tool`, asking for approval before each call when the session's mode asks\n * before `action`, and marking the input it was asked about as one of the\n * session's own. The mode is read at each call, not once, so a switch the\n * client makes mid-turn holds from the next call on.\n */\nfunction gated(tool: Tool, session: AcpSession, action: GatedAction): Tool {\n return {\n ...tool,\n needs_approval: (input) => {\n if (is_record(input)) asked_of(session).add(input)\n return asks_before(session.mode(), action)\n },\n }\n}\n\n/**\n * The workspace tools for one session: the reads (`read_file`, `list_files`,\n * and `search`), then the writes (`write_file` and `edit_file`), each\n * confined to the session's `cwd` and additional directories, then\n * `run_command`. The writes and the command ask before they run as the\n * session's mode says. From the first call on, the six names are the\n * workspace tools' within the session.\n */\nexport function workspace_tools(session: AcpSession, options: WorkspaceToolsOptions = {}): ReadonlyArray<Tool> {\n const ignore = options.ignore ?? IGNORE\n const tools = [\n read_file_tool(session, options.read_limit_lines ?? READ_LIMIT_LINES),\n list_files_tool(session, ignore, LIST_LIMIT),\n search_tool(session, ignore, options.search_timeout_ms ?? SEARCH_TIMEOUT_MS),\n gated(write_file_tool(session), session, 'edit'),\n gated(edit_file_tool(session), session, 'edit'),\n gated(\n run_command_tool(session, {\n timeout_ms: options.command_timeout_ms ?? COMMAND_TIMEOUT_MS,\n output_limit_bytes: options.output_limit_bytes ?? OUTPUT_LIMIT_BYTES,\n env: options.command_env,\n }),\n session,\n 'command',\n ),\n ]\n built.set(session, new Set(tools.map((tool) => tool.name)))\n return tools\n}\n","/**\n * presentation: how a workspace tool's call looks in the client, matching\n * what Zed's Claude Agent sends for its own tools.\n *\n * Each card gets the kind that picks its icon, a title that reads like the\n * call (`Read src/a.ts (1 - 40)`, `grep \"todo\" src`, the command line) with\n * its paths relative to `cwd`, and the places it touches as locations, whose\n * lines count from 1 as Claude Agent's do. A write's or an edit's card shows\n * its diff once the call lands, a read's, a listing's, or a search's shows\n * the text the model read in a code block, and a command's shows what it\n * printed: in a terminal when the client advertises Zed's terminal extension\n * (`_meta.terminal_output`), and as a `console` code block otherwise.\n *\n * It's keyed by tool name, since nothing ACP-specific may reach the engine's\n * `Tool` type and a card opens with nothing but the name the model called.\n * Only the names the session's `workspace_tools` built count, so in a\n * session that never built them, a tool of the flow's own that shares a\n * name gets the plain card. It does no I/O: the file reads behind a diff\n * happen in the tools, which leave each call's preview in the session's\n * store for its card to take when the call's result arrives.\n */\n\nimport { resolve } from 'node:path'\nimport type { SessionUpdate, ToolCall, ToolCallContent, ToolCallLocation, ToolKind } from '@agentclientprotocol/sdk'\nimport type { StreamChunk } from '#engine'\nimport { as_record } from '#schema'\nimport { shown_path } from './tools/containment.js'\nimport { take_preview } from './tools/previews.js'\nimport type { ChangePreview, CommandPreview, ToolPreview } from './tools/previews.js'\nimport type { AcpSession } from './types.js'\nimport { is_workspace_tool } from './workspace_tools.js'\n\ntype ToolResultChunk = Extract<StreamChunk, { kind: 'tool_result' }>\n\n/** An update to a card the client already shows. */\nexport type CardUpdate = Extract<SessionUpdate, { sessionUpdate: 'tool_call_update' }>\n\n/** What a call's input says about its card: its title, and the places it touches. */\ntype Described = {\n readonly title: string\n readonly locations?: ToolCallLocation[]\n}\n\n/** How a command ended, as its terminal shows it. */\ntype Ran = Pick<CommandPreview, 'output' | 'exit_code' | 'signal'>\n\n/**\n * How one workspace tool's cards look: the kind that picks the icon, what a\n * call's input says about it, and what its card shows once the call\n * succeeds: the change it made, what the command printed, or the text the\n * model read.\n */\ntype Presenter = {\n readonly kind: ToolKind\n readonly describe: (fields: Record<string, unknown>, session: AcpSession) => Described | undefined\n readonly shows?: 'change' | 'command' | 'text'\n}\n\n/**\n * A path the call names, made absolute under the client's `cwd`, which is\n * how a location and a diff carry it.\n */\nfunction absolute(session: AcpSession, path: string): string {\n return resolve(session.cwd, path)\n}\n\n/**\n * A path as a title shows it: relative to `cwd` when it's under it, and\n * absolute otherwise, the way the tools show paths to the model.\n */\nfunction shown(session: AcpSession, path: string): string {\n return shown_path(session, absolute(session, path))\n}\n\n/**\n * The lines a read covers, as its title says them: a range when the call\n * sets a limit, where it starts when it sets only an offset, and nothing\n * when it reads from the top.\n */\nfunction read_range(first: number, offset: unknown, limit: unknown): string {\n if (typeof limit === 'number') return ` (${first} - ${first + limit - 1})`\n if (typeof offset === 'number') return ` (from line ${offset})`\n return ''\n}\n\n/**\n * A `read_file` card: `Read <path>` with the lines it covers, pointing at\n * the line the read starts on.\n */\nfunction describe_read({ path, offset, limit }: Record<string, unknown>, session: AcpSession): Described | undefined {\n if (typeof path !== 'string') return undefined\n const first = typeof offset === 'number' ? offset : 1\n return {\n title: `Read ${shown(session, path)}${read_range(first, offset, limit)}`,\n locations: [{ path: absolute(session, path), line: first }],\n }\n}\n\n/**\n * A `write_file` or `edit_file` card: the verb and the path, pointing at\n * the file. The line an edit lands on comes with its preview, once the\n * edit has found it.\n */\nfunction describe_change(verb: string): Presenter['describe'] {\n return ({ path }, session) =>\n typeof path === 'string'\n ? { title: `${verb} ${shown(session, path)}`, locations: [{ path: absolute(session, path) }] }\n : undefined\n}\n\n/**\n * A `list_files` card: `Find` with the directory and the pattern in code\n * spans, each when the call names it.\n */\nfunction describe_find({ pattern, path }: Record<string, unknown>, session: AcpSession): Described {\n const parts = ['Find']\n if (typeof path === 'string') parts.push(`\\`${shown(session, path)}\\``)\n if (typeof pattern === 'string') parts.push(`\\`${pattern}\\``)\n return { title: parts.join(' ') }\n}\n\n/**\n * A `search` card, titled the way the grep command line that does the same\n * search reads.\n */\nfunction describe_grep({ pattern, path, glob }: Record<string, unknown>, session: AcpSession): Described {\n const parts = ['grep']\n if (typeof glob === 'string') parts.push(`--include=\"${glob}\"`)\n if (typeof pattern === 'string') parts.push(`\"${pattern}\"`)\n if (typeof path === 'string') parts.push(shown(session, path))\n return { title: parts.join(' ') }\n}\n\n/**\n * A `run_command` card, titled with the command line itself.\n */\nfunction describe_command({ command }: Record<string, unknown>): Described | undefined {\n return typeof command === 'string' ? { title: command } : undefined\n}\n\n/**\n * The workspace tools by name. The key takes `undefined` too, so a card\n * whose opening the mapper never saw simply finds nothing.\n */\nconst PRESENTERS = new Map<string | undefined, Presenter>([\n ['read_file', { kind: 'read', describe: describe_read, shows: 'text' }],\n ['list_files', { kind: 'search', describe: describe_find, shows: 'text' }],\n ['search', { kind: 'search', describe: describe_grep, shows: 'text' }],\n ['write_file', { kind: 'edit', describe: describe_change('Write'), shows: 'change' }],\n ['edit_file', { kind: 'edit', describe: describe_change('Edit'), shows: 'change' }],\n ['run_command', { kind: 'execute', describe: describe_command, shows: 'command' }],\n])\n\n/**\n * How the cards of the tool `name` look in `session`, when the session's\n * `workspace_tools` built a tool of that name. Any other tool gets the\n * plain card.\n */\nfunction presenter_of(session: AcpSession, name: string | undefined): Presenter | undefined {\n return is_workspace_tool(session, name) ? PRESENTERS.get(name) : undefined\n}\n\n/**\n * Whether the client draws a command's output in a terminal from Zed's\n * `_meta` extension, which it says in `initialize`.\n */\nfunction renders_terminals(session: AcpSession): boolean {\n const { _meta: meta } = session.client_capabilities\n return meta?.['terminal_output'] === true\n}\n\n/**\n * The terminal a card shows, under the card's own id, as Claude Agent names\n * its terminals.\n */\nfunction terminal(card: string): ToolCallContent {\n return { type: 'terminal', terminalId: card }\n}\n\n/**\n * What a workspace tool's card opens with: its kind, and for a command in a\n * client that draws terminals, the terminal its output will land in.\n */\nexport function opening_fields(session: AcpSession | undefined, name: string, card: string): Partial<ToolCall> {\n // Stryker disable next-line ConditionalExpression: a missing session built no workspace tools, so presenter_of finds nothing for it either way; the check narrows the type.\n if (session === undefined) return {}\n const presenter = presenter_of(session, name)\n if (presenter === undefined) return {}\n if (presenter.shows !== 'command' || !renders_terminals(session)) return { kind: presenter.kind }\n return { kind: presenter.kind, content: [terminal(card)], _meta: { terminal_info: { terminal_id: card } } }\n}\n\n/**\n * What a workspace tool call's complete input adds to its card: its title\n * and locations. An input that lacks what they need leaves the card as it\n * opened.\n */\nexport function input_fields(session: AcpSession | undefined, name: string | undefined, input: unknown): Partial<CardUpdate> {\n // Stryker disable next-line ConditionalExpression: a missing session built no workspace tools, so presenter_of finds nothing for it either way; the check narrows the type.\n if (session === undefined) return {}\n const presenter = presenter_of(session, name)\n if (presenter === undefined) return {}\n return presenter.describe(as_record(input) ?? {}, session) ?? {}\n}\n\n/**\n * A file change as a diff, which a client shows as the file's hunks.\n */\nfunction diff_of(change: ChangePreview): ToolCallContent {\n return { type: 'diff', path: change.path, oldText: change.old_text, newText: change.new_text }\n}\n\n/**\n * Close a write's or an edit's card with the change it made, and for an\n * edit, the line its first match starts on. The closing update replaces the\n * card's content, so it carries the diff again rather than dropping one the\n * card already shows. A call that failed, or left no change behind, closes\n * as it stands.\n */\nfunction close_change(closing: CardUpdate, preview: ToolPreview | undefined): CardUpdate {\n if (preview?.kind !== 'change') return closing\n return {\n ...closing,\n content: [diff_of(preview)],\n ...(preview.line === undefined ? {} : { locations: [{ path: preview.path, line: preview.line }] }),\n }\n}\n\n/**\n * Text in a code block under the `info` string, its fence longer than any\n * run of backticks that opens one of its lines, so nothing in the text can\n * close the block early.\n */\nfunction code_block(text: string, info: string): ToolCallContent {\n const longest = Math.max(2, ...Array.from(text.matchAll(/^`+/gm), ([run]) => run.length))\n const fence = '`'.repeat(longest + 1)\n return { type: 'content', content: { type: 'text', text: `${fence}${info}\\n${text}\\n${fence}` } }\n}\n\n/**\n * Close a read's, a listing's, or a search's card with the text the model\n * read. A listing or a search result goes in a code block too, since a\n * matching line can hold markdown that the client would otherwise render.\n * A failed call keeps its error text.\n */\nfunction close_text(closing: CardUpdate, chunk: ToolResultChunk): CardUpdate {\n if (chunk.error !== undefined) return closing\n return { ...closing, content: [code_block(String(chunk.output), '')] }\n}\n\n/**\n * How a command's terminal ends: what it printed and how it exited, or, for\n * a call that failed or left nothing behind, the error text and no exit\n * code.\n */\nfunction ran(chunk: ToolResultChunk, preview: ToolPreview | undefined): Ran {\n if (preview?.kind === 'command') return preview\n return { output: chunk.error?.message ?? '', exit_code: null, signal: null }\n}\n\n/**\n * Close a command's card. A client that draws terminals gets the output on\n * the terminal the card opened with, then the exit and the status, as\n * Claude Agent sends them. Any other client gets what the model read, its\n * exit code included, in a `console` block; a failed call keeps its error\n * text.\n */\nfunction close_command(\n session: AcpSession,\n card: string,\n chunk: ToolResultChunk,\n closing: CardUpdate,\n preview: ToolPreview | undefined,\n): SessionUpdate[] {\n if (!renders_terminals(session)) {\n if (chunk.error !== undefined) return [closing]\n return [{ ...closing, content: [code_block(String(chunk.output), 'console')] }]\n }\n const { output, exit_code, signal } = ran(chunk, preview)\n return [\n {\n sessionUpdate: 'tool_call_update',\n toolCallId: card,\n _meta: { terminal_output: { terminal_id: card, data: output } },\n },\n {\n ...closing,\n content: [terminal(card)],\n _meta: { terminal_exit: { terminal_id: card, exit_code, signal } },\n },\n ]\n}\n\n/**\n * The updates that close a tool call's card, starting from the plain\n * `closing` update. A read, a listing, or a search leaves no preview, so its\n * card takes nothing from the session's store. A successful call of a tool\n * that leaves a preview takes it from the store whatever the card then does\n * with it, which keeps each raw id's queue in step with its results.\n */\nexport function closing_updates(\n session: AcpSession | undefined,\n name: string | undefined,\n card: string,\n chunk: ToolResultChunk,\n closing: CardUpdate,\n): SessionUpdate[] {\n // Stryker disable next-line ConditionalExpression: a missing session built no workspace tools, so presenter_of finds nothing for it either way; the check narrows the type.\n if (session === undefined) return [closing]\n const shows = presenter_of(session, name)?.shows\n if (shows === undefined) return [closing]\n if (shows === 'text') return [close_text(closing, chunk)]\n const preview = chunk.error === undefined ? take_preview(session, chunk.id) : undefined\n if (shows === 'change') return [close_change(closing, preview)]\n return close_command(session, card, chunk, closing, preview)\n}\n","/**\n * approve: ask the client before a workspace tool edits a file or runs a\n * command, through `session/request_permission`.\n *\n * The request shows the card the client already draws for the call, and\n * for an edit, the change worked out on disk first, so the user approves\n * the diff itself. It offers Allow, Reject, and an \"always\" that lives in\n * memory for the session. For an edit, \"always\" switches the session to\n * Accept edits, as Claude Agent's does, and tells the client both ways so\n * its mode picker follows. For a command, it covers that exact command\n * line and nothing else, since one flag can turn a listing into a delete\n * (`find . -name '*.ts'` and `find . -delete`). A command with shell\n * control syntax is never covered and never offered one, since anything\n * can follow a `;` or a `|`.\n *\n * Only the session's own workspace tools get the diff and the \"always\",\n * known by the input their `needs_approval` marked rather than by name. A\n * tool of a flow's own or an MCP tool that shares a name gets the plain\n * request, and no grant covers it.\n *\n * A permission check that fails open isn't a check, so anything short of\n * an allow denies the call: a rejection, a `cancelled` outcome, an option\n * the request never offered, and a request that fails for any reason.\n *\n * The engine asks with its raw call id, which can repeat inside a turn,\n * and the turn's consumer can still be sending earlier updates when it\n * asks. So the request waits until the consumer has sent everything the\n * run had recorded by then, the card's opening included, and points at the\n * latest card the client was sent for that raw id. The consumer never\n * waits on an approval, so the wait can't deadlock, and the turn's abort\n * ends it.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type {\n PermissionOption,\n RequestPermissionOutcome,\n RequestPermissionRequest,\n RequestPermissionResponse,\n SessionUpdate,\n ToolCallUpdate,\n} from '@agentclientprotocol/sdk'\nimport type { TrajectoryEvent, TrajectoryLogger } from '#core'\nimport type { ToolApprovalRequest } from '#engine'\nimport { as_record } from '#schema'\nimport { asks_before } from './modes.js'\nimport type { GatedAction, SessionModes } from './modes.js'\nimport { input_fields, opening_fields } from './presentation.js'\nimport { edit_file_change } from './tools/edit_file.js'\nimport { write_file_change } from './tools/write_file.js'\nimport type { ShownChange } from './tools/write_file.js'\nimport type { AcpSession } from './types.js'\nimport { is_workspace_call } from './workspace_tools.js'\n\n/**\n * What a session's turn tells its approvals: how far the turn's consumer\n * has got, and which card each raw call id opened last.\n *\n * A run that outran the client so far that it dropped events never lets\n * the consumer catch up, so an approval it asks for waits until the turn\n * is cancelled. Only a client that has stopped reading gets that far\n * behind, and it wouldn't answer the request either.\n */\nexport type CardSync = {\n /**\n * Start a turn, forgetting the last one. Returns the logger the turn's\n * run records through, which counts every event `run.stream` queues and\n * passes each one on to `inner`.\n */\n readonly start: (inner: TrajectoryLogger | undefined) => TrajectoryLogger\n /** Note that the consumer has sent every update one event maps to. */\n readonly sent: (event: TrajectoryEvent, updates: ReadonlyArray<SessionUpdate>) => void\n /** Settle once the consumer has sent every event the run had recorded by now. */\n readonly caught_up: () => Promise<void>\n /** The id of the latest card the client was sent for a raw call id. */\n readonly card_for: (raw_id: string) => string | undefined\n}\n\n/** One turn's count of the events its run recorded and its consumer sent. */\ntype TurnProgress = {\n recorded: number\n sent: number\n /** Settles at the consumer's next event, then gives way to a fresh one. */\n moved: PromiseWithResolvers<void>\n readonly cards: Map<string, string>\n}\n\n/**\n * Asks the client to approve one tool call, and withdraws the request\n * when `cancel` fires.\n */\nexport type PermissionAsker = (\n request: RequestPermissionRequest,\n cancel: AbortSignal,\n) => Promise<RequestPermissionResponse>\n\n/** What a session's approvals need beside the session itself. */\nexport type ApproverDeps = {\n readonly modes: SessionModes\n readonly cards: CardSync\n readonly ask: PermissionAsker\n}\n\n/** Answers the engine's approval requests for the calls in one session. */\nexport type SessionApprover = (session: AcpSession, request: ToolApprovalRequest) => Promise<boolean>\n\n/**\n * What a workspace tool that asks does, and for a write or an edit, how\n * to work out its change without making it. A gate goes by name, but only\n * a call the session's own workspace tool marked ever reaches one.\n */\ntype Gate = {\n readonly action: GatedAction\n readonly change?: (session: AcpSession, input: unknown) => Promise<ShownChange>\n}\n\nconst GATES: ReadonlyMap<string, Gate> = new Map<string, Gate>([\n ['write_file', { action: 'edit', change: write_file_change }],\n ['edit_file', { action: 'edit', change: edit_file_change }],\n ['run_command', { action: 'command' }],\n])\n\n/**\n * Shell syntax that runs, chains, or redirects something past the\n * command's own program: `;`, `&`, `|`, `>`, `<`, a backtick, `$(`, and a\n * newline.\n */\nconst CONTROL_SYNTAX = /[;&|<>`\\n]|\\$\\(/\n\n/** The \"always\" an approval offers, and what choosing it grants. */\ntype Always = {\n readonly name: string\n readonly grant: () => Promise<void>\n}\n\nconst ALLOW_ONCE: PermissionOption = { optionId: 'allow_once', name: 'Allow', kind: 'allow_once' }\nconst REJECT_ONCE: PermissionOption = { optionId: 'reject_once', name: 'Reject', kind: 'reject_once' }\n\n/**\n * A fresh count for a turn that has recorded and sent nothing yet.\n */\nfunction fresh_progress(): TurnProgress {\n return { recorded: 0, sent: 0, moved: Promise.withResolvers(), cards: new Map() }\n}\n\n/**\n * `inner`, or nothing, with `count` called after each call that queues an\n * event. Without an inner logger, a span gets an id of its own, as the\n * runner's default logger gives one.\n */\nfunction counting_logger(inner: TrajectoryLogger | undefined, count: () => void): TrajectoryLogger {\n return {\n record: (event) => {\n inner?.record(event)\n count()\n },\n start_span: (name, meta) => {\n const id = inner?.start_span(name, meta) ?? `${name}:${randomUUID()}`\n count()\n return id\n },\n end_span: (id, meta) => {\n inner?.end_span(id, meta)\n count()\n },\n }\n}\n\n/**\n * The raw id of the call a `tool_call_start` chunk opens, or `undefined`\n * for any other event.\n */\nfunction started_call(event: TrajectoryEvent): string | undefined {\n if (event.kind !== 'model_chunk') return undefined\n const chunk = as_record(event['chunk'])\n // Stryker disable next-line ConditionalExpression: a non-string id would land under a key no string lookup finds, so the check only narrows the type.\n return chunk?.['kind'] === 'tool_call_start' && typeof chunk['id'] === 'string' ? chunk['id'] : undefined\n}\n\n/**\n * Whether an update opens a card.\n */\nfunction opens_card(update: SessionUpdate): update is Extract<SessionUpdate, { sessionUpdate: 'tool_call' }> {\n return update.sessionUpdate === 'tool_call'\n}\n\n/**\n * Create the sync between a session's turns and its approvals. Turns in a\n * session never overlap, so one sync serves them all, a turn at a time.\n */\nexport function create_card_sync(): CardSync {\n let turn = fresh_progress()\n return {\n start: (inner) => {\n const started = fresh_progress()\n turn = started\n return counting_logger(inner, () => {\n started.recorded += 1\n })\n },\n sent: (event, updates) => {\n const raw_id = started_call(event)\n const card = updates.find(opens_card)\n // Stryker disable next-line ConditionalExpression: a card noted under no raw id sits where no lookup asks, so the check only narrows the type.\n if (raw_id !== undefined && card !== undefined) turn.cards.set(raw_id, card.toolCallId)\n turn.sent += 1\n turn.moved.resolve()\n turn.moved = Promise.withResolvers()\n },\n caught_up: async () => {\n const waiting = turn\n const target = waiting.recorded\n while (waiting.sent < target) await waiting.moved.promise\n },\n card_for: (raw_id) => turn.cards.get(raw_id),\n }\n}\n\n/**\n * What an \"always\" grant for a command covers: the command line itself,\n * with the whitespace at its ends trimmed and everything between compared\n * exactly, because `rm \"a b\"` and `rm \"a b\"` name different files. A\n * command with shell control syntax has none, so no grant ever covers it,\n * and neither does one that isn't a string or is only whitespace.\n */\nexport function command_key(input: unknown): string | undefined {\n const command = as_record(input)?.['command']\n if (typeof command !== 'string' || CONTROL_SYNTAX.test(command)) return undefined\n const key = command.trim()\n return key === '' ? undefined : key\n}\n\n/**\n * The message a failure carries, whatever was thrown.\n */\nexport function message_of(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/**\n * Start `work` and settle with it, or reject with the abort's reason as\n * soon as `abort` fires, so a turn's cancel never waits on the client. A\n * turn already cancelled starts nothing, so no request goes out for it.\n */\nasync function unless_aborted<T>(abort: AbortSignal, work: () => Promise<T>): Promise<T> {\n abort.throwIfAborted()\n const { promise: aborted, reject } = Promise.withResolvers<never>()\n const on_abort = (): void => {\n reject(abort.reason)\n }\n abort.addEventListener('abort', on_abort)\n try {\n return await Promise.race([work(), aborted])\n } finally {\n // The turn's signal outlives every approval it asks for.\n abort.removeEventListener('abort', on_abort)\n }\n}\n\n/**\n * What a change adds to the request's card: its diff, and for an edit,\n * the line its first match starts on. A change that can't be worked out\n * shows why instead, which is what the call will fail with if it's\n * allowed, so the user isn't asked to approve a change they can't see.\n */\nasync function change_fields(\n change: NonNullable<Gate['change']>,\n session: AcpSession,\n input: unknown,\n): Promise<Partial<ToolCallUpdate>> {\n try {\n const { path, old_text, new_text, line } = await change(session, input)\n return {\n content: [{ type: 'diff', path, oldText: old_text, newText: new_text }],\n ...(line === undefined ? {} : { locations: [{ path, line }] }),\n }\n } catch (err: unknown) {\n return { content: [{ type: 'content', content: { type: 'text', text: message_of(err) } }] }\n }\n}\n\n/**\n * The card a request shows: the one the client already draws for the call\n * under `card`, as its tool's presentation describes it, with the change\n * for a write or an edit.\n */\nasync function permission_card(\n session: AcpSession,\n request: ToolApprovalRequest,\n card: string,\n gate: Gate | undefined,\n): Promise<ToolCallUpdate> {\n const { tool_name: name, input } = request\n const fields: ToolCallUpdate = {\n toolCallId: card,\n title: name,\n kind: opening_fields(session, name, card).kind ?? 'other',\n rawInput: input,\n ...input_fields(session, name, input),\n }\n if (gate?.change === undefined) return fields\n return { ...fields, ...(await change_fields(gate.change, session, input)) }\n}\n\n/**\n * Whether the user's answer allows the call, granting the \"always\" first\n * when that's what they chose. Only an option the request offered counts.\n */\nasync function allowed(outcome: RequestPermissionOutcome, always: Always | undefined): Promise<boolean> {\n if (outcome.outcome !== 'selected') return false\n if (outcome.optionId === ALLOW_ONCE.optionId) return true\n if (outcome.optionId !== 'allow_always' || always === undefined) return false\n await always.grant()\n return true\n}\n\n/**\n * Say on stderr that a permission request failed, since the call was\n * refused without the user ever seeing it.\n */\nfunction warn_failed(tool_name: string, err: unknown): void {\n process.stderr.write(\n `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`,\n )\n}\n\n/**\n * The \"always\" a call is offered: Accept edits for an edit, and a grant of\n * its key for a command that has one. Any other call gets none. Choosing\n * Accept edits leaves a session that has moved past Manual since the call\n * asked where it is.\n */\nfunction always_for(\n gate: Gate | undefined,\n key: string | undefined,\n modes: SessionModes,\n granted: Set<string>,\n): Always | undefined {\n if (gate?.action === 'edit') {\n return {\n name: 'Allow all edits this session',\n grant: async () => {\n if (asks_before(modes.current(), 'edit')) await modes.switch_to('accept_edits')\n },\n }\n }\n if (key === undefined) return undefined\n return {\n name: `Always allow \\`${key}\\` this session`,\n grant: async () => {\n granted.add(key)\n },\n }\n}\n\n/**\n * The options a request offers. Allow is always among them, since some\n * hosts answer every request on their own by choosing `allow_once`.\n */\nfunction options_for(always: Always | undefined): PermissionOption[] {\n if (always === undefined) return [ALLOW_ONCE, REJECT_ONCE]\n return [ALLOW_ONCE, { optionId: 'allow_always', name: always.name, kind: 'allow_always' }, REJECT_ONCE]\n}\n\n/**\n * Create the approvals for one session's calls, holding its commands'\n * \"always\" grants for the life of the session.\n */\nexport function session_approver({ modes, cards, ask }: ApproverDeps): SessionApprover {\n const granted = new Set<string>()\n return async (session, request) => {\n const gate = is_workspace_call(session, request.input) ? GATES.get(request.tool_name) : undefined\n const key = gate?.action === 'command' ? command_key(request.input) : undefined\n // Stryker disable next-line ConditionalExpression: only keys are ever granted, so has() answers false for a missing key either way; the check narrows the type.\n if (key !== undefined && granted.has(key)) return true\n const always = always_for(gate, key, modes, granted)\n const options = options_for(always)\n try {\n await unless_aborted(request.abort, cards.caught_up)\n const card = cards.card_for(request.tool_call_id) ?? randomUUID()\n const toolCall = await permission_card(session, request, card, gate)\n const answer = await unless_aborted(request.abort, () =>\n ask({ sessionId: session.id, toolCall, options }, request.abort),\n )\n return await allowed(answer.outcome, always)\n } catch (err: unknown) {\n if (!request.abort.aborted) warn_failed(request.tool_name, err)\n return false\n }\n }\n}\n","/**\n * Maps a run's events onto ACP `session/update` payloads.\n *\n * Under `run.stream`, each `model_call` records `model_chunk` events carrying\n * the engine's `StreamChunk`, the same source fascicle/ui reads. This half of\n * a prompt turn does no I/O and holds no SDK value, so a flow author can wrap\n * `to_session_updates` in their own `to_updates` and add to what it returns,\n * as long as every event still reaches it: each `span_start` advances the\n * state's count of how many times a step has run, and a workspace tool's\n * result takes its call's preview from the session's store. Spans, `cost`,\n * and `emit` events map to nothing; an `emit` never becomes chat output\n * implicitly, because output that changes with a value's shape is a trap.\n *\n * Every tool gets a plain card here. Given the turn's session, the workspace\n * tools' cards also take the look `presentation.ts` gives them.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { ContentBlock, SessionUpdate } from '@agentclientprotocol/sdk'\nimport type { TrajectoryEvent } from '#core'\nimport type { StreamChunk } from '#engine'\nimport { closing_updates, input_fields, opening_fields } from './presentation.js'\nimport type { CardUpdate } from './presentation.js'\nimport type { AcpMapperOptions, AcpMapperState, AcpStreamRoute } from './types.js'\n\ntype ToolResultChunk = Extract<StreamChunk, { kind: 'tool_result' }>\n\n/**\n * Create the state for one prompt turn's events, routing every model call's\n * text to the reply unless `stream` says otherwise.\n */\nexport function create_acp_mapper_state(options: AcpMapperOptions = {}): AcpMapperState {\n return {\n turn_id: options.turn_id ?? randomUUID(),\n stream: options.stream ?? (() => 'message'),\n runs: new Map(),\n session: options.session,\n tools: new Map(),\n }\n}\n\n/**\n * Build the session-unique ACP id for an engine tool call id.\n *\n * Raw ids repeat across model calls, turns, and runs of one model call\n * (Ollama has none on the wire, so the engine numbers them\n * `ollama_call_<step>_<n>` afresh on every generate call), and a repeated id\n * would make the client update an old card instead of opening a new one.\n */\nfunction acp_tool_call_id(state: AcpMapperState, step_id: string, raw_id: string): string {\n return `${state.turn_id}:${step_id}:${state.runs.get(step_id) ?? 0}:${raw_id}`\n}\n\n/**\n * Count one more run of the step a `span_start` opens, by the `id` its span\n * carries. Counting starts rather than finishes covers a retry whose first\n * attempt failed before it finished.\n */\nfunction count_run(event: TrajectoryEvent, state: AcpMapperState): void {\n const id = event['id']\n if (typeof id === 'string') state.runs.set(id, (state.runs.get(id) ?? 0) + 1)\n}\n\n/**\n * Wrap streamed text as the update its route names, or nothing for `'none'`.\n */\nfunction text_updates(route: AcpStreamRoute, text: string): SessionUpdate[] {\n const content: ContentBlock = { type: 'text', text }\n if (route === 'message') return [{ sessionUpdate: 'agent_message_chunk', content }]\n if (route === 'thought') return [{ sessionUpdate: 'agent_thought_chunk', content }]\n return []\n}\n\n/**\n * Close a tool card: `completed` with the raw output, or `failed` with the\n * error text as the card's content, since that text is what the user needs\n * to see.\n */\nfunction tool_result_update(tool_call_id: string, chunk: ToolResultChunk): CardUpdate {\n if (chunk.error !== undefined) {\n return {\n sessionUpdate: 'tool_call_update',\n toolCallId: tool_call_id,\n status: 'failed',\n content: [{ type: 'content', content: { type: 'text', text: chunk.error.message } }],\n }\n }\n return {\n sessionUpdate: 'tool_call_update',\n toolCallId: tool_call_id,\n status: 'completed',\n rawOutput: chunk.output,\n }\n}\n\n/**\n * Map one engine `StreamChunk` from the model call `step_id` to the session\n * updates it produces.\n */\nfunction map_chunk(chunk: StreamChunk, step_id: string, state: AcpMapperState): SessionUpdate[] {\n switch (chunk.kind) {\n case 'text':\n return text_updates(state.stream(step_id), chunk.text)\n case 'reasoning':\n return text_updates('thought', chunk.text)\n case 'tool_call_start': {\n const card = acp_tool_call_id(state, step_id, chunk.id)\n state.tools.set(card, chunk.name)\n return [\n {\n sessionUpdate: 'tool_call',\n toolCallId: card,\n title: chunk.name,\n kind: 'other',\n status: 'pending',\n ...opening_fields(state.session, chunk.name, card),\n },\n ]\n }\n case 'tool_call_end': {\n const card = acp_tool_call_id(state, step_id, chunk.id)\n return [\n {\n sessionUpdate: 'tool_call_update',\n toolCallId: card,\n status: 'in_progress',\n rawInput: chunk.input,\n ...input_fields(state.session, state.tools.get(card), chunk.input),\n },\n ]\n }\n case 'tool_result': {\n const card = acp_tool_call_id(state, step_id, chunk.id)\n return closing_updates(state.session, state.tools.get(card), card, chunk, tool_result_update(card, chunk))\n }\n default:\n // The input arrives whole at tool_call_end, so its deltas add nothing,\n // and step_finish and finish carry no content for the client.\n return []\n }\n}\n\n/**\n * Narrow the loose `chunk` field of a `model_chunk` event. model_call records\n * only real StreamChunks there, and map_chunk maps a kind it doesn't know to\n * nothing, so ruling out a missing or null value is enough.\n */\nfunction is_stream_chunk(value: unknown): value is StreamChunk {\n return typeof value === 'object' && value !== null\n}\n\n/**\n * Map one run event to zero or more ACP session updates. Only `model_chunk`\n * events produce any. A `span_start` advances the state's run count, a\n * card's opening records its tool, and a workspace tool's result takes its\n * preview; the function does no I/O.\n */\nexport function to_session_updates(event: TrajectoryEvent, state: AcpMapperState): SessionUpdate[] {\n if (event.kind === 'span_start') {\n count_run(event, state)\n return []\n }\n if (event.kind !== 'model_chunk') return []\n const step_id = event['step_id']\n const chunk = event['chunk']\n if (typeof step_id !== 'string' || !is_stream_chunk(chunk)) return []\n return map_chunk(chunk, step_id, state)\n}\n","/**\n * One ACP prompt turn: run the session's flow through `run.stream` and send\n * what it produces to the client as session updates.\n *\n * The turn holds three rules the protocol leaves to the agent. A cancel\n * (`session/cancel`, the request's own `$/cancel_request`, a disconnect, or\n * the config's `abort`) stops the sending at once, then waits for the run to\n * settle and answers `cancelled`, even when the flow ignored the abort and\n * finished. A turn that sent no message text sends `to_text(output)` as its\n * reply. And the history records what the client was actually sent, a\n * cancelled turn included, so it matches the thread the user sees.\n */\n\nimport type { ContentBlock, PromptResponse, SessionUpdate } from '@agentclientprotocol/sdk'\nimport { aborted_error, run } from '#core'\nimport type { Step, TrajectoryEvent } from '#core'\nimport type { CardSync } from './approve.js'\nimport { create_acp_mapper_state, to_session_updates } from './to_session_updates.js'\nimport { reset_previews } from './tools/previews.js'\nimport type { AcpHistoryEntry, AcpSession, AcpTurn, ServeAcpConfig } from './types.js'\n\n/**\n * A session's latest turn, finished or not. Cancelling a finished turn does\n * nothing and waiting on it returns at once, so the record never needs\n * clearing.\n */\ntype TurnHandle = {\n readonly cancel: AbortController\n readonly settled: Promise<void>\n}\n\n/**\n * A session between turns: its flow, its history, its latest turn, and the\n * sync that lets its approvals wait for the client to catch up.\n */\nexport type SessionRecord<i, o> = {\n readonly session: AcpSession\n readonly flow: Step<i, o>\n readonly history: AcpHistoryEntry[]\n readonly cards: CardSync\n last_turn: TurnHandle | null\n}\n\nexport type SendUpdate = (update: SessionUpdate) => Promise<void>\n\ntype Reply = { sent: boolean; text: string; card_since_text: boolean }\n\ntype Settled<o> = { readonly ok: true; readonly output: o } | { readonly ok: false; readonly error: unknown }\n\n/**\n * Join a prompt's blocks into the text a flow reads. Text blocks join as the\n * client split them, and a resource link or an embedded resource reads as\n * its URI where it sat. Each embedded resource's text follows the prompt in\n * a `<context>` block naming that URI, the form Claude Agent uses, so a file\n * the user @-mentioned reaches the model without splitting the sentence that\n * mentions it. Image and audio blocks stay in `turn.prompt` only, since the\n * agent advertises neither.\n */\nfunction turn_text(prompt: ReadonlyArray<ContentBlock>): string {\n const inline: string[] = []\n const context: string[] = []\n for (const block of prompt) {\n if (block.type === 'text') inline.push(block.text)\n else if (block.type === 'resource_link') inline.push(block.uri)\n else if (block.type === 'resource') {\n inline.push(block.resource.uri)\n if ('text' in block.resource) {\n context.push(`<context ref=\"${block.resource.uri}\">\\n${block.resource.text}\\n</context>`)\n }\n }\n }\n return [inline.join(''), ...context].join('\\n\\n')\n}\n\n/**\n * The flow's input for a turn: the config's `to_input`, or the turn's text,\n * which `ServeAcpConfig` allows only when the flow takes a string.\n */\nfunction turn_input<i, o>(config: ServeAcpConfig<i, o>, turn: AcpTurn): i {\n if (config.to_input !== undefined) return config.to_input(turn)\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return turn.text as i\n}\n\n/**\n * The default `to_text`: a string as-is, anything else as JSON, and nothing\n * at all for a flow that returns nothing.\n */\nfunction default_to_text(output: unknown): string {\n return typeof output === 'string' ? output : (JSON.stringify(output) ?? '')\n}\n\n/**\n * Wrap a turn's final text as the message update that carries it.\n */\nfunction agent_message(text: string): SessionUpdate {\n return { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } }\n}\n\n/**\n * Count a message update the client was sent toward the turn's reply. Only\n * text joins the reply's text, but any message counts as a reply, so a flow\n * that sent an image doesn't get a `to_text` message after it. A tool card\n * that opened after some reply text splits the reply in two on the client,\n * so the recorded text starts the next run on a blank line instead of\n * running the two together.\n */\nfunction note_reply(reply: Reply, update: SessionUpdate): void {\n if (update.sessionUpdate === 'tool_call' && reply.text !== '') reply.card_since_text = true\n if (update.sessionUpdate !== 'agent_message_chunk') return\n reply.sent = true\n if (update.content.type !== 'text' || update.content.text === '') return\n reply.text += reply.card_since_text ? `\\n\\n${update.content.text}` : update.content.text\n reply.card_since_text = false\n}\n\n/**\n * Append a turn to the session's history: the user's text, then the reply\n * text the client was sent, when there was any. A cancelled turn marks\n * whichever of the two came last.\n */\nfunction record_exchange(history: AcpHistoryEntry[], user_text: string, reply_text: string, cancelled: boolean): void {\n const stop = cancelled ? { cancelled: true as const } : {}\n if (reply_text === '') history.push({ role: 'user', text: user_text, ...stop })\n else history.push({ role: 'user', text: user_text }, { role: 'agent', text: reply_text, ...stop })\n}\n\n/**\n * Settle a run's result into a value, so a run that fails while the turn is\n * still sending never surfaces as an unhandled rejection.\n */\nfunction settle<o>(result: Promise<o>): Promise<Settled<o>> {\n return result.then(\n (output): Settled<o> => ({ ok: true, output }),\n (error: unknown): Settled<o> => ({ ok: false, error }),\n )\n}\n\n/**\n * Say on stderr that the run outran the client and dropped events, since the\n * reply the client shows is missing text from that point on.\n */\nfunction warn_dropped(event: TrajectoryEvent): void {\n process.stderr.write(\n `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`,\n )\n}\n\n/**\n * Send each run event's updates in order, and tell the session's card sync\n * once all of an event's updates have gone out. Once the turn is cancelled\n * nothing more is sent, and leaving the loop closes the run's event stream.\n */\nasync function forward<i, o>(\n events: AsyncIterable<TrajectoryEvent>,\n config: ServeAcpConfig<i, o>,\n record: SessionRecord<i, o>,\n cancelled: AbortSignal,\n send: SendUpdate,\n): Promise<void> {\n const state = create_acp_mapper_state({ stream: config.stream, session: record.session })\n const to_updates = config.to_updates ?? to_session_updates\n for await (const event of events) {\n if (event.kind === 'events_dropped') warn_dropped(event)\n const updates = to_updates(event, state)\n for (const update of updates) {\n if (cancelled.aborted) return\n await send(update)\n }\n record.cards.sent(event, updates)\n }\n}\n\n/**\n * Run the flow for one turn, forward its updates, and record the exchange.\n * The run has always settled by the time this returns or throws, so a turn\n * never leaves a run behind.\n */\nasync function run_turn<i, o>(\n config: ServeAcpConfig<i, o>,\n record: SessionRecord<i, o>,\n prompt: ReadonlyArray<ContentBlock>,\n cancelled: AbortSignal,\n send: SendUpdate,\n): Promise<PromptResponse> {\n const turn: AcpTurn = {\n session_id: record.session.id,\n cwd: record.session.cwd,\n text: turn_text(prompt),\n prompt,\n history: [...record.history],\n }\n const reply: Reply = { sent: false, text: '', card_since_text: false }\n const send_update: SendUpdate = async (update) => {\n await send(update)\n note_reply(reply, update)\n }\n const stop = new AbortController()\n // A turn cancelled before its consumer caught up leaves previews nobody\n // took, and raw ids repeat from turn to turn.\n reset_previews(record.session)\n const handle = run.stream(record.flow, turn_input(config, turn), {\n abort: AbortSignal.any([cancelled, stop.signal]),\n install_signal_handlers: false,\n // Every event the run queues for the consumer passes through here first,\n // which is how an approval knows what the client hasn't been sent yet.\n trajectory: record.cards.start(config.trajectory),\n })\n const outcome = settle(handle.result)\n try {\n await forward(handle.events, config, record, cancelled, send_update)\n const result = await outcome\n if (!cancelled.aborted) {\n if (!result.ok) throw result.error\n const final_text = (config.to_text ?? default_to_text)(result.output)\n if (!reply.sent && final_text !== '') await send_update(agent_message(final_text))\n }\n } catch (err: unknown) {\n stop.abort(new aborted_error('the prompt turn failed before its run finished'))\n await outcome\n if (!cancelled.aborted) throw err\n }\n record_exchange(record.history, turn.text, reply.text, cancelled.aborted)\n return { stopReason: cancelled.aborted ? 'cancelled' : 'end_turn' }\n}\n\n/**\n * Run one prompt turn and answer with its stop reason. A new prompt cancels\n * the session's turn in flight and waits for it to settle first, so it sees\n * that turn in its history and never runs beside it.\n */\nexport async function prompt_turn<i, o>(\n config: ServeAcpConfig<i, o>,\n record: SessionRecord<i, o>,\n prompt: ReadonlyArray<ContentBlock>,\n request_signal: AbortSignal,\n send: SendUpdate,\n): Promise<PromptResponse> {\n const previous = record.last_turn\n const cancel = new AbortController()\n const { promise: settled, resolve: settle_turn } = Promise.withResolvers<void>()\n record.last_turn = { cancel, settled }\n try {\n if (previous !== null) {\n previous.cancel.abort(new aborted_error('a new prompt replaced the turn'))\n await previous.settled\n }\n const signals = [cancel.signal, request_signal, ...(config.abort === undefined ? [] : [config.abort])]\n return await run_turn(config, record, prompt, AbortSignal.any(signals), send)\n } finally {\n settle_turn()\n }\n}\n\n/**\n * Cancel the session's latest turn on the client's `session/cancel`.\n */\nexport function cancel_turn<i, o>(record: SessionRecord<i, o>): void {\n record.last_turn?.cancel.abort(new aborted_error('the ACP client cancelled the turn'))\n}\n","/**\n * Typed errors for the ACP adapter.\n *\n * Listed alongside src/mcp/errors.ts in the `no-class` rule ignores:\n * `instanceof` branching is how callers tell a missing optional peer apart\n * from a failure inside a prompt turn.\n */\n\nexport class acp_sdk_missing_error extends Error {\n readonly kind = 'acp_sdk_missing_error' as const;\n constructor(\n message = '@agentclientprotocol/sdk is required for fascicle/acp; install it with its zod peer: pnpm add @agentclientprotocol/sdk zod',\n ) {\n super(message)\n this.name = 'acp_sdk_missing_error'\n }\n}\n","/**\n * Lazy loader for the optional `@agentclientprotocol/sdk` peer.\n *\n * The adapter needs SDK values (the `agent()` builder, `ndJsonStream`,\n * `RequestError`), so it imports the SDK dynamically rather than statically:\n * a consumer can import `fascicle/acp` without the SDK installed and only pays\n * for it when they serve a flow. A missing peer surfaces as a typed\n * `acp_sdk_missing_error` with install guidance, mirroring\n * src/mcp/sdk_loader.ts.\n *\n * The package root is the SDK's stable protocol v1 entry; v2 sits under its\n * `experimental/` subpaths, which fascicle never imports. The SDK imports\n * `zod/v4` at runtime as its own peer, so a missing zod fails here too, and\n * the error names both installs.\n */\n\nimport { acp_sdk_missing_error } from './errors.js'\n\n/**\n * Dynamically imports the `@agentclientprotocol/sdk` v1 entry, throwing a\n * typed `acp_sdk_missing_error` when the optional peer (or its zod peer) is\n * not installed.\n */\nexport async function load_acp_sdk() {\n try {\n return await import('@agentclientprotocol/sdk')\n } catch (err: unknown) {\n const detail = err instanceof Error ? err.message : String(err)\n throw new acp_sdk_missing_error(\n `@agentclientprotocol/sdk is required for fascicle/acp; install it with its zod peer: pnpm add @agentclientprotocol/sdk zod (cause: ${detail})`,\n )\n }\n}\n","/**\n * acp_agent: the ACP agent app that answers each prompt turn by running a\n * flow.\n *\n * It registers the protocol v1 handlers and holds the sessions, and connects\n * to anything the SDK can: `serve_acp`'s stdio streams, or an in-process\n * `client()` in a test. It doesn't own the process, so it leaves the console\n * and the engine alone; `serve_acp` handles both.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { AgentApp, AgentContext, ClientCapabilities, SessionUpdate } from '@agentclientprotocol/sdk'\nimport { create_card_sync, message_of, session_approver } from './approve.js'\nimport type { PermissionAsker } from './approve.js'\nimport {\n config_options,\n DEFAULT_MODE,\n is_acp_mode,\n MODE_CONFIG_ID,\n mode_state,\n session_modes,\n unknown_mode_message,\n} from './modes.js'\nimport type { SessionModes } from './modes.js'\nimport { cancel_turn, prompt_turn } from './prompt_turn.js'\nimport type { SessionRecord } from './prompt_turn.js'\nimport { load_acp_sdk } from './sdk_loader.js'\nimport { resolve_roots } from './tools/containment.js'\nimport type { AcpMode, AcpSession, ServeAcpConfig } from './types.js'\n\ntype AcpSdk = Awaited<ReturnType<typeof load_acp_sdk>>\n\n/** A session as the agent holds it: what a turn needs, and its mode. */\ntype AgentSession<i, o> = SessionRecord<i, o> & { readonly modes: SessionModes }\n\nconst ONE_CONNECTION =\n 'acp_agent: this app already serves a connection; build an app for each connection, as serve_acp does'\n\n/**\n * Turn a failure inside a handler into a JSON-RPC error that carries its\n * message. The SDK reports a plain thrown `Error` as a bare \"Internal error\",\n * which tells the user in the client nothing about what went wrong.\n */\nfunction internal_error(sdk: AcpSdk, err: unknown): Error {\n return sdk.RequestError.internalError(undefined, message_of(err))\n}\n\n/**\n * A function that sends one update to the client for one session.\n */\nfunction sender(sdk: AcpSdk, client: AgentContext, sessionId: string): (update: SessionUpdate) => Promise<void> {\n return (update) => client.notify(sdk.methods.client.session.update, { sessionId, update })\n}\n\n/**\n * A function that asks the client to approve one tool call. The SDK\n * withdraws the request with `$/cancel_request` once `cancel` fires, which\n * is the turn's abort, so a cancelled turn takes its prompt down with it.\n */\nfunction permission_asker(sdk: AcpSdk, client: AgentContext): PermissionAsker {\n return (request, cancel) =>\n client.request(sdk.methods.client.session.requestPermission, request, { cancellationSignal: cancel })\n}\n\n/**\n * The mode a client asked for, or an invalid-params error naming the modes\n * there are. `field` is the param the id arrived in, for the error's data.\n */\nfunction requested_mode(sdk: AcpSdk, id: unknown, field: 'modeId' | 'value'): AcpMode {\n if (is_acp_mode(id)) return id\n throw sdk.RequestError.invalidParams({ [field]: id }, unknown_mode_message(id))\n}\n\n/**\n * Build the ACP agent app that answers each prompt turn by running the\n * config's flow, with its handlers registered and not yet connected.\n *\n * An app serves one connection for its life, since its sessions and the\n * client's capabilities aren't scoped to a connection. A second `connect`\n * throws, and so, for a server that routes a second client to the same app\n * and runs `initialize` before any connect hook, does a second `initialize`,\n * before it can overwrite the first client's capabilities.\n */\nexport async function acp_agent<i, o>(config: ServeAcpConfig<i, o>): Promise<AgentApp> {\n const sdk = await load_acp_sdk()\n const sessions = new Map<string, AgentSession<i, o>>()\n let client_capabilities: ClientCapabilities = {}\n let connected = false\n let initialized = false\n const session_of = (sessionId: string): AgentSession<i, o> => {\n const record = sessions.get(sessionId)\n if (record !== undefined) return record\n throw sdk.RequestError.invalidParams({ sessionId }, `unknown session ${sessionId}; start one with session/new first`)\n }\n return sdk\n .agent()\n .onConnect(() => {\n if (connected) throw new Error(ONE_CONNECTION)\n connected = true\n })\n .onRequest('initialize', (ctx) => {\n if (initialized) throw sdk.RequestError.invalidRequest(undefined, ONE_CONNECTION)\n initialized = true\n client_capabilities = ctx.params.clientCapabilities ?? {}\n return {\n protocolVersion: sdk.PROTOCOL_VERSION,\n agentInfo: { name: config.name, version: config.version ?? '0.0.0' },\n // Embedded context lets a file the user @-mentions arrive with its\n // text, rather than as a bare URI the flow has no way to read.\n // Additional directories let a client widen the workspace past `cwd`.\n agentCapabilities: {\n loadSession: false,\n promptCapabilities: { embeddedContext: true },\n sessionCapabilities: { additionalDirectories: {} },\n },\n // Providers authenticate with what the launched process can see;\n // ACP v1 gives the client no way to hand the agent credentials.\n authMethods: [],\n }\n })\n .onRequest(\n 'authenticate',\n // Stryker disable next-line ArrowFunction: the SDK answers an authenticate handler's undefined with {}, so both read the same on the wire.\n () => ({}),\n )\n .onRequest('session/new', async (ctx) => {\n // `mcpServers` is accepted and ignored until a flow can be handed them.\n const { cwd, additionalDirectories: additional_directories = [] } = ctx.params\n // The roots resolve once, here, so every containment check compares\n // against the same real paths for the life of the session.\n const roots = await resolve_roots([cwd, ...additional_directories]).catch((err: unknown) => {\n throw sdk.RequestError.invalidParams({ cwd, additionalDirectories: additional_directories }, message_of(err))\n })\n const id = randomUUID()\n const modes = session_modes(config.default_mode ?? DEFAULT_MODE, sender(sdk, ctx.client, id))\n const cards = create_card_sync()\n const approver = session_approver({ modes, cards, ask: permission_asker(sdk, ctx.client) })\n const session: AcpSession = {\n id,\n cwd,\n additional_directories,\n roots,\n client_capabilities,\n mode: modes.current,\n approve: (request) => approver(session, request),\n }\n try {\n const flow = typeof config.flow === 'function' ? config.flow(session) : config.flow\n sessions.set(id, { session, flow, history: [], cards, last_turn: null, modes })\n } catch (err: unknown) {\n throw internal_error(sdk, err)\n }\n return { sessionId: id, modes: mode_state(modes.current()), configOptions: config_options(modes.current()) }\n })\n .onRequest('session/prompt', async (ctx) => {\n const { sessionId, prompt } = ctx.params\n const record = session_of(sessionId)\n try {\n return await prompt_turn(config, record, prompt, ctx.signal, sender(sdk, ctx.client, sessionId))\n } catch (err: unknown) {\n throw internal_error(sdk, err)\n }\n })\n .onRequest('session/set_mode', async (ctx) => {\n const { sessionId, modeId } = ctx.params\n const { modes } = session_of(sessionId)\n await modes.switch_to(requested_mode(sdk, modeId, 'modeId'))\n return {}\n })\n .onRequest('session/set_config_option', async (ctx) => {\n const { sessionId, configId, value } = ctx.params\n const { modes } = session_of(sessionId)\n if (configId !== MODE_CONFIG_ID) {\n throw sdk.RequestError.invalidParams(\n { configId },\n `unknown config option ${configId}; the only one is ${MODE_CONFIG_ID}`,\n )\n }\n await modes.switch_to(requested_mode(sdk, value, 'value'))\n return { configOptions: config_options(modes.current()) }\n })\n .onNotification('session/cancel', (ctx) => {\n const record = sessions.get(ctx.params.sessionId)\n if (record !== undefined) cancel_turn(record)\n })\n}\n","/**\n * The ACP agent's serving loop, minus the process.\n *\n * `serve_streams` is everything `serve_acp` does once the console and the\n * signals are handled: connect `acp_agent` to a pair of ndjson byte streams,\n * hold the connection until the client hangs up or `shutdown` fires, then\n * dispose the engine. It takes its streams as arguments, mirroring\n * `execute_stdio` under `run_stdio`, so the disconnect path is unit-tested\n * here and the thin glue in `serve_acp.ts` owns the real stdin and stdout.\n *\n * Closing the connection is what aborts the runs: the SDK aborts every\n * in-flight request's signal as it closes, and each prompt turn's run\n * listens on its request's signal. So by the time `closed` resolves, every\n * active run has seen its abort, and only then is the engine disposed.\n */\n\nimport { acp_agent } from './acp_agent.js'\nimport { load_acp_sdk } from './sdk_loader.js'\nimport type { ServeAcpConfig } from './types.js'\n\ntype AcpServeIo = {\n /** What the client sends, as ndjson bytes; stdin under `serve_acp`. */\n readonly input: ReadableStream<Uint8Array>\n /** Where the protocol goes, as ndjson bytes; stdout under `serve_acp`. */\n readonly output: WritableStream<Uint8Array>\n /** Ends the connection from the agent's side, aborting every active run with its reason. */\n readonly shutdown?: AbortSignal | undefined\n}\n\n/**\n * Serve the config's flow as an ACP agent over `io` until the client\n * disconnects or `io.shutdown` fires, then dispose the engine once every\n * active run has been aborted.\n */\nexport async function serve_streams<i, o>(config: ServeAcpConfig<i, o>, io: AcpServeIo): Promise<void> {\n const sdk = await load_acp_sdk()\n const app = await acp_agent(config)\n const connection = app.connect(sdk.ndJsonStream(io.output, io.input))\n const { shutdown } = io\n if (shutdown !== undefined) {\n // A signal can land while the SDK loads, before there is a listener to hear it.\n if (shutdown.aborted) connection.close(shutdown.reason)\n else shutdown.addEventListener('abort', () => connection.close(shutdown.reason))\n }\n await connection.closed\n await config.engine?.dispose()\n}\n","/**\n * Process glue for serving a flow as an ACP agent over stdio.\n *\n * Binds `serve_streams` to the real process: ndjson in on stdin, the\n * protocol out on stdout, and nothing else on stdout ever. A stray log line\n * from a flow or a dependency would corrupt the protocol stream, so\n * `console.log`, `console.info`, `console.debug`, `console.dir`, and\n * `console.dirxml` go to stderr for the life of the process.\n *\n * SIGTERM and SIGINT abort every active run, dispose the engine, and exit.\n * A host that ends the agent with a signal instead of closing stdin would\n * otherwise leave a run's work going after the editor has closed, since each\n * turn runs with the runner's own signal handlers off. The handlers are\n * one-shot, so a second Ctrl-C falls through to Node's default and kills the\n * process outright when a shutdown hangs.\n *\n * Excluded from mutation testing as process glue (see stryker.config.mjs);\n * the spawn tests in `__tests__/e2e/` exercise it for real.\n */\n\nimport { constants } from 'node:os'\nimport { Readable, Writable } from 'node:stream'\nimport { aborted_error } from '#core'\nimport { route_console_to_stderr } from '#process'\nimport { serve_streams } from './serve_streams.js'\nimport type { ServeAcpConfig } from './types.js'\n\n/**\n * Serve a flow as an ACP agent over stdin and stdout until the client\n * disconnects, disposing the engine once every active run has been aborted.\n * A SIGTERM or SIGINT does the same, then exits with the signal's code.\n */\nexport async function serve_acp<i, o>(config: ServeAcpConfig<i, o>): Promise<void> {\n // Leave stdout to the protocol alone.\n route_console_to_stderr(console, process.stderr)\n const shutdown = new AbortController()\n let received: NodeJS.Signals | null = null\n const on_signal = (signal: NodeJS.Signals): void => {\n received = signal\n shutdown.abort(new aborted_error(`received ${signal}`, { reason: { signal } }))\n }\n process.once('SIGTERM', on_signal)\n process.once('SIGINT', on_signal)\n try {\n await serve_streams(config, {\n input: Readable.toWeb(process.stdin),\n output: Writable.toWeb(process.stdout),\n shutdown: shutdown.signal,\n })\n } finally {\n process.off('SIGTERM', on_signal)\n process.off('SIGINT', on_signal)\n }\n // Exiting here rather than draining tells the host a signal ended the\n // agent, and leaves no wait on a flow that ignored its abort.\n if (received !== null) process.exit(128 + constants.signals[received])\n}\n"],"mappings":";;;;;;;;;;;;;;AAuBA,MAAa,iBAAiB;;AAY9B,MAAM,QAA8C;CAClD,QAAQ;EACN,MAAM;EACN,aAAa;EACb,MAAM;GAAE,MAAM;GAAM,SAAS;EAAK;CACpC;CACA,cAAc;EACZ,MAAM;EACN,aAAa;EACb,MAAM;GAAE,MAAM;GAAO,SAAS;EAAK;CACrC;CACA,MAAM;EACJ,MAAM;EACN,aAAa;EACb,MAAM;GAAE,MAAM;GAAO,SAAS;EAAM;CACtC;AACF;;;;;AAMA,SAAgB,YAAY,IAA4B;CACtD,OAAO,OAAO,OAAO,YAAY,OAAO,OAAO,OAAO,EAAE;AAC1D;;;;AAKA,SAAgB,qBAAqB,IAAqB;CACxD,OAAO,gBAAgB,KAAK,UAAU,EAAE,EAAE,kBAAkB,OAAO,KAAK,KAAK,CAAC,CAAC,KAAK,IAAI;AAC1F;;;;AAKA,SAAgB,YAAY,MAAe,QAA8B;CACvE,OAAO,MAAM,KAAK,CAAC,KAAK;AAC1B;;;;AAKA,SAAS,kBAAiC;CACxC,OAAO,OAAO,QAAQ,KAAK,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,MAAM,oBAAoB;EAAE;EA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W,MAAM,SAAS,MAAM,CAAC;CACjF;CACA,MAAM,WAAW;CACjB,MAAM,OAAO,QAAQ,QAAQ;AAC/B;;;;;;;;;;;;;;;;;;;;;;;;;;;ACdA,eAAsB,UAAgB,QAA6C;CAEjF,wBAAwB,SAAS,QAAQ,MAAM;CAC/C,MAAM,WAAW,IAAI,gBAAgB;CACrC,IAAI,WAAkC;CACtC,MAAM,aAAa,WAAiC;EAClD,WAAW;EACX,SAAS,MAAM,IAAI,cAAc,YAAY,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC;CAChF;CACA,QAAQ,KAAK,WAAW,SAAS;CACjC,QAAQ,KAAK,UAAU,SAAS;CAChC,IAAI;EACF,MAAM,cAAc,QAAQ;GAC1B,OAAO,SAAS,MAAM,QAAQ,KAAK;GACnC,QAAQ,SAAS,MAAM,QAAQ,MAAM;GACrC,UAAU,SAAS;EACrB,CAAC;CACH,UAAU;EACR,QAAQ,IAAI,WAAW,SAAS;EAChC,QAAQ,IAAI,UAAU,SAAS;CACjC;CAGA,IAAI,aAAa,MAAM,QAAQ,KAAK,MAAM,UAAU,QAAQ,SAAS;AACvE"}
|
|
1
|
+
{"version":3,"file":"acp.js","names":[],"sources":["../src/acp/modes.ts","../src/acp/tools/previews.ts","../src/acp/tools/write_file.ts","../src/acp/tools/edit_file.ts","../src/acp/tools/run_command.ts","../src/acp/workspace_tools.ts","../src/acp/presentation.ts","../src/acp/approve.ts","../src/acp/to_session_updates.ts","../src/acp/prompt_turn.ts","../src/acp/errors.ts","../src/acp/sdk_loader.ts","../src/acp/acp_agent.ts","../src/acp/serve_streams.ts","../src/acp/serve_acp.ts"],"sourcesContent":["/**\n * modes: the three ways a coding session runs, and when each asks the\n * client before a workspace tool acts.\n *\n * Reads and searches never ask. Manual asks before every edit and every\n * command, Accept edits only before a command, and Auto never asks. That is\n * the contract Claude Agent set and Zed's mode picker presents. Auto runs\n * commands with nobody watching, so it belongs in a container or a\n * throwaway worktree, and an agent that runs anywhere else leaves it out\n * with `ServeAcpConfig.modes`.\n *\n * ACP reports a session's mode two ways, as `modes` and as a config option\n * in the `mode` category, and a client reads one or the other. Both come\n * from the one table here and the one `ModeOffer` an agent builds from its\n * config, and every change sends both updates, so the two can't disagree in\n * front of the user.\n */\n\nimport type { SessionConfigOption, SessionModeState, SessionUpdate } from '@agentclientprotocol/sdk'\nimport type { AcpMode } from './types.js'\n\n/** The id of the config option that carries the mode, the only option this agent has. */\nexport const MODE_CONFIG_ID = 'mode'\n\n/** What a workspace tool does that a mode may want to ask about first. */\nexport type GatedAction = 'edit' | 'command'\n\ntype ModeEntry = {\n readonly name: string\n readonly description: string\n readonly asks: Readonly<Record<GatedAction, boolean>>\n}\n\n/** Every mode, in the order a client lists them. */\nconst MODES: Readonly<Record<AcpMode, ModeEntry>> = {\n manual: {\n name: 'Manual',\n description: 'Ask before every edit and every command',\n asks: { edit: true, command: true },\n },\n accept_edits: {\n name: 'Accept edits',\n description: 'Edit files without asking, and ask before every command',\n asks: { edit: false, command: true },\n },\n auto: {\n name: 'Auto',\n description: 'Edit files and run commands without asking, for a container or a throwaway worktree',\n asks: { edit: false, command: false },\n },\n}\n\n/**\n * Whether `id` names one of the modes. An own-key check, so an id such as\n * `toString` that every object answers to isn't taken for one.\n */\nexport function is_acp_mode(id: unknown): id is AcpMode {\n return typeof id === 'string' && Object.hasOwn(MODES, id)\n}\n\n/**\n * The modes an agent offers, in the table's order and each once, and the\n * mode each of its sessions starts in. `acp_agent` builds one from its\n * config, and every list, check, and start mode reads it.\n */\nexport type ModeOffer = {\n readonly modes: ReadonlyArray<AcpMode>\n readonly default_mode: AcpMode\n}\n\n/** Every mode's id, as the refusals list them. */\nconst MODE_NAMES = Object.keys(MODES).join(', ')\n\n/**\n * The modes an agent offers and where its sessions start, from the config's\n * `modes` (default: all three) and `default_mode` (default: the first mode\n * offered). Throws an `Error` that names the problem for an empty `modes`,\n * an entry that isn't a mode, or a `default_mode` the agent doesn't offer,\n * so `acp_agent` fails as it's built rather than at every `session/new`.\n */\nexport function mode_offer(config: {\n readonly modes?: ReadonlyArray<AcpMode> | undefined\n readonly default_mode?: AcpMode | undefined\n}): ModeOffer {\n // A caller with no types can pass anything, so each entry is checked as unknown.\n const listed: ReadonlyArray<unknown> = config.modes ?? Object.keys(MODES)\n if (listed.length === 0) {\n throw new Error(\n `acp_agent: modes is empty; list at least one of ${MODE_NAMES}, or leave modes out to offer all three`,\n )\n }\n for (const entry of listed) {\n if (!is_acp_mode(entry)) {\n throw new Error(`acp_agent: modes lists ${JSON.stringify(entry)}, which isn't a mode; use one of ${MODE_NAMES}`)\n }\n }\n const modes = Object.keys(MODES).filter((id): id is AcpMode => listed.includes(id))\n const wanted = config.default_mode ?? modes[0]\n const default_mode = modes.find((mode) => mode === wanted)\n if (default_mode === undefined) {\n throw new Error(\n `acp_agent: default_mode ${JSON.stringify(config.default_mode)} isn't one of the modes this agent offers (${modes.join(', ')}); add it to modes or leave default_mode out`,\n )\n }\n return { modes, default_mode }\n}\n\n/**\n * The refusal for a mode id the agent doesn't offer, naming the ones it does.\n */\nexport function unknown_mode_message(id: unknown, offer: ModeOffer): string {\n return `unknown mode ${JSON.stringify(id)}; choose one of ${offer.modes.join(', ')}`\n}\n\n/**\n * Whether a session in `mode` asks the client before a tool does `action`.\n */\nexport function asks_before(mode: AcpMode, action: GatedAction): boolean {\n return MODES[mode].asks[action]\n}\n\n/** A mode as ACP lists one: its id, its name, and what it asks. */\ntype ListedMode = { readonly id: AcpMode; readonly name: string; readonly description: string }\n\n/**\n * Every mode the agent offers as ACP lists one, in the table's order.\n */\nfunction available_modes(offer: ModeOffer): ListedMode[] {\n return offer.modes.map((id) => ({ id, name: MODES[id].name, description: MODES[id].description }))\n}\n\n/**\n * The session's modes as `session/new` reports them in `modes`.\n */\nexport function mode_state(offer: ModeOffer, mode: AcpMode): SessionModeState {\n return { currentModeId: mode, availableModes: available_modes(offer) }\n}\n\n/**\n * The session's config options, the mode as a select being the only one, as\n * `session/new` and `session/set_config_option` report them.\n */\nexport function config_options(offer: ModeOffer, mode: AcpMode): SessionConfigOption[] {\n return [\n {\n id: MODE_CONFIG_ID,\n name: 'Mode',\n description: 'When the agent asks before it edits a file or runs a command',\n category: 'mode',\n type: 'select',\n currentValue: mode,\n options: available_modes(offer).map(({ id, name, description }) => ({ value: id, name, description })),\n },\n ]\n}\n\n/**\n * A session's mode as the agent holds it: what it is now, whether the agent\n * offers a mode, and the one way to change it, which tells the client both\n * ways it may be reading it.\n */\nexport type SessionModes = {\n readonly current: () => AcpMode\n readonly offers: (mode: unknown) => mode is AcpMode\n readonly switch_to: (mode: AcpMode) => Promise<void>\n}\n\n/**\n * Hold a session's mode, starting at the offer's `default_mode`. A switch\n * takes effect before the client hears of it, so a tool call that asks after\n * the switch reads the new mode, and the two updates go out in order through\n * `send`.\n */\nexport function session_modes(offer: ModeOffer, send: (update: SessionUpdate) => Promise<void>): SessionModes {\n let mode = offer.default_mode\n const offered: ReadonlyArray<unknown> = offer.modes\n return {\n current: () => mode,\n offers: (candidate): candidate is AcpMode => offered.includes(candidate),\n switch_to: async (next) => {\n mode = next\n await send({ sessionUpdate: 'current_mode_update', currentModeId: next })\n await send({ sessionUpdate: 'config_option_update', configOptions: config_options(offer, next) })\n },\n }\n}\n","/**\n * The preview store: what each workspace tool call changed or ran, kept for\n * the client's card that shows it.\n *\n * A write's card shows its diff and a command's shows its output and exit\n * code, but the model reads back a single line, so the call's result can't\n * carry them. Each tool leaves its call's preview here once the call\n * succeeds, under the engine's raw call id, and `to_session_updates` takes\n * it when that call's result arrives. The file reads behind a diff happen\n * in the tool, before it writes, so the mapper itself stays free of I/O.\n *\n * Raw ids repeat across model calls (Ollama numbers its calls afresh on\n * each one), and the turn's consumer can fall behind the engine, so each id\n * holds a queue, taken oldest first. The engine runs a turn's calls one\n * after another, which keeps each queue in the order its results arrive.\n * Only a call that succeeded leaves a preview, and only a successful result\n * takes one, so a call refused before it ran can't take a later call's.\n *\n * The store belongs to the session and is keyed by the session object, so\n * `AcpSession` carries nothing for it. Each turn starts it empty, so what a\n * cancelled turn left behind never reaches the next.\n */\n\nimport type { AcpSession } from '../types.js'\n\n/**\n * A file change that landed: the path in the client's terms, the text\n * before (`null` for a new file) and after, and for an edit, the line where\n * its first match starts, counting from 1 (a write has none).\n */\nexport type ChangePreview = {\n readonly kind: 'change'\n readonly path: string\n readonly old_text: string | null\n readonly new_text: string\n readonly line: number | undefined\n}\n\n/**\n * A command that ran to its end: what it printed, and its exit code or the\n * signal that ended it.\n */\nexport type CommandPreview = {\n readonly kind: 'command'\n readonly output: string\n readonly exit_code: number | null\n readonly signal: string | null\n}\n\nexport type ToolPreview = ChangePreview | CommandPreview\n\nconst stores = new WeakMap<AcpSession, Map<string, ToolPreview[]>>()\n\n/**\n * The session's store, made empty the first time it's asked for.\n */\nfunction store_of(session: AcpSession): Map<string, ToolPreview[]> {\n const store = stores.get(session) ?? new Map<string, ToolPreview[]>()\n stores.set(session, store)\n return store\n}\n\n/**\n * Empty the session's store as a turn starts.\n */\nexport function reset_previews(session: AcpSession): void {\n stores.set(session, new Map())\n}\n\n/**\n * Leave a call's preview at the back of its raw id's queue.\n */\nexport function record_preview(session: AcpSession, tool_call_id: string, preview: ToolPreview): void {\n const store = store_of(session)\n store.set(tool_call_id, [...(store.get(tool_call_id) ?? []), preview])\n}\n\n/**\n * Take the oldest preview waiting under a raw id, or `undefined` when none\n * is.\n */\nexport function take_preview(session: AcpSession, tool_call_id: string): ToolPreview | undefined {\n return store_of(session).get(tool_call_id)?.shift()\n}\n","/**\n * write_file: create a text file in the workspace, or replace everything one\n * holds.\n *\n * Every write is worked out before it happens, as the file's whole text\n * before and after, so the client can be shown the change as a diff before\n * anything reaches the disk. `edit_file` builds its change from the same\n * pieces, so the two tools agree on what they refuse and how they write.\n *\n * A write lands at the path's real location, which `contain` placed inside a\n * root, and creates the directories it needs there, so a model writing\n * `src/new/thing.ts` doesn't need a command to make `src/new` first.\n */\n\nimport { isUtf8 } from 'node:buffer'\nimport { mkdir, open, stat, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\nimport type { Tool } from '#engine'\nimport { as_record, json_schema_to_standard } from '#schema'\nimport type { AcpSession } from '../types.js'\nimport { contain_writable, error_code, shown_path } from './containment.js'\nimport type { ContainedPath } from './containment.js'\nimport { record_preview } from './previews.js'\nimport { is_binary } from './read_file.js'\n\n/**\n * A write worked out before anything is written: the file both ways\n * `contain` names it, and its whole text before and after. `old_text` is\n * `null` only when the write creates the file.\n */\nexport type FileChange = ContainedPath & {\n readonly old_text: string | null\n readonly new_text: string\n}\n\n/** A file change as a card or a permission request shows it, with the line an edit lands on. */\nexport type ShownChange = FileChange & { readonly line?: number }\n\n/**\n * The largest file a change reads, in bytes. A change is shown as a diff,\n * which carries the file's whole text twice, as its text before and after,\n * and the closing card update carries it again.\n */\nconst CHANGE_LIMIT_BYTES = 1_000_000\n\n/** One write as the model asked for it. */\ntype WriteRequest = {\n readonly path: string\n readonly content: string\n}\n\n/**\n * Read the call's path and content out of its input.\n */\nfunction write_request(input: unknown): WriteRequest {\n const fields: Record<string, unknown> = as_record(input) ?? {}\n const { path, content } = fields\n if (typeof path !== 'string' || typeof content !== 'string') {\n throw new Error('write_file needs a path and the content to write, as strings')\n }\n return { path, content }\n}\n\n/**\n * The text a write would replace, or `null` when no file is there yet.\n * Anything but a regular UTF-8 text file is refused, because the change is\n * shown as a diff of text, and rewriting a file in another encoding would\n * change bytes outside the edit. A file with other hard links is refused too:\n * a write changes the file under every name it has, and real paths can't say\n * where the other names lie. A file over CHANGE_LIMIT_BYTES is refused from\n * its size, before it's opened. `shown` is the path as the model gave it,\n * and `tool` names the tool asking, for the refusals.\n */\nexport async function current_text(real: string, shown: string, tool: string): Promise<string | null> {\n const info = await stat(real).catch((err: unknown) => {\n if (error_code(err) === 'ENOENT') return undefined\n throw err\n })\n if (info === undefined) return null\n if (info.isDirectory()) throw new Error(`${shown} is a directory; ${tool} changes a file, so name one inside it`)\n if (!info.isFile()) throw new Error(`${shown} isn't a regular file, so ${tool} can't change it`)\n if (info.nlink > 1) {\n throw new Error(\n `${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`,\n )\n }\n if (info.size > CHANGE_LIMIT_BYTES) {\n throw new Error(\n `${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`,\n )\n }\n const handle = await open(real)\n try {\n if (await is_binary(handle)) {\n throw new Error(`${shown} is a binary file (it has a NUL byte in its first 8 KB), so ${tool} won't change it`)\n }\n // The binary check reads at an explicit position, which leaves the\n // handle's own position at the top, where readFile starts.\n const bytes = await handle.readFile()\n if (!isUtf8(bytes)) throw new Error(`${shown} isn't UTF-8 text, so ${tool} won't change it`)\n return bytes.toString('utf8')\n } finally {\n await handle.close()\n }\n}\n\n/**\n * Write a change's new text where it lands, creating the directories it\n * needs first. A turn cancelled while the change was worked out stops here,\n * before anything is written. A new file is created exclusively, so a file or\n * a symlink that appeared at its path since then stops the write instead of\n * taking it.\n */\nexport async function apply_change(change: FileChange, abort: AbortSignal): Promise<void> {\n abort.throwIfAborted()\n await mkdir(dirname(change.real), { recursive: true })\n await writeFile(change.real, change.new_text, change.old_text === null ? { flag: 'wx' } : {})\n}\n\n/**\n * Leave a change that landed in the session's preview store, for the card\n * of the call that made it to show as a diff.\n */\nexport function record_change(\n session: AcpSession,\n tool_call_id: string,\n change: ShownChange,\n): void {\n record_preview(session, tool_call_id, {\n kind: 'change',\n path: change.path,\n old_text: change.old_text,\n new_text: change.new_text,\n line: change.line,\n })\n}\n\n/**\n * The change a `write_file` call would make, worked out without writing: its\n * path checked against the session's roots and kept out of `.git` and\n * `node_modules`, the text it would replace, and the content that replaces\n * it.\n */\nexport async function write_file_change(session: AcpSession, input: unknown): Promise<FileChange> {\n const request = write_request(input)\n const target = await contain_writable(session, request.path, 'write_file')\n const old_text = await current_text(target.real, request.path, 'write_file')\n return { ...target, old_text, new_text: request.content }\n}\n\n/**\n * The `write_file` tool for one session: a file inside its workspace,\n * created or replaced whole. The model reads back a line saying which, since\n * it already has the text it sent.\n */\nexport function write_file_tool(session: AcpSession): Tool {\n return {\n name: 'write_file',\n description:\n 'Write a text file in the workspace: create it, along with any directories it needs, or replace everything it holds. ' +\n \"content is the file's whole text; to change part of a file, use edit_file. \" +\n 'The path is absolute or relative to the workspace root.',\n input_schema: json_schema_to_standard({\n type: 'object',\n properties: {\n path: { type: 'string', description: 'The file to write, absolute or relative to the workspace root' },\n content: { type: 'string', description: \"The file's whole text\" },\n },\n required: ['path', 'content'],\n additionalProperties: false,\n }),\n execute: async (input, ctx) => {\n const change = await write_file_change(session, input)\n await apply_change(change, ctx.abort)\n record_change(session, ctx.tool_call_id, change)\n return `${change.old_text === null ? 'created' : 'overwrote'} ${shown_path(session, change.path)}`\n },\n }\n}\n","/**\n * edit_file: replace an exact match in a text file in the workspace.\n *\n * The match has to be exact and, unless the call sets `replace_all`, the only\n * one, so the model names enough of the file to say which place it means. A\n * looser match could change a place it never looked at. The change is worked\n * out first, the way `write_file`'s is, as the whole file before and after,\n * with the line where the first match starts for the client to point at.\n */\n\nimport type { Tool } from '#engine'\nimport { as_record, json_schema_to_standard } from '#schema'\nimport type { AcpSession } from '../types.js'\nimport { contain_writable, shown_path } from './containment.js'\nimport { apply_change, current_text, record_change } from './write_file.js'\nimport type { FileChange } from './write_file.js'\n\n/**\n * A change `edit_file` would make. The file exists, so `old_text` is always\n * its text. `line` is where the first match starts, counting from 1, and\n * `matches` is how many places the edit replaces.\n */\nexport type EditChange = FileChange & {\n readonly old_text: string\n readonly line: number\n readonly matches: number\n}\n\n/** One edit as the model asked for it. */\ntype EditRequest = {\n readonly path: string\n readonly old_text: string\n readonly new_text: string\n readonly replace_all: boolean\n}\n\n/**\n * Read the call's path, texts, and `replace_all` out of its input, refusing\n * an `old_text` that's empty, which matches everywhere, or the same as\n * `new_text`, which changes nothing.\n */\nfunction edit_request(input: unknown): EditRequest {\n const fields: Record<string, unknown> = as_record(input) ?? {}\n const { path, old_text, new_text, replace_all = false } = fields\n if (\n typeof path !== 'string' ||\n typeof old_text !== 'string' ||\n typeof new_text !== 'string' ||\n typeof replace_all !== 'boolean'\n ) {\n throw new Error('edit_file needs path, old_text, and new_text as strings, and takes replace_all as true or false')\n }\n if (old_text === '') throw new Error(\"old_text is empty, so there's nothing to find; write_file writes a whole file\")\n if (old_text === new_text) throw new Error('old_text and new_text are the same, so the edit would change nothing')\n return { path, old_text, new_text, replace_all }\n}\n\n/**\n * The change an `edit_file` call would make, worked out without writing: the\n * file's whole text before, and after `old_text` is replaced. It fails on a\n * path that `contain_writable` refuses, when `old_text` isn't there, or when\n * it's there more than once and the call doesn't set `replace_all`.\n */\nexport async function edit_file_change(session: AcpSession, input: unknown): Promise<EditChange> {\n const request = edit_request(input)\n const target = await contain_writable(session, request.path, 'edit_file')\n const text = await current_text(target.real, request.path, 'edit_file')\n if (text === null) throw new Error(`${request.path} doesn't exist; write_file creates a file`)\n // Splitting on the match, where String.replace would read its replacement\n // as a pattern, keeps a `$&` or `$$` in new_text as the model wrote it.\n const pieces = text.split(request.old_text)\n const matches = pieces.length - 1\n if (matches === 0) {\n throw new Error(\n `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`,\n )\n }\n if (matches > 1 && !request.replace_all) {\n throw new Error(\n `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`,\n )\n }\n const before = text.slice(0, text.indexOf(request.old_text))\n return {\n ...target,\n old_text: text,\n new_text: pieces.join(request.new_text),\n line: before.split('\\n').length,\n matches,\n }\n}\n\n/**\n * The `edit_file` tool for one session: an exact match replaced in a file\n * inside its workspace. The model reads back where the edit landed rather\n * than the file again.\n */\nexport function edit_file_tool(session: AcpSession): Tool {\n return {\n name: 'edit_file',\n description:\n 'Edit a text file in the workspace by replacing old_text with new_text. ' +\n 'old_text has to match the file exactly, whitespace and line breaks included, ' +\n 'and appear in it once, unless replace_all is set to replace every match. ' +\n 'Copy it from read_file without the line number and tab that read_file puts before each line. ' +\n 'The path is absolute or relative to the workspace root.',\n input_schema: json_schema_to_standard({\n type: 'object',\n properties: {\n path: { type: 'string', description: 'The file to edit, absolute or relative to the workspace root' },\n old_text: { type: 'string', minLength: 1, description: 'The exact text to replace' },\n new_text: { type: 'string', description: 'The text to put in its place' },\n replace_all: {\n type: 'boolean',\n description: 'Replace every match of old_text, rather than exactly one; default: false',\n },\n },\n required: ['path', 'old_text', 'new_text'],\n additionalProperties: false,\n }),\n execute: async (input, ctx) => {\n const change = await edit_file_change(session, input)\n await apply_change(change, ctx.abort)\n record_change(session, ctx.tool_call_id, change)\n const shown = shown_path(session, change.path)\n return change.matches === 1\n ? `edited ${shown} at line ${change.line}`\n : `edited ${shown} in ${change.matches} places, the first at line ${change.line}`\n },\n }\n}\n","/**\n * run_command: run a shell command in the workspace and hand back what it\n * printed and how it ended.\n *\n * The command is a string the model wrote in POSIX shell, so it runs as\n * `/bin/sh -c`, which behaves the same on every host and needs no read of\n * the user's `$SHELL`. Windows has neither that shell nor POSIX process\n * groups, so there the tool refuses and the file tools carry on.\n *\n * Each command leads a process group of its own, so the whole tree it starts\n * dies together: when the turn is cancelled, when it runs past its timeout,\n * and when the shell exits, which stops whatever it left running in the\n * background. Without that last kill, a job left behind would outlive the\n * call, and then the agent, since nothing would ever abort it. A command\n * that moves work into a group of its own (`set -m` in an interactive\n * shell, or a daemon that starts its own session) takes that work out of\n * reach, as it would from a terminal's Ctrl-C.\n *\n * The file tools' containment doesn't bind a command: the shell reaches\n * anything the user can.\n *\n * This is the one file in `src/acp/` that may import `node:child_process`\n * (rules/no-child-process-outside-run-command.yml).\n */\n\nimport { spawn } from 'node:child_process'\nimport type { ChildProcess } from 'node:child_process'\nimport { StringDecoder } from 'node:string_decoder'\nimport type { Tool } from '#engine'\nimport { as_record, json_schema_to_standard } from '#schema'\nimport type { AcpSession } from '../types.js'\nimport { record_preview } from './previews.js'\nimport type { CommandPreview } from './previews.js'\n\n/** The shell every command runs in. */\nconst SHELL = '/bin/sh'\n\n/**\n * The longest delay a Node timer keeps. A longer one fires after 1 ms\n * instead, so a longer timeout is held to this, about 24.8 days.\n */\nconst MAX_TIMER_MS = 2_147_483_647\n\n/**\n * How long the output may stay open once the shell has exited and its group\n * has been killed. The group's processes are gone by then, so only\n * something moved out of the group can be holding it, and that could hold\n * it for good.\n */\nconst OUTPUT_GRACE_MS = 1000\n\n/** How `run_command` runs one session's commands, from `workspace_tools`' options. */\nexport type CommandSettings = {\n /** How long a call may run, unless it sets its own `timeout_ms`. */\n readonly timeout_ms: number\n /** The most output a call returns, in bytes. */\n readonly output_limit_bytes: number\n /** The whole environment commands run with, or `undefined` to inherit the agent's. */\n readonly env: Readonly<Record<string, string>> | undefined\n}\n\n/** One command as the model asked for it. */\ntype CommandRequest = {\n readonly command: string\n readonly timeout_ms: number | undefined\n}\n\n/**\n * What a command printed, stdout and stderr together in the order they\n * arrived, up to `limit` bytes: the parts kept, the bytes they account\n * for, and every byte the command printed.\n */\ntype Capture = {\n readonly limit: number\n readonly parts: string[]\n kept: number\n total: number\n}\n\n/**\n * Whether a value counts milliseconds: a whole number of at least 1.\n */\nfunction is_millis(value: unknown): value is number {\n return Number.isInteger(value) && Number(value) >= 1\n}\n\n/**\n * Read the call's command and timeout out of its input. The tool loop has\n * already checked the types against the schema, but a flow that wraps the\n * tool can call `execute` directly, and the schema's `minimum` is advice to\n * the model rather than something the loop enforces.\n */\nfunction command_request(input: unknown): CommandRequest {\n const fields: Record<string, unknown> = as_record(input) ?? {}\n const { command, timeout_ms } = fields\n if (typeof command !== 'string') throw new Error('run_command needs a command, as a string')\n if (timeout_ms !== undefined && !is_millis(timeout_ms)) {\n throw new Error('run_command counts timeout_ms in milliseconds, so it has to be a whole number of at least 1')\n }\n return { command, timeout_ms }\n}\n\n/**\n * Keep a chunk of output while the capture has room, cutting the chunk that\n * crosses the limit, and count every byte either way. The output goes on\n * being read past the limit, since a command blocked on a full pipe would\n * never finish.\n */\nfunction take(capture: Capture, chunk: string): void {\n const size = Buffer.byteLength(chunk)\n const room = capture.limit - capture.kept\n capture.total += size\n // Stryker disable next-line ConditionalExpression,EqualityOperator: with no room left the cut below keeps an empty string and counts no bytes, so going on reads the same; the return only spares a copy of every chunk past the cap.\n if (room <= 0) return\n // A chunk that fits comes through whole. One cut at the limit can end\n // inside a character, whose partial bytes the decoder holds back.\n capture.parts.push(new StringDecoder().write(Buffer.from(chunk).subarray(0, room)))\n capture.kept += Math.min(size, room)\n}\n\n/**\n * What a command printed as the model reads it, without its trailing\n * whitespace, with a marker when it was cut, and a line saying so when it\n * printed nothing at all.\n */\nfunction printed(capture: Capture): string[] {\n if (capture.total === 0) return ['[no output]']\n const lines = [capture.parts.join('').trimEnd()]\n if (capture.total > capture.kept) {\n lines.push(\n `[output cut at ${capture.limit} bytes of ${capture.total}; pipe the command through tail, head, or grep to see the part you need]`,\n )\n }\n return lines.filter((line) => line !== '')\n}\n\n/**\n * How a finished command ended, as its report's last line: its exit code,\n * or the signal that ended it. Node sets exactly one of the two.\n */\nfunction ending(child: ChildProcess): string {\n return child.exitCode === null ? `[ended by ${String(child.signalCode)}]` : `[exit code ${child.exitCode}]`\n}\n\n/**\n * A command that ran to its end: what it printed, its process, and whether\n * something it moved out of its group held its output open.\n */\ntype Finished = {\n readonly capture: Capture\n readonly child: ChildProcess\n readonly held: boolean\n}\n\n/**\n * A finished command's report: what it printed, then how it ended, and a\n * note when something it moved out of its group held its output open and\n * was left running.\n */\nfunction report({ capture, child, held }: Finished): string {\n const lines = [...printed(capture), ending(child)]\n if (held) {\n lines.push(\n '[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]',\n )\n }\n return lines.join('\\n')\n}\n\n/**\n * A finished command as its card shows it: what it printed, with nothing in\n * place of an empty output, and its exit code or the signal that ended it.\n */\nfunction command_preview({ capture, child }: Finished): CommandPreview {\n return {\n kind: 'command',\n output: capture.total === 0 ? '' : printed(capture).join('\\n'),\n exit_code: child.exitCode,\n signal: child.signalCode,\n }\n}\n\n/**\n * The error a call that ran past its timeout fails with, carrying what the\n * command printed before it was killed.\n */\nfunction timeout_error(capture: Capture, timeout_ms: number): Error {\n return new Error(\n `the command didn't finish within ${timeout_ms / 1000} s, so run_command killed it and everything it started; ` +\n '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. ' +\n `What it printed before then:\\n${printed(capture).join('\\n')}`,\n )\n}\n\n/**\n * Kill a command's whole process group with SIGKILL, the one signal no\n * command can ignore. The turn's abort can be the agent's last act before\n * `serve_acp` exits, which leaves no later moment to follow a gentler\n * signal with this one.\n */\nfunction kill_group(child: ChildProcess): void {\n // Stryker disable next-line ConditionalExpression: without a pid, process.kill throws on the NaN it's handed, and the catch below takes that the same way.\n if (child.pid === undefined) return\n try {\n process.kill(-child.pid, 'SIGKILL')\n } catch {\n // The group is gone: every process in it has exited.\n }\n}\n\n/**\n * Run one command to its end in its own process group. A command that ends\n * on its own is a result, whatever its exit code; a timeout and a shell that\n * won't start are errors, and the turn's abort rejects with its reason. The\n * timeout and the abort kill the group, and the shell's exit kills whatever\n * it left behind. Each reads on to the end of the output, so what the\n * command printed last isn't lost, until the grace after the shell's exit\n * runs out. However the call ends, its timers and the abort listener go\n * with it.\n */\nasync function run_shell(\n request: CommandRequest,\n cwd: string,\n settings: CommandSettings,\n abort: AbortSignal,\n): Promise<Finished> {\n abort.throwIfAborted()\n const timeout_ms = request.timeout_ms ?? settings.timeout_ms\n const capture: Capture = { limit: settings.output_limit_bytes, parts: [], kept: 0, total: 0 }\n const child = spawn(SHELL, ['-c', request.command], {\n cwd,\n env: settings.env === undefined ? undefined : { ...settings.env },\n detached: true,\n stdio: ['ignore', 'pipe', 'pipe'],\n })\n const { promise, resolve, reject } = Promise.withResolvers<Finished>()\n let timed_out = false\n let held = false\n let settled = false\n let grace: NodeJS.Timeout | undefined\n const on_abort = (): void => {\n kill_group(child)\n reject(abort.reason)\n }\n for (const stream of [child.stdout, child.stderr]) {\n // Stryker disable next-line StringLiteral: Node reads an empty encoding name as UTF-8.\n stream.setEncoding('utf8')\n stream.on('data', (chunk: string) => {\n take(capture, chunk)\n })\n }\n const timer = setTimeout(() => {\n timed_out = true\n kill_group(child)\n }, Math.min(timeout_ms, MAX_TIMER_MS))\n child.once('error', (err) => {\n reject(\n new Error(`run_command couldn't start ${SHELL} in ${cwd} (${err.message}); the workspace may have been moved or deleted`, {\n cause: err,\n }),\n )\n })\n const stop_reading = (): void => {\n child.stdout.destroy()\n child.stderr.destroy()\n }\n child.once('exit', () => {\n clearTimeout(timer)\n kill_group(child)\n // A call the abort has already settled reads nothing more, so its output\n // closes at once, rather than on a grace timer that would outlive it.\n if (settled) {\n stop_reading()\n return\n }\n // Stopping the reads closes the call even while something still holds\n // the other end of the output open.\n grace = setTimeout(() => {\n held = true\n stop_reading()\n }, OUTPUT_GRACE_MS)\n })\n child.once('close', () => {\n if (timed_out) reject(timeout_error(capture, timeout_ms))\n else resolve({ capture, child, held })\n })\n abort.addEventListener('abort', on_abort)\n try {\n return await promise\n } finally {\n settled = true\n clearTimeout(timer)\n clearTimeout(grace)\n abort.removeEventListener('abort', on_abort)\n }\n}\n\n/**\n * The `run_command` tool for one session: a command run through the shell\n * in its `cwd`, with a timeout, an output cap, and the environment the\n * settings give it, its whole process tree killed when the turn is\n * cancelled. POSIX only: on Windows every call is refused.\n */\nexport function run_command_tool(session: AcpSession, settings: CommandSettings): Tool {\n return {\n name: 'run_command',\n description: [\n `Run a shell command with ${SHELL} -c in the workspace root, and return what it printed (stdout and stderr together) and its exit code.`,\n 'Each call starts a fresh shell there, so a cd lasts for its own command only.',\n `The command is stopped after ${settings.timeout_ms / 1000} s unless timeout_ms says otherwise,`,\n `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.`,\n 'Give the command plainly, without 2>&1 or a pipe to trim output that may well fit:',\n 'the user can allow a plain command for the rest of the session, but never one that holds a pipe, a redirect, &&, or ;.',\n \"It gets no input, and anything it starts is stopped once it exits, so it can't leave a server or a watcher running.\",\n ].join(' '),\n input_schema: json_schema_to_standard({\n type: 'object',\n properties: {\n command: { type: 'string', description: 'The command line, as you would type it in a POSIX shell' },\n timeout_ms: {\n type: 'integer',\n minimum: 1,\n description: `How long the command may run, in milliseconds; default: ${settings.timeout_ms}`,\n },\n },\n required: ['command'],\n additionalProperties: false,\n }),\n execute: async (input, ctx) => {\n if (process.platform === 'win32') {\n throw new Error(\n `run_command runs commands through ${SHELL} in a process group of their own, which Windows doesn't have, ` +\n 'so it can only refuse here; read_file, list_files, search, write_file, and edit_file still work',\n )\n }\n const finished = await run_shell(command_request(input), session.cwd, settings, ctx.abort)\n record_preview(session, ctx.tool_call_id, command_preview(finished))\n return report(finished)\n },\n }\n}\n","/**\n * workspace_tools: the tools a coding agent served over ACP needs, confined\n * to its session's workspace.\n *\n * They run in-process against the files on disk and in a shell of their\n * own, never through the client's `fs/*` or `terminal/*` methods, which\n * Claude Agent stopped using and the ACP v2 draft drops. They're plain\n * `Tool` values, so a flow can filter them (a read-only critic takes the\n * reads), set its own beside them, or wrap them. Each file tool checks every\n * path it's handed against the session's roots; a command starts in `cwd`\n * and reaches whatever the user can.\n *\n * The writes and `run_command` ask for approval when the session's mode\n * says to, and the reads never do.\n *\n * A flow or an MCP server can hand a model a tool of its own under one of\n * these names, and a name is all the engine tells the approval and the\n * cards. So each session keeps what it built: the names, which pick the\n * cards it draws, and every validated input that its gated tools were\n * asked about, which is how the approval knows its own calls. The engine\n * hands `needs_approval` and the approval handler the same input object,\n * so a same-named tool's call never passes for one of these.\n */\n\nimport type { Tool } from '#engine'\nimport { is_record } from '#schema'\nimport { asks_before } from './modes.js'\nimport type { GatedAction } from './modes.js'\nimport { edit_file_tool } from './tools/edit_file.js'\nimport { list_files_tool } from './tools/list_files.js'\nimport { read_file_tool } from './tools/read_file.js'\nimport { run_command_tool } from './tools/run_command.js'\nimport { search_tool } from './tools/search.js'\nimport { write_file_tool } from './tools/write_file.js'\nimport type { AcpSession, WorkspaceToolsOptions } from './types.js'\n\n/** The most lines one `read_file` call returns unless the options say otherwise. */\nconst READ_LIMIT_LINES = 2000\n\n/** The most paths one `list_files` call returns, so a very large repository's listing can't fill the context. */\nconst LIST_LIMIT = 1000\n\n/** The names `list_files` and `search` skip unless the options say otherwise. */\nconst IGNORE: ReadonlyArray<string> = ['.git', 'node_modules']\n\n/** How long one `search` may run unless the options say otherwise. */\nconst SEARCH_TIMEOUT_MS = 30_000\n\n/** How long one `run_command` call may run unless the options or the call say otherwise. */\nconst COMMAND_TIMEOUT_MS = 120_000\n\n/** The most output one `run_command` call returns unless the options say otherwise. */\nconst OUTPUT_LIMIT_BYTES = 32_000\n\n/**\n * The names each session's `workspace_tools` built. The set takes\n * `undefined` too, so a card whose opening the mapper never saw simply\n * finds nothing.\n */\nconst built = new WeakMap<AcpSession, ReadonlySet<string | undefined>>()\n\n/** The validated inputs each session's gated workspace tools were asked about. */\nconst asked = new WeakMap<AcpSession, WeakSet<object>>()\n\n/**\n * The inputs the session's gated workspace tools were asked about, made\n * empty the first time it's asked for.\n */\nfunction asked_of(session: AcpSession): WeakSet<object> {\n const inputs = asked.get(session) ?? new WeakSet<object>()\n asked.set(session, inputs)\n return inputs\n}\n\n/**\n * Whether the session's `workspace_tools` built a tool named `name`, so its\n * calls take the card that tool's presentation gives it.\n */\nexport function is_workspace_tool(session: AcpSession, name: string | undefined): boolean {\n return built.get(session)?.has(name) === true\n}\n\n/**\n * Whether one of the session's gated workspace tools was asked about this\n * very input, which makes the call one of theirs rather than a call to a\n * tool that only shares a name with one.\n */\nexport function is_workspace_call(session: AcpSession, input: unknown): boolean {\n return is_record(input) && asked.get(session)?.has(input) === true\n}\n\n/**\n * `tool`, asking for approval before each call when the session's mode asks\n * before `action`, and marking the input it was asked about as one of the\n * session's own. The mode is read at each call, not once, so a switch the\n * client makes mid-turn holds from the next call on.\n */\nfunction gated(tool: Tool, session: AcpSession, action: GatedAction): Tool {\n return {\n ...tool,\n needs_approval: (input) => {\n if (is_record(input)) asked_of(session).add(input)\n return asks_before(session.mode(), action)\n },\n }\n}\n\n/**\n * The workspace tools for one session: the reads (`read_file`, `list_files`,\n * and `search`), then the writes (`write_file` and `edit_file`), each\n * confined to the session's `cwd` and additional directories, then\n * `run_command`. The writes and the command ask before they run as the\n * session's mode says. From the first call on, the six names are the\n * workspace tools' within the session.\n */\nexport function workspace_tools(session: AcpSession, options: WorkspaceToolsOptions = {}): ReadonlyArray<Tool> {\n const ignore = options.ignore ?? IGNORE\n const tools = [\n read_file_tool(session, options.read_limit_lines ?? READ_LIMIT_LINES),\n list_files_tool(session, ignore, LIST_LIMIT),\n search_tool(session, ignore, options.search_timeout_ms ?? SEARCH_TIMEOUT_MS),\n gated(write_file_tool(session), session, 'edit'),\n gated(edit_file_tool(session), session, 'edit'),\n gated(\n run_command_tool(session, {\n timeout_ms: options.command_timeout_ms ?? COMMAND_TIMEOUT_MS,\n output_limit_bytes: options.output_limit_bytes ?? OUTPUT_LIMIT_BYTES,\n env: options.command_env,\n }),\n session,\n 'command',\n ),\n ]\n built.set(session, new Set(tools.map((tool) => tool.name)))\n return tools\n}\n","/**\n * presentation: how a workspace tool's call looks in the client, matching\n * what Zed's Claude Agent sends for its own tools.\n *\n * Each card gets the kind that picks its icon, a title that reads like the\n * call (`Read src/a.ts (1 - 40)`, `grep \"todo\" src`, the command line) with\n * its paths relative to `cwd`, and the places it touches as locations, whose\n * lines count from 1 as Claude Agent's do. A write's or an edit's card shows\n * its diff once the call lands, a read's, a listing's, or a search's shows\n * the text the model read in a code block, and a command's shows what it\n * printed: in a terminal when the client advertises Zed's terminal extension\n * (`_meta.terminal_output`), and as a `console` code block otherwise.\n *\n * It's keyed by tool name, since nothing ACP-specific may reach the engine's\n * `Tool` type and a card opens with nothing but the name the model called.\n * Only the names the session's `workspace_tools` built count, so in a\n * session that never built them, a tool of the flow's own that shares a\n * name gets the plain card. It does no I/O: the file reads behind a diff\n * happen in the tools, which leave each call's preview in the session's\n * store for its card to take when the call's result arrives.\n */\n\nimport { resolve } from 'node:path'\nimport type { SessionUpdate, ToolCall, ToolCallContent, ToolCallLocation, ToolKind } from '@agentclientprotocol/sdk'\nimport type { StreamChunk } from '#engine'\nimport { as_record } from '#schema'\nimport { shown_path } from './tools/containment.js'\nimport { take_preview } from './tools/previews.js'\nimport type { ChangePreview, CommandPreview, ToolPreview } from './tools/previews.js'\nimport type { AcpSession } from './types.js'\nimport { is_workspace_tool } from './workspace_tools.js'\n\ntype ToolResultChunk = Extract<StreamChunk, { kind: 'tool_result' }>\n\n/** An update to a card the client already shows. */\nexport type CardUpdate = Extract<SessionUpdate, { sessionUpdate: 'tool_call_update' }>\n\n/** What a call's input says about its card: its title, and the places it touches. */\ntype Described = {\n readonly title: string\n readonly locations?: ToolCallLocation[]\n}\n\n/** How a command ended, as its terminal shows it. */\ntype Ran = Pick<CommandPreview, 'output' | 'exit_code' | 'signal'>\n\n/**\n * How one workspace tool's cards look: the kind that picks the icon, what a\n * call's input says about it, and what its card shows once the call\n * succeeds: the change it made, what the command printed, or the text the\n * model read.\n */\ntype Presenter = {\n readonly kind: ToolKind\n readonly describe: (fields: Record<string, unknown>, session: AcpSession) => Described | undefined\n readonly shows?: 'change' | 'command' | 'text'\n}\n\n/**\n * A path the call names, made absolute under the client's `cwd`, which is\n * how a location and a diff carry it.\n */\nfunction absolute(session: AcpSession, path: string): string {\n return resolve(session.cwd, path)\n}\n\n/**\n * A path as a title shows it: relative to `cwd` when it's under it, and\n * absolute otherwise, the way the tools show paths to the model.\n */\nfunction shown(session: AcpSession, path: string): string {\n return shown_path(session, absolute(session, path))\n}\n\n/**\n * The lines a read covers, as its title says them: a range when the call\n * sets a limit, where it starts when it sets only an offset, and nothing\n * when it reads from the top.\n */\nfunction read_range(first: number, offset: unknown, limit: unknown): string {\n if (typeof limit === 'number') return ` (${first} - ${first + limit - 1})`\n if (typeof offset === 'number') return ` (from line ${offset})`\n return ''\n}\n\n/**\n * A `read_file` card: `Read <path>` with the lines it covers, pointing at\n * the line the read starts on.\n */\nfunction describe_read({ path, offset, limit }: Record<string, unknown>, session: AcpSession): Described | undefined {\n if (typeof path !== 'string') return undefined\n const first = typeof offset === 'number' ? offset : 1\n return {\n title: `Read ${shown(session, path)}${read_range(first, offset, limit)}`,\n locations: [{ path: absolute(session, path), line: first }],\n }\n}\n\n/**\n * A `write_file` or `edit_file` card: the verb and the path, pointing at\n * the file. The line an edit lands on comes with its preview, once the\n * edit has found it.\n */\nfunction describe_change(verb: string): Presenter['describe'] {\n return ({ path }, session) =>\n typeof path === 'string'\n ? { title: `${verb} ${shown(session, path)}`, locations: [{ path: absolute(session, path) }] }\n : undefined\n}\n\n/**\n * A `list_files` card: `Find` with the directory and the pattern in code\n * spans, each when the call names it.\n */\nfunction describe_find({ pattern, path }: Record<string, unknown>, session: AcpSession): Described {\n const parts = ['Find']\n if (typeof path === 'string') parts.push(`\\`${shown(session, path)}\\``)\n if (typeof pattern === 'string') parts.push(`\\`${pattern}\\``)\n return { title: parts.join(' ') }\n}\n\n/**\n * A `search` card, titled the way the grep command line that does the same\n * search reads.\n */\nfunction describe_grep({ pattern, path, glob }: Record<string, unknown>, session: AcpSession): Described {\n const parts = ['grep']\n if (typeof glob === 'string') parts.push(`--include=\"${glob}\"`)\n if (typeof pattern === 'string') parts.push(`\"${pattern}\"`)\n if (typeof path === 'string') parts.push(shown(session, path))\n return { title: parts.join(' ') }\n}\n\n/**\n * A `run_command` card, titled with the command line itself.\n */\nfunction describe_command({ command }: Record<string, unknown>): Described | undefined {\n return typeof command === 'string' ? { title: command } : undefined\n}\n\n/**\n * The workspace tools by name. The key takes `undefined` too, so a card\n * whose opening the mapper never saw simply finds nothing.\n */\nconst PRESENTERS = new Map<string | undefined, Presenter>([\n ['read_file', { kind: 'read', describe: describe_read, shows: 'text' }],\n ['list_files', { kind: 'search', describe: describe_find, shows: 'text' }],\n ['search', { kind: 'search', describe: describe_grep, shows: 'text' }],\n ['write_file', { kind: 'edit', describe: describe_change('Write'), shows: 'change' }],\n ['edit_file', { kind: 'edit', describe: describe_change('Edit'), shows: 'change' }],\n ['run_command', { kind: 'execute', describe: describe_command, shows: 'command' }],\n])\n\n/**\n * How the cards of the tool `name` look in `session`, when the session's\n * `workspace_tools` built a tool of that name. Any other tool gets the\n * plain card.\n */\nfunction presenter_of(session: AcpSession, name: string | undefined): Presenter | undefined {\n return is_workspace_tool(session, name) ? PRESENTERS.get(name) : undefined\n}\n\n/**\n * Whether the client draws a command's output in a terminal from Zed's\n * `_meta` extension, which it says in `initialize`.\n */\nfunction renders_terminals(session: AcpSession): boolean {\n const { _meta: meta } = session.client_capabilities\n return meta?.['terminal_output'] === true\n}\n\n/**\n * The terminal a card shows, under the card's own id, as Claude Agent names\n * its terminals.\n */\nfunction terminal(card: string): ToolCallContent {\n return { type: 'terminal', terminalId: card }\n}\n\n/**\n * What a workspace tool's card opens with: its kind, and for a command in a\n * client that draws terminals, the terminal its output will land in.\n */\nexport function opening_fields(session: AcpSession | undefined, name: string, card: string): Partial<ToolCall> {\n // Stryker disable next-line ConditionalExpression: a missing session built no workspace tools, so presenter_of finds nothing for it either way; the check narrows the type.\n if (session === undefined) return {}\n const presenter = presenter_of(session, name)\n if (presenter === undefined) return {}\n if (presenter.shows !== 'command' || !renders_terminals(session)) return { kind: presenter.kind }\n return { kind: presenter.kind, content: [terminal(card)], _meta: { terminal_info: { terminal_id: card } } }\n}\n\n/**\n * What a workspace tool call's complete input adds to its card: its title\n * and locations. An input that lacks what they need leaves the card as it\n * opened.\n */\nexport function input_fields(session: AcpSession | undefined, name: string | undefined, input: unknown): Partial<CardUpdate> {\n // Stryker disable next-line ConditionalExpression: a missing session built no workspace tools, so presenter_of finds nothing for it either way; the check narrows the type.\n if (session === undefined) return {}\n const presenter = presenter_of(session, name)\n if (presenter === undefined) return {}\n return presenter.describe(as_record(input) ?? {}, session) ?? {}\n}\n\n/**\n * A file change as a diff, which a client shows as the file's hunks.\n */\nfunction diff_of(change: ChangePreview): ToolCallContent {\n return { type: 'diff', path: change.path, oldText: change.old_text, newText: change.new_text }\n}\n\n/**\n * Close a write's or an edit's card with the change it made, and for an\n * edit, the line its first match starts on. The closing update replaces the\n * card's content, so it carries the diff again rather than dropping one the\n * card already shows. A call that failed, or left no change behind, closes\n * as it stands.\n */\nfunction close_change(closing: CardUpdate, preview: ToolPreview | undefined): CardUpdate {\n if (preview?.kind !== 'change') return closing\n return {\n ...closing,\n content: [diff_of(preview)],\n ...(preview.line === undefined ? {} : { locations: [{ path: preview.path, line: preview.line }] }),\n }\n}\n\n/**\n * Text in a code block under the `info` string, its fence longer than any\n * run of backticks that opens one of its lines, so nothing in the text can\n * close the block early.\n */\nfunction code_block(text: string, info: string): ToolCallContent {\n const longest = Math.max(2, ...Array.from(text.matchAll(/^`+/gm), ([run]) => run.length))\n const fence = '`'.repeat(longest + 1)\n return { type: 'content', content: { type: 'text', text: `${fence}${info}\\n${text}\\n${fence}` } }\n}\n\n/**\n * Close a read's, a listing's, or a search's card with the text the model\n * read. A listing or a search result goes in a code block too, since a\n * matching line can hold markdown that the client would otherwise render.\n * A failed call keeps its error text.\n */\nfunction close_text(closing: CardUpdate, chunk: ToolResultChunk): CardUpdate {\n if (chunk.error !== undefined) return closing\n return { ...closing, content: [code_block(String(chunk.output), '')] }\n}\n\n/**\n * How a command's terminal ends: what it printed and how it exited, or, for\n * a call that failed or left nothing behind, the error text and no exit\n * code.\n */\nfunction ran(chunk: ToolResultChunk, preview: ToolPreview | undefined): Ran {\n if (preview?.kind === 'command') return preview\n return { output: chunk.error?.message ?? '', exit_code: null, signal: null }\n}\n\n/**\n * Close a command's card. A client that draws terminals gets the output on\n * the terminal the card opened with, then the exit and the status, as\n * Claude Agent sends them. Any other client gets what the model read, its\n * exit code included, in a `console` block; a failed call keeps its error\n * text.\n */\nfunction close_command(\n session: AcpSession,\n card: string,\n chunk: ToolResultChunk,\n closing: CardUpdate,\n preview: ToolPreview | undefined,\n): SessionUpdate[] {\n if (!renders_terminals(session)) {\n if (chunk.error !== undefined) return [closing]\n return [{ ...closing, content: [code_block(String(chunk.output), 'console')] }]\n }\n const { output, exit_code, signal } = ran(chunk, preview)\n return [\n {\n sessionUpdate: 'tool_call_update',\n toolCallId: card,\n _meta: { terminal_output: { terminal_id: card, data: output } },\n },\n {\n ...closing,\n content: [terminal(card)],\n _meta: { terminal_exit: { terminal_id: card, exit_code, signal } },\n },\n ]\n}\n\n/**\n * The updates that close a tool call's card, starting from the plain\n * `closing` update. A read, a listing, or a search leaves no preview, so its\n * card takes nothing from the session's store. A successful call of a tool\n * that leaves a preview takes it from the store whatever the card then does\n * with it, which keeps each raw id's queue in step with its results.\n */\nexport function closing_updates(\n session: AcpSession | undefined,\n name: string | undefined,\n card: string,\n chunk: ToolResultChunk,\n closing: CardUpdate,\n): SessionUpdate[] {\n // Stryker disable next-line ConditionalExpression: a missing session built no workspace tools, so presenter_of finds nothing for it either way; the check narrows the type.\n if (session === undefined) return [closing]\n const shows = presenter_of(session, name)?.shows\n if (shows === undefined) return [closing]\n if (shows === 'text') return [close_text(closing, chunk)]\n const preview = chunk.error === undefined ? take_preview(session, chunk.id) : undefined\n if (shows === 'change') return [close_change(closing, preview)]\n return close_command(session, card, chunk, closing, preview)\n}\n","/**\n * approve: ask the client before a workspace tool edits a file or runs a\n * command, through `session/request_permission`.\n *\n * The request shows the card the client already draws for the call, and\n * for an edit, the change worked out on disk first, so the user approves\n * the diff itself. It offers Allow, Reject, and an \"always\" that lives in\n * memory for the session. For an edit, \"always\" switches the session to\n * Accept edits, as Claude Agent's does, and tells the client both ways so\n * its mode picker follows. An edit is offered one only when the agent\n * offers Accept edits, since that's the mode it switches to. For a\n * command, it covers that exact command line and nothing else, since one\n * flag can turn a listing into a delete (`find . -name '*.ts'` and\n * `find . -delete`). A command with shell control syntax is never covered\n * and never offered one, since anything can follow a `;` or a `|`.\n *\n * Only the session's own workspace tools get the diff and the \"always\",\n * known by the input their `needs_approval` marked rather than by name. A\n * tool of a flow's own or an MCP tool that shares a name gets the plain\n * request, and no grant covers it.\n *\n * A permission check that fails open isn't a check, so anything short of\n * an allow denies the call: a rejection, a `cancelled` outcome, an option\n * the request never offered, and a request that fails for any reason.\n *\n * The engine asks with its raw call id, which can repeat inside a turn,\n * and the turn's consumer can still be sending earlier updates when it\n * asks. So the request waits until the consumer has sent everything the\n * run had recorded by then, the card's opening included, and points at the\n * latest card the client was sent for that raw id. The consumer never\n * waits on an approval, so the wait can't deadlock, and the turn's abort\n * ends it.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type {\n PermissionOption,\n RequestPermissionOutcome,\n RequestPermissionRequest,\n RequestPermissionResponse,\n SessionUpdate,\n ToolCallUpdate,\n} from '@agentclientprotocol/sdk'\nimport type { TrajectoryEvent, TrajectoryLogger } from '#core'\nimport type { ToolApprovalRequest } from '#engine'\nimport { as_record } from '#schema'\nimport { asks_before } from './modes.js'\nimport type { GatedAction, SessionModes } from './modes.js'\nimport { input_fields, opening_fields } from './presentation.js'\nimport { edit_file_change } from './tools/edit_file.js'\nimport { write_file_change } from './tools/write_file.js'\nimport type { ShownChange } from './tools/write_file.js'\nimport type { AcpSession } from './types.js'\nimport { is_workspace_call } from './workspace_tools.js'\n\n/**\n * What a session's turn tells its approvals: how far the turn's consumer\n * has got, and which card each raw call id opened last.\n *\n * A run that outran the client so far that it dropped events never lets\n * the consumer catch up, so an approval it asks for waits until the turn\n * is cancelled. Only a client that has stopped reading gets that far\n * behind, and it wouldn't answer the request either.\n */\nexport type CardSync = {\n /**\n * Start a turn, forgetting the last one. Returns the logger the turn's\n * run records through, which counts every event `run.stream` queues and\n * passes each one on to `inner`.\n */\n readonly start: (inner: TrajectoryLogger | undefined) => TrajectoryLogger\n /** Note that the consumer has sent every update one event maps to. */\n readonly sent: (event: TrajectoryEvent, updates: ReadonlyArray<SessionUpdate>) => void\n /** Settle once the consumer has sent every event the run had recorded by now. */\n readonly caught_up: () => Promise<void>\n /** The id of the latest card the client was sent for a raw call id. */\n readonly card_for: (raw_id: string) => string | undefined\n}\n\n/** One turn's count of the events its run recorded and its consumer sent. */\ntype TurnProgress = {\n recorded: number\n sent: number\n /** Settles at the consumer's next event, then gives way to a fresh one. */\n moved: PromiseWithResolvers<void>\n readonly cards: Map<string, string>\n}\n\n/**\n * Asks the client to approve one tool call, and withdraws the request\n * when `cancel` fires.\n */\nexport type PermissionAsker = (\n request: RequestPermissionRequest,\n cancel: AbortSignal,\n) => Promise<RequestPermissionResponse>\n\n/** What a session's approvals need beside the session itself. */\nexport type ApproverDeps = {\n readonly modes: SessionModes\n readonly cards: CardSync\n readonly ask: PermissionAsker\n}\n\n/** Answers the engine's approval requests for the calls in one session. */\nexport type SessionApprover = (session: AcpSession, request: ToolApprovalRequest) => Promise<boolean>\n\n/**\n * What a workspace tool that asks does, and for a write or an edit, how\n * to work out its change without making it. A gate goes by name, but only\n * a call the session's own workspace tool marked ever reaches one.\n */\ntype Gate = {\n readonly action: GatedAction\n readonly change?: (session: AcpSession, input: unknown) => Promise<ShownChange>\n}\n\nconst GATES: ReadonlyMap<string, Gate> = new Map<string, Gate>([\n ['write_file', { action: 'edit', change: write_file_change }],\n ['edit_file', { action: 'edit', change: edit_file_change }],\n ['run_command', { action: 'command' }],\n])\n\n/**\n * Shell syntax that runs, chains, or redirects something past the\n * command's own program: `;`, `&`, `|`, `>`, `<`, a backtick, `$(`, and a\n * newline.\n */\nconst CONTROL_SYNTAX = /[;&|<>`\\n]|\\$\\(/\n\n/** The \"always\" an approval offers, and what choosing it grants. */\ntype Always = {\n readonly name: string\n readonly grant: () => Promise<void>\n}\n\nconst ALLOW_ONCE: PermissionOption = { optionId: 'allow_once', name: 'Allow', kind: 'allow_once' }\nconst REJECT_ONCE: PermissionOption = { optionId: 'reject_once', name: 'Reject', kind: 'reject_once' }\n\n/**\n * A fresh count for a turn that has recorded and sent nothing yet.\n */\nfunction fresh_progress(): TurnProgress {\n return { recorded: 0, sent: 0, moved: Promise.withResolvers(), cards: new Map() }\n}\n\n/**\n * `inner`, or nothing, with `count` called after each call that queues an\n * event. Without an inner logger, a span gets an id of its own, as the\n * runner's default logger gives one.\n */\nfunction counting_logger(inner: TrajectoryLogger | undefined, count: () => void): TrajectoryLogger {\n return {\n record: (event) => {\n inner?.record(event)\n count()\n },\n start_span: (name, meta) => {\n const id = inner?.start_span(name, meta) ?? `${name}:${randomUUID()}`\n count()\n return id\n },\n end_span: (id, meta) => {\n inner?.end_span(id, meta)\n count()\n },\n }\n}\n\n/**\n * The raw id of the call a `tool_call_start` chunk opens, or `undefined`\n * for any other event.\n */\nfunction started_call(event: TrajectoryEvent): string | undefined {\n if (event.kind !== 'model_chunk') return undefined\n const chunk = as_record(event['chunk'])\n // Stryker disable next-line ConditionalExpression: a non-string id would land under a key no string lookup finds, so the check only narrows the type.\n return chunk?.['kind'] === 'tool_call_start' && typeof chunk['id'] === 'string' ? chunk['id'] : undefined\n}\n\n/**\n * Whether an update opens a card.\n */\nfunction opens_card(update: SessionUpdate): update is Extract<SessionUpdate, { sessionUpdate: 'tool_call' }> {\n return update.sessionUpdate === 'tool_call'\n}\n\n/**\n * Create the sync between a session's turns and its approvals. Turns in a\n * session never overlap, so one sync serves them all, a turn at a time.\n */\nexport function create_card_sync(): CardSync {\n let turn = fresh_progress()\n return {\n start: (inner) => {\n const started = fresh_progress()\n turn = started\n return counting_logger(inner, () => {\n started.recorded += 1\n })\n },\n sent: (event, updates) => {\n const raw_id = started_call(event)\n const card = updates.find(opens_card)\n // Stryker disable next-line ConditionalExpression: a card noted under no raw id sits where no lookup asks, so the check only narrows the type.\n if (raw_id !== undefined && card !== undefined) turn.cards.set(raw_id, card.toolCallId)\n turn.sent += 1\n turn.moved.resolve()\n turn.moved = Promise.withResolvers()\n },\n caught_up: async () => {\n const waiting = turn\n const target = waiting.recorded\n while (waiting.sent < target) await waiting.moved.promise\n },\n card_for: (raw_id) => turn.cards.get(raw_id),\n }\n}\n\n/**\n * What an \"always\" grant for a command covers: the command line itself,\n * with the whitespace at its ends trimmed and everything between compared\n * exactly, because `rm \"a b\"` and `rm \"a b\"` name different files. A\n * command with shell control syntax has none, so no grant ever covers it,\n * and neither does one that isn't a string or is only whitespace.\n */\nexport function command_key(input: unknown): string | undefined {\n const command = as_record(input)?.['command']\n if (typeof command !== 'string' || CONTROL_SYNTAX.test(command)) return undefined\n const key = command.trim()\n return key === '' ? undefined : key\n}\n\n/**\n * The message a failure carries, whatever was thrown.\n */\nexport function message_of(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/**\n * Start `work` and settle with it, or reject with the abort's reason as\n * soon as `abort` fires, so a turn's cancel never waits on the client. A\n * turn already cancelled starts nothing, so no request goes out for it.\n */\nasync function unless_aborted<T>(abort: AbortSignal, work: () => Promise<T>): Promise<T> {\n abort.throwIfAborted()\n const { promise: aborted, reject } = Promise.withResolvers<never>()\n const on_abort = (): void => {\n reject(abort.reason)\n }\n abort.addEventListener('abort', on_abort)\n try {\n return await Promise.race([work(), aborted])\n } finally {\n // The turn's signal outlives every approval it asks for.\n abort.removeEventListener('abort', on_abort)\n }\n}\n\n/**\n * What a change adds to the request's card: its diff, and for an edit,\n * the line its first match starts on. A change that can't be worked out\n * shows why instead, which is what the call will fail with if it's\n * allowed, so the user isn't asked to approve a change they can't see.\n */\nasync function change_fields(\n change: NonNullable<Gate['change']>,\n session: AcpSession,\n input: unknown,\n): Promise<Partial<ToolCallUpdate>> {\n try {\n const { path, old_text, new_text, line } = await change(session, input)\n return {\n content: [{ type: 'diff', path, oldText: old_text, newText: new_text }],\n ...(line === undefined ? {} : { locations: [{ path, line }] }),\n }\n } catch (err: unknown) {\n return { content: [{ type: 'content', content: { type: 'text', text: message_of(err) } }] }\n }\n}\n\n/**\n * The card a request shows: the one the client already draws for the call\n * under `card`, as its tool's presentation describes it, with the change\n * for a write or an edit.\n */\nasync function permission_card(\n session: AcpSession,\n request: ToolApprovalRequest,\n card: string,\n gate: Gate | undefined,\n): Promise<ToolCallUpdate> {\n const { tool_name: name, input } = request\n const fields: ToolCallUpdate = {\n toolCallId: card,\n title: name,\n kind: opening_fields(session, name, card).kind ?? 'other',\n rawInput: input,\n ...input_fields(session, name, input),\n }\n if (gate?.change === undefined) return fields\n return { ...fields, ...(await change_fields(gate.change, session, input)) }\n}\n\n/**\n * Whether the user's answer allows the call, granting the \"always\" first\n * when that's what they chose. Only an option the request offered counts.\n */\nasync function allowed(outcome: RequestPermissionOutcome, always: Always | undefined): Promise<boolean> {\n if (outcome.outcome !== 'selected') return false\n if (outcome.optionId === ALLOW_ONCE.optionId) return true\n if (outcome.optionId !== 'allow_always' || always === undefined) return false\n await always.grant()\n return true\n}\n\n/**\n * Say on stderr that a permission request failed, since the call was\n * refused without the user ever seeing it.\n */\nfunction warn_failed(tool_name: string, err: unknown): void {\n process.stderr.write(\n `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`,\n )\n}\n\n/**\n * The \"always\" a call is offered: Accept edits for an edit, when the agent\n * offers that mode, and a grant of its key for a command that has one. Any\n * other call gets none. Choosing Accept edits leaves a session that has\n * moved past Manual since the call asked where it is.\n */\nfunction always_for(\n gate: Gate | undefined,\n key: string | undefined,\n modes: SessionModes,\n granted: Set<string>,\n): Always | undefined {\n if (gate?.action === 'edit') {\n if (!modes.offers('accept_edits')) return undefined\n return {\n name: 'Allow all edits this session',\n grant: async () => {\n if (asks_before(modes.current(), 'edit')) await modes.switch_to('accept_edits')\n },\n }\n }\n if (key === undefined) return undefined\n return {\n name: `Always allow \\`${key}\\` this session`,\n grant: async () => {\n granted.add(key)\n },\n }\n}\n\n/**\n * The options a request offers. Allow is always among them, since some\n * hosts answer every request on their own by choosing `allow_once`.\n */\nfunction options_for(always: Always | undefined): PermissionOption[] {\n if (always === undefined) return [ALLOW_ONCE, REJECT_ONCE]\n return [ALLOW_ONCE, { optionId: 'allow_always', name: always.name, kind: 'allow_always' }, REJECT_ONCE]\n}\n\n/**\n * Create the approvals for one session's calls, holding its commands'\n * \"always\" grants for the life of the session.\n */\nexport function session_approver({ modes, cards, ask }: ApproverDeps): SessionApprover {\n const granted = new Set<string>()\n return async (session, request) => {\n const gate = is_workspace_call(session, request.input) ? GATES.get(request.tool_name) : undefined\n const key = gate?.action === 'command' ? command_key(request.input) : undefined\n // Stryker disable next-line ConditionalExpression: only keys are ever granted, so has() answers false for a missing key either way; the check narrows the type.\n if (key !== undefined && granted.has(key)) return true\n const always = always_for(gate, key, modes, granted)\n const options = options_for(always)\n try {\n await unless_aborted(request.abort, cards.caught_up)\n const card = cards.card_for(request.tool_call_id) ?? randomUUID()\n const toolCall = await permission_card(session, request, card, gate)\n const answer = await unless_aborted(request.abort, () =>\n ask({ sessionId: session.id, toolCall, options }, request.abort),\n )\n return await allowed(answer.outcome, always)\n } catch (err: unknown) {\n if (!request.abort.aborted) warn_failed(request.tool_name, err)\n return false\n }\n }\n}\n","/**\n * Maps a run's events onto ACP `session/update` payloads.\n *\n * Under `run.stream`, each `model_call` records `model_chunk` events carrying\n * the engine's `StreamChunk`, the same source fascicle/ui reads. This half of\n * a prompt turn does no I/O and holds no SDK value, so a flow author can wrap\n * `to_session_updates` in their own `to_updates` and add to what it returns,\n * as long as every event still reaches it: each `span_start` advances the\n * state's count of how many times a step has run, and a workspace tool's\n * result takes its call's preview from the session's store. Spans, `cost`,\n * and `emit` events map to nothing; an `emit` never becomes chat output\n * implicitly, because output that changes with a value's shape is a trap.\n *\n * Every tool gets a plain card here. Given the turn's session, the workspace\n * tools' cards also take the look `presentation.ts` gives them.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { ContentBlock, SessionUpdate } from '@agentclientprotocol/sdk'\nimport type { TrajectoryEvent } from '#core'\nimport type { StreamChunk } from '#engine'\nimport { closing_updates, input_fields, opening_fields } from './presentation.js'\nimport type { CardUpdate } from './presentation.js'\nimport type { AcpMapperOptions, AcpMapperState, AcpStreamRoute } from './types.js'\n\ntype ToolResultChunk = Extract<StreamChunk, { kind: 'tool_result' }>\n\n/**\n * Create the state for one prompt turn's events, routing every model call's\n * text to the reply unless `stream` says otherwise.\n */\nexport function create_acp_mapper_state(options: AcpMapperOptions = {}): AcpMapperState {\n return {\n turn_id: options.turn_id ?? randomUUID(),\n stream: options.stream ?? (() => 'message'),\n runs: new Map(),\n session: options.session,\n tools: new Map(),\n }\n}\n\n/**\n * Build the session-unique ACP id for an engine tool call id.\n *\n * Raw ids repeat across model calls, turns, and runs of one model call\n * (Ollama has none on the wire, so the engine numbers them\n * `ollama_call_<step>_<n>` afresh on every generate call), and a repeated id\n * would make the client update an old card instead of opening a new one.\n */\nfunction acp_tool_call_id(state: AcpMapperState, step_id: string, raw_id: string): string {\n return `${state.turn_id}:${step_id}:${state.runs.get(step_id) ?? 0}:${raw_id}`\n}\n\n/**\n * Count one more run of the step a `span_start` opens, by the `id` its span\n * carries. Counting starts rather than finishes covers a retry whose first\n * attempt failed before it finished.\n */\nfunction count_run(event: TrajectoryEvent, state: AcpMapperState): void {\n const id = event['id']\n if (typeof id === 'string') state.runs.set(id, (state.runs.get(id) ?? 0) + 1)\n}\n\n/**\n * Wrap streamed text as the update its route names, or nothing for `'none'`.\n */\nfunction text_updates(route: AcpStreamRoute, text: string): SessionUpdate[] {\n const content: ContentBlock = { type: 'text', text }\n if (route === 'message') return [{ sessionUpdate: 'agent_message_chunk', content }]\n if (route === 'thought') return [{ sessionUpdate: 'agent_thought_chunk', content }]\n return []\n}\n\n/**\n * Close a tool card: `completed` with the raw output, or `failed` with the\n * error text as the card's content, since that text is what the user needs\n * to see.\n */\nfunction tool_result_update(tool_call_id: string, chunk: ToolResultChunk): CardUpdate {\n if (chunk.error !== undefined) {\n return {\n sessionUpdate: 'tool_call_update',\n toolCallId: tool_call_id,\n status: 'failed',\n content: [{ type: 'content', content: { type: 'text', text: chunk.error.message } }],\n }\n }\n return {\n sessionUpdate: 'tool_call_update',\n toolCallId: tool_call_id,\n status: 'completed',\n rawOutput: chunk.output,\n }\n}\n\n/**\n * Map one engine `StreamChunk` from the model call `step_id` to the session\n * updates it produces.\n */\nfunction map_chunk(chunk: StreamChunk, step_id: string, state: AcpMapperState): SessionUpdate[] {\n switch (chunk.kind) {\n case 'text':\n return text_updates(state.stream(step_id), chunk.text)\n case 'reasoning':\n return text_updates('thought', chunk.text)\n case 'tool_call_start': {\n const card = acp_tool_call_id(state, step_id, chunk.id)\n state.tools.set(card, chunk.name)\n return [\n {\n sessionUpdate: 'tool_call',\n toolCallId: card,\n title: chunk.name,\n kind: 'other',\n status: 'pending',\n ...opening_fields(state.session, chunk.name, card),\n },\n ]\n }\n case 'tool_call_end': {\n const card = acp_tool_call_id(state, step_id, chunk.id)\n return [\n {\n sessionUpdate: 'tool_call_update',\n toolCallId: card,\n status: 'in_progress',\n rawInput: chunk.input,\n ...input_fields(state.session, state.tools.get(card), chunk.input),\n },\n ]\n }\n case 'tool_result': {\n const card = acp_tool_call_id(state, step_id, chunk.id)\n return closing_updates(state.session, state.tools.get(card), card, chunk, tool_result_update(card, chunk))\n }\n default:\n // The input arrives whole at tool_call_end, so its deltas add nothing,\n // and step_finish and finish carry no content for the client.\n return []\n }\n}\n\n/**\n * Narrow the loose `chunk` field of a `model_chunk` event. model_call records\n * only real StreamChunks there, and map_chunk maps a kind it doesn't know to\n * nothing, so ruling out a missing or null value is enough.\n */\nfunction is_stream_chunk(value: unknown): value is StreamChunk {\n return typeof value === 'object' && value !== null\n}\n\n/**\n * Map one run event to zero or more ACP session updates. Only `model_chunk`\n * events produce any. A `span_start` advances the state's run count, a\n * card's opening records its tool, and a workspace tool's result takes its\n * preview; the function does no I/O.\n */\nexport function to_session_updates(event: TrajectoryEvent, state: AcpMapperState): SessionUpdate[] {\n if (event.kind === 'span_start') {\n count_run(event, state)\n return []\n }\n if (event.kind !== 'model_chunk') return []\n const step_id = event['step_id']\n const chunk = event['chunk']\n if (typeof step_id !== 'string' || !is_stream_chunk(chunk)) return []\n return map_chunk(chunk, step_id, state)\n}\n","/**\n * One ACP prompt turn: run the session's flow through `run.stream` and send\n * what it produces to the client as session updates.\n *\n * The turn holds three rules the protocol leaves to the agent. A cancel\n * (`session/cancel`, the request's own `$/cancel_request`, a disconnect, or\n * the config's `abort`) stops the sending at once, then waits for the run to\n * settle and answers `cancelled`, even when the flow ignored the abort and\n * finished. A turn that sent no message text sends `to_text(output)` as its\n * reply. And the history records what the client was actually sent, a\n * cancelled turn included, so it matches the thread the user sees.\n */\n\nimport type { ContentBlock, PromptResponse, SessionUpdate } from '@agentclientprotocol/sdk'\nimport { aborted_error, run } from '#core'\nimport type { Step, TrajectoryEvent } from '#core'\nimport type { CardSync } from './approve.js'\nimport { create_acp_mapper_state, to_session_updates } from './to_session_updates.js'\nimport { reset_previews } from './tools/previews.js'\nimport type { AcpHistoryEntry, AcpSession, AcpTurn, ServeAcpConfig } from './types.js'\n\n/**\n * A session's latest turn, finished or not. Cancelling a finished turn does\n * nothing and waiting on it returns at once, so the record never needs\n * clearing.\n */\ntype TurnHandle = {\n readonly cancel: AbortController\n readonly settled: Promise<void>\n}\n\n/**\n * A session between turns: its flow, its history, its latest turn, and the\n * sync that lets its approvals wait for the client to catch up.\n */\nexport type SessionRecord<i, o> = {\n readonly session: AcpSession\n readonly flow: Step<i, o>\n readonly history: AcpHistoryEntry[]\n readonly cards: CardSync\n last_turn: TurnHandle | null\n}\n\nexport type SendUpdate = (update: SessionUpdate) => Promise<void>\n\ntype Reply = { sent: boolean; text: string; card_since_text: boolean }\n\ntype Settled<o> = { readonly ok: true; readonly output: o } | { readonly ok: false; readonly error: unknown }\n\n/**\n * Join a prompt's blocks into the text a flow reads. Text blocks join as the\n * client split them, and a resource link or an embedded resource reads as\n * its URI where it sat. Each embedded resource's text follows the prompt in\n * a `<context>` block naming that URI, the form Claude Agent uses, so a file\n * the user @-mentioned reaches the model without splitting the sentence that\n * mentions it. Image and audio blocks stay in `turn.prompt` only, since the\n * agent advertises neither.\n */\nfunction turn_text(prompt: ReadonlyArray<ContentBlock>): string {\n const inline: string[] = []\n const context: string[] = []\n for (const block of prompt) {\n if (block.type === 'text') inline.push(block.text)\n else if (block.type === 'resource_link') inline.push(block.uri)\n else if (block.type === 'resource') {\n inline.push(block.resource.uri)\n if ('text' in block.resource) {\n context.push(`<context ref=\"${block.resource.uri}\">\\n${block.resource.text}\\n</context>`)\n }\n }\n }\n return [inline.join(''), ...context].join('\\n\\n')\n}\n\n/**\n * The flow's input for a turn: the config's `to_input`, or the turn's text,\n * which `ServeAcpConfig` allows only when the flow takes a string.\n */\nfunction turn_input<i, o>(config: ServeAcpConfig<i, o>, turn: AcpTurn): i {\n if (config.to_input !== undefined) return config.to_input(turn)\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return turn.text as i\n}\n\n/**\n * The default `to_text`: a string as-is, anything else as JSON, and nothing\n * at all for a flow that returns nothing.\n */\nfunction default_to_text(output: unknown): string {\n return typeof output === 'string' ? output : (JSON.stringify(output) ?? '')\n}\n\n/**\n * Wrap a turn's final text as the message update that carries it.\n */\nfunction agent_message(text: string): SessionUpdate {\n return { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } }\n}\n\n/**\n * Count a message update the client was sent toward the turn's reply. Only\n * text joins the reply's text, but any message counts as a reply, so a flow\n * that sent an image doesn't get a `to_text` message after it. A tool card\n * that opened after some reply text splits the reply in two on the client,\n * so the recorded text starts the next run on a blank line instead of\n * running the two together.\n */\nfunction note_reply(reply: Reply, update: SessionUpdate): void {\n if (update.sessionUpdate === 'tool_call' && reply.text !== '') reply.card_since_text = true\n if (update.sessionUpdate !== 'agent_message_chunk') return\n reply.sent = true\n if (update.content.type !== 'text' || update.content.text === '') return\n reply.text += reply.card_since_text ? `\\n\\n${update.content.text}` : update.content.text\n reply.card_since_text = false\n}\n\n/**\n * Append a turn to the session's history: the user's text, then the reply\n * text the client was sent, when there was any. A cancelled turn marks\n * whichever of the two came last.\n */\nfunction record_exchange(history: AcpHistoryEntry[], user_text: string, reply_text: string, cancelled: boolean): void {\n const stop = cancelled ? { cancelled: true as const } : {}\n if (reply_text === '') history.push({ role: 'user', text: user_text, ...stop })\n else history.push({ role: 'user', text: user_text }, { role: 'agent', text: reply_text, ...stop })\n}\n\n/**\n * Settle a run's result into a value, so a run that fails while the turn is\n * still sending never surfaces as an unhandled rejection.\n */\nfunction settle<o>(result: Promise<o>): Promise<Settled<o>> {\n return result.then(\n (output): Settled<o> => ({ ok: true, output }),\n (error: unknown): Settled<o> => ({ ok: false, error }),\n )\n}\n\n/**\n * Say on stderr that the run outran the client and dropped events, since the\n * reply the client shows is missing text from that point on.\n */\nfunction warn_dropped(event: TrajectoryEvent): void {\n process.stderr.write(\n `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`,\n )\n}\n\n/**\n * Send each run event's updates in order, and tell the session's card sync\n * once all of an event's updates have gone out. Once the turn is cancelled\n * nothing more is sent, and leaving the loop closes the run's event stream.\n */\nasync function forward<i, o>(\n events: AsyncIterable<TrajectoryEvent>,\n config: ServeAcpConfig<i, o>,\n record: SessionRecord<i, o>,\n cancelled: AbortSignal,\n send: SendUpdate,\n): Promise<void> {\n const state = create_acp_mapper_state({ stream: config.stream, session: record.session })\n const to_updates = config.to_updates ?? to_session_updates\n for await (const event of events) {\n if (event.kind === 'events_dropped') warn_dropped(event)\n const updates = to_updates(event, state)\n for (const update of updates) {\n if (cancelled.aborted) return\n await send(update)\n }\n record.cards.sent(event, updates)\n }\n}\n\n/**\n * Run the flow for one turn, forward its updates, and record the exchange.\n * The run has always settled by the time this returns or throws, so a turn\n * never leaves a run behind.\n */\nasync function run_turn<i, o>(\n config: ServeAcpConfig<i, o>,\n record: SessionRecord<i, o>,\n prompt: ReadonlyArray<ContentBlock>,\n cancelled: AbortSignal,\n send: SendUpdate,\n): Promise<PromptResponse> {\n const turn: AcpTurn = {\n session_id: record.session.id,\n cwd: record.session.cwd,\n text: turn_text(prompt),\n prompt,\n history: [...record.history],\n }\n const reply: Reply = { sent: false, text: '', card_since_text: false }\n const send_update: SendUpdate = async (update) => {\n await send(update)\n note_reply(reply, update)\n }\n const stop = new AbortController()\n // A turn cancelled before its consumer caught up leaves previews nobody\n // took, and raw ids repeat from turn to turn.\n reset_previews(record.session)\n const handle = run.stream(record.flow, turn_input(config, turn), {\n abort: AbortSignal.any([cancelled, stop.signal]),\n install_signal_handlers: false,\n // Every event the run queues for the consumer passes through here first,\n // which is how an approval knows what the client hasn't been sent yet.\n trajectory: record.cards.start(config.trajectory),\n })\n const outcome = settle(handle.result)\n try {\n await forward(handle.events, config, record, cancelled, send_update)\n const result = await outcome\n if (!cancelled.aborted) {\n if (!result.ok) throw result.error\n const final_text = (config.to_text ?? default_to_text)(result.output)\n if (!reply.sent && final_text !== '') await send_update(agent_message(final_text))\n }\n } catch (err: unknown) {\n stop.abort(new aborted_error('the prompt turn failed before its run finished'))\n await outcome\n if (!cancelled.aborted) throw err\n }\n record_exchange(record.history, turn.text, reply.text, cancelled.aborted)\n return { stopReason: cancelled.aborted ? 'cancelled' : 'end_turn' }\n}\n\n/**\n * Run one prompt turn and answer with its stop reason. A new prompt cancels\n * the session's turn in flight and waits for it to settle first, so it sees\n * that turn in its history and never runs beside it.\n */\nexport async function prompt_turn<i, o>(\n config: ServeAcpConfig<i, o>,\n record: SessionRecord<i, o>,\n prompt: ReadonlyArray<ContentBlock>,\n request_signal: AbortSignal,\n send: SendUpdate,\n): Promise<PromptResponse> {\n const previous = record.last_turn\n const cancel = new AbortController()\n const { promise: settled, resolve: settle_turn } = Promise.withResolvers<void>()\n record.last_turn = { cancel, settled }\n try {\n if (previous !== null) {\n previous.cancel.abort(new aborted_error('a new prompt replaced the turn'))\n await previous.settled\n }\n const signals = [cancel.signal, request_signal, ...(config.abort === undefined ? [] : [config.abort])]\n return await run_turn(config, record, prompt, AbortSignal.any(signals), send)\n } finally {\n settle_turn()\n }\n}\n\n/**\n * Cancel the session's latest turn on the client's `session/cancel`.\n */\nexport function cancel_turn<i, o>(record: SessionRecord<i, o>): void {\n record.last_turn?.cancel.abort(new aborted_error('the ACP client cancelled the turn'))\n}\n","/**\n * Typed errors for the ACP adapter.\n *\n * Listed alongside src/mcp/errors.ts in the `no-class` rule ignores:\n * `instanceof` branching is how callers tell a missing optional peer apart\n * from a failure inside a prompt turn.\n */\n\nexport class acp_sdk_missing_error extends Error {\n readonly kind = 'acp_sdk_missing_error' as const;\n constructor(\n message = '@agentclientprotocol/sdk is required for fascicle/acp; install it with its zod peer: pnpm add @agentclientprotocol/sdk zod',\n ) {\n super(message)\n this.name = 'acp_sdk_missing_error'\n }\n}\n","/**\n * Lazy loader for the optional `@agentclientprotocol/sdk` peer.\n *\n * The adapter needs SDK values (the `agent()` builder, `ndJsonStream`,\n * `RequestError`), so it imports the SDK dynamically rather than statically:\n * a consumer can import `fascicle/acp` without the SDK installed and only pays\n * for it when they serve a flow. A missing peer surfaces as a typed\n * `acp_sdk_missing_error` with install guidance, mirroring\n * src/mcp/sdk_loader.ts.\n *\n * The package root is the SDK's stable protocol v1 entry; v2 sits under its\n * `experimental/` subpaths, which fascicle never imports. The SDK imports\n * `zod/v4` at runtime as its own peer, so a missing zod fails here too, and\n * the error names both installs.\n */\n\nimport { acp_sdk_missing_error } from './errors.js'\n\n/**\n * Dynamically imports the `@agentclientprotocol/sdk` v1 entry, throwing a\n * typed `acp_sdk_missing_error` when the optional peer (or its zod peer) is\n * not installed.\n */\nexport async function load_acp_sdk() {\n try {\n return await import('@agentclientprotocol/sdk')\n } catch (err: unknown) {\n const detail = err instanceof Error ? err.message : String(err)\n throw new acp_sdk_missing_error(\n `@agentclientprotocol/sdk is required for fascicle/acp; install it with its zod peer: pnpm add @agentclientprotocol/sdk zod (cause: ${detail})`,\n )\n }\n}\n","/**\n * acp_agent: the ACP agent app that answers each prompt turn by running a\n * flow.\n *\n * It registers the protocol v1 handlers and holds the sessions, and connects\n * to anything the SDK can: `serve_acp`'s stdio streams, or an in-process\n * `client()` in a test. It doesn't own the process, so it leaves the console\n * and the engine alone; `serve_acp` handles both.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { AgentApp, AgentContext, ClientCapabilities, SessionUpdate } from '@agentclientprotocol/sdk'\nimport { create_card_sync, message_of, session_approver } from './approve.js'\nimport type { PermissionAsker } from './approve.js'\nimport { config_options, MODE_CONFIG_ID, mode_offer, mode_state, session_modes, unknown_mode_message } from './modes.js'\nimport type { ModeOffer, SessionModes } from './modes.js'\nimport { cancel_turn, prompt_turn } from './prompt_turn.js'\nimport type { SessionRecord } from './prompt_turn.js'\nimport { load_acp_sdk } from './sdk_loader.js'\nimport { resolve_roots } from './tools/containment.js'\nimport type { AcpMode, AcpSession, ServeAcpConfig } from './types.js'\n\ntype AcpSdk = Awaited<ReturnType<typeof load_acp_sdk>>\n\n/** A session as the agent holds it: what a turn needs, and its mode. */\ntype AgentSession<i, o> = SessionRecord<i, o> & { readonly modes: SessionModes }\n\nconst ONE_CONNECTION =\n 'acp_agent: this app already serves a connection; build an app for each connection, as serve_acp does'\n\n/**\n * Turn a failure inside a handler into a JSON-RPC error that carries its\n * message. The SDK reports a plain thrown `Error` as a bare \"Internal error\",\n * which tells the user in the client nothing about what went wrong.\n */\nfunction internal_error(sdk: AcpSdk, err: unknown): Error {\n return sdk.RequestError.internalError(undefined, message_of(err))\n}\n\n/**\n * A function that sends one update to the client for one session.\n */\nfunction sender(sdk: AcpSdk, client: AgentContext, sessionId: string): (update: SessionUpdate) => Promise<void> {\n return (update) => client.notify(sdk.methods.client.session.update, { sessionId, update })\n}\n\n/**\n * A function that asks the client to approve one tool call. The SDK\n * withdraws the request with `$/cancel_request` once `cancel` fires, which\n * is the turn's abort, so a cancelled turn takes its prompt down with it.\n */\nfunction permission_asker(sdk: AcpSdk, client: AgentContext): PermissionAsker {\n return (request, cancel) =>\n client.request(sdk.methods.client.session.requestPermission, request, { cancellationSignal: cancel })\n}\n\n/**\n * The mode a client asked for, or an invalid-params error naming the modes\n * the agent offers, for a mode it doesn't know and one it leaves out alike.\n * `field` is the param the id arrived in, for the error's data.\n */\nfunction requested_mode(\n sdk: AcpSdk,\n offer: ModeOffer,\n modes: SessionModes,\n id: unknown,\n field: 'modeId' | 'value',\n): AcpMode {\n if (modes.offers(id)) return id\n throw sdk.RequestError.invalidParams({ [field]: id }, unknown_mode_message(id, offer))\n}\n\n/**\n * The additional directories a client sent with a session request, or, from\n * an agent whose config sets `additional_directories: false`, an\n * invalid-params error refusing them. Every session request that carries\n * `additionalDirectories` goes through this check before its roots resolve,\n * so each one refuses them the same way. The protocol reads an empty list as\n * none, so an empty list passes.\n */\nfunction requested_directories(\n sdk: AcpSdk,\n config: { readonly additional_directories?: boolean | undefined },\n method: string,\n directories: ReadonlyArray<string> = [],\n): ReadonlyArray<string> {\n if (config.additional_directories !== false || directories.length === 0) return directories\n throw sdk.RequestError.invalidParams(\n { additionalDirectories: directories },\n `this agent works in cwd alone and takes no additional directories; send ${method} without additionalDirectories`,\n )\n}\n\n/**\n * Build the ACP agent app that answers each prompt turn by running the\n * config's flow, with its handlers registered and not yet connected.\n *\n * An app serves one connection for its life, since its sessions and the\n * client's capabilities aren't scoped to a connection. A second `connect`\n * throws, and so, for a server that routes a second client to the same app\n * and runs `initialize` before any connect hook, does a second `initialize`,\n * before it can overwrite the first client's capabilities.\n */\nexport async function acp_agent<i, o>(config: ServeAcpConfig<i, o>): Promise<AgentApp> {\n // A bad config fails here, before the SDK loads, so the error names it.\n const offer = mode_offer(config)\n const sdk = await load_acp_sdk()\n const sessions = new Map<string, AgentSession<i, o>>()\n let client_capabilities: ClientCapabilities = {}\n let connected = false\n let initialized = false\n const session_of = (sessionId: string): AgentSession<i, o> => {\n const record = sessions.get(sessionId)\n if (record !== undefined) return record\n throw sdk.RequestError.invalidParams({ sessionId }, `unknown session ${sessionId}; start one with session/new first`)\n }\n return sdk\n .agent()\n .onConnect(() => {\n if (connected) throw new Error(ONE_CONNECTION)\n connected = true\n })\n .onRequest('initialize', (ctx) => {\n if (initialized) throw sdk.RequestError.invalidRequest(undefined, ONE_CONNECTION)\n initialized = true\n client_capabilities = ctx.params.clientCapabilities ?? {}\n return {\n protocolVersion: sdk.PROTOCOL_VERSION,\n agentInfo: { name: config.name, version: config.version ?? '0.0.0' },\n // Embedded context lets a file the user @-mentions arrive with its\n // text, rather than as a bare URI the flow has no way to read. The\n // agent advertises additional directories, which let a client widen\n // the workspace past `cwd`, unless the config sets\n // `additional_directories: false`.\n agentCapabilities: {\n loadSession: false,\n promptCapabilities: { embeddedContext: true },\n sessionCapabilities: config.additional_directories === false ? {} : { additionalDirectories: {} },\n },\n // Providers authenticate with what the launched process can see;\n // ACP v1 gives the client no way to hand the agent credentials.\n authMethods: [],\n }\n })\n .onRequest(\n 'authenticate',\n // Stryker disable next-line ArrowFunction: the SDK answers an authenticate handler's undefined with {}, so both read the same on the wire.\n () => ({}),\n )\n .onRequest('session/new', async (ctx) => {\n // `mcpServers` is accepted and ignored until a flow can be handed them.\n const { cwd } = ctx.params\n const additional_directories = requested_directories(sdk, config, 'session/new', ctx.params.additionalDirectories)\n // The roots resolve once, here, so every containment check compares\n // against the same real paths for the life of the session.\n const roots = await resolve_roots([cwd, ...additional_directories]).catch((err: unknown) => {\n throw sdk.RequestError.invalidParams({ cwd, additionalDirectories: additional_directories }, message_of(err))\n })\n const id = randomUUID()\n const modes = session_modes(offer, sender(sdk, ctx.client, id))\n const cards = create_card_sync()\n const approver = session_approver({ modes, cards, ask: permission_asker(sdk, ctx.client) })\n const session: AcpSession = {\n id,\n cwd,\n additional_directories,\n roots,\n client_capabilities,\n mode: modes.current,\n approve: (request) => approver(session, request),\n }\n try {\n const flow = typeof config.flow === 'function' ? config.flow(session) : config.flow\n sessions.set(id, { session, flow, history: [], cards, last_turn: null, modes })\n } catch (err: unknown) {\n throw internal_error(sdk, err)\n }\n return {\n sessionId: id,\n modes: mode_state(offer, modes.current()),\n configOptions: config_options(offer, modes.current()),\n }\n })\n .onRequest('session/prompt', async (ctx) => {\n const { sessionId, prompt } = ctx.params\n const record = session_of(sessionId)\n try {\n return await prompt_turn(config, record, prompt, ctx.signal, sender(sdk, ctx.client, sessionId))\n } catch (err: unknown) {\n throw internal_error(sdk, err)\n }\n })\n .onRequest('session/set_mode', async (ctx) => {\n const { sessionId, modeId } = ctx.params\n const { modes } = session_of(sessionId)\n await modes.switch_to(requested_mode(sdk, offer, modes, modeId, 'modeId'))\n return {}\n })\n .onRequest('session/set_config_option', async (ctx) => {\n const { sessionId, configId, value } = ctx.params\n const { modes } = session_of(sessionId)\n if (configId !== MODE_CONFIG_ID) {\n throw sdk.RequestError.invalidParams(\n { configId },\n `unknown config option ${configId}; the only one is ${MODE_CONFIG_ID}`,\n )\n }\n await modes.switch_to(requested_mode(sdk, offer, modes, value, 'value'))\n return { configOptions: config_options(offer, modes.current()) }\n })\n .onNotification('session/cancel', (ctx) => {\n const record = sessions.get(ctx.params.sessionId)\n if (record !== undefined) cancel_turn(record)\n })\n}\n","/**\n * The ACP agent's serving loop, minus the process.\n *\n * `serve_streams` is everything `serve_acp` does once the console and the\n * signals are handled: connect `acp_agent` to a pair of ndjson byte streams,\n * hold the connection until the client hangs up or `shutdown` fires, then\n * dispose the engine. It takes its streams as arguments, mirroring\n * `execute_stdio` under `run_stdio`, so the disconnect path is unit-tested\n * here and the thin glue in `serve_acp.ts` owns the real stdin and stdout.\n *\n * Closing the connection is what aborts the runs: the SDK aborts every\n * in-flight request's signal as it closes, and each prompt turn's run\n * listens on its request's signal. So by the time `closed` resolves, every\n * active run has seen its abort, and only then is the engine disposed.\n */\n\nimport { acp_agent } from './acp_agent.js'\nimport { load_acp_sdk } from './sdk_loader.js'\nimport type { ServeAcpConfig } from './types.js'\n\ntype AcpServeIo = {\n /** What the client sends, as ndjson bytes; stdin under `serve_acp`. */\n readonly input: ReadableStream<Uint8Array>\n /** Where the protocol goes, as ndjson bytes; stdout under `serve_acp`. */\n readonly output: WritableStream<Uint8Array>\n /** Ends the connection from the agent's side, aborting every active run with its reason. */\n readonly shutdown?: AbortSignal | undefined\n}\n\n/**\n * Serve the config's flow as an ACP agent over `io` until the client\n * disconnects or `io.shutdown` fires, then dispose the engine once every\n * active run has been aborted.\n */\nexport async function serve_streams<i, o>(config: ServeAcpConfig<i, o>, io: AcpServeIo): Promise<void> {\n const sdk = await load_acp_sdk()\n const app = await acp_agent(config)\n const connection = app.connect(sdk.ndJsonStream(io.output, io.input))\n const { shutdown } = io\n if (shutdown !== undefined) {\n // A signal can land while the SDK loads, before there is a listener to hear it.\n if (shutdown.aborted) connection.close(shutdown.reason)\n else shutdown.addEventListener('abort', () => connection.close(shutdown.reason))\n }\n await connection.closed\n await config.engine?.dispose()\n}\n","/**\n * Process glue for serving a flow as an ACP agent over stdio.\n *\n * Binds `serve_streams` to the real process: ndjson in on stdin, the\n * protocol out on stdout, and nothing else on stdout ever. A stray log line\n * from a flow or a dependency would corrupt the protocol stream, so\n * `console.log`, `console.info`, `console.debug`, `console.dir`, and\n * `console.dirxml` go to stderr for the life of the process.\n *\n * SIGTERM and SIGINT abort every active run, dispose the engine, and exit.\n * A host that ends the agent with a signal instead of closing stdin would\n * otherwise leave a run's work going after the editor has closed, since each\n * turn runs with the runner's own signal handlers off. The handlers are\n * one-shot, so a second Ctrl-C falls through to Node's default and kills the\n * process outright when a shutdown hangs.\n *\n * Excluded from mutation testing as process glue (see stryker.config.mjs);\n * the spawn tests in `__tests__/e2e/` exercise it for real.\n */\n\nimport { constants } from 'node:os'\nimport { Readable, Writable } from 'node:stream'\nimport { aborted_error } from '#core'\nimport { route_console_to_stderr } from '#process'\nimport { serve_streams } from './serve_streams.js'\nimport type { ServeAcpConfig } from './types.js'\n\n/**\n * Serve a flow as an ACP agent over stdin and stdout until the client\n * disconnects, disposing the engine once every active run has been aborted.\n * A SIGTERM or SIGINT does the same, then exits with the signal's code.\n */\nexport async function serve_acp<i, o>(config: ServeAcpConfig<i, o>): Promise<void> {\n // Leave stdout to the protocol alone.\n route_console_to_stderr(console, process.stderr)\n const shutdown = new AbortController()\n let received: NodeJS.Signals | null = null\n const on_signal = (signal: NodeJS.Signals): void => {\n received = signal\n shutdown.abort(new aborted_error(`received ${signal}`, { reason: { signal } }))\n }\n process.once('SIGTERM', on_signal)\n process.once('SIGINT', on_signal)\n try {\n await serve_streams(config, {\n input: Readable.toWeb(process.stdin),\n output: Writable.toWeb(process.stdout),\n shutdown: shutdown.signal,\n })\n } finally {\n process.off('SIGTERM', on_signal)\n process.off('SIGINT', on_signal)\n }\n // Exiting here rather than draining tells the host a signal ended the\n // agent, and leaves no wait on a flow that ignored its abort.\n if (received !== null) process.exit(128 + constants.signals[received])\n}\n"],"mappings":";;;;;;;;;;;;;;;AAsBA,MAAa,iBAAiB;;AAY9B,MAAM,QAA8C;CAClD,QAAQ;EACN,MAAM;EACN,aAAa;EACb,MAAM;GAAE,MAAM;GAAM,SAAS;EAAK;CACpC;CACA,cAAc;EACZ,MAAM;EACN,aAAa;EACb,MAAM;GAAE,MAAM;GAAO,SAAS;EAAK;CACrC;CACA,MAAM;EACJ,MAAM;EACN,aAAa;EACb,MAAM;GAAE,MAAM;GAAO,SAAS;EAAM;CACtC;AACF;;;;;AAMA,SAAgB,YAAY,IAA4B;CACtD,OAAO,OAAO,OAAO,YAAY,OAAO,OAAO,OAAO,EAAE;AAC1D;;AAaA,MAAM,aAAa,OAAO,KAAK,KAAK,CAAC,CAAC,KAAK,IAAI;;;;;;;;AAS/C,SAAgB,WAAW,QAGb;CAEZ,MAAM,SAAiC,OAAO,SAAS,OAAO,KAAK,KAAK;CACxE,IAAI,OAAO,WAAW,GACpB,MAAM,IAAI,MACR,mDAAmD,WAAW,wCAChE;CAEF,KAAK,MAAM,SAAS,QAClB,IAAI,CAAC,YAAY,KAAK,GACpB,MAAM,IAAI,MAAM,0BAA0B,KAAK,UAAU,KAAK,EAAE,mCAAmC,YAAY;CAGnH,MAAM,QAAQ,OAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,OAAsB,OAAO,SAAS,EAAE,CAAC;CAClF,MAAM,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BAAwB,SAAS,QAAQ,MAAM;CAC/C,MAAM,WAAW,IAAI,gBAAgB;CACrC,IAAI,WAAkC;CACtC,MAAM,aAAa,WAAiC;EAClD,WAAW;EACX,SAAS,MAAM,IAAI,cAAc,YAAY,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC;CAChF;CACA,QAAQ,KAAK,WAAW,SAAS;CACjC,QAAQ,KAAK,UAAU,SAAS;CAChC,IAAI;EACF,MAAM,cAAc,QAAQ;GAC1B,OAAO,SAAS,MAAM,QAAQ,KAAK;GACnC,QAAQ,SAAS,MAAM,QAAQ,MAAM;GACrC,UAAU,SAAS;EACrB,CAAC;CACH,UAAU;EACR,QAAQ,IAAI,WAAW,SAAS;EAChC,QAAQ,IAAI,UAAU,SAAS;CACjC;CAGA,IAAI,aAAa,MAAM,QAAQ,KAAK,MAAM,UAAU,QAAQ,SAAS;AACvE"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fascicle",
|
|
3
|
-
"version": "0.16.
|
|
3
|
+
"version": "0.16.2",
|
|
4
4
|
"description": "Compose agents like plain values. A TypeScript toolkit that wires LLM calls, tools, and functions into typed steps over eight providers. No framework, no ambient state.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agents",
|
|
@@ -229,7 +229,7 @@
|
|
|
229
229
|
"@vvago/vale": "3.24.0",
|
|
230
230
|
"ai": "7.0.138",
|
|
231
231
|
"arktype": "2.2.8",
|
|
232
|
-
"checkride": "0.
|
|
232
|
+
"checkride": "0.15.0",
|
|
233
233
|
"cspell": "10.3.6",
|
|
234
234
|
"fallow": "3.33.1",
|
|
235
235
|
"markdownlint-cli2": "0.23.3",
|