apple-fm 1.0.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,73 @@
1
+ /// What Node sends back for a tool call: the textual result, or a failure message.
2
+ enum ToolReply {
3
+ case result(String)
4
+ case error(String)
5
+ }
6
+
7
+ /// Bridges a model-invoked tool call out to Node and back. A `DynamicTool` can't run
8
+ /// the tool itself, so each `call` emits a `tool_call` event and suspends until Node
9
+ /// replies with a `tool_result` / `tool_error` (matched by `callId`). Modeled as an
10
+ /// actor so the stdin reader and the in-flight turn touch it safely; `callId`s are
11
+ /// `"<turnId>:<n>"`.
12
+ actor ToolBridge {
13
+ private let emit: @Sendable (String, String, String, String?) -> Void
14
+ private var turnId: String?
15
+ private var counter = 0
16
+ private var cancelled = false
17
+ private var inputClosed = false
18
+ private var waiters: [String: CheckedContinuation<ToolReply, Never>] = [:]
19
+
20
+ init(emit: @escaping @Sendable (String, String, String, String?) -> Void) {
21
+ self.emit = emit
22
+ }
23
+
24
+ /// Mark the start of a turn so emitted `tool_call` events carry its id and the
25
+ /// per-turn call counter restarts.
26
+ func beginTurn(_ id: String?) {
27
+ turnId = id
28
+ counter = 0
29
+ cancelled = false
30
+ }
31
+
32
+ /// Wake calls suspended in a cancelled native turn so it can finish promptly.
33
+ func cancelTurn(_ id: String?) {
34
+ guard turnId == id else { return }
35
+ cancelled = true
36
+ failWaiters("tool call interrupted")
37
+ }
38
+
39
+ /// No more tool results can arrive once the input stream closes.
40
+ func finishInput() {
41
+ inputClosed = true
42
+ failWaiters("session input closed")
43
+ }
44
+
45
+ private func failWaiters(_ message: String) {
46
+ for continuation in waiters.values {
47
+ continuation.resume(returning: .error(message))
48
+ }
49
+ waiters.removeAll()
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
+ guard !inputClosed else { return .error("session input closed") }
55
+ guard !cancelled, !Task.isCancelled else { return .error("tool call interrupted") }
56
+ counter += 1
57
+ let callId = "\(turnId ?? "0"):\(counter)"
58
+ return await withCheckedContinuation { continuation in
59
+ // Register the waiter BEFORE emitting, so a fast `tool_result` can't race
60
+ // ahead: `resolve` is actor-isolated and can't run until this body
61
+ // suspends, by which point the waiter is already stored.
62
+ waiters[callId] = continuation
63
+ emit(name, callId, argumentsJSON, turnId)
64
+ }
65
+ }
66
+
67
+ /// Resume the suspended call matching `callId` (a no-op if unknown — e.g. a stale
68
+ /// or duplicate reply).
69
+ func resolve(callId: String, reply: ToolReply) {
70
+ guard let continuation = waiters.removeValue(forKey: callId) else { return }
71
+ continuation.resume(returning: reply)
72
+ }
73
+ }
@@ -0,0 +1,68 @@
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
+ /// Thrown when Node reports a tool call failed. The framework surfaces it to the
23
+ /// model, which can continue without that tool.
24
+ struct ToolCallError: Error, CustomStringConvertible {
25
+ let message: String
26
+ var description: String { message }
27
+ }
28
+
29
+ /// A generic tool standing in for any Node-defined tool. `parameters` is provided
30
+ /// explicitly (the compiled caller schema) rather than derived from `Arguments`,
31
+ /// since `Arguments` is the dynamic `GeneratedContent` carrier.
32
+ struct DynamicTool: Tool {
33
+ typealias Arguments = GeneratedContent
34
+ typealias Output = String
35
+
36
+ let name: String
37
+ let description: String
38
+ let parameters: GenerationSchema
39
+ let bridge: ToolBridge
40
+
41
+ func call(arguments: GeneratedContent) async throws -> String {
42
+ let reply = await bridge.call(name: name, argumentsJSON: arguments.jsonString)
43
+ switch reply {
44
+ case .result(let content):
45
+ return content
46
+ case .error(let message):
47
+ throw ToolCallError(message: message)
48
+ }
49
+ }
50
+ }
51
+
52
+ /// Compile wire tool defs into `DynamicTool`s. A tool whose argument schema can't be
53
+ /// expressed natively is skipped with an `unsupportedSchema` diagnostic rather than
54
+ /// failing the whole session — the other tools still work.
55
+ func buildTools(_ defs: [WireTool], bridge: ToolBridge) -> [any Tool] {
56
+ var tools: [any Tool] = []
57
+ for def in defs {
58
+ do {
59
+ let schema = try compileSchema(from: def.parameters)
60
+ tools.append(DynamicTool(name: def.name, description: def.description, parameters: schema, bridge: bridge))
61
+ } catch let error as UnsupportedSchema {
62
+ emitError("unsupportedSchema", "tool \(def.name): \(error.message)", id: nil)
63
+ } catch {
64
+ emitError("unsupportedSchema", "tool \(def.name): could not build a generation schema", id: nil)
65
+ }
66
+ }
67
+ return tools
68
+ }
@@ -5,9 +5,8 @@
5
5
  //
