apple-fm 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Brian Westphal
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,82 @@
1
+ # apple-fm
2
+
3
+ Command-line and programmatic access to Apple's **on-device Foundation Models**
4
+ (Apple Intelligence) on **macOS 26+ / Apple Silicon**. Free, private, offline —
5
+ nothing leaves your machine.
6
+
7
+ Apple ships `FoundationModels` as Swift-only API with no command-line front-end.
8
+ apple-fm provides one: a tiny Swift helper does the model work, and a tested,
9
+ zero-dependency Node layer gives you a CLI and a library.
10
+
11
+ > ⚠️ **Early scaffold.** The Node layer is fully unit-tested; the Swift helper is
12
+ > smoke-verified on a macOS 26 / Apple Intelligence machine (probe, generate,
13
+ > stream, schema, chat all work). Native guaranteed-structure output, an
14
+ > automated on-device CI test, and signed release binaries are still to come —
15
+ > see [docs/3-requirements.md](docs/3-requirements.md).
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ npm install -g apple-fm # CLI
21
+ npm install apple-fm # library
22
+ ```
23
+
24
+ Requires macOS 26+ on Apple Silicon with Apple Intelligence enabled. The package
25
+ bundles a prebuilt helper; you can also build it from source:
26
+
27
+ ```bash
28
+ npm run build:helper # → bin/apple-fm-helper (needs Xcode 26 / macOS 26 SDK)
29
+ ```
30
+
31
+ The helper is located via `APPLE_FM_BIN`, then the bundled `bin/apple-fm-helper`,
32
+ then `apple-fm-helper` on `PATH`.
33
+
34
+ ## CLI
35
+
36
+ ```bash
37
+ apple-fm probe # is the on-device model available?
38
+ apple-fm generate "Summarize: …" # one-shot text
39
+ cat notes.md | apple-fm generate # read the prompt from stdin
40
+ apple-fm generate "…" --stream # stream tokens as they arrive
41
+ apple-fm generate "…" --schema shape.json # structured/guided JSON output
42
+ apple-fm chat # interactive chat (streamed, auto-compacted)
43
+ ```
44
+
45
+ Run `apple-fm --help` for the full flag list.
46
+
47
+ ## Library
48
+
49
+ ```ts
50
+ import { probe, generate, ChatSession } from 'apple-fm';
51
+
52
+ if ((await probe()).available) {
53
+ // One-shot
54
+ const summary = await generate({ prompt: 'Summarize: …', system: 'Be terse.' });
55
+
56
+ // Streaming
57
+ await generate({ prompt: '…', stream: true }, {}, (chunk) => process.stdout.write(chunk));
58
+
59
+ // Multi-turn chat with automatic context compaction
60
+ const chat = new ChatSession({ system: 'You are a helpful assistant.' });
61
+ const reply = await chat.send('Hello');
62
+ }
63
+ ```
64
+
65
+ ## How it works
66
+
67
+ A single binary, three shapes (probe / generate / chat), all over one
68
+ line-delimited JSON protocol ([docs/4-protocol.md](docs/4-protocol.md)). The chat
69
+ session keeps the transcript on the Node side and, when it approaches the
70
+ on-device model's small context window, summarizes older turns and continues —
71
+ so long conversations stay coherent. Because the helper resolves the current
72
+ on-device model at runtime, OS and model updates are picked up without a rebuild.
73
+
74
+ ## Documentation
75
+
76
+ - [Overview](docs/1-overview.md) · [Architecture](docs/2-architecture.md) ·
77
+ [Requirements](docs/3-requirements.md) · [Protocol](docs/4-protocol.md) ·
78
+ [Releasing](docs/5-releasing.md)
79
+
80
+ ## License
81
+
82
+ MIT © Brian Westphal
@@ -0,0 +1,238 @@
1
+ // apple-fm-helper — the only part of apple-fm that touches Apple's native
2
+ // `FoundationModels` framework. Node can't call it directly, so the CLI/library
3
+ // shells out to this tiny Swift program (see ../src/helper.ts) and exchanges
4
+ // line-delimited JSON (NDJSON).
5
+ //
6
+ // Protocol:
7
+ // apple-fm-helper --probe
8
+ // → one JSON line: {"available":true}
9
+ // or {"available":false,"reason":"appleIntelligenceNotEnabled"}
10
+ // apple-fm-helper --generate
11
+ // reads one request object on stdin:
12
+ // {"system"?,"prompt"?,"messages"?:[{"role","content"}],
13
+ // "schema"?,"options"?:{"temperature"?,"maxTokens"?},"stream"?}
14
+ // writes NDJSON on stdout:
15
+ // {"type":"delta","text":"…"} (zero or more, only when "stream":true)
16
+ // {"type":"result","content":"…"} (exactly one on success)
17
+ // {"type":"error","code":"…","message":"…"} (on failure; exit != 0)
18
+ //
19
+ // Requires macOS 26+ on Apple Silicon with Apple Intelligence (FoundationModels).
20
+ // Build with scripts/build-apple-fm-helper.sh; point apple-fm at the binary with
21
+ // APPLE_FM_BIN (or build it to ./bin/apple-fm-helper).
22
+ import Foundation
23
+ import FoundationModels
24
+
25
+ // MARK: - Wire types
26
+
27
+ struct WireMessage: Decodable {
28
+ let role: String
29
+ let content: String
30
+ }
31
+
32
+ struct WireOptions: Decodable {
33
+ let temperature: Double?
34
+ let maxTokens: Int?
35
+ }
36
+
37
+ struct GenerateRequest: Decodable {
38
+ let system: String?
39
+ let prompt: String?
40
+ let messages: [WireMessage]?
41
+ // Guided-generation schema. Captured but, for now, applied as prompt
42
+ // guidance (see `instructions(for:)`). Native `DynamicGenerationSchema`
43
+ // guided generation is the planned enhancement — see docs/3-requirements.md.
44
+ let schema: JSONValue?
45
+ let options: WireOptions?
46
+ let stream: Bool?
47
+ }
48
+
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.
51
+ indirect enum JSONValue: Decodable {
52
+ case null
53
+ case bool(Bool)
54
+ case number(Double)
55
+ case string(String)
56
+ case array([JSONValue])
57
+ case object([String: JSONValue])
58
+
59
+ init(from decoder: Decoder) throws {
60
+ let container = try decoder.singleValueContainer()
61
+ if container.decodeNil() {
62
+ self = .null
63
+ } else if let b = try? container.decode(Bool.self) {
64
+ self = .bool(b)
65
+ } else if let n = try? container.decode(Double.self) {
66
+ self = .number(n)
67
+ } else if let s = try? container.decode(String.self) {
68
+ self = .string(s)
69
+ } else if let a = try? container.decode([JSONValue].self) {
70
+ self = .array(a)
71
+ } else if let o = try? container.decode([String: JSONValue].self) {
72
+ self = .object(o)
73
+ } else {
74
+ throw DecodingError.dataCorruptedError(in: container, debugDescription: "unsupported JSON")
75
+ }
76
+ }
77
+
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
+ }
92
+
93
+ // MARK: - Output
94
+
95
+ private func emit(_ json: String) {
96
+ FileHandle.standardOutput.write(Data((json + "\n").utf8))
97
+ }
98
+
99
+ private func emitResult(_ content: String) {
100
+ emit("{\"type\":\"result\",\"content\":\(encodeString(content))}")
101
+ }
102
+
103
+ private func emitDelta(_ text: String) {
104
+ emit("{\"type\":\"delta\",\"text\":\(encodeString(text))}")
105
+ }
106
+
107
+ private func failEvent(_ code: String, _ message: String) -> Never {
108
+ emit("{\"type\":\"error\",\"code\":\(encodeString(code)),\"message\":\(encodeString(message))}")
109
+ exit(1)
110
+ }
111
+
112
+ /// JSON-encode a string (with surrounding quotes) using Foundation's encoder so
113
+ /// escaping is always correct.
114
+ private func encodeString(_ value: String) -> String {
115
+ let data = try? JSONEncoder().encode(value)
116
+ return data.flatMap { String(data: $0, encoding: .utf8) } ?? "\"\""
117
+ }
118
+
119
+ // MARK: - Probe
120
+
121
+ private func probe() -> Never {
122
+ switch SystemLanguageModel.default.availability {
123
+ case .available:
124
+ emit("{\"available\":true}")
125
+ case .unavailable(let reason):
126
+ emit("{\"available\":false,\"reason\":\(encodeString(reasonString(reason)))}")
127
+ @unknown default:
128
+ emit("{\"available\":false,\"reason\":\"unknown\"}")
129
+ }
130
+ exit(0)
131
+ }
132
+
133
+ private func reasonString(_ reason: SystemLanguageModel.Availability.UnavailableReason) -> String {
134
+ switch reason {
135
+ case .deviceNotEligible: return "deviceNotEligible"
136
+ case .appleIntelligenceNotEnabled: return "appleIntelligenceNotEnabled"
137
+ case .modelNotReady: return "modelNotReady"
138
+ @unknown default: return "unknown"
139
+ }
140
+ }
141
+
142
+ // MARK: - Generate
143
+
144
+ /// Combine the caller's system prompt with any schema guidance.
145
+ private func instructions(for request: GenerateRequest) -> String {
146
+ var parts: [String] = []
147
+ if let system = request.system, !system.isEmpty { parts.append(system) }
148
+ if let schema = request.schema {
149
+ // Prompt-guided structured output. The richer path (native guided
150
+ // generation with a runtime `DynamicGenerationSchema`) is tracked in the
151
+ // requirements doc; until then we instruct the model to match the schema.
152
+ parts.append(
153
+ "Respond with JSON only — no prose, no code fences — matching this JSON Schema:\n"
154
+ + (schema.jsonString ?? "{}"))
155
+ }
156
+ return parts.joined(separator: "\n\n")
157
+ }
158
+
159
+ /// Build the single user prompt from either `prompt` or a `messages` transcript.
160
+ /// The `messages` labeling below must mirror the Node side's canonical format
161
+ /// (`src/protocol.ts` `flattenMessages`: `User:`/`Assistant:`, blank-line
162
+ /// separated) so replayed conversations behave identically on both sides.
163
+ private func userPrompt(for request: GenerateRequest) -> String {
164
+ if let prompt = request.prompt { return prompt }
165
+ if let messages = request.messages {
166
+ return messages.map { "\($0.role == "assistant" ? "Assistant" : "User"): \($0.content)" }
167
+ .joined(separator: "\n\n")
168
+ }
169
+ return ""
170
+ }
171
+
172
+ private func generationOptions(_ options: WireOptions?) -> GenerationOptions {
173
+ guard let options else { return GenerationOptions() }
174
+ return GenerationOptions(
175
+ temperature: options.temperature,
176
+ maximumResponseTokens: options.maxTokens)
177
+ }
178
+
179
+ private func generate(_ request: GenerateRequest) async -> Never {
180
+ guard case .available = SystemLanguageModel.default.availability else {
181
+ failEvent("unavailable", "Apple Foundation Models unavailable")
182
+ }
183
+ let session = LanguageModelSession(instructions: instructions(for: request))
184
+ let prompt = userPrompt(for: request)
185
+ let options = generationOptions(request.options)
186
+ do {
187
+ if request.stream == true {
188
+ var emitted = ""
189
+ for try await partial in session.streamResponse(to: prompt, options: options) {
190
+ // Partials are cumulative; emit only the newly-appended suffix.
191
+ let full = partial.content
192
+ if full.count > emitted.count {
193
+ emitDelta(String(full.dropFirst(emitted.count)))
194
+ emitted = full
195
+ }
196
+ }
197
+ emitResult(emitted)
198
+ } else {
199
+ let response = try await session.respond(to: prompt, options: options)
200
+ emitResult(response.content)
201
+ }
202
+ exit(0)
203
+ } catch let error as LanguageModelSession.GenerationError {
204
+ failEvent(errorCode(error), String(describing: error))
205
+ } catch {
206
+ failEvent("inferenceFailed", String(describing: error))
207
+ }
208
+ }
209
+
210
+ private func errorCode(_ error: LanguageModelSession.GenerationError) -> String {
211
+ switch error {
212
+ case .exceededContextWindowSize: return "contextWindowExceeded"
213
+ case .guardrailViolation: return "guardrailViolation"
214
+ default: return "generationError"
215
+ }
216
+ }
217
+
218
+ // MARK: - Entry
219
+
220
+ private func readRequest() -> GenerateRequest {
221
+ let data = FileHandle.standardInput.readDataToEndOfFile()
222
+ guard let request = try? JSONDecoder().decode(GenerateRequest.self, from: data) else {
223
+ failEvent("badRequest", "expected a JSON generation request on stdin")
224
+ }
225
+ return request
226
+ }
227
+
228
+ let args = CommandLine.arguments
229
+ if args.contains("--probe") {
230
+ probe()
231
+ } else if args.contains("--generate") {
232
+ let request = readRequest()
233
+ Task { await generate(request) }
234
+ dispatchMain()
235
+ } else {
236
+ FileHandle.standardError.write(Data("usage: apple-fm-helper --probe | --generate\n".utf8))
237
+ exit(64)
238
+ }
Binary file
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/cli.js ADDED
@@ -0,0 +1,460 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { readFileSync } from "fs";
5
+ import { readFile } from "fs/promises";
6
+
7
+ // src/cliArgs.ts
8
+ var USAGE = `apple-fm \u2014 command-line access to Apple's on-device Foundation Models
9
+
10
+ Usage:
11
+ apple-fm probe Check on-device model availability
12
+ apple-fm generate [prompt] [flags] One-shot generation (reads stdin if no prompt)
13
+ apple-fm chat [flags] Interactive chat (streaming, auto-compaction)
14
+
15
+ Generate flags:
16
+ -s, --system <text> System instructions
17
+ --schema <file> JSON Schema file for guided/structured output
18
+ --stream Stream output as it is produced
19
+ --temp <n> Sampling temperature
20
+ --max-tokens <n> Maximum response tokens
21
+
22
+ Chat flags:
23
+ -s, --system <text> System instructions
24
+ --no-stream Disable token streaming
25
+ --compact-at <n> Compact the transcript past <n> estimated tokens
26
+
27
+ Global:
28
+ -h, --help Show this help
29
+ -v, --version Show version
30
+
31
+ The helper binary is found via APPLE_FM_BIN, then the bundled bin/apple-fm-helper,
32
+ then apple-fm-helper on PATH. Requires macOS 26+ on Apple Silicon with Apple
33
+ Intelligence enabled.`;
34
+ function parseNumber(flag, value) {
35
+ if (value === void 0) throw new Error(`${flag} requires a value`);
36
+ const n = Number(value);
37
+ if (Number.isNaN(n)) throw new Error(`${flag} expects a number, got "${value}"`);
38
+ return n;
39
+ }
40
+ function takeValue(argv, i, flag) {
41
+ const value = argv[i + 1];
42
+ if (value === void 0) throw new Error(`${flag} requires a value`);
43
+ return value;
44
+ }
45
+ function parseArgs(argv) {
46
+ const first = argv[0];
47
+ if (first === void 0 || first === "-h" || first === "--help") return { command: "help" };
48
+ if (first === "-v" || first === "--version") return { command: "version" };
49
+ switch (first) {
50
+ case "probe":
51
+ return { command: "probe" };
52
+ case "generate":
53
+ return parseGenerate(argv.slice(1));
54
+ case "chat":
55
+ return parseChat(argv.slice(1));
56
+ default:
57
+ throw new Error(`unknown command "${first}" (try: probe, generate, chat, --help)`);
58
+ }
59
+ }
60
+ function parseGenerate(argv) {
61
+ const result = { command: "generate", stream: false };
62
+ for (let i = 0; i < argv.length; i++) {
63
+ const arg = argv[i];
64
+ if (arg === void 0) continue;
65
+ switch (arg) {
66
+ case "-s":
67
+ case "--system":
68
+ result.system = takeValue(argv, i++, arg);
69
+ break;
70
+ case "--schema":
71
+ result.schemaFile = takeValue(argv, i++, arg);
72
+ break;
73
+ case "--stream":
74
+ result.stream = true;
75
+ break;
76
+ case "--temp":
77
+ result.temperature = parseNumber(arg, takeValue(argv, i++, arg));
78
+ break;
79
+ case "--max-tokens":
80
+ result.maxTokens = parseNumber(arg, takeValue(argv, i++, arg));
81
+ break;
82
+ default:
83
+ if (arg.startsWith("-")) throw new Error(`unknown flag "${arg}"`);
84
+ if (result.prompt !== void 0) throw new Error("generate accepts a single prompt argument");
85
+ result.prompt = arg;
86
+ }
87
+ }
88
+ return result;
89
+ }
90
+ function parseChat(argv) {
91
+ const result = { command: "chat", stream: true };
92
+ for (let i = 0; i < argv.length; i++) {
93
+ const arg = argv[i];
94
+ if (arg === void 0) continue;
95
+ switch (arg) {
96
+ case "-s":
97
+ case "--system":
98
+ result.system = takeValue(argv, i++, arg);
99
+ break;
100
+ case "--no-stream":
101
+ result.stream = false;
102
+ break;
103
+ case "--compact-at":
104
+ result.compactAtTokens = parseNumber(arg, takeValue(argv, i++, arg));
105
+ break;
106
+ default:
107
+ throw new Error(`unknown flag "${arg}"`);
108
+ }
109
+ }
110
+ return result;
111
+ }
112
+
113
+ // src/helper.ts
114
+ import { spawn } from "child_process";
115
+ import { fileURLToPath } from "url";
116
+
117
+ // src/protocol.ts
118
+ function encodeRequest(request) {
119
+ return JSON.stringify(request) + "\n";
120
+ }
121
+ function splitLines(buffer) {
122
+ const parts = buffer.split("\n");
123
+ const rest = parts.pop() ?? "";
124
+ const lines = parts.filter((line) => line.trim().length > 0);
125
+ return { lines, rest };
126
+ }
127
+ function parseEvent(line) {
128
+ const value = JSON.parse(line);
129
+ if (typeof value !== "object" || value === null || !("type" in value)) {
130
+ throw new Error(`malformed helper event: ${line}`);
131
+ }
132
+ const event = value;
133
+ switch (event.type) {
134
+ case "delta":
135
+ if (typeof event.text !== "string") break;
136
+ return { type: "delta", text: event.text };
137
+ case "result":
138
+ if (typeof event.content !== "string") break;
139
+ return { type: "result", content: event.content };
140
+ case "error":
141
+ if (typeof event.code !== "string" || typeof event.message !== "string") break;
142
+ return { type: "error", code: event.code, message: event.message };
143
+ default:
144
+ break;
145
+ }
146
+ throw new Error(`malformed helper event: ${line}`);
147
+ }
148
+ function flattenMessages(messages) {
149
+ return messages.map((message) => `${message.role === "assistant" ? "Assistant" : "User"}: ${message.content}`).join("\n\n");
150
+ }
151
+ var CHARS_PER_TOKEN = 4;
152
+ function estimateTokens(text) {
153
+ return Math.ceil(text.length / CHARS_PER_TOKEN);
154
+ }
155
+ function estimateConversationTokens(system, messages) {
156
+ const body = messages.reduce((total, message) => total + estimateTokens(message.content), 0);
157
+ return estimateTokens(system) + body;
158
+ }
159
+
160
+ // src/helper.ts
161
+ var HELPER_BIN_ENV = "APPLE_FM_BIN";
162
+ var DEFAULT_TIMEOUT_MS = 12e4;
163
+ function resolveHelperPath(options = {}) {
164
+ if (options.binPath !== void 0 && options.binPath.length > 0) return options.binPath;
165
+ const fromEnv = process.env[HELPER_BIN_ENV];
166
+ if (fromEnv !== void 0 && fromEnv.length > 0) return fromEnv;
167
+ return fileURLToPath(new URL("../bin/apple-fm-helper", import.meta.url));
168
+ }
169
+ function runHelper(args, options, input, onLine) {
170
+ const command = resolveHelperPath(options);
171
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
172
+ return new Promise((resolve, reject) => {
173
+ const child = spawn(command, args, { stdio: ["pipe", "pipe", "pipe"] });
174
+ let stdout = "";
175
+ let stderr = "";
176
+ let settled = false;
177
+ const timer = setTimeout(() => {
178
+ if (settled) return;
179
+ settled = true;
180
+ child.kill("SIGKILL");
181
+ reject(new Error(`apple-fm helper timed out after ${String(timeoutMs)}ms`));
182
+ }, timeoutMs);
183
+ const finish = (error) => {
184
+ if (settled) return;
185
+ settled = true;
186
+ clearTimeout(timer);
187
+ if (error) reject(error);
188
+ else resolve();
189
+ };
190
+ child.on("error", (error) => {
191
+ finish(new Error(`failed to run apple-fm helper (${command}): ${error.message}`));
192
+ });
193
+ const deliver = (line) => {
194
+ try {
195
+ onLine(line);
196
+ return true;
197
+ } catch (error) {
198
+ child.kill("SIGKILL");
199
+ finish(error instanceof Error ? error : new Error(String(error)));
200
+ return false;
201
+ }
202
+ };
203
+ child.stdout.setEncoding("utf8");
204
+ child.stdout.on("data", (chunk) => {
205
+ stdout += chunk;
206
+ const { lines, rest } = splitLines(stdout);
207
+ stdout = rest;
208
+ for (const line of lines) if (!deliver(line)) return;
209
+ });
210
+ child.stderr.setEncoding("utf8");
211
+ child.stderr.on("data", (chunk) => stderr += chunk);
212
+ child.on("close", (code) => {
213
+ if (settled) return;
214
+ const trailing = stdout.trim();
215
+ if (trailing.length > 0 && !deliver(trailing)) return;
216
+ if (code === 0) finish();
217
+ else finish(new Error(`apple-fm helper exited with code ${String(code)}: ${stderr.trim()}`));
218
+ });
219
+ if (input !== void 0) {
220
+ child.stdin.on("error", () => void 0);
221
+ child.stdin.end(input);
222
+ } else {
223
+ child.stdin.end();
224
+ }
225
+ });
226
+ }
227
+ async function probe(options = {}) {
228
+ let result;
229
+ await runHelper(["--probe"], options, void 0, (line) => {
230
+ result = JSON.parse(line);
231
+ });
232
+ if (result === void 0) throw new Error("apple-fm helper --probe produced no result");
233
+ return result;
234
+ }
235
+ async function generate(request, options = {}, onDelta) {
236
+ let content;
237
+ await runHelper(["--generate"], options, encodeRequest(request), (line) => {
238
+ const event = parseEvent(line);
239
+ switch (event.type) {
240
+ case "delta":
241
+ onDelta?.(event.text);
242
+ break;
243
+ case "result":
244
+ content = event.content;
245
+ break;
246
+ case "error":
247
+ throw new Error(`[${event.code}] ${event.message}`);
248
+ }
249
+ });
250
+ if (content === void 0) throw new Error("apple-fm helper --generate produced no result");
251
+ return content;
252
+ }
253
+
254
+ // src/repl.ts
255
+ import { createInterface } from "readline";
256
+
257
+ // src/session.ts
258
+ var DEFAULT_COMPACT_AT = 3e3;
259
+ var DEFAULT_KEEP_RECENT = 4;
260
+ var SUMMARIZE_SYSTEM = "You compress conversations. Given a transcript, produce a terse third-person summary that preserves facts, decisions, names, and open questions needed to continue the conversation. Output only the summary prose.";
261
+ function defaultGenerateFn(helper, options) {
262
+ return (system, messages, onDelta) => generate({ system, messages, options, stream: onDelta !== void 0 }, helper, onDelta);
263
+ }
264
+ var ChatSession = class {
265
+ system;
266
+ options;
267
+ compactAtTokens;
268
+ keepRecentTurns;
269
+ generateFn;
270
+ messages = [];
271
+ /** Recap of turns dropped by compaction; folded into the system prompt. */
272
+ summary;
273
+ constructor(config = {}) {
274
+ this.system = config.system ?? "";
275
+ this.options = config.options;
276
+ this.compactAtTokens = config.compactAtTokens ?? DEFAULT_COMPACT_AT;
277
+ this.keepRecentTurns = config.keepRecentTurns ?? DEFAULT_KEEP_RECENT;
278
+ this.generateFn = config.generateFn ?? defaultGenerateFn(config.helper, config.options);
279
+ }
280
+ /** The system prompt actually sent to the model (instructions + any recap). */
281
+ effectiveSystem() {
282
+ if (this.summary === void 0) return this.system;
283
+ const recap = `Conversation so far:
284
+ ${this.summary}`;
285
+ return this.system.length > 0 ? `${this.system}
286
+
287
+ ${recap}` : recap;
288
+ }
289
+ /** The current transcript (a copy; mutating it does not affect the session). */
290
+ history() {
291
+ return this.messages.map((message) => ({ ...message }));
292
+ }
293
+ /** Whether the next turn would push the transcript past the compaction bound. */
294
+ shouldCompact() {
295
+ return estimateConversationTokens(this.effectiveSystem(), this.messages) > this.compactAtTokens;
296
+ }
297
+ /** Send a user turn and return the assistant's reply (streamed via `onDelta`). */
298
+ async send(text, onDelta) {
299
+ if (this.shouldCompact()) await this.compact();
300
+ this.messages.push({ role: "user", content: text });
301
+ const reply = await this.generateFn(this.effectiveSystem(), this.messages, onDelta);
302
+ this.messages.push({ role: "assistant", content: reply });
303
+ return reply;
304
+ }
305
+ /**
306
+ * Fold all but the most recent turns into the rolling summary. Safe to call
307
+ * directly; {@link send} calls it automatically when {@link shouldCompact}.
308
+ */
309
+ async compact() {
310
+ if (this.messages.length <= this.keepRecentTurns) return;
311
+ const cutoff = this.messages.length - this.keepRecentTurns;
312
+ const older = this.messages.slice(0, cutoff);
313
+ const recent = this.messages.slice(cutoff);
314
+ const transcript = [
315
+ this.summary !== void 0 ? `Previous summary:
316
+ ${this.summary}` : "",
317
+ flattenMessages(older)
318
+ ].filter((part) => part.length > 0).join("\n\n");
319
+ this.summary = (await this.generateFn(SUMMARIZE_SYSTEM, [{ role: "user", content: transcript }])).trim();
320
+ this.messages = recent;
321
+ }
322
+ /** Clear the transcript and summary; optionally replace the system prompt. */
323
+ reset(system) {
324
+ if (system !== void 0) this.system = system;
325
+ this.messages = [];
326
+ this.summary = void 0;
327
+ }
328
+ };
329
+
330
+ // src/repl.ts
331
+ var HELP = `Commands:
332
+ /reset [system] Start over (optionally set new system instructions)
333
+ /system <text> Replace the system instructions and reset
334
+ /clear Clear the conversation context (keep system instructions)
335
+ /compact Compact the conversation context now
336
+ /help Show this help
337
+ /quit Quit (alias /exit, or Ctrl-D)`;
338
+ async function runRepl(opts) {
339
+ const session = new ChatSession({
340
+ system: opts.system,
341
+ options: opts.options,
342
+ compactAtTokens: opts.compactAtTokens
343
+ });
344
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
345
+ process.stdout.write("apple-fm chat \u2014 Ctrl-D or /quit to quit, /help for commands.\n");
346
+ rl.setPrompt("> ");
347
+ rl.prompt();
348
+ for await (const line of rl) {
349
+ const text = line.trim();
350
+ if (text.length === 0) {
351
+ rl.prompt();
352
+ continue;
353
+ }
354
+ if (text === "/quit" || text === "/exit") break;
355
+ if (text === "/help") {
356
+ process.stdout.write(`${HELP}
357
+ `);
358
+ rl.prompt();
359
+ continue;
360
+ }
361
+ if (text === "/clear") {
362
+ session.reset();
363
+ process.stdout.write("(context cleared)\n");
364
+ rl.prompt();
365
+ continue;
366
+ }
367
+ if (text === "/compact") {
368
+ try {
369
+ await session.compact();
370
+ process.stdout.write("(compacted)\n");
371
+ } catch (error) {
372
+ process.stdout.write(`error: ${error instanceof Error ? error.message : String(error)}
373
+ `);
374
+ }
375
+ rl.prompt();
376
+ continue;
377
+ }
378
+ if (text === "/reset" || text.startsWith("/reset ")) {
379
+ session.reset(text.slice("/reset".length).trim() || void 0);
380
+ process.stdout.write("(reset)\n");
381
+ rl.prompt();
382
+ continue;
383
+ }
384
+ if (text.startsWith("/system ")) {
385
+ session.reset(text.slice("/system ".length).trim());
386
+ process.stdout.write("(system updated, conversation reset)\n");
387
+ rl.prompt();
388
+ continue;
389
+ }
390
+ try {
391
+ const reply = await session.send(text, opts.stream ? (chunk) => process.stdout.write(chunk) : void 0);
392
+ if (!opts.stream) process.stdout.write(reply);
393
+ process.stdout.write("\n");
394
+ } catch (error) {
395
+ process.stdout.write(`error: ${error instanceof Error ? error.message : String(error)}
396
+ `);
397
+ }
398
+ rl.prompt();
399
+ }
400
+ rl.close();
401
+ }
402
+
403
+ // src/cli.ts
404
+ async function readStdin() {
405
+ const chunks = [];
406
+ for await (const chunk of process.stdin) chunks.push(chunk);
407
+ return Buffer.concat(chunks).toString("utf8").trim();
408
+ }
409
+ function readVersion() {
410
+ try {
411
+ const url = new URL("../package.json", import.meta.url);
412
+ const pkg = JSON.parse(readFileSync(url, "utf8"));
413
+ return pkg.version;
414
+ } catch {
415
+ return "0.0.0";
416
+ }
417
+ }
418
+ async function main() {
419
+ const args = parseArgs(process.argv.slice(2));
420
+ switch (args.command) {
421
+ case "help":
422
+ process.stdout.write(`${USAGE}
423
+ `);
424
+ return;
425
+ case "version":
426
+ process.stdout.write(`${readVersion()}
427
+ `);
428
+ return;
429
+ case "probe": {
430
+ const result = await probe();
431
+ process.stdout.write(`${JSON.stringify(result)}
432
+ `);
433
+ if (!result.available) process.exitCode = 1;
434
+ return;
435
+ }
436
+ case "generate": {
437
+ const prompt = args.prompt ?? await readStdin();
438
+ if (prompt.length === 0) throw new Error("generate: no prompt given (pass an argument or pipe stdin)");
439
+ const options = {};
440
+ if (args.temperature !== void 0) options.temperature = args.temperature;
441
+ if (args.maxTokens !== void 0) options.maxTokens = args.maxTokens;
442
+ const request = { prompt, system: args.system, options, stream: args.stream };
443
+ if (args.schemaFile !== void 0) request.schema = JSON.parse(await readFile(args.schemaFile, "utf8"));
444
+ const text = await generate(request, {}, args.stream ? (chunk) => process.stdout.write(chunk) : void 0);
445
+ if (!args.stream) process.stdout.write(text);
446
+ process.stdout.write("\n");
447
+ return;
448
+ }
449
+ case "chat": {
450
+ await runRepl({ system: args.system, stream: args.stream, compactAtTokens: args.compactAtTokens });
451
+ return;
452
+ }
453
+ }
454
+ }
455
+ main().catch((error) => {
456
+ process.stderr.write(`apple-fm: ${error instanceof Error ? error.message : String(error)}
457
+ `);
458
+ process.exitCode = 1;
459
+ });
460
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Shared types for apple-fm.
3
+ *
4
+ * The Node layer never imports `FoundationModels` directly — it spawns the Swift
5
+ * helper (`apple-fm-helper`) and exchanges line-delimited JSON. These types
6
+ * describe that wire contract and the public API built on top of it.
7
+ */
8
+ /** A conversational role. The on-device model is instructed via `system`. */
9
+ type Role = 'user' | 'assistant';
10
+ /** One turn in a conversation. */
11
+ interface Message {
12
+ role: Role;
13
+ content: string;
14
+ }
15
+ /** Per-request generation knobs, passed through to the on-device session. */
16
+ interface GenerateOptions {
17
+ /** Sampling temperature (0–2). Omitted ⇒ the model's default. */
18
+ temperature?: number;
19
+ /** Cap on the response length, in tokens. Omitted ⇒ the model's default. */
20
+ maxTokens?: number;
21
+ }
22
+ /**
23
+ * A single generation request sent to the helper's `--generate` mode.
24
+ *
25
+ * Provide either `prompt` (a single user turn) or `messages` (a full
26
+ * conversation, replayed as the session transcript). `schema`, when present,
27
+ * requests guided generation that conforms to the given JSON Schema.
28
+ */
29
+ interface GenerateRequest {
30
+ /** Instructions for the session (the system prompt). */
31
+ system?: string;
32
+ /** A single user turn. Mutually exclusive with `messages`. */
33
+ prompt?: string;
34
+ /** A full conversation. Mutually exclusive with `prompt`. */
35
+ messages?: Message[];
36
+ /** JSON Schema for guided/structured output. */
37
+ schema?: unknown;
38
+ /** Generation knobs. */
39
+ options?: GenerateOptions;
40
+ /** Stream partial output as `delta` events (default: false). */
41
+ stream?: boolean;
42
+ }
43
+ /** Why the on-device model is or isn't usable right now. */
44
+ type UnavailableReason = 'deviceNotEligible' | 'appleIntelligenceNotEnabled' | 'modelNotReady' | 'unknown';
45
+ /** Result of `apple-fm-helper --probe`. */
46
+ interface ProbeResult {
47
+ available: boolean;
48
+ /** Present only when `available` is false. */
49
+ reason?: UnavailableReason;
50
+ }
51
+ /**
52
+ * One line of helper output (NDJSON). `delta` events appear only when streaming;
53
+ * every successful generation ends with exactly one `result`. Failures emit a
54
+ * single `error`.
55
+ */
56
+ type HelperEvent = {
57
+ type: 'delta';
58
+ text: string;
59
+ } | {
60
+ type: 'result';
61
+ content: string;
62
+ } | {
63
+ type: 'error';
64
+ code: string;
65
+ message: string;
66
+ };
67
+ /** Options for locating + invoking the helper binary. */
68
+ interface HelperOptions {
69
+ /** Explicit path to the helper binary. Overrides discovery. */
70
+ binPath?: string;
71
+ /** Milliseconds before a one-shot generation is aborted (default 120_000). */
72
+ timeoutMs?: number;
73
+ }
74
+ /** Callback fired for each streamed text chunk. */
75
+ type DeltaHandler = (text: string) => void;
76
+
77
+ /** Environment variable that pins the helper binary path. */
78
+ declare const HELPER_BIN_ENV = "APPLE_FM_BIN";
79
+ /**
80
+ * Resolve the helper binary path: `APPLE_FM_BIN`, then the prebuilt binary
81
+ * bundled with the package (`bin/apple-fm-helper`), then bare `apple-fm-helper`
82
+ * to be found on `PATH` (e.g. a Homebrew install).
83
+ */
84
+ declare function resolveHelperPath(options?: HelperOptions): string;
85
+ /** Ask the helper whether the on-device model is available right now. */
86
+ declare function probe(options?: HelperOptions): Promise<ProbeResult>;
87
+ /**
88
+ * Run one generation. Streamed `delta` chunks are forwarded to `onDelta` (when
89
+ * `request.stream` is set); the resolved value is always the full text (or, for
90
+ * guided generation, the JSON string).
91
+ */
92
+ declare function generate(request: GenerateRequest, options?: HelperOptions, onDelta?: DeltaHandler): Promise<string>;
93
+
94
+ /**
95
+ * The line-delimited JSON (NDJSON) wire protocol between the Node layer and the
96
+ * Swift helper, plus small pure helpers used by both the one-shot and chat
97
+ * paths. Everything here is pure and unit-tested directly — no I/O.
98
+ */
99
+
100
+ /** Encode a generation request as the single JSON line the helper reads. */
101
+ declare function encodeRequest(request: GenerateRequest): string;
102
+ /**
103
+ * Split a streaming buffer into complete NDJSON lines plus the trailing
104
+ * remainder that has not yet been terminated by a newline. Carry `rest` into the
105
+ * next chunk.
106
+ */
107
+ declare function splitLines(buffer: string): {
108
+ lines: string[];
109
+ rest: string;
110
+ };
111
+ /**
112
+ * Parse one NDJSON line into a {@link HelperEvent}. Throws if the line is not a
113
+ * recognized event shape, so callers can surface a clear protocol error rather
114
+ * than silently dropping output.
115
+ */
116
+ declare function parseEvent(line: string): HelperEvent;
117
+ /**
118
+ * Flatten a conversation into a single prompt with labeled turns. The helper is
119
+ * stateless per one-shot call, so multi-turn context is replayed this way; the
120
+ * system prompt is delivered separately as the session's instructions.
121
+ *
122
+ * This is the canonical labeled-turn format (`User:`/`Assistant:`, blank-line
123
+ * separated). `session.ts:compact` reuses it, and `apple-fm-helper/main.swift`
124
+ * (`userPrompt`) must mirror it byte-for-byte so on-device replay matches; the
125
+ * format is pinned by a test in `tests/protocol.test.ts`.
126
+ */
127
+ declare function flattenMessages(messages: Message[]): string;
128
+ /**
129
+ * Rough token estimate (~4 characters per token). Used only to decide when a
130
+ * chat transcript should be compacted; it does not need to be exact, just
131
+ * monotonic and cheap.
132
+ */
133
+ declare function estimateTokens(text: string): number;
134
+ /** Sum the estimated tokens of a system prompt plus a conversation. */
135
+ declare function estimateConversationTokens(system: string, messages: Message[]): number;
136
+
137
+ /** Pluggable generation function (real helper by default; a stub in tests). */
138
+ type GenerateFn = (system: string, messages: Message[], onDelta?: DeltaHandler) => Promise<string>;
139
+ /** Configuration for a {@link ChatSession}. */
140
+ interface ChatSessionConfig {
141
+ /** Instructions for the model (system prompt). */
142
+ system?: string;
143
+ /** Generation knobs forwarded to every turn. */
144
+ options?: GenerateOptions;
145
+ /**
146
+ * Compact the transcript once its estimated size (system + summary + turns)
147
+ * exceeds this many tokens. The on-device window is ~4k; default 3000 leaves
148
+ * headroom for the summarization turn itself.
149
+ */
150
+ compactAtTokens?: number;
151
+ /** Number of most-recent turns kept verbatim through a compaction (default 4). */
152
+ keepRecentTurns?: number;
153
+ /** Helper discovery / timeout options (ignored when `generateFn` is given). */
154
+ helper?: HelperOptions;
155
+ /** Override the generation backend (tests inject a stub here). */
156
+ generateFn?: GenerateFn;
157
+ }
158
+ /** A stateful, auto-compacting conversation with the on-device model. */
159
+ declare class ChatSession {
160
+ private system;
161
+ private readonly options;
162
+ private readonly compactAtTokens;
163
+ private readonly keepRecentTurns;
164
+ private readonly generateFn;
165
+ private messages;
166
+ /** Recap of turns dropped by compaction; folded into the system prompt. */
167
+ private summary;
168
+ constructor(config?: ChatSessionConfig);
169
+ /** The system prompt actually sent to the model (instructions + any recap). */
170
+ private effectiveSystem;
171
+ /** The current transcript (a copy; mutating it does not affect the session). */
172
+ history(): Message[];
173
+ /** Whether the next turn would push the transcript past the compaction bound. */
174
+ shouldCompact(): boolean;
175
+ /** Send a user turn and return the assistant's reply (streamed via `onDelta`). */
176
+ send(text: string, onDelta?: DeltaHandler): Promise<string>;
177
+ /**
178
+ * Fold all but the most recent turns into the rolling summary. Safe to call
179
+ * directly; {@link send} calls it automatically when {@link shouldCompact}.
180
+ */
181
+ compact(): Promise<void>;
182
+ /** Clear the transcript and summary; optionally replace the system prompt. */
183
+ reset(system?: string): void;
184
+ }
185
+
186
+ export { ChatSession, type ChatSessionConfig, type DeltaHandler, type GenerateFn, type GenerateOptions, type GenerateRequest, HELPER_BIN_ENV, type HelperEvent, type HelperOptions, type Message, type ProbeResult, type Role, type UnavailableReason, encodeRequest, estimateConversationTokens, estimateTokens, flattenMessages, generate, parseEvent, probe, resolveHelperPath, splitLines };
package/dist/index.js ADDED
@@ -0,0 +1,227 @@
1
+ // src/helper.ts
2
+ import { spawn } from "child_process";
3
+ import { fileURLToPath } from "url";
4
+
5
+ // src/protocol.ts
6
+ function encodeRequest(request) {
7
+ return JSON.stringify(request) + "\n";
8
+ }
9
+ function splitLines(buffer) {
10
+ const parts = buffer.split("\n");
11
+ const rest = parts.pop() ?? "";
12
+ const lines = parts.filter((line) => line.trim().length > 0);
13
+ return { lines, rest };
14
+ }
15
+ function parseEvent(line) {
16
+ const value = JSON.parse(line);
17
+ if (typeof value !== "object" || value === null || !("type" in value)) {
18
+ throw new Error(`malformed helper event: ${line}`);
19
+ }
20
+ const event = value;
21
+ switch (event.type) {
22
+ case "delta":
23
+ if (typeof event.text !== "string") break;
24
+ return { type: "delta", text: event.text };
25
+ case "result":
26
+ if (typeof event.content !== "string") break;
27
+ return { type: "result", content: event.content };
28
+ case "error":
29
+ if (typeof event.code !== "string" || typeof event.message !== "string") break;
30
+ return { type: "error", code: event.code, message: event.message };
31
+ default:
32
+ break;
33
+ }
34
+ throw new Error(`malformed helper event: ${line}`);
35
+ }
36
+ function flattenMessages(messages) {
37
+ return messages.map((message) => `${message.role === "assistant" ? "Assistant" : "User"}: ${message.content}`).join("\n\n");
38
+ }
39
+ var CHARS_PER_TOKEN = 4;
40
+ function estimateTokens(text) {
41
+ return Math.ceil(text.length / CHARS_PER_TOKEN);
42
+ }
43
+ function estimateConversationTokens(system, messages) {
44
+ const body = messages.reduce((total, message) => total + estimateTokens(message.content), 0);
45
+ return estimateTokens(system) + body;
46
+ }
47
+
48
+ // src/helper.ts
49
+ var HELPER_BIN_ENV = "APPLE_FM_BIN";
50
+ var DEFAULT_TIMEOUT_MS = 12e4;
51
+ function resolveHelperPath(options = {}) {
52
+ if (options.binPath !== void 0 && options.binPath.length > 0) return options.binPath;
53
+ const fromEnv = process.env[HELPER_BIN_ENV];
54
+ if (fromEnv !== void 0 && fromEnv.length > 0) return fromEnv;
55
+ return fileURLToPath(new URL("../bin/apple-fm-helper", import.meta.url));
56
+ }
57
+ function runHelper(args, options, input, onLine) {
58
+ const command = resolveHelperPath(options);
59
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
60
+ return new Promise((resolve, reject) => {
61
+ const child = spawn(command, args, { stdio: ["pipe", "pipe", "pipe"] });
62
+ let stdout = "";
63
+ let stderr = "";
64
+ let settled = false;
65
+ const timer = setTimeout(() => {
66
+ if (settled) return;
67
+ settled = true;
68
+ child.kill("SIGKILL");
69
+ reject(new Error(`apple-fm helper timed out after ${String(timeoutMs)}ms`));
70
+ }, timeoutMs);
71
+ const finish = (error) => {
72
+ if (settled) return;
73
+ settled = true;
74
+ clearTimeout(timer);
75
+ if (error) reject(error);
76
+ else resolve();
77
+ };
78
+ child.on("error", (error) => {
79
+ finish(new Error(`failed to run apple-fm helper (${command}): ${error.message}`));
80
+ });
81
+ const deliver = (line) => {
82
+ try {
83
+ onLine(line);
84
+ return true;
85
+ } catch (error) {
86
+ child.kill("SIGKILL");
87
+ finish(error instanceof Error ? error : new Error(String(error)));
88
+ return false;
89
+ }
90
+ };
91
+ child.stdout.setEncoding("utf8");
92
+ child.stdout.on("data", (chunk) => {
93
+ stdout += chunk;
94
+ const { lines, rest } = splitLines(stdout);
95
+ stdout = rest;
96
+ for (const line of lines) if (!deliver(line)) return;
97
+ });
98
+ child.stderr.setEncoding("utf8");
99
+ child.stderr.on("data", (chunk) => stderr += chunk);
100
+ child.on("close", (code) => {
101
+ if (settled) return;
102
+ const trailing = stdout.trim();
103
+ if (trailing.length > 0 && !deliver(trailing)) return;
104
+ if (code === 0) finish();
105
+ else finish(new Error(`apple-fm helper exited with code ${String(code)}: ${stderr.trim()}`));
106
+ });
107
+ if (input !== void 0) {
108
+ child.stdin.on("error", () => void 0);
109
+ child.stdin.end(input);
110
+ } else {
111
+ child.stdin.end();
112
+ }
113
+ });
114
+ }
115
+ async function probe(options = {}) {
116
+ let result;
117
+ await runHelper(["--probe"], options, void 0, (line) => {
118
+ result = JSON.parse(line);
119
+ });
120
+ if (result === void 0) throw new Error("apple-fm helper --probe produced no result");
121
+ return result;
122
+ }
123
+ async function generate(request, options = {}, onDelta) {
124
+ let content;
125
+ await runHelper(["--generate"], options, encodeRequest(request), (line) => {
126
+ const event = parseEvent(line);
127
+ switch (event.type) {
128
+ case "delta":
129
+ onDelta?.(event.text);
130
+ break;
131
+ case "result":
132
+ content = event.content;
133
+ break;
134
+ case "error":
135
+ throw new Error(`[${event.code}] ${event.message}`);
136
+ }
137
+ });
138
+ if (content === void 0) throw new Error("apple-fm helper --generate produced no result");
139
+ return content;
140
+ }
141
+
142
+ // src/session.ts
143
+ var DEFAULT_COMPACT_AT = 3e3;
144
+ var DEFAULT_KEEP_RECENT = 4;
145
+ var SUMMARIZE_SYSTEM = "You compress conversations. Given a transcript, produce a terse third-person summary that preserves facts, decisions, names, and open questions needed to continue the conversation. Output only the summary prose.";
146
+ function defaultGenerateFn(helper, options) {
147
+ return (system, messages, onDelta) => generate({ system, messages, options, stream: onDelta !== void 0 }, helper, onDelta);
148
+ }
149
+ var ChatSession = class {
150
+ system;
151
+ options;
152
+ compactAtTokens;
153
+ keepRecentTurns;
154
+ generateFn;
155
+ messages = [];
156
+ /** Recap of turns dropped by compaction; folded into the system prompt. */
157
+ summary;
158
+ constructor(config = {}) {
159
+ this.system = config.system ?? "";
160
+ this.options = config.options;
161
+ this.compactAtTokens = config.compactAtTokens ?? DEFAULT_COMPACT_AT;
162
+ this.keepRecentTurns = config.keepRecentTurns ?? DEFAULT_KEEP_RECENT;
163
+ this.generateFn = config.generateFn ?? defaultGenerateFn(config.helper, config.options);
164
+ }
165
+ /** The system prompt actually sent to the model (instructions + any recap). */
166
+ effectiveSystem() {
167
+ if (this.summary === void 0) return this.system;
168
+ const recap = `Conversation so far:
169
+ ${this.summary}`;
170
+ return this.system.length > 0 ? `${this.system}
171
+
172
+ ${recap}` : recap;
173
+ }
174
+ /** The current transcript (a copy; mutating it does not affect the session). */
175
+ history() {
176
+ return this.messages.map((message) => ({ ...message }));
177
+ }
178
+ /** Whether the next turn would push the transcript past the compaction bound. */
179
+ shouldCompact() {
180
+ return estimateConversationTokens(this.effectiveSystem(), this.messages) > this.compactAtTokens;
181
+ }
182
+ /** Send a user turn and return the assistant's reply (streamed via `onDelta`). */
183
+ async send(text, onDelta) {
184
+ if (this.shouldCompact()) await this.compact();
185
+ this.messages.push({ role: "user", content: text });
186
+ const reply = await this.generateFn(this.effectiveSystem(), this.messages, onDelta);
187
+ this.messages.push({ role: "assistant", content: reply });
188
+ return reply;
189
+ }
190
+ /**
191
+ * Fold all but the most recent turns into the rolling summary. Safe to call
192
+ * directly; {@link send} calls it automatically when {@link shouldCompact}.
193
+ */
194
+ async compact() {
195
+ if (this.messages.length <= this.keepRecentTurns) return;
196
+ const cutoff = this.messages.length - this.keepRecentTurns;
197
+ const older = this.messages.slice(0, cutoff);
198
+ const recent = this.messages.slice(cutoff);
199
+ const transcript = [
200
+ this.summary !== void 0 ? `Previous summary:
201
+ ${this.summary}` : "",
202
+ flattenMessages(older)
203
+ ].filter((part) => part.length > 0).join("\n\n");
204
+ this.summary = (await this.generateFn(SUMMARIZE_SYSTEM, [{ role: "user", content: transcript }])).trim();
205
+ this.messages = recent;
206
+ }
207
+ /** Clear the transcript and summary; optionally replace the system prompt. */
208
+ reset(system) {
209
+ if (system !== void 0) this.system = system;
210
+ this.messages = [];
211
+ this.summary = void 0;
212
+ }
213
+ };
214
+ export {
215
+ ChatSession,
216
+ HELPER_BIN_ENV,
217
+ encodeRequest,
218
+ estimateConversationTokens,
219
+ estimateTokens,
220
+ flattenMessages,
221
+ generate,
222
+ parseEvent,
223
+ probe,
224
+ resolveHelperPath,
225
+ splitLines
226
+ };
227
+ //# sourceMappingURL=index.js.map
package/package.json ADDED
@@ -0,0 +1,76 @@
1
+ {
2
+ "name": "apple-fm",
3
+ "version": "0.0.1",
4
+ "description": "Command-line and programmatic access to Apple's on-device Foundation Models (Apple Intelligence) on macOS 26+.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Brian Westphal",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/brianwestphal/apple-fm.git"
11
+ },
12
+ "keywords": [
13
+ "apple",
14
+ "apple-intelligence",
15
+ "foundation-models",
16
+ "on-device",
17
+ "llm",
18
+ "ai",
19
+ "macos",
20
+ "cli",
21
+ "chat"
22
+ ],
23
+ "os": [
24
+ "darwin"
25
+ ],
26
+ "engines": {
27
+ "node": ">=20"
28
+ },
29
+ "bin": {
30
+ "apple-fm": "dist/cli.js"
31
+ },
32
+ "main": "./dist/index.js",
33
+ "module": "./dist/index.js",
34
+ "types": "./dist/index.d.ts",
35
+ "exports": {
36
+ ".": {
37
+ "types": "./dist/index.d.ts",
38
+ "import": "./dist/index.js"
39
+ }
40
+ },
41
+ "files": [
42
+ "dist",
43
+ "!dist/*.map",
44
+ "apple-fm-helper",
45
+ "scripts/build-apple-fm-helper.sh",
46
+ "bin/apple-fm-helper"
47
+ ],
48
+ "scripts": {
49
+ "build": "tsup",
50
+ "build:helper": "bash scripts/build-apple-fm-helper.sh",
51
+ "dev": "tsup --watch",
52
+ "test": "vitest run --coverage",
53
+ "test:watch": "vitest",
54
+ "lint": "eslint src/ tests/",
55
+ "typecheck": "tsc --noEmit",
56
+ "clean": "rm -rf dist coverage node_modules/.cache",
57
+ "release": "bash scripts/release.sh",
58
+ "release:beta": "bash scripts/release.sh --beta",
59
+ "prepublishOnly": "npm run build"
60
+ },
61
+ "devDependencies": {
62
+ "@eslint/js": "^10.0.1",
63
+ "@types/node": "^25.9.3",
64
+ "@vitest/coverage-v8": "^4.1.9",
65
+ "eslint": "^10.5.0",
66
+ "eslint-plugin-import-x": "^4.16.2",
67
+ "eslint-plugin-simple-import-sort": "^12.1.1",
68
+ "eslint-plugin-tsdoc": "^0.5.2",
69
+ "tsup": "^8.5.1",
70
+ "tsx": "^4.22.4",
71
+ "typescript": "^5.9.3",
72
+ "typescript-eslint": "^8.61.1",
73
+ "vitest": "^4.1.9"
74
+ },
75
+ "dependencies": {}
76
+ }
@@ -0,0 +1,49 @@
1
+ #!/usr/bin/env bash
2
+ # Compile the Apple Foundation Models helper (apple-fm-helper/main.swift) — the
3
+ # native Swift binary that apple-fm shells out to.
4
+ #
5
+ # GUARDED so it never breaks a build: it no-ops with exit 0 on non-macOS, when
6
+ # swiftc is missing, or when the macOS 26 SDK (FoundationModels) isn't present.
7
+ # On a capable machine it emits the helper binary at $1 (default ./bin/apple-fm-helper);
8
+ # point apple-fm at it with APPLE_FM_BIN, or run from a directory where
9
+ # ./bin/apple-fm-helper is resolvable.
10
+ #
11
+ # Code-signing: set CODESIGN_IDENTITY to sign the binary (needed if you ship it
12
+ # to other machines — the helper must be signed + notarized to run elsewhere).
13
+ set -euo pipefail
14
+
15
+ ROOT="$(cd "$(dirname "$0")/.." && pwd)"
16
+ OUT="${1:-$ROOT/bin/apple-fm-helper}"
17
+ SRC="$ROOT/apple-fm-helper/main.swift"
18
+
19
+ if [[ "$(uname -s)" != "Darwin" ]]; then
20
+ echo "[apple-fm] not macOS — skipping helper build"; exit 0
21
+ fi
22
+ if ! command -v swiftc >/dev/null 2>&1; then
23
+ echo "[apple-fm] swiftc not found — skipping helper build"; exit 0
24
+ fi
25
+ if [[ ! -f "$SRC" ]]; then
26
+ echo "[apple-fm] source missing ($SRC) — skipping"; exit 0
27
+ fi
28
+
29
+ mkdir -p "$(dirname "$OUT")"
30
+
31
+ # Capture swiftc's diagnostics to a per-run temp file (not a hardcoded shared
32
+ # /tmp path, which breaks where /tmp is read-only and collides across builds).
33
+ LOG="$(mktemp "${TMPDIR:-/tmp}/apple-fm-build.XXXXXX.log")"
34
+ trap 'rm -f "$LOG"' EXIT
35
+
36
+ # Apple Intelligence is arm64-only and needs the macOS 26 SDK for FoundationModels.
37
+ if ! swiftc -O -target arm64-apple-macos26 "$SRC" -o "$OUT" 2>"$LOG"; then
38
+ echo "[apple-fm] build failed (needs the macOS 26 SDK / Xcode 26) — skipping:"
39
+ sed 's/^/[apple-fm] /' "$LOG" || true
40
+ exit 0
41
+ fi
42
+
43
+ if [[ -n "${CODESIGN_IDENTITY:-}" ]]; then
44
+ # Hardened runtime + secure timestamp are required for notarization.
45
+ codesign --force --options runtime --timestamp --sign "$CODESIGN_IDENTITY" "$OUT"
46
+ echo "[apple-fm] signed with $CODESIGN_IDENTITY"
47
+ fi
48
+
49
+ echo "[apple-fm] built $OUT"