apple-fm 1.0.1 → 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,56 @@ 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");
60
+ }
61
+ var UNAVAILABLE_REASONS = [
62
+ "deviceNotEligible",
63
+ "appleIntelligenceNotEnabled",
64
+ "modelNotReady",
65
+ "unsupportedPlatform",
66
+ "unknown"
67
+ ];
68
+ function parseProbeResult(line) {
69
+ const value = parseWireJson(line, "probe result");
70
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
71
+ throw new Error("malformed probe result");
72
+ }
73
+ const record = value;
74
+ if (typeof record.available !== "boolean") {
75
+ throw new Error("malformed probe result (available must be a boolean)");
76
+ }
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 };
81
+ if (typeof record.reason !== "string" || !UNAVAILABLE_REASONS.includes(record.reason)) {
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");
92
+ }
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
+ });
38
109
  }
39
110
  function flattenMessages(messages) {
40
111
  return messages.map((message) => `${message.role === "assistant" ? "Assistant" : "User"}: ${message.content}`).join("\n\n");
@@ -71,9 +142,10 @@ function resolveHelperPath(options = {}) {
71
142
  return fileURLToPath(new URL("../bin/apple-fm-helper", import.meta.url));
72
143
  }
73
144
  function runHelper(args, options, input, onLine) {
145
+ if (input !== void 0) assertHelperFrameSize(input.slice(0, -1));
74
146
  const command = resolveHelperPath(options);
75
147
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
76
- return new Promise((resolve, reject) => {
148
+ return new Promise((resolve2, reject) => {
77
149
  const child = spawn(command, args, { stdio: ["pipe", "pipe", "pipe"] });
78
150
  let stdout = "";
79
151
  let stderr = "";
@@ -89,7 +161,7 @@ function runHelper(args, options, input, onLine) {
89
161
  settled = true;
90
162
  clearTimeout(timer);
91
163
  if (error) reject(error);
92
- else resolve();
164
+ else resolve2();
93
165
  };
94
166
  child.on("error", (error) => {
95
167
  finish(new Error(`failed to run apple-fm helper (${command}): ${error.message}`));
@@ -106,19 +178,26 @@ function runHelper(args, options, input, onLine) {
106
178
  };
107
179
  child.stdout.setEncoding("utf8");
108
180
  child.stdout.on("data", (chunk) => {
109
- stdout += chunk;
110
- const { lines, rest } = splitLines(stdout);
111
- stdout = rest;
112
- 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
+ }
113
190
  });
114
191
  child.stderr.setEncoding("utf8");
115
- 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
+ });
116
195
  child.on("close", (code) => {
117
196
  if (settled) return;
118
197
  const trailing = stdout.trim();
119
198
  if (trailing.length > 0 && !deliver(trailing)) return;
120
199
  if (code === 0) finish();
121
- 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)}`));
122
201
  });
123
202
  if (input !== void 0) {
124
203
  child.stdin.on("error", () => void 0);
@@ -134,15 +213,58 @@ async function probe(options = {}) {
134
213
  }
135
214
  let result;
136
215
  await runHelper(["--probe"], options, void 0, (line) => {
137
- result = JSON.parse(line);
216
+ if (result !== void 0) throw new Error("[protocolError] helper produced duplicate probe results");
217
+ result = parseProbeResult(line);
138
218
  });
139
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");
140
221
  return result;
141
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
+ }
142
240
  async function generate(request, options = {}, onDelta, onSnapshot) {
143
241
  if (usingBundledHelper(options) && !isPlatformSupported()) throw unsupportedPlatformError();
144
242
  let content;
145
- 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");
146
268
  const event = parseEvent(line);
147
269
  switch (event.type) {
148
270
  case "delta":
@@ -155,83 +277,701 @@ async function generate(request, options = {}, onDelta, onSnapshot) {
155
277
  content = event.content;
156
278
  break;
157
279
  case "error":
158
- throw new Error(`[${event.code}] ${event.message}`);
280
+ throw helperError(event.code, event.message);
159
281
  }
160
282
  });
161
- 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`);
162
284
  return content;
163
285
  }
164
286
 
165
287
  // src/liveSession.ts
288
+ import { spawn as spawn3 } from "child_process";
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
+
467
+ // src/tools/dispatch.ts
468
+ async function dispatchToolCall(event, deps) {
469
+ const callId = typeof event.callId === "string" ? event.callId : void 0;
470
+ const name = typeof event.name === "string" ? event.name : void 0;
471
+ const args = typeof event.arguments === "object" && event.arguments !== null ? event.arguments : {};
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
+ };
481
+ const reply = (command) => {
482
+ if (deps.isCurrent?.() === false) return;
483
+ deps.send({ ...command, callId });
484
+ };
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)}`) });
498
+ return;
499
+ }
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;
515
+ if (!allowed) {
516
+ report2("denied");
517
+ reply({ type: "tool_result", content: capOutput(`Permission to use the "${name}" tool was denied by the user.`) });
518
+ return;
519
+ }
520
+ }
521
+ try {
522
+ reply({ type: "tool_result", content: await (prepared?.run() ?? tool.run(args, context)) });
523
+ report2("completed");
524
+ } catch (error) {
525
+ report2("failed");
526
+ reply({ type: "tool_result", content: capOutput(`The "${name}" tool failed: ${error instanceof Error ? error.message : String(error)}`) });
527
+ }
528
+ }
529
+
530
+ // src/tools/builtin/bash.ts
166
531
  import { spawn as spawn2 } from "child_process";
532
+ var DEFAULT_TIMEOUT_MS2 = 3e4;
533
+ var MAX_CAPTURE_CHARS = 256 * 1024;
534
+ var PIPE_DRAIN_GRACE_MS = 100;
535
+ var SAFE_ENV_KEYS = [
536
+ "PATH",
537
+ "HOME",
538
+ "USER",
539
+ "LOGNAME",
540
+ "SHELL",
541
+ "PWD",
542
+ "TMPDIR",
543
+ "LANG",
544
+ "LANGUAGE",
545
+ "LC_ALL",
546
+ "LC_CTYPE",
547
+ "TERM",
548
+ "TZ"
549
+ ];
550
+ function scopedEnv() {
551
+ const env = {};
552
+ for (const key of SAFE_ENV_KEYS) {
553
+ const value = process.env[key];
554
+ if (value !== void 0) env[key] = value;
555
+ }
556
+ return env;
557
+ }
558
+ function runShellCommand(command, options = {}) {
559
+ if (command.trim().length === 0) return Promise.reject(new Error('bash: "command" (string) is required'));
560
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
561
+ return new Promise((resolve2) => {
562
+ const child = spawn2("/bin/sh", ["-c", command], {
563
+ stdio: ["ignore", "pipe", "pipe"],
564
+ detached: true,
565
+ env: options.inheritEnv === true ? process.env : scopedEnv()
566
+ });
567
+ let stdout = "";
568
+ let stderr = "";
569
+ let timedOut = false;
570
+ let overflowed = false;
571
+ let settled = false;
572
+ let exitCode = null;
573
+ let exitSignal = null;
574
+ let graceTimer;
575
+ const killGroup = () => {
576
+ try {
577
+ if (child.pid !== void 0) process.kill(-child.pid, "SIGKILL");
578
+ else child.kill("SIGKILL");
579
+ } catch {
580
+ child.kill("SIGKILL");
581
+ }
582
+ };
583
+ const timer = setTimeout(() => {
584
+ timedOut = true;
585
+ killGroup();
586
+ }, timeoutMs);
587
+ const append = (buffer, chunk) => {
588
+ if (overflowed) return buffer;
589
+ const remaining = MAX_CAPTURE_CHARS - (stdout.length + stderr.length);
590
+ if (chunk.length <= remaining) return buffer + chunk;
591
+ overflowed = true;
592
+ killGroup();
593
+ return buffer + chunk.slice(0, Math.max(0, remaining));
594
+ };
595
+ const settle = () => {
596
+ if (settled) return;
597
+ settled = true;
598
+ clearTimeout(timer);
599
+ if (graceTimer !== void 0) clearTimeout(graceTimer);
600
+ child.stdout.destroy();
601
+ child.stderr.destroy();
602
+ const status = timedOut ? `timed out after ${String(timeoutMs)}ms (killed)` : overflowed ? `killed after exceeding the ${String(MAX_CAPTURE_CHARS)}-byte output limit` : exitCode !== null ? `exit code: ${String(exitCode)}` : `killed by signal ${String(exitSignal)}`;
603
+ resolve2(report({ stdout, stderr, status }));
604
+ };
605
+ child.stdout.setEncoding("utf8");
606
+ child.stderr.setEncoding("utf8");
607
+ child.stdout.on("data", (chunk) => stdout = append(stdout, chunk));
608
+ child.stderr.on("data", (chunk) => stderr = append(stderr, chunk));
609
+ child.on("error", (error) => {
610
+ if (settled) return;
611
+ settled = true;
612
+ clearTimeout(timer);
613
+ if (graceTimer !== void 0) clearTimeout(graceTimer);
614
+ resolve2(report({ stdout, stderr, status: `failed to start: ${error.message}` }));
615
+ });
616
+ child.on("exit", (code, signal) => {
617
+ exitCode = code;
618
+ exitSignal = signal;
619
+ killGroup();
620
+ graceTimer = setTimeout(settle, PIPE_DRAIN_GRACE_MS);
621
+ });
622
+ child.on("close", settle);
623
+ });
624
+ }
625
+ function report({ stdout, stderr, status }) {
626
+ const sections = [status];
627
+ if (stdout.length > 0) sections.push(`stdout:
628
+ ${stdout}`);
629
+ if (stderr.length > 0) sections.push(`stderr:
630
+ ${stderr}`);
631
+ return capOutput(sections.join("\n"));
632
+ }
633
+ var bashTool = {
634
+ name: "bash",
635
+ description: "Run a shell command (via `sh -c`) and return its exit code, stdout, and stderr. Use to inspect the system or run command-line tools. Avoid destructive commands.",
636
+ parameters: {
637
+ type: "object",
638
+ description: "Arguments for the bash tool.",
639
+ required: ["command"],
640
+ properties: {
641
+ command: { type: "string", description: "The shell command to run." }
642
+ }
643
+ },
644
+ dangerous: true,
645
+ permissionKey: (args) => typeof args.command === "string" ? args.command : void 0,
646
+ // Allow grants are EXACT — approving `ls` never approves `ls; curl evil` (AFM-63).
647
+ // Deny rules are a broad best-effort token match: the denied token, at a start /
648
+ // whitespace / path boundary, anywhere in the normalized command, so `--deny-tool
649
+ // bash:rm` also catches `/bin/rm` and `command rm` — but this is NOT a security
650
+ // guarantee (`eval`, `$(…)`, aliases evade it); the real control is not enabling
651
+ // bash (AFM-67).
652
+ matchKey: (ruleKey, callKey, kind) => {
653
+ if (kind === "allow") return ruleKey === callKey;
654
+ const token = ruleKey.trim();
655
+ if (token.length === 0) return false;
656
+ const escaped = token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
657
+ return new RegExp(`(^|[\\s/])${escaped}`).test(callKey.trim().replace(/\s+/g, " "));
658
+ },
659
+ describe: (args) => `run: ${typeof args.command === "string" ? args.command : "(no command)"}`,
660
+ usageHint: "bash \u2014 run a shell command; use it to inspect the system or run CLI tools, NOT to read files or fetch URLs.",
661
+ run: (args) => runShellCommand(typeof args.command === "string" ? args.command : "")
662
+ };
663
+
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
669
+ import { realpathSync } from "fs";
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
688
+ function intArg(value) {
689
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
690
+ }
691
+ var READ_MAX_BYTES = 1024 * 1024;
692
+ var READ_TIMEOUT_MS = 1e4;
693
+ function withTimeout(promise, ms, label) {
694
+ return new Promise((res, rej) => {
695
+ const timer = setTimeout(() => {
696
+ rej(new Error(`read: timed out after ${String(ms)}ms reading "${label}"`));
697
+ }, ms);
698
+ promise.then(
699
+ (value) => {
700
+ clearTimeout(timer);
701
+ res(value);
702
+ },
703
+ (error) => {
704
+ clearTimeout(timer);
705
+ rej(error instanceof Error ? error : new Error(String(error)));
706
+ }
707
+ );
708
+ });
709
+ }
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
+ });
742
+ }
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')) };
757
+ }
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
+ };
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
+ };
776
+ }
777
+ var readTool = {
778
+ name: "read",
779
+ description: 'Read a UTF-8 text file from the local filesystem and return its contents. Optionally pass a 0-based line "offset" and a "limit" number of lines to read a range.',
780
+ parameters: {
781
+ type: "object",
782
+ description: "Arguments for the read tool.",
783
+ required: ["path"],
784
+ properties: {
785
+ path: { type: "string", description: "Filesystem path of the file to read." },
786
+ offset: { type: "integer", minimum: 0, description: "First line to return (0-based)." },
787
+ limit: { type: "integer", minimum: 1, description: "Maximum number of lines to return." }
788
+ }
789
+ },
790
+ // Scope permission rules / "always" grants to the path, so a user can approve a
791
+ // directory once (`read:/Users/me/project`) without allowing every read.
792
+ permissionKey: (args) => typeof args.path === "string" ? args.path : void 0,
793
+ // A path rule covers a file exactly or a directory and everything *inside* it — after
794
+ // resolving `..` AND following symlinks, and only across a real path-separator
795
+ // boundary. Resolving the **real** path (not just the textual one) is what stops a
796
+ // symlink inside an approved dir from escaping the grant (AFM-76): `read:/proj`
797
+ // neither leaks `/proj-secret`, lets `/proj/../.ssh/id_rsa` escape, nor lets
798
+ // `/proj/link → /etc/shadow` read outside the boundary. Same test for allow and deny.
799
+ matchKey: (ruleKey, callKey) => containsPath(canonicalPath(ruleKey), canonicalPath(callKey)),
800
+ prepare: prepareRead,
801
+ describe: (args) => `read ${typeof args.path === "string" ? args.path : "(no path)"}`,
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.",
803
+ async run(args, context) {
804
+ const prepared = await prepareRead(args, context);
805
+ return prepared.run();
806
+ }
807
+ };
808
+
809
+ // src/tools/index.ts
810
+ var BUILTIN_TOOLS = { read: readTool, bash: bashTool };
811
+ function toolGuidancePrompt(registry) {
812
+ const hints = registry.usageHints();
813
+ if (hints.length === 0) return "";
814
+ const intro = "You have tools available and the user has authorized their use \u2014 every call is permission-checked, so you do not need to ask first. Prefer calling a tool over refusing: never claim you cannot read files or run commands \u2014 call the matching tool instead. Match the task to the tool: a local file path \u2192 read; a shell command \u2192 bash. Call ONE tool for the job, not several for the same thing. Do not use bash to read files, and never invent a tool or write a tool call as plain text. Available tools:";
815
+ return [intro, ...hints.map((hint) => `- ${hint}`)].join("\n");
816
+ }
817
+ function registryFromNames(names) {
818
+ const registry = new ToolRegistry();
819
+ for (const name of names) {
820
+ const tool = BUILTIN_TOOLS[name];
821
+ if (tool === void 0) {
822
+ throw new Error(`unknown built-in tool "${name}" (available: ${Object.keys(BUILTIN_TOOLS).join(", ")})`);
823
+ }
824
+ registry.register(tool);
825
+ }
826
+ return registry;
827
+ }
828
+
829
+ // src/liveSession.ts
167
830
  var DEFAULT_TURN_TIMEOUT_MS = 12e4;
