apple-fm 1.0.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -2,132 +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)
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";
14
10
 
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
21
-
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
-
27
- Global:
28
- -h, --help Show this help
29
- -v, --version Show version
11
+ // src/helper.ts
12
+ import { spawn } from "child_process";
13
+ import { fileURLToPath } from "url";
30
14
 
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.`;
34
- function parseNumber(flag, value) {
35
- if (value === void 0) throw new Error(`${flag} requires a value`);
36
- const n = Number(value);
37
- if (Number.isNaN(n)) throw new Error(`${flag} expects a number, got "${value}"`);
38
- return n;
39
- }
40
- function takeValue(argv, i, flag) {
41
- const value = argv[i + 1];
42
- if (value === void 0) throw new Error(`${flag} requires a value`);
43
- return value;
44
- }
45
- function parseArgs(argv) {
46
- const first = argv[0];
47
- if (first === void 0 || first === "-h" || first === "--help") return { command: "help" };
48
- if (first === "-v" || first === "--version") return { command: "version" };
49
- switch (first) {
50
- case "probe":
51
- return { command: "probe" };
52
- case "generate":
53
- return parseGenerate(argv.slice(1));
54
- case "chat":
55
- return parseChat(argv.slice(1));
56
- default:
57
- 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");
58
21
  }
59
22
  }
60
- function parseGenerate(argv) {
61
- const result = { command: "generate", stream: false };
62
- for (let i = 0; i < argv.length; i++) {
63
- const arg = argv[i];
64
- if (arg === void 0) continue;
65
- switch (arg) {
66
- case "-s":
67
- case "--system":
68
- result.system = takeValue(argv, i++, arg);
69
- break;
70
- case "--schema":
71
- result.schemaFile = takeValue(argv, i++, arg);
72
- break;
73
- case "--stream":
74
- result.stream = true;
75
- break;
76
- case "--temp":
77
- result.temperature = parseNumber(arg, takeValue(argv, i++, arg));
78
- break;
79
- case "--max-tokens":
80
- result.maxTokens = parseNumber(arg, takeValue(argv, i++, arg));
81
- break;
82
- default:
83
- if (arg.startsWith("-")) throw new Error(`unknown flag "${arg}"`);
84
- if (result.prompt !== void 0) throw new Error("generate accepts a single prompt argument");
85
- result.prompt = arg;
86
- }
87
- }
88
- 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();
89
25
  }
90
- function parseChat(argv) {
91
- const result = { command: "chat", stream: true };
92
- for (let i = 0; i < argv.length; i++) {
93
- const arg = argv[i];
94
- if (arg === void 0) continue;
95
- switch (arg) {
96
- case "-s":
97
- case "--system":
98
- result.system = takeValue(argv, i++, arg);
99
- break;
100
- case "--no-stream":
101
- result.stream = false;
102
- break;
103
- case "--compact-at":
104
- result.compactAtTokens = parseNumber(arg, takeValue(argv, i++, arg));
105
- break;
106
- default:
107
- throw new Error(`unknown flag "${arg}"`);
108
- }
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)}`);
29
+ }
30
+ function parseWireJson(line, label) {
31
+ try {
32
+ return JSON.parse(line);
33
+ } catch {
34
+ throw new Error(`malformed ${label} JSON`);
109
35
  }
110
- return result;
111
36
  }
112
-
113
- // src/helper.ts
114
- import { spawn } from "child_process";
115
- import { fileURLToPath } from "url";
116
-
117
- // src/protocol.ts
118
37
  function encodeRequest(request) {
119
38
  return JSON.stringify(request) + "\n";
120
39
  }
121
- function splitLines(buffer) {
40
+ function splitLines(buffer, bounded = false) {
122
41
  const parts = buffer.split("\n");
42
+ if (bounded) for (const part of parts) assertHelperFrameSize(part);
123
43
  const rest = parts.pop() ?? "";
124
44
  const lines = parts.filter((line) => line.trim().length > 0);
125
45
  return { lines, rest };
126
46
  }
127
47
  function parseEvent(line) {
128
- const value = JSON.parse(line);
48
+ const value = parseWireJson(line, "helper event");
129
49
  if (typeof value !== "object" || value === null || !("type" in value)) {
130
- throw new Error(`malformed helper event: ${line}`);
50
+ throw new Error("malformed helper event");
131
51
  }
132
52
  const event = value;
133
53
  switch (event.type) {
@@ -146,7 +66,56 @@ function parseEvent(line) {
146
66
  default:
147
67
  break;
148
68
  }
149
- throw new Error(`malformed helper event: ${line}`);
69
+ throw new Error("malformed helper event");
70
+ }
71
+ var UNAVAILABLE_REASONS = [
72
+ "deviceNotEligible",
73
+ "appleIntelligenceNotEnabled",
74
+ "modelNotReady",
75
+ "unsupportedPlatform",
76
+ "unknown"
77
+ ];
78
+ function parseProbeResult(line) {
79
+ const value = parseWireJson(line, "probe result");
80
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
81
+ throw new Error("malformed probe result");
82
+ }
83
+ const record = value;
84
+ if (typeof record.available !== "boolean") {
85
+ throw new Error("malformed probe result (available must be a boolean)");
86
+ }
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 };
91
+ if (typeof record.reason !== "string" || !UNAVAILABLE_REASONS.includes(record.reason)) {
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");
102
+ }
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
+ });
150
119
  }
