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/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). */
@@ -102,13 +129,17 @@ declare const HELPER_BIN_ENV = "APPLE_FM_BIN";
102
129
  */
103
130
  declare function isPlatformSupported(): boolean;
104
131
  /**
105
- * Resolve the helper binary path: `APPLE_FM_BIN`, then the prebuilt binary
106
- * bundled with the package (`bin/apple-fm-helper`), then bare `apple-fm-helper`
107
- * to be found on `PATH`.
132
+ * Resolve the helper binary path: an explicit `binPath`, then the `APPLE_FM_BIN`
133
+ * override (trusted as-is — an advanced/testing escape hatch), then the prebuilt
134
+ * binary bundled with the package (`bin/apple-fm-helper`), addressed by an absolute
135
+ * path relative to this module. There is **no bare-name `PATH` lookup** — the helper
136
+ * is never resolved off `PATH`, so it can't be shadowed by a planted binary (AFM-66).
108
137
  */
109
138
  declare function resolveHelperPath(options?: HelperOptions): string;
110
- /** 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. */
111
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>;
112
143
  /**
113
144
  * Run one generation. When `request.stream` is set, freeform text is forwarded to
114
145
  * `onDelta` (append the suffix) and guided/structured output to `onSnapshot` (the
@@ -118,17 +149,295 @@ declare function probe(options?: HelperOptions): Promise<ProbeResult>;
118
149
  */
119
150
  declare function generate(request: GenerateRequest, options?: HelperOptions, onDelta?: DeltaHandler, onSnapshot?: SnapshotHandler): Promise<string>;
120
151
 
