apple-fm 1.0.0 → 1.2.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
@@ -102,9 +102,11 @@ declare const HELPER_BIN_ENV = "APPLE_FM_BIN";
102
102
  */
103
103
  declare function isPlatformSupported(): boolean;
104
104
  /**
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`.
105
+ * Resolve the helper binary path: an explicit `binPath`, then the `APPLE_FM_BIN`
106
+ * override (trusted as-is — an advanced/testing escape hatch), then the prebuilt
107
+ * binary bundled with the package (`bin/apple-fm-helper`), addressed by an absolute
108
+ * path relative to this module. There is **no bare-name `PATH` lookup** — the helper
109
+ * is never resolved off `PATH`, so it can't be shadowed by a planted binary (AFM-66).
108
110
  */
109
111
  declare function resolveHelperPath(options?: HelperOptions): string;
110
112
  /** Ask the helper whether the on-device model is available right now. */
@@ -118,15 +120,257 @@ declare function probe(options?: HelperOptions): Promise<ProbeResult>;
118
120
  */
119
121
  declare function generate(request: GenerateRequest, options?: HelperOptions, onDelta?: DeltaHandler, onSnapshot?: SnapshotHandler): Promise<string>;
120
122
 
123
+ /**
124
+ * Per-call permission policy for tool calling (FR-14 / AF-5 phase 2; see
125
+ * docs/10-permissions.md). Consulted by the live-session dispatcher *before* a
126
+ * tool runs. Kept entirely in Node — the Swift helper never decides policy.
127
+ *
128
+ * A request resolves to `allow` / `deny` / `ask`. `ask` prompts via an injected
129
+ * {@link PermissionAsker} (the REPL supplies one bound to readline); with no asker
130
+ * (non-interactive / piped), `ask` denies — a script never silently runs a tool. An
131
+ * "always" answer is remembered for the process lifetime.
132
+ *
133
+ * Rules are keyed by tool name, or by a finer `tool:key` so that allowing one
134
+ * command (a `bash:git status` rule) or one path (`read:/etc`) doesn't allow all of
135
+ * the tool. How a keyed rule's key matches a call's key is decided by the tool's
136
+ * {@link Tool.matchKey} — **exact equality** by default (never a prefix, so a grant
137
+ * can't be extended with shell metacharacters or `..`), `read` widening it to a
138
+ * resolved path boundary, `bash` keeping `allow` exact but making `deny` a broad
139
+ * best-effort token match (AFM-63 / AFM-67). A permissive *default* never
140
+ * blanket-approves a {@link Tool.dangerous} tool (AFM-64).
141
+ */
142
+ /** The three policy outcomes for a tool call. */
143
+ type PermissionMode = 'allow' | 'deny' | 'ask';
144
+ /** Which rule set a match is being tested against (tools may match differently). */
145
+ type RuleKind = 'allow' | 'deny';
146
+ /** How a tool's key is compared to a rule's key. Defaults to exact equality. */
147
+ type KeyMatcher = (ruleKey: string, callKey: string, kind: RuleKind) => boolean;
148
+ /** What the user chose at an interactive prompt. */
149
+ type AskOutcome = 'once' | 'always' | 'deny';
150
+ /** A pending tool call presented to the policy (and the prompt). */
151
+ interface PermissionRequest {
152
+ /** The tool name. */
153
+ tool: string;
154
+ /** A finer-grained key for this call (e.g. the path/command), if the tool gives one. */
155
+ key?: string;
156
+ /** One-line, human-readable description of the action (shown in the prompt). */
157
+ description: string;
158
+ /** The raw arguments the model generated. */
159
+ args: Record<string, unknown>;
160
+ /**
161
+ * How this tool compares a rule's key to {@link key} (from `Tool.matchKey`). Omitted
162
+ * ⇒ exact equality — a keyed rule matches only the identical key, never a prefix.
163
+ */
164
+ matchKey?: KeyMatcher;
165
+ /** High-risk tool (`Tool.dangerous`): a permissive default won't blanket-approve it. */
166
+ dangerous?: boolean;
167
+ }
168
+ /** Prompts the user to approve a call; the REPL provides this on a TTY. */
169
+ type PermissionAsker = (request: PermissionRequest) => Promise<AskOutcome>;
170
+ /** Construction options for a {@link PermissionPolicy}. */
171
+ interface PermissionPolicyConfig {
172
+ /** Decision when no rule matches (default `ask`). */
173
+ default?: PermissionMode;
174
+ /** Pre-authorized rules (`tool` or `tool:keyPrefix`), e.g. from `--allow-tool`. */
175
+ allow?: string[];
176
+ /** Denied rules (`tool` or `tool:keyPrefix`), e.g. from `--deny-tool`. */
177
+ deny?: string[];
178
+ /** Prompt on `ask`. Omitted ⇒ non-interactive: `ask` denies. */
179
+ asker?: PermissionAsker;
180
+ }
181
+ declare class PermissionPolicy {
182
+ private readonly defaultMode;
183
+ private readonly allow;
184
+ private readonly deny;
185
+ private readonly asker;
186
+ constructor(config?: PermissionPolicyConfig);
187
+ /** Whether any rule in `set` matches the request, evaluated as the given kind. */
188
+ private matches;
189
+ /**
190
+ * The static decision for a request, before any prompt. `deny` wins over `allow`. A
191
+ * permissive *default* (`allow`, e.g. `--yes`) does **not** cover a `dangerous` tool:
192
+ * it downgrades to `ask` so a blanket approval can't silently grant `bash` arbitrary
193
+ * command execution (AFM-64). An explicit allow rule still grants it.
194
+ */
195
+ decide(request: PermissionRequest): PermissionMode;
196
+ /** Remember an "always" approval for this call (process lifetime). */
197
+ private remember;
198
+ /**
199
+ * Decide whether a call may proceed, prompting on `ask` and remembering an
200
+ * "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.
203
+ */
204
+ authorize(request: PermissionRequest): Promise<boolean>;
205
+ }
206
+
207
+ /**
208
+ * Types for tool calling (FR-14 / AF-5 phase 1; see docs/9-tool-calling.md).
209
+ *
210
+ * A {@link Tool} is a Node-side capability the on-device model can invoke
211
+ * mid-generation. The model decides *when* to call a tool; the Swift helper runs
212
+ * the framework's tool-call loop and round-trips each invocation back to Node — the
213
+ * tool's `run` executes here, where typed logic, tests, and (phase 2) permission
214
+ * checks live. Only the Node layer ever implements a tool; the helper carries the
215
+ * call across the wire.
216
+ */
217
+ /**
218
+ * Context handed to {@link Tool.run}. Intentionally minimal in phase 1; phase 2
219
+ * threads the permission decision and (later) cancellation through here.
220
+ */
221
+ interface ToolContext {
222
+ /** Aborts the in-flight tool when the turn is torn down (reserved; unused in phase 1). */
223
+ signal?: AbortSignal;
224
+ }
225
+ /**
226
+ * A tool the model can call. `parameters` is a JSON Schema for the call arguments,
227
+ * expressed in the same subset the helper compiles for guided generation (FR-8;
228
+ * see docs/6-guided-generation.md) — it becomes the tool's native `GenerationSchema`
229
+ * so the model can only produce valid arguments.
230
+ */
231
+ interface Tool {
232
+ /** Unique tool name the model references (e.g. `read`). */
233
+ name: string;
234
+ /** What the tool does — shown to the model so it knows when to call it. */
235
+ description: string;
236
+ /** JSON Schema (the guided-generation subset) for the call arguments. */
237
+ parameters: unknown;
238
+ /**
239
+ * Execute the call. `args` is the object the model generated (already validated
240
+ * against `parameters` by the framework). Return the textual result fed back to
241
+ * the model. Throw to signal the call failed — the model is told and may continue.
242
+ */
243
+ run(args: Record<string, unknown>, ctx: ToolContext): Promise<string>;
244
+ /**
245
+ * Optional finer-grained permission key for a call (e.g. the file path for `read`,
246
+ * the command for `bash`). Used to scope allow/deny rules and "always" grants
247
+ * below the whole tool (FR-14 phase 2). Omitted ⇒ rules apply at the tool level.
248
+ */
249
+ permissionKey?(args: Record<string, unknown>): string | undefined;
250
+ /** Optional one-line description of a call, shown in the permission prompt. */
251
+ describe?(args: Record<string, unknown>): string;
252
+ /**
253
+ * Optional: does a permission rule's key match this call's key, for the given rule
254
+ * kind? Lets a tool define *safe* semantics for its own key type instead of the
255
+ * generic default. `bash` requires an **exact** command for an `allow` (a grant for
256
+ * `ls` never extends to `ls; rm -rf ~`) but a broad best-effort token match for a
257
+ * `deny`; `read` treats the key as a filesystem boundary (a directory grant covers
258
+ * its descendants, after resolving `..`). Omitted ⇒ the policy matches keys by
259
+ * **exact equality** — the safe default, never a prefix. (FR-14; AFM-63 / AFM-67.)
260
+ */
261
+ matchKey?(ruleKey: string, callKey: string, kind: 'allow' | 'deny'): boolean;
262
+ /**
263
+ * Optional: mark the tool as high-risk (e.g. `bash`, which runs arbitrary shell
264
+ * commands). A permissive policy **default** (`--yes`) does not blanket-approve a
265
+ * dangerous tool — it still requires an explicit allow rule or an interactive
266
+ * approval — so a single `--yes` can't silently hand the untrusted model arbitrary
267
+ * command execution. (FR-14; AFM-64.)
268
+ */
269
+ dangerous?: boolean;
270
+ /**
271
+ * Optional one-line hint telling the model *when* to use this tool, folded into the
272
+ * auto-injected tool-use system prompt (CLI only; see `toolGuidancePrompt`). Without
273
+ * it, the tool's `name`/`description` are used.
274
+ */
275
+ usageHint?: string;
276
+ }
277
+ /**
278
+ * The wire shape of a tool sent to the helper on a turn command (`tools[]`). Just
279
+ * the model-facing surface — never the `run` implementation, which stays in Node.
280
+ */
281
+ interface ToolDefinition {
282
+ name: string;
283
+ description: string;
284
+ parameters: unknown;
285
+ }
286
+
287
+ /**
288
+ * A registry of the tools exposed to a session. The extensibility seam for
289
+ * FR-14 / AF-5: a library consumer registers their own {@link Tool}s, the CLI
290
+ * enables built-ins by name. The registry emits the model-facing
291
+ * {@link ToolDefinition}s onto each turn command and dispatches an incoming
292
+ * `tool_call` to the matching tool's `run`.
293
+ */
294
+
295
+ declare class ToolRegistry {
296
+ private readonly tools;
297
+ constructor(tools?: Tool[]);
298
+ /** Register (or replace) a tool by name. */
299
+ register(tool: Tool): void;
300
+ /** Whether a tool with this name is registered. */
301
+ has(name: string): boolean;
302
+ /** Number of registered tools (0 ⇒ no `tools[]` is sent on a turn). */
303
+ get size(): number;
304
+ /** The model-facing definitions sent to the helper on a turn command. */
305
+ definitions(): ToolDefinition[];
306
+ /** The registered tool names (for the REPL `/tools` listing). */
307
+ names(): string[];
308
+ /** One usage hint per tool (its `usageHint`, or a `name: description` fallback). */
309
+ usageHints(): string[];
310
+ /**
311
+ * Build a {@link PermissionRequest} for a call, using the tool's optional
312
+ * `permissionKey` / `describe` hooks. Returns `undefined` for an unknown tool.
313
+ */
314
+ permissionRequest(name: string, args: Record<string, unknown>): PermissionRequest | undefined;
315
+ /**
316
+ * Run a tool by name. Throws (with a clear message) if no such tool is
317
+ * registered, so the dispatcher can surface a `tool_error` to the model.
318
+ */
319
+ run(name: string, args: Record<string, unknown>, ctx?: ToolContext): Promise<string>;
320
+ }
321
+
322
+ declare const bashTool: Tool;
323
+
324
+ declare const readTool: Tool;
325
+
326
+ /** The built-in tools, keyed by name. All run locally — apple-fm makes no network calls. */
327
+ declare const BUILTIN_TOOLS: Readonly<Record<string, Tool>>;
328
+ /**
329
+ * A short system-prompt preamble telling the model it has tools and should use them
330
+ * rather than refuse — built from the registry's enabled tools. The CLI injects this
331
+ * when `--tools` is set (merged with any `-s`) so the small on-device model knows
332
+ * *when* to call a tool instead of falling back on a "can't access files" refusal.
333
+ * Returns `''` for an empty registry. (Library consumers can use it too; the library
334
+ * itself stays unopinionated.)
335
+ */
336
+ declare function toolGuidancePrompt(registry: ToolRegistry): string;
337
+ /**
338
+ * Build a registry from built-in tool names (e.g. the CLI's `--tools read`).
339
+ * Throws on an unknown name so a typo is a clear error rather than a silent no-op.
340
+ */
341
+ declare function registryFromNames(names: string[]): ToolRegistry;
342
+
121
343
  /** Construction options for a {@link LiveSession}. */