151
120
  function flattenMessages(messages) {
152
121
  return messages.map((message) => `${message.role === "assistant" ? "Assistant" : "User"}: ${message.content}`).join("\n\n");
@@ -183,9 +152,10 @@ function resolveHelperPath(options = {}) {
183
152
  return fileURLToPath(new URL("../bin/apple-fm-helper", import.meta.url));
184
153
  }
185
154
  function runHelper(args, options, input, onLine) {
155
+ if (input !== void 0) assertHelperFrameSize(input.slice(0, -1));
186
156
  const command = resolveHelperPath(options);
187
157
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
188
- return new Promise((resolve, reject) => {
158
+ return new Promise((resolve3, reject) => {
189
159
  const child = spawn(command, args, { stdio: ["pipe", "pipe", "pipe"] });
190
160
  let stdout = "";
191
161
  let stderr = "";
@@ -201,7 +171,7 @@ function runHelper(args, options, input, onLine) {
201
171
  settled = true;
202
172
  clearTimeout(timer);
203
173
  if (error) reject(error);
204
- else resolve();
174
+ else resolve3();
205
175
  };
206
176
  child.on("error", (error) => {
207
177
  finish(new Error(`failed to run apple-fm helper (${command}): ${error.message}`));
@@ -218,19 +188,26 @@ function runHelper(args, options, input, onLine) {
218
188
  };
219
189
  child.stdout.setEncoding("utf8");
220
190
  child.stdout.on("data", (chunk) => {
221
- stdout += chunk;
222
- const { lines, rest } = splitLines(stdout);
223
- stdout = rest;
224
- 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
+ }
225
200
  });
226
201
  child.stderr.setEncoding("utf8");
227
- 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
+ });
228
205
  child.on("close", (code) => {
229
206
  if (settled) return;
230
207
  const trailing = stdout.trim();
231
208
  if (trailing.length > 0 && !deliver(trailing)) return;
232
209
  if (code === 0) finish();
233
- 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)}`));
234
211
  });
235
212
  if (input !== void 0) {
236
213
  child.stdin.on("error", () => void 0);
@@ -246,15 +223,58 @@ async function probe(options = {}) {
246
223
  }
247
224
  let result;
248
225
  await runHelper(["--probe"], options, void 0, (line) => {
249
- result = JSON.parse(line);
226
+ if (result !== void 0) throw new Error("[protocolError] helper produced duplicate probe results");
227
+ result = parseProbeResult(line);
250
228
  });
251
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");
252
231
  return result;
253
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
+ }
254
250
  async function generate(request, options = {}, onDelta, onSnapshot) {
255
251
  if (usingBundledHelper(options) && !isPlatformSupported()) throw unsupportedPlatformError();
256
252
  let content;
257
- 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");
258
278
  const event = parseEvent(line);
259
279
  switch (event.type) {
260
280
  case "delta":
@@ -267,86 +287,701 @@ async function generate(request, options = {}, onDelta, onSnapshot) {
267
287
  content = event.content;
268
288
  break;
269
289
  case "error":
270
- throw new Error(`[${event.code}] ${event.message}`);
290
+ throw helperError(event.code, event.message);
271
291
  }
272
292
  });
273
- 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`);
274
294
  return content;
275
295
  }
276
296
 
277
- // src/repl.ts
278
- import { createInterface } from "readline";
279
-
280
297
  // src/liveSession.ts
298
+ import { spawn as spawn3 } from "child_process";
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
+
477
+ // src/tools/dispatch.ts
478
+ async function dispatchToolCall(event, deps) {
479
+ const callId = typeof event.callId === "string" ? event.callId : void 0;
480
+ const name = typeof event.name === "string" ? event.name : void 0;
481
+ const args = typeof event.arguments === "object" && event.arguments !== null ? event.arguments : {};
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
+ };
491
+ const reply = (command) => {
492
+ if (deps.isCurrent?.() === false) return;
493
+ deps.send({ ...command, callId });
494
+ };
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}".`) });
499
+ return;
500
+ }
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;
525
+ if (!allowed) {
526
+ report2("denied");
527
+ reply({ type: "tool_result", content: capOutput(`Permission to use the "${name}" tool was denied by the user.`) });
528
+ return;
529
+ }
530
+ }
531
+ try {
532
+ reply({ type: "tool_result", content: await (prepared?.run() ?? tool.run(args, context)) });
533
+ report2("completed");
534
+ } catch (error) {
535
+ report2("failed");
536
+ reply({ type: "tool_result", content: capOutput(`The "${name}" tool failed: ${error instanceof Error ? error.message : String(error)}`) });
537
+ }
538
+ }
539
+
540
+ // src/tools/builtin/bash.ts
281
541
  import { spawn as spawn2 } from "child_process";
