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/README.md CHANGED
@@ -2,24 +2,17 @@
2
2
 
3
3
  **Apple Intelligence from your command line and your code.** apple-fm gives you
4
4
  the on-device **Foundation Models** on **macOS 26+ / Apple Silicon** — free,
5
- private, and fully offline. No API key, no network, nothing leaves your Mac.
5
+ private, and fully offline. No API key, no cloud, no network — your prompts never
6
+ leave your Mac.
6
7
 
7
- Apple ships `FoundationModels` as a Swift-only framework with no command-line
8
- front-end. apple-fm provides one: a tiny Swift helper does the model work, and a
9
- tested, **zero-runtime-dependency** Node layer gives you a CLI and a library.
8
+ Apple ships these models as a Swift-only framework with no command-line
9
+ front-end. apple-fm provides one — a fast, lightweight CLI and a TypeScript
10
+ library, so you can use the on-device model from your terminal or your code.
10
11
 
11
12
  <p align="center">
12
- <img src="assets/demos/generate.svg" alt="apple-fm generate &quot;Explain a closure in one sentence.&quot; runs Apple's on-device model and prints the answer — fully offline, no API key." width="820">
13
+ <img src="assets/demos/generate.svg" alt="apple-fm generate &quot;Explain a closure in one sentence.&quot; runs Apple's on-device model and prints the answer — fully offline, no API key." width="880">
13
14
  </p>
14
15
 
15
- > ℹ️ **Status.** Published to npm with a Developer-ID **signed + notarized**
16
- > helper, and smoke-verified on a macOS 26 / Apple Intelligence machine — probe,
17
- > generate (freeform / guided / streamed), native guaranteed-structure output, and
18
- > persistent multi-turn chat all work on-device. The one tracked gap is an
19
- > automated on-device *generation* test in CI: hosted runners build, sign, and
20
- > notarize the helper but can't run the model (it needs Apple Intelligence). See
21
- > [docs/3-requirements.md](docs/3-requirements.md).
22
-
23
16
  ## Why apple-fm
24
17
 
25
18
  - **On-device & private.** Runs on the model Apple Intelligence already
@@ -34,9 +27,13 @@ tested, **zero-runtime-dependency** Node layer gives you a CLI and a library.
34
27
  - **Long conversations stay coherent — and cheap.** `chat` holds one on-device
35
28
  session across turns, reusing the model's cache instead of replaying the
36
29
  transcript, and automatically summarizes older turns as the small context
37
- window fills.
38
- - **Zero runtime dependencies.** The Node layer only spawns the helper and speaks
39
- JSON. Strict TypeScript, ESM, lint-clean.
30
+ window fills. Press **Esc** to interrupt a reply mid-stream — the partial is kept.
31
+ - **The model can use tools — locally.** Opt `chat` into permission-gated `read`
32
+ and `bash` tools (`--tools read,bash`) so the model can read a file or run a
33
+ command to answer you. Every call is approved per-use, and it's all on your
34
+ machine — still no network. Register your own `Tool` from the library, too.
35
+ - **Lightweight, nothing to audit.** Zero runtime dependencies — apple-fm just
36
+ talks to the on-device model and gets out of your way.
40
37
  - **Future-proof.** The helper resolves the current on-device model at runtime,
41
38
  so OS and model updates are picked up without a rebuild.
42
39
 
@@ -47,15 +44,9 @@ npm install -g apple-fm # CLI
47
44
  npm install apple-fm # library
