fascicle 0.17.5 → 0.17.7

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/dist/acp.js CHANGED
@@ -1,18 +1,19 @@
1
1
  import { j as aborted_error, w as run } from "./core-Bfzt55Fl.js";
2
- import { n as is_record, t as as_record } from "./records-1HU7mWXf.js";
2
+ import { n as is_record$1, t as as_record } from "./records-1HU7mWXf.js";
3
3
  import { t as json_schema_to_standard } from "./json_schema_to_standard-C4F4lXHE.js";
4
+ import { n as mcp_client } from "./mcp-8mKK7eDY.js";
4
5
  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-DjhdMsJ8.js";
5
6
  import { t as route_console_to_stderr } from "./console-CdB4pcFO.js";
6
7
  import { randomUUID } from "node:crypto";
7
- import { mkdir, open, stat, writeFile } from "node:fs/promises";
8
- import { dirname, resolve } from "node:path";
8
+ import { mkdir, open, readFile, readdir, rename, stat, writeFile } from "node:fs/promises";
9
+ import { dirname, join, resolve } from "node:path";
9
10
  import { constants } from "node:os";
10
11
  import { spawn } from "node:child_process";
11
12
  import { isUtf8 } from "node:buffer";
12
13
  import { StringDecoder } from "node:string_decoder";
13
14
  import { Readable, Writable } from "node:stream";
14
15
  //#region src/acp/modes.ts
15
- /** The id of the config option that carries the mode, the only option this agent has. */
16
+ /** The id of the config option that carries the mode. */
16
17
  const MODE_CONFIG_ID = "mode";
17
18
  /** Every mode, in the order a client lists them. */
18
19
  const MODES = {
@@ -102,8 +103,9 @@ function mode_state(offer, mode) {
102
103
  };
103
104
  }
104
105
  /**
105
- * The session's config options, the mode as a select being the only one, as
106
- * `session/new` and `session/set_config_option` report them.
106
+ * The session's mode as a config option, a select over every mode the agent
107
+ * offers, which leads the options `session/new` and
108
+ * `session/set_config_option` report.
107
109
  */
108
110
  function config_options(offer, mode) {
109
111
  return [{
@@ -121,14 +123,17 @@ function config_options(offer, mode) {
121
123
  }];
122
124
  }
123
125
  /**
124
- * Hold a session's mode, starting at the offer's `default_mode`. A switch
126
+ * Hold a session's mode, starting at `start` when the agent offers it and
127
+ * at the offer's `default_mode` otherwise, so a stored session whose mode the
128
+ * agent has since stopped offering starts where a new one would. A switch
125
129
  * takes effect before the client hears of it, so a tool call that asks after
126
130
  * the switch reads the new mode, and the two updates go out in order through
127
- * `send`.
131
+ * `send`. A config option update carries every option the session has, so
132
+ * `others` gives the ones after the mode, such as the model.
128
133
  */
129
- function session_modes(offer, send) {
130
- let mode = offer.default_mode;
134
+ function session_modes(offer, send, start, others = () => []) {
131
135
  const offered = offer.modes;
136
+ let mode = offer.modes.find((entry) => entry === start) ?? offer.default_mode;
132
137
  return {
133
138
  current: () => mode,
134
139
  offers: (candidate) => offered.includes(candidate),
@@ -140,12 +145,133 @@ function session_modes(offer, send) {
140
145
  });
141
146
  await send({
142
147
  sessionUpdate: "config_option_update",
143
- configOptions: config_options(offer, next)
148
+ configOptions: [...config_options(offer, next), ...others()]
144
149
  });
145
150
  }
146
151
  };
147
152
  }
148
153
  //#endregion
154
+ //#region src/acp/mcp_servers.ts
155
+ /**
156
+ * The MCP transports the agent tells a client it speaks beside stdio, which
157
+ * every agent takes.
158
+ */
159
+ const MCP_CAPABILITIES = { http: true };
160
+ /** The connections of a session with no MCP servers. */
161
+ const NO_MCP = {
162
+ tools: [],
163
+ close: async () => {}
164
+ };
165
+ /** The validated inputs each session's MCP tools were asked about. */
166
+ const asked$1 = /* @__PURE__ */ new WeakMap();
167
+ /**
168
+ * Say on stderr what went wrong with a session's MCP servers, since the
169
+ * session carries on without what failed.
170
+ */
171
+ function warn(message) {
172
+ process.stderr.write(`fascicle/acp: ${message}\n`);
173
+ }
174
+ /**
175
+ * A list of names and values as the record a transport takes.
176
+ */
177
+ function record_of(entries) {
178
+ return Object.fromEntries(entries.map(({ name, value }) => [name, value]));
179
+ }
180
+ /**
181
+ * How `mcp_client` reaches a server the client sent, or undefined for a
182
+ * transport it doesn't speak. A stdio server starts in the session's cwd
183
+ * with the variables the client gave it on top of the MCP SDK's own short
184
+ * list, so it doesn't inherit the agent's provider keys.
185
+ */
186
+ function client_config(server, cwd) {
187
+ if ("command" in server) return {
188
+ transport: "stdio",
189
+ command: server.command,
190
+ args: [...server.args],
191
+ env: record_of(server.env),
192
+ cwd
193
+ };
194
+ if (server.type === "http") return {
195
+ transport: "http",
196
+ url: server.url,
197
+ headers: record_of(server.headers)
198
+ };
199
+ }
200
+ /**
201
+ * Connect to one server, or warn and return undefined when it can't be
202
+ * reached, so the session starts without it.
203
+ */
204
+ async function connect_server(server, cwd, identity) {
205
+ const config = client_config(server, cwd);
206
+ if (config === void 0) {
207
+ warn(`MCP server ${server.name} uses a transport this agent doesn't speak, so its tools are left out of the session`);
208
+ return;
209
+ }
210
+ const name_prefix = `mcp__${server.name.replaceAll(/[^\w-]/g, "_")}__`;
211
+ try {
212
+ return await mcp_client(config, {
213
+ client_info: identity,
214
+ name_prefix
215
+ });
216
+ } catch (err) {
217
+ const reason = err instanceof Error ? err.message : String(err);
218
+ warn(`couldn't connect to MCP server ${server.name} (${reason}), so its tools are left out of the session`);
219
+ return;
220
+ }
221
+ }
222
+ /**
223
+ * Close every connection, warning about any that fails to close rather
224
+ * than leaving the others open.
225
+ */
226
+ async function close_all(handles) {
227
+ const results = await Promise.allSettled(handles.map((handle) => handle.close()));
228
+ for (const result of results) if (result.status === "rejected") {
229
+ const reason = result.reason;
230
+ warn(`couldn't close an MCP server (${reason instanceof Error ? reason.message : String(reason)})`);
231
+ }
232
+ }
233
+ /**
234
+ * Connect to every server the client sent for a session, all at once, and
235
+ * gather their tools, keeping the first tool to take each name.
236
+ */
237
+ async function connect_mcp_servers(servers, cwd, identity) {
238
+ if (servers.length === 0) return NO_MCP;
239
+ const handles = (await Promise.all(servers.map((server) => connect_server(server, cwd, identity)))).filter((handle) => handle !== void 0);
240
+ const tools = /* @__PURE__ */ new Map();
241
+ for (const tool of handles.flatMap((handle) => handle.tools)) if (tools.has(tool.name)) warn(`two MCP servers offer a tool named ${tool.name}, so the second one's is left out`);
242
+ else tools.set(tool.name, tool);
243
+ return {
244
+ tools: [...tools.values()],
245
+ close: () => close_all(handles)
246
+ };
247
+ }
248
+ /**
249
+ * Whether one of the session's MCP tools was asked about this very input,
250
+ * which makes the call one of theirs rather than a call to a tool that only
251
+ * shares a name with one.
252
+ */
253
+ function is_mcp_call(session, input) {
254
+ return is_record$1(input) && asked$1.get(session)?.has(input) === true;
255
+ }
256
+ /**
257
+ * The session's MCP tools, each asking before it runs whenever the
258
+ * session's mode asks before a command, and marking the input it was asked
259
+ * about as one of the session's own MCP calls. The tools are made as the
260
+ * session is, so they reach it through `session` at each call.
261
+ */
262
+ function gated_mcp_tools(tools, session) {
263
+ return tools.map((tool) => ({
264
+ ...tool,
265
+ needs_approval: (input) => {
266
+ const current = session();
267
+ const inputs = asked$1.get(current) ?? /* @__PURE__ */ new WeakSet();
268
+ asked$1.set(current, inputs);
269
+ if (is_record$1(input)) inputs.add(input);
270
+ return asks_before(current.mode(), "command");
271
+ }
272
+ }));
273
+ }
274
+ //#endregion
149
275
  //#region src/acp/tools/previews.ts
