@orkestrel/ollama 0.0.2 → 0.0.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orkestrel/ollama",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
4
4
  "description": "A typed local-LLM provider for the @orkestrel line — a ProviderInterface over a local Ollama daemon's /api/chat with NDJSON streaming and guard-narrowed wire boundaries. Part of the @orkestrel line.",
5
5
  "keywords": [
6
6
  "ai",
@@ -63,7 +63,7 @@
63
63
  "prepublishOnly": "npm run format:check && npm run lint:check && npm run check && npm run check:src && npm run build"
64
64
  },
65
65
  "dependencies": {
66
- "@orkestrel/agent": "^0.0.4",
66
+ "@orkestrel/agent": "^0.0.6",
67
67
  "@orkestrel/budget": "^0.0.1",
68
68
  "@orkestrel/contract": "^0.0.1",
69
69
  "@orkestrel/ndjson": "^0.0.1",
@@ -1,459 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- let _orkestrel_agent = require("@orkestrel/agent");
3
- let _orkestrel_contract = require("@orkestrel/contract");
4
- let _orkestrel_ndjson = require("@orkestrel/ndjson");
5
- let _orkestrel_timeout = require("@orkestrel/timeout");
6
- //#region src/server/constants.ts
7
- /** The local Ollama daemon base URL assumed when `OllamaOptions.url` is omitted. */
8
- var DEFAULT_OLLAMA_URL = "http://localhost:11434";
9
- /**
10
- * How long the model stays resident after a call when `OllamaOptions.keepAlive` is
11
- * omitted — Ollama's own `keep_alive` default, expressed as a duration string.
12
- */
13
- var DEFAULT_KEEP_ALIVE = "5m";
14
- /**
15
- * The per-call deadline in milliseconds when `OllamaOptions.timeout` is omitted —
16
- * generous enough that a cold model load does not trip it.
17
- */
18
- var DEFAULT_PROVIDER_TIMEOUT = 12e4;
19
- /**
20
- * The cap, in characters, on how much of a non-OK response body is
21
- * incorporated into a thrown {@link OllamaHTTPError}'s message.
22
- *
23
- * @remarks
24
- * Bounds the excerpt so a defensive proxy or a misbehaving daemon handing
25
- * back an unbounded response body cannot inflate the thrown error's message
26
- * without limit (§14). `2048` characters is generous enough to carry a
27
- * useful diagnostic snippet while staying well short of any practical size
28
- * concern.
29
- */
30
- var MAX_ERROR_BODY_LENGTH = 2048;
31
- //#endregion
32
- //#region src/server/errors.ts
33
- /**
34
- * An error thrown when the Ollama `/api/chat` HTTP transport fails.
35
- *
36
- * @remarks
37
- * Carries the response `status` (0 when no HTTP response was received at all,
38
- * e.g. a `null` body). Thrown by {@link OllamaProvider} at its two HTTP
39
- * failure sites — the non-OK status branch and the null-body branch — so a
40
- * caller can branch on `error.status` instead of parsing the message. Narrow
41
- * a caught value with {@link isOllamaHTTPError}.
42
- *
43
- * @example
44
- * ```ts
45
- * try {
46
- * await provider.generate(messages, signal)
47
- * } catch (error) {
48
- * if (isOllamaHTTPError(error) && error.status === 404) {
49
- * // the configured model isn't pulled
50
- * }
51
- * }
52
- * ```
53
- */
54
- var OllamaHTTPError = class extends Error {
55
- status;
56
- constructor(message, status, options) {
57
- super(message, options);
58
- this.name = "OllamaHTTPError";
59
- this.status = status;
60
- }
61
- };
62
- /**
63
- * Whether a value is an {@link OllamaHTTPError}.
64
- *
65
- * @param value - The value to test
66
- * @returns `true` when `value` is an `OllamaHTTPError`
67
- */
68
- function isOllamaHTTPError(value) {
69
- return value instanceof OllamaHTTPError;
70
- }
71
- //#endregion
72
- //#region src/server/OllamaProvider.ts
73
- /**
74
- * The local Ollama inference boundary — a {@link ProviderInterface} over Ollama's
75
- * `POST /api/chat`, both non-streaming (`generate`) and streaming NDJSON (`stream`).
76
- *
77
- * @remarks
78
- * - **Wire protocol.** Posts `{ model, messages, stream, keep_alive, think }` plus
79
- * passthrough sampling `options` and mapped function `tools`. The `think` flag is
80
- * CONFIGURABLE via {@link OllamaOptions.think} (default `false`). Non-stream parses
81
- * one JSON body; stream consumes NDJSON (one JSON object per `\n`-terminated line) —
82
- * deltas carry `message.content`, the final `done: true` line carries the token usage.
83
- * - **Think separation (H4).** The wire `think` flag is configurable
84
- * ({@link OllamaOptions.think}, default `false`). With `think: true` a thinking model's
85
- * daemon separates reasoning NATIVELY — returning it on the distinct `message.thinking`
86
- * channel (read here via `#thinking`) instead of inline in `message.content`. EITHER
87
- * way the per-call {@link ThinkSplitterInterface} is the defensive guarantee: a daemon
88
- * may ignore `think: false` for a thinking model and inline `<think>` tags, so every
89
- * content delta routes through the splitter, only CLEAN content is yielded / assembled,
90
- * and the separated reasoning (plus any daemon-side `message.thinking` deltas) lands on
91
- * `ProviderResult.thinking`, never in the conversation.
92
- * - **Boundary narrowing (§14).** Every wire value arrives as `unknown` and is
93
- * narrowed through guards (`isRecord` / `isString` / `isNumber`) — never `as`. A
94
- * missing / malformed field degrades to a sensible default (empty content, no
95
- * usage, `{}` arguments), never a throw.
96
- * - **Bounded.** Each call arms a {@link Timeout} for `OllamaOptions.timeout` and
97
- * passes `AbortSignal.any([timeout.signal, signal])` to `fetch`, so the caller's
98
- * signal AND the deadline both cancel the request. The timeout is always cleared —
99
- * in `#fetch` if the request fails/aborts, otherwise in the consuming call's `finally`.
100
- * - **Abort recovers partial.** A `stream` cancelled mid-flight throws a
101
- * `ProviderAbortError` carrying the partial result assembled so far; pairing the
102
- * `TextDecoder({ stream: true })` with the {@link NDJSONParser} parser keeps multi-byte
103
- * UTF-8 splits and partial lines honest.
104
- * - **Event-free.** A pure functional boundary — no Emitter, no events.
105
- * - **Transport seam.** {@link OllamaOptions.fetch} swaps the transport (default
106
- * `globalThis.fetch`) and {@link OllamaOptions.headers} is a per-request, possibly
107
- * async header injector merged over the base `Content-Type` — so a browser runtime
108
- * can route through the developer's own server with an obfuscated bearer token,
109
- * without this library ever handling a real API key. Both omitted ⇒ today's behaviour.
110
- * Orthogonal to the deadline: the hook is awaited inside `#fetch`'s try, so a hook
111
- * rejection clears the armed timer like any other request failure.
112
- *
113
- * @example
114
- * ```ts
115
- * const provider = new OllamaProvider({ model: 'qwen3.5:2b-q4_K_M' })
116
- * const result = await provider.generate(messages, abort.signal)
117
- * ```
118
- */
119
- var OllamaProvider = class {
120
- id = crypto.randomUUID();
121
- name = "ollama";
122
- #model;
123
- #url;
124
- #keepAlive;
125
- #timeout;
126
- #think;
127
- #options;
128
- #transport;
129
- #headers;
130
- #format;
131
- constructor(options) {
132
- this.#model = options.model;
133
- this.#url = options.url ?? "http://localhost:11434";
134
- this.#keepAlive = options.keepAlive ?? "5m";
135
- this.#timeout = options.timeout ?? 12e4;
136
- this.#think = options.think ?? false;
137
- this.#options = options.options;
138
- this.#transport = options.fetch ?? globalThis.fetch.bind(globalThis);
139
- this.#headers = options.headers;
140
- this.#format = options.format;
141
- }
142
- /**
143
- * The provider's context-framing default — the PROVIDER-DEFAULT level of
144
- * {@link import('@orkestrel/agent').AgentContextInterface.build}'s format cascade (it BEATS
145
- * the managers' built-in framing, is BEATEN by a manager-options or per-item override).
146
- * Satisfies the OPTIONAL {@link ProviderInterface.format} contract member: `undefined`
147
- * when {@link OllamaOptions.format} was omitted (the framing-agnostic default ⇒ core's
148
- * built-in framing applies unchanged), else the exact configured framing the Agent
149
- * threads into `build()`.
150
- *
151
- * @remarks
152
- * EXPOSE-ONLY — read by the Agent loop and consumed by core's cascade; it is NEVER sent
153
- * on the `/api/chat` wire (it is absent from `#body` / the request). This is NOT Ollama's
154
- * structured-output `format` wire parameter, which this provider does not send; only the
155
- * word collides.
156
- *
157
- * @returns The configured {@link ContextFormatInterface}, or `undefined` when none
158
- */
159
- get format() {
160
- return this.#format;
161
- }
162
- async generate(messages, signal, tools, options) {
163
- const { response, timeout } = await this.#fetch(messages, false, signal, tools, options);
164
- try {
165
- const record = await this.#parseBody(response);
166
- const splitter = (0, _orkestrel_agent.createThinkSplitter)();
167
- splitter.split(this.#content(record));
168
- splitter.flush();
169
- const thinking = this.#thought(splitter, this.#thinking(record));
170
- return this.#result(splitter.content, thinking, this.#tools(record), this.#usage(record));
171
- } finally {
172
- timeout.clear();
173
- }
174
- }
175
- async *stream(messages, signal, tools, options) {
176
- const { response, timeout, combined } = await this.#fetch(messages, true, signal, tools, options);
177
- const body = response.body;
178
- if (body === null) {
179
- timeout.clear();
180
- throw new OllamaHTTPError("Ollama API error: no response body", 0);
181
- }
182
- const reader = body.getReader();
183
- const decoder = new TextDecoder();
184
- const parser = (0, _orkestrel_ndjson.createNDJSONParser)();
185
- const splitter = (0, _orkestrel_agent.createThinkSplitter)();
186
- let wired = "";
187
- const calls = [];
188
- let usage;
189
- const contentOf = (record) => this.#content(record);
190
- const thinkingOf = (record) => this.#thinking(record);
191
- const toolsOf = (record) => this.#tools(record);
192
- const usageOf = (record) => this.#usage(record);
193
- function* handle(record) {
194
- const delta = splitter.split(contentOf(record));
195
- if (delta.length > 0) yield {
196
- type: "content",
197
- text: delta
198
- };
199
- const thinking = thinkingOf(record);
200
- if (thinking.length > 0) yield {
201
- type: "thinking",
202
- text: thinking
203
- };
204
- wired += thinking;
205
- calls.push(...toolsOf(record));
206
- if (Reflect.get(record, "done") === true) usage = usageOf(record);
207
- }
208
- try {
209
- for (;;) {
210
- const { value, done } = await reader.read();
211
- if (done) break;
212
- for (const record of parser.parse(decoder.decode(value, { stream: true }))) yield* handle(record);
213
- }
214
- const decoderTail = decoder.decode();
215
- for (const record of parser.parse(decoderTail.length > 0 ? `${decoderTail}\n` : "\n")) yield* handle(record);
216
- const tail = splitter.flush();
217
- if (tail.length > 0) yield {
218
- type: "content",
219
- text: tail
220
- };
221
- } catch (error) {
222
- if (combined.aborted) {
223
- splitter.flush();
224
- throw new _orkestrel_agent.ProviderAbortError(this.#result(splitter.content, this.#thought(splitter, wired), calls, usage));
225
- }
226
- throw error;
227
- } finally {
228
- try {
229
- await reader.cancel();
230
- } catch {}
231
- parser.reset();
232
- timeout.clear();
233
- }
234
- return this.#result(splitter.content, this.#thought(splitter, wired), calls, usage);
235
- }
236
- async #fetch(messages, stream, signal, tools, options) {
237
- const timeout = new _orkestrel_timeout.Timeout({ ms: this.#timeout });
238
- timeout.start();
239
- const combined = AbortSignal.any([timeout.signal, signal]);
240
- try {
241
- const response = await this.#transport(`${this.#url}/api/chat`, {
242
- method: "POST",
243
- headers: await this.#requestHeaders(),
244
- body: JSON.stringify(this.#body(messages, stream, tools, options)),
245
- signal: combined
246
- });
247
- if (!response.ok) {
248
- let detail;
249
- try {
250
- const text = await response.text();
251
- detail = text.length > 2048 ? text.slice(0, MAX_ERROR_BODY_LENGTH) : text;
252
- } catch (cause) {
253
- throw new OllamaHTTPError(`Ollama API error: ${response.status} - (error body unavailable)`, response.status, { cause });
254
- }
255
- throw new OllamaHTTPError(`Ollama API error: ${response.status} - ${detail}`, response.status);
256
- }
257
- return {
258
- response,
259
- timeout,
260
- combined
261
- };
262
- } catch (error) {
263
- timeout.clear();
264
- throw error;
265
- }
266
- }
267
- async #parseBody(response) {
268
- const text = await response.text();
269
- if (text.length === 0) return {};
270
- try {
271
- const data = JSON.parse(text);
272
- return (0, _orkestrel_contract.isRecord)(data) ? data : {};
273
- } catch {
274
- return {};
275
- }
276
- }
277
- async #requestHeaders() {
278
- const headers = { "Content-Type": "application/json" };
279
- if (this.#headers !== void 0) for (const [key, value] of Object.entries(await this.#headers())) headers[key] = value;
280
- return headers;
281
- }
282
- #body(messages, stream, tools, options) {
283
- return {
284
- model: this.#model,
285
- messages: this.#plain(messages),
286
- stream,
287
- keep_alive: this.#keepAlive,
288
- think: options?.think ?? this.#think,
289
- ...this.#options !== void 0 ? { options: this.#options } : {},
290
- ...tools !== void 0 && tools.length > 0 ? { tools: tools.map((tool) => ({
291
- type: "function",
292
- function: {
293
- name: tool.name,
294
- description: tool.description,
295
- parameters: tool.parameters
296
- }
297
- })) } : {}
298
- };
299
- }
300
- #plain(messages) {
301
- return messages.map((message) => ({
302
- role: message.role,
303
- content: message.content,
304
- ...message.calls !== void 0 && message.calls.length > 0 ? { tool_calls: message.calls.map((call) => ({ function: {
305
- name: call.name,
306
- arguments: call.arguments
307
- } })) } : {},
308
- ...message.images !== void 0 && message.images.length > 0 ? { images: [...message.images] } : {}
309
- }));
310
- }
311
- #result(content, thinking, tools, usage) {
312
- const result = { content };
313
- if (thinking.length > 0) result.thinking = thinking;
314
- if (tools.length > 0) result.tools = tools;
315
- if (usage !== void 0) result.usage = usage;
316
- return result;
317
- }
318
- #content(record) {
319
- const message = Reflect.get(record, "message");
320
- if (!(0, _orkestrel_contract.isRecord)(message)) return "";
321
- const content = Reflect.get(message, "content");
322
- return (0, _orkestrel_contract.isString)(content) ? content : "";
323
- }
324
- #thinking(record) {
325
- const message = Reflect.get(record, "message");
326
- if (!(0, _orkestrel_contract.isRecord)(message)) return "";
327
- const thinking = Reflect.get(message, "thinking");
328
- return (0, _orkestrel_contract.isString)(thinking) ? thinking : "";
329
- }
330
- #thought(splitter, wired) {
331
- if (splitter.thinking.length === 0) return wired;
332
- if (wired.length === 0) return splitter.thinking;
333
- return `${splitter.thinking}\n\n${wired}`;
334
- }
335
- #usage(record) {
336
- const prompt = Reflect.get(record, "prompt_eval_count");
337
- const completion = Reflect.get(record, "eval_count");
338
- if (!(0, _orkestrel_contract.isNumber)(prompt) || !(0, _orkestrel_contract.isNumber)(completion)) return void 0;
339
- return {
340
- prompt,
341
- completion,
342
- total: prompt + completion
343
- };
344
- }
345
- #tools(record) {
346
- const message = Reflect.get(record, "message");
347
- if (!(0, _orkestrel_contract.isRecord)(message)) return [];
348
- const calls = Reflect.get(message, "tool_calls");
349
- if (!Array.isArray(calls)) return [];
350
- const out = [];
351
- for (const entry of calls) {
352
- if (!(0, _orkestrel_contract.isRecord)(entry)) continue;
353
- const callable = Reflect.get(entry, "function");
354
- if (!(0, _orkestrel_contract.isRecord)(callable)) continue;
355
- const name = Reflect.get(callable, "name");
356
- if (!(0, _orkestrel_contract.isString)(name)) continue;
357
- const id = Reflect.get(entry, "id");
358
- out.push({
359
- id: (0, _orkestrel_contract.isString)(id) ? id : crypto.randomUUID(),
360
- name,
361
- arguments: this.#arguments(Reflect.get(callable, "arguments"))
362
- });
363
- }
364
- return out;
365
- }
366
- #arguments(value) {
367
- if ((0, _orkestrel_contract.isRecord)(value)) return value;
368
- if ((0, _orkestrel_contract.isString)(value)) try {
369
- const parsed = JSON.parse(value);
370
- if ((0, _orkestrel_contract.isRecord)(parsed)) return parsed;
371
- } catch {
372
- return {};
373
- }
374
- return {};
375
- }
376
- };
377
- //#endregion
378
- //#region src/server/factories.ts
379
- /**
380
- * Create a local Ollama inference provider — a {@link ProviderInterface} over the
381
- * daemon's `POST /api/chat`, supporting non-streaming `generate` and streaming
382
- * `stream`.
383
- *
384
- * @remarks
385
- * Only `model` is required; `url` defaults to the local daemon, `keepAlive` to `'5m'`,
386
- * `timeout` to `120_000`ms, and `options` is forwarded verbatim as sampling
387
- * parameters (`temperature` / `seed` / `num_predict` / …). Both calls take an
388
- * `AbortSignal` to bound the request; a `stream` cancelled mid-flight throws a
389
- * `ProviderAbortError` carrying the partial result.
390
- *
391
- * The optional `fetch` + `headers` form a transport seam (see {@link OllamaOptions}):
392
- * point `url` at your own server, inject a custom `fetch`, and have `headers` attach a
393
- * generated/obfuscated bearer token your server validates — so a browser runtime
394
- * reaches the LLM through your middleware WITHOUT this library ever handling the real API
395
- * key. Both omitted ⇒ today's behaviour (the global `fetch`, only a JSON content type).
396
- *
397
- * The optional `format` is the provider's context-framing default — the PROVIDER-DEFAULT
398
- * level of `AgentContext`'s format cascade (see [agents.md]; beaten by a manager-options
399
- * or per-item override, beating the managers' built-in framing), declaring how this
400
- * provider's models prefer context sections framed (e.g. XML group wrappers vs. Markdown
401
- * headers). It is EXPOSED on the provider for the Agent's `build()` and is NOT Ollama's
402
- * `/api/chat` `format` wire parameter (structured output) — the two are unrelated despite
403
- * the shared word. Omitted ⇒ the provider is framing-agnostic (core's built-in defaults).
404
- *
405
- * @param options - `model` (required), and optional `url` / `keepAlive` / `timeout` /
406
- * `options` / `fetch` / `headers` / `format` (see {@link OllamaOptions})
407
- * @returns A working {@link ProviderInterface} backed by Ollama
408
- *
409
- * @example
410
- * ```ts
411
- * import { createAbort } from '@orkestrel/abort'
412
- * import { createOllama } from '@src/server'
413
- *
414
- * const provider = createOllama({ model: 'qwen3.5:2b-q4_K_M' })
415
- * const abort = createAbort()
416
- * const result = await provider.generate(messages, abort.signal)
417
- * ```
418
- *
419
- * @example
420
- * Route through your own server with an obfuscated token (deployment scenario S2):
421
- * ```ts
422
- * const provider = createOllama({
423
- * model: 'qwen3.5:2b-q4_K_M',
424
- * url: 'https://my-app.example.com/llm', // your server, not the daemon
425
- * fetch: myFetch, // optional custom transport
426
- * headers: () => ({ authorization: `Bearer ${myToken}` }), // your server validates this
427
- * })
428
- * ```
429
- *
430
- * @example
431
- * Declare a context-framing default — wrap the instructions section in an XML group (the
432
- * provider-default level of `AgentContext`'s cascade; NOT the wire `format`):
433
- * ```ts
434
- * const provider = createOllama({
435
- * model: 'qwen3.5:2b-q4_K_M',
436
- * format: {
437
- * instructions: {
438
- * open: '<instructions>',
439
- * render: (i) => `<instruction>${i.content}</instruction>`,
440
- * close: '</instructions>',
441
- * },
442
- * },
443
- * })
444
- * ```
445
- */
446
- function createOllama(options) {
447
- return new OllamaProvider(options);
448
- }
449
- //#endregion
450
- exports.DEFAULT_KEEP_ALIVE = DEFAULT_KEEP_ALIVE;
451
- exports.DEFAULT_OLLAMA_URL = DEFAULT_OLLAMA_URL;
452
- exports.DEFAULT_PROVIDER_TIMEOUT = DEFAULT_PROVIDER_TIMEOUT;
453
- exports.MAX_ERROR_BODY_LENGTH = MAX_ERROR_BODY_LENGTH;
454
- exports.OllamaHTTPError = OllamaHTTPError;
455
- exports.OllamaProvider = OllamaProvider;
456
- exports.createOllama = createOllama;
457
- exports.isOllamaHTTPError = isOllamaHTTPError;
458
-
459
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.cjs","names":["#model","#url","#keepAlive","#timeout","#think","#options","#transport","#headers","#format","#fetch","#parseBody","#content","#thought","#thinking","#result","#tools","#usage","#requestHeaders","#body","#plain","#arguments"],"sources":["../../../src/server/constants.ts","../../../src/server/errors.ts","../../../src/server/OllamaProvider.ts","../../../src/server/factories.ts"],"sourcesContent":["// Ollama constants — the provider's defaults (AGENTS §5).\n\n/** The local Ollama daemon base URL assumed when `OllamaOptions.url` is omitted. */\nexport const DEFAULT_OLLAMA_URL = 'http://localhost:11434'\n\n/**\n * How long the model stays resident after a call when `OllamaOptions.keepAlive` is\n * omitted — Ollama's own `keep_alive` default, expressed as a duration string.\n */\nexport const DEFAULT_KEEP_ALIVE = '5m'\n\n/**\n * The per-call deadline in milliseconds when `OllamaOptions.timeout` is omitted —\n * generous enough that a cold model load does not trip it.\n */\nexport const DEFAULT_PROVIDER_TIMEOUT = 120_000\n\n/**\n * The cap, in characters, on how much of a non-OK response body is\n * incorporated into a thrown {@link OllamaHTTPError}'s message.\n *\n * @remarks\n * Bounds the excerpt so a defensive proxy or a misbehaving daemon handing\n * back an unbounded response body cannot inflate the thrown error's message\n * without limit (§14). `2048` characters is generous enough to carry a\n * useful diagnostic snippet while staying well short of any practical size\n * concern.\n */\nexport const MAX_ERROR_BODY_LENGTH = 2048\n","// Errors for the Ollama provider. A single `OllamaHTTPError` carries the\n// `/api/chat` HTTP status at the boundary — non-OK responses and a missing\n// response body both throw it — so a `catch` can branch on `error.status`\n// rather than parsing a message (AGENTS §12).\n\n/**\n * An error thrown when the Ollama `/api/chat` HTTP transport fails.\n *\n * @remarks\n * Carries the response `status` (0 when no HTTP response was received at all,\n * e.g. a `null` body). Thrown by {@link OllamaProvider} at its two HTTP\n * failure sites — the non-OK status branch and the null-body branch — so a\n * caller can branch on `error.status` instead of parsing the message. Narrow\n * a caught value with {@link isOllamaHTTPError}.\n *\n * @example\n * ```ts\n * try {\n * \tawait provider.generate(messages, signal)\n * } catch (error) {\n * \tif (isOllamaHTTPError(error) && error.status === 404) {\n * \t\t// the configured model isn't pulled\n * \t}\n * }\n * ```\n */\nexport class OllamaHTTPError extends Error {\n\treadonly status: number\n\n\tconstructor(message: string, status: number, options?: { readonly cause?: unknown }) {\n\t\tsuper(message, options)\n\t\tthis.name = 'OllamaHTTPError'\n\t\tthis.status = status\n\t}\n}\n\n/**\n * Whether a value is an {@link OllamaHTTPError}.\n *\n * @param value - The value to test\n * @returns `true` when `value` is an `OllamaHTTPError`\n */\nexport function isOllamaHTTPError(value: unknown): value is OllamaHTTPError {\n\treturn value instanceof OllamaHTTPError\n}\n","import type {\n\tContextFormatInterface,\n\tMessageInterface,\n\tProviderDelta,\n\tProviderInterface,\n\tProviderResult,\n\tProviderStreamOptions,\n\tThinkSplitterInterface,\n\tToolCall,\n\tToolDefinition,\n} from '@orkestrel/agent'\nimport type { TokenUsage } from '@orkestrel/budget'\nimport type { OllamaOptions, OllamaResponse, WireChatRequest } from './types.js'\nimport { createThinkSplitter, ProviderAbortError } from '@orkestrel/agent'\nimport { isNumber, isRecord, isString } from '@orkestrel/contract'\nimport { createNDJSONParser } from '@orkestrel/ndjson'\nimport { Timeout } from '@orkestrel/timeout'\nimport {\n\tDEFAULT_KEEP_ALIVE,\n\tDEFAULT_OLLAMA_URL,\n\tDEFAULT_PROVIDER_TIMEOUT,\n\tMAX_ERROR_BODY_LENGTH,\n} from './constants.js'\nimport { OllamaHTTPError } from './errors.js'\n\n/**\n * The local Ollama inference boundary — a {@link ProviderInterface} over Ollama's\n * `POST /api/chat`, both non-streaming (`generate`) and streaming NDJSON (`stream`).\n *\n * @remarks\n * - **Wire protocol.** Posts `{ model, messages, stream, keep_alive, think }` plus\n * passthrough sampling `options` and mapped function `tools`. The `think` flag is\n * CONFIGURABLE via {@link OllamaOptions.think} (default `false`). Non-stream parses\n * one JSON body; stream consumes NDJSON (one JSON object per `\\n`-terminated line) —\n * deltas carry `message.content`, the final `done: true` line carries the token usage.\n * - **Think separation (H4).** The wire `think` flag is configurable\n * ({@link OllamaOptions.think}, default `false`). With `think: true` a thinking model's\n * daemon separates reasoning NATIVELY — returning it on the distinct `message.thinking`\n * channel (read here via `#thinking`) instead of inline in `message.content`. EITHER\n * way the per-call {@link ThinkSplitterInterface} is the defensive guarantee: a daemon\n * may ignore `think: false` for a thinking model and inline `<think>` tags, so every\n * content delta routes through the splitter, only CLEAN content is yielded / assembled,\n * and the separated reasoning (plus any daemon-side `message.thinking` deltas) lands on\n * `ProviderResult.thinking`, never in the conversation.\n * - **Boundary narrowing (§14).** Every wire value arrives as `unknown` and is\n * narrowed through guards (`isRecord` / `isString` / `isNumber`) — never `as`. A\n * missing / malformed field degrades to a sensible default (empty content, no\n * usage, `{}` arguments), never a throw.\n * - **Bounded.** Each call arms a {@link Timeout} for `OllamaOptions.timeout` and\n * passes `AbortSignal.any([timeout.signal, signal])` to `fetch`, so the caller's\n * signal AND the deadline both cancel the request. The timeout is always cleared —\n * in `#fetch` if the request fails/aborts, otherwise in the consuming call's `finally`.\n * - **Abort recovers partial.** A `stream` cancelled mid-flight throws a\n * `ProviderAbortError` carrying the partial result assembled so far; pairing the\n * `TextDecoder({ stream: true })` with the {@link NDJSONParser} parser keeps multi-byte\n * UTF-8 splits and partial lines honest.\n * - **Event-free.** A pure functional boundary — no Emitter, no events.\n * - **Transport seam.** {@link OllamaOptions.fetch} swaps the transport (default\n * `globalThis.fetch`) and {@link OllamaOptions.headers} is a per-request, possibly\n * async header injector merged over the base `Content-Type` — so a browser runtime\n * can route through the developer's own server with an obfuscated bearer token,\n * without this library ever handling a real API key. Both omitted ⇒ today's behaviour.\n * Orthogonal to the deadline: the hook is awaited inside `#fetch`'s try, so a hook\n * rejection clears the armed timer like any other request failure.\n *\n * @example\n * ```ts\n * const provider = new OllamaProvider({ model: 'qwen3.5:2b-q4_K_M' })\n * const result = await provider.generate(messages, abort.signal)\n * ```\n */\nexport class OllamaProvider implements ProviderInterface {\n\treadonly id = crypto.randomUUID()\n\treadonly name = 'ollama'\n\treadonly #model: string\n\treadonly #url: string\n\treadonly #keepAlive: string | number\n\treadonly #timeout: number\n\treadonly #think: boolean\n\treadonly #options: Readonly<Record<string, unknown>> | undefined\n\treadonly #transport: typeof globalThis.fetch\n\treadonly #headers: (() => Record<string, string> | Promise<Record<string, string>>) | undefined\n\treadonly #format: ContextFormatInterface | undefined\n\n\tconstructor(options: OllamaOptions) {\n\t\tthis.#model = options.model\n\t\tthis.#url = options.url ?? DEFAULT_OLLAMA_URL\n\t\tthis.#keepAlive = options.keepAlive ?? DEFAULT_KEEP_ALIVE\n\t\tthis.#timeout = options.timeout ?? DEFAULT_PROVIDER_TIMEOUT\n\t\t// The `/api/chat` `think` wire flag — DEFAULT `false` so the general-purpose provider\n\t\t// stays backward-compatible and immediate for non-thinking models. A thinking model whose\n\t\t// reasoning is DISPLAYED separately sets `think: true`, and the daemon then returns it on\n\t\t// the `message.thinking` channel (`#thinking`) rather than inline in `message.content`.\n\t\tthis.#think = options.think ?? false\n\t\tthis.#options = options.options\n\t\t// The transport seam (§21): a custom fetch (defaulting to the global, BOUND to its\n\t\t// `globalThis` receiver — invoking a bare reference through a field loses the `window`\n\t\t// receiver and browsers throw `Illegal invocation`; node's fetch is receiver-agnostic,\n\t\t// so only a browser runtime ever saw it) and a dynamic header injector — both omitted\n\t\t// by default, so today's behaviour is byte-identical (the global fetch, only the JSON\n\t\t// content type). The injected transport is `#transport` (the request METHOD already\n\t\t// owns the `#fetch` name).\n\t\tthis.#transport = options.fetch ?? globalThis.fetch.bind(globalThis)\n\t\tthis.#headers = options.headers\n\t\t// The context-framing default (the provider-DEFAULT level of AgentContext's format\n\t\t// cascade) — EXPOSE-ONLY: read by the Agent via `build(this.#provider.format)` and\n\t\t// consumed by core's cascade, it NEVER enters `#body` / the `/api/chat` wire. It is\n\t\t// NOT Ollama's structured-output `format` param (which this provider doesn't send) —\n\t\t// only the shared word collides. Omitted ⇒ undefined ⇒ core's built-in framing.\n\t\tthis.#format = options.format\n\t}\n\n\t/**\n\t * The provider's context-framing default — the PROVIDER-DEFAULT level of\n\t * {@link import('@orkestrel/agent').AgentContextInterface.build}'s format cascade (it BEATS\n\t * the managers' built-in framing, is BEATEN by a manager-options or per-item override).\n\t * Satisfies the OPTIONAL {@link ProviderInterface.format} contract member: `undefined`\n\t * when {@link OllamaOptions.format} was omitted (the framing-agnostic default ⇒ core's\n\t * built-in framing applies unchanged), else the exact configured framing the Agent\n\t * threads into `build()`.\n\t *\n\t * @remarks\n\t * EXPOSE-ONLY — read by the Agent loop and consumed by core's cascade; it is NEVER sent\n\t * on the `/api/chat` wire (it is absent from `#body` / the request). This is NOT Ollama's\n\t * structured-output `format` wire parameter, which this provider does not send; only the\n\t * word collides.\n\t *\n\t * @returns The configured {@link ContextFormatInterface}, or `undefined` when none\n\t */\n\tget format(): ContextFormatInterface | undefined {\n\t\treturn this.#format\n\t}\n\n\tasync generate(\n\t\tmessages: readonly MessageInterface[],\n\t\tsignal: AbortSignal,\n\t\ttools?: readonly ToolDefinition[],\n\t\toptions?: ProviderStreamOptions,\n\t): Promise<ProviderResult> {\n\t\tconst { response, timeout } = await this.#fetch(messages, false, signal, tools, options)\n\t\ttry {\n\t\t\tconst record = await this.#parseBody(response)\n\t\t\t// The one-body call routes through the SAME splitter as the stream (the daemon may\n\t\t\t// ignore `think: false` — the splitter is the guarantee): the assembled content is\n\t\t\t// CLEAN (the splitter's authoritative `content`, which also covers the qwen3\n\t\t\t// template's IMPLICIT leading open), the separated spans + any wire-side\n\t\t\t// `message.thinking` land on `thinking`.\n\t\t\tconst splitter = createThinkSplitter()\n\t\t\tsplitter.split(this.#content(record))\n\t\t\tsplitter.flush()\n\t\t\tconst thinking = this.#thought(splitter, this.#thinking(record))\n\t\t\treturn this.#result(splitter.content, thinking, this.#tools(record), this.#usage(record))\n\t\t} finally {\n\t\t\ttimeout.clear()\n\t\t}\n\t}\n\n\tasync *stream(\n\t\tmessages: readonly MessageInterface[],\n\t\tsignal: AbortSignal,\n\t\ttools?: readonly ToolDefinition[],\n\t\toptions?: ProviderStreamOptions,\n\t): AsyncGenerator<ProviderDelta, ProviderResult> {\n\t\tconst { response, timeout, combined } = await this.#fetch(\n\t\t\tmessages,\n\t\t\ttrue,\n\t\t\tsignal,\n\t\t\ttools,\n\t\t\toptions,\n\t\t)\n\t\tconst body = response.body\n\t\tif (body === null) {\n\t\t\ttimeout.clear()\n\t\t\tthrow new OllamaHTTPError('Ollama API error: no response body', 0)\n\t\t}\n\t\tconst reader = body.getReader()\n\t\tconst decoder = new TextDecoder()\n\t\tconst parser = createNDJSONParser()\n\t\t// The per-call think separator (H4): every wire content delta routes through it, so\n\t\t// only CLEAN content is yielded / assembled even when the daemon ignores `think: false`\n\t\t// for a thinking model; daemon-side `message.thinking` deltas accumulate beside it.\n\t\t// The ASSEMBLED content is the splitter's authoritative `content` — across the qwen3\n\t\t// template's IMPLICIT leading open (a bare `</think>` with the open pre-seeded into the\n\t\t// prompt scaffold) the splitter RECLASSIFIES the already-yielded prefix into `thinking`,\n\t\t// so the result stays clean even though those deltas could not be recalled.\n\t\tconst splitter = createThinkSplitter()\n\t\tlet wired = ''\n\t\tconst calls: ToolCall[] = []\n\t\tlet usage: TokenUsage | undefined\n\t\t// Per-record handling shared between the live loop and the post-loop NDJSON\n\t\t// tail flush below — captured over `this` so a nested `function*` (not an\n\t\t// arrow, which cannot be a generator) needs no rebinding.\n\t\tconst contentOf = (record: Record<string, unknown>): string => this.#content(record)\n\t\tconst thinkingOf = (record: Record<string, unknown>): string => this.#thinking(record)\n\t\tconst toolsOf = (record: Record<string, unknown>): readonly ToolCall[] => this.#tools(record)\n\t\tconst usageOf = (record: Record<string, unknown>): TokenUsage | undefined => this.#usage(record)\n\t\tfunction* handle(record: Record<string, unknown>): Generator<ProviderDelta> {\n\t\t\tconst delta = splitter.split(contentOf(record))\n\t\t\tif (delta.length > 0) yield { type: 'content', text: delta }\n\t\t\t// The PRIMARY live reasoning channel: each native `message.thinking` wire delta is\n\t\t\t// surfaced as a tagged `thinking` delta AND accumulated into `wired` for the assembled\n\t\t\t// result (the two stay in lockstep). The ThinkSplitter's in-content reclassified spans\n\t\t\t// have no per-delta hook — the final `ProviderResult.thinking` reconciles them; the\n\t\t\t// native channel (think: true) is what streams live.\n\t\t\tconst thinking = thinkingOf(record)\n\t\t\tif (thinking.length > 0) yield { type: 'thinking', text: thinking }\n\t\t\twired += thinking\n\t\t\tcalls.push(...toolsOf(record))\n\t\t\tif (Reflect.get(record, 'done') === true) usage = usageOf(record)\n\t\t}\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tconst { value, done } = await reader.read()\n\t\t\t\tif (done) break\n\t\t\t\t// Pair the streaming decoder with the line parser: the decoder handles\n\t\t\t\t// partial multi-byte CHARS, the parser handles partial LINES (§14).\n\t\t\t\tfor (const record of parser.parse(decoder.decode(value, { stream: true }))) {\n\t\t\t\t\tyield* handle(record)\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Flush the decoder's held partial multi-byte tail and feed it (plus a\n\t\t\t// terminating `\\n`) through the parser, so a non-conformant proxy's final\n\t\t\t// unterminated `done` line is recovered instead of silently dropped.\n\t\t\tconst decoderTail = decoder.decode()\n\t\t\tfor (const record of parser.parse(decoderTail.length > 0 ? `${decoderTail}\\n` : '\\n')) {\n\t\t\t\tyield* handle(record)\n\t\t\t}\n\t\t\t// Stream end: a held partial tag that never completed was real content — it is the\n\t\t\t// final delta (the splitter folds it into its `content` too).\n\t\t\tconst tail = splitter.flush()\n\t\t\tif (tail.length > 0) yield { type: 'content', text: tail }\n\t\t} catch (error) {\n\t\t\t// A mid-stream cancel (the caller's signal or the deadline) surfaces the\n\t\t\t// partial so the loop can recover what streamed; anything else propagates.\n\t\t\tif (combined.aborted) {\n\t\t\t\t// Flush the splitter's held partial tail first (mirrors the\n\t\t\t\t// normal-completion assembly above) so the recovered partial includes\n\t\t\t\t// any clean content that never crossed a tag boundary.\n\t\t\t\tsplitter.flush()\n\t\t\t\tthrow new ProviderAbortError(\n\t\t\t\t\tthis.#result(splitter.content, this.#thought(splitter, wired), calls, usage),\n\t\t\t\t)\n\t\t\t}\n\t\t\tthrow error\n\t\t} finally {\n\t\t\t// Cancel (not merely release) the reader on early return so the\n\t\t\t// underlying HTTP connection is freed; a normal-done or already-errored\n\t\t\t// reader tolerates the redundant cancel as a no-op. `cancel()` also\n\t\t\t// releases the lock — never call `releaseLock()` afterward.\n\t\t\ttry {\n\t\t\t\tawait reader.cancel()\n\t\t\t} catch {\n\t\t\t\t// Never mask the primary error/result with a cancel failure.\n\t\t\t}\n\t\t\tparser.reset()\n\t\t\ttimeout.clear()\n\t\t}\n\t\treturn this.#result(splitter.content, this.#thought(splitter, wired), calls, usage)\n\t}\n\n\t// Arm the deadline, POST `/api/chat`, and hand back the response + the handles\n\t// that bound it. On a non-OK status, clear the deadline and throw with the body.\n\tasync #fetch(\n\t\tmessages: readonly MessageInterface[],\n\t\tstream: boolean,\n\t\tsignal: AbortSignal,\n\t\ttools?: readonly ToolDefinition[],\n\t\toptions?: ProviderStreamOptions,\n\t): Promise<OllamaResponse> {\n\t\tconst timeout = new Timeout({ ms: this.#timeout })\n\t\ttimeout.start()\n\t\tconst combined = AbortSignal.any([timeout.signal, signal])\n\t\ttry {\n\t\t\tconst response = await this.#transport(`${this.#url}/api/chat`, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: await this.#requestHeaders(),\n\t\t\t\tbody: JSON.stringify(this.#body(messages, stream, tools, options)),\n\t\t\t\tsignal: combined,\n\t\t\t})\n\t\t\tif (!response.ok) {\n\t\t\t\t// Bound the incorporated body: a defensive proxy or daemon could hand\n\t\t\t\t// back an unbounded response — read defensively so a body-read\n\t\t\t\t// failure still throws with the status, never a masked/unbounded read.\n\t\t\t\tlet detail: string\n\t\t\t\ttry {\n\t\t\t\t\tconst text = await response.text()\n\t\t\t\t\tdetail = text.length > MAX_ERROR_BODY_LENGTH ? text.slice(0, MAX_ERROR_BODY_LENGTH) : text\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tthrow new OllamaHTTPError(\n\t\t\t\t\t\t`Ollama API error: ${response.status} - (error body unavailable)`,\n\t\t\t\t\t\tresponse.status,\n\t\t\t\t\t\t{ cause },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tthrow new OllamaHTTPError(\n\t\t\t\t\t`Ollama API error: ${response.status} - ${detail}`,\n\t\t\t\t\tresponse.status,\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn { response, timeout, combined }\n\t\t} catch (error) {\n\t\t\t// `fetch` rejected (pre-aborted signal / unreachable / network) or the status\n\t\t\t// was non-OK — clear the deadline so the armed timer can't outlive the failed\n\t\t\t// call. The caller's `finally` only takes ownership once we return a response.\n\t\t\ttimeout.clear()\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t// The non-stream `/api/chat` body — read the 200-OK response as text and parse it\n\t// inside a total guard (§14): a malformed or empty body degrades to `{}` (empty\n\t// content, no usage), never a raw `SyntaxError` escaping to the caller.\n\tasync #parseBody(response: Response): Promise<Record<string, unknown>> {\n\t\tconst text = await response.text()\n\t\tif (text.length === 0) return {}\n\t\ttry {\n\t\t\tconst data: unknown = JSON.parse(text)\n\t\t\treturn isRecord(data) ? data : {}\n\t\t} catch {\n\t\t\treturn {}\n\t\t}\n\t}\n\n\t// The request headers — the base JSON content type, plus the dynamic `headers`\n\t// hook's result merged ON TOP when configured (so a dev can attach an obfuscated\n\t// bearer the server validates). Merge order: `Content-Type` is seeded first, then\n\t// the hook's entries overlay it — so the hook ADDS auth headers but only clobbers\n\t// `Content-Type` if the dev explicitly returns one. Awaited (the hook may be async,\n\t// e.g. refreshing a token); called inside `#fetch`'s try so a hook rejection clears\n\t// the armed deadline like any other request failure. §14: the hook's result is a\n\t// `Record<string, string>` already — merged via `Object.entries`, no `as`.\n\tasync #requestHeaders(): Promise<Record<string, string>> {\n\t\tconst headers: Record<string, string> = { 'Content-Type': 'application/json' }\n\t\tif (this.#headers !== undefined) {\n\t\t\tfor (const [key, value] of Object.entries(await this.#headers())) headers[key] = value\n\t\t}\n\t\treturn headers\n\t}\n\n\t// The `/api/chat` request body — conditional `options` / `tools` only when set. The wire\n\t// `think` flag honours a PER-CALL override (`options.think`) over the constructor default\n\t// (`#think`), so a caller can flip reasoning on / off for one turn without reconfiguring the\n\t// provider; no per-call option ⇒ the constructed default, byte-for-byte the prior behaviour.\n\t#body(\n\t\tmessages: readonly MessageInterface[],\n\t\tstream: boolean,\n\t\ttools?: readonly ToolDefinition[],\n\t\toptions?: ProviderStreamOptions,\n\t): WireChatRequest {\n\t\treturn {\n\t\t\tmodel: this.#model,\n\t\t\tmessages: this.#plain(messages),\n\t\t\tstream,\n\t\t\tkeep_alive: this.#keepAlive,\n\t\t\tthink: options?.think ?? this.#think,\n\t\t\t...(this.#options !== undefined ? { options: this.#options } : {}),\n\t\t\t...(tools !== undefined && tools.length > 0\n\t\t\t\t? {\n\t\t\t\t\t\ttools: tools.map(\n\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\ttool,\n\t\t\t\t\t\t\t): {\n\t\t\t\t\t\t\t\ttype: 'function'\n\t\t\t\t\t\t\t\tfunction: {\n\t\t\t\t\t\t\t\t\tname: string\n\t\t\t\t\t\t\t\t\tdescription?: string\n\t\t\t\t\t\t\t\t\tparameters?: Readonly<Record<string, unknown>>\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} => ({\n\t\t\t\t\t\t\t\ttype: 'function',\n\t\t\t\t\t\t\t\tfunction: {\n\t\t\t\t\t\t\t\t\tname: tool.name,\n\t\t\t\t\t\t\t\t\tdescription: tool.description,\n\t\t\t\t\t\t\t\t\tparameters: tool.parameters,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t}\n\t}\n\n\t// Map messages to the wire's minimal turn shape — `tool_calls` only on a turn\n\t// that replays them, `images` only on a multimodal turn (omit empty optionals).\n\t#plain(messages: readonly MessageInterface[]): WireChatRequest['messages'] {\n\t\treturn messages.map((message) => ({\n\t\t\trole: message.role,\n\t\t\tcontent: message.content,\n\t\t\t...(message.calls !== undefined && message.calls.length > 0\n\t\t\t\t? {\n\t\t\t\t\t\ttool_calls: message.calls.map((call) => ({\n\t\t\t\t\t\t\tfunction: { name: call.name, arguments: call.arguments },\n\t\t\t\t\t\t})),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t// Forward multimodal image data — Ollama accepts a base64 `images` array on a\n\t\t\t// message, which a vision-capable model receives alongside the text content.\n\t\t\t...(message.images !== undefined && message.images.length > 0\n\t\t\t\t? { images: [...message.images] }\n\t\t\t\t: {}),\n\t\t}))\n\t}\n\n\t// Assemble a ProviderResult including only the present optionals — no empty\n\t// `thinking` / `tools`, no `usage` unless the wire reported it.\n\t#result(\n\t\tcontent: string,\n\t\tthinking: string,\n\t\ttools: readonly ToolCall[],\n\t\tusage: TokenUsage | undefined,\n\t): ProviderResult {\n\t\tconst result: {\n\t\t\tcontent: string\n\t\t\tthinking?: string\n\t\t\ttools?: readonly ToolCall[]\n\t\t\tusage?: TokenUsage\n\t\t} = { content }\n\t\tif (thinking.length > 0) result.thinking = thinking\n\t\tif (tools.length > 0) result.tools = tools\n\t\tif (usage !== undefined) result.usage = usage\n\t\treturn result\n\t}\n\n\t// The assistant text of one wire record — `message.content` when a string, else\n\t// `''` (a delta line, a tool-only turn, or a malformed shape).\n\t#content(record: Record<string, unknown>): string {\n\t\tconst message = Reflect.get(record, 'message')\n\t\tif (!isRecord(message)) return ''\n\t\tconst content = Reflect.get(message, 'content')\n\t\treturn isString(content) ? content : ''\n\t}\n\n\t// The daemon-side reasoning of one wire record — `message.thinking` when a string\n\t// (the `think: true` wire shape — surfaced when the configured `think` flag is on, and\n\t// handled defensively regardless since the daemon may vary), else `''`.\n\t#thinking(record: Record<string, unknown>): string {\n\t\tconst message = Reflect.get(record, 'message')\n\t\tif (!isRecord(message)) return ''\n\t\tconst thinking = Reflect.get(message, 'thinking')\n\t\treturn isString(thinking) ? thinking : ''\n\t}\n\n\t// Join a call's two reasoning carriers — the splitter's separated in-content spans and\n\t// the accumulated wire-side `message.thinking` — blank-line separated when both exist.\n\t#thought(splitter: ThinkSplitterInterface, wired: string): string {\n\t\tif (splitter.thinking.length === 0) return wired\n\t\tif (wired.length === 0) return splitter.thinking\n\t\treturn `${splitter.thinking}\\n\\n${wired}`\n\t}\n\n\t// Token usage from a wire record — only when BOTH counts are numbers (`done`\n\t// line / non-stream body); a delta line carries neither, so it yields undefined.\n\t#usage(record: Record<string, unknown>): TokenUsage | undefined {\n\t\tconst prompt = Reflect.get(record, 'prompt_eval_count')\n\t\tconst completion = Reflect.get(record, 'eval_count')\n\t\tif (!isNumber(prompt) || !isNumber(completion)) return undefined\n\t\treturn { prompt, completion, total: prompt + completion }\n\t}\n\n\t// Tool calls from a wire record's `message.tool_calls` — each entry narrowed to\n\t// `{ id, name, arguments }`, minting an id when the wire omits one and coercing a\n\t// JSON-string `arguments` to a record (defaulting to `{}`); §14, no `as`.\n\t#tools(record: Record<string, unknown>): readonly ToolCall[] {\n\t\tconst message = Reflect.get(record, 'message')\n\t\tif (!isRecord(message)) return []\n\t\tconst calls = Reflect.get(message, 'tool_calls')\n\t\tif (!Array.isArray(calls)) return []\n\t\tconst out: ToolCall[] = []\n\t\tfor (const entry of calls) {\n\t\t\tif (!isRecord(entry)) continue\n\t\t\tconst callable = Reflect.get(entry, 'function')\n\t\t\tif (!isRecord(callable)) continue\n\t\t\tconst name = Reflect.get(callable, 'name')\n\t\t\tif (!isString(name)) continue\n\t\t\tconst id = Reflect.get(entry, 'id')\n\t\t\tout.push({\n\t\t\t\tid: isString(id) ? id : crypto.randomUUID(),\n\t\t\t\tname,\n\t\t\t\targuments: this.#arguments(Reflect.get(callable, 'arguments')),\n\t\t\t})\n\t\t}\n\t\treturn out\n\t}\n\n\t// Narrow a wire `arguments` value to a record — an object as-is, a JSON string\n\t// parsed (when it yields a record), otherwise `{}`. Total: a bad string never throws.\n\t#arguments(value: unknown): Readonly<Record<string, unknown>> {\n\t\tif (isRecord(value)) return value\n\t\tif (isString(value)) {\n\t\t\ttry {\n\t\t\t\tconst parsed: unknown = JSON.parse(value)\n\t\t\t\tif (isRecord(parsed)) return parsed\n\t\t\t} catch {\n\t\t\t\treturn {}\n\t\t\t}\n\t\t}\n\t\treturn {}\n\t}\n}\n","import type { ProviderInterface } from '@orkestrel/agent'\nimport type { OllamaOptions } from './types.js'\nimport { OllamaProvider } from './OllamaProvider.js'\n\n/**\n * Create a local Ollama inference provider — a {@link ProviderInterface} over the\n * daemon's `POST /api/chat`, supporting non-streaming `generate` and streaming\n * `stream`.\n *\n * @remarks\n * Only `model` is required; `url` defaults to the local daemon, `keepAlive` to `'5m'`,\n * `timeout` to `120_000`ms, and `options` is forwarded verbatim as sampling\n * parameters (`temperature` / `seed` / `num_predict` / …). Both calls take an\n * `AbortSignal` to bound the request; a `stream` cancelled mid-flight throws a\n * `ProviderAbortError` carrying the partial result.\n *\n * The optional `fetch` + `headers` form a transport seam (see {@link OllamaOptions}):\n * point `url` at your own server, inject a custom `fetch`, and have `headers` attach a\n * generated/obfuscated bearer token your server validates — so a browser runtime\n * reaches the LLM through your middleware WITHOUT this library ever handling the real API\n * key. Both omitted ⇒ today's behaviour (the global `fetch`, only a JSON content type).\n *\n * The optional `format` is the provider's context-framing default — the PROVIDER-DEFAULT\n * level of `AgentContext`'s format cascade (see [agents.md]; beaten by a manager-options\n * or per-item override, beating the managers' built-in framing), declaring how this\n * provider's models prefer context sections framed (e.g. XML group wrappers vs. Markdown\n * headers). It is EXPOSED on the provider for the Agent's `build()` and is NOT Ollama's\n * `/api/chat` `format` wire parameter (structured output) — the two are unrelated despite\n * the shared word. Omitted ⇒ the provider is framing-agnostic (core's built-in defaults).\n *\n * @param options - `model` (required), and optional `url` / `keepAlive` / `timeout` /\n * `options` / `fetch` / `headers` / `format` (see {@link OllamaOptions})\n * @returns A working {@link ProviderInterface} backed by Ollama\n *\n * @example\n * ```ts\n * import { createAbort } from '@orkestrel/abort'\n * import { createOllama } from '@src/server'\n *\n * const provider = createOllama({ model: 'qwen3.5:2b-q4_K_M' })\n * const abort = createAbort()\n * const result = await provider.generate(messages, abort.signal)\n * ```\n *\n * @example\n * Route through your own server with an obfuscated token (deployment scenario S2):\n * ```ts\n * const provider = createOllama({\n * model: 'qwen3.5:2b-q4_K_M',\n * url: 'https://my-app.example.com/llm', // your server, not the daemon\n * fetch: myFetch, // optional custom transport\n * headers: () => ({ authorization: `Bearer ${myToken}` }), // your server validates this\n * })\n * ```\n *\n * @example\n * Declare a context-framing default — wrap the instructions section in an XML group (the\n * provider-default level of `AgentContext`'s cascade; NOT the wire `format`):\n * ```ts\n * const provider = createOllama({\n * model: 'qwen3.5:2b-q4_K_M',\n * format: {\n * instructions: {\n * open: '<instructions>',\n * render: (i) => `<instruction>${i.content}</instruction>`,\n * close: '</instructions>',\n * },\n * },\n * })\n * ```\n */\nexport function createOllama(options: OllamaOptions): ProviderInterface {\n\treturn new OllamaProvider(options)\n}\n"],"mappings":";;;;;;;AAGA,IAAa,qBAAqB;;;;;AAMlC,IAAa,qBAAqB;;;;;AAMlC,IAAa,2BAA2B;;;;;;;;;;;;AAaxC,IAAa,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;ACFrC,IAAa,kBAAb,cAAqC,MAAM;CAC1C;CAEA,YAAY,SAAiB,QAAgB,SAAwC;EACpF,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;EACZ,KAAK,SAAS;CACf;AACD;;;;;;;AAQA,SAAgB,kBAAkB,OAA0C;CAC3E,OAAO,iBAAiB;AACzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC2BA,IAAa,iBAAb,MAAyD;CACxD,KAAc,OAAO,WAAW;CAChC,OAAgB;CAChB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,SAAwB;EACnC,KAAKA,SAAS,QAAQ;EACtB,KAAKC,OAAO,QAAQ,OAAA;EACpB,KAAKC,aAAa,QAAQ,aAAA;EAC1B,KAAKC,WAAW,QAAQ,WAAA;EAKxB,KAAKC,SAAS,QAAQ,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