48
45
  ```
49
46
 
50
- Requires macOS 26+ on Apple Silicon with Apple Intelligence enabled. Releases
51
- bundle a signed + notarized helper; you can also build it from source:
52
-
53
- ```bash
54
- npm run build:helper # → bin/apple-fm-helper (needs Xcode 26 / macOS 26 SDK)
55
- ```
56
-
57
- The helper is located via `APPLE_FM_BIN`, then the bundled `bin/apple-fm-helper`,
58
- then `apple-fm-helper` on `PATH`.
47
+ Requires macOS 26+ on Apple Silicon with Apple Intelligence enabled. Every
48
+ release is Developer-ID signed and notarized, so it runs without security
49
+ prompts.
59
50
 
60
51
  ### Platform support
61
52
 
@@ -85,6 +76,7 @@ cat notes.md | apple-fm generate # read the prompt from stdin
85
76
  apple-fm generate "…" --stream # stream tokens as they arrive
86
77
  apple-fm generate "…" --schema shape.json # structured/guided JSON output
87
78
  apple-fm chat # interactive chat (streamed, auto-compacted)
79
+ apple-fm chat --tools read,bash # let the model read files / run commands (gated)
88
80
  ```
89
81
 
90
82
  Run `apple-fm --help` for the full flag list.
@@ -94,7 +86,7 @@ Run `apple-fm --help` for the full flag list.
94
86
  Before generating, confirm Apple Intelligence is ready on this machine.
95
87
 
96
88
  <p align="center">
97
- <img src="assets/demos/probe.svg" alt="apple-fm probe prints {&quot;available&quot;:true} when the on-device model is ready, or a reason like appleIntelligenceNotEnabled when it isn't." width="820">
89
+ <img src="assets/demos/probe.svg" alt="apple-fm probe prints {&quot;available&quot;:true} when the on-device model is ready, or a reason like appleIntelligenceNotEnabled when it isn't." width="880">
98
90
  </p>
99
91
 
100
92
  ### Structured output
@@ -104,19 +96,35 @@ conform** to it — native guided generation, not prompt-and-hope — ready to p
104
96
  into the rest of your tooling.
105
97
 
106
98
  <p align="center">
107
- <img src="assets/demos/schema.svg" alt="apple-fm generate &quot;Recommend a classic sci-fi novel.&quot; --schema novel.json returns a JSON object with title, author, year, and why fields." width="820">
99
+ <img src="assets/demos/schema.svg" alt="apple-fm generate &quot;Recommend a classic sci-fi novel.&quot; --schema novel.json returns a JSON object with title, author, year, and why fields." width="880">
108
100
  </p>
109
101
 
110
102
  ### Interactive chat
111
103
 
112
104
  `chat` is a multi-turn REPL that streams replies and compacts the transcript
113
105
  automatically near the context window. Built-in slash commands: `/reset`,
114
- `/system`, `/clear`, `/compact`, `/help`, `/quit`.
106
+ `/system`, `/clear`, `/compact`, `/help`, `/quit`. Press **Esc** while the model is
107
+ replying to interrupt it (the partial reply is kept in context).
115
108
 
116
109
  <p align="center">
117
- <img src="assets/demos/chat.svg" alt="apple-fm chat answers a prompt, then /help lists the slash commands: /reset, /system, /clear, /compact, /help, /quit." width="820">
110
+ <img src="assets/demos/chat.svg" alt="apple-fm chat answers a prompt, then /help lists the slash commands (/reset, /system, /clear, /compact, /help, /quit) and notes that Esc interrupts a reply." width="880">
118
111
  </p>
119
112
 
113
+ ### Tool calling
114
+
115
+ Opt `chat` into built-in tools and the on-device model can call them mid-reply to
116
+ answer you — `read` (read a local file) and `bash` (run a shell command):
117
+
118
+ ```bash
119
+ apple-fm chat --tools read,bash
120
+ ```
121
+
122
+ Every call is **permission-gated**: you approve each one (`[y/N/a]`), or pre-approve
123
+ with `--allow-tool "bash:git "` / auto-approve with `--yes`; non-interactive runs
124
+ deny by default, so a script never silently runs a command. It stays **fully local** —
125
+ tools run on your machine and nothing hits the network. Library consumers can register
126
+ their own `Tool` (see [docs/9-tool-calling.md](docs/9-tool-calling.md)).
127
+
120
128
  ## Library
121
129
 