168
831
  var LiveSession = class {
169
832
  command;
170
833
  timeoutMs;
171
834
  options;
835
+ tools;
836
+ permission;
837
+ onToolActivity;
172
838
  /** Whether we'd spawn the bundled macOS helper (subject to the platform gate). */
173
839
  bundled;
174
840
  child;
175
841
  buffer = "";
842
+ contextSize;
843
+ transcriptPersistence = false;
176
844
  nextId = 0;
177
845
  pending = /* @__PURE__ */ new Map();
178
846
  constructor(config = {}) {
179
847
  this.command = resolveHelperPath(config);
848
+ assertSupportedModel(config.model);
180
849
  this.timeoutMs = config.timeoutMs ?? DEFAULT_TURN_TIMEOUT_MS;
181
850
  this.options = config.options;
851
+ this.tools = config.tools !== void 0 && config.tools.size > 0 ? config.tools.snapshot() : void 0;
852
+ this.onToolActivity = config.onToolActivity;
853
+ this.permission = config.permission ?? (this.tools !== void 0 ? new PermissionPolicy() : void 0);
182
854
  this.bundled = usingBundledHelper(config);
183
855
  }
184
- /** Recreate the underlying session with new instructions + seed turns. */
856
+ /**
857
+ * Recreate the underlying session with new instructions + seed turns. Tool
858
+ * definitions ride on `reset` because the framework binds tools at session
859
+ * construction (not per turn); the helper builds the session's tools here.
860
+ */
185
861
  async reset(system, seed = []) {
186
- await this.dispatch({ type: "reset", system, seed }, void 0);
187
- }
188
- /** Send one user turn; prior turns stay in context. Streams via `onDelta`. */
189
- send(text, onDelta) {
190
- return this.dispatch(
191
- { prompt: text, options: this.options, stream: onDelta !== void 0 },
192
- onDelta
862
+ await this.dispatch(
863
+ {
864
+ type: "reset",
865
+ system,
866
+ seed,
867
+ // Only attach tools when some are registered, so resets stay byte-identical
868
+ // to the no-tools path otherwise.
869
+ ...this.tools !== void 0 ? { tools: this.tools.definitions() } : {}
870
+ },
871
+ void 0
193
872
  );
194
873
  }
874
+ /**
875
+ * Send one user turn; prior turns stay in context. Streams via `onDelta`. An
876
+ * optional `signal` interrupts the turn: on abort a `cancel` command is sent and
877
+ * the helper ends the turn with the partial text generated so far (FR-15).
878
+ */
879
+ send(text, onDelta, signal) {
880
+ return this.dispatch({ prompt: text, options: this.options, stream: onDelta !== void 0 }, onDelta, signal);
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
+ }
195
913
  /** Tear down the helper process and reject any in-flight commands. */
196
914
  close() {
197
915
  const child = this.child;
198
- this.child = void 0;
199
- if (child !== void 0) child.kill("SIGKILL");
200
- this.rejectAll(new Error("[sessionClosed] live session closed"));
916
+ if (child !== void 0) this.retireChild(child, new Error("[sessionClosed] live session closed"));
201
917
  }
202
- rejectAll(error) {
203
- for (const pending of this.pending.values()) {
204
- clearTimeout(pending.timer);
205
- 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);
206
928
  }
207
- this.pending.clear();
208
929
  }
209
930
  ensureChild() {
210
931
  const existing = this.child;
211
- if (existing !== void 0 && existing.exitCode === null && !existing.killed) return existing;
212
- const child = spawn2(this.command, ["--session"], { stdio: ["pipe", "pipe", "pipe"] });
932
+ if (existing !== void 0 && this.isActive()) return existing;
933
+ if (existing !== void 0) this.retireChild(existing, new Error("[sessionClosed] live session helper exited"));
934
+ const child = spawn3(this.command, ["--session"], { stdio: ["pipe", "pipe", "pipe"] });
935
+ let stderr = "";
213
936
  this.buffer = "";
214
937
  child.stdout.setEncoding("utf8");
215
938
  child.stdout.on("data", (chunk) => {
216
- 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);
217
949
  });
218
950
  child.stdin.on("error", () => void 0);
219
- const onGone = () => {
220
- if (this.child === child) this.child = void 0;
221
- 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}`));
222
955
  };
223
- child.on("close", onGone);
224
- child.on("error", onGone);
956
+ child.on("close", () => {
957
+ onGone(stderr);
958
+ });
959
+ child.on("error", (error) => {
960
+ onGone(error.message);
961
+ });
225
962
  this.child = child;
226
963
  return child;
227
964
  }
228
- onStdout(chunk) {
965
+ onStdout(child, chunk) {
229
966
  this.buffer += chunk;
230
- const { lines, rest } = splitLines(this.buffer);
967
+ const { lines, rest } = splitLines(this.buffer, true);
231
968
  this.buffer = rest;
232
- 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
+ }
233
973
  }
234
- onLine(line) {
974
+ onLine(child, line) {
235
975
  let value;
236
976
  try {
237
977
  value = JSON.parse(line);
@@ -240,55 +980,107 @@ var LiveSession = class {
240
980
  }
241
981
  if (typeof value !== "object" || value === null) return;
242
982
  const event = value;
243
- 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
+ }
244
989
  const id = event.id;
245
990
  const pending = this.pending.get(id);
246
991
  if (pending === void 0) return;
247
992
  switch (event.type) {
248
993
  case "delta":
249
- if (typeof event.text === "string") {
250
- pending.acc += event.text;
251
- pending.onDelta?.(event.text);
252
- }
994
+ if (typeof event.text !== "string") throw new Error("[protocolError] malformed live delta");
995
+ pending.onDelta?.(event.text);
996
+ break;
997
+ case "tool_call":
998
+ void this.handleToolCall(id, pending, event);
253
999
  break;
254
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);
255
1004
  this.settle(id, "");
256
1005
  break;
257
1006
  case "result":
258
- 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);
259
1011
  break;
260
1012
  case "error":
261
- 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));
262
1017
  break;
263
1018
  default:
264
1019
  break;
265
1020
  }
266
1021
  }
267
- settle(id, content) {
268
- const pending = this.pending.get(id);
269
- if (pending === void 0) return;
270
- clearTimeout(pending.timer);
271
- this.pending.delete(id);
272
- pending.resolve(content);
1022
+ /**
1023
+ * Dispatch a `tool_call` to the registered tool and write the outcome back to the
1024
+ * helper, keyed by `callId`. Runs concurrently with the still-open turn; the tool
1025
+ * policy lives in {@link dispatchToolCall} (`src/tools/dispatch.ts`) — this wires it
1026
+ * to the session's child process and the pending turn's lifetime.
1027
+ */
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;
1030
+ return dispatchToolCall(event, {
1031
+ tools: this.tools,
1032
+ permission: this.permission,
1033
+ isCurrent,
1034
+ signal: pending.toolLifetime?.signal,
1035
+ onActivity: this.onToolActivity,
1036
+ send: (command) => {
1037
+ if (!isCurrent()) return;
1038
+ const line = JSON.stringify(command);
1039
+ assertHelperFrameSize(line);
1040
+ pending.child.stdin.write(line + "\n");
1041
+ }
1042
+ });
273
1043
  }
274
- fail(id, message) {
1044
+ takePending(id) {
275
1045
  const pending = this.pending.get(id);
276
- if (pending === void 0) return;
1046
+ if (pending === void 0) return void 0;
277
1047
  clearTimeout(pending.timer);
1048
+ pending.removeAbortListener?.();
278
1049
  this.pending.delete(id);
279
- pending.reject(new Error(message));
1050
+ pending.toolLifetime?.abort();
1051
+ return pending;
280
1052
  }
281
- dispatch(command, onDelta) {
282
- if (this.bundled && !isPlatformSupported()) return Promise.reject(unsupportedPlatformError());
283
- const child = this.ensureChild();
1053
+ settle(id, content) {
1054
+ this.takePending(id)?.resolve(content);
1055
+ }
1056
+ async dispatch(command, onDelta, signal) {
1057
+ if (signal?.aborted === true) return "";
1058
+ if (this.bundled && !isPlatformSupported()) throw unsupportedPlatformError();
284
1059
  const id = String(this.nextId++);
285
- return new Promise((resolve, reject) => {
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";
1064
+ return new Promise((resolve2, reject) => {
286
1065
  const timer = setTimeout(() => {
287
- this.pending.delete(id);
288
- 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);
289
1068
  }, this.timeoutMs);
290
- this.pending.set(id, { resolve, reject, onDelta, acc: "", timer });
291
- child.stdin.write(JSON.stringify({ ...command, id }) + "\n");
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");
1073
+ if (signal !== void 0) {
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
+ };
1083
+ }
292
1084
  });
293
1085
  }
294
1086
  };
@@ -296,9 +1088,14 @@ var LiveSession = class {
296
1088
  // src/session.ts
297
1089
  var DEFAULT_COMPACT_AT = 3e3;
298
1090
  var DEFAULT_KEEP_RECENT = 4;
1091
+ var CONTEXT_COMPACTION_FRACTION = 0.75;
299
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.";
300
- function defaultGenerateFn(helper, options) {
301
- 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
+ );
302
1099
  }
303
1100
  var ChatSession = class {
304
1101
  system;
@@ -306,17 +1103,28 @@ var ChatSession = class {
306
1103
  keepRecentTurns;
307
1104
  backend;
308
1105
  generateFn;
1106
+ toolNames;
309
1107
  messages = [];
310
1108
  /** Recap of turns dropped by compaction; folded into the system prompt. */
311
1109
  summary;
312
1110
  /** Instructions the backend was last `reset` with (`undefined` ⇒ needs reset). */
313
1111
  backendInstructions;
1112
+ operations = Promise.resolve();
1113
+ revision = 0;
314
1114
  constructor(config = {}) {
315
1115
  this.system = config.system ?? "";
1116
+ this.toolNames = config.tools?.names().sort() ?? [];
316
1117
  this.compactAtTokens = config.compactAtTokens ?? DEFAULT_COMPACT_AT;
317
1118
  this.keepRecentTurns = config.keepRecentTurns ?? DEFAULT_KEEP_RECENT;
318
- this.backend = config.backend ?? new LiveSession({ ...config.helper, options: config.options });
319
- this.generateFn = config.generateFn ?? defaultGenerateFn(config.helper, config.options);
1119
+ this.backend = config.backend ?? new LiveSession({
1120
+ ...config.helper,
1121
+ model: config.model,
1122
+ options: config.options,
1123
+ tools: config.tools,
1124
+ permission: config.permission,
1125
+ onToolActivity: config.onToolActivity
1126
+ });
1127
+ this.generateFn = config.generateFn ?? defaultGenerateFn(config);
320
1128
  }
321
1129
  /** The system prompt actually sent to the model (instructions + any recap). */
322
1130
  effectiveSystem() {
@@ -331,47 +1139,102 @@ ${recap}` : recap;
331
1139
  history() {
332
1140
  return this.messages.map((message) => ({ ...message }));
333
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
+ }
334
1152
  /** Whether the next turn would push the transcript past the compaction bound. */
335
1153
  shouldCompact() {
336
1154
  return estimateConversationTokens(this.effectiveSystem(), this.messages) > this.compactAtTokens;
337
1155
  }
338
- /** Send a user turn and return the assistant's reply (streamed via `onDelta`). */
339
- async send(text, onDelta) {
340
- if (this.shouldCompact()) await this.compact();
341
- await this.ensureStarted();
342
- this.messages.push({ role: "user", content: text });
1156
+ /**
1157
+ * Send a user turn and return the assistant's reply (streamed via `onDelta`). An
1158
+ * optional `signal` interrupts the turn (FR-15, esc-to-interrupt): on abort the
1159
+ * reply resolves with the partial text generated so far, and both the user prompt
1160
+ * and that partial reply are kept in history. Aborting before a turn starts
1161
+ * returns empty text without adding a turn.
1162
+ */
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 "";
343
1180
  let reply;
344
1181
  try {
345
- reply = await this.backend.send(text, onDelta);
1182
+ reply = await this.runBackend(revision, () => this.backend.send(text, stream, signal));
346
1183
  } catch (error) {
347
- if (!recoverable(error)) {
348
- this.messages.pop();
349
- throw error;
350
- }
351
- this.messages.pop();
352
- this.backendInstructions = void 0;
353
- await this.ensureStarted();
354
- this.messages.push({ role: "user", content: text });
355
- reply = await this.backend.send(text, onDelta);
1184
+ this.assertCurrent(revision);
1185
+ const overflow = isContextOverflow(error);
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));
356
1191
  }
357
- this.messages.push({ role: "assistant", content: reply });
1192
+ this.assertCurrent(revision);
1193
+ this.messages.push({ role: "user", content: text }, { role: "assistant", content: reply });
358
1194
  return reply;
359
1195
  }
360
1196
  /**
361
1197
  * Reset the backend's session whenever the effective system prompt changes (the
362
1198
  * first turn, or after a compaction), seeding it with the transcript so far.
363
1199
  */
364
- async ensureStarted() {
1200
+ async ensureStarted(revision) {
1201
+ this.assertCurrent(revision);
365
1202
  const system = this.effectiveSystem();
366
- if (this.backendInstructions === system) return;
367
- 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);
368
1206
  this.backendInstructions = system;
369
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
+ }
370
1230
  /**
371
1231
  * Fold all but the most recent turns into the rolling summary. Safe to call
372
1232
  * directly; {@link send} calls it automatically when {@link shouldCompact}.
373
1233
  */
374
- async compact() {
1234
+ compact() {
1235
+ return this.schedule((revision) => this.compactHistory(revision));
1236
+ }
1237
+ async compactHistory(revision) {
375
1238
  if (this.messages.length <= this.keepRecentTurns) return;
376
1239
  const cutoff = this.messages.length - this.keepRecentTurns;
377
1240
  const older = this.messages.slice(0, cutoff);
@@ -381,11 +1244,53 @@ ${recap}` : recap;
381
1244
  ${this.summary}` : "",
382
1245
  flattenMessages(older)
383
1246
  ].filter((part) => part.length > 0).join("\n\n");
384
- 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();
385
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
+ });
386
1290
  }
387
1291
  /** Clear the transcript and summary; optionally replace the system prompt. */
388
1292
  reset(system) {
1293
+ this.revision += 1;
389
1294
  if (system !== void 0) this.system = system;
390
1295
  this.messages = [];
391
1296
  this.summary = void 0;
@@ -393,16 +1298,26 @@ ${this.summary}` : "",
393
1298
  }
394
1299
  /** Tear down the underlying live session (kills the helper process). */
395
1300
  close() {
1301
+ this.revision += 1;
1302
+ this.backendInstructions = void 0;
396
1303
  this.backend.close();
397
1304
  }
398
1305
  };
399
1306
  function recoverable(error) {
400
1307
  return error instanceof Error && error.message.includes("[sessionClosed]");
401
1308
  }
1309
+ function isContextOverflow(error) {
1310
+ return error instanceof Error && error.message.includes("[contextWindowExceeded]");
1311
+ }
402
1312
  export {
1313
+ BUILTIN_TOOLS,
403
1314
  ChatSession,
404
1315
  HELPER_BIN_ENV,
405
1316
  LiveSession,
1317
+ PermissionPolicy,
1318
+ ToolRegistry,
1319
+ bashTool,
1320
+ countTokens,
406
1321
  encodeRequest,
407
1322
  estimateConversationTokens,
408
1323
  estimateTokens,
@@ -411,7 +1326,10 @@ export {
411
1326
  isPlatformSupported,
412
1327
  parseEvent,
413
1328
  probe,
1329
+ readTool,
1330
+ registryFromNames,
414
1331
  resolveHelperPath,
415
- splitLines
1332
+ splitLines,
1333
+ toolGuidancePrompt
416
1334
  };
417
1335
  //# sourceMappingURL=index.js.map