apple-fm 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -3,19 +3,41 @@ import { spawn } from "child_process";
3
3
  import { fileURLToPath } from "url";
4
4
 
5
5
  // src/protocol.ts
6
+ var MAX_HELPER_FRAME_BYTES = 4 * 1024 * 1024;
7
+ var MAX_HELPER_STDERR_CHARS = 4096;
8
+ function assertHelperFrameSize(frame) {
9
+ if (Buffer.byteLength(frame) > MAX_HELPER_FRAME_BYTES) {
10
+ throw new Error("[protocolError] helper frame exceeds 4 MiB");
11
+ }
12
+ }
13
+ function helperDiagnostic(value) {
14
+ return value.slice(0, MAX_HELPER_STDERR_CHARS).replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "").replace(/[\p{Cc}\p{Cf}]+/gu, " ").trim();
15
+ }
16
+ function helperError(code, message) {
17
+ const label = /^[A-Za-z][A-Za-z0-9]{0,63}$/.test(code) ? code : "protocolError";
18
+ return new Error(`[${label}] ${helperDiagnostic(message)}`);
19
+ }
20
+ function parseWireJson(line, label) {
21
+ try {
22
+ return JSON.parse(line);
23
+ } catch {
24
+ throw new Error(`malformed ${label} JSON`);
25
+ }
26
+ }
6
27
  function encodeRequest(request) {
7
28
  return JSON.stringify(request) + "\n";
8
29
  }