122
130
  ```ts
@@ -143,23 +151,20 @@ documented in [docs/ai/code-summary.md](docs/ai/code-summary.md).
143
151
 
144
152
  ## How it works
145
153
 
146
- A single binary, three shapes (probe / generate / chat), all over one
147
- line-delimited JSON protocol ([docs/4-protocol.md](docs/4-protocol.md)). Only the
148
- Swift helper imports `FoundationModels`; all policy — argument parsing, the wire
149
- protocol, chat history, auto-compaction — lives in strict TypeScript and is
150
- unit-tested against a stub helper, so the suite runs on any platform. For chat the
151
- helper holds one `LanguageModelSession` across turns (so the model's cache is
152
- reused instead of replaying the transcript), while the Node side keeps the
153
- transcript so it can summarize older turns as the small context window fills — so
154
- long conversations stay coherent and cheap. Because the helper resolves the
155
- current on-device model at runtime, OS and model updates are picked up without a
156
- rebuild.
154
+ apple-fm talks to the same on-device model that powers Apple Intelligence —
155
+ nothing is sent to the cloud. For chat it keeps one model session alive across
156
+ turns so replies stay fast, and automatically summarizes older messages as the
157
+ context window fills, so long conversations stay coherent and cheap. And because
158
+ it resolves the current on-device model at runtime, OS and model updates are
159
+ picked up automatically — no reinstall.
157
160
 
158
161
  ## Documentation
159
162
 
160
- - [Overview](docs/1-overview.md) · [Architecture](docs/2-architecture.md) ·
161
- [Requirements](docs/3-requirements.md) · [Protocol](docs/4-protocol.md) ·
162
- [Releasing](docs/5-releasing.md)
163
+ - [Overview](docs/1-overview.md) — what apple-fm is and its principles
164
+ - [Architecture](docs/2-architecture.md) — module layout and data flow
165
+ - [Wire protocol](docs/4-protocol.md) — the NDJSON helper ⇄ Node protocol
166
+ - [Requirements](docs/3-requirements.md) — every feature and its status
167
+ - [Tool calling](docs/9-tool-calling.md) — the extensible, permission-gated tool system
163
168
 
164
169
  ## Disclaimer
165
170
 
@@ -0,0 +1,112 @@
1
+ // Tool calling (FR-14 / AF-5; see docs/9-tool-calling.md). The on-device model can
2
+ // call tools, but apple-fm's tools (read/bash/web) live in the Node layer — typed,
3
+ // tested, and (phase 2) permission-checked. So one generic `DynamicTool` represents
4
+ // any Node-defined tool: its arguments schema is the caller's JSON Schema compiled to
5
+ // a native `GenerationSchema` (reusing the guided-generation translation, FR-8), and
6
+ // its `call` round-trips the invocation to Node over NDJSON via the `ToolBridge`.
7
+ //
8
+ // Part of apple-fm-helper (see main.swift) — all the .swift files compile into one
9
+ // binary.
10
+ import Foundation
11
+ import FoundationModels
12
+
13
+ /// A tool as it arrives on the wire (the `reset` command's `tools[]`): the
14
+ /// model-facing surface plus the JSON Schema for its arguments. The `call`
15
+ /// implementation is never sent — it stays in Node.
16
+ struct WireTool: Decodable {
17
+ let name: String
18
+ let description: String
19
+ let parameters: JSONValue
20
+ }
21
+
22
+ /// What Node sends back for a tool call: the textual result, or a failure message.
23
+ enum ToolReply {
24
+ case result(String)
25
+ case error(String)
26
+ }
27
+
28
+ /// Thrown when Node reports a tool call failed. The framework surfaces it to the
29
+ /// model, which can continue without that tool.
30
+ struct ToolCallError: Error, CustomStringConvertible {
31
+ let message: String
32
+ var description: String { message }
33
+ }
34
+
35
+ /// Bridges a model-invoked tool call out to Node and back. A `DynamicTool` can't run
36
+ /// the tool itself, so each `call` emits a `tool_call` event and suspends until Node
37
+ /// replies with a `tool_result` / `tool_error` (matched by `callId`). Modeled as an
38
+ /// actor so the stdin reader and the in-flight turn touch it safely; `callId`s are
39
+ /// `"<turnId>:<n>"`.
40
+ actor ToolBridge {
41
+ private var turnId: String?
42
+ private var counter = 0
43
+ private var waiters: [String: CheckedContinuation<ToolReply, Never>] = [:]
44
+
45
+ /// Mark the start of a turn so emitted `tool_call` events carry its id and the
46
+ /// per-turn call counter restarts.
47
+ func beginTurn(_ id: String?) {
48
+ turnId = id
49
+ counter = 0
50
+ }
51
+
52
+ /// Emit a `tool_call` for `name`/`argumentsJSON` and suspend until Node replies.
53
+ func call(name: String, argumentsJSON: String) async -> ToolReply {
54
+ counter += 1
55
+ let callId = "\(turnId ?? "0"):\(counter)"
56
+ return await withCheckedContinuation { continuation in
57
+ // Register the waiter BEFORE emitting, so a fast `tool_result` can't race
58
+ // ahead: `resolve` is actor-isolated and can't run until this body
59
+ // suspends, by which point the waiter is already stored.
60
+ waiters[callId] = continuation
61
+ emitToolCall(name: name, callId: callId, argumentsJSON: argumentsJSON, id: turnId)
62
+ }
63
+ }
64
+
65
+ /// Resume the suspended call matching `callId` (a no-op if unknown — e.g. a stale
66
+ /// or duplicate reply).
67
+ func resolve(callId: String, reply: ToolReply) {
68
+ guard let continuation = waiters.removeValue(forKey: callId) else { return }
69
+ continuation.resume(returning: reply)
70
+ }
71
+ }
72
+
73
+ /// A generic tool standing in for any Node-defined tool. `parameters` is provided
74
+ /// explicitly (the compiled caller schema) rather than derived from `Arguments`,
75
+ /// since `Arguments` is the dynamic `GeneratedContent` carrier.
76
+ struct DynamicTool: Tool {
77
+ typealias Arguments = GeneratedContent
78
+ typealias Output = String
79
+
80
+ let name: String
81
+ let description: String
82
+ let parameters: GenerationSchema
83
+ let bridge: ToolBridge
84
+
85
+ func call(arguments: GeneratedContent) async throws -> String {
86
+ let reply = await bridge.call(name: name, argumentsJSON: arguments.jsonString)
87
+ switch reply {
88
+ case .result(let content):
89
+ return content
90
+ case .error(let message):
91
+ throw ToolCallError(message: message)
92
+ }
93
+ }
94
+ }
95
+
96
+ /// Compile wire tool defs into `DynamicTool`s. A tool whose argument schema can't be
97
+ /// expressed natively is skipped with an `unsupportedSchema` diagnostic rather than
98
+ /// failing the whole session — the other tools still work.
99
+ func buildTools(_ defs: [WireTool], bridge: ToolBridge) -> [any Tool] {
100
+ var tools: [any Tool] = []
101
+ for def in defs {
102
+ do {
103
+ let schema = try compileSchema(from: def.parameters)
104
+ tools.append(DynamicTool(name: def.name, description: def.description, parameters: schema, bridge: bridge))
105
+ } catch let error as UnsupportedSchema {
106
+ emitError("unsupportedSchema", "tool \(def.name): \(error.message)", id: nil)
107
+ } catch {
108
+ emitError("unsupportedSchema", "tool \(def.name): could not build a generation schema", id: nil)
109
+ }
110
+ }
111
+ return tools
112
+ }
@@ -120,8 +120,16 @@ private func emitSnapshot(_ content: String, id: String? = nil) {
120
120
  emit("{\"type\":\"snapshot\"\(idField(id)),\"content\":\(encodeString(content))}")
121
121
  }
122
122
 
123
- /// Emit an error event without exiting (used per-turn in `--session`).
124
- private func emitError(_ code: String, _ message: String, id: String?) {
123
+ /// A tool the model invoked mid-turn. `argumentsJSON` is embedded as raw JSON (the
124
+ /// model's generated arguments), not a string. `internal` so `ToolBridge` (in
125
+ /// Tools.swift) can call it. See docs/9-tool-calling.md.
126
+ func emitToolCall(name: String, callId: String, argumentsJSON: String, id: String?) {
127
+ emit("{\"type\":\"tool_call\"\(idField(id)),\"callId\":\(encodeString(callId)),\"name\":\(encodeString(name)),\"arguments\":\(argumentsJSON)}")
128
+ }
129
+
130
+ /// Emit an error event without exiting (used per-turn in `--session`). `internal` so
131
+ /// `buildTools` (in Tools.swift) can report an unsupported tool schema.
132
+ func emitError(_ code: String, _ message: String, id: String?) {
125
133
  emit("{\"type\":\"error\"\(idField(id)),\"code\":\(encodeString(code)),\"message\":\(encodeString(message))}")
126
134
  }
127
135
 
@@ -230,10 +238,9 @@ private func generate(_ request: GenerateRequest) async -> Never {
230
238
  emitResult(response.content.jsonString)
231
239
  }
232
240
  exit(0)
233
- } catch let error as LanguageModelSession.GenerationError {
234
- failEvent(errorCode(error), String(describing: error))
235
241
  } catch {
236
- failEvent("inferenceFailed", String(describing: error))
242
+ let f = failure(for: error)
243
+ failEvent(f.code, f.message)
237
244
  }
238
245
  }
239
246
 
@@ -254,19 +261,58 @@ private func generate(_ request: GenerateRequest) async -> Never {
254
261
  emitResult(response.content)
255
262
  }
256
263
  exit(0)
257
- } catch let error as LanguageModelSession.GenerationError {
258
- failEvent(errorCode(error), String(describing: error))
259
264
  } catch {
260
- failEvent("inferenceFailed", String(describing: error))
265
+ let f = failure(for: error)
266
+ failEvent(f.code, f.message)
261
267
  }
262
268
  }
263
269
 
264
- private func errorCode(_ error: LanguageModelSession.GenerationError) -> String {
265
- switch error {
266
- case .exceededContextWindowSize: return "contextWindowExceeded"
267
- case .guardrailViolation: return "guardrailViolation"
268
- default: return "generationError"
270
+ /// Collect an NSError and every error nested under it (`NSUnderlyingErrorKey` plus
271
+ /// the `NSMultipleUnderlyingErrorsKey` array), breadth-first, outermost first.
272
+ /// Bounded so a pathological cycle can't spin forever.
273
+ private func errorChain(_ error: Error) -> [NSError] {
274
+ var collected: [NSError] = []
275
+ var queue: [NSError] = [error as NSError]
276
+ while let next = queue.first, collected.count < 50 {
277
+ queue.removeFirst()
278
+ collected.append(next)
279
+ if let underlying = next.userInfo[NSUnderlyingErrorKey] as? NSError {
280
+ queue.append(underlying)
281
+ }
282
+ if let multiple = next.userInfo[NSMultipleUnderlyingErrorsKey] as? [Error] {
283
+ queue.append(contentsOf: multiple.map { $0 as NSError })
284
+ }
285
+ }
286
+ return collected
287
+ }
288
+
289
+ /// Reduce a thrown error to a wire `(code, message)`. The framework wraps the real
290
+ /// cause in nested NSErrors, so: recognize "model still provisioning"
291
+ /// (`ModelManagerError` 1008 — which can occur even though `availability` reported
292
+ /// `.available`); honor the typed `GenerationError` cases; otherwise collapse the
293
+ /// chain to its innermost `domain Code=n` rather than emitting the whole multi-level
294
+ /// NSError dump. See docs/4-protocol.md (error codes).
295
+ private func failure(for error: Error) -> (code: String, message: String) {
296
+ let chain = errorChain(error)
297
+ if chain.contains(where: { $0.domain.contains("ModelManagerError") && $0.code == 1008 }) {
298
+ return ("modelNotReady", "the on-device model is still provisioning; try again shortly")
299
+ }
300
+ if let generation = error as? LanguageModelSession.GenerationError {
301
+ switch generation {
302
+ case .exceededContextWindowSize:
303
+ return ("contextWindowExceeded", "the model's context window was exceeded")
304
+ case .guardrailViolation:
305
+ return ("guardrailViolation", "the request was blocked by the model's safety guardrails")
306
+ default:
307
+ break
308
+ }
269
309
  }
310
+ let innermost = chain.last ?? (error as NSError)
311
+ let summary = "\(innermost.domain) Code=\(innermost.code)"
312
+ // A typed-but-unmatched generation error is still a generation-side failure;
313
+ // anything else is a generic inference failure.
314
+ let code = error is LanguageModelSession.GenerationError ? "generationError" : "inferenceFailed"
315
+ return (code, summary)
270
316
  }
271
317
 
272
318
  // MARK: - Session (persistent live session)
@@ -281,6 +327,13 @@ struct SessionCommand: Decodable {
281
327
  let prompt: String?
282
328
  let options: WireOptions?
283
329
  let stream: Bool?
330
+ // Tool calling (FR-14): `tools` rides on a `reset` (the framework binds tools at
331
+ // session construction); `callId`/`content`/`message` carry a tool outcome back
332
+ // into a suspended `tool_call`. See docs/9-tool-calling.md.
333
+ let tools: [WireTool]?
334
+ let callId: String?
335
+ let content: String?
336
+ let message: String?
284
337
  }
285
338
 
286
339
  /// Compose session instructions from a system prompt plus any seed turns, folded
@@ -298,14 +351,20 @@ private func sessionInstructions(system: String?, seed: [WireMessage]?) -> Strin
298
351
  return parts.isEmpty ? nil : parts.joined(separator: "\n\n")
299
352
  }
300
353
 
301
- /// Run one turn against the held session, emitting id-tagged events.
354
+ /// Run one turn against the held session, emitting id-tagged events. The turn runs
355
+ /// as a cancellable task (see `runSession`): a `cancel` command cancels it, and the
356
+ /// turn ends cleanly by emitting a `result` carrying the partial text generated so
357
+ /// far — *not* an `error` — so the Node side (which requested the cancel) settles the
358
+ /// turn and keeps the partial reply (FR-15; esc-to-interrupt). See docs/4-protocol.md.
302
359
  private func sessionTurn(_ session: LanguageModelSession, _ command: SessionCommand) async {
303
360
  let prompt = command.prompt ?? ""
304
361
  let options = generationOptions(command.options)
362
+ var emitted = ""
305
363
  do {
306
364
  if command.stream == true {
307
- var emitted = ""
308
365
  for try await partial in session.streamResponse(to: prompt, options: options) {
366
+ // Cooperative cancellation: stop streaming and report the partial.
367
+ if Task.isCancelled { break }
309
368
  let full = partial.content
310
369
  if full.count > emitted.count {
311
370
  emitDelta(String(full.dropFirst(emitted.count)), id: command.id)
@@ -317,22 +376,50 @@ private func sessionTurn(_ session: LanguageModelSession, _ command: SessionComm
317
376
  let response = try await session.respond(to: prompt, options: options)
318
377
  emitResult(response.content, id: command.id)
319
378
  }
320
- } catch let error as LanguageModelSession.GenerationError {
321
- emitError(errorCode(error), String(describing: error), id: command.id)
379
+ } catch is CancellationError {
380
+ emitResult(emitted, id: command.id)
322
381
  } catch {
323
- emitError("inferenceFailed", String(describing: error), id: command.id)
382
+ // A cancelled stream can surface as a generic framework error rather than a
383
+ // typed CancellationError; treat any error on a cancelled turn as the same
384
+ // clean partial-result interrupt.
385
+ if Task.isCancelled {
386
+ emitResult(emitted, id: command.id)
387
+ } else {
388
+ let f = failure(for: error)
389
+ emitError(f.code, f.message, id: command.id)
390
+ }
324
391
  }
325
392
  }
326
393
 
394
+ /// Build the session for a `reset`: with the command's tools when any are offered,
395
+ /// otherwise the plain session. Tools are bound at construction (the framework's
396
+ /// model), so they ride on `reset`, not each turn.
397
+ private func makeSession(_ command: SessionCommand, bridge: ToolBridge) -> LanguageModelSession {
398
+ let instructions = sessionInstructions(system: command.system, seed: command.seed)
399
+ let tools = buildTools(command.tools ?? [], bridge: bridge)
400
+ if tools.isEmpty {
401
+ return LanguageModelSession(instructions: instructions)
402
+ }
403
+ return LanguageModelSession(tools: tools, instructions: instructions)
404
+ }
405
+
327
406
  /// Hold one `LanguageModelSession` across many turns (KV-cache reuse). Reads one
328
- /// command per stdin line, serially, and exits 0 on EOF. A turn error is reported
329
- /// per-turn and does not end the loop; a `reset` recreates the session with new
330
- /// instructions + seed and acks with `ready`.
407
+ /// command per stdin line and exits 0 on EOF. A turn error is reported per-turn and
408
+ /// does not end the loop; a `reset` recreates the session with new instructions +
409
+ /// seed (+ tools) and acks with `ready`.
410
+ ///
411
+ /// Turns are serial, but the model may call a tool mid-turn — so a turn runs as a
412
+ /// detached task while the reader keeps reading, delivering the `tool_result` /
413
+ /// `tool_error` lines into the suspended `tool_call` via the `ToolBridge`. The next
414
+ /// turn waits on the previous task, so only one turn is ever live. See
415
+ /// docs/9-tool-calling.md.
331
416
  private func runSession() async -> Never {
332
417
  guard case .available = SystemLanguageModel.default.availability else {
333
418
  failEvent("unavailable", "Apple Foundation Models unavailable")
334
419
  }
420
+ let bridge = ToolBridge()
335
421
  var session = LanguageModelSession()
422
+ var currentTurn: Task<Void, Never>?
336
423
  do {
337
424
  for try await line in FileHandle.standardInput.bytes.lines {
338
425
  if line.trimmingCharacters(in: .whitespaces).isEmpty { continue }
@@ -340,14 +427,27 @@ private func runSession() async -> Never {
340
427
  emitError("badRequest", "malformed session command", id: nil)
341
428
  continue
342
429
  }
343
- if command.type == "reset" {
344
- session = LanguageModelSession(
345
- instructions: sessionInstructions(system: command.system, seed: command.seed))
430
+ switch command.type {
431
+ case "tool_result":
432
+ await bridge.resolve(callId: command.callId ?? "", reply: .result(command.content ?? ""))
433
+ case "tool_error":
434
+ await bridge.resolve(callId: command.callId ?? "", reply: .error(command.message ?? "tool failed"))
435
+ case "cancel":
436
+ // Interrupt the in-flight turn (FR-15). Turns are serial, so the one
437
+ // live task is the target; it ends by emitting its partial `result`.
438
+ currentTurn?.cancel()
439
+ case "reset":
440
+ await currentTurn?.value // no turn should be in flight, but be safe
441
+ session = makeSession(command, bridge: bridge)
346
442
  emitReady(command.id)
347
- } else {
348
- await sessionTurn(session, command)
443
+ default:
444
+ await currentTurn?.value // serialize: one turn at a time
445
+ await bridge.beginTurn(command.id)
446
+ let active = session
447
+ currentTurn = Task { await sessionTurn(active, command) }
349
448
  }
350
449
  }
450
+ await currentTurn?.value
351
451
  } catch {
352
452
  failEvent("inferenceFailed", "session input error: \(String(describing: error))")
353
453
  }
Binary file