apple-fm 0.0.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,18 +1,44 @@
1
1
  # apple-fm
2
2
 
3
- Command-line and programmatic access to Apple's **on-device Foundation Models**
4
- (Apple Intelligence) on **macOS 26+ / Apple Silicon**. Free, private, offline —
5
- nothing leaves your machine.
6
-
7
- Apple ships `FoundationModels` as Swift-only API with no command-line front-end.
8
- apple-fm provides one: a tiny Swift helper does the model work, and a tested,
9
- zero-dependency Node layer gives you a CLI and a library.
10
-
11
- > ⚠️ **Early scaffold.** The Node layer is fully unit-tested; the Swift helper is
12
- > smoke-verified on a macOS 26 / Apple Intelligence machine (probe, generate,
13
- > stream, schema, chat all work). Native guaranteed-structure output, an
14
- > automated on-device CI test, and signed release binaries are still to come —
15
- > see [docs/3-requirements.md](docs/3-requirements.md).
3
+ **Apple Intelligence from your command line and your code.** apple-fm gives you
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.
6
+
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.
10
+
11
+ <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
+ </p>
14
+
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
+ ## Why apple-fm
24
+
25
+ - **On-device & private.** Runs on the model Apple Intelligence already
26
+ installed. No key, no cloud, no telemetry — your prompts never leave the
27
+ machine.
28
+ - **One binary, three shapes.** `probe`, one-shot `generate` (freeform, guided,
29
+ or streamed), and an interactive `chat` — all over a single
30
+ [NDJSON protocol](docs/4-protocol.md).
31
+ - **Guaranteed structured output.** Hand it a JSON Schema and the output is
32
+ *guaranteed* to conform — native guided generation built on Apple's
33
+ `DynamicGenerationSchema`, not best-effort prompting. Stream it, too.
34
+ - **Long conversations stay coherent — and cheap.** `chat` holds one on-device
35
+ session across turns, reusing the model's cache instead of replaying the
36
+ 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.
40
+ - **Future-proof.** The helper resolves the current on-device model at runtime,
41
+ so OS and model updates are picked up without a rebuild.
16
42
 
17
43
  ## Install
18
44
 
@@ -21,8 +47,8 @@ npm install -g apple-fm # CLI
21
47
  npm install apple-fm # library
22
48
  ```
23
49
 
24
- Requires macOS 26+ on Apple Silicon with Apple Intelligence enabled. The package
25
- bundles a prebuilt helper; you can also build it from source:
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:
26
52
 
27
53
  ```bash
28
54
  npm run build:helper # → bin/apple-fm-helper (needs Xcode 26 / macOS 26 SDK)
@@ -31,6 +57,25 @@ npm run build:helper # → bin/apple-fm-helper (needs Xcode 26 / macOS 26
31
57
  The helper is located via `APPLE_FM_BIN`, then the bundled `bin/apple-fm-helper`,
32
58
  then `apple-fm-helper` on `PATH`.
33
59
 
60
+ ### Platform support
61
+
62
+ apple-fm **installs on any OS** — so it can be a dependency of a cross-platform
63
+ project — but the on-device model only *runs* on **macOS 26+ Apple Silicon**.
64
+ Everywhere else it degrades gracefully instead of crashing: `probe()` returns
65
+ `{ available: false, reason: 'unsupportedPlatform' }`, and `generate` / `chat`
66
+ throw a clear `[unsupportedPlatform]` error. Gate on `isPlatformSupported()` or
67
+ `probe()`:
68
+
69
+ ```ts
70
+ import { isPlatformSupported, probe, generate } from 'apple-fm';
71
+
72
+ if ((await probe()).available) {
73
+ await generate({ prompt: '…' });
74
+ } else {
75
+ // fall back (cloud model, cached result, skip the feature, …)
76
+ }
77
+ ```
78
+
34
79
  ## CLI
35
80
 