152
+ /**
153
+ * Per-call permission policy for tool calling (FR-14 / AF-5 phase 2; see
154
+ * docs/10-permissions.md). Consulted by the live-session dispatcher *before* a
155
+ * tool runs. Kept entirely in Node — the Swift helper never decides policy.
156
+ *
157
+ * A request resolves to `allow` / `deny` / `ask`. `ask` prompts via an injected
158
+ * {@link PermissionAsker} (the REPL supplies one bound to readline); with no asker
159
+ * (non-interactive / piped), `ask` denies — a script never silently runs a tool. An
160
+ * "always" answer is remembered for the process lifetime.
161
+ *
162
+ * Rules are keyed by tool name, or by a finer `tool:key` so that allowing one
163
+ * command (a `bash:git status` rule) or one path (`read:/etc`) doesn't allow all of
164
+ * the tool. How a keyed rule's key matches a call's key is decided by the tool's
165
+ * {@link Tool.matchKey} — **exact equality** by default (never a prefix, so a grant
166
+ * can't be extended with shell metacharacters or `..`), `read` widening it to a
167
+ * resolved path boundary, `bash` keeping `allow` exact but making `deny` a broad
168
+ * best-effort token match (AFM-63 / AFM-67). A permissive *default* never
169
+ * blanket-approves a {@link Tool.dangerous} tool (AFM-64).
170
+ */
171
+ /** The three policy outcomes for a tool call. */
172
+ type PermissionMode = 'allow' | 'deny' | 'ask';
173
+ /** Which rule set a match is being tested against (tools may match differently). */
174
+ type RuleKind = 'allow' | 'deny';
175
+ /** How a tool's key is compared to a rule's key. Defaults to exact equality. */
176
+ type KeyMatcher = (ruleKey: string, callKey: string, kind: RuleKind) => boolean;
177
+ /** What the user chose at an interactive prompt. */
178
+ type AskOutcome = 'once' | 'always' | 'deny';
179
+ /** A pending tool call presented to the policy (and the prompt). */
180
+ interface PermissionRequest {
181
+ /** The tool name. */
182
+ tool: string;
183
+ /** A finer-grained key for this call (e.g. the path/command), if the tool gives one. */
184
+ key?: string;
185
+ /** One-line, human-readable description of the action (shown in the prompt). */
186
+ description: string;
187
+ /** The raw arguments the model generated. */
188
+ args: Record<string, unknown>;
189
+ /** Aborted when the originating live turn settles or is interrupted. */
190
+ signal?: AbortSignal;
191
+ /**
192
+ * How this tool compares a rule's key to {@link key} (from `Tool.matchKey`). Omitted
193
+ * ⇒ exact equality — a keyed rule matches only the identical key, never a prefix.
194
+ */
195
+ matchKey?: KeyMatcher;
196
+ /** Resolve configured keys off the main thread before matching the prepared resource. */
197
+ resolveRuleKeys?: (keys: string[]) => Promise<string[]>;
198
+ /** High-risk tool (`Tool.dangerous`): a permissive default won't blanket-approve it. */
199
+ dangerous?: boolean;
200
+ }
201
+ /** Prompts the user to approve a call; the REPL provides this on a TTY. */
202
+ type PermissionAsker = (request: PermissionRequest) => Promise<AskOutcome>;
203
+ /** Construction options for a {@link PermissionPolicy}. */
204
+ interface PermissionPolicyConfig {
205
+ /** Decision when no rule matches (default `ask`). */
206
+ default?: PermissionMode;
207
+ /** Pre-authorized rules (`tool` or `tool:keyPrefix`), e.g. from `--allow-tool`. */
208
+ allow?: string[];
209
+ /** Denied rules (`tool` or `tool:keyPrefix`), e.g. from `--deny-tool`. */
210
+ deny?: string[];
211
+ /** Prompt on `ask`. Omitted ⇒ non-interactive: `ask` denies. */
212
+ asker?: PermissionAsker;
213
+ }
214
+ declare class PermissionPolicy {
215
+ private readonly defaultMode;
216
+ private readonly allow;
217
+ private readonly deny;
218
+ private readonly asker;
219
+ constructor(config?: PermissionPolicyConfig);
220
+ /** Whether any rule in `set` matches the request, evaluated as the given kind. */
221
+ private matches;
222
+ /**
223
+ * The static decision for a request, before any prompt. `deny` wins over `allow`. A
224
+ * permissive *default* (`allow`, e.g. `--yes`) does **not** cover a `dangerous` tool:
225
+ * it downgrades to `ask` so a blanket approval can't silently grant `bash` arbitrary
226
+ * command execution (AFM-64). An explicit allow rule still grants it.
227
+ */
228
+ decide(request: PermissionRequest): PermissionMode;
229
+ /** Remember an "always" approval for this call (process lifetime). */
230
+ private remember;
231
+ /**
232
+ * Decide whether a call may proceed, prompting on `ask` and remembering an
233
+ * "always". Resolves `true` to run the tool, `false` to refuse it (the dispatcher
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.
236
+ */
237
+ authorize(request: PermissionRequest, isCurrent?: () => boolean): Promise<boolean>;
238
+ }
239
+
240
+ /**
241
+ * Types for tool calling (FR-14 / AF-5 phase 1; see docs/9-tool-calling.md).
242
+ *
243
+ * A {@link Tool} is a Node-side capability the on-device model can invoke
244
+ * mid-generation. The model decides *when* to call a tool; the Swift helper runs
245
+ * the framework's tool-call loop and round-trips each invocation back to Node — the
246
+ * tool's `run` executes here, where typed logic, tests, and (phase 2) permission
247
+ * checks live. Only the Node layer ever implements a tool; the helper carries the
248
+ * call across the wire.
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
+ }
262
+ /**
263
+ * Context handed to {@link Tool.run} for cooperative cancellation.
264
+ */
265
+ interface ToolContext {
266
+ /** Aborted when the originating turn settles or is interrupted. */
267
+ signal?: AbortSignal;
268
+ }
269
+ /**
270
+ * A tool the model can call. `parameters` is a JSON Schema for the call arguments,
271
+ * expressed in the same subset the helper compiles for guided generation (FR-8;
272
+ * see docs/6-guided-generation.md) — it becomes the tool's native `GenerationSchema`
273
+ * so the model can only produce valid arguments.
274
+ */
275
+ interface Tool {
276
+ /** Unique tool name the model references (e.g. `read`). */
277
+ name: string;
278
+ /** What the tool does — shown to the model so it knows when to call it. */
279
+ description: string;
280
+ /** JSON Schema (the guided-generation subset) for the call arguments. */
281
+ parameters: unknown;
282
+ /**
283
+ * Execute the call. `args` is the object the model generated (already validated
284
+ * against `parameters` by the framework). Return the textual result fed back to
285
+ * the model. Throw to signal the call failed — the model is told and may continue.
286
+ */
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>;
290
+ /**
291
+ * Optional finer-grained permission key for a call (e.g. the file path for `read`,
292
+ * the command for `bash`). Used to scope allow/deny rules and "always" grants
293
+ * below the whole tool (FR-14 phase 2). Omitted ⇒ rules apply at the tool level.
294
+ */
295
+ permissionKey?(args: Record<string, unknown>): string | undefined;
296
+ /** Optional one-line description of a call, shown in the permission prompt. */
297
+ describe?(args: Record<string, unknown>): string;
298
+ /**
299
+ * Optional: does a permission rule's key match this call's key, for the given rule
300
+ * kind? Lets a tool define *safe* semantics for its own key type instead of the
301
+ * generic default. `bash` requires an **exact** command for an `allow` (a grant for
302
+ * `ls` never extends to `ls; rm -rf ~`) but a broad best-effort token match for a
303
+ * `deny`; `read` treats the key as a filesystem boundary (a directory grant covers
304
+ * its descendants, after resolving `..`). Omitted ⇒ the policy matches keys by
305
+ * **exact equality** — the safe default, never a prefix. (FR-14; AFM-63 / AFM-67.)
306
+ */
307
+ matchKey?(ruleKey: string, callKey: string, kind: 'allow' | 'deny'): boolean;
308
+ /**
309
+ * Optional: mark the tool as high-risk (e.g. `bash`, which runs arbitrary shell
310
+ * commands). A permissive policy **default** (`--yes`) does not blanket-approve a
311
+ * dangerous tool — it still requires an explicit allow rule or an interactive
312
+ * approval — so a single `--yes` can't silently hand the untrusted model arbitrary
313
+ * command execution. (FR-14; AFM-64.)
314
+ */
315
+ dangerous?: boolean;
316
+ /**
317
+ * Optional one-line hint telling the model *when* to use this tool, folded into the
318
+ * auto-injected tool-use system prompt (CLI only; see `toolGuidancePrompt`). Without
319
+ * it, the tool's `name`/`description` are used.
320
+ */
321
+ usageHint?: string;
322
+ }
323
+ /**
324
+ * The wire shape of a tool sent to the helper on a turn command (`tools[]`). Just
325
+ * the model-facing surface — never the `run` implementation, which stays in Node.
326
+ */
327
+ interface ToolDefinition {
328
+ name: string;
329
+ description: string;
330
+ parameters: unknown;
331
+ }
332
+
333
+ /**
334
+ * A registry of the tools exposed to a session. The extensibility seam for
335
+ * FR-14 / AF-5: a library consumer registers their own {@link Tool}s, the CLI
336
+ * enables built-ins by name. The registry emits the model-facing
337
+ * {@link ToolDefinition}s onto each turn command and dispatches an incoming
338
+ * `tool_call` to the matching tool's `run`.
339
+ */
340
+
341
+ declare class ToolRegistry {
342
+ private readonly tools;
343
+ constructor(tools?: Tool[]);
344
+ /** Register (or replace) a tool by name. */
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;
350
+ /** Whether a tool with this name is registered. */
351
+ has(name: string): boolean;
352
+ /** Number of registered tools (0 ⇒ no `tools[]` is sent on a turn). */
353
+ get size(): number;
354
+ /** The model-facing definitions sent to the helper on a turn command. */
355
+ definitions(): ToolDefinition[];
356
+ /** The registered tool names (for the REPL `/tools` listing). */
357
+ names(): string[];
358
+ /** One usage hint per tool (its `usageHint`, or a `name: description` fallback). */
359
+ usageHints(): string[];
360
+ /**
361
+ * Build a {@link PermissionRequest} for a call, using the tool's optional
362
+ * `permissionKey` / `describe` hooks. Returns `undefined` for an unknown tool.
363
+ */
364
+ permissionRequest(name: string, args: Record<string, unknown>): PermissionRequest | undefined;
365
+ /**
366
+ * Run a tool by name. Throws (with a clear message) if no such tool is
367
+ * registered, so the dispatcher can surface a `tool_error` to the model.
368
+ */
369
+ run(name: string, args: Record<string, unknown>, ctx?: ToolContext): Promise<string>;
370
+ }
371
+
372
+ declare const bashTool: Tool;
373
+
374
+ declare const readTool: Tool;
375
+
376
+ /** The built-in tools, keyed by name. All run locally — apple-fm makes no network calls. */
377
+ declare const BUILTIN_TOOLS: Readonly<Record<string, Tool>>;
378
+ /**
379
+ * A short system-prompt preamble telling the model it has tools and should use them
380
+ * rather than refuse — built from the registry's enabled tools. The CLI injects this
381
+ * when `--tools` is set (merged with any `-s`) so the small on-device model knows
382
+ * *when* to call a tool instead of falling back on a "can't access files" refusal.
383
+ * Returns `''` for an empty registry. (Library consumers can use it too; the library
384
+ * itself stays unopinionated.)
385
+ */
386
+ declare function toolGuidancePrompt(registry: ToolRegistry): string;
387
+ /**
388
+ * Build a registry from built-in tool names (e.g. the CLI's `--tools read`).
389
+ * Throws on an unknown name so a typo is a clear error rather than a silent no-op.
390
+ */
391
+ declare function registryFromNames(names: string[]): ToolRegistry;
392
+
121
393
  /** Construction options for a {@link LiveSession}. */
