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/cli.js CHANGED
@@ -23,14 +23,22 @@ Chat flags:
23
23
  -s, --system <text> System instructions
24
24
  --no-stream Disable token streaming
25
25
  --compact-at <n> Compact the transcript past <n> estimated tokens
26
+ --tools <a,b> Enable built-in tools the model may call (read, bash)
27
+ --allow-tool <rule> Pre-approve a tool (read, read:/path, or bash:<exact cmd>).
28
+ A read path grant covers that dir; a bash grant is the
29
+ EXACT command only. Repeatable
30
+ --deny-tool <rule> Deny a tool (same syntax; a bash deny is best-effort).
31
+ Repeatable
32
+ --yes Auto-approve tool calls \u2014 except bash, which still prompts
33
+ (add --allow-tool bash to include it). Use with care
26
34
 
27
35
  Global:
28
36
  -h, --help Show this help
29
37
  -v, --version Show version
30
38
 
31
- The helper binary is found via APPLE_FM_BIN, then the bundled bin/apple-fm-helper,
32
- then apple-fm-helper on PATH. Requires macOS 26+ on Apple Silicon with Apple
33
- Intelligence enabled.`;
39
+ The helper binary is found via APPLE_FM_BIN (an explicit override, trusted as-is),
40
+ otherwise the bundled bin/apple-fm-helper shipped with the package. Requires macOS
41
+ 26+ on Apple Silicon with Apple Intelligence enabled.`;
34
42
  function parseNumber(flag, value) {
35
43
  if (value === void 0) throw new Error(`${flag} requires a value`);
36
44
  const n = Number(value);
@@ -103,12 +111,27 @@ function parseChat(argv) {
103
111
  case "--compact-at":
104
112
  result.compactAtTokens = parseNumber(arg, takeValue(argv, i++, arg));
105
113
  break;
114
+ case "--tools":
115
+ result.tools = parseList(takeValue(argv, i++, arg));
116
+ break;
117
+ case "--allow-tool":
118
+ (result.allowTools ??= []).push(takeValue(argv, i++, arg));
119
+ break;
120
+ case "--deny-tool":
121
+ (result.denyTools ??= []).push(takeValue(argv, i++, arg));
122
+ break;
123
+ case "--yes":
124
+ result.yes = true;
125
+ break;
106
126
  default:
107
127
  throw new Error(`unknown flag "${arg}"`);
108
128
  }
109
129
  }
110
130
  return result;
111
131
  }
132
+ function parseList(value) {
133
+ return value.split(",").map((name) => name.trim()).filter((name) => name.length > 0);
134
+ }
112
135
 
113
136
  // src/helper.ts
114
137
  import { spawn } from "child_process";
@@ -148,6 +171,28 @@ function parseEvent(line) {
148
171
  }
149
172
  throw new Error(`malformed helper event: ${line}`);
150
173
  }
174
+ var UNAVAILABLE_REASONS = [
175
+ "deviceNotEligible",
176
+ "appleIntelligenceNotEnabled",
177
+ "modelNotReady",
178
+ "unsupportedPlatform",
179
+ "unknown"
180
+ ];
181
+ function parseProbeResult(line) {
182
+ const value = JSON.parse(line);
183
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
184
+ throw new Error(`malformed probe result: ${line}`);
185
+ }
186
+ const record = value;
187
+ if (typeof record.available !== "boolean") {
188
+ throw new Error(`malformed probe result (available must be a boolean): ${line}`);
189
+ }
190
+ if (record.available) return { available: true };
191
+ if (typeof record.reason !== "string" || !UNAVAILABLE_REASONS.includes(record.reason)) {
192
+ throw new Error(`malformed probe result (missing/unknown reason): ${line}`);
193
+ }
194
+ return { available: false, reason: record.reason };
195
+ }
151
196
  function flattenMessages(messages) {
152
197
  return messages.map((message) => `${message.role === "assistant" ? "Assistant" : "User"}: ${message.content}`).join("\n\n");
153
198
  }
