apple-fm 0.0.1 → 0.1.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,43 @@
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
+ > ⚠️ **Pre-release.** The Node layer is fully unit-tested and the Swift helper is
16
+ > smoke-verified on a macOS 26 / Apple Intelligence machine — probe, generate
17
+ > (freeform / guided / streamed), native guaranteed-structure output, and a
18
+ > persistent multi-turn chat all work on-device. Still in flight: an automated
19
+ > on-device test in CI and the first signed + notarized npm release — see
20
+ > [docs/3-requirements.md](docs/3-requirements.md).
21
+
22
+ ## Why apple-fm
23
+
24
+ - **On-device & private.** Runs on the model Apple Intelligence already
25
+ installed. No key, no cloud, no telemetry — your prompts never leave the
26
+ machine.
27
+ - **One binary, three shapes.** `probe`, one-shot `generate` (freeform, guided,
28
+ or streamed), and an interactive `chat` — all over a single
29
+ [NDJSON protocol](docs/4-protocol.md).
30
+ - **Guaranteed structured output.** Hand it a JSON Schema and the output is
31
+ *guaranteed* to conform — native guided generation built on Apple's
32
+ `DynamicGenerationSchema`, not best-effort prompting. Stream it, too.
33
+ - **Long conversations stay coherent — and cheap.** `chat` holds one on-device
34
+ session across turns, reusing the model's cache instead of replaying the
35
+ transcript, and automatically summarizes older turns as the small context
36
+ window fills.
37
+ - **Zero runtime dependencies.** The Node layer only spawns the helper and speaks
38
+ JSON. Strict TypeScript, ESM, lint-clean.
39
+ - **Future-proof.** The helper resolves the current on-device model at runtime,
40
+ so OS and model updates are picked up without a rebuild.
16
41
 
17
42
  ## Install
18
43
 
@@ -21,8 +46,8 @@ npm install -g apple-fm # CLI
21
46
  npm install apple-fm # library
22
47
  ```
23
48
 
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:
49
+ Requires macOS 26+ on Apple Silicon with Apple Intelligence enabled. Releases
50
+ bundle a signed + notarized helper; you can also build it from source:
26
51
 
27
52
  ```bash
28
53
  npm run build:helper # → bin/apple-fm-helper (needs Xcode 26 / macOS 26 SDK)
@@ -44,6 +69,34 @@ apple-fm chat # interactive chat (streamed, auto-compacte
44
69
 
45
70
  Run `apple-fm --help` for the full flag list.
46
71
 
72
+ ### Check availability
73
+
74
+ Before generating, confirm Apple Intelligence is ready on this machine.
75
+
76
+ <p align="center">
77
+ <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">
78
+ </p>
79
+
80
+ ### Structured output
81
+
82
+ Pass a JSON Schema with `--schema` and apple-fm returns JSON **guaranteed to
83
+ conform** to it — native guided generation, not prompt-and-hope — ready to pipe
84
+ into the rest of your tooling.
85
+
86
+ <p align="center">
87
+ <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">
88
+ </p>
89
+
90
+ ### Interactive chat
91
+
92
+ `chat` is a multi-turn REPL that streams replies and compacts the transcript
93
+ automatically near the context window. Built-in slash commands: `/reset`,
94
+ `/system`, `/clear`, `/compact`, `/help`, `/quit`.
95
+
96
+ <p align="center">
97
+ <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">
98
+ </p>
99
+
47
100
  ## Library
48
101
 
49
102
  ```ts
@@ -56,20 +109,31 @@ if ((await probe()).available) {
56
109
  // Streaming
57
110
  await generate({ prompt: '…', stream: true }, {}, (chunk) => process.stdout.write(chunk));
58
111
 
59
- // Multi-turn chat with automatic context compaction
112
+ // Guaranteed structured output — pass a JSON Schema, get conforming JSON back
113
+ const json = await generate({ prompt: 'A classic sci-fi novel', schema: novelSchema });
114
+
115
+ // Multi-turn chat: one persistent on-device session, auto-compacted
60
116
  const chat = new ChatSession({ system: 'You are a helpful assistant.' });
61
117
  const reply = await chat.send('Hello');
62
118
  }
63
119
  ```
64
120
 
121
+ The full API (`probe`, `generate`, `ChatSession`, protocol helpers, and types) is
122
+ documented in [docs/ai/code-summary.md](docs/ai/code-summary.md).
123
+
65
124
  ## How it works
66
125
 
67
126
  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.
127
+ line-delimited JSON protocol ([docs/4-protocol.md](docs/4-protocol.md)). Only the
128
+ Swift helper imports `FoundationModels`; all policy — argument parsing, the wire
129
+ protocol, chat history, auto-compaction — lives in strict TypeScript and is
130
+ unit-tested against a stub helper, so the suite runs on any platform. For chat the
131
+ helper holds one `LanguageModelSession` across turns (so the model's cache is
132
+ reused instead of replaying the transcript), while the Node side keeps the
133
+ transcript so it can summarize older turns as the small context window fills — so
134
+ long conversations stay coherent and cheap. Because the helper resolves the
135
+ current on-device model at runtime, OS and model updates are picked up without a
136
+ rebuild.
73
137
 