36
81
  ```bash
@@ -44,6 +89,34 @@ apple-fm chat # interactive chat (streamed, auto-compacte
44
89
 
45
90
  Run `apple-fm --help` for the full flag list.
46
91
 
92
+ ### Check availability
93
+
94
+ Before generating, confirm Apple Intelligence is ready on this machine.
95
+
96
+ <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">
98
+ </p>
99
+
100
+ ### Structured output
101
+
102
+ Pass a JSON Schema with `--schema` and apple-fm returns JSON **guaranteed to
103
+ conform** to it — native guided generation, not prompt-and-hope — ready to pipe
104
+ into the rest of your tooling.
105
+
106
+ <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">
108
+ </p>
109
+
110
+ ### Interactive chat
111
+
112
+ `chat` is a multi-turn REPL that streams replies and compacts the transcript
113
+ automatically near the context window. Built-in slash commands: `/reset`,
114
+ `/system`, `/clear`, `/compact`, `/help`, `/quit`.
115
+
116
+ <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">
118
+ </p>
119
+
47
120
  ## Library
48
121
 
49
122
  ```ts
@@ -56,20 +129,31 @@ if ((await probe()).available) {
56
129
  // Streaming
57
130
  await generate({ prompt: '…', stream: true }, {}, (chunk) => process.stdout.write(chunk));
58
131
 
59
- // Multi-turn chat with automatic context compaction
132
+ // Guaranteed structured output — pass a JSON Schema, get conforming JSON back
133
+ const json = await generate({ prompt: 'A classic sci-fi novel', schema: novelSchema });
134
+
135
+ // Multi-turn chat: one persistent on-device session, auto-compacted
60
136
  const chat = new ChatSession({ system: 'You are a helpful assistant.' });
61
137
  const reply = await chat.send('Hello');
62
138
  }