542
+ var DEFAULT_TIMEOUT_MS2 = 3e4;
543
+ var MAX_CAPTURE_CHARS = 256 * 1024;
544
+ var PIPE_DRAIN_GRACE_MS = 100;
545
+ var SAFE_ENV_KEYS = [
546
+ "PATH",
547
+ "HOME",
548
+ "USER",
549
+ "LOGNAME",
550
+ "SHELL",
551
+ "PWD",
552
+ "TMPDIR",
553
+ "LANG",
554
+ "LANGUAGE",
555
+ "LC_ALL",
556
+ "LC_CTYPE",
557
+ "TERM",
558
+ "TZ"
559
+ ];
560
+ function scopedEnv() {
561
+ const env = {};
562
+ for (const key of SAFE_ENV_KEYS) {
563
+ const value = process.env[key];
564
+ if (value !== void 0) env[key] = value;
565
+ }
566
+ return env;
567
+ }
568
+ function runShellCommand(command, options = {}) {
569
+ if (command.trim().length === 0) return Promise.reject(new Error('bash: "command" (string) is required'));
570
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
571
+ return new Promise((resolve3) => {
572
+ const child = spawn2("/bin/sh", ["-c", command], {
573
+ stdio: ["ignore", "pipe", "pipe"],
574
+ detached: true,
575
+ env: options.inheritEnv === true ? process.env : scopedEnv()
576
+ });
577
+ let stdout = "";
578
+ let stderr = "";
579
+ let timedOut = false;
580
+ let overflowed = false;
581
+ let settled = false;
582
+ let exitCode = null;
583
+ let exitSignal = null;
584
+ let graceTimer;
585
+ const killGroup = () => {
586
+ try {
587
+ if (child.pid !== void 0) process.kill(-child.pid, "SIGKILL");
588
+ else child.kill("SIGKILL");
589
+ } catch {
590
+ child.kill("SIGKILL");
591
+ }
592
+ };
593
+ const timer = setTimeout(() => {
594
+ timedOut = true;
595
+ killGroup();
596
+ }, timeoutMs);
597
+ const append = (buffer, chunk) => {
598
+ if (overflowed) return buffer;
599
+ const remaining = MAX_CAPTURE_CHARS - (stdout.length + stderr.length);
600
+ if (chunk.length <= remaining) return buffer + chunk;
601
+ overflowed = true;
602
+ killGroup();
603
+ return buffer + chunk.slice(0, Math.max(0, remaining));
604
+ };
605
+ const settle = () => {
606
+ if (settled) return;
607
+ settled = true;
608
+ clearTimeout(timer);
609
+ if (graceTimer !== void 0) clearTimeout(graceTimer);
610
+ child.stdout.destroy();
611
+ child.stderr.destroy();
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)}`;
613
+ resolve3(report({ stdout, stderr, status }));
614
+ };
615
+ child.stdout.setEncoding("utf8");
616
+ child.stderr.setEncoding("utf8");
617
+ child.stdout.on("data", (chunk) => stdout = append(stdout, chunk));
618
+ child.stderr.on("data", (chunk) => stderr = append(stderr, chunk));
619
+ child.on("error", (error) => {
620
+ if (settled) return;
621
+ settled = true;
622
+ clearTimeout(timer);
623
+ if (graceTimer !== void 0) clearTimeout(graceTimer);
624
+ resolve3(report({ stdout, stderr, status: `failed to start: ${error.message}` }));
625
+ });
626
+ child.on("exit", (code, signal) => {
627
+ exitCode = code;
628
+ exitSignal = signal;
629
+ killGroup();
630
+ graceTimer = setTimeout(settle, PIPE_DRAIN_GRACE_MS);
631
+ });
632
+ child.on("close", settle);
633
+ });
634
+ }
635
+ function report({ stdout, stderr, status }) {
636
+ const sections = [status];
637
+ if (stdout.length > 0) sections.push(`stdout:
638
+ ${stdout}`);
639
+ if (stderr.length > 0) sections.push(`stderr:
640
+ ${stderr}`);
641
+ return capOutput(sections.join("\n"));
642
+ }
643
+ var bashTool = {
644
+ name: "bash",
645
+ 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.",
646
+ parameters: {
647
+ type: "object",
648
+ description: "Arguments for the bash tool.",
649
+ required: ["command"],
650
+ properties: {
651
+ command: { type: "string", description: "The shell command to run." }
652
+ }
653
+ },
654
+ dangerous: true,
655
+ permissionKey: (args) => typeof args.command === "string" ? args.command : void 0,
656
+ // Allow grants are EXACT — approving `ls` never approves `ls; curl evil` (AFM-63).
657
+ // Deny rules are a broad best-effort token match: the denied token, at a start /
658
+ // whitespace / path boundary, anywhere in the normalized command, so `--deny-tool
659
+ // bash:rm` also catches `/bin/rm` and `command rm` — but this is NOT a security
660
+ // guarantee (`eval`, `$(…)`, aliases evade it); the real control is not enabling
661
+ // bash (AFM-67).
662
+ matchKey: (ruleKey, callKey, kind) => {
663
+ if (kind === "allow") return ruleKey === callKey;
664
+ const token = ruleKey.trim();
665
+ if (token.length === 0) return false;
666
+ const escaped = token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
667
+ return new RegExp(`(^|[\\s/])${escaped}`).test(callKey.trim().replace(/\s+/g, " "));
668
+ },
669
+ describe: (args) => `run: ${typeof args.command === "string" ? args.command : "(no command)"}`,
670
+ usageHint: "bash \u2014 run a shell command; use it to inspect the system or run CLI tools, NOT to read files or fetch URLs.",
671
+ run: (args) => runShellCommand(typeof args.command === "string" ? args.command : "")
672
+ };
673
+
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
679
+ import { realpathSync } from "fs";
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
698
+ function intArg(value) {
699
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
700
+ }
701
+ var READ_MAX_BYTES = 1024 * 1024;
702
+ var READ_TIMEOUT_MS = 1e4;
703
+ function withTimeout(promise, ms, label) {
704
+ return new Promise((res, rej) => {
705
+ const timer = setTimeout(() => {
706
+ rej(new Error(`read: timed out after ${String(ms)}ms reading "${label}"`));
707
+ }, ms);
708
+ promise.then(
709
+ (value) => {
710
+ clearTimeout(timer);
711
+ res(value);
712
+ },
713
+ (error) => {
714
+ clearTimeout(timer);
715
+ rej(error instanceof Error ? error : new Error(String(error)));
716
+ }
717
+ );
718
+ });
719
+ }
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
+ });
752
+ }
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);
761
+ }
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')) };
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
+ };
786
+ }
787
+ var readTool = {
788
+ name: "read",
789
+ 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.',
790
+ parameters: {
791
+ type: "object",
792
+ description: "Arguments for the read tool.",
793
+ required: ["path"],
794
+ properties: {
795
+ path: { type: "string", description: "Filesystem path of the file to read." },
796
+ offset: { type: "integer", minimum: 0, description: "First line to return (0-based)." },
797
+ limit: { type: "integer", minimum: 1, description: "Maximum number of lines to return." }
798
+ }
799
+ },
800
+ // Scope permission rules / "always" grants to the path, so a user can approve a
801
+ // directory once (`read:/Users/me/project`) without allowing every read.
802
+ permissionKey: (args) => typeof args.path === "string" ? args.path : void 0,
803
+ // A path rule covers a file exactly or a directory and everything *inside* it — after
804
+ // resolving `..` AND following symlinks, and only across a real path-separator
805
+ // boundary. Resolving the **real** path (not just the textual one) is what stops a
806
+ // symlink inside an approved dir from escaping the grant (AFM-76): `read:/proj`
807
+ // neither leaks `/proj-secret`, lets `/proj/../.ssh/id_rsa` escape, nor lets
808
+ // `/proj/link → /etc/shadow` read outside the boundary. Same test for allow and deny.
809
+ matchKey: (ruleKey, callKey) => containsPath(canonicalPath(ruleKey), canonicalPath(callKey)),
810
+ prepare: prepareRead,
811
+ describe: (args) => `read ${typeof args.path === "string" ? args.path : "(no path)"}`,
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.",
813
+ async run(args, context) {
814
+ const prepared = await prepareRead(args, context);
815
+ return prepared.run();
816
+ }
817
+ };
818
+
819
+ // src/tools/index.ts
820
+ var BUILTIN_TOOLS = { read: readTool, bash: bashTool };
821
+ function toolGuidancePrompt(registry) {
822
+ const hints = registry.usageHints();
823
+ if (hints.length === 0) return "";
824
+ 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:";
825
+ return [intro, ...hints.map((hint) => `- ${hint}`)].join("\n");
826
+ }
827
+ function registryFromNames(names) {
828
+ const registry = new ToolRegistry();
829
+ for (const name of names) {
830
+ const tool = BUILTIN_TOOLS[name];
831
+ if (tool === void 0) {
832
+ throw new Error(`unknown built-in tool "${name}" (available: ${Object.keys(BUILTIN_TOOLS).join(", ")})`);
833
+ }
834
+ registry.register(tool);
835
+ }
836
+ return registry;
837
+ }
838
+
839
+ // src/liveSession.ts
282
840
  var DEFAULT_TURN_TIMEOUT_MS = 12e4;
