apple-fm 0.0.1 → 1.0.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
@@ -134,6 +134,9 @@ function parseEvent(line) {
134
134
  case "delta":
135
135
  if (typeof event.text !== "string") break;
136
136
  return { type: "delta", text: event.text };
137
+ case "snapshot":
138
+ if (typeof event.content !== "string") break;
139
+ return { type: "snapshot", content: event.content };
137
140
  case "result":
138
141
  if (typeof event.content !== "string") break;
139
142
  return { type: "result", content: event.content };
@@ -160,6 +163,19 @@ function estimateConversationTokens(system, messages) {
160
163
  // src/helper.ts
161
164
  var HELPER_BIN_ENV = "APPLE_FM_BIN";
162
165
  var DEFAULT_TIMEOUT_MS = 12e4;
166
+ function isPlatformSupported() {
167
+ return process.platform === "darwin" && process.arch === "arm64";
168
+ }
169
+ function usingBundledHelper(options = {}) {
170
+ if (options.binPath !== void 0 && options.binPath.length > 0) return false;
171
+ const fromEnv = process.env[HELPER_BIN_ENV];
172
+ return fromEnv === void 0 || fromEnv.length === 0;
173
+ }
174
+ function unsupportedPlatformError() {
175
+ return new Error(
176
+ `[unsupportedPlatform] apple-fm requires macOS 26+ on Apple Silicon; the on-device model cannot run on ${process.platform}/${process.arch}`
177
+ );
178
+ }
163
179
  function resolveHelperPath(options = {}) {
164
180
  if (options.binPath !== void 0 && options.binPath.length > 0) return options.binPath;
165
181
  const fromEnv = process.env[HELPER_BIN_ENV];
@@ -225,6 +241,9 @@ function runHelper(args, options, input, onLine) {
225
241
  });
226
242
  }
227
243
  async function probe(options = {}) {
244
+ if (usingBundledHelper(options) && !isPlatformSupported()) {
245
+ return { available: false, reason: "unsupportedPlatform" };
246
+ }
228
247
  let result;
229
248
  await runHelper(["--probe"], options, void 0, (line) => {
230
249
  result = JSON.parse(line);
@@ -232,7 +251,8 @@ async function probe(options = {}) {
232
251
  if (result === void 0) throw new Error("apple-fm helper --probe produced no result");
233
252
  return result;
234
253
  }
235
- async function generate(request, options = {}, onDelta) {
254
+ async function generate(request, options = {}, onDelta, onSnapshot) {
255
+ if (usingBundledHelper(options) && !isPlatformSupported()) throw unsupportedPlatformError();
236
256
  let content;
237
257
  await runHelper(["--generate"], options, encodeRequest(request), (line) => {
238
258
  const event = parseEvent(line);
@@ -240,6 +260,9 @@ async function generate(request, options = {}, onDelta) {
240
260
  case "delta":
241
261
  onDelta?.(event.text);
242
262
  break;
263
+ case "snapshot":
264
+ onSnapshot?.(event.content);
265
+ break;
243
266
  case "result":
244
267
  content = event.content;
245
268
  break;
@@ -254,6 +277,137 @@ async function generate(request, options = {}, onDelta) {
254
277
  // src/repl.ts
255
278
  import { createInterface } from "readline";
256
279
 
280
+ // src/liveSession.ts
281
+ import { spawn as spawn2 } from "child_process";
282
+ var DEFAULT_TURN_TIMEOUT_MS = 12e4;
283
+ var LiveSession = class {
284
+ command;
285
+ timeoutMs;
286
+ options;
287
+ /** Whether we'd spawn the bundled macOS helper (subject to the platform gate). */
288
+ bundled;
289
+ child;
290
+ buffer = "";
291
+ nextId = 0;
292
+ pending = /* @__PURE__ */ new Map();
293
+ constructor(config = {}) {
294
+ this.command = resolveHelperPath(config);
295
+ this.timeoutMs = config.timeoutMs ?? DEFAULT_TURN_TIMEOUT_MS;
296
+ this.options = config.options;
297
+ this.bundled = usingBundledHelper(config);
298
+ }
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);
302
+ }
303
+ /** Send one user turn; prior turns stay in context. Streams via `onDelta`. */
304
+ send(text, onDelta) {
305
+ return this.dispatch(
306
+ { prompt: text, options: this.options, stream: onDelta !== void 0 },
307
+ onDelta
308
+ );
309
+ }
310
+ /** Tear down the helper process and reject any in-flight commands. */
311
+ close() {
312
+ 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"));
316
+ }
317
+ rejectAll(error) {
318
+ for (const pending of this.pending.values()) {
319
+ clearTimeout(pending.timer);
320
+ pending.reject(error);
321
+ }
322
+ this.pending.clear();
323
+ }
324
+ ensureChild() {
325
+ 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"] });
328
+ this.buffer = "";
329
+ child.stdout.setEncoding("utf8");
330
+ child.stdout.on("data", (chunk) => {
331
+ this.onStdout(chunk);
332
+ });
333
+ 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"));
337
+ };
338
+ child.on("close", onGone);
339
+ child.on("error", onGone);
340
+ this.child = child;
341
+ return child;
342
+ }
343
+ onStdout(chunk) {
344
+ this.buffer += chunk;
345
+ const { lines, rest } = splitLines(this.buffer);
346
+ this.buffer = rest;
347
+ for (const line of lines) this.onLine(line);
348
+ }
349
+ onLine(line) {
350
+ let value;
351
+ try {
352
+ value = JSON.parse(line);
353
+ } catch {
354
+ return;
355
+ }
356
+ if (typeof value !== "object" || value === null) return;
357
+ const event = value;
358
+ if (typeof event.id !== "string") return;
359
+ const id = event.id;
360
+ const pending = this.pending.get(id);
361
+ if (pending === void 0) return;
362
+ switch (event.type) {
363
+ case "delta":
364
+ if (typeof event.text === "string") {
365
+ pending.acc += event.text;
366
+ pending.onDelta?.(event.text);
367
+ }
368
+ break;
369
+ case "ready":
370
+ this.settle(id, "");
371
+ break;
372
+ case "result":
373
+ this.settle(id, typeof event.content === "string" ? event.content : pending.acc);
374
+ break;
375
+ case "error":
376
+ this.fail(id, `[${String(event.code)}] ${String(event.message)}`);
377
+ break;
378
+ default:
379
+ break;
380
+ }
381
+ }
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);
388
+ }
389
+ fail(id, message) {
390
+ const pending = this.pending.get(id);
391
+ if (pending === void 0) return;
392
+ clearTimeout(pending.timer);
393
+ this.pending.delete(id);
394
+ pending.reject(new Error(message));
395
+ }
396
+ dispatch(command, onDelta) {
397
+ if (this.bundled && !isPlatformSupported()) return Promise.reject(unsupportedPlatformError());
398
+ const child = this.ensureChild();
399
+ const id = String(this.nextId++);
400
+ return new Promise((resolve, reject) => {
401
+ const timer = setTimeout(() => {
402
+ this.pending.delete(id);
403
+ reject(new Error(`live session timed out after ${String(this.timeoutMs)}ms`));
404
+ }, this.timeoutMs);
405
+ this.pending.set(id, { resolve, reject, onDelta, acc: "", timer });
406
+ child.stdin.write(JSON.stringify({ ...command, id }) + "\n");
407
+ });
408
+ }
409
+ };
410
+
257
411
  // src/session.ts
258
412
  var DEFAULT_COMPACT_AT = 3e3;
259
413
  var DEFAULT_KEEP_RECENT = 4;
@@ -263,18 +417,20 @@ function defaultGenerateFn(helper, options) {
263
417
  }
264
418
  var ChatSession = class {
265
419
  system;
266
- options;
267
420
  compactAtTokens;
268
421
  keepRecentTurns;
422
+ backend;
269
423
  generateFn;
270
424
  messages = [];
271
425
  /** Recap of turns dropped by compaction; folded into the system prompt. */
272
426
  summary;
427
+ /** Instructions the backend was last `reset` with (`undefined` ⇒ needs reset). */
428
+ backendInstructions;
273
429
  constructor(config = {}) {
274
430
  this.system = config.system ?? "";
275
- this.options = config.options;
276
431
  this.compactAtTokens = config.compactAtTokens ?? DEFAULT_COMPACT_AT;
277
432
  this.keepRecentTurns = config.keepRecentTurns ?? DEFAULT_KEEP_RECENT;
433
+ this.backend = config.backend ?? new LiveSession({ ...config.helper, options: config.options });
278
434
  this.generateFn = config.generateFn ?? defaultGenerateFn(config.helper, config.options);
279
435
  }
280
436
  /** The system prompt actually sent to the model (instructions + any recap). */
@@ -297,11 +453,35 @@ ${recap}` : recap;
297
453
  /** Send a user turn and return the assistant's reply (streamed via `onDelta`). */
298
454
  async send(text, onDelta) {
299
455
  if (this.shouldCompact()) await this.compact();
456
+ await this.ensureStarted();
300
457
  this.messages.push({ role: "user", content: text });
301
- const reply = await this.generateFn(this.effectiveSystem(), this.messages, onDelta);
458
+ let reply;
459
+ try {
460
+ reply = await this.backend.send(text, onDelta);
461
+ } 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);
471
+ }
302
472
  this.messages.push({ role: "assistant", content: reply });
303
473
  return reply;
304
474
  }
475
+ /**
476
+ * Reset the backend's session whenever the effective system prompt changes (the
477
+ * first turn, or after a compaction), seeding it with the transcript so far.
478
+ */
479
+ async ensureStarted() {
480
+ const system = this.effectiveSystem();
481
+ if (this.backendInstructions === system) return;
482
+ await this.backend.reset(system, this.messages);
483
+ this.backendInstructions = system;
484
+ }
305
485
  /**
306
486
  * Fold all but the most recent turns into the rolling summary. Safe to call
307
487
  * directly; {@link send} calls it automatically when {@link shouldCompact}.
@@ -324,8 +504,16 @@ ${this.summary}` : "",
324
504
  if (system !== void 0) this.system = system;
325
505
  this.messages = [];
326
506
  this.summary = void 0;
507
+ this.backendInstructions = void 0;
508
+ }
509
+ /** Tear down the underlying live session (kills the helper process). */
510
+ close() {
511
+ this.backend.close();
327
512
  }
328
513
  };
514
+ function recoverable(error) {
515
+ return error instanceof Error && error.message.includes("[sessionClosed]");
516
+ }
329
517
 
330
518
  // src/repl.ts
331
519
  var HELP = `Commands:
@@ -398,6 +586,7 @@ async function runRepl(opts) {
398
586
  rl.prompt();
399
587
  }
400
588
  rl.close();
589
+ session.close();
401
590
  }
402
591
 
403
592
  // src/cli.ts
@@ -441,8 +630,12 @@ async function main() {
441
630
  if (args.maxTokens !== void 0) options.maxTokens = args.maxTokens;
442
631
  const request = { prompt, system: args.system, options, stream: args.stream };
443
632
  if (args.schemaFile !== void 0) request.schema = JSON.parse(await readFile(args.schemaFile, "utf8"));
444
- const text = await generate(request, {}, args.stream ? (chunk) => process.stdout.write(chunk) : void 0);
445
- if (!args.stream) process.stdout.write(text);
633
+ const structured = args.schemaFile !== void 0;
634
+ const onDelta = args.stream && !structured ? (chunk) => process.stdout.write(chunk) : void 0;
635
+ const onSnapshot = args.stream && structured && process.stdout.isTTY ? (json) => process.stdout.write(`\r\x1B[2K${json}`) : void 0;
636
+ const text = await generate(request, {}, onDelta, onSnapshot);
637
+ if (onSnapshot !== void 0) process.stdout.write("\r\x1B[2K");
638
+ if (onDelta === void 0) process.stdout.write(text);
446
639
  process.stdout.write("\n");
447
640
  return;
448
641
  }
package/dist/index.d.ts CHANGED
@@ -40,8 +40,13 @@ interface GenerateRequest {
40
40
  /** Stream partial output as `delta` events (default: false). */
41
41
  stream?: boolean;
42
42
  }
43
- /** Why the on-device model is or isn't usable right now. */
44
- type UnavailableReason = 'deviceNotEligible' | 'appleIntelligenceNotEnabled' | 'modelNotReady' | 'unknown';
43
+ /**
44
+ * Why the on-device model is or isn't usable right now. The first three +
45
+ * `unknown` come from the Swift helper; `unsupportedPlatform` is reported by the
46
+ * Node layer *without* running the helper, when the OS/CPU can't run it at all
47
+ * (not macOS on Apple Silicon).
48
+ */
49
+ type UnavailableReason = 'deviceNotEligible' | 'appleIntelligenceNotEnabled' | 'modelNotReady' | 'unsupportedPlatform' | 'unknown';
45
50
  /** Result of `apple-fm-helper --probe`. */
46
51
  interface ProbeResult {
47
52
  available: boolean;
@@ -49,13 +54,18 @@ interface ProbeResult {
49
54
  reason?: UnavailableReason;
50
55
  }
51
56
  /**
52
- * One line of helper output (NDJSON). `delta` events appear only when streaming;
53
- * every successful generation ends with exactly one `result`. Failures emit a
54
- * single `error`.
57
+ * One line of helper output (NDJSON). When streaming, freeform text emits `delta`
58
+ * events (append the suffix) while guided/structured output emits `snapshot`
59
+ * events (the full partial value — replace, since structured partials are not
60
+ * append-only). Every successful generation ends with exactly one `result`.
61
+ * Failures emit a single `error`.
55
62
  */
56
63
  type HelperEvent = {
57
64
  type: 'delta';
58
65
  text: string;
66
+ } | {
67
+ type: 'snapshot';
68
+ content: string;
59
69
  } | {
60
70
  type: 'result';
61
71
  content: string;
@@ -71,25 +81,82 @@ interface HelperOptions {
71
81
  /** Milliseconds before a one-shot generation is aborted (default 120_000). */
72
82
  timeoutMs?: number;
73
83
  }
74
- /** Callback fired for each streamed text chunk. */
84
+ /** Callback fired for each streamed text chunk (append the suffix). */
75
85
  type DeltaHandler = (text: string) => void;
86
+ /**
87
+ * Callback fired for each full partial value during guided/structured streaming.
88
+ * Each call carries the complete current JSON (replace, not append) — structured
89
+ * partials are not append-only.
90
+ */
91
+ type SnapshotHandler = (content: string) => void;
76
92
 
77
93
  /** Environment variable that pins the helper binary path. */
78
94
  declare const HELPER_BIN_ENV = "APPLE_FM_BIN";
95
+ /**
96
+ * Whether this platform can run the bundled on-device helper at all: macOS on
97
+ * Apple Silicon. (Whether the *model* is usable then — macOS 26+, Apple
98
+ * Intelligence enabled — is what {@link probe} checks.) apple-fm installs on any
99
+ * OS so it can be a dependency of cross-platform projects; off-platform it
100
+ * degrades gracefully rather than crashing — `probe` reports `unsupportedPlatform`
101
+ * and `generate` / `ChatSession` throw a clear `[unsupportedPlatform]` error.
102
+ */
103
+ declare function isPlatformSupported(): boolean;
79
104
  /**
80
105
  * Resolve the helper binary path: `APPLE_FM_BIN`, then the prebuilt binary
81
106
  * bundled with the package (`bin/apple-fm-helper`), then bare `apple-fm-helper`
82
- * to be found on `PATH` (e.g. a Homebrew install).
107
+ * to be found on `PATH`.
83
108
  */
84
109
  declare function resolveHelperPath(options?: HelperOptions): string;
85
110
  /** Ask the helper whether the on-device model is available right now. */
86
111
  declare function probe(options?: HelperOptions): Promise<ProbeResult>;
87
112
  /**
88
- * Run one generation. Streamed `delta` chunks are forwarded to `onDelta` (when
89
- * `request.stream` is set); the resolved value is always the full text (or, for
90
- * guided generation, the JSON string).
113
+ * Run one generation. When `request.stream` is set, freeform text is forwarded to
114
+ * `onDelta` (append the suffix) and guided/structured output to `onSnapshot` (the
115
+ * full partial JSON each time — replace, since structured partials are not
116
+ * append-only). The resolved value is always the full text (or, for guided
117
+ * generation, the complete JSON string).
91
118
  */
92
- declare function generate(request: GenerateRequest, options?: HelperOptions, onDelta?: DeltaHandler): Promise<string>;
119
+ declare function generate(request: GenerateRequest, options?: HelperOptions, onDelta?: DeltaHandler, onSnapshot?: SnapshotHandler): Promise<string>;
120
+
121
+ /** Construction options for a {@link LiveSession}. */
122
+ interface LiveSessionConfig extends HelperOptions {
123
+ /** Generation knobs forwarded with every turn. */
124
+ options?: GenerateOptions;
125
+ }
126
+ /** The backend contract that `ChatSession` drives. */
127
+ interface ChatBackend {
128
+ /** Send one user turn; prior turns stay in the session's context. */
129
+ send(text: string, onDelta?: DeltaHandler): Promise<string>;
130
+ /** Recreate the underlying session with new instructions + seed turns. */
131
+ reset(system: string, seed: Message[]): Promise<void>;
132
+ /** Tear down the backend. */
133
+ close(): void;
134
+ }
135
+ declare class LiveSession implements ChatBackend {
136
+ private readonly command;
137
+ private readonly timeoutMs;
138
+ private readonly options;
139
+ /** Whether we'd spawn the bundled macOS helper (subject to the platform gate). */
140
+ private readonly bundled;
141
+ private child;
142
+ private buffer;
143
+ private nextId;
144
+ private readonly pending;
145
+ constructor(config?: LiveSessionConfig);
146
+ /** Recreate the underlying session with new instructions + seed turns. */
147
+ reset(system: string, seed?: Message[]): Promise<void>;
148
+ /** Send one user turn; prior turns stay in context. Streams via `onDelta`. */
149
+ send(text: string, onDelta?: DeltaHandler): Promise<string>;
150
+ /** Tear down the helper process and reject any in-flight commands. */
151
+ close(): void;
152
+ private rejectAll;
153
+ private ensureChild;
154
+ private onStdout;
155
+ private onLine;
156
+ private settle;
157
+ private fail;
158
+ private dispatch;
159
+ }
93
160
 
94
161
  /**
95
162
  * The line-delimited JSON (NDJSON) wire protocol between the Node layer and the
@@ -134,7 +201,7 @@ declare function estimateTokens(text: string): number;
134
201
  /** Sum the estimated tokens of a system prompt plus a conversation. */
135
202
  declare function estimateConversationTokens(system: string, messages: Message[]): number;
136
203
 
137
- /** Pluggable generation function (real helper by default; a stub in tests). */
204
+ /** Pluggable one-shot generation, used for summarization (a stub in tests). */
138
205
  type GenerateFn = (system: string, messages: Message[], onDelta?: DeltaHandler) => Promise<string>;
139
206
  /** Configuration for a {@link ChatSession}. */
140
207
  interface ChatSessionConfig {
@@ -150,21 +217,30 @@ interface ChatSessionConfig {
150
217
  compactAtTokens?: number;
151
218
  /** Number of most-recent turns kept verbatim through a compaction (default 4). */
152
219
  keepRecentTurns?: number;
153
- /** Helper discovery / timeout options (ignored when `generateFn` is given). */
220
+ /** Helper discovery / timeout options (used for the default backend + summarizer). */
154
221
  helper?: HelperOptions;
155
- /** Override the generation backend (tests inject a stub here). */
222
+ /** Override the live-session backend (tests inject a fake here). */
223
+ backend?: ChatBackend;
224
+ /** Override the one-shot summarization backend (tests inject a stub here). */
156
225
  generateFn?: GenerateFn;
157
226
  }
158
- /** A stateful, auto-compacting conversation with the on-device model. */
227
+ /**
228
+ * A stateful, auto-compacting conversation with the on-device model. Turns run
229
+ * against a persistent {@link LiveSession} (one `LanguageModelSession` reused
230
+ * across turns, FR-12) rather than replaying the transcript each turn; the
231
+ * transcript is still held here to drive compaction, history, and reseed.
232
+ */
159
233
  declare class ChatSession {
160
234
  private system;
161
- private readonly options;
162
235
  private readonly compactAtTokens;
163
236
  private readonly keepRecentTurns;
237
+ private readonly backend;
164
238
  private readonly generateFn;
165
239
  private messages;
166
240
  /** Recap of turns dropped by compaction; folded into the system prompt. */
167
241
  private summary;
242
+ /** Instructions the backend was last `reset` with (`undefined` ⇒ needs reset). */
243
+ private backendInstructions;
168
244
  constructor(config?: ChatSessionConfig);
169
245
  /** The system prompt actually sent to the model (instructions + any recap). */
170
246
  private effectiveSystem;
@@ -174,6 +250,11 @@ declare class ChatSession {
174
250
  shouldCompact(): boolean;
175
251
  /** Send a user turn and return the assistant's reply (streamed via `onDelta`). */
176
252
  send(text: string, onDelta?: DeltaHandler): Promise<string>;
253
+ /**
254
+ * Reset the backend's session whenever the effective system prompt changes (the
255
+ * first turn, or after a compaction), seeding it with the transcript so far.
256
+ */
257
+ private ensureStarted;
177
258
  /**
178
259
  * Fold all but the most recent turns into the rolling summary. Safe to call
179
260
  * directly; {@link send} calls it automatically when {@link shouldCompact}.
@@ -181,6 +262,8 @@ declare class ChatSession {
181
262
  compact(): Promise<void>;
182
263
  /** Clear the transcript and summary; optionally replace the system prompt. */
183
264
  reset(system?: string): void;
265
+ /** Tear down the underlying live session (kills the helper process). */
266
+ close(): void;
184
267
  }
185
268
 
186
- export { ChatSession, type ChatSessionConfig, type DeltaHandler, type GenerateFn, type GenerateOptions, type GenerateRequest, HELPER_BIN_ENV, type HelperEvent, type HelperOptions, type Message, type ProbeResult, type Role, type UnavailableReason, encodeRequest, estimateConversationTokens, estimateTokens, flattenMessages, generate, parseEvent, probe, resolveHelperPath, splitLines };
269
+ export { type ChatBackend, ChatSession, type ChatSessionConfig, type DeltaHandler, type GenerateFn, type GenerateOptions, type GenerateRequest, HELPER_BIN_ENV, type HelperEvent, type HelperOptions, LiveSession, type LiveSessionConfig, type Message, type ProbeResult, type Role, type SnapshotHandler, type UnavailableReason, encodeRequest, estimateConversationTokens, estimateTokens, flattenMessages, generate, isPlatformSupported, parseEvent, probe, resolveHelperPath, splitLines };