/** Selects and invokes registered model providers with admission, failover, streaming, and trajectory recording. Handlers receive the original runtime; private lifecycle and prompt collaborators remain explicit host callbacks. */ import { type ConfidentialInferenceAuthority } from "../security/confidential-inference.js"; import { type PseudonymSession } from "../security/pii-pseudonymizer.js"; import { type ProcessingPolicy } from "../security/processing-policy.js"; import type { SecretSwapSession } from "../security/secret-swap.js"; import { type ModelHandler, type ModelParamsMap, type ModelRegistrationInfo, type ModelRegistrationMetadata, type ModelResultMap, type ModelTypeName } from "../types/model.js"; import type { JsonValue, UUID } from "../types/primitives.js"; import type { IAgentRuntime } from "../types/runtime.js"; import type { Service, ServiceTypeName } from "../types/service.js"; import { type ModelInputBudget } from "./model-input-budget.js"; import { type ResolvedModelRegistration } from "./model-policy.js"; import type { RuntimePipelineHooks } from "./pipeline-hooks.js"; export interface RuntimeModelDispatchHost { confidentialInference(): ConfidentialInferenceAuthority | undefined; processingPolicy(): ProcessingPolicy | undefined; models(): Map; pinnedEmbeddingProvider(): string | undefined; validateEmbeddingOutput(modelType: string, params: unknown, source: unknown, result: unknown, provider: string, signal?: AbortSignal): void | Promise; currentRoomId(): UUID | undefined; isSecretSwapEnabled(): boolean; isPiiSwapEnabled(): boolean; hooksForPhase(...args: Parameters): ReturnType; invokePipelineHooks(...args: Parameters): ReturnType; createSecretSwapSession(): SecretSwapSession; createPiiSwapSession(): PseudonymSession; initResolver(): ((value?: void | PromiseLike) => void) | undefined; _ensureServiceStarted(serviceType: ServiceTypeName | string): Promise; } export declare class RuntimeModelDispatch { private readonly runtime; private readonly host; private readonly pendingDiagnostics; private trackDiagnostic; /** Finish owned writes before services or their database are closed. */ drainDiagnostics(): Promise; constructor(runtime: IAgentRuntime, host: RuntimeModelDispatchHost); /** Records the provider serving the most recent successful call for each requested model type. Trajectory recorders use this attribution instead of inventing a provider identity. */ private readonly lastResolvedModelProviderByType; buildRuntimeSystemPrompt(): string | undefined; /** Attach the effective system prompt to a text request that does not set one. */ private attachEffectiveSystemPrompt; registerModel(modelType: ModelTypeName | string, handler: (runtime: IAgentRuntime, params: Record) => Promise, provider: string, priority?: number, metadata?: ModelRegistrationMetadata): void; /** * Handler-free snapshot of every registered model handler, sorted by * priority (descending) then registration order within each model type — * the same order `getModel`/`useModel` select in. Exposes the private * `models` map as metadata so hosts and observers can render a routing * table or seed a mirror without touching handler functions. Pair with the * {@link EventType.MODEL_REGISTERED} event to stay live. */ getModelRegistrations(): ModelRegistrationInfo[]; /** * Record the provider that served a successful `useModel` call, keyed by the * requested model-type string. Only real (non-empty) provider names are * stored so a caller reading it back never sees a fabricated value. */ noteResolvedModelProvider(modelTypeKey: string, provider: string | undefined): void; /** * The provider name that served the most recent successful `useModel` call * for the given model type, or `undefined` if no such call has completed * (so callers can fail-closed rather than fabricate a provider). Lets the * trajectory stage recorders in `services/message.ts` name the real provider * that answered the messageHandler / factsAndRelationships call instead of * the hardcoded `"default"` literal. */ getLastResolvedModelProvider(modelType: ModelTypeName | string): string | undefined; /** * The runtime-selected text-model provider from `ELIZA_BRAIN_PROVIDER`, read * on every call so an owner change applies with no restart. It is a strict * pin: a provider with no handler fails the call (see throwNoModelHandler) * and its failures never fall over to another provider. */ resolveTextProviderOverride(): string | undefined; isCanonicalModelCapabilityDisabled(modelType: string): boolean; assertCanonicalModelCapabilityEnabled(modelType: string): void; resolveModelRegistration(modelType: ModelTypeName | string, provider?: string): ResolvedModelRegistration | undefined; resolveModelRegistrations(modelType: ModelTypeName | string, provider?: string): ResolvedModelRegistration[]; logModelProviderFailover(args: { requestedModelKey: string; failedModel: ResolvedModelRegistration; nextModel: ResolvedModelRegistration; error: unknown; }): void; shouldFailOverModelProvider(error: unknown, modelType: string): boolean; throwNoModelHandler(requestedModelKey: string, pinnedProvider?: string): never; /** * Surface the failure that ends a `useModel` failover chain. A real `Error` * with a message rethrows unchanged so provider SDK stack traces and typed * subclasses (e.g. `NoModelProviderConfiguredError`, which the chat UI * narrows on) survive the boundary. Everything else — the bare * `{ status, error }` objects some providers/AI-SDK paths throw, or a * message-less `Error` — becomes an `ElizaError` whose message names the * provider, HTTP status, and underlying cause. Without this, a bare object * stringified to the diagnostically useless "[object Object]" in logs, * trajectories, and any user-surfaced failure text. */ rethrowModelFailoverError(error: unknown, failed?: { modelKey: string; provider: string; }): never; getModel(modelType: ModelTypeName | string): ((runtime: IAgentRuntime, params: Record) => Promise) | undefined; /** * Retrieves model configuration settings from character settings with support for * model-specific overrides and default fallbacks. * * Precedence order (highest to lowest): * 1. Model-specific settings (e.g., TEXT_SMALL_TEMPERATURE) * 2. Default settings (e.g., DEFAULT_TEMPERATURE) * * @param modelType The specific model type to get settings for * @returns Object containing model parameters if they exist, or null if no settings are configured */ getModelSettings(modelType?: ModelTypeName): Record | null; /** Resolve the concrete provider model id used for final-wire budgeting. */ resolveRegistrationModelName(metadata: ModelRegistrationMetadata | undefined): string | undefined; /** * Budget the exact text-generation request after runtime transforms and * pre-model hooks. UTF-8 bytes are a conservative token upper bound. The * estimate is diagnostic: it never rejects a request or rewrites any * model-facing field. */ buildFinalModelInputBudget(params: unknown, metadata: ModelRegistrationMetadata | undefined): ModelInputBudget; /** * Attach the final budget to `providerOptions.eliza.modelInputBudget` so the * estimate includes its own metadata. The request is serialized once, with a * placeholder budget of the same shape; the real budget differs only in the * digits of `estimatedInputTokens`, so its size is settled arithmetically. */ attachFinalModelInputBudget(record: Record, metadata: ModelRegistrationMetadata | undefined): ModelInputBudget; /** Clone caller-owned request data before runtime transforms. Arrays and * plain records become handler-owned; opaque transport collaborators retain * identity because cloning them would change platform semantics. */ cloneModelRequestGraph(value: T): T; /** Freeze the complete admitted handler payload so provider code cannot add, * remove, or rewrite model-bound data after the final measurement. Only * arrays and plain records belong to the request graph; platform objects * such as AbortSignal remain opaque transport collaborators. */ freezeAdmittedModelRequest(value: unknown): void; logModelCall(modelType: string, modelKey: string, promptContent: string | null, systemPrompt: string | undefined, elapsedTime: number, provider: string | undefined, response: unknown): void; private resolveDispatchRegistrations; /** Resolve an action chain once; nested attempts clear only modelClass. */ private routeActionModel; useModel(modelType: T, params: ModelParamsMap[T], provider?: string): Promise; /** * Emit an llm-call entry against the current trajectory step for a * `useModel` call. Pure dedupe of the streaming and non-streaming paths * inside {@link useModel}; both paths formerly inlined an identical block. * * Skipped while the runtime is still initializing because * {@link _ensureServiceStarted} awaits `initPromise` and would deadlock. * Trajectory logging must never break core model flow, so any thrown * error here is swallowed. */ recordUseModelTrajectory(args: { modelType: string; resolvedModelKey: string; provider?: string; modelParams: unknown; promptContent: string | null | undefined; result?: unknown; response: string; elapsedTime: number; providerRecorded: boolean; }): Promise; /** * Emit a failure llm-call entry for a `useModel` attempt that threw before * producing a usable result. Without this, a rejected provider attempt is * invisible in the trajectory: if failover succeeds, only the successful * call appears and the failed (and often billed) attempt is lost; if every * attempt fails, the step has zero model entries at all. * * Records the real error — sanitized of secrets — as the response payload * with `finishReason: "error"`, and does NOT fabricate an empty response or * zero token counts. Trajectory logging never breaks core model flow, so * failures here are swallowed and surfaced via reportError instead. */ recordFailedModelTrajectory(args: { modelType: string; resolvedModelKey: string; provider?: string; modelParams: unknown; promptContent: string | null | undefined; error: unknown; elapsedTime: number; }): Promise; }