283
841
  var LiveSession = class {
284
842
  command;
285
843
  timeoutMs;
286
844
  options;
845
+ tools;
846
+ permission;
847
+ onToolActivity;
287
848
  /** Whether we'd spawn the bundled macOS helper (subject to the platform gate). */
288
849
  bundled;
289
850
  child;
290
851
  buffer = "";
852
+ contextSize;
853
+ transcriptPersistence = false;
291
854
  nextId = 0;
292
855
  pending = /* @__PURE__ */ new Map();
293
856
  constructor(config = {}) {
294
857
  this.command = resolveHelperPath(config);
858
+ assertSupportedModel(config.model);
295
859
  this.timeoutMs = config.timeoutMs ?? DEFAULT_TURN_TIMEOUT_MS;
296
860
  this.options = config.options;
861
+ this.tools = config.tools !== void 0 && config.tools.size > 0 ? config.tools.snapshot() : void 0;
862
+ this.onToolActivity = config.onToolActivity;
863
+ this.permission = config.permission ?? (this.tools !== void 0 ? new PermissionPolicy() : void 0);
297
864
  this.bundled = usingBundledHelper(config);
298
865
  }
299
- /** Recreate the underlying session with new instructions + seed turns. */
300
- async reset(system, seed = []) {
301
- await this.dispatch({ type: "reset", system, seed }, void 0);
866
+ /**
867
+ * Recreate the underlying session with new instructions + seed turns. Tool
868
+ * definitions ride on `reset` because the framework binds tools at session
869
+ * construction (not per turn); the helper builds the session's tools here.
870
+ */
871
+ async reset(system, seed = []) {
872
+ await this.dispatch(
873
+ {
874
+ type: "reset",
875
+ system,
876
+ seed,
877
+ // Only attach tools when some are registered, so resets stay byte-identical
878
+ // to the no-tools path otherwise.
879
+ ...this.tools !== void 0 ? { tools: this.tools.definitions() } : {}
880
+ },
881
+ void 0
882
+ );
883
+ }
884
+ /**
885
+ * Send one user turn; prior turns stay in context. Streams via `onDelta`. An
886
+ * optional `signal` interrupts the turn: on abort a `cancel` command is sent and
887
+ * the helper ends the turn with the partial text generated so far (FR-15).
888
+ */
889
+ send(text, onDelta, signal) {
890
+ return this.dispatch({ prompt: text, options: this.options, stream: onDelta !== void 0 }, onDelta, signal);
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);
302
907
  }
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
308
- );
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
+ }
309
922
  }