122
394
  interface LiveSessionConfig extends HelperOptions {
395
+ /** Model to use for the lifetime of the session. Defaults to on-device. */
396
+ model?: ModelId;
123
397
  /** Generation knobs forwarded with every turn. */
124
398
  options?: GenerateOptions;
399
+ /**
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.
402
+ */
403
+ tools?: ToolRegistry;
404
+ /** Observe sanitized tool actions and outcomes for the current turn. */
405
+ onToolActivity?: (event: ToolActivity) => void;
406
+ /**
407
+ * Per-call permission policy consulted before each tool runs (FR-14 phase 2).
408
+ *
409
+ * **Safe by default (AFM-78):** when {@link tools} are registered and this is
410
+ * omitted, the session installs a **fail-closed** policy (default `ask`, no asker ⇒
411
+ * every tool call is denied) rather than running tools ungated. So a `tool_call` —
412
+ * including one emitted by a compromised/replaced helper — never runs without an
413
+ * explicit decision. To actually let tools run, supply a policy with `allow` rules,
414
+ * an interactive `asker`, or `{ default: 'allow' }` (a deliberate opt-in; a `dangerous`
415
+ * tool like `bash` still requires an explicit allow — AFM-64). A refused call is fed
416
+ * back to the model as the tool result.
417
+ */
418
+ permission?: PermissionPolicy;
125
419
  }
