fascicle 0.18.1 → 0.19.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +66 -0
- package/README.md +27 -1
- package/dist/AGENTS.md +11 -10
- package/dist/a2a.d.ts +358 -0
- package/dist/a2a.js +2234 -0
- package/dist/a2a.js.map +1 -0
- package/dist/acp.d.ts +120 -9
- package/dist/acp.js +927 -154
- package/dist/acp.js.map +1 -1
- package/dist/adapters-DYFauXE1.js +1147 -0
- package/dist/adapters-DYFauXE1.js.map +1 -0
- package/dist/adapters.d.ts +124 -36
- package/dist/adapters.js +1 -1
- package/dist/agents.d.ts +2 -2
- package/dist/agents.js +1 -1
- package/dist/{core-BH7sWpEG.js → core-xTtRZqdb.js} +217 -99
- package/dist/core-xTtRZqdb.js.map +1 -0
- package/dist/diagram_bin.js +1 -1
- package/dist/durable-CgU0kO2H.d.ts +144 -0
- package/dist/{engine-fOjYHcv6.js → engine-B_Yl7acj.js} +128 -42
- package/dist/engine-B_Yl7acj.js.map +1 -0
- package/dist/index.d.ts +9 -136
- package/dist/index.js +6 -5
- package/dist/index.js.map +1 -1
- package/dist/{invoke-7iu8db6V.js → invoke-Bbk0RuVL.js} +3 -3
- package/dist/{invoke-7iu8db6V.js.map → invoke-Bbk0RuVL.js.map} +1 -1
- package/dist/{leading_system-BeQUSAim.js → leading_system-m-x7HzbQ.js} +16 -4
- package/dist/leading_system-m-x7HzbQ.js.map +1 -0
- package/dist/mcp-D1hN5ywq.js +662 -0
- package/dist/mcp-D1hN5ywq.js.map +1 -0
- package/dist/mcp.d.ts +115 -5
- package/dist/mcp.js +2 -2
- package/dist/otel.d.ts +1 -1
- package/dist/stdio.d.ts +1 -1
- package/dist/stdio.js +2 -2
- package/dist/testing.d.ts +7 -5
- package/dist/testing.js +618 -318
- package/dist/testing.js.map +1 -1
- package/dist/{types-BUXt_zgJ.d.ts → types-BtRpSctv.d.ts} +38 -5
- package/dist/{types-Dk9tLpUq.d.ts → types-CDTW7XWB.d.ts} +2 -2
- package/dist/ui.d.ts +2 -2
- package/dist/viewer.js +2 -2
- package/dist/web.d.ts +1 -1
- package/package.json +18 -6
- package/dist/adapters-CpKpDk7r.js +0 -461
- package/dist/adapters-CpKpDk7r.js.map +0 -1
- package/dist/core-BH7sWpEG.js.map +0 -1
- package/dist/engine-fOjYHcv6.js.map +0 -1
- package/dist/leading_system-BeQUSAim.js.map +0 -1
- package/dist/mcp-CHJ88HiG.js +0 -262
- package/dist/mcp-CHJ88HiG.js.map +0 -1
package/dist/acp.js
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
import { n as is_record$1, t as as_record } from "./records-Btlmvunj.js";
|
|
2
|
-
import { n as mcp_client } from "./mcp-
|
|
2
|
+
import { n as mcp_client } from "./mcp-D1hN5ywq.js";
|
|
3
3
|
import { a as read_file_tool, c as resolve_roots, i as is_binary, l as shown_path, n as search_tool, o as contain_writable, r as list_files_tool, s as error_code } from "./search-BZagxXtd.js";
|
|
4
4
|
import { t as json_schema_to_standard } from "./json_schema_to_standard-BstoXjM8.js";
|
|
5
|
-
import { j as aborted_error, w as run } from "./core-
|
|
5
|
+
import { j as aborted_error, w as run } from "./core-xTtRZqdb.js";
|
|
6
6
|
import { t as route_console_to_stderr } from "./console-B1ozi_ii.js";
|
|
7
|
-
import { randomUUID } from "node:crypto";
|
|
8
|
-
import { mkdir, open, readFile, readdir, rename, stat, writeFile } from "node:fs/promises";
|
|
7
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
8
|
+
import { mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
9
9
|
import { dirname, join, resolve } from "node:path";
|
|
10
|
-
import {
|
|
10
|
+
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { constants as constants$1 } from "node:os";
|
|
11
12
|
import { spawn } from "node:child_process";
|
|
13
|
+
import { Readable, Writable } from "node:stream";
|
|
12
14
|
import { isUtf8 } from "node:buffer";
|
|
13
15
|
import { StringDecoder } from "node:string_decoder";
|
|
14
|
-
import { Readable, Writable } from "node:stream";
|
|
15
16
|
// src/acp/modes.ts
|
|
16
17
|
/** The id of the config option that carries the mode. */
|
|
17
18
|
const MODE_CONFIG_ID = "mode";
|
|
@@ -152,6 +153,39 @@ function session_modes(offer, send, start, others = () => []) {
|
|
|
152
153
|
}
|
|
153
154
|
// src/acp/mcp_servers.ts
|
|
154
155
|
/**
|
|
156
|
+
* mcp_servers: the MCP servers a client sends with a session, connected
|
|
157
|
+
* for the session's flow.
|
|
158
|
+
*
|
|
159
|
+
* Zed sends the MCP servers its user configured with every session. An
|
|
160
|
+
* agent whose config sets `mcp_servers` connects to each one through
|
|
161
|
+
* `mcp_client` from fascicle/mcp and hands their tools to the flow builder.
|
|
162
|
+
* A server that can't be reached is left out with a warning on stderr
|
|
163
|
+
* rather than failing the session, so one broken entry in the editor's
|
|
164
|
+
* settings can't stop every thread, and the warning is kept for a client
|
|
165
|
+
* that shows notices. A server's `env` and `headers` values are
|
|
166
|
+
* credentials, so a warning carries the server's name and its error with
|
|
167
|
+
* those values cut out, and nothing else of the server. The one value that
|
|
168
|
+
* stays is a value under three characters, which is too short to tell from
|
|
169
|
+
* the message's own words and numbers.
|
|
170
|
+
*
|
|
171
|
+
* Each tool is named `mcp__<server>__<tool>`, the form Claude Code uses, so
|
|
172
|
+
* two servers' tools don't collide and none takes a workspace tool's name.
|
|
173
|
+
* A provider takes a tool name of 64 characters at most, and the engine
|
|
174
|
+
* refuses two tools under one name, so a name that runs longer, or that
|
|
175
|
+
* another tool already took once the server's name was cleaned up, is cut
|
|
176
|
+
* and ends in a hash of its server and tool. The tool still calls its
|
|
177
|
+
* server under the name the server gave it.
|
|
178
|
+
*
|
|
179
|
+
* An MCP tool can do anything its server can, so each one asks before it
|
|
180
|
+
* runs whenever the session's mode asks before a command. The approval
|
|
181
|
+
* knows these calls the way it knows the workspace tools', by the input
|
|
182
|
+
* their `needs_approval` was asked about, so a flow's own tool that copies
|
|
183
|
+
* one's name doesn't pass for it.
|
|
184
|
+
*
|
|
185
|
+
* The connections last as long as the session, and close when the client
|
|
186
|
+
* closes the session or the connection.
|
|
187
|
+
*/
|
|
188
|
+
/**
|
|
155
189
|
* The MCP transports the agent tells a client it speaks beside stdio, which
|
|
156
190
|
* every agent takes.
|
|
157
191
|
*/
|
|
@@ -159,8 +193,28 @@ const MCP_CAPABILITIES = { http: true };
|
|
|
159
193
|
/** The connections of a session with no MCP servers. */
|
|
160
194
|
const NO_MCP = {
|
|
161
195
|
tools: [],
|
|
162
|
-
close: async () => {}
|
|
196
|
+
close: async () => {},
|
|
197
|
+
warnings: []
|
|
163
198
|
};
|
|
199
|
+
/** The longest tool name a provider takes. */
|
|
200
|
+
const NAME_LIMIT = 64;
|
|
201
|
+
/**
|
|
202
|
+
* The shortest `env` or `headers` value that's cut out of a warning
|
|
203
|
+
* wherever it appears. A shorter one, such as `true` or `8080`, is cut only
|
|
204
|
+
* where it stands whole, since cutting it out of the middle of every word
|
|
205
|
+
* and number would shred the message it happens to appear in.
|
|
206
|
+
*/
|
|
207
|
+
const SECRET_LENGTH = 8;
|
|
208
|
+
/**
|
|
209
|
+
* The shortest `env` or `headers` value that's cut out of a warning at
|
|
210
|
+
* all. A value of one or two characters, such as `1` or `no`, stands whole
|
|
211
|
+
* in ordinary error text (the `1` of `exit 1`, the last octet of
|
|
212
|
+
* `127.0.0.1`), so cutting it hides the error and protects nothing worth
|
|
213
|
+
* calling a secret.
|
|
214
|
+
*/
|
|
215
|
+
const SHORTEST_CUT = 3;
|
|
216
|
+
/** How many characters of a hash end a shortened name. */
|
|
217
|
+
const HASH_LENGTH = 8;
|
|
164
218
|
/** The validated inputs each session's MCP tools were asked about. */
|
|
165
219
|
const asked$1 = /* @__PURE__ */ new WeakMap();
|
|
166
220
|
/**
|
|
@@ -197,15 +251,46 @@ function client_config(server, cwd) {
|
|
|
197
251
|
};
|
|
198
252
|
}
|
|
199
253
|
/**
|
|
200
|
-
*
|
|
201
|
-
*
|
|
254
|
+
* `text` with one `env` or `headers` value cut out. A short value is cut
|
|
255
|
+
* where no letter, digit, or underscore adjoins it, and a value under
|
|
256
|
+
* three characters is left where it is.
|
|
257
|
+
*/
|
|
258
|
+
function without_value(text, value) {
|
|
259
|
+
if (value.length < SHORTEST_CUT) return text;
|
|
260
|
+
if (value.length >= SECRET_LENGTH) return text.replaceAll(value, "[redacted]");
|
|
261
|
+
const literal = value.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
|
|
262
|
+
return text.replaceAll(new RegExp(String.raw`(?<!\w)${literal}(?!\w)`, "g"), "[redacted]");
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* `text` with the `env` and `headers` values of `server` cut out, the
|
|
266
|
+
* longest first, since an error that quotes one would carry it to stderr
|
|
267
|
+
* and to the client.
|
|
268
|
+
*/
|
|
269
|
+
function without_secrets(server, text) {
|
|
270
|
+
return ("command" in server ? server.env : "headers" in server ? server.headers : []).map(({ value }) => value).toSorted((a, b) => b.length - a.length).reduce(without_value, text);
|
|
271
|
+
}
|
|
272
|
+
const NEEDS_AUTHORIZATION = "it answered 401, which means that its entry in your editor's MCP settings sends no token it accepts (fix the entry's headers)";
|
|
273
|
+
/**
|
|
274
|
+
* The warning for a server left out of the session, also written to
|
|
275
|
+
* stderr, for a client that shows no notices. `error` is the server's own
|
|
276
|
+
* failure, which is the part that can quote one of its values.
|
|
277
|
+
*/
|
|
278
|
+
function left_out(server, reason, error) {
|
|
279
|
+
const description = `${reason}${error === void 0 ? "" : ` (${without_secrets(server, error)})`}, so its tools are left out of the session`;
|
|
280
|
+
warn(`MCP server ${server.name}: ${description}`);
|
|
281
|
+
return {
|
|
282
|
+
title: `MCP server ${server.name} isn't connected`,
|
|
283
|
+
description
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Connect to one server, or return the warning that says why it was left
|
|
288
|
+
* out, so the session starts without it. A missing MCP SDK isn't one
|
|
289
|
+
* server's failure, so that error is thrown on.
|
|
202
290
|
*/
|
|
203
291
|
async function connect_server(server, cwd, identity) {
|
|
204
292
|
const config = client_config(server, cwd);
|
|
205
|
-
if (config === void 0)
|
|
206
|
-
warn(`MCP server ${server.name} uses a transport this agent doesn't speak, so its tools are left out of the session`);
|
|
207
|
-
return;
|
|
208
|
-
}
|
|
293
|
+
if (config === void 0) return left_out(server, "it uses a transport this agent doesn't speak");
|
|
209
294
|
const name_prefix = `mcp__${server.name.replaceAll(/[^\w-]/g, "_")}__`;
|
|
210
295
|
try {
|
|
211
296
|
return await mcp_client(config, {
|
|
@@ -213,9 +298,9 @@ async function connect_server(server, cwd, identity) {
|
|
|
213
298
|
name_prefix
|
|
214
299
|
});
|
|
215
300
|
} catch (err) {
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
return;
|
|
301
|
+
if (err instanceof Error && err.name === "mcp_sdk_missing_error") throw err;
|
|
302
|
+
if (err instanceof Error && err.name === "mcp_auth_required_error") return left_out(server, NEEDS_AUTHORIZATION);
|
|
303
|
+
return left_out(server, "it couldn't be reached", err instanceof Error ? err.message : String(err));
|
|
219
304
|
}
|
|
220
305
|
}
|
|
221
306
|
/**
|
|
@@ -230,18 +315,60 @@ async function close_all(handles) {
|
|
|
230
315
|
}
|
|
231
316
|
}
|
|
232
317
|
/**
|
|
318
|
+
* A tool's name cut to the limit, ending in a hash of the server it came
|
|
319
|
+
* from (by its place in the list and its name as the client sent it) and
|
|
320
|
+
* the name `mcp_client` gave the tool, so two tools that would share a name
|
|
321
|
+
* each get one of their own.
|
|
322
|
+
*/
|
|
323
|
+
function shortened(name, server, index) {
|
|
324
|
+
const hash = createHash("sha256").update(`${index}\0${server.name}\0${name}`).digest("hex").slice(0, HASH_LENGTH);
|
|
325
|
+
return `${name.slice(0, 55)}_${hash}`;
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Whether `value` is a connection instead of the warning that stands in
|
|
329
|
+
* for one.
|
|
330
|
+
*/
|
|
331
|
+
function is_handle(value) {
|
|
332
|
+
return "tools" in value;
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
233
335
|
* Connect to every server the client sent for a session, all at once, and
|
|
234
|
-
* gather their tools
|
|
336
|
+
* gather their tools under names no two of them share and no provider
|
|
337
|
+
* refuses.
|
|
235
338
|
*/
|
|
236
339
|
async function connect_mcp_servers(servers, cwd, identity) {
|
|
237
340
|
if (servers.length === 0) return NO_MCP;
|
|
238
|
-
const
|
|
341
|
+
const settled = await Promise.allSettled(servers.map(async (server) => ({
|
|
342
|
+
server,
|
|
343
|
+
entry: await connect_server(server, cwd, identity)
|
|
344
|
+
})));
|
|
345
|
+
const reached = settled.flatMap((result) => result.status === "fulfilled" ? [result.value] : []);
|
|
346
|
+
const handles = reached.map(({ entry }) => entry).filter(is_handle);
|
|
347
|
+
const failed = settled.find((result) => result.status === "rejected");
|
|
348
|
+
if (failed !== void 0) {
|
|
349
|
+
await close_all(handles);
|
|
350
|
+
throw failed.reason;
|
|
351
|
+
}
|
|
239
352
|
const tools = /* @__PURE__ */ new Map();
|
|
240
|
-
|
|
241
|
-
|
|
353
|
+
const warnings = [];
|
|
354
|
+
reached.forEach(({ server, entry }, index) => {
|
|
355
|
+
if (!is_handle(entry)) {
|
|
356
|
+
warnings.push(entry);
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
for (const tool of entry.tools) {
|
|
360
|
+
const name = tool.name.length > NAME_LIMIT || tools.has(tool.name) ? shortened(tool.name, server, index) : tool.name;
|
|
361
|
+
if (tools.has(name)) warn(`MCP server ${server.name} offers a tool named ${tool.name} twice, so the second one is left out`);
|
|
362
|
+
else tools.set(name, name === tool.name ? tool : {
|
|
363
|
+
...tool,
|
|
364
|
+
name
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
});
|
|
242
368
|
return {
|
|
243
369
|
tools: [...tools.values()],
|
|
244
|
-
close: () => close_all(handles)
|
|
370
|
+
close: () => close_all(handles),
|
|
371
|
+
warnings
|
|
245
372
|
};
|
|
246
373
|
}
|
|
247
374
|
/**
|
|
@@ -1738,6 +1865,77 @@ function to_session_updates(event, state) {
|
|
|
1738
1865
|
if (typeof step_id !== "string" || !is_stream_chunk(chunk)) return [];
|
|
1739
1866
|
return map_chunk(chunk, step_id, state);
|
|
1740
1867
|
}
|
|
1868
|
+
// src/acp/transcript.ts
|
|
1869
|
+
/** The updates about the session, which a turn's record leaves out. */
|
|
1870
|
+
const ABOUT_THE_SESSION = /* @__PURE__ */ new Set([
|
|
1871
|
+
"session_info_update",
|
|
1872
|
+
"usage_update",
|
|
1873
|
+
"notice"
|
|
1874
|
+
]);
|
|
1875
|
+
/**
|
|
1876
|
+
* Whether `update` carries a run of text, which is what gets joined.
|
|
1877
|
+
*/
|
|
1878
|
+
function is_text_chunk(update) {
|
|
1879
|
+
const kind = update.sessionUpdate;
|
|
1880
|
+
if (kind !== "user_message_chunk" && kind !== "agent_message_chunk" && kind !== "agent_thought_chunk") return false;
|
|
1881
|
+
return update.content.type === "text";
|
|
1882
|
+
}
|
|
1883
|
+
/**
|
|
1884
|
+
* Everything about a text chunk but its text, as one string. Two chunks join
|
|
1885
|
+
* only when this matches, so a chunk that belongs to another message stays
|
|
1886
|
+
* its own.
|
|
1887
|
+
*/
|
|
1888
|
+
function rest_of(chunk) {
|
|
1889
|
+
return JSON.stringify({
|
|
1890
|
+
...chunk,
|
|
1891
|
+
content: {
|
|
1892
|
+
...chunk.content,
|
|
1893
|
+
text: ""
|
|
1894
|
+
}
|
|
1895
|
+
});
|
|
1896
|
+
}
|
|
1897
|
+
/**
|
|
1898
|
+
* `first` with the text of `second` after its own.
|
|
1899
|
+
*/
|
|
1900
|
+
function joined(first, second) {
|
|
1901
|
+
if (first.content.type !== "text" || second.content.type !== "text") return first;
|
|
1902
|
+
return {
|
|
1903
|
+
...first,
|
|
1904
|
+
content: {
|
|
1905
|
+
...first.content,
|
|
1906
|
+
text: first.content.text + second.content.text
|
|
1907
|
+
}
|
|
1908
|
+
};
|
|
1909
|
+
}
|
|
1910
|
+
/**
|
|
1911
|
+
* Add `update` to `updates`, joined onto the last one when both are text
|
|
1912
|
+
* chunks that differ only in their text.
|
|
1913
|
+
*/
|
|
1914
|
+
function append(updates, update) {
|
|
1915
|
+
const last = updates.at(-1);
|
|
1916
|
+
if (last !== void 0 && is_text_chunk(last) && is_text_chunk(update) && rest_of(last) === rest_of(update)) {
|
|
1917
|
+
updates[updates.length - 1] = joined(last, update);
|
|
1918
|
+
return;
|
|
1919
|
+
}
|
|
1920
|
+
updates.push(structuredClone(update));
|
|
1921
|
+
}
|
|
1922
|
+
/**
|
|
1923
|
+
* Start a turn's record with the prompt the client sent, one
|
|
1924
|
+
* `user_message_chunk` for each block, with adjacent text joined.
|
|
1925
|
+
*/
|
|
1926
|
+
function create_transcript(prompt) {
|
|
1927
|
+
const updates = [];
|
|
1928
|
+
for (const content of prompt) append(updates, {
|
|
1929
|
+
sessionUpdate: "user_message_chunk",
|
|
1930
|
+
content
|
|
1931
|
+
});
|
|
1932
|
+
return {
|
|
1933
|
+
note: (update) => {
|
|
1934
|
+
if (!ABOUT_THE_SESSION.has(update.sessionUpdate)) append(updates, update);
|
|
1935
|
+
},
|
|
1936
|
+
updates: () => updates
|
|
1937
|
+
};
|
|
1938
|
+
}
|
|
1741
1939
|
// src/acp/usage.ts
|
|
1742
1940
|
/**
|
|
1743
1941
|
* A session's usage before its first turn.
|
|
@@ -1998,11 +2196,42 @@ async function forward(events, config, record, cancelled, send) {
|
|
|
1998
2196
|
return finish;
|
|
1999
2197
|
}
|
|
2000
2198
|
/**
|
|
2199
|
+
* The finish reason of a model call that threw because it ended before its
|
|
2200
|
+
* schema validated, or undefined for any other failure. The engine throws
|
|
2201
|
+
* `incomplete_generation_error` for that, known here by its `kind`, since
|
|
2202
|
+
* the turn answers with a stop reason where the client can say what
|
|
2203
|
+
* happened in its own words.
|
|
2204
|
+
*/
|
|
2205
|
+
function incomplete_finish(error) {
|
|
2206
|
+
if (!is_record$1(error) || error["kind"] !== "incomplete_generation_error") return void 0;
|
|
2207
|
+
const finish = error["finish_reason"];
|
|
2208
|
+
return finish === "length" || finish === "max_steps" || finish === "content_filter" ? finish : void 0;
|
|
2209
|
+
}
|
|
2210
|
+
/**
|
|
2211
|
+
* End a turn whose run has settled and wasn't cancelled. A run that
|
|
2212
|
+
* finished sends `to_text(output)` as the reply when the turn sent none. A
|
|
2213
|
+
* run that threw because a schema call ended early resolves with that
|
|
2214
|
+
* call's finish reason, which decides the turn's stop reason, and any other
|
|
2215
|
+
* failure is thrown on.
|
|
2216
|
+
*/
|
|
2217
|
+
async function end_run(config, result, reply, send) {
|
|
2218
|
+
if (result.ok) {
|
|
2219
|
+
const final_text = (config.to_text ?? default_to_text)(result.output);
|
|
2220
|
+
if (!reply.sent && final_text !== "") await send(agent_message(final_text));
|
|
2221
|
+
return;
|
|
2222
|
+
}
|
|
2223
|
+
const finish = incomplete_finish(result.error);
|
|
2224
|
+
if (finish === void 0) throw result.error;
|
|
2225
|
+
return finish;
|
|
2226
|
+
}
|
|
2227
|
+
/**
|
|
2001
2228
|
* Run the flow for one turn, forward its updates, and record the exchange.
|
|
2002
2229
|
* The run has always settled by the time this returns or throws, so a turn
|
|
2003
2230
|
* never leaves a run behind. A turn that ends in a refusal stays out of the
|
|
2004
|
-
* history, since the protocol has the client leave
|
|
2005
|
-
* too.
|
|
2231
|
+
* history and leaves no transcript, since the protocol has the client leave
|
|
2232
|
+
* it out of the next prompt too. A flow that throws because a schema call
|
|
2233
|
+
* ran out of tokens or steps, or was filtered, ends the turn with that stop
|
|
2234
|
+
* reason instead of failing the request.
|
|
2006
2235
|
*/
|
|
2007
2236
|
async function run_turn(config, record, prompt, cancelled, send) {
|
|
2008
2237
|
const turn = {
|
|
@@ -2017,9 +2246,11 @@ async function run_turn(config, record, prompt, cancelled, send) {
|
|
|
2017
2246
|
text: "",
|
|
2018
2247
|
card_since_text: false
|
|
2019
2248
|
};
|
|
2249
|
+
const transcript = create_transcript(prompt);
|
|
2020
2250
|
const send_update = async (update) => {
|
|
2021
2251
|
await send(update);
|
|
2022
2252
|
note_reply(reply, update);
|
|
2253
|
+
transcript.note(update);
|
|
2023
2254
|
};
|
|
2024
2255
|
const stop = new AbortController();
|
|
2025
2256
|
reset_previews(record.session);
|
|
@@ -2034,18 +2265,17 @@ async function run_turn(config, record, prompt, cancelled, send) {
|
|
|
2034
2265
|
await name_session(config, record, turn, send_update);
|
|
2035
2266
|
finish = await forward(handle.events, config, record, cancelled, send_update);
|
|
2036
2267
|
const result = await outcome;
|
|
2037
|
-
if (!cancelled.aborted)
|
|
2038
|
-
if (!result.ok) throw result.error;
|
|
2039
|
-
const final_text = (config.to_text ?? default_to_text)(result.output);
|
|
2040
|
-
if (!reply.sent && final_text !== "") await send_update(agent_message(final_text));
|
|
2041
|
-
}
|
|
2268
|
+
if (!cancelled.aborted) finish = await end_run(config, result, reply, send_update) ?? finish;
|
|
2042
2269
|
} catch (err) {
|
|
2043
2270
|
stop.abort(new aborted_error("the prompt turn failed before its run finished"));
|
|
2044
2271
|
await outcome;
|
|
2045
2272
|
if (!cancelled.aborted) throw err;
|
|
2046
2273
|
}
|
|
2047
2274
|
const stop_reason = cancelled.aborted ? "cancelled" : stop_reason_for(finish);
|
|
2048
|
-
if (stop_reason !== "refusal")
|
|
2275
|
+
if (stop_reason !== "refusal") {
|
|
2276
|
+
record_exchange(record.history, turn.text, reply.text, cancelled.aborted);
|
|
2277
|
+
record.unsaved_turns.push(transcript.updates());
|
|
2278
|
+
}
|
|
2049
2279
|
return { stopReason: stop_reason };
|
|
2050
2280
|
}
|
|
2051
2281
|
/**
|
|
@@ -2125,6 +2355,57 @@ async function load_acp_sdk() {
|
|
|
2125
2355
|
throw new acp_sdk_missing_error(`@agentclientprotocol/sdk is required for fascicle/acp; install it with its zod peer: pnpm add @agentclientprotocol/sdk zod (cause: ${err instanceof Error ? err.message : String(err)})`);
|
|
2126
2356
|
}
|
|
2127
2357
|
}
|
|
2358
|
+
/**
|
|
2359
|
+
* Order two sessions newest first, and by id where two changed in the same
|
|
2360
|
+
* millisecond, so the order is the same every time it's asked for.
|
|
2361
|
+
*/
|
|
2362
|
+
function newest_first(a, b) {
|
|
2363
|
+
return b.updated_at.localeCompare(a.updated_at) || a.id.localeCompare(b.id);
|
|
2364
|
+
}
|
|
2365
|
+
/**
|
|
2366
|
+
* The cursor that names `last` as the end of a page.
|
|
2367
|
+
*/
|
|
2368
|
+
function cursor_after(last) {
|
|
2369
|
+
return Buffer.from(JSON.stringify([last.updated_at, last.id]), "utf8").toString("base64url");
|
|
2370
|
+
}
|
|
2371
|
+
/**
|
|
2372
|
+
* The session a cursor names, or undefined for a string that isn't one of
|
|
2373
|
+
* this agent's cursors.
|
|
2374
|
+
*/
|
|
2375
|
+
function cursor_position(cursor) {
|
|
2376
|
+
let value;
|
|
2377
|
+
try {
|
|
2378
|
+
value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
|
|
2379
|
+
} catch {
|
|
2380
|
+
return;
|
|
2381
|
+
}
|
|
2382
|
+
if (!Array.isArray(value) || value.length !== 2) return void 0;
|
|
2383
|
+
const [updated_at, id] = value;
|
|
2384
|
+
return typeof updated_at === "string" && typeof id === "string" ? {
|
|
2385
|
+
updated_at,
|
|
2386
|
+
id
|
|
2387
|
+
} : void 0;
|
|
2388
|
+
}
|
|
2389
|
+
/**
|
|
2390
|
+
* The page of `summaries` that follows `cursor`, or the first page without
|
|
2391
|
+
* one, keeping only the sessions that started in `cwd` when it's given.
|
|
2392
|
+
* Returns undefined for a cursor that isn't valid.
|
|
2393
|
+
*/
|
|
2394
|
+
function session_page(summaries, cwd, cursor) {
|
|
2395
|
+
const listed = summaries.filter((summary) => cwd === void 0 || cwd === null || summary.cwd === cwd).toSorted(newest_first);
|
|
2396
|
+
let rest = listed;
|
|
2397
|
+
if (cursor !== void 0 && cursor !== null) {
|
|
2398
|
+
const position = cursor_position(cursor);
|
|
2399
|
+
if (position === void 0) return void 0;
|
|
2400
|
+
rest = listed.filter((summary) => newest_first(position, summary) < 0);
|
|
2401
|
+
}
|
|
2402
|
+
const sessions = rest.slice(0, 50);
|
|
2403
|
+
const last = sessions.at(-1);
|
|
2404
|
+
return rest.length > 50 && last !== void 0 ? {
|
|
2405
|
+
sessions,
|
|
2406
|
+
next_cursor: cursor_after(last)
|
|
2407
|
+
} : { sessions };
|
|
2408
|
+
}
|
|
2128
2409
|
// src/acp/acp_agent.ts
|
|
2129
2410
|
/**
|
|
2130
2411
|
* acp_agent: the ACP agent app that answers each prompt turn by running a
|
|
@@ -2136,17 +2417,28 @@ async function load_acp_sdk() {
|
|
|
2136
2417
|
* and the engine alone; `serve_acp` handles both.
|
|
2137
2418
|
*
|
|
2138
2419
|
* Given a session store, it saves each session after every turn and every
|
|
2139
|
-
* mode or model switch, and answers `session/list`, `session/load`,
|
|
2140
|
-
* `session/resume` from it. A loaded session gets a
|
|
2141
|
-
* config, and the history it carries is what its next
|
|
2420
|
+
* mode or model switch, and answers `session/list`, `session/load`,
|
|
2421
|
+
* `session/resume`, and `session/delete` from it. A loaded session gets a
|
|
2422
|
+
* fresh flow from the config, and the history it carries is what its next
|
|
2423
|
+
* turn starts from.
|
|
2142
2424
|
*
|
|
2143
2425
|
* A session holds what the client gave it until the client closes it with
|
|
2144
2426
|
* `session/close` or drops the connection: its MCP servers, for an agent
|
|
2145
2427
|
* that connects to them, are closed then, and a closed session leaves
|
|
2146
2428
|
* memory, though not the store.
|
|
2429
|
+
*
|
|
2430
|
+
* A request that names a session the agent doesn't hold fails with -32002
|
|
2431
|
+
* and the id as `data.sessionId`, which is how the protocol has an agent
|
|
2432
|
+
* say that a session is gone, and what a host reads before it offers to
|
|
2433
|
+
* start the thread over. Given an `auth`, the agent offers a login and
|
|
2434
|
+
* refuses to start, load, or resume a session until the login is ready.
|
|
2147
2435
|
*/
|
|
2148
2436
|
/** Every config option id a session can have, as a refusal lists them. */
|
|
2149
2437
|
const CONFIG_IDS = `${MODE_CONFIG_ID} and ${MODEL_CONFIG_ID}`;
|
|
2438
|
+
/** The id of the login every client is offered, which `authenticate` takes. */
|
|
2439
|
+
const LOGIN_METHOD = "login";
|
|
2440
|
+
/** The id of the login a client runs in a terminal. */
|
|
2441
|
+
const TERMINAL_LOGIN_METHOD = "terminal-login";
|
|
2150
2442
|
const ONE_CONNECTION = "acp_agent: this app already serves a connection; build an app for each connection, as serve_acp does";
|
|
2151
2443
|
/**
|
|
2152
2444
|
* Turn a failure inside a handler into a JSON-RPC error that carries its
|
|
@@ -2157,6 +2449,61 @@ function internal_error(sdk, err) {
|
|
|
2157
2449
|
return sdk.RequestError.internalError(void 0, message_of(err));
|
|
2158
2450
|
}
|
|
2159
2451
|
/**
|
|
2452
|
+
* The error for a request that names a session the agent doesn't hold:
|
|
2453
|
+
* -32002 with the id as `data.sessionId`, as the protocol asks. It's built
|
|
2454
|
+
* here because the SDK's own helper for it is newer than the oldest SDK the
|
|
2455
|
+
* peer range takes.
|
|
2456
|
+
*/
|
|
2457
|
+
function unknown_session(sdk, sessionId) {
|
|
2458
|
+
return new sdk.RequestError(-32002, "Resource not found", { sessionId });
|
|
2459
|
+
}
|
|
2460
|
+
/**
|
|
2461
|
+
* The error that tells a client the user has to log in first, which it
|
|
2462
|
+
* answers by offering the agent's login methods.
|
|
2463
|
+
*/
|
|
2464
|
+
function login_required(sdk, auth) {
|
|
2465
|
+
return new sdk.RequestError(-32e3, `Authentication required: ${auth.instructions}`);
|
|
2466
|
+
}
|
|
2467
|
+
/**
|
|
2468
|
+
* The error for a load or a resume that names a session with another cwd
|
|
2469
|
+
* than the one it started in, which the protocol has the client send.
|
|
2470
|
+
*/
|
|
2471
|
+
function other_cwd(sdk, method, sessionId, started_in, cwd) {
|
|
2472
|
+
return sdk.RequestError.invalidParams({
|
|
2473
|
+
sessionId,
|
|
2474
|
+
cwd
|
|
2475
|
+
}, `session ${sessionId} started in ${started_in}; send that cwd with ${method}`);
|
|
2476
|
+
}
|
|
2477
|
+
/**
|
|
2478
|
+
* The login methods an agent offers a client. Every client gets the one
|
|
2479
|
+
* the agent checks by itself, which is what the ACP registry looks for,
|
|
2480
|
+
* and a client that can run a terminal login also gets that one.
|
|
2481
|
+
*/
|
|
2482
|
+
function auth_methods(auth, capabilities) {
|
|
2483
|
+
if (auth === void 0) return [];
|
|
2484
|
+
const shown = {
|
|
2485
|
+
name: auth.name,
|
|
2486
|
+
...auth.description === void 0 ? {} : { description: auth.description }
|
|
2487
|
+
};
|
|
2488
|
+
const agent_login = {
|
|
2489
|
+
id: LOGIN_METHOD,
|
|
2490
|
+
...shown
|
|
2491
|
+
};
|
|
2492
|
+
if (auth.terminal_args === void 0 || capabilities.auth?.terminal !== true) return [agent_login];
|
|
2493
|
+
return [agent_login, {
|
|
2494
|
+
type: "terminal",
|
|
2495
|
+
id: TERMINAL_LOGIN_METHOD,
|
|
2496
|
+
...shown,
|
|
2497
|
+
args: [...auth.terminal_args]
|
|
2498
|
+
}];
|
|
2499
|
+
}
|
|
2500
|
+
/**
|
|
2501
|
+
* Whether two lists of MCP servers are the same list, entry for entry.
|
|
2502
|
+
*/
|
|
2503
|
+
function same_servers(a, b) {
|
|
2504
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
2505
|
+
}
|
|
2506
|
+
/**
|
|
2160
2507
|
* A function that sends one update to the client for one session.
|
|
2161
2508
|
*/
|
|
2162
2509
|
function sender(sdk, client, sessionId) {
|
|
@@ -2204,7 +2551,8 @@ function requested_directories(sdk, config, method, directories = []) {
|
|
|
2204
2551
|
}
|
|
2205
2552
|
/**
|
|
2206
2553
|
* A session's state as the store keeps it, copied, so a turn that runs while
|
|
2207
|
-
* the save is writing can't change what it writes.
|
|
2554
|
+
* the save is writing can't change what it writes. Its count of turns isn't
|
|
2555
|
+
* here, since the save adds it once it has written them.
|
|
2208
2556
|
*/
|
|
2209
2557
|
function stored_session(record) {
|
|
2210
2558
|
return {
|
|
@@ -2220,18 +2568,44 @@ function stored_session(record) {
|
|
|
2220
2568
|
};
|
|
2221
2569
|
}
|
|
2222
2570
|
/**
|
|
2223
|
-
* Save a session after the save before it
|
|
2224
|
-
*
|
|
2225
|
-
*
|
|
2226
|
-
*
|
|
2571
|
+
* Save a session after the save before it: first each turn the store hasn't
|
|
2572
|
+
* been handed, for a store that keeps turns, then the session, whose count
|
|
2573
|
+
* of turns then reaches them. A turn leaves `unsaved_turns` and joins the
|
|
2574
|
+
* count only once it's written, so a turn whose write failed goes with the
|
|
2575
|
+
* next save instead of leaving a hole in the thread. A session with no
|
|
2576
|
+
* history yet isn't saved, so a thread the user never wrote in doesn't fill
|
|
2577
|
+
* the list, and neither is a deleted one. A failed save is reported on
|
|
2578
|
+
* stderr rather than failing the turn the user already watched finish, and
|
|
2579
|
+
* it leaves the session as it was in the store.
|
|
2227
2580
|
*/
|
|
2228
2581
|
function save_session(config, record) {
|
|
2229
2582
|
const store = config.session_store;
|
|
2230
|
-
if (store === void 0 || record.history.length === 0)
|
|
2583
|
+
if (store === void 0 || record.deleted || record.history.length === 0) {
|
|
2584
|
+
record.unsaved_turns.length = 0;
|
|
2585
|
+
return Promise.resolve();
|
|
2586
|
+
}
|
|
2587
|
+
const { save_turn } = store;
|
|
2231
2588
|
const snapshot = stored_session(record);
|
|
2232
|
-
|
|
2589
|
+
const report = (err) => {
|
|
2233
2590
|
process.stderr.write(`fascicle/acp: couldn't save session ${snapshot.id}: ${message_of(err)}\n`);
|
|
2234
|
-
}
|
|
2591
|
+
};
|
|
2592
|
+
if (record.turns === null || save_turn === void 0) {
|
|
2593
|
+
record.unsaved_turns.length = 0;
|
|
2594
|
+
record.saving = record.saving.then(() => store.save(snapshot)).catch(report);
|
|
2595
|
+
return record.saving;
|
|
2596
|
+
}
|
|
2597
|
+
const through = record.turns + record.unsaved_turns.length;
|
|
2598
|
+
record.saving = record.saving.then(async () => {
|
|
2599
|
+
const first = record.turns ?? 0;
|
|
2600
|
+
const unsaved = record.unsaved_turns.slice(0, through - first);
|
|
2601
|
+
await Promise.all(unsaved.map((updates, offset) => save_turn(snapshot.id, first + offset, updates)));
|
|
2602
|
+
record.unsaved_turns.splice(0, unsaved.length);
|
|
2603
|
+
record.turns = first + unsaved.length;
|
|
2604
|
+
return store.save({
|
|
2605
|
+
...snapshot,
|
|
2606
|
+
turns: record.turns
|
|
2607
|
+
});
|
|
2608
|
+
}).catch(report);
|
|
2235
2609
|
return record.saving;
|
|
2236
2610
|
}
|
|
2237
2611
|
/**
|
|
@@ -2277,6 +2651,7 @@ async function acp_agent(config) {
|
|
|
2277
2651
|
const models = model_offer(config);
|
|
2278
2652
|
const sdk = await load_acp_sdk();
|
|
2279
2653
|
const sessions = /* @__PURE__ */ new Map();
|
|
2654
|
+
const opening = /* @__PURE__ */ new Map();
|
|
2280
2655
|
const store = config.session_store;
|
|
2281
2656
|
const identity = {
|
|
2282
2657
|
name: config.name,
|
|
@@ -2285,13 +2660,34 @@ async function acp_agent(config) {
|
|
|
2285
2660
|
let client_capabilities = {};
|
|
2286
2661
|
let connected = false;
|
|
2287
2662
|
let initialized = false;
|
|
2663
|
+
const { auth } = config;
|
|
2288
2664
|
const session_of = (sessionId) => {
|
|
2289
2665
|
const record = sessions.get(sessionId);
|
|
2290
2666
|
if (record !== void 0) return record;
|
|
2291
|
-
throw sdk
|
|
2667
|
+
throw unknown_session(sdk, sessionId);
|
|
2668
|
+
};
|
|
2669
|
+
const require_login = async () => {
|
|
2670
|
+
if (auth === void 0) return;
|
|
2671
|
+
if (!await Promise.resolve().then(() => auth.ready()).catch((err) => {
|
|
2672
|
+
throw internal_error(sdk, err);
|
|
2673
|
+
})) throw login_required(sdk, auth);
|
|
2674
|
+
};
|
|
2675
|
+
const connect = (servers, cwd) => config.mcp_servers === true ? connect_mcp_servers(servers, cwd, identity).catch((err) => {
|
|
2676
|
+
throw internal_error(sdk, err);
|
|
2677
|
+
}) : Promise.resolve(NO_MCP);
|
|
2678
|
+
const send_notices = async (client, record) => {
|
|
2679
|
+
const warnings = record.notices.splice(0);
|
|
2680
|
+
if (client_capabilities.session?.notices === void 0 || client_capabilities.session.notices === null) return;
|
|
2681
|
+
const send = sender(sdk, client, record.session.id);
|
|
2682
|
+
await Promise.all(warnings.map(({ title, description }) => send({
|
|
2683
|
+
sessionUpdate: "notice",
|
|
2684
|
+
severity: "warning",
|
|
2685
|
+
title,
|
|
2686
|
+
description
|
|
2687
|
+
}).catch(() => {})));
|
|
2292
2688
|
};
|
|
2293
2689
|
const options_of = (record) => [...config_options(offer, record.modes.current()), ...model_options(models, record.model.id)];
|
|
2294
|
-
const build_flow = (session) => typeof config.flow === "function" ? config.flow(session) : config.flow;
|
|
2690
|
+
const build_flow = async (session) => typeof config.flow === "function" ? config.flow(session) : config.flow;
|
|
2295
2691
|
const open_session = async (client, start) => {
|
|
2296
2692
|
const { id, cwd, additional_directories, stored } = start;
|
|
2297
2693
|
const roots = await resolve_roots([cwd, ...additional_directories]).catch((err) => {
|
|
@@ -2308,7 +2704,8 @@ async function acp_agent(config) {
|
|
|
2308
2704
|
cards,
|
|
2309
2705
|
ask: permission_asker(sdk, client)
|
|
2310
2706
|
});
|
|
2311
|
-
const mcp =
|
|
2707
|
+
const mcp = await connect(start.mcp_servers, cwd);
|
|
2708
|
+
const tools = { gated: gated_mcp_tools(mcp.tools, () => session) };
|
|
2312
2709
|
const session = {
|
|
2313
2710
|
id,
|
|
2314
2711
|
cwd,
|
|
@@ -2317,23 +2714,35 @@ async function acp_agent(config) {
|
|
|
2317
2714
|
client_capabilities,
|
|
2318
2715
|
mode: modes.current,
|
|
2319
2716
|
model: () => model.id,
|
|
2320
|
-
mcp_tools
|
|
2717
|
+
get mcp_tools() {
|
|
2718
|
+
return tools.gated;
|
|
2719
|
+
},
|
|
2321
2720
|
approve: (request) => approver(session, request)
|
|
2322
2721
|
};
|
|
2323
2722
|
const usage = stored === void 0 ? create_session_usage() : { ...stored.usage };
|
|
2723
|
+
const keeps_turns = store?.save_turn !== void 0 && store.load_turns !== void 0;
|
|
2324
2724
|
try {
|
|
2325
2725
|
const record = {
|
|
2326
2726
|
session,
|
|
2327
|
-
flow: build_flow(session),
|
|
2727
|
+
flow: await build_flow(session),
|
|
2328
2728
|
history: structuredClone([...stored?.history ?? []]),
|
|
2329
2729
|
cards,
|
|
2330
2730
|
usage,
|
|
2331
2731
|
last_turn: null,
|
|
2332
2732
|
title: stored?.title ?? null,
|
|
2733
|
+
unsaved_turns: [],
|
|
2333
2734
|
modes,
|
|
2334
2735
|
model,
|
|
2335
2736
|
mcp,
|
|
2336
|
-
|
|
2737
|
+
mcp_servers: start.mcp_servers,
|
|
2738
|
+
use_mcp: (connections) => {
|
|
2739
|
+
tools.gated = gated_mcp_tools(connections.tools, () => session);
|
|
2740
|
+
},
|
|
2741
|
+
notices: [...mcp.warnings],
|
|
2742
|
+
turns: keeps_turns ? stored === void 0 ? 0 : stored.turns ?? null : null,
|
|
2743
|
+
saving: Promise.resolve(),
|
|
2744
|
+
prompts: /* @__PURE__ */ new Set(),
|
|
2745
|
+
deleted: false
|
|
2337
2746
|
};
|
|
2338
2747
|
sessions.set(id, record);
|
|
2339
2748
|
return record;
|
|
@@ -2342,29 +2751,72 @@ async function acp_agent(config) {
|
|
|
2342
2751
|
throw internal_error(sdk, err);
|
|
2343
2752
|
}
|
|
2344
2753
|
};
|
|
2754
|
+
const switch_servers = async (record, servers) => {
|
|
2755
|
+
if (config.mcp_servers !== true || same_servers(record.mcp_servers, servers)) return;
|
|
2756
|
+
const previous = record.mcp;
|
|
2757
|
+
const next = await connect(servers, record.session.cwd);
|
|
2758
|
+
record.use_mcp(next);
|
|
2759
|
+
try {
|
|
2760
|
+
record.flow = await build_flow(record.session);
|
|
2761
|
+
} catch (err) {
|
|
2762
|
+
record.use_mcp(previous);
|
|
2763
|
+
await next.close();
|
|
2764
|
+
throw internal_error(sdk, err);
|
|
2765
|
+
}
|
|
2766
|
+
record.mcp = next;
|
|
2767
|
+
record.mcp_servers = servers;
|
|
2768
|
+
record.notices.push(...next.warnings);
|
|
2769
|
+
Promise.resolve(record.last_turn?.settled).then(() => previous.close());
|
|
2770
|
+
};
|
|
2771
|
+
const restore = async (client, method, request, session_store) => {
|
|
2772
|
+
const { sessionId, cwd } = request;
|
|
2773
|
+
const stored = await session_store.load(sessionId).catch((err) => {
|
|
2774
|
+
throw internal_error(sdk, err);
|
|
2775
|
+
});
|
|
2776
|
+
if (stored === void 0) throw unknown_session(sdk, sessionId);
|
|
2777
|
+
if (stored.cwd !== cwd) throw other_cwd(sdk, method, sessionId, stored.cwd, cwd);
|
|
2778
|
+
const kept = config.additional_directories === false ? [] : stored.additional_directories;
|
|
2779
|
+
return open_session(client, {
|
|
2780
|
+
id: sessionId,
|
|
2781
|
+
cwd,
|
|
2782
|
+
additional_directories: request.additional_directories.length > 0 ? request.additional_directories : kept,
|
|
2783
|
+
mcp_servers: request.mcp_servers ?? [],
|
|
2784
|
+
stored
|
|
2785
|
+
});
|
|
2786
|
+
};
|
|
2345
2787
|
const reopen = async (client, method, params) => {
|
|
2346
2788
|
if (store === void 0) throw sdk.RequestError.methodNotFound(method);
|
|
2789
|
+
await require_login();
|
|
2347
2790
|
const { sessionId, cwd } = params;
|
|
2348
2791
|
const additional_directories = requested_directories(sdk, config, method, params.additionalDirectories);
|
|
2792
|
+
for (let pending = opening.get(sessionId); pending !== void 0; pending = opening.get(sessionId)) await pending.catch(() => {});
|
|
2349
2793
|
const live = sessions.get(sessionId);
|
|
2350
|
-
|
|
2794
|
+
if (live === void 0) {
|
|
2795
|
+
const request = {
|
|
2796
|
+
sessionId,
|
|
2797
|
+
cwd,
|
|
2798
|
+
additional_directories,
|
|
2799
|
+
mcp_servers: params.mcpServers
|
|
2800
|
+
};
|
|
2801
|
+
const opened = restore(client, method, request, store).finally(() => opening.delete(sessionId));
|
|
2802
|
+
opening.set(sessionId, opened);
|
|
2803
|
+
return opened;
|
|
2804
|
+
}
|
|
2805
|
+
if (live.session.cwd !== cwd) throw other_cwd(sdk, method, sessionId, live.session.cwd, cwd);
|
|
2806
|
+
if (params.mcpServers !== void 0) await switch_servers(live, params.mcpServers);
|
|
2807
|
+
return live;
|
|
2808
|
+
};
|
|
2809
|
+
const replay = async (client, record) => {
|
|
2810
|
+
await record.saving;
|
|
2811
|
+
const kept = record.turns !== null && record.turns > 0 && store?.load_turns !== void 0 ? await store.load_turns(record.session.id, record.turns).catch((err) => {
|
|
2351
2812
|
throw internal_error(sdk, err);
|
|
2352
2813
|
}) : void 0;
|
|
2353
|
-
const
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
sessionId,
|
|
2357
|
-
cwd
|
|
2358
|
-
}, `session ${sessionId} started in ${started_in}; send that cwd with ${method}`);
|
|
2359
|
-
return live ?? open_session(client, {
|
|
2360
|
-
id: sessionId,
|
|
2361
|
-
cwd,
|
|
2362
|
-
additional_directories,
|
|
2363
|
-
mcp_servers: params.mcpServers ?? [],
|
|
2364
|
-
stored
|
|
2365
|
-
});
|
|
2814
|
+
const send = sender(sdk, client, record.session.id);
|
|
2815
|
+
const turns = kept === void 0 || kept.length === 0 ? record.history.map(replayed) : kept.flat();
|
|
2816
|
+
for (const update of turns) await send(update);
|
|
2366
2817
|
};
|
|
2367
2818
|
const reopened = async (client, record) => {
|
|
2819
|
+
await send_notices(client, record);
|
|
2368
2820
|
const send = sender(sdk, client, record.session.id);
|
|
2369
2821
|
if (record.title !== null && record.title !== "") await send({
|
|
2370
2822
|
sessionUpdate: "session_info_update",
|
|
@@ -2377,11 +2829,11 @@ async function acp_agent(config) {
|
|
|
2377
2829
|
configOptions: options_of(record)
|
|
2378
2830
|
};
|
|
2379
2831
|
};
|
|
2380
|
-
const switch_model = (record, next) => {
|
|
2832
|
+
const switch_model = async (record, next) => {
|
|
2381
2833
|
const previous = record.model.id;
|
|
2382
2834
|
record.model.id = next;
|
|
2383
2835
|
try {
|
|
2384
|
-
record.flow = build_flow(record.session);
|
|
2836
|
+
record.flow = await build_flow(record.session);
|
|
2385
2837
|
} catch (err) {
|
|
2386
2838
|
record.model.id = previous;
|
|
2387
2839
|
throw internal_error(sdk, err);
|
|
@@ -2391,6 +2843,8 @@ async function acp_agent(config) {
|
|
|
2391
2843
|
sessions.delete(record.session.id);
|
|
2392
2844
|
cancel_turn(record);
|
|
2393
2845
|
await record.last_turn?.settled;
|
|
2846
|
+
await Promise.all(record.prompts);
|
|
2847
|
+
await record.saving;
|
|
2394
2848
|
await record.mcp.close();
|
|
2395
2849
|
};
|
|
2396
2850
|
return sdk.agent().onConnect((connection) => {
|
|
@@ -2414,12 +2868,27 @@ async function acp_agent(config) {
|
|
|
2414
2868
|
...store === void 0 ? {} : {
|
|
2415
2869
|
list: {},
|
|
2416
2870
|
resume: {}
|
|
2417
|
-
}
|
|
2418
|
-
|
|
2871
|
+
},
|
|
2872
|
+
...store?.delete === void 0 ? {} : { delete: {} }
|
|
2873
|
+
},
|
|
2874
|
+
...auth?.logout === void 0 ? {} : { auth: { logout: {} } }
|
|
2419
2875
|
},
|
|
2420
|
-
authMethods:
|
|
2876
|
+
authMethods: auth_methods(auth, client_capabilities)
|
|
2421
2877
|
};
|
|
2422
|
-
}).onRequest("authenticate",
|
|
2878
|
+
}).onRequest("authenticate", async (ctx) => {
|
|
2879
|
+
if (auth === void 0) return {};
|
|
2880
|
+
const { methodId } = ctx.params;
|
|
2881
|
+
if (methodId !== LOGIN_METHOD) throw sdk.RequestError.invalidParams({ methodId }, `unknown login method ${JSON.stringify(methodId)}; the method is ${LOGIN_METHOD}`);
|
|
2882
|
+
await require_login();
|
|
2883
|
+
return {};
|
|
2884
|
+
}).onRequest("logout", async () => {
|
|
2885
|
+
if (auth?.logout === void 0) throw sdk.RequestError.methodNotFound("logout");
|
|
2886
|
+
await auth.logout().catch((err) => {
|
|
2887
|
+
throw internal_error(sdk, err);
|
|
2888
|
+
});
|
|
2889
|
+
return {};
|
|
2890
|
+
}).onRequest("session/new", async (ctx) => {
|
|
2891
|
+
await require_login();
|
|
2423
2892
|
const { cwd, mcpServers } = ctx.params;
|
|
2424
2893
|
const additional_directories = requested_directories(sdk, config, "session/new", ctx.params.additionalDirectories);
|
|
2425
2894
|
const record = await open_session(ctx.client, {
|
|
@@ -2435,27 +2904,49 @@ async function acp_agent(config) {
|
|
|
2435
2904
|
};
|
|
2436
2905
|
}).onRequest("session/load", async (ctx) => {
|
|
2437
2906
|
const record = await reopen(ctx.client, "session/load", ctx.params);
|
|
2438
|
-
|
|
2439
|
-
for (const entry of record.history) await send(replayed(entry));
|
|
2907
|
+
await replay(ctx.client, record);
|
|
2440
2908
|
return reopened(ctx.client, record);
|
|
2441
2909
|
}).onRequest("session/resume", async (ctx) => reopened(ctx.client, await reopen(ctx.client, "session/resume", ctx.params))).onRequest("session/list", async (ctx) => {
|
|
2442
2910
|
if (store === void 0) throw sdk.RequestError.methodNotFound("session/list");
|
|
2443
|
-
const { cwd } = ctx.params;
|
|
2444
|
-
|
|
2911
|
+
const { cwd, cursor } = ctx.params;
|
|
2912
|
+
const page = session_page(await store.list().catch((err) => {
|
|
2445
2913
|
throw internal_error(sdk, err);
|
|
2446
|
-
})
|
|
2914
|
+
}), cwd, cursor);
|
|
2915
|
+
if (page === void 0) throw sdk.RequestError.invalidParams({ cursor }, "that cursor isn't one this agent gave out; send session/list without a cursor to start over");
|
|
2916
|
+
return {
|
|
2917
|
+
sessions: page.sessions.map(session_info),
|
|
2918
|
+
...page.next_cursor === void 0 ? {} : { nextCursor: page.next_cursor }
|
|
2919
|
+
};
|
|
2920
|
+
}).onRequest("session/delete", async (ctx) => {
|
|
2921
|
+
if (store?.delete === void 0) throw sdk.RequestError.methodNotFound("session/delete");
|
|
2922
|
+
const { sessionId } = ctx.params;
|
|
2923
|
+
const live = sessions.get(sessionId);
|
|
2924
|
+
if (live !== void 0) {
|
|
2925
|
+
live.deleted = true;
|
|
2926
|
+
await close_session(live);
|
|
2927
|
+
await live.saving;
|
|
2928
|
+
}
|
|
2929
|
+
await store.delete(sessionId).catch((err) => {
|
|
2930
|
+
throw internal_error(sdk, err);
|
|
2931
|
+
});
|
|
2932
|
+
return {};
|
|
2447
2933
|
}).onRequest("session/close", async (ctx) => {
|
|
2448
2934
|
await close_session(session_of(ctx.params.sessionId));
|
|
2449
2935
|
return {};
|
|
2450
2936
|
}).onRequest("session/prompt", async (ctx) => {
|
|
2451
2937
|
const { sessionId, prompt } = ctx.params;
|
|
2452
2938
|
const record = session_of(sessionId);
|
|
2939
|
+
await send_notices(ctx.client, record);
|
|
2940
|
+
const saved = Promise.withResolvers();
|
|
2941
|
+
record.prompts.add(saved.promise);
|
|
2453
2942
|
try {
|
|
2454
2943
|
return await prompt_turn(config, record, prompt, ctx.signal, sender(sdk, ctx.client, sessionId));
|
|
2455
2944
|
} catch (err) {
|
|
2456
2945
|
throw internal_error(sdk, err);
|
|
2457
2946
|
} finally {
|
|
2458
2947
|
await save_session(config, record);
|
|
2948
|
+
record.prompts.delete(saved.promise);
|
|
2949
|
+
saved.resolve();
|
|
2459
2950
|
}
|
|
2460
2951
|
}).onRequest("session/set_mode", async (ctx) => {
|
|
2461
2952
|
const { sessionId, modeId } = ctx.params;
|
|
@@ -2467,7 +2958,7 @@ async function acp_agent(config) {
|
|
|
2467
2958
|
const { sessionId, configId, value } = ctx.params;
|
|
2468
2959
|
const record = session_of(sessionId);
|
|
2469
2960
|
if (configId === "mode") await record.modes.switch_to(requested_mode(sdk, offer, record.modes, value, "value"));
|
|
2470
|
-
else if (configId === "model" && models !== void 0) switch_model(record, requested_model(sdk, models, value));
|
|
2961
|
+
else if (configId === "model" && models !== void 0) await switch_model(record, requested_model(sdk, models, value));
|
|
2471
2962
|
else {
|
|
2472
2963
|
const known = models === void 0 ? `the only one is ${MODE_CONFIG_ID}` : `the options are ${CONFIG_IDS}`;
|
|
2473
2964
|
throw sdk.RequestError.invalidParams({ configId }, `unknown config option ${configId}; ${known}`);
|
|
@@ -2479,84 +2970,129 @@ async function acp_agent(config) {
|
|
|
2479
2970
|
if (record !== void 0) cancel_turn(record);
|
|
2480
2971
|
});
|
|
2481
2972
|
}
|
|
2482
|
-
// src/acp/
|
|
2973
|
+
// src/acp/api_key_login.ts
|
|
2483
2974
|
/**
|
|
2484
|
-
*
|
|
2975
|
+
* api_key_login: a login that keeps one API key in a file only the user can
|
|
2976
|
+
* read.
|
|
2485
2977
|
*
|
|
2486
|
-
*
|
|
2487
|
-
*
|
|
2488
|
-
*
|
|
2489
|
-
*
|
|
2490
|
-
* `
|
|
2491
|
-
*
|
|
2978
|
+
* Every agent that runs on a provider's API key needs the same login, so
|
|
2979
|
+
* this is it. The key comes from an environment variable first, so a key in
|
|
2980
|
+
* the client's agent server entry keeps working, and then from the file. A
|
|
2981
|
+
* client that can run a terminal login runs the agent's own command with
|
|
2982
|
+
* `--login`, where `run` asks for the key without echoing it and writes the
|
|
2983
|
+
* file. The agent's entry point calls `run` before it serves, so
|
|
2984
|
+
* `serve_acp` never reads a terminal.
|
|
2492
2985
|
*
|
|
2493
|
-
*
|
|
2494
|
-
*
|
|
2495
|
-
*
|
|
2496
|
-
*
|
|
2986
|
+
* The file holds the key in plain text, as `~/.aws/credentials` does, in a
|
|
2987
|
+
* directory made for its owner alone (mode 0700) and readable by its owner
|
|
2988
|
+
* alone (mode 0600). The key never reaches a log, stdout, or the protocol:
|
|
2989
|
+
* the prompt and every message go to the terminal's own output, and none of
|
|
2990
|
+
* them carries it.
|
|
2991
|
+
*
|
|
2992
|
+
* The environment and the path are accepted at construction; this module
|
|
2993
|
+
* never reads `process.env`.
|
|
2497
2994
|
*/
|
|
2995
|
+
/** The argument an agent's entry point runs the terminal login under. */
|
|
2996
|
+
const LOGIN_ARGUMENT = "--login";
|
|
2498
2997
|
/**
|
|
2499
|
-
*
|
|
2500
|
-
*
|
|
2501
|
-
* active run has been aborted.
|
|
2998
|
+
* The key a credentials file holds, or undefined when the file is missing
|
|
2999
|
+
* or holds anything else.
|
|
2502
3000
|
*/
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
|
|
3001
|
+
function stored_key(file) {
|
|
3002
|
+
try {
|
|
3003
|
+
const value = JSON.parse(readFileSync(file, "utf8"));
|
|
3004
|
+
const key = is_record$1(value) ? value["api_key"] : void 0;
|
|
3005
|
+
return typeof key === "string" && key !== "" ? key : void 0;
|
|
3006
|
+
} catch {
|
|
3007
|
+
return;
|
|
2510
3008
|
}
|
|
2511
|
-
await connection.closed;
|
|
2512
|
-
await config.engine?.dispose();
|
|
2513
3009
|
}
|
|
2514
|
-
// src/acp/serve_acp.ts
|
|
2515
3010
|
/**
|
|
2516
|
-
*
|
|
2517
|
-
*
|
|
2518
|
-
*
|
|
2519
|
-
* protocol out on stdout, and nothing else on stdout ever. A stray log line
|
|
2520
|
-
* from a flow or a dependency would corrupt the protocol stream, so
|
|
2521
|
-
* `console.log`, `console.info`, `console.debug`, `console.dir`, and
|
|
2522
|
-
* `console.dirxml` go to stderr for the life of the process.
|
|
2523
|
-
*
|
|
2524
|
-
* SIGTERM and SIGINT abort every active run, dispose the engine, and exit.
|
|
2525
|
-
* A host that ends the agent with a signal instead of closing stdin would
|
|
2526
|
-
* otherwise leave a run's work going after the editor has closed, since each
|
|
2527
|
-
* turn runs with the runner's own signal handlers off. The handlers are
|
|
2528
|
-
* one-shot, so a second Ctrl-C falls through to Node's default and kills the
|
|
2529
|
-
* process outright when a shutdown hangs.
|
|
2530
|
-
*
|
|
2531
|
-
* Excluded from mutation testing as process glue (see stryker.config.mjs);
|
|
2532
|
-
* the spawn tests in `__tests__/e2e/` exercise it for real.
|
|
3011
|
+
* Write the key to `file`, readable by its owner alone, in a directory made
|
|
3012
|
+
* for its owner alone. The key goes to a temporary sibling first and is
|
|
3013
|
+
* renamed into place, so a crash mid-write leaves the earlier file whole.
|
|
2533
3014
|
*/
|
|
3015
|
+
function store_key(file, key) {
|
|
3016
|
+
mkdirSync(dirname(file), {
|
|
3017
|
+
recursive: true,
|
|
3018
|
+
mode: 448
|
|
3019
|
+
});
|
|
3020
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
3021
|
+
writeFileSync(temporary, `${JSON.stringify({ api_key: key })}\n`, {
|
|
3022
|
+
encoding: "utf8",
|
|
3023
|
+
mode: 384
|
|
3024
|
+
});
|
|
3025
|
+
renameSync(temporary, file);
|
|
3026
|
+
}
|
|
3027
|
+
/**
|
|
3028
|
+
* Read one line from a terminal in raw mode, so nothing typed is echoed.
|
|
3029
|
+
* Resolves with the line at Enter, and with undefined at Ctrl-C or Ctrl-D.
|
|
3030
|
+
* Backspace removes the last character.
|
|
3031
|
+
*/
|
|
3032
|
+
function read_secret(terminal) {
|
|
3033
|
+
const { input } = terminal;
|
|
3034
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
3035
|
+
let typed = "";
|
|
3036
|
+
const on_data = (chunk) => {
|
|
3037
|
+
for (const character of chunk.toString()) {
|
|
3038
|
+
if (character === "\r" || character === "\n") return resolve(typed);
|
|
3039
|
+
if (character === "" || character === "") return resolve(void 0);
|
|
3040
|
+
if (character === "" || character === "\b") typed = typed.slice(0, -1);
|
|
3041
|
+
else typed += character;
|
|
3042
|
+
}
|
|
3043
|
+
};
|
|
3044
|
+
input.setRawMode?.(true);
|
|
3045
|
+
input.on("data", on_data);
|
|
3046
|
+
input.resume?.();
|
|
3047
|
+
return promise.finally(() => {
|
|
3048
|
+
input.off("data", on_data);
|
|
3049
|
+
input.setRawMode?.(false);
|
|
3050
|
+
input.pause?.();
|
|
3051
|
+
});
|
|
3052
|
+
}
|
|
2534
3053
|
/**
|
|
2535
|
-
*
|
|
2536
|
-
*
|
|
2537
|
-
*
|
|
3054
|
+
* Build a login that keeps one API key: `key` reads it, `auth` goes to
|
|
3055
|
+
* `serve_acp`, and `run` is the terminal login the agent's entry point runs
|
|
3056
|
+
* under `--login`.
|
|
2538
3057
|
*/
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
const
|
|
2542
|
-
|
|
2543
|
-
|
|
2544
|
-
|
|
2545
|
-
|
|
3058
|
+
function api_key_login(config) {
|
|
3059
|
+
const { name, variable, file, env } = config;
|
|
3060
|
+
const key = () => {
|
|
3061
|
+
const from_env = env[variable];
|
|
3062
|
+
return from_env !== void 0 && from_env !== "" ? from_env : stored_key(file);
|
|
3063
|
+
};
|
|
3064
|
+
return {
|
|
3065
|
+
key,
|
|
3066
|
+
auth: {
|
|
3067
|
+
name,
|
|
3068
|
+
description: `Reads ${variable}, or a key kept in ${file}`,
|
|
3069
|
+
ready: () => key() !== void 0,
|
|
3070
|
+
instructions: `set ${variable} in the agent server's env, or run the agent with ${LOGIN_ARGUMENT} in a terminal to enter a key`,
|
|
3071
|
+
terminal_args: [LOGIN_ARGUMENT],
|
|
3072
|
+
logout: async () => {
|
|
3073
|
+
rmSync(file, { force: true });
|
|
3074
|
+
}
|
|
3075
|
+
},
|
|
3076
|
+
run: async (terminal) => {
|
|
3077
|
+
const say = (text) => {
|
|
3078
|
+
terminal.output.write(text);
|
|
3079
|
+
};
|
|
3080
|
+
if (terminal.input.isTTY !== true) {
|
|
3081
|
+
say(`${name}: this login needs a terminal to read the key from; run it in one, or set ${variable} instead\n`);
|
|
3082
|
+
return 1;
|
|
3083
|
+
}
|
|
3084
|
+
say(`${name} (what you type isn't shown): `);
|
|
3085
|
+
const entered = (await read_secret(terminal))?.trim();
|
|
3086
|
+
say("\n");
|
|
3087
|
+
if (entered === void 0 || entered === "") {
|
|
3088
|
+
say(`${name}: no key was entered, so nothing was saved; run the login again to enter one\n`);
|
|
3089
|
+
return 1;
|
|
3090
|
+
}
|
|
3091
|
+
store_key(file, entered);
|
|
3092
|
+
say(`${name}: saved to ${file}\n`);
|
|
3093
|
+
return 0;
|
|
3094
|
+
}
|
|
2546
3095
|
};
|
|
2547
|
-
process.once("SIGTERM", on_signal);
|
|
2548
|
-
process.once("SIGINT", on_signal);
|
|
2549
|
-
try {
|
|
2550
|
-
await serve_streams(config, {
|
|
2551
|
-
input: Readable.toWeb(process.stdin),
|
|
2552
|
-
output: Writable.toWeb(process.stdout),
|
|
2553
|
-
shutdown: shutdown.signal
|
|
2554
|
-
});
|
|
2555
|
-
} finally {
|
|
2556
|
-
process.off("SIGTERM", on_signal);
|
|
2557
|
-
process.off("SIGINT", on_signal);
|
|
2558
|
-
}
|
|
2559
|
-
if (received !== null) process.exit(128 + constants.signals[received]);
|
|
2560
3096
|
}
|
|
2561
3097
|
// src/acp/session_store.ts
|
|
2562
3098
|
/**
|
|
@@ -2573,6 +3109,11 @@ async function serve_acp(config) {
|
|
|
2573
3109
|
* fails its load with a message naming it, and `list` skips it with a
|
|
2574
3110
|
* warning on stderr, so one bad file can't hide every other thread.
|
|
2575
3111
|
*
|
|
3112
|
+
* Each turn as the client saw it goes in a file of its own,
|
|
3113
|
+
* `<id>.turns/<n>.json`, so a long session costs one small write for each
|
|
3114
|
+
* turn instead of a rewrite of everything it has shown. Deleting a session
|
|
3115
|
+
* removes its file and that directory.
|
|
3116
|
+
*
|
|
2576
3117
|
* Paths are accepted at construction; the store never reads `process.env`.
|
|
2577
3118
|
*/
|
|
2578
3119
|
/** The ids that can name a file, which every id the agent makes matches. */
|
|
@@ -2612,8 +3153,53 @@ function is_usage(value) {
|
|
|
2612
3153
|
*/
|
|
2613
3154
|
function is_stored_session(value) {
|
|
2614
3155
|
if (!is_record(value)) return false;
|
|
2615
|
-
const { id, cwd, additional_directories, mode, model, title, updated_at, history, usage } = value;
|
|
2616
|
-
return typeof id === "string" && typeof cwd === "string" && is_strings(additional_directories) && is_acp_mode(mode) && (model === void 0 || typeof model === "string") && (title === null || typeof title === "string") && typeof updated_at === "string" && Array.isArray(history) && history.every(is_history_entry) && is_usage(usage);
|
|
3156
|
+
const { id, cwd, additional_directories, mode, model, title, updated_at, history, usage, turns } = value;
|
|
3157
|
+
return typeof id === "string" && typeof cwd === "string" && is_strings(additional_directories) && is_acp_mode(mode) && (model === void 0 || typeof model === "string") && (title === null || typeof title === "string") && typeof updated_at === "string" && Array.isArray(history) && history.every(is_history_entry) && is_usage(usage) && (turns === void 0 || typeof turns === "number");
|
|
3158
|
+
}
|
|
3159
|
+
/**
|
|
3160
|
+
* Whether `value` is one turn as a store keeps it: a list of session
|
|
3161
|
+
* updates, each checked only for the field that names its kind, since the
|
|
3162
|
+
* client checks the rest as it takes them.
|
|
3163
|
+
*/
|
|
3164
|
+
function is_stored_turn(value) {
|
|
3165
|
+
return Array.isArray(value) && value.every((update) => is_record(update) && typeof update["sessionUpdate"] === "string");
|
|
3166
|
+
}
|
|
3167
|
+
/**
|
|
3168
|
+
* What `session/list` reports of a stored session.
|
|
3169
|
+
*/
|
|
3170
|
+
function summary_of(session) {
|
|
3171
|
+
const { id, cwd, additional_directories, title, updated_at } = session;
|
|
3172
|
+
return {
|
|
3173
|
+
id,
|
|
3174
|
+
cwd,
|
|
3175
|
+
additional_directories,
|
|
3176
|
+
title,
|
|
3177
|
+
updated_at
|
|
3178
|
+
};
|
|
3179
|
+
}
|
|
3180
|
+
/**
|
|
3181
|
+
* Write `value` as JSON to `path` through a temporary sibling and a rename,
|
|
3182
|
+
* readable by its owner alone.
|
|
3183
|
+
*/
|
|
3184
|
+
async function write_private(path, value) {
|
|
3185
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
3186
|
+
await writeFile(temporary, JSON.stringify(value), {
|
|
3187
|
+
encoding: "utf8",
|
|
3188
|
+
mode: 384
|
|
3189
|
+
});
|
|
3190
|
+
await rename(temporary, path);
|
|
3191
|
+
}
|
|
3192
|
+
/**
|
|
3193
|
+
* Read one stored turn, or undefined when its file is missing or holds
|
|
3194
|
+
* anything else, so a load replays the turns that can be read.
|
|
3195
|
+
*/
|
|
3196
|
+
async function read_turn(path) {
|
|
3197
|
+
try {
|
|
3198
|
+
const value = JSON.parse(await readFile(path, "utf8"));
|
|
3199
|
+
return is_stored_turn(value) ? value : void 0;
|
|
3200
|
+
} catch {
|
|
3201
|
+
return;
|
|
3202
|
+
}
|
|
2617
3203
|
}
|
|
2618
3204
|
/**
|
|
2619
3205
|
* Read the session file at `path`, or undefined when there is none. Throws
|
|
@@ -2637,26 +3223,50 @@ async function read_session(path) {
|
|
|
2637
3223
|
throw new Error(`${path} isn't a stored ACP session; fix or delete the file to load the others`);
|
|
2638
3224
|
}
|
|
2639
3225
|
/**
|
|
3226
|
+
* `id` when it can name a file, and otherwise an error that says which ids
|
|
3227
|
+
* can.
|
|
3228
|
+
*/
|
|
3229
|
+
function checked(id) {
|
|
3230
|
+
if (SAFE_ID.test(id)) return id;
|
|
3231
|
+
throw new Error(`can't save session ${JSON.stringify(id)}: an id names a file, so use letters, digits, - and _`);
|
|
3232
|
+
}
|
|
3233
|
+
/**
|
|
2640
3234
|
* Build a session store that keeps one JSON file for each session under
|
|
2641
3235
|
* `root_dir`.
|
|
2642
3236
|
*/
|
|
2643
3237
|
function filesystem_session_store(config) {
|
|
2644
3238
|
const path_of = (id) => join(config.root_dir, `${id}.json`);
|
|
3239
|
+
const turns_dir = (id) => join(config.root_dir, `${id}.turns`);
|
|
3240
|
+
const turn_path = (id, index) => join(turns_dir(id), `${index}.json`);
|
|
2645
3241
|
return {
|
|
2646
3242
|
save: async (session) => {
|
|
2647
|
-
|
|
3243
|
+
const id = checked(session.id);
|
|
2648
3244
|
await mkdir(config.root_dir, {
|
|
2649
3245
|
recursive: true,
|
|
2650
3246
|
mode: 448
|
|
2651
3247
|
});
|
|
2652
|
-
|
|
2653
|
-
await writeFile(temporary, JSON.stringify(session), {
|
|
2654
|
-
encoding: "utf8",
|
|
2655
|
-
mode: 384
|
|
2656
|
-
});
|
|
2657
|
-
await rename(temporary, path_of(session.id));
|
|
3248
|
+
await write_private(path_of(id), session);
|
|
2658
3249
|
},
|
|
2659
3250
|
load: async (id) => SAFE_ID.test(id) ? read_session(path_of(id)) : void 0,
|
|
3251
|
+
delete: async (id) => {
|
|
3252
|
+
if (!SAFE_ID.test(id)) return;
|
|
3253
|
+
await rm(path_of(id), { force: true });
|
|
3254
|
+
await rm(turns_dir(id), {
|
|
3255
|
+
recursive: true,
|
|
3256
|
+
force: true
|
|
3257
|
+
});
|
|
3258
|
+
},
|
|
3259
|
+
save_turn: async (id, index, updates) => {
|
|
3260
|
+
await mkdir(turns_dir(checked(id)), {
|
|
3261
|
+
recursive: true,
|
|
3262
|
+
mode: 448
|
|
3263
|
+
});
|
|
3264
|
+
await write_private(turn_path(id, index), updates);
|
|
3265
|
+
},
|
|
3266
|
+
load_turns: async (id, count) => {
|
|
3267
|
+
if (!SAFE_ID.test(id)) return [];
|
|
3268
|
+
return (await Promise.all(Array.from({ length: count }, (_, index) => read_turn(turn_path(id, index))))).filter((turn) => turn !== void 0);
|
|
3269
|
+
},
|
|
2660
3270
|
list: async () => {
|
|
2661
3271
|
let names;
|
|
2662
3272
|
try {
|
|
@@ -2668,16 +3278,179 @@ function filesystem_session_store(config) {
|
|
|
2668
3278
|
const files = names.filter((name) => name.endsWith(".json") && !name.startsWith("."));
|
|
2669
3279
|
return (await Promise.all(files.map((name) => read_session(join(config.root_dir, name)).catch((err) => {
|
|
2670
3280
|
process.stderr.write(`fascicle/acp: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
2671
|
-
})))).filter((session) => session !== void 0).map(
|
|
2672
|
-
id,
|
|
2673
|
-
cwd,
|
|
2674
|
-
additional_directories,
|
|
2675
|
-
title,
|
|
2676
|
-
updated_at
|
|
2677
|
-
}));
|
|
3281
|
+
})))).filter((session) => session !== void 0).map(summary_of);
|
|
2678
3282
|
}
|
|
2679
3283
|
};
|
|
2680
3284
|
}
|
|
2681
|
-
|
|
3285
|
+
// src/acp/checkpoint_session_store.ts
|
|
3286
|
+
/** The key of the index that `session/list` reads. */
|
|
3287
|
+
const INDEX_KEY = "acp/sessions";
|
|
3288
|
+
/** How many times an index update reads again after losing its write to another writer. */
|
|
3289
|
+
const INDEX_ATTEMPTS = 50;
|
|
3290
|
+
/**
|
|
3291
|
+
* The latest index update on each store that can't compare and set, which
|
|
3292
|
+
* the next one waits on, so two updates in one process never read the same
|
|
3293
|
+
* index and write over each other. It's keyed by the store, since two
|
|
3294
|
+
* session stores can share one.
|
|
3295
|
+
*/
|
|
3296
|
+
const index_updates = /* @__PURE__ */ new WeakMap();
|
|
3297
|
+
/**
|
|
3298
|
+
* The key a session is kept under.
|
|
3299
|
+
*/
|
|
3300
|
+
function session_key(id) {
|
|
3301
|
+
return `acp/session/${id}`;
|
|
3302
|
+
}
|
|
3303
|
+
/**
|
|
3304
|
+
* The key one turn of a session is kept under.
|
|
3305
|
+
*/
|
|
3306
|
+
function turn_key(id, index) {
|
|
3307
|
+
return `${session_key(id)}/turn/${index}`;
|
|
3308
|
+
}
|
|
3309
|
+
/**
|
|
3310
|
+
* Whether `value` is one entry of the index.
|
|
3311
|
+
*/
|
|
3312
|
+
function is_summary(value) {
|
|
3313
|
+
if (!is_record$1(value)) return false;
|
|
3314
|
+
const { id, cwd, additional_directories, title, updated_at } = value;
|
|
3315
|
+
return typeof id === "string" && typeof cwd === "string" && Array.isArray(additional_directories) && additional_directories.every((entry) => typeof entry === "string") && (title === null || typeof title === "string") && typeof updated_at === "string";
|
|
3316
|
+
}
|
|
3317
|
+
/**
|
|
3318
|
+
* The index a store holds, read from whatever is under its key. Anything
|
|
3319
|
+
* that isn't an entry is left out, so one bad entry can't hide the rest.
|
|
3320
|
+
*/
|
|
3321
|
+
function index_of(value) {
|
|
3322
|
+
return Array.isArray(value) ? value.filter(is_summary) : [];
|
|
3323
|
+
}
|
|
3324
|
+
/**
|
|
3325
|
+
* Replace the index with `change` applied to it. On a store that can
|
|
3326
|
+
* compare and set, a write that lost to another writer reads the index
|
|
3327
|
+
* again and applies the change to what it finds. On any other store, the
|
|
3328
|
+
* update waits for every one this process already started there, whether
|
|
3329
|
+
* or not that one failed, since nothing else keeps two of them apart.
|
|
3330
|
+
*/
|
|
3331
|
+
async function update_index(store, change) {
|
|
3332
|
+
const { get_versioned, set_if } = store;
|
|
3333
|
+
if (get_versioned === void 0 || set_if === void 0) {
|
|
3334
|
+
const update = (index_updates.get(store) ?? Promise.resolve()).then(async () => store.set(INDEX_KEY, change(index_of(await store.get(INDEX_KEY)))));
|
|
3335
|
+
index_updates.set(store, update.catch(() => {}));
|
|
3336
|
+
return update;
|
|
3337
|
+
}
|
|
3338
|
+
for (let attempt = 0; attempt < INDEX_ATTEMPTS; attempt += 1) {
|
|
3339
|
+
const read = await get_versioned(INDEX_KEY);
|
|
3340
|
+
if (await set_if(INDEX_KEY, change(index_of(read?.value)), read?.version ?? null)) return;
|
|
3341
|
+
}
|
|
3342
|
+
throw new Error(`couldn't update the session index at ${INDEX_KEY}: ${INDEX_ATTEMPTS} writes in a row lost to another writer; save the session again`);
|
|
3343
|
+
}
|
|
3344
|
+
/**
|
|
3345
|
+
* Build a session store that keeps its sessions in `store`, with their
|
|
3346
|
+
* turns, and can delete them.
|
|
3347
|
+
*/
|
|
3348
|
+
function checkpoint_session_store(store) {
|
|
3349
|
+
return {
|
|
3350
|
+
save: async (session) => {
|
|
3351
|
+
await store.set(session_key(session.id), session);
|
|
3352
|
+
const summary = summary_of(session);
|
|
3353
|
+
await update_index(store, (index) => [summary, ...index.filter((entry) => entry.id !== session.id)]);
|
|
3354
|
+
},
|
|
3355
|
+
load: async (id) => {
|
|
3356
|
+
const value = await store.get(session_key(id));
|
|
3357
|
+
if (value === void 0 || value === null) return void 0;
|
|
3358
|
+
if (is_stored_session(value)) return value;
|
|
3359
|
+
throw new Error(`the value at ${session_key(id)} isn't a stored ACP session; delete the session to list the others`);
|
|
3360
|
+
},
|
|
3361
|
+
list: async () => index_of(await store.get(INDEX_KEY)),
|
|
3362
|
+
delete: async (id) => {
|
|
3363
|
+
const value = await store.get(session_key(id));
|
|
3364
|
+
const turns = is_stored_session(value) ? value.turns ?? 0 : 0;
|
|
3365
|
+
await Promise.all(Array.from({ length: turns }, (_, index) => store.delete(turn_key(id, index))));
|
|
3366
|
+
await store.delete(session_key(id));
|
|
3367
|
+
await update_index(store, (index) => index.filter((entry) => entry.id !== id));
|
|
3368
|
+
},
|
|
3369
|
+
save_turn: (id, index, updates) => store.set(turn_key(id, index), updates),
|
|
3370
|
+
load_turns: async (id, count) => {
|
|
3371
|
+
return (await Promise.all(Array.from({ length: count }, (_, index) => store.get(turn_key(id, index))))).filter(is_stored_turn);
|
|
3372
|
+
}
|
|
3373
|
+
};
|
|
3374
|
+
}
|
|
3375
|
+
// src/acp/serve_streams.ts
|
|
3376
|
+
/**
|
|
3377
|
+
* The ACP agent's serving loop, minus the process.
|
|
3378
|
+
*
|
|
3379
|
+
* `serve_streams` is everything `serve_acp` does once the console and the
|
|
3380
|
+
* signals are handled: connect `acp_agent` to a pair of ndjson byte streams,
|
|
3381
|
+
* hold the connection until the client hangs up or `shutdown` fires, then
|
|
3382
|
+
* dispose the engine. It takes its streams as arguments, mirroring
|
|
3383
|
+
* `execute_stdio` under `run_stdio`, so the disconnect path is unit-tested
|
|
3384
|
+
* here and the thin glue in `serve_acp.ts` owns the real stdin and stdout.
|
|
3385
|
+
*
|
|
3386
|
+
* Closing the connection is what aborts the runs: the SDK aborts every
|
|
3387
|
+
* in-flight request's signal as it closes, and each prompt turn's run
|
|
3388
|
+
* listens on its request's signal. So by the time `closed` resolves, every
|
|
3389
|
+
* active run has seen its abort, and only then is the engine disposed.
|
|
3390
|
+
*/
|
|
3391
|
+
/**
|
|
3392
|
+
* Serve the config's flow as an ACP agent over `io` until the client
|
|
3393
|
+
* disconnects or `io.shutdown` fires, then dispose the engine once every
|
|
3394
|
+
* active run has been aborted.
|
|
3395
|
+
*/
|
|
3396
|
+
async function serve_streams(config, io) {
|
|
3397
|
+
const sdk = await load_acp_sdk();
|
|
3398
|
+
const connection = (await acp_agent(config)).connect(sdk.ndJsonStream(io.output, io.input));
|
|
3399
|
+
const { shutdown } = io;
|
|
3400
|
+
if (shutdown !== void 0) {
|
|
3401
|
+
if (shutdown.aborted) connection.close(shutdown.reason);
|
|
3402
|
+
else shutdown.addEventListener("abort", () => connection.close(shutdown.reason));
|
|
3403
|
+
}
|
|
3404
|
+
await connection.closed;
|
|
3405
|
+
await config.engine?.dispose();
|
|
3406
|
+
}
|
|
3407
|
+
// src/acp/serve_acp.ts
|
|
3408
|
+
/**
|
|
3409
|
+
* Process glue for serving a flow as an ACP agent over stdio.
|
|
3410
|
+
*
|
|
3411
|
+
* Binds `serve_streams` to the real process: ndjson in on stdin, the
|
|
3412
|
+
* protocol out on stdout, and nothing else on stdout ever. A stray log line
|
|
3413
|
+
* from a flow or a dependency would corrupt the protocol stream, so
|
|
3414
|
+
* `console.log`, `console.info`, `console.debug`, `console.dir`, and
|
|
3415
|
+
* `console.dirxml` go to stderr for the life of the process.
|
|
3416
|
+
*
|
|
3417
|
+
* SIGTERM and SIGINT abort every active run, dispose the engine, and exit.
|
|
3418
|
+
* A host that ends the agent with a signal instead of closing stdin would
|
|
3419
|
+
* otherwise leave a run's work going after the editor has closed, since each
|
|
3420
|
+
* turn runs with the runner's own signal handlers off. The handlers are
|
|
3421
|
+
* one-shot, so a second Ctrl-C falls through to Node's default and kills the
|
|
3422
|
+
* process outright when a shutdown hangs.
|
|
3423
|
+
*
|
|
3424
|
+
* Excluded from mutation testing as process glue (see stryker.config.mjs);
|
|
3425
|
+
* the spawn tests in `__tests__/e2e/` exercise it for real.
|
|
3426
|
+
*/
|
|
3427
|
+
/**
|
|
3428
|
+
* Serve a flow as an ACP agent over stdin and stdout until the client
|
|
3429
|
+
* disconnects, disposing the engine once every active run has been aborted.
|
|
3430
|
+
* A SIGTERM or SIGINT does the same, then exits with the signal's code.
|
|
3431
|
+
*/
|
|
3432
|
+
async function serve_acp(config) {
|
|
3433
|
+
route_console_to_stderr(console, process.stderr);
|
|
3434
|
+
const shutdown = new AbortController();
|
|
3435
|
+
let received = null;
|
|
3436
|
+
const on_signal = (signal) => {
|
|
3437
|
+
received = signal;
|
|
3438
|
+
shutdown.abort(new aborted_error(`received ${signal}`, { reason: { signal } }));
|
|
3439
|
+
};
|
|
3440
|
+
process.once("SIGTERM", on_signal);
|
|
3441
|
+
process.once("SIGINT", on_signal);
|
|
3442
|
+
try {
|
|
3443
|
+
await serve_streams(config, {
|
|
3444
|
+
input: Readable.toWeb(process.stdin),
|
|
3445
|
+
output: Writable.toWeb(process.stdout),
|
|
3446
|
+
shutdown: shutdown.signal
|
|
3447
|
+
});
|
|
3448
|
+
} finally {
|
|
3449
|
+
process.off("SIGTERM", on_signal);
|
|
3450
|
+
process.off("SIGINT", on_signal);
|
|
3451
|
+
}
|
|
3452
|
+
if (received !== null) process.exit(128 + constants$1.signals[received]);
|
|
3453
|
+
}
|
|
3454
|
+
export { acp_agent, acp_sdk_missing_error, api_key_login, checkpoint_session_store, create_acp_mapper_state, filesystem_session_store, serve_acp, to_session_updates, workspace_tools };
|
|
2682
3455
|
|
|
2683
3456
|
//# sourceMappingURL=acp.js.map
|