9
- function splitLines(buffer) {
30
+ function splitLines(buffer, bounded = false) {
10
31
  const parts = buffer.split("\n");
32
+ if (bounded) for (const part of parts) assertHelperFrameSize(part);
11
33
  const rest = parts.pop() ?? "";
12
34
  const lines = parts.filter((line) => line.trim().length > 0);
13
35
  return { lines, rest };
14
36
  }
15
37
  function parseEvent(line) {
16
- const value = JSON.parse(line);
38
+ const value = parseWireJson(line, "helper event");
17
39
  if (typeof value !== "object" || value === null || !("type" in value)) {
18
- throw new Error(`malformed helper event: ${line}`);
40
+ throw new Error("malformed helper event");
19
41
  }
20
42
  const event = value;
21
43
  switch (event.type) {
@@ -34,7 +56,7 @@ function parseEvent(line) {
34
56
  default:
35
57
  break;
36
58
  }
37
- throw new Error(`malformed helper event: ${line}`);
59
+ throw new Error("malformed helper event");
38
60
  }
39
61
  var UNAVAILABLE_REASONS = [
40
62
  "deviceNotEligible",
@@ -44,19 +66,46 @@ var UNAVAILABLE_REASONS = [
44
66
  "unknown"
45
67
  ];
46
68
  function parseProbeResult(line) {
47
- const value = JSON.parse(line);
69
+ const value = parseWireJson(line, "probe result");
48
70
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
49
- throw new Error(`malformed probe result: ${line}`);
71
+ throw new Error("malformed probe result");
50
72
  }
51
73
  const record = value;
52
74
  if (typeof record.available !== "boolean") {
53
- throw new Error(`malformed probe result (available must be a boolean): ${line}`);
75
+ throw new Error("malformed probe result (available must be a boolean)");
54
76
  }
55
- if (record.available) return { available: true };
77
+ const models = record.models === void 0 ? {} : { models: parseModels(record.models) };
78
+ const contextSize = parseContextSize(record.contextSize);
79
+ const context = contextSize === void 0 ? {} : { contextSize };
80
+ if (record.available) return { available: true, ...models, ...context };
56
81
  if (typeof record.reason !== "string" || !UNAVAILABLE_REASONS.includes(record.reason)) {
57
- throw new Error(`malformed probe result (missing/unknown reason): ${line}`);
82
+ throw new Error("malformed probe result (missing/unknown reason)");
83
+ }
84
+ return { available: false, reason: record.reason, ...models, ...context };
85
+ }
86
+ function parseContextSize(value) {
87
+ return value === void 0 || value === 0 ? void 0 : parseTokenCount(value);
88
+ }
89
+ function parseTokenCount(value) {
90
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
91
+ throw new Error("malformed helper token count");
58
92
  }
59
- return { available: false, reason: record.reason };
93
+ return value;
94
+ }
95
+ function parseTokenCountResult(content) {
96
+ return parseTokenCount(parseWireJson(content, "helper token count"));
97
+ }
98
+ function parseModels(value) {
99
+ if (!Array.isArray(value)) throw new Error("malformed probe result (models must be an array)");
100
+ return value.map((entry) => {
101
+ if (typeof entry === "object" && entry !== null && "id" in entry && typeof entry.id === "string" && "available" in entry) {
102
+ if (entry.available === true) return { id: entry.id, available: true };
103
+ if (entry.available === false && "reason" in entry && typeof entry.reason === "string") {
104
+ return { id: entry.id, available: false, reason: entry.reason };
105
+ }
106
+ }
107
+ throw new Error("malformed probe result (invalid model availability)");
108
+ });
60
109
  }
61
110
  function flattenMessages(messages) {
62
111
  return messages.map((message) => `${message.role === "assistant" ? "Assistant" : "User"}: ${message.content}`).join("\n\n");
@@ -93,6 +142,7 @@ function resolveHelperPath(options = {}) {
93
142
  return fileURLToPath(new URL("../bin/apple-fm-helper", import.meta.url));
94
143
  }
95
144
  function runHelper(args, options, input, onLine) {
145
+ if (input !== void 0) assertHelperFrameSize(input.slice(0, -1));
96
146
  const command = resolveHelperPath(options);
97
147
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
98
148
  return new Promise((resolve2, reject) => {
@@ -128,19 +178,26 @@ function runHelper(args, options, input, onLine) {
128
178
  };
129
179
  child.stdout.setEncoding("utf8");
130
180
  child.stdout.on("data", (chunk) => {
131
- stdout += chunk;
132
- const { lines, rest } = splitLines(stdout);
133
- stdout = rest;
134
- for (const line of lines) if (!deliver(line)) return;
181
+ if (settled) return;
182
+ try {
183
+ const { lines, rest } = splitLines(stdout + chunk, true);
184
+ stdout = rest;
185
+ for (const line of lines) if (!deliver(line)) return;
186
+ } catch (error) {
187
+ child.kill("SIGKILL");
188
+ finish(error instanceof Error ? error : new Error(String(error)));
189
+ }
135
190
  });
136
191
  child.stderr.setEncoding("utf8");
137
- child.stderr.on("data", (chunk) => stderr += chunk);
192
+ child.stderr.on("data", (chunk) => {
193
+ stderr += chunk.slice(0, MAX_HELPER_STDERR_CHARS - stderr.length);
194
+ });
138
195
  child.on("close", (code) => {
139
196
  if (settled) return;
140
197
  const trailing = stdout.trim();
141
198
  if (trailing.length > 0 && !deliver(trailing)) return;
142
199
  if (code === 0) finish();
143
- else finish(new Error(`apple-fm helper exited with code ${String(code)}: ${stderr.trim()}`));
200
+ else finish(new Error(`apple-fm helper exited with code ${String(code)}: ${helperDiagnostic(stderr)}`));
144
201
  });
145
202
  if (input !== void 0) {
146
203
  child.stdin.on("error", () => void 0);
@@ -156,15 +213,58 @@ async function probe(options = {}) {
156
213
  }
157
214
  let result;
158
215
  await runHelper(["--probe"], options, void 0, (line) => {
216
+ if (result !== void 0) throw new Error("[protocolError] helper produced duplicate probe results");
159
217
  result = parseProbeResult(line);
160
218
  });
161
219
  if (result === void 0) throw new Error("apple-fm helper --probe produced no result");
220
+ if (result.models !== void 0) result.models = result.models.filter((entry) => entry.id === "on-device");
162
221
  return result;
163
222
  }
223
+ function assertSupportedModel(model) {
224
+ if (model !== void 0 && model !== "on-device") {
225
+ throw new Error(`unknown model "${model}" (run apple-fm probe)`);
226
+ }
227
+ }
228
+ async function countTokens(prompt, options = {}) {
229
+ if (usingBundledHelper(options) && !isPlatformSupported()) throw unsupportedPlatformError();
230
+ let count;
231
+ await runHelper(["--tokens"], options, encodeRequest({ prompt }), (line) => {
232
+ const event = parseEvent(line);
233
+ if (count !== void 0) throw new Error("[protocolError] helper sent an event after the token count result");
234
+ if (event.type === "error") throw helperError(event.code, event.message);
235
+ if (event.type === "result") count = parseTokenCountResult(event.content);
236
+ });
237
+ if (count === void 0) throw new Error("apple-fm helper --tokens produced no result");
238
+ return count;
239
+ }
164
240
  async function generate(request, options = {}, onDelta, onSnapshot) {
165
241
  if (usingBundledHelper(options) && !isPlatformSupported()) throw unsupportedPlatformError();
166
242
  let content;
167
- await runHelper(["--generate"], options, encodeRequest(request), (line) => {
243
+ const { model, useCase, imagePath, imagePaths, ...rest } = request;
244
+ const wireRequest = rest;
245
+ assertSupportedModel(model);
246
+ const tagging = useCase === "content-tagging";
247
+ if (useCase !== void 0 && useCase !== "general" && !tagging) {
248
+ throw new Error("unknown use case (choose general or content-tagging)");
249
+ }
250
+ if (tagging && (request.stream === true || request.schema !== void 0)) {
251
+ throw new Error("content-tagging cannot be combined with streaming or a custom schema");
252
+ }
253
+ if (imagePath !== void 0 && imagePaths !== void 0) throw new Error("provide either imagePath or imagePaths");
254
+ if (imagePaths?.length === 0) throw new Error("imagePaths requires at least one local image path");
255
+ const paths = imagePaths ?? (imagePath === void 0 ? [] : [imagePath]);
256
+ if (tagging && paths.length > 0) throw new Error("image input requires the general use case");
257
+ let mode = tagging ? "--tag-content" : "--generate";
258
+ const [first] = paths;
259
+ if (paths.length > 1) {
260
+ mode = "--generate-images";
261
+ wireRequest.imagePaths = paths;
262
+ } else if (first !== void 0) {
263
+ mode = "--generate-image";
264
+ wireRequest.imagePath = first;
265
+ }
266
+ await runHelper([mode], options, encodeRequest(wireRequest), (line) => {
267
+ if (content !== void 0) throw new Error("[protocolError] helper sent an event after the generation result");
168
268
  const event = parseEvent(line);
169
269
  switch (event.type) {
170
270
  case "delta":
@@ -177,59 +277,258 @@ async function generate(request, options = {}, onDelta, onSnapshot) {
177
277
  content = event.content;
178
278
  break;
179
279
  case "error":
180
- throw new Error(`[${event.code}] ${event.message}`);
280
+ throw helperError(event.code, event.message);
181
281
  }
182
282
  });
183
- if (content === void 0) throw new Error("apple-fm helper --generate produced no result");
283
+ if (content === void 0) throw new Error(`apple-fm helper ${mode} produced no result`);
184
284
  return content;
185
285
  }
186
286
 
187
287
  // src/liveSession.ts
188
288
  import { spawn as spawn3 } from "child_process";
189
289
 
290
+ // src/tools/output.ts
291
+ var MAX_TOOL_OUTPUT_CHARS = 3e3;
292
+ function capOutput(text, max = MAX_TOOL_OUTPUT_CHARS) {
293
+ if (text.length <= max) return text;
294
+ return `${text.slice(0, max)}
295
+ \u2026(${String(text.length - max)} more chars truncated)`;
296
+ }
297
+
298
+ // src/tools/permissions.ts
299
+ var MAX_PROMPT_DESCRIPTION = 200;
300
+ function sanitizeForPrompt(text) {
301
+ const stripped = text.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "").replace(/[\p{Cc}\p{Cf}]+/gu, " ").trim();
302
+ if (stripped.length <= MAX_PROMPT_DESCRIPTION) return stripped;
303
+ return `${stripped.slice(0, MAX_PROMPT_DESCRIPTION)}\u2026 (${String(stripped.length - MAX_PROMPT_DESCRIPTION)} more chars)`;
304
+ }
305
+ var exactKeyMatch = (ruleKey, callKey) => ruleKey === callKey;
306
+ function ruleMatches(rule, request, kind) {
307
+ const colon = rule.indexOf(":");
308
+ if (colon < 0) return rule === request.tool;
309
+ if (rule.slice(0, colon) !== request.tool) return false;
310
+ if (request.key === void 0) return false;
311
+ return (request.matchKey ?? exactKeyMatch)(rule.slice(colon + 1), request.key, kind);
312
+ }
313
+ var PermissionPolicy = class {
314
+ defaultMode;
315
+ allow;
316
+ deny;
317
+ asker;
318
+ constructor(config = {}) {
319
+ this.defaultMode = config.default ?? "ask";
320
+ this.allow = new Set(config.allow ?? []);
321
+ this.deny = new Set(config.deny ?? []);
322
+ this.asker = config.asker;
323
+ }
324
+ /** Whether any rule in `set` matches the request, evaluated as the given kind. */
325
+ matches(set, request, kind) {
326
+ for (const rule of set) if (ruleMatches(rule, request, kind)) return true;
327
+ return false;
328
+ }
329
+ /**
330
+ * The static decision for a request, before any prompt. `deny` wins over `allow`. A
331
+ * permissive *default* (`allow`, e.g. `--yes`) does **not** cover a `dangerous` tool:
332
+ * it downgrades to `ask` so a blanket approval can't silently grant `bash` arbitrary
333
+ * command execution (AFM-64). An explicit allow rule still grants it.
334
+ */
335
+ decide(request) {
336
+ if (this.matches(this.deny, request, "deny")) return "deny";
337
+ if (this.matches(this.allow, request, "allow")) return "allow";
338
+ if (this.defaultMode === "allow" && request.dangerous === true) return "ask";
339
+ return this.defaultMode;
340
+ }
341
+ /** Remember an "always" approval for this call (process lifetime). */
342
+ remember(request) {
343
+ this.allow.add(request.key !== void 0 ? `${request.tool}:${request.key}` : request.tool);
344
+ }
345
+ /**
346
+ * Decide whether a call may proceed, prompting on `ask` and remembering an
347
+ * "always". Resolves `true` to run the tool, `false` to refuse it (the dispatcher
348
+ * feeds a refusal back to the model as a tool result). A rejected asker is treated
349
+ * as a denial. The dispatcher also fails closed if a tool's rule resolver throws.
350
+ */
351
+ async authorize(request, isCurrent) {
352
+ if (isCurrent?.() === false) return false;
353
+ let effective = request;
354
+ if (request.resolveRuleKeys !== void 0) {
355
+ const prefix = `${request.tool}:`;
356
+ const keys = [...new Set([...this.allow, ...this.deny].filter((rule) => rule.startsWith(prefix)).map((rule) => rule.slice(prefix.length)))];
357
+ if (keys.length > 0) {
358
+ const resolved = await request.resolveRuleKeys(keys);
359
+ const resolvedKeys = new Map(keys.map((key, index) => [key, resolved[index] ?? key]));
360
+ const compare = request.matchKey ?? exactKeyMatch;
361
+ effective = { ...request, matchKey: (rule, call, kind) => compare(resolvedKeys.get(rule) ?? rule, call, kind) };
362
+ }
363
+ }
364
+ if (isCurrent?.() === false) return false;
365
+ const mode = this.decide(effective);
366
+ if (mode === "allow") return true;
367
+ if (mode === "deny") return false;
368
+ if (this.asker === void 0) return false;
369
+ let outcome;
370
+ try {
371
+ outcome = await this.asker(request);
372
+ } catch {
373
+ return false;
374
+ }
375
+ if (isCurrent?.() === false) return false;
376
+ if (outcome === "always") {
377
+ this.remember(request);
378
+ return true;
379
+ }
380
+ return outcome === "once";
381
+ }
382
+ };
383
+
384
+ // src/tools/registry.ts
385
+ function toolPermissionRequest(tool, args) {
386
+ return {
387
+ tool: tool.name,
388
+ key: tool.permissionKey?.(args),
389
+ description: tool.describe?.(args) ?? `${tool.name} ${JSON.stringify(args)}`,
390
+ matchKey: tool.matchKey?.bind(tool),
391
+ dangerous: tool.dangerous,
392
+ args
393
+ };
394
+ }
395
+ var ToolRegistry = class _ToolRegistry {
396
+ tools = /* @__PURE__ */ new Map();
397
+ constructor(tools = []) {
398
+ for (const tool of tools) this.register(tool);
399
+ }
400
+ /** Register (or replace) a tool by name. */
401
+ register(tool) {
402
+ this.tools.set(tool.name, tool);
403
+ }
404
+ /** Look up the implementation for one call. */
405
+ get(name) {
406
+ return this.tools.get(name);
407
+ }
408
+ /** Copy the wire definitions, permission hooks, and implementations for a live session. */
409
+ snapshot() {
410
+ return new _ToolRegistry([...this.tools.values()].map((tool) => ({
411
+ name: tool.name,
412
+ description: tool.description,
413
+ parameters: structuredClone(tool.parameters),
414
+ run: tool.run.bind(tool),
415
+ prepare: tool.prepare?.bind(tool),
416
+ permissionKey: tool.permissionKey?.bind(tool),
417
+ describe: tool.describe?.bind(tool),
418
+ matchKey: tool.matchKey?.bind(tool),
419
+ dangerous: tool.dangerous,
420
+ usageHint: tool.usageHint
421
+ })));
422
+ }
423
+ /** Whether a tool with this name is registered. */
424
+ has(name) {
425
+ return this.tools.has(name);
426
+ }
427
+ /** Number of registered tools (0 ⇒ no `tools[]` is sent on a turn). */
428
+ get size() {
429
+ return this.tools.size;
430
+ }
431
+ /** The model-facing definitions sent to the helper on a turn command. */
432
+ definitions() {
433
+ return [...this.tools.values()].map(({ name, description, parameters }) => ({
434
+ name,
435
+ description,
436
+ parameters
437
+ }));
438
+ }
439
+ /** The registered tool names (for the REPL `/tools` listing). */
440
+ names() {
441
+ return [...this.tools.keys()];
442
+ }
443
+ /** One usage hint per tool (its `usageHint`, or a `name: description` fallback). */
444
+ usageHints() {
445
+ return [...this.tools.values()].map((tool) => tool.usageHint ?? `${tool.name}: ${tool.description}`);
446
+ }
447
+ /**
448
+ * Build a {@link PermissionRequest} for a call, using the tool's optional
449
+ * `permissionKey` / `describe` hooks. Returns `undefined` for an unknown tool.
450
+ */
451
+ permissionRequest(name, args) {
452
+ const tool = this.tools.get(name);
453
+ if (tool === void 0) return void 0;
454
+ return toolPermissionRequest(tool, args);
455
+ }
456
+ /**
457
+ * Run a tool by name. Throws (with a clear message) if no such tool is
458
+ * registered, so the dispatcher can surface a `tool_error` to the model.
459
+ */
460
+ async run(name, args, ctx = {}) {
461
+ const tool = this.tools.get(name);
462
+ if (tool === void 0) throw new Error(`unknown tool: ${name}`);
463
+ return tool.run(args, ctx);
464
+ }
465
+ };
466
+
190
467
  // src/tools/dispatch.ts
191
468
  async function dispatchToolCall(event, deps) {
192
469
  const callId = typeof event.callId === "string" ? event.callId : void 0;
193
470
  const name = typeof event.name === "string" ? event.name : void 0;
194
471
  const args = typeof event.arguments === "object" && event.arguments !== null ? event.arguments : {};
195
- if (callId === void 0 || name === void 0) return;
196
- deps.keepAlive();
472
+ if (callId === void 0 || name === void 0 || deps.isCurrent?.() === false) return;
473
+ let action = name;
474
+ const report2 = (status) => {
475
+ if (deps.onActivity === void 0 || deps.isCurrent?.() === false) return;
476
+ try {
477
+ deps.onActivity({ tool: sanitizeForPrompt(name), action: sanitizeForPrompt(action), status });
478
+ } catch {
479
+ }
480
+ };
197
481
  const reply = (command) => {
198
- deps.keepAlive();
482
+ if (deps.isCurrent?.() === false) return;
199
483
  deps.send({ ...command, callId });
200
484
  };
201
- const registry = deps.tools;
202
- if (registry === void 0 || !registry.has(name)) {
203
- reply({ type: "tool_result", content: `Unknown tool "${name}".` });
485
+ const tool = deps.tools?.get(name);
486
+ if (tool === void 0) {
487
+ report2("failed");
488
+ reply({ type: "tool_result", content: capOutput(`Unknown tool "${name}".`) });
489
+ return;
490
+ }
491
+ const context = { signal: deps.signal };
492
+ let prepared;
493
+ try {
494
+ if (tool.prepare !== void 0) prepared = await tool.prepare(args, context);
495
+ } catch (error) {
496
+ report2("failed");
497
+ reply({ type: "tool_result", content: capOutput(`The "${name}" tool failed: ${error instanceof Error ? error.message : String(error)}`) });
204
498
  return;
205
499
  }
206
- if (deps.permission !== void 0) {
207
- const request = registry.permissionRequest(name, args);
208
- const allowed = request !== void 0 && await deps.permission.authorize(request);
500
+ if (deps.isCurrent?.() === false) return;
501
+ if (deps.permission !== void 0 || deps.onActivity !== void 0) {
502
+ let allowed;
503
+ try {
504
+ const request = prepared?.request ?? toolPermissionRequest(tool, args);
505
+ action = request.description;
506
+ report2("requested");
507
+ request.signal = deps.signal;
508
+ allowed = deps.permission === void 0 || await deps.permission.authorize(request, deps.isCurrent);
509
+ } catch {
510
+ report2("failed");
511
+ reply({ type: "tool_result", content: "The tool could not be authorized." });
512
+ return;
513
+ }
514
+ if (deps.isCurrent?.() === false) return;
209
515
  if (!allowed) {
210
- reply({ type: "tool_result", content: `Permission to use the "${name}" tool was denied by the user.` });
516
+ report2("denied");
517
+ reply({ type: "tool_result", content: capOutput(`Permission to use the "${name}" tool was denied by the user.`) });
211
518
  return;
212
519
  }
213
520
  }
214
521
  try {
215
- reply({ type: "tool_result", content: await registry.run(name, args) });
522
+ reply({ type: "tool_result", content: await (prepared?.run() ?? tool.run(args, context)) });
523
+ report2("completed");
216
524
  } catch (error) {
217
- reply({ type: "tool_result", content: `The "${name}" tool failed: ${error instanceof Error ? error.message : String(error)}` });
525
+ report2("failed");
526
+ reply({ type: "tool_result", content: capOutput(`The "${name}" tool failed: ${error instanceof Error ? error.message : String(error)}`) });
218
527
  }
219
528
  }
220
529
 
221
530
  // src/tools/builtin/bash.ts
222
531
  import { spawn as spawn2 } from "child_process";
223
-
224
- // src/tools/output.ts
225
- var MAX_TOOL_OUTPUT_CHARS = 3e3;
226
- function capOutput(text, max = MAX_TOOL_OUTPUT_CHARS) {
227
- if (text.length <= max) return text;
228
- return `${text.slice(0, max)}
229
- \u2026(${String(text.length - max)} more chars truncated)`;
230
- }
231
-
232
- // src/tools/builtin/bash.ts
233
532
  var DEFAULT_TIMEOUT_MS2 = 3e4;
234
533
  var MAX_CAPTURE_CHARS = 256 * 1024;
235
534
  var PIPE_DRAIN_GRACE_MS = 100;
@@ -363,9 +662,29 @@ var bashTool = {
363
662
  };
364
663
 
365
664
  // src/tools/builtin/read.ts
665
+ import { execFile } from "child_process";
666
+ import { fileURLToPath as fileURLToPath2 } from "url";
667
+
668
+ // src/tools/builtin/readPaths.ts
366
669
  import { realpathSync } from "fs";
367
- import { open, stat } from "fs/promises";
368
670
  import { basename, dirname, join, resolve, sep } from "path";
671
+ function canonicalPath(path) {
672
+ const absolute = resolve(path);
673
+ try {
674
+ return realpathSync(absolute);
675
+ } catch {
676
+ try {
677
+ return join(realpathSync(dirname(absolute)), basename(absolute));
678
+ } catch {
679
+ return absolute;
680
+ }
681
+ }
682
+ }
683
+ function containsPath(rule, file) {
684
+ return file === rule || file.startsWith(rule.endsWith(sep) ? rule : rule + sep);
685
+ }
686
+
687
+ // src/tools/builtin/read.ts
369
688
  function intArg(value) {
370
689
  return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
371
690
  }
@@ -388,50 +707,72 @@ function withTimeout(promise, ms, label) {
388
707
  );
389
708
  });
390
709
  }
391
- function fileKind(stats) {
392
- if (stats.isDirectory()) return "directory";
393
- if (stats.isFIFO()) return "named pipe (fifo)";
394
- if (stats.isCharacterDevice()) return "character device";
395
- if (stats.isBlockDevice()) return "block device";
396
- if (stats.isSocket()) return "socket";
397
- return "special file";
710
+ function runWorker(request, timeoutMs, label, signal) {
711
+ const source = import.meta.url.endsWith(".ts");
712
+ const entry = fileURLToPath2(new URL(source ? "./read-worker.ts" : "./read-worker.js", import.meta.url));
713
+ const args = [...source ? ["--import", "tsx"] : [], entry, "--apple-fm-read-worker", JSON.stringify(request)];
714
+ let child;
715
+ const work = new Promise((resolve2, reject) => {
716
+ child = execFile(
717
+ process.execPath,
718
+ args,
719
+ { signal, killSignal: "SIGKILL", maxBuffer: 1024 * 1024 },
720
+ (error, stdout) => {
721
+ if (error !== null) {
722
+ reject(new Error("read: isolated filesystem operation failed"));
723
+ return;
724
+ }
725
+ try {
726
+ const result = JSON.parse(stdout);
727
+ if (result.value === void 0) throw new Error(result.error ?? "read: invalid filesystem response");
728
+ resolve2(result.value);
729
+ } catch (failure) {
730
+ reject(failure instanceof Error ? failure : new Error(String(failure)));
731
+ }
732
+ }
733
+ );
734
+ });
735
+ return withTimeout(work, timeoutMs, label).finally(() => {
736
+ if (child === void 0 || child.exitCode !== null || child.signalCode !== null) return;
737
+ child.kill("SIGKILL");
738
+ child.stdout?.destroy();
739
+ child.stderr?.destroy();
740
+ child.unref();
741
+ });
398
742
  }
399
- async function readRegularFileBounded(path, maxBytes) {
400
- const stats = await stat(path);
401
- if (!stats.isFile()) {
402
- throw new Error(`read: "${path}" is a ${fileKind(stats)}, not a regular file \u2014 refusing to read it`);
743
+ function readSnapshot(snapshot, range, options, signal) {
744
+ if ("error" in snapshot) return Promise.reject(new Error(snapshot.error));
745
+ return runWorker({
746
+ kind: "read",
747
+ identity: snapshot.identity,
748
+ maxBytes: options.maxBytes ?? READ_MAX_BYTES,
749
+ ...range
750
+ }, options.timeoutMs ?? READ_TIMEOUT_MS, snapshot.path, signal);
751
+ }
752
+ async function prepareRead(args, context) {
753
+ const path = typeof args.path === "string" ? args.path : "";
754
+ const request = { tool: "read", key: path.length > 0 ? path : void 0, description: `read ${path || "(no path)"}`, args };
755
+ if (path.length === 0) {
756
+ return { request, run: () => Promise.reject(new Error('read: "path" (string) is required')) };
403
757
  }
404
- const handle = await open(path, "r");
405
- try {
406
- const buffer = Buffer.alloc(maxBytes);
407
- const { bytesRead } = await handle.read(buffer, 0, maxBytes, 0);
408
- return buffer.toString("utf8", 0, bytesRead);
409
- } finally {
410
- await handle.close();
411
- }
412
- }
413
- async function readTextFile(path, range = {}, options = {}) {
414
- const maxBytes = options.maxBytes ?? READ_MAX_BYTES;
415
- const timeoutMs = options.timeoutMs ?? READ_TIMEOUT_MS;
416
- const content = await withTimeout(readRegularFileBounded(path, maxBytes), timeoutMs, path);
417
- const { offset, limit } = range;
418
- if (offset === void 0 && limit === void 0) return capOutput(content);
419
- const lines = content.split("\n");
420
- const start = offset ?? 0;
421
- const end = limit !== void 0 ? start + limit : lines.length;
422
- return capOutput(lines.slice(start, end).join("\n"));
423
- }
424
- function realResolve(path) {
425
- const abs = resolve(path);
426
- try {
427
- return realpathSync(abs);
428
- } catch {
429
- try {
430
- return join(realpathSync(dirname(abs)), basename(abs));
431
- } catch {
432
- return abs;
433
- }
758
+ if (/^https?:\/\//i.test(path)) {
759
+ return {
760
+ request,
761
+ run: () => Promise.resolve(`"${path}" is a URL, not a local file: the read tool only reads local files; apple-fm cannot fetch URLs.`)
762
+ };
434
763
  }
764
+ const snapshot = await runWorker({ kind: "inspect", path }, READ_TIMEOUT_MS, path, context.signal);
765
+ const range = { offset: intArg(args.offset), limit: intArg(args.limit) };
766
+ return {
767
+ request: {
768
+ ...request,
769
+ key: snapshot.path,
770
+ description: `read ${snapshot.path}`,
771
+ matchKey: containsPath,
772
+ resolveRuleKeys: (keys) => runWorker({ kind: "rules", paths: keys }, READ_TIMEOUT_MS, path, context.signal)
773
+ },
774
+ run: () => readSnapshot(snapshot, range, {}, context.signal)
775
+ };
435
776
  }
436
777
  var readTool = {
437
778
  name: "read",
@@ -455,149 +796,13 @@ var readTool = {
455
796
  // symlink inside an approved dir from escaping the grant (AFM-76): `read:/proj`
456
797
  // neither leaks `/proj-secret`, lets `/proj/../.ssh/id_rsa` escape, nor lets
457
798
  // `/proj/link → /etc/shadow` read outside the boundary. Same test for allow and deny.
458
- matchKey: (ruleKey, callKey) => {
459
- const rulePath = realResolve(ruleKey);
460
- const callPath = realResolve(callKey);
461
- return callPath === rulePath || callPath.startsWith(rulePath + sep);
462
- },
799
+ matchKey: (ruleKey, callKey) => containsPath(canonicalPath(ruleKey), canonicalPath(callKey)),
800
+ prepare: prepareRead,
463
801
  describe: (args) => `read ${typeof args.path === "string" ? args.path : "(no path)"}`,
464
802
  usageHint: "read \u2014 read a LOCAL file by its path; use it whenever the user references a file path (never use bash to read a file). Local files only \u2014 apple-fm cannot fetch URLs.",
465
- async run(args) {
466
- const path = typeof args.path === "string" ? args.path : "";
467
- if (path.length === 0) throw new Error('read: "path" (string) is required');
468
- if (/^https?:\/\//i.test(path)) {
469
- return `"${path}" is a URL, not a local file. The read tool only reads local files; apple-fm cannot fetch URLs.`;
470
- }
471
- return readTextFile(path, { offset: intArg(args.offset), limit: intArg(args.limit) });
472
- }
473
- };
474
-
475
- // src/tools/registry.ts
476
- var ToolRegistry = class {
477
- tools = /* @__PURE__ */ new Map();
478
- constructor(tools = []) {
479
- for (const tool of tools) this.register(tool);
480
- }
481
- /** Register (or replace) a tool by name. */
482
- register(tool) {
483
- this.tools.set(tool.name, tool);
484
- }
485
- /** Whether a tool with this name is registered. */
486
- has(name) {
487
- return this.tools.has(name);
488
- }
489
- /** Number of registered tools (0 ⇒ no `tools[]` is sent on a turn). */
490
- get size() {
491
- return this.tools.size;
492
- }
493
- /** The model-facing definitions sent to the helper on a turn command. */
494
- definitions() {
495
- return [...this.tools.values()].map(({ name, description, parameters }) => ({
496
- name,
497
- description,
498
- parameters
499
- }));
500
- }
501
- /** The registered tool names (for the REPL `/tools` listing). */
502
- names() {
503
- return [...this.tools.keys()];
504
- }
505
- /** One usage hint per tool (its `usageHint`, or a `name: description` fallback). */
506
- usageHints() {
507
- return [...this.tools.values()].map((tool) => tool.usageHint ?? `${tool.name}: ${tool.description}`);
508
- }
509
- /**
510
- * Build a {@link PermissionRequest} for a call, using the tool's optional
511
- * `permissionKey` / `describe` hooks. Returns `undefined` for an unknown tool.
512
- */
513
- permissionRequest(name, args) {
514
- const tool = this.tools.get(name);
515
- if (tool === void 0) return void 0;
516
- return {
517
- tool: name,
518
- key: tool.permissionKey?.(args),
519
- description: tool.describe?.(args) ?? `${name} ${JSON.stringify(args)}`,
520
- args,
521
- // Carry the tool's own key-matching + risk semantics so the policy can apply
522
- // them without knowing about specific tools (AFM-63 / AFM-64 / AFM-67).
523
- matchKey: tool.matchKey?.bind(tool),
524
- dangerous: tool.dangerous
525
- };
526
- }
527
- /**
528
- * Run a tool by name. Throws (with a clear message) if no such tool is
529
- * registered, so the dispatcher can surface a `tool_error` to the model.
530
- */
531
- async run(name, args, ctx = {}) {
532
- const tool = this.tools.get(name);
533
- if (tool === void 0) throw new Error(`unknown tool: ${name}`);
534
- return tool.run(args, ctx);
535
- }
536
- };
537
-
538
- // src/tools/permissions.ts
539
- var exactKeyMatch = (ruleKey, callKey) => ruleKey === callKey;
540
- function ruleMatches(rule, request, kind) {
541
- const colon = rule.indexOf(":");
542
- if (colon < 0) return rule === request.tool;
543
- if (rule.slice(0, colon) !== request.tool) return false;
544
- if (request.key === void 0) return false;
545
- return (request.matchKey ?? exactKeyMatch)(rule.slice(colon + 1), request.key, kind);
546
- }
547
- var PermissionPolicy = class {
548
- defaultMode;
549
- allow;
550
- deny;
551
- asker;
552
- constructor(config = {}) {
553
- this.defaultMode = config.default ?? "ask";
554
- this.allow = new Set(config.allow ?? []);
555
- this.deny = new Set(config.deny ?? []);
556
- this.asker = config.asker;
557
- }
558
- /** Whether any rule in `set` matches the request, evaluated as the given kind. */
559
- matches(set, request, kind) {
560
- for (const rule of set) if (ruleMatches(rule, request, kind)) return true;
561
- return false;
562
- }
563
- /**
564
- * The static decision for a request, before any prompt. `deny` wins over `allow`. A
565
- * permissive *default* (`allow`, e.g. `--yes`) does **not** cover a `dangerous` tool:
566
- * it downgrades to `ask` so a blanket approval can't silently grant `bash` arbitrary
567
- * command execution (AFM-64). An explicit allow rule still grants it.
568
- */
569
- decide(request) {
570
- if (this.matches(this.deny, request, "deny")) return "deny";
571
- if (this.matches(this.allow, request, "allow")) return "allow";
572
- if (this.defaultMode === "allow" && request.dangerous === true) return "ask";
573
- return this.defaultMode;
574
- }
575
- /** Remember an "always" approval for this call (process lifetime). */
576
- remember(request) {
577
- this.allow.add(request.key !== void 0 ? `${request.tool}:${request.key}` : request.tool);
578
- }
579
- /**
580
- * Decide whether a call may proceed, prompting on `ask` and remembering an
581
- * "always". Resolves `true` to run the tool, `false` to refuse it (the dispatcher
582
- * feeds a refusal back to the model as a tool result). Never throws — an asker that
583
- * rejects is treated as a denial.
584
- */
585
- async authorize(request) {
586
- const mode = this.decide(request);
587
- if (mode === "allow") return true;
588
- if (mode === "deny") return false;
589
- if (this.asker === void 0) return false;
590
- let outcome;
591
- try {
592
- outcome = await this.asker(request);
593
- } catch {
594
- return false;
595
- }
596
- if (outcome === "always") {
597
- this.remember(request);
598
- return true;
599
- }
600
- return outcome === "once";
803
+ async run(args, context) {
804
+ const prepared = await prepareRead(args, context);
805
+ return prepared.run();
601
806
  }
602
807
  };
603
808
 
@@ -629,17 +834,22 @@ var LiveSession = class {
629
834
  options;
630
835
  tools;
631
836
  permission;
837
+ onToolActivity;
632
838
  /** Whether we'd spawn the bundled macOS helper (subject to the platform gate). */
633
839
  bundled;
634
840
  child;
635
841
  buffer = "";
842
+ contextSize;
843
+ transcriptPersistence = false;
636
844
  nextId = 0;
637
845
  pending = /* @__PURE__ */ new Map();
638
846
  constructor(config = {}) {
639
847
  this.command = resolveHelperPath(config);
848
+ assertSupportedModel(config.model);
640
849
  this.timeoutMs = config.timeoutMs ?? DEFAULT_TURN_TIMEOUT_MS;
641
850
  this.options = config.options;
642
- this.tools = config.tools !== void 0 && config.tools.size > 0 ? config.tools : void 0;
851
+ this.tools = config.tools !== void 0 && config.tools.size > 0 ? config.tools.snapshot() : void 0;
852
+ this.onToolActivity = config.onToolActivity;
643
853
  this.permission = config.permission ?? (this.tools !== void 0 ? new PermissionPolicy() : void 0);
644
854
  this.bundled = usingBundledHelper(config);
645
855
  }
@@ -669,46 +879,99 @@ var LiveSession = class {
669
879
  send(text, onDelta, signal) {
670
880
  return this.dispatch({ prompt: text, options: this.options, stream: onDelta !== void 0 }, onDelta, signal);
671
881
  }
882
+ /** Count native tokens for the active session without starting another helper. */
883
+ async tokenBudget(prompt) {
884
+ const contextSize = this.contextSize;
885
+ if (contextSize === void 0 || !this.isActive()) return void 0;
886
+ try {
887
+ const content = await this.dispatch({ type: "count_tokens", prompt }, void 0);
888
+ return { tokens: parseTokenCountResult(content), contextSize };
889
+ } catch {
890
+ return void 0;
891
+ }
892
+ }
893
+ /** Serialize the active native transcript without starting another helper. */
894
+ exportTranscript() {
895
+ this.requireTranscriptPersistence();
896
+ return this.dispatch({ type: "export_transcript" }, void 0);
897
+ }
898
+ /** Whether the current helper can still hold the active session. */
899
+ isActive() {
900
+ const child = this.child;
901
+ return child !== void 0 && child.exitCode === null && child.signalCode === null && !child.killed;
902
+ }
903
+ /** Restore the transcript using the currently configured tools. */
904
+ async importTranscript(transcript) {
905
+ this.requireTranscriptPersistence();
906
+ await this.dispatch({ type: "import_transcript", content: transcript, tools: this.tools?.definitions() }, void 0);
907
+ }
908
+ requireTranscriptPersistence() {
909
+ if (!this.transcriptPersistence || !this.isActive()) {
910
+ throw new Error("native transcript persistence requires a current apple-fm helper");
911
+ }
912
+ }
672
913
  /** Tear down the helper process and reject any in-flight commands. */
673
914
  close() {
674
915
  const child = this.child;
675
- this.child = void 0;
676
- if (child !== void 0) child.kill("SIGKILL");
677
- this.rejectAll(new Error("[sessionClosed] live session closed"));
916
+ if (child !== void 0) this.retireChild(child, new Error("[sessionClosed] live session closed"));
678
917
  }
679
- rejectAll(error) {
680
- for (const pending of this.pending.values()) {
681
- clearTimeout(pending.timer);
682
- pending.reject(error);
918
+ retireChild(child, error, timedOutId) {
919
+ if (this.child !== child) return;
920
+ this.child = void 0;
921
+ this.contextSize = void 0;
922
+ this.transcriptPersistence = false;
923
+ child.kill("SIGKILL");
924
+ for (const [id, pending] of this.pending) {
925
+ if (pending.child !== child) continue;
926
+ const failure = id === timedOutId ? new Error(`live session timed out after ${String(this.timeoutMs)}ms`) : error;
927
+ this.takePending(id)?.reject(failure);
683
928
  }
684
- this.pending.clear();
685
929
  }
686
930
  ensureChild() {
687
931
  const existing = this.child;
688
- if (existing !== void 0 && existing.exitCode === null && !existing.killed) return existing;
932
+ if (existing !== void 0 && this.isActive()) return existing;
933
+ if (existing !== void 0) this.retireChild(existing, new Error("[sessionClosed] live session helper exited"));
689
934
  const child = spawn3(this.command, ["--session"], { stdio: ["pipe", "pipe", "pipe"] });
935
+ let stderr = "";
690
936
  this.buffer = "";
691
937
  child.stdout.setEncoding("utf8");
692
938
  child.stdout.on("data", (chunk) => {
693
- this.onStdout(chunk);
939
+ if (this.child !== child) return;
940
+ try {
941
+ this.onStdout(child, chunk);
942
+ } catch (error) {
943
+ this.retireChild(child, error instanceof Error ? error : new Error(String(error)));
944
+ }
945
+ });
946
+ child.stderr.setEncoding("utf8");
947
+ child.stderr.on("data", (chunk) => {
948
+ stderr += chunk.slice(0, MAX_HELPER_STDERR_CHARS - stderr.length);
694
949
  });
695
950
  child.stdin.on("error", () => void 0);
696
- const onGone = () => {
697
- if (this.child === child) this.child = void 0;
698
- this.rejectAll(new Error("[sessionClosed] live session helper exited"));
951
+ const onGone = (detail) => {
952
+ const diagnostic = helperDiagnostic(detail);
953
+ const message = diagnostic.length > 0 ? `live session helper exited: ${diagnostic}` : "live session helper exited";
954
+ this.retireChild(child, new Error(`[sessionClosed] ${message}`));
699
955
  };
700
- child.on("close", onGone);
701
- child.on("error", onGone);
956
+ child.on("close", () => {
957
+ onGone(stderr);
958
+ });
959
+ child.on("error", (error) => {
960
+ onGone(error.message);
961
+ });
702
962
  this.child = child;
703
963
  return child;
704
964
  }
705
- onStdout(chunk) {
965
+ onStdout(child, chunk) {
706
966
  this.buffer += chunk;
707
- const { lines, rest } = splitLines(this.buffer);
967
+ const { lines, rest } = splitLines(this.buffer, true);
708
968
  this.buffer = rest;
709
- for (const line of lines) this.onLine(line);
969
+ for (const line of lines) {
970
+ if (this.child !== child) return;
971
+ this.onLine(child, line);
972
+ }
710
973
  }
711
- onLine(line) {
974
+ onLine(child, line) {
712
975
  let value;
713
976
  try {
714
977
  value = JSON.parse(line);
@@ -717,28 +980,40 @@ var LiveSession = class {
717
980
  }
718
981
  if (typeof value !== "object" || value === null) return;
719
982
  const event = value;
720
- if (typeof event.id !== "string") return;
983
+ if (typeof event.id !== "string") {
984
+ if (event.type === "error" && typeof event.code === "string" && typeof event.message === "string") {
985
+ this.retireChild(child, helperError(event.code, event.message));
986
+ }
987
+ return;
988
+ }
721
989
  const id = event.id;
722
990
  const pending = this.pending.get(id);
723
991
  if (pending === void 0) return;
724
992
  switch (event.type) {
725
993
  case "delta":
726
- if (typeof event.text === "string") {
727
- pending.acc += event.text;
728
- pending.onDelta?.(event.text);
729
- }
994
+ if (typeof event.text !== "string") throw new Error("[protocolError] malformed live delta");
995
+ pending.onDelta?.(event.text);
730
996
  break;
731
997
  case "tool_call":
732
998
  void this.handleToolCall(id, pending, event);
733
999
  break;
734
1000
  case "ready":
1001
+ if (pending.replyType !== "ready") throw new Error("[protocolError] unexpected live ready event");
1002
+ this.transcriptPersistence = event.transcriptPersistence === true;
1003
+ this.contextSize = parseContextSize(event.contextSize);
735
1004
  this.settle(id, "");
736
1005
  break;
737
1006
  case "result":
738
- this.settle(id, typeof event.content === "string" ? event.content : pending.acc);
1007
+ if (pending.replyType !== "result" || typeof event.content !== "string") {
1008
+ throw new Error("[protocolError] malformed or unexpected live result");
1009
+ }
1010
+ this.settle(id, event.content);
739
1011
  break;
740
1012
  case "error":
741
- this.fail(id, `[${String(event.code)}] ${String(event.message)}`);
1013
+ if (typeof event.code !== "string" || typeof event.message !== "string") {
1014
+ throw new Error("[protocolError] malformed live error");
1015
+ }
1016
+ this.takePending(id)?.reject(helperError(event.code, event.message));
742
1017
  break;
743
1018
  default:
744
1019
  break;
@@ -748,80 +1023,79 @@ var LiveSession = class {
748
1023
  * Dispatch a `tool_call` to the registered tool and write the outcome back to the
749
1024
  * helper, keyed by `callId`. Runs concurrently with the still-open turn; the tool
750
1025
  * policy lives in {@link dispatchToolCall} (`src/tools/dispatch.ts`) — this wires it
751
- * to the session's child process and the pending turn's timeout.
1026
+ * to the session's child process and the pending turn's lifetime.
752
1027
  */
753
1028
  handleToolCall(id, pending, event) {
1029
+ const isCurrent = () => this.child === pending.child && this.pending.get(id) === pending && pending.toolLifetime?.signal.aborted !== true && pending.child.exitCode === null && pending.child.signalCode === null;
754
1030
  return dispatchToolCall(event, {
755
1031
  tools: this.tools,
756
1032
  permission: this.permission,
1033
+ isCurrent,
1034
+ signal: pending.toolLifetime?.signal,
1035
+ onActivity: this.onToolActivity,
757
1036
  send: (command) => {
758
- this.child?.stdin.write(JSON.stringify(command) + "\n");
759
- },
760
- // Hold the turn open while the tool (and any permission prompt) runs.
761
- keepAlive: () => {
762
- this.restartTimer(id, pending);
1037
+ if (!isCurrent()) return;
1038
+ const line = JSON.stringify(command);
1039
+ assertHelperFrameSize(line);
1040
+ pending.child.stdin.write(line + "\n");
763
1041
  }
764
1042
  });
765
1043
  }
766
- /** Restart a pending turn's timeout (e.g. across a tool call). */
767
- restartTimer(id, pending) {
768
- clearTimeout(pending.timer);
769
- pending.timer = setTimeout(() => {
770
- this.fail(id, `live session timed out after ${String(this.timeoutMs)}ms`);
771
- }, this.timeoutMs);
772
- }
773
- settle(id, content) {
1044
+ takePending(id) {
774
1045
  const pending = this.pending.get(id);
775
- if (pending === void 0) return;
1046
+ if (pending === void 0) return void 0;
776
1047
  clearTimeout(pending.timer);
1048
+ pending.removeAbortListener?.();
777
1049
  this.pending.delete(id);
778
- pending.resolve(content);
1050
+ pending.toolLifetime?.abort();
1051
+ return pending;
779
1052
  }
780
- fail(id, message) {
781
- const pending = this.pending.get(id);
782
- if (pending === void 0) return;
783
- clearTimeout(pending.timer);
784
- this.pending.delete(id);
785
- pending.reject(new Error(message));
1053
+ settle(id, content) {
1054
+ this.takePending(id)?.resolve(content);
786
1055
  }
787
- dispatch(command, onDelta, signal) {
788
- if (this.bundled && !isPlatformSupported()) return Promise.reject(unsupportedPlatformError());
789
- const child = this.ensureChild();
1056
+ async dispatch(command, onDelta, signal) {
1057
+ if (signal?.aborted === true) return "";
1058
+ if (this.bundled && !isPlatformSupported()) throw unsupportedPlatformError();
790
1059
  const id = String(this.nextId++);
1060
+ const line = JSON.stringify({ ...command, id });
1061
+ assertHelperFrameSize(line);
1062
+ const child = this.ensureChild();
1063
+ const replyType = command.type === "reset" || command.type === "import_transcript" ? "ready" : "result";
791
1064
  return new Promise((resolve2, reject) => {
792
1065
  const timer = setTimeout(() => {
793
- this.pending.delete(id);
794
- reject(new Error(`live session timed out after ${String(this.timeoutMs)}ms`));
1066
+ if (this.child !== child || !this.pending.has(id)) return;
1067
+ this.retireChild(child, new Error("[sessionClosed] live session helper terminated after a command timed out"), id);
795
1068
  }, this.timeoutMs);
796
- this.pending.set(id, { resolve: resolve2, reject, onDelta, acc: "", timer });
1069
+ const toolLifetime = this.tools !== void 0 ? new AbortController() : void 0;
1070
+ const pending = { child, resolve: resolve2, reject, onDelta, replyType, timer, toolLifetime };
1071
+ this.pending.set(id, pending);
1072
+ child.stdin.write(line + "\n");
797
1073
  if (signal !== void 0) {
798
- if (signal.aborted) this.cancel(id);
799
- else {
800
- signal.addEventListener(
801
- "abort",
802
- () => {
803
- this.cancel(id);
804
- },
805
- { once: true }
806
- );
807
- }
1074
+ const onAbort = () => {
1075
+ if (this.pending.get(id) !== pending) return;
1076
+ child.stdin.write(JSON.stringify({ type: "cancel", id }) + "\n");
1077
+ toolLifetime?.abort();
1078
+ };
1079
+ signal.addEventListener("abort", onAbort, { once: true });
1080
+ pending.removeAbortListener = () => {
1081
+ signal.removeEventListener("abort", onAbort);
1082
+ };
808
1083
  }
809
- child.stdin.write(JSON.stringify({ ...command, id }) + "\n");
810
1084
  });
811
1085
  }
812
- /** Ask the helper to cancel an in-flight turn (no-op if it already settled). */
813
- cancel(id) {
814
- if (!this.pending.has(id)) return;
815
- this.child?.stdin.write(JSON.stringify({ type: "cancel", id }) + "\n");
816
- }
817
1086
  };
818
1087
 
819
1088
  // src/session.ts
820
1089
  var DEFAULT_COMPACT_AT = 3e3;
821
1090
  var DEFAULT_KEEP_RECENT = 4;
1091
+ var CONTEXT_COMPACTION_FRACTION = 0.75;
822
1092
  var SUMMARIZE_SYSTEM = "You compress conversations. Given a transcript, produce a terse third-person summary that preserves facts, decisions, names, and open questions needed to continue the conversation. Output only the summary prose.";
823
- function defaultGenerateFn(helper, options) {
824
- return (system, messages, onDelta) => generate({ system, messages, options, stream: onDelta !== void 0 }, helper, onDelta);
1093
+ function defaultGenerateFn({ model, helper, options }) {
1094
+ return (system, messages, onDelta) => generate(
1095
+ { model, system, messages, options, stream: onDelta !== void 0 },
1096
+ helper,
1097
+ onDelta
1098
+ );
825
1099
  }
826
1100
  var ChatSession = class {
827
1101
  system;
@@ -829,22 +1103,28 @@ var ChatSession = class {
829
1103
  keepRecentTurns;
830
1104
  backend;
831
1105
  generateFn;
1106
+ toolNames;
832
1107
  messages = [];
833
1108
  /** Recap of turns dropped by compaction; folded into the system prompt. */
834
1109
  summary;
835
1110
  /** Instructions the backend was last `reset` with (`undefined` ⇒ needs reset). */
836
1111
  backendInstructions;
1112
+ operations = Promise.resolve();
1113
+ revision = 0;
837
1114
  constructor(config = {}) {
838
1115
  this.system = config.system ?? "";
1116
+ this.toolNames = config.tools?.names().sort() ?? [];
839
1117
  this.compactAtTokens = config.compactAtTokens ?? DEFAULT_COMPACT_AT;
840
1118
  this.keepRecentTurns = config.keepRecentTurns ?? DEFAULT_KEEP_RECENT;
841
1119
  this.backend = config.backend ?? new LiveSession({
842
1120
  ...config.helper,
1121
+ model: config.model,
843
1122
  options: config.options,
844
1123
  tools: config.tools,
845
- permission: config.permission
1124
+ permission: config.permission,
1125
+ onToolActivity: config.onToolActivity
846
1126
  });
847
- this.generateFn = config.generateFn ?? defaultGenerateFn(config.helper, config.options);
1127
+ this.generateFn = config.generateFn ?? defaultGenerateFn(config);
848
1128
  }
849
1129
  /** The system prompt actually sent to the model (instructions + any recap). */
850
1130
  effectiveSystem() {
@@ -859,6 +1139,16 @@ ${recap}` : recap;
859
1139
  history() {
860
1140
  return this.messages.map((message) => ({ ...message }));
861
1141
  }
1142
+ /** Report the active context in tokens. A missing capacity indicates an estimate. */
1143
+ usage() {
1144
+ return this.schedule(async (revision) => {
1145
+ await this.ensureStarted(revision);
1146
+ this.assertCurrent(revision);
1147
+ const budget = await this.backend.tokenBudget?.("");
1148
+ this.assertCurrent(revision);
1149
+ return budget ?? { tokens: estimateConversationTokens(this.effectiveSystem(), this.messages) };
1150
+ });
1151
+ }
862
1152
  /** Whether the next turn would push the transcript past the compaction bound. */
863
1153
  shouldCompact() {
864
1154
  return estimateConversationTokens(this.effectiveSystem(), this.messages) > this.compactAtTokens;
@@ -867,46 +1157,84 @@ ${recap}` : recap;
867
1157
  * Send a user turn and return the assistant's reply (streamed via `onDelta`). An
868
1158
  * optional `signal` interrupts the turn (FR-15, esc-to-interrupt): on abort the
869
1159
  * reply resolves with the partial text generated so far, and both the user prompt
870
- * and that partial reply are kept in history (so a follow-up turn stays coherent).
1160
+ * and that partial reply are kept in history. Aborting before a turn starts
1161
+ * returns empty text without adding a turn.
871
1162
  */
872
- async send(text, onDelta, signal) {
873
- if (this.shouldCompact()) await this.compact();
874
- await this.ensureStarted();
875
- this.messages.push({ role: "user", content: text });
1163
+ send(text, onDelta, signal) {
1164
+ return this.schedule((revision) => this.sendTurn(revision, text, onDelta, signal));
1165
+ }
1166
+ async sendTurn(revision, text, onDelta, signal) {
1167
+ const interrupted = () => signal?.aborted === true;
1168
+ if (interrupted()) return "";
1169
+ const stream = onDelta === void 0 ? void 0 : (chunk) => {
1170
+ if (revision === this.revision) onDelta(chunk);
1171
+ };
1172
+ if (this.messages.length > this.keepRecentTurns) {
1173
+ const budget = this.backendInstructions === this.effectiveSystem() ? await this.backend.tokenBudget?.(text) : void 0;
1174
+ this.assertCurrent(revision);
1175
+ const shouldCompact = budget === void 0 ? this.shouldCompact() : budget.tokens > Math.min(this.compactAtTokens, Math.floor(budget.contextSize * CONTEXT_COMPACTION_FRACTION));
1176
+ if (shouldCompact) await this.compactHistory(revision);
1177
+ }
1178
+ await this.ensureStarted(revision);
1179
+ if (interrupted()) return "";
876
1180
  let reply;
877
1181
  try {
878
- reply = await this.backend.send(text, onDelta, signal);
1182
+ reply = await this.runBackend(revision, () => this.backend.send(text, stream, signal));
879
1183
  } catch (error) {
1184
+ this.assertCurrent(revision);
880
1185
  const overflow = isContextOverflow(error);
881
- if (!recoverable(error) && !overflow) {
882
- this.messages.pop();
883
- throw error;
884
- }
885
- this.messages.pop();
886
- if (overflow) await this.compact();
887
- this.backendInstructions = void 0;
888
- await this.ensureStarted();
889
- this.messages.push({ role: "user", content: text });
890
- reply = await this.backend.send(text, onDelta, signal);
1186
+ if (!recoverable(error) && !overflow) throw error;
1187
+ if (overflow) await this.compactHistory(revision);
1188
+ await this.ensureStarted(revision);
1189
+ if (interrupted()) return "";
1190
+ reply = await this.runBackend(revision, () => this.backend.send(text, stream, signal));
891
1191
  }
892
- this.messages.push({ role: "assistant", content: reply });
1192
+ this.assertCurrent(revision);
1193
+ this.messages.push({ role: "user", content: text }, { role: "assistant", content: reply });
893
1194
  return reply;
894
1195
  }
895
1196
  /**
896
1197
  * Reset the backend's session whenever the effective system prompt changes (the
897
1198
  * first turn, or after a compaction), seeding it with the transcript so far.
898
1199
  */
899
- async ensureStarted() {
1200
+ async ensureStarted(revision) {
1201
+ this.assertCurrent(revision);
900
1202
  const system = this.effectiveSystem();
901
- if (this.backendInstructions === system) return;
902
- await this.backend.reset(system, this.messages);
1203
+ if (this.backendInstructions === system && this.backend.isActive?.() !== false) return;
1204
+ await this.runBackend(revision, () => this.backend.reset(system, this.history()));
1205
+ this.assertCurrent(revision);
903
1206
  this.backendInstructions = system;
904
1207
  }
1208
+ async runBackend(revision, operation) {
1209
+ this.assertCurrent(revision);
1210
+ try {
1211
+ return await operation();
1212
+ } catch (error) {
1213
+ this.assertCurrent(revision);
1214
+ this.backendInstructions = void 0;
1215
+ throw error;
1216
+ }
1217
+ }
1218
+ schedule(operation) {
1219
+ const revision = this.revision;
1220
+ const scheduled = this.operations.then(() => {
1221
+ this.assertCurrent(revision);
1222
+ return operation(revision);
1223
+ });
1224
+ this.operations = scheduled.then(() => void 0, () => void 0);
1225
+ return scheduled;
1226
+ }
1227
+ assertCurrent(revision) {
1228
+ if (this.revision !== revision) throw new Error("chat session changed during the operation");
1229
+ }
905
1230
  /**
906
1231
  * Fold all but the most recent turns into the rolling summary. Safe to call
907
1232
  * directly; {@link send} calls it automatically when {@link shouldCompact}.
908
1233
  */
909
- async compact() {
1234
+ compact() {
1235
+ return this.schedule((revision) => this.compactHistory(revision));
1236
+ }
1237
+ async compactHistory(revision) {
910
1238
  if (this.messages.length <= this.keepRecentTurns) return;
911
1239
  const cutoff = this.messages.length - this.keepRecentTurns;
912
1240
  const older = this.messages.slice(0, cutoff);
@@ -916,11 +1244,53 @@ ${recap}` : recap;
916
1244
  ${this.summary}` : "",
917
1245
  flattenMessages(older)
918
1246
  ].filter((part) => part.length > 0).join("\n\n");
919
- this.summary = (await this.generateFn(SUMMARIZE_SYSTEM, [{ role: "user", content: transcript }])).trim();
1247
+ const summary = await this.generateFn(SUMMARIZE_SYSTEM, [{ role: "user", content: transcript }]);
1248
+ this.assertCurrent(revision);
1249
+ this.summary = summary.trim();
920
1250
  this.messages = recent;
1251
+ this.backendInstructions = void 0;
1252
+ }
1253
+ /** Capture a versioned snapshot with the native session transcript. */
1254
+ saveTranscript() {
1255
+ return this.schedule(async (revision) => {
1256
+ const exportTranscript = this.backend.exportTranscript?.bind(this.backend);
1257
+ if (exportTranscript === void 0) throw new Error("backend cannot save a native transcript");
1258
+ await this.ensureStarted(revision);
1259
+ const transcript = await this.runBackend(revision, exportTranscript);
1260
+ this.assertCurrent(revision);
1261
+ return {
1262
+ version: 1,
1263
+ system: this.system,
1264
+ summary: this.summary,
1265
+ messages: this.history(),
1266
+ tools: [...this.toolNames],
1267
+ transcript
1268
+ };
1269
+ });
1270
+ }
1271
+ /** Resume a saved chat using this invocation's tool registry and permissions. */
1272
+ resumeTranscript(saved) {
1273
+ const { system, summary, transcript } = saved;
1274
+ const messages = saved.messages.map((message) => ({ ...message }));
1275
+ const tools = [...saved.tools].sort();
1276
+ return this.schedule(async (revision) => {
1277
+ const importTranscript = this.backend.importTranscript?.bind(this.backend);
1278
+ if (importTranscript === void 0) throw new Error("backend cannot resume a native transcript");
1279
+ if (JSON.stringify(this.toolNames) !== JSON.stringify(tools)) {
1280
+ throw new Error("enabled tools do not match the saved chat; use the same --tools list");
1281
+ }
1282
+ await this.ensureStarted(revision);
1283
+ await this.runBackend(revision, () => importTranscript(transcript));
1284
+ this.assertCurrent(revision);
1285
+ this.system = system;
1286
+ this.summary = summary;
1287
+ this.messages = messages;
1288
+ this.backendInstructions = this.effectiveSystem();
1289
+ });
921
1290
  }
922
1291
  /** Clear the transcript and summary; optionally replace the system prompt. */
923
1292
  reset(system) {
1293
+ this.revision += 1;
924
1294
  if (system !== void 0) this.system = system;
925
1295
  this.messages = [];
926
1296
  this.summary = void 0;
@@ -928,6 +1298,8 @@ ${this.summary}` : "",
928
1298
  }
929
1299
  /** Tear down the underlying live session (kills the helper process). */
930
1300
  close() {
1301
+ this.revision += 1;
1302
+ this.backendInstructions = void 0;
931
1303
  this.backend.close();
932
1304
  }
933
1305
  };
@@ -945,6 +1317,7 @@ export {
945
1317
  PermissionPolicy,
946
1318
  ToolRegistry,
947
1319
  bashTool,
1320
+ countTokens,
948
1321
  encodeRequest,
949
1322
  estimateConversationTokens,
950
1323
  estimateTokens,