apple-fm 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -14,11 +14,15 @@ interface Message {
14
14
  }
15
15
  /** Per-request generation knobs, passed through to the on-device session. */
16
16
  interface GenerateOptions {
17
+ /** Choose the highest-probability token at each step. Omitted uses system sampling. */
18
+ sampling?: 'greedy';
17
19
  /** Sampling temperature (0–2). Omitted ⇒ the model's default. */
18
20
  temperature?: number;
19
21
  /** Cap on the response length, in tokens. Omitted ⇒ the model's default. */
20
22
  maxTokens?: number;
21
23
  }
24
+ /** On-device model specializations supported by one-shot generation. */
25
+ type GenerateUseCase = 'general' | 'content-tagging';
22
26
  /**
23
27
  * A single generation request sent to the helper's `--generate` mode.
24
28
  *
@@ -27,6 +31,14 @@ interface GenerateOptions {
27
31
  * requests guided generation that conforms to the given JSON Schema.
28
32
  */
29
33
  interface GenerateRequest {
34
+ /** Local image file for general generation on macOS 27 and later. */
35
+ imagePath?: string;
36
+ /** Ordered local images for general generation. Use this or imagePath. */
37
+ imagePaths?: string[];
38
+ /** Specialization for one-shot generation. Content tagging returns a JSON array of strings. */
39
+ useCase?: GenerateUseCase;
40
+ /** Model to use. Defaults to on-device. */
41
+ model?: ModelId;
30
42
  /** Instructions for the session (the system prompt). */
31
43
  system?: string;
32
44
  /** A single user turn. Mutually exclusive with `messages`. */
@@ -47,9 +59,24 @@ interface GenerateRequest {
47
59
  * (not macOS on Apple Silicon).
48
60
  */
49
61
  type UnavailableReason = 'deviceNotEligible' | 'appleIntelligenceNotEnabled' | 'modelNotReady' | 'unsupportedPlatform' | 'unknown';
50
- /** Result of `apple-fm-helper --probe`. */
62
+ /** Stable IDs accepted by the CLI and library. */
63
+ type ModelId = 'on-device';
64
+ /** Availability of a model exposed by the current helper and OS. */
65
+ type ModelAvailability = {
66
+ id: string;
67
+ } & ({
68
+ available: true;
69
+ } | {
70
+ available: false;
71
+ reason: string;
72
+ });
73
+ /** Result of `apple-fm-helper --probe`. Legacy fields describe the on-device model. */
51
74
  interface ProbeResult {
75
+ /** Native context capacity in tokens, when reported by the helper. */
76
+ contextSize?: number;
52
77
  available: boolean;
78
+ /** Omitted by older helpers. */
79
+ models?: ModelAvailability[];
53
80
  /** Present only when `available` is false. */
54
81
  reason?: UnavailableReason;
55
82
  }
@@ -78,7 +105,7 @@ type HelperEvent = {
78
105
  interface HelperOptions {
79
106
  /** Explicit path to the helper binary. Overrides discovery. */
80
107
  binPath?: string;
81
- /** Milliseconds before a one-shot generation is aborted (default 120_000). */
108
+ /** Overall timeout for a helper command, including live tools and permission prompts (default 120_000 ms). */
82
109
  timeoutMs?: number;
83
110
  }
84
111
  /** Callback fired for each streamed text chunk (append the suffix). */
@@ -109,8 +136,10 @@ declare function isPlatformSupported(): boolean;
109
136
  * is never resolved off `PATH`, so it can't be shadowed by a planted binary (AFM-66).
110
137
  */
111
138
  declare function resolveHelperPath(options?: HelperOptions): string;
112
- /** Ask the helper whether the on-device model is available right now. */
139
+ /** Ask the helper which models it exposes and whether each is available. */
113
140
  declare function probe(options?: HelperOptions): Promise<ProbeResult>;
141
+ /** Count the native prompt tokens for this text. Requires macOS 26.4 or later. */
142
+ declare function countTokens(prompt: string, options?: HelperOptions): Promise<number>;
114
143
  /**
115
144
  * Run one generation. When `request.stream` is set, freeform text is forwarded to
116
145
  * `onDelta` (append the suffix) and guided/structured output to `onSnapshot` (the
@@ -157,11 +186,15 @@ interface PermissionRequest {
157
186
  description: string;
158
187
  /** The raw arguments the model generated. */
159
188
  args: Record<string, unknown>;
189
+ /** Aborted when the originating live turn settles or is interrupted. */
190
+ signal?: AbortSignal;
160
191
  /**
161
192
  * How this tool compares a rule's key to {@link key} (from `Tool.matchKey`). Omitted
162
193
  * ⇒ exact equality — a keyed rule matches only the identical key, never a prefix.
163
194
  */
164
195
  matchKey?: KeyMatcher;
196
+ /** Resolve configured keys off the main thread before matching the prepared resource. */
197
+ resolveRuleKeys?: (keys: string[]) => Promise<string[]>;
165
198
  /** High-risk tool (`Tool.dangerous`): a permissive default won't blanket-approve it. */
166
199
  dangerous?: boolean;
167
200
  }
@@ -198,10 +231,10 @@ declare class PermissionPolicy {
198
231
  /**
199
232
  * Decide whether a call may proceed, prompting on `ask` and remembering an
200
233
  * "always". Resolves `true` to run the tool, `false` to refuse it (the dispatcher
201
- * feeds a refusal back to the model as a tool result). Never throws — an asker that
202
- * rejects is treated as a denial.
234
+ * feeds a refusal back to the model as a tool result). A rejected asker is treated
235
+ * as a denial. The dispatcher also fails closed if a tool's rule resolver throws.
203
236
  */
204
- authorize(request: PermissionRequest): Promise<boolean>;
237
+ authorize(request: PermissionRequest, isCurrent?: () => boolean): Promise<boolean>;
205
238
  }
206
239
 
207
240
  /**
@@ -214,12 +247,23 @@ declare class PermissionPolicy {
214
247
  * checks live. Only the Node layer ever implements a tool; the helper carries the
215
248
  * call across the wire.
216
249
  */
250
+
251
+ /** A call prepared with the same resource identity for authorization and execution. */
252
+ interface PreparedToolCall {
253
+ request: PermissionRequest;
254
+ run(): Promise<string>;
255
+ }
256
+ /** A sanitized update about a tool invocation in a live turn. */
257
+ interface ToolActivity {
258
+ tool: string;
259
+ action: string;
260
+ status: 'requested' | 'completed' | 'denied' | 'failed';
261
+ }
217
262
  /**
218
- * Context handed to {@link Tool.run}. Intentionally minimal in phase 1; phase 2
219
- * threads the permission decision and (later) cancellation through here.
263
+ * Context handed to {@link Tool.run} for cooperative cancellation.
220
264
  */
221
265
  interface ToolContext {
222
- /** Aborts the in-flight tool when the turn is torn down (reserved; unused in phase 1). */
266
+ /** Aborted when the originating turn settles or is interrupted. */
223
267
  signal?: AbortSignal;
224
268
  }
225
269
  /**
@@ -241,6 +285,8 @@ interface Tool {
241
285
  * the model. Throw to signal the call failed — the model is told and may continue.
242
286
  */
243
287
  run(args: Record<string, unknown>, ctx: ToolContext): Promise<string>;
288
+ /** Optionally prepare a resource identity without reading its contents. */
289
+ prepare?(args: Record<string, unknown>, ctx: ToolContext): Promise<PreparedToolCall>;
244
290
  /**
245
291
  * Optional finer-grained permission key for a call (e.g. the file path for `read`,
246
292
  * the command for `bash`). Used to scope allow/deny rules and "always" grants
@@ -297,6 +343,10 @@ declare class ToolRegistry {
297
343
  constructor(tools?: Tool[]);
298
344
  /** Register (or replace) a tool by name. */
299
345
  register(tool: Tool): void;
346
+ /** Look up the implementation for one call. */
347
+ get(name: string): Tool | undefined;
348
+ /** Copy the wire definitions, permission hooks, and implementations for a live session. */
349
+ snapshot(): ToolRegistry;
300
350
  /** Whether a tool with this name is registered. */
301
351
  has(name: string): boolean;
302
352
  /** Number of registered tools (0 ⇒ no `tools[]` is sent on a turn). */
@@ -342,13 +392,17 @@ declare function registryFromNames(names: string[]): ToolRegistry;
342
392
 
343
393
  /** Construction options for a {@link LiveSession}. */
344
394
  interface LiveSessionConfig extends HelperOptions {
395
+ /** Model to use for the lifetime of the session. Defaults to on-device. */
396
+ model?: ModelId;
345
397
  /** Generation knobs forwarded with every turn. */
346
398
  options?: GenerateOptions;
347
399
  /**
348
- * Tools the model may call mid-turn (FR-14). When non-empty, their definitions
349
- * are sent with each turn and the session dispatches `tool_call` events to them.
400
+ * Tools the model may call mid-turn (FR-14). Captured when the session is
401
+ * constructed. Their definitions bind on reset and transcript import.
350
402
  */
351
403
  tools?: ToolRegistry;
404
+ /** Observe sanitized tool actions and outcomes for the current turn. */
405
+ onToolActivity?: (event: ToolActivity) => void;
352
406
  /**
353
407
  * Per-call permission policy consulted before each tool runs (FR-14 phase 2).
354
408
  *
@@ -373,6 +427,17 @@ interface ChatBackend {
373
427
  send(text: string, onDelta?: DeltaHandler, signal?: AbortSignal): Promise<string>;
374
428
  /** Recreate the underlying session with new instructions + seed turns. */
375
429
  reset(system: string, seed: Message[]): Promise<void>;
430
+ /** Native token budget for the active transcript plus the next prompt, if supported. */
431
+ tokenBudget?(prompt: string): Promise<{
432
+ tokens: number;
433
+ contextSize: number;
434
+ } | undefined>;
435
+ /** Serialize the active native transcript, when the backend supports it. */
436
+ exportTranscript?(): Promise<string>;
437
+ /** Replace the native transcript after validating it against the enabled tools. */
438
+ importTranscript?(transcript: string): Promise<void>;
439
+ /** Whether the current backend process can still hold a previously reset session. */
440
+ isActive?(): boolean;
376
441
  /** Tear down the backend. */
377
442
  close(): void;
378
443
  }
@@ -382,10 +447,13 @@ declare class LiveSession implements ChatBackend {
382
447
  private readonly options;
383
448
  private readonly tools;
384
449
  private readonly permission;
450
+ private readonly onToolActivity;
385
451
  /** Whether we'd spawn the bundled macOS helper (subject to the platform gate). */
386
452
  private readonly bundled;
387
453
  private child;
388
454
  private buffer;
455
+ private contextSize?;
456
+ private transcriptPersistence;
389
457
  private nextId;
390
458
  private readonly pending;
391
459
  constructor(config?: LiveSessionConfig);
@@ -401,9 +469,21 @@ declare class LiveSession implements ChatBackend {
401
469
  * the helper ends the turn with the partial text generated so far (FR-15).
402
470
  */
403
471
  send(text: string, onDelta?: DeltaHandler, signal?: AbortSignal): Promise<string>;
472
+ /** Count native tokens for the active session without starting another helper. */
473
+ tokenBudget(prompt: string): Promise<{
474
+ tokens: number;
475
+ contextSize: number;
476
+ } | undefined>;
477
+ /** Serialize the active native transcript without starting another helper. */
478
+ exportTranscript(): Promise<string>;
479
+ /** Whether the current helper can still hold the active session. */
480
+ isActive(): boolean;
481
+ /** Restore the transcript using the currently configured tools. */
482
+ importTranscript(transcript: string): Promise<void>;
483
+ private requireTranscriptPersistence;
404
484
  /** Tear down the helper process and reject any in-flight commands. */
405
485
  close(): void;
406
- private rejectAll;
486
+ private retireChild;
407
487
  private ensureChild;
408
488
  private onStdout;
409
489
  private onLine;
@@ -411,16 +491,12 @@ declare class LiveSession implements ChatBackend {
411
491
  * Dispatch a `tool_call` to the registered tool and write the outcome back to the
412
492
  * helper, keyed by `callId`. Runs concurrently with the still-open turn; the tool
413
493
  * policy lives in {@link dispatchToolCall} (`src/tools/dispatch.ts`) — this wires it
414
- * to the session's child process and the pending turn's timeout.
494
+ * to the session's child process and the pending turn's lifetime.
415
495
  */
416
496
  private handleToolCall;
417
- /** Restart a pending turn's timeout (e.g. across a tool call). */
418
- private restartTimer;
497
+ private takePending;
419
498
  private settle;
420
- private fail;
421
499
  private dispatch;
422
- /** Ask the helper to cancel an in-flight turn (no-op if it already settled). */
423
- private cancel;
424
500
  }
425
501
 
426
502
  /**
@@ -436,7 +512,7 @@ declare function encodeRequest(request: GenerateRequest): string;
436
512
  * remainder that has not yet been terminated by a newline. Carry `rest` into the
437
513
  * next chunk.
438
514
  */
439
- declare function splitLines(buffer: string): {
515
+ declare function splitLines(buffer: string, bounded?: boolean): {
440
516
  lines: string[];
441
517
  rest: string;
442
518
  };
@@ -468,8 +544,19 @@ declare function estimateConversationTokens(system: string, messages: Message[])
468
544
 
469
545
  /** Pluggable one-shot generation, used for summarization (a stub in tests). */
470
546
  type GenerateFn = (system: string, messages: Message[], onDelta?: DeltaHandler) => Promise<string>;
547
+ /** Versioned snapshot for saving and resuming a chat. */
548
+ interface SavedChat {
549
+ version: 1;
550
+ system: string;
551
+ summary?: string;
552
+ messages: Message[];
553
+ tools: string[];
554
+ transcript: string;
555
+ }
471
556
  /** Configuration for a {@link ChatSession}. */
472
557
  interface ChatSessionConfig {
558
+ /** Model used for chat and compaction. Defaults to on-device. */
559
+ model?: ModelId;
473
560
  /** Instructions for the model (system prompt). */
474
561
  system?: string;
475
562
  /** Generation knobs forwarded to every turn. */
@@ -486,6 +573,8 @@ interface ChatSessionConfig {
486
573
  helper?: HelperOptions;
487
574
  /** Tools the model may call mid-turn (FR-14). Ignored when a custom `backend` is set. */
488
575
  tools?: ToolRegistry;
576
+ /** Observe tool activity from the default live backend. */
577
+ onToolActivity?: LiveSessionConfig['onToolActivity'];
489
578
  /**
490
579
  * Per-call permission policy for tools (FR-14 phase 2). Ignored when a custom
491
580
  * `backend` is set. Safe by default: with `tools` set but no policy, the default
@@ -500,7 +589,7 @@ interface ChatSessionConfig {
500
589
  generateFn?: GenerateFn;
501
590
  }
502
591
  /**
503
- * A stateful, auto-compacting conversation with the on-device model. Turns run
592
+ * A stateful, auto-compacting conversation with the selected model. Turns run
504
593
  * against a persistent {@link LiveSession} (one `LanguageModelSession` reused
505
594
  * across turns, FR-12) rather than replaying the transcript each turn; the
506
595
  * transcript is still held here to drive compaction, history, and reseed.
@@ -511,39 +600,57 @@ declare class ChatSession {
511
600
  private readonly keepRecentTurns;
512
601
  private readonly backend;
513
602
  private readonly generateFn;
603
+ private readonly toolNames;
514
604
  private messages;
515
605
  /** Recap of turns dropped by compaction; folded into the system prompt. */
516
606
  private summary;
517
607
  /** Instructions the backend was last `reset` with (`undefined` ⇒ needs reset). */
518
608
  private backendInstructions;
609
+ private operations;
610
+ private revision;
519
611
  constructor(config?: ChatSessionConfig);
520
612
  /** The system prompt actually sent to the model (instructions + any recap). */
521
613
  private effectiveSystem;
522
614
  /** The current transcript (a copy; mutating it does not affect the session). */
523
615
  history(): Message[];
616
+ /** Report the active context in tokens. A missing capacity indicates an estimate. */
617
+ usage(): Promise<{
618
+ tokens: number;
619
+ contextSize?: number;
620
+ }>;
524
621
  /** Whether the next turn would push the transcript past the compaction bound. */
525
622
  shouldCompact(): boolean;
526
623
  /**
527
624
  * Send a user turn and return the assistant's reply (streamed via `onDelta`). An
528
625
  * optional `signal` interrupts the turn (FR-15, esc-to-interrupt): on abort the
529
626
  * reply resolves with the partial text generated so far, and both the user prompt
530
- * and that partial reply are kept in history (so a follow-up turn stays coherent).
627
+ * and that partial reply are kept in history. Aborting before a turn starts
628
+ * returns empty text without adding a turn.
531
629
  */
532
630
  send(text: string, onDelta?: DeltaHandler, signal?: AbortSignal): Promise<string>;
631
+ private sendTurn;
533
632
  /**
534
633
  * Reset the backend's session whenever the effective system prompt changes (the
535
634
  * first turn, or after a compaction), seeding it with the transcript so far.
536
635
  */
537
636
  private ensureStarted;
637
+ private runBackend;
638
+ private schedule;
639
+ private assertCurrent;
538
640
  /**
539
641
  * Fold all but the most recent turns into the rolling summary. Safe to call
540
642
  * directly; {@link send} calls it automatically when {@link shouldCompact}.
541
643
  */
542
644
  compact(): Promise<void>;
645
+ private compactHistory;
646
+ /** Capture a versioned snapshot with the native session transcript. */
647
+ saveTranscript(): Promise<SavedChat>;
648
+ /** Resume a saved chat using this invocation's tool registry and permissions. */
649
+ resumeTranscript(saved: SavedChat): Promise<void>;
543
650
  /** Clear the transcript and summary; optionally replace the system prompt. */
544
651
  reset(system?: string): void;
545
652
  /** Tear down the underlying live session (kills the helper process). */
546
653
  close(): void;
547
654
  }
548
655
 
549
- export { type AskOutcome, BUILTIN_TOOLS, 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 PermissionAsker, type PermissionMode, PermissionPolicy, type PermissionPolicyConfig, type PermissionRequest, type ProbeResult, type Role, type SnapshotHandler, type Tool, type ToolContext, type ToolDefinition, ToolRegistry, type UnavailableReason, bashTool, encodeRequest, estimateConversationTokens, estimateTokens, flattenMessages, generate, isPlatformSupported, parseEvent, probe, readTool, registryFromNames, resolveHelperPath, splitLines, toolGuidancePrompt };
656
+ export { type AskOutcome, BUILTIN_TOOLS, type ChatBackend, ChatSession, type ChatSessionConfig, type DeltaHandler, type GenerateFn, type GenerateOptions, type GenerateRequest, type GenerateUseCase, HELPER_BIN_ENV, type HelperEvent, type HelperOptions, LiveSession, type LiveSessionConfig, type Message, type ModelAvailability, type ModelId, type PermissionAsker, type PermissionMode, PermissionPolicy, type PermissionPolicyConfig, type PermissionRequest, type ProbeResult, type Role, type SnapshotHandler, type Tool, type ToolActivity, type ToolContext, type ToolDefinition, ToolRegistry, type UnavailableReason, bashTool, countTokens, encodeRequest, estimateConversationTokens, estimateTokens, flattenMessages, generate, isPlatformSupported, parseEvent, probe, readTool, registryFromNames, resolveHelperPath, splitLines, toolGuidancePrompt };