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
package/README.md
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
1
|
# apple-fm
|
|
2
2
|
|
|
3
3
|
**Apple Intelligence from your command line and your code.** apple-fm gives you
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
leave your Mac.
|
|
4
|
+
Apple's **Foundation Models** on **macOS 26+ / Apple Silicon**. Inference runs
|
|
5
|
+
on-device and works offline without an API key.
|
|
7
6
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
library, so you can use the on-device model from your terminal or your code.
|
|
7
|
+
apple-fm provides a lightweight CLI and TypeScript library for the Foundation
|
|
8
|
+
Models framework, including persistent, permission-gated chat.
|
|
11
9
|
|
|
12
10
|
<p align="center">
|
|
13
11
|
<img src="assets/demos/generate.svg" alt="apple-fm generate "Explain a closure in one sentence." runs Apple's on-device model and prints the answer — fully offline, no API key." width="880">
|
|
@@ -15,27 +13,51 @@ library, so you can use the on-device model from your terminal or your code.
|
|
|
15
13
|
|
|
16
14
|
## Why apple-fm
|
|
17
15
|
|
|
18
|
-
- **
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
- **
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
- **
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
-
|
|
38
|
-
|
|
16
|
+
- **From shell or TypeScript.** Check model availability, generate or stream a
|
|
17
|
+
response, extract content tags, and count prompt tokens.
|
|
18
|
+
- **Structured JSON.** Native guided generation enforces supported JSON Schema
|
|
19
|
+
constraints and can stream complete JSON snapshots.
|
|
20
|
+
- **Compare local images.** Attach multiple images to one prompt on macOS 27+,
|
|
21
|
+
including prompts that return guided JSON.
|
|
22
|
+
- **Pick up a chat later.** Save and resume a persistent session. Chat summarizes
|
|
23
|
+
older turns as context fills, `/usage` shows how much context is occupied, and
|
|
24
|
+
**Esc** interrupts a streamed reply while keeping the partial response.
|
|
25
|
+
- **Permission-gated tools.** Enable local file reads and shell commands in chat,
|
|
26
|
+
or register your own tools through the TypeScript library.
|
|
27
|
+
- **Zero Node runtime dependencies.** The Swift helper resolves Apple's current
|
|
28
|
+
on-device model at runtime.
|
|
29
|
+
|
|
30
|
+
## Model selection
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
apple-fm probe
|
|
34
|
+
apple-fm generate --model on-device "Explain Swift actors in one sentence"
|
|
35
|
+
apple-fm chat --model on-device
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
`probe` reports the current on-device model and its availability on macOS 26 and
|
|
39
|
+
later. The model ID is `on-device`, which is also the default for generation and chat.
|
|
40
|
+
On macOS 26.4 and later, `apple-fm tokens 'text'` prints the native prompt token
|
|
41
|
+
count. It also reads text from stdin. `probe` reports the model's `contextSize`
|
|
42
|
+
where available. In chat, `/usage` shows the current context count and capacity when
|
|
43
|
+
native counting is available, or a labeled estimate on older helpers.
|
|
44
|
+
|
|
45
|
+
On macOS 27 and later, repeat `--image` to compare local images in the order you
|
|
46
|
+
attach them. Add `--schema` to return guided JSON.
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
apple-fm generate --image before.png --image after.png "What changed between these images?"
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
In chat, use `/save session.json` and later `apple-fm chat --resume session.json`
|
|
53
|
+
to continue the conversation. If you enabled tools, pass the same `--tools` list
|
|
54
|
+
when resuming.
|
|
55
|
+
|
|
56
|
+
Use `generate --sampling greedy` to select the highest-probability token at each step.
|
|
57
|
+
|
|
58
|
+
Use `apple-fm generate --use-case content-tagging "A picnic at the beach"` to
|
|
59
|
+
extract tags as a JSON array.
|
|
60
|
+
See [model discovery and selection](docs/12-models.md) for the full contract.
|
|
39
61
|
|
|
40
62
|
## Install
|
|
41
63
|
|
|
@@ -44,9 +66,12 @@ npm install -g apple-fm # CLI
|
|
|
44
66
|
npm install apple-fm # library
|
|
45
67
|
```
|
|
46
68
|
|
|
47
|
-
Requires macOS 26+ on Apple Silicon with Apple
|
|
48
|
-
|
|
49
|
-
|
|
69
|
+
Requires Node.js 20+ for the package and macOS 26+ on Apple Silicon with Apple
|
|
70
|
+
Intelligence enabled for inference. The published package normally bundles a
|
|
71
|
+
Developer ID-signed, notarized helper. A source checkout or a package published
|
|
72
|
+
without the helper needs a local Swift build. In the checkout, run `npm ci`,
|
|
73
|
+
`npm run build:helper`, then `npm run build` and use `node dist/cli.js probe`.
|
|
74
|
+
Use Xcode 27 for an image-capable build. See [release details](docs/5-releasing.md).
|
|
50
75
|
|
|
51
76
|
### Platform support
|
|
52
77
|
|
|
@@ -58,7 +83,7 @@ throw a clear `[unsupportedPlatform]` error. Gate on `isPlatformSupported()` or
|
|
|
58
83
|
`probe()`:
|
|
59
84
|
|
|
60
85
|
```ts
|
|
61
|
-
import {
|
|
86
|
+
import { probe, generate } from 'apple-fm';
|
|
62
87
|
|
|
63
88
|
if ((await probe()).available) {
|
|
64
89
|
await generate({ prompt: '…' });
|
|
@@ -70,7 +95,8 @@ if ((await probe()).available) {
|
|
|
70
95
|
## CLI
|
|
71
96
|
|
|
72
97
|
```bash
|
|
73
|
-
apple-fm probe #
|
|
98
|
+
apple-fm probe # list models and availability
|
|
99
|
+
apple-fm tokens "Count this text" # native prompt token count on macOS 26.4+
|
|
74
100
|
apple-fm generate "Summarize: …" # one-shot text
|
|
75
101
|
cat notes.md | apple-fm generate # read the prompt from stdin
|
|
76
102
|
apple-fm generate "…" --stream # stream tokens as they arrive
|
|
@@ -86,14 +112,14 @@ Run `apple-fm --help` for the full flag list.
|
|
|
86
112
|
Before generating, confirm Apple Intelligence is ready on this machine.
|
|
87
113
|
|
|
88
114
|
<p align="center">
|
|
89
|
-
<img src="assets/demos/probe.svg" alt="apple-fm probe
|
|
115
|
+
<img src="assets/demos/probe.svg" alt="apple-fm probe lists the on-device model, availability, and the context capacity when supported." width="880">
|
|
90
116
|
</p>
|
|
91
117
|
|
|
92
118
|
### Structured output
|
|
93
119
|
|
|
94
|
-
Pass a JSON Schema with `--schema`
|
|
95
|
-
|
|
96
|
-
|
|
120
|
+
Pass a supported JSON Schema with `--schema` to get JSON that conforms to it.
|
|
121
|
+
Apple's native guided generation enforces the supported constraints. See the
|
|
122
|
+
[supported JSON Schema subset](docs/6-guided-generation.md).
|
|
97
123
|
|
|
98
124
|
<p align="center">
|
|
99
125
|
<img src="assets/demos/schema.svg" alt="apple-fm generate "Recommend a classic sci-fi novel." --schema novel.json returns a JSON object with title, author, year, and why fields." width="880">
|
|
@@ -102,12 +128,12 @@ into the rest of your tooling.
|
|
|
102
128
|
### Interactive chat
|
|
103
129
|
|
|
104
130
|
`chat` is a multi-turn REPL that streams replies and compacts the transcript
|
|
105
|
-
automatically near the context window.
|
|
106
|
-
`/
|
|
107
|
-
|
|
131
|
+
automatically near the context window. Use `/usage` to see context occupancy,
|
|
132
|
+
`/save` to save a chat, `/tools` to list enabled tools, and `/help` for all
|
|
133
|
+
commands. Press **Esc** while the model is replying to keep the partial reply.
|
|
108
134
|
|
|
109
135
|
<p align="center">
|
|
110
|
-
<img src="assets/demos/chat.svg" alt="apple-fm chat
|
|
136
|
+
<img src="assets/demos/chat.svg" alt="An apple-fm chat session showing an on-device reply and the /usage command." width="880">
|
|
111
137
|
</p>
|
|
112
138
|
|
|
113
139
|
### Tool calling
|
|
@@ -119,11 +145,12 @@ answer you — `read` (read a local file) and `bash` (run a shell command):
|
|
|
119
145
|
apple-fm chat --tools read,bash
|
|
120
146
|
```
|
|
121
147
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
148
|
+
Chat prompts for permission by default. Use `--allow-tool "bash:git status"` to
|
|
149
|
+
approve that exact command in advance. With `--yes`, file reads are approved
|
|
150
|
+
automatically and shell commands still require approval. In non-interactive chat,
|
|
151
|
+
calls that require a prompt are denied. Approved shell commands run with your user
|
|
152
|
+
permissions and can access the network. Library consumers can register their own
|
|
153
|
+
`Tool`. See [tool calling](docs/9-tool-calling.md).
|
|
127
154
|
|
|
128
155
|
## Library
|
|
129
156
|
|
|
@@ -137,12 +164,23 @@ if ((await probe()).available) {
|
|
|
137
164
|
// Streaming
|
|
138
165
|
await generate({ prompt: '…', stream: true }, {}, (chunk) => process.stdout.write(chunk));
|
|
139
166
|
|
|
140
|
-
//
|
|
141
|
-
const json = await generate({
|
|
167
|
+
// Guided output using a supported JSON Schema
|
|
168
|
+
const json = await generate({
|
|
169
|
+
prompt: 'Recommend a classic sci-fi novel',
|
|
170
|
+
schema: {
|
|
171
|
+
type: 'object',
|
|
172
|
+
properties: { title: { type: 'string' } },
|
|
173
|
+
required: ['title'],
|
|
174
|
+
},
|
|
175
|
+
});
|
|
142
176
|
|
|
143
177
|
// Multi-turn chat: one persistent on-device session, auto-compacted
|
|
144
178
|
const chat = new ChatSession({ system: 'You are a helpful assistant.' });
|
|
145
|
-
|
|
179
|
+
try {
|
|
180
|
+
const reply = await chat.send('Hello');
|
|
181
|
+
} finally {
|
|
182
|
+
chat.close();
|
|
183
|
+
}
|
|
146
184
|
}
|
|
147
185
|
```
|
|
148
186
|
|
|
@@ -151,12 +189,9 @@ documented in [docs/ai/code-summary.md](docs/ai/code-summary.md).
|
|
|
151
189
|
|
|
152
190
|
## How it works
|
|
153
191
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
context window fills, so long conversations stay coherent and cheap. And because
|
|
158
|
-
it resolves the current on-device model at runtime, OS and model updates are
|
|
159
|
-
picked up automatically — no reinstall.
|
|
192
|
+
The Node CLI and library talk to a Swift helper over newline-delimited JSON.
|
|
193
|
+
The helper runs inference through Apple’s Foundation Models framework and keeps
|
|
194
|
+
the native chat session alive across turns.
|
|
160
195
|
|
|
161
196
|
## Documentation
|
|
162
197
|
|
|
@@ -15,21 +15,51 @@ private func stringField(_ object: [String: JSONValue], _ key: String) -> String
|
|
|
15
15
|
return nil
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
-
private func
|
|
19
|
-
|
|
20
|
-
|
|
18
|
+
private func decimalField(_ object: [String: JSONValue], _ key: String) throws -> Double? {
|
|
19
|
+
guard let field = object[key] else { return nil }
|
|
20
|
+
guard case .number(let value) = field, value.isFinite else {
|
|
21
|
+
throw UnsupportedSchema(message: "\(key) must be a finite number")
|
|
22
|
+
}
|
|
23
|
+
return value
|
|
21
24
|
}
|
|
22
25
|
|
|
23
|
-
private func
|
|
24
|
-
|
|
25
|
-
|
|
26
|
+
private func integerField(
|
|
27
|
+
_ object: [String: JSONValue], _ key: String, rounding: FloatingPointRoundingRule? = nil
|
|
28
|
+
) throws -> Int? {
|
|
29
|
+
guard let value = try decimalField(object, key) else { return nil }
|
|
30
|
+
let bound = rounding.map { value.rounded($0) } ?? value
|
|
31
|
+
guard let integer = Int(exactly: bound) else {
|
|
32
|
+
throw UnsupportedSchema(message: "\(key) is outside the supported integer range or is not an integer")
|
|
33
|
+
}
|
|
34
|
+
return integer
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
private let unsupportedSchemaKeywords = [
|
|
38
|
+
"$ref", "$defs", "definitions", "oneOf", "anyOf", "allOf", "not",
|
|
39
|
+
"if", "then", "else", "patternProperties", "propertyNames",
|
|
40
|
+
"dependentRequired", "dependentSchemas", "dependencies", "prefixItems",
|
|
41
|
+
"contains", "unevaluatedProperties", "unevaluatedItems", "const",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
private func requiredKeys(_ field: JSONValue?, properties: [String: JSONValue]) throws -> Set<String> {
|
|
45
|
+
guard let field else { return [] }
|
|
46
|
+
guard case .array(let entries) = field else {
|
|
47
|
+
throw UnsupportedSchema(message: "required must be an array of property names")
|
|
48
|
+
}
|
|
49
|
+
var names: Set<String> = []
|
|
50
|
+
for entry in entries {
|
|
51
|
+
guard case .string(let name) = entry, properties[name] != nil, names.insert(name).inserted else {
|
|
52
|
+
throw UnsupportedSchema(message: "required must contain unique names declared in properties")
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return names
|
|
26
56
|
}
|
|
27
57
|
|
|
28
58
|
/// `minimum` / `maximum` → integer range guides (a documented range, or an open
|
|
29
59
|
/// bound). A `minimum > maximum` schema is rejected so the `ClosedRange` is valid.
|
|
30
60
|
private func intGuides(_ object: [String: JSONValue]) throws -> [GenerationGuide<Int>] {
|
|
31
|
-
let lo =
|
|
32
|
-
let hi =
|
|
61
|
+
let lo = try integerField(object, "minimum", rounding: .up)
|
|
62
|
+
let hi = try integerField(object, "maximum", rounding: .down)
|
|
33
63
|
if let lo, let hi {
|
|
34
64
|
guard lo <= hi else { throw UnsupportedSchema(message: "minimum (\(lo)) is greater than maximum (\(hi))") }
|
|
35
65
|
return [.range(lo...hi)]
|
|
@@ -41,8 +71,8 @@ private func intGuides(_ object: [String: JSONValue]) throws -> [GenerationGuide
|
|
|
41
71
|
|
|
42
72
|
/// `minimum` / `maximum` → floating-point range guides (see `intGuides`).
|
|
43
73
|
private func doubleGuides(_ object: [String: JSONValue]) throws -> [GenerationGuide<Double>] {
|
|
44
|
-
let lo =
|
|
45
|
-
let hi =
|
|
74
|
+
let lo = try decimalField(object, "minimum")
|
|
75
|
+
let hi = try decimalField(object, "maximum")
|
|
46
76
|
if let lo, let hi {
|
|
47
77
|
guard lo <= hi else { throw UnsupportedSchema(message: "minimum (\(lo)) is greater than maximum (\(hi))") }
|
|
48
78
|
return [.range(lo...hi)]
|
|
@@ -59,19 +89,28 @@ private func dynamicSchema(_ node: JSONValue, name: String, counter: inout Int)
|
|
|
59
89
|
guard case .object(let object) = node else {
|
|
60
90
|
throw UnsupportedSchema(message: "schema node must be a JSON object")
|
|
61
91
|
}
|
|
92
|
+
if let key = unsupportedSchemaKeywords.first(where: { object[$0] != nil }) {
|
|
93
|
+
throw UnsupportedSchema(message: "unsupported JSON Schema keyword: \(key)")
|
|
94
|
+
}
|
|
95
|
+
if let additional = object["additionalProperties"] {
|
|
96
|
+
// The emitted object already contains only the declared properties.
|
|
97
|
+
guard case .bool = additional else {
|
|
98
|
+
throw UnsupportedSchema(message: "additionalProperties schemas are not supported")
|
|
99
|
+
}
|
|
100
|
+
}
|
|
62
101
|
let description = stringField(object, "description")
|
|
63
102
|
guard let type = stringField(object, "type") else {
|
|
64
103
|
throw UnsupportedSchema(message: "schema node is missing a string \"type\" (oneOf / anyOf / allOf / $ref are not supported)")
|
|
65
104
|
}
|
|
105
|
+
if object["enum"] != nil && type != "string" {
|
|
106
|
+
throw UnsupportedSchema(message: "only string enums are supported")
|
|
107
|
+
}
|
|
66
108
|
switch type {
|
|
67
109
|
case "object":
|
|
68
110
|
guard case .object(let properties)? = object["properties"] else {
|
|
69
111
|
throw UnsupportedSchema(message: "object schema is missing \"properties\"")
|
|
70
112
|
}
|
|
71
|
-
|
|
72
|
-
if case .array(let names)? = object["required"] {
|
|
73
|
-
for entry in names { if case .string(let key) = entry { required.insert(key) } }
|
|
74
|
-
}
|
|
113
|
+
let required = try requiredKeys(object["required"], properties: properties)
|
|
75
114
|
var built: [DynamicGenerationSchema.Property] = []
|
|
76
115
|
for (key, child) in properties {
|
|
77
116
|
counter += 1
|
|
@@ -84,7 +123,10 @@ private func dynamicSchema(_ node: JSONValue, name: String, counter: inout Int)
|
|
|
84
123
|
}
|
|
85
124
|
return DynamicGenerationSchema(name: name, description: description, properties: built)
|
|
86
125
|
case "string":
|
|
87
|
-
if
|
|
126
|
+
if let enumeration = object["enum"] {
|
|
127
|
+
guard case .array(let choices) = enumeration, !choices.isEmpty else {
|
|
128
|
+
throw UnsupportedSchema(message: "enum must be a non-empty array of strings")
|
|
129
|
+
}
|
|
88
130
|
var values: [String] = []
|
|
89
131
|
for choice in choices {
|
|
90
132
|
guard case .string(let value) = choice else {
|
|
@@ -112,10 +154,13 @@ private func dynamicSchema(_ node: JSONValue, name: String, counter: inout Int)
|
|
|
112
154
|
}
|
|
113
155
|
counter += 1
|
|
114
156
|
let itemSchema = try dynamicSchema(items, name: "\(name).item.\(counter)", counter: &counter)
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
157
|
+
let minimum = try integerField(object, "minItems")
|
|
158
|
+
let maximum = try integerField(object, "maxItems")
|
|
159
|
+
guard (minimum ?? 0) >= 0, (maximum ?? 0) >= 0,
|
|
160
|
+
(minimum ?? 0) <= (maximum ?? Int.max) else {
|
|
161
|
+
throw UnsupportedSchema(message: "minItems and maxItems must be non-negative and ordered")
|
|
162
|
+
}
|
|
163
|
+
return DynamicGenerationSchema(arrayOf: itemSchema, minimumElements: minimum, maximumElements: maximum)
|
|
119
164
|
default:
|
|
120
165
|
throw UnsupportedSchema(message: "unsupported JSON Schema type: \(type)")
|
|
121
166
|
}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import FoundationModels
|
|
3
|
+
|
|
4
|
+
// MARK: - Session (persistent live session)
|
|
5
|
+
|
|
6
|
+
/// One command read on stdin in `--session` mode: either a turn (has `prompt`) or
|
|
7
|
+
/// a `reset` (`type == "reset"`). See docs/4-protocol.md / docs/7-live-session.md.
|
|
8
|
+
struct SessionCommand: Decodable {
|
|
9
|
+
let type: String?
|
|
10
|
+
let id: String?
|
|
11
|
+
let system: String?
|
|
12
|
+
let seed: [WireMessage]?
|
|
13
|
+
let prompt: String?
|
|
14
|
+
let options: WireOptions?
|
|
15
|
+
let stream: Bool?
|
|
16
|
+
// Tool calling (FR-14): `tools` rides on a `reset` (the framework binds tools at
|
|
17
|
+
// session construction); `callId`/`content`/`message` carry a tool outcome back
|
|
18
|
+
// into a suspended `tool_call`. See docs/9-tool-calling.md.
|
|
19
|
+
let tools: [WireTool]?
|
|
20
|
+
let callId: String?
|
|
21
|
+
let content: String?
|
|
22
|
+
let message: String?
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/// Compose session instructions from a system prompt plus any seed turns, folded
|
|
26
|
+
/// in as a labeled recap so a `reset` preserves recent context without re-running
|
|
27
|
+
/// it as live turns. Mirrors `userPrompt` / `flattenMessages` labeling.
|
|
28
|
+
private func sessionInstructions(system: String?, seed: [WireMessage]?) -> String? {
|
|
29
|
+
var parts: [String] = []
|
|
30
|
+
if let system, !system.isEmpty { parts.append(system) }
|
|
31
|
+
if let seed, !seed.isEmpty {
|
|
32
|
+
let transcript = seed
|
|
33
|
+
.map { "\($0.role == "assistant" ? "Assistant" : "User"): \($0.content)" }
|
|
34
|
+
.joined(separator: "\n\n")
|
|
35
|
+
parts.append("Conversation so far:\n\(transcript)")
|
|
36
|
+
}
|
|
37
|
+
return parts.isEmpty ? nil : parts.joined(separator: "\n\n")
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/// Run one turn against the held session, emitting id-tagged events. The turn runs
|
|
41
|
+
/// as a cancellable task (see `runSession`): a `cancel` command cancels it, and the
|
|
42
|
+
/// turn ends cleanly by emitting a `result` carrying the partial text generated so
|
|
43
|
+
/// far — *not* an `error` — so the Node side (which requested the cancel) settles the
|
|
44
|
+
/// turn and keeps the partial reply (FR-15; esc-to-interrupt). See docs/4-protocol.md.
|
|
45
|
+
private func sessionTurn(_ session: LanguageModelSession, _ command: SessionCommand) async {
|
|
46
|
+
let prompt = command.prompt ?? ""
|
|
47
|
+
let options = generationOptions(command.options)
|
|
48
|
+
var emitted = ""
|
|
49
|
+
do {
|
|
50
|
+
try Task.checkCancellation()
|
|
51
|
+
if command.stream == true {
|
|
52
|
+
for try await partial in session.streamResponse(to: prompt, options: options) {
|
|
53
|
+
// Cooperative cancellation: stop streaming and report the partial.
|
|
54
|
+
if Task.isCancelled { break }
|
|
55
|
+
let full = partial.content
|
|
56
|
+
if full.count > emitted.count {
|
|
57
|
+
emitDelta(String(full.dropFirst(emitted.count)), id: command.id)
|
|
58
|
+
emitted = full
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
emitResult(emitted, id: command.id)
|
|
62
|
+
} else {
|
|
63
|
+
let response = try await session.respond(to: prompt, options: options)
|
|
64
|
+
emitResult(Task.isCancelled ? emitted : response.content, id: command.id)
|
|
65
|
+
}
|
|
66
|
+
} catch is CancellationError {
|
|
67
|
+
emitResult(emitted, id: command.id)
|
|
68
|
+
} catch {
|
|
69
|
+
// A cancelled stream can surface as a generic framework error rather than a
|
|
70
|
+
// typed CancellationError; treat any error on a cancelled turn as the same
|
|
71
|
+
// clean partial-result interrupt.
|
|
72
|
+
if Task.isCancelled {
|
|
73
|
+
emitResult(emitted, id: command.id)
|
|
74
|
+
} else {
|
|
75
|
+
let f = failure(for: error)
|
|
76
|
+
emitError(f.code, f.message, id: command.id)
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/// Build the session for a `reset`: with the command's tools when any are offered,
|
|
82
|
+
/// otherwise the plain session. Tools are bound at construction (the framework's
|
|
83
|
+
/// model), so they ride on `reset`, not each turn.
|
|
84
|
+
private func makeSession(_ command: SessionCommand, bridge: ToolBridge) -> LanguageModelSession {
|
|
85
|
+
let instructions = sessionInstructions(system: command.system, seed: command.seed)
|
|
86
|
+
let tools = buildTools(command.tools ?? [], bridge: bridge)
|
|
87
|
+
if tools.isEmpty {
|
|
88
|
+
return LanguageModelSession(instructions: instructions)
|
|
89
|
+
}
|
|
90
|
+
return LanguageModelSession(tools: tools, instructions: instructions)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/// Mutates the held model session in command order while the reader routes
|
|
94
|
+
/// cancellation and tool replies independently to the active turn.
|
|
95
|
+
private func runSessionCommands(
|
|
96
|
+
_ commands: AsyncStream<SessionCommand>, bridge: ToolBridge, turns: SessionTurns
|
|
97
|
+
) async {
|
|
98
|
+
var session = LanguageModelSession()
|
|
99
|
+
for await command in commands {
|
|
100
|
+
switch command.type {
|
|
101
|
+
case "export_transcript":
|
|
102
|
+
do {
|
|
103
|
+
let data = try JSONEncoder().encode(session.transcript)
|
|
104
|
+
emitResult(String(decoding: data, as: UTF8.self), id: command.id)
|
|
105
|
+
} catch {
|
|
106
|
+
emitError("transcriptError", "could not encode native transcript", id: command.id)
|
|
107
|
+
}
|
|
108
|
+
case "import_transcript":
|
|
109
|
+
guard let content = command.content,
|
|
110
|
+
let transcript = try? JSONDecoder().decode(Transcript.self, from: Data(content.utf8))
|
|
111
|
+
else {
|
|
112
|
+
emitError("transcriptError", "invalid or incompatible native transcript", id: command.id)
|
|
113
|
+
continue
|
|
114
|
+
}
|
|
115
|
+
let tools = buildTools(command.tools ?? [], bridge: bridge)
|
|
116
|
+
let expected = Set(transcript.flatMap { entry -> [String] in
|
|
117
|
+
if case .instructions(let instructions) = entry {
|
|
118
|
+
return instructions.toolDefinitions.map(\.name)
|
|
119
|
+
}
|
|
120
|
+
return []
|
|
121
|
+
})
|
|
122
|
+
guard expected == Set(tools.map(\.name)) else {
|
|
123
|
+
emitError("transcriptError", "enabled tools do not match the native transcript", id: command.id)
|
|
124
|
+
continue
|
|
125
|
+
}
|
|
126
|
+
session = LanguageModelSession(tools: tools, transcript: transcript)
|
|
127
|
+
emitReady(command.id)
|
|
128
|
+
case "count_tokens":
|
|
129
|
+
if #available(macOS 26.4, *) {
|
|
130
|
+
do {
|
|
131
|
+
let model = SystemLanguageModel.default
|
|
132
|
+
let history = try await model.tokenCount(for: session.transcript)
|
|
133
|
+
let prompt: Int
|
|
134
|
+
if let nextPrompt = command.prompt, !nextPrompt.isEmpty {
|
|
135
|
+
prompt = try await model.tokenCount(for: nextPrompt)
|
|
136
|
+
} else {
|
|
137
|
+
prompt = 0
|
|
138
|
+
}
|
|
139
|
+
emitResult(String(history + prompt), id: command.id)
|
|
140
|
+
} catch {
|
|
141
|
+
let f = failure(for: error)
|
|
142
|
+
emitError(f.code, f.message, id: command.id)
|
|
143
|
+
}
|
|
144
|
+
} else {
|
|
145
|
+
emitError("unsupported", "native token counting requires macOS 26.4 or later", id: command.id)
|
|
146
|
+
}
|
|
147
|
+
case "reset":
|
|
148
|
+
session = makeSession(command, bridge: bridge)
|
|
149
|
+
emitReady(command.id)
|
|
150
|
+
default:
|
|
151
|
+
let active = session
|
|
152
|
+
let ran = await turns.run(command.id) {
|
|
153
|
+
await bridge.beginTurn(command.id)
|
|
154
|
+
await sessionTurn(active, command)
|
|
155
|
+
}
|
|
156
|
+
if !ran { emitResult("", id: command.id) }
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/// Read commands until EOF. Turns and session operations stay serial. The
|
|
162
|
+
/// reader can still deliver a tool result or cancel while an operation is queued.
|
|
163
|
+
func runSession() async -> Never {
|
|
164
|
+
guard case .available = SystemLanguageModel.default.availability else {
|
|
165
|
+
failEvent("unavailable", "Apple Foundation Models unavailable")
|
|
166
|
+
}
|
|
167
|
+
let bridge = ToolBridge { name, callId, argumentsJSON, id in
|
|
168
|
+
emitToolCall(name: name, callId: callId, argumentsJSON: argumentsJSON, id: id)
|
|
169
|
+
}
|
|
170
|
+
let turns = SessionTurns()
|
|
171
|
+
let (commands, input) = AsyncStream<SessionCommand>.makeStream(bufferingPolicy: .bufferingOldest(16))
|
|
172
|
+
let worker = Task { await runSessionCommands(commands, bridge: bridge, turns: turns) }
|
|
173
|
+
|
|
174
|
+
func queue(_ command: SessionCommand, turn: Bool = false) async {
|
|
175
|
+
if case .dropped = input.yield(command) {
|
|
176
|
+
if turn { await turns.discardQueued(command.id) }
|
|
177
|
+
emitError("badRequest", "session command queue is full", id: command.id)
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
func consume(_ line: Data) async {
|
|
182
|
+
if line.allSatisfy({ $0 == 32 || $0 == 9 || $0 == 13 }) { return }
|
|
183
|
+
guard let command = try? JSONDecoder().decode(SessionCommand.self, from: line) else {
|
|
184
|
+
emitError("badRequest", "malformed session command", id: nil)
|
|
185
|
+
return
|
|
186
|
+
}
|
|
187
|
+
switch command.type {
|
|
188
|
+
case "tool_result":
|
|
189
|
+
await bridge.resolve(callId: command.callId ?? "", reply: .result(command.content ?? ""))
|
|
190
|
+
case "tool_error":
|
|
191
|
+
await bridge.resolve(callId: command.callId ?? "", reply: .error(command.message ?? "tool failed"))
|
|
192
|
+
case "cancel":
|
|
193
|
+
if await turns.cancel(command.id) { await bridge.cancelTurn(command.id) }
|
|
194
|
+
case "export_transcript", "import_transcript", "count_tokens", "reset":
|
|
195
|
+
await queue(command)
|
|
196
|
+
default:
|
|
197
|
+
if await turns.enqueue(command.id) {
|
|
198
|
+
await queue(command, turn: true)
|
|
199
|
+
} else {
|
|
200
|
+
emitError("badRequest", "duplicate pending turn id", id: nil)
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
do {
|
|
205
|
+
var line = Data()
|
|
206
|
+
for try await byte in FileHandle.standardInput.bytes {
|
|
207
|
+
if byte == 10 {
|
|
208
|
+
await consume(line)
|
|
209
|
+
line.removeAll(keepingCapacity: true)
|
|
210
|
+
} else {
|
|
211
|
+
guard line.count < maxInputFrameBytes else {
|
|
212
|
+
failEvent("badRequest", "session command exceeds 4 MiB")
|
|
213
|
+
}
|
|
214
|
+
line.append(byte)
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
if !line.isEmpty { await consume(line) }
|
|
218
|
+
await bridge.finishInput()
|
|
219
|
+
input.finish()
|
|
220
|
+
await worker.value
|
|
221
|
+
} catch {
|
|
222
|
+
failEvent("inferenceFailed", "session input error: \(String(describing: error))")
|
|
223
|
+
}
|
|
224
|
+
exit(0)
|
|
225
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/// Tracks cancelable turns while a separate worker executes commands in wire order.
|
|
2
|
+
actor SessionTurns {
|
|
3
|
+
private var queued: [String: Bool] = [:]
|
|
4
|
+
private var active: (id: String?, task: Task<Void, Never>)?
|
|
5
|
+
|
|
6
|
+
func enqueue(_ id: String?) -> Bool {
|
|
7
|
+
guard let id else { return true }
|
|
8
|
+
guard queued[id] == nil, active?.id != id else { return false }
|
|
9
|
+
queued[id] = false
|
|
10
|
+
return true
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
func discardQueued(_ id: String?) {
|
|
14
|
+
if let id { queued.removeValue(forKey: id) }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/// Returns `false` for a turn cancelled before it started.
|
|
18
|
+
func run(_ id: String?, operation: @escaping @Sendable () async -> Void) async -> Bool {
|
|
19
|
+
if let id, queued.removeValue(forKey: id) == true { return false }
|
|
20
|
+
let task = Task { await operation() }
|
|
21
|
+
active = (id, task)
|
|
22
|
+
await task.value
|
|
23
|
+
active = nil
|
|
24
|
+
return true
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/// Returns `true` if a running turn was cancelled and its tool waiters need waking.
|
|
28
|
+
func cancel(_ id: String?) -> Bool {
|
|
29
|
+
guard let id else { return false }
|
|
30
|
+
if let active, active.id == id {
|
|
31
|
+
active.task.cancel()
|
|
32
|
+
return true
|
|
33
|
+
}
|
|
34
|
+
if queued[id] != nil { queued[id] = true }
|
|
35
|
+
return false
|
|
36
|
+
}
|
|
37
|
+
}
|