@tanstack-ai-browser/afm 0.0.0-stage → 0.2.2

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.
Files changed (56) hide show
  1. package/LICENSE +21 -0
  2. package/Package.swift +33 -0
  3. package/README.md +75 -2
  4. package/dist/adapter.d.ts +107 -0
  5. package/dist/adapter.d.ts.map +1 -0
  6. package/dist/adapter.js +522 -0
  7. package/dist/electron.d.ts +29 -0
  8. package/dist/electron.d.ts.map +1 -0
  9. package/dist/electron.js +136 -0
  10. package/dist/index.d.ts +17 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +12 -0
  13. package/dist/json-value.d.ts +9 -0
  14. package/dist/json-value.d.ts.map +1 -0
  15. package/dist/json-value.js +19 -0
  16. package/dist/messages.d.ts +12 -0
  17. package/dist/messages.d.ts.map +1 -0
  18. package/dist/messages.js +29 -0
  19. package/dist/model-meta.d.ts +23 -0
  20. package/dist/model-meta.d.ts.map +1 -0
  21. package/dist/model-meta.js +20 -0
  22. package/dist/native.d.ts +175 -0
  23. package/dist/native.d.ts.map +1 -0
  24. package/dist/native.js +21 -0
  25. package/dist/schema.d.ts +17 -0
  26. package/dist/schema.d.ts.map +1 -0
  27. package/dist/schema.js +133 -0
  28. package/dist/validate.d.ts +2 -0
  29. package/dist/validate.d.ts.map +1 -0
  30. package/dist/validate.js +124 -0
  31. package/electron/AfmNode.swift +81 -0
  32. package/electron/afm.c +94 -0
  33. package/electron/afm.node +0 -0
  34. package/electron/afm.node.sha256 +1 -0
  35. package/electron/build.mjs +54 -0
  36. package/electron/preload.cjs +35 -0
  37. package/electron/sources-hash.mjs +40 -0
  38. package/ios/Sources/AfmCore/Bridge.swift +354 -0
  39. package/ios/Sources/AfmCore/Conversation.swift +49 -0
  40. package/ios/Sources/AfmCore/Schema.swift +90 -0
  41. package/ios/Sources/AfmPlugin/AfmPlugin.swift +89 -0
  42. package/package.json +97 -3
  43. package/src/adapter.test.ts +428 -0
  44. package/src/adapter.ts +616 -0
  45. package/src/electron.ts +193 -0
  46. package/src/index.ts +28 -0
  47. package/src/json-value.test.ts +26 -0
  48. package/src/json-value.ts +17 -0
  49. package/src/messages.ts +37 -0
  50. package/src/model-meta.ts +37 -0
  51. package/src/native-build.test.ts +13 -0
  52. package/src/native.ts +128 -0
  53. package/src/schema.test.ts +146 -0
  54. package/src/schema.ts +153 -0
  55. package/src/validate.test.ts +38 -0
  56. package/src/validate.ts +112 -0
@@ -0,0 +1,522 @@
1
+ /**
2
+ * A TanStack AI text adapter for Apple's on-device model, through the
3
+ * Foundation Models framework itself: the Capacitor plugin on iOS, or any
4
+ * host that implements `AfmNative`. Hand it to `chat()` like any
5
+ * other adapter: `chat()` runs the tools and the agent loop, and each
6
+ * `chatStream` call here is one step of the model, streamed as AG-UI events.
7
+ *
8
+ * Tools are the framework's own, so the model's arguments always fit their
9
+ * parameters, and it calls several at once. The framework runs a tool in the
10
+ * middle of a response; here the call is reported to `chat()` (the step ends
11
+ * with `tool_calls`) while the native response waits, and the next step hands
12
+ * it the results: the response goes on where it was, without the session
13
+ * reading the conversation again.
14
+ *
15
+ * Each thread (`threadId`) keeps a session: a step prompts it with only the
16
+ * new message. A conversation that changed (an edit, other tools, a new
17
+ * system prompt) starts a new session from the messages.
18
+ */
19
+ import { buildBaseUsage, EventType, normalizeSystemPrompts } from "@tanstack/ai";
20
+ import { BaseTextAdapter } from "@tanstack/ai/adapters";
21
+ import { contentText, toNativeMessages } from "./messages.js";
22
+ import { Afm } from "./native.js";
23
+ import { toNativeSchema } from "./schema.js";
24
+ import { parseJsonValue } from "./json-value.js";
25
+ import { schemaErrors } from "./validate.js";
26
+ /** Events of one native response, as they come. */
27
+ class EventQueue {
28
+ events = [];
29
+ wake;
30
+ push(event) {
31
+ this.events.push(event);
32
+ this.wake?.();
33
+ this.wake = undefined;
34
+ }
35
+ async next(signal) {
36
+ // Stopped: not even an event already here (a buffered done) goes out.
37
+ signal?.throwIfAborted();
38
+ while (this.events.length === 0) {
39
+ signal?.throwIfAborted();
40
+ await new Promise((resolve, reject) => {
41
+ const abort = () => reject(signal?.reason ?? new DOMException("Aborted", "AbortError"));
42
+ this.wake = () => {
43
+ signal?.removeEventListener("abort", abort);
44
+ resolve();
45
+ };
46
+ signal?.addEventListener("abort", abort, { once: true });
47
+ });
48
+ }
49
+ return this.events.shift();
50
+ }
51
+ }
52
+ const KEPT_SESSIONS = 4;
53
+ /** A message, as the session holds it: an assistant's text and its tool calls (ids, names, arguments). */
54
+ const messageKey = (m) => m.role === "assistant"
55
+ ? JSON.stringify([
56
+ "assistant",
57
+ contentText(m.content).trim(),
58
+ (m.toolCalls ?? []).map((call) => [call.id, call.function.name, call.function.arguments])
59
+ ])
60
+ : JSON.stringify([m.role, contentText(m.content), m.toolCallId ?? null]);
61
+ function offeredTools(options) {
62
+ const { toolChoice, tools = [] } = options;
63
+ if (toolChoice === "none")
64
+ return [];
65
+ if (typeof toolChoice === "object")
66
+ return tools.filter((tool) => tool.name === toolChoice.name);
67
+ return tools;
68
+ }
69
+ /**
70
+ * When to call tools, added to the instructions of a session that has some.
71
+ * Given tools and no word on when to use them, Apple's model on an iPhone
72
+ * (iOS 27.2) calls one for every prompt, "Hi" and "What is 2 + 2?" included;
73
+ * on a Mac it doesn't. With this, the iPhone's answered greetings, small talk,
74
+ * math, explanations and writing itself, and called the weather, location and
75
+ * web search tools for the weather, "here", current facts and the news. Told
76
+ * only to answer such requests "directly", it refused to write poems ("I
77
+ * cannot write a haiku"); naming poems, stories and emails as its own work
78
+ * keeps it writing.
79
+ */
80
+ const TOOL_USE = "Most requests need no tool: greetings and small talk, math, writing (poems, stories, emails), explanations and general knowledge. Answer those yourself, without calling a tool. Call a tool only for what you can't do yourself: information that changes or that you don't have, or something only a tool can do.";
81
+ /** The framework's tool-calling mode for a step: "required" when a tool must be called ("required", or the one tool named). */
82
+ const toolCallingModeOf = (options) => options.toolChoice === "required" || typeof options.toolChoice === "object" ? "required" : undefined;
83
+ /** The system prompts, and when to call tools if the session has some. */
84
+ const instructionsOf = (options, tools) => [...normalizeSystemPrompts(options.systemPrompts).map((p) => p.content), ...(tools.length > 0 ? [TOOL_USE] : [])]
85
+ .filter(Boolean)
86
+ .join("\n\n");
87
+ const AVAILABILITY = {
88
+ deviceNotEligible: "unavailable",
89
+ appleIntelligenceNotEnabled: "unavailable",
90
+ unsupportedOS: "unavailable",
91
+ unavailable: "unavailable",
92
+ // Apple Intelligence is on, and its model is still downloading.
93
+ modelNotReady: "downloading"
94
+ };
95
+ const usageOf = (usage) => usage && {
96
+ ...buildBaseUsage({
97
+ promptTokens: usage.inputTokens,
98
+ completionTokens: usage.outputTokens,
99
+ totalTokens: usage.inputTokens + usage.outputTokens
100
+ }),
101
+ // 0 too: nothing was cached. Left out where the framework can't say.
102
+ ...(usage.cachedTokens !== undefined && { promptTokensDetails: { cachedTokens: usage.cachedTokens } })
103
+ };
104
+ let ids = 0;
105
+ const nextId = (prefix) => `${prefix}_${Date.now().toString(36)}_${(ids++).toString(36)}`;
106
+ const signalOf = (options) => options.abortController?.signal ?? options.request?.signal ?? undefined;
107
+ /**
108
+ * A structured answer the model wrote as text (permissive guardrails' fallback,
109
+ * which the framework didn't hold to the schema): its JSON value, if it fits the
110
+ * schema. chat() validates only schemas with a Standard Schema validator, not
111
+ * plain JSON Schema, so the adapter checks it here.
112
+ */
113
+ function checkedAnswer(text, schema) {
114
+ let data;
115
+ try {
116
+ data = parseJsonValue(text);
117
+ }
118
+ catch (error) {
119
+ throw Object.assign(new Error(`Apple's model wrote no JSON for the schema (its answer, written as text past its guardrails, was ${JSON.stringify(text.slice(0, 120))})`, { cause: error }), { code: "invalidJson" });
120
+ }
121
+ const problems = schemaErrors(schema, data);
122
+ if (problems.length > 0) {
123
+ throw Object.assign(new Error(`Apple's model's answer, written as text past its guardrails, doesn't fit the schema: ${problems.slice(0, 5).join("; ")}`), { code: "schemaMismatch" });
124
+ }
125
+ return data;
126
+ }
127
+ const parse = (json) => {
128
+ try {
129
+ return JSON.parse(json);
130
+ }
131
+ catch {
132
+ return {};
133
+ }
134
+ };
135
+ export class AfmTextAdapter extends BaseTextAdapter {
136
+ kind = "text";
137
+ name = "afm";
138
+ provider = "afm";
139
+ api = "afm";
140
+ inputModalities = ["text"];
141
+ native;
142
+ threads = new Map();
143
+ queues = new Map();
144
+ /**
145
+ * Responses waiting for tool results in sessions no thread keeps (prompt
146
+ * cache retention "none"), by thread: the next step resumes them.
147
+ */
148
+ paused = new Map();
149
+ listening;
150
+ constructor(config, model) {
151
+ super({}, model);
152
+ this.native = config.native ?? globalThis.afm ?? Afm;
153
+ this.guardrails = config.guardrails;
154
+ }
155
+ guardrails;
156
+ /** A request's guardrails: its own, else the adapter's (left out: the host's, else Apple's default). */
157
+ guardrailsOf(options) {
158
+ return options.modelOptions?.guardrails ?? this.guardrails;
159
+ }
160
+ /** Whether Apple's model can run here: "downloading" while Apple Intelligence gets it. */
161
+ async availability() {
162
+ try {
163
+ const answer = await this.native.availability(this.guardrails ? { guardrails: this.guardrails } : undefined);
164
+ return answer.available ? "available" : AVAILABILITY[answer.reason ?? "unavailable"];
165
+ }
166
+ catch {
167
+ return "unavailable";
168
+ }
169
+ }
170
+ /** Tokens a session holds, where the OS says (26.4 and later). */
171
+ async contextSize() {
172
+ try {
173
+ return (await this.native.availability(this.guardrails ? { guardrails: this.guardrails } : undefined)).contextSize;
174
+ }
175
+ catch {
176
+ return undefined;
177
+ }
178
+ }
179
+ /** Resolves to this adapter if the model can run here, else rejects. */
180
+ async create(options = {}) {
181
+ options.signal?.throwIfAborted();
182
+ const answer = await this.native.availability();
183
+ options.signal?.throwIfAborted();
184
+ if (!answer.available)
185
+ throw new Error(`Apple's on-device model is unavailable here (${answer.reason ?? "unavailable"})`);
186
+ return this;
187
+ }
188
+ /**
189
+ * Ends every session: the threads', responses waiting for tool results, and
190
+ * responses streaming now (structured output's, and those of sessions no
191
+ * thread keeps), each once.
192
+ */
193
+ async destroy() {
194
+ const all = new Set([...this.threads.values(), ...this.paused.values(), ...this.queues.values()]);
195
+ for (const thread of all)
196
+ this.close(thread);
197
+ this.threads.clear();
198
+ this.paused.clear();
199
+ }
200
+ /** Routes the native events to their thread's response. Listens once. */
201
+ listen() {
202
+ this.listening ??= this.native.addListener("event", (event) => {
203
+ const thread = this.queues.get(event.sessionId);
204
+ if (thread && event.turn === thread.turn)
205
+ thread.queue?.push(event);
206
+ });
207
+ return this.listening;
208
+ }
209
+ /** Ends a session. A response still streaming from it ends with an error. */
210
+ close(thread) {
211
+ this.queues.delete(thread.sessionId);
212
+ thread.queue?.push({ type: "error", code: "closed", message: "The session was closed", sessionId: thread.sessionId, turn: thread.turn });
213
+ thread.queue = undefined;
214
+ void this.native.deleteSession({ sessionId: thread.sessionId }).catch(() => undefined);
215
+ }
216
+ /** Keeps a thread's session, ending the least recently used past the limit. */
217
+ keep(key, thread) {
218
+ this.threads.delete(key);
219
+ this.threads.set(key, thread);
220
+ for (const [id, old] of this.threads) {
221
+ if (this.threads.size <= KEPT_SESSIONS)
222
+ break;
223
+ if (old.busy)
224
+ continue;
225
+ this.close(old);
226
+ this.threads.delete(id);
227
+ }
228
+ }
229
+ /** A new native session for a thread, holding `messages`. */
230
+ async open(options, tools, settings, messages) {
231
+ const thread = {
232
+ sessionId: nextId("session"),
233
+ settings,
234
+ seen: [],
235
+ turn: 0,
236
+ queue: undefined,
237
+ written: "",
238
+ waiting: new Set(),
239
+ busy: true
240
+ };
241
+ const instructions = instructionsOf(options, tools);
242
+ await this.native.createSession({
243
+ sessionId: thread.sessionId,
244
+ ...(instructions && { instructions }),
245
+ tools: tools.map((tool) => ({
246
+ name: tool.name,
247
+ description: tool.description ?? "",
248
+ parameters: toNativeSchema(tool.inputSchema ?? { type: "object", properties: {} }, tool.name)
249
+ })),
250
+ messages,
251
+ ...(this.guardrailsOf(options) && { guardrails: this.guardrailsOf(options) })
252
+ });
253
+ return thread;
254
+ }
255
+ /**
256
+ * The step's thread, and what it sends: the results of the tool calls its
257
+ * response waits on, a new prompt to its session, or (for a conversation the
258
+ * session doesn't hold) a new session and the last message as its prompt.
259
+ */
260
+ async begin(options) {
261
+ await this.listen();
262
+ const key = options.promptCache?.key ?? options.threadId;
263
+ const retain = options.promptCache?.retention !== "none";
264
+ const tools = offeredTools(options);
265
+ const { temperature, maximumResponseTokens } = options.modelOptions ?? {};
266
+ const settings = JSON.stringify([
267
+ instructionsOf(options, tools),
268
+ tools.map((tool) => [tool.name, tool.description, tool.inputSchema]),
269
+ temperature,
270
+ maximumResponseTokens,
271
+ // A response keeps the mode it started with: a step with another mode
272
+ // (required, then auto) can't resume it, and starts a new session.
273
+ toolCallingModeOf(options),
274
+ // A session's guardrails are its model's: other guardrails, another session.
275
+ // None named isn't "default": the host's (serveAfm's) may be permissive.
276
+ this.guardrailsOf(options) ?? "inherited"
277
+ ]);
278
+ const keys = options.messages.map(messageKey);
279
+ // A kept session, or one whose response waits for tool results.
280
+ const held = (retain ? this.threads.get(key) : undefined) ?? this.paused.get(key);
281
+ const holds = !!held && !held.busy && held.settings === settings && held.seen.every((k, i) => k === keys[i]);
282
+ // The results of the tool calls the session's response waits on.
283
+ if (holds && held.queue && held.waiting.size > 0) {
284
+ const results = options.messages
285
+ .slice(held.seen.length)
286
+ .filter((m) => m.role === "tool" && !!m.toolCallId && held.waiting.has(m.toolCallId));
287
+ if (results.length === held.waiting.size) {
288
+ held.busy = true;
289
+ this.paused.delete(key);
290
+ return { key, thread: held, kept: this.threads.get(key) === held, keys, results };
291
+ }
292
+ }
293
+ // A new message to the session's finished response.
294
+ const last = options.messages.at(-1);
295
+ if (holds && !held.queue && keys.length === held.seen.length + 1 && last?.role === "user") {
296
+ held.busy = true;
297
+ return { key, thread: held, kept: true, keys, prompt: contentText(last.content) };
298
+ }
299
+ // A new session for the conversation, prompted with its last message.
300
+ if (held && !held.busy) {
301
+ this.close(held);
302
+ if (this.threads.get(key) === held)
303
+ this.threads.delete(key);
304
+ if (this.paused.get(key) === held)
305
+ this.paused.delete(key);
306
+ }
307
+ const prompted = last?.role === "user";
308
+ const before = prompted ? options.messages.slice(0, -1) : options.messages;
309
+ const thread = await this.open(options, tools, settings, toNativeMessages(before));
310
+ const kept = retain && !this.threads.get(key)?.busy;
311
+ if (kept)
312
+ this.keep(key, thread);
313
+ return { key, thread, kept, keys, prompt: prompted ? contentText(last.content) : "" };
314
+ }
315
+ async *chatStream(options) {
316
+ const runId = options.runId ?? nextId("run");
317
+ const { threadId } = options;
318
+ const messageId = nextId("msg");
319
+ const model = this.model;
320
+ const signal = signalOf(options);
321
+ const timestamp = () => Date.now();
322
+ yield {
323
+ type: EventType.RUN_STARTED,
324
+ runId,
325
+ threadId,
326
+ model,
327
+ timestamp: timestamp(),
328
+ ...(options.parentRunId && { parentRunId: options.parentRunId })
329
+ };
330
+ let step;
331
+ let paused = false;
332
+ try {
333
+ // A stopped request starts no native work (and one stopped meanwhile ends here).
334
+ signal?.throwIfAborted();
335
+ step = await this.begin(options);
336
+ signal?.throwIfAborted();
337
+ const { thread, keys } = step;
338
+ if (step.results) {
339
+ for (const result of step.results) {
340
+ const callId = result.toolCallId;
341
+ thread.waiting.delete(callId);
342
+ await this.native.submitToolResult({ sessionId: thread.sessionId, callId, output: contentText(result.content) });
343
+ }
344
+ }
345
+ else {
346
+ const { temperature, maximumResponseTokens } = options.modelOptions ?? {};
347
+ thread.turn += 1;
348
+ thread.written = "";
349
+ thread.queue = new EventQueue();
350
+ this.queues.set(thread.sessionId, thread);
351
+ await this.native.respond({
352
+ sessionId: thread.sessionId,
353
+ turn: thread.turn,
354
+ prompt: step.prompt ?? "",
355
+ options: {
356
+ ...(temperature !== undefined && { temperature }),
357
+ ...(maximumResponseTokens !== undefined && { maximumResponseTokens }),
358
+ ...(toolCallingModeOf(options) && { toolCallingMode: toolCallingModeOf(options) })
359
+ }
360
+ });
361
+ }
362
+ // This step's text (its assistant message), and the events that write it.
363
+ let text = "";
364
+ const textEvents = function* (delta) {
365
+ if (!delta)
366
+ return;
367
+ if (!text)
368
+ yield { type: EventType.TEXT_MESSAGE_START, messageId, role: "assistant", model, timestamp: timestamp() };
369
+ text += delta;
370
+ thread.written += delta;
371
+ yield { type: EventType.TEXT_MESSAGE_CONTENT, messageId, delta, content: text, model, timestamp: timestamp() };
372
+ };
373
+ const endText = function* () {
374
+ if (text)
375
+ yield { type: EventType.TEXT_MESSAGE_END, messageId, model, timestamp: timestamp() };
376
+ };
377
+ const queue = thread.queue;
378
+ for (;;) {
379
+ const event = await queue.next(signal);
380
+ if (event.type === "delta") {
381
+ yield* textEvents(event.text);
382
+ }
383
+ else if (event.type === "toolCalls") {
384
+ yield* endText();
385
+ for (const [index, call] of event.calls.entries()) {
386
+ thread.waiting.add(call.id);
387
+ yield {
388
+ type: EventType.TOOL_CALL_START,
389
+ toolCallId: call.id,
390
+ toolCallName: call.name,
391
+ parentMessageId: messageId,
392
+ index,
393
+ model,
394
+ timestamp: timestamp()
395
+ };
396
+ yield { type: EventType.TOOL_CALL_ARGS, toolCallId: call.id, delta: call.arguments, args: call.arguments, model, timestamp: timestamp() };
397
+ yield {
398
+ type: EventType.TOOL_CALL_END,
399
+ toolCallId: call.id,
400
+ toolCallName: call.name,
401
+ args: call.arguments,
402
+ input: parse(call.arguments),
403
+ model,
404
+ timestamp: timestamp()
405
+ };
406
+ }
407
+ // The response waits for the results, which the next step sends.
408
+ thread.seen = keys;
409
+ paused = true;
410
+ // A session no thread keeps is still found by the step with the results.
411
+ if (!step.kept)
412
+ this.paused.set(step.key, thread);
413
+ yield { type: EventType.RUN_FINISHED, runId, threadId, model, timestamp: timestamp(), finishReason: "tool_calls" };
414
+ return;
415
+ }
416
+ else if (event.type === "done") {
417
+ // Any of the response not sent as deltas.
418
+ if (event.text.startsWith(thread.written))
419
+ yield* textEvents(event.text.slice(thread.written.length));
420
+ yield* endText();
421
+ thread.queue = undefined;
422
+ this.queues.delete(thread.sessionId);
423
+ thread.seen = [...keys, messageKey({ role: "assistant", content: text })];
424
+ const usage = usageOf(event.usage);
425
+ yield {
426
+ type: EventType.RUN_FINISHED,
427
+ runId,
428
+ threadId,
429
+ model,
430
+ timestamp: timestamp(),
431
+ finishReason: "stop",
432
+ ...(usage && { usage })
433
+ };
434
+ return;
435
+ }
436
+ else {
437
+ throw Object.assign(new Error(event.message), { code: event.code });
438
+ }
439
+ }
440
+ }
441
+ catch (error) {
442
+ const aborted = !!signal?.aborted;
443
+ if (step) {
444
+ if (aborted)
445
+ void this.native.cancel({ sessionId: step.thread.sessionId }).catch(() => undefined);
446
+ // A stopped or failed response leaves the session behind: the next step starts a new one.
447
+ this.close(step.thread);
448
+ if (this.threads.get(step.key) === step.thread)
449
+ this.threads.delete(step.key);
450
+ if (this.paused.get(step.key) === step.thread)
451
+ this.paused.delete(step.key);
452
+ }
453
+ options.logger.errors("afm chatStream failed", { error, source: "afm.chatStream" });
454
+ const message = error instanceof Error ? error.message : String(error);
455
+ const code = aborted ? "aborted" : error?.code;
456
+ yield {
457
+ type: EventType.RUN_ERROR,
458
+ runId,
459
+ model,
460
+ timestamp: timestamp(),
461
+ message,
462
+ error: { message, ...(typeof code === "string" && { code }) }
463
+ };
464
+ }
465
+ finally {
466
+ if (step) {
467
+ step.thread.busy = false;
468
+ // A session no thread keeps ends with its step, unless its response waits for tools.
469
+ if (!step.kept && !paused)
470
+ this.close(step.thread);
471
+ }
472
+ }
473
+ }
474
+ /**
475
+ * A JSON answer for `chat({ outputSchema })`: a session holding the
476
+ * conversation answers its last message, held to the schema by the
477
+ * framework. `chat()` validates the result.
478
+ */
479
+ async structuredOutput(options) {
480
+ const { chatOptions, outputSchema } = options;
481
+ const signal = signalOf(chatOptions);
482
+ signal?.throwIfAborted();
483
+ await this.listen();
484
+ const last = chatOptions.messages.at(-1);
485
+ const prompted = last?.role === "user";
486
+ const before = prompted ? chatOptions.messages.slice(0, -1) : chatOptions.messages;
487
+ const thread = await this.open(chatOptions, [], "", toNativeMessages(before));
488
+ try {
489
+ thread.turn = 1;
490
+ thread.queue = new EventQueue();
491
+ this.queues.set(thread.sessionId, thread);
492
+ const { temperature, maximumResponseTokens } = chatOptions.modelOptions ?? {};
493
+ await this.native.respond({
494
+ sessionId: thread.sessionId,
495
+ turn: 1,
496
+ prompt: prompted ? contentText(last.content) : "",
497
+ schema: toNativeSchema(outputSchema, "Answer"),
498
+ options: {
499
+ ...(temperature !== undefined && { temperature }),
500
+ ...(maximumResponseTokens !== undefined && { maximumResponseTokens })
501
+ }
502
+ });
503
+ for (;;) {
504
+ const event = await thread.queue.next(signal);
505
+ if (event.type === "done") {
506
+ const usage = usageOf(event.usage);
507
+ return { data: event.asText ? checkedAnswer(event.text, outputSchema) : JSON.parse(event.text), rawText: event.text, model: this.model, ...(usage && { usage }) };
508
+ }
509
+ if (event.type === "error")
510
+ throw Object.assign(new Error(event.message), { code: event.code });
511
+ }
512
+ }
513
+ finally {
514
+ this.close(thread);
515
+ }
516
+ }
517
+ }
518
+ export function afmText(modelOrConfig, config = {}) {
519
+ return typeof modelOrConfig === "string"
520
+ ? new AfmTextAdapter(config, modelOrConfig)
521
+ : new AfmTextAdapter(modelOrConfig ?? {}, "system");
522
+ }
@@ -0,0 +1,29 @@
1
+ import type { AfmGuardrails } from "./native.js";
2
+ export type ServeAfmOptions = {
3
+ /**
4
+ * The folder with the package's Electron files (afm.node and preload.cjs):
5
+ * by default the package's own `electron` folder, found from the app's
6
+ * node_modules. An app that leaves node_modules out of its package copies
7
+ * the two files in and passes their folder. Inside an asar archive, the
8
+ * unpacked afm.node beside it is loaded (native code can't load from an archive).
9
+ */
10
+ directory?: string;
11
+ /**
12
+ * Which pages may use the model, by URL. By default the app's own: any page
13
+ * but an http(s) one on another host than localhost.
14
+ */
15
+ allow?: (url: string) => boolean;
16
+ /**
17
+ * Apple's guardrails for every page's sessions that don't name their own
18
+ * (`afmText({ guardrails })` or a request's `modelOptions.guardrails`):
19
+ * "default" (the default), or "permissiveContentTransformations".
20
+ */
21
+ guardrails?: AfmGuardrails;
22
+ };
23
+ /**
24
+ * Runs Apple's on-device model for the app's pages, where `afmText()` finds it.
25
+ * Call it once in the main process, before opening windows. On a Mac before
26
+ * macOS 26, or elsewhere, the pages hear the model is unavailable.
27
+ */
28
+ export declare function serveAfm(options?: ServeAfmOptions): void;
29
+ //# sourceMappingURL=electron.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"electron.d.ts","sourceRoot":"","sources":["../src/electron.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AA8BhD,MAAM,MAAM,eAAe,GAAG;IAC5B;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB;;;OAGG;IACH,KAAK,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAA;IAChC;;;;OAIG;IACH,UAAU,CAAC,EAAE,aAAa,CAAA;CAC3B,CAAA;AAgBD;;;;GAIG;AACH,wBAAgB,QAAQ,CAAC,OAAO,GAAE,eAAoB,GAAG,IAAI,CAwG5D"}