63
139
  ```
64
140
 
141
+ The full API (`probe`, `generate`, `ChatSession`, protocol helpers, and types) is
142
+ documented in [docs/ai/code-summary.md](docs/ai/code-summary.md).
143
+
65
144
  ## How it works
66
145
 
67
146
  A single binary, three shapes (probe / generate / chat), all over one
68
- line-delimited JSON protocol ([docs/4-protocol.md](docs/4-protocol.md)). The chat
69
- session keeps the transcript on the Node side and, when it approaches the
70
- on-device model's small context window, summarizes older turns and continues —
71
- so long conversations stay coherent. Because the helper resolves the current
72
- on-device model at runtime, OS and model updates are picked up without a rebuild.
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.
73
157
 
74
158
  ## Documentation
75
159
 
@@ -77,6 +161,15 @@ on-device model at runtime, OS and model updates are picked up without a rebuild
77
161
  [Requirements](docs/3-requirements.md) · [Protocol](docs/4-protocol.md) ·
78
162
  [Releasing](docs/5-releasing.md)
79
163
 
164
+ ## Disclaimer
165
+
166
+ apple-fm is an independent, unofficial project and is **not affiliated with,
167
+ endorsed by, or sponsored by Apple Inc.** It simply provides command-line and
168
+ programmatic access to Apple's on-device Foundation Models on machines that
169
+ already support them (macOS 26+ on Apple Silicon with Apple Intelligence enabled).
170
+ Apple, Apple Intelligence, Apple Silicon, Foundation Models, and macOS are
171
+ trademarks of Apple Inc.
172
+
80
173
  ## License
81
174
 
82
175
  MIT © Brian Westphal
@@ -0,0 +1,130 @@
1
+ // Guided generation: translate a request's JSON Schema into a native
2
+ // `GenerationSchema` so `respond(to:schema:)` can guarantee the output conforms.
3
+ // Part of apple-fm-helper (see main.swift) — all the .swift files here are
4
+ // compiled together into one binary. See docs/6-guided-generation.md.
5
+ import Foundation
6
+ import FoundationModels
7
+
8
+ /// Thrown when a request's JSON Schema uses a construct the native
9
+ /// `DynamicGenerationSchema` can't express. Surfaced to the caller as the
10
+ /// `unsupportedSchema` error code — strict, no prompt-guided fallback.
11
+ struct UnsupportedSchema: Error { let message: String }
12
+
13
+ private func stringField(_ object: [String: JSONValue], _ key: String) -> String? {
14
+ if case .string(let value)? = object[key] { return value }
15
+ return nil
16
+ }
17
+
18
+ private func intField(_ object: [String: JSONValue], _ key: String) -> Int? {
19
+ if case .number(let value)? = object[key] { return Int(value) }
20
+ return nil
21
+ }
22
+
23
+ private func doubleField(_ object: [String: JSONValue], _ key: String) -> Double? {
24
+ if case .number(let value)? = object[key] { return value }
25
+ return nil
26
+ }
27
+
28
+ /// `minimum` / `maximum` → integer range guides (a documented range, or an open
29
+ /// bound). A `minimum > maximum` schema is rejected so the `ClosedRange` is valid.
30
+ private func intGuides(_ object: [String: JSONValue]) throws -> [GenerationGuide<Int>] {
31
+ let lo = intField(object, "minimum")
32
+ let hi = intField(object, "maximum")
33
+ if let lo, let hi {
34
+ guard lo <= hi else { throw UnsupportedSchema(message: "minimum (\(lo)) is greater than maximum (\(hi))") }
35
+ return [.range(lo...hi)]
36
+ }
37
+ if let lo { return [.minimum(lo)] }
38
+ if let hi { return [.maximum(hi)] }
39
+ return []
40
+ }
41
+
42
+ /// `minimum` / `maximum` → floating-point range guides (see `intGuides`).
43
+ private func doubleGuides(_ object: [String: JSONValue]) throws -> [GenerationGuide<Double>] {
44
+ let lo = doubleField(object, "minimum")
45
+ let hi = doubleField(object, "maximum")
46
+ if let lo, let hi {
47
+ guard lo <= hi else { throw UnsupportedSchema(message: "minimum (\(lo)) is greater than maximum (\(hi))") }
48
+ return [.range(lo...hi)]
49
+ }
50
+ if let lo { return [.minimum(lo)] }
51
+ if let hi { return [.maximum(hi)] }
52
+ return []
53
+ }
54
+
55
+ /// Translate one JSON Schema node into a `DynamicGenerationSchema`. Strict: any
56
+ /// construct outside the documented subset throws `UnsupportedSchema`. `name` is
57
+ /// made unique across the tree by `counter` (object / enum nodes are named).
58
+ private func dynamicSchema(_ node: JSONValue, name: String, counter: inout Int) throws -> DynamicGenerationSchema {
59
+ guard case .object(let object) = node else {
60
+ throw UnsupportedSchema(message: "schema node must be a JSON object")
61
+ }
62
+ let description = stringField(object, "description")
63
+ guard let type = stringField(object, "type") else {
64
+ throw UnsupportedSchema(message: "schema node is missing a string \"type\" (oneOf / anyOf / allOf / $ref are not supported)")
65
+ }
66
+ switch type {
67
+ case "object":
68
+ guard case .object(let properties)? = object["properties"] else {
69
+ throw UnsupportedSchema(message: "object schema is missing \"properties\"")
70
+ }
71
+ var required: Set<String> = []
72
+ if case .array(let names)? = object["required"] {
73
+ for entry in names { if case .string(let key) = entry { required.insert(key) } }
74
+ }
75
+ var built: [DynamicGenerationSchema.Property] = []
76
+ for (key, child) in properties {
77
+ counter += 1
78
+ let childSchema = try dynamicSchema(child, name: "\(name).\(key).\(counter)", counter: &counter)
79
+ let childDescription: String? = {
80
+ if case .object(let childObject) = child { return stringField(childObject, "description") }
81
+ return nil
82
+ }()
83
+ built.append(.init(name: key, description: childDescription, schema: childSchema, isOptional: !required.contains(key)))
84
+ }
85
+ return DynamicGenerationSchema(name: name, description: description, properties: built)
86
+ case "string":
87
+ if case .array(let choices)? = object["enum"] {
88
+ var values: [String] = []
89
+ for choice in choices {
90
+ guard case .string(let value) = choice else {
91
+ throw UnsupportedSchema(message: "only string enum values are supported")
92
+ }
93
+ values.append(value)
94
+ }
95
+ return DynamicGenerationSchema(name: name, description: description, anyOf: values)
96
+ }
97
+ // String value constraints (pattern / minLength / maxLength / format) are
98
+ // not enforced: the on-device model's constrained decoding rejects a
99
+ // `GenerationGuide.pattern` regex (it errors at generation time), so a
100
+ // `pattern` guide would break any schema that uses one. Structure is still
101
+ // guaranteed; the constraint is documented as best-effort. See docs/6.
102
+ return DynamicGenerationSchema(type: String.self)
103
+ case "integer":
104
+ return DynamicGenerationSchema(type: Int.self, guides: try intGuides(object))
105
+ case "number":
106
+ return DynamicGenerationSchema(type: Double.self, guides: try doubleGuides(object))
107
+ case "boolean":
108
+ return DynamicGenerationSchema(type: Bool.self)
109
+ case "array":
110
+ guard let items = object["items"] else {
111
+ throw UnsupportedSchema(message: "array schema is missing \"items\"")
112
+ }
113
+ counter += 1
114
+ let itemSchema = try dynamicSchema(items, name: "\(name).item.\(counter)", counter: &counter)
115
+ return DynamicGenerationSchema(
116
+ arrayOf: itemSchema,
117
+ minimumElements: intField(object, "minItems"),
118
+ maximumElements: intField(object, "maxItems"))
119
+ default:
120
+ throw UnsupportedSchema(message: "unsupported JSON Schema type: \(type)")
121
+ }
122
+ }
123
+
124
+ /// Build a native `GenerationSchema` from the request's JSON Schema. Nested schemas
125
+ /// are inlined, so `dependencies` is empty.
126
+ func compileSchema(from schema: JSONValue) throws -> GenerationSchema {
127
+ var counter = 0
128
+ let root = try dynamicSchema(schema, name: "Output", counter: &counter)
129
+ return try GenerationSchema(root: root, dependencies: [])
130
+ }
@@ -38,9 +38,9 @@ struct GenerateRequest: Decodable {
38
38
  let system: String?
39
39
  let prompt: String?
40
40
  let messages: [WireMessage]?
41
- // Guided-generation schema. Captured but, for now, applied as prompt
42
- // guidance (see `instructions(for:)`). Native `DynamicGenerationSchema`
43
- // guided generation is the planned enhancement — see docs/3-requirements.md.
41
+ // Guided-generation JSON Schema. When present, translated at runtime to a
42
+ // native `GenerationSchema` (see `compileSchema`) so the framework guarantees
43
+ // the output conforms — see docs/6-guided-generation.md.
44
44
  let schema: JSONValue?
45
45
  let options: WireOptions?
46
46
  let stream: Bool?
@@ -96,16 +96,38 @@ private func emit(_ json: String) {
96
96
  FileHandle.standardOutput.write(Data((json + "\n").utf8))
97
97
  }
98
98
 
99
- private func emitResult(_ content: String) {
100
- emit("{\"type\":\"result\",\"content\":\(encodeString(content))}")
99
+ // Events carry an optional `id` so the persistent `--session` mode can correlate
100
+ // each event with the command that produced it; `--probe`/`--generate` omit it.
101
+ private func idField(_ id: String?) -> String {
102
+ guard let id else { return "" }
103
+ return ",\"id\":\(encodeString(id))"
101
104
  }
102
105
 
103
- private func emitDelta(_ text: String) {
104
- emit("{\"type\":\"delta\",\"text\":\(encodeString(text))}")
106
+ private func emitResult(_ content: String, id: String? = nil) {
107
+ emit("{\"type\":\"result\"\(idField(id)),\"content\":\(encodeString(content))}")
105
108
  }
106
109
 
110
+ private func emitDelta(_ text: String, id: String? = nil) {
111
+ emit("{\"type\":\"delta\"\(idField(id)),\"text\":\(encodeString(text))}")
112
+ }
113
+
114
+ private func emitReady(_ id: String?) {
115
+ emit("{\"type\":\"ready\"\(idField(id))}")
116
+ }
117
+
118
+ /// A full partial value for guided streaming (replace semantics, not a suffix).
119
+ private func emitSnapshot(_ content: String, id: String? = nil) {
120
+ emit("{\"type\":\"snapshot\"\(idField(id)),\"content\":\(encodeString(content))}")
121
+ }
122
+
123
+ /// Emit an error event without exiting (used per-turn in `--session`).
124
+ private func emitError(_ code: String, _ message: String, id: String?) {
125
+ emit("{\"type\":\"error\"\(idField(id)),\"code\":\(encodeString(code)),\"message\":\(encodeString(message))}")
126
+ }
127
+
128
+ /// Emit an error event and exit non-zero (one-shot `--probe`/`--generate`).
107
129
  private func failEvent(_ code: String, _ message: String) -> Never {
108
- emit("{\"type\":\"error\",\"code\":\(encodeString(code)),\"message\":\(encodeString(message))}")
130
+ emitError(code, message, id: nil)
109
131
  exit(1)
110
132
  }
111
133
 
@@ -141,21 +163,17 @@ private func reasonString(_ reason: SystemLanguageModel.Availability.Unavailable
141
163
 
142
164
  // MARK: - Generate
143
165
 
144
- /// Combine the caller's system prompt with any schema guidance.
145
- private func instructions(for request: GenerateRequest) -> String {
146
- var parts: [String] = []
147
- if let system = request.system, !system.isEmpty { parts.append(system) }
148
- if let schema = request.schema {
149
- // Prompt-guided structured output. The richer path (native guided
150
- // generation with a runtime `DynamicGenerationSchema`) is tracked in the
151
- // requirements doc; until then we instruct the model to match the schema.
152
- parts.append(
153
- "Respond with JSON only — no prose, no code fences — matching this JSON Schema:\n"
154
- + (schema.jsonString ?? "{}"))
155
- }
156
- return parts.joined(separator: "\n\n")
166
+ /// The session instructions — just the caller's system prompt. Structured output
167
+ /// is handled natively via `respond(to:schema:)` (see `generate`), not by injecting
168
+ /// the schema into the prompt.
169
+ private func instructions(for request: GenerateRequest) -> String? {
170
+ guard let system = request.system, !system.isEmpty else { return nil }
171
+ return system
157
172
  }
158
173
 
174
+ // Guided-generation schema translation lives in GuidedGeneration.swift
175
+ // (`compileSchema` / `UnsupportedSchema`), compiled into the same binary.
176
+
159
177
  /// Build the single user prompt from either `prompt` or a `messages` transcript.
160
178
  /// The `messages` labeling below must mirror the Node side's canonical format
161
179
  /// (`src/protocol.ts` `flattenMessages`: `User:`/`Assistant:`, blank-line
@@ -183,6 +201,42 @@ private func generate(_ request: GenerateRequest) async -> Never {
183
201
  let session = LanguageModelSession(instructions: instructions(for: request))
184
202
  let prompt = userPrompt(for: request)
185
203
  let options = generationOptions(request.options)
204
+
205
+ // Native guided generation: guaranteed structure, or a clear error. Strict —
206
+ // no prompt-guided fallback (see docs/6-guided-generation.md).
207
+ if let schema = request.schema {
208
+ let compiled: GenerationSchema
209
+ do {
210
+ compiled = try compileSchema(from: schema)
211
+ } catch let error as UnsupportedSchema {
212
+ failEvent("unsupportedSchema", error.message)
213
+ } catch {
214
+ failEvent("unsupportedSchema", "could not build a generation schema: \(String(describing: error))")
215
+ }
216
+ do {
217
+ if request.stream == true {
218
+ // Structured partials are NOT append-only (keys reorder, values
219
+ // grow in place), so each partial is emitted as a full `snapshot`
220
+ // (replace semantics) rather than a `delta` suffix; the final
221
+ // `result` carries the complete JSON. See docs/4-protocol.md.
222
+ var last = ""
223
+ for try await partial in session.streamResponse(to: prompt, schema: compiled, options: options) {
224
+ last = partial.content.jsonString
225
+ emitSnapshot(last)
226
+ }
227
+ emitResult(last)
228
+ } else {
229
+ let response = try await session.respond(to: prompt, schema: compiled, options: options)
230
+ emitResult(response.content.jsonString)
231
+ }
232
+ exit(0)
233
+ } catch let error as LanguageModelSession.GenerationError {
234
+ failEvent(errorCode(error), String(describing: error))
235
+ } catch {
236
+ failEvent("inferenceFailed", String(describing: error))
237
+ }
238
+ }
239
+
186
240
  do {
187
241
  if request.stream == true {
188
242
  var emitted = ""
@@ -215,6 +269,91 @@ private func errorCode(_ error: LanguageModelSession.GenerationError) -> String
215
269
  }
216
270
  }
217
271
 
272
+ // MARK: - Session (persistent live session)
273
+
274
+ /// One command read on stdin in `--session` mode: either a turn (has `prompt`) or
275
+ /// a `reset` (`type == "reset"`). See docs/4-protocol.md / docs/7-live-session.md.
276
+ struct SessionCommand: Decodable {
277
+ let type: String?
278
+ let id: String?
279
+ let system: String?
280
+ let seed: [WireMessage]?
281
+ let prompt: String?
282
+ let options: WireOptions?
283
+ let stream: Bool?
284
+ }
285
+
286
+ /// Compose session instructions from a system prompt plus any seed turns, folded
287
+ /// in as a labeled recap so a `reset` preserves recent context without re-running
288
+ /// it as live turns. Mirrors `userPrompt` / `flattenMessages` labeling.
289
+ private func sessionInstructions(system: String?, seed: [WireMessage]?) -> String? {
290
+ var parts: [String] = []
291
+ if let system, !system.isEmpty { parts.append(system) }
292
+ if let seed, !seed.isEmpty {
293
+ let transcript = seed
294
+ .map { "\($0.role == "assistant" ? "Assistant" : "User"): \($0.content)" }
295
+ .joined(separator: "\n\n")
296
+ parts.append("Conversation so far:\n\(transcript)")
297
+ }
298
+ return parts.isEmpty ? nil : parts.joined(separator: "\n\n")
299
+ }
300
+
301
+ /// Run one turn against the held session, emitting id-tagged events.
302
+ private func sessionTurn(_ session: LanguageModelSession, _ command: SessionCommand) async {
303
+ let prompt = command.prompt ?? ""
304
+ let options = generationOptions(command.options)
305
+ do {
306
+ if command.stream == true {
307
+ var emitted = ""
308
+ for try await partial in session.streamResponse(to: prompt, options: options) {
309
+ let full = partial.content
310
+ if full.count > emitted.count {
311
+ emitDelta(String(full.dropFirst(emitted.count)), id: command.id)
312
+ emitted = full
313
+ }
314
+ }
315
+ emitResult(emitted, id: command.id)
316
+ } else {
317
+ let response = try await session.respond(to: prompt, options: options)
318
+ emitResult(response.content, id: command.id)
319
+ }
320
+ } catch let error as LanguageModelSession.GenerationError {
321
+ emitError(errorCode(error), String(describing: error), id: command.id)
322
+ } catch {
323
+ emitError("inferenceFailed", String(describing: error), id: command.id)
324
+ }
325
+ }
326
+
327
+ /// 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`.
331
+ private func runSession() async -> Never {
332
+ guard case .available = SystemLanguageModel.default.availability else {
333
+ failEvent("unavailable", "Apple Foundation Models unavailable")
334
+ }
335
+ var session = LanguageModelSession()
336
+ do {
337
+ for try await line in FileHandle.standardInput.bytes.lines {
338
+ if line.trimmingCharacters(in: .whitespaces).isEmpty { continue }
339
+ guard let command = try? JSONDecoder().decode(SessionCommand.self, from: Data(line.utf8)) else {
340
+ emitError("badRequest", "malformed session command", id: nil)
341
+ continue
342
+ }
343
+ if command.type == "reset" {
344
+ session = LanguageModelSession(
345
+ instructions: sessionInstructions(system: command.system, seed: command.seed))
346
+ emitReady(command.id)
347
+ } else {
348
+ await sessionTurn(session, command)
349
+ }
350
+ }
351
+ } catch {
352
+ failEvent("inferenceFailed", "session input error: \(String(describing: error))")
353
+ }
354
+ exit(0)
355
+ }
356
+
218
357
  // MARK: - Entry
219
358
 
220
359
  private func readRequest() -> GenerateRequest {
@@ -232,7 +371,10 @@ if args.contains("--probe") {
232
371
  let request = readRequest()
233
372
  Task { await generate(request) }
234
373
  dispatchMain()
374
+ } else if args.contains("--session") {
375
+ Task { await runSession() }
376
+ dispatchMain()
235
377
  } else {
236
- FileHandle.standardError.write(Data("usage: apple-fm-helper --probe | --generate\n".utf8))
378
+ FileHandle.standardError.write(Data("usage: apple-fm-helper --probe | --generate | --session\n".utf8))
237
379
  exit(64)
238
380
  }
Binary file