/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see .
*/
import crypto from 'node:crypto';
import { PassThrough } from 'node:stream';
import { EventMap } from '../../../../clients/event/types.js';
import type { Actor } from '../../../../core/actor.js';
import { Context } from '../../../../core/context.js';
import { HttpError, isHttpError } from '../../../../core/http/HttpError.js';
import {
creditsRefilled,
insufficientCreditsError,
} from '../../../../services/metering/enforcement.js';
import { isFreeSubscription } from '../../../../services/metering/consts.js';
import type { MeteringService } from '../../../../services/metering/MeteringService.js';
import type { CreditHold } from '../../../../services/metering/types.js';
import { NO_CREDIT_HOLD } from '../../../../services/metering/types.js';
import type { DriverStreamResult } from '../../../meta.js';
import { PuterDriver } from '../../../types.js';
import {
type AiMeteringService,
factoredTotal,
requestAiCosts,
withAiCostFactor,
} from '../../../../util/aiCostFactor.js';
import { AI_CONCURRENT, AI_RATE_LIMIT } from '../../shared/aiLimits.js';
import {
isCreditExhaustion as isUpstreamCreditExhaustion,
isUpstreamConnectionError,
isUpstreamTimeoutError,
sanitizeUpstreamMessage,
UpstreamDeadlineError,
} from '../../../util/upstreamErrors.js';
import { AlibabaProvider } from '../../providers/alibaba/chat/AlibabaProvider.js';
import { AzureChatProvider } from '../../providers/azure/chat/AzureChatProvider.js';
import { AzureResponsesProvider } from '../../providers/azure/chat/AzureResponsesProvider.js';
import { BytePlusProvider } from '../../providers/byteplus/chat/BytePlusProvider.js';
import { ClaudeProvider } from '../../providers/claude/chat/ClaudeProvider.js';
import { DeepSeekProvider } from '../../providers/deepseek/chat/DeepSeekProvider.js';
import { FakeChatProvider } from '../../providers/fake/chat/FakeChatProvider.js';
import { GeminiChatProvider } from '../../providers/gemini/chat/GeminiChatProvider.js';
import { GroqAIProvider } from '../../providers/groq/chat/GroqAIProvider.js';
import { HoonifyProvider } from '../../providers/hoonify/chat/HoonifyProvider.js';
import { InfronProvider } from '../../providers/infron/chat/InfronProvider.js';
import { MetaProvider } from '../../providers/meta/chat/MetaProvider.js';
import { MiniMaxProvider } from '../../providers/minimax/chat/MiniMaxProvider.js';
import { MistralAIProvider } from '../../providers/mistral/chat/MistralAiProvider.js';
import { MoonshotProvider } from '../../providers/moonshot/chat/MoonshotProvider.js';
import { NeuralwattProvider } from '../../providers/neuralwatt/chat/NeuralwattProvider.js';
import { OllamaChatProvider } from '../../providers/ollama/chat/OllamaProvider.js';
import type { ChatProviderConfig } from '../../protocols/openaiCompatible/OpenAICompatProvider.js';
import { processPuterPathUploads } from '../../providers/openai/chat/fileUpload.js';
import { OpenAiChatProvider } from '../../providers/openai/chat/OpenAiChatCompletionsProvider.js';
import { OpenAiResponsesChatProvider } from '../../providers/openai/chat/OpenAiChatResponsesProvider.js';
import { OpenRouterProvider } from '../../providers/openrouter/chat/OpenRouterProvider.js';
import { TogetherAIProvider } from '../../providers/together/chat/TogetherAIProvider.js';
import { XAIProvider } from '../../providers/xai/chat/XAIProvider.js';
import { ZAIProvider } from '../../providers/zai/chat/ZAIProvider.js';
import type {
IChatCompleteResult,
IChatMessageResult,
IChatModel,
IChatProvider,
ICompleteArguments,
RefusalFallback,
UsageDetails,
} from './types.js';
import { normalize_tools_object } from './utils/FunctionCalling.js';
import {
requestedServiceSpeed,
selectServiceSpeed,
lowerServiceSpeed,
isServiceSpeedUnavailable,
} from './utils/serviceSpeed.js';
import {
messagesHavePuterPaths,
modelSupportsModality,
normalizeMediaParts,
requiredInputModalities,
} from './utils/mediaParts.js';
import {
normalize_messages,
normalize_single_message,
} from './utils/Messages.js';
import {
compareModelPreference,
isIdentityKey,
normalizeModelKey,
} from './utils/modelRouting.js';
import {
normalizeResultToOpenAI,
shouldPresentAsOpenAI,
} from './utils/normalizeToOpenAI.js';
import {
isToolChoice,
toolChoiceFromWire,
} from '../../protocols/openaiCompatible/openaiParams.js';
import { assertScalarOptions } from '../../shared/scalarOptions.js';
import { catalogPrice } from '../../shared/catalogPrice.js';
import {
costKeys,
costsForRequest,
isFreeModel,
listedCosts,
longContextMultipliers,
scheduledChangeTimes,
trackedOutputTokens,
usageCost,
usageDetailsFromUsage,
} from './utils/pricing.js';
import {
isRouteUnhealthy,
markRouteUnhealthy,
TRANSIENT_UNHEALTHY_TTL_SEC,
UNHEALTHY_TTL_SEC,
} from './utils/providerHealth.js';
import { CATALOG_TTL_MS } from '../../shared/cachedRemoteCatalog.js';
import { SDK_TIMEOUT_MS } from './utils/sdkClient.js';
import { fromFinishReason } from './utils/stopReason.js';
import { AIChatStream } from './utils/Streaming.js';
import {
estimateOutputTokens,
estimatePromptTokens,
estimateToolTokens,
} from './utils/usageEstimate.js';
const MAX_ATTEMPTS = 3; // the first attempt plus two fallbacks
/**
* Providers built from `config.providers[configKey]` (default: `name`) when it
* carries an API key.
*/
const KEYED_PROVIDERS: {
name: string;
configKey?: string;
Class: new (
config: ChatProviderConfig,
metering: MeteringService,
) => IChatProvider;
}[] = [
{ name: 'gemini', Class: GeminiChatProvider },
{ name: 'meta', Class: MetaProvider },
{ name: 'groq', Class: GroqAIProvider },
{ name: 'deepseek', Class: DeepSeekProvider },
{ name: 'mistral', Class: MistralAIProvider },
{ name: 'xai', Class: XAIProvider },
{ name: 'moonshotai', configKey: 'moonshot', Class: MoonshotProvider },
{ name: 'minimax', Class: MiniMaxProvider },
{ name: 'zai', Class: ZAIProvider },
{ name: 'alibaba', Class: AlibabaProvider },
{ name: 'infron', Class: InfronProvider },
{ name: 'openrouter', Class: OpenRouterProvider },
{ name: 'together-ai', Class: TogetherAIProvider },
{ name: 'byteplus', Class: BytePlusProvider },
{ name: 'neuralwatt', Class: NeuralwattProvider },
{ name: 'hoonify', Class: HoonifyProvider },
];
/**
* Key of the driver's token-count entry point. A symbol rather than a method
* name so it stays off the `/drivers/call` surface, which only resolves
* string-named methods; the Anthropic route calls it in-process.
*/
export const COUNT_TOKENS = Symbol('aiChat.countTokens');
/**
* How often a streaming completion renews its credit hold. Holds default to a
* 10-minute TTL; a long generation (a reasoning model with a large
* `max_tokens`) can stream past that, and a hold that expires mid-stream
* reopens the overspend window it exists to close.
*/
const HOLD_RENEW_INTERVAL_MS = 5 * 60 * 1000;
// Options that reach error messages and request headers as text.
const SCALAR_OPTIONS = [
'model',
'provider',
'service_tier',
'refusalFallbackModel',
];
/**
* A moderation refusal is a completion that was produced and charged, then
* withheld — not a route failure. Retrying it on a fallback provider would bill
* the account again for another completion the user will never see. A check
* that couldn't run withholds the completion the same way.
*/
const isModerationRefusal = (e: unknown): boolean =>
isHttpError(e) &&
(e.code === 'moderation_flagged' || e.code === 'moderation_unavailable');
/** Times the credit gate sizes a request again after losing the headroom. */
const CREDIT_GATE_ATTEMPTS = 3;
/**
* Times the credit gate reads a balance that keeps changing under it, and the
* upper bound of the randomized wait before each new read, times the attempt.
* The same policy as a fixed-amount reservation's.
*/
const CREDIT_GATE_STALE_ATTEMPTS = 5;
const CREDIT_GATE_STALE_BACKOFF_MS = 20;
/**
* The refusal for a request its funds can't cover. When what's missing is only
* held by the account's own requests still in flight, waiting is the remedy,
* not a top-up: a retryable 429 rather than a 402 that prompts an upgrade.
*/
const fundsRefusal = (heldByInFlight: boolean): HttpError =>
heldByInFlight
? new HttpError(
429,
'Usage is reserved by requests still running. Retry when they finish, or upgrade at https://puter.com/#billing',
{ legacyCode: 'too_many_requests', code: 'credits_reserved' },
)
: insufficientCreditsError();
/**
* A clear 400 for media parts the catalog says the model cannot read. Entries
* that declare no modalities (reseller catalogs) are not judged.
*/
const assertInputModalities = (
model: IChatModel,
messages: ICompleteArguments['messages'] | undefined,
): void => {
if (!Array.isArray(model.modalities?.input)) return;
for (const modality of requiredInputModalities(messages)) {
if (!modelSupportsModality(model, modality)) {
throw new HttpError(
400,
`Model ${model.id} does not support ${modality} input`,
{ legacyCode: 'bad_request' },
);
}
}
};
const positiveOrInfinity = (n: unknown): number =>
typeof n === 'number' && Number.isFinite(n) && n > 0
? n
: Number.POSITIVE_INFINITY;
/**
* The most output a request to `model` can get: its output limit, and no more
* than the context window leaves after the prompt. A limit a catalog doesn't
* know bounds nothing. A prompt estimated to fill the window is left for the
* provider to refuse — the estimate is approximate, and running out of credits
* would be the wrong answer either way.
*/
const outputCeiling = (
model: IChatModel,
promptTokenEstimate: number,
): number => {
const outputLimit = positiveOrInfinity(model.max_tokens);
const contextRoom = positiveOrInfinity(model.context) - promptTokenEstimate;
return contextRoom >= 1 ? Math.min(outputLimit, contextRoom) : outputLimit;
};
type ProviderAttempt = {
model: string;
provider: string;
status?: number;
code?: string;
error: string;
/** The attempt died to a transport timeout rather than an answer. */
timedOut?: boolean;
/** The connection dropped or never opened (reset, refused) before an answer. */
connectionFailed?: boolean;
/**
* The vendor's own error type (Anthropic `error.error.type`, OpenAI
* `error.type`).
*/
upstreamType?: string;
/**
* The vendor's own, uncleaned message — kept separate so
* `requestLevelError` can surface it verbatim.
*/
upstreamMessage?: string;
retryAfter?: string | number;
};
/**
* Capture what an upstream provider gave us so the classifier downstream can
* decide a user-facing status code instead of always returning 500.
*
* OpenAI-SDK-based providers throw `APIError` with `.status` and a structured
* `.error` body — pull both. For arbitrary errors we fall back to the message
* and a status sniff so providers that throw plain `Error("... 503 ...")`
* strings still classify correctly.
*/
const toAttempt = (
modelId: string,
providerId: string,
err: unknown,
): ProviderAttempt => {
const e = err as {
status?: number;
statusCode?: number;
code?: string;
error?: {
code?: string;
type?: string;
message?: string;
error?: { type?: string; message?: string };
};
message?: string;
headers?: Headers | Record;
};
const message = e?.message ?? (typeof err === 'string' ? err : String(err));
let status = e?.status ?? e?.statusCode;
if (status === undefined) {
const m = message.match(/\b(4\d\d|5\d\d)\b/);
if (m) status = Number(m[1]);
}
// Anthropic nests its own error under `error.error`; OpenAI's is flat.
const upstreamType = e?.error?.error?.type ?? e?.error?.type;
const upstreamMessage = e?.error?.error?.message ?? e?.error?.message;
const headers = e?.headers;
const retryAfter =
typeof (headers as Headers)?.get === 'function'
? ((headers as Headers).get('retry-after') ?? undefined)
: (headers as Record | undefined)?.['retry-after'];
const timedOut = isUpstreamTimeoutError(err);
return {
model: modelId,
provider: providerId,
status,
code: e?.error?.code ?? e?.code,
error: sanitizeUpstreamMessage(message),
...(timedOut ? { timedOut: true } : {}),
...(!timedOut && isUpstreamConnectionError(err)
? { connectionFailed: true }
: {}),
...(upstreamType !== undefined ? { upstreamType } : {}),
...(upstreamMessage !== undefined
? {
upstreamMessage: sanitizeUpstreamMessage(
upstreamMessage,
1000,
),
}
: {}),
...(retryAfter !== undefined ? { retryAfter } : {}),
};
};
const isCreditExhaustion = (a: ProviderAttempt) =>
isUpstreamCreditExhaustion(a.status, a.code, a.error);
const isRateLimit = (a: ProviderAttempt) =>
a.status === 429 ||
/rate[\s_-]?limit|too many requests|quota/i.test(a.error);
const isModelAccessDenied = (a: ProviderAttempt) =>
a.status === 403 && a.code === 'model_not_found';
const isModelUnavailable = (a: ProviderAttempt) =>
a.status === 404 || isModelAccessDenied(a);
const isAuthFailure = (a: ProviderAttempt) =>
!isModelAccessDenied(a) &&
(a.status === 401 ||
a.status === 403 ||
/unauthorized|forbidden|invalid api key/i.test(a.error));
/**
* A new-api gateway's (Infron's) wrapper for an upstream that answered without
* a JSON error body. It mirrors the upstream's status, so the 4xx says nothing
* about the caller's request; a real vendor rejection carries its own message.
*/
const isOpaqueGatewayFailure = (a: ProviderAttempt) =>
/bad response status code \d+(?:,\s*body:|$)/i.test(a.error);
const isUpstream5xx = (a: ProviderAttempt) =>
(a.status !== undefined && a.status >= 500) ||
isOpaqueGatewayFailure(a) ||
/provider returned error|internal server error|service unavailable|bad gateway/i.test(
a.error,
);
/**
* Whether a failure indicts the route rather than the request.
*
* Outages, rate limits and bad credentials will hit the next caller too, so the
* route is worth marking. A 4xx the upstream returned on the request's own
* merits (malformed tools, oversized prompt) says nothing about the route and
* must not take it out of rotation for everyone else. Attempts with no status
* at all are transport failures — treat them as route problems. 404 (the model
* isn't served on this route) and 408 (upstream request timeout) are likewise
* about the route, not the caller's request.
*/
const isRouteLevelFailure = (a: ProviderAttempt) =>
a.status === undefined ||
isModelUnavailable(a) ||
a.status === 408 ||
isCreditExhaustion(a) ||
isRateLimit(a) ||
isAuthFailure(a) ||
isUpstream5xx(a);
/**
* A route-level failure that usually clears within a minute. Bad credentials
* and an exhausted account stay broken until someone fixes them.
*/
const isTransientFailure = (a: ProviderAttempt) =>
!isAuthFailure(a) &&
!isCreditExhaustion(a) &&
(isUpstream5xx(a) ||
isRateLimit(a) ||
a.status === 408 ||
a.timedOut === true ||
a.connectionFailed === true);
// One bucket can hold the same model id under several providers *and* several
// ids under one provider, so only the pair identifies an attempt.
const routeId = (provider: string, modelId: string) => `${provider}:${modelId}`;
/**
* The error surfaced for a request-level upstream failure (a 4xx that is the
* caller's own fault, e.g. a malformed tool or an oversized prompt) — thrown
* immediately, with no fallback attempt, since a different provider would only
* translate the same mistake into a different vendor's 400.
*/
const requestLevelError = (a: ProviderAttempt): HttpError =>
new HttpError(400, a.upstreamMessage || a.error, {
legacyCode: 'upstream_bad_request',
...(a.upstreamType ? { code: a.upstreamType } : {}),
fields: { attempts: [a], upstreamStatus: a.status },
});
const isOverloaded = (a: ProviderAttempt) =>
a.status === 529 || a.upstreamType === 'overloaded_error';
/**
* The HTTP status an in-band mid-stream error chunk reports — a stream
* populator failure never goes through `classifyAttempts` (there is no fallback
* once bytes have already reached the client), so it gets its own, narrower
* status pick from the same upstream signal.
*/
const streamErrorStatus = (a: ProviderAttempt): number => {
if (isOverloaded(a)) return 529;
if (a.upstreamType === 'rate_limit_error' || isRateLimit(a)) return 429;
if (a.upstreamType === 'timeout_error' || a.timedOut) return 504;
if (a.status !== undefined && a.status >= 400 && a.status < 500)
return a.status;
return 500;
};
/**
* Map an exhausted fallback chain to a single user-facing HttpError.
*
* Every caller except the Anthropic route sees main's statuses and codes here —
* a 529 (overloaded) or 404 (model not served) chain still reaches a 400, like
* any other upstream failure. The real status rides along in
* `fields.upstreamStatus`; `renderAnthropicError` (wireErrors.ts) is the only
* renderer that reads it back out, to give Claude Code the 529/404 it expects.
*
* Per-class rules (see also alarm gate in server.ts):
*
* - All credit-exhausted → 503 `upstream_credits_exhausted` (alerted)
* - All rate-limited → 429 `upstream_rate_limited` (alerted, unless every attempt
* was on a free model — see `allModelsFree`)
* - All auth failures, or any alongside 403 `model_not_found` → 500
* `upstream_auth_failed` (paged: our config)
* - All overloaded (529 / `overloaded_error`) → 400
* `upstream_provider_unavailable`, `upstreamStatus: 529` (no page)
* - All model-not-found (404, or 403 `model_not_found`) → 400
* `upstream_bad_request`, `upstreamStatus: 404` (no page)
* - All upstream 5xx or dropped connections → 400 `upstream_provider_unavailable`
* (no page)
* - All upstream 4xx (other) → 400 `upstream_bad_request` (no page)
* - All timed out → 504 `upstream_timeout` (no page)
* - Mixed → 400 `upstream_failed` (no page)
*/
const classifyAttempts = (
attempts: ProviderAttempt[],
{ allModelsFree = false } = {},
): HttpError => {
const fields = { attempts };
if (attempts.length === 0) {
return new HttpError(500, 'No providers attempted', {
legacyCode: 'internal_error',
fields,
});
}
if (attempts.every(isCreditExhaustion)) {
return new HttpError(503, 'AI provider out of credits', {
legacyCode: 'upstream_credits_exhausted',
fields,
});
}
if (attempts.every(isRateLimit)) {
const retryAfters = attempts
.map((a) => Number(a.retryAfter))
.filter(Number.isFinite);
return new HttpError(429, 'AI provider rate limit exceeded', {
legacyCode: 'upstream_rate_limited',
fields: retryAfters.length
? { ...fields, retryAfter: Math.max(...retryAfters) }
: fields,
// A free model getting throttled upstream is the deal we took
// when we picked it up for nothing: there's no billing at stake
// and nothing to act on, and the volume tracks traffic. The
// caller still gets the 429; we just don't record it.
noAlarm: allModelsFree,
});
}
if (
attempts.some(isAuthFailure) &&
attempts.every((a) => isAuthFailure(a) || isModelAccessDenied(a))
) {
return new HttpError(500, 'AI provider authentication failed', {
legacyCode: 'upstream_auth_failed',
fields,
});
}
if (attempts.every(isOverloaded)) {
return new HttpError(400, 'AI provider unavailable', {
legacyCode: 'upstream_provider_unavailable',
fields: { ...fields, upstreamStatus: 529 },
});
}
if (attempts.every(isModelUnavailable)) {
const accessDenied = attempts.some(isModelAccessDenied);
const message = accessDenied
? `Model not available: ${attempts[0].model}`
: attempts[0].error;
return new HttpError(400, message, {
legacyCode: 'upstream_bad_request',
fields: { ...fields, upstreamStatus: 404 },
// Our provider account lost access to the model; low alarm so
// someone notices.
...(accessDenied
? {
alarmSeverity: 'info' as const,
alarmChannel: 'ai_providers',
}
: {}),
});
}
if (
attempts.every((a) => isUpstream5xx(a) || a.connectionFailed === true)
) {
return new HttpError(400, 'AI provider unavailable', {
legacyCode: 'upstream_provider_unavailable',
fields,
});
}
if (
attempts.every(
(a) => a.status !== undefined && a.status >= 400 && a.status < 500,
)
) {
return new HttpError(400, attempts[0].error, {
legacyCode: 'upstream_bad_request',
fields,
});
}
if (attempts.every((a) => a.timedOut)) {
return new HttpError(504, 'AI provider timed out', {
legacyCode: 'upstream_timeout',
fields,
});
}
// Mixed failures where at least one attempt is clearly upstream
// (had an HTTP status from the SDK, lost its connection, or never got one
// in time) means "AI providers couldn't satisfy the request" — expose,
// don't page.
const isUpstreamSignal = (a: ProviderAttempt) =>
a.timedOut === true ||
a.connectionFailed === true ||
a.status !== undefined ||
isRateLimit(a) ||
isAuthFailure(a) ||
isUpstream5xx(a);
if (attempts.some(isUpstreamSignal)) {
return new HttpError(400, 'All AI providers failed', {
legacyCode: 'upstream_failed',
fields,
});
}
// Nothing identifiable as an upstream issue — treat as our bug
// and let the global alarm fire so we actually find out.
return new HttpError(500, 'All providers failed', {
legacyCode: 'internal_error',
fields,
});
};
// Claude's usage has always carried thinking_tokens. It's a subset of
// output_tokens, so it's added only after pricing, usd_cents, cost-calculated,
// and the funds cap all ran off the untouched usage.
const withClaudeThinkingTokens = (
usage: Record | undefined,
model: IChatModel,
details: UsageDetails | null | undefined,
): void => {
if (
usage &&
model.provider === 'claude' &&
usage.thinking_tokens === undefined
) {
usage.thinking_tokens = details?.reasoningTokens ?? 0;
}
};
/** What the model routes serve, built when the model map is swapped. */
interface ModelListing {
models: readonly IChatModel[];
/** Ids as `list()` reports them, sorted. */
names: readonly string[];
/** The listed rates hold from `validFrom` until `validUntil`. */
validFrom: number;
validUntil: number;
}
/** Never in force, so the first call builds the listing from the map. */
const UNBUILT_LISTING: ModelListing = {
models: [],
names: [],
validFrom: Infinity,
validUntil: -Infinity,
};
/**
* One entry per model id, by provider then id, at the rates listed at `now`. A
* bucket is reachable from each of its names, so it is walked once.
*/
const buildModelListing = (
modelIdMap: Record,
now = Date.now(),
): ModelListing => {
const at = new Date(now);
const seen = new Set();
const models: IChatModel[] = [];
let validFrom = -Infinity;
let validUntil = Infinity;
for (const bucket of new Set(Object.values(modelIdMap))) {
for (const model of bucket) {
if (seen.has(model.id)) continue;
seen.add(model.id);
for (const change of scheduledChangeTimes(model)) {
if (change <= now) validFrom = Math.max(validFrom, change);
else validUntil = Math.min(validUntil, change);
}
const costs = listedCosts(model, at);
models.push(costs === model.costs ? model : { ...model, costs });
}
}
models.sort((a, b) => {
if (a.provider === b.provider) return a.id.localeCompare(b.id);
return a.provider!.localeCompare(b.provider!);
});
return {
models: Object.freeze(models),
names: Object.freeze(models.map((m) => m.puterId || m.id).sort()),
validFrom,
validUntil,
};
};
/**
* Driver implementing the `puter-chat-completion` interface.
*
* Manages multiple upstream providers (Claude, OpenAI, …) and handles model
* resolution, provider routing, fallback on failure, and message normalisation.
* Each provider is a plain `IChatProvider` — the driver instantiates them from
* config on boot.
*
* Providers handle their own metering internally.
*/
export class ChatCompletionDriver extends PuterDriver {
readonly driverInterface = 'puter-chat-completion';
readonly driverName = 'ai-chat';
readonly isDefault = true;
// Shared AI policy — see `drivers/ai/shared/aiLimits.ts` for the tier table.
readonly rateLimit = AI_RATE_LIMIT;
readonly concurrent = AI_CONCURRENT;
#providers: Record = Object.create(null);
#modelIdMap: Record = Object.create(null);
/** Each bucket entry's own catalog entry, which keeps the vendor's casing. */
#catalogEntries = new WeakMap();
/** What the model routes serve; replaced with the map it is built from. */
#listing = UNBUILT_LISTING;
#modelMapRefresh: ReturnType | undefined;
/** The first model-map build, finished once every catalog is in. */
#modelMapBuilt: Promise = Promise.resolve();
/** Metering scoped to this driver. Lazy: services wire up after drivers. */
get #aiMetering(): AiMeteringService {
return withAiCostFactor(
this.services.metering,
this.clients.event,
this.driverName,
);
}
override onServerStart() {
this.#registerProviders();
// Not awaited: a gateway catalog can take its whole fetch timeout, and
// the drivers started after this one shouldn't wait for it.
// A failed build keeps the map it had; nothing awaits the refreshes, so
// a rejection left alone would be an unhandled one.
const keepMap = (error: unknown) =>
console.warn(
`[ai-chat] model map build failed: ${(error as Error)?.message ?? error}`,
);
this.#modelMapBuilt = this.#buildModelMap({
publishEachCatalog: true,
}).catch(keepMap);
// Gateway catalogs change under us; rebuild once they've expired.
this.#modelMapRefresh = setInterval(() => {
void this.#buildModelMap().catch(keepMap);
}, CATALOG_TTL_MS);
this.#modelMapRefresh.unref?.();
}
override onServerShutdown() {
clearInterval(this.#modelMapRefresh);
}
// -- Interface methods -------------------------------------------
async models(): Promise {
await this.#modelMapBuilt;
return this.#currentListing().models;
}
async list(): Promise {
await this.#modelMapBuilt;
return this.#currentListing().names;
}
/** A scheduled price change relists without waiting for a map rebuild. */
#currentListing(): ModelListing {
const now = Date.now();
if (now < this.#listing.validFrom || now >= this.#listing.validUntil) {
this.#listing = buildModelListing(this.#modelIdMap, now);
}
return this.#listing;
}
override getReportedCosts(): Record[] {
const out: Record[] = [];
const seen = new Set();
for (const bucket of Object.values(this.#modelIdMap)) {
for (const model of bucket) {
const key = `${model.provider}:${model.id}`;
if (seen.has(key)) continue;
seen.add(key);
for (const [costKey, raw] of Object.entries(
model.costs ? listedCosts(model) : {},
)) {
// `tokens` is a scale descriptor ("costs expressed per N
// tokens"), not a real per-operation cost — skip it.
if (costKey === 'tokens') continue;
if (typeof raw !== 'number' || !Number.isFinite(raw))
continue;
out.push({
usageType: `${model.provider}:${model.id}:${costKey}`,
ucentsPerUnit: raw,
unit: costKey.endsWith('_requests')
? 'request'
: 'token',
source: `driver:aiChat/${model.provider}`,
costs_currency: model.costs_currency,
});
}
}
}
return out;
}
async complete(args: ICompleteArguments): Promise {
if (
args.serviceSpeed !== undefined &&
!['standard', 'fast', 'ultrafast'].includes(args.serviceSpeed)
) {
throw new HttpError(
400,
'serviceSpeed must be standard, fast, or ultrafast',
{ legacyCode: 'invalid_service_speed' },
);
}
assertScalarOptions(args, SCALAR_OPTIONS);
const abortSignal = Context.get('abortSignal');
abortSignal?.throwIfAborted();
const actor = Context.get('actor');
if (!actor)
throw new HttpError(401, 'Authentication required', {
legacyCode: 'unauthorized',
});
// The caller hanging up stops nothing that has reached an upstream: it
// would bill the request anyway, so it runs to its usage report.
const upstream = new AbortController();
Context.set('upstreamSignal', upstream.signal);
// AI charges recorded in this request before the current attempt.
let priorCharges = requestAiCosts().length;
let intendedProvider = args.provider || '';
if (!args.model && !intendedProvider) {
intendedProvider = 'azure-openai'; // default provider
}
if (
!args.model &&
intendedProvider &&
this.#providers[intendedProvider]
) {
args.model = this.#providers[intendedProvider].getDefaultModel();
}
const initialModel = await this.#resolveLoadedModel(
args.model,
intendedProvider,
);
if (!initialModel) {
throw new HttpError(400, `Model not found: ${args.model}`, {
legacyCode: 'bad_request',
});
}
let model: IChatModel = initialModel;
// A pinned provider without a route for the model normally resolves
// to another vendor; with `fallback: false` that is the one thing the
// caller asked us not to do.
if (
args.fallback === false &&
intendedProvider &&
model.provider !== intendedProvider
) {
throw new HttpError(
400,
`Model ${args.model} is not served by provider ${intendedProvider}`,
{ legacyCode: 'bad_request' },
);
}
// A conversation the requested model already declined runs on the
// model that answered it.
const pinnedFallback = await this.#pinnedRefusalFallback(args, model);
if (pinnedFallback) model = pinnedFallback;
args.messages = normalizeMediaParts(normalize_messages(args.messages));
if (args.tools) {
normalize_tools_object(args.tools);
} else {
// `tools: enabled && list` leaves `false` here; it means no tools.
delete args.tools;
}
// A raw `/drivers/call` caller still sends the OpenAI wire form
// ('auto'/'none'/'required', {type:'function', function:{name}}) —
// normalize it once here so a provider downstream never spreads a
// bare string or an unrecognized shape into its request.
if (args.tool_choice !== undefined && !isToolChoice(args.tool_choice)) {
args.tool_choice = toolChoiceFromWire(args.tool_choice, 'chat');
}
// Before the credit hold and the round trip.
assertInputModalities(model, args.messages);
// Both estimated once, before any attempt: providers rewrite
// `args.messages` in place (tool_use blocks move out of `content`), so
// an estimate taken after a failed attempt would undercount the same
// prompt — and the gate writes each attempt's output cap into
// `args.max_tokens`, so the user's requested value has to be kept
// apart from what the previous attempt was capped to.
const promptTokenEstimate = estimatePromptTokens(args.messages ?? []);
// Direct driver calls reach here without the controller's coercion, so
// a non-finite max_tokens (e.g. NaN from the string "NaN") could still
// arrive. Drop it to undefined — a poisoned value would disable the
// output cap below and skip the credit hold entirely.
const requestedMaxTokens = Number.isFinite(args.max_tokens as number)
? args.max_tokens
: undefined;
const completionId = crypto
.randomUUID()
.replaceAll('-', '')
.slice(0, 25);
const validateEvent: EventMap['ai.prompt.validate'] = {
username: actor.user?.username || '',
actor,
completionId,
allow: true,
intended_service: intendedProvider,
parameters: args,
};
await this.clients.event.emitAndWait(
'ai.prompt.validate',
validateEvent,
{},
);
// Blocked prompts get rerouted to fake-chat. With `event.abuse` we
// pick the `abuse` model, which embeds `event.custom` (phone-home
// script for bots, etc.) in its response so the bot's renderer
// executes it. Without `abuse`, we silently route to the default
// `fake` model (lorem-ipsum response). Mirrors v1 AIChatService.
let blocked = false;
if (!validateEvent.allow) {
const fakeModelId = validateEvent.abuse ? 'abuse' : 'fake';
const fakeModel = this.#resolveModel(fakeModelId, 'fake-chat');
if (!fakeModel) {
throw new HttpError(403, 'Prompt blocked by policy', {
legacyCode: 'forbidden',
});
}
blocked = true;
model = fakeModel;
intendedProvider = 'fake-chat';
if (typeof validateEvent.custom !== 'undefined') {
args.custom = validateEvent.custom;
}
}
if (args.test_mode === true && !blocked) {
const fakeModel = this.#resolveModel('fake', 'fake-chat');
if (!fakeModel) {
throw new HttpError(500, 'Test chat provider unavailable', {
legacyCode: 'internal_error',
});
}
model = fakeModel;
}
const useFakeProvider = blocked || args.test_mode === true;
// The models a request the model declines is rerun on, in order.
const refusalChain = useFakeProvider
? []
: await this.#refusalFallbackChain(
args,
initialModel,
pinnedFallback,
);
// One per rerun, in order.
const handoffs: RefusalFallback[] = [];
// What the declined attempts were charged, and the usage they
// reported, under `declined_` keys.
let declinedCost = 0;
const declinedUsage: Record = {};
const declinedCosts: Record = {};
// Fake responses need no credit hold, including blocked prompts and
// test requests.
//
// The gate hands back a hold on what this attempt could cost, which
// stands in for its usage until the real numbers land. It is released
// on every way out of this method — including the streaming path,
// where "done" is the stream draining rather than this method
// returning.
let hold: CreditHold = NO_CREDIT_HOLD;
// The gate's estimate for the current attempt: the message estimate
// plus whatever its provider reads back as prompt beyond the messages.
let attemptPromptTokenEstimate = promptTokenEstimate;
// The current attempt's balance-bound output cap, if it had one.
let fundsCap: number | undefined;
// The cost factor the current attempt's charges are recorded at.
let costFactor = 1;
// The instant the current attempt is priced at, from its hold to its
// charge, so a rate change mid-request can't split the two.
let pricingTime = new Date();
// First attempt
const provider = this.#providers[model.provider!];
if (!provider) {
throw new HttpError(
500,
`No provider found for model ${model.id}`,
{ legacyCode: 'internal_error' },
);
}
const attempts: ProviderAttempt[] = [];
let res: IChatCompleteResult | undefined;
// Tracked across the chain so the classifier can tell a chain that
// only ever touched free models from one that cost the user something.
let allModelsFree = true;
// The Anthropic route sets this so its callers get the vendor's own
// 4xx instead of a fallback provider's translation of it; every other
// caller keeps falling back on a request-level failure, as main did.
const strict = Context.get('strictUpstreamErrors') === true;
// A failed route is remembered briefly so the next request skips it
// rather than paying its timeout again.
const recordFailure = (
failed: IChatModel,
err: unknown,
): ProviderAttempt => {
const attempt = toAttempt(failed.id, failed.provider!, err);
attempts.push(attempt);
if (!isFreeModel(failed)) allModelsFree = false;
// A request that outlived its deadline says nothing about the
// route's health.
if (
isRouteLevelFailure(attempt) &&
!(err instanceof UpstreamDeadlineError)
) {
markRouteUnhealthy(
failed.provider!,
failed.id,
isTransientFailure(attempt)
? TRANSIENT_UNHEALTHY_TTL_SEC
: UNHEALTHY_TTL_SEC,
);
}
return attempt;
};
let variantSpeed: ICompleteArguments['serviceSpeed'];
let creditGateError: unknown;
const runAttempt = async (
attemptProvider: IChatProvider,
baseModel: IChatModel,
) => {
let requestedSpeed = requestedServiceSpeed(
args,
baseModel.provider,
);
const offers =
requestedSpeed !== undefined && requestedSpeed !== 'standard'
? ((await attemptProvider.serviceSpeedModels?.(
baseModel,
)) ?? {})
: {};
for (;;) {
const selection = selectServiceSpeed(
baseModel,
{ ...args, serviceSpeed: requestedSpeed },
(id) => {
const variant = this.#resolveModel(
id,
baseModel.provider!,
);
return variant &&
variant.provider === baseModel.provider
? variant
: undefined;
},
offers,
);
const attemptModel = selection.model;
const requestArgs = {
...selection.args,
model: attemptModel.id,
provider: attemptModel.provider,
};
const catalogModel = this.#resolveModel(
attemptModel.id,
attemptModel.provider!,
);
const rawModel = this.#catalogEntries.get(
catalogModel ?? baseModel,
);
const snapshot = rawModel
? {
...rawModel,
costs: attemptModel.costs,
pricingOverrides: attemptModel.pricingOverrides,
serviceSpeedPricing: attemptModel.serviceSpeedPricing,
}
: attemptModel;
if (!useFakeProvider) {
try {
({
hold,
fundsCap,
costFactor,
promptTokenEstimate: attemptPromptTokenEstimate,
} = await this.#applyCreditGate(
actor,
attemptModel,
requestArgs,
{
promptTokenEstimate,
requestedMaxTokens,
pricingTime,
},
));
} catch (error) {
creditGateError = error;
throw error;
}
await this.#resolvePuterPaths(
attemptProvider,
requestArgs,
actor,
attemptModel,
);
}
abortSignal?.throwIfAborted();
try {
const result = await attemptProvider.complete(
requestArgs,
snapshot,
pricingTime,
);
model = attemptModel;
variantSpeed =
attemptModel.id !== baseModel.id
? selection.speed
: undefined;
if (
args.serviceSpeed !== undefined &&
'message' in result
) {
const messageResult = result as IChatMessageResult;
const details =
messageResult.usageDetails ??
usageDetailsFromUsage(messageResult.usage, model);
messageResult.usageDetails = {
...details,
serviceSpeed:
variantSpeed ??
details?.serviceSpeed ??
details?.speed ??
'standard',
};
}
return result;
} catch (error) {
await hold.release();
hold = NO_CREDIT_HOLD;
if (
args.serviceSpeed === undefined ||
selection.speed === 'standard' ||
!isServiceSpeedUnavailable(
error,
attemptModel.id !== baseModel.id,
)
)
throw error;
requestedSpeed = lowerServiceSpeed(selection.speed);
pricingTime = new Date();
}
}
};
try {
res = await runAttempt(provider, model);
} catch (e) {
// This attempt is over and cost whatever it cost; the next one
// takes a hold of its own.
await hold.release();
hold = NO_CREDIT_HOLD;
// A cancelled request carries no status, which would otherwise
// mark the route unhealthy and walk the fallback chain.
abortSignal?.throwIfAborted();
// A withheld completion was still a completion — charged, final,
// not a route failure worth another (billed) attempt elsewhere.
if (isModerationRefusal(e)) throw e;
// Our own request validation (policy rejection, bad tool shape)
// is never a route problem — no other provider would accept it
// either, so there is nothing a fallback would fix. An empty
// Responses-API output is the one exception: it falls back like
// any other route-level failure instead of being final.
if (
isHttpError(e) &&
e.statusCode < 500 &&
e.legacyCode !== 'bad_response'
)
throw e;
const first = recordFailure(model, e);
// A request-level upstream failure (malformed tools, oversized
// prompt) is the caller's request, not the route's fault — for
// the Anthropic route, retrying it on a different provider would
// translate the same mistake into a different vendor's 400, not
// fix it, so it's surfaced immediately. Other callers keep
// falling back, matching main.
if (strict && !isRouteLevelFailure(first))
throw requestLevelError(first);
// Fallback loop — the bucket holds every provider that serves this
// model, ranked by `compareModelPreference`, so each miss walks one
// step down that order.
const bucketKey = model.id;
const tried = new Set([routeId(model.provider!, model.id)]);
let lastError: Error | null = e as Error;
// With `fallback: false` the caller wants this route's answer or
// its error, not a bill for another provider's attempt.
const fallbackAllowed = args.fallback !== false;
while (
fallbackAllowed &&
lastError &&
attempts.length < MAX_ATTEMPTS
) {
const fallback = this.#findFallback(bucketKey, tried);
if (!fallback) break;
const fbProvider = this.#providers[fallback.provider!];
if (!fbProvider) break;
// Every attempt is a whole completion the account pays for, so
// each one goes through the full gate again rather than a
// token "do they have anything left" check: the balance may
// have been spent by a parallel request, and the fallback is
// a different model at a different price, whose output has to
// be capped against what is actually left.
// The previous attempt released its hold when it failed, so
// this one starts from nothing held.
pricingTime = new Date();
tried.add(routeId(fallback.provider!, fallback.id));
try {
res = await runAttempt(fbProvider, fallback);
lastError = null;
console.warn(
`[ai-chat] fallback served (${completionId}, ${first.provider}:${first.model} -> ${fallback.provider}:${fallback.id}, first ${first.status ?? 'none'}${first.upstreamType ? `/${first.upstreamType}` : ''})`,
);
} catch (fbErr) {
if (fbErr === creditGateError) throw fbErr;
await hold.release();
hold = NO_CREDIT_HOLD;
abortSignal?.throwIfAborted();
if (isModerationRefusal(fbErr)) throw fbErr;
const attempt = recordFailure(fallback, fbErr);
// A fallback's own 4xx is a translation gap between
// vendors, not the caller's fault — stop climbing the
// chain here, but still classify on whichever attempts
// were actually route-level. Non-strict callers keep
// falling back past a request-level failure, as main did.
if (
(isHttpError(fbErr) &&
fbErr.statusCode < 500 &&
fbErr.legacyCode !== 'bad_response') ||
(strict && !isRouteLevelFailure(attempt))
) {
console.warn(
`[ai-chat] fallback rejected request (${completionId}, ${fallback.provider}:${fallback.id}, ${attempt.status})`,
);
break;
}
lastError = fbErr as Error;
}
}
}
if (!res) {
await hold.release();
// The chain began on the caller's own request-level 4xx and never
// recovered — surface that vendor's error rather than a generic
// "all routes failed", which would otherwise swallow it once
// every route-level attempt in the chain gets filtered out below.
if (attempts[0] && !isRouteLevelFailure(attempts[0])) {
throw requestLevelError(attempts[0]);
}
const failure = classifyAttempts(
attempts.filter(isRouteLevelFailure),
{ allModelsFree },
);
// A deduped alarm shows only its latest occurrence, so each
// request's per-route failures are logged here, under its trace.
if (!failure.noAlarm) {
console.warn(
`[ai-chat] all routes failed (${completionId}, ${model.provider}:${model.id}, ${failure.legacyCode}): ${JSON.stringify(attempts)}`,
);
}
throw failure;
}
const username = actor.user?.username;
/** What this completion was charged, in µ¢, as the ledger holds it. */
const charged = () =>
declinedCost +
factoredTotal(requestAiCosts().slice(priorCharges), costFactor);
// A completion that used all of a balance-bound cap stopped because
// the account ran dry, so the caller is told to top up.
const ranOutOfFunds = (usage: Record | undefined) =>
fundsCap !== undefined &&
!!usage &&
trackedOutputTokens(usage, model) >= fundsCap;
/**
* Reruns the request `model` just declined on its next fallback model:
* a whole attempt of its own, through the credit gate. Undefined when
* no rerun ran, and then the refusal stands.
*/
const rerunDeclined = async (attempt: {
usage?: Record;
usageCosts?: Record | null;
stopDetails?: Record | null;
}): Promise => {
const fallback = abortSignal?.aborted
? undefined
: refusalChain.shift();
const fallbackProvider =
fallback && this.#providers[fallback.provider!];
if (!fallback || !fallbackProvider) {
refusalChain.length = 0;
return undefined;
}
const declinedModel = model;
const declinedAttempt = {
fundsCap,
costFactor,
pricingTime,
attemptPromptTokenEstimate,
};
const cost = charged();
const chargesSoFar = requestAiCosts().length;
// The declined attempt's usage is recorded, so its hold is done
// and the rerun's gate reads the balance without it.
await hold.release();
hold = NO_CREDIT_HOLD;
pricingTime = new Date();
let rerun: IChatCompleteResult;
try {
rerun = await runAttempt(fallbackProvider, fallback);
} catch (e) {
await hold.release();
hold = NO_CREDIT_HOLD;
({
fundsCap,
costFactor,
pricingTime,
attemptPromptTokenEstimate,
} = declinedAttempt);
refusalChain.length = 0;
console.warn(
`[ai-chat] refusal fallback failed (${completionId}, ${declinedModel.provider}:${declinedModel.id} -> ${fallback.id}): ${sanitizeUpstreamMessage(e instanceof Error ? e.message : String(e))}`,
);
return undefined;
}
declinedCost = cost;
priorCharges = chargesSoFar;
const category = attempt.stopDetails?.category;
handoffs.push({
type: 'fallback',
from: { model: declinedModel.id },
to: { model: fallback.id },
trigger: {
type: 'refusal',
category: typeof category === 'string' ? category : null,
},
});
for (const [key, amount] of Object.entries(attempt.usage ?? {})) {
if (!Number.isFinite(amount)) continue;
const reported = `declined_${key}`;
declinedUsage[reported] =
(declinedUsage[reported] ?? 0) + amount;
const keyCost = attempt.usageCosts?.[key];
if (Number.isFinite(keyCost)) {
declinedCosts[reported] =
(declinedCosts[reported] ?? 0) + keyCost!;
}
}
console.warn(
`[ai-chat] refusal fallback served (${completionId}, ${declinedModel.provider}:${declinedModel.id} -> ${fallback.id}, ${category ?? 'no category'})`,
);
return rerun;
};
/** Whether a refusal from `model` has a fallback model to rerun on. */
const canRerunDeclined = () =>
refusalChain.length > 0 &&
refusalChain[0].provider === model.provider;
// A declined request reruns on each fallback model in turn until one
// answers. A stream is rerun where it ends, below.
while (
canRerunDeclined() &&
'message' in res &&
(res as IChatMessageResult).stopReason === 'refusal'
) {
const declined = res as IChatMessageResult;
const rerun = await rerunDeclined({
usage: declined.usage,
usageCosts: declined.usageCosts,
stopDetails: declined.stopDetails,
});
if (!rerun) break;
res = rerun;
}
// Streaming result — create a PassThrough, kick off the provider's
// stream populator, and return a DriverStreamResult so the route
// handler pipes it to the HTTP response as chunked NDJSON.
if ('init_chat_stream' in res && res.init_chat_stream) {
const passthrough = new PassThrough();
const chatStream = new AIChatStream({
stream: passthrough,
streamToolInput: !!args.streamToolInput,
});
const init = res.init_chat_stream;
// One per attempt that streamed.
const cleanups = [res.finally_fn];
// A caller who leaves stops getting output, but the upstream keeps
// going until it reports usage, with as long to finish as a
// non-streaming completion gets.
let detachedLimit: ReturnType | undefined;
const detachStream = () => {
chatStream.detach();
detachedLimit = setTimeout(
() => upstream.abort(),
SDK_TIMEOUT_MS,
);
detachedLimit.unref?.();
};
if (abortSignal?.aborted) detachStream();
else abortSignal?.addEventListener('abort', detachStream);
// Intercept `chatStream.end(usage)` to fire complete + cost events
// (mirrors the non-streaming branch). Clone usage so providers that
// meter after this call (e.g. Claude) don't pick up `usd_cents`.
const originalEnd = chatStream.end.bind(chatStream);
// Set when an attempt was declined before any output: nothing has
// been written, so a rerun can still answer on this stream.
let declinedEnd: { usage?: Record } | undefined;
chatStream.end = (reported?: Record) => {
if (
canRerunDeclined() &&
chatStream.stop?.reason === 'refusal' &&
!chatStream.hasOutput &&
!chatStream.detached
) {
declinedEnd = { usage: reported };
return;
}
// Declined attempts report beside the attempt that answered,
// unless that one reported nothing and is charged an estimate.
const afterRerun =
handoffs.length > 0 &&
!!reported &&
Object.values(reported).some(Number.isFinite);
const usage = afterRerun
? { ...reported, ...declinedUsage }
: reported;
// Read before `originalEnd` writes the wire line — the
// provider sets it (if at all) any time before `end()`.
const usageCosts = afterRerun
? { ...chatStream.usageCosts, ...declinedCosts }
: (chatStream.usageCosts ?? undefined);
const enrichedUsage = usage ? { ...usage } : usage;
if (enrichedUsage) {
this.#injectUsdCents(
enrichedUsage,
model,
usageCosts,
pricingTime,
);
// An empty report recorded nothing; the stream is charged
// an estimate once it ends instead.
if (Object.values(usage!).some(Number.isFinite)) {
enrichedUsage.cost = charged();
}
}
// A completion nobody received isn't announced, but it still
// gets its cost row.
if (!chatStream.detached) {
this.clients.event.emit(
'ai.prompt.complete',
{
username: username!,
completionId,
intended_service: intendedProvider,
parameters: args,
result: { usage: enrichedUsage, stream: true },
model_used: model.id,
service_used: model.provider!,
},
{},
);
}
if (usage) {
this.#emitCostCalculated({
completionId,
username,
usage,
model,
intendedProvider,
usageCosts,
pricingTime,
});
}
// Fill in sensible defaults when the provider reported no
// stop/usage-detail shape of its own, so every stream ends
// with the same fields regardless of which provider served
// it.
if (!chatStream.stop) {
chatStream.setStop({
reason: ranOutOfFunds(usage)
? 'max_tokens'
: 'end_turn',
});
}
if (usage && !chatStream.usageDetails) {
chatStream.setUsageDetails(
usageDetailsFromUsage(usage, model),
);
}
if (handoffs.length > 0 && chatStream.usageDetails) {
chatStream.setUsageDetails({
...chatStream.usageDetails,
fallbackModel: handoffs.at(-1)!.to.model,
});
}
if (
args.serviceSpeed !== undefined &&
chatStream.usageDetails
) {
const details = chatStream.usageDetails;
chatStream.setUsageDetails({
...details,
serviceSpeed:
variantSpeed ??
details.serviceSpeed ??
details.speed ??
'standard',
});
}
withClaudeThinkingTokens(
enrichedUsage,
model,
chatStream.usageDetails,
);
return originalEnd(
enrichedUsage!,
ranOutOfFunds(usage)
? { metadata: { usage_limited: true } }
: undefined,
);
};
// The hold lives for the whole stream, which can outlast its TTL —
// keep pushing the deadline out until the pump is done.
const renewHold = setInterval(() => {
void hold.extend?.();
}, HOLD_RENEW_INTERVAL_MS);
renewHold.unref?.();
// The upstream runs on after a caller hangs up, so the request
// keeps its concurrency slot until the upstream is done, not until
// the cleanup after it.
let upstreamDone!: () => void;
const upstreamRunning = new Promise((resolve) => {
upstreamDone = resolve;
});
Context.get('keepConcurrencySlot')?.(upstreamRunning);
// The stream writes happen async while the response is piped to
// the client.
(async () => {
try {
await init({ chatStream });
while (declinedEnd) {
const { usage } = declinedEnd;
declinedEnd = undefined;
const rerun = await rerunDeclined({
usage,
usageCosts: chatStream.usageCosts,
stopDetails: chatStream.stop?.details,
});
if (
!rerun ||
!('init_chat_stream' in rerun) ||
!rerun.init_chat_stream
) {
// No rerun, so the refusal is the response.
refusalChain.length = 0;
chatStream.end(usage!);
break;
}
cleanups.push(rerun.finally_fn);
chatStream.refusalFallback(handoffs.at(-1)!);
chatStream.restart();
await rerun.init_chat_stream({ chatStream });
}
if (!passthrough.writableEnded) {
throw new Error('Stream ended before completion');
}
} catch (e) {
if (!chatStream.detached) {
const attempt = toAttempt(model.id, model.provider!, e);
chatStream.write(
`${JSON.stringify({
type: 'error',
message: sanitizeUpstreamMessage(
e instanceof Error ? e.message : String(e),
),
...(attempt.upstreamType
? { code: attempt.upstreamType }
: {}),
status: streamErrorStatus(attempt),
})}\n`,
);
}
passthrough.end();
} finally {
upstreamDone();
clearInterval(renewHold);
clearTimeout(detachedLimit);
abortSignal?.removeEventListener('abort', detachStream);
// Providers report usage the moment they meter it (see
// `AIChatStream.reportUsage`); a stream that never got
// there was never charged for.
try {
if (!blocked && !chatStream.reportedUsage) {
this.#meterUnreportedStream({
actor,
chatStream,
model,
promptTokenEstimate: attemptPromptTokenEstimate,
completionId,
username,
intendedProvider,
pricingTime,
});
}
} finally {
try {
await hold.release();
} finally {
await Promise.all(
cleanups.map((cleanup) => cleanup?.()),
);
}
}
}
})().catch((error) => {
console.warn(
'Chat stream cleanup failed:',
sanitizeUpstreamMessage(
error instanceof Error ? error.message : String(error),
),
);
});
const streamResult: DriverStreamResult = {
dataType: 'stream',
content_type: 'application/x-ndjson',
chunked: true,
stream: passthrough,
};
return streamResult as unknown as IChatCompleteResult;
}
// The provider recorded this completion's usage before returning it,
// so the hold has served its purpose.
await hold.release();
// Declined attempts report beside the attempt that answered.
if (handoffs.length > 0 && 'message' in res) {
const answered = res as IChatMessageResult;
answered.refusalFallbacks = handoffs;
answered.usageDetails = {
...(answered.usageDetails ??
usageDetailsFromUsage(answered.usage, model)),
fallbackModel: handoffs.at(-1)!.to.model,
};
answered.usage = { ...answered.usage, ...declinedUsage };
answered.usageCosts = { ...answered.usageCosts, ...declinedCosts };
}
// -- Post-completion audit event ------------------------------
// Only for non-streaming results (streaming emits from the
// `chatStream.end` wrapper above). Extensions like prompt_block /
// prodMeteringAndBilling listen for this to log completions.
this.clients.event.emit(
'ai.prompt.complete',
{
username: username!,
completionId,
intended_service: intendedProvider,
parameters: args,
result: res,
model_used: model.id,
service_used: model.provider!,
},
{},
);
const usageCosts = (res as IChatMessageResult).usageCosts;
if ('usage' in res && res.usage) {
this.#injectUsdCents(res.usage, model, usageCosts, pricingTime);
this.#emitCostCalculated({
completionId,
username,
usage: res.usage,
model,
intendedProvider,
usageCosts,
pricingTime,
});
res.usage.cost = charged();
}
Context.set('driverMetadata', {
service_used: model.provider,
providerUsed: model.id,
...(ranOutOfFunds(
'usage' in res
? (res.usage as Record)
: undefined,
)
? { usage_limited: true }
: {}),
});
if ('usage' in res) {
withClaudeThinkingTokens(
res.usage,
model,
(res as IChatMessageResult).usageDetails,
);
}
// Response-format precedence: an explicit per-call `normalize` wins in
// both directions; the legacy `response.normalize` (internal
// block-format normalization) applies only when the new flag is
// absent; otherwise the release-date cutoff decides. The coercer is
// idempotent, so already-OpenAI-shaped results (most providers, or a
// Claude model served through a reseller fallback) pass through.
if ('message' in res && res.message) {
// `'message' in res` doesn't narrow the result union for TS.
const messageRes = res as IChatMessageResult;
// Fill in a stop reason and usage breakdown when the provider
// didn't set its own, so every non-stream result carries the
// same shape regardless of which provider served it.
if (messageRes.stopReason === undefined) {
const nativeStop = (
messageRes.message as Record | undefined
)?.stop_reason;
messageRes.stopReason =
typeof nativeStop === 'string' && nativeStop !== ''
? nativeStop
: fromFinishReason(messageRes.finish_reason);
}
if (messageRes.usageDetails === undefined && messageRes.usage) {
messageRes.usageDetails = usageDetailsFromUsage(
messageRes.usage,
model,
);
}
// Internal-only; never reaches the caller.
delete messageRes.usageCosts;
// A fallback model's answer keeps the requested model's format.
const servedByFallback =
handoffs.length > 0 || (!!pinnedFallback && !useFakeProvider);
if (
shouldPresentAsOpenAI(
args,
(servedByFallback ? initialModel : model).release_date,
)
) {
return {
...normalizeResultToOpenAI(messageRes),
normalized: true,
via_ai_chat_service: true,
};
}
// The legacy flag normalizes the other way — to Anthropic blocks —
// and only when the new flag is absent. It deliberately does NOT
// set `normalized`: that field is the caller's signal that the
// message is in the OpenAI shape, and this branch produces the
// opposite. Stamping both made the flag mean "some normalization
// happened", which no consumer can act on.
if (args.normalize !== false && args.response?.normalize) {
return {
...messageRes,
message: normalize_single_message(messageRes.message),
via_ai_chat_service: true,
};
}
}
// Streaming results returned above; only message results reach here.
return { ...(res as IChatMessageResult), via_ai_chat_service: true };
}
/**
* Exact prompt token count for a request that will never be sent — no
* credit gate, no metering, no fallback. Resolves the model and normalizes
* messages/tools the same way `complete()` does, then prefers the
* provider's own counter (Claude's `count_tokens`) over the driver's
* estimate.
*/
async [COUNT_TOKENS](
args: ICompleteArguments,
): Promise<{ input_tokens: number }> {
assertScalarOptions(args, SCALAR_OPTIONS);
let intendedProvider = args.provider || '';
if (!args.model && !intendedProvider) {
intendedProvider = 'azure-openai';
}
if (
!args.model &&
intendedProvider &&
this.#providers[intendedProvider]
) {
args.model = this.#providers[intendedProvider].getDefaultModel();
}
const model = await this.#resolveLoadedModel(
args.model,
intendedProvider,
);
if (!model) {
throw new HttpError(400, `Model not found: ${args.model}`, {
legacyCode: 'bad_request',
});
}
args.messages = normalizeMediaParts(normalize_messages(args.messages));
if (args.tools) {
normalize_tools_object(args.tools);
} else {
// `tools: enabled && list` leaves `false` here; it means no tools.
delete args.tools;
}
const provider = this.#providers[model.provider!];
if (!provider) {
throw new HttpError(
500,
`No provider found for model ${model.id}`,
{ legacyCode: 'internal_error' },
);
}
const requestArgs: ICompleteArguments = {
...args,
model: model.id,
provider: model.provider,
};
if (provider.countTokens) {
return { input_tokens: await provider.countTokens(requestArgs) };
}
return {
input_tokens:
estimatePromptTokens(requestArgs.messages ?? []) +
estimateToolTokens(requestArgs.tools),
};
}
/**
* The credit and subscription gate for one upstream attempt.
*
* Runs before every attempt, not once per request: each attempt is a whole
* completion the account pays for, at that model's prices, against whatever
* balance is left by the time it starts.
*
* Rejects when the account can't afford the approximate input cost, keeps
* subscriber-only models gated, and tightens `args.max_tokens` so the
* output this attempt can produce is bounded by the remaining balance. A
* balance short of either is first offered to top-up listeners.
*
* Returns a hold on what the attempt can cost at worst, so requests this
* account is running in parallel see the spend before it is recorded. The
* caller releases it once the attempt is done. `fundsCap` is set when the
* account's balance, not the request or the model, decided the output cap —
* a completion that uses all of it has run the account dry.
*/
async #applyCreditGate(
actor: Actor,
model: IChatModel,
args: ICompleteArguments,
estimates: {
/**
* Prompt tokens, estimated once before any attempt — counts
* attachments as well as text, and predates any in-place message
* rewriting a previous attempt's provider did.
*/
promptTokenEstimate: number;
/**
* What the user asked for, kept apart from `args.max_tokens`, which
* carries the previous attempt's cap: a cheap fallback must not
* inherit the ceiling computed at an expensive model's price.
*/
requestedMaxTokens: number | undefined;
/** The instant this attempt is priced at. */
pricingTime: Date;
},
attempt = 1,
staleAttempt = 1,
): Promise<{
hold: CreditHold;
fundsCap?: number;
costFactor: number;
/** The prompt estimate this attempt was priced on. */
promptTokenEstimate: number;
}> {
const metering = this.services.metering;
const { requestedMaxTokens, pricingTime } = estimates;
let { promptTokenEstimate } = estimates;
// Providers reserve tool calls using the same caps they send upstream.
const pricing =
this.#providers[model.provider!]?.requestPricing?.(args, model, {
promptTokenEstimate,
}) ?? {};
promptTokenEstimate += pricing.additionalPromptTokens ?? 0;
const { inputKey: defaultInputKey, outputKey: defaultOutputKey } =
costKeys(model);
const inputKey = pricing.inputKey ?? defaultInputKey;
const outputKey = pricing.outputKey ?? defaultOutputKey;
// A prompt estimated past a long-context threshold pays the raised
// rates on input and output alike.
const multipliers = longContextMultipliers(model, promptTokenEstimate);
// Recorded costs pass through the AI cost factor; the gate prices at
// the same rate or it under-reserves on every request.
const costFactor = await this.#aiMetering.costFactor(
actor,
this.#meteringModelKey(model),
);
const requestCosts = costsForRequest(
model,
promptTokenEstimate,
pricingTime,
);
// `|| 0` also catches NaN from a malformed cost table.
const inputTokenCost =
(Number(requestCosts[inputKey] ?? 0) || 0) *
multipliers.input *
costFactor;
const outputTokenCost =
(Number(requestCosts[outputKey] ?? 0) || 0) *
multipliers.output *
costFactor;
const approximateInputCost = promptTokenEstimate * inputTokenCost;
const requestFee = catalogPrice(requestCosts.request) ?? 0;
const extras = ((pricing.extraCost ?? 0) + requestFee) * costFactor;
const minimumCredits = Number(model.minimumCredits || 1);
const needed = Math.max(approximateInputCost + extras, minimumCredits);
// What the request would get with money no object.
const limit = Math.min(
requestedMaxTokens ?? Number.POSITIVE_INFINITY,
outputCeiling(model, promptTokenEstimate),
positiveOrInfinity(pricing.maxTokens),
);
// The prompt plus output run to `limit`. A balance short of it would
// cut the reply off, which the caller is told the same way as a refusal.
const fullCost =
outputTokenCost > 0 && Number.isFinite(limit)
? Math.max(
needed,
approximateInputCost + extras + limit * outputTokenCost,
)
: needed;
// One read of the balance and its holds serves the whole gate: the
// affordability check here and the output cap below, net of holds,
// and the balance alone, which tells spent from committed to requests
// that are still running.
let headroom = await metering.getUsageHeadroom(actor, {
versioned: true,
});
// Short of funds rather than of what running requests hold: a top-up
// made at this moment is worth reading the balance once more.
if (
headroom.balance < fullCost &&
(await creditsRefilled(this.clients.event, actor))
) {
headroom = await metering.getUsageHeadroom(actor, {
versioned: true,
});
}
const { balance, held } = headroom;
const remainingCredits = Math.max(0, balance - held);
if (remainingCredits < needed) {
throw fundsRefusal(balance >= needed);
}
if (model.subscriberOnly) {
const subscription = await metering.getActorSubscription(actor);
if (isFreeSubscription(subscription.id)) {
throw new HttpError(
403,
`The model ${model.id} is only available to subscribers. Please subscribe to access this model.`,
{ legacyCode: 'permission_denied' },
);
}
}
let fundsCap: number | undefined;
if (outputTokenCost > 0) {
const affordableOutputTokens = (credits: number): number =>
(credits - approximateInputCost - extras) / outputTokenCost;
const cap = Math.floor(
Math.min(limit, affordableOutputTokens(remainingCredits)),
);
// `cap` is the credit-bounded ceiling on output tokens. When it
// drops below 1 the user can't afford even a single output token,
// so reject the request. Crucially we must NOT leave `max_tokens`
// unset here: an undefined max_tokens lets the provider run to the
// model's full output limit (e.g. 128k for Claude), billing far
// past the user's remaining balance.
// `!(cap >= 1)` rather than `cap < 1` so a non-finite cap is caught
// too: a NaN requested max_tokens poisons the Math.min above, and
// `NaN < 1` is false — letting an uncapped request through.
if (!(cap >= 1)) {
// Holds only explain a shortfall in funds, not a request that
// asked for less than a token.
const fundsShort = !(
affordableOutputTokens(remainingCredits) >= 1
);
throw fundsRefusal(
fundsShort && affordableOutputTokens(balance) >= 1,
);
}
args.max_tokens = cap;
// Only the balance itself bounding output counts as running dry;
// a cap that holds shrank further is a busy account.
const balanceBound = affordableOutputTokens(balance);
if (balanceBound < limit && cap >= Math.floor(balanceBound)) {
fundsCap = cap;
}
} else {
// No output price, nothing to bound — but a previous attempt may
// have written its cap here; give this one the user's own value.
args.max_tokens = requestedMaxTokens;
}
// What this attempt can cost at worst: the prompt, plus output run to
// the cap just set. Capped output is what makes the number finite —
// for a model with no output price the output term is zero and the
// prompt estimate stands alone. Already factored, so it's held through
// `reserveCredits`, which doesn't scale a second time, and released
// only once this request's usage has been recorded.
const worstCaseCost =
approximateInputCost +
extras +
(args.max_tokens ?? 0) * outputTokenCost;
// Held only if it still fits the headroom the cap was sized from.
// Requests this account started at the same moment read the same
// headroom; the ones that lose size themselves again from what is left.
const hold = await this.#aiMetering.reserveCredits(
actor,
Math.max(worstCaseCost, minimumCredits),
{ within: headroom },
);
if (hold === 'stale') {
// The balance changed since it was read, which says nothing about
// what is held: counted apart from lost headroom, and read again
// after a short wait.
if (staleAttempt >= CREDIT_GATE_STALE_ATTEMPTS) {
throw new HttpError(
429,
'The account balance is changing too quickly to admit this request. Retry shortly.',
{ legacyCode: 'too_many_requests' },
);
}
await new Promise((resolve) =>
setTimeout(
resolve,
Math.random() * CREDIT_GATE_STALE_BACKOFF_MS * staleAttempt,
),
);
return this.#applyCreditGate(
actor,
model,
args,
estimates,
attempt,
staleAttempt + 1,
);
}
if (!hold) {
if (attempt >= CREDIT_GATE_ATTEMPTS) throw fundsRefusal(true);
return this.#applyCreditGate(
actor,
model,
args,
estimates,
attempt + 1,
staleAttempt,
);
}
return { hold, fundsCap, costFactor, promptTokenEstimate };
}
/** The key `model`'s usage is recorded and cost-factored under. */
#meteringModelKey(model: IChatModel): string {
return (
this.#providers[model.provider!]?.meteringModelKey?.(model.id) ??
`${model.provider}:${model.id}`
);
}
/**
* Charge a stream that produced output but never reported usage.
*
* Providers meter from the usage they hand to `chatStream.end`, at the very
* end of the stream — so anything that stops the stream short of that point
* (an upstream error mid-response, a malformed tool-call payload, a
* provider that never sends a usage chunk) leaves a completion the upstream
* has already billed us for and the account has paid nothing for. This is
* the backstop: what the stream actually emitted, priced off the model's
* own cost table.
*
* Only when there was output. A stream that failed before producing
* anything cost the user nothing, and charging an estimated prompt to
* someone whose request we failed to serve is worse than the leak.
*
* Recorded under `estimated_*` usage keys so the numbers stay separable
* from provider-reported ones in the usage breakdown.
*/
#meterUnreportedStream(params: {
actor: Actor;
chatStream: AIChatStream;
model: IChatModel;
/** Estimated before any provider rewrote `args.messages` in place. */
promptTokenEstimate: number;
completionId: string;
username?: string;
intendedProvider: string;
pricingTime: Date;
}): void {
const {
actor,
chatStream,
model,
promptTokenEstimate,
completionId,
username,
intendedProvider,
pricingTime,
} = params;
const outputTokens = estimateOutputTokens(chatStream.outputChars ?? 0);
if (outputTokens <= 0) return;
const { inputKey, outputKey } = costKeys(model);
const inputTokens = promptTokenEstimate;
const usage = {
[inputKey]: inputTokens,
[outputKey]: outputTokens,
};
const cost = usageCost(usage, model, undefined, pricingTime);
this.#aiMetering.utilRecordUsageObject(
{
[`estimated_${inputKey}`]: inputTokens,
[`estimated_${outputKey}`]: outputTokens,
},
actor,
this.#meteringModelKey(model),
{
// Undefined when the model has no cost table: the entry is
// recorded unpriced rather than free.
[`estimated_${inputKey}`]: cost?.inputMicroCents,
[`estimated_${outputKey}`]: cost?.outputMicroCents,
},
);
console.warn(
`[ai-chat] stream ended without usage; charged an estimate (${completionId}, ${model.provider}:${model.id}, ~${inputTokens} in / ~${outputTokens} out)`,
);
this.#emitCostCalculated({
completionId,
username,
usage,
model,
intendedProvider,
pricingTime,
});
}
// Add `usd_cents` to the usage object. Skips if the provider already
// set an authoritative value (e.g. OpenRouter's `usage.cost`).
// Sets `null` when cost data is unavailable for the model.
#injectUsdCents(
usage: Record,
model: IChatModel,
usageCosts: Record | undefined,
pricingTime: Date,
): void {
if (
typeof usage.usd_cents === 'number' &&
Number.isFinite(usage.usd_cents)
) {
return;
}
const cost = usageCost(usage, model, usageCosts, pricingTime);
if (!cost) {
(usage as Record).usd_cents = null;
return;
}
usage.usd_cents =
(cost.inputMicroCents + cost.outputMicroCents) / 1_000_000;
}
// Compute per-token cost in microcents using the model's cost map,
// then emit `ai.prompt.cost-calculated` for listeners that persist
// billing/abuse rows keyed on the completion id.
#emitCostCalculated(params: {
completionId: string;
username?: string;
usage: Record;
model: IChatModel;
intendedProvider: string;
usageCosts?: Record;
pricingTime: Date;
}) {
const {
completionId,
username,
usage,
model,
intendedProvider,
usageCosts,
pricingTime,
} = params;
const cost = usageCost(usage, model, usageCosts, pricingTime);
const { inputKey, outputKey } = costKeys(model);
// The vendor reports usage, and pricing skips a count that is not a
// number; so does this.
const count = (value: unknown) =>
typeof value === 'number' && Number.isFinite(value) ? value : 0;
const inputTokens = cost
? count(
usage[inputKey] ?? usage.prompt_tokens ?? usage.input_tokens,
)
: 0;
const outputTokens = cost
? count(
usage[outputKey] ??
usage.completion_tokens ??
usage.output_tokens,
)
: 0;
const inputMicroCents = cost?.inputMicroCents ?? 0;
const outputMicroCents = cost?.outputMicroCents ?? 0;
this.clients.event.emit(
'ai.prompt.cost-calculated',
{
completionId,
username: username!,
usage,
input_tokens: inputTokens,
output_tokens: outputTokens,
input_ucents: inputMicroCents,
output_ucents: outputMicroCents,
total_ucents: inputMicroCents + outputMicroCents,
costs_currency: model.costs_currency,
model_used: model.id,
service_used: model.provider!,
intended_service: intendedProvider,
model_details: {
id: model.id,
provider: model.provider!,
input_cost_key: inputKey,
output_cost_key: outputKey,
costs: model.costs,
costs_currency: model.costs_currency,
},
},
{},
);
}
// -- Provider registration ---------------------------------------
#registerProviders() {
const providers = this.config.providers ?? {};
const metering = this.#aiMetering;
const readKey = (cfg: Record | undefined) =>
(cfg?.apiKey as string | undefined) ??
(cfg?.secret_key as string | undefined);
const claudeKey = readKey(providers['claude']);
if (claudeKey) {
this.#providers['claude'] = new ClaudeProvider(
metering,
{
fsEntry: this.stores.fsEntry,
s3Object: this.stores.s3Object,
},
this.services.fs,
{ apiKey: claudeKey },
);
}
// Azure AI Foundry (OpenAI + xAI Grok). Its costs mirror the vendors'
// and it is preferred for us; `PREFERRED_PROVIDERS` in modelRouting
// puts it ahead of them in the per-model bucket.
const azureOpenai = providers['azure-openai'];
const azureOpenaiKey = readKey(azureOpenai);
const azureOpenaiURL = azureOpenai?.apiURL as string | undefined;
let azureResponses: AzureResponsesProvider | undefined;
if (azureOpenaiKey && azureOpenaiURL) {
const azureStores = {
fsEntry: this.stores.fsEntry,
s3Object: this.stores.s3Object,
};
const azureConfig = {
apiKey: azureOpenaiKey,
apiURL: azureOpenaiURL,
};
const azureCompletions = new AzureChatProvider(
metering,
azureStores,
this.services.fs,
azureConfig,
);
// Codex / Responses-API-only models can't use Chat Completions, so
// they route through a sibling Responses provider pointed at the
// same Azure endpoint. web_search (also Responses-only) delegates
// here too.
azureResponses = new AzureResponsesProvider(
metering,
azureStores,
this.services.fs,
azureConfig,
);
azureCompletions.setResponsesProvider(azureResponses);
this.#providers['azure-openai'] = azureCompletions;
this.#providers['azure-openai-responses'] = azureResponses;
}
const openaiKey = readKey(providers['openai-completion']);
if (openaiKey) {
const openaiCompletions = new OpenAiChatProvider(
{ apiKey: openaiKey },
metering,
);
const openaiResponses = new OpenAiResponsesChatProvider(
{ apiKey: openaiKey },
metering,
);
// web_search is Responses-only; let the Completions path delegate
// to its sibling when users request it.
openaiCompletions.setResponsesProvider(openaiResponses);
// Azure serves no moderation endpoint; its routes check here.
azureResponses?.setModerationProvider(openaiCompletions);
this.#providers['openai-completion'] = openaiCompletions;
this.#providers['openai-responses'] = openaiResponses;
}
for (const { name, configKey = name, Class } of KEYED_PROVIDERS) {
const config = providers[configKey];
const apiKey = readKey(config);
if (!apiKey) continue;
this.#providers[name] = new Class(
{
apiKey,
apiBaseUrl: config?.apiBaseUrl as string | undefined,
},
metering,
);
}
// Ollama — auto-discover local instance unless `enabled: false`.
const ollama = providers['ollama'];
if (ollama?.enabled !== false) {
this.#providers['ollama'] = new OllamaChatProvider(
{
apiBaseUrl: ollama?.apiBaseUrl,
},
metering,
);
}
// Fake provider — always available for testing
this.#providers['fake-chat'] = new FakeChatProvider();
}
// -- Model map ---------------------------------------------------
/**
* Load every provider's catalog and swap in the map built from them. A
* provider whose catalog fails is left out rather than failing the build.
*
* A refresh swaps once, so the previous map serves until every catalog is
* in. The first build also publishes as each catalog lands, so models from
* catalogs that need no fetch are served while the gateways' still load.
*/
async #buildModelMap({ publishEachCatalog = false } = {}) {
const names = Object.keys(this.#providers);
const catalogs = new Array(names.length);
await Promise.all(
names.map(async (name, i) => {
try {
catalogs[i] = await this.#providers[name].models();
} catch (e) {
console.warn(
`[ai-chat] ${name} catalog unavailable: ${(e as Error)?.message ?? e}`,
);
return;
}
if (publishEachCatalog) {
this.#publish(this.#assembleModelMap(names, catalogs));
}
}),
);
this.#publish(this.#assembleModelMap(names, catalogs));
}
/** The map and its listing change together, so they never disagree. */
#publish(modelIdMap: Record) {
this.#modelIdMap = modelIdMap;
try {
this.#listing = buildModelListing(modelIdMap);
} catch {
// Routing keeps the new map; each listing call reports the error.
this.#listing = UNBUILT_LISTING;
}
}
/**
* Group the loaded catalogs into per-model buckets, in provider
* registration order.
*
* A bucket is the set of routes to one model: the vendor we integrate with
* directly plus every reseller carrying it. They are deliberately _not_
* deduplicated — the duplicates are what the fallback loop walks when a
* route fails. `compareModelPreference` decides who serves first, so a
* reseller only takes traffic once the vendor has actually failed.
*
* Entries join a bucket by identity key (see `isIdentityKey`); display
* names remain addressable but never merge two providers' entries.
*/
#assembleModelMap(
names: string[],
catalogs: (IChatModel[] | undefined)[],
): Record {
const modelIdMap: Record = Object.create(null);
names.forEach((providerName, i) => {
const catalog = catalogs[i];
if (!catalog) return;
for (const entry of catalog) {
// A gateway's list can carry an entry with no usable id; one
// such entry must not cost every provider its place in the map.
if (
typeof entry?.id !== 'string' ||
(entry.puterId !== undefined &&
typeof entry.puterId !== 'string')
) {
continue;
}
// Catalogs are module-level constants shared by every driver
// instance, so they are read and never written: normalizing
// the id or appending puterId in place would accumulate across
// instantiations. The bucket gets its own copy instead.
// Keep upstream ids for provider calls and publish a qualified
// routing name even when a catalog omits its vendor namespace.
const publicId = entry.puterId || entry.id;
// A colon after the first slash belongs to the model name, as
// in `vendor/model:free`, and names no service.
const serviceSeparator = publicId
.split('/', 1)[0]!
.indexOf(':');
const service =
serviceSeparator < 0
? providerName
: publicId.slice(0, serviceSeparator);
const modelPath =
serviceSeparator < 0
? publicId
: publicId.slice(serviceSeparator + 1);
const puterId =
providerName === 'fake-chat'
? entry.puterId
: `${service}:${modelPath.includes('/') ? modelPath : `${service}/${modelPath}`}`;
const aliases = puterId
? [
...new Set([
...(Array.isArray(entry.aliases)
? entry.aliases.filter(
(alias) => typeof alias === 'string',
)
: []),
...(entry.puterId ? [entry.puterId] : []),
puterId,
]),
]
: entry.aliases;
const model = {
...entry,
id: normalizeModelKey(entry.id),
...(puterId ? { puterId } : {}),
};
// Assigned only when the entry has names to carry: models()
// is serialized to the API, and an entry that declared no
// aliases should not sprout an `aliases: []` key on the wire.
if (aliases) model.aliases = aliases;
// Catalogs derive an alias by stripping the vendor org off the
// id, which yields '' for ids that carry no org. Drop those —
// an empty key would pool unrelated models together.
//
// Names may repeat: an entry is free to list its own id among
// its aliases, and normalizing can collapse two spellings onto
// one key. Deduplicate so a repeat can neither register a key
// twice nor make the bucket search consider it twice.
const keys = [
...new Set(
[model.id, ...(aliases ?? [])]
.map(normalizeModelKey)
.filter((key) => key.length > 0),
),
];
const bucket =
keys
.filter(isIdentityKey)
.map((key) => modelIdMap[key])
.find(Boolean) ?? [];
const routed = { ...model, provider: providerName };
this.#catalogEntries.set(routed, entry);
bucket.push(routed);
// First registration owns a key: a name already claimed by
// another model keeps pointing where it did.
for (const key of keys) {
modelIdMap[key] ??= bucket;
}
bucket.sort(compareModelPreference);
}
});
return modelIdMap;
}
/**
* The fallback model a caller pinned for this conversation, when it is one
* of the requested model's own. Anything else is ignored: a stale pin must
* not fail the request.
*/
async #pinnedRefusalFallback(
args: ICompleteArguments,
requested: IChatModel,
): Promise {
const pinnedId = args.refusalFallbackModel;
if (pinnedId === undefined || args.refusalFallback === false) {
return null;
}
const pinned = await this.#resolveLoadedModel(
pinnedId,
requested.provider,
);
return pinned &&
pinned.provider === requested.provider &&
requested.refusalFallbackModels?.includes(pinned.id)
? pinned
: null;
}
/**
* The models a request `requested` declines is rerun on, in order. A
* request already running on `pinned` has only the models after it left.
*/
async #refusalFallbackChain(
args: ICompleteArguments,
requested: IChatModel,
pinned: IChatModel | null,
): Promise {
const ids = requested.refusalFallbackModels;
if (!ids?.length || args.refusalFallback === false) return [];
const chain = await Promise.all(
ids
.slice(pinned ? ids.indexOf(pinned.id) + 1 : 0)
.map((id) => this.#resolveLoadedModel(id, requested.provider)),
);
return chain.filter(
(fallback): fallback is IChatModel =>
fallback?.provider === requested.provider,
);
}
/**
* Resolve against the map as it stands. A model, or the provider route
* asked for, that isn't in it yet may be in a catalog still loading at
* boot, so that waits for the first build before giving up.
*/
async #resolveLoadedModel(
modelId: string,
provider?: string,
): Promise {
const model = this.#resolveModel(modelId, provider);
if (model && (!provider || model.provider === provider)) return model;
await this.#modelMapBuilt;
return this.#resolveModel(modelId, provider);
}
#resolveModel(modelId: string, provider?: string): IChatModel | null {
// `model` comes straight from the caller and may not be a string.
if (typeof modelId !== 'string') return null;
const models = this.#modelIdMap[normalizeModelKey(modelId)];
if (!models || models.length === 0) return null;
// An explicitly requested provider is honoured even if its route is
// marked — the caller asked for that one, not for the cheapest hop.
if (provider) {
const pinned = models.find((m) => m.provider === provider);
if (pinned) return pinned;
}
return this.#preferHealthy(models) ?? models[0];
}
/**
* Inline `puter_path` parts as data URLs for a provider without its own
* upload path. Per attempt, not once up front: Claude uploads the same
* parts to its Files API and restores them if its attempt fails.
* Idempotent.
*/
async #resolvePuterPaths(
provider: IChatProvider,
args: ICompleteArguments,
actor: Actor | undefined,
model: IChatModel,
): Promise {
if (provider.resolvesPuterPaths) return;
if (!messagesHavePuterPaths(args.messages)) return;
await processPuterPathUploads(
args.messages,
{ fsEntry: this.stores.fsEntry, s3Object: this.stores.s3Object },
this.services.fs,
actor,
);
// What a Puter file holds is only known once it's read.
assertInputModalities(model, args.messages);
}
#findFallback(modelId: string, tried: Set): IChatModel | null {
const models = this.#modelIdMap[modelId];
if (!models) return null;
const untried = models.filter(
(m) => !tried.has(routeId(m.provider!, m.id)),
);
// Degrade to a marked route rather than to no route at all: the marks
// are a hint about recent failures, not a quota.
return this.#preferHealthy(untried) ?? untried[0] ?? null;
}
#preferHealthy(models: IChatModel[]): IChatModel | undefined {
return models.find((m) => !isRouteUnhealthy(m.provider!, m.id));
}
}