310
923
  /** Tear down the helper process and reject any in-flight commands. */
311
924
  close() {
312
925
  const child = this.child;
313
- this.child = void 0;
314
- if (child !== void 0) child.kill("SIGKILL");
315
- this.rejectAll(new Error("[sessionClosed] live session closed"));
926
+ if (child !== void 0) this.retireChild(child, new Error("[sessionClosed] live session closed"));
316
927
  }
317
- rejectAll(error) {
318
- for (const pending of this.pending.values()) {
319
- clearTimeout(pending.timer);
320
- 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);
321
938
  }
322
- this.pending.clear();
323
939
  }
324
940
  ensureChild() {
325
941
  const existing = this.child;
326
- if (existing !== void 0 && existing.exitCode === null && !existing.killed) return existing;
327
- const child = spawn2(this.command, ["--session"], { stdio: ["pipe", "pipe", "pipe"] });
942
+ if (existing !== void 0 && this.isActive()) return existing;
943
+ if (existing !== void 0) this.retireChild(existing, new Error("[sessionClosed] live session helper exited"));
944
+ const child = spawn3(this.command, ["--session"], { stdio: ["pipe", "pipe", "pipe"] });
945
+ let stderr = "";
328
946
  this.buffer = "";
329
947
  child.stdout.setEncoding("utf8");
330
948
  child.stdout.on("data", (chunk) => {
331
- 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);
332
959
  });
333
960
  child.stdin.on("error", () => void 0);