122
344
  interface LiveSessionConfig extends HelperOptions {
123
345
  /** Generation knobs forwarded with every turn. */
124
346
  options?: GenerateOptions;
347
+ /**
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.
350
+ */
351
+ tools?: ToolRegistry;
352
+ /**
353
+ * Per-call permission policy consulted before each tool runs (FR-14 phase 2).
354
+ *
355
+ * **Safe by default (AFM-78):** when {@link tools} are registered and this is
356
+ * omitted, the session installs a **fail-closed** policy (default `ask`, no asker ⇒
357
+ * every tool call is denied) rather than running tools ungated. So a `tool_call` —
358
+ * including one emitted by a compromised/replaced helper — never runs without an
359
+ * explicit decision. To actually let tools run, supply a policy with `allow` rules,
360
+ * an interactive `asker`, or `{ default: 'allow' }` (a deliberate opt-in; a `dangerous`
361
+ * tool like `bash` still requires an explicit allow — AFM-64). A refused call is fed
362
+ * back to the model as the tool result.
363
+ */
364
+ permission?: PermissionPolicy;
125
365
  }
126
366
  /** The backend contract that `ChatSession` drives. */
127
367
  interface ChatBackend {
128
- /** Send one user turn; prior turns stay in the session's context. */
129
- send(text: string, onDelta?: DeltaHandler): Promise<string>;
368
+ /**
369
+ * Send one user turn; prior turns stay in the session's context. An optional
370
+ * `signal` interrupts the in-flight turn (FR-15, esc-to-interrupt): on abort the
371
+ * turn is cancelled and resolves with the partial text generated so far.
372
+ */
373
+ send(text: string, onDelta?: DeltaHandler, signal?: AbortSignal): Promise<string>;
130
374
  /** Recreate the underlying session with new instructions + seed turns. */
131
375
  reset(system: string, seed: Message[]): Promise<void>;
132
376
  /** Tear down the backend. */
@@ -136,6 +380,8 @@ declare class LiveSession implements ChatBackend {
136
380
  private readonly command;
137
381
  private readonly timeoutMs;
138
382
  private readonly options;
383
+ private readonly tools;
384
+ private readonly permission;
139
385
  /** Whether we'd spawn the bundled macOS helper (subject to the platform gate). */
140
386
  private readonly bundled;
141
387
  private child;
@@ -143,19 +389,38 @@ declare class LiveSession implements ChatBackend {
143
389
  private nextId;
144
390
  private readonly pending;
145
391
  constructor(config?: LiveSessionConfig);
146
- /** Recreate the underlying session with new instructions + seed turns. */
392
+ /**
393
+ * Recreate the underlying session with new instructions + seed turns. Tool
394
+ * definitions ride on `reset` because the framework binds tools at session
395
+ * construction (not per turn); the helper builds the session's tools here.
396
+ */
147
397
  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>;
398
+ /**
399
+ * Send one user turn; prior turns stay in context. Streams via `onDelta`. An
400
+ * optional `signal` interrupts the turn: on abort a `cancel` command is sent and
401
+ * the helper ends the turn with the partial text generated so far (FR-15).
402
+ */
403
+ send(text: string, onDelta?: DeltaHandler, signal?: AbortSignal): Promise<string>;
150
404
  /** Tear down the helper process and reject any in-flight commands. */
151
405
  close(): void;
152
406
  private rejectAll;
153
407
  private ensureChild;
154
408
  private onStdout;
155
409
  private onLine;
410
+ /**
411
+ * Dispatch a `tool_call` to the registered tool and write the outcome back to the
412
+ * helper, keyed by `callId`. Runs concurrently with the still-open turn; the tool
413
+ * 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.
415
+ */
416
+ private handleToolCall;
417
+ /** Restart a pending turn's timeout (e.g. across a tool call). */
418
+ private restartTimer;
156
419
  private settle;
157
420
  private fail;
158
421
  private dispatch;
422
+ /** Ask the helper to cancel an in-flight turn (no-op if it already settled). */
423
+ private cancel;
159
424
  }
160
425
 
161
426
  /**
@@ -219,6 +484,16 @@ interface ChatSessionConfig {
219
484
  keepRecentTurns?: number;
220
485
  /** Helper discovery / timeout options (used for the default backend + summarizer). */
221
486
  helper?: HelperOptions;
487
+ /** Tools the model may call mid-turn (FR-14). Ignored when a custom `backend` is set. */
488
+ tools?: ToolRegistry;
489
+ /**
490
+ * Per-call permission policy for tools (FR-14 phase 2). Ignored when a custom
491
+ * `backend` is set. Safe by default: with `tools` set but no policy, the default
492
+ * live-session backend installs a **fail-closed** policy (all tool calls denied) —
493
+ * supply a policy with `allow` rules / an `asker` / `{ default: 'allow' }` to let tools
494
+ * run (AFM-78).
495
+ */
496
+ permission?: PermissionPolicy;
222
497
  /** Override the live-session backend (tests inject a fake here). */
223
498
  backend?: ChatBackend;
224
499
  /** Override the one-shot summarization backend (tests inject a stub here). */
@@ -248,8 +523,13 @@ declare class ChatSession {
248
523
  history(): Message[];
249
524
  /** Whether the next turn would push the transcript past the compaction bound. */
250
525
  shouldCompact(): boolean;
251
- /** Send a user turn and return the assistant's reply (streamed via `onDelta`). */
252
- send(text: string, onDelta?: DeltaHandler): Promise<string>;
526
+ /**
527
+ * Send a user turn and return the assistant's reply (streamed via `onDelta`). An
528
+ * optional `signal` interrupts the turn (FR-15, esc-to-interrupt): on abort the
529
+ * 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).
531
+ */
532
+ send(text: string, onDelta?: DeltaHandler, signal?: AbortSignal): Promise<string>;
253
533
  /**
254
534
  * Reset the backend's session whenever the effective system prompt changes (the
255
535
  * first turn, or after a compaction), seeding it with the transcript so far.
@@ -266,4 +546,4 @@ declare class ChatSession {
266
546
  close(): void;
267
547
  }
268
548
 
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 };
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 };