6
6
  // Protocol:
7
7
  // apple-fm-helper --probe
8
- // → one JSON line: {"available":true}
9
- // or {"available":false,"reason":"appleIntelligenceNotEnabled"}
10
- // apple-fm-helper --generate
8
+ // → one JSON line with on-device status and its model entry.
9
+ // apple-fm-helper --generate (or --tag-content for JSON topic tags)
11
10
  // reads one request object on stdin:
12
11
  // {"system"?,"prompt"?,"messages"?:[{"role","content"}],
13
12
  // "schema"?,"options"?:{"temperature"?,"maxTokens"?},"stream"?}
@@ -21,6 +20,9 @@
21
20
  // APPLE_FM_BIN (or build it to ./bin/apple-fm-helper).
22
21
  import Foundation
23
22
  import FoundationModels
23
+ #if APPLE_FM_IMAGES
24
+ import ImageIO
25
+ #endif
24
26
 
25
27
  // MARK: - Wire types
26
28
 
@@ -29,12 +31,19 @@ struct WireMessage: Decodable {
29
31
  let content: String
30
32
  }
31
33
 
34
+ enum WireSampling: String, Decodable {
35
+ case greedy
36
+ }
37
+
32
38
  struct WireOptions: Decodable {
39
+ let sampling: WireSampling?
33
40
  let temperature: Double?
34
41
  let maxTokens: Int?
35
42
  }
36
43
 
37
44
  struct GenerateRequest: Decodable {
45
+ let imagePath: String?
46
+ let imagePaths: [String]?
38
47
  let system: String?
39
48
  let prompt: String?
40
49
  let messages: [WireMessage]?
@@ -46,8 +55,7 @@ struct GenerateRequest: Decodable {
46
55
  let stream: Bool?
47
56
  }
48
57
 
49
- /// A minimal decoder for arbitrary JSON, used to carry the optional `schema`
50
- /// through verbatim so it can be re-rendered into the prompt.
58
+ /// A decoder for the raw JSON Schema carried by the wire request.
51
59
  indirect enum JSONValue: Decodable {
52
60
  case null
53
61
  case bool(Bool)
@@ -75,24 +83,16 @@ indirect enum JSONValue: Decodable {
75
83
  }
76
84
  }
77
85
 
78
- var jsonString: String? {
79
- switch self {
80
- case .null: return "null"
81
- case .bool(let b): return b ? "true" : "false"
82
- case .number(let n):
83
- return n == n.rounded() ? String(Int(n)) : String(n)
84
- case .string(let s): return encodeString(s)
85
- case .array(let a): return "[" + a.compactMap { $0.jsonString }.joined(separator: ",") + "]"
86
- case .object(let o):
87
- return "{" + o.map { "\(encodeString($0.key)):\($0.value.jsonString ?? "null")" }
88
- .joined(separator: ",") + "}"
89
- }
90
- }
91
86
  }
92
87
 
93
88
  // MARK: - Output
94
89
 
90
+ private let outputLock = NSLock()
91
+ let maxInputFrameBytes = 4 * 1024 * 1024
92
+
95
93
  private func emit(_ json: String) {
94
+ outputLock.lock()
95
+ defer { outputLock.unlock() }
96
96
  FileHandle.standardOutput.write(Data((json + "\n").utf8))
97
97
  }
98
98
 
@@ -103,16 +103,17 @@ private func idField(_ id: String?) -> String {
103
103
  return ",\"id\":\(encodeString(id))"
104
104
  }
105
105
 
106
- private func emitResult(_ content: String, id: String? = nil) {
106
+ func emitResult(_ content: String, id: String? = nil) {
107
107
  emit("{\"type\":\"result\"\(idField(id)),\"content\":\(encodeString(content))}")
108
108
  }
109
109
 
110
- private func emitDelta(_ text: String, id: String? = nil) {
110
+ func emitDelta(_ text: String, id: String? = nil) {
111
111
  emit("{\"type\":\"delta\"\(idField(id)),\"text\":\(encodeString(text))}")
112
112
  }
113
113
 
114
- private func emitReady(_ id: String?) {
115
- emit("{\"type\":\"ready\"\(idField(id))}")
114
+ func emitReady(_ id: String?) {
115
+ let capability = modelContextSize().map { ",\"contextSize\":\($0)" } ?? ""
116
+ emit("{\"type\":\"ready\"\(idField(id))\(capability),\"transcriptPersistence\":true}")
116
117
  }
117
118
 
118
119
  /// A full partial value for guided streaming (replace semantics, not a suffix).
@@ -120,13 +121,21 @@ private func emitSnapshot(_ content: String, id: String? = nil) {
120
121
  emit("{\"type\":\"snapshot\"\(idField(id)),\"content\":\(encodeString(content))}")
121
122
  }
122
123
 
123
- /// Emit an error event without exiting (used per-turn in `--session`).
124
- private func emitError(_ code: String, _ message: String, id: String?) {
124
+ /// A tool the model invoked mid-turn. `argumentsJSON` is embedded as raw JSON (the
125
+ /// model's generated arguments), not a string. `internal` so `ToolBridge` (in
126
+ /// Tools.swift) can call it. See docs/9-tool-calling.md.
127
+ func emitToolCall(name: String, callId: String, argumentsJSON: String, id: String?) {
128
+ emit("{\"type\":\"tool_call\"\(idField(id)),\"callId\":\(encodeString(callId)),\"name\":\(encodeString(name)),\"arguments\":\(argumentsJSON)}")
129
+ }
130
+
131
+ /// Emit an error event without exiting (used per-turn in `--session`). `internal` so
132
+ /// `buildTools` (in Tools.swift) can report an unsupported tool schema.
133
+ func emitError(_ code: String, _ message: String, id: String?) {
125
134
  emit("{\"type\":\"error\"\(idField(id)),\"code\":\(encodeString(code)),\"message\":\(encodeString(message))}")
126
135
  }
127
136
 
128
137
  /// Emit an error event and exit non-zero (one-shot `--probe`/`--generate`).
129
- private func failEvent(_ code: String, _ message: String) -> Never {
138
+ func failEvent(_ code: String, _ message: String) -> Never {
130
139
  emitError(code, message, id: nil)
131
140
  exit(1)
132
141
  }
@@ -140,14 +149,34 @@ private func encodeString(_ value: String) -> String {
140
149
 
141
150
  // MARK: - Probe
142
151
 
152
+ private func modelContextSize() -> Int? {
153
+ if #available(macOS 26.4, *) {
154
+ let capacity = SystemLanguageModel.default.contextSize
155
+ return capacity > 0 ? capacity : nil
156
+ }
157
+ return nil
158
+ }
159
+
143
160
  private func probe() -> Never {
161
+ let reason: String?
144
162
  switch SystemLanguageModel.default.availability {
145
- case .available:
146
- emit("{\"available\":true}")
147
- case .unavailable(let reason):
148
- emit("{\"available\":false,\"reason\":\(encodeString(reasonString(reason)))}")
149
- @unknown default:
150
- emit("{\"available\":false,\"reason\":\"unknown\"}")
163
+ case .available: reason = nil
164
+ case .unavailable(let unavailable): reason = reasonString(unavailable)
165
+ @unknown default: reason = "unknown"
166
+ }
167
+
168
+ var status: [String: Any] = ["available": reason == nil]
169
+ status["reason"] = reason
170
+ var result = status
171
+ var model = status
172
+ model["id"] = "on-device"
173
+ result["models"] = [model]
174
+ result["contextSize"] = modelContextSize()
175
+ do {
176
+ let data = try JSONSerialization.data(withJSONObject: result, options: .sortedKeys)
177
+ emit(String(decoding: data, as: UTF8.self))
178
+ } catch {
179
+ failEvent("probeFailed", "could not encode model availability")
151
180
  }
152
181
  exit(0)
153
182
  }
@@ -187,32 +216,110 @@ private func userPrompt(for request: GenerateRequest) -> String {
187
216
  return ""
188
217
  }
189
218
 
190
- private func generationOptions(_ options: WireOptions?) -> GenerationOptions {
219
+ private func countPromptTokens(_ request: GenerateRequest) async -> Never {
220
+ guard #available(macOS 26.4, *) else {
221
+ failEvent("unsupported", "native token counting requires macOS 26.4 or later")
222
+ }
223
+ let model = SystemLanguageModel.default
224
+ guard case .available = model.availability else {
225
+ failEvent("unavailable", "Apple Foundation Models unavailable")
226
+ }
227
+ do {
228
+ let count = try await model.tokenCount(for: userPrompt(for: request))
229
+ emitResult(String(count))
230
+ } catch {
231
+ let f = failure(for: error)
232
+ failEvent(f.code, f.message)
233
+ }
234
+ exit(0)
235
+ }
236
+
237
+ func generationOptions(_ options: WireOptions?) -> GenerationOptions {
191
238
  guard let options else { return GenerationOptions() }
192
239
  return GenerationOptions(
240
+ sampling: options.sampling == .greedy ? .greedy : nil,
193
241
  temperature: options.temperature,
194
242
  maximumResponseTokens: options.maxTokens)
195
243
  }
196
244
 
197
- private func generate(_ request: GenerateRequest) async -> Never {
245
+ @Generable
246
+ private struct ContentTags {
247
+ @Guide(description: "Short tags that categorize the input text.")
248
+ let tags: [String]
249
+ }
250
+
251
+ private func tagContent(_ request: GenerateRequest) async -> Never {
252
+ guard request.schema == nil, request.stream != true else {
253
+ failEvent("badRequest", "content-tagging cannot be combined with streaming or a custom schema")
254
+ }
255
+ let model = SystemLanguageModel(useCase: .contentTagging)
256
+ guard case .available = model.availability else {
257
+ failEvent("unavailable", "Apple Foundation Models content tagging unavailable")
258
+ }
259
+ let session = LanguageModelSession(
260
+ model: model,
261
+ instructions: instructions(for: request) ?? "Return the most significant topic tags in the input."
262
+ )
263
+ do {
264
+ let response = try await session.respond(
265
+ to: userPrompt(for: request),
266
+ generating: ContentTags.self,
267
+ options: generationOptions(request.options)
268
+ )
269
+ let data = try JSONEncoder().encode(response.content.tags)
270
+ emitResult(String(decoding: data, as: UTF8.self))
271
+ } catch {
272
+ let f = failure(for: error)
273
+ failEvent(f.code, f.message)
274
+ }
275
+ exit(0)
276
+ }
277
+
278
+ private func generateImage(_ request: GenerateRequest) async -> Never {
279
+ #if APPLE_FM_IMAGES
280
+ if #available(macOS 27.0, *) {
281
+ let paths = request.imagePaths ?? request.imagePath.map { [$0] } ?? []
282
+ guard !paths.isEmpty, paths.allSatisfy({ !$0.isEmpty }) else {
283
+ failEvent("badRequest", "expected at least one local image path")
284
+ }
285
+ let urls = paths.map { path in
286
+ let url = URL(fileURLWithPath: path)
287
+ guard let source = CGImageSourceCreateWithURL(url as CFURL, nil),
288
+ CGImageSourceGetCount(source) > 0 else {
289
+ failEvent("invalidImage", "could not read an image at \(path)")
290
+ }
291
+ return url
292
+ }
293
+ let prompt = Prompt {
294
+ userPrompt(for: request)
295
+ for url in urls {
296
+ Attachment(imageURL: url)
297
+ }
298
+ }
299
+ await generate(request, prompt: prompt)
300
+ }
301
+ #endif
302
+ failEvent("unsupported", "image input requires macOS 27 and a helper built with the macOS 27 SDK")
303
+ }
304
+
305
+ private func generate(_ request: GenerateRequest, prompt: Prompt) async -> Never {
306
+ // Validate the user's schema independently of model availability.
307
+ let compiled: GenerationSchema?
308
+ do {
309
+ compiled = try request.schema.map { try compileSchema(from: $0) }
310
+ } catch let error as UnsupportedSchema {
311
+ failEvent("unsupportedSchema", error.message)
312
+ } catch {
313
+ failEvent("unsupportedSchema", "could not build a generation schema: \(String(describing: error))")
314
+ }
315
+
198
316
  guard case .available = SystemLanguageModel.default.availability else {
199
317
  failEvent("unavailable", "Apple Foundation Models unavailable")
200
318
  }
201
319
  let session = LanguageModelSession(instructions: instructions(for: request))
202
- let prompt = userPrompt(for: request)
203
320
  let options = generationOptions(request.options)
204
321
 
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
- }
322
+ if let compiled {
216
323
  do {
217
324
  if request.stream == true {
218
325
  // Structured partials are NOT append-only (keys reorder, values
@@ -230,10 +337,9 @@ private func generate(_ request: GenerateRequest) async -> Never {
230
337
  emitResult(response.content.jsonString)
231
338
  }
232
339
  exit(0)
233
- } catch let error as LanguageModelSession.GenerationError {
234
- failEvent(errorCode(error), String(describing: error))
235
340
  } catch {
236
- failEvent("inferenceFailed", String(describing: error))
341
+ let f = failure(for: error)
342
+ failEvent(f.code, f.message)
237
343
  }
238
344
  }
239
345
 
@@ -254,110 +360,85 @@ private func generate(_ request: GenerateRequest) async -> Never {
254
360
  emitResult(response.content)
255
361
  }
256
362
  exit(0)
257
- } catch let error as LanguageModelSession.GenerationError {
258
- failEvent(errorCode(error), String(describing: error))
259
363
  } catch {
260
- failEvent("inferenceFailed", String(describing: error))
364
+ let f = failure(for: error)
365
+ failEvent(f.code, f.message)
261
366
  }
262
367
  }
263
368
 
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"
369
+ /// Collect an NSError and every error nested under it (`NSUnderlyingErrorKey` plus
370
+ /// the `NSMultipleUnderlyingErrorsKey` array), breadth-first, outermost first.
371
+ /// Bounded so a pathological cycle can't spin forever.
372
+ private func errorChain(_ error: Error) -> [NSError] {
373
+ var collected: [NSError] = []
374
+ var queue: [NSError] = [error as NSError]
375
+ while let next = queue.first, collected.count < 50 {
376
+ queue.removeFirst()
377
+ collected.append(next)
378
+ if let underlying = next.userInfo[NSUnderlyingErrorKey] as? NSError {
379
+ queue.append(underlying)
380
+ }
381
+ if let multiple = next.userInfo[NSMultipleUnderlyingErrorsKey] as? [Error] {
382
+ queue.append(contentsOf: multiple.map { $0 as NSError })
383
+ }
269
384
  }
385
+ return collected
270
386
  }
271
387
 
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)")
388
+ /// Reduce a thrown error to a wire `(code, message)`. The framework wraps the real
389
+ /// cause in nested NSErrors, so: recognize "model still provisioning"
390
+ /// (`ModelManagerError` 1008 — which can occur even though `availability` reported
391
+ /// `.available`); honor the typed `GenerationError` cases; otherwise collapse the
392
+ /// chain to its innermost `domain Code=n` rather than emitting the whole multi-level
393
+ /// NSError dump. See docs/4-protocol.md (error codes).
394
+ func failure(for error: Error) -> (code: String, message: String) {
395
+ #if APPLE_FM_IMAGES
396
+ if #available(macOS 27.0, *),
397
+ let modelError = error as? LanguageModelError,
398
+ case .contextSizeExceeded = modelError {
399
+ return ("contextWindowExceeded", "the model's context window was exceeded")
297
400
  }
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)
401
+ #endif
402
+ let chain = errorChain(error)
403
+ if chain.contains(where: { $0.domain.contains("ModelManagerError") && $0.code == 1008 }) {
404
+ return ("modelNotReady", "the on-device model is still provisioning; try again shortly")
405
+ }
406
+ if let generation = error as? LanguageModelSession.GenerationError {
407
+ switch generation {
408
+ case .exceededContextWindowSize:
409
+ return ("contextWindowExceeded", "the model's context window was exceeded")
410
+ case .guardrailViolation:
411
+ return ("guardrailViolation", "the request was blocked by the model's safety guardrails")
412
+ default:
413
+ break
319
414
  }
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
415
  }
416
+ let innermost = chain.last ?? (error as NSError)
417
+ let summary = "\(innermost.domain) Code=\(innermost.code)"
418
+ // A typed-but-unmatched generation error is still a generation-side failure;
419
+ // anything else is a generic inference failure.
420
+ let code = error is LanguageModelSession.GenerationError ? "generationError" : "inferenceFailed"
421
+ return (code, summary)
325
422
  }
326
423
 
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()
424
+ // MARK: - Entry
425
+
426
+ private func readRequest() -> GenerateRequest {
427
+ var data = Data()
336
428
  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)
429
+ while let chunk = try FileHandle.standardInput.read(upToCount: 64 * 1024), !chunk.isEmpty {
430
+ guard data.count + chunk.count <= maxInputFrameBytes + 1 else {
431
+ failEvent("badRequest", "generation request exceeds 4 MiB")
349
432
  }
433
+ data.append(chunk)
350
434
  }
351
435
  } catch {
352
- failEvent("inferenceFailed", "session input error: \(String(describing: error))")
436
+ failEvent("badRequest", "could not read the generation request")
437
+ }
438
+ if data.last == 10 { data.removeLast() }
439
+ guard data.count <= maxInputFrameBytes else {
440
+ failEvent("badRequest", "generation request exceeds 4 MiB")
353
441
  }
354
- exit(0)
355
- }
356
-
357
- // MARK: - Entry
358
-
359
- private func readRequest() -> GenerateRequest {
360
- let data = FileHandle.standardInput.readDataToEndOfFile()
361
442
  guard let request = try? JSONDecoder().decode(GenerateRequest.self, from: data) else {
362
443
  failEvent("badRequest", "expected a JSON generation request on stdin")
363
444
  }
@@ -367,14 +448,26 @@ private func readRequest() -> GenerateRequest {
367
448
  let args = CommandLine.arguments
368
449
  if args.contains("--probe") {
369
450
  probe()
451
+ } else if args.contains("--tokens") {
452
+ let request = readRequest()
453
+ Task { await countPromptTokens(request) }
454
+ dispatchMain()
370
455
  } else if args.contains("--generate") {
371
456
  let request = readRequest()
372
- Task { await generate(request) }
457
+ Task { await generate(request, prompt: Prompt(userPrompt(for: request))) }
458
+ dispatchMain()
459
+ } else if args.contains("--generate-image") || args.contains("--generate-images") {
460
+ let request = readRequest()
461
+ Task { await generateImage(request) }
462
+ dispatchMain()
463
+ } else if args.contains("--tag-content") {
464
+ let request = readRequest()
465
+ Task { await tagContent(request) }
373
466
  dispatchMain()
374
467
  } else if args.contains("--session") {
375
468
  Task { await runSession() }
376
469
  dispatchMain()
377
470
  } else {
378
- FileHandle.standardError.write(Data("usage: apple-fm-helper --probe | --generate | --session\n".utf8))
471
+ FileHandle.standardError.write(Data("usage: apple-fm-helper --probe | --tokens | --generate | --generate-image | --generate-images | --tag-content | --session\n".utf8))
379
472
  exit(64)
380
473
  }
Binary file