334
- const onGone = () => {
335
- if (this.child === child) this.child = void 0;
336
- 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}`));
337
965
  };
338
- child.on("close", onGone);
339
- child.on("error", onGone);
966
+ child.on("close", () => {
967
+ onGone(stderr);
968
+ });
969
+ child.on("error", (error) => {
970
+ onGone(error.message);
971
+ });
340
972
  this.child = child;
341
973
  return child;
342
974
  }
343
- onStdout(chunk) {
975
+ onStdout(child, chunk) {
344
976
  this.buffer += chunk;
345
- const { lines, rest } = splitLines(this.buffer);
977
+ const { lines, rest } = splitLines(this.buffer, true);
346
978
  this.buffer = rest;
347
- 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
+ }
348
983
  }
349
- onLine(line) {
984
+ onLine(child, line) {
350
985
  let value;
351
986
  try {
352
987
  value = JSON.parse(line);
@@ -355,65 +990,137 @@ var LiveSession = class {
355
990
  }
356
991
  if (typeof value !== "object" || value === null) return;
357
992
  const event = value;
358
- 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
+ }
359
999
  const id = event.id;
360
1000
  const pending = this.pending.get(id);
361
1001
  if (pending === void 0) return;
362
1002
  switch (event.type) {
363
1003
  case "delta":
364
- if (typeof event.text === "string") {
365
- pending.acc += event.text;
366
- pending.onDelta?.(event.text);
367
- }
1004
+ if (typeof event.text !== "string") throw new Error("[protocolError] malformed live delta");
1005
+ pending.onDelta?.(event.text);
1006
+ break;
1007
+ case "tool_call":
1008
+ void this.handleToolCall(id, pending, event);
368
1009
  break;
369
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);
370
1014
  this.settle(id, "");
371
1015
  break;
372
1016
  case "result":
373
- 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);
374
1021
  break;
375
1022
  case "error":
376
- 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));
377
1027
  break;
378
1028
  default:
379
1029
  break;
380
1030
  }
381
1031
  }
382
- settle(id, content) {
383
- const pending = this.pending.get(id);
384
- if (pending === void 0) return;
385
- clearTimeout(pending.timer);
386
- this.pending.delete(id);
387
- pending.resolve(content);
1032
+ /**
1033
+ * Dispatch a `tool_call` to the registered tool and write the outcome back to the
1034
+ * helper, keyed by `callId`. Runs concurrently with the still-open turn; the tool
1035
+ * policy lives in {@link dispatchToolCall} (`src/tools/dispatch.ts`) — this wires it
1036
+ * to the session's child process and the pending turn's lifetime.
1037
+ */
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;
1040
+ return dispatchToolCall(event, {
1041
+ tools: this.tools,
1042
+ permission: this.permission,
1043
+ isCurrent,
1044
+ signal: pending.toolLifetime?.signal,
1045
+ onActivity: this.onToolActivity,
1046
+ send: (command) => {
1047
+ if (!isCurrent()) return;
1048
+ const line = JSON.stringify(command);
1049
+ assertHelperFrameSize(line);
1050
+ pending.child.stdin.write(line + "\n");
1051
+ }
1052
+ });
388
1053
  }
389
- fail(id, message) {
1054
+ takePending(id) {
390
1055
  const pending = this.pending.get(id);
391
- if (pending === void 0) return;
1056
+ if (pending === void 0) return void 0;
392
1057
  clearTimeout(pending.timer);
1058
+ pending.removeAbortListener?.();
393
1059
  this.pending.delete(id);
394
- pending.reject(new Error(message));
1060
+ pending.toolLifetime?.abort();
1061
+ return pending;
395
1062
  }
396
- dispatch(command, onDelta) {
397
- if (this.bundled && !isPlatformSupported()) return Promise.reject(unsupportedPlatformError());
398
- const child = this.ensureChild();
1063
+ settle(id, content) {
1064
+ this.takePending(id)?.resolve(content);
1065
+ }
1066
+ async dispatch(command, onDelta, signal) {
1067
+ if (signal?.aborted === true) return "";
1068
+ if (this.bundled && !isPlatformSupported()) throw unsupportedPlatformError();
399
1069
  const id = String(this.nextId++);
400
- return new Promise((resolve, 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) => {
401
1075
  const timer = setTimeout(() => {
402
- this.pending.delete(id);
403
- 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);
404
1078
  }, this.timeoutMs);
405
- this.pending.set(id, { resolve, reject, onDelta, acc: "", timer });
406
- child.stdin.write(JSON.stringify({ ...command, id }) + "\n");
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");
1083
+ if (signal !== void 0) {
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
+ };
1093
+ }
407
1094
  });
408
1095
  }
409
1096
  };
410
1097
 
411
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
+ }
412
1114
  var DEFAULT_COMPACT_AT = 3e3;
413
1115
  var DEFAULT_KEEP_RECENT = 4;
1116
+ var CONTEXT_COMPACTION_FRACTION = 0.75;
414
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.";
415
- function defaultGenerateFn(helper, options) {
416
- 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
+ );
417
1124
  }
418
1125
  var ChatSession = class {
419
1126
  system;
@@ -421,17 +1128,28 @@ var ChatSession = class {
421
1128
  keepRecentTurns;
422
1129
  backend;
423
1130
  generateFn;
1131
+ toolNames;
424
1132
  messages = [];
425
1133
  /** Recap of turns dropped by compaction; folded into the system prompt. */
426
1134
  summary;
427
1135
  /** Instructions the backend was last `reset` with (`undefined` ⇒ needs reset). */
428
1136
  backendInstructions;
1137
+ operations = Promise.resolve();
1138
+ revision = 0;
429
1139
  constructor(config = {}) {
430
1140
  this.system = config.system ?? "";
1141
+ this.toolNames = config.tools?.names().sort() ?? [];
431
1142
  this.compactAtTokens = config.compactAtTokens ?? DEFAULT_COMPACT_AT;
432
1143
  this.keepRecentTurns = config.keepRecentTurns ?? DEFAULT_KEEP_RECENT;
433
- this.backend = config.backend ?? new LiveSession({ ...config.helper, options: config.options });
434
- this.generateFn = config.generateFn ?? defaultGenerateFn(config.helper, config.options);
1144
+ this.backend = config.backend ?? new LiveSession({
1145
+ ...config.helper,
1146
+ model: config.model,
1147
+ options: config.options,
1148
+ tools: config.tools,
1149
+ permission: config.permission,
1150
+ onToolActivity: config.onToolActivity
1151
+ });
1152
+ this.generateFn = config.generateFn ?? defaultGenerateFn(config);
435
1153
  }
436
1154
  /** The system prompt actually sent to the model (instructions + any recap). */
437
1155
  effectiveSystem() {
@@ -446,47 +1164,102 @@ ${recap}` : recap;
446
1164
  history() {
447
1165
  return this.messages.map((message) => ({ ...message }));
448
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
+ }
449
1177
  /** Whether the next turn would push the transcript past the compaction bound. */
450
1178
  shouldCompact() {
451
1179
  return estimateConversationTokens(this.effectiveSystem(), this.messages) > this.compactAtTokens;
452
1180
  }
453
- /** Send a user turn and return the assistant's reply (streamed via `onDelta`). */
454
- async send(text, onDelta) {
455
- if (this.shouldCompact()) await this.compact();
456
- await this.ensureStarted();
457
- this.messages.push({ role: "user", content: text });
1181
+ /**
1182
+ * Send a user turn and return the assistant's reply (streamed via `onDelta`). An
1183
+ * optional `signal` interrupts the turn (FR-15, esc-to-interrupt): on abort the
1184
+ * reply resolves with the partial text generated so far, and both the user prompt
1185
+ * and that partial reply are kept in history. Aborting before a turn starts
1186
+ * returns empty text without adding a turn.
1187
+ */
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 "";
458
1205
  let reply;
459
1206
  try {
460
- reply = await this.backend.send(text, onDelta);
1207
+ reply = await this.runBackend(revision, () => this.backend.send(text, stream, signal));
461
1208
  } catch (error) {
462
- if (!recoverable(error)) {
463
- this.messages.pop();
464
- throw error;
465
- }
466
- this.messages.pop();
467
- this.backendInstructions = void 0;
468
- await this.ensureStarted();
469
- this.messages.push({ role: "user", content: text });
470
- reply = await this.backend.send(text, onDelta);
1209
+ this.assertCurrent(revision);
1210
+ const overflow = isContextOverflow(error);
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));
471
1216
  }
