@nemesis-oss/ollama-sdk 1.7.0 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +168 -1
- package/README.md +181 -10
- package/dist/anthropic-5oYIRS6D.d.ts +1649 -0
- package/dist/anthropic-BIh45UXj.d.cts +1649 -0
- package/dist/{compose-DLStUfaF.d.ts → compose-DCVYMvOL.d.ts} +1 -1
- package/dist/{compose-DS-UWFx8.d.cts → compose-Dj6FdF2n.d.cts} +1 -1
- package/dist/generated-api.cjs +116 -9
- package/dist/generated-api.cjs.map +1 -1
- package/dist/generated-api.d.cts +321 -630
- package/dist/generated-api.d.ts +321 -630
- package/dist/generated-api.js +112 -10
- package/dist/generated-api.js.map +1 -1
- package/dist/generated-models-schemas.cjs +151 -3
- package/dist/generated-models-schemas.cjs.map +1 -1
- package/dist/generated-models-schemas.d.cts +228 -3
- package/dist/generated-models-schemas.d.ts +228 -3
- package/dist/generated-models-schemas.js +134 -4
- package/dist/generated-models-schemas.js.map +1 -1
- package/dist/generated-runtime.cjs +679 -60
- package/dist/generated-runtime.cjs.map +1 -1
- package/dist/generated-runtime.d.cts +22 -24
- package/dist/generated-runtime.d.ts +22 -24
- package/dist/generated-runtime.js +678 -61
- package/dist/generated-runtime.js.map +1 -1
- package/dist/index.cjs +2468 -132
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1666 -864
- package/dist/index.d.ts +1666 -864
- package/dist/index.js +2432 -133
- package/dist/index.js.map +1 -1
- package/dist/mcp/tools.json +306 -73
- package/dist/mcp-generated.cjs +138 -7
- package/dist/mcp-generated.cjs.map +1 -1
- package/dist/mcp-generated.d.cts +2 -2
- package/dist/mcp-generated.d.ts +2 -2
- package/dist/mcp-generated.js +138 -7
- package/dist/mcp-generated.js.map +1 -1
- package/dist/{runtime-qwD72cpn.d.ts → runtime-C3rfpkZw.d.ts} +286 -5
- package/dist/{runtime-bQ48I-RC.d.cts → runtime-D2W9TfCJ.d.cts} +286 -5
- package/dist/skills.cjs.map +1 -1
- package/dist/skills.d.cts +3 -3
- package/dist/skills.d.ts +3 -3
- package/dist/skills.js.map +1 -1
- package/dist/{types-5PAjLoCp.d.cts → types-DVcX_zMp.d.cts} +110 -10
- package/dist/{types-5PAjLoCp.d.ts → types-DVcX_zMp.d.ts} +110 -10
- package/package.json +9 -5
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config.ts","../src/errors.ts","../src/logger.ts","../src/providers/endpoint-registry.ts","../src/middleware.ts","../src/utils.ts","../src/streaming/ndjson.ts","../src/streaming/sse.ts","../src/telemetry/tracer.ts","../src/transport/http.ts","../src/providers/health-check.ts","../src/capabilities/capabilities.ts","../src/schema/zod.ts","../src/usage.ts","../src/tools/tool-call-id.ts","../src/streaming/stream.ts","../src/streaming/normalize.ts","../src/transport/backoff.ts","../src/transport/retry.ts","../src/transport/timeout.ts","../src/models-client.ts","../src/integrations/openai.ts","../src/integrations/anthropic.ts","../src/generated/models/ToolCall.schema.ts","../src/generated/models/ChatMessage.schema.ts","../src/generated/models/ModelOptions.schema.ts","../src/generated/models/ThinkValue.schema.ts","../src/generated/models/ToolDefinition.schema.ts","../src/generated/models/ChatRequest.schema.ts","../src/generated/models/GenerateRequest.schema.ts","../src/generated/models/EmbedRequest.schema.ts","../src/generated/models/CreateRequest.schema.ts","../src/generated/models/CopyRequest.schema.ts","../src/generated/models/DeleteRequest.schema.ts","../src/generated/models/PullRequest.schema.ts","../src/generated/models/PushRequest.schema.ts","../src/generated/models/ShowRequest.schema.ts","../src/generated/runtime/schema-registry.ts","../src/generated/runtime/runtime.ts","../src/client.ts","../src/streaming/adapters.ts","../src/quota.ts","../src/tools/define-tool.ts","../src/tools/registry.ts","../src/mcp/json-schema.ts","../src/mcp/mcp-tools.ts","../src/mcp/bridge.ts","../src/skills/frontmatter.ts","../src/skills/compose.ts","../src/agent/agent.ts"],"names":["message","disp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AAA,MAAW,OAAO,WAAA,EAAa;AAC7B,YAAA,IAAA,CAAK,KAAA,EAAO,gBAAgB,GAAG,CAAA;AAC/B,YAAA,OAAA,CAAQ,IAAA,CAAK;AAAA,cACX,IAAA,EAAM,MAAA;AAAA,cACN,WAAW,GAAA,CAAI,QAAA;AAAA,cACf,SAAS,GAAA,CAAI;AAAA,aACd,CAAA;AAAA,UACH;AAEA,UAAA,MAAM,OAAkB,EAAE,SAAA,EAAW,OAAA,EAAS,gBAAA,EAAkB,WAAW,WAAA,EAAY;AACvF,UAAA,KAAA,CAAM,KAAK,IAAI,CAAA;AACf,UAAA,IAAA,CAAK,KAAA,EAAO,YAAY,IAAI,CAAA;AAC5B,UAAA,OAAO,EAAE,MAAM,KAAA,EAAe;AAAA,QAChC;AAAA,OACF;AAEA,MAAA,IAAI,QAAQ,IAAA,EAAM;AAChB,QAAA,OAAO,EAAE,YAAA,EAAc,OAAA,CAAQ,YAAA,EAAc,KAAA,EAAO,iBAAiB,SAAA,EAAU;AAAA,MACjF;AAAA,IACF;AAEA,IAAA,MAAM,IAAI,6BAAA;AAAA,MACR,CAAA,+BAAA,EAAkC,KAAK,aAAa,CAAA,oBAAA,CAAA;AAAA,MACpD,EAAE,aAAA,EAAe,IAAA,CAAK,aAAA;AAAc,KACtC;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Configuration options and constants for OllamaClient.\n */\n\nimport type { Logger, RequestLifecycleHook } from './logger.js';\nimport type { Middleware } from './middleware.js';\nimport type { RetryConfig } from './transport/retry.js';\nimport type { FetchLike } from './transport/http.js';\nimport type { EndpointRegistryOptions, OllamaEndpoint } from './providers/endpoint-registry.js';\n\nexport const DEFAULT_BASE_URL = 'http://localhost:11434';\nexport const DEFAULT_TIMEOUT_MS = 30_000;\n/**\n * Fixed host for Ollama's hosted web tools (`/api/web_search`, `/api/web_fetch`) — see\n * `OllamaClient.webSearch`/`webFetch`. These are an Ollama Cloud service reachable only\n * at this host, independent of any locally-configured `baseUrl`/`endpoints`.\n */\nexport const OLLAMA_CLOUD_BASE_URL = 'https://ollama.com';\n\n/**\n * Reads a process environment variable, if any. Guarded with `typeof process` rather\n * than importing `node:process` so this stays safe to call from Edge Runtimes (Cloudflare\n * Workers, Vercel Edge) where `process` doesn't exist — it just returns `undefined` there.\n */\nfunction readEnv(name: string): string | undefined {\n return typeof process !== 'undefined' && process.env ? process.env[name] : undefined;\n}\n\n/**\n * Resolves the default single-endpoint `baseUrl`, falling back to the `OLLAMA_HOST`\n * environment variable (the same one the official `ollama` CLI and client libraries\n * read) before `DEFAULT_BASE_URL`. Explicit `config.baseUrl` always wins.\n */\nexport function resolveBaseUrl(configBaseUrl?: string | undefined): string {\n return configBaseUrl ?? readEnv('OLLAMA_HOST') ?? DEFAULT_BASE_URL;\n}\n\n/**\n * Resolves the default single-endpoint `apiKey`, falling back to the `OLLAMA_API_KEY`\n * environment variable before leaving it unset. Explicit `config.apiKey` always wins.\n */\nexport function resolveApiKey(configApiKey?: string | undefined): string | undefined {\n return configApiKey ?? readEnv('OLLAMA_API_KEY');\n}\n\n/** One named credential for the `credentials`/`modelBindings` config shape. */\nexport interface OllamaCredentialConfig {\n readonly apiKey: string;\n /** Overrides `OllamaClientConfig.baseUrl` for requests made with this credential. */\n readonly baseUrl?: string | undefined;\n readonly headers?: Record<string, string> | undefined;\n}\n\n/**\n * Builds synthetic `OllamaEndpoint`s (named `credential:<id>`) from `config.credentials` +\n * `config.modelBindings` — an ergonomic, map-based alternative to writing out `endpoints`\n * with per-entry `models` allow-lists directly. Both shapes feed the same\n * `EndpointRegistry`/`executeWithFailover` routing engine; this is pure config sugar, not\n * a separate routing mechanism. Returns `[]` if `config.credentials` is unset.\n *\n * A model bound to one credential (`modelBindings: { \"minimax-m3\": \"coder\" }`) scopes that\n * credential to only that model, same as `OllamaEndpoint.models`. A model bound to several\n * credentials (`modelBindings: { \"gpt-oss:120b\": [\"key1\", \"key2\"] }`) makes ordinary\n * endpoint failover apply between them. `config.defaultCredential`, if set, is given a\n * lower priority than explicitly-bound credentials and no `models` restriction, so it acts\n * as a catch-all for any model without an explicit binding without ever pre-empting one\n * that has.\n */\nexport function resolveCredentialEndpoints(\n config: Pick<OllamaClientConfig, 'credentials' | 'modelBindings' | 'defaultCredential' | 'baseUrl'>,\n): readonly OllamaEndpoint[] {\n if (config.credentials === undefined) return [];\n\n const modelsByCredential = new Map<string, string[]>();\n for (const [model, bound] of Object.entries(config.modelBindings ?? {})) {\n for (const id of typeof bound === 'string' ? [bound] : bound) {\n if (!(id in config.credentials)) {\n throw new Error(\n `modelBindings[\"${model}\"] references unknown credential \"${id}\" — it isn't ` +\n `in \\`credentials\\`. Known credentials: ${Object.keys(config.credentials).join(', ') || '(none)'}.`,\n );\n }\n const list = modelsByCredential.get(id) ?? [];\n list.push(model);\n modelsByCredential.set(id, list);\n }\n }\n\n return Object.entries(config.credentials).map(([id, credential]) => {\n const isDefault = id === config.defaultCredential;\n const boundModels = isDefault ? undefined : modelsByCredential.get(id);\n return {\n name: `credential:${id}`,\n baseUrl: resolveBaseUrl(credential.baseUrl ?? config.baseUrl),\n apiKey: credential.apiKey,\n ...(credential.headers !== undefined ? { headers: credential.headers } : {}),\n ...(boundModels !== undefined ? { models: boundModels } : {}),\n priority: isDefault ? -1 : 0,\n };\n });\n}\n\nexport const DEFAULT_FAILOVER_CODES: readonly string[] = [\n 'network_error',\n 'timeout',\n 'server_error',\n 'rate_limited',\n 'auth_error',\n // A candidate endpoint rejected the request pre-flight for a known-unsupported\n // capability (e.g. structured output against Ollama Cloud) — try the next candidate\n // rather than failing outright; see OllamaUnsupportedCapabilityError.\n 'unsupported_capability',\n];\n\nexport interface OllamaClientConfig {\n /**\n * Base URL of a single Ollama server. Ignored if `endpoints` is provided. Falls back to\n * the `OLLAMA_HOST` environment variable (when set and running under Node), then\n * `http://localhost:11434`.\n */\n readonly baseUrl?: string;\n /**\n * Bearer token sent as `Authorization: Bearer <apiKey>` for a single-endpoint setup.\n * Falls back to the `OLLAMA_API_KEY` environment variable (when set and running under\n * Node).\n */\n readonly apiKey?: string;\n /** Static headers merged into every request. */\n readonly headers?: Record<string, string>;\n /**\n * Multiple named endpoints for rotation and automatic failover. Each endpoint may\n * carry its own `apiKey` and, via `models`, be scoped to only the models that\n * credential is entitled to — see `OllamaEndpoint.models` for routing several\n * per-model Ollama Cloud API keys through a single client.\n */\n readonly endpoints?: readonly OllamaEndpoint[];\n /**\n * Named credentials, keyed by an id you choose — an ergonomic alternative to writing\n * out `endpoints` by hand for the common \"several Ollama Cloud API keys, each entitled\n * to different models\" shape. Combine with `modelBindings` to scope each credential to\n * the models it's authorized for; a credential with no binding (or set as\n * `defaultCredential`) is eligible for every model, same as an `OllamaEndpoint` with no\n * `models`. Merges additively with `endpoints` if both are given.\n */\n readonly credentials?: Readonly<Record<string, OllamaCredentialConfig>>;\n /**\n * Maps a model name to the `credentials` id (or ids, for several keys authorized for\n * the same model — ordinary failover applies between them) that may serve it. Has no\n * effect without `credentials`. Referencing an id not present in `credentials` throws\n * at construction time.\n */\n readonly modelBindings?: Readonly<Record<string, string | readonly string[]>>;\n /**\n * The `credentials` id to fall back to for a model with no entry in `modelBindings`.\n * Unset means such a model has no synthesized-from-`credentials` route — it still\n * routes normally through any plain `endpoints` entry without a `models` restriction.\n */\n readonly defaultCredential?: string | undefined;\n /**\n * Tuning options for the endpoint circuit breaker, and candidate selection ordering —\n * pass `{ strategy: 'round-robin' }` to spread requests across a pool of same-priority\n * endpoints/credentials (e.g. several unbound `credentials`) instead of always\n * preferring the first one, or `{ strategy: 'least-connections' }` to route each\n * request to whichever candidate currently has the fewest requests in flight (e.g.\n * several free-tier Ollama Cloud accounts, each capped at 1 concurrent request — this\n * deterministically spreads concurrent `Promise.all`-style calls one-per-account rather\n * than risking two landing on the same still-busy one), and `maxConcurrentPerEndpoint`\n * to cap that at an exact number and queue (rather than overrun a saturated candidate)\n * once every eligible one is at capacity — e.g. `{ strategy: 'least-connections',\n * maxConcurrentPerEndpoint: 1 }` for accounts that only allow one request at a time.\n * See `EndpointRegistryOptions`.\n */\n readonly endpointHealth?: EndpointRegistryOptions;\n /** Error codes that trigger failover to the next candidate endpoint. */\n readonly failoverOn?: readonly string[];\n /** Default per-request timeout in milliseconds (default 30_000ms). */\n readonly timeoutMs?: number;\n /** Retry configuration or retry count override. */\n readonly retries?: number | Partial<RetryConfig>;\n /** Custom fetch implementation (defaults to globalThis.fetch). */\n readonly fetch?: FetchLike;\n /** Request/Response middleware list. */\n readonly middleware?: readonly Middleware[];\n /** Structured logger. */\n readonly logger?: Logger;\n /** Enables console debug logger if true. */\n readonly debug?: boolean;\n /** Request lifecycle hook for telemetry/metrics. */\n readonly onLifecycleEvent?: RequestLifecycleHook;\n}\n","/**\n * Structured, typed error hierarchy for OllamaClient.\n */\n\nimport type { z } from 'zod';\n\nexport interface OllamaErrorRequestContext {\n readonly method?: string | undefined;\n readonly url?: string | undefined;\n readonly model?: string | undefined;\n}\n\nexport interface OllamaErrorResponseContext {\n readonly status?: number | undefined;\n readonly headers?: Record<string, string> | undefined;\n readonly body?: unknown;\n}\n\nexport interface OllamaClientErrorOptions extends ErrorOptions {\n readonly code: string;\n readonly status?: number | undefined;\n readonly retryable?: boolean | undefined;\n readonly request?: OllamaErrorRequestContext | undefined;\n readonly response?: OllamaErrorResponseContext | undefined;\n}\n\nexport class OllamaClientError extends Error {\n readonly code: string;\n readonly status?: number | undefined;\n readonly retryable: boolean;\n readonly request?: OllamaErrorRequestContext | undefined;\n readonly response?: OllamaErrorResponseContext | undefined;\n\n constructor(message: string, options: OllamaClientErrorOptions) {\n super(message, { cause: options.cause });\n this.name = this.constructor.name;\n this.code = options.code;\n this.status = options.status;\n this.retryable = options.retryable ?? false;\n this.request = options.request;\n this.response = options.response;\n }\n}\n\nexport class OllamaNetworkError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'network_error', retryable: true });\n }\n}\n\nexport class OllamaTimeoutError extends OllamaClientError {\n readonly timeoutMs?: number | undefined;\n constructor(\n message: string,\n options?:\n | (Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & { timeoutMs?: number | undefined })\n | undefined,\n ) {\n super(message, { ...options, code: 'timeout', retryable: true });\n this.timeoutMs = options?.timeoutMs;\n }\n}\n\nexport class OllamaAuthError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'auth_error', retryable: false });\n }\n}\n\nexport class OllamaNotFoundError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'not_found', retryable: false });\n }\n}\n\nexport class OllamaRateLimitError extends OllamaClientError {\n readonly retryAfterMs?: number | undefined;\n constructor(\n message: string,\n options?:\n | (Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n retryAfterMs?: number | undefined;\n })\n | undefined,\n ) {\n super(message, { ...options, code: 'rate_limited', retryable: true });\n this.retryAfterMs = options?.retryAfterMs;\n }\n}\n\n/**\n * Thrown client-side, before a network request is made, by `QuotaManager.assertCanProceed`\n * (see `src/quota.ts`) when issuing the request would exceed a configured usage budget for\n * one of its rolling windows. This is distinct from `OllamaRateLimitError`, which reflects\n * the server's own 429 response — Ollama Cloud does not expose account-level quota via the\n * API, so `QuotaManager` tracks usage against budgets the caller configures locally and\n * fails fast rather than waiting for the server to reject the request.\n */\nexport class OllamaQuotaExceededError extends OllamaClientError {\n readonly windowId: string;\n readonly resetAt: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n windowId: string;\n resetAt: number;\n },\n ) {\n super(message, { ...options, code: 'quota_exceeded', retryable: false });\n this.windowId = options.windowId;\n this.resetAt = options.resetAt;\n }\n}\n\nexport class OllamaServerError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'server_error', retryable: true });\n }\n}\n\nexport class OllamaAbortError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'aborted', retryable: false });\n }\n}\n\nexport class OllamaToolValidationError extends OllamaClientError {\n readonly toolName: string;\n readonly issues?: unknown;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & { toolName: string; issues?: unknown },\n ) {\n super(message, { ...options, code: 'tool_validation_error', retryable: false });\n this.toolName = options.toolName;\n this.issues = options.issues;\n }\n}\n\n/**\n * Thrown by `OllamaRuntime.invoke` when `validateRequests: true` is set and\n * the request body fails Zod validation against the operation's registered\n * schema. See ADR 0020 (runtime Zod validation).\n *\n * The error carries the original Zod issues so callers can inspect which\n * fields failed. No HTTP request is made when this error is thrown.\n */\nexport class OllamaRequestValidationError extends OllamaClientError {\n readonly operationId: string;\n readonly issues: readonly z.ZodIssue[];\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n operationId: string;\n issues: readonly z.ZodIssue[];\n },\n ) {\n super(message, { ...options, code: 'request_validation_error', retryable: false });\n this.operationId = options.operationId;\n this.issues = options.issues;\n }\n}\n\nexport class OllamaToolTimeoutError extends OllamaClientError {\n readonly toolName: string;\n readonly timeoutMs: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n toolName: string;\n timeoutMs: number;\n },\n ) {\n super(message, { ...options, code: 'tool_timeout', retryable: false });\n this.toolName = options.toolName;\n this.timeoutMs = options.timeoutMs;\n }\n}\n\n/**\n * Thrown client-side, before a network request is made, when a request asks for a\n * capability an endpoint is known not to support (e.g. structured output `format` against\n * an Ollama Cloud endpoint — see `ModelCapabilities.supportsStructuredOutputRequest` in\n * `src/capabilities/capabilities.ts`). Its `code` is included in `DEFAULT_FAILOVER_CODES`\n * by default, so in a multi-endpoint setup it causes failover to the next candidate rather\n * than failing outright — it only surfaces to the caller if every candidate is rejected.\n */\nexport class OllamaUnsupportedCapabilityError extends OllamaClientError {\n readonly capability: string;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & { capability: string },\n ) {\n super(message, { ...options, code: 'unsupported_capability', retryable: false });\n this.capability = options.capability;\n }\n}\n\n/**\n * Thrown client-side, before any network call, when `config.endpoints` uses\n * `OllamaEndpoint.models` to scope endpoints/credentials to specific models and the\n * requested `model` isn't in any configured endpoint's allow-list. This is a routing\n * misconfiguration, not a connectivity problem — the SDK deliberately does not \"probe\"\n * unauthorized endpoints to find one that happens to work (that would burn quota on keys\n * that were never entitled to the model and produce non-deterministic startup behavior).\n */\nexport class OllamaModelRoutingError extends OllamaClientError {\n readonly model: string;\n readonly availableModels: readonly string[];\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n model: string;\n availableModels: readonly string[];\n },\n ) {\n super(message, { ...options, code: 'model_routing_error', retryable: false });\n this.model = options.model;\n this.availableModels = options.availableModels;\n }\n}\n\n/**\n * Thrown before an agent tool loop starts when the selected model's /api/show metadata\n * does not advertise a capability required by the loop.\n */\nexport class OllamaIncompatibleModelError extends OllamaClientError {\n readonly model: string;\n readonly capability: string;\n readonly reportedCapabilities: readonly string[];\n\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n model: string;\n capability: string;\n reportedCapabilities: readonly string[];\n },\n ) {\n super(message, { ...options, code: 'incompatible_model', retryable: false });\n this.model = options.model;\n this.capability = options.capability;\n this.reportedCapabilities = options.reportedCapabilities;\n }\n}\nexport class OllamaAgentMaxToolCallsError extends OllamaClientError {\n readonly maxToolCalls: number;\n readonly toolCallsExecuted: number;\n\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n maxToolCalls: number;\n toolCallsExecuted: number;\n },\n ) {\n super(message, { ...options, code: 'agent_max_tool_calls_exceeded', retryable: false });\n this.maxToolCalls = options.maxToolCalls;\n this.toolCallsExecuted = options.toolCallsExecuted;\n }\n}\n\nexport class OllamaAgentMaxIterationsError extends OllamaClientError {\n readonly maxIterations: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & { maxIterations: number },\n ) {\n super(message, { ...options, code: 'agent_max_iterations_exceeded', retryable: false });\n this.maxIterations = options.maxIterations;\n }\n}\n\nexport class OllamaMcpError extends OllamaClientError {\n readonly mcpMethod:\n | 'listTools'\n | 'callTool'\n | 'tools/call'\n | 'tasks/get'\n | 'tasks/result'\n | 'tasks/cancel';\n readonly toolName?: string | undefined;\n readonly issues?: unknown;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n mcpMethod:\n | 'listTools'\n | 'callTool'\n | 'tools/call'\n | 'tasks/get'\n | 'tasks/result'\n | 'tasks/cancel';\n toolName?: string | undefined;\n issues?: unknown;\n },\n ) {\n super(message, { ...options, code: 'mcp_error', retryable: options.retryable ?? false });\n this.mcpMethod = options.mcpMethod;\n this.toolName = options.toolName;\n this.issues = options.issues;\n }\n}\n\nexport class OllamaSkillNotFoundError extends OllamaClientError {\n readonly skillName: string;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & { skillName: string },\n ) {\n super(message, { ...options, code: 'skill_not_found', retryable: false });\n this.skillName = options.skillName;\n }\n}\n\nexport class OllamaSkillInvalidError extends OllamaClientError {\n readonly skillName: string;\n readonly path?: string | undefined;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n skillName: string;\n path?: string | undefined;\n },\n ) {\n super(message, { ...options, code: 'skill_invalid', retryable: false });\n this.skillName = options.skillName;\n this.path = options.path;\n }\n}\n\nexport class OllamaGenericClientError extends OllamaClientError {\n constructor(message: string, options?: Omit<OllamaClientErrorOptions, 'code'> | undefined) {\n super(message, { ...options, code: 'client_error' });\n }\n}\n\nfunction isDomAbortError(error: unknown): error is DOMException {\n return (\n typeof DOMException !== 'undefined' &&\n error instanceof DOMException &&\n error.name === 'AbortError'\n );\n}\n\nfunction statusToError(\n status: number,\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'status'>,\n): OllamaClientError {\n if (status === 401 || status === 403) {\n return new OllamaAuthError(message, { ...options, status });\n }\n if (status === 404) {\n return new OllamaNotFoundError(message, { ...options, status });\n }\n if (status === 429) {\n return new OllamaRateLimitError(message, { ...options, status });\n }\n if (status >= 500) {\n return new OllamaServerError(message, { ...options, status });\n }\n return new OllamaGenericClientError(message, { ...options, status });\n}\n\n/**\n * Maps arbitrary thrown exceptions into structured OllamaClientError instances.\n */\nexport function mapError(\n error: unknown,\n context: {\n request?: OllamaErrorRequestContext | undefined;\n response?: OllamaErrorResponseContext | undefined;\n } = {},\n): OllamaClientError {\n if (error instanceof OllamaClientError) {\n return error;\n }\n if (isDomAbortError(error)) {\n return new OllamaAbortError(error.message || 'Request was aborted', {\n cause: error,\n request: context.request,\n });\n }\n if (error instanceof TypeError) {\n return new OllamaNetworkError(error.message || 'Network request failed', {\n cause: error,\n request: context.request,\n });\n }\n if (context.response?.status !== undefined) {\n const message = error instanceof Error ? error.message : String(error);\n return statusToError(context.response.status, message, {\n cause: error,\n request: context.request,\n response: context.response,\n });\n }\n const message = error instanceof Error ? error.message : String(error);\n return new OllamaGenericClientError(message, {\n cause: error,\n request: context.request,\n response: context.response,\n });\n}\n","/**\n * Structured logger and request lifecycle interfaces.\n */\n\nexport interface LogFn {\n (message: string, context?: Record<string, unknown>): void;\n}\n\nexport interface Logger {\n readonly debug: LogFn;\n readonly info: LogFn;\n readonly warn: LogFn;\n readonly error: LogFn;\n}\n\nexport interface LifecycleStartEvent {\n readonly type: 'start';\n readonly requestId: string;\n readonly method: string;\n readonly url: string;\n readonly timestamp: number;\n}\n\nexport interface LifecycleSuccessEvent {\n readonly type: 'success';\n readonly requestId: string;\n readonly durationMs: number;\n readonly status: number;\n readonly timestamp: number;\n}\n\nexport interface LifecycleRetryEvent {\n readonly type: 'retry';\n readonly requestId: string;\n readonly attempt: number;\n readonly error: Error;\n readonly delayMs: number;\n readonly timestamp: number;\n}\n\nexport interface LifecycleErrorEvent {\n readonly type: 'error';\n readonly requestId: string;\n readonly durationMs: number;\n readonly error: Error;\n readonly timestamp: number;\n}\n\nexport type RequestLifecycleEvent =\n LifecycleStartEvent | LifecycleSuccessEvent | LifecycleRetryEvent | LifecycleErrorEvent;\n\nexport interface RequestLifecycleHook {\n (event: RequestLifecycleEvent): void;\n}\n\nexport const NOOP_LOGGER: Logger = {\n debug: () => undefined,\n info: () => undefined,\n warn: () => undefined,\n error: () => undefined,\n};\n\nexport function createConsoleLogger(prefix = '[@nemesis-oss/ollama-sdk]'): Logger {\n return {\n debug: (msg, ctx) => console.debug(`${prefix} ${msg}`, ctx ?? ''),\n info: (msg, ctx) => console.info(`${prefix} ${msg}`, ctx ?? ''),\n warn: (msg, ctx) => console.warn(`${prefix} ${msg}`, ctx ?? ''),\n error: (msg, ctx) => console.error(`${prefix} ${msg}`, ctx ?? ''),\n };\n}\n","/**\n * Multi-endpoint registry with priority routing and circuit breaker failover.\n */\n\nimport { OllamaAbortError } from '../errors.js';\n\nexport interface OllamaEndpoint {\n readonly name: string;\n readonly baseUrl: string;\n readonly apiKey?: string | undefined;\n readonly headers?: Record<string, string> | undefined;\n readonly priority?: number | undefined;\n /**\n * Restricts this endpoint/credential to a specific set of models — for the common case\n * of several Ollama Cloud API keys, each entitled to a different model. When set,\n * `EndpointRegistry.candidates(model)` only returns this endpoint for a request whose\n * `model` is in the list, so cross-endpoint failover never retries a request against a\n * credential that isn't authorized for the requested model. Omit (the default) to make\n * the endpoint eligible for every model, preserving prior behavior.\n */\n readonly models?: readonly string[] | undefined;\n}\n\nexport interface EndpointHealth {\n readonly endpoint: OllamaEndpoint;\n readonly failureCount: number;\n readonly lastFailureTimestamp?: number | undefined;\n readonly isCoolingDown: boolean;\n /** In-flight requests currently attempting this endpoint — see `acquire`/`release`. */\n readonly activeRequests: number;\n}\n\nexport interface EndpointRegistryOptions {\n readonly failureThreshold?: number | undefined;\n readonly cooldownMs?: number | undefined;\n readonly now?: (() => number) | undefined;\n /**\n * How candidates that share the same `priority` are ordered within `candidates()`.\n * `'priority'` (the default) keeps them in registration order, so the same candidate is\n * always tried first while it stays healthy. `'round-robin'` rotates each same-priority\n * group by one position per `candidates()` call — i.e. per `chat`/`generate`/etc. call —\n * so consecutive requests spread across a pool of interchangeable endpoints/credentials\n * instead of always preferring the first one (the common case: several Ollama Cloud keys\n * registered with no `models` restriction, meant to be used interchangeably). Endpoints\n * at different priorities are unaffected either way — a higher-priority one is still\n * always tried first, and failover to the rest of the group still applies if the\n * rotated-to-front candidate fails.\n *\n * `'least-connections'` instead orders each same-priority group by ascending in-flight\n * request count (tracked via `acquire`/`release`, ties broken by registration order),\n * so a request always prefers whichever candidate currently has the fewest requests\n * still in progress. Unlike `'round-robin'`, this remains correct under uneven or\n * overlapping request durations — e.g. several Ollama Cloud accounts each limited to 1\n * concurrent request: firing several requests at once (`Promise.all`) deterministically\n * lands each on a different account rather than risking two landing on the same\n * still-busy one, because `candidates()` and the subsequent `acquire()` for the chosen\n * candidate run synchronously with no `await` in between — JS's single-threaded\n * execution means no two concurrent calls can observe the same \"0 active\" snapshot for\n * the same candidate.\n */\n readonly strategy?: 'priority' | 'round-robin' | 'least-connections' | undefined;\n /**\n * Caps in-flight requests per endpoint (tracked via `acquire`/`release`). Unset (the\n * default) means no cap — candidates are never treated as saturated. When set, a\n * request whose every otherwise-eligible candidate is already at this cap waits\n * (`waitForCapacity`, FIFO per candidate) for one of them to free up, instead of being\n * sent to an already-saturated candidate. Pairs naturally with `strategy:\n * 'least-connections'` for a pool of accounts each limited to N concurrent requests —\n * e.g. `maxConcurrentPerEndpoint: 1` for several Ollama Cloud free-tier accounts, so\n * `N + 1` concurrent calls against `N` such accounts run `N` immediately and queue the\n * rest, rather than the `(N+1)`th overrunning whichever account looks \"least busy\" at\n * that instant. Waiting is bounded by the request's own timeout/`AbortSignal`, same as\n * any other in-flight request — it never blocks indefinitely on its own.\n */\n readonly maxConcurrentPerEndpoint?: number | undefined;\n}\n\ninterface CapacityWaiter {\n readonly names: readonly string[];\n readonly resolve: () => void;\n cleanup: () => void;\n}\n\nexport class EndpointRegistry {\n private readonly endpoints: readonly OllamaEndpoint[];\n private readonly failureCounts = new Map<string, number>();\n private readonly lastFailures = new Map<string, number>();\n private readonly failureThreshold: number;\n private readonly cooldownMs: number;\n private readonly now: () => number;\n private readonly strategy: 'priority' | 'round-robin' | 'least-connections';\n private roundRobinCounter = 0;\n private readonly activeCounts = new Map<string, number>();\n private readonly maxConcurrentPerEndpoint: number | undefined;\n private readonly waiters: CapacityWaiter[] = [];\n\n constructor(endpoints: readonly OllamaEndpoint[], options: EndpointRegistryOptions = {}) {\n this.endpoints =\n endpoints.length > 0 ? endpoints : [{ name: 'default', baseUrl: 'http://localhost:11434' }];\n this.failureThreshold = options.failureThreshold ?? 3;\n this.cooldownMs = options.cooldownMs ?? 30_000;\n this.now = options.now ?? Date.now;\n this.strategy = options.strategy ?? 'priority';\n this.maxConcurrentPerEndpoint = options.maxConcurrentPerEndpoint;\n }\n\n /**\n * Marks one more request as in-flight against `name`. Callers (`OllamaClient`) must\n * pair every `acquire` with a `release` once that attempt finishes, success or not —\n * see `OllamaClient.executeWithFailover`. Only affects candidate ordering when\n * `strategy` is `'least-connections'`; harmless (just bookkeeping) otherwise, and\n * always reflected in `status()`'s `activeRequests`.\n */\n acquire(name: string): void {\n this.activeCounts.set(name, (this.activeCounts.get(name) ?? 0) + 1);\n }\n\n /** Releases one in-flight request marked via `acquire`, waking one waiter for `name` if any. */\n release(name: string): void {\n const next = (this.activeCounts.get(name) ?? 0) - 1;\n if (next <= 0) {\n this.activeCounts.delete(name);\n } else {\n this.activeCounts.set(name, next);\n }\n const idx = this.waiters.findIndex((w) => w.names.includes(name));\n if (idx !== -1) {\n const [waiter] = this.waiters.splice(idx, 1);\n waiter?.cleanup();\n waiter?.resolve();\n }\n }\n\n /**\n * `candidates` filtered down to those currently under `maxConcurrentPerEndpoint` (all\n * of them, unchanged, if that option is unset).\n */\n filterWithCapacity(candidates: readonly OllamaEndpoint[]): OllamaEndpoint[] {\n const cap = this.maxConcurrentPerEndpoint;\n if (cap === undefined) return [...candidates];\n return candidates.filter((ep) => (this.activeCounts.get(ep.name) ?? 0) < cap);\n }\n\n /**\n * Resolves once any endpoint named in `names` has spare capacity under\n * `maxConcurrentPerEndpoint` (a no-op resolve if that option is unset, or if one\n * already does). Otherwise queues (FIFO per name) until a matching `release()` frees a\n * slot, or rejects if `signal` aborts first — mirroring whatever aborted it\n * (`OllamaTimeoutError`/the caller's own abort reason) so callers see the same error\n * shape as any other in-flight request that times out or is cancelled. FIFO order is\n * best-effort (a newly-arriving request can still win a race for a slot that just\n * freed) — the capacity cap itself, not fairness, is the guarantee this exists for.\n */\n waitForCapacity(names: readonly string[], signal?: AbortSignal): Promise<void> {\n const cap = this.maxConcurrentPerEndpoint;\n if (cap === undefined) return Promise.resolve();\n if (names.some((n) => (this.activeCounts.get(n) ?? 0) < cap)) return Promise.resolve();\n\n return new Promise<void>((resolve, reject) => {\n const waiter: CapacityWaiter = { names, resolve, cleanup: () => undefined };\n const onAbort = (): void => {\n const idx = this.waiters.indexOf(waiter);\n if (idx !== -1) this.waiters.splice(idx, 1);\n reject(\n signal?.reason instanceof Error\n ? signal.reason\n : new OllamaAbortError('Aborted while waiting for endpoint capacity'),\n );\n };\n if (signal !== undefined) {\n if (signal.aborted) {\n onAbort();\n return;\n }\n signal.addEventListener('abort', onAbort, { once: true });\n waiter.cleanup = () => signal.removeEventListener('abort', onAbort);\n }\n this.waiters.push(waiter);\n });\n }\n\n /**\n * Rotates each same-`priority` group in `sorted` (already sorted highest-priority-first)\n * by one position further per call, wrapping around within the group. Priority tiers\n * themselves are never reordered — only candidates that were already tied.\n */\n private applyRoundRobin(sorted: readonly OllamaEndpoint[]): OllamaEndpoint[] {\n const offset = this.roundRobinCounter++;\n const result: OllamaEndpoint[] = [];\n let i = 0;\n while (i < sorted.length) {\n const priority = sorted[i]?.priority ?? 0;\n let j = i + 1;\n while (j < sorted.length && (sorted[j]?.priority ?? 0) === priority) j++;\n const tier = sorted.slice(i, j);\n const rotation = offset % tier.length;\n result.push(...tier.slice(rotation), ...tier.slice(0, rotation));\n i = j;\n }\n return result;\n }\n\n /**\n * Reorders each same-`priority` group in `sorted` by ascending in-flight request count\n * (from `acquire`/`release`); a stable sort, so candidates tied on active count keep\n * their relative (priority-then-registration) order. Priority tiers themselves are\n * never reordered.\n */\n private applyLeastConnections(sorted: readonly OllamaEndpoint[]): OllamaEndpoint[] {\n const result: OllamaEndpoint[] = [];\n let i = 0;\n while (i < sorted.length) {\n const priority = sorted[i]?.priority ?? 0;\n let j = i + 1;\n while (j < sorted.length && (sorted[j]?.priority ?? 0) === priority) j++;\n const tier = [...sorted.slice(i, j)].sort(\n (a, b) => (this.activeCounts.get(a.name) ?? 0) - (this.activeCounts.get(b.name) ?? 0),\n );\n result.push(...tier);\n i = j;\n }\n return result;\n }\n\n /**\n * Endpoints eligible for `model`, sorted healthy-first-by-priority (falling back to\n * soonest-to-recover if every eligible endpoint is cooling down); same-priority\n * candidates are further reordered per `options.strategy` (see\n * `EndpointRegistryOptions.strategy`). When `model` is given, endpoints whose `models`\n * allow-list doesn't include it are excluded entirely — see `OllamaEndpoint.models`.\n * Omit `model` to consider every configured endpoint, regardless of any `models`\n * restriction (used for non-model-scoped operations).\n */\n candidates(model?: string): OllamaEndpoint[] {\n const currentTime = this.now();\n const scoped =\n model === undefined\n ? this.endpoints\n : this.endpoints.filter((ep) => ep.models === undefined || ep.models.includes(model));\n const healthy: OllamaEndpoint[] = [];\n const coolingDown: Array<{ endpoint: OllamaEndpoint; recoveredAt: number }> = [];\n\n for (const ep of scoped) {\n const failures = this.failureCounts.get(ep.name) ?? 0;\n const lastFail = this.lastFailures.get(ep.name) ?? 0;\n const isCooling =\n failures >= this.failureThreshold && currentTime - lastFail < this.cooldownMs;\n\n if (!isCooling) {\n healthy.push(ep);\n } else {\n coolingDown.push({ endpoint: ep, recoveredAt: lastFail + this.cooldownMs });\n }\n }\n\n if (healthy.length > 0) {\n const sorted = healthy.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));\n if (this.strategy === 'round-robin') return this.applyRoundRobin(sorted);\n if (this.strategy === 'least-connections') return this.applyLeastConnections(sorted);\n return sorted;\n }\n\n // Fail-open: sort by soonest-to-recover\n return coolingDown.sort((a, b) => a.recoveredAt - b.recoveredAt).map((c) => c.endpoint);\n }\n\n reportSuccess(name: string): void {\n this.failureCounts.delete(name);\n this.lastFailures.delete(name);\n }\n\n reportFailure(name: string): void {\n const current = (this.failureCounts.get(name) ?? 0) + 1;\n this.failureCounts.set(name, current);\n this.lastFailures.set(name, this.now());\n }\n\n list(): readonly OllamaEndpoint[] {\n return this.endpoints;\n }\n\n /** True if any configured endpoint restricts itself to a `models` allow-list. */\n hasModelScopedEndpoints(): boolean {\n return this.endpoints.some((ep) => ep.models !== undefined);\n }\n\n status(): EndpointHealth[] {\n const currentTime = this.now();\n return this.endpoints.map((ep) => {\n const failures = this.failureCounts.get(ep.name) ?? 0;\n const lastFail = this.lastFailures.get(ep.name);\n const isCoolingDown =\n failures >= this.failureThreshold &&\n lastFail !== undefined &&\n currentTime - lastFail < this.cooldownMs;\n\n return {\n endpoint: ep,\n failureCount: failures,\n ...(lastFail !== undefined ? { lastFailureTimestamp: lastFail } : {}),\n isCoolingDown,\n activeRequests: this.activeCounts.get(ep.name) ?? 0,\n };\n });\n }\n}\n","/**\n * Request/response middleware pipeline.\n */\n\nexport interface RequestContext {\n readonly url: string;\n readonly method: string;\n readonly headers: Record<string, string>;\n readonly body?: unknown;\n readonly signal?: AbortSignal;\n}\n\nexport interface ResponseContext {\n readonly status: number;\n readonly headers: Record<string, string>;\n readonly body: unknown;\n}\n\nexport type NextFunction = () => Promise<ResponseContext>;\n\nexport interface MiddlewareContext {\n readonly request: RequestContext;\n readonly next: NextFunction;\n}\n\nexport interface Middleware {\n (ctx: MiddlewareContext): Promise<ResponseContext>;\n}\n\nexport function composeMiddleware(\n middlewares: readonly Middleware[],\n finalHandler: (req: RequestContext) => Promise<ResponseContext>,\n): (req: RequestContext) => Promise<ResponseContext> {\n return function runPipeline(initialRequest: RequestContext): Promise<ResponseContext> {\n let index = -1;\n\n function dispatch(i: number, currentRequest: RequestContext): Promise<ResponseContext> {\n if (i <= index) {\n return Promise.reject(new Error('next() called multiple times in middleware'));\n }\n index = i;\n const fn = middlewares[i];\n if (i === middlewares.length || !fn) {\n return finalHandler(currentRequest);\n }\n return fn({\n request: currentRequest,\n next: () => dispatch(i + 1, currentRequest),\n });\n }\n\n return dispatch(0, initialRequest);\n };\n}\n","/**\n * Cross-runtime helpers with no Node.js API dependency, so they stay safe to import from\n * the core client bundle (see ADR 0006 — Edge Runtime CI).\n */\n\n/**\n * Encodes an image to a base64 string, matching the wire format Ollama's `/api/chat` and\n * `/api/generate` `images` arrays expect.\n *\n * - A `string` is assumed to already be base64-encoded and is returned unchanged.\n * - A `Uint8Array` is base64-encoded using whichever universal primitive the runtime\n * exposes: `Buffer` on Node.js, `btoa` on browsers/Edge runtimes. Chunked so it doesn't\n * blow the engine's max call-stack/argument-count limits on large images.\n */\nexport async function encodeImage(image: Uint8Array | string): Promise<string> {\n if (typeof image === 'string') return image;\n\n const bufferCtor = (\n globalThis as { Buffer?: { from(data: Uint8Array): { toString(encoding: string): string } } }\n ).Buffer;\n if (bufferCtor !== undefined) return bufferCtor.from(image).toString('base64');\n\n const CHUNK_SIZE = 0x8000;\n let binary = '';\n for (let i = 0; i < image.length; i += CHUNK_SIZE) {\n binary += String.fromCharCode(...image.subarray(i, i + CHUNK_SIZE));\n }\n return btoa(binary);\n}\n\nasync function encodeImages(\n images: readonly (string | Uint8Array)[] | undefined,\n): Promise<readonly string[] | undefined> {\n if (images === undefined) return undefined;\n return Promise.all(images.map((image) => encodeImage(image)));\n}\n\n/**\n * Returns `req` unchanged if `req.images` has no `Uint8Array` entries (the common case),\n * otherwise a shallow copy with `images` base64-encoded. Keeps `chat`/`generate` request\n * bodies wire-compatible without requiring callers to pre-encode raw image bytes.\n */\nexport async function withEncodedImages<\n T extends { images?: readonly (string | Uint8Array)[] | undefined },\n>(req: T): Promise<T> {\n if (!req.images?.some((image) => image instanceof Uint8Array)) return req;\n return { ...req, images: await encodeImages(req.images) };\n}\n\n/**\n * Applies {@link withEncodedImages} to each message's `images` array. Returns `messages`\n * unchanged (same reference) if no message carries a `Uint8Array` image.\n */\nexport async function withEncodedMessageImages<\n T extends { images?: readonly (string | Uint8Array)[] | undefined },\n>(messages: readonly T[]): Promise<readonly T[]> {\n if (!messages.some((message) => message.images?.some((image) => image instanceof Uint8Array)))\n return messages;\n return Promise.all(messages.map((message) => withEncodedImages(message)));\n}\n\n// ─── Disposable helpers (TS 5.2+ `using` declarations) ──────────────────\n//\n// These wrappers turn cleanup operations into `Disposable` / `AsyncDisposable`\n// values so callers can use `using` / `await using` declarations instead of\n// try/finally blocks. This eliminates the \"forgot to clean up in the finally\n// block\" bug class for timer, reader, and span lifecycles.\n\n/** Wraps a `setTimeout` handle so `clearTimeout` runs at scope exit. */\nexport function disposableTimer(timer: ReturnType<typeof setTimeout>): Disposable {\n return {\n [Symbol.dispose]() {\n clearTimeout(timer);\n },\n };\n}\n\n/** Wraps a `ReadableStreamDefaultReader` so `cancel()` + `releaseLock()` run at scope exit. */\nexport function disposableReader<T>(reader: ReadableStreamDefaultReader<T>): AsyncDisposable {\n return {\n async [Symbol.asyncDispose]() {\n try {\n await reader.cancel();\n } catch {\n /* stream may already be closed */\n }\n reader.releaseLock();\n },\n };\n}\n\n/** Wraps an OpenTelemetry span so `span.end()` runs at scope exit. */\nexport function disposableSpan(span: { end(): void }): Disposable {\n return {\n [Symbol.dispose]() {\n span.end();\n },\n };\n}\n","/**\n * NDJSON (newline-delimited JSON) stream reader for native fetch Response bodies.\n */\n\nimport { OllamaGenericClientError } from '../errors.js';\nimport { disposableReader } from '../utils.js';\n\n/**\n * Parses a byte stream from fetch body into an async generator of typed JSON chunks.\n */\nexport async function* parseNdjsonStream<T>(\n stream: ReadableStream<Uint8Array>,\n): AsyncGenerator<T, void, undefined> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n await using _reader = disposableReader(reader);\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n // Keep the last partial line in buffer\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n yield JSON.parse(trimmed) as T;\n } catch (err) {\n throw new OllamaGenericClientError(`Failed to parse stream JSON chunk: ${trimmed}`, {\n cause: err,\n });\n }\n }\n }\n\n if (buffer.trim()) {\n yield JSON.parse(buffer.trim()) as T;\n }\n // reader.cancel() + reader.releaseLock() called automatically via `await using _reader`\n}\n","/**\n * Server-Sent Events (SSE) parser for OpenAI/Anthropic-compatible streaming endpoints.\n *\n * Implements standard event-stream field rules without coupling the parser to\n * any provider-specific event schema.\n */\n\nimport { disposableReader } from '../utils.js';\n\nexport interface SseEvent {\n /** Event type; omitted when the server emitted no explicit event field. */\n readonly event?: string | undefined;\n /** Event data with consecutive data fields joined by a newline. */\n readonly data: string;\n /** Last event id associated with this dispatch, when present. */\n readonly id?: string | undefined;\n /** Reconnection delay requested by the server, in milliseconds, when valid. */\n readonly retry?: number | undefined;\n}\n\nfunction dispatch(\n event: string | undefined,\n data: string[],\n id: string | undefined,\n retry: number | undefined,\n): SseEvent | undefined {\n if (data.length === 0) return undefined;\n\n const joined = data.join('\\n');\n return {\n ...(event !== undefined ? { event } : {}),\n data: joined.endsWith('\\n') ? joined.slice(0, -1) : joined,\n ...(id !== undefined ? { id } : {}),\n ...(retry !== undefined ? { retry } : {}),\n };\n}\n\n/**\n * Parses an SSE byte stream into discrete events.\n *\n * Supports CRLF, CR, and LF line endings; comments; repeated data fields;\n * event/id/retry fields; UTF-8 chunks split across arbitrary byte boundaries;\n * and a terminal event without a trailing blank line.\n */\nexport async function* parseSseStream(\n stream: ReadableStream<Uint8Array>,\n): AsyncGenerator<SseEvent, void, undefined> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n\n let buffer = '';\n let eventType: string | undefined;\n let data: string[] = [];\n let lastEventId: string | undefined;\n let retry: number | undefined;\n\n const processLine = (line: string): SseEvent | undefined => {\n if (line.length === 0) {\n const event = dispatch(eventType, data, lastEventId, retry);\n eventType = undefined;\n data = [];\n retry = undefined;\n return event;\n }\n\n if (line.startsWith(':')) return undefined;\n\n const separator = line.indexOf(':');\n const field = separator === -1 ? line : line.slice(0, separator);\n let value = separator === -1 ? '' : line.slice(separator + 1);\n if (value.startsWith(' ')) value = value.slice(1);\n\n switch (field) {\n case 'event':\n eventType = value;\n break;\n case 'data':\n data.push(value);\n break;\n case 'id':\n if (!value.includes('\\0')) lastEventId = value;\n break;\n case 'retry': {\n if (/^\\d+$/.test(value)) {\n const parsed = Number(value);\n if (Number.isSafeInteger(parsed)) retry = parsed;\n }\n break;\n }\n default:\n break;\n }\n\n return undefined;\n };\n\n await using _reader = disposableReader(reader);\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n\n while (true) {\n const lf = buffer.indexOf('\\n');\n const cr = buffer.indexOf('\\r');\n if (lf === -1 && cr === -1) break;\n // A CR may be the first half of a CRLF sequence split across two network chunks.\n if (cr !== -1 && lf === -1 && cr === buffer.length - 1) break;\n\n const lineEnd = lf === -1 ? cr : cr === -1 ? lf : Math.min(lf, cr);\n let separatorLength = 1;\n\n if (buffer[lineEnd] === '\\r' && buffer[lineEnd + 1] === '\\n') {\n separatorLength = 2;\n }\n\n const line = buffer.slice(0, lineEnd);\n buffer = buffer.slice(lineEnd + separatorLength);\n\n const event = processLine(line);\n if (event) yield event;\n }\n }\n\n buffer += decoder.decode();\n if (buffer.length > 0) {\n const event = processLine(buffer);\n if (event) yield event;\n }\n\n const terminal = dispatch(eventType, data, lastEventId, retry);\n if (terminal) yield terminal;\n // reader.cancel() + reader.releaseLock() called automatically via `await using _reader`\n}\n","/**\n * Optional OpenTelemetry tracing.\n *\n * `@opentelemetry/api` is an optional peer dependency. When it isn't installed, or when\n * the host process hasn't registered a global TracerProvider, `withSpan` degrades to\n * invoking its callback directly — no spans, no exporters, nothing beyond one cached\n * dynamic `import()` attempt. Once a consumer wires up an OpenTelemetry SDK, spans for\n * HTTP requests, endpoint failover attempts, agent turns, and tool calls appear\n * automatically without any configuration on this SDK's side.\n */\n\nimport type * as Otel from '@opentelemetry/api';\nimport { disposableSpan } from '../utils.js';\n\nexport type SpanAttributeValue = string | number | boolean;\nexport type SpanAttributes = Record<string, SpanAttributeValue | undefined>;\n\nconst INSTRUMENTATION_NAME = '@nemesis-oss/ollama-sdk';\nconst INSTRUMENTATION_VERSION = '1.0.0';\n\nlet apiPromise: Promise<typeof Otel | undefined> | undefined;\n\nfunction loadApi(): Promise<typeof Otel | undefined> {\n apiPromise ??= import('@opentelemetry/api').catch(() => undefined);\n return apiPromise;\n}\n\nfunction cleanAttributes(attributes: SpanAttributes): Record<string, SpanAttributeValue> {\n const clean: Record<string, SpanAttributeValue> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (value !== undefined) {\n clean[key] = value;\n }\n }\n return clean;\n}\n\n/**\n * Runs `fn` inside an active OpenTelemetry span named `name`, when OpenTelemetry is\n * available. `fn` receives the live span (to add events/attributes as work proceeds) or\n * `undefined` when tracing is a no-op. Exceptions from `fn` are recorded on the span,\n * marked as an error status, and re-thrown unchanged; the span always ends.\n *\n * On success the span status is left `Unset` rather than forced to `Ok` — per the\n * OpenTelemetry spec, `Ok` is final and silently suppresses any later `Error` status.\n * Some call sites (e.g. tool execution, which reports failure via a return value rather\n * than a throw) need to mark a successfully-*returned* span as an error after the fact,\n * via `setSpanError`; leaving success as `Unset` keeps that possible. Backends treat\n * `Unset` the same as `Ok` for filtering purposes.\n */\nexport async function withSpan<T>(\n name: string,\n attributes: SpanAttributes,\n fn: (span: Otel.Span | undefined) => Promise<T>,\n): Promise<T> {\n const api = await loadApi();\n if (!api) {\n return fn(undefined);\n }\n\n const tracer = api.trace.getTracer(INSTRUMENTATION_NAME, INSTRUMENTATION_VERSION);\n return tracer.startActiveSpan(name, async (span) => {\n span.setAttributes(cleanAttributes(attributes));\n using _span = disposableSpan(span);\n try {\n return await fn(span);\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n span.recordException(error);\n span.setStatus({ code: api.SpanStatusCode.ERROR, message: error.message });\n throw error;\n }\n // span.end() called automatically via `using _span` at scope exit\n });\n}\n\n/** Adds an attribute/event to `span` if tracing is active; a cheap no-op otherwise. */\nexport function addSpanEvent(\n span: Otel.Span | undefined,\n name: string,\n attributes?: SpanAttributes,\n): void {\n span?.addEvent(name, attributes ? cleanAttributes(attributes) : undefined);\n}\n\n/**\n * Marks a span as failed without throwing — for operations (like tool execution) that\n * report failure through a return value rather than an exception. No-ops when tracing\n * is inactive.\n */\nexport async function setSpanError(span: Otel.Span | undefined, error: Error): Promise<void> {\n if (!span) {\n return;\n }\n const api = await loadApi();\n span.recordException(error);\n span.setStatus({ code: api?.SpanStatusCode.ERROR ?? 2, message: error.message });\n}\n\n// --- Semantic convention attribute keys used by this SDK's instrumentation ---\n// https://opentelemetry.io/docs/specs/semconv/http/http-spans/\nexport const ATTR_HTTP_REQUEST_METHOD = 'http.request.method';\nexport const ATTR_URL_FULL = 'url.full';\nexport const ATTR_SERVER_ADDRESS = 'server.address';\nexport const ATTR_SERVER_PORT = 'server.port';\nexport const ATTR_HTTP_RESPONSE_STATUS_CODE = 'http.response.status_code';\n\n// https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/\nexport const ATTR_GEN_AI_SYSTEM = 'gen_ai.system';\nexport const ATTR_GEN_AI_OPERATION_NAME = 'gen_ai.operation.name';\nexport const ATTR_GEN_AI_REQUEST_MODEL = 'gen_ai.request.model';\nexport const ATTR_GEN_AI_RESPONSE_MODEL = 'gen_ai.response.model';\nexport const ATTR_GEN_AI_USAGE_INPUT_TOKENS = 'gen_ai.usage.input_tokens';\nexport const ATTR_GEN_AI_USAGE_OUTPUT_TOKENS = 'gen_ai.usage.output_tokens';\nexport const ATTR_GEN_AI_TOOL_NAME = 'gen_ai.tool.name';\nexport const ATTR_GEN_AI_TOOL_CALL_ID = 'gen_ai.tool.call.id';\n\n// Attributes specific to this SDK's failover/agent model (no matching semconv entry).\nexport const ATTR_OLLAMA_ENDPOINT_NAME = 'ollama.endpoint.name';\nexport const ATTR_OLLAMA_ENDPOINT_ATTEMPT = 'ollama.endpoint.attempt';\nexport const ATTR_OLLAMA_AGENT_MAX_ITERATIONS = 'ollama.agent.max_iterations';\nexport const ATTR_OLLAMA_AGENT_ITERATION = 'ollama.agent.iteration';\nexport const GEN_AI_SYSTEM_OLLAMA = 'ollama';\n","/**\n * Native fetch HTTP transport client for Ollama API.\n */\n\nimport { mapError } from '../errors.js';\nimport { composeMiddleware, type Middleware, type RequestContext } from '../middleware.js';\nimport type { RequestLifecycleHook } from '../logger.js';\nimport { parseNdjsonStream } from '../streaming/ndjson.js';\nimport { parseSseStream, type SseEvent } from '../streaming/sse.js';\nimport type { AbortableAsyncIterable } from '../streaming/types.js';\nimport {\n withSpan,\n ATTR_HTTP_REQUEST_METHOD,\n ATTR_URL_FULL,\n ATTR_SERVER_ADDRESS,\n ATTR_SERVER_PORT,\n ATTR_HTTP_RESPONSE_STATUS_CODE,\n type SpanAttributes,\n} from '../telemetry/index.js';\n\n/** Collapses path segments with high-cardinality values (e.g. blob digests) for span names. */\nfunction routeTemplate(path: string): string {\n return path.replace(/^\\/api\\/blobs\\/.+$/, '/api/blobs/{digest}');\n}\n\nfunction httpSpanAttributes(method: string, url: string): SpanAttributes {\n const target = new URL(url);\n return {\n [ATTR_HTTP_REQUEST_METHOD]: method,\n [ATTR_URL_FULL]: url,\n [ATTR_SERVER_ADDRESS]: target.hostname,\n [ATTR_SERVER_PORT]: target.port ? Number(target.port) : undefined,\n };\n}\n\nexport type FetchLike = typeof globalThis.fetch;\nexport type BinaryBody = Uint8Array | ArrayBuffer | string | Blob | ReadableStream<Uint8Array>;\nexport type HttpBody = unknown;\n\nlet requestSequence = 0;\n\nfunction createRequestId(): string {\n requestSequence += 1;\n return `ollama-http-${requestSequence}`;\n}\n\nfunction sameHeaders(actual: Record<string, string>, expected: Headers): boolean {\n const actualEntries = Object.fromEntries(\n Object.entries(actual).map(([key, value]) => [key.toLowerCase(), value]),\n );\n const expectedEntries = Object.fromEntries(expected.entries());\n const actualKeys = Object.keys(actualEntries);\n const expectedKeys = Object.keys(expectedEntries);\n return (\n actualKeys.length === expectedKeys.length &&\n expectedKeys.every((key) => actualEntries[key] === expectedEntries[key])\n );\n}\n\nexport interface HttpClientOptions {\n readonly baseUrl: string;\n readonly apiKey?: string | undefined;\n readonly headers?: Record<string, string> | undefined;\n readonly fetch?: FetchLike | undefined;\n readonly middleware?: readonly Middleware[] | undefined;\n readonly onLifecycleEvent?: RequestLifecycleHook | undefined;\n /** Reuse a logical request id across endpoint failover/retry attempts. */\n readonly requestId?: string | undefined;\n}\n\nexport interface HttpRequestOptions {\n readonly path: string;\n readonly method?: 'GET' | 'POST' | 'DELETE' | 'HEAD' | undefined;\n readonly body?: HttpBody;\n readonly rawBody?: BinaryBody | undefined;\n readonly headers?: Record<string, string> | undefined;\n readonly signal?: AbortSignal | undefined;\n /**\n * When `true`, return the raw {@link Response} object instead of parsing\n * the body as JSON. Used by callers that need direct access to the\n * streaming body (e.g. {@link src/generated/runtime/runtime.ts} for\n * NDJSON streaming through the runtime seam).\n *\n * The returned `Response` is the same one middleware/retry/telemetry\n * have already processed, so this option does NOT bypass any of the\n * transport-layer concerns.\n */\n readonly raw?: boolean | undefined;\n}\n\nexport class HttpClient {\n readonly baseUrl: string;\n private readonly apiKey?: string | undefined;\n private readonly defaultHeaders: Record<string, string>;\n private readonly fetchImpl: FetchLike;\n private readonly middleware: readonly Middleware[];\n private readonly onLifecycleEvent: RequestLifecycleHook | undefined;\n private readonly requestId?: string | undefined;\n\n constructor(options: HttpClientOptions) {\n this.baseUrl = options.baseUrl.replace(/\\/+$/, '');\n this.apiKey = options.apiKey;\n this.defaultHeaders = options.headers ?? {};\n this.fetchImpl = options.fetch ?? globalThis.fetch;\n this.middleware = options.middleware ?? [];\n this.onLifecycleEvent = options.onLifecycleEvent;\n this.requestId = options.requestId;\n }\n\n private buildHeaders(customHeaders?: Record<string, string> | undefined): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...this.defaultHeaders,\n ...customHeaders,\n };\n if (this.apiKey) {\n headers['Authorization'] = `Bearer ${this.apiKey}`;\n }\n return headers;\n }\n\n private async fetchWithMiddleware(request: RequestContext): Promise<Response> {\n const requestId = this.requestId ?? createRequestId();\n const startedAt = Date.now();\n let rawResponse: unknown;\n this.onLifecycleEvent?.({\n type: 'start',\n requestId,\n method: request.method,\n url: request.url,\n timestamp: startedAt,\n });\n\n const finalHandler = async (req: RequestContext): Promise<{\n status: number;\n headers: Record<string, string>;\n body: Response;\n }> => {\n const init: RequestInit = {\n method: req.method,\n headers: req.headers,\n ...(req.body !== undefined ? { body: req.body as NonNullable<RequestInit['body']> } : {}),\n ...(req.signal !== undefined ? { signal: req.signal } : {}),\n };\n const response = await this.fetchImpl(req.url, init);\n rawResponse = response;\n const responseHeaders =\n response.headers && typeof response.headers.entries === 'function'\n ? Object.fromEntries(response.headers.entries())\n : {};\n return {\n status: response.status,\n headers: responseHeaders,\n body: response,\n };\n };\n\n try {\n if (this.middleware.length === 0) {\n const response = await this.fetchImpl(request.url, {\n method: request.method,\n headers: request.headers,\n ...(request.body !== undefined\n ? { body: request.body as NonNullable<RequestInit['body']> }\n : {}),\n ...(request.signal !== undefined ? { signal: request.signal } : {}),\n });\n if (response.status >= 200 && response.status < 300) {\n this.onLifecycleEvent?.({\n type: 'success',\n requestId,\n durationMs: Date.now() - startedAt,\n status: response.status,\n timestamp: Date.now(),\n });\n } else {\n this.onLifecycleEvent?.({\n type: 'error',\n requestId,\n durationMs: Date.now() - startedAt,\n error: mapError(new Error(`HTTP ${response.status}`), {\n request: { method: request.method, url: request.url },\n response: { status: response.status },\n }),\n timestamp: Date.now(),\n });\n }\n return response;\n }\n\n const pipeline = composeMiddleware(this.middleware, finalHandler);\n const context = await pipeline(request);\n\n let response: Response;\n if (rawResponse !== undefined && context.body === rawResponse) {\n response = rawResponse as Response;\n if (\n context.status !== response.status ||\n !sameHeaders(context.headers, response.headers)\n ) {\n const cloned = response.clone();\n response = new Response(cloned.body, {\n status: context.status,\n headers: context.headers,\n });\n }\n } else if (context.body instanceof Response) {\n if (\n context.status === context.body.status &&\n sameHeaders(context.headers, context.body.headers)\n ) {\n response = context.body;\n } else {\n const cloned = context.body.clone();\n response = new Response(cloned.body, {\n status: context.status,\n headers: context.headers,\n });\n }\n } else if (\n context.body === undefined ||\n typeof context.body === 'string' ||\n context.body instanceof ArrayBuffer ||\n ArrayBuffer.isView(context.body) ||\n context.body instanceof Blob ||\n context.body instanceof ReadableStream\n ) {\n response = new Response(context.body as RequestInit['body'], {\n status: context.status,\n headers: context.headers,\n });\n } else {\n response = new Response(JSON.stringify(context.body), {\n status: context.status,\n headers: context.headers,\n });\n }\n\n if (context.status >= 200 && context.status < 300) {\n this.onLifecycleEvent?.({\n type: 'success',\n requestId,\n durationMs: Date.now() - startedAt,\n status: context.status,\n timestamp: Date.now(),\n });\n } else {\n this.onLifecycleEvent?.({\n type: 'error',\n requestId,\n durationMs: Date.now() - startedAt,\n error: mapError(new Error(`HTTP ${context.status}`), {\n request: { method: request.method, url: request.url },\n response: { status: context.status, headers: context.headers },\n }),\n timestamp: Date.now(),\n });\n }\n return response;\n } catch (error) {\n const mapped = mapError(error, {\n request: { method: request.method, url: request.url },\n });\n this.onLifecycleEvent?.({\n type: 'error',\n requestId,\n durationMs: Date.now() - startedAt,\n error: mapped,\n timestamp: Date.now(),\n });\n throw mapped;\n }\n }\n\n async request<T>(options: HttpRequestOptions): Promise<T> {\n const url = `${this.baseUrl}${options.path}`;\n const method =\n options.method ??\n (options.body !== undefined || options.rawBody !== undefined ? 'POST' : 'GET');\n const headers = this.buildHeaders(options.headers);\n\n if (options.rawBody !== undefined && !options.headers?.['Content-Type']) {\n delete headers['Content-Type'];\n }\n\n return withSpan(\n `${method} ${routeTemplate(options.path)}`,\n httpSpanAttributes(method, url),\n async (span) => {\n try {\n const bodyInit =\n options.rawBody !== undefined\n ? (options.rawBody as never)\n : options.body !== undefined\n ? JSON.stringify(options.body)\n : undefined;\n\n const response = await this.fetchWithMiddleware({\n url,\n method,\n headers,\n ...(bodyInit !== undefined ? { body: bodyInit } : {}),\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n });\n span?.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, response.status);\n\n if (!response.ok) {\n let errorBody: unknown;\n try {\n errorBody = await response.json();\n } catch {\n errorBody = await response.text();\n }\n const message =\n typeof errorBody === 'object' && errorBody !== null && 'error' in errorBody\n ? String((errorBody as { error: unknown }).error)\n : `HTTP ${response.status} ${response.statusText}`;\n\n throw mapError(new Error(message), {\n request: { method, url },\n response: { status: response.status, body: errorBody },\n });\n }\n\n if (options.method === 'HEAD' || response.status === 204) {\n return undefined as T;\n }\n\n // Raw mode: return the Response object directly so callers can\n // access the streaming body. Middleware, retry, telemetry, and\n // error-mapping have already run by this point.\n if (options.raw === true) {\n return response as unknown as T;\n }\n\n if (typeof response.text === 'function') {\n const text = await response.text();\n return (text ? JSON.parse(text) : undefined) as T;\n }\n if (typeof response.json === 'function') {\n return (await response.json()) as T;\n }\n return undefined as T;\n } catch (err) {\n throw mapError(err, { request: { method, url } });\n }\n },\n );\n }\n\n /**\n * Opens an event-stream response and exposes parsed SSE events.\n *\n * This is intentionally schema-agnostic so OpenAI and Anthropic compatibility layers\n * can decode their provider-specific event payloads without duplicating transport logic.\n */\n async requestSseStream(options: HttpRequestOptions): Promise<AbortableAsyncIterable<SseEvent>> {\n const url = `${this.baseUrl}${options.path}`;\n const method = options.method ?? 'POST';\n const headers = {\n ...this.buildHeaders(options.headers),\n Accept: 'text/event-stream',\n };\n\n return withSpan(\n `${method} ${routeTemplate(options.path)}`,\n httpSpanAttributes(method, url),\n async (span) => {\n try {\n const controller = new AbortController();\n const removeAbortListener =\n options.signal !== undefined\n ? (() => {\n if (options.signal.aborted) {\n controller.abort(options.signal.reason);\n } else {\n const onAbort = (): void => controller.abort(options.signal?.reason);\n options.signal.addEventListener('abort', onAbort, { once: true });\n return () => options.signal?.removeEventListener('abort', onAbort);\n }\n return undefined;\n })()\n : undefined;\n\n const response = await this.fetchWithMiddleware({\n url,\n method,\n headers,\n ...(options.body !== undefined ? { body: JSON.stringify(options.body) } : {}),\n signal: controller.signal,\n });\n span?.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, response.status);\n\n if (!response.ok) {\n removeAbortListener?.();\n const errorText = await response.text();\n throw mapError(new Error(errorText || `HTTP ${response.status}`), {\n request: { method, url },\n response: { status: response.status, body: errorText },\n });\n }\n\n if (!response.body) {\n removeAbortListener?.();\n throw mapError(new Error('Response body is null, cannot stream SSE'), {\n request: { method, url },\n });\n }\n\n const stream = (async function* (): AsyncGenerator<SseEvent, void, undefined> {\n try {\n yield* parseSseStream(response.body!);\n } finally {\n removeAbortListener?.();\n }\n })();\n\n return {\n [Symbol.asyncIterator]() {\n return stream[Symbol.asyncIterator]();\n },\n abort: () => {\n removeAbortListener?.();\n controller.abort();\n },\n } as AbortableAsyncIterable<SseEvent>;\n } catch (err) {\n throw mapError(err, { request: { method, url } });\n }\n },\n );\n }\n\n async requestStream<T>(options: HttpRequestOptions): Promise<AbortableAsyncIterable<T>> {\n const url = `${this.baseUrl}${options.path}`;\n const method = options.method ?? 'POST';\n const headers = this.buildHeaders(options.headers);\n\n return withSpan(\n `${method} ${routeTemplate(options.path)}`,\n httpSpanAttributes(method, url),\n async (span) => {\n try {\n const controller = new AbortController();\n const removeAbortListener =\n options.signal !== undefined\n ? (() => {\n if (options.signal.aborted) {\n controller.abort(options.signal.reason);\n } else {\n const onAbort = (): void => controller.abort(options.signal?.reason);\n options.signal.addEventListener('abort', onAbort, { once: true });\n return () => options.signal?.removeEventListener('abort', onAbort);\n }\n return undefined;\n })()\n : undefined;\n\n const response = await this.fetchWithMiddleware({\n url,\n method,\n headers,\n ...(options.body !== undefined ? { body: JSON.stringify(options.body) } : {}),\n signal: controller.signal,\n });\n span?.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, response.status);\n\n if (!response.ok) {\n removeAbortListener?.();\n const errorText = await response.text();\n throw mapError(new Error(errorText || `HTTP ${response.status}`), {\n request: { method, url },\n response: { status: response.status, body: errorText },\n });\n }\n\n if (!response.body) {\n removeAbortListener?.();\n throw mapError(new Error('Response body is null, cannot stream'), {\n request: { method, url },\n });\n }\n\n const stream = parseNdjsonStream<T>(response.body);\n const abortable: AbortableAsyncIterable<T> = {\n [Symbol.asyncIterator]() {\n return (async function* (): AsyncGenerator<T, void, undefined> {\n try {\n yield* stream;\n } finally {\n removeAbortListener?.();\n }\n })()[Symbol.asyncIterator]();\n },\n abort: () => {\n removeAbortListener?.();\n controller.abort();\n },\n };\n return abortable;\n } catch (err) {\n throw mapError(err, { request: { method, url } });\n }\n },\n );\n }\n}\n","/**\n * Active endpoint health pinging utility.\n */\n\nimport { HttpClient, type FetchLike } from '../transport/http.js';\nimport type { OllamaEndpoint } from './endpoint-registry.js';\nimport type { Middleware } from '../middleware.js';\nimport type { RequestLifecycleHook } from '../logger.js';\nimport type { VersionResponse } from '../types.js';\nimport { disposableTimer } from '../utils.js';\n\nexport interface EndpointHealthCheckResult {\n readonly name: string;\n readonly baseUrl: string;\n readonly reachable: boolean;\n readonly latencyMs: number;\n readonly version?: string;\n readonly error?: string;\n}\n\nexport async function checkEndpointHealth(\n endpoint: OllamaEndpoint,\n fetchImpl?: FetchLike,\n timeoutMs = 5000,\n middleware?: readonly Middleware[] | undefined,\n onLifecycleEvent?: RequestLifecycleHook | undefined,\n): Promise<EndpointHealthCheckResult> {\n const client = new HttpClient({\n baseUrl: endpoint.baseUrl,\n apiKey: endpoint.apiKey,\n headers: endpoint.headers,\n fetch: fetchImpl,\n middleware,\n onLifecycleEvent,\n });\n\n const startTime = Date.now();\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n using _timer = disposableTimer(timer);\n\n try {\n const res = await client.request<VersionResponse>({\n path: '/api/version',\n method: 'GET',\n signal: controller.signal,\n });\n const latencyMs = Date.now() - startTime;\n return {\n name: endpoint.name,\n baseUrl: endpoint.baseUrl,\n reachable: true,\n latencyMs,\n version: res.version,\n };\n } catch (err) {\n const latencyMs = Date.now() - startTime;\n return {\n name: endpoint.name,\n baseUrl: endpoint.baseUrl,\n reachable: false,\n latencyMs,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n // clearTimeout(timer) called automatically via `using _timer` at scope exit\n}\n","/**\n * Model capability detection and runtime environment inference.\n */\n\nimport { HttpClient } from '../transport/http.js';\nimport type { ListResponse, ModelResponse, ShowResponse, ThinkingMetadata } from '../types.js';\n\nexport type RuntimeMode = 'local' | 'cloud' | 'unknown';\n\nexport interface ModelCapabilities {\n readonly model: string;\n readonly reported: readonly string[];\n readonly supportsTools: boolean;\n readonly supportsVision: boolean;\n readonly supportsEmbedding: boolean;\n readonly supportsCompletion: boolean;\n readonly supportsThinking: boolean;\n /** Model-defined thinking values and default, when /api/show reports them. */\n readonly thinking?: ThinkingMetadata | undefined;\n readonly supportsStreaming: true;\n /** Maximum model context length reported by /api/show model_info, when available. */\n readonly contextLength?: number | undefined;\n /**\n * Best-effort inference, not a guarantee: Ollama's `/api/show` does not report structured\n * output support as a queryable capability, so this is inferred from {@link inferRuntimeMode}\n * — `false` for `cloud`, since Ollama Cloud does not currently support structured outputs;\n * `true` for `local`/`unknown`. A locally-hosted model that genuinely can't follow a JSON\n * schema will still report `true` here; the request itself is the only reliable way to find\n * out. `OllamaClient.chat`/`generate` apply this same inference as a fail-fast pre-flight\n * guard whenever `format` is set, throwing `OllamaUnsupportedCapabilityError` rather than\n * making a network call that Ollama Cloud is known to reject.\n */\n readonly supportsStructuredOutputRequest: boolean;\n}\n\nexport function inferRuntimeMode(baseUrl: string): RuntimeMode {\n try {\n const url = new URL(baseUrl);\n const host = url.hostname.toLowerCase();\n if (\n host === 'localhost' ||\n host === '127.0.0.1' ||\n host === '::1' ||\n host.endsWith('.local') ||\n host.startsWith('192.168.') ||\n host.startsWith('10.')\n ) {\n return 'local';\n }\n return 'cloud';\n } catch {\n return 'unknown';\n }\n}\n\nfunction extractContextLength(modelInfo?: Record<string, unknown>): number | undefined {\n if (!modelInfo) return undefined;\n for (const [key, value] of Object.entries(modelInfo)) {\n if (\n key.endsWith('.context_length') &&\n typeof value === 'number' &&\n Number.isFinite(value) &&\n value > 0\n ) {\n return value;\n }\n }\n return undefined;\n}\n\nexport async function detectModelCapabilities(\n http: HttpClient,\n model: string,\n signal?: AbortSignal,\n): Promise<ModelCapabilities> {\n const showRes = await http.request<ShowResponse>({\n path: '/api/show',\n body: { model },\n ...(signal !== undefined ? { signal } : {}),\n });\n\n const reported = showRes.capabilities ?? [];\n const reportedSet = new Set(reported.map((c) => c.toLowerCase()));\n\n const contextLength = extractContextLength(showRes.model_info);\n\n return {\n model,\n reported,\n supportsTools: reportedSet.has('tools'),\n supportsVision: reportedSet.has('vision'),\n supportsEmbedding: reportedSet.has('embedding'),\n supportsCompletion: reportedSet.has('completion') || !reportedSet.has('embedding'),\n supportsThinking: reportedSet.has('thinking'),\n ...(showRes.thinking !== undefined ? { thinking: showRes.thinking } : {}),\n ...(contextLength !== undefined ? { contextLength } : {}),\n supportsStreaming: true,\n supportsStructuredOutputRequest: inferRuntimeMode(http.baseUrl) !== 'cloud',\n };\n}\n\nexport async function listAvailableModels(http: HttpClient): Promise<ModelResponse[]> {\n const res = await http.request<ListResponse>({\n path: '/api/tags',\n method: 'GET',\n });\n return [...res.models];\n}\n","/**\n * Zod schema conversion to JSON Schema for Ollama structured outputs.\n */\n\nimport { z } from 'zod';\nimport { OllamaToolValidationError } from '../errors.js';\n\nexport type SupportedSchema<T = unknown> = z.ZodType<T>;\n\nfunction extractJsonSubstring(text: string): string {\n const trimmed = text.trim();\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) {\n return trimmed;\n }\n const match = trimmed.match(/```(?:json)?\\s*([\\s\\S]*?)\\s*```/);\n if (match && match[1]) {\n return match[1].trim();\n }\n const firstBrace = trimmed.indexOf('{');\n const lastBrace = trimmed.lastIndexOf('}');\n if (firstBrace !== -1 && lastBrace > firstBrace) {\n return trimmed.slice(firstBrace, lastBrace + 1);\n }\n return trimmed;\n}\n\n/**\n * Best-effort structural JSON Schema conversion for Zod v3 schemas, which lack a\n * native `toJSONSchema` API. Walks the internal `_def` shape that v3 exposes.\n */\nexport function zodV3ToJsonSchema(schema: unknown): Record<string, unknown> {\n const def = (schema as { _def?: { typeName?: string; [key: string]: unknown } })._def;\n if (!def) {\n return { type: 'object' };\n }\n\n switch (def['typeName']) {\n case 'ZodObject': {\n const shape = (def['shape'] as () => Record<string, unknown>)();\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n for (const [key, value] of Object.entries(shape)) {\n properties[key] = zodV3ToJsonSchema(value);\n if (!isZodV3Optional(value)) {\n required.push(key);\n }\n }\n return {\n type: 'object',\n properties,\n ...(required.length > 0 ? { required } : {}),\n };\n }\n case 'ZodString':\n return { type: 'string' };\n case 'ZodNumber':\n return { type: 'number' };\n case 'ZodBoolean':\n return { type: 'boolean' };\n case 'ZodDate':\n return { type: 'string', format: 'date-time' };\n case 'ZodArray':\n return { type: 'array', items: zodV3ToJsonSchema(def['type']) };\n case 'ZodEnum':\n return { type: 'string', enum: def['values'] };\n case 'ZodNativeEnum':\n return { enum: Object.values(def['values'] as Record<string, unknown>) };\n case 'ZodLiteral':\n return { const: def['value'] };\n case 'ZodOptional':\n case 'ZodNullable':\n case 'ZodDefault':\n return zodV3ToJsonSchema(def['innerType']);\n case 'ZodEffects':\n return zodV3ToJsonSchema(def['schema']);\n case 'ZodUnion':\n return { anyOf: (def['options'] as unknown[]).map((option) => zodV3ToJsonSchema(option)) };\n case 'ZodRecord':\n return { type: 'object', additionalProperties: zodV3ToJsonSchema(def['valueType']) };\n default:\n return { type: 'object' };\n }\n}\n\nfunction isZodV3Optional(schema: unknown): boolean {\n const typeName = (schema as { _def?: { typeName?: string } })._def?.typeName;\n return typeName === 'ZodOptional' || typeName === 'ZodDefault';\n}\n\n/**\n * Converts a Zod schema into a JSON Schema object accepted by Ollama's `format` parameter.\n *\n * Uses Zod v4's native `z.toJSONSchema` when available, falling back to a structural\n * walk of Zod v3's internal `_def` shape so both major versions work as peer dependencies.\n */\nexport function zodToJsonSchema<T>(schema: z.ZodType<T>): Record<string, unknown> {\n if (\n typeof (z as { toJSONSchema?: (s: z.ZodType<T>) => Record<string, unknown> }).toJSONSchema ===\n 'function'\n ) {\n return (\n z as unknown as { toJSONSchema: (s: z.ZodType<T>) => Record<string, unknown> }\n ).toJSONSchema(schema);\n }\n\n return zodV3ToJsonSchema(schema);\n}\n\n/**\n * Parses and validates a JSON output string against a Zod schema.\n */\nexport function parseStructuredOutput<T>(\n rawJson: string,\n schema: z.ZodType<T>,\n toolName = 'structured_output',\n): T {\n let parsed: unknown;\n const jsonStr = extractJsonSubstring(rawJson);\n try {\n parsed = JSON.parse(jsonStr);\n } catch (err) {\n throw new OllamaToolValidationError(`Failed to parse structured output as JSON: ${rawJson}`, {\n toolName,\n cause: err,\n });\n }\n\n const result = schema.safeParse(parsed);\n if (!result.success) {\n throw new OllamaToolValidationError(`Structured output failed schema validation`, {\n toolName,\n issues: result.error.issues,\n cause: result.error,\n });\n }\n\n return result.data;\n}\n","/**\n * Token usage and duration calculation utilities.\n */\n\nexport const NANOS_PER_MS = 1_000_000;\nexport const NANOS_PER_SECOND = 1_000_000_000;\n\nexport interface TokenUsage {\n readonly promptTokens: number;\n /** Prompt tokens read from Ollama's KV cache. */\n readonly cachedPromptTokens?: number | undefined;\n readonly completionTokens: number;\n readonly totalTokens: number;\n readonly tokensPerSecond?: number | undefined;\n readonly loadDurationMs?: number | undefined;\n readonly promptEvalDurationMs?: number | undefined;\n readonly evalDurationMs?: number | undefined;\n readonly totalDurationMs?: number | undefined;\n}\n\nexport interface RawUsageSource {\n readonly prompt_eval_count?: number | undefined;\n readonly prompt_eval_cached_count?: number | undefined;\n readonly eval_count?: number | undefined;\n readonly total_duration?: number | undefined;\n readonly load_duration?: number | undefined;\n readonly prompt_eval_duration?: number | undefined;\n readonly eval_duration?: number | undefined;\n}\n\n/**\n * Extracts and normalizes token usage metrics from an Ollama response.\n */\nexport function extractUsage(raw: RawUsageSource): TokenUsage {\n const promptTokens = raw.prompt_eval_count ?? 0;\n const completionTokens = raw.eval_count ?? 0;\n const totalTokens = promptTokens + completionTokens;\n\n let tokensPerSecond: number | undefined;\n if (raw.eval_count && raw.eval_duration && raw.eval_duration > 0) {\n tokensPerSecond = Number(((raw.eval_count / raw.eval_duration) * NANOS_PER_SECOND).toFixed(2));\n }\n\n return {\n promptTokens,\n ...(raw.prompt_eval_cached_count !== undefined\n ? { cachedPromptTokens: raw.prompt_eval_cached_count }\n : {}),\n completionTokens,\n totalTokens,\n ...(tokensPerSecond !== undefined ? { tokensPerSecond } : {}),\n ...(raw.load_duration !== undefined\n ? { loadDurationMs: raw.load_duration / NANOS_PER_MS }\n : {}),\n ...(raw.prompt_eval_duration !== undefined\n ? { promptEvalDurationMs: raw.prompt_eval_duration / NANOS_PER_MS }\n : {}),\n ...(raw.eval_duration !== undefined\n ? { evalDurationMs: raw.eval_duration / NANOS_PER_MS }\n : {}),\n ...(raw.total_duration !== undefined\n ? { totalDurationMs: raw.total_duration / NANOS_PER_MS }\n : {}),\n };\n}\n","/**\n * Synthetic tool-call ID generation.\n *\n * Ollama's native `/api/chat` protocol does not assign an identifier to a tool call —\n * see the {@link ToolCall} docs in `../types.js`. To let consumers correlate a tool\n * result back to its call the way OpenAI's `tool_call_id` does (useful for logging,\n * OpenAI-shaped transcripts, or just not having to track array position by hand), the\n * SDK synthesizes a stable client-side `id` the first time it sees a tool call that\n * doesn't already have one, and reuses that same id everywhere that call is referenced\n * (the streamed `tool_call` event, the final aggregated message, `ToolExecutionResult`,\n * and the `role: 'tool'` history entry `Agent` appends). It has no meaning to Ollama or\n * the model itself — it's purely a client-side bookkeeping aid.\n *\n * Uses the global Web Crypto `crypto.randomUUID()` (available in Node 20+, browsers, and\n * every Edge runtime this SDK targets) rather than `node:crypto`, which would break Edge\n * Runtime compatibility (see ADR 0006).\n */\n\nimport type { ToolCall } from '../types.js';\n\nexport function generateToolCallId(): string {\n return `call_${crypto.randomUUID()}`;\n}\n\n/**\n * Returns `toolCalls` with every entry guaranteed to have an `id`, generating one for any\n * entry that lacks it. Entries that already have an `id` (e.g. re-processed calls) are\n * left untouched so ids stay stable across repeated calls on the same data.\n */\nexport function ensureToolCallIds(\n toolCalls: readonly ToolCall[] | undefined,\n): readonly ToolCall[] | undefined {\n if (!toolCalls || toolCalls.length === 0) {\n return toolCalls;\n }\n return toolCalls.map((tc) => (tc.id !== undefined ? tc : { ...tc, id: generateToolCallId() }));\n}\n","/**\n * Dual-mode (AsyncIterator and EventEmitter-like) stream wrapper.\n */\n\nimport { mapError, OllamaAbortError, type OllamaClientError } from '../errors.js';\nimport type { AbortableAsyncIterable, OllamaStreamEvent, OllamaStreamEventType } from './types.js';\n\ntype ChunkMapper<TChunk, TFinal> = (\n chunk: TChunk,\n accumulated: TFinal,\n) => Array<OllamaStreamEvent<TChunk, TFinal>>;\n\ntype Aggregator<TChunk, TFinal> = (accumulated: TFinal, chunk: TChunk) => TFinal;\n\ntype Listener<TChunk, TFinal> = (event: OllamaStreamEvent<TChunk, TFinal>) => void;\n\nexport class OllamaStream<TChunk, TFinal> implements AsyncIterable<\n OllamaStreamEvent<TChunk, TFinal>\n> {\n private mode: 'unconsumed' | 'iterator' | 'events' = 'unconsumed';\n private readonly listeners = new Map<string, Set<Listener<TChunk, TFinal>>>();\n private readonly finalResultPromise: Promise<TFinal>;\n private resolveFinal!: (value: TFinal) => void;\n private rejectFinal!: (reason: OllamaClientError) => void;\n private removeAbortListener: (() => void) | undefined;\n\n constructor(\n private readonly source: AbortableAsyncIterable<TChunk>,\n private readonly mapChunk: ChunkMapper<TChunk, TFinal>,\n private readonly aggregate: Aggregator<TChunk, TFinal>,\n private readonly initial: TFinal,\n signal?: AbortSignal,\n ) {\n this.finalResultPromise = new Promise<TFinal>((resolve, reject) => {\n this.resolveFinal = resolve;\n this.rejectFinal = reject;\n });\n\n if (signal !== undefined) {\n const onAbort = (): void => this.abort();\n if (signal.aborted) {\n onAbort();\n } else {\n signal.addEventListener('abort', onAbort, { once: true });\n this.removeAbortListener = () => signal.removeEventListener('abort', onAbort);\n }\n }\n }\n\n get finalResult(): Promise<TFinal> {\n return this.finalResultPromise;\n }\n\n abort(): void {\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.source.abort?.();\n this.rejectFinal(new OllamaAbortError('Ollama stream aborted'));\n }\n\n on<TType extends OllamaStreamEventType>(\n type: TType,\n listener: (event: Extract<OllamaStreamEvent<TChunk, TFinal>, { type: TType }>) => void,\n ): () => void {\n if (this.mode === 'iterator') {\n throw new Error(\n 'Cannot register event listeners: this stream is already being consumed via async iteration.',\n );\n }\n\n const genericListener = listener as Listener<TChunk, TFinal>;\n let set = this.listeners.get(type);\n if (!set) {\n set = new Set();\n this.listeners.set(type, set);\n }\n set.add(genericListener);\n\n if (this.mode !== 'events') {\n this.mode = 'events';\n void this.pump();\n }\n\n return () => {\n set?.delete(genericListener);\n };\n }\n\n private emit(event: OllamaStreamEvent<TChunk, TFinal>): void {\n for (const listener of this.listeners.get(event.type) ?? []) {\n listener(event);\n }\n }\n\n private async pump(): Promise<void> {\n let accumulated = this.initial;\n try {\n for await (const chunk of this.source) {\n accumulated = this.aggregate(accumulated, chunk);\n for (const event of this.mapChunk(chunk, accumulated)) {\n this.emit(event);\n if (event.type === 'done') {\n this.resolveFinal(event.data.result);\n }\n }\n }\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n } catch (error) {\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n const mapped = mapError(error);\n this.emit({ type: 'error', data: { error: mapped } });\n this.rejectFinal(mapped);\n }\n }\n\n async *[Symbol.asyncIterator](): AsyncGenerator<\n OllamaStreamEvent<TChunk, TFinal>,\n void,\n undefined\n > {\n if (this.mode === 'events') {\n throw new Error(\n 'Cannot use async iteration: this stream already has event listeners registered via .on().',\n );\n }\n this.mode = 'iterator';\n let accumulated = this.initial;\n let completed = false;\n try {\n for await (const chunk of this.source) {\n accumulated = this.aggregate(accumulated, chunk);\n const events = this.mapChunk(chunk, accumulated);\n for (const event of events) {\n if (event.type === 'done') {\n completed = true;\n this.resolveFinal(event.data.result);\n }\n yield event;\n }\n }\n } catch (error) {\n const mapped = mapError(error);\n this.rejectFinal(mapped);\n yield { type: 'error', data: { error: mapped } };\n } finally {\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n if (!completed) {\n this.source.abort?.();\n this.rejectFinal(new OllamaAbortError('Ollama stream ended before completion'));\n }\n }\n }\n}\n","/**\n * Normalization mappers and aggregators for Ollama streaming responses.\n */\n\nimport type { ChatResponse, GenerateResponse, ProgressResponse } from '../types.js';\nimport { extractUsage, NANOS_PER_MS } from '../usage.js';\nimport { ensureToolCallIds } from '../tools/tool-call-id.js';\nimport { OllamaStream } from './stream.js';\nimport type {\n AbortableAsyncIterable,\n ChatStreamResult,\n GenerateStreamResult,\n OllamaStreamEvent,\n ProgressStreamResult,\n} from './types.js';\n\nfunction aggregateChat(accumulated: ChatStreamResult, chunk: ChatResponse): ChatStreamResult {\n const message = chunk.message ?? { role: 'assistant', content: '' };\n return {\n message: {\n role: message.role || accumulated.message.role,\n content: accumulated.message.content + (message.content ?? ''),\n thinking:\n message.thinking !== undefined\n ? (accumulated.message.thinking ?? '') + message.thinking\n : accumulated.message.thinking,\n tool_calls: message.tool_calls?.length\n ? [...(accumulated.message.tool_calls ?? []), ...message.tool_calls]\n : accumulated.message.tool_calls,\n },\n model: chunk.model,\n done: chunk.done,\n doneReason: chunk.done ? chunk.done_reason : accumulated.doneReason,\n totalDurationMs:\n chunk.done && chunk.total_duration !== undefined\n ? chunk.total_duration / NANOS_PER_MS\n : accumulated.totalDurationMs,\n usage: chunk.done ? extractUsage(chunk) : accumulated.usage,\n raw: chunk,\n };\n}\n\nfunction mapChatChunk(\n chunk: ChatResponse,\n aggregated: ChatStreamResult,\n): Array<OllamaStreamEvent<ChatResponse, ChatStreamResult>> {\n const events: Array<OllamaStreamEvent<ChatResponse, ChatStreamResult>> = [];\n const message = chunk.message;\n\n if (message?.thinking) {\n events.push({ type: 'thinking', data: { delta: message.thinking } });\n }\n for (const toolCall of message?.tool_calls ?? []) {\n events.push({ type: 'tool_call', data: { toolCall } });\n }\n if (message?.content) {\n events.push({ type: 'token', data: { delta: message.content, role: message.role } });\n }\n events.push({ type: 'message', data: { chunk } });\n if (chunk.done) {\n events.push({ type: 'done', data: { result: aggregated } });\n }\n return events;\n}\n\n/**\n * Wraps `source` so every chunk's `message.tool_calls` carries a stable client-synthesized\n * `id` (see `../tools/tool-call-id.js`) before it reaches either the aggregator or the\n * per-chunk event mapper — both read the same chunk object, so ids must be assigned exactly\n * once here rather than independently in each, or the streamed `tool_call` event and the\n * final aggregated message would end up with two different ids for the same call.\n */\nfunction withStableToolCallIds(\n source: AbortableAsyncIterable<ChatResponse>,\n): AbortableAsyncIterable<ChatResponse> {\n async function* generator(): AsyncGenerator<ChatResponse, void, undefined> {\n for await (const chunk of source) {\n const toolCalls = chunk.message?.tool_calls;\n if (!toolCalls?.length) {\n yield chunk;\n continue;\n }\n yield { ...chunk, message: { ...chunk.message, tool_calls: ensureToolCallIds(toolCalls) } };\n }\n }\n return Object.assign(generator(), { abort: source.abort });\n}\n\nexport function normalizeChatStream(\n source: AbortableAsyncIterable<ChatResponse>,\n signal?: AbortSignal,\n): OllamaStream<ChatResponse, ChatStreamResult> {\n const initial: ChatStreamResult = {\n message: { role: 'assistant', content: '' },\n model: '',\n done: false,\n };\n return new OllamaStream(withStableToolCallIds(source), mapChatChunk, aggregateChat, initial, signal);\n}\n\nfunction aggregateGenerate(\n accumulated: GenerateStreamResult,\n chunk: GenerateResponse,\n): GenerateStreamResult {\n return {\n response: accumulated.response + (chunk.response ?? ''),\n model: chunk.model,\n done: chunk.done,\n doneReason: chunk.done ? chunk.done_reason : accumulated.doneReason,\n totalDurationMs:\n chunk.done && chunk.total_duration !== undefined\n ? chunk.total_duration / NANOS_PER_MS\n : accumulated.totalDurationMs,\n usage: chunk.done ? extractUsage(chunk) : accumulated.usage,\n thinking:\n chunk.thinking !== undefined\n ? (accumulated.thinking ?? '') + chunk.thinking\n : accumulated.thinking,\n image: chunk.image ?? accumulated.image,\n completed: chunk.completed ?? accumulated.completed,\n total: chunk.total ?? accumulated.total,\n raw: chunk,\n };\n}\n\nfunction mapGenerateChunk(\n chunk: GenerateResponse,\n aggregated: GenerateStreamResult,\n): Array<OllamaStreamEvent<GenerateResponse, GenerateStreamResult>> {\n const events: Array<OllamaStreamEvent<GenerateResponse, GenerateStreamResult>> = [];\n\n if (chunk.thinking) {\n events.push({ type: 'thinking', data: { delta: chunk.thinking } });\n }\n if (chunk.response) {\n events.push({ type: 'token', data: { delta: chunk.response, role: 'assistant' } });\n }\n events.push({ type: 'message', data: { chunk } });\n if (chunk.done) {\n events.push({ type: 'done', data: { result: aggregated } });\n }\n return events;\n}\n\nexport function normalizeGenerateStream(\n source: AbortableAsyncIterable<GenerateResponse>,\n signal?: AbortSignal,\n): OllamaStream<GenerateResponse, GenerateStreamResult> {\n const initial: GenerateStreamResult = { response: '', model: '', done: false };\n return new OllamaStream(source, mapGenerateChunk, aggregateGenerate, initial, signal);\n}\n\nfunction aggregateProgress(\n _accumulated: ProgressStreamResult,\n chunk: ProgressResponse,\n): ProgressStreamResult {\n return {\n status: chunk.status,\n completed: chunk.completed,\n total: chunk.total,\n done: chunk.status === 'success',\n raw: chunk,\n };\n}\n\nfunction mapProgressChunk(\n chunk: ProgressResponse,\n aggregated: ProgressStreamResult,\n): Array<OllamaStreamEvent<ProgressResponse, ProgressStreamResult>> {\n const events: Array<OllamaStreamEvent<ProgressResponse, ProgressStreamResult>> = [\n { type: 'message', data: { chunk } },\n ];\n if (chunk.status === 'success') {\n events.push({ type: 'done', data: { result: aggregated } });\n }\n return events;\n}\n\nexport function normalizeProgressStream(\n source: AbortableAsyncIterable<ProgressResponse>,\n signal?: AbortSignal,\n): OllamaStream<ProgressResponse, ProgressStreamResult> {\n const initial: ProgressStreamResult = { status: '', done: false };\n return new OllamaStream(source, mapProgressChunk, aggregateProgress, initial, signal);\n}\n","/**\n * Exponential backoff with full jitter calculation.\n */\n\nexport interface BackoffOptions {\n readonly initialDelayMs: number;\n readonly maxDelayMs: number;\n readonly backoffFactor: number;\n}\n\nexport const DEFAULT_BACKOFF: BackoffOptions = {\n initialDelayMs: 500,\n maxDelayMs: 30_000,\n backoffFactor: 2,\n};\n\n/**\n * Calculates exponential backoff with full jitter for attempt (0-indexed).\n */\nexport function calculateBackoff(\n attempt: number,\n options: BackoffOptions = DEFAULT_BACKOFF,\n): number {\n const exponential = options.initialDelayMs * Math.pow(options.backoffFactor, attempt);\n const ceiling = Math.min(exponential, options.maxDelayMs);\n // Full jitter: random duration between 0 and ceiling\n return Math.floor(Math.random() * (ceiling + 1));\n}\n","/**\n * Retry policy and execution runner.\n */\n\nimport { OllamaAbortError, OllamaClientError } from '../errors.js';\nimport { calculateBackoff, type BackoffOptions, DEFAULT_BACKOFF } from './backoff.js';\n\nexport interface RetryConfig {\n readonly maxRetries: number;\n readonly backoff: BackoffOptions;\n readonly shouldRetry?: (error: Error, attempt: number) => boolean;\n readonly onRetry?: (error: Error, attempt: number, delayMs: number) => void;\n}\n\nexport const DEFAULT_RETRY_CONFIG: RetryConfig = {\n maxRetries: 3,\n backoff: DEFAULT_BACKOFF,\n};\n\nfunction isRetryableDefault(error: Error): boolean {\n if (error instanceof OllamaClientError) {\n return error.retryable;\n }\n return false;\n}\n\nfunction abortError(\n signal: AbortSignal | undefined,\n fallbackMessage: string,\n): OllamaAbortError | OllamaClientError {\n const reason = signal?.reason;\n if (reason instanceof OllamaClientError) return reason;\n return new OllamaAbortError(\n reason instanceof Error && reason.message ? reason.message : fallbackMessage,\n { cause: reason },\n );\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortError(signal, 'Retry backoff aborted'));\n return;\n }\n\n const timerId = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = (): void => {\n if (timerId !== undefined) clearTimeout(timerId);\n signal?.removeEventListener('abort', onAbort);\n reject(abortError(signal, 'Retry backoff aborted'));\n };\n\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\n/**\n * Executes an async operation with retries according to config.\n */\nexport async function withRetry<T>(\n operation: (attempt: number) => Promise<T>,\n config: RetryConfig = DEFAULT_RETRY_CONFIG,\n signal?: AbortSignal,\n): Promise<T> {\n let attempt = 0;\n while (true) {\n try {\n return await operation(attempt);\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n const shouldRetry = config.shouldRetry ?? isRetryableDefault;\n if (attempt >= config.maxRetries || !shouldRetry(error, attempt)) {\n throw error;\n }\n const delayMs = calculateBackoff(attempt, config.backoff);\n config.onRetry?.(error, attempt, delayMs);\n await sleep(delayMs, signal);\n attempt += 1;\n }\n }\n}\n","/**\n * AbortSignal and timeout management for HTTP requests.\n */\n\nimport { OllamaTimeoutError } from '../errors.js';\n\nexport interface TimeoutSignal {\n readonly signal: AbortSignal;\n readonly cancel: () => void;\n}\n\n/**\n * Combines an optional timeout with an optional caller-provided AbortSignal.\n */\nexport function createTimeoutSignal(timeoutMs?: number, userSignal?: AbortSignal): TimeoutSignal {\n if (!timeoutMs && !userSignal) {\n const controller = new AbortController();\n return { signal: controller.signal, cancel: () => undefined };\n }\n\n const controller = new AbortController();\n let timerId: ReturnType<typeof setTimeout> | undefined;\n\n if (timeoutMs && timeoutMs > 0) {\n timerId = setTimeout(() => {\n controller.abort(\n new OllamaTimeoutError(`Request timed out after ${timeoutMs}ms`, { timeoutMs }),\n );\n }, timeoutMs);\n }\n\n const onUserAbort = (): void => {\n if (timerId) clearTimeout(timerId);\n controller.abort(userSignal?.reason);\n };\n\n if (userSignal) {\n if (userSignal.aborted) {\n if (timerId) clearTimeout(timerId);\n controller.abort(userSignal.reason);\n } else {\n userSignal.addEventListener('abort', onUserAbort, { once: true });\n }\n }\n\n const cancel = (): void => {\n if (timerId) clearTimeout(timerId);\n if (userSignal) {\n userSignal.removeEventListener('abort', onUserAbort);\n }\n };\n\n return { signal: controller.signal, cancel };\n}\n","/**\n * Model and blob management operations.\n */\n\nimport { listAvailableModels } from './capabilities/capabilities.js';\nimport { normalizeProgressStream } from './streaming/normalize.js';\nimport type { OllamaStream } from './streaming/stream.js';\nimport type { ProgressStreamResult } from './streaming/types.js';\nimport type { BinaryBody } from './transport/http.js';\nimport type { RequestRunner } from './transport/runner.js';\nimport type {\n CopyRequestOptions,\n CreateRequestOptions,\n DeleteRequestOptions,\n ModelResponse,\n ProgressResponse,\n PsResponse,\n PullRequestOptions,\n PushRequestOptions,\n ShowRequestOptions,\n ShowResponse,\n StatusResponse,\n VersionResponse,\n} from './types.js';\n\n/**\n * Every operation here targets one specific Ollama server's local model catalog or blob\n * store — unlike `chat`/`generate`/`embed`, a different endpoint isn't an interchangeable\n * substitute; it's a different catalog/store entirely. `singleEndpoint: true` disables\n * `OllamaClient`'s cross-endpoint failover for these calls (same-endpoint retry via\n * `withRetry` still applies), so a multi-endpoint setup never silently lists/mutates the\n * wrong server just because the intended one had a transient failure. See ADR 0008.\n */\nexport class ModelsClient {\n constructor(private readonly runner: RequestRunner) {}\n\n list(): Promise<ModelResponse[]> {\n return this.runner((http) => listAvailableModels(http), { singleEndpoint: true });\n }\n\n show(request: ShowRequestOptions): Promise<ShowResponse> {\n return this.runner(\n (http, signal) => http.request<ShowResponse>({ path: '/api/show', body: request, signal }),\n { ...request, singleEndpoint: true },\n );\n }\n\n pull(\n request: PullRequestOptions & { stream: true },\n ): Promise<OllamaStream<ProgressResponse, ProgressStreamResult>>;\n pull(request: PullRequestOptions & { stream?: false | undefined }): Promise<ProgressResponse>;\n pull(\n request: PullRequestOptions,\n ): Promise<ProgressResponse | OllamaStream<ProgressResponse, ProgressStreamResult>>;\n async pull(\n request: PullRequestOptions,\n ): Promise<ProgressResponse | OllamaStream<ProgressResponse, ProgressStreamResult>> {\n if (request.stream) {\n return this.runner(\n async (http, signal) => {\n const stream = await http.requestStream<ProgressResponse>({\n path: '/api/pull',\n body: { ...request, stream: true },\n signal,\n });\n return normalizeProgressStream(stream, signal);\n },\n { ...request, singleEndpoint: true, holdUntil: (stream) => stream.finalResult },\n );\n }\n return this.runner(\n (http, signal) =>\n http.request<ProgressResponse>({\n path: '/api/pull',\n body: { ...request, stream: false },\n signal,\n }),\n { ...request, singleEndpoint: true },\n );\n }\n\n push(\n request: PushRequestOptions & { stream: true },\n ): Promise<OllamaStream<ProgressResponse, ProgressStreamResult>>;\n push(request: PushRequestOptions & { stream?: false | undefined }): Promise<ProgressResponse>;\n push(\n request: PushRequestOptions,\n ): Promise<ProgressResponse | OllamaStream<ProgressResponse, ProgressStreamResult>>;\n async push(\n request: PushRequestOptions,\n ): Promise<ProgressResponse | OllamaStream<ProgressResponse, ProgressStreamResult>> {\n if (request.stream) {\n return this.runner(\n async (http, signal) => {\n const stream = await http.requestStream<ProgressResponse>({\n path: '/api/push',\n body: { ...request, stream: true },\n signal,\n });\n return normalizeProgressStream(stream, signal);\n },\n { ...request, singleEndpoint: true, holdUntil: (stream) => stream.finalResult },\n );\n }\n return this.runner(\n (http, signal) =>\n http.request<ProgressResponse>({\n path: '/api/push',\n body: { ...request, stream: false },\n signal,\n }),\n { ...request, singleEndpoint: true },\n );\n }\n\n create(\n request: CreateRequestOptions & { stream: true },\n ): Promise<OllamaStream<ProgressResponse, ProgressStreamResult>>;\n create(request: CreateRequestOptions & { stream?: false | undefined }): Promise<ProgressResponse>;\n create(\n request: CreateRequestOptions,\n ): Promise<ProgressResponse | OllamaStream<ProgressResponse, ProgressStreamResult>>;\n async create(\n request: CreateRequestOptions,\n ): Promise<ProgressResponse | OllamaStream<ProgressResponse, ProgressStreamResult>> {\n if (request.stream) {\n return this.runner(\n async (http, signal) => {\n const stream = await http.requestStream<ProgressResponse>({\n path: '/api/create',\n body: { ...request, stream: true },\n signal,\n });\n return normalizeProgressStream(stream);\n },\n { ...request, singleEndpoint: true, holdUntil: (stream) => stream.finalResult },\n );\n }\n return this.runner(\n (http, signal) =>\n http.request<ProgressResponse>({\n path: '/api/create',\n body: { ...request, stream: false },\n signal,\n }),\n { ...request, singleEndpoint: true },\n );\n }\n\n delete(request: DeleteRequestOptions): Promise<StatusResponse> {\n return this.runner(\n (http, signal) =>\n http.request<StatusResponse>({\n path: '/api/delete',\n method: 'DELETE',\n body: request,\n signal,\n }),\n { ...request, singleEndpoint: true },\n );\n }\n\n copy(request: CopyRequestOptions): Promise<StatusResponse> {\n return this.runner(\n (http, signal) => http.request<StatusResponse>({ path: '/api/copy', body: request, signal }),\n { ...request, singleEndpoint: true },\n );\n }\n\n ps(): Promise<PsResponse> {\n return this.runner((http) => http.request<PsResponse>({ path: '/api/ps', method: 'GET' }), {\n singleEndpoint: true,\n });\n }\n\n version(): Promise<VersionResponse> {\n return this.runner(\n (http) => http.request<VersionResponse>({ path: '/api/version', method: 'GET' }),\n { singleEndpoint: true },\n );\n }\n\n async createBlob(digest: string, data: BinaryBody): Promise<void> {\n await this.runner(\n (http, signal) =>\n http.request<void>({\n path: `/api/blobs/${encodeURIComponent(digest)}`,\n method: 'POST',\n rawBody: data,\n signal,\n }),\n { singleEndpoint: true },\n );\n }\n\n async checkBlob(digest: string): Promise<boolean> {\n try {\n await this.runner(\n (http, signal) =>\n http.request<void>({\n path: `/api/blobs/${encodeURIComponent(digest)}`,\n method: 'HEAD',\n signal,\n }),\n { singleEndpoint: true },\n );\n return true;\n } catch {\n return false;\n }\n }\n}\n","/**\n * OpenAI Compatibility interfaces and client helpers for Ollama.\n * Ollama exposes OpenAI-compatible /v1 endpoints.\n *\n * @remarks\n * This is a typed pass-through to Ollama's own OpenAI-compatible `/v1` endpoints — it\n * implements the subset of the OpenAI API surface that Ollama documents as supported\n * (https://docs.ollama.com/api/openai-compatibility), not the full OpenAI surface (hosted\n * tools like web/file search, computer use, code interpreter, or stateful server-side\n * conversation state). Notably, `tools` is supported by Ollama's compat layer but\n * `tool_choice` and `parallel_tool_calls` are not — both are still typed on\n * {@link OpenAIChatCompletionRequest} (accepted-but-ignored) so consumers passing a\n * standard OpenAI request object don't get spurious type errors; see the `@remarks` on\n * each field. `/v1/responses` is supported non-statefully — see\n * {@link OpenAIResponsesRequest}.\n */\n\nimport type { AbortableAsyncIterable } from '../streaming/types.js';\nimport type { SseEvent } from '../streaming/sse.js';\nimport type { HttpClient } from '../transport/http.js';\nimport type { RequestRunner } from '../transport/runner.js';\nimport { OllamaAbortError, OllamaClientError } from '../errors.js';\n\nexport interface OpenAIToolCall {\n readonly id: string;\n readonly type: 'function';\n readonly function: {\n readonly name: string;\n /** JSON-encoded arguments string, matching OpenAI's wire format (not a parsed object). */\n readonly arguments: string;\n };\n}\n\nexport interface OpenAITextContentPart {\n readonly type: 'text';\n readonly text: string;\n}\n\nexport interface OpenAIImageUrlContentPart {\n readonly type: 'image_url';\n /** Ollama accepts a data/image URL string or the standard OpenAI URL object. */\n readonly image_url:\n | string\n | { readonly url: string; readonly detail?: 'auto' | 'low' | 'high' | 'original' | undefined };\n}\n\nexport type OpenAIContentPart = OpenAITextContentPart | OpenAIImageUrlContentPart;\n\nexport interface OpenAIMessage {\n readonly role: 'system' | 'user' | 'assistant' | 'tool';\n readonly content: string | readonly OpenAIContentPart[];\n readonly name?: string | undefined;\n readonly tool_calls?: readonly OpenAIToolCall[] | undefined;\n /** Ollama may emit model reasoning alongside assistant content. */\n readonly reasoning?: string | undefined;\n /** Set on a `role: 'tool'` message to identify which call this is a result for. */\n readonly tool_call_id?: string | undefined;\n}\n\nexport interface OpenAIStreamOptions {\n /** Emit a final SSE chunk carrying `usage` (prompt/completion/total tokens) before `[DONE]`. */\n readonly include_usage?: boolean | undefined;\n}\n\nexport interface OpenAIFunctionDefinition {\n readonly name: string;\n readonly description?: string | undefined;\n readonly parameters?: Record<string, unknown> | undefined;\n}\n\nexport interface OpenAITool {\n readonly type: 'function';\n readonly function: OpenAIFunctionDefinition;\n}\n\nexport type OpenAIReasoningEffort =\n | 'high'\n | 'medium'\n | 'low'\n | 'max'\n | 'none'\n | 'minimal'\n | 'xhigh'\n | 'ultra'\n | (string & {});\n\nexport type OpenAIResponseFormat =\n | { readonly type: 'text' }\n | { readonly type: 'json_object' }\n | { readonly type: 'json_schema'; readonly json_schema: Record<string, unknown> };\n\nexport interface OpenAIChatCompletionRequest {\n readonly model: string;\n readonly messages: readonly OpenAIMessage[];\n readonly temperature?: number | undefined;\n readonly top_p?: number | undefined;\n readonly stream?: boolean | undefined;\n /** Only meaningful when `stream: true`; ignored otherwise. */\n readonly stream_options?: OpenAIStreamOptions | undefined;\n readonly max_tokens?: number | undefined;\n readonly stop?: readonly string[] | undefined;\n readonly response_format?: OpenAIResponseFormat | undefined;\n readonly seed?: number | undefined;\n readonly presence_penalty?: number | undefined;\n readonly frequency_penalty?: number | undefined;\n readonly user?: string | undefined;\n readonly logit_bias?: Record<string, number> | undefined;\n readonly n?: number | undefined;\n /** Ollama exposes log probabilities for supported reasoning/chat models. */\n readonly logprobs?: boolean | undefined;\n readonly top_logprobs?: number | undefined;\n readonly tools?: readonly OpenAITool[] | undefined;\n /**\n * @remarks Accepted for OpenAI compatibility but ignored by Ollama — every tool the\n * model is given remains callable regardless of this value.\n */\n readonly tool_choice?:\n | 'none'\n | 'auto'\n | 'required'\n | { readonly type: 'function'; readonly function: { readonly name: string } }\n | undefined;\n /**\n * @remarks Accepted for OpenAI compatibility but ignored by Ollama — Ollama does not\n * control tool-call parallelism through this flag.\n */\n readonly parallel_tool_calls?: boolean | undefined;\n /**\n * Effort level for thinking models (e.g. `deepseek-r1`, `qwen3`). Equivalent to\n * `reasoning.effort`; only effective for models that support reasoning/thinking.\n */\n readonly reasoning_effort?: OpenAIReasoningEffort | undefined;\n /**\n * Effort level for thinking models (e.g. `deepseek-r1`, `qwen3`), nested OpenAI-style.\n * Equivalent to `reasoning_effort`; only effective for models that support\n * reasoning/thinking.\n */\n readonly reasoning?:\n { readonly effort?: OpenAIReasoningEffort | undefined } | undefined;\n}\n\n/** Ollama Chat Completions supports text plus base64 image content via a string image URL. */\nexport type OllamaOpenAIChatContentPart =\n | OpenAITextContentPart\n | {\n readonly type: 'image_url';\n /** Ollama's current compatibility docs accept an image URL string, including data URLs. */\n readonly image_url: string;\n };\n\nexport type OllamaOpenAIReasoningEffort =\n | 'high'\n | 'medium'\n | 'low'\n | 'max'\n | 'none';\n\nexport type OllamaOpenAIChatMessage = Omit<OpenAIMessage, 'content'> & {\n readonly content: string | readonly OllamaOpenAIChatContentPart[];\n};\n\n/** Strict Ollama-documented Chat Completions request; excludes only the SDK-only parallel tool flag. */\nexport type OllamaOpenAIChatCompletionRequest = Omit<\n OpenAIChatCompletionRequest,\n 'messages' | 'parallel_tool_calls' | 'reasoning_effort' | 'reasoning'\n> & {\n readonly messages: readonly OllamaOpenAIChatMessage[];\n readonly reasoning_effort?: OllamaOpenAIReasoningEffort | undefined;\n readonly reasoning?: { readonly effort?: OllamaOpenAIReasoningEffort | undefined } | undefined;\n};\n\nexport interface OpenAIChatCompletionChoice {\n readonly index: number;\n readonly message: OpenAIMessage;\n readonly finish_reason: string;\n readonly logprobs?: Record<string, unknown> | null | undefined;\n}\n\nexport interface OpenAIToolCallDelta {\n readonly index: number;\n readonly id?: string | undefined;\n readonly type?: 'function' | undefined;\n readonly function?: {\n readonly name?: string | undefined;\n readonly arguments?: string | undefined;\n } | undefined;\n}\n\nexport interface OpenAIChatCompletionDelta {\n readonly role?: OpenAIMessage['role'] | undefined;\n readonly content?: string | null | undefined;\n readonly reasoning?: string | null | undefined;\n readonly refusal?: string | null | undefined;\n readonly tool_calls?: readonly OpenAIToolCallDelta[] | undefined;\n}\n\nexport interface OpenAIChatCompletionChunkChoice {\n readonly index: number;\n readonly delta: OpenAIChatCompletionDelta;\n readonly finish_reason?: string | null | undefined;\n readonly logprobs?: Record<string, unknown> | null | undefined;\n}\n\nexport interface OpenAIChatCompletionChunk {\n readonly id: string;\n readonly object: 'chat.completion.chunk';\n readonly created: number;\n readonly model: string;\n readonly system_fingerprint?: string | undefined;\n readonly choices: readonly OpenAIChatCompletionChunkChoice[];\n readonly usage?:\n | {\n readonly prompt_tokens: number;\n readonly completion_tokens: number;\n readonly total_tokens: number;\n }\n | null\n | undefined;\n}\n\nexport interface OpenAIUsage {\n readonly prompt_tokens: number;\n readonly completion_tokens: number;\n readonly total_tokens: number;\n readonly prompt_tokens_details?: {\n readonly cached_tokens?: number | undefined;\n } | undefined;\n}\n\nexport interface OpenAIChatCompletionResponse {\n readonly id: string;\n readonly object: 'chat.completion';\n readonly created: number;\n readonly model: string;\n readonly system_fingerprint?: string | undefined;\n readonly choices: readonly OpenAIChatCompletionChoice[];\n readonly usage?: OpenAIUsage | undefined;\n}\n\nexport interface OpenAIModelItem {\n readonly id: string;\n readonly object: 'model';\n readonly created: number;\n readonly owned_by: string;\n}\n\nexport interface OpenAIListModelsResponse {\n readonly object: 'list';\n readonly data: readonly OpenAIModelItem[];\n}\n\nexport interface OpenAICompletionRequest {\n readonly model: string;\n /** Ollama currently accepts a string prompt for /v1/completions. */\n readonly prompt: string;\n /** Number of log probability alternatives requested for completion tokens. */\n readonly logprobs?: number | undefined;\n readonly frequency_penalty?: number | undefined;\n readonly presence_penalty?: number | undefined;\n readonly seed?: number | undefined;\n readonly stop?: readonly string[] | undefined;\n readonly stream?: boolean | undefined;\n readonly stream_options?: OpenAIStreamOptions | undefined;\n readonly temperature?: number | undefined;\n readonly top_p?: number | undefined;\n readonly max_tokens?: number | undefined;\n readonly suffix?: string | undefined;\n readonly best_of?: number | undefined;\n readonly echo?: boolean | undefined;\n readonly logit_bias?: Record<string, number> | undefined;\n readonly user?: string | undefined;\n readonly n?: number | undefined;\n}\n\n/** Strict Ollama-documented Completions request. */\nexport type OllamaOpenAICompletionRequest = OpenAICompletionRequest;\n\nexport interface OpenAICompletionChoice {\n readonly text: string;\n readonly index: number;\n readonly logprobs?: Record<string, unknown> | null | undefined;\n readonly finish_reason: string | null;\n}\n\nexport interface OpenAICompletionChunk {\n readonly id: string;\n readonly object: 'text_completion';\n readonly created: number;\n readonly model: string;\n readonly system_fingerprint?: string | undefined;\n readonly choices: readonly {\n readonly text: string;\n readonly index: number;\n readonly logprobs?: Record<string, unknown> | null | undefined;\n readonly finish_reason?: string | null | undefined;\n }[];\n readonly usage?:\n | {\n readonly prompt_tokens: number;\n readonly completion_tokens: number;\n readonly total_tokens: number;\n }\n | null\n | undefined;\n}\n\nexport interface OpenAICompletionResponse {\n readonly id: string;\n readonly object: 'text_completion';\n readonly created: number;\n readonly model: string;\n readonly system_fingerprint?: string | undefined;\n readonly choices: readonly OpenAICompletionChoice[];\n readonly usage?: OpenAIUsage | undefined;\n}\n\nexport type OpenAIEmbeddingInput =\n | string\n | readonly string[]\n | readonly number[]\n | readonly (readonly number[])[];\n\nexport interface OpenAIEmbeddingRequest {\n readonly model: string;\n readonly input: OpenAIEmbeddingInput;\n readonly encoding_format?: 'float' | 'base64' | undefined;\n readonly dimensions?: number | undefined;\n readonly user?: string | undefined;\n}\n\n/** Strict Ollama-documented Embeddings request. */\nexport type OllamaOpenAIEmbeddingRequest = OpenAIEmbeddingRequest;\n\nexport interface OpenAIEmbeddingItem {\n readonly object: 'embedding';\n readonly embedding: readonly number[] | string;\n readonly index: number;\n}\n\nexport interface OpenAIEmbeddingResponse {\n readonly object: 'list';\n readonly data: readonly OpenAIEmbeddingItem[];\n readonly model: string;\n readonly usage?: {\n readonly prompt_tokens: number;\n readonly total_tokens: number;\n } | undefined;\n}\n\n/**\n * Request body for OpenAI's Responses API (`/v1/responses`), added in Ollama v0.13.3.\n *\n * @remarks\n * Ollama implements this **non-statefully**: every call is independent, so\n * {@link previous_response_id} and {@link conversation} — OpenAI's mechanisms for\n * resuming server-side conversation state — are accepted for compatibility but ignored.\n * Send the full conversation in `input` on every call, the same as `/api/chat`.\n */\nexport interface OpenAIResponsesRequest {\n readonly model: string;\n readonly input: string | readonly OpenAIMessage[];\n readonly instructions?: string | undefined;\n readonly tools?: readonly OpenAITool[] | undefined;\n readonly stream?: boolean | undefined;\n readonly temperature?: number | undefined;\n readonly top_p?: number | undefined;\n readonly max_output_tokens?: number | undefined;\n /** @remarks Not supported by Ollama, which is stateless across calls — accepted but ignored. */\n readonly previous_response_id?: string | undefined;\n /** @remarks Not supported by Ollama, which is stateless across calls — accepted but ignored. */\n readonly conversation?: string | undefined;\n readonly truncation?: string | undefined;\n readonly reasoning?: { readonly effort?: OpenAIReasoningEffort | undefined } | undefined;\n /** Ollama extension: boolean, model-defined string, or null for model default. */\n readonly think?: boolean | string | null | undefined;\n}\n\n/** Strict Ollama-documented Responses request; excludes stateful and SDK-only request fields. */\n/** Strict Ollama-documented Responses request; excludes only unsupported stateful fields. */\nexport type OllamaOpenAIResponsesRequest = Omit<\n OpenAIResponsesRequest,\n 'previous_response_id' | 'conversation'\n>;\n\nexport type OpenAIResponsesStatus = 'completed' | 'failed' | 'in_progress' | 'cancelled' | 'queued' | 'incomplete';\n\nexport interface OpenAIResponsesError { readonly code?: string | undefined; readonly message?: string | undefined; readonly [key: string]: unknown; }\nexport interface OpenAIResponsesIncompleteDetails { readonly reason?: string | undefined; readonly [key: string]: unknown; }\n\nexport interface OpenAIResponsesOutputTextContent {\n readonly type: 'output_text'; readonly text: string;\n readonly annotations?: readonly Record<string, unknown>[] | undefined;\n readonly logprobs?: readonly Record<string, unknown>[] | undefined;\n}\nexport interface OpenAIResponsesOutputRefusal { readonly type: 'refusal'; readonly refusal: string; }\nexport type OpenAIResponsesOutputContent = OpenAIResponsesOutputTextContent | OpenAIResponsesOutputRefusal;\n\nexport interface OpenAIResponsesOutputMessage {\n readonly type: 'message'; readonly id?: string | undefined; readonly status?: OpenAIResponsesStatus | undefined;\n readonly role?: string | undefined; readonly phase?: string | undefined;\n readonly content: readonly OpenAIResponsesOutputContent[];\n}\nexport interface OpenAIResponsesOutputFunctionCall {\n readonly type: 'function_call'; readonly id?: string | undefined; readonly call_id?: string | undefined;\n readonly name: string; readonly arguments: string; readonly status?: OpenAIResponsesStatus | undefined;\n}\nexport interface OpenAIResponsesOutputReasoning {\n readonly type: 'reasoning'; readonly id?: string | undefined; readonly status?: OpenAIResponsesStatus | undefined;\n readonly summary?: readonly { readonly type: 'summary_text'; readonly text: string }[] | undefined;\n readonly text?: string | undefined; readonly encrypted_content?: string | undefined;\n}\nexport type OpenAIResponsesOutputItem = OpenAIResponsesOutputMessage | OpenAIResponsesOutputFunctionCall | OpenAIResponsesOutputReasoning;\n\nexport interface OpenAIResponsesUsage {\n readonly input_tokens: number; readonly output_tokens: number; readonly total_tokens: number;\n readonly input_tokens_details?: Record<string, unknown> | undefined;\n readonly output_tokens_details?: Record<string, unknown> | undefined;\n}\n\n/** Non-stateful response shape for the Ollama Responses compatibility endpoint. */\nexport interface OpenAIResponsesResponse {\n readonly id: string; readonly object: 'response'; readonly created: number;\n readonly created_at?: number | undefined; readonly status?: OpenAIResponsesStatus | undefined;\n readonly completed_at?: number | null | undefined; readonly error?: OpenAIResponsesError | null | undefined;\n readonly incomplete_details?: OpenAIResponsesIncompleteDetails | null | undefined;\n readonly model: string; readonly output: readonly OpenAIResponsesOutputItem[];\n readonly output_text?: string | undefined; readonly previous_response_id?: string | null | undefined;\n readonly parallel_tool_calls?: boolean | undefined; readonly usage?: OpenAIResponsesUsage | undefined;\n}\n\nexport class OpenAIResponsesStreamError extends OllamaClientError {\n readonly responsePayload: OpenAIResponsesResponse;\n constructor(message: string, responsePayload: OpenAIResponsesResponse) {\n super(message, { code: 'openai_responses_stream_error', retryable: false, response: { body: responsePayload } });\n this.responsePayload = responsePayload;\n }\n}\nexport class OpenAIChatCompletionStream implements AsyncIterable<OpenAIChatCompletionChunk> {\n private readonly finalResultPromise: Promise<OpenAIChatCompletionResponse>;\n private resolveFinal!: (value: OpenAIChatCompletionResponse) => void;\n private rejectFinal!: (reason: unknown) => void;\n private removeAbortListener: (() => void) | undefined;\n\n constructor(private readonly source: AbortableAsyncIterable<SseEvent>, signal?: AbortSignal) {\n this.finalResultPromise = new Promise<OpenAIChatCompletionResponse>((resolve, reject) => {\n this.resolveFinal = resolve;\n this.rejectFinal = reject;\n });\n if (signal !== undefined) {\n const onAbort = (): void => this.abort();\n if (signal.aborted) onAbort();\n else {\n signal.addEventListener('abort', onAbort, { once: true });\n this.removeAbortListener = () => signal.removeEventListener('abort', onAbort);\n }\n }\n }\n\n get finalResult(): Promise<OpenAIChatCompletionResponse> {\n return this.finalResultPromise;\n }\n\n abort(): void {\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.source.abort?.();\n this.rejectFinal(new OllamaAbortError('OpenAI Chat Completion stream aborted'));\n }\n\n async *[Symbol.asyncIterator](): AsyncGenerator<OpenAIChatCompletionChunk, void, undefined> {\n const choices = new Map<number, {\n message: OpenAIMessage;\n finish_reason: string;\n logprobs?: Record<string, unknown> | null | undefined;\n }>();\n let id = '';\n let model = '';\n let created = 0;\n let systemFingerprint: string | undefined;\n let usage: OpenAIUsage | undefined;\n let completed = false;\n\n try {\n for await (const event of this.source) {\n if (event.data === '[DONE]') break;\n let chunk: OpenAIChatCompletionChunk;\n try {\n chunk = JSON.parse(event.data) as OpenAIChatCompletionChunk;\n } catch (error) {\n throw new Error('Failed to parse OpenAI chat completion SSE payload', { cause: error });\n }\n id = chunk.id || id;\n model = chunk.model || model;\n created = chunk.created || created;\n if (chunk.system_fingerprint !== undefined) systemFingerprint = chunk.system_fingerprint;\n if (chunk.usage !== null && chunk.usage !== undefined) usage = chunk.usage;\n\n for (const choice of chunk.choices) {\n const existing = choices.get(choice.index);\n const delta = choice.delta;\n if (!existing) {\n const toolCalls = delta.tool_calls?.map((toolCall) => ({\n id: toolCall.id ?? '',\n type: 'function' as const,\n function: {\n name: toolCall.function?.name ?? '',\n arguments: toolCall.function?.arguments ?? '',\n },\n }));\n choices.set(choice.index, {\n message: {\n role: delta.role ?? 'assistant',\n content: delta.content ?? '',\n ...(delta.reasoning !== undefined && delta.reasoning !== null\n ? { reasoning: delta.reasoning }\n : {}),\n ...(toolCalls?.length ? { tool_calls: toolCalls } : {}),\n },\n finish_reason: choice.finish_reason ?? '',\n ...(choice.logprobs !== undefined ? { logprobs: choice.logprobs } : {}),\n });\n continue;\n }\n\n const priorToolCalls = [...(existing.message.tool_calls ?? [])];\n for (const toolCall of delta.tool_calls ?? []) {\n const position = toolCall.index;\n const current = priorToolCalls[position];\n if (current) {\n priorToolCalls[position] = {\n ...current,\n ...(toolCall.id !== undefined ? { id: toolCall.id } : {}),\n function: {\n name: current.function?.name ?? toolCall.function?.name ?? '',\n arguments:\n (current.function?.arguments ?? '') + (toolCall.function?.arguments ?? ''),\n },\n };\n } else {\n priorToolCalls[position] = {\n id: toolCall.id ?? '',\n type: 'function',\n function: {\n name: toolCall.function?.name ?? '',\n arguments: toolCall.function?.arguments ?? '',\n },\n };\n }\n }\n choices.set(choice.index, {\n message: {\n ...existing.message,\n ...(delta.content !== undefined && delta.content !== null\n ? { content: existing.message.content + delta.content }\n : {}),\n ...(delta.reasoning !== undefined && delta.reasoning !== null\n ? { reasoning: (existing.message.reasoning ?? '') + delta.reasoning }\n : {}),\n ...(priorToolCalls.length ? { tool_calls: priorToolCalls } : {}),\n },\n finish_reason: choice.finish_reason ?? existing.finish_reason,\n ...(choice.logprobs !== undefined ? { logprobs: choice.logprobs } : {}),\n });\n }\n\n yield chunk;\n }\n\n const response: OpenAIChatCompletionResponse = {\n id,\n object: 'chat.completion',\n created,\n model,\n ...(systemFingerprint !== undefined ? { system_fingerprint: systemFingerprint } : {}),\n choices: [...choices.entries()]\n .sort(([a], [b]) => a - b)\n .map(([index, choice]) => ({\n index,\n message: choice.message,\n finish_reason: choice.finish_reason,\n ...(choice.logprobs !== undefined ? { logprobs: choice.logprobs } : {}),\n })),\n ...(usage !== undefined ? { usage } : {}),\n };\n completed = true;\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.resolveFinal(response);\n } catch (error) {\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.rejectFinal(error);\n throw error;\n } finally {\n if (!completed) {\n this.source.abort?.();\n this.rejectFinal(new OllamaAbortError('OpenAI Chat Completion stream ended before completion'));\n }\n }\n }\n}\n\nexport class OpenAICompletionStream implements AsyncIterable<OpenAICompletionChunk> {\n private readonly finalResultPromise: Promise<OpenAICompletionResponse>;\n private resolveFinal!: (value: OpenAICompletionResponse) => void;\n private rejectFinal!: (reason: unknown) => void;\n private removeAbortListener: (() => void) | undefined;\n\n constructor(private readonly source: AbortableAsyncIterable<SseEvent>, signal?: AbortSignal) {\n this.finalResultPromise = new Promise<OpenAICompletionResponse>((resolve, reject) => {\n this.resolveFinal = resolve;\n this.rejectFinal = reject;\n });\n if (signal !== undefined) {\n const onAbort = (): void => this.abort();\n if (signal.aborted) onAbort();\n else {\n signal.addEventListener('abort', onAbort, { once: true });\n this.removeAbortListener = () => signal.removeEventListener('abort', onAbort);\n }\n }\n }\n\n get finalResult(): Promise<OpenAICompletionResponse> {\n return this.finalResultPromise;\n }\n\n abort(): void {\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.source.abort?.();\n this.rejectFinal(new OllamaAbortError('OpenAI Completion stream aborted'));\n }\n\n async *[Symbol.asyncIterator](): AsyncGenerator<OpenAICompletionChunk, void, undefined> {\n const texts = new Map<number, OpenAICompletionChoice>();\n let id = '';\n let model = '';\n let created = 0;\n let usage:\n | { prompt_tokens: number; completion_tokens: number; total_tokens: number }\n | undefined;\n let completed = false;\n\n try {\n for await (const event of this.source) {\n if (event.data === '[DONE]') break;\n const chunk = JSON.parse(event.data) as OpenAICompletionChunk;\n id = chunk.id || id;\n model = chunk.model || model;\n created = chunk.created || created;\n if (chunk.usage !== null && chunk.usage !== undefined) usage = chunk.usage;\n\n for (const choice of chunk.choices) {\n const existing = texts.get(choice.index);\n texts.set(choice.index, {\n text: (existing?.text ?? '') + (choice.text ?? ''),\n index: choice.index,\n finish_reason: choice.finish_reason ?? existing?.finish_reason ?? null,\n ...(choice.logprobs !== undefined ? { logprobs: choice.logprobs } : {}),\n });\n }\n yield chunk;\n }\n\n const response: OpenAICompletionResponse = {\n id,\n object: 'text_completion',\n created,\n model,\n choices: [...texts.values()].sort((a, b) => a.index - b.index),\n ...(usage !== undefined ? { usage } : {}),\n };\n completed = true;\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.resolveFinal(response);\n } catch (error) {\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.rejectFinal(error);\n throw error;\n } finally {\n if (!completed) {\n this.source.abort?.();\n this.rejectFinal(new OllamaAbortError('OpenAI Completion stream ended before completion'));\n }\n }\n }\n}\n\nexport interface OpenAIResponsesEventBase { readonly response_id?: string | undefined; readonly sequence_number?: number | undefined; }\n\nexport interface OpenAIResponsesOutputTextDeltaEvent extends OpenAIResponsesEventBase { readonly type: 'response.output_text.delta'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly delta: string; }\nexport interface OpenAIResponsesOutputTextDoneEvent extends OpenAIResponsesEventBase { readonly type: 'response.output_text.done'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly text: string; }\nexport interface OpenAIResponsesFunctionCallArgumentsDeltaEvent extends OpenAIResponsesEventBase { readonly type: 'response.function_call_arguments.delta'; readonly item_id: string; readonly output_index: number; readonly delta: string; }\nexport interface OpenAIResponsesFunctionCallArgumentsDoneEvent extends OpenAIResponsesEventBase { readonly type: 'response.function_call_arguments.done'; readonly item_id: string; readonly output_index: number; readonly arguments: string; readonly name?: string | undefined; }\nexport interface OpenAIResponsesReasoningTextDeltaEvent extends OpenAIResponsesEventBase { readonly type: 'response.reasoning_text.delta'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly delta: string; }\nexport interface OpenAIResponsesReasoningTextDoneEvent extends OpenAIResponsesEventBase { readonly type: 'response.reasoning_text.done'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly text: string; }\nexport interface OpenAIResponsesReasoningSummaryPartAddedEvent extends OpenAIResponsesEventBase { readonly type: 'response.reasoning_summary_part.added'; readonly item_id: string; readonly output_index: number; readonly summary_index: number; readonly part: { readonly type: 'summary_text'; readonly text: string }; }\nexport interface OpenAIResponsesReasoningSummaryPartDoneEvent extends OpenAIResponsesEventBase { readonly type: 'response.reasoning_summary_part.done'; readonly item_id: string; readonly output_index: number; readonly summary_index: number; readonly part: { readonly type: 'summary_text'; readonly text: string }; readonly status?: 'incomplete' | undefined; }\nexport interface OpenAIResponsesReasoningSummaryTextDeltaEvent extends OpenAIResponsesEventBase { readonly type: 'response.reasoning_summary_text.delta'; readonly item_id: string; readonly output_index: number; readonly summary_index: number; readonly delta: string; }\nexport interface OpenAIResponsesReasoningSummaryTextDoneEvent extends OpenAIResponsesEventBase { readonly type: 'response.reasoning_summary_text.done'; readonly item_id: string; readonly output_index: number; readonly summary_index: number; readonly text: string; }\nexport interface OpenAIResponsesOutputItemAddedEvent extends OpenAIResponsesEventBase { readonly type: 'response.output_item.added'; readonly item: OpenAIResponsesOutputItem; readonly output_index: number; }\nexport interface OpenAIResponsesOutputItemDoneEvent extends OpenAIResponsesEventBase { readonly type: 'response.output_item.done'; readonly item: OpenAIResponsesOutputItem; readonly output_index: number; }\nexport interface OpenAIResponsesContentPartAddedEvent extends OpenAIResponsesEventBase { readonly type: 'response.content_part.added'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly part: OpenAIResponsesOutputContent | { readonly type: string; readonly [key: string]: unknown }; }\nexport interface OpenAIResponsesContentPartDoneEvent extends OpenAIResponsesEventBase { readonly type: 'response.content_part.done'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly part: OpenAIResponsesOutputContent | { readonly type: string; readonly [key: string]: unknown }; }\nexport interface OpenAIResponsesRefusalDeltaEvent extends OpenAIResponsesEventBase { readonly type: 'response.refusal.delta'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly delta: string; }\nexport interface OpenAIResponsesRefusalDoneEvent extends OpenAIResponsesEventBase { readonly type: 'response.refusal.done'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly refusal: string; }\nexport interface OpenAIResponsesCreatedEvent extends OpenAIResponsesEventBase { readonly type: 'response.created'; readonly response: OpenAIResponsesResponse; }\nexport interface OpenAIResponsesInProgressEvent extends OpenAIResponsesEventBase { readonly type: 'response.in_progress'; readonly response: OpenAIResponsesResponse; }\nexport interface OpenAIResponsesQueuedEvent extends OpenAIResponsesEventBase { readonly type: 'response.queued'; readonly response: OpenAIResponsesResponse; }\nexport interface OpenAIResponsesCompletedEvent extends OpenAIResponsesEventBase { readonly type: 'response.completed' | 'response.done'; readonly response: OpenAIResponsesResponse; }\nexport interface OpenAIResponsesFailedEvent extends OpenAIResponsesEventBase { readonly type: 'response.failed'; readonly response: OpenAIResponsesResponse; }\nexport interface OpenAIResponsesIncompleteEvent extends OpenAIResponsesEventBase { readonly type: 'response.incomplete'; readonly response: OpenAIResponsesResponse; }\n\nexport type OpenAIResponsesStreamEvent =\n | OpenAIResponsesOutputTextDeltaEvent | OpenAIResponsesOutputTextDoneEvent\n | OpenAIResponsesFunctionCallArgumentsDeltaEvent | OpenAIResponsesFunctionCallArgumentsDoneEvent\n | OpenAIResponsesReasoningTextDeltaEvent | OpenAIResponsesReasoningTextDoneEvent\n | OpenAIResponsesReasoningSummaryPartAddedEvent | OpenAIResponsesReasoningSummaryPartDoneEvent\n | OpenAIResponsesReasoningSummaryTextDeltaEvent | OpenAIResponsesReasoningSummaryTextDoneEvent\n | OpenAIResponsesOutputItemAddedEvent | OpenAIResponsesOutputItemDoneEvent\n | OpenAIResponsesContentPartAddedEvent | OpenAIResponsesContentPartDoneEvent\n | OpenAIResponsesRefusalDeltaEvent | OpenAIResponsesRefusalDoneEvent\n | OpenAIResponsesCreatedEvent | OpenAIResponsesInProgressEvent | OpenAIResponsesQueuedEvent\n | OpenAIResponsesCompletedEvent | OpenAIResponsesFailedEvent | OpenAIResponsesIncompleteEvent\n | { readonly type: string; readonly [key: string]: unknown };\n\ntype OpenAIResponsesOutputState = {\n itemId: string; kind: 'message' | 'function_call' | 'reasoning';\n content: Map<number, OpenAIResponsesOutputContent>; summary: Map<number, string>;\n arguments: string; name?: string | undefined; callId?: string | undefined; status?: OpenAIResponsesStatus | undefined;\n role?: string | undefined; phase?: string | undefined; reasoningText: string;\n};\nexport class OpenAIResponsesStream implements AsyncIterable<OpenAIResponsesStreamEvent> {\n private readonly finalResultPromise: Promise<OpenAIResponsesResponse>;\n private resolveFinal!: (value: OpenAIResponsesResponse) => void;\n private rejectFinal!: (reason: unknown) => void;\n private removeAbortListener: (() => void) | undefined;\n\n constructor(private readonly source: AbortableAsyncIterable<SseEvent>, signal?: AbortSignal) {\n this.finalResultPromise = new Promise<OpenAIResponsesResponse>((resolve, reject) => { this.resolveFinal = resolve; this.rejectFinal = reject; });\n if (signal !== undefined) {\n const onAbort = (): void => this.abort();\n if (signal.aborted) onAbort();\n else { signal.addEventListener('abort', onAbort, { once: true }); this.removeAbortListener = () => signal.removeEventListener('abort', onAbort); }\n }\n }\n get finalResult(): Promise<OpenAIResponsesResponse> { return this.finalResultPromise; }\n abort(): void {\n this.removeAbortListener?.(); this.removeAbortListener = undefined; this.source.abort?.();\n this.rejectFinal(new OllamaAbortError('OpenAI Responses stream aborted'));\n }\n\n async *[Symbol.asyncIterator](): AsyncGenerator<OpenAIResponsesStreamEvent, void, undefined> {\n let finalResponse: OpenAIResponsesResponse | undefined;\n let responseMeta: OpenAIResponsesResponse | undefined;\n let terminalFailure: OpenAIResponsesResponse | undefined;\n let terminalIncomplete: OpenAIResponsesResponse | undefined;\n const outputs = new Map<number, OpenAIResponsesOutputState>();\n const canonicalOutputItems = new Map<number, OpenAIResponsesOutputItem>();\n let completed = false;\n\n const ensureState = (outputIndex: number, itemId: string, kind: OpenAIResponsesOutputState['kind']): OpenAIResponsesOutputState => {\n const existing = outputs.get(outputIndex);\n if (existing) { if (itemId) existing.itemId = itemId; existing.kind = kind; return existing; }\n const state: OpenAIResponsesOutputState = { itemId, kind, content: new Map(), summary: new Map(), arguments: '', reasoningText: '' };\n outputs.set(outputIndex, state); return state;\n };\n\n const applyOutputItem = (outputIndex: number, item: OpenAIResponsesOutputItem): void => {\n const kind = item.type === 'message' ? 'message' : item.type === 'function_call' ? 'function_call' : 'reasoning';\n const state = ensureState(outputIndex, item.id ?? '', kind);\n state.itemId = item.id ?? state.itemId; state.status = item.status;\n if (item.type === 'message') { state.role = item.role; state.phase = item.phase; state.content.clear(); item.content.forEach((p, i) => state.content.set(i, p)); }\n else if (item.type === 'function_call') { state.callId = item.call_id; state.name = item.name; state.arguments = item.arguments; }\n else { state.summary.clear(); item.summary?.forEach((p, i) => state.summary.set(i, p.text)); state.reasoningText = item.text ?? ''; }\n };\n const applyContentPart = (outputIndex: number, itemId: string, contentIndex: number, part: OpenAIResponsesOutputContent): void => {\n const state = ensureState(outputIndex, itemId, 'message'); state.content.set(contentIndex, part);\n };\n const reconstructedOutput = (): readonly OpenAIResponsesOutputItem[] =>\n [...outputs.entries()].sort(([a], [b]) => a - b).map(([outputIndex, state]) => {\n const canonical = canonicalOutputItems.get(outputIndex); if (canonical) return canonical;\n if (state.kind === 'message') return { type: 'message', ...(state.itemId ? { id: state.itemId } : {}), ...(state.status ? { status: state.status } : {}), role: state.role ?? 'assistant', ...(state.phase ? { phase: state.phase } : {}), content: [...state.content.entries()].sort(([a], [b]) => a - b).map(([, p]) => p) };\n if (state.kind === 'function_call') return { type: 'function_call', ...(state.itemId ? { id: state.itemId } : {}), ...(state.callId ? { call_id: state.callId } : {}), ...(state.status ? { status: state.status } : {}), name: state.name ?? '', arguments: state.arguments };\n return { type: 'reasoning', ...(state.itemId ? { id: state.itemId } : {}), ...(state.status ? { status: state.status } : {}), ...(state.summary.size ? { summary: [...state.summary.entries()].sort(([a], [b]) => a - b).map(([, text]) => ({ type: 'summary_text' as const, text })) } : {}), ...(state.reasoningText ? { text: state.reasoningText } : {}) };\n });\n\n try {\n for await (const event of this.source) {\n if (event.data === '[DONE]') break;\n let payload: OpenAIResponsesStreamEvent;\n try { payload = JSON.parse(event.data) as OpenAIResponsesStreamEvent; } catch (error) { throw new Error('Failed to parse OpenAI Responses SSE payload', { cause: error }); }\n switch (payload.type) {\n case 'response.created': case 'response.in_progress': case 'response.queued': responseMeta = (payload as OpenAIResponsesCreatedEvent).response; break;\n case 'response.completed': case 'response.done': finalResponse = (payload as OpenAIResponsesCompletedEvent).response; break;\n case 'response.failed': terminalFailure = (payload as OpenAIResponsesFailedEvent).response; finalResponse = terminalFailure; break;\n case 'response.incomplete': terminalIncomplete = (payload as OpenAIResponsesIncompleteEvent).response; finalResponse = terminalIncomplete; break;\n case 'response.output_item.added': { const e = payload as OpenAIResponsesOutputItemAddedEvent; applyOutputItem(e.output_index, e.item); break; }\n case 'response.output_item.done': { const e = payload as OpenAIResponsesOutputItemDoneEvent; applyOutputItem(e.output_index, e.item); canonicalOutputItems.set(e.output_index, e.item); break; }\n case 'response.content_part.added': case 'response.content_part.done': {\n const e = payload as OpenAIResponsesContentPartAddedEvent | OpenAIResponsesContentPartDoneEvent;\n if (\n (e.part.type === 'output_text' && 'text' in e.part && typeof e.part.text === 'string') ||\n (e.part.type === 'refusal' && 'refusal' in e.part && typeof e.part.refusal === 'string')\n ) {\n applyContentPart(e.output_index, e.item_id, e.content_index, e.part as OpenAIResponsesOutputContent);\n }\n break;\n }\n case 'response.output_text.delta': { const e = payload as OpenAIResponsesOutputTextDeltaEvent; const s = ensureState(e.output_index, e.item_id, 'message'); const p=s.content.get(e.content_index); s.content.set(e.content_index,{type:'output_text',text:(p?.type==='output_text'?p.text:'')+e.delta}); break; }\n case 'response.output_text.done': { const e = payload as OpenAIResponsesOutputTextDoneEvent; const s=ensureState(e.output_index,e.item_id,'message'); s.content.set(e.content_index,{type:'output_text',text:e.text}); break; }\n case 'response.refusal.delta': { const e=payload as OpenAIResponsesRefusalDeltaEvent; const s=ensureState(e.output_index,e.item_id,'message'); const p=s.content.get(e.content_index); s.content.set(e.content_index,{type:'refusal',refusal:(p?.type==='refusal'?p.refusal:'')+e.delta}); break; }\n case 'response.refusal.done': { const e=payload as OpenAIResponsesRefusalDoneEvent; const s=ensureState(e.output_index,e.item_id,'message'); s.content.set(e.content_index,{type:'refusal',refusal:e.refusal}); break; }\n case 'response.function_call_arguments.delta': { const e=payload as OpenAIResponsesFunctionCallArgumentsDeltaEvent; const s=ensureState(e.output_index,e.item_id,'function_call'); s.arguments+=e.delta; break; }\n case 'response.function_call_arguments.done': { const e=payload as OpenAIResponsesFunctionCallArgumentsDoneEvent; const s=ensureState(e.output_index,e.item_id,'function_call'); s.arguments=e.arguments; if(e.name!==undefined) s.name=e.name; break; }\n case 'response.reasoning_summary_part.added': case 'response.reasoning_summary_part.done': { const e=payload as OpenAIResponsesReasoningSummaryPartAddedEvent | OpenAIResponsesReasoningSummaryPartDoneEvent; const s=ensureState(e.output_index,e.item_id,'reasoning'); s.summary.set(e.summary_index,e.part.text); break; }\n case 'response.reasoning_summary_text.delta': { const e=payload as OpenAIResponsesReasoningSummaryTextDeltaEvent; const s=ensureState(e.output_index,e.item_id,'reasoning'); s.summary.set(e.summary_index,(s.summary.get(e.summary_index)??'')+e.delta); break; }\n case 'response.reasoning_summary_text.done': { const e=payload as OpenAIResponsesReasoningSummaryTextDoneEvent; const s=ensureState(e.output_index,e.item_id,'reasoning'); s.summary.set(e.summary_index,e.text); break; }\n case 'response.reasoning_text.delta': { const e=payload as OpenAIResponsesReasoningTextDeltaEvent; const s=ensureState(e.output_index,e.item_id,'reasoning'); s.reasoningText+=e.delta; break; }\n case 'response.reasoning_text.done': { const e=payload as OpenAIResponsesReasoningTextDoneEvent; const s=ensureState(e.output_index,e.item_id,'reasoning'); s.reasoningText=e.text; break; }\n default: break;\n }\n yield payload;\n }\n if (terminalFailure || terminalIncomplete) {\n const response = terminalFailure ?? terminalIncomplete!; const status = terminalFailure ? 'failed' : 'incomplete';\n const detail = response.error?.message ?? response.incomplete_details?.reason ?? 'unknown error';\n throw new OpenAIResponsesStreamError('OpenAI Responses stream ' + status + ': ' + detail, response);\n }\n if (!finalResponse) {\n if (!responseMeta) throw new Error('OpenAI Responses stream ended without a terminal response payload');\n if (responseMeta.status === 'failed' || responseMeta.status === 'incomplete') {\n const detail=responseMeta.error?.message ?? responseMeta.incomplete_details?.reason ?? 'unknown error';\n throw new OpenAIResponsesStreamError('OpenAI Responses stream ' + responseMeta.status + ': ' + detail, responseMeta);\n }\n finalResponse={...responseMeta,output:reconstructedOutput(),status:'completed'};\n } else if (finalResponse.status === 'failed' || finalResponse.status === 'incomplete') {\n const detail=finalResponse.error?.message ?? finalResponse.incomplete_details?.reason ?? 'unknown error';\n throw new OpenAIResponsesStreamError('OpenAI Responses stream ' + finalResponse.status + ': ' + detail, finalResponse);\n }\n if (finalResponse.output.length===0 && outputs.size>0) finalResponse={...finalResponse,output:reconstructedOutput()};\n completed=true; this.removeAbortListener?.(); this.removeAbortListener=undefined; this.resolveFinal(finalResponse);\n } catch(error) { this.removeAbortListener?.(); this.removeAbortListener=undefined; this.rejectFinal(error); throw error; }\n finally { if(!completed){ this.source.abort?.(); this.rejectFinal(new OllamaAbortError('OpenAI Responses stream ended before completion')); } }\n }\n}\nexport class OpenAICompatClient {\n constructor(\n private readonly http: HttpClient,\n private readonly runner?: RequestRunner | undefined,\n ) {}\n\n private request<T>(\n operation: (http: HttpClient, signal?: AbortSignal) => Promise<T>,\n model: string | undefined,\n signal?: AbortSignal,\n holdUntil?: ((result: T) => Promise<unknown>) | undefined,\n ): Promise<T> {\n if (this.runner) {\n return this.runner(\n (http, runnerSignal) => operation(http, runnerSignal),\n {\n ...(model !== undefined ? { model } : {}),\n ...(signal !== undefined ? { signal } : {}),\n ...(holdUntil !== undefined ? { holdUntil } : {}),\n },\n );\n }\n return operation(this.http, signal);\n }\n\n async createChatCompletion(\n request: OpenAIChatCompletionRequest & { stream: true },\n signal?: AbortSignal,\n ): Promise<OpenAIChatCompletionStream>;\n async createChatCompletion(\n request: OpenAIChatCompletionRequest & { stream?: false | undefined },\n signal?: AbortSignal,\n ): Promise<OpenAIChatCompletionResponse>;\n async createChatCompletion(\n request: OpenAIChatCompletionRequest,\n signal?: AbortSignal,\n ): Promise<OpenAIChatCompletionResponse | OpenAIChatCompletionStream> {\n if (request.stream) {\n return this.request(\n (http, requestSignal) =>\n http.requestSseStream({\n path: '/v1/chat/completions',\n body: request,\n signal: requestSignal,\n }).then((source) => new OpenAIChatCompletionStream(source, requestSignal)),\n request.model,\n signal,\n (stream: OpenAIChatCompletionStream) => stream.finalResult,\n );\n }\n return this.request(\n (http, requestSignal) =>\n http.request<OpenAIChatCompletionResponse>({\n path: '/v1/chat/completions',\n body: request,\n signal: requestSignal,\n }),\n request.model,\n signal,\n );\n }\n\n async chatCompletions(\n request: OpenAIChatCompletionRequest & { stream: true },\n signal?: AbortSignal,\n ): Promise<OpenAIChatCompletionStream>;\n async chatCompletions(\n request: OpenAIChatCompletionRequest & { stream?: false | undefined },\n signal?: AbortSignal,\n ): Promise<OpenAIChatCompletionResponse>;\n async chatCompletions(\n request: OpenAIChatCompletionRequest,\n signal?: AbortSignal,\n ): Promise<OpenAIChatCompletionResponse | OpenAIChatCompletionStream> {\n return this.createChatCompletion(request as never, signal);\n }\n\n async listModels(signal?: AbortSignal): Promise<OpenAIListModelsResponse> {\n return this.request(\n (http, requestSignal) =>\n http.request<OpenAIListModelsResponse>({\n path: '/v1/models',\n method: 'GET',\n signal: requestSignal,\n }),\n undefined,\n signal,\n );\n }\n\n async retrieveModel(\n model: string,\n signal?: AbortSignal,\n ): Promise<OpenAIModelItem> {\n return this.request(\n (http, requestSignal) =>\n http.request<OpenAIModelItem>({\n path: `/v1/models/${encodeURIComponent(model)}`,\n method: 'GET',\n signal: requestSignal,\n }),\n model,\n signal,\n );\n }\n\n async getModel(model: string, signal?: AbortSignal): Promise<OpenAIModelItem> {\n return this.retrieveModel(model, signal);\n }\n\n async createCompletion(\n request: OpenAICompletionRequest & { stream: true },\n signal?: AbortSignal,\n ): Promise<OpenAICompletionStream>;\n async createCompletion(\n request: OpenAICompletionRequest & { stream?: false | undefined },\n signal?: AbortSignal,\n ): Promise<OpenAICompletionResponse>;\n async createCompletion(\n request: OpenAICompletionRequest,\n signal?: AbortSignal,\n ): Promise<OpenAICompletionResponse | OpenAICompletionStream> {\n if (request.stream) {\n return this.request(\n (http, requestSignal) =>\n http.requestSseStream({\n path: '/v1/completions',\n body: request,\n signal: requestSignal,\n }).then((source) => new OpenAICompletionStream(source, requestSignal)),\n request.model,\n signal,\n (stream: OpenAICompletionStream) => stream.finalResult,\n );\n }\n return this.request(\n (http, requestSignal) =>\n http.request<OpenAICompletionResponse>({\n path: '/v1/completions',\n body: request,\n signal: requestSignal,\n }),\n request.model,\n signal,\n );\n }\n\n async completions(\n request: OpenAICompletionRequest & { stream: true },\n signal?: AbortSignal,\n ): Promise<OpenAICompletionStream>;\n async completions(\n request: OpenAICompletionRequest & { stream?: false | undefined },\n signal?: AbortSignal,\n ): Promise<OpenAICompletionResponse>;\n async completions(\n request: OpenAICompletionRequest,\n signal?: AbortSignal,\n ): Promise<OpenAICompletionResponse | OpenAICompletionStream> {\n return this.createCompletion(request as never, signal);\n }\n\n async createEmbedding(\n request: OpenAIEmbeddingRequest,\n signal?: AbortSignal,\n ): Promise<OpenAIEmbeddingResponse> {\n return this.request(\n (http, requestSignal) =>\n http.request<OpenAIEmbeddingResponse>({\n path: '/v1/embeddings',\n body: request,\n signal: requestSignal,\n }),\n request.model,\n signal,\n );\n }\n\n async embeddings(\n request: OpenAIEmbeddingRequest,\n signal?: AbortSignal,\n ): Promise<OpenAIEmbeddingResponse> {\n return this.createEmbedding(request, signal);\n }\n\n async createResponses(\n request: OpenAIResponsesRequest & { stream: true },\n signal?: AbortSignal,\n ): Promise<OpenAIResponsesStream>;\n async createResponses(\n request: OpenAIResponsesRequest & { stream?: false | undefined },\n signal?: AbortSignal,\n ): Promise<OpenAIResponsesResponse>;\n async createResponses(\n request: OpenAIResponsesRequest,\n signal?: AbortSignal,\n ): Promise<OpenAIResponsesResponse | OpenAIResponsesStream> {\n if (request.stream) {\n return this.request(\n (http, requestSignal) =>\n http.requestSseStream({\n path: '/v1/responses',\n body: request,\n signal: requestSignal,\n }).then((source) => new OpenAIResponsesStream(source, requestSignal)),\n request.model,\n signal,\n (stream: OpenAIResponsesStream) => stream.finalResult,\n );\n }\n return this.request(\n (http, requestSignal) =>\n http.request<OpenAIResponsesResponse>({\n path: '/v1/responses',\n body: request,\n signal: requestSignal,\n }),\n request.model,\n signal,\n );\n }\n\n async responses(\n request: OpenAIResponsesRequest & { stream: true },\n signal?: AbortSignal,\n ): Promise<OpenAIResponsesStream>;\n async responses(\n request: OpenAIResponsesRequest & { stream?: false | undefined },\n signal?: AbortSignal,\n ): Promise<OpenAIResponsesResponse>;\n async responses(\n request: OpenAIResponsesRequest,\n signal?: AbortSignal,\n ): Promise<OpenAIResponsesResponse | OpenAIResponsesStream> {\n return this.createResponses(request as never, signal);\n }\n}\n","/**\n * Anthropic Compatibility interfaces and client helpers for Ollama.\n * Ollama supports the Anthropic Messages API format.\n */\n\nimport type { AbortableAsyncIterable } from '../streaming/types.js';\nimport type { SseEvent } from '../streaming/sse.js';\nimport type { HttpClient } from '../transport/http.js';\nimport type { RequestRunner } from '../transport/runner.js';\nimport { OllamaAbortError } from '../errors.js';\n\nexport interface AnthropicCacheControl {\n readonly type: 'ephemeral';\n readonly ttl?: '5m' | '1h' | undefined;\n}\n\nexport interface AnthropicTextContentBlock {\n readonly type: 'text';\n readonly text: string;\n readonly cache_control?: AnthropicCacheControl | undefined;\n}\n\nexport interface AnthropicImageContentBlock {\n readonly type: 'image';\n readonly source: {\n readonly type: 'base64';\n readonly media_type: string;\n readonly data: string;\n };\n}\n\nexport interface AnthropicToolUseContentBlock {\n readonly type: 'tool_use';\n readonly id: string;\n readonly name: string;\n readonly input: Record<string, unknown>;\n}\n\nexport interface AnthropicToolResultContentBlock {\n readonly type: 'tool_result';\n readonly tool_use_id: string;\n readonly content?: string | readonly AnthropicTextContentBlock[] | undefined;\n readonly is_error?: boolean | undefined;\n}\n\nexport interface AnthropicThinkingContentBlock {\n readonly type: 'thinking';\n readonly thinking: string;\n readonly signature?: string | undefined;\n}\n\nexport interface AnthropicRedactedThinkingContentBlock {\n readonly type: 'redacted_thinking';\n readonly data: string;\n}\n\nexport type AnthropicContentBlock =\n | AnthropicTextContentBlock\n | AnthropicImageContentBlock\n | AnthropicToolUseContentBlock\n | AnthropicToolResultContentBlock\n | AnthropicThinkingContentBlock\n | AnthropicRedactedThinkingContentBlock;\n\nexport interface AnthropicMessage {\n readonly role: 'user' | 'assistant';\n readonly content: string | readonly AnthropicContentBlock[];\n}\n\nexport interface AnthropicSystemTextBlock {\n readonly type: 'text';\n readonly text: string;\n readonly cache_control?: AnthropicCacheControl | undefined;\n}\n\nexport type AnthropicSystem = string | readonly AnthropicSystemTextBlock[];\n\nexport interface AnthropicTool {\n readonly name: string;\n readonly description?: string | undefined;\n readonly input_schema: Record<string, unknown>;\n readonly eager_input_streaming?: boolean | undefined;\n}\n\nexport type AnthropicToolChoice =\n | { readonly type: 'auto'; readonly disable_parallel_tool_use?: boolean | undefined }\n | { readonly type: 'any'; readonly disable_parallel_tool_use?: boolean | undefined }\n | { readonly type: 'tool'; readonly name: string; readonly disable_parallel_tool_use?: boolean | undefined }\n | { readonly type: 'none' };\n\nexport interface AnthropicThinkingConfig {\n readonly type: 'enabled' | 'disabled' | 'adaptive';\n readonly display?: 'omitted' | 'summarized' | 'updates' | undefined;\n /** Accepted by Ollama for compatibility but currently not enforced by the server. */\n readonly budget_tokens?: number | undefined;\n}\n\nexport interface AnthropicOutputConfig {\n readonly effort?: string | undefined;\n}\n\nexport interface AnthropicMetadata {\n readonly user_id?: string | undefined;\n}\n\nexport interface AnthropicMessagesRequest {\n readonly model: string;\n readonly messages: readonly AnthropicMessage[];\n readonly system?: AnthropicSystem | undefined;\n readonly max_tokens?: number | undefined;\n readonly temperature?: number | undefined;\n readonly top_p?: number | undefined;\n readonly top_k?: number | undefined;\n readonly stop_sequences?: readonly string[] | undefined;\n readonly stream?: boolean | undefined;\n readonly tools?: readonly AnthropicTool[] | undefined;\n readonly thinking?: AnthropicThinkingConfig | undefined;\n readonly output_config?: AnthropicOutputConfig | undefined;\n /**\n * Accepted for Anthropic compatibility but currently ignored by Ollama.\n * Tool selection cannot be forced through the Ollama compatibility endpoint.\n */\n readonly tool_choice?: AnthropicToolChoice | undefined;\n /** Accepted for compatibility but currently ignored by Ollama. */\n readonly metadata?: AnthropicMetadata | undefined;\n}\n\n/** Strict Ollama-documented Messages request; excludes fields Ollama marks unsupported. */\nexport type OllamaAnthropicTextContentBlock = Omit<\n AnthropicTextContentBlock,\n 'cache_control'\n>;\n\nexport type OllamaAnthropicTool = Omit<AnthropicTool, 'eager_input_streaming'>;\n\nexport type OllamaAnthropicThinkingConfig = {\n readonly type: 'enabled' | 'disabled';\n /** Accepted by Ollama for compatibility but currently not enforced by the server. */\n readonly budget_tokens?: number | undefined;\n};\n\nexport type OllamaAnthropicToolResultContentBlock = Omit<\n AnthropicToolResultContentBlock,\n 'content'\n> & {\n readonly content?: string | readonly OllamaAnthropicTextContentBlock[] | undefined;\n};\n\nexport type OllamaAnthropicContentBlock =\n | OllamaAnthropicTextContentBlock\n | AnthropicImageContentBlock\n | AnthropicToolUseContentBlock\n | OllamaAnthropicToolResultContentBlock\n | AnthropicThinkingContentBlock;\n\nexport type OllamaAnthropicMessage = Omit<AnthropicMessage, 'content'> & {\n readonly content: string | readonly OllamaAnthropicContentBlock[];\n};\n\nexport type OllamaAnthropicSystemTextBlock = Omit<\n AnthropicSystemTextBlock,\n 'cache_control'\n>;\n\nexport type OllamaAnthropicSystem =\n | string\n | readonly OllamaAnthropicSystemTextBlock[];\n\n/** Strict Ollama-documented Messages request; excludes unsupported caching/tool-choice metadata. */\nexport type OllamaAnthropicMessagesRequest = Omit<\n AnthropicMessagesRequest,\n 'messages' | 'system' | 'tools' | 'thinking' | 'tool_choice' | 'metadata'\n> & {\n readonly messages: readonly OllamaAnthropicMessage[];\n readonly system?: OllamaAnthropicSystem | undefined;\n readonly tools?: readonly OllamaAnthropicTool[] | undefined;\n readonly thinking?: OllamaAnthropicThinkingConfig | undefined;\n};\n\nexport interface AnthropicMessagesResponse {\n readonly id: string;\n readonly type: 'message';\n readonly role: 'assistant';\n readonly content: readonly AnthropicContentBlock[];\n readonly model: string;\n readonly stop_reason: string | null;\n readonly stop_sequence?: string | null | undefined;\n readonly usage?: {\n readonly input_tokens: number;\n readonly output_tokens: number;\n readonly cache_creation_input_tokens?: number | undefined;\n readonly cache_read_input_tokens?: number | undefined;\n readonly cache_creation?: Record<string, unknown> | undefined;\n } | undefined;\n}\n\nexport interface AnthropicMessageStartEvent {\n readonly type: 'message_start';\n readonly message: AnthropicMessagesResponse;\n}\n\nexport interface AnthropicContentBlockStartEvent {\n readonly type: 'content_block_start';\n readonly index: number;\n readonly content_block: AnthropicContentBlock;\n}\n\nexport type AnthropicContentBlockDelta =\n | { readonly type: 'text_delta'; readonly text: string }\n | { readonly type: 'input_json_delta'; readonly partial_json: string }\n | { readonly type: 'thinking_delta'; readonly thinking: string }\n | { readonly type: 'signature_delta'; readonly signature: string };\n\nexport interface AnthropicContentBlockDeltaEvent {\n readonly type: 'content_block_delta';\n readonly index: number;\n readonly delta: AnthropicContentBlockDelta;\n}\n\nexport interface AnthropicContentBlockStopEvent {\n readonly type: 'content_block_stop';\n readonly index: number;\n}\n\nexport interface AnthropicMessageDeltaEvent {\n readonly type: 'message_delta';\n readonly delta: {\n readonly stop_reason?: string | null | undefined;\n readonly stop_sequence?: string | null | undefined;\n };\n readonly usage?: {\n readonly input_tokens?: number | undefined;\n readonly output_tokens: number;\n readonly cache_creation_input_tokens?: number | undefined;\n readonly cache_read_input_tokens?: number | undefined;\n readonly cache_creation?: Record<string, unknown> | undefined;\n } | undefined;\n}\n\nexport interface AnthropicMessageStopEvent {\n readonly type: 'message_stop';\n}\n\nexport interface AnthropicPingEvent {\n readonly type: 'ping';\n}\n\nexport interface AnthropicErrorEvent {\n readonly type: 'error';\n readonly error: {\n readonly type: string;\n readonly message: string;\n };\n}\n\nexport interface AnthropicUnknownStreamEvent {\n /** Forward-compatible event type not yet modeled by this SDK. */\n readonly type: string;\n readonly [key: string]: unknown;\n}\n\nexport type AnthropicMessageStreamEvent =\n | AnthropicMessageStartEvent\n | AnthropicContentBlockStartEvent\n | AnthropicContentBlockDeltaEvent\n | AnthropicContentBlockStopEvent\n | AnthropicMessageDeltaEvent\n | AnthropicMessageStopEvent\n | AnthropicPingEvent\n | AnthropicErrorEvent\n | AnthropicUnknownStreamEvent;\n\ntype AnthropicKnownStreamEvent = Exclude<\n AnthropicMessageStreamEvent,\n AnthropicUnknownStreamEvent\n>;\n\nfunction isAnthropicKnownStreamEvent(\n event: AnthropicMessageStreamEvent,\n): event is AnthropicKnownStreamEvent {\n switch (event.type) {\n case 'message_start':\n case 'content_block_start':\n case 'content_block_delta':\n case 'content_block_stop':\n case 'message_delta':\n case 'message_stop':\n case 'ping':\n case 'error':\n return true;\n default:\n return false;\n }\n}\n\nfunction parseAnthropicEvent(event: SseEvent): AnthropicMessageStreamEvent {\n return JSON.parse(event.data) as AnthropicMessageStreamEvent;\n}\n\nfunction mergeContentBlock(\n current: AnthropicContentBlock,\n delta: AnthropicContentBlockDelta,\n): AnthropicContentBlock {\n if (delta.type === 'text_delta' && current.type === 'text') {\n return { ...current, text: current.text + delta.text };\n }\n if (delta.type === 'input_json_delta' && current.type === 'tool_use') {\n return current;\n }\n if (delta.type === 'thinking_delta' && current.type === 'thinking') {\n return { ...current, thinking: current.thinking + delta.thinking };\n }\n if (delta.type === 'signature_delta' && current.type === 'thinking') {\n return { ...current, signature: (current.signature ?? '') + delta.signature };\n }\n return current;\n}\n\nfunction sanitizeAnthropicTextBlock(\n block: AnthropicTextContentBlock,\n): OllamaAnthropicTextContentBlock {\n if (block.cache_control === undefined) return block;\n const { cache_control: _cacheControl, ...sanitized } = block;\n return sanitized;\n}\n\nfunction sanitizeAnthropicContentBlock(\n block: AnthropicContentBlock,\n): AnthropicContentBlock {\n if (block.type === 'text') {\n return sanitizeAnthropicTextBlock(block);\n }\n\n if (block.type === 'tool_result' && Array.isArray(block.content)) {\n return {\n ...block,\n content: block.content.map(sanitizeAnthropicTextBlock),\n };\n }\n\n return block;\n}\n\nfunction sanitizeAnthropicRequest(request: AnthropicMessagesRequest): AnthropicMessagesRequest {\n const messages = request.messages.map((message) => {\n if (typeof message.content === 'string') return message;\n return {\n ...message,\n content: message.content.map(sanitizeAnthropicContentBlock),\n };\n });\n\n const system = Array.isArray(request.system)\n ? request.system.map(sanitizeAnthropicTextBlock)\n : request.system;\n\n const {\n tool_choice: _toolChoice,\n metadata: _metadata,\n ...sanitized\n } = request;\n\n return {\n ...sanitized,\n messages,\n ...(system !== undefined ? { system } : {}),\n };\n}\nexport class AnthropicMessagesStream implements AsyncIterable<AnthropicMessageStreamEvent> {\n private readonly finalResultPromise: Promise<AnthropicMessagesResponse>;\n private resolveFinal!: (value: AnthropicMessagesResponse) => void;\n private rejectFinal!: (reason: unknown) => void;\n private removeAbortListener: (() => void) | undefined;\n\n constructor(private readonly source: AbortableAsyncIterable<SseEvent>, signal?: AbortSignal) {\n this.finalResultPromise = new Promise<AnthropicMessagesResponse>((resolve, reject) => {\n this.resolveFinal = resolve;\n this.rejectFinal = reject;\n });\n if (signal !== undefined) {\n const onAbort = (): void => this.abort();\n if (signal.aborted) onAbort();\n else {\n signal.addEventListener('abort', onAbort, { once: true });\n this.removeAbortListener = () => signal.removeEventListener('abort', onAbort);\n }\n }\n }\n\n get finalResult(): Promise<AnthropicMessagesResponse> {\n return this.finalResultPromise;\n }\n\n abort(): void {\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.source.abort?.();\n this.rejectFinal(new OllamaAbortError('Anthropic Messages stream aborted'));\n }\n\n async *[Symbol.asyncIterator](): AsyncGenerator<AnthropicMessageStreamEvent, void, undefined> {\n let message:\n | AnthropicMessagesResponse\n | undefined;\n const blocks = new Map<number, AnthropicContentBlock>();\n const toolInputJson = new Map<number, string>();\n let completed = false;\n\n try {\n for await (const rawEvent of this.source) {\n let event: AnthropicMessageStreamEvent;\n try {\n event = parseAnthropicEvent(rawEvent);\n } catch (error) {\n throw new Error('Failed to parse Anthropic message SSE payload', { cause: error });\n }\n\n if (!isAnthropicKnownStreamEvent(event)) {\n yield event;\n continue;\n }\n\n if (event.type === 'error') {\n throw new Error(event.error.message);\n }\n\n if (event.type === 'message_start') {\n message = {\n ...event.message,\n content: [],\n ...(event.message.usage !== undefined ? { usage: event.message.usage } : {}),\n };\n } else if (event.type === 'content_block_start') {\n blocks.set(event.index, event.content_block);\n } else if (event.type === 'content_block_delta') {\n const current = blocks.get(event.index);\n if (event.delta.type === 'input_json_delta') {\n toolInputJson.set(event.index, (toolInputJson.get(event.index) ?? '') + event.delta.partial_json);\n }\n if (current) blocks.set(event.index, mergeContentBlock(current, event.delta));\n } else if (event.type === 'content_block_stop') {\n const current = blocks.get(event.index);\n if (current?.type === 'tool_use') {\n const rawJson = toolInputJson.get(event.index);\n if (rawJson !== undefined && rawJson !== '') {\n try {\n const parsed = JSON.parse(rawJson) as Record<string, unknown>;\n blocks.set(event.index, { ...current, input: parsed });\n } catch {\n // Keep the provider-provided partial object when the accumulated JSON is malformed.\n blocks.set(event.index, current);\n }\n }\n }\n } else if (event.type === 'message_delta') {\n if (message) {\n message = {\n ...message,\n stop_reason:\n event.delta.stop_reason !== undefined && event.delta.stop_reason !== null\n ? event.delta.stop_reason\n : message.stop_reason,\n stop_sequence: event.delta.stop_sequence ?? message.stop_sequence,\n ...(event.usage !== undefined\n ? {\n usage: {\n input_tokens: event.usage.input_tokens ?? message.usage?.input_tokens ?? 0,\n output_tokens: event.usage.output_tokens,\n ...(event.usage.cache_creation_input_tokens !== undefined\n ? { cache_creation_input_tokens: event.usage.cache_creation_input_tokens }\n : message.usage?.cache_creation_input_tokens !== undefined\n ? { cache_creation_input_tokens: message.usage.cache_creation_input_tokens }\n : {}),\n ...(event.usage.cache_read_input_tokens !== undefined\n ? { cache_read_input_tokens: event.usage.cache_read_input_tokens }\n : message.usage?.cache_read_input_tokens !== undefined\n ? { cache_read_input_tokens: message.usage.cache_read_input_tokens }\n : {}),\n ...(event.usage.cache_creation !== undefined\n ? { cache_creation: event.usage.cache_creation }\n : message.usage?.cache_creation !== undefined\n ? { cache_creation: message.usage.cache_creation }\n : {}),\n },\n }\n : {}),\n };\n }\n } else if (event.type === 'message_stop' && message) {\n message = {\n ...message,\n content: [...blocks.entries()].sort(([a], [b]) => a - b).map(([, block]) => block),\n };\n }\n\n yield event;\n }\n\n if (!message) {\n throw new Error('Anthropic Messages stream ended without message_start');\n }\n\n const final: AnthropicMessagesResponse = {\n ...message,\n content: [...blocks.entries()].sort(([a], [b]) => a - b).map(([, block]) => block),\n };\n completed = true;\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.resolveFinal(final);\n } catch (error) {\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.rejectFinal(error);\n throw error;\n } finally {\n if (!completed) {\n this.source.abort?.();\n this.rejectFinal(new OllamaAbortError('Anthropic Messages stream ended before completion'));\n }\n }\n }\n}\n\nexport class AnthropicCompatClient {\n constructor(\n private readonly http: HttpClient,\n private readonly runner?: RequestRunner | undefined,\n ) {}\n\n private request<T>(\n operation: (http: HttpClient, signal?: AbortSignal) => Promise<T>,\n model: string,\n signal?: AbortSignal,\n holdUntil?: ((result: T) => Promise<unknown>) | undefined,\n ): Promise<T> {\n if (this.runner) {\n return this.runner(\n (http, runnerSignal) => operation(http, runnerSignal),\n {\n model,\n ...(signal !== undefined ? { signal } : {}),\n ...(holdUntil !== undefined ? { holdUntil } : {}),\n },\n );\n }\n return operation(this.http, signal);\n }\n\n async createMessage(\n request: AnthropicMessagesRequest & { stream: true },\n signal?: AbortSignal,\n ): Promise<AnthropicMessagesStream>;\n async createMessage(\n request: AnthropicMessagesRequest & { stream?: false | undefined },\n signal?: AbortSignal,\n ): Promise<AnthropicMessagesResponse>;\n async createMessage(\n request: AnthropicMessagesRequest,\n signal?: AbortSignal,\n ): Promise<AnthropicMessagesResponse | AnthropicMessagesStream>;\n async createMessage(\n request: AnthropicMessagesRequest,\n signal?: AbortSignal,\n ): Promise<AnthropicMessagesResponse | AnthropicMessagesStream> {\n if (request.stream) {\n return this.request(\n (http, requestSignal) =>\n http.requestSseStream({\n path: '/v1/messages',\n body: sanitizeAnthropicRequest(request),\n headers: { 'anthropic-version': '2023-06-01' },\n signal: requestSignal,\n }).then((source) => new AnthropicMessagesStream(source, requestSignal)),\n request.model,\n signal,\n (stream: AnthropicMessagesStream) => stream.finalResult,\n );\n }\n return this.request(\n (http, requestSignal) =>\n http.request<AnthropicMessagesResponse>({\n path: '/v1/messages',\n body: sanitizeAnthropicRequest(request),\n headers: { 'anthropic-version': '2023-06-01' },\n signal: requestSignal,\n }),\n request.model,\n signal,\n );\n }\n\n async messages(\n request: AnthropicMessagesRequest & { stream: true },\n signal?: AbortSignal,\n ): Promise<AnthropicMessagesStream>;\n async messages(\n request: AnthropicMessagesRequest & { stream?: false | undefined },\n signal?: AbortSignal,\n ): Promise<AnthropicMessagesResponse>;\n async messages(\n request: AnthropicMessagesRequest,\n signal?: AbortSignal,\n ): Promise<AnthropicMessagesResponse | AnthropicMessagesStream>;\n async messages(\n request: AnthropicMessagesRequest,\n signal?: AbortSignal,\n ): Promise<AnthropicMessagesResponse | AnthropicMessagesStream> {\n if (request.stream) {\n return this.createMessage(request, signal);\n }\n return this.createMessage(request, signal);\n }\n}\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const ToolCallSchema = z.object({\n function: z\n .object({\n name: z.string(),\n description: z.string().optional(),\n arguments: z.object({}).optional(),\n })\n .optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { ToolCallSchema } from './ToolCall.schema.js';\n\nexport const ChatMessageSchema = z.object({\n role: z.enum(['system', 'user', 'assistant', 'tool']),\n content: z.string(),\n images: z.array(z.string()).optional(),\n tool_calls: z.array(ToolCallSchema).optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\n/** Runtime options that control text generation */\nexport const ModelOptionsSchema = z\n .object({\n seed: z.number().optional(),\n temperature: z.number().optional(),\n top_k: z.number().optional(),\n top_p: z.number().optional(),\n min_p: z.number().optional(),\n stop: z.union([z.string(), z.array(z.string())]).optional(),\n num_ctx: z.number().optional(),\n num_predict: z.number().optional(),\n })\n .catchall(z.unknown());\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\n/** Controls a model's thinking output. Use `/api/show` to discover the supported values and default for the selected model. `true` requests thinking, `false` requests no thinking output, and `null` uses the model default. String values are model-defined; supported names must match `/api/show` exactly. Numbers are not supported. */\nexport const ThinkValueSchema = z.union([z.boolean(), z.string(), z.null()]);\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const ToolDefinitionSchema = z.object({\n type: z.enum(['function']),\n function: z.object({\n name: z.string(),\n description: z.string().optional(),\n parameters: z.object({}),\n }),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { ChatMessageSchema } from './ChatMessage.schema.js';\nimport { ModelOptionsSchema } from './ModelOptions.schema.js';\nimport { ThinkValueSchema } from './ThinkValue.schema.js';\nimport { ToolDefinitionSchema } from './ToolDefinition.schema.js';\n\nexport const ChatRequestSchema = z.object({\n model: z.string(),\n messages: z.array(ChatMessageSchema),\n tools: z.array(ToolDefinitionSchema).optional(),\n format: z.union([z.enum(['json']), z.object({})]).optional(),\n options: ModelOptionsSchema.optional(),\n stream: z.boolean().optional(),\n think: ThinkValueSchema.optional(),\n keep_alive: z.union([z.string(), z.number()]).optional(),\n logprobs: z.boolean().optional(),\n top_logprobs: z.number().optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { ModelOptionsSchema } from './ModelOptions.schema.js';\nimport { ThinkValueSchema } from './ThinkValue.schema.js';\n\nexport const GenerateRequestSchema = z.object({\n model: z.string(),\n prompt: z.string().optional(),\n suffix: z.string().optional(),\n images: z.array(z.string()).optional(),\n format: z.union([z.string(), z.object({})]).optional(),\n system: z.string().optional(),\n stream: z.boolean().optional(),\n think: ThinkValueSchema.optional(),\n raw: z.boolean().optional(),\n keep_alive: z.union([z.string(), z.number()]).optional(),\n options: ModelOptionsSchema.optional(),\n logprobs: z.boolean().optional(),\n top_logprobs: z.number().optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { ModelOptionsSchema } from './ModelOptions.schema.js';\n\nexport const EmbedRequestSchema = z.object({\n model: z.string(),\n input: z.union([z.string(), z.array(z.string())]),\n truncate: z.boolean().optional(),\n dimensions: z.number().optional(),\n keep_alive: z.string().optional(),\n options: ModelOptionsSchema.optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { ChatMessageSchema } from './ChatMessage.schema.js';\n\nexport const CreateRequestSchema = z.object({\n model: z.string(),\n from: z.string().optional(),\n template: z.string().optional(),\n renderer: z.string().optional(),\n parser: z.string().optional(),\n files: z.object({}).catchall(z.string()).optional(),\n draft_files: z.object({}).catchall(z.string()).optional(),\n license: z.union([z.string(), z.array(z.string())]).optional(),\n system: z.string().optional(),\n parameters: z.object({}).optional(),\n messages: z.array(ChatMessageSchema).optional(),\n quantize: z.string().optional(),\n draft_quantize: z.string().optional(),\n requires: z.string().optional(),\n stream: z.boolean().optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const CopyRequestSchema = z.object({\n source: z.string(),\n destination: z.string(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const DeleteRequestSchema = z.object({\n model: z.string(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const PullRequestSchema = z.object({\n model: z.string(),\n insecure: z.boolean().optional(),\n stream: z.boolean().optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const PushRequestSchema = z.object({\n model: z.string(),\n insecure: z.boolean().optional(),\n stream: z.boolean().optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const ShowRequestSchema = z.object({\n model: z.string(),\n verbose: z.boolean().optional(),\n});\n","/**\n * Schema registry — maps operationId → request/response Zod schemas.\n *\n * The runtime consults this registry to validate request bodies before\n * sending and response payloads after receiving. This is the runtime\n * enforcement layer described in ADR 0019 (Zod schema generation) and\n * ADR 0020 (runtime validation wiring).\n *\n * The registry is hand-written (not generated) because:\n * 1. Not every operation has a request schema (GET/HEAD have no body).\n * 2. Not every operation has a response schema (DELETE returns 204).\n * 3. The map is small (21 operations) and changes only when overlays\n * add new operations — at which point the generator should remind\n * the maintainer to update this file via the contract validator.\n *\n * When `validateRequests: true` is set on `OllamaRuntime` and an\n * operation has no registered request schema, the runtime skips\n * validation (it doesn't fail — the contract just doesn't have a\n * schema for that operation yet).\n */\nimport type { z } from 'zod';\nimport { ChatRequestSchema } from '../models/ChatRequest.schema.js';\nimport { GenerateRequestSchema } from '../models/GenerateRequest.schema.js';\nimport { EmbedRequestSchema } from '../models/EmbedRequest.schema.js';\nimport { CreateRequestSchema } from '../models/CreateRequest.schema.js';\nimport { CopyRequestSchema } from '../models/CopyRequest.schema.js';\nimport { DeleteRequestSchema } from '../models/DeleteRequest.schema.js';\nimport { PullRequestSchema } from '../models/PullRequest.schema.js';\nimport { PushRequestSchema } from '../models/PushRequest.schema.js';\nimport { ShowRequestSchema } from '../models/ShowRequest.schema.js';\n\n/**\n * Map from operationId → request schema. Response schemas are intentionally\n * NOT registered here — see ADR 0020 for the rationale (response validation\n * would break on legitimate forward-compat extensions to the wire format).\n */\nexport const requestSchemas: Readonly<Record<string, z.ZodType>> = {\n chat: ChatRequestSchema,\n generate: GenerateRequestSchema,\n embed: EmbedRequestSchema,\n create: CreateRequestSchema,\n copy: CopyRequestSchema,\n delete: DeleteRequestSchema,\n pull: PullRequestSchema,\n push: PushRequestSchema,\n show: ShowRequestSchema,\n // Operations without a registered request schema (blobs, ps, tags,\n // version, systemOne, openai*, anthropic*) skip validation. This is\n // deliberate — the OpenAPI spec doesn't define request bodies for\n // GET/HEAD operations, and the compat-surface request schemas (OpenAI,\n // Anthropic) are richer than what the IR currently models.\n};\n\n/** Look up a request schema by operationId. Returns `undefined` if no schema exists. */\nexport function getRequestSchema(operationId: string): z.ZodType | undefined {\n return requestSchemas[operationId];\n}\n","/**\n * OllamaRuntime — the runtime seam generated API classes delegate to.\n *\n * This is the only hand-written file in `src/generated/runtime/`. Every\n * generated method in `src/generated/api/*-api.ts` ends with:\n *\n * ```ts\n * return this.runtime.invoke({ operation: chatOp, body: request });\n * ```\n *\n * The runtime is responsible for:\n * - Method/path resolution (from {@link OperationDefinition})\n * - Streaming default application (when the request doesn't set `stream`)\n * - Environment guard (rejecting cloud calls for local-only operations)\n * - Version constraint guard (failing fast when the server is too old)\n * - Delegating to the existing {@link HttpClient} for transport, retry,\n * telemetry, NDJSON/SSE parsing\n *\n * It is intentionally a thin adapter — the existing transport, streaming,\n * middleware, and error-mapping layers are preserved verbatim. This file\n * only adds the contract-aware glue between generated API classes and the\n * existing HttpClient.\n */\nimport { HttpClient, type HttpRequestOptions } from '../../transport/http.js';\nimport { parseNdjsonStream } from '../../streaming/ndjson.js';\nimport { OllamaGenericClientError, OllamaRequestValidationError } from '../../errors.js';\nimport type { OperationDefinition, InvokeRequest } from './operation-definition.js';\nimport { getRequestSchema } from './schema-registry.js';\n\n/** Constructor options for {@link OllamaRuntime}. */\nexport interface OllamaRuntimeOptions {\n readonly http: HttpClient;\n /**\n * Whether this runtime is targeting a local Ollama instance. Defaults to\n * `true`. When `false`, operations marked `environment.cloud === false`\n * (i.e. local-only like `/v1/systemone`) are rejected at request time.\n */\n readonly localMode?: boolean;\n /**\n * Server version, if known (typically from a prior `/api/version` call).\n * When set, operations with `constraints.minOllamaVersion` are checked\n * against this value at request time.\n */\n readonly serverVersion?: string;\n /**\n * When `true`, the runtime validates every request body against the\n * generated Zod schema before sending it. Defaults to `false` — opt-in.\n *\n * Validation behavior:\n * - If the operation has a registered request schema (see\n * {@link schema-registry.ts}), the body is parsed via `safeParse`.\n * - On parse failure, throws `OllamaRequestValidationError` with the\n * Zod issues attached. No HTTP request is made.\n * - On parse success, the parsed (and stripped of unknown fields) body\n * is sent — this means callers can't accidentally send extra fields\n * that the contract doesn't allow.\n * - If the operation has NO registered schema (e.g. GET endpoints,\n * `/v1/systemone`, OpenAI/Anthropic compat surfaces), validation is\n * skipped silently.\n *\n * Response validation is intentionally NOT enabled — see ADR 0020 for\n * the rationale (forward-compat with wire-format extensions).\n */\n readonly validateRequests?: boolean;\n}\n\nfunction compareVersions(a: string, b: string): number {\n const pa = a.split('.').map((s) => Number.parseInt(s, 10) ?? 0);\n const pb = b.split('.').map((s) => Number.parseInt(s, 10) ?? 0);\n for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) {\n const va = pa[i] ?? 0;\n const vb = pb[i] ?? 0;\n if (va !== vb) return va - vb;\n }\n return 0;\n}\n\n/**\n * Apply environment + version guards before delegating to HttpClient.\n *\n * Throws {@link OllamaGenericClientError} when:\n * - The operation is local-only and the runtime is in cloud mode.\n * - The operation has `constraints.minOllamaVersion` and the server is older.\n */\nfunction assertOperationAllowed(\n operation: OperationDefinition,\n options: OllamaRuntimeOptions,\n): void {\n const localMode = options.localMode ?? true;\n if (!localMode && !operation.environment.cloud) {\n throw new OllamaGenericClientError(\n `Operation ${operation.operationId} (${operation.method} ${operation.path}) ` +\n `is local-only and not supported in cloud mode.`,\n );\n }\n if (\n operation.constraints?.minOllamaVersion &&\n options.serverVersion &&\n compareVersions(options.serverVersion, operation.constraints.minOllamaVersion) < 0\n ) {\n throw new OllamaGenericClientError(\n `Operation ${operation.operationId} (${operation.method} ${operation.path}) ` +\n `requires Ollama >= ${operation.constraints.minOllamaVersion} ` +\n `(server reports ${options.serverVersion}).`,\n );\n }\n}\n\n/**\n * Decide whether the request should stream. If the request body explicitly\n * sets `stream`, that wins. Otherwise the operation's `streamingDefault`\n * from the contract is used.\n */\nfunction shouldStream(req: InvokeRequest): boolean {\n if (req.body && typeof req.body === 'object' && 'stream' in req.body) {\n const explicit = (req.body as { stream?: unknown }).stream;\n if (typeof explicit === 'boolean') return explicit;\n }\n return Boolean(req.streamingDefault ?? req.operation.transport.streamingDefault);\n}\n\n/**\n * Apply the streaming default to the request body if needed.\n *\n * If the operation streams by default and the body doesn't set `stream`,\n * add `stream: true`. The user can always override by setting `stream`\n * explicitly on the request.\n */\nfunction buildBody(req: InvokeRequest): unknown {\n if (req.body === undefined) return undefined;\n if (typeof req.body !== 'object' || req.body === null) return req.body;\n const body = req.body as Record<string, unknown>;\n if (\n req.operation.transport.streaming &&\n req.operation.transport.streamingDefault &&\n body.stream === undefined\n ) {\n return { ...body, stream: true };\n }\n return body;\n}\n\n/** The runtime seam. */\nexport class OllamaRuntime {\n constructor(private readonly options: OllamaRuntimeOptions) {}\n\n /**\n * Invoke an operation. Called by every generated API method.\n *\n * Returns a `Promise<T>` for non-streaming operations, or an\n * `AsyncGenerator<T>` for streaming operations. The generated API\n * class's overloads pick the right return type at compile time.\n */\n async invoke<T = unknown>(req: InvokeRequest): Promise<T> {\n assertOperationAllowed(req.operation, this.options);\n let body = buildBody(req);\n\n // Wave 10 (ADR 0020): runtime Zod validation. Opt-in via\n // `validateRequests: true` on the runtime constructor. Throws\n // `OllamaRequestValidationError` BEFORE any HTTP request is made\n // when the body fails validation. The validated (and stripped)\n // body replaces the original so unknown fields can't leak through.\n if (this.options.validateRequests === true && body !== undefined) {\n const schema = getRequestSchema(req.operation.operationId);\n if (schema) {\n const result = schema.safeParse(body);\n if (!result.success) {\n throw new OllamaRequestValidationError(\n `Request validation failed for operation \"${req.operation.operationId}\" ` +\n `(${req.operation.method} ${req.operation.path}): ` +\n result.error.issues\n .map((i) => `${i.path.join('.') || '<root>'}: ${i.message}`)\n .join('; '),\n {\n operationId: req.operation.operationId,\n issues: result.error.issues,\n request: { method: req.operation.method, url: req.operation.path },\n },\n );\n }\n body = result.data;\n }\n }\n\n const streaming = shouldStream(req);\n\n // The HttpClient expects the narrow method union 'GET' | 'POST' |\n // 'DELETE' | 'HEAD' | undefined — cast through `as` because our\n // OperationDefinition.method is the wider HttpMethod type.\n const httpReq: HttpRequestOptions = {\n path: req.operation.path,\n method: req.operation.method as 'GET' | 'POST' | 'DELETE' | 'HEAD',\n ...(body !== undefined ? { body } : {}),\n ...(req.signal !== undefined ? { signal: req.signal } : {}),\n // For streaming calls, request the raw Response so we can pipe it\n // through parseNdjsonStream directly. This inherits middleware,\n // retry, telemetry, and error-mapping from HttpClient — the\n // previous Wave 3 implementation bypassed them with a direct\n // `fetch()` call.\n ...(streaming ? { raw: true } : {}),\n };\n\n if (!streaming) {\n return (await this.options.http.request<T>(httpReq)) as T;\n }\n\n // Streaming: HttpClient returns the raw Response (via the `raw: true`\n // option) so we can read its body as an NDJSON stream.\n const response = await this.options.http.request<Response>(httpReq);\n if (!response.body) {\n throw new OllamaGenericClientError(\n `Operation ${req.operation.operationId}: streaming response had no body.`,\n );\n }\n return parseNdjsonStream<T>(response.body) as unknown as T;\n }\n}\n","/**\n * Main OllamaClient class with failover, streaming, structured outputs, and ecosystem integrations.\n */\n\nimport { z } from 'zod';\nimport {\n DEFAULT_BASE_URL,\n DEFAULT_FAILOVER_CODES,\n DEFAULT_TIMEOUT_MS,\n OLLAMA_CLOUD_BASE_URL,\n resolveApiKey,\n resolveBaseUrl,\n resolveCredentialEndpoints,\n type OllamaClientConfig,\n} from './config.js';\nimport {\n OllamaClientError,\n OllamaModelRoutingError,\n OllamaUnsupportedCapabilityError,\n} from './errors.js';\nimport { createConsoleLogger, NOOP_LOGGER, type Logger } from './logger.js';\nimport { EndpointRegistry, type EndpointHealth } from './providers/endpoint-registry.js';\nimport { checkEndpointHealth, type EndpointHealthCheckResult } from './providers/health-check.js';\nimport {\n detectModelCapabilities,\n inferRuntimeMode,\n type ModelCapabilities,\n type RuntimeMode,\n} from './capabilities/capabilities.js';\nimport { parseStructuredOutput, zodToJsonSchema } from './schema/zod.js';\nimport { normalizeChatStream, normalizeGenerateStream } from './streaming/normalize.js';\nimport { OllamaStream } from './streaming/stream.js';\nimport type { ChatStreamResult, GenerateStreamResult } from './streaming/types.js';\nimport { HttpClient, type BinaryBody, type FetchLike } from './transport/http.js';\nimport { DEFAULT_RETRY_CONFIG, withRetry, type RetryConfig } from './transport/retry.js';\nimport { createTimeoutSignal } from './transport/timeout.js';\nimport { ModelsClient } from './models-client.js';\nimport { OpenAICompatClient } from './integrations/openai.js';\nimport { AnthropicCompatClient } from './integrations/anthropic.js';\nimport { OllamaRuntime } from './generated/runtime/runtime.js';\nimport { ensureToolCallIds } from './tools/tool-call-id.js';\nimport { withEncodedImages, withEncodedMessageImages } from './utils.js';\nimport {\n withSpan,\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_GEN_AI_RESPONSE_MODEL,\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n ATTR_OLLAMA_ENDPOINT_NAME,\n ATTR_OLLAMA_ENDPOINT_ATTEMPT,\n GEN_AI_SYSTEM_OLLAMA,\n} from './telemetry/index.js';\nimport type {\n ChatRequestOptions,\n ChatResponse,\n CopyRequestOptions,\n CreateRequestOptions,\n DeleteRequestOptions,\n EmbedRequestOptions,\n EmbedResponse,\n EmbeddingsRequestOptions,\n EmbeddingsResponse,\n GenerateRequestOptions,\n GenerateResponse,\n PullRequestOptions,\n PushRequestOptions,\n RequestCancellationOptions,\n ShowRequestOptions,\n WebFetchRequestOptions,\n WebFetchResponse,\n WebSearchRequestOptions,\n WebSearchResponse,\n} from './types.js';\n\nlet logicalRequestSequence = 0;\n\nfunction createLogicalRequestId(): string {\n logicalRequestSequence += 1;\n return `ollama-request-${logicalRequestSequence}`;\n}\n\n/**\n * High-level Ollama client — the original, hand-written API surface.\n *\n * **Wave 8 (ADR 0018) deprecation notice:**\n *\n * For new code, prefer the generated `NativeApi` from\n * {@link ./generated/runtime/runtime.js} + {@link ./generated/api/native-api.js}\n * instead. The generated surface:\n *\n * - Inherits every contract-layer guarantee (environment guards, version\n * guards, streaming defaults) automatically from the canonical IR.\n * - Stays in sync with the OpenAPI spec by construction — no hand-written\n * surface to drift.\n * - Uses the same `HttpClient` (and therefore the same middleware,\n * retry, telemetry, and streaming pipeline) as this client.\n *\n * The migration path is non-breaking:\n *\n * ```ts\n * // Before (still works, no breaking changes):\n * const client = new OllamaClient({ baseUrl: 'http://localhost:11434' });\n * const res = await client.chat({ model, messages });\n *\n * // After (recommended for new code):\n * const http = new HttpClient({ baseUrl: 'http://localhost:11434' });\n * const runtime = new OllamaRuntime({ http });\n * const api = new NativeApi(runtime);\n * const res = await api.chat({ model, messages, stream: false });\n * ```\n *\n * `OllamaClient` is preserved verbatim — existing callers do not need to\n * change anything. New methods and operations will land on the generated\n * surface first; `OllamaClient` will receive them only as a follow-up.\n */\nexport class OllamaClient {\n readonly registry: EndpointRegistry;\n readonly models: ModelsClient;\n private readonly retryConfig: RetryConfig;\n private readonly timeoutMs: number;\n private readonly failoverCodes: Set<string>;\n private readonly fetchImpl: FetchLike;\n private readonly logger: Logger;\n private readonly middleware: OllamaClientConfig['middleware'];\n private readonly onLifecycleEvent: OllamaClientConfig['onLifecycleEvent'];\n /**\n * API key for Ollama's hosted web tools (`webSearch`/`webFetch`), which always target\n * `OLLAMA_CLOUD_BASE_URL` regardless of `config.endpoints` — an Ollama account API key\n * is inherently a single global credential, not tied to any one inference endpoint.\n * Resolved the same way as a single-endpoint `apiKey` (`config.apiKey` falling back to\n * `OLLAMA_API_KEY`), independent of whether `config.endpoints` was used instead.\n */\n private readonly cloudApiKey: string | undefined;\n\n constructor(config: OllamaClientConfig = {}) {\n const resolvedApiKey = resolveApiKey(config.apiKey);\n this.cloudApiKey = resolvedApiKey;\n const credentialEndpoints = resolveCredentialEndpoints(config);\n const endpoints =\n config.endpoints ??\n (credentialEndpoints.length > 0\n ? []\n : [\n {\n name: 'default',\n baseUrl: resolveBaseUrl(config.baseUrl),\n ...(resolvedApiKey !== undefined ? { apiKey: resolvedApiKey } : {}),\n ...(config.headers !== undefined ? { headers: config.headers } : {}),\n },\n ]);\n this.registry = new EndpointRegistry(\n [...endpoints, ...credentialEndpoints],\n config.endpointHealth,\n );\n this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.failoverCodes = new Set(config.failoverOn ?? DEFAULT_FAILOVER_CODES);\n this.fetchImpl = config.fetch ?? globalThis.fetch;\n this.logger = config.logger ?? (config.debug ? createConsoleLogger() : NOOP_LOGGER);\n this.middleware = config.middleware;\n this.onLifecycleEvent = config.onLifecycleEvent;\n this.retryConfig =\n typeof config.retries === 'number'\n ? { ...DEFAULT_RETRY_CONFIG, maxRetries: config.retries }\n : { ...DEFAULT_RETRY_CONFIG, ...config.retries };\n this.models = new ModelsClient((op, opts) => this.executeWithFailover(op, opts));\n }\n\n get modelsClient(): ModelsClient {\n return this.models;\n }\n\n /**\n * Return a generated {@link OllamaRuntime} that shares this client's\n * transport (HttpClient + middleware + retry + telemetry).\n *\n * Wave 8 (ADR 0018) bridge: lets callers mix the existing `OllamaClient`\n * API with the generated `NativeApi` / `OpenAIApi` / `AnthropicApi`\n * surface without configuring two separate HttpClient instances.\n *\n * The returned runtime is bound to the registry's first candidate\n * endpoint (or the resolved single-endpoint config if no `endpoints`\n * array was provided). For multi-endpoint configs that need per-call\n * routing, prefer constructing `OllamaRuntime` directly with a\n * specific HttpClient:\n *\n * ```ts\n * const http = new HttpClient({ baseUrl: 'http://host-a:11434' });\n * const runtime = new OllamaRuntime({ http });\n * const api = new NativeApi(runtime);\n * ```\n *\n * The runtime is cached on first call — subsequent calls return the\n * same instance.\n */\n get runtime(): OllamaRuntime {\n if (this._runtime === undefined) {\n // Pick the first candidate endpoint to bind the runtime to. The\n // generated surface doesn't currently support multi-endpoint\n // failover; callers needing that should keep using OllamaClient\n // (or construct OllamaRuntime per-call with the desired endpoint).\n const candidates = this.registry.candidates();\n const endpoint = candidates[0];\n const baseUrl = endpoint?.baseUrl ?? 'http://localhost:11434';\n const http = new HttpClient({\n baseUrl,\n ...(endpoint?.apiKey !== undefined ? { apiKey: endpoint.apiKey } : {}),\n ...(endpoint?.headers !== undefined ? { headers: endpoint.headers } : {}),\n fetch: this.fetchImpl,\n ...(this.middleware !== undefined ? { middleware: this.middleware } : {}),\n ...(this.onLifecycleEvent !== undefined ? { onLifecycleEvent: this.onLifecycleEvent } : {}),\n });\n this._runtime = new OllamaRuntime({\n http,\n localMode: inferRuntimeMode(baseUrl) === 'local',\n });\n }\n return this._runtime;\n }\n private _runtime: OllamaRuntime | undefined;\n\n /**\n * Fail-fast guard for `format` (structured output) requests: throws before any network\n * call if the candidate endpoint is inferred as Ollama Cloud, which does not currently\n * support structured outputs (see `ModelCapabilities.supportsStructuredOutputRequest`).\n * `unsupported_capability` is in `DEFAULT_FAILOVER_CODES`, so in a multi-endpoint setup\n * this causes failover to the next candidate rather than failing the whole request.\n */\n private assertStructuredOutputSupported(baseUrl: string, model: string): void {\n if (inferRuntimeMode(baseUrl) === 'cloud') {\n throw new OllamaUnsupportedCapabilityError(\n `Structured output (\"format\") requests are not supported against Ollama Cloud ` +\n `endpoints (model \"${model}\" via ${baseUrl}). This is a known Ollama Cloud ` +\n `limitation, not a bug in this SDK.`,\n { capability: 'structuredOutputRequest' },\n );\n }\n }\n\n async executeWithFailover<T>(\n operation: (http: HttpClient, signal: AbortSignal) => Promise<T>,\n options?: {\n signal?: AbortSignal | undefined;\n timeoutMs?: number | undefined;\n /**\n * Disables cross-endpoint failover: only the single best candidate endpoint is\n * tried (same-endpoint retry via `withRetry` still applies). For operations whose\n * target IS the endpoint — model catalog/blob management — a different endpoint\n * isn't an interchangeable substitute, so failing over to one would silently\n * operate on the wrong server's state rather than retrying \"the same\" request. See\n * ADR 0008. Defaults to `false`, preserving normal failover for inference calls.\n */\n singleEndpoint?: boolean | undefined;\n /**\n * The model this request targets, used to filter candidates by\n * `OllamaEndpoint.models` (credential-scoped routing — see that field's docs).\n * Requests without a `model` (e.g. `listModels`) consider every configured\n * endpoint, same as before this option existed.\n */\n model?: string | undefined;\n /**\n * For an operation whose real completion outlasts its own returned promise — a\n * streaming response, specifically — defers releasing the endpoint's concurrency\n * slot (see `EndpointRegistryOptions.maxConcurrentPerEndpoint`/`'least-connections'`)\n * until the promise this returns settles, instead of releasing as soon as\n * `operation` resolves. Pass `(stream) => stream.finalResult` for `chatStream`/\n * `generateStream` so the slot stays held for as long as the underlying HTTP\n * connection realistically does — until the stream is fully consumed, errors, or is\n * aborted. Omit for anything whose returned promise already represents the whole\n * request/response (the default, and correct for every non-streaming call).\n */\n holdUntil?: ((result: T) => Promise<unknown>) | undefined;\n },\n ): Promise<T> {\n const timeout = createTimeoutSignal(options?.timeoutMs ?? this.timeoutMs, options?.signal);\n const requestId = createLogicalRequestId();\n let deferTimeoutCancel = false;\n try {\n let lastError: Error | undefined;\n\n for (;;) {\n const allCandidates = this.registry.candidates(options?.model);\n if (\n allCandidates.length === 0 &&\n options?.model !== undefined &&\n this.registry.hasModelScopedEndpoints()\n ) {\n const configured = this.registry\n .list()\n .flatMap((ep) => ep.models ?? [])\n .filter((m, i, arr) => arr.indexOf(m) === i);\n throw new OllamaModelRoutingError(\n `No configured endpoint is authorized for model \"${options.model}\". ` +\n (configured.length > 0\n ? `Endpoints are scoped to: ${configured.join(', ')}.`\n : 'No endpoint declares a `models` allow-list that includes it.') +\n ' Add or widen an `OllamaEndpoint.models` entry to route this model.',\n { model: options.model, availableModels: configured },\n );\n }\n const candidates = options?.singleEndpoint ? allCandidates.slice(0, 1) : allCandidates;\n\n const runnable = this.registry.filterWithCapacity(candidates);\n if (runnable.length === 0 && candidates.length > 0) {\n await this.registry.waitForCapacity(\n candidates.map((c) => c.name),\n timeout.signal,\n );\n continue;\n }\n\n for (const [attemptIndex, endpoint] of runnable.entries()) {\n this.logger.debug(`Executing on endpoint \"${endpoint.name}\" (${endpoint.baseUrl})`);\n const http = new HttpClient({\n baseUrl: endpoint.baseUrl,\n ...(endpoint.apiKey !== undefined ? { apiKey: endpoint.apiKey } : {}),\n ...(endpoint.headers !== undefined ? { headers: endpoint.headers } : {}),\n fetch: this.fetchImpl,\n middleware: this.middleware,\n onLifecycleEvent: this.onLifecycleEvent,\n requestId,\n });\n\n // Acquired synchronously, right after this endpoint was chosen from\n // `candidates()`/`filterWithCapacity()` with no `await` in between — see\n // `EndpointRegistryOptions.strategy`'s `'least-connections'` doc for why that\n // ordering is what makes it race-free.\n this.registry.acquire(endpoint.name);\n let holdPromise: Promise<unknown> | undefined;\n try {\n const result = await withSpan(\n 'ollama.endpoint.attempt',\n {\n [ATTR_OLLAMA_ENDPOINT_NAME]: endpoint.name,\n [ATTR_OLLAMA_ENDPOINT_ATTEMPT]: attemptIndex,\n },\n () =>\n withRetry(\n () => operation(http, timeout.signal),\n {\n ...this.retryConfig,\n onRetry: (error, attempt, delayMs) => {\n this.retryConfig.onRetry?.(error, attempt, delayMs);\n this.onLifecycleEvent?.({\n type: 'retry',\n requestId,\n attempt: attempt + 1,\n error,\n delayMs,\n timestamp: Date.now(),\n });\n },\n },\n timeout.signal,\n ),\n );\n this.registry.reportSuccess(endpoint.name);\n if (options?.holdUntil) {\n holdPromise = options.holdUntil(result);\n deferTimeoutCancel = true;\n }\n return result;\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n lastError = error;\n this.registry.reportFailure(endpoint.name);\n this.logger.warn(`Failed on \"${endpoint.name}\": ${error.message}`);\n if (!(error instanceof OllamaClientError && this.failoverCodes.has(error.code)))\n throw error;\n } finally {\n if (holdPromise) {\n void holdPromise\n .catch(() => undefined)\n .finally(() => {\n timeout.cancel();\n this.registry.release(endpoint.name);\n });\n } else {\n this.registry.release(endpoint.name);\n }\n }\n }\n throw lastError ?? new Error('No healthy Ollama endpoints available');\n }\n } finally {\n if (!deferTimeoutCancel) timeout.cancel();\n }\n }\n\n // --- Chat ---\n chat(\n req: ChatRequestOptions & { stream: true },\n ): Promise<OllamaStream<ChatResponse, ChatStreamResult>>;\n chat(req: ChatRequestOptions & { stream?: false | undefined }): Promise<ChatResponse>;\n chat(\n req: ChatRequestOptions,\n ): Promise<ChatResponse | OllamaStream<ChatResponse, ChatStreamResult>>;\n async chat(\n req: ChatRequestOptions,\n ): Promise<ChatResponse | OllamaStream<ChatResponse, ChatStreamResult>> {\n const encodedMessages = await withEncodedMessageImages(req.messages);\n const messages = encodedMessages.map((message) => {\n if (message.role === 'tool' && message.tool_call_id !== undefined) {\n const { tool_call_id: _toolCallId, ...nativeMessage } = message;\n return nativeMessage;\n }\n return message;\n });\n if (req.stream) {\n return this.executeWithFailover(\n async (http, signal) => {\n if (req.format !== undefined)\n this.assertStructuredOutputSupported(http.baseUrl, req.model);\n const stream = await http.requestStream<ChatResponse>({\n path: '/api/chat',\n body: { ...req, messages, stream: true },\n signal,\n });\n return normalizeChatStream(stream, signal);\n },\n {\n signal: req.signal,\n timeoutMs: req.timeoutMs,\n model: req.model,\n // The endpoint's concurrency slot must stay held for as long as the stream is\n // actually being consumed, not just until the initial response/headers arrive\n // — see `executeWithFailover`'s `holdUntil` doc.\n holdUntil: (stream) => stream.finalResult,\n },\n );\n }\n return withSpan(\n `chat ${req.model}`,\n {\n [ATTR_GEN_AI_SYSTEM]: GEN_AI_SYSTEM_OLLAMA,\n [ATTR_GEN_AI_OPERATION_NAME]: 'chat',\n [ATTR_GEN_AI_REQUEST_MODEL]: req.model,\n },\n async (span) => {\n const rawRes = await this.executeWithFailover((http, signal) => {\n if (req.format !== undefined)\n this.assertStructuredOutputSupported(http.baseUrl, req.model);\n return http.request<ChatResponse>({\n path: '/api/chat',\n body: { ...req, messages, stream: false },\n signal,\n });\n }, req);\n const toolCalls = ensureToolCallIds(rawRes.message.tool_calls);\n const res: ChatResponse =\n toolCalls === rawRes.message.tool_calls\n ? rawRes\n : { ...rawRes, message: { ...rawRes.message, tool_calls: toolCalls } };\n span?.setAttributes({\n [ATTR_GEN_AI_RESPONSE_MODEL]: res.model,\n ...(res.prompt_eval_count !== undefined\n ? { [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: res.prompt_eval_count }\n : {}),\n ...(res.eval_count !== undefined\n ? { [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: res.eval_count }\n : {}),\n });\n return res;\n },\n );\n }\n\n chatStream(\n req: Omit<ChatRequestOptions, 'stream'>,\n ): Promise<OllamaStream<ChatResponse, ChatStreamResult>> {\n return this.chat({ ...req, stream: true });\n }\n\n async chatText(req: Omit<ChatRequestOptions, 'stream'>): Promise<string> {\n const res = await this.chat({ ...req, stream: false });\n return res.message.content;\n }\n\n async chatWithSchema<T>(\n req: Omit<ChatRequestOptions, 'stream' | 'format'>,\n schema: z.ZodType<T>,\n ): Promise<T> {\n const res = await this.chat({ ...req, format: zodToJsonSchema(schema), stream: false });\n return parseStructuredOutput(res.message.content, schema);\n }\n\n // --- Generate ---\n generate(\n req: GenerateRequestOptions & { stream: true },\n ): Promise<OllamaStream<GenerateResponse, GenerateStreamResult>>;\n generate(req: GenerateRequestOptions & { stream?: false | undefined }): Promise<GenerateResponse>;\n generate(\n req: GenerateRequestOptions,\n ): Promise<GenerateResponse | OllamaStream<GenerateResponse, GenerateStreamResult>>;\n async generate(\n req: GenerateRequestOptions,\n ): Promise<GenerateResponse | OllamaStream<GenerateResponse, GenerateStreamResult>> {\n const encodedReq = await withEncodedImages(req);\n if (encodedReq.stream) {\n return this.executeWithFailover(\n async (http, signal) => {\n if (encodedReq.format !== undefined)\n this.assertStructuredOutputSupported(http.baseUrl, encodedReq.model);\n const stream = await http.requestStream<GenerateResponse>({\n path: '/api/generate',\n body: { ...encodedReq, stream: true },\n signal,\n });\n return normalizeGenerateStream(stream, signal);\n },\n {\n signal: encodedReq.signal,\n timeoutMs: encodedReq.timeoutMs,\n model: encodedReq.model,\n holdUntil: (stream) => stream.finalResult,\n },\n );\n }\n return withSpan(\n `text_completion ${encodedReq.model}`,\n {\n [ATTR_GEN_AI_SYSTEM]: GEN_AI_SYSTEM_OLLAMA,\n [ATTR_GEN_AI_OPERATION_NAME]: 'text_completion',\n [ATTR_GEN_AI_REQUEST_MODEL]: encodedReq.model,\n },\n async (span) => {\n const res = await this.executeWithFailover((http, signal) => {\n if (encodedReq.format !== undefined)\n this.assertStructuredOutputSupported(http.baseUrl, encodedReq.model);\n return http.request<GenerateResponse>({\n path: '/api/generate',\n body: { ...encodedReq, stream: false },\n signal,\n });\n }, encodedReq);\n span?.setAttributes({\n [ATTR_GEN_AI_RESPONSE_MODEL]: res.model,\n ...(res.prompt_eval_count !== undefined\n ? { [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: res.prompt_eval_count }\n : {}),\n ...(res.eval_count !== undefined\n ? { [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: res.eval_count }\n : {}),\n });\n return res;\n },\n );\n }\n\n generateStream(\n req: Omit<GenerateRequestOptions, 'stream'>,\n ): Promise<OllamaStream<GenerateResponse, GenerateStreamResult>> {\n return this.generate({ ...req, stream: true });\n }\n\n async generateText(req: Omit<GenerateRequestOptions, 'stream'>): Promise<string> {\n const res = await this.generate({ ...req, stream: false });\n return res.response;\n }\n\n async generateWithSchema<T>(\n req: Omit<GenerateRequestOptions, 'stream' | 'format'>,\n schema: z.ZodType<T>,\n ): Promise<T> {\n const res = await this.generate({ ...req, format: zodToJsonSchema(schema), stream: false });\n return parseStructuredOutput(res.response, schema);\n }\n\n // --- Embeddings ---\n embed(req: EmbedRequestOptions): Promise<EmbedResponse> {\n return this.executeWithFailover(\n (http, signal) => http.request<EmbedResponse>({ path: '/api/embed', body: req, signal }),\n req,\n );\n }\n\n async embedText(\n model: string,\n input: string | readonly string[],\n ): Promise<readonly (readonly number[])[]> {\n const res = await this.embed({ model, input });\n return res.embeddings;\n }\n\n /**\n * @deprecated Ollama's `/api/embeddings` endpoint has been superseded by `/api/embed`\n * (exposed here as {@link OllamaClient.embed}), which additionally supports batch\n * input. Kept for compatibility with existing callers; new code should use `embed`.\n */\n embeddings(req: EmbeddingsRequestOptions): Promise<EmbeddingsResponse> {\n return this.executeWithFailover(\n (http, signal) =>\n http.request<EmbeddingsResponse>({ path: '/api/embeddings', body: req, signal }),\n req,\n );\n }\n\n // --- Model Operations (Delegated to ModelsClient) ---\n readonly listModels = () => this.models.list();\n readonly showModel = (req: ShowRequestOptions) => this.models.show(req);\n readonly pullModel = (r: PullRequestOptions) => this.models.pull(r);\n readonly pushModel = (r: PushRequestOptions) => this.models.push(r);\n readonly createModel = (r: CreateRequestOptions) => this.models.create(r);\n readonly deleteModel = (req: DeleteRequestOptions) => this.models.delete(req);\n readonly copyModel = (req: CopyRequestOptions) => this.models.copy(req);\n readonly ps = () => this.models.ps();\n readonly version = () => this.models.version();\n readonly createBlob = (digest: string, data: BinaryBody) => this.models.createBlob(digest, data);\n readonly checkBlob = (digest: string) => this.models.checkBlob(digest);\n\n // --- Web Endpoints ---\n /**\n * Ollama's hosted web search tool (`POST https://ollama.com/api/web_search`) — a fixed\n * Ollama Cloud service, unrelated to `config.endpoints`/`baseUrl` and not proxied\n * through a local server. Requires an Ollama account API key: pass `apiKey` to the\n * client constructor or set `OLLAMA_API_KEY`. Applies the same default `timeoutMs` and\n * retry policy as inference calls, but never cross-endpoint-fails-over — there is only\n * ever the one cloud endpoint to call.\n */\n async webSearch(req: WebSearchRequestOptions): Promise<WebSearchResponse> {\n const { count, max_results, ...rest } = req;\n const res = await this.executeCloudRequest(\n (http, signal) =>\n http.request<WebSearchResponse>({\n path: '/api/web_search',\n body: { ...rest, max_results: max_results ?? count },\n signal,\n }),\n req,\n );\n // `snippet` is a deprecated mirror of `content`, kept for backward compatibility —\n // see the `@deprecated` note on `WebSearchResult.snippet`.\n return { results: res.results.map((r) => ({ ...r, snippet: r.content })) };\n }\n /**\n * Ollama's hosted web fetch tool (`POST https://ollama.com/api/web_fetch`) — see\n * {@link OllamaClient.webSearch} for the cloud-endpoint/auth/timeout/retry behavior,\n * which applies identically here.\n */\n webFetch(req: WebFetchRequestOptions): Promise<WebFetchResponse> {\n return this.executeCloudRequest(\n (http, signal) =>\n http.request<WebFetchResponse>({ path: '/api/web_fetch', body: req, signal }),\n req,\n );\n }\n /**\n * Runs `operation` against the fixed Ollama Cloud host with this client's default\n * timeout and retry policy — the same primitives `executeWithFailover` uses, minus the\n * multi-candidate loop, since `webSearch`/`webFetch` only ever have the one endpoint.\n */\n private async executeCloudRequest<T>(\n operation: (http: HttpClient, signal: AbortSignal) => Promise<T>,\n options: RequestCancellationOptions,\n ): Promise<T> {\n const timeout = createTimeoutSignal(options.timeoutMs ?? this.timeoutMs, options.signal);\n using _timeout = {\n [Symbol.dispose]() {\n timeout.cancel();\n },\n };\n const requestId = createLogicalRequestId();\n const http = new HttpClient({\n baseUrl: OLLAMA_CLOUD_BASE_URL,\n apiKey: this.cloudApiKey,\n fetch: this.fetchImpl,\n middleware: this.middleware,\n onLifecycleEvent: this.onLifecycleEvent,\n requestId,\n });\n return await withRetry(\n () => operation(http, timeout.signal),\n {\n ...this.retryConfig,\n onRetry: (error, attempt, delayMs) => {\n this.retryConfig.onRetry?.(error, attempt, delayMs);\n this.onLifecycleEvent?.({\n type: 'retry',\n requestId,\n attempt: attempt + 1,\n error,\n delayMs,\n timestamp: Date.now(),\n });\n },\n },\n timeout.signal,\n );\n // timeout.cancel() called automatically via `using _timeout`\n }\n\n // --- Capabilities & Health ---\n capabilities(model: string, signal?: AbortSignal): Promise<ModelCapabilities> {\n return this.executeWithFailover(\n (http, runnerSignal) => detectModelCapabilities(http, model, runnerSignal),\n {\n singleEndpoint: true,\n model,\n ...(signal !== undefined ? { signal } : {}),\n },\n );\n }\n runtimeMode(): RuntimeMode {\n const ep = this.registry.candidates()[0];\n return inferRuntimeMode(ep?.baseUrl ?? DEFAULT_BASE_URL);\n }\n healthCheck(): Promise<EndpointHealthCheckResult[]> {\n return Promise.all(\n this.registry\n .list()\n .map((ep) =>\n checkEndpointHealth(ep, this.fetchImpl, 5000, this.middleware, this.onLifecycleEvent),\n ),\n );\n }\n endpointStatus(): EndpointHealth[] {\n return this.registry.status();\n }\n\n // --- Compatibility Adapters ---\n get openai(): OpenAICompatClient {\n const ep = this.registry.candidates()[0];\n return new OpenAICompatClient(\n new HttpClient({\n baseUrl: ep?.baseUrl ?? DEFAULT_BASE_URL,\n apiKey: ep?.apiKey,\n headers: ep?.headers,\n fetch: this.fetchImpl,\n middleware: this.middleware,\n onLifecycleEvent: this.onLifecycleEvent,\n }),\n (op, opts) => this.executeWithFailover(op, opts),\n );\n }\n get anthropic(): AnthropicCompatClient {\n const ep = this.registry.candidates()[0];\n return new AnthropicCompatClient(\n new HttpClient({\n baseUrl: ep?.baseUrl ?? DEFAULT_BASE_URL,\n apiKey: ep?.apiKey,\n headers: ep?.headers,\n fetch: this.fetchImpl,\n middleware: this.middleware,\n onLifecycleEvent: this.onLifecycleEvent,\n }),\n (op, opts) => this.executeWithFailover(op, opts),\n );\n }\n}\n","/**\n * Web Standard Stream adapters for OllamaStream.\n * Enables seamless integration with Vercel AI SDK, Next.js route handlers, and standard web fetch responses.\n */\n\nimport type { OllamaStream } from './stream.js';\n\n/**\n * Transforms an OllamaStream into a standard Web ReadableStream of token text strings.\n */\nexport function toTextStream<TChunk, TFinal>(\n stream: OllamaStream<TChunk, TFinal>,\n): ReadableStream<string> {\n const iterator = stream[Symbol.asyncIterator]();\n\n return new ReadableStream<string>({\n async pull(controller) {\n try {\n while (true) {\n const { done, value } = await iterator.next();\n if (done) {\n controller.close();\n return;\n }\n if (value.type === 'token' && value.data.delta) {\n controller.enqueue(value.data.delta);\n return;\n }\n }\n } catch (err) {\n controller.error(err);\n }\n },\n cancel() {\n stream.abort();\n },\n });\n}\n\n/**\n * Transforms an OllamaStream into a standard Web ReadableStream of encoded Uint8Array bytes.\n */\nexport function toDataStream<TChunk, TFinal>(\n stream: OllamaStream<TChunk, TFinal>,\n): ReadableStream<Uint8Array> {\n const textStream = toTextStream(stream);\n const reader = textStream.getReader();\n const encoder = new TextEncoder();\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n return;\n }\n controller.enqueue(encoder.encode(value));\n } catch (err) {\n controller.error(err);\n }\n },\n cancel() {\n reader.cancel();\n stream.abort();\n },\n });\n}\n\n/**\n * Converts an OllamaStream directly into a standard Web Response with text/plain streaming headers.\n */\nexport function toResponse<TChunk, TFinal>(\n stream: OllamaStream<TChunk, TFinal>,\n init: ResponseInit = {},\n): Response {\n const body = toDataStream(stream);\n const headers = new Headers(init.headers);\n if (!headers.has('Content-Type')) {\n headers.set('Content-Type', 'text/plain; charset=utf-8');\n }\n return new Response(body, { ...init, headers });\n}\n","/**\n * Client-side usage budgeting.\n *\n * Ollama Cloud does not expose account-level quota or remaining-budget through the API —\n * chat/generate responses carry only per-request token counts, and there is no header or\n * endpoint that reports how much of your plan's session or weekly limit is left (the only\n * way to see that today is the https://ollama.com dashboard or the 90%-usage email). See\n * https://github.com/ollama/ollama/issues/15663.\n *\n * `QuotaManager` does not — and cannot — read Ollama's real limits. It tracks usage you\n * record against budgets *you* configure over one or more rolling windows, and refuses to\n * proceed once a window's budget is spent. Pair it with `OllamaRateLimitError` (thrown by\n * `OllamaClient` on the server's actual 429) as the authoritative signal; treat\n * `QuotaManager` as a local safety net that fails fast before the request is even sent.\n */\n\nimport { OllamaQuotaExceededError } from './errors.js';\nimport { extractUsage, type RawUsageSource, type TokenUsage } from './usage.js';\n\nexport interface QuotaWindowConfig {\n /** Identifies this window in status reports and thrown errors (e.g. \"session\", \"weekly\"). */\n readonly id: string;\n /** Length of the rolling window in milliseconds, after which usage resets to zero. */\n readonly windowMs: number;\n /** Token budget for the window. Omit to only track requests. */\n readonly maxTokens?: number;\n /** Request-count budget for the window. Omit to only track tokens. */\n readonly maxRequests?: number;\n}\n\nexport interface QuotaWindowStatus extends QuotaWindowConfig {\n readonly tokensUsed: number;\n readonly requestsMade: number;\n readonly windowStartedAt: number;\n readonly windowResetAt: number;\n readonly remainingTokens?: number;\n readonly remainingRequests?: number;\n}\n\nexport interface QuotaManagerOptions {\n readonly windows: readonly QuotaWindowConfig[];\n /** Clock override for testing. Defaults to `Date.now`. */\n readonly now?: () => number;\n}\n\ninterface WindowState {\n readonly config: QuotaWindowConfig;\n tokensUsed: number;\n requestsMade: number;\n windowStartedAt: number;\n}\n\nexport class QuotaManager {\n private readonly now: () => number;\n private readonly windows: readonly WindowState[];\n\n constructor(options: QuotaManagerOptions) {\n if (options.windows.length === 0) {\n throw new Error('QuotaManager requires at least one window configuration.');\n }\n this.now = options.now ?? Date.now;\n this.windows = options.windows.map((config) => ({\n config,\n tokensUsed: 0,\n requestsMade: 0,\n windowStartedAt: this.now(),\n }));\n }\n\n private rollover(state: WindowState): void {\n if (this.now() - state.windowStartedAt >= state.config.windowMs) {\n state.tokensUsed = 0;\n state.requestsMade = 0;\n state.windowStartedAt = this.now();\n }\n }\n\n /** Current usage, budgets, and reset time for every configured window. */\n status(): readonly QuotaWindowStatus[] {\n return this.windows.map((state) => {\n this.rollover(state);\n const { config } = state;\n return {\n ...config,\n tokensUsed: state.tokensUsed,\n requestsMade: state.requestsMade,\n windowStartedAt: state.windowStartedAt,\n windowResetAt: state.windowStartedAt + config.windowMs,\n ...(config.maxTokens !== undefined\n ? { remainingTokens: Math.max(0, config.maxTokens - state.tokensUsed) }\n : {}),\n ...(config.maxRequests !== undefined\n ? { remainingRequests: Math.max(0, config.maxRequests - state.requestsMade) }\n : {}),\n };\n });\n }\n\n /**\n * True if one more request — optionally estimated at `estimatedTokens` — would stay\n * within every configured window's budget. Read-only; does not record usage.\n */\n canProceed(estimatedTokens = 0): boolean {\n return this.windows.every((state) => {\n this.rollover(state);\n const { config } = state;\n if (config.maxRequests !== undefined && state.requestsMade + 1 > config.maxRequests) {\n return false;\n }\n return !(\n config.maxTokens !== undefined && state.tokensUsed + estimatedTokens > config.maxTokens\n );\n });\n }\n\n /**\n * Throws `OllamaQuotaExceededError` for the first window that `canProceed(estimatedTokens)`\n * would fail on; otherwise a no-op. Call before issuing a request.\n */\n assertCanProceed(estimatedTokens = 0): void {\n for (const state of this.windows) {\n this.rollover(state);\n const { config } = state;\n if (config.maxRequests !== undefined && state.requestsMade + 1 > config.maxRequests) {\n throw new OllamaQuotaExceededError(\n `Client-side quota window \"${config.id}\" would exceed its request budget ` +\n `(${state.requestsMade}/${config.maxRequests} requests used).`,\n { windowId: config.id, resetAt: state.windowStartedAt + config.windowMs },\n );\n }\n if (config.maxTokens !== undefined && state.tokensUsed + estimatedTokens > config.maxTokens) {\n throw new OllamaQuotaExceededError(\n `Client-side quota window \"${config.id}\" would exceed its token budget ` +\n `(${state.tokensUsed}/${config.maxTokens} tokens used).`,\n { windowId: config.id, resetAt: state.windowStartedAt + config.windowMs },\n );\n }\n }\n }\n\n /** Records one request's actual usage — a raw API response or a pre-normalized `TokenUsage` — against every window. */\n recordUsage(usage: RawUsageSource | TokenUsage): void {\n const normalized: TokenUsage = 'totalTokens' in usage ? usage : extractUsage(usage);\n for (const state of this.windows) {\n this.rollover(state);\n state.tokensUsed += normalized.totalTokens;\n state.requestsMade += 1;\n }\n }\n\n /** Resets one window (by `id`) or, if omitted, all windows — zeroing usage and restarting their clocks. */\n reset(windowId?: string): void {\n for (const state of this.windows) {\n if (windowId === undefined || state.config.id === windowId) {\n state.tokensUsed = 0;\n state.requestsMade = 0;\n state.windowStartedAt = this.now();\n }\n }\n }\n}\n\nexport interface OllamaCloudFreeTierQuotaBudgets {\n /** Budget for the free tier's ~5-hour session window. Omit to skip tracking it. */\n readonly session?: { readonly maxTokens?: number; readonly maxRequests?: number };\n /** Budget for the free tier's 7-day weekly window. Omit to skip tracking it. */\n readonly weekly?: { readonly maxTokens?: number; readonly maxRequests?: number };\n readonly now?: () => number;\n}\n\n/**\n * Convenience factory mirroring Ollama Cloud free-tier's documented reset cadence — a\n * session window that resets every 5 hours and a weekly window that resets every 7 days\n * (see https://ollama.com/pricing). Ollama does not publish the actual token/request\n * ceilings for either window, so you must supply the budgets yourself (e.g. from your own\n * observed usage) — this only wires up the window durations.\n */\nexport function createOllamaCloudFreeTierQuota(\n budgets: OllamaCloudFreeTierQuotaBudgets,\n): QuotaManager {\n const windows: QuotaWindowConfig[] = [];\n if (budgets.session !== undefined) {\n windows.push({ id: 'session', windowMs: 5 * 60 * 60 * 1000, ...budgets.session });\n }\n if (budgets.weekly !== undefined) {\n windows.push({ id: 'weekly', windowMs: 7 * 24 * 60 * 60 * 1000, ...budgets.weekly });\n }\n if (windows.length === 0) {\n throw new Error(\n 'createOllamaCloudFreeTierQuota requires at least a `session` or `weekly` budget.',\n );\n }\n return new QuotaManager({ windows, ...(budgets.now !== undefined ? { now: budgets.now } : {}) });\n}\n","/**\n * Type-safe tool definition helper.\n */\n\nimport type { z } from 'zod';\nimport { zodToJsonSchema } from '../schema/zod.js';\nimport type { Tool, ToolHandler } from './types.js';\nimport type { ToolProperty } from '../types.js';\n\nexport interface DefineToolOptions<TParams, TResult> {\n readonly name: string;\n readonly description: string;\n readonly schema: z.ZodType<TParams>;\n readonly execute: ToolHandler<TParams, TResult>;\n /**\n * Per-tool execution timeout in milliseconds, overriding the registry's default.\n * Pass `0` to explicitly disable timeout enforcement for this tool.\n */\n readonly timeoutMs?: number | undefined;\n}\n\n/**\n * Creates a strongly-typed Tool definition with automatic JSON Schema conversion.\n */\nexport function defineTool<TParams, TResult>(\n options: DefineToolOptions<TParams, TResult>,\n): Tool<TParams, TResult> {\n const jsonSchema = zodToJsonSchema(options.schema);\n const properties = (jsonSchema['properties'] ?? {}) as Record<string, ToolProperty>;\n const required = (jsonSchema['required'] ?? []) as string[];\n\n return {\n name: options.name,\n description: options.description,\n schema: options.schema,\n execute: options.execute,\n timeoutMs: options.timeoutMs,\n definition: {\n type: 'function',\n function: {\n name: options.name,\n description: options.description,\n parameters: {\n type: 'object',\n properties,\n ...(required.length > 0 ? { required } : {}),\n },\n },\n },\n };\n}\n","/**\n * Tool registry for managing definitions and executing model tool calls.\n */\n\nimport {\n OllamaNotFoundError,\n OllamaToolTimeoutError,\n OllamaToolValidationError,\n} from '../errors.js';\nimport {\n withSpan,\n setSpanError,\n ATTR_GEN_AI_TOOL_NAME,\n ATTR_GEN_AI_TOOL_CALL_ID,\n} from '../telemetry/index.js';\nimport type { ToolCall, ToolDefinition } from '../types.js';\nimport type { AnyTool, Tool, ToolExecutionContext, ToolExecutionResult } from './types.js';\nimport { disposableTimer } from '../utils.js';\n\nexport interface ToolRegistryOptions {\n readonly tools?: readonly AnyTool[] | undefined;\n readonly onError?: ((error: Error, toolCall: ToolCall) => string) | undefined;\n /**\n * Default per-call execution timeout in milliseconds, applied to any tool that\n * doesn't declare its own `timeoutMs`. Undefined (the default) means no timeout is\n * enforced, matching prior behavior. Recommended whenever tool arguments or\n * implementations are influenced by model output you don't fully control, since an\n * unbounded tool call can otherwise stall the entire agent loop indefinitely.\n *\n * Enforcement is cooperative: it races the tool's promise against a timer and\n * reports a timeout failure, but cannot forcibly halt synchronous or non-abort-aware\n * asynchronous work already in flight on the same thread. Tools that perform I/O\n * should honor `ToolExecutionContext.signal` to stop promptly on timeout.\n */\n readonly timeoutMs?: number | undefined;\n /**\n * Maximum number of tool calls executed concurrently by `executeToolCalls`.\n * Undefined (the default) runs all calls in parallel, matching prior behavior.\n */\n readonly maxConcurrency?: number | undefined;\n /**\n * Maximum length of a tool's `outputString` before it is truncated. Guards against a\n * single tool call flooding the conversation history / model context (and process\n * memory) with unbounded output. Undefined (the default) applies no limit.\n */\n readonly maxOutputChars?: number | undefined;\n}\n\nexport class ToolRegistry {\n private readonly tools = new Map<string, AnyTool>();\n private readonly onError?: ((error: Error, toolCall: ToolCall) => string) | undefined;\n private readonly defaultTimeoutMs?: number | undefined;\n private readonly maxConcurrency?: number | undefined;\n private readonly maxOutputChars?: number | undefined;\n\n constructor(toolsOrOptions?: readonly AnyTool[] | ToolRegistryOptions | undefined) {\n if (Array.isArray(toolsOrOptions)) {\n this.registerMany(toolsOrOptions);\n } else if (toolsOrOptions !== undefined) {\n const opts = toolsOrOptions as ToolRegistryOptions;\n this.onError = opts.onError;\n this.defaultTimeoutMs = opts.timeoutMs;\n this.maxConcurrency = opts.maxConcurrency;\n this.maxOutputChars = opts.maxOutputChars;\n if (opts.tools) {\n this.registerMany(opts.tools);\n }\n }\n }\n\n register(tool: AnyTool): this {\n this.tools.set(tool.name, tool);\n return this;\n }\n\n registerMany(tools: readonly AnyTool[]): this {\n for (const tool of tools) {\n this.register(tool);\n }\n return this;\n }\n\n get(name: string): AnyTool | undefined {\n return this.tools.get(name);\n }\n\n definitions(): ToolDefinition[] {\n return Array.from(this.tools.values()).map((t) => t.definition);\n }\n\n async executeToolCall(\n toolCall: ToolCall,\n ctx: ToolExecutionContext = {},\n ): Promise<ToolExecutionResult> {\n const { name } = toolCall.function;\n return withSpan(\n `execute_tool ${name}`,\n { [ATTR_GEN_AI_TOOL_NAME]: name, [ATTR_GEN_AI_TOOL_CALL_ID]: toolCall.id },\n async (span) => {\n const result = await this.executeToolCallUninstrumented(toolCall, ctx);\n if (!result.success) {\n await setSpanError(span, result.error);\n }\n return result;\n },\n );\n }\n\n private async executeToolCallUninstrumented(\n toolCall: ToolCall,\n ctx: ToolExecutionContext,\n ): Promise<ToolExecutionResult> {\n const { name, arguments: args } = toolCall.function;\n const tool = this.tools.get(name);\n\n if (!tool) {\n const err = new OllamaNotFoundError(`Tool \"${name}\" is not registered in this registry`);\n return this.handleExecutionError(err, toolCall);\n }\n\n const parseResult = tool.schema.safeParse(args);\n if (!parseResult.success) {\n const err = new OllamaToolValidationError(`Tool \"${name}\" arguments validation failed`, {\n toolName: name,\n issues: parseResult.error.issues,\n cause: parseResult.error,\n });\n return this.handleExecutionError(err, toolCall);\n }\n\n try {\n const result = await this.runWithTimeout(tool, parseResult.data, ctx, name);\n const outputString = this.truncateOutput(\n typeof result === 'string' ? result : JSON.stringify(result),\n );\n return {\n toolName: name,\n toolCallId: toolCall.id,\n success: true,\n result,\n outputString,\n };\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n return this.handleExecutionError(error, toolCall);\n }\n }\n\n /**\n * Executes every call in `toolCalls` and returns results in the same order, so results\n * are always correlatable by array position regardless of `id`. Each result also echoes\n * its call's `toolCallId` for callers who'd rather match by ID — see the {@link ToolCall}\n * docs for how that id is produced. Runs fully in parallel (`Promise.all`) unless\n * `maxConcurrency` was configured, in which case a bounded worker pool is used instead.\n */\n async executeToolCalls(\n toolCalls: readonly ToolCall[],\n ctx: ToolExecutionContext = {},\n ): Promise<ToolExecutionResult[]> {\n const limit = this.maxConcurrency;\n if (!limit || limit >= toolCalls.length) {\n return Promise.all(toolCalls.map((tc) => this.executeToolCall(tc, ctx)));\n }\n\n const results = new Array<ToolExecutionResult>(toolCalls.length);\n let nextIndex = 0;\n const worker = async (): Promise<void> => {\n for (let i = nextIndex++; i < toolCalls.length; i = nextIndex++) {\n results[i] = await this.executeToolCall(toolCalls[i] as ToolCall, ctx);\n }\n };\n await Promise.all(Array.from({ length: limit }, () => worker()));\n return results;\n }\n\n private async runWithTimeout<TParams>(\n tool: Tool<TParams, unknown>,\n params: TParams,\n ctx: ToolExecutionContext,\n toolName: string,\n ): Promise<unknown> {\n const timeoutMs = tool.timeoutMs ?? this.defaultTimeoutMs;\n if (!timeoutMs || timeoutMs <= 0) {\n return tool.execute(params, ctx);\n }\n\n const controller = new AbortController();\n const onParentAbort = (): void => controller.abort(ctx.signal?.reason);\n if (ctx.signal) {\n if (ctx.signal.aborted) {\n controller.abort(ctx.signal.reason);\n } else {\n ctx.signal.addEventListener('abort', onParentAbort, { once: true });\n }\n }\n\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs);\n using _timer = disposableTimer(timer);\n // Also clean up the parent-abort listener at scope exit (conditional on ctx.signal)\n using _listener = {\n [Symbol.dispose]() {\n ctx.signal?.removeEventListener('abort', onParentAbort);\n },\n };\n\n const executePromise = Promise.resolve(\n tool.execute(params, { ...ctx, signal: controller.signal }),\n );\n // Prevent an unhandled rejection if the tool's promise loses the race and later\n // rejects; the tool remains responsible for actually stopping its own work via\n // `signal` since JS cannot forcibly cancel work already in flight.\n executePromise.catch(() => undefined);\n\n const abortRejection = (): Error =>\n timedOut\n ? new OllamaToolTimeoutError(`Tool \"${toolName}\" timed out after ${timeoutMs}ms`, {\n toolName,\n timeoutMs,\n })\n : ((ctx.signal?.reason as Error | undefined) ?? new Error('Tool execution aborted'));\n\n return await Promise.race([\n executePromise,\n controller.signal.aborted\n ? Promise.reject(abortRejection())\n : new Promise<never>((_resolve, reject) => {\n controller.signal.addEventListener('abort', () => reject(abortRejection()), {\n once: true,\n });\n }),\n ]);\n // clearTimeout(timer) + removeEventListener called automatically via `using`\n }\n\n private truncateOutput(output: string): string {\n const limit = this.maxOutputChars;\n if (!limit || output.length <= limit) {\n return output;\n }\n return `${output.slice(0, limit)}\\n… [truncated ${output.length - limit} of ${output.length} chars]`;\n }\n\n private handleExecutionError(error: Error, toolCall: ToolCall): ToolExecutionResult {\n const fallbackMessage = this.onError ? this.onError(error, toolCall) : error.message;\n return {\n toolName: toolCall.function.name,\n toolCallId: toolCall.id,\n success: false,\n error,\n outputString: this.truncateOutput(fallbackMessage),\n };\n }\n}\n","/** Dependency-free JSON Schema validator for MCP tool argument boundaries. */\n\nexport interface JsonSchemaValidationIssue {\n readonly path: readonly (string | number)[];\n readonly message: string;\n}\n\nfunction label(path: readonly (string | number)[]): string {\n return path.length === 0 ? 'value' : 'value' + path.map((part) => typeof part === 'number' ? '[' + part + ']' : '.' + part).join('');\n}\n\nfunction equalJson(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== typeof b || a === null || b === null) return false;\n if (Array.isArray(a) || Array.isArray(b)) {\n return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, i) => equalJson(item, b[i]));\n }\n if (typeof a === 'object' && typeof b === 'object') {\n const ar = a as Record<string, unknown>;\n const br = b as Record<string, unknown>;\n const ak = Object.keys(ar).sort();\n const bk = Object.keys(br).sort();\n return ak.length === bk.length && ak.every((key, i) => key === bk[i] && equalJson(ar[key], br[key]));\n }\n return false;\n}\n\nfunction matchesType(value: unknown, type: string): boolean {\n switch (type) {\n case 'null': return value === null;\n case 'boolean': return typeof value === 'boolean';\n case 'object': return typeof value === 'object' && value !== null && !Array.isArray(value);\n case 'array': return Array.isArray(value);\n case 'string': return typeof value === 'string';\n case 'number': return typeof value === 'number' && Number.isFinite(value);\n case 'integer': return typeof value === 'number' && Number.isInteger(value);\n default: return true;\n }\n}\n\nfunction validate(value: unknown, schema: unknown, path: readonly (string | number)[]): JsonSchemaValidationIssue[] {\n if (schema === true || schema === undefined) return [];\n if (schema === false) return [{ path, message: label(path) + ' is not allowed by the schema' }];\n if (typeof schema !== 'object' || schema === null || Array.isArray(schema)) return [];\n const s = schema as Record<string, unknown>;\n const issues: JsonSchemaValidationIssue[] = [];\n\n if (s['nullable'] === true && value === null) return issues;\n\n const type = s['type'];\n if (typeof type === 'string' && !matchesType(value, type)) {\n return [{ path, message: label(path) + ' must be ' + type }];\n }\n if (Array.isArray(type) && !type.some((t) => typeof t === 'string' && matchesType(value, t))) {\n return [{ path, message: label(path) + ' must match one of: ' + type.join(', ') }];\n }\n\n if ('const' in s && !equalJson(value, s['const'])) issues.push({ path, message: label(path) + ' must equal the schema const value' });\n const enumValues = s['enum'];\n if (Array.isArray(enumValues) && !enumValues.some((item) => equalJson(value, item))) issues.push({ path, message: label(path) + ' must be one of the allowed enum values' });\n\n const anyOf = s['anyOf'];\n if (Array.isArray(anyOf) && !anyOf.some((candidate) => validate(value, candidate, path).length === 0)) issues.push({ path, message: label(path) + ' must satisfy at least one anyOf schema' });\n const oneOf = s['oneOf'];\n if (Array.isArray(oneOf)) {\n const matches = oneOf.filter((candidate) => validate(value, candidate, path).length === 0).length;\n if (matches !== 1) issues.push({ path, message: label(path) + ' must satisfy exactly one oneOf schema' });\n }\n const allOf = s['allOf'];\n if (Array.isArray(allOf)) for (const candidate of allOf) issues.push(...validate(value, candidate, path));\n if ('not' in s && validate(value, s['not'], path).length === 0) issues.push({ path, message: label(path) + ' must not satisfy the not schema' });\n\n if (typeof value === 'string') {\n const min = s['minLength'];\n const max = s['maxLength'];\n if (typeof min === 'number' && value.length < min) issues.push({ path, message: label(path) + ' must have at least ' + min + ' characters' });\n if (typeof max === 'number' && value.length > max) issues.push({ path, message: label(path) + ' must have at most ' + max + ' characters' });\n if (typeof s['pattern'] === 'string') {\n try { if (!new RegExp(s['pattern']).test(value)) issues.push({ path, message: label(path) + ' does not match the required pattern' }); }\n catch { /* malformed provider regex; do not reject otherwise valid arguments */ }\n }\n }\n\n if (typeof value === 'number' && Number.isFinite(value)) {\n const numericRules: readonly [string, (n: number, bound: number) => boolean, string][] = [\n ['minimum', (n, b) => n >= b, 'must be greater than or equal to'],\n ['maximum', (n, b) => n <= b, 'must be less than or equal to'],\n ['exclusiveMinimum', (n, b) => n > b, 'must be greater than'],\n ['exclusiveMaximum', (n, b) => n < b, 'must be less than'],\n ];\n for (const [keyword, check, phrase] of numericRules) {\n const bound = s[keyword];\n if (typeof bound === 'number' && !check(value, bound)) issues.push({ path, message: label(path) + ' ' + phrase + ' ' + bound });\n }\n const multipleOf = s['multipleOf'];\n if (typeof multipleOf === 'number' && multipleOf > 0) {\n const quotient = value / multipleOf;\n if (Math.abs(quotient - Math.round(quotient)) > 1e-12) issues.push({ path, message: label(path) + ' must be a multiple of ' + multipleOf });\n }\n }\n\n if (Array.isArray(value)) {\n const min = s['minItems'];\n const max = s['maxItems'];\n if (typeof min === 'number' && value.length < min) issues.push({ path, message: label(path) + ' must contain at least ' + min + ' items' });\n if (typeof max === 'number' && value.length > max) issues.push({ path, message: label(path) + ' must contain at most ' + max + ' items' });\n if (s['uniqueItems'] === true) {\n for (let i = 0; i < value.length; i += 1) if (value.slice(0, i).some((previous) => equalJson(previous, value[i]))) { issues.push({ path: [...path, i], message: label([...path, i]) + ' must be unique' }); break; }\n }\n if ('items' in s) value.forEach((item, i) => issues.push(...validate(item, s['items'], [...path, i])));\n if (Array.isArray(s['prefixItems'])) s['prefixItems'].forEach((itemSchema, i) => { if (i < value.length) issues.push(...validate(value[i], itemSchema, [...path, i])); });\n }\n\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n const object = value as Record<string, unknown>;\n const required = s['required'];\n if (Array.isArray(required)) for (const key of required) if (typeof key === 'string' && !(key in object)) issues.push({ path: [...path, key], message: label([...path, key]) + ' is required' });\n const properties = s['properties'];\n if (typeof properties === 'object' && properties !== null && !Array.isArray(properties)) {\n const propertySchemas = properties as Record<string, unknown>;\n for (const [key, propertySchema] of Object.entries(propertySchemas)) if (key in object) issues.push(...validate(object[key], propertySchema, [...path, key]));\n const additional = s['additionalProperties'];\n for (const key of Object.keys(object)) {\n if (key in propertySchemas) continue;\n if (additional === false) issues.push({ path: [...path, key], message: label([...path, key]) + ' is not allowed' });\n else if (additional !== true && additional !== undefined) issues.push(...validate(object[key], additional, [...path, key]));\n }\n }\n const min = s['minProperties'];\n const max = s['maxProperties'];\n if (typeof min === 'number' && Object.keys(object).length < min) issues.push({ path, message: label(path) + ' must contain at least ' + min + ' properties' });\n if (typeof max === 'number' && Object.keys(object).length > max) issues.push({ path, message: label(path) + ' must contain at most ' + max + ' properties' });\n }\n\n return issues;\n}\n\nexport function validateJsonSchema(value: unknown, schema: unknown): readonly JsonSchemaValidationIssue[] {\n return validate(value, schema, []);\n}","/**\n * Converts MCP tools into Ollama-compatible tools.\n */\n\nimport { z } from 'zod';\nimport { validateJsonSchema } from './json-schema.js';\nimport { OllamaMcpError } from '../errors.js';\nimport type { AnyTool } from '../tools/types.js';\nimport type { ToolRegistry } from '../tools/registry.js';\nimport type {\n McpClientLike,\n McpListToolsParams,\n McpRequestOptions,\n McpToolCallResult,\n McpToolDescriptor,\n} from './types.js';\nimport type { ToolDefinition, ToolProperty } from '../types.js';\n\nexport type McpToolResultMode = 'text' | 'structured';\n\nexport interface LoadMcpToolsOptions {\n readonly namePrefix?: string | undefined;\n /** Maximum number of paginated tools/list responses to traverse. */\n readonly maxPages?: number | undefined;\n /**\n * Return MCP's raw CallToolResult to programmatic callers instead of the legacy\n * model-oriented text representation. The default preserves existing behavior.\n */\n readonly resultMode?: McpToolResultMode | undefined;\n /** Validate structuredContent against a tool's MCP outputSchema. Defaults to true. */\n readonly validateOutputSchema?: boolean | undefined;\n /** Invoke optional task-capable tools as legacy MCP tasks when supported. */\n readonly taskMode?: 'required-only' | 'all-supported' | undefined;\n /** Requested lifetime for legacy task-augmented tool calls, in milliseconds. */\n readonly taskTtlMs?: number | undefined;\n}\n\nfunction resolveMaxPages(options: LoadMcpToolsOptions): number {\n const maxPages = options.maxPages ?? 64;\n if (!Number.isInteger(maxPages) || maxPages <= 0) {\n throw new RangeError('MCP maxPages must be a positive integer');\n }\n return maxPages;\n}\n\nexport async function listAllMcpTools(\n mcpClient: McpClientLike,\n options: LoadMcpToolsOptions = {},\n signal?: AbortSignal,\n): Promise<McpToolDescriptor[]> {\n const maxPages = resolveMaxPages(options);\n const tools: McpToolDescriptor[] = [];\n const seenCursors = new Set<string>();\n let cursor: string | undefined;\n\n for (let pageNumber = 1; pageNumber <= maxPages; pageNumber += 1) {\n const params: McpListToolsParams | undefined =\n cursor !== undefined ? { cursor } : undefined;\n const requestOptions: McpRequestOptions | undefined =\n signal !== undefined ? { signal } : undefined;\n const page = await mcpClient.listTools(params, requestOptions);\n const pageNames = new Set<string>();\n for (const tool of page.tools) {\n if (pageNames.has(tool.name)) {\n throw new OllamaMcpError(\n `MCP tools/list returned duplicate tool name \"${tool.name}\"`,\n { mcpMethod: 'listTools', toolName: tool.name },\n );\n }\n pageNames.add(tool.name);\n if (tools.some((existing) => existing.name === tool.name)) {\n throw new OllamaMcpError(\n `MCP tools/list returned duplicate tool name \"${tool.name}\" across pages`,\n { mcpMethod: 'listTools', toolName: tool.name },\n );\n }\n }\n tools.push(...page.tools);\n\n if (page.nextCursor === undefined) {\n return tools;\n }\n if (seenCursors.has(page.nextCursor)) {\n throw new Error('MCP tools/list returned a repeated nextCursor');\n }\n seenCursors.add(page.nextCursor);\n cursor = page.nextCursor;\n }\n\n throw new Error('MCP tools/list exceeded maxPages (' + maxPages + ')');\n}\n\nfunction formatMcpToolResult(result: McpToolCallResult): string {\n if ('resultType' in result || 'task' in result) {\n return JSON.stringify(result) ?? String(result);\n }\n\n const parts = result.content.map((block) => {\n if (block.type === 'text' && typeof block.text === 'string') {\n return block.text;\n }\n try {\n return JSON.stringify(block);\n } catch {\n return `[${block.type}]`;\n }\n });\n\n if (result.structuredContent !== undefined) {\n try {\n parts.push(JSON.stringify(result.structuredContent));\n } catch {\n // Preserve the regular content if structuredContent cannot be serialized.\n }\n }\n\n if (result.isError) {\n parts.unshift('[MCP tool error]');\n }\n\n return parts.join('\\n');\n}\n\nfunction supportsTaskCalls(mcpClient: McpClientLike): boolean {\n return mcpClient.getServerCapabilities?.()?.tasks?.requests?.tools?.call !== undefined;\n}\n\nfunction shouldCallAsTask(\n descriptor: McpToolDescriptor,\n options: LoadMcpToolsOptions,\n serverSupportsTasks: boolean,\n): boolean {\n const support = descriptor.execution?.taskSupport;\n if (support === 'required' && !serverSupportsTasks) {\n throw new OllamaMcpError(\n `MCP tool \"${descriptor.name}\" requires task execution, but the server does not advertise tasks.requests.tools.call`,\n { mcpMethod: 'callTool', toolName: descriptor.name },\n );\n }\n if (!serverSupportsTasks || support === undefined || support === 'forbidden') return false;\n return support === 'required' || options.taskMode === 'all-supported';\n}\n\nfunction createInputValidator(inputSchema: Record<string, unknown>): z.ZodType<Record<string, unknown>> {\n return z.custom<Record<string, unknown>>().superRefine((value, ctx) => {\n const issues = validateJsonSchema(value, inputSchema);\n for (const issue of issues) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [...issue.path],\n message: issue.message,\n });\n }\n });\n}\n\nfunction convertMcpDescriptorToTool(\n descriptor: McpToolDescriptor,\n mcpClient: McpClientLike,\n namePrefix = '',\n resultMode: McpToolResultMode = 'text',\n validateOutputSchema = true,\n executeAsTask = false,\n taskTtlMs?: number,\n): AnyTool {\n const toolName = `${namePrefix}${descriptor.name}`;\n const inputSchema = descriptor.inputSchema ?? { type: 'object', properties: {} };\n const properties = (inputSchema['properties'] ?? {}) as Record<string, ToolProperty>;\n const required = (inputSchema['required'] ?? []) as string[];\n const parameters = {\n ...inputSchema,\n type: 'object' as const,\n properties,\n ...(required.length > 0 ? { required } : {}),\n } as ToolDefinition['function']['parameters'];\n\n return {\n name: toolName,\n description: descriptor.description ?? '',\n schema: createInputValidator(inputSchema),\n execute: async (args: Record<string, unknown>, context: { readonly signal?: AbortSignal | undefined }) => {\n try {\n const result = await mcpClient.callTool(\n {\n name: descriptor.name,\n arguments: args,\n ...(executeAsTask\n ? { task: taskTtlMs !== undefined ? { ttl: taskTtlMs } : {} }\n : {}),\n },\n {\n ...(context.signal !== undefined ? { signal: context.signal } : {}),\n allowInputRequired: true,\n },\n );\n\n if (\n !('resultType' in result) &&\n !('task' in result) &&\n validateOutputSchema &&\n descriptor.outputSchema !== undefined &&\n result.structuredContent !== undefined\n ) {\n const issues = validateJsonSchema(result.structuredContent, descriptor.outputSchema);\n if (issues.length > 0) {\n throw new OllamaMcpError(\n `MCP tool \"${descriptor.name}\" returned structuredContent that violates outputSchema`,\n {\n mcpMethod: 'tools/call',\n toolName: descriptor.name,\n issues,\n },\n );\n }\n }\n\n // MCP tool failures are ordinary CallToolResult values, not transport failures.\n // Keep the result model-readable so the agent can observe the error and recover.\n return resultMode === 'structured' ? result : formatMcpToolResult(result);\n } catch (err) {\n if (err instanceof OllamaMcpError) throw err;\n throw new OllamaMcpError(`Failed calling MCP tool \"${descriptor.name}\"`, {\n mcpMethod: 'callTool',\n toolName: descriptor.name,\n cause: err,\n });\n }\n },\n definition: {\n type: 'function',\n function: {\n name: toolName,\n description: descriptor.description ?? '',\n parameters,\n },\n },\n };\n}\n\nexport async function loadMcpTools(\n mcpClient: McpClientLike,\n options: LoadMcpToolsOptions = {},\n signal?: AbortSignal,\n): Promise<AnyTool[]> {\n try {\n if (\n options.taskTtlMs !== undefined &&\n (!Number.isFinite(options.taskTtlMs) || options.taskTtlMs <= 0)\n ) {\n throw new RangeError('MCP taskTtlMs must be a positive finite number');\n }\n const tools = await listAllMcpTools(mcpClient, options, signal);\n const serverSupportsTasks = supportsTaskCalls(mcpClient);\n return tools.map((tool) => {\n const taskCall = shouldCallAsTask(\n tool,\n options,\n serverSupportsTasks,\n );\n return convertMcpDescriptorToTool(\n tool,\n mcpClient,\n options.namePrefix,\n options.resultMode,\n options.validateOutputSchema ?? true,\n taskCall,\n options.taskTtlMs,\n );\n });\n } catch (err) {\n if (err instanceof OllamaMcpError) throw err;\n throw new OllamaMcpError('Failed listing MCP tools from client', {\n mcpMethod: 'listTools',\n cause: err,\n });\n }\n}\n\nexport async function registerMcpTools(\n registry: ToolRegistry,\n mcpClient: McpClientLike,\n options: LoadMcpToolsOptions = {},\n signal?: AbortSignal,\n): Promise<void> {\n const tools = await loadMcpTools(mcpClient, options, signal);\n registry.registerMany(tools);\n}\n","/**\n * First-class MCP-to-Ollama bridge.\n *\n * The core package deliberately stays transport-agnostic and Edge-compatible. Connect\n * to an MCP server with an MCP client implementation (stdio, Streamable HTTP, etc.)\n * then pass that client to this bridge.\n */\nimport type { ToolDefinition } from '../types.js';\nimport type { ToolRegistry } from '../tools/registry.js';\nimport { OllamaMcpError } from '../errors.js';\nimport { z } from 'zod';\nimport { listAllMcpTools, loadMcpTools, type LoadMcpToolsOptions } from './mcp-tools.js';\nimport type {\n McpClientLike,\n McpCallToolResult,\n McpTask,\n McpTaskMethod,\n McpToolDescriptor,\n} from './types.js';\n\nexport type McpBridgeOptions = LoadMcpToolsOptions;\n\nconst taskSchema = z.object({\n taskId: z.string(),\n status: z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']),\n statusMessage: z.string().optional(),\n createdAt: z.string(),\n lastUpdatedAt: z.string(),\n ttl: z.number().optional(),\n pollInterval: z.number().optional(),\n}).passthrough();\nconst callToolResultSchema = z.custom<McpCallToolResult>(\n (value) =>\n typeof value === 'object' &&\n value !== null &&\n 'content' in value &&\n Array.isArray(value.content),\n);\n\nexport class McpBridge {\n constructor(\n private readonly client: McpClientLike,\n private readonly options: McpBridgeOptions = {},\n ) {}\n\n static toOllamaTools(\n tools: readonly McpToolDescriptor[],\n options: McpBridgeOptions = {},\n ): ToolDefinition[] {\n const prefix = options.namePrefix ?? '';\n return tools.map((tool) => ({\n type: 'function',\n function: {\n name: prefix + tool.name,\n description: tool.description ?? '',\n parameters: {\n ...(tool.inputSchema ?? { type: 'object', properties: {} }),\n type: 'object' as const,\n properties: ((tool.inputSchema ?? {})['properties'] ?? {}) as ToolDefinition['function']['parameters']['properties'],\n } as ToolDefinition['function']['parameters'],\n },\n }));\n }\n\n async listTools(signal?: AbortSignal): Promise<readonly McpToolDescriptor[]> {\n return listAllMcpTools(this.client, this.options, signal);\n }\n\n async definitions(signal?: AbortSignal): Promise<ToolDefinition[]> {\n return McpBridge.toOllamaTools(await this.listTools(signal), this.options);\n }\n\n async loadTools(signal?: AbortSignal) {\n return loadMcpTools(this.client, this.options, signal);\n }\n\n async register(registry: ToolRegistry, signal?: AbortSignal): Promise<void> {\n await registry.registerMany(await this.loadTools(signal));\n }\n\n /** Refreshes the current MCP tool catalog into an existing registry without clearing local tools. */\n async refresh(registry: ToolRegistry, signal?: AbortSignal): Promise<void> {\n await registry.registerMany(await this.loadTools(signal));\n }\n\n /** Fetches one legacy MCP task's current status without starting a polling loop. */\n async getTaskStatus(taskId: string, signal?: AbortSignal): Promise<McpTask> {\n return this.requestTask(\n 'tasks/get',\n taskId,\n taskSchema,\n signal,\n );\n }\n\n /** Retrieves a completed legacy MCP task's result. */\n async getTaskResult(taskId: string, signal?: AbortSignal): Promise<McpCallToolResult> {\n return this.requestTask(\n 'tasks/result',\n taskId,\n callToolResultSchema,\n signal,\n );\n }\n\n /** Cancels one legacy MCP task. */\n async cancelTask(taskId: string, signal?: AbortSignal): Promise<McpTask> {\n return this.requestTask(\n 'tasks/cancel',\n taskId,\n taskSchema,\n signal,\n );\n }\n\n private requestTask<T>(\n method: McpTaskMethod,\n taskId: string,\n resultSchema: z.ZodType<T>,\n signal?: AbortSignal,\n ): Promise<T> {\n if (this.client.request === undefined) {\n throw new OllamaMcpError(\n `MCP client does not support ${method} requests`,\n { mcpMethod: method },\n );\n }\n return this.client.request(\n { method, params: { taskId } },\n resultSchema,\n signal !== undefined ? { signal } : undefined,\n );\n }\n}\n","/**\n * Lightweight frontmatter parser for SKILL.md files.\n */\n\nimport { OllamaSkillInvalidError } from '../errors.js';\nimport type { SkillFrontmatter } from './types.js';\n\nexport interface ParsedFrontmatter {\n readonly frontmatter: SkillFrontmatter;\n readonly body: string;\n}\n\nfunction parseYamlValue(raw: string): unknown {\n const trimmed = raw.trim();\n if (trimmed === 'true') return true;\n if (trimmed === 'false') return false;\n if (!Number.isNaN(Number(trimmed)) && trimmed !== '') return Number(trimmed);\n if (\n (trimmed.startsWith('\"') && trimmed.endsWith('\"')) ||\n (trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\"))\n ) {\n return trimmed.slice(1, -1);\n }\n return trimmed;\n}\n\nfunction parseYamlBlock(yamlText: string): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n const lines = yamlText.split('\\n');\n let currentKey: string | undefined;\n let currentList: unknown[] | undefined;\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n if (trimmed.startsWith('- ') && currentKey) {\n if (!currentList) {\n currentList = [];\n result[currentKey] = currentList;\n }\n currentList.push(parseYamlValue(trimmed.slice(2)));\n continue;\n }\n\n currentList = undefined;\n const colonIndex = line.indexOf(':');\n if (colonIndex > 0) {\n const key = line.slice(0, colonIndex).trim();\n const valStr = line.slice(colonIndex + 1).trim();\n currentKey = key;\n if (valStr.length > 0) {\n result[key] = parseYamlValue(valStr);\n }\n }\n }\n\n return result;\n}\n\nexport function parseFrontmatter(source: string, path = ''): ParsedFrontmatter {\n const match = source.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/);\n if (!match) {\n throw new OllamaSkillInvalidError('Missing YAML frontmatter delimiters (---)', {\n skillName: path || 'unknown',\n path,\n });\n }\n\n const rawYaml = match[1] ?? '';\n const body = match[2]?.trim() ?? '';\n const parsed = parseYamlBlock(rawYaml);\n\n if (!parsed['name'] || typeof parsed['name'] !== 'string') {\n throw new OllamaSkillInvalidError('Frontmatter missing required string \"name\"', {\n skillName: String(parsed['name'] ?? 'unknown'),\n path,\n });\n }\n if (!parsed['description'] || typeof parsed['description'] !== 'string') {\n throw new OllamaSkillInvalidError('Frontmatter missing required string \"description\"', {\n skillName: parsed['name'],\n path,\n });\n }\n\n return {\n frontmatter: parsed as unknown as SkillFrontmatter,\n body,\n };\n}\n","/**\n * Skill composition and context injection.\n */\n\nimport type { Message } from '../types.js';\nimport type { ToolRegistry } from '../tools/registry.js';\nimport type { Skill } from './types.js';\n\nexport interface ApplySkillOptions {\n readonly messages: readonly Message[];\n readonly tools?: ToolRegistry;\n}\n\nexport interface AppliedSkillResult {\n readonly messages: readonly Message[];\n readonly tools?: ToolRegistry;\n}\n\n/**\n * Injects a skill's body into messages as a system prompt and applies allowed tool filters.\n */\nexport function applySkill(skill: Skill, options: ApplySkillOptions): AppliedSkillResult {\n const systemPrompt = `[Skill: ${skill.name}]\\n${skill.description}\\n\\n${skill.body}`;\n const messages = [...options.messages];\n const systemIndex = messages.findIndex((m) => m.role === 'system');\n\n if (systemIndex >= 0) {\n const existing = messages[systemIndex];\n if (existing) {\n messages[systemIndex] = {\n role: 'system',\n content: `${existing.content}\\n\\n${systemPrompt}`,\n };\n }\n } else {\n messages.unshift({ role: 'system', content: systemPrompt });\n }\n\n return {\n messages,\n ...(options.tools !== undefined ? { tools: options.tools } : {}),\n };\n}\n","/**\n * Multi-turn tool execution loop agent.\n */\n\nimport {\n OllamaAgentMaxIterationsError,\n OllamaAgentMaxToolCallsError,\n OllamaIncompatibleModelError,\n} from '../errors.js';\nimport {\n withSpan,\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_OLLAMA_AGENT_MAX_ITERATIONS,\n ATTR_OLLAMA_AGENT_ITERATION,\n GEN_AI_SYSTEM_OLLAMA,\n} from '../telemetry/index.js';\nimport { ensureToolCallIds } from '../tools/tool-call-id.js';\nimport type { ModelCapabilities } from '../capabilities/capabilities.js';\nimport type { Message, ModelOptions, ThinkValue, ToolDefinition } from '../types.js';\nimport type { ToolRegistry } from '../tools/registry.js';\nimport type { AgentConfig, AgentHooks, AgentResult, AgentRunInput, AgentTurn } from './types.js';\n\nexport interface AgentChatClient {\n capabilities?:\n | ((model: string, signal?: AbortSignal) => Promise<ModelCapabilities>)\n | undefined;\n chat(request: {\n readonly model: string;\n readonly messages: readonly Message[];\n readonly tools?: readonly ToolDefinition[] | undefined;\n readonly options?: ModelOptions | undefined;\n readonly think?: ThinkValue | undefined;\n readonly stream?: false | undefined;\n readonly signal?: AbortSignal | undefined;\n }): Promise<{ readonly message: Message }>;\n}\n\n/**\n * Runs a multi-turn `chat` + tool-execution loop until the model responds without\n * requesting further tool calls, or `maxIterations` is exceeded. Tool calls within a\n * single turn are handed to `ToolRegistry.executeToolCalls` and their results are\n * appended to history in the same order the model requested them. Native Ollama tool-result\n * messages use `tool_name` on the wire; the SDK-generated `toolCallId` remains execution\n * metadata and is not sent to Ollama.\n * `Agent` assigns ids defensively even when `AgentChatClient` isn't `OllamaClient` (e.g. a\n * custom/test implementation), so this guarantee holds regardless of which chat client is\n * supplied.\n */\nexport class Agent {\n private readonly client: AgentChatClient;\n private readonly tools?: ToolRegistry | undefined;\n private readonly maxIterations: number;\n private readonly maxToolCalls?: number | undefined;\n private readonly hooks?: AgentHooks | undefined;\n private readonly validateToolCapability: boolean;\n private readonly toolContextSize: number;\n\n constructor(client: AgentChatClient, config: AgentConfig = {}) {\n this.client = client;\n this.tools = config.tools;\n this.maxIterations = config.maxIterations ?? 10;\n this.maxToolCalls = config.maxToolCalls;\n this.hooks = config.hooks;\n if (this.maxToolCalls !== undefined && (!Number.isInteger(this.maxToolCalls) || this.maxToolCalls < 0)) {\n throw new RangeError('Agent maxToolCalls must be a non-negative integer');\n }\n this.validateToolCapability = config.validateToolCapability ?? true;\n this.toolContextSize = config.toolContextSize ?? 32768;\n if (!Number.isInteger(this.toolContextSize) || this.toolContextSize <= 0) {\n throw new RangeError('Agent toolContextSize must be a positive integer');\n }\n }\n\n run(input: AgentRunInput): Promise<AgentResult> {\n return withSpan(\n `invoke_agent ${input.model}`,\n {\n [ATTR_GEN_AI_SYSTEM]: GEN_AI_SYSTEM_OLLAMA,\n [ATTR_GEN_AI_OPERATION_NAME]: 'invoke_agent',\n [ATTR_GEN_AI_REQUEST_MODEL]: input.model,\n [ATTR_OLLAMA_AGENT_MAX_ITERATIONS]: this.maxIterations,\n },\n () => this.runLoop(input),\n );\n }\n\n private async runLoop(input: AgentRunInput): Promise<AgentResult> {\n const history: Message[] = [...input.messages];\n const turns: AgentTurn[] = [];\n const toolDefs = this.tools?.definitions();\n const hasTools = toolDefs !== undefined && toolDefs.length > 0;\n let capabilities: ModelCapabilities | undefined;\n\n if (hasTools && this.validateToolCapability && this.client.capabilities) {\n capabilities = await this.client.capabilities(input.model, input.signal);\n if (!capabilities.supportsTools) {\n throw new OllamaIncompatibleModelError(\n `Model \"${input.model}\" does not advertise the \"tools\" capability.`,\n {\n model: input.model,\n capability: 'tools',\n reportedCapabilities: capabilities.reported,\n },\n );\n }\n }\n\n const shouldAutoSizeContext =\n hasTools &&\n this.validateToolCapability &&\n capabilities !== undefined &&\n input.options?.num_ctx === undefined;\n\n const effectiveOptions = shouldAutoSizeContext\n ? {\n ...(input.options ?? {}),\n num_ctx: Math.min(\n this.toolContextSize,\n capabilities?.contextLength ?? this.toolContextSize,\n ),\n }\n : input.options;\n\n let toolCallsExecuted = 0;\n\n for (let iteration = 1; iteration <= this.maxIterations; iteration++) {\n const outcome = await withSpan(\n 'ollama.agent.turn',\n { [ATTR_OLLAMA_AGENT_ITERATION]: iteration },\n async () => {\n this.hooks?.onTurnStart?.(iteration);\n\n const response = await this.client.chat({\n model: input.model,\n messages: history,\n ...(toolDefs !== undefined ? { tools: toolDefs } : {}),\n ...(effectiveOptions !== undefined ? { options: effectiveOptions } : {}),\n ...(input.think !== undefined ? { think: input.think } : {}),\n stream: false,\n ...(input.signal !== undefined ? { signal: input.signal } : {}),\n });\n\n const rawToolCalls = response.message.tool_calls;\n const toolCalls = ensureToolCallIds(rawToolCalls);\n const assistantMessage: Message =\n toolCalls === rawToolCalls\n ? response.message\n : { ...response.message, tool_calls: toolCalls };\n history.push(assistantMessage);\n\n if (!toolCalls || toolCalls.length === 0 || !this.tools) {\n const finalTurn: AgentTurn = { iteration, message: assistantMessage };\n turns.push(finalTurn);\n this.hooks?.onTurnEnd?.(finalTurn);\n return { done: true as const, finalMessage: assistantMessage };\n }\n\n if (this.maxToolCalls !== undefined && toolCallsExecuted + toolCalls.length > this.maxToolCalls) {\n throw new OllamaAgentMaxToolCallsError(\n `Agent exceeded max tool calls (${this.maxToolCalls})`,\n { maxToolCalls: this.maxToolCalls, toolCallsExecuted },\n );\n }\n\n for (const tc of toolCalls) {\n this.hooks?.onToolCallStart?.(tc);\n }\n\n const toolResults = await this.tools.executeToolCalls(toolCalls, {\n signal: input.signal,\n });\n toolCallsExecuted += toolCalls.length;\n\n for (const res of toolResults) {\n this.hooks?.onToolCallEnd?.(res);\n history.push({\n role: 'tool',\n tool_name: res.toolName,\n content: res.outputString,\n });\n }\n\n const turn: AgentTurn = { iteration, message: assistantMessage, toolCalls, toolResults };\n turns.push(turn);\n this.hooks?.onTurnEnd?.(turn);\n return { done: false as const };\n },\n );\n\n if (outcome.done) {\n return { finalMessage: outcome.finalMessage, turns, totalIterations: iteration };\n }\n }\n\n throw new OllamaAgentMaxIterationsError(\n `Agent exceeded max iterations (${this.maxIterations}) without converging`,\n { maxIterations: this.maxIterations },\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/transport/host.ts","../src/config.ts","../src/errors.ts","../src/logger.ts","../src/providers/endpoint-registry.ts","../src/middleware.ts","../src/vision.ts","../src/utils.ts","../src/streaming/ndjson.ts","../src/streaming/sse.ts","../src/telemetry/tracer.ts","../src/transport/http.ts","../src/providers/health-check.ts","../src/capabilities/capabilities.ts","../src/schema/zod.ts","../src/usage.ts","../src/tools/tool-call-id.ts","../src/tools/tool-call-accumulator.ts","../src/streaming/stream.ts","../src/streaming/normalize.ts","../src/transport/backoff.ts","../src/transport/retry.ts","../src/transport/timeout.ts","../src/keep-alive.ts","../src/models-client.ts","../src/integrations/openai.ts","../src/integrations/anthropic.ts","../src/generated/models/IncludedBalance.schema.ts","../src/generated/models/LegacyBalanceLimit.schema.ts","../src/generated/models/LegacyIncludedBalance.schema.ts","../src/generated/models/BalanceResponse.schema.ts","../src/generated/models/ToolCall.schema.ts","../src/generated/models/ChatMessage.schema.ts","../src/generated/models/ModelOptions.schema.ts","../src/generated/models/ThinkValue.schema.ts","../src/generated/models/ToolDefinition.schema.ts","../src/generated/models/ChatRequest.schema.ts","../src/generated/models/TokenLogprob.schema.ts","../src/generated/models/Logprob.schema.ts","../src/generated/models/ChatResponse.schema.ts","../src/generated/models/CopyRequest.schema.ts","../src/generated/models/CreateRequest.schema.ts","../src/generated/models/DeleteRequest.schema.ts","../src/generated/models/EmbedRequest.schema.ts","../src/generated/models/EmbedResponse.schema.ts","../src/generated/models/GenerateRequest.schema.ts","../src/generated/models/GenerateResponse.schema.ts","../src/generated/models/ModelSummary.schema.ts","../src/generated/models/ListResponse.schema.ts","../src/generated/models/Ps.schema.ts","../src/generated/models/PsResponse.schema.ts","../src/generated/models/PullRequest.schema.ts","../src/generated/models/PushRequest.schema.ts","../src/generated/models/ShowRequest.schema.ts","../src/generated/models/Thinking.schema.ts","../src/generated/models/ShowResponse.schema.ts","../src/generated/models/StatusResponse.schema.ts","../src/generated/models/SystemOneContent.schema.ts","../src/generated/models/SystemOneChoiceQuestion.schema.ts","../src/generated/models/SystemOneNoulQuestion.schema.ts","../src/generated/models/SystemOneScoreQuestion.schema.ts","../src/generated/models/SystemOneRequest.schema.ts","../src/generated/models/SystemOneConfidence.schema.ts","../src/generated/models/SystemOneProbabilities.schema.ts","../src/generated/models/SystemOneChoiceAnswer.schema.ts","../src/generated/models/SystemOneNoulAnswer.schema.ts","../src/generated/models/SystemOneScoreAnswer.schema.ts","../src/generated/models/SystemOneResponse.schema.ts","../src/generated/models/UsageMetrics.schema.ts","../src/generated/models/UsageBucket.schema.ts","../src/generated/models/UsageResponse.schema.ts","../src/generated/models/VersionResponse.schema.ts","../src/generated/models/WebFetchRequest.schema.ts","../src/generated/models/WebFetchResponse.schema.ts","../src/generated/models/WebSearchRequest.schema.ts","../src/generated/models/WebSearchResult.schema.ts","../src/generated/models/WebSearchResponse.schema.ts","../src/generated/runtime/schema-registry.ts","../src/generated/runtime/runtime.ts","../src/responses.ts","../src/conversation.ts","../src/context-safety.ts","../src/generated/api/operations.ts","../src/generated/api/native-api.ts","../src/failover-http-client.ts","../src/decision.ts","../src/client.ts","../src/transport/fetch-with-backoff.ts","../src/done-reason.ts","../src/streaming/adapters.ts","../src/quota.ts","../src/tools/define-tool.ts","../src/tools/registry.ts","../src/mcp/json-schema.ts","../src/mcp/mcp-tools.ts","../src/mcp/bridge.ts","../src/skills/frontmatter.ts","../src/skills/compose.ts","../src/agent/agent.ts","../src/system-one.ts"],"names":["message","dispatch","response","z","controller","check","sleep"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQA,IAAM,YAAA,GAAe,OAAA;AACrB,IAAM,SAAA,GAAY,0BAAA;AAaX,SAAS,iBAAiB,IAAA,EAAsB;AACrD,EAAA,MAAM,OAAA,GAAU,KAAK,IAAA,EAAK;AAC1B,EAAA,IAAI,OAAA,KAAY,IAAI,OAAO,OAAA;AAE3B,EAAA,MAAM,cAAA,GAAiB,CAAC,SAAA,CAAU,IAAA,CAAK,OAAO,CAAA;AAC9C,EAAA,MAAM,WAAW,OAAA,CAAQ,UAAA,CAAW,GAAG,CAAA,GAAI,CAAA,SAAA,EAAY,OAAO,CAAA,CAAA,GAAK,OAAA;AACnE,EAAA,MAAM,SAAA,GAAY,cAAA,GAAiB,CAAA,OAAA,EAAU,QAAQ,CAAA,CAAA,GAAK,QAAA;AAE1D,EAAA,IAAI,GAAA;AACJ,EAAA,IAAI;AACF,IAAA,GAAA,GAAM,IAAI,IAAI,SAAS,CAAA;AAAA,EACzB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,OAAA,CAAQ,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAA;AAAA,EACnC;AAEA,EAAA,IAAI,WAAW,GAAA,CAAI,QAAA;AACnB,EAAA,IAAI,OAAO,GAAA,CAAI,IAAA;AACf,EAAA,IAAI,cAAA,EAAgB;AAClB,IAAA,IAAI,SAAS,KAAA,EAAO;A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Ollama base URLs.\n *\n * `OLLAMA_HOST` is conventionally written as a bare `host:port` (`127.0.0.1:11434`,\n * `0.0.0.0`, `:11434`), not a full URL — the official `ollama` CLI and client libraries\n * accept all of those. `fetch` does not, so every base URL is normalized before use.\n */\n\nconst DEFAULT_PORT = '11434';\nconst SCHEME_RE = /^[a-z][a-z0-9+.-]*:\\/\\//i;\n\n/**\n * Normalizes an Ollama host string into a base URL without a trailing slash.\n *\n * - An explicit scheme is kept as-is (`https://host`, `http://host:9999`).\n * - A missing scheme defaults to `http://`; a missing port on a scheme-less host defaults\n * to `11434`, except that port `443` with no scheme selects `https://` (port dropped).\n * - A leading `:port` means localhost (`:11434` → `http://127.0.0.1:11434`).\n * - A path prefix (reverse proxy mount) is preserved.\n * - Input that cannot be parsed is returned trimmed so the failure surfaces at request time\n * exactly as it did before normalization existed.\n */\nexport function normalizeBaseUrl(host: string): string {\n const trimmed = host.trim();\n if (trimmed === '') return trimmed;\n\n const implicitScheme = !SCHEME_RE.test(trimmed);\n const withHost = trimmed.startsWith(':') ? `127.0.0.1${trimmed}` : trimmed;\n const candidate = implicitScheme ? `http://${withHost}` : withHost;\n\n let url: URL;\n try {\n url = new URL(candidate);\n } catch {\n return trimmed.replace(/\\/+$/, '');\n }\n\n let protocol = url.protocol;\n let port = url.port;\n if (implicitScheme) {\n if (port === '443') {\n protocol = 'https:';\n port = '';\n } else if (port === '') {\n port = DEFAULT_PORT;\n }\n }\n\n const authority = `${url.hostname}${port !== '' ? `:${port}` : ''}`;\n return `${protocol}//${authority}${url.pathname}`.replace(/\\/+$/, '');\n}\n\n/**\n * Whether an environment-sourced credential (`OLLAMA_API_KEY`) may be sent to `baseUrl`.\n *\n * Only Ollama Cloud (`ollama.com` and subdomains) and loopback hosts qualify. An ambient\n * env var must not silently follow `baseUrl` to an arbitrary third-party host; callers who\n * want a key sent elsewhere pass `apiKey` (or per-endpoint `apiKey`) explicitly.\n */\nexport function isEnvApiKeyHost(baseUrl: string): boolean {\n let hostname: string;\n try {\n hostname = new URL(normalizeBaseUrl(baseUrl)).hostname.toLowerCase();\n } catch {\n return false;\n }\n if (hostname === 'ollama.com' || hostname.endsWith('.ollama.com')) return true;\n if (hostname === 'localhost' || hostname.endsWith('.localhost')) return true;\n if (hostname === '[::1]' || hostname === '::1' || hostname === '0.0.0.0') return true;\n return /^127(?:\\.\\d{1,3}){3}$/.test(hostname);\n}\n","/**\n * Configuration options and constants for OllamaClient.\n */\n\nimport type { Logger, RequestLifecycleHook } from './logger.js';\nimport type { Middleware } from './middleware.js';\nimport type { RetryConfig } from './transport/retry.js';\nimport { isEnvApiKeyHost, normalizeBaseUrl } from './transport/host.js';\nimport type { FetchLike } from './transport/http.js';\nimport type { EndpointRegistryOptions, OllamaEndpoint } from './providers/endpoint-registry.js';\n\nexport const DEFAULT_BASE_URL = 'http://localhost:11434';\nexport const DEFAULT_TIMEOUT_MS = 30_000;\n/**\n * Fixed host for Ollama's hosted web tools (`/api/web_search`, `/api/web_fetch`) — see\n * `OllamaClient.webSearch`/`webFetch`. These are an Ollama Cloud service reachable only\n * at this host, independent of any locally-configured `baseUrl`/`endpoints`.\n */\nexport const OLLAMA_CLOUD_BASE_URL = 'https://ollama.com';\n\n/**\n * Reads a process environment variable, if any. Guarded with `typeof process` rather\n * than importing `node:process` so this stays safe to call from Edge Runtimes (Cloudflare\n * Workers, Vercel Edge) where `process` doesn't exist — it just returns `undefined` there.\n */\nfunction readEnv(name: string): string | undefined {\n return typeof process !== 'undefined' && process.env ? process.env[name] : undefined;\n}\n\n/**\n * Resolves the default single-endpoint `baseUrl`, falling back to the `OLLAMA_HOST`\n * environment variable (the same one the official `ollama` CLI and client libraries\n * read) before `DEFAULT_BASE_URL`. Explicit `config.baseUrl` always wins.\n */\nexport function resolveBaseUrl(configBaseUrl?: string | undefined): string {\n return normalizeBaseUrl(configBaseUrl ?? readEnv('OLLAMA_HOST') ?? DEFAULT_BASE_URL);\n}\n\n/**\n * Resolves the default single-endpoint `apiKey`, falling back to the `OLLAMA_API_KEY`\n * environment variable before leaving it unset. Explicit `config.apiKey` always wins.\n */\nexport function resolveApiKey(configApiKey?: string | undefined): string | undefined {\n return configApiKey ?? readEnv('OLLAMA_API_KEY');\n}\n\n/**\n * Like {@link resolveApiKey}, but scoped to the endpoint it will be sent to. An explicit\n * `config.apiKey` is always honored. The `OLLAMA_API_KEY` fallback applies only when\n * `baseUrl` is Ollama Cloud or a loopback host, so an ambient env var is never forwarded\n * to an arbitrary third-party server.\n */\nexport function resolveEndpointApiKey(\n configApiKey: string | undefined,\n baseUrl: string,\n): string | undefined {\n if (configApiKey !== undefined) return configApiKey;\n const envKey = readEnv('OLLAMA_API_KEY');\n return envKey !== undefined && isEnvApiKeyHost(baseUrl) ? envKey : undefined;\n}\n\n/** One named credential for the `credentials`/`modelBindings` config shape. */\nexport interface OllamaCredentialConfig {\n readonly apiKey: string;\n /** Overrides `OllamaClientConfig.baseUrl` for requests made with this credential. */\n readonly baseUrl?: string | undefined;\n readonly headers?: Record<string, string> | undefined;\n}\n\n/**\n * Builds synthetic `OllamaEndpoint`s (named `credential:<id>`) from `config.credentials` +\n * `config.modelBindings` — an ergonomic, map-based alternative to writing out `endpoints`\n * with per-entry `models` allow-lists directly. Both shapes feed the same\n * `EndpointRegistry`/`executeWithFailover` routing engine; this is pure config sugar, not\n * a separate routing mechanism. Returns `[]` if `config.credentials` is unset.\n *\n * A model bound to one credential (`modelBindings: { \"minimax-m3\": \"coder\" }`) scopes that\n * credential to only that model, same as `OllamaEndpoint.models`. A model bound to several\n * credentials (`modelBindings: { \"gpt-oss:120b\": [\"key1\", \"key2\"] }`) makes ordinary\n * endpoint failover apply between them. `config.defaultCredential`, if set, is given a\n * lower priority than explicitly-bound credentials and no `models` restriction, so it acts\n * as a catch-all for any model without an explicit binding without ever pre-empting one\n * that has.\n */\nexport function resolveCredentialEndpoints(\n config: Pick<\n OllamaClientConfig,\n 'credentials' | 'modelBindings' | 'defaultCredential' | 'baseUrl'\n >,\n): readonly OllamaEndpoint[] {\n if (config.credentials === undefined) return [];\n\n const modelsByCredential = new Map<string, string[]>();\n for (const [model, bound] of Object.entries(config.modelBindings ?? {})) {\n for (const id of typeof bound === 'string' ? [bound] : bound) {\n if (!(id in config.credentials)) {\n throw new Error(\n `modelBindings[\"${model}\"] references unknown credential \"${id}\" — it isn't ` +\n `in \\`credentials\\`. Known credentials: ${Object.keys(config.credentials).join(', ') || '(none)'}.`,\n );\n }\n const list = modelsByCredential.get(id) ?? [];\n list.push(model);\n modelsByCredential.set(id, list);\n }\n }\n\n return Object.entries(config.credentials).map(([id, credential]) => {\n const isDefault = id === config.defaultCredential;\n const boundModels = isDefault ? undefined : modelsByCredential.get(id);\n return {\n name: `credential:${id}`,\n baseUrl: resolveBaseUrl(credential.baseUrl ?? config.baseUrl),\n apiKey: credential.apiKey,\n ...(credential.headers !== undefined ? { headers: credential.headers } : {}),\n ...(boundModels !== undefined ? { models: boundModels } : {}),\n priority: isDefault ? -1 : 0,\n };\n });\n}\n\nexport const DEFAULT_FAILOVER_CODES: readonly string[] = [\n 'network_error',\n 'timeout',\n 'server_error',\n // HTTP 503 — server queue saturated (OLLAMA_MAX_QUEUE exceeded).\n // The new OllamaOverloadedError specialization is retryable: the\n // queue will eventually drain, and a different candidate endpoint\n // may have capacity right now. Listed separately from\n // 'server_error' because OllamaOverloadedError extends\n // OllamaClientError (NOT OllamaServerError) — see\n // src/errors.ts for the rationale.\n 'overloaded',\n // HTTP 502 — cloud model could not be reached by the Ollama Cloud\n // proxy. Fail over to a different model/endpoint rather than\n // retrying the same one.\n 'bad_gateway',\n 'rate_limited',\n 'auth_error',\n // A candidate endpoint rejected the request pre-flight for a known-unsupported\n // capability (e.g. structured output against Ollama Cloud) — try the next candidate\n // rather than failing outright; see OllamaUnsupportedCapabilityError.\n 'unsupported_capability',\n];\n\nexport interface OllamaClientConfig {\n /**\n * Base URL of a single Ollama server. Ignored if `endpoints` is provided. Falls back to\n * the `OLLAMA_HOST` environment variable (when set and running under Node), then\n * `http://localhost:11434`.\n */\n readonly baseUrl?: string;\n /**\n * Bearer token sent as `Authorization: Bearer <apiKey>` for a single-endpoint setup.\n * Falls back to the `OLLAMA_API_KEY` environment variable (when set and running under\n * Node).\n */\n readonly apiKey?: string;\n /** Static headers merged into every request. */\n readonly headers?: Record<string, string>;\n /**\n * Multiple named endpoints for rotation and automatic failover. Each endpoint may\n * carry its own `apiKey` and, via `models`, be scoped to only the models that\n * credential is entitled to — see `OllamaEndpoint.models` for routing several\n * per-model Ollama Cloud API keys through a single client.\n */\n readonly endpoints?: readonly OllamaEndpoint[];\n /**\n * Named credentials, keyed by an id you choose — an ergonomic alternative to writing\n * out `endpoints` by hand for the common \"several Ollama Cloud API keys, each entitled\n * to different models\" shape. Combine with `modelBindings` to scope each credential to\n * the models it's authorized for; a credential with no binding (or set as\n * `defaultCredential`) is eligible for every model, same as an `OllamaEndpoint` with no\n * `models`. Merges additively with `endpoints` if both are given.\n */\n readonly credentials?: Readonly<Record<string, OllamaCredentialConfig>>;\n /**\n * Maps a model name to the `credentials` id (or ids, for several keys authorized for\n * the same model — ordinary failover applies between them) that may serve it. Has no\n * effect without `credentials`. Referencing an id not present in `credentials` throws\n * at construction time.\n */\n readonly modelBindings?: Readonly<Record<string, string | readonly string[]>>;\n /**\n * The `credentials` id to fall back to for a model with no entry in `modelBindings`.\n * Unset means such a model has no synthesized-from-`credentials` route — it still\n * routes normally through any plain `endpoints` entry without a `models` restriction.\n */\n readonly defaultCredential?: string | undefined;\n /**\n * Tuning options for the endpoint circuit breaker, and candidate selection ordering —\n * pass `{ strategy: 'round-robin' }` to spread requests across a pool of same-priority\n * endpoints/credentials (e.g. several unbound `credentials`) instead of always\n * preferring the first one, or `{ strategy: 'least-connections' }` to route each\n * request to whichever candidate currently has the fewest requests in flight (e.g.\n * several free-tier Ollama Cloud accounts, each capped at 1 concurrent request — this\n * deterministically spreads concurrent `Promise.all`-style calls one-per-account rather\n * than risking two landing on the same still-busy one), and `maxConcurrentPerEndpoint`\n * to cap that at an exact number and queue (rather than overrun a saturated candidate)\n * once every eligible one is at capacity — e.g. `{ strategy: 'least-connections',\n * maxConcurrentPerEndpoint: 1 }` for accounts that only allow one request at a time.\n * See `EndpointRegistryOptions`.\n */\n readonly endpointHealth?: EndpointRegistryOptions;\n /** Error codes that trigger failover to the next candidate endpoint. */\n readonly failoverOn?: readonly string[];\n /** Default per-request timeout in milliseconds (default 30_000ms). */\n readonly timeoutMs?: number;\n /** Retry configuration or retry count override. */\n readonly retries?: number | Partial<RetryConfig>;\n /** Custom fetch implementation (defaults to globalThis.fetch). */\n readonly fetch?: FetchLike;\n /** Request/Response middleware list. */\n readonly middleware?: readonly Middleware[];\n /** Structured logger. */\n readonly logger?: Logger;\n /** Enables console debug logger if true. */\n readonly debug?: boolean;\n /**\n * Default context window (`num_ctx`) applied to every `chat`/`generate`\n * request that doesn't set `options.num_ctx` itself. Injected as\n * `options.num_ctx` on the wire, making the effective window explicit\n * instead of leaving it to Ollama's server default (commonly 2048–4096,\n * model-dependent) — which **silently truncates** prompts that don't fit,\n * with no error and no warning. See `src/context-safety.ts`.\n */\n readonly defaultContextLength?: number;\n /**\n * Fraction of the effective context window at which the client warns that\n * a request's estimated prompt size is approaching truncation (default\n * `0.9` — see `DEFAULT_CONTEXT_WARNING_THRESHOLD`).\n */\n readonly contextWarningThreshold?: number;\n /**\n * What happens when the pre-flight context check (see\n * `src/context-safety.ts`) concludes a request will likely be truncated:\n * `'warn'` (default) logs a warning through the configured logger and sends\n * the request anyway; `'throw'` rejects the request client-side with\n * `OllamaClientError` before anything hits the wire. `'throw'` is the\n * safety-critical choice — use it when silent history truncation would\n * corrupt application behavior (e.g. long-context RAG, agents).\n */\n readonly onContextOverflow?: 'warn' | 'throw';\n /** Request lifecycle hook for telemetry/metrics. */\n readonly onLifecycleEvent?: RequestLifecycleHook;\n}\n","/**\n * Structured, typed error hierarchy for OllamaClient.\n */\n\nimport type { z } from 'zod';\n\nexport interface OllamaErrorRequestContext {\n readonly method?: string | undefined;\n readonly url?: string | undefined;\n readonly model?: string | undefined;\n}\n\nexport interface OllamaErrorResponseContext {\n readonly status?: number | undefined;\n readonly headers?: Record<string, string> | undefined;\n readonly body?: unknown;\n}\n\nexport interface OllamaClientErrorOptions extends ErrorOptions {\n readonly code: string;\n readonly status?: number | undefined;\n readonly retryable?: boolean | undefined;\n readonly request?: OllamaErrorRequestContext | undefined;\n readonly response?: OllamaErrorResponseContext | undefined;\n}\n\nexport class OllamaClientError extends Error {\n readonly code: string;\n readonly status?: number | undefined;\n readonly retryable: boolean;\n readonly request?: OllamaErrorRequestContext | undefined;\n readonly response?: OllamaErrorResponseContext | undefined;\n\n constructor(message: string, options: OllamaClientErrorOptions) {\n super(message, { cause: options.cause });\n this.name = this.constructor.name;\n this.code = options.code;\n this.status = options.status;\n this.retryable = options.retryable ?? false;\n this.request = options.request;\n this.response = options.response;\n }\n}\n\nexport class OllamaNetworkError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'network_error', retryable: true });\n }\n}\n\nexport class OllamaTimeoutError extends OllamaClientError {\n readonly timeoutMs?: number | undefined;\n constructor(\n message: string,\n options?:\n | (Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & { timeoutMs?: number | undefined })\n | undefined,\n ) {\n super(message, { ...options, code: 'timeout', retryable: true });\n this.timeoutMs = options?.timeoutMs;\n }\n}\n\nexport class OllamaAuthError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'auth_error', retryable: false });\n }\n}\n\nexport class OllamaNotFoundError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'not_found', retryable: false });\n }\n}\n\nexport class OllamaRateLimitError extends OllamaClientError {\n readonly retryAfterMs?: number | undefined;\n constructor(\n message: string,\n options?:\n | (Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n retryAfterMs?: number | undefined;\n })\n | undefined,\n ) {\n super(message, { ...options, code: 'rate_limited', retryable: true });\n this.retryAfterMs = options?.retryAfterMs;\n }\n}\n\n/**\n * Thrown client-side, before a network request is made, by `QuotaManager.assertCanProceed`\n * (see `src/quota.ts`) when issuing the request would exceed a configured usage budget for\n * one of its rolling windows. This is distinct from `OllamaRateLimitError`, which reflects\n * the server's own 429 response — Ollama Cloud does not expose account-level quota via the\n * API, so `QuotaManager` tracks usage against budgets the caller configures locally and\n * fails fast rather than waiting for the server to reject the request.\n */\nexport class OllamaQuotaExceededError extends OllamaClientError {\n readonly windowId: string;\n readonly resetAt: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n windowId: string;\n resetAt: number;\n },\n ) {\n super(message, { ...options, code: 'quota_exceeded', retryable: false });\n this.windowId = options.windowId;\n this.resetAt = options.resetAt;\n }\n}\n\nexport class OllamaServerError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'server_error', retryable: true });\n }\n}\n\n/**\n * Thrown when the Ollama server returns HTTP **503 Service Unavailable**,\n * indicating that the request queue is saturated (`OLLAMA_MAX_QUEUE`\n * exceeded, default 512 — see the FAQ).\n *\n * Semantically a specialization of {@link OllamaServerError} (503 is a\n * kind of 5xx server error), but extends {@link OllamaClientError}\n * directly to preserve the subclass-specific `code: 'overloaded'` —\n * `OllamaServerError`'s constructor unconditionally forces\n * `code: 'server_error'`. Callers wanting to catch any 5xx should\n * use `error.status >= 500 && error.status < 600` OR explicitly\n * list both `OllamaServerError` and `OllamaOverloadedError`/\n * `OllamaBadGatewayError` in their `instanceof` checks.\n *\n * `retryable` is `true` because the queue will eventually drain;\n * callers using {@link withRetry} will get automatic backoff.\n */\nexport class OllamaOverloadedError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable' | 'status'> | undefined,\n ) {\n super(message, { ...options, code: 'overloaded', status: 503, retryable: true });\n }\n}\n\n/**\n * Thrown when the Ollama server returns HTTP **502 Bad Gateway**,\n * indicating that a cloud model could not be reached by the\n * Ollama Cloud proxy. The model may be temporarily down, the\n * cloud provider may be experiencing an outage, or the model\n * may have been deprovisioned.\n *\n * Semantically a specialization of {@link OllamaServerError} (502 is a\n * kind of 5xx server error), but extends {@link OllamaClientError}\n * directly to preserve the subclass-specific `code: 'bad_gateway'` —\n * see {@link OllamaOverloadedError} for the rationale. Callers wanting\n * to catch any 5xx should use `error.status >= 500 && error.status < 600`\n * OR explicitly list both classes in their `instanceof` checks.\n *\n * `retryable` is `true` for transient cloud-provider outages.\n */\nexport class OllamaBadGatewayError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable' | 'status'> | undefined,\n ) {\n super(message, { ...options, code: 'bad_gateway', status: 502, retryable: true });\n }\n}\n\n/**\n * Thrown when the Ollama server emits an in-band error frame inside\n * an NDJSON stream (chat / generate / pull / push / create).\n *\n * Ollama streams start with HTTP 200 OK and chunked transfer encoding.\n * If an error occurs mid-generation (GPU OOM, driver crash, context\n * window overflow, model unload race, etc.), the server emits a final\n * JSON chunk of the form `{\"error\": \"...\"}` and closes the stream.\n * The HTTP status code never changes from 200, so HTTP-status-based\n * error detection misses these errors entirely — they would silently\n * bleed into the assistant's content stream as garbage tokens or\n * undefined-field accesses.\n *\n * `partialContent` carries whatever was accumulated before the error\n * frame, so callers can log/diagnose what the model produced before\n * failing. For chat streams this is the concatenated `message.content`;\n * for generate streams it's the concatenated `response`; for pull/push\n * streams it's empty (progress events don't accumulate content).\n *\n * See: https://github.com/ollama/ollama/blob/main/docs/api.md\n */\nexport class OllamaStreamError extends OllamaClientError {\n /** Content accumulated before the in-band error frame, or '' if none. */\n readonly partialContent: string;\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n partialContent?: string | undefined;\n },\n ) {\n super(message, { ...options, code: 'stream_error', retryable: false });\n this.partialContent = options?.partialContent ?? '';\n }\n}\n\nexport class OllamaAbortError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'aborted', retryable: false });\n }\n}\n\nexport class OllamaToolValidationError extends OllamaClientError {\n readonly toolName: string;\n readonly issues?: unknown;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & { toolName: string; issues?: unknown },\n ) {\n super(message, { ...options, code: 'tool_validation_error', retryable: false });\n this.toolName = options.toolName;\n this.issues = options.issues;\n }\n}\n\n/**\n * Thrown by `OllamaRuntime.invoke` when `validateRequests: true` is set and\n * the request body fails Zod validation against the operation's registered\n * schema. See ADR 0020 (runtime Zod validation).\n *\n * The error carries the original Zod issues so callers can inspect which\n * fields failed. No HTTP request is made when this error is thrown.\n */\nexport class OllamaRequestValidationError extends OllamaClientError {\n readonly operationId: string;\n readonly issues: readonly z.ZodIssue[];\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n operationId: string;\n issues: readonly z.ZodIssue[];\n },\n ) {\n super(message, { ...options, code: 'request_validation_error', retryable: false });\n this.operationId = options.operationId;\n this.issues = options.issues;\n }\n}\n\n/**\n * Thrown by `OllamaRuntime.invoke` BEFORE any HTTP request is made when the\n * serialized request body exceeds the operation's declared\n * `constraints.maxRequestBytes`. The Ollama server returns 413 for such\n * payloads; this client-side check fails fast so the round-trip is avoided.\n *\n * Wave 12 (P0 #5): the IR has carried `maxRequestBytes` for System One\n * (64 KiB) since v1.7.0, but the runtime never enforced it. This closes\n * that contract/runtime gap.\n */\nexport class OllamaRequestTooLargeError extends OllamaClientError {\n readonly operationId: string;\n readonly actualBytes: number;\n readonly maxBytes: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable' | 'status'> & {\n operationId: string;\n actualBytes: number;\n maxBytes: number;\n },\n ) {\n super(message, { ...options, code: 'request_too_large', retryable: false, status: 413 });\n this.operationId = options.operationId;\n this.actualBytes = options.actualBytes;\n this.maxBytes = options.maxBytes;\n }\n}\n\n/**\n * Thrown by `OllamaRuntime.invoke` AFTER the HTTP response is received\n * when `validateResponses: true` is set and the response body fails Zod\n * validation against the operation's registered response schema.\n *\n * Wave 13: the runtime previously never validated responses (see ADR\n * 0020). This opt-in error gives callers a way to detect wire-format\n * mismatches for operations where typed response semantics are critical\n * (e.g. System One). The error carries the original Zod issues so\n * callers can inspect which fields failed.\n */\nexport class OllamaResponseValidationError extends OllamaClientError {\n readonly operationId: string;\n readonly issues: readonly z.ZodIssue[];\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n operationId: string;\n issues: readonly z.ZodIssue[];\n },\n ) {\n super(message, { ...options, code: 'response_validation_error', retryable: false });\n this.operationId = options.operationId;\n this.issues = options.issues;\n }\n}\n\n/**\n * Thrown by `OllamaRuntime.invoke` BEFORE any HTTP request is made when the\n * operation declares `constraints.minOllamaVersion` and the runtime could\n * not obtain a server version to compare against (e.g. `enforceVersion:\n * 'strict'` was set and `/api/version` was unreachable). Distinct from\n * {@link OllamaGenericClientError} so callers can branch on the failure\n * mode rather than parsing the message.\n */\nexport class OllamaServerVersionUnknownError extends OllamaClientError {\n readonly operationId: string;\n readonly minRequiredVersion: string;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n operationId: string;\n minRequiredVersion: string;\n },\n ) {\n super(message, { ...options, code: 'server_version_unknown', retryable: false });\n this.operationId = options.operationId;\n this.minRequiredVersion = options.minRequiredVersion;\n }\n}\n\nexport class OllamaToolTimeoutError extends OllamaClientError {\n readonly toolName: string;\n readonly timeoutMs: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n toolName: string;\n timeoutMs: number;\n },\n ) {\n super(message, { ...options, code: 'tool_timeout', retryable: false });\n this.toolName = options.toolName;\n this.timeoutMs = options.timeoutMs;\n }\n}\n\n/**\n * Thrown client-side, before a network request is made, when a request asks for a\n * capability an endpoint is known not to support (e.g. structured output `format` against\n * an Ollama Cloud endpoint — see `ModelCapabilities.supportsStructuredOutputRequest` in\n * `src/capabilities/capabilities.ts`). Its `code` is included in `DEFAULT_FAILOVER_CODES`\n * by default, so in a multi-endpoint setup it causes failover to the next candidate rather\n * than failing outright — it only surfaces to the caller if every candidate is rejected.\n */\nexport class OllamaUnsupportedCapabilityError extends OllamaClientError {\n readonly capability: string;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & { capability: string },\n ) {\n super(message, { ...options, code: 'unsupported_capability', retryable: false });\n this.capability = options.capability;\n }\n}\n\n/**\n * Thrown client-side, before any network call, when `config.endpoints` uses\n * `OllamaEndpoint.models` to scope endpoints/credentials to specific models and the\n * requested `model` isn't in any configured endpoint's allow-list. This is a routing\n * misconfiguration, not a connectivity problem — the SDK deliberately does not \"probe\"\n * unauthorized endpoints to find one that happens to work (that would burn quota on keys\n * that were never entitled to the model and produce non-deterministic startup behavior).\n */\nexport class OllamaModelRoutingError extends OllamaClientError {\n readonly model: string;\n readonly availableModels: readonly string[];\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n model: string;\n availableModels: readonly string[];\n },\n ) {\n super(message, { ...options, code: 'model_routing_error', retryable: false });\n this.model = options.model;\n this.availableModels = options.availableModels;\n }\n}\n\n/**\n * Thrown before an agent tool loop starts when the selected model's /api/show metadata\n * does not advertise a capability required by the loop.\n */\nexport class OllamaIncompatibleModelError extends OllamaClientError {\n readonly model: string;\n readonly capability: string;\n readonly reportedCapabilities: readonly string[];\n\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n model: string;\n capability: string;\n reportedCapabilities: readonly string[];\n },\n ) {\n super(message, { ...options, code: 'incompatible_model', retryable: false });\n this.model = options.model;\n this.capability = options.capability;\n this.reportedCapabilities = options.reportedCapabilities;\n }\n}\nexport class OllamaAgentMaxToolCallsError extends OllamaClientError {\n readonly maxToolCalls: number;\n readonly toolCallsExecuted: number;\n\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n maxToolCalls: number;\n toolCallsExecuted: number;\n },\n ) {\n super(message, { ...options, code: 'agent_max_tool_calls_exceeded', retryable: false });\n this.maxToolCalls = options.maxToolCalls;\n this.toolCallsExecuted = options.toolCallsExecuted;\n }\n}\n\nexport class OllamaAgentMaxIterationsError extends OllamaClientError {\n readonly maxIterations: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & { maxIterations: number },\n ) {\n super(message, { ...options, code: 'agent_max_iterations_exceeded', retryable: false });\n this.maxIterations = options.maxIterations;\n }\n}\n\nexport class OllamaMcpError extends OllamaClientError {\n readonly mcpMethod:\n | 'listTools'\n | 'callTool'\n | 'tools/call'\n | 'tasks/get'\n | 'tasks/result'\n | 'tasks/cancel';\n readonly toolName?: string | undefined;\n readonly issues?: unknown;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n mcpMethod:\n | 'listTools'\n | 'callTool'\n | 'tools/call'\n | 'tasks/get'\n | 'tasks/result'\n | 'tasks/cancel';\n toolName?: string | undefined;\n issues?: unknown;\n },\n ) {\n super(message, { ...options, code: 'mcp_error', retryable: options.retryable ?? false });\n this.mcpMethod = options.mcpMethod;\n this.toolName = options.toolName;\n this.issues = options.issues;\n }\n}\n\nexport class OllamaSkillNotFoundError extends OllamaClientError {\n readonly skillName: string;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & { skillName: string },\n ) {\n super(message, { ...options, code: 'skill_not_found', retryable: false });\n this.skillName = options.skillName;\n }\n}\n\nexport class OllamaSkillInvalidError extends OllamaClientError {\n readonly skillName: string;\n readonly path?: string | undefined;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n skillName: string;\n path?: string | undefined;\n },\n ) {\n super(message, { ...options, code: 'skill_invalid', retryable: false });\n this.skillName = options.skillName;\n this.path = options.path;\n }\n}\n\nexport class OllamaGenericClientError extends OllamaClientError {\n constructor(message: string, options?: Omit<OllamaClientErrorOptions, 'code'> | undefined) {\n super(message, { ...options, code: 'client_error' });\n }\n}\n\nfunction isDomAbortError(error: unknown): error is DOMException {\n return (\n typeof DOMException !== 'undefined' &&\n error instanceof DOMException &&\n error.name === 'AbortError'\n );\n}\n\nfunction statusToError(\n status: number,\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'status'>,\n): OllamaClientError {\n if (status === 401 || status === 403) {\n return new OllamaAuthError(message, { ...options, status });\n }\n if (status === 404) {\n return new OllamaNotFoundError(message, { ...options, status });\n }\n if (status === 429) {\n return new OllamaRateLimitError(message, { ...options, status });\n }\n if (status === 502) {\n // Cloud model could not be reached. Distinct from generic 5xx so\n // callers running multi-model agents can branch on cloud-provider\n // failures specifically (fail over to a different model/endpoint\n // rather than blindly retrying the same one).\n return new OllamaBadGatewayError(message, { ...options });\n }\n if (status === 503) {\n // Queue saturation (OLLAMA_MAX_QUEUE exceeded). Retryable — the\n // queue will eventually drain. Distinct from generic 5xx so\n // callers running parallel swarms can branch on saturation.\n return new OllamaOverloadedError(message, { ...options });\n }\n if (status >= 500) {\n return new OllamaServerError(message, { ...options, status });\n }\n return new OllamaGenericClientError(message, { ...options, status });\n}\n\n/**\n * Maps arbitrary thrown exceptions into structured OllamaClientError instances.\n */\nexport function mapError(\n error: unknown,\n context: {\n request?: OllamaErrorRequestContext | undefined;\n response?: OllamaErrorResponseContext | undefined;\n } = {},\n): OllamaClientError {\n if (error instanceof OllamaClientError) {\n return error;\n }\n if (isDomAbortError(error)) {\n return new OllamaAbortError(error.message || 'Request was aborted', {\n cause: error,\n request: context.request,\n });\n }\n if (error instanceof TypeError) {\n return new OllamaNetworkError(error.message || 'Network request failed', {\n cause: error,\n request: context.request,\n });\n }\n if (context.response?.status !== undefined) {\n const message = error instanceof Error ? error.message : String(error);\n return statusToError(context.response.status, message, {\n cause: error,\n request: context.request,\n response: context.response,\n });\n }\n const message = error instanceof Error ? error.message : String(error);\n return new OllamaGenericClientError(message, {\n cause: error,\n request: context.request,\n response: context.response,\n });\n}\n","/**\n * Structured logger and request lifecycle interfaces.\n */\n\nexport interface LogFn {\n (message: string, context?: Record<string, unknown>): void;\n}\n\nexport interface Logger {\n readonly debug: LogFn;\n readonly info: LogFn;\n readonly warn: LogFn;\n readonly error: LogFn;\n}\n\nexport interface LifecycleStartEvent {\n readonly type: 'start';\n readonly requestId: string;\n readonly method: string;\n readonly url: string;\n readonly timestamp: number;\n}\n\nexport interface LifecycleSuccessEvent {\n readonly type: 'success';\n readonly requestId: string;\n readonly durationMs: number;\n readonly status: number;\n readonly timestamp: number;\n}\n\nexport interface LifecycleRetryEvent {\n readonly type: 'retry';\n readonly requestId: string;\n readonly attempt: number;\n readonly error: Error;\n readonly delayMs: number;\n readonly timestamp: number;\n}\n\nexport interface LifecycleErrorEvent {\n readonly type: 'error';\n readonly requestId: string;\n readonly durationMs: number;\n readonly error: Error;\n readonly timestamp: number;\n}\n\nexport type RequestLifecycleEvent =\n LifecycleStartEvent | LifecycleSuccessEvent | LifecycleRetryEvent | LifecycleErrorEvent;\n\nexport interface RequestLifecycleHook {\n (event: RequestLifecycleEvent): void;\n}\n\nexport const NOOP_LOGGER: Logger = {\n debug: () => undefined,\n info: () => undefined,\n warn: () => undefined,\n error: () => undefined,\n};\n\nexport function createConsoleLogger(prefix = '[@nemesis-oss/ollama-sdk]'): Logger {\n return {\n debug: (msg, ctx) => console.debug(`${prefix} ${msg}`, ctx ?? ''),\n info: (msg, ctx) => console.info(`${prefix} ${msg}`, ctx ?? ''),\n warn: (msg, ctx) => console.warn(`${prefix} ${msg}`, ctx ?? ''),\n error: (msg, ctx) => console.error(`${prefix} ${msg}`, ctx ?? ''),\n };\n}\n","/**\n * Multi-endpoint registry with priority routing and circuit breaker failover.\n */\n\nimport { OllamaAbortError } from '../errors.js';\n\nexport interface OllamaEndpoint {\n readonly name: string;\n readonly baseUrl: string;\n readonly apiKey?: string | undefined;\n readonly headers?: Record<string, string> | undefined;\n readonly priority?: number | undefined;\n /**\n * Restricts this endpoint/credential to a specific set of models — for the common case\n * of several Ollama Cloud API keys, each entitled to a different model. When set,\n * `EndpointRegistry.candidates(model)` only returns this endpoint for a request whose\n * `model` is in the list, so cross-endpoint failover never retries a request against a\n * credential that isn't authorized for the requested model. Omit (the default) to make\n * the endpoint eligible for every model, preserving prior behavior.\n */\n readonly models?: readonly string[] | undefined;\n}\n\nexport interface EndpointHealth {\n readonly endpoint: OllamaEndpoint;\n readonly failureCount: number;\n readonly lastFailureTimestamp?: number | undefined;\n readonly isCoolingDown: boolean;\n /** In-flight requests currently attempting this endpoint — see `acquire`/`release`. */\n readonly activeRequests: number;\n}\n\nexport interface EndpointRegistryOptions {\n readonly failureThreshold?: number | undefined;\n readonly cooldownMs?: number | undefined;\n readonly now?: (() => number) | undefined;\n /**\n * How candidates that share the same `priority` are ordered within `candidates()`.\n * `'priority'` (the default) keeps them in registration order, so the same candidate is\n * always tried first while it stays healthy. `'round-robin'` rotates each same-priority\n * group by one position per `candidates()` call — i.e. per `chat`/`generate`/etc. call —\n * so consecutive requests spread across a pool of interchangeable endpoints/credentials\n * instead of always preferring the first one (the common case: several Ollama Cloud keys\n * registered with no `models` restriction, meant to be used interchangeably). Endpoints\n * at different priorities are unaffected either way — a higher-priority one is still\n * always tried first, and failover to the rest of the group still applies if the\n * rotated-to-front candidate fails.\n *\n * `'least-connections'` instead orders each same-priority group by ascending in-flight\n * request count (tracked via `acquire`/`release`, ties broken by registration order),\n * so a request always prefers whichever candidate currently has the fewest requests\n * still in progress. Unlike `'round-robin'`, this remains correct under uneven or\n * overlapping request durations — e.g. several Ollama Cloud accounts each limited to 1\n * concurrent request: firing several requests at once (`Promise.all`) deterministically\n * lands each on a different account rather than risking two landing on the same\n * still-busy one, because `candidates()` and the subsequent `acquire()` for the chosen\n * candidate run synchronously with no `await` in between — JS's single-threaded\n * execution means no two concurrent calls can observe the same \"0 active\" snapshot for\n * the same candidate.\n */\n readonly strategy?: 'priority' | 'round-robin' | 'least-connections' | undefined;\n /**\n * Caps in-flight requests per endpoint (tracked via `acquire`/`release`). Unset (the\n * default) means no cap — candidates are never treated as saturated. When set, a\n * request whose every otherwise-eligible candidate is already at this cap waits\n * (`waitForCapacity`, FIFO per candidate) for one of them to free up, instead of being\n * sent to an already-saturated candidate. Pairs naturally with `strategy:\n * 'least-connections'` for a pool of accounts each limited to N concurrent requests —\n * e.g. `maxConcurrentPerEndpoint: 1` for several Ollama Cloud free-tier accounts, so\n * `N + 1` concurrent calls against `N` such accounts run `N` immediately and queue the\n * rest, rather than the `(N+1)`th overrunning whichever account looks \"least busy\" at\n * that instant. Waiting is bounded by the request's own timeout/`AbortSignal`, same as\n * any other in-flight request — it never blocks indefinitely on its own.\n */\n readonly maxConcurrentPerEndpoint?: number | undefined;\n}\n\ninterface CapacityWaiter {\n readonly names: readonly string[];\n readonly resolve: () => void;\n cleanup: () => void;\n}\n\nexport class EndpointRegistry {\n private readonly endpoints: readonly OllamaEndpoint[];\n private readonly failureCounts = new Map<string, number>();\n private readonly lastFailures = new Map<string, number>();\n private readonly failureThreshold: number;\n private readonly cooldownMs: number;\n private readonly now: () => number;\n private readonly strategy: 'priority' | 'round-robin' | 'least-connections';\n private roundRobinCounter = 0;\n private readonly activeCounts = new Map<string, number>();\n private readonly maxConcurrentPerEndpoint: number | undefined;\n private readonly waiters: CapacityWaiter[] = [];\n\n constructor(endpoints: readonly OllamaEndpoint[], options: EndpointRegistryOptions = {}) {\n this.endpoints =\n endpoints.length > 0 ? endpoints : [{ name: 'default', baseUrl: 'http://localhost:11434' }];\n this.failureThreshold = options.failureThreshold ?? 3;\n this.cooldownMs = options.cooldownMs ?? 30_000;\n this.now = options.now ?? Date.now;\n this.strategy = options.strategy ?? 'priority';\n this.maxConcurrentPerEndpoint = options.maxConcurrentPerEndpoint;\n }\n\n /**\n * Marks one more request as in-flight against `name`. Callers (`OllamaClient`) must\n * pair every `acquire` with a `release` once that attempt finishes, success or not —\n * see `OllamaClient.executeWithFailover`. Only affects candidate ordering when\n * `strategy` is `'least-connections'`; harmless (just bookkeeping) otherwise, and\n * always reflected in `status()`'s `activeRequests`.\n */\n acquire(name: string): void {\n this.activeCounts.set(name, (this.activeCounts.get(name) ?? 0) + 1);\n }\n\n /** Releases one in-flight request marked via `acquire`, waking one waiter for `name` if any. */\n release(name: string): void {\n const next = (this.activeCounts.get(name) ?? 0) - 1;\n if (next <= 0) {\n this.activeCounts.delete(name);\n } else {\n this.activeCounts.set(name, next);\n }\n const idx = this.waiters.findIndex((w) => w.names.includes(name));\n if (idx !== -1) {\n const [waiter] = this.waiters.splice(idx, 1);\n waiter?.cleanup();\n waiter?.resolve();\n }\n }\n\n /**\n * `candidates` filtered down to those currently under `maxConcurrentPerEndpoint` (all\n * of them, unchanged, if that option is unset).\n */\n filterWithCapacity(candidates: readonly OllamaEndpoint[]): OllamaEndpoint[] {\n const cap = this.maxConcurrentPerEndpoint;\n if (cap === undefined) return [...candidates];\n return candidates.filter((ep) => (this.activeCounts.get(ep.name) ?? 0) < cap);\n }\n\n /**\n * Resolves once any endpoint named in `names` has spare capacity under\n * `maxConcurrentPerEndpoint` (a no-op resolve if that option is unset, or if one\n * already does). Otherwise queues (FIFO per name) until a matching `release()` frees a\n * slot, or rejects if `signal` aborts first — mirroring whatever aborted it\n * (`OllamaTimeoutError`/the caller's own abort reason) so callers see the same error\n * shape as any other in-flight request that times out or is cancelled. FIFO order is\n * best-effort (a newly-arriving request can still win a race for a slot that just\n * freed) — the capacity cap itself, not fairness, is the guarantee this exists for.\n */\n waitForCapacity(names: readonly string[], signal?: AbortSignal): Promise<void> {\n const cap = this.maxConcurrentPerEndpoint;\n if (cap === undefined) return Promise.resolve();\n if (names.some((n) => (this.activeCounts.get(n) ?? 0) < cap)) return Promise.resolve();\n\n return new Promise<void>((resolve, reject) => {\n const waiter: CapacityWaiter = { names, resolve, cleanup: () => undefined };\n const onAbort = (): void => {\n const idx = this.waiters.indexOf(waiter);\n if (idx !== -1) this.waiters.splice(idx, 1);\n reject(\n signal?.reason instanceof Error\n ? signal.reason\n : new OllamaAbortError('Aborted while waiting for endpoint capacity'),\n );\n };\n if (signal !== undefined) {\n if (signal.aborted) {\n onAbort();\n return;\n }\n signal.addEventListener('abort', onAbort, { once: true });\n waiter.cleanup = () => signal.removeEventListener('abort', onAbort);\n }\n this.waiters.push(waiter);\n });\n }\n\n /**\n * Rotates each same-`priority` group in `sorted` (already sorted highest-priority-first)\n * by one position further per call, wrapping around within the group. Priority tiers\n * themselves are never reordered — only candidates that were already tied.\n */\n private applyRoundRobin(sorted: readonly OllamaEndpoint[]): OllamaEndpoint[] {\n const offset = this.roundRobinCounter++;\n const result: OllamaEndpoint[] = [];\n let i = 0;\n while (i < sorted.length) {\n const priority = sorted[i]?.priority ?? 0;\n let j = i + 1;\n while (j < sorted.length && (sorted[j]?.priority ?? 0) === priority) j++;\n const tier = sorted.slice(i, j);\n const rotation = offset % tier.length;\n result.push(...tier.slice(rotation), ...tier.slice(0, rotation));\n i = j;\n }\n return result;\n }\n\n /**\n * Reorders each same-`priority` group in `sorted` by ascending in-flight request count\n * (from `acquire`/`release`); a stable sort, so candidates tied on active count keep\n * their relative (priority-then-registration) order. Priority tiers themselves are\n * never reordered.\n */\n private applyLeastConnections(sorted: readonly OllamaEndpoint[]): OllamaEndpoint[] {\n const result: OllamaEndpoint[] = [];\n let i = 0;\n while (i < sorted.length) {\n const priority = sorted[i]?.priority ?? 0;\n let j = i + 1;\n while (j < sorted.length && (sorted[j]?.priority ?? 0) === priority) j++;\n const tier = [...sorted.slice(i, j)].sort(\n (a, b) => (this.activeCounts.get(a.name) ?? 0) - (this.activeCounts.get(b.name) ?? 0),\n );\n result.push(...tier);\n i = j;\n }\n return result;\n }\n\n /**\n * Endpoints eligible for `model`, sorted healthy-first-by-priority (falling back to\n * soonest-to-recover if every eligible endpoint is cooling down); same-priority\n * candidates are further reordered per `options.strategy` (see\n * `EndpointRegistryOptions.strategy`). When `model` is given, endpoints whose `models`\n * allow-list doesn't include it are excluded entirely — see `OllamaEndpoint.models`.\n * Omit `model` to consider every configured endpoint, regardless of any `models`\n * restriction (used for non-model-scoped operations).\n */\n candidates(model?: string): OllamaEndpoint[] {\n const currentTime = this.now();\n const scoped =\n model === undefined\n ? this.endpoints\n : this.endpoints.filter((ep) => ep.models === undefined || ep.models.includes(model));\n const healthy: OllamaEndpoint[] = [];\n const coolingDown: Array<{ endpoint: OllamaEndpoint; recoveredAt: number }> = [];\n\n for (const ep of scoped) {\n const failures = this.failureCounts.get(ep.name) ?? 0;\n const lastFail = this.lastFailures.get(ep.name) ?? 0;\n const isCooling =\n failures >= this.failureThreshold && currentTime - lastFail < this.cooldownMs;\n\n if (!isCooling) {\n healthy.push(ep);\n } else {\n coolingDown.push({ endpoint: ep, recoveredAt: lastFail + this.cooldownMs });\n }\n }\n\n if (healthy.length > 0) {\n const sorted = healthy.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));\n if (this.strategy === 'round-robin') return this.applyRoundRobin(sorted);\n if (this.strategy === 'least-connections') return this.applyLeastConnections(sorted);\n return sorted;\n }\n\n // Fail-open: sort by soonest-to-recover\n return coolingDown.sort((a, b) => a.recoveredAt - b.recoveredAt).map((c) => c.endpoint);\n }\n\n reportSuccess(name: string): void {\n this.failureCounts.delete(name);\n this.lastFailures.delete(name);\n }\n\n reportFailure(name: string): void {\n const current = (this.failureCounts.get(name) ?? 0) + 1;\n this.failureCounts.set(name, current);\n this.lastFailures.set(name, this.now());\n }\n\n list(): readonly OllamaEndpoint[] {\n return this.endpoints;\n }\n\n /** True if any configured endpoint restricts itself to a `models` allow-list. */\n hasModelScopedEndpoints(): boolean {\n return this.endpoints.some((ep) => ep.models !== undefined);\n }\n\n status(): EndpointHealth[] {\n const currentTime = this.now();\n return this.endpoints.map((ep) => {\n const failures = this.failureCounts.get(ep.name) ?? 0;\n const lastFail = this.lastFailures.get(ep.name);\n const isCoolingDown =\n failures >= this.failureThreshold &&\n lastFail !== undefined &&\n currentTime - lastFail < this.cooldownMs;\n\n return {\n endpoint: ep,\n failureCount: failures,\n ...(lastFail !== undefined ? { lastFailureTimestamp: lastFail } : {}),\n isCoolingDown,\n activeRequests: this.activeCounts.get(ep.name) ?? 0,\n };\n });\n }\n}\n","/**\n * Request/response middleware pipeline.\n */\n\nexport interface RequestContext {\n readonly url: string;\n readonly method: string;\n readonly headers: Record<string, string>;\n readonly body?: unknown;\n readonly signal?: AbortSignal;\n}\n\nexport interface ResponseContext {\n readonly status: number;\n readonly headers: Record<string, string>;\n readonly body: unknown;\n}\n\nexport type NextFunction = () => Promise<ResponseContext>;\n\nexport interface MiddlewareContext {\n readonly request: RequestContext;\n readonly next: NextFunction;\n}\n\nexport interface Middleware {\n (ctx: MiddlewareContext): Promise<ResponseContext>;\n}\n\nexport function composeMiddleware(\n middlewares: readonly Middleware[],\n finalHandler: (req: RequestContext) => Promise<ResponseContext>,\n): (req: RequestContext) => Promise<ResponseContext> {\n return function runPipeline(initialRequest: RequestContext): Promise<ResponseContext> {\n let index = -1;\n\n function dispatch(i: number, currentRequest: RequestContext): Promise<ResponseContext> {\n if (i <= index) {\n return Promise.reject(new Error('next() called multiple times in middleware'));\n }\n index = i;\n const fn = middlewares[i];\n if (i === middlewares.length || !fn) {\n return finalHandler(currentRequest);\n }\n return fn({\n request: currentRequest,\n next: () => dispatch(i + 1, currentRequest),\n });\n }\n\n return dispatch(0, initialRequest);\n };\n}\n","/**\n * Universal vision asset resolution — the SDK-side half of Ollama's documented\n * vision ingestion convention.\n *\n * Ollama's REST API strictly requires raw base64 strings in the `images`\n * arrays of `/api/chat` and `/api/generate` (no `data:image/...;base64,` URI\n * prefixes). The official SDKs, however, are expected to accept polymorphic\n * image sources — local file paths, web URLs, or raw byte buffers — and\n * normalize them to that wire format on the caller's behalf. This module is\n * that normalization layer for this SDK.\n *\n * Resolution order for `string` inputs:\n *\n * 1. `data:image/...;base64,` data URIs — the header is stripped, the\n * payload passed through.\n * 2. `http://` / `https://` URLs — fetched with the platform's global\n * `fetch`, then base64-encoded.\n * 3. Strings with a known image file extension (`.png`, `.jpg`, `.webp`,\n * ...) — treated as a local file path and read via a *dynamically\n * imported* `node:fs` (Node.js only). If the read fails, the string is\n * passed through unchanged (it may have been a base64 payload that\n * happened to end in an image-like suffix — rare, but the safe\n * fallback). In browsers/edge runtimes, where `node:fs` does not exist,\n * a path-shaped string throws a descriptive error instead of silently\n * shipping garbage to the server.\n * 4. Anything else — assumed to already be raw base64 and passed through.\n *\n * `Buffer` and `Uint8Array` inputs are base64-encoded via the runtime's\n * universal base64 primitive (`Buffer` on Node, `btoa` on the web), matching\n * {@link encodeImage}.\n *\n * Everything here is dependency-free and safe to import from the core client\n * bundle: the `node:fs` import is dynamic and guarded, so browser/edge builds\n * never pull it in (see ADR 0006 — Edge Runtime CI).\n */\n\nimport { OllamaClientError } from './errors.js';\n\n/**\n * Polymorphic vision input accepted anywhere this SDK takes an `images` entry.\n *\n * - `string` — a raw base64 payload, a `data:image/...;base64,` data URI, an\n * `http(s)://` URL, or (on Node.js) a local file path.\n * - `Buffer` / `Uint8Array` — raw image bytes, base64-encoded automatically.\n */\nexport type VisionInput = string | Buffer | Uint8Array;\n\n/** Data-URI prefix, e.g. `data:image/png;base64,`. Case-insensitive on the MIME type. */\nconst DATA_URI_PATTERN = /^data:image\\/[a-z0-9.+-]+;base64,/i;\n\n/**\n * Known image file extensions. A string ending in one of these (and only\n * these — a plain base64 payload cannot contain a `.` before the suffix) is\n * treated as a local file path candidate. This is deliberately narrower than\n * \"contains a slash\", because `/` is a legal base64 alphabet character and a\n * naive contains-slash heuristic would misfire on ~any longer payload.\n */\nconst IMAGE_FILE_EXTENSION_PATTERN = /\\.(png|jpe?g|webp|gif|bmp|tiff?|avif)$/i;\n\n/**\n * Cheap synchronous check: does this string input require async resolution\n * (data-URI stripping, URL fetch, or file read), or is it already wire-ready\n * base64? Used to keep the hot path in `withEncodedImages` allocation-free\n * when callers pass pre-encoded strings (the overwhelmingly common case).\n */\nexport function imageStringNeedsResolution(input: string): boolean {\n return (\n DATA_URI_PATTERN.test(input) ||\n input.startsWith('http://') ||\n input.startsWith('https://') ||\n IMAGE_FILE_EXTENSION_PATTERN.test(input)\n );\n}\n\n/** True when the current runtime has Node.js `fs` available (Node/Bun, not browser/edge). */\nfunction hasNodeFs(): boolean {\n return (\n typeof process !== 'undefined' &&\n process !== null &&\n typeof (process as { versions?: { node?: string } }).versions?.node === 'string'\n );\n}\n\n/**\n * `node:fs` module specifier, kept behind a variable so bundlers can't see\n * it as a literal — esbuild's browser/edge platform (and Cloudflare's and\n * Vercel's own build pipelines) refuse to resolve Node builtins at build\n * time. The dynamic import only ever executes at call time, and only after a\n * `hasNodeFs()` guard, so edge bundles carry it as dead code.\n */\nconst NODE_FS_MODULE = 'node:fs';\n\n/**\n * Reads a local file as base64. The `node:fs` import is dynamic so that\n * bundlers exclude it from browser/edge builds; the function is only ever\n * called after a `hasNodeFs()` guard.\n */\nasync function readFileAsBase64(path: string): Promise<string> {\n const { promises: fs } = (await import(NODE_FS_MODULE)) as typeof import('node:fs');\n const data = await fs.readFile(path);\n return data.toString('base64');\n}\n\nasync function fetchUrlAsBase64(url: string, signal?: AbortSignal | undefined): Promise<string> {\n const res = await fetch(url, signal !== undefined ? { signal } : undefined);\n if (!res.ok) {\n throw new OllamaClientError(\n `Failed to fetch image from URL \"${url}\": HTTP ${res.status} ${res.statusText}.`,\n { code: 'image_fetch_failed' },\n );\n }\n const arrayBuffer = await res.arrayBuffer();\n return encodeBytesBase64(new Uint8Array(arrayBuffer));\n}\n\n/** Base64-encodes bytes using whichever universal primitive the runtime exposes. */\nfunction encodeBytesBase64(bytes: Uint8Array): string {\n const bufferCtor = (\n globalThis as { Buffer?: { from(data: Uint8Array): { toString(encoding: string): string } } }\n ).Buffer;\n if (bufferCtor !== undefined) return bufferCtor.from(bytes).toString('base64');\n\n // Web/edge path — chunked so large images don't blow the engine's\n // max call-stack/argument-count limit on String.fromCharCode.\n const CHUNK_SIZE = 0x8000;\n let binary = '';\n for (let i = 0; i < bytes.length; i += CHUNK_SIZE) {\n binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK_SIZE));\n }\n return btoa(binary);\n}\n\n/**\n * Resolves any supported vision input into the raw base64 string Ollama's\n * REST API expects — no data-URI headers, no URL/path indirection left\n * behind. See the module doc for the full resolution order.\n *\n * @throws {OllamaClientError} if a URL fetch fails (non-2xx), or if a\n * path-shaped string is passed in a runtime without `node:fs` (browser/edge)\n * — in that environment, read the file yourself and pass the bytes.\n */\nexport async function resolveImageInput(\n input: VisionInput,\n signal?: AbortSignal | undefined,\n): Promise<string> {\n if (typeof input !== 'string') {\n return encodeBytesBase64(input instanceof Uint8Array ? input : new Uint8Array(input));\n }\n\n // 1. Data URI: strip the `data:image/...;base64,` header.\n if (DATA_URI_PATTERN.test(input)) {\n return input.replace(DATA_URI_PATTERN, '').trim();\n }\n\n // 2. HTTP(S) URL: fetch and encode.\n if (input.startsWith('http://') || input.startsWith('https://')) {\n return fetchUrlAsBase64(input, signal);\n }\n\n // 3. Local file path: read and encode (Node.js only — dynamic import).\n if (IMAGE_FILE_EXTENSION_PATTERN.test(input)) {\n if (!hasNodeFs()) {\n throw new OllamaClientError(\n `Vision input \"${input}\" looks like a local file path, but this runtime has no ` +\n `Node.js \\`fs\\` module (browser/edge). Read the file into bytes yourself and pass ` +\n `the \\`Uint8Array\\`, or pass a base64 string / data URI / http(s) URL instead.`,\n { code: 'vision_path_unsupported_runtime' },\n );\n }\n try {\n return await readFileAsBase64(input);\n } catch {\n // Fall through: the string may have been a base64 payload that merely\n // ended in an image-like suffix. Pass it through untouched (digest's\n // documented graceful fallback) — if it really was a path, the server\n // will reject the invalid base64 with a clear error.\n return input;\n }\n }\n\n // 4. Anything else: assume raw base64.\n return input.trim();\n}\n\n/**\n * Resolves a whole `images` array in parallel. Returns the same array\n * reference (not a copy) when every entry is already wire-ready — the common\n * pre-encoded case — so callers on the hot path pay zero allocation cost.\n */\nexport async function resolveImages(\n images: readonly VisionInput[] | undefined,\n signal?: AbortSignal | undefined,\n): Promise<readonly string[] | undefined> {\n if (images === undefined) return undefined;\n if (images.every((image) => typeof image === 'string' && !imageStringNeedsResolution(image))) {\n return images as readonly string[];\n }\n return Promise.all(images.map((image) => resolveImageInput(image, signal)));\n}\n","/**\n * Cross-runtime helpers with no Node.js API dependency, so they stay safe to import from\n * the core client bundle (see ADR 0006 — Edge Runtime CI).\n */\n\nimport { imageStringNeedsResolution, resolveImages, type VisionInput } from './vision.js';\n\n/**\n * Encodes an image to a base64 string, matching the wire format Ollama's `/api/chat` and\n * `/api/generate` `images` arrays expect.\n *\n * - A `string` is assumed to already be base64-encoded and is returned unchanged. For\n * data URIs, URLs, and local file paths use {@link resolveImageInput}, which this SDK's\n * request pipeline applies automatically (see {@link withEncodedImages}).\n * - A `Uint8Array` (or Node `Buffer`) is base64-encoded using whichever universal primitive\n * the runtime exposes: `Buffer` on Node.js, `btoa` on browsers/Edge runtimes. Chunked so it\n * doesn't blow the engine's max call-stack/argument-count limits on large images.\n */\nexport async function encodeImage(image: VisionInput): Promise<string> {\n if (typeof image === 'string') return image;\n\n const bufferCtor = (\n globalThis as { Buffer?: { from(data: Uint8Array): { toString(encoding: string): string } } }\n ).Buffer;\n if (bufferCtor !== undefined) return bufferCtor.from(image).toString('base64');\n\n const CHUNK_SIZE = 0x8000;\n let binary = '';\n for (let i = 0; i < image.length; i += CHUNK_SIZE) {\n binary += String.fromCharCode(...image.subarray(i, i + CHUNK_SIZE));\n }\n return btoa(binary);\n}\n\nasync function encodeImages(\n images: readonly VisionInput[],\n signal?: AbortSignal | undefined,\n): Promise<readonly string[]> {\n return resolveImages(images, signal) as Promise<readonly string[]>;\n}\n\n/**\n * Normalizes `req.images` to wire-ready raw base64 strings, resolving every polymorphic\n * {@link VisionInput} — data URIs (header stripped), `http(s)://` URLs (fetched), local\n * file paths (read via dynamically-imported `node:fs`, Node.js only), and raw\n * `Buffer`/`Uint8Array` bytes (base64-encoded). Returns `req` **unchanged (same reference)**\n * when every entry is already a plain base64 string (the common case), so the request\n * pipeline stays allocation-free for pre-encoded callers.\n */\nexport async function withEncodedImages<T extends { images?: readonly VisionInput[] | undefined }>(\n req: T,\n signal?: AbortSignal | undefined,\n): Promise<T> {\n const needsResolution = req.images?.some(\n (image) => typeof image !== 'string' || imageStringNeedsResolution(image),\n );\n if (!needsResolution) return req;\n return { ...req, images: await encodeImages(req.images ?? [], signal) };\n}\n\n/**\n * Applies {@link withEncodedImages} to each message's `images` array. Returns `messages`\n * unchanged (same reference) if no message carries a non-base64-ready image.\n */\nexport async function withEncodedMessageImages<\n T extends { images?: readonly VisionInput[] | undefined },\n>(messages: readonly T[], signal?: AbortSignal | undefined): Promise<readonly T[]> {\n const needsResolution = messages.some((message) =>\n message.images?.some((image) => typeof image !== 'string' || imageStringNeedsResolution(image)),\n );\n if (!needsResolution) return messages;\n return Promise.all(messages.map((message) => withEncodedImages(message, signal)));\n}\n\n// ─── Disposable helpers (TS 5.2+ `using` declarations) ──────────────────\n//\n// These wrappers turn cleanup operations into `Disposable` / `AsyncDisposable`\n// values so callers can use `using` / `await using` declarations instead of\n// try/finally blocks. This eliminates the \"forgot to clean up in the finally\n// block\" bug class for timer, reader, and span lifecycles.\n\n/** Wraps a `setTimeout` handle so `clearTimeout` runs at scope exit. */\nexport function disposableTimer(timer: ReturnType<typeof setTimeout>): Disposable {\n return {\n [Symbol.dispose]() {\n clearTimeout(timer);\n },\n };\n}\n\n/** Wraps a `ReadableStreamDefaultReader` so `cancel()` + `releaseLock()` run at scope exit. */\nexport function disposableReader<T>(reader: ReadableStreamDefaultReader<T>): AsyncDisposable {\n return {\n async [Symbol.asyncDispose]() {\n try {\n await reader.cancel();\n } catch {\n /* stream may already be closed */\n }\n reader.releaseLock();\n },\n };\n}\n\n/** Wraps an OpenTelemetry span so `span.end()` runs at scope exit. */\nexport function disposableSpan(span: { end(): void }): Disposable {\n return {\n [Symbol.dispose]() {\n span.end();\n },\n };\n}\n","/**\n * NDJSON (newline-delimited JSON) stream reader for native fetch Response bodies.\n *\n * Ollama's streaming endpoints (chat / generate / pull / push / create)\n * emit newline-delimited JSON objects. Each line is a complete JSON\n * document. The transport is chunked HTTP with status 200 OK — meaning\n * the HTTP status never changes mid-stream even when the server\n * encounters an error after generation has started.\n *\n * Instead, Ollama emits a final JSON frame of the form\n * `{\"error\": \"...\"}` and closes the stream. This reader detects such\n * in-band error frames and throws {@link OllamaStreamError} immediately,\n * so callers don't see the error message bleed into the assistant's\n * content stream as garbage tokens.\n */\n\nimport { OllamaGenericClientError, OllamaStreamError } from '../errors.js';\nimport { disposableReader } from '../utils.js';\n\n/**\n * A frame carrying an in-band stream error. Ollama emits this shape as\n * the final chunk of a stream when generation fails mid-flight (GPU\n * OOM, driver crash, context window overflow, model unload race, etc).\n *\n * Note that not every chunk with an `error` field is an error frame —\n * some valid Ollama response shapes carry `error` as a property name\n * for unrelated purposes (none documented in the public API, but the\n * generated schema set has a few). We only treat a frame as an\n * in-band error when it has an `error` field that is a non-empty\n * string AND no other top-level fields that would identify it as a\n * valid response chunk (e.g. `model`, `response`, `message`, `status`,\n * `done`).\n */\ninterface InBandErrorFrame {\n readonly error: string;\n}\n\n/**\n * Returns `true` if `value` looks like an Ollama in-band stream error\n * frame — i.e. it has a non-empty string `error` field and none of\n * the markers that would identify it as a valid response chunk.\n *\n * The valid-chunk markers (`model`, `response`, `message`, `status`,\n * `done`) cover every documented Ollama streaming endpoint: chat\n * chunks carry `message` and `done`; generate chunks carry `response`\n * and `done`; pull/push/create chunks carry `status`; all chunks\n * carry `model` once the model has loaded. A bare `{\"error\": \"...\"}`\n * frame with none of these is unambiguously an in-band error.\n */\nfunction isInBandErrorFrame(value: unknown): value is InBandErrorFrame {\n if (typeof value !== 'object' || value === null) return false;\n const record = value as Record<string, unknown>;\n if (typeof record.error !== 'string' || record.error.length === 0) return false;\n // Reject frames that look like valid response chunks which happen to\n // also carry an `error` field (none documented, but defensive).\n return (\n !('model' in record) &&\n !('response' in record) &&\n !('message' in record) &&\n !('status' in record) &&\n !('done' in record)\n );\n}\n\n/**\n * Parses a byte stream from fetch body into an async generator of typed JSON chunks.\n *\n * Throws {@link OllamaStreamError} immediately upon encountering an\n * in-band `{\"error\": \"...\"}` frame. The thrown error carries an empty\n * `partialContent` (this low-level parser does not accumulate content;\n * the higher-level aggregator in `streaming/normalize.ts` is the\n * right place to surface partial content if needed).\n */\nexport async function* parseNdjsonStream<T>(\n stream: ReadableStream<Uint8Array>,\n): AsyncGenerator<T, void, undefined> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n await using _reader = disposableReader(reader);\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n // Keep the last partial line in buffer\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n let json: unknown;\n try {\n json = JSON.parse(trimmed);\n } catch (err) {\n throw new OllamaGenericClientError(`Failed to parse stream JSON chunk: ${trimmed}`, {\n cause: err,\n });\n }\n\n // In-band error trapping: detect `{\"error\": \"...\"}` frames\n // before they reach the typed-chunk consumer. This is the\n // critical fix for the \"HTTP 200 OK + mid-stream error\" case\n // documented in Ollama's errors.md — without it, the error\n // message would either bleed into content or hit undefined-field\n // accesses downstream.\n if (isInBandErrorFrame(json)) {\n throw new OllamaStreamError((json as InBandErrorFrame).error);\n }\n\n yield json as T;\n }\n }\n\n if (buffer.trim()) {\n const trimmed = buffer.trim();\n let json: unknown;\n try {\n json = JSON.parse(trimmed);\n } catch (err) {\n throw new OllamaGenericClientError(`Failed to parse stream JSON chunk: ${trimmed}`, {\n cause: err,\n });\n }\n if (isInBandErrorFrame(json)) {\n throw new OllamaStreamError((json as InBandErrorFrame).error);\n }\n yield json as T;\n }\n // reader.cancel() + reader.releaseLock() called automatically via `await using _reader`\n}\n","/**\n * Server-Sent Events (SSE) parser for OpenAI/Anthropic-compatible streaming endpoints.\n *\n * Implements standard event-stream field rules without coupling the parser to\n * any provider-specific event schema.\n */\n\nimport { disposableReader } from '../utils.js';\n\nexport interface SseEvent {\n /** Event type; omitted when the server emitted no explicit event field. */\n readonly event?: string | undefined;\n /** Event data with consecutive data fields joined by a newline. */\n readonly data: string;\n /** Last event id associated with this dispatch, when present. */\n readonly id?: string | undefined;\n /** Reconnection delay requested by the server, in milliseconds, when valid. */\n readonly retry?: number | undefined;\n}\n\nfunction dispatch(\n event: string | undefined,\n data: string[],\n id: string | undefined,\n retry: number | undefined,\n): SseEvent | undefined {\n if (data.length === 0) return undefined;\n\n const joined = data.join('\\n');\n return {\n ...(event !== undefined ? { event } : {}),\n data: joined.endsWith('\\n') ? joined.slice(0, -1) : joined,\n ...(id !== undefined ? { id } : {}),\n ...(retry !== undefined ? { retry } : {}),\n };\n}\n\n/**\n * Parses an SSE byte stream into discrete events.\n *\n * Supports CRLF, CR, and LF line endings; comments; repeated data fields;\n * event/id/retry fields; UTF-8 chunks split across arbitrary byte boundaries;\n * and a terminal event without a trailing blank line.\n */\nexport async function* parseSseStream(\n stream: ReadableStream<Uint8Array>,\n): AsyncGenerator<SseEvent, void, undefined> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n\n let buffer = '';\n let eventType: string | undefined;\n let data: string[] = [];\n let lastEventId: string | undefined;\n let retry: number | undefined;\n\n const processLine = (line: string): SseEvent | undefined => {\n if (line.length === 0) {\n const event = dispatch(eventType, data, lastEventId, retry);\n eventType = undefined;\n data = [];\n retry = undefined;\n return event;\n }\n\n if (line.startsWith(':')) return undefined;\n\n const separator = line.indexOf(':');\n const field = separator === -1 ? line : line.slice(0, separator);\n let value = separator === -1 ? '' : line.slice(separator + 1);\n if (value.startsWith(' ')) value = value.slice(1);\n\n switch (field) {\n case 'event':\n eventType = value;\n break;\n case 'data':\n data.push(value);\n break;\n case 'id':\n if (!value.includes('\\0')) lastEventId = value;\n break;\n case 'retry': {\n if (/^\\d+$/.test(value)) {\n const parsed = Number(value);\n if (Number.isSafeInteger(parsed)) retry = parsed;\n }\n break;\n }\n default:\n break;\n }\n\n return undefined;\n };\n\n await using _reader = disposableReader(reader);\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n\n while (true) {\n const lf = buffer.indexOf('\\n');\n const cr = buffer.indexOf('\\r');\n if (lf === -1 && cr === -1) break;\n // A CR may be the first half of a CRLF sequence split across two network chunks.\n if (cr !== -1 && lf === -1 && cr === buffer.length - 1) break;\n\n const lineEnd = lf === -1 ? cr : cr === -1 ? lf : Math.min(lf, cr);\n let separatorLength = 1;\n\n if (buffer[lineEnd] === '\\r' && buffer[lineEnd + 1] === '\\n') {\n separatorLength = 2;\n }\n\n const line = buffer.slice(0, lineEnd);\n buffer = buffer.slice(lineEnd + separatorLength);\n\n const event = processLine(line);\n if (event) yield event;\n }\n }\n\n buffer += decoder.decode();\n if (buffer.length > 0) {\n const event = processLine(buffer);\n if (event) yield event;\n }\n\n const terminal = dispatch(eventType, data, lastEventId, retry);\n if (terminal) yield terminal;\n // reader.cancel() + reader.releaseLock() called automatically via `await using _reader`\n}\n","/**\n * Optional OpenTelemetry tracing.\n *\n * `@opentelemetry/api` is an optional peer dependency. When it isn't installed, or when\n * the host process hasn't registered a global TracerProvider, `withSpan` degrades to\n * invoking its callback directly — no spans, no exporters, nothing beyond one cached\n * dynamic `import()` attempt. Once a consumer wires up an OpenTelemetry SDK, spans for\n * HTTP requests, endpoint failover attempts, agent turns, and tool calls appear\n * automatically without any configuration on this SDK's side.\n */\n\nimport type * as Otel from '@opentelemetry/api';\nimport { disposableSpan } from '../utils.js';\n\nexport type SpanAttributeValue = string | number | boolean;\nexport type SpanAttributes = Record<string, SpanAttributeValue | undefined>;\n\nconst INSTRUMENTATION_NAME = '@nemesis-oss/ollama-sdk';\nconst INSTRUMENTATION_VERSION = '1.0.0';\n\nlet apiPromise: Promise<typeof Otel | undefined> | undefined;\n\nfunction loadApi(): Promise<typeof Otel | undefined> {\n apiPromise ??= import('@opentelemetry/api').catch(() => undefined);\n return apiPromise;\n}\n\nfunction cleanAttributes(attributes: SpanAttributes): Record<string, SpanAttributeValue> {\n const clean: Record<string, SpanAttributeValue> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (value !== undefined) {\n clean[key] = value;\n }\n }\n return clean;\n}\n\n/**\n * Runs `fn` inside an active OpenTelemetry span named `name`, when OpenTelemetry is\n * available. `fn` receives the live span (to add events/attributes as work proceeds) or\n * `undefined` when tracing is a no-op. Exceptions from `fn` are recorded on the span,\n * marked as an error status, and re-thrown unchanged; the span always ends.\n *\n * On success the span status is left `Unset` rather than forced to `Ok` — per the\n * OpenTelemetry spec, `Ok` is final and silently suppresses any later `Error` status.\n * Some call sites (e.g. tool execution, which reports failure via a return value rather\n * than a throw) need to mark a successfully-*returned* span as an error after the fact,\n * via `setSpanError`; leaving success as `Unset` keeps that possible. Backends treat\n * `Unset` the same as `Ok` for filtering purposes.\n */\nexport async function withSpan<T>(\n name: string,\n attributes: SpanAttributes,\n fn: (span: Otel.Span | undefined) => Promise<T>,\n): Promise<T> {\n const api = await loadApi();\n if (!api) {\n return fn(undefined);\n }\n\n const tracer = api.trace.getTracer(INSTRUMENTATION_NAME, INSTRUMENTATION_VERSION);\n return tracer.startActiveSpan(name, async (span) => {\n span.setAttributes(cleanAttributes(attributes));\n using _span = disposableSpan(span);\n try {\n return await fn(span);\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n span.recordException(error);\n span.setStatus({ code: api.SpanStatusCode.ERROR, message: error.message });\n throw error;\n }\n // span.end() called automatically via `using _span` at scope exit\n });\n}\n\n/** Adds an attribute/event to `span` if tracing is active; a cheap no-op otherwise. */\nexport function addSpanEvent(\n span: Otel.Span | undefined,\n name: string,\n attributes?: SpanAttributes,\n): void {\n span?.addEvent(name, attributes ? cleanAttributes(attributes) : undefined);\n}\n\n/**\n * Marks a span as failed without throwing — for operations (like tool execution) that\n * report failure through a return value rather than an exception. No-ops when tracing\n * is inactive.\n */\nexport async function setSpanError(span: Otel.Span | undefined, error: Error): Promise<void> {\n if (!span) {\n return;\n }\n const api = await loadApi();\n span.recordException(error);\n span.setStatus({ code: api?.SpanStatusCode.ERROR ?? 2, message: error.message });\n}\n\n// --- Semantic convention attribute keys used by this SDK's instrumentation ---\n// https://opentelemetry.io/docs/specs/semconv/http/http-spans/\nexport const ATTR_HTTP_REQUEST_METHOD = 'http.request.method';\nexport const ATTR_URL_FULL = 'url.full';\nexport const ATTR_SERVER_ADDRESS = 'server.address';\nexport const ATTR_SERVER_PORT = 'server.port';\nexport const ATTR_HTTP_RESPONSE_STATUS_CODE = 'http.response.status_code';\n\n// https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/\nexport const ATTR_GEN_AI_SYSTEM = 'gen_ai.system';\nexport const ATTR_GEN_AI_OPERATION_NAME = 'gen_ai.operation.name';\nexport const ATTR_GEN_AI_REQUEST_MODEL = 'gen_ai.request.model';\nexport const ATTR_GEN_AI_RESPONSE_MODEL = 'gen_ai.response.model';\nexport const ATTR_GEN_AI_USAGE_INPUT_TOKENS = 'gen_ai.usage.input_tokens';\nexport const ATTR_GEN_AI_USAGE_OUTPUT_TOKENS = 'gen_ai.usage.output_tokens';\nexport const ATTR_GEN_AI_TOOL_NAME = 'gen_ai.tool.name';\nexport const ATTR_GEN_AI_TOOL_CALL_ID = 'gen_ai.tool.call.id';\n\n// Attributes specific to this SDK's failover/agent model (no matching semconv entry).\nexport const ATTR_OLLAMA_ENDPOINT_NAME = 'ollama.endpoint.name';\nexport const ATTR_OLLAMA_ENDPOINT_ATTEMPT = 'ollama.endpoint.attempt';\nexport const ATTR_OLLAMA_AGENT_MAX_ITERATIONS = 'ollama.agent.max_iterations';\nexport const ATTR_OLLAMA_AGENT_ITERATION = 'ollama.agent.iteration';\nexport const GEN_AI_SYSTEM_OLLAMA = 'ollama';\n","/**\n * Native fetch HTTP transport client for Ollama API.\n */\n\nimport { normalizeBaseUrl } from './host.js';\nimport { mapError } from '../errors.js';\nimport { composeMiddleware, type Middleware, type RequestContext } from '../middleware.js';\nimport type { RequestLifecycleHook } from '../logger.js';\nimport { parseNdjsonStream } from '../streaming/ndjson.js';\nimport { parseSseStream, type SseEvent } from '../streaming/sse.js';\nimport type { AbortableAsyncIterable } from '../streaming/types.js';\nimport {\n withSpan,\n ATTR_HTTP_REQUEST_METHOD,\n ATTR_URL_FULL,\n ATTR_SERVER_ADDRESS,\n ATTR_SERVER_PORT,\n ATTR_HTTP_RESPONSE_STATUS_CODE,\n type SpanAttributes,\n} from '../telemetry/index.js';\n\n/** Collapses path segments with high-cardinality values (e.g. blob digests) for span names. */\nfunction routeTemplate(path: string): string {\n return path.replace(/^\\/api\\/blobs\\/.+$/, '/api/blobs/{digest}');\n}\n\nfunction httpSpanAttributes(method: string, url: string): SpanAttributes {\n const target = new URL(url);\n return {\n [ATTR_HTTP_REQUEST_METHOD]: method,\n [ATTR_URL_FULL]: url,\n [ATTR_SERVER_ADDRESS]: target.hostname,\n [ATTR_SERVER_PORT]: target.port ? Number(target.port) : undefined,\n };\n}\n\nexport type FetchLike = typeof globalThis.fetch;\nexport type BinaryBody = Uint8Array | ArrayBuffer | string | Blob | ReadableStream<Uint8Array>;\nexport type HttpBody = unknown;\n\nlet requestSequence = 0;\n\nfunction createRequestId(): string {\n requestSequence += 1;\n return `ollama-http-${requestSequence}`;\n}\n\nfunction sameHeaders(actual: Record<string, string>, expected: Headers): boolean {\n const actualEntries = Object.fromEntries(\n Object.entries(actual).map(([key, value]) => [key.toLowerCase(), value]),\n );\n const expectedEntries = Object.fromEntries(expected.entries());\n const actualKeys = Object.keys(actualEntries);\n const expectedKeys = Object.keys(expectedEntries);\n return (\n actualKeys.length === expectedKeys.length &&\n expectedKeys.every((key) => actualEntries[key] === expectedEntries[key])\n );\n}\n\nexport interface HttpClientOptions {\n readonly baseUrl: string;\n readonly apiKey?: string | undefined;\n readonly headers?: Record<string, string> | undefined;\n readonly fetch?: FetchLike | undefined;\n readonly middleware?: readonly Middleware[] | undefined;\n readonly onLifecycleEvent?: RequestLifecycleHook | undefined;\n /** Reuse a logical request id across endpoint failover/retry attempts. */\n readonly requestId?: string | undefined;\n}\n\nexport interface HttpRequestOptions {\n readonly path: string;\n readonly method?: 'GET' | 'POST' | 'DELETE' | 'HEAD' | undefined;\n readonly body?: HttpBody;\n readonly rawBody?: BinaryBody | undefined;\n readonly headers?: Record<string, string> | undefined;\n readonly signal?: AbortSignal | undefined;\n /**\n * When `true`, return the raw {@link Response} object instead of parsing\n * the body as JSON. Used by callers that need direct access to the\n * streaming body (e.g. {@link src/generated/runtime/runtime.ts} for\n * NDJSON streaming through the runtime seam).\n *\n * The returned `Response` is the same one middleware/retry/telemetry\n * have already processed, so this option does NOT bypass any of the\n * transport-layer concerns.\n */\n readonly raw?: boolean | undefined;\n}\n\nexport class HttpClient {\n readonly baseUrl: string;\n private readonly apiKey?: string | undefined;\n private readonly defaultHeaders: Record<string, string>;\n private readonly fetchImpl: FetchLike;\n private readonly middleware: readonly Middleware[];\n private readonly onLifecycleEvent: RequestLifecycleHook | undefined;\n private readonly requestId?: string | undefined;\n\n constructor(options: HttpClientOptions) {\n this.baseUrl = normalizeBaseUrl(options.baseUrl);\n this.apiKey = options.apiKey;\n this.defaultHeaders = options.headers ?? {};\n this.fetchImpl = options.fetch ?? globalThis.fetch;\n this.middleware = options.middleware ?? [];\n this.onLifecycleEvent = options.onLifecycleEvent;\n this.requestId = options.requestId;\n }\n\n private buildHeaders(customHeaders?: Record<string, string> | undefined): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...this.defaultHeaders,\n ...customHeaders,\n };\n if (this.apiKey) {\n headers['Authorization'] = `Bearer ${this.apiKey}`;\n }\n return headers;\n }\n\n private async fetchWithMiddleware(request: RequestContext): Promise<Response> {\n const requestId = this.requestId ?? createRequestId();\n const startedAt = Date.now();\n let rawResponse: unknown;\n this.onLifecycleEvent?.({\n type: 'start',\n requestId,\n method: request.method,\n url: request.url,\n timestamp: startedAt,\n });\n\n const finalHandler = async (req: RequestContext): Promise<{\n status: number;\n headers: Record<string, string>;\n body: Response;\n }> => {\n const init: RequestInit = {\n method: req.method,\n headers: req.headers,\n ...(req.body !== undefined ? { body: req.body as NonNullable<RequestInit['body']> } : {}),\n ...(req.signal !== undefined ? { signal: req.signal } : {}),\n };\n const response = await this.fetchImpl(req.url, init);\n rawResponse = response;\n const responseHeaders =\n response.headers && typeof response.headers.entries === 'function'\n ? Object.fromEntries(response.headers.entries())\n : {};\n return {\n status: response.status,\n headers: responseHeaders,\n body: response,\n };\n };\n\n try {\n if (this.middleware.length === 0) {\n const response = await this.fetchImpl(request.url, {\n method: request.method,\n headers: request.headers,\n ...(request.body !== undefined\n ? { body: request.body as NonNullable<RequestInit['body']> }\n : {}),\n ...(request.signal !== undefined ? { signal: request.signal } : {}),\n });\n if (response.status >= 200 && response.status < 300) {\n this.onLifecycleEvent?.({\n type: 'success',\n requestId,\n durationMs: Date.now() - startedAt,\n status: response.status,\n timestamp: Date.now(),\n });\n } else {\n this.onLifecycleEvent?.({\n type: 'error',\n requestId,\n durationMs: Date.now() - startedAt,\n error: mapError(new Error(`HTTP ${response.status}`), {\n request: { method: request.method, url: request.url },\n response: { status: response.status },\n }),\n timestamp: Date.now(),\n });\n }\n return response;\n }\n\n const pipeline = composeMiddleware(this.middleware, finalHandler);\n const context = await pipeline(request);\n\n let response: Response;\n if (rawResponse !== undefined && context.body === rawResponse) {\n response = rawResponse as Response;\n if (\n context.status !== response.status ||\n !sameHeaders(context.headers, response.headers)\n ) {\n const cloned = response.clone();\n response = new Response(cloned.body, {\n status: context.status,\n headers: context.headers,\n });\n }\n } else if (context.body instanceof Response) {\n if (\n context.status === context.body.status &&\n sameHeaders(context.headers, context.body.headers)\n ) {\n response = context.body;\n } else {\n const cloned = context.body.clone();\n response = new Response(cloned.body, {\n status: context.status,\n headers: context.headers,\n });\n }\n } else if (\n context.body === undefined ||\n typeof context.body === 'string' ||\n context.body instanceof ArrayBuffer ||\n ArrayBuffer.isView(context.body) ||\n context.body instanceof Blob ||\n context.body instanceof ReadableStream\n ) {\n response = new Response(context.body as RequestInit['body'], {\n status: context.status,\n headers: context.headers,\n });\n } else {\n response = new Response(JSON.stringify(context.body), {\n status: context.status,\n headers: context.headers,\n });\n }\n\n if (context.status >= 200 && context.status < 300) {\n this.onLifecycleEvent?.({\n type: 'success',\n requestId,\n durationMs: Date.now() - startedAt,\n status: context.status,\n timestamp: Date.now(),\n });\n } else {\n this.onLifecycleEvent?.({\n type: 'error',\n requestId,\n durationMs: Date.now() - startedAt,\n error: mapError(new Error(`HTTP ${context.status}`), {\n request: { method: request.method, url: request.url },\n response: { status: context.status, headers: context.headers },\n }),\n timestamp: Date.now(),\n });\n }\n return response;\n } catch (error) {\n const mapped = mapError(error, {\n request: { method: request.method, url: request.url },\n });\n this.onLifecycleEvent?.({\n type: 'error',\n requestId,\n durationMs: Date.now() - startedAt,\n error: mapped,\n timestamp: Date.now(),\n });\n throw mapped;\n }\n }\n\n async request<T>(options: HttpRequestOptions): Promise<T> {\n const url = `${this.baseUrl}${options.path}`;\n const method =\n options.method ??\n (options.body !== undefined || options.rawBody !== undefined ? 'POST' : 'GET');\n const headers = this.buildHeaders(options.headers);\n\n if (options.rawBody !== undefined && !options.headers?.['Content-Type']) {\n delete headers['Content-Type'];\n }\n\n return withSpan(\n `${method} ${routeTemplate(options.path)}`,\n httpSpanAttributes(method, url),\n async (span) => {\n try {\n const bodyInit =\n options.rawBody !== undefined\n ? (options.rawBody as never)\n : options.body !== undefined\n ? JSON.stringify(options.body)\n : undefined;\n\n const response = await this.fetchWithMiddleware({\n url,\n method,\n headers,\n ...(bodyInit !== undefined ? { body: bodyInit } : {}),\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n });\n span?.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, response.status);\n\n if (!response.ok) {\n let errorBody: unknown;\n try {\n errorBody = await response.json();\n } catch {\n errorBody = await response.text();\n }\n const message =\n typeof errorBody === 'object' && errorBody !== null && 'error' in errorBody\n ? String((errorBody as { error: unknown }).error)\n : `HTTP ${response.status} ${response.statusText}`;\n\n throw mapError(new Error(message), {\n request: { method, url },\n response: { status: response.status, body: errorBody },\n });\n }\n\n if (options.method === 'HEAD' || response.status === 204) {\n return undefined as T;\n }\n\n // Raw mode: return the Response object directly so callers can\n // access the streaming body. Middleware, retry, telemetry, and\n // error-mapping have already run by this point.\n if (options.raw === true) {\n return response as unknown as T;\n }\n\n if (typeof response.text === 'function') {\n const text = await response.text();\n return (text ? JSON.parse(text) : undefined) as T;\n }\n if (typeof response.json === 'function') {\n return (await response.json()) as T;\n }\n return undefined as T;\n } catch (err) {\n throw mapError(err, { request: { method, url } });\n }\n },\n );\n }\n\n /**\n * Opens an event-stream response and exposes parsed SSE events.\n *\n * This is intentionally schema-agnostic so OpenAI and Anthropic compatibility layers\n * can decode their provider-specific event payloads without duplicating transport logic.\n */\n async requestSseStream(options: HttpRequestOptions): Promise<AbortableAsyncIterable<SseEvent>> {\n const url = `${this.baseUrl}${options.path}`;\n const method = options.method ?? 'POST';\n const headers = {\n ...this.buildHeaders(options.headers),\n Accept: 'text/event-stream',\n };\n\n return withSpan(\n `${method} ${routeTemplate(options.path)}`,\n httpSpanAttributes(method, url),\n async (span) => {\n try {\n const controller = new AbortController();\n const removeAbortListener =\n options.signal !== undefined\n ? (() => {\n if (options.signal.aborted) {\n controller.abort(options.signal.reason);\n } else {\n const onAbort = (): void => controller.abort(options.signal?.reason);\n options.signal.addEventListener('abort', onAbort, { once: true });\n return () => options.signal?.removeEventListener('abort', onAbort);\n }\n return undefined;\n })()\n : undefined;\n\n const response = await this.fetchWithMiddleware({\n url,\n method,\n headers,\n ...(options.body !== undefined ? { body: JSON.stringify(options.body) } : {}),\n signal: controller.signal,\n });\n span?.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, response.status);\n\n if (!response.ok) {\n removeAbortListener?.();\n const errorText = await response.text();\n throw mapError(new Error(errorText || `HTTP ${response.status}`), {\n request: { method, url },\n response: { status: response.status, body: errorText },\n });\n }\n\n if (!response.body) {\n removeAbortListener?.();\n throw mapError(new Error('Response body is null, cannot stream SSE'), {\n request: { method, url },\n });\n }\n\n const stream = (async function* (): AsyncGenerator<SseEvent, void, undefined> {\n try {\n yield* parseSseStream(response.body!);\n } finally {\n removeAbortListener?.();\n }\n })();\n\n return {\n [Symbol.asyncIterator]() {\n return stream[Symbol.asyncIterator]();\n },\n abort: () => {\n removeAbortListener?.();\n controller.abort();\n },\n } as AbortableAsyncIterable<SseEvent>;\n } catch (err) {\n throw mapError(err, { request: { method, url } });\n }\n },\n );\n }\n\n async requestStream<T>(options: HttpRequestOptions): Promise<AbortableAsyncIterable<T>> {\n const url = `${this.baseUrl}${options.path}`;\n const method = options.method ?? 'POST';\n const headers = this.buildHeaders(options.headers);\n\n return withSpan(\n `${method} ${routeTemplate(options.path)}`,\n httpSpanAttributes(method, url),\n async (span) => {\n try {\n const controller = new AbortController();\n const removeAbortListener =\n options.signal !== undefined\n ? (() => {\n if (options.signal.aborted) {\n controller.abort(options.signal.reason);\n } else {\n const onAbort = (): void => controller.abort(options.signal?.reason);\n options.signal.addEventListener('abort', onAbort, { once: true });\n return () => options.signal?.removeEventListener('abort', onAbort);\n }\n return undefined;\n })()\n : undefined;\n\n const response = await this.fetchWithMiddleware({\n url,\n method,\n headers,\n ...(options.body !== undefined ? { body: JSON.stringify(options.body) } : {}),\n signal: controller.signal,\n });\n span?.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, response.status);\n\n if (!response.ok) {\n removeAbortListener?.();\n const errorText = await response.text();\n throw mapError(new Error(errorText || `HTTP ${response.status}`), {\n request: { method, url },\n response: { status: response.status, body: errorText },\n });\n }\n\n if (!response.body) {\n removeAbortListener?.();\n throw mapError(new Error('Response body is null, cannot stream'), {\n request: { method, url },\n });\n }\n\n const stream = parseNdjsonStream<T>(response.body);\n const abortable: AbortableAsyncIterable<T> = {\n [Symbol.asyncIterator]() {\n return (async function* (): AsyncGenerator<T, void, undefined> {\n try {\n yield* stream;\n } finally {\n removeAbortListener?.();\n }\n })()[Symbol.asyncIterator]();\n },\n abort: () => {\n removeAbortListener?.();\n controller.abort();\n },\n };\n return abortable;\n } catch (err) {\n throw mapError(err, { request: { method, url } });\n }\n },\n );\n }\n}\n","/**\n * Active endpoint health pinging utility.\n */\n\nimport { HttpClient, type FetchLike } from '../transport/http.js';\nimport type { OllamaEndpoint } from './endpoint-registry.js';\nimport type { Middleware } from '../middleware.js';\nimport type { RequestLifecycleHook } from '../logger.js';\nimport type { VersionResponse } from '../types.js';\nimport { disposableTimer } from '../utils.js';\n\nexport interface EndpointHealthCheckResult {\n readonly name: string;\n readonly baseUrl: string;\n readonly reachable: boolean;\n readonly latencyMs: number;\n readonly version?: string;\n readonly error?: string;\n}\n\nexport async function checkEndpointHealth(\n endpoint: OllamaEndpoint,\n fetchImpl?: FetchLike,\n timeoutMs = 5000,\n middleware?: readonly Middleware[] | undefined,\n onLifecycleEvent?: RequestLifecycleHook | undefined,\n): Promise<EndpointHealthCheckResult> {\n const client = new HttpClient({\n baseUrl: endpoint.baseUrl,\n apiKey: endpoint.apiKey,\n headers: endpoint.headers,\n fetch: fetchImpl,\n middleware,\n onLifecycleEvent,\n });\n\n const startTime = Date.now();\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n using _timer = disposableTimer(timer);\n\n try {\n const res = await client.request<VersionResponse>({\n path: '/api/version',\n method: 'GET',\n signal: controller.signal,\n });\n const latencyMs = Date.now() - startTime;\n return {\n name: endpoint.name,\n baseUrl: endpoint.baseUrl,\n reachable: true,\n latencyMs,\n version: res.version,\n };\n } catch (err) {\n const latencyMs = Date.now() - startTime;\n return {\n name: endpoint.name,\n baseUrl: endpoint.baseUrl,\n reachable: false,\n latencyMs,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n // clearTimeout(timer) called automatically via `using _timer` at scope exit\n}\n","/**\n * Model capability detection and runtime environment inference.\n */\n\nimport { HttpClient } from '../transport/http.js';\nimport type { ListResponse, ModelResponse, ShowResponse, ThinkingMetadata } from '../types.js';\n\nexport type RuntimeMode = 'local' | 'cloud' | 'unknown';\n\n/**\n * Best-effort classification of a model's parallel tool-call emission\n * behavior. Used by agent loops that need to know whether the model\n * is likely to emit multiple `tool_calls` in a single assistant\n * message (parallel) or one-at-a-time (sequential).\n *\n * This is a **heuristic** derived from runtime mode + model family\n * pattern matching against `/api/show`'s reported model_info. The\n * SDK does NOT normalize between cloud and local — it reports the\n * best assessment it can and lets the caller decide how to act.\n *\n * See ADR 0023 for the rationale and the recommended caller pattern.\n */\nexport type ParallelToolCallBehavior = 'yes' | 'no' | 'unknown';\n\nexport interface ModelCapabilities {\n readonly model: string;\n readonly reported: readonly string[];\n readonly supportsTools: boolean;\n readonly supportsVision: boolean;\n readonly supportsEmbedding: boolean;\n readonly supportsCompletion: boolean;\n readonly supportsThinking: boolean;\n /** Model-defined thinking values and default, when /api/show reports them. */\n readonly thinking?: ThinkingMetadata | undefined;\n readonly supportsStreaming: true;\n /** Maximum model context length reported by /api/show model_info, when available. */\n readonly contextLength?: number | undefined;\n /**\n * Best-effort inference, not a guarantee: Ollama's `/api/show` does not report structured\n * output support as a queryable capability, so this is inferred from {@link inferRuntimeMode}\n * — `false` for `cloud`, since Ollama Cloud does not currently support structured outputs;\n * `true` for `local`/`unknown`. A locally-hosted model that genuinely can't follow a JSON\n * schema will still report `true` here; the request itself is the only reliable way to find\n * out. `OllamaClient.chat`/`generate` apply this same inference as a fail-fast pre-flight\n * guard whenever `format` is set, throwing `OllamaUnsupportedCapabilityError` rather than\n * making a network call that Ollama Cloud is known to reject.\n */\n readonly supportsStructuredOutputRequest: boolean;\n /**\n * Best-effort inference of whether the model is likely to emit\n * **multiple `tool_calls` in a single assistant message** (parallel)\n * vs **one tool call per assistant turn** (sequential).\n *\n * The SDK does NOT normalize between cloud and local — it reports\n * the best assessment it can and lets the caller decide. Agent\n * authors who need hard sequential execution should set\n * `ToolRegistry`'s `maxConcurrency: 1` regardless of this field's\n * value, since the model's behavior is not deterministic across\n * prompts.\n *\n * Inference matrix (see ADR 0023):\n *\n * - **`'yes'`** — the model is known to emit parallel tool calls:\n * - Cloud-mode endpoints (the OpenAI/Anthropic compat bridges\n * proxy to proprietary models like GPT-4o, Claude, which\n * freely emit parallel tool calls).\n * - Local models from families that ship with parallel-tool-call\n * training (Qwen 2.5+, Llama 3.1+ tool-use variants, Mistral\n * function-calling fine-tunes, Hermes 2/3, Command R+).\n *\n * - **`'no'`** — the model is known to emit at most one tool call\n * per assistant turn. Currently no model family is classified\n * as `'no'` by default; the field is reserved for future\n * narrowing as more is learned about specific models.\n *\n * - **`'unknown'`** — the model family is not in the known-yes or\n * known-no list, OR `/api/show` didn't return enough\n * information to make an assessment. Callers should treat\n * `'unknown'` as \"ask the model and see what it does\" — the\n * `ToolRegistry` will execute whatever calls the model emits,\n * in parallel via `Promise.all` by default.\n *\n * See: `src/tools/registry.ts` for `maxConcurrency` enforcement,\n * and ADR 0023 for the full design rationale.\n */\n readonly parallelToolCalls: ParallelToolCallBehavior;\n}\n\nexport function inferRuntimeMode(baseUrl: string): RuntimeMode {\n try {\n const url = new URL(baseUrl);\n // WHATWG URL keeps the brackets on an IPv6 literal (\"[::1]\"), so strip them before comparing\n const host = url.hostname.toLowerCase().replace(/^\\[|\\]$/g, '');\n if (\n host === 'localhost' ||\n host === '127.0.0.1' ||\n host === '::1' ||\n host.endsWith('.local') ||\n host.startsWith('192.168.') ||\n host.startsWith('10.')\n ) {\n return 'local';\n }\n return 'cloud';\n } catch {\n return 'unknown';\n }\n}\n\nfunction extractContextLength(modelInfo?: Record<string, unknown>): number | undefined {\n if (!modelInfo) return undefined;\n for (const [key, value] of Object.entries(modelInfo)) {\n if (\n key.endsWith('.context_length') &&\n typeof value === 'number' &&\n Number.isFinite(value) &&\n value > 0\n ) {\n return value;\n }\n }\n return undefined;\n}\n\n/**\n * Best-effort extraction of the model's architectural family from\n * `/api/show`'s `model_info` record.\n *\n * Ollama's `model_info` keys are dotted strings like\n * `llama.architecture`, `qwen2.architecture`, `mistral.architecture`,\n * etc. We look for any key ending in `.architecture` and return its\n * value (e.g. `\"llama\"`, `\"qwen2\"`, `\"mistral\"`). When absent, fall\n * back to scanning the `details.family` / `details.families` fields\n * from `/api/show`'s top-level response.\n *\n * Returns `undefined` when no family signal is available — the\n * caller treats this as `'unknown'` for parallel-tool-call purposes.\n */\nfunction extractModelFamily(showRes: ShowResponse): string | undefined {\n // 1. Scan model_info for any `*.architecture` key.\n if (showRes.model_info) {\n for (const [key, value] of Object.entries(showRes.model_info)) {\n if (key.endsWith('.architecture') && typeof value === 'string' && value.length > 0) {\n return value.toLowerCase();\n }\n }\n }\n // 2. Fall back to details.family.\n if (showRes.details?.family && showRes.details.family.length > 0) {\n return showRes.details.family.toLowerCase();\n }\n // 3. Fall back to the first entry in details.families (when present).\n const families = showRes.details?.families;\n if (families && families.length > 0) {\n const first = families[0];\n if (typeof first === 'string' && first.length > 0) return first.toLowerCase();\n }\n return undefined;\n}\n\n/**\n * Local-mode model families known to support parallel tool calls.\n *\n * This is intentionally a conservative list — only families with a\n * documented track record of training parallel tool calls. When in\n * doubt, the heuristic returns `'unknown'` rather than `'yes'`,\n * because over-promising parallel tool calls causes agent loops to\n * over-allocate concurrency (which the SDK's `ToolRegistry` would\n * then have to serialize back down anyway).\n *\n * Sources:\n * - Qwen 2.5 / Qwen 2.5 Coder tool-use: parallel tool calls supported\n * - Llama 3.1+ tool-use variants: parallel tool calls supported\n * - Mistral / Mixtral function-calling fine-tunes: parallel supported\n * - Hermes 2/3 (NousResearch): parallel supported\n * - Command R / Command R+ (Cohere): parallel supported\n */\nconst PARALLEL_TOOL_CALL_LOCAL_FAMILIES: ReadonlySet<string> = new Set([\n 'qwen2',\n 'qwen2.5',\n 'qwen3',\n 'llama3.1',\n 'llama3.2',\n 'llama3.3',\n 'llama4',\n 'mistral',\n 'mixtral',\n 'hermes',\n 'command-r',\n 'command-r-plus',\n]);\n\n/**\n * Local-mode model name substrings that, when present, indicate\n * the model is a tool-use / function-calling variant likely to\n * support parallel tool calls. This catches fine-tunes whose\n * `model_info.architecture` reports the base family (e.g. `llama`)\n * but whose model name reveals the tool-use variant (e.g.\n * `llama3.1-tool-use:8b`).\n */\nconst PARALLEL_TOOL_CALL_NAME_HINTS: ReadonlySet<string> = new Set([\n 'tool-use',\n 'tooluse',\n 'function-call',\n 'functioncall',\n 'instruct', // Most \"instruct\" variants of tool-capable families ship with parallel tool calls\n 'hermes',\n 'command-r',\n]);\n\n/**\n * Heuristic for determining whether a local-mode model is known to\n * emit parallel tool calls. Returns `'yes'` when the model family\n * is in the known-parallel list OR the model name contains a tool-use\n * variant hint, `'no'` for families explicitly known to emit single\n * calls (currently none — the field is reserved for future use), and\n * `'unknown'` otherwise.\n *\n * The name-hint check scans the FULL model name (including tags like\n * `:7b-instruct`), not just the base name, because tool-use variants\n * often carry the hint in the tag (e.g. `phi3:14b-instruct`,\n * `llama3.1:8b-tool-use`).\n *\n * See ADR 0023 for the rationale.\n */\nfunction inferLocalParallelToolCalls(\n model: string,\n family: string | undefined,\n): ParallelToolCallBehavior {\n const modelLower = model.toLowerCase();\n // 1. Family-based assessment.\n if (family !== undefined && PARALLEL_TOOL_CALL_LOCAL_FAMILIES.has(family)) {\n return 'yes';\n }\n // 2. Name-substring assessment for tool-use variants. We scan the\n // FULL model name (including the tag) because tool-use variants\n // often carry the hint in the tag (e.g. `phi3:14b-instruct`,\n // `llama3.1:8b-tool-use`).\n for (const hint of PARALLEL_TOOL_CALL_NAME_HINTS) {\n if (modelLower.includes(hint)) {\n return 'yes';\n }\n }\n // 3. Default: unknown. The caller should treat this as \"ask the\n // model and see what it does.\"\n return 'unknown';\n}\n\n/**\n * Heuristic for determining cloud-mode parallel tool call behavior.\n *\n * Cloud endpoints go through the OpenAI / Anthropic compatibility\n * bridges, which proxy to proprietary models (GPT-4o, Claude, etc.).\n * Both OpenAI and Anthropic models freely emit parallel tool calls\n * when they judge it appropriate, so cloud-mode is `'yes'` whenever\n * the model is tool-capable (`supportsTools === true`), and\n * `'unknown'` otherwise (an embedding-only model on a cloud endpoint\n * is an edge case that shouldn't claim parallel tool calls).\n */\nfunction inferCloudParallelToolCalls(supportsTools: boolean): ParallelToolCallBehavior {\n return supportsTools ? 'yes' : 'unknown';\n}\n\nexport async function detectModelCapabilities(\n http: HttpClient,\n model: string,\n signal?: AbortSignal,\n): Promise<ModelCapabilities> {\n const showRes = await http.request<ShowResponse>({\n path: '/api/show',\n body: { model },\n ...(signal !== undefined ? { signal } : {}),\n });\n\n const reported = showRes.capabilities ?? [];\n const reportedSet = new Set(reported.map((c) => c.toLowerCase()));\n\n const contextLength = extractContextLength(showRes.model_info);\n const supportsTools = reportedSet.has('tools');\n const runtimeMode = inferRuntimeMode(http.baseUrl);\n\n // Parallel-tool-call inference: see ADR 0023.\n const parallelToolCalls: ParallelToolCallBehavior =\n runtimeMode === 'cloud'\n ? inferCloudParallelToolCalls(supportsTools)\n : runtimeMode === 'local'\n ? inferLocalParallelToolCalls(model, extractModelFamily(showRes))\n : // unknown runtime mode — can't even tell if we're cloud or local\n 'unknown';\n\n return {\n model,\n reported,\n supportsTools,\n supportsVision: reportedSet.has('vision'),\n supportsEmbedding: reportedSet.has('embedding'),\n supportsCompletion: reportedSet.has('completion') || !reportedSet.has('embedding'),\n supportsThinking: reportedSet.has('thinking'),\n ...(showRes.thinking !== undefined ? { thinking: showRes.thinking } : {}),\n ...(contextLength !== undefined ? { contextLength } : {}),\n supportsStreaming: true,\n supportsStructuredOutputRequest: runtimeMode !== 'cloud',\n parallelToolCalls,\n };\n}\n\nexport async function listAvailableModels(http: HttpClient): Promise<ModelResponse[]> {\n const res = await http.request<ListResponse>({\n path: '/api/tags',\n method: 'GET',\n });\n return [...res.models];\n}\n","/**\n * Zod schema conversion to JSON Schema for Ollama structured outputs.\n */\n\nimport { z } from 'zod';\nimport { OllamaToolValidationError } from '../errors.js';\n\nexport type SupportedSchema<T = unknown> = z.ZodType<T>;\n\nfunction extractJsonSubstring(text: string): string {\n const trimmed = text.trim();\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) {\n return trimmed;\n }\n const match = trimmed.match(/```(?:json)?\\s*([\\s\\S]*?)\\s*```/);\n if (match && match[1]) {\n return match[1].trim();\n }\n const firstBrace = trimmed.indexOf('{');\n const lastBrace = trimmed.lastIndexOf('}');\n if (firstBrace !== -1 && lastBrace > firstBrace) {\n return trimmed.slice(firstBrace, lastBrace + 1);\n }\n return trimmed;\n}\n\n/**\n * Best-effort structural JSON Schema conversion for Zod v3 schemas, which lack a\n * native `toJSONSchema` API. Walks the internal `_def` shape that v3 exposes.\n */\nexport function zodV3ToJsonSchema(schema: unknown): Record<string, unknown> {\n const def = (schema as { _def?: { typeName?: string; [key: string]: unknown } })._def;\n if (!def) {\n return { type: 'object' };\n }\n\n switch (def['typeName']) {\n case 'ZodObject': {\n const shape = (def['shape'] as () => Record<string, unknown>)();\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n for (const [key, value] of Object.entries(shape)) {\n properties[key] = zodV3ToJsonSchema(value);\n if (!isZodV3Optional(value)) {\n required.push(key);\n }\n }\n return {\n type: 'object',\n properties,\n ...(required.length > 0 ? { required } : {}),\n };\n }\n case 'ZodString':\n return { type: 'string' };\n case 'ZodNumber':\n return { type: 'number' };\n case 'ZodBoolean':\n return { type: 'boolean' };\n case 'ZodDate':\n return { type: 'string', format: 'date-time' };\n case 'ZodArray':\n return { type: 'array', items: zodV3ToJsonSchema(def['type']) };\n case 'ZodEnum':\n return { type: 'string', enum: def['values'] };\n case 'ZodNativeEnum':\n return { enum: Object.values(def['values'] as Record<string, unknown>) };\n case 'ZodLiteral':\n return { const: def['value'] };\n case 'ZodOptional':\n case 'ZodNullable':\n case 'ZodDefault':\n return zodV3ToJsonSchema(def['innerType']);\n case 'ZodEffects':\n return zodV3ToJsonSchema(def['schema']);\n case 'ZodUnion':\n return { anyOf: (def['options'] as unknown[]).map((option) => zodV3ToJsonSchema(option)) };\n case 'ZodRecord':\n return { type: 'object', additionalProperties: zodV3ToJsonSchema(def['valueType']) };\n default:\n return { type: 'object' };\n }\n}\n\nfunction isZodV3Optional(schema: unknown): boolean {\n const typeName = (schema as { _def?: { typeName?: string } })._def?.typeName;\n return typeName === 'ZodOptional' || typeName === 'ZodDefault';\n}\n\n/**\n * Converts a Zod schema into a JSON Schema object accepted by Ollama's `format` parameter.\n *\n * Uses Zod v4's native `z.toJSONSchema` when available, falling back to a structural\n * walk of Zod v3's internal `_def` shape so both major versions work as peer dependencies.\n */\nexport function zodToJsonSchema<T>(schema: z.ZodType<T>): Record<string, unknown> {\n if (\n typeof (z as { toJSONSchema?: (s: z.ZodType<T>) => Record<string, unknown> }).toJSONSchema ===\n 'function'\n ) {\n return (\n z as unknown as { toJSONSchema: (s: z.ZodType<T>) => Record<string, unknown> }\n ).toJSONSchema(schema);\n }\n\n return zodV3ToJsonSchema(schema);\n}\n\n/**\n * Parses and validates a JSON output string against a Zod schema.\n */\nexport function parseStructuredOutput<T>(\n rawJson: string,\n schema: z.ZodType<T>,\n toolName = 'structured_output',\n): T {\n let parsed: unknown;\n const jsonStr = extractJsonSubstring(rawJson);\n try {\n parsed = JSON.parse(jsonStr);\n } catch (err) {\n throw new OllamaToolValidationError(`Failed to parse structured output as JSON: ${rawJson}`, {\n toolName,\n cause: err,\n });\n }\n\n const result = schema.safeParse(parsed);\n if (!result.success) {\n throw new OllamaToolValidationError(`Structured output failed schema validation`, {\n toolName,\n issues: result.error.issues,\n cause: result.error,\n });\n }\n\n return result.data;\n}\n","/**\n * Token usage and duration calculation utilities.\n */\n\nexport const NANOS_PER_MS = 1_000_000;\nexport const NANOS_PER_SECOND = 1_000_000_000;\n\nexport interface TokenUsage {\n readonly promptTokens: number;\n /** Prompt tokens read from Ollama's KV cache. */\n readonly cachedPromptTokens?: number | undefined;\n readonly completionTokens: number;\n readonly totalTokens: number;\n readonly tokensPerSecond?: number | undefined;\n readonly loadDurationMs?: number | undefined;\n readonly promptEvalDurationMs?: number | undefined;\n readonly evalDurationMs?: number | undefined;\n readonly totalDurationMs?: number | undefined;\n}\n\nexport interface RawUsageSource {\n readonly prompt_eval_count?: number | undefined;\n readonly prompt_eval_cached_count?: number | undefined;\n readonly eval_count?: number | undefined;\n readonly total_duration?: number | undefined;\n readonly load_duration?: number | undefined;\n readonly prompt_eval_duration?: number | undefined;\n readonly eval_duration?: number | undefined;\n}\n\n/**\n * Extracts and normalizes token usage metrics from an Ollama response.\n */\nexport function extractUsage(raw: RawUsageSource): TokenUsage {\n const promptTokens = raw.prompt_eval_count ?? 0;\n const completionTokens = raw.eval_count ?? 0;\n const totalTokens = promptTokens + completionTokens;\n\n let tokensPerSecond: number | undefined;\n if (raw.eval_count && raw.eval_duration && raw.eval_duration > 0) {\n tokensPerSecond = Number(((raw.eval_count / raw.eval_duration) * NANOS_PER_SECOND).toFixed(2));\n }\n\n return {\n promptTokens,\n ...(raw.prompt_eval_cached_count !== undefined\n ? { cachedPromptTokens: raw.prompt_eval_cached_count }\n : {}),\n completionTokens,\n totalTokens,\n ...(tokensPerSecond !== undefined ? { tokensPerSecond } : {}),\n ...(raw.load_duration !== undefined\n ? { loadDurationMs: raw.load_duration / NANOS_PER_MS }\n : {}),\n ...(raw.prompt_eval_duration !== undefined\n ? { promptEvalDurationMs: raw.prompt_eval_duration / NANOS_PER_MS }\n : {}),\n ...(raw.eval_duration !== undefined\n ? { evalDurationMs: raw.eval_duration / NANOS_PER_MS }\n : {}),\n ...(raw.total_duration !== undefined\n ? { totalDurationMs: raw.total_duration / NANOS_PER_MS }\n : {}),\n };\n}\n","/**\n * Synthetic tool-call ID generation.\n *\n * Ollama's native `/api/chat` protocol does not assign an identifier to a tool call —\n * see the {@link ToolCall} docs in `../types.js`. To let consumers correlate a tool\n * result back to its call the way OpenAI's `tool_call_id` does (useful for logging,\n * OpenAI-shaped transcripts, or just not having to track array position by hand), the\n * SDK synthesizes a stable client-side `id` the first time it sees a tool call that\n * doesn't already have one, and reuses that same id everywhere that call is referenced\n * (the streamed `tool_call` event, the final aggregated message, `ToolExecutionResult`,\n * and the `role: 'tool'` history entry `Agent` appends). It has no meaning to Ollama or\n * the model itself — it's purely a client-side bookkeeping aid.\n *\n * Uses the global Web Crypto `crypto.randomUUID()` (available in Node 20+, browsers, and\n * every Edge runtime this SDK targets) rather than `node:crypto`, which would break Edge\n * Runtime compatibility (see ADR 0006).\n */\n\nimport type { ToolCall } from '../types.js';\n\nexport function generateToolCallId(): string {\n return `call_${crypto.randomUUID()}`;\n}\n\n/**\n * Returns `toolCalls` with every entry guaranteed to have an `id`, generating one for any\n * entry that lacks it. Entries that already have an `id` (e.g. re-processed calls) are\n * left untouched so ids stay stable across repeated calls on the same data.\n */\nexport function ensureToolCallIds(\n toolCalls: readonly ToolCall[] | undefined,\n): readonly ToolCall[] | undefined {\n if (!toolCalls || toolCalls.length === 0) {\n return toolCalls;\n }\n return toolCalls.map((tc) => (tc.id !== undefined ? tc : { ...tc, id: generateToolCallId() }));\n}\n","/**\n * Tool-call streaming accumulator — defensive merge logic for\n * `message.tool_calls` arrays that arrive across multiple NDJSON\n * chunks.\n *\n * ## When this matters\n *\n * Ollama's **native `/api/chat`** streaming protocol emits\n * `message.tool_calls` as a complete JSON array (with parsed-object\n * `arguments`, not stringified deltas) in a single `done: true` chunk.\n * For native streaming, the accumulator here is mostly a no-op —\n * one chunk carries the full array, the next chunk has nothing.\n *\n * The accumulator becomes load-bearing in three scenarios:\n *\n * 1. **OpenAI-compat streaming** (`/v1/chat/completions` with\n * `stream: true`): tool call arguments come as string deltas\n * spread across multiple chunks, identified by `index`. The\n * compat layer at `src/integrations/openai.ts` already does\n * its own per-index accumulation; this utility exists for\n * callers who want the same logic on raw NDJSON chunks.\n *\n * 2. **Defensive native streaming**: although the documented\n * Ollama behavior is \"tool_calls arrive in the final chunk\",\n * a future server version could legitimately stream them\n * incrementally. The SDK shouldn't crash or produce\n * duplicates if that happens.\n *\n * 3. **Caller-side buffering**: agent loops that consume\n * `OllamaStream` events directly may want to buffer tool-call\n * deltas themselves rather than trust the SDK's aggregator —\n * this utility gives them a typed, tested building block.\n *\n * ## Merge semantics\n *\n * Two `ToolCall` entries are considered \"the same call\" when they\n * share the same `id` (the SDK-synthesized stable identifier — see\n * `src/tools/tool-call-id.ts`), OR when they're at the same array\n * position and neither has an `id`. When two same-call entries are\n * merged:\n *\n * - `function.name` — the later chunk's name wins (the model may\n * emit the name in a later chunk after an initial empty one).\n * - `function.arguments` — the two objects are merged with\n * spread semantics: `{...earlier, ...later}`. This handles\n * the case where the model emits arguments incrementally as\n * partial JSON objects (which is non-standard but seen in some\n * open-weights fine-tunes).\n *\n * For arguments-as-string deltas (the OpenAI-compat case), the\n * accumulator concatenates the strings rather than merging — see\n * {@link mergeToolCallArgumentsString}.\n */\n\nimport type { ToolCall, ToolCallFunction } from '../types.js';\n\n/**\n * Determine whether two `ToolCall` entries refer to the same logical\n * call (and should therefore be merged rather than appended).\n *\n * Returns `true` when:\n * - both have an `id` and the ids match, OR\n * - neither has an `id` and they're at the same array index\n * (caller is responsible for the index check — this helper\n * only handles the id case).\n */\nexport function isSameToolCall(\n a: ToolCall,\n b: ToolCall,\n aIndex?: number,\n bIndex?: number,\n): boolean {\n if (a.id !== undefined && b.id !== undefined) {\n return a.id === b.id;\n }\n // No id on either side — same call iff the caller says they're at\n // the same array index. Default to \"different\" if the caller didn't\n // supply indices (safer than incorrectly merging unrelated calls).\n if (aIndex !== undefined && bIndex !== undefined) {\n return aIndex === bIndex;\n }\n return false;\n}\n\n/**\n * Merge two `ToolCall` entries that refer to the same logical call.\n *\n * The later chunk's `function.name` wins when present; otherwise the\n * earlier one's name is preserved. The two `arguments` objects are\n * merged with spread semantics (`{...earlier, ...later}`), which\n * handles the (non-standard but observed) case where the model\n * emits arguments as partial JSON objects across chunks.\n *\n * For arguments-as-string deltas (OpenAI-compat streaming), use\n * {@link mergeToolCallArgumentsString} instead.\n */\nexport function mergeToolCall(earlier: ToolCall, later: ToolCall): ToolCall {\n const earlierFn = earlier.function;\n const laterFn = later.function;\n const earlierArgs = earlierFn.arguments as Record<string, unknown> | undefined;\n const laterArgs = laterFn.arguments as Record<string, unknown> | undefined;\n\n const mergedFn: ToolCallFunction = {\n name: laterFn.name || earlierFn.name,\n arguments:\n earlierArgs !== undefined && laterArgs !== undefined\n ? { ...earlierArgs, ...laterArgs }\n : laterArgs ?? earlierArgs ?? {},\n };\n\n return {\n // id: prefer the later one if present, else the earlier one\n ...(later.id !== undefined ? { id: later.id } : earlier.id !== undefined ? { id: earlier.id } : {}),\n function: mergedFn,\n };\n}\n\n/**\n * Merge two `ToolCall` entries where `function.arguments` is a JSON\n * string (the OpenAI-compat streaming format), concatenating the\n * string deltas rather than spreading objects.\n *\n * Returns a `ToolCall` whose `function.arguments` is the\n * concatenated string. The caller is responsible for JSON-parsing\n * the final string when the stream completes.\n */\nexport function mergeToolCallArgumentsString(earlier: ToolCall, later: ToolCall): ToolCall {\n const earlierArgs = earlier.function.arguments as unknown as string | undefined;\n const laterArgs = later.function.arguments as unknown as string | undefined;\n const concatenated = (typeof earlierArgs === 'string' ? earlierArgs : '') +\n (typeof laterArgs === 'string' ? laterArgs : '');\n\n return {\n ...(later.id !== undefined ? { id: later.id } : earlier.id !== undefined ? { id: earlier.id } : {}),\n function: {\n name: later.function.name || earlier.function.name,\n arguments: concatenated as unknown as Record<string, unknown>,\n },\n };\n}\n\n/**\n * Defensive accumulator for `message.tool_calls` arrays that arrive\n * across multiple NDJSON chunks. Used internally by\n * `aggregateChat` in `src/streaming/normalize.ts` so the SDK doesn't\n * produce duplicate tool_call entries if a future server version\n * starts streaming them incrementally.\n *\n * The merge strategy is:\n *\n * - For each tool call in the new chunk, check whether an existing\n * entry matches (by `id` if both have one, by array position\n * otherwise).\n * - If a match is found, merge the two entries via\n * {@link mergeToolCall}.\n * - If no match is found, append the new entry.\n *\n * This preserves the documented native Ollama behavior (tool_calls\n * arrive complete in one chunk → no merge happens, just one append)\n * while being defensive against incremental streaming.\n *\n * @example\n * ```ts\n * const acc = new ToolCallAccumulator();\n * acc.process([\n * { function: { name: 'get_weather', arguments: { city: 'Tokyo' } } },\n * ]);\n * acc.process([\n * { function: { name: 'get_weather', arguments: { unit: 'celsius' } } },\n * ]);\n * const result = acc.finalize();\n * // → [{ function: { name: 'get_weather', arguments: { city: 'Tokyo', unit: 'celsius' } } }]\n * ```\n */\nexport class ToolCallAccumulator {\n private readonly entries: ToolCall[] = [];\n\n /**\n * Process a chunk's `tool_calls` array. Entries that match an\n * existing accumulated entry (by id or array position) are merged;\n * new entries are appended.\n *\n * Returns the current accumulated state (a shallow copy — entries\n * themselves are NOT deep-cloned, so callers that mutate\n * `function.arguments` on a returned entry will mutate the\n * accumulator's internal state. Use {@link snapshot} for an\n * explicitly read-only view, or deep-clone the result if you need\n * full isolation).\n */\n process(toolCalls: readonly ToolCall[] | undefined): readonly ToolCall[] {\n if (!toolCalls || toolCalls.length === 0) {\n return [...this.entries];\n }\n\n for (let i = 0; i < toolCalls.length; i++) {\n const incoming = toolCalls[i];\n if (!incoming) continue;\n\n // Find a matching existing entry. We check by id first\n // (the SDK-synthesized stable identifier), then by array\n // position. If neither matches, this is a new call.\n let matchedIndex = -1;\n for (let j = 0; j < this.entries.length; j++) {\n const existing = this.entries[j];\n if (existing && isSameToolCall(existing, incoming, j, i)) {\n matchedIndex = j;\n break;\n }\n }\n\n if (matchedIndex >= 0) {\n // Merge into the existing entry.\n this.entries[matchedIndex] = mergeToolCall(this.entries[matchedIndex]!, incoming);\n } else {\n // New call — append at the end (or at index i if we're\n // preserving positions; we append because the SDK's\n // ToolCall type doesn't guarantee array-position stability\n // across chunks).\n this.entries.push(incoming);\n }\n }\n\n return [...this.entries];\n }\n\n /**\n * Returns the final accumulated tool calls. Identical to calling\n * `process(undefined)` — included for ergonomics so callers can\n * express \"I'm done, give me the result\" without a no-op call.\n *\n * The returned array is a shallow copy; entries themselves are\n * the same object references the accumulator holds internally.\n */\n finalize(): readonly ToolCall[] {\n return [...this.entries];\n }\n\n /**\n * Returns the current accumulated state without modifying the\n * accumulator. Useful for mid-stream inspection.\n *\n * The returned array is a shallow copy; mutating it (e.g.\n * `result.push(...)`) does not affect the accumulator, but\n * mutating an entry's `function.arguments` object DOES affect\n * the accumulator's internal state because the entry reference\n * is shared. Deep-clone the result if you need full isolation.\n */\n snapshot(): readonly ToolCall[] {\n return [...this.entries];\n }\n\n /**\n * Returns the number of accumulated tool calls so far.\n */\n get length(): number {\n return this.entries.length;\n }\n}\n\n/**\n * Convenience function: merge two `tool_calls` arrays using the\n * default accumulator semantics, returning the merged array.\n *\n * Stateless equivalent of:\n *\n * ```ts\n * const acc = new ToolCallAccumulator();\n * acc.process(earlier);\n * acc.process(later);\n * return acc.finalize();\n * ```\n *\n * Useful for one-off merges without instantiating an accumulator.\n */\nexport function mergeToolCallArrays(\n earlier: readonly ToolCall[] | undefined,\n later: readonly ToolCall[] | undefined,\n): readonly ToolCall[] {\n const acc = new ToolCallAccumulator();\n acc.process(earlier);\n acc.process(later);\n return acc.finalize();\n}\n","/**\n * Dual-mode (AsyncIterator and EventEmitter-like) stream wrapper.\n */\n\nimport {\n mapError,\n OllamaAbortError,\n OllamaStreamError,\n type OllamaClientError,\n} from '../errors.js';\nimport type { AbortableAsyncIterable, OllamaStreamEvent, OllamaStreamEventType } from './types.js';\n\n/**\n * Extract accumulated partial content from a stream's intermediate\n * aggregation state, used to enrich {@link OllamaStreamError} when\n * the underlying NDJSON parser detects an in-band `{\"error\": \"...\"}`\n * frame mid-flight.\n *\n * Returns `''` for aggregator states that don't carry content (e.g.\n * progress streams for pull/push). The shape is intentionally a\n * best-effort string extractor — callers who want richer partial\n * state should consume the stream's `on('message', …)` events\n * directly.\n */\nfunction extractPartialContent<TFinal>(accumulated: TFinal): string {\n if (typeof accumulated !== 'object' || accumulated === null) return '';\n const record = accumulated as Record<string, unknown>;\n // ChatStreamResult carries `message.content`.\n const message = record.message;\n if (typeof message === 'object' && message !== null) {\n const content = (message as Record<string, unknown>).content;\n if (typeof content === 'string') return content;\n }\n // GenerateStreamResult carries `response`.\n const response = record.response;\n if (typeof response === 'string') return response;\n // ProgressStreamResult and others don't accumulate content.\n return '';\n}\n\ntype ChunkMapper<TChunk, TFinal> = (\n chunk: TChunk,\n accumulated: TFinal,\n) => Array<OllamaStreamEvent<TChunk, TFinal>>;\n\ntype Aggregator<TChunk, TFinal> = (accumulated: TFinal, chunk: TChunk) => TFinal;\n\ntype Listener<TChunk, TFinal> = (event: OllamaStreamEvent<TChunk, TFinal>) => void;\n\nexport class OllamaStream<TChunk, TFinal> implements AsyncIterable<\n OllamaStreamEvent<TChunk, TFinal>\n> {\n private mode: 'unconsumed' | 'iterator' | 'events' = 'unconsumed';\n private readonly listeners = new Map<string, Set<Listener<TChunk, TFinal>>>();\n private readonly finalResultPromise: Promise<TFinal>;\n private resolveFinal!: (value: TFinal) => void;\n private rejectFinal!: (reason: OllamaClientError) => void;\n private removeAbortListener: (() => void) | undefined;\n\n constructor(\n private readonly source: AbortableAsyncIterable<TChunk>,\n private readonly mapChunk: ChunkMapper<TChunk, TFinal>,\n private readonly aggregate: Aggregator<TChunk, TFinal>,\n private readonly initial: TFinal,\n signal?: AbortSignal,\n ) {\n this.finalResultPromise = new Promise<TFinal>((resolve, reject) => {\n this.resolveFinal = resolve;\n this.rejectFinal = reject;\n });\n\n if (signal !== undefined) {\n const onAbort = (): void => this.abort();\n if (signal.aborted) {\n onAbort();\n } else {\n signal.addEventListener('abort', onAbort, { once: true });\n this.removeAbortListener = () => signal.removeEventListener('abort', onAbort);\n }\n }\n }\n\n get finalResult(): Promise<TFinal> {\n return this.finalResultPromise;\n }\n\n abort(): void {\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.source.abort?.();\n this.rejectFinal(new OllamaAbortError('Ollama stream aborted'));\n }\n\n on<TType extends OllamaStreamEventType>(\n type: TType,\n listener: (event: Extract<OllamaStreamEvent<TChunk, TFinal>, { type: TType }>) => void,\n ): () => void {\n if (this.mode === 'iterator') {\n throw new Error(\n 'Cannot register event listeners: this stream is already being consumed via async iteration.',\n );\n }\n\n const genericListener = listener as Listener<TChunk, TFinal>;\n let set = this.listeners.get(type);\n if (!set) {\n set = new Set();\n this.listeners.set(type, set);\n }\n set.add(genericListener);\n\n if (this.mode !== 'events') {\n this.mode = 'events';\n void this.pump();\n }\n\n return () => {\n set?.delete(genericListener);\n };\n }\n\n private emit(event: OllamaStreamEvent<TChunk, TFinal>): void {\n for (const listener of this.listeners.get(event.type) ?? []) {\n listener(event);\n }\n }\n\n private async pump(): Promise<void> {\n let accumulated = this.initial;\n try {\n for await (const chunk of this.source) {\n accumulated = this.aggregate(accumulated, chunk);\n for (const event of this.mapChunk(chunk, accumulated)) {\n this.emit(event);\n if (event.type === 'done') {\n this.resolveFinal(event.data.result);\n }\n }\n }\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n } catch (error) {\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n // Enrich OllamaStreamError with whatever content was accumulated\n // before the in-band error frame arrived — callers use this for\n // diagnostics (\"what did the model say before it died?\").\n const mapped =\n error instanceof OllamaStreamError && error.partialContent === ''\n ? new OllamaStreamError(error.message, {\n partialContent: extractPartialContent(accumulated),\n cause: error,\n })\n : mapError(error);\n this.emit({ type: 'error', data: { error: mapped } });\n this.rejectFinal(mapped);\n }\n }\n\n async *[Symbol.asyncIterator](): AsyncGenerator<\n OllamaStreamEvent<TChunk, TFinal>,\n void,\n undefined\n > {\n if (this.mode === 'events') {\n throw new Error(\n 'Cannot use async iteration: this stream already has event listeners registered via .on().',\n );\n }\n this.mode = 'iterator';\n let accumulated = this.initial;\n let completed = false;\n try {\n for await (const chunk of this.source) {\n accumulated = this.aggregate(accumulated, chunk);\n const events = this.mapChunk(chunk, accumulated);\n for (const event of events) {\n if (event.type === 'done') {\n completed = true;\n this.resolveFinal(event.data.result);\n }\n yield event;\n }\n }\n } catch (error) {\n // Enrich OllamaStreamError with whatever content was accumulated\n // before the in-band error frame arrived.\n const mapped =\n error instanceof OllamaStreamError && error.partialContent === ''\n ? new OllamaStreamError(error.message, {\n partialContent: extractPartialContent(accumulated),\n cause: error,\n })\n : mapError(error);\n this.rejectFinal(mapped);\n yield { type: 'error', data: { error: mapped } };\n } finally {\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n if (!completed) {\n this.source.abort?.();\n this.rejectFinal(new OllamaAbortError('Ollama stream ended before completion'));\n }\n }\n }\n}\n","/**\n * Normalization mappers and aggregators for Ollama streaming responses.\n */\n\nimport type { ChatResponse, GenerateResponse, ProgressResponse } from '../types.js';\nimport { extractUsage, NANOS_PER_MS } from '../usage.js';\nimport { ensureToolCallIds } from '../tools/tool-call-id.js';\nimport { mergeToolCallArrays } from '../tools/tool-call-accumulator.js';\nimport { OllamaStream } from './stream.js';\nimport type {\n AbortableAsyncIterable,\n ChatStreamResult,\n GenerateStreamResult,\n OllamaStreamEvent,\n ProgressStreamResult,\n} from './types.js';\n\nfunction aggregateChat(accumulated: ChatStreamResult, chunk: ChatResponse): ChatStreamResult {\n const message = chunk.message ?? { role: 'assistant', content: '' };\n return {\n message: {\n role: message.role || accumulated.message.role,\n content: accumulated.message.content + (message.content ?? ''),\n thinking:\n message.thinking !== undefined\n ? (accumulated.message.thinking ?? '') + message.thinking\n : accumulated.message.thinking,\n // Defensive tool-call merging: instead of blindly appending\n // every chunk's tool_calls array (which would produce\n // duplicates if Ollama ever starts streaming them\n // incrementally), merge entries that refer to the same logical\n // call (matched by id or array position). For the documented\n // native behavior (tool_calls arrive complete in one chunk)\n // this is a no-op — the accumulator appends exactly once.\n //\n // See src/tools/tool-call-accumulator.ts for the full merge\n // semantics and the rationale.\n tool_calls:\n message.tool_calls?.length || accumulated.message.tool_calls?.length\n ? mergeToolCallArrays(accumulated.message.tool_calls, message.tool_calls)\n : undefined,\n },\n model: chunk.model,\n done: chunk.done,\n doneReason: chunk.done ? chunk.done_reason : accumulated.doneReason,\n totalDurationMs:\n chunk.done && chunk.total_duration !== undefined\n ? chunk.total_duration / NANOS_PER_MS\n : accumulated.totalDurationMs,\n usage: chunk.done ? extractUsage(chunk) : accumulated.usage,\n raw: chunk,\n };\n}\n\nfunction mapChatChunk(\n chunk: ChatResponse,\n aggregated: ChatStreamResult,\n): Array<OllamaStreamEvent<ChatResponse, ChatStreamResult>> {\n const events: Array<OllamaStreamEvent<ChatResponse, ChatStreamResult>> = [];\n const message = chunk.message;\n\n if (message?.thinking) {\n events.push({ type: 'thinking', data: { delta: message.thinking } });\n }\n for (const toolCall of message?.tool_calls ?? []) {\n events.push({ type: 'tool_call', data: { toolCall } });\n }\n if (message?.content) {\n events.push({ type: 'token', data: { delta: message.content, role: message.role } });\n }\n events.push({ type: 'message', data: { chunk } });\n if (chunk.done) {\n events.push({ type: 'done', data: { result: aggregated } });\n }\n return events;\n}\n\n/**\n * Wraps `source` so every chunk's `message.tool_calls` carries a stable client-synthesized\n * `id` (see `../tools/tool-call-id.js`) before it reaches either the aggregator or the\n * per-chunk event mapper — both read the same chunk object, so ids must be assigned exactly\n * once here rather than independently in each, or the streamed `tool_call` event and the\n * final aggregated message would end up with two different ids for the same call.\n */\nfunction withStableToolCallIds(\n source: AbortableAsyncIterable<ChatResponse>,\n): AbortableAsyncIterable<ChatResponse> {\n async function* generator(): AsyncGenerator<ChatResponse, void, undefined> {\n for await (const chunk of source) {\n const toolCalls = chunk.message?.tool_calls;\n if (!toolCalls?.length) {\n yield chunk;\n continue;\n }\n yield { ...chunk, message: { ...chunk.message, tool_calls: ensureToolCallIds(toolCalls) } };\n }\n }\n return Object.assign(generator(), { abort: source.abort });\n}\n\nexport function normalizeChatStream(\n source: AbortableAsyncIterable<ChatResponse>,\n signal?: AbortSignal,\n): OllamaStream<ChatResponse, ChatStreamResult> {\n const initial: ChatStreamResult = {\n message: { role: 'assistant', content: '' },\n model: '',\n done: false,\n };\n return new OllamaStream(withStableToolCallIds(source), mapChatChunk, aggregateChat, initial, signal);\n}\n\nfunction aggregateGenerate(\n accumulated: GenerateStreamResult,\n chunk: GenerateResponse,\n): GenerateStreamResult {\n return {\n response: accumulated.response + (chunk.response ?? ''),\n model: chunk.model,\n done: chunk.done,\n doneReason: chunk.done ? chunk.done_reason : accumulated.doneReason,\n totalDurationMs:\n chunk.done && chunk.total_duration !== undefined\n ? chunk.total_duration / NANOS_PER_MS\n : accumulated.totalDurationMs,\n usage: chunk.done ? extractUsage(chunk) : accumulated.usage,\n thinking:\n chunk.thinking !== undefined\n ? (accumulated.thinking ?? '') + chunk.thinking\n : accumulated.thinking,\n image: chunk.image ?? accumulated.image,\n completed: chunk.completed ?? accumulated.completed,\n total: chunk.total ?? accumulated.total,\n raw: chunk,\n };\n}\n\nfunction mapGenerateChunk(\n chunk: GenerateResponse,\n aggregated: GenerateStreamResult,\n): Array<OllamaStreamEvent<GenerateResponse, GenerateStreamResult>> {\n const events: Array<OllamaStreamEvent<GenerateResponse, GenerateStreamResult>> = [];\n\n if (chunk.thinking) {\n events.push({ type: 'thinking', data: { delta: chunk.thinking } });\n }\n if (chunk.response) {\n events.push({ type: 'token', data: { delta: chunk.response, role: 'assistant' } });\n }\n events.push({ type: 'message', data: { chunk } });\n if (chunk.done) {\n events.push({ type: 'done', data: { result: aggregated } });\n }\n return events;\n}\n\nexport function normalizeGenerateStream(\n source: AbortableAsyncIterable<GenerateResponse>,\n signal?: AbortSignal,\n): OllamaStream<GenerateResponse, GenerateStreamResult> {\n const initial: GenerateStreamResult = { response: '', model: '', done: false };\n return new OllamaStream(source, mapGenerateChunk, aggregateGenerate, initial, signal);\n}\n\nfunction aggregateProgress(\n _accumulated: ProgressStreamResult,\n chunk: ProgressResponse,\n): ProgressStreamResult {\n return {\n status: chunk.status,\n completed: chunk.completed,\n total: chunk.total,\n done: chunk.status === 'success',\n raw: chunk,\n };\n}\n\nfunction mapProgressChunk(\n chunk: ProgressResponse,\n aggregated: ProgressStreamResult,\n): Array<OllamaStreamEvent<ProgressResponse, ProgressStreamResult>> {\n const events: Array<OllamaStreamEvent<ProgressResponse, ProgressStreamResult>> = [\n { type: 'message', data: { chunk } },\n ];\n if (chunk.status === 'success') {\n events.push({ type: 'done', data: { result: aggregated } });\n }\n return events;\n}\n\nexport function normalizeProgressStream(\n source: AbortableAsyncIterable<ProgressResponse>,\n signal?: AbortSignal,\n): OllamaStream<ProgressResponse, ProgressStreamResult> {\n const initial: ProgressStreamResult = { status: '', done: false };\n return new OllamaStream(source, mapProgressChunk, aggregateProgress, initial, signal);\n}\n","/**\n * Exponential backoff with full jitter calculation.\n */\n\nexport interface BackoffOptions {\n readonly initialDelayMs: number;\n readonly maxDelayMs: number;\n readonly backoffFactor: number;\n}\n\nexport const DEFAULT_BACKOFF: BackoffOptions = {\n initialDelayMs: 500,\n maxDelayMs: 30_000,\n backoffFactor: 2,\n};\n\n/**\n * Calculates exponential backoff with full jitter for attempt (0-indexed).\n */\nexport function calculateBackoff(\n attempt: number,\n options: BackoffOptions = DEFAULT_BACKOFF,\n): number {\n const exponential = options.initialDelayMs * Math.pow(options.backoffFactor, attempt);\n const ceiling = Math.min(exponential, options.maxDelayMs);\n // Full jitter: random duration between 0 and ceiling\n return Math.floor(Math.random() * (ceiling + 1));\n}\n","/**\n * Retry policy and execution runner.\n */\n\nimport { OllamaAbortError, OllamaClientError } from '../errors.js';\nimport { calculateBackoff, type BackoffOptions, DEFAULT_BACKOFF } from './backoff.js';\n\nexport interface RetryConfig {\n readonly maxRetries: number;\n readonly backoff: BackoffOptions;\n readonly shouldRetry?: (error: Error, attempt: number) => boolean;\n readonly onRetry?: (error: Error, attempt: number, delayMs: number) => void;\n}\n\nexport const DEFAULT_RETRY_CONFIG: RetryConfig = {\n maxRetries: 3,\n backoff: DEFAULT_BACKOFF,\n};\n\nfunction isRetryableDefault(error: Error): boolean {\n if (error instanceof OllamaClientError) {\n return error.retryable;\n }\n return false;\n}\n\nfunction abortError(\n signal: AbortSignal | undefined,\n fallbackMessage: string,\n): OllamaAbortError | OllamaClientError {\n const reason = signal?.reason;\n if (reason instanceof OllamaClientError) return reason;\n return new OllamaAbortError(\n reason instanceof Error && reason.message ? reason.message : fallbackMessage,\n { cause: reason },\n );\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortError(signal, 'Retry backoff aborted'));\n return;\n }\n\n const timerId = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = (): void => {\n if (timerId !== undefined) clearTimeout(timerId);\n signal?.removeEventListener('abort', onAbort);\n reject(abortError(signal, 'Retry backoff aborted'));\n };\n\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\n/**\n * Executes an async operation with retries according to config.\n */\nexport async function withRetry<T>(\n operation: (attempt: number) => Promise<T>,\n config: RetryConfig = DEFAULT_RETRY_CONFIG,\n signal?: AbortSignal,\n): Promise<T> {\n let attempt = 0;\n while (true) {\n try {\n return await operation(attempt);\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n const shouldRetry = config.shouldRetry ?? isRetryableDefault;\n if (attempt >= config.maxRetries || !shouldRetry(error, attempt)) {\n throw error;\n }\n const delayMs = calculateBackoff(attempt, config.backoff);\n config.onRetry?.(error, attempt, delayMs);\n await sleep(delayMs, signal);\n attempt += 1;\n }\n }\n}\n","/**\n * AbortSignal and timeout management for HTTP requests.\n */\n\nimport { OllamaTimeoutError } from '../errors.js';\n\nexport interface TimeoutSignal {\n readonly signal: AbortSignal;\n readonly cancel: () => void;\n}\n\n/**\n * Combines an optional timeout with an optional caller-provided AbortSignal.\n */\nexport function createTimeoutSignal(timeoutMs?: number, userSignal?: AbortSignal): TimeoutSignal {\n if (!timeoutMs && !userSignal) {\n const controller = new AbortController();\n return { signal: controller.signal, cancel: () => undefined };\n }\n\n const controller = new AbortController();\n let timerId: ReturnType<typeof setTimeout> | undefined;\n\n if (timeoutMs && timeoutMs > 0) {\n timerId = setTimeout(() => {\n controller.abort(\n new OllamaTimeoutError(`Request timed out after ${timeoutMs}ms`, { timeoutMs }),\n );\n }, timeoutMs);\n }\n\n const onUserAbort = (): void => {\n if (timerId) clearTimeout(timerId);\n controller.abort(userSignal?.reason);\n };\n\n if (userSignal) {\n if (userSignal.aborted) {\n if (timerId) clearTimeout(timerId);\n controller.abort(userSignal.reason);\n } else {\n userSignal.addEventListener('abort', onUserAbort, { once: true });\n }\n }\n\n const cancel = (): void => {\n if (timerId) clearTimeout(timerId);\n if (userSignal) {\n userSignal.removeEventListener('abort', onUserAbort);\n }\n };\n\n return { signal: controller.signal, cancel };\n}\n","/**\n * VRAM lifecycle helpers — ergonomic `keep_alive` primitives.\n *\n * Ollama's `keep_alive` parameter (accepted by `/api/generate`,\n * `/api/chat`, `/api/embed`, `/api/embeddings`, and `/v1/systemone`)\n * controls how long a model remains resident in VRAM after a request\n * completes. The upstream spec defines four operational semantics:\n *\n * - **Duration string** (`\"5m\"`, `\"10s\"`, `\"24h\"`) — explicit window.\n * - **Integer seconds** (`3600`, `300`) — explicit window in seconds.\n * - **Indefinite pinning** (`-1` or `\"-1m\"`) — keep the model\n * permanently resident in VRAM until the server is restarted or\n * an explicit `0` request is made. Useful for hot-loop inference\n * where load latency dominates.\n * - **Immediate eviction** (`0` or `\"0s\"`) — unload the model from\n * VRAM as soon as the response is finalized. Frees GPU memory\n * for the next pipeline (e.g. swap a vision model out before\n * loading an LLM).\n *\n * These primitives let callers express VRAM-lifecycle intent with\n * readable names instead of magic integers, while preserving full\n * backward compatibility with raw `string | number` values.\n *\n * See: https://github.com/ollama/ollama/blob/main/docs/faq.md\n * #how-do-i-keep-a-model-loaded-in-memory-or-make-it-unload-immediately\n */\n\n/**\n * Sentinel value that, when passed as `keep_alive`, instructs the\n * server to evict the model from VRAM as soon as the in-flight\n * request finalizes its response. Equivalent to passing `0` or\n * `\"0s\"`.\n */\nexport const KEEP_ALIVE_UNLOAD = 0 as const;\n\n/**\n * Sentinel value that, when passed as `keep_alive`, instructs the\n * server to keep the model resident in VRAM indefinitely (until\n * the server is restarted or an explicit `0` request arrives).\n * Equivalent to passing `-1` or `\"-1m\"`.\n */\nexport const KEEP_ALIVE_INDEFINITE = -1 as const;\n\n/**\n * Ergonomic union for the `keep_alive` field on chat/generate/embed/\n * embeddings/System One requests.\n *\n * Accepts every upstream-supported shape plus two SDK-level sugar\n * literals:\n *\n * - `'unload'` — same as `0`; frees GPU VRAM after this request.\n * - `'indefinite'` — same as `-1`; pins the model in VRAM until\n * an explicit unload.\n *\n * Use {@link normalizeKeepAlive} to convert this into the raw\n * `string | number` shape the wire expects.\n */\nexport type KeepAlive =\n | string // duration strings like '5m', '24h', '0s', '-1m'\n | number // seconds (300, 0, -1, …)\n | 'unload'\n | 'indefinite';\n\n/**\n * Convert a {@link KeepAlive} value into the raw `string | number`\n * shape Ollama's REST API expects.\n *\n * - `'unload'` → `0` (immediate eviction)\n * - `'indefinite'` → `-1` (perpetual pinning)\n * - everything else is passed through unchanged\n *\n * Returns `undefined` for `undefined` input so callers can pipe\n * optional fields straight through without conditional spreads.\n *\n * @example\n * normalizeKeepAlive('unload') // → 0\n * normalizeKeepAlive('indefinite') // → -1\n * normalizeKeepAlive('5m') // → '5m'\n * normalizeKeepAlive(3600) // → 3600\n * normalizeKeepAlive(undefined) // → undefined\n */\nexport function normalizeKeepAlive(\n keepAlive: KeepAlive | undefined,\n): string | number | undefined {\n if (keepAlive === undefined) return undefined;\n if (keepAlive === 'unload') return KEEP_ALIVE_UNLOAD;\n if (keepAlive === 'indefinite') return KEEP_ALIVE_INDEFINITE;\n return keepAlive;\n}\n\n/**\n * Type guard: `true` when the value is one of the SDK-level sugar\n * literals (`'unload'` or `'indefinite'`). Useful for callers that\n * want to branch on intent rather than magic integers.\n */\nexport function isKeepAliveSugar(\n value: KeepAlive | unknown,\n): value is 'unload' | 'indefinite' {\n return value === 'unload' || value === 'indefinite';\n}\n","/**\n * Model and blob management operations.\n */\n\nimport { listAvailableModels } from './capabilities/capabilities.js';\nimport { OllamaClientError, OllamaNotFoundError } from './errors.js';\nimport { KEEP_ALIVE_INDEFINITE, KEEP_ALIVE_UNLOAD } from './keep-alive.js';\nimport { normalizeProgressStream } from './streaming/normalize.js';\nimport type { OllamaStream } from './streaming/stream.js';\nimport type { ProgressStreamResult } from './streaming/types.js';\nimport type { BinaryBody } from './transport/http.js';\nimport type { RequestRunner } from './transport/runner.js';\nimport type {\n CopyRequestOptions,\n CreateRequestOptions,\n DeleteRequestOptions,\n GenerateResponse,\n ModelResponse,\n ProgressResponse,\n PsResponse,\n PullRequestOptions,\n PushRequestOptions,\n ShowRequestOptions,\n ShowResponse,\n StatusResponse,\n VersionResponse,\n} from './types.js';\n\n/** Result of a convenience blob upload ({@link ModelsClient.createBlobFromData}). */\nexport interface BlobUploadResult {\n /** Content digest (`sha256:<hex>`) of the uploaded payload. */\n readonly digest: string;\n /** True when the server already had this blob (HTTP 200) and skipped writing. */\n readonly alreadyExisted: boolean;\n}\n\n/**\n * Every operation here targets one specific Ollama server's local model catalog or blob\n * store — unlike `chat`/`generate`/`embed`, a different endpoint isn't an interchangeable\n * substitute; it's a different catalog/store entirely. `singleEndpoint: true` disables\n * `OllamaClient`'s cross-endpoint failover for these calls (same-endpoint retry via\n * `withRetry` still applies), so a multi-endpoint setup never silently lists/mutates the\n * wrong server just because the intended one had a transient failure. See ADR 0008.\n */\nexport class ModelsClient {\n constructor(private readonly runner: RequestRunner) {}\n\n list(): Promise<ModelResponse[]> {\n return this.runner((http) => listAvailableModels(http), { singleEndpoint: true });\n }\n\n show(request: ShowRequestOptions): Promise<ShowResponse> {\n return this.runner(\n (http, signal) => http.request<ShowResponse>({ path: '/api/show', body: request, signal }),\n { ...request, singleEndpoint: true },\n );\n }\n\n pull(\n request: PullRequestOptions & { stream: true },\n ): Promise<OllamaStream<ProgressResponse, ProgressStreamResult>>;\n pull(request: PullRequestOptions & { stream?: false | undefined }): Promise<ProgressResponse>;\n pull(\n request: PullRequestOptions,\n ): Promise<ProgressResponse | OllamaStream<ProgressResponse, ProgressStreamResult>>;\n async pull(\n request: PullRequestOptions,\n ): Promise<ProgressResponse | OllamaStream<ProgressResponse, ProgressStreamResult>> {\n if (request.stream) {\n return this.runner(\n async (http, signal) => {\n const stream = await http.requestStream<ProgressResponse>({\n path: '/api/pull',\n body: { ...request, stream: true },\n signal,\n });\n return normalizeProgressStream(stream, signal);\n },\n { ...request, singleEndpoint: true, holdUntil: (stream) => stream.finalResult },\n );\n }\n return this.runner(\n (http, signal) =>\n http.request<ProgressResponse>({\n path: '/api/pull',\n body: { ...request, stream: false },\n signal,\n }),\n { ...request, singleEndpoint: true },\n );\n }\n\n push(\n request: PushRequestOptions & { stream: true },\n ): Promise<OllamaStream<ProgressResponse, ProgressStreamResult>>;\n push(request: PushRequestOptions & { stream?: false | undefined }): Promise<ProgressResponse>;\n push(\n request: PushRequestOptions,\n ): Promise<ProgressResponse | OllamaStream<ProgressResponse, ProgressStreamResult>>;\n async push(\n request: PushRequestOptions,\n ): Promise<ProgressResponse | OllamaStream<ProgressResponse, ProgressStreamResult>> {\n if (request.stream) {\n return this.runner(\n async (http, signal) => {\n const stream = await http.requestStream<ProgressResponse>({\n path: '/api/push',\n body: { ...request, stream: true },\n signal,\n });\n return normalizeProgressStream(stream, signal);\n },\n { ...request, singleEndpoint: true, holdUntil: (stream) => stream.finalResult },\n );\n }\n return this.runner(\n (http, signal) =>\n http.request<ProgressResponse>({\n path: '/api/push',\n body: { ...request, stream: false },\n signal,\n }),\n { ...request, singleEndpoint: true },\n );\n }\n\n create(\n request: CreateRequestOptions & { stream: true },\n ): Promise<OllamaStream<ProgressResponse, ProgressStreamResult>>;\n create(request: CreateRequestOptions & { stream?: false | undefined }): Promise<ProgressResponse>;\n create(\n request: CreateRequestOptions,\n ): Promise<ProgressResponse | OllamaStream<ProgressResponse, ProgressStreamResult>>;\n async create(\n request: CreateRequestOptions,\n ): Promise<ProgressResponse | OllamaStream<ProgressResponse, ProgressStreamResult>> {\n if (request.stream) {\n return this.runner(\n async (http, signal) => {\n const stream = await http.requestStream<ProgressResponse>({\n path: '/api/create',\n body: { ...request, stream: true },\n signal,\n });\n return normalizeProgressStream(stream);\n },\n { ...request, singleEndpoint: true, holdUntil: (stream) => stream.finalResult },\n );\n }\n return this.runner(\n (http, signal) =>\n http.request<ProgressResponse>({\n path: '/api/create',\n body: { ...request, stream: false },\n signal,\n }),\n { ...request, singleEndpoint: true },\n );\n }\n\n delete(request: DeleteRequestOptions): Promise<StatusResponse> {\n return this.runner(\n (http, signal) =>\n http.request<StatusResponse>({\n path: '/api/delete',\n method: 'DELETE',\n body: request,\n signal,\n }),\n { ...request, singleEndpoint: true },\n );\n }\n\n copy(request: CopyRequestOptions): Promise<StatusResponse> {\n return this.runner(\n (http, signal) => http.request<StatusResponse>({ path: '/api/copy', body: request, signal }),\n { ...request, singleEndpoint: true },\n );\n }\n\n ps(): Promise<PsResponse> {\n return this.runner((http) => http.request<PsResponse>({ path: '/api/ps', method: 'GET' }), {\n singleEndpoint: true,\n });\n }\n\n version(): Promise<VersionResponse> {\n return this.runner(\n (http) => http.request<VersionResponse>({ path: '/api/version', method: 'GET' }),\n { singleEndpoint: true },\n );\n }\n\n /**\n * Immediately unloads `model` from VRAM/RAM by issuing an empty\n * `/api/generate` request with `keep_alive: 0`. The server\n * finalizes any in-flight generation, releases the model's\n * weights from GPU memory, and frees the slot for subsequent\n * pipelines (e.g. swap a vision encoder out before loading an\n * LLM).\n *\n * This is the ergonomic equivalent of:\n *\n * ```ts\n * client.generate({ model, prompt: '', keep_alive: 0 });\n * ```\n *\n * Use {@link pin} for the opposite lifecycle — pinning a model\n * indefinitely in VRAM for hot-loop inference.\n *\n * Resolves once the server acknowledges the unload. The promise\n * rejects on transport errors, model-not-found (404), or auth\n * failures — callers handling transient issues can retry via the\n * standard {@link withRetry} policy.\n *\n * See: https://github.com/ollama/ollama/blob/main/docs/faq.md\n * #how-do-i-keep-a-model-loaded-in-memory-or-make-it-unload-immediately\n */\n async unload(model: string): Promise<void> {\n await this.runner(\n (http, signal) =>\n http.request<GenerateResponse>({\n path: '/api/generate',\n body: { model, prompt: '', keep_alive: KEEP_ALIVE_UNLOAD, stream: false },\n signal,\n }),\n { model, singleEndpoint: true },\n );\n }\n\n /**\n * Pre-loads and pins `model` into VRAM indefinitely by issuing an\n * empty `/api/generate` request with `keep_alive: -1`. The server\n * loads the model into GPU memory (paying the cold-load latency\n * once) and keeps it resident until either:\n *\n * - an explicit {@link unload} call is made,\n * - the server process is restarted, or\n * - the host runs out of VRAM and the server's own eviction\n * policy kicks in.\n *\n * This is the ergonomic equivalent of:\n *\n * ```ts\n * client.generate({ model, prompt: '', keep_alive: -1 });\n * ```\n *\n * Use {@link unload} to release the pinned slot when the hot loop\n * is done — leaving models pinned indefinitely exhausts VRAM and\n * starves subsequent pipelines.\n *\n * Resolves once the server acknowledges the pin (i.e. the model\n * is fully loaded). The promise rejects on transport errors,\n * model-not-found (404), or VRAM-exhaustion failures.\n */\n async pin(model: string): Promise<void> {\n await this.runner(\n (http, signal) =>\n http.request<GenerateResponse>({\n path: '/api/generate',\n body: { model, prompt: '', keep_alive: KEEP_ALIVE_INDEFINITE, stream: false },\n signal,\n }),\n { model, singleEndpoint: true },\n );\n }\n\n async createBlob(digest: string, data: BinaryBody): Promise<void> {\n await this.runner(\n (http, signal) =>\n http.request<void>({\n path: `/api/blobs/${encodeURIComponent(digest)}`,\n method: 'POST',\n rawBody: data,\n signal,\n }),\n { singleEndpoint: true },\n );\n }\n\n async checkBlob(digest: string): Promise<boolean> {\n // Wave 12 (P2): previously this method caught every error and returned\n // false, which conflated \"blob absent\" (HTTP 404) with auth failures\n // (401/403), rate limits (429), server errors (5xx), network failures,\n // timeouts, and aborts. Callers had no way to distinguish \"the blob\n // doesn't exist\" from \"the server is unreachable\" — both looked like\n // `false`. That's a real SDK correctness issue: a transient network\n // blip would silently look like a missing blob, and a downstream\n // caller would proceed to re-upload (potentially burning bandwidth\n // and quota on a blob that was already there).\n //\n // Only HTTP 404 means \"blob absent.\" Everything else propagates so\n // callers can branch on the actual failure mode. The OllamaNotFoundError\n // class is what HttpClient throws for 404s (see src/errors.ts).\n try {\n await this.runner(\n (http, signal) =>\n http.request<void>({\n path: `/api/blobs/${encodeURIComponent(digest)}`,\n method: 'HEAD',\n signal,\n }),\n { singleEndpoint: true },\n );\n return true;\n } catch (err) {\n if (err instanceof OllamaNotFoundError) return false;\n throw err;\n }\n }\n\n /**\n * Computes a blob digest the way Ollama's content-addressed store expects:\n * SHA-256 over the raw bytes, formatted as `sha256:<64 lowercase hex>`.\n *\n * Uses the Web Crypto API (`crypto.subtle.digest`), which exists in every\n * supported runtime — Node.js ≥ 19 exposes it as a global (this SDK\n * requires Node ≥ 20), and browsers/edge runtimes have always had it.\n */\n async computeBlobDigest(data: Uint8Array): Promise<string> {\n // Minimal structural type for Web Crypto's SubtleCrypto.digest — declared\n // locally because this project's `lib` is ES2022-only (no DOM types),\n // while Node ≥ 20 and every browser expose `crypto.subtle` as a global.\n const subtle = (\n globalThis as {\n crypto?:\n | {\n subtle?:\n | {\n digest(\n algorithm: 'SHA-256',\n data: ArrayBufferView | ArrayBuffer,\n ): Promise<ArrayBuffer>;\n }\n | undefined;\n }\n | undefined;\n }\n ).crypto?.subtle;\n if (subtle === undefined) {\n throw new OllamaClientError(\n 'computeBlobDigest requires the Web Crypto API (crypto.subtle), unavailable in this runtime.',\n { code: 'crypto_unavailable' },\n );\n }\n const digestBytes = await subtle.digest('SHA-256', data as unknown as ArrayBuffer);\n const hex = Array.from(new Uint8Array(digestBytes), (byte) =>\n byte.toString(16).padStart(2, '0'),\n ).join('');\n return `sha256:${hex}`;\n }\n\n /**\n * Computes the SHA-256 digest of `data` and pushes it as a blob in one\n * step — the content-addressed upload Ollama's own tooling performs\n * (`curl -T file http://…/api/blobs/sha256:…`). Returns the digest, which\n * `/api/create`'s `files` field references.\n *\n * Pass `digest` to skip recomputation when the caller already knows it —\n * the server verifies the content against the digest and rejects mismatches.\n */\n async createBlobFromData(\n data: Uint8Array,\n opts?: { readonly digest?: string | undefined; readonly signal?: AbortSignal | undefined },\n ): Promise<BlobUploadResult> {\n const digest = opts?.digest ?? (await this.computeBlobDigest(data));\n const alreadyExisted = await this.checkBlob(digest);\n if (!alreadyExisted) {\n await this.createBlob(digest, data);\n }\n return { digest, alreadyExisted };\n }\n\n /**\n * Reads a local file and uploads it as a blob (Node.js only — dynamic\n * `node:fs` import, so browser bundles never pull it in). The file name\n * (basename) is what `/api/create`'s `files` map expects as the key, so\n * this returns it alongside the digest.\n */\n async createBlobFromFile(\n path: string,\n opts?: { readonly signal?: AbortSignal | undefined },\n ): Promise<BlobUploadResult & { readonly fileName: string }> {\n // Specifier hidden behind a variable so browser/edge bundlers never try\n // to resolve `node:fs` at build time — see src/vision.ts NODE_FS_MODULE.\n const nodeFsModule = 'node:fs';\n const { promises: fs } = (await import(nodeFsModule)) as typeof import('node:fs');\n const data = await fs.readFile(path);\n const result = await this.createBlobFromData(new Uint8Array(data), {\n ...opts,\n });\n const fileName = path.split(/[\\\\/]/).pop() ?? path;\n return { ...result, fileName };\n }\n\n /**\n * One-shot custom-model publishing from raw GGUF weights, following the\n * protocol Ollama's API reference documents: push a blob for the GGUF\n * bytes, then `POST /api/create` with `files: { <fileName>: <digest> }`.\n * Split GGUFs are supported via `files` — pass every shard's path.\n *\n * ```ts\n * await client.models.createModelFromGguf('my-model', '/path/to/model.gguf', {\n * template: '{{ .Prompt }}',\n * });\n * ```\n *\n * @param model Name for the new model (e.g. `'my-model:latest'`).\n * @param gguf Path(s) to GGUF file(s) on the local filesystem.\n * @param opts Everything else `/api/create` accepts (`template`, `system`,\n * `parameters`, `license`, `quantize`, …) except `files` and `from`.\n */\n async createModelFromGguf(\n model: string,\n gguf: string | readonly string[],\n opts?: Omit<CreateRequestOptions, 'model' | 'files' | 'from' | 'stream'>,\n ): Promise<ProgressResponse> {\n const paths = typeof gguf === 'string' ? [gguf] : gguf;\n if (paths.length === 0) {\n throw new OllamaClientError('createModelFromGguf: at least one GGUF path is required.', {\n code: 'invalid_request',\n });\n }\n const files: Record<string, string> = {};\n for (const path of paths) {\n const uploaded = await this.createBlobFromFile(path, { signal: opts?.signal });\n files[uploaded.fileName] = uploaded.digest;\n }\n const {\n model: _model,\n files: _files,\n from: _from,\n stream: _stream,\n ...rest\n } = (opts ?? {}) as CreateRequestOptions;\n return this.create({ ...rest, model, files, stream: false } as CreateRequestOptions & {\n stream: false;\n });\n }\n}\n","/**\n * OpenAI Compatibility interfaces and client helpers for Ollama.\n * Ollama exposes OpenAI-compatible /v1 endpoints.\n *\n * @remarks\n * This is a typed pass-through to Ollama's own OpenAI-compatible `/v1` endpoints — it\n * implements the subset of the OpenAI API surface that Ollama documents as supported\n * (https://docs.ollama.com/api/openai-compatibility), not the full OpenAI surface (hosted\n * tools like web/file search, computer use, code interpreter, or stateful server-side\n * conversation state). Notably, `tools` is supported by Ollama's compat layer but\n * `tool_choice` and `parallel_tool_calls` are not — both are still typed on\n * {@link OpenAIChatCompletionRequest} (accepted-but-ignored) so consumers passing a\n * standard OpenAI request object don't get spurious type errors; see the `@remarks` on\n * each field. `/v1/responses` is supported non-statefully — see\n * {@link OpenAIResponsesRequest}.\n */\n\nimport type { AbortableAsyncIterable } from '../streaming/types.js';\nimport type { SseEvent } from '../streaming/sse.js';\nimport type { HttpClient } from '../transport/http.js';\nimport type { RequestRunner } from '../transport/runner.js';\nimport { OllamaAbortError, OllamaClientError } from '../errors.js';\n\nexport interface OpenAIToolCall {\n readonly id: string;\n readonly type: 'function';\n readonly function: {\n readonly name: string;\n /** JSON-encoded arguments string, matching OpenAI's wire format (not a parsed object). */\n readonly arguments: string;\n };\n}\n\nexport interface OpenAITextContentPart {\n readonly type: 'text';\n readonly text: string;\n}\n\nexport interface OpenAIImageUrlContentPart {\n readonly type: 'image_url';\n /** Ollama accepts a data/image URL string or the standard OpenAI URL object. */\n readonly image_url:\n | string\n | { readonly url: string; readonly detail?: 'auto' | 'low' | 'high' | 'original' | undefined };\n}\n\nexport type OpenAIContentPart = OpenAITextContentPart | OpenAIImageUrlContentPart;\n\nexport interface OpenAIMessage {\n readonly role: 'system' | 'user' | 'assistant' | 'tool';\n readonly content: string | readonly OpenAIContentPart[];\n readonly name?: string | undefined;\n readonly tool_calls?: readonly OpenAIToolCall[] | undefined;\n /** Ollama may emit model reasoning alongside assistant content. */\n readonly reasoning?: string | undefined;\n /** Set on a `role: 'tool'` message to identify which call this is a result for. */\n readonly tool_call_id?: string | undefined;\n}\n\nexport interface OpenAIStreamOptions {\n /** Emit a final SSE chunk carrying `usage` (prompt/completion/total tokens) before `[DONE]`. */\n readonly include_usage?: boolean | undefined;\n}\n\nexport interface OpenAIFunctionDefinition {\n readonly name: string;\n readonly description?: string | undefined;\n readonly parameters?: Record<string, unknown> | undefined;\n}\n\nexport interface OpenAITool {\n readonly type: 'function';\n readonly function: OpenAIFunctionDefinition;\n}\n\nexport type OpenAIReasoningEffort =\n | 'high'\n | 'medium'\n | 'low'\n | 'max'\n | 'none'\n | 'minimal'\n | 'xhigh'\n | 'ultra'\n | (string & {});\n\nexport type OpenAIResponseFormat =\n | { readonly type: 'text' }\n | { readonly type: 'json_object' }\n | { readonly type: 'json_schema'; readonly json_schema: Record<string, unknown> };\n\nexport interface OpenAIChatCompletionRequest {\n readonly model: string;\n readonly messages: readonly OpenAIMessage[];\n readonly temperature?: number | undefined;\n readonly top_p?: number | undefined;\n readonly stream?: boolean | undefined;\n /** Only meaningful when `stream: true`; ignored otherwise. */\n readonly stream_options?: OpenAIStreamOptions | undefined;\n readonly max_tokens?: number | undefined;\n readonly stop?: readonly string[] | undefined;\n readonly response_format?: OpenAIResponseFormat | undefined;\n readonly seed?: number | undefined;\n readonly presence_penalty?: number | undefined;\n readonly frequency_penalty?: number | undefined;\n readonly user?: string | undefined;\n readonly logit_bias?: Record<string, number> | undefined;\n readonly n?: number | undefined;\n /** Ollama exposes log probabilities for supported reasoning/chat models. */\n readonly logprobs?: boolean | undefined;\n readonly top_logprobs?: number | undefined;\n readonly tools?: readonly OpenAITool[] | undefined;\n /**\n * @remarks Accepted for OpenAI compatibility but ignored by Ollama — every tool the\n * model is given remains callable regardless of this value.\n */\n readonly tool_choice?:\n | 'none'\n | 'auto'\n | 'required'\n | { readonly type: 'function'; readonly function: { readonly name: string } }\n | undefined;\n /**\n * @remarks Accepted for OpenAI compatibility but ignored by Ollama — Ollama does not\n * control tool-call parallelism through this flag.\n */\n readonly parallel_tool_calls?: boolean | undefined;\n /**\n * Effort level for thinking models (e.g. `deepseek-r1`, `qwen3`). Equivalent to\n * `reasoning.effort`; only effective for models that support reasoning/thinking.\n */\n readonly reasoning_effort?: OpenAIReasoningEffort | undefined;\n /**\n * Effort level for thinking models (e.g. `deepseek-r1`, `qwen3`), nested OpenAI-style.\n * Equivalent to `reasoning_effort`; only effective for models that support\n * reasoning/thinking.\n */\n readonly reasoning?:\n { readonly effort?: OpenAIReasoningEffort | undefined } | undefined;\n}\n\n/** Ollama Chat Completions supports text plus base64 image content via a string image URL. */\nexport type OllamaOpenAIChatContentPart =\n | OpenAITextContentPart\n | {\n readonly type: 'image_url';\n /** Ollama's current compatibility docs accept an image URL string, including data URLs. */\n readonly image_url: string;\n };\n\nexport type OllamaOpenAIReasoningEffort =\n | 'high'\n | 'medium'\n | 'low'\n | 'max'\n | 'none';\n\nexport type OllamaOpenAIChatMessage = Omit<OpenAIMessage, 'content'> & {\n readonly content: string | readonly OllamaOpenAIChatContentPart[];\n};\n\n/** Strict Ollama-documented Chat Completions request; excludes only the SDK-only parallel tool flag. */\nexport type OllamaOpenAIChatCompletionRequest = Omit<\n OpenAIChatCompletionRequest,\n 'messages' | 'parallel_tool_calls' | 'reasoning_effort' | 'reasoning'\n> & {\n readonly messages: readonly OllamaOpenAIChatMessage[];\n readonly reasoning_effort?: OllamaOpenAIReasoningEffort | undefined;\n readonly reasoning?: { readonly effort?: OllamaOpenAIReasoningEffort | undefined } | undefined;\n};\n\nexport interface OpenAIChatCompletionChoice {\n readonly index: number;\n readonly message: OpenAIMessage;\n readonly finish_reason: string;\n readonly logprobs?: Record<string, unknown> | null | undefined;\n}\n\nexport interface OpenAIToolCallDelta {\n readonly index: number;\n readonly id?: string | undefined;\n readonly type?: 'function' | undefined;\n readonly function?: {\n readonly name?: string | undefined;\n readonly arguments?: string | undefined;\n } | undefined;\n}\n\nexport interface OpenAIChatCompletionDelta {\n readonly role?: OpenAIMessage['role'] | undefined;\n readonly content?: string | null | undefined;\n readonly reasoning?: string | null | undefined;\n readonly refusal?: string | null | undefined;\n readonly tool_calls?: readonly OpenAIToolCallDelta[] | undefined;\n}\n\nexport interface OpenAIChatCompletionChunkChoice {\n readonly index: number;\n readonly delta: OpenAIChatCompletionDelta;\n readonly finish_reason?: string | null | undefined;\n readonly logprobs?: Record<string, unknown> | null | undefined;\n}\n\nexport interface OpenAIChatCompletionChunk {\n readonly id: string;\n readonly object: 'chat.completion.chunk';\n readonly created: number;\n readonly model: string;\n readonly system_fingerprint?: string | undefined;\n readonly choices: readonly OpenAIChatCompletionChunkChoice[];\n readonly usage?:\n | {\n readonly prompt_tokens: number;\n readonly completion_tokens: number;\n readonly total_tokens: number;\n }\n | null\n | undefined;\n}\n\nexport interface OpenAIUsage {\n readonly prompt_tokens: number;\n readonly completion_tokens: number;\n readonly total_tokens: number;\n readonly prompt_tokens_details?: {\n readonly cached_tokens?: number | undefined;\n } | undefined;\n}\n\nexport interface OpenAIChatCompletionResponse {\n readonly id: string;\n readonly object: 'chat.completion';\n readonly created: number;\n readonly model: string;\n readonly system_fingerprint?: string | undefined;\n readonly choices: readonly OpenAIChatCompletionChoice[];\n readonly usage?: OpenAIUsage | undefined;\n}\n\nexport interface OpenAIModelItem {\n readonly id: string;\n readonly object: 'model';\n readonly created: number;\n readonly owned_by: string;\n}\n\nexport interface OpenAIListModelsResponse {\n readonly object: 'list';\n readonly data: readonly OpenAIModelItem[];\n}\n\nexport interface OpenAICompletionRequest {\n readonly model: string;\n /** Ollama currently accepts a string prompt for /v1/completions. */\n readonly prompt: string;\n /** Number of log probability alternatives requested for completion tokens. */\n readonly logprobs?: number | undefined;\n readonly frequency_penalty?: number | undefined;\n readonly presence_penalty?: number | undefined;\n readonly seed?: number | undefined;\n readonly stop?: readonly string[] | undefined;\n readonly stream?: boolean | undefined;\n readonly stream_options?: OpenAIStreamOptions | undefined;\n readonly temperature?: number | undefined;\n readonly top_p?: number | undefined;\n readonly max_tokens?: number | undefined;\n readonly suffix?: string | undefined;\n readonly best_of?: number | undefined;\n readonly echo?: boolean | undefined;\n readonly logit_bias?: Record<string, number> | undefined;\n readonly user?: string | undefined;\n readonly n?: number | undefined;\n}\n\n/** Strict Ollama-documented Completions request. */\nexport type OllamaOpenAICompletionRequest = OpenAICompletionRequest;\n\nexport interface OpenAICompletionChoice {\n readonly text: string;\n readonly index: number;\n readonly logprobs?: Record<string, unknown> | null | undefined;\n readonly finish_reason: string | null;\n}\n\nexport interface OpenAICompletionChunk {\n readonly id: string;\n readonly object: 'text_completion';\n readonly created: number;\n readonly model: string;\n readonly system_fingerprint?: string | undefined;\n readonly choices: readonly {\n readonly text: string;\n readonly index: number;\n readonly logprobs?: Record<string, unknown> | null | undefined;\n readonly finish_reason?: string | null | undefined;\n }[];\n readonly usage?:\n | {\n readonly prompt_tokens: number;\n readonly completion_tokens: number;\n readonly total_tokens: number;\n }\n | null\n | undefined;\n}\n\nexport interface OpenAICompletionResponse {\n readonly id: string;\n readonly object: 'text_completion';\n readonly created: number;\n readonly model: string;\n readonly system_fingerprint?: string | undefined;\n readonly choices: readonly OpenAICompletionChoice[];\n readonly usage?: OpenAIUsage | undefined;\n}\n\nexport type OpenAIEmbeddingInput =\n | string\n | readonly string[]\n | readonly number[]\n | readonly (readonly number[])[];\n\nexport interface OpenAIEmbeddingRequest {\n readonly model: string;\n readonly input: OpenAIEmbeddingInput;\n readonly encoding_format?: 'float' | 'base64' | undefined;\n readonly dimensions?: number | undefined;\n readonly user?: string | undefined;\n}\n\n/** Strict Ollama-documented Embeddings request. */\nexport type OllamaOpenAIEmbeddingRequest = OpenAIEmbeddingRequest;\n\nexport interface OpenAIEmbeddingItem {\n readonly object: 'embedding';\n readonly embedding: readonly number[] | string;\n readonly index: number;\n}\n\nexport interface OpenAIEmbeddingResponse {\n readonly object: 'list';\n readonly data: readonly OpenAIEmbeddingItem[];\n readonly model: string;\n readonly usage?: {\n readonly prompt_tokens: number;\n readonly total_tokens: number;\n } | undefined;\n}\n\n/**\n * Request body for OpenAI's Responses API (`/v1/responses`), added in Ollama v0.13.3.\n *\n * @remarks\n * Ollama implements this **non-statefully**: every call is independent, so\n * {@link previous_response_id} and {@link conversation} — OpenAI's mechanisms for\n * resuming server-side conversation state — are accepted for compatibility but ignored.\n * Send the full conversation in `input` on every call, the same as `/api/chat`.\n */\nexport interface OpenAIResponsesRequest {\n readonly model: string;\n readonly input: string | readonly OpenAIMessage[];\n readonly instructions?: string | undefined;\n readonly tools?: readonly OpenAITool[] | undefined;\n readonly stream?: boolean | undefined;\n readonly temperature?: number | undefined;\n readonly top_p?: number | undefined;\n readonly max_output_tokens?: number | undefined;\n /** @remarks Not supported by Ollama, which is stateless across calls — accepted but ignored. */\n readonly previous_response_id?: string | undefined;\n /** @remarks Not supported by Ollama, which is stateless across calls — accepted but ignored. */\n readonly conversation?: string | undefined;\n readonly truncation?: string | undefined;\n readonly reasoning?: { readonly effort?: OpenAIReasoningEffort | undefined } | undefined;\n /** Ollama extension: boolean, model-defined string, or null for model default. */\n readonly think?: boolean | string | null | undefined;\n}\n\n/** Strict Ollama-documented Responses request; excludes stateful and SDK-only request fields. */\n/** Strict Ollama-documented Responses request; excludes only unsupported stateful fields. */\nexport type OllamaOpenAIResponsesRequest = Omit<\n OpenAIResponsesRequest,\n 'previous_response_id' | 'conversation'\n>;\n\nexport type OpenAIResponsesStatus = 'completed' | 'failed' | 'in_progress' | 'cancelled' | 'queued' | 'incomplete';\n\nexport interface OpenAIResponsesError { readonly code?: string | undefined; readonly message?: string | undefined; readonly [key: string]: unknown; }\nexport interface OpenAIResponsesIncompleteDetails { readonly reason?: string | undefined; readonly [key: string]: unknown; }\n\nexport interface OpenAIResponsesOutputTextContent {\n readonly type: 'output_text'; readonly text: string;\n readonly annotations?: readonly Record<string, unknown>[] | undefined;\n readonly logprobs?: readonly Record<string, unknown>[] | undefined;\n}\nexport interface OpenAIResponsesOutputRefusal { readonly type: 'refusal'; readonly refusal: string; }\nexport type OpenAIResponsesOutputContent = OpenAIResponsesOutputTextContent | OpenAIResponsesOutputRefusal;\n\nexport interface OpenAIResponsesOutputMessage {\n readonly type: 'message'; readonly id?: string | undefined; readonly status?: OpenAIResponsesStatus | undefined;\n readonly role?: string | undefined; readonly phase?: string | undefined;\n readonly content: readonly OpenAIResponsesOutputContent[];\n}\nexport interface OpenAIResponsesOutputFunctionCall {\n readonly type: 'function_call'; readonly id?: string | undefined; readonly call_id?: string | undefined;\n readonly name: string; readonly arguments: string; readonly status?: OpenAIResponsesStatus | undefined;\n}\nexport interface OpenAIResponsesOutputReasoning {\n readonly type: 'reasoning'; readonly id?: string | undefined; readonly status?: OpenAIResponsesStatus | undefined;\n readonly summary?: readonly { readonly type: 'summary_text'; readonly text: string }[] | undefined;\n readonly text?: string | undefined; readonly encrypted_content?: string | undefined;\n}\nexport type OpenAIResponsesOutputItem = OpenAIResponsesOutputMessage | OpenAIResponsesOutputFunctionCall | OpenAIResponsesOutputReasoning;\n\nexport interface OpenAIResponsesUsage {\n readonly input_tokens: number; readonly output_tokens: number; readonly total_tokens: number;\n readonly input_tokens_details?: Record<string, unknown> | undefined;\n readonly output_tokens_details?: Record<string, unknown> | undefined;\n}\n\n/** Non-stateful response shape for the Ollama Responses compatibility endpoint. */\nexport interface OpenAIResponsesResponse {\n readonly id: string; readonly object: 'response'; readonly created: number;\n readonly created_at?: number | undefined; readonly status?: OpenAIResponsesStatus | undefined;\n readonly completed_at?: number | null | undefined; readonly error?: OpenAIResponsesError | null | undefined;\n readonly incomplete_details?: OpenAIResponsesIncompleteDetails | null | undefined;\n readonly model: string; readonly output: readonly OpenAIResponsesOutputItem[];\n readonly output_text?: string | undefined; readonly previous_response_id?: string | null | undefined;\n readonly parallel_tool_calls?: boolean | undefined; readonly usage?: OpenAIResponsesUsage | undefined;\n}\n\nexport class OpenAIResponsesStreamError extends OllamaClientError {\n readonly responsePayload: OpenAIResponsesResponse;\n constructor(message: string, responsePayload: OpenAIResponsesResponse) {\n super(message, { code: 'openai_responses_stream_error', retryable: false, response: { body: responsePayload } });\n this.responsePayload = responsePayload;\n }\n}\nexport class OpenAIChatCompletionStream implements AsyncIterable<OpenAIChatCompletionChunk> {\n private readonly finalResultPromise: Promise<OpenAIChatCompletionResponse>;\n private resolveFinal!: (value: OpenAIChatCompletionResponse) => void;\n private rejectFinal!: (reason: unknown) => void;\n private removeAbortListener: (() => void) | undefined;\n\n constructor(private readonly source: AbortableAsyncIterable<SseEvent>, signal?: AbortSignal) {\n this.finalResultPromise = new Promise<OpenAIChatCompletionResponse>((resolve, reject) => {\n this.resolveFinal = resolve;\n this.rejectFinal = reject;\n });\n if (signal !== undefined) {\n const onAbort = (): void => this.abort();\n if (signal.aborted) onAbort();\n else {\n signal.addEventListener('abort', onAbort, { once: true });\n this.removeAbortListener = () => signal.removeEventListener('abort', onAbort);\n }\n }\n }\n\n get finalResult(): Promise<OpenAIChatCompletionResponse> {\n return this.finalResultPromise;\n }\n\n abort(): void {\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.source.abort?.();\n this.rejectFinal(new OllamaAbortError('OpenAI Chat Completion stream aborted'));\n }\n\n async *[Symbol.asyncIterator](): AsyncGenerator<OpenAIChatCompletionChunk, void, undefined> {\n const choices = new Map<number, {\n message: OpenAIMessage;\n finish_reason: string;\n logprobs?: Record<string, unknown> | null | undefined;\n }>();\n let id = '';\n let model = '';\n let created = 0;\n let systemFingerprint: string | undefined;\n let usage: OpenAIUsage | undefined;\n let completed = false;\n\n try {\n for await (const event of this.source) {\n if (event.data === '[DONE]') break;\n let chunk: OpenAIChatCompletionChunk;\n try {\n chunk = JSON.parse(event.data) as OpenAIChatCompletionChunk;\n } catch (error) {\n throw new Error('Failed to parse OpenAI chat completion SSE payload', { cause: error });\n }\n id = chunk.id || id;\n model = chunk.model || model;\n created = chunk.created || created;\n if (chunk.system_fingerprint !== undefined) systemFingerprint = chunk.system_fingerprint;\n if (chunk.usage !== null && chunk.usage !== undefined) usage = chunk.usage;\n\n for (const choice of chunk.choices) {\n const existing = choices.get(choice.index);\n const delta = choice.delta;\n if (!existing) {\n const toolCalls = delta.tool_calls?.map((toolCall) => ({\n id: toolCall.id ?? '',\n type: 'function' as const,\n function: {\n name: toolCall.function?.name ?? '',\n arguments: toolCall.function?.arguments ?? '',\n },\n }));\n choices.set(choice.index, {\n message: {\n role: delta.role ?? 'assistant',\n content: delta.content ?? '',\n ...(delta.reasoning !== undefined && delta.reasoning !== null\n ? { reasoning: delta.reasoning }\n : {}),\n ...(toolCalls?.length ? { tool_calls: toolCalls } : {}),\n },\n finish_reason: choice.finish_reason ?? '',\n ...(choice.logprobs !== undefined ? { logprobs: choice.logprobs } : {}),\n });\n continue;\n }\n\n const priorToolCalls = [...(existing.message.tool_calls ?? [])];\n for (const toolCall of delta.tool_calls ?? []) {\n const position = toolCall.index;\n const current = priorToolCalls[position];\n if (current) {\n priorToolCalls[position] = {\n ...current,\n ...(toolCall.id !== undefined ? { id: toolCall.id } : {}),\n function: {\n name: current.function?.name ?? toolCall.function?.name ?? '',\n arguments:\n (current.function?.arguments ?? '') + (toolCall.function?.arguments ?? ''),\n },\n };\n } else {\n priorToolCalls[position] = {\n id: toolCall.id ?? '',\n type: 'function',\n function: {\n name: toolCall.function?.name ?? '',\n arguments: toolCall.function?.arguments ?? '',\n },\n };\n }\n }\n choices.set(choice.index, {\n message: {\n ...existing.message,\n ...(delta.content !== undefined && delta.content !== null\n ? { content: existing.message.content + delta.content }\n : {}),\n ...(delta.reasoning !== undefined && delta.reasoning !== null\n ? { reasoning: (existing.message.reasoning ?? '') + delta.reasoning }\n : {}),\n ...(priorToolCalls.length ? { tool_calls: priorToolCalls } : {}),\n },\n finish_reason: choice.finish_reason ?? existing.finish_reason,\n ...(choice.logprobs !== undefined ? { logprobs: choice.logprobs } : {}),\n });\n }\n\n yield chunk;\n }\n\n const response: OpenAIChatCompletionResponse = {\n id,\n object: 'chat.completion',\n created,\n model,\n ...(systemFingerprint !== undefined ? { system_fingerprint: systemFingerprint } : {}),\n choices: [...choices.entries()]\n .sort(([a], [b]) => a - b)\n .map(([index, choice]) => ({\n index,\n message: choice.message,\n finish_reason: choice.finish_reason,\n ...(choice.logprobs !== undefined ? { logprobs: choice.logprobs } : {}),\n })),\n ...(usage !== undefined ? { usage } : {}),\n };\n completed = true;\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.resolveFinal(response);\n } catch (error) {\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.rejectFinal(error);\n throw error;\n } finally {\n if (!completed) {\n this.source.abort?.();\n this.rejectFinal(new OllamaAbortError('OpenAI Chat Completion stream ended before completion'));\n }\n }\n }\n}\n\nexport class OpenAICompletionStream implements AsyncIterable<OpenAICompletionChunk> {\n private readonly finalResultPromise: Promise<OpenAICompletionResponse>;\n private resolveFinal!: (value: OpenAICompletionResponse) => void;\n private rejectFinal!: (reason: unknown) => void;\n private removeAbortListener: (() => void) | undefined;\n\n constructor(private readonly source: AbortableAsyncIterable<SseEvent>, signal?: AbortSignal) {\n this.finalResultPromise = new Promise<OpenAICompletionResponse>((resolve, reject) => {\n this.resolveFinal = resolve;\n this.rejectFinal = reject;\n });\n if (signal !== undefined) {\n const onAbort = (): void => this.abort();\n if (signal.aborted) onAbort();\n else {\n signal.addEventListener('abort', onAbort, { once: true });\n this.removeAbortListener = () => signal.removeEventListener('abort', onAbort);\n }\n }\n }\n\n get finalResult(): Promise<OpenAICompletionResponse> {\n return this.finalResultPromise;\n }\n\n abort(): void {\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.source.abort?.();\n this.rejectFinal(new OllamaAbortError('OpenAI Completion stream aborted'));\n }\n\n async *[Symbol.asyncIterator](): AsyncGenerator<OpenAICompletionChunk, void, undefined> {\n const texts = new Map<number, OpenAICompletionChoice>();\n let id = '';\n let model = '';\n let created = 0;\n let usage:\n | { prompt_tokens: number; completion_tokens: number; total_tokens: number }\n | undefined;\n let completed = false;\n\n try {\n for await (const event of this.source) {\n if (event.data === '[DONE]') break;\n const chunk = JSON.parse(event.data) as OpenAICompletionChunk;\n id = chunk.id || id;\n model = chunk.model || model;\n created = chunk.created || created;\n if (chunk.usage !== null && chunk.usage !== undefined) usage = chunk.usage;\n\n for (const choice of chunk.choices) {\n const existing = texts.get(choice.index);\n texts.set(choice.index, {\n text: (existing?.text ?? '') + (choice.text ?? ''),\n index: choice.index,\n finish_reason: choice.finish_reason ?? existing?.finish_reason ?? null,\n ...(choice.logprobs !== undefined ? { logprobs: choice.logprobs } : {}),\n });\n }\n yield chunk;\n }\n\n const response: OpenAICompletionResponse = {\n id,\n object: 'text_completion',\n created,\n model,\n choices: [...texts.values()].sort((a, b) => a.index - b.index),\n ...(usage !== undefined ? { usage } : {}),\n };\n completed = true;\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.resolveFinal(response);\n } catch (error) {\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.rejectFinal(error);\n throw error;\n } finally {\n if (!completed) {\n this.source.abort?.();\n this.rejectFinal(new OllamaAbortError('OpenAI Completion stream ended before completion'));\n }\n }\n }\n}\n\nexport interface OpenAIResponsesEventBase { readonly response_id?: string | undefined; readonly sequence_number?: number | undefined; }\n\nexport interface OpenAIResponsesOutputTextDeltaEvent extends OpenAIResponsesEventBase { readonly type: 'response.output_text.delta'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly delta: string; }\nexport interface OpenAIResponsesOutputTextDoneEvent extends OpenAIResponsesEventBase { readonly type: 'response.output_text.done'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly text: string; }\nexport interface OpenAIResponsesFunctionCallArgumentsDeltaEvent extends OpenAIResponsesEventBase { readonly type: 'response.function_call_arguments.delta'; readonly item_id: string; readonly output_index: number; readonly delta: string; }\nexport interface OpenAIResponsesFunctionCallArgumentsDoneEvent extends OpenAIResponsesEventBase { readonly type: 'response.function_call_arguments.done'; readonly item_id: string; readonly output_index: number; readonly arguments: string; readonly name?: string | undefined; }\nexport interface OpenAIResponsesReasoningTextDeltaEvent extends OpenAIResponsesEventBase { readonly type: 'response.reasoning_text.delta'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly delta: string; }\nexport interface OpenAIResponsesReasoningTextDoneEvent extends OpenAIResponsesEventBase { readonly type: 'response.reasoning_text.done'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly text: string; }\nexport interface OpenAIResponsesReasoningSummaryPartAddedEvent extends OpenAIResponsesEventBase { readonly type: 'response.reasoning_summary_part.added'; readonly item_id: string; readonly output_index: number; readonly summary_index: number; readonly part: { readonly type: 'summary_text'; readonly text: string }; }\nexport interface OpenAIResponsesReasoningSummaryPartDoneEvent extends OpenAIResponsesEventBase { readonly type: 'response.reasoning_summary_part.done'; readonly item_id: string; readonly output_index: number; readonly summary_index: number; readonly part: { readonly type: 'summary_text'; readonly text: string }; readonly status?: 'incomplete' | undefined; }\nexport interface OpenAIResponsesReasoningSummaryTextDeltaEvent extends OpenAIResponsesEventBase { readonly type: 'response.reasoning_summary_text.delta'; readonly item_id: string; readonly output_index: number; readonly summary_index: number; readonly delta: string; }\nexport interface OpenAIResponsesReasoningSummaryTextDoneEvent extends OpenAIResponsesEventBase { readonly type: 'response.reasoning_summary_text.done'; readonly item_id: string; readonly output_index: number; readonly summary_index: number; readonly text: string; }\nexport interface OpenAIResponsesOutputItemAddedEvent extends OpenAIResponsesEventBase { readonly type: 'response.output_item.added'; readonly item: OpenAIResponsesOutputItem; readonly output_index: number; }\nexport interface OpenAIResponsesOutputItemDoneEvent extends OpenAIResponsesEventBase { readonly type: 'response.output_item.done'; readonly item: OpenAIResponsesOutputItem; readonly output_index: number; }\nexport interface OpenAIResponsesContentPartAddedEvent extends OpenAIResponsesEventBase { readonly type: 'response.content_part.added'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly part: OpenAIResponsesOutputContent | { readonly type: string; readonly [key: string]: unknown }; }\nexport interface OpenAIResponsesContentPartDoneEvent extends OpenAIResponsesEventBase { readonly type: 'response.content_part.done'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly part: OpenAIResponsesOutputContent | { readonly type: string; readonly [key: string]: unknown }; }\nexport interface OpenAIResponsesRefusalDeltaEvent extends OpenAIResponsesEventBase { readonly type: 'response.refusal.delta'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly delta: string; }\nexport interface OpenAIResponsesRefusalDoneEvent extends OpenAIResponsesEventBase { readonly type: 'response.refusal.done'; readonly item_id: string; readonly output_index: number; readonly content_index: number; readonly refusal: string; }\nexport interface OpenAIResponsesCreatedEvent extends OpenAIResponsesEventBase { readonly type: 'response.created'; readonly response: OpenAIResponsesResponse; }\nexport interface OpenAIResponsesInProgressEvent extends OpenAIResponsesEventBase { readonly type: 'response.in_progress'; readonly response: OpenAIResponsesResponse; }\nexport interface OpenAIResponsesQueuedEvent extends OpenAIResponsesEventBase { readonly type: 'response.queued'; readonly response: OpenAIResponsesResponse; }\nexport interface OpenAIResponsesCompletedEvent extends OpenAIResponsesEventBase { readonly type: 'response.completed' | 'response.done'; readonly response: OpenAIResponsesResponse; }\nexport interface OpenAIResponsesFailedEvent extends OpenAIResponsesEventBase { readonly type: 'response.failed'; readonly response: OpenAIResponsesResponse; }\nexport interface OpenAIResponsesIncompleteEvent extends OpenAIResponsesEventBase { readonly type: 'response.incomplete'; readonly response: OpenAIResponsesResponse; }\n\nexport type OpenAIResponsesStreamEvent =\n | OpenAIResponsesOutputTextDeltaEvent | OpenAIResponsesOutputTextDoneEvent\n | OpenAIResponsesFunctionCallArgumentsDeltaEvent | OpenAIResponsesFunctionCallArgumentsDoneEvent\n | OpenAIResponsesReasoningTextDeltaEvent | OpenAIResponsesReasoningTextDoneEvent\n | OpenAIResponsesReasoningSummaryPartAddedEvent | OpenAIResponsesReasoningSummaryPartDoneEvent\n | OpenAIResponsesReasoningSummaryTextDeltaEvent | OpenAIResponsesReasoningSummaryTextDoneEvent\n | OpenAIResponsesOutputItemAddedEvent | OpenAIResponsesOutputItemDoneEvent\n | OpenAIResponsesContentPartAddedEvent | OpenAIResponsesContentPartDoneEvent\n | OpenAIResponsesRefusalDeltaEvent | OpenAIResponsesRefusalDoneEvent\n | OpenAIResponsesCreatedEvent | OpenAIResponsesInProgressEvent | OpenAIResponsesQueuedEvent\n | OpenAIResponsesCompletedEvent | OpenAIResponsesFailedEvent | OpenAIResponsesIncompleteEvent\n | { readonly type: string; readonly [key: string]: unknown };\n\ntype OpenAIResponsesOutputState = {\n itemId: string; kind: 'message' | 'function_call' | 'reasoning';\n content: Map<number, OpenAIResponsesOutputContent>; summary: Map<number, string>;\n arguments: string; name?: string | undefined; callId?: string | undefined; status?: OpenAIResponsesStatus | undefined;\n role?: string | undefined; phase?: string | undefined; reasoningText: string;\n};\nexport class OpenAIResponsesStream implements AsyncIterable<OpenAIResponsesStreamEvent> {\n private readonly finalResultPromise: Promise<OpenAIResponsesResponse>;\n private resolveFinal!: (value: OpenAIResponsesResponse) => void;\n private rejectFinal!: (reason: unknown) => void;\n private removeAbortListener: (() => void) | undefined;\n\n constructor(private readonly source: AbortableAsyncIterable<SseEvent>, signal?: AbortSignal) {\n this.finalResultPromise = new Promise<OpenAIResponsesResponse>((resolve, reject) => { this.resolveFinal = resolve; this.rejectFinal = reject; });\n if (signal !== undefined) {\n const onAbort = (): void => this.abort();\n if (signal.aborted) onAbort();\n else { signal.addEventListener('abort', onAbort, { once: true }); this.removeAbortListener = () => signal.removeEventListener('abort', onAbort); }\n }\n }\n get finalResult(): Promise<OpenAIResponsesResponse> { return this.finalResultPromise; }\n abort(): void {\n this.removeAbortListener?.(); this.removeAbortListener = undefined; this.source.abort?.();\n this.rejectFinal(new OllamaAbortError('OpenAI Responses stream aborted'));\n }\n\n async *[Symbol.asyncIterator](): AsyncGenerator<OpenAIResponsesStreamEvent, void, undefined> {\n let finalResponse: OpenAIResponsesResponse | undefined;\n let responseMeta: OpenAIResponsesResponse | undefined;\n let terminalFailure: OpenAIResponsesResponse | undefined;\n let terminalIncomplete: OpenAIResponsesResponse | undefined;\n const outputs = new Map<number, OpenAIResponsesOutputState>();\n const canonicalOutputItems = new Map<number, OpenAIResponsesOutputItem>();\n let completed = false;\n\n const ensureState = (outputIndex: number, itemId: string, kind: OpenAIResponsesOutputState['kind']): OpenAIResponsesOutputState => {\n const existing = outputs.get(outputIndex);\n if (existing) { if (itemId) existing.itemId = itemId; existing.kind = kind; return existing; }\n const state: OpenAIResponsesOutputState = { itemId, kind, content: new Map(), summary: new Map(), arguments: '', reasoningText: '' };\n outputs.set(outputIndex, state); return state;\n };\n\n const applyOutputItem = (outputIndex: number, item: OpenAIResponsesOutputItem): void => {\n const kind = item.type === 'message' ? 'message' : item.type === 'function_call' ? 'function_call' : 'reasoning';\n const state = ensureState(outputIndex, item.id ?? '', kind);\n state.itemId = item.id ?? state.itemId; state.status = item.status;\n if (item.type === 'message') { state.role = item.role; state.phase = item.phase; state.content.clear(); item.content.forEach((p, i) => state.content.set(i, p)); }\n else if (item.type === 'function_call') { state.callId = item.call_id; state.name = item.name; state.arguments = item.arguments; }\n else { state.summary.clear(); item.summary?.forEach((p, i) => state.summary.set(i, p.text)); state.reasoningText = item.text ?? ''; }\n };\n const applyContentPart = (outputIndex: number, itemId: string, contentIndex: number, part: OpenAIResponsesOutputContent): void => {\n const state = ensureState(outputIndex, itemId, 'message'); state.content.set(contentIndex, part);\n };\n const reconstructedOutput = (): readonly OpenAIResponsesOutputItem[] =>\n [...outputs.entries()].sort(([a], [b]) => a - b).map(([outputIndex, state]) => {\n const canonical = canonicalOutputItems.get(outputIndex); if (canonical) return canonical;\n if (state.kind === 'message') return { type: 'message', ...(state.itemId ? { id: state.itemId } : {}), ...(state.status ? { status: state.status } : {}), role: state.role ?? 'assistant', ...(state.phase ? { phase: state.phase } : {}), content: [...state.content.entries()].sort(([a], [b]) => a - b).map(([, p]) => p) };\n if (state.kind === 'function_call') return { type: 'function_call', ...(state.itemId ? { id: state.itemId } : {}), ...(state.callId ? { call_id: state.callId } : {}), ...(state.status ? { status: state.status } : {}), name: state.name ?? '', arguments: state.arguments };\n return { type: 'reasoning', ...(state.itemId ? { id: state.itemId } : {}), ...(state.status ? { status: state.status } : {}), ...(state.summary.size ? { summary: [...state.summary.entries()].sort(([a], [b]) => a - b).map(([, text]) => ({ type: 'summary_text' as const, text })) } : {}), ...(state.reasoningText ? { text: state.reasoningText } : {}) };\n });\n\n try {\n for await (const event of this.source) {\n if (event.data === '[DONE]') break;\n let payload: OpenAIResponsesStreamEvent;\n try { payload = JSON.parse(event.data) as OpenAIResponsesStreamEvent; } catch (error) { throw new Error('Failed to parse OpenAI Responses SSE payload', { cause: error }); }\n switch (payload.type) {\n case 'response.created': case 'response.in_progress': case 'response.queued': responseMeta = (payload as OpenAIResponsesCreatedEvent).response; break;\n case 'response.completed': case 'response.done': finalResponse = (payload as OpenAIResponsesCompletedEvent).response; break;\n case 'response.failed': terminalFailure = (payload as OpenAIResponsesFailedEvent).response; finalResponse = terminalFailure; break;\n case 'response.incomplete': terminalIncomplete = (payload as OpenAIResponsesIncompleteEvent).response; finalResponse = terminalIncomplete; break;\n case 'response.output_item.added': { const e = payload as OpenAIResponsesOutputItemAddedEvent; applyOutputItem(e.output_index, e.item); break; }\n case 'response.output_item.done': { const e = payload as OpenAIResponsesOutputItemDoneEvent; applyOutputItem(e.output_index, e.item); canonicalOutputItems.set(e.output_index, e.item); break; }\n case 'response.content_part.added': case 'response.content_part.done': {\n const e = payload as OpenAIResponsesContentPartAddedEvent | OpenAIResponsesContentPartDoneEvent;\n if (\n (e.part.type === 'output_text' && 'text' in e.part && typeof e.part.text === 'string') ||\n (e.part.type === 'refusal' && 'refusal' in e.part && typeof e.part.refusal === 'string')\n ) {\n applyContentPart(e.output_index, e.item_id, e.content_index, e.part as OpenAIResponsesOutputContent);\n }\n break;\n }\n case 'response.output_text.delta': { const e = payload as OpenAIResponsesOutputTextDeltaEvent; const s = ensureState(e.output_index, e.item_id, 'message'); const p=s.content.get(e.content_index); s.content.set(e.content_index,{type:'output_text',text:(p?.type==='output_text'?p.text:'')+e.delta}); break; }\n case 'response.output_text.done': { const e = payload as OpenAIResponsesOutputTextDoneEvent; const s=ensureState(e.output_index,e.item_id,'message'); s.content.set(e.content_index,{type:'output_text',text:e.text}); break; }\n case 'response.refusal.delta': { const e=payload as OpenAIResponsesRefusalDeltaEvent; const s=ensureState(e.output_index,e.item_id,'message'); const p=s.content.get(e.content_index); s.content.set(e.content_index,{type:'refusal',refusal:(p?.type==='refusal'?p.refusal:'')+e.delta}); break; }\n case 'response.refusal.done': { const e=payload as OpenAIResponsesRefusalDoneEvent; const s=ensureState(e.output_index,e.item_id,'message'); s.content.set(e.content_index,{type:'refusal',refusal:e.refusal}); break; }\n case 'response.function_call_arguments.delta': { const e=payload as OpenAIResponsesFunctionCallArgumentsDeltaEvent; const s=ensureState(e.output_index,e.item_id,'function_call'); s.arguments+=e.delta; break; }\n case 'response.function_call_arguments.done': { const e=payload as OpenAIResponsesFunctionCallArgumentsDoneEvent; const s=ensureState(e.output_index,e.item_id,'function_call'); s.arguments=e.arguments; if(e.name!==undefined) s.name=e.name; break; }\n case 'response.reasoning_summary_part.added': case 'response.reasoning_summary_part.done': { const e=payload as OpenAIResponsesReasoningSummaryPartAddedEvent | OpenAIResponsesReasoningSummaryPartDoneEvent; const s=ensureState(e.output_index,e.item_id,'reasoning'); s.summary.set(e.summary_index,e.part.text); break; }\n case 'response.reasoning_summary_text.delta': { const e=payload as OpenAIResponsesReasoningSummaryTextDeltaEvent; const s=ensureState(e.output_index,e.item_id,'reasoning'); s.summary.set(e.summary_index,(s.summary.get(e.summary_index)??'')+e.delta); break; }\n case 'response.reasoning_summary_text.done': { const e=payload as OpenAIResponsesReasoningSummaryTextDoneEvent; const s=ensureState(e.output_index,e.item_id,'reasoning'); s.summary.set(e.summary_index,e.text); break; }\n case 'response.reasoning_text.delta': { const e=payload as OpenAIResponsesReasoningTextDeltaEvent; const s=ensureState(e.output_index,e.item_id,'reasoning'); s.reasoningText+=e.delta; break; }\n case 'response.reasoning_text.done': { const e=payload as OpenAIResponsesReasoningTextDoneEvent; const s=ensureState(e.output_index,e.item_id,'reasoning'); s.reasoningText=e.text; break; }\n default: break;\n }\n yield payload;\n }\n if (terminalFailure || terminalIncomplete) {\n const response = terminalFailure ?? terminalIncomplete!; const status = terminalFailure ? 'failed' : 'incomplete';\n const detail = response.error?.message ?? response.incomplete_details?.reason ?? 'unknown error';\n throw new OpenAIResponsesStreamError('OpenAI Responses stream ' + status + ': ' + detail, response);\n }\n if (!finalResponse) {\n if (!responseMeta) throw new Error('OpenAI Responses stream ended without a terminal response payload');\n if (responseMeta.status === 'failed' || responseMeta.status === 'incomplete') {\n const detail=responseMeta.error?.message ?? responseMeta.incomplete_details?.reason ?? 'unknown error';\n throw new OpenAIResponsesStreamError('OpenAI Responses stream ' + responseMeta.status + ': ' + detail, responseMeta);\n }\n finalResponse={...responseMeta,output:reconstructedOutput(),status:'completed'};\n } else if (finalResponse.status === 'failed' || finalResponse.status === 'incomplete') {\n const detail=finalResponse.error?.message ?? finalResponse.incomplete_details?.reason ?? 'unknown error';\n throw new OpenAIResponsesStreamError('OpenAI Responses stream ' + finalResponse.status + ': ' + detail, finalResponse);\n }\n if (finalResponse.output.length===0 && outputs.size>0) finalResponse={...finalResponse,output:reconstructedOutput()};\n completed=true; this.removeAbortListener?.(); this.removeAbortListener=undefined; this.resolveFinal(finalResponse);\n } catch(error) { this.removeAbortListener?.(); this.removeAbortListener=undefined; this.rejectFinal(error); throw error; }\n finally { if(!completed){ this.source.abort?.(); this.rejectFinal(new OllamaAbortError('OpenAI Responses stream ended before completion')); } }\n }\n}\nexport class OpenAICompatClient {\n constructor(\n private readonly http: HttpClient,\n private readonly runner?: RequestRunner | undefined,\n ) {}\n\n private request<T>(\n operation: (http: HttpClient, signal?: AbortSignal) => Promise<T>,\n model: string | undefined,\n signal?: AbortSignal,\n holdUntil?: ((result: T) => Promise<unknown>) | undefined,\n ): Promise<T> {\n if (this.runner) {\n return this.runner(\n (http, runnerSignal) => operation(http, runnerSignal),\n {\n ...(model !== undefined ? { model } : {}),\n ...(signal !== undefined ? { signal } : {}),\n ...(holdUntil !== undefined ? { holdUntil } : {}),\n },\n );\n }\n return operation(this.http, signal);\n }\n\n async createChatCompletion(\n request: OpenAIChatCompletionRequest & { stream: true },\n signal?: AbortSignal,\n ): Promise<OpenAIChatCompletionStream>;\n async createChatCompletion(\n request: OpenAIChatCompletionRequest & { stream?: false | undefined },\n signal?: AbortSignal,\n ): Promise<OpenAIChatCompletionResponse>;\n async createChatCompletion(\n request: OpenAIChatCompletionRequest,\n signal?: AbortSignal,\n ): Promise<OpenAIChatCompletionResponse | OpenAIChatCompletionStream> {\n if (request.stream) {\n return this.request(\n (http, requestSignal) =>\n http.requestSseStream({\n path: '/v1/chat/completions',\n body: request,\n signal: requestSignal,\n }).then((source) => new OpenAIChatCompletionStream(source, requestSignal)),\n request.model,\n signal,\n (stream: OpenAIChatCompletionStream) => stream.finalResult,\n );\n }\n return this.request(\n (http, requestSignal) =>\n http.request<OpenAIChatCompletionResponse>({\n path: '/v1/chat/completions',\n body: request,\n signal: requestSignal,\n }),\n request.model,\n signal,\n );\n }\n\n async chatCompletions(\n request: OpenAIChatCompletionRequest & { stream: true },\n signal?: AbortSignal,\n ): Promise<OpenAIChatCompletionStream>;\n async chatCompletions(\n request: OpenAIChatCompletionRequest & { stream?: false | undefined },\n signal?: AbortSignal,\n ): Promise<OpenAIChatCompletionResponse>;\n async chatCompletions(\n request: OpenAIChatCompletionRequest,\n signal?: AbortSignal,\n ): Promise<OpenAIChatCompletionResponse | OpenAIChatCompletionStream> {\n return this.createChatCompletion(request as never, signal);\n }\n\n async listModels(signal?: AbortSignal): Promise<OpenAIListModelsResponse> {\n return this.request(\n (http, requestSignal) =>\n http.request<OpenAIListModelsResponse>({\n path: '/v1/models',\n method: 'GET',\n signal: requestSignal,\n }),\n undefined,\n signal,\n );\n }\n\n async retrieveModel(\n model: string,\n signal?: AbortSignal,\n ): Promise<OpenAIModelItem> {\n return this.request(\n (http, requestSignal) =>\n http.request<OpenAIModelItem>({\n path: `/v1/models/${encodeURIComponent(model)}`,\n method: 'GET',\n signal: requestSignal,\n }),\n model,\n signal,\n );\n }\n\n async getModel(model: string, signal?: AbortSignal): Promise<OpenAIModelItem> {\n return this.retrieveModel(model, signal);\n }\n\n async createCompletion(\n request: OpenAICompletionRequest & { stream: true },\n signal?: AbortSignal,\n ): Promise<OpenAICompletionStream>;\n async createCompletion(\n request: OpenAICompletionRequest & { stream?: false | undefined },\n signal?: AbortSignal,\n ): Promise<OpenAICompletionResponse>;\n async createCompletion(\n request: OpenAICompletionRequest,\n signal?: AbortSignal,\n ): Promise<OpenAICompletionResponse | OpenAICompletionStream> {\n if (request.stream) {\n return this.request(\n (http, requestSignal) =>\n http.requestSseStream({\n path: '/v1/completions',\n body: request,\n signal: requestSignal,\n }).then((source) => new OpenAICompletionStream(source, requestSignal)),\n request.model,\n signal,\n (stream: OpenAICompletionStream) => stream.finalResult,\n );\n }\n return this.request(\n (http, requestSignal) =>\n http.request<OpenAICompletionResponse>({\n path: '/v1/completions',\n body: request,\n signal: requestSignal,\n }),\n request.model,\n signal,\n );\n }\n\n async completions(\n request: OpenAICompletionRequest & { stream: true },\n signal?: AbortSignal,\n ): Promise<OpenAICompletionStream>;\n async completions(\n request: OpenAICompletionRequest & { stream?: false | undefined },\n signal?: AbortSignal,\n ): Promise<OpenAICompletionResponse>;\n async completions(\n request: OpenAICompletionRequest,\n signal?: AbortSignal,\n ): Promise<OpenAICompletionResponse | OpenAICompletionStream> {\n return this.createCompletion(request as never, signal);\n }\n\n async createEmbedding(\n request: OpenAIEmbeddingRequest,\n signal?: AbortSignal,\n ): Promise<OpenAIEmbeddingResponse> {\n return this.request(\n (http, requestSignal) =>\n http.request<OpenAIEmbeddingResponse>({\n path: '/v1/embeddings',\n body: request,\n signal: requestSignal,\n }),\n request.model,\n signal,\n );\n }\n\n async embeddings(\n request: OpenAIEmbeddingRequest,\n signal?: AbortSignal,\n ): Promise<OpenAIEmbeddingResponse> {\n return this.createEmbedding(request, signal);\n }\n\n async createResponses(\n request: OpenAIResponsesRequest & { stream: true },\n signal?: AbortSignal,\n ): Promise<OpenAIResponsesStream>;\n async createResponses(\n request: OpenAIResponsesRequest & { stream?: false | undefined },\n signal?: AbortSignal,\n ): Promise<OpenAIResponsesResponse>;\n async createResponses(\n request: OpenAIResponsesRequest,\n signal?: AbortSignal,\n ): Promise<OpenAIResponsesResponse | OpenAIResponsesStream> {\n if (request.stream) {\n return this.request(\n (http, requestSignal) =>\n http.requestSseStream({\n path: '/v1/responses',\n body: request,\n signal: requestSignal,\n }).then((source) => new OpenAIResponsesStream(source, requestSignal)),\n request.model,\n signal,\n (stream: OpenAIResponsesStream) => stream.finalResult,\n );\n }\n return this.request(\n (http, requestSignal) =>\n http.request<OpenAIResponsesResponse>({\n path: '/v1/responses',\n body: request,\n signal: requestSignal,\n }),\n request.model,\n signal,\n );\n }\n\n async responses(\n request: OpenAIResponsesRequest & { stream: true },\n signal?: AbortSignal,\n ): Promise<OpenAIResponsesStream>;\n async responses(\n request: OpenAIResponsesRequest & { stream?: false | undefined },\n signal?: AbortSignal,\n ): Promise<OpenAIResponsesResponse>;\n async responses(\n request: OpenAIResponsesRequest,\n signal?: AbortSignal,\n ): Promise<OpenAIResponsesResponse | OpenAIResponsesStream> {\n return this.createResponses(request as never, signal);\n }\n}\n","/**\n * Anthropic Compatibility interfaces and client helpers for Ollama.\n * Ollama supports the Anthropic Messages API format.\n */\n\nimport type { AbortableAsyncIterable } from '../streaming/types.js';\nimport type { SseEvent } from '../streaming/sse.js';\nimport type { HttpClient } from '../transport/http.js';\nimport type { RequestRunner } from '../transport/runner.js';\nimport { OllamaAbortError } from '../errors.js';\n\nexport interface AnthropicCacheControl {\n readonly type: 'ephemeral';\n readonly ttl?: '5m' | '1h' | undefined;\n}\n\nexport interface AnthropicTextContentBlock {\n readonly type: 'text';\n readonly text: string;\n readonly cache_control?: AnthropicCacheControl | undefined;\n}\n\nexport interface AnthropicImageContentBlock {\n readonly type: 'image';\n readonly source: {\n readonly type: 'base64';\n readonly media_type: string;\n readonly data: string;\n };\n}\n\nexport interface AnthropicToolUseContentBlock {\n readonly type: 'tool_use';\n readonly id: string;\n readonly name: string;\n readonly input: Record<string, unknown>;\n}\n\nexport interface AnthropicToolResultContentBlock {\n readonly type: 'tool_result';\n readonly tool_use_id: string;\n readonly content?: string | readonly AnthropicTextContentBlock[] | undefined;\n readonly is_error?: boolean | undefined;\n}\n\nexport interface AnthropicThinkingContentBlock {\n readonly type: 'thinking';\n readonly thinking: string;\n readonly signature?: string | undefined;\n}\n\nexport interface AnthropicRedactedThinkingContentBlock {\n readonly type: 'redacted_thinking';\n readonly data: string;\n}\n\nexport type AnthropicContentBlock =\n | AnthropicTextContentBlock\n | AnthropicImageContentBlock\n | AnthropicToolUseContentBlock\n | AnthropicToolResultContentBlock\n | AnthropicThinkingContentBlock\n | AnthropicRedactedThinkingContentBlock;\n\nexport interface AnthropicMessage {\n readonly role: 'user' | 'assistant';\n readonly content: string | readonly AnthropicContentBlock[];\n}\n\nexport interface AnthropicSystemTextBlock {\n readonly type: 'text';\n readonly text: string;\n readonly cache_control?: AnthropicCacheControl | undefined;\n}\n\nexport type AnthropicSystem = string | readonly AnthropicSystemTextBlock[];\n\nexport interface AnthropicTool {\n readonly name: string;\n readonly description?: string | undefined;\n readonly input_schema: Record<string, unknown>;\n readonly eager_input_streaming?: boolean | undefined;\n}\n\nexport type AnthropicToolChoice =\n | { readonly type: 'auto'; readonly disable_parallel_tool_use?: boolean | undefined }\n | { readonly type: 'any'; readonly disable_parallel_tool_use?: boolean | undefined }\n | { readonly type: 'tool'; readonly name: string; readonly disable_parallel_tool_use?: boolean | undefined }\n | { readonly type: 'none' };\n\nexport interface AnthropicThinkingConfig {\n readonly type: 'enabled' | 'disabled' | 'adaptive';\n readonly display?: 'omitted' | 'summarized' | 'updates' | undefined;\n /** Accepted by Ollama for compatibility but currently not enforced by the server. */\n readonly budget_tokens?: number | undefined;\n}\n\nexport interface AnthropicOutputConfig {\n readonly effort?: string | undefined;\n}\n\nexport interface AnthropicMetadata {\n readonly user_id?: string | undefined;\n}\n\nexport interface AnthropicMessagesRequest {\n readonly model: string;\n readonly messages: readonly AnthropicMessage[];\n readonly system?: AnthropicSystem | undefined;\n readonly max_tokens?: number | undefined;\n readonly temperature?: number | undefined;\n readonly top_p?: number | undefined;\n readonly top_k?: number | undefined;\n readonly stop_sequences?: readonly string[] | undefined;\n readonly stream?: boolean | undefined;\n readonly tools?: readonly AnthropicTool[] | undefined;\n readonly thinking?: AnthropicThinkingConfig | undefined;\n readonly output_config?: AnthropicOutputConfig | undefined;\n /**\n * Accepted for Anthropic compatibility but currently ignored by Ollama.\n * Tool selection cannot be forced through the Ollama compatibility endpoint.\n */\n readonly tool_choice?: AnthropicToolChoice | undefined;\n /** Accepted for compatibility but currently ignored by Ollama. */\n readonly metadata?: AnthropicMetadata | undefined;\n}\n\n/** Strict Ollama-documented Messages request; excludes fields Ollama marks unsupported. */\nexport type OllamaAnthropicTextContentBlock = Omit<\n AnthropicTextContentBlock,\n 'cache_control'\n>;\n\nexport type OllamaAnthropicTool = Omit<AnthropicTool, 'eager_input_streaming'>;\n\nexport type OllamaAnthropicThinkingConfig = {\n readonly type: 'enabled' | 'disabled';\n /** Accepted by Ollama for compatibility but currently not enforced by the server. */\n readonly budget_tokens?: number | undefined;\n};\n\nexport type OllamaAnthropicToolResultContentBlock = Omit<\n AnthropicToolResultContentBlock,\n 'content'\n> & {\n readonly content?: string | readonly OllamaAnthropicTextContentBlock[] | undefined;\n};\n\nexport type OllamaAnthropicContentBlock =\n | OllamaAnthropicTextContentBlock\n | AnthropicImageContentBlock\n | AnthropicToolUseContentBlock\n | OllamaAnthropicToolResultContentBlock\n | AnthropicThinkingContentBlock;\n\nexport type OllamaAnthropicMessage = Omit<AnthropicMessage, 'content'> & {\n readonly content: string | readonly OllamaAnthropicContentBlock[];\n};\n\nexport type OllamaAnthropicSystemTextBlock = Omit<\n AnthropicSystemTextBlock,\n 'cache_control'\n>;\n\nexport type OllamaAnthropicSystem =\n | string\n | readonly OllamaAnthropicSystemTextBlock[];\n\n/** Strict Ollama-documented Messages request; excludes unsupported caching/tool-choice metadata. */\nexport type OllamaAnthropicMessagesRequest = Omit<\n AnthropicMessagesRequest,\n 'messages' | 'system' | 'tools' | 'thinking' | 'tool_choice' | 'metadata'\n> & {\n readonly messages: readonly OllamaAnthropicMessage[];\n readonly system?: OllamaAnthropicSystem | undefined;\n readonly tools?: readonly OllamaAnthropicTool[] | undefined;\n readonly thinking?: OllamaAnthropicThinkingConfig | undefined;\n};\n\nexport interface AnthropicMessagesResponse {\n readonly id: string;\n readonly type: 'message';\n readonly role: 'assistant';\n readonly content: readonly AnthropicContentBlock[];\n readonly model: string;\n readonly stop_reason: string | null;\n readonly stop_sequence?: string | null | undefined;\n readonly usage?: {\n readonly input_tokens: number;\n readonly output_tokens: number;\n readonly cache_creation_input_tokens?: number | undefined;\n readonly cache_read_input_tokens?: number | undefined;\n readonly cache_creation?: Record<string, unknown> | undefined;\n } | undefined;\n}\n\nexport interface AnthropicMessageStartEvent {\n readonly type: 'message_start';\n readonly message: AnthropicMessagesResponse;\n}\n\nexport interface AnthropicContentBlockStartEvent {\n readonly type: 'content_block_start';\n readonly index: number;\n readonly content_block: AnthropicContentBlock;\n}\n\nexport type AnthropicContentBlockDelta =\n | { readonly type: 'text_delta'; readonly text: string }\n | { readonly type: 'input_json_delta'; readonly partial_json: string }\n | { readonly type: 'thinking_delta'; readonly thinking: string }\n | { readonly type: 'signature_delta'; readonly signature: string };\n\nexport interface AnthropicContentBlockDeltaEvent {\n readonly type: 'content_block_delta';\n readonly index: number;\n readonly delta: AnthropicContentBlockDelta;\n}\n\nexport interface AnthropicContentBlockStopEvent {\n readonly type: 'content_block_stop';\n readonly index: number;\n}\n\nexport interface AnthropicMessageDeltaEvent {\n readonly type: 'message_delta';\n readonly delta: {\n readonly stop_reason?: string | null | undefined;\n readonly stop_sequence?: string | null | undefined;\n };\n readonly usage?: {\n readonly input_tokens?: number | undefined;\n readonly output_tokens: number;\n readonly cache_creation_input_tokens?: number | undefined;\n readonly cache_read_input_tokens?: number | undefined;\n readonly cache_creation?: Record<string, unknown> | undefined;\n } | undefined;\n}\n\nexport interface AnthropicMessageStopEvent {\n readonly type: 'message_stop';\n}\n\nexport interface AnthropicPingEvent {\n readonly type: 'ping';\n}\n\nexport interface AnthropicErrorEvent {\n readonly type: 'error';\n readonly error: {\n readonly type: string;\n readonly message: string;\n };\n}\n\nexport interface AnthropicUnknownStreamEvent {\n /** Forward-compatible event type not yet modeled by this SDK. */\n readonly type: string;\n readonly [key: string]: unknown;\n}\n\nexport type AnthropicMessageStreamEvent =\n | AnthropicMessageStartEvent\n | AnthropicContentBlockStartEvent\n | AnthropicContentBlockDeltaEvent\n | AnthropicContentBlockStopEvent\n | AnthropicMessageDeltaEvent\n | AnthropicMessageStopEvent\n | AnthropicPingEvent\n | AnthropicErrorEvent\n | AnthropicUnknownStreamEvent;\n\ntype AnthropicKnownStreamEvent = Exclude<\n AnthropicMessageStreamEvent,\n AnthropicUnknownStreamEvent\n>;\n\nfunction isAnthropicKnownStreamEvent(\n event: AnthropicMessageStreamEvent,\n): event is AnthropicKnownStreamEvent {\n switch (event.type) {\n case 'message_start':\n case 'content_block_start':\n case 'content_block_delta':\n case 'content_block_stop':\n case 'message_delta':\n case 'message_stop':\n case 'ping':\n case 'error':\n return true;\n default:\n return false;\n }\n}\n\nfunction parseAnthropicEvent(event: SseEvent): AnthropicMessageStreamEvent {\n return JSON.parse(event.data) as AnthropicMessageStreamEvent;\n}\n\nfunction mergeContentBlock(\n current: AnthropicContentBlock,\n delta: AnthropicContentBlockDelta,\n): AnthropicContentBlock {\n if (delta.type === 'text_delta' && current.type === 'text') {\n return { ...current, text: current.text + delta.text };\n }\n if (delta.type === 'input_json_delta' && current.type === 'tool_use') {\n return current;\n }\n if (delta.type === 'thinking_delta' && current.type === 'thinking') {\n return { ...current, thinking: current.thinking + delta.thinking };\n }\n if (delta.type === 'signature_delta' && current.type === 'thinking') {\n return { ...current, signature: (current.signature ?? '') + delta.signature };\n }\n return current;\n}\n\nfunction sanitizeAnthropicTextBlock(\n block: AnthropicTextContentBlock,\n): OllamaAnthropicTextContentBlock {\n if (block.cache_control === undefined) return block;\n const { cache_control: _cacheControl, ...sanitized } = block;\n return sanitized;\n}\n\nfunction sanitizeAnthropicContentBlock(\n block: AnthropicContentBlock,\n): AnthropicContentBlock {\n if (block.type === 'text') {\n return sanitizeAnthropicTextBlock(block);\n }\n\n if (block.type === 'tool_result' && Array.isArray(block.content)) {\n return {\n ...block,\n content: block.content.map(sanitizeAnthropicTextBlock),\n };\n }\n\n return block;\n}\n\nfunction sanitizeAnthropicRequest(request: AnthropicMessagesRequest): AnthropicMessagesRequest {\n const messages = request.messages.map((message) => {\n if (typeof message.content === 'string') return message;\n return {\n ...message,\n content: message.content.map(sanitizeAnthropicContentBlock),\n };\n });\n\n const system = Array.isArray(request.system)\n ? request.system.map(sanitizeAnthropicTextBlock)\n : request.system;\n\n const {\n tool_choice: _toolChoice,\n metadata: _metadata,\n ...sanitized\n } = request;\n\n return {\n ...sanitized,\n messages,\n ...(system !== undefined ? { system } : {}),\n };\n}\nexport class AnthropicMessagesStream implements AsyncIterable<AnthropicMessageStreamEvent> {\n private readonly finalResultPromise: Promise<AnthropicMessagesResponse>;\n private resolveFinal!: (value: AnthropicMessagesResponse) => void;\n private rejectFinal!: (reason: unknown) => void;\n private removeAbortListener: (() => void) | undefined;\n\n constructor(private readonly source: AbortableAsyncIterable<SseEvent>, signal?: AbortSignal) {\n this.finalResultPromise = new Promise<AnthropicMessagesResponse>((resolve, reject) => {\n this.resolveFinal = resolve;\n this.rejectFinal = reject;\n });\n if (signal !== undefined) {\n const onAbort = (): void => this.abort();\n if (signal.aborted) onAbort();\n else {\n signal.addEventListener('abort', onAbort, { once: true });\n this.removeAbortListener = () => signal.removeEventListener('abort', onAbort);\n }\n }\n }\n\n get finalResult(): Promise<AnthropicMessagesResponse> {\n return this.finalResultPromise;\n }\n\n abort(): void {\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.source.abort?.();\n this.rejectFinal(new OllamaAbortError('Anthropic Messages stream aborted'));\n }\n\n async *[Symbol.asyncIterator](): AsyncGenerator<AnthropicMessageStreamEvent, void, undefined> {\n let message:\n | AnthropicMessagesResponse\n | undefined;\n const blocks = new Map<number, AnthropicContentBlock>();\n const toolInputJson = new Map<number, string>();\n let completed = false;\n\n try {\n for await (const rawEvent of this.source) {\n let event: AnthropicMessageStreamEvent;\n try {\n event = parseAnthropicEvent(rawEvent);\n } catch (error) {\n throw new Error('Failed to parse Anthropic message SSE payload', { cause: error });\n }\n\n if (!isAnthropicKnownStreamEvent(event)) {\n yield event;\n continue;\n }\n\n if (event.type === 'error') {\n throw new Error(event.error.message);\n }\n\n if (event.type === 'message_start') {\n message = {\n ...event.message,\n content: [],\n ...(event.message.usage !== undefined ? { usage: event.message.usage } : {}),\n };\n } else if (event.type === 'content_block_start') {\n blocks.set(event.index, event.content_block);\n } else if (event.type === 'content_block_delta') {\n const current = blocks.get(event.index);\n if (event.delta.type === 'input_json_delta') {\n toolInputJson.set(event.index, (toolInputJson.get(event.index) ?? '') + event.delta.partial_json);\n }\n if (current) blocks.set(event.index, mergeContentBlock(current, event.delta));\n } else if (event.type === 'content_block_stop') {\n const current = blocks.get(event.index);\n if (current?.type === 'tool_use') {\n const rawJson = toolInputJson.get(event.index);\n if (rawJson !== undefined && rawJson !== '') {\n try {\n const parsed = JSON.parse(rawJson) as Record<string, unknown>;\n blocks.set(event.index, { ...current, input: parsed });\n } catch {\n // Keep the provider-provided partial object when the accumulated JSON is malformed.\n blocks.set(event.index, current);\n }\n }\n }\n } else if (event.type === 'message_delta') {\n if (message) {\n message = {\n ...message,\n stop_reason:\n event.delta.stop_reason !== undefined && event.delta.stop_reason !== null\n ? event.delta.stop_reason\n : message.stop_reason,\n stop_sequence: event.delta.stop_sequence ?? message.stop_sequence,\n ...(event.usage !== undefined\n ? {\n usage: {\n input_tokens: event.usage.input_tokens ?? message.usage?.input_tokens ?? 0,\n output_tokens: event.usage.output_tokens,\n ...(event.usage.cache_creation_input_tokens !== undefined\n ? { cache_creation_input_tokens: event.usage.cache_creation_input_tokens }\n : message.usage?.cache_creation_input_tokens !== undefined\n ? { cache_creation_input_tokens: message.usage.cache_creation_input_tokens }\n : {}),\n ...(event.usage.cache_read_input_tokens !== undefined\n ? { cache_read_input_tokens: event.usage.cache_read_input_tokens }\n : message.usage?.cache_read_input_tokens !== undefined\n ? { cache_read_input_tokens: message.usage.cache_read_input_tokens }\n : {}),\n ...(event.usage.cache_creation !== undefined\n ? { cache_creation: event.usage.cache_creation }\n : message.usage?.cache_creation !== undefined\n ? { cache_creation: message.usage.cache_creation }\n : {}),\n },\n }\n : {}),\n };\n }\n } else if (event.type === 'message_stop' && message) {\n message = {\n ...message,\n content: [...blocks.entries()].sort(([a], [b]) => a - b).map(([, block]) => block),\n };\n }\n\n yield event;\n }\n\n if (!message) {\n throw new Error('Anthropic Messages stream ended without message_start');\n }\n\n const final: AnthropicMessagesResponse = {\n ...message,\n content: [...blocks.entries()].sort(([a], [b]) => a - b).map(([, block]) => block),\n };\n completed = true;\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.resolveFinal(final);\n } catch (error) {\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.rejectFinal(error);\n throw error;\n } finally {\n if (!completed) {\n this.source.abort?.();\n this.rejectFinal(new OllamaAbortError('Anthropic Messages stream ended before completion'));\n }\n }\n }\n}\n\nexport class AnthropicCompatClient {\n constructor(\n private readonly http: HttpClient,\n private readonly runner?: RequestRunner | undefined,\n ) {}\n\n private request<T>(\n operation: (http: HttpClient, signal?: AbortSignal) => Promise<T>,\n model: string,\n signal?: AbortSignal,\n holdUntil?: ((result: T) => Promise<unknown>) | undefined,\n ): Promise<T> {\n if (this.runner) {\n return this.runner(\n (http, runnerSignal) => operation(http, runnerSignal),\n {\n model,\n ...(signal !== undefined ? { signal } : {}),\n ...(holdUntil !== undefined ? { holdUntil } : {}),\n },\n );\n }\n return operation(this.http, signal);\n }\n\n async createMessage(\n request: AnthropicMessagesRequest & { stream: true },\n signal?: AbortSignal,\n ): Promise<AnthropicMessagesStream>;\n async createMessage(\n request: AnthropicMessagesRequest & { stream?: false | undefined },\n signal?: AbortSignal,\n ): Promise<AnthropicMessagesResponse>;\n async createMessage(\n request: AnthropicMessagesRequest,\n signal?: AbortSignal,\n ): Promise<AnthropicMessagesResponse | AnthropicMessagesStream>;\n async createMessage(\n request: AnthropicMessagesRequest,\n signal?: AbortSignal,\n ): Promise<AnthropicMessagesResponse | AnthropicMessagesStream> {\n if (request.stream) {\n return this.request(\n (http, requestSignal) =>\n http.requestSseStream({\n path: '/v1/messages',\n body: sanitizeAnthropicRequest(request),\n headers: { 'anthropic-version': '2023-06-01' },\n signal: requestSignal,\n }).then((source) => new AnthropicMessagesStream(source, requestSignal)),\n request.model,\n signal,\n (stream: AnthropicMessagesStream) => stream.finalResult,\n );\n }\n return this.request(\n (http, requestSignal) =>\n http.request<AnthropicMessagesResponse>({\n path: '/v1/messages',\n body: sanitizeAnthropicRequest(request),\n headers: { 'anthropic-version': '2023-06-01' },\n signal: requestSignal,\n }),\n request.model,\n signal,\n );\n }\n\n async messages(\n request: AnthropicMessagesRequest & { stream: true },\n signal?: AbortSignal,\n ): Promise<AnthropicMessagesStream>;\n async messages(\n request: AnthropicMessagesRequest & { stream?: false | undefined },\n signal?: AbortSignal,\n ): Promise<AnthropicMessagesResponse>;\n async messages(\n request: AnthropicMessagesRequest,\n signal?: AbortSignal,\n ): Promise<AnthropicMessagesResponse | AnthropicMessagesStream>;\n async messages(\n request: AnthropicMessagesRequest,\n signal?: AbortSignal,\n ): Promise<AnthropicMessagesResponse | AnthropicMessagesStream> {\n if (request.stream) {\n return this.createMessage(request, signal);\n }\n return this.createMessage(request, signal);\n }\n}\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const IncludedBalanceSchema = z.object({\n balance_usd: z.number(),\n allowance_usd: z.number(),\n period: z.object({\n from: z.string(),\n until: z.string(),\n }),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const LegacyBalanceLimitSchema = z.object({\n remaining_percent: z.number().min(0).max(100),\n resets_at: z.string(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { LegacyBalanceLimitSchema } from './LegacyBalanceLimit.schema.js';\n\nexport const LegacyIncludedBalanceSchema = z.object({\n session: LegacyBalanceLimitSchema,\n weekly: LegacyBalanceLimitSchema,\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { IncludedBalanceSchema } from './IncludedBalance.schema.js';\nimport { LegacyIncludedBalanceSchema } from './LegacyIncludedBalance.schema.js';\n\nexport const BalanceResponseSchema = z.object({\n included: z.union([IncludedBalanceSchema, LegacyIncludedBalanceSchema]),\n purchased: z.object({\n balance_usd: z.number(),\n }),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const ToolCallSchema = z.object({\n function: z\n .object({\n name: z.string(),\n description: z.string().optional(),\n arguments: z.object({}).optional(),\n })\n .optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { ToolCallSchema } from './ToolCall.schema.js';\n\nexport const ChatMessageSchema = z.object({\n role: z.enum(['system', 'user', 'assistant', 'tool']),\n content: z.string(),\n images: z.array(z.string()).optional(),\n tool_calls: z.array(ToolCallSchema).optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\n/** Runtime options that control text generation */\nexport const ModelOptionsSchema = z\n .object({\n seed: z.number().optional(),\n temperature: z.number().optional(),\n top_k: z.number().optional(),\n top_p: z.number().optional(),\n min_p: z.number().optional(),\n stop: z.union([z.string(), z.array(z.string())]).optional(),\n num_ctx: z.number().optional(),\n num_predict: z.number().optional(),\n })\n .catchall(z.unknown());\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\n/** Controls a model's thinking output. Use `/api/show` to discover the supported values and default for the selected model. `true` requests thinking, `false` requests no thinking output, and `null` uses the model default. String values are model-defined; supported names must match `/api/show` exactly. Numbers are not supported. */\nexport const ThinkValueSchema = z.union([z.boolean(), z.string(), z.null()]);\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const ToolDefinitionSchema = z.object({\n type: z.enum(['function']),\n function: z.object({\n name: z.string(),\n description: z.string().optional(),\n parameters: z.object({}),\n }),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { ChatMessageSchema } from './ChatMessage.schema.js';\nimport { ModelOptionsSchema } from './ModelOptions.schema.js';\nimport { ThinkValueSchema } from './ThinkValue.schema.js';\nimport { ToolDefinitionSchema } from './ToolDefinition.schema.js';\n\nexport const ChatRequestSchema = z.object({\n model: z.string(),\n messages: z.array(ChatMessageSchema),\n tools: z.array(ToolDefinitionSchema).optional(),\n format: z.union([z.enum(['json']), z.object({})]).optional(),\n options: ModelOptionsSchema.optional(),\n stream: z.boolean().optional(),\n think: ThinkValueSchema.optional(),\n keep_alive: z.union([z.string(), z.number()]).optional(),\n logprobs: z.boolean().optional(),\n top_logprobs: z.number().optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\n/** Log probability information for a single token alternative */\nexport const TokenLogprobSchema = z.object({\n token: z.string().optional(),\n logprob: z.number().optional(),\n bytes: z.array(z.number()).optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { TokenLogprobSchema } from './TokenLogprob.schema.js';\n\n/** Log probability information for a generated token */\nexport const LogprobSchema = z.object({\n token: z.string().optional(),\n logprob: z.number().optional(),\n bytes: z.array(z.number()).optional(),\n top_logprobs: z.array(TokenLogprobSchema).optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { LogprobSchema } from './Logprob.schema.js';\nimport { ToolCallSchema } from './ToolCall.schema.js';\n\nexport const ChatResponseSchema = z.object({\n model: z.string().optional(),\n created_at: z.string().optional(),\n message: z\n .object({\n role: z.enum(['assistant']).optional(),\n content: z.string().optional(),\n thinking: z.string().optional(),\n tool_calls: z.array(ToolCallSchema).optional(),\n images: z.array(z.string()).optional(),\n })\n .optional(),\n done: z.boolean().optional(),\n done_reason: z.string().optional(),\n total_duration: z.number().optional(),\n load_duration: z.number().optional(),\n prompt_eval_count: z.number().optional(),\n prompt_eval_cached_count: z.number().optional(),\n prompt_eval_duration: z.number().optional(),\n eval_count: z.number().optional(),\n eval_duration: z.number().optional(),\n logprobs: z.array(LogprobSchema).optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const CopyRequestSchema = z.object({\n source: z.string(),\n destination: z.string(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { ChatMessageSchema } from './ChatMessage.schema.js';\n\nexport const CreateRequestSchema = z.object({\n model: z.string(),\n from: z.string().optional(),\n template: z.string().optional(),\n renderer: z.string().optional(),\n parser: z.string().optional(),\n files: z.object({}).catchall(z.string()).optional(),\n draft_files: z.object({}).catchall(z.string()).optional(),\n license: z.union([z.string(), z.array(z.string())]).optional(),\n system: z.string().optional(),\n parameters: z.object({}).optional(),\n messages: z.array(ChatMessageSchema).optional(),\n quantize: z.string().optional(),\n draft_quantize: z.string().optional(),\n requires: z.string().optional(),\n capabilities: z.array(z.string()).optional(),\n stream: z.boolean().optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const DeleteRequestSchema = z.object({\n model: z.string(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { ModelOptionsSchema } from './ModelOptions.schema.js';\n\nexport const EmbedRequestSchema = z.object({\n model: z.string(),\n input: z.union([z.string(), z.array(z.string())]),\n truncate: z.boolean().optional(),\n dimensions: z.number().optional(),\n keep_alive: z.string().optional(),\n options: ModelOptionsSchema.optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const EmbedResponseSchema = z.object({\n model: z.string().optional(),\n embeddings: z.array(z.array(z.number())).optional(),\n total_duration: z.number().optional(),\n load_duration: z.number().optional(),\n prompt_eval_count: z.number().optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { ModelOptionsSchema } from './ModelOptions.schema.js';\nimport { ThinkValueSchema } from './ThinkValue.schema.js';\n\nexport const GenerateRequestSchema = z.object({\n model: z.string(),\n prompt: z.string().optional(),\n suffix: z.string().optional(),\n images: z.array(z.string()).optional(),\n format: z.union([z.string(), z.object({})]).optional(),\n system: z.string().optional(),\n stream: z.boolean().optional(),\n think: ThinkValueSchema.optional(),\n raw: z.boolean().optional(),\n keep_alive: z.union([z.string(), z.number()]).optional(),\n options: ModelOptionsSchema.optional(),\n logprobs: z.boolean().optional(),\n top_logprobs: z.number().optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { LogprobSchema } from './Logprob.schema.js';\n\nexport const GenerateResponseSchema = z.object({\n model: z.string().optional(),\n created_at: z.string().optional(),\n response: z.string().optional(),\n thinking: z.string().optional(),\n done: z.boolean().optional(),\n done_reason: z.string().optional(),\n total_duration: z.number().optional(),\n load_duration: z.number().optional(),\n prompt_eval_count: z.number().optional(),\n prompt_eval_cached_count: z.number().optional(),\n prompt_eval_duration: z.number().optional(),\n eval_count: z.number().optional(),\n eval_duration: z.number().optional(),\n logprobs: z.array(LogprobSchema).optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\n/** Summary information for a locally available model */\nexport const ModelSummarySchema = z.object({\n name: z.string().optional(),\n model: z.string().optional(),\n remote_model: z.string().optional(),\n remote_host: z.string().optional(),\n modified_at: z.string().optional(),\n size: z.number().optional(),\n digest: z.string().optional(),\n details: z\n .object({\n format: z.string().optional(),\n family: z.string().optional(),\n families: z.union([z.array(z.string()), z.null()]).optional(),\n parameter_size: z.string().optional(),\n quantization_level: z.string().optional(),\n })\n .optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { ModelSummarySchema } from './ModelSummary.schema.js';\n\nexport const ListResponseSchema = z.object({\n models: z.array(ModelSummarySchema).optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const PsSchema = z.object({\n name: z.string().optional(),\n model: z.string().optional(),\n size: z.number().optional(),\n digest: z.string().optional(),\n details: z.object({}).optional(),\n expires_at: z.string().optional(),\n size_vram: z.number().optional(),\n context_length: z.number().optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { PsSchema } from './Ps.schema.js';\n\nexport const PsResponseSchema = z.object({\n models: z.array(PsSchema).optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const PullRequestSchema = z.object({\n model: z.string(),\n insecure: z.boolean().optional(),\n stream: z.boolean().optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const PushRequestSchema = z.object({\n model: z.string(),\n insecure: z.boolean().optional(),\n stream: z.boolean().optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const ShowRequestSchema = z.object({\n model: z.string(),\n verbose: z.boolean().optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\n/** Thinking controls advertised by a model. Models without thinking metadata omit this field. */\nexport const ThinkingSchema = z.object({\n values: z.array(z.union([z.boolean(), z.string()])),\n default: z.union([z.boolean(), z.string()]),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { ThinkingSchema } from './Thinking.schema.js';\n\nexport const ShowResponseSchema = z.object({\n thinking: ThinkingSchema.optional(),\n parameters: z.string().optional(),\n license: z.string().optional(),\n modified_at: z.string().optional(),\n details: z.object({}).optional(),\n template: z.string().optional(),\n capabilities: z.array(z.string()).optional(),\n model_info: z.object({}).optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const StatusResponseSchema = z.object({\n status: z.string().optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\n/** A nonempty string, or an object or array serialized as JSON text. Not interpreted as chat messages or multimodal input. */\nexport const SystemOneContentSchema = z.union([\n z.string().regex(new RegExp('\\\\S')),\n z.object({}).catchall(z.unknown()),\n z.array(z.unknown()),\n]);\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { SystemOneContentSchema } from './SystemOneContent.schema.js';\n\nexport const SystemOneChoiceQuestionSchema = z.object({\n type: z.enum(['choice']),\n instructions: SystemOneContentSchema,\n criteria: z\n .object({})\n .catchall(z.union([z.string(), z.null()]))\n .refine((v) => Object.keys(v).length >= 2, { message: 'must have at least 2 properties' })\n .refine((v) => Object.keys(v).length <= 26, { message: 'must have at most 26 properties' })\n .refine((v) => Object.keys(v).every((k) => new RegExp('\\\\S').test(k)), {\n message: 'property names must match pattern \"\\\\S\"',\n }),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { SystemOneContentSchema } from './SystemOneContent.schema.js';\n\nexport const SystemOneNoulQuestionSchema = z.object({\n type: z.enum(['noul']),\n instructions: SystemOneContentSchema,\n criteria: z\n .object({\n false: z.string().optional(),\n true: z.string().optional(),\n })\n .optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { SystemOneContentSchema } from './SystemOneContent.schema.js';\n\nexport const SystemOneScoreQuestionSchema = z.object({\n type: z.enum(['score']),\n instructions: SystemOneContentSchema,\n criteria: z.array(z.string()).min(2).max(26),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { SystemOneChoiceQuestionSchema } from './SystemOneChoiceQuestion.schema.js';\nimport { SystemOneContentSchema } from './SystemOneContent.schema.js';\nimport { SystemOneNoulQuestionSchema } from './SystemOneNoulQuestion.schema.js';\nimport { SystemOneScoreQuestionSchema } from './SystemOneScoreQuestion.schema.js';\n\nexport const SystemOneRequestSchema = z.object({\n model: z.string().regex(new RegExp('\\\\S')),\n state: SystemOneContentSchema,\n images: z.array(z.string()).optional(),\n questions: z\n .object({})\n .catchall(\n z.union([\n SystemOneChoiceQuestionSchema,\n SystemOneNoulQuestionSchema,\n SystemOneScoreQuestionSchema,\n ]),\n )\n .refine((v) => Object.keys(v).length >= 1, { message: 'must have at least 1 properties' })\n .refine((v) => Object.keys(v).length <= 64, { message: 'must have at most 64 properties' })\n .refine((v) => Object.keys(v).every((k) => new RegExp('\\\\S').test(k)), {\n message: 'property names must match pattern \"\\\\S\"',\n }),\n keep_alive: z.union([z.string(), z.number()]).optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\n/** Distribution concentration, calculated as 1 - H(p) / ln(N), where H(p) is entropy and N is the candidate count. Zero means uniform probabilities; values near 1 mean one candidate dominates. Not calibrated correctness. */\nexport const SystemOneConfidenceSchema = z.number().min(0).max(1);\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\n/** Probabilities normalized over the supplied candidates, summing to 1 subject to floating-point precision. */\nexport const SystemOneProbabilitiesSchema = z.object({}).catchall(z.number().min(0).max(1));\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { SystemOneConfidenceSchema } from './SystemOneConfidence.schema.js';\nimport { SystemOneProbabilitiesSchema } from './SystemOneProbabilities.schema.js';\n\nexport const SystemOneChoiceAnswerSchema = z.object({\n type: z.enum(['choice']),\n choice: z.string(),\n probabilities: SystemOneProbabilitiesSchema,\n confidence: SystemOneConfidenceSchema,\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const SystemOneNoulAnswerSchema = z.object({\n type: z.enum(['noul']),\n noul: z.number().min(0).max(1),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { SystemOneConfidenceSchema } from './SystemOneConfidence.schema.js';\nimport { SystemOneProbabilitiesSchema } from './SystemOneProbabilities.schema.js';\n\nexport const SystemOneScoreAnswerSchema = z.object({\n type: z.enum(['score']),\n score: z.number().min(0).max(25),\n legend: z.object({}).catchall(z.string()),\n probabilities: SystemOneProbabilitiesSchema,\n confidence: SystemOneConfidenceSchema,\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { SystemOneChoiceAnswerSchema } from './SystemOneChoiceAnswer.schema.js';\nimport { SystemOneNoulAnswerSchema } from './SystemOneNoulAnswer.schema.js';\nimport { SystemOneScoreAnswerSchema } from './SystemOneScoreAnswer.schema.js';\n\nexport const SystemOneResponseSchema = z.object({\n model: z.string(),\n answers: z\n .object({})\n .catchall(\n z.union([SystemOneChoiceAnswerSchema, SystemOneNoulAnswerSchema, SystemOneScoreAnswerSchema]),\n ),\n usage: z.object({\n input_tokens: z.number().min(0),\n output_tokens: z.number().min(0),\n }),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const UsageMetricsSchema = z.object({\n request_count: z.number().min(0),\n usage_usd: z.number().optional(),\n input_tokens: z.number().optional(),\n cached_input_tokens: z.number().optional(),\n output_tokens: z.number().optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { UsageMetricsSchema } from './UsageMetrics.schema.js';\n\nexport const UsageBucketSchema = z.intersection(\n UsageMetricsSchema,\n z.object({\n from: z.string(),\n until: z.string(),\n partial: z.boolean().optional(),\n }),\n);\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { UsageBucketSchema } from './UsageBucket.schema.js';\nimport { UsageMetricsSchema } from './UsageMetrics.schema.js';\n\nexport const UsageResponseSchema = z.object({\n range: z.enum(['24h', '7d', '30d']),\n scope: z.enum(['self', 'team']),\n granularity: z.enum(['hour', 'day']),\n from: z.string(),\n until: z.string(),\n totals: UsageMetricsSchema,\n buckets: z.array(UsageBucketSchema),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const VersionResponseSchema = z.object({\n version: z.string().optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const WebFetchRequestSchema = z.object({\n url: z.string(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const WebFetchResponseSchema = z.object({\n title: z.string().optional(),\n content: z.string().optional(),\n links: z.array(z.string()).optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const WebSearchRequestSchema = z.object({\n query: z.string(),\n max_results: z.number().min(1).max(10).optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\n\nexport const WebSearchResultSchema = z.object({\n title: z.string().optional(),\n url: z.string().optional(),\n content: z.string().optional(),\n});\n","// AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n// Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n// Pairs with ./<name>.ts (the TypeScript interface).\n\nimport { z } from 'zod';\nimport { WebSearchResultSchema } from './WebSearchResult.schema.js';\n\nexport const WebSearchResponseSchema = z.object({\n results: z.array(WebSearchResultSchema).optional(),\n});\n","/**\n * AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n * Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n * Maps every operation whose IR entry carries `request.$ref` / `response.$ref`\n * to its generated Zod schema. Consumed by OllamaRuntime when\n * `validateRequests: true` / `validateResponses: true` is set (ADR 0020).\n */\n\nimport type { z } from 'zod';\nimport { BalanceResponseSchema } from '../models/BalanceResponse.schema.js';\nimport { ChatRequestSchema } from '../models/ChatRequest.schema.js';\nimport { ChatResponseSchema } from '../models/ChatResponse.schema.js';\nimport { CopyRequestSchema } from '../models/CopyRequest.schema.js';\nimport { CreateRequestSchema } from '../models/CreateRequest.schema.js';\nimport { DeleteRequestSchema } from '../models/DeleteRequest.schema.js';\nimport { EmbedRequestSchema } from '../models/EmbedRequest.schema.js';\nimport { EmbedResponseSchema } from '../models/EmbedResponse.schema.js';\nimport { GenerateRequestSchema } from '../models/GenerateRequest.schema.js';\nimport { GenerateResponseSchema } from '../models/GenerateResponse.schema.js';\nimport { ListResponseSchema } from '../models/ListResponse.schema.js';\nimport { PsResponseSchema } from '../models/PsResponse.schema.js';\nimport { PullRequestSchema } from '../models/PullRequest.schema.js';\nimport { PushRequestSchema } from '../models/PushRequest.schema.js';\nimport { ShowRequestSchema } from '../models/ShowRequest.schema.js';\nimport { ShowResponseSchema } from '../models/ShowResponse.schema.js';\nimport { StatusResponseSchema } from '../models/StatusResponse.schema.js';\nimport { SystemOneRequestSchema } from '../models/SystemOneRequest.schema.js';\nimport { SystemOneResponseSchema } from '../models/SystemOneResponse.schema.js';\nimport { UsageResponseSchema } from '../models/UsageResponse.schema.js';\nimport { VersionResponseSchema } from '../models/VersionResponse.schema.js';\nimport { WebFetchRequestSchema } from '../models/WebFetchRequest.schema.js';\nimport { WebFetchResponseSchema } from '../models/WebFetchResponse.schema.js';\nimport { WebSearchRequestSchema } from '../models/WebSearchRequest.schema.js';\nimport { WebSearchResponseSchema } from '../models/WebSearchResponse.schema.js';\n\n/**\n * Map from operationId → request schema. The runtime consults this\n * registry (via getRequestSchema) when `validateRequests: true` is\n * set on OllamaRuntime.\n *\n * Wave 12 (P1 #6): this file is now generated from the canonical IR.\n */\nexport const requestSchemas: Readonly<Record<string, z.ZodType>> = {\n chat: ChatRequestSchema,\n copy: CopyRequestSchema,\n create: CreateRequestSchema,\n delete: DeleteRequestSchema,\n embed: EmbedRequestSchema,\n generate: GenerateRequestSchema,\n pull: PullRequestSchema,\n push: PushRequestSchema,\n show: ShowRequestSchema,\n systemOne: SystemOneRequestSchema,\n webFetch: WebFetchRequestSchema,\n webSearch: WebSearchRequestSchema,\n};\n\n/**\n * Map from operationId → response schema. The runtime consults this\n * registry (via getResponseSchema) when `validateResponses: true` is\n * set on OllamaRuntime. Wave 13 added this map for operations where\n * typed response semantics are critical (e.g. System One).\n */\nexport const responseSchemas: Readonly<Record<string, z.ZodType>> = {\n balance: BalanceResponseSchema,\n chat: ChatResponseSchema,\n create: StatusResponseSchema,\n embed: EmbedResponseSchema,\n generate: GenerateResponseSchema,\n ps: PsResponseSchema,\n pull: StatusResponseSchema,\n push: StatusResponseSchema,\n show: ShowResponseSchema,\n systemOne: SystemOneResponseSchema,\n tags: ListResponseSchema,\n usage: UsageResponseSchema,\n version: VersionResponseSchema,\n webFetch: WebFetchResponseSchema,\n webSearch: WebSearchResponseSchema,\n};\n\n/** Look up a request schema by operationId. Returns `undefined` if no schema exists. */\nexport function getRequestSchema(operationId: string): z.ZodType | undefined {\n return requestSchemas[operationId];\n}\n\n/** Look up a response schema by operationId. Returns `undefined` if no schema exists. */\nexport function getResponseSchema(operationId: string): z.ZodType | undefined {\n return responseSchemas[operationId];\n}\n","/**\n * OllamaRuntime — the runtime seam generated API classes delegate to.\n *\n * This is the only hand-written file in `src/generated/runtime/`. Every\n * generated method in `src/generated/api/*-api.ts` ends with:\n *\n * ```ts\n * return this.runtime.invoke({ operation: chatOp, body: request });\n * ```\n *\n * The runtime is responsible for:\n * - Method/path resolution (from {@link OperationDefinition})\n * - Streaming default application (when the request doesn't set `stream`)\n * - Environment guard (rejecting cloud calls for local-only operations)\n * - Version constraint guard (failing fast when the server is too old)\n * - Delegating to the existing {@link HttpClient} for transport, retry,\n * telemetry, NDJSON/SSE parsing\n *\n * It is intentionally a thin adapter — the existing transport, streaming,\n * middleware, and error-mapping layers are preserved verbatim. This file\n * only adds the contract-aware glue between generated API classes and the\n * existing HttpClient.\n */\nimport { HttpClient, type HttpRequestOptions } from '../../transport/http.js';\nimport { parseNdjsonStream } from '../../streaming/ndjson.js';\nimport { parseSseStream } from '../../streaming/sse.js';\nimport {\n OllamaGenericClientError,\n OllamaRequestTooLargeError,\n OllamaRequestValidationError,\n OllamaResponseValidationError,\n OllamaServerVersionUnknownError,\n} from '../../errors.js';\nimport type { OperationDefinition, InvokeRequest } from './operation-definition.js';\nimport type { TransportMode } from './operation-definition.js';\nimport { getRequestSchema, getResponseSchema } from './schema-registry.js';\n\n/**\n * Minimal HTTP client surface the runtime consumes. Either a full\n * {@link HttpClient} or a {@link FailoverHttpClient} — the runtime only\n * calls `request()`.\n *\n * Wave 14: widened from `HttpClient` to allow the failover-aware wrapper\n * without breaking existing callers that pass a plain HttpClient.\n */\nexport type RuntimeHttpBackend = Pick<HttpClient, 'baseUrl' | 'request'>;\n\n/** Constructor options for {@link OllamaRuntime}. */\nexport interface OllamaRuntimeOptions {\n readonly http: RuntimeHttpBackend;\n /**\n * Wave 15 (P0): HTTP backend for operations that declare a non-default\n * `host` (e.g. web search/fetch at `https://ollama.com`). When an\n * operation has `host: 'https://ollama.com'` and `cloudHttp` is\n * configured, the runtime routes the request through this backend\n * instead of the default `http`. When `cloudHttp` is not configured\n * and a host-bearing operation is invoked, the runtime throws.\n *\n * OllamaClient.runtime sets this to a dedicated cloud HttpClient\n * pointed at `https://ollama.com` with the configured API key.\n */\n readonly cloudHttp?: RuntimeHttpBackend;\n /**\n * Whether this runtime is targeting a local Ollama instance. Defaults to\n * `true`. When `false`, operations marked `environment.cloud === false`\n * (i.e. local-only like `/v1/systemone`) are rejected at request time.\n */\n readonly localMode?: boolean;\n /**\n * Server version, if known (typically from a prior `/api/version` call).\n * When set, operations with `constraints.minOllamaVersion` are checked\n * against this value at request time.\n *\n * Wave 12 (P0 #5): when unset, the runtime will lazily fetch and cache\n * the server version the first time a version-gated operation is\n * invoked. The fetch policy is controlled by {@link enforceVersion}.\n */\n readonly serverVersion?: string;\n /**\n * When `true`, the runtime validates every request body against the\n * generated Zod schema before sending it. Defaults to `false` — opt-in.\n *\n * Validation behavior:\n * - If the operation has a registered request schema (see\n * {@link schema-registry.ts}), the body is parsed via `safeParse`.\n * - On parse failure, throws `OllamaRequestValidationError` with the\n * Zod issues attached. No HTTP request is made.\n * - On parse success, the parsed (and stripped of unknown fields) body\n * is sent — this means callers can't accidentally send extra fields\n * that the contract doesn't allow.\n * - If the operation has NO registered schema (e.g. GET endpoints,\n * `/v1/systemone`, OpenAI/Anthropic compat surfaces), validation is\n * skipped silently.\n *\n * Response validation is intentionally NOT enabled by default — see\n * ADR 0020 for the rationale (forward-compat with wire-format\n * extensions).\n *\n * Wave 13: an opt-in `validateResponses` option is now available for\n * operations where typed response semantics are the entire point\n * (e.g. System One). When enabled, the runtime validates the HTTP\n * response body against the operation's registered response schema\n * before returning it to the caller. On failure, throws\n * {@link OllamaResponseValidationError}.\n */\n readonly validateRequests?: boolean;\n /**\n * Wave 13: when `true`, the runtime validates every response body\n * against the operation's registered response schema before returning\n * it. Defaults to `false` — opt-in. Only operations with a registered\n * response schema are validated; others pass through unchanged.\n *\n * On validation failure, throws {@link OllamaResponseValidationError}\n * with the Zod issues attached. The HTTP response is still consumed.\n *\n * Use this for operations where typed response semantics are critical\n * (System One, structured output). Don't enable globally — legitimate\n * forward-compat wire-format extensions would cause false rejections.\n */\n readonly validateResponses?: boolean;\n /**\n * Policy for enforcing `constraints.minOllamaVersion` when\n * {@link serverVersion} is not explicitly supplied.\n *\n * - `'auto'` (default): lazily fetch `/api/version` once and cache the\n * result; subsequent version-gated invocations reuse the cached\n * value. If the fetch fails, the operation is allowed through\n * (fail-open) — the server will reject it if it truly doesn't\n * support it.\n * - `'strict'`: same as `'auto'`, but if the version fetch fails the\n * invocation throws {@link OllamaServerVersionUnknownError} rather\n * than fail-open. Use this when the caller wants hard guarantees\n * that a version-gated operation will not be sent to a server that\n * can't handle it.\n * - `'off'`: never fetch `/api/version` automatically. The runtime\n * only enforces the version constraint when {@link serverVersion}\n * was explicitly supplied. Useful in tests that mock fetch and want\n * to avoid spurious version probes.\n */\n readonly enforceVersion?: 'auto' | 'strict' | 'off';\n}\n\nfunction compareVersions(a: string, b: string): number {\n const pa = a.split('.').map((s) => Number.parseInt(s, 10) ?? 0);\n const pb = b.split('.').map((s) => Number.parseInt(s, 10) ?? 0);\n for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) {\n const va = pa[i] ?? 0;\n const vb = pb[i] ?? 0;\n if (va !== vb) return va - vb;\n }\n return 0;\n}\n\n/**\n * Best-effort one-shot fetch of the Ollama server version.\n *\n * Resolves to `undefined` if the server's response shape doesn't include a\n * `version` field. Network/parse errors propagate to the caller, where the\n * `enforceVersion` policy decides whether they become hard failures\n * ('strict') or silent fallthrough ('auto').\n *\n * The result is cached per-runtime in {@link OllamaRuntime}'s private\n * state — we don't re-probe `/api/version` for every version-gated call.\n */\nasync function fetchServerVersion(http: RuntimeHttpBackend): Promise<string | undefined> {\n const result = await http.request<{ version?: unknown }>({\n path: '/api/version',\n method: 'GET',\n });\n if (result && typeof result.version === 'string') return result.version;\n return undefined;\n}\n\n/**\n * Decide whether the request should stream. If the request body explicitly\n * sets `stream`, that wins. Otherwise the operation's `streamingDefault`\n * from the contract is used.\n */\nfunction shouldStream(req: InvokeRequest): boolean {\n if (req.body && typeof req.body === 'object' && 'stream' in req.body) {\n const explicit = (req.body as { stream?: unknown }).stream;\n if (typeof explicit === 'boolean') return explicit;\n }\n return Boolean(req.streamingDefault ?? req.operation.transport.streamingDefault);\n}\n\n/**\n * Apply the streaming default to the request body if needed.\n *\n * If the operation streams by default and the body doesn't set `stream`,\n * add `stream: true`. The user can always override by setting `stream`\n * explicitly on the request.\n */\nfunction buildBody(req: InvokeRequest): unknown {\n if (req.body === undefined) return undefined;\n if (typeof req.body !== 'object' || req.body === null) return req.body;\n const body = req.body as Record<string, unknown>;\n if (\n req.operation.transport.streaming &&\n req.operation.transport.streamingDefault &&\n body.stream === undefined\n ) {\n return { ...body, stream: true };\n }\n return body;\n}\n\n/** The runtime seam. */\nexport class OllamaRuntime {\n /**\n * Cached promise of the Ollama server version, populated lazily the first\n * time a version-gated operation is invoked. `undefined` until then.\n *\n * Wave 12 (P0 #5): see {@link OllamaRuntimeOptions.enforceVersion}.\n */\n private serverVersionCache: Promise<string | undefined> | undefined;\n\n constructor(private readonly options: OllamaRuntimeOptions) {}\n\n /**\n * Wave 15 (P0): resolve the HTTP backend for a given operation.\n *\n * Operations with a declared `host` (e.g. web search/fetch at\n * https://ollama.com) must route to a HttpClient pointed at that host,\n * not the default one. The runtime accepts an optional `cloudHttp`\n * backend for this purpose — if the operation declares a host and no\n * cloud backend is configured, the runtime throws rather than silently\n * sending the request to the wrong server.\n */\n private resolveHttpBackend(operation: OperationDefinition): RuntimeHttpBackend {\n if (operation.host) {\n const cloudHttp = this.options.cloudHttp;\n if (!cloudHttp) {\n throw new OllamaGenericClientError(\n `Operation ${operation.operationId} (${operation.method} ${operation.path}) ` +\n `targets host \"${operation.host}\" but the runtime has no cloudHttp backend configured. ` +\n `Use OllamaClient.webSearch() / OllamaClient.webFetch() for cloud-hosted operations, ` +\n `or construct OllamaRuntime with a cloudHttp option.`,\n );\n }\n return cloudHttp;\n }\n return this.options.http;\n }\n\n /**\n * Invoke an operation. Called by every generated API method.\n *\n * Returns a `Promise<T>` for non-streaming operations, or an\n * `AsyncGenerator<T>` for streaming operations. The generated API\n * class's overloads pick the right return type at compile time.\n */\n async invoke<T = unknown>(req: InvokeRequest): Promise<T> {\n await this.assertOperationAllowed(req.operation);\n let body = buildBody(req);\n\n // Wave 10 (ADR 0020): runtime Zod validation. Opt-in via\n // `validateRequests: true` on the runtime constructor. Throws\n // `OllamaRequestValidationError` BEFORE any HTTP request is made\n // when the body fails validation. The validated (and stripped)\n // body replaces the original so unknown fields can't leak through.\n if (this.options.validateRequests === true && body !== undefined) {\n const schema = getRequestSchema(req.operation.operationId);\n if (schema) {\n const result = schema.safeParse(body);\n if (!result.success) {\n throw new OllamaRequestValidationError(\n `Request validation failed for operation \"${req.operation.operationId}\" ` +\n `(${req.operation.method} ${req.operation.path}): ` +\n result.error.issues\n .map((i) => `${i.path.join('.') || '<root>'}: ${i.message}`)\n .join('; '),\n {\n operationId: req.operation.operationId,\n issues: result.error.issues,\n request: { method: req.operation.method, url: req.operation.path },\n },\n );\n }\n body = result.data;\n }\n }\n\n // Wave 12 (P0 #5) + Wave 13: enforce request size limits BEFORE\n // the request is sent. The Ollama server returns 413 for oversized\n // bodies; failing fast client-side avoids the round-trip.\n //\n // Wave 13 adds conditional limits: when the operation declares\n // `maxRequestBytesWithImages` AND the body contains a non-empty\n // `images` array, the higher limit applies (e.g. System One allows\n // 32 MiB with images vs 64 KiB without). When images are absent\n // or the operation doesn't declare a separate images limit, the\n // base `maxRequestBytes` applies.\n if (body !== undefined) {\n const serialized = serializeForByteCount(body);\n const hasImages = bodyHasImages(body);\n const maxBytesWithImages = req.operation.constraints?.maxRequestBytesWithImages;\n const maxBytesBase = req.operation.constraints?.maxRequestBytes;\n const applicableLimit =\n hasImages && maxBytesWithImages !== undefined ? maxBytesWithImages : maxBytesBase;\n if (applicableLimit !== undefined && serialized.byteLength > applicableLimit) {\n throw new OllamaRequestTooLargeError(\n `Operation ${req.operation.operationId} (${req.operation.method} ` +\n `${req.operation.path}) request body is ${serialized.byteLength} bytes, ` +\n `exceeding the contract limit of ${applicableLimit} bytes` +\n (hasImages ? ' (images limit).' : '.'),\n {\n operationId: req.operation.operationId,\n actualBytes: serialized.byteLength,\n maxBytes: applicableLimit,\n request: { method: req.operation.method, url: req.operation.path },\n },\n );\n }\n }\n\n const streaming = shouldStream(req);\n\n // Wave 15 (P0): substitute path parameters into the path template.\n // The operation's path may contain `{name}` segments (e.g.\n // `/v1/models/{model}`, `/api/blobs/{digest}`). The caller provides\n // values via `req.pathParams`; we URI-encode each value and substitute\n // it into the template. If a required path parameter is missing, we\n // throw before making the HTTP request.\n const resolvedPath = resolvePathParams(req.operation.path, req.pathParams);\n\n // Wave 17 (P1): apply query parameters to the path. Query params are\n // appended as URL-encoded key=value pairs after a '?' separator.\n const pathWithQuery = applyQueryParams(resolvedPath, req.queryParams);\n\n // Wave 17 (P1): extract model from the request body for failover\n // routing. The failover layer uses this to filter endpoints by\n // OllamaEndpoint.models (credential-scoped routing). We extract it\n // here rather than in the FailoverHttpClient because the runtime\n // has access to the request body.\n const model = req.model ?? extractModelFromBody(body);\n\n // Wave 17 (P1): merge header parameters from the InvokeRequest with\n // any existing headers. The operation may declare header parameters\n // (e.g. Authorization, Accept); the caller provides values via\n // req.headerParams.\n const headers: Record<string, string> = {};\n if (req.headerParams) {\n for (const [key, value] of Object.entries(req.headerParams)) {\n headers[key] = value;\n }\n }\n\n // The HttpClient expects the narrow method union 'GET' | 'POST' |\n // 'DELETE' | 'HEAD' | undefined — cast through `as` because our\n // OperationDefinition.method is the wider HttpMethod type.\n // Wave 15: pass the model through via a custom property on the\n // request options. The FailoverHttpClient reads this to pass to\n // executeWithFailover for model-scoped routing. Plain HttpClient\n // ignores it (it's not part of HttpRequestOptions).\n const httpReq = {\n path: pathWithQuery,\n method: req.operation.method as 'GET' | 'POST' | 'DELETE' | 'HEAD',\n ...(body !== undefined ? { body } : {}),\n ...(Object.keys(headers).length > 0 ? { headers } : {}),\n ...(req.signal !== undefined ? { signal: req.signal } : {}),\n ...(streaming ? { raw: true } : {}),\n ...(model !== undefined ? { model } : {}),\n } as HttpRequestOptions;\n\n if (!streaming) {\n const result = (await this.resolveHttpBackend(req.operation).request<T>(httpReq)) as T;\n // Wave 13: opt-in response validation. When `validateResponses: true`\n // is set and the operation has a registered response schema, validate\n // the response body before returning it. Throws\n // OllamaResponseValidationError on failure. Only use this for\n // operations where typed response semantics are critical (System One,\n // structured output) — don't enable globally.\n if (this.options.validateResponses === true) {\n const responseSchema = getResponseSchema(req.operation.operationId);\n if (responseSchema) {\n const result2 = responseSchema.safeParse(result);\n if (!result2.success) {\n throw new OllamaResponseValidationError(\n `Response validation failed for operation \"${req.operation.operationId}\" ` +\n `(${req.operation.method} ${req.operation.path}): ` +\n result2.error.issues\n .map((i) => `${i.path.join('.') || '<root>'}: ${i.message}`)\n .join('; '),\n {\n operationId: req.operation.operationId,\n issues: result2.error.issues,\n request: { method: req.operation.method, url: req.operation.path },\n },\n );\n }\n }\n }\n return result;\n }\n\n // Streaming: HttpClient returns the raw Response (via the `raw: true`\n // option) so we can read its body through the parser the contract\n // specifies for this operation.\n //\n // Wave 12 (P0 #2): the runtime now honors `operation.transport.mode`\n // instead of unconditionally parsing every stream as NDJSON. Native\n // Ollama operations (chat/generate/create/pull/push) declare\n // `transport.mode === 'ndjson'` and continue to use parseNdjsonStream;\n // OpenAI/Anthropic compatibility operations declare `transport.mode ===\n // 'sse'` and now correctly use the SSE parser, then JSON-decode each\n // event's `data` field. This closes the contract/runtime violation\n // where generated compat streaming was being parsed as NDJSON.\n const response = await this.resolveHttpBackend(req.operation).request<Response>(httpReq);\n if (!response.body) {\n throw new OllamaGenericClientError(\n `Operation ${req.operation.operationId}: streaming response had no body.`,\n );\n }\n return parseStreamByMode<T>(req.operation.transport.mode, response.body) as unknown as T;\n }\n\n /**\n * Apply environment + version guards before delegating to HttpClient.\n *\n * Throws {@link OllamaGenericClientError} when:\n * - The operation is local-only and the runtime is in cloud mode.\n * - The operation has `constraints.minOllamaVersion` and the server is older.\n *\n * Wave 12 (P0 #5): when `minOllamaVersion` is declared but the runtime's\n * `serverVersion` is unknown AND `enforceVersion` is `'auto'` or\n * `'strict'`, the runtime lazily fetches `/api/version` (cached on the\n * runtime instance) so the constraint is actually enforced even when the\n * caller didn't supply it. Previously the constraint was only enforced\n * when `serverVersion` was manually supplied — meaning in practice it was\n * almost never enforced.\n */\n private async assertOperationAllowed(operation: OperationDefinition): Promise<void> {\n const localMode = this.options.localMode ?? true;\n if (!localMode && !operation.environment.cloud) {\n throw new OllamaGenericClientError(\n `Operation ${operation.operationId} (${operation.method} ${operation.path}) ` +\n `is local-only and not supported in cloud mode.`,\n );\n }\n const minVersion = operation.constraints?.minOllamaVersion;\n if (!minVersion) return;\n\n let serverVersion = this.options.serverVersion;\n const policy = this.options.enforceVersion ?? 'auto';\n if (!serverVersion && policy !== 'off') {\n if (!this.serverVersionCache) {\n const p = fetchServerVersion(this.options.http).catch((err) => {\n if (policy === 'strict') {\n throw new OllamaServerVersionUnknownError(\n `Operation ${operation.operationId} requires Ollama >= ${minVersion} ` +\n `but the runtime could not determine the server version ` +\n `(enforceVersion: 'strict').`,\n {\n operationId: operation.operationId,\n minRequiredVersion: minVersion,\n cause: err,\n },\n );\n }\n // 'auto' — fail-open: surface nothing, the server will reject if\n // it can't handle it.\n return undefined;\n });\n this.serverVersionCache = p;\n }\n serverVersion = (await this.serverVersionCache) ?? undefined;\n }\n\n if (serverVersion && compareVersions(serverVersion, minVersion) < 0) {\n throw new OllamaGenericClientError(\n `Operation ${operation.operationId} (${operation.method} ${operation.path}) ` +\n `requires Ollama >= ${minVersion} (server reports ${serverVersion}).`,\n );\n }\n }\n}\n\n/**\n * Pick the stream parser that matches the operation's declared transport\n * mode, returning a uniform `AsyncGenerator<T>`.\n *\n * - `ndjson` → one JSON object per line (native Ollama streaming).\n * - `sse` → Server-Sent Events; each event's `data` field is parsed as\n * JSON. Heartbeat/comment-only events and events whose `data`\n * is the literal `[DONE]` sentinel are skipped (the OpenAI\n * compatibility layer uses that sentinel to terminate streams).\n * - `json` → not a streaming mode; callers should never reach this branch\n * for a non-streaming operation. We throw defensively so a\n * future operation that mis-declares its transport surfaces\n * loudly instead of silently degrading.\n */\nfunction parseStreamByMode<T>(\n mode: TransportMode,\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<T, void, undefined> {\n if (mode === 'ndjson') {\n return parseNdjsonStream<T>(body);\n }\n if (mode === 'sse') {\n return parseSseStreamAsJson<T>(body);\n }\n throw new OllamaGenericClientError(\n `Transport mode \"${mode}\" is not a streaming mode; cannot parse a stream for it.`,\n );\n}\n\n/**\n * Adapter that yields the JSON-decoded payload of each SSE `data` field.\n *\n * The hand-written OpenAI/Anthropic compatibility clients\n * (`src/integrations/{openai,anthropic}.ts`) consume raw `SseEvent`s and\n * apply provider-specific event-shape logic (tool-call accumulation,\n * reasoning deltas, etc.). The generated compatibility API surface is\n * intentionally shape-agnostic: it yields the raw JSON payload of each\n * event, leaving provider-specific interpretation to the caller. Consumers\n * who want the richer aggregated streaming experience should use\n * `client.openai` / `client.anthropic` instead of the generated API class.\n */\nasync function* parseSseStreamAsJson<T>(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<T, void, undefined> {\n for await (const event of parseSseStream(body)) {\n const data = event.data;\n if (!data) continue;\n // OpenAI's stream terminator sentinel — yield nothing; the generator\n // simply completes on the next iteration.\n if (data === '[DONE]') return;\n try {\n yield JSON.parse(data) as T;\n } catch (err) {\n throw new OllamaGenericClientError(`Failed to parse SSE event data as JSON: ${data}`, {\n cause: err,\n });\n }\n }\n}\n\n/**\n * Serialize a request body for byte counting (used by the\n * `maxRequestBytes` guard). The byte count mirrors what the HttpClient\n * would actually send on the wire: UTF-8 encoded JSON. Buffer (Node) and\n * Uint8Array inputs are passed through directly since their byte length\n * is already known.\n *\n * This intentionally mirrors HttpClient's serialization (`JSON.stringify`\n * with no whitespace) so the byte count is accurate against the actual\n * request payload — using a different serializer would let oversized\n * bodies through.\n */\nfunction serializeForByteCount(body: unknown): Uint8Array {\n if (body instanceof Uint8Array) return body;\n if (typeof body === 'string') return new TextEncoder().encode(body);\n // HttpClient calls JSON.stringify on the body before sending — match that.\n const json = JSON.stringify(body);\n return new TextEncoder().encode(json);\n}\n\n/**\n * Wave 13: detect whether a request body carries a non-empty `images`\n * array. Used by the request-size guard to select between the base\n * `maxRequestBytes` limit and the higher `maxRequestBytesWithImages`\n * limit (e.g. System One: 64 KiB without images, 32 MiB with).\n *\n * Returns true only when the body is an object with an `images` property\n * that is a non-empty array. Falsy/absent/empty images → false (base\n * limit applies).\n */\nfunction bodyHasImages(body: unknown): boolean {\n if (typeof body !== 'object' || body === null) return false;\n const obj = body as Record<string, unknown>;\n const images = obj.images;\n return Array.isArray(images) && images.length > 0;\n}\n\n/**\n * Wave 15 (P0): substitute path parameters into a path template.\n *\n * Replaces every `{name}` segment in the path with the URI-encoded value\n * from `pathParams`. If a `{name}` segment has no corresponding value in\n * `pathParams`, throws an error — sending a literal `{name}` to the server\n * would produce a confusing 404 rather than a clear client-side error.\n *\n * Example:\n * resolvePathParams('/v1/models/{model}', { model: 'gpt-4' })\n * → '/v1/models/gpt-4'\n *\n * resolvePathParams('/api/blobs/{digest}', { digest: 'sha256:abc' })\n * → '/api/blobs/sha256%3Aabc'\n */\nfunction resolvePathParams(\n pathTemplate: string,\n pathParams: Readonly<Record<string, string>> | undefined,\n): string {\n // If the path has no `{...}` segments, return it unchanged.\n if (!pathTemplate.includes('{')) return pathTemplate;\n\n const params = pathParams ?? {};\n return pathTemplate.replace(/\\{([^}]+)\\}/g, (_match, name: string) => {\n const value = params[name];\n if (value === undefined) {\n throw new OllamaGenericClientError(\n `Missing path parameter \"${name}\" for path template \"${pathTemplate}\". ` +\n `Provide it via the pathParams field on the invoke() request.`,\n );\n }\n return encodeURIComponent(value);\n });\n}\n\n/**\n * Wave 15 (P1): extract the `model` field from a request body for\n * failover routing. The failover layer uses this to filter endpoints by\n * `OllamaEndpoint.models` (credential-scoped routing). Returns undefined\n * for bodies that don't carry a model (e.g. GET /api/tags, GET /api/version).\n */\nfunction extractModelFromBody(body: unknown): string | undefined {\n if (typeof body !== 'object' || body === null) return undefined;\n const obj = body as Record<string, unknown>;\n const model = obj.model;\n return typeof model === 'string' ? model : undefined;\n}\n\n/**\n * Wave 17 (P1): append query parameters to a path.\n *\n * Takes a resolved path (e.g. `/api/tags`) and a map of query params\n * (e.g. `{ limit: '10' }`), returns the path with `?limit=10` appended.\n * Values are URI-encoded. If no query params are provided, the path is\n * returned unchanged.\n */\nfunction applyQueryParams(\n path: string,\n queryParams: Readonly<Record<string, string>> | undefined,\n): string {\n if (!queryParams || Object.keys(queryParams).length === 0) return path;\n const pairs = Object.entries(queryParams)\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)\n .join('&');\n return `${path}?${pairs}`;\n}\n","/**\n * Ergonomic OpenAI Responses API bridge — `client.responses.create()`.\n *\n * Ollama (v0.13.3+) exposes OpenAI's Responses API at `POST /v1/responses` as\n * a **stateless** compatibility endpoint: it accepts `model`, `input`,\n * `instructions`, `tools`, `stream`, `temperature`, `top_p`,\n * `max_output_tokens`, `reasoning.effort`, `truncation`, and the Ollama\n * extension `think` — and rejects OpenAI's stateful `previous_response_id` /\n * `conversation` fields, because every call is independent. Responses deliver\n * text inside `output[] → message → content[] → output_text` blocks rather\n * than chat-completion `choices`.\n *\n * This module wraps that endpoint with a small, OpenAI-SDK-shaped surface for\n * teams migrating from `openai.responses.create()` — and adds a safety net the\n * raw compat layer doesn't have: **dual-mode transport**.\n *\n * 1. **Native** — POST `/v1/responses` directly. Used when the server\n * supports it (Ollama ≥ v0.13.3, or Ollama Cloud).\n * 2. **Chat adapter** — on `404 Not Found` (older Ollama builds without the\n * endpoint), the same request is transparently re-issued against\n * `/api/chat` with `instructions` mapped to a system message,\n * `max_output_tokens` to `options.num_predict`, and tools mapped to the\n * native tool-definition shape. The response is normalized back into the\n * Responses form (`output_text`, `usage.input_tokens`/`output_tokens`),\n * so migrating code works unchanged against old servers.\n *\n * The `transport` field on the result records which path served the request.\n *\n * For the full OpenAI-shaped surface (stateful fields accepted-but-ignored,\n * raw `output` items, SSE event objects), use `client.openai.responses()`\n * instead — this module is the ergonomic subset.\n */\n\nimport { OllamaNotFoundError } from './errors.js';\nimport type {\n OpenAIResponsesResponse,\n OpenAIResponsesStream,\n OpenAIResponsesUsage,\n} from './integrations/openai.js';\nimport { OpenAIResponsesStream as OpenAIResponsesStreamClass } from './integrations/openai.js';\nimport { normalizeChatStream } from './streaming/normalize.js';\nimport type { ChatStreamResult } from './streaming/types.js';\nimport type {\n ChatResponse,\n RequestCancellationOptions,\n ThinkValue,\n ToolCall,\n ToolDefinition,\n ToolParameters,\n} from './types.js';\nimport type { RequestRunner } from './transport/runner.js';\n\n/** Flat tool definition, matching the `openai` npm SDK's `tools[]` shape. */\nexport interface ResponsesToolDefinition {\n readonly name: string;\n readonly description?: string | undefined;\n readonly parameters?: ToolParameters | undefined;\n}\n\n/** Reasoning effort levels Ollama's `/v1/responses` accepts under `reasoning.effort`. */\nexport type ResponsesReasoningEffort = 'low' | 'medium' | 'high';\n\n/**\n * Ergonomic request for {@link ResponsesModule.create} — the subset of\n * OpenAI's Responses API that Ollama supports, minus the stateful fields\n * (`previous_response_id`, `conversation`) Ollama rejects.\n */\nexport interface ResponsesCreateRequest extends RequestCancellationOptions {\n readonly model: string;\n /** The user prompt. Send the full conversation here — Ollama is stateless. */\n readonly input: string;\n /** System/developer instructions, mapped to a system message. */\n readonly instructions?: string | undefined;\n readonly tools?: readonly ResponsesToolDefinition[] | undefined;\n readonly temperature?: number | undefined;\n readonly top_p?: number | undefined;\n readonly max_output_tokens?: number | undefined;\n /** Maps to `reasoning.effort` on the native endpoint; ignored by the chat adapter. */\n readonly reasoning_effort?: ResponsesReasoningEffort | undefined;\n /** Ollama-specific extension: thinking output control (boolean or model-defined level). */\n readonly think?: ThinkValue | undefined;\n}\n\n/** Token usage in OpenAI Responses naming. */\nexport interface ResponsesUsage {\n readonly input_tokens: number;\n readonly output_tokens: number;\n readonly total_tokens: number;\n}\n\n/**\n * Normalized, non-stateful Responses result — `output_text` is the joined\n * text of all `output_text` content blocks, so consumers never touch the\n * nested `output[]` structure.\n */\nexport interface ResponsesCreateResponse {\n readonly id: string;\n readonly model: string;\n readonly created_at: string;\n readonly output_text: string;\n /** Reasoning-model thinking trace, when produced with `think` enabled. */\n readonly thinking?: string | undefined;\n /** Parsed function calls the model requested, when `tools` were provided. */\n readonly tool_calls?: readonly ToolCall[] | undefined;\n readonly usage?: ResponsesUsage | undefined;\n /** Which transport served the request — see the module doc on dual-mode. */\n readonly transport: 'native' | 'chat-adapter';\n}\n\n/** Simplified streaming events from {@link ResponsesModule.stream}. */\nexport type ResponsesStreamEvent =\n | { readonly type: 'text_delta'; readonly delta: string }\n | { readonly type: 'thinking_delta'; readonly delta: string }\n | { readonly type: 'done'; readonly response: ResponsesCreateResponse };\n\n/** Sequences client-synthesized response IDs for the chat-adapter path. */\nlet adapterResponseSequence = 0;\n\nfunction toNativeTools(\n tools: readonly ResponsesToolDefinition[] | undefined,\n): readonly ToolDefinition[] | undefined {\n if (tools === undefined || tools.length === 0) return undefined;\n return tools.map((tool) => ({\n type: 'function' as const,\n function: {\n name: tool.name,\n description: tool.description ?? '',\n parameters: tool.parameters ?? { type: 'object', properties: {} },\n },\n }));\n}\n\nfunction mapNativeUsage(usage: OpenAIResponsesUsage | undefined): ResponsesUsage | undefined {\n if (usage === undefined) return undefined;\n const input = usage.input_tokens ?? 0;\n const output = usage.output_tokens ?? 0;\n return { input_tokens: input, output_tokens: output, total_tokens: input + output };\n}\n\nfunction parseToolCallArguments(raw: string): Record<string, unknown> {\n if (raw === undefined || raw === null || raw === '') return {};\n try {\n const parsed = JSON.parse(raw) as unknown;\n return typeof parsed === 'object' && parsed !== null ? (parsed as Record<string, unknown>) : {};\n } catch {\n // Model emitted malformed JSON — surface the raw string under a stable\n // key rather than dropping the call entirely.\n return { _raw: raw };\n }\n}\n\n/** Extracts the joined `output_text` payload, thinking trace, and tool calls from a native response. */\nfunction mapNativeResponse(\n native: OpenAIResponsesResponse,\n): Pick<\n ResponsesCreateResponse,\n 'id' | 'model' | 'created_at' | 'output_text' | 'thinking' | 'tool_calls' | 'usage'\n> {\n const textParts: string[] = [];\n const thinkingParts: string[] = [];\n const toolCalls: ToolCall[] = [];\n for (const item of native.output ?? []) {\n if (item.type === 'message') {\n for (const part of item.content ?? []) {\n if (part.type === 'output_text') textParts.push(part.text ?? '');\n else if (part.type === 'refusal') textParts.push(part.refusal ?? '');\n }\n } else if (item.type === 'reasoning') {\n if (item.text !== undefined && item.text !== '') thinkingParts.push(item.text);\n } else if (item.type === 'function_call') {\n toolCalls.push({\n ...(item.id !== undefined ? { id: item.id } : {}),\n function: { name: item.name, arguments: parseToolCallArguments(item.arguments) },\n });\n }\n }\n return {\n id: native.id ?? `resp_${Date.now().toString(36)}`,\n model: native.model,\n created_at: new Date((native.created_at ?? 0) * 1000).toISOString(),\n output_text: textParts.join(''),\n ...(thinkingParts.length > 0 ? { thinking: thinkingParts.join('\\n') } : {}),\n ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),\n ...(mapNativeUsage(native.usage) !== undefined ? { usage: mapNativeUsage(native.usage)! } : {}),\n };\n}\n\nfunction mapChatUsage(res: ChatResponse | ChatStreamResult): ResponsesUsage | undefined {\n const asChat = res as ChatResponse;\n const asStream = res as ChatStreamResult;\n const input =\n asChat.prompt_eval_count ??\n asStream.usage?.promptTokens ??\n asStream.raw?.prompt_eval_count ??\n 0;\n const output =\n asChat.eval_count ?? asStream.usage?.completionTokens ?? asStream.raw?.eval_count ?? 0;\n if (input === 0 && output === 0) return undefined;\n return { input_tokens: input, output_tokens: output, total_tokens: input + output };\n}\n\n/** Maps a native `/api/chat` response into the Responses result shape. */\nfunction mapChatResponse(res: ChatResponse): ResponsesCreateResponse {\n adapterResponseSequence += 1;\n return {\n id: `resp_${Date.now().toString(36)}${adapterResponseSequence.toString(36)}`,\n model: res.model,\n created_at: res.created_at,\n output_text: res.message.content,\n ...(res.message.thinking !== undefined ? { thinking: res.message.thinking } : {}),\n ...(res.message.tool_calls !== undefined && res.message.tool_calls.length > 0\n ? { tool_calls: res.message.tool_calls }\n : {}),\n ...(mapChatUsage(res) !== undefined ? { usage: mapChatUsage(res)! } : {}),\n transport: 'chat-adapter',\n };\n}\n\n/**\n * Dual-mode Responses API bridge. Access via `client.responses` — see the\n * module doc for the transport selection rules.\n */\nexport class ResponsesModule {\n constructor(private readonly runner: RequestRunner) {}\n\n /** The request body sent to the native endpoint (also reused for streaming). */\n private nativeBody(req: ResponsesCreateRequest): Record<string, unknown> {\n return {\n model: req.model,\n input: req.input,\n ...(req.instructions !== undefined ? { instructions: req.instructions } : {}),\n ...(req.tools !== undefined && req.tools.length > 0\n ? { tools: toNativeTools(req.tools) }\n : {}),\n ...(req.temperature !== undefined ? { temperature: req.temperature } : {}),\n ...(req.top_p !== undefined ? { top_p: req.top_p } : {}),\n ...(req.max_output_tokens !== undefined ? { max_output_tokens: req.max_output_tokens } : {}),\n ...(req.reasoning_effort !== undefined\n ? { reasoning: { effort: req.reasoning_effort } }\n : {}),\n ...(req.think !== undefined ? { think: req.think } : {}),\n };\n }\n\n /**\n * Runs one Responses request, preferring the native `POST /v1/responses`\n * endpoint and transparently re-issuing via `/api/chat` when the server\n * answers `404` (pre-v0.13.3 Ollama without the compatibility endpoint).\n */\n async create(req: ResponsesCreateRequest): Promise<ResponsesCreateResponse> {\n const body = this.nativeBody(req);\n try {\n const native = await this.runner(\n (http, signal) =>\n http.request<OpenAIResponsesResponse>({\n path: '/v1/responses',\n body: { ...body, stream: false },\n signal,\n }),\n { model: req.model, signal: req.signal, timeoutMs: req.timeoutMs },\n );\n return { ...mapNativeResponse(native), transport: 'native' };\n } catch (err) {\n if (!(err instanceof OllamaNotFoundError)) throw err;\n }\n return this.createViaChatAdapter(req);\n }\n\n /** Convenience: `create()` returning only the `output_text` string. */\n async createText(req: ResponsesCreateRequest): Promise<string> {\n const res = await this.create(req);\n return res.output_text;\n }\n\n private async createViaChatAdapter(\n req: ResponsesCreateRequest,\n ): Promise<ResponsesCreateResponse> {\n const messages = [\n ...(req.instructions !== undefined\n ? [{ role: 'system' as const, content: req.instructions }]\n : []),\n { role: 'user' as const, content: req.input },\n ];\n const chatRes = await this.runner(\n (http, signal) =>\n http.request<ChatResponse>({\n path: '/api/chat',\n body: {\n model: req.model,\n messages,\n ...(req.tools !== undefined && req.tools.length > 0\n ? { tools: toNativeTools(req.tools) }\n : {}),\n options: {\n ...(req.temperature !== undefined ? { temperature: req.temperature } : {}),\n ...(req.top_p !== undefined ? { top_p: req.top_p } : {}),\n ...(req.max_output_tokens !== undefined\n ? { num_predict: req.max_output_tokens }\n : {}),\n },\n ...(req.think !== undefined ? { think: req.think } : {}),\n stream: false,\n },\n signal,\n }),\n { model: req.model, signal: req.signal, timeoutMs: req.timeoutMs },\n );\n return mapChatResponse(chatRes);\n }\n\n /**\n * Streams a Responses request as simplified\n * `{type: 'text_delta' | 'thinking_delta' | 'done'}` events. Dual-mode like\n * {@link create}: native SSE from `/v1/responses` when available, otherwise\n * the normalized `/api/chat` token stream. Tool calls are not delta'd —\n * collect them from the final `done` event's `response.tool_calls`.\n *\n * This is a lazy async generator: nothing is sent until the first\n * iteration, matching `for await (... of client.responses.stream(req))`\n * intuition. The generator is also cancellable through `req.signal`.\n */\n async *stream(req: ResponsesCreateRequest): AsyncGenerator<ResponsesStreamEvent, void, void> {\n const body = this.nativeBody(req);\n\n // Phase 1 — establish the native stream. A 404 here (endpoint absent)\n // falls through to the chat adapter. Errors during iteration (phase 2)\n // do NOT trigger the fallback — the consumer may already have consumed\n // partial output, so silently re-issuing would duplicate it.\n let nativeStream: OpenAIResponsesStream | undefined;\n try {\n nativeStream = await this.runner(\n async (http, signal) => {\n const source = await http.requestSseStream({\n path: '/v1/responses',\n body: { ...body, stream: true },\n signal,\n });\n return new OpenAIResponsesStreamClass(source, signal);\n },\n {\n model: req.model,\n signal: req.signal,\n timeoutMs: req.timeoutMs,\n holdUntil: (s) => s.finalResult,\n },\n );\n } catch (err) {\n if (!(err instanceof OllamaNotFoundError)) throw err;\n }\n\n if (nativeStream !== undefined) {\n for await (const event of nativeStream) {\n // The stream-event union carries a `{ type: string; [k: string]: unknown }`\n // forward-compat catch-all, so narrow by casting rather than by\n // discriminated-union checks.\n const type = (event as { type: string }).type;\n if (type === 'response.output_text.delta') {\n yield { type: 'text_delta', delta: (event as { delta: string }).delta };\n } else if (type === 'response.reasoning_text.delta') {\n yield { type: 'thinking_delta', delta: (event as { delta: string }).delta };\n }\n }\n yield {\n type: 'done',\n response: { ...mapNativeResponse(await nativeStream.finalResult), transport: 'native' },\n };\n return;\n }\n\n // Phase 2 — chat-adapter fallback stream.\n const chatStream = await this.runner(\n async (http, signal) => {\n const source = await http.requestStream<ChatResponse>({\n path: '/api/chat',\n body: {\n model: req.model,\n messages: [\n ...(req.instructions !== undefined\n ? [{ role: 'system' as const, content: req.instructions }]\n : []),\n { role: 'user' as const, content: req.input },\n ],\n ...(req.tools !== undefined && req.tools.length > 0\n ? { tools: toNativeTools(req.tools) }\n : {}),\n options: {\n ...(req.temperature !== undefined ? { temperature: req.temperature } : {}),\n ...(req.top_p !== undefined ? { top_p: req.top_p } : {}),\n ...(req.max_output_tokens !== undefined\n ? { num_predict: req.max_output_tokens }\n : {}),\n },\n ...(req.think !== undefined ? { think: req.think } : {}),\n stream: true,\n },\n signal,\n });\n return normalizeChatStream(source, signal);\n },\n {\n model: req.model,\n signal: req.signal,\n timeoutMs: req.timeoutMs,\n holdUntil: (s) => s.finalResult,\n },\n );\n\n // Iterate first — `finalResult` only settles once the stream has been\n // fully consumed (see OllamaStream), so awaiting it before the loop would\n // deadlock. Buffer nothing here; consumers see deltas live.\n for await (const event of chatStream) {\n if (event.type === 'token') {\n yield { type: 'text_delta', delta: (event.data as { delta: string }).delta };\n } else if (event.type === 'thinking') {\n yield { type: 'thinking_delta', delta: (event.data as { delta: string }).delta };\n }\n }\n const result = await chatStream.finalResult;\n yield {\n type: 'done',\n response: {\n id: `resp_${Date.now().toString(36)}${(++adapterResponseSequence).toString(36)}`,\n model: result.model,\n created_at: new Date().toISOString(),\n output_text: result.message.content,\n ...(result.message.thinking !== undefined ? { thinking: result.message.thinking } : {}),\n ...(result.message.tool_calls !== undefined && result.message.tool_calls.length > 0\n ? { tool_calls: result.message.tool_calls }\n : {}),\n ...(mapChatUsage(result) !== undefined ? { usage: mapChatUsage(result)! } : {}),\n transport: 'chat-adapter',\n },\n };\n }\n}\n","/**\n * KV-prefix-preserving conversation sessions.\n *\n * Ollama reuses the model's KV cache across turns of a conversation by\n * **prompt prefix matching**: if the new prompt's leading tokens are\n * byte-identical to the previous turn's, the cached prefix is reused and\n * only the new suffix is evaluated — surfaced by the server as\n * `prompt_eval_cached_count`. Anything that mutates the prefix invalidates\n * the whole cache and forces a full re-evaluation (`prompt_eval_count`\n * spikes, latency jumps): changing the system prompt, prepending dynamic\n * timestamps or request IDs to the conversation, or reordering past turns.\n *\n * `ConversationSession` makes the cache-friendly structure the default:\n *\n * - The system prompt (if any) is fixed at construction and always the\n * first message. There is deliberately **no API to mutate it later** —\n * a mutable system prompt is the #1 silent KV-cache killer.\n * - History is append-only. Messages are never reordered, rewritten, or\n * re-serialized between turns — `getMessages()` copies, so external\n * mutation can't leak in either.\n * - Per-turn options (`options`, `think`, `tools`, …) ride on the request,\n * not the history, so changing them never disturbs the prefix.\n *\n * Each turn records what the server reported about the cache, so degrading\n * hit rates (a symptom of prefix churn somewhere upstream, or a context\n * window that no longer holds the whole history) are visible in\n * {@link ConversationSession.cacheStats} instead of hiding in raw responses.\n */\n\nimport type { OllamaClient } from './client.js';\nimport type {\n ChatRequestOptions,\n ChatResponse,\n FormatOption,\n Message,\n ModelOptions,\n ThinkValue,\n ToolDefinition,\n} from './types.js';\n\n/** What one turn's response reported about KV-cache reuse and evaluation. */\nexport interface TurnCacheStats {\n /** Prompt tokens served from the KV cache this turn. */\n readonly cachedTokens: number;\n /** Prompt tokens freshly evaluated this turn. */\n readonly evaluatedTokens: number;\n /**\n * Cache hit rate for this turn: `cached / (cached + evaluated)`.\n *\n * Note the denominator adds both counters — when the *entire* prompt hits\n * the cache, Ollama reports `prompt_eval_count: 0`, so dividing by\n * `prompt_eval_count` alone would falsely yield a 0% hit rate on the\n * best-case turn.\n */\n readonly hitRate: number;\n}\n\n/** Cumulative cache statistics across every completed turn so far. */\nexport interface CumulativeCacheStats extends TurnCacheStats {\n /** Number of completed turns (user+assistant pairs). */\n readonly turns: number;\n /** Total prompt tokens across turns, cached + evaluated. */\n readonly totalPromptTokens: number;\n}\n\n/** Everything one {@link ConversationSession.sendTurn} call knows. */\nexport interface SessionTurn {\n /** The assistant's text reply (same value `send()` returns). */\n readonly content: string;\n /** What the server reported about KV-cache reuse for this turn. */\n readonly cache: TurnCacheStats;\n /** The full underlying `/api/chat` response (usage, durations, thinking, …). */\n readonly response: ChatResponse;\n}\n\n/** Per-turn overrides — none of these touch the history prefix, so they are KV-safe. */\nexport interface ConversationSendOptions extends Pick<ChatRequestOptions, 'signal' | 'timeoutMs'> {\n readonly options?: ModelOptions | undefined;\n readonly think?: ThinkValue | undefined;\n readonly keep_alive?: string | number | undefined;\n readonly tools?: readonly ToolDefinition[] | undefined;\n readonly format?: FormatOption | undefined;\n}\n\n/** Static configuration for a session, fixed at construction (KV-prefix safety). */\nexport interface ConversationSessionOptions {\n readonly model: string;\n /**\n * System prompt, pinned as the first history message for the session's\n * whole lifetime. Avoid dynamic content here (timestamps, request IDs) —\n * a per-call system prompt defeats prefix caching entirely.\n */\n readonly systemPrompt?: string | undefined;\n /** Default `options` (sampler settings, `num_ctx`, …) applied to every turn. */\n readonly options?: ModelOptions | undefined;\n /** Default `think` control applied to every turn. */\n readonly think?: ThinkValue | undefined;\n /** Default `keep_alive` applied to every turn. */\n readonly keep_alive?: string | number | undefined;\n /** Default `tools` applied to every turn. */\n readonly tools?: readonly ToolDefinition[] | undefined;\n /** Default `format` (structured output) applied to every turn. */\n readonly format?: FormatOption | undefined;\n}\n\nfunction extractTurnStats(res: ChatResponse): TurnCacheStats {\n const cachedTokens = res.prompt_eval_cached_count ?? 0;\n const evaluatedTokens = res.prompt_eval_count ?? 0;\n const total = cachedTokens + evaluatedTokens;\n return {\n cachedTokens,\n evaluatedTokens,\n hitRate: total > 0 ? cachedTokens / total : 0,\n };\n}\n\n/**\n * A multi-turn chat session with an immutable, cache-friendly message\n * history. Create via `client.session(...)` or construct directly:\n *\n * ```ts\n * const session = client.session('llama3.1', 'You are a concise assistant.');\n * await session.send('Hi!'); // turn 1 — cold cache\n * await session.send('Why is the sky blue?'); // turn 2 — prefix reused\n * session.cacheStats; // cumulative hit rate\n * ```\n */\nexport class ConversationSession {\n /** Ordered, append-only history. Message objects are frozen on push. */\n private readonly history: Message[] = [];\n /** Mutable tallies behind the read-only {@link cacheStats} view. */\n private readonly tallies = {\n turns: 0,\n cachedTokens: 0,\n evaluatedTokens: 0,\n };\n\n constructor(\n private readonly client: OllamaClient,\n private readonly config: ConversationSessionOptions,\n ) {\n if (config.systemPrompt !== undefined && config.systemPrompt !== '') {\n this.history.push(Object.freeze({ role: 'system', content: config.systemPrompt }) as Message);\n }\n }\n\n /** The model name this session talks to. */\n get model(): string {\n return this.config.model;\n }\n\n /** Number of completed turns. */\n get turnCount(): number {\n return this.tallies.turns;\n }\n\n /** Cumulative KV-cache statistics across completed turns. */\n get cacheStats(): CumulativeCacheStats {\n const total = this.tallies.cachedTokens + this.tallies.evaluatedTokens;\n return {\n turns: this.tallies.turns,\n cachedTokens: this.tallies.cachedTokens,\n evaluatedTokens: this.tallies.evaluatedTokens,\n totalPromptTokens: total,\n hitRate: total > 0 ? this.tallies.cachedTokens / total : 0,\n };\n }\n\n /**\n * Sends the user's message and returns the assistant's reply text —\n * the ergonomic path. Use {@link sendTurn} when you also need the\n * per-turn cache statistics or the raw response.\n */\n async send(content: string, overrides?: ConversationSendOptions): Promise<string> {\n const turn = await this.sendTurn(content, overrides);\n return turn.content;\n }\n\n /**\n * Sends the user's message and returns the full turn record: reply text,\n * per-turn KV-cache statistics, and the raw `/api/chat` response.\n */\n async sendTurn(content: string, overrides?: ConversationSendOptions): Promise<SessionTurn> {\n this.history.push(Object.freeze({ role: 'user', content }) as Message);\n\n const response = await this.client.chat({\n model: this.config.model,\n messages: [...this.history],\n ...(this.config.tools !== undefined || overrides?.tools !== undefined\n ? { tools: overrides?.tools ?? this.config.tools }\n : {}),\n ...(this.config.format !== undefined || overrides?.format !== undefined\n ? { format: overrides?.format ?? this.config.format }\n : {}),\n options: { ...this.config.options, ...overrides?.options },\n ...(this.config.think !== undefined || overrides?.think !== undefined\n ? { think: overrides?.think ?? this.config.think }\n : {}),\n ...(this.config.keep_alive !== undefined || overrides?.keep_alive !== undefined\n ? { keep_alive: overrides?.keep_alive ?? this.config.keep_alive }\n : {}),\n ...(overrides?.signal !== undefined ? { signal: overrides.signal } : {}),\n ...(overrides?.timeoutMs !== undefined ? { timeoutMs: overrides.timeoutMs } : {}),\n stream: false,\n });\n\n // Append exactly what the server produced (content, tool_calls, thinking)\n // — reusing the response's message object verbatim guarantees the next\n // turn's prefix matches what the model actually saw.\n this.history.push(Object.freeze({ ...response.message }) as Message);\n\n const cache = extractTurnStats(response);\n this.tallies.turns += 1;\n this.tallies.cachedTokens += cache.cachedTokens;\n this.tallies.evaluatedTokens += cache.evaluatedTokens;\n\n return { content: response.message.content, cache, response };\n }\n\n /**\n * A defensive copy of the session history — mutating the returned array or\n * its frozen messages has no effect on the session.\n */\n getMessages(): readonly Message[] {\n return this.history.map((message) => message);\n }\n\n /**\n * Clears the conversation back to its initial state (system prompt, zero\n * turns, zeroed cache statistics). The next turn starts with a cold cache\n * by definition — there is nothing upstream of it to reuse.\n */\n reset(): void {\n this.history.length = 0;\n if (this.config.systemPrompt !== undefined && this.config.systemPrompt !== '') {\n this.history.push(\n Object.freeze({ role: 'system', content: this.config.systemPrompt }) as Message,\n );\n }\n this.tallies.turns = 0;\n this.tallies.cachedTokens = 0;\n this.tallies.evaluatedTokens = 0;\n }\n}\n","/**\n * Context-window safety: client-side token estimation and pre-flight overflow\n * warnings for `/api/chat` and `/api/generate`.\n *\n * Why this exists: when `options.num_ctx` is left unset, Ollama loads the\n * model with a conservative default context window (commonly 2048–4096\n * tokens, model-dependent) and **silently truncates** any prompt that doesn't\n * fit — the model just loses the top of the conversation with no error, no\n * warning, and often no visible symptom beyond degraded answers. This module\n * estimates the prompt size client-side (a fast heuristic — no tokenizer\n * download, no model dependency) and surfaces a warning *before* the request\n * is sent, when the estimate approaches the effective context window.\n *\n * The estimator is deliberately simple and documented as approximate\n * (±20–30% vs a real BPE tokenizer):\n *\n * - CJK code points (Chinese/Japanese/Korean) count as ~1 token each —\n * modern tokenizers emit roughly one token per CJK character.\n * - Everything else estimates at ~4 characters per token, the classic\n * English GPT-style average.\n * - Each attached image adds a fixed {@link IMAGE_TOKEN_ESTIMATE} —\n * vision encoders consume a roughly predictable tile budget per image\n * (e.g. LLaVA-family encoders emit a few hundred tokens per image).\n *\n * It is used in three places:\n *\n * 1. `OllamaClient.chat()`/`generate()` pre-flight — logs a warning (or\n * throws, per `onContextOverflow`) when the estimate crosses\n * {@link DEFAULT_CONTEXT_WARNING_THRESHOLD} of the effective window.\n * 2. The `defaultContextLength` client config — injects `num_ctx` when the\n * caller didn't set one, making the effective window explicit instead\n * of server-default guesswork.\n * 3. `ConversationSession` — sessions grow monotonically, so they surface\n * cache and context stats per turn.\n */\n\nimport type { ChatRequestOptions, GenerateRequestOptions, Message } from './types.js';\n\n/**\n * Fraction of the effective context window at which a pre-flight warning\n * fires. 0.9 = warn when the estimated prompt reaches 90% of `num_ctx`.\n * Above this, the response has little room left and the next turn's history\n * will almost certainly overflow.\n */\nexport const DEFAULT_CONTEXT_WARNING_THRESHOLD = 0.9;\n\n/**\n * Rough token budget consumed per attached image. Vision encoders emit a few\n * hundred embedding tokens per image tile; 300 sits between LLaVA-1.5's ~258\n * and qwen-vl's higher tile counts. This is an estimate for warning purposes\n * only — it never gates a request on its own unless images push the total\n * past the threshold.\n */\nexport const IMAGE_TOKEN_ESTIMATE = 300;\n\n/** Tokens estimated per non-CJK character of text. */\nconst CHARS_PER_TOKEN = 4;\n\n/** CJK Unified Ideographs and the common extension/full-width ranges. */\nfunction isCjkCodePoint(code: number): boolean {\n return (\n (code >= 0x4e00 && code <= 0x9fff) || // CJK Unified Ideographs\n (code >= 0x3400 && code <= 0x4dbf) || // CJK Extension A\n (code >= 0x3040 && code <= 0x30ff) || // Hiragana + Katakana\n (code >= 0xac00 && code <= 0xd7af) || // Hangul syllables\n (code >= 0xf900 && code <= 0xfaff) || // CJK Compatibility Ideographs\n (code >= 0xff00 && code <= 0xffef) // Full-width forms\n );\n}\n\n/**\n * Heuristic token estimate for a single text string: ~1 token per CJK\n * character + ~1 token per 4 non-CJK characters. Approximate by design —\n * accurate enough to warn against silent truncation without shipping a\n * model-specific tokenizer.\n */\nexport function estimateTokens(text: string): number {\n if (text.length === 0) return 0;\n let cjk = 0;\n let other = 0;\n for (const char of text) {\n if (isCjkCodePoint(char.codePointAt(0) ?? 0)) cjk += 1;\n else other += 1;\n }\n return Math.ceil(cjk + other / CHARS_PER_TOKEN);\n}\n\n/** Rough per-message framing overhead: role tags, chat-template delimiters. */\nconst MESSAGE_OVERHEAD_TOKENS = 4;\n\nfunction estimateMessageTokens(message: Message): number {\n let total = MESSAGE_OVERHEAD_TOKENS + estimateTokens(message.content ?? '');\n if (message.thinking !== undefined) total += estimateTokens(message.thinking);\n if (message.tool_calls !== undefined) {\n for (const call of message.tool_calls) {\n total += estimateTokens(call.function.name);\n total += estimateTokens(JSON.stringify(call.function.arguments ?? {}));\n }\n }\n if (message.images !== undefined) total += message.images.length * IMAGE_TOKEN_ESTIMATE;\n return total;\n}\n\n/**\n * Estimated prompt tokens for a `/api/chat` request: every message plus\n * tool-schema overhead (each tool definition's JSON schema serializes into\n * the prompt on Ollama's side).\n */\nexport function estimateChatRequestTokens(req: ChatRequestOptions): number {\n let total = 0;\n for (const message of req.messages) total += estimateMessageTokens(message);\n if (req.tools !== undefined) {\n for (const tool of req.tools) {\n total += estimateTokens(tool.function.description ?? '');\n total += estimateTokens(JSON.stringify(tool.function.parameters ?? {}));\n }\n }\n return total;\n}\n\n/** Estimated prompt tokens for a `/api/generate` request (prompt + system + images). */\nexport function estimateGenerateRequestTokens(req: GenerateRequestOptions): number {\n let total = estimateTokens(req.prompt ?? '');\n if (req.system !== undefined) total += estimateTokens(req.system);\n if (req.template !== undefined) total += estimateTokens(req.template);\n if (req.images !== undefined) total += req.images.length * IMAGE_TOKEN_ESTIMATE;\n return total;\n}\n\n/** Where the context window used by a pre-flight check came from. */\nexport type ContextWindowSource =\n /** Explicit `options.num_ctx` on the request — exact, server-enforced. */\n | 'request'\n /** Client `defaultContextLength` config — injected as `num_ctx` by the pipeline. */\n | 'client-default'\n /** Neither set; Ollama's server default applies (2048–4096, model-dependent). */\n | 'server-fallback';\n\n/** What the pre-flight check concluded about one request. */\nexport interface ContextCheck {\n /** Estimated prompt tokens (heuristic — see {@link estimateTokens}). */\n readonly estimatedPromptTokens: number;\n /** The context window the estimate was compared against. */\n readonly effectiveContextLength: number;\n /** Where that window came from. */\n readonly windowSource: ContextWindowSource;\n /** True when the estimate crossed the warning threshold of the effective window. */\n readonly exceedsThreshold: boolean;\n}\n\nexport interface ContextCheckOptions {\n /** Client `defaultContextLength`, applied when the request doesn't set `num_ctx`. */\n readonly defaultContextLength?: number | undefined;\n /** Warning threshold; defaults to {@link DEFAULT_CONTEXT_WARNING_THRESHOLD}. */\n readonly threshold?: number | undefined;\n}\n\n/**\n * Runs the pre-flight context check for a chat request. Pure — callers decide\n * what to do with the result (log, throw, ignore).\n */\nexport function checkChatContext(\n req: ChatRequestOptions,\n options: ContextCheckOptions = {},\n): ContextCheck {\n return check(estimateChatRequestTokens(req), req.options?.num_ctx, options);\n}\n\n/**\n * Runs the pre-flight context check for a generate request. Pure — callers\n * decide what to do with the result (log, throw, ignore).\n */\nexport function checkGenerateContext(\n req: GenerateRequestOptions,\n options: ContextCheckOptions = {},\n): ContextCheck {\n return check(estimateGenerateRequestTokens(req), req.options?.num_ctx, options);\n}\n\nfunction check(\n estimatedPromptTokens: number,\n requestNumCtx: number | undefined,\n options: ContextCheckOptions,\n): ContextCheck {\n const threshold = options.threshold ?? DEFAULT_CONTEXT_WARNING_THRESHOLD;\n // With no explicit window anywhere, compare against the conservative 2048\n // fallback *without* the safety margin — the real server default may be as\n // high as 4096, so warning at merely 90% of an assumed 2048 would produce\n // false positives. Only flag prompts that outright exceed the fallback.\n if (requestNumCtx !== undefined) {\n return {\n estimatedPromptTokens,\n effectiveContextLength: requestNumCtx,\n windowSource: 'request',\n exceedsThreshold: estimatedPromptTokens > requestNumCtx * threshold,\n };\n }\n if (options.defaultContextLength !== undefined) {\n return {\n estimatedPromptTokens,\n effectiveContextLength: options.defaultContextLength,\n windowSource: 'client-default',\n exceedsThreshold: estimatedPromptTokens > options.defaultContextLength * threshold,\n };\n }\n return {\n estimatedPromptTokens,\n effectiveContextLength: OLLAMA_FALLBACK_CONTEXT_LENGTH,\n windowSource: 'server-fallback',\n exceedsThreshold: estimatedPromptTokens > OLLAMA_FALLBACK_CONTEXT_LENGTH,\n };\n}\n\n/**\n * The conservative server-side default (2048) Ollama most commonly applies\n * when `num_ctx` is unset — used to warn about *likely* truncation even when\n * no effective window is known client-side.\n */\nexport const OLLAMA_FALLBACK_CONTEXT_LENGTH = 2048;\n\n/**\n * Builds the human-readable warning text for a failed pre-flight check.\n * Exported for reuse by `ConversationSession` and for tests.\n */\nexport function contextWarningMessage(check: ContextCheck, kind: 'chat' | 'generate'): string {\n const where = `OllamaClient.${kind}()`;\n const estimate = `~${check.estimatedPromptTokens} tokens`;\n if (check.windowSource === 'request') {\n return (\n `${where}: estimated prompt size ${estimate} is close to or beyond the request's ` +\n `context window (num_ctx=${check.effectiveContextLength}). The server will likely ` +\n `silently truncate the top of the conversation — the model loses earlier turns with ` +\n `no error. Raise \\`options.num_ctx\\` or shorten the conversation. ` +\n `Estimates are heuristic (±20–30%); see \\`estimateTokens\\`.`\n );\n }\n if (check.windowSource === 'client-default') {\n return (\n `${where}: estimated prompt size ${estimate} is close to or beyond the client's ` +\n `\\`defaultContextLength\\` (${check.effectiveContextLength}, injected as \\`num_ctx\\`). ` +\n `The server will likely silently truncate the top of the conversation — the model ` +\n `loses earlier turns with no error. Raise \\`defaultContextLength\\`, set \\`options.num_ctx\\` ` +\n `per request, or shorten the conversation. ` +\n `Estimates are heuristic (±20–30%); see \\`estimateTokens\\`.`\n );\n }\n return (\n `${where}: estimated prompt size ${estimate} outright exceeds Ollama's conservative ` +\n `server-default context window (${OLLAMA_FALLBACK_CONTEXT_LENGTH}–4096 tokens when ` +\n `\\`num_ctx\\` is unset — model-dependent). Unless the model's default is larger, the ` +\n `server will silently truncate the top of the conversation — the model loses earlier ` +\n `turns with no error. Set \\`options.num_ctx\\` (or the client's \\`defaultContextLength\\`) ` +\n `to an explicit window to make truncation visible and controllable. ` +\n `Estimates are heuristic (±20–30%); see \\`estimateTokens\\`.`\n );\n}\n","/**\n * AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n * Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n * Each OperationDefinition captures what Ollama exposes; the runtime\n * in src/generated/runtime/runtime.ts captures how the SDK behaves.\n */\n\nimport type { OperationDefinition } from '../runtime/operation-definition.js';\n\nexport const balanceOp = {\n operationId: 'balance',\n method: 'GET',\n path: '/api/balance',\n response: { $ref: '#/schemas/BalanceResponse' },\n environment: { local: false, cloud: true },\n host: 'https://ollama.com',\n transport: { mode: 'json', streaming: false },\n capabilities: {},\n status: { documented: true },\n domain: 'native',\n notes: [\n 'Cloud-only account endpoint — targets https://ollama.com, not the local Ollama server.',\n 'Requires an Ollama Cloud API key (set via OllamaClient credentials).',\n 'Takes no parameters. For usage history see the usage operation.',\n 'Rate limited to 10 requests/minute per user; 429 responses carry a Retry-After header.',\n 'Use OllamaClient.balance() — the generated NativeApi class does not expose this operation.',\n ],\n} as const satisfies OperationDefinition;\n\nexport const blobsOp = {\n operationId: 'blobs',\n method: 'HEAD',\n path: '/api/blobs/{digest}',\n environment: { local: true, cloud: false },\n parameters: [{ name: 'digest', in: 'path', required: true, schema: { type: 'string' } }],\n transport: { mode: 'json', streaming: false },\n capabilities: {},\n status: { documented: true },\n domain: 'native',\n notes: [\n 'HEAD-only endpoint for blob existence checks; declared in OpenAPI but not in the legacy parity manifest.',\n ],\n} as const satisfies OperationDefinition;\n\nexport const chatOp = {\n operationId: 'chat',\n method: 'POST',\n path: '/api/chat',\n request: { $ref: '#/schemas/ChatRequest' },\n response: { $ref: '#/schemas/ChatResponse' },\n environment: { local: true, cloud: true },\n transport: { mode: 'ndjson', streaming: true, streamingDefault: true },\n capabilities: {\n thinking: 'model-dependent',\n tools: 'model-dependent',\n vision: 'model-dependent',\n structuredOutput: 'supported',\n logprobs: 'supported',\n },\n status: { documented: true },\n domain: 'native',\n notes: [\n 'Use /api/show to discover model-specific thinking values and defaults.',\n 'Structured output (format field) is rejected by Ollama Cloud.',\n ],\n} as const satisfies OperationDefinition;\n\nexport const copyOp = {\n operationId: 'copy',\n method: 'POST',\n path: '/api/copy',\n request: { $ref: '#/schemas/CopyRequest' },\n environment: { local: true, cloud: false },\n transport: { mode: 'json', streaming: false },\n capabilities: {},\n status: { documented: true },\n domain: 'native',\n} as const satisfies OperationDefinition;\n\nexport const createOp = {\n operationId: 'create',\n method: 'POST',\n path: '/api/create',\n request: { $ref: '#/schemas/CreateRequest' },\n response: { $ref: '#/schemas/StatusResponse' },\n environment: { local: true, cloud: false },\n transport: { mode: 'ndjson', streaming: true, streamingDefault: true },\n capabilities: { thinking: 'unsupported', tools: 'unsupported' },\n status: { documented: true },\n domain: 'native',\n notes: ['Model creation is local-only; Ollama Cloud does not support it.'],\n} as const satisfies OperationDefinition;\n\nexport const createBlobOp = {\n operationId: 'createBlob',\n method: 'POST',\n path: '/api/blobs/{digest}',\n environment: { local: true, cloud: false },\n parameters: [{ name: 'digest', in: 'path', required: true, schema: { type: 'string' } }],\n transport: { mode: 'json', streaming: false },\n capabilities: {},\n status: { documented: true },\n domain: 'native',\n notes: [\n 'POST endpoint for blob creation; takes a binary body (application/octet-stream).',\n 'Handled by OllamaClient.createBlob() — the generated NativeApi does not expose this operation because the runtime JSON-encodes request bodies.',\n ],\n} as const satisfies OperationDefinition;\n\nexport const deleteOp = {\n operationId: 'delete',\n method: 'DELETE',\n path: '/api/delete',\n request: { $ref: '#/schemas/DeleteRequest' },\n environment: { local: true, cloud: false },\n transport: { mode: 'json', streaming: false },\n capabilities: {},\n status: { documented: true },\n domain: 'native',\n} as const satisfies OperationDefinition;\n\nexport const embedOp = {\n operationId: 'embed',\n method: 'POST',\n path: '/api/embed',\n request: { $ref: '#/schemas/EmbedRequest' },\n response: { $ref: '#/schemas/EmbedResponse' },\n environment: { local: true, cloud: true },\n transport: { mode: 'json', streaming: false },\n capabilities: { embeddings: 'supported' },\n status: { documented: true },\n domain: 'native',\n} as const satisfies OperationDefinition;\n\nexport const generateOp = {\n operationId: 'generate',\n method: 'POST',\n path: '/api/generate',\n request: { $ref: '#/schemas/GenerateRequest' },\n response: { $ref: '#/schemas/GenerateResponse' },\n environment: { local: true, cloud: true },\n transport: { mode: 'ndjson', streaming: true, streamingDefault: true },\n capabilities: {\n thinking: 'model-dependent',\n vision: 'supported',\n structuredOutput: 'supported',\n logprobs: 'supported',\n },\n status: { documented: true },\n domain: 'native',\n} as const satisfies OperationDefinition;\n\nexport const psOp = {\n operationId: 'ps',\n method: 'GET',\n path: '/api/ps',\n response: { $ref: '#/schemas/PsResponse' },\n environment: { local: true, cloud: true },\n transport: { mode: 'json', streaming: false },\n capabilities: {},\n status: { documented: true },\n domain: 'native',\n} as const satisfies OperationDefinition;\n\nexport const pullOp = {\n operationId: 'pull',\n method: 'POST',\n path: '/api/pull',\n request: { $ref: '#/schemas/PullRequest' },\n response: { $ref: '#/schemas/StatusResponse' },\n environment: { local: true, cloud: false },\n transport: { mode: 'ndjson', streaming: true, streamingDefault: true },\n capabilities: {},\n status: { documented: true },\n domain: 'native',\n} as const satisfies OperationDefinition;\n\nexport const pushOp = {\n operationId: 'push',\n method: 'POST',\n path: '/api/push',\n request: { $ref: '#/schemas/PushRequest' },\n response: { $ref: '#/schemas/StatusResponse' },\n environment: { local: true, cloud: false },\n transport: { mode: 'ndjson', streaming: true, streamingDefault: true },\n capabilities: {},\n status: { documented: true },\n domain: 'native',\n} as const satisfies OperationDefinition;\n\nexport const showOp = {\n operationId: 'show',\n method: 'POST',\n path: '/api/show',\n request: { $ref: '#/schemas/ShowRequest' },\n response: { $ref: '#/schemas/ShowResponse' },\n environment: { local: true, cloud: true },\n transport: { mode: 'json', streaming: false },\n capabilities: {},\n status: { documented: true },\n domain: 'native',\n notes: [\n 'Capabilities source: /api/show is the runtime source of truth for model-dependent capability values (tools, vision, thinking, embeddings).',\n ],\n} as const satisfies OperationDefinition;\n\nexport const systemOneOp = {\n operationId: 'systemOne',\n method: 'POST',\n path: '/v1/systemone',\n request: { $ref: '#/schemas/SystemOneRequest' },\n response: { $ref: '#/schemas/SystemOneResponse' },\n environment: { local: true, cloud: false },\n transport: { mode: 'json', streaming: false },\n capabilities: {\n thinking: 'unsupported',\n tools: 'unsupported',\n vision: 'model-dependent',\n structuredOutput: 'unsupported',\n logprobs: 'unsupported',\n embeddings: 'unsupported',\n },\n constraints: {\n minOllamaVersion: '0.35.0',\n maxRequestBytes: 65536,\n maxRequestBytesWithImages: 33554432,\n },\n status: { documented: true, experimental: true },\n domain: 'native',\n notes: [\n 'Local-only; Ollama Cloud rejects /v1/systemone.',\n '64 KiB request limit without images, 32 MiB with images (includes JSON/base64 overhead).',\n 'No tools, no generation controls (temperature, top_p, etc.).',\n 'Vision is model-dependent: images are accepted by vision-weighted models (Clef/Clef Flash) but not by text-only models.',\n 'Experimental: behavioral surface may change between Ollama releases.',\n ],\n} as const satisfies OperationDefinition;\n\nexport const tagsOp = {\n operationId: 'tags',\n method: 'GET',\n path: '/api/tags',\n response: { $ref: '#/schemas/ListResponse' },\n environment: { local: true, cloud: true },\n transport: { mode: 'json', streaming: false },\n capabilities: {},\n status: { documented: true },\n domain: 'native',\n} as const satisfies OperationDefinition;\n\nexport const usageOp = {\n operationId: 'usage',\n method: 'GET',\n path: '/api/usage',\n response: { $ref: '#/schemas/UsageResponse' },\n environment: { local: false, cloud: true },\n host: 'https://ollama.com',\n transport: { mode: 'json', streaming: false },\n capabilities: {},\n status: { documented: true },\n domain: 'native',\n notes: [\n 'Cloud-only account endpoint — targets https://ollama.com, not the local Ollama server.',\n 'Requires an Ollama Cloud API key (set via OllamaClient credentials).',\n 'Query parameters (not modeled by the generated runtime): range = 24h | 7d | 30d (server default 7d), scope = self | team (server default self; team scope requires a team admin).',\n 'Rate limited to 10 requests/minute per user; 429 responses carry a Retry-After header.',\n 'Use OllamaClient.usage() — the generated NativeApi class does not expose this operation.',\n ],\n} as const satisfies OperationDefinition;\n\nexport const versionOp = {\n operationId: 'version',\n method: 'GET',\n path: '/api/version',\n response: { $ref: '#/schemas/VersionResponse' },\n environment: { local: true, cloud: true },\n transport: { mode: 'json', streaming: false },\n capabilities: {},\n status: { documented: true },\n domain: 'native',\n} as const satisfies OperationDefinition;\n\nexport const webFetchOp = {\n operationId: 'webFetch',\n method: 'POST',\n path: '/api/web_fetch',\n request: { $ref: '#/schemas/WebFetchRequest' },\n response: { $ref: '#/schemas/WebFetchResponse' },\n environment: { local: false, cloud: true },\n host: 'https://ollama.com',\n transport: { mode: 'json', streaming: false },\n capabilities: {},\n status: { documented: true },\n domain: 'native',\n notes: [\n 'Cloud-only capability endpoint — targets https://ollama.com, not the local Ollama server.',\n 'Requires an Ollama Cloud API key (set via OllamaClient credentials).',\n 'Use OllamaClient.webFetch() — the generated NativeApi class does not expose this operation.',\n ],\n} as const satisfies OperationDefinition;\n\nexport const webSearchOp = {\n operationId: 'webSearch',\n method: 'POST',\n path: '/api/web_search',\n request: { $ref: '#/schemas/WebSearchRequest' },\n response: { $ref: '#/schemas/WebSearchResponse' },\n environment: { local: false, cloud: true },\n host: 'https://ollama.com',\n transport: { mode: 'json', streaming: false },\n capabilities: {},\n status: { documented: true },\n domain: 'native',\n notes: [\n 'Cloud-only capability endpoint — targets https://ollama.com, not the local Ollama server.',\n 'Requires an Ollama Cloud API key (set via OllamaClient credentials).',\n 'Use OllamaClient.webSearch() — the generated NativeApi class does not expose this operation.',\n ],\n} as const satisfies OperationDefinition;\n\nexport const openaiChatCompletionsOp = {\n operationId: 'openaiChatCompletions',\n method: 'POST',\n path: '/v1/chat/completions',\n environment: { local: true, cloud: true },\n transport: { mode: 'sse', streaming: true, streamingDefault: false },\n capabilities: {\n thinking: 'model-dependent',\n tools: 'model-dependent',\n vision: 'model-dependent',\n structuredOutput: 'supported',\n logprobs: 'supported',\n },\n status: { documented: true },\n domain: 'openai',\n notes: [\n 'Ollama exposes a subset of the OpenAI Chat Completions request fields; see docs/upstream/ollama-openai-compatibility.mdx.',\n ],\n} as const satisfies OperationDefinition;\n\nexport const openaiCompletionsOp = {\n operationId: 'openaiCompletions',\n method: 'POST',\n path: '/v1/completions',\n environment: { local: true, cloud: true },\n transport: { mode: 'sse', streaming: true, streamingDefault: false },\n capabilities: { logprobs: 'supported' },\n status: { documented: true },\n domain: 'openai',\n} as const satisfies OperationDefinition;\n\nexport const openaiEmbeddingsOp = {\n operationId: 'openaiEmbeddings',\n method: 'POST',\n path: '/v1/embeddings',\n environment: { local: true, cloud: true },\n transport: { mode: 'json', streaming: false },\n capabilities: { embeddings: 'supported' },\n status: { documented: true },\n domain: 'openai',\n} as const satisfies OperationDefinition;\n\nexport const openaiModelsOp = {\n operationId: 'openaiModels',\n method: 'GET',\n path: '/v1/models',\n environment: { local: true, cloud: true },\n transport: { mode: 'json', streaming: false },\n capabilities: {},\n status: { documented: true },\n domain: 'openai',\n} as const satisfies OperationDefinition;\n\nexport const openaiModelsGetOneOp = {\n operationId: 'openaiModelsGetOne',\n method: 'GET',\n path: '/v1/models/{model}',\n environment: { local: true, cloud: true },\n parameters: [{ name: 'model', in: 'path', required: true, schema: { type: 'string' } }],\n transport: { mode: 'json', streaming: false },\n capabilities: {},\n status: { documented: true },\n domain: 'openai',\n notes: ['Returns metadata for a single OpenAI-compat model by id.'],\n} as const satisfies OperationDefinition;\n\nexport const openaiResponsesOp = {\n operationId: 'openaiResponses',\n method: 'POST',\n path: '/v1/responses',\n environment: { local: true, cloud: true },\n transport: { mode: 'sse', streaming: true, streamingDefault: false },\n capabilities: { thinking: 'model-dependent', tools: 'model-dependent' },\n status: { documented: true },\n domain: 'openai',\n notes: [\n 'Ollama implements a subset of the OpenAI Responses API; previous_response_id and conversation are explicitly unsupported.',\n ],\n} as const satisfies OperationDefinition;\n\nexport const anthropicMessagesOp = {\n operationId: 'anthropicMessages',\n method: 'POST',\n path: '/v1/messages',\n environment: { local: true, cloud: true },\n transport: { mode: 'sse', streaming: true, streamingDefault: false },\n capabilities: { thinking: 'model-dependent', tools: 'model-dependent' },\n status: { documented: true },\n domain: 'anthropic',\n notes: [\n \"tool_choice and metadata are explicitly unsupported by Ollama's Anthropic compat layer.\",\n 'Nested cache_control fields under messages[].content[].cache_control are unsupported.',\n ],\n} as const satisfies OperationDefinition;\n\nexport const allOperations = [\n balanceOp,\n blobsOp,\n chatOp,\n copyOp,\n createOp,\n createBlobOp,\n deleteOp,\n embedOp,\n generateOp,\n psOp,\n pullOp,\n pushOp,\n showOp,\n systemOneOp,\n tagsOp,\n usageOp,\n versionOp,\n webFetchOp,\n webSearchOp,\n openaiChatCompletionsOp,\n openaiCompletionsOp,\n openaiEmbeddingsOp,\n openaiModelsOp,\n openaiModelsGetOneOp,\n openaiResponsesOp,\n anthropicMessagesOp,\n] as const;\n","/**\n * AUTO-GENERATED by `npm run contract:generate`. DO NOT EDIT.\n * Source: contracts/ir/ollama.ir.json (canonical Ollama IR).\n * Each generated class delegates to OllamaRuntime — the runtime owns\n * transport, retry, streaming, telemetry, and error handling.\n */\n\nimport type { OllamaRuntime } from '../runtime/runtime.js';\nimport type {\n ChatRequest,\n ChatResponse,\n CopyRequest,\n CreateRequest,\n DeleteRequest,\n EmbedRequest,\n EmbedResponse,\n GenerateRequest,\n GenerateResponse,\n ListResponse,\n PsResponse,\n PullRequest,\n PushRequest,\n ShowRequest,\n ShowResponse,\n StatusResponse,\n SystemOneRequest,\n SystemOneResponse,\n VersionResponse,\n} from '../models/index.js';\nimport {\n blobsOp,\n chatOp,\n copyOp,\n createOp,\n deleteOp,\n embedOp,\n generateOp,\n psOp,\n pullOp,\n pushOp,\n showOp,\n systemOneOp,\n tagsOp,\n versionOp,\n} from './operations.js';\n\n/**\n * Generated API surface for Ollama's native domain.\n * Each method delegates to {@link OllamaRuntime.invoke}.\n */\nexport class NativeApi {\n constructor(private readonly runtime: OllamaRuntime) {}\n\n blobs(digest: string, options?: { signal?: AbortSignal }): Promise<unknown> {\n return this.runtime.invoke({\n operation: blobsOp,\n body: undefined,\n pathParams: { digest },\n ...(options?.signal !== undefined ? { signal: options.signal } : {}),\n });\n }\n\n chat(request: ChatRequest & { stream?: false }): Promise<ChatResponse>;\n chat(\n request: ChatRequest & { stream: true },\n ): Promise<AsyncGenerator<ChatResponse, void, undefined>>;\n chat(\n request: ChatRequest,\n ): Promise<ChatResponse | AsyncGenerator<ChatResponse, void, undefined>> {\n return this.runtime.invoke({\n operation: chatOp,\n body: request,\n streamingDefault: true,\n });\n }\n\n copy(request: CopyRequest): Promise<unknown> {\n return this.runtime.invoke({\n operation: copyOp,\n body: request,\n });\n }\n\n create(request: CreateRequest & { stream?: false }): Promise<StatusResponse>;\n create(\n request: CreateRequest & { stream: true },\n ): Promise<AsyncGenerator<StatusResponse, void, undefined>>;\n create(\n request: CreateRequest,\n ): Promise<StatusResponse | AsyncGenerator<StatusResponse, void, undefined>> {\n return this.runtime.invoke({\n operation: createOp,\n body: request,\n streamingDefault: true,\n });\n }\n\n delete(request: DeleteRequest): Promise<unknown> {\n return this.runtime.invoke({\n operation: deleteOp,\n body: request,\n });\n }\n\n embed(request: EmbedRequest): Promise<EmbedResponse> {\n return this.runtime.invoke({\n operation: embedOp,\n body: request,\n });\n }\n\n generate(request: GenerateRequest & { stream?: false }): Promise<GenerateResponse>;\n generate(\n request: GenerateRequest & { stream: true },\n ): Promise<AsyncGenerator<GenerateResponse, void, undefined>>;\n generate(\n request: GenerateRequest,\n ): Promise<GenerateResponse | AsyncGenerator<GenerateResponse, void, undefined>> {\n return this.runtime.invoke({\n operation: generateOp,\n body: request,\n streamingDefault: true,\n });\n }\n\n ps(options?: { signal?: AbortSignal }): Promise<PsResponse> {\n return this.runtime.invoke({\n operation: psOp,\n body: undefined,\n ...(options?.signal !== undefined ? { signal: options.signal } : {}),\n });\n }\n\n pull(request: PullRequest & { stream?: false }): Promise<StatusResponse>;\n pull(\n request: PullRequest & { stream: true },\n ): Promise<AsyncGenerator<StatusResponse, void, undefined>>;\n pull(\n request: PullRequest,\n ): Promise<StatusResponse | AsyncGenerator<StatusResponse, void, undefined>> {\n return this.runtime.invoke({\n operation: pullOp,\n body: request,\n streamingDefault: true,\n });\n }\n\n push(request: PushRequest & { stream?: false }): Promise<StatusResponse>;\n push(\n request: PushRequest & { stream: true },\n ): Promise<AsyncGenerator<StatusResponse, void, undefined>>;\n push(\n request: PushRequest,\n ): Promise<StatusResponse | AsyncGenerator<StatusResponse, void, undefined>> {\n return this.runtime.invoke({\n operation: pushOp,\n body: request,\n streamingDefault: true,\n });\n }\n\n show(request: ShowRequest): Promise<ShowResponse> {\n return this.runtime.invoke({\n operation: showOp,\n body: request,\n });\n }\n\n systemOne(request: SystemOneRequest): Promise<SystemOneResponse> {\n return this.runtime.invoke({\n operation: systemOneOp,\n body: request,\n });\n }\n\n tags(options?: { signal?: AbortSignal }): Promise<ListResponse> {\n return this.runtime.invoke({\n operation: tagsOp,\n body: undefined,\n ...(options?.signal !== undefined ? { signal: options.signal } : {}),\n });\n }\n\n version(options?: { signal?: AbortSignal }): Promise<VersionResponse> {\n return this.runtime.invoke({\n operation: versionOp,\n body: undefined,\n ...(options?.signal !== undefined ? { signal: options.signal } : {}),\n });\n }\n}\n","/**\n * Failover-aware HttpClient wrapper for OllamaRuntime.\n *\n * Wave 14: The generated OllamaRuntime takes a single HttpClient and uses\n * it for all requests. Previously, OllamaClient.runtime bound the runtime\n * to the registry's first candidate endpoint — meaning the generated API\n * surface (NativeApi, OpenAIApi, AnthropicApi) didn't participate in\n * multi-endpoint failover. If the first endpoint was down, the generated\n * API failed outright instead of failing over to the next candidate.\n *\n * This class wraps OllamaClient's failover machinery in an object that\n * implements the HttpClient surface OllamaRuntime needs. Each request()\n * call is routed through executeWithFailover, which picks the best\n * healthy endpoint, applies retry/backoff, and fails over on retryable\n * errors — exactly matching the behavior of the hand-written\n * OllamaClient methods (chat, generate, embed, etc.).\n *\n * The runtime's version-gating (enforceVersion: 'auto'/'strict') also\n * benefits: the cached server version is now probed against whichever\n * endpoint the first version-gated call lands on, and subsequent calls\n * reuse that cache. If the cached endpoint goes down, the next call\n * fails over to a healthy endpoint and the version cache is refreshed.\n */\nimport type { HttpRequestOptions } from './transport/http.js';\nimport type { OllamaClient } from './client.js';\n\n/**\n * Minimal HttpClient surface that OllamaRuntime consumes.\n *\n * OllamaRuntime only calls http.request() — it doesn't use\n * requestStream() or requestSseStream() (those are used directly by\n * the hand-written OllamaClient methods, not the generated runtime).\n * This interface captures just what the runtime needs, so the\n * FailoverHttpClient doesn't have to implement the full HttpClient.\n */\nexport interface RuntimeHttpClient {\n readonly baseUrl: string;\n request<T>(options: HttpRequestOptions): Promise<T>;\n}\n\n/**\n * A failover-aware HttpClient that routes each request through\n * OllamaClient.executeWithFailover.\n *\n * The `baseUrl` property reflects the first candidate endpoint's URL —\n * this is used by inferRuntimeMode() to determine local vs cloud mode.\n * The actual request routing picks the best healthy endpoint per call,\n * not necessarily the first one.\n */\nexport class FailoverHttpClient implements RuntimeHttpClient {\n /**\n * The first candidate endpoint's base URL. Used for inferRuntimeMode()\n * checks (local vs cloud). The actual request routing picks the best\n * healthy endpoint per call.\n */\n readonly baseUrl: string;\n\n constructor(\n private readonly client: OllamaClient,\n baseUrl: string,\n ) {\n this.baseUrl = baseUrl;\n }\n\n /**\n * Route a request through OllamaClient's failover machinery.\n *\n * Each call to request() goes through executeWithFailover, which:\n * - Picks the best healthy endpoint from the registry\n * - Applies retry/backoff within that endpoint\n * - Fails over to the next candidate on retryable errors\n * - Reports success/failure to the endpoint health tracker\n *\n * Wave 15 (P1): the model is extracted from the request body by the\n * runtime and passed via the `model` field on the options. This lets\n * the failover layer filter endpoints by `OllamaEndpoint.models`\n * (credential-scoped routing). If no model is provided, all endpoints\n * are considered.\n *\n * The `raw` option (for streaming responses) is passed through\n * unchanged — executeWithFailover returns whatever the operation\n * callback returns, including raw Response objects.\n */\n async request<T>(options: HttpRequestOptions & { model?: string }): Promise<T> {\n const { model, ...httpOptions } = options;\n return this.client.executeWithFailover(\n async (http, signal) => {\n const mergedOptions: HttpRequestOptions = {\n ...httpOptions,\n ...(httpOptions.signal !== undefined ? { signal } : { signal }),\n };\n return http.request<T>(mergedOptions);\n },\n {\n singleEndpoint: false,\n ...(model !== undefined ? { model } : {}),\n },\n );\n }\n}\n","/**\n * Higher-level System One decision helpers.\n *\n * Wave 14B: These helpers wrap the low-level `OllamaClient.systemOne()`\n * with ergonomic APIs for the six most common decision patterns. Each\n * helper constructs a single-question request, sends it, and extracts\n * the typed answer — so callers don't have to deal with the question\n * map / answer map indirection for single-decision calls.\n *\n * The helpers return typed results (not generic SystemOneAnswer) so\n * callers can branch on the discriminated union without manual\n * type narrowing.\n *\n * For multi-question calls (e.g. routing + urgency + difficulty in\n * one request), use `OllamaClient.systemOne()` directly with the\n * generic key-safe wrapper.\n */\n\nimport type { OllamaClient } from './client.js';\nimport type {\n SystemOneChoiceAnswer,\n SystemOneNoulAnswer,\n SystemOneScoreAnswer,\n SystemOneContent,\n} from './system-one.js';\n\n/**\n * Result of a choice decision: the selected option key + probability\n * distribution + confidence.\n */\nexport interface ChoiceDecision {\n /** The selected option key (highest probability). */\n readonly choice: string;\n /** Probability distribution over all options. */\n readonly probabilities: Record<string, number>;\n /** Distribution concentration (0–1). NOT a guarantee of correctness. */\n readonly confidence: number;\n /** Token usage for the call. */\n readonly usage: { readonly input_tokens: number; readonly output_tokens: number };\n}\n\n/**\n * Result of a noul (yes/no) decision: the probability of true + a\n * boolean derived from it (>= 0.5 → true).\n */\nexport interface NoulDecision {\n /** Probability of true (0–1). */\n readonly noul: number;\n /** Boolean decision: true if noul >= 0.5, false otherwise. */\n readonly bool: boolean;\n /** Token usage for the call. */\n readonly usage: { readonly input_tokens: number; readonly output_tokens: number };\n}\n\n/**\n * Result of a score decision: the probability-weighted average score,\n * the legend (index → description), the probability distribution, and\n * confidence.\n */\nexport interface ScoreDecision {\n /** Probability-weighted average of zero-based criterion indices (0 to N-1). */\n readonly score: number;\n /** Zero-based indices as string keys → criterion descriptions. */\n readonly legend: Record<string, string>;\n /** Probabilities keyed by zero-based criterion indices as strings. */\n readonly probabilities: Record<string, number>;\n /** Distribution concentration (0–1). NOT a guarantee of correctness. */\n readonly confidence: number;\n /** Token usage for the call. */\n readonly usage: { readonly input_tokens: number; readonly output_tokens: number };\n}\n\n/**\n * Result of a ranking call: candidates sorted by score (highest first),\n * each with its score and probability distribution.\n */\nexport interface RankResult<T extends string> {\n readonly candidate: T;\n readonly score: number;\n readonly confidence: number;\n}\n\n/**\n * Higher-level System One decision helpers.\n *\n * Create via `createDecision(client)` or access via `client.decision`\n * (if the accessor is wired). Each helper constructs a single-question\n * System One request and extracts the typed answer.\n *\n * Example:\n * ```ts\n * const decision = createDecision(client);\n * const result = await decision.choice({\n * model: 'tev1:4b',\n * state: 'Customer was charged twice',\n * instructions: 'What is the primary intent?',\n * criteria: {\n * refund: 'Customer wants a refund',\n * duplicate_charge: 'Customer reports multiple charges',\n * cancellation: 'Customer wants to cancel',\n * },\n * });\n * console.log(result.choice); // 'duplicate_charge'\n * console.log(result.confidence); // 0.89\n * ```\n */\nexport interface Decision {\n /**\n * Ask a single choice question. Returns the selected option + full\n * probability distribution + confidence.\n *\n * Use for: routing, classification, model selection, tool selection,\n * category assignment — any \"which one?\" decision with bounded options.\n */\n choice(params: {\n model: string;\n state: SystemOneContent;\n instructions: SystemOneContent;\n criteria: Record<string, string | null>;\n images?: string[];\n keepAlive?: string | number;\n }): Promise<ChoiceDecision>;\n\n /**\n * Ask a single yes/no (noul) question. Returns the probability of\n * true (0–1) + a boolean derived from it (>= 0.5 → true).\n *\n * Use for: gating, verification, safety checks, eligibility, prompt-\n * injection detection — any \"is this true?\" decision.\n */\n noul(params: {\n model: string;\n state: SystemOneContent;\n instructions: SystemOneContent;\n images?: string[];\n keepAlive?: string | number;\n }): Promise<NoulDecision>;\n\n /**\n * Ask a single score question. Returns the probability-weighted\n * average score + legend + probability distribution + confidence.\n *\n * Use for: severity, priority, difficulty, relevance, quality — any\n * \"how strongly does this fit this ordered rubric?\" decision.\n */\n score(params: {\n model: string;\n state: SystemOneContent;\n instructions: SystemOneContent;\n /** Ordered criteria from lowest (index 0) to highest. 2–26 items. */\n criteria: string[];\n images?: string[];\n keepAlive?: string | number;\n }): Promise<ScoreDecision>;\n\n /**\n * Route a request to one of N named options. Convenience wrapper\n * around `choice()` that returns just the selected route name.\n *\n * Use for: workflow routing, model routing, agent dispatch, tool\n * selection — any \"which handler?\" decision.\n */\n route<T extends string>(params: {\n model: string;\n state: SystemOneContent;\n instructions: SystemOneContent;\n criteria: Record<T, string | null>;\n images?: string[];\n keepAlive?: string | number;\n }): Promise<{ readonly route: T; readonly confidence: number }>;\n\n /**\n * Verify whether a claim is supported by evidence. Convenience\n * wrapper around `noul()` that returns a boolean + the probability\n * of true (not System One's confidence score — noul answers don't\n * carry a separate confidence field).\n *\n * Use for: evidence verification, safety gates, prompt-injection\n * detection, compliance checks — any \"is this claim true given\n * this evidence?\" decision.\n */\n verify(params: {\n model: string;\n claim: SystemOneContent;\n evidence: SystemOneContent;\n instructions?: SystemOneContent;\n images?: string[];\n keepAlive?: string | number;\n }): Promise<{ readonly verified: boolean; readonly probability: number }>;\n\n /**\n * Rank candidates by score. Sends one System One call per candidate\n * (parallelized), then sorts by score descending.\n *\n * Use for: semantic reranking, candidate ranking, priority scoring,\n * relevance scoring — any \"which of these is best?\" decision where\n * each candidate is scored independently against the same rubric.\n *\n * Note: this makes N parallel requests (one per candidate). For\n * large candidate sets, consider batching or using a single choice\n * question with all candidates as options instead.\n */\n rank<T extends string>(params: {\n model: string;\n instructions: SystemOneContent;\n /** Ordered criteria from lowest (index 0) to highest. 2–26 items. */\n criteria: string[];\n candidates: ReadonlyArray<{ readonly id: T; readonly state: SystemOneContent }>;\n images?: string[];\n keepAlive?: string | number;\n }): Promise<ReadonlyArray<RankResult<T>>>;\n}\n\n/** Create a Decision helper bound to an OllamaClient. */\nexport function createDecision(client: OllamaClient): Decision {\n return {\n async choice(params) {\n const response = await client.systemOne({\n model: params.model,\n state: params.state,\n ...(params.images ? { images: params.images } : {}),\n questions: {\n decision: {\n type: 'choice',\n instructions: params.instructions,\n criteria: params.criteria,\n },\n },\n ...(params.keepAlive !== undefined ? { keep_alive: params.keepAlive } : {}),\n });\n const answer = response.answers.decision as SystemOneChoiceAnswer;\n return {\n choice: answer.choice,\n probabilities: answer.probabilities,\n confidence: answer.confidence,\n usage: response.usage,\n };\n },\n\n async noul(params) {\n const response = await client.systemOne({\n model: params.model,\n state: params.state,\n ...(params.images ? { images: params.images } : {}),\n questions: {\n decision: {\n type: 'noul',\n instructions: params.instructions,\n },\n },\n ...(params.keepAlive !== undefined ? { keep_alive: params.keepAlive } : {}),\n });\n const answer = response.answers.decision as SystemOneNoulAnswer;\n return {\n noul: answer.noul,\n bool: answer.noul >= 0.5,\n usage: response.usage,\n };\n },\n\n async score(params) {\n const response = await client.systemOne({\n model: params.model,\n state: params.state,\n ...(params.images ? { images: params.images } : {}),\n questions: {\n decision: {\n type: 'score',\n instructions: params.instructions,\n criteria: params.criteria,\n },\n },\n ...(params.keepAlive !== undefined ? { keep_alive: params.keepAlive } : {}),\n });\n const answer = response.answers.decision as SystemOneScoreAnswer;\n return {\n score: answer.score,\n legend: answer.legend,\n probabilities: answer.probabilities,\n confidence: answer.confidence,\n usage: response.usage,\n };\n },\n\n async route(params) {\n const response = await client.systemOne({\n model: params.model,\n state: params.state,\n ...(params.images ? { images: params.images } : {}),\n questions: {\n decision: {\n type: 'choice',\n instructions: params.instructions,\n criteria: params.criteria,\n },\n },\n ...(params.keepAlive !== undefined ? { keep_alive: params.keepAlive } : {}),\n });\n const answer = response.answers.decision as SystemOneChoiceAnswer;\n // `answer.choice` is one of the criteria keys (T extends string).\n // TypeScript can't prove this relationship because createDecision()\n // is not generic — the generic <T> lives on the Decision interface's\n // route() method, not on the factory. The cast is safe because the\n // caller's criteria keys define T, and the server's response choice\n // is guaranteed by the contract to be one of those keys.\n return {\n route: answer.choice as never,\n confidence: answer.confidence,\n };\n },\n\n async verify(params) {\n const state: SystemOneContent = {\n claim: params.claim,\n evidence: params.evidence,\n };\n const response = await client.systemOne({\n model: params.model,\n state,\n ...(params.images ? { images: params.images } : {}),\n questions: {\n decision: {\n type: 'noul',\n instructions: params.instructions ?? 'Is the claim supported by the evidence?',\n },\n },\n ...(params.keepAlive !== undefined ? { keep_alive: params.keepAlive } : {}),\n });\n const answer = response.answers.decision as SystemOneNoulAnswer;\n return {\n verified: answer.noul >= 0.5,\n probability: answer.noul,\n };\n },\n\n async rank(params) {\n const promises = params.candidates.map(async (candidate) => {\n const response = await client.systemOne({\n model: params.model,\n state: candidate.state,\n ...(params.images ? { images: params.images } : {}),\n questions: {\n decision: {\n type: 'score',\n instructions: params.instructions,\n criteria: params.criteria,\n },\n },\n ...(params.keepAlive !== undefined ? { keep_alive: params.keepAlive } : {}),\n });\n const answer = response.answers.decision as SystemOneScoreAnswer;\n return {\n candidate: candidate.id,\n score: answer.score,\n confidence: answer.confidence,\n };\n });\n const results = await Promise.all(promises);\n // Sort by score descending (highest first). Cast through unknown to\n // RankResult<T>[] — same pattern as route(): the generic <T> lives\n // on the Decision interface, not on the factory. The candidate IDs\n // come from the caller's typed array, so the runtime shape is\n // RankResult<T>[], but TypeScript can't prove it through the\n // non-generic createDecision factory.\n return results.sort((a, b) => b.score - a.score) as unknown as ReadonlyArray<RankResult<never>>;\n },\n };\n}\n","/**\n * Main OllamaClient class with failover, streaming, structured outputs, and ecosystem integrations.\n */\n\nimport { z } from 'zod';\nimport {\n DEFAULT_BASE_URL,\n DEFAULT_FAILOVER_CODES,\n DEFAULT_TIMEOUT_MS,\n OLLAMA_CLOUD_BASE_URL,\n resolveApiKey,\n resolveEndpointApiKey,\n resolveBaseUrl,\n resolveCredentialEndpoints,\n type OllamaClientConfig,\n} from './config.js';\nimport {\n OllamaClientError,\n OllamaModelRoutingError,\n OllamaUnsupportedCapabilityError,\n} from './errors.js';\nimport { createConsoleLogger, NOOP_LOGGER, type Logger } from './logger.js';\nimport { EndpointRegistry, type EndpointHealth } from './providers/endpoint-registry.js';\nimport { checkEndpointHealth, type EndpointHealthCheckResult } from './providers/health-check.js';\nimport {\n detectModelCapabilities,\n inferRuntimeMode,\n type ModelCapabilities,\n type RuntimeMode,\n} from './capabilities/capabilities.js';\nimport { parseStructuredOutput, zodToJsonSchema } from './schema/zod.js';\nimport { normalizeChatStream, normalizeGenerateStream } from './streaming/normalize.js';\nimport { OllamaStream } from './streaming/stream.js';\nimport type { ChatStreamResult, GenerateStreamResult } from './streaming/types.js';\nimport { HttpClient, type BinaryBody, type FetchLike } from './transport/http.js';\nimport { DEFAULT_RETRY_CONFIG, withRetry, type RetryConfig } from './transport/retry.js';\nimport { createTimeoutSignal } from './transport/timeout.js';\nimport { ModelsClient } from './models-client.js';\nimport { OpenAICompatClient } from './integrations/openai.js';\nimport { AnthropicCompatClient } from './integrations/anthropic.js';\nimport { OllamaRuntime } from './generated/runtime/runtime.js';\nimport { ResponsesModule } from './responses.js';\nimport { ConversationSession, type ConversationSessionOptions } from './conversation.js';\nimport {\n checkChatContext,\n checkGenerateContext,\n contextWarningMessage,\n type ContextCheck,\n} from './context-safety.js';\nimport type { ModelOptions } from './types.js';\nimport { NativeApi } from './generated/api/native-api.js';\nimport { FailoverHttpClient } from './failover-http-client.js';\nimport { createDecision, type Decision } from './decision.js';\nimport type {\n SystemOneRequest as SystemOneRequestBase,\n SystemOneResponse as SystemOneResponseBase,\n} from './generated/models/index.js';\nimport type { SystemOneQuestions, SystemOneRequest, SystemOneResponse } from './system-one.js';\nimport { ensureToolCallIds } from './tools/tool-call-id.js';\nimport { withEncodedImages, withEncodedMessageImages } from './utils.js';\nimport {\n withSpan,\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_GEN_AI_RESPONSE_MODEL,\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n ATTR_OLLAMA_ENDPOINT_NAME,\n ATTR_OLLAMA_ENDPOINT_ATTEMPT,\n GEN_AI_SYSTEM_OLLAMA,\n} from './telemetry/index.js';\nimport type {\n ChatRequestOptions,\n ChatResponse,\n CopyRequestOptions,\n CreateRequestOptions,\n DeleteRequestOptions,\n EmbedRequestOptions,\n EmbedResponse,\n EmbeddingsRequestOptions,\n EmbeddingsResponse,\n GenerateRequestOptions,\n GenerateResponse,\n PullRequestOptions,\n PushRequestOptions,\n RequestCancellationOptions,\n ShowRequestOptions,\n UsageRequestOptions,\n WebFetchRequestOptions,\n WebFetchResponse,\n WebSearchRequestOptions,\n WebSearchResponse,\n BalanceRequestOptions,\n} from './types.js';\nimport type { BalanceResponse, UsageResponse } from './generated/models/index.js';\n\nlet logicalRequestSequence = 0;\n\nfunction createLogicalRequestId(): string {\n logicalRequestSequence += 1;\n return `ollama-request-${logicalRequestSequence}`;\n}\n\n/**\n * High-level Ollama client — the original, hand-written API surface.\n *\n * **Wave 8 (ADR 0018) deprecation notice:**\n *\n * For new code, prefer the generated `NativeApi` from\n * {@link ./generated/runtime/runtime.js} + {@link ./generated/api/native-api.js}\n * instead. The generated surface:\n *\n * - Inherits every contract-layer guarantee (environment guards, version\n * guards, streaming defaults) automatically from the canonical IR.\n * - Stays in sync with the OpenAPI spec by construction — no hand-written\n * surface to drift.\n * - Uses the same `HttpClient` (and therefore the same middleware,\n * retry, telemetry, and streaming pipeline) as this client.\n *\n * The migration path is non-breaking:\n *\n * ```ts\n * // Before (still works, no breaking changes):\n * const client = new OllamaClient({ baseUrl: 'http://localhost:11434' });\n * const res = await client.chat({ model, messages });\n *\n * // After (recommended for new code):\n * const http = new HttpClient({ baseUrl: 'http://localhost:11434' });\n * const runtime = new OllamaRuntime({ http });\n * const api = new NativeApi(runtime);\n * const res = await api.chat({ model, messages, stream: false });\n * ```\n *\n * `OllamaClient` is preserved verbatim — existing callers do not need to\n * change anything. New methods and operations will land on the generated\n * surface first; `OllamaClient` will receive them only as a follow-up.\n */\nexport class OllamaClient {\n readonly registry: EndpointRegistry;\n readonly models: ModelsClient;\n private readonly retryConfig: RetryConfig;\n private readonly timeoutMs: number;\n private readonly failoverCodes: Set<string>;\n private readonly fetchImpl: FetchLike;\n private readonly logger: Logger;\n private readonly middleware: OllamaClientConfig['middleware'];\n private readonly onLifecycleEvent: OllamaClientConfig['onLifecycleEvent'];\n /**\n * API key for Ollama's hosted web tools (`webSearch`/`webFetch`), which always target\n * `OLLAMA_CLOUD_BASE_URL` regardless of `config.endpoints` — an Ollama account API key\n * is inherently a single global credential, not tied to any one inference endpoint.\n * Resolved the same way as a single-endpoint `apiKey` (`config.apiKey` falling back to\n * `OLLAMA_API_KEY`), independent of whether `config.endpoints` was used instead.\n */\n private readonly cloudApiKey: string | undefined;\n /** Configured `defaultContextLength` — injected as `num_ctx` when a request omits it. */\n private readonly defaultContextLength: number | undefined;\n /** Configured `contextWarningThreshold` (default 0.9). */\n private readonly contextWarningThreshold: number | undefined;\n /** Configured overflow policy — `'warn'` (default) or `'throw'`. */\n private readonly onContextOverflow: 'warn' | 'throw';\n\n constructor(config: OllamaClientConfig = {}) {\n this.cloudApiKey = resolveApiKey(config.apiKey);\n const defaultBaseUrl = resolveBaseUrl(config.baseUrl);\n const resolvedApiKey = resolveEndpointApiKey(config.apiKey, defaultBaseUrl);\n const credentialEndpoints = resolveCredentialEndpoints(config);\n const endpoints =\n config.endpoints ??\n (credentialEndpoints.length > 0\n ? []\n : [\n {\n name: 'default',\n baseUrl: defaultBaseUrl,\n ...(resolvedApiKey !== undefined ? { apiKey: resolvedApiKey } : {}),\n ...(config.headers !== undefined ? { headers: config.headers } : {}),\n },\n ]);\n this.registry = new EndpointRegistry(\n [...endpoints, ...credentialEndpoints],\n config.endpointHealth,\n );\n this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.failoverCodes = new Set(config.failoverOn ?? DEFAULT_FAILOVER_CODES);\n this.fetchImpl = config.fetch ?? globalThis.fetch;\n this.logger = config.logger ?? (config.debug ? createConsoleLogger() : NOOP_LOGGER);\n this.middleware = config.middleware;\n this.onLifecycleEvent = config.onLifecycleEvent;\n this.retryConfig =\n typeof config.retries === 'number'\n ? { ...DEFAULT_RETRY_CONFIG, maxRetries: config.retries }\n : { ...DEFAULT_RETRY_CONFIG, ...config.retries };\n this.defaultContextLength = config.defaultContextLength;\n this.contextWarningThreshold = config.contextWarningThreshold;\n this.onContextOverflow = config.onContextOverflow ?? 'warn';\n this.models = new ModelsClient((op, opts) => this.executeWithFailover(op, opts));\n }\n\n get modelsClient(): ModelsClient {\n return this.models;\n }\n\n /**\n * Return a generated {@link OllamaRuntime} that shares this client's\n * transport (HttpClient + middleware + retry + telemetry).\n *\n * Wave 8 (ADR 0018) bridge: lets callers mix the existing `OllamaClient`\n * API with the generated `NativeApi` / `OpenAIApi` / `AnthropicApi`\n * surface without configuring two separate HttpClient instances.\n *\n * Wave 14: the runtime now participates in multi-endpoint failover.\n * Each request is routed through this client's `executeWithFailover`\n * machinery via a {@link FailoverHttpClient} wrapper. If the first\n * candidate endpoint is down, requests automatically fail over to\n * the next healthy candidate — matching the behavior of the\n * hand-written OllamaClient methods (chat, generate, etc.).\n *\n * The runtime is cached on first call — subsequent calls return the\n * same instance. The `FailoverHttpClient` holds a reference to this\n * client, so it always sees the current endpoint registry state.\n */\n get runtime(): OllamaRuntime {\n if (this._runtime === undefined) {\n // Use the first candidate's baseUrl for inferRuntimeMode() — the\n // actual request routing picks the best healthy endpoint per call\n // via executeWithFailover.\n const candidates = this.registry.candidates();\n const endpoint = candidates[0];\n const baseUrl = endpoint?.baseUrl ?? 'http://localhost:11434';\n const http = new FailoverHttpClient(this, baseUrl);\n // Wave 15 (P0): provide a cloud HTTP backend for operations that\n // declare a non-default host (web search, web fetch). This lets\n // the generated runtime route host-bearing operations to\n // https://ollama.com with the configured API key, rather than\n // silently sending them to the local Ollama server.\n const cloudHttp = new HttpClient({\n baseUrl: OLLAMA_CLOUD_BASE_URL,\n ...(this.cloudApiKey !== undefined ? { apiKey: this.cloudApiKey } : {}),\n fetch: this.fetchImpl,\n ...(this.middleware !== undefined ? { middleware: this.middleware } : {}),\n ...(this.onLifecycleEvent !== undefined ? { onLifecycleEvent: this.onLifecycleEvent } : {}),\n });\n this._runtime = new OllamaRuntime({\n http,\n cloudHttp,\n localMode: inferRuntimeMode(baseUrl) === 'local',\n });\n }\n return this._runtime;\n }\n private _runtime: OllamaRuntime | undefined;\n\n /**\n * Lazily-constructed `NativeApi` bound to this client's runtime. Exposes\n * the full generated native API surface (chat, generate, embed, systemOne,\n * etc.) with contract-driven types and runtime enforcement.\n *\n * Wave 13: `systemOne()` delegates to this accessor.\n */\n get native(): NativeApi {\n if (this._nativeApi === undefined) {\n this._nativeApi = new NativeApi(this.runtime);\n }\n return this._nativeApi;\n }\n private _nativeApi: NativeApi | undefined;\n\n /**\n * Higher-level System One decision helpers (Wave 14B).\n *\n * Ergonomic wrappers around `systemOne()` for the six most common\n * decision patterns: `choice()`, `noul()`, `score()`, `route()`,\n * `verify()`, `rank()`. Each constructs a single-question request\n * and extracts the typed answer.\n *\n * ```ts\n * const result = await client.decision.choice({\n * model: 'tev1:4b',\n * state: 'Customer was charged twice',\n * instructions: 'What is the primary intent?',\n * criteria: {\n * refund: 'Customer wants a refund',\n * duplicate_charge: 'Customer reports multiple charges',\n * },\n * });\n * console.log(result.choice); // 'duplicate_charge'\n * console.log(result.confidence); // 0.89\n * ```\n */\n get decision(): Decision {\n if (this._decision === undefined) {\n this._decision = createDecision(this);\n }\n return this._decision;\n }\n private _decision: Decision | undefined;\n\n /**\n * Ergonomic OpenAI Responses API bridge (`client.responses.create()` /\n * `.stream()`). Dual-mode transport: prefers the native `POST\n * /v1/responses` endpoint (Ollama ≥ v0.13.3) and transparently re-issues via\n * `/api/chat` when the server answers 404, so migrating OpenAI code works\n * unchanged against older servers. See `src/responses.ts`.\n */\n get responses(): ResponsesModule {\n if (this._responses === undefined) {\n this._responses = new ResponsesModule((op, opts) => this.executeWithFailover(op, opts));\n }\n return this._responses;\n }\n private _responses: ResponsesModule | undefined;\n\n /**\n * Starts a KV-prefix-preserving multi-turn conversation session.\n *\n * ```ts\n * const session = client.session('llama3.1', 'You are a concise assistant.');\n * const reply = await session.send('Hi!');\n * const detail = await session.sendTurn('Why is the sky blue?');\n * detail.cache.hitRate; // per-turn KV-cache hit rate\n * session.cacheStats; // cumulative stats across turns\n * ```\n *\n * Accepts either `(model, systemPrompt?)` or a full options object\n * (`{ model, systemPrompt, options, think, keep_alive, tools }`). See\n * `src/conversation.ts` for why the system prompt is pinned for the\n * session's lifetime.\n */\n session(model: string, systemPrompt?: string): ConversationSession;\n session(options: ConversationSessionOptions): ConversationSession;\n session(\n modelOrOptions: string | ConversationSessionOptions,\n systemPrompt?: string,\n ): ConversationSession {\n const options: ConversationSessionOptions =\n typeof modelOrOptions === 'string'\n ? {\n model: modelOrOptions,\n ...(systemPrompt !== undefined ? { systemPrompt } : {}),\n }\n : modelOrOptions;\n return new ConversationSession(this, options);\n }\n\n /**\n * Context-window pre-flight enforcement — see `src/context-safety.ts` and\n * the `defaultContextLength` / `onContextOverflow` config docs. Logs a\n * warning (default) or throws client-side when the estimated prompt size\n * is close to / beyond the effective context window.\n */\n private enforceContextSafety(kind: 'chat' | 'generate', check: ContextCheck): void {\n if (!check.exceedsThreshold) return;\n const message = contextWarningMessage(check, kind);\n if (this.onContextOverflow === 'throw') {\n throw new OllamaClientError(message, { code: 'context_overflow' });\n }\n this.logger.warn(message);\n }\n\n /**\n * Returns `options` with `num_ctx` injected from the client's\n * `defaultContextLength` when the request didn't set one — making the\n * effective context window explicit on the wire instead of relying on\n * Ollama's silently-truncating server default. Returns the original\n * reference when there's nothing to inject (the common case).\n */\n private injectDefaultContextLength(options: ModelOptions | undefined): ModelOptions | undefined {\n if (options?.num_ctx !== undefined || this.defaultContextLength === undefined) {\n return options;\n }\n return { ...options, num_ctx: this.defaultContextLength };\n }\n\n /**\n * Fail-fast guard for `format` (structured output) requests: throws before any network\n * call if the candidate endpoint is inferred as Ollama Cloud, which does not currently\n * support structured outputs (see `ModelCapabilities.supportsStructuredOutputRequest`).\n * `unsupported_capability` is in `DEFAULT_FAILOVER_CODES`, so in a multi-endpoint setup\n * this causes failover to the next candidate rather than failing the whole request.\n */\n private assertStructuredOutputSupported(baseUrl: string, model: string): void {\n if (inferRuntimeMode(baseUrl) === 'cloud') {\n throw new OllamaUnsupportedCapabilityError(\n `Structured output (\"format\") requests are not supported against Ollama Cloud ` +\n `endpoints (model \"${model}\" via ${baseUrl}). This is a known Ollama Cloud ` +\n `limitation, not a bug in this SDK.`,\n { capability: 'structuredOutputRequest' },\n );\n }\n }\n\n async executeWithFailover<T>(\n operation: (http: HttpClient, signal: AbortSignal) => Promise<T>,\n options?: {\n signal?: AbortSignal | undefined;\n timeoutMs?: number | undefined;\n /**\n * Disables cross-endpoint failover: only the single best candidate endpoint is\n * tried (same-endpoint retry via `withRetry` still applies). For operations whose\n * target IS the endpoint — model catalog/blob management — a different endpoint\n * isn't an interchangeable substitute, so failing over to one would silently\n * operate on the wrong server's state rather than retrying \"the same\" request. See\n * ADR 0008. Defaults to `false`, preserving normal failover for inference calls.\n */\n singleEndpoint?: boolean | undefined;\n /**\n * The model this request targets, used to filter candidates by\n * `OllamaEndpoint.models` (credential-scoped routing — see that field's docs).\n * Requests without a `model` (e.g. `listModels`) consider every configured\n * endpoint, same as before this option existed.\n */\n model?: string | undefined;\n /**\n * For an operation whose real completion outlasts its own returned promise — a\n * streaming response, specifically — defers releasing the endpoint's concurrency\n * slot (see `EndpointRegistryOptions.maxConcurrentPerEndpoint`/`'least-connections'`)\n * until the promise this returns settles, instead of releasing as soon as\n * `operation` resolves. Pass `(stream) => stream.finalResult` for `chatStream`/\n * `generateStream` so the slot stays held for as long as the underlying HTTP\n * connection realistically does — until the stream is fully consumed, errors, or is\n * aborted. Omit for anything whose returned promise already represents the whole\n * request/response (the default, and correct for every non-streaming call).\n */\n holdUntil?: ((result: T) => Promise<unknown>) | undefined;\n },\n ): Promise<T> {\n const timeout = createTimeoutSignal(options?.timeoutMs ?? this.timeoutMs, options?.signal);\n const requestId = createLogicalRequestId();\n let deferTimeoutCancel = false;\n try {\n let lastError: Error | undefined;\n\n for (;;) {\n const allCandidates = this.registry.candidates(options?.model);\n if (\n allCandidates.length === 0 &&\n options?.model !== undefined &&\n this.registry.hasModelScopedEndpoints()\n ) {\n const configured = this.registry\n .list()\n .flatMap((ep) => ep.models ?? [])\n .filter((m, i, arr) => arr.indexOf(m) === i);\n throw new OllamaModelRoutingError(\n `No configured endpoint is authorized for model \"${options.model}\". ` +\n (configured.length > 0\n ? `Endpoints are scoped to: ${configured.join(', ')}.`\n : 'No endpoint declares a `models` allow-list that includes it.') +\n ' Add or widen an `OllamaEndpoint.models` entry to route this model.',\n { model: options.model, availableModels: configured },\n );\n }\n const candidates = options?.singleEndpoint ? allCandidates.slice(0, 1) : allCandidates;\n\n const runnable = this.registry.filterWithCapacity(candidates);\n if (runnable.length === 0 && candidates.length > 0) {\n await this.registry.waitForCapacity(\n candidates.map((c) => c.name),\n timeout.signal,\n );\n continue;\n }\n\n for (const [attemptIndex, endpoint] of runnable.entries()) {\n this.logger.debug(`Executing on endpoint \"${endpoint.name}\" (${endpoint.baseUrl})`);\n const http = new HttpClient({\n baseUrl: endpoint.baseUrl,\n ...(endpoint.apiKey !== undefined ? { apiKey: endpoint.apiKey } : {}),\n ...(endpoint.headers !== undefined ? { headers: endpoint.headers } : {}),\n fetch: this.fetchImpl,\n middleware: this.middleware,\n onLifecycleEvent: this.onLifecycleEvent,\n requestId,\n });\n\n // Acquired synchronously, right after this endpoint was chosen from\n // `candidates()`/`filterWithCapacity()` with no `await` in between — see\n // `EndpointRegistryOptions.strategy`'s `'least-connections'` doc for why that\n // ordering is what makes it race-free.\n this.registry.acquire(endpoint.name);\n let holdPromise: Promise<unknown> | undefined;\n try {\n const result = await withSpan(\n 'ollama.endpoint.attempt',\n {\n [ATTR_OLLAMA_ENDPOINT_NAME]: endpoint.name,\n [ATTR_OLLAMA_ENDPOINT_ATTEMPT]: attemptIndex,\n },\n () =>\n withRetry(\n () => operation(http, timeout.signal),\n {\n ...this.retryConfig,\n onRetry: (error, attempt, delayMs) => {\n this.retryConfig.onRetry?.(error, attempt, delayMs);\n this.onLifecycleEvent?.({\n type: 'retry',\n requestId,\n attempt: attempt + 1,\n error,\n delayMs,\n timestamp: Date.now(),\n });\n },\n },\n timeout.signal,\n ),\n );\n this.registry.reportSuccess(endpoint.name);\n if (options?.holdUntil) {\n holdPromise = options.holdUntil(result);\n deferTimeoutCancel = true;\n }\n return result;\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n lastError = error;\n this.registry.reportFailure(endpoint.name);\n this.logger.warn(`Failed on \"${endpoint.name}\": ${error.message}`);\n if (!(error instanceof OllamaClientError && this.failoverCodes.has(error.code)))\n throw error;\n } finally {\n if (holdPromise) {\n void holdPromise\n .catch(() => undefined)\n .finally(() => {\n timeout.cancel();\n this.registry.release(endpoint.name);\n });\n } else {\n this.registry.release(endpoint.name);\n }\n }\n }\n throw lastError ?? new Error('No healthy Ollama endpoints available');\n }\n } finally {\n if (!deferTimeoutCancel) timeout.cancel();\n }\n }\n\n // --- Chat ---\n chat(\n req: ChatRequestOptions & { stream: true },\n ): Promise<OllamaStream<ChatResponse, ChatStreamResult>>;\n chat(req: ChatRequestOptions & { stream?: false | undefined }): Promise<ChatResponse>;\n chat(\n req: ChatRequestOptions,\n ): Promise<ChatResponse | OllamaStream<ChatResponse, ChatStreamResult>>;\n async chat(\n req: ChatRequestOptions,\n ): Promise<ChatResponse | OllamaStream<ChatResponse, ChatStreamResult>> {\n const encodedMessages = await withEncodedMessageImages(req.messages, req.signal);\n const messages = encodedMessages.map((message) => {\n if (message.role === 'tool' && message.tool_call_id !== undefined) {\n const { tool_call_id: _toolCallId, ...nativeMessage } = message;\n return nativeMessage;\n }\n return message;\n });\n // Context-window pre-flight: warn (or throw) before sending when the\n // estimated prompt is close to / beyond the effective window, and make\n // the window explicit by injecting `defaultContextLength` as `num_ctx`.\n this.enforceContextSafety(\n 'chat',\n checkChatContext(req, {\n defaultContextLength: this.defaultContextLength,\n threshold: this.contextWarningThreshold,\n }),\n );\n const options = this.injectDefaultContextLength(req.options);\n if (req.stream) {\n return this.executeWithFailover(\n async (http, signal) => {\n if (req.format !== undefined)\n this.assertStructuredOutputSupported(http.baseUrl, req.model);\n const stream = await http.requestStream<ChatResponse>({\n path: '/api/chat',\n body: { ...req, options, messages, stream: true },\n signal,\n });\n return normalizeChatStream(stream, signal);\n },\n {\n signal: req.signal,\n timeoutMs: req.timeoutMs,\n model: req.model,\n // The endpoint's concurrency slot must stay held for as long as the stream is\n // actually being consumed, not just until the initial response/headers arrive\n // — see `executeWithFailover`'s `holdUntil` doc.\n holdUntil: (stream) => stream.finalResult,\n },\n );\n }\n return withSpan(\n `chat ${req.model}`,\n {\n [ATTR_GEN_AI_SYSTEM]: GEN_AI_SYSTEM_OLLAMA,\n [ATTR_GEN_AI_OPERATION_NAME]: 'chat',\n [ATTR_GEN_AI_REQUEST_MODEL]: req.model,\n },\n async (span) => {\n const rawRes = await this.executeWithFailover((http, signal) => {\n if (req.format !== undefined)\n this.assertStructuredOutputSupported(http.baseUrl, req.model);\n return http.request<ChatResponse>({\n path: '/api/chat',\n body: { ...req, options, messages, stream: false },\n signal,\n });\n }, req);\n const toolCalls = ensureToolCallIds(rawRes.message.tool_calls);\n const res: ChatResponse =\n toolCalls === rawRes.message.tool_calls\n ? rawRes\n : { ...rawRes, message: { ...rawRes.message, tool_calls: toolCalls } };\n span?.setAttributes({\n [ATTR_GEN_AI_RESPONSE_MODEL]: res.model,\n ...(res.prompt_eval_count !== undefined\n ? { [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: res.prompt_eval_count }\n : {}),\n ...(res.eval_count !== undefined\n ? { [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: res.eval_count }\n : {}),\n });\n return res;\n },\n );\n }\n\n chatStream(\n req: Omit<ChatRequestOptions, 'stream'>,\n ): Promise<OllamaStream<ChatResponse, ChatStreamResult>> {\n return this.chat({ ...req, stream: true });\n }\n\n async chatText(req: Omit<ChatRequestOptions, 'stream'>): Promise<string> {\n const res = await this.chat({ ...req, stream: false });\n return res.message.content;\n }\n\n async chatWithSchema<T>(\n req: Omit<ChatRequestOptions, 'stream' | 'format'>,\n schema: z.ZodType<T>,\n ): Promise<T> {\n const res = await this.chat({ ...req, format: zodToJsonSchema(schema), stream: false });\n return parseStructuredOutput(res.message.content, schema);\n }\n\n // --- Generate ---\n generate(\n req: GenerateRequestOptions & { stream: true },\n ): Promise<OllamaStream<GenerateResponse, GenerateStreamResult>>;\n generate(req: GenerateRequestOptions & { stream?: false | undefined }): Promise<GenerateResponse>;\n generate(\n req: GenerateRequestOptions,\n ): Promise<GenerateResponse | OllamaStream<GenerateResponse, GenerateStreamResult>>;\n async generate(\n req: GenerateRequestOptions,\n ): Promise<GenerateResponse | OllamaStream<GenerateResponse, GenerateStreamResult>> {\n const encodedReq = await withEncodedImages(req, req.signal);\n // Context-window pre-flight — same policy as `chat`.\n this.enforceContextSafety(\n 'generate',\n checkGenerateContext(req, {\n defaultContextLength: this.defaultContextLength,\n threshold: this.contextWarningThreshold,\n }),\n );\n const options = this.injectDefaultContextLength(req.options);\n if (encodedReq.stream) {\n return this.executeWithFailover(\n async (http, signal) => {\n if (encodedReq.format !== undefined)\n this.assertStructuredOutputSupported(http.baseUrl, encodedReq.model);\n const stream = await http.requestStream<GenerateResponse>({\n path: '/api/generate',\n body: { ...encodedReq, options, stream: true },\n signal,\n });\n return normalizeGenerateStream(stream, signal);\n },\n {\n signal: encodedReq.signal,\n timeoutMs: encodedReq.timeoutMs,\n model: encodedReq.model,\n holdUntil: (stream) => stream.finalResult,\n },\n );\n }\n return withSpan(\n `text_completion ${encodedReq.model}`,\n {\n [ATTR_GEN_AI_SYSTEM]: GEN_AI_SYSTEM_OLLAMA,\n [ATTR_GEN_AI_OPERATION_NAME]: 'text_completion',\n [ATTR_GEN_AI_REQUEST_MODEL]: encodedReq.model,\n },\n async (span) => {\n const res = await this.executeWithFailover((http, signal) => {\n if (encodedReq.format !== undefined)\n this.assertStructuredOutputSupported(http.baseUrl, encodedReq.model);\n return http.request<GenerateResponse>({\n path: '/api/generate',\n body: { ...encodedReq, options, stream: false },\n signal,\n });\n }, encodedReq);\n span?.setAttributes({\n [ATTR_GEN_AI_RESPONSE_MODEL]: res.model,\n ...(res.prompt_eval_count !== undefined\n ? { [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: res.prompt_eval_count }\n : {}),\n ...(res.eval_count !== undefined\n ? { [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: res.eval_count }\n : {}),\n });\n return res;\n },\n );\n }\n\n generateStream(\n req: Omit<GenerateRequestOptions, 'stream'>,\n ): Promise<OllamaStream<GenerateResponse, GenerateStreamResult>> {\n return this.generate({ ...req, stream: true });\n }\n\n async generateText(req: Omit<GenerateRequestOptions, 'stream'>): Promise<string> {\n const res = await this.generate({ ...req, stream: false });\n return res.response;\n }\n\n async generateWithSchema<T>(\n req: Omit<GenerateRequestOptions, 'stream' | 'format'>,\n schema: z.ZodType<T>,\n ): Promise<T> {\n const res = await this.generate({ ...req, format: zodToJsonSchema(schema), stream: false });\n return parseStructuredOutput(res.response, schema);\n }\n\n // --- Embeddings ---\n embed(req: EmbedRequestOptions): Promise<EmbedResponse> {\n return this.executeWithFailover(\n (http, signal) => http.request<EmbedResponse>({ path: '/api/embed', body: req, signal }),\n req,\n );\n }\n\n async embedText(\n model: string,\n input: string | readonly string[],\n ): Promise<readonly (readonly number[])[]> {\n const res = await this.embed({ model, input });\n return res.embeddings;\n }\n\n /**\n * @deprecated Ollama's `/api/embeddings` endpoint has been superseded by `/api/embed`\n * (exposed here as {@link OllamaClient.embed}), which additionally supports batch\n * input. Kept for compatibility with existing callers; new code should use `embed`.\n */\n embeddings(req: EmbeddingsRequestOptions): Promise<EmbeddingsResponse> {\n return this.executeWithFailover(\n (http, signal) =>\n http.request<EmbeddingsResponse>({ path: '/api/embeddings', body: req, signal }),\n req,\n );\n }\n\n // --- Model Operations (Delegated to ModelsClient) ---\n readonly listModels = () => this.models.list();\n readonly showModel = (req: ShowRequestOptions) => this.models.show(req);\n readonly pullModel = (r: PullRequestOptions) => this.models.pull(r);\n readonly pushModel = (r: PushRequestOptions) => this.models.push(r);\n readonly createModel = (r: CreateRequestOptions) => this.models.create(r);\n readonly deleteModel = (req: DeleteRequestOptions) => this.models.delete(req);\n readonly copyModel = (req: CopyRequestOptions) => this.models.copy(req);\n readonly ps = () => this.models.ps();\n readonly version = () => this.models.version();\n readonly createBlob = (digest: string, data: BinaryBody) => this.models.createBlob(digest, data);\n readonly checkBlob = (digest: string) => this.models.checkBlob(digest);\n /**\n * Immediately unloads `model` from VRAM. Convenience alias for\n * {@link ModelsClient.unload} — see that method for the full\n * lifecycle contract.\n */\n readonly unloadModel = (model: string) => this.models.unload(model);\n /**\n * Pre-loads and pins `model` into VRAM indefinitely. Convenience\n * alias for {@link ModelsClient.pin} — see that method for the\n * full lifecycle contract.\n */\n readonly pinModel = (model: string) => this.models.pin(model);\n\n // --- System One (Wave 13) ---\n /**\n * Ollama's System One decision layer (`POST /v1/systemone`) — evaluates\n * 1–64 typed questions (choice, noul, or score) against a provided state\n * and returns typed answers with probabilities and confidence.\n *\n * Local-only; requires Ollama >= 0.35.0. The runtime enforces the\n * version constraint automatically (lazily fetching `/api/version` when\n * `enforceVersion` is `'auto'` or `'strict'`) and rejects cloud-mode\n * calls. Request size is checked client-side: 64 KiB without images,\n * 32 MiB with images.\n *\n * The generic `Q` parameter captures the caller's question map at\n * compile time, giving key-safe answer access:\n *\n * ```ts\n * const result = await ollama.systemOne({\n * model: 'tev1:4b',\n * state: { ticket: 'Customer was charged twice' },\n * questions: {\n * intent: { type: 'choice', instructions: '...', criteria: { ... } },\n * urgent: { type: 'noul', instructions: '...' },\n * },\n * });\n * result.answers.intent // ✓ SystemOneAnswer (choice)\n * result.answers.urgent // ✓ SystemOneAnswer (noul)\n * result.answers.typo // ✗ TypeScript error\n * ```\n *\n * For the low-level generated API (without the generic wrapper), use\n * `client.native.systemOne(request)` directly.\n */\n async systemOne<Q extends SystemOneQuestions = SystemOneQuestions>(\n request: SystemOneRequest<Q>,\n ): Promise<SystemOneResponse<Q>> {\n // Delegate to the generated NativeApi. The cast through `unknown`\n // is necessary because the generic SystemOneRequest<Q> extends but\n // doesn't sufficiently overlap with the base SystemOneRequest for\n // TypeScript's direct conversion check. The generic Q is purely a\n // compile-time wrapper — the runtime behavior is identical.\n return this.native.systemOne(\n request as unknown as SystemOneRequestBase,\n ) as Promise<SystemOneResponseBase> as Promise<SystemOneResponse<Q>>;\n }\n\n // --- Web Endpoints ---\n /**\n * Ollama's hosted web search tool (`POST https://ollama.com/api/web_search`) — a fixed\n * Ollama Cloud service, unrelated to `config.endpoints`/`baseUrl` and not proxied\n * through a local server. Requires an Ollama account API key: pass `apiKey` to the\n * client constructor or set `OLLAMA_API_KEY`. Applies the same default `timeoutMs` and\n * retry policy as inference calls, but never cross-endpoint-fails-over — there is only\n * ever the one cloud endpoint to call.\n */\n async webSearch(req: WebSearchRequestOptions): Promise<WebSearchResponse> {\n const { count, max_results, ...rest } = req;\n const res = await this.executeCloudRequest(\n (http, signal) =>\n http.request<WebSearchResponse>({\n path: '/api/web_search',\n body: { ...rest, max_results: max_results ?? count },\n signal,\n }),\n req,\n );\n // `snippet` is a deprecated mirror of `content`, kept for backward compatibility —\n // see the `@deprecated` note on `WebSearchResult.snippet`.\n return { results: res.results.map((r) => ({ ...r, snippet: r.content })) };\n }\n /**\n * Ollama's hosted web fetch tool (`POST https://ollama.com/api/web_fetch`) — see\n * {@link OllamaClient.webSearch} for the cloud-endpoint/auth/timeout/retry behavior,\n * which applies identically here.\n */\n webFetch(req: WebFetchRequestOptions): Promise<WebFetchResponse> {\n return this.executeCloudRequest(\n (http, signal) =>\n http.request<WebFetchResponse>({ path: '/api/web_fetch', body: req, signal }),\n req,\n );\n }\n /**\n * Ollama Cloud usage statistics (`GET https://ollama.com/api/usage`) — request counts,\n * USD spend, and token totals (including cached input tokens) for cloud inference,\n * web search, and web fetch, bucketed by hour (`range: '24h'`) or day (`'7d'`/`'30d'`).\n *\n * See {@link OllamaClient.webSearch} for the cloud-endpoint/auth/timeout/retry\n * behavior, which applies identically here. Query parameters mirror the official\n * endpoint: `range` (`'24h' | '7d' | '30d'`, server default `'7d'`) and `scope`\n * (`'self' | 'team'`, server default `'self'`; team scope requires a team admin).\n * Omitted options are left unset so the server applies its own defaults.\n *\n * ```ts\n * const usage = await client.usage({ range: '24h' });\n * console.log(usage.totals.request_count, usage.totals.usage_usd);\n * for (const bucket of usage.buckets) {\n * if (bucket.partial) continue; // current hour, still in progress\n * // ...\n * }\n * ```\n */\n usage(req: UsageRequestOptions = {}): Promise<UsageResponse> {\n const params = new URLSearchParams();\n if (req.range !== undefined) params.set('range', req.range);\n if (req.scope !== undefined) params.set('scope', req.scope);\n const query = params.toString();\n return this.executeCloudRequest(\n (http, signal) =>\n http.request<UsageResponse>({\n path: query ? `/api/usage?${query}` : '/api/usage',\n method: 'GET',\n signal,\n }),\n req,\n );\n }\n /**\n * Ollama Cloud balance (`GET https://ollama.com/api/balance`) — remaining included\n * and purchased usage credits. The included balance is either a plan-period credit\n * object (`balance_usd`/`allowance_usd`/`period`) or, on legacy plans, session/weekly\n * percentage limits; the shape is discriminated at runtime by the server response.\n * See {@link OllamaClient.webSearch} for the cloud-endpoint/auth/timeout/retry\n * behavior, which applies identically here.\n *\n * ```ts\n * const balance = await client.balance();\n * if ('balance_usd' in balance.included) {\n * console.log(balance.included.balance_usd, balance.purchased.balance_usd);\n * } else {\n * console.log(balance.included.session.remaining_percent, '% of session limit left');\n * }\n * ```\n */\n balance(req: BalanceRequestOptions = {}): Promise<BalanceResponse> {\n return this.executeCloudRequest(\n (http, signal) =>\n http.request<BalanceResponse>({ path: '/api/balance', method: 'GET', signal }),\n req,\n );\n }\n /**\n * Runs `operation` against the fixed Ollama Cloud host with this client's default\n * timeout and retry policy — the same primitives `executeWithFailover` uses, minus the\n * multi-candidate loop, since `webSearch`/`webFetch` only ever have the one endpoint.\n */\n private async executeCloudRequest<T>(\n operation: (http: HttpClient, signal: AbortSignal) => Promise<T>,\n options: RequestCancellationOptions,\n ): Promise<T> {\n const timeout = createTimeoutSignal(options.timeoutMs ?? this.timeoutMs, options.signal);\n using _timeout = {\n [Symbol.dispose]() {\n timeout.cancel();\n },\n };\n const requestId = createLogicalRequestId();\n const http = new HttpClient({\n baseUrl: OLLAMA_CLOUD_BASE_URL,\n apiKey: this.cloudApiKey,\n fetch: this.fetchImpl,\n middleware: this.middleware,\n onLifecycleEvent: this.onLifecycleEvent,\n requestId,\n });\n return await withRetry(\n () => operation(http, timeout.signal),\n {\n ...this.retryConfig,\n onRetry: (error, attempt, delayMs) => {\n this.retryConfig.onRetry?.(error, attempt, delayMs);\n this.onLifecycleEvent?.({\n type: 'retry',\n requestId,\n attempt: attempt + 1,\n error,\n delayMs,\n timestamp: Date.now(),\n });\n },\n },\n timeout.signal,\n );\n // timeout.cancel() called automatically via `using _timeout`\n }\n\n // --- Capabilities & Health ---\n capabilities(model: string, signal?: AbortSignal): Promise<ModelCapabilities> {\n return this.executeWithFailover(\n (http, runnerSignal) => detectModelCapabilities(http, model, runnerSignal),\n {\n singleEndpoint: true,\n model,\n ...(signal !== undefined ? { signal } : {}),\n },\n );\n }\n runtimeMode(): RuntimeMode {\n const ep = this.registry.candidates()[0];\n return inferRuntimeMode(ep?.baseUrl ?? DEFAULT_BASE_URL);\n }\n healthCheck(): Promise<EndpointHealthCheckResult[]> {\n return Promise.all(\n this.registry\n .list()\n .map((ep) =>\n checkEndpointHealth(ep, this.fetchImpl, 5000, this.middleware, this.onLifecycleEvent),\n ),\n );\n }\n endpointStatus(): EndpointHealth[] {\n return this.registry.status();\n }\n\n // --- Compatibility Adapters ---\n get openai(): OpenAICompatClient {\n const ep = this.registry.candidates()[0];\n return new OpenAICompatClient(\n new HttpClient({\n baseUrl: ep?.baseUrl ?? DEFAULT_BASE_URL,\n apiKey: ep?.apiKey,\n headers: ep?.headers,\n fetch: this.fetchImpl,\n middleware: this.middleware,\n onLifecycleEvent: this.onLifecycleEvent,\n }),\n (op, opts) => this.executeWithFailover(op, opts),\n );\n }\n get anthropic(): AnthropicCompatClient {\n const ep = this.registry.candidates()[0];\n return new AnthropicCompatClient(\n new HttpClient({\n baseUrl: ep?.baseUrl ?? DEFAULT_BASE_URL,\n apiKey: ep?.apiKey,\n headers: ep?.headers,\n fetch: this.fetchImpl,\n middleware: this.middleware,\n onLifecycleEvent: this.onLifecycleEvent,\n }),\n (op, opts) => this.executeWithFailover(op, opts),\n );\n }\n}\n","/**\n * Standalone fetch-with-backoff helper.\n *\n * Ollama's server caps in-flight work via `OLLAMA_MAX_QUEUE` (default\n * 512); when the queue saturates, excess requests are rejected with\n * HTTP **503 Service Unavailable**. The same retry discipline applies\n * to **429 Too Many Requests** for rate-limited cloud endpoints.\n *\n * Callers running parallel agentic swarms (multi-turn tool loops,\n * fan-out embed batches, speculative-decoding pipelines) can't always\n * predict saturation ahead of time, so the SDK exposes this helper —\n * a thin wrapper around `fetch` that retries 503/429 responses with\n * the same jittered exponential backoff used by the SDK's internal\n * transport (see `./backoff.ts` and `./retry.ts`).\n *\n * The helper is intentionally standalone: it works with any\n * `fetch`-shaped function (browser `globalThis.fetch`, `undici`, an\n * Edge runtime polyfill, or a `vi.fn()` mock) and does not depend on\n * the wider `OllamaClient` / `HttpClient` machinery. Use it when you\n * want the SDK's retry ergonomics on raw HTTP traffic that doesn't go\n * through `OllamaClient` — for example, when calling the OpenAI / Anthropic\n * compatibility bridges directly, or when talking to a sibling Ollama\n * instance outside the configured endpoint registry.\n *\n * For SDK-routed traffic (`client.chat`, `client.generate`, …),\n * retry/backoff is already applied automatically by the transport\n * layer; you do NOT need to wrap those calls in `fetchWithBackoff`.\n */\n\nimport { calculateBackoff, DEFAULT_BACKOFF, type BackoffOptions } from './backoff.js';\n\n/**\n * Configuration for {@link fetchWithBackoff}.\n *\n * All fields optional; sensible defaults are provided.\n */\nexport interface FetchWithBackoffConfig {\n /**\n * Maximum number of retry attempts after the initial request.\n * Defaults to `3` (i.e. up to 4 total HTTP requests).\n */\n readonly maxRetries?: number | undefined;\n /**\n * Backoff tuning. Defaults to {@link DEFAULT_BACKOFF}\n * (`initialDelayMs: 500`, `maxDelayMs: 30_000`, `backoffFactor: 2`).\n */\n readonly backoff?: BackoffOptions | undefined;\n /**\n * Optional callback fired before each retry sleep. Useful for\n * logging, OpenTelemetry span events, or surfacing the\n * backoff in observability dashboards.\n *\n * Receives the attempt index (0-based for the original request,\n * 1+ for retries), the HTTP status that triggered the retry\n * (or `0` for network-level failures), and the calculated delay\n * in milliseconds (already jittered).\n */\n readonly onRetry?:\n | ((attempt: number, status: number, delayMs: number) => void)\n | undefined;\n /**\n * Optional `AbortSignal` forwarded to the underlying `fetch`.\n * Aborting mid-backoff cancels the sleep and rejects with an\n * `AbortError`-shaped error (the same shape `fetch` itself\n * rejects with on abort).\n */\n readonly signal?: AbortSignal | undefined;\n /**\n * Optional `fetch` implementation to use. Defaults to\n * `globalThis.fetch`. Pass an explicit implementation when\n * running in environments without a global `fetch` (legacy\n * Node.js, custom sandboxes), or to inject a mock for testing.\n */\n readonly fetch?: typeof globalThis.fetch | undefined;\n}\n\n/**\n * HTTP statuses that trigger a retry by default. Both indicate\n * transient, server-side saturation — the queue is full and the\n * request is rejected without consuming inference resources.\n *\n * - `503 Service Unavailable` — Ollama queue saturated\n * (`OLLAMA_MAX_QUEUE` exceeded).\n * - `429 Too Many Requests` — rate limit hit (typically Ollama\n * Cloud endpoints).\n */\nexport const RETRYABLE_STATUS_CODES: ReadonlySet<number> = new Set([429, 503]);\n\n/**\n * Default retry configuration used when {@link FetchWithBackoffConfig}\n * is omitted entirely. Matches the SDK's internal transport defaults\n * so consumers see identical retry behavior whether they go through\n * `OllamaClient` or call `fetchWithBackoff` directly.\n */\nexport const DEFAULT_FETCH_BACKOFF_CONFIG = {\n maxRetries: 3,\n} as const satisfies Pick<FetchWithBackoffConfig, 'maxRetries'>;\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(\n Object.assign(new Error('fetchWithBackoff aborted during backoff sleep'), {\n name: 'AbortError',\n }),\n );\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = (): void => {\n clearTimeout(timer);\n signal?.removeEventListener('abort', onAbort);\n reject(\n Object.assign(new Error('fetchWithBackoff aborted during backoff sleep'), {\n name: 'AbortError',\n }),\n );\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\n/**\n * Wrapper around any `fetch`-shaped function that retries HTTP 429 / 503\n * responses with jittered exponential backoff (full-jitter strategy —\n * see `./backoff.ts` for the rationale and AWS Architecture Blog\n * citation).\n *\n * The wrapper:\n * - forwards `input`/`init` unchanged to every attempt,\n * - sleeps before each retry using the configured backoff,\n * - retries up to `maxRetries` times (default 3), then returns the\n * final `Response` (whatever its status) so the caller can\n * branch on it,\n * - rethrows network errors (TypeError under WHATWG fetch) only\n * after exhausting retries — intermediate attempts also sleep,\n * - honors `AbortSignal` for both the underlying `fetch` and the\n * sleep between retries.\n *\n * @example\n * ```ts\n * const res = await fetchWithBackoff(\n * 'http://localhost:11434/api/chat',\n * { method: 'POST', body: JSON.stringify(payload) },\n * {\n * maxRetries: 5,\n * onRetry: (attempt, status, delayMs) =>\n * console.warn(`retry ${attempt} (HTTP ${status}) in ${delayMs}ms`),\n * },\n * );\n * if (!res.ok) throw new Error(`chat failed: HTTP ${res.status}`);\n * ```\n */\nexport async function fetchWithBackoff(\n input: string | URL | Request,\n init?: RequestInit | undefined,\n config: FetchWithBackoffConfig = {},\n): Promise<Response> {\n const fetchImpl = config.fetch ?? (globalThis.fetch as typeof globalThis.fetch | undefined);\n if (typeof fetchImpl !== 'function') {\n throw new Error(\n 'fetchWithBackoff: no global fetch is available. Pass a fetch implementation ' +\n 'via config.fetch, or run in Node.js >= 18 / a browser-like environment.',\n );\n }\n\n const maxRetries: number = config.maxRetries ?? DEFAULT_FETCH_BACKOFF_CONFIG.maxRetries;\n const backoff = config.backoff ?? DEFAULT_BACKOFF;\n const signal = config.signal;\n\n let lastError: unknown;\n for (let attempt = 0; attempt <= maxRetries; attempt += 1) {\n // Defensive guard: if the signal has already been aborted (e.g.\n // caller passed an already-aborted controller, or a prior iteration's\n // sleep-abort set this in-flight), bail out before issuing the next\n // HTTP attempt. WHATWG `fetch` would reject on its own, but we add\n // the explicit check so custom `fetch` implementations that don't\n // honor `signal` still can't accidentally fire a request after the\n // caller has cancelled.\n if (signal?.aborted) {\n throw Object.assign(new Error('fetchWithBackoff aborted'), { name: 'AbortError' });\n }\n try {\n const response = await fetchImpl(input, {\n ...init,\n ...(signal !== undefined ? { signal } : {}),\n });\n\n if (\n RETRYABLE_STATUS_CODES.has(response.status) &&\n attempt < maxRetries\n ) {\n const delayMs = calculateBackoff(attempt, backoff);\n config.onRetry?.(attempt, response.status, delayMs);\n await sleep(delayMs, signal);\n continue;\n }\n\n return response;\n } catch (err) {\n lastError = err;\n // WHATWG fetch rejects with an AbortError-shaped DOMException\n // when the signal fires. Never retry those — propagate immediately.\n if (\n signal?.aborted ||\n (err instanceof Error && err.name === 'AbortError')\n ) {\n throw err;\n }\n // Network-level failures (TypeError under WHATWG fetch, or\n // any thrown error from a custom fetchImpl) are treated as\n // retryable: a connection reset mid-flight is just as much a\n // sign of transient saturation as a 503.\n if (attempt < maxRetries) {\n const delayMs = calculateBackoff(attempt, backoff);\n config.onRetry?.(attempt, 0, delayMs);\n await sleep(delayMs, signal);\n continue;\n }\n }\n }\n\n // All retries exhausted. Re-throw the last network-level error.\n throw lastError ?? new Error('fetchWithBackoff: exhausted retry attempts');\n}\n","/**\n * `done_reason` decoder helpers — graceful handling of upstream\n * variance in the `done_reason` field returned by `/api/chat` and\n * `/api/generate`.\n *\n * The Ollama OpenAPI documents `done_reason` as a free-form string,\n * but the values actually observed on the wire fall into a small,\n * stable set:\n *\n * - `\"stop\"` — natural stop token hit or end-of-text.\n * - `\"length\"` — `num_predict` ceiling reached mid-generation.\n * - `\"load\"` — model load event (seen in streaming chunks\n * before the first token is generated; the\n * server reports `done: true` with `done_reason:\n * 'load'` to indicate the load phase completed).\n * - `\"unload\"` — model unloaded (seen after a `keep_alive: 0`\n * request finalizes the unload).\n *\n * The SDK accepts any string for `done_reason` (so unknown values\n * don't cause runtime errors — the conformance-test failure mode\n * the Wave 13 CI run flagged). These helpers give callers who want\n * to narrow on the known set a type-safe way to do so.\n *\n * See: https://github.com/ollama/ollama/blob/main/docs/api.md\n */\n\n/**\n * The set of `done_reason` values Ollama documents and emits in\n * practice. Unknown upstream additions pass through as plain\n * strings — use {@link isKnownDoneReason} to narrow.\n */\nexport type KnownDoneReason = 'stop' | 'length' | 'load' | 'unload';\n\n/**\n * Set of known `done_reason` literals, exposed for callers building\n * exhaustive `switch` statements or runtime validation tables.\n */\nexport const KNOWN_DONE_REASONS: ReadonlySet<KnownDoneReason> = new Set([\n 'stop',\n 'length',\n 'load',\n 'unload',\n]);\n\n/**\n * Type guard: `true` when `value` is one of the documented\n * `done_reason` literals. Use this to safely narrow from\n * `string | undefined` to {@link KnownDoneReason} before a\n * `switch` block.\n *\n * @example\n * ```ts\n * if (isKnownDoneReason(res.done_reason)) {\n * switch (res.done_reason) {\n * case 'stop': // …\n * case 'length': // …\n * case 'load': // …\n * case 'unload': // …\n * }\n * } else {\n * // forward-compat: an unknown reason we didn't list\n * }\n * ```\n */\nexport function isKnownDoneReason(\n value: string | undefined | null,\n): value is KnownDoneReason {\n return value !== undefined && value !== null && KNOWN_DONE_REASONS.has(value as KnownDoneReason);\n}\n","/**\n * Web Standard Stream adapters for OllamaStream.\n * Enables seamless integration with Vercel AI SDK, Next.js route handlers, and standard web fetch responses.\n */\n\nimport type { OllamaStream } from './stream.js';\n\n/**\n * Transforms an OllamaStream into a standard Web ReadableStream of token text strings.\n */\nexport function toTextStream<TChunk, TFinal>(\n stream: OllamaStream<TChunk, TFinal>,\n): ReadableStream<string> {\n const iterator = stream[Symbol.asyncIterator]();\n\n return new ReadableStream<string>({\n async pull(controller) {\n try {\n while (true) {\n const { done, value } = await iterator.next();\n if (done) {\n controller.close();\n return;\n }\n if (value.type === 'token' && value.data.delta) {\n controller.enqueue(value.data.delta);\n return;\n }\n }\n } catch (err) {\n controller.error(err);\n }\n },\n cancel() {\n stream.abort();\n },\n });\n}\n\n/**\n * Transforms an OllamaStream into a standard Web ReadableStream of encoded Uint8Array bytes.\n */\nexport function toDataStream<TChunk, TFinal>(\n stream: OllamaStream<TChunk, TFinal>,\n): ReadableStream<Uint8Array> {\n const textStream = toTextStream(stream);\n const reader = textStream.getReader();\n const encoder = new TextEncoder();\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n return;\n }\n controller.enqueue(encoder.encode(value));\n } catch (err) {\n controller.error(err);\n }\n },\n cancel() {\n reader.cancel();\n stream.abort();\n },\n });\n}\n\n/**\n * Converts an OllamaStream directly into a standard Web Response with text/plain streaming headers.\n */\nexport function toResponse<TChunk, TFinal>(\n stream: OllamaStream<TChunk, TFinal>,\n init: ResponseInit = {},\n): Response {\n const body = toDataStream(stream);\n const headers = new Headers(init.headers);\n if (!headers.has('Content-Type')) {\n headers.set('Content-Type', 'text/plain; charset=utf-8');\n }\n return new Response(body, { ...init, headers });\n}\n","/**\n * Client-side usage budgeting.\n *\n * Ollama Cloud does not expose account-level quota or remaining-budget through the API —\n * chat/generate responses carry only per-request token counts, and there is no header or\n * endpoint that reports how much of your plan's session or weekly limit is left (the only\n * way to see that today is the https://ollama.com dashboard or the 90%-usage email). See\n * https://github.com/ollama/ollama/issues/15663.\n *\n * `QuotaManager` does not — and cannot — read Ollama's real limits. It tracks usage you\n * record against budgets *you* configure over one or more rolling windows, and refuses to\n * proceed once a window's budget is spent. Pair it with `OllamaRateLimitError` (thrown by\n * `OllamaClient` on the server's actual 429) as the authoritative signal; treat\n * `QuotaManager` as a local safety net that fails fast before the request is even sent.\n */\n\nimport { OllamaQuotaExceededError } from './errors.js';\nimport { extractUsage, type RawUsageSource, type TokenUsage } from './usage.js';\n\nexport interface QuotaWindowConfig {\n /** Identifies this window in status reports and thrown errors (e.g. \"session\", \"weekly\"). */\n readonly id: string;\n /** Length of the rolling window in milliseconds, after which usage resets to zero. */\n readonly windowMs: number;\n /** Token budget for the window. Omit to only track requests. */\n readonly maxTokens?: number;\n /** Request-count budget for the window. Omit to only track tokens. */\n readonly maxRequests?: number;\n}\n\nexport interface QuotaWindowStatus extends QuotaWindowConfig {\n readonly tokensUsed: number;\n readonly requestsMade: number;\n readonly windowStartedAt: number;\n readonly windowResetAt: number;\n readonly remainingTokens?: number;\n readonly remainingRequests?: number;\n}\n\nexport interface QuotaManagerOptions {\n readonly windows: readonly QuotaWindowConfig[];\n /** Clock override for testing. Defaults to `Date.now`. */\n readonly now?: () => number;\n}\n\ninterface WindowState {\n readonly config: QuotaWindowConfig;\n tokensUsed: number;\n requestsMade: number;\n windowStartedAt: number;\n}\n\nexport class QuotaManager {\n private readonly now: () => number;\n private readonly windows: readonly WindowState[];\n\n constructor(options: QuotaManagerOptions) {\n if (options.windows.length === 0) {\n throw new Error('QuotaManager requires at least one window configuration.');\n }\n this.now = options.now ?? Date.now;\n this.windows = options.windows.map((config) => ({\n config,\n tokensUsed: 0,\n requestsMade: 0,\n windowStartedAt: this.now(),\n }));\n }\n\n private rollover(state: WindowState): void {\n if (this.now() - state.windowStartedAt >= state.config.windowMs) {\n state.tokensUsed = 0;\n state.requestsMade = 0;\n state.windowStartedAt = this.now();\n }\n }\n\n /** Current usage, budgets, and reset time for every configured window. */\n status(): readonly QuotaWindowStatus[] {\n return this.windows.map((state) => {\n this.rollover(state);\n const { config } = state;\n return {\n ...config,\n tokensUsed: state.tokensUsed,\n requestsMade: state.requestsMade,\n windowStartedAt: state.windowStartedAt,\n windowResetAt: state.windowStartedAt + config.windowMs,\n ...(config.maxTokens !== undefined\n ? { remainingTokens: Math.max(0, config.maxTokens - state.tokensUsed) }\n : {}),\n ...(config.maxRequests !== undefined\n ? { remainingRequests: Math.max(0, config.maxRequests - state.requestsMade) }\n : {}),\n };\n });\n }\n\n /**\n * True if one more request — optionally estimated at `estimatedTokens` — would stay\n * within every configured window's budget. Read-only; does not record usage.\n */\n canProceed(estimatedTokens = 0): boolean {\n return this.windows.every((state) => {\n this.rollover(state);\n const { config } = state;\n if (config.maxRequests !== undefined && state.requestsMade + 1 > config.maxRequests) {\n return false;\n }\n return !(\n config.maxTokens !== undefined && state.tokensUsed + estimatedTokens > config.maxTokens\n );\n });\n }\n\n /**\n * Throws `OllamaQuotaExceededError` for the first window that `canProceed(estimatedTokens)`\n * would fail on; otherwise a no-op. Call before issuing a request.\n */\n assertCanProceed(estimatedTokens = 0): void {\n for (const state of this.windows) {\n this.rollover(state);\n const { config } = state;\n if (config.maxRequests !== undefined && state.requestsMade + 1 > config.maxRequests) {\n throw new OllamaQuotaExceededError(\n `Client-side quota window \"${config.id}\" would exceed its request budget ` +\n `(${state.requestsMade}/${config.maxRequests} requests used).`,\n { windowId: config.id, resetAt: state.windowStartedAt + config.windowMs },\n );\n }\n if (config.maxTokens !== undefined && state.tokensUsed + estimatedTokens > config.maxTokens) {\n throw new OllamaQuotaExceededError(\n `Client-side quota window \"${config.id}\" would exceed its token budget ` +\n `(${state.tokensUsed}/${config.maxTokens} tokens used).`,\n { windowId: config.id, resetAt: state.windowStartedAt + config.windowMs },\n );\n }\n }\n }\n\n /** Records one request's actual usage — a raw API response or a pre-normalized `TokenUsage` — against every window. */\n recordUsage(usage: RawUsageSource | TokenUsage): void {\n const normalized: TokenUsage = 'totalTokens' in usage ? usage : extractUsage(usage);\n for (const state of this.windows) {\n this.rollover(state);\n state.tokensUsed += normalized.totalTokens;\n state.requestsMade += 1;\n }\n }\n\n /** Resets one window (by `id`) or, if omitted, all windows — zeroing usage and restarting their clocks. */\n reset(windowId?: string): void {\n for (const state of this.windows) {\n if (windowId === undefined || state.config.id === windowId) {\n state.tokensUsed = 0;\n state.requestsMade = 0;\n state.windowStartedAt = this.now();\n }\n }\n }\n}\n\nexport interface OllamaCloudFreeTierQuotaBudgets {\n /** Budget for the free tier's ~5-hour session window. Omit to skip tracking it. */\n readonly session?: { readonly maxTokens?: number; readonly maxRequests?: number };\n /** Budget for the free tier's 7-day weekly window. Omit to skip tracking it. */\n readonly weekly?: { readonly maxTokens?: number; readonly maxRequests?: number };\n readonly now?: () => number;\n}\n\n/**\n * Convenience factory mirroring Ollama Cloud free-tier's documented reset cadence — a\n * session window that resets every 5 hours and a weekly window that resets every 7 days\n * (see https://ollama.com/pricing). Ollama does not publish the actual token/request\n * ceilings for either window, so you must supply the budgets yourself (e.g. from your own\n * observed usage) — this only wires up the window durations.\n */\nexport function createOllamaCloudFreeTierQuota(\n budgets: OllamaCloudFreeTierQuotaBudgets,\n): QuotaManager {\n const windows: QuotaWindowConfig[] = [];\n if (budgets.session !== undefined) {\n windows.push({ id: 'session', windowMs: 5 * 60 * 60 * 1000, ...budgets.session });\n }\n if (budgets.weekly !== undefined) {\n windows.push({ id: 'weekly', windowMs: 7 * 24 * 60 * 60 * 1000, ...budgets.weekly });\n }\n if (windows.length === 0) {\n throw new Error(\n 'createOllamaCloudFreeTierQuota requires at least a `session` or `weekly` budget.',\n );\n }\n return new QuotaManager({ windows, ...(budgets.now !== undefined ? { now: budgets.now } : {}) });\n}\n","/**\n * Type-safe tool definition helper.\n */\n\nimport type { z } from 'zod';\nimport { zodToJsonSchema } from '../schema/zod.js';\nimport type { Tool, ToolHandler } from './types.js';\nimport type { ToolProperty } from '../types.js';\n\nexport interface DefineToolOptions<TParams, TResult> {\n readonly name: string;\n readonly description: string;\n readonly schema: z.ZodType<TParams>;\n readonly execute: ToolHandler<TParams, TResult>;\n /**\n * Per-tool execution timeout in milliseconds, overriding the registry's default.\n * Pass `0` to explicitly disable timeout enforcement for this tool.\n */\n readonly timeoutMs?: number | undefined;\n}\n\n/**\n * Creates a strongly-typed Tool definition with automatic JSON Schema conversion.\n */\nexport function defineTool<TParams, TResult>(\n options: DefineToolOptions<TParams, TResult>,\n): Tool<TParams, TResult> {\n const jsonSchema = zodToJsonSchema(options.schema);\n const properties = (jsonSchema['properties'] ?? {}) as Record<string, ToolProperty>;\n const required = (jsonSchema['required'] ?? []) as string[];\n\n return {\n name: options.name,\n description: options.description,\n schema: options.schema,\n execute: options.execute,\n timeoutMs: options.timeoutMs,\n definition: {\n type: 'function',\n function: {\n name: options.name,\n description: options.description,\n parameters: {\n type: 'object',\n properties,\n ...(required.length > 0 ? { required } : {}),\n },\n },\n },\n };\n}\n","/**\n * Tool registry for managing definitions and executing model tool calls.\n */\n\nimport {\n OllamaNotFoundError,\n OllamaToolTimeoutError,\n OllamaToolValidationError,\n} from '../errors.js';\nimport {\n withSpan,\n setSpanError,\n ATTR_GEN_AI_TOOL_NAME,\n ATTR_GEN_AI_TOOL_CALL_ID,\n} from '../telemetry/index.js';\nimport type { ToolCall, ToolDefinition } from '../types.js';\nimport type { AnyTool, Tool, ToolExecutionContext, ToolExecutionResult } from './types.js';\nimport { disposableTimer } from '../utils.js';\n\nexport interface ToolRegistryOptions {\n readonly tools?: readonly AnyTool[] | undefined;\n readonly onError?: ((error: Error, toolCall: ToolCall) => string) | undefined;\n /**\n * Default per-call execution timeout in milliseconds, applied to any tool that\n * doesn't declare its own `timeoutMs`. Undefined (the default) means no timeout is\n * enforced, matching prior behavior. Recommended whenever tool arguments or\n * implementations are influenced by model output you don't fully control, since an\n * unbounded tool call can otherwise stall the entire agent loop indefinitely.\n *\n * Enforcement is cooperative: it races the tool's promise against a timer and\n * reports a timeout failure, but cannot forcibly halt synchronous or non-abort-aware\n * asynchronous work already in flight on the same thread. Tools that perform I/O\n * should honor `ToolExecutionContext.signal` to stop promptly on timeout.\n */\n readonly timeoutMs?: number | undefined;\n /**\n * Maximum number of tool calls executed concurrently by `executeToolCalls`.\n * Undefined (the default) runs all calls in parallel, matching prior behavior.\n */\n readonly maxConcurrency?: number | undefined;\n /**\n * Maximum length of a tool's `outputString` before it is truncated. Guards against a\n * single tool call flooding the conversation history / model context (and process\n * memory) with unbounded output. Undefined (the default) applies no limit.\n */\n readonly maxOutputChars?: number | undefined;\n}\n\nexport class ToolRegistry {\n private readonly tools = new Map<string, AnyTool>();\n private readonly onError?: ((error: Error, toolCall: ToolCall) => string) | undefined;\n private readonly defaultTimeoutMs?: number | undefined;\n private readonly maxConcurrency?: number | undefined;\n private readonly maxOutputChars?: number | undefined;\n\n constructor(toolsOrOptions?: readonly AnyTool[] | ToolRegistryOptions | undefined) {\n if (Array.isArray(toolsOrOptions)) {\n this.registerMany(toolsOrOptions);\n } else if (toolsOrOptions !== undefined) {\n const opts = toolsOrOptions as ToolRegistryOptions;\n this.onError = opts.onError;\n this.defaultTimeoutMs = opts.timeoutMs;\n this.maxConcurrency = opts.maxConcurrency;\n this.maxOutputChars = opts.maxOutputChars;\n if (opts.tools) {\n this.registerMany(opts.tools);\n }\n }\n }\n\n register(tool: AnyTool): this {\n this.tools.set(tool.name, tool);\n return this;\n }\n\n registerMany(tools: readonly AnyTool[]): this {\n for (const tool of tools) {\n this.register(tool);\n }\n return this;\n }\n\n get(name: string): AnyTool | undefined {\n return this.tools.get(name);\n }\n\n definitions(): ToolDefinition[] {\n return Array.from(this.tools.values()).map((t) => t.definition);\n }\n\n async executeToolCall(\n toolCall: ToolCall,\n ctx: ToolExecutionContext = {},\n ): Promise<ToolExecutionResult> {\n const { name } = toolCall.function;\n return withSpan(\n `execute_tool ${name}`,\n { [ATTR_GEN_AI_TOOL_NAME]: name, [ATTR_GEN_AI_TOOL_CALL_ID]: toolCall.id },\n async (span) => {\n const result = await this.executeToolCallUninstrumented(toolCall, ctx);\n if (!result.success) {\n await setSpanError(span, result.error);\n }\n return result;\n },\n );\n }\n\n private async executeToolCallUninstrumented(\n toolCall: ToolCall,\n ctx: ToolExecutionContext,\n ): Promise<ToolExecutionResult> {\n const { name, arguments: args } = toolCall.function;\n const tool = this.tools.get(name);\n\n if (!tool) {\n const err = new OllamaNotFoundError(`Tool \"${name}\" is not registered in this registry`);\n return this.handleExecutionError(err, toolCall);\n }\n\n const parseResult = tool.schema.safeParse(args);\n if (!parseResult.success) {\n const err = new OllamaToolValidationError(`Tool \"${name}\" arguments validation failed`, {\n toolName: name,\n issues: parseResult.error.issues,\n cause: parseResult.error,\n });\n return this.handleExecutionError(err, toolCall);\n }\n\n try {\n const result = await this.runWithTimeout(tool, parseResult.data, ctx, name);\n const outputString = this.truncateOutput(\n typeof result === 'string' ? result : JSON.stringify(result),\n );\n return {\n toolName: name,\n toolCallId: toolCall.id,\n success: true,\n result,\n outputString,\n };\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n return this.handleExecutionError(error, toolCall);\n }\n }\n\n /**\n * Executes every call in `toolCalls` and returns results in the same order, so results\n * are always correlatable by array position regardless of `id`. Each result also echoes\n * its call's `toolCallId` for callers who'd rather match by ID — see the {@link ToolCall}\n * docs for how that id is produced. Runs fully in parallel (`Promise.all`) unless\n * `maxConcurrency` was configured, in which case a bounded worker pool is used instead.\n */\n async executeToolCalls(\n toolCalls: readonly ToolCall[],\n ctx: ToolExecutionContext = {},\n ): Promise<ToolExecutionResult[]> {\n const limit = this.maxConcurrency;\n if (!limit || limit >= toolCalls.length) {\n return Promise.all(toolCalls.map((tc) => this.executeToolCall(tc, ctx)));\n }\n\n const results = new Array<ToolExecutionResult>(toolCalls.length);\n let nextIndex = 0;\n const worker = async (): Promise<void> => {\n for (let i = nextIndex++; i < toolCalls.length; i = nextIndex++) {\n results[i] = await this.executeToolCall(toolCalls[i] as ToolCall, ctx);\n }\n };\n await Promise.all(Array.from({ length: limit }, () => worker()));\n return results;\n }\n\n private async runWithTimeout<TParams>(\n tool: Tool<TParams, unknown>,\n params: TParams,\n ctx: ToolExecutionContext,\n toolName: string,\n ): Promise<unknown> {\n const timeoutMs = tool.timeoutMs ?? this.defaultTimeoutMs;\n if (!timeoutMs || timeoutMs <= 0) {\n return tool.execute(params, ctx);\n }\n\n const controller = new AbortController();\n const onParentAbort = (): void => controller.abort(ctx.signal?.reason);\n if (ctx.signal) {\n if (ctx.signal.aborted) {\n controller.abort(ctx.signal.reason);\n } else {\n ctx.signal.addEventListener('abort', onParentAbort, { once: true });\n }\n }\n\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs);\n using _timer = disposableTimer(timer);\n // Also clean up the parent-abort listener at scope exit (conditional on ctx.signal)\n using _listener = {\n [Symbol.dispose]() {\n ctx.signal?.removeEventListener('abort', onParentAbort);\n },\n };\n\n const executePromise = Promise.resolve(\n tool.execute(params, { ...ctx, signal: controller.signal }),\n );\n // Prevent an unhandled rejection if the tool's promise loses the race and later\n // rejects; the tool remains responsible for actually stopping its own work via\n // `signal` since JS cannot forcibly cancel work already in flight.\n executePromise.catch(() => undefined);\n\n const abortRejection = (): Error =>\n timedOut\n ? new OllamaToolTimeoutError(`Tool \"${toolName}\" timed out after ${timeoutMs}ms`, {\n toolName,\n timeoutMs,\n })\n : ((ctx.signal?.reason as Error | undefined) ?? new Error('Tool execution aborted'));\n\n return await Promise.race([\n executePromise,\n controller.signal.aborted\n ? Promise.reject(abortRejection())\n : new Promise<never>((_resolve, reject) => {\n controller.signal.addEventListener('abort', () => reject(abortRejection()), {\n once: true,\n });\n }),\n ]);\n // clearTimeout(timer) + removeEventListener called automatically via `using`\n }\n\n private truncateOutput(output: string): string {\n const limit = this.maxOutputChars;\n if (!limit || output.length <= limit) {\n return output;\n }\n return `${output.slice(0, limit)}\\n… [truncated ${output.length - limit} of ${output.length} chars]`;\n }\n\n private handleExecutionError(error: Error, toolCall: ToolCall): ToolExecutionResult {\n const fallbackMessage = this.onError ? this.onError(error, toolCall) : error.message;\n return {\n toolName: toolCall.function.name,\n toolCallId: toolCall.id,\n success: false,\n error,\n outputString: this.truncateOutput(fallbackMessage),\n };\n }\n}\n","/** Dependency-free JSON Schema validator for MCP tool argument boundaries. */\n\nexport interface JsonSchemaValidationIssue {\n readonly path: readonly (string | number)[];\n readonly message: string;\n}\n\nfunction label(path: readonly (string | number)[]): string {\n return path.length === 0 ? 'value' : 'value' + path.map((part) => typeof part === 'number' ? '[' + part + ']' : '.' + part).join('');\n}\n\nfunction equalJson(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== typeof b || a === null || b === null) return false;\n if (Array.isArray(a) || Array.isArray(b)) {\n return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, i) => equalJson(item, b[i]));\n }\n if (typeof a === 'object' && typeof b === 'object') {\n const ar = a as Record<string, unknown>;\n const br = b as Record<string, unknown>;\n const ak = Object.keys(ar).sort();\n const bk = Object.keys(br).sort();\n return ak.length === bk.length && ak.every((key, i) => key === bk[i] && equalJson(ar[key], br[key]));\n }\n return false;\n}\n\nfunction matchesType(value: unknown, type: string): boolean {\n switch (type) {\n case 'null': return value === null;\n case 'boolean': return typeof value === 'boolean';\n case 'object': return typeof value === 'object' && value !== null && !Array.isArray(value);\n case 'array': return Array.isArray(value);\n case 'string': return typeof value === 'string';\n case 'number': return typeof value === 'number' && Number.isFinite(value);\n case 'integer': return typeof value === 'number' && Number.isInteger(value);\n default: return true;\n }\n}\n\nfunction validate(value: unknown, schema: unknown, path: readonly (string | number)[]): JsonSchemaValidationIssue[] {\n if (schema === true || schema === undefined) return [];\n if (schema === false) return [{ path, message: label(path) + ' is not allowed by the schema' }];\n if (typeof schema !== 'object' || schema === null || Array.isArray(schema)) return [];\n const s = schema as Record<string, unknown>;\n const issues: JsonSchemaValidationIssue[] = [];\n\n if (s['nullable'] === true && value === null) return issues;\n\n const type = s['type'];\n if (typeof type === 'string' && !matchesType(value, type)) {\n return [{ path, message: label(path) + ' must be ' + type }];\n }\n if (Array.isArray(type) && !type.some((t) => typeof t === 'string' && matchesType(value, t))) {\n return [{ path, message: label(path) + ' must match one of: ' + type.join(', ') }];\n }\n\n if ('const' in s && !equalJson(value, s['const'])) issues.push({ path, message: label(path) + ' must equal the schema const value' });\n const enumValues = s['enum'];\n if (Array.isArray(enumValues) && !enumValues.some((item) => equalJson(value, item))) issues.push({ path, message: label(path) + ' must be one of the allowed enum values' });\n\n const anyOf = s['anyOf'];\n if (Array.isArray(anyOf) && !anyOf.some((candidate) => validate(value, candidate, path).length === 0)) issues.push({ path, message: label(path) + ' must satisfy at least one anyOf schema' });\n const oneOf = s['oneOf'];\n if (Array.isArray(oneOf)) {\n const matches = oneOf.filter((candidate) => validate(value, candidate, path).length === 0).length;\n if (matches !== 1) issues.push({ path, message: label(path) + ' must satisfy exactly one oneOf schema' });\n }\n const allOf = s['allOf'];\n if (Array.isArray(allOf)) for (const candidate of allOf) issues.push(...validate(value, candidate, path));\n if ('not' in s && validate(value, s['not'], path).length === 0) issues.push({ path, message: label(path) + ' must not satisfy the not schema' });\n\n if (typeof value === 'string') {\n const min = s['minLength'];\n const max = s['maxLength'];\n if (typeof min === 'number' && value.length < min) issues.push({ path, message: label(path) + ' must have at least ' + min + ' characters' });\n if (typeof max === 'number' && value.length > max) issues.push({ path, message: label(path) + ' must have at most ' + max + ' characters' });\n if (typeof s['pattern'] === 'string') {\n try { if (!new RegExp(s['pattern']).test(value)) issues.push({ path, message: label(path) + ' does not match the required pattern' }); }\n catch { /* malformed provider regex; do not reject otherwise valid arguments */ }\n }\n }\n\n if (typeof value === 'number' && Number.isFinite(value)) {\n const numericRules: readonly [string, (n: number, bound: number) => boolean, string][] = [\n ['minimum', (n, b) => n >= b, 'must be greater than or equal to'],\n ['maximum', (n, b) => n <= b, 'must be less than or equal to'],\n ['exclusiveMinimum', (n, b) => n > b, 'must be greater than'],\n ['exclusiveMaximum', (n, b) => n < b, 'must be less than'],\n ];\n for (const [keyword, check, phrase] of numericRules) {\n const bound = s[keyword];\n if (typeof bound === 'number' && !check(value, bound)) issues.push({ path, message: label(path) + ' ' + phrase + ' ' + bound });\n }\n const multipleOf = s['multipleOf'];\n if (typeof multipleOf === 'number' && multipleOf > 0) {\n const quotient = value / multipleOf;\n if (Math.abs(quotient - Math.round(quotient)) > 1e-12) issues.push({ path, message: label(path) + ' must be a multiple of ' + multipleOf });\n }\n }\n\n if (Array.isArray(value)) {\n const min = s['minItems'];\n const max = s['maxItems'];\n if (typeof min === 'number' && value.length < min) issues.push({ path, message: label(path) + ' must contain at least ' + min + ' items' });\n if (typeof max === 'number' && value.length > max) issues.push({ path, message: label(path) + ' must contain at most ' + max + ' items' });\n if (s['uniqueItems'] === true) {\n for (let i = 0; i < value.length; i += 1) if (value.slice(0, i).some((previous) => equalJson(previous, value[i]))) { issues.push({ path: [...path, i], message: label([...path, i]) + ' must be unique' }); break; }\n }\n if ('items' in s) value.forEach((item, i) => issues.push(...validate(item, s['items'], [...path, i])));\n if (Array.isArray(s['prefixItems'])) s['prefixItems'].forEach((itemSchema, i) => { if (i < value.length) issues.push(...validate(value[i], itemSchema, [...path, i])); });\n }\n\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n const object = value as Record<string, unknown>;\n const required = s['required'];\n if (Array.isArray(required)) for (const key of required) if (typeof key === 'string' && !(key in object)) issues.push({ path: [...path, key], message: label([...path, key]) + ' is required' });\n const properties = s['properties'];\n if (typeof properties === 'object' && properties !== null && !Array.isArray(properties)) {\n const propertySchemas = properties as Record<string, unknown>;\n for (const [key, propertySchema] of Object.entries(propertySchemas)) if (key in object) issues.push(...validate(object[key], propertySchema, [...path, key]));\n const additional = s['additionalProperties'];\n for (const key of Object.keys(object)) {\n if (key in propertySchemas) continue;\n if (additional === false) issues.push({ path: [...path, key], message: label([...path, key]) + ' is not allowed' });\n else if (additional !== true && additional !== undefined) issues.push(...validate(object[key], additional, [...path, key]));\n }\n }\n const min = s['minProperties'];\n const max = s['maxProperties'];\n if (typeof min === 'number' && Object.keys(object).length < min) issues.push({ path, message: label(path) + ' must contain at least ' + min + ' properties' });\n if (typeof max === 'number' && Object.keys(object).length > max) issues.push({ path, message: label(path) + ' must contain at most ' + max + ' properties' });\n }\n\n return issues;\n}\n\nexport function validateJsonSchema(value: unknown, schema: unknown): readonly JsonSchemaValidationIssue[] {\n return validate(value, schema, []);\n}","/**\n * Converts MCP tools into Ollama-compatible tools.\n */\n\nimport { z } from 'zod';\nimport { validateJsonSchema } from './json-schema.js';\nimport { OllamaMcpError } from '../errors.js';\nimport type { AnyTool } from '../tools/types.js';\nimport type { ToolRegistry } from '../tools/registry.js';\nimport type {\n McpClientLike,\n McpListToolsParams,\n McpRequestOptions,\n McpToolCallResult,\n McpToolDescriptor,\n} from './types.js';\nimport type { ToolDefinition, ToolProperty } from '../types.js';\n\nexport type McpToolResultMode = 'text' | 'structured';\n\nexport interface LoadMcpToolsOptions {\n readonly namePrefix?: string | undefined;\n /** Maximum number of paginated tools/list responses to traverse. */\n readonly maxPages?: number | undefined;\n /**\n * Return MCP's raw CallToolResult to programmatic callers instead of the legacy\n * model-oriented text representation. The default preserves existing behavior.\n */\n readonly resultMode?: McpToolResultMode | undefined;\n /** Validate structuredContent against a tool's MCP outputSchema. Defaults to true. */\n readonly validateOutputSchema?: boolean | undefined;\n /** Invoke optional task-capable tools as legacy MCP tasks when supported. */\n readonly taskMode?: 'required-only' | 'all-supported' | undefined;\n /** Requested lifetime for legacy task-augmented tool calls, in milliseconds. */\n readonly taskTtlMs?: number | undefined;\n}\n\nfunction resolveMaxPages(options: LoadMcpToolsOptions): number {\n const maxPages = options.maxPages ?? 64;\n if (!Number.isInteger(maxPages) || maxPages <= 0) {\n throw new RangeError('MCP maxPages must be a positive integer');\n }\n return maxPages;\n}\n\nexport async function listAllMcpTools(\n mcpClient: McpClientLike,\n options: LoadMcpToolsOptions = {},\n signal?: AbortSignal,\n): Promise<McpToolDescriptor[]> {\n const maxPages = resolveMaxPages(options);\n const tools: McpToolDescriptor[] = [];\n const seenCursors = new Set<string>();\n let cursor: string | undefined;\n\n for (let pageNumber = 1; pageNumber <= maxPages; pageNumber += 1) {\n const params: McpListToolsParams | undefined =\n cursor !== undefined ? { cursor } : undefined;\n const requestOptions: McpRequestOptions | undefined =\n signal !== undefined ? { signal } : undefined;\n const page = await mcpClient.listTools(params, requestOptions);\n const pageNames = new Set<string>();\n for (const tool of page.tools) {\n if (pageNames.has(tool.name)) {\n throw new OllamaMcpError(\n `MCP tools/list returned duplicate tool name \"${tool.name}\"`,\n { mcpMethod: 'listTools', toolName: tool.name },\n );\n }\n pageNames.add(tool.name);\n if (tools.some((existing) => existing.name === tool.name)) {\n throw new OllamaMcpError(\n `MCP tools/list returned duplicate tool name \"${tool.name}\" across pages`,\n { mcpMethod: 'listTools', toolName: tool.name },\n );\n }\n }\n tools.push(...page.tools);\n\n if (page.nextCursor === undefined) {\n return tools;\n }\n if (seenCursors.has(page.nextCursor)) {\n throw new Error('MCP tools/list returned a repeated nextCursor');\n }\n seenCursors.add(page.nextCursor);\n cursor = page.nextCursor;\n }\n\n throw new Error('MCP tools/list exceeded maxPages (' + maxPages + ')');\n}\n\nfunction formatMcpToolResult(result: McpToolCallResult): string {\n if ('resultType' in result || 'task' in result) {\n return JSON.stringify(result) ?? String(result);\n }\n\n const parts = result.content.map((block) => {\n if (block.type === 'text' && typeof block.text === 'string') {\n return block.text;\n }\n try {\n return JSON.stringify(block);\n } catch {\n return `[${block.type}]`;\n }\n });\n\n if (result.structuredContent !== undefined) {\n try {\n parts.push(JSON.stringify(result.structuredContent));\n } catch {\n // Preserve the regular content if structuredContent cannot be serialized.\n }\n }\n\n if (result.isError) {\n parts.unshift('[MCP tool error]');\n }\n\n return parts.join('\\n');\n}\n\nfunction supportsTaskCalls(mcpClient: McpClientLike): boolean {\n return mcpClient.getServerCapabilities?.()?.tasks?.requests?.tools?.call !== undefined;\n}\n\nfunction shouldCallAsTask(\n descriptor: McpToolDescriptor,\n options: LoadMcpToolsOptions,\n serverSupportsTasks: boolean,\n): boolean {\n const support = descriptor.execution?.taskSupport;\n if (support === 'required' && !serverSupportsTasks) {\n throw new OllamaMcpError(\n `MCP tool \"${descriptor.name}\" requires task execution, but the server does not advertise tasks.requests.tools.call`,\n { mcpMethod: 'callTool', toolName: descriptor.name },\n );\n }\n if (!serverSupportsTasks || support === undefined || support === 'forbidden') return false;\n return support === 'required' || options.taskMode === 'all-supported';\n}\n\nfunction createInputValidator(inputSchema: Record<string, unknown>): z.ZodType<Record<string, unknown>> {\n return z.custom<Record<string, unknown>>().superRefine((value, ctx) => {\n const issues = validateJsonSchema(value, inputSchema);\n for (const issue of issues) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [...issue.path],\n message: issue.message,\n });\n }\n });\n}\n\nfunction convertMcpDescriptorToTool(\n descriptor: McpToolDescriptor,\n mcpClient: McpClientLike,\n namePrefix = '',\n resultMode: McpToolResultMode = 'text',\n validateOutputSchema = true,\n executeAsTask = false,\n taskTtlMs?: number,\n): AnyTool {\n const toolName = `${namePrefix}${descriptor.name}`;\n const inputSchema = descriptor.inputSchema ?? { type: 'object', properties: {} };\n const properties = (inputSchema['properties'] ?? {}) as Record<string, ToolProperty>;\n const required = (inputSchema['required'] ?? []) as string[];\n const parameters = {\n ...inputSchema,\n type: 'object' as const,\n properties,\n ...(required.length > 0 ? { required } : {}),\n } as ToolDefinition['function']['parameters'];\n\n return {\n name: toolName,\n description: descriptor.description ?? '',\n schema: createInputValidator(inputSchema),\n execute: async (args: Record<string, unknown>, context: { readonly signal?: AbortSignal | undefined }) => {\n try {\n const result = await mcpClient.callTool(\n {\n name: descriptor.name,\n arguments: args,\n ...(executeAsTask\n ? { task: taskTtlMs !== undefined ? { ttl: taskTtlMs } : {} }\n : {}),\n },\n {\n ...(context.signal !== undefined ? { signal: context.signal } : {}),\n allowInputRequired: true,\n },\n );\n\n if (\n !('resultType' in result) &&\n !('task' in result) &&\n validateOutputSchema &&\n descriptor.outputSchema !== undefined &&\n result.structuredContent !== undefined\n ) {\n const issues = validateJsonSchema(result.structuredContent, descriptor.outputSchema);\n if (issues.length > 0) {\n throw new OllamaMcpError(\n `MCP tool \"${descriptor.name}\" returned structuredContent that violates outputSchema`,\n {\n mcpMethod: 'tools/call',\n toolName: descriptor.name,\n issues,\n },\n );\n }\n }\n\n // MCP tool failures are ordinary CallToolResult values, not transport failures.\n // Keep the result model-readable so the agent can observe the error and recover.\n return resultMode === 'structured' ? result : formatMcpToolResult(result);\n } catch (err) {\n if (err instanceof OllamaMcpError) throw err;\n throw new OllamaMcpError(`Failed calling MCP tool \"${descriptor.name}\"`, {\n mcpMethod: 'callTool',\n toolName: descriptor.name,\n cause: err,\n });\n }\n },\n definition: {\n type: 'function',\n function: {\n name: toolName,\n description: descriptor.description ?? '',\n parameters,\n },\n },\n };\n}\n\nexport async function loadMcpTools(\n mcpClient: McpClientLike,\n options: LoadMcpToolsOptions = {},\n signal?: AbortSignal,\n): Promise<AnyTool[]> {\n try {\n if (\n options.taskTtlMs !== undefined &&\n (!Number.isFinite(options.taskTtlMs) || options.taskTtlMs <= 0)\n ) {\n throw new RangeError('MCP taskTtlMs must be a positive finite number');\n }\n const tools = await listAllMcpTools(mcpClient, options, signal);\n const serverSupportsTasks = supportsTaskCalls(mcpClient);\n return tools.map((tool) => {\n const taskCall = shouldCallAsTask(\n tool,\n options,\n serverSupportsTasks,\n );\n return convertMcpDescriptorToTool(\n tool,\n mcpClient,\n options.namePrefix,\n options.resultMode,\n options.validateOutputSchema ?? true,\n taskCall,\n options.taskTtlMs,\n );\n });\n } catch (err) {\n if (err instanceof OllamaMcpError) throw err;\n throw new OllamaMcpError('Failed listing MCP tools from client', {\n mcpMethod: 'listTools',\n cause: err,\n });\n }\n}\n\nexport async function registerMcpTools(\n registry: ToolRegistry,\n mcpClient: McpClientLike,\n options: LoadMcpToolsOptions = {},\n signal?: AbortSignal,\n): Promise<void> {\n const tools = await loadMcpTools(mcpClient, options, signal);\n registry.registerMany(tools);\n}\n","/**\n * First-class MCP-to-Ollama bridge.\n *\n * The core package deliberately stays transport-agnostic and Edge-compatible. Connect\n * to an MCP server with an MCP client implementation (stdio, Streamable HTTP, etc.)\n * then pass that client to this bridge.\n */\nimport type { ToolDefinition } from '../types.js';\nimport type { ToolRegistry } from '../tools/registry.js';\nimport { OllamaMcpError } from '../errors.js';\nimport { z } from 'zod';\nimport { listAllMcpTools, loadMcpTools, type LoadMcpToolsOptions } from './mcp-tools.js';\nimport type {\n McpClientLike,\n McpCallToolResult,\n McpTask,\n McpTaskMethod,\n McpToolDescriptor,\n} from './types.js';\n\nexport type McpBridgeOptions = LoadMcpToolsOptions;\n\nconst taskSchema = z.object({\n taskId: z.string(),\n status: z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']),\n statusMessage: z.string().optional(),\n createdAt: z.string(),\n lastUpdatedAt: z.string(),\n ttl: z.number().optional(),\n pollInterval: z.number().optional(),\n}).passthrough();\nconst callToolResultSchema = z.custom<McpCallToolResult>(\n (value) =>\n typeof value === 'object' &&\n value !== null &&\n 'content' in value &&\n Array.isArray(value.content),\n);\n\nexport class McpBridge {\n constructor(\n private readonly client: McpClientLike,\n private readonly options: McpBridgeOptions = {},\n ) {}\n\n static toOllamaTools(\n tools: readonly McpToolDescriptor[],\n options: McpBridgeOptions = {},\n ): ToolDefinition[] {\n const prefix = options.namePrefix ?? '';\n return tools.map((tool) => ({\n type: 'function',\n function: {\n name: prefix + tool.name,\n description: tool.description ?? '',\n parameters: {\n ...(tool.inputSchema ?? { type: 'object', properties: {} }),\n type: 'object' as const,\n properties: ((tool.inputSchema ?? {})['properties'] ?? {}) as ToolDefinition['function']['parameters']['properties'],\n } as ToolDefinition['function']['parameters'],\n },\n }));\n }\n\n async listTools(signal?: AbortSignal): Promise<readonly McpToolDescriptor[]> {\n return listAllMcpTools(this.client, this.options, signal);\n }\n\n async definitions(signal?: AbortSignal): Promise<ToolDefinition[]> {\n return McpBridge.toOllamaTools(await this.listTools(signal), this.options);\n }\n\n async loadTools(signal?: AbortSignal) {\n return loadMcpTools(this.client, this.options, signal);\n }\n\n async register(registry: ToolRegistry, signal?: AbortSignal): Promise<void> {\n await registry.registerMany(await this.loadTools(signal));\n }\n\n /** Refreshes the current MCP tool catalog into an existing registry without clearing local tools. */\n async refresh(registry: ToolRegistry, signal?: AbortSignal): Promise<void> {\n await registry.registerMany(await this.loadTools(signal));\n }\n\n /** Fetches one legacy MCP task's current status without starting a polling loop. */\n async getTaskStatus(taskId: string, signal?: AbortSignal): Promise<McpTask> {\n return this.requestTask(\n 'tasks/get',\n taskId,\n taskSchema,\n signal,\n );\n }\n\n /** Retrieves a completed legacy MCP task's result. */\n async getTaskResult(taskId: string, signal?: AbortSignal): Promise<McpCallToolResult> {\n return this.requestTask(\n 'tasks/result',\n taskId,\n callToolResultSchema,\n signal,\n );\n }\n\n /** Cancels one legacy MCP task. */\n async cancelTask(taskId: string, signal?: AbortSignal): Promise<McpTask> {\n return this.requestTask(\n 'tasks/cancel',\n taskId,\n taskSchema,\n signal,\n );\n }\n\n private requestTask<T>(\n method: McpTaskMethod,\n taskId: string,\n resultSchema: z.ZodType<T>,\n signal?: AbortSignal,\n ): Promise<T> {\n if (this.client.request === undefined) {\n throw new OllamaMcpError(\n `MCP client does not support ${method} requests`,\n { mcpMethod: method },\n );\n }\n return this.client.request(\n { method, params: { taskId } },\n resultSchema,\n signal !== undefined ? { signal } : undefined,\n );\n }\n}\n","/**\n * Lightweight frontmatter parser for SKILL.md files.\n */\n\nimport { OllamaSkillInvalidError } from '../errors.js';\nimport type { SkillFrontmatter } from './types.js';\n\nexport interface ParsedFrontmatter {\n readonly frontmatter: SkillFrontmatter;\n readonly body: string;\n}\n\nfunction parseYamlValue(raw: string): unknown {\n const trimmed = raw.trim();\n if (trimmed === 'true') return true;\n if (trimmed === 'false') return false;\n if (!Number.isNaN(Number(trimmed)) && trimmed !== '') return Number(trimmed);\n if (\n (trimmed.startsWith('\"') && trimmed.endsWith('\"')) ||\n (trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\"))\n ) {\n return trimmed.slice(1, -1);\n }\n return trimmed;\n}\n\nfunction parseYamlBlock(yamlText: string): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n const lines = yamlText.split('\\n');\n let currentKey: string | undefined;\n let currentList: unknown[] | undefined;\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n if (trimmed.startsWith('- ') && currentKey) {\n if (!currentList) {\n currentList = [];\n result[currentKey] = currentList;\n }\n currentList.push(parseYamlValue(trimmed.slice(2)));\n continue;\n }\n\n currentList = undefined;\n const colonIndex = line.indexOf(':');\n if (colonIndex > 0) {\n const key = line.slice(0, colonIndex).trim();\n const valStr = line.slice(colonIndex + 1).trim();\n currentKey = key;\n if (valStr.length > 0) {\n result[key] = parseYamlValue(valStr);\n }\n }\n }\n\n return result;\n}\n\nexport function parseFrontmatter(source: string, path = ''): ParsedFrontmatter {\n const match = source.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/);\n if (!match) {\n throw new OllamaSkillInvalidError('Missing YAML frontmatter delimiters (---)', {\n skillName: path || 'unknown',\n path,\n });\n }\n\n const rawYaml = match[1] ?? '';\n const body = match[2]?.trim() ?? '';\n const parsed = parseYamlBlock(rawYaml);\n\n if (!parsed['name'] || typeof parsed['name'] !== 'string') {\n throw new OllamaSkillInvalidError('Frontmatter missing required string \"name\"', {\n skillName: String(parsed['name'] ?? 'unknown'),\n path,\n });\n }\n if (!parsed['description'] || typeof parsed['description'] !== 'string') {\n throw new OllamaSkillInvalidError('Frontmatter missing required string \"description\"', {\n skillName: parsed['name'],\n path,\n });\n }\n\n return {\n frontmatter: parsed as unknown as SkillFrontmatter,\n body,\n };\n}\n","/**\n * Skill composition and context injection.\n */\n\nimport type { Message } from '../types.js';\nimport type { ToolRegistry } from '../tools/registry.js';\nimport type { Skill } from './types.js';\n\nexport interface ApplySkillOptions {\n readonly messages: readonly Message[];\n readonly tools?: ToolRegistry;\n}\n\nexport interface AppliedSkillResult {\n readonly messages: readonly Message[];\n readonly tools?: ToolRegistry;\n}\n\n/**\n * Injects a skill's body into messages as a system prompt and applies allowed tool filters.\n */\nexport function applySkill(skill: Skill, options: ApplySkillOptions): AppliedSkillResult {\n const systemPrompt = `[Skill: ${skill.name}]\\n${skill.description}\\n\\n${skill.body}`;\n const messages = [...options.messages];\n const systemIndex = messages.findIndex((m) => m.role === 'system');\n\n if (systemIndex >= 0) {\n const existing = messages[systemIndex];\n if (existing) {\n messages[systemIndex] = {\n role: 'system',\n content: `${existing.content}\\n\\n${systemPrompt}`,\n };\n }\n } else {\n messages.unshift({ role: 'system', content: systemPrompt });\n }\n\n return {\n messages,\n ...(options.tools !== undefined ? { tools: options.tools } : {}),\n };\n}\n","/**\n * Multi-turn tool execution loop agent.\n */\n\nimport {\n OllamaAgentMaxIterationsError,\n OllamaAgentMaxToolCallsError,\n OllamaIncompatibleModelError,\n} from '../errors.js';\nimport {\n withSpan,\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_OLLAMA_AGENT_MAX_ITERATIONS,\n ATTR_OLLAMA_AGENT_ITERATION,\n GEN_AI_SYSTEM_OLLAMA,\n} from '../telemetry/index.js';\nimport { ensureToolCallIds } from '../tools/tool-call-id.js';\nimport type { ModelCapabilities } from '../capabilities/capabilities.js';\nimport type { Message, ModelOptions, ThinkValue, ToolDefinition } from '../types.js';\nimport type { ToolRegistry } from '../tools/registry.js';\nimport type { AgentConfig, AgentHooks, AgentResult, AgentRunInput, AgentTurn } from './types.js';\n\nexport interface AgentChatClient {\n capabilities?:\n | ((model: string, signal?: AbortSignal) => Promise<ModelCapabilities>)\n | undefined;\n chat(request: {\n readonly model: string;\n readonly messages: readonly Message[];\n readonly tools?: readonly ToolDefinition[] | undefined;\n readonly options?: ModelOptions | undefined;\n readonly think?: ThinkValue | undefined;\n readonly stream?: false | undefined;\n readonly signal?: AbortSignal | undefined;\n }): Promise<{ readonly message: Message }>;\n}\n\n/**\n * Runs a multi-turn `chat` + tool-execution loop until the model responds without\n * requesting further tool calls, or `maxIterations` is exceeded. Tool calls within a\n * single turn are handed to `ToolRegistry.executeToolCalls` and their results are\n * appended to history in the same order the model requested them. Native Ollama tool-result\n * messages use `tool_name` on the wire; the SDK-generated `toolCallId` remains execution\n * metadata and is not sent to Ollama.\n * `Agent` assigns ids defensively even when `AgentChatClient` isn't `OllamaClient` (e.g. a\n * custom/test implementation), so this guarantee holds regardless of which chat client is\n * supplied.\n */\nexport class Agent {\n private readonly client: AgentChatClient;\n private readonly tools?: ToolRegistry | undefined;\n private readonly maxIterations: number;\n private readonly maxToolCalls?: number | undefined;\n private readonly hooks?: AgentHooks | undefined;\n private readonly validateToolCapability: boolean;\n private readonly toolContextSize: number;\n\n constructor(client: AgentChatClient, config: AgentConfig = {}) {\n this.client = client;\n this.tools = config.tools;\n this.maxIterations = config.maxIterations ?? 10;\n this.maxToolCalls = config.maxToolCalls;\n this.hooks = config.hooks;\n if (this.maxToolCalls !== undefined && (!Number.isInteger(this.maxToolCalls) || this.maxToolCalls < 0)) {\n throw new RangeError('Agent maxToolCalls must be a non-negative integer');\n }\n this.validateToolCapability = config.validateToolCapability ?? true;\n this.toolContextSize = config.toolContextSize ?? 32768;\n if (!Number.isInteger(this.toolContextSize) || this.toolContextSize <= 0) {\n throw new RangeError('Agent toolContextSize must be a positive integer');\n }\n }\n\n run(input: AgentRunInput): Promise<AgentResult> {\n return withSpan(\n `invoke_agent ${input.model}`,\n {\n [ATTR_GEN_AI_SYSTEM]: GEN_AI_SYSTEM_OLLAMA,\n [ATTR_GEN_AI_OPERATION_NAME]: 'invoke_agent',\n [ATTR_GEN_AI_REQUEST_MODEL]: input.model,\n [ATTR_OLLAMA_AGENT_MAX_ITERATIONS]: this.maxIterations,\n },\n () => this.runLoop(input),\n );\n }\n\n private async runLoop(input: AgentRunInput): Promise<AgentResult> {\n const history: Message[] = [...input.messages];\n const turns: AgentTurn[] = [];\n const toolDefs = this.tools?.definitions();\n const hasTools = toolDefs !== undefined && toolDefs.length > 0;\n let capabilities: ModelCapabilities | undefined;\n\n if (hasTools && this.validateToolCapability && this.client.capabilities) {\n capabilities = await this.client.capabilities(input.model, input.signal);\n if (!capabilities.supportsTools) {\n throw new OllamaIncompatibleModelError(\n `Model \"${input.model}\" does not advertise the \"tools\" capability.`,\n {\n model: input.model,\n capability: 'tools',\n reportedCapabilities: capabilities.reported,\n },\n );\n }\n }\n\n const shouldAutoSizeContext =\n hasTools &&\n this.validateToolCapability &&\n capabilities !== undefined &&\n input.options?.num_ctx === undefined;\n\n const effectiveOptions = shouldAutoSizeContext\n ? {\n ...(input.options ?? {}),\n num_ctx: Math.min(\n this.toolContextSize,\n capabilities?.contextLength ?? this.toolContextSize,\n ),\n }\n : input.options;\n\n let toolCallsExecuted = 0;\n\n for (let iteration = 1; iteration <= this.maxIterations; iteration++) {\n const outcome = await withSpan(\n 'ollama.agent.turn',\n { [ATTR_OLLAMA_AGENT_ITERATION]: iteration },\n async () => {\n this.hooks?.onTurnStart?.(iteration);\n\n const response = await this.client.chat({\n model: input.model,\n messages: history,\n ...(toolDefs !== undefined ? { tools: toolDefs } : {}),\n ...(effectiveOptions !== undefined ? { options: effectiveOptions } : {}),\n ...(input.think !== undefined ? { think: input.think } : {}),\n stream: false,\n ...(input.signal !== undefined ? { signal: input.signal } : {}),\n });\n\n const rawToolCalls = response.message.tool_calls;\n const toolCalls = ensureToolCallIds(rawToolCalls);\n const assistantMessage: Message =\n toolCalls === rawToolCalls\n ? response.message\n : { ...response.message, tool_calls: toolCalls };\n history.push(assistantMessage);\n\n if (!toolCalls || toolCalls.length === 0 || !this.tools) {\n const finalTurn: AgentTurn = { iteration, message: assistantMessage };\n turns.push(finalTurn);\n this.hooks?.onTurnEnd?.(finalTurn);\n return { done: true as const, finalMessage: assistantMessage };\n }\n\n if (this.maxToolCalls !== undefined && toolCallsExecuted + toolCalls.length > this.maxToolCalls) {\n throw new OllamaAgentMaxToolCallsError(\n `Agent exceeded max tool calls (${this.maxToolCalls})`,\n { maxToolCalls: this.maxToolCalls, toolCallsExecuted },\n );\n }\n\n for (const tc of toolCalls) {\n this.hooks?.onToolCallStart?.(tc);\n }\n\n const toolResults = await this.tools.executeToolCalls(toolCalls, {\n signal: input.signal,\n });\n toolCallsExecuted += toolCalls.length;\n\n for (const res of toolResults) {\n this.hooks?.onToolCallEnd?.(res);\n history.push({\n role: 'tool',\n tool_name: res.toolName,\n content: res.outputString,\n });\n }\n\n const turn: AgentTurn = { iteration, message: assistantMessage, toolCalls, toolResults };\n turns.push(turn);\n this.hooks?.onTurnEnd?.(turn);\n return { done: false as const };\n },\n );\n\n if (outcome.done) {\n return { finalMessage: outcome.finalMessage, turns, totalIterations: iteration };\n }\n }\n\n throw new OllamaAgentMaxIterationsError(\n `Agent exceeded max iterations (${this.maxIterations}) without converging`,\n { maxIterations: this.maxIterations },\n );\n }\n}\n","/**\n * Ergonomic System One types — key-safe generics on top of the generated\n * contract models.\n *\n * The generated `SystemOneRequest` and `SystemOneResponse` (in\n * `src/generated/models/`) use `Record<string, ...>` for the\n * questions/answers maps. That's structurally correct but loses the\n * connection between the question names the caller sends and the answer\n * names they receive back — `response.answers.someRandomKey` would\n * compile even though the caller never asked that question.\n *\n * This file adds a generic layer:\n *\n * ```ts\n * const result = await ollama.systemOne({\n * model: 'tev1:4b',\n * state: { ticket: 'charged twice' },\n * questions: {\n * intent: { type: 'choice', ... },\n * urgent: { type: 'noul', ... },\n * },\n * });\n *\n * // Key-safe: 'intent' and 'urgent' are the only valid keys.\n * result.answers.intent // ✓ SystemOneAnswer\n * result.answers.urgent // ✓ SystemOneAnswer\n * result.answers.typo // ✗ TypeScript error\n * ```\n *\n * The generic is purely a compile-time wrapper — the runtime behavior is\n * unchanged. The generated types remain the canonical contract; these\n * types are an SDK-level convenience that OpenAPI cannot express.\n *\n * Wave 13.\n */\n\n// Re-export the concrete generated types that the OpenAPI source defines\n// as named schemas.\n//\n// Each type is imported directly from its own model file (NOT the\n// `./generated/models/index.js` barrel) to avoid the circular chunk\n// dependency Rollup warned about during `tsup` builds (the barrel\n// `index.js` re-exports the same files this module imports, so going\n// through it makes `system-one.ts` and `generated/models/index.ts`\n// mutually dependent). The barrel still exists for downstream\n// consumers; this internal-only import path sidesteps the cycle\n// without changing the public surface.\nexport type { SystemOneContent } from './generated/models/SystemOneContent.js';\nexport type {\n SystemOneRequest as SystemOneRequestBase,\n} from './generated/models/SystemOneRequest.js';\nexport type {\n SystemOneResponse as SystemOneResponseBase,\n} from './generated/models/SystemOneResponse.js';\nexport type { SystemOneChoiceQuestion } from './generated/models/SystemOneChoiceQuestion.js';\nexport type { SystemOneNoulQuestion } from './generated/models/SystemOneNoulQuestion.js';\nexport type { SystemOneScoreQuestion } from './generated/models/SystemOneScoreQuestion.js';\nexport type { SystemOneChoiceAnswer } from './generated/models/SystemOneChoiceAnswer.js';\nexport type { SystemOneNoulAnswer } from './generated/models/SystemOneNoulAnswer.js';\nexport type { SystemOneScoreAnswer } from './generated/models/SystemOneScoreAnswer.js';\nexport type { SystemOneProbabilities } from './generated/models/SystemOneProbabilities.js';\nexport type { SystemOneConfidence } from './generated/models/SystemOneConfidence.js';\n\nimport type { SystemOneChoiceQuestion } from './generated/models/SystemOneChoiceQuestion.js';\nimport type { SystemOneNoulQuestion } from './generated/models/SystemOneNoulQuestion.js';\nimport type { SystemOneScoreQuestion } from './generated/models/SystemOneScoreQuestion.js';\nimport type { SystemOneChoiceAnswer } from './generated/models/SystemOneChoiceAnswer.js';\nimport type { SystemOneNoulAnswer } from './generated/models/SystemOneNoulAnswer.js';\nimport type { SystemOneScoreAnswer } from './generated/models/SystemOneScoreAnswer.js';\nimport type {\n SystemOneRequest as SystemOneRequestBase,\n} from './generated/models/SystemOneRequest.js';\nimport type {\n SystemOneResponse as SystemOneResponseBase,\n} from './generated/models/SystemOneResponse.js';\n\n/**\n * Maximum total request size, in bytes, accepted by `/v1/systemone`\n * when the request body carries a non-empty `images` array.\n *\n * The Ollama server enforces this limit server-side and rejects\n * oversized payloads with HTTP 413. The SDK's runtime also enforces\n * it client-side (see `OllamaRuntime`'s `maxRequestBytesWithImages`\n * handling) so the round-trip is avoided.\n *\n * Without images, the limit is the much smaller\n * {@link MAX_SYSTEM_ONE_REQUEST_BYTES} (64 KiB) — the bumped\n * images-cap exists specifically to accommodate base64-encoded image\n * bytes shared across all questions in a single System One call.\n */\nexport const MAX_SYSTEM_ONE_IMAGES_BYTES = 32 * 1024 * 1024; // 32 MiB\n\n/**\n * Maximum total request size, in bytes, for `/v1/systemone` when no\n * images are attached. The Ollama server caps the JSON-only payload\n * at 64 KiB; the runtime enforces this client-side (see\n * `OllamaRuntime`'s `maxRequestBytes`).\n */\nexport const MAX_SYSTEM_ONE_REQUEST_BYTES = 64 * 1024; // 64 KiB\n\n/**\n * Discriminated union of the three question kinds. The upstream OpenAPI\n * defines this inline as `oneOf` within SystemOneRequest.questions; we\n * reconstruct it as a named type for SDK ergonomics.\n */\nexport type SystemOneQuestion =\n | SystemOneChoiceQuestion\n | SystemOneNoulQuestion\n | SystemOneScoreQuestion;\n\n/**\n * Discriminated union of the three answer kinds. The upstream OpenAPI\n * defines this inline as `oneOf` within SystemOneResponse.answers; we\n * reconstruct it as a named type for SDK ergonomics.\n */\nexport type SystemOneAnswer =\n | SystemOneChoiceAnswer\n | SystemOneNoulAnswer\n | SystemOneScoreAnswer;\n\n/**\n * Token usage for a System One call. The upstream OpenAPI defines this\n * inline within SystemOneResponse; we reconstruct it as a named type\n * for SDK ergonomics. Carries input_tokens and output_tokens (not\n * prompt_tokens/completion_tokens).\n */\nexport interface SystemOneUsage {\n readonly input_tokens: number;\n readonly output_tokens: number;\n}\n\n/** Map of question id → question descriptor. */\nexport type SystemOneQuestions = Record<string, SystemOneQuestion>;\n\n/**\n * Wave 16 (P2): conditional mapping from a question type to its\n * corresponding answer type. This gives compile-time type correlation:\n *\n * choice question → choice answer\n * noul question → noul answer\n * score question → score answer\n *\n * Without this, `SystemOneAnswers<Q>` maps every key to the full\n * `SystemOneAnswer` union, requiring manual narrowing. With this,\n * `result.answers.myChoiceQuestion` is automatically typed as\n * `SystemOneChoiceAnswer`.\n */\nexport type AnswerFor<Q> = Q extends { readonly type: 'choice' }\n ? SystemOneChoiceAnswer\n : Q extends { readonly type: 'noul' }\n ? SystemOneNoulAnswer\n : Q extends { readonly type: 'score' }\n ? SystemOneScoreAnswer\n : SystemOneAnswer;\n\n/**\n * Key-safe answers map: for every question key `K` in `Q`, the response\n * carries the answer type that corresponds to that question's type.\n * Wave 16: now uses `AnswerFor<Q[K]>` for exact type correlation.\n */\nexport type SystemOneAnswers<Q extends SystemOneQuestions = SystemOneQuestions> = {\n readonly [K in keyof Q]: AnswerFor<Q[K]>;\n};\n\n/**\n * Generic System One request. When `Q` is provided, `questions` is typed\n * as `Q` (the caller's specific question map) rather than the loose\n * `Record<string, SystemOneQuestion>`. The response's `answers` will\n * then carry the same keys.\n *\n * The `model`, `state`, `images`, and `keep_alive` fields are inherited\n * from the generated base type unchanged.\n *\n * ## Image support\n *\n * The `images` field accepts up to N base64-encoded images shared by\n * all questions in the request. Total request payload (JSON + images)\n * must remain within {@link MAX_SYSTEM_ONE_IMAGES_BYTES} (32 MiB);\n * requests without images are capped at\n * {@link MAX_SYSTEM_ONE_REQUEST_BYTES} (64 KiB).\n *\n * Use {@link estimateSystemOneRequestBytes} for a client-side pre-flight\n * check before sending a large multi-image batch — the runtime also\n * enforces the limit, but the early check avoids the round-trip when\n * the caller already knows the payload is too large.\n *\n * Requires Clef or Clef Flash with vision weights. URLs and data URLs\n * are NOT supported — pre-encode the bytes to base64 before adding to\n * the array.\n */\nexport interface SystemOneRequest<Q extends SystemOneQuestions = SystemOneQuestions>\n extends Omit<SystemOneRequestBase, 'questions'> {\n readonly questions: Q;\n}\n\n/**\n * Generic System One response. When `Q` is provided, `answers` is typed\n * as `SystemOneAnswers<Q>` — a key-safe map matching the questions the\n * caller asked.\n */\nexport interface SystemOneResponse<Q extends SystemOneQuestions = SystemOneQuestions>\n extends Omit<SystemOneResponseBase, 'answers' | 'usage'> {\n readonly answers: SystemOneAnswers<Q>;\n readonly usage: SystemOneUsage;\n}\n\n/**\n * Estimate the on-the-wire byte size of a System One request body, for\n * pre-flight size validation against {@link MAX_SYSTEM_ONE_REQUEST_BYTES}\n * (no images) or {@link MAX_SYSTEM_ONE_IMAGES_BYTES} (with images).\n *\n * The estimate is conservative: it uses `JSON.stringify` length and\n * assumes UTF-8 encoding. The actual wire size may differ slightly due\n * to server-side JSON normalization (key ordering, whitespace), but the\n * estimate is always within a few percent of the real payload size and\n * is suitable for \"fail fast before sending\" checks.\n *\n * @example\n * ```ts\n * const request: SystemOneRequest = { ... };\n * const bytes = estimateSystemOneRequestBytes(request);\n * const cap = request.images?.length ? MAX_SYSTEM_ONE_IMAGES_BYTES : MAX_SYSTEM_ONE_REQUEST_BYTES;\n * if (bytes > cap) throw new Error(`payload ${bytes}B exceeds cap ${cap}B`);\n * await client.systemOne(request);\n * ```\n */\nexport function estimateSystemOneRequestBytes(\n request: SystemOneRequest | SystemOneRequestBase,\n): number {\n // JSON.stringify is a faithful proxy for what the runtime sends on\n // the wire — see src/transport/http.ts's request() method, which\n // calls JSON.stringify on the body before passing to fetch. UTF-8\n // multi-byte chars (the common case for non-ASCII base64) are counted\n // correctly because String.prototype.length already reflects UTF-16\n // code units; for pure-ASCII payloads (the typical case) the length\n // equals the byte length directly. We err on the side of over-counting\n // so the pre-flight check is conservative.\n return new TextEncoder().encode(JSON.stringify(request)).byteLength;\n}\n"]}
|