126
420
  /** The backend contract that `ChatSession` drives. */
127
421
  interface ChatBackend {
128
- /** Send one user turn; prior turns stay in the session's context. */
129
- send(text: string, onDelta?: DeltaHandler): Promise<string>;
422
+ /**
423
+ * Send one user turn; prior turns stay in the session's context. An optional
424
+ * `signal` interrupts the in-flight turn (FR-15, esc-to-interrupt): on abort the
425
+ * turn is cancelled and resolves with the partial text generated so far.
426
+ */
427
+ send(text: string, onDelta?: DeltaHandler, signal?: AbortSignal): Promise<string>;
130
428
  /** Recreate the underlying session with new instructions + seed turns. */
131
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;
132
441
  /** Tear down the backend. */
133
442
  close(): void;
134
443
  }
@@ -136,25 +445,57 @@ declare class LiveSession implements ChatBackend {
136
445
  private readonly command;
137
446
  private readonly timeoutMs;
138
447
  private readonly options;
448
+ private readonly tools;
449
+ private readonly permission;
450
+ private readonly onToolActivity;
139
451
  /** Whether we'd spawn the bundled macOS helper (subject to the platform gate). */
140
452
  private readonly bundled;
141
453
  private child;
142
454
  private buffer;
455
+ private contextSize?;
456
+ private transcriptPersistence;
143
457
  private nextId;
144
458
  private readonly pending;
145
459
  constructor(config?: LiveSessionConfig);
146
- /** Recreate the underlying session with new instructions + seed turns. */
460
+ /**
461
+ * Recreate the underlying session with new instructions + seed turns. Tool
462
+ * definitions ride on `reset` because the framework binds tools at session
463
+ * construction (not per turn); the helper builds the session's tools here.
464
+ */
147
465
  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>;
466
+ /**
467
+ * Send one user turn; prior turns stay in context. Streams via `onDelta`. An
468
+ * optional `signal` interrupts the turn: on abort a `cancel` command is sent and
469
+ * the helper ends the turn with the partial text generated so far (FR-15).
470
+ */
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;
150
484
  /** Tear down the helper process and reject any in-flight commands. */
151
485
  close(): void;
152
- private rejectAll;
486
+ private retireChild;
153
487
  private ensureChild;
154
488
  private onStdout;
155
489
  private onLine;
490
+ /**
491
+ * Dispatch a `tool_call` to the registered tool and write the outcome back to the
492
+ * helper, keyed by `callId`. Runs concurrently with the still-open turn; the tool
493
+ * policy lives in {@link dispatchToolCall} (`src/tools/dispatch.ts`) — this wires it
494
+ * to the session's child process and the pending turn's lifetime.
495
+ */
496
+ private handleToolCall;
497
+ private takePending;
156
498
  private settle;
157
- private fail;
158
499
  private dispatch;
159
500
  }