472
- this.messages.push({ role: "assistant", content: reply });
1217
+ this.assertCurrent(revision);
1218
+ this.messages.push({ role: "user", content: text }, { role: "assistant", content: reply });
473
1219
  return reply;
474
1220
  }
475
1221
  /**
476
1222
  * Reset the backend's session whenever the effective system prompt changes (the
477
1223
  * first turn, or after a compaction), seeding it with the transcript so far.
478
1224
  */
479
- async ensureStarted() {
1225
+ async ensureStarted(revision) {
1226
+ this.assertCurrent(revision);
480
1227
  const system = this.effectiveSystem();
481
- if (this.backendInstructions === system) return;
482
- 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);
483
1231
  this.backendInstructions = system;
484
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
+ }
485
1255
  /**
486
1256
  * Fold all but the most recent turns into the rolling summary. Safe to call
487
1257
  * directly; {@link send} calls it automatically when {@link shouldCompact}.
488
1258
  */
489
- async compact() {
1259
+ compact() {
1260
+ return this.schedule((revision) => this.compactHistory(revision));
1261
+ }
1262
+ async compactHistory(revision) {
490
1263
  if (this.messages.length <= this.keepRecentTurns) return;
491
1264
  const cutoff = this.messages.length - this.keepRecentTurns;
492
1265
  const older = this.messages.slice(0, cutoff);
@@ -496,11 +1269,53 @@ ${recap}` : recap;
496
1269
  ${this.summary}` : "",
497
1270
  flattenMessages(older)
498
1271
  ].filter((part) => part.length > 0).join("\n\n");
499
- 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();
500
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
+ });
501
1315
  }
502
1316
  /** Clear the transcript and summary; optionally replace the system prompt. */