74
138
  ## Documentation
75
139
 
@@ -77,6 +141,15 @@ on-device model at runtime, OS and model updates are picked up without a rebuild
77
141
  [Requirements](docs/3-requirements.md) · [Protocol](docs/4-protocol.md) ·
78
142
  [Releasing](docs/5-releasing.md)
79
143
 
144
+ ## Disclaimer
145
+
146
+ apple-fm is an independent, unofficial project and is **not affiliated with,
147
+ endorsed by, or sponsored by Apple Inc.** It simply provides command-line and
148
+ programmatic access to Apple's on-device Foundation Models on machines that
149
+ already support them (macOS 26+ on Apple Silicon with Apple Intelligence enabled).
150
+ Apple, Apple Intelligence, Apple Silicon, Foundation Models, and macOS are
151
+ trademarks of Apple Inc.
152
+
80
153
  ## License
81
154
 
82
155
  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
package/dist/cli.js CHANGED
@@ -134,6 +134,9 @@ function parseEvent(line) {
134
134
  case "delta":
135
135
  if (typeof event.text !== "string") break;
136
136
  return { type: "delta", text: event.text };
137
+ case "snapshot":
138
+ if (typeof event.content !== "string") break;
139
+ return { type: "snapshot", content: event.content };
137
140
  case "result":
138
141
  if (typeof event.content !== "string") break;
139
142
  return { type: "result", content: event.content };
@@ -232,7 +235,7 @@ async function probe(options = {}) {
232
235
  if (result === void 0) throw new Error("apple-fm helper --probe produced no result");
233
236
  return result;
234
237
  }
235
- async function generate(request, options = {}, onDelta) {
238
+ async function generate(request, options = {}, onDelta, onSnapshot) {
236
239
  let content;
237
240
  await runHelper(["--generate"], options, encodeRequest(request), (line) => {
238
241
  const event = parseEvent(line);
@@ -240,6 +243,9 @@ async function generate(request, options = {}, onDelta) {
240
243
  case "delta":
241
244
  onDelta?.(event.text);
242
245
  break;
246
+ case "snapshot":
247
+ onSnapshot?.(event.content);
248
+ break;
243
249
  case "result":
244
250
  content = event.content;
245
251
  break;
@@ -254,6 +260,133 @@ async function generate(request, options = {}, onDelta) {
254
260
  // src/repl.ts
255
261
  import { createInterface } from "readline";
256
262
 
263
+ // src/liveSession.ts
264
+ import { spawn as spawn2 } from "child_process";
265
+ var DEFAULT_TURN_TIMEOUT_MS = 12e4;
266
+ var LiveSession = class {
267
+ command;
268
+ timeoutMs;
269
+ options;
270
+ child;
271
+ buffer = "";
272
+ nextId = 0;
273
+ pending = /* @__PURE__ */ new Map();
274
+ constructor(config = {}) {
275
+ this.command = resolveHelperPath(config);
276
+ this.timeoutMs = config.timeoutMs ?? DEFAULT_TURN_TIMEOUT_MS;
277
+ this.options = config.options;
278
+ }
279
+ /** Recreate the underlying session with new instructions + seed turns. */
280
+ async reset(system, seed = []) {
281
+ await this.dispatch({ type: "reset", system, seed }, void 0);
282
+ }
283
+ /** Send one user turn; prior turns stay in context. Streams via `onDelta`. */
284
+ send(text, onDelta) {
285
+ return this.dispatch(
286
+ { prompt: text, options: this.options, stream: onDelta !== void 0 },
287
+ onDelta
288
+ );
289
+ }
290
+ /** Tear down the helper process and reject any in-flight commands. */
291
+ close() {
292
+ const child = this.child;
293
+ this.child = void 0;
294
+ if (child !== void 0) child.kill("SIGKILL");
295
+ this.rejectAll(new Error("[sessionClosed] live session closed"));
296
+ }
297
+ rejectAll(error) {
298
+ for (const pending of this.pending.values()) {
299
+ clearTimeout(pending.timer);
300
+ pending.reject(error);
301
+ }
302
+ this.pending.clear();
303
+ }
304
+ ensureChild() {
305
+ const existing = this.child;
306
+ if (existing !== void 0 && existing.exitCode === null && !existing.killed) return existing;
307
+ const child = spawn2(this.command, ["--session"], { stdio: ["pipe", "pipe", "pipe"] });
308
+ this.buffer = "";
309
+ child.stdout.setEncoding("utf8");
310
+ child.stdout.on("data", (chunk) => {
311
+ this.onStdout(chunk);
312
+ });
313
+ child.stdin.on("error", () => void 0);
314
+ const onGone = () => {
315
+ if (this.child === child) this.child = void 0;
316
+ this.rejectAll(new Error("[sessionClosed] live session helper exited"));
317
+ };
318
+ child.on("close", onGone);
319
+ child.on("error", onGone);
320
+ this.child = child;
321
+ return child;
322
+ }
323
+ onStdout(chunk) {
324
+ this.buffer += chunk;
325
+ const { lines, rest } = splitLines(this.buffer);
326
+ this.buffer = rest;
327
+ for (const line of lines) this.onLine(line);
328
+ }
329
+ onLine(line) {
330
+ let value;
331
+ try {
332
+ value = JSON.parse(line);
333
+ } catch {
334
+ return;
335
+ }
336
+ if (typeof value !== "object" || value === null) return;
337
+ const event = value;
338
+ if (typeof event.id !== "string") return;
339
+ const id = event.id;
340
+ const pending = this.pending.get(id);
341
+ if (pending === void 0) return;
342
+ switch (event.type) {
343
+ case "delta":
344
+ if (typeof event.text === "string") {
345
+ pending.acc += event.text;
346
+ pending.onDelta?.(event.text);
347
+ }
348
+ break;
349
+ case "ready":
350
+ this.settle(id, "");
351
+ break;
352
+ case "result":
353
+ this.settle(id, typeof event.content === "string" ? event.content : pending.acc);
354
+ break;
355
+ case "error":
356
+ this.fail(id, `[${String(event.code)}] ${String(event.message)}`);
357
+ break;
358
+ default:
359
+ break;
360
+ }
361
+ }
362
+ settle(id, content) {
363
+ const pending = this.pending.get(id);
364
+ if (pending === void 0) return;
365
+ clearTimeout(pending.timer);
366
+ this.pending.delete(id);
367
+ pending.resolve(content);
368
+ }
369
+ fail(id, message) {
370
+ const pending = this.pending.get(id);
371
+ if (pending === void 0) return;
372
+ clearTimeout(pending.timer);
373
+ this.pending.delete(id);
374
+ pending.reject(new Error(message));
375
+ }
376
+ dispatch(command, onDelta) {
377
+ const child = this.ensureChild();
378
+ const id = String(this.nextId++);
379
+ return new Promise((resolve, reject) => {
380
+ const timer = setTimeout(() => {
381
+ this.pending.delete(id);
382
+ reject(new Error(`live session timed out after ${String(this.timeoutMs)}ms`));
383
+ }, this.timeoutMs);
384
+ this.pending.set(id, { resolve, reject, onDelta, acc: "", timer });
385
+ child.stdin.write(JSON.stringify({ ...command, id }) + "\n");
386
+ });
387
+ }
388
+ };
389
+
257
390
  // src/session.ts
258
391
  var DEFAULT_COMPACT_AT = 3e3;
259
392
  var DEFAULT_KEEP_RECENT = 4;
@@ -263,18 +396,20 @@ function defaultGenerateFn(helper, options) {
263
396
  }
264
397
  var ChatSession = class {
265
398
  system;
266
- options;
267
399
  compactAtTokens;
268
400
  keepRecentTurns;
401
+ backend;
269
402
  generateFn;
270
403
  messages = [];
271
404
  /** Recap of turns dropped by compaction; folded into the system prompt. */
272
405
  summary;
406
+ /** Instructions the backend was last `reset` with (`undefined` ⇒ needs reset). */
407
+ backendInstructions;
273
408
  constructor(config = {}) {
274
409
  this.system = config.system ?? "";
275
- this.options = config.options;
276
410
  this.compactAtTokens = config.compactAtTokens ?? DEFAULT_COMPACT_AT;
277
411
  this.keepRecentTurns = config.keepRecentTurns ?? DEFAULT_KEEP_RECENT;
412
+ this.backend = config.backend ?? new LiveSession({ ...config.helper, options: config.options });
278
413
  this.generateFn = config.generateFn ?? defaultGenerateFn(config.helper, config.options);
279
414
  }
280
415
  /** The system prompt actually sent to the model (instructions + any recap). */
@@ -297,11 +432,35 @@ ${recap}` : recap;
297
432
  /** Send a user turn and return the assistant's reply (streamed via `onDelta`). */
298
433
  async send(text, onDelta) {
299
434
  if (this.shouldCompact()) await this.compact();
435
+ await this.ensureStarted();
300
436
  this.messages.push({ role: "user", content: text });
301
- const reply = await this.generateFn(this.effectiveSystem(), this.messages, onDelta);
437
+ let reply;
438
+ try {
439
+ reply = await this.backend.send(text, onDelta);
440
+ } catch (error) {
441
+ if (!recoverable(error)) {
442
+ this.messages.pop();
443
+ throw error;
444
+ }
445
+ this.messages.pop();
446
+ this.backendInstructions = void 0;
447
+ await this.ensureStarted();
448
+ this.messages.push({ role: "user", content: text });
449
+ reply = await this.backend.send(text, onDelta);
450
+ }
302
451
  this.messages.push({ role: "assistant", content: reply });
303
452
  return reply;
304
453
  }
454
+ /**
455
+ * Reset the backend's session whenever the effective system prompt changes (the
456
+ * first turn, or after a compaction), seeding it with the transcript so far.
457
+ */
458
+ async ensureStarted() {
459
+ const system = this.effectiveSystem();
460
+ if (this.backendInstructions === system) return;
461
+ await this.backend.reset(system, this.messages);
462
+ this.backendInstructions = system;
463
+ }
305
464
  /**
306
465
  * Fold all but the most recent turns into the rolling summary. Safe to call
307
466
  * directly; {@link send} calls it automatically when {@link shouldCompact}.
@@ -324,8 +483,16 @@ ${this.summary}` : "",
324
483
  if (system !== void 0) this.system = system;
325
484
  this.messages = [];
326
485
  this.summary = void 0;
486
+ this.backendInstructions = void 0;
487
+ }
488
+ /** Tear down the underlying live session (kills the helper process). */
489
+ close() {
490
+ this.backend.close();
327
491
  }
328
492
  };
493
+ function recoverable(error) {
494
+ return error instanceof Error && error.message.includes("[sessionClosed]");
495
+ }
329
496
 
330
497
  // src/repl.ts
331
498
  var HELP = `Commands:
@@ -398,6 +565,7 @@ async function runRepl(opts) {
398
565
  rl.prompt();
399
566
  }
400
567
  rl.close();
568
+ session.close();
401
569
  }
402
570
 
403
571
  // src/cli.ts
@@ -441,8 +609,12 @@ async function main() {
441
609
  if (args.maxTokens !== void 0) options.maxTokens = args.maxTokens;
442
610
  const request = { prompt, system: args.system, options, stream: args.stream };
443
611
  if (args.schemaFile !== void 0) request.schema = JSON.parse(await readFile(args.schemaFile, "utf8"));
444
- const text = await generate(request, {}, args.stream ? (chunk) => process.stdout.write(chunk) : void 0);
445
- if (!args.stream) process.stdout.write(text);
612
+ const structured = args.schemaFile !== void 0;
613
+ const onDelta = args.stream && !structured ? (chunk) => process.stdout.write(chunk) : void 0;
614
+ const onSnapshot = args.stream && structured && process.stdout.isTTY ? (json) => process.stdout.write(`\r\x1B[2K${json}`) : void 0;
615
+ const text = await generate(request, {}, onDelta, onSnapshot);
616
+ if (onSnapshot !== void 0) process.stdout.write("\r\x1B[2K");
617
+ if (onDelta === void 0) process.stdout.write(text);
446
618
  process.stdout.write("\n");
447
619
  return;
448
620
  }
package/dist/index.d.ts CHANGED
@@ -49,13 +49,18 @@ interface ProbeResult {
49
49
  reason?: UnavailableReason;
50
50
  }
51
51
  /**
52
- * One line of helper output (NDJSON). `delta` events appear only when streaming;
53
- * every successful generation ends with exactly one `result`. Failures emit a
54
- * single `error`.
52
+ * One line of helper output (NDJSON). When streaming, freeform text emits `delta`
53
+ * events (append the suffix) while guided/structured output emits `snapshot`
54
+ * events (the full partial value — replace, since structured partials are not
55
+ * append-only). Every successful generation ends with exactly one `result`.
56
+ * Failures emit a single `error`.
55
57
  */
56
58
  type HelperEvent = {
57
59
  type: 'delta';
58
60
  text: string;
61
+ } | {
62
+ type: 'snapshot';
63
+ content: string;
59
64
  } | {
60
65
  type: 'result';
61
66
  content: string;
@@ -71,25 +76,71 @@ interface HelperOptions {
71
76
  /** Milliseconds before a one-shot generation is aborted (default 120_000). */
72
77
  timeoutMs?: number;
73
78
  }
74
- /** Callback fired for each streamed text chunk. */
79
+ /** Callback fired for each streamed text chunk (append the suffix). */
75
80
  type DeltaHandler = (text: string) => void;
81
+ /**
82
+ * Callback fired for each full partial value during guided/structured streaming.
83
+ * Each call carries the complete current JSON (replace, not append) — structured
84
+ * partials are not append-only.
85
+ */
86
+ type SnapshotHandler = (content: string) => void;
76
87
 
77
88
  /** Environment variable that pins the helper binary path. */
78
89
  declare const HELPER_BIN_ENV = "APPLE_FM_BIN";
79
90
  /**
80
91
  * Resolve the helper binary path: `APPLE_FM_BIN`, then the prebuilt binary
81
92
  * bundled with the package (`bin/apple-fm-helper`), then bare `apple-fm-helper`
82
- * to be found on `PATH` (e.g. a Homebrew install).
93
+ * to be found on `PATH`.
83
94
  */
84
95
  declare function resolveHelperPath(options?: HelperOptions): string;
85
96
  /** Ask the helper whether the on-device model is available right now. */
86
97
  declare function probe(options?: HelperOptions): Promise<ProbeResult>;
87
98
  /**
88
- * Run one generation. Streamed `delta` chunks are forwarded to `onDelta` (when
89
- * `request.stream` is set); the resolved value is always the full text (or, for
90
- * guided generation, the JSON string).
99
+ * Run one generation. When `request.stream` is set, freeform text is forwarded to
100
+ * `onDelta` (append the suffix) and guided/structured output to `onSnapshot` (the
101
+ * full partial JSON each time — replace, since structured partials are not
102
+ * append-only). The resolved value is always the full text (or, for guided
103
+ * generation, the complete JSON string).
91
104
  */
92
- declare function generate(request: GenerateRequest, options?: HelperOptions, onDelta?: DeltaHandler): Promise<string>;
105
+ declare function generate(request: GenerateRequest, options?: HelperOptions, onDelta?: DeltaHandler, onSnapshot?: SnapshotHandler): Promise<string>;
106
+
107
+ /** Construction options for a {@link LiveSession}. */
108
+ interface LiveSessionConfig extends HelperOptions {
109
+ /** Generation knobs forwarded with every turn. */
110
+ options?: GenerateOptions;
111
+ }
112
+ /** The backend contract that `ChatSession` drives. */
113
+ interface ChatBackend {
114
+ /** Send one user turn; prior turns stay in the session's context. */
115
+ send(text: string, onDelta?: DeltaHandler): Promise<string>;
116
+ /** Recreate the underlying session with new instructions + seed turns. */
117
+ reset(system: string, seed: Message[]): Promise<void>;
118
+ /** Tear down the backend. */
119
+ close(): void;
120
+ }
121
+ declare class LiveSession implements ChatBackend {
122
+ private readonly command;
123
+ private readonly timeoutMs;
124
+ private readonly options;
125
+ private child;
126
+ private buffer;
127
+ private nextId;
128
+ private readonly pending;
129
+ constructor(config?: LiveSessionConfig);
130
+ /** Recreate the underlying session with new instructions + seed turns. */
131
+ reset(system: string, seed?: Message[]): Promise<void>;
132
+ /** Send one user turn; prior turns stay in context. Streams via `onDelta`. */
133
+ send(text: string, onDelta?: DeltaHandler): Promise<string>;
134
+ /** Tear down the helper process and reject any in-flight commands. */
135
+ close(): void;
136
+ private rejectAll;
137
+ private ensureChild;
138
+ private onStdout;
139
+ private onLine;
140
+ private settle;
141
+ private fail;
142
+ private dispatch;
143
+ }
93
144
 
94
145
  /**
95
146
  * The line-delimited JSON (NDJSON) wire protocol between the Node layer and the
@@ -134,7 +185,7 @@ declare function estimateTokens(text: string): number;
134
185
  /** Sum the estimated tokens of a system prompt plus a conversation. */
135
186
  declare function estimateConversationTokens(system: string, messages: Message[]): number;
136
187
 
137
- /** Pluggable generation function (real helper by default; a stub in tests). */
188
+ /** Pluggable one-shot generation, used for summarization (a stub in tests). */
138
189
  type GenerateFn = (system: string, messages: Message[], onDelta?: DeltaHandler) => Promise<string>;
139
190
  /** Configuration for a {@link ChatSession}. */
140
191
  interface ChatSessionConfig {
@@ -150,21 +201,30 @@ interface ChatSessionConfig {
150
201
  compactAtTokens?: number;
151
202
  /** Number of most-recent turns kept verbatim through a compaction (default 4). */
152
203
  keepRecentTurns?: number;
153
- /** Helper discovery / timeout options (ignored when `generateFn` is given). */
204
+ /** Helper discovery / timeout options (used for the default backend + summarizer). */
154
205
  helper?: HelperOptions;
155
- /** Override the generation backend (tests inject a stub here). */
206
+ /** Override the live-session backend (tests inject a fake here). */
207
+ backend?: ChatBackend;
208
+ /** Override the one-shot summarization backend (tests inject a stub here). */
156
209
  generateFn?: GenerateFn;
157
210
  }
158
- /** A stateful, auto-compacting conversation with the on-device model. */
211
+ /**
212
+ * A stateful, auto-compacting conversation with the on-device model. Turns run
213
+ * against a persistent {@link LiveSession} (one `LanguageModelSession` reused
214
+ * across turns, FR-12) rather than replaying the transcript each turn; the
215
+ * transcript is still held here to drive compaction, history, and reseed.
216
+ */
159
217
  declare class ChatSession {
160
218
  private system;
161
- private readonly options;
162
219
  private readonly compactAtTokens;
163
220
  private readonly keepRecentTurns;
221
+ private readonly backend;
164
222
  private readonly generateFn;
165
223
  private messages;
166
224
  /** Recap of turns dropped by compaction; folded into the system prompt. */
167
225
  private summary;
226
+ /** Instructions the backend was last `reset` with (`undefined` ⇒ needs reset). */
227
+ private backendInstructions;
168
228
  constructor(config?: ChatSessionConfig);
169
229
  /** The system prompt actually sent to the model (instructions + any recap). */
170
230
  private effectiveSystem;
@@ -174,6 +234,11 @@ declare class ChatSession {
174
234
  shouldCompact(): boolean;
175
235
  /** Send a user turn and return the assistant's reply (streamed via `onDelta`). */
176
236
  send(text: string, onDelta?: DeltaHandler): Promise<string>;
237
+ /**
238
+ * Reset the backend's session whenever the effective system prompt changes (the
239
+ * first turn, or after a compaction), seeding it with the transcript so far.
240
+ */
241
+ private ensureStarted;
177
242
  /**
178
243
  * Fold all but the most recent turns into the rolling summary. Safe to call
179
244
  * directly; {@link send} calls it automatically when {@link shouldCompact}.
@@ -181,6 +246,8 @@ declare class ChatSession {
181
246
  compact(): Promise<void>;
182
247
  /** Clear the transcript and summary; optionally replace the system prompt. */
183
248
  reset(system?: string): void;
249
+ /** Tear down the underlying live session (kills the helper process). */
250
+ close(): void;
184
251
  }
185
252
 
186
- export { ChatSession, type ChatSessionConfig, type DeltaHandler, type GenerateFn, type GenerateOptions, type GenerateRequest, HELPER_BIN_ENV, type HelperEvent, type HelperOptions, type Message, type ProbeResult, type Role, type UnavailableReason, encodeRequest, estimateConversationTokens, estimateTokens, flattenMessages, generate, parseEvent, probe, resolveHelperPath, splitLines };
253
+ 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, parseEvent, probe, resolveHelperPath, splitLines };
package/dist/index.js CHANGED
@@ -22,6 +22,9 @@ function parseEvent(line) {
22
22
  case "delta":
23
23
  if (typeof event.text !== "string") break;
24
24
  return { type: "delta", text: event.text };
25
+ case "snapshot":
26
+ if (typeof event.content !== "string") break;
27
+ return { type: "snapshot", content: event.content };
25
28
  case "result":
26
29
  if (typeof event.content !== "string") break;
27
30
  return { type: "result", content: event.content };
@@ -120,7 +123,7 @@ async function probe(options = {}) {
120
123
  if (result === void 0) throw new Error("apple-fm helper --probe produced no result");
121
124
  return result;
122
125
  }
123
- async function generate(request, options = {}, onDelta) {
126
+ async function generate(request, options = {}, onDelta, onSnapshot) {
124
127
  let content;
125
128
  await runHelper(["--generate"], options, encodeRequest(request), (line) => {
126
129
  const event = parseEvent(line);
@@ -128,6 +131,9 @@ async function generate(request, options = {}, onDelta) {
128
131
  case "delta":
129
132
  onDelta?.(event.text);
130
133
  break;
134
+ case "snapshot":
135
+ onSnapshot?.(event.content);
136
+ break;
131
137
  case "result":
132
138
  content = event.content;
133
139
  break;
@@ -139,6 +145,133 @@ async function generate(request, options = {}, onDelta) {
139
145
  return content;
140
146
  }
141
147
 
148
+ // src/liveSession.ts
149
+ import { spawn as spawn2 } from "child_process";
150
+ var DEFAULT_TURN_TIMEOUT_MS = 12e4;
151
+ var LiveSession = class {
152
+ command;
153
+ timeoutMs;
154
+ options;
155
+ child;
156
+ buffer = "";
157
+ nextId = 0;
158
+ pending = /* @__PURE__ */ new Map();
159
+ constructor(config = {}) {
160
+ this.command = resolveHelperPath(config);
161
+ this.timeoutMs = config.timeoutMs ?? DEFAULT_TURN_TIMEOUT_MS;
162
+ this.options = config.options;
163
+ }
164
+ /** Recreate the underlying session with new instructions + seed turns. */
165
+ async reset(system, seed = []) {
166
+ await this.dispatch({ type: "reset", system, seed }, void 0);
167
+ }
168
+ /** Send one user turn; prior turns stay in context. Streams via `onDelta`. */
169
+ send(text, onDelta) {
170
+ return this.dispatch(
171
+ { prompt: text, options: this.options, stream: onDelta !== void 0 },
172
+ onDelta
173
+ );
174
+ }
175
+ /** Tear down the helper process and reject any in-flight commands. */
176
+ close() {
177
+ const child = this.child;
178
+ this.child = void 0;
179
+ if (child !== void 0) child.kill("SIGKILL");
180
+ this.rejectAll(new Error("[sessionClosed] live session closed"));
181
+ }
182
+ rejectAll(error) {
183
+ for (const pending of this.pending.values()) {
184
+ clearTimeout(pending.timer);
185
+ pending.reject(error);
186
+ }
187
+ this.pending.clear();
188
+ }
189
+ ensureChild() {
190
+ const existing = this.child;
191
+ if (existing !== void 0 && existing.exitCode === null && !existing.killed) return existing;
192
+ const child = spawn2(this.command, ["--session"], { stdio: ["pipe", "pipe", "pipe"] });
193
+ this.buffer = "";
194
+ child.stdout.setEncoding("utf8");
195
+ child.stdout.on("data", (chunk) => {
196
+ this.onStdout(chunk);
197
+ });
198
+ child.stdin.on("error", () => void 0);
199
+ const onGone = () => {
200
+ if (this.child === child) this.child = void 0;
201
+ this.rejectAll(new Error("[sessionClosed] live session helper exited"));
202
+ };
203
+ child.on("close", onGone);
204
+ child.on("error", onGone);
205
+ this.child = child;
206
+ return child;
207
+ }
208
+ onStdout(chunk) {
209
+ this.buffer += chunk;
210
+ const { lines, rest } = splitLines(this.buffer);
211
+ this.buffer = rest;
212
+ for (const line of lines) this.onLine(line);
213
+ }
214
+ onLine(line) {
215
+ let value;
216
+ try {
217
+ value = JSON.parse(line);
218
+ } catch {
219
+ return;
220
+ }
221
+ if (typeof value !== "object" || value === null) return;
222
+ const event = value;
223
+ if (typeof event.id !== "string") return;
224
+ const id = event.id;
225
+ const pending = this.pending.get(id);
226
+ if (pending === void 0) return;
227
+ switch (event.type) {
228
+ case "delta":
229
+ if (typeof event.text === "string") {
230
+ pending.acc += event.text;
231
+ pending.onDelta?.(event.text);
232
+ }
233
+ break;
234
+ case "ready":
235
+ this.settle(id, "");
236
+ break;
237
+ case "result":
238
+ this.settle(id, typeof event.content === "string" ? event.content : pending.acc);
239
+ break;
240
+ case "error":
241
+ this.fail(id, `[${String(event.code)}] ${String(event.message)}`);
242
+ break;
243
+ default:
244
+ break;
245
+ }
246
+ }
247
+ settle(id, content) {
248
+ const pending = this.pending.get(id);
249
+ if (pending === void 0) return;
250
+ clearTimeout(pending.timer);
251
+ this.pending.delete(id);
252
+ pending.resolve(content);
253
+ }
254
+ fail(id, message) {
255
+ const pending = this.pending.get(id);
256
+ if (pending === void 0) return;
257
+ clearTimeout(pending.timer);
258
+ this.pending.delete(id);
259
+ pending.reject(new Error(message));
260
+ }
261
+ dispatch(command, onDelta) {
262
+ const child = this.ensureChild();
263
+ const id = String(this.nextId++);
264
+ return new Promise((resolve, reject) => {
265
+ const timer = setTimeout(() => {
266
+ this.pending.delete(id);
267
+ reject(new Error(`live session timed out after ${String(this.timeoutMs)}ms`));
268
+ }, this.timeoutMs);
269
+ this.pending.set(id, { resolve, reject, onDelta, acc: "", timer });
270
+ child.stdin.write(JSON.stringify({ ...command, id }) + "\n");
271
+ });
272
+ }
273
+ };
274
+
142
275
  // src/session.ts
143
276
  var DEFAULT_COMPACT_AT = 3e3;
144
277
  var DEFAULT_KEEP_RECENT = 4;
@@ -148,18 +281,20 @@ function defaultGenerateFn(helper, options) {
148
281
  }
149
282
  var ChatSession = class {
150
283
  system;
151
- options;
152
284
  compactAtTokens;
153
285
  keepRecentTurns;
286
+ backend;
154
287
  generateFn;
155
288
  messages = [];
156
289
  /** Recap of turns dropped by compaction; folded into the system prompt. */
157
290
  summary;
291
+ /** Instructions the backend was last `reset` with (`undefined` ⇒ needs reset). */
292
+ backendInstructions;
158
293
  constructor(config = {}) {
159
294
  this.system = config.system ?? "";
160
- this.options = config.options;
161
295
  this.compactAtTokens = config.compactAtTokens ?? DEFAULT_COMPACT_AT;
162
296
  this.keepRecentTurns = config.keepRecentTurns ?? DEFAULT_KEEP_RECENT;
297
+ this.backend = config.backend ?? new LiveSession({ ...config.helper, options: config.options });
163
298
  this.generateFn = config.generateFn ?? defaultGenerateFn(config.helper, config.options);
164
299
  }
165
300
  /** The system prompt actually sent to the model (instructions + any recap). */
@@ -182,11 +317,35 @@ ${recap}` : recap;
182
317
  /** Send a user turn and return the assistant's reply (streamed via `onDelta`). */
183
318
  async send(text, onDelta) {
184
319
  if (this.shouldCompact()) await this.compact();
320
+ await this.ensureStarted();
185
321
  this.messages.push({ role: "user", content: text });
186
- const reply = await this.generateFn(this.effectiveSystem(), this.messages, onDelta);
322
+ let reply;
323
+ try {
324
+ reply = await this.backend.send(text, onDelta);
325
+ } catch (error) {
326
+ if (!recoverable(error)) {
327
+ this.messages.pop();
328
+ throw error;
329
+ }
330
+ this.messages.pop();
331
+ this.backendInstructions = void 0;
332
+ await this.ensureStarted();
333
+ this.messages.push({ role: "user", content: text });
334
+ reply = await this.backend.send(text, onDelta);
335
+ }
187
336
  this.messages.push({ role: "assistant", content: reply });
188
337
  return reply;
189
338
  }
339
+ /**
340
+ * Reset the backend's session whenever the effective system prompt changes (the
341
+ * first turn, or after a compaction), seeding it with the transcript so far.
342
+ */
343
+ async ensureStarted() {
344
+ const system = this.effectiveSystem();
345
+ if (this.backendInstructions === system) return;
346
+ await this.backend.reset(system, this.messages);
347
+ this.backendInstructions = system;
348
+ }
190
349
  /**
191
350
  * Fold all but the most recent turns into the rolling summary. Safe to call
192
351
  * directly; {@link send} calls it automatically when {@link shouldCompact}.
@@ -209,11 +368,20 @@ ${this.summary}` : "",
209
368
  if (system !== void 0) this.system = system;
210
369
  this.messages = [];
211
370
  this.summary = void 0;
371
+ this.backendInstructions = void 0;
372
+ }
373
+ /** Tear down the underlying live session (kills the helper process). */
374
+ close() {
375
+ this.backend.close();
212
376
  }
213
377
  };
378
+ function recoverable(error) {
379
+ return error instanceof Error && error.message.includes("[sessionClosed]");
380
+ }
214
381
  export {
215
382
  ChatSession,
216
383
  HELPER_BIN_ENV,
384
+ LiveSession,
217
385
  encodeRequest,
218
386
  estimateConversationTokens,
219
387
  estimateTokens,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apple-fm",
3
- "version": "0.0.1",
3
+ "version": "0.1.0",
4
4
  "description": "Command-line and programmatic access to Apple's on-device Foundation Models (Apple Intelligence) on macOS 26+.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -54,6 +54,7 @@
54
54
  "lint": "eslint src/ tests/",
55
55
  "typecheck": "tsc --noEmit",
56
56
  "clean": "rm -rf dist coverage node_modules/.cache",
57
+ "demo": "npm run build && node scripts/demo.mjs",
57
58
  "release": "bash scripts/release.sh",
58
59
  "release:beta": "bash scripts/release.sh --beta",
59
60
  "prepublishOnly": "npm run build"
@@ -62,6 +63,7 @@
62
63
  "@eslint/js": "^10.0.1",
63
64
  "@types/node": "^25.9.3",
64
65
  "@vitest/coverage-v8": "^4.1.9",
66
+ "domotion-svg": "^0.13.3",
65
67
  "eslint": "^10.5.0",
66
68
  "eslint-plugin-import-x": "^4.16.2",
67
69
  "eslint-plugin-simple-import-sort": "^12.1.1",
@@ -1,6 +1,8 @@
1
1
  #!/usr/bin/env bash
2
- # Compile the Apple Foundation Models helper (apple-fm-helper/main.swift) — the
3
- # native Swift binary that apple-fm shells out to.
2
+ # Compile the Apple Foundation Models helper (apple-fm-helper/*.swift) — the
3
+ # native Swift binary that apple-fm shells out to. The helper is split across a
4
+ # few .swift files (main.swift holds the entry point); they share one module and
5
+ # are compiled together.
4
6
  #
5
7
  # GUARDED so it never breaks a build: it no-ops with exit 0 on non-macOS, when
6
8
  # swiftc is missing, or when the macOS 26 SDK (FoundationModels) isn't present.
@@ -14,7 +16,7 @@ set -euo pipefail
14
16
 
15
17
  ROOT="$(cd "$(dirname "$0")/.." && pwd)"
16
18
  OUT="${1:-$ROOT/bin/apple-fm-helper}"
17
- SRC="$ROOT/apple-fm-helper/main.swift"
19
+ SRCDIR="$ROOT/apple-fm-helper"
18
20
 
19
21
  if [[ "$(uname -s)" != "Darwin" ]]; then
20
22
  echo "[apple-fm] not macOS — skipping helper build"; exit 0
@@ -22,8 +24,8 @@ fi
22
24
  if ! command -v swiftc >/dev/null 2>&1; then
23
25
  echo "[apple-fm] swiftc not found — skipping helper build"; exit 0
24
26
  fi
25
- if [[ ! -f "$SRC" ]]; then
26
- echo "[apple-fm] source missing ($SRC) — skipping"; exit 0
27
+ if [[ ! -f "$SRCDIR/main.swift" ]]; then
28
+ echo "[apple-fm] source missing ($SRCDIR/main.swift) — skipping"; exit 0
27
29
  fi
28
30
 
29
31
  mkdir -p "$(dirname "$OUT")"
@@ -34,7 +36,9 @@ LOG="$(mktemp "${TMPDIR:-/tmp}/apple-fm-build.XXXXXX.log")"
34
36
  trap 'rm -f "$LOG"' EXIT
35
37
 
36
38
  # Apple Intelligence is arm64-only and needs the macOS 26 SDK for FoundationModels.
37
- if ! swiftc -O -target arm64-apple-macos26 "$SRC" -o "$OUT" 2>"$LOG"; then
39
+ # Compile every .swift in the helper dir into one binary (one shared module).
40
+ sources=("$SRCDIR"/*.swift)
41
+ if ! swiftc -O -target arm64-apple-macos26 "${sources[@]}" -o "$OUT" 2>"$LOG"; then
38
42
  echo "[apple-fm] build failed (needs the macOS 26 SDK / Xcode 26) — skipping:"
39
43
  sed 's/^/[apple-fm] /' "$LOG" || true
40
44
  exit 0