apple-fm 1.0.1 → 1.2.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
@@ -36,6 +36,28 @@ function parseEvent(line) {
36
36
  }
37
37
  throw new Error(`malformed helper event: ${line}`);
38
38
  }
39
+ var UNAVAILABLE_REASONS = [
40
+ "deviceNotEligible",
41
+ "appleIntelligenceNotEnabled",
42
+ "modelNotReady",
43
+ "unsupportedPlatform",
44
+ "unknown"
45
+ ];
46
+ function parseProbeResult(line) {
47
+ const value = JSON.parse(line);
48
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
49
+ throw new Error(`malformed probe result: ${line}`);
50
+ }
51
+ const record = value;
52
+ if (typeof record.available !== "boolean") {
53
+ throw new Error(`malformed probe result (available must be a boolean): ${line}`);
54
+ }
55
+ if (record.available) return { available: true };
56
+ if (typeof record.reason !== "string" || !UNAVAILABLE_REASONS.includes(record.reason)) {
57
+ throw new Error(`malformed probe result (missing/unknown reason): ${line}`);
58
+ }
59
+ return { available: false, reason: record.reason };
60
+ }
39
61
  function flattenMessages(messages) {
40
62
  return messages.map((message) => `${message.role === "assistant" ? "Assistant" : "User"}: ${message.content}`).join("\n\n");
41
63
  }