160
501
 
@@ -171,7 +512,7 @@ declare function encodeRequest(request: GenerateRequest): string;
171
512
  * remainder that has not yet been terminated by a newline. Carry `rest` into the
172
513
  * next chunk.
173
514
  */
174
- declare function splitLines(buffer: string): {
515
+ declare function splitLines(buffer: string, bounded?: boolean): {
175
516
  lines: string[];
176
517
  rest: string;
177
518
  };
@@ -203,8 +544,19 @@ declare function estimateConversationTokens(system: string, messages: Message[])
203
544
 
204
545
  /** Pluggable one-shot generation, used for summarization (a stub in tests). */
205
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
+ }
206
556
  /** Configuration for a {@link ChatSession}. */
207
557
  interface ChatSessionConfig {
558
+ /** Model used for chat and compaction. Defaults to on-device. */
559
+ model?: ModelId;
208
560
  /** Instructions for the model (system prompt). */
209
561
  system?: string;
210
562
  /** Generation knobs forwarded to every turn. */
@@ -219,13 +571,25 @@ interface ChatSessionConfig {
219
571
  keepRecentTurns?: number;
220
572
  /** Helper discovery / timeout options (used for the default backend + summarizer). */
221
573
  helper?: HelperOptions;
574
+ /** Tools the model may call mid-turn (FR-14). Ignored when a custom `backend` is set. */
575
+ tools?: ToolRegistry;
576
+ /** Observe tool activity from the default live backend. */
577
+ onToolActivity?: LiveSessionConfig['onToolActivity'];
578
+ /**
579
+ * Per-call permission policy for tools (FR-14 phase 2). Ignored when a custom
580
+ * `backend` is set. Safe by default: with `tools` set but no policy, the default
581
+ * live-session backend installs a **fail-closed** policy (all tool calls denied) —
582
+ * supply a policy with `allow` rules / an `asker` / `{ default: 'allow' }` to let tools
583
+ * run (AFM-78).
584
+ */
585
+ permission?: PermissionPolicy;
222
586
  /** Override the live-session backend (tests inject a fake here). */
223
587
  backend?: ChatBackend;
224
588
  /** Override the one-shot summarization backend (tests inject a stub here). */
225
589
  generateFn?: GenerateFn;
226
590
  }
227
591
  /**
228
- * A stateful, auto-compacting conversation with the on-device model. Turns run
592
+ * A stateful, auto-compacting conversation with the selected model. Turns run
229
593
  * against a persistent {@link LiveSession} (one `LanguageModelSession` reused
230
594
  * across turns, FR-12) rather than replaying the transcript each turn; the
231
595
  * transcript is still held here to drive compaction, history, and reseed.
@@ -236,34 +600,57 @@ declare class ChatSession {
236
600
  private readonly keepRecentTurns;
237
601
  private readonly backend;
238
602
  private readonly generateFn;
603
+ private readonly toolNames;
239
604
  private messages;
240
605
  /** Recap of turns dropped by compaction; folded into the system prompt. */
241
606
  private summary;
242
607
  /** Instructions the backend was last `reset` with (`undefined` ⇒ needs reset). */
243
608
  private backendInstructions;
609
+ private operations;
610
+ private revision;
244
611
  constructor(config?: ChatSessionConfig);
245
612
  /** The system prompt actually sent to the model (instructions + any recap). */
246
613
  private effectiveSystem;
247
614
  /** The current transcript (a copy; mutating it does not affect the session). */
248
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
+ }>;
249
621
  /** Whether the next turn would push the transcript past the compaction bound. */