150
276
  const stores = /* @__PURE__ */ new WeakMap();
151
277
  /**
@@ -705,7 +831,7 @@ function is_workspace_tool(session, name) {
705
831
  * tool that only shares a name with one.
706
832
  */
707
833
  function is_workspace_call(session, input) {
708
- return is_record(input) && asked.get(session)?.has(input) === true;
834
+ return is_record$1(input) && asked.get(session)?.has(input) === true;
709
835
  }
710
836
  /**
711
837
  * `tool`, asking for approval before each call when the session's mode asks
@@ -717,7 +843,7 @@ function gated(tool, session, action) {
717
843
  return {
718
844
  ...tool,
719
845
  needs_approval: (input) => {
720
- if (is_record(input)) asked_of(session).add(input);
846
+ if (is_record$1(input)) asked_of(session).add(input);
721
847
  return asks_before(session.mode(), action);
722
848
  }
723
849
  };
@@ -1074,9 +1200,11 @@ function closing_updates(session, name, card, chunk, closing) {
1074
1200
  * and never offered one, since anything can follow a `;` or a `|`.
1075
1201
  *
1076
1202
  * Only the session's own workspace tools get the diff and the "always",
1077
- * known by the input their `needs_approval` marked rather than by name. A
1078
- * tool of a flow's own or an MCP tool that shares a name gets the plain
1079
- * request, and no grant covers it.
1203
+ * known by the input their `needs_approval` marked rather than by name. The
1204
+ * tools of the MCP servers the client sent ask as a command does, and their
1205
+ * "always" covers that one tool for the session. A tool of a flow's own
1206
+ * that shares a name with either gets the plain request, and no grant
1207
+ * covers it.
1080
1208
  *
1081
1209
  * A permission check that fails open isn't a check, so anything short of
1082
1210
  * an allow denies the call: a rejection, a `cancelled` outcome, an option
@@ -1091,16 +1219,29 @@ function closing_updates(session, name, card, chunk, closing) {
1091
1219
  * ends it.
1092
1220
  */
1093
1221
  const GATES = /* @__PURE__ */ new Map([
1094
- ["write_file", {
1095
- action: "edit",
1096
- change: write_file_change
1097
- }],
1098
- ["edit_file", {
1099
- action: "edit",
1100
- change: edit_file_change
1101
- }],
1102
- ["run_command", { action: "command" }]
1222
+ ["write_file", { change: write_file_change }],
1223
+ ["edit_file", { change: edit_file_change }],
1224
+ ["run_command", { grant: (request) => {
1225
+ const line = command_key(request.input);
1226
+ return line === void 0 ? void 0 : {
1227
+ key: `command ${line}`,
1228
+ name: `Always allow \`${line}\` this session`
1229
+ };
1230
+ } }]
1103
1231
  ]);
1232
+ /** The gate every MCP tool's call goes through: it asks as a command does, and the grant covers the tool. */
1233
+ const MCP_GATE = { grant: (request) => ({
1234
+ key: `tool ${request.tool_name}`,
1235
+ name: `Always allow ${request.tool_name} this session`
1236
+ }) };
1237
+ /**
1238
+ * The gate a call goes through: its workspace tool's, the MCP tools' for a
1239
+ * call one of the session's MCP tools marked, and none for any other call.
1240
+ */
1241
+ function gate_for(session, request) {
1242
+ if (is_workspace_call(session, request.input)) return GATES.get(request.tool_name);
1243
+ return is_mcp_call(session, request.input) ? MCP_GATE : void 0;
1244
+ }
1104
1245
  /**
1105
1246
  * Shell syntax that runs, chains, or redirects something past the
1106
1247
  * command's own program: `;`, `&`, `|`, `>`, `<`, a backtick, `$(`, and a
@@ -1308,12 +1449,12 @@ function warn_failed(tool_name, err) {
1308
1449
  }
1309
1450
  /**
1310
1451
  * The "always" a call is offered: Accept edits for an edit, when the agent
1311
- * offers that mode, and a grant of its key for a command that has one. Any
1312
- * other call gets none. Choosing Accept edits leaves a session that has
1313
- * moved past Manual since the call asked where it is.
1452
+ * offers that mode, and the grant its gate makes for a command line or an
1453
+ * MCP tool. Any other call gets none. Choosing Accept edits leaves a session
1454
+ * that has moved past Manual since the call asked where it is.
1314
1455
  */