@@ -185,7 +230,7 @@ function resolveHelperPath(options = {}) {
185
230
  function runHelper(args, options, input, onLine) {
186
231
  const command = resolveHelperPath(options);
187
232
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
188
- return new Promise((resolve, reject) => {
233
+ return new Promise((resolve2, reject) => {
189
234
  const child = spawn(command, args, { stdio: ["pipe", "pipe", "pipe"] });
190
235
  let stdout = "";
191
236
  let stderr = "";
@@ -201,7 +246,7 @@ function runHelper(args, options, input, onLine) {
201
246
  settled = true;
202
247
  clearTimeout(timer);
203
248
  if (error) reject(error);
204
- else resolve();
249
+ else resolve2();
205
250
  };
206
251
  child.on("error", (error) => {
207
252
  finish(new Error(`failed to run apple-fm helper (${command}): ${error.message}`));
@@ -246,7 +291,7 @@ async function probe(options = {}) {
246
291
  }
247
292
  let result;
248
293
  await runHelper(["--probe"], options, void 0, (line) => {
249
- result = JSON.parse(line);
294
+ result = parseProbeResult(line);
250
295
  });
251
296
  if (result === void 0) throw new Error("apple-fm helper --probe produced no result");
252
297
  return result;
@@ -275,15 +320,459 @@ async function generate(request, options = {}, onDelta, onSnapshot) {
275
320
  }
276
321
 
277
322
  // src/repl.ts
278
- import { createInterface } from "readline";
323
+ import { createInterface, emitKeypressEvents } from "readline";
279
324
 
280
325
  // src/liveSession.ts
326
+ import { spawn as spawn3 } from "child_process";
327
+
328
+ // src/tools/dispatch.ts
329
+ async function dispatchToolCall(event, deps) {
330
+ const callId = typeof event.callId === "string" ? event.callId : void 0;
331
+ const name = typeof event.name === "string" ? event.name : void 0;
332
+ const args = typeof event.arguments === "object" && event.arguments !== null ? event.arguments : {};
333
+ if (callId === void 0 || name === void 0) return;
334
+ deps.keepAlive();
335
+ const reply = (command) => {
336
+ deps.keepAlive();
337
+ deps.send({ ...command, callId });
338
+ };
339
+ const registry = deps.tools;
340
+ if (registry === void 0 || !registry.has(name)) {
341
+ reply({ type: "tool_result", content: `Unknown tool "${name}".` });
342
+ return;
343
+ }
344
+ if (deps.permission !== void 0) {
345
+ const request = registry.permissionRequest(name, args);
346
+ const allowed = request !== void 0 && await deps.permission.authorize(request);
347
+ if (!allowed) {
348
+ reply({ type: "tool_result", content: `Permission to use the "${name}" tool was denied by the user.` });
349
+ return;
350
+ }
351
+ }
352
+ try {
353
+ reply({ type: "tool_result", content: await registry.run(name, args) });
354
+ } catch (error) {
355
+ reply({ type: "tool_result", content: `The "${name}" tool failed: ${error instanceof Error ? error.message : String(error)}` });
356
+ }
357
+ }
358
+
359
+ // src/tools/builtin/bash.ts
281
360
  import { spawn as spawn2 } from "child_process";
361
+
362
+ // src/tools/output.ts
363
+ var MAX_TOOL_OUTPUT_CHARS = 3e3;
364
+ function capOutput(text, max = MAX_TOOL_OUTPUT_CHARS) {
365
+ if (text.length <= max) return text;
366
+ return `${text.slice(0, max)}
367
+ \u2026(${String(text.length - max)} more chars truncated)`;
368
+ }
369
+
370
+ // src/tools/builtin/bash.ts
371
+ var DEFAULT_TIMEOUT_MS2 = 3e4;
372
+ var MAX_CAPTURE_CHARS = 256 * 1024;
373
+ var PIPE_DRAIN_GRACE_MS = 100;
374
+ var SAFE_ENV_KEYS = [
375
+ "PATH",
376
+ "HOME",
377
+ "USER",
378
+ "LOGNAME",
379
+ "SHELL",
380
+ "PWD",
381
+ "TMPDIR",
382
+ "LANG",
383
+ "LANGUAGE",
384
+ "LC_ALL",
385
+ "LC_CTYPE",
386
+ "TERM",
387
+ "TZ"
388
+ ];
389
+ function scopedEnv() {
390
+ const env = {};
391
+ for (const key of SAFE_ENV_KEYS) {
392
+ const value = process.env[key];
393
+ if (value !== void 0) env[key] = value;
394
+ }
395
+ return env;
396
+ }
397
+ function runShellCommand(command, options = {}) {
398
+ if (command.trim().length === 0) return Promise.reject(new Error('bash: "command" (string) is required'));
399
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
400
+ return new Promise((resolve2) => {
401
+ const child = spawn2("/bin/sh", ["-c", command], {
402
+ stdio: ["ignore", "pipe", "pipe"],
403
+ detached: true,
404
+ env: options.inheritEnv === true ? process.env : scopedEnv()
405
+ });
406
+ let stdout = "";
407
+ let stderr = "";
408
+ let timedOut = false;
409
+ let overflowed = false;
410
+ let settled = false;
411
+ let exitCode = null;
412
+ let exitSignal = null;
413
+ let graceTimer;
414
+ const killGroup = () => {
415
+ try {
416
+ if (child.pid !== void 0) process.kill(-child.pid, "SIGKILL");
417
+ else child.kill("SIGKILL");
418
+ } catch {
419
+ child.kill("SIGKILL");
420
+ }
421
+ };
422
+ const timer = setTimeout(() => {
423
+ timedOut = true;
424
+ killGroup();
425
+ }, timeoutMs);
426
+ const append = (buffer, chunk) => {
427
+ if (overflowed) return buffer;
428
+ const remaining = MAX_CAPTURE_CHARS - (stdout.length + stderr.length);
429
+ if (chunk.length <= remaining) return buffer + chunk;
430
+ overflowed = true;
431
+ killGroup();
432
+ return buffer + chunk.slice(0, Math.max(0, remaining));
433
+ };
434
+ const settle = () => {
435
+ if (settled) return;
436
+ settled = true;
437
+ clearTimeout(timer);
438
+ if (graceTimer !== void 0) clearTimeout(graceTimer);
439
+ child.stdout.destroy();
440
+ child.stderr.destroy();
441
+ 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)}`;
442
+ resolve2(report({ stdout, stderr, status }));
443
+ };
444
+ child.stdout.setEncoding("utf8");
445
+ child.stderr.setEncoding("utf8");
446
+ child.stdout.on("data", (chunk) => stdout = append(stdout, chunk));
447
+ child.stderr.on("data", (chunk) => stderr = append(stderr, chunk));
448
+ child.on("error", (error) => {
449
+ if (settled) return;
450
+ settled = true;
451
+ clearTimeout(timer);
452
+ if (graceTimer !== void 0) clearTimeout(graceTimer);
453
+ resolve2(report({ stdout, stderr, status: `failed to start: ${error.message}` }));
454
+ });
455
+ child.on("exit", (code, signal) => {
456
+ exitCode = code;
457
+ exitSignal = signal;
458
+ killGroup();
459
+ graceTimer = setTimeout(settle, PIPE_DRAIN_GRACE_MS);
460
+ });
461
+ child.on("close", settle);
462
+ });
463
+ }
464
+ function report({ stdout, stderr, status }) {
465
+ const sections = [status];
466
+ if (stdout.length > 0) sections.push(`stdout:
467
+ ${stdout}`);
468
+ if (stderr.length > 0) sections.push(`stderr:
469
+ ${stderr}`);
470
+ return capOutput(sections.join("\n"));
471
+ }
472
+ var bashTool = {
473
+ name: "bash",
474
+ 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.",
475
+ parameters: {
476
+ type: "object",
477
+ description: "Arguments for the bash tool.",
478
+ required: ["command"],
479
+ properties: {
480
+ command: { type: "string", description: "The shell command to run." }
481
+ }
482
+ },
483
+ dangerous: true,
484
+ permissionKey: (args) => typeof args.command === "string" ? args.command : void 0,
485
+ // Allow grants are EXACT — approving `ls` never approves `ls; curl evil` (AFM-63).
486
+ // Deny rules are a broad best-effort token match: the denied token, at a start /
487
+ // whitespace / path boundary, anywhere in the normalized command, so `--deny-tool
488
+ // bash:rm` also catches `/bin/rm` and `command rm` — but this is NOT a security
489
+ // guarantee (`eval`, `$(…)`, aliases evade it); the real control is not enabling
490
+ // bash (AFM-67).
491
+ matchKey: (ruleKey, callKey, kind) => {
492
+ if (kind === "allow") return ruleKey === callKey;
493
+ const token = ruleKey.trim();
494
+ if (token.length === 0) return false;
495
+ const escaped = token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
496
+ return new RegExp(`(^|[\\s/])${escaped}`).test(callKey.trim().replace(/\s+/g, " "));
497
+ },
498
+ describe: (args) => `run: ${typeof args.command === "string" ? args.command : "(no command)"}`,
499
+ usageHint: "bash \u2014 run a shell command; use it to inspect the system or run CLI tools, NOT to read files or fetch URLs.",
500
+ run: (args) => runShellCommand(typeof args.command === "string" ? args.command : "")
501
+ };
502
+
503
+ // src/tools/builtin/read.ts
504
+ import { realpathSync } from "fs";
505
+ import { open, stat } from "fs/promises";
506
+ import { basename, dirname, join, resolve, sep } from "path";
507
+ function intArg(value) {
508
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
509
+ }
510
+ var READ_MAX_BYTES = 1024 * 1024;
511
+ var READ_TIMEOUT_MS = 1e4;
512
+ function withTimeout(promise, ms, label) {
513
+ return new Promise((res, rej) => {
514
+ const timer = setTimeout(() => {
515
+ rej(new Error(`read: timed out after ${String(ms)}ms reading "${label}"`));
516
+ }, ms);
517
+ promise.then(
518
+ (value) => {
519
+ clearTimeout(timer);
520
+ res(value);
521
+ },
522
+ (error) => {
523
+ clearTimeout(timer);
524
+ rej(error instanceof Error ? error : new Error(String(error)));
525
+ }
526
+ );
527
+ });
528
+ }
529
+ function fileKind(stats) {
530
+ if (stats.isDirectory()) return "directory";
531
+ if (stats.isFIFO()) return "named pipe (fifo)";
532
+ if (stats.isCharacterDevice()) return "character device";
533
+ if (stats.isBlockDevice()) return "block device";
534
+ if (stats.isSocket()) return "socket";
535
+ return "special file";
536
+ }
537
+ async function readRegularFileBounded(path, maxBytes) {
538
+ const stats = await stat(path);
539
+ if (!stats.isFile()) {
540
+ throw new Error(`read: "${path}" is a ${fileKind(stats)}, not a regular file \u2014 refusing to read it`);
541
+ }
542
+ const handle = await open(path, "r");
543
+ try {
544
+ const buffer = Buffer.alloc(maxBytes);
545
+ const { bytesRead } = await handle.read(buffer, 0, maxBytes, 0);
546
+ return buffer.toString("utf8", 0, bytesRead);
547
+ } finally {
548
+ await handle.close();
549
+ }
550
+ }
551
+ async function readTextFile(path, range = {}, options = {}) {
552
+ const maxBytes = options.maxBytes ?? READ_MAX_BYTES;
553
+ const timeoutMs = options.timeoutMs ?? READ_TIMEOUT_MS;
554
+ const content = await withTimeout(readRegularFileBounded(path, maxBytes), timeoutMs, path);
555
+ const { offset, limit } = range;
556
+ if (offset === void 0 && limit === void 0) return capOutput(content);
557
+ const lines = content.split("\n");
558
+ const start = offset ?? 0;
559
+ const end = limit !== void 0 ? start + limit : lines.length;
560
+ return capOutput(lines.slice(start, end).join("\n"));
561
+ }
562
+ function realResolve(path) {
563
+ const abs = resolve(path);
564
+ try {
565
+ return realpathSync(abs);
566
+ } catch {
567
+ try {
568
+ return join(realpathSync(dirname(abs)), basename(abs));
569
+ } catch {
570
+ return abs;
571
+ }
572
+ }
573
+ }
574
+ var readTool = {
575
+ name: "read",
576
+ 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.',
577
+ parameters: {
578
+ type: "object",
579
+ description: "Arguments for the read tool.",
580
+ required: ["path"],
581
+ properties: {
582
+ path: { type: "string", description: "Filesystem path of the file to read." },
583
+ offset: { type: "integer", minimum: 0, description: "First line to return (0-based)." },
584
+ limit: { type: "integer", minimum: 1, description: "Maximum number of lines to return." }
585
+ }
586
+ },
587
+ // Scope permission rules / "always" grants to the path, so a user can approve a
588
+ // directory once (`read:/Users/me/project`) without allowing every read.
589
+ permissionKey: (args) => typeof args.path === "string" ? args.path : void 0,
590
+ // A path rule covers a file exactly or a directory and everything *inside* it — after
591
+ // resolving `..` AND following symlinks, and only across a real path-separator
592
+ // boundary. Resolving the **real** path (not just the textual one) is what stops a
593
+ // symlink inside an approved dir from escaping the grant (AFM-76): `read:/proj`
594
+ // neither leaks `/proj-secret`, lets `/proj/../.ssh/id_rsa` escape, nor lets
595
+ // `/proj/link → /etc/shadow` read outside the boundary. Same test for allow and deny.
596
+ matchKey: (ruleKey, callKey) => {
597
+ const rulePath = realResolve(ruleKey);
598
+ const callPath = realResolve(callKey);
599
+ return callPath === rulePath || callPath.startsWith(rulePath + sep);
600
+ },
601
+ describe: (args) => `read ${typeof args.path === "string" ? args.path : "(no path)"}`,
602
+ 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.",
603
+ async run(args) {
604
+ const path = typeof args.path === "string" ? args.path : "";
605
+ if (path.length === 0) throw new Error('read: "path" (string) is required');
606
+ if (/^https?:\/\//i.test(path)) {
607
+ return `"${path}" is a URL, not a local file. The read tool only reads local files; apple-fm cannot fetch URLs.`;
608
+ }
609
+ return readTextFile(path, { offset: intArg(args.offset), limit: intArg(args.limit) });
610
+ }
611
+ };
612
+
613
+ // src/tools/registry.ts
614
+ var ToolRegistry = class {
615
+ tools = /* @__PURE__ */ new Map();
616
+ constructor(tools = []) {
617
+ for (const tool of tools) this.register(tool);
618
+ }
619
+ /** Register (or replace) a tool by name. */
620
+ register(tool) {
621
+ this.tools.set(tool.name, tool);
622
+ }
623
+ /** Whether a tool with this name is registered. */
624
+ has(name) {
625
+ return this.tools.has(name);
626
+ }
627
+ /** Number of registered tools (0 ⇒ no `tools[]` is sent on a turn). */
628
+ get size() {
629
+ return this.tools.size;
630
+ }
631
+ /** The model-facing definitions sent to the helper on a turn command. */
632
+ definitions() {
633
+ return [...this.tools.values()].map(({ name, description, parameters }) => ({
634
+ name,
635
+ description,
636
+ parameters
637
+ }));
638
+ }
639
+ /** The registered tool names (for the REPL `/tools` listing). */
640
+ names() {
641
+ return [...this.tools.keys()];
642
+ }
643
+ /** One usage hint per tool (its `usageHint`, or a `name: description` fallback). */
644
+ usageHints() {
645
+ return [...this.tools.values()].map((tool) => tool.usageHint ?? `${tool.name}: ${tool.description}`);
646
+ }
647
+ /**
648
+ * Build a {@link PermissionRequest} for a call, using the tool's optional
649
+ * `permissionKey` / `describe` hooks. Returns `undefined` for an unknown tool.
650
+ */
651
+ permissionRequest(name, args) {
652
+ const tool = this.tools.get(name);
653
+ if (tool === void 0) return void 0;
654
+ return {
655
+ tool: name,
656
+ key: tool.permissionKey?.(args),
657
+ description: tool.describe?.(args) ?? `${name} ${JSON.stringify(args)}`,
658
+ args,
659
+ // Carry the tool's own key-matching + risk semantics so the policy can apply
660
+ // them without knowing about specific tools (AFM-63 / AFM-64 / AFM-67).
661
+ matchKey: tool.matchKey?.bind(tool),
662
+ dangerous: tool.dangerous
663
+ };
664
+ }
665
+ /**
666
+ * Run a tool by name. Throws (with a clear message) if no such tool is
667
+ * registered, so the dispatcher can surface a `tool_error` to the model.
668
+ */
669
+ async run(name, args, ctx = {}) {
670
+ const tool = this.tools.get(name);
671
+ if (tool === void 0) throw new Error(`unknown tool: ${name}`);
672
+ return tool.run(args, ctx);
673
+ }
674
+ };
675
+
676
+ // src/tools/permissions.ts
677
+ var MAX_PROMPT_DESCRIPTION = 200;
678
+ function sanitizeForPrompt(text) {
679
+ const stripped = text.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "").replace(/[\x00-\x1f\x7f]+/g, " ").trim();
680
+ if (stripped.length <= MAX_PROMPT_DESCRIPTION) return stripped;
681
+ return `${stripped.slice(0, MAX_PROMPT_DESCRIPTION)}\u2026 (${String(stripped.length - MAX_PROMPT_DESCRIPTION)} more chars)`;
682
+ }
683
+ var exactKeyMatch = (ruleKey, callKey) => ruleKey === callKey;
684
+ function ruleMatches(rule, request, kind) {
685
+ const colon = rule.indexOf(":");
686
+ if (colon < 0) return rule === request.tool;
687
+ if (rule.slice(0, colon) !== request.tool) return false;
688
+ if (request.key === void 0) return false;
689
+ return (request.matchKey ?? exactKeyMatch)(rule.slice(colon + 1), request.key, kind);
690
+ }
691
+ var PermissionPolicy = class {
692
+ defaultMode;
693
+ allow;
694
+ deny;
695
+ asker;
696
+ constructor(config = {}) {
697
+ this.defaultMode = config.default ?? "ask";
698
+ this.allow = new Set(config.allow ?? []);
699
+ this.deny = new Set(config.deny ?? []);
700
+ this.asker = config.asker;
701
+ }
702
+ /** Whether any rule in `set` matches the request, evaluated as the given kind. */
703
+ matches(set, request, kind) {
704
+ for (const rule of set) if (ruleMatches(rule, request, kind)) return true;
705
+ return false;
706
+ }
707
+ /**
708
+ * The static decision for a request, before any prompt. `deny` wins over `allow`. A
709
+ * permissive *default* (`allow`, e.g. `--yes`) does **not** cover a `dangerous` tool:
710
+ * it downgrades to `ask` so a blanket approval can't silently grant `bash` arbitrary
711
+ * command execution (AFM-64). An explicit allow rule still grants it.
712
+ */
713
+ decide(request) {
714
+ if (this.matches(this.deny, request, "deny")) return "deny";
715
+ if (this.matches(this.allow, request, "allow")) return "allow";
716
+ if (this.defaultMode === "allow" && request.dangerous === true) return "ask";
717
+ return this.defaultMode;
718
+ }
719
+ /** Remember an "always" approval for this call (process lifetime). */
720
+ remember(request) {
721
+ this.allow.add(request.key !== void 0 ? `${request.tool}:${request.key}` : request.tool);
722
+ }
723
+ /**
724
+ * Decide whether a call may proceed, prompting on `ask` and remembering an
725
+ * "always". Resolves `true` to run the tool, `false` to refuse it (the dispatcher
726
+ * feeds a refusal back to the model as a tool result). Never throws — an asker that
727
+ * rejects is treated as a denial.
728
+ */
729
+ async authorize(request) {
730
+ const mode = this.decide(request);
731
+ if (mode === "allow") return true;
732
+ if (mode === "deny") return false;
733
+ if (this.asker === void 0) return false;
734
+ let outcome;
735
+ try {
736
+ outcome = await this.asker(request);
737
+ } catch {
738
+ return false;
739
+ }
740
+ if (outcome === "always") {
741
+ this.remember(request);
742
+ return true;
743
+ }
744
+ return outcome === "once";
745
+ }
746
+ };
747
+
748
+ // src/tools/index.ts
749
+ var BUILTIN_TOOLS = { read: readTool, bash: bashTool };
750
+ function toolGuidancePrompt(registry) {
751
+ const hints = registry.usageHints();
752
+ if (hints.length === 0) return "";
753
+ 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:";
754
+ return [intro, ...hints.map((hint) => `- ${hint}`)].join("\n");
755
+ }
756
+ function registryFromNames(names) {
757
+ const registry = new ToolRegistry();
758
+ for (const name of names) {
759
+ const tool = BUILTIN_TOOLS[name];
760
+ if (tool === void 0) {
761
+ throw new Error(`unknown built-in tool "${name}" (available: ${Object.keys(BUILTIN_TOOLS).join(", ")})`);
762
+ }
763
+ registry.register(tool);
764
+ }
765
+ return registry;
766
+ }
767
+
768
+ // src/liveSession.ts
282
769
  var DEFAULT_TURN_TIMEOUT_MS = 12e4;
283
770
  var LiveSession = class {
284
771
  command;
285
772
  timeoutMs;
286
773
  options;
774
+ tools;
775
+ permission;
287
776
  /** Whether we'd spawn the bundled macOS helper (subject to the platform gate). */
288
777
  bundled;
289
778
  child;
@@ -294,19 +783,36 @@ var LiveSession = class {
294
783
  this.command = resolveHelperPath(config);
295
784
  this.timeoutMs = config.timeoutMs ?? DEFAULT_TURN_TIMEOUT_MS;
296
785
  this.options = config.options;
786
+ this.tools = config.tools !== void 0 && config.tools.size > 0 ? config.tools : void 0;
787
+ this.permission = config.permission ?? (this.tools !== void 0 ? new PermissionPolicy() : void 0);
297
788
  this.bundled = usingBundledHelper(config);
298
789
  }
299
- /** Recreate the underlying session with new instructions + seed turns. */
790
+ /**
791
+ * Recreate the underlying session with new instructions + seed turns. Tool
792
+ * definitions ride on `reset` because the framework binds tools at session
793
+ * construction (not per turn); the helper builds the session's tools here.
794
+ */
300
795
  async reset(system, seed = []) {
301
- await this.dispatch({ type: "reset", system, seed }, void 0);
302
- }
303
- /** Send one user turn; prior turns stay in context. Streams via `onDelta`. */
304
- send(text, onDelta) {
305
- return this.dispatch(
306
- { prompt: text, options: this.options, stream: onDelta !== void 0 },
307
- onDelta
796
+ await this.dispatch(
797
+ {
798
+ type: "reset",
799
+ system,
800
+ seed,
801
+ // Only attach tools when some are registered, so resets stay byte-identical
802
+ // to the no-tools path otherwise.
803
+ ...this.tools !== void 0 ? { tools: this.tools.definitions() } : {}
804
+ },
805
+ void 0
308
806
  );
309
807
  }
808
+ /**
809
+ * Send one user turn; prior turns stay in context. Streams via `onDelta`. An
810
+ * optional `signal` interrupts the turn: on abort a `cancel` command is sent and
811
+ * the helper ends the turn with the partial text generated so far (FR-15).
812
+ */
813
+ send(text, onDelta, signal) {
814
+ return this.dispatch({ prompt: text, options: this.options, stream: onDelta !== void 0 }, onDelta, signal);
815
+ }
310
816
  /** Tear down the helper process and reject any in-flight commands. */
311
817
  close() {
312
818
  const child = this.child;
@@ -324,7 +830,7 @@ var LiveSession = class {
324
830
  ensureChild() {
325
831
  const existing = this.child;
326
832
  if (existing !== void 0 && existing.exitCode === null && !existing.killed) return existing;
327
- const child = spawn2(this.command, ["--session"], { stdio: ["pipe", "pipe", "pipe"] });
833
+ const child = spawn3(this.command, ["--session"], { stdio: ["pipe", "pipe", "pipe"] });
328
834
  this.buffer = "";
329
835
  child.stdout.setEncoding("utf8");
330
836
  child.stdout.on("data", (chunk) => {
@@ -366,6 +872,9 @@ var LiveSession = class {
366
872
  pending.onDelta?.(event.text);
367
873
  }
368
874
  break;
875
+ case "tool_call":
876
+ void this.handleToolCall(id, pending, event);
877
+ break;
369
878
  case "ready":
370
879
  this.settle(id, "");
371
880
  break;
@@ -379,6 +888,32 @@ var LiveSession = class {
379
888
  break;
380
889
  }
381
890
  }
891
+ /**
892
+ * Dispatch a `tool_call` to the registered tool and write the outcome back to the
893
+ * helper, keyed by `callId`. Runs concurrently with the still-open turn; the tool
894
+ * policy lives in {@link dispatchToolCall} (`src/tools/dispatch.ts`) — this wires it
895
+ * to the session's child process and the pending turn's timeout.
896
+ */
897
+ handleToolCall(id, pending, event) {
898
+ return dispatchToolCall(event, {
899
+ tools: this.tools,
900
+ permission: this.permission,
901
+ send: (command) => {
902
+ this.child?.stdin.write(JSON.stringify(command) + "\n");
903
+ },
904
+ // Hold the turn open while the tool (and any permission prompt) runs.
905
+ keepAlive: () => {
906
+ this.restartTimer(id, pending);
907
+ }
908
+ });
909
+ }
910
+ /** Restart a pending turn's timeout (e.g. across a tool call). */
911
+ restartTimer(id, pending) {
912
+ clearTimeout(pending.timer);
913
+ pending.timer = setTimeout(() => {
914
+ this.fail(id, `live session timed out after ${String(this.timeoutMs)}ms`);
915
+ }, this.timeoutMs);
916
+ }
382
917
  settle(id, content) {
383
918
  const pending = this.pending.get(id);
384
919
  if (pending === void 0) return;
@@ -393,19 +928,36 @@ var LiveSession = class {
393
928
  this.pending.delete(id);
394
929
  pending.reject(new Error(message));
395
930
  }
396
- dispatch(command, onDelta) {
931
+ dispatch(command, onDelta, signal) {
397
932
  if (this.bundled && !isPlatformSupported()) return Promise.reject(unsupportedPlatformError());
398
933
  const child = this.ensureChild();
399
934
  const id = String(this.nextId++);
400
- return new Promise((resolve, reject) => {
935
+ return new Promise((resolve2, reject) => {
401
936
  const timer = setTimeout(() => {
402
937
  this.pending.delete(id);
403
938
  reject(new Error(`live session timed out after ${String(this.timeoutMs)}ms`));
404
939
  }, this.timeoutMs);
405
- this.pending.set(id, { resolve, reject, onDelta, acc: "", timer });
940
+ this.pending.set(id, { resolve: resolve2, reject, onDelta, acc: "", timer });
941
+ if (signal !== void 0) {
942
+ if (signal.aborted) this.cancel(id);
943
+ else {
944
+ signal.addEventListener(
945
+ "abort",
946
+ () => {
947
+ this.cancel(id);
948
+ },
949
+ { once: true }
950
+ );
951
+ }
952
+ }
406
953
  child.stdin.write(JSON.stringify({ ...command, id }) + "\n");
407
954
  });
408
955
  }
956
+ /** Ask the helper to cancel an in-flight turn (no-op if it already settled). */
957
+ cancel(id) {
958
+ if (!this.pending.has(id)) return;
959
+ this.child?.stdin.write(JSON.stringify({ type: "cancel", id }) + "\n");
960
+ }
409
961
  };
410
962
 
411
963
  // src/session.ts
@@ -430,7 +982,12 @@ var ChatSession = class {
430
982
  this.system = config.system ?? "";
431
983
  this.compactAtTokens = config.compactAtTokens ?? DEFAULT_COMPACT_AT;
432
984
  this.keepRecentTurns = config.keepRecentTurns ?? DEFAULT_KEEP_RECENT;
433
- this.backend = config.backend ?? new LiveSession({ ...config.helper, options: config.options });
985
+ this.backend = config.backend ?? new LiveSession({
986
+ ...config.helper,
987
+ options: config.options,
988
+ tools: config.tools,
989
+ permission: config.permission
990
+ });
434
991
  this.generateFn = config.generateFn ?? defaultGenerateFn(config.helper, config.options);
435
992
  }
436
993
  /** The system prompt actually sent to the model (instructions + any recap). */
@@ -450,24 +1007,31 @@ ${recap}` : recap;
450
1007
  shouldCompact() {
451
1008
  return estimateConversationTokens(this.effectiveSystem(), this.messages) > this.compactAtTokens;
452
1009
  }
453
- /** Send a user turn and return the assistant's reply (streamed via `onDelta`). */
454
- async send(text, onDelta) {
1010
+ /**
1011
+ * Send a user turn and return the assistant's reply (streamed via `onDelta`). An
1012
+ * optional `signal` interrupts the turn (FR-15, esc-to-interrupt): on abort the
1013
+ * reply resolves with the partial text generated so far, and both the user prompt
1014
+ * and that partial reply are kept in history (so a follow-up turn stays coherent).
1015
+ */
1016
+ async send(text, onDelta, signal) {
455
1017
  if (this.shouldCompact()) await this.compact();
456
1018
  await this.ensureStarted();
457
1019
  this.messages.push({ role: "user", content: text });
458
1020
  let reply;
459
1021
  try {
460
- reply = await this.backend.send(text, onDelta);
1022
+ reply = await this.backend.send(text, onDelta, signal);
461
1023
  } catch (error) {
462
- if (!recoverable(error)) {
1024
+ const overflow = isContextOverflow(error);
1025
+ if (!recoverable(error) && !overflow) {
463
1026
  this.messages.pop();
464
1027
  throw error;
465
1028
  }
466
1029
  this.messages.pop();
1030
+ if (overflow) await this.compact();
467
1031
  this.backendInstructions = void 0;
468
1032
  await this.ensureStarted();
469
1033
  this.messages.push({ role: "user", content: text });
470
- reply = await this.backend.send(text, onDelta);
1034
+ reply = await this.backend.send(text, onDelta, signal);
471
1035
  }
472
1036
  this.messages.push({ role: "assistant", content: reply });
473
1037
  return reply;
@@ -514,6 +1078,9 @@ ${this.summary}` : "",
514
1078
  function recoverable(error) {
515
1079
  return error instanceof Error && error.message.includes("[sessionClosed]");
516
1080
  }
1081
+ function isContextOverflow(error) {
1082
+ return error instanceof Error && error.message.includes("[contextWindowExceeded]");
1083
+ }
517
1084
 
518
1085
  // src/repl.ts
519
1086
  var HELP = `Commands:
@@ -521,16 +1088,53 @@ var HELP = `Commands:
521
1088
  /system <text> Replace the system instructions and reset
522
1089
  /clear Clear the conversation context (keep system instructions)
523
1090
  /compact Compact the conversation context now
1091
+ /tools List the tools the model may call
524
1092
  /help Show this help
525
- /quit Quit (alias /exit, or Ctrl-D)`;
1093
+ /quit Quit (alias /exit, or Ctrl-D)
1094
+
1095
+ Press Esc while the model is replying to interrupt it (keeps the partial reply).`;
1096
+ function readlineAsker(rl) {
1097
+ return (request) => new Promise((resolve2) => {
1098
+ rl.question(`
1099
+ Run ${sanitizeForPrompt(request.description)}? [y/N/a(lways)] `, (answer) => {
1100
+ const a = answer.trim().toLowerCase();
1101
+ if (a === "a" || a === "always") resolve2("always");
1102
+ else resolve2(a === "y" || a === "yes" ? "once" : "deny");
1103
+ });
1104
+ });
1105
+ }
526
1106
  async function runRepl(opts) {
1107
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1108
+ const asker = process.stdin.isTTY ? readlineAsker(rl) : void 0;
1109
+ const permission = opts.tools !== void 0 ? new PermissionPolicy({
1110
+ default: opts.yes === true ? "allow" : "ask",
1111
+ allow: opts.allowTools,
1112
+ deny: opts.denyTools,
1113
+ asker
1114
+ }) : void 0;
1115
+ const guidance = opts.tools !== void 0 ? toolGuidancePrompt(opts.tools) : "";
1116
+ const withGuidance = (userSystem) => {
1117
+ if (guidance.length === 0) return userSystem;
1118
+ return userSystem !== void 0 && userSystem.length > 0 ? `${userSystem}
1119
+
1120
+ ${guidance}` : guidance;
1121
+ };
527
1122
  const session = new ChatSession({
528
- system: opts.system,
1123
+ system: withGuidance(opts.system),
529
1124
  options: opts.options,
530
- compactAtTokens: opts.compactAtTokens
1125
+ compactAtTokens: opts.compactAtTokens,
1126
+ tools: opts.tools,
1127
+ permission
531
1128
  });
532
- const rl = createInterface({ input: process.stdin, output: process.stdout });
533
1129
  process.stdout.write("apple-fm chat \u2014 Ctrl-D or /quit to quit, /help for commands.\n");
1130
+ let active;
1131
+ const onKeypress = (_str, key) => {
1132
+ if (key?.name === "escape") active?.abort();
1133
+ };
1134
+ if (process.stdin.isTTY) {
1135
+ emitKeypressEvents(process.stdin, rl);
1136
+ process.stdin.on("keypress", onKeypress);
1137
+ }
534
1138
  rl.setPrompt("> ");
535
1139
  rl.prompt();
536
1140
  for await (const line of rl) {
@@ -563,28 +1167,50 @@ async function runRepl(opts) {
563
1167
  rl.prompt();
564
1168
  continue;
565
1169
  }
1170
+ if (text === "/tools") {
1171
+ const names = opts.tools?.names() ?? [];
1172
+ process.stdout.write(names.length > 0 ? `tools: ${names.join(", ")}
1173
+ ` : "(no tools enabled)\n");
1174
+ rl.prompt();
1175
+ continue;
1176
+ }
566
1177
  if (text === "/reset" || text.startsWith("/reset ")) {
567
- session.reset(text.slice("/reset".length).trim() || void 0);
1178
+ const arg = text.slice("/reset".length).trim();
1179
+ session.reset(arg.length > 0 ? withGuidance(arg) : void 0);
568
1180
  process.stdout.write("(reset)\n");
569
1181
  rl.prompt();
570
1182
  continue;
571
1183
  }
572
1184
  if (text.startsWith("/system ")) {
573
- session.reset(text.slice("/system ".length).trim());
1185
+ session.reset(withGuidance(text.slice("/system ".length).trim()));
574
1186
  process.stdout.write("(system updated, conversation reset)\n");
575
1187
  rl.prompt();
576
1188
  continue;
577
1189
  }
1190
+ const controller = new AbortController();
1191
+ active = controller;
578
1192
  try {
579
- const reply = await session.send(text, opts.stream ? (chunk) => process.stdout.write(chunk) : void 0);
580
- if (!opts.stream) process.stdout.write(reply);
581
- process.stdout.write("\n");
1193
+ const reply = await session.send(
1194
+ text,
1195
+ opts.stream ? (chunk) => process.stdout.write(chunk) : void 0,
1196
+ controller.signal
1197
+ );
1198
+ if (controller.signal.aborted) {
1199
+ process.stdout.write("\n(interrupted)\n");
1200
+ } else {
1201
+ if (!opts.stream) process.stdout.write(reply);
1202
+ if (reply.trim().length === 0) process.stdout.write("(no response)");
1203
+ process.stdout.write("\n");
1204
+ }
582
1205
  } catch (error) {
583
1206
  process.stdout.write(`error: ${error instanceof Error ? error.message : String(error)}
584
1207
  `);
1208
+ } finally {
1209
+ active = void 0;
585
1210
  }
586
1211
  rl.prompt();
587
1212
  }
1213
+ if (process.stdin.isTTY) process.stdin.off("keypress", onKeypress);
588
1214
  rl.close();
589
1215
  session.close();
590
1216
  }
@@ -640,7 +1266,16 @@ async function main() {
640
1266
  return;
641
1267
  }
642
1268
  case "chat": {
643
- await runRepl({ system: args.system, stream: args.stream, compactAtTokens: args.compactAtTokens });
1269
+ const tools = args.tools !== void 0 ? registryFromNames(args.tools) : void 0;
1270
+ await runRepl({
1271
+ system: args.system,
1272
+ stream: args.stream,
1273
+ compactAtTokens: args.compactAtTokens,
1274
+ tools,
1275
+ allowTools: args.allowTools,
1276
+ denyTools: args.denyTools,
1277
+ yes: args.yes
1278
+ });
644
1279
  return;
645
1280
  }
646
1281
  }