250
622
  shouldCompact(): boolean;
251
- /** Send a user turn and return the assistant's reply (streamed via `onDelta`). */
252
- send(text: string, onDelta?: DeltaHandler): Promise<string>;
623
+ /**
624
+ * Send a user turn and return the assistant's reply (streamed via `onDelta`). An
625
+ * optional `signal` interrupts the turn (FR-15, esc-to-interrupt): on abort the
626
+ * reply resolves with the partial text generated so far, and both the user prompt
627
+ * and that partial reply are kept in history. Aborting before a turn starts
628
+ * returns empty text without adding a turn.
629
+ */
630
+ send(text: string, onDelta?: DeltaHandler, signal?: AbortSignal): Promise<string>;
631
+ private sendTurn;
253
632
  /**
254
633
  * Reset the backend's session whenever the effective system prompt changes (the
255
634
  * first turn, or after a compaction), seeding it with the transcript so far.
256
635
  */
257
636
  private ensureStarted;
637
+ private runBackend;
638
+ private schedule;
639
+ private assertCurrent;
258
640
  /**
259
641
  * Fold all but the most recent turns into the rolling summary. Safe to call
260
642
  * directly; {@link send} calls it automatically when {@link shouldCompact}.
261
643
  */
262
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>;
263
650
  /** Clear the transcript and summary; optionally replace the system prompt. */
264
651
  reset(system?: string): void;
265
652
  /** Tear down the underlying live session (kills the helper process). */
266
653
  close(): void;
267
654
  }
268
655
 
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 };
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 };