1315
- function always_for(gate, key, modes, granted) {
1316
- if (gate?.action === "edit") {
1456
+ function always_for(gate, grant, modes, granted) {
1457
+ if (gate?.change !== void 0) {
1317
1458
  if (!modes.offers("accept_edits")) return void 0;
1318
1459
  return {
1319
1460
  name: "Allow all edits this session",
@@ -1322,11 +1463,11 @@ function always_for(gate, key, modes, granted) {
1322
1463
  }
1323
1464
  };
1324
1465
  }
1325
- if (key === void 0) return void 0;
1466
+ if (grant === void 0) return void 0;
1326
1467
  return {
1327
- name: `Always allow \`${key}\` this session`,
1468
+ name: grant.name,
1328
1469
  grant: async () => {
1329
- granted.add(key);
1470
+ granted.add(grant.key);
1330
1471
  }
1331
1472
  };
1332
1473
  }
@@ -1353,10 +1494,10 @@ function options_for(always) {
1353
1494
  function session_approver({ modes, cards, ask }) {
1354
1495
  const granted = /* @__PURE__ */ new Set();
1355
1496
  return async (session, request) => {
1356
- const gate = is_workspace_call(session, request.input) ? GATES.get(request.tool_name) : void 0;
1357
- const key = gate?.action === "command" ? command_key(request.input) : void 0;
1358
- if (key !== void 0 && granted.has(key)) return true;
1359
- const always = always_for(gate, key, modes, granted);
1497
+ const gate = gate_for(session, request);
1498
+ const grant = gate?.grant?.(request);
1499
+ if (grant !== void 0 && granted.has(grant.key)) return true;
1500
+ const always = always_for(gate, grant, modes, granted);
1360
1501
  const options = options_for(always);
1361
1502
  try {
1362
1503
  await unless_aborted(request.abort, cards.caught_up);
@@ -1373,6 +1514,85 @@ function session_approver({ modes, cards, ask }) {
1373
1514
  };
1374
1515
  }
1375
1516
  //#endregion
1517
+ //#region src/acp/models.ts
1518
+ /** The id of the config option that carries the model. */
1519
+ const MODEL_CONFIG_ID = "model";
1520
+ /**
1521
+ * The models an agent offers, from the config's `models` and
1522
+ * `default_model`, or undefined for an agent that offers none. Throws an
1523
+ * `Error` that names the problem for a `models` that's empty or lists an id
1524
+ * twice, a `default_model` it doesn't list, a `default_model` without
1525
+ * `models`, and a flow built once, which can't change its model, so
1526
+ * `acp_agent` fails as it's built.
1527
+ */
1528
+ function model_offer(config) {
1529
+ const { models, default_model } = config;
1530
+ if (models === void 0) {
1531
+ if (default_model === void 0) return void 0;
1532
+ throw new Error("acp_agent: default_model is set without models; list the models a session can run on, or leave default_model out");
1533
+ }
1534
+ if (typeof config.flow !== "function") throw new Error("acp_agent: models needs flow to be a function of the session, since a flow built once can't change its model; build the flow with session.model()");
1535
+ const ids = models.map((model) => model.id);
1536
+ const [first] = ids;
1537
+ if (first === void 0) throw new Error("acp_agent: models is empty; list at least one model, or leave models out");
1538
+ const repeated = ids.find((id, index) => ids.indexOf(id) !== index);
1539
+ if (repeated !== void 0) throw new Error(`acp_agent: models lists ${JSON.stringify(repeated)} twice; give each model its own id`);
1540
+ const start = default_model ?? first;
1541
+ if (!ids.includes(start)) throw new Error(`acp_agent: default_model ${JSON.stringify(start)} isn't one of the models (${ids.join(", ")}); add it to models or leave default_model out`);
1542
+ return {
1543
+ models,
1544
+ default_model: start
1545
+ };
1546
+ }
1547
+ /**
1548
+ * Whether the agent offers a model with the id `id`.
1549
+ */
1550
+ function offers_model(offer, id) {
1551
+ return offer.models.some((model) => model.id === id);
1552
+ }
1553
+ /**
1554
+ * The model a session starts on: the one it was stored with when the agent
1555
+ * still offers it, and the offer's `default_model` otherwise, or undefined
1556
+ * for an agent that offers none.
1557
+ */
1558
+ function start_model(offer, stored) {
1559
+ if (offer === void 0) return void 0;
1560
+ return offers_model(offer, stored) ? stored : offer.default_model;
1561
+ }
1562
+ /**
1563
+ * The refusal for a model id the agent doesn't offer, naming the ones it does.
1564
+ */
1565
+ function unknown_model_message(id, offer) {
1566
+ return `unknown model ${JSON.stringify(id)}; choose one of ${offer.models.map((model) => model.id).join(", ")}`;
1567
+ }
1568
+ /**
1569
+ * The session's model as a config option, a select over every model the
1570
+ * agent offers, or none for an agent that offers no models.
1571
+ */
1572
+ function model_options(offer, model) {
1573
+ if (offer === void 0 || model === void 0) return [];
1574
+ return [{
1575
+ id: MODEL_CONFIG_ID,
1576
+ name: "Model",
1577
+ description: "The model that answers the next turn",
1578
+ category: "model",
1579
+ type: "select",
1580
+ currentValue: model,
1581
+ options: offer.models.map(({ id, name, description }) => ({
1582
+ value: id,
1583
+ name: name ?? id,
1584
+ ...description === void 0 ? {} : { description }
1585
+ }))
1586
+ }];
1587
+ }
1588
+ /**
1589
+ * The context window a session's context ring is drawn against: the
1590
+ * window its model names, and the config's `context_window` otherwise.
1591
+ */
1592
+ function context_window_of(config, model) {
1593
+ return config.models?.find((entry) => entry.id === model)?.context_window ?? config.context_window;
1594
+ }
1595
+ //#endregion
1376
1596
  //#region src/acp/to_session_updates.ts
1377
1597
  /**
1378
1598
  * Maps a run's events onto ACP `session/update` payloads.
@@ -1529,6 +1749,93 @@ function to_session_updates(event, state) {
1529
1749
  return map_chunk(chunk, step_id, state);
1530
1750
  }
1531
1751
  //#endregion
1752
+ //#region src/acp/usage.ts
1753
+ /**
1754
+ * A session's usage before its first turn.
1755
+ */
1756
+ function create_session_usage() {
1757
+ return {
1758
+ context_tokens: 0,
1759
+ cost_usd: 0,
1760
+ priced: false
1761
+ };
1762
+ }
1763
+ /**
1764
+ * The stream chunk a `model_chunk` event carries, or undefined for any other
1765
+ * event.
1766
+ */
1767
+ function chunk_of(event) {
1768
+ if (event.kind !== "model_chunk") return void 0;
1769
+ const chunk = event["chunk"];
1770
+ return is_stream_chunk(chunk) ? chunk : void 0;
1771
+ }
1772
+ /**
1773
+ * The tokens a model turn left in the context, from either way a turn is
1774
+ * reported, or undefined for any other event.
1775
+ */
1776
+ function context_of(event) {
1777
+ if (event.kind === "response_received") {
1778
+ const input = event["input_tokens"];
1779
+ const output = event["output_tokens"];
1780
+ return typeof input === "number" && typeof output === "number" ? input + output : void 0;
1781
+ }
1782
+ const chunk = chunk_of(event);
1783
+ return chunk?.kind === "step_finish" ? chunk.usage.input_tokens + chunk.usage.output_tokens : void 0;
1784
+ }
1785
+ /**
1786
+ * Fold one run event into the session's usage, and say whether it changed,
1787
+ * so a turn that a provider reports twice tells the client once.
1788
+ */
1789
+ function note_usage(usage, event) {
1790
+ if (event.kind === "cost") {
1791
+ const total = event["total_usd"];
1792
+ if (typeof total !== "number") return false;
1793
+ usage.cost_usd += total;
1794
+ usage.priced = true;
1795
+ return true;
1796
+ }
1797
+ const context = context_of(event);
1798
+ if (context === void 0 || context === usage.context_tokens) return false;
1799
+ usage.context_tokens = context;
1800
+ return true;
1801
+ }
1802
+ /**
1803
+ * The session's usage as the update a client draws its context ring from,
1804
+ * against a context window of `size` tokens.
1805
+ */
1806
+ function usage_update(usage, size) {
1807
+ return {
1808
+ sessionUpdate: "usage_update",
1809
+ used: usage.context_tokens,
1810
+ size,
1811
+ ...usage.priced ? { cost: {
1812
+ amount: usage.cost_usd,
1813
+ currency: "USD"
1814
+ } } : {}
1815
+ };
1816
+ }
1817
+ /**
1818
+ * The finish reason a model call's `finish` chunk carries, or undefined for
1819
+ * any other event.
1820
+ */
1821
+ function finish_reason_of(event) {
1822
+ const chunk = chunk_of(event);
1823
+ return chunk?.kind === "finish" ? chunk.finish_reason : void 0;
1824
+ }
1825
+ /**
1826
+ * The stop reason for a turn that wasn't cancelled, from the finish reason of
1827
+ * the last model call that finished in it, which is the one whose reply the
1828
+ * user reads. A call that ran out of tool turns, ran out of output tokens, or
1829
+ * was stopped by the provider's filter says so, rather than reading as a turn
1830
+ * that finished.
1831
+ */
1832
+ function stop_reason_for(finish) {
1833
+ if (finish === "max_steps") return "max_turn_requests";
1834
+ if (finish === "length") return "max_tokens";
1835
+ if (finish === "content_filter") return "refusal";
1836
+ return "end_turn";
1837
+ }
1838
+ //#endregion
1532
1839
  //#region src/acp/prompt_turn.ts
1533
1840
  /**
1534
1841
  * Join a prompt's blocks into the text a flow reads. Text blocks join as the
@@ -1558,6 +1865,29 @@ function turn_input(config, turn) {
1558
1865
  if (config.to_input !== void 0) return config.to_input(turn);
1559
1866
  return turn.text;
1560
1867
  }
1868
+ /** The most characters a default title keeps. */
1869
+ const TITLE_LIMIT = 60;
1870
+ /**
1871
+ * The default `to_title`: the first line of the turn's text with its
1872
+ * whitespace collapsed, cut to `TITLE_LIMIT` characters.
1873
+ */
1874
+ function default_title(turn) {
1875
+ const words = (turn.text.split("\n").find((text) => text.trim() !== "") ?? "").trim().replaceAll(/\s+/g, " ");
1876
+ return words.length <= TITLE_LIMIT ? words : `${words.slice(0, 59).trimEnd()}…`;
1877
+ }
1878
+ /**
1879
+ * Name the session from its first turn, and tell the client, which shows it
1880
+ * on the thread. A session already named keeps its title, and an empty one
1881
+ * leaves the thread untitled.
1882
+ */
1883
+ async function name_session(config, record, turn, send) {
1884
+ if (record.title !== null) return;
1885
+ record.title = (config.to_title ?? default_title)(turn);
1886
+ if (record.title !== "") await send({
1887
+ sessionUpdate: "session_info_update",
1888
+ title: record.title
1889
+ });
1890
+ }
1561
1891
  /**
1562
1892
  * The default `to_text`: a string as-is, anything else as JSON, and nothing
1563
1893
  * at all for a flow that returns nothing.
@@ -1635,9 +1965,32 @@ function warn_dropped(event) {
1635
1965
  process.stderr.write(`fascicle/acp: the client read updates slower than the run produced them, so ${String(event["count"])} run events were dropped and the reply is missing text from that point; send the prompt again for the whole reply\n`);
1636
1966
  }
1637
1967
  /**
1968
+ * Send `updates` in order until the turn is cancelled, and say whether all
1969
+ * of them went out.
1970
+ */
1971
+ async function send_all(updates, cancelled, send) {
1972
+ for (const update of updates) {
1973
+ if (cancelled.aborted) return false;
1974
+ await send(update);
1975
+ }
1976
+ return true;
1977
+ }
1978
+ /**
1979
+ * Fold a run event into the session's usage, and return the `usage_update`
1980
+ * that a change sends, when the config names the context window.
1981
+ */
1982
+ function usage_updates(config, record, event) {
1983
+ const changed = note_usage(record.usage, event);
1984
+ const window = context_window_of(config, record.session.model());
1985
+ return changed && window !== void 0 ? [usage_update(record.usage, window)] : [];
1986
+ }
1987
+ /**
1638
1988
  * Send each run event's updates in order, and tell the session's card sync
1639
- * once all of an event's updates have gone out. Once the turn is cancelled
1640
- * nothing more is sent, and leaving the loop closes the run's event stream.
1989
+ * once all of an event's updates have gone out. Each event also folds into
1990
+ * the session's usage, and a change goes out as a `usage_update` when the
1991
+ * config names the context window. Once the turn is cancelled nothing more
1992
+ * is sent, and leaving the loop closes the run's event stream. Resolves with
1993
+ * the finish reason of the last model call that finished.
1641
1994
  */
1642
1995
  async function forward(events, config, record, cancelled, send) {
1643
1996
  const state = create_acp_mapper_state({
@@ -1645,20 +1998,23 @@ async function forward(events, config, record, cancelled, send) {
1645
1998
  session: record.session
1646
1999
  });
1647
2000
  const to_updates = config.to_updates ?? to_session_updates;
2001
+ let finish;
1648
2002
  for await (const event of events) {
1649
2003
  if (event.kind === "events_dropped") warn_dropped(event);
2004
+ finish = finish_reason_of(event) ?? finish;
1650
2005
  const updates = to_updates(event, state);
1651
- for (const update of updates) {
1652
- if (cancelled.aborted) return;
1653
- await send(update);
1654
- }
2006
+ if (!await send_all(updates, cancelled, send)) return finish;
1655
2007
  record.cards.sent(event, updates);
2008
+ if (!await send_all(usage_updates(config, record, event), cancelled, send)) return finish;
1656
2009
  }
2010
+ return finish;
1657
2011
  }
1658
2012
  /**
1659
2013
  * Run the flow for one turn, forward its updates, and record the exchange.
1660
2014
  * The run has always settled by the time this returns or throws, so a turn
1661
- * never leaves a run behind.
2015
+ * never leaves a run behind. A turn that ends in a refusal stays out of the
2016
+ * history, since the protocol has the client leave it out of the next prompt
2017
+ * too.
1662
2018
  */
1663
2019
  async function run_turn(config, record, prompt, cancelled, send) {
1664
2020
  const turn = {
@@ -1685,8 +2041,10 @@ async function run_turn(config, record, prompt, cancelled, send) {
1685
2041
  trajectory: record.cards.start(config.trajectory)
1686
2042
  });
1687
2043
  const outcome = settle(handle.result);
2044
+ let finish;
1688
2045
  try {
1689
- await forward(handle.events, config, record, cancelled, send_update);
2046
+ await name_session(config, record, turn, send_update);
2047
+ finish = await forward(handle.events, config, record, cancelled, send_update);
1690
2048
  const result = await outcome;
1691
2049
  if (!cancelled.aborted) {
1692
2050
  if (!result.ok) throw result.error;
@@ -1698,8 +2056,9 @@ async function run_turn(config, record, prompt, cancelled, send) {
1698
2056
  await outcome;
1699
2057
  if (!cancelled.aborted) throw err;
1700
2058
  }
1701
- record_exchange(record.history, turn.text, reply.text, cancelled.aborted);
1702
- return { stopReason: cancelled.aborted ? "cancelled" : "end_turn" };
2059
+ const stop_reason = cancelled.aborted ? "cancelled" : stop_reason_for(finish);
2060
+ if (stop_reason !== "refusal") record_exchange(record.history, turn.text, reply.text, cancelled.aborted);
2061
+ return { stopReason: stop_reason };
1703
2062
  }
1704
2063
  /**
1705
2064
  * Run one prompt turn and answer with its stop reason. A new prompt cancels
@@ -1790,7 +2149,19 @@ async function load_acp_sdk() {
1790
2149
  * to anything the SDK can: `serve_acp`'s stdio streams, or an in-process
1791
2150
  * `client()` in a test. It doesn't own the process, so it leaves the console
1792
2151
  * and the engine alone; `serve_acp` handles both.
2152
+ *
2153
+ * Given a session store, it saves each session after every turn and every
2154
+ * mode or model switch, and answers `session/list`, `session/load`, and
2155
+ * `session/resume` from it. A loaded session gets a fresh flow from the
2156
+ * config, and the history it carries is what its next turn starts from.
2157
+ *
2158
+ * A session holds what the client gave it until the client closes it with
2159
+ * `session/close` or drops the connection: its MCP servers, for an agent
2160
+ * that connects to them, are closed then, and a closed session leaves
2161
+ * memory, though not the store.
1793
2162
  */
2163
+ /** Every config option id a session can have, as a refusal lists them. */
2164
+ const CONFIG_IDS = `${MODE_CONFIG_ID} and ${MODEL_CONFIG_ID}`;
1794
2165
  const ONE_CONNECTION = "acp_agent: this app already serves a connection; build an app for each connection, as serve_acp does";
1795
2166
  /**
1796
2167
  * Turn a failure inside a handler into a JSON-RPC error that carries its
@@ -1818,6 +2189,14 @@ function permission_asker(sdk, client) {
1818
2189
  return (request, cancel) => client.request(sdk.methods.client.session.requestPermission, request, { cancellationSignal: cancel });
1819
2190
  }
1820
2191
  /**
2192
+ * The model a client asked for, or an invalid-params error naming the
2193
+ * models the agent offers.
2194
+ */
2195
+ function requested_model(sdk, offer, id) {
2196
+ if (offers_model(offer, id)) return id;
2197
+ throw sdk.RequestError.invalidParams({ value: id }, unknown_model_message(id, offer));
2198
+ }
2199
+ /**
1821
2200
  * The mode a client asked for, or an invalid-params error naming the modes
1822
2201
  * the agent offers, for a mode it doesn't know and one it leaves out alike.
1823
2202
  * `field` is the param the id arrived in, for the error's data.
@@ -1839,6 +2218,66 @@ function requested_directories(sdk, config, method, directories = []) {
1839
2218
  throw sdk.RequestError.invalidParams({ additionalDirectories: directories }, `this agent works in cwd alone and takes no additional directories; send ${method} without additionalDirectories`);
1840
2219
  }
1841
2220
  /**
2221
+ * A session's state as the store keeps it, copied, so a turn that runs while
2222
+ * the save is writing can't change what it writes.
2223
+ */
2224
+ function stored_session(record) {
2225
+ return {
2226
+ id: record.session.id,
2227
+ cwd: record.session.cwd,
2228
+ additional_directories: [...record.session.additional_directories],
2229
+ mode: record.modes.current(),
2230
+ model: record.model.id,
2231
+ title: record.title,
2232
+ updated_at: (/* @__PURE__ */ new Date()).toISOString(),
2233
+ history: structuredClone(record.history),
2234
+ usage: { ...record.usage }
2235
+ };
2236
+ }
2237
+ /**
2238
+ * Save a session after the save before it. A session with no history yet
2239
+ * isn't saved, so a thread the user never wrote in doesn't fill the list. A
2240
+ * failed save is reported on stderr rather than failing the turn the user
2241
+ * already watched finish, and it leaves the session as it was in the store.
2242
+ */
2243
+ function save_session(config, record) {
2244
+ const store = config.session_store;
2245
+ if (store === void 0 || record.history.length === 0) return Promise.resolve();
2246
+ const snapshot = stored_session(record);
2247
+ record.saving = record.saving.then(() => store.save(snapshot)).catch((err) => {
2248
+ process.stderr.write(`fascicle/acp: couldn't save session ${snapshot.id}: ${message_of(err)}\n`);
2249
+ });
2250
+ return record.saving;
2251
+ }
2252
+ /**
2253
+ * A history entry as the update that shows it again in a loaded thread.
2254
+ */
2255
+ function replayed(entry) {
2256
+ const content = {
2257
+ type: "text",
2258
+ text: entry.text
2259
+ };
2260
+ return entry.role === "user" ? {
2261
+ sessionUpdate: "user_message_chunk",
2262
+ content
2263
+ } : {
2264
+ sessionUpdate: "agent_message_chunk",
2265
+ content
2266
+ };
2267
+ }
2268
+ /**
2269
+ * A stored session as `session/list` reports one.
2270
+ */
2271
+ function session_info(summary) {
2272
+ return {
2273
+ sessionId: summary.id,
2274
+ cwd: summary.cwd,
2275
+ updatedAt: summary.updated_at,
2276
+ ...summary.additional_directories.length > 0 ? { additionalDirectories: [...summary.additional_directories] } : {},
2277
+ ...summary.title !== null && summary.title !== "" ? { title: summary.title } : {}
2278
+ };
2279
+ }
2280
+ /**
1842
2281
  * Build the ACP agent app that answers each prompt turn by running the
1843
2282
  * config's flow, with its handlers registered and not yet connected.
1844
2283
  *
@@ -1850,8 +2289,14 @@ function requested_directories(sdk, config, method, directories = []) {
1850
2289
  */
1851
2290
  async function acp_agent(config) {
1852
2291
  const offer = mode_offer(config);
2292
+ const models = model_offer(config);
1853
2293
  const sdk = await load_acp_sdk();
1854
2294
  const sessions = /* @__PURE__ */ new Map();
2295
+ const store = config.session_store;
2296
+ const identity = {
2297
+ name: config.name,
2298
+ version: config.version ?? "0.0.0"
2299
+ };
1855
2300
  let client_capabilities = {};
1856
2301
  let connected = false;
1857
2302
  let initialized = false;
@@ -1860,43 +2305,25 @@ async function acp_agent(config) {
1860
2305
  if (record !== void 0) return record;
1861
2306
  throw sdk.RequestError.invalidParams({ sessionId }, `unknown session ${sessionId}; start one with session/new first`);
1862
2307
  };
1863
- return sdk.agent().onConnect(() => {
1864
- if (connected) throw new Error(ONE_CONNECTION);
1865
- connected = true;
1866
- }).onRequest("initialize", (ctx) => {
1867
- if (initialized) throw sdk.RequestError.invalidRequest(void 0, ONE_CONNECTION);
1868
- initialized = true;
1869
- client_capabilities = ctx.params.clientCapabilities ?? {};
1870
- return {
1871
- protocolVersion: sdk.PROTOCOL_VERSION,
1872
- agentInfo: {
1873
- name: config.name,
1874
- version: config.version ?? "0.0.0"
1875
- },
1876
- agentCapabilities: {
1877
- loadSession: false,
1878
- promptCapabilities: { embeddedContext: true },
1879
- sessionCapabilities: config.additional_directories === false ? {} : { additionalDirectories: {} }
1880
- },
1881
- authMethods: []
1882
- };
1883
- }).onRequest("authenticate", () => ({})).onRequest("session/new", async (ctx) => {
1884
- const { cwd } = ctx.params;
1885
- const additional_directories = requested_directories(sdk, config, "session/new", ctx.params.additionalDirectories);
2308
+ const options_of = (record) => [...config_options(offer, record.modes.current()), ...model_options(models, record.model.id)];
2309
+ const build_flow = (session) => typeof config.flow === "function" ? config.flow(session) : config.flow;
2310
+ const open_session = async (client, start) => {
2311
+ const { id, cwd, additional_directories, stored } = start;
1886
2312
  const roots = await resolve_roots([cwd, ...additional_directories]).catch((err) => {
1887
2313
  throw sdk.RequestError.invalidParams({
1888
2314
  cwd,
1889
2315
  additionalDirectories: additional_directories
1890
2316
  }, message_of(err));
1891
2317
  });
1892
- const id = randomUUID();
1893
- const modes = session_modes(offer, sender(sdk, ctx.client, id));
2318
+ const model = { id: start_model(models, stored?.model) };
2319
+ const modes = session_modes(offer, sender(sdk, client, id), stored?.mode, () => model_options(models, model.id));
1894
2320
  const cards = create_card_sync();
1895
2321
  const approver = session_approver({
1896
2322
  modes,
1897
2323
  cards,
1898
- ask: permission_asker(sdk, ctx.client)
2324
+ ask: permission_asker(sdk, client)
1899
2325
  });
2326
+ const mcp = config.mcp_servers === true ? await connect_mcp_servers(start.mcp_servers, cwd, identity) : NO_MCP;
1900
2327
  const session = {
1901
2328
  id,
1902
2329
  cwd,
@@ -1904,26 +2331,137 @@ async function acp_agent(config) {
1904
2331
  roots,
1905
2332
  client_capabilities,
1906
2333
  mode: modes.current,
2334
+ model: () => model.id,
2335
+ mcp_tools: gated_mcp_tools(mcp.tools, () => session),
1907
2336
  approve: (request) => approver(session, request)
1908
2337
  };
2338
+ const usage = stored === void 0 ? create_session_usage() : { ...stored.usage };
1909
2339
  try {
1910
- const flow = typeof config.flow === "function" ? config.flow(session) : config.flow;
1911
- sessions.set(id, {
2340
+ const record = {
1912
2341
  session,
1913
- flow,
1914
- history: [],
2342
+ flow: build_flow(session),
2343
+ history: structuredClone([...stored?.history ?? []]),
1915
2344
  cards,
2345
+ usage,
1916
2346
  last_turn: null,
1917
- modes
1918
- });
2347
+ title: stored?.title ?? null,
2348
+ modes,
2349
+ model,
2350
+ mcp,
2351
+ saving: Promise.resolve()
2352
+ };
2353
+ sessions.set(id, record);
2354
+ return record;
1919
2355
  } catch (err) {
2356
+ await mcp.close();
1920
2357
  throw internal_error(sdk, err);
1921
2358
  }
2359
+ };
2360
+ const reopen = async (client, method, params) => {
2361
+ if (store === void 0) throw sdk.RequestError.methodNotFound(method);
2362
+ const { sessionId, cwd } = params;
2363
+ const additional_directories = requested_directories(sdk, config, method, params.additionalDirectories);
2364
+ const live = sessions.get(sessionId);
2365
+ const stored = live === void 0 ? await store.load(sessionId).catch((err) => {
2366
+ throw internal_error(sdk, err);
2367
+ }) : void 0;
2368
+ const started_in = live?.session.cwd ?? stored?.cwd;
2369
+ if (started_in === void 0) throw sdk.RequestError.invalidParams({ sessionId }, `unknown session ${sessionId}; list the stored ones with session/list`);
2370
+ if (started_in !== cwd) throw sdk.RequestError.invalidParams({
2371
+ sessionId,
2372
+ cwd
2373
+ }, `session ${sessionId} started in ${started_in}; send that cwd with ${method}`);
2374
+ return live ?? open_session(client, {
2375
+ id: sessionId,
2376
+ cwd,
2377
+ additional_directories,
2378
+ mcp_servers: params.mcpServers ?? [],
2379
+ stored
2380
+ });
2381
+ };
2382
+ const reopened = async (client, record) => {
2383
+ const send = sender(sdk, client, record.session.id);
2384
+ if (record.title !== null && record.title !== "") await send({
2385
+ sessionUpdate: "session_info_update",
2386
+ title: record.title
2387
+ });
2388
+ const window = context_window_of(config, record.model.id);
2389
+ if (window !== void 0 && (record.usage.context_tokens > 0 || record.usage.priced)) await send(usage_update(record.usage, window));
1922
2390
  return {
1923
- sessionId: id,
1924
- modes: mode_state(offer, modes.current()),
1925
- configOptions: config_options(offer, modes.current())
2391
+ modes: mode_state(offer, record.modes.current()),
2392
+ configOptions: options_of(record)
1926
2393
  };
2394
+ };
2395
+ const switch_model = (record, next) => {
2396
+ const previous = record.model.id;
2397
+ record.model.id = next;
2398
+ try {
2399
+ record.flow = build_flow(record.session);
2400
+ } catch (err) {
2401
+ record.model.id = previous;
2402
+ throw internal_error(sdk, err);
2403
+ }
2404
+ };
2405
+ const close_session = async (record) => {
2406
+ sessions.delete(record.session.id);
2407
+ cancel_turn(record);
2408
+ await record.last_turn?.settled;
2409
+ await record.mcp.close();
2410
+ };
2411
+ return sdk.agent().onConnect((connection) => {
2412
+ if (connected) throw new Error(ONE_CONNECTION);
2413
+ connected = true;
2414
+ connection.closed.then(() => Promise.all([...sessions.values()].map(close_session)));
2415
+ }).onRequest("initialize", (ctx) => {
2416
+ if (initialized) throw sdk.RequestError.invalidRequest(void 0, ONE_CONNECTION);
2417
+ initialized = true;
2418
+ client_capabilities = ctx.params.clientCapabilities ?? {};
2419
+ return {
2420
+ protocolVersion: sdk.PROTOCOL_VERSION,
2421
+ agentInfo: identity,
2422
+ agentCapabilities: {
2423
+ loadSession: store !== void 0,
2424
+ promptCapabilities: { embeddedContext: true },
2425
+ ...config.mcp_servers === true ? { mcpCapabilities: MCP_CAPABILITIES } : {},
2426
+ sessionCapabilities: {
2427
+ close: {},
2428
+ ...config.additional_directories === false ? {} : { additionalDirectories: {} },
2429
+ ...store === void 0 ? {} : {
2430
+ list: {},
2431
+ resume: {}
2432
+ }
2433
+ }
2434
+ },
2435
+ authMethods: []
2436
+ };
2437
+ }).onRequest("authenticate", () => ({})).onRequest("session/new", async (ctx) => {
2438
+ const { cwd, mcpServers } = ctx.params;
2439
+ const additional_directories = requested_directories(sdk, config, "session/new", ctx.params.additionalDirectories);
2440
+ const record = await open_session(ctx.client, {
2441
+ id: randomUUID(),
2442
+ cwd,
2443
+ additional_directories,
2444
+ mcp_servers: mcpServers
2445
+ });
2446
+ return {
2447
+ sessionId: record.session.id,
2448
+ modes: mode_state(offer, record.modes.current()),
2449
+ configOptions: options_of(record)
2450
+ };
2451
+ }).onRequest("session/load", async (ctx) => {
2452
+ const record = await reopen(ctx.client, "session/load", ctx.params);
2453
+ const send = sender(sdk, ctx.client, record.session.id);
2454
+ for (const entry of record.history) await send(replayed(entry));
2455
+ return reopened(ctx.client, record);
2456
+ }).onRequest("session/resume", async (ctx) => reopened(ctx.client, await reopen(ctx.client, "session/resume", ctx.params))).onRequest("session/list", async (ctx) => {
2457
+ if (store === void 0) throw sdk.RequestError.methodNotFound("session/list");
2458
+ const { cwd } = ctx.params;
2459
+ return { sessions: (await store.list().catch((err) => {
2460
+ throw internal_error(sdk, err);
2461
+ })).filter((summary) => cwd === void 0 || cwd === null || summary.cwd === cwd).toSorted((a, b) => b.updated_at.localeCompare(a.updated_at)).map(session_info) };
2462
+ }).onRequest("session/close", async (ctx) => {
2463
+ await close_session(session_of(ctx.params.sessionId));
2464
+ return {};
1927
2465
  }).onRequest("session/prompt", async (ctx) => {
1928
2466
  const { sessionId, prompt } = ctx.params;
1929
2467
  const record = session_of(sessionId);
@@ -1931,18 +2469,26 @@ async function acp_agent(config) {
1931
2469
  return await prompt_turn(config, record, prompt, ctx.signal, sender(sdk, ctx.client, sessionId));
1932
2470
  } catch (err) {
1933
2471
  throw internal_error(sdk, err);
2472
+ } finally {
2473
+ await save_session(config, record);
1934
2474
  }
1935
2475
  }).onRequest("session/set_mode", async (ctx) => {
1936
2476
  const { sessionId, modeId } = ctx.params;
1937
- const { modes } = session_of(sessionId);
1938
- await modes.switch_to(requested_mode(sdk, offer, modes, modeId, "modeId"));
2477
+ const record = session_of(sessionId);
2478
+ await record.modes.switch_to(requested_mode(sdk, offer, record.modes, modeId, "modeId"));
2479
+ await save_session(config, record);
1939
2480
  return {};
1940
2481
  }).onRequest("session/set_config_option", async (ctx) => {
1941
2482
  const { sessionId, configId, value } = ctx.params;
1942
- const { modes } = session_of(sessionId);
1943
- if (configId !== "mode") throw sdk.RequestError.invalidParams({ configId }, `unknown config option ${configId}; the only one is ${MODE_CONFIG_ID}`);
1944
- await modes.switch_to(requested_mode(sdk, offer, modes, value, "value"));
1945
- return { configOptions: config_options(offer, modes.current()) };
2483
+ const record = session_of(sessionId);
2484
+ if (configId === "mode") await record.modes.switch_to(requested_mode(sdk, offer, record.modes, value, "value"));
2485
+ else if (configId === "model" && models !== void 0) switch_model(record, requested_model(sdk, models, value));
2486
+ else {
2487
+ const known = models === void 0 ? `the only one is ${MODE_CONFIG_ID}` : `the options are ${CONFIG_IDS}`;
2488
+ throw sdk.RequestError.invalidParams({ configId }, `unknown config option ${configId}; ${known}`);
2489
+ }
2490
+ await save_session(config, record);
2491
+ return { configOptions: options_of(record) };
1946
2492
  }).onNotification("session/cancel", (ctx) => {
1947
2493
  const record = sessions.get(ctx.params.sessionId);
1948
2494
  if (record !== void 0) cancel_turn(record);
@@ -2030,6 +2576,127 @@ async function serve_acp(config) {
2030
2576
  if (received !== null) process.exit(128 + constants.signals[received]);
2031
2577
  }
2032
2578
  //#endregion
2033
- export { acp_agent, acp_sdk_missing_error, create_acp_mapper_state, serve_acp, to_session_updates, workspace_tools };
2579
+ //#region src/acp/session_store.ts
2580
+ /**
2581
+ * session_store: a filesystem store for ACP sessions, one JSON file each.
2582
+ *
2583
+ * A session is saved as `<id>.json` under the root directory. A save writes a
2584
+ * temporary sibling first and renames it into place, so a crash mid-write
2585
+ * leaves the earlier copy whole. A session holds the whole conversation,
2586
+ * which can carry code or a key the user pasted, so the directory the store
2587
+ * makes is readable by its owner alone, and so is every file it writes. A session id comes from the client on
2588
+ * `session/load` and `session/resume`, so only an id made of letters, digits,
2589
+ * `-`, and `_` names a file, and any other id reads as a session the store
2590
+ * doesn't hold rather than as a path. A file that isn't a stored session
2591
+ * fails its load with a message naming it, and `list` skips it with a
2592
+ * warning on stderr, so one bad file can't hide every other thread.
2593
+ *
2594
+ * Paths are accepted at construction; the store never reads `process.env`.
2595
+ */
2596
+ /** The ids that can name a file, which every id the agent makes matches. */
2597
+ const SAFE_ID = /^[\w-]+$/;
2598
+ /**
2599
+ * Whether `value` is a plain object, read as a record of unknown fields.
2600
+ */
2601
+ function is_record(value) {
2602
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2603
+ }
2604
+ /**
2605
+ * Whether `value` is a list of strings.
2606
+ */
2607
+ function is_strings(value) {
2608
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");
2609
+ }
2610
+ /**
2611
+ * Whether `value` is one history entry, with a role, its text, and, on the
2612
+ * entry where a cancelled turn stopped, the mark that says so.
2613
+ */
2614
+ function is_history_entry(value) {
2615
+ if (!is_record(value)) return false;
2616
+ const { role, text, cancelled } = value;
2617
+ return (role === "user" || role === "agent") && typeof text === "string" && (cancelled === void 0 || cancelled === true);
2618
+ }
2619
+ /**
2620
+ * Whether `value` is a session's usage.
2621
+ */
2622
+ function is_usage(value) {
2623
+ if (!is_record(value)) return false;
2624
+ const { context_tokens, cost_usd, priced } = value;
2625
+ return typeof context_tokens === "number" && typeof cost_usd === "number" && typeof priced === "boolean";
2626
+ }
2627
+ /**
2628
+ * Whether `value` is a stored session, checked field by field, since the
2629
+ * file is anything a person or another program left there.
2630
+ */
2631
+ function is_stored_session(value) {
2632
+ if (!is_record(value)) return false;
2633
+ const { id, cwd, additional_directories, mode, model, title, updated_at, history, usage } = value;
2634
+ 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);
2635
+ }
2636
+ /**
2637
+ * Read the session file at `path`, or undefined when there is none. Throws
2638
+ * an `Error` naming the file when it holds anything but a stored session.
2639
+ */
2640
+ async function read_session(path) {
2641
+ let text;
2642
+ try {
2643
+ text = await readFile(path, "utf8");
2644
+ } catch (err) {
2645
+ if (error_code(err) === "ENOENT") return void 0;
2646
+ throw err;
2647
+ }
2648
+ let value;
2649
+ try {
2650
+ value = JSON.parse(text);
2651
+ } catch {
2652
+ value = void 0;
2653
+ }
2654
+ if (is_stored_session(value)) return value;
2655
+ throw new Error(`${path} isn't a stored ACP session; fix or delete the file to load the others`);
2656
+ }
2657
+ /**
2658
+ * Build a session store that keeps one JSON file for each session under
2659
+ * `root_dir`.
2660
+ */
2661
+ function filesystem_session_store(config) {
2662
+ const path_of = (id) => join(config.root_dir, `${id}.json`);
2663
+ return {
2664
+ save: async (session) => {
2665
+ if (!SAFE_ID.test(session.id)) throw new Error(`can't save session ${JSON.stringify(session.id)}: an id names a file, so use letters, digits, - and _`);
2666
+ await mkdir(config.root_dir, {
2667
+ recursive: true,
2668
+ mode: 448
2669
+ });
2670
+ const temporary = join(config.root_dir, `.${session.id}.${randomUUID()}.tmp`);
2671
+ await writeFile(temporary, JSON.stringify(session), {
2672
+ encoding: "utf8",
2673
+ mode: 384
2674
+ });
2675
+ await rename(temporary, path_of(session.id));
2676
+ },
2677
+ load: async (id) => SAFE_ID.test(id) ? read_session(path_of(id)) : void 0,
2678
+ list: async () => {
2679
+ let names;
2680
+ try {
2681
+ names = await readdir(config.root_dir);
2682
+ } catch (err) {
2683
+ if (error_code(err) === "ENOENT") return [];
2684
+ throw err;
2685
+ }
2686
+ const files = names.filter((name) => name.endsWith(".json") && !name.startsWith("."));
2687
+ return (await Promise.all(files.map((name) => read_session(join(config.root_dir, name)).catch((err) => {
2688
+ process.stderr.write(`fascicle/acp: ${err instanceof Error ? err.message : String(err)}\n`);
2689
+ })))).filter((session) => session !== void 0).map(({ id, cwd, additional_directories, title, updated_at }) => ({
2690
+ id,
2691
+ cwd,
2692
+ additional_directories,
2693
+ title,
2694
+ updated_at
2695
+ }));
2696
+ }
2697
+ };
2698
+ }
2699
+ //#endregion
2700
+ export { acp_agent, acp_sdk_missing_error, create_acp_mapper_state, filesystem_session_store, serve_acp, to_session_updates, workspace_tools };
2034
2701
 
2035
2702
  //# sourceMappingURL=acp.js.map