apple-fm 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -2,155 +2,52 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { readFileSync } from "fs";
5
- import { readFile } from "fs/promises";
5
+ import { readFile as readFile2 } from "fs/promises";
6
6
 
7
- // src/cliArgs.ts
8
- var USAGE = `apple-fm \u2014 command-line access to Apple's on-device Foundation Models
9
-
10
- Usage:
11
- apple-fm probe Check on-device model availability
12
- apple-fm generate [prompt] [flags] One-shot generation (reads stdin if no prompt)
13
- apple-fm chat [flags] Interactive chat (streaming, auto-compaction)
14
-
15
- Generate flags:
16
- -s, --system <text> System instructions
17
- --schema <file> JSON Schema file for guided/structured output
18
- --stream Stream output as it is produced
19
- --temp <n> Sampling temperature
20
- --max-tokens <n> Maximum response tokens
7
+ // src/chatFile.ts
8
+ import { link, mkdtemp, readFile, rm, writeFile } from "fs/promises";
9
+ import { dirname as dirname2, join as join2, resolve as resolve2 } from "path";
21
10
 
22
- Chat flags:
23
- -s, --system <text> System instructions
24
- --no-stream Disable token streaming
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
34
-
35
- Global:
36
- -h, --help Show this help
37
- -v, --version Show version
11
+ // src/helper.ts
12
+ import { spawn } from "child_process";
13
+ import { fileURLToPath } from "url";
38
14
 
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.`;
42
- function parseNumber(flag, value) {
43
- if (value === void 0) throw new Error(`${flag} requires a value`);
44
- const n = Number(value);
45
- if (Number.isNaN(n)) throw new Error(`${flag} expects a number, got "${value}"`);
46
- return n;
47
- }
48
- function takeValue(argv, i, flag) {
49
- const value = argv[i + 1];
50
- if (value === void 0) throw new Error(`${flag} requires a value`);
51
- return value;
52
- }
53
- function parseArgs(argv) {
54
- const first = argv[0];
55
- if (first === void 0 || first === "-h" || first === "--help") return { command: "help" };
56
- if (first === "-v" || first === "--version") return { command: "version" };
57
- switch (first) {
58
- case "probe":
59
- return { command: "probe" };
60
- case "generate":
61
- return parseGenerate(argv.slice(1));
62
- case "chat":
63
- return parseChat(argv.slice(1));
64
- default:
65
- throw new Error(`unknown command "${first}" (try: probe, generate, chat, --help)`);
15
+ // src/protocol.ts
16
+ var MAX_HELPER_FRAME_BYTES = 4 * 1024 * 1024;
17
+ var MAX_HELPER_STDERR_CHARS = 4096;
18
+ function assertHelperFrameSize(frame) {
19
+ if (Buffer.byteLength(frame) > MAX_HELPER_FRAME_BYTES) {
20
+ throw new Error("[protocolError] helper frame exceeds 4 MiB");
66
21
  }
67
22
  }
68
- function parseGenerate(argv) {
69
- const result = { command: "generate", stream: false };
70
- for (let i = 0; i < argv.length; i++) {
71
- const arg = argv[i];
72
- if (arg === void 0) continue;
73
- switch (arg) {
74
- case "-s":
75
- case "--system":
76
- result.system = takeValue(argv, i++, arg);
77
- break;
78
- case "--schema":
79
- result.schemaFile = takeValue(argv, i++, arg);
80
- break;
81
- case "--stream":
82
- result.stream = true;
83
- break;
84
- case "--temp":
85
- result.temperature = parseNumber(arg, takeValue(argv, i++, arg));
86
- break;
87
- case "--max-tokens":
88
- result.maxTokens = parseNumber(arg, takeValue(argv, i++, arg));
89
- break;
90
- default:
91
- if (arg.startsWith("-")) throw new Error(`unknown flag "${arg}"`);
92
- if (result.prompt !== void 0) throw new Error("generate accepts a single prompt argument");
93
- result.prompt = arg;
94
- }
95
- }
96
- return result;
23
+ function helperDiagnostic(value) {
24
+ return value.slice(0, MAX_HELPER_STDERR_CHARS).replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "").replace(/[\p{Cc}\p{Cf}]+/gu, " ").trim();
97
25
  }
98
- function parseChat(argv) {
99
- const result = { command: "chat", stream: true };
100
- for (let i = 0; i < argv.length; i++) {
101
- const arg = argv[i];
102
- if (arg === void 0) continue;
103
- switch (arg) {
104
- case "-s":
105
- case "--system":
106
- result.system = takeValue(argv, i++, arg);
107
- break;
108
- case "--no-stream":
109
- result.stream = false;
110
- break;
111
- case "--compact-at":
112
- result.compactAtTokens = parseNumber(arg, takeValue(argv, i++, arg));
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;
126
- default:
127
- throw new Error(`unknown flag "${arg}"`);
128
- }
129
- }
130
- return result;
26
+ function helperError(code, message) {
27
+ const label = /^[A-Za-z][A-Za-z0-9]{0,63}$/.test(code) ? code : "protocolError";
28
+ return new Error(`[${label}] ${helperDiagnostic(message)}`);
131
29
  }
132
- function parseList(value) {
133
- return value.split(",").map((name) => name.trim()).filter((name) => name.length > 0);
30
+ function parseWireJson(line, label) {
31
+ try {
32
+ return JSON.parse(line);
33
+ } catch {
34
+ throw new Error(`malformed ${label} JSON`);
35
+ }
134
36
  }
135
-
136
- // src/helper.ts
137
- import { spawn } from "child_process";
138
- import { fileURLToPath } from "url";
139
-
140
- // src/protocol.ts
141
37
  function encodeRequest(request) {
142
38
  return JSON.stringify(request) + "\n";
143
39
  }
144
- function splitLines(buffer) {
40
+ function splitLines(buffer, bounded = false) {
145
41
  const parts = buffer.split("\n");
42
+ if (bounded) for (const part of parts) assertHelperFrameSize(part);
146
43
  const rest = parts.pop() ?? "";
147
44
  const lines = parts.filter((line) => line.trim().length > 0);
148
45
  return { lines, rest };
149
46
  }
150
47
  function parseEvent(line) {
151
- const value = JSON.parse(line);
48
+ const value = parseWireJson(line, "helper event");
152
49
  if (typeof value !== "object" || value === null || !("type" in value)) {
153
- throw new Error(`malformed helper event: ${line}`);
50
+ throw new Error("malformed helper event");
154
51
  }
155
52
  const event = value;
156
53
  switch (event.type) {
@@ -169,7 +66,7 @@ function parseEvent(line) {
169
66
  default:
170
67
  break;
171
68
  }
172
- throw new Error(`malformed helper event: ${line}`);
69
+ throw new Error("malformed helper event");
173
70
  }
174
71
  var UNAVAILABLE_REASONS = [
175
72
  "deviceNotEligible",
@@ -179,19 +76,46 @@ var UNAVAILABLE_REASONS = [
179
76
  "unknown"
180
77
  ];
181
78
  function parseProbeResult(line) {
182
- const value = JSON.parse(line);
79
+ const value = parseWireJson(line, "probe result");
183
80
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
184
- throw new Error(`malformed probe result: ${line}`);
81
+ throw new Error("malformed probe result");
185
82
  }
186
83
  const record = value;
187
84
  if (typeof record.available !== "boolean") {
188
- throw new Error(`malformed probe result (available must be a boolean): ${line}`);
85
+ throw new Error("malformed probe result (available must be a boolean)");
189
86
  }
190
- if (record.available) return { available: true };
87
+ const models = record.models === void 0 ? {} : { models: parseModels(record.models) };
88
+ const contextSize = parseContextSize(record.contextSize);
89
+ const context = contextSize === void 0 ? {} : { contextSize };
90
+ if (record.available) return { available: true, ...models, ...context };
191
91
  if (typeof record.reason !== "string" || !UNAVAILABLE_REASONS.includes(record.reason)) {
192
- throw new Error(`malformed probe result (missing/unknown reason): ${line}`);
92
+ throw new Error("malformed probe result (missing/unknown reason)");
93
+ }
94
+ return { available: false, reason: record.reason, ...models, ...context };
95
+ }
96
+ function parseContextSize(value) {
97
+ return value === void 0 || value === 0 ? void 0 : parseTokenCount(value);
98
+ }
99
+ function parseTokenCount(value) {
100
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
101
+ throw new Error("malformed helper token count");
193
102
  }
194
- return { available: false, reason: record.reason };
103
+ return value;
104
+ }
105
+ function parseTokenCountResult(content) {
106
+ return parseTokenCount(parseWireJson(content, "helper token count"));
107
+ }
108
+ function parseModels(value) {
109
+ if (!Array.isArray(value)) throw new Error("malformed probe result (models must be an array)");
110
+ return value.map((entry) => {
111
+ if (typeof entry === "object" && entry !== null && "id" in entry && typeof entry.id === "string" && "available" in entry) {
112
+ if (entry.available === true) return { id: entry.id, available: true };
113
+ if (entry.available === false && "reason" in entry && typeof entry.reason === "string") {
114
+ return { id: entry.id, available: false, reason: entry.reason };
115
+ }
116
+ }
117
+ throw new Error("malformed probe result (invalid model availability)");
118
+ });
195
119
  }
196
120
  function flattenMessages(messages) {
197
121
  return messages.map((message) => `${message.role === "assistant" ? "Assistant" : "User"}: ${message.content}`).join("\n\n");
@@ -228,9 +152,10 @@ function resolveHelperPath(options = {}) {
228
152
  return fileURLToPath(new URL("../bin/apple-fm-helper", import.meta.url));
229
153
  }
230
154
  function runHelper(args, options, input, onLine) {
155
+ if (input !== void 0) assertHelperFrameSize(input.slice(0, -1));
231
156
  const command = resolveHelperPath(options);
232
157
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
233
- return new Promise((resolve2, reject) => {
158
+ return new Promise((resolve3, reject) => {
234
159
  const child = spawn(command, args, { stdio: ["pipe", "pipe", "pipe"] });
235
160
  let stdout = "";
236
161
  let stderr = "";
@@ -246,7 +171,7 @@ function runHelper(args, options, input, onLine) {
246
171
  settled = true;
247
172
  clearTimeout(timer);
248
173
  if (error) reject(error);
249
- else resolve2();
174
+ else resolve3();
250
175
  };
251
176
  child.on("error", (error) => {
252
177
  finish(new Error(`failed to run apple-fm helper (${command}): ${error.message}`));
@@ -263,19 +188,26 @@ function runHelper(args, options, input, onLine) {
263
188
  };
264
189
  child.stdout.setEncoding("utf8");
265
190
  child.stdout.on("data", (chunk) => {
266
- stdout += chunk;
267
- const { lines, rest } = splitLines(stdout);
268
- stdout = rest;
269
- for (const line of lines) if (!deliver(line)) return;
191
+ if (settled) return;
192
+ try {
193
+ const { lines, rest } = splitLines(stdout + chunk, true);
194
+ stdout = rest;
195
+ for (const line of lines) if (!deliver(line)) return;
196
+ } catch (error) {
197
+ child.kill("SIGKILL");
198
+ finish(error instanceof Error ? error : new Error(String(error)));
199
+ }
270
200
  });
271
201
  child.stderr.setEncoding("utf8");
272
- child.stderr.on("data", (chunk) => stderr += chunk);
202
+ child.stderr.on("data", (chunk) => {
203
+ stderr += chunk.slice(0, MAX_HELPER_STDERR_CHARS - stderr.length);
204
+ });
273
205
  child.on("close", (code) => {
274
206
  if (settled) return;
275
207
  const trailing = stdout.trim();
276
208
  if (trailing.length > 0 && !deliver(trailing)) return;
277
209
  if (code === 0) finish();
278
- else finish(new Error(`apple-fm helper exited with code ${String(code)}: ${stderr.trim()}`));
210
+ else finish(new Error(`apple-fm helper exited with code ${String(code)}: ${helperDiagnostic(stderr)}`));
279
211
  });
280
212
  if (input !== void 0) {
281
213
  child.stdin.on("error", () => void 0);
@@ -291,15 +223,58 @@ async function probe(options = {}) {
291
223
  }
292
224
  let result;
293
225
  await runHelper(["--probe"], options, void 0, (line) => {
226
+ if (result !== void 0) throw new Error("[protocolError] helper produced duplicate probe results");
294
227
  result = parseProbeResult(line);
295
228
  });
296
229
  if (result === void 0) throw new Error("apple-fm helper --probe produced no result");
230
+ if (result.models !== void 0) result.models = result.models.filter((entry) => entry.id === "on-device");
297
231
  return result;
298
232
  }
233
+ function assertSupportedModel(model) {
234
+ if (model !== void 0 && model !== "on-device") {
235
+ throw new Error(`unknown model "${model}" (run apple-fm probe)`);
236
+ }
237
+ }
238
+ async function countTokens(prompt, options = {}) {
239
+ if (usingBundledHelper(options) && !isPlatformSupported()) throw unsupportedPlatformError();
240
+ let count;
241
+ await runHelper(["--tokens"], options, encodeRequest({ prompt }), (line) => {
242
+ const event = parseEvent(line);
243
+ if (count !== void 0) throw new Error("[protocolError] helper sent an event after the token count result");
244
+ if (event.type === "error") throw helperError(event.code, event.message);
245
+ if (event.type === "result") count = parseTokenCountResult(event.content);
246
+ });
247
+ if (count === void 0) throw new Error("apple-fm helper --tokens produced no result");
248
+ return count;
249
+ }
299
250
  async function generate(request, options = {}, onDelta, onSnapshot) {
300
251
  if (usingBundledHelper(options) && !isPlatformSupported()) throw unsupportedPlatformError();
301
252
  let content;
302
- await runHelper(["--generate"], options, encodeRequest(request), (line) => {
253
+ const { model, useCase, imagePath, imagePaths, ...rest } = request;
254
+ const wireRequest = rest;
255
+ assertSupportedModel(model);
256
+ const tagging = useCase === "content-tagging";
257
+ if (useCase !== void 0 && useCase !== "general" && !tagging) {
258
+ throw new Error("unknown use case (choose general or content-tagging)");
259
+ }
260
+ if (tagging && (request.stream === true || request.schema !== void 0)) {
261
+ throw new Error("content-tagging cannot be combined with streaming or a custom schema");
262
+ }
263
+ if (imagePath !== void 0 && imagePaths !== void 0) throw new Error("provide either imagePath or imagePaths");
264
+ if (imagePaths?.length === 0) throw new Error("imagePaths requires at least one local image path");
265
+ const paths = imagePaths ?? (imagePath === void 0 ? [] : [imagePath]);
266
+ if (tagging && paths.length > 0) throw new Error("image input requires the general use case");
267
+ let mode = tagging ? "--tag-content" : "--generate";
268
+ const [first] = paths;
269
+ if (paths.length > 1) {
270
+ mode = "--generate-images";
271
+ wireRequest.imagePaths = paths;
272
+ } else if (first !== void 0) {
273
+ mode = "--generate-image";
274
+ wireRequest.imagePath = first;
275
+ }
276
+ await runHelper([mode], options, encodeRequest(wireRequest), (line) => {
277
+ if (content !== void 0) throw new Error("[protocolError] helper sent an event after the generation result");
303
278
  const event = parseEvent(line);
304
279
  switch (event.type) {
305
280
  case "delta":
@@ -312,62 +287,258 @@ async function generate(request, options = {}, onDelta, onSnapshot) {
312
287
  content = event.content;
313
288
  break;
314
289
  case "error":
315
- throw new Error(`[${event.code}] ${event.message}`);
290
+ throw helperError(event.code, event.message);
316
291
  }
317
292
  });
318
- if (content === void 0) throw new Error("apple-fm helper --generate produced no result");
293
+ if (content === void 0) throw new Error(`apple-fm helper ${mode} produced no result`);
319
294
  return content;
320
295
  }
321
296
 
322
- // src/repl.ts
323
- import { createInterface, emitKeypressEvents } from "readline";
324
-
325
297
  // src/liveSession.ts
326
298
  import { spawn as spawn3 } from "child_process";
327
299
 
300
+ // src/tools/output.ts
301
+ var MAX_TOOL_OUTPUT_CHARS = 3e3;
302
+ function capOutput(text, max = MAX_TOOL_OUTPUT_CHARS) {
303
+ if (text.length <= max) return text;
304
+ return `${text.slice(0, max)}
305
+ \u2026(${String(text.length - max)} more chars truncated)`;
306
+ }
307
+
308
+ // src/tools/permissions.ts
309
+ var MAX_PROMPT_DESCRIPTION = 200;
310
+ function sanitizeForPrompt(text) {
311
+ const stripped = text.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "").replace(/[\p{Cc}\p{Cf}]+/gu, " ").trim();
312
+ if (stripped.length <= MAX_PROMPT_DESCRIPTION) return stripped;
313
+ return `${stripped.slice(0, MAX_PROMPT_DESCRIPTION)}\u2026 (${String(stripped.length - MAX_PROMPT_DESCRIPTION)} more chars)`;
314
+ }
315
+ var exactKeyMatch = (ruleKey, callKey) => ruleKey === callKey;
316
+ function ruleMatches(rule, request, kind) {
317
+ const colon = rule.indexOf(":");
318
+ if (colon < 0) return rule === request.tool;
319
+ if (rule.slice(0, colon) !== request.tool) return false;
320
+ if (request.key === void 0) return false;
321
+ return (request.matchKey ?? exactKeyMatch)(rule.slice(colon + 1), request.key, kind);
322
+ }
323
+ var PermissionPolicy = class {
324
+ defaultMode;
325
+ allow;
326
+ deny;
327
+ asker;
328
+ constructor(config = {}) {
329
+ this.defaultMode = config.default ?? "ask";
330
+ this.allow = new Set(config.allow ?? []);
331
+ this.deny = new Set(config.deny ?? []);
332
+ this.asker = config.asker;
333
+ }
334
+ /** Whether any rule in `set` matches the request, evaluated as the given kind. */
335
+ matches(set, request, kind) {
336
+ for (const rule of set) if (ruleMatches(rule, request, kind)) return true;
337
+ return false;
338
+ }
339
+ /**
340
+ * The static decision for a request, before any prompt. `deny` wins over `allow`. A
341
+ * permissive *default* (`allow`, e.g. `--yes`) does **not** cover a `dangerous` tool:
342
+ * it downgrades to `ask` so a blanket approval can't silently grant `bash` arbitrary
343
+ * command execution (AFM-64). An explicit allow rule still grants it.
344
+ */
345
+ decide(request) {
346
+ if (this.matches(this.deny, request, "deny")) return "deny";
347
+ if (this.matches(this.allow, request, "allow")) return "allow";
348
+ if (this.defaultMode === "allow" && request.dangerous === true) return "ask";
349
+ return this.defaultMode;
350
+ }
351
+ /** Remember an "always" approval for this call (process lifetime). */
352
+ remember(request) {
353
+ this.allow.add(request.key !== void 0 ? `${request.tool}:${request.key}` : request.tool);
354
+ }
355
+ /**
356
+ * Decide whether a call may proceed, prompting on `ask` and remembering an
357
+ * "always". Resolves `true` to run the tool, `false` to refuse it (the dispatcher
358
+ * feeds a refusal back to the model as a tool result). A rejected asker is treated
359
+ * as a denial. The dispatcher also fails closed if a tool's rule resolver throws.
360
+ */
361
+ async authorize(request, isCurrent) {
362
+ if (isCurrent?.() === false) return false;
363
+ let effective = request;
364
+ if (request.resolveRuleKeys !== void 0) {
365
+ const prefix = `${request.tool}:`;
366
+ const keys = [...new Set([...this.allow, ...this.deny].filter((rule) => rule.startsWith(prefix)).map((rule) => rule.slice(prefix.length)))];
367
+ if (keys.length > 0) {
368
+ const resolved = await request.resolveRuleKeys(keys);
369
+ const resolvedKeys = new Map(keys.map((key, index) => [key, resolved[index] ?? key]));
370
+ const compare = request.matchKey ?? exactKeyMatch;
371
+ effective = { ...request, matchKey: (rule, call, kind) => compare(resolvedKeys.get(rule) ?? rule, call, kind) };
372
+ }
373
+ }
374
+ if (isCurrent?.() === false) return false;
375
+ const mode = this.decide(effective);
376
+ if (mode === "allow") return true;
377
+ if (mode === "deny") return false;
378
+ if (this.asker === void 0) return false;
379
+ let outcome;
380
+ try {
381
+ outcome = await this.asker(request);
382
+ } catch {
383
+ return false;
384
+ }
385
+ if (isCurrent?.() === false) return false;
386
+ if (outcome === "always") {
387
+ this.remember(request);
388
+ return true;
389
+ }
390
+ return outcome === "once";
391
+ }
392
+ };
393
+
394
+ // src/tools/registry.ts
395
+ function toolPermissionRequest(tool, args) {
396
+ return {
397
+ tool: tool.name,
398
+ key: tool.permissionKey?.(args),
399
+ description: tool.describe?.(args) ?? `${tool.name} ${JSON.stringify(args)}`,
400
+ matchKey: tool.matchKey?.bind(tool),
401
+ dangerous: tool.dangerous,
402
+ args
403
+ };
404
+ }
405
+ var ToolRegistry = class _ToolRegistry {
406
+ tools = /* @__PURE__ */ new Map();
407
+ constructor(tools = []) {
408
+ for (const tool of tools) this.register(tool);
409
+ }
410
+ /** Register (or replace) a tool by name. */
411
+ register(tool) {
412
+ this.tools.set(tool.name, tool);
413
+ }
414
+ /** Look up the implementation for one call. */
415
+ get(name) {
416
+ return this.tools.get(name);
417
+ }
418
+ /** Copy the wire definitions, permission hooks, and implementations for a live session. */
419
+ snapshot() {
420
+ return new _ToolRegistry([...this.tools.values()].map((tool) => ({
421
+ name: tool.name,
422
+ description: tool.description,
423
+ parameters: structuredClone(tool.parameters),
424
+ run: tool.run.bind(tool),
425
+ prepare: tool.prepare?.bind(tool),
426
+ permissionKey: tool.permissionKey?.bind(tool),
427
+ describe: tool.describe?.bind(tool),
428
+ matchKey: tool.matchKey?.bind(tool),
429
+ dangerous: tool.dangerous,
430
+ usageHint: tool.usageHint
431
+ })));
432
+ }
433
+ /** Whether a tool with this name is registered. */
434
+ has(name) {
435
+ return this.tools.has(name);
436
+ }
437
+ /** Number of registered tools (0 ⇒ no `tools[]` is sent on a turn). */
438
+ get size() {
439
+ return this.tools.size;
440
+ }
441
+ /** The model-facing definitions sent to the helper on a turn command. */
442
+ definitions() {
443
+ return [...this.tools.values()].map(({ name, description, parameters }) => ({
444
+ name,
445
+ description,
446
+ parameters
447
+ }));
448
+ }
449
+ /** The registered tool names (for the REPL `/tools` listing). */
450
+ names() {
451
+ return [...this.tools.keys()];
452
+ }
453
+ /** One usage hint per tool (its `usageHint`, or a `name: description` fallback). */
454
+ usageHints() {
455
+ return [...this.tools.values()].map((tool) => tool.usageHint ?? `${tool.name}: ${tool.description}`);
456
+ }
457
+ /**
458
+ * Build a {@link PermissionRequest} for a call, using the tool's optional
459
+ * `permissionKey` / `describe` hooks. Returns `undefined` for an unknown tool.
460
+ */
461
+ permissionRequest(name, args) {
462
+ const tool = this.tools.get(name);
463
+ if (tool === void 0) return void 0;
464
+ return toolPermissionRequest(tool, args);
465
+ }
466
+ /**
467
+ * Run a tool by name. Throws (with a clear message) if no such tool is
468
+ * registered, so the dispatcher can surface a `tool_error` to the model.
469
+ */
470
+ async run(name, args, ctx = {}) {
471
+ const tool = this.tools.get(name);
472
+ if (tool === void 0) throw new Error(`unknown tool: ${name}`);
473
+ return tool.run(args, ctx);
474
+ }
475
+ };
476
+
328
477
  // src/tools/dispatch.ts
329
478
  async function dispatchToolCall(event, deps) {
330
479
  const callId = typeof event.callId === "string" ? event.callId : void 0;
331
480
  const name = typeof event.name === "string" ? event.name : void 0;
332
481
  const args = typeof event.arguments === "object" && event.arguments !== null ? event.arguments : {};
333
- if (callId === void 0 || name === void 0) return;
334
- deps.keepAlive();
482
+ if (callId === void 0 || name === void 0 || deps.isCurrent?.() === false) return;
483
+ let action = name;
484
+ const report2 = (status) => {
485
+ if (deps.onActivity === void 0 || deps.isCurrent?.() === false) return;
486
+ try {
487
+ deps.onActivity({ tool: sanitizeForPrompt(name), action: sanitizeForPrompt(action), status });
488
+ } catch {
489
+ }
490
+ };
335
491
  const reply = (command) => {
336
- deps.keepAlive();
492
+ if (deps.isCurrent?.() === false) return;
337
493
  deps.send({ ...command, callId });
338
494
  };
339
- const registry = deps.tools;
340
- if (registry === void 0 || !registry.has(name)) {
341
- reply({ type: "tool_result", content: `Unknown tool "${name}".` });
495
+ const tool = deps.tools?.get(name);
496
+ if (tool === void 0) {
497
+ report2("failed");
498
+ reply({ type: "tool_result", content: capOutput(`Unknown tool "${name}".`) });
342
499
  return;
343
500
  }
344
- if (deps.permission !== void 0) {
345
- const request = registry.permissionRequest(name, args);
346
- const allowed = request !== void 0 && await deps.permission.authorize(request);
501
+ const context = { signal: deps.signal };
502
+ let prepared;
503
+ try {
504
+ if (tool.prepare !== void 0) prepared = await tool.prepare(args, context);
505
+ } catch (error) {
506
+ report2("failed");
507
+ reply({ type: "tool_result", content: capOutput(`The "${name}" tool failed: ${error instanceof Error ? error.message : String(error)}`) });
508
+ return;
509
+ }
510
+ if (deps.isCurrent?.() === false) return;
511
+ if (deps.permission !== void 0 || deps.onActivity !== void 0) {
512
+ let allowed;
513
+ try {
514
+ const request = prepared?.request ?? toolPermissionRequest(tool, args);
515
+ action = request.description;
516
+ report2("requested");
517
+ request.signal = deps.signal;
518
+ allowed = deps.permission === void 0 || await deps.permission.authorize(request, deps.isCurrent);
519
+ } catch {
520
+ report2("failed");
521
+ reply({ type: "tool_result", content: "The tool could not be authorized." });
522
+ return;
523
+ }
524
+ if (deps.isCurrent?.() === false) return;
347
525
  if (!allowed) {
348
- reply({ type: "tool_result", content: `Permission to use the "${name}" tool was denied by the user.` });
526
+ report2("denied");
527
+ reply({ type: "tool_result", content: capOutput(`Permission to use the "${name}" tool was denied by the user.`) });
349
528
  return;
350
529
  }
351
530
  }
352
531
  try {
353
- reply({ type: "tool_result", content: await registry.run(name, args) });
532
+ reply({ type: "tool_result", content: await (prepared?.run() ?? tool.run(args, context)) });
533
+ report2("completed");
354
534
  } catch (error) {
355
- reply({ type: "tool_result", content: `The "${name}" tool failed: ${error instanceof Error ? error.message : String(error)}` });
535
+ report2("failed");
536
+ reply({ type: "tool_result", content: capOutput(`The "${name}" tool failed: ${error instanceof Error ? error.message : String(error)}`) });
356
537
  }
357
538
  }
358
539
 
359
540
  // src/tools/builtin/bash.ts
360
541
  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
542
  var DEFAULT_TIMEOUT_MS2 = 3e4;
372
543
  var MAX_CAPTURE_CHARS = 256 * 1024;
373
544
  var PIPE_DRAIN_GRACE_MS = 100;
@@ -397,7 +568,7 @@ function scopedEnv() {
397
568
  function runShellCommand(command, options = {}) {
398
569
  if (command.trim().length === 0) return Promise.reject(new Error('bash: "command" (string) is required'));
399
570
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
400
- return new Promise((resolve2) => {
571
+ return new Promise((resolve3) => {
401
572
  const child = spawn2("/bin/sh", ["-c", command], {
402
573
  stdio: ["ignore", "pipe", "pipe"],
403
574
  detached: true,
@@ -439,7 +610,7 @@ function runShellCommand(command, options = {}) {
439
610
  child.stdout.destroy();
440
611
  child.stderr.destroy();
441
612
  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 }));
613
+ resolve3(report({ stdout, stderr, status }));
443
614
  };
444
615
  child.stdout.setEncoding("utf8");
445
616
  child.stderr.setEncoding("utf8");
@@ -450,7 +621,7 @@ function runShellCommand(command, options = {}) {
450
621
  settled = true;
451
622
  clearTimeout(timer);
452
623
  if (graceTimer !== void 0) clearTimeout(graceTimer);
453
- resolve2(report({ stdout, stderr, status: `failed to start: ${error.message}` }));
624
+ resolve3(report({ stdout, stderr, status: `failed to start: ${error.message}` }));
454
625
  });
455
626
  child.on("exit", (code, signal) => {
456
627
  exitCode = code;
@@ -501,9 +672,29 @@ var bashTool = {
501
672
  };
502
673
 
503
674
  // src/tools/builtin/read.ts
675
+ import { execFile } from "child_process";
676
+ import { fileURLToPath as fileURLToPath2 } from "url";
677
+
678
+ // src/tools/builtin/readPaths.ts
504
679
  import { realpathSync } from "fs";
505
- import { open, stat } from "fs/promises";
506
680
  import { basename, dirname, join, resolve, sep } from "path";
681
+ function canonicalPath(path) {
682
+ const absolute = resolve(path);
683
+ try {
684
+ return realpathSync(absolute);
685
+ } catch {
686
+ try {
687
+ return join(realpathSync(dirname(absolute)), basename(absolute));
688
+ } catch {
689
+ return absolute;
690
+ }
691
+ }
692
+ }
693
+ function containsPath(rule, file) {
694
+ return file === rule || file.startsWith(rule.endsWith(sep) ? rule : rule + sep);
695
+ }
696
+
697
+ // src/tools/builtin/read.ts
507
698
  function intArg(value) {
508
699
  return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
509
700
  }
@@ -526,50 +717,72 @@ function withTimeout(promise, ms, label) {
526
717
  );
527
718
  });
528
719
  }
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
- }
720
+ function runWorker(request, timeoutMs, label, signal) {
721
+ const source = import.meta.url.endsWith(".ts");
722
+ const entry = fileURLToPath2(new URL(source ? "./read-worker.ts" : "./read-worker.js", import.meta.url));
723
+ const args = [...source ? ["--import", "tsx"] : [], entry, "--apple-fm-read-worker", JSON.stringify(request)];
724
+ let child;
725
+ const work = new Promise((resolve3, reject) => {
726
+ child = execFile(
727
+ process.execPath,
728
+ args,
729
+ { signal, killSignal: "SIGKILL", maxBuffer: 1024 * 1024 },
730
+ (error, stdout) => {
731
+ if (error !== null) {
732
+ reject(new Error("read: isolated filesystem operation failed"));
733
+ return;
734
+ }
735
+ try {
736
+ const result = JSON.parse(stdout);
737
+ if (result.value === void 0) throw new Error(result.error ?? "read: invalid filesystem response");
738
+ resolve3(result.value);
739
+ } catch (failure) {
740
+ reject(failure instanceof Error ? failure : new Error(String(failure)));
741
+ }
742
+ }
743
+ );
744
+ });
745
+ return withTimeout(work, timeoutMs, label).finally(() => {
746
+ if (child === void 0 || child.exitCode !== null || child.signalCode !== null) return;
747
+ child.kill("SIGKILL");
748
+ child.stdout?.destroy();
749
+ child.stderr?.destroy();
750
+ child.unref();
751
+ });
550
752
  }
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"));
753
+ function readSnapshot(snapshot, range, options, signal) {
754
+ if ("error" in snapshot) return Promise.reject(new Error(snapshot.error));
755
+ return runWorker({
756
+ kind: "read",
757
+ identity: snapshot.identity,
758
+ maxBytes: options.maxBytes ?? READ_MAX_BYTES,
759
+ ...range
760
+ }, options.timeoutMs ?? READ_TIMEOUT_MS, snapshot.path, signal);
561
761
  }
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
- }
762
+ async function prepareRead(args, context) {
763
+ const path = typeof args.path === "string" ? args.path : "";
764
+ const request = { tool: "read", key: path.length > 0 ? path : void 0, description: `read ${path || "(no path)"}`, args };
765
+ if (path.length === 0) {
766
+ return { request, run: () => Promise.reject(new Error('read: "path" (string) is required')) };
572
767
  }
768
+ if (/^https?:\/\//i.test(path)) {
769
+ return {
770
+ request,
771
+ run: () => Promise.resolve(`"${path}" is a URL, not a local file: the read tool only reads local files; apple-fm cannot fetch URLs.`)
772
+ };
773
+ }
774
+ const snapshot = await runWorker({ kind: "inspect", path }, READ_TIMEOUT_MS, path, context.signal);
775
+ const range = { offset: intArg(args.offset), limit: intArg(args.limit) };
776
+ return {
777
+ request: {
778
+ ...request,
779
+ key: snapshot.path,
780
+ description: `read ${snapshot.path}`,
781
+ matchKey: containsPath,
782
+ resolveRuleKeys: (keys) => runWorker({ kind: "rules", paths: keys }, READ_TIMEOUT_MS, path, context.signal)
783
+ },
784
+ run: () => readSnapshot(snapshot, range, {}, context.signal)
785
+ };
573
786
  }
574
787
  var readTool = {
575
788
  name: "read",
@@ -593,155 +806,13 @@ var readTool = {
593
806
  // symlink inside an approved dir from escaping the grant (AFM-76): `read:/proj`
594
807
  // neither leaks `/proj-secret`, lets `/proj/../.ssh/id_rsa` escape, nor lets
595
808
  // `/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
- },
809
+ matchKey: (ruleKey, callKey) => containsPath(canonicalPath(ruleKey), canonicalPath(callKey)),
810
+ prepare: prepareRead,
601
811
  describe: (args) => `read ${typeof args.path === "string" ? args.path : "(no path)"}`,
602
812
  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";
813
+ async run(args, context) {
814
+ const prepared = await prepareRead(args, context);
815
+ return prepared.run();
745
816
  }
746
817
  };
747
818
 
@@ -773,17 +844,22 @@ var LiveSession = class {
773
844
  options;
774
845
  tools;
775
846
  permission;
847
+ onToolActivity;
776
848
  /** Whether we'd spawn the bundled macOS helper (subject to the platform gate). */
777
849
  bundled;
778
850
  child;
779
851
  buffer = "";
852
+ contextSize;
853
+ transcriptPersistence = false;
780
854
  nextId = 0;
781
855
  pending = /* @__PURE__ */ new Map();
782
856
  constructor(config = {}) {
783
857
  this.command = resolveHelperPath(config);
858
+ assertSupportedModel(config.model);
784
859
  this.timeoutMs = config.timeoutMs ?? DEFAULT_TURN_TIMEOUT_MS;
785
860
  this.options = config.options;
786
- this.tools = config.tools !== void 0 && config.tools.size > 0 ? config.tools : void 0;
861
+ this.tools = config.tools !== void 0 && config.tools.size > 0 ? config.tools.snapshot() : void 0;
862
+ this.onToolActivity = config.onToolActivity;
787
863
  this.permission = config.permission ?? (this.tools !== void 0 ? new PermissionPolicy() : void 0);
788
864
  this.bundled = usingBundledHelper(config);
789
865
  }
@@ -813,46 +889,99 @@ var LiveSession = class {
813
889
  send(text, onDelta, signal) {
814
890
  return this.dispatch({ prompt: text, options: this.options, stream: onDelta !== void 0 }, onDelta, signal);
815
891
  }
892
+ /** Count native tokens for the active session without starting another helper. */
893
+ async tokenBudget(prompt) {
894
+ const contextSize = this.contextSize;
895
+ if (contextSize === void 0 || !this.isActive()) return void 0;
896
+ try {
897
+ const content = await this.dispatch({ type: "count_tokens", prompt }, void 0);
898
+ return { tokens: parseTokenCountResult(content), contextSize };
899
+ } catch {
900
+ return void 0;
901
+ }
902
+ }
903
+ /** Serialize the active native transcript without starting another helper. */
904
+ exportTranscript() {
905
+ this.requireTranscriptPersistence();
906
+ return this.dispatch({ type: "export_transcript" }, void 0);
907
+ }
908
+ /** Whether the current helper can still hold the active session. */
909
+ isActive() {
910
+ const child = this.child;
911
+ return child !== void 0 && child.exitCode === null && child.signalCode === null && !child.killed;
912
+ }
913
+ /** Restore the transcript using the currently configured tools. */
914
+ async importTranscript(transcript) {
915
+ this.requireTranscriptPersistence();
916
+ await this.dispatch({ type: "import_transcript", content: transcript, tools: this.tools?.definitions() }, void 0);
917
+ }
918
+ requireTranscriptPersistence() {
919
+ if (!this.transcriptPersistence || !this.isActive()) {
920
+ throw new Error("native transcript persistence requires a current apple-fm helper");
921
+ }
922
+ }
816
923
  /** Tear down the helper process and reject any in-flight commands. */
817
924
  close() {
818
925
  const child = this.child;
819
- this.child = void 0;
820
- if (child !== void 0) child.kill("SIGKILL");
821
- this.rejectAll(new Error("[sessionClosed] live session closed"));
926
+ if (child !== void 0) this.retireChild(child, new Error("[sessionClosed] live session closed"));
822
927
  }
823
- rejectAll(error) {
824
- for (const pending of this.pending.values()) {
825
- clearTimeout(pending.timer);
826
- pending.reject(error);
928
+ retireChild(child, error, timedOutId) {
929
+ if (this.child !== child) return;
930
+ this.child = void 0;
931
+ this.contextSize = void 0;
932
+ this.transcriptPersistence = false;
933
+ child.kill("SIGKILL");
934
+ for (const [id, pending] of this.pending) {
935
+ if (pending.child !== child) continue;
936
+ const failure = id === timedOutId ? new Error(`live session timed out after ${String(this.timeoutMs)}ms`) : error;
937
+ this.takePending(id)?.reject(failure);
827
938
  }
828
- this.pending.clear();
829
939
  }
830
940
  ensureChild() {
831
941
  const existing = this.child;
832
- if (existing !== void 0 && existing.exitCode === null && !existing.killed) return existing;
942
+ if (existing !== void 0 && this.isActive()) return existing;
943
+ if (existing !== void 0) this.retireChild(existing, new Error("[sessionClosed] live session helper exited"));
833
944
  const child = spawn3(this.command, ["--session"], { stdio: ["pipe", "pipe", "pipe"] });
945
+ let stderr = "";
834
946
  this.buffer = "";
835
947
  child.stdout.setEncoding("utf8");
836
948
  child.stdout.on("data", (chunk) => {
837
- this.onStdout(chunk);
949
+ if (this.child !== child) return;
950
+ try {
951
+ this.onStdout(child, chunk);
952
+ } catch (error) {
953
+ this.retireChild(child, error instanceof Error ? error : new Error(String(error)));
954
+ }
955
+ });
956
+ child.stderr.setEncoding("utf8");
957
+ child.stderr.on("data", (chunk) => {
958
+ stderr += chunk.slice(0, MAX_HELPER_STDERR_CHARS - stderr.length);
838
959
  });
839
960
  child.stdin.on("error", () => void 0);
840
- const onGone = () => {
841
- if (this.child === child) this.child = void 0;
842
- this.rejectAll(new Error("[sessionClosed] live session helper exited"));
961
+ const onGone = (detail) => {
962
+ const diagnostic = helperDiagnostic(detail);
963
+ const message = diagnostic.length > 0 ? `live session helper exited: ${diagnostic}` : "live session helper exited";
964
+ this.retireChild(child, new Error(`[sessionClosed] ${message}`));
843
965
  };
844
- child.on("close", onGone);
845
- child.on("error", onGone);
966
+ child.on("close", () => {
967
+ onGone(stderr);
968
+ });
969
+ child.on("error", (error) => {
970
+ onGone(error.message);
971
+ });
846
972
  this.child = child;
847
973
  return child;
848
974
  }
849
- onStdout(chunk) {
975
+ onStdout(child, chunk) {
850
976
  this.buffer += chunk;
851
- const { lines, rest } = splitLines(this.buffer);
977
+ const { lines, rest } = splitLines(this.buffer, true);
852
978
  this.buffer = rest;
853
- for (const line of lines) this.onLine(line);
979
+ for (const line of lines) {
980
+ if (this.child !== child) return;
981
+ this.onLine(child, line);
982
+ }
854
983
  }
855
- onLine(line) {
984
+ onLine(child, line) {
856
985
  let value;
857
986
  try {
858
987
  value = JSON.parse(line);
@@ -861,28 +990,40 @@ var LiveSession = class {
861
990
  }
862
991
  if (typeof value !== "object" || value === null) return;
863
992
  const event = value;
864
- if (typeof event.id !== "string") return;
993
+ if (typeof event.id !== "string") {
994
+ if (event.type === "error" && typeof event.code === "string" && typeof event.message === "string") {
995
+ this.retireChild(child, helperError(event.code, event.message));
996
+ }
997
+ return;
998
+ }
865
999
  const id = event.id;
866
1000
  const pending = this.pending.get(id);
867
1001
  if (pending === void 0) return;
868
1002
  switch (event.type) {
869
1003
  case "delta":
870
- if (typeof event.text === "string") {
871
- pending.acc += event.text;
872
- pending.onDelta?.(event.text);
873
- }
1004
+ if (typeof event.text !== "string") throw new Error("[protocolError] malformed live delta");
1005
+ pending.onDelta?.(event.text);
874
1006
  break;
875
1007
  case "tool_call":
876
1008
  void this.handleToolCall(id, pending, event);
877
1009
  break;
878
1010
  case "ready":
1011
+ if (pending.replyType !== "ready") throw new Error("[protocolError] unexpected live ready event");
1012
+ this.transcriptPersistence = event.transcriptPersistence === true;
1013
+ this.contextSize = parseContextSize(event.contextSize);
879
1014
  this.settle(id, "");
880
1015
  break;
881
1016
  case "result":
882
- this.settle(id, typeof event.content === "string" ? event.content : pending.acc);
1017
+ if (pending.replyType !== "result" || typeof event.content !== "string") {
1018
+ throw new Error("[protocolError] malformed or unexpected live result");
1019
+ }
1020
+ this.settle(id, event.content);
883
1021
  break;
884
1022
  case "error":
885
- this.fail(id, `[${String(event.code)}] ${String(event.message)}`);
1023
+ if (typeof event.code !== "string" || typeof event.message !== "string") {
1024
+ throw new Error("[protocolError] malformed live error");
1025
+ }
1026
+ this.takePending(id)?.reject(helperError(event.code, event.message));
886
1027
  break;
887
1028
  default:
888
1029
  break;
@@ -892,80 +1033,94 @@ var LiveSession = class {
892
1033
  * Dispatch a `tool_call` to the registered tool and write the outcome back to the
893
1034
  * helper, keyed by `callId`. Runs concurrently with the still-open turn; the tool
894
1035
  * 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.
1036
+ * to the session's child process and the pending turn's lifetime.
896
1037
  */
897
1038
  handleToolCall(id, pending, event) {
1039
+ const isCurrent = () => this.child === pending.child && this.pending.get(id) === pending && pending.toolLifetime?.signal.aborted !== true && pending.child.exitCode === null && pending.child.signalCode === null;
898
1040
  return dispatchToolCall(event, {
899
1041
  tools: this.tools,
900
1042
  permission: this.permission,
1043
+ isCurrent,
1044
+ signal: pending.toolLifetime?.signal,
1045
+ onActivity: this.onToolActivity,
901
1046
  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);
1047
+ if (!isCurrent()) return;
1048
+ const line = JSON.stringify(command);
1049
+ assertHelperFrameSize(line);
1050
+ pending.child.stdin.write(line + "\n");
907
1051
  }
908
1052
  });
909
1053
  }
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
- }
917
- settle(id, content) {
1054
+ takePending(id) {
918
1055
  const pending = this.pending.get(id);
919
- if (pending === void 0) return;
1056
+ if (pending === void 0) return void 0;
920
1057
  clearTimeout(pending.timer);
1058
+ pending.removeAbortListener?.();
921
1059
  this.pending.delete(id);
922
- pending.resolve(content);
1060
+ pending.toolLifetime?.abort();
1061
+ return pending;
923
1062
  }
924
- fail(id, message) {
925
- const pending = this.pending.get(id);
926
- if (pending === void 0) return;
927
- clearTimeout(pending.timer);
928
- this.pending.delete(id);
929
- pending.reject(new Error(message));
1063
+ settle(id, content) {
1064
+ this.takePending(id)?.resolve(content);
930
1065
  }
931
- dispatch(command, onDelta, signal) {
932
- if (this.bundled && !isPlatformSupported()) return Promise.reject(unsupportedPlatformError());
933
- const child = this.ensureChild();
1066
+ async dispatch(command, onDelta, signal) {
1067
+ if (signal?.aborted === true) return "";
1068
+ if (this.bundled && !isPlatformSupported()) throw unsupportedPlatformError();
934
1069
  const id = String(this.nextId++);
935
- return new Promise((resolve2, reject) => {
1070
+ const line = JSON.stringify({ ...command, id });
1071
+ assertHelperFrameSize(line);
1072
+ const child = this.ensureChild();
1073
+ const replyType = command.type === "reset" || command.type === "import_transcript" ? "ready" : "result";
1074
+ return new Promise((resolve3, reject) => {
936
1075
  const timer = setTimeout(() => {
937
- this.pending.delete(id);
938
- reject(new Error(`live session timed out after ${String(this.timeoutMs)}ms`));
1076
+ if (this.child !== child || !this.pending.has(id)) return;
1077
+ this.retireChild(child, new Error("[sessionClosed] live session helper terminated after a command timed out"), id);
939
1078
  }, this.timeoutMs);
940
- this.pending.set(id, { resolve: resolve2, reject, onDelta, acc: "", timer });
1079
+ const toolLifetime = this.tools !== void 0 ? new AbortController() : void 0;
1080
+ const pending = { child, resolve: resolve3, reject, onDelta, replyType, timer, toolLifetime };
1081
+ this.pending.set(id, pending);
1082
+ child.stdin.write(line + "\n");
941
1083
  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
- }
1084
+ const onAbort = () => {
1085
+ if (this.pending.get(id) !== pending) return;
1086
+ child.stdin.write(JSON.stringify({ type: "cancel", id }) + "\n");
1087
+ toolLifetime?.abort();
1088
+ };
1089
+ signal.addEventListener("abort", onAbort, { once: true });
1090
+ pending.removeAbortListener = () => {
1091
+ signal.removeEventListener("abort", onAbort);
1092
+ };
952
1093
  }
953
- child.stdin.write(JSON.stringify({ ...command, id }) + "\n");
954
1094
  });
955
1095
  }
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
- }
961
1096
  };
962
1097
 
963
1098
  // src/session.ts
1099
+ function parseSavedChat(text) {
1100
+ const value = JSON.parse(text);
1101
+ if (typeof value !== "object" || value === null || !("version" in value) || value.version !== 1) {
1102
+ throw new Error("unsupported apple-fm chat file version");
1103
+ }
1104
+ const record = value;
1105
+ const { system, summary, messages, tools, transcript } = record;
1106
+ if (typeof system !== "string" || summary !== void 0 && typeof summary !== "string" || typeof transcript !== "string" || !Array.isArray(tools) || !tools.every((tool) => typeof tool === "string") || !Array.isArray(messages) || !messages.every(isSavedMessage)) {
1107
+ throw new Error("invalid apple-fm chat file");
1108
+ }
1109
+ return { version: 1, system, summary, messages, tools, transcript };
1110
+ }
1111
+ function isSavedMessage(value) {
1112
+ return typeof value === "object" && value !== null && "role" in value && (value.role === "user" || value.role === "assistant") && "content" in value && typeof value.content === "string";
1113
+ }
964
1114
  var DEFAULT_COMPACT_AT = 3e3;
965
1115
  var DEFAULT_KEEP_RECENT = 4;
1116
+ var CONTEXT_COMPACTION_FRACTION = 0.75;
966
1117
  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.";
967
- function defaultGenerateFn(helper, options) {
968
- return (system, messages, onDelta) => generate({ system, messages, options, stream: onDelta !== void 0 }, helper, onDelta);
1118
+ function defaultGenerateFn({ model, helper, options }) {
1119
+ return (system, messages, onDelta) => generate(
1120
+ { model, system, messages, options, stream: onDelta !== void 0 },
1121
+ helper,
1122
+ onDelta
1123
+ );
969
1124
  }
970
1125
  var ChatSession = class {
971
1126
  system;
@@ -973,22 +1128,28 @@ var ChatSession = class {
973
1128
  keepRecentTurns;
974
1129
  backend;
975
1130
  generateFn;
1131
+ toolNames;
976
1132
  messages = [];
977
1133
  /** Recap of turns dropped by compaction; folded into the system prompt. */
978
1134
  summary;
979
1135
  /** Instructions the backend was last `reset` with (`undefined` ⇒ needs reset). */
980
1136
  backendInstructions;
1137
+ operations = Promise.resolve();
1138
+ revision = 0;
981
1139
  constructor(config = {}) {
982
1140
  this.system = config.system ?? "";
1141
+ this.toolNames = config.tools?.names().sort() ?? [];
983
1142
  this.compactAtTokens = config.compactAtTokens ?? DEFAULT_COMPACT_AT;
984
1143
  this.keepRecentTurns = config.keepRecentTurns ?? DEFAULT_KEEP_RECENT;
985
1144
  this.backend = config.backend ?? new LiveSession({
986
1145
  ...config.helper,
1146
+ model: config.model,
987
1147
  options: config.options,
988
1148
  tools: config.tools,
989
- permission: config.permission
1149
+ permission: config.permission,
1150
+ onToolActivity: config.onToolActivity
990
1151
  });
991
- this.generateFn = config.generateFn ?? defaultGenerateFn(config.helper, config.options);
1152
+ this.generateFn = config.generateFn ?? defaultGenerateFn(config);
992
1153
  }
993
1154
  /** The system prompt actually sent to the model (instructions + any recap). */
994
1155
  effectiveSystem() {
@@ -1003,6 +1164,16 @@ ${recap}` : recap;
1003
1164
  history() {
1004
1165
  return this.messages.map((message) => ({ ...message }));
1005
1166
  }
1167
+ /** Report the active context in tokens. A missing capacity indicates an estimate. */
1168
+ usage() {
1169
+ return this.schedule(async (revision) => {
1170
+ await this.ensureStarted(revision);
1171
+ this.assertCurrent(revision);
1172
+ const budget = await this.backend.tokenBudget?.("");
1173
+ this.assertCurrent(revision);
1174
+ return budget ?? { tokens: estimateConversationTokens(this.effectiveSystem(), this.messages) };
1175
+ });
1176
+ }
1006
1177
  /** Whether the next turn would push the transcript past the compaction bound. */
1007
1178
  shouldCompact() {
1008
1179
  return estimateConversationTokens(this.effectiveSystem(), this.messages) > this.compactAtTokens;
@@ -1011,46 +1182,84 @@ ${recap}` : recap;
1011
1182
  * Send a user turn and return the assistant's reply (streamed via `onDelta`). An
1012
1183
  * optional `signal` interrupts the turn (FR-15, esc-to-interrupt): on abort the
1013
1184
  * 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).
1185
+ * and that partial reply are kept in history. Aborting before a turn starts
1186
+ * returns empty text without adding a turn.
1015
1187
  */
1016
- async send(text, onDelta, signal) {
1017
- if (this.shouldCompact()) await this.compact();
1018
- await this.ensureStarted();
1019
- this.messages.push({ role: "user", content: text });
1188
+ send(text, onDelta, signal) {
1189
+ return this.schedule((revision) => this.sendTurn(revision, text, onDelta, signal));
1190
+ }
1191
+ async sendTurn(revision, text, onDelta, signal) {
1192
+ const interrupted = () => signal?.aborted === true;
1193
+ if (interrupted()) return "";
1194
+ const stream = onDelta === void 0 ? void 0 : (chunk) => {
1195
+ if (revision === this.revision) onDelta(chunk);
1196
+ };
1197
+ if (this.messages.length > this.keepRecentTurns) {
1198
+ const budget = this.backendInstructions === this.effectiveSystem() ? await this.backend.tokenBudget?.(text) : void 0;
1199
+ this.assertCurrent(revision);
1200
+ const shouldCompact = budget === void 0 ? this.shouldCompact() : budget.tokens > Math.min(this.compactAtTokens, Math.floor(budget.contextSize * CONTEXT_COMPACTION_FRACTION));
1201
+ if (shouldCompact) await this.compactHistory(revision);
1202
+ }
1203
+ await this.ensureStarted(revision);
1204
+ if (interrupted()) return "";
1020
1205
  let reply;
1021
1206
  try {
1022
- reply = await this.backend.send(text, onDelta, signal);
1207
+ reply = await this.runBackend(revision, () => this.backend.send(text, stream, signal));
1023
1208
  } catch (error) {
1209
+ this.assertCurrent(revision);
1024
1210
  const overflow = isContextOverflow(error);
1025
- if (!recoverable(error) && !overflow) {
1026
- this.messages.pop();
1027
- throw error;
1028
- }
1029
- this.messages.pop();
1030
- if (overflow) await this.compact();
1031
- this.backendInstructions = void 0;
1032
- await this.ensureStarted();
1033
- this.messages.push({ role: "user", content: text });
1034
- reply = await this.backend.send(text, onDelta, signal);
1211
+ if (!recoverable(error) && !overflow) throw error;
1212
+ if (overflow) await this.compactHistory(revision);
1213
+ await this.ensureStarted(revision);
1214
+ if (interrupted()) return "";
1215
+ reply = await this.runBackend(revision, () => this.backend.send(text, stream, signal));
1035
1216
  }
1036
- this.messages.push({ role: "assistant", content: reply });
1217
+ this.assertCurrent(revision);
1218
+ this.messages.push({ role: "user", content: text }, { role: "assistant", content: reply });
1037
1219
  return reply;
1038
1220
  }
1039
1221
  /**
1040
1222
  * Reset the backend's session whenever the effective system prompt changes (the
1041
1223
  * first turn, or after a compaction), seeding it with the transcript so far.
1042
1224
  */
1043
- async ensureStarted() {
1225
+ async ensureStarted(revision) {
1226
+ this.assertCurrent(revision);
1044
1227
  const system = this.effectiveSystem();
1045
- if (this.backendInstructions === system) return;
1046
- await this.backend.reset(system, this.messages);
1228
+ if (this.backendInstructions === system && this.backend.isActive?.() !== false) return;
1229
+ await this.runBackend(revision, () => this.backend.reset(system, this.history()));
1230
+ this.assertCurrent(revision);
1047
1231
  this.backendInstructions = system;
1048
1232
  }
1233
+ async runBackend(revision, operation) {
1234
+ this.assertCurrent(revision);
1235
+ try {
1236
+ return await operation();
1237
+ } catch (error) {
1238
+ this.assertCurrent(revision);
1239
+ this.backendInstructions = void 0;
1240
+ throw error;
1241
+ }
1242
+ }
1243
+ schedule(operation) {
1244
+ const revision = this.revision;
1245
+ const scheduled = this.operations.then(() => {
1246
+ this.assertCurrent(revision);
1247
+ return operation(revision);
1248
+ });
1249
+ this.operations = scheduled.then(() => void 0, () => void 0);
1250
+ return scheduled;
1251
+ }
1252
+ assertCurrent(revision) {
1253
+ if (this.revision !== revision) throw new Error("chat session changed during the operation");
1254
+ }
1049
1255
  /**
1050
1256
  * Fold all but the most recent turns into the rolling summary. Safe to call
1051
1257
  * directly; {@link send} calls it automatically when {@link shouldCompact}.
1052
1258
  */
1053
- async compact() {
1259
+ compact() {
1260
+ return this.schedule((revision) => this.compactHistory(revision));
1261
+ }
1262
+ async compactHistory(revision) {
1054
1263
  if (this.messages.length <= this.keepRecentTurns) return;
1055
1264
  const cutoff = this.messages.length - this.keepRecentTurns;
1056
1265
  const older = this.messages.slice(0, cutoff);
@@ -1060,11 +1269,53 @@ ${recap}` : recap;
1060
1269
  ${this.summary}` : "",
1061
1270
  flattenMessages(older)
1062
1271
  ].filter((part) => part.length > 0).join("\n\n");
1063
- this.summary = (await this.generateFn(SUMMARIZE_SYSTEM, [{ role: "user", content: transcript }])).trim();
1272
+ const summary = await this.generateFn(SUMMARIZE_SYSTEM, [{ role: "user", content: transcript }]);
1273
+ this.assertCurrent(revision);
1274
+ this.summary = summary.trim();
1064
1275
  this.messages = recent;
1276
+ this.backendInstructions = void 0;
1277
+ }
1278
+ /** Capture a versioned snapshot with the native session transcript. */
1279
+ saveTranscript() {
1280
+ return this.schedule(async (revision) => {
1281
+ const exportTranscript = this.backend.exportTranscript?.bind(this.backend);
1282
+ if (exportTranscript === void 0) throw new Error("backend cannot save a native transcript");
1283
+ await this.ensureStarted(revision);
1284
+ const transcript = await this.runBackend(revision, exportTranscript);
1285
+ this.assertCurrent(revision);
1286
+ return {
1287
+ version: 1,
1288
+ system: this.system,
1289
+ summary: this.summary,
1290
+ messages: this.history(),
1291
+ tools: [...this.toolNames],
1292
+ transcript
1293
+ };
1294
+ });
1295
+ }
1296
+ /** Resume a saved chat using this invocation's tool registry and permissions. */
1297
+ resumeTranscript(saved) {
1298
+ const { system, summary, transcript } = saved;
1299
+ const messages = saved.messages.map((message) => ({ ...message }));
1300
+ const tools = [...saved.tools].sort();
1301
+ return this.schedule(async (revision) => {
1302
+ const importTranscript = this.backend.importTranscript?.bind(this.backend);
1303
+ if (importTranscript === void 0) throw new Error("backend cannot resume a native transcript");
1304
+ if (JSON.stringify(this.toolNames) !== JSON.stringify(tools)) {
1305
+ throw new Error("enabled tools do not match the saved chat; use the same --tools list");
1306
+ }
1307
+ await this.ensureStarted(revision);
1308
+ await this.runBackend(revision, () => importTranscript(transcript));
1309
+ this.assertCurrent(revision);
1310
+ this.system = system;
1311
+ this.summary = summary;
1312
+ this.messages = messages;
1313
+ this.backendInstructions = this.effectiveSystem();
1314
+ });
1065
1315
  }
1066
1316
  /** Clear the transcript and summary; optionally replace the system prompt. */
1067
1317
  reset(system) {
1318
+ this.revision += 1;
1068
1319
  if (system !== void 0) this.system = system;
1069
1320
  this.messages = [];
1070
1321
  this.summary = void 0;
@@ -1072,6 +1323,8 @@ ${this.summary}` : "",
1072
1323
  }
1073
1324
  /** Tear down the underlying live session (kills the helper process). */
1074
1325
  close() {
1326
+ this.revision += 1;
1327
+ this.backendInstructions = void 0;
1075
1328
  this.backend.close();
1076
1329
  }
1077
1330
  };
@@ -1082,30 +1335,347 @@ function isContextOverflow(error) {
1082
1335
  return error instanceof Error && error.message.includes("[contextWindowExceeded]");
1083
1336
  }
1084
1337
 
1338
+ // src/chatFile.ts
1339
+ async function writeSavedChat(path, saved) {
1340
+ const destination = resolve2(path);
1341
+ const staging = await mkdtemp(join2(dirname2(destination), ".apple-fm-save-"));
1342
+ try {
1343
+ const file = join2(staging, "session.json");
1344
+ await writeFile(file, `${JSON.stringify(saved)}
1345
+ `, { mode: 384, flag: "wx" });
1346
+ await link(file, destination);
1347
+ } finally {
1348
+ await rm(staging, { recursive: true, force: true });
1349
+ }
1350
+ }
1351
+ async function readSavedChat(path) {
1352
+ return parseSavedChat(await readFile(path, "utf8"));
1353
+ }
1354
+
1355
+ // src/cliArgs.ts
1356
+ var USAGE = `apple-fm \u2014 command-line access to Apple Foundation Models
1357
+
1358
+ Usage:
1359
+ apple-fm probe List models and their availability
1360
+ apple-fm tokens [text] Count prompt tokens (macOS 26.4+, reads stdin if omitted)
1361
+ apple-fm generate [prompt] [flags] One-shot generation (reads stdin if no prompt)
1362
+ apple-fm chat [flags] Interactive chat (streaming, auto-compaction)
1363
+
1364
+ Generate flags:
1365
+ --image <file> Attach a local image to the prompt (repeatable, macOS 27+)
1366
+ --use-case <name> general (default) or content-tagging (JSON array)
1367
+ Content tagging cannot use --stream or --schema
1368
+ --model <id> Model ID from probe (default: on-device)
1369
+ -s, --system <text> System instructions
1370
+ --schema <file> JSON Schema file for guided/structured output
1371
+ --stream Stream output as it is produced
1372
+ --sampling greedy Choose the highest-probability token at each step
1373
+ --temp <n> Sampling temperature from 0 to 2
1374
+ --max-tokens <n> Maximum response tokens (positive integer)
1375
+
1376
+ Chat flags:
1377
+ --resume <file> Resume a saved chat transcript
1378
+ --model <id> Model ID from probe (default: on-device)
1379
+ -s, --system <text> System instructions
1380
+ --no-stream Disable token streaming
1381
+ --compact-at <n> Compact after <n> tokens (non-negative integer)
1382
+ --tools <a,b> Enable built-in tools the model may call (read, bash)
1383
+ --allow-tool <rule> Pre-approve a tool (read, read:/path, or bash:<exact cmd>).
1384
+ A read path grant covers that dir; a bash grant is the
1385
+ EXACT command only. Repeatable
1386
+ --deny-tool <rule> Deny a tool (same syntax; a bash deny is best-effort).
1387
+ Repeatable
1388
+ --yes Auto-approve tool calls \u2014 except bash, which still prompts
1389
+ (add --allow-tool bash to include it). Use with care
1390
+
1391
+ Global:
1392
+ -h, --help Show this help
1393
+ -v, --version Show version
1394
+
1395
+ The helper binary is found via APPLE_FM_BIN (an explicit override, trusted as-is),
1396
+ otherwise the bundled bin/apple-fm-helper shipped with the package. Requires macOS
1397
+ 26+ on Apple Silicon with Apple Intelligence enabled.`;
1398
+ function parseNumber(flag, value) {
1399
+ if (value === void 0) throw new Error(`${flag} requires a value`);
1400
+ const n = Number(value);
1401
+ if (value.trim().length === 0 || !Number.isFinite(n)) {
1402
+ throw new Error(`${flag} expects a number that is finite, got "${value}"`);
1403
+ }
1404
+ return n;
1405
+ }
1406
+ function parseTokenLimit(flag, value, minimum) {
1407
+ const count = parseNumber(flag, value);
1408
+ if (!Number.isSafeInteger(count) || count < minimum) {
1409
+ throw new Error(`${flag} expects a whole number at least ${String(minimum)}`);
1410
+ }
1411
+ return count;
1412
+ }
1413
+ function takeValue(argv, i, flag) {
1414
+ const value = argv[i + 1];
1415
+ if (value === void 0) throw new Error(`${flag} requires a value`);
1416
+ return value;
1417
+ }
1418
+ function parseArgs(argv) {
1419
+ const first = argv[0];
1420
+ if (first === void 0 || first === "-h" || first === "--help") return { command: "help" };
1421
+ if (first === "-v" || first === "--version") return { command: "version" };
1422
+ switch (first) {
1423
+ case "probe":
1424
+ if (argv.length > 1) throw new Error("probe accepts no arguments");
1425
+ return { command: "probe" };
1426
+ case "tokens": {
1427
+ const [, prompt, extra] = argv;
1428
+ if (extra !== void 0) throw new Error("tokens accepts a single text argument");
1429
+ return { command: "tokens", prompt };
1430
+ }
1431
+ case "generate":
1432
+ return parseGenerate(argv.slice(1));
1433
+ case "chat":
1434
+ return parseChat(argv.slice(1));
1435
+ default:
1436
+ throw new Error(`unknown command "${first}" (try: probe, tokens, generate, chat, --help)`);
1437
+ }
1438
+ }
1439
+ function parseModel(value) {
1440
+ if (value === void 0 || value.startsWith("-")) throw new Error("--model requires a value");
1441
+ if (value === "on-device") return value;
1442
+ throw new Error(`unknown model "${value}" (run apple-fm probe)`);
1443
+ }
1444
+ function parseUseCase(value) {
1445
+ if (value === void 0 || value.startsWith("-")) throw new Error("--use-case requires a value");
1446
+ if (value === "general" || value === "content-tagging") return value;
1447
+ throw new Error(`unknown use case "${value}" (choose general or content-tagging)`);
1448
+ }
1449
+ function parseGenerate(argv) {
1450
+ const result = { command: "generate", stream: false };
1451
+ for (let i = 0; i < argv.length; i++) {
1452
+ const arg = argv[i];
1453
+ if (arg === void 0) continue;
1454
+ switch (arg) {
1455
+ case "--image": {
1456
+ const path = takeValue(argv, i++, arg);
1457
+ if (path.length === 0 || path.startsWith("--")) throw new Error("--image requires a file path");
1458
+ (result.imagePaths ??= []).push(path);
1459
+ break;
1460
+ }
1461
+ case "--use-case":
1462
+ result.useCase = parseUseCase(argv[++i]);
1463
+ break;
1464
+ case "--model":
1465
+ result.model = parseModel(argv[++i]);
1466
+ break;
1467
+ case "-s":
1468
+ case "--system":
1469
+ result.system = takeValue(argv, i++, arg);
1470
+ break;
1471
+ case "--schema":
1472
+ result.schemaFile = takeValue(argv, i++, arg);
1473
+ break;
1474
+ case "--stream":
1475
+ result.stream = true;
1476
+ break;
1477
+ case "--sampling": {
1478
+ const sampling = takeValue(argv, i++, arg);
1479
+ if (sampling.startsWith("-")) throw new Error("--sampling requires a value");
1480
+ if (sampling !== "greedy") throw new Error(`unknown sampling mode "${sampling}" (choose greedy)`);
1481
+ result.sampling = sampling;
1482
+ break;
1483
+ }
1484
+ case "--temp": {
1485
+ const temperature = parseNumber(arg, takeValue(argv, i++, arg));
1486
+ if (temperature < 0 || temperature > 2) throw new Error("--temp expects a number from 0 to 2");
1487
+ result.temperature = temperature;
1488
+ break;
1489
+ }
1490
+ case "--max-tokens":
1491
+ result.maxTokens = parseTokenLimit(arg, takeValue(argv, i++, arg), 1);
1492
+ break;
1493
+ default:
1494
+ if (arg.startsWith("-")) throw new Error(`unknown flag "${arg}"`);
1495
+ if (result.prompt !== void 0) throw new Error("generate accepts a single prompt argument");
1496
+ result.prompt = arg;
1497
+ }
1498
+ }
1499
+ if (result.useCase === "content-tagging" && (result.stream || result.schemaFile !== void 0)) {
1500
+ throw new Error("content-tagging cannot be combined with --stream or --schema");
1501
+ }
1502
+ if (result.useCase === "content-tagging" && result.imagePaths !== void 0) {
1503
+ throw new Error("--image requires the general use case");
1504
+ }
1505
+ return result;
1506
+ }
1507
+ function parseChat(argv) {
1508
+ const result = { command: "chat", stream: true };
1509
+ for (let i = 0; i < argv.length; i++) {
1510
+ const arg = argv[i];
1511
+ if (arg === void 0) continue;
1512
+ switch (arg) {
1513
+ case "--resume":
1514
+ result.resumeFile = takeValue(argv, i++, arg);
1515
+ if (result.resumeFile.length === 0 || result.resumeFile.startsWith("--")) {
1516
+ throw new Error("--resume requires a file path");
1517
+ }
1518
+ break;
1519
+ case "--model":
1520
+ result.model = parseModel(argv[++i]);
1521
+ break;
1522
+ case "-s":
1523
+ case "--system":
1524
+ result.system = takeValue(argv, i++, arg);
1525
+ break;
1526
+ case "--no-stream":
1527
+ result.stream = false;
1528
+ break;
1529
+ case "--compact-at":
1530
+ result.compactAtTokens = parseTokenLimit(arg, takeValue(argv, i++, arg), 0);
1531
+ break;
1532
+ case "--tools":
1533
+ result.tools = parseList(takeValue(argv, i++, arg));
1534
+ break;
1535
+ case "--allow-tool":
1536
+ (result.allowTools ??= []).push(takeValue(argv, i++, arg));
1537
+ break;
1538
+ case "--deny-tool":
1539
+ (result.denyTools ??= []).push(takeValue(argv, i++, arg));
1540
+ break;
1541
+ case "--yes":
1542
+ result.yes = true;
1543
+ break;
1544
+ default:
1545
+ throw new Error(`unknown flag "${arg}"`);
1546
+ }
1547
+ }
1548
+ if (result.resumeFile !== void 0 && result.system !== void 0) {
1549
+ throw new Error("--resume already contains system instructions; omit --system");
1550
+ }
1551
+ return result;
1552
+ }
1553
+ function parseList(value) {
1554
+ return value.split(",").map((name) => name.trim()).filter((name) => name.length > 0);
1555
+ }
1556
+
1085
1557
  // src/repl.ts
1558
+ import { createInterface, emitKeypressEvents } from "readline";
1559
+
1560
+ // src/chat/commands.ts
1086
1561
  var HELP = `Commands:
1087
1562
  /reset [system] Start over (optionally set new system instructions)
1088
1563
  /system <text> Replace the system instructions and reset
1089
1564
  /clear Clear the conversation context (keep system instructions)
1090
1565
  /compact Compact the conversation context now
1566
+ /usage Show the current context token count
1567
+ /save <file> Save the native transcript to a new file
1091
1568
  /tools List the tools the model may call
1092
1569
  /help Show this help
1093
1570
  /quit Quit (alias /exit, or Ctrl-D)
1094
1571
 
1095
1572
  Press Esc while the model is replying to interrupt it (keeps the partial reply).`;
1573
+ async function handleChatCommand(text, commands) {
1574
+ const { session, toolNames, withGuidance, write } = commands;
1575
+ const space = text.indexOf(" ");
1576
+ const command = space === -1 ? text : text.slice(0, space);
1577
+ const argument = space === -1 ? void 0 : text.slice(space + 1).trim();
1578
+ try {
1579
+ switch (command) {
1580
+ case "/help":
1581
+ if (argument !== void 0) return false;
1582
+ write(`${HELP}
1583
+ `);
1584
+ break;
1585
+ case "/clear":
1586
+ if (argument !== void 0) return false;
1587
+ session.reset();
1588
+ write("(context cleared)\n");
1589
+ break;
1590
+ case "/usage": {
1591
+ if (argument !== void 0) return false;
1592
+ const { tokens, contextSize } = await session.usage();
1593
+ if (contextSize === void 0) write(`Context: ~${String(tokens)} tokens (estimate)
1594
+ `);
1595
+ else write(`Context: ${String(tokens)} / ${String(contextSize)} tokens (${String(Math.round(tokens / contextSize * 100))}%)
1596
+ `);
1597
+ break;
1598
+ }
1599
+ case "/compact":
1600
+ if (argument !== void 0) return false;
1601
+ await session.compact();
1602
+ write("(compacted)\n");
1603
+ break;
1604
+ case "/save":
1605
+ if (argument === void 0 || argument.length === 0) throw new Error("/save requires a file path");
1606
+ await writeSavedChat(argument, await session.saveTranscript());
1607
+ write("(saved)\n");
1608
+ break;
1609
+ case "/tools":
1610
+ if (argument !== void 0) return false;
1611
+ write(toolNames.length > 0 ? `tools: ${toolNames.join(", ")}
1612
+ ` : "(no tools enabled)\n");
1613
+ break;
1614
+ case "/reset":
1615
+ session.reset(argument !== void 0 && argument.length > 0 ? withGuidance(argument) : void 0);
1616
+ write("(reset)\n");
1617
+ break;
1618
+ case "/system":
1619
+ if (argument === void 0) return false;
1620
+ session.reset(withGuidance(argument));
1621
+ write("(system updated, conversation reset)\n");
1622
+ break;
1623
+ default:
1624
+ return false;
1625
+ }
1626
+ } catch (error) {
1627
+ write(`error: ${error instanceof Error ? error.message : String(error)}
1628
+ `);
1629
+ }
1630
+ return true;
1631
+ }
1632
+
1633
+ // src/repl.ts
1096
1634
  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
- });
1635
+ let tail = Promise.resolve(void 0);
1636
+ let closed = false;
1637
+ let activeQuestion;
1638
+ rl.once("close", () => {
1639
+ closed = true;
1640
+ activeQuestion?.abort();
1104
1641
  });
1642
+ return (request) => {
1643
+ const queued = tail.then(async () => {
1644
+ if (closed || request.signal?.aborted === true) return "deny";
1645
+ const controller = new AbortController();
1646
+ activeQuestion = controller;
1647
+ const cancel = () => {
1648
+ controller.abort();
1649
+ };
1650
+ request.signal?.addEventListener("abort", cancel, { once: true });
1651
+ try {
1652
+ return await new Promise((resolve3) => {
1653
+ controller.signal.addEventListener("abort", () => {
1654
+ resolve3("deny");
1655
+ }, { once: true });
1656
+ const prompt = `
1657
+ Run ${sanitizeForPrompt(request.description)}? [y/N/a(lways)] `;
1658
+ rl.question(prompt, { signal: controller.signal }, (answer) => {
1659
+ const a = answer.trim().toLowerCase();
1660
+ if (a === "a" || a === "always") resolve3("always");
1661
+ else resolve3(a === "y" || a === "yes" ? "once" : "deny");
1662
+ });
1663
+ });
1664
+ } catch {
1665
+ return "deny";
1666
+ } finally {
1667
+ activeQuestion = void 0;
1668
+ request.signal?.removeEventListener("abort", cancel);
1669
+ }
1670
+ });
1671
+ tail = queued;
1672
+ return queued;
1673
+ };
1105
1674
  }
1106
1675
  async function runRepl(opts) {
1107
1676
  const rl = createInterface({ input: process.stdin, output: process.stdout });
1108
- const asker = process.stdin.isTTY ? readlineAsker(rl) : void 0;
1677
+ const interactive = process.stdin.isTTY;
1678
+ const asker = interactive ? readlineAsker(rl) : void 0;
1109
1679
  const permission = opts.tools !== void 0 ? new PermissionPolicy({
1110
1680
  default: opts.yes === true ? "allow" : "ask",
1111
1681
  allow: opts.allowTools,
@@ -1120,73 +1690,71 @@ async function runRepl(opts) {
1120
1690
  ${guidance}` : guidance;
1121
1691
  };
1122
1692
  const session = new ChatSession({
1693
+ model: opts.model,
1123
1694
  system: withGuidance(opts.system),
1124
1695
  options: opts.options,
1125
1696
  compactAtTokens: opts.compactAtTokens,
1126
1697
  tools: opts.tools,
1127
- permission
1698
+ permission,
1699
+ onToolActivity: interactive ? ({ tool, action, status }) => {
1700
+ const message = status === "requested" ? action : `${tool} ${status}`;
1701
+ process.stderr.write(`
1702
+ [tool] ${message}
1703
+ `);
1704
+ } : void 0
1128
1705
  });
1706
+ if (opts.saved !== void 0) {
1707
+ rl.pause();
1708
+ try {
1709
+ await session.resumeTranscript(opts.saved);
1710
+ rl.resume();
1711
+ } catch (error) {
1712
+ session.close();
1713
+ rl.close();
1714
+ throw error;
1715
+ }
1716
+ }
1129
1717
  process.stdout.write("apple-fm chat \u2014 Ctrl-D or /quit to quit, /help for commands.\n");
1130
1718
  let active;
1719
+ const terminal = { closed: false };
1720
+ const terminalClosed = () => terminal.closed;
1721
+ const prompt = () => {
1722
+ if (!terminalClosed()) rl.prompt();
1723
+ };
1131
1724
  const onKeypress = (_str, key) => {
1132
1725
  if (key?.name === "escape") active?.abort();
1133
1726
  };
1134
- if (process.stdin.isTTY) {
1727
+ if (interactive) {
1135
1728
  emitKeypressEvents(process.stdin, rl);
1136
1729
  process.stdin.on("keypress", onKeypress);
1730
+ rl.once("close", () => {
1731
+ terminal.closed = true;
1732
+ active?.abort();
1733
+ });
1137
1734
  }
1138
1735
  rl.setPrompt("> ");
1139
- rl.prompt();
1736
+ prompt();
1737
+ const commands = {
1738
+ session,
1739
+ withGuidance,
1740
+ toolNames: opts.tools?.names() ?? [],
1741
+ write: (text) => {
1742
+ process.stdout.write(text);
1743
+ }
1744
+ };
1140
1745
  for await (const line of rl) {
1746
+ if (terminalClosed()) break;
1141
1747
  const text = line.trim();
1142
1748
  if (text.length === 0) {
1143
- rl.prompt();
1749
+ prompt();
1144
1750
  continue;
1145
1751
  }
1146
1752
  if (text === "/quit" || text === "/exit") break;
1147
- if (text === "/help") {
1148
- process.stdout.write(`${HELP}
1149
- `);
1150
- rl.prompt();
1151
- continue;
1152
- }
1153
- if (text === "/clear") {
1154
- session.reset();
1155
- process.stdout.write("(context cleared)\n");
1156
- rl.prompt();
1157
- continue;
1158
- }
1159
- if (text === "/compact") {
1160
- try {
1161
- await session.compact();
1162
- process.stdout.write("(compacted)\n");
1163
- } catch (error) {
1164
- process.stdout.write(`error: ${error instanceof Error ? error.message : String(error)}
1165
- `);
1166
- }
1167
- rl.prompt();
1168
- continue;
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
- }
1177
- if (text === "/reset" || text.startsWith("/reset ")) {
1178
- const arg = text.slice("/reset".length).trim();
1179
- session.reset(arg.length > 0 ? withGuidance(arg) : void 0);
1180
- process.stdout.write("(reset)\n");
1181
- rl.prompt();
1182
- continue;
1183
- }
1184
- if (text.startsWith("/system ")) {
1185
- session.reset(withGuidance(text.slice("/system ".length).trim()));
1186
- process.stdout.write("(system updated, conversation reset)\n");
1187
- rl.prompt();
1753
+ if (await handleChatCommand(text, commands)) {
1754
+ prompt();
1188
1755
  continue;
1189
1756
  }
1757
+ if (terminalClosed()) break;
1190
1758
  const controller = new AbortController();
1191
1759
  active = controller;
1192
1760
  try {
@@ -1208,9 +1776,9 @@ ${guidance}` : guidance;
1208
1776
  } finally {
1209
1777
  active = void 0;
1210
1778
  }
1211
- rl.prompt();
1779
+ prompt();
1212
1780
  }
1213
- if (process.stdin.isTTY) process.stdin.off("keypress", onKeypress);
1781
+ if (interactive) process.stdin.off("keypress", onKeypress);
1214
1782
  rl.close();
1215
1783
  session.close();
1216
1784
  }
@@ -1248,14 +1816,30 @@ async function main() {
1248
1816
  if (!result.available) process.exitCode = 1;
1249
1817
  return;
1250
1818
  }
1819
+ case "tokens": {
1820
+ const prompt = args.prompt ?? await readStdin();
1821
+ if (prompt.length === 0) throw new Error("tokens: no text given (pass an argument or pipe stdin)");
1822
+ process.stdout.write(`${String(await countTokens(prompt))}
1823
+ `);
1824
+ return;
1825
+ }
1251
1826
  case "generate": {
1252
1827
  const prompt = args.prompt ?? await readStdin();
1253
1828
  if (prompt.length === 0) throw new Error("generate: no prompt given (pass an argument or pipe stdin)");
1254
1829
  const options = {};
1830
+ if (args.sampling !== void 0) options.sampling = args.sampling;
1255
1831
  if (args.temperature !== void 0) options.temperature = args.temperature;
1256
1832
  if (args.maxTokens !== void 0) options.maxTokens = args.maxTokens;
1257
- const request = { prompt, system: args.system, options, stream: args.stream };
1258
- if (args.schemaFile !== void 0) request.schema = JSON.parse(await readFile(args.schemaFile, "utf8"));
1833
+ const request = {
1834
+ model: args.model,
1835
+ useCase: args.useCase,
1836
+ imagePaths: args.imagePaths,
1837
+ prompt,
1838
+ system: args.system,
1839
+ options,
1840
+ stream: args.stream
1841
+ };
1842
+ if (args.schemaFile !== void 0) request.schema = JSON.parse(await readFile2(args.schemaFile, "utf8"));
1259
1843
  const structured = args.schemaFile !== void 0;
1260
1844
  const onDelta = args.stream && !structured ? (chunk) => process.stdout.write(chunk) : void 0;
1261
1845
  const onSnapshot = args.stream && structured && process.stdout.isTTY ? (json) => process.stdout.write(`\r\x1B[2K${json}`) : void 0;
@@ -1267,7 +1851,10 @@ async function main() {
1267
1851
  }
1268
1852
  case "chat": {
1269
1853
  const tools = args.tools !== void 0 ? registryFromNames(args.tools) : void 0;
1854
+ const saved = args.resumeFile === void 0 ? void 0 : await readSavedChat(args.resumeFile);
1270
1855
  await runRepl({
1856
+ saved,
1857
+ model: args.model,
1271
1858
  system: args.system,
1272
1859
  stream: args.stream,
1273
1860
  compactAtTokens: args.compactAtTokens,