apple-fm 1.2.0 → 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.
- package/README.md +89 -54
- package/apple-fm-helper/GuidedGeneration.swift +64 -19
- package/apple-fm-helper/Session.swift +225 -0
- package/apple-fm-helper/SessionTurns.swift +37 -0
- package/apple-fm-helper/ToolBridge.swift +73 -0
- package/apple-fm-helper/Tools.swift +0 -44
- package/apple-fm-helper/main.swift +175 -182
- package/bin/apple-fm-helper +0 -0
- package/dist/cli.js +1108 -521
- package/dist/index.d.ts +129 -22
- package/dist/index.js +694 -321
- package/dist/read-worker.d.ts +32 -0
- package/dist/read-worker.js +91 -0
- package/package.json +17 -8
- package/scripts/build-apple-fm-helper.sh +7 -1
|
@@ -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
|
+
}
|
|
@@ -19,12 +19,6 @@ struct WireTool: Decodable {
|
|
|
19
19
|
let parameters: JSONValue
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
/// What Node sends back for a tool call: the textual result, or a failure message.
|
|
23
|
-
enum ToolReply {
|
|
24
|
-
case result(String)
|
|
25
|
-
case error(String)
|
|
26
|
-
}
|
|
27
|
-
|
|
28
22
|
/// Thrown when Node reports a tool call failed. The framework surfaces it to the
|
|
29
23
|
/// model, which can continue without that tool.
|
|
30
24
|
struct ToolCallError: Error, CustomStringConvertible {
|
|
@@ -32,44 +26,6 @@ struct ToolCallError: Error, CustomStringConvertible {
|
|
|
32
26
|
var description: String { message }
|
|
33
27
|
}
|
|
34
28
|
|
|
35
|
-
/// Bridges a model-invoked tool call out to Node and back. A `DynamicTool` can't run
|
|
36
|
-
/// the tool itself, so each `call` emits a `tool_call` event and suspends until Node
|
|
37
|
-
/// replies with a `tool_result` / `tool_error` (matched by `callId`). Modeled as an
|
|
38
|
-
/// actor so the stdin reader and the in-flight turn touch it safely; `callId`s are
|
|
39
|
-
/// `"<turnId>:<n>"`.
|
|
40
|
-
actor ToolBridge {
|
|
41
|
-
private var turnId: String?
|
|
42
|
-
private var counter = 0
|
|
43
|
-
private var waiters: [String: CheckedContinuation<ToolReply, Never>] = [:]
|
|
44
|
-
|
|
45
|
-
/// Mark the start of a turn so emitted `tool_call` events carry its id and the
|
|
46
|
-
/// per-turn call counter restarts.
|
|
47
|
-
func beginTurn(_ id: String?) {
|
|
48
|
-
turnId = id
|
|
49
|
-
counter = 0
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/// Emit a `tool_call` for `name`/`argumentsJSON` and suspend until Node replies.
|
|
53
|
-
func call(name: String, argumentsJSON: String) async -> ToolReply {
|
|
54
|
-
counter += 1
|
|
55
|
-
let callId = "\(turnId ?? "0"):\(counter)"
|
|
56
|
-
return await withCheckedContinuation { continuation in
|
|
57
|
-
// Register the waiter BEFORE emitting, so a fast `tool_result` can't race
|
|
58
|
-
// ahead: `resolve` is actor-isolated and can't run until this body
|
|
59
|
-
// suspends, by which point the waiter is already stored.
|
|
60
|
-
waiters[callId] = continuation
|
|
61
|
-
emitToolCall(name: name, callId: callId, argumentsJSON: argumentsJSON, id: turnId)
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/// Resume the suspended call matching `callId` (a no-op if unknown — e.g. a stale
|
|
66
|
-
/// or duplicate reply).
|
|
67
|
-
func resolve(callId: String, reply: ToolReply) {
|
|
68
|
-
guard let continuation = waiters.removeValue(forKey: callId) else { return }
|
|
69
|
-
continuation.resume(returning: reply)
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
|
|
73
29
|
/// A generic tool standing in for any Node-defined tool. `parameters` is provided
|
|
74
30
|
/// explicitly (the compiled caller schema) rather than derived from `Arguments`,
|
|
75
31
|
/// since `Arguments` is the dynamic `GeneratedContent` carrier.
|
|
@@ -5,9 +5,8 @@
|
|
|
5
5
|
//
|
|
6
6
|
// Protocol:
|
|
7
7
|
// apple-fm-helper --probe
|
|
8
|
-
// → one JSON line
|
|
9
|
-
//
|
|
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
|
|
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
|
-
|
|
106
|
+
func emitResult(_ content: String, id: String? = nil) {
|
|
107
107
|
emit("{\"type\":\"result\"\(idField(id)),\"content\":\(encodeString(content))}")
|
|
108
108
|
}
|
|
109
109
|
|
|
110
|
-
|
|
110
|
+
func emitDelta(_ text: String, id: String? = nil) {
|
|
111
111
|
emit("{\"type\":\"delta\"\(idField(id)),\"text\":\(encodeString(text))}")
|
|
112
112
|
}
|
|
113
113
|
|
|
114
|
-
|
|
115
|
-
|
|
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).
|
|
@@ -134,7 +135,7 @@ func emitError(_ code: String, _ message: String, id: String?) {
|
|
|
134
135
|
}
|
|
135
136
|
|
|
136
137
|
/// Emit an error event and exit non-zero (one-shot `--probe`/`--generate`).
|
|
137
|
-
|
|
138
|
+
func failEvent(_ code: String, _ message: String) -> Never {
|
|
138
139
|
emitError(code, message, id: nil)
|
|
139
140
|
exit(1)
|
|
140
141
|
}
|
|
@@ -148,14 +149,34 @@ private func encodeString(_ value: String) -> String {
|
|
|
148
149
|
|
|
149
150
|
// MARK: - Probe
|
|
150
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
|
+
|
|
151
160
|
private func probe() -> Never {
|
|
161
|
+
let reason: String?
|
|
152
162
|
switch SystemLanguageModel.default.availability {
|
|
153
|
-
case .available:
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
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")
|
|
159
180
|
}
|
|
160
181
|
exit(0)
|
|
161
182
|
}
|
|
@@ -195,32 +216,110 @@ private func userPrompt(for request: GenerateRequest) -> String {
|
|
|
195
216
|
return ""
|
|
196
217
|
}
|
|
197
218
|
|
|
198
|
-
private func
|
|
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 {
|
|
199
238
|
guard let options else { return GenerationOptions() }
|
|
200
239
|
return GenerationOptions(
|
|
240
|
+
sampling: options.sampling == .greedy ? .greedy : nil,
|
|
201
241
|
temperature: options.temperature,
|
|
202
242
|
maximumResponseTokens: options.maxTokens)
|
|
203
243
|
}
|
|
204
244
|
|
|
205
|
-
|
|
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
|
+
|
|
206
316
|
guard case .available = SystemLanguageModel.default.availability else {
|
|
207
317
|
failEvent("unavailable", "Apple Foundation Models unavailable")
|
|
208
318
|
}
|
|
209
319
|
let session = LanguageModelSession(instructions: instructions(for: request))
|
|
210
|
-
let prompt = userPrompt(for: request)
|
|
211
320
|
let options = generationOptions(request.options)
|
|
212
321
|
|
|
213
|
-
|
|
214
|
-
// no prompt-guided fallback (see docs/6-guided-generation.md).
|
|
215
|
-
if let schema = request.schema {
|
|
216
|
-
let compiled: GenerationSchema
|
|
217
|
-
do {
|
|
218
|
-
compiled = try compileSchema(from: schema)
|
|
219
|
-
} catch let error as UnsupportedSchema {
|
|
220
|
-
failEvent("unsupportedSchema", error.message)
|
|
221
|
-
} catch {
|
|
222
|
-
failEvent("unsupportedSchema", "could not build a generation schema: \(String(describing: error))")
|
|
223
|
-
}
|
|
322
|
+
if let compiled {
|
|
224
323
|
do {
|
|
225
324
|
if request.stream == true {
|
|
226
325
|
// Structured partials are NOT append-only (keys reorder, values
|
|
@@ -292,7 +391,14 @@ private func errorChain(_ error: Error) -> [NSError] {
|
|
|
292
391
|
/// `.available`); honor the typed `GenerationError` cases; otherwise collapse the
|
|
293
392
|
/// chain to its innermost `domain Code=n` rather than emitting the whole multi-level
|
|
294
393
|
/// NSError dump. See docs/4-protocol.md (error codes).
|
|
295
|
-
|
|
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")
|
|
400
|
+
}
|
|
401
|
+
#endif
|
|
296
402
|
let chain = errorChain(error)
|
|
297
403
|
if chain.contains(where: { $0.domain.contains("ModelManagerError") && $0.code == 1008 }) {
|
|
298
404
|
return ("modelNotReady", "the on-device model is still provisioning; try again shortly")
|
|
@@ -315,149 +421,24 @@ private func failure(for error: Error) -> (code: String, message: String) {
|
|
|
315
421
|
return (code, summary)
|
|
316
422
|
}
|
|
317
423
|
|
|
318
|
-
// MARK: -
|
|
319
|
-
|
|
320
|
-
/// One command read on stdin in `--session` mode: either a turn (has `prompt`) or
|
|
321
|
-
/// a `reset` (`type == "reset"`). See docs/4-protocol.md / docs/7-live-session.md.
|
|
322
|
-
struct SessionCommand: Decodable {
|
|
323
|
-
let type: String?
|
|
324
|
-
let id: String?
|
|
325
|
-
let system: String?
|
|
326
|
-
let seed: [WireMessage]?
|
|
327
|
-
let prompt: String?
|
|
328
|
-
let options: WireOptions?
|
|
329
|
-
let stream: Bool?
|
|
330
|
-
// Tool calling (FR-14): `tools` rides on a `reset` (the framework binds tools at
|
|
331
|
-
// session construction); `callId`/`content`/`message` carry a tool outcome back
|
|
332
|
-
// into a suspended `tool_call`. See docs/9-tool-calling.md.
|
|
333
|
-
let tools: [WireTool]?
|
|
334
|
-
let callId: String?
|
|
335
|
-
let content: String?
|
|
336
|
-
let message: String?
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
/// Compose session instructions from a system prompt plus any seed turns, folded
|
|
340
|
-
/// in as a labeled recap so a `reset` preserves recent context without re-running
|
|
341
|
-
/// it as live turns. Mirrors `userPrompt` / `flattenMessages` labeling.
|
|
342
|
-
private func sessionInstructions(system: String?, seed: [WireMessage]?) -> String? {
|
|
343
|
-
var parts: [String] = []
|
|
344
|
-
if let system, !system.isEmpty { parts.append(system) }
|
|
345
|
-
if let seed, !seed.isEmpty {
|
|
346
|
-
let transcript = seed
|
|
347
|
-
.map { "\($0.role == "assistant" ? "Assistant" : "User"): \($0.content)" }
|
|
348
|
-
.joined(separator: "\n\n")
|
|
349
|
-
parts.append("Conversation so far:\n\(transcript)")
|
|
350
|
-
}
|
|
351
|
-
return parts.isEmpty ? nil : parts.joined(separator: "\n\n")
|
|
352
|
-
}
|
|
424
|
+
// MARK: - Entry
|
|
353
425
|
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
/// turn ends cleanly by emitting a `result` carrying the partial text generated so
|
|
357
|
-
/// far — *not* an `error` — so the Node side (which requested the cancel) settles the
|
|
358
|
-
/// turn and keeps the partial reply (FR-15; esc-to-interrupt). See docs/4-protocol.md.
|
|
359
|
-
private func sessionTurn(_ session: LanguageModelSession, _ command: SessionCommand) async {
|
|
360
|
-
let prompt = command.prompt ?? ""
|
|
361
|
-
let options = generationOptions(command.options)
|
|
362
|
-
var emitted = ""
|
|
426
|
+
private func readRequest() -> GenerateRequest {
|
|
427
|
+
var data = Data()
|
|
363
428
|
do {
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
if Task.isCancelled { break }
|
|
368
|
-
let full = partial.content
|
|
369
|
-
if full.count > emitted.count {
|
|
370
|
-
emitDelta(String(full.dropFirst(emitted.count)), id: command.id)
|
|
371
|
-
emitted = full
|
|
372
|
-
}
|
|
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")
|
|
373
432
|
}
|
|
374
|
-
|
|
375
|
-
} else {
|
|
376
|
-
let response = try await session.respond(to: prompt, options: options)
|
|
377
|
-
emitResult(response.content, id: command.id)
|
|
433
|
+
data.append(chunk)
|
|
378
434
|
}
|
|
379
|
-
} catch is CancellationError {
|
|
380
|
-
emitResult(emitted, id: command.id)
|
|
381
435
|
} catch {
|
|
382
|
-
|
|
383
|
-
// typed CancellationError; treat any error on a cancelled turn as the same
|
|
384
|
-
// clean partial-result interrupt.
|
|
385
|
-
if Task.isCancelled {
|
|
386
|
-
emitResult(emitted, id: command.id)
|
|
387
|
-
} else {
|
|
388
|
-
let f = failure(for: error)
|
|
389
|
-
emitError(f.code, f.message, id: command.id)
|
|
390
|
-
}
|
|
436
|
+
failEvent("badRequest", "could not read the generation request")
|
|
391
437
|
}
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
/// otherwise the plain session. Tools are bound at construction (the framework's
|
|
396
|
-
/// model), so they ride on `reset`, not each turn.
|
|
397
|
-
private func makeSession(_ command: SessionCommand, bridge: ToolBridge) -> LanguageModelSession {
|
|
398
|
-
let instructions = sessionInstructions(system: command.system, seed: command.seed)
|
|
399
|
-
let tools = buildTools(command.tools ?? [], bridge: bridge)
|
|
400
|
-
if tools.isEmpty {
|
|
401
|
-
return LanguageModelSession(instructions: instructions)
|
|
402
|
-
}
|
|
403
|
-
return LanguageModelSession(tools: tools, instructions: instructions)
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
/// Hold one `LanguageModelSession` across many turns (KV-cache reuse). Reads one
|
|
407
|
-
/// command per stdin line and exits 0 on EOF. A turn error is reported per-turn and
|
|
408
|
-
/// does not end the loop; a `reset` recreates the session with new instructions +
|
|
409
|
-
/// seed (+ tools) and acks with `ready`.
|
|
410
|
-
///
|
|
411
|
-
/// Turns are serial, but the model may call a tool mid-turn — so a turn runs as a
|
|
412
|
-
/// detached task while the reader keeps reading, delivering the `tool_result` /
|
|
413
|
-
/// `tool_error` lines into the suspended `tool_call` via the `ToolBridge`. The next
|
|
414
|
-
/// turn waits on the previous task, so only one turn is ever live. See
|
|
415
|
-
/// docs/9-tool-calling.md.
|
|
416
|
-
private func runSession() async -> Never {
|
|
417
|
-
guard case .available = SystemLanguageModel.default.availability else {
|
|
418
|
-
failEvent("unavailable", "Apple Foundation Models unavailable")
|
|
419
|
-
}
|
|
420
|
-
let bridge = ToolBridge()
|
|
421
|
-
var session = LanguageModelSession()
|
|
422
|
-
var currentTurn: Task<Void, Never>?
|
|
423
|
-
do {
|
|
424
|
-
for try await line in FileHandle.standardInput.bytes.lines {
|
|
425
|
-
if line.trimmingCharacters(in: .whitespaces).isEmpty { continue }
|
|
426
|
-
guard let command = try? JSONDecoder().decode(SessionCommand.self, from: Data(line.utf8)) else {
|
|
427
|
-
emitError("badRequest", "malformed session command", id: nil)
|
|
428
|
-
continue
|
|
429
|
-
}
|
|
430
|
-
switch command.type {
|
|
431
|
-
case "tool_result":
|
|
432
|
-
await bridge.resolve(callId: command.callId ?? "", reply: .result(command.content ?? ""))
|
|
433
|
-
case "tool_error":
|
|
434
|
-
await bridge.resolve(callId: command.callId ?? "", reply: .error(command.message ?? "tool failed"))
|
|
435
|
-
case "cancel":
|
|
436
|
-
// Interrupt the in-flight turn (FR-15). Turns are serial, so the one
|
|
437
|
-
// live task is the target; it ends by emitting its partial `result`.
|
|
438
|
-
currentTurn?.cancel()
|
|
439
|
-
case "reset":
|
|
440
|
-
await currentTurn?.value // no turn should be in flight, but be safe
|
|
441
|
-
session = makeSession(command, bridge: bridge)
|
|
442
|
-
emitReady(command.id)
|
|
443
|
-
default:
|
|
444
|
-
await currentTurn?.value // serialize: one turn at a time
|
|
445
|
-
await bridge.beginTurn(command.id)
|
|
446
|
-
let active = session
|
|
447
|
-
currentTurn = Task { await sessionTurn(active, command) }
|
|
448
|
-
}
|
|
449
|
-
}
|
|
450
|
-
await currentTurn?.value
|
|
451
|
-
} catch {
|
|
452
|
-
failEvent("inferenceFailed", "session input error: \(String(describing: error))")
|
|
438
|
+
if data.last == 10 { data.removeLast() }
|
|
439
|
+
guard data.count <= maxInputFrameBytes else {
|
|
440
|
+
failEvent("badRequest", "generation request exceeds 4 MiB")
|
|
453
441
|
}
|
|
454
|
-
exit(0)
|
|
455
|
-
}
|
|
456
|
-
|
|
457
|
-
// MARK: - Entry
|
|
458
|
-
|
|
459
|
-
private func readRequest() -> GenerateRequest {
|
|
460
|
-
let data = FileHandle.standardInput.readDataToEndOfFile()
|
|
461
442
|
guard let request = try? JSONDecoder().decode(GenerateRequest.self, from: data) else {
|
|
462
443
|
failEvent("badRequest", "expected a JSON generation request on stdin")
|
|
463
444
|
}
|
|
@@ -467,14 +448,26 @@ private func readRequest() -> GenerateRequest {
|
|
|
467
448
|
let args = CommandLine.arguments
|
|
468
449
|
if args.contains("--probe") {
|
|
469
450
|
probe()
|
|
451
|
+
} else if args.contains("--tokens") {
|
|
452
|
+
let request = readRequest()
|
|
453
|
+
Task { await countPromptTokens(request) }
|
|
454
|
+
dispatchMain()
|
|
470
455
|
} else if args.contains("--generate") {
|
|
471
456
|
let request = readRequest()
|
|
472
|
-
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) }
|
|
473
466
|
dispatchMain()
|
|
474
467
|
} else if args.contains("--session") {
|
|
475
468
|
Task { await runSession() }
|
|
476
469
|
dispatchMain()
|
|
477
470
|
} else {
|
|
478
|
-
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))
|
|
479
472
|
exit(64)
|
|
480
473
|
}
|
package/bin/apple-fm-helper
CHANGED
|
Binary file
|