@nemesis-oss/ollama-sdk 1.15.0 → 1.17.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 +50 -0
- package/README.md +114 -2
- package/dist/{anthropic-DrDUfbfQ.d.ts → anthropic-AKbXnWJU.d.cts} +1 -1
- package/dist/{anthropic-UeaVjLeP.d.cts → anthropic-CTv2acbj.d.ts} +1 -1
- package/dist/generated-api.d.cts +4 -4
- package/dist/generated-api.d.ts +4 -4
- package/dist/generated-runtime.cjs.map +1 -1
- package/dist/generated-runtime.d.cts +1 -1
- package/dist/generated-runtime.d.ts +1 -1
- package/dist/generated-runtime.js.map +1 -1
- package/dist/index.cjs +207 -33
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +200 -13
- package/dist/index.d.ts +200 -13
- package/dist/index.js +204 -34
- package/dist/index.js.map +1 -1
- package/dist/mcp-generated.d.cts +1 -1
- package/dist/mcp-generated.d.ts +1 -1
- package/dist/{runtime-BIjr5ME4.d.ts → runtime-CFuv7Ifh.d.ts} +29 -1
- package/dist/{runtime-C4RRHqOs.d.cts → runtime-CdZP-N7j.d.cts} +29 -1
- package/dist/skills.cjs.map +1 -1
- package/dist/skills.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/transport/host.ts","../src/config.ts","../src/errors.ts","../src/logger.ts","../src/providers/endpoint-registry.ts","../src/transport/url.ts","../src/middleware.ts","../src/vision.ts","../src/utils.ts","../src/streaming/ndjson.ts","../src/streaming/sse.ts","../src/telemetry/tracer.ts","../src/telemetry/metrics.ts","../src/transport/http.ts","../src/providers/health-check.ts","../src/capabilities/capabilities.ts","../src/context-safety.ts","../src/context-discovery.ts","../src/providers/model-affinity-router.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/embed-batch.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/tools/web-tools.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/draft-benchmark.ts","../src/affinity.ts","../src/system-one.ts"],"names":["message","dispatch","response","check","controller","z","sleep","positiveInt"],"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,IAA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SAAS,8BACd,OAAA,EACQ;AASR,EAAA,OAAO,IAAI,aAAY,CAAE,MAAA,CAAO,KAAK,SAAA,CAAU,OAAO,CAAC,CAAA,CAAE,UAAA;AAC3D","file":"index.js","sourcesContent":["/**\n * Host normalization and credential-scoping helpers for 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\n/**\n * Thrown when the agent's cycle detection fires: the same tool call —\n * identical name **and** identical arguments — would execute more times than\n * `maxRepeatedToolCalls` allows during one run.\n *\n * This is the fail-fast diagnosis for a model stuck in a tool loop (repeatedly\n * calling the same function with the same arguments, never reacting to the\n * results); without it, a looping model only surfaces as a generic\n * {@link OllamaAgentMaxIterationsError} after burning the full iteration\n * budget on wasted calls.\n */\nexport class OllamaAgentToolLoopError extends OllamaClientError {\n /** Name of the tool whose identical call would exceed the repeat budget. */\n readonly toolName: string;\n /** How many times this exact call would have executed including the rejected one. */\n readonly repeatedExecutions: number;\n /** The configured per-signature execution budget. */\n readonly maxRepeatedToolCalls: number;\n /** Canonical `name(args)` signature of the repeated call (very large payloads truncated). */\n readonly signature: string;\n\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n toolName: string;\n repeatedExecutions: number;\n maxRepeatedToolCalls: number;\n signature: string;\n },\n ) {\n super(message, { ...options, code: 'agent_tool_loop_detected', retryable: false });\n this.toolName = options.toolName;\n this.repeatedExecutions = options.repeatedExecutions;\n this.maxRepeatedToolCalls = options.maxRepeatedToolCalls;\n this.signature = options.signature;\n }\n}\n\nexport class OllamaMcpError extends OllamaClientError {\n readonly mcpMethod:\n 'listTools' | 'callTool' | 'tools/call' | 'tasks/get' | 'tasks/result' | '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' | 'callTool' | 'tools/call' | 'tasks/get' | 'tasks/result' | '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';\nimport type { ModelAffinityRoutingOptions } from './model-affinity-router.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 * Dynamic model-affinity routing across endpoints: reorder each request's\n * candidates so endpoints whose `GET /api/ps` shows the requested model already\n * resident in VRAM are tried first — avoiding unload/cold-load swaps on\n * `OLLAMA_MAX_LOADED_MODELS`-bounded daemons. Off unless set.\n *\n * Implemented by `OllamaClient`'s request path (`executeWithFailover` + a\n * TTL-cached `ModelAffinityRouter`), not by this registry — the registry is a\n * pure, HTTP-free data structure and simply ignores this key. See\n * `src/providers/model-affinity-router.ts` and ADR 0028.\n */\n readonly modelAffinity?: ModelAffinityRoutingOptions | 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 URL assembly for the HTTP transport.\n *\n * Ollama is frequently deployed behind a reverse proxy under a path prefix\n * (`https://gateway.internal.corp/ai/ollama`). The transport therefore joins\n * base URLs and request paths by explicit string concatenation — never via\n * `new URL(path, base)`, whose WHATWG semantics discard the base's path\n * segments whenever the path is absolute (`new URL('/api/chat', base)`).\n *\n * {@link joinUrlPath} is the single place that owns the join, so the\n * \"exactly one slash between the base and the path\" invariant holds even if\n * a base URL slips through with a trailing slash or a future call site\n * passes a path without its leading slash.\n */\n\n/**\n * Joins a base URL and a request path with exactly one slash.\n *\n * - Any number of trailing slashes on `baseUrl` and leading slashes on\n * `path` are collapsed, so `https://host/ai/ollama/` + `/api/chat`,\n * `https://host/ai/ollama` + `/api/chat`, and `https://host/ai/ollama`\n * + `api/chat` all produce `https://host/ai/ollama/api/chat` — a proxy\n * mount prefix is always preserved.\n * - A path may carry a query string (`/api/usage?bucket=24h`); it is\n * concatenated untouched after the join.\n * - An empty path yields the base unchanged (trailing slashes stripped).\n */\nexport function joinUrlPath(baseUrl: string, path: string): string {\n const base = baseUrl.replace(/\\/+$/, '');\n const tail = path.replace(/^\\/+/, '');\n if (tail === '') return base;\n if (base === '') return `/${tail}`;\n return `${base}/${tail}`;\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 * - `Uint8Array` — raw image bytes, base64-encoded automatically. Node\n * `Buffer` is a `Uint8Array` subclass, so buffers are accepted everywhere\n * bytes are — without importing Node types into consumer compilations: the\n * published declarations stay free of `@types/node` globals (audit TYP-03).\n */\nexport type VisionInput = string | 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 * Standardized telemetry normalizer — raw nanosecond counters to derived metrics.\n *\n * Ollama reports every duration as an **integer in nanoseconds** on its generation\n * responses (`total_duration`, `load_duration`, `prompt_eval_duration`,\n * `eval_duration` — see the official \"Usage\" documentation), plus token counters\n * (`prompt_eval_count`, `prompt_eval_cached_count`, `eval_count`). Consumers that\n * want milliseconds, tokens/second, or a cache-hit ratio otherwise each reimplement\n * the same division-and-rounding math — this module is that math, once, with the\n * formulas the official docs spell out:\n *\n * - `tokensPerSecond` = `eval_count / (eval_duration / 1e9)` — generation throughput.\n * - `promptTokensPerSecond` = `prompt_eval_count / (prompt_eval_duration / 1e9)` —\n * prompt ingestion (pre-fill) throughput.\n * - `cacheHitRatio` = `prompt_eval_cached_count / (cached + evaluated)` — see the\n * note on {@link FormattedTelemetry.cacheHitRatio} for why the denominator is the\n * *sum*, not `prompt_eval_count` alone.\n *\n * Pure and dependency-free: {@link formatTelemetry} never fetches, never throws, and\n * treats every missing counter as `0` — partial responses (stream final events,\n * older servers without `prompt_eval_cached_count`) format cleanly instead of\n * producing `NaN`/`Infinity`.\n *\n * The input is structural: any response object carrying these optional fields —\n * `GenerateResponse`, `ChatResponse`, the final `GenerateStreamEvent`,\n * `EmbedResponse` — can be passed directly, no picking/plucking required.\n */\n\n/**\n * The raw nanosecond/token counters Ollama attaches to generation responses. Every\n * field is optional because servers report a subset: streaming final events may omit\n * load counters, older builds predate `prompt_eval_cached_count`, and embeddings\n * carry no `eval_count`. Accepts full response objects structurally.\n */\nexport interface RawOllamaMetrics {\n /** Total end-to-end request latency, nanoseconds. */\n readonly total_duration?: number | undefined;\n /** Model cold-load and weight-transfer time into VRAM, nanoseconds. */\n readonly load_duration?: number | undefined;\n /** Prompt tokens freshly evaluated this request (not served from the KV cache). */\n readonly prompt_eval_count?: number | undefined;\n /** Prompt tokens served from the KV prompt cache (prefix reuse). */\n readonly prompt_eval_cached_count?: number | undefined;\n /** Prompt ingestion / pre-fill processing time, nanoseconds. */\n readonly prompt_eval_duration?: number | undefined;\n /** Tokens generated (the response proper). */\n readonly eval_count?: number | undefined;\n /** Token generation time, nanoseconds. */\n readonly eval_duration?: number | undefined;\n}\n\n/** The normalized, human-scale view of one response's {@link RawOllamaMetrics}. */\nexport interface FormattedTelemetry {\n /** `total_duration` in milliseconds, 2 decimals. */\n readonly totalLatencyMs: number;\n /** `load_duration` in milliseconds, 2 decimals — 0 when the model was already resident. */\n readonly modelLoadMs: number;\n /** `prompt_eval_duration` in milliseconds, 2 decimals. */\n readonly promptEvalMs: number;\n /** `eval_duration` in milliseconds, 2 decimals. */\n readonly generationMs: number;\n /** `eval_count / eval_duration` in tokens/second, 1 decimal — 0 when either is absent. */\n readonly tokensPerSecond: number;\n /** `prompt_eval_count / prompt_eval_duration` in tokens/second, 1 decimal. */\n readonly promptTokensPerSecond: number;\n /**\n * Share of prompt tokens served from the KV cache:\n * `cached / (cached + evaluated)`, 3 decimals.\n *\n * The denominator is the **sum**, not `prompt_eval_count` alone, because Ollama\n * reports `prompt_eval_count: 0` on a *full* cache hit — the same house semantics\n * as `ConversationSession`'s `cacheStats.hitRate` (see `src/conversation.ts`). A\n * `cached / prompt_eval_count` formula would report a perfect cache as `0`.\n */\n readonly cacheHitRatio: number;\n}\n\n/** Nanoseconds → milliseconds, rounded to 2 decimals; absent/zero stays `0`. */\nfunction nsToMs(ns: number | undefined): number {\n return ns ? Math.round((ns / 1e6) * 100) / 100 : 0;\n}\n\n/**\n * Derives the standardized metrics summary from one response's raw nanosecond\n * counters. Pure — never throws, never fetches; every missing counter reads as `0`.\n *\n * ```ts\n * const res = await client.chat({ model: 'llama3.2', messages });\n * const t = formatTelemetry(res);\n * console.log(t.tokensPerSecond, 'tok/s |', t.totalLatencyMs, 'ms |',\n * `${Math.round(t.cacheHitRatio * 100)}% prompt cache hit`);\n * ```\n */\nexport function formatTelemetry(raw: RawOllamaMetrics): FormattedTelemetry {\n const evalDurationSec = raw.eval_duration ? raw.eval_duration / 1e9 : 0;\n const promptDurationSec = raw.prompt_eval_duration ? raw.prompt_eval_duration / 1e9 : 0;\n\n const promptEvaluated = raw.prompt_eval_count ?? 0;\n const promptCached = raw.prompt_eval_cached_count ?? 0;\n const promptTotal = promptCached + promptEvaluated;\n\n return {\n totalLatencyMs: nsToMs(raw.total_duration),\n modelLoadMs: nsToMs(raw.load_duration),\n promptEvalMs: nsToMs(raw.prompt_eval_duration),\n generationMs: nsToMs(raw.eval_duration),\n tokensPerSecond:\n evalDurationSec > 0 && raw.eval_count\n ? Math.round((raw.eval_count / evalDurationSec) * 10) / 10\n : 0,\n promptTokensPerSecond:\n promptDurationSec > 0 && promptEvaluated\n ? Math.round((promptEvaluated / promptDurationSec) * 10) / 10\n : 0,\n cacheHitRatio: promptTotal > 0 ? Math.round((promptCached / promptTotal) * 1000) / 1000 : 0,\n };\n}\n","/**\n * Native fetch HTTP transport client for Ollama API.\n */\n\nimport { normalizeBaseUrl } from './host.js';\nimport { joinUrlPath } from './url.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 (\n req: RequestContext,\n ): 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 (context.status !== response.status || !sameHeaders(context.headers, response.headers)) {\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 = joinUrlPath(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 = joinUrlPath(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 = joinUrlPath(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\n/**\n * Scans `/api/show`'s `model_info` for the model's **native** context length\n * (keys are architecture-prefixed: `llama.context_length`,\n * `gemma4.context_length`, …). Also re-exported by `src/context-discovery.ts`\n * as `extractNativeContextLength` for the context-window discovery flow.\n */\nexport function 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 * 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/**\n * Rough per-message framing overhead: role tags, chat-template delimiters.\n */\nexport const MESSAGE_OVERHEAD_TOKENS = 4;\n\nexport function 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 * Dynamic context-window discovery.\n *\n * Guessing context windows (\"it's probably 2048… or 4096?\") is how silent\n * truncation happens. Ollama advertises the real numbers in two places, and\n * they answer *different questions*:\n *\n * - **`GET /api/ps`** reports `context_length` for every currently-running\n * model — the window the runner has **actually allocated**. This is the\n * exact, server-enforced number: it already reflects the model's Modelfile\n * `num_ctx` default (if any) and the memory the runner was able to claim.\n * Only meaningful while the model is loaded.\n * - **`POST /api/show`** exposes two deeper signals in its response:\n * - `model_info[\"<architecture>.context_length\"]` — the model's **native**\n * maximum from its GGUF metadata (e.g. `gemma4.context_length: 131072`).\n * This is the ceiling you could raise `num_ctx` to, not the window you\n * have. The official API examples show a model whose native max is\n * 131072 while its running instance allocated 4096 — a 32× gap.\n * - `parameters` — the Modelfile's serialized option list; a\n * `num_ctx <n>` line (when the model's author set one) is the default\n * window the runner will allocate for this model.\n *\n * `OllamaClient.models.getContextLength()` consults them in precedence order\n * (see {@link resolveContextLength}) and returns every signal it found, so\n * callers can both act on the effective window *now* and know how much\n * headroom exists for raising it.\n */\n\nimport { extractContextLength } from './capabilities/capabilities.js';\nimport { OLLAMA_FALLBACK_CONTEXT_LENGTH } from './context-safety.js';\nimport type { ModelResponse, RequestCancellationOptions } from './types.js';\n\n/** Request shape for {@link ModelsClient.getContextLength}. */\nexport interface ContextDiscoveryRequestOptions extends RequestCancellationOptions {\n /** Model to introspect (tag optional — `\"llama3.1\"` matches `\"llama3.1:latest\"`). */\n readonly model: string;\n /**\n * Skip the `GET /api/ps` lookup — e.g. on cloud endpoints where the local\n * running-models listing isn't meaningful, or when the extra round-trip\n * isn't wanted. Discovery then falls back to `/api/show` signals only.\n */\n readonly skipRunningCheck?: boolean | undefined;\n}\n\n/** Where a discovered context window came from, in precedence order. */\nexport type ContextLengthSource =\n /** `GET /api/ps` — window actually allocated by the running instance (exact). */\n | 'running'\n /** `POST /api/show` `parameters` — Modelfile-authored `num_ctx` default. */\n | 'parameters'\n /** `POST /api/show` `model_info[\"*.context_length\"]` — native GGUF maximum. */\n | 'model-info'\n /** Nothing discoverable — Ollama's conservative unset-`num_ctx` default (2048). */\n | 'fallback';\n\n/** Result of {@link ModelsClient.getContextLength}. */\nexport interface DiscoveredContextLength {\n /**\n * The effective context window to program against, resolved by precedence:\n * `running` (exact, when loaded) → `parameters` (Modelfile default) →\n * `model-info` (native max) → `2048` fallback.\n */\n readonly contextLength: number;\n /** Which source produced {@link contextLength}. */\n readonly source: ContextLengthSource;\n /** Window allocated by the running instance, when the model is loaded and reports it. */\n readonly runningContextLength?: number | undefined;\n /** Modelfile `num_ctx` default from `/api/show`'s `parameters` string, when set. */\n readonly parameterContextLength?: number | undefined;\n /** Native GGUF maximum from `model_info[\"*.context_length\"]`, when reported. */\n readonly nativeContextLength?: number | undefined;\n}\n\n/**\n * Parses `num_ctx <n>` out of `/api/show`'s `parameters` string.\n *\n * The string is the Modelfile's serialized option list — one `name value`\n * pair per line, value separated by whitespace padding, e.g.\n * `\"num_stop 8192\\nnum_ctx 4096\"`. Returns `undefined` when no positive\n * integer `num_ctx` line is present.\n */\nexport function extractParameterNumCtx(parameters?: string | undefined): number | undefined {\n if (!parameters) return undefined;\n const match = /^[ \\t]*num_ctx[ \\t]+(\\d+)\\s*$/m.exec(parameters);\n if (match === null) return undefined;\n const value = Number.parseInt(match[1]!, 10);\n return Number.isFinite(value) && value > 0 ? value : undefined;\n}\n\n/**\n * Whether one `/api/ps` running-model entry is the same model `model` refers to.\n * Matching mirrors Ollama's own model resolution: exact match on the entry's\n * `name`/`model`, or — when `model` carries no tag — any entry whose name starts\n * with `<model>:`. Shared by context-window discovery\n * (`findRunningModelContextLength`) and multi-host model-affinity routing\n * (`ModelAffinityRouter`) so the two can never disagree on what \"loaded\" means.\n * Fields are optional because raw wire payloads (the generated `Ps` model) mark\n * them so; the hand-written `ModelResponse` (required fields) is assignable too.\n */\nfunction matchesModelReference(\n entry: { readonly name?: string | undefined; readonly model?: string | undefined },\n model: string,\n): boolean {\n const exact = entry.name === model || entry.model === model;\n const taglessPrefix =\n !model.includes(':') &&\n ((entry.name !== undefined && entry.name.startsWith(`${model}:`)) ||\n (entry.model !== undefined && entry.model.startsWith(`${model}:`)));\n return exact || taglessPrefix;\n}\n\n/**\n * Whether `model` is currently resident (loaded in VRAM) per a `GET /api/ps`\n * response — exact or tag-less-prefix match, same resolution rules as Ollama\n * itself applies to model names. See {@link matchesModelReference}.\n */\nexport function isModelResident(\n psModels: readonly { readonly name?: string | undefined; readonly model?: string | undefined }[],\n model: string,\n): boolean {\n return psModels.some((entry) => matchesModelReference(entry, model));\n}\n\n/**\n * Finds the context window Ollama actually allocated for `model`, from a\n * `GET /api/ps` response. Matching mirrors Ollama's own model resolution:\n * exact match on the entry's `name`/`model`, or — when `model` carries no\n * tag — any entry whose name starts with `<model>:`.\n *\n * Returns `undefined` when the model isn't loaded or the running entry\n * doesn't report `context_length` (older server versions).\n */\nexport function findRunningModelContextLength(\n psModels: readonly ModelResponse[],\n model: string,\n): number | undefined {\n for (const entry of psModels) {\n if (matchesModelReference(entry, model)) {\n return typeof entry.context_length === 'number' &&\n Number.isFinite(entry.context_length) &&\n entry.context_length > 0\n ? entry.context_length\n : undefined;\n }\n }\n return undefined;\n}\n\n/** Internal inputs to {@link resolveContextLength}; each signal independently optional. */\nexport interface ContextLengthSignals {\n readonly running?: number | undefined;\n readonly parameter?: number | undefined;\n readonly native?: number | undefined;\n}\n\nfunction positiveInt(value: number | undefined): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;\n}\n\n/**\n * Resolves the effective context window from whatever signals were\n * discovered, by precedence:\n *\n * 1. **`running`** — the allocated window of the loaded instance. When the\n * model is in memory this is the ground truth; it already incorporates\n * any Modelfile `num_ctx` default.\n * 2. **`parameter`** — the Modelfile's `num_ctx`, i.e. the window the\n * runner *will* allocate for this model on the next cold load.\n * 3. **`native`** — the GGUF maximum. Only used when nothing tighter is\n * known: a fresh `num_ctx`-less load may allocate far less than native\n * (Ollama's conservative default), so native is a *ceiling*, not an\n * expectation.\n * 4. **Fallback** — {@link OLLAMA_FALLBACK_CONTEXT_LENGTH} (2048), the\n * conservative server-side default, so the result is always actionable.\n *\n * Pure — used by `ModelsClient.getContextLength()` and exported for callers\n * that already hold `/api/ps` / `/api/show` responses.\n */\nexport function resolveContextLength(signals: ContextLengthSignals): DiscoveredContextLength {\n const running = positiveInt(signals.running);\n const parameter = positiveInt(signals.parameter);\n const native = positiveInt(signals.native);\n if (running !== undefined) {\n return {\n contextLength: running,\n source: 'running',\n ...(parameter !== undefined ? { parameterContextLength: parameter } : {}),\n ...(native !== undefined ? { nativeContextLength: native } : {}),\n runningContextLength: running,\n };\n }\n if (parameter !== undefined) {\n return {\n contextLength: parameter,\n source: 'parameters',\n parameterContextLength: parameter,\n ...(native !== undefined ? { nativeContextLength: native } : {}),\n };\n }\n if (native !== undefined) {\n return { contextLength: native, source: 'model-info', nativeContextLength: native };\n }\n return { contextLength: OLLAMA_FALLBACK_CONTEXT_LENGTH, source: 'fallback' };\n}\n\n/** Re-exported for `getContextLength` consumers that also want the raw model_info scanner. */\nexport { extractContextLength as extractNativeContextLength };\n","/**\n * Multi-host model-affinity routing — prefer the endpoint already holding the\n * requested model in VRAM.\n *\n * Ollama daemons keep a bounded set of models resident (`OLLAMA_MAX_LOADED_MODELS`).\n * With several interchangeable endpoints serving the same models, sending a request\n * to a host that doesn't currently hold the model forces an unload/cold-load swap\n * on that host — the thrashing `ModelAffinityScheduler` avoids for a *single*\n * client's task queues. This router brings the same affinity to the *multi-host*\n * request path: given the candidate endpoints `executeWithFailover` would try\n * anyway, it reorders them so hosts whose `GET /api/ps` shows the requested model\n * resident come first.\n *\n * Design constraints (see ADR 0028):\n *\n * - **Zero added request latency.** Reordering is synchronous and consults only\n * cached `/api/ps` snapshots. A request never waits for a probe: when a\n * snapshot is missing or stale, the request proceeds with the unchanged\n * candidate order and the refresh happens in the background, warming the cache\n * for subsequent requests.\n * - **Race-free with `least-connections`.** The reorder runs entirely between the\n * registry's synchronous `candidates()`/`filterWithCapacity()` and the\n * endpoint's `acquire()` — no `await` in between — so the strategy's\n * no-two-calls-pick-the-same-idle-endpoint guarantee is untouched. Affinity\n * only reorders *within each priority tier* of the runnable set: a\n * higher-priority endpoint is always tried before a lower-priority one, and\n * per-strategy ordering is kept inside the resident/non-resident groups.\n * - **Best-effort, never blocking, never failing a request.** A probe failure is\n * recorded with a short backoff (`failureRetryMs`) and never cached as data;\n * the affected endpoint is simply treated as unknown until a probe succeeds.\n * - **Fresh-data-only decisions.** Only snapshots within `ttlMs` reorder\n * requests — `/api/ps` can change at any moment (evictions, other clients),\n * so stale data is treated as no data. Last-known snapshots are still exposed\n * via `status()` for observability.\n */\n\nimport { isModelResident } from '../context-discovery.js';\nimport type { OllamaEndpoint } from './endpoint-registry.js';\n\n/**\n * One `/api/ps` running-model entry, as the router consumes it — name/model only.\n * Optional to match the generated `Ps` wire shape; hand-written `ModelResponse`\n * values (required fields) are assignable as-is.\n */\nexport interface AffinityRunningModel {\n readonly name?: string | undefined;\n readonly model?: string | undefined;\n}\n\n/**\n * Options for dynamic model-affinity routing across endpoints. Configured under\n * `OllamaClientConfig.endpointHealth.modelAffinity`; implemented by\n * `OllamaClient`'s request path (`executeWithFailover`), which has HTTP access —\n * the `EndpointRegistry` itself ignores this key.\n */\nexport interface ModelAffinityRoutingOptions {\n /**\n * How long a `GET /api/ps` snapshot stays fresh enough to reorder requests\n * (default 30_000ms). Mirrors `ModelAffinityScheduler`'s `psCacheTtlMs`.\n */\n readonly ttlMs?: number | undefined;\n /**\n * How long a failed `/api/ps` probe suppresses retries against that endpoint\n * (default 5_000ms) — a dead host isn't probed on every request while it's\n * down, and comes back automatically once it recovers. Failures are never\n * cached as data.\n */\n readonly failureRetryMs?: number | undefined;\n}\n\n/** Introspection snapshot for one endpoint's affinity cache. */\nexport interface ModelAffinitySnapshot {\n readonly endpointName: string;\n readonly baseUrl: string;\n /** Model names reported resident by the last successful probe (may be stale). */\n readonly loadedModels: readonly string[];\n /** When the last successful probe completed — `undefined` if it never succeeded. */\n readonly fetchedAt: number | undefined;\n /** Whether the snapshot is within `ttlMs` and therefore still drives reordering. */\n readonly fresh: boolean;\n}\n\ninterface CacheEntry {\n readonly models: readonly AffinityRunningModel[];\n readonly fetchedAt: number;\n}\n\n/** Test seam: injectable clock — defaults to `Date.now`. */\nexport type NowFn = () => number;\n\nconst DEFAULT_TTL_MS = 30_000;\nconst DEFAULT_FAILURE_RETRY_MS = 5_000;\n\n/**\n * Cache-and-reorder engine for multi-host model affinity. See the module docs for\n * the design constraints; `OllamaClient` constructs one (only when\n * `endpointHealth.modelAffinity` is set) and calls {@link reorder} synchronously\n * inside its request path.\n */\nexport class ModelAffinityRouter {\n private readonly fetchPs: (endpoint: OllamaEndpoint) => Promise<readonly AffinityRunningModel[]>;\n private readonly ttlMs: number;\n private readonly failureRetryMs: number;\n private readonly now: NowFn;\n private readonly cache = new Map<string, CacheEntry>();\n private readonly failedAt = new Map<string, number>();\n private readonly inflight = new Map<string, Promise<void>>();\n\n constructor(\n fetchPs: (endpoint: OllamaEndpoint) => Promise<readonly AffinityRunningModel[]>,\n options: ModelAffinityRoutingOptions & { readonly now?: NowFn } = {},\n ) {\n this.fetchPs = fetchPs;\n this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;\n this.failureRetryMs = options.failureRetryMs ?? DEFAULT_FAILURE_RETRY_MS;\n this.now = options.now ?? Date.now;\n }\n\n /**\n * Synchronously reorders `candidates` so that, within each priority tier\n * (run of consecutive equal `priority`), endpoints whose fresh `/api/ps`\n * snapshot shows `model` resident come first (relative order preserved within\n * each group). Never moves an endpoint across tiers. Returns the input unchanged — and kicks a background refresh —\n * when any candidate's snapshot is missing or stale: a wrong reorder is worse\n * than no reorder, and the first request after a cache miss simply isn't\n * reordered. No-op without a `model` or with fewer than two candidates.\n */\n reorder(\n candidates: readonly OllamaEndpoint[],\n model: string | undefined,\n ): readonly OllamaEndpoint[] {\n if (model === undefined || candidates.length < 2) return candidates;\n\n const currentTime = this.now();\n let allFresh = true;\n for (const endpoint of candidates) {\n const entry = this.cache.get(endpoint.name);\n if (entry === undefined || currentTime - entry.fetchedAt > this.ttlMs) {\n allFresh = false;\n this.kickRefresh(endpoint);\n }\n }\n if (!allFresh) return candidates;\n\n const isResident = (ep: OllamaEndpoint): boolean => {\n const entry = this.cache.get(ep.name);\n return entry !== undefined && isModelResident(entry.models, model);\n };\n\n // Affinity only breaks ties *within* a priority tier: a higher-priority\n // endpoint is always tried before a lower-priority one, resident or not.\n // Tiers are runs of consecutive equal `priority` (unset = 0, as in the\n // registry), so whatever order the registry produced between runs —\n // priority-sorted, or the fail-open recovery order — is kept as-is.\n const reordered: OllamaEndpoint[] = [];\n let changed = false;\n for (let start = 0; start < candidates.length;) {\n const tierPriority = candidates[start]!.priority ?? 0;\n let end = start + 1;\n while (end < candidates.length && (candidates[end]!.priority ?? 0) === tierPriority) end++;\n const tier = candidates.slice(start, end);\n const resident = tier.filter(isResident);\n if (resident.length === 0 || resident.length === tier.length) {\n reordered.push(...tier);\n } else {\n const tierOrder = [...resident, ...tier.filter((ep) => !isResident(ep))];\n changed ||= tierOrder.some((ep, i) => ep !== tier[i]);\n reordered.push(...tierOrder);\n }\n start = end;\n }\n return changed ? reordered : candidates;\n }\n\n /**\n * Forces a refresh of the affinity cache for the given endpoints (deduped with\n * any in-flight refresh; bypasses the failure backoff, because this is an\n * explicit caller request — `client.warmModelAffinity()`). Resolves once every\n * probe has settled — successfully or not; individual failures never reject.\n */\n async warm(endpoints: readonly OllamaEndpoint[]): Promise<void> {\n await Promise.all(endpoints.map((endpoint) => this.refresh(endpoint)));\n }\n\n /** Introspection snapshots for the given endpoints (defaults to cached ones). */\n status(endpoints?: readonly OllamaEndpoint[]): readonly ModelAffinitySnapshot[] {\n const names =\n endpoints !== undefined\n ? endpoints.map((ep) => ep.name)\n : [...this.cache.keys(), ...this.failedAt.keys()];\n const byName = new Map((endpoints ?? []).map((ep) => [ep.name, ep] as const));\n const currentTime = this.now();\n return names\n .filter((name, i, arr) => arr.indexOf(name) === i)\n .map((name) => {\n const entry = this.cache.get(name);\n return {\n endpointName: name,\n baseUrl: byName.get(name)?.baseUrl ?? '',\n loadedModels:\n entry?.models.map((m) => m.name ?? m.model ?? '').filter((n) => n !== '') ?? [],\n fetchedAt: entry?.fetchedAt,\n fresh: entry !== undefined && currentTime - entry.fetchedAt <= this.ttlMs,\n };\n });\n }\n\n /**\n * Starts (or joins) a background refresh for `endpoint`, unless one is already\n * in flight or the failure backoff suppresses it. Fire-and-forget: the promise\n * is stored only for dedupe/warm-joins; callers never await it on the request\n * path.\n */\n private kickRefresh(endpoint: OllamaEndpoint): void {\n if (this.inflight.has(endpoint.name)) return; // deduped inside refresh() too\n const lastFailure = this.failedAt.get(endpoint.name);\n if (lastFailure !== undefined && this.now() - lastFailure < this.failureRetryMs) return;\n void this.refresh(endpoint);\n }\n\n /** Refreshes one endpoint's snapshot; never rejects (failures record a backoff). */\n private refresh(endpoint: OllamaEndpoint): Promise<void> {\n const existing = this.inflight.get(endpoint.name);\n if (existing !== undefined) return existing;\n\n const attempt = this.fetchPs(endpoint)\n .then((models) => {\n this.cache.set(endpoint.name, { models, fetchedAt: this.now() });\n this.failedAt.delete(endpoint.name);\n })\n .catch(() => {\n // Unreachable host, auth hiccup, timeout — affinity routing is\n // best-effort. Record a backoff so a dead endpoint isn't re-probed on\n // every single request, and never cache a failure as data: the endpoint\n // is simply \"unknown\" until a probe succeeds. (A previous success stays\n // in the cache for `status()` observability but is too stale to reorder.)\n this.failedAt.set(endpoint.name, this.now());\n })\n .finally(() => {\n this.inflight.delete(endpoint.name);\n });\n\n this.inflight.set(endpoint.name, attempt);\n return attempt;\n }\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 {\n extractParameterNumCtx,\n findRunningModelContextLength,\n resolveContextLength,\n type ContextDiscoveryRequestOptions,\n type DiscoveredContextLength,\n} from './context-discovery.js';\nimport { extractContextLength } 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 RequestCancellationOptions,\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 */\n/** Options for {@link ModelsClient.createModelFromGguf}: every `/api/create` field except identity/source ones, plus the draft-shard path convenience. */\nexport interface CreateModelFromGgufOptions extends Omit<\n CreateRequestOptions,\n 'model' | 'files' | 'from' | 'stream'\n> {\n /**\n * Local path(s) to the draft-model GGUF shard(s) for speculative decoding —\n * each is uploaded as a blob and assembled into `draft_files` under its\n * basename, the same protocol as the primary shards. Composes with an\n * explicit `draft_files` digest map (path uploads win on basename\n * collision). Pair with `parameters.draft_num_predict` and, optionally,\n * `draft_quantize` to compress the draft weights during ingestion.\n */\n readonly draftGguf?: string | readonly string[] | undefined;\n}\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(request?: RequestCancellationOptions): Promise<PsResponse> {\n return this.runner(\n (http, signal) => http.request<PsResponse>({ path: '/api/ps', method: 'GET', signal }),\n {\n singleEndpoint: true,\n ...(request?.signal !== undefined ? { signal: request.signal } : {}),\n ...(request?.timeoutMs !== undefined ? { timeoutMs: request.timeoutMs } : {}),\n },\n );\n }\n\n /**\n * Discovers the model's real context window from the server — no more\n * 2048/4096 guesswork. Consults, in precedence order:\n *\n * 1. `GET /api/ps` — the window the **running instance actually\n * allocated** (exact, reflects the Modelfile `num_ctx` default and\n * what fit in memory); skipped when the model isn't loaded, when\n * `skipRunningCheck` is set, or harmlessly on servers without the\n * field.\n * 2. `POST /api/show` `parameters` — a Modelfile-authored\n * `num_ctx <n>` default, i.e. the window a cold load will allocate.\n * 3. `POST /api/show` `model_info[\"<arch>.context_length\"]` — the\n * model's **native GGUF maximum** (a ceiling to raise `num_ctx`\n * toward, not the allocated window).\n * 4. Fallback — Ollama's conservative unset-`num_ctx` default (2048).\n *\n * The result carries every signal it found, so `nativeContextLength:\n * 131072` vs `contextLength: 4096` (a 32× gap seen in the official API\n * examples) is visible rather than guessed. Typical wiring:\n *\n * ```ts\n * const { contextLength, source, nativeContextLength } =\n * await client.models.getContextLength({ model: 'gemma4' });\n * // -> { contextLength: 4096, source: 'running', nativeContextLength: 131072 }\n * ```\n *\n * Makes two server calls (`/api/ps` + `/api/show`) unless\n * `skipRunningCheck` is set. A 404 from `/api/ps` (endpoint without the\n * listing) is treated as \"not running\" and never fails the lookup;\n * other transport errors propagate normally.\n */\n async getContextLength(\n request: ContextDiscoveryRequestOptions,\n ): Promise<DiscoveredContextLength> {\n let running: number | undefined;\n if (request.skipRunningCheck !== true) {\n try {\n const ps = await this.ps({ signal: request.signal, timeoutMs: request.timeoutMs });\n running = findRunningModelContextLength(ps.models, request.model);\n } catch (err) {\n // Endpoints without the running-models listing (e.g. compat-only\n // hosts) still deserve parameter/model-info discovery.\n if (!(err instanceof OllamaNotFoundError)) throw err;\n }\n }\n const showRes = await this.show({\n model: request.model,\n signal: request.signal,\n timeoutMs: request.timeoutMs,\n });\n return resolveContextLength({\n running,\n parameter: extractParameterNumCtx(showRes.parameters),\n native: extractContextLength(showRes.model_info),\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 * // Speculative decoding: primary + draft shards + tuning:\n * await client.models.createModelFromGguf('my-model', '/path/to/model.gguf', {\n * draftGguf: '/path/to/draft.gguf',\n * draftQuantize: 'q8_0',\n * parameters: { draft_num_predict: 8 },\n * });\n * ```\n *\n * Speculative-decoding models assemble the same way: pass the draft\n * network's GGUF(s) as `draftGguf` (uploaded into `draft_files`), optionally\n * set `draft_quantize` to compress the draft weights independently of the\n * primary model, and set `parameters.draft_num_predict` to tune how many\n * tokens the draft network predicts per step (Ollama defaults separate\n * draft models to 4; `0` disables drafting; models with embedded MTP\n * tensors require setting it explicitly).\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`, `draftGguf`, …) except `files`,\n * `draft_files` (use `draftGguf` for path-based drafts; an explicit digest\n * map is still accepted and merged), `from`, and `stream`.\n */\n async createModelFromGguf(\n model: string,\n gguf: string | readonly string[],\n opts?: CreateModelFromGgufOptions,\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 draftOpt = opts?.draftGguf;\n const draftPaths = typeof draftOpt === 'string' ? [draftOpt] : (draftOpt ?? []);\n const {\n model: _model,\n files: _files,\n from: _from,\n stream: _stream,\n draftGguf: _draftGguf,\n draft_files: _draftFiles,\n ...rest\n } = (opts ?? {}) as CreateRequestOptions & {\n draftGguf?: string | readonly string[] | undefined;\n };\n const draftFiles: Record<string, string> = { ...(_draftFiles ?? {}) };\n for (const path of draftPaths) {\n const uploaded = await this.createBlobFromFile(path, { signal: opts?.signal });\n draftFiles[uploaded.fileName] = uploaded.digest;\n }\n return this.create({\n ...rest,\n model,\n files,\n ...(Object.keys(draftFiles).length > 0 ? { draft_files: draftFiles } : {}),\n stream: false,\n } 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' | 'medium' | 'low' | 'max' | 'none' | 'minimal' | 'xhigh' | 'ultra' | (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 /** @remarks Documented as unsupported by Ollama — accepted for OpenAI interop, ignored by the server. */\n readonly user?: string | undefined;\n /** @remarks Documented as unsupported by Ollama — accepted for OpenAI interop, ignored by the server. */\n readonly logit_bias?: Record<string, number> | undefined;\n /** @remarks Documented as unsupported by Ollama — accepted for OpenAI interop, ignored by the server. */\n readonly n?: number | undefined;\n /**\n * @remarks Logprobs are documented as unsupported on Ollama's `/v1/chat/completions`.\n * Use native `chat({ logprobs: true, top_logprobs })` for token log probabilities.\n */\n readonly logprobs?: boolean | undefined;\n /** @remarks Documented as unsupported by Ollama — accepted for OpenAI interop, ignored by the server. */\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?: { readonly effort?: OpenAIReasoningEffort | undefined } | undefined;\n}\n\n/** A base64 data URL (`data:image/png;base64,...`) — the only image form Ollama accepts here. */\nexport type OllamaOpenAIImageDataUrl = `data:${string}`;\n\n/** Ollama Chat Completions supports text plus base64 image content. */\nexport type OllamaOpenAIChatContentPart =\n | OpenAITextContentPart\n | {\n readonly type: 'image_url';\n /**\n * A base64 `data:` URL, as a string or inside the OpenAI `{ url, detail? }` object.\n * Ollama documents remote image URLs as unsupported on `/v1/chat/completions`, so\n * `http(s)://` URLs are a compile error here; resolve remote images to base64 first\n * (e.g. with {@link resolveImageInput}) or use the native `images` field.\n */\n readonly image_url:\n | OllamaOpenAIImageDataUrl\n | {\n readonly url: OllamaOpenAIImageDataUrl;\n readonly detail?: 'auto' | 'low' | 'high' | 'original' | undefined;\n };\n };\n\nexport type OllamaOpenAIReasoningEffort = 'high' | 'medium' | 'low' | 'max' | 'none';\n\nexport type OllamaOpenAIChatMessage = Omit<OpenAIMessage, 'content'> & {\n readonly content: string | readonly OllamaOpenAIChatContentPart[];\n};\n\n/**\n * Strict Ollama-documented Chat Completions request. Excludes the fields\n * https://docs.ollama.com/api/openai-compatibility marks unsupported (`tool_choice`,\n * `logit_bias`, `user`, `n`, `logprobs`/`top_logprobs`) and the SDK-only\n * `parallel_tool_calls` flag, so passing any of them is a compile-time error instead of\n * a silently ignored request field.\n */\nexport type OllamaOpenAIChatCompletionRequest = Omit<\n OpenAIChatCompletionRequest,\n | 'messages'\n | 'parallel_tool_calls'\n | 'reasoning_effort'\n | 'reasoning'\n | 'tool_choice'\n | 'logit_bias'\n | 'user'\n | 'n'\n | 'logprobs'\n | 'top_logprobs'\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 | {\n readonly name?: string | undefined;\n readonly arguments?: string | undefined;\n }\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 | {\n readonly cached_tokens?: number | undefined;\n }\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 /**\n * @remarks Logprobs are documented as unsupported on Ollama's `/v1/completions`. Use\n * native `generate({ logprobs: true, top_logprobs })` for token log probabilities.\n */\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 /** @remarks Documented as unsupported by Ollama — accepted for OpenAI interop, ignored by the server. */\n readonly best_of?: number | undefined;\n /** @remarks Documented as unsupported by Ollama — accepted for OpenAI interop, ignored by the server. */\n readonly echo?: boolean | undefined;\n /** @remarks Documented as unsupported by Ollama — accepted for OpenAI interop, ignored by the server. */\n readonly logit_bias?: Record<string, number> | undefined;\n /** @remarks Documented as unsupported by Ollama — accepted for OpenAI interop, ignored by the server. */\n readonly user?: string | undefined;\n /** @remarks Documented as unsupported by Ollama — accepted for OpenAI interop, ignored by the server. */\n readonly n?: number | undefined;\n}\n\n/** Strict Ollama-documented Completions request. */\n/**\n * Strict Ollama-documented Completions request: excludes `best_of`, `echo`,\n * `logit_bias`, `user`, `n`, and `logprobs`, which Ollama documents as unsupported.\n */\nexport type OllamaOpenAICompletionRequest = Omit<\n OpenAICompletionRequest,\n 'best_of' | 'echo' | 'logit_bias' | 'user' | 'n' | 'logprobs'\n>;\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 | readonly string[] | readonly number[] | 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 /** @remarks Documented as unsupported by Ollama — accepted for OpenAI interop, ignored by the server. */\n readonly user?: string | undefined;\n}\n\n/** Strict Ollama-documented Embeddings request. */\n/**\n * Strict Ollama-documented Embeddings request: `input` is a string or an array of\n * strings (token and token-array inputs are documented as unsupported), and `user` is\n * excluded.\n */\nexport type OllamaOpenAIEmbeddingRequest = Omit<OpenAIEmbeddingRequest, 'input' | 'user'> & {\n readonly input: string | readonly string[];\n};\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 | {\n readonly prompt_tokens: number;\n readonly total_tokens: number;\n }\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 /** @remarks Documented as unsupported by Ollama — accepted but ignored. */\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/**\n * Strict Ollama-documented Responses request: excludes the stateful fields\n * (`previous_response_id`, `conversation`) and `truncation`, which Ollama documents as\n * unsupported.\n */\nexport type OllamaOpenAIResponsesRequest = Omit<\n OpenAIResponsesRequest,\n 'previous_response_id' | 'conversation' | 'truncation'\n>;\n\nexport type OpenAIResponsesStatus =\n 'completed' | 'failed' | 'in_progress' | 'cancelled' | 'queued' | 'incomplete';\n\nexport interface OpenAIResponsesError {\n readonly code?: string | undefined;\n readonly message?: string | undefined;\n readonly [key: string]: unknown;\n}\nexport interface OpenAIResponsesIncompleteDetails {\n readonly reason?: string | undefined;\n readonly [key: string]: unknown;\n}\n\nexport interface OpenAIResponsesOutputTextContent {\n readonly type: 'output_text';\n readonly text: string;\n readonly annotations?: readonly Record<string, unknown>[] | undefined;\n readonly logprobs?: readonly Record<string, unknown>[] | undefined;\n}\nexport interface OpenAIResponsesOutputRefusal {\n readonly type: 'refusal';\n readonly refusal: string;\n}\nexport type OpenAIResponsesOutputContent =\n OpenAIResponsesOutputTextContent | OpenAIResponsesOutputRefusal;\n\nexport interface OpenAIResponsesOutputMessage {\n readonly type: 'message';\n readonly id?: string | undefined;\n readonly status?: OpenAIResponsesStatus | undefined;\n readonly role?: string | undefined;\n readonly phase?: string | undefined;\n readonly content: readonly OpenAIResponsesOutputContent[];\n}\nexport interface OpenAIResponsesOutputFunctionCall {\n readonly type: 'function_call';\n readonly id?: string | undefined;\n readonly call_id?: string | undefined;\n readonly name: string;\n readonly arguments: string;\n readonly status?: OpenAIResponsesStatus | undefined;\n}\nexport interface OpenAIResponsesOutputReasoning {\n readonly type: 'reasoning';\n readonly id?: string | undefined;\n readonly status?: OpenAIResponsesStatus | undefined;\n readonly summary?:\n readonly { readonly type: 'summary_text'; readonly text: string }[] | undefined;\n readonly text?: string | undefined;\n readonly encrypted_content?: string | undefined;\n}\nexport type OpenAIResponsesOutputItem =\n OpenAIResponsesOutputMessage | OpenAIResponsesOutputFunctionCall | OpenAIResponsesOutputReasoning;\n\nexport interface OpenAIResponsesUsage {\n readonly input_tokens: number;\n readonly output_tokens: number;\n 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;\n readonly object: 'response';\n readonly created: number;\n readonly created_at?: number | undefined;\n readonly status?: OpenAIResponsesStatus | undefined;\n readonly completed_at?: number | null | undefined;\n readonly error?: OpenAIResponsesError | null | undefined;\n readonly incomplete_details?: OpenAIResponsesIncompleteDetails | null | undefined;\n readonly model: string;\n readonly output: readonly OpenAIResponsesOutputItem[];\n readonly output_text?: string | undefined;\n readonly previous_response_id?: string | null | undefined;\n readonly parallel_tool_calls?: boolean | undefined;\n readonly usage?: OpenAIResponsesUsage | undefined;\n}\n\nexport class OpenAIResponsesStreamError extends OllamaClientError {\n readonly responsePayload: OpenAIResponsesResponse;\n constructor(message: string, responsePayload: OpenAIResponsesResponse) {\n super(message, {\n code: 'openai_responses_stream_error',\n retryable: false,\n response: { body: responsePayload },\n });\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(\n private readonly source: AbortableAsyncIterable<SseEvent>,\n signal?: AbortSignal,\n ) {\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<\n number,\n {\n message: OpenAIMessage;\n finish_reason: string;\n logprobs?: Record<string, unknown> | null | undefined;\n }\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(\n new OllamaAbortError('OpenAI Chat Completion stream ended before completion'),\n );\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(\n private readonly source: AbortableAsyncIterable<SseEvent>,\n signal?: AbortSignal,\n ) {\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 } | 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 {\n readonly response_id?: string | undefined;\n readonly sequence_number?: number | undefined;\n}\n\nexport interface OpenAIResponsesOutputTextDeltaEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.output_text.delta';\n readonly item_id: string;\n readonly output_index: number;\n readonly content_index: number;\n readonly delta: string;\n}\nexport interface OpenAIResponsesOutputTextDoneEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.output_text.done';\n readonly item_id: string;\n readonly output_index: number;\n readonly content_index: number;\n readonly text: string;\n}\nexport interface OpenAIResponsesFunctionCallArgumentsDeltaEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.function_call_arguments.delta';\n readonly item_id: string;\n readonly output_index: number;\n readonly delta: string;\n}\nexport interface OpenAIResponsesFunctionCallArgumentsDoneEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.function_call_arguments.done';\n readonly item_id: string;\n readonly output_index: number;\n readonly arguments: string;\n readonly name?: string | undefined;\n}\nexport interface OpenAIResponsesReasoningTextDeltaEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.reasoning_text.delta';\n readonly item_id: string;\n readonly output_index: number;\n readonly content_index: number;\n readonly delta: string;\n}\nexport interface OpenAIResponsesReasoningTextDoneEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.reasoning_text.done';\n readonly item_id: string;\n readonly output_index: number;\n readonly content_index: number;\n readonly text: string;\n}\nexport interface OpenAIResponsesReasoningSummaryPartAddedEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.reasoning_summary_part.added';\n readonly item_id: string;\n readonly output_index: number;\n readonly summary_index: number;\n readonly part: { readonly type: 'summary_text'; readonly text: string };\n}\nexport interface OpenAIResponsesReasoningSummaryPartDoneEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.reasoning_summary_part.done';\n readonly item_id: string;\n readonly output_index: number;\n readonly summary_index: number;\n readonly part: { readonly type: 'summary_text'; readonly text: string };\n readonly status?: 'incomplete' | undefined;\n}\nexport interface OpenAIResponsesReasoningSummaryTextDeltaEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.reasoning_summary_text.delta';\n readonly item_id: string;\n readonly output_index: number;\n readonly summary_index: number;\n readonly delta: string;\n}\nexport interface OpenAIResponsesReasoningSummaryTextDoneEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.reasoning_summary_text.done';\n readonly item_id: string;\n readonly output_index: number;\n readonly summary_index: number;\n readonly text: string;\n}\nexport interface OpenAIResponsesOutputItemAddedEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.output_item.added';\n readonly item: OpenAIResponsesOutputItem;\n readonly output_index: number;\n}\nexport interface OpenAIResponsesOutputItemDoneEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.output_item.done';\n readonly item: OpenAIResponsesOutputItem;\n readonly output_index: number;\n}\nexport interface OpenAIResponsesContentPartAddedEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.content_part.added';\n readonly item_id: string;\n readonly output_index: number;\n readonly content_index: number;\n readonly part:\n OpenAIResponsesOutputContent | { readonly type: string; readonly [key: string]: unknown };\n}\nexport interface OpenAIResponsesContentPartDoneEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.content_part.done';\n readonly item_id: string;\n readonly output_index: number;\n readonly content_index: number;\n readonly part:\n OpenAIResponsesOutputContent | { readonly type: string; readonly [key: string]: unknown };\n}\nexport interface OpenAIResponsesRefusalDeltaEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.refusal.delta';\n readonly item_id: string;\n readonly output_index: number;\n readonly content_index: number;\n readonly delta: string;\n}\nexport interface OpenAIResponsesRefusalDoneEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.refusal.done';\n readonly item_id: string;\n readonly output_index: number;\n readonly content_index: number;\n readonly refusal: string;\n}\nexport interface OpenAIResponsesCreatedEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.created';\n readonly response: OpenAIResponsesResponse;\n}\nexport interface OpenAIResponsesInProgressEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.in_progress';\n readonly response: OpenAIResponsesResponse;\n}\nexport interface OpenAIResponsesQueuedEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.queued';\n readonly response: OpenAIResponsesResponse;\n}\nexport interface OpenAIResponsesCompletedEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.completed' | 'response.done';\n readonly response: OpenAIResponsesResponse;\n}\nexport interface OpenAIResponsesFailedEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.failed';\n readonly response: OpenAIResponsesResponse;\n}\nexport interface OpenAIResponsesIncompleteEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.incomplete';\n readonly response: OpenAIResponsesResponse;\n}\n\nexport type OpenAIResponsesStreamEvent =\n | OpenAIResponsesOutputTextDeltaEvent\n | OpenAIResponsesOutputTextDoneEvent\n | OpenAIResponsesFunctionCallArgumentsDeltaEvent\n | OpenAIResponsesFunctionCallArgumentsDoneEvent\n | OpenAIResponsesReasoningTextDeltaEvent\n | OpenAIResponsesReasoningTextDoneEvent\n | OpenAIResponsesReasoningSummaryPartAddedEvent\n | OpenAIResponsesReasoningSummaryPartDoneEvent\n | OpenAIResponsesReasoningSummaryTextDeltaEvent\n | OpenAIResponsesReasoningSummaryTextDoneEvent\n | OpenAIResponsesOutputItemAddedEvent\n | OpenAIResponsesOutputItemDoneEvent\n | OpenAIResponsesContentPartAddedEvent\n | OpenAIResponsesContentPartDoneEvent\n | OpenAIResponsesRefusalDeltaEvent\n | OpenAIResponsesRefusalDoneEvent\n | OpenAIResponsesCreatedEvent\n | OpenAIResponsesInProgressEvent\n | OpenAIResponsesQueuedEvent\n | OpenAIResponsesCompletedEvent\n | OpenAIResponsesFailedEvent\n | OpenAIResponsesIncompleteEvent\n | { readonly type: string; readonly [key: string]: unknown };\n\ntype OpenAIResponsesOutputState = {\n itemId: string;\n kind: 'message' | 'function_call' | 'reasoning';\n content: Map<number, OpenAIResponsesOutputContent>;\n summary: Map<number, string>;\n arguments: string;\n name?: string | undefined;\n callId?: string | undefined;\n status?: OpenAIResponsesStatus | undefined;\n role?: string | undefined;\n phase?: string | undefined;\n 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(\n private readonly source: AbortableAsyncIterable<SseEvent>,\n signal?: AbortSignal,\n ) {\n this.finalResultPromise = new Promise<OpenAIResponsesResponse>((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 get finalResult(): Promise<OpenAIResponsesResponse> {\n return this.finalResultPromise;\n }\n abort(): void {\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n 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 = (\n outputIndex: number,\n itemId: string,\n kind: OpenAIResponsesOutputState['kind'],\n ): OpenAIResponsesOutputState => {\n const existing = outputs.get(outputIndex);\n if (existing) {\n if (itemId) existing.itemId = itemId;\n existing.kind = kind;\n return existing;\n }\n const state: OpenAIResponsesOutputState = {\n itemId,\n kind,\n content: new Map(),\n summary: new Map(),\n arguments: '',\n reasoningText: '',\n };\n outputs.set(outputIndex, state);\n return state;\n };\n\n const applyOutputItem = (outputIndex: number, item: OpenAIResponsesOutputItem): void => {\n const kind =\n item.type === 'message'\n ? 'message'\n : item.type === 'function_call'\n ? 'function_call'\n : 'reasoning';\n const state = ensureState(outputIndex, item.id ?? '', kind);\n state.itemId = item.id ?? state.itemId;\n state.status = item.status;\n if (item.type === 'message') {\n state.role = item.role;\n state.phase = item.phase;\n state.content.clear();\n item.content.forEach((p, i) => state.content.set(i, p));\n } else if (item.type === 'function_call') {\n state.callId = item.call_id;\n state.name = item.name;\n state.arguments = item.arguments;\n } else {\n state.summary.clear();\n item.summary?.forEach((p, i) => state.summary.set(i, p.text));\n state.reasoningText = item.text ?? '';\n }\n };\n const applyContentPart = (\n outputIndex: number,\n itemId: string,\n contentIndex: number,\n part: OpenAIResponsesOutputContent,\n ): void => {\n const state = ensureState(outputIndex, itemId, 'message');\n state.content.set(contentIndex, part);\n };\n const reconstructedOutput = (): readonly OpenAIResponsesOutputItem[] =>\n [...outputs.entries()]\n .sort(([a], [b]) => a - b)\n .map(([outputIndex, state]) => {\n const canonical = canonicalOutputItems.get(outputIndex);\n if (canonical) return canonical;\n if (state.kind === 'message')\n return {\n type: 'message',\n ...(state.itemId ? { id: state.itemId } : {}),\n ...(state.status ? { status: state.status } : {}),\n role: state.role ?? 'assistant',\n ...(state.phase ? { phase: state.phase } : {}),\n content: [...state.content.entries()].sort(([a], [b]) => a - b).map(([, p]) => p),\n };\n if (state.kind === 'function_call')\n return {\n type: 'function_call',\n ...(state.itemId ? { id: state.itemId } : {}),\n ...(state.callId ? { call_id: state.callId } : {}),\n ...(state.status ? { status: state.status } : {}),\n name: state.name ?? '',\n arguments: state.arguments,\n };\n return {\n type: 'reasoning',\n ...(state.itemId ? { id: state.itemId } : {}),\n ...(state.status ? { status: state.status } : {}),\n ...(state.summary.size\n ? {\n summary: [...state.summary.entries()]\n .sort(([a], [b]) => a - b)\n .map(([, text]) => ({ type: 'summary_text' as const, text })),\n }\n : {}),\n ...(state.reasoningText ? { text: state.reasoningText } : {}),\n };\n });\n\n try {\n for await (const event of this.source) {\n if (event.data === '[DONE]') break;\n let payload: OpenAIResponsesStreamEvent;\n try {\n payload = JSON.parse(event.data) as OpenAIResponsesStreamEvent;\n } catch (error) {\n throw new Error('Failed to parse OpenAI Responses SSE payload', { cause: error });\n }\n switch (payload.type) {\n case 'response.created':\n case 'response.in_progress':\n case 'response.queued':\n responseMeta = (payload as OpenAIResponsesCreatedEvent).response;\n break;\n case 'response.completed':\n case 'response.done':\n finalResponse = (payload as OpenAIResponsesCompletedEvent).response;\n break;\n case 'response.failed':\n terminalFailure = (payload as OpenAIResponsesFailedEvent).response;\n finalResponse = terminalFailure;\n break;\n case 'response.incomplete':\n terminalIncomplete = (payload as OpenAIResponsesIncompleteEvent).response;\n finalResponse = terminalIncomplete;\n break;\n case 'response.output_item.added': {\n const e = payload as OpenAIResponsesOutputItemAddedEvent;\n applyOutputItem(e.output_index, e.item);\n break;\n }\n case 'response.output_item.done': {\n const e = payload as OpenAIResponsesOutputItemDoneEvent;\n applyOutputItem(e.output_index, e.item);\n canonicalOutputItems.set(e.output_index, e.item);\n break;\n }\n case 'response.content_part.added':\n case 'response.content_part.done': {\n const e = payload as\n OpenAIResponsesContentPartAddedEvent | OpenAIResponsesContentPartDoneEvent;\n if (\n (e.part.type === 'output_text' &&\n 'text' in e.part &&\n typeof e.part.text === 'string') ||\n (e.part.type === 'refusal' &&\n 'refusal' in e.part &&\n typeof e.part.refusal === 'string')\n ) {\n applyContentPart(\n e.output_index,\n e.item_id,\n e.content_index,\n e.part as OpenAIResponsesOutputContent,\n );\n }\n break;\n }\n case 'response.output_text.delta': {\n const e = payload as OpenAIResponsesOutputTextDeltaEvent;\n const s = ensureState(e.output_index, e.item_id, 'message');\n const p = s.content.get(e.content_index);\n s.content.set(e.content_index, {\n type: 'output_text',\n text: (p?.type === 'output_text' ? p.text : '') + e.delta,\n });\n break;\n }\n case 'response.output_text.done': {\n const e = payload as OpenAIResponsesOutputTextDoneEvent;\n const s = ensureState(e.output_index, e.item_id, 'message');\n s.content.set(e.content_index, { type: 'output_text', text: e.text });\n break;\n }\n case 'response.refusal.delta': {\n const e = payload as OpenAIResponsesRefusalDeltaEvent;\n const s = ensureState(e.output_index, e.item_id, 'message');\n const p = s.content.get(e.content_index);\n s.content.set(e.content_index, {\n type: 'refusal',\n refusal: (p?.type === 'refusal' ? p.refusal : '') + e.delta,\n });\n break;\n }\n case 'response.refusal.done': {\n const e = payload as OpenAIResponsesRefusalDoneEvent;\n const s = ensureState(e.output_index, e.item_id, 'message');\n s.content.set(e.content_index, { type: 'refusal', refusal: e.refusal });\n break;\n }\n case 'response.function_call_arguments.delta': {\n const e = payload as OpenAIResponsesFunctionCallArgumentsDeltaEvent;\n const s = ensureState(e.output_index, e.item_id, 'function_call');\n s.arguments += e.delta;\n break;\n }\n case 'response.function_call_arguments.done': {\n const e = payload as OpenAIResponsesFunctionCallArgumentsDoneEvent;\n const s = ensureState(e.output_index, e.item_id, 'function_call');\n s.arguments = e.arguments;\n if (e.name !== undefined) s.name = e.name;\n break;\n }\n case 'response.reasoning_summary_part.added':\n case 'response.reasoning_summary_part.done': {\n const e = payload as\n | OpenAIResponsesReasoningSummaryPartAddedEvent\n | OpenAIResponsesReasoningSummaryPartDoneEvent;\n const s = ensureState(e.output_index, e.item_id, 'reasoning');\n s.summary.set(e.summary_index, e.part.text);\n break;\n }\n case 'response.reasoning_summary_text.delta': {\n const e = payload as OpenAIResponsesReasoningSummaryTextDeltaEvent;\n const s = ensureState(e.output_index, e.item_id, 'reasoning');\n s.summary.set(e.summary_index, (s.summary.get(e.summary_index) ?? '') + e.delta);\n break;\n }\n case 'response.reasoning_summary_text.done': {\n const e = payload as OpenAIResponsesReasoningSummaryTextDoneEvent;\n const s = ensureState(e.output_index, e.item_id, 'reasoning');\n s.summary.set(e.summary_index, e.text);\n break;\n }\n case 'response.reasoning_text.delta': {\n const e = payload as OpenAIResponsesReasoningTextDeltaEvent;\n const s = ensureState(e.output_index, e.item_id, 'reasoning');\n s.reasoningText += e.delta;\n break;\n }\n case 'response.reasoning_text.done': {\n const e = payload as OpenAIResponsesReasoningTextDoneEvent;\n const s = ensureState(e.output_index, e.item_id, 'reasoning');\n s.reasoningText = e.text;\n break;\n }\n default:\n break;\n }\n yield payload;\n }\n if (terminalFailure || terminalIncomplete) {\n const response = terminalFailure ?? terminalIncomplete!;\n const status = terminalFailure ? 'failed' : 'incomplete';\n const detail =\n response.error?.message ?? response.incomplete_details?.reason ?? 'unknown error';\n throw new OpenAIResponsesStreamError(\n 'OpenAI Responses stream ' + status + ': ' + detail,\n response,\n );\n }\n if (!finalResponse) {\n if (!responseMeta)\n throw new Error('OpenAI Responses stream ended without a terminal response payload');\n if (responseMeta.status === 'failed' || responseMeta.status === 'incomplete') {\n const detail =\n responseMeta.error?.message ??\n responseMeta.incomplete_details?.reason ??\n 'unknown error';\n throw new OpenAIResponsesStreamError(\n 'OpenAI Responses stream ' + responseMeta.status + ': ' + detail,\n responseMeta,\n );\n }\n finalResponse = { ...responseMeta, output: reconstructedOutput(), status: 'completed' };\n } else if (finalResponse.status === 'failed' || finalResponse.status === 'incomplete') {\n const detail =\n finalResponse.error?.message ??\n finalResponse.incomplete_details?.reason ??\n 'unknown error';\n throw new OpenAIResponsesStreamError(\n 'OpenAI Responses stream ' + finalResponse.status + ': ' + detail,\n finalResponse,\n );\n }\n if (finalResponse.output.length === 0 && outputs.size > 0)\n finalResponse = { ...finalResponse, output: reconstructedOutput() };\n completed = true;\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.resolveFinal(finalResponse);\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 Responses stream ended before completion'));\n }\n }\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((http, runnerSignal) => operation(http, runnerSignal), {\n ...(model !== undefined ? { model } : {}),\n ...(signal !== undefined ? { signal } : {}),\n ...(holdUntil !== undefined ? { holdUntil } : {}),\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\n .requestSseStream({\n path: '/v1/chat/completions',\n body: request,\n signal: requestSignal,\n })\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(model: string, signal?: AbortSignal): 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\n .requestSseStream({\n path: '/v1/completions',\n body: request,\n signal: requestSignal,\n })\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\n .requestSseStream({\n path: '/v1/responses',\n body: request,\n signal: requestSignal,\n })\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 <= 255, { message: 'must have at most 255 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 copy: StatusResponseSchema,\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 { estimateMessageTokens, OLLAMA_FALLBACK_CONTEXT_LENGTH } from './context-safety.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/** Options for {@link compactConversationHistory} / {@link ConversationSession.compact}. */\nexport interface CompactionOptions {\n /**\n * Estimated-token budget the compacted history must fit within (including\n * any retained system message and the 10%-style reply reservation below).\n * Estimated with the same CJK-aware heuristic as the pre-flight checks\n * (`estimateMessageTokens` — ±20–30%, message overhead + tool calls +\n * `IMAGE_TOKEN_ESTIMATE` per image included).\n */\n readonly maxEstimatedTokens: number;\n /**\n * Tokens subtracted from the budget and reserved for the model's next\n * reply (default `0` for the pure function; `session.compact()` defaults\n * to ~10% of the window, mirroring the pre-flight warning threshold's\n * headroom).\n */\n readonly reserveForReply?: number | undefined;\n /**\n * Trailing messages always retained, even when they don't fit the budget\n * (default `2` — the latest user/assistant exchange). Guarantees a\n * compacted conversation never loses its most recent context; an\n * oversized tail is retained deliberately rather than truncated, because\n * silent truncation is the server's failure mode, not one this SDK\n * reproduces.\n */\n readonly minTailMessages?: number | undefined;\n}\n\n/**\n * Sliding-window history compaction: keep the pinned system message(s) plus\n * the most recent turns that fit `maxEstimatedTokens`, dropping the oldest\n * turns in between.\n *\n * Deliberately **not** automatic anywhere in the SDK: compaction rewrites the\n * prompt prefix, so the next request's KV-cache hit rate drops to zero and\n * the whole retained suffix re-evaluates. That tradeoff (latency + recompute\n * for a window that now fits) is sometimes exactly right — long-running\n * agent threads that would otherwise silently lose their oldest turns — and\n * sometimes catastrophic (a hot cache-friendly session that never actually\n * overflows). `ConversationSession.cacheStats` makes the \"session no longer\n * fits\" case visible; this function is the explicit, caller-initiated fix.\n *\n * Semantics:\n *\n * - **Leading `system` messages are always retained** and count against\n * the budget (they consume context too).\n * - Non-system messages are walked newest → oldest; each is retained while\n * it fits the remaining budget, or while fewer than `minTailMessages`\n * have been retained.\n * - Mid-conversation `system`/`tool` messages are ordinary tailable\n * history (only the *leading* system block is pinned).\n * - Returns a new array; the input is never mutated. Message objects are\n * reused by reference (sessions freeze them; external arrays are copied\n * defensively by the caller if needed).\n *\n * ```ts\n * const kept = compactConversationHistory(session.getMessages(), {\n * maxEstimatedTokens: window.contextLength,\n * reserveForReply: 512,\n * });\n * ```\n */\nexport function compactConversationHistory(\n messages: readonly Message[],\n options: CompactionOptions,\n): readonly Message[] {\n const reserve = Math.max(0, options.reserveForReply ?? 0);\n const minTail = Math.max(0, options.minTailMessages ?? 2);\n const budget = Math.max(0, options.maxEstimatedTokens - reserve);\n\n // Pin the leading system block (zero or more messages).\n let split = 0;\n while (split < messages.length && messages[split]!.role === 'system') split += 1;\n const pinned = messages.slice(0, split);\n const tail = messages.slice(split);\n\n let used = 0;\n for (const message of pinned) used += estimateMessageTokens(message);\n\n const retained: Message[] = [];\n for (let i = tail.length - 1; i >= 0; i -= 1) {\n const message = tail[i]!;\n const cost = estimateMessageTokens(message);\n const fits = used + cost <= budget;\n if (!fits && retained.length >= minTail) break;\n retained.unshift(message);\n used += cost;\n }\n\n return [...pinned, ...retained];\n}\n\n/** Options for {@link sanitizeHistoryForNextTurn}; all fields optional. */\nexport interface HistorySanitizeOptions {\n /**\n * Messages — counted from the **end** of the array — whose `images` are\n * preserved. Default `1`: only the final message keeps its image payload,\n * which is the rolling one-image window long-running vision chats almost\n * always want (sanitize after appending the newest turn, and every prior\n * base64 payload is gone by the next request). `0` evicts images\n * everywhere; negative values clamp to `0`.\n */\n readonly keepImagesOnLastMessages?: number | undefined;\n /**\n * Optional note appended to the `content` of each evicted message so the\n * model can still tell an image used to be there — e.g.\n * `\"[image from an earlier turn removed to save context]\"`. When omitted\n * (default) the `images` field is dropped and the text is untouched,\n * matching the wire behavior of never having sent the image at all.\n */\n readonly imagePlaceholder?: string | undefined;\n}\n\n/**\n * Vision-history hygiene: returns a copy of `messages` with image payloads\n * evicted from every message outside the trailing keep-window, conversation\n * text fully preserved.\n *\n * Ollama's `/api/chat` is stateless — each request re-sends and re-bills the\n * whole history, base64 images included (each one costing real context\n * tokens via `IMAGE_TOKEN_ESTIMATE` in the pre-flight estimators). A\n * consumer-managed `messages` array therefore re-uploads every image from\n * every prior turn on every request, long after the model has already\n * answered the question that needed them. This helper is the explicit fix:\n *\n * ```ts\n * history.push({ role: 'user', content: 'What is in THIS photo?', images: [nextImage] });\n * await client.chat({ model, messages: sanitizeHistoryForNextTurn(history) });\n * ```\n *\n * Same philosophy as {@link compactConversationHistory}: caller-initiated,\n * never automatic. Two deliberate tradeoffs, both documented in ADR 0027:\n *\n * - **The model loses access to evicted images** — it keeps the\n * conversation text (and the optional `imagePlaceholder` note) but can\n * no longer \"see\" earlier pictures. That is the point: a bounded\n * payload in exchange for fading visual memory.\n * - **KV-prefix invalidation** — evicting rewrites the message at that\n * position, so the next turn's prompt prefix diverges and the cache\n * re-evaluates from that point. A hot cache-friendly session shouldn't\n * sanitize; a growing vision session should.\n *\n * Pure: the input array is never mutated, and messages that keep their\n * images are reused by reference (identity-stable for the untouched ones,\n * fresh copies only where eviction happened).\n */\nexport function sanitizeHistoryForNextTurn(\n messages: readonly Message[],\n options: HistorySanitizeOptions = {},\n): readonly Message[] {\n const keep = Math.max(0, options.keepImagesOnLastMessages ?? 1);\n const placeholder = options.imagePlaceholder;\n const cutoff = messages.length - keep;\n\n const sanitized: Message[] = [];\n for (let index = 0; index < messages.length; index += 1) {\n const message = messages[index]!;\n if (index >= cutoff || !message.images || message.images.length === 0) {\n sanitized.push(message);\n continue;\n }\n const { images: _evicted, ...rest } = message;\n if (placeholder === undefined) {\n sanitized.push(rest as Message);\n } else {\n sanitized.push({\n ...rest,\n content: rest.content === '' ? placeholder : `${rest.content}\\n\\n${placeholder}`,\n } as Message);\n }\n }\n return sanitized;\n}\n\n/** Options for {@link ConversationSession.compact}; all fields optional. */\nexport interface SessionCompactionOptions {\n /**\n * Token budget for the compacted history. Defaults to the session's own\n * window: `options.num_ctx` from the session config, or Ollama's\n * conservative 2048 fallback when unset — pair with\n * `client.models.getContextLength()` to program against the real window.\n */\n readonly maxEstimatedTokens?: number | undefined;\n /** Reply reservation; defaults to ~10% of the (derived) budget. */\n readonly reserveForReply?: number | undefined;\n /** Trailing messages always kept (default `2`). See {@link CompactionOptions}. */\n readonly minTailMessages?: number | undefined;\n}\n\n/** What {@link ConversationSession.compact} did. */\nexport interface SessionCompactionResult {\n /** Number of messages dropped from the front of the tailable history. */\n readonly droppedMessages: number;\n /** Estimated tokens of the whole history before compaction. */\n readonly estimatedTokensBefore: number;\n /** Estimated tokens of the retained history after compaction. */\n readonly estimatedTokensAfter: number;\n /** The budget that was applied (after the reply reservation). */\n readonly effectiveBudget: number;\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 * Compacts the session's history in place: pinned system prompt plus the\n * most recent turns that fit the budget, oldest tailable turns dropped.\n *\n * This is the explicit escape hatch for sessions that outgrew their\n * window — `cacheStats.hitRate` collapsing toward zero while history grows\n * is the usual symptom, and the pre-flight warnings on `chat()` fire once\n * the prompt estimate crosses the threshold. After compaction the next\n * turn's prompt prefix differs from everything before it, so the KV cache\n * starts cold — visible as a one-turn `evaluatedTokens` spike in\n * `cacheStats`. Cumulative cache tallies are deliberately **not** reset:\n * they are observations, and the spike is part of the story.\n *\n * Returns the before/after estimates and the drop count. No-op (zero\n * drops, equal before/after estimates) when the history already fits.\n */\n compact(options: SessionCompactionOptions = {}): SessionCompactionResult {\n const window =\n options.maxEstimatedTokens ?? this.config.options?.num_ctx ?? OLLAMA_FALLBACK_CONTEXT_LENGTH;\n const reserve = options.reserveForReply ?? Math.ceil(window * 0.1);\n const estimatedTokensBefore = this.history.reduce(\n (sum, message) => sum + estimateMessageTokens(message),\n 0,\n );\n const compacted = compactConversationHistory(this.history, {\n maxEstimatedTokens: window,\n reserveForReply: reserve,\n ...(options.minTailMessages !== undefined\n ? { minTailMessages: options.minTailMessages }\n : {}),\n });\n const estimatedTokensAfter = compacted.reduce(\n (sum, message) => sum + estimateMessageTokens(message),\n 0,\n );\n const droppedMessages = this.history.length - compacted.length;\n this.history.length = 0;\n this.history.push(...compacted);\n return {\n droppedMessages,\n estimatedTokensBefore,\n estimatedTokensAfter,\n effectiveBudget: window - reserve,\n };\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 * Batch-constrained embedding generation for high-volume ingestion pipelines.\n *\n * Ollama's `/api/embed` accepts an array of inputs, but two independent limits\n * make naive usage fragile at corpus scale:\n *\n * 1. **Concurrency.** `Promise.all(inputs.map(...))` fires every request at\n * once; against a local Ollama daemon this contends sockets, saturates the\n * request queue (`OLLAMA_MAX_QUEUE`, surfacing as 503 `overloaded`), and —\n * worst case — exhausts GPU VRAM as the model instance serves N prompts\n * simultaneously.\n * 2. **Context window.** Ollama truncates any input string longer than the\n * model's context window (`num_ctx`) *silently* unless `truncate: false` is\n * set — degraded vectors with no error, no warning, nothing on the wire.\n *\n * {@link batchEmbed} addresses the first with a fixed-size worker pool over\n * `client.embed()` (so every batch still rides the client's full pipeline:\n * failover, retry, auth, logging, telemetry). The client-level\n * `embedBatch()` wrapper addresses the second with a pre-flight per-string\n * token estimate against the resolved `num_ctx` window (see\n * {@link findOversizedEmbedInputs}).\n *\n * Semantics:\n * - **Order-preserving** — result index `i` is always the embedding of\n * `input[i]`, regardless of which batch completed first.\n * - **Fail-fast** — the first batch error aborts every sibling in-flight\n * batch (surfaces the *original* error, not the derived aborts) and rejects\n * the whole operation. Vector indexing that half-succeeds is a corrupted\n * index; callers re-running an ingestion prefer all-or-nothing.\n * - **Abortable** — the caller's `signal` cancels queued and in-flight batches\n * alike and rejects with `code: 'aborted'`.\n */\n\nimport { estimateTokens } from './context-safety.js';\nimport { OllamaAbortError, OllamaClientError } from './errors.js';\nimport type { ModelOptions } from './types.js';\nimport type { EmbedRequestOptions, EmbedResponse } from './types.js';\nimport type { OllamaClient } from './client.js';\n\n/**\n * Default number of input strings per `/api/embed` request. 32 keeps a single\n * request's prompt comfortably inside typical embedding-model context windows\n * (2048+) while amortizing HTTP overhead across the corpus.\n */\nexport const DEFAULT_EMBED_BATCH_SIZE = 32;\n\n/**\n * Default number of batches kept in flight concurrently. 3 is deliberately\n * conservative: a local Ollama daemon serves one model instance per GPU, so\n * 3 concurrent embedding prompts bound queue depth and VRAM pressure without\n * leaving the hardware idle between batches. Raise for multi-endpoint\n * clients or remote daemons; lower (to 1) for constrained devices.\n */\nexport const DEFAULT_EMBED_CONCURRENCY = 3;\n\nexport interface EmbedBatchOptions {\n /** Model to embed with (e.g. `'nomic-embed-text:latest'`). */\n readonly model: string;\n /** Input strings, in corpus order. Result index `i` matches `input[i]`. */\n readonly input: readonly string[];\n /**\n * Inputs per `/api/embed` request. Default {@link DEFAULT_EMBED_BATCH_SIZE}\n * (32). Must be a positive integer.\n */\n readonly batchSize?: number | undefined;\n /**\n * Batches kept in flight simultaneously. Default\n * {@link DEFAULT_EMBED_CONCURRENCY} (3). Must be a positive integer.\n */\n readonly concurrency?: number | undefined;\n /** Passed through to each batch request — `false` makes oversized inputs\n * a server-side error instead of a silent truncation. */\n readonly truncate?: boolean | undefined;\n /** Passed through to each batch request (dimensionality truncation). */\n readonly dimensions?: number | undefined;\n /** Passed through to each batch request (model unload policy). */\n readonly keep_alive?: string | number | undefined;\n /** Ollama model options (`num_ctx`, …) passed through to each batch request. */\n readonly options?: ModelOptions | undefined;\n /** Aborts the whole batch operation — queued and in-flight alike. */\n readonly signal?: AbortSignal | undefined;\n /** Per-request timeout applied to each individual batch request. */\n readonly timeoutMs?: number | undefined;\n /**\n * Progress callback invoked after each successfully embedded batch as\n * `onBatchComplete(completedBatches, totalBatches)`. Never called after the\n * operation rejects.\n */\n readonly onBatchComplete?: ((completedBatches: number, totalBatches: number) => void) | undefined;\n}\n\nexport interface EmbedBatchResult {\n readonly model: string;\n /**\n * Embeddings in input order — `embeddings[i]` corresponds to\n * `options.input[i]`, independent of batch completion order.\n */\n readonly embeddings: readonly (readonly number[])[];\n /** Number of `/api/embed` requests the corpus was split into. */\n readonly batchCount: number;\n}\n\n/** An input string whose estimated token count exceeds the context window. */\nexport interface OversizedEmbedInput {\n /** Index into the input array. */\n readonly index: number;\n /** Estimated token count for `input[index]`. */\n readonly estimate: number;\n}\n\n/**\n * Finds input strings whose heuristic token estimate exceeds `contextLength`\n * (typically the resolved `num_ctx`). Unlike chat/generate pre-flight there is\n * no warning margin and no output-token headroom: an embedding request's\n * prompt IS the whole input, so the exact window is the trip point, and\n * crossing it means silent truncation (or, with `truncate: false`, a\n * server-side rejection).\n */\nexport function findOversizedEmbedInputs(\n input: readonly string[],\n contextLength: number,\n): OversizedEmbedInput[] {\n const oversized: OversizedEmbedInput[] = [];\n for (let index = 0; index < input.length; index++) {\n const text = input[index];\n if (text === undefined) continue;\n const estimate = estimateTokens(text);\n if (estimate > contextLength) {\n oversized.push({ index, estimate });\n }\n }\n return oversized;\n}\n\n/**\n * Builds the warn/throw message for oversized embed inputs (mirrors\n * `contextWarningMessage` for chat/generate).\n */\nexport function embedBatchOverflowMessage(\n oversized: readonly OversizedEmbedInput[],\n totalInputs: number,\n contextLength: number,\n truncateFalse: boolean,\n): string {\n const shown = oversized.slice(0, 5).map((entry) => `#${entry.index} (~${entry.estimate} tokens)`);\n const elided = oversized.length > 5 ? `, +${oversized.length - 5} more` : '';\n const outcome = truncateFalse\n ? 'the server will reject them (`truncate: false`)'\n : 'Ollama will silently truncate them, producing degraded vectors';\n return (\n `embedBatch: ${oversized.length} of ${totalInputs} input strings exceed the ` +\n `${contextLength}-token context window (${shown.join(', ')}${elided}). ` +\n `${outcome}. Raise \\`options.num_ctx\\`, pre-split long inputs, or set ` +\n `\\`truncate: true\\` explicitly to acknowledge truncation.`\n );\n}\n\nfunction assertPositiveInteger(value: number, field: 'batchSize' | 'concurrency'): void {\n if (!Number.isInteger(value) || value < 1) {\n throw new OllamaClientError(\n `embedBatch: \\`${field}\\` must be a positive integer (got ${value}).`,\n { code: 'invalid_request' },\n );\n }\n}\n\n/**\n * Splits `input` into `batchSize` slices and embeds them through `client.embed()`\n * with at most `concurrency` batches in flight. Order-preserving and fail-fast —\n * see the module doc for the full semantics.\n *\n * Prefer the {@link OllamaClient.embedBatch} wrapper, which additionally\n * injects `defaultContextLength` as `num_ctx` and enforces the client's\n * `onContextOverflow` policy against per-string estimates before any request\n * is sent.\n */\nexport async function batchEmbed(\n client: OllamaClient,\n options: EmbedBatchOptions,\n): Promise<EmbedBatchResult> {\n const { model, input } = options;\n const batchSize = options.batchSize ?? DEFAULT_EMBED_BATCH_SIZE;\n const concurrency = options.concurrency ?? DEFAULT_EMBED_CONCURRENCY;\n assertPositiveInteger(batchSize, 'batchSize');\n assertPositiveInteger(concurrency, 'concurrency');\n\n if (input.length === 0) {\n return { model, embeddings: [], batchCount: 0 };\n }\n\n // Partition in corpus order — result index math below depends on it.\n const batches: string[][] = [];\n for (let start = 0; start < input.length; start += batchSize) {\n batches.push(input.slice(start, start + batchSize) as string[]);\n }\n\n const embeddings: (readonly number[] | undefined)[] = new Array(input.length);\n\n // Internal controller: aborted by the caller's `signal` OR by the first\n // batch failure. Every in-flight `client.embed()` receives it, so a single\n // failure (or caller abort) cancels siblings immediately instead of letting\n // them finish — fail-fast, not fail-slow.\n const controller = new AbortController();\n const propagateExternalAbort = (): void => {\n controller.abort(options.signal?.reason);\n };\n if (options.signal) {\n if (options.signal.aborted) {\n propagateExternalAbort();\n } else {\n options.signal.addEventListener('abort', propagateExternalAbort, { once: true });\n }\n }\n\n let nextBatch = 0;\n let completedBatches = 0;\n /** The first failure, rethrown by every sibling worker so the caller always\n * sees the root cause rather than a cascade of derived `AbortError`s. */\n let failure: { error: unknown } | undefined;\n\n const worker = async (): Promise<void> => {\n for (;;) {\n if (controller.signal.aborted) {\n throw failure?.error ?? new OllamaAbortError('Embed batch aborted');\n }\n const batchIndex = nextBatch;\n nextBatch++;\n if (batchIndex >= batches.length) return;\n const batch = batches[batchIndex];\n if (!batch) return;\n\n try {\n const request: EmbedRequestOptions = {\n model,\n input: batch,\n ...(options.truncate !== undefined ? { truncate: options.truncate } : {}),\n ...(options.dimensions !== undefined ? { dimensions: options.dimensions } : {}),\n ...(options.keep_alive !== undefined ? { keep_alive: options.keep_alive } : {}),\n ...(options.options !== undefined ? { options: options.options } : {}),\n ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n signal: controller.signal,\n };\n const response: EmbedResponse = await client.embed(request);\n\n if (response.embeddings.length !== batch.length) {\n throw new OllamaClientError(\n `embedBatch: server returned ${response.embeddings.length} embeddings for a ` +\n `batch of ${batch.length} inputs (batch ${batchIndex}).`,\n { code: 'invalid_response' },\n );\n }\n const offset = batchIndex * batchSize;\n for (let j = 0; j < batch.length; j++) {\n embeddings[offset + j] = response.embeddings[j];\n }\n completedBatches++;\n options.onBatchComplete?.(completedBatches, batches.length);\n } catch (error) {\n if (!failure) {\n failure = { error };\n controller.abort(error);\n throw error;\n }\n // A sibling already failed and aborted us — surface ITS error so the\n // caller diagnoses the root cause, not the derived cancellation.\n throw failure.error;\n }\n }\n };\n\n try {\n const workerCount = Math.min(concurrency, batches.length);\n await Promise.all(Array.from({ length: workerCount }, () => worker()));\n } finally {\n if (options.signal) {\n options.signal.removeEventListener('abort', propagateExternalAbort);\n }\n }\n\n // Defensive completeness check — every index must have been written by the\n // batch that owned it (Promise.all resolving implies every batch resolved).\n for (let i = 0; i < embeddings.length; i++) {\n if (embeddings[i] === undefined) {\n throw new OllamaClientError(\n `embedBatch: internal invariant violated — no embedding produced for input #${i}.`,\n { code: 'invalid_response' },\n );\n }\n }\n\n return {\n model,\n embeddings: embeddings as readonly (readonly number[])[],\n batchCount: batches.length,\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 response: { $ref: '#/schemas/StatusResponse' },\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: 'unsupported',\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: 'unsupported' },\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<StatusResponse> {\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 OllamaAbortError,\n OllamaClientError,\n OllamaModelRoutingError,\n OllamaUnsupportedCapabilityError,\n} from './errors.js';\nimport { createConsoleLogger, NOOP_LOGGER, type Logger } from './logger.js';\nimport {\n EndpointRegistry,\n type EndpointHealth,\n type OllamaEndpoint,\n} from './providers/endpoint-registry.js';\nimport { checkEndpointHealth, type EndpointHealthCheckResult } from './providers/health-check.js';\nimport {\n ModelAffinityRouter,\n type AffinityRunningModel,\n type ModelAffinitySnapshot,\n} from './providers/model-affinity-router.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 batchEmbed,\n embedBatchOverflowMessage,\n findOversizedEmbedInputs,\n type EmbedBatchOptions,\n type EmbedBatchResult,\n} from './embed-batch.js';\nimport {\n checkChatContext,\n checkGenerateContext,\n contextWarningMessage,\n type ContextCheck,\n} from './context-safety.js';\nimport type { ContextDiscoveryRequestOptions } from './context-discovery.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 PingResult,\n} from './types.js';\nimport type { BalanceResponse, UsageResponse } from './generated/models/index.js';\nimport { disposableTimer } from './utils.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 * Controllers for every in-flight request and active stream managed by this\n * client — see {@link OllamaClient.destroy} and {@link createRequestScope}.\n * Entries live for exactly as long as the underlying work does: until the\n * response settles (requests) or the stream's `finalResult` settles\n * (streams, via `executeWithFailover`'s `holdUntil` release path).\n */\n private readonly activeRequests = new Set<AbortController>();\n /**\n * Dynamic multi-host model-affinity routing, active only when\n * `config.endpointHealth.modelAffinity` is set — see\n * `src/providers/model-affinity-router.ts` and ADR 0028. `undefined` means\n * the request path skips reordering entirely (zero overhead, and no `/api/ps`\n * probes are ever issued).\n */\n private readonly modelAffinity: ModelAffinityRouter | undefined;\n\n /** Default timeout for one-off probe requests (`ping`, affinity `/api/ps` refreshes). */\n private static readonly PROBE_TIMEOUT_MS = 5000;\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 const modelAffinityOptions = config.endpointHealth?.modelAffinity;\n this.modelAffinity =\n modelAffinityOptions !== undefined\n ? new ModelAffinityRouter(\n (endpoint) => this.fetchEndpointRunningModels(endpoint),\n modelAffinityOptions,\n )\n : undefined;\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 * Creates the per-request abort scope registered with {@link destroy}:\n * a controller that fires when the caller's `signal` aborts OR when\n * `destroy()` runs, whichever comes first. `dispose()` removes the\n * registration when the work it guards settles — for plain requests when\n * the response settles, for streams when `finalResult` settles (the same\n * moment `executeWithFailover`'s `holdUntil` releases the endpoint slot),\n * so a destroy() can tear down a stream mid-consumption but never outlives\n * one that already finished.\n */\n private createRequestScope(userSignal: AbortSignal | undefined): {\n signal: AbortSignal;\n dispose: () => void;\n } {\n const controller = new AbortController();\n const propagateUserAbort = (): void => {\n controller.abort(userSignal?.reason);\n };\n let detach: (() => void) | undefined;\n if (userSignal) {\n if (userSignal.aborted) {\n propagateUserAbort();\n } else {\n userSignal.addEventListener('abort', propagateUserAbort, { once: true });\n detach = () => userSignal.removeEventListener('abort', propagateUserAbort);\n }\n }\n this.activeRequests.add(controller);\n return {\n signal: controller.signal,\n dispose: () => {\n detach?.();\n this.activeRequests.delete(controller);\n },\n };\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 scope = this.createRequestScope(options?.signal);\n const timeout = createTimeoutSignal(options?.timeoutMs ?? this.timeoutMs, scope.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 // Dynamic model-affinity routing: a synchronous, cache-only reorder of the\n // runnable set (endpoints whose fresh GET /api/ps snapshot shows the target\n // model resident come first). Deliberately no `await` between here and the\n // `acquire()` below — see ModelAffinityRouter's module docs and ADR 0028;\n // the 'least-connections' race-free guarantee depends on it. No-op (and no\n // /api/ps probes at all) unless `endpointHealth.modelAffinity` is configured.\n const ordered =\n this.modelAffinity !== undefined\n ? this.modelAffinity.reorder(runnable, options?.model)\n : runnable;\n\n for (const [attemptIndex, endpoint] of ordered.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 scope.dispose();\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) {\n timeout.cancel();\n scope.dispose();\n }\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 * Batch-constrained, order-preserving embedding generation for large\n * corpora — the safe building block for RAG/vector-index ingestion at\n * scale. Splits `input` into `batchSize` slices and embeds them through\n * {@link embed} with at most `concurrency` batches in flight (defaults:\n * 32 × 3), so `Promise.all`-style floods that OOM local daemons and\n * saturate `OLLAMA_MAX_QUEUE` can't happen by accident. Fail-fast: the\n * first batch error aborts every sibling in-flight batch and rejects the\n * whole operation with the original error.\n *\n * Before any request is sent, `defaultContextLength` is injected as\n * `num_ctx` (same as chat/generate) and each input string's token estimate\n * is checked against the resolved window: Ollama silently truncates\n * oversized embedding inputs by default, so the client warns (or throws,\n * under `onContextOverflow: 'throw'`) with the offending indexes — see\n * `src/embed-batch.ts` for the exact trip point (no margin: an embedding\n * prompt IS the whole input).\n *\n * ```ts\n * const { embeddings, batchCount } = await client.embedBatch({\n * model: 'nomic-embed-text:latest',\n * input: corpus, // e.g. 50k chunks\n * batchSize: 32, // inputs per /api/embed request\n * concurrency: 3, // batches in flight\n * onBatchComplete: (done, total) => progress.log(`${done}/${total}`),\n * });\n * // embeddings[i] always corresponds to corpus[i]\n * ```\n */\n async embedBatch(options: EmbedBatchOptions): Promise<EmbedBatchResult> {\n const resolvedOptions = this.injectDefaultContextLength(options.options);\n const contextLength = resolvedOptions?.num_ctx;\n if (contextLength !== undefined) {\n const oversized = findOversizedEmbedInputs(options.input, contextLength);\n if (oversized.length > 0) {\n const message = embedBatchOverflowMessage(\n oversized,\n options.input.length,\n contextLength,\n options.truncate === false,\n );\n if (this.onContextOverflow === 'throw') {\n throw new OllamaClientError(message, { code: 'context_overflow' });\n }\n this.logger.warn(message);\n }\n }\n return batchEmbed(\n this,\n resolvedOptions === options.options ? options : { ...options, options: resolvedOptions },\n );\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 = (request?: RequestCancellationOptions) => this.models.ps(request);\n /**\n * Discovers the model's real context window — the allocated window of the\n * running instance (`/api/ps`), the Modelfile `num_ctx` default, and the\n * native GGUF maximum (`/api/show` `model_info`), resolved by precedence.\n * Convenience alias for {@link ModelsClient.getContextLength} — see that\n * method for the full contract and the precedence order.\n */\n readonly getContextLength = (request: ContextDiscoveryRequestOptions) =>\n this.models.getContextLength(request);\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 scope = this.createRequestScope(options.signal);\n const timeout = createTimeoutSignal(options.timeoutMs ?? this.timeoutMs, scope.signal);\n using _timeout = {\n [Symbol.dispose]() {\n timeout.cancel();\n scope.dispose();\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\n /**\n * Ultra-lightweight liveness probe against the client's current best\n * endpoint: `HEAD /` — the root ping Ollama's documentation defines for\n * load-balancer health checks (HTTP 200; the daemon answers `GET /` with the\n * plain-text body \"Ollama is running\", which a HEAD request doesn't transfer).\n *\n * Deliberately a *single-endpoint, single-shot* probe — no failover to other\n * candidates, no retry — so the answer reflects one concrete host, not \"some\n * endpoint eventually answered\". To audit every configured endpoint, use\n * {@link healthCheck} (which probes all of them, and also reports the server\n * version at the cost of the heavier `GET /api/version` round trip).\n *\n * Resolves — never throws — with `{ healthy: false, error }` for connection\n * failures and timeouts; only caller-initiated cancellation (`signal`/\n * `destroy()`) rejects, mirroring how any other aborted request behaves.\n */\n async ping(options?: RequestCancellationOptions): Promise<PingResult> {\n const endpoint = this.registry.candidates()[0];\n if (endpoint === undefined) {\n return { healthy: false, latencyMs: 0, baseUrl: '', error: 'No configured endpoints' };\n }\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 });\n\n const timeout = createTimeoutSignal(\n options?.timeoutMs ?? OllamaClient.PROBE_TIMEOUT_MS,\n options?.signal,\n );\n const startTime = Date.now();\n try {\n await http.request<void>({ path: '/', method: 'HEAD', signal: timeout.signal });\n return { healthy: true, latencyMs: Date.now() - startTime, baseUrl: endpoint.baseUrl };\n } catch (err) {\n if (options?.signal?.aborted) {\n // Caller-initiated cancellation is not an unhealthiness signal.\n throw err instanceof Error ? err : new Error(String(err));\n }\n return {\n healthy: false,\n latencyMs: Date.now() - startTime,\n baseUrl: endpoint.baseUrl,\n error: err instanceof Error ? err.message : String(err),\n };\n } finally {\n timeout.cancel();\n }\n }\n\n /**\n * Affinity-cache snapshots for every configured endpoint — which models each\n * host held in VRAM at the last successful `/api/ps` probe, when that was, and\n * whether it's still fresh. Empty when `endpointHealth.modelAffinity` isn't\n * configured (no probes are ever issued, so there is nothing to report).\n */\n modelAffinityStatus(): readonly ModelAffinitySnapshot[] {\n return this.modelAffinity?.status(this.registry.list()) ?? [];\n }\n\n /**\n * Explicitly refreshes the model-affinity cache for every configured endpoint\n * (deduped with any in-flight background refresh). No-op — resolves\n * immediately — when `endpointHealth.modelAffinity` isn't configured. Use it\n * to warm the cache at startup so the very first request already routes by\n * residency instead of waiting for the self-warming first-round refresh.\n */\n async warmModelAffinity(): Promise<void> {\n await this.modelAffinity?.warm(this.registry.list());\n }\n\n endpointStatus(): EndpointHealth[] {\n return this.registry.status();\n }\n\n /**\n * Fetches one endpoint's `GET /api/ps` running-model list for the affinity\n * router. Bypasses `executeWithFailover` deliberately: probes must not\n * reenter the routing machinery they inform, must not touch the registry's\n * circuit-breaker/failure bookkeeping (a dead host's probe failing must not\n * cool it down harder than its real traffic already does), and must not fail\n * over to a different host (the answer is per-host by definition). Failures\n * propagate to the router, which records a short backoff and retries later.\n */\n private async fetchEndpointRunningModels(\n endpoint: OllamaEndpoint,\n ): Promise<readonly AffinityRunningModel[]> {\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 });\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), OllamaClient.PROBE_TIMEOUT_MS);\n using _timer = disposableTimer(timer);\n const res = await http.request<{ models?: readonly AffinityRunningModel[] }>({\n path: '/api/ps',\n method: 'GET',\n signal: controller.signal,\n });\n return res.models ?? [];\n }\n\n /**\n * Immediately aborts every in-flight request and active stream managed by\n * this client — the clean teardown path for short-lived processes, CLI\n * runners, and `node:worker_threads` tasks where dangling fetch bodies,\n * unconsumed stream readers, or queued capacity waiters would otherwise\n * keep the event loop (and thus the thread/process) alive.\n *\n * Every aborted operation rejects with an {@link OllamaAbortError}\n * (`code: 'aborted'`) carrying `reason` as its message — including requests\n * still queued behind `maxConcurrentPerEndpoint`, not just dispatched ones.\n * Streams reject their `finalResult` and release their endpoint slots.\n *\n * Idempotent: calling it again (or on a client with nothing in flight)\n * is a no-op that returns `0`. The client remains usable afterward —\n * `destroy()` is a drain, not a permanent disable; callers that want a\n * permanently-dead client should discard the instance.\n *\n * @returns the number of in-flight operations that were aborted.\n */\n destroy(reason: string = 'Ollama client destroyed'): number {\n const controllers = [...this.activeRequests];\n const cause = new OllamaAbortError(reason);\n for (const controller of controllers) {\n controller.abort(cause);\n }\n this.activeRequests.clear();\n return controllers.length;\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","/**\n * Ollama web search / web fetch exposed as model-callable tools.\n *\n * Implements the \"Building a search agent\" pattern from\n * https://docs.ollama.com/capabilities/web-search: hand `web_search` and `web_fetch`\n * to a tool-capable model, execute the calls it emits against Ollama Cloud's hosted\n * `/api/web_search` and `/api/web_fetch`, and feed bounded results back as\n * `role: 'tool'` messages. Use with {@link ToolRegistry} / `Agent`.\n */\n\nimport { z } from 'zod';\nimport type {\n WebFetchRequestOptions,\n WebFetchResponse,\n WebSearchRequestOptions,\n WebSearchResponse,\n} from '../types.js';\nimport { defineTool } from './define-tool.js';\nimport type { Tool } from './types.js';\n\n/** The subset of `OllamaClient` the web tools call. */\nexport interface WebToolsClient {\n webSearch(req: WebSearchRequestOptions): Promise<WebSearchResponse>;\n webFetch(req: WebFetchRequestOptions): Promise<WebFetchResponse>;\n}\n\nexport interface WebToolsOptions {\n /**\n * Upper bound on the model-visible JSON a single call returns. Web pages and search\n * snippets can run to thousands of tokens; the docs truncate each result to\n * `2000 * 4` characters, which is the default here. Content fields are trimmed (not\n * the serialized JSON), so the output always stays valid JSON.\n */\n readonly maxOutputChars?: number | undefined;\n /** `max_results` sent when the model omits it. Server default is 5, max 10. */\n readonly defaultMaxResults?: number | undefined;\n /** Maximum number of page links `web_fetch` returns to the model. Default 25. */\n readonly maxLinks?: number | undefined;\n /** Per-call tool execution timeout in milliseconds (see `ToolRegistryOptions.timeoutMs`). */\n readonly timeoutMs?: number | undefined;\n}\n\nexport const WEB_SEARCH_TOOL_NAME = 'web_search';\nexport const WEB_FETCH_TOOL_NAME = 'web_fetch';\n\nconst DEFAULT_MAX_OUTPUT_CHARS = 2000 * 4;\nconst DEFAULT_MAX_LINKS = 25;\nconst TRUNCATION_MARKER = '…[truncated]';\n\nconst webSearchSchema = z.object({\n query: z.string().min(1).describe('The search query string'),\n max_results: z\n .number()\n .int()\n .min(1)\n .max(10)\n .optional()\n .describe('Maximum results to return (default 5, max 10)'),\n});\n\nconst webFetchSchema = z.object({\n url: z.string().min(1).describe('The URL of the web page to fetch'),\n});\n\nexport type WebSearchToolParams = z.infer<typeof webSearchSchema>;\nexport type WebFetchToolParams = z.infer<typeof webFetchSchema>;\n\nfunction positiveInt(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (!Number.isInteger(value) || value < 1) {\n throw new RangeError(`${name} must be a positive integer, received ${String(value)}`);\n }\n return value;\n}\n\nfunction truncate(text: string, maxChars: number): string {\n if (text.length <= maxChars) return text;\n if (maxChars <= TRUNCATION_MARKER.length) return text.slice(0, maxChars);\n return text.slice(0, maxChars - TRUNCATION_MARKER.length) + TRUNCATION_MARKER;\n}\n\n/** Serialize a web search response within `maxChars`, trimming each snippet evenly. */\nexport function formatWebSearchResult(res: WebSearchResponse, maxChars: number): string {\n const results = res.results.map(({ title, url, content }) => ({ title, url, content }));\n const full = JSON.stringify({ results });\n if (full.length <= maxChars || results.length === 0) return truncate(full, maxChars);\n\n // Budget the content fields: everything except the snippets is structural overhead.\n const overhead = JSON.stringify({\n results: results.map((r) => ({ ...r, content: '' })),\n }).length;\n const perResult = Math.max(0, Math.floor((maxChars - overhead) / results.length));\n const trimmed = JSON.stringify({\n results: results.map((r) => ({ ...r, content: truncate(r.content, perResult) })),\n });\n // JSON escaping can still overshoot the estimate; fall back to a hard cut.\n return trimmed.length <= maxChars ? trimmed : truncate(trimmed, maxChars);\n}\n\n/** Serialize a web fetch response within `maxChars`, trimming page content first. */\nexport function formatWebFetchResult(\n res: WebFetchResponse,\n maxChars: number,\n maxLinks: number = DEFAULT_MAX_LINKS,\n): string {\n const page = {\n title: res.title ?? '',\n content: res.content,\n links: (res.links ?? []).slice(0, maxLinks),\n };\n const full = JSON.stringify(page);\n if (full.length <= maxChars) return full;\n\n const overhead = JSON.stringify({ ...page, content: '' }).length;\n const trimmed = JSON.stringify({\n ...page,\n content: truncate(page.content, Math.max(0, maxChars - overhead)),\n });\n return trimmed.length <= maxChars ? trimmed : truncate(trimmed, maxChars);\n}\n\n/** `web_search` tool backed by {@link WebToolsClient.webSearch}. */\nexport function createWebSearchTool(\n client: WebToolsClient,\n options: WebToolsOptions = {},\n): Tool<WebSearchToolParams, string> {\n const maxChars = positiveInt(options.maxOutputChars, DEFAULT_MAX_OUTPUT_CHARS, 'maxOutputChars');\n const defaultMaxResults =\n options.defaultMaxResults === undefined\n ? undefined\n : Math.min(positiveInt(options.defaultMaxResults, 5, 'defaultMaxResults'), 10);\n return defineTool({\n name: WEB_SEARCH_TOOL_NAME,\n description:\n 'Search the web for current information. Returns a list of results, each with a title, url, and relevant content snippet.',\n schema: webSearchSchema,\n timeoutMs: options.timeoutMs,\n execute: async ({ query, max_results }, { signal }) => {\n const res = await client.webSearch({\n query,\n ...((max_results ?? defaultMaxResults) !== undefined\n ? { max_results: max_results ?? defaultMaxResults }\n : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n return formatWebSearchResult(res, maxChars);\n },\n });\n}\n\n/** `web_fetch` tool backed by {@link WebToolsClient.webFetch}. */\nexport function createWebFetchTool(\n client: WebToolsClient,\n options: WebToolsOptions = {},\n): Tool<WebFetchToolParams, string> {\n const maxChars = positiveInt(options.maxOutputChars, DEFAULT_MAX_OUTPUT_CHARS, 'maxOutputChars');\n const maxLinks = positiveInt(options.maxLinks, DEFAULT_MAX_LINKS, 'maxLinks');\n return defineTool({\n name: WEB_FETCH_TOOL_NAME,\n description:\n 'Fetch a single web page by URL. Returns the page title, its main content, and links found on the page.',\n schema: webFetchSchema,\n timeoutMs: options.timeoutMs,\n execute: async ({ url }, { signal }) => {\n const res = await client.webFetch({ url, ...(signal !== undefined ? { signal } : {}) });\n return formatWebFetchResult(res, maxChars, maxLinks);\n },\n });\n}\n\n/**\n * Both web tools, ready to register:\n *\n * ```ts\n * const registry = new ToolRegistry(createWebTools(client));\n * const agent = new Agent(client, { tools: registry });\n * ```\n *\n * Requires an Ollama API key on the client (`apiKey` or `OLLAMA_API_KEY`); calls\n * always go to `https://ollama.com`, independent of the client's inference endpoints.\n */\nexport function createWebTools(\n client: WebToolsClient,\n options: WebToolsOptions = {},\n): [Tool<WebSearchToolParams, string>, Tool<WebFetchToolParams, string>] {\n return [createWebSearchTool(client, options), createWebFetchTool(client, options)];\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 OllamaAgentToolLoopError,\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, ToolCall, 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?: ((model: string, signal?: AbortSignal) => Promise<ModelCapabilities>) | 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/** Cap on the `signature` carried by {@link OllamaAgentToolLoopError} — enough to\n * identify the call, small enough not to bloat logs with a huge payload. */\nconst SIGNATURE_REPORT_LIMIT = 200;\n\n/** `JSON.stringify` with recursively sorted object keys, so key order never\n * splits one logical value into several distinct strings. `undefined` maps\n * to `'null'` to keep the output a valid JSON fragment. */\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') {\n return JSON.stringify(value) ?? 'null';\n }\n if (Array.isArray(value)) {\n return `[${value.map((entry) => stableStringify(entry)).join(',')}]`;\n }\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, entryValue]) => entryValue !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([key, entryValue]) => `${JSON.stringify(key)}:${stableStringify(entryValue)}`);\n return `{${entries.join(',')}}`;\n}\n\n/**\n * Canonical signature of a tool call for cycle detection: `name(args)` with\n * recursively key-sorted arguments, so the same call re-emitted by a model\n * in a different argument key order collapses to one signature instead of\n * counting as two \"distinct\" calls.\n *\n * ```ts\n * canonicalToolCallSignature({ function: { name: 'search', arguments: { q: 'x' } } })\n * // 'search({\"q\":\"x\"})'\n * ```\n */\nexport function canonicalToolCallSignature(toolCall: ToolCall): string {\n return `${toolCall.function.name}(${stableStringify(toolCall.function.arguments)})`;\n}\n\nfunction reportableSignature(signature: string): string {\n return signature.length <= SIGNATURE_REPORT_LIMIT\n ? signature\n : `${signature.slice(0, SIGNATURE_REPORT_LIMIT)}…`;\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 maxRepeatedToolCalls?: 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.maxRepeatedToolCalls = config.maxRepeatedToolCalls;\n this.hooks = config.hooks;\n if (\n this.maxToolCalls !== undefined &&\n (!Number.isInteger(this.maxToolCalls) || this.maxToolCalls < 0)\n ) {\n throw new RangeError('Agent maxToolCalls must be a non-negative integer');\n }\n if (\n this.maxRepeatedToolCalls !== undefined &&\n (!Number.isInteger(this.maxRepeatedToolCalls) || this.maxRepeatedToolCalls < 1)\n ) {\n throw new RangeError('Agent maxRepeatedToolCalls must be a positive 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 /** Canonical-signature execution counts for cycle detection — one entry per\n * distinct `name(args)` pair this run has handed to the registry. */\n const signatureCounts = new Map<string, number>();\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 (\n this.maxToolCalls !== undefined &&\n toolCallsExecuted + toolCalls.length > this.maxToolCalls\n ) {\n throw new OllamaAgentMaxToolCallsError(\n `Agent exceeded max tool calls (${this.maxToolCalls})`,\n { maxToolCalls: this.maxToolCalls, toolCallsExecuted },\n );\n }\n\n // Cycle detection: prospective per-signature counts for this batch\n // (duplicate calls within one batch see each other). Checked before\n // any of the batch executes and before onToolCallStart fires, so hook\n // pairing stays consistent and the doomed batch is never started —\n // mirroring the maxToolCalls semantics above.\n if (this.maxRepeatedToolCalls !== undefined) {\n for (const tc of toolCalls) {\n const signature = canonicalToolCallSignature(tc);\n const executions = (signatureCounts.get(signature) ?? 0) + 1;\n if (executions > this.maxRepeatedToolCalls) {\n throw new OllamaAgentToolLoopError(\n `Agent would repeat tool call \"${tc.function.name}\" ${executions} times ` +\n `(max ${this.maxRepeatedToolCalls}) without changing arguments — stuck in a tool loop`,\n {\n toolName: tc.function.name,\n repeatedExecutions: executions,\n maxRepeatedToolCalls: this.maxRepeatedToolCalls,\n signature: reportableSignature(signature),\n },\n );\n }\n signatureCounts.set(signature, executions);\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 * Speculative-decoding draft benchmark — measures whether the runtime\n * `draft_num_predict` option provides a net throughput gain for a specific\n * prompt (October 13 digest; see ADR 0030).\n *\n * Upstream Ollama does not emit a dedicated draft-token acceptance counter —\n * speculative efficiency is only observable as effective throughput\n * (`eval_count` / `eval_duration`). And the signal is noisy: rejected draft\n * predictions *add* compute (high-temperature, creative, non-deterministic\n * prompts), while accepted drafts dramatically cut `eval_duration` on\n * predictable workloads (structured code generation, JSON extraction). A\n * single run therefore proves nothing — this helper implements the\n * deterministic profiling protocol the upstream observations call for:\n *\n * - **Deterministic sampling** — `temperature: 0` is forced and a fixed\n * `seed` (default 42) is stamped on every measured run, so both sides\n * generate comparable token streams.\n * - **Warm-up discard** — one throwaway `num_predict: 1` generation per\n * setting pays the model load (`load_duration`) before any sample is\n * taken.\n * - **Identical prompt, both sides** — baseline (`draft_num_predict: 0`,\n * drafting disabled) vs. speculative (`draft_num_predict: N`), several\n * samples each, **median** compared (single samples mislead).\n * - Throughput comes from `formatTelemetry` — the official Usage-doc\n * tokens/second math, never hand-rolled nanosecond division.\n *\n * `effectiveGain` is true when the reported `speedupMultiplier` exceeds\n * `gainThreshold` (default 1.05 — five percent, past run-to-run noise). A\n * speedup of about 1.0 usually means the model has **no draft network** (and\n * no embedded MTP tensors): the server silently ignores the option and both\n * sides measure the same — see `lab/15-speculative-draft` for a per-setting\n * table over 0/4/8/16.\n *\n * ```ts\n * import { OllamaClient, compareDraftPerformance } from '@nemesis-oss/ollama-sdk';\n *\n * const comparison = await compareDraftPerformance(new OllamaClient(), {\n * model: 'llama3.1',\n * prompt: 'Extract the sender, subject, and date from this email as JSON: ...',\n * });\n * if (comparison.effectiveGain) {\n * // drafting pays off for this prompt\n * }\n * ```\n */\n\nimport { OllamaClientError } from './errors.js';\nimport { formatTelemetry } from './telemetry/index.js';\nimport type { GenerateRequestOptions, GenerateResponse } from './types.js';\n\n/**\n * Structural dependency of {@link compareDraftPerformance}: anything that can\n * run a non-streaming `/api/generate` call. `OllamaClient` satisfies it\n * without being named (same discipline as the model-affinity router's\n * structural client), so tests and alternative transports can substitute a\n * minimal object.\n */\nexport interface DraftBenchmarkClient {\n generate(req: GenerateRequestOptions & { stream?: false | undefined }): Promise<GenerateResponse>;\n}\n\n/** Options for {@link compareDraftPerformance}. */\nexport interface CompareDraftPerformanceOptions {\n /** Model to benchmark — must be a name the target server can load. */\n readonly model: string;\n /**\n * The prompt both sides generate. The comparison is only meaningful with a\n * fixed prompt: draft acceptance — and thus speedup — is workload-dependent\n * (structured/predictable prompts gain the most; creative ones can lose).\n */\n readonly prompt: string;\n /**\n * Draft tokens per step for the speculative side. Default `4` (Ollama's\n * default for separate draft models). Must be >= 1 — the baseline side\n * always measures with drafting disabled (`0`).\n */\n readonly draftNumPredict?: number | undefined;\n /**\n * Measured runs per setting; the median is reported. Default `5`. Single\n * samples mislead — noisy small-model runs swing tens of percent.\n */\n readonly samples?: number | undefined;\n /** `num_predict` cap per measured run. Default `256`. */\n readonly numPredict?: number | undefined;\n /** Fixed sampling seed stamped on every run (with `temperature: 0`). Default `42`. */\n readonly seed?: number | undefined;\n /**\n * Run one throwaway `num_predict: 1` generation per setting before sampling\n * (pays the model load). Default `true`.\n */\n readonly warmup?: boolean | undefined;\n /**\n * `speedupMultiplier` above this reports `effectiveGain: true`. Default\n * `1.05` — five percent, past typical run-to-run noise.\n */\n readonly gainThreshold?: number | undefined;\n /** Abort signal — checked before every run and forwarded to each generate call. */\n readonly signal?: AbortSignal | undefined;\n}\n\n/** One side's measurement detail (see {@link DraftPerformanceComparison}). */\nexport interface DraftRunStats {\n /** The `draft_num_predict` value this side ran with (`0` = baseline). */\n readonly draftNumPredict: number;\n /** Median tokens/second across the valid samples (unrounded). */\n readonly medianTokensPerSecond: number;\n /** Every valid sample's tokens/second, in run order. */\n readonly sampleTokensPerSecond: readonly number[];\n /** Median generation-phase duration (`eval_duration`) in milliseconds. */\n readonly medianEvalDurationMs: number;\n}\n\n/** Result of {@link compareDraftPerformance}. */\nexport interface DraftPerformanceComparison {\n /** The model that was benchmarked. */\n readonly model: string;\n /** The prompt both sides generated. */\n readonly prompt: string;\n /** The speculative side's `draft_num_predict` (the baseline always ran `0`). */\n readonly draftNumPredict: number;\n /** Baseline median tokens/second, rounded to 1 decimal. */\n readonly baselineTokensPerSec: number;\n /** Speculative median tokens/second, rounded to 1 decimal. */\n readonly speculativeTokensPerSec: number;\n /** `speculativeTokensPerSec / baselineTokensPerSec`, rounded to 2 decimals. */\n readonly speedupMultiplier: number;\n /** `true` when the reported `speedupMultiplier` exceeds `gainThreshold`. */\n readonly effectiveGain: boolean;\n /** The threshold `effectiveGain` was evaluated against. */\n readonly gainThreshold: number;\n /** Full baseline detail (samples, medians). */\n readonly baseline: DraftRunStats;\n /** Full speculative detail (samples, medians). */\n readonly speculative: DraftRunStats;\n}\n\nconst DEFAULT_DRAFT_TOKENS = 4;\nconst DEFAULT_SAMPLES = 5;\nconst DEFAULT_NUM_PREDICT = 256;\nconst DEFAULT_SEED = 42;\nconst DEFAULT_GAIN_THRESHOLD = 1.05;\n\nfunction median(values: readonly number[]): number {\n const sorted = [...values].sort((a, b) => a - b);\n const mid = Math.floor(sorted.length / 2);\n return sorted.length % 2 === 1\n ? (sorted[mid] ?? 0)\n : ((sorted[mid - 1] ?? 0) + (sorted[mid] ?? 0)) / 2;\n}\n\nfunction roundTo(value: number, decimals: number): number {\n const factor = 10 ** decimals;\n return Math.round(value * factor) / factor;\n}\n\nfunction requirePositiveInteger(name: string, value: number): void {\n if (!Number.isInteger(value) || value < 1) {\n throw new RangeError(\n `compareDraftPerformance: ${name} must be an integer >= 1 (got ${value}).`,\n );\n }\n}\n\nasync function runSide(\n client: DraftBenchmarkClient,\n options: CompareDraftPerformanceOptions,\n draftNumPredict: number,\n samples: number,\n numPredict: number,\n seed: number,\n): Promise<DraftRunStats> {\n const samplingOptions = {\n num_predict: numPredict,\n temperature: 0,\n seed,\n draft_num_predict: draftNumPredict,\n };\n\n if (options.warmup ?? true) {\n // Throwaway run: pays the model load (`load_duration`) so the measured\n // samples reflect steady-state generation, not cold-start I/O.\n await client.generate({\n model: options.model,\n prompt: options.prompt,\n options: { ...samplingOptions, num_predict: 1 },\n stream: false,\n signal: options.signal,\n });\n }\n\n const tokensPerSecond: number[] = [];\n const generationMs: number[] = [];\n for (let i = 0; i < samples; i++) {\n options.signal?.throwIfAborted();\n const response = await client.generate({\n model: options.model,\n prompt: options.prompt,\n options: samplingOptions,\n stream: false,\n signal: options.signal,\n });\n const telemetry = formatTelemetry(response);\n if (Number.isFinite(telemetry.tokensPerSecond) && telemetry.tokensPerSecond > 0) {\n tokensPerSecond.push(telemetry.tokensPerSecond);\n generationMs.push(telemetry.generationMs);\n }\n }\n\n if (tokensPerSecond.length === 0) {\n throw new OllamaClientError(\n `compareDraftPerformance: every draft_num_predict=${draftNumPredict} sample returned a ` +\n `non-positive tokens/second. The model name is likely wrong, or the server returned ` +\n `empty generations.`,\n { code: 'draft_benchmark_no_valid_samples' },\n );\n }\n\n return {\n draftNumPredict,\n medianTokensPerSecond: median(tokensPerSecond),\n sampleTokensPerSecond: tokensPerSecond,\n medianEvalDurationMs: median(generationMs),\n };\n}\n\n/**\n * Measure whether speculative drafting pays off for a specific prompt:\n * identical prompt, deterministic sampling (`temperature: 0` + fixed `seed`),\n * warm-up discard, several samples per setting, median baseline\n * (`draft_num_predict: 0`) vs. median speculative (`draft_num_predict: N`)\n * compared as `speedupMultiplier`.\n *\n * Both sides run through the client's non-streaming `generate` — the raw\n * counters come back on the response and throughput is derived by\n * `formatTelemetry`. Non-positive/unusable samples are skipped; if a side\n * ends up with none, an `OllamaClientError` explains why (wrong model name /\n * empty generations) rather than reporting a fabricated zero.\n */\nexport async function compareDraftPerformance(\n client: DraftBenchmarkClient,\n options: CompareDraftPerformanceOptions,\n): Promise<DraftPerformanceComparison> {\n const draftNumPredict = options.draftNumPredict ?? DEFAULT_DRAFT_TOKENS;\n requirePositiveInteger('draftNumPredict', draftNumPredict);\n const samples = options.samples ?? DEFAULT_SAMPLES;\n requirePositiveInteger('samples', samples);\n const numPredict = options.numPredict ?? DEFAULT_NUM_PREDICT;\n requirePositiveInteger('numPredict', numPredict);\n const seed = options.seed ?? DEFAULT_SEED;\n if (!Number.isInteger(seed)) {\n throw new RangeError(`compareDraftPerformance: seed must be an integer (got ${seed}).`);\n }\n const gainThreshold = options.gainThreshold ?? DEFAULT_GAIN_THRESHOLD;\n if (!Number.isFinite(gainThreshold) || gainThreshold <= 0) {\n throw new RangeError(\n `compareDraftPerformance: gainThreshold must be a positive finite number (got ${gainThreshold}).`,\n );\n }\n\n options.signal?.throwIfAborted();\n\n // Baseline first, then speculative — a fixed order keeps runs reproducible\n // (identical prompts, deterministic sampling, shared warm-VRAM state).\n const baseline = await runSide(client, options, 0, samples, numPredict, seed);\n const speculative = await runSide(client, options, draftNumPredict, samples, numPredict, seed);\n\n // The reported numbers are self-consistent: the multiplier divides the two\n // rounded medians, and `effectiveGain` compares that reported multiplier\n // against the threshold.\n const baselineTokensPerSec = roundTo(baseline.medianTokensPerSecond, 1);\n const speculativeTokensPerSec = roundTo(speculative.medianTokensPerSecond, 1);\n const speedupMultiplier =\n baselineTokensPerSec > 0 ? roundTo(speculativeTokensPerSec / baselineTokensPerSec, 2) : 0;\n\n return {\n model: options.model,\n prompt: options.prompt,\n draftNumPredict,\n baselineTokensPerSec,\n speculativeTokensPerSec,\n speedupMultiplier,\n effectiveGain: speedupMultiplier > gainThreshold,\n gainThreshold,\n baseline,\n speculative,\n };\n}\n","/**\n * Model-affinity scheduling: keep the daemon's working set small.\n *\n * Ollama's concurrency model (per the official FAQ):\n *\n * - A model's KV cache scales by `OLLAMA_NUM_PARALLEL × context_length` —\n * parallel requests to the *same* loaded model are cheap (each gets its\n * own slot of the already-allocated cache).\n * - Requests for a *different* model queue until the first goes idle or is\n * evicted (`OLLAMA_MAX_LOADED_MODELS`, default 3× GPU count) — a swap is\n * an expensive unload/cold-load cycle: seconds of VRAM churn that a\n * concurrent multi-model workload pays again and again when it\n * interleaves models arbitrarily.\n * - Once `OLLAMA_MAX_QUEUE` (default 512) requests are waiting, new ones\n * are rejected outright with 503s.\n *\n * `ModelAffinityScheduler` is the client-side counterpart for workloads that\n * juggle several models — extraction on a coder model, reasoning on a\n * thinking model, embeddings for retrieval. It groups tasks into per-model\n * serial queues and caps how many *distinct* models have work in flight\n * (`concurrentModels`, default 1), preferring to deepen the currently-active\n * model over starting the next one — the anti-thrashing order. Candidate\n * lists let a task run on whichever of several interchangeable models is\n * already loaded (`GET /api/ps`, cached with a TTL).\n *\n * It is a user-space primitive, deliberately not wired into `OllamaClient`'s\n * request path: affinity decisions are workload policy, and the scheduler is\n * the foundation the multi-instance routing work builds on. See ADR 0026.\n */\n\nimport { OllamaClientError } from './errors.js';\nimport type { OllamaClient } from './client.js';\n\n/**\n * The minimal client surface the scheduler needs. `OllamaClient` satisfies it\n * structurally; tests and custom setups can pass any compatible object.\n */\nexport interface ModelAffinityClient {\n readonly models: {\n ps(): Promise<{ readonly models: ReadonlyArray<{ readonly name: string }> }>;\n };\n}\n\n/** Options for {@link ModelAffinityScheduler}. */\nexport interface ModelAffinitySchedulerOptions {\n /**\n * Maximum number of *distinct* models with work in flight at once\n * (default `1`). `1` is the anti-thrashing setting: one model stays hot\n * until its queue drains, then the next loads. Raise it only when the\n * host has VRAM for several concurrent models\n * (`OLLAMA_MAX_LOADED_MODELS`).\n */\n readonly concurrentModels?: number | undefined;\n /**\n * Parallel tasks allowed per active model (default `1`). Raising this\n * mirrors the server's own `OLLAMA_NUM_PARALLEL` — same-model parallelism\n * reuses the loaded weights without swap cost.\n */\n readonly perModelConcurrency?: number | undefined;\n /**\n * How long a `GET /api/ps` result is reused when choosing among candidate\n * models (default `30_000` ms). Only multi-candidate `run()` calls and\n * `loadedModels()` consult the server; single-model tasks never do.\n */\n readonly psCacheTtlMs?: number | undefined;\n}\n\n/** Live scheduling state, from {@link ModelAffinityScheduler.stats}. */\nexport interface ModelAffinityStats {\n /** Models with at least one task currently executing. */\n readonly activeModels: readonly string[];\n /** Tasks waiting in queues (not yet started). */\n readonly queuedTasks: number;\n}\n\ninterface TaskEntry {\n readonly task: (model: string) => Promise<unknown>;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n}\n\ninterface ModelQueue {\n readonly items: TaskEntry[];\n active: number;\n}\n\nconst DEFAULT_CONCURRENT_MODELS = 1;\nconst DEFAULT_PER_MODEL_CONCURRENCY = 1;\nconst DEFAULT_PS_CACHE_TTL_MS = 30_000;\n\n/**\n * Groups async work by model with load-aware dispatch.\n *\n * ```ts\n * const scheduler = new ModelAffinityScheduler(client);\n *\n * // Serial queue per model; one model hot at a time (default):\n * await scheduler.run('deepseek-r1', () => reason(client));\n * await scheduler.run('qwen2.5:coder', () => extract(client));\n *\n * // Either-or: picks whichever candidate is already loaded (/api/ps):\n * const summary = await scheduler.run(\n * ['qwen2.5:coder', 'qwen2.5:14b'],\n * (model) => extractWith(client, model),\n * );\n * ```\n *\n * Dispatch order is **affinity-sticky, not round-robin**: when a queued\n * model is already active, its tasks start before a different model's (up to\n * `perModelConcurrency`), because deepening the hot model avoids a swap.\n * Tasks run in FIFO order within each model's queue. Task functions are the\n * caller's own — the scheduler adds no retry, timeout, or failover, and a\n * rejected task simply rejects its `run()` promise while its siblings\n * proceed.\n */\nexport class ModelAffinityScheduler {\n private readonly queues = new Map<string, ModelQueue>();\n private readonly concurrentModels: number;\n private readonly perModelConcurrency: number;\n private readonly psCacheTtlMs: number;\n private psCache: { at: number; names: ReadonlySet<string> } | undefined;\n private readonly drainWaiters: Array<() => void> = [];\n\n constructor(\n private readonly client: ModelAffinityClient,\n options: ModelAffinitySchedulerOptions = {},\n ) {\n this.concurrentModels = options.concurrentModels ?? DEFAULT_CONCURRENT_MODELS;\n this.perModelConcurrency = options.perModelConcurrency ?? DEFAULT_PER_MODEL_CONCURRENCY;\n this.psCacheTtlMs = options.psCacheTtlMs ?? DEFAULT_PS_CACHE_TTL_MS;\n if (!Number.isInteger(this.concurrentModels) || this.concurrentModels < 1) {\n throw new OllamaClientError('concurrentModels must be an integer >= 1.', {\n code: 'invalid_request',\n });\n }\n if (!Number.isInteger(this.perModelConcurrency) || this.perModelConcurrency < 1) {\n throw new OllamaClientError('perModelConcurrency must be an integer >= 1.', {\n code: 'invalid_request',\n });\n }\n if (!Number.isFinite(this.psCacheTtlMs) || this.psCacheTtlMs < 0) {\n throw new OllamaClientError('psCacheTtlMs must be a non-negative number.', {\n code: 'invalid_request',\n });\n }\n }\n\n /**\n * Runs `task` on the scheduler, serialized per model. When `model` is a\n * list of candidates, the already-loaded one is preferred (fresh\n * `/api/ps` data subject to the TTL cache); with none loaded — or when the\n * lookup fails — the first candidate runs. The chosen model is handed to\n * the task.\n */\n async run<T>(model: string | readonly string[], task: (model: string) => Promise<T>): Promise<T> {\n const candidates = typeof model === 'string' ? [model] : [...model];\n if (\n candidates.length === 0 ||\n candidates.some((name) => typeof name !== 'string' || name === '')\n ) {\n throw new OllamaClientError('run() requires at least one non-empty model name.', {\n code: 'invalid_request',\n });\n }\n const chosen =\n candidates.length === 1 ? candidates[0]! : await this.chooseCandidate(candidates);\n return new Promise<T>((resolve, reject) => {\n const queue = this.queues.get(chosen) ?? { items: [], active: 0 };\n this.queues.set(chosen, queue);\n queue.items.push({\n task: task as (model: string) => Promise<unknown>,\n resolve: resolve as (value: unknown) => void,\n reject,\n });\n this.pump();\n });\n }\n\n /**\n * Names of the models currently loaded, per `GET /api/ps`, cached for\n * `psCacheTtlMs`. Degrades to an empty list when the server can't answer\n * (never throws; candidate selection treats it as \"nothing loaded\").\n */\n async loadedModels(): Promise<readonly string[]> {\n const names = await this.refreshPsNames();\n return [...names];\n }\n\n /** Current scheduling state — active models and queued task count. */\n get stats(): ModelAffinityStats {\n const activeModels: string[] = [];\n let queuedTasks = 0;\n for (const [name, queue] of this.queues) {\n if (queue.active > 0) activeModels.push(name);\n queuedTasks += queue.items.length;\n }\n return { activeModels, queuedTasks };\n }\n\n /**\n * Resolves once every queue is empty and no task is running. Does not\n * abort anything — tasks are caller-owned; abort them via their own\n * signals before disposing if needed.\n */\n async dispose(): Promise<void> {\n if (this.stats.queuedTasks === 0 && this.stats.activeModels.length === 0) return;\n await new Promise<void>((resolve) => {\n this.drainWaiters.push(resolve);\n });\n }\n\n private async chooseCandidate(candidates: readonly string[]): Promise<string> {\n const loaded = await this.refreshPsNames();\n for (const candidate of candidates) {\n if (loaded.has(candidate)) return candidate;\n }\n return candidates[0]!;\n }\n\n private async refreshPsNames(): Promise<ReadonlySet<string>> {\n const now = Date.now();\n if (this.psCache !== undefined && now - this.psCache.at <= this.psCacheTtlMs) {\n return this.psCache.names;\n }\n let names: ReadonlySet<string>;\n try {\n const ps = await this.client.models.ps();\n names = new Set(ps.models.map((entry) => entry.name));\n } catch {\n // Unreachable server, compat-only endpoint, auth hiccup — affinity\n // routing is best-effort. Degrade to \"nothing loaded\" without caching\n // the failure, so the next call retries.\n return new Set();\n }\n this.psCache = { at: now, names };\n return names;\n }\n\n private pump(): void {\n // Map iteration order = queue creation order, so dispatch is stable and\n // FIFO across models. An already-active model is allowed to deepen (up\n // to perModelConcurrency) even at the concurrentModels cap — that IS the\n // affinity: keep the hot model hot. The distinct-active count is\n // recomputed per check because tasks started earlier in this same pass\n // (or by concurrent completions) must count.\n for (const [name, queue] of this.queues) {\n while (queue.items.length > 0 && queue.active < this.perModelConcurrency) {\n if (queue.active === 0 && this.activeModelCount() >= this.concurrentModels) {\n break; // starting this model would exceed the distinct-models cap\n }\n const entry = queue.items.shift()!;\n queue.active += 1;\n this.execute(name, queue, entry);\n }\n }\n }\n\n private activeModelCount(): number {\n let count = 0;\n for (const queue of this.queues.values()) {\n if (queue.active > 0) count += 1;\n }\n return count;\n }\n\n private execute(name: string, queue: ModelQueue, entry: TaskEntry): void {\n void (async () => {\n try {\n entry.resolve(await entry.task(name));\n } catch (err) {\n entry.reject(err);\n } finally {\n queue.active -= 1;\n if (queue.items.length === 0 && queue.active === 0) {\n this.queues.delete(name);\n }\n if (this.stats.queuedTasks === 0 && this.stats.activeModels.length === 0) {\n const waiters = [...this.drainWaiters];\n this.drainWaiters.length = 0;\n for (const resolve of waiters) resolve();\n }\n this.pump();\n }\n })();\n }\n}\n\n/** Convenience factory — `createModelAffinityScheduler(client, opts)` reads better in setups. */\nexport function createModelAffinityScheduler(\n client: ModelAffinityClient | OllamaClient,\n options?: ModelAffinitySchedulerOptions,\n): ModelAffinityScheduler {\n return new ModelAffinityScheduler(client as ModelAffinityClient, options);\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"]}
|
|
1
|
+
{"version":3,"sources":["../src/transport/host.ts","../src/config.ts","../src/errors.ts","../src/logger.ts","../src/providers/endpoint-registry.ts","../src/transport/url.ts","../src/middleware.ts","../src/vision.ts","../src/utils.ts","../src/streaming/ndjson.ts","../src/streaming/sse.ts","../src/telemetry/tracer.ts","../src/telemetry/metrics.ts","../src/transport/http.ts","../src/providers/health-check.ts","../src/capabilities/capabilities.ts","../src/context-safety.ts","../src/context-discovery.ts","../src/providers/model-affinity-router.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/embed-batch.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/streaming/observe.ts","../src/quota.ts","../src/tools/define-tool.ts","../src/tools/registry.ts","../src/tools/web-tools.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/draft-benchmark.ts","../src/affinity.ts","../src/system-one.ts"],"names":["message","dispatch","response","exceeds","check","controller","z","sleep","positiveInt"],"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,c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QAAA,IAAA,CAAK,IAAA,EAAK;AAAA,MACZ;AAAA,IACF,CAAA,GAAG;AAAA,EACL;AACF;AAGO,SAAS,4BAAA,CACd,QACA,OAAA,EACwB;AACxB,EAAA,OAAO,IAAI,sBAAA,CAAuB,MAAA,EAA+B,OAAO,CAAA;AAC1E;;;AC3MO,IAAM,2BAAA,GAA8B,KAAK,IAAA,GAAO;AAQhD,IAAM,+BAA+B,EAAA,GAAK;AAgI1C,SAAS,8BACd,OAAA,EACQ;AASR,EAAA,OAAO,IAAI,aAAY,CAAE,MAAA,CAAO,KAAK,SAAA,CAAU,OAAO,CAAC,CAAA,CAAE,UAAA;AAC3D","file":"index.js","sourcesContent":["/**\n * Host normalization and credential-scoping helpers for 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\n/**\n * Thrown when the agent's cycle detection fires: the same tool call —\n * identical name **and** identical arguments — would execute more times than\n * `maxRepeatedToolCalls` allows during one run.\n *\n * This is the fail-fast diagnosis for a model stuck in a tool loop (repeatedly\n * calling the same function with the same arguments, never reacting to the\n * results); without it, a looping model only surfaces as a generic\n * {@link OllamaAgentMaxIterationsError} after burning the full iteration\n * budget on wasted calls.\n */\nexport class OllamaAgentToolLoopError extends OllamaClientError {\n /** Name of the tool whose identical call would exceed the repeat budget. */\n readonly toolName: string;\n /** How many times this exact call would have executed including the rejected one. */\n readonly repeatedExecutions: number;\n /** The configured per-signature execution budget. */\n readonly maxRepeatedToolCalls: number;\n /** Canonical `name(args)` signature of the repeated call (very large payloads truncated). */\n readonly signature: string;\n\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n toolName: string;\n repeatedExecutions: number;\n maxRepeatedToolCalls: number;\n signature: string;\n },\n ) {\n super(message, { ...options, code: 'agent_tool_loop_detected', retryable: false });\n this.toolName = options.toolName;\n this.repeatedExecutions = options.repeatedExecutions;\n this.maxRepeatedToolCalls = options.maxRepeatedToolCalls;\n this.signature = options.signature;\n }\n}\n\nexport class OllamaMcpError extends OllamaClientError {\n readonly mcpMethod:\n 'listTools' | 'callTool' | 'tools/call' | 'tasks/get' | 'tasks/result' | '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' | 'callTool' | 'tools/call' | 'tasks/get' | 'tasks/result' | '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\n/**\n * Error `code`s that mean the transport never delivered a usable response —\n * the request died at the socket/connection layer. This is the stale-socket\n * family: keep-alive connections recycled by a restarting/idle-timeouting\n * daemon (`ECONNRESET`, `EPIPE`, undici's `UND_ERR_SOCKET`/`UND_ERR_CLOSED`\n * when the pooled socket is reused after the server closed it), connections\n * that never established (`ECONNREFUSED`, `EAI_AGAIN`, `ENOTFOUND`), and\n * connect/header/body timeouts from the undici dispatcher.\n *\n * `UND_ERR_ABORTED` is deliberately NOT here: it is the dispatcher's shape\n * for caller-initiated aborts, which map to `OllamaAbortError` (never\n * retried) — classifying it as a network failure would re-dispatch requests\n * the caller explicitly cancelled.\n */\nexport const NETWORK_ERROR_CODES: ReadonlySet<string> = new Set([\n 'ECONNRESET',\n 'ECONNREFUSED',\n 'EPIPE',\n 'ETIMEDOUT',\n 'ECONNABORTED',\n 'EHOSTUNREACH',\n 'ENETUNREACH',\n 'ENOTFOUND',\n 'EAI_AGAIN',\n 'UND_ERR_SOCKET',\n 'UND_ERR_CONNECT_TIMEOUT',\n 'UND_ERR_HEADERS_TIMEOUT',\n 'UND_ERR_BODY_TIMEOUT',\n 'UND_ERR_CLOSED',\n]);\n\n/** How many `cause` links to walk looking for a network-level `code`. */\nconst MAX_CAUSE_DEPTH = 4;\n\n/**\n * Structural network-failure detection: looks for a `code` from\n * {@link NETWORK_ERROR_CODES} on the error itself or anywhere down its\n * `cause` chain (bounded depth — cause cycles must not spin forever).\n *\n * Deliberately does NOT match on message text (`String(err).includes(...)`\n * style): undici/Node message wording is not a stable contract across\n * versions, while `error.code` is. Custom `fetch` implementations built on\n * `node:http` reject with these codes natively (WHATWG `fetch` wraps them in\n * a `TypeError`, which `mapError` already classifies); this predicate closes\n * the gap for the non-`TypeError` shapes.\n */\nexport function isNetworkLevelError(error: unknown): boolean {\n let current: unknown = error;\n for (\n let depth = 0;\n depth < MAX_CAUSE_DEPTH && current !== undefined && current !== null;\n depth += 1\n ) {\n if (typeof current === 'object' && 'code' in current) {\n const code = (current as { code?: unknown }).code;\n if (typeof code === 'string' && NETWORK_ERROR_CODES.has(code)) {\n return true;\n }\n }\n current = (current as { cause?: unknown }).cause;\n }\n return false;\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 // Socket/connection-level failures — including the non-TypeError shapes a\n // custom `fetch` implementation produces (`Error` + `code: 'ECONNRESET'`\n // and friends) and network codes nested in `cause` chains. Checked before\n // the `TypeError` branch so a code-carrying TypeError maps through the same\n // specialized construction with a better message. Retryable + failover-eligible.\n if (isNetworkLevelError(error)) {\n const message =\n error instanceof Error && error.message ? error.message : 'Network request failed';\n return new OllamaNetworkError(message, {\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';\nimport type { ModelAffinityRoutingOptions } from './model-affinity-router.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 * Dynamic model-affinity routing across endpoints: reorder each request's\n * candidates so endpoints whose `GET /api/ps` shows the requested model already\n * resident in VRAM are tried first — avoiding unload/cold-load swaps on\n * `OLLAMA_MAX_LOADED_MODELS`-bounded daemons. Off unless set.\n *\n * Implemented by `OllamaClient`'s request path (`executeWithFailover` + a\n * TTL-cached `ModelAffinityRouter`), not by this registry — the registry is a\n * pure, HTTP-free data structure and simply ignores this key. See\n * `src/providers/model-affinity-router.ts` and ADR 0028.\n */\n readonly modelAffinity?: ModelAffinityRoutingOptions | 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 URL assembly for the HTTP transport.\n *\n * Ollama is frequently deployed behind a reverse proxy under a path prefix\n * (`https://gateway.internal.corp/ai/ollama`). The transport therefore joins\n * base URLs and request paths by explicit string concatenation — never via\n * `new URL(path, base)`, whose WHATWG semantics discard the base's path\n * segments whenever the path is absolute (`new URL('/api/chat', base)`).\n *\n * {@link joinUrlPath} is the single place that owns the join, so the\n * \"exactly one slash between the base and the path\" invariant holds even if\n * a base URL slips through with a trailing slash or a future call site\n * passes a path without its leading slash.\n */\n\n/**\n * Joins a base URL and a request path with exactly one slash.\n *\n * - Any number of trailing slashes on `baseUrl` and leading slashes on\n * `path` are collapsed, so `https://host/ai/ollama/` + `/api/chat`,\n * `https://host/ai/ollama` + `/api/chat`, and `https://host/ai/ollama`\n * + `api/chat` all produce `https://host/ai/ollama/api/chat` — a proxy\n * mount prefix is always preserved.\n * - A path may carry a query string (`/api/usage?bucket=24h`); it is\n * concatenated untouched after the join.\n * - An empty path yields the base unchanged (trailing slashes stripped).\n */\nexport function joinUrlPath(baseUrl: string, path: string): string {\n const base = baseUrl.replace(/\\/+$/, '');\n const tail = path.replace(/^\\/+/, '');\n if (tail === '') return base;\n if (base === '') return `/${tail}`;\n return `${base}/${tail}`;\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 * - `Uint8Array` — raw image bytes, base64-encoded automatically. Node\n * `Buffer` is a `Uint8Array` subclass, so buffers are accepted everywhere\n * bytes are — without importing Node types into consumer compilations: the\n * published declarations stay free of `@types/node` globals (audit TYP-03).\n */\nexport type VisionInput = string | 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 * Standardized telemetry normalizer — raw nanosecond counters to derived metrics.\n *\n * Ollama reports every duration as an **integer in nanoseconds** on its generation\n * responses (`total_duration`, `load_duration`, `prompt_eval_duration`,\n * `eval_duration` — see the official \"Usage\" documentation), plus token counters\n * (`prompt_eval_count`, `prompt_eval_cached_count`, `eval_count`). Consumers that\n * want milliseconds, tokens/second, or a cache-hit ratio otherwise each reimplement\n * the same division-and-rounding math — this module is that math, once, with the\n * formulas the official docs spell out:\n *\n * - `tokensPerSecond` = `eval_count / (eval_duration / 1e9)` — generation throughput.\n * - `promptTokensPerSecond` = `prompt_eval_count / (prompt_eval_duration / 1e9)` —\n * prompt ingestion (pre-fill) throughput.\n * - `cacheHitRatio` = `prompt_eval_cached_count / (cached + evaluated)` — see the\n * note on {@link FormattedTelemetry.cacheHitRatio} for why the denominator is the\n * *sum*, not `prompt_eval_count` alone.\n *\n * Pure and dependency-free: {@link formatTelemetry} never fetches, never throws, and\n * treats every missing counter as `0` — partial responses (stream final events,\n * older servers without `prompt_eval_cached_count`) format cleanly instead of\n * producing `NaN`/`Infinity`.\n *\n * The input is structural: any response object carrying these optional fields —\n * `GenerateResponse`, `ChatResponse`, the final `GenerateStreamEvent`,\n * `EmbedResponse` — can be passed directly, no picking/plucking required.\n */\n\n/**\n * The raw nanosecond/token counters Ollama attaches to generation responses. Every\n * field is optional because servers report a subset: streaming final events may omit\n * load counters, older builds predate `prompt_eval_cached_count`, and embeddings\n * carry no `eval_count`. Accepts full response objects structurally.\n */\nexport interface RawOllamaMetrics {\n /** Total end-to-end request latency, nanoseconds. */\n readonly total_duration?: number | undefined;\n /** Model cold-load and weight-transfer time into VRAM, nanoseconds. */\n readonly load_duration?: number | undefined;\n /** Prompt tokens freshly evaluated this request (not served from the KV cache). */\n readonly prompt_eval_count?: number | undefined;\n /** Prompt tokens served from the KV prompt cache (prefix reuse). */\n readonly prompt_eval_cached_count?: number | undefined;\n /** Prompt ingestion / pre-fill processing time, nanoseconds. */\n readonly prompt_eval_duration?: number | undefined;\n /** Tokens generated (the response proper). */\n readonly eval_count?: number | undefined;\n /** Token generation time, nanoseconds. */\n readonly eval_duration?: number | undefined;\n}\n\n/** The normalized, human-scale view of one response's {@link RawOllamaMetrics}. */\nexport interface FormattedTelemetry {\n /** `total_duration` in milliseconds, 2 decimals. */\n readonly totalLatencyMs: number;\n /** `load_duration` in milliseconds, 2 decimals — 0 when the model was already resident. */\n readonly modelLoadMs: number;\n /** `prompt_eval_duration` in milliseconds, 2 decimals. */\n readonly promptEvalMs: number;\n /** `eval_duration` in milliseconds, 2 decimals. */\n readonly generationMs: number;\n /** `eval_count / eval_duration` in tokens/second, 1 decimal — 0 when either is absent. */\n readonly tokensPerSecond: number;\n /** `prompt_eval_count / prompt_eval_duration` in tokens/second, 1 decimal. */\n readonly promptTokensPerSecond: number;\n /**\n * Share of prompt tokens served from the KV cache:\n * `cached / (cached + evaluated)`, 3 decimals.\n *\n * The denominator is the **sum**, not `prompt_eval_count` alone, because Ollama\n * reports `prompt_eval_count: 0` on a *full* cache hit — the same house semantics\n * as `ConversationSession`'s `cacheStats.hitRate` (see `src/conversation.ts`). A\n * `cached / prompt_eval_count` formula would report a perfect cache as `0`.\n */\n readonly cacheHitRatio: number;\n}\n\n/** Nanoseconds → milliseconds, rounded to 2 decimals; absent/zero stays `0`. */\nfunction nsToMs(ns: number | undefined): number {\n return ns ? Math.round((ns / 1e6) * 100) / 100 : 0;\n}\n\n/**\n * Derives the standardized metrics summary from one response's raw nanosecond\n * counters. Pure — never throws, never fetches; every missing counter reads as `0`.\n *\n * ```ts\n * const res = await client.chat({ model: 'llama3.2', messages });\n * const t = formatTelemetry(res);\n * console.log(t.tokensPerSecond, 'tok/s |', t.totalLatencyMs, 'ms |',\n * `${Math.round(t.cacheHitRatio * 100)}% prompt cache hit`);\n * ```\n */\nexport function formatTelemetry(raw: RawOllamaMetrics): FormattedTelemetry {\n const evalDurationSec = raw.eval_duration ? raw.eval_duration / 1e9 : 0;\n const promptDurationSec = raw.prompt_eval_duration ? raw.prompt_eval_duration / 1e9 : 0;\n\n const promptEvaluated = raw.prompt_eval_count ?? 0;\n const promptCached = raw.prompt_eval_cached_count ?? 0;\n const promptTotal = promptCached + promptEvaluated;\n\n return {\n totalLatencyMs: nsToMs(raw.total_duration),\n modelLoadMs: nsToMs(raw.load_duration),\n promptEvalMs: nsToMs(raw.prompt_eval_duration),\n generationMs: nsToMs(raw.eval_duration),\n tokensPerSecond:\n evalDurationSec > 0 && raw.eval_count\n ? Math.round((raw.eval_count / evalDurationSec) * 10) / 10\n : 0,\n promptTokensPerSecond:\n promptDurationSec > 0 && promptEvaluated\n ? Math.round((promptEvaluated / promptDurationSec) * 10) / 10\n : 0,\n cacheHitRatio: promptTotal > 0 ? Math.round((promptCached / promptTotal) * 1000) / 1000 : 0,\n };\n}\n","/**\n * Native fetch HTTP transport client for Ollama API.\n */\n\nimport { normalizeBaseUrl } from './host.js';\nimport { joinUrlPath } from './url.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\n/**\n * Structural (realm-safe) guard for web `ReadableStream` bodies. Undici\n * requires `duplex: 'half'` on the fetch init whenever the body is a stream\n * (Node 18+; without it the request throws before any bytes hit the wire),\n * and the same init member is now part of the WHATWG fetch spec — harmless\n * in browsers. Duck-typing on `getReader` avoids cross-realm `instanceof`\n * misses: a stream created inside a worker/VM context is still a stream to\n * undici, and `instanceof` across realms would silently skip the member.\n */\nfunction isWebReadableStreamBody(body: unknown): body is ReadableStream<Uint8Array> {\n return (\n typeof body === 'object' &&\n body !== null &&\n typeof (body as { getReader?: unknown }).getReader === 'function'\n );\n}\n\n/**\n * `RequestInit` plus the `duplex` member this project's `@types/node`\n * `RequestInit` doesn't carry yet (`@types/node` 22's undici types predate\n * its promotion into the shared init shape). Node's fetch reads it at\n * runtime regardless of the TS declaration — the intersection type just\n * makes the assignment legal at compile time. Assignable to plain\n * `RequestInit`, so `FetchLike` call sites need no casts.\n */\ntype FetchInitWithDuplex = RequestInit & { readonly duplex?: 'half' };\n\n/** Shared fetch-init builder for the middleware and no-middleware paths. */\nfunction buildFetchInit(req: RequestContext): FetchInitWithDuplex {\n return {\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 ...(isWebReadableStreamBody(req.body) ? { duplex: 'half' } : {}),\n };\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 (\n req: RequestContext,\n ): Promise<{\n status: number;\n headers: Record<string, string>;\n body: Response;\n }> => {\n const response = await this.fetchImpl(req.url, buildFetchInit(req));\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, buildFetchInit(request));\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 (context.status !== response.status || !sameHeaders(context.headers, response.headers)) {\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 = joinUrlPath(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 = joinUrlPath(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 = joinUrlPath(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\n/**\n * Scans `/api/show`'s `model_info` for the model's **native** context length\n * (keys are architecture-prefixed: `llama.context_length`,\n * `gemma4.context_length`, …). Also re-exported by `src/context-discovery.ts`\n * as `extractNativeContextLength` for the context-window discovery flow.\n */\nexport function 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 * 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/**\n * Rough per-message framing overhead: role tags, chat-template delimiters.\n */\nexport const MESSAGE_OVERHEAD_TOKENS = 4;\n\nexport function 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 * Present only when `exceedsThreshold` is `true`: the smallest power-of-two\n * window with ~30% generation headroom above the estimate (see\n * {@link recommendContextWindow}). A starting point, not a verdict — check\n * the model's native ceiling with `client.models.getContextLength()` before\n * adopting it; a prompt that outgrows the native maximum needs compaction\n * or history truncation, not a bigger `num_ctx`.\n */\n readonly recommendedNumCtx?: number | undefined;\n}\n\n/**\n * Smallest power-of-two context window that comfortably fits\n * `estimatedTokens` — ~30% headroom for the response, floored at 4096 (the\n * common modern server default when `num_ctx` is unset).\n *\n * Uses an exact doubling loop rather than\n * `Math.pow(2, Math.ceil(Math.log2(x)))`: floating-point `log2` of exact\n * powers of two can land marginally above the integer (e.g.\n * `Math.log2(8) > 3` on some platforms), which rounds a perfect fit *up* a\n * whole power of two. The loop has no such boundary bugs.\n *\n * Non-finite / non-positive inputs return the 4096 floor rather than throwing:\n * callers use this to *suggest* a window after their own estimate already\n * flagged a problem, so garbage-in should degrade to a conservative\n * suggestion, not a second error path.\n */\nexport function recommendContextWindow(estimatedTokens: number): number {\n if (!Number.isFinite(estimatedTokens) || estimatedTokens <= 0) return 4096;\n const target = estimatedTokens * 1.3;\n let window = 4096;\n while (window < target) window *= 2;\n return window;\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 const exceeds = estimatedPromptTokens > requestNumCtx * threshold;\n return {\n estimatedPromptTokens,\n effectiveContextLength: requestNumCtx,\n windowSource: 'request',\n exceedsThreshold: exceeds,\n ...(exceeds ? { recommendedNumCtx: recommendContextWindow(estimatedPromptTokens) } : {}),\n };\n }\n if (options.defaultContextLength !== undefined) {\n const exceeds = estimatedPromptTokens > options.defaultContextLength * threshold;\n return {\n estimatedPromptTokens,\n effectiveContextLength: options.defaultContextLength,\n windowSource: 'client-default',\n exceedsThreshold: exceeds,\n ...(exceeds ? { recommendedNumCtx: recommendContextWindow(estimatedPromptTokens) } : {}),\n };\n }\n const exceeds = estimatedPromptTokens > OLLAMA_FALLBACK_CONTEXT_LENGTH;\n return {\n estimatedPromptTokens,\n effectiveContextLength: OLLAMA_FALLBACK_CONTEXT_LENGTH,\n windowSource: 'server-fallback',\n exceedsThreshold: exceeds,\n ...(exceeds ? { recommendedNumCtx: recommendContextWindow(estimatedPromptTokens) } : {}),\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 // When the check carries a concrete suggestion (it does whenever it\n // exceeds the threshold — see `check()`), surface it with the ceiling\n // caveat: the number is a fit for *this estimate*, not a guarantee the\n // model's native context goes that high.\n const suggestion =\n check.recommendedNumCtx !== undefined\n ? ` A window of at least ${check.recommendedNumCtx} tokens would fit this prompt with ~30% ` +\n `headroom (see \\`recommendContextWindow\\`) — verify the model's native maximum via ` +\n `\\`client.models.getContextLength()\\` before adopting it.`\n : '';\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.${suggestion} ` +\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.${suggestion} ` +\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.${suggestion} ` +\n `Estimates are heuristic (±20–30%); see \\`estimateTokens\\`.`\n );\n}\n","/**\n * Dynamic context-window discovery.\n *\n * Guessing context windows (\"it's probably 2048… or 4096?\") is how silent\n * truncation happens. Ollama advertises the real numbers in two places, and\n * they answer *different questions*:\n *\n * - **`GET /api/ps`** reports `context_length` for every currently-running\n * model — the window the runner has **actually allocated**. This is the\n * exact, server-enforced number: it already reflects the model's Modelfile\n * `num_ctx` default (if any) and the memory the runner was able to claim.\n * Only meaningful while the model is loaded.\n * - **`POST /api/show`** exposes two deeper signals in its response:\n * - `model_info[\"<architecture>.context_length\"]` — the model's **native**\n * maximum from its GGUF metadata (e.g. `gemma4.context_length: 131072`).\n * This is the ceiling you could raise `num_ctx` to, not the window you\n * have. The official API examples show a model whose native max is\n * 131072 while its running instance allocated 4096 — a 32× gap.\n * - `parameters` — the Modelfile's serialized option list; a\n * `num_ctx <n>` line (when the model's author set one) is the default\n * window the runner will allocate for this model.\n *\n * `OllamaClient.models.getContextLength()` consults them in precedence order\n * (see {@link resolveContextLength}) and returns every signal it found, so\n * callers can both act on the effective window *now* and know how much\n * headroom exists for raising it.\n */\n\nimport { extractContextLength } from './capabilities/capabilities.js';\nimport { OLLAMA_FALLBACK_CONTEXT_LENGTH } from './context-safety.js';\nimport type { ModelResponse, RequestCancellationOptions } from './types.js';\n\n/** Request shape for {@link ModelsClient.getContextLength}. */\nexport interface ContextDiscoveryRequestOptions extends RequestCancellationOptions {\n /** Model to introspect (tag optional — `\"llama3.1\"` matches `\"llama3.1:latest\"`). */\n readonly model: string;\n /**\n * Skip the `GET /api/ps` lookup — e.g. on cloud endpoints where the local\n * running-models listing isn't meaningful, or when the extra round-trip\n * isn't wanted. Discovery then falls back to `/api/show` signals only.\n */\n readonly skipRunningCheck?: boolean | undefined;\n}\n\n/** Where a discovered context window came from, in precedence order. */\nexport type ContextLengthSource =\n /** `GET /api/ps` — window actually allocated by the running instance (exact). */\n | 'running'\n /** `POST /api/show` `parameters` — Modelfile-authored `num_ctx` default. */\n | 'parameters'\n /** `POST /api/show` `model_info[\"*.context_length\"]` — native GGUF maximum. */\n | 'model-info'\n /** Nothing discoverable — Ollama's conservative unset-`num_ctx` default (2048). */\n | 'fallback';\n\n/** Result of {@link ModelsClient.getContextLength}. */\nexport interface DiscoveredContextLength {\n /**\n * The effective context window to program against, resolved by precedence:\n * `running` (exact, when loaded) → `parameters` (Modelfile default) →\n * `model-info` (native max) → `2048` fallback.\n */\n readonly contextLength: number;\n /** Which source produced {@link contextLength}. */\n readonly source: ContextLengthSource;\n /** Window allocated by the running instance, when the model is loaded and reports it. */\n readonly runningContextLength?: number | undefined;\n /** Modelfile `num_ctx` default from `/api/show`'s `parameters` string, when set. */\n readonly parameterContextLength?: number | undefined;\n /** Native GGUF maximum from `model_info[\"*.context_length\"]`, when reported. */\n readonly nativeContextLength?: number | undefined;\n}\n\n/**\n * Parses `num_ctx <n>` out of `/api/show`'s `parameters` string.\n *\n * The string is the Modelfile's serialized option list — one `name value`\n * pair per line, value separated by whitespace padding, e.g.\n * `\"num_stop 8192\\nnum_ctx 4096\"`. Returns `undefined` when no positive\n * integer `num_ctx` line is present.\n */\nexport function extractParameterNumCtx(parameters?: string | undefined): number | undefined {\n if (!parameters) return undefined;\n const match = /^[ \\t]*num_ctx[ \\t]+(\\d+)\\s*$/m.exec(parameters);\n if (match === null) return undefined;\n const value = Number.parseInt(match[1]!, 10);\n return Number.isFinite(value) && value > 0 ? value : undefined;\n}\n\n/**\n * Whether one `/api/ps` running-model entry is the same model `model` refers to.\n * Matching mirrors Ollama's own model resolution: exact match on the entry's\n * `name`/`model`, or — when `model` carries no tag — any entry whose name starts\n * with `<model>:`. Shared by context-window discovery\n * (`findRunningModelContextLength`) and multi-host model-affinity routing\n * (`ModelAffinityRouter`) so the two can never disagree on what \"loaded\" means.\n * Fields are optional because raw wire payloads (the generated `Ps` model) mark\n * them so; the hand-written `ModelResponse` (required fields) is assignable too.\n */\nfunction matchesModelReference(\n entry: { readonly name?: string | undefined; readonly model?: string | undefined },\n model: string,\n): boolean {\n const exact = entry.name === model || entry.model === model;\n const taglessPrefix =\n !model.includes(':') &&\n ((entry.name !== undefined && entry.name.startsWith(`${model}:`)) ||\n (entry.model !== undefined && entry.model.startsWith(`${model}:`)));\n return exact || taglessPrefix;\n}\n\n/**\n * Whether `model` is currently resident (loaded in VRAM) per a `GET /api/ps`\n * response — exact or tag-less-prefix match, same resolution rules as Ollama\n * itself applies to model names. See {@link matchesModelReference}.\n */\nexport function isModelResident(\n psModels: readonly { readonly name?: string | undefined; readonly model?: string | undefined }[],\n model: string,\n): boolean {\n return psModels.some((entry) => matchesModelReference(entry, model));\n}\n\n/**\n * Finds the context window Ollama actually allocated for `model`, from a\n * `GET /api/ps` response. Matching mirrors Ollama's own model resolution:\n * exact match on the entry's `name`/`model`, or — when `model` carries no\n * tag — any entry whose name starts with `<model>:`.\n *\n * Returns `undefined` when the model isn't loaded or the running entry\n * doesn't report `context_length` (older server versions).\n */\nexport function findRunningModelContextLength(\n psModels: readonly ModelResponse[],\n model: string,\n): number | undefined {\n for (const entry of psModels) {\n if (matchesModelReference(entry, model)) {\n return typeof entry.context_length === 'number' &&\n Number.isFinite(entry.context_length) &&\n entry.context_length > 0\n ? entry.context_length\n : undefined;\n }\n }\n return undefined;\n}\n\n/** Internal inputs to {@link resolveContextLength}; each signal independently optional. */\nexport interface ContextLengthSignals {\n readonly running?: number | undefined;\n readonly parameter?: number | undefined;\n readonly native?: number | undefined;\n}\n\nfunction positiveInt(value: number | undefined): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;\n}\n\n/**\n * Resolves the effective context window from whatever signals were\n * discovered, by precedence:\n *\n * 1. **`running`** — the allocated window of the loaded instance. When the\n * model is in memory this is the ground truth; it already incorporates\n * any Modelfile `num_ctx` default.\n * 2. **`parameter`** — the Modelfile's `num_ctx`, i.e. the window the\n * runner *will* allocate for this model on the next cold load.\n * 3. **`native`** — the GGUF maximum. Only used when nothing tighter is\n * known: a fresh `num_ctx`-less load may allocate far less than native\n * (Ollama's conservative default), so native is a *ceiling*, not an\n * expectation.\n * 4. **Fallback** — {@link OLLAMA_FALLBACK_CONTEXT_LENGTH} (2048), the\n * conservative server-side default, so the result is always actionable.\n *\n * Pure — used by `ModelsClient.getContextLength()` and exported for callers\n * that already hold `/api/ps` / `/api/show` responses.\n */\nexport function resolveContextLength(signals: ContextLengthSignals): DiscoveredContextLength {\n const running = positiveInt(signals.running);\n const parameter = positiveInt(signals.parameter);\n const native = positiveInt(signals.native);\n if (running !== undefined) {\n return {\n contextLength: running,\n source: 'running',\n ...(parameter !== undefined ? { parameterContextLength: parameter } : {}),\n ...(native !== undefined ? { nativeContextLength: native } : {}),\n runningContextLength: running,\n };\n }\n if (parameter !== undefined) {\n return {\n contextLength: parameter,\n source: 'parameters',\n parameterContextLength: parameter,\n ...(native !== undefined ? { nativeContextLength: native } : {}),\n };\n }\n if (native !== undefined) {\n return { contextLength: native, source: 'model-info', nativeContextLength: native };\n }\n return { contextLength: OLLAMA_FALLBACK_CONTEXT_LENGTH, source: 'fallback' };\n}\n\n/** Re-exported for `getContextLength` consumers that also want the raw model_info scanner. */\nexport { extractContextLength as extractNativeContextLength };\n","/**\n * Multi-host model-affinity routing — prefer the endpoint already holding the\n * requested model in VRAM.\n *\n * Ollama daemons keep a bounded set of models resident (`OLLAMA_MAX_LOADED_MODELS`).\n * With several interchangeable endpoints serving the same models, sending a request\n * to a host that doesn't currently hold the model forces an unload/cold-load swap\n * on that host — the thrashing `ModelAffinityScheduler` avoids for a *single*\n * client's task queues. This router brings the same affinity to the *multi-host*\n * request path: given the candidate endpoints `executeWithFailover` would try\n * anyway, it reorders them so hosts whose `GET /api/ps` shows the requested model\n * resident come first.\n *\n * Design constraints (see ADR 0028):\n *\n * - **Zero added request latency.** Reordering is synchronous and consults only\n * cached `/api/ps` snapshots. A request never waits for a probe: when a\n * snapshot is missing or stale, the request proceeds with the unchanged\n * candidate order and the refresh happens in the background, warming the cache\n * for subsequent requests.\n * - **Race-free with `least-connections`.** The reorder runs entirely between the\n * registry's synchronous `candidates()`/`filterWithCapacity()` and the\n * endpoint's `acquire()` — no `await` in between — so the strategy's\n * no-two-calls-pick-the-same-idle-endpoint guarantee is untouched. Affinity\n * only reorders *within each priority tier* of the runnable set: a\n * higher-priority endpoint is always tried before a lower-priority one, and\n * per-strategy ordering is kept inside the resident/non-resident groups.\n * - **Best-effort, never blocking, never failing a request.** A probe failure is\n * recorded with a short backoff (`failureRetryMs`) and never cached as data;\n * the affected endpoint is simply treated as unknown until a probe succeeds.\n * - **Fresh-data-only decisions.** Only snapshots within `ttlMs` reorder\n * requests — `/api/ps` can change at any moment (evictions, other clients),\n * so stale data is treated as no data. Last-known snapshots are still exposed\n * via `status()` for observability.\n */\n\nimport { isModelResident } from '../context-discovery.js';\nimport type { OllamaEndpoint } from './endpoint-registry.js';\n\n/**\n * One `/api/ps` running-model entry, as the router consumes it — name/model only.\n * Optional to match the generated `Ps` wire shape; hand-written `ModelResponse`\n * values (required fields) are assignable as-is.\n */\nexport interface AffinityRunningModel {\n readonly name?: string | undefined;\n readonly model?: string | undefined;\n}\n\n/**\n * Options for dynamic model-affinity routing across endpoints. Configured under\n * `OllamaClientConfig.endpointHealth.modelAffinity`; implemented by\n * `OllamaClient`'s request path (`executeWithFailover`), which has HTTP access —\n * the `EndpointRegistry` itself ignores this key.\n */\nexport interface ModelAffinityRoutingOptions {\n /**\n * How long a `GET /api/ps` snapshot stays fresh enough to reorder requests\n * (default 30_000ms). Mirrors `ModelAffinityScheduler`'s `psCacheTtlMs`.\n */\n readonly ttlMs?: number | undefined;\n /**\n * How long a failed `/api/ps` probe suppresses retries against that endpoint\n * (default 5_000ms) — a dead host isn't probed on every request while it's\n * down, and comes back automatically once it recovers. Failures are never\n * cached as data.\n */\n readonly failureRetryMs?: number | undefined;\n}\n\n/** Introspection snapshot for one endpoint's affinity cache. */\nexport interface ModelAffinitySnapshot {\n readonly endpointName: string;\n readonly baseUrl: string;\n /** Model names reported resident by the last successful probe (may be stale). */\n readonly loadedModels: readonly string[];\n /** When the last successful probe completed — `undefined` if it never succeeded. */\n readonly fetchedAt: number | undefined;\n /** Whether the snapshot is within `ttlMs` and therefore still drives reordering. */\n readonly fresh: boolean;\n}\n\ninterface CacheEntry {\n readonly models: readonly AffinityRunningModel[];\n readonly fetchedAt: number;\n}\n\n/** Test seam: injectable clock — defaults to `Date.now`. */\nexport type NowFn = () => number;\n\nconst DEFAULT_TTL_MS = 30_000;\nconst DEFAULT_FAILURE_RETRY_MS = 5_000;\n\n/**\n * Cache-and-reorder engine for multi-host model affinity. See the module docs for\n * the design constraints; `OllamaClient` constructs one (only when\n * `endpointHealth.modelAffinity` is set) and calls {@link reorder} synchronously\n * inside its request path.\n */\nexport class ModelAffinityRouter {\n private readonly fetchPs: (endpoint: OllamaEndpoint) => Promise<readonly AffinityRunningModel[]>;\n private readonly ttlMs: number;\n private readonly failureRetryMs: number;\n private readonly now: NowFn;\n private readonly cache = new Map<string, CacheEntry>();\n private readonly failedAt = new Map<string, number>();\n private readonly inflight = new Map<string, Promise<void>>();\n\n constructor(\n fetchPs: (endpoint: OllamaEndpoint) => Promise<readonly AffinityRunningModel[]>,\n options: ModelAffinityRoutingOptions & { readonly now?: NowFn } = {},\n ) {\n this.fetchPs = fetchPs;\n this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;\n this.failureRetryMs = options.failureRetryMs ?? DEFAULT_FAILURE_RETRY_MS;\n this.now = options.now ?? Date.now;\n }\n\n /**\n * Synchronously reorders `candidates` so that, within each priority tier\n * (run of consecutive equal `priority`), endpoints whose fresh `/api/ps`\n * snapshot shows `model` resident come first (relative order preserved within\n * each group). Never moves an endpoint across tiers. Returns the input unchanged — and kicks a background refresh —\n * when any candidate's snapshot is missing or stale: a wrong reorder is worse\n * than no reorder, and the first request after a cache miss simply isn't\n * reordered. No-op without a `model` or with fewer than two candidates.\n */\n reorder(\n candidates: readonly OllamaEndpoint[],\n model: string | undefined,\n ): readonly OllamaEndpoint[] {\n if (model === undefined || candidates.length < 2) return candidates;\n\n const currentTime = this.now();\n let allFresh = true;\n for (const endpoint of candidates) {\n const entry = this.cache.get(endpoint.name);\n if (entry === undefined || currentTime - entry.fetchedAt > this.ttlMs) {\n allFresh = false;\n this.kickRefresh(endpoint);\n }\n }\n if (!allFresh) return candidates;\n\n const isResident = (ep: OllamaEndpoint): boolean => {\n const entry = this.cache.get(ep.name);\n return entry !== undefined && isModelResident(entry.models, model);\n };\n\n // Affinity only breaks ties *within* a priority tier: a higher-priority\n // endpoint is always tried before a lower-priority one, resident or not.\n // Tiers are runs of consecutive equal `priority` (unset = 0, as in the\n // registry), so whatever order the registry produced between runs —\n // priority-sorted, or the fail-open recovery order — is kept as-is.\n const reordered: OllamaEndpoint[] = [];\n let changed = false;\n for (let start = 0; start < candidates.length;) {\n const tierPriority = candidates[start]!.priority ?? 0;\n let end = start + 1;\n while (end < candidates.length && (candidates[end]!.priority ?? 0) === tierPriority) end++;\n const tier = candidates.slice(start, end);\n const resident = tier.filter(isResident);\n if (resident.length === 0 || resident.length === tier.length) {\n reordered.push(...tier);\n } else {\n const tierOrder = [...resident, ...tier.filter((ep) => !isResident(ep))];\n changed ||= tierOrder.some((ep, i) => ep !== tier[i]);\n reordered.push(...tierOrder);\n }\n start = end;\n }\n return changed ? reordered : candidates;\n }\n\n /**\n * Forces a refresh of the affinity cache for the given endpoints (deduped with\n * any in-flight refresh; bypasses the failure backoff, because this is an\n * explicit caller request — `client.warmModelAffinity()`). Resolves once every\n * probe has settled — successfully or not; individual failures never reject.\n */\n async warm(endpoints: readonly OllamaEndpoint[]): Promise<void> {\n await Promise.all(endpoints.map((endpoint) => this.refresh(endpoint)));\n }\n\n /** Introspection snapshots for the given endpoints (defaults to cached ones). */\n status(endpoints?: readonly OllamaEndpoint[]): readonly ModelAffinitySnapshot[] {\n const names =\n endpoints !== undefined\n ? endpoints.map((ep) => ep.name)\n : [...this.cache.keys(), ...this.failedAt.keys()];\n const byName = new Map((endpoints ?? []).map((ep) => [ep.name, ep] as const));\n const currentTime = this.now();\n return names\n .filter((name, i, arr) => arr.indexOf(name) === i)\n .map((name) => {\n const entry = this.cache.get(name);\n return {\n endpointName: name,\n baseUrl: byName.get(name)?.baseUrl ?? '',\n loadedModels:\n entry?.models.map((m) => m.name ?? m.model ?? '').filter((n) => n !== '') ?? [],\n fetchedAt: entry?.fetchedAt,\n fresh: entry !== undefined && currentTime - entry.fetchedAt <= this.ttlMs,\n };\n });\n }\n\n /**\n * Starts (or joins) a background refresh for `endpoint`, unless one is already\n * in flight or the failure backoff suppresses it. Fire-and-forget: the promise\n * is stored only for dedupe/warm-joins; callers never await it on the request\n * path.\n */\n private kickRefresh(endpoint: OllamaEndpoint): void {\n if (this.inflight.has(endpoint.name)) return; // deduped inside refresh() too\n const lastFailure = this.failedAt.get(endpoint.name);\n if (lastFailure !== undefined && this.now() - lastFailure < this.failureRetryMs) return;\n void this.refresh(endpoint);\n }\n\n /** Refreshes one endpoint's snapshot; never rejects (failures record a backoff). */\n private refresh(endpoint: OllamaEndpoint): Promise<void> {\n const existing = this.inflight.get(endpoint.name);\n if (existing !== undefined) return existing;\n\n const attempt = this.fetchPs(endpoint)\n .then((models) => {\n this.cache.set(endpoint.name, { models, fetchedAt: this.now() });\n this.failedAt.delete(endpoint.name);\n })\n .catch(() => {\n // Unreachable host, auth hiccup, timeout — affinity routing is\n // best-effort. Record a backoff so a dead endpoint isn't re-probed on\n // every single request, and never cache a failure as data: the endpoint\n // is simply \"unknown\" until a probe succeeds. (A previous success stays\n // in the cache for `status()` observability but is too stale to reorder.)\n this.failedAt.set(endpoint.name, this.now());\n })\n .finally(() => {\n this.inflight.delete(endpoint.name);\n });\n\n this.inflight.set(endpoint.name, attempt);\n return attempt;\n }\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 {\n extractParameterNumCtx,\n findRunningModelContextLength,\n resolveContextLength,\n type ContextDiscoveryRequestOptions,\n type DiscoveredContextLength,\n} from './context-discovery.js';\nimport { extractContextLength } from './capabilities/capabilities.js';\nimport { OllamaAbortError, 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 RequestCancellationOptions,\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 */\n/** Options for {@link ModelsClient.createModelFromGguf}: every `/api/create` field except identity/source ones, plus the draft-shard path convenience. */\nexport interface CreateModelFromGgufOptions extends Omit<\n CreateRequestOptions,\n 'model' | 'files' | 'from' | 'stream'\n> {\n /**\n * Local path(s) to the draft-model GGUF shard(s) for speculative decoding —\n * each is uploaded as a blob and assembled into `draft_files` under its\n * basename, the same protocol as the primary shards. Composes with an\n * explicit `draft_files` digest map (path uploads win on basename\n * collision). Pair with `parameters.draft_num_predict` and, optionally,\n * `draft_quantize` to compress the draft weights during ingestion.\n */\n readonly draftGguf?: string | readonly string[] | undefined;\n}\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(request?: RequestCancellationOptions): Promise<PsResponse> {\n return this.runner(\n (http, signal) => http.request<PsResponse>({ path: '/api/ps', method: 'GET', signal }),\n {\n singleEndpoint: true,\n ...(request?.signal !== undefined ? { signal: request.signal } : {}),\n ...(request?.timeoutMs !== undefined ? { timeoutMs: request.timeoutMs } : {}),\n },\n );\n }\n\n /**\n * Discovers the model's real context window from the server — no more\n * 2048/4096 guesswork. Consults, in precedence order:\n *\n * 1. `GET /api/ps` — the window the **running instance actually\n * allocated** (exact, reflects the Modelfile `num_ctx` default and\n * what fit in memory); skipped when the model isn't loaded, when\n * `skipRunningCheck` is set, or harmlessly on servers without the\n * field.\n * 2. `POST /api/show` `parameters` — a Modelfile-authored\n * `num_ctx <n>` default, i.e. the window a cold load will allocate.\n * 3. `POST /api/show` `model_info[\"<arch>.context_length\"]` — the\n * model's **native GGUF maximum** (a ceiling to raise `num_ctx`\n * toward, not the allocated window).\n * 4. Fallback — Ollama's conservative unset-`num_ctx` default (2048).\n *\n * The result carries every signal it found, so `nativeContextLength:\n * 131072` vs `contextLength: 4096` (a 32× gap seen in the official API\n * examples) is visible rather than guessed. Typical wiring:\n *\n * ```ts\n * const { contextLength, source, nativeContextLength } =\n * await client.models.getContextLength({ model: 'gemma4' });\n * // -> { contextLength: 4096, source: 'running', nativeContextLength: 131072 }\n * ```\n *\n * Makes two server calls (`/api/ps` + `/api/show`) unless\n * `skipRunningCheck` is set. A 404 from `/api/ps` (endpoint without the\n * listing) is treated as \"not running\" and never fails the lookup;\n * other transport errors propagate normally.\n */\n async getContextLength(\n request: ContextDiscoveryRequestOptions,\n ): Promise<DiscoveredContextLength> {\n let running: number | undefined;\n if (request.skipRunningCheck !== true) {\n try {\n const ps = await this.ps({ signal: request.signal, timeoutMs: request.timeoutMs });\n running = findRunningModelContextLength(ps.models, request.model);\n } catch (err) {\n // Endpoints without the running-models listing (e.g. compat-only\n // hosts) still deserve parameter/model-info discovery.\n if (!(err instanceof OllamaNotFoundError)) throw err;\n }\n }\n const showRes = await this.show({\n model: request.model,\n signal: request.signal,\n timeoutMs: request.timeoutMs,\n });\n return resolveContextLength({\n running,\n parameter: extractParameterNumCtx(showRes.parameters),\n native: extractContextLength(showRes.model_info),\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(\n digest: string,\n data: BinaryBody,\n request?: RequestCancellationOptions,\n ): 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 { ...request, singleEndpoint: true },\n );\n }\n\n async checkBlob(digest: string, request?: RequestCancellationOptions): 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 { ...request, 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);\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 } & RequestCancellationOptions,\n ): Promise<BlobUploadResult> {\n const digest = opts?.digest ?? (await this.computeBlobDigest(data));\n const alreadyExisted = await this.checkBlob(digest, opts);\n if (!alreadyExisted) {\n await this.createBlob(digest, data, opts);\n }\n return { digest, alreadyExisted };\n }\n\n /**\n * Streams a blob upload straight from a web `ReadableStream` — the\n * multi-gigabyte-safe counterpart of {@link createBlobFromData}. The body\n * is never materialized in memory: the transport hands the stream to\n * `fetch` directly (setting `duplex: 'half'`, which Node 18+ requires for\n * stream bodies), so peak heap usage is a transport-level chunk, not the\n * blob size.\n *\n * The digest must be known up front — it *is* the upload URL\n * (`/api/blobs/<digest>`), the same content-addressed protocol\n * `curl -T` performs. Hash first when you don't have it: in-memory bytes\n * via {@link computeBlobDigest}, files via {@link createBlobFromFile}\n * (which hashes in a streaming pass). The server verifies the streamed\n * bytes against the digest and rejects mismatches, so a corrupted or\n * truncated stream fails the upload instead of poisoning the store.\n */\n async createBlobFromStream(\n digest: string,\n stream: ReadableStream<Uint8Array>,\n request?: RequestCancellationOptions,\n ): Promise<BlobUploadResult> {\n const alreadyExisted = await this.checkBlob(digest, request);\n if (!alreadyExisted) {\n await this.createBlob(digest, stream, request);\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 * Streams both passes in fixed-size chunks — peak heap is O(chunk), not\n * O(file), so multi-gigabyte GGUFs never enter the Node heap:\n *\n * 1. **Hash pass** (skipped when `opts.digest` is provided): the file is\n * streamed through `node:crypto`'s incremental SHA-256.\n * 2. **Upload pass**: `node:fs` createReadStream → web ReadableStream →\n * `fetch` body with `duplex: 'half'` (see {@link createBlobFromStream}).\n *\n * A pre-existing blob (HEAD 200) skips the upload pass entirely, same as\n * {@link createBlobFromData}.\n */\n async createBlobFromFile(\n path: string,\n opts?: { readonly digest?: string | undefined } & RequestCancellationOptions,\n ): Promise<BlobUploadResult & { readonly fileName: string }> {\n // Specifiers hidden behind variables so browser/edge bundlers never try\n // to resolve `node:*` modules at build time — see src/vision.ts\n // NODE_FS_MODULE (the same trick keeps this Node-only method out of\n // edge bundles while the class itself stays portable).\n const nodeFsModule = 'node:fs';\n const { createReadStream } = (await import(nodeFsModule)) as typeof import('node:fs');\n const nodeCryptoModule = 'node:crypto';\n const { createHash } = (await import(nodeCryptoModule)) as typeof import('node:crypto');\n const nodeStreamModule = 'node:stream';\n const { Readable } = (await import(nodeStreamModule)) as typeof import('node:stream');\n\n const CHUNK_BYTES = 256 * 1024;\n\n // Pass 1 — streaming hash (O(chunk) memory). Aborts surface as\n // OllamaAbortError, the same class the transport boundary produces.\n let digest = opts?.digest;\n if (digest === undefined) {\n const hash = createHash('sha256');\n const hashStream = createReadStream(path, { highWaterMark: CHUNK_BYTES });\n try {\n for await (const chunk of hashStream) {\n if (opts?.signal?.aborted) {\n throw new OllamaAbortError('createBlobFromFile: aborted while hashing', {});\n }\n hash.update(chunk);\n }\n } finally {\n // Closes the fd on both the abort-throw and any read error —\n // a destroyed/errored iterator would otherwise rely on GC.\n hashStream.destroy();\n }\n digest = `sha256:${hash.digest('hex')}`;\n }\n\n const alreadyExisted = await this.checkBlob(digest, opts);\n if (!alreadyExisted) {\n // Pass 2 — streaming upload (O(chunk) memory).\n const uploadStream = createReadStream(path, { highWaterMark: CHUNK_BYTES });\n const onAbort = (): void => {\n // Destroying the Node side cancels the web stream, which undici\n // propagates as a body error; the forwarded signal also aborts the\n // fetch itself, so this is belt-and-braces fd hygiene.\n uploadStream.destroy();\n };\n opts?.signal?.addEventListener('abort', onAbort, { once: true });\n try {\n await this.createBlob(\n digest,\n Readable.toWeb(uploadStream) as unknown as ReadableStream<Uint8Array>,\n opts,\n );\n } finally {\n opts?.signal?.removeEventListener('abort', onAbort);\n }\n }\n const fileName = path.split(/[\\\\/]/).pop() ?? path;\n return { digest, alreadyExisted, 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 * // Speculative decoding: primary + draft shards + tuning:\n * await client.models.createModelFromGguf('my-model', '/path/to/model.gguf', {\n * draftGguf: '/path/to/draft.gguf',\n * draftQuantize: 'q8_0',\n * parameters: { draft_num_predict: 8 },\n * });\n * ```\n *\n * Speculative-decoding models assemble the same way: pass the draft\n * network's GGUF(s) as `draftGguf` (uploaded into `draft_files`), optionally\n * set `draft_quantize` to compress the draft weights independently of the\n * primary model, and set `parameters.draft_num_predict` to tune how many\n * tokens the draft network predicts per step (Ollama defaults separate\n * draft models to 4; `0` disables drafting; models with embedded MTP\n * tensors require setting it explicitly).\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`, `draftGguf`, …) except `files`,\n * `draft_files` (use `draftGguf` for path-based drafts; an explicit digest\n * map is still accepted and merged), `from`, and `stream`.\n */\n async createModelFromGguf(\n model: string,\n gguf: string | readonly string[],\n opts?: CreateModelFromGgufOptions,\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 draftOpt = opts?.draftGguf;\n const draftPaths = typeof draftOpt === 'string' ? [draftOpt] : (draftOpt ?? []);\n const {\n model: _model,\n files: _files,\n from: _from,\n stream: _stream,\n draftGguf: _draftGguf,\n draft_files: _draftFiles,\n ...rest\n } = (opts ?? {}) as CreateRequestOptions & {\n draftGguf?: string | readonly string[] | undefined;\n };\n const draftFiles: Record<string, string> = { ...(_draftFiles ?? {}) };\n for (const path of draftPaths) {\n const uploaded = await this.createBlobFromFile(path, { signal: opts?.signal });\n draftFiles[uploaded.fileName] = uploaded.digest;\n }\n return this.create({\n ...rest,\n model,\n files,\n ...(Object.keys(draftFiles).length > 0 ? { draft_files: draftFiles } : {}),\n stream: false,\n } 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' | 'medium' | 'low' | 'max' | 'none' | 'minimal' | 'xhigh' | 'ultra' | (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 /** @remarks Documented as unsupported by Ollama — accepted for OpenAI interop, ignored by the server. */\n readonly user?: string | undefined;\n /** @remarks Documented as unsupported by Ollama — accepted for OpenAI interop, ignored by the server. */\n readonly logit_bias?: Record<string, number> | undefined;\n /** @remarks Documented as unsupported by Ollama — accepted for OpenAI interop, ignored by the server. */\n readonly n?: number | undefined;\n /**\n * @remarks Logprobs are documented as unsupported on Ollama's `/v1/chat/completions`.\n * Use native `chat({ logprobs: true, top_logprobs })` for token log probabilities.\n */\n readonly logprobs?: boolean | undefined;\n /** @remarks Documented as unsupported by Ollama — accepted for OpenAI interop, ignored by the server. */\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?: { readonly effort?: OpenAIReasoningEffort | undefined } | undefined;\n}\n\n/** A base64 data URL (`data:image/png;base64,...`) — the only image form Ollama accepts here. */\nexport type OllamaOpenAIImageDataUrl = `data:${string}`;\n\n/** Ollama Chat Completions supports text plus base64 image content. */\nexport type OllamaOpenAIChatContentPart =\n | OpenAITextContentPart\n | {\n readonly type: 'image_url';\n /**\n * A base64 `data:` URL, as a string or inside the OpenAI `{ url, detail? }` object.\n * Ollama documents remote image URLs as unsupported on `/v1/chat/completions`, so\n * `http(s)://` URLs are a compile error here; resolve remote images to base64 first\n * (e.g. with {@link resolveImageInput}) or use the native `images` field.\n */\n readonly image_url:\n | OllamaOpenAIImageDataUrl\n | {\n readonly url: OllamaOpenAIImageDataUrl;\n readonly detail?: 'auto' | 'low' | 'high' | 'original' | undefined;\n };\n };\n\nexport type OllamaOpenAIReasoningEffort = 'high' | 'medium' | 'low' | 'max' | 'none';\n\nexport type OllamaOpenAIChatMessage = Omit<OpenAIMessage, 'content'> & {\n readonly content: string | readonly OllamaOpenAIChatContentPart[];\n};\n\n/**\n * Strict Ollama-documented Chat Completions request. Excludes the fields\n * https://docs.ollama.com/api/openai-compatibility marks unsupported (`tool_choice`,\n * `logit_bias`, `user`, `n`, `logprobs`/`top_logprobs`) and the SDK-only\n * `parallel_tool_calls` flag, so passing any of them is a compile-time error instead of\n * a silently ignored request field.\n */\nexport type OllamaOpenAIChatCompletionRequest = Omit<\n OpenAIChatCompletionRequest,\n | 'messages'\n | 'parallel_tool_calls'\n | 'reasoning_effort'\n | 'reasoning'\n | 'tool_choice'\n | 'logit_bias'\n | 'user'\n | 'n'\n | 'logprobs'\n | 'top_logprobs'\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 | {\n readonly name?: string | undefined;\n readonly arguments?: string | undefined;\n }\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 | {\n readonly cached_tokens?: number | undefined;\n }\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 /**\n * @remarks Logprobs are documented as unsupported on Ollama's `/v1/completions`. Use\n * native `generate({ logprobs: true, top_logprobs })` for token log probabilities.\n */\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 /** @remarks Documented as unsupported by Ollama — accepted for OpenAI interop, ignored by the server. */\n readonly best_of?: number | undefined;\n /** @remarks Documented as unsupported by Ollama — accepted for OpenAI interop, ignored by the server. */\n readonly echo?: boolean | undefined;\n /** @remarks Documented as unsupported by Ollama — accepted for OpenAI interop, ignored by the server. */\n readonly logit_bias?: Record<string, number> | undefined;\n /** @remarks Documented as unsupported by Ollama — accepted for OpenAI interop, ignored by the server. */\n readonly user?: string | undefined;\n /** @remarks Documented as unsupported by Ollama — accepted for OpenAI interop, ignored by the server. */\n readonly n?: number | undefined;\n}\n\n/** Strict Ollama-documented Completions request. */\n/**\n * Strict Ollama-documented Completions request: excludes `best_of`, `echo`,\n * `logit_bias`, `user`, `n`, and `logprobs`, which Ollama documents as unsupported.\n */\nexport type OllamaOpenAICompletionRequest = Omit<\n OpenAICompletionRequest,\n 'best_of' | 'echo' | 'logit_bias' | 'user' | 'n' | 'logprobs'\n>;\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 | readonly string[] | readonly number[] | 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 /** @remarks Documented as unsupported by Ollama — accepted for OpenAI interop, ignored by the server. */\n readonly user?: string | undefined;\n}\n\n/** Strict Ollama-documented Embeddings request. */\n/**\n * Strict Ollama-documented Embeddings request: `input` is a string or an array of\n * strings (token and token-array inputs are documented as unsupported), and `user` is\n * excluded.\n */\nexport type OllamaOpenAIEmbeddingRequest = Omit<OpenAIEmbeddingRequest, 'input' | 'user'> & {\n readonly input: string | readonly string[];\n};\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 | {\n readonly prompt_tokens: number;\n readonly total_tokens: number;\n }\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 /** @remarks Documented as unsupported by Ollama — accepted but ignored. */\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/**\n * Strict Ollama-documented Responses request: excludes the stateful fields\n * (`previous_response_id`, `conversation`) and `truncation`, which Ollama documents as\n * unsupported.\n */\nexport type OllamaOpenAIResponsesRequest = Omit<\n OpenAIResponsesRequest,\n 'previous_response_id' | 'conversation' | 'truncation'\n>;\n\nexport type OpenAIResponsesStatus =\n 'completed' | 'failed' | 'in_progress' | 'cancelled' | 'queued' | 'incomplete';\n\nexport interface OpenAIResponsesError {\n readonly code?: string | undefined;\n readonly message?: string | undefined;\n readonly [key: string]: unknown;\n}\nexport interface OpenAIResponsesIncompleteDetails {\n readonly reason?: string | undefined;\n readonly [key: string]: unknown;\n}\n\nexport interface OpenAIResponsesOutputTextContent {\n readonly type: 'output_text';\n readonly text: string;\n readonly annotations?: readonly Record<string, unknown>[] | undefined;\n readonly logprobs?: readonly Record<string, unknown>[] | undefined;\n}\nexport interface OpenAIResponsesOutputRefusal {\n readonly type: 'refusal';\n readonly refusal: string;\n}\nexport type OpenAIResponsesOutputContent =\n OpenAIResponsesOutputTextContent | OpenAIResponsesOutputRefusal;\n\nexport interface OpenAIResponsesOutputMessage {\n readonly type: 'message';\n readonly id?: string | undefined;\n readonly status?: OpenAIResponsesStatus | undefined;\n readonly role?: string | undefined;\n readonly phase?: string | undefined;\n readonly content: readonly OpenAIResponsesOutputContent[];\n}\nexport interface OpenAIResponsesOutputFunctionCall {\n readonly type: 'function_call';\n readonly id?: string | undefined;\n readonly call_id?: string | undefined;\n readonly name: string;\n readonly arguments: string;\n readonly status?: OpenAIResponsesStatus | undefined;\n}\nexport interface OpenAIResponsesOutputReasoning {\n readonly type: 'reasoning';\n readonly id?: string | undefined;\n readonly status?: OpenAIResponsesStatus | undefined;\n readonly summary?:\n readonly { readonly type: 'summary_text'; readonly text: string }[] | undefined;\n readonly text?: string | undefined;\n readonly encrypted_content?: string | undefined;\n}\nexport type OpenAIResponsesOutputItem =\n OpenAIResponsesOutputMessage | OpenAIResponsesOutputFunctionCall | OpenAIResponsesOutputReasoning;\n\nexport interface OpenAIResponsesUsage {\n readonly input_tokens: number;\n readonly output_tokens: number;\n 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;\n readonly object: 'response';\n readonly created: number;\n readonly created_at?: number | undefined;\n readonly status?: OpenAIResponsesStatus | undefined;\n readonly completed_at?: number | null | undefined;\n readonly error?: OpenAIResponsesError | null | undefined;\n readonly incomplete_details?: OpenAIResponsesIncompleteDetails | null | undefined;\n readonly model: string;\n readonly output: readonly OpenAIResponsesOutputItem[];\n readonly output_text?: string | undefined;\n readonly previous_response_id?: string | null | undefined;\n readonly parallel_tool_calls?: boolean | undefined;\n readonly usage?: OpenAIResponsesUsage | undefined;\n}\n\nexport class OpenAIResponsesStreamError extends OllamaClientError {\n readonly responsePayload: OpenAIResponsesResponse;\n constructor(message: string, responsePayload: OpenAIResponsesResponse) {\n super(message, {\n code: 'openai_responses_stream_error',\n retryable: false,\n response: { body: responsePayload },\n });\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(\n private readonly source: AbortableAsyncIterable<SseEvent>,\n signal?: AbortSignal,\n ) {\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<\n number,\n {\n message: OpenAIMessage;\n finish_reason: string;\n logprobs?: Record<string, unknown> | null | undefined;\n }\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(\n new OllamaAbortError('OpenAI Chat Completion stream ended before completion'),\n );\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(\n private readonly source: AbortableAsyncIterable<SseEvent>,\n signal?: AbortSignal,\n ) {\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 } | 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 {\n readonly response_id?: string | undefined;\n readonly sequence_number?: number | undefined;\n}\n\nexport interface OpenAIResponsesOutputTextDeltaEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.output_text.delta';\n readonly item_id: string;\n readonly output_index: number;\n readonly content_index: number;\n readonly delta: string;\n}\nexport interface OpenAIResponsesOutputTextDoneEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.output_text.done';\n readonly item_id: string;\n readonly output_index: number;\n readonly content_index: number;\n readonly text: string;\n}\nexport interface OpenAIResponsesFunctionCallArgumentsDeltaEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.function_call_arguments.delta';\n readonly item_id: string;\n readonly output_index: number;\n readonly delta: string;\n}\nexport interface OpenAIResponsesFunctionCallArgumentsDoneEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.function_call_arguments.done';\n readonly item_id: string;\n readonly output_index: number;\n readonly arguments: string;\n readonly name?: string | undefined;\n}\nexport interface OpenAIResponsesReasoningTextDeltaEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.reasoning_text.delta';\n readonly item_id: string;\n readonly output_index: number;\n readonly content_index: number;\n readonly delta: string;\n}\nexport interface OpenAIResponsesReasoningTextDoneEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.reasoning_text.done';\n readonly item_id: string;\n readonly output_index: number;\n readonly content_index: number;\n readonly text: string;\n}\nexport interface OpenAIResponsesReasoningSummaryPartAddedEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.reasoning_summary_part.added';\n readonly item_id: string;\n readonly output_index: number;\n readonly summary_index: number;\n readonly part: { readonly type: 'summary_text'; readonly text: string };\n}\nexport interface OpenAIResponsesReasoningSummaryPartDoneEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.reasoning_summary_part.done';\n readonly item_id: string;\n readonly output_index: number;\n readonly summary_index: number;\n readonly part: { readonly type: 'summary_text'; readonly text: string };\n readonly status?: 'incomplete' | undefined;\n}\nexport interface OpenAIResponsesReasoningSummaryTextDeltaEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.reasoning_summary_text.delta';\n readonly item_id: string;\n readonly output_index: number;\n readonly summary_index: number;\n readonly delta: string;\n}\nexport interface OpenAIResponsesReasoningSummaryTextDoneEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.reasoning_summary_text.done';\n readonly item_id: string;\n readonly output_index: number;\n readonly summary_index: number;\n readonly text: string;\n}\nexport interface OpenAIResponsesOutputItemAddedEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.output_item.added';\n readonly item: OpenAIResponsesOutputItem;\n readonly output_index: number;\n}\nexport interface OpenAIResponsesOutputItemDoneEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.output_item.done';\n readonly item: OpenAIResponsesOutputItem;\n readonly output_index: number;\n}\nexport interface OpenAIResponsesContentPartAddedEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.content_part.added';\n readonly item_id: string;\n readonly output_index: number;\n readonly content_index: number;\n readonly part:\n OpenAIResponsesOutputContent | { readonly type: string; readonly [key: string]: unknown };\n}\nexport interface OpenAIResponsesContentPartDoneEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.content_part.done';\n readonly item_id: string;\n readonly output_index: number;\n readonly content_index: number;\n readonly part:\n OpenAIResponsesOutputContent | { readonly type: string; readonly [key: string]: unknown };\n}\nexport interface OpenAIResponsesRefusalDeltaEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.refusal.delta';\n readonly item_id: string;\n readonly output_index: number;\n readonly content_index: number;\n readonly delta: string;\n}\nexport interface OpenAIResponsesRefusalDoneEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.refusal.done';\n readonly item_id: string;\n readonly output_index: number;\n readonly content_index: number;\n readonly refusal: string;\n}\nexport interface OpenAIResponsesCreatedEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.created';\n readonly response: OpenAIResponsesResponse;\n}\nexport interface OpenAIResponsesInProgressEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.in_progress';\n readonly response: OpenAIResponsesResponse;\n}\nexport interface OpenAIResponsesQueuedEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.queued';\n readonly response: OpenAIResponsesResponse;\n}\nexport interface OpenAIResponsesCompletedEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.completed' | 'response.done';\n readonly response: OpenAIResponsesResponse;\n}\nexport interface OpenAIResponsesFailedEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.failed';\n readonly response: OpenAIResponsesResponse;\n}\nexport interface OpenAIResponsesIncompleteEvent extends OpenAIResponsesEventBase {\n readonly type: 'response.incomplete';\n readonly response: OpenAIResponsesResponse;\n}\n\nexport type OpenAIResponsesStreamEvent =\n | OpenAIResponsesOutputTextDeltaEvent\n | OpenAIResponsesOutputTextDoneEvent\n | OpenAIResponsesFunctionCallArgumentsDeltaEvent\n | OpenAIResponsesFunctionCallArgumentsDoneEvent\n | OpenAIResponsesReasoningTextDeltaEvent\n | OpenAIResponsesReasoningTextDoneEvent\n | OpenAIResponsesReasoningSummaryPartAddedEvent\n | OpenAIResponsesReasoningSummaryPartDoneEvent\n | OpenAIResponsesReasoningSummaryTextDeltaEvent\n | OpenAIResponsesReasoningSummaryTextDoneEvent\n | OpenAIResponsesOutputItemAddedEvent\n | OpenAIResponsesOutputItemDoneEvent\n | OpenAIResponsesContentPartAddedEvent\n | OpenAIResponsesContentPartDoneEvent\n | OpenAIResponsesRefusalDeltaEvent\n | OpenAIResponsesRefusalDoneEvent\n | OpenAIResponsesCreatedEvent\n | OpenAIResponsesInProgressEvent\n | OpenAIResponsesQueuedEvent\n | OpenAIResponsesCompletedEvent\n | OpenAIResponsesFailedEvent\n | OpenAIResponsesIncompleteEvent\n | { readonly type: string; readonly [key: string]: unknown };\n\ntype OpenAIResponsesOutputState = {\n itemId: string;\n kind: 'message' | 'function_call' | 'reasoning';\n content: Map<number, OpenAIResponsesOutputContent>;\n summary: Map<number, string>;\n arguments: string;\n name?: string | undefined;\n callId?: string | undefined;\n status?: OpenAIResponsesStatus | undefined;\n role?: string | undefined;\n phase?: string | undefined;\n 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(\n private readonly source: AbortableAsyncIterable<SseEvent>,\n signal?: AbortSignal,\n ) {\n this.finalResultPromise = new Promise<OpenAIResponsesResponse>((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 get finalResult(): Promise<OpenAIResponsesResponse> {\n return this.finalResultPromise;\n }\n abort(): void {\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n 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 = (\n outputIndex: number,\n itemId: string,\n kind: OpenAIResponsesOutputState['kind'],\n ): OpenAIResponsesOutputState => {\n const existing = outputs.get(outputIndex);\n if (existing) {\n if (itemId) existing.itemId = itemId;\n existing.kind = kind;\n return existing;\n }\n const state: OpenAIResponsesOutputState = {\n itemId,\n kind,\n content: new Map(),\n summary: new Map(),\n arguments: '',\n reasoningText: '',\n };\n outputs.set(outputIndex, state);\n return state;\n };\n\n const applyOutputItem = (outputIndex: number, item: OpenAIResponsesOutputItem): void => {\n const kind =\n item.type === 'message'\n ? 'message'\n : item.type === 'function_call'\n ? 'function_call'\n : 'reasoning';\n const state = ensureState(outputIndex, item.id ?? '', kind);\n state.itemId = item.id ?? state.itemId;\n state.status = item.status;\n if (item.type === 'message') {\n state.role = item.role;\n state.phase = item.phase;\n state.content.clear();\n item.content.forEach((p, i) => state.content.set(i, p));\n } else if (item.type === 'function_call') {\n state.callId = item.call_id;\n state.name = item.name;\n state.arguments = item.arguments;\n } else {\n state.summary.clear();\n item.summary?.forEach((p, i) => state.summary.set(i, p.text));\n state.reasoningText = item.text ?? '';\n }\n };\n const applyContentPart = (\n outputIndex: number,\n itemId: string,\n contentIndex: number,\n part: OpenAIResponsesOutputContent,\n ): void => {\n const state = ensureState(outputIndex, itemId, 'message');\n state.content.set(contentIndex, part);\n };\n const reconstructedOutput = (): readonly OpenAIResponsesOutputItem[] =>\n [...outputs.entries()]\n .sort(([a], [b]) => a - b)\n .map(([outputIndex, state]) => {\n const canonical = canonicalOutputItems.get(outputIndex);\n if (canonical) return canonical;\n if (state.kind === 'message')\n return {\n type: 'message',\n ...(state.itemId ? { id: state.itemId } : {}),\n ...(state.status ? { status: state.status } : {}),\n role: state.role ?? 'assistant',\n ...(state.phase ? { phase: state.phase } : {}),\n content: [...state.content.entries()].sort(([a], [b]) => a - b).map(([, p]) => p),\n };\n if (state.kind === 'function_call')\n return {\n type: 'function_call',\n ...(state.itemId ? { id: state.itemId } : {}),\n ...(state.callId ? { call_id: state.callId } : {}),\n ...(state.status ? { status: state.status } : {}),\n name: state.name ?? '',\n arguments: state.arguments,\n };\n return {\n type: 'reasoning',\n ...(state.itemId ? { id: state.itemId } : {}),\n ...(state.status ? { status: state.status } : {}),\n ...(state.summary.size\n ? {\n summary: [...state.summary.entries()]\n .sort(([a], [b]) => a - b)\n .map(([, text]) => ({ type: 'summary_text' as const, text })),\n }\n : {}),\n ...(state.reasoningText ? { text: state.reasoningText } : {}),\n };\n });\n\n try {\n for await (const event of this.source) {\n if (event.data === '[DONE]') break;\n let payload: OpenAIResponsesStreamEvent;\n try {\n payload = JSON.parse(event.data) as OpenAIResponsesStreamEvent;\n } catch (error) {\n throw new Error('Failed to parse OpenAI Responses SSE payload', { cause: error });\n }\n switch (payload.type) {\n case 'response.created':\n case 'response.in_progress':\n case 'response.queued':\n responseMeta = (payload as OpenAIResponsesCreatedEvent).response;\n break;\n case 'response.completed':\n case 'response.done':\n finalResponse = (payload as OpenAIResponsesCompletedEvent).response;\n break;\n case 'response.failed':\n terminalFailure = (payload as OpenAIResponsesFailedEvent).response;\n finalResponse = terminalFailure;\n break;\n case 'response.incomplete':\n terminalIncomplete = (payload as OpenAIResponsesIncompleteEvent).response;\n finalResponse = terminalIncomplete;\n break;\n case 'response.output_item.added': {\n const e = payload as OpenAIResponsesOutputItemAddedEvent;\n applyOutputItem(e.output_index, e.item);\n break;\n }\n case 'response.output_item.done': {\n const e = payload as OpenAIResponsesOutputItemDoneEvent;\n applyOutputItem(e.output_index, e.item);\n canonicalOutputItems.set(e.output_index, e.item);\n break;\n }\n case 'response.content_part.added':\n case 'response.content_part.done': {\n const e = payload as\n OpenAIResponsesContentPartAddedEvent | OpenAIResponsesContentPartDoneEvent;\n if (\n (e.part.type === 'output_text' &&\n 'text' in e.part &&\n typeof e.part.text === 'string') ||\n (e.part.type === 'refusal' &&\n 'refusal' in e.part &&\n typeof e.part.refusal === 'string')\n ) {\n applyContentPart(\n e.output_index,\n e.item_id,\n e.content_index,\n e.part as OpenAIResponsesOutputContent,\n );\n }\n break;\n }\n case 'response.output_text.delta': {\n const e = payload as OpenAIResponsesOutputTextDeltaEvent;\n const s = ensureState(e.output_index, e.item_id, 'message');\n const p = s.content.get(e.content_index);\n s.content.set(e.content_index, {\n type: 'output_text',\n text: (p?.type === 'output_text' ? p.text : '') + e.delta,\n });\n break;\n }\n case 'response.output_text.done': {\n const e = payload as OpenAIResponsesOutputTextDoneEvent;\n const s = ensureState(e.output_index, e.item_id, 'message');\n s.content.set(e.content_index, { type: 'output_text', text: e.text });\n break;\n }\n case 'response.refusal.delta': {\n const e = payload as OpenAIResponsesRefusalDeltaEvent;\n const s = ensureState(e.output_index, e.item_id, 'message');\n const p = s.content.get(e.content_index);\n s.content.set(e.content_index, {\n type: 'refusal',\n refusal: (p?.type === 'refusal' ? p.refusal : '') + e.delta,\n });\n break;\n }\n case 'response.refusal.done': {\n const e = payload as OpenAIResponsesRefusalDoneEvent;\n const s = ensureState(e.output_index, e.item_id, 'message');\n s.content.set(e.content_index, { type: 'refusal', refusal: e.refusal });\n break;\n }\n case 'response.function_call_arguments.delta': {\n const e = payload as OpenAIResponsesFunctionCallArgumentsDeltaEvent;\n const s = ensureState(e.output_index, e.item_id, 'function_call');\n s.arguments += e.delta;\n break;\n }\n case 'response.function_call_arguments.done': {\n const e = payload as OpenAIResponsesFunctionCallArgumentsDoneEvent;\n const s = ensureState(e.output_index, e.item_id, 'function_call');\n s.arguments = e.arguments;\n if (e.name !== undefined) s.name = e.name;\n break;\n }\n case 'response.reasoning_summary_part.added':\n case 'response.reasoning_summary_part.done': {\n const e = payload as\n | OpenAIResponsesReasoningSummaryPartAddedEvent\n | OpenAIResponsesReasoningSummaryPartDoneEvent;\n const s = ensureState(e.output_index, e.item_id, 'reasoning');\n s.summary.set(e.summary_index, e.part.text);\n break;\n }\n case 'response.reasoning_summary_text.delta': {\n const e = payload as OpenAIResponsesReasoningSummaryTextDeltaEvent;\n const s = ensureState(e.output_index, e.item_id, 'reasoning');\n s.summary.set(e.summary_index, (s.summary.get(e.summary_index) ?? '') + e.delta);\n break;\n }\n case 'response.reasoning_summary_text.done': {\n const e = payload as OpenAIResponsesReasoningSummaryTextDoneEvent;\n const s = ensureState(e.output_index, e.item_id, 'reasoning');\n s.summary.set(e.summary_index, e.text);\n break;\n }\n case 'response.reasoning_text.delta': {\n const e = payload as OpenAIResponsesReasoningTextDeltaEvent;\n const s = ensureState(e.output_index, e.item_id, 'reasoning');\n s.reasoningText += e.delta;\n break;\n }\n case 'response.reasoning_text.done': {\n const e = payload as OpenAIResponsesReasoningTextDoneEvent;\n const s = ensureState(e.output_index, e.item_id, 'reasoning');\n s.reasoningText = e.text;\n break;\n }\n default:\n break;\n }\n yield payload;\n }\n if (terminalFailure || terminalIncomplete) {\n const response = terminalFailure ?? terminalIncomplete!;\n const status = terminalFailure ? 'failed' : 'incomplete';\n const detail =\n response.error?.message ?? response.incomplete_details?.reason ?? 'unknown error';\n throw new OpenAIResponsesStreamError(\n 'OpenAI Responses stream ' + status + ': ' + detail,\n response,\n );\n }\n if (!finalResponse) {\n if (!responseMeta)\n throw new Error('OpenAI Responses stream ended without a terminal response payload');\n if (responseMeta.status === 'failed' || responseMeta.status === 'incomplete') {\n const detail =\n responseMeta.error?.message ??\n responseMeta.incomplete_details?.reason ??\n 'unknown error';\n throw new OpenAIResponsesStreamError(\n 'OpenAI Responses stream ' + responseMeta.status + ': ' + detail,\n responseMeta,\n );\n }\n finalResponse = { ...responseMeta, output: reconstructedOutput(), status: 'completed' };\n } else if (finalResponse.status === 'failed' || finalResponse.status === 'incomplete') {\n const detail =\n finalResponse.error?.message ??\n finalResponse.incomplete_details?.reason ??\n 'unknown error';\n throw new OpenAIResponsesStreamError(\n 'OpenAI Responses stream ' + finalResponse.status + ': ' + detail,\n finalResponse,\n );\n }\n if (finalResponse.output.length === 0 && outputs.size > 0)\n finalResponse = { ...finalResponse, output: reconstructedOutput() };\n completed = true;\n this.removeAbortListener?.();\n this.removeAbortListener = undefined;\n this.resolveFinal(finalResponse);\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 Responses stream ended before completion'));\n }\n }\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((http, runnerSignal) => operation(http, runnerSignal), {\n ...(model !== undefined ? { model } : {}),\n ...(signal !== undefined ? { signal } : {}),\n ...(holdUntil !== undefined ? { holdUntil } : {}),\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\n .requestSseStream({\n path: '/v1/chat/completions',\n body: request,\n signal: requestSignal,\n })\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(model: string, signal?: AbortSignal): 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\n .requestSseStream({\n path: '/v1/completions',\n body: request,\n signal: requestSignal,\n })\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\n .requestSseStream({\n path: '/v1/responses',\n body: request,\n signal: requestSignal,\n })\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 <= 255, { message: 'must have at most 255 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 copy: StatusResponseSchema,\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 { estimateMessageTokens, OLLAMA_FALLBACK_CONTEXT_LENGTH } from './context-safety.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/** Options for {@link compactConversationHistory} / {@link ConversationSession.compact}. */\nexport interface CompactionOptions {\n /**\n * Estimated-token budget the compacted history must fit within (including\n * any retained system message and the 10%-style reply reservation below).\n * Estimated with the same CJK-aware heuristic as the pre-flight checks\n * (`estimateMessageTokens` — ±20–30%, message overhead + tool calls +\n * `IMAGE_TOKEN_ESTIMATE` per image included).\n */\n readonly maxEstimatedTokens: number;\n /**\n * Tokens subtracted from the budget and reserved for the model's next\n * reply (default `0` for the pure function; `session.compact()` defaults\n * to ~10% of the window, mirroring the pre-flight warning threshold's\n * headroom).\n */\n readonly reserveForReply?: number | undefined;\n /**\n * Trailing messages always retained, even when they don't fit the budget\n * (default `2` — the latest user/assistant exchange). Guarantees a\n * compacted conversation never loses its most recent context; an\n * oversized tail is retained deliberately rather than truncated, because\n * silent truncation is the server's failure mode, not one this SDK\n * reproduces.\n */\n readonly minTailMessages?: number | undefined;\n}\n\n/**\n * Sliding-window history compaction: keep the pinned system message(s) plus\n * the most recent turns that fit `maxEstimatedTokens`, dropping the oldest\n * turns in between.\n *\n * Deliberately **not** automatic anywhere in the SDK: compaction rewrites the\n * prompt prefix, so the next request's KV-cache hit rate drops to zero and\n * the whole retained suffix re-evaluates. That tradeoff (latency + recompute\n * for a window that now fits) is sometimes exactly right — long-running\n * agent threads that would otherwise silently lose their oldest turns — and\n * sometimes catastrophic (a hot cache-friendly session that never actually\n * overflows). `ConversationSession.cacheStats` makes the \"session no longer\n * fits\" case visible; this function is the explicit, caller-initiated fix.\n *\n * Semantics:\n *\n * - **Leading `system` messages are always retained** and count against\n * the budget (they consume context too).\n * - Non-system messages are walked newest → oldest; each is retained while\n * it fits the remaining budget, or while fewer than `minTailMessages`\n * have been retained.\n * - Mid-conversation `system`/`tool` messages are ordinary tailable\n * history (only the *leading* system block is pinned).\n * - Returns a new array; the input is never mutated. Message objects are\n * reused by reference (sessions freeze them; external arrays are copied\n * defensively by the caller if needed).\n *\n * ```ts\n * const kept = compactConversationHistory(session.getMessages(), {\n * maxEstimatedTokens: window.contextLength,\n * reserveForReply: 512,\n * });\n * ```\n */\nexport function compactConversationHistory(\n messages: readonly Message[],\n options: CompactionOptions,\n): readonly Message[] {\n const reserve = Math.max(0, options.reserveForReply ?? 0);\n const minTail = Math.max(0, options.minTailMessages ?? 2);\n const budget = Math.max(0, options.maxEstimatedTokens - reserve);\n\n // Pin the leading system block (zero or more messages).\n let split = 0;\n while (split < messages.length && messages[split]!.role === 'system') split += 1;\n const pinned = messages.slice(0, split);\n const tail = messages.slice(split);\n\n let used = 0;\n for (const message of pinned) used += estimateMessageTokens(message);\n\n const retained: Message[] = [];\n for (let i = tail.length - 1; i >= 0; i -= 1) {\n const message = tail[i]!;\n const cost = estimateMessageTokens(message);\n const fits = used + cost <= budget;\n if (!fits && retained.length >= minTail) break;\n retained.unshift(message);\n used += cost;\n }\n\n return [...pinned, ...retained];\n}\n\n/** Options for {@link sanitizeHistoryForNextTurn}; all fields optional. */\nexport interface HistorySanitizeOptions {\n /**\n * Messages — counted from the **end** of the array — whose `images` are\n * preserved. Default `1`: only the final message keeps its image payload,\n * which is the rolling one-image window long-running vision chats almost\n * always want (sanitize after appending the newest turn, and every prior\n * base64 payload is gone by the next request). `0` evicts images\n * everywhere; negative values clamp to `0`.\n */\n readonly keepImagesOnLastMessages?: number | undefined;\n /**\n * Optional note appended to the `content` of each evicted message so the\n * model can still tell an image used to be there — e.g.\n * `\"[image from an earlier turn removed to save context]\"`. When omitted\n * (default) the `images` field is dropped and the text is untouched,\n * matching the wire behavior of never having sent the image at all.\n */\n readonly imagePlaceholder?: string | undefined;\n}\n\n/**\n * Vision-history hygiene: returns a copy of `messages` with image payloads\n * evicted from every message outside the trailing keep-window, conversation\n * text fully preserved.\n *\n * Ollama's `/api/chat` is stateless — each request re-sends and re-bills the\n * whole history, base64 images included (each one costing real context\n * tokens via `IMAGE_TOKEN_ESTIMATE` in the pre-flight estimators). A\n * consumer-managed `messages` array therefore re-uploads every image from\n * every prior turn on every request, long after the model has already\n * answered the question that needed them. This helper is the explicit fix:\n *\n * ```ts\n * history.push({ role: 'user', content: 'What is in THIS photo?', images: [nextImage] });\n * await client.chat({ model, messages: sanitizeHistoryForNextTurn(history) });\n * ```\n *\n * Same philosophy as {@link compactConversationHistory}: caller-initiated,\n * never automatic. Two deliberate tradeoffs, both documented in ADR 0027:\n *\n * - **The model loses access to evicted images** — it keeps the\n * conversation text (and the optional `imagePlaceholder` note) but can\n * no longer \"see\" earlier pictures. That is the point: a bounded\n * payload in exchange for fading visual memory.\n * - **KV-prefix invalidation** — evicting rewrites the message at that\n * position, so the next turn's prompt prefix diverges and the cache\n * re-evaluates from that point. A hot cache-friendly session shouldn't\n * sanitize; a growing vision session should.\n *\n * Pure: the input array is never mutated, and messages that keep their\n * images are reused by reference (identity-stable for the untouched ones,\n * fresh copies only where eviction happened).\n */\nexport function sanitizeHistoryForNextTurn(\n messages: readonly Message[],\n options: HistorySanitizeOptions = {},\n): readonly Message[] {\n const keep = Math.max(0, options.keepImagesOnLastMessages ?? 1);\n const placeholder = options.imagePlaceholder;\n const cutoff = messages.length - keep;\n\n const sanitized: Message[] = [];\n for (let index = 0; index < messages.length; index += 1) {\n const message = messages[index]!;\n if (index >= cutoff || !message.images || message.images.length === 0) {\n sanitized.push(message);\n continue;\n }\n const { images: _evicted, ...rest } = message;\n if (placeholder === undefined) {\n sanitized.push(rest as Message);\n } else {\n sanitized.push({\n ...rest,\n content: rest.content === '' ? placeholder : `${rest.content}\\n\\n${placeholder}`,\n } as Message);\n }\n }\n return sanitized;\n}\n\n/** Options for {@link ConversationSession.compact}; all fields optional. */\nexport interface SessionCompactionOptions {\n /**\n * Token budget for the compacted history. Defaults to the session's own\n * window: `options.num_ctx` from the session config, or Ollama's\n * conservative 2048 fallback when unset — pair with\n * `client.models.getContextLength()` to program against the real window.\n */\n readonly maxEstimatedTokens?: number | undefined;\n /** Reply reservation; defaults to ~10% of the (derived) budget. */\n readonly reserveForReply?: number | undefined;\n /** Trailing messages always kept (default `2`). See {@link CompactionOptions}. */\n readonly minTailMessages?: number | undefined;\n}\n\n/** What {@link ConversationSession.compact} did. */\nexport interface SessionCompactionResult {\n /** Number of messages dropped from the front of the tailable history. */\n readonly droppedMessages: number;\n /** Estimated tokens of the whole history before compaction. */\n readonly estimatedTokensBefore: number;\n /** Estimated tokens of the retained history after compaction. */\n readonly estimatedTokensAfter: number;\n /** The budget that was applied (after the reply reservation). */\n readonly effectiveBudget: number;\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 * Compacts the session's history in place: pinned system prompt plus the\n * most recent turns that fit the budget, oldest tailable turns dropped.\n *\n * This is the explicit escape hatch for sessions that outgrew their\n * window — `cacheStats.hitRate` collapsing toward zero while history grows\n * is the usual symptom, and the pre-flight warnings on `chat()` fire once\n * the prompt estimate crosses the threshold. After compaction the next\n * turn's prompt prefix differs from everything before it, so the KV cache\n * starts cold — visible as a one-turn `evaluatedTokens` spike in\n * `cacheStats`. Cumulative cache tallies are deliberately **not** reset:\n * they are observations, and the spike is part of the story.\n *\n * Returns the before/after estimates and the drop count. No-op (zero\n * drops, equal before/after estimates) when the history already fits.\n */\n compact(options: SessionCompactionOptions = {}): SessionCompactionResult {\n const window =\n options.maxEstimatedTokens ?? this.config.options?.num_ctx ?? OLLAMA_FALLBACK_CONTEXT_LENGTH;\n const reserve = options.reserveForReply ?? Math.ceil(window * 0.1);\n const estimatedTokensBefore = this.history.reduce(\n (sum, message) => sum + estimateMessageTokens(message),\n 0,\n );\n const compacted = compactConversationHistory(this.history, {\n maxEstimatedTokens: window,\n reserveForReply: reserve,\n ...(options.minTailMessages !== undefined\n ? { minTailMessages: options.minTailMessages }\n : {}),\n });\n const estimatedTokensAfter = compacted.reduce(\n (sum, message) => sum + estimateMessageTokens(message),\n 0,\n );\n const droppedMessages = this.history.length - compacted.length;\n this.history.length = 0;\n this.history.push(...compacted);\n return {\n droppedMessages,\n estimatedTokensBefore,\n estimatedTokensAfter,\n effectiveBudget: window - reserve,\n };\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 * Batch-constrained embedding generation for high-volume ingestion pipelines.\n *\n * Ollama's `/api/embed` accepts an array of inputs, but two independent limits\n * make naive usage fragile at corpus scale:\n *\n * 1. **Concurrency.** `Promise.all(inputs.map(...))` fires every request at\n * once; against a local Ollama daemon this contends sockets, saturates the\n * request queue (`OLLAMA_MAX_QUEUE`, surfacing as 503 `overloaded`), and —\n * worst case — exhausts GPU VRAM as the model instance serves N prompts\n * simultaneously.\n * 2. **Context window.** Ollama truncates any input string longer than the\n * model's context window (`num_ctx`) *silently* unless `truncate: false` is\n * set — degraded vectors with no error, no warning, nothing on the wire.\n *\n * {@link batchEmbed} addresses the first with a fixed-size worker pool over\n * `client.embed()` (so every batch still rides the client's full pipeline:\n * failover, retry, auth, logging, telemetry). The client-level\n * `embedBatch()` wrapper addresses the second with a pre-flight per-string\n * token estimate against the resolved `num_ctx` window (see\n * {@link findOversizedEmbedInputs}).\n *\n * Semantics:\n * - **Order-preserving** — result index `i` is always the embedding of\n * `input[i]`, regardless of which batch completed first.\n * - **Fail-fast** — the first batch error aborts every sibling in-flight\n * batch (surfaces the *original* error, not the derived aborts) and rejects\n * the whole operation. Vector indexing that half-succeeds is a corrupted\n * index; callers re-running an ingestion prefer all-or-nothing.\n * - **Abortable** — the caller's `signal` cancels queued and in-flight batches\n * alike and rejects with `code: 'aborted'`.\n */\n\nimport { estimateTokens } from './context-safety.js';\nimport { OllamaAbortError, OllamaClientError } from './errors.js';\nimport type { ModelOptions } from './types.js';\nimport type { EmbedRequestOptions, EmbedResponse } from './types.js';\nimport type { OllamaClient } from './client.js';\n\n/**\n * Default number of input strings per `/api/embed` request. 32 keeps a single\n * request's prompt comfortably inside typical embedding-model context windows\n * (2048+) while amortizing HTTP overhead across the corpus.\n */\nexport const DEFAULT_EMBED_BATCH_SIZE = 32;\n\n/**\n * Default number of batches kept in flight concurrently. 3 is deliberately\n * conservative: a local Ollama daemon serves one model instance per GPU, so\n * 3 concurrent embedding prompts bound queue depth and VRAM pressure without\n * leaving the hardware idle between batches. Raise for multi-endpoint\n * clients or remote daemons; lower (to 1) for constrained devices.\n */\nexport const DEFAULT_EMBED_CONCURRENCY = 3;\n\nexport interface EmbedBatchOptions {\n /** Model to embed with (e.g. `'nomic-embed-text:latest'`). */\n readonly model: string;\n /** Input strings, in corpus order. Result index `i` matches `input[i]`. */\n readonly input: readonly string[];\n /**\n * Inputs per `/api/embed` request. Default {@link DEFAULT_EMBED_BATCH_SIZE}\n * (32). Must be a positive integer.\n */\n readonly batchSize?: number | undefined;\n /**\n * Batches kept in flight simultaneously. Default\n * {@link DEFAULT_EMBED_CONCURRENCY} (3). Must be a positive integer.\n */\n readonly concurrency?: number | undefined;\n /** Passed through to each batch request — `false` makes oversized inputs\n * a server-side error instead of a silent truncation. */\n readonly truncate?: boolean | undefined;\n /** Passed through to each batch request (dimensionality truncation). */\n readonly dimensions?: number | undefined;\n /** Passed through to each batch request (model unload policy). */\n readonly keep_alive?: string | number | undefined;\n /** Ollama model options (`num_ctx`, …) passed through to each batch request. */\n readonly options?: ModelOptions | undefined;\n /** Aborts the whole batch operation — queued and in-flight alike. */\n readonly signal?: AbortSignal | undefined;\n /** Per-request timeout applied to each individual batch request. */\n readonly timeoutMs?: number | undefined;\n /**\n * Progress callback invoked after each successfully embedded batch as\n * `onBatchComplete(completedBatches, totalBatches)`. Never called after the\n * operation rejects.\n */\n readonly onBatchComplete?: ((completedBatches: number, totalBatches: number) => void) | undefined;\n}\n\nexport interface EmbedBatchResult {\n readonly model: string;\n /**\n * Embeddings in input order — `embeddings[i]` corresponds to\n * `options.input[i]`, independent of batch completion order.\n */\n readonly embeddings: readonly (readonly number[])[];\n /** Number of `/api/embed` requests the corpus was split into. */\n readonly batchCount: number;\n}\n\n/** An input string whose estimated token count exceeds the context window. */\nexport interface OversizedEmbedInput {\n /** Index into the input array. */\n readonly index: number;\n /** Estimated token count for `input[index]`. */\n readonly estimate: number;\n}\n\n/**\n * Finds input strings whose heuristic token estimate exceeds `contextLength`\n * (typically the resolved `num_ctx`). Unlike chat/generate pre-flight there is\n * no warning margin and no output-token headroom: an embedding request's\n * prompt IS the whole input, so the exact window is the trip point, and\n * crossing it means silent truncation (or, with `truncate: false`, a\n * server-side rejection).\n */\nexport function findOversizedEmbedInputs(\n input: readonly string[],\n contextLength: number,\n): OversizedEmbedInput[] {\n const oversized: OversizedEmbedInput[] = [];\n for (let index = 0; index < input.length; index++) {\n const text = input[index];\n if (text === undefined) continue;\n const estimate = estimateTokens(text);\n if (estimate > contextLength) {\n oversized.push({ index, estimate });\n }\n }\n return oversized;\n}\n\n/**\n * Builds the warn/throw message for oversized embed inputs (mirrors\n * `contextWarningMessage` for chat/generate).\n */\nexport function embedBatchOverflowMessage(\n oversized: readonly OversizedEmbedInput[],\n totalInputs: number,\n contextLength: number,\n truncateFalse: boolean,\n): string {\n const shown = oversized.slice(0, 5).map((entry) => `#${entry.index} (~${entry.estimate} tokens)`);\n const elided = oversized.length > 5 ? `, +${oversized.length - 5} more` : '';\n const outcome = truncateFalse\n ? 'the server will reject them (`truncate: false`)'\n : 'Ollama will silently truncate them, producing degraded vectors';\n return (\n `embedBatch: ${oversized.length} of ${totalInputs} input strings exceed the ` +\n `${contextLength}-token context window (${shown.join(', ')}${elided}). ` +\n `${outcome}. Raise \\`options.num_ctx\\`, pre-split long inputs, or set ` +\n `\\`truncate: true\\` explicitly to acknowledge truncation.`\n );\n}\n\nfunction assertPositiveInteger(value: number, field: 'batchSize' | 'concurrency'): void {\n if (!Number.isInteger(value) || value < 1) {\n throw new OllamaClientError(\n `embedBatch: \\`${field}\\` must be a positive integer (got ${value}).`,\n { code: 'invalid_request' },\n );\n }\n}\n\n/**\n * Splits `input` into `batchSize` slices and embeds them through `client.embed()`\n * with at most `concurrency` batches in flight. Order-preserving and fail-fast —\n * see the module doc for the full semantics.\n *\n * Prefer the {@link OllamaClient.embedBatch} wrapper, which additionally\n * injects `defaultContextLength` as `num_ctx` and enforces the client's\n * `onContextOverflow` policy against per-string estimates before any request\n * is sent.\n */\nexport async function batchEmbed(\n client: OllamaClient,\n options: EmbedBatchOptions,\n): Promise<EmbedBatchResult> {\n const { model, input } = options;\n const batchSize = options.batchSize ?? DEFAULT_EMBED_BATCH_SIZE;\n const concurrency = options.concurrency ?? DEFAULT_EMBED_CONCURRENCY;\n assertPositiveInteger(batchSize, 'batchSize');\n assertPositiveInteger(concurrency, 'concurrency');\n\n if (input.length === 0) {\n return { model, embeddings: [], batchCount: 0 };\n }\n\n // Partition in corpus order — result index math below depends on it.\n const batches: string[][] = [];\n for (let start = 0; start < input.length; start += batchSize) {\n batches.push(input.slice(start, start + batchSize) as string[]);\n }\n\n const embeddings: (readonly number[] | undefined)[] = new Array(input.length);\n\n // Internal controller: aborted by the caller's `signal` OR by the first\n // batch failure. Every in-flight `client.embed()` receives it, so a single\n // failure (or caller abort) cancels siblings immediately instead of letting\n // them finish — fail-fast, not fail-slow.\n const controller = new AbortController();\n const propagateExternalAbort = (): void => {\n controller.abort(options.signal?.reason);\n };\n if (options.signal) {\n if (options.signal.aborted) {\n propagateExternalAbort();\n } else {\n options.signal.addEventListener('abort', propagateExternalAbort, { once: true });\n }\n }\n\n let nextBatch = 0;\n let completedBatches = 0;\n /** The first failure, rethrown by every sibling worker so the caller always\n * sees the root cause rather than a cascade of derived `AbortError`s. */\n let failure: { error: unknown } | undefined;\n\n const worker = async (): Promise<void> => {\n for (;;) {\n if (controller.signal.aborted) {\n throw failure?.error ?? new OllamaAbortError('Embed batch aborted');\n }\n const batchIndex = nextBatch;\n nextBatch++;\n if (batchIndex >= batches.length) return;\n const batch = batches[batchIndex];\n if (!batch) return;\n\n try {\n const request: EmbedRequestOptions = {\n model,\n input: batch,\n ...(options.truncate !== undefined ? { truncate: options.truncate } : {}),\n ...(options.dimensions !== undefined ? { dimensions: options.dimensions } : {}),\n ...(options.keep_alive !== undefined ? { keep_alive: options.keep_alive } : {}),\n ...(options.options !== undefined ? { options: options.options } : {}),\n ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n signal: controller.signal,\n };\n const response: EmbedResponse = await client.embed(request);\n\n if (response.embeddings.length !== batch.length) {\n throw new OllamaClientError(\n `embedBatch: server returned ${response.embeddings.length} embeddings for a ` +\n `batch of ${batch.length} inputs (batch ${batchIndex}).`,\n { code: 'invalid_response' },\n );\n }\n const offset = batchIndex * batchSize;\n for (let j = 0; j < batch.length; j++) {\n embeddings[offset + j] = response.embeddings[j];\n }\n completedBatches++;\n options.onBatchComplete?.(completedBatches, batches.length);\n } catch (error) {\n if (!failure) {\n failure = { error };\n controller.abort(error);\n throw error;\n }\n // A sibling already failed and aborted us — surface ITS error so the\n // caller diagnoses the root cause, not the derived cancellation.\n throw failure.error;\n }\n }\n };\n\n try {\n const workerCount = Math.min(concurrency, batches.length);\n await Promise.all(Array.from({ length: workerCount }, () => worker()));\n } finally {\n if (options.signal) {\n options.signal.removeEventListener('abort', propagateExternalAbort);\n }\n }\n\n // Defensive completeness check — every index must have been written by the\n // batch that owned it (Promise.all resolving implies every batch resolved).\n for (let i = 0; i < embeddings.length; i++) {\n if (embeddings[i] === undefined) {\n throw new OllamaClientError(\n `embedBatch: internal invariant violated — no embedding produced for input #${i}.`,\n { code: 'invalid_response' },\n );\n }\n }\n\n return {\n model,\n embeddings: embeddings as readonly (readonly number[])[],\n batchCount: batches.length,\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 response: { $ref: '#/schemas/StatusResponse' },\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: 'unsupported',\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: 'unsupported' },\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<StatusResponse> {\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 OllamaAbortError,\n OllamaClientError,\n OllamaModelRoutingError,\n OllamaUnsupportedCapabilityError,\n} from './errors.js';\nimport { createConsoleLogger, NOOP_LOGGER, type Logger } from './logger.js';\nimport {\n EndpointRegistry,\n type EndpointHealth,\n type OllamaEndpoint,\n} from './providers/endpoint-registry.js';\nimport { checkEndpointHealth, type EndpointHealthCheckResult } from './providers/health-check.js';\nimport {\n ModelAffinityRouter,\n type AffinityRunningModel,\n type ModelAffinitySnapshot,\n} from './providers/model-affinity-router.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 batchEmbed,\n embedBatchOverflowMessage,\n findOversizedEmbedInputs,\n type EmbedBatchOptions,\n type EmbedBatchResult,\n} from './embed-batch.js';\nimport {\n checkChatContext,\n checkGenerateContext,\n contextWarningMessage,\n type ContextCheck,\n} from './context-safety.js';\nimport type { ContextDiscoveryRequestOptions } from './context-discovery.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 PingResult,\n} from './types.js';\nimport type { BalanceResponse, UsageResponse } from './generated/models/index.js';\nimport { disposableTimer } from './utils.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 * Controllers for every in-flight request and active stream managed by this\n * client — see {@link OllamaClient.destroy} and {@link createRequestScope}.\n * Entries live for exactly as long as the underlying work does: until the\n * response settles (requests) or the stream's `finalResult` settles\n * (streams, via `executeWithFailover`'s `holdUntil` release path).\n */\n private readonly activeRequests = new Set<AbortController>();\n /**\n * Dynamic multi-host model-affinity routing, active only when\n * `config.endpointHealth.modelAffinity` is set — see\n * `src/providers/model-affinity-router.ts` and ADR 0028. `undefined` means\n * the request path skips reordering entirely (zero overhead, and no `/api/ps`\n * probes are ever issued).\n */\n private readonly modelAffinity: ModelAffinityRouter | undefined;\n\n /** Default timeout for one-off probe requests (`ping`, affinity `/api/ps` refreshes). */\n private static readonly PROBE_TIMEOUT_MS = 5000;\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 const modelAffinityOptions = config.endpointHealth?.modelAffinity;\n this.modelAffinity =\n modelAffinityOptions !== undefined\n ? new ModelAffinityRouter(\n (endpoint) => this.fetchEndpointRunningModels(endpoint),\n modelAffinityOptions,\n )\n : undefined;\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 * Creates the per-request abort scope registered with {@link destroy}:\n * a controller that fires when the caller's `signal` aborts OR when\n * `destroy()` runs, whichever comes first. `dispose()` removes the\n * registration when the work it guards settles — for plain requests when\n * the response settles, for streams when `finalResult` settles (the same\n * moment `executeWithFailover`'s `holdUntil` releases the endpoint slot),\n * so a destroy() can tear down a stream mid-consumption but never outlives\n * one that already finished.\n */\n private createRequestScope(userSignal: AbortSignal | undefined): {\n signal: AbortSignal;\n dispose: () => void;\n } {\n const controller = new AbortController();\n const propagateUserAbort = (): void => {\n controller.abort(userSignal?.reason);\n };\n let detach: (() => void) | undefined;\n if (userSignal) {\n if (userSignal.aborted) {\n propagateUserAbort();\n } else {\n userSignal.addEventListener('abort', propagateUserAbort, { once: true });\n detach = () => userSignal.removeEventListener('abort', propagateUserAbort);\n }\n }\n this.activeRequests.add(controller);\n return {\n signal: controller.signal,\n dispose: () => {\n detach?.();\n this.activeRequests.delete(controller);\n },\n };\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 scope = this.createRequestScope(options?.signal);\n const timeout = createTimeoutSignal(options?.timeoutMs ?? this.timeoutMs, scope.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 // Dynamic model-affinity routing: a synchronous, cache-only reorder of the\n // runnable set (endpoints whose fresh GET /api/ps snapshot shows the target\n // model resident come first). Deliberately no `await` between here and the\n // `acquire()` below — see ModelAffinityRouter's module docs and ADR 0028;\n // the 'least-connections' race-free guarantee depends on it. No-op (and no\n // /api/ps probes at all) unless `endpointHealth.modelAffinity` is configured.\n const ordered =\n this.modelAffinity !== undefined\n ? this.modelAffinity.reorder(runnable, options?.model)\n : runnable;\n\n for (const [attemptIndex, endpoint] of ordered.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 scope.dispose();\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) {\n timeout.cancel();\n scope.dispose();\n }\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 * Batch-constrained, order-preserving embedding generation for large\n * corpora — the safe building block for RAG/vector-index ingestion at\n * scale. Splits `input` into `batchSize` slices and embeds them through\n * {@link embed} with at most `concurrency` batches in flight (defaults:\n * 32 × 3), so `Promise.all`-style floods that OOM local daemons and\n * saturate `OLLAMA_MAX_QUEUE` can't happen by accident. Fail-fast: the\n * first batch error aborts every sibling in-flight batch and rejects the\n * whole operation with the original error.\n *\n * Before any request is sent, `defaultContextLength` is injected as\n * `num_ctx` (same as chat/generate) and each input string's token estimate\n * is checked against the resolved window: Ollama silently truncates\n * oversized embedding inputs by default, so the client warns (or throws,\n * under `onContextOverflow: 'throw'`) with the offending indexes — see\n * `src/embed-batch.ts` for the exact trip point (no margin: an embedding\n * prompt IS the whole input).\n *\n * ```ts\n * const { embeddings, batchCount } = await client.embedBatch({\n * model: 'nomic-embed-text:latest',\n * input: corpus, // e.g. 50k chunks\n * batchSize: 32, // inputs per /api/embed request\n * concurrency: 3, // batches in flight\n * onBatchComplete: (done, total) => progress.log(`${done}/${total}`),\n * });\n * // embeddings[i] always corresponds to corpus[i]\n * ```\n */\n async embedBatch(options: EmbedBatchOptions): Promise<EmbedBatchResult> {\n const resolvedOptions = this.injectDefaultContextLength(options.options);\n const contextLength = resolvedOptions?.num_ctx;\n if (contextLength !== undefined) {\n const oversized = findOversizedEmbedInputs(options.input, contextLength);\n if (oversized.length > 0) {\n const message = embedBatchOverflowMessage(\n oversized,\n options.input.length,\n contextLength,\n options.truncate === false,\n );\n if (this.onContextOverflow === 'throw') {\n throw new OllamaClientError(message, { code: 'context_overflow' });\n }\n this.logger.warn(message);\n }\n }\n return batchEmbed(\n this,\n resolvedOptions === options.options ? options : { ...options, options: resolvedOptions },\n );\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 = (request?: RequestCancellationOptions) => this.models.ps(request);\n /**\n * Discovers the model's real context window — the allocated window of the\n * running instance (`/api/ps`), the Modelfile `num_ctx` default, and the\n * native GGUF maximum (`/api/show` `model_info`), resolved by precedence.\n * Convenience alias for {@link ModelsClient.getContextLength} — see that\n * method for the full contract and the precedence order.\n */\n readonly getContextLength = (request: ContextDiscoveryRequestOptions) =>\n this.models.getContextLength(request);\n readonly version = () => this.models.version();\n readonly createBlob = (digest: string, data: BinaryBody, request?: RequestCancellationOptions) =>\n this.models.createBlob(digest, data, request);\n readonly checkBlob = (digest: string, request?: RequestCancellationOptions) =>\n this.models.checkBlob(digest, request);\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 scope = this.createRequestScope(options.signal);\n const timeout = createTimeoutSignal(options.timeoutMs ?? this.timeoutMs, scope.signal);\n using _timeout = {\n [Symbol.dispose]() {\n timeout.cancel();\n scope.dispose();\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\n /**\n * Ultra-lightweight liveness probe against the client's current best\n * endpoint: `HEAD /` — the root ping Ollama's documentation defines for\n * load-balancer health checks (HTTP 200; the daemon answers `GET /` with the\n * plain-text body \"Ollama is running\", which a HEAD request doesn't transfer).\n *\n * Deliberately a *single-endpoint, single-shot* probe — no failover to other\n * candidates, no retry — so the answer reflects one concrete host, not \"some\n * endpoint eventually answered\". To audit every configured endpoint, use\n * {@link healthCheck} (which probes all of them, and also reports the server\n * version at the cost of the heavier `GET /api/version` round trip).\n *\n * Resolves — never throws — with `{ healthy: false, error }` for connection\n * failures and timeouts; only caller-initiated cancellation (`signal`/\n * `destroy()`) rejects, mirroring how any other aborted request behaves.\n */\n async ping(options?: RequestCancellationOptions): Promise<PingResult> {\n const endpoint = this.registry.candidates()[0];\n if (endpoint === undefined) {\n return { healthy: false, latencyMs: 0, baseUrl: '', error: 'No configured endpoints' };\n }\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 });\n\n const timeout = createTimeoutSignal(\n options?.timeoutMs ?? OllamaClient.PROBE_TIMEOUT_MS,\n options?.signal,\n );\n const startTime = Date.now();\n try {\n await http.request<void>({ path: '/', method: 'HEAD', signal: timeout.signal });\n return { healthy: true, latencyMs: Date.now() - startTime, baseUrl: endpoint.baseUrl };\n } catch (err) {\n if (options?.signal?.aborted) {\n // Caller-initiated cancellation is not an unhealthiness signal.\n throw err instanceof Error ? err : new Error(String(err));\n }\n return {\n healthy: false,\n latencyMs: Date.now() - startTime,\n baseUrl: endpoint.baseUrl,\n error: err instanceof Error ? err.message : String(err),\n };\n } finally {\n timeout.cancel();\n }\n }\n\n /**\n * Affinity-cache snapshots for every configured endpoint — which models each\n * host held in VRAM at the last successful `/api/ps` probe, when that was, and\n * whether it's still fresh. Empty when `endpointHealth.modelAffinity` isn't\n * configured (no probes are ever issued, so there is nothing to report).\n */\n modelAffinityStatus(): readonly ModelAffinitySnapshot[] {\n return this.modelAffinity?.status(this.registry.list()) ?? [];\n }\n\n /**\n * Explicitly refreshes the model-affinity cache for every configured endpoint\n * (deduped with any in-flight background refresh). No-op — resolves\n * immediately — when `endpointHealth.modelAffinity` isn't configured. Use it\n * to warm the cache at startup so the very first request already routes by\n * residency instead of waiting for the self-warming first-round refresh.\n */\n async warmModelAffinity(): Promise<void> {\n await this.modelAffinity?.warm(this.registry.list());\n }\n\n endpointStatus(): EndpointHealth[] {\n return this.registry.status();\n }\n\n /**\n * Fetches one endpoint's `GET /api/ps` running-model list for the affinity\n * router. Bypasses `executeWithFailover` deliberately: probes must not\n * reenter the routing machinery they inform, must not touch the registry's\n * circuit-breaker/failure bookkeeping (a dead host's probe failing must not\n * cool it down harder than its real traffic already does), and must not fail\n * over to a different host (the answer is per-host by definition). Failures\n * propagate to the router, which records a short backoff and retries later.\n */\n private async fetchEndpointRunningModels(\n endpoint: OllamaEndpoint,\n ): Promise<readonly AffinityRunningModel[]> {\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 });\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), OllamaClient.PROBE_TIMEOUT_MS);\n using _timer = disposableTimer(timer);\n const res = await http.request<{ models?: readonly AffinityRunningModel[] }>({\n path: '/api/ps',\n method: 'GET',\n signal: controller.signal,\n });\n return res.models ?? [];\n }\n\n /**\n * Immediately aborts every in-flight request and active stream managed by\n * this client — the clean teardown path for short-lived processes, CLI\n * runners, and `node:worker_threads` tasks where dangling fetch bodies,\n * unconsumed stream readers, or queued capacity waiters would otherwise\n * keep the event loop (and thus the thread/process) alive.\n *\n * Every aborted operation rejects with an {@link OllamaAbortError}\n * (`code: 'aborted'`) carrying `reason` as its message — including requests\n * still queued behind `maxConcurrentPerEndpoint`, not just dispatched ones.\n * Streams reject their `finalResult` and release their endpoint slots.\n *\n * Idempotent: calling it again (or on a client with nothing in flight)\n * is a no-op that returns `0`. The client remains usable afterward —\n * `destroy()` is a drain, not a permanent disable; callers that want a\n * permanently-dead client should discard the instance.\n *\n * @returns the number of in-flight operations that were aborted.\n */\n destroy(reason: string = 'Ollama client destroyed'): number {\n const controllers = [...this.activeRequests];\n const cause = new OllamaAbortError(reason);\n for (const controller of controllers) {\n controller.abort(cause);\n }\n this.activeRequests.clear();\n return controllers.length;\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 * Zero-copy stream observation — the safe alternative to `ReadableStream.tee()`\n * for multi-sink consumption (audit logging, token counting, telemetry taps).\n *\n * ## The `tee()` hazard this exists for\n *\n * Developers streaming to a UI while also feeding a logger (or a token\n * counter, or an OpenTelemetry exporter) typically reach for:\n *\n * ```ts\n * // VULNERABLE PATTERN — do not do this\n * const [forUi, forLogger] = response.body.tee();\n * ```\n *\n * WHATWG `tee()` branches share a single upstream pull mechanism: a branch\n * that reads slower than its sibling forces every intermediate chunk to be\n * retained in that branch's internal queue until it catches up. If the slow\n * consumer is a logger waiting on a database write — or never drains at all —\n * the queue grows without bound, and because both branches apply shared\n * backpressure, the *fast* consumer is throttled by the slowest one. In a\n * long-lived streaming server this is a slow, silent heap leak.\n *\n * ## What `observeStream` does instead\n *\n * A single-pass wrapper: chunks flow from the source through the observer\n * callbacks to the primary consumer with **no second queue and no forked\n * stream**. The contract is deliberately one-sided in favor of the primary\n * consumer:\n *\n * - **Never blocks.** Observer callbacks run on a serialized microtask\n * chain, not on the hot path. A slow async observer (a logger waiting on\n * I/O) delays only its own tail — the primary consumer keeps receiving\n * chunks at source speed.\n * - **Never fails.** An observer that throws (sync) or rejects (async) is\n * routed to `onListenerError` and otherwise discarded. Observer failures\n * can never poison the primary pipeline.\n * - **Never leaks via the wrapper.** There is no second branch to\n * backpressure. The only retained state is one closure per backlogged\n * observer callback; if your observer can stall *forever*, bound it on\n * your side (queue, drop policy) — the wrapper will keep enqueueing\n * otherwise, exactly like any fire-and-forget log sink.\n * - **Ordered.** Observer callbacks run strictly FIFO, one at a time —\n * async sinks see chunks in stream order, and `onDone` is enqueued only\n * after the last chunk's callback settles. (This is intentionally\n * stricter than a naive `void onChunk(chunk)` fire-and-forget, which\n * runs concurrent, out-of-order observers and turns a rejected async\n * callback into an unhandled rejection.)\n *\n * ## Lifecycle\n *\n * - Source completes naturally → `onDone` (enqueued after the last chunk\n * callback settles, so a logger has flushed everything it saw).\n * - Source throws → `onError(err)` immediately, then the error re-throws to\n * the primary consumer (the observer is transparent, not a circuit\n * breaker).\n * - Primary consumer stops early (`break` / `return` / `throw` inside the\n * `for await` loop) → `onAbandon()` immediately. This is distinct from\n * completion: the source's iterator-`return()` has already closed the\n * underlying transport by the time `onAbandon` fires.\n *\n * Works over any `AsyncIterable<T>` — the SDK's `OllamaStream` (streaming\n * `chat`/`generate`), the raw NDJSON chunk iterables, or your own sources.\n * Note that `OllamaStream` itself is dual-mode but mode-exclusive (`.on()`\n * listeners cannot be combined with `for await`); `observeStream` is the\n * supported way to tap a stream you are already iterating.\n */\n\n/**\n * Lifecycle phase an observer failure came from. `'chunk'` and `'done'`\n * failures arrive from the serialized callback chain; `'error'` and\n * `'abandon'` failures come from those terminal hooks themselves.\n */\nexport type StreamObserverPhase = 'chunk' | 'done' | 'error' | 'abandoned';\n\n/** Passive, best-effort observer hooks — see the module docs for semantics. */\nexport interface StreamObserverCallbacks<T> {\n /**\n * Called once per chunk, in stream order, FIFO, never overlapping with a\n * previous still-running call. May be sync (`void`) or async\n * (`Promise<void>`); async return values are awaited *on the observer\n * chain only* — they never delay the primary consumer. Rejections (and\n * sync throws) route to {@link StreamObserverCallbacks.onListenerError}.\n */\n onChunk?: ((chunk: T) => void | Promise<void>) | undefined;\n /**\n * Called with the source's error immediately before that error is re-thrown\n * to the primary consumer. A throwing `onError` hook cannot mask the\n * original error — it is reported via {@link StreamObserverCallbacks.onListenerError}\n * and the original error still propagates.\n */\n onError?: ((error: unknown) => void) | undefined;\n /**\n * Called when the source completes naturally — enqueued after the last\n * chunk's observer callback settles, so a flushed logger has seen every\n * chunk before its \"done\" marker.\n */\n onDone?: (() => void | Promise<void>) | undefined;\n /**\n * Called when the primary consumer stops early (`break`/`return`/`throw` in\n * the consuming loop). The source has already been closed via the\n * iterator-`return()` protocol when this fires. `onDone` does not fire in\n * this case.\n */\n onAbandon?: (() => void) | undefined;\n /**\n * The observation failure channel: any observer hook that throws or rejects\n * is reported here together with the phase it came from, and then\n * discarded. If this hook itself throws, the failure is swallowed — an\n * error reporter must never become the next unhandled rejection.\n */\n onListenerError?: ((error: unknown, phase: StreamObserverPhase) => void) | undefined;\n}\n\n/**\n * Wraps an `AsyncIterable` with passive observer hooks without creating a\n * secondary buffered stream queue — avoiding the memory retention and shared\n * backpressure penalties of `ReadableStream.tee()`.\n *\n * @example\n * ```ts\n * const stream = await client.chat({ model: 'llama4', messages, stream: true });\n * let tokens = 0;\n * const observed = observeStream(stream, {\n * onChunk: (event) => {\n * if (event.type === 'token') tokens += 1;\n * auditLog.write(event); // slow async sink — never delays the consumer\n * },\n * onDone: () => auditLog.flush(),\n * onListenerError: (err) => telemetry.count('audit_log_failure', err),\n * });\n * for await (const event of observed) {\n * ui.render(event); // primary consumer — full speed, full order\n * }\n * ```\n */\nexport async function* observeStream<T>(\n source: AsyncIterable<T>,\n callbacks: StreamObserverCallbacks<T> = {},\n): AsyncGenerator<T, void, unknown> {\n const { onChunk, onError, onDone, onAbandon, onListenerError } = callbacks;\n\n /** Reports a failing observer hook without ever throwing ourselves. */\n const reportListenerFailure = (error: unknown, phase: StreamObserverPhase): void => {\n try {\n onListenerError?.(error, phase);\n } catch {\n // The error reporter itself failed — nothing further we can safely do.\n }\n };\n\n // Serialized observer chain: every queued callback runs FIFO, one at a\n // time, on microtasks. Sync observers pay one hop; async observers queue\n // behind each other (bounded concurrency of exactly one); failures are\n // routed to `onListenerError` instead of surfacing as unhandled\n // rejections. The chain is never awaited on the primary path.\n let observerChain: Promise<void> = Promise.resolve();\n const dispatch = (phase: StreamObserverPhase, task: () => void | Promise<void>): void => {\n observerChain = observerChain.then(task).then(\n () => undefined,\n (error: unknown) => {\n reportListenerFailure(error, phase);\n },\n );\n };\n\n // 'running' while the source is being consumed; flipped to a terminal\n // state before the natural/error paths complete so the `finally` block can\n // distinguish \"consumer walked away\" (the only case that still reads\n // 'running' there) from completion and failure.\n let state: 'running' | 'done' | 'error' | 'abandoned' = 'running';\n try {\n for await (const chunk of source) {\n if (onChunk !== undefined) {\n dispatch('chunk', () => onChunk(chunk));\n }\n yield chunk;\n }\n state = 'done';\n if (onDone !== undefined) {\n // Enqueued after the last chunk callback has settled (FIFO chain), so\n // sinks observe their \"done\" marker only after every chunk was handed\n // over — even when the last async sink was still draining.\n dispatch('done', () => onDone());\n }\n } catch (error) {\n state = 'error';\n // Terminal hooks fire immediately rather than joining the chain: the\n // source has stopped, so there is nothing left to stay ordered with, and\n // error surfacing should not wait behind a slow logger.\n try {\n onError?.(error);\n } catch (listenerError) {\n reportListenerFailure(listenerError, 'error');\n }\n throw error;\n } finally {\n if (state === 'running') {\n // The only way to land here still 'running' is an early exit at the\n // `yield` (break/return/throw in the consuming loop): the for-await's\n // iterator-close protocol has already called `source.return()` and\n // awaited it, so the transport is closed by the time this fires.\n state = 'abandoned';\n try {\n onAbandon?.();\n } catch (listenerError) {\n reportListenerFailure(listenerError, 'abandoned');\n }\n }\n }\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","/**\n * Ollama web search / web fetch exposed as model-callable tools.\n *\n * Implements the \"Building a search agent\" pattern from\n * https://docs.ollama.com/capabilities/web-search: hand `web_search` and `web_fetch`\n * to a tool-capable model, execute the calls it emits against Ollama Cloud's hosted\n * `/api/web_search` and `/api/web_fetch`, and feed bounded results back as\n * `role: 'tool'` messages. Use with {@link ToolRegistry} / `Agent`.\n */\n\nimport { z } from 'zod';\nimport type {\n WebFetchRequestOptions,\n WebFetchResponse,\n WebSearchRequestOptions,\n WebSearchResponse,\n} from '../types.js';\nimport { defineTool } from './define-tool.js';\nimport type { Tool } from './types.js';\n\n/** The subset of `OllamaClient` the web tools call. */\nexport interface WebToolsClient {\n webSearch(req: WebSearchRequestOptions): Promise<WebSearchResponse>;\n webFetch(req: WebFetchRequestOptions): Promise<WebFetchResponse>;\n}\n\nexport interface WebToolsOptions {\n /**\n * Upper bound on the model-visible JSON a single call returns. Web pages and search\n * snippets can run to thousands of tokens; the docs truncate each result to\n * `2000 * 4` characters, which is the default here. Content fields are trimmed (not\n * the serialized JSON), so the output always stays valid JSON.\n */\n readonly maxOutputChars?: number | undefined;\n /** `max_results` sent when the model omits it. Server default is 5, max 10. */\n readonly defaultMaxResults?: number | undefined;\n /** Maximum number of page links `web_fetch` returns to the model. Default 25. */\n readonly maxLinks?: number | undefined;\n /** Per-call tool execution timeout in milliseconds (see `ToolRegistryOptions.timeoutMs`). */\n readonly timeoutMs?: number | undefined;\n}\n\nexport const WEB_SEARCH_TOOL_NAME = 'web_search';\nexport const WEB_FETCH_TOOL_NAME = 'web_fetch';\n\nconst DEFAULT_MAX_OUTPUT_CHARS = 2000 * 4;\nconst DEFAULT_MAX_LINKS = 25;\nconst TRUNCATION_MARKER = '…[truncated]';\n\nconst webSearchSchema = z.object({\n query: z.string().min(1).describe('The search query string'),\n max_results: z\n .number()\n .int()\n .min(1)\n .max(10)\n .optional()\n .describe('Maximum results to return (default 5, max 10)'),\n});\n\nconst webFetchSchema = z.object({\n url: z.string().min(1).describe('The URL of the web page to fetch'),\n});\n\nexport type WebSearchToolParams = z.infer<typeof webSearchSchema>;\nexport type WebFetchToolParams = z.infer<typeof webFetchSchema>;\n\nfunction positiveInt(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (!Number.isInteger(value) || value < 1) {\n throw new RangeError(`${name} must be a positive integer, received ${String(value)}`);\n }\n return value;\n}\n\nfunction truncate(text: string, maxChars: number): string {\n if (text.length <= maxChars) return text;\n if (maxChars <= TRUNCATION_MARKER.length) return text.slice(0, maxChars);\n return text.slice(0, maxChars - TRUNCATION_MARKER.length) + TRUNCATION_MARKER;\n}\n\n/** Serialize a web search response within `maxChars`, trimming each snippet evenly. */\nexport function formatWebSearchResult(res: WebSearchResponse, maxChars: number): string {\n const results = res.results.map(({ title, url, content }) => ({ title, url, content }));\n const full = JSON.stringify({ results });\n if (full.length <= maxChars || results.length === 0) return truncate(full, maxChars);\n\n // Budget the content fields: everything except the snippets is structural overhead.\n const overhead = JSON.stringify({\n results: results.map((r) => ({ ...r, content: '' })),\n }).length;\n const perResult = Math.max(0, Math.floor((maxChars - overhead) / results.length));\n const trimmed = JSON.stringify({\n results: results.map((r) => ({ ...r, content: truncate(r.content, perResult) })),\n });\n // JSON escaping can still overshoot the estimate; fall back to a hard cut.\n return trimmed.length <= maxChars ? trimmed : truncate(trimmed, maxChars);\n}\n\n/** Serialize a web fetch response within `maxChars`, trimming page content first. */\nexport function formatWebFetchResult(\n res: WebFetchResponse,\n maxChars: number,\n maxLinks: number = DEFAULT_MAX_LINKS,\n): string {\n const page = {\n title: res.title ?? '',\n content: res.content,\n links: (res.links ?? []).slice(0, maxLinks),\n };\n const full = JSON.stringify(page);\n if (full.length <= maxChars) return full;\n\n const overhead = JSON.stringify({ ...page, content: '' }).length;\n const trimmed = JSON.stringify({\n ...page,\n content: truncate(page.content, Math.max(0, maxChars - overhead)),\n });\n return trimmed.length <= maxChars ? trimmed : truncate(trimmed, maxChars);\n}\n\n/** `web_search` tool backed by {@link WebToolsClient.webSearch}. */\nexport function createWebSearchTool(\n client: WebToolsClient,\n options: WebToolsOptions = {},\n): Tool<WebSearchToolParams, string> {\n const maxChars = positiveInt(options.maxOutputChars, DEFAULT_MAX_OUTPUT_CHARS, 'maxOutputChars');\n const defaultMaxResults =\n options.defaultMaxResults === undefined\n ? undefined\n : Math.min(positiveInt(options.defaultMaxResults, 5, 'defaultMaxResults'), 10);\n return defineTool({\n name: WEB_SEARCH_TOOL_NAME,\n description:\n 'Search the web for current information. Returns a list of results, each with a title, url, and relevant content snippet.',\n schema: webSearchSchema,\n timeoutMs: options.timeoutMs,\n execute: async ({ query, max_results }, { signal }) => {\n const res = await client.webSearch({\n query,\n ...((max_results ?? defaultMaxResults) !== undefined\n ? { max_results: max_results ?? defaultMaxResults }\n : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n return formatWebSearchResult(res, maxChars);\n },\n });\n}\n\n/** `web_fetch` tool backed by {@link WebToolsClient.webFetch}. */\nexport function createWebFetchTool(\n client: WebToolsClient,\n options: WebToolsOptions = {},\n): Tool<WebFetchToolParams, string> {\n const maxChars = positiveInt(options.maxOutputChars, DEFAULT_MAX_OUTPUT_CHARS, 'maxOutputChars');\n const maxLinks = positiveInt(options.maxLinks, DEFAULT_MAX_LINKS, 'maxLinks');\n return defineTool({\n name: WEB_FETCH_TOOL_NAME,\n description:\n 'Fetch a single web page by URL. Returns the page title, its main content, and links found on the page.',\n schema: webFetchSchema,\n timeoutMs: options.timeoutMs,\n execute: async ({ url }, { signal }) => {\n const res = await client.webFetch({ url, ...(signal !== undefined ? { signal } : {}) });\n return formatWebFetchResult(res, maxChars, maxLinks);\n },\n });\n}\n\n/**\n * Both web tools, ready to register:\n *\n * ```ts\n * const registry = new ToolRegistry(createWebTools(client));\n * const agent = new Agent(client, { tools: registry });\n * ```\n *\n * Requires an Ollama API key on the client (`apiKey` or `OLLAMA_API_KEY`); calls\n * always go to `https://ollama.com`, independent of the client's inference endpoints.\n */\nexport function createWebTools(\n client: WebToolsClient,\n options: WebToolsOptions = {},\n): [Tool<WebSearchToolParams, string>, Tool<WebFetchToolParams, string>] {\n return [createWebSearchTool(client, options), createWebFetchTool(client, options)];\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 OllamaAgentToolLoopError,\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, ToolCall, 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?: ((model: string, signal?: AbortSignal) => Promise<ModelCapabilities>) | 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/** Cap on the `signature` carried by {@link OllamaAgentToolLoopError} — enough to\n * identify the call, small enough not to bloat logs with a huge payload. */\nconst SIGNATURE_REPORT_LIMIT = 200;\n\n/** `JSON.stringify` with recursively sorted object keys, so key order never\n * splits one logical value into several distinct strings. `undefined` maps\n * to `'null'` to keep the output a valid JSON fragment. */\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') {\n return JSON.stringify(value) ?? 'null';\n }\n if (Array.isArray(value)) {\n return `[${value.map((entry) => stableStringify(entry)).join(',')}]`;\n }\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, entryValue]) => entryValue !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([key, entryValue]) => `${JSON.stringify(key)}:${stableStringify(entryValue)}`);\n return `{${entries.join(',')}}`;\n}\n\n/**\n * Canonical signature of a tool call for cycle detection: `name(args)` with\n * recursively key-sorted arguments, so the same call re-emitted by a model\n * in a different argument key order collapses to one signature instead of\n * counting as two \"distinct\" calls.\n *\n * ```ts\n * canonicalToolCallSignature({ function: { name: 'search', arguments: { q: 'x' } } })\n * // 'search({\"q\":\"x\"})'\n * ```\n */\nexport function canonicalToolCallSignature(toolCall: ToolCall): string {\n return `${toolCall.function.name}(${stableStringify(toolCall.function.arguments)})`;\n}\n\nfunction reportableSignature(signature: string): string {\n return signature.length <= SIGNATURE_REPORT_LIMIT\n ? signature\n : `${signature.slice(0, SIGNATURE_REPORT_LIMIT)}…`;\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 maxRepeatedToolCalls?: 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.maxRepeatedToolCalls = config.maxRepeatedToolCalls;\n this.hooks = config.hooks;\n if (\n this.maxToolCalls !== undefined &&\n (!Number.isInteger(this.maxToolCalls) || this.maxToolCalls < 0)\n ) {\n throw new RangeError('Agent maxToolCalls must be a non-negative integer');\n }\n if (\n this.maxRepeatedToolCalls !== undefined &&\n (!Number.isInteger(this.maxRepeatedToolCalls) || this.maxRepeatedToolCalls < 1)\n ) {\n throw new RangeError('Agent maxRepeatedToolCalls must be a positive 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 /** Canonical-signature execution counts for cycle detection — one entry per\n * distinct `name(args)` pair this run has handed to the registry. */\n const signatureCounts = new Map<string, number>();\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 (\n this.maxToolCalls !== undefined &&\n toolCallsExecuted + toolCalls.length > this.maxToolCalls\n ) {\n throw new OllamaAgentMaxToolCallsError(\n `Agent exceeded max tool calls (${this.maxToolCalls})`,\n { maxToolCalls: this.maxToolCalls, toolCallsExecuted },\n );\n }\n\n // Cycle detection: prospective per-signature counts for this batch\n // (duplicate calls within one batch see each other). Checked before\n // any of the batch executes and before onToolCallStart fires, so hook\n // pairing stays consistent and the doomed batch is never started —\n // mirroring the maxToolCalls semantics above.\n if (this.maxRepeatedToolCalls !== undefined) {\n for (const tc of toolCalls) {\n const signature = canonicalToolCallSignature(tc);\n const executions = (signatureCounts.get(signature) ?? 0) + 1;\n if (executions > this.maxRepeatedToolCalls) {\n throw new OllamaAgentToolLoopError(\n `Agent would repeat tool call \"${tc.function.name}\" ${executions} times ` +\n `(max ${this.maxRepeatedToolCalls}) without changing arguments — stuck in a tool loop`,\n {\n toolName: tc.function.name,\n repeatedExecutions: executions,\n maxRepeatedToolCalls: this.maxRepeatedToolCalls,\n signature: reportableSignature(signature),\n },\n );\n }\n signatureCounts.set(signature, executions);\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 * Speculative-decoding draft benchmark — measures whether the runtime\n * `draft_num_predict` option provides a net throughput gain for a specific\n * prompt (October 13 digest; see ADR 0030).\n *\n * Upstream Ollama does not emit a dedicated draft-token acceptance counter —\n * speculative efficiency is only observable as effective throughput\n * (`eval_count` / `eval_duration`). And the signal is noisy: rejected draft\n * predictions *add* compute (high-temperature, creative, non-deterministic\n * prompts), while accepted drafts dramatically cut `eval_duration` on\n * predictable workloads (structured code generation, JSON extraction). A\n * single run therefore proves nothing — this helper implements the\n * deterministic profiling protocol the upstream observations call for:\n *\n * - **Deterministic sampling** — `temperature: 0` is forced and a fixed\n * `seed` (default 42) is stamped on every measured run, so both sides\n * generate comparable token streams.\n * - **Warm-up discard** — one throwaway `num_predict: 1` generation per\n * setting pays the model load (`load_duration`) before any sample is\n * taken.\n * - **Identical prompt, both sides** — baseline (`draft_num_predict: 0`,\n * drafting disabled) vs. speculative (`draft_num_predict: N`), several\n * samples each, **median** compared (single samples mislead).\n * - Throughput comes from `formatTelemetry` — the official Usage-doc\n * tokens/second math, never hand-rolled nanosecond division.\n *\n * `effectiveGain` is true when the reported `speedupMultiplier` exceeds\n * `gainThreshold` (default 1.05 — five percent, past run-to-run noise). A\n * speedup of about 1.0 usually means the model has **no draft network** (and\n * no embedded MTP tensors): the server silently ignores the option and both\n * sides measure the same — see `lab/15-speculative-draft` for a per-setting\n * table over 0/4/8/16.\n *\n * ```ts\n * import { OllamaClient, compareDraftPerformance } from '@nemesis-oss/ollama-sdk';\n *\n * const comparison = await compareDraftPerformance(new OllamaClient(), {\n * model: 'llama3.1',\n * prompt: 'Extract the sender, subject, and date from this email as JSON: ...',\n * });\n * if (comparison.effectiveGain) {\n * // drafting pays off for this prompt\n * }\n * ```\n */\n\nimport { OllamaClientError } from './errors.js';\nimport { formatTelemetry } from './telemetry/index.js';\nimport type { GenerateRequestOptions, GenerateResponse } from './types.js';\n\n/**\n * Structural dependency of {@link compareDraftPerformance}: anything that can\n * run a non-streaming `/api/generate` call. `OllamaClient` satisfies it\n * without being named (same discipline as the model-affinity router's\n * structural client), so tests and alternative transports can substitute a\n * minimal object.\n */\nexport interface DraftBenchmarkClient {\n generate(req: GenerateRequestOptions & { stream?: false | undefined }): Promise<GenerateResponse>;\n}\n\n/** Options for {@link compareDraftPerformance}. */\nexport interface CompareDraftPerformanceOptions {\n /** Model to benchmark — must be a name the target server can load. */\n readonly model: string;\n /**\n * The prompt both sides generate. The comparison is only meaningful with a\n * fixed prompt: draft acceptance — and thus speedup — is workload-dependent\n * (structured/predictable prompts gain the most; creative ones can lose).\n */\n readonly prompt: string;\n /**\n * Draft tokens per step for the speculative side. Default `4` (Ollama's\n * default for separate draft models). Must be >= 1 — the baseline side\n * always measures with drafting disabled (`0`).\n */\n readonly draftNumPredict?: number | undefined;\n /**\n * Measured runs per setting; the median is reported. Default `5`. Single\n * samples mislead — noisy small-model runs swing tens of percent.\n */\n readonly samples?: number | undefined;\n /** `num_predict` cap per measured run. Default `256`. */\n readonly numPredict?: number | undefined;\n /** Fixed sampling seed stamped on every run (with `temperature: 0`). Default `42`. */\n readonly seed?: number | undefined;\n /**\n * Run one throwaway `num_predict: 1` generation per setting before sampling\n * (pays the model load). Default `true`.\n */\n readonly warmup?: boolean | undefined;\n /**\n * `speedupMultiplier` above this reports `effectiveGain: true`. Default\n * `1.05` — five percent, past typical run-to-run noise.\n */\n readonly gainThreshold?: number | undefined;\n /** Abort signal — checked before every run and forwarded to each generate call. */\n readonly signal?: AbortSignal | undefined;\n}\n\n/** One side's measurement detail (see {@link DraftPerformanceComparison}). */\nexport interface DraftRunStats {\n /** The `draft_num_predict` value this side ran with (`0` = baseline). */\n readonly draftNumPredict: number;\n /** Median tokens/second across the valid samples (unrounded). */\n readonly medianTokensPerSecond: number;\n /** Every valid sample's tokens/second, in run order. */\n readonly sampleTokensPerSecond: readonly number[];\n /** Median generation-phase duration (`eval_duration`) in milliseconds. */\n readonly medianEvalDurationMs: number;\n}\n\n/** Result of {@link compareDraftPerformance}. */\nexport interface DraftPerformanceComparison {\n /** The model that was benchmarked. */\n readonly model: string;\n /** The prompt both sides generated. */\n readonly prompt: string;\n /** The speculative side's `draft_num_predict` (the baseline always ran `0`). */\n readonly draftNumPredict: number;\n /** Baseline median tokens/second, rounded to 1 decimal. */\n readonly baselineTokensPerSec: number;\n /** Speculative median tokens/second, rounded to 1 decimal. */\n readonly speculativeTokensPerSec: number;\n /** `speculativeTokensPerSec / baselineTokensPerSec`, rounded to 2 decimals. */\n readonly speedupMultiplier: number;\n /** `true` when the reported `speedupMultiplier` exceeds `gainThreshold`. */\n readonly effectiveGain: boolean;\n /** The threshold `effectiveGain` was evaluated against. */\n readonly gainThreshold: number;\n /** Full baseline detail (samples, medians). */\n readonly baseline: DraftRunStats;\n /** Full speculative detail (samples, medians). */\n readonly speculative: DraftRunStats;\n}\n\nconst DEFAULT_DRAFT_TOKENS = 4;\nconst DEFAULT_SAMPLES = 5;\nconst DEFAULT_NUM_PREDICT = 256;\nconst DEFAULT_SEED = 42;\nconst DEFAULT_GAIN_THRESHOLD = 1.05;\n\nfunction median(values: readonly number[]): number {\n const sorted = [...values].sort((a, b) => a - b);\n const mid = Math.floor(sorted.length / 2);\n return sorted.length % 2 === 1\n ? (sorted[mid] ?? 0)\n : ((sorted[mid - 1] ?? 0) + (sorted[mid] ?? 0)) / 2;\n}\n\nfunction roundTo(value: number, decimals: number): number {\n const factor = 10 ** decimals;\n return Math.round(value * factor) / factor;\n}\n\nfunction requirePositiveInteger(name: string, value: number): void {\n if (!Number.isInteger(value) || value < 1) {\n throw new RangeError(\n `compareDraftPerformance: ${name} must be an integer >= 1 (got ${value}).`,\n );\n }\n}\n\nasync function runSide(\n client: DraftBenchmarkClient,\n options: CompareDraftPerformanceOptions,\n draftNumPredict: number,\n samples: number,\n numPredict: number,\n seed: number,\n): Promise<DraftRunStats> {\n const samplingOptions = {\n num_predict: numPredict,\n temperature: 0,\n seed,\n draft_num_predict: draftNumPredict,\n };\n\n if (options.warmup ?? true) {\n // Throwaway run: pays the model load (`load_duration`) so the measured\n // samples reflect steady-state generation, not cold-start I/O.\n await client.generate({\n model: options.model,\n prompt: options.prompt,\n options: { ...samplingOptions, num_predict: 1 },\n stream: false,\n signal: options.signal,\n });\n }\n\n const tokensPerSecond: number[] = [];\n const generationMs: number[] = [];\n for (let i = 0; i < samples; i++) {\n options.signal?.throwIfAborted();\n const response = await client.generate({\n model: options.model,\n prompt: options.prompt,\n options: samplingOptions,\n stream: false,\n signal: options.signal,\n });\n const telemetry = formatTelemetry(response);\n if (Number.isFinite(telemetry.tokensPerSecond) && telemetry.tokensPerSecond > 0) {\n tokensPerSecond.push(telemetry.tokensPerSecond);\n generationMs.push(telemetry.generationMs);\n }\n }\n\n if (tokensPerSecond.length === 0) {\n throw new OllamaClientError(\n `compareDraftPerformance: every draft_num_predict=${draftNumPredict} sample returned a ` +\n `non-positive tokens/second. The model name is likely wrong, or the server returned ` +\n `empty generations.`,\n { code: 'draft_benchmark_no_valid_samples' },\n );\n }\n\n return {\n draftNumPredict,\n medianTokensPerSecond: median(tokensPerSecond),\n sampleTokensPerSecond: tokensPerSecond,\n medianEvalDurationMs: median(generationMs),\n };\n}\n\n/**\n * Measure whether speculative drafting pays off for a specific prompt:\n * identical prompt, deterministic sampling (`temperature: 0` + fixed `seed`),\n * warm-up discard, several samples per setting, median baseline\n * (`draft_num_predict: 0`) vs. median speculative (`draft_num_predict: N`)\n * compared as `speedupMultiplier`.\n *\n * Both sides run through the client's non-streaming `generate` — the raw\n * counters come back on the response and throughput is derived by\n * `formatTelemetry`. Non-positive/unusable samples are skipped; if a side\n * ends up with none, an `OllamaClientError` explains why (wrong model name /\n * empty generations) rather than reporting a fabricated zero.\n */\nexport async function compareDraftPerformance(\n client: DraftBenchmarkClient,\n options: CompareDraftPerformanceOptions,\n): Promise<DraftPerformanceComparison> {\n const draftNumPredict = options.draftNumPredict ?? DEFAULT_DRAFT_TOKENS;\n requirePositiveInteger('draftNumPredict', draftNumPredict);\n const samples = options.samples ?? DEFAULT_SAMPLES;\n requirePositiveInteger('samples', samples);\n const numPredict = options.numPredict ?? DEFAULT_NUM_PREDICT;\n requirePositiveInteger('numPredict', numPredict);\n const seed = options.seed ?? DEFAULT_SEED;\n if (!Number.isInteger(seed)) {\n throw new RangeError(`compareDraftPerformance: seed must be an integer (got ${seed}).`);\n }\n const gainThreshold = options.gainThreshold ?? DEFAULT_GAIN_THRESHOLD;\n if (!Number.isFinite(gainThreshold) || gainThreshold <= 0) {\n throw new RangeError(\n `compareDraftPerformance: gainThreshold must be a positive finite number (got ${gainThreshold}).`,\n );\n }\n\n options.signal?.throwIfAborted();\n\n // Baseline first, then speculative — a fixed order keeps runs reproducible\n // (identical prompts, deterministic sampling, shared warm-VRAM state).\n const baseline = await runSide(client, options, 0, samples, numPredict, seed);\n const speculative = await runSide(client, options, draftNumPredict, samples, numPredict, seed);\n\n // The reported numbers are self-consistent: the multiplier divides the two\n // rounded medians, and `effectiveGain` compares that reported multiplier\n // against the threshold.\n const baselineTokensPerSec = roundTo(baseline.medianTokensPerSecond, 1);\n const speculativeTokensPerSec = roundTo(speculative.medianTokensPerSecond, 1);\n const speedupMultiplier =\n baselineTokensPerSec > 0 ? roundTo(speculativeTokensPerSec / baselineTokensPerSec, 2) : 0;\n\n return {\n model: options.model,\n prompt: options.prompt,\n draftNumPredict,\n baselineTokensPerSec,\n speculativeTokensPerSec,\n speedupMultiplier,\n effectiveGain: speedupMultiplier > gainThreshold,\n gainThreshold,\n baseline,\n speculative,\n };\n}\n","/**\n * Model-affinity scheduling: keep the daemon's working set small.\n *\n * Ollama's concurrency model (per the official FAQ):\n *\n * - A model's KV cache scales by `OLLAMA_NUM_PARALLEL × context_length` —\n * parallel requests to the *same* loaded model are cheap (each gets its\n * own slot of the already-allocated cache).\n * - Requests for a *different* model queue until the first goes idle or is\n * evicted (`OLLAMA_MAX_LOADED_MODELS`, default 3× GPU count) — a swap is\n * an expensive unload/cold-load cycle: seconds of VRAM churn that a\n * concurrent multi-model workload pays again and again when it\n * interleaves models arbitrarily.\n * - Once `OLLAMA_MAX_QUEUE` (default 512) requests are waiting, new ones\n * are rejected outright with 503s.\n *\n * `ModelAffinityScheduler` is the client-side counterpart for workloads that\n * juggle several models — extraction on a coder model, reasoning on a\n * thinking model, embeddings for retrieval. It groups tasks into per-model\n * serial queues and caps how many *distinct* models have work in flight\n * (`concurrentModels`, default 1), preferring to deepen the currently-active\n * model over starting the next one — the anti-thrashing order. Candidate\n * lists let a task run on whichever of several interchangeable models is\n * already loaded (`GET /api/ps`, cached with a TTL).\n *\n * It is a user-space primitive, deliberately not wired into `OllamaClient`'s\n * request path: affinity decisions are workload policy, and the scheduler is\n * the foundation the multi-instance routing work builds on. See ADR 0026.\n */\n\nimport { OllamaClientError } from './errors.js';\nimport type { OllamaClient } from './client.js';\n\n/**\n * The minimal client surface the scheduler needs. `OllamaClient` satisfies it\n * structurally; tests and custom setups can pass any compatible object.\n */\nexport interface ModelAffinityClient {\n readonly models: {\n ps(): Promise<{ readonly models: ReadonlyArray<{ readonly name: string }> }>;\n };\n}\n\n/** Options for {@link ModelAffinityScheduler}. */\nexport interface ModelAffinitySchedulerOptions {\n /**\n * Maximum number of *distinct* models with work in flight at once\n * (default `1`). `1` is the anti-thrashing setting: one model stays hot\n * until its queue drains, then the next loads. Raise it only when the\n * host has VRAM for several concurrent models\n * (`OLLAMA_MAX_LOADED_MODELS`).\n */\n readonly concurrentModels?: number | undefined;\n /**\n * Parallel tasks allowed per active model (default `1`). Raising this\n * mirrors the server's own `OLLAMA_NUM_PARALLEL` — same-model parallelism\n * reuses the loaded weights without swap cost.\n */\n readonly perModelConcurrency?: number | undefined;\n /**\n * How long a `GET /api/ps` result is reused when choosing among candidate\n * models (default `30_000` ms). Only multi-candidate `run()` calls and\n * `loadedModels()` consult the server; single-model tasks never do.\n */\n readonly psCacheTtlMs?: number | undefined;\n}\n\n/** Live scheduling state, from {@link ModelAffinityScheduler.stats}. */\nexport interface ModelAffinityStats {\n /** Models with at least one task currently executing. */\n readonly activeModels: readonly string[];\n /** Tasks waiting in queues (not yet started). */\n readonly queuedTasks: number;\n}\n\ninterface TaskEntry {\n readonly task: (model: string) => Promise<unknown>;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n}\n\ninterface ModelQueue {\n readonly items: TaskEntry[];\n active: number;\n}\n\nconst DEFAULT_CONCURRENT_MODELS = 1;\nconst DEFAULT_PER_MODEL_CONCURRENCY = 1;\nconst DEFAULT_PS_CACHE_TTL_MS = 30_000;\n\n/**\n * Groups async work by model with load-aware dispatch.\n *\n * ```ts\n * const scheduler = new ModelAffinityScheduler(client);\n *\n * // Serial queue per model; one model hot at a time (default):\n * await scheduler.run('deepseek-r1', () => reason(client));\n * await scheduler.run('qwen2.5:coder', () => extract(client));\n *\n * // Either-or: picks whichever candidate is already loaded (/api/ps):\n * const summary = await scheduler.run(\n * ['qwen2.5:coder', 'qwen2.5:14b'],\n * (model) => extractWith(client, model),\n * );\n * ```\n *\n * Dispatch order is **affinity-sticky, not round-robin**: when a queued\n * model is already active, its tasks start before a different model's (up to\n * `perModelConcurrency`), because deepening the hot model avoids a swap.\n * Tasks run in FIFO order within each model's queue. Task functions are the\n * caller's own — the scheduler adds no retry, timeout, or failover, and a\n * rejected task simply rejects its `run()` promise while its siblings\n * proceed.\n */\nexport class ModelAffinityScheduler {\n private readonly queues = new Map<string, ModelQueue>();\n private readonly concurrentModels: number;\n private readonly perModelConcurrency: number;\n private readonly psCacheTtlMs: number;\n private psCache: { at: number; names: ReadonlySet<string> } | undefined;\n private readonly drainWaiters: Array<() => void> = [];\n\n constructor(\n private readonly client: ModelAffinityClient,\n options: ModelAffinitySchedulerOptions = {},\n ) {\n this.concurrentModels = options.concurrentModels ?? DEFAULT_CONCURRENT_MODELS;\n this.perModelConcurrency = options.perModelConcurrency ?? DEFAULT_PER_MODEL_CONCURRENCY;\n this.psCacheTtlMs = options.psCacheTtlMs ?? DEFAULT_PS_CACHE_TTL_MS;\n if (!Number.isInteger(this.concurrentModels) || this.concurrentModels < 1) {\n throw new OllamaClientError('concurrentModels must be an integer >= 1.', {\n code: 'invalid_request',\n });\n }\n if (!Number.isInteger(this.perModelConcurrency) || this.perModelConcurrency < 1) {\n throw new OllamaClientError('perModelConcurrency must be an integer >= 1.', {\n code: 'invalid_request',\n });\n }\n if (!Number.isFinite(this.psCacheTtlMs) || this.psCacheTtlMs < 0) {\n throw new OllamaClientError('psCacheTtlMs must be a non-negative number.', {\n code: 'invalid_request',\n });\n }\n }\n\n /**\n * Runs `task` on the scheduler, serialized per model. When `model` is a\n * list of candidates, the already-loaded one is preferred (fresh\n * `/api/ps` data subject to the TTL cache); with none loaded — or when the\n * lookup fails — the first candidate runs. The chosen model is handed to\n * the task.\n */\n async run<T>(model: string | readonly string[], task: (model: string) => Promise<T>): Promise<T> {\n const candidates = typeof model === 'string' ? [model] : [...model];\n if (\n candidates.length === 0 ||\n candidates.some((name) => typeof name !== 'string' || name === '')\n ) {\n throw new OllamaClientError('run() requires at least one non-empty model name.', {\n code: 'invalid_request',\n });\n }\n const chosen =\n candidates.length === 1 ? candidates[0]! : await this.chooseCandidate(candidates);\n return new Promise<T>((resolve, reject) => {\n const queue = this.queues.get(chosen) ?? { items: [], active: 0 };\n this.queues.set(chosen, queue);\n queue.items.push({\n task: task as (model: string) => Promise<unknown>,\n resolve: resolve as (value: unknown) => void,\n reject,\n });\n this.pump();\n });\n }\n\n /**\n * Names of the models currently loaded, per `GET /api/ps`, cached for\n * `psCacheTtlMs`. Degrades to an empty list when the server can't answer\n * (never throws; candidate selection treats it as \"nothing loaded\").\n */\n async loadedModels(): Promise<readonly string[]> {\n const names = await this.refreshPsNames();\n return [...names];\n }\n\n /** Current scheduling state — active models and queued task count. */\n get stats(): ModelAffinityStats {\n const activeModels: string[] = [];\n let queuedTasks = 0;\n for (const [name, queue] of this.queues) {\n if (queue.active > 0) activeModels.push(name);\n queuedTasks += queue.items.length;\n }\n return { activeModels, queuedTasks };\n }\n\n /**\n * Resolves once every queue is empty and no task is running. Does not\n * abort anything — tasks are caller-owned; abort them via their own\n * signals before disposing if needed.\n */\n async dispose(): Promise<void> {\n if (this.stats.queuedTasks === 0 && this.stats.activeModels.length === 0) return;\n await new Promise<void>((resolve) => {\n this.drainWaiters.push(resolve);\n });\n }\n\n private async chooseCandidate(candidates: readonly string[]): Promise<string> {\n const loaded = await this.refreshPsNames();\n for (const candidate of candidates) {\n if (loaded.has(candidate)) return candidate;\n }\n return candidates[0]!;\n }\n\n private async refreshPsNames(): Promise<ReadonlySet<string>> {\n const now = Date.now();\n if (this.psCache !== undefined && now - this.psCache.at <= this.psCacheTtlMs) {\n return this.psCache.names;\n }\n let names: ReadonlySet<string>;\n try {\n const ps = await this.client.models.ps();\n names = new Set(ps.models.map((entry) => entry.name));\n } catch {\n // Unreachable server, compat-only endpoint, auth hiccup — affinity\n // routing is best-effort. Degrade to \"nothing loaded\" without caching\n // the failure, so the next call retries.\n return new Set();\n }\n this.psCache = { at: now, names };\n return names;\n }\n\n private pump(): void {\n // Map iteration order = queue creation order, so dispatch is stable and\n // FIFO across models. An already-active model is allowed to deepen (up\n // to perModelConcurrency) even at the concurrentModels cap — that IS the\n // affinity: keep the hot model hot. The distinct-active count is\n // recomputed per check because tasks started earlier in this same pass\n // (or by concurrent completions) must count.\n for (const [name, queue] of this.queues) {\n while (queue.items.length > 0 && queue.active < this.perModelConcurrency) {\n if (queue.active === 0 && this.activeModelCount() >= this.concurrentModels) {\n break; // starting this model would exceed the distinct-models cap\n }\n const entry = queue.items.shift()!;\n queue.active += 1;\n this.execute(name, queue, entry);\n }\n }\n }\n\n private activeModelCount(): number {\n let count = 0;\n for (const queue of this.queues.values()) {\n if (queue.active > 0) count += 1;\n }\n return count;\n }\n\n private execute(name: string, queue: ModelQueue, entry: TaskEntry): void {\n void (async () => {\n try {\n entry.resolve(await entry.task(name));\n } catch (err) {\n entry.reject(err);\n } finally {\n queue.active -= 1;\n if (queue.items.length === 0 && queue.active === 0) {\n this.queues.delete(name);\n }\n if (this.stats.queuedTasks === 0 && this.stats.activeModels.length === 0) {\n const waiters = [...this.drainWaiters];\n this.drainWaiters.length = 0;\n for (const resolve of waiters) resolve();\n }\n this.pump();\n }\n })();\n }\n}\n\n/** Convenience factory — `createModelAffinityScheduler(client, opts)` reads better in setups. */\nexport function createModelAffinityScheduler(\n client: ModelAffinityClient | OllamaClient,\n options?: ModelAffinitySchedulerOptions,\n): ModelAffinityScheduler {\n return new ModelAffinityScheduler(client as ModelAffinityClient, options);\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"]}
|