503
1317
  reset(system) {
1318
+ this.revision += 1;
504
1319
  if (system !== void 0) this.system = system;
505
1320
  this.messages = [];
506
1321
  this.summary = void 0;
@@ -508,83 +1323,462 @@ ${this.summary}` : "",
508
1323
  }
509
1324
  /** Tear down the underlying live session (kills the helper process). */
510
1325
  close() {
1326
+ this.revision += 1;
1327
+ this.backendInstructions = void 0;
511
1328
  this.backend.close();
512
1329
  }
513
1330
  };
514
1331
  function recoverable(error) {
515
1332
  return error instanceof Error && error.message.includes("[sessionClosed]");
516
1333
  }
1334
+ function isContextOverflow(error) {
1335
+ return error instanceof Error && error.message.includes("[contextWindowExceeded]");
1336
+ }
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
+ }
517
1556
 
518
1557
  // src/repl.ts
1558
+ import { createInterface, emitKeypressEvents } from "readline";
1559
+
1560
+ // src/chat/commands.ts
519
1561
  var HELP = `Commands:
520
1562
  /reset [system] Start over (optionally set new system instructions)
521
1563
  /system <text> Replace the system instructions and reset
522
1564
  /clear Clear the conversation context (keep system instructions)
523
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
1568
+ /tools List the tools the model may call
524
1569
  /help Show this help
525
- /quit Quit (alias /exit, or Ctrl-D)`;
1570
+ /quit Quit (alias /exit, or Ctrl-D)
1571
+
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
1634
+ function readlineAsker(rl) {
1635
+ let tail = Promise.resolve(void 0);
1636
+ let closed = false;
1637
+ let activeQuestion;
1638
+ rl.once("close", () => {
1639
+ closed = true;
1640
+ activeQuestion?.abort();
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
+ };
1674
+ }
526
1675
  async function runRepl(opts) {
1676
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1677
+ const interactive = process.stdin.isTTY;
1678
+ const asker = interactive ? readlineAsker(rl) : void 0;
1679
+ const permission = opts.tools !== void 0 ? new PermissionPolicy({
1680
+ default: opts.yes === true ? "allow" : "ask",
1681
+ allow: opts.allowTools,
1682
+ deny: opts.denyTools,
1683
+ asker
1684
+ }) : void 0;
1685
+ const guidance = opts.tools !== void 0 ? toolGuidancePrompt(opts.tools) : "";
1686
+ const withGuidance = (userSystem) => {
1687
+ if (guidance.length === 0) return userSystem;
1688
+ return userSystem !== void 0 && userSystem.length > 0 ? `${userSystem}
1689
+
1690
+ ${guidance}` : guidance;
1691
+ };
527
1692
  const session = new ChatSession({
528
- system: opts.system,
1693
+ model: opts.model,
1694
+ system: withGuidance(opts.system),
529
1695
  options: opts.options,
530
- compactAtTokens: opts.compactAtTokens
1696
+ compactAtTokens: opts.compactAtTokens,
1697
+ tools: opts.tools,
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
531
1705
  });
532
- const rl = createInterface({ input: process.stdin, output: process.stdout });
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
+ }
533
1717
  process.stdout.write("apple-fm chat \u2014 Ctrl-D or /quit to quit, /help for commands.\n");
1718
+ let active;
1719
+ const terminal = { closed: false };
1720
+ const terminalClosed = () => terminal.closed;
1721
+ const prompt = () => {
1722
+ if (!terminalClosed()) rl.prompt();
1723
+ };
1724
+ const onKeypress = (_str, key) => {
1725
+ if (key?.name === "escape") active?.abort();
1726
+ };
1727
+ if (interactive) {
1728
+ emitKeypressEvents(process.stdin, rl);
1729
+ process.stdin.on("keypress", onKeypress);
1730
+ rl.once("close", () => {
1731
+ terminal.closed = true;
1732
+ active?.abort();
1733
+ });
1734
+ }
534
1735
  rl.setPrompt("> ");
535
- 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
+ };
536
1745
  for await (const line of rl) {
1746
+ if (terminalClosed()) break;
537
1747
  const text = line.trim();
538
1748
  if (text.length === 0) {
539
- rl.prompt();
1749
+ prompt();
540
1750
  continue;
541
1751
  }
542
1752
  if (text === "/quit" || text === "/exit") break;
543
- if (text === "/help") {
544
- process.stdout.write(`${HELP}
545
- `);
546
- rl.prompt();
547
- continue;
548
- }
549
- if (text === "/clear") {
550
- session.reset();
551
- process.stdout.write("(context cleared)\n");
552
- rl.prompt();
553
- continue;
554
- }
555
- if (text === "/compact") {
556
- try {
557
- await session.compact();
558
- process.stdout.write("(compacted)\n");
559
- } catch (error) {
560
- process.stdout.write(`error: ${error instanceof Error ? error.message : String(error)}
561
- `);
562
- }
563
- rl.prompt();
564
- continue;
565
- }
566
- if (text === "/reset" || text.startsWith("/reset ")) {
567
- session.reset(text.slice("/reset".length).trim() || void 0);
568
- process.stdout.write("(reset)\n");
569
- rl.prompt();
570
- continue;
571
- }
572
- if (text.startsWith("/system ")) {
573
- session.reset(text.slice("/system ".length).trim());
574
- process.stdout.write("(system updated, conversation reset)\n");
575
- rl.prompt();
1753
+ if (await handleChatCommand(text, commands)) {
1754
+ prompt();
576
1755
  continue;
577
1756
  }
1757
+ if (terminalClosed()) break;
1758
+ const controller = new AbortController();
1759
+ active = controller;
578
1760
  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");
1761
+ const reply = await session.send(
1762
+ text,
1763
+ opts.stream ? (chunk) => process.stdout.write(chunk) : void 0,
1764
+ controller.signal
1765
+ );
1766
+ if (controller.signal.aborted) {
1767
+ process.stdout.write("\n(interrupted)\n");
1768
+ } else {
1769
+ if (!opts.stream) process.stdout.write(reply);
1770
+ if (reply.trim().length === 0) process.stdout.write("(no response)");
1771
+ process.stdout.write("\n");
1772
+ }
582
1773
  } catch (error) {
583
1774
  process.stdout.write(`error: ${error instanceof Error ? error.message : String(error)}
584
1775
  `);
1776
+ } finally {
1777
+ active = void 0;
585
1778
  }
586
- rl.prompt();
1779
+ prompt();
587
1780
  }
1781
+ if (interactive) process.stdin.off("keypress", onKeypress);
588
1782
  rl.close();
589
1783
  session.close();
590
1784
  }
@@ -622,14 +1816,30 @@ async function main() {
622
1816
  if (!result.available) process.exitCode = 1;
623
1817
  return;
624
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
+ }
625
1826
  case "generate": {
626
1827
  const prompt = args.prompt ?? await readStdin();
627
1828
  if (prompt.length === 0) throw new Error("generate: no prompt given (pass an argument or pipe stdin)");
628
1829
  const options = {};
1830
+ if (args.sampling !== void 0) options.sampling = args.sampling;
629
1831
  if (args.temperature !== void 0) options.temperature = args.temperature;
630
1832
  if (args.maxTokens !== void 0) options.maxTokens = args.maxTokens;
631
- const request = { prompt, system: args.system, options, stream: args.stream };
632
- 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"));
633
1843
  const structured = args.schemaFile !== void 0;
634
1844
  const onDelta = args.stream && !structured ? (chunk) => process.stdout.write(chunk) : void 0;
635
1845
  const onSnapshot = args.stream && structured && process.stdout.isTTY ? (json) => process.stdout.write(`\r\x1B[2K${json}`) : void 0;
@@ -640,7 +1850,19 @@ async function main() {
640
1850
  return;
641
1851
  }
642
1852
  case "chat": {
643
- await runRepl({ system: args.system, stream: args.stream, compactAtTokens: args.compactAtTokens });
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);
1855
+ await runRepl({
1856
+ saved,
1857
+ model: args.model,
1858
+ system: args.system,
1859
+ stream: args.stream,
1860
+ compactAtTokens: args.compactAtTokens,
1861
+ tools,
1862
+ allowTools: args.allowTools,
1863
+ denyTools: args.denyTools,
1864
+ yes: args.yes
1865
+ });
644
1866
  return;
645
1867
  }
646
1868
  }