@@ -73,7 +95,7 @@ function resolveHelperPath(options = {}) {
73
95
  function runHelper(args, options, input, onLine) {
74
96
  const command = resolveHelperPath(options);
75
97
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
76
- return new Promise((resolve, reject) => {
98
+ return new Promise((resolve2, reject) => {
77
99
  const child = spawn(command, args, { stdio: ["pipe", "pipe", "pipe"] });
78
100
  let stdout = "";
79
101
  let stderr = "";
@@ -89,7 +111,7 @@ function runHelper(args, options, input, onLine) {
89
111
  settled = true;
90
112
  clearTimeout(timer);
91
113
  if (error) reject(error);
92
- else resolve();
114
+ else resolve2();
93
115
  };
94
116
  child.on("error", (error) => {
95
117
  finish(new Error(`failed to run apple-fm helper (${command}): ${error.message}`));
@@ -134,7 +156,7 @@ async function probe(options = {}) {
134
156
  }
135
157
  let result;
136
158
  await runHelper(["--probe"], options, void 0, (line) => {
137
- result = JSON.parse(line);
159
+ result = parseProbeResult(line);
138
160
  });
139
161
  if (result === void 0) throw new Error("apple-fm helper --probe produced no result");
140
162
  return result;
@@ -163,12 +185,450 @@ async function generate(request, options = {}, onDelta, onSnapshot) {
163
185
  }
164
186
 
165
187
  // src/liveSession.ts
188
+ import { spawn as spawn3 } from "child_process";
189
+
190
+ // src/tools/dispatch.ts
191
+ async function dispatchToolCall(event, deps) {
192
+ const callId = typeof event.callId === "string" ? event.callId : void 0;
193
+ const name = typeof event.name === "string" ? event.name : void 0;
194
+ const args = typeof event.arguments === "object" && event.arguments !== null ? event.arguments : {};
195
+ if (callId === void 0 || name === void 0) return;
196
+ deps.keepAlive();
197
+ const reply = (command) => {
198
+ deps.keepAlive();
199
+ deps.send({ ...command, callId });
200
+ };
201
+ const registry = deps.tools;
202
+ if (registry === void 0 || !registry.has(name)) {
203
+ reply({ type: "tool_result", content: `Unknown tool "${name}".` });
204
+ return;
205
+ }
206
+ if (deps.permission !== void 0) {
207
+ const request = registry.permissionRequest(name, args);
208
+ const allowed = request !== void 0 && await deps.permission.authorize(request);
209
+ if (!allowed) {
210
+ reply({ type: "tool_result", content: `Permission to use the "${name}" tool was denied by the user.` });
211
+ return;
212
+ }
213
+ }
214
+ try {
215
+ reply({ type: "tool_result", content: await registry.run(name, args) });
216
+ } catch (error) {
217
+ reply({ type: "tool_result", content: `The "${name}" tool failed: ${error instanceof Error ? error.message : String(error)}` });
218
+ }
219
+ }
220
+
221
+ // src/tools/builtin/bash.ts
166
222
  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
+ var DEFAULT_TIMEOUT_MS2 = 3e4;
234
+ var MAX_CAPTURE_CHARS = 256 * 1024;
235
+ var PIPE_DRAIN_GRACE_MS = 100;
236
+ var SAFE_ENV_KEYS = [
237
+ "PATH",
238
+ "HOME",
239
+ "USER",
240
+ "LOGNAME",
241
+ "SHELL",
242
+ "PWD",
243
+ "TMPDIR",
244
+ "LANG",
245
+ "LANGUAGE",
246
+ "LC_ALL",
247
+ "LC_CTYPE",
248
+ "TERM",
249
+ "TZ"
250
+ ];
251
+ function scopedEnv() {
252
+ const env = {};
253
+ for (const key of SAFE_ENV_KEYS) {
254
+ const value = process.env[key];
255
+ if (value !== void 0) env[key] = value;
256
+ }
257
+ return env;
258
+ }
259
+ function runShellCommand(command, options = {}) {
260
+ if (command.trim().length === 0) return Promise.reject(new Error('bash: "command" (string) is required'));
261
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
262
+ return new Promise((resolve2) => {
263
+ const child = spawn2("/bin/sh", ["-c", command], {
264
+ stdio: ["ignore", "pipe", "pipe"],
265
+ detached: true,
266
+ env: options.inheritEnv === true ? process.env : scopedEnv()
267
+ });
268
+ let stdout = "";
269
+ let stderr = "";
270
+ let timedOut = false;
271
+ let overflowed = false;
272
+ let settled = false;
273
+ let exitCode = null;
274
+ let exitSignal = null;
275
+ let graceTimer;
276
+ const killGroup = () => {
277
+ try {
278
+ if (child.pid !== void 0) process.kill(-child.pid, "SIGKILL");
279
+ else child.kill("SIGKILL");
280
+ } catch {
281
+ child.kill("SIGKILL");
282
+ }
283
+ };
284
+ const timer = setTimeout(() => {
285
+ timedOut = true;
286
+ killGroup();
287
+ }, timeoutMs);
288
+ const append = (buffer, chunk) => {
289
+ if (overflowed) return buffer;
290
+ const remaining = MAX_CAPTURE_CHARS - (stdout.length + stderr.length);
291
+ if (chunk.length <= remaining) return buffer + chunk;
292
+ overflowed = true;
293
+ killGroup();
294
+ return buffer + chunk.slice(0, Math.max(0, remaining));
295
+ };
296
+ const settle = () => {
297
+ if (settled) return;
298
+ settled = true;
299
+ clearTimeout(timer);
300
+ if (graceTimer !== void 0) clearTimeout(graceTimer);
301
+ child.stdout.destroy();
302
+ child.stderr.destroy();
303
+ 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)}`;
304
+ resolve2(report({ stdout, stderr, status }));
305
+ };
306
+ child.stdout.setEncoding("utf8");
307
+ child.stderr.setEncoding("utf8");
308
+ child.stdout.on("data", (chunk) => stdout = append(stdout, chunk));
309
+ child.stderr.on("data", (chunk) => stderr = append(stderr, chunk));
310
+ child.on("error", (error) => {
311
+ if (settled) return;
312
+ settled = true;
313
+ clearTimeout(timer);
314
+ if (graceTimer !== void 0) clearTimeout(graceTimer);
315
+ resolve2(report({ stdout, stderr, status: `failed to start: ${error.message}` }));
316
+ });
317
+ child.on("exit", (code, signal) => {
318
+ exitCode = code;
319
+ exitSignal = signal;
320
+ killGroup();
321
+ graceTimer = setTimeout(settle, PIPE_DRAIN_GRACE_MS);
322
+ });
323
+ child.on("close", settle);
324
+ });
325
+ }
326
+ function report({ stdout, stderr, status }) {
327
+ const sections = [status];
328
+ if (stdout.length > 0) sections.push(`stdout:
329
+ ${stdout}`);
330
+ if (stderr.length > 0) sections.push(`stderr:
331
+ ${stderr}`);
332
+ return capOutput(sections.join("\n"));
333
+ }
334
+ var bashTool = {
335
+ name: "bash",
336
+ 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.",
337
+ parameters: {
338
+ type: "object",
339
+ description: "Arguments for the bash tool.",
340
+ required: ["command"],
341
+ properties: {
342
+ command: { type: "string", description: "The shell command to run." }
343
+ }
344
+ },
345
+ dangerous: true,
346
+ permissionKey: (args) => typeof args.command === "string" ? args.command : void 0,
347
+ // Allow grants are EXACT — approving `ls` never approves `ls; curl evil` (AFM-63).
348
+ // Deny rules are a broad best-effort token match: the denied token, at a start /
349
+ // whitespace / path boundary, anywhere in the normalized command, so `--deny-tool
350
+ // bash:rm` also catches `/bin/rm` and `command rm` — but this is NOT a security
351
+ // guarantee (`eval`, `$(…)`, aliases evade it); the real control is not enabling
352
+ // bash (AFM-67).
353
+ matchKey: (ruleKey, callKey, kind) => {
354
+ if (kind === "allow") return ruleKey === callKey;
355
+ const token = ruleKey.trim();
356
+ if (token.length === 0) return false;
357
+ const escaped = token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
358
+ return new RegExp(`(^|[\\s/])${escaped}`).test(callKey.trim().replace(/\s+/g, " "));
359
+ },
360
+ describe: (args) => `run: ${typeof args.command === "string" ? args.command : "(no command)"}`,
361
+ usageHint: "bash \u2014 run a shell command; use it to inspect the system or run CLI tools, NOT to read files or fetch URLs.",
362
+ run: (args) => runShellCommand(typeof args.command === "string" ? args.command : "")
363
+ };
364
+
365
+ // src/tools/builtin/read.ts
366
+ import { realpathSync } from "fs";
367
+ import { open, stat } from "fs/promises";
368
+ import { basename, dirname, join, resolve, sep } from "path";
369
+ function intArg(value) {
370
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
371
+ }
372
+ var READ_MAX_BYTES = 1024 * 1024;
373
+ var READ_TIMEOUT_MS = 1e4;
374
+ function withTimeout(promise, ms, label) {
375
+ return new Promise((res, rej) => {
376
+ const timer = setTimeout(() => {
377
+ rej(new Error(`read: timed out after ${String(ms)}ms reading "${label}"`));
378
+ }, ms);
379
+ promise.then(
380
+ (value) => {
381
+ clearTimeout(timer);
382
+ res(value);
383
+ },
384
+ (error) => {
385
+ clearTimeout(timer);
386
+ rej(error instanceof Error ? error : new Error(String(error)));
387
+ }
388
+ );
389
+ });
390
+ }
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";
398
+ }
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`);
403
+ }
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
+ }
434
+ }
435
+ }
436
+ var readTool = {
437
+ name: "read",
438
+ 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.',
439
+ parameters: {
440
+ type: "object",
441
+ description: "Arguments for the read tool.",
442
+ required: ["path"],
443
+ properties: {
444
+ path: { type: "string", description: "Filesystem path of the file to read." },
445
+ offset: { type: "integer", minimum: 0, description: "First line to return (0-based)." },
446
+ limit: { type: "integer", minimum: 1, description: "Maximum number of lines to return." }
447
+ }
448
+ },
449
+ // Scope permission rules / "always" grants to the path, so a user can approve a
450
+ // directory once (`read:/Users/me/project`) without allowing every read.
451
+ permissionKey: (args) => typeof args.path === "string" ? args.path : void 0,
452
+ // A path rule covers a file exactly or a directory and everything *inside* it — after
453
+ // resolving `..` AND following symlinks, and only across a real path-separator
454
+ // boundary. Resolving the **real** path (not just the textual one) is what stops a
455
+ // symlink inside an approved dir from escaping the grant (AFM-76): `read:/proj`
456
+ // neither leaks `/proj-secret`, lets `/proj/../.ssh/id_rsa` escape, nor lets
457
+ // `/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
+ },
463
+ describe: (args) => `read ${typeof args.path === "string" ? args.path : "(no path)"}`,
464
+ 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";
601
+ }
602
+ };
603
+
604
+ // src/tools/index.ts
605
+ var BUILTIN_TOOLS = { read: readTool, bash: bashTool };
606
+ function toolGuidancePrompt(registry) {
607
+ const hints = registry.usageHints();
608
+ if (hints.length === 0) return "";
609
+ 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:";
610
+ return [intro, ...hints.map((hint) => `- ${hint}`)].join("\n");
611
+ }
612
+ function registryFromNames(names) {
613
+ const registry = new ToolRegistry();
614
+ for (const name of names) {
615
+ const tool = BUILTIN_TOOLS[name];
616
+ if (tool === void 0) {
617
+ throw new Error(`unknown built-in tool "${name}" (available: ${Object.keys(BUILTIN_TOOLS).join(", ")})`);
618
+ }
619
+ registry.register(tool);
620
+ }
621
+ return registry;
622
+ }
623
+
624
+ // src/liveSession.ts
167
625
  var DEFAULT_TURN_TIMEOUT_MS = 12e4;
168
626
  var LiveSession = class {
169
627
  command;
170
628
  timeoutMs;
171
629
  options;
630
+ tools;
631
+ permission;
172
632
  /** Whether we'd spawn the bundled macOS helper (subject to the platform gate). */
173
633
  bundled;
174
634
  child;
@@ -179,19 +639,36 @@ var LiveSession = class {
179
639
  this.command = resolveHelperPath(config);
180
640
  this.timeoutMs = config.timeoutMs ?? DEFAULT_TURN_TIMEOUT_MS;
181
641
  this.options = config.options;
642
+ this.tools = config.tools !== void 0 && config.tools.size > 0 ? config.tools : void 0;
643
+ this.permission = config.permission ?? (this.tools !== void 0 ? new PermissionPolicy() : void 0);
182
644
  this.bundled = usingBundledHelper(config);
183
645
  }
184
- /** Recreate the underlying session with new instructions + seed turns. */
646
+ /**
647
+ * Recreate the underlying session with new instructions + seed turns. Tool
648
+ * definitions ride on `reset` because the framework binds tools at session
649
+ * construction (not per turn); the helper builds the session's tools here.
650
+ */
185
651
  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
652
+ await this.dispatch(
653
+ {
654
+ type: "reset",
655
+ system,
656
+ seed,
657
+ // Only attach tools when some are registered, so resets stay byte-identical
658
+ // to the no-tools path otherwise.
659
+ ...this.tools !== void 0 ? { tools: this.tools.definitions() } : {}
660
+ },
661
+ void 0
193
662
  );
194
663
  }
664
+ /**
665
+ * Send one user turn; prior turns stay in context. Streams via `onDelta`. An
666
+ * optional `signal` interrupts the turn: on abort a `cancel` command is sent and
667
+ * the helper ends the turn with the partial text generated so far (FR-15).
668
+ */
669
+ send(text, onDelta, signal) {
670
+ return this.dispatch({ prompt: text, options: this.options, stream: onDelta !== void 0 }, onDelta, signal);
671
+ }
195
672
  /** Tear down the helper process and reject any in-flight commands. */
196
673
  close() {
197
674
  const child = this.child;
@@ -209,7 +686,7 @@ var LiveSession = class {
209
686
  ensureChild() {
210
687
  const existing = this.child;
211
688
  if (existing !== void 0 && existing.exitCode === null && !existing.killed) return existing;
212
- const child = spawn2(this.command, ["--session"], { stdio: ["pipe", "pipe", "pipe"] });
689
+ const child = spawn3(this.command, ["--session"], { stdio: ["pipe", "pipe", "pipe"] });
213
690
  this.buffer = "";
214
691
  child.stdout.setEncoding("utf8");
215
692
  child.stdout.on("data", (chunk) => {
@@ -251,6 +728,9 @@ var LiveSession = class {
251
728
  pending.onDelta?.(event.text);
252
729
  }
253
730
  break;
731
+ case "tool_call":
732
+ void this.handleToolCall(id, pending, event);
733
+ break;
254
734
  case "ready":
255
735
  this.settle(id, "");
256
736
  break;
@@ -264,6 +744,32 @@ var LiveSession = class {
264
744
  break;
265
745
  }
266
746
  }
747
+ /**
748
+ * Dispatch a `tool_call` to the registered tool and write the outcome back to the
749
+ * helper, keyed by `callId`. Runs concurrently with the still-open turn; the tool
750
+ * 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.
752
+ */
753
+ handleToolCall(id, pending, event) {
754
+ return dispatchToolCall(event, {
755
+ tools: this.tools,
756
+ permission: this.permission,
757
+ 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);
763
+ }
764
+ });
765
+ }
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
+ }
267
773
  settle(id, content) {
268
774
  const pending = this.pending.get(id);
269
775
  if (pending === void 0) return;
@@ -278,19 +784,36 @@ var LiveSession = class {
278
784
  this.pending.delete(id);
279
785
  pending.reject(new Error(message));
280
786
  }
281
- dispatch(command, onDelta) {
787
+ dispatch(command, onDelta, signal) {
282
788
  if (this.bundled && !isPlatformSupported()) return Promise.reject(unsupportedPlatformError());
283
789
  const child = this.ensureChild();
284
790
  const id = String(this.nextId++);
285
- return new Promise((resolve, reject) => {
791
+ return new Promise((resolve2, reject) => {
286
792
  const timer = setTimeout(() => {
287
793
  this.pending.delete(id);
288
794
  reject(new Error(`live session timed out after ${String(this.timeoutMs)}ms`));
289
795
  }, this.timeoutMs);
290
- this.pending.set(id, { resolve, reject, onDelta, acc: "", timer });
796
+ this.pending.set(id, { resolve: resolve2, reject, onDelta, acc: "", timer });
797
+ 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
+ }
808
+ }
291
809
  child.stdin.write(JSON.stringify({ ...command, id }) + "\n");
292
810
  });
293
811
  }
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
+ }
294
817
  };
295
818
 
296
819
  // src/session.ts
@@ -315,7 +838,12 @@ var ChatSession = class {
315
838
  this.system = config.system ?? "";
316
839
  this.compactAtTokens = config.compactAtTokens ?? DEFAULT_COMPACT_AT;
317
840
  this.keepRecentTurns = config.keepRecentTurns ?? DEFAULT_KEEP_RECENT;
318
- this.backend = config.backend ?? new LiveSession({ ...config.helper, options: config.options });
841
+ this.backend = config.backend ?? new LiveSession({
842
+ ...config.helper,
843
+ options: config.options,
844
+ tools: config.tools,
845
+ permission: config.permission
846
+ });
319
847
  this.generateFn = config.generateFn ?? defaultGenerateFn(config.helper, config.options);
320
848
  }
321
849
  /** The system prompt actually sent to the model (instructions + any recap). */
@@ -335,24 +863,31 @@ ${recap}` : recap;
335
863
  shouldCompact() {
336
864
  return estimateConversationTokens(this.effectiveSystem(), this.messages) > this.compactAtTokens;
337
865
  }
338
- /** Send a user turn and return the assistant's reply (streamed via `onDelta`). */
339
- async send(text, onDelta) {
866
+ /**
867
+ * Send a user turn and return the assistant's reply (streamed via `onDelta`). An
868
+ * optional `signal` interrupts the turn (FR-15, esc-to-interrupt): on abort the
869
+ * 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).
871
+ */
872
+ async send(text, onDelta, signal) {
340
873
  if (this.shouldCompact()) await this.compact();
341
874
  await this.ensureStarted();
342
875
  this.messages.push({ role: "user", content: text });
343
876
  let reply;
344
877
  try {
345
- reply = await this.backend.send(text, onDelta);
878
+ reply = await this.backend.send(text, onDelta, signal);
346
879
  } catch (error) {
347
- if (!recoverable(error)) {
880
+ const overflow = isContextOverflow(error);
881
+ if (!recoverable(error) && !overflow) {
348
882
  this.messages.pop();
349
883
  throw error;
350
884
  }
351
885
  this.messages.pop();
886
+ if (overflow) await this.compact();
352
887
  this.backendInstructions = void 0;
353
888
  await this.ensureStarted();
354
889
  this.messages.push({ role: "user", content: text });
355
- reply = await this.backend.send(text, onDelta);
890
+ reply = await this.backend.send(text, onDelta, signal);
356
891
  }
357
892
  this.messages.push({ role: "assistant", content: reply });
358
893
  return reply;
@@ -399,10 +934,17 @@ ${this.summary}` : "",
399
934
  function recoverable(error) {
400
935
  return error instanceof Error && error.message.includes("[sessionClosed]");
401
936
  }
937
+ function isContextOverflow(error) {
938
+ return error instanceof Error && error.message.includes("[contextWindowExceeded]");
939
+ }
402
940
  export {
941
+ BUILTIN_TOOLS,
403
942
  ChatSession,
404
943
  HELPER_BIN_ENV,
405
944
  LiveSession,
945
+ PermissionPolicy,
946
+ ToolRegistry,
947
+ bashTool,
406
948
  encodeRequest,
407
949
  estimateConversationTokens,
408
950
  estimateTokens,
@@ -411,7 +953,10 @@ export {
411
953
  isPlatformSupported,
412
954
  parseEvent,
413
955
  probe,
956
+ readTool,
957
+ registryFromNames,
414
958
  resolveHelperPath,
415
- splitLines
959
+ splitLines,
960
+ toolGuidancePrompt
416
961
  };
417
962
  //# sourceMappingURL=index.js.map