@orkestrel/ollama 0.0.14 → 0.0.16

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.
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.cjs","names":["#id","#model","#url","#keepAlive","#timeout","#think","#options","#transport","#headers","#format","#fetch","#deltas","#requestHeaders","#body"],"sources":["../../../src/server/constants.ts","../../../src/server/errors.ts","../../../src/server/helpers.ts","../../../src/server/parsers.ts","../../../src/server/OllamaProvider.ts","../../../src/server/factories.ts"],"sourcesContent":["// Ollama constants — the provider's defaults.\n\n/** Names the local Ollama daemon base URL assumed when `OllamaOptions.url` is omitted. */\nexport const DEFAULT_OLLAMA_URL = 'http://localhost:11434'\n\n/**\n * Names 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 *\n * @remarks\n * The name mirrors the Ollama `/api/chat` `keep_alive` field this value is sent as, so\n * the constant, the `OllamaOptions.keepAlive` key, and the wire member read as one term.\n */\nexport const DEFAULT_KEEP_ALIVE = '5m'\n\n/**\n * Names 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 * Names 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. `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.\n\nimport type { OllamaHTTPErrorOptions } from './types.js'\n\n/**\n * Represents an error thrown when the Ollama `/api/chat` HTTP transport fails.\n *\n * @remarks\n * Carries the machine-readable `code` `'HTTP'` and the response `status` (0 when no\n * HTTP response was received at all, for example a `null` body). Thrown by\n * {@link OllamaProvider} at its HTTP failure sites — the non-OK status branch and the\n * null-body branch — so a caller can branch on `error.code` and read `error.status`\n * for the HTTP number instead of parsing the message. Narrow a caught value with\n * {@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\t/**\n\t * Names the machine-readable condition this error reports — `'HTTP'`: an `/api/chat`\n\t * transport, status, or body failure.\n\t */\n\treadonly code = 'HTTP' as const\n\treadonly status: number\n\n\tconstructor(message: string, status: number, options?: OllamaHTTPErrorOptions) {\n\t\tsuper(message, options)\n\t\tthis.name = 'OllamaHTTPError'\n\t\tthis.status = status\n\t}\n}\n\n/**\n * Checks whether a value is an {@link OllamaHTTPError}.\n *\n * @param value - The value to test\n * @returns True if `value` is an `OllamaHTTPError`; false otherwise\n */\nexport function isOllamaHTTPError(value: unknown): value is OllamaHTTPError {\n\treturn value instanceof OllamaHTTPError\n}\n","// The Ollama wire leaves — the request projections and the response extractions\n// `OllamaProvider` composes. Each is a pure, total function of its parameters: a missing\n// or malformed wire field degrades to a sensible default (empty content, no usage, `{}`\n// arguments), never a throw, and no value is reached through `as`.\n\nimport type { Message, ProviderResult, ThinkSplitterInterface } from '@orkestrel/agent'\nimport type { TokenUsage } from '@orkestrel/budget'\nimport type { ToolCall } from '@orkestrel/tool'\nimport type { WireChatRequest } from './types.js'\nimport { isNumber, isRecord, isString, parseJSONAs } from '@orkestrel/contract'\n\n/**\n * Maps conversation turns onto the `/api/chat` wire's minimal message shape.\n *\n * @remarks\n * `tool_calls` is emitted only on a turn that replays them and `images` only on a\n * multimodal turn, so an empty optional never reaches the wire.\n *\n * @param messages - The conversation turns to send\n * @returns The wire `messages` array, one entry per turn, in order\n *\n * @example\n * ```ts\n * mapMessages([{ id: '1', role: 'user', content: 'Say hello.' }])\n * // [{ role: 'user', content: 'Say hello.' }]\n * ```\n */\nexport function mapMessages(messages: readonly Message[]): WireChatRequest['messages'] {\n\treturn messages.map((message) => ({\n\t\trole: message.role,\n\t\tcontent: message.content,\n\t\t...(message.calls !== undefined && message.calls.length > 0\n\t\t\t? {\n\t\t\t\t\ttool_calls: message.calls.map((call) => ({\n\t\t\t\t\t\tfunction: { name: call.name, arguments: call.arguments },\n\t\t\t\t\t})),\n\t\t\t\t}\n\t\t\t: {}),\n\t\t// Forward multimodal image data — Ollama accepts a base64 `images` array on a\n\t\t// message, which a vision-capable model receives alongside the text content.\n\t\t...(message.images !== undefined && message.images.length > 0\n\t\t\t? { images: [...message.images] }\n\t\t\t: {}),\n\t}))\n}\n\n/**\n * Builds a provider result from a turn's content, reasoning, tool calls, and usage.\n *\n * @remarks\n * Only the present optionals are set: no empty `thinking`, no empty `tools`, and no\n * `usage` unless the wire reported one.\n *\n * @param content - The clean assistant content the splitter accumulated\n * @param thinking - The joined reasoning, empty when the turn produced none\n * @param tools - The tool calls collected across the turn\n * @param usage - The token usage, or `undefined` when the wire reported none\n * @returns The result carrying only its populated fields\n *\n * @example\n * ```ts\n * buildResult('ok', '', [], undefined) // { content: 'ok' }\n * ```\n */\nexport function buildResult(\n\tcontent: string,\n\tthinking: string,\n\ttools: readonly ToolCall[],\n\tusage: TokenUsage | undefined,\n): ProviderResult {\n\tconst result: {\n\t\tcontent: string\n\t\tthinking?: string\n\t\ttools?: readonly ToolCall[]\n\t\tusage?: TokenUsage\n\t} = { content }\n\tif (thinking.length > 0) result.thinking = thinking\n\tif (tools.length > 0) result.tools = tools\n\tif (usage !== undefined) result.usage = usage\n\treturn result\n}\n\n/**\n * Extracts the assistant text of one wire record.\n *\n * @param record - One parsed `/api/chat` record — a non-stream body or an NDJSON line\n * @returns The record's `message.content` when it is a string, else `''`\n *\n * @example\n * ```ts\n * extractContent({ message: { content: 'ok' } }) // 'ok'\n * ```\n */\nexport function extractContent(record: Readonly<Record<string, unknown>>): string {\n\tconst message = Reflect.get(record, 'message')\n\tif (!isRecord(message)) return ''\n\tconst content = Reflect.get(message, 'content')\n\treturn isString(content) ? content : ''\n}\n\n/**\n * Extracts the daemon-side reasoning of one wire record.\n *\n * @remarks\n * `message.thinking` is the `think: true` wire shape. It is read whatever the configured\n * flag says, because a daemon may separate reasoning on its own.\n *\n * @param record - One parsed `/api/chat` record — a non-stream body or an NDJSON line\n * @returns The record's `message.thinking` when it is a string, else `''`\n *\n * @example\n * ```ts\n * extractThinking({ message: { thinking: 'weighing it' } }) // 'weighing it'\n * ```\n */\nexport function extractThinking(record: Readonly<Record<string, unknown>>): string {\n\tconst message = Reflect.get(record, 'message')\n\tif (!isRecord(message)) return ''\n\tconst thinking = Reflect.get(message, 'thinking')\n\treturn isString(thinking) ? thinking : ''\n}\n\n/**\n * Joins a call's two reasoning carriers into the result's `thinking`.\n *\n * @param splitter - The per-call splitter holding the separated in-content spans\n * @param wired - The accumulated wire-side `message.thinking` text\n * @returns The two carriers separated by a blank line, or whichever one is non-empty\n *\n * @example\n * ```ts\n * joinThinking(createThinkSplitter(), 'from the wire') // 'from the wire'\n * ```\n */\nexport function joinThinking(splitter: ThinkSplitterInterface, wired: string): string {\n\tif (splitter.thinking.length === 0) return wired\n\tif (wired.length === 0) return splitter.thinking\n\treturn `${splitter.thinking}\\n\\n${wired}`\n}\n\n/**\n * Extracts the token usage of one wire record.\n *\n * @remarks\n * Both counts must be numbers, which is true of the non-stream body and the stream's\n * `done: true` line. A delta line carries neither, so it yields `undefined`.\n *\n * @param record - One parsed `/api/chat` record — a non-stream body or an NDJSON line\n * @returns The `TokenUsage` shape, or `undefined` when either count is absent\n *\n * @example\n * ```ts\n * extractUsage({ prompt_eval_count: 3, eval_count: 4 })\n * // { prompt: 3, completion: 4, total: 7 }\n * ```\n */\nexport function extractUsage(record: Readonly<Record<string, unknown>>): TokenUsage | undefined {\n\tconst prompt = Reflect.get(record, 'prompt_eval_count')\n\tconst completion = Reflect.get(record, 'eval_count')\n\tif (!isNumber(prompt) || !isNumber(completion)) return undefined\n\treturn { prompt, completion, total: prompt + completion }\n}\n\n/**\n * Extracts the tool calls of one wire record's `message.tool_calls`.\n *\n * @remarks\n * Each entry narrows to `{ id, name, arguments }`: the entry and its `function` must be\n * records and `name` a string, else the entry is dropped. An id is minted when the wire\n * omits one.\n *\n * @param record - One parsed `/api/chat` record — a non-stream body or an NDJSON line\n * @returns The narrowed tool calls, empty when the record carries none\n *\n * @example\n * ```ts\n * extractTools({ message: { tool_calls: [{ function: { name: 'weather' } }] } })\n * // [{ id: '…', name: 'weather', arguments: {} }]\n * ```\n */\nexport function extractTools(record: Readonly<Record<string, unknown>>): readonly ToolCall[] {\n\tconst message = Reflect.get(record, 'message')\n\tif (!isRecord(message)) return []\n\tconst calls = Reflect.get(message, 'tool_calls')\n\tif (!Array.isArray(calls)) return []\n\tconst out: ToolCall[] = []\n\tfor (const entry of calls) {\n\t\tif (!isRecord(entry)) continue\n\t\tconst callable = Reflect.get(entry, 'function')\n\t\tif (!isRecord(callable)) continue\n\t\tconst name = Reflect.get(callable, 'name')\n\t\tif (!isString(name)) continue\n\t\tconst id = Reflect.get(entry, 'id')\n\t\tout.push({\n\t\t\tid: isString(id) ? id : crypto.randomUUID(),\n\t\t\tname,\n\t\t\targuments: extractArguments(Reflect.get(callable, 'arguments')),\n\t\t})\n\t}\n\treturn out\n}\n\n/**\n * Extracts a wire `arguments` value as a record.\n *\n * @remarks\n * Total: an object passes through, a JSON string is parsed when it yields a record, and\n * a malformed string yields `{}` rather than throwing.\n *\n * @param value - The wire's `function.arguments` value, of unknown shape\n * @returns The argument record, or `{}` when the value carries none\n *\n * @example\n * ```ts\n * extractArguments('{\"city\":\"Oslo\"}') // { city: 'Oslo' }\n * ```\n */\nexport function extractArguments(value: unknown): Readonly<Record<string, unknown>> {\n\tif (isRecord(value)) return value\n\tif (isString(value)) return parseJSONAs(value, isRecord) ?? {}\n\treturn {}\n}\n","// The Ollama response coercer — the non-stream `/api/chat` body read off the wire and\n// coerced to a record inside a total guard, never a raw `SyntaxError`.\n\nimport { isRecord, parseJSONAs } from '@orkestrel/contract'\n\n/**\n * Parses a non-stream `/api/chat` response body into a wire record.\n *\n * @remarks\n * Total by construction: an empty body, a body that is not JSON, and a body whose JSON is\n * not an object all yield `undefined`, so a malformed daemon response never escapes as a\n * `SyntaxError`. The call site supplies the empty-record default that reads as empty\n * content and no usage.\n *\n * @param response - The 200-OK `/api/chat` response whose body is read as text\n * @returns The parsed record, or `undefined` when the body is empty or malformed\n *\n * @example\n * ```ts\n * await parseBody(new Response('{\"message\":{\"content\":\"ok\"}}'))\n * // { message: { content: 'ok' } }\n * ```\n */\nexport async function parseBody(\n\tresponse: Response,\n): Promise<Readonly<Record<string, unknown>> | undefined> {\n\treturn parseJSONAs(await response.text(), isRecord)\n}\n","import type {\n\tContextFormat,\n\tMessage,\n\tProviderDelta,\n\tProviderInterface,\n\tProviderResult,\n\tProviderStreamOptions,\n\tThinkSplitterInterface,\n} from '@orkestrel/agent'\nimport type { TokenUsage } from '@orkestrel/budget'\nimport type { ToolCall, ToolDefinition } from '@orkestrel/tool'\nimport type { OllamaOptions, OllamaResponse, WireChatRequest } from './types.js'\nimport { createThinkSplitter, ProviderAbortError } from '@orkestrel/agent'\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'\nimport {\n\tbuildResult,\n\textractContent,\n\textractThinking,\n\textractTools,\n\textractUsage,\n\tjoinThinking,\n\tmapMessages,\n} from './helpers.js'\nimport { parseBody } from './parsers.js'\n\n/**\n * Implements 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 through {@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.** 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 through `extractThinking`) 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.** 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 ⇒ the global `fetch`\n * and only a JSON content type.\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 name = 'ollama'\n\treadonly #id: string\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:\n\t\t| (() => Readonly<Record<string, string>> | Promise<Readonly<Record<string, string>>>)\n\t\t| undefined\n\treadonly #format: ContextFormat | undefined\n\n\tconstructor(options: OllamaOptions) {\n\t\tthis.#id = crypto.randomUUID()\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 a non-thinking model needs no\n\t\t// configuration and answers immediately. A thinking model whose reasoning is DISPLAYED\n\t\t// separately sets `think: true`, and the daemon then returns it on the\n\t\t// `message.thinking` channel (`extractThinking`) 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: 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 the request goes out over the global fetch carrying 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 through `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` wire param — that one IS sent in `#body`,\n\t\t// but only when a per-call `ProviderStreamOptions.schema` is supplied; the two\n\t\t// merely share a word. Omitted ⇒ undefined ⇒ core's built-in framing.\n\t\tthis.#format = options.format\n\t}\n\n\t/**\n\t * Exposes this instance's identity — a fresh `crypto.randomUUID()` minted at\n\t * construction, satisfying the {@link ProviderInterface.id} contract member. A second\n\t * provider built from identical options carries a distinct id.\n\t *\n\t * @returns The instance's minted identifier\n\t */\n\tget id(): string {\n\t\treturn this.#id\n\t}\n\n\t/**\n\t * Exposes 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 — that one IS sent in `#body`, but only when\n\t * a per-call `ProviderStreamOptions.schema` is supplied; only the word collides.\n\t *\n\t * @returns The configured {@link ContextFormat}, or `undefined` when none\n\t */\n\tget format(): ContextFormat | undefined {\n\t\treturn this.#format\n\t}\n\n\tasync generate(\n\t\tmessages: readonly Message[],\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 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(extractContent(record))\n\t\t\tsplitter.flush()\n\t\t\tconst thinking = joinThinking(splitter, extractThinking(record))\n\t\t\treturn buildResult(splitter.content, thinking, extractTools(record), extractUsage(record))\n\t\t} finally {\n\t\t\ttimeout.clear()\n\t\t}\n\t}\n\n\tasync *stream(\n\t\tmessages: readonly Message[],\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: 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\t// The per-stream accumulators, folded from every `#deltas` return across the live\n\t\t// loop and the post-loop NDJSON tail flush following.\n\t\tlet wired = ''\n\t\tconst calls: ToolCall[] = []\n\t\tlet usage: TokenUsage | undefined\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.\n\t\t\t\tfor (const record of parser.parse(decoder.decode(value, { stream: true }))) {\n\t\t\t\t\tconst increment = yield* this.#deltas(record, splitter, usage)\n\t\t\t\t\twired += increment.thinking\n\t\t\t\t\tcalls.push(...increment.calls)\n\t\t\t\t\tusage = increment.usage\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\tconst increment = yield* this.#deltas(record, splitter, usage)\n\t\t\t\twired += increment.thinking\n\t\t\t\tcalls.push(...increment.calls)\n\t\t\t\tusage = increment.usage\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 { channel: '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 preceding) 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\tbuildResult(splitter.content, joinThinking(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.clear()\n\t\t\ttimeout.clear()\n\t\t}\n\t\treturn buildResult(splitter.content, joinThinking(splitter, wired), calls, usage)\n\t}\n\n\t// Per-record streaming step shared between the live NDJSON loop and the post-loop\n\t// tail flush in `stream()` — a `#` private method (not a free helper) because it is\n\t// the streaming spine that composes the wire leaves and drives the splitter, and\n\t// because its yields are the stream's own. It mutates nothing: it RETURNS the record's\n\t// increments (`thinking` / `calls` / `usage`) and `stream()` folds them, so the\n\t// accumulator's shape is written once, here.\n\t*#deltas(\n\t\trecord: Readonly<Record<string, unknown>>,\n\t\tsplitter: ThinkSplitterInterface,\n\t\tusage: TokenUsage | undefined,\n\t): Generator<\n\t\tProviderDelta,\n\t\t{\n\t\t\treadonly thinking: string\n\t\t\treadonly calls: readonly ToolCall[]\n\t\t\treadonly usage: TokenUsage | undefined\n\t\t}\n\t> {\n\t\tconst delta = splitter.split(extractContent(record))\n\t\tif (delta.length > 0) yield { channel: 'content', text: delta }\n\t\t// The PRIMARY live reasoning channel: each native `message.thinking` wire delta is\n\t\t// surfaced as a tagged `thinking` delta AND returned for the caller's `wired`\n\t\t// accumulation (the two stay in lockstep). The ThinkSplitter's in-content\n\t\t// reclassified spans have no per-delta hook — the final `ProviderResult.thinking`\n\t\t// reconciles them; the native channel (think: true) is what streams live.\n\t\tconst thinking = extractThinking(record)\n\t\tif (thinking.length > 0) yield { channel: 'thinking', text: thinking }\n\t\t// Only the `done` line carries usage, so every other record hands the caller's\n\t\t// current value straight back rather than clearing it.\n\t\treturn {\n\t\t\tthinking,\n\t\t\tcalls: extractTools(record),\n\t\t\tusage: Reflect.get(record, 'done') === true ? extractUsage(record) : usage,\n\t\t}\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 Message[],\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 `#fetch` returns a response.\n\t\t\ttimeout.clear()\n\t\t\tthrow error\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// for example refreshing a token); called inside `#fetch`'s try so a hook rejection\n\t// clears the armed deadline like any other request failure. The hook's result is a\n\t// `Readonly<Record<string, string>>` already — merged through `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` / `format` only when set. The\n\t// wire `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.\n\t// `format` is the wire's structured-output constraint, forwarded verbatim from the per-call\n\t// `ProviderStreamOptions.schema` — unrelated to `OllamaOptions.format` (prompt-context framing).\n\t#body(\n\t\tmessages: readonly Message[],\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: mapMessages(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...(options?.schema !== undefined ? { format: options.schema } : {}),\n\t\t\t...(tools !== undefined && tools.length > 0\n\t\t\t\t? {\n\t\t\t\t\t\ttools: tools.map((tool): NonNullable<WireChatRequest['tools']>[number] => ({\n\t\t\t\t\t\t\ttype: 'function',\n\t\t\t\t\t\t\tfunction: {\n\t\t\t\t\t\t\t\tname: tool.name,\n\t\t\t\t\t\t\t\t...(tool.description === undefined ? {} : { description: tool.description }),\n\t\t\t\t\t\t\t\t...(tool.parameters === undefined ? {} : { parameters: tool.parameters }),\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","import type { ProviderInterface } from '@orkestrel/agent'\nimport type { OllamaOptions } from './types.js'\nimport { OllamaProvider } from './OllamaProvider.js'\n\n/**\n * Creates 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`, and `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 ⇒ the global `fetch` and 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 (beaten by a manager-options or per-item\n * override, beating the managers' built-in framing), declaring how this\n * provider's models prefer context sections framed (for example 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 '@orkestrel/ollama'\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:\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;;;;;;;;;AAUlC,IAAa,qBAAqB;;;;;AAMlC,IAAa,2BAA2B;;;;;;;;;;;;AAaxC,IAAa,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;ACHrC,IAAa,kBAAb,cAAqC,MAAM;;;;;CAK1C,OAAgB;CAChB;CAEA,YAAY,SAAiB,QAAgB,SAAkC;EAC9E,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;EACZ,KAAK,SAAS;CACf;AACD;;;;;;;AAQA,SAAgB,kBAAkB,OAA0C;CAC3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CACD;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC/UA,SAAgB,aAAa,SAA2C;CACvE,OAAO,IAAI,eAAe,OAAO;AAClC"}
@@ -1,542 +0,0 @@
1
- import { ContextFormat } from '@orkestrel/agent';
2
- import { Message } from '@orkestrel/agent';
3
- import { ProviderDelta } from '@orkestrel/agent';
4
- import { ProviderInterface } from '@orkestrel/agent';
5
- import { ProviderResult } from '@orkestrel/agent';
6
- import { ProviderStreamOptions } from '@orkestrel/agent';
7
- import { ThinkSplitterInterface } from '@orkestrel/agent';
8
- import { TimeoutInterface } from '@orkestrel/timeout';
9
- import { TokenUsage } from '@orkestrel/budget';
10
- import { ToolCall } from '@orkestrel/tool';
11
- import { ToolDefinition } from '@orkestrel/tool';
12
-
13
- /**
14
- * Builds a provider result from a turn's content, reasoning, tool calls, and usage.
15
- *
16
- * @remarks
17
- * Only the present optionals are set: no empty `thinking`, no empty `tools`, and no
18
- * `usage` unless the wire reported one.
19
- *
20
- * @param content - The clean assistant content the splitter accumulated
21
- * @param thinking - The joined reasoning, empty when the turn produced none
22
- * @param tools - The tool calls collected across the turn
23
- * @param usage - The token usage, or `undefined` when the wire reported none
24
- * @returns The result carrying only its populated fields
25
- *
26
- * @example
27
- * ```ts
28
- * buildResult('ok', '', [], undefined) // { content: 'ok' }
29
- * ```
30
- */
31
- export declare function buildResult(content: string, thinking: string, tools: readonly ToolCall[], usage: TokenUsage | undefined): ProviderResult;
32
-
33
- /**
34
- * Creates a local Ollama inference provider — a {@link ProviderInterface} over the
35
- * daemon's `POST /api/chat`, supporting non-streaming `generate` and streaming
36
- * `stream`.
37
- *
38
- * @remarks
39
- * Only `model` is required; `url` defaults to the local daemon, `keepAlive` to `'5m'`,
40
- * `timeout` to `120_000`ms, and `options` is forwarded verbatim as sampling
41
- * parameters (`temperature`, `seed`, and `num_predict`). Both calls take an
42
- * `AbortSignal` to bound the request; a `stream` cancelled mid-flight throws a
43
- * `ProviderAbortError` carrying the partial result.
44
- *
45
- * The optional `fetch` + `headers` form a transport seam (see {@link OllamaOptions}):
46
- * point `url` at your own server, inject a custom `fetch`, and have `headers` attach a
47
- * generated/obfuscated bearer token your server validates — so a browser runtime
48
- * reaches the LLM through your middleware WITHOUT this library ever handling the real API
49
- * key. Both omitted ⇒ the global `fetch` and only a JSON content type.
50
- *
51
- * The optional `format` is the provider's context-framing default — the PROVIDER-DEFAULT
52
- * level of `AgentContext`'s format cascade (beaten by a manager-options or per-item
53
- * override, beating the managers' built-in framing), declaring how this
54
- * provider's models prefer context sections framed (for example XML group wrappers vs. Markdown
55
- * headers). It is EXPOSED on the provider for the Agent's `build()` and is NOT Ollama's
56
- * `/api/chat` `format` wire parameter (structured output) — the two are unrelated despite
57
- * the shared word. Omitted ⇒ the provider is framing-agnostic (core's built-in defaults).
58
- *
59
- * @param options - `model` (required), and optional `url` / `keepAlive` / `timeout` /
60
- * `options` / `fetch` / `headers` / `format` (see {@link OllamaOptions})
61
- * @returns A working {@link ProviderInterface} backed by Ollama
62
- *
63
- * @example
64
- * ```ts
65
- * import { createAbort } from '@orkestrel/abort'
66
- * import { createOllama } from '@orkestrel/ollama'
67
- *
68
- * const provider = createOllama({ model: 'qwen3.5:2b-q4_K_M' })
69
- * const abort = createAbort()
70
- * const result = await provider.generate(messages, abort.signal)
71
- * ```
72
- *
73
- * @example
74
- * Route through your own server with an obfuscated token:
75
- * ```ts
76
- * const provider = createOllama({
77
- * model: 'qwen3.5:2b-q4_K_M',
78
- * url: 'https://my-app.example.com/llm', // your server, not the daemon
79
- * fetch: myFetch, // optional custom transport
80
- * headers: () => ({ authorization: `Bearer ${myToken}` }), // your server validates this
81
- * })
82
- * ```
83
- *
84
- * @example
85
- * Declare a context-framing default — wrap the instructions section in an XML group (the
86
- * provider-default level of `AgentContext`'s cascade; NOT the wire `format`):
87
- * ```ts
88
- * const provider = createOllama({
89
- * model: 'qwen3.5:2b-q4_K_M',
90
- * format: {
91
- * instructions: {
92
- * open: '<instructions>',
93
- * render: (i) => `<instruction>${i.content}</instruction>`,
94
- * close: '</instructions>',
95
- * },
96
- * },
97
- * })
98
- * ```
99
- */
100
- export declare function createOllama(options: OllamaOptions): ProviderInterface;
101
-
102
- /**
103
- * Names how long the model stays resident after a call when `OllamaOptions.keepAlive` is
104
- * omitted — Ollama's own `keep_alive` default, expressed as a duration string.
105
- *
106
- * @remarks
107
- * The name mirrors the Ollama `/api/chat` `keep_alive` field this value is sent as, so
108
- * the constant, the `OllamaOptions.keepAlive` key, and the wire member read as one term.
109
- */
110
- export declare const DEFAULT_KEEP_ALIVE = "5m";
111
-
112
- /** Names the local Ollama daemon base URL assumed when `OllamaOptions.url` is omitted. */
113
- export declare const DEFAULT_OLLAMA_URL = "http://localhost:11434";
114
-
115
- /**
116
- * Names the per-call deadline in milliseconds when `OllamaOptions.timeout` is omitted —
117
- * generous enough that a cold model load does not trip it.
118
- */
119
- export declare const DEFAULT_PROVIDER_TIMEOUT = 120000;
120
-
121
- /**
122
- * Extracts a wire `arguments` value as a record.
123
- *
124
- * @remarks
125
- * Total: an object passes through, a JSON string is parsed when it yields a record, and
126
- * a malformed string yields `{}` rather than throwing.
127
- *
128
- * @param value - The wire's `function.arguments` value, of unknown shape
129
- * @returns The argument record, or `{}` when the value carries none
130
- *
131
- * @example
132
- * ```ts
133
- * extractArguments('{"city":"Oslo"}') // { city: 'Oslo' }
134
- * ```
135
- */
136
- export declare function extractArguments(value: unknown): Readonly<Record<string, unknown>>;
137
-
138
- /**
139
- * Extracts the assistant text of one wire record.
140
- *
141
- * @param record - One parsed `/api/chat` record — a non-stream body or an NDJSON line
142
- * @returns The record's `message.content` when it is a string, else `''`
143
- *
144
- * @example
145
- * ```ts
146
- * extractContent({ message: { content: 'ok' } }) // 'ok'
147
- * ```
148
- */
149
- export declare function extractContent(record: Readonly<Record<string, unknown>>): string;
150
-
151
- /**
152
- * Extracts the daemon-side reasoning of one wire record.
153
- *
154
- * @remarks
155
- * `message.thinking` is the `think: true` wire shape. It is read whatever the configured
156
- * flag says, because a daemon may separate reasoning on its own.
157
- *
158
- * @param record - One parsed `/api/chat` record — a non-stream body or an NDJSON line
159
- * @returns The record's `message.thinking` when it is a string, else `''`
160
- *
161
- * @example
162
- * ```ts
163
- * extractThinking({ message: { thinking: 'weighing it' } }) // 'weighing it'
164
- * ```
165
- */
166
- export declare function extractThinking(record: Readonly<Record<string, unknown>>): string;
167
-
168
- /**
169
- * Extracts the tool calls of one wire record's `message.tool_calls`.
170
- *
171
- * @remarks
172
- * Each entry narrows to `{ id, name, arguments }`: the entry and its `function` must be
173
- * records and `name` a string, else the entry is dropped. An id is minted when the wire
174
- * omits one.
175
- *
176
- * @param record - One parsed `/api/chat` record — a non-stream body or an NDJSON line
177
- * @returns The narrowed tool calls, empty when the record carries none
178
- *
179
- * @example
180
- * ```ts
181
- * extractTools({ message: { tool_calls: [{ function: { name: 'weather' } }] } })
182
- * // [{ id: '…', name: 'weather', arguments: {} }]
183
- * ```
184
- */
185
- export declare function extractTools(record: Readonly<Record<string, unknown>>): readonly ToolCall[];
186
-
187
- /**
188
- * Extracts the token usage of one wire record.
189
- *
190
- * @remarks
191
- * Both counts must be numbers, which is true of the non-stream body and the stream's
192
- * `done: true` line. A delta line carries neither, so it yields `undefined`.
193
- *
194
- * @param record - One parsed `/api/chat` record — a non-stream body or an NDJSON line
195
- * @returns The `TokenUsage` shape, or `undefined` when either count is absent
196
- *
197
- * @example
198
- * ```ts
199
- * extractUsage({ prompt_eval_count: 3, eval_count: 4 })
200
- * // { prompt: 3, completion: 4, total: 7 }
201
- * ```
202
- */
203
- export declare function extractUsage(record: Readonly<Record<string, unknown>>): TokenUsage | undefined;
204
-
205
- /**
206
- * Checks whether a value is an {@link OllamaHTTPError}.
207
- *
208
- * @param value - The value to test
209
- * @returns True if `value` is an `OllamaHTTPError`; false otherwise
210
- */
211
- export declare function isOllamaHTTPError(value: unknown): value is OllamaHTTPError;
212
-
213
- /**
214
- * Joins a call's two reasoning carriers into the result's `thinking`.
215
- *
216
- * @param splitter - The per-call splitter holding the separated in-content spans
217
- * @param wired - The accumulated wire-side `message.thinking` text
218
- * @returns The two carriers separated by a blank line, or whichever one is non-empty
219
- *
220
- * @example
221
- * ```ts
222
- * joinThinking(createThinkSplitter(), 'from the wire') // 'from the wire'
223
- * ```
224
- */
225
- export declare function joinThinking(splitter: ThinkSplitterInterface, wired: string): string;
226
-
227
- /**
228
- * Maps conversation turns onto the `/api/chat` wire's minimal message shape.
229
- *
230
- * @remarks
231
- * `tool_calls` is emitted only on a turn that replays them and `images` only on a
232
- * multimodal turn, so an empty optional never reaches the wire.
233
- *
234
- * @param messages - The conversation turns to send
235
- * @returns The wire `messages` array, one entry per turn, in order
236
- *
237
- * @example
238
- * ```ts
239
- * mapMessages([{ id: '1', role: 'user', content: 'Say hello.' }])
240
- * // [{ role: 'user', content: 'Say hello.' }]
241
- * ```
242
- */
243
- export declare function mapMessages(messages: readonly Message[]): WireChatRequest['messages'];
244
-
245
- /**
246
- * Names the cap, in characters, on how much of a non-OK response body is
247
- * incorporated into a thrown {@link OllamaHTTPError}'s message.
248
- *
249
- * @remarks
250
- * Bounds the excerpt so a defensive proxy or a misbehaving daemon handing
251
- * back an unbounded response body cannot inflate the thrown error's message
252
- * without limit. `2048` characters is generous enough to carry a
253
- * useful diagnostic snippet while staying well short of any practical size
254
- * concern.
255
- */
256
- export declare const MAX_ERROR_BODY_LENGTH = 2048;
257
-
258
- /**
259
- * Represents an error thrown when the Ollama `/api/chat` HTTP transport fails.
260
- *
261
- * @remarks
262
- * Carries the machine-readable `code` `'HTTP'` and the response `status` (0 when no
263
- * HTTP response was received at all, for example a `null` body). Thrown by
264
- * {@link OllamaProvider} at its HTTP failure sites — the non-OK status branch and the
265
- * null-body branch — so a caller can branch on `error.code` and read `error.status`
266
- * for the HTTP number instead of parsing the message. Narrow a caught value with
267
- * {@link isOllamaHTTPError}.
268
- *
269
- * @example
270
- * ```ts
271
- * try {
272
- * await provider.generate(messages, signal)
273
- * } catch (error) {
274
- * if (isOllamaHTTPError(error) && error.status === 404) {
275
- * // the configured model isn't pulled
276
- * }
277
- * }
278
- * ```
279
- */
280
- export declare class OllamaHTTPError extends Error {
281
- /**
282
- * Names the machine-readable condition this error reports — `'HTTP'`: an `/api/chat`
283
- * transport, status, or body failure.
284
- */
285
- readonly code: "HTTP";
286
- readonly status: number;
287
- constructor(message: string, status: number, options?: OllamaHTTPErrorOptions);
288
- }
289
-
290
- /**
291
- * Represents the options a thrown {@link OllamaHTTPError} accepts beside its message and status —
292
- * the standard error `cause` link, named so a consumer can reference the shape.
293
- *
294
- * @remarks
295
- * `cause` is the underlying value that produced the HTTP failure: the transport or
296
- * body-read rejection the provider caught before rethrowing. It is `unknown` because a
297
- * thrown value is unconstrained. Omitted ⇒ the error carries no cause.
298
- */
299
- export declare interface OllamaHTTPErrorOptions {
300
- readonly cause?: unknown;
301
- }
302
-
303
- /**
304
- * Represents the configuration `createOllama` accepts for the local Ollama backend.
305
- *
306
- * @remarks
307
- * Only `model` is required. `url` defaults to the local daemon, `keepAlive` controls
308
- * how long the model stays resident after a call, `timeout` is the per-call deadline
309
- * in milliseconds, and `options` is a passthrough bag of sampling parameters
310
- * (`temperature`, `seed`, and `num_predict`) forwarded verbatim to the wire.
311
- *
312
- * The optional `fetch` + `headers` form a **transport seam**: by default the provider
313
- * talks straight to a local daemon over `globalThis.fetch` with only a JSON content
314
- * type, but a browser-side runtime can inject a custom transport AND a dynamic header
315
- * (for example an obfuscated bearer token) so requests route through the developer's OWN
316
- * server, which validates that header and forwards to the real LLM. Your app never
317
- * holds a real API key — the real key lives only on the developer's server; the
318
- * `headers` hook supplies whatever short-lived/obfuscated token that server expects.
319
- */
320
- export declare interface OllamaOptions {
321
- readonly model: string;
322
- /** Sets the daemon base URL; defaults to `'http://localhost:11434'`. */
323
- readonly url?: string;
324
- /**
325
- * Sets how long the model stays resident after a call; defaults to `'5m'`. Mirrors the
326
- * Ollama `/api/chat` `keep_alive` field, whose value this key carries verbatim onto
327
- * {@link WireChatRequest.keep_alive}.
328
- */
329
- readonly keepAlive?: string | number;
330
- /** Sets the per-call deadline in milliseconds; defaults to `120_000`. */
331
- readonly timeout?: number;
332
- /**
333
- * Carries passthrough sampling parameters (`temperature`, `seed`, and `num_predict`).
334
- * Mirrors the Ollama `/api/chat` `options` field, whose value this key carries verbatim
335
- * onto {@link WireChatRequest.options}.
336
- */
337
- readonly options?: Readonly<Record<string, unknown>>;
338
- /**
339
- * Sets the `/api/chat` `think` wire flag; defaults to `false`. When `true`, a thinking-capable
340
- * model (for example `qwen3`) separates its reasoning NATIVELY at the wire — the daemon returns it
341
- * on the distinct `message.thinking` channel (surfaced on `ProviderResult.thinking`) rather
342
- * than inline in `message.content`. The default is `false`, so a non-thinking model needs no
343
- * configuration and answers immediately; the per-call ThinkSplitter
344
- * remains the defensive fallback for daemons/models that still inline `<think>` tags either
345
- * way. Set it `true` for a thinking model whose reasoning you intend to DISPLAY separately.
346
- */
347
- readonly think?: boolean;
348
- /**
349
- * Sets a custom `fetch` implementation for every request; defaults to
350
- * `globalThis.fetch`. Lets a runtime inject its own transport (a browser fetch
351
- * pointed at the developer's server, an instrumented wrapper) without changing
352
- * the wire protocol. Omitted ⇒ the global `fetch`.
353
- */
354
- readonly fetch?: typeof globalThis.fetch;
355
- /**
356
- * Sets a dynamic, possibly-async header injector called once per request; its returned
357
- * headers are merged into the request on top of the base `Content-Type`. Use it to
358
- * attach an authorization header — for example an obfuscated/generated bearer token the
359
- * developer's server validates before relaying to the real LLM — so a browser
360
- * runtime can authenticate WITHOUT your app ever handling a real API key. Async so a
361
- * token can be refreshed/fetched per call. A returned `Content-Type` overrides the
362
- * default; other headers add to it. Omitted ⇒ only `Content-Type: application/json`.
363
- */
364
- readonly headers?: () => Readonly<Record<string, string>> | Promise<Readonly<Record<string, string>>>;
365
- /**
366
- * Sets the provider's OPTIONAL context-framing default — the PROVIDER-DEFAULT level of
367
- * `AgentContext`'s format cascade (beaten by a manager-options or per-item override,
368
- * beating the managers' built-in framing). Declares how this provider's models prefer
369
- * context sections framed (for example XML group wrappers vs. Markdown headers). Omitted ⇒
370
- * the provider is framing-agnostic and core's built-in defaults apply unchanged. NOTE:
371
- * this is the prompt-CONTEXT framing consumed by `AgentContext.build()` — it is NOT
372
- * Ollama's `/api/chat` `format` wire parameter (structured-output / JSON schema),
373
- * which this provider sends only when a call supplies a `schema`; the two are unrelated
374
- * despite the shared word.
375
- */
376
- readonly format?: ContextFormat;
377
- }
378
-
379
- /**
380
- * Implements the local Ollama inference boundary — a {@link ProviderInterface} over Ollama's
381
- * `POST /api/chat`, both non-streaming (`generate`) and streaming NDJSON (`stream`).
382
- *
383
- * @remarks
384
- * - **Wire protocol.** Posts `{ model, messages, stream, keep_alive, think }` plus
385
- * passthrough sampling `options` and mapped function `tools`. The `think` flag is
386
- * CONFIGURABLE through {@link OllamaOptions.think} (default `false`). Non-stream parses
387
- * one JSON body; stream consumes NDJSON (one JSON object per `\n`-terminated line) —
388
- * deltas carry `message.content`, the final `done: true` line carries the token usage.
389
- * - **Think separation.** The wire `think` flag is configurable
390
- * ({@link OllamaOptions.think}, default `false`). With `think: true` a thinking model's
391
- * daemon separates reasoning NATIVELY — returning it on the distinct `message.thinking`
392
- * channel (read here through `extractThinking`) instead of inline in `message.content`. EITHER
393
- * way the per-call {@link ThinkSplitterInterface} is the defensive guarantee: a daemon
394
- * may ignore `think: false` for a thinking model and inline `<think>` tags, so every
395
- * content delta routes through the splitter, only CLEAN content is yielded / assembled,
396
- * and the separated reasoning (plus any daemon-side `message.thinking` deltas) lands on
397
- * `ProviderResult.thinking`, never in the conversation.
398
- * - **Boundary narrowing.** Every wire value arrives as `unknown` and is
399
- * narrowed through guards (`isRecord` / `isString` / `isNumber`) — never `as`. A
400
- * missing / malformed field degrades to a sensible default (empty content, no
401
- * usage, `{}` arguments), never a throw.
402
- * - **Bounded.** Each call arms a {@link Timeout} for `OllamaOptions.timeout` and
403
- * passes `AbortSignal.any([timeout.signal, signal])` to `fetch`, so the caller's
404
- * signal AND the deadline both cancel the request. The timeout is always cleared —
405
- * in `#fetch` if the request fails/aborts, otherwise in the consuming call's `finally`.
406
- * - **Abort recovers partial.** A `stream` cancelled mid-flight throws a
407
- * `ProviderAbortError` carrying the partial result assembled so far; pairing the
408
- * `TextDecoder({ stream: true })` with the {@link NDJSONParser} parser keeps multi-byte
409
- * UTF-8 splits and partial lines honest.
410
- * - **Event-free.** A pure functional boundary — no Emitter, no events.
411
- * - **Transport seam.** {@link OllamaOptions.fetch} swaps the transport (default
412
- * `globalThis.fetch`) and {@link OllamaOptions.headers} is a per-request, possibly
413
- * async header injector merged over the base `Content-Type` — so a browser runtime
414
- * can route through the developer's own server with an obfuscated bearer token,
415
- * without this library ever handling a real API key. Both omitted ⇒ the global `fetch`
416
- * and only a JSON content type.
417
- * Orthogonal to the deadline: the hook is awaited inside `#fetch`'s try, so a hook
418
- * rejection clears the armed timer like any other request failure.
419
- *
420
- * @example
421
- * ```ts
422
- * const provider = new OllamaProvider({ model: 'qwen3.5:2b-q4_K_M' })
423
- * const result = await provider.generate(messages, abort.signal)
424
- * ```
425
- */
426
- export declare class OllamaProvider implements ProviderInterface {
427
- #private;
428
- readonly name = "ollama";
429
- constructor(options: OllamaOptions);
430
- /**
431
- * Exposes this instance's identity — a fresh `crypto.randomUUID()` minted at
432
- * construction, satisfying the {@link ProviderInterface.id} contract member. A second
433
- * provider built from identical options carries a distinct id.
434
- *
435
- * @returns The instance's minted identifier
436
- */
437
- get id(): string;
438
- /**
439
- * Exposes the provider's context-framing default — the PROVIDER-DEFAULT level of
440
- * {@link import('@orkestrel/agent').AgentContextInterface.build}'s format cascade (it BEATS
441
- * the managers' built-in framing, is BEATEN by a manager-options or per-item override).
442
- * Satisfies the OPTIONAL {@link ProviderInterface.format} contract member: `undefined`
443
- * when {@link OllamaOptions.format} was omitted (the framing-agnostic default ⇒ core's
444
- * built-in framing applies unchanged), else the exact configured framing the Agent
445
- * threads into `build()`.
446
- *
447
- * @remarks
448
- * EXPOSE-ONLY — read by the Agent loop and consumed by core's cascade; it is NEVER sent
449
- * on the `/api/chat` wire (it is absent from `#body` / the request). This is NOT Ollama's
450
- * structured-output `format` wire parameter — that one IS sent in `#body`, but only when
451
- * a per-call `ProviderStreamOptions.schema` is supplied; only the word collides.
452
- *
453
- * @returns The configured {@link ContextFormat}, or `undefined` when none
454
- */
455
- get format(): ContextFormat | undefined;
456
- generate(messages: readonly Message[], signal: AbortSignal, tools?: readonly ToolDefinition[], options?: ProviderStreamOptions): Promise<ProviderResult>;
457
- stream(messages: readonly Message[], signal: AbortSignal, tools?: readonly ToolDefinition[], options?: ProviderStreamOptions): AsyncGenerator<ProviderDelta, ProviderResult>;
458
- }
459
-
460
- /**
461
- * Represents an open `POST /api/chat` response together with the deadline and the
462
- * combined signal that bound the request.
463
- *
464
- * @remarks
465
- * The `response` is the open `POST /api/chat` `Response`; `timeout` is the armed
466
- * {@link TimeoutInterface} the consuming call clears once it finishes reading the body
467
- * (or that the provider clears on a failed or aborted request); `combined` is the
468
- * `AbortSignal.any([timeout.signal, callerSignal])` the request was issued under, which
469
- * the streaming path checks to tell a mid-stream cancel apart from any other error.
470
- */
471
- export declare interface OllamaResponse {
472
- readonly response: Response;
473
- readonly timeout: TimeoutInterface;
474
- readonly combined: AbortSignal;
475
- }
476
-
477
- /**
478
- * Parses a non-stream `/api/chat` response body into a wire record.
479
- *
480
- * @remarks
481
- * Total by construction: an empty body, a body that is not JSON, and a body whose JSON is
482
- * not an object all yield `undefined`, so a malformed daemon response never escapes as a
483
- * `SyntaxError`. The call site supplies the empty-record default that reads as empty
484
- * content and no usage.
485
- *
486
- * @param response - The 200-OK `/api/chat` response whose body is read as text
487
- * @returns The parsed record, or `undefined` when the body is empty or malformed
488
- *
489
- * @example
490
- * ```ts
491
- * await parseBody(new Response('{"message":{"content":"ok"}}'))
492
- * // { message: { content: 'ok' } }
493
- * ```
494
- */
495
- export declare function parseBody(response: Response): Promise<Readonly<Record<string, unknown>> | undefined>;
496
-
497
- /**
498
- * Represents the exact `POST /api/chat` request body `OllamaProvider` sends — the internal typed
499
- * wire contract.
500
- *
501
- * @remarks
502
- * This is the typed wire shape asserted against the official `ollama` client's
503
- * `ChatRequest` by the compile-time parity test; `src/` never imports `ollama` itself.
504
- * `messages` mirrors the minimal turn shape `mapMessages` builds (`role` / `content`, plus
505
- * `tool_calls` only on a turn that replays them and `images` only on a multimodal
506
- * turn); `options` and `tools` are only present when configured.
507
- */
508
- export declare interface WireChatRequest {
509
- readonly model: string;
510
- readonly messages: ReadonlyArray<{
511
- readonly role: string;
512
- readonly content: string;
513
- readonly tool_calls?: ReadonlyArray<{
514
- readonly function: {
515
- readonly name: string;
516
- readonly arguments: Readonly<Record<string, unknown>>;
517
- };
518
- }>;
519
- readonly images?: readonly string[];
520
- }>;
521
- readonly stream: boolean;
522
- readonly keep_alive: string | number;
523
- readonly think: boolean;
524
- readonly options?: Readonly<Record<string, unknown>>;
525
- readonly tools?: ReadonlyArray<{
526
- readonly type: 'function';
527
- readonly function: {
528
- readonly name: string;
529
- readonly description?: string;
530
- readonly parameters?: Readonly<Record<string, unknown>>;
531
- };
532
- }>;
533
- /**
534
- * Holds the `/api/chat` structured-output constraint — a JSON-Schema object forwarded
535
- * verbatim from the per-call `ProviderStreamOptions.schema`. This is NOT
536
- * `OllamaOptions.format` (the unrelated prompt-context framing); only present
537
- * when a call supplies a `schema`.
538
- */
539
- readonly format?: Readonly<Record<string, unknown>>;
540
- }
541
-
542
- export { }