apple-fm 0.0.1 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +114 -21
- package/apple-fm-helper/GuidedGeneration.swift +130 -0
- package/apple-fm-helper/main.swift +164 -22
- package/bin/apple-fm-helper +0 -0
- package/dist/cli.js +199 -6
- package/dist/index.d.ts +100 -17
- package/dist/index.js +194 -4
- package/package.json +3 -4
- package/scripts/build-apple-fm-helper.sh +10 -6
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 };
|
|
@@ -48,6 +51,19 @@ function estimateConversationTokens(system, messages) {
|
|
|
48
51
|
// src/helper.ts
|
|
49
52
|
var HELPER_BIN_ENV = "APPLE_FM_BIN";
|
|
50
53
|
var DEFAULT_TIMEOUT_MS = 12e4;
|
|
54
|
+
function isPlatformSupported() {
|
|
55
|
+
return process.platform === "darwin" && process.arch === "arm64";
|
|
56
|
+
}
|
|
57
|
+
function usingBundledHelper(options = {}) {
|
|
58
|
+
if (options.binPath !== void 0 && options.binPath.length > 0) return false;
|
|
59
|
+
const fromEnv = process.env[HELPER_BIN_ENV];
|
|
60
|
+
return fromEnv === void 0 || fromEnv.length === 0;
|
|
61
|
+
}
|
|
62
|
+
function unsupportedPlatformError() {
|
|
63
|
+
return new Error(
|
|
64
|
+
`[unsupportedPlatform] apple-fm requires macOS 26+ on Apple Silicon; the on-device model cannot run on ${process.platform}/${process.arch}`
|
|
65
|
+
);
|
|
66
|
+
}
|
|
51
67
|
function resolveHelperPath(options = {}) {
|
|
52
68
|
if (options.binPath !== void 0 && options.binPath.length > 0) return options.binPath;
|
|
53
69
|
const fromEnv = process.env[HELPER_BIN_ENV];
|
|
@@ -113,6 +129,9 @@ function runHelper(args, options, input, onLine) {
|
|
|
113
129
|
});
|
|
114
130
|
}
|
|
115
131
|
async function probe(options = {}) {
|
|
132
|
+
if (usingBundledHelper(options) && !isPlatformSupported()) {
|
|
133
|
+
return { available: false, reason: "unsupportedPlatform" };
|
|
134
|
+
}
|
|
116
135
|
let result;
|
|
117
136
|
await runHelper(["--probe"], options, void 0, (line) => {
|
|
118
137
|
result = JSON.parse(line);
|
|
@@ -120,7 +139,8 @@ async function probe(options = {}) {
|
|
|
120
139
|
if (result === void 0) throw new Error("apple-fm helper --probe produced no result");
|
|
121
140
|
return result;
|
|
122
141
|
}
|
|
123
|
-
async function generate(request, options = {}, onDelta) {
|
|
142
|
+
async function generate(request, options = {}, onDelta, onSnapshot) {
|
|
143
|
+
if (usingBundledHelper(options) && !isPlatformSupported()) throw unsupportedPlatformError();
|
|
124
144
|
let content;
|
|
125
145
|
await runHelper(["--generate"], options, encodeRequest(request), (line) => {
|
|
126
146
|
const event = parseEvent(line);
|
|
@@ -128,6 +148,9 @@ async function generate(request, options = {}, onDelta) {
|
|
|
128
148
|
case "delta":
|
|
129
149
|
onDelta?.(event.text);
|
|
130
150
|
break;
|
|
151
|
+
case "snapshot":
|
|
152
|
+
onSnapshot?.(event.content);
|
|
153
|
+
break;
|
|
131
154
|
case "result":
|
|
132
155
|
content = event.content;
|
|
133
156
|
break;
|
|
@@ -139,6 +162,137 @@ async function generate(request, options = {}, onDelta) {
|
|
|
139
162
|
return content;
|
|
140
163
|
}
|
|
141
164
|
|
|
165
|
+
// src/liveSession.ts
|
|
166
|
+
import { spawn as spawn2 } from "child_process";
|
|
167
|
+
var DEFAULT_TURN_TIMEOUT_MS = 12e4;
|
|
168
|
+
var LiveSession = class {
|
|
169
|
+
command;
|
|
170
|
+
timeoutMs;
|
|
171
|
+
options;
|
|
172
|
+
/** Whether we'd spawn the bundled macOS helper (subject to the platform gate). */
|
|
173
|
+
bundled;
|
|
174
|
+
child;
|
|
175
|
+
buffer = "";
|
|
176
|
+
nextId = 0;
|
|
177
|
+
pending = /* @__PURE__ */ new Map();
|
|
178
|
+
constructor(config = {}) {
|
|
179
|
+
this.command = resolveHelperPath(config);
|
|
180
|
+
this.timeoutMs = config.timeoutMs ?? DEFAULT_TURN_TIMEOUT_MS;
|
|
181
|
+
this.options = config.options;
|
|
182
|
+
this.bundled = usingBundledHelper(config);
|
|
183
|
+
}
|
|
184
|
+
/** Recreate the underlying session with new instructions + seed turns. */
|
|
185
|
+
async reset(system, seed = []) {
|
|
186
|
+
await this.dispatch({ type: "reset", system, seed }, void 0);
|
|
187
|
+
}
|
|
188
|
+
/** Send one user turn; prior turns stay in context. Streams via `onDelta`. */
|
|
189
|
+
send(text, onDelta) {
|
|
190
|
+
return this.dispatch(
|
|
191
|
+
{ prompt: text, options: this.options, stream: onDelta !== void 0 },
|
|
192
|
+
onDelta
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
/** Tear down the helper process and reject any in-flight commands. */
|
|
196
|
+
close() {
|
|
197
|
+
const child = this.child;
|
|
198
|
+
this.child = void 0;
|
|
199
|
+
if (child !== void 0) child.kill("SIGKILL");
|
|
200
|
+
this.rejectAll(new Error("[sessionClosed] live session closed"));
|
|
201
|
+
}
|
|
202
|
+
rejectAll(error) {
|
|
203
|
+
for (const pending of this.pending.values()) {
|
|
204
|
+
clearTimeout(pending.timer);
|
|
205
|
+
pending.reject(error);
|
|
206
|
+
}
|
|
207
|
+
this.pending.clear();
|
|
208
|
+
}
|
|
209
|
+
ensureChild() {
|
|
210
|
+
const existing = this.child;
|
|
211
|
+
if (existing !== void 0 && existing.exitCode === null && !existing.killed) return existing;
|
|
212
|
+
const child = spawn2(this.command, ["--session"], { stdio: ["pipe", "pipe", "pipe"] });
|
|
213
|
+
this.buffer = "";
|
|
214
|
+
child.stdout.setEncoding("utf8");
|
|
215
|
+
child.stdout.on("data", (chunk) => {
|
|
216
|
+
this.onStdout(chunk);
|
|
217
|
+
});
|
|
218
|
+
child.stdin.on("error", () => void 0);
|
|
219
|
+
const onGone = () => {
|
|
220
|
+
if (this.child === child) this.child = void 0;
|
|
221
|
+
this.rejectAll(new Error("[sessionClosed] live session helper exited"));
|
|
222
|
+
};
|
|
223
|
+
child.on("close", onGone);
|
|
224
|
+
child.on("error", onGone);
|
|
225
|
+
this.child = child;
|
|
226
|
+
return child;
|
|
227
|
+
}
|
|
228
|
+
onStdout(chunk) {
|
|
229
|
+
this.buffer += chunk;
|
|
230
|
+
const { lines, rest } = splitLines(this.buffer);
|
|
231
|
+
this.buffer = rest;
|
|
232
|
+
for (const line of lines) this.onLine(line);
|
|
233
|
+
}
|
|
234
|
+
onLine(line) {
|
|
235
|
+
let value;
|
|
236
|
+
try {
|
|
237
|
+
value = JSON.parse(line);
|
|
238
|
+
} catch {
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
if (typeof value !== "object" || value === null) return;
|
|
242
|
+
const event = value;
|
|
243
|
+
if (typeof event.id !== "string") return;
|
|
244
|
+
const id = event.id;
|
|
245
|
+
const pending = this.pending.get(id);
|
|
246
|
+
if (pending === void 0) return;
|
|
247
|
+
switch (event.type) {
|
|
248
|
+
case "delta":
|
|
249
|
+
if (typeof event.text === "string") {
|
|
250
|
+
pending.acc += event.text;
|
|
251
|
+
pending.onDelta?.(event.text);
|
|
252
|
+
}
|
|
253
|
+
break;
|
|
254
|
+
case "ready":
|
|
255
|
+
this.settle(id, "");
|
|
256
|
+
break;
|
|
257
|
+
case "result":
|
|
258
|
+
this.settle(id, typeof event.content === "string" ? event.content : pending.acc);
|
|
259
|
+
break;
|
|
260
|
+
case "error":
|
|
261
|
+
this.fail(id, `[${String(event.code)}] ${String(event.message)}`);
|
|
262
|
+
break;
|
|
263
|
+
default:
|
|
264
|
+
break;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
settle(id, content) {
|
|
268
|
+
const pending = this.pending.get(id);
|
|
269
|
+
if (pending === void 0) return;
|
|
270
|
+
clearTimeout(pending.timer);
|
|
271
|
+
this.pending.delete(id);
|
|
272
|
+
pending.resolve(content);
|
|
273
|
+
}
|
|
274
|
+
fail(id, message) {
|
|
275
|
+
const pending = this.pending.get(id);
|
|
276
|
+
if (pending === void 0) return;
|
|
277
|
+
clearTimeout(pending.timer);
|
|
278
|
+
this.pending.delete(id);
|
|
279
|
+
pending.reject(new Error(message));
|
|
280
|
+
}
|
|
281
|
+
dispatch(command, onDelta) {
|
|
282
|
+
if (this.bundled && !isPlatformSupported()) return Promise.reject(unsupportedPlatformError());
|
|
283
|
+
const child = this.ensureChild();
|
|
284
|
+
const id = String(this.nextId++);
|
|
285
|
+
return new Promise((resolve, reject) => {
|
|
286
|
+
const timer = setTimeout(() => {
|
|
287
|
+
this.pending.delete(id);
|
|
288
|
+
reject(new Error(`live session timed out after ${String(this.timeoutMs)}ms`));
|
|
289
|
+
}, this.timeoutMs);
|
|
290
|
+
this.pending.set(id, { resolve, reject, onDelta, acc: "", timer });
|
|
291
|
+
child.stdin.write(JSON.stringify({ ...command, id }) + "\n");
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
|
|
142
296
|
// src/session.ts
|
|
143
297
|
var DEFAULT_COMPACT_AT = 3e3;
|
|
144
298
|
var DEFAULT_KEEP_RECENT = 4;
|
|
@@ -148,18 +302,20 @@ function defaultGenerateFn(helper, options) {
|
|
|
148
302
|
}
|
|
149
303
|
var ChatSession = class {
|
|
150
304
|
system;
|
|
151
|
-
options;
|
|
152
305
|
compactAtTokens;
|
|
153
306
|
keepRecentTurns;
|
|
307
|
+
backend;
|
|
154
308
|
generateFn;
|
|
155
309
|
messages = [];
|
|
156
310
|
/** Recap of turns dropped by compaction; folded into the system prompt. */
|
|
157
311
|
summary;
|
|
312
|
+
/** Instructions the backend was last `reset` with (`undefined` ⇒ needs reset). */
|
|
313
|
+
backendInstructions;
|
|
158
314
|
constructor(config = {}) {
|
|
159
315
|
this.system = config.system ?? "";
|
|
160
|
-
this.options = config.options;
|
|
161
316
|
this.compactAtTokens = config.compactAtTokens ?? DEFAULT_COMPACT_AT;
|
|
162
317
|
this.keepRecentTurns = config.keepRecentTurns ?? DEFAULT_KEEP_RECENT;
|
|
318
|
+
this.backend = config.backend ?? new LiveSession({ ...config.helper, options: config.options });
|
|
163
319
|
this.generateFn = config.generateFn ?? defaultGenerateFn(config.helper, config.options);
|
|
164
320
|
}
|
|
165
321
|
/** The system prompt actually sent to the model (instructions + any recap). */
|
|
@@ -182,11 +338,35 @@ ${recap}` : recap;
|
|
|
182
338
|
/** Send a user turn and return the assistant's reply (streamed via `onDelta`). */
|
|
183
339
|
async send(text, onDelta) {
|
|
184
340
|
if (this.shouldCompact()) await this.compact();
|
|
341
|
+
await this.ensureStarted();
|
|
185
342
|
this.messages.push({ role: "user", content: text });
|
|
186
|
-
|
|
343
|
+
let reply;
|
|
344
|
+
try {
|
|
345
|
+
reply = await this.backend.send(text, onDelta);
|
|
346
|
+
} catch (error) {
|
|
347
|
+
if (!recoverable(error)) {
|
|
348
|
+
this.messages.pop();
|
|
349
|
+
throw error;
|
|
350
|
+
}
|
|
351
|
+
this.messages.pop();
|
|
352
|
+
this.backendInstructions = void 0;
|
|
353
|
+
await this.ensureStarted();
|
|
354
|
+
this.messages.push({ role: "user", content: text });
|
|
355
|
+
reply = await this.backend.send(text, onDelta);
|
|
356
|
+
}
|
|
187
357
|
this.messages.push({ role: "assistant", content: reply });
|
|
188
358
|
return reply;
|
|
189
359
|
}
|
|
360
|
+
/**
|
|
361
|
+
* Reset the backend's session whenever the effective system prompt changes (the
|
|
362
|
+
* first turn, or after a compaction), seeding it with the transcript so far.
|
|
363
|
+
*/
|
|
364
|
+
async ensureStarted() {
|
|
365
|
+
const system = this.effectiveSystem();
|
|
366
|
+
if (this.backendInstructions === system) return;
|
|
367
|
+
await this.backend.reset(system, this.messages);
|
|
368
|
+
this.backendInstructions = system;
|
|
369
|
+
}
|
|
190
370
|
/**
|
|
191
371
|
* Fold all but the most recent turns into the rolling summary. Safe to call
|
|
192
372
|
* directly; {@link send} calls it automatically when {@link shouldCompact}.
|
|
@@ -209,16 +389,26 @@ ${this.summary}` : "",
|
|
|
209
389
|
if (system !== void 0) this.system = system;
|
|
210
390
|
this.messages = [];
|
|
211
391
|
this.summary = void 0;
|
|
392
|
+
this.backendInstructions = void 0;
|
|
393
|
+
}
|
|
394
|
+
/** Tear down the underlying live session (kills the helper process). */
|
|
395
|
+
close() {
|
|
396
|
+
this.backend.close();
|
|
212
397
|
}
|
|
213
398
|
};
|
|
399
|
+
function recoverable(error) {
|
|
400
|
+
return error instanceof Error && error.message.includes("[sessionClosed]");
|
|
401
|
+
}
|
|
214
402
|
export {
|
|
215
403
|
ChatSession,
|
|
216
404
|
HELPER_BIN_ENV,
|
|
405
|
+
LiveSession,
|
|
217
406
|
encodeRequest,
|
|
218
407
|
estimateConversationTokens,
|
|
219
408
|
estimateTokens,
|
|
220
409
|
flattenMessages,
|
|
221
410
|
generate,
|
|
411
|
+
isPlatformSupported,
|
|
222
412
|
parseEvent,
|
|
223
413
|
probe,
|
|
224
414
|
resolveHelperPath,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "apple-fm",
|
|
3
|
-
"version": "0.0
|
|
3
|
+
"version": "1.0.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",
|
|
@@ -20,9 +20,6 @@
|
|
|
20
20
|
"cli",
|
|
21
21
|
"chat"
|
|
22
22
|
],
|
|
23
|
-
"os": [
|
|
24
|
-
"darwin"
|
|
25
|
-
],
|
|
26
23
|
"engines": {
|
|
27
24
|
"node": ">=20"
|
|
28
25
|
},
|
|
@@ -54,6 +51,7 @@
|
|
|
54
51
|
"lint": "eslint src/ tests/",
|
|
55
52
|
"typecheck": "tsc --noEmit",
|
|
56
53
|
"clean": "rm -rf dist coverage node_modules/.cache",
|
|
54
|
+
"demo": "npm run build && node scripts/demo.mjs",
|
|
57
55
|
"release": "bash scripts/release.sh",
|
|
58
56
|
"release:beta": "bash scripts/release.sh --beta",
|
|
59
57
|
"prepublishOnly": "npm run build"
|
|
@@ -62,6 +60,7 @@
|
|
|
62
60
|
"@eslint/js": "^10.0.1",
|
|
63
61
|
"@types/node": "^25.9.3",
|
|
64
62
|
"@vitest/coverage-v8": "^4.1.9",
|
|
63
|
+
"domotion-svg": "^0.13.3",
|
|
65
64
|
"eslint": "^10.5.0",
|
|
66
65
|
"eslint-plugin-import-x": "^4.16.2",
|
|
67
66
|
"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
|
|
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
|
-
|
|
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 "$
|
|
26
|
-
echo "[apple-fm] source missing ($
|
|
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
|
-
|
|
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
|