@nemesis-oss/ollama-sdk 1.11.0 → 1.12.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/dist/index.d.cts CHANGED
@@ -1,12 +1,12 @@
1
- import { T as ThinkingMetadata, M as ModelResponse, R as RequestCancellationOptions, S as ShowRequestOptions, a as ShowResponse, P as PullRequestOptions, b as ProgressResponse, c as PushRequestOptions, C as CreateRequestOptions, D as DeleteRequestOptions, d as StatusResponse, e as CopyRequestOptions, f as PsResponse, V as VersionResponse, g as ToolParameters, h as ThinkValue, i as ToolCall, j as ChatRequestOptions, k as ModelOptions, l as ToolDefinition, F as FormatOption, m as ChatResponse, n as Message, G as GenerateRequestOptions, o as GenerateResponse, E as EmbedRequestOptions, p as EmbedResponse, q as EmbeddingsRequestOptions, r as EmbeddingsResponse, W as WebSearchRequestOptions, s as WebSearchResponse, t as WebFetchRequestOptions, u as WebFetchResponse, U as UsageRequestOptions, B as BalanceRequestOptions, v as VisionInput } from './types-BtQexFpT.cjs';
2
- export { L as ListResponse, w as Logprob, x as LogprobToken, y as ModelDetails, z as Role, A as ToolCallFunction, H as ToolFunctionDefinition, I as ToolProperty, J as UsageRange, K as UsageScope, N as WebSearchResult, O as imageStringNeedsResolution, Q as resolveImageInput } from './types-BtQexFpT.cjs';
3
- import { H as HttpClient, F as FetchLike, M as Middleware, L as Logger, R as RequestLifecycleHook, c as OllamaStreamEvent, A as AbortableAsyncIterable, d as OllamaStreamEventType, P as ProgressStreamResult, B as BinaryBody, O as OllamaRuntime, C as ChatStreamResult, G as GenerateStreamResult, e as RawUsageSource, T as TokenUsage } from './runtime-DTtWCxDs.cjs';
4
- export { D as DoneEvent, E as ErrorEvent, f as HttpBody, g as HttpClientOptions, h as HttpRequestOptions, i as LifecycleErrorEvent, j as LifecycleRetryEvent, k as LifecycleStartEvent, l as LifecycleSuccessEvent, m as LogFn, n as MessageEvent, o as MiddlewareContext, N as NANOS_PER_MS, p as NANOS_PER_SECOND, q as NOOP_LOGGER, r as NextFunction, s as OllamaAbortError, t as OllamaAgentMaxIterationsError, u as OllamaAgentMaxToolCallsError, v as OllamaAgentToolLoopError, w as OllamaAuthError, x as OllamaBadGatewayError, y as OllamaClientError, z as OllamaClientErrorOptions, J as OllamaErrorRequestContext, K as OllamaErrorResponseContext, Q as OllamaGenericClientError, U as OllamaIncompatibleModelError, V as OllamaMcpError, W as OllamaModelRoutingError, X as OllamaNetworkError, Y as OllamaNotFoundError, Z as OllamaOverloadedError, _ as OllamaQuotaExceededError, $ as OllamaRateLimitError, a0 as OllamaRequestTooLargeError, a1 as OllamaRequestValidationError, a2 as OllamaResponseValidationError, a3 as OllamaServerError, a4 as OllamaServerVersionUnknownError, a5 as OllamaSkillInvalidError, a6 as OllamaSkillNotFoundError, a7 as OllamaStreamError, a8 as OllamaTimeoutError, a9 as OllamaToolTimeoutError, aa as OllamaToolValidationError, ab as OllamaUnsupportedCapabilityError, ac as RequestContext, ad as RequestLifecycleEvent, ae as ResponseContext, af as SseEvent, ag as ThinkingEvent, ah as TokenEvent, ai as ToolCallEvent, aj as composeMiddleware, ak as createConsoleLogger, al as extractUsage, am as mapError, an as parseSseStream } from './runtime-DTtWCxDs.cjs';
1
+ import { T as ThinkingMetadata, M as ModelResponse, R as RequestCancellationOptions, S as ShowRequestOptions, a as ShowResponse, P as PullRequestOptions, b as ProgressResponse, c as PushRequestOptions, C as CreateRequestOptions, D as DeleteRequestOptions, d as StatusResponse, e as CopyRequestOptions, f as PsResponse, V as VersionResponse, g as ToolParameters, h as ThinkValue, i as ToolCall, j as ChatRequestOptions, k as ModelOptions, l as ToolDefinition, F as FormatOption, m as ChatResponse, n as Message, G as GenerateRequestOptions, o as GenerateResponse, E as EmbedRequestOptions, p as EmbedResponse, q as EmbeddingsRequestOptions, r as EmbeddingsResponse, W as WebSearchRequestOptions, s as WebSearchResponse, t as WebFetchRequestOptions, u as WebFetchResponse, U as UsageRequestOptions, B as BalanceRequestOptions, v as PingResult, w as VisionInput } from './types-B57ZZfp3.cjs';
2
+ export { L as ListResponse, x as Logprob, y as LogprobToken, z as ModelDetails, A as Role, H as ToolCallFunction, I as ToolFunctionDefinition, J as ToolProperty, K as UsageRange, N as UsageScope, O as WebSearchResult, Q as imageStringNeedsResolution, X as resolveImageInput } from './types-B57ZZfp3.cjs';
3
+ import { H as HttpClient, F as FetchLike, M as Middleware, L as Logger, R as RequestLifecycleHook, c as OllamaStreamEvent, A as AbortableAsyncIterable, d as OllamaStreamEventType, P as ProgressStreamResult, B as BinaryBody, O as OllamaRuntime, C as ChatStreamResult, G as GenerateStreamResult, e as RawUsageSource, T as TokenUsage } from './runtime-DmI1cOEq.cjs';
4
+ export { D as DoneEvent, E as ErrorEvent, f as HttpBody, g as HttpClientOptions, h as HttpRequestOptions, i as LifecycleErrorEvent, j as LifecycleRetryEvent, k as LifecycleStartEvent, l as LifecycleSuccessEvent, m as LogFn, n as MessageEvent, o as MiddlewareContext, N as NANOS_PER_MS, p as NANOS_PER_SECOND, q as NOOP_LOGGER, r as NextFunction, s as OllamaAbortError, t as OllamaAgentMaxIterationsError, u as OllamaAgentMaxToolCallsError, v as OllamaAgentToolLoopError, w as OllamaAuthError, x as OllamaBadGatewayError, y as OllamaClientError, z as OllamaClientErrorOptions, J as OllamaErrorRequestContext, K as OllamaErrorResponseContext, Q as OllamaGenericClientError, U as OllamaIncompatibleModelError, V as OllamaMcpError, W as OllamaModelRoutingError, X as OllamaNetworkError, Y as OllamaNotFoundError, Z as OllamaOverloadedError, _ as OllamaQuotaExceededError, $ as OllamaRateLimitError, a0 as OllamaRequestTooLargeError, a1 as OllamaRequestValidationError, a2 as OllamaResponseValidationError, a3 as OllamaServerError, a4 as OllamaServerVersionUnknownError, a5 as OllamaSkillInvalidError, a6 as OllamaSkillNotFoundError, a7 as OllamaStreamError, a8 as OllamaTimeoutError, a9 as OllamaToolTimeoutError, aa as OllamaToolValidationError, ab as OllamaUnsupportedCapabilityError, ac as RequestContext, ad as RequestLifecycleEvent, ae as ResponseContext, af as SseEvent, ag as ThinkingEvent, ah as TokenEvent, ai as ToolCallEvent, aj as composeMiddleware, ak as createConsoleLogger, al as extractUsage, am as mapError, an as parseSseStream } from './runtime-DmI1cOEq.cjs';
5
5
  import { z } from 'zod';
6
- import { R as RequestRunner, S as SystemOneChoiceAnswer, o as SystemOneNoulAnswer, p as SystemOneScoreAnswer, q as SystemOneChoiceQuestion, r as SystemOneNoulQuestion, s as SystemOneScoreQuestion, t as SystemOneRequest$1, u as SystemOneResponse$1, v as SystemOneContent, N as NativeApi, w as OpenAICompatClient, x as AnthropicCompatClient } from './anthropic-DinrABof.cjs';
7
- export { y as AnthropicCacheControl, z as AnthropicContentBlock, B as AnthropicImageContentBlock, C as AnthropicMessage, n as AnthropicMessageStreamEvent, A as AnthropicMessagesRequest, m as AnthropicMessagesResponse, D as AnthropicMessagesStream, E as AnthropicMetadata, F as AnthropicOutputConfig, G as AnthropicRedactedThinkingContentBlock, H as AnthropicSystem, I as AnthropicSystemTextBlock, J as AnthropicTextContentBlock, K as AnthropicThinkingConfig, L as AnthropicThinkingContentBlock, M as AnthropicTool, P as AnthropicToolChoice, Q as AnthropicToolResultContentBlock, T as AnthropicToolUseContentBlock, U as AnthropicUnknownStreamEvent, V as OllamaAnthropicContentBlock, W as OllamaAnthropicMessage, X as OllamaAnthropicMessagesRequest, Y as OllamaAnthropicSystem, Z as OllamaAnthropicSystemTextBlock, _ as OllamaAnthropicTextContentBlock, $ as OllamaAnthropicThinkingConfig, a0 as OllamaAnthropicTool, a1 as OllamaAnthropicToolResultContentBlock, a2 as OllamaOpenAIChatCompletionRequest, a3 as OllamaOpenAICompletionRequest, a4 as OllamaOpenAIEmbeddingRequest, a5 as OllamaOpenAIReasoningEffort, a6 as OllamaOpenAIResponsesRequest, a7 as OpenAIChatCompletionChoice, b as OpenAIChatCompletionChunk, a8 as OpenAIChatCompletionChunkChoice, a9 as OpenAIChatCompletionDelta, O as OpenAIChatCompletionRequest, a as OpenAIChatCompletionResponse, aa as OpenAIChatCompletionStream, ab as OpenAICompletionChoice, e as OpenAICompletionChunk, c as OpenAICompletionRequest, d as OpenAICompletionResponse, ac as OpenAICompletionStream, ad as OpenAIContentPart, ae as OpenAIEmbeddingInput, af as OpenAIEmbeddingItem, f as OpenAIEmbeddingRequest, g as OpenAIEmbeddingResponse, ag as OpenAIFunctionDefinition, ah as OpenAIImageUrlContentPart, h as OpenAIListModelsResponse, ai as OpenAIMessage, i as OpenAIModelItem, aj as OpenAIReasoningEffort, ak as OpenAIResponseFormat, al as OpenAIResponsesCompletedEvent, am as OpenAIResponsesContentPartAddedEvent, an as OpenAIResponsesContentPartDoneEvent, ao as OpenAIResponsesCreatedEvent, ap as OpenAIResponsesError, aq as OpenAIResponsesEventBase, ar as OpenAIResponsesFailedEvent, as as OpenAIResponsesFunctionCallArgumentsDeltaEvent, at as OpenAIResponsesFunctionCallArgumentsDoneEvent, au as OpenAIResponsesInProgressEvent, av as OpenAIResponsesIncompleteDetails, aw as OpenAIResponsesIncompleteEvent, ax as OpenAIResponsesOutputContent, ay as OpenAIResponsesOutputFunctionCall, az as OpenAIResponsesOutputItem, aA as OpenAIResponsesOutputItemAddedEvent, aB as OpenAIResponsesOutputItemDoneEvent, aC as OpenAIResponsesOutputMessage, aD as OpenAIResponsesOutputReasoning, aE as OpenAIResponsesOutputRefusal, aF as OpenAIResponsesOutputTextContent, aG as OpenAIResponsesOutputTextDeltaEvent, aH as OpenAIResponsesOutputTextDoneEvent, aI as OpenAIResponsesQueuedEvent, aJ as OpenAIResponsesReasoningSummaryPartAddedEvent, aK as OpenAIResponsesReasoningSummaryPartDoneEvent, aL as OpenAIResponsesReasoningSummaryTextDeltaEvent, aM as OpenAIResponsesReasoningSummaryTextDoneEvent, aN as OpenAIResponsesReasoningTextDeltaEvent, aO as OpenAIResponsesReasoningTextDoneEvent, aP as OpenAIResponsesRefusalDeltaEvent, aQ as OpenAIResponsesRefusalDoneEvent, j as OpenAIResponsesRequest, k as OpenAIResponsesResponse, aR as OpenAIResponsesStatus, aS as OpenAIResponsesStream, aT as OpenAIResponsesStreamError, l as OpenAIResponsesStreamEvent, aU as OpenAIResponsesUsage, aV as OpenAIStreamOptions, aW as OpenAITextContentPart, aX as OpenAITool, aY as OpenAIToolCall, aZ as OpenAIToolCallDelta, a_ as OpenAIUsage, a$ as SystemOneConfidence, b0 as SystemOneProbabilities } from './anthropic-DinrABof.cjs';
8
- import { T as ToolHandler, a as Tool, A as AnyTool, b as ToolRegistry, c as ToolExecutionResult } from './compose-lt-Qz3lI.cjs';
9
- export { d as AppliedSkillResult, e as ApplySkillOptions, P as ParsedFrontmatter, S as Skill, f as SkillFrontmatter, g as SkillSummary, h as ToolExecutionContext, i as ToolExecutionFailure, j as ToolExecutionSuccess, k as ToolRegistryOptions, l as applySkill, p as parseFrontmatter } from './compose-lt-Qz3lI.cjs';
6
+ import { R as RequestRunner, S as SystemOneChoiceAnswer, o as SystemOneNoulAnswer, p as SystemOneScoreAnswer, q as SystemOneChoiceQuestion, r as SystemOneNoulQuestion, s as SystemOneScoreQuestion, t as SystemOneRequest$1, u as SystemOneResponse$1, v as SystemOneContent, N as NativeApi, w as OpenAICompatClient, x as AnthropicCompatClient } from './anthropic-Did0lQxP.cjs';
7
+ export { y as AnthropicCacheControl, z as AnthropicContentBlock, B as AnthropicImageContentBlock, C as AnthropicMessage, n as AnthropicMessageStreamEvent, A as AnthropicMessagesRequest, m as AnthropicMessagesResponse, D as AnthropicMessagesStream, E as AnthropicMetadata, F as AnthropicOutputConfig, G as AnthropicRedactedThinkingContentBlock, H as AnthropicSystem, I as AnthropicSystemTextBlock, J as AnthropicTextContentBlock, K as AnthropicThinkingConfig, L as AnthropicThinkingContentBlock, M as AnthropicTool, P as AnthropicToolChoice, Q as AnthropicToolResultContentBlock, T as AnthropicToolUseContentBlock, U as AnthropicUnknownStreamEvent, V as OllamaAnthropicContentBlock, W as OllamaAnthropicMessage, X as OllamaAnthropicMessagesRequest, Y as OllamaAnthropicSystem, Z as OllamaAnthropicSystemTextBlock, _ as OllamaAnthropicTextContentBlock, $ as OllamaAnthropicThinkingConfig, a0 as OllamaAnthropicTool, a1 as OllamaAnthropicToolResultContentBlock, a2 as OllamaOpenAIChatCompletionRequest, a3 as OllamaOpenAICompletionRequest, a4 as OllamaOpenAIEmbeddingRequest, a5 as OllamaOpenAIReasoningEffort, a6 as OllamaOpenAIResponsesRequest, a7 as OpenAIChatCompletionChoice, b as OpenAIChatCompletionChunk, a8 as OpenAIChatCompletionChunkChoice, a9 as OpenAIChatCompletionDelta, O as OpenAIChatCompletionRequest, a as OpenAIChatCompletionResponse, aa as OpenAIChatCompletionStream, ab as OpenAICompletionChoice, e as OpenAICompletionChunk, c as OpenAICompletionRequest, d as OpenAICompletionResponse, ac as OpenAICompletionStream, ad as OpenAIContentPart, ae as OpenAIEmbeddingInput, af as OpenAIEmbeddingItem, f as OpenAIEmbeddingRequest, g as OpenAIEmbeddingResponse, ag as OpenAIFunctionDefinition, ah as OpenAIImageUrlContentPart, h as OpenAIListModelsResponse, ai as OpenAIMessage, i as OpenAIModelItem, aj as OpenAIReasoningEffort, ak as OpenAIResponseFormat, al as OpenAIResponsesCompletedEvent, am as OpenAIResponsesContentPartAddedEvent, an as OpenAIResponsesContentPartDoneEvent, ao as OpenAIResponsesCreatedEvent, ap as OpenAIResponsesError, aq as OpenAIResponsesEventBase, ar as OpenAIResponsesFailedEvent, as as OpenAIResponsesFunctionCallArgumentsDeltaEvent, at as OpenAIResponsesFunctionCallArgumentsDoneEvent, au as OpenAIResponsesInProgressEvent, av as OpenAIResponsesIncompleteDetails, aw as OpenAIResponsesIncompleteEvent, ax as OpenAIResponsesOutputContent, ay as OpenAIResponsesOutputFunctionCall, az as OpenAIResponsesOutputItem, aA as OpenAIResponsesOutputItemAddedEvent, aB as OpenAIResponsesOutputItemDoneEvent, aC as OpenAIResponsesOutputMessage, aD as OpenAIResponsesOutputReasoning, aE as OpenAIResponsesOutputRefusal, aF as OpenAIResponsesOutputTextContent, aG as OpenAIResponsesOutputTextDeltaEvent, aH as OpenAIResponsesOutputTextDoneEvent, aI as OpenAIResponsesQueuedEvent, aJ as OpenAIResponsesReasoningSummaryPartAddedEvent, aK as OpenAIResponsesReasoningSummaryPartDoneEvent, aL as OpenAIResponsesReasoningSummaryTextDeltaEvent, aM as OpenAIResponsesReasoningSummaryTextDoneEvent, aN as OpenAIResponsesReasoningTextDeltaEvent, aO as OpenAIResponsesReasoningTextDoneEvent, aP as OpenAIResponsesRefusalDeltaEvent, aQ as OpenAIResponsesRefusalDoneEvent, j as OpenAIResponsesRequest, k as OpenAIResponsesResponse, aR as OpenAIResponsesStatus, aS as OpenAIResponsesStream, aT as OpenAIResponsesStreamError, l as OpenAIResponsesStreamEvent, aU as OpenAIResponsesUsage, aV as OpenAIStreamOptions, aW as OpenAITextContentPart, aX as OpenAITool, aY as OpenAIToolCall, aZ as OpenAIToolCallDelta, a_ as OpenAIUsage, a$ as SystemOneConfidence, b0 as SystemOneProbabilities } from './anthropic-Did0lQxP.cjs';
8
+ import { T as ToolHandler, a as Tool, A as AnyTool, b as ToolRegistry, c as ToolExecutionResult } from './compose-DhvoUrWa.cjs';
9
+ export { d as AppliedSkillResult, e as ApplySkillOptions, P as ParsedFrontmatter, S as Skill, f as SkillFrontmatter, g as SkillSummary, h as ToolExecutionContext, i as ToolExecutionFailure, j as ToolExecutionSuccess, k as ToolRegistryOptions, l as applySkill, p as parseFrontmatter } from './compose-DhvoUrWa.cjs';
10
10
  import { M as McpClientLike, a as McpToolDescriptor, b as McpTask, c as McpCallToolResult } from './types-CI-gM2u5.cjs';
11
11
  export { d as McpContentBlock, e as McpCreateTaskResult, f as McpElicitationFormRequest, g as McpElicitationHandlers, h as McpElicitationRequest, i as McpElicitationResult, j as McpElicitationUrlRequest, k as McpIcon, l as McpInputRequiredResult, m as McpListToolsParams, n as McpListToolsResult, o as McpRequestOptions, p as McpServerCapabilities, q as McpTaskMethod, r as McpTaskRequest, s as McpTaskStatus, t as McpToolAnnotations, u as McpToolCallResult, v as McpToolExecution } from './types-CI-gM2u5.cjs';
12
12
  import * as Otel from '@opentelemetry/api';
@@ -290,6 +290,15 @@ interface DiscoveredContextLength {
290
290
  * integer `num_ctx` line is present.
291
291
  */
292
292
  declare function extractParameterNumCtx(parameters?: string | undefined): number | undefined;
293
+ /**
294
+ * Whether `model` is currently resident (loaded in VRAM) per a `GET /api/ps`
295
+ * response — exact or tag-less-prefix match, same resolution rules as Ollama
296
+ * itself applies to model names. See {@link matchesModelReference}.
297
+ */
298
+ declare function isModelResident(psModels: readonly {
299
+ readonly name?: string | undefined;
300
+ readonly model?: string | undefined;
301
+ }[], model: string): boolean;
293
302
  /**
294
303
  * Finds the context window Ollama actually allocated for `model`, from a
295
304
  * `GET /api/ps` response. Matching mirrors Ollama's own model resolution:
@@ -357,9 +366,133 @@ declare const DEFAULT_RETRY_CONFIG: RetryConfig;
357
366
  */
358
367
  declare function withRetry<T>(operation: (attempt: number) => Promise<T>, config?: RetryConfig, signal?: AbortSignal): Promise<T>;
359
368
 
369
+ /**
370
+ * Multi-host model-affinity routing — prefer the endpoint already holding the
371
+ * requested model in VRAM.
372
+ *
373
+ * Ollama daemons keep a bounded set of models resident (`OLLAMA_MAX_LOADED_MODELS`).
374
+ * With several interchangeable endpoints serving the same models, sending a request
375
+ * to a host that doesn't currently hold the model forces an unload/cold-load swap
376
+ * on that host — the thrashing `ModelAffinityScheduler` avoids for a *single*
377
+ * client's task queues. This router brings the same affinity to the *multi-host*
378
+ * request path: given the candidate endpoints `executeWithFailover` would try
379
+ * anyway, it reorders them so hosts whose `GET /api/ps` shows the requested model
380
+ * resident come first.
381
+ *
382
+ * Design constraints (see ADR 0028):
383
+ *
384
+ * - **Zero added request latency.** Reordering is synchronous and consults only
385
+ * cached `/api/ps` snapshots. A request never waits for a probe: when a
386
+ * snapshot is missing or stale, the request proceeds with the unchanged
387
+ * candidate order and the refresh happens in the background, warming the cache
388
+ * for subsequent requests.
389
+ * - **Race-free with `least-connections`.** The reorder runs entirely between the
390
+ * registry's synchronous `candidates()`/`filterWithCapacity()` and the
391
+ * endpoint's `acquire()` — no `await` in between — so the strategy's
392
+ * no-two-calls-pick-the-same-idle-endpoint guarantee is untouched. Affinity
393
+ * only reorders *within* the runnable set; priority tiers and per-strategy
394
+ * ordering stay intact inside the resident/non-resident groups.
395
+ * - **Best-effort, never blocking, never failing a request.** A probe failure is
396
+ * recorded with a short backoff (`failureRetryMs`) and never cached as data;
397
+ * the affected endpoint is simply treated as unknown until a probe succeeds.
398
+ * - **Fresh-data-only decisions.** Only snapshots within `ttlMs` reorder
399
+ * requests — `/api/ps` can change at any moment (evictions, other clients),
400
+ * so stale data is treated as no data. Last-known snapshots are still exposed
401
+ * via `status()` for observability.
402
+ */
403
+
404
+ /**
405
+ * One `/api/ps` running-model entry, as the router consumes it — name/model only.
406
+ * Optional to match the generated `Ps` wire shape; hand-written `ModelResponse`
407
+ * values (required fields) are assignable as-is.
408
+ */
409
+ interface AffinityRunningModel {
410
+ readonly name?: string | undefined;
411
+ readonly model?: string | undefined;
412
+ }
413
+ /**
414
+ * Options for dynamic model-affinity routing across endpoints. Configured under
415
+ * `OllamaClientConfig.endpointHealth.modelAffinity`; implemented by
416
+ * `OllamaClient`'s request path (`executeWithFailover`), which has HTTP access —
417
+ * the `EndpointRegistry` itself ignores this key.
418
+ */
419
+ interface ModelAffinityRoutingOptions {
420
+ /**
421
+ * How long a `GET /api/ps` snapshot stays fresh enough to reorder requests
422
+ * (default 30_000ms). Mirrors `ModelAffinityScheduler`'s `psCacheTtlMs`.
423
+ */
424
+ readonly ttlMs?: number | undefined;
425
+ /**
426
+ * How long a failed `/api/ps` probe suppresses retries against that endpoint
427
+ * (default 5_000ms) — a dead host isn't probed on every request while it's
428
+ * down, and comes back automatically once it recovers. Failures are never
429
+ * cached as data.
430
+ */
431
+ readonly failureRetryMs?: number | undefined;
432
+ }
433
+ /** Introspection snapshot for one endpoint's affinity cache. */
434
+ interface ModelAffinitySnapshot {
435
+ readonly endpointName: string;
436
+ readonly baseUrl: string;
437
+ /** Model names reported resident by the last successful probe (may be stale). */
438
+ readonly loadedModels: readonly string[];
439
+ /** When the last successful probe completed — `undefined` if it never succeeded. */
440
+ readonly fetchedAt: number | undefined;
441
+ /** Whether the snapshot is within `ttlMs` and therefore still drives reordering. */
442
+ readonly fresh: boolean;
443
+ }
444
+ /** Test seam: injectable clock — defaults to `Date.now`. */
445
+ type NowFn = () => number;
446
+ /**
447
+ * Cache-and-reorder engine for multi-host model affinity. See the module docs for
448
+ * the design constraints; `OllamaClient` constructs one (only when
449
+ * `endpointHealth.modelAffinity` is set) and calls {@link reorder} synchronously
450
+ * inside its request path.
451
+ */
452
+ declare class ModelAffinityRouter {
453
+ private readonly fetchPs;
454
+ private readonly ttlMs;
455
+ private readonly failureRetryMs;
456
+ private readonly now;
457
+ private readonly cache;
458
+ private readonly failedAt;
459
+ private readonly inflight;
460
+ constructor(fetchPs: (endpoint: OllamaEndpoint) => Promise<readonly AffinityRunningModel[]>, options?: ModelAffinityRoutingOptions & {
461
+ readonly now?: NowFn;
462
+ });
463
+ /**
464
+ * Synchronously reorders `candidates` so endpoints whose fresh `/api/ps`
465
+ * snapshot shows `model` resident come first (relative order preserved within
466
+ * each group). Returns the input unchanged — and kicks a background refresh —
467
+ * when any candidate's snapshot is missing or stale: a wrong reorder is worse
468
+ * than no reorder, and the first request after a cache miss simply isn't
469
+ * reordered. No-op without a `model` or with fewer than two candidates.
470
+ */
471
+ reorder(candidates: readonly OllamaEndpoint[], model: string | undefined): readonly OllamaEndpoint[];
472
+ /**
473
+ * Forces a refresh of the affinity cache for the given endpoints (deduped with
474
+ * any in-flight refresh; bypasses the failure backoff, because this is an
475
+ * explicit caller request — `client.warmModelAffinity()`). Resolves once every
476
+ * probe has settled — successfully or not; individual failures never reject.
477
+ */
478
+ warm(endpoints: readonly OllamaEndpoint[]): Promise<void>;
479
+ /** Introspection snapshots for the given endpoints (defaults to cached ones). */
480
+ status(endpoints?: readonly OllamaEndpoint[]): readonly ModelAffinitySnapshot[];
481
+ /**
482
+ * Starts (or joins) a background refresh for `endpoint`, unless one is already
483
+ * in flight or the failure backoff suppresses it. Fire-and-forget: the promise
484
+ * is stored only for dedupe/warm-joins; callers never await it on the request
485
+ * path.
486
+ */
487
+ private kickRefresh;
488
+ /** Refreshes one endpoint's snapshot; never rejects (failures record a backoff). */
489
+ private refresh;
490
+ }
491
+
360
492
  /**
361
493
  * Multi-endpoint registry with priority routing and circuit breaker failover.
362
494
  */
495
+
363
496
  interface OllamaEndpoint {
364
497
  readonly name: string;
365
498
  readonly baseUrl: string;
@@ -427,6 +560,18 @@ interface EndpointRegistryOptions {
427
560
  * any other in-flight request — it never blocks indefinitely on its own.
428
561
  */
429
562
  readonly maxConcurrentPerEndpoint?: number | undefined;
563
+ /**
564
+ * Dynamic model-affinity routing across endpoints: reorder each request's
565
+ * candidates so endpoints whose `GET /api/ps` shows the requested model already
566
+ * resident in VRAM are tried first — avoiding unload/cold-load swaps on
567
+ * `OLLAMA_MAX_LOADED_MODELS`-bounded daemons. Off unless set.
568
+ *
569
+ * Implemented by `OllamaClient`'s request path (`executeWithFailover` + a
570
+ * TTL-cached `ModelAffinityRouter`), not by this registry — the registry is a
571
+ * pure, HTTP-free data structure and simply ignores this key. See
572
+ * `src/providers/model-affinity-router.ts` and ADR 0028.
573
+ */
574
+ readonly modelAffinity?: ModelAffinityRoutingOptions | undefined;
430
575
  }
431
576
  declare class EndpointRegistry {
432
577
  private readonly endpoints;
@@ -1867,6 +2012,16 @@ declare class OllamaClient {
1867
2012
  * (streams, via `executeWithFailover`'s `holdUntil` release path).
1868
2013
  */
1869
2014
  private readonly activeRequests;
2015
+ /**
2016
+ * Dynamic multi-host model-affinity routing, active only when
2017
+ * `config.endpointHealth.modelAffinity` is set — see
2018
+ * `src/providers/model-affinity-router.ts` and ADR 0028. `undefined` means
2019
+ * the request path skips reordering entirely (zero overhead, and no `/api/ps`
2020
+ * probes are ever issued).
2021
+ */
2022
+ private readonly modelAffinity;
2023
+ /** Default timeout for one-off probe requests (`ping`, affinity `/api/ps` refreshes). */
2024
+ private static readonly PROBE_TIMEOUT_MS;
1870
2025
  constructor(config?: OllamaClientConfig);
1871
2026
  get modelsClient(): ModelsClient;
1872
2027
  /**
@@ -2200,7 +2355,49 @@ declare class OllamaClient {
2200
2355
  capabilities(model: string, signal?: AbortSignal): Promise<ModelCapabilities>;
2201
2356
  runtimeMode(): RuntimeMode;
2202
2357
  healthCheck(): Promise<EndpointHealthCheckResult[]>;
2358
+ /**
2359
+ * Ultra-lightweight liveness probe against the client's current best
2360
+ * endpoint: `HEAD /` — the root ping Ollama's documentation defines for
2361
+ * load-balancer health checks (HTTP 200; the daemon answers `GET /` with the
2362
+ * plain-text body "Ollama is running", which a HEAD request doesn't transfer).
2363
+ *
2364
+ * Deliberately a *single-endpoint, single-shot* probe — no failover to other
2365
+ * candidates, no retry — so the answer reflects one concrete host, not "some
2366
+ * endpoint eventually answered". To audit every configured endpoint, use
2367
+ * {@link healthCheck} (which probes all of them, and also reports the server
2368
+ * version at the cost of the heavier `GET /api/version` round trip).
2369
+ *
2370
+ * Resolves — never throws — with `{ healthy: false, error }` for connection
2371
+ * failures and timeouts; only caller-initiated cancellation (`signal`/
2372
+ * `destroy()`) rejects, mirroring how any other aborted request behaves.
2373
+ */
2374
+ ping(options?: RequestCancellationOptions): Promise<PingResult>;
2375
+ /**
2376
+ * Affinity-cache snapshots for every configured endpoint — which models each
2377
+ * host held in VRAM at the last successful `/api/ps` probe, when that was, and
2378
+ * whether it's still fresh. Empty when `endpointHealth.modelAffinity` isn't
2379
+ * configured (no probes are ever issued, so there is nothing to report).
2380
+ */
2381
+ modelAffinityStatus(): readonly ModelAffinitySnapshot[];
2382
+ /**
2383
+ * Explicitly refreshes the model-affinity cache for every configured endpoint
2384
+ * (deduped with any in-flight background refresh). No-op — resolves
2385
+ * immediately — when `endpointHealth.modelAffinity` isn't configured. Use it
2386
+ * to warm the cache at startup so the very first request already routes by
2387
+ * residency instead of waiting for the self-warming first-round refresh.
2388
+ */
2389
+ warmModelAffinity(): Promise<void>;
2203
2390
  endpointStatus(): EndpointHealth[];
2391
+ /**
2392
+ * Fetches one endpoint's `GET /api/ps` running-model list for the affinity
2393
+ * router. Bypasses `executeWithFailover` deliberately: probes must not
2394
+ * reenter the routing machinery they inform, must not touch the registry's
2395
+ * circuit-breaker/failure bookkeeping (a dead host's probe failing must not
2396
+ * cool it down harder than its real traffic already does), and must not fail
2397
+ * over to a different host (the answer is per-host by definition). Failures
2398
+ * propagate to the router, which records a short backoff and retries later.
2399
+ */
2400
+ private fetchEndpointRunningModels;
2204
2401
  /**
2205
2402
  * Immediately aborts every in-flight request and active stream managed by
2206
2403
  * this client — the clean teardown path for short-lived processes, CLI
@@ -3066,6 +3263,93 @@ declare const ATTR_OLLAMA_AGENT_MAX_ITERATIONS = "ollama.agent.max_iterations";
3066
3263
  declare const ATTR_OLLAMA_AGENT_ITERATION = "ollama.agent.iteration";
3067
3264
  declare const GEN_AI_SYSTEM_OLLAMA = "ollama";
3068
3265
 
3266
+ /**
3267
+ * Standardized telemetry normalizer — raw nanosecond counters to derived metrics.
3268
+ *
3269
+ * Ollama reports every duration as an **integer in nanoseconds** on its generation
3270
+ * responses (`total_duration`, `load_duration`, `prompt_eval_duration`,
3271
+ * `eval_duration` — see the official "Usage" documentation), plus token counters
3272
+ * (`prompt_eval_count`, `prompt_eval_cached_count`, `eval_count`). Consumers that
3273
+ * want milliseconds, tokens/second, or a cache-hit ratio otherwise each reimplement
3274
+ * the same division-and-rounding math — this module is that math, once, with the
3275
+ * formulas the official docs spell out:
3276
+ *
3277
+ * - `tokensPerSecond` = `eval_count / (eval_duration / 1e9)` — generation throughput.
3278
+ * - `promptTokensPerSecond` = `prompt_eval_count / (prompt_eval_duration / 1e9)` —
3279
+ * prompt ingestion (pre-fill) throughput.
3280
+ * - `cacheHitRatio` = `prompt_eval_cached_count / (cached + evaluated)` — see the
3281
+ * note on {@link FormattedTelemetry.cacheHitRatio} for why the denominator is the
3282
+ * *sum*, not `prompt_eval_count` alone.
3283
+ *
3284
+ * Pure and dependency-free: {@link formatTelemetry} never fetches, never throws, and
3285
+ * treats every missing counter as `0` — partial responses (stream final events,
3286
+ * older servers without `prompt_eval_cached_count`) format cleanly instead of
3287
+ * producing `NaN`/`Infinity`.
3288
+ *
3289
+ * The input is structural: any response object carrying these optional fields —
3290
+ * `GenerateResponse`, `ChatResponse`, the final `GenerateStreamEvent`,
3291
+ * `EmbedResponse` — can be passed directly, no picking/plucking required.
3292
+ */
3293
+ /**
3294
+ * The raw nanosecond/token counters Ollama attaches to generation responses. Every
3295
+ * field is optional because servers report a subset: streaming final events may omit
3296
+ * load counters, older builds predate `prompt_eval_cached_count`, and embeddings
3297
+ * carry no `eval_count`. Accepts full response objects structurally.
3298
+ */
3299
+ interface RawOllamaMetrics {
3300
+ /** Total end-to-end request latency, nanoseconds. */
3301
+ readonly total_duration?: number | undefined;
3302
+ /** Model cold-load and weight-transfer time into VRAM, nanoseconds. */
3303
+ readonly load_duration?: number | undefined;
3304
+ /** Prompt tokens freshly evaluated this request (not served from the KV cache). */
3305
+ readonly prompt_eval_count?: number | undefined;
3306
+ /** Prompt tokens served from the KV prompt cache (prefix reuse). */
3307
+ readonly prompt_eval_cached_count?: number | undefined;
3308
+ /** Prompt ingestion / pre-fill processing time, nanoseconds. */
3309
+ readonly prompt_eval_duration?: number | undefined;
3310
+ /** Tokens generated (the response proper). */
3311
+ readonly eval_count?: number | undefined;
3312
+ /** Token generation time, nanoseconds. */
3313
+ readonly eval_duration?: number | undefined;
3314
+ }
3315
+ /** The normalized, human-scale view of one response's {@link RawOllamaMetrics}. */
3316
+ interface FormattedTelemetry {
3317
+ /** `total_duration` in milliseconds, 2 decimals. */
3318
+ readonly totalLatencyMs: number;
3319
+ /** `load_duration` in milliseconds, 2 decimals — 0 when the model was already resident. */
3320
+ readonly modelLoadMs: number;
3321
+ /** `prompt_eval_duration` in milliseconds, 2 decimals. */
3322
+ readonly promptEvalMs: number;
3323
+ /** `eval_duration` in milliseconds, 2 decimals. */
3324
+ readonly generationMs: number;
3325
+ /** `eval_count / eval_duration` in tokens/second, 1 decimal — 0 when either is absent. */
3326
+ readonly tokensPerSecond: number;
3327
+ /** `prompt_eval_count / prompt_eval_duration` in tokens/second, 1 decimal. */
3328
+ readonly promptTokensPerSecond: number;
3329
+ /**
3330
+ * Share of prompt tokens served from the KV cache:
3331
+ * `cached / (cached + evaluated)`, 3 decimals.
3332
+ *
3333
+ * The denominator is the **sum**, not `prompt_eval_count` alone, because Ollama
3334
+ * reports `prompt_eval_count: 0` on a *full* cache hit — the same house semantics
3335
+ * as `ConversationSession`'s `cacheStats.hitRate` (see `src/conversation.ts`). A
3336
+ * `cached / prompt_eval_count` formula would report a perfect cache as `0`.
3337
+ */
3338
+ readonly cacheHitRatio: number;
3339
+ }
3340
+ /**
3341
+ * Derives the standardized metrics summary from one response's raw nanosecond
3342
+ * counters. Pure — never throws, never fetches; every missing counter reads as `0`.
3343
+ *
3344
+ * ```ts
3345
+ * const res = await client.chat({ model: 'llama3.2', messages });
3346
+ * const t = formatTelemetry(res);
3347
+ * console.log(t.tokensPerSecond, 'tok/s |', t.totalLatencyMs, 'ms |',
3348
+ * `${Math.round(t.cacheHitRatio * 100)}% prompt cache hit`);
3349
+ * ```
3350
+ */
3351
+ declare function formatTelemetry(raw: RawOllamaMetrics): FormattedTelemetry;
3352
+
3069
3353
  /**
3070
3354
  * Cross-runtime helpers with no Node.js API dependency, so they stay safe to import from
3071
3355
  * the core client bundle (see ADR 0006 — Edge Runtime CI).
@@ -3340,4 +3624,4 @@ declare class ModelAffinityScheduler {
3340
3624
  /** Convenience factory — `createModelAffinityScheduler(client, opts)` reads better in setups. */
3341
3625
  declare function createModelAffinityScheduler(client: ModelAffinityClient | OllamaClient, options?: ModelAffinitySchedulerOptions): ModelAffinityScheduler;
3342
3626
 
3343
- export { ATTR_GEN_AI_OPERATION_NAME, ATTR_GEN_AI_REQUEST_MODEL, ATTR_GEN_AI_RESPONSE_MODEL, ATTR_GEN_AI_SYSTEM, ATTR_GEN_AI_TOOL_CALL_ID, ATTR_GEN_AI_TOOL_NAME, ATTR_GEN_AI_USAGE_INPUT_TOKENS, ATTR_GEN_AI_USAGE_OUTPUT_TOKENS, ATTR_HTTP_REQUEST_METHOD, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_OLLAMA_AGENT_ITERATION, ATTR_OLLAMA_AGENT_MAX_ITERATIONS, ATTR_OLLAMA_ENDPOINT_ATTEMPT, ATTR_OLLAMA_ENDPOINT_NAME, ATTR_SERVER_ADDRESS, ATTR_SERVER_PORT, ATTR_URL_FULL, AbortableAsyncIterable, Agent, type AgentChatClient, type AgentConfig, type AgentHooks, type AgentResult, type AgentRunInput, type AgentTurn, type AnswerFor, AnthropicCompatClient, AnyTool, type BackoffOptions, BalanceRequestOptions, type BalanceResponse, type BlobUploadResult, ChatRequestOptions, ChatResponse, ChatStreamResult, type ChoiceDecision, type CompactionOptions, type ContextCheck, type ContextCheckOptions, type ContextDiscoveryRequestOptions, type ContextLengthSignals, type ContextLengthSource, type ContextWindowSource, type ConversationSendOptions, ConversationSession, type ConversationSessionOptions, CopyRequestOptions, CreateRequestOptions, type CumulativeCacheStats, DEFAULT_BACKOFF, DEFAULT_BASE_URL, DEFAULT_CONTEXT_WARNING_THRESHOLD, DEFAULT_EMBED_BATCH_SIZE, DEFAULT_EMBED_CONCURRENCY, DEFAULT_FAILOVER_CODES, DEFAULT_FETCH_BACKOFF_CONFIG, DEFAULT_RETRY_CONFIG, DEFAULT_TIMEOUT_MS, type Decision, type DefineToolOptions, DeleteRequestOptions, type DiscoveredContextLength, type EmbedBatchOptions, type EmbedBatchResult, EmbedRequestOptions, EmbedResponse, EmbeddingsRequestOptions, EmbeddingsResponse, type EndpointHealth, type EndpointHealthCheckResult, EndpointRegistry, type EndpointRegistryOptions, FetchLike, type FetchWithBackoffConfig, FormatOption, GEN_AI_SYSTEM_OLLAMA, GenerateRequestOptions, GenerateResponse, GenerateStreamResult, type HistorySanitizeOptions, HttpClient, IMAGE_TOKEN_ESTIMATE, type IncludedBalance, KEEP_ALIVE_INDEFINITE, KEEP_ALIVE_UNLOAD, KNOWN_DONE_REASONS, type KeepAlive, type KnownDoneReason, type LegacyBalanceLimit, type LegacyIncludedBalance, type LoadMcpToolsOptions, Logger, MAX_SYSTEM_ONE_IMAGES_BYTES, MAX_SYSTEM_ONE_REQUEST_BYTES, MESSAGE_OVERHEAD_TOKENS, McpBridge, type McpBridgeOptions, McpCallToolResult, McpClientLike, McpTask, McpToolDescriptor, Message, Middleware, type ModelAffinityClient, ModelAffinityScheduler, type ModelAffinitySchedulerOptions, type ModelAffinityStats, type ModelCapabilities, ModelOptions, ModelResponse, ModelsClient, type NoulDecision, OLLAMA_CLOUD_BASE_URL, OLLAMA_FALLBACK_CONTEXT_LENGTH, OllamaClient, type OllamaClientConfig, type OllamaCloudFreeTierQuotaBudgets, type OllamaCredentialConfig, type OllamaEndpoint, OllamaStream, OllamaStreamEvent, OllamaStreamEventType, OpenAICompatClient, type OversizedEmbedInput, type ParallelToolCallBehavior, ProgressResponse, ProgressStreamResult, PsResponse, PullRequestOptions, PushRequestOptions, QuotaManager, type QuotaManagerOptions, type QuotaWindowConfig, type QuotaWindowStatus, RETRYABLE_STATUS_CODES, type RankResult, RawUsageSource, RequestCancellationOptions, RequestLifecycleHook, RequestRunner, type ResponsesCreateRequest, type ResponsesCreateResponse, ResponsesModule, type ResponsesReasoningEffort, type ResponsesStreamEvent, type ResponsesToolDefinition, type ResponsesUsage, type RetryConfig, type RuntimeMode, type ScoreDecision, type SessionCompactionOptions, type SessionCompactionResult, type SessionTurn, ShowRequestOptions, ShowResponse, type SpanAttributeValue, type SpanAttributes, StatusResponse, type SupportedSchema, type SystemOneAnswer, type SystemOneAnswers, SystemOneChoiceAnswer, SystemOneChoiceQuestion, SystemOneContent, SystemOneNoulAnswer, SystemOneNoulQuestion, type SystemOneQuestion, type SystemOneQuestions, type SystemOneRequest, type SystemOneResponse, SystemOneScoreAnswer, SystemOneScoreQuestion, type SystemOneUsage, ThinkValue, ThinkingMetadata, type TimeoutSignal, TokenUsage, Tool, ToolCall, ToolCallAccumulator, ToolDefinition, ToolExecutionResult, ToolHandler, ToolParameters, ToolRegistry, type TurnCacheStats, type UsageBucket, type UsageMetrics, UsageRequestOptions, type UsageResponse, VersionResponse, VisionInput, WebFetchRequestOptions, WebFetchResponse, WebSearchRequestOptions, WebSearchResponse, addSpanEvent, batchEmbed, calculateBackoff, canonicalToolCallSignature, checkChatContext, checkEndpointHealth, checkGenerateContext, compactConversationHistory, contextWarningMessage, createDecision, createModelAffinityScheduler, createOllamaCloudFreeTierQuota, createTimeoutSignal, defineTool, detectModelCapabilities, embedBatchOverflowMessage, encodeImage, estimateChatRequestTokens, estimateGenerateRequestTokens, estimateMessageTokens, estimateSystemOneRequestBytes, estimateTokens, extractContextLength as extractNativeContextLength, extractParameterNumCtx, fetchWithBackoff, findOversizedEmbedInputs, findRunningModelContextLength, inferRuntimeMode, isKeepAliveSugar, isKnownDoneReason, isSameToolCall, listAllMcpTools, listAvailableModels, loadMcpTools, mergeToolCall, mergeToolCallArgumentsString, mergeToolCallArrays, normalizeChatStream, normalizeGenerateStream, normalizeKeepAlive, normalizeProgressStream, parseNdjsonStream, parseStructuredOutput, registerMcpTools, resolveContextLength, resolveCredentialEndpoints, sanitizeHistoryForNextTurn, setSpanError, toDataStream, toResponse, toTextStream, withRetry, withSpan, zodToJsonSchema };
3627
+ export { ATTR_GEN_AI_OPERATION_NAME, ATTR_GEN_AI_REQUEST_MODEL, ATTR_GEN_AI_RESPONSE_MODEL, ATTR_GEN_AI_SYSTEM, ATTR_GEN_AI_TOOL_CALL_ID, ATTR_GEN_AI_TOOL_NAME, ATTR_GEN_AI_USAGE_INPUT_TOKENS, ATTR_GEN_AI_USAGE_OUTPUT_TOKENS, ATTR_HTTP_REQUEST_METHOD, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_OLLAMA_AGENT_ITERATION, ATTR_OLLAMA_AGENT_MAX_ITERATIONS, ATTR_OLLAMA_ENDPOINT_ATTEMPT, ATTR_OLLAMA_ENDPOINT_NAME, ATTR_SERVER_ADDRESS, ATTR_SERVER_PORT, ATTR_URL_FULL, AbortableAsyncIterable, type AffinityRunningModel, Agent, type AgentChatClient, type AgentConfig, type AgentHooks, type AgentResult, type AgentRunInput, type AgentTurn, type AnswerFor, AnthropicCompatClient, AnyTool, type BackoffOptions, BalanceRequestOptions, type BalanceResponse, type BlobUploadResult, ChatRequestOptions, ChatResponse, ChatStreamResult, type ChoiceDecision, type CompactionOptions, type ContextCheck, type ContextCheckOptions, type ContextDiscoveryRequestOptions, type ContextLengthSignals, type ContextLengthSource, type ContextWindowSource, type ConversationSendOptions, ConversationSession, type ConversationSessionOptions, CopyRequestOptions, CreateRequestOptions, type CumulativeCacheStats, DEFAULT_BACKOFF, DEFAULT_BASE_URL, DEFAULT_CONTEXT_WARNING_THRESHOLD, DEFAULT_EMBED_BATCH_SIZE, DEFAULT_EMBED_CONCURRENCY, DEFAULT_FAILOVER_CODES, DEFAULT_FETCH_BACKOFF_CONFIG, DEFAULT_RETRY_CONFIG, DEFAULT_TIMEOUT_MS, type Decision, type DefineToolOptions, DeleteRequestOptions, type DiscoveredContextLength, type EmbedBatchOptions, type EmbedBatchResult, EmbedRequestOptions, EmbedResponse, EmbeddingsRequestOptions, EmbeddingsResponse, type EndpointHealth, type EndpointHealthCheckResult, EndpointRegistry, type EndpointRegistryOptions, FetchLike, type FetchWithBackoffConfig, FormatOption, type FormattedTelemetry, GEN_AI_SYSTEM_OLLAMA, GenerateRequestOptions, GenerateResponse, GenerateStreamResult, type HistorySanitizeOptions, HttpClient, IMAGE_TOKEN_ESTIMATE, type IncludedBalance, KEEP_ALIVE_INDEFINITE, KEEP_ALIVE_UNLOAD, KNOWN_DONE_REASONS, type KeepAlive, type KnownDoneReason, type LegacyBalanceLimit, type LegacyIncludedBalance, type LoadMcpToolsOptions, Logger, MAX_SYSTEM_ONE_IMAGES_BYTES, MAX_SYSTEM_ONE_REQUEST_BYTES, MESSAGE_OVERHEAD_TOKENS, McpBridge, type McpBridgeOptions, McpCallToolResult, McpClientLike, McpTask, McpToolDescriptor, Message, Middleware, type ModelAffinityClient, ModelAffinityRouter, type ModelAffinityRoutingOptions, ModelAffinityScheduler, type ModelAffinitySchedulerOptions, type ModelAffinitySnapshot, type ModelAffinityStats, type ModelCapabilities, ModelOptions, ModelResponse, ModelsClient, type NoulDecision, OLLAMA_CLOUD_BASE_URL, OLLAMA_FALLBACK_CONTEXT_LENGTH, OllamaClient, type OllamaClientConfig, type OllamaCloudFreeTierQuotaBudgets, type OllamaCredentialConfig, type OllamaEndpoint, OllamaStream, OllamaStreamEvent, OllamaStreamEventType, OpenAICompatClient, type OversizedEmbedInput, type ParallelToolCallBehavior, PingResult, ProgressResponse, ProgressStreamResult, PsResponse, PullRequestOptions, PushRequestOptions, QuotaManager, type QuotaManagerOptions, type QuotaWindowConfig, type QuotaWindowStatus, RETRYABLE_STATUS_CODES, type RankResult, type RawOllamaMetrics, RawUsageSource, RequestCancellationOptions, RequestLifecycleHook, RequestRunner, type ResponsesCreateRequest, type ResponsesCreateResponse, ResponsesModule, type ResponsesReasoningEffort, type ResponsesStreamEvent, type ResponsesToolDefinition, type ResponsesUsage, type RetryConfig, type RuntimeMode, type ScoreDecision, type SessionCompactionOptions, type SessionCompactionResult, type SessionTurn, ShowRequestOptions, ShowResponse, type SpanAttributeValue, type SpanAttributes, StatusResponse, type SupportedSchema, type SystemOneAnswer, type SystemOneAnswers, SystemOneChoiceAnswer, SystemOneChoiceQuestion, SystemOneContent, SystemOneNoulAnswer, SystemOneNoulQuestion, type SystemOneQuestion, type SystemOneQuestions, type SystemOneRequest, type SystemOneResponse, SystemOneScoreAnswer, SystemOneScoreQuestion, type SystemOneUsage, ThinkValue, ThinkingMetadata, type TimeoutSignal, TokenUsage, Tool, ToolCall, ToolCallAccumulator, ToolDefinition, ToolExecutionResult, ToolHandler, ToolParameters, ToolRegistry, type TurnCacheStats, type UsageBucket, type UsageMetrics, UsageRequestOptions, type UsageResponse, VersionResponse, VisionInput, WebFetchRequestOptions, WebFetchResponse, WebSearchRequestOptions, WebSearchResponse, addSpanEvent, batchEmbed, calculateBackoff, canonicalToolCallSignature, checkChatContext, checkEndpointHealth, checkGenerateContext, compactConversationHistory, contextWarningMessage, createDecision, createModelAffinityScheduler, createOllamaCloudFreeTierQuota, createTimeoutSignal, defineTool, detectModelCapabilities, embedBatchOverflowMessage, encodeImage, estimateChatRequestTokens, estimateGenerateRequestTokens, estimateMessageTokens, estimateSystemOneRequestBytes, estimateTokens, extractContextLength as extractNativeContextLength, extractParameterNumCtx, fetchWithBackoff, findOversizedEmbedInputs, findRunningModelContextLength, formatTelemetry, inferRuntimeMode, isKeepAliveSugar, isKnownDoneReason, isModelResident, isSameToolCall, listAllMcpTools, listAvailableModels, loadMcpTools, mergeToolCall, mergeToolCallArgumentsString, mergeToolCallArrays, normalizeChatStream, normalizeGenerateStream, normalizeKeepAlive, normalizeProgressStream, parseNdjsonStream, parseStructuredOutput, registerMcpTools, resolveContextLength, resolveCredentialEndpoints, sanitizeHistoryForNextTurn, setSpanError, toDataStream, toResponse, toTextStream, withRetry, withSpan, zodToJsonSchema };