Provider quirks: special casings, streams, auth, and catalog handling
Per-provider deep dive for packages/ai transports: what each provider special-cases beyond
the shared pipeline, how its stream differs from the plain SSE/delta model, how it
authenticates and tracks usage/quotas, and what packages/catalog does specially for its
models (descriptors, discovery, identity, thinking metadata, pricing).
Related references:
- Provider compat reference — compat flags, reasoning levels, tool handling, forced tool choice
- Provider endpoint constraints — where new constraints should live
- Provider streaming internals — stream event normalization
- Providers — availability, credentials, login flows
OpenAI Chat Completions
The OpenAI Chat Completions provider implements HTTP POST JSON body streaming over Server-Sent Events (SSE) for the standard OpenAI /chat/completions wire contract (ChatCompletionCreateParamsStreaming request schema and ChatCompletionChunk event payloads). It serves as the primary workhorse transport for OpenAI models as well as dozens of OpenAI-compatible gateways and third-party providers including Groq, Cerebras, Mistral, DeepSeek, Fireworks, Zhipu (Z.AI), Qwen (DashScope), Kimi (Moonshot), Synthetic, GitLab Duo, OpenRouter, Vercel AI Gateway, CoreWeave, HuggingFace, Nvidia NIM, Novita, GMI Cloud, Baseten, NanoGPT, and Sakana/Fugu. The transport is implemented across packages/ai/src/providers/openai-completions.ts (main streaming runner streamOpenAICompletions), packages/ai/src/providers/openai-chat-wire.ts (vendored wire types), packages/ai/src/providers/openai-shared.ts (shared request/policy/usage helpers), packages/ai/src/providers/openai-reasoning-fallback.ts (400 reasoning-effort recovery), packages/ai/src/utils/openai-http.ts (HTTP SSE client postOpenAIStream), and packages/ai/src/utils/empty-completion-retry.ts (withEmptyCompletionRetry wrapper).
Special casings
- Azure Deployment Name Mapping:
parseAzureDeploymentNameMapinpackages/ai/src/providers/openai-shared.tsparses theAZURE_OPENAI_DEPLOYMENT_NAME_MAPenvironment variable (comma-separatedmodelId:deploymentNamepairs) increateRequestSetup(packages/ai/src/providers/openai-completions.ts) to translate model IDs into Azure deployment names, defaulting tomodel.idif unmapped. - Gateway Routing & Variant Transformations:
applyOpenAIGatewayRoutinginpackages/ai/src/providers/openai-shared.tsinjects OpenRouter provider routing preferences (params.provider).applyOpenRouterRoutingVariantandapplyWireModelIdTransformappend OpenRouter model variant suffixes (:nitro,:floor,:online,:extended).resolveSakanaRequestBaseUrlhandles Sakana/Fugu base URL overrides (SAKANA_BASE_URL/FUGU_BASE_URL), andapplyCoreWeaveProjectHeaderinjects CoreWeave project headers. - Empty-Completion Retry:
streamOpenAICompletionsis wrapped withwithEmptyCompletionRetry(packages/ai/src/utils/empty-completion-retry.ts), which retries a request up toMAX_EMPTY_COMPLETION_RETRIES(2 retries with exponential backoffEMPTY_COMPLETION_BASE_DELAY_MS= 500ms) if an attempt finishes cleanly withfinish_reason: "stop"but emits no visible assistant content (hasVisibleAssistantContentchecks for text, thinking, image, or tool calls) and <= 1 output token. - Reasoning-Effort 400 Fallback:
resolveOpenAIReasoningEffortFallbackandapplyOpenAIReasoningEffortFallback(packages/ai/src/providers/openai-reasoning-fallback.ts) intercept 400/422 HTTP error responses caused by unsupportedreasoning_effortvalues. It parses allowed levels from error messages (or resolves nearest supported level/null), remembers the fallback per-endpoint/model key (createOpenAIReasoningEffortFallbackKey,rememberOpenAIReasoningEffortFallback) in provider session state (getOpenAICompletionsProviderSessionState), and transparently retries the request without failing the turn. - Finish Reason Promotion: In
streamOpenAICompletionsOnce(packages/ai/src/providers/openai-completions.ts), if the backend reportsfinish_reason: "stop"but the turn produced structuraltoolCallblocks or healed tool calls viaStreamMarkupHealing,output.stopReasonis promoted from"stop"to"toolUse"so the agent execution loop correctly invokes tool handlers. - Mistral Tool ID Normalization:
normalizeMistralToolIdinpackages/ai/src/providers/openai-completions.tsrestricts tool call IDs for Mistral models to exactly 9 alphanumeric characters (padding with deterministic characters"ABCDEFGHI"or truncating). - MiniMax Object Arguments Deep Merge:
mergeStreamingArgumentObjectsinpackages/ai/src/providers/openai-completions.tshandles MiniMax-compatible backends that streamfunction.argumentsas JSON objects rather than strings, recursively merging partial object deltas across stream chunks. - DeepSeek Chat Template & Special Token Stripping:
stripDeepseekSpecialTokensandgetTrailingPartialDeepseekTokeninpackages/ai/src/providers/openai-completions.tsbuffer and strip raw<|...|>/<|...|>chat-template markers leaked indelta.contenton DeepSeek endpoints (e.g. NVIDIA NIM, DeepSeek native API). - Dialect & Provider-Specific Quirks:
isZaiReasoningEffortDialectinpackages/ai/src/providers/openai-shared.tshandles GLM-5.2zaithinking formats.dropOpenRouterKimiForcedToolReasoning,hasActiveNativeKimiK3Reasoning, andnormalizeSchemaForMoonshotmanage Kimi (Moonshot) K3 tool schemas and reasoning modes.applyOpenAIChatCompletionsPromptCachePolicyinjects prompt caching breakpoints (cache_control: { type: "ephemeral" }ornormalizeOpenAIPromptCacheKey64-charpc_prefix).
Stream behavior
- SSE Delta Decoding & Normalization:
postOpenAIStream(packages/ai/src/utils/openai-http.ts) usesreadSseJsonto decode raw SSEdata:payloads intoChatCompletionChunkobjects.normalizeStreamingContentText(packages/ai/src/providers/openai-completions.ts) normalizesdelta.contentwhether received as a string or an array of content parts ([{ type: "text", text: "..." }], e.g., Mistral Medium 3.5), preventing[object Object]string coercions. - Reasoning Fields & Encrypted Signatures:
streamOpenAICompletionsOnceinspectsdelta.reasoning_content(llama.cpp/vLLM),delta.reasoning, anddelta.reasoning_text, using the first non-empty field per chunk to prevent duplicate reasoning text. Encrypted reasoning signatures indelta.reasoning_details(reasoning.encrypted) are attached to correspondingtoolCall.thoughtSignature. - Partial JSON Throttling:
parseStreamingJsonThrottled(from@musepi/pi-utils) throttles incremental JSON parsing during tool argument streaming instreamOpenAICompletionsOnceto avoid high CPU overhead. - Stream Markup Healing:
StreamMarkupHealing(packages/ai/src/utils/stream-markup-healing.ts) is activated whenpolicy.stream.markupHealingPatternis configured. It inspects streamed text for XML/markdown-wrapped tool calls (e.g. DSML leaks), parses completed tool calls, emitstoolcall_start/toolcall_delta/toolcall_endevents, and promotesstopfinish reasons totoolUse. - Demoted Thinking & Cumulative Reasoning:
renderDemotedThinking(packages/ai/src/dialect/demotion.ts) handles demoted thinking blocks (isDemotedThinking).lastCumulativeReasoningBySignaturetracks cumulative reasoning streams (e.g., MiniMax-M3) across text block transitions to prevent re-emitting thinking text as duplicate blocks after visible text has started. - Watchdogs & Terminal Grace Window:
iterateWithIdleTimeout(packages/ai/src/utils/idle-iterator.ts) monitors stream activity usinggetOpenAIStreamFirstEventTimeoutMsandgetOpenAIStreamIdleTimeoutMs, injectingX-Stainless-Timeoutheaders downstream. On stream finish,iterateWithTerminalGraceenforces a 2,500ms post-finish grace window (OPENAI_COMPLETIONS_POST_FINISH_GRACE_MS) allowing trailing usage-only chunks (stream_options.include_usage) with cache-read token details (awaitTrailingUsageDetails) to arrive before closing the stream. - Usage Chunk Parsing:
parseChunkUsageandapplyUsagePayloadinpackages/ai/src/providers/openai-completions.tsprocess token usage fromchunk.usageorchoice.usage. Fields extracted includeprompt_tokens_details.cached_tokens,prompt_cache_hit_tokens,prompt_cache_miss_tokens,completion_tokens_details.reasoning_tokens,cache_write_tokens, and provider-reported costs viaapplyOpenRouterReportedCost(packages/ai/src/providers/openai-shared.ts).
Auth & usage
- API-Key Validation:
validateOpenAICompatibleApiKeyinpackages/ai/src/registry/api-key-validation.tsvalidates API credentials by issuing a lightweightPOST /chat/completionsrequest withmessages: [{ role: "user", content: "ping" }],max_tokens: 1,temperature: 0, andAuthorization: Bearer ${apiKey}. - Credential Resolution & Env Vars:
getEnvApiKeyinpackages/ai/src/stream.tsresolves provider-specific environment variables for OpenAI-compatible providers:OPENAI_API_KEY,GROQ_API_KEY,CEREBRAS_API_KEY,MISTRAL_API_KEY,DEEPSEEK_API_KEY,FIREWORKS_API_KEY,OPENROUTER_API_KEY,TOGETHER_API_KEY,SAMBANOVA_API_KEY,NEBIUS_API_KEY,NOVITA_API_KEY,AVALAI_API_KEY,CHUTES_API_KEY,NANOGPT_API_KEY,HYPERBOLIC_API_KEY,PERPLEXITY_API_KEY,XAI_API_KEY, andAZURE_OPENAI_API_KEY. - Usage Accounting & Quota Surfacing:
calculateOpenAIUsageAccounting(packages/ai/src/providers/openai-shared.ts) reconciles input, output, cache-read, and cache-write tokens into standardUsagerecords. OpenRouter authoritative charges are populated intooutput.usage.costviaapplyOpenRouterReportedCost. Copilot request counts are stored inoutput.usage.premiumRequests. Transport HTTP errors (e.g. 429 Rate Limit, 408 Timeout, 5xx Server Error) are thrown asOpenAIHttpError(packages/ai/src/utils/openai-http.ts), capturing status, headers, and error envelope details for upstream error mapping inAIError.finalize.
Catalog model handling
- Provider Descriptors:
CATALOG_PROVIDERSinpackages/catalog/src/provider-models/descriptors.tsregisters all catalog entries using this transport (e.g.,openai,groq,cerebras,mistral,deepseek,fireworks,openrouter), specifyingapi: "openai-completions",defaultModel, environment variable keys, and documentation URLs. - Model Resolvers & Managers:
createOpenAICompatibleModelManagerOptionsinpackages/catalog/src/provider-models/openai-compat.tsconstructs model managers foropenai-completionsproviders. It combines static/curated model definitions, bundled reference specs (getBundledModels), and live models fetched from remote catalog endpoints. - Catalog Discovery:
fetchOpenAICompatibleModelsinpackages/catalog/src/discovery/openai-compatible.tsqueries provider/modelsendpoints. It safely parses envelopes (data,models,result,items), enforces request timeouts usingwithOpenAICompatibleDiscoveryTimeout, validates model record schemas (openAICompatibleModelRecordSchema), applies custom mappers/filters, and deduplicates models by ID. - Identity & Classification:
parseKnownModelandparseOpenAIModelinpackages/catalog/src/identity/classify.tsextract model families, variants (base,codex,mini,max,nano), and SemVer versions (parseSemVer) for OpenAI models matchinggpt-(\d+(?:\.\d+){0,2})(?:-(...))?. Version comparison utilities (semverGte,semverEqual) drive capabilities detection across GPT-4, GPT-4o, and GPT-5 families. - Thinking Metadata & Effort Ladders:
resolveModelThinkingandderiveThinkinginpackages/catalog/src/model-thinking.tsconstruct thinking metadata (ThinkingConfig) and map model identity/compat settings to effort ladders:DEFAULT_REASONING_EFFORTS:[minimal, low, medium, high]DEFAULT_REASONING_EFFORTS_WITH_XHIGH:[minimal, low, medium, high, xhigh](e.g., OpenRouter GLM-5.2)GPT_5_2_PLUS_EFFORTS:[low, medium, high, xhigh]FIVE_TIER_EFFORTS_LOW_TO_MAX:[low, medium, high, xhigh, max](GPT-5.6+ wire effort models, Fire Pass Kimi router)LOW_HIGH_MAX_REASONING_EFFORTS:[low, high, max](Kimi K3, DeepSeek V4 Flash)HIGH_MAX_REASONING_EFFORTS:[high, max](GLM-5.2 on Z.ai/Umans/Baseten, DeepSeek V4 Pro)HIGH_ONLY_REASONING_EFFORTS:[high](OpenRouter DeepSeek)OLLAMA_REASONING_EFFORTS:[low, medium, high, max](Ollama endpoints)
OpenAI Responses
The OpenAI Responses provider (packages/ai/src/providers/openai-responses.ts) handles OpenAI’s stateful /v1/responses HTTP Server-Sent Events (SSE) streaming wire protocol (types defined in openai-responses-wire.ts, shared encoding and decoding logic in openai-shared.ts). Unlike chat completions, the Responses API operates on a structured item sequence (ResponseInput) containing typed input/output items (input_text, input_image, input_file, message, function_call, custom_tool_call, computer_call, reasoning), supports server-side context chaining via previous_response_id, explicit prompt-cache breakpoints, and native reasoning summaries and encrypted content blocks.
Special casings
- Responses input-item model vs chat messages:
buildResponsesInputinopenai-shared.tsconverts standard conversation contexts into theResponseInputarray (ResponseInputItem[]). System instructions use top-levelinstructionsby default or developer-role items ({ role: "developer" }) whenpolicy.messages.systemRole === "developer"(required for reasoning models). Replayed history strips or retains reasoning items based onfilterReasoningHistory, while Harmony dialect models (GPT-5+) escape reserved control token spellings in replayed transport data viaescapeReplayedControlTokens. previous_response_idchaining & stale-chain reset:buildOpenAIResponsesChainedParamsinopenai-responses.tsmanages stateful turns. WhenstatefulResponsesis active (default ON for official OpenAI endpoints viaPI_OPENAI_STATEFULflag andhostMatchesUrl), requests forcestore: trueand calculate a delta payload (buildResponsesDeltaInput) anchored toprevious_response_id. If history mutates, options change, or prompt-cache breakpoint policy alters, the chain resets to a full replay (resetOpenAIResponsesChainState). If the endpoint returns a stale ID error (isOpenAIResponsesStalePreviousResponseError), the provider incrementsstaleFailuresand falls back to a full transcript replay; afterOPENAI_RESPONSES_CHAIN_STALE_FAILURE_LIMIT(3) consecutive failures, chaining is disabled for the session. Zero Data Retention (ZDR) org errors (markOpenAIResponsesChainZeroDataRetention) immediately disable chaining for the session and forcestore: false.- Encrypted reasoning items & summaries: Supports
include: ["reasoning.encrypted_content"]viapolicy.reasoning.includeEncryptedReasoning.ResponseReasoningItemobjects contain encrypted content payloads, reasoning text deltas (response.reasoning_text.delta), and summary text deltas (response.reasoning_summary_text.delta). Thinking signatures carrying serialized JSON are parsed viaparseResponseReasoningReplayItemand replayed as nativereasoningitems whenfilterReasoningHistoryis false. - Composite
callId|itemIdtool IDs:normalizeResponsesToolCallIdinpackages/ai/src/utils.tshandles tool call ID normalization. Tool call identifiers in Responses are composite strings formatted as${callId}|${itemId}. The function splits incoming IDs on|into distinctcallId(truncated to 64 chars withcall_prefix) anditemId(prefixed withfc_orctc_). When an un-synthesized ID is passed, it generates a hash-based pair (call_<hash>andfc_<hash>/ctc_<hash>). Transformed messages usenormalizeResponsesToolCallIdForTransformto preserve alignment across tool calls and tool result messages. - Custom (freeform) tools & computer tools: Tool conversion in
convertToolshandles function, custom, and computer tools. Whenmodel.applyPatchToolType === "freeform"(checked viasupportsFreeformApplyPatch), custom format tools (likeapply_patch) are encoded astype: "custom"with grammar definitions (compactGrammarDefinition). Whenmodel.supportsComputerUse === true, native computer tools (type: "computer") emitcomputer_callandcomputer_call_outputitems using structuredComputerActionlists; models without native computer support fall back to regular function tools. Tool schemas are sanitized viasanitizeSchemaForOpenAIResponsesandadaptSchemaForStrict, and schemas violating strict constraints are quarantined (findStrictToolSchemaViolation) to prevent invalid MCP schemas from failing entire requests. - Service tier & obfuscation opt-out:
serviceTieroption is passed down to sampling params and reported in output usage viaprocessResponsesStream. Whenmodel.compat.supportsObfuscationOptOutis true, sampling parameters includestream_options: { include_obfuscation: false }. - Image detail handling: Image content conversion in
convertResponsesInputContentandappendResponsesToolResultMessagesrespectsmodel.compat.supportsImageDetailOriginal. When false,"original"image detail values are mapped to"auto"to prevent upstream rejection. Tool result images generate synthetic user input messages attached after tool outputs.
Stream behavior
- Stream event protocol (
response.*lifecycle):processResponsesStreaminopenai-shared.tsprocesses SSE events emitted by/v1/responses. Handles lifecycle events includingresponse.created,response.output_item.added,response.output_text.delta,response.reasoning_text.delta,response.reasoning_summary_text.delta,response.function_call_arguments.delta,response.custom_tool_call_input.delta,response.output_item.done,response.completed, andresponse.done. Interleaved parallel tool calls are tracked concurrently acrossoutput_index,item_id, and prefixed call ID lookup maps (openItemsByOutputIndex,openItemsByItemId,openItemsByPrefixedCallId). - Watchdogs & transient retries:
streamOpenAIResponsesOnceusesiterateWithIdleTimeoutwith two timeout thresholds:streamFirstEventTimeoutMs(withX-Stainless-Timeoutrequest header) for initial response headers/events andstreamIdleTimeoutMsfor inter-event stalls. If a stream terminates prematurely before emitting replay-unsafe output (isOpenAIResponsesReplayUnsafeEvent), the single-attempt streamer performs a transient retry (OPENAI_RESPONSES_MAX_TRANSIENT_STREAM_RETRIES = 1) after a delay (OPENAI_RESPONSES_TRANSIENT_STREAM_RETRY_DELAY_MS = 500ms). The publicstreamOpenAIResponseswraps execution withwithEmptyCompletionRetryto retry empty completions.
Auth & usage
- Standard OpenAI auth relies on
OPENAI_API_KEY(or provider-specific environment variables) resolved viagetEnvApiKeyandresolveOpenAIRequestSetupinopenai-shared.ts. Requests pass standard Bearer token authorization headers (Authorization: Bearer <key>) alongside optional Stainless/Copilot headers. (Note:openai-codex/ ChatGPT subscription plan OAuth auth is handled separately).
Catalog model handling
gpt-5+identity classification: Models in thegpt-5family are identified viaisOpenAIWireGen5PlusandisOpenAIWireGen54Plusinpackages/catalog/src/identity/family.ts.gpt-5+models reject legacy sampling parameters (such astemperature,top_p,frequency_penalty) with HTTP 400 errors across serving hosts, whichbuildOpenAICompat/buildOpenAIResponsesCompataccount for viasupportsReasoningParams.- Prompt-cache breakpoints (
supportsOfficialOpenAIPromptCacheBreakpoints): Evaluated inpackages/catalog/src/compat/openai.ts.supportsOfficialOpenAIPromptCacheBreakpointsreturns true for official OpenAI endpoints serving models with version >= 5.6. When enabled andpromptCache.mode === "explicit",markLatestStableResponsesCacheBreakpointinopenai-responses.tsinjects{ mode: "explicit" }prompt_cache_breakpointannotations onto the latest stable developer/user message block, while preserving stateful baseline breakpoints. - Reasoning summary config & effort ladders:
buildParamsapplies reasoning parameters viaapplyResponsesCompatPolicy. Effort parameters map through model-specific maps (reasoningEffortMaporthinking.effortMap). Forgpt-5.6+models and 5-tier effort scales (includingxhighandmax),model-thinking.tsconfigures effort ladders (minimal,low,medium,high,xhigh,max), mappingxhighandmax1:1 or shifting per host dialect (e.g.KIMI_K3_REASONING_EFFORT_MAP,MIMO_REASONING_EFFORT_MAP). Generated pro aliases (gpt-5.6-*-pro) automatically attachreasoningMode: "pro".
OpenAI Codex
The OpenAI Codex provider integrates ChatGPT Plus/Pro subscription models using the OpenAI Responses API surface over SSE or WebSocket transport. Requests target the ChatGPT backend (https://chatgpt.com/backend-api/codex/responses or custom base URL) using ChatGPT OAuth tokens with account-level isolation. Entry modules include streaming in packages/ai/src/providers/openai-codex-responses.ts, request transformation in packages/ai/src/providers/openai-codex/request-transformer.ts, error and rate-limit parsing in packages/ai/src/providers/openai-codex/response-handler.ts, quota and usage tracking in packages/ai/src/usage/openai-codex.ts, reset management in packages/ai/src/usage/openai-codex-reset.ts, base URL normalization in packages/ai/src/usage/openai-codex-base-url.ts, provider registry in packages/ai/src/registry/openai-codex.ts, and OAuth login flow in packages/ai/src/registry/oauth/openai-codex.ts.
Special casings
- WebSocket vs SSE dual transport: Supports WebSocket streaming (
v2StreamingEnabled: true, headerOpenAI-Beta: responses_websockets=2026-02-06,preferWebsocketsoption) viaCodexWebSocketConnectioninpackages/ai/src/providers/openai-codex-responses.ts. Reuses sockets with a max idle reuse cap (CODEX_WEBSOCKET_MAX_IDLE_REUSE_MS= 30s), ping/pong heartbeats (10s interval, 60s timeout), and queue capacity (4096). Instantly falls back to SSE on connection/handshake failures (CODEX_WEBSOCKET_FATAL_PATTERNS,CodexWebSocketTransportError). - Sampling parameter stripping: Sampling parameters (
temperature,top_p,top_k,min_p,presence_penalty,repetition_penalty,frequency_penalty,stop) are stripped inpackages/ai/src/providers/openai-codex/request-transformer.tstransformRequestBody; the Codex backend returns HTTP 400Unsupported parameterif any sampling parameters are sent (#3117). - Responses Lite transport: Enabled via catalog (
useResponsesLite), request option (responsesLite), orPI_CODEX_RESPONSES_LITEenv (resolveCodexResponsesLite). FunctionapplyCodexResponsesLiteShapeembeds declared tools into a leadingadditional_toolsdeveloper item, system instructions into a developer message, strips imagedetail, turns off parallel tool calls, forcesreasoning.context: "all_turns", and appendsx-openai-internal-codex-responses-lite: trueheader (orws_request_header_x_openai_internal_codex_responses_litein WSclient_metadata). Hosted tool choices (tool_choice) fall back to"auto"if no matching declared tool is present (#5771). - Tool call/output pair repair:
repairToolCallPairsinrequest-transformer.tsrewrites orphanedfunction_call_output/custom_tool_call_outputlacking prior calls into assistant messages ([Previous tool result; call_id=...]), and injects synthetic outputs ([No tool output recorded...]) for orphaned calls missing outputs, preventing backend HTTP 400 validation failures. - Session affinity & headers: Emits session headers including
session_id,session-id,x-codex-installation-id,x-codex-window-id,x-codex-turn-metadata(JSON containingturn_id,installation_id,parent_turn_id,request_kind),x-codex-parent-thread-id, andx-openai-subagentdefined inpackages/catalog/src/wire/codex.tsandopenai-codex-responses.ts. - Attestation & compression: Consults process-wide DeviceCheck attestation hook
setCodexAttestationProviderforx-oai-attestationheader (getCodexAttestationHeader). Compresses request body payloads with zstd (compressCodexRequestBody) for official origins whenPI_CODEX_ZSTDis active. - Harmony control token escaping: Sanitizes replayed input text with
escapeHarmonyControlTokensfor models operating on the Harmony dialect (isHarmonyDialectModel).
Stream behavior
- Event protocol: Parses SSE JSON payloads or WebSocket frames (
response,sequence_number,type). Fires progress events (isOpenAIResponsesProgressEvent,CODEX_ADDITIONAL_PROGRESS_EVENT_TYPESsuch asresponse.doneandresponse.incomplete). - Timeout watchdogs: Enforces
CODEX_WEBSOCKET_FIRST_EVENT_TIMEOUT_MS(300s) for first event,CODEX_WEBSOCKET_IDLE_TIMEOUT_MS(300s) for steady-state stream idle cap, anditerateWithIdleTimeoutfor SSE streams. - Stale history recovery: Re-streams/replays on stale
previous_response_iderrors (CODEX_STALE_PREVIOUS_RESPONSE_CODES) by clearing the invalid chained response pointer and retrying. - Retry budget & rate limits: Up to
CODEX_MAX_RETRIES(5) retries on transient errors (model_error,server_error,internal_error, orCODEX_RETRYABLE_EVENT_MESSAGE). Handles HTTP 429 backoff with server retry delays within a 5-minute budget (CODEX_RATE_LIMIT_BUDGET_MS). - Whitespace loop defense: Detects infinite whitespace tool call argument deltas (
CODEX_WHITESPACE_TOOL_CALL_ARGUMENT_DELTA_EVENT_LIMIT= 256, 16KB limit), interrupting execution withCodexWhitespaceToolCallLoopErrorand attempting up to 2 retries (CODEX_WHITESPACE_LOOP_RETRY_LIMIT). - Concurrent reasoning summaries: Request body includes
stream_options: { reasoning_summary_delivery: "sequential_cutoff" }when reasoning summaries are requested (supportsCodexReasoningSummary), enabling output text streaming before summary completion.
Auth & usage
- OAuth login flows: Implements ChatGPT OAuth in
packages/ai/src/registry/oauth/openai-codex.ts. Browser flow uses PKCE S256 (createOpenAICodexAuthorizationUrl) with fixed local port 1455 (http://localhost:1455/auth/callback), client IDapp_EMoamEEZ73f0CkXaXp7hrann, and simplified CLI flow flags. Headless device-code flow (loginOpenAICodexDevice) useshttps://auth.openai.com/api/accounts/deviceauth/usercodeand pollsdeviceauth/token. - Token refresh & claims:
refreshOpenAICodexTokenpostsgrant_type: refresh_tokentohttps://auth.openai.com/oauth/token. Extractschatgpt_account_idand useremailfrom JWT claims (https://api.openai.com/authandhttps://api.openai.com/profileingetTokenProfile). - Account rotation & rate-limit ranking: Account identity is set via
ChatGPT-Account-Idheader (getCodexAccountId).codexRankingStrategyinpackages/ai/src/usage/openai-codex.tsisolates standard chat limits (5h primary, 7d secondary) from Spark meter limits (-sparkmodel suffix spendssparkscope), preventing Spark exhaustion from blocking normal chat requests. - Usage tracking:
openaiCodexUsageProviderqueries/wham/usageon canonical ChatGPT origins. Parsesprimary_window(5h) andsecondary_window(7d), plusadditional_rate_limits(Spark/extra meters). Ingests response headers (x-codex-primary-used-percent,x-codex-primary-window-minutes,x-codex-primary-reset-at,x-codex-secondary-*) inparseCodexRateLimitHeaders(response-handler.tsparseCodexError). - Saved rate limit reset credits: Reads
rate_limit_reset_creditsfrom/wham/usage. Lists available credits withlistCodexResetCredits(GET /wham/rate-limit-reset-credits), selects soonest-expiring credit withpickSoonestExpiringCredit, and redeems viaconsumeCodexResetCredit(POST /wham/rate-limit-reset-credits/consumewith client UUIDredeem_request_id). - Base URL normalization:
normalizeCodexBaseUrlinpackages/ai/src/usage/openai-codex-base-url.tsforces account API requests (wham/usage, reset credits) to canonicalchatgpt.comorchat.openai.comorigins (/backend-api), ignoring custom proxy overrides (providers.openai-codex.baseUrl) that would 404. Stream URLs resolve viaresolveCodexResponsesUrlinopenai-codex-responses.ts.
Catalog model handling
- Descriptor & management: Defined as
openai-codexprovider descriptor inpackages/catalog/src/provider-models/descriptors.ts(default model"gpt-5.5"). Configured inpackages/catalog/src/provider-models/special.tscreateOpenAICodexModelManagerOptionsas a special-managed provider with dynamic model discovery. - Dynamic discovery:
fetchCodexModelsinpackages/catalog/src/discovery/codex.tsqueries/codex/modelsor/modelswithv2StreamingEnabled: true, parsingreasoning_presets(effort,summary) intoModelSpec<"openai-codex-responses">. - Identity & classification:
OpenAIVariantinpackages/catalog/src/identity/classify.tssupports"codex","codex-max","codex-mini","codex-spark".parseOpenAIModelmatchesgpt-X.Y-(codex-spark|codex-mini|codex-max|codex|mini|max|nano). Priority list inpackages/catalog/src/identity/priority.tsranksopenai-codexabove generic provider fallbacks. - Thinking & effort limits:
packages/catalog/src/model-thinking.tsmaps supported efforts (minimal,low,medium,high,xhigh,max), pinpoints model-specific tiers (e.g.GPT_5_1_CODEX_MINI_EFFORTS), and checkssupportsAllTurnsReasoningContextandsupportsCodexReasoningSummaryinidentity/family.ts. - Pricing fallback:
applyCodexPricingFallbackinpackages/catalog/scripts/generate-models.tscopies billable costs fromopenaiprovider entries with matching model IDs when Codex discovery models lack explicit cost metadata.
Azure OpenAI
Azure OpenAI Responses provider (azure-openai-responses) handles transport, endpoint resolution, and compatibility wrapping for OpenAI-family models (GPT-4/4.1/4o, GPT-5 series, o-series, Codex) served over Azure OpenAI’s Responses API. It uses the internal postOpenAIStream transport (packages/ai/src/utils/openai-http.ts) to make JSON-POST / SSE requests. Stream generation is initialized in streamAzureOpenAIResponses (packages/ai/src/providers/azure-openai-responses.ts), while shared Responses input/output processing logic lives in packages/ai/src/providers/openai-shared.ts.
Special casings
- Deployment-name mapping: Azure OpenAI requires deployment names in request payloads.
resolveDeploymentName(packages/ai/src/providers/azure-openai-responses.ts) checksoptions.azureDeploymentName, then checks theAZURE_OPENAI_DEPLOYMENT_NAME_MAPenvironment variable (parsed byparseAzureDeploymentNameMapinopenai-shared.tsinto a map ofmodelId=deploymentNamepairs, e.g.gpt-5-mini=my-mini-dep,o3=my-o3-dep), and defaults tomodel.id. - Base-URL / resource resolution:
resolveAzureConfig(packages/ai/src/providers/azure-openai-responses.ts) checksoptions.azureBaseUrlor$env.AZURE_OPENAI_BASE_URL. If missing, it constructshttps://${resourceName}.openai.azure.com/openai/v1fromoptions.azureResourceNameor$env.AZURE_OPENAI_RESOURCE_NAME. If still missing, it falls back tomodel.baseUrl, throwingAIError.ConfigurationErrorif no endpoint is found. Trailing slashes are stripped. - API-version handling:
resolveAzureConfigresolves the API version fromoptions.azureApiVersion,$env.AZURE_OPENAI_API_VERSION, or defaults to"v1". It is passed as theapi-versionURL query parameter on the request (${baseUrl}/responses?api-version=${apiVersion}), not as an HTTP header. - Strict responses tool-pairing: Enabled by default for Azure OpenAI models via
buildOpenAIResponsesCompat(packages/catalog/src/compat/openai.ts,isAzure = true). InbuildResponsesInput/appendResponsesToolResultMessages(packages/ai/src/providers/openai-shared.ts), unpaired tool outputs (results whosecallIdwas not emitted by a prior assistantfunction_callitem) are rejected by Azure’s strict backend. Omp folds orphan tool results into synthetic assistant note messages ([Orphan <tool> result; call_id=<id>]: <text>up to 16,000 characters, or[Orphan computer result; call_id=<id>]) rather than sending un-paired output items. - Image detail clamps: In
appendResponsesToolResultMessages/convertResponsesInputContent,clampResponsesImageDetailclampsdetail: "original"to"auto"ifsupportsImageDetailOriginalisfalse. For Azure OpenAI,supportsImageDetailOriginalistrue(unlike GitHub Copilot and xAI OAuth), preserving original image resolution. - Computer-tool fallback mapping:
modelForAzureEndpoint(packages/ai/src/providers/azure-openai-responses.ts) verifies that the resolved endpoint host ends with.openai.azure.comormodels.inference.ai.azure.com. If routed through an unrecognized proxy,supportsComputerUseis disabled. InbuildParams, if a tool hasnative.type === "computer"andmodel.supportsComputerUseistrue, it is serialized as{ type: "computer" }. IfsupportsComputerUseisfalse, it falls back to serializing the computer tool as a standard{ type: "function", name: tool.name, ... }tool.tool_choiceis automatically translated betweencomputerandfunctiontargets. - Differences from plain Responses (
openai-responses): Uses theapi-keyheader (neverAuthorization: Bearer), uses a fixed endpoint path${baseUrl}/responses?api-version=...(the/responsespath is non-deployment-scoped, unlike Chat Completions/deployments/{dep}/chat/completions), passes the deployment name inside the request body asmodel, performs dynamic runtime endpoint construction from env/options, and defaultsstrictResponsesPairingtotrue.
Stream behavior
- Event processing: Uses
processResponsesStreaminpackages/ai/src/providers/openai-shared.tsto consume SSE stream events (response.created,response.output_item.added,response.content_part.added,response.output_text.delta,response.completed,response.incomplete). Terminalresponse.incompleteevents (output-token truncation) update usage counters and setstopReason: "length". - Idle & first-event watchdogs: Wrapped with
iterateWithIdleTimeout. If the first SSE event does not arrive withinstreamFirstEventTimeoutMs, aborts with"Azure OpenAI responses stream timed out while waiting for the first event". - Untyped SSE payload resolution:
onSseEventinspects untyped JSON event data (typeorobjectproperties) to attach the event type tag when missing from standard SSE header lines. - Reasoning effort fallback: Catches
OpenAIHttpErrorduring stream initiation. If the endpoint rejects the requested reasoning effort (e.g.xhigh),resolveOpenAIReasoningEffortFallbackdetermines a lower effort level, steps downparams.reasoning, and retries the request usingcreateOpenAIReasoningEffortFallbackKey("azure-responses", url, model).
Auth & usage
- Credential source: Sourced from
options.apiKeyor$env.AZURE_OPENAI_API_KEY(retrieved viagetEnvApiKey(model.provider)inpackages/ai/src/stream.tsorbuildAzureResponsesRequest). Sent as theapi-keyheader. - Usage tracking: Extracted directly from terminal
response.completed/response.incompletestream events (input_tokens,output_tokens,reasoning_tokens,cached_tokens) byprocessResponsesStream. No separate usage tracker exists underpackages/ai/src/usage/. - Prompt caching controls:
prompt_cache_keyis generated viagetOpenAIPromptCacheKey(options). Explicit prompt caching mode is rejected (AIError.ConfigurationError) because Azure Responses does not support explicit cache control headers or retention directives.
Catalog model handling
- Descriptors: Catalog provider defined in
packages/catalog/src/provider-models/descriptors.ts(id: "azure",defaultModel: "gpt-5.5",envVars: ["AZURE_OPENAI_API_KEY"]). Inpackages/catalog/src/provider-models/openai-compat.ts, mapped viasimpleModelsDevDescriptor("azure", "azure", "azure-openai-responses", "", ...)which filters stencil catalog models to tool-capable OpenAI-family IDs (gpt-,o1,o3,o4,codex,chatgpt), dropping third-party Foundry models (Claude, DeepSeek, Llama, Mistral, Phi). - Why bundled models carry no
baseUrl: Azure OpenAI endpoints are resource-specific and unknown during catalog generation (models.jsonstoresbaseUrl: ""). Runtime resolution resolves endpoints fromAZURE_OPENAI_BASE_URLorAZURE_OPENAI_RESOURCE_NAME. Compat detection (isAzureinpackages/catalog/src/compat/openai.ts) matchesprovider === "azure", ensuring bundled models with emptybaseUrlstill receive Azure compat flags (strictResponsesPairing,supportsDeveloperRole,supportsStrictMode). - Identity & classification:
hosts.tsdefinesazureOpenAImatchingprovider: "azure"or hostnames ending with.openai.azure.com,azure.com/openai, ormodels.inference.ai.azure.com. - Thinking metadata: In
packages/catalog/src/model-thinking.ts, Azure reasoning models (o-series, GPT-5, Codex) resolve discrete OpenAI reasoning effort tiers (minimal,low,medium,high,xhigh,max) viaDEFAULT_REASONING_EFFORTS_WITH_XHIGH.
Anthropic Messages
The Anthropic provider (packages/ai/src/providers/anthropic.ts) implements the Anthropic Messages API protocol over HTTPS POST to /v1/messages (or /v1/messages?beta=true) using Server-Sent Events (SSE) for streaming. Custom HTTP client transport is provided by AnthropicMessagesClient (packages/ai/src/providers/anthropic-client.ts), replacing @anthropic-ai/sdk with built-in retry and timeout logic. Wire structures and SSE payloads are typed in packages/ai/src/providers/anthropic-wire.ts. Client fingerprinting constants (version, user agent, tool prefix) live in packages/ai/src/providers/claude-code-fingerprint.ts, while low-level Node HTTPS socket reuse and header ordering are handled by coworkFetch (packages/ai/src/providers/cowork-fetch.ts).
Special casings
- OAuth vs API Key Paths:
buildAnthropicHeaders(packages/ai/src/providers/anthropic.ts) checksoptions.isOAuth ?? isAnthropicOAuthToken(apiKey). OAuth requests sendAuthorization: Bearer <token>withoutX-Api-Key, defaultAccept: application/json(ortext/event-stream), and inject Cowork desktop beta flags (buildCoworkBetas). API key requests sendX-Api-Key: <key>withoutAuthorizationand include only caller extra betas. Non-official endpoints allow header overrides whenallowAnthropicHeaderOverridesis enabled. - Claude Code Fingerprint Headers & Betas: Default headers include
anthropic-version: 2023-06-01,anthropic-dangerous-direct-browser-access: true,x-app: cli, andUser-Agent: claude-cli/2.1.220 (external, claude-desktop)(coworkUserAgent). Active beta flags (buildCoworkBetas) includeclaude-code-20250219,interleaved-thinking-2025-05-14,thinking-token-count-2026-05-13,context-management-2025-06-27,prompt-caching-scope-2026-01-05,mid-conversation-system-2026-04-07,advanced-tool-use-2025-11-20,effort-2025-11-24, andfallback-credit-2026-06-01(context-1m-2025-08-07is omitted to avoid 429 credit errors on subscription tokens, #7238). Fingerprint metadata (generateClaudeCloakingUserId,deriveClaudeDeviceId,generateClaudeJsonUserId) generates device/session IDs. Billing attestation headers (createClaudeBillingHeader,wrapFetchForCch,patchCch) embedcch=00000XXHash64 hashes intosystem[0]. - System-Prompt Injection:
buildAnthropicSystemBlocks(packages/ai/src/providers/anthropic.ts) automatically prependsclaudeCodeSystemInstruction(“You are a Claude agent, built on Anthropic’s Claude Agent SDK.”) assystem[0]for OAuth credentials. Mid-conversation system messages in turn history are enabled for Opus 4.8+ / Sonnet 5+ viamid-conversation-system-2026-04-07. - Thinking Signatures & Redacted Thinking: Replaying modified or unsigned thinking blocks causes Anthropic API errors (
invalid signature in thinking block).convertAnthropicMessagesconvertsThinkingContentandRedactedThinkingContent(type: "redacted_thinking",data).maybeAddReplayUnsignedThinkingHintattaches recovery hints on signature errors, whileunwrapAnthropicThinkingEnvelopestrips legacy<thinking>XML wrappers. - Tool Use Replay & Prefixes:
encodeAnthropicToolName/decodeAnthropicToolName(packages/ai/src/providers/anthropic.ts) prefixes custom tool names with_(claudeToolPrefix) when using OAuth to prevent collisions with built-in tools (web_search,code_execution,text_editor,computer). Server-executed web searches (ServerToolUseBlockParam,WebSearchToolResultBlockParaminanthropic-wire.ts) are detected viaisAnthropicWebSearchHistoryBlockfor turn replay. Empty tool errors are filled byensureErrorToolResultWireContent. - Strict-Tool Schema Normalization & Fallback:
normalizeAnthropicToolSchemaandnormalizeAnthropicStrictSchemastrip unsupported JSON schema keywords (e.g.minItems/maxItemson objects) for thestructured-outputs-2025-12-15beta. If a strict tool schema causes HTTP 400,streamAnthropicOncecallsdropAnthropicStrictToolsand automatically retries without strict mode. - Adaptive vs Budget Thinking:
ThinkingConfigParam(anthropic-wire.ts) supports budget thinking ({ type: "enabled", budget_tokens: N }enforced byensureMaxTokensForThinking) and adaptive thinking ({ type: "adaptive" }paired withoutput_config: { effort: level }viaeffort-2025-11-24beta). Forced tool choices (disableThinkingIfToolChoiceForced) automatically disable thinking. - Prompt Cache Breakpoints:
applyPromptCaching(packages/ai/src/providers/anthropic.ts) attaches{ type: "ephemeral", scope: "global" }breakpoints to system prompts (cacheSystemPrefixBreakpoints), tool definitions, and historical user turns.enforceCacheControlLimitcaps total breakpoints to 4 per request.
Stream behavior
- Event Protocol: SSE streams in
streamAnthropicOnce(packages/ai/src/providers/anthropic.ts) emit standard framing events:message_start(delivering initial input and cache usage),content_block_start(initializing block types: text, thinking, tool_use, redacted_thinking, fallback),content_block_delta(streamingtext_delta,thinking_delta,signature_delta,input_json_delta),message_delta(deliveringstop_reasonand finaloutput_tokens),content_block_stop,message_stop, andping. - Fine-Grained Tool Streaming: Enabled via
fine-grained-tool-streaming-2025-05-14beta. Incominginput_json_deltachunks accumulate inkStreamingPartialJson, parsed continuously byparseStreamingJsonThrottledto surface streaming tool arguments. - Stream Watchdogs & Healing: Streams are monitored for stall timeouts using
getStreamFirstEventTimeoutMsandgetStreamIdleTimeoutMsinsideiterateWithIdleTimeout.pingevents (ANTHROPIC_PING_EVENT) reset idle timeout multipliers. Empty completion responses (0 tokens) trigger automatic retry viawithEmptyCompletionRetry. Fast mode (speed: "fast") failures clear session fast mode state (clearAnthropicFastModeFallback,dropAnthropicFastMode) to fallback to standard execution.
Auth & usage
- OAuth Authentication & PKCE:
AnthropicOAuthFlow(packages/ai/src/registry/oauth/anthropic.ts) performs PKCES256authentication againsthttps://claude.ai/oauth/authorizeandhttps://api.anthropic.com/v1/oauth/tokenusing decoded Client ID (OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl). OAuth tokens carry an absolute grant TTL of 30 days (ANTHROPIC_OAUTH_GRANT_TTL_MSinanthropic-constants.ts), requiring monthly interactive re-login regardless of refresh token rotation. Account identity is resolved viaextractAccountFromTokenResponseorfetchBootstrapIdentity(/api/claude_cli/bootstrap). - Quota Tracking & Account Rotation:
packages/ai/src/usage/claude.tspollshttps://api.anthropic.com/api/oauth/usageto track rollingfive_hour,seven_day,limits[](weekly_scoped), andanthropic-ratelimit-unified-*headers. Errors matchingisUsageLimitOutcome(packages/ai/src/error/rate-limit.ts) andparseRateLimitReason(QUOTA_EXHAUSTED) trigger automatic credential rotation. - Error Classification: HTTP errors are categorized by
parseRateLimitReason(packages/ai/src/error/rate-limit.ts) intoQUOTA_EXHAUSTED(30m backoff / rotation),RATE_LIMIT_EXCEEDED(30s backoff),CONCURRENT_LIMIT(5s backoff), andMODEL_CAPACITY_EXHAUSTED(45s ± 15s backoff). Transient HTTP 408/409/429/5xx errors are retried byAnthropicMessagesClient(packages/ai/src/providers/anthropic-client.ts), respectingretry-after-ms/retry-afterheaders.
Catalog model handling
- Model Identity & Classification:
isClaudeModelId(packages/catalog/src/identity/family.ts) uses regex/(^|[/.])claude[-.]/ito identify bare, namespaced (anthropic/claude-*), and Bedrock (us.anthropic.claude-*) Claude models.parseAnthropicModel(packages/catalog/src/identity/classify.ts) parses model kind (Opus, Sonnet, Fable, Mythos), version, and variant. Feature checks includeanthropicModelSupportsThinking(v>=3.7),supportsAdaptiveThinkingDisplay(v>=4.7),supportsMidConversationSystemMessages(v>=4.8), andisAnthropicFableOrMythosModel. - Provider Descriptor:
CATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts) defines the Anthropic provider entry withdefaultModel: "claude-opus-4-8",envVars: ["ANTHROPIC_API_KEY"], and model manager optionsanthropicModelManagerOptions. - Thinking Configuration:
resolveModelThinking(packages/catalog/src/model-thinking.ts) derives thinking capabilities. Modern adaptive models (Opus 4.7+, Sonnet 5+) useFIVE_TIER_EFFORTS_LOW_TO_MAX([low, medium, high, xhigh, max]), while older adaptive models useFOUR_TIER_EFFORTS_LOW_TO_MAX. Effort levels map to Anthropic wire values viamapEffortToAnthropicAdaptiveEffort. - Pricing & Multipliers:
COPILOT_PREMIUM_MULTIPLIERSinpackages/catalog/scripts/generate-models.tsassigns premium multipliers for GitHub Copilot Anthropic models (e.g.claude-opus-4.6: 3x,claude-haiku-4.5: 0.33x) during model catalog generation.
Google Gemini
Google Gemini integrations use REST/SSE over HTTP (POST https://generativelanguage.googleapis.com/v1beta/models/{model}:streamGenerateContent?alt=sse). Core provider entry points are packages/ai/src/providers/google.ts (streamGoogle), packages/ai/src/providers/google-shared.ts (streamGoogleGenAI, buildGoogleGenerateContentParams, convertMessages, consumeGoogleStream), and packages/ai/src/providers/google-types.ts.
Special casings
generateContentprotocol: System prompts are lifted into{ systemInstruction: { parts: [{ text }] } }inbuildGoogleGenerateContentParams. Tools are formatted intotools[].functionDeclarationsusingparametersJsonSchema(sanitized vianormalizeSchemaForGoogleinpackages/ai/src/utils/schema/normalize.ts).thinkingConfigmapping:buildGoogleGenerateContentParamssetsincludeThoughts: !options.hideThinkingSummary. Gemini 3 models mapoptions.thinking.leveltothinkingLevel(THINKING_LEVEL_UNSPECIFIED,MINIMAL,LOW,MEDIUM,HIGH). Gemini 2.x models mapoptions.thinking.budgetTokenstothinkingBudget. Cloud Code Assist providers (google-gemini-cli.ts) mapthinking.suppressto explicitincludeThoughts: falsewith level/budget when disabled (suppressWhenOff).- Function call ID synthesis & Vertex AI strip:
nextToolCallIdingoogle-shared.tsgenerates unique IDs (${name}_${Date.now()}_${++toolCallCounter}) when IDs are missing or duplicate.supportsFunctionPartIdenablesfunctionCall.id/functionResponse.idpropagation forclaude-models or Gemini 3 models (isGemini3Model).google-vertexAPI rejectsidfields in function parts, sogoogle-shared.tsstripspart.functionCall.idandpart.functionResponse.idfor Vertex requests. - Contiguous
functionResponserule: Gemini requires parallel tool call results to reside in a single contiguoususerrole message.convertMessagesingoogle-shared.tsinspectslastContentand mergesfunctionResponseparts into existinguserturns (lastContent.parts.push(functionResponsePart)). - Multimodal function responses by version: Gemini 3+ models (
supportsMultimodalFunctionResponsechecked viagetGeminiMajorVersion >= 3) support inline tool output images nested directly insidefunctionResponse.parts. Gemini < 3 models buffer tool images intopendingToolImagePartsand flush them in a separate subsequentusertext/image turn. - Safety settings & Prompt feedback: Safety blocks in
PromptFeedback(blockReason,blockReasonMessage) throwAIError.ProviderResponseErrorwithkind: "content-blocked".FinishReasonvalues (SAFETY,BLOCKLIST,PROHIBITED_CONTENT,SPII,IMAGE_SAFETY,RECITATION,MALFORMED_FUNCTION_CALL,UNEXPECTED_TOOL_CALL,NO_IMAGE,OTHER) map tostopReason: "error"inmapStopReason.
Stream behavior
streamGenerateContentSSE protocol: Streams are consumed viareadSseJson<GenerateContentResponse>instreamGoogleGenAI.- Thought parts & signature retention:
isThinkingPartidentifies reasoning text whenpart.thought === true. Encryptedpart.thoughtSignaturefields are preserved across deltas usingretainThoughtSignature. InconvertMessages, thought signatures are retained only when message provider/model match the target (msg.provider === model.provider && msg.model === model.id) and passisValidThoughtSignature(base64 check). Gemini 3 tool calls lacking a signature fall back toSKIP_THOUGHT_SIGNATURE("skip_thought_signature_validator"). - Empty response retry loop:
streamGoogleGenAIguards against Gemini returningfinishReason: STOPwith blank content without calling tools.hasMeaningfulGoogleContentvalidates output; if empty,streamGoogleGenAIretries up toMAX_EMPTY_STREAM_RETRIES(2 retries, 3 total attempts) with exponential backoff (EMPTY_STREAM_BASE_DELAY_MS * 2^attempt) after resetting stream output viaresetGoogleStreamOutputForRetry. - Thinking loop guard: Implemented in
packages/ai/src/utils/thinking-loop.ts(ThinkingLoopDetector). Gemini, DeepSeek, and Grok model-id families are monitored before tool calls for three runaway shapes:- Verbatim tail repetition (
VERBATIM_TAIL_WINDOW = 250, >= 180 repeated chars). - Near-duplicate segments (trigram Jaccard similarity >= 0.8 across last 16 segments).
- Progress-lexicon stall (novelty <= 0.2 without new concrete reference anchors over 8 consecutive segments).
- Gemini’s
GEMINI_HEADER_RUNAWAY_THRESHOLD = 24halts streams emitting excessive titled reasoning summaries without acting. Triggers emit a synthetic retryableerrortagged withAIError.Flag.ThinkingLoop.
- Verbatim tail repetition (
- Finish reason mapping & incomplete streams:
candidate.finishReasonis mapped viamapStopReason;stop/lengthreasons upgrade totoolUseif output contains tool calls. Drops withoutfinishReasonthrowProviderResponseErrorwithkind: "incomplete-stream". - UsageMetadata accounting: Attached to trailing chunks in
consumeGoogleStream.inputis calculated aspromptTokenCount - (cachedContentTokenCount || 0);outputascandidatesTokenCount + (thoughtsTokenCount || 0);cacheReadascachedContentTokenCount || 0; andreasoningTokensasthoughtsTokenCount. Token costs are computed viacalculateCost(model, output.usage).
Auth & usage
- Credential source: Directly authenticates via
x-goog-api-key: apiKeyheader (orGEMINI_API_KEYenvironment variable retrieved viagetEnvApiKey(model.provider)inpackages/ai/src/providers/google.ts). - Usage tracker:
googleGeminiCliUsageProviderinpackages/ai/src/usage/gemini.tsmonitors OAuth-backed Cloud Code Assist usage by callingPOST /v1internal:loadCodeAssist(for project resolution) andPOST /v1internal:retrieveUserQuota. Quota buckets are mapped to tiers (Flash,Pro,3-Flash) with remaining fraction usage percentages and reset windows (parseWindow).
Catalog model handling
- Identity & classification:
parseGeminiModelinpackages/catalog/src/identity/classify.tsparses model IDs matchinggemini-{version}-{kind}(with optional-previewsuffix), returningGeminiModel(family: "gemini",kind: "pro" | "flash",version: SemVer). - Thinking metadata & levels:
packages/catalog/src/model-thinking.tsconfigures thinking options usingThinkingLevelenum strings (THINKING_LEVEL_UNSPECIFIED,MINIMAL,LOW,MEDIUM,HIGH). Effort ladders are defined for Gemini 3 models:GEMINI_3_PRO_EFFORTS([low, high]) andGEMINI_3_FLASH_EFFORTS([minimal, low, medium, high]). - Descriptors & discovery: Configured in
packages/catalog/src/provider-models/descriptors.ts(CATALOG_PROVIDERSentry forgoogle, default modelgemini-3.1-pro-preview,GEMINI_API_KEY). Dynamic discovery inpackages/catalog/src/discovery/gemini.ts(fetchGeminiModels) fetchesGET /v1beta/models?key=..., filtering forgenerateContentmethods and parsinginputTokenLimitandoutputTokenLimit. - Pricing & Antigravity backfill: Base prices are calculated via
calculateCost. Inscripts/generated-policies.tsandscripts/generate-models.ts,google-antigravitymodels report $0 list price upstream and are backfilled usingANTIGRAVITY_PRICING_PEERS(["google", "google-vertex", "anthropic"]), resolving Gemini aliases viaANTIGRAVITY_PRICING_ID_ALIASES(e.g.gemini-3-flash->gemini-3-flash-preview).
Google Vertex AI
The Google Vertex AI provider enables streaming generation for Gemini models hosted on Google Cloud Vertex AI as well as third-party models (such as Anthropic Claude) served via Vertex endpoints. Entry points include streamGoogleVertex in packages/ai/src/providers/google-vertex.ts for Gemini models (API type "google-vertex"), streamAnthropic via createVertexAuthenticatedFetch in packages/ai/src/stream.ts for Claude models (API type "anthropic-messages"), and ADC authentication in packages/ai/src/providers/google-auth.ts. Transport uses HTTPS REST / SSE with either Application Default Credentials (ADC OAuth Bearer tokens) or Vertex Express Mode API key (x-goog-api-key).
Special casings
- Endpoint & Project/Location Resolution: In ADC mode (
packages/ai/src/providers/google-vertex.ts), request URLs followhttps://${host}/v1/projects/${project}/locations/${location}/publishers/google/models/${model.id}:streamGenerateContent?alt=sse.projectis resolved fromoptions.project,$env.GOOGLE_CLOUD_PROJECT,$env.GCP_PROJECT, or$env.GCLOUD_PROJECT(throwsConfigurationErrorif missing).locationis resolved fromoptions.location,$env.GOOGLE_VERTEX_LOCATION,$env.GOOGLE_CLOUD_LOCATION, or$env.VERTEX_LOCATION(throwsConfigurationErrorif missing). In Express Mode (API Key mode viaoptions.apiKeyor$env.GOOGLE_CLOUD_API_KEY), URL followshttps://${host}/v1/publishers/google/models/${model.id}:streamGenerateContent?alt=ssewithx-goog-api-keyheader and defaultslocationto"global"with global endpoint fallback if an ambient region host fails. - Endpoint Host Resolution:
resolveVertexEndpointHost(location)inpackages/catalog/src/hosts.tsmaps locations to hostnames:"global"→aiplatform.googleapis.com; multi-regions"eu"/"us"→aiplatform.{location}.rep.googleapis.com(preventing 404s from standard interpolation); regional (e.g."us-central1","europe-west4") →${location}-aiplatform.googleapis.com. - Function Call & Response ID Stripping:
supportsFunctionPartId(model)inpackages/ai/src/providers/google-shared.tsreturnsfalseforgoogle-vertex.convertMessagesexplicitly deletespart.functionCall.idandfunctionResponsePart.functionResponse.idbefore wire serialisation because Vertex AI returns400 INVALID_ARGUMENTwhen function parts contain anidfield. - Safety Settings Defaults:
streamGoogleVertexinpackages/ai/src/providers/google-vertex.tsautomatically injects safety settings disabling all harm categories (HARM_CATEGORY_HATE_SPEECH,HARM_CATEGORY_DANGEROUS_CONTENT,HARM_CATEGORY_SEXUALLY_EXPLICIT,HARM_CATEGORY_HARASSMENTset tothreshold: "OFF") intoparams.config.safetySettingsif unconfigured. - Service Tier Priority Header: Direct
serviceTierrequest-body fields are ignored by Vertex;options.serviceTier === "priority"is transmitted as the request headerX-Vertex-AI-LLM-Shared-Request-Type: priority(google-vertex.ts).flexhas no documented control and is a no-op. - Cached Content Passthrough: Passes caller-supplied
cachedContentresource names opaquely intoparams.config.cachedContent(google-shared.ts), bypassing creation/refresh lifecycle.
Stream behavior
- Gemini Streaming Execution: Delegated to
streamGoogleGenAIandconsumeGoogleStreaminpackages/ai/src/providers/google-shared.tswithretainTextSignature: true. Handles SSE chunk parsing, text/thinking block aggregation (thoughtSignature), tool-call ID synthesis (generating IDs when Vertex omits them), and finish reasons. - Anthropic-on-Vertex RawPredict Handling:
isGoogleVertexAuthenticatedModelinpackages/ai/src/stream.tsmatchesmodel.provider === "google-vertex"withanthropic-messagesAPI and:streamRawPredictbaseUrl. Requests route throughstreamAnthropicusingapiKey: "vertex-adc"andcreateVertexAuthenticatedFetch. - Anthropic Request Rewriting:
createVertexAuthenticatedFetchinpackages/ai/src/stream.tsinvokesresolveVertexRequestto substitute{project}and{location}placeholders in URL, normalizes:streamRawPredict/v1/messagespath to:streamRawPredict, and appliestransformVertexAnthropicBodyto strippayload.model(encoded in URL path) and injectpayload.anthropic_version = "vertex-2023-10-16"into the JSON body. - Anthropic Effort Beta Gating: Vertex
rawPredictrejectsanthropic-betaHTTP headers with a 400 error. Inpackages/ai/src/providers/anthropic.ts,effortBeta(effort-2025-11-24),contextManagementBeta, andoutput_config.effortfields are gated off formodel.provider === "google-vertex". Fallback payloads inanthropic.tsalso scruboutput_config.efforton Vertex requests (#5614).
Auth & usage
- ADC Resolution Ladder:
packages/ai/src/providers/google-auth.tsresolves credentials in priority order:GOOGLE_APPLICATION_CREDENTIALSenv pointing to JSON credentials file. Supportstype: "service_account"(RS256 JWT assertion signed via WebCryptocrypto.subtleexchanged athttps://oauth2.googleapis.com/token),type: "authorized_user"(refresh-token exchange), ortype: "impersonated_service_account"(exchanges source credentials then calls GCP IAMgenerateAccessToken).- User ADC file
~/.config/gcloud/application_default_credentials.json(authorized_userflow). - GCE / Cloud Run metadata server (
http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token).
- Explicit Access Token Override:
GOOGLE_CLOUD_ACCESS_TOKENorCLOUDSDK_AUTH_ACCESS_TOKENenvironment variables bypass file/metadata lookup and caching entirely. - Token Caching & In-flight Deduplication: Access tokens are stored in
tokenCache(Map) keyed by resolved source and refreshedGOOGLE_VERTEX_REFRESH_SKEW_MSbefore expiry (default 60s). Concurrent resolution requests share a single in-flight promise ininflightMap, bounded bySHARED_TOKEN_RESOLVE_TIMEOUT_MS(30s). Individual callers race their abort signals against the shared promise viaraceWithSignalso one caller’s abort does not cancel batch resolution. OAuth scope requested:https://www.googleapis.com/auth/cloud-platform. - Usage & Token Normalization:
consumeGoogleStreaminpackages/ai/src/providers/google-shared.tsextractsusageMetadatafrom responses:inputis calculated aspromptTokenCount - cachedContentTokenCount,outputascandidatesTokenCount + thoughtsTokenCount,cacheReadascachedContentTokenCount, andreasoningTokensasthoughtsTokenCount. Passes normalized usage tocalculateCost(model, output.usage).
Catalog model handling
- Catalog API Resolution:
resolveGoogleVertexApiinpackages/catalog/src/provider-models/openai-compat.tsroutes@ai-sdk/google-vertex/anthropicnpm package models toapi: "anthropic-messages"withGOOGLE_VERTEX_ANTHROPIC_BASE_URL(https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/publishers/anthropic/models/{model}:streamRawPredict). Models with slash IDs or@ai-sdk/openai-compatibleroute toapi: "openai-completions". All other models route toapi: "google-vertex"withGOOGLE_VERTEX_BASE_URL(https://{location}-aiplatform.googleapis.com). - Provider Descriptor:
packages/catalog/src/provider-models/descriptors.tsregistersid: "google-vertex"withdefaultModel: "gemini-3.1-pro-preview". - Registry Credentials Guard:
googleVertexProviderinpackages/ai/src/registry/google-vertex.tsexportsenvKeys(). Returns$env.GOOGLE_CLOUD_API_KEYif set, orAUTHENTICATED_SENTINEL("<authenticated>") if ADC credentials exist (hasVertexAdcCredentials()) AND project env (GOOGLE_CLOUD_PROJECT/GCP_PROJECT/GCLOUD_PROJECT) AND location env (GOOGLE_VERTEX_LOCATION/GOOGLE_CLOUD_LOCATION/VERTEX_LOCATION) are present. Returnsundefinedotherwise, preventing models from appearing in catalog listings without proper auth.
Google Gemini CLI / Antigravity
Google Cloud Code Assist (CCA) transport wrapper accessing Gemini and Claude models over /v1internal:streamGenerateContent SSE endpoints. Implementation spans packages/ai/src/providers/google-gemini-cli.ts (shared execution engine, request construction, stream parsing, and planning leak filters), packages/ai/src/registry/google-gemini-cli.ts & packages/ai/src/registry/google-antigravity.ts (provider definitions and OAuth lazy-loaders), packages/ai/src/registry/oauth/google-gemini-cli.ts & google-antigravity.ts (OAuth login flows, project discovery, and onboarding), packages/ai/src/usage/google-antigravity.ts & packages/ai/src/usage/gemini.ts (quota tracking and credential ranking), and packages/catalog/src/discovery/antigravity.ts (model catalog discovery).
Special casings
- CCA JSON Schema Normalization:
normalizeSchemaForCCA(packages/ai/src/utils/schema/normalize.ts) recursively strips unsupported JSON Schema keywords (propertyNames,additionalProperties,patternProperties,$schema,title,description, etc.) to prevent HTTP 400 errors from CCA. Accurately tracks context inside properties namedpropertiesto avoid premature re-assertion of property stripping. Tools are normalized inbuildRequest(packages/ai/src/providers/google-gemini-cli.ts) vianormalizeSchemaForCCA. - Function Calling Config Mode: Defaults to
functionCallingConfig: { mode: "VALIDATED" }for Antigravity inbuildRequest. Claude models on Antigravity forceVALIDATEDmode even when context contains no declared tools (isClaudeModel). Single named tool choice (options.toolChoice) setsmode: "ANY"withallowedFunctionNames: [...]. - Provider Protocol & Request Envelope:
- Endpoints:
google-gemini-clidefaults tohttps://cloudcode-pa.googleapis.com.google-antigravityuses auto-failover acrosshttps://daily-cloudcode-pa.googleapis.com(primary) andhttps://daily-cloudcode-pa.sandbox.googleapis.com(sandbox), persistinglastGoodEndpointinAntigravityProviderSessionState. - Headers & User-Agent:
google-gemini-clisendsgetGeminiCliHeaders()(GeminiCLI/0.46.0/<modelId> (platform; arch; terminal)).google-antigravitysendsgetAntigravityUserAgent()(antigravity/hub/2.1.4 <os>/<arch>). Reasoning Claude models on Antigravity sendanthropic-beta: interleaved-thinking-2025-05-14(needsClaudeThinkingBetaHeader). - System Instructions: Antigravity tags system instructions with
role: "user". Claude and Gemini 3 models prependANTIGRAVITY_SYSTEM_INSTRUCTION(“You are Antigravity, a powerful agentic AI coding assistant…”) viashouldInjectAntigravitySystemInstruction. - Request Envelope & Session State: Antigravity wraps requests in
buildAntigravityRequestEnvelope:project(projectId),requestId(agent/<agentId>/<ts>/<trajectoryId>/<step>),userAgent(antigravity),requestType(agent), andlabels(last_step_index,model_enum,trajectory_id,used_claude,used_claude_conservative,last_execution_id). State maintains monotonicstepIndex, persistentagentId,trajectoryId, and signed-decimalsessionId(deriveAntigravitySessionId). - Wire Profiles:
getAntigravityModelWireProfile(packages/catalog/src/wire/gemini-headers.ts) maps wire IDs tomaxOutputTokensandmodel_enum. Claude wire IDs capmaxOutputTokensat64000(backend rejects >64000 with 400).
- Endpoints:
- Thinking Configuration & Wire Suppression: Gemini 2.x models send
thinkingConfig.thinkingBudget, while Gemini 3 models sendthinkingConfig.thinkingLevel. When reasoning is disabled for models withthinking.suppressWhenOff,buildRequestemits explicit wire suppression (includeThoughts: falsewith level/budget). OmittingthinkingConfigcauses CCA to re-apply server defaults and silently bill thinking tokens.
Stream behavior
- Transport & SSE Protocol: Consumes
POST /v1internal:streamGenerateContent?alt=sseviareadSseJson<CloudCodeAssistResponseChunk>. Chunks delivercandidates[0].content.parts,usageMetadata,modelVersion,responseId,promptFeedback, or top-levelerror. - In-band Errors & Block Reasons:
chunk.errorstatus/code >=400 throwsAIError.GeminiCliApiErrororAIError.ProviderResponseError.promptFeedback.blockReasonthrowsAIError.ProviderResponseErrorwithkind: "content-blocked". - Planning Leak Detection & Filtering: Flash models (
isFlashLeakModel) can stream raw JSON internal planning blocks into visible text parts.consumePlanningBufferchecks prefixes starting with{or"thought":usingisPlanningLeakPrefixandsplitLeadingJsonObject. If parsed JSON containsthought,call(matching active tool names),_i,paths,command, orpath/content, the object is classified askind: "leak"and stripped from visible output. - Thinking Parts & Signature Retention: Parts with
thought: trueorisThinkingPart()route to thinking blocks.thoughtSignatureon text, thinking, or toolCall parts is retained viaretainThoughtSignature. Inline<thinking>tags are processed usingStreamMarkupHealing. - Empty Stream Retry: Google models can return
finishReason: "STOP"with empty text parts and no tool call.hasMeaningfulGoogleContentchecks for non-empty text, thinking, or tool calls. Empty responses withstopReason === "stop"trigger up toMAX_EMPTY_STREAM_RETRIES(3 retries) with exponential backoff (EMPTY_STREAM_BASE_DELAY_MS = 1000ms) before failing (packages/ai/src/providers/google-gemini-cli.ts). - Pre-Response Watchdogs: Arms
armPreResponseTimeoutwithgetStreamFirstEventTimeoutMs(5-minute ceiling) to prevent hung HTTP proxy connections before the first SSE chunk arrives. Native Bun fetch pre-response timeout is disabled (timeout: false).
Auth & usage
- Credential Model & Token Expiry: Credentials stored as JSON (
parseGeminiCliCredentials):{ token, projectId, refreshToken, expiresAt, email }. AuthStorage is the sole refresh authority.shouldRefreshGeminiCliCredentialschecks token expiry with a 60s skew (ANTIGRAVITY_REFRESH_SKEW_MS/GOOGLE_GEMINI_REFRESH_SKEW_MS). Stale tokens fail fast before making HTTP requests. - OAuth Installed-App Flow: Callback ports are
8085(google-gemini-cli,/oauth2callback) and51121(google-antigravity,/oauth-callback). Supports paste code flow (pasteCodeFlow: true). Authorizes via Google PKCE OAuth 2.0 (accounts.google.com/o/oauth2/v2/auth). Antigravity scopes includecloud-platform,userinfo.email,userinfo.profile,cclog, andexperimentsandconfigs. - Project Discovery & Onboarding:
google-gemini-cli(packages/ai/src/registry/oauth/google-gemini-cli.ts): callsPOST /v1internal:loadCodeAssistwith$GOOGLE_CLOUD_PROJECTfallback. If project absent, callsPOST /v1internal:onboardUserwithtierId(free-tier,legacy-tier,standard-tier) and pollsLongRunningOperationResponseviapollOperation(up toPOLL_MAX_ATTEMPTS = 24at 5s intervals). Detects VPC-SC restriction (SECURITY_POLICY_VIOLATED).google-antigravity(packages/ai/src/registry/oauth/google-antigravity.ts): callsPOST /v1internal:loadCodeAssistwith metadata{ ideType: "ANTIGRAVITY", platform: "PLATFORM_UNSPECIFIED", pluginType: "GEMINI" }. Onboards project viaonboardProjectWithRetriesup to 5 attempts (PROJECT_ONBOARD_MAX_ATTEMPTS) at 2s intervals.
- Usage & Quota Tracking (
google-antigravity):antigravityUsageProvider(packages/ai/src/usage/google-antigravity.ts) queriesPOST /v1internal:fetchAvailableModels. Normalizes quota buckets into daily (24h) and weekly (7d) windows. Deduplicates quotas into backend counter keys (Anthropic,Google,OpenAI).antigravityRankingStrategyscopes ranking by requested model family (getAntigravityCounterKeyForModel:claude-→ Anthropic,gemini-/gemma-→ Google,gpt-/openai/→ OpenAI), selecting stored OAuth credentials with available quota headroom. - Usage & Quota Tracking (
google-gemini-cli):googleGeminiCliUsageProvider(packages/ai/src/usage/gemini.ts) queriesloadCodeAssistandretrieveUserQuota, surfacing quota percentages per model tier (3-Flash,Flash,Pro).
Catalog model handling
- Provider Descriptors:
google-antigravity(default modelgemini-3.1-pro) andgoogle-gemini-cli(default modelgemini-3.1-pro-preview) are defined inCATALOG_PROVIDERSwithspecialModelManager: true(packages/catalog/src/provider-models/descriptors.ts), bypassing standard factories. - Model Resolution & Discovery:
googleAntigravityModelManagerOptions&googleGeminiCliModelManagerOptions(packages/catalog/src/provider-models/google.ts) invokefetchAntigravityDiscoveryModels(packages/catalog/src/discovery/antigravity.ts). - Identity & Thinking Metadata: Parsed as
family: "gemini"with kindspro/flash(packages/catalog/src/identity/classify.ts). Gemini 3.0+ models enforce mandatory reasoning (impliesMandatoryReasoninginmodel-thinking.ts). Efforts:GEMINI_3_PRO_EFFORTS([Low, High]) andGEMINI_3_FLASH_EFFORTS([Minimal, Low, Medium, High]). - Variant Collapsing: Effort-tier variants are collapsed into logical specs at discovery (
packages/catalog/src/variant-collapse.ts):gemini-3.5-flash: collapsesgemini-3.5-flash-extra-low,gemini-3.5-flash-low,gemini-3-flash-agent. Antigravity budget mode maps Minimal/Low →extra-low(1000 tokens), Medium →low(4000 tokens), High →agent(10000 tokens). Gemini CLI maps to level transport. Alias:gemini-3-flash.gemini-3.6-flash: collapsesgemini-3.6-flash-low,-medium,-high,-tieredintogemini-3.6-flashwithgoogle-levelmode.gemini-3.1-pro: collapsesgemini-3.1-pro-low,gemini-pro-agent,gemini-3.1-pro-high. High effort routes togemini-pro-agentbecause upstreamgemini-3.1-pro-highdeployment returns INVALID_ARGUMENT on streamGenerateContent.claude-*: bare and-thinkingpairs collapse intoclaude-*usingthinkingPair(preserveAbsentEffortRoutes: true).
- Catalog Generator Integration:
fetchAntigravityModels(packages/catalog/scripts/generate-models.ts) fetches models via discovery token (falling back fromgoogle-antigravitytogoogle-gemini-cliOAuth credentials) and fixesbaseUrltohttps://daily-cloudcode-pa.googleapis.com.
Amazon Bedrock
Amazon Bedrock (amazon-bedrock provider, bedrock-converse-stream API) communicates directly with bedrock-runtime.{region}.amazonaws.com/model/{modelId}/converse-stream via HTTPS POST requests using AWS SigV4 signatures or explicit bearer tokens, decoding binary application/vnd.amazon.eventstream responses. The implementation bypasses heavy AWS SDK dependencies (@aws-sdk/*, @smithy/*), executing native fetches signed with WebCrypto and decoded via a lightweight eventstream parser. Entry modules comprise packages/ai/src/providers/amazon-bedrock.ts (streamBedrock), packages/ai/src/registry/amazon-bedrock.ts (amazonBedrockProvider), packages/ai/src/registry/aws.ts, packages/ai/src/providers/aws-credentials.ts (resolveAwsCredentials), packages/ai/src/providers/aws-eventstream.ts (decodeEventStream), and packages/ai/src/providers/aws-sigv4.ts (signRequest).
Special casings
- Converse API Payload & Message Mapping: Requests build a
ConverseStreamRequestwithmessages,system,inferenceConfig(maxTokens,temperature,topP),toolConfig, andadditionalModelRequestFields. System prompts normalize toSystemContent[]with text blocks andCachePointmarkers ({ cachePoint: { type: "default", ttl?: "1h" } }). User content maps totext,image(jpeg/png/gif/webpbase64 viacreateImageBlock),toolResult, orcachePoint. Bedrock requires consecutive tool result blocks to be consolidated into a singleuserroleWireMessage(convertMessagesloops to merge adjacenttoolResultturns). Empty text blocks and empty content arrays are filtered to avoid HTTP 400 validation failures. - NO_TOOLS_SENTINEL (
__no_tools__): Bedrock validates that any request containing priortoolUseortoolResultblocks must supply atoolConfig. When tools are disabled (toolChoice: "none") or empty on a turn with tool history,planToolConfiginjects a placeholder toolNO_TOOLS_SENTINEL(name: "__no_tools__", dummy schema). Per-request flagsentinelInjectedtracks injection (so caller tools named__no_tools__work normally). WhensentinelInjectedis true,handleContentBlockStartignores synthetic tool-use start events, andmessageStopdemotesstopReason: "tool_use"to"stop". - Thinking & Reasoning (
additionalModelRequestFields):anthropic-adaptivemodels (Claude Opus 4.7+, Sonnet/Opus 5, Fable/Mythos 5): mapped to{ thinking: { type: "adaptive", display? }, output_config: { effort } }viamapEffortToAnthropicAdaptiveEffort.thinkingDisplaydefaults to"summarized"on display-supporting models so silent reasoning streams under Anthropic’s"omitted"default are avoided (issue #1373).- Budget-mode models (e.g. Claude 3.7 / 4.6): mapped to
{ thinking: { type: "enabled", budget_tokens, display }, anthropic_beta? }. Setsanthropic_beta: ["interleaved-thinking-2025-05-14"]wheninterleavedThinkingis true. - Forced Tool Choice Conflict: Bedrock rejects thinking when
toolChoiceforces tool execution (anyor named{ tool: { name } }).streamBedrockclearsadditionalModelRequestFieldswhen forced tool choice is active. - Thinking Signatures & Demotion: Assistant thinking blocks without
thinkingSignatureon Claude models (supportsThinkingSignature) are demoted to text viarenderDemotedThinking. Non-Claude models (Nova, Titan, Llama, Mistral) reject thinking signatures and receive unsignedreasoningContent.
- Region & Inference-Profile Resolution:
resolveBedrockRegionresolves runtime regions in order: explicitoptions.region-> ARN-embedded region (inferRegionFromBedrockArn) -> ambient environment/profile region (resolveAwsAmbientRegion). For geo-prefixed cross-region inference profiles (us.,us-gov.,eu.,apac.,au.,jp.),regionServesGeoverifies ambient region compatibility; mismatched or missing ambient regions fallback to geo-default endpoints (INFERENCE_PROFILE_GEO_DEFAULT_REGION:us->us-east-1,us-gov->us-gov-west-1,eu->eu-west-1,apac->ap-southeast-1,au->ap-southeast-2,jp->ap-northeast-1).global.profiles use ambient region orus-east-1.
Stream behavior
- AWS Eventstream Binary Decoding: Framed as big-endian integers (
[total len u32][headers len u32][prelude CRC u32][headers][payload][message CRC u32]).decodeMessageinpackages/ai/src/providers/aws-eventstream.tschecks total length (minimum 16 bytes), computes IEEE 802.3 CRC32 viaBun.hash.crc32(bytes) >>> 0(crc32), and verifies both prelude (first 8 bytes) and message CRCs (entire frame minus 4 bytes). Header parser (parseHeaders) reads typed headers (bool, byte, short, int, long, byte-array, string, timestamp, uuid).decodeEventStreamyields messages from aReadableStream<Uint8Array>using a growable Uint8Array buffer and cancels reader lock on abort. - Event Dispatch & Error Handling: Stream messages carrying
:message-type = "event"dispatch:messageStart: verifiesrole === "assistant"and pushes streamstart.contentBlockStart: pushestoolcall_start(skipping sentinel).contentBlockDelta: pushestext_delta(creates text block if absent),toolcall_delta(accumulates JSON input delta inkStreamingPartialJson, throttled viaparseStreamingJsonThrottled), orthinking_delta(accumulates reasoning text and signature).contentBlockStop: parses tool JSON viaparseStreamingJsonand pushestext_end/thinking_end/toolcall_end.messageStop: mapsstopReason(end_turn/stop_sequence->stop,max_tokens/model_context_window_exceeded->length,tool_use->toolUse).metadata: extracts usage (inputTokens,outputTokens,cacheReadInputTokens,cacheWriteInputTokens) and invokescalculateCost.:message-type = "exception"extracts:exception-typeand error payload to throwBedrockApiError(400).:message-type = "error"extracts:error-codeand:error-message.
- Idle Watchdogs & Pre-Response Timeout: Bun’s native
fetchtimeout is disabled (timeout: false) to support long prefill prompts. Pre-response timeout is armed viaarmPreResponseTimeoutusingstreamFirstEventTimeoutMs. Bedrock streams send no ping/keepalive events during reasoning; catalog compat (packages/catalog/src/compat/bedrock.tsbuildBedrockCompat) setsstreamIdleTimeoutMsfloor to 600s for standard reasoning models and 900s for adaptive-thinking models (Claude Opus 4.7+, Sonnet/Opus 5, Fable 5).
Auth & usage
- Dual Auth Modes:
- Bearer Token: If
options.bearerToken,options.apiKey, or$env.AWS_BEARER_TOKEN_BEDROCKis present (resolveAwsBearerToken), setsAuthorization: Bearer <token>and bypasses SigV4 signing. - AWS SigV4 Signing:
signRequest(packages/ai/src/providers/aws-sigv4.ts) signs headers using WebCrypto (crypto.subtle). Computes SHA-256 payload digest (x-amz-content-sha256), date (x-amz-date), host, and security token (x-amz-security-token). Derives HMAC-SHA256 signing key chain (AWS4+secretAccessKey->kDate->kRegion->kService(“bedrock”) ->kSigning).
- Bearer Token: If
- 5-Tier Credential Resolution Chain:
resolveAwsCredentials(packages/ai/src/providers/aws-credentials.ts) caches resolved credentials perprofile\0region\0configkey with a 60s refresh skew (REFRESH_SKEW_MS) and single-flight inflight deduplication bounded by 30s timeout (SHARED_RESOLVE_TIMEOUT_MS). Chain precedence:- Environment Variables:
AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY, optionalAWS_SESSION_TOKEN. - Web Identity / OIDC:
AWS_WEB_IDENTITY_TOKEN_FILE,AWS_ROLE_ARN,AWS_ROLE_SESSION_NAME. Calls STSAssumeRoleWithWebIdentityonsts.{region}.amazonaws.com. - Shared Config / Profile (
~/.aws/credentials,~/.aws/configparsed viaparseAwsIni): Static keys (file session tokens capped at 5 min TTL viaFILE_SESSION_CREDS_TTL_MS), AWS SSO (sso_account_id,sso_role_name, legacysso_start_url/sso_regionorsso-sessionblock; reads cached token from~/.aws/sso/cache/*.jsonand callsportal.sso.{ssoRegion}.amazonaws.com/federation/credentials), orcredential_process(spawns external process using POSIX tokenizationtokenizeCredentialProcessCommand; Windows.cmd/.batrouted throughcmd.exe /c; expects Version 1 JSON envelope). - ECS / Container:
AWS_CONTAINER_CREDENTIALS_RELATIVE_URI(onhttp://169.254.170.2/) orAWS_CONTAINER_CREDENTIALS_FULL_URIwith optional auth token/file. - EC2 IMDSv2:
169.254.169.254(or IPv6[fd00:ec2::254]), requests PUT token fromlatest/api/tokenwith 1s timeout (IMDS_TIMEOUT_MS).
- Environment Variables:
- Cache Invalidation & Registry Status: On 401/403 HTTP response,
streamBedrockcallsinvalidateAwsCredentialCache({ profile, region })to drop cached credentials so subsequent turns re-resolve fresh credentials.amazonBedrockProvider(packages/ai/src/registry/amazon-bedrock.ts) evaluateshasAwsCredentialSource()(packages/ai/src/registry/aws.ts) to returnAUTHENTICATED_SENTINELwhen valid credentials or environment tokens exist.
Catalog model handling
- Descriptor Registration: Registered in
CATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts) with default modelus.anthropic.claude-opus-4-8. - models.dev Mapping & Cross-Region Profiles:
MODELS_DEV_PROVIDER_DESCRIPTORS(packages/catalog/src/provider-models/openai-compat.ts) mapsmodelsDevKey: "amazon-bedrock"to APIbedrock-converse-stream.bedrockCrossRegionIdprefixesglobal.orus.for matching models. Foranthropic.claude-*models,transformModelautomatically emits EU (eu.) and AWS GovCloud (us-gov.) cross-region inference-profile spec variants. Non-tool and legacy models (ai21.jamba,titan-text-express,mistral-7b) are filtered out. - Mantle & Undocumented Model Exclusion: Bedrock Mantle is a distinct provider (
bedrock-mantle,openai-responsesAPI,https://bedrock-mantle.{region}.api.aws/openai/v1) covered by a separate subagent. Catalog build policies (packages/catalog/scripts/generated-policies.ts) rundropBedrockMantleOpenAIModelsto exclude Mantle OpenAI model rows (openai.gpt-5.4,5.5,5.6-luna,sol,terra) fromamazon-bedrock.dropUnsupportedBedrockGeoIdsprunesjp.anthropic.claude-opus-5(listed upstream on models.dev but unsupported and rejected by AWS Bedrock). - Prompt Caching & Thinking Compat:
buildBedrockCompat(packages/catalog/src/compat/bedrock.ts) maps model IDs to explicit prompt caching contracts (promptCacheMode:explicitornone, minimum token thresholds 512, 1024, 2048, 4096;supportsLongPromptCacheRetention1h vs 5m; maximum 4 checkpoints).inferThinkingControlMode(packages/catalog/src/model-thinking.ts) classifies Claude 4.6+ adaptive models asanthropic-adaptive(settingsupportsDisplay: true), Opus 4.5 asanthropic-budget-effort, and non-adaptive models asbudget. Pricing is generated and materialized intopackages/catalog/src/models.json.
Amazon Bedrock Mantle
Amazon Bedrock Mantle is AWS’s gateway endpoint serving OpenAI-compatible models (such as openai.gpt-5.4, openai.gpt-5.5, and openai.gpt-5.6 Luna/Sol/Terra variants) over the OpenAI Responses API (openai-responses) protocol rather than Bedrock’s native Converse JSON transport (amazon-bedrock). Requests target region-interpolated endpoints (https://bedrock-mantle.{region}.api.aws/openai/v1) with OpenAI Responses API payloads (/responses). Entry modules are packages/ai/src/providers/bedrock-mantle.ts, packages/ai/src/registry/bedrock-mantle.ts, and catalog setup in packages/catalog/src/provider-models/openai-compat.ts.
Special casings
- Endpoint Structure: Unlike standard Bedrock Converse endpoints (
bedrock-runtime.{region}.amazonaws.com), Mantle requests targethttps://bedrock-mantle.{region}.api.aws/openai/v1. The{region}template placeholder inmodel.baseUrlis dynamically replaced at request preparation time inprepareBedrockMantleRequest(packages/ai/src/providers/bedrock-mantle.ts). - Region Resolution Hierarchy: Region substitution in
resolveAwsRegion(packages/ai/src/utils/aws-profile.ts) evaluates in order: explicitproviderOptions.region->AWS_REGION->AWS_DEFAULT_REGION-> region from active AWS shared-config profile in~/.aws/config(resolveAwsProfileRegion) -> fallback default"us-east-1". - 401/403 Credential Invalidation: When using SigV4 signed requests in
createSignedFetch(packages/ai/src/providers/bedrock-mantle.ts), an HTTP 401 or 403 response triggersinvalidateAwsCredentialCache({ profile, region })(packages/ai/src/providers/aws-credentials.ts) so subsequent attempts re-resolve fresh credentials from profile, environment, or STS roles. - Registry Sentinel & Auth Flag:
bedrockMantleProviderinpackages/ai/src/registry/bedrock-mantle.tssetsallowsMissingApiKey: true. When ambient AWS credentials exist (hasAwsCredentialSourceinpackages/ai/src/registry/aws.ts),resolveAwsRegistryApiKeyreturnsAUTHENTICATED_SENTINEL.resolveAwsBearerTokenstrips this sentinel value so SigV4 authentication is selected unless an actual bearer token is present. - Generator Model Drop Policy: In
packages/catalog/scripts/generated-policies.ts,dropBedrockMantleOpenAIModelsfilters outopenai.gpt-5.*rows from theamazon-bedrockprovider (where upstreammodels.devincorrectly assigns them under Bedrock Converse) so that only workingbedrock-mantleResponses API models are exposed.
Stream behavior
- Transport: Delegated to the
openai-responsesprovider pipeline (packages/ai/src/providers/openai-responses.ts), consuming SSE stream events likeresponse.created,response.text.delta,response.output_item.added, andresponse.completed. - Reasoning & Thinking Effort: Configured via
BEDROCK_MANTLE_GPT_5_X_THINKINGandBEDROCK_MANTLE_GPT_5_6_THINKING(packages/catalog/src/provider-models/openai-compat.ts) supporting effort levels (low,medium,high,xhigh,max). Reasoning content is streamed inopenai-responsesreasoning delta frames. - Error Handling: Non-2xx SSE streams pass error status codes back to the stream result handler; 401/403 status codes invalidate the cached AWS credential state in
createSignedFetch.
Auth & usage
- Dual Authentication Modes:
- Bearer Token: Evaluated by
resolveBearerToken(packages/ai/src/providers/bedrock-mantle.ts). Active whenAWS_BEARER_TOKEN_BEDROCK,providerOptions.bearerToken, or an explicit non-sentinelapiKeyis provided.createBedrockMantleAuthenticatedFetchinjectsAuthorization: Bearer <token>. - AWS SigV4 Signing: Active when no bearer token exists but ambient credentials pass
hasAwsCredentialSource. Request headers are signed bysignRequest(packages/ai/src/providers/aws-sigv4.ts) using service name"bedrock-mantle", settingAuthorization: AWS4-HMAC-SHA256 ...andx-amz-security-token(when using session credentials).
- Bearer Token: Evaluated by
- Authentication Precedence: Bearer token takes precedence over SigV4 signing when both are available.
- Usage Tracking: Input, output, cached, and reasoning token usages are parsed directly from the standard OpenAI Responses wire payload (
usage.input_tokens,usage.output_tokens,usage.input_token_details.cached_tokens,usage.output_token_details.reasoning_tokens) byopenai-responses.
Catalog model handling
- Provider Descriptor: The
bedrock-mantledescriptor inpackages/catalog/src/provider-models/descriptors.tssetsdefaultModel: "openai.gpt-5.6-terra",envVars: ["AWS_BEARER_TOKEN_BEDROCK"], anddynamicModelsAuthoritative: true. - Static Seeds: Pre-bundled in
BEDROCK_MANTLE_STATIC_MODELS(packages/catalog/src/provider-models/openai-compat.ts) with 5 OpenAI models (openai.gpt-5.4,openai.gpt-5.5,openai.gpt-5.6-luna,openai.gpt-5.6-sol,openai.gpt-5.6-terra) defining context windows (272,000), max tokens (128,000), pricing structures, and thinking effort specs. - Authenticated Model Discovery:
prepareModelDiscoveryinpackages/ai/src/registry/bedrock-mantle.tsrequires a valid bearer token (resolveAwsBearerToken). If unauthenticated or SigV4-only,authenticated: falseis returned and discovery is bypassed.- When authenticated, discovery strips
/openai/v1to callhttps://bedrock-mantle.{region}.api.aws/v1/modelsviafetchOpenAICompatibleModels.
- Authoritative Dynamic Model Replacement:
dynamicModelsAuthoritative: trueinbedrockMantleModelManagerOptionscauses successful dynamic discovery responses to replace static seeds entirely, pruning models not enabled for the AWS account/token. - Reference Attribute Merging:
mapWithBundledReferencemerges statically defined costs, thinking configs, and context windows onto dynamically discovered model definitions matchingBEDROCK_MANTLE_MODEL_BY_ID.
Kimi Code
Kimi Code (kimi-code) and Moonshot (moonshot) provide access to Moonshot AI’s model family through dual-transport execution—wrapping OpenAI-compatible chat completions (/coding/v1/chat/completions) and Anthropic-compatible messages (/coding/v1/messages). Entry points are packages/ai/src/providers/kimi.ts (streamKimi) and packages/ai/src/providers/openai-anthropic-shim.ts (streamOpenAIAnthropicShim), with model discovery and catalog descriptors configured in packages/catalog/src/provider-models/descriptors.ts and packages/catalog/src/provider-models/openai-compat.ts.
Special casings
- Dual Transport Routing:
streamKimidelegates tostreamOpenAIAnthropicShiminpackages/ai/src/providers/openai-anthropic-shim.ts, selecting format frommodel.compat.kimiApiFormator explicitoptions.formatinKimiOptions.anthropic: Reconstructs model spec withapi: "anthropic-messages", adjusts base URL viamodel.baseUrl.replace(/\/v1\/?$/, "")(https://api.kimi.com/coding), injectsgetKimiCommonHeaders(), maps thinking format toanthropic-adaptive, computes token budgets viaANTHROPIC_THINKING, and streams viastreamAnthropic.openai: Retainsmodel.baseUrl(https://api.kimi.com/coding/v1), injectsgetKimiCommonHeaders(), passesreasoningeffort, and streams viastreamOpenAICompletions.
- MFJS Tool Schema Validation:
toolSchemaFlavor: "moonshot-mfjs"is enforced inpackages/catalog/src/compat/openai.ts(buildOpenAICompat) for native Moonshot hosts (isMoonshotNative) and Kimi model IDs across third-party proxies. Moonshot Flavored JSON Schema collapses single-valueconstconstructs into single-elementenumarrays, infers explicittypeon bareenumdeclarations, and strips unsupported non-standard keywords to prevent 400 schema validation errors. - Forced Tool Choice Guards: Native K2.7 Code models (
kimi-k2.7-code,kimi-for-coding) and K3 models require server-side thinking (requiresThinkingEnabled = trueinpackages/catalog/src/compat/anthropic.ts). On the Anthropic surface, forced tool selection is downgraded toauto. On the OpenAI surface (packages/catalog/src/compat/openai.ts),supportsForcedToolChoiceisfalsefor mandatory-thinking K2.7 models (requiresEnabledThinking) but remainstruefor K3 (!isMoonshotKimiK3). - Turn & Token Invariants:
alwaysSendMaxTokens: isKimiModelinpackages/catalog/src/compat/openai.ts: Kimi calculates rate limits (TPM) based onmax_tokensrather than emitted tokens, requiring explicit max tokens on every request.requiresReasoningContentForToolCalls: True for Kimi models on non-OpenCode providers (packages/catalog/src/compat/openai.ts). Prior assistant tool-call turns must carryreasoning_contenton thinking follow-ups, with synthetic placeholder"."allowed when raw reasoning is missing (allowsSyntheticReasoningContentForToolCalls).requiresAssistantContentForToolCalls: Forces non-empty text content in assistant tool-calling turns.
Stream behavior
- Inband Control Tag & Thinking Scanning:
KimiInbandScannerinpackages/ai/src/dialect/kimi.tsprocesses raw output streams for XML-like tool control tags (<|tool_calls_section_begin|>,<|tool_call_begin|>,<|tool_call_argument_begin|>,<|tool_call_end|>,<|tool_calls_section_end|>) and<think>...</think>thinking blocks, emitting structuredInbandScanEventevents (text,thinkingStart,thinkingDelta,thinkingEnd,toolStart,toolEnd). - Stream Markup Healing:
streamMarkupHealingPattern: "kimi"inpackages/catalog/src/compat/openai.ts(detectStreamMarkupHealingPattern) fixes truncated or split inband control tokens across chunk boundaries forkimi-code,moonshot, orkimi-k2model IDs. - Idle Watchdog Timeout:
streamIdleTimeoutMsfloor is extended to 300s for native K2.7 Code models (packages/catalog/src/compat/openai.ts) to prevent premature stream aborts during long initial reasoning generation.
Auth & usage
- Device OAuth Flow: Implemented in
packages/ai/src/registry/oauth/kimi.ts(loginKimi,refreshKimiToken). Uses OAuth 2.0 Device Authorization Grant (urn:ietf:params:oauth:grant-type:device_code) with client ID17e5f671-d194-4dfb-9706-5516cb48c098against host${resolveOAuthHost()}(https://auth.kimi.com, configurable viaKIMI_CODE_OAUTH_HOSTorKIMI_OAUTH_HOST).- Initiates via
POST /api/oauth/device_authorization, prompts user withuserCodeandverificationUriComplete, and pollsPOST /api/oauth/tokenwith backoff onauthorization_pendingandslow_down. Token refresh usesgrant_type: "refresh_token".
- Initiates via
- Fingerprinting Headers & Device ID:
getKimiCommonHeaders()inpackages/ai/src/registry/oauth/kimi.tsinjects device tracking headers:User-Agent: KimiCLI/<ver>,X-Msh-Platform: kimi_cli,X-Msh-Version,X-Msh-Device-Name,X-Msh-Device-Model,X-Msh-Os-Version, andX-Msh-Device-Id.getDeviceIdpersists a random hex UUID topath.join(getAgentDir(), "kimi-device-id")(mode 0600) or falls back to an ephemeral process UUID. - Usage & Quota Tracker:
kimiUsageProviderinpackages/ai/src/usage/kimi.tstargetsGET /coding/v1/usages(https://api.kimi.com/coding/v1/usages, configurable viaKIMI_CODE_BASE_URL) with OAuth bearer token andgetKimiCommonHeaders().- Short-circuits when credentials are expired (
credential.expiresAt <= nowMs). ParsesKimiUsagePayload: mapsusageobject to aTotal quotasummary row andlimitsarray (extractingdetailandwindowduration/timeUnit) intoUsageLimitentries, resolving reset timestamps viaparseResetTime(reset_at,resetTime,ttl).
- Short-circuits when credentials are expired (
Catalog model handling
- Provider Descriptors:
packages/catalog/src/provider-models/descriptors.tsdefines:kimi-code: Default model"kimi-for-coding", envKIMI_API_KEY, dynamic discovery viakimiCodeModelManagerOptions.moonshot: Default model"kimi-k2.7-code", envsMOONSHOT_API_KEYandKIMI_API_KEYfallback, dynamic discovery viamoonshotModelManagerOptions(default base URLhttps://api.moonshot.ai/v1, overrideable viaMOONSHOT_BASE_URL).
- Identity Classification:
packages/catalog/src/identity/family.tsexportsisKimiModelId(matchesmoonshotai/kimior/(^|\/)kimi[-.]/),isKimiK26ModelId(/kimi-k2(\.6|p6)/), andisKimiK3ModelId(/kimi-k3/).isKimiK27CodeModelIdinpackages/catalog/src/provider-models/openai-compat.tsmatches/kimi-k2.7-code/. - K2.x vs K3 Reasoning Differences:
- K2.x: Native Moonshot K2.x models use binary thinking (
thinking: { type: "enabled" | "disabled" }) viathinkingFormat: "zai"inpackages/catalog/src/compat/openai.ts. Configured with 4-tier effort range[Minimal, Low, Medium, High]inmoonshotModelManagerOptions. K2.6 retains full thinking context (thinkingKeep: "all"). - K3: K3 models use OpenAI-style
reasoning_effort(thinkingFormat: "openai"). Configured with 3-tier wire scaleLOW_HIGH_MAX_REASONING_EFFORTS([Low, High, Max]),defaultLevel: Effort.Max, and mandatory reasoning (requiresEffort: true,impliesMandatoryReasoninginpackages/catalog/src/model-thinking.ts).moonshotModelManagerOptionsstamps 1M context window, 131,072 maxTokens, and vision input (["text", "image"]).
- K2.x: Native Moonshot K2.x models use binary thinking (
- Output Token Ceilings:
kimiCodeMaxTokensinpackages/catalog/src/provider-models/openai-compat.tsderives per-family output limits: 131,072 (KIMI_CODE_K3_MAX_TOKENS) fork3/k3-256k, 32,768 (KIMI_CODE_FOR_CODING_MAX_TOKENS) forkimi-for-coding/kimi-for-coding-highspeed, and fallback 32,000 (KIMI_CODE_DEFAULT_MAX_TOKENS) for legacy K2 discovery rows. Applied in catalog generator (packages/catalog/scripts/generate-models.ts).
Ollama
The Ollama integration consists of two distinct provider definitions in packages/ai: ollama for local Ollama instances (using openai-responses or openai-completions API via baseUrl pointing to local endpoint /v1, defaulting to http://127.0.0.1:11434/v1), and ollama-cloud for Ollama Cloud (using native ollama-chat API transport at https://ollama.com/api/chat). Entry modules are packages/ai/src/providers/ollama.ts for native streaming, packages/catalog/src/provider-models/openai-compat.ts for local Ollama catalog options (ollamaModelManagerOptions), and packages/catalog/src/provider-models/ollama.ts for Ollama Cloud catalog options (ollamaCloudModelManagerOptions).
Special casings
- Transport Routing: Local
ollamadefaults to OpenAI-compatible paths (openai-responses/openai-completions), whileollama-clouduses the nativeollama-chatprotocol. - Thinking / Reasoning Support: For
ollama-chat, reasoning is controlled via the nativethinkfield increateChatBodymapped bymapReasoning(minimal/low->"low",medium->"medium",high/xhigh->"high",max->"max", orfalsewhendisableReasoningis set). Ollama Cloud effort levels for GLM-5.2 are restricted tohighandmax(OLLAMA_CLOUD_GLM_52_THINKINGinpackages/catalog/src/provider-models/ollama.ts). Localollamaon OpenAI-compat paths supportsreasoning.effortwith valueslow,medium,high,max,none(OLLAMA_REASONING_EFFORTSinpackages/catalog/src/model-thinking.ts), withreplayReasoningContent: trueauto-enabled for local KV-cache/chat-template preservation (LOCAL_OPENAI_COMPAT_PROVIDERSinpackages/catalog/src/compat/openai.ts). - Tool Choice Emulation:
selectToolsForToolChoiceinpackages/ai/src/providers/ollama.tsmanually filterscontext.toolsdown to the target tool when a specific named tool choice is requested ({ type: "function", function: { name } }or{ name }). MaptoolChoicemaps"none"to"none","required"/"any"/named object to"required", and"auto"toundefined. - Developer Role & History Sanitization: Developer system prompts stay on Ollama’s
systemrole if they are initial system prompts or agent-attributed, but user-attributed developer turns demote touserfor stable prefix caching. If nouserrole exists,convertMessagesdemotes the last system turn touserto prevent Ollama from emittingdone_reason: "load"without generating output. Forollama-cloud,thinkingfields are stripped from assistant history messages (convertMessages) because Ollama Cloud rejects incoming history carryingthinkingwith HTTP 400. - Schema Sanitization: Tool schemas pass through
sanitizeSchemaForOllama(toolWireSchema(tool))to ensure compatibility. - Model Loading /
keep_alive& Error Rewriting: When a request contains no user turn or Ollama generates zero tokens, Ollama returnsdone_reason: "load", mapped to stopReason"error"withEMPTY_OLLAMA_LOAD_COMPLETION_MESSAGE. Malformed tool-call JSON errors from local llama.cpp backend (HTTP 500) are rewritten byrewriteOllamaToolCallJsonErrorinpackages/ai/src/error/format.ts.shouldRetryOllamaResponseretries 5xx errors unless matched byLLAMA_CPP_TOOL_CALL_PARSE_PATTERN.
Stream behavior
- NDJSON / JSONL Event Protocol: Native
ollama-chatstreams NDJSON chunks parsed viareadJsonl<OllamaChatChunk>. - Reasoning vs Content Handling: Reasoning chunks arrive as
chunk.message.thinking(yieldingthinking_start,thinking_delta,thinking_end). Content text arrives aschunk.message.content. Structured tool calls arrive aschunk.message.tool_calls. - Stream Markup Healing: Stream markup healing (
StreamMarkupHealingusinggetStreamMarkupHealingPattern) is engaged for text-channel tool call and reasoning recovery. When nativechunk.message.thinkingis present,suppressHealedThinkingis set totrueto avoid double-counting reasoning blocks. - Finish Reason Mapping:
mapDoneReasonmapsdone_reason:"length"->"length","tool_calls"->"toolUse","load"->"error", andundefinedwith tool calls ->"toolUse". Naturalstopwith produced tool calls is promoted to"toolUse". - Watchdogs & Local Prefill: Pre-response timeout is armed via
armPreResponseTimeoutwithfirstEventTimeoutMs(derived fromPI_STREAM_FIRST_EVENT_TIMEOUT_MSoridleTimeoutMs) whiletimeout: falseis passed tofetchWithRetryto avoid premature Bun fetch timeout aborts during heavy local prefill. Retries use delays[2000, 5000, 10000]. - Empty Completion Retry:
streamOllamais wrapped withwithEmptyCompletionRetryto transparently retry EOS-only empty completions.
Auth & usage
- Credential Source:
loginOllama(packages/ai/src/registry/ollama.ts) prompts for an optional API key (allowEmpty: true), defaulting to no-auth local usage withenvVars: ["OLLAMA_API_KEY"].loginOllamaCloud(packages/ai/src/registry/ollama-cloud.ts) mandates an API key created athttps://ollama.com/settings/keyswithenvVars: ["OLLAMA_CLOUD_API_KEY"]. - Authentication Headers: Local requests attach
Authorization: Bearer ${apiKey}if provided;ollama-cloudrequiresAuthorization: Bearer ${apiKey}. - Usage & Quota: Quota tracking is registered via
ollamaUsageProviderandollamaCloudUsageProviderinpackages/ai/src/usage/ollama.ts. Neither provider exposes a standalone usage/quota API (validatesCredentials: false, emptylimits), relying on per-responseprompt_eval_count(input) andeval_count(output) returned in stream completion chunks.
Catalog model handling
- Descriptors: Defined in
packages/catalog/src/provider-models/descriptors.ts:ollama:defaultModel: "gpt-oss:20b",allowUnauthenticated: true,envVars: ["OLLAMA_API_KEY"], options built viaollamaModelManagerOptions. Excluded fromgenerate-models.tsstatic baking (DISCOVERY_ONLY_PROVIDERS).ollama-cloud:defaultModel: "gpt-oss:120b",envVars: ["OLLAMA_CLOUD_API_KEY"],catalogDiscovery: { label: "Ollama Cloud", oauthProvider: "ollama-cloud" }, options built viaollamaCloudModelManagerOptions.
- Local Catalog Discovery:
ollamaModelManagerOptionsinpackages/catalog/src/provider-models/openai-compat.tsattemptsfetchOpenAICompatibleModelsat/v1/modelsfirst. If unavailable, it falls back to nativefetchOllamaNativeModelsquerying/api/tags. - Cloud Catalog Discovery:
ollamaCloudModelManagerOptionsinpackages/catalog/src/provider-models/ollama.tsqueries/api/tagsonhttps://ollama.comusingOLLAMA_CLOUD_API_KEY. - Context-Length & Capability Detection via
/api/show: Both local and cloud discovery query Ollama’s/api/showfor each model to inspectmodel_infoandcapabilities.- Context length is extracted from
model_infokeys ending in.context_length,.num_ctx, or.context_window. Fallback context window is128_000(OLLAMA_FALLBACK_CONTEXT_WINDOW). - Capability stamping:
capabilities.includes("thinking")setsreasoning: trueand configuresthinkingeffort config ([minimal, low, medium, high]).capabilities.includes("vision")stampsinput: ["text", "image"].
- Context length is extracted from
- Output Token Ceiling Capping: Ollama Cloud enforces
OLLAMA_CLOUD_MAX_OUTPUT_TOKENS = 65_536for DeepSeek V4 Pro/Flash models (isOllamaCloudOutputCapped).ollamaCloudModelManagerOptionscapsmaxTokensatmin(contextWindow, 65536)and setsomitMaxOutputTokens: true.resolveNumPredictinpackages/ai/src/providers/ollama.tsfurther clampsnum_predicton wire payloads to65_536. - Cache Provider ID: Resolved by
resolveModelCacheProviderIdinpackages/catalog/src/provider-models/cache-provider-id.tsusinghttp://127.0.0.1:11434forollamaor endpoint hash.
Cursor
Cursor’s integration in packages/ai operates over an HTTP/2 Connect RPC transport (/agent.v1.AgentService/Run) sending length-prefixed binary Protobuf messages (AgentClientMessage and AgentServerMessage). Key implementation entry points include packages/ai/src/providers/cursor.ts for connection lifecycle, Connect message streaming, and frame dispatching; packages/ai/src/providers/cursor-pi-args.ts for pure argument and path transformations; packages/ai/src/providers/cursor/exec-modern.ts for local tool result frame builders; packages/ai/src/registry/cursor.ts and packages/ai/src/registry/oauth/cursor.ts for PKCE browser authentication and token refresh; packages/ai/src/usage/cursor.ts for multi-endpoint quota tracking; and packages/catalog/src/discovery/cursor.ts for Connect RPC model discovery.
Special casings
- Pure Argument Translation (
cursor-pi-args.ts): Path and argument formatting functions (piReadPath,piReadPathHasRange,piReadDisplayPath,piGrepSkip,piJoinPath,piLsPath,piEscapeRegexLiteral,piLimit,piTimeout) are kept strictly independent of Protobuf imports so legacy shims can share them without bundling@bufbuild/protobufinto virtual registries. - Empty Grep Pattern Rejection:
grepArgsframes with an emptypatternand non-emptyglobare rejected up front (emptyGrepPatternRejection) with a descriptive error, forcing the model to retry or switch tools rather than triggering local tool failure after block persistence. - Native Tools &
SoftToolRequirementInterplay:- Native tools (
CURSOR_NATIVE_TOOL_NAMES:bash,read,write,delete,ls,grep,todo) are omitted when buildingrequestContextMCP tool definitions. - Exception:
writeis explicitly re-included inbuildMcpToolDefinitionswhenever pi-agent tools are advertised.writeacts as thexd://transport for staged previews (e.g.ast_edit). Withoutwrite, staged previews cannot be resolved andSoftToolRequirement('write')escalation aborts the turn.
- Native tools (
rootPromptMessagesJson& Blob Store:buildGrpcRequestpasses conversation history as SHA-256 binary blob IDs (blobStore) inrootPromptMessagesJsonandturns.- System prompts are stored as individual JSON blobs (
buildCursorSystemPromptJsons), allowing independent server-side prefix blob caching hits when only downstream prompts change.
- Thinking Replay Safeguards:
- Assistant thinking content is replayed in turn history (
canReplayCursorThinking) only for same-model Kimi K3 variants (assertCursorKimiK3HistoryReplayable). Foreign or hidden reasoning is omitted to prevent leaking non-Cursor thinking blocks into native conversation turns.
- Assistant thinking content is replayed in turn history (
Stream behavior
- Length-Prefixed Connect Framing:
- Connect HTTP/2 streams use 5-byte headers (1-byte flag + 4-byte big-endian uint32 payload length).
CONNECT_END_STREAM_FLAG(0b00000010) flags terminal frames carrying JSON error objects (parseConnectEndStream).
- Trailer & Transport Error Handling:
- Monitors HTTP/2 trailers (
grpc-status,grpc-message) and maps socket or TLS disconnects usingmapH2TransportError.
- Monitors HTTP/2 trailers (
- Bi-Directional RPC Dispatch:
- Server streams
AgentServerMessage(interactionUpdate,execServerMessage,kvServerMessage). - Client writes
AgentClientMessage(runRequest, periodicclientHeartbeatevery 5 seconds) andExecClientMessagetool responses (readResult,writeResult,execClientThrow,requestContextResult).
- Server streams
- Async Execution Drain & Turn Completion:
handleServerMessageprocesses frames asynchronously so the socket continues draining. Dispatches are tracked ininFlightDispatchesand bounded byoptions.signalabort handling before finalizing stream completion.- Stream completion verifies
turnEnded(sawTurnEnded) or throwsincomplete-stream.
- Tool Call Synthesis:
synthesizeCursorExecToolCallgenerates displaytoolCallblocks on assistant output messages to mirror local tool execution in the UI and transcript.
Auth & usage
- Credentials & Headers:
- Authenticates via
CURSOR_ACCESS_TOKENsent inAuthorization: Bearer <token>. - Client headers:
x-ghost-mode: true,x-cursor-client-version: cli-2026.07.23-e383d2b,x-cursor-client-type: cli,x-request-id.
- Authenticates via
- PKCE OAuth & Polling:
- Deep-link PKCE login generates verifier/challenge and redirects to
https://cursor.com/loginDeepControl. - Polls
https://api2.cursor.sh/auth/poll?uuid=...&verifier=...with exponential backoff (1s to 10s delay, up to 150 attempts). - Refresh trades refresh token via POST
https://api2.cursor.sh/auth/exchange_user_api_key.
- Deep-link PKCE login generates verifier/challenge and redirects to
- Usage & Quota Tracking (
packages/ai/src/usage/cursor.ts):- Standard quota fetched from
https://api2.cursor.sh/auth/usage(parseCursorUsage). - For OAuth credentials with WorkOS user sessions (
WorkosCursorSessionToken=${userId}::${accessToken}), fetches personal usage fromhttps://cursor.com/api/usage-summary(parseCursorIndividualUsage) and user profile email fromhttps://cursor.com/api/auth/me.
- Standard quota fetched from
Catalog model handling
- Descriptor Config (
packages/catalog/src/provider-models/descriptors.ts):- Configured with provider ID
"cursor", default model"claude-4.6-opus-high", runtime env varCURSOR_ACCESS_TOKEN, and catalog discovery env varCURSOR_API_KEY.
- Configured with provider ID
- Cache Provider ID (
packages/catalog/src/provider-models/cache-provider-id.ts):- Returns
"cursor:max-mode-v3"to ensure context window cache invalidation.
- Returns
- Model Discovery (
packages/catalog/src/discovery/cursor.ts):fetchCursorUsableModelscallsGetUsableModels(/agent.v1.AgentService/GetUsableModels) over Connect RPC.- Sets
cursorMaxModefromdetails.maxMode, assignsapi: "cursor-agent", maps 1M max-mode vs 200k default context windows, and defaultsmaxTokensto 64,000. - Dynamic discovery merges with bundled reference models from
models.json.
Devin
The Devin integration (devin-agent API) communicates with Codeium Cascade backend services over HTTP/1.1 using the Connect protocol and gRPC/Protobuf messages. Its implementation spans provider stream logic in packages/ai/src/providers/devin.ts (streamDevin, DEVIN_API_URL), provider registry entry in packages/ai/src/registry/devin.ts (devinProvider), CLI OAuth handling in packages/ai/src/registry/oauth/devin.ts (loginDevin), and Connect protobuf schemas located in packages/catalog/src/discovery/devin-gen/exa/*.
Special casings
- Connect Binary Protocol & Frame Wrapping: Transport uses Connect protocol over HTTP/1.1 targeting
https://server.codeium.com. Request payloads are serialized Protobuf (GetChatMessageRequestSchema), compressed with gzip, and wrapped in 5-byte Connect streaming binary frame headers (CONNECT_COMPRESSED_FLAG = 0x01, 4-byte big-endian payload length). End-of-stream frames carryCONNECT_END_STREAM_FLAG = 0x02with JSON error trailers (readConnectTrailerError). - Frame Size Safeguards: Reader enforces a 16MB frame payload cap (
MAX_CONNECT_FRAME_PAYLOAD) instreamDevinto reject corrupt frame length headers prior to buffering. - Message Format Mapping: System prompts are normalized (
normalizeSystemPrompts) into the top-levelpromptfield. Messages are formatted inbuildChatMessagePrompts:- User/developer messages map to
ChatMessageSource.USERwith deterministic message IDs (cascadeId\0index\0role). - Assistant messages map to
ChatMessageSource.SYSTEMwith text,thinking,signature, andtoolCalls. Native Devin assistant turns preserveresponseIdor fall back tobot-<uuid>. - Tool results map to
ChatMessageSource.TOOLwithtoolCallIdandtoolResultIsError.
- User/developer messages map to
- Session Threading & Stop Patterns: Session threading passes
options.conversationIdoroptions.sessionIdascascadeId. Default stop patterns include<|user|>,<|bot|>,<|context_request|>,<|endoftext|>, and<|end_of_turn|>(DEVIN_DEFAULT_STOP_PATTERNS). Tool selection specifiesautochoice withdisableParallelToolCalls: trueand ephemeral system prompt caching (CacheControlType.EPHEMERAL).
Stream behavior
- Protobuf Frame Streaming:
streamDevinreads chunked response bytes, parsing 5-byte Connect headers. Decompressed binary payloads are decoded intoGetChatMessageResponseSchema. - Opaque Error Recovery (
invalid_argument): End-of-stream trailers withinvalid_argumenterror codes (e.g. “internal error occurred”) trigger history recovery instreamDevin. When eligible history request size exceeds 512KB (LARGE_HISTORY_RECOVERY_BYTES), the error is reclassified asAIError.Flag.ContextOverflowto invoke automated context pruning rather than failing as an invalid request. - Event Stream Translation:
deltaThinking->thinking_start/thinking_delta(signature populated fromdeltaSignature).deltaText->text_start/text_delta.deltaToolCalls->toolcall_start/toolcall_delta.
- Throttled Streaming Tool Args: Mid-stream argument parsing uses
parseStreamingJsonThrottled(toolLastParseLen) to maintain O(N) performance on streaming JSON deltas before executing an authoritativeparseStreamingJsonupontoolcall_end. - Stop Reason Resolution: Maps
StopReason.MAX_TOKENStolength, active tool calls totoolUse, and defaults tostop.
Auth & usage
- Dual Auth Lifecycle:
- Session Token Prefixing: API key credentials are normalized via
normalizeDevinSessionTokento ensure adevin-session-token$prefix. - JWT Exchange:
fetchDevinAuthMetadatasends an initial Connect request (GetUserJwtRequestSchema) to/exa.auth_pb.AuthService/GetUserJwtusingapiKeyinsideMetadataSchema. The server returns auserJwt(and optional server base URL override) which is included in subsequent chat request metadata.
- Session Token Prefixing: API key credentials are normalized via
- CLI OAuth Flow:
loginDevininpackages/ai/src/registry/oauth/devin.tsexecutes a PKCE OAuth flow usinghttps://app.devin.ai/auth/cli/continue. Tokens are exchanged athttps://api.devin.ai/auth/cli/token(exchangeDevinCliToken) with expiration derived from JWT payload or a 1-year default fallback. - Usage Surface: Devin does not have a separate usage endpoint provider under
packages/ai/src/usage/(unlikeumans). Streaming response frames include token counts (msg.usage:inputTokens,outputTokens,cacheReadTokens,cacheWriteTokens), which feed directly intocalculateCost(model, output.usage).
Catalog model handling
- Model Manager Config:
devinModelManagerOptionsinpackages/catalog/src/provider-models/special.tsconfigures dynamic discovery withdynamicModelsAuthoritative: truewhen an API key is available.descriptors.tsregistersdevininCATALOG_PROVIDERS(DEVIN_API_KEY, OAuth providerdevin). - Dynamic Discovery:
fetchDevinModelsinpackages/catalog/src/discovery/devin.tsinvokes the unary Connect RPCGetCliModelConfigs(/exa.api_server_pb.ApiServerService/GetCliModelConfigs) withMetadataSchema.normalizeDevinModelsconvertsClientModelConfigintoModelSpec<"devin-agent">entries (defaulting to 200k context window, 64k max tokens). - Thinking Detection:
supportsDevinThinkingchecks label regex patterns (/think|thinking|minimal|high|medium|low|xhigh|max|reasoning/ivs/\bno thinking\b/i) andmodelInfo.modelFeatures.supportsThinking. - Compat Resolution:
buildDevinCompatinpackages/catalog/src/compat/devin.tssetstrustExplicitThinkingOnly: true(ResolvedDevinCompat), preventing implicit effort ladder inference (model-thinking.ts). - Reasoning Effort Routing: Devin models use sibling model routing instead of wire reasoning fields (
variant-collapse.ts).DEVIN_VARIANT_COLLAPSE_TABLEmaps model families (e.g.gpt-5-6-luna,claude-opus-5) across wire effort levels (low,medium,high,xhigh,max) to specific routed sibling model UIDs.
GitLab Duo
GitLab Duo is integrated via two distinct providers in OMP: GitLab Duo Non-Agentic (gitlab-duo), which proxies LLM requests through GitLab AI Gateway using standard HTTP/SSE sub-providers, and GitLab Duo Agent (gitlab-duo-agent), which connects to the GitLab Duo Workflow Service (DWS) over a WebSocket-based agent execution protocol. Entry modules for gitlab-duo are packages/ai/src/providers/gitlab-duo.ts and packages/ai/src/registry/gitlab-duo.ts (OAuth in packages/ai/src/registry/oauth/gitlab-duo.ts), while gitlab-duo-agent is implemented in packages/ai/src/providers/gitlab-duo-workflow.ts, packages/ai/src/registry/gitlab-duo-workflow.ts (OAuth in packages/ai/src/registry/oauth/gitlab-duo-workflow.ts), and catalog discovery in packages/catalog/src/discovery/gitlab-duo-workflow.ts.
Special casings
gitlab-duoModel Routing & Proxying: Maps Duo model identifiers (duo-chat-opus-4-6,duo-chat-sonnet-4-6,duo-chat-gpt-5-1,duo-chat-gpt-5-codex, etc.) inMODEL_MAPPINGS(packages/ai/src/providers/gitlab-duo.ts) to underlying provider types (anthropicoropenai) and API flavors (anthropic-messages,openai-completions,openai-responses). Requests are proxied to GitLab AI Gateway endpoints (https://cloud.gitlab.com/ai/v1/proxy/anthropic/orhttps://cloud.gitlab.com/ai/v1/proxy/openai/v1) using direct access tokens exchanged viagetDirectAccessToken.gitlab-duo-agentChatML Goal Generation: Translates OMP conversation history (context.messages) into a single flattened rendered ChatML prompt string (buildGitLabDuoWorkflowGoal,renderGitLabDuoWorkflowChatMl,buildGitLabDuoWorkflowInlineFlowConfiginpackages/ai/src/providers/gitlab-duo-workflow.ts). Guided by system prompt instructions ingitlab-duo-workflow-chatml-note.md.gitlab-duo-agentInline Flow Spec: Sends an ambient inline workflow definition (buildGitLabDuoWorkflowInlineFlowConfig) with anAgentComponentnamed"omp_agent", carrying OMP’s system prompt in its template and user template ``, with UI log events (on_agent_reasoning,on_agent_final_answer,on_tool_execution_success,on_tool_execution_failed).gitlab-duo-agentByte Budget & Overflow: Enforces goal byte limits (GITLAB_DUO_WORKFLOW_GOAL_SOFT_OVERFLOW_BYTES= 1MB,GITLAB_DUO_WORKFLOW_GOAL_HARD_OVERFLOW_BYTES= 2MB). Goals exceeding limits trigger an overflow error message (buildGitLabDuoWorkflowGoalOverflowMessage), driving automatic context compaction in the session loop.gitlab-duo-agentTool Execution Protocol: Maps OMP tools into MCP tool definitions (buildGitLabDuoWorkflowMcpTools,GitLabMcpToolDefinition) sent instartRequest.mcpTools. Tool invocation requests (runMCPTool,run_mcp_tool) received over WebSocket are extracted (extractGitLabDuoWorkflowAction), dispatched to OMP tool execution (mapGitLabDuoWorkflowActionToOmpTool,emitGitLabDuoWorkflowActionToolCall), and returned viabuildGitLabDuoWorkflowActionResponse.gitlab-duo-agentNamespace Settings Auto-Enable: REST setup routinely invokesensureGitLabDuoWorkflowSettingspostingbuildGitLabDuoWorkflowSettingsBodyto/api/v4/ai/duo_workflows/settingsto enable required namespace flags (duo_workflow,duo_workflow_service,duo_agent_platform).
Stream behavior
gitlab-duoDelegate Streaming: CallsstreamAnthropic,streamOpenAICompletions, orstreamOpenAIResponsesdirectly insidestreamGitLabDuo(packages/ai/src/providers/gitlab-duo.ts), piping underlying SSE events verbatim after injecting Direct Access headers (Authorization: Bearer <direct_access_token>).gitlab-duo-agentWebSocket Agent Loop: Connects via WebSocket (wss://<instance>/api/v4/ai/duo_workflows/wsor DWS runway hostbuildGitLabDuoWorkflowWebSocketUrl). Receives raw JSON events parsed byparseGitLabDuoWorkflowSocketDataand handled inrunGitLabDuoWorkflowSocket(packages/ai/src/providers/gitlab-duo-workflow.ts).gitlab-duo-agentEvent Processing & Reasoning: Extracts workflow checkpoints (extractGitLabDuoWorkflowCheckpoint), emitting incremental text (emitGitLabDuoWorkflowText) and chain-of-thought reasoning (emitGitLabDuoWorkflowThinking) derived fromon_agent_reasoningUI log events.gitlab-duo-agentApproval & Completion Signals: Monitors workflow approval states (isGitLabWorkflowApprovalStatus:PLAN_APPROVAL_REQUIRED,TOOL_CALL_APPROVAL_REQUIRED) and completion states (isGitLabWorkflowCompletionStatus:INPUT_REQUIRED,FINISHED).gitlab-duo-agentTimeouts & Health Deadlines: Implements a 90-second idle deadline on the WebSocket (GITLAB_DUO_WORKFLOW_IDLE_TIMEOUT_MS). Socket inactivity triggers an abort and resume on the existingworkflowID. REST setup calls are bounded by a 30-second timeout (GITLAB_DUO_WORKFLOW_REST_TIMEOUT_MS).gitlab-duo-agentBounded Restarts:- Step limit overruns: Up to 4 restarts (
GITLAB_DUO_WORKFLOW_MAX_STEP_LIMIT_RESTARTS) on fresh workflows when server reports max step limits (isGitLabDuoWorkflowStepLimitMessage). - Generic errors: Up to 1 retry (
GITLAB_DUO_WORKFLOW_MAX_GENERIC_ERROR_RETRIES) for transient processing faults (isGitLabDuoWorkflowGenericProcessingError). - Stall detection: Up to 2 restarts (
GITLAB_DUO_WORKFLOW_MAX_STALL_RESTARTS) whendetectGitLabDuoWorkflowStalldetects consecutive unchanged checkpoint content lengths at tool boundaries (lastToolBoundaryContentLength).
- Step limit overruns: Up to 4 restarts (
Auth & usage
gitlab-duoAuthentication: Supports PAT viaGITLAB_TOKENor OAuth (loginGitLabDuoinpackages/ai/src/registry/oauth/gitlab-duo.ts). Direct Access tokens are fetched viaPOST /api/v4/ai/third_party_agents/direct_accesswithDuoAgentPlatformNext: true(getDirectAccessTokeninpackages/ai/src/providers/gitlab-duo.ts) and cached for 25 minutes (DIRECT_ACCESS_TTL_MS). OAuth uses PKCE withDEFAULT_CLIENT_ID(overrideable viaGITLAB_CLIENT_ID/GITLAB_REDIRECT_URI) and callback port 8080 (packages/ai/src/registry/gitlab-duo.ts).gitlab-duo-agentAuthentication: Accepts PAT viaGITLAB_TOKENor OAuth (loginGitLabDuoWorkflowinpackages/ai/src/registry/oauth/gitlab-duo-workflow.ts). Direct Access workflow tokens are obtained viaPOST /api/v4/ai/duo_workflows/direct_access(requestGitLabDuoWorkflowDirectAccess). OAuth relies on the official GitLab VS Code client ID (GITLAB_DUO_WORKFLOW_OAUTH_CLIENT_ID = "36f2a70cddeb5a0889d4fd8295c241b7e9848e89cf9e599d0eed2d8e5350fbf5"), redirecting tovscode://gitlab.gitlab-workflow/authentication(pasteCodeFlow: true).gitlab-duo-agentProtocol Headers: Requests includex-gitlab-client-type: node-websocket,x-gitlab-language-server-version: 8.104.0, and resource scope headers (x-gitlab-project-id,x-gitlab-namespace-id,x-gitlab-root-namespace-id) constructed bybuildGitLabDuoWorkflowWebSocketHeaders.- Usage Tracking: Neither provider uses a module under
packages/ai/src/usage/. Forgitlab-duo-agent, context occupancy is extracted from server checkpoint telemetry (extractGitLabDuoWorkflowContextUsagereadingagent_context_usage), prioritizing"Chat Agent"and"context_builder"entries, and applied to prompt token estimates inapplyGitLabDuoWorkflowContextUsage.
Catalog model handling
- Provider Descriptors: Defined in
packages/catalog/src/provider-models/descriptors.ts:gitlab-duo: default modelduo-chat-opus-4-6,envVars: ["GITLAB_TOKEN"]. Models static-built viagetGitLabDuoModels().gitlab-duo-agent: default modelclaude_sonnet_4_6_vertex,envVars: ["GITLAB_TOKEN"],dynamicModelsAuthoritative: true, manager options built bygitLabDuoWorkflowModelManagerOptionsinpackages/catalog/src/provider-models/special.ts.
- Namespace Auto-Discovery:
discoverGitLabDuoWorkflowNamespace(packages/catalog/src/discovery/gitlab-duo-workflow.ts) locates the root namespace from explicit overrides, configuration, or workspace Git remotes (discoverGitLabDuoWorkflowProject). Models are discovered via GraphQL queryaiChatAvailableModels(rootNamespaceId:)(fetchGitLabDuoWorkflowModels). - Context Window Resolution:
resolveGitLabDuoWorkflowContextWindowinpackages/catalog/src/discovery/gitlab-duo-workflow.tsinfers context window sizes from model refs (Claude Opus/Sonnet: 1,000,000; Haiku: 200,000; GPT-5: 400,000; default: 200,000). - Cache Partitioning:
gitLabDuoWorkflowModelCacheProviderId(packages/catalog/src/provider-models/special.ts) partitions dynamic catalog cache keys by hashingapiKey,baseUrl,namespaceId,projectId, and workspacecwd. - Catalog Generation Rules:
scripts/generate-models.tsexcludesgitlab-duo-agentfrom static generation discovery to prevent bundling single-account namespace models into static catalogs, bundling onlybuildGitLabDuoWorkflowFallbackModelas a generic fallback seed.
Pi Native
Pi Native is a lossless internal server/client transport protocol used when a pi-ai client (such as containerized musepi or a sidecar agent slot) delegates request execution to a musepi auth-gateway holding real provider credentials. Activated when a Model sets transport: "pi-native", streamSimple in packages/ai/src/stream.ts short-circuits local provider resolution and POSTs the canonical Context directly to /v1/pi/stream. Primary entry modules are packages/ai/src/providers/pi-native-client.ts (streamPiNative) on the client side, packages/ai/src/providers/pi-native-server.ts (parseRequest, encodeStream, formatError) on the wire framing side, and packages/ai/src/auth-gateway/server.ts (POST /v1/pi/stream route handler) on the server side.
Special casings
- Lossless Pass-through & Dialect Absence: Unlike OpenAI/Anthropic routes,
pi-nativeis not a textual tool-call dialect (docs/toolconv/pi-native.md). Tool calls remain canonical pi-aiToolCallcontent blocks insideContextandAssistantMessageEvent. It preserves first-class pi-ai fields (service tier, cache markers, thinking budgets, tool-choice variants, image blocks, tool-call IDs) without foreign-wire quantization. - Wire Request & Minimal Boundary Validation: Client POSTs
{ modelId: "${provider}/${id}", context, options, stream: true }to${model.baseUrl}/v1/pi/stream(packages/ai/src/providers/pi-native-client.tsresolveStreamUrl).packages/ai/src/providers/pi-native-server.tsparseRequestacceptsmodelId,model.id, or stringmodel(supportingstreamProxytarget swaps). Validation checks only object shapes and arrays (context.messages, optionalcontext.systemPrompt,context.tools), leaving message/tool internals unvalidated until downstream provider execution. - Option Allow-list & Non-Wire Key Stripping: Server filters
optionsagainstALLOWED_OPTION_KEYS(31 keys) inpackages/ai/src/providers/pi-native-server.tsparseRequest, silently dropping unknown keys for cross-version compatibility. Client strips runtime-only and function-valued fields (signal,apiKey,fetch,onPayload,onResponse,onSseEvent,execHandlers,cursorExecHandlers,cursorOnToolResult,providerSessionState) viaNON_WIRE_KEYSinpackages/ai/src/providers/pi-native-client.tsbuildWireOptions. - Gateway Options Modification: On the auth-gateway (
packages/ai/src/auth-gateway/server.ts), sampling controls (temperature,topP,topK,minP,stopSequences, penalties) are stripped foropenai-codex-responsesmodels to prevent 400 errors, and passthrough request headers are captured (captureRequestHeaders) and merged under client headers. - Dispatch Precedence & Cache Bypass: In
packages/ai/src/stream.tsstreamSimple,model.transport === "pi-native"takes precedence over extension-registered custom APIs (getCustomApi).packages/ai/src/stream.tsassertExplicitOpenAIResponsesPromptCacheSupportexplicitly bypasses prompt cache assertions forpi-nativetransports because validation is deferred to the gateway-resolved model.
Stream behavior
- Verbatim SSE Framing: Server’s
encodeStream(packages/ai/src/providers/pi-native-server.ts) streams each canonicalAssistantMessageEventverbatim as JSON-serialized SSE frames (data: ${JSON.stringify(event)}\n\n) terminated bydata: [DONE]\n\n. Client (packages/ai/src/providers/pi-native-client.tsstreamPiNative) usesreadSseJsonand pushes events directly intoAssistantMessageEventStream. - Quadratic Partial Framing: Delta events include rolling
partial: AssistantMessagesnapshots, making wire bandwidth O(N²) in turn length. This overhead is accepted for loopback / sidecar topologies where provider latency dominates. - Idle & First-Event Watchdogs: Client wraps SSE streams with
iterateWithIdleTimeoutusingPI_STREAM_FIRST_EVENT_TIMEOUT_MSandPI_STREAM_IDLE_TIMEOUT_MS.isPiNativeProgressEventinpackages/ai/src/providers/pi-native-client.tsignorestype: "start"events so initial setup does not reset the idle timeout. - Synthetic Terminal Boundaries: If the SSE stream closes without a
doneorerrorevent, client’sstreamPiNativeconstructs a synthetic assistant message viamakeSyntheticAssistant. It pushes{ type: "error", reason: "aborted", error: { ..., stopReason: "aborted", errorMessage: "stream closed without terminal event" } }if caller aborted, or{ type: "done", reason: "stop", message: { ..., stopReason: "stop" } }on ungraceful clean close. - Server Iterator Exception Fallback: If the server’s
encodeStreamevent iterator throws, it enqueuesdata: {"type":"error","reason":"error","errorMessage":"..."}\n\nfollowed bydata: [DONE]\n\nso client iterators resolve instead of hanging. - Thinking loop guard:
packages/ai/src/stream.tsstreamSimplewrapsstreamPiNativewithwithThinkingLoopGuardandwithProviderInFlightLimit, ensuring Gemini, DeepSeek, and Grok runaway thinking streams abort with empty-content retryable errors.
Auth & usage
- Bearer Token Authorization: Client (
packages/ai/src/providers/pi-native-client.tsbuildHeaders) passesoptions.apiKey(the gateway bearer token) inAuthorization: Bearer <apiKey>, unlessmodel.headers.Authorizationis explicitly provided. - Gateway Credential Resolution: Server route handler (
packages/ai/src/auth-gateway/server.ts) validates the gateway bearer first. Missing/invalid tokens return401viapackages/ai/src/providers/pi-native-server.tsformatError. Valid requests instantiatebuildGatewayApiKeyResolverto fetch target provider credentials fromAuthStorageusingsessionId/promptCacheKeyand format"pi-native". - Error Envelope & Gateway Mapping: Server emits errors via
formatErroras{ error: { type, message } }with HTTP status,application/json, andCache-Control: no-store. Client’sdecodeGatewayErrorconverts non-2xx responses intoAIError.AuthGatewayError, preserving HTTP status, headers, and errortype. - Usage & Header Tracking: Token usage (
input,output,cacheRead,cacheWrite,cost) is carried directly inside canonicalAssistantMessageevents. Client notifies response metadata (x-request-id, headers) vianotifyProviderResponse.
Catalog model handling
- No Catalog Provider Entry:
pi-nativeis NOT a provider inpackages/catalog(absent fromdescriptors.tsCATALOG_PROVIDERS,src/provider-models/*,src/identity/classify.ts,src/model-thinking.ts, andscripts/generate-models.ts). - Transport Override Property: Defined solely as
transport?: "pi-native"on theModelinterface inpackages/catalog/src/types.ts. - Local Catalog Resolution: Metadata (pricing, context windows, max tokens, thinking configurations in
ThinkingConfig, capability flags, provider priority) resolves locally from the catalog model definition (e.g.anthropic/claude-3-5-sonnet), while execution dispatch is routed to the gatewaybaseUrl.
Catalog providers
Every CATALOG_PROVIDERS entry (packages/catalog/src/provider-models/descriptors.ts) that is not itself a transport, one section per provider id, alphabetical. These providers ride one of the transports documented above; each section covers only what the provider adds on top: special casings, auth and usage/quota tracking, and catalog wiring. Providers whose id IS a transport (anthropic, openai, openai-codex, azure, google, google-vertex, amazon-bedrock, bedrock-mantle, cursor, devin) are covered by their transport sections in the first half. Shared-engine providers (google-gemini-cli, google-antigravity, gitlab-duo, gitlab-duo-agent, kimi-code, moonshot, ollama, ollama-cloud) get both: engine mechanics above, per-id auth/usage/catalog wiring below.
ai& (aiand)
ai& (aiand) is an OpenAI-compatible inference API provider (aiand.com) offering open-weights and flagship LLMs with dynamic model catalog discovery, reasoning effort metadata, and token usage pricing. Transport: OpenAI Chat Completions.
Special casings
- Base URL Normalization:
normalizeAiandBaseUrlinpackages/catalog/src/provider-models/openai-compat.tstrims base URLs, defaults tohttps://api.aiand.com/v1, strips trailing slashes, and appends/v1if omitted. Nothing beyond the OpenAI Chat Completions pipeline.
Auth & usage
- API-Key Authentication: Supports API key authentication configured via the
AIAND_API_KEYenvironment variable (resolved viagetEnvApiKey("aiand")inpackages/ai/src/stream.ts) or explicitapiKeyoptions. - Console Login & Validation: Interactive login (
loginAiandinpackages/ai/src/registry/aiand.ts) prompts for an API key fromhttps://console.aiand.com/api-keysand validates credentials viacreateApiKeyLoginagainsthttps://api.aiand.com/v1/models. Registered asaiandProviderinpackages/ai/src/registry/registry.ts.
Catalog model handling
- Provider Descriptor: Registered in
packages/catalog/src/provider-models/descriptors.tswithdefaultModel: "moonshotai/kimi-k2.7-code",envVars: ["AIAND_API_KEY"], anddynamicModelsAuthoritative: true. - Static Seed Models:
AIAND_STATIC_MODELSinpackages/catalog/src/provider-models/openai-compat.tsprovides 9 bundled offline model specs (qwen/qwen3.6-27b,deepseek-ai/deepseek-v4-flash,google/gemma-4-31b-it,openai/gpt-oss-120b,deepseek-ai/deepseek-v4-pro,moonshotai/kimi-k2.7-code,moonshotai/kimi-k2.6,zai-org/glm-5.2,zai-org/glm-5.1) created viacreateAiandStaticModelwith effort reasoning ladders ([low, medium, high], defaultmedium). Seed models are pushed inscripts/generate-models.tswhen authoritative online catalog generation is disabled. - Authoritative Discovery:
aiandModelManagerOptionsinpackages/catalog/src/provider-models/openai-compat.tssetsdynamicModelsAuthoritative: trueand invalidates static IDs viadropCachedModelIdsOnStaticMismatch: AIAND_STATIC_MODEL_IDS. When anapiKeyis supplied,fetchDynamicModelsqueries/v1/modelsusingfetchOpenAICompatibleModelswithmapAiandModel. - Thinking Configuration (
mapAiandThinking):mapAiandThinkingconverts wire string arrayreasoning_effortsinto piEffortlevels viaAIAND_EFFORT_BY_WIRE_VALUE(minimal,low,medium,high,xhigh,max), settingdefaultLevelfromreasoning_effort_defaultwhen valid. Returnsundefinedif efforts are empty. - Cost Mapping (
mapAiandCost):mapAiandCostextractsinput_per_1mandoutput_per_1mUSD token prices viatoPositiveNumber. Non-USD org billing currencies (e.g.currency !== "usd") fall back to{ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }to avoid cost model corruption. - Model Attribute Mapping (
mapAiandModel):mapAiandModelmaps model descriptions or names (toModelName), checkscapabilitiesfor"reasoning"(attachingthinking) and"vision"(settinginput: ["text", "image"]), and parsescontext_window.
AIML API (aimlapi)
AIML API is an AI model aggregator platform providing access to diverse multi-vendor models through a unified OpenAI-compatible endpoint. It uses the OpenAI Chat Completions (openai-completions) transport pipeline.
Special casings
- Non-chat model filtering: Dynamic model listings are filtered via
isLikelyAimlApiChatModelId(packages/catalog/src/provider-models/openai-compat.ts), excluding audio, embedding, image, video, and TTS models matched by regex/(?:^|[/:._-])(?:audio|embed|embedding|embeddings|i2i|i2v|image|speech|t2i|t2v|tts|video)(?:$|[/:._-])/ior substrings (dall-e,dalle,flux,imagen,sora,veo,whisper). - Standard transport pipeline: Uses un-customized
openai-completionstransport with no custom request transformers or error handlers (packages/catalog/src/provider-models/openai-compat.ts).
Auth & usage
- Environment authentication: Configured to discover credentials via the
AIMLAPI_API_KEYenvironment variable (packages/catalog/src/provider-models/descriptors.ts,packages/ai/src/registry/aimlapi.ts). - API authorization: Transmits key as an HTTP
Authorization: Bearer <key>header to target hosthttps://api.aimlapi.com/v1. - Usage tracking: Has no dedicated quota or usage parsing module registered in
packages/ai/src/usage/.
Catalog model handling
- Descriptor registration: Defined in
PROVIDER_DESCRIPTORSwithdefaultModel: "gpt-5.5-2026-04-23",dynamicModelsAuthoritative: true, and label"AIML API"(packages/catalog/src/provider-models/descriptors.ts). - Dynamic discovery: Managed via
aimlApiModelManagerOptions()inpackages/catalog/src/provider-models/openai-compat.ts, which fetcheshttps://api.aimlapi.com/v1/modelsand maps candidates viafilterModel(isLikelyAimlApiChatModelId) andmapWithBundledReference. - Canonical resolution: Multi-vendor namespaced models (e.g.,
alibaba/qwen3-32b,x-ai/grok-4-3) resolve canonical parameter defaults throughbuildModelProviderPriorityRank, whereaimlapiparticipates in cross-provider identity lookup (packages/catalog/src/identity/priority.ts,packages/catalog/test/canonical-limit-fallback.test.ts).
Alibaba Coding Plan (alibaba-coding-plan)
Alibaba Coding Plan provides coding-oriented model endpoints hosted on Alibaba Cloud’s DashScope platform. It uses the OpenAI Chat Completions transport (openai-completions) connecting to international (https://coding-intl.dashscope.aliyuncs.com/v1) or mainland China (https://coding.dashscope.aliyuncs.com/v1) endpoints.
Special casings
- Structured API key parsing: In
packages/ai/src/providers/openai-shared.ts, whenalibabaCodingPlanAuthis enabled (packages/ai/src/providers/openai-completions.ts), JSON-formatted API keys (emitted by login/OAuth storage) are parsed to extract the bearertokenand overridebaseUrlviaenterpriseUrl. - Low priority selection: Included in
LOW_PRIORITY_PROVIDERS(packages/catalog/src/identity/priority.ts), preventingalibaba-coding-planmodels from winning ambiguous automatic role selection over primary providers. - Host classification: Grouped under the
alibabaDashscopehost entry inpackages/catalog/src/hosts.ts(urlMarkers: ["dashscope", "token-plan."]). - OAuth structured key flag: Registered in
needsStructuredApiKey(packages/ai/src/registry/oauth/index.ts) to serialize endpoint and token metadata (enterpriseUrl,access,refresh,expires) into a JSON key string.
Auth & usage
- Interactive login & endpoint selection:
loginAlibabaCodingPlan(packages/ai/src/registry/alibaba-coding-plan.ts) prompts users to select between International (https://coding-intl.dashscope.aliyuncs.com/v1), Mainland China (https://coding.dashscope.aliyuncs.com/v1), or a custom proxy base URL. - API key validation: Validates credentials via
apiKeyValidation.validateOpenAICompatibleApiKeyagainst modelqwen3.5-plusfor preset endpoints, orvalidateApiKeyAgainstModelsEndpointfor custom URLs (packages/ai/src/registry/alibaba-coding-plan.ts). - Environment variable: API key is retrieved via
ALIBABA_CODING_PLAN_API_KEY(packages/catalog/src/provider-models/descriptors.ts). - Usage & quota tracking: Unlike
alibaba-token-plan,alibaba-coding-planhas no dedicated usage provider or quota tracking inpackages/ai/src/usage/.
Catalog model handling
- Model manager options:
alibabaCodingPlanModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts) creates manager options viacreateOpenAICompatibleModelManagerOptionsconfigured withproviderId: "alibaba-coding-plan",defaultBaseUrl: "https://coding-intl.dashscope.aliyuncs.com/v1", andmapWithBundledReference. - Descriptor & defaults: Registered descriptor (
packages/catalog/src/provider-models/descriptors.ts) setsdefaultModel: "qwen3.7-plus". - Model source: Model specifications are bundled in
packages/catalog/src/models.jsonunder"alibaba-coding-plan".
Stream behavior
- Extended stream idle timeout: Sets
streamIdleTimeoutMsto 600,000 ms (ALIBABA_CODING_PLAN_STREAM_IDLE_TIMEOUT_MS = 600_000inpackages/catalog/src/compat/openai.ts) to prevent premature stream watchdogs aborting during long initial generation delays before the first SSE event.
QwenCloud Token Plan (alibaba-token-plan)
QwenCloud Token Plan provides model subscription access to Alibaba Cloud’s Qwen and DeepSeek model suites. It operates using the OpenAI Chat Completions transport (openai-completions API schema) over HTTP POST JSON and Server-Sent Events (SSE) streaming (packages/ai/src/providers/openai-shared.ts).
Special casings
- Explicit Credential Isolation:
resolveOpenAIRequestSetup(packages/ai/src/providers/openai-shared.ts) requires an explicitALIBABA_TOKEN_PLAN_API_KEYorBAILIAN_TOKEN_PLAN_API_KEYcredential and explicitly disables the generic$env.OPENAI_API_KEYfallback to prevent key leakage to QwenCloud endpoints. - Region Base URL Routing: Credentials support region-locked endpoints: International Singapore (
ALIBABA_TOKEN_PLAN_BASE_URL=https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1) and China Beijing (ALIBABA_TOKEN_PLAN_CN_BASE_URL=https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1). Region keys are non-interchangeable; storedbaseUrloverrides catalog defaults for inference and model discovery (packages/catalog/src/provider-models/openai-compat.ts). - Store Deduplication:
hasAuthCredentialForProvider(packages/ai/src/auth/sqlite-credential-store.ts) parses JSON compound credentials (parseAlibabaTokenPlanCredential) to compare innertokenstrings rather than raw JSON text.
Auth & usage
- Environment & Wire Credential: Resolves
ALIBABA_TOKEN_PLAN_API_KEYthenBAILIAN_TOKEN_PLAN_API_KEY. Supports plain bearer keys (sk-sp-...) or serialized JSON strings ({ token, cookie?, baseUrl? }) parsed viaparseAlibabaTokenPlanCredentialand formatted viaserializeAlibabaTokenPlanCredential(packages/catalog/src/wire/alibaba-token-plan.ts). - Interactive Login:
loginAlibabaTokenPlan(packages/ai/src/registry/alibaba-token-plan.ts) prompts for region (1=International, 2=China Beijing, 3=Custom URL), validates the API key via${baseUrl}/models(validateApiKeyAgainstModelsEndpoint), and accepts an optionalcs-data.qwencloud.combrowserCookieheader for quota reporting. - Console Quota Scraping:
alibabaTokenPlanUsageProvider(packages/ai/src/usage/alibaba-token-plan.ts) uses the storedCookieheader to fetchsecTokenfromhttps://home.qwencloud.com/tool/user/info.jsonand issues a POST tohttps://cs-data.qwencloud.com/data/api.json?product=sfm_bailian&action=IntlBroadScopeAspnGateway&api=zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usagewith URL-encoded parameters. - Quota Windows & Ranking: Parses
per5HourPercentage/per5HourResetTime(5-hour window,credits:5h) andper1WeekPercentage/per1WeekResetTime(7-day window,credits:7d).alibabaTokenPlanRankingStrategyconfigurescredits:5has primary limit (5h window) andcredits:7das secondary limit (7d window).
Catalog model handling
- Authoritative Discovery: Configured with
dynamicModelsAuthoritative: true(packages/catalog/src/provider-models/descriptors.ts)./modelsdiscovery is subscription-scoped; a successful endpoint response is authoritative and overrides static fallback catalogs even if empty (packages/catalog/scripts/generate-models.ts). - Discovery Filtering & Overrides:
isAlibabaTokenPlanChatModelId(packages/catalog/src/provider-models/openai-compat.ts) filters non-chat prefixes (qwen-audio-,qwen-image-,text-embedding-,wan2.7-). Discovereddeepseek-v4*models are mapped withreasoning: trueand effort thinking ([Effort.High, Effort.Max]). - Static Catalog Fallback:
ALIBABA_TOKEN_PLAN_STATIC_MODELSprovides static catalog seed fallback when uncredentialed or when discovery fails (packages/catalog/scripts/generate-models.ts).
Baseten (baseten)
Baseten provides high-performance infrastructure for hosting open-weight LLMs (including Moonshot Kimi, DeepSeek, Zhipu GLM, and gpt-oss series). Requests execute over the OpenAI Chat Completions transport (openai-completions API) targeting default base URL https://inference.baseten.co/v1.
Special casings
- Nothing beyond the
openai-completionspipeline.
Auth & usage
- API Key Authentication: Authenticates via
BASETEN_API_KEY(packages/catalog/src/provider-models/descriptors.ts). Login flowloginBaseten(packages/ai/src/registry/baseten.ts) usescreateApiKeyLoginpointing to dashboardhttps://app.baseten.co/settings/api_keyswith placeholderbt_.... - Endpoint Validation: API key validation in
loginBaseten(packages/ai/src/registry/baseten.ts) verifies credentials viaGET https://inference.baseten.co/v1/models(models-endpointvalidation kind). - Usage Accounting: Reconciles token usage and pricing through standard OpenAI Chat Completions usage handling (
calculateOpenAIUsageAccountinginpackages/ai/src/providers/openai-shared.ts).
Catalog model handling
- Provider Descriptor: Registered in
CATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts) withid: "baseten",defaultModel: "moonshotai/Kimi-K2.7-Code",envVars: ["BASETEN_API_KEY"],dynamicModelsAuthoritative: true, and discovery label"Baseten". - Model Manager Options:
basetenModelManagerOptionsinpackages/catalog/src/provider-models/openai-compat.tsconfigures model resolution withdefaultBaseUrl: "https://inference.baseten.co/v1"andrequireApiKey: true. - Dynamic Model Discovery & Pricing:
fetchDynamicModelsquerieshttps://inference.baseten.co/v1/models.mapModelparses raw record metadata includingsupported_features,input_modalities(imagefor vision capability), context and completion token bounds (context_length,max_completion_tokens), and per-million token pricing (prompt,completion,input_cache_read). - Native Reasoning Identification: Flags
reasoning: trueforopenai/gpt-oss-120b,deepseek-ai/DeepSeek-V4-Pro, andzai-org/GLM-5.2when dynamic features listreasoningorreasoning_effort. - Reasoning Effort Tier Restrictions:
getModelDefinedEffortsinpackages/catalog/src/model-thinking.tsandbasetenModelManagerOptionsinpackages/catalog/src/provider-models/openai-compat.tsrestrict reasoning effort tiers for bothzai-org/GLM-5.2(isGlm52ReasoningEffortModelId) andopenai/gpt-oss-120b(isOpenAIGptOssModelId) routes to the two-tierHIGH_MAX_REASONING_EFFORTSscale ([high, max]). - Identity Priority & Host Matching: Prioritized in
PROVIDER_PRIORITY(packages/catalog/src/identity/priority.ts) and matched via URL markerbaseten.coinpackages/catalog/src/hosts.ts.
Cerebras (cerebras)
Cerebras provides ultra-fast inference on wafer-scale engine hardware for open-weights models such as zai-glm-4.7, gpt-oss-120b, qwen-3-235b-a22b-instruct-2507, and gemma-4-31b. It communicates via the OpenAI Chat Completions (openai-completions) transport.
Special casings
all_strictTool Mode:toolStrictModedefaults to"all_strict"for Cerebras inpackages/catalog/src/compat/openai.ts(isCerebras), forcingstrict: trueacross all passed tool schemas inopenai-completions.ts(AppliedToolStrictMode).supportsUsageInStreaming: false: Configured viasupportsUsageInStreaming: !isCerebrasinpackages/catalog/src/compat/openai.tsto suppressstream_options: { include_usage: true }inopenai-completions.ts, preventing API rejections when streaming responses.- Empty 400/413 Context-Overflow Detection: Cerebras context and payload overflow errors return empty HTTP 400 or 413 response bodies. Recognized in
packages/ai/src/error/flags.tsbyOVERFLOW_NO_BODY_PATTERN(/\b4(00|13)\s*(status code)?\s*\(no body\)/i), allowingisContextOverflowto setFlag.ContextOverflowso agent sessions auto-compact context rather than failing terminally. - Gemma Image Input Serialization: Models matching
gemma-4-31bserialize attached image blocks into Chat Completionsimage_urldata URIs (data:image/png;base64,...) when processed byconvertMessagesinpackages/ai/src/providers/openai-completions.ts.
Auth & usage
- API Key Login: Configured via
loginCerebrasinpackages/ai/src/registry/cerebras.tsusingcreateApiKeyLoginwith default validation modelgpt-oss-120band base URLhttps://api.cerebras.ai/v1. - Environment Resolution: Registered as
cerebrasProviderinpackages/ai/src/registry/cerebras.tsand catalog descriptordescriptors.tsusing environment variableCEREBRAS_API_KEY.
Catalog model handling
- Provider Registration: Catalog entry in
descriptors.ts(CATALOG_PROVIDERS) setsid: "cerebras",defaultModel: "zai-glm-4.7", and delegates option construction tocerebrasModelManagerOptions. - Manager Options & Discovery:
cerebrasModelManagerOptionsinpackages/catalog/src/provider-models/openai-compat.tsusescreateOpenAICompatibleModelManagerOptionswithproviderId: "cerebras"and default base URLhttps://api.cerebras.ai/v1. - Gemma Image Capability Override:
applyCerebrasDiscoveryOverridesinpackages/catalog/src/provider-models/openai-compat.tschecksCEREBRAS_IMAGE_INPUT_MODEL_IDS(Set(["gemma-4-31b"])) during model mapping to explicitly append"image"toinputcapabilities (input: ["text", "image"]), overriding missing vision capability flags in remote endpoint discovery metadata.
Cloudflare AI Gateway (cloudflare-ai-gateway)
Cloudflare AI Gateway proxies requests through Cloudflare’s edge infrastructure to model providers, utilizing the Anthropic Messages transport. Base URLs require substituting <account> and <gateway> path placeholders with the user’s specific Cloudflare account ID and gateway slug in model configurations.
Special casings
- Custom Authorization Header: Uses
cf-aig-authorization: Bearer <key>instead of standardx-api-keyorAuthorizationheaders (packages/ai/src/providers/anthropic.ts:buildAnthropicHeaders). - Suppressed Client Credentials:
apiKeyandauthTokenare set tonullon the Anthropic client options object so credentials travel exclusively via pre-built default headers (packages/ai/src/providers/anthropic.ts:3027-3037). - Signing Proxy Detection: URLs matching
gateway.ai.cloudflare.com/.+/anthropicare recognized viaisCloudflareAnthropicGatewayas Anthropic signing proxies (packages/catalog/src/compat/anthropic.ts:CLOUDFLARE_ANTHROPIC_GATEWAY_URL_MARKER,isAnthropicSigningProxyUrl). - OAuth Session Protection: Excluded from receiving Claude OAuth
account_uuidheaders to prevent identity leakage to third-party proxies (packages/coding-agent/src/session/session-metadata.ts).
Auth & usage
- Authentication Prompt:
loginCloudflareAiGatewayprompts for a Cloudflare AI Gateway token/API key (cf-aig-...) and directs users to Cloudflare’s authentication documentation (packages/ai/src/registry/cloudflare-ai-gateway.ts). - Environment Variable: Reads API key credentials from
CLOUDFLARE_AI_GATEWAY_API_KEY(packages/catalog/src/provider-models/descriptors.ts). - Account & Gateway Resolution: Uses
https://gateway.ai.cloudflare.com/v1/<account>/<gateway>/anthropicas the base URL template where<account>and<gateway>placeholders are replaced with the user’s Cloudflare account ID and gateway slug (packages/catalog/src/provider-models/openai-compat.ts:cloudflareAiGatewayModelManagerOptions).
Catalog model handling
- Descriptor & Default Model: Wired via
anthropicMessagesDescriptorwith default modelanthropic/claude-opus-4-8(packages/catalog/src/provider-models/descriptors.ts). - Static Fallback Model: Injects
CLOUDFLARE_FALLBACK_MODEL(claude-sonnet-4-5, reasoning enabled, 200k context) during catalog generation when no models are returned by discovery (packages/catalog/scripts/generated-policies.ts,packages/catalog/scripts/generate-models.ts:536-538). - Priority Wiring: Assigned catalog priority level 39 in
providerPriority(packages/catalog/src/identity/priority.ts).
CoreWeave Serverless Inference (coreweave)
CoreWeave Serverless Inference provides hosted AI model inference powered by Weights & Biases (W&B) infrastructure at https://api.inference.wandb.ai/v1. It operates using the “OpenAI Chat Completions” transport.
Special casings
- Project Header Injection:
applyCoreWeaveProjectHeaderinpackages/ai/src/providers/openai-shared.tsintercepts requests forcoreweavemodels inresolveOpenAIRequestSetupand injects the requiredOpenAI-ProjectHTTP header. Header resolution is handled byresolveCoreWeaveProjectandcoreWeaveProjectHeadersinpackages/catalog/src/wire/coreweave.ts, checkingCOREWEAVE_PROJECT,WANDB_INFERENCE_PROJECT, orWANDB_ENTITY/WANDB_PROJECT.removeBlankCoreWeaveProjectHeadersremoves empty project headers to allow fallback to environment variables. - GPT-OSS Reasoning Transformation: In
openAiCompletionsDescriptor(packages/catalog/src/provider-models/openai-compat.ts), models starting withopenai/gpt-oss-are transformed to setreasoning: trueand configured with effort-based thinking (Effort.Low,Effort.Medium,Effort.High).
Auth & usage
- API Key & Environment Resolution: Authenticates via
COREWEAVE_API_KEY, falling back toWANDB_API_KEY(descriptors.ts,getEnvApiKeyinpackages/ai/src/stream.ts). - Login Flow & Project Validation: Interactive login is configured in
loginCoreWeave(packages/ai/src/registry/coreweave.ts), referencing settings athttps://wandb.ai/settings.requireCoreWeaveProjectHeadersenforces that a validOpenAI-Projectheader can be constructed from environment variables before validating credentials againsthttps://api.inference.wandb.ai/v1/models.
Catalog model handling
- Descriptor Configuration: Registered in
CATALOG_PROVIDERSinpackages/catalog/src/provider-models/descriptors.tswith IDcoreweave, default modelopenai/gpt-oss-120b, and discovery label"CoreWeave Serverless Inference". - Model Manager & Dynamic Discovery:
coreWeaveModelManagerOptionsinpackages/catalog/src/provider-models/openai-compat.tsconstructs provider options forhttps://api.inference.wandb.ai/v1viacreateSimpleOpenAICompletionsOptions, dynamically supplyingcoreWeaveProjectHeaders(Bun.env)on catalog model fetches.
DeepSeek (deepseek)
The DeepSeek provider interfaces directly with DeepSeek’s API (https://api.deepseek.com/v1) using the OpenAI Chat Completions transport (openai-completions). It powers official DeepSeek models like deepseek-v4-pro and deepseek-v4-flash, implementing provider-specific reasoning flags, token-stripping stream filters, custom prompt-cache usage accounting, and Bearer-sanitized API key storage.
Special casings
- Reasoning Compat &
whenThinkingSwap: Direct DeepSeek reasoning models (isDirectDeepseekReasoninginpackages/catalog/src/compat/openai.ts) configuresupportsToolChoice: false(omittingtool_choiceon reasoning calls) andreasoningDisableMode: "zai-thinking-disabled". Active reasoning activates awhenThinkingcompat pointer-swap that mergesextraBody: { thinking: { type: "enabled" } }. Setting anytool_choicedrops reasoning fields (disableReasoningOnToolChoice: true). See Provider compat reference. - Reasoning Content Invariants: Replays exact prior
reasoning_contenton follow-up turns (requiresReasoningContentForToolCallsandrequiresReasoningContentForAllAssistantTurns), rejecting synthetic"."placeholders (allowsSyntheticReasoningContentForToolCalls: false). Empty assistant content on tool turns is promoted to"."(requiresAssistantContentForToolCalls: true). - Chat Template Token Stripping & Healing:
stripDeepseekSpecialTokensinpackages/ai/src/providers/openai-completions.tsbuffers and strips raw streamed chat-template tokens (<|User|>,<|Assistant|>, etc.). In-band DSML tool blocks (<|DSML|tool_calls>) are healed viaStreamMarkupHealingwith pattern"dsml". - Wire Parameters & Stream Watchdog: Output token ceiling uses
max_tokens(maxTokensField: "max_tokens"). Inter-event stream watchdog extends to 300 s (DEEPSEEK_REASONING_STREAM_IDLE_TIMEOUT_MS) to allow for lengthy prefill/thinking delays.supportsStrictMode: trueis enabled for function tools.
Auth & usage
- API Key Normalization & Login:
normalizeDeepSeekApiKeyinpackages/ai/src/registry/deepseek.tstrims inputs and strips any leadingBearerprefix (case-insensitive), throwingApiKeyRequiredErrorif empty. InteractiveloginDeepSeekwrapsonPromptwith normalization and validates against/v1/models. Runtime credential relies onDEEPSEEK_API_KEY. - Prompt-Cache Usage Accounting: DeepSeek returns top-level usage fields
prompt_cache_hit_tokensandprompt_cache_miss_tokens.calculateOpenAIUsageAccounting(packages/ai/src/providers/openai-shared.ts) detectsisDeepSeekUsage, mapping net input tokens toMath.max(0, promptTokens - cachedTokens)(the miss count) and settingcacheWriteto0to avoid double-charging uncached prompt tokens as explicit cache writes.
Catalog model handling
- Descriptor & Manager: Catalog entry
deepseekinpackages/catalog/src/provider-models/descriptors.tssetsdefaultModel: "deepseek-v4-pro"and usesdeepseekModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts) targetinghttps://api.deepseek.com. Built-in discovery filters for tool-callingdeepseek-v4models. - Reasoning Effort Ladders: Configures
HIGH_MAX_REASONING_EFFORTS([high, max]) fordeepseek-v4-proandLOW_HIGH_MAX_REASONING_EFFORTS([low, high, max]) fordeepseek-v4-flash. Normalizesxhigheffort requests tomaxacross DeepSeek models (isDeepseekModelIdOrName).
Fire Pass (firepass)
Fire Pass is a Fireworks AI subscription tier providing dedicated high-throughput router access to Kimi K2.6 Turbo. It uses the OpenAI Chat Completions transport (https://api.fireworks.ai/inference/v1) with Fireworks router endpoint translation.
Special casings
- Wire Model ID Translation (
wireModelIdMode: "firepass"):buildOpenAICompat(packages/catalog/src/compat/openai.ts) assignswireModelIdMode: "firepass"forfirepassor Fireworks fast router models (isFireworksFastRouter).applyWireModelIdTransform(packages/ai/src/providers/openai-shared.ts) usestoFirepassWireModelId(packages/catalog/src/fireworks-model-id.ts) to convert friendly catalog IDs (e.g.,kimi-k2.6-turbo) into Fireworks router wire IDs (accounts/fireworks/routers/kimi-k2p6-turbo) by replacing dots withp. - Max Output Token Cap: Output tokens are capped at 32,768 (
FIREWORKS_KIMI_MAX_TOKENS) viaclampFireworksKimiMaxTokens(packages/catalog/src/provider-models/openai-compat.ts) andapplyKimiMaxTokensCap(packages/catalog/scripts/generate-models.ts) to prevent runaway reasoning traces on Kimi K2 models. - Five-Tier Thinking Effort:
getThinkingConfig(packages/catalog/src/model-thinking.ts) mapsfirepasstoFIVE_TIER_EFFORTS_LOW_TO_MAX(low,medium,high,xhigh,max).
Auth & usage
- Authentication: Defined in
packages/ai/src/registry/firepass.ts(firepassProvider,loginFirepass) using environment variableFIREPASS_API_KEY(fpk_...). - Validation: Dedicated
fpk_...keys only authorize the router endpoint and fail on/v1/models.loginFirepassusesvalidation.kind: "chat-completions"targetingaccounts/fireworks/routers/kimi-k2p6-turbodirectly.
Catalog model handling
- Descriptor: Registered in
packages/catalog/src/provider-models/descriptors.ts(id: "firepass",defaultModel: "kimi-k2.6-turbo",envVars: ["FIREPASS_API_KEY"]). - Manager Options:
firepassModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts) returns a static configuration without dynamic discovery, relying on the canonical bundled catalog inmodels.json. - Script Cleanups:
dropFireworksWireIds(packages/catalog/scripts/generate-models.ts) strips internalaccounts/fireworks/wire IDs during catalog generation.
Fireworks (fireworks)
Fireworks (packages/ai/src/registry/fireworks.ts) is a high-throughput AI inference provider serving serverless and dedicated models via an OpenAI-compatible HTTP REST API (https://api.fireworks.ai/inference/v1). It uses the OpenAI Chat Completions transport (streamOpenAICompletions in packages/ai/src/providers/openai-completions.ts) with custom model ID wire translation, thinking parameter conflict resolution, and priority tier handling.
Special casings
wireModelIdMode: "fireworks"& Wire Model ID Transformation:applyWireModelIdTransform(packages/ai/src/providers/openai-shared.ts), enabled bywireModelIdMode: "fireworks"resolved inpackages/catalog/src/compat/openai.ts, invokestoFireworksWireModelId(packages/catalog/src/fireworks-model-id.ts) to prefix public catalog model IDs withaccounts/fireworks/models/and convert version dots top(e.g.,glm-5.1maps toaccounts/fireworks/models/glm-5p1). Public catalog normalization usestoFireworksPublicModelId.- Fast Router & Fire Pass Model Wire Routing: Models ending in
-fast(isFireworksFastModelIdinpackages/catalog/src/fireworks-model-id.ts) represent high-throughput serving routes.buildOpenAICompat(packages/catalog/src/compat/openai.ts) resolvesisFireworksFastRoutertowireModelIdMode: "firepass", mapping wire dispatch viatoFirepassWireModelIdtoaccounts/fireworks/routers/<id>-fastinstead ofaccounts/fireworks/models/. dropThinkingWhenReasoningEffortConflict Resolution:compat.dropThinkingWhenReasoningEffortis set totruefor Fireworks inpackages/catalog/src/compat/openai.ts. Whenreasoning_effortis present in request parameters,applyOpenAIExtraBody(packages/ai/src/providers/openai-shared.ts) deletes top-levelthinkingtoggle objects to prevent HTTP 400 errors from Fireworks rejecting both parameters simultaneously.- Qwen Thinking Format Override:
buildOpenAICompat(packages/catalog/src/compat/openai.ts) assignsthinkingFormat: "openai"to Fireworks-hosted Qwen models (e.g.,fireworks/qwen3.7-plus) rather than"qwen", forcing the use ofreasoning_effortinstead of Alibaba DashScope’senable_thinkingboolean (which Fireworks rejects with 400). - Service Tier / Priority Control:
excludesInferredOpenAIServiceTierandshouldSendServiceTier(packages/ai/src/types.ts) allowfireworksrequests to sendservice_tier: "priority"whenproviders.fireworksTier: priority(or/fastmode) is enabled, suppressing unneeded tier defaults. - Stream Markup Healing:
modelMayLeakDsmlToolCallsinpackages/ai/src/utils/stream-markup-healing.tsflagsprovider === "fireworks", invokingThinkingInbandScannerto buffer and clean leaked DSML XML markup from visible text deltas.
Auth & usage
- API Key Authentication: Authenticates with HTTP Bearer tokens (
Authorization: Bearer ${apiKey}) configured viaFIREWORKS_API_KEY(resolved viagetEnvApiKeyinpackages/ai/src/stream.ts). - Control-Plane Login Validation:
/login fireworks(loginFireworksinpackages/ai/src/registry/fireworks.ts) validates credentials against the static control-plane catalogGET /v1/accounts/fireworks/models?filter=supports_serverless%3Dtrue&pageSize=1rather than/v1/models(the inference endpoint serves per-account deployments and returns 500 for accounts without active deployments). - Usage Accounting: Token usage is processed via standard
openai-completionsaccounting incalculateOpenAIUsageAccounting(packages/ai/src/providers/openai-shared.ts), extractingprompt_tokens,completion_tokens,prompt_tokens_details.cached_tokens, andcompletion_tokens_details.reasoning_tokens.
Catalog model handling
- Descriptor Registration: Registered in
CATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts) withid: "fireworks",defaultModel: "kimi-k2.7-code",envVars: ["FIREWORKS_API_KEY"], andcreateModelManagerOptions: fireworksModelManagerOptions. - Control-Plane Discovery:
fireworksModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts) enumerates models via control-plane catalogGET /v1/accounts/fireworks/models?filter=supports_serverless=trueinstead of/v1/models, converting resource names (accounts/fireworks/models/<id>) to public catalog IDs usingtoFireworksPublicModelId. Internal account resource IDs are pruned during catalog generation inscripts/generate-models.ts. - Fast Variant Seeding:
buildFireworksFastSeed(packages/catalog/src/provider-models/openai-compat.ts) programmatically generates-fastcatalog seeds (e.g.,kimi-k2.7-code-fast,glm-5.1-fast) paired to curated base models, retaining base pricing while targeting high-speed router wire paths. - Kimi Family Output Token Caps:
clampFireworksKimiMaxTokens(packages/catalog/src/provider-models/openai-compat.ts) clamps output budgetmaxTokenstoFIREWORKS_KIMI_MAX_TOKENS = 32_768for Kimi K2.5/K2.6 models (isFireworksKimiK2ModelId) to prevent runaway reasoning traces caused by Fireworks’ reportedmax_completion_tokens: 65536.kimi-k2.7-codeis explicitly excluded from this cap and allowed up to its full output budget (FIREWORKS_KIMI_K27_CODE_MAX_TOKENS = 65_536). - Reasoning Effort Ladders:
FIREWORKS_REASONING_EFFORT_MAP(packages/catalog/src/model-thinking.ts) mapsminimal -> "none"(disabling reasoning on Fireworks) while passinglow,medium, andhighthrough. Restrictive models (e.g.,minimax-m2.7,gpt-oss-120b) override effort ladders to[low, medium, high]in catalog definitions.
GitHub Copilot (github-copilot)
GitHub Copilot routes multi-vendor model execution (OpenAI GPT, Anthropic Claude, xAI Grok, Google Gemini) through GitHub’s unified proxy endpoints (https://api.githubcopilot.com or Enterprise copilot-api.<domain>). The provider dynamically dispatches across three wire transports: OpenAI Chat Completions, OpenAI Responses, and Anthropic Messages.
Special casings
- Dynamic Copilot Headers & Initiator:
buildCopilotDynamicHeaders(packages/ai/src/registry/github-copilot.ts) injects per-request headersX-Initiator("user"vs"agent"inferred from message history viainferCopilotInitiatoror overridden viagetCopilotInitiatorOverride),Openai-Intent: conversation-edits, andCopilot-Vision-Request: truewhenhasCopilotVisionInputdetects image payloads in user or tool result blocks. - API Versioning & Wire Headers:
COPILOT_API_HEADERS(packages/catalog/src/wire/github-copilot.ts) mandatesUser-Agent: opencode/1.3.15(COPILOT_USER_AGENT) andX-GitHub-Api-Version: 2026-06-01(COPILOT_API_VERSION).restorableHeaderFallbackinpackages/catalog/src/provider-models/openai-compat.tspreserves static wire headers during offline cache rehydration. - Base URL & Endpoint Resolution:
resolveGitHubCopilotBaseUrl(packages/ai/src/registry/github-copilot.ts) andparseGitHubCopilotApiKey(packages/catalog/src/wire/github-copilot.ts) parse customenterpriseUrlandapiEndpointproperties embedded in API keys or credentials, defaulting tohttps://api.githubcopilot.com(PERSONAL_GITHUB_COPILOT_BASE_URL). - OpenAI & Responses Compat Flags:
supportsReasoningParams: Disabled (supportsReasoningParams: provider !== "github-copilot") inpackages/catalog/src/compat/openai.tsbecause Copilot Chat Completions endpoints rejectreasoning_effortand reasoning fields with HTTP 400.supportsDeveloperRole: Disabled for Chat Completions specs (openai-compat.ts) but enabled on OpenAI Responses specs.strictResponsesPairing: Enabled (spec.provider === "github-copilot") inpackages/catalog/src/compat/openai.ts, forcing strict pairing between tool calls and tool result messages on Responses endpoints.supportsImageDetailOriginal: Disabled (supportsImageDetailOriginal: false), clamping image detail from"original"to"auto"to avoid proxy 400/422 rejection.
- Anthropic Wire & Signing Compat:
supportsEagerToolInputStreaming: Disabled (supportsEagerToolInputStreaming: false) inpackages/catalog/src/compat/anthropic.tsand fine-grained tool streaming beta headers are omitted because the Copilot Anthropic proxy rejectseager_input_streaming(#2558).- Recognized as a signing host (
buildAnthropicCompat), suppressing unsigned thinking replay for Claude models (#2851).
Auth & usage
- Device-Flow OAuth (
opencodeOAuth app):loginGitHubCopilotinpackages/ai/src/registry/oauth/github-copilot.tsexecutes the GitHub Device Authorization Flow using client IDOv23li8tweQw6odWQebz(CLIENT_ID) and scoperead:user.startDeviceFlowposts tohttps://<domain>/login/device/codewithOPENCODE_HEADERS.pollForGitHubAccessTokenpollshttps://<domain>/login/oauth/access_token, automatically handlingauthorization_pendingandslow_downrate-limit backoffs.- Post-login,
discoverGitHubCopilotApiEndpointquerieshttps://api.github.com/copilot_internal/user, andenableAllGitHubCopilotModelsissues model enablement requests (POST /models/{modelId}/policywith{ state: "enabled" }andopenai-intent: chat-policy).
- Token Exchange & Refresh:
refreshGitHubCopilotToken(packages/ai/src/registry/oauth/github-copilot.ts) uses long-lived GitHub OAuth tokens directly without secondary JWT exchange cycles, setting expiry toFAR_FUTURE_MS(10 years).
- Usage & Quota Accounting:
fetchInternalUsageinpackages/ai/src/usage/github-copilot.tsqueriesGET /copilot_internal/useronresolveGitHubApiBaseUrlwithOPENCODE_HEADERS.normalizeQuotaSnapshotsandbuildLimitFromQuotaconvertquota_snapshots(chat,completions,premium_interactions) andquota_reset_dateinto monthlyUsageLimitstructures (copilot:premium,copilot:chat,copilot:completions).fetchBillingUsageprovides supplementary user billing details (/settings/billing/premium_request/usage).getCopilotPremiumRequests(packages/ai/src/registry/github-copilot.ts) calculates model premium request cost:0for agent turns (initiator === "agent"), orgetCopilotPremiumMultiplier(premiumMultiplier, planTier)for user turns.
Catalog model handling
- Descriptor & Management: Registered as
github-copilotdescriptor inPROVIDER_DESCRIPTORS(packages/catalog/src/provider-models/descriptors.ts) withdefaultModel: "gpt-5.5"and env varCOPILOT_GITHUB_TOKEN. Options constructed viagithubCopilotModelManagerOptions. - Dynamic Model Discovery:
fetchDynamicModelsinpackages/catalog/src/provider-models/openai-compat.tsfetches/modelsusingCOPILOT_API_HEADERS. Parses window/token limits fromentry.capabilities.limits(maxContextWindowTokens,maxPromptTokens,maxOutputTokens), infers wire API (inferCopilotApi), and configures vision support (extractCopilotSupportsVision). - Long-Context Variant Synthesis: Models advertising long-context pricing in
billing.token_prices.long_contexttriggercreateCopilotLongContextVariantto synthesize opt-in-1mcatalog models (e.g.,claude-opus-4.7-1mwithrequestModelId: "claude-opus-4.7"). The base model receives acontextPromotionTargetpointing to its long-context sibling. - Premium Request Multipliers: Model-specific request multipliers are mapped in
COPILOT_PREMIUM_MULTIPLIERS(packages/catalog/scripts/generate-models.ts), assigning values such asgpt-4o: 0,grok-code-fast-1: 0.25,claude-haiku-4.5: 0.33,gpt-5.4-mini: 0.33, andclaude-opus-4.6: 3.
GitLab Duo Non-Agentic (gitlab-duo)
GitLab Duo Non-Agentic (gitlab-duo) proxies Duo Chat LLM completion requests to GitLab AI Gateway proxy endpoints. Depending on the target model mapping, it dynamically delegates execution to the Anthropic Messages, OpenAI Chat Completions, or OpenAI Responses wire transports. It rides the shared GitLab Duo transport section.
Special casings
- Model ID Mapping & Routing:
MODEL_MAPPINGSinpackages/ai/src/providers/gitlab-duo.tsmaps Duo model identifiers (duo-chat-opus-4-6,duo-chat-sonnet-4-6,duo-chat-opus-4-5,duo-chat-sonnet-4-5,duo-chat-haiku-4-5,duo-chat-gpt-5-1,duo-chat-gpt-5-2,duo-chat-gpt-5-mini,duo-chat-gpt-5-codex,duo-chat-gpt-5-2-codex) to backend providers (anthropicoropenai), underlying model IDs, API schemas (anthropic-messages,openai-completions,openai-responses), and proxy target URLs (ANTHROPIC_PROXY_URL=https://cloud.gitlab.com/ai/v1/proxy/anthropic/orOPENAI_PROXY_URL=https://cloud.gitlab.com/ai/v1/proxy/openai/v1). - Canonical Model Alias Lookup:
getModelMappinginpackages/ai/src/providers/gitlab-duo.tsresolves model mappings by matching either the Duo alias key or the underlying canonical model ID string (e.g.gpt-5-codexorclaude-sonnet-4-5-20250929). - Direct Access Token Exchange & Caching:
getDirectAccessTokeninpackages/ai/src/providers/gitlab-duo.tsexchanges a user’s GitLab access token for a short-lived direct access token viaPOST https://gitlab.com/api/v4/ai/third_party_agents/direct_accesswith{ feature_flags: { DuoAgentPlatformNext: true } }. The resulting token and headers are cached indirectAccessCachefor 25 minutes (DIRECT_ACCESS_TTL_MS). - Delegated Stream Dispatch:
streamGitLabDuoinpackages/ai/src/providers/gitlab-duo.tsvalidates the user token (MissingApiKeyError), fetches direct access headers, translates Anthropic tool choice viamapAnthropicToolChoice(packages/ai/src/stream.ts), and dispatches tostreamAnthropic,streamOpenAICompletions, orstreamOpenAIResponses(packages/ai/src/providers/register-builtins.ts) using synthesized model specs (buildModel).
Auth & usage
- PAT & OAuth Support:
gitlabDuoProviderinpackages/ai/src/registry/gitlab-duo.tssupports Personal Access Tokens viaGITLAB_TOKENor PKCE browser OAuth vialoginGitLabDuoinpackages/ai/src/registry/oauth/gitlab-duo.ts. - OAuth Authorization & Client ID:
GitLabDuoOAuthFlowinpackages/ai/src/registry/oauth/gitlab-duo.tsexecutes PKCE OAuth againsthttps://gitlab.com/oauth/authorize(scope: "api",callbackPort: 8080,pasteCodeFlow: true). UsesDEFAULT_CLIENT_ID("da4edff2e6ebd2bc3208611e2768bc1c1dd7be791dc5ff26ca34ca9ee44f7d4b"), overrideable viaGITLAB_CLIENT_ID(resolveClientId) andGITLAB_REDIRECT_URI(resolveCallbackOptions). - Token Refresh & Cache Invalidation:
refreshGitLabDuoTokeninpackages/ai/src/registry/oauth/gitlab-duo.tsexchanges refresh tokens athttps://gitlab.com/oauth/token. Both exchange and refresh clear cached direct access tokens viaclearGitLabDuoDirectAccessCache(packages/ai/src/providers/gitlab-duo.ts). - Usage Surface: Nothing beyond the GitLab Duo pipeline.
Catalog model handling
- Descriptor Config:
PROVIDER_DESCRIPTORSinpackages/catalog/src/provider-models/descriptors.tsregistersgitlab-duowithdefaultModel: "duo-chat-opus-4-6"andenvVars: ["GITLAB_TOKEN"]. - Static Catalog Generation:
scripts/generate-models.tsinpackages/cataloginvokesgetGitLabDuoModels(packages/ai/src/providers/gitlab-duo.ts), convertingMODEL_MAPPINGSentries into bundledModelSpecdefinitions inmodels.json. - Provider Priority:
PROVIDER_PRIORITYinpackages/catalog/src/identity/priority.tsassignsgitlab-duopriority rank 35.
GitLab Duo Agent (gitlab-duo-agent)
The gitlab-duo-agent provider connects OMP to the GitLab Duo Workflow Service (DWS) for agentic execution over a WebSocket action-bridge protocol. It rides the GitLab Duo transport section.
Special casings
- Stream Direct Bypass & Thinking Healing: In
packages/ai/src/stream.ts,gitlab-duo-agentbypasseswithProviderInFlightLimitand standarditerateWithIdleTimeoutwrappers.streamGitLabDuoWorkflow(packages/ai/src/providers/gitlab-duo-workflow.ts) is invoked directly wrapped inhealLeakedThinking. - Runtime Namespace Resolution & Auto-Enablement: Stream initialization invokes
resolveGitLabDuoWorkflowNamespaceSelection(packages/ai/src/providers/gitlab-duo-workflow.ts) to resolve the root namespace from options,GITLAB_DUO_NAMESPACE_ID/GITLAB_DUO_PROJECT_IDenv vars, or workspace git remotes.ensureGitLabDuoWorkflowSettingsposts to/api/v4/ai/duo_workflows/settings(30s timeout viaGITLAB_DUO_WORKFLOW_REST_TIMEOUT_MS) to auto-enable required namespace settings (duo_workflow,duo_workflow_service,duo_agent_platform). - ChatML Goal & Inline Spec Generation: Renders conversation history into a ChatML goal string (
buildGitLabDuoWorkflowGoal,renderGitLabDuoWorkflowChatMl), subject to 1MB soft (GITLAB_DUO_WORKFLOW_GOAL_SOFT_OVERFLOW_BYTES) and 2MB hard (GITLAB_DUO_WORKFLOW_GOAL_HARD_OVERFLOW_BYTES) limits. Emits an ambient inline workflow definition (buildGitLabDuoWorkflowInlineFlowConfig) targetingomp_agent. - WebSocket Action Bridge: Tool definitions are converted into MCP format (
buildGitLabDuoWorkflowMcpTools) instartRequest.mcpTools. IncomingrunMCPTool/run_mcp_toolactions over the WebSocket are extracted (extractGitLabDuoWorkflowAction), executed locally, and returned viabuildGitLabDuoWorkflowActionResponse.
Auth & usage
- Registry & Credential Resolution: Provider definition
gitLabDuoWorkflowProvider(packages/ai/src/registry/gitlab-duo-workflow.ts) requiresGITLAB_TOKEN(PAT or OAuth token). - OAuth PKCE & Official Client ID: Browser authentication (
loginGitLabDuoWorkflowinpackages/ai/src/registry/oauth/gitlab-duo-workflow.ts) uses S256 PKCE withpasteCodeFlow: trueon callback port 8080. It uses official GitLab VS Code client IDGITLAB_DUO_WORKFLOW_OAUTH_CLIENT_ID(36f2a70cddeb5a0889d4fd8295c241b7e9848e89cf9e599d0eed2d8e5350fbf5) and redirect URIvscode://gitlab.gitlab-workflow/authentication, supporting manual callback URL pasting if VS Code intercepts the redirect. Token refresh usesrefreshGitLabDuoWorkflowToken. - Direct Access Tokens: Requests ephemeral credentials via
POST /api/v4/ai/duo_workflows/direct_access(requestGitLabDuoWorkflowDirectAccessinpackages/ai/src/providers/gitlab-duo-workflow.ts). No dedicated usage module exists underpackages/ai/src/usage/. - Context Telemetry Usage:
extractGitLabDuoWorkflowContextUsageextracts checkpoint telemetry (agent_context_usage), prioritizing"Chat Agent"and"context_builder"entries, and updates token estimates viaapplyGitLabDuoWorkflowContextUsage.
Catalog model handling
- Provider Descriptor: Registered in
packages/catalog/src/provider-models/descriptors.tswithdefaultModel: "claude_sonnet_4_6_vertex",envVars: ["GITLAB_TOKEN"], anddynamicModelsAuthoritative: true. OmitscatalogDiscoveryto prevent single-account namespace discovery from running during static catalog generation. - Fingerprinted Scope Cache:
gitLabDuoWorkflowModelManagerOptionsinpackages/catalog/src/provider-models/special.tsconfigures dynamic model management.gitLabDuoWorkflowModelCacheProviderIdpartitions dynamic catalog caches usingBun.hashonapiKeyand a scope string ofbaseUrl,namespaceId,projectId, and workspacecwd. - GraphQL Discovery:
fetchGitLabDuoWorkflowModels(packages/catalog/src/discovery/gitlab-duo-workflow.ts) callsdiscoverGitLabDuoWorkflowNamespaceto locate the root namespace (via explicit config, env, or git remote matchingdiscoverGitLabRemoteProjectPath) and executes GraphQL queryaiChatAvailableModels(rootNamespaceId:)to querydefaultModel,selectableModels, andpinnedModel. - Model Specs & Context Windows:
buildGitLabDuoWorkflowModelSpecconstructs model specs withreasoning: false(disabling thinking UI controls because Duo Agent Platform manages Anthropic reasoning parameters server-side).resolveGitLabDuoWorkflowContextWindowmaps model refs to context window sizes (Claude Opus/Sonnet: 1,000,000; Haiku: 200,000; Gemini: 1,000,000; GPT-5: 400,000; default: 200,000). - Fallback Model Seeding:
scripts/generate-models.tsseedsbuildGitLabDuoWorkflowFallbackModel()(claude_sonnet_4_6_vertex) so unauthenticated/fresh installations contain a default model entry.
GMI Cloud (gmi-cloud)
GMI Cloud is an AI GPU infrastructure and cloud model inference provider hosting open-weight and proprietary model endpoints. It operates over the OpenAI Chat Completions transport using the standard /v1 wire protocol hosted at https://api.gmi-serving.com/v1.
Special casings
- Nothing beyond the OpenAI Chat Completions pipeline.
Auth & usage
- API Key Login & Validation:
loginGmiCloud(packages/ai/src/registry/gmi-cloud.ts) implements interactive API key authentication viacreateApiKeyLogin, pointing users tohttps://console.gmicloud.ai. Key validation useskind: "models-endpoint"hittinghttps://api.gmi-serving.com/v1/modelsthroughvalidateOpenAICompatibleApiKey(packages/ai/src/registry/api-key-validation.ts). - Environment Variables: Primary credential resolution inspects
GMI_API_KEY(envVarsinpackages/catalog/src/provider-models/descriptors.ts). - Provider Registry:
gmiCloudProvider(packages/ai/src/registry/gmi-cloud.ts) is exported inpackages/ai/src/registry/registry.tswithin the provider definitions array.
Catalog model handling
- Descriptor & Gateway Options: Registered in
CATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts) withid: "gmi-cloud",defaultModel: "deepseek-ai/DeepSeek-V4-Flash", anddynamicModelsAuthoritative: true. Gateway options are created bygmiCloudModelManagerOptionswrappingcreateSimpleOpenAICompletionsOptionswithGMI_CLOUD_BASE_URL(https://api.gmi-serving.com/v1) (packages/catalog/src/provider-models/openai-compat.ts). - Dynamic Model Discovery: Configured with
catalogDiscovery: { label: "GMI Cloud" }(packages/catalog/src/provider-models/descriptors.ts) to dynamically query/v1/modelsviafetchOpenAICompatibleModels(packages/catalog/src/discovery/openai-compatible.ts). When API credentials are available, live discovery results marked as authoritative overwrite cached or static entries. - Static Seed Model:
GMI_CLOUD_STATIC_MODELS(packages/catalog/src/provider-models/openai-compat.ts) defines a bundled fallback seed fordeepseek-ai/DeepSeek-V4-Flash(1,048,576 context window, 384,000 max tokens,$0.14/$0.28per 1M input/output tokens, reasoning enabled withHighandMaxeffort modes). This seed ensures that fresh installs or model generation runs lackingGMI_API_KEYcan synchronously resolve the provider’s default model (packages/catalog/scripts/generate-models.ts,packages/catalog/test/gmi-cloud-provider.test.ts).
Google Antigravity (google-antigravity)
The Google Antigravity provider (google-antigravity) routes requests to Google Cloud Code Assist daily/sandbox endpoints (daily-cloudcode-pa.googleapis.com) using dedicated OAuth credentials. It provides access to Google Gemini 3.x/2.5 models as well as Anthropic Claude and OpenAI GPT-OSS models using the shared “Google Gemini CLI / Antigravity” transport (packages/ai/src/providers/google-gemini-cli.ts).
Special casings
- Validated Function Calling Default: Default tool selection mode in
buildRequest(packages/ai/src/providers/google-gemini-cli.ts) isVALIDATED(functionCallingConfig: { mode: "VALIDATED" }). Claude models on Antigravity always forceVALIDATEDtool mode even when no tools are declared (packages/ai/src/providers/google-gemini-cli.ts). - System Instruction & Request Envelope:
shouldInjectAntigravitySystemInstructioninpackages/ai/src/providers/google-gemini-cli.tsprependsANTIGRAVITY_SYSTEM_INSTRUCTIONwithrole: "user"for Claude and Gemini 3 models.buildAntigravityRequestEnvelopeinjects structuredrequestId(agent/<id>/<ts>/<trajectoryId>/<step>),userAgent: "antigravity",requestType: "agent",sessionId, andlabels(model_enum,trajectory_id,last_step_index,last_execution_id,used_claude*) usinggetAntigravityModelWireProfile. - Endpoint Auto-Failover: Operates across
ANTIGRAVITY_DAILY_ENDPOINT(https://daily-cloudcode-pa.googleapis.com) andANTIGRAVITY_SANDBOX_ENDPOINT(https://daily-cloudcode-pa.sandbox.googleapis.com) with state-tracked fallback ingetAntigravityProviderSessionState(packages/ai/src/providers/google-gemini-cli.ts).
Auth & usage
- Dedicated OAuth Flow:
loginAntigravityandrefreshAntigravityToken(packages/ai/src/registry/oauth/google-antigravity.ts) execute an independent OAuth flow with distinct client credentials, callback port 51121, and project discovery/provisioning via/v1internal:loadCodeAssistand/v1internal:onboardUserusingANTIGRAVITY_LOAD_CODE_ASSIST_METADATA. - Model-Family Credential Ranking:
antigravityRankingStrategy(packages/ai/src/usage/google-antigravity.ts) scopes usage limits by model family (scopeAntigravityLimitsForModelviagetAntigravityCounterKeyForModel:anthropicforclaude-,googleforgemini-/gemma-,openaiforgpt-/openai/). This prevents quota exhaustion on one counter (e.g. Gemini) from blocking multi-account credential selection for another family (e.g. Claude).
Catalog model handling
- Catalog Discovery:
fetchAntigravityDiscoveryModels(packages/catalog/src/discovery/antigravity.ts) queries/v1internal:fetchAvailableModels, filters denylisted IDs (chat_20706,chat_23310,gemini-2.5-pro) and internal models (isInternal), and applies effort-tier variant collapsing viaANTIGRAVITY_VARIANT_COLLAPSE_TABLE. - Claude & GPT-OSS Model Availability: Exposes Anthropic Claude models (
claude-opus-4-5,claude-opus-4-6,claude-sonnet-4-5,claude-sonnet-4-6) andgpt-oss-120balongside Gemini 3.x/2.5 models inmodels.json(packages/catalog/src/models.json). - Pricing Fallback:
applyAntigravityPricingFallback(packages/catalog/scripts/generated-policies.ts) backfills 0-cost discovery models usingANTIGRAVITY_PRICING_PEERS(google,google-vertex,anthropic) andANTIGRAVITY_PRICING_ID_ALIASES(gemini-3-flash->gemini-3-flash-preview,claude-opus-4-5->claude-opus-4-5@20251101), mapping Gemini models to Google API prices and Claude models to Google Vertex list prices.
Google Gemini CLI (google-gemini-cli)
Google Cloud Code Assist (Gemini CLI) (google-gemini-cli) is Google’s OAuth-authenticated developer free and workspace tier providing direct access to Gemini models over the Cloud Code Assist API endpoint (https://cloudcode-pa.googleapis.com). Rides the shared Google Gemini CLI / Antigravity transport section (packages/ai/src/providers/google-gemini-cli.ts).
Special casings
- Default Endpoint & Headers: Dispatches requests to
https://cloudcode-pa.googleapis.comand emits headers viagetGeminiCliHeaders()(GeminiCLI/0.46.0/<modelId> ...inpackages/catalog/src/wire/gemini-headers.ts). - Thinking Transport: Maps Gemini thinking via
google-levelthinkingLeveltransport (GEMINI_CLI_VARIANT_COLLAPSE_TABLEinpackages/catalog/src/variant-collapse.ts), unlikegoogle-antigravitywhich usesbudgettransport (ANTIGRAVITY_VARIANT_COLLAPSE_TABLE). - Standard request pipeline: Nothing beyond the Google Gemini CLI / Antigravity transport pipeline.
Auth & usage
- OAuth Installed-App Flow: Authorizes via Google PKCE OAuth 2.0 (
loginGeminiCliinpackages/ai/src/registry/oauth/google-gemini-cli.ts) on callback port8085(/oauth2callback) requesting Google Cloud scopes (cloud-platform,userinfo.email,userinfo.profile). Refresh is handled viarefreshGoogleCloudToken(packages/ai/src/registry/oauth/google-gemini-cli.ts). - Project Discovery & Onboarding:
discoverProject(packages/ai/src/registry/oauth/google-gemini-cli.ts) checks existing projects viaPOST /v1internal:loadCodeAssistwith$GOOGLE_CLOUD_PROJECT/$GOOGLE_CLOUD_PROJECT_IDfallback. Non-free tiers (legacy-tier,standard-tier) or new accounts callPOST /v1internal:onboardUserwithtierId(free-tier,legacy-tier,standard-tier) and pollpollOperation(up toPOLL_MAX_ATTEMPTS = 24at 5s intervals). Detects VPC-SC restrictions (isVpcScAffectedUsercheckingSECURITY_POLICY_VIOLATED). - Quota & Usage Provider:
googleGeminiCliUsageProvider(packages/ai/src/usage/gemini.ts) posts toloadCodeAssistandretrieveUserQuota(/v1internal:retrieveUserQuota), mapping remaining bucket fractions into usage percentages grouped by model tier (3-Flash,Flash,ProviagetModelTier).
Catalog model handling
- Provider Descriptor: Registered in
CATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts) withdefaultModel: "gemini-3.1-pro-preview"andspecialModelManager: true, bypassing standard model factories. - Model Resolution & Discovery:
googleGeminiCliModelManagerOptions(packages/catalog/src/provider-models/google.ts) configures runtime discovery by callingfetchAntigravityDiscoveryModels(packages/catalog/src/discovery/antigravity.ts) withGEMINI_CLI_VARIANT_COLLAPSE_TABLE, rewriting model providers togoogle-gemini-cliand base URL tohttps://cloudcode-pa.googleapis.com. - Generator Integration & Priority: Serves as fallback OAuth token provider in
fetchAntigravityModels(packages/catalog/scripts/generate-models.ts) ifgoogle-antigravityaccess is unavailable. Ranked second in provider priority (packages/catalog/src/identity/priority.ts).
Groq (groq)
Groq provides high-speed LLM inference powered by custom LPU hardware for open-weights models using the OpenAI Chat Completions transport (https://api.groq.com/openai/v1).
Special casings
- Context Overflow: Detected when error messages match
/reduce the length of the messages/iinOVERFLOW_PATTERNS(packages/ai/src/error/flags.ts). - Reasoning Effort Mapping: Model
qwen/qwen3-32bmapsMinimal,Low,Medium,High, andXHighto"default"viaGROQ_QWEN3_32B_REASONING_EFFORT_MAP(packages/catalog/src/model-thinking.ts). - Multiple System Messages: Supported natively by default in OpenAI compatibility settings via
isGroqHostinsupportsMultipleSystemMessagesDefault(packages/catalog/src/compat/openai.ts).
Auth & usage
- Auth: Authenticates via
GROQ_API_KEYenvironment variable (packages/catalog/src/provider-models/descriptors.ts). - Provider Registry: Registered as
groqProvider(packages/ai/src/registry/groq.ts). - Priority: Listed 19th in provider priority ordering (
packages/catalog/src/identity/priority.ts).
Catalog model handling
- Host Matching: Matched by URL marker
api.groq.comor providergroqin host definitions (packages/catalog/src/hosts.ts). - Manager Options: Configured via
groqModelManagerOptionstargetinghttps://api.groq.com/openai/v1(packages/catalog/src/provider-models/openai-compat.ts). - Default Model: Defaults to
openai/gpt-oss-120b(packages/catalog/src/provider-models/descriptors.ts).
Hugging Face Inference (huggingface)
Hugging Face Inference provides access to open-source model serverless endpoints hosted on the Hugging Face Hub using the OpenAI Chat Completions transport (openai-completions) pointing to https://router.huggingface.co/v1. The provider enables serverless LLM generation across models including DeepSeek-R1.
Special casings
- Standard Transport Pipeline: Nothing beyond the OpenAI Chat Completions pipeline (
packages/ai/src/providers/openai-completions.ts).
Auth & usage
- Environment Fallbacks: Environment variable resolution in
getEnvApiKey(packages/ai/src/stream.ts) consultsenvVarsfromCATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts), checkingHUGGINGFACE_HUB_TOKENfirst, followed byHF_TOKEN. - Interactive CLI Login:
loginHuggingfaceinpackages/ai/src/registry/huggingface.tsusescreateApiKeyLogin(packages/ai/src/registry/api-key-login.ts) to prompt for fine-grained user access tokens (placeholderhf_...). - Fine-Grained Token Permission: Auth setup directs users to
https://huggingface.co/settings/tokens/new?ownUserPermissions=inference.serverless.write&tokenType=fineGrained(AUTH_URLinpackages/ai/src/registry/huggingface.ts), which automatically selects fine-grained tokens with the required “Make calls to Inference Providers” permission (inference.serverless.write). - Credential Validation:
loginHuggingfacevalidates API keys using lightweight chat completion requests to base URLhttps://router.huggingface.co/v1(API_BASE_URL) against validation modelopenai/gpt-oss-120b(VALIDATION_MODELinpackages/ai/src/registry/huggingface.ts).
Catalog model handling
- Provider Descriptor: Registered in
CATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts) withid: "huggingface",defaultModel: "deepseek-ai/DeepSeek-R1", environment fallbacksenvVars: ["HUGGINGFACE_HUB_TOKEN", "HF_TOKEN"], andcatalogDiscovery: { label: "Hugging Face" }. - Model Manager Options:
huggingfaceModelManagerOptionsinpackages/catalog/src/provider-models/openai-compat.tsconstructs manager options viacreateSimpleOpenAICompletionsOptions, binding default base URLhttps://router.huggingface.co/v1and mapping static models with bundled reference specs (mapWithBundledReference). - Catalog Descriptor:
openAiCompletionsDescriptorinpackages/catalog/src/provider-models/openai-compat.tsregistershuggingfaceinPROVIDER_DESCRIPTORStargetinghttps://router.huggingface.co/v1. - Catalog Discovery: Participating in catalog generation via
catalogDiscovery,generate-models.ts(packages/catalog/scripts/generate-models.ts) resolves API tokens viaresolveProviderApiKeyand callsfetchOpenAICompatibleModels(packages/catalog/src/discovery/openai-compatible.ts) againsthttps://router.huggingface.co/v1/modelsto discover available Hub inference endpoints.
Kilo Gateway (kilo)
Kilo Gateway (kilo) is an AI model aggregator and proxy service (https://api.kilo.ai/api/gateway) using the OpenAI Chat Completions transport (api: "openai-completions"). It supports authentication via KILO_API_KEY or device-code OAuth flow (/login kilo), and allows unauthenticated dynamic model discovery from its OpenAI-compatible /models catalog endpoint.
Special casings
- Device-Code OAuth Authentication:
loginKiloinpackages/ai/src/registry/kilo.tsinitiates device authorization viaPOST https://api.kilo.ai/api/device-auth/codes, returning a usercode,verificationUrl, andexpiresInseconds. It displays instructions viacallbacks.onAuthand pollsGET https://api.kilo.ai/api/device-auth/codes/<userCode>every 5,000ms until expiration. Handles HTTP 202 (pending), 403/410 (denied/expired), and rate limiting (HTTP 429), returning access tokens with 1-year expiration upon approval (pollData.status === "approved"). Supports cancellation viacallbacks.signal. - Non-Standard Host Classification:
modelMatchesHost(hostModel, "kilo")setsisKiloinpackages/catalog/src/compat/openai.ts, placing Kilo among non-standard OpenAI-compatible providers (isNonStandard) to govern transport compatibility behavior. - Host URL Matching: Host mapping in
packages/catalog/src/hosts.tsassociates URL markerapi.kilo.aiwith provider"kilo". - Provider Priority: Included in
packages/catalog/src/identity/priority.tsprovider priority sequence ("opencode-go","kilo","vercel-ai-gateway").
Auth & usage
- API Key & OAuth Tokens: Authenticates via static environment variable
KILO_API_KEYor OAuth access tokens issued through the device-code flow (/login kilo). - Bearer Token Headers: Requests pass credentials as standard Bearer tokens (
Authorization: Bearer <key>) against base URLhttps://api.kilo.ai/api/gateway.
Catalog model handling
- Provider Descriptor: Registered in
packages/catalog/src/provider-models/descriptors.tswithdefaultModel: "anthropic/claude-opus-4.8", environment variableKILO_API_KEY, andcatalogDiscovery: { label: "Kilo Gateway", allowUnauthenticated: true }enabling catalog discovery without requiring an API key. - Model Manager & Wire Descriptor:
kiloModelManagerOptionsinpackages/catalog/src/provider-models/openai-compat.tsmapsproviderId: "kilo"to base URLhttps://api.kilo.ai/api/gatewayand delegates dynamic model discovery tofetchOpenAICompatibleModels. Associated withopenAiCompletionsDescriptor("kilo", "kilo", "https://api.kilo.ai/api/gateway"). - Thinking Configuration: Models routed via Kilo (such as
moonshotai/kimi-k2.6) inherit standard OpenAI-style thinking format resolution (compat.thinkingFormat = "openai").
Kimi Code (kimi-code)
Kimi Code provides subscription-backed access to Kimi models (kimi-for-coding, k3) via Moonshot AI’s /coding/v1 API endpoints. It rides the Kimi Code transport pipeline, delegating request execution to streamKimi (packages/ai/src/providers/kimi.ts) and streamOpenAIAnthropicShim (packages/ai/src/providers/openai-anthropic-shim.ts).
Special casings
- Prompt Cache Key Sharing:
isKimiModel(packages/ai/src/providers/kimi.ts) gates prompt caching; Anthropic-compatible (packages/ai/src/providers/anthropic.ts:3480) and OpenAI-compatible (packages/ai/src/providers/openai-completions.ts:1508) requests both attachprompt_cache_keyderived viagetOpenAIPromptCacheKeyto share affinity identity across transport switches. - Common Header Prepending:
prependHeadersinpackages/ai/src/providers/openai-completions.tsinjectsgetKimiCommonHeaders()(packages/ai/src/registry/oauth/kimi.ts) into allkimi-coderequests. - Schema Validation & Tool Choice: Matched via
isMoonshotNative(packages/catalog/src/hosts.ts), enforcingtoolSchemaFlavor: "moonshot-mfjs"(packages/catalog/src/compat/openai.ts). Mandatory-thinking models (kimi-for-coding,k3) resolverequiresThinkingEnabled = truein Anthropic compat (packages/catalog/src/compat/anthropic.ts), downgrading forced tool choice toauto. - Reasoning Guard:
stream.ts:1214checksisKimiModelbefore execution, disabling unsupported reasoning configurations on K3 (packages/ai/src/providers/openai-completions.ts:1454).
Auth & usage
- Device OAuth Flow:
kimiCodeProvider(packages/ai/src/registry/kimi-code.ts) lazy-loadsloginKimiandrefreshKimiToken(packages/ai/src/registry/oauth/kimi.ts). Uses OAuth 2.0 Device Code Authorization (CLIENT_ID17e5f671-d194-4dfb-9706-5516cb48c098) against${resolveOAuthHost()}(https://auth.kimi.com, overrideable viaKIMI_CODE_OAUTH_HOSTorKIMI_OAUTH_HOST). - Fingerprinting & Device Persistence:
getKimiCommonHeaders()injects tracking headers (User-Agent: KimiCLI/<ver>,X-Msh-Platform,X-Msh-Version,X-Msh-Device-Name,X-Msh-Device-Model,X-Msh-Os-Version,X-Msh-Device-Id).getDeviceIdpersists a random hex UUID topath.join(getAgentDir(), "kimi-device-id")(mode0600), falling back to an in-memory ephemeral UUID if file writing fails. - Usage & Quota Tracker:
kimiUsageProvider(packages/ai/src/usage/kimi.ts) fetchesGET /coding/v1/usages(https://api.kimi.com/coding/v1/usages, configurable viaKIMI_CODE_BASE_URL) for OAuth credentials. Short-circuits when tokens are expired (credential.expiresAt <= nowMs). ParsesusageandlimitsintoUsageLimitentries, carrying row-level reset timestamps (reset_at,resetTime,ttl) to the window object when window reset time is absent.
Catalog model handling
- Provider Descriptor: Registered in
CATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts) withid: "kimi-code",defaultModel: "kimi-for-coding", discovery label"Kimi Code", andenvVars: ["KIMI_API_KEY"]. Delegate options build viakimiCodeModelManagerOptions. - Dynamic Model Discovery:
kimiCodeModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts) queries/coding/v1/modelsusingfetchOpenAICompatibleModelswithKimiCLI/1.0headers. Maps models viakimiSupportsReasoning,mapKimiThinking, andmapKimiApiFormat(settingcompat.kimiApiFormatto"anthropic"or"openai"). - Per-Family Output Ceilings:
kimiCodeMaxTokens(packages/catalog/src/provider-models/openai-compat.ts) derives output caps by ID: 131,072 (KIMI_CODE_K3_MAX_TOKENS) fork3/k3-256k, 32,768 (KIMI_CODE_FOR_CODING_MAX_TOKENS) forkimi-for-coding/kimi-for-coding-highspeed, and fallback 32,000 (KIMI_CODE_DEFAULT_MAX_TOKENS) for legacy K2 rows. Applied during static generation (packages/catalog/scripts/generate-models.ts).
LiteLLM (litellm)
LiteLLM is an open-source AI proxy and gateway that unifies access to multiple LLM providers behind an OpenAI-compatible API host. In pi, it operates using the OpenAI Chat Completions (openai-completions) transport pipeline.
Special casings
- Reasoning replay exclusion (
packages/catalog/src/compat/openai.ts): Listed inPROXY_OPENAI_COMPAT_PROVIDERS. Unlike native local runtimes (llama.cpp,vllm),replayReasoningContentdefaults tofalsebecause LiteLLM proxies route turns to arbitrary upstream providers (e.g., Anthropic, OpenAI) where replayingreasoning_contentcan trigger HTTP 400 errors. - Loopback stream-timeout floor (
packages/catalog/src/compat/openai.ts): Even though LiteLLM is excluded fromisLocalOpenAICompatBackend, loopback/RFC1918 URLs (localhost,127.0.0.1) still participate inhasLocalLoopbackBaseUrl, preserving the local stream-timeout floor to avoid premature prefill timeouts when fronting slow local backends. - Anthropic & Bedrock tool compatibility (
packages/ai/src/providers/openai-completions.ts):- When
context.toolsisundefinedbut conversation history contains tool calls,params.toolsis set to[]for Anthropic-via-LiteLLM compatibility. - When
context.toolsis explicitly empty ([], e.g.,/btwor background turns),params.toolsandtool_choice: "none"are omitted so LiteLLM → Bedrock routes do not generate invalid, emptytoolConfigblocks.
- When
- Telemetry & gateway header detection (
packages/ai/src/telemetry.ts,packages/ai/src/auth-gateway/http.ts):detectGatewayFromHeadersinspectsx-litellm-call-id(falling back tox-litellm-model-idorx-litellm-model-group) to populatepi.gen_ai.gateway.*span attributes. Auth gateway HTTP endpoints exposex-litellm-model-id,x-litellm-model-api-base,x-litellm-response-cost, andx-litellm-response-duration-ms.
Auth & usage
- Credentials & env (
packages/catalog/src/provider-models/descriptors.ts,packages/ai/src/registry/litellm.ts): Authenticates viaLITELLM_API_KEY. - Login onboarding (
packages/ai/src/registry/litellm.ts):loginLiteLLM(viacreateApiKeyLogin) directs users to setup docs (https://docs.litellm.ai/docs/proxy/deploy), prompts for master/virtual keys (sk-...), and notesLITELLM_BASE_URLfor custom proxy endpoints. CLIlogindelegates toSqliteAuthCredentialStore.login(). - Default base URL (
packages/catalog/src/provider-models/cache-provider-id.ts): Resolves toBun.env.LITELLM_BASE_URLorhttp://localhost:4000/v1.
Catalog model handling
- Bundled catalog exclusion (
packages/scripts/generate-models.ts): Included inDISCOVERY_ONLY_PROVIDERS. LiteLLM models are excluded from staticmodels.jsongeneration to avoid leaking developer localhost endpoints. - Rich management endpoint discovery (
packages/catalog/src/provider-models/openai-compat.ts):fetchLiteLLMRichModelsprobes/model_group/info,/v2/model/info,/model/info, and/v1/model/info. It filters sentinel placeholder IDs (all-team-models,all-proxy-models,no-default-models) and parses context limits (max_input_tokens), output limits (max_output_tokens),supports_vision,supports_reasoning,supported_openai_params(mappingreasoning_effort), and per-token pricing (input_cost_per_token,output_cost_per_token, cache read/write costs mapped to $/million tokens). - Fallback discovery & display names (
packages/catalog/src/provider-models/openai-compat.ts): If rich endpoints fail, discovery falls back to/v1/models(fetchOpenAICompatibleModels) and resolves specs againstmodels.devreferences. Strips reseller multiplier suffixes (e.g.,(1.5x usage)) from display names. - Compatibility overrides (
packages/catalog/src/provider-models/openai-compat.ts): Hardcodescompat.supportsStore: falseandcompat.supportsDeveloperRole: falsefor all resolved models.
LM Studio (lm-studio)
LM Studio is a local OpenAI-compatible model server running on user hardware (defaulting to http://127.0.0.1:1234/v1). It uses the OpenAI Chat Completions transport (api: "openai-completions") to stream chat completions and tool calls.
Special casings
- String-Only Named Tool Choice: Registered in
STRING_ONLY_NAMED_TOOL_CHOICE_PROVIDERS(packages/catalog/src/compat/openai.ts) withsupportsNamedToolChoice: false. Object-style forced tool choices ({ type: "function", function: { name: "..." } }) are downgraded to"required"while the advertisedtoolslist is narrowed to the single forced tool. - Grammar Schema Normalization: Configures
toolSchemaFlavor: "grammar"in catalog compat (packages/catalog/src/compat/openai.ts). Tool JSON schemas are sanitized viasanitizeSchemaForGrammar(packages/ai/src/utils/schema/normalize.ts), widening bare booleantrueor{}subschemas in property positions into primitive unions to avoid GBNF grammar parser failures (Unrecognized schema: true, issue #5914). - Replay Reasoning Content & Append-Only Context: Included in
LOCAL_OPENAI_COMPAT_PROVIDERS(packages/catalog/src/compat/openai.ts) andLOCAL_INFERENCE_PROVIDERS(packages/coding-agent/src/config/append-only-context-mode.ts).replayReasoningContentis auto-enabled for local reasoning models so<think>blocks are preserved inreasoning_contentacross turns for KV-cache hits in local chat templates;qwenPreserveThinkingis also enabled for Qwen thinking dialects. - Static Catalog Generator Exclusion: Listed in
DISCOVERY_ONLY_PROVIDERS(scripts/generate-models.ts) andLOCAL_ONLY_PROVIDERS(test/models-json-no-local-endpoints.test.ts), ensuring local endpoints are never fetched during build or committed to staticmodels.json.
Stream behavior
- Watchdog Timeout Floors: Configures
streamFirstEventTimeoutMs: 0(packages/catalog/src/compat/openai.ts) to disable the pre-response first-event watchdog during long local model cold-loads or prompt prefills, and setsstreamIdleTimeoutMs: 300_000(300s inter-event floor; see Provider compat reference) to prevent stream cancellation during slow token generation.
Auth & usage
- Keyless Local Auth: Defined as a keyless provider (
lmStudioProviderinpackages/ai/src/registry/lm-studio.ts,allowUnauthenticated: trueinpackages/catalog/src/provider-models/descriptors.ts). UsesDEFAULT_LOCAL_TOKEN = "lm-studio-local"whenLM_STUDIO_API_KEYis not provided. - Endpoint & Credentials: Base URL defaults to
http://127.0.0.1:1234/v1orLM_STUDIO_BASE_URL. Interactive CLI login usesloginLmStudio(createApiKeyLogininpackages/ai/src/registry/lm-studio.ts). - Usage Accounting: Employs standard OpenAI Chat Completions usage accounting (
calculateOpenAIUsageAccountinginpackages/ai/src/providers/openai-shared.ts).
Catalog model handling
- Implicit & Dynamic Discovery:
ModelRegistry(packages/coding-agent/src/config/model-registry.ts) auto-registerslm-studioas an implicit discoverable provider when unconfigured. Dynamic model resolution (lmStudioModelManagerOptionsinpackages/catalog/src/provider-models/openai-compat.ts/discoverLmStudioModelsinpackages/coding-agent/src/config/model-discovery.ts) queries/v1/models. - Native Metadata Probe: Probes LM Studio’s native endpoint
/api/v0/modelsviafetchLmStudioNativeModelMetadata(withLM_STUDIO_NATIVE_METADATA_TIMEOUT_MS = 250). Setsinput: ["text", "image"]whentype === "vlm"or capabilities includevision/image(settingimageInputDecoder: "stb"during discovery). - Loaded Context Length:
getLmStudioNativeContextWindowprefersloaded_context_lengthfor active models over architectural ceilings (max_context_length,context_length,max_model_len), ensuring context window limits accurately reflect current VRAM/RAM allocations.
Meta Model API (meta)
Meta Model API is Meta’s commercial API platform hosting first-party models such as muse-spark-1.1. It interacts with the model service via the OpenAI Responses transport targeting https://api.meta.ai/v1.
Special casings
- Output Token Clamp Bypass:
resolveOpenAIResponsesOutputClamp(packages/ai/src/providers/openai-shared.ts) checksmodel.provider === "meta"to allow Meta requests to output up tomodel.maxTokens(131,072 tokens) rather than being restricted by the default 64,000 token ceiling (OPENAI_MAX_OUTPUT_TOKENS).
Auth & usage
- API Key Login: Configured via
loginMeta/metaProvider(packages/ai/src/registry/meta.ts) usingcreateApiKeyLoginwith dashboard URLhttps://developer.meta.com/ai/. Validation issues a GET request tohttps://api.meta.ai/v1/models. - Environment Variables: Key resolution checks
MODEL_API_KEYfirst, falling back toMETA_API_KEY(packages/catalog/src/provider-models/descriptors.ts).
Catalog model handling
- Descriptor & Management: Defined in
CATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts) withdefaultModel: "muse-spark-1.1". UsesmetaModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts) constructed viacreateOpenAICompatibleModelManagerOptions(api: "openai-responses",providerId: "meta",defaultBaseUrl: "https://api.meta.ai/v1",mapModel: mapWithBundledReference). - Static Bundled Models:
META_MUSE_STATIC_MODELS(packages/catalog/src/provider-models/openai-compat.ts) definesmuse-spark-1.1:- 1,048,576 token context window and 131,072 token max output limit.
- Multimodal input support (
text,image). - Reasoning enabled with effort-based thinking levels (
minimal,low,medium,high,xhigh). - Compatibility flags
supportsReasoningEffort: trueandincludeEncryptedReasoning: true.
MiniMax (minimax)
MiniMax provides foundation models (including MiniMax-M3 and M2 generation) accessible via regional international (api.minimax.io) and mainland China (api.minimaxi.com) endpoints. Transport depends on descriptor type: standard minimax and minimax-cn use “Anthropic Messages” (/anthropic), while MiniMax Token Plan minimax-code and minimax-code-cn use “OpenAI Chat Completions” (/v1).
Special casings
- Cumulative reasoning deltas:
MINIMAX_PROVIDER_OR_ID_PATTERNinpackages/catalog/src/compat/openai.tsflagsreasoningDeltasMayBeCumulative: truefor any provider or model ID matching/minimax/i, preventing duplicate reasoning content when streams resend cumulative thinking text. - Object tool args:
streamOpenAICompletionsinpackages/ai/src/providers/openai-completions.tsintercepts MiniMax-compatible hosts that streamfunction.argumentsas raw JSON objects rather than standard JSON strings, deep-merging object deltas intoblock.partialArgsand serializing a single concat-safe string delta atfinishToolCallBlockbeforetoolcall_end. - Single system message constraint:
isMiniMaxHostinpackages/catalog/src/compat/openai.ts(matchingapi.minimax.ioandapi.minimaxi.cominpackages/catalog/src/hosts.ts) setssupportsMultipleSystemMessagesDefaulttofalse, requiring system prompts to be merged into a single system message. - Thinking effort restriction:
isMinimaxM2FamilyModelIdinpackages/catalog/src/identity/family.tsenforceslow|medium|highallowedreasoning_effortfor M2/M3 models and rejectsminimal/xhigh. - Inband XML dialect:
packages/ai/src/dialect/minimax.tsregisters theminimaxdialect (<minimax:tool_call>) for fallback XML tool invocation parsing. - Gateway API overrides:
OPENCODE_ZEN_API_RESOLUTIONandOPENCODE_GO_API_RESOLUTIONinpackages/catalog/src/provider-models/openai-compat.tsforceminimax-m3/minimax-m3-free/minimax-m2.7on OpenCode gateways to route overopenai-completionsat/v1/chat/completionsinstead of Anthropic/v1/messages.
Auth & usage
- Auth keys: Uses
MINIMAX_API_KEY(minimax),MINIMAX_CODE_API_KEY(minimax-code), andMINIMAX_CODE_CN_API_KEY(minimax-code-cn) declared inpackages/catalog/src/provider-models/descriptors.ts. - Token Plan login:
loginMiniMaxCodeandloginMiniMaxCodeCninpackages/ai/src/registry/oauth/minimax-code.tsdrive browser login flows toplatform.minimax.io(international) andplatform.minimaxi.com(China) to prompt and validate API key setup against modelMiniMax-M3. - Usage quota:
minimaxCodeUsageProviderinpackages/ai/src/usage/minimax-code.tspollsGET /v1/token_plan/remainsathttps://api.minimax.io(or China equivalent), parsing rolling interval and weekly usage windows per plan bucket into remaining percentages formusepi usage.
Catalog model handling
- Default model:
MiniMax-M3set inpackages/catalog/src/provider-models/descriptors.ts(minimax,minimax-code,minimax-code-cn). - Context window policy:
scripts/generated-policies.tsoverridesMiniMax-M3context limits to 1,000,000 tokens forminimax,minimax-cn,minimax-code, andminimax-code-cn, matching the documented 1M long-context tier over upstream pricing boundaries. - OpenAI completions flags:
openAiCompletionsDescriptorinpackages/catalog/src/provider-models/openai-compat.tsconfiguressupportsStore: false,supportsDeveloperRole: false,supportsReasoningEffort: false, andreasoningContentField: "reasoning_content".
MiniMax Token Plan (minimax-code)
The MiniMax Token Plan provider (minimax-code, alongside its mainland China regional variant minimax-code-cn) provides access to MiniMax subscription models such as MiniMax-M3 and MiniMax-M2.5 using the OpenAI Chat Completions transport over HTTP POST SSE (https://api.minimax.io/v1 for international, https://api.minimaxi.com/v1 for China). In contrast to plain minimax (which routes over the Anthropic Messages transport using standard static API key authentication), minimax-code uses an interactive subscription login flow and features token plan quota monitoring via musepi usage.
Special casings
- Transport Difference from Plain
minimax: Plainminimax(minimax/minimax-cn) communicates over theanthropic-messagestransport (https://api.minimax.io/anthropic), whereasminimax-code(minimax-code/minimax-code-cn) targets theopenai-completionstransport (/v1/chat/completions). - Streaming Object Tool Call Arguments:
mergeStreamingArgumentObjectsinpackages/ai/src/providers/openai-completions.tshandles MiniMax backends that streamfunction.argumentsas partial JSON objects instead of standard OpenAI JSON strings, deep-merging object properties across deltas to prevent[object Object]string coercions. - Reasoning Content & Think Tag Deduplication: Configured with
reasoningContentField: "reasoning_content"(packages/catalog/src/provider-models/openai-compat.ts). The provider parses inline<think>…</think>tags into thinking blocks while deduplicating MiniMax-M3 cumulative reasoning snapshots to prevent re-emitting thinking text after visible answer content has started. - Compat Flag Restrictions: OpenAI compatibility policy explicitly disables
store, developer system roles, and reasoning effort controls (supportsStore: false,supportsDeveloperRole: false,supportsReasoningEffort: falseinpackages/catalog/src/provider-models/openai-compat.ts).
Auth & usage
- Interactive Subscription Login Flow: Implemented via
createApiKeyLogininpackages/ai/src/registry/oauth/minimax-code.ts(lazy-loaded bypackages/ai/src/registry/minimax-code.tsandminimax-code-cn.ts). Despite residing underoauth/, this is an interactive API key prompt rather than OAuth PKCE: it opens the regional subscription portal (https://platform.minimax.io/subscribe/token-planfor international,https://platform.minimaxi.com/subscribe/token-planfor China), prompts for key entry (sk-...), and validates the key via aPOST /v1/chat/completionsrequest usingMiniMax-M3. - Environment Variables: Resolves credentials from
MINIMAX_CODE_API_KEYfor internationalminimax-codeandMINIMAX_CODE_CN_API_KEYfor Chinaminimax-code-cn(plainminimaxresolvesMINIMAX_API_KEY/MINIMAX_CN_API_KEY). - Token Plan Quota Tracking:
minimaxCodeUsageProviderinpackages/ai/src/usage/minimax-code.tsqueriesGET /v1/token_plan/remainswithAuthorization: Bearer ${apiKey}. - Quota Metric Parsing & Normalization: Parses
model_remains[]entries into rolling interval windows (current_interval_*) and 7-day windows (current_weekly_*). The shared plan quotageneralis scoped as{ shared: true }. CalculatesusedFractionvia(100 - remainingPercent) / 100and overrides status ifcurrent_*_status === 2(STATUS_EXHAUSTED). Out-of-plan models (status 3STATUS_UNLIMITEDwith zero totals) are filtered out intometadata.unavailableModels. Validates success viabase_resp.status_code === 0to catch API errors returned under HTTP 200 responses.
Catalog model handling
- Provider Descriptors: Registered in
packages/catalog/src/provider-models/descriptors.ts(id: "minimax-code",id: "minimax-code-cn"), defaulting toMiniMax-M3. - Catalog Wiring:
openAiCompletionsDescriptorinpackages/catalog/src/provider-models/openai-compat.tsregisters descriptors"minimax-coding-plan"and"minimax-cn-coding-plan"bound to base URLshttps://api.minimax.io/v1andhttps://api.minimaxi.com/v1. - 1M Context Tier Override: Policy generation (
packages/catalog/scripts/generated-policies.ts) explicitly overridesMiniMax-M3context windows forminimax-codeandminimax-code-cnto report the documented 1,000,000-token tier instead of the upstream 512,000-token pricing boundary. - Host Matching: Provider host mapping in
packages/catalog/src/hosts.tsassociatesurlMarkersapi.minimax.ioandapi.minimaxi.comwithminimax,minimax-code, andminimax-code-cn.
MiniMax Token Plan (China) (minimax-code-cn)
MiniMax Token Plan (China) provides access to MiniMax models for mainland China subscribers using the OpenAI Chat Completions transport (openai-completions). It connects to China regional endpoints for subscription onboarding, API key validation, and model execution.
Special casings
- Streaming Argument Deep Merge:
mergeStreamingArgumentObjectsinpackages/ai/src/providers/openai-completions.tshandles MiniMax backends streamingfunction.argumentsas raw JSON objects instead of standard OpenAI JSON strings, recursively merging partial object deltas across stream chunks without failing or coercing arguments to[object Object](test/issue-1776-repro.test.ts,test/issue-2080-repro.test.ts). - Reasoning Deduplication & Think Tags:
<think>tags delivered in content streams are normalized into thinking blocks (test/issue-1203-repro.test.ts), whilelastCumulativeReasoningBySignatureinpackages/ai/src/dialect/demotion.tsandstreamOpenAICompletionsOnce(packages/ai/src/providers/openai-completions.ts) deduplicate cumulative reasoning snapshots forMiniMax-M3across text block transitions. - Unsupported Feature Stripping: Requests omit unsupported thinking options (
test/issue-955-repro.test.ts) and apply static compatibility overrides inpackages/catalog/src/provider-models/openai-compat.ts(supportsStore: false,supportsDeveloperRole: false,supportsReasoningEffort: false,reasoningContentField: "reasoning_content").
Auth & usage
- API Key & Interactive Login: Authenticates via
MINIMAX_CODE_CN_API_KEY(packages/catalog/src/provider-models/descriptors.ts). Interactive login (loginMiniMaxCodeCninpackages/ai/src/registry/oauth/minimax-code.ts) openshttps://platform.minimaxi.com/subscribe/token-planand validates the pasted key via aMiniMax-M3completions check againsthttps://api.minimaxi.com/v1. - Endpoints & Host Detection: API requests target
https://api.minimaxi.com/v1(packages/catalog/src/models.json).urlMarkersincludesapi.minimaxi.comunder theminimaxhost classification inpackages/catalog/src/hosts.ts. - Usage Telemetry Availability: Unlike
minimax-code(which fetches quota remaining percentages fromhttps://api.minimax.io/v1/token_plan/remainsviaminimaxCodeUsageProviderinpackages/ai/src/usage/minimax-code.ts),minimax-code-cnhas no usage provider registered (storage.usageProviderFor("minimax-code-cn")returnsundefinedinpackages/ai/src/auth-storage.tsandtest/minimax-token-plan-usage.test.ts), so usage telemetry is disabled for China regional accounts.
Catalog model handling
- Default Model: Configured to default to
MiniMax-M3inCATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts). - 1M Context Window Override:
packages/catalog/scripts/generated-policies.tsoverridesMiniMax-M3context window from the upstream 512K pricing boundary to 1,000,000 (1M) tokens (model.contextWindow = 1_000_000) forminimax-code-cn(alongsideminimax-code,minimax, andminimax-cn). - Catalog Policy Overrides:
generated-policies.tsremovesthinkingFormatfrommodel.compatand enforcesreasoningContentField: "reasoning_content",supportsStore: false,supportsDeveloperRole: false, andsupportsReasoningEffort: false.
Mistral (mistral)
Mistral AI provides access to Mistral, Codestral, Devstral, Ministral, and Pixtral models via api.mistral.ai/v1. Requests use the OpenAI Chat Completions transport (openai-completions).
Special casings
- Compat Cluster (
packages/catalog/src/compat/openai.ts:isMistral):requiresMistralToolIds/toolCallIdKind: "mistral-9-alnum"(packages/ai/src/providers/openai-shared.ts): Restricts tool call IDs to 9-character alphanumeric strings ([a-zA-Z0-9]{9}).requiresAssistantAfterToolResult: Synthesizes an assistant message bridge following tool result messages prior to subsequent content (packages/ai/src/providers/openai-completions.ts).requiresToolResultName: Mandates the tool functionnameproperty on tool result messages (packages/ai/src/providers/openai-completions.ts).requiresThinkingAsText: Formats reasoning and thinking content as plain text blocks instead of native reasoning fields (packages/catalog/src/compat/openai.ts).maxTokensField: "max_tokens": Emitsmax_tokensinstead ofmax_completion_tokensin request payloads (packages/catalog/src/compat/openai.ts).
- Array
delta.contentStreaming Normalization (packages/ai/src/providers/openai-completions.ts:normalizeStreamingContentText): Unpacks streaming response chunks where models (e.g.mistral-medium-2604) deliverdelta.contentas typed arrays ([{ type: "text", text: "..." }]), preventing[object Object]string coercion bugs.
Auth & usage
- Authentication: Authenticates using bearer tokens from the
MISTRAL_API_KEYenvironment variable (packages/catalog/src/provider-models/descriptors.ts:mistral). - Usage Tracking: Standard OpenAI chat completions usage parsing (
packages/ai/src/providers/openai-completions.ts).
Catalog model handling
- Provider Descriptor: Configured via
mistralModelManagerOptionspointing tohttps://api.mistral.ai/v1(packages/catalog/src/provider-models/openai-compat.ts) with default modeldevstral-medium-latest(packages/catalog/src/provider-models/descriptors.ts). - Host Matching: Host URL marker matching checks for
mistral.ai(packages/catalog/src/hosts.ts:mistral).
Moonshot (moonshot)
Moonshot is the pay-as-you-go open platform provider for Moonshot AI endpoints (https://api.moonshot.ai/v1 or mainland China https://api.moonshot.cn/v1). It rides the OpenAI Chat Completions transport engine (openai-completions API surface) and shares Kimi-family dialect and thinking mechanics (isKimiModelId in packages/catalog/src/identity/family.ts). It is distinct from kimi-code, which uses subscription device OAuth and subscription endpoints (api.kimi.com / /coding/v1/*).
Special casings
MOONSHOT_BASE_URLOverride:resolveOpenAIRequestSetup(packages/ai/src/providers/openai-shared.ts) overrides default catalog base URLs (api.moonshot.ai/v1) with$env.MOONSHOT_BASE_URL(e.g.https://api.moonshot.cn/v1for mainland China platform users whose keys are rejected by the international endpoint; issue #2883).- Moonshot Flavored JSON Schema (
moonshot-mfjs):toolSchemaFlavordefaults to"moonshot-mfjs"for native Moonshot hosts (moonshotNativeinpackages/catalog/src/hosts.ts) and Kimi model IDs (isKimiModel) viabuildOpenAICompat(packages/catalog/src/compat/openai.ts).normalizeSchemaForMoonshot(packages/ai/src/utils/schema/normalize.ts) normalizes tool parameters (collapsesconstintoenum, inferstypeon bare enums, strips unsupported constructs) inpackages/ai/src/providers/openai-completions.tsandopenai-responses.tsto prevent HTTP 400 validation failures (tools.function.parameters is not a valid moonshot flavored json schema). - Z.AI Thinking Format & Preserved Thinking:
isMoonshotKimiinpackages/catalog/src/compat/openai.tssetsthinkingFormat: "zai". Forkimi-k2.6(andkimi-k2.xmodels),thinkingKeep: "all"is enabled (usesMoonshotKimiPreservedThinkingincompat/openai.ts). Active reasoning turns emitthinking: { type: "enabled", keep: "all" }(or{ type: "disabled" }when disabled) inopenai-completions.ts(issues #1838,#2113). K3 models use OpenAI-stylereasoning_effort: "max"viaMOONSHOT_KIMI_K3_THINKING(packages/catalog/src/provider-models/openai-compat.ts). - Stream Markup Healing & Inband Control Tags:
modelMayLeakKimiToolCalls(packages/ai/src/utils/stream-markup-healing.ts) anddetectStreamMarkupHealingPattern(packages/catalog/src/compat/openai.ts) return"kimi"forprovider === "moonshot", enabling stream parsing for raw inband control tags (<|tool_calls_section_begin|>, etc.). - Max Token Output Ceiling & Forced Tokens:
alwaysSendMaxTokens(packages/catalog/src/compat/openai.ts) forcesmax_tokenson every Kimi request because Moonshot calculates TPM rate limits frommax_tokens.resolveOpenAIRequestSetup(packages/ai/src/providers/openai-shared.ts) capsmax_tokensfor K3 models (isKimiK3ModelId) to131_072. - Reasoning Content Replay Requirement:
requiresReasoningContentForToolCalls(packages/catalog/src/compat/openai.ts) forces tool-call continuation turns to replay priorreasoning_content(or a synthetic placeholder.), preventing Moonshot from aborting or re-deriving reasoning from scratch.
Auth & usage
- API-Key Authentication:
loginMoonshot(packages/ai/src/registry/moonshot.ts) usescreateApiKeyLoginpointing users to dashboardhttps://platform.moonshot.ai/console/api-keys. - Endpoint Validation:
resolveMoonshotModelsUrl(packages/ai/src/registry/moonshot.ts) validates keys viaGET ${MOONSHOT_BASE_URL || "https://api.moonshot.ai/v1"}/models(kind: "models-endpoint"). - Environment Variable Resolution:
envVars: ["MOONSHOT_API_KEY", "KIMI_API_KEY"]inpackages/catalog/src/provider-models/descriptors.tsacceptsKIMI_API_KEYas a fallback for mainland China users who configure Kimi keys withoutMOONSHOT_API_KEY(issue #2883). - No Dedicated Usage Tracker: Token usage is returned directly in OpenAI stream chunk
usageobjects inopenai-completions; no separate usage API or file exists inpackages/ai/src/usage/.
Catalog model handling
- Descriptor Registration: Registered as
moonshotinCATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts) withdefaultModel: "kimi-k2.7-code",envVars: ["MOONSHOT_API_KEY", "KIMI_API_KEY"], andcreateModelManagerOptions: moonshotModelManagerOptions. - Dynamic Model Discovery:
moonshotModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts) usescreateOpenAICompatibleModelManagerOptionswithdefaultBaseUrl: Bun.env.MOONSHOT_BASE_URL ?? "https://api.moonshot.ai/v1". - Dynamic K3 & K2.x Model Mapping: In
moonshotModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts):- Unreferenced
kimi-k3entries are stamped withreasoning: true, input["text", "image"],MOONSHOT_KIMI_K3_COST,contextWindow: 1_000_000,maxTokens: 131_072, and effort-basedthinkingconfig (issue #5756). kimi-k2.xentries (e.g.kimi-k2.5,kimi-k2.6) are marked withreasoning: true, vision["text", "image"], and multi-tier effort ([Minimal, Low, Medium, High]), ensuringthinkingpayloads are generated so models do not stall (issue #2113).
- Unreferenced
- Host & Priority Token Classification: Host marker
moonshotNative(urlMarkers: ["api.moonshot.ai", "api.kimi.com"]) inpackages/catalog/src/hosts.tsmaps native Moonshot endpoints. Family priority token inpackages/catalog/src/identity/priority.tsranks"moonshot"right after"kimi-code".
NanoGPT (nanogpt)
NanoGPT is a pay-per-token API gateway exposing diverse open-weights and commercial language models via an OpenAI-compatible interface. It executes requests using the OpenAI Chat Completions transport (openai-completions) with a default base URL of https://nano-gpt.com/api/v1.
Special casings
- DSML Leak Healing: NanoGPT is included in
modelMayLeakDsmlToolCallsinpackages/ai/src/utils/stream-markup-healing.ts. DeepSeek models hosted on NanoGPT (such asnanogpt/deepseek/deepseek-v4-pro) that leak<|DSML|tool_calls>...</|DSML|tool_calls>text envelopes during streaming are routed togetStreamMarkupHealingPattern("nanogpt", modelId)to heal the stream into structured tool calls. - Direct Route Execution: NanoGPT avoids appending
:toolsmodel route suffixes on DeepSeek requests, preventing502errors withcode: "malformed_tool_call"triggered by NanoGPT’s server-side tool parser on complex schemas. - Indexed Tool Delta Preservation: Relies on
tool_calls[].indextracking instreamOpenAICompletionsOnce(packages/ai/src/providers/openai-completions.ts) to ensure parallel streaming tool calls from NanoGPT do not merge or drop arguments across deltas.
Auth & usage
- API Key & Environment Variables: Authenticates via
NANO_GPT_API_KEY(resolved viagetEnvApiKeyinpackages/ai/src/stream.tsand configured in catalog descriptorspackages/catalog/src/provider-models/descriptors.ts). - Interactive Login:
loginNanoGPTinpackages/ai/src/registry/nanogpt.tsprompts for an API key linked fromhttps://nano-gpt.com/apiand validates credentials viamodels-endpointagainsthttps://nano-gpt.com/api/v1/models.
Catalog model handling
- Descriptor & Options: Registered in
CATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts) with default modelopenai/gpt-5.5and options configured viananoGptModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts). - Model Variant Filtering: During dynamic discovery in
fetchDynamicModels, models matching non-text tokens inNANO_GPT_NON_TEXT_MODEL_TOKENS(e.g.,embedding,image,vision,audio,speech,transcribe,moderation,realtime,whisper,tts) are filtered out byisLikelyNanoGptTextModelId. - Thinking Variant Detection: Models with
:thinkingor:thinking:<level>suffixes are matched byNANO_GPT_THINKING_SUFFIX_REand excluded from model listings, while their base model IDs are recorded inthinkingBaseIdsto flag corresponding base models as reasoning-capable (model.reasoning = true).
Novita (novita)
Novita AI is an AI cloud platform offering serverless OpenAI-compatible LLM inference for open models. It uses the OpenAI Chat Completions transport over https://api.novita.ai/openai/v1.
Special casings
- Nothing beyond the OpenAI Chat Completions pipeline.
Auth & usage
- Authentication: Configured via
loginNovita(packages/ai/src/registry/novita.ts) using standard API key prompt (sk_...) linking tohttps://novita.ai/settings/key-management. Environment variableNOVITA_API_KEYis checked via catalog descriptors (packages/catalog/src/provider-models/descriptors.ts). - Inference-based key validation:
loginNovita(packages/ai/src/registry/novita.ts) validates keys by sending a 1-token request to/chat/completionsusingmoonshotai/kimi-k2.7-code. Novita’s Developer and Basic team roles lack permission for/openapi/v1/billing/balance/detail, so inference validation avoids rejecting valid developer keys.
Catalog model handling
- Model discovery: Configured via
novitaModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts) withdefaultBaseUrl: "https://api.novita.ai/openai/v1"anddynamicModelsAuthoritative: true. - Unauthenticated discovery: Descriptor sets
catalogDiscovery.allowUnauthenticated: true(packages/catalog/src/provider-models/descriptors.ts), allowing public catalog retrieval from/openai/v1/modelswithout an API key. - Model filtering:
filterModelverifies active status (status === 1or non-number), requiresendpointsto include"chat/completions", checks positivemax_output_tokens, and excludes internal test model IDs usingisPublicNovitaModelId(excluding prefixes starting withai_infer_test). - Cost scaling:
toNovitaCostPerMillionconverts price fields (input_token_price_per_m,output_token_price_per_m,pricing.input_cache_read.price_per_m) by dividing by 10,000, scaling Novita’s 1/10,000-USD per million rate to standard USD per million tokens. - Capabilities & metadata:
mapNovitaModelinspectsfeaturesvianovitaArrayIncludesfor"reasoning"and"function-calling", parses input modalities withtoInputCapabilities, and extracts context/output window bounds.
NVIDIA (nvidia)
NVIDIA NIM (Inference Microservice) provides access to hosted open and proprietary foundation models via the OpenAI Chat Completions transport (openai-completions API). Base endpoints default to https://integrate.api.nvidia.com/v1.
Special casings
- Qwen Thinking Format: Host
nvidia(integrate.api.nvidia.com,packages/catalog/src/hosts.ts:63) routes Qwen models (isQwen) tothinkingFormat: "qwen-chat-template"(packages/catalog/src/compat/openai.ts:452). Top-levelenable_thinkingis rejected by NIM’s strict request schema (additionalProperties: false), so thinking is passed viachat_template_kwargs.enable_thinking. - DeepSeek Token Stripping & DSML Markup:
stripDeepseekSpecialTokensis set totruefor DeepSeek models underprovider === "nvidia"(packages/catalog/src/compat/openai.ts:596,755), stripping leaked raw<|DSML|...|>envelopes and thinking tags from visible output (packages/ai/test/openai-completions-compat.test.ts:2096-2216). Registered inmodelMayLeakDsmlToolCallsfor stream markup healing (packages/ai/src/utils/stream-markup-healing.ts:227). - Tool Choice & Reasoning: DeepSeek reasoning models disable reasoning when tool choice is active (
disableReasoningOnToolChoice,packages/catalog/src/compat/openai.ts:487), while standard models support forced tool choice (supportsForcedToolChoice: true,packages/ai/test/openai-completions-compat.test.ts:1801).
Auth & usage
- Authentication: Key-based auth using NVIDIA NGC Personal Keys (
AUTH_URL = "https://org.ngc.nvidia.com/setup/personal-keys",packages/ai/src/registry/nvidia.ts:6), stored inNVIDIA_API_KEY(packages/catalog/src/provider-models/descriptors.ts:316). Base URL isAPI_BASE_URL = "https://integrate.api.nvidia.com/v1"(packages/ai/src/registry/nvidia.ts:7). - Login & Validation: CLI login (
loginNvidia,packages/ai/src/registry/nvidia.ts:12) validates keys againstVALIDATION_MODEL = "nvidia/llama-3.1-nemotron-70b-instruct"(packages/ai/src/registry/nvidia.ts:8) usingvalidateOpenAICompatibleApiKey. Fatal auth errors (401/403,AIError.Flag.AuthFailed) abort login; non-fatal validation errors are caught to allow custom or newly deployed models. - Provider Registration: Registered as
nvidiaProvider(packages/ai/src/registry/nvidia.ts:57,packages/ai/src/registry/registry.ts:126). Credential storage and deduplication are tested inpackages/ai/test/auth-storage-email-dedupe.test.ts:756-775. - Usage: Standard OpenAI Chat Completions usage metrics; no custom usage handler or quota endpoint.
Catalog model handling
- Descriptor & Options: Configured via
nvidiaModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts:1072) andopenAiCompletionsDescriptor(packages/catalog/src/provider-models/openai-compat.ts:5675). - Defaults: Default context window is
131072(packages/catalog/src/provider-models/openai-compat.ts:5676). Default model isnvidia/llama-3.1-nemotron-70b-instruct(packages/catalog/src/provider-models/descriptors.ts:315). - Catalog Discovery: Registered in catalog descriptors with
catalogDiscovery: { label: "NVIDIA" }(packages/catalog/src/provider-models/descriptors.ts:318).
Ollama (ollama)
Local OpenAI-compatible provider integration running on local or self-hosted Ollama instances (defaulting to base URL http://127.0.0.1:11434/v1). Discovered models ride the shared Ollama and OpenAI Responses transport engines.
Special casings
- Tool-Call Error Rewriting:
rewriteOllamaToolCallJsonErrorinpackages/ai/src/error/format.tsintercepts HTTP 500 tool-call JSON parse failures from the localllama.cppbackend matchingLLAMA_CPP_TOOL_CALL_PARSE_PATTERNand rewrites them to explain deterministic model-output degradation during context overflow. - Empty-Length Finish Context Error:
emptyLengthFinishIsContextErroris set totruewhenprovider === "ollama"inbuildOpenAICompat(packages/catalog/src/compat/openai.ts), treating empty completions withfinish_reason: "length"as context overflow errors. - KV-Cache Reasoning Replay:
LOCAL_OPENAI_COMPAT_PROVIDERSinpackages/catalog/src/compat/openai.tsincludes"ollama", auto-enablingOpenAICompat.replayReasoningContentso local Qwen3 / DeepSeek-R1 / GLM chat-templates reconstruct prior<think>blocks across turns for byte-identical prefix-KV-cache reuse. - DSML Tool-Call Markup Healing:
modelMayLeakDsmlToolCallsinpackages/ai/src/utils/stream-markup-healing.tsandDSML_HEALING_PROVIDERSinpackages/catalog/src/compat/openai.tsinclude"ollama"to heal leaked DeepSeek DSML tool-call envelopes in visible text streams. - Wire Reasoning Effort Ladder:
spec.provider === "ollama"inpackages/catalog/src/model-thinking.tsreturnsOLLAMA_REASONING_EFFORTS([low, medium, high, max]), matching Ollama’s native wire effort vocabulary without requiring compat-level effort remapping.
Auth & usage
- Interactive Login & Optional Key:
loginOllamainpackages/ai/src/registry/ollama.tsprompts viaoptions.onPromptfor an optional API key/token (allowEmpty: true, placeholder"ollama-local") pointing toOLLAMA_DOCS_URL; returning""signals local keyless mode.ollamaProviderregistersloginOllama. - Usage Provider & Quota Surfacing:
ollamaUsageProviderinpackages/ai/src/usage/ollama.ts(id: "ollama") implementsfetchUsage, returning aUsageReportwith emptylimitsand a note that standalone quota endpoints are not exposed;validatesCredentialsis set tofalse. - Environment Variable Fallback:
envVars: ["OLLAMA_API_KEY"]inCATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts) resolves optional caller credentials fromprocess.env.OLLAMA_API_KEY.
Catalog model handling
- Descriptor & Keyless Registration:
CATALOG_PROVIDERSinpackages/catalog/src/provider-models/descriptors.tsregistersid: "ollama"withdefaultModel: "gpt-oss:20b",envVars: ["OLLAMA_API_KEY"],allowUnauthenticated: true(permitting model manager creation without a key), andcreateModelManagerOptionsdelegating toollamaModelManagerOptions. - Static Bundle Exclusion:
DISCOVERY_ONLY_PROVIDERSinscripts/generate-models.tsincludes"ollama", preventing local endpoints from baking machine-specific localhost models into the committedmodels.json. - Dynamic Model Discovery:
ollamaModelManagerOptionsinpackages/catalog/src/provider-models/openai-compat.tsnormalizes the endpoint vianormalizeOllamaBaseUrl(defaulting tohttp://127.0.0.1:11434/v1) and queries/v1/modelsusingfetchOpenAICompatibleModels(packages/catalog/src/discovery/openai-compatible.ts). If/v1/modelsis unavailable or empty, it falls back to nativefetchOllamaNativeModelsquerying/api/tagsontoOllamaNativeBaseUrl(http://127.0.0.1:11434). - Capability Probing & Context-Length Stamping:
fetchOllamaShowMetadatainpackages/catalog/src/provider-models/openai-compat.tsposts{ model: modelId }to/api/showviacreateOllamaMetadataResolver. It extracts context length frommodel_infokeys matching.context_length,.num_ctx, or.context_window(falling back toOLLAMA_FALLBACK_CONTEXT_WINDOW= 128,000 andOLLAMA_DEFAULT_MAX_TOKENS= 8,192).capabilities.includes("thinking")setsreasoning: trueand configuresthinkingefforts ([minimal, low, medium, high]), whilecapabilities.includes("vision")stampsinput: ["text", "image"]. - Model Cache Partitioning:
cacheProviderIdinollamaModelManagerOptionsinvokesresolveModelCacheProviderId(packages/catalog/src/provider-models/cache-provider-id.ts), partitioning local model cache keys byollama:ollama-models-v1:<hash>derived frombaseUrl.
Ollama Cloud (ollama-cloud)
Ollama Cloud provides managed cloud access to open-weight LLMs via native ollama-chat protocol endpoints at https://ollama.com. It rides the Ollama transport section, distinguishing itself from local Ollama by requiring explicit API key authentication and enforcing cloud-specific history sanitization and output token caps.
Special casings
- Assistant History Thinking Stripping:
convertMessages(packages/ai/src/providers/ollama.ts) stripsthinkingfields from assistant history messages whenmodel.provider === "ollama-cloud". Ollama Cloud endpoints reject incoming history containingthinkingwith HTTP 400 errors, whereas localollamaretains them. - Reasoning Effort Mapping:
mapReasoning(packages/ai/src/providers/ollama.ts) maps reasoning throughmodel.thinking.effortMap.OLLAMA_CLOUD_GLM_52_THINKING(packages/catalog/src/provider-models/ollama.ts) restricts GLM-5.2 reasoning effort levels tohighandmax, assigned viaisOllamaCloudGlm52ReasoningEffortModel(packages/catalog/src/model-thinking.ts). - Wire-Level Output Token Clamping:
resolveNumPredict(packages/ai/src/providers/ollama.ts) clampsoptions.num_predicttoOLLAMA_CLOUD_NUM_PREDICT_CAP(65,536) forollama-cloudmodels, acting as a safety net against HTTP 400 errors whenmaxTokensor overrides are passed (#3392). Localollamaendpoints do not clampnum_predict. - Stream Markup Healing: Registered in
DSML_HEALING_PROVIDERS(packages/catalog/src/compat/openai.ts) andgetStreamMarkupHealingPattern(packages/ai/src/utils/stream-markup-healing.ts) for XML/markdown tool call and reasoning recovery.
Auth & usage
- Interactive Key Authentication:
loginOllamaCloud(packages/ai/src/registry/ollama-cloud.ts) prompts for an API key generated athttps://ollama.com/settings/keys, rejecting empty input withApiKeyRequiredError. - Environment Variable Resolution:
descriptors.ts(packages/catalog/src/provider-models/descriptors.ts) andgetEnvApiKey(packages/ai/src/stream.ts) resolve credentials viaOLLAMA_CLOUD_API_KEY. - Usage Accounting:
ollamaCloudUsageProvider(packages/ai/src/usage/ollama.ts) handles usage forollama-cloudusingfetchOllamaUsage. Because Ollama Cloud has no standalone quota API (validatesCredentials: false), usage is tracked per-response viaprompt_eval_countandeval_countstream metrics.
Catalog model handling
- Descriptor & Discovery Wiring: Descriptor
CATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts) definesdefaultModel: "gpt-oss:120b",envVars: ["OLLAMA_CLOUD_API_KEY"], options builderollamaCloudModelManagerOptions, andcatalogDiscovery: { label: "Ollama Cloud", oauthProvider: "ollama-cloud" }. - Dynamic Model Discovery &
/api/showMetadata:ollamaCloudModelManagerOptions(packages/catalog/src/provider-models/ollama.ts) fetches models viaGET /api/tagsonhttps://ollama.comusing Bearer token auth, then queriesPOST /api/show(fetchShowMetadata) per model to inspect capabilities (thinking,vision) andmodel_infocontext window size (defaulting to 128,000). Returns an empty list when unauthenticated. - Output Token Ceiling & Token Parameter Omission:
isOllamaCloudOutputCapped(packages/catalog/src/provider-models/ollama.ts) identifies DeepSeek V4 Pro/Flash models, pinningmaxTokenstoMath.min(contextWindow, OLLAMA_CLOUD_MAX_OUTPUT_TOKENS)(65,536) to prevent backend rejected requests (ollama/ollama#16890, #7266). All discovered cloud models setomitMaxOutputTokens: true(also enforced viaapplyGeneratedModelPolicyinpackages/catalog/scripts/generated-policies.ts).
OpenCode Go (opencode-go)
OpenCode Go provides access to multi-provider subscription models (including Kimi, DeepSeek, GLM, Qwen, and MiniMax) through a unified gateway at https://opencode.ai/zen/go. Depending on the target model, requests route over the OpenAI Chat Completions or Anthropic Messages transport pipelines with dynamic API resolution.
Special casings
- API Resolution & Model ID Overrides:
createOpenCodeApiResolution(packages/catalog/src/provider-models/openai-compat.ts) constructsOPENCODE_GO_API_RESOLUTIONforhttps://opencode.ai/zen/go. Explicit ID overrides (minimax-m2.7,minimax-m3,minimax-m3-free,qwen3.5-plus,qwen3.6-plus) take precedence over npm-based heuristics (@ai-sdk/anthropic), forcing route resolution toopenai-completionsat/v1/chat/completionsto prevent gateway 404 HTML errors or raw tool-call markup leaks. - Reasoning Tool-Call Replay Policy:
OPENCODE_WHEN_THINKINGinpackages/catalog/src/compat/openai.tsis applied whenisOpenCodeProvideris true (opencode-go/opencode-zen) and reasoning is active. It setsrequiresReasoningContentForToolCalls: true,allowsSyntheticReasoningContentForToolCalls: false, andreasoningContentField: "reasoning_content", satisfying gateway requirements that 400 whenreasoning_contentis missing on thinking tool-call replays (#1484) or sent when thinking is off (#1071). X-Api-KeyAuth Normalization: Inpackages/ai/src/providers/anthropic.ts(lines 3045–3046), whenmodel.provider === "opencode-go", the transport deletes auto-generatedAuthorizationBearer headers soAnthropicMessagesClientemitsX-Api-Key. Bearer-only requests to OpenCode Anthropic endpoints fail with HTTP401 Missing API key(#6510).
Auth & usage
- API Key Login Flow:
opencodeGoProvider(packages/ai/src/registry/opencode-go.ts) lazy-importsloginOpenCodefrompackages/ai/src/registry/oauth/opencode.ts. It directs the user tohttps://opencode.ai/authviaonAuth, prompts for the API key viaonPrompt, and returns the trimmed key stored underOPENCODE_API_KEY. - Rolling Spend Windows:
opencodeGoUsageProvider(packages/ai/src/usage/opencode-go.ts) tracks OMP-observed request costs across three rolling time windows:rolling-5h($12 / 5 hours),weekly($30 / 7 days), andmonthly($60 / 30 days). Costs are aggregated fromctx.listUsageCostsviasumWindowCoststo compute fractional usage, reset timestamps (resetsAt), and limit statuses (ok,warningat >=80%,exhaustedat >=100%).
Catalog model handling
- Authoritative Dynamic Models:
opencodeGoModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts) and descriptor configuration (packages/catalog/src/provider-models/descriptors.ts, default modelkimi-k2.7-code) specifydynamicModelsAuthoritative: true. Successful runtime discovery viafetchOpenAICompatibleModelsfromhttps://opencode.ai/zen/go/v1/modelscompletely replaces bundled provider models instead of merging fallback-only IDs (model-manager.ts).
OpenCode Zen (opencode-zen)
OpenCode Zen (opencode-zen) is a subscription service providing access to multi-vendor AI models (Anthropic Claude, DeepSeek, MiniMax, Gemini, etc.) routed through unified proxy endpoints at https://opencode.ai/zen. Requests are dispatched dynamically across multiple underlying transport APIs—primarily “Anthropic Messages” (/zen), “OpenAI Chat Completions” (/zen/v1), “OpenAI Responses” (/zen/v1), and “Google Generative AI” (/zen/v1)—based on catalog resolution rules, with claude-opus-4-8 designated as its default model.
Special casings
- Multi-API Resolution & Endpoint Wiring:
createOpenCodeApiResolutioninpackages/catalog/src/provider-models/openai-compat.tsresolves model transport targets via@ai-sdk/*npm metadata.OPENCODE_ZEN_API_RESOLUTIONdefines per-id overrides mapping"minimax-m3"and"minimax-m3-free"to"openai-completions"athttps://opencode.ai/zen/v1, overriding upstream@ai-sdk/anthropictags that lead to HTTP 400 errors or raw<invoke>/<|minimax|>/<tool_call>markup leaks (#1617). - Anthropic Proxy Header & Beta Handling: In
packages/ai/src/providers/anthropic.ts,opencode-zendeletes defaultAuthorizationheaders (delete defaultHeaders.Authorization) and suppliesapiKeyto emitX-Api-Keyheaders. Thinking requests onopencode-zensuppress thecontext_management_20251015beta header and body field (context_management) because the Zen Anthropic proxy rejects unrecognized fields with400 Extra inputs are not permitted(#6510). - Thinking Mode Content Replay (
whenThinking): Baseline compat for OpenCode models setsrequiresReasoningContentForToolCalls: falseto prevent sending unrecognized parameters on thinking-disabled requests (#1071). When reasoning is enabled,buildOpenAICompatinpackages/catalog/src/compat/openai.tsconstructs anOPENCODE_WHEN_THINKINGoverlay (requiresReasoningContentForToolCalls: true,allowsSyntheticReasoningContentForToolCalls: false), whichresolveOpenAICompatPolicyinpackages/ai/src/providers/openai-shared.tspointer-swaps in at request time to prevent400 thinking is enabled but reasoning_content is missing in assistant tool call messageerrors (#1484, #2084). - Aliased Reasoning Models (
big-pickle): The model IDbig-pickleis an OpenCode Zen DeepSeek reasoning alias recognized viaisOpenCodeDeepseekAliasinpackages/catalog/src/compat/openai.tsandpackages/catalog/src/model-thinking.ts. It is classified as part ofisDeepseekFamily, enforcing strictreasoning_contentreplay during thinking tool-call turns.
Auth & usage
- API Key Manual Auth: Configured via the
OPENCODE_API_KEYenvironment variable (CATALOG_PROVIDERSdescriptor inpackages/catalog/src/provider-models/descriptors.ts). - Interactive CLI Login Flow:
opencodeZenProvider.login(packages/ai/src/registry/opencode-zen.ts) lazily invokesloginOpenCodeinpackages/ai/src/registry/oauth/opencode.ts. Despite residing underoauth/, it is an API key prompt flow: it openshttps://opencode.ai/authin the browser and prompts the user to paste their API key. - Wire Authentication: Credentials across both Anthropic and OpenAI-compatible protocol endpoints are passed via
X-Api-Keyheaders rather than standard Bearer tokens.
Catalog model handling
- Descriptor & Options: Catalog entry
opencode-zen(packages/catalog/src/provider-models/descriptors.ts) setsdefaultModel: "claude-opus-4-8",dynamicModelsAuthoritative: true, and instantiatesopencodeZenModelManagerOptionsfrompackages/catalog/src/provider-models/openai-compat.ts. - Dynamic Discovery & Base URL Normalization:
opencodeZenModelManagerOptionsinvokesopenCodeModelManagerOptions("opencode-zen", config), fetching dynamic OpenAI-compatible models fromhttps://opencode.ai/zen/v1/models(discoveryBaseUrl). Models are mapped to positivecontextWindow(context_length) andmaxTokens(max_completion_tokens), with base URLs normalized per API type (openCodeBaseUrlForApi/normalizeOpenCodeBasePath). - Zen vs Go Differences:
- Base URL Root: Zen uses base path
https://opencode.ai/zen(completions at/zen/v1), whereas OpenCode Go (opencode-go) targetshttps://opencode.ai/zen/go(completions at/zen/go/v1). - Default Models: Zen defaults to
claude-opus-4-8; Go defaults tokimi-k2.7-code. - API Resolution Overrides: Zen (
OPENCODE_ZEN_API_RESOLUTION) overrides"minimax-m3"and"minimax-m3-free"to"openai-completions". Go (OPENCODE_GO_API_RESOLUTION) overrides"minimax-m2.7","minimax-m3","minimax-m3-free","qwen3.5-plus", and"qwen3.6-plus"to"openai-completions"to prevent gateway 404s or XML markup leaks (#887, #1617). - Model Aliasing: Zen includes the
big-picklealias (DeepSeek reasoning), which is uniquely detected viaisOpenCodeDeepseekAliasfor DeepSeek compat policy application.
- Base URL Root: Zen uses base path
OpenRouter (openrouter)
OpenRouter is a unified multi-provider routing gateway serving hundreds of third-party models over OpenAI-compatible interfaces. Requests execute using the pseudo-API openrouter, dispatching by default to the OpenAI Responses transport or falling back to OpenAI Chat Completions based on environment configuration.
Special casings
- Pseudo-API Dispatch & Dual-Wire Fallback:
streamSimpleinpackages/ai/src/stream.tsevaluatesmodel.api === "openrouter". When$env.PI_OPENROUTER_RESPONSES !== "0"(default), it dispatches tostreamOpenAIResponses(“OpenAI Responses”); when set to"0", it falls back tostreamOpenAICompletions(“OpenAI Chat Completions”). Catalog compat usesResolvedOpenRouterCompat(packages/catalog/src/types.ts), constructed viabuildOpenRouterCompatinpackages/catalog/src/compat/openai.tsby combiningResolvedOpenAICompatandResolvedOpenAIResponsesCompat. - Routing Variant Transformation (
:nitro/:floor): Options specifyingopenrouterVariant("nitro","floor","online","exacto","extended") map throughapplyOpenRouterRoutingVariant(packages/ai/src/providers/openai-shared.ts). The variant suffix (:<variant>) is appended tomodel.idat request time unless a colon already exists after the final slash (lastColon > lastSlash), preserving explicit user or catalog variant overrides. - Provider Order & Exclusion Preferences:
applyOpenAIGatewayRoutinginpackages/ai/src/providers/openai-shared.tsinjects catalogopenRouterRoutingpreferences (OpenRouterRoutinginterface withonly?: string[]andorder?: string[]) into the top-levelproviderrequest parameter whencompat.isOpenRouterHostis true. - Anthropic
cache_controlBreakpoints:isOpenRouterAnthropicModel(packages/ai/src/providers/openai-shared.ts) identifies models matchingprovider === "openrouter"and ID starting withanthropic/. On the Chat Completions wire,applyOpenAIChatCompletionsPromptCachePolicy(openai-completions.ts) attachescache_control: { type: "ephemeral" }to the last non-empty text part of the latest message. On the Responses wire,applyOpenAIResponsesPromptCachePolicy(openai-responses.ts) setsparams.cache_control = cacheRetention === "long" ? { type: "ephemeral", ttl: "1h" } : { type: "ephemeral" }. - Catalog Default Max-Tokens Omission:
resolveOpenAIOutputTokenParaminpackages/ai/src/providers/openai-shared.tsomits default output token limits (max_tokens,max_completion_tokens,max_output_tokens) whenisOpenRouterHostis true andmaxTokensExplicitis false. This prevents OpenRouter from filtering out upstreams whose advertised output ceiling is below catalog maximums when executingprovider.order/onlyfallbacks; explicitly specified callermaxTokensare retained. - Custom Request Headers:
getOpenRouterHeadersinpackages/ai/src/utils/openrouter-headers.tsattachesUser-Agent: omp/<ver>,HTTP-Referer: https://omp.sh/,X-OpenRouter-Title: omp,X-OpenRouter-Categories: cli-agent,X-OpenRouter-Cache: true, andX-OpenRouter-Cache-TTL: 3600to all requests for edge response caching.
Auth & usage
- Auth Key Validation via
/api/v1/auth/key:loginOpenRouterinpackages/ai/src/registry/openrouter.tsconfigures API key validation usingvalidateApiKeyAgainstModelsEndpointtargeted athttps://openrouter.ai/api/v1/auth/key. Public/api/v1/modelsreturns HTTP 200 for unauthenticated requests, so/api/v1/auth/keyis used as the canonical identity check (returning 200 for valid keys, 401 otherwise). Key resolution checksOPENROUTER_API_KEYviagetEnvApiKeyinpackages/ai/src/stream.ts. - Authoritative Reported Cost Reconciling:
applyOpenRouterReportedCostinpackages/ai/src/providers/openai-shared.tsextractsrawUsage.costechoed in API responses. If estimated token cost is finite and positive, input, output, cache-read, and cache-write costs are scaled byreportedCost / estimatedCostto match OpenRouter’s exact billable total; otherwise,usage.cost.inputis assigned the reported cost directly.
Catalog model handling
- Descriptor & Unauthenticated Discovery: Registered as
openrouterinCATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts), withdefaultModel: "openai/gpt-5.5",envVars: ["OPENROUTER_API_KEY"], andcatalogDiscovery: { label: "OpenRouter", allowUnauthenticated: true }. - Dynamic Discovery & Filter:
openrouterModelManagerOptionsinpackages/catalog/src/provider-models/openai-compat.tsquerieshttps://openrouter.ai/api/v1/modelsusingfetchOpenAICompatibleModelswithapi: "openrouter". Cache entries are partitioned underresolveModelCacheProviderId("openrouter"). Discovered models are filtered to entries specifyingsupported_parameters.includes("tools"). - Spec Mapping:
openrouterModelManagerOptionsmapsmodality(text/image), pricing per million tokens (prompt,completion,input_cache_read,input_cache_write),context_length,top_provider.max_completion_tokens, and reasoning effort ladders viamapOpenRouterThinking.
Qianfan (qianfan)
Qianfan (Baidu Cloud) provides access to Baidu’s hosted model family via an OpenAI-compatible v2 API using the OpenAI Chat Completions transport. Entry points include packages/ai/src/registry/qianfan.ts (qianfanProvider, loginQianfan) for provider registration and API key authentication, packages/catalog/src/provider-models/descriptors.ts (CATALOG_PROVIDERS) for catalog registration, and packages/catalog/src/provider-models/openai-compat.ts (qianfanModelManagerOptions) for model manager options.
Special casings
- Nothing beyond the OpenAI Chat Completions pipeline.
Auth & usage
- API Key Authentication & Validation: Authenticates via
QIANFAN_API_KEYor stored credentials using API keys with formatbce-v3/ALTAK-...obtained fromhttps://console.bce.baidu.com/qianfan/ais/console/apiKey. The CLI login flow (loginQianfaninpackages/ai/src/registry/qianfan.ts) validates credentials usingcreateApiKeyLoginby issuing anopenai-completionsrequest tohttps://qianfan.baidubce.com/v2withdeepseek-v3.2. - Usage & Quotas: Standard OpenAI Chat Completions token usage tracking (
input,output,reasoning) and HTTP status code error handling apply.
Catalog model handling
- Provider Descriptor: Configured in
CATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts) withdefaultModel: "deepseek-v3.2",envVars: ["QIANFAN_API_KEY"], and catalog discovery label"Qianfan". - Model Options:
qianfanModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts) constructsopenai-completionsoptions bound tohttps://qianfan.baidubce.com/v2viacreateSimpleOpenAICompletionsOptions. - Bundled Models: Static model specifications in
packages/catalog/src/models.jsondefine Qianfan models (e.g.deepseek-v3.2withreasoning: trueandbaseUrl: "https://qianfan.baidubce.com/v2").
Qwen Portal (qwen-portal)
Qwen Portal provides access to Qwen hosted models via an OpenAI-compatible endpoint at https://portal.qwen.ai/v1. It uses the OpenAI Chat Completions transport for model execution and tool calling.
Special casings
- System message restriction: Host matching (
qwenPortalinpackages/catalog/src/hosts.ts, matchingportal.qwen.ai) setssupportsMultipleSystemMessagesDefault = false(packages/catalog/src/compat/openai.ts). This forces multi-system message blocks to be coalesced into a single block to prevent 500 internal server errors triggered by the default Qwen chat template.
Auth & usage
- Environment variables: Automatically resolves credentials from
QWEN_OAUTH_TOKENorQWEN_PORTAL_API_KEY(packages/catalog/src/provider-models/descriptors.ts:385). - Interactive login:
loginQwenPortal(packages/ai/src/registry/qwen-portal.ts:8) guides users to copy a token or API key fromhttps://chat.qwen.aiand prompts for input viaoptions.onPrompt. - Credential validation: Validates input tokens against
https://portal.qwen.ai/v1usingvalidateOpenAICompatibleApiKeytargeting thecoder-model(packages/ai/src/registry/qwen-portal.ts:35). - Usage tracking: No dedicated usage reporting module exists under
packages/ai/src/usage/.
Catalog model handling
- Descriptor setup:
qwenPortalModelManagerOptionsusescreateSimpleOpenAICompletionsOptions(packages/catalog/src/provider-models/openai-compat.ts:4139) with default context window 128,000 tokens and max output tokens 8,192 (openai-compat.ts:5894). - Catalog configuration: Registered in
descriptors.ts:383with default modelcoder-model, discovery label"Qwen Portal", andoauthProvider: "qwen-portal". - Static model definitions: Exposes pre-defined static models in
packages/catalog/src/models.json:coder-model(Qwen Coder) andvision-model(Qwen Vision, supportingtextandimagemodalities).
Sakana AI (sakana)
Sakana AI provides reasoning models from the Fugu model family hosted via api.sakana.ai.
Requests are routed through the stateful OpenAI Responses transport (api: "openai-responses").
Special casings
- Base URL Normalization & Overrides:
resolveSakanaRequestBaseUrlinpackages/ai/src/providers/openai-shared.tsandnormalizeSakanaBaseUrlinpackages/catalog/src/provider-models/openai-compat.tsresolve base URL overrides fromSAKANA_BASE_URLor fallbackFUGU_BASE_URL. Base URLs are normalized to remove trailing slashes and ensure a/v1path suffix, falling back tohttps://api.sakana.ai/v1.
Auth & usage
- API Key Resolution: Environment variable discovery checks
SAKANA_API_KEYfirst, then falls back toFUGU_API_KEY(configured in descriptorpackages/catalog/src/provider-models/descriptors.ts). - Interactive Login:
loginSakanainpackages/ai/src/registry/sakana.tsconfigures API key login directing users to the Sakana AI console (https://console.sakana.ai/api-keys), validating credentials againsthttps://api.sakana.ai/v1/models.
Catalog model handling
- Static Fugu Seeds:
SAKANA_FUGU_STATIC_MODELSinpackages/catalog/src/provider-models/openai-compat.tsexports bundled seed specs (fugu,fugu-ultra,fugu-ultra-20260615), with default provider modelfugu. - Dynamic Model Manager:
sakanaModelManagerOptionsmarks live/modelsdiscovery as authoritative (dynamicModelsAuthoritative: true) and purges stale cached model rows on seed changes viadropCachedModelIdsOnStaticMismatch. - Two-Tier Effort Config:
isSakanaFuguReasoningModel(packages/catalog/src/model-thinking.ts) andisSakanaFuguModelId(packages/catalog/src/provider-models/openai-compat.ts) match Fugu models (/^fugu(?:$|-)/i), marking them as reasoning models with a two-tier effort scale (HIGH_MAX_REASONING_EFFORTS:[high, max]).
SiliconFlow (siliconflow)
SiliconFlow is a high-performance AI inference platform providing access to open-source models (such as DeepSeek and GLM). It uses the OpenAI Chat Completions transport (https://api.siliconflow.com/v1 for global, https://api.siliconflow.cn/v1 for China region).
Special casings
- Dynamic-Only Catalog: Configured as
dynamicModelsAuthoritative: trueinCATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts). No static catalog models are bundled (catalogDiscoveryis omitted andMODELS_DEV_PROVIDER_DESCRIPTORSexcludes it for generator bundling); models are discovered live via/v1/models. - Non-Chat Model Filtering:
isLikelySiliconFlowChatModelIdinpackages/catalog/src/provider-models/openai-compat.tsusesSILICONFLOW_NON_CHAT_MODEL_TOKENSto filter out non-chat models (embeddings, rerankers, Stable Diffusion, Flux, audio/video generators like Whisper, Wan2, CosyVoice) returned by/v1/models. - Runtime Metadata Hydration & Fallbacks:
loadSiliconFlowModelsDevReferencesqueries models.dev with a 5,000ms timeout (SILICONFLOW_MODELS_DEV_REFERENCE_TIMEOUT_MS). Missing models fall back to canonical bundled specs (resolveModelReference) to infer context window, max tokens, and reasoning capabilities while excluding pricing.
Auth & usage
- API Key Login: Authenticates via API key stored in
SILICONFLOW_API_KEY(orSILICONFLOW_CN_API_KEYforsiliconflow-cn). Interactively registered vialoginSiliconFlow(packages/ai/src/registry/siliconflow.ts) andloginSiliconFlowCn(packages/ai/src/registry/siliconflow-cn.ts). - Endpoint Validation: Credentials are validated during login via a
models-endpointrequest tohttps://api.siliconflow.com/v1/models(https://api.siliconflow.cn/v1/models). - Console URLs: Key creation instructions point to
https://cloud.siliconflow.com/account/ak(https://cloud.siliconflow.cn/account/akfor China region).
Catalog model handling
- Manager Construction:
siliconflowModelManagerOptionsandsiliconflowCnModelManagerOptionsinpackages/catalog/src/provider-models/openai-compat.tsconstruct dynamic OpenAI-compatible model managers viacreateSiliconFlowModelManagerOptions. - Default Models: Default model is
zai-org/GLM-5.1forsiliconflowanddeepseek-ai/DeepSeek-V4-Proforsiliconflow-cn(defined inpackages/catalog/src/provider-models/descriptors.ts). - Dynamic Model Discovery: When an API key is available,
fetchDynamicModelscallsfetchOpenAICompatibleModelsto fetch live models from/v1/models, joining models.dev pricing/limits (mapWithBundledReference) or canonical fallback references.
SiliconFlow (China) (siliconflow-cn)
SiliconFlow (China) is the domestic China deployment of SiliconFlow’s AI model platform, offering OpenAI-compatible LLM inference for open-weight models tailored for regional availability. It uses the OpenAI Chat Completions transport (openai-completions) with base URL https://api.siliconflow.cn/v1.
Special casings
- Endpoint Differences: Uses
https://api.siliconflow.cn/v1for model endpoints insiliconflowCnModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts), distinct from globalsiliconflow(https://api.siliconflow.com/v1). - Non-Chat Model Filtering: Model discovery excludes non-chat model IDs (embedding, reranker, image, TTS, audio, and video models containing tokens such as
bge-,bce-,stable-diffusion,flux,kolors,sensevoice,cosyvoice,fish-speech,wan2, etc.) viaisLikelySiliconFlowChatModelIdinpackages/catalog/src/provider-models/openai-compat.ts. - Bundled Upstream Reference Fallback: Models absent from models.dev recover intrinsic capabilities (
reasoning,input), context window, and max output tokens from bundled upstream model reference definitions (getBundledModelReferenceIndex), while provider-specific pricing is omitted.
Auth & usage
- Environment Variable: Authenticates via
SILICONFLOW_CN_API_KEYconfigured in descriptorenvVars(packages/catalog/src/provider-models/descriptors.ts), separate from globalSILICONFLOW_API_KEY. - API Key Login: Configured via
createApiKeyLogininpackages/ai/src/registry/siliconflow-cn.tswith management console URLhttps://cloud.siliconflow.cn/account/akand validation endpointhttps://api.siliconflow.cn/v1/models. - No Usage Tracking: No dedicated quota or usage resolution module is present under
packages/ai/src/usage/.
Catalog model handling
- Descriptor Configuration: Defined in
packages/catalog/src/provider-models/descriptors.tswithdefaultModel: "deepseek-ai/DeepSeek-V4-Pro"(vszai-org/GLM-5.1forsiliconflow),envVars: ["SILICONFLOW_CN_API_KEY"], anddynamicModelsAuthoritative: true. - Dynamic-Only Model Discovery: Deliberately omitted from
MODELS_DEV_PROVIDER_DESCRIPTORSand static catalog generation (scripts/generate-models.ts), fetching available chat models live fromhttps://api.siliconflow.cn/v1/models. - Runtime Reference Hydration: Live discovered models are cross-referenced with models.dev catalog entries (
SILICONFLOW_MODELS_DEV_DESCRIPTORS) with a 5-second timeout (SILICONFLOW_MODELS_DEV_REFERENCE_TIMEOUT_MS) inloadSiliconFlowModelsDevReferences(packages/catalog/src/provider-models/openai-compat.ts) to hydrate pricing and limit metadata.
Synthetic (synthetic)
Synthetic is an AI platform offering dual API format support for its models, exposing both OpenAI-compatible (https://api.synthetic.new/openai/v1/chat/completions) and Anthropic-compatible (https://api.synthetic.new/anthropic/v1/messages) endpoints. Calls default to the OpenAI Chat Completions transport, but can switch dynamically to the Anthropic Messages transport when configured.
Special casings
-
Dual API Surface: streamSynthetic(packages/ai/src/providers/synthetic.ts) utilizesstreamOpenAIAnthropicShim(packages/ai/src/providers/openai-anthropic-shim.ts) to wrap both OpenAI completions and Anthropic messages endpoints. The API format is selectable via the request’ssyntheticApiFormatoption ("openai""anthropic"), defaulting to"openai". - Eager Module Import:
streamSyntheticandisSyntheticModelare imported eagerly inpackages/ai/src/stream.ts(bypassing lazy builtin registration) to support immediate model provider classification and routing. - Dynamic Reasoning & Features: In
packages/catalog/src/provider-models/openai-compat.ts,syntheticModelManagerOptionsmaps dynamic model entries fromGET /openai/v1/models. It checkssupported_featuresfor"reasoning"and parses wire effort tiers (e.g.reasoning_parameters.efforts) to constructthinkingoptions and set thereasoningflag appropriately.
Auth & usage
- Authentication: Key-based auth using
SYNTHETIC_API_KEY(packages/ai/src/registry/synthetic.ts). Validated viacreateApiKeyLoginagainstGET https://api.synthetic.new/openai/v1/models. - Usage & Quota Polling:
syntheticUsageProvider(packages/ai/src/usage/synthetic.ts) pollsGET https://api.synthetic.new/v2/quotaswith the bearer API key. It reports two distinct limit windows:synthetic:requests:5h: Rolling 5-hour request limit with per-tick regeneration percentage (rollingFiveHourLimit).synthetic:usd:7d: Weekly credit limit in USD (weeklyTokenLimit) with per-tick dollar regeneration rates.
Catalog model handling
- Default model:
hf:zai-org/GLM-5.1(packages/catalog/src/provider-models/descriptors.ts). dynamicModelsAuthoritative: true: Models are fetched dynamically viasyntheticModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts).- Modalities and Vision:
inputmodalities ("text","image") are dynamically resolved frominput_modalities,supports_vision, or fallback reference specs. - Capabilities Filter:
supported_featuresstrictly bounds tool support; if present without"tools", tool calling is disabled for that model.
Together (together)
Together is a cloud inference provider offering access to various open-source and proprietary foundation models via an OpenAI Chat Completions-compatible API.
Special casings
- Strict JSON Schema Mode: Identified as supporting strict schema mode (
detectStrictModeSupportinpackages/catalog/src/compat/openai.ts), enabled fortogetherprovider ID andapi.together.xyzbase URLs. - Multiple System Messages: Recognized as supporting multiple system messages (
supportsMultipleSystemMessagesDefaultinpackages/catalog/src/compat/openai.ts), so system messages are not forced to coalesce at index 0.
Auth & usage
- API Key Auth: Authenticates using the
TOGETHER_API_KEYenvironment variable or API key input duringpi-ai login together. - Validation:
loginTogethervalidates keys viacreateApiKeyLoginusingchat-completionsagainsthttps://api.together.xyz/v1with modelmoonshotai/Kimi-K2.5. - API Base URL:
https://api.together.xyz/v1.
Catalog model handling
- Descriptor & Defaults: Configured in
descriptors.tswith default modelmoonshotai/Kimi-K2.7-CodeandtogetherModelManagerOptionsinopenai-compat.ts. - Catalog Source: Models generated via
models.devdescriptor using keytogetheraimapping to providertogetherathttps://api.together.xyz/v1(packages/catalog/src/provider-models/openai-compat.ts). - Host Matching: Listed in
packages/catalog/src/hosts.tsmatching host URL markersapi.together.xyzand registered inpriority.tsidentity mapping.
Umans AI Coding Plan (umans)
Umans AI Coding Plan is a proxy service for AI coding models, operating via the Anthropic Messages wire format (“Anthropic Messages”) with its default base URL set to https://api.code.umans.ai.
Special casings
- Auth header strategy: Anthropic-compatible Umans requests force
X-Api-Keyheader authentication (loginUmansinpackages/ai/src/registry/umans.ts) instead ofAuthorization: Bearer(buildAnthropicClientOptionsinpackages/ai/src/providers/anthropic.ts). - Tool name escaping: Configured with
compat.escapeBuiltinToolNames: true(packages/catalog/src/compat/anthropic.ts) to prefix client tool names with_on outbound requests and strip them on return, avoiding collision with gateway built-in tool names unless gateway web search is active (packages/ai/src/providers/anthropic.ts). -
Gateway web search: Routes web search requests by inspecting X-Umans-Websearch-Providercaller headers or theUMANS_WEBSEARCH_PROVIDER(nativeexa) environment variable (packages/ai/src/providers/anthropic.ts). When enabled,web_searchtool names pass through unescaped. - Thinking / reasoning effort: Supports thinking configurations with levels mapped via
UMANS_REASONING_EFFORT_BY_LEVEL(packages/catalog/src/provider-models/openai-compat.ts). GLM-5.2 on Umans uses a two-tier high/max effort scale wheremaxmaps to theanthropic-budget-effortmode (xhigheffort) (packages/catalog/src/model-thinking.ts).
Auth & usage
- Auth: Uses
UMANS_AI_CODING_PLAN_API_KEYenvironment variable or/login umanskey prompt (packages/ai/src/registry/umans.ts,packages/ai/src/registry/registry.ts). Key validation executes a lightweight Anthropic messages call (max_tokens: 1) tohttps://api.code.umans.ai/v1/messages. - Usage endpoint: Fetches quota and rate limit status from
GET /v1/usage(packages/ai/src/usage/umans.ts) usingAuthorization: Bearer <key>. - Limits surfaced: Returns a rolling 5-hour request limit (
umans:requests) and an instantaneous session concurrency limit (umans:concurrency). Also surfaces low-priority status notes when rate-limit bursts occur.
Catalog model handling
- Descriptor & discovery: Registered as
umanswith default modelumans-coder(packages/catalog/src/provider-models/descriptors.ts). Dynamic discovery fetches model details fromGET /v1/models/info(packages/catalog/src/provider-models/openai-compat.ts). - Vision capability filtering:
umansSupportsVisionstrictly checks forsupports_vision === true. Sentinel string values (such as"via-handoff"forumans-glm-5.1andumans-glm-5.2) are mapped to text-only (["text"]) so image content is handled via client-side vision handoff rather than sending raw image blocks that cause HTTP 400 errors (packages/catalog/src/provider-models/openai-compat.ts). - Pricing & fallback: Generates catalog entries with pricing fallback rules for pay-as-you-go and technical alias models like
umans-qwen3.6-35b-a3bmapping toumans-flash(packages/catalog/scripts/generate-models.ts).
Venice (venice)
Venice is a privacy-focused AI platform delivering uncensored and open-source models. It operates over the OpenAI Chat Completions transport (api: "openai-completions") with default base URL https://api.venice.ai/api/v1.
Special casings
- Nothing beyond the OpenAI Chat Completions pipeline.
Auth & usage
- API Key Login & Validation:
loginVeniceinpackages/ai/src/registry/venice.tsusescreateApiKeyLogin(packages/ai/src/registry/api-key-login.ts) to direct users tohttps://venice.ai/settings/apifor API keys (vapi_...placeholder prefix) and validates credentials via a lightweightchat-completionsrequest using validation modelqwen3-4b. Registered asveniceProviderinpackages/ai/src/registry/registry.ts. - Environment Variables & Credentials: Resolves API keys from the
VENICE_API_KEYenvironment variable configured inCATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts). - Usage Accounting: Uses standard OpenAI Chat Completions usage accounting (
calculateOpenAIUsageAccountinginpackages/ai/src/providers/openai-shared.ts) without custom quota or usage endpoints.
Catalog model handling
- Provider Descriptor: Registered in
CATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts) with default modelllama-3.3-70b,envVars: ["VENICE_API_KEY"], and catalog discovery configured withallowUnauthenticated: true. - Model Manager Options:
veniceModelManagerOptionsinpackages/catalog/src/provider-models/openai-compat.tsconfigures model management usingcreateOpenAICompatibleModelManagerOptionsoverhttps://api.venice.ai/api/v1. - Streaming Usage Compat: In
veniceModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts), mapped models explicitly disable streaming usage payloads by settingcompat: { ...model.compat, supportsUsageInStreaming: false }. - Kimi K2.7 Code Max Tokens Capping:
clampKimiK27CodeMaxTokensinpackages/catalog/src/provider-models/openai-compat.ts(andapplyKimiMaxTokensCapinpackages/catalog/scripts/generate-models.ts) caps output tokens (maxTokens) for Kimi K2.7 Code models (isKimiK27CodeModelId) toKIMI_K27_CODE_RECOMMENDED_MAX_TOKENS. - Catalog Transformation:
openAiCompletionsDescriptorfor Venice inpackages/catalog/src/provider-models/openai-compat.tsappliesclampKimiK27CodeMaxTokensduring model catalog build and discovery transformations.
Vercel AI Gateway (vercel-ai-gateway)
Vercel AI Gateway routes LLM requests through a unified proxy (https://ai-gateway.vercel.sh) to underlying upstream providers (such as Anthropic, OpenAI, or Bedrock). It operates across the Anthropic Messages (anthropic-messages), OpenAI Chat Completions (openai-completions), and OpenAI Responses (openai-responses) transport protocols depending on model configuration.
Special casings
- Host Detection:
isVercelGatewayHostis evaluated viamodelMatchesHost({ provider, baseUrl }, "vercelAIGateway")(packages/catalog/src/compat/openai.ts,packages/catalog/src/hosts.ts), matching `provider === “vercel-ai-gateway”
vLLM (Local OpenAI-compatible) (vllm)
vLLM is an open-source high-throughput LLM serving engine running local or self-hosted OpenAI-compatible inference servers. It uses the OpenAI Chat Completions transport over HTTP/SSE. Entry modules include packages/ai/src/registry/vllm.ts for authentication and credential handling, and packages/catalog/src/provider-models/openai-compat.ts (vllmModelManagerOptions) for catalog options and dynamic model discovery.
Special casings
- Reasoning Content Replay (
replayReasoningContent): Registered inLOCAL_OPENAI_COMPAT_PROVIDERS(packages/catalog/src/compat/openai.ts). Because local inference backends rely on prefix KV-cache reuse,isLocalOpenAICompatBackendauto-enablesreplayReasoningContent: true. When assistant history contains reasoning content (<think>blocks), it is replayed inreasoning_contenton subsequent requests to maintain exact prompt token alignments. - Qwen Thinking Preservation (
qwenPreserveThinking): Auto-enabled (packages/catalog/src/compat/openai.ts) whenthinkingFormatis"qwen"or"qwen-chat-template"andisLocalOpenAICompatBackendis true. SetsqwenPreserveThinking: trueon the compat object, emittingpreserve_thinking: truein request bodies (both top-level and inchat_template_kwargs) so Qwen 3.6+ chat templates retain<think>blocks across multi-turn histories. - Stream Idle Timeout Floor: As a local serving backend (
isLocalServingBackendinpackages/catalog/src/compat/openai.ts), vLLM automatically applies an expanded stream idle timeout floor (streamIdleTimeoutMs: 300_000/ 5 minutes) rather than the default 100 seconds to accommodate heavy model prefill delays on local GPUs or CPUs. - Dynamic-Only Catalog Exclusion: Included in
DISCOVERY_ONLY_PROVIDERS(scripts/generate-models.ts) andLOCAL_ONLY_PROVIDERS(test/models-json-no-local-endpoints.test.ts). Local vLLM models are excluded from static catalog generation so machine-specific endpoints are never committed tomodels.json.
Auth & usage
- Credential Resolution & Defaults: Managed via
loginVllm(createApiKeyLogininpackages/ai/src/registry/vllm.ts). Reads optional API keys from theVLLM_API_KEYenvironment variable or credentials stored viamusepi auth-broker login vllm. - Unauthenticated Local Mode: Defaults to base URL
http://127.0.0.1:8000/v1and placeholder token"vllm-local"(DEFAULT_LOCAL_TOKEN) when no key is supplied (emptyKeyFallback: "vllm-local"). Descriptor settings specifycatalogDiscovery: { label: "vLLM", allowUnauthenticated: true }. - Documentation & Endpoint Setup: The login helper points to
https://docs.vllm.ai/en/latest/serving/openai_compatible_server.htmlfor configuring local vLLM OpenAI-compatible server endpoints.
Catalog model handling
- Descriptor Configuration: Registered in
packages/catalog/src/provider-models/descriptors.tswithid: "vllm",defaultModel: "gpt-oss-20b",envVars: ["VLLM_API_KEY"],allowUnauthenticated: true, and manager options generated byvllmModelManagerOptions. - Dynamic Model Discovery:
vllmModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts) invokesfetchOpenAICompatibleModelswithapi: "openai-completions",provider: "vllm", base URLconfig?.baseUrl ?? getDefaultModelDiscoveryBaseUrl("vllm")!(http://127.0.0.1:8000/v1), and a 10-second timeout (VLLM_DISCOVERY_TIMEOUT_MS = 10_000). - Context Window Extraction: Custom
mapModelinvllmModelManagerOptionsextractscontextWindowfrom vLLM’s non-standard/v1/modelsresponse fieldentry.max_model_lenusingtoPositiveNumber(entry.max_model_len, model.contextWindow). - Cache Provider ID: Resolved by
resolveModelCacheProviderId("vllm", { baseUrl })inpackages/catalog/src/provider-models/cache-provider-id.ts(usinggetDefaultModelDiscoveryBaseUrl("vllm")), generating base-URL-hashed cache keys formatted asvllm:${Bun.hash(baseUrl).toString(36)}.
Wafer Serverless (wafer-serverless)
Wafer Serverless is a pay-as-you-go provider proxying multiple upstream models (such as Zhipu GLM, Moonshot Kimi, Alibaba Qwen, and DeepSeek) through an OpenAI-compatible API at https://pass.wafer.ai/v1. It relies on the OpenAI Chat Completions transport (openai-completions).
Special casings
- Upstream thinking parameter selection is configured dynamically via
resolveWaferServerlessThinkingFormat(packages/catalog/src/provider-models/openai-compat.ts:2137) based on thewafer.providerenvelope hint:- Upstreams matching
zai,zhipu,moonshot, orkimisetthinkingFormat: "zai". - Upstreams matching
qwen,alibaba, ordashscopesetthinkingFormat: "qwen". - Fallback without envelope hints uses
isReasoningGlmModelIdorisKimiModelIdfor"zai"(packages/catalog/src/provider-models/openai-compat.ts:2150). - Static policies in
generated-policies.tsapplythinkingFormat: "zai"for bundled GLM/Kimi models (packages/catalog/scripts/generated-policies.ts:364).
- Upstreams matching
- All reasoning entries configure
reasoningContentField: "reasoning_content"and setsupportsDeveloperRole: false(packages/catalog/src/provider-models/openai-compat.ts:2244). wafer-passhas been retired in favor ofwafer-serverless(packages/catalog/scripts/generate-models.ts:79).
Auth & usage
- Authenticates using Bearer API keys (
wfr_…prefix) supplied via theWAFER_SERVERLESS_API_KEYenvironment variable (packages/catalog/src/provider-models/descriptors.ts:465). - Interactive login is handled by
loginWaferServerlessusingcreateApiKeyLogin(packages/ai/src/registry/oauth/wafer.ts:14), pointing users tohttps://app.wafer.ai/usage. - Key validation probes
https://pass.wafer.ai/v1/models(packages/ai/src/registry/oauth/wafer.ts:11).
Catalog model handling
- Registered in provider descriptors with
defaultModel: "GLM-5.1"and base URLhttps://pass.wafer.ai/v1(packages/catalog/src/provider-models/descriptors.ts:463). - Dynamic catalog generation uses
waferServerlessModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts:2252) and parses the/v1/modelsresponse viareadWaferRecord(packages/catalog/src/provider-models/openai-compat.ts:2151). - Map model capabilities from
wafer.capabilities:visionenables["text", "image"]input,reasoningenables reasoning mode, andtoolssetssupportsTools(packages/catalog/src/provider-models/openai-compat.ts:2193). - Context window reads
wafer.context_length(falling back tomax_model_len), andmaxTokensis capped at65536(WAFER_MAX_TOKENS_CAP,packages/catalog/src/provider-models/openai-compat.ts:2201). - Pricing converts internal wholesale units from
wafer.pricingto USD/M tokens usingcents * 125 / 10000(cents * 0.0125) (packages/catalog/src/provider-models/openai-compat.ts:2203). - Model IDs are preserved verbatim on the wire without case transformation (
packages/catalog/src/provider-models/openai-compat.ts:2210).
xAI API (xai)
xAI API (xai) provides access to xAI’s Grok model suite using standard API key authentication. It routes inference requests through the OpenAI Chat Completions transport (https://api.x.ai/v1), distinct from xai-oauth which uses OAuth bearer tokens and the OpenAI Responses transport.
Special casings
- Grok Host Compatibility: Host detection (
packages/catalog/src/hosts.tssymbolhosts.xai) matches provider"xai"andapi.x.aiURLs to evaluateisGrokin the Chat Completions compatibility layer (packages/catalog/src/compat/openai.tssymbolresolveOpenAICompatForHost). - Prompt Cache Header: Configures
promptCacheSessionHeader: "x-grok-conv-id"whenisGrokis true (packages/catalog/src/compat/openai.tssymbolresolveOpenAICompatForHost), enabling conversation ID header attachment for prompt cache retention. - Reasoning Effort Disabled: Explicitly sets
supportsReasoningEffort: falsevia!isGrokcheck in Chat Completions compatibility (packages/catalog/src/compat/openai.tssymbolresolveOpenAICompatForHost), contrasting withxai-oauth’s selective reasoning-effort support. - Provider Priority Ranking: Positioned in provider priority (
packages/catalog/src/identity/priority.tssymbolPROVIDER_PRIORITY) belowxai-oauth("xai-oauth">"xai">"mistral").
Auth & usage
- Authentication: Key-based auth implemented via
createApiKeyLogininpackages/ai/src/registry/xai.ts(symbolsloginXAI,xaiProvider). Directs users to"https://console.x.ai/team/default/api-keys"with prompt"Paste your xAI API key"(placeholder"xai-..."). - Validation: Performs credentials check via
models-endpointagainst"https://api.x.ai/v1/models"(packages/ai/src/registry/xai.tssymbolloginXAI). - Environment Fallback: Configured to resolve
XAI_API_KEY(packages/catalog/src/provider-models/descriptors.tssymboldescriptors). - Usage Tracking: Nothing beyond the
OpenAI Chat Completionspipeline.
Catalog model handling
- Descriptor Config: Provider descriptor (
packages/catalog/src/provider-models/descriptors.tssymboldescriptors) specifies default modelgrok-4-fast-non-reasoningand delegates toxaiModelManagerOptions. - Manager Options: Constructed via
createSimpleOpenAICompletionsOptions("xai", "https://api.x.ai/v1", config)(packages/catalog/src/provider-models/openai-compat.tssymbolxaiModelManagerOptions). - Completions Descriptor: Registered with
openAiCompletionsDescriptor("xai", "xai", "https://api.x.ai/v1")(packages/catalog/src/provider-models/openai-compat.tssymbolopenAiCompletionsDescriptor), serving Grok models over theopenai-completionsAPI.
xAI Grok OAuth (SuperGrok) (xai-oauth)
xAI Grok OAuth provides subscription-backed access (SuperGrok / X Premium+) to xAI Grok models over the OpenAI Responses transport (api: "openai-responses", baseUrl: "https://api.x.ai/v1"). Authentication uses RFC 8628 device code flow against https://auth.x.ai, while usage tracking probes the dedicated SuperGrok CLI billing proxy.
Special casings
- Encrypted Reasoning & History Replay:
includeEncryptedReasoningisfalse(packages/catalog/src/compat/openai.tsbuildOpenAIResponsesCompat) to suppress encrypted reasoning item replay.filterReasoningHistoryistrue(packages/catalog/src/compat/openai.ts,packages/ai/src/providers/openai-responses.ts) to filter native reasoning items and thinking signatures out of replayed Responses history. - Image Detail Clamping:
supportsImageDetailOriginalisfalse(packages/catalog/src/compat/openai.tsbuildOpenAIResponsesCompat), clamping image detail from"original"to"auto"because xAI endpoints return HTTP 400/422 on"original". - Reasoning Effort Gating & Summary:
supportsReasoningEffortisfalseunless the model is on theisGrokReasoningEffortCapableallowlist (packages/catalog/src/identity/family.ts, e.g.grok-3-mini,grok-4.20-multi-agent,grok-4.3,grok-4.5). Non-capable models (grok-build,grok-build-0.1,grok-4.20-0309-reasoning,grok-composer-2.5-fast) setomitReasoningEffort: trueto prevent HTTP 400 onapi.x.ai.reasoningSummaryis set tonull(orundefinedwhen disabled) inpackages/ai/src/providers/openai-responses.tsto omit unsupportedreasoning.summarywire fields. - Reasoning Effort Map & Caching: Maps
minimalto"low"(packages/catalog/src/provider-models/openai-compat.tsXAI_REASONING_EFFORT_MAP). SendsX-Grok-Conv-Idfor session prompt-cache retention (promptCacheSessionHeader).
Auth & usage
- OAuth Authentication:
xaiOauthProvider(packages/ai/src/registry/xai-oauth.ts) delegates tologinXAIOAuthandrefreshXAIOAuthToken(packages/ai/src/registry/oauth/xai-oauth.ts). Executes RFC 8628 device authorization againsthttps://auth.x.ai(client IDb1a00492-073a-47ea-816f-4c329264a828, scopeopenid profile email offline_access grok-cli:access api:access).xaiOAuthDiscoveryfetches OIDC configuration and validates endpoints (validateXAIEndpointpins to HTTPS*.x.ai). Fetches user identity fromhttps://auth.x.ai/oauth2/userinfo(fetchXAIOAuthIdentity). Env fallbacks:XAI_OAUTH_TOKENthenXAI_API_KEY(descriptors.ts). - Usage Tracking:
xaiOauthUsageProvider(packages/ai/src/usage/xai-oauth.ts) querieshttps://cli-chat-proxy.grok.com/v1/billing(validateXAIBillingEndpointpins to HTTPS*.grok.com) with headerX-XAI-Token-Auth: xai-grok-cli(getXAICliBillingHeaders). Only accepts valid OAuth bearer credentials. Probes legacy weekly credits (?format=credits,parseWeeklyBillingConfigforcreditUsagePercentandproductUsage) and unified monthly quota (parseMonthlyBillingConfigformonthlyLimitandused), plus positiveonDemandCap/onDemandUsedlimits.
Catalog model handling
- Curated Models & Static Seed:
XAI_OAUTH_CURATED_MODELS(packages/catalog/src/provider-models/openai-compat.ts) defines static models (grok-build,grok-build-0.1,grok-4.3,grok-4.5,grok-4.20-multi-agent-0309,grok-4.20-0309-reasoning,grok-4.20-0309-non-reasoning,grok-composer-2.5-fast) with zero cost (cost: 0). Default model isgrok-4.3(descriptors.ts).buildXaiOAuthStaticSeedseedsModelRegistrysynchronously at boot somodelRoles.default = "xai-oauth/<id>"works before dynamic refresh. - Dynamic Curation Overlay:
applyXAIOAuthCuration(openai-compat.ts,xaiOAuthModelManagerOptions) filters non-chat prefixes (grok-imagine-,grok-stt-,grok-voice-), overlays curated context windows (up to 2M), setsmaxTokensequal tocontextWindow, preserves image capabilities and reasoning flags, and injects missing curated models. - Reference Resolution Exclusion:
isZeroCostXaiOAuthCandidate(packages/catalog/src/identity/reference.ts) excludes zero-cost subscription entries from reference index matching so subscription pricing and limits do not override public/paid Grok references.
Xiaomi MiMo (xiaomi)
Xiaomi MiMo delivers Xiaomi’s proprietary MiMo model family (such as mimo-v2.5 and mimo-v2.5-pro) over OpenAI-compatible endpoints. Requests execute over the OpenAI Chat Completions transport using standard pay-as-you-go base URLs (https://api.xiaomimimo.com/v1) or regional Token Plan base URLs (https://token-plan-{sgp,ams,cn}.xiaomimimo.com/v1).
Special casings
- MiMo Compat Classification: Matched via
isXiaomiHost(modelMatchesHost(hostModel, "xiaomi")) andisMimoModelIdOrName(packages/catalog/src/identity/family.ts) inpackages/catalog/src/compat/openai.ts. - Reasoning Content Invariants:
requiresReasoningContentForToolCalls: true(packages/catalog/src/compat/openai.ts): MiMo models require exactreasoning_contentreplay on thinking-mode tool-call continuations across standard and Token Plan hosts.requiresReasoningContentForAllAssistantTurns: true(packages/catalog/src/compat/openai.ts): Enforcesreasoning_contentpresence on all prior assistant turns during reasoning mode (except when routed via OpenRouter).allowsSyntheticReasoningContentForToolCalls: false(packages/catalog/src/compat/openai.ts): Rejects syntheticreasoning_contentplaceholders (e.g.".") on tool-call turns.
- Thinking Format & Effort Mapping:
thinkingFormat: "zai"(packages/catalog/src/compat/openai.ts): Formats thinking mode payloads using the z.ai binarythinkingstructure.supportsReasoningEffort: false(packages/catalog/src/compat/openai.ts): Suppresses standardreasoning_effortparameters.
- Non-Standard Host Protocol Flags:
isXiaomiHostis categorized underisNonStandard(packages/catalog/src/compat/openai.ts), settingsupportsStore: falseand defaultingsupportsDeveloperRole: false.
Stream behavior
- Widen Idle Watchdog Timeout:
streamIdleTimeoutMsis widened to 300,000 ms (5 minutes) viaXIAOMI_MIMO_STREAM_IDLE_TIMEOUT_MSinpackages/catalog/src/compat/openai.tsbecause MiMo Pro onapi.xiaomimimo.comcan stall ~2 minutes before emitting its first SSE event (issue #1770).
Auth & usage
- Registry & Provider Definitions: Primary provider is defined in
packages/ai/src/registry/xiaomi.ts(xiaomiProvider); regional Token Plan providers are exported inpackages/ai/src/registry/xiaomi-token-plan-{ams,cn,sgp}.ts(xiaomiTokenPlanAmsProvider,xiaomiTokenPlanCnProvider,xiaomiTokenPlanSgpProvider). - Interactive Key Prompts & Validation:
loginXiaomiandloginXiaomiTokenPlan(packages/ai/src/registry/oauth/xiaomi.ts) prompt for standard (sk-...) or Token Plan (tp-...) API keys and validate them viavalidateXiaomiApiKey. - Token Plan Validation Fallback: Standard
xiaomilogin withtp-keys falls back sequentially through SGP (https://token-plan-sgp.xiaomimimo.com/v1) → AMS (https://token-plan-ams.xiaomimimo.com/v1) → CN (https://token-plan-cn.xiaomimimo.com/v1), using fresh per-endpointAbortSignal.timeout(15_000)signals so regional timeouts do not abort subsequent fallback endpoints. Regionalxiaomi-token-plan-*logins validate against their specific cluster. - Environment Variables:
XIAOMI_API_KEYfor standardxiaomi, andXIAOMI_TOKEN_PLAN_AMS_API_KEY,XIAOMI_TOKEN_PLAN_CN_API_KEY,XIAOMI_TOKEN_PLAN_SGP_API_KEYfor regional Token Plan providers (packages/catalog/src/provider-models/descriptors.ts).
Catalog model handling
- Provider Descriptors: Catalog descriptors in
packages/catalog/src/provider-models/descriptors.tsconfigurexiaomi,xiaomi-token-plan-ams,xiaomi-token-plan-cn, andxiaomi-token-plan-sgpwithdefaultModel: "mimo-v2.5". - Dynamic Model Discovery:
xiaomiModelManagerOptionsinpackages/catalog/src/provider-models/openai-compat.tsinspects keys (tp-vssk-) and provider IDs to query standard or regional/modelsendpoints (XIAOMI_TOKEN_PLAN_BASE_URLS), preserving regional provider IDs on returned models. - Audio Model Filtering: Speech and audio models are excluded from discovery and catalog generation (
!model.id.includes("-tts") && !model.id.includes("-asr")) inxiaomiModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts) andscripts/generate-models.ts. - Host Matching:
modelMatchesHost(packages/catalog/src/hosts.ts) matchesxiaomiprovider IDs,xiaomi-token-plan-provider prefixes, andxiaomimimo.comURL markers to thexiaomihost class.
Xiaomi Token Plan (Europe) (xiaomi-token-plan-ams)
Xiaomi Token Plan (Europe) (xiaomi-token-plan-ams) provides regional access to Xiaomi’s MiMo model family (such as mimo-v2.5 and mimo-v2-omni) via Xiaomi’s European Token Plan gateway (https://token-plan-ams.xiaomimimo.com/v1). It uses the OpenAI Chat Completions transport (api: "openai-completions"). This regional provider allows CLI login (musepi login) and dynamic model lookup to store and validate tp- API keys against the European cluster without falling back across regions.
Special casings
- Host Matching & Extended Idle Timeout: Matched under host class
xiaomiviaproviderPrefixes: ["xiaomi-token-plan-"]inpackages/catalog/src/hosts.ts. Inpackages/catalog/src/compat/openai.ts,isXiaomiHostmatches, enablingisXiaomiMimowhich configuresXIAOMI_MIMO_STREAM_IDLE_TIMEOUT_MS = 300_000(5-minute stream idle watchdog) to accommodate initial response stalls on MiMo models. - TTS/ASR Model Filter: Dynamic model manager options (
xiaomiModelManagerOptionsinpackages/catalog/src/provider-models/openai-compat.ts) and model generation scripts (scripts/generate-models.ts) filter out audio models (!model.id.includes("-tts") && !model.id.includes("-asr")). - Provider ID Retention:
xiaomiModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts) explicitly setsproviderId: "xiaomi-token-plan-ams"and maps dynamic discovery entries back toprovider: "xiaomi-token-plan-ams"rather than collapsing them to genericxiaomi.
Auth & usage
- Registry Provider & OAuth Lazy Loader:
xiaomiTokenPlanAmsProviderinpackages/ai/src/registry/xiaomi-token-plan-ams.tsregisters ID"xiaomi-token-plan-ams"and lazy-loadsloginXiaomiTokenPlanfrompackages/ai/src/registry/oauth/xiaomi.ts. - Region Console Instructions: Interactive CLI login (
loginXiaomiTokenPlan(cb, "ams")) prompts users for atp-prefix API key and directs them to the Token Plan console URL (https://platform.xiaomimimo.com/console/plan-manage). - Single-Cluster Validation:
validateXiaomiApiKeyinpackages/ai/src/registry/oauth/xiaomi.tsvalidates keys directly againsthttps://token-plan-ams.xiaomimimo.com/v1/chat/completions(usingmimo-v2.5,max_tokens: 1), bypassing the multi-region fallback sequence used by genericloginXiaomi. - Headers & Errors: Requests pass standard
Authorization: Bearer tp-...headers. Authentication or network failures throwAIError.OAuthErrororAIError.ApiKeyRequiredError.
Catalog model handling
- Provider Descriptors: Registered in
CATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts) withid: "xiaomi-token-plan-ams",defaultModel: "mimo-v2.5", and manager factoryxiaomiModelManagerOptions({ ...config, providerId: "xiaomi-token-plan-ams", tokenPlanRegion: "ams" }). - OpenAI-Compat Descriptor: Configured via
openAiCompletionsDescriptor("xiaomi-token-plan-ams", "xiaomi-token-plan-ams", "https://token-plan-ams.xiaomimimo.com/v1")inpackages/catalog/src/provider-models/openai-compat.ts. - Dynamic Model Manager:
xiaomiModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts) mapstokenPlanRegion: "ams"to base URLhttps://token-plan-ams.xiaomimimo.com/v1forfetchDynamicModels, utilizingcreateBundledReferenceMap("xiaomi")for baseline specs. - Pre-packaged Catalog Models: Bundled models (e.g.
mimo-v2-omni,mimo-v2.5) are registered inpackages/catalog/src/models.jsonunder key"xiaomi-token-plan-ams", settingbaseUrl: "https://token-plan-ams.xiaomimimo.com/v1"withapi: "openai-completions".
Xiaomi Token Plan (China) (xiaomi-token-plan-cn)
Xiaomi Token Plan (China) is the regional China endpoint for Xiaomi MiMo’s Token Plan subscription service (https://token-plan-cn.xiaomimimo.com/v1). It provides access to MiMo AI models using regional tp-... API keys. It uses the “OpenAI Chat Completions” transport.
Special casings
- Host classification:
KNOWN_HOSTS.xiaomiinpackages/catalog/src/hosts.tsmatchesxiaomi-token-plan-cnviaproviderPrefixes: ["xiaomi-token-plan-"]andurlMarkers: ["xiaomimimo.com"], enabling host-level compatibility flags across all Token Plan endpoints. - Reasoning content replay:
packages/catalog/src/compat/openai.tsmarks MiMo models on Xiaomi hosts withrequiresReasoningContentForToolCalls: trueandrequiresReasoningContentForAllAssistantTurns: true, requiring prior assistant tool-call turns to preserve exactreasoning_content. - Synthetic reasoning rejection:
allowsSyntheticReasoningContentForToolCallsinpackages/catalog/src/compat/openai.tsevaluates tofalsefor MiMo models, rejecting synthetic.placeholders on tool-call continuations. - Extended stream idle timeout:
XIAOMI_MIMO_STREAM_IDLE_TIMEOUT_MS(300,000 ms / 5 minutes) inpackages/catalog/src/compat/openai.tsoverrides default first-event/idle timeouts to accommodate pre-generation reasoning stalls. - Audio SKU filtering:
packages/catalog/scripts/generate-models.tsfilters out speech-synthesis and recognition SKUs containing-ttsor-asrforxiaomi-token-plan-providers.
Auth & usage
- Environment variable & login: Authenticates via
XIAOMI_TOKEN_PLAN_CN_API_KEY.xiaomiTokenPlanCnProvider.logininpackages/ai/src/registry/xiaomi-token-plan-cn.tsinvokesloginXiaomiTokenPlan(options, "cn")inpackages/ai/src/registry/oauth/xiaomi.ts. - Regional API key validation: Prompts for a
tp-...key fromhttps://platform.xiaomimimo.com/console/plan-manageand validates it viavalidateXiaomiApiKeyby sending aPOST /v1/chat/completionsrequest formimo-v2.5strictly againsthttps://token-plan-cn.xiaomimimo.com/v1with a 15-second timeout (VALIDATION_TIMEOUT_MS). - Usage accounting: Standard OpenAI Chat Completions usage accounting applies (
calculateOpenAIUsageAccounting); no provider-specific usage or quota module exists.
Catalog model handling
- Provider descriptor: Configured in
packages/catalog/src/provider-models/descriptors.tswithid: "xiaomi-token-plan-cn",defaultModel: "mimo-v2.5",envVars: ["XIAOMI_TOKEN_PLAN_CN_API_KEY"], andcreateModelManagerOptionsdelegating toxiaomiModelManagerOptionswithtokenPlanRegion: "cn". - OpenAI compat entry: Registered via
openAiCompletionsDescriptorinpackages/catalog/src/provider-models/openai-compat.tswith base URLhttps://token-plan-cn.xiaomimimo.com/v1. - Regional discovery & model manager:
xiaomiModelManagerOptionsinpackages/catalog/src/provider-models/openai-compat.tspins discovery toXIAOMI_TOKEN_PLAN_BASE_URLS.cn(https://token-plan-cn.xiaomimimo.com/v1). Dynamic model discovery preservesproviderId: "xiaomi-token-plan-cn", filters-ttsand-asrmodels, and merges metadata from bundledxiaomireference specs usingcreateBundledReferenceMap("xiaomi").
Xiaomi Token Plan (Singapore) (xiaomi-token-plan-sgp)
The Xiaomi Token Plan (Singapore) provider (xiaomi-token-plan-sgp) routes requests to Xiaomi’s Singapore Token Plan cluster using the OpenAI Chat Completions transport (openai-completions). It provides dedicated access to Xiaomi MiMo models (mimo-v2.5, mimo-v2-omni) using region-bound tp-... API keys targeted at https://token-plan-sgp.xiaomimimo.com/v1. This regional entry allows login and model storage isolated from standard Xiaomi MiMo (xiaomi) and other regional token plan endpoints (xiaomi-token-plan-ams, xiaomi-token-plan-cn).
Special casings
- Regional Base URL Binding:
xiaomiModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts) explicitly setsbaseUrltohttps://token-plan-sgp.xiaomimimo.com/v1(XIAOMI_TOKEN_PLAN_BASE_URLS.sgp) when configured withtokenPlanRegion: "sgp", preventing token-plan keys from reverting to the standard Xiaomi endpointhttps://api.xiaomimimo.com/v1(XIAOMI_STANDARD_BASE_URL). - Audio/Speech Model Exclusion:
fetchOpenAICompatibleModels(packages/catalog/src/provider-models/openai-compat.ts) and model generator filtering inscripts/generate-models.ts(isXiaomiProvider) filter out non-chat models containing-ttsor-asrfrom dynamic catalog discovery and generation. - Extended Stream Idle Timeout:
modelMatchesHost(packages/catalog/src/hosts.ts) matchesxiaomi-token-plan-viaproviderPrefixes, inheritingXIAOMI_MIMO_STREAM_IDLE_TIMEOUT_MS(300,000ms / 5 minutes) inpackages/catalog/src/compat/openai.tsto prevent premature timeouts during long initial response delays on MiMo models.
Auth & usage
- Pinned Regional Validation:
loginXiaomiTokenPlan(packages/ai/src/registry/oauth/xiaomi.ts) validates keys strictly against the Singapore endpointhttps://token-plan-sgp.xiaomimimo.com/v1(TOKEN_PLAN_VALIDATION_ENDPOINTS.sgp) usingvalidateXiaomiApiKey(packages/ai/src/registry/oauth/xiaomi.ts). Unlike genericloginXiaomi(which performs SGP -> AMS -> CN fallback fortp-keys),xiaomi-token-plan-sgpdisables cross-region fallback during auth validation. - Plan Management Auth URL:
loginXiaomiTokenPlan(packages/ai/src/registry/oauth/xiaomi.ts) invoked byxiaomiTokenPlanSgpProvider(packages/ai/src/registry/xiaomi-token-plan-sgp.ts) prompts users with instructions pointing tohttps://platform.xiaomimimo.com/console/plan-manage(TOKEN_PLAN_AUTH_URL) for acquiring regionaltp-keys (TOKEN_PLAN_KEY_PREFIX), contrasting withSTANDARD_AUTH_URL(https://platform.xiaomimimo.com/#/console/api-keys). - Validation Handshake:
validateXiaomiApiKey(packages/ai/src/registry/oauth/xiaomi.ts) tests credentials viaPOST /chat/completionsusing modelmimo-v2.5(TOKEN_PLAN_VALIDATION_MODEL),max_tokens: 1, andmessages: [{ role: "user", content: "ping" }], enforcing a 15-second timeout (VALIDATION_TIMEOUT_MS = 15_000). - Usage Accounting: Token consumption and cache metrics are calculated using standard OpenAI Chat Completions accounting via
calculateOpenAIUsageAccounting(packages/ai/src/providers/openai-shared.ts).
Catalog model handling
- Provider Descriptor: Registered in
CATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.ts) withid: "xiaomi-token-plan-sgp",defaultModel: "mimo-v2.5", andcreateModelManagerOptionssupplyingtokenPlanRegion: "sgp"andproviderId: "xiaomi-token-plan-sgp". Static model metadata is declared inopenAiCompletionsDescriptor(packages/catalog/src/provider-models/openai-compat.ts). - Provider Identity Preservation:
xiaomiModelManagerOptions(packages/catalog/src/provider-models/openai-compat.ts) dynamic model fetcher (fetchOpenAICompatibleModels) tags all discovered models withprovider: "xiaomi-token-plan-sgp"andbaseUrl: "https://token-plan-sgp.xiaomimimo.com/v1", ensuring stored model selections map back to the Singapore provider entry. - Bundled Spec Mapping: Dynamic model mapping uses
createBundledReferenceMap(packages/catalog/src/provider-models/openai-compat.ts) to merge dynamic models with static reference specs defined under"xiaomi"inpackages/catalog/src/models.json.
Z.AI (GLM Coding Plan) (zai)
Z.AI provides GLM family models (such as glm-5.2) via Zhipu AI’s coding plan infrastructure using the Anthropic Messages transport (https://api.z.ai/api/anthropic). Authentication supports both direct API keys and an OAuth browser sign-in flow that mints a durable API key.
Special casings
zaithinking format dialect:isZaiThinkingFormat(packages/catalog/src/model-thinking.ts) andisZaiReasoningEffortDialect(packages/ai/src/providers/openai-shared.ts) identify endpoints using thethinkingFormat: "zai"dialect (thinking: { type: "enabled" | "disabled" }). When reasoning is turned off (reasoningDisableMode === "zai-thinking-disabled"or wire effort"none"),resolveOpenAICompatPolicy(packages/ai/src/providers/openai-shared.ts) setsparams.thinking = { type: "disabled" }.- Reasoning content continuation replay: In
streamOpenAICompletionsOnce(packages/ai/src/providers/openai-completions.ts), whencompat.thinkingFormat === "zai"andmodel.reasoningis true, preserved thinking blocks are re-serialized intoassistantMsg.reasoning_contenton cross-API provider switches (e.g. Anthropic → OpenAI) to preserve structured reasoning history without text demotion (#3434). - Foreign thinking preservation:
targetReadsForeignThinkinginpackages/ai/src/providers/transform-messages.tsreturns true for reasoning models withcompat.thinkingFormat === "zai", preserving non-native thinking blocks across message transforms. - Max output token clamping:
resolveOpenAICompletionsOutputClampinpackages/ai/src/providers/openai-shared.tsclamps output forisZaiReasoningEffortDialectmodels (glm-5.2) tomodel.maxTokensrather than the default 64k ceiling. - Host URL matching:
hostMatchesUrlinpackages/catalog/src/hosts.tsmatches Z.AI endpoints against theapi.z.aiURL marker.
Auth & usage
- API Key Login:
loginZaiinpackages/ai/src/registry/zai.tsprompts forZAI_API_KEY(dashboardhttps://z.ai/manage-apikey/apikey-list) and validates via a chat completions probe againsthttps://api.z.ai/api/coding/paas/v4with modelglm-5.2(VALIDATION_MODEL). - OAuth flow & browser sign-in:
zaiCodingPlanProvider(packages/ai/src/registry/zai.ts) routes sign-in tologinZaiOAuth/ZaiOAuthFlow(packages/ai/src/registry/oauth/zai.ts). It initiates authorization atAUTHORIZE_URL(https://chat.z.ai/api/oauth/authorize, callback port 54548 / paste code fallback) and exchanges authorization codes atTOKEN_URL(https://zcode.z.ai/api/v1/oauth/token). - Durable key minting:
mintZaiApiKey(packages/ai/src/registry/oauth/zai.ts) exchanges the short-lived OAuth token for a business token viabusinessLogin(https://api.z.ai/api/auth/z/login), resolves default org/project viagetCustomerInfo(BIZ_BASE=https://api.z.ai), creates or reuses key"oh-my-pi"(KEY_NAME), and copies the secret via/copy/${apiKey}to output a durable 49-char${apiKey}.${secretKey}token saved asstoreCredentialsAs: "zai". - Usage & quota fetcher:
fetchZaiUsage/zaiUsageProvider(packages/ai/src/usage/zai.ts) queriesQUOTA_PATH(/api/monitor/usage/quota/limit) onDEFAULT_ENDPOINT(https://api.z.ai) with direct key authorization.parseLimitItemparsesTOKENS_LIMITinto token quotas (zai:tokens:<window>) andTIME_LIMITinto request quotas (zai:requests:<window>orzai:features:zread:<window>whenisZaiFeatureRequestLimitmatches).buildZaiWindowmaps time units to 1h, 1d, 1mo, or 1w windows, and optionally fetchesMODEL_USAGE_PATH(/api/monitor/usage/model-usage). - Credential ranking:
zaiRankingStrategy(packages/ai/src/usage/zai.ts, registered inpackages/ai/src/auth-storage.ts) ranks request limits viarankZaiRequestLimits, selecting primary 5-hour and secondary weekly quota windows.
Catalog model handling
- Descriptor & PAYG pricing:
MODELS_DEV_PROVIDER_DESCRIPTORS_CODING_PLANSinpackages/catalog/src/provider-models/openai-compat.tsdefinesanthropicMessagesDescriptor("zai", "zai", "https://api.z.ai/api/anthropic"), mapping models.devzaipay-as-you-go pricing key instead ofzai-coding-planto avoid surfacing subscription rates as all-$0 Free models (#5598). - Default model & context policy:
PROVIDER_DESCRIPTORSinpackages/catalog/src/provider-models/descriptors.tssets default modelglm-5.2.generated-policies.ts(packages/catalog/scripts/generated-policies.ts) pinsglm-5.2context window to 1,000,000 tokens, whiledropUnusableZaiContextTierIds(packages/catalog/scripts/generate-models.ts) filters out[1m]context tier ID suffixes. - GLM-5.2 effort support:
getModelDefinedEffortsinpackages/catalog/src/model-thinking.ts(checked viaisAnthropicMessagesGlm52ReasoningEffortModel) assignsHIGH_MAX_REASONING_EFFORTS(["high", "max"]) toglm-5.2, treating"none"as the disabled state rather than a user tier level.
ZenMux (zenmux)
ZenMux is a multi-provider gateway using dual transport routing based on model ownership. Models owned by Anthropic (identified by owned_by: "anthropic" or an anthropic/ prefix) route through Anthropic Messages (https://zenmux.ai/api/anthropic), while all other models route through OpenAI Chat Completions (https://zenmux.ai/api/v1).
Special casings
- Dual Transport Base URL Normalization:
normalizeZenMuxOpenAiBaseUrlandtoZenMuxAnthropicBaseUrl(packages/catalog/src/provider-models/openai-compat.ts) translate between endpoint URLs. OpenAI endpoints default tohttps://zenmux.ai/api/v1and Anthropic routes tohttps://zenmux.ai/api/anthropic, automatically converting paths when custom base URLs are specified. - Anthropic Proxy Signature Integrity:
KNOWN_HOSTS.zenmux(packages/catalog/src/hosts.ts) identifies ZenMux as a signing host. InbuildAnthropicCompat(packages/catalog/src/compat/anthropic.ts),isZenmuxmarks the proxy as asigningEndpoint, settingreplayUnsignedThinking: false. This ensures historical thinking blocks retain valid signatures rather than replaying empty signatures that trigger HTTP 400 errors. - Strict Mode Support:
detectStrictModeSupport(packages/catalog/src/compat/openai.ts) enables strict structured tool outputs for ZenMux OpenAI-compatible endpoints.
Auth & usage
- API Key Resolution:
ZENMUX_API_KEYis registered indescriptors.ts(packages/catalog/src/provider-models/descriptors.ts) and resolved viagetEnvApiKey("zenmux")inpackages/ai/src/stream.ts. - Key Validation & Login:
loginZenMuxinpackages/ai/src/registry/zenmux.tsdirects users tohttps://zenmux.ai/settings/keysand validates credentials withkind: "models-endpoint"againsthttps://zenmux.ai/api/v1/models. - Unauthenticated Discovery:
allowUnauthenticated: trueindescriptors.tsenables model catalog discovery without requiring an API key.
Catalog model handling
- Descriptor & Default Model:
descriptors.tsdefines the provider descriptor with default modelanthropic/claude-opus-4.8. - Dynamic Model Discovery:
zenmuxModelManagerOptionsinpackages/catalog/src/provider-models/openai-compat.tsquerieshttps://zenmux.ai/api/v1/modelsusingfetchOpenAICompatibleModels.isZenMuxAnthropicModelinspectsentry.owned_by === "anthropic"or ID prefixanthropic/to setapi: "anthropic-messages"orapi: "openai-completions". - Pricing Extraction:
getZenMuxPricingValueandgetZenMuxCacheWritePrice(packages/catalog/src/provider-models/openai-compat.ts) extract token costs fromentry.pricings:promptfor input cost,completionfor output cost,input_cache_readfor cache read cost, and hierarchical lookup ofinput_cache_write_1_h,input_cache_write_5_min, orinput_cache_writefor cache write cost. - Capabilities & Limits: Maps
entry.display_name,entry.context_length(contextWindow),entry.max_completion_tokens(maxTokens),entry.input_modalities(input), andcapabilities.reasoning(reasoning).
Zhipu Coding Plan (智谱) (zhipu-coding-plan)
Zhipu (智谱) BigModel’s domestic coding-plan provider using the OpenAI Chat Completions transport (openai-completions API). It routes requests to Zhipu’s dedicated Coding Plan endpoint (https://open.bigmodel.cn/api/coding/paas/v4) rather than the general BigModel endpoint to ensure API calls consume coding-plan quota instead of account balance.
Special casings
- Z.AI Thinking Format & Reasoning Effort: Configures
thinkingFormat: "zai"(packages/catalog/src/compat/openai.tsline 447) to structure thinking outputs viathinking: { type: "enabled" }andreasoning_contentdeltas (cross-referencing the Z.AI format). EnablessupportsReasoningEffortonly for GLM-5.2+ models viaisGlm52ReasoningEffortModelId(packages/catalog/src/compat/openai.tslines 283, 469). - Stream Watchdog Idle Floor: Applies a 600s (
600_000ms) stream idle timeout floor (GLM_CODING_PLAN_STREAM_IDLE_TIMEOUT_MS = 600_000,GLM_CODING_PLAN_MODEL_PATTERNinpackages/catalog/src/compat/openai.tslines 39-40, 417) for GLM coding-plan model IDs (glm-5...) whenisZhipuis active, avoiding spurious stream watchdog aborts during long reasoning phases. - Max Tokens & System Messages: Sets
useMaxTokens: true(packages/catalog/src/compat/openai.tsline 362) and enablessupportsMultipleSystemMessages: true(packages/catalog/src/compat/openai.tsline 408) forisZhipu.
Auth & usage
- Credentials & API Base: Authenticates via
ZHIPU_API_KEY(packages/catalog/src/provider-models/descriptors.tsline 541) with API base URLhttps://open.bigmodel.cn/api/coding/paas/v4(packages/ai/src/registry/zhipu-coding-plan.tsline 6) and dashboard URLhttps://bigmodel.cn/coding-plan/personal/overview(packages/ai/src/registry/zhipu-coding-plan.tsline 5). - API Key Login & Validation:
loginZhipuCodingPlan(packages/ai/src/registry/zhipu-coding-plan.tsline 10) usescreateApiKeyLoginwith key format<id>.<secret>, validating againstglm-5.1athttps://open.bigmodel.cn/api/coding/paas/v4. Host detection is wired viahosts.ts(zhipu, urlMarkeropen.bigmodel.cn,packages/catalog/src/hosts.tsline 42). - Chinese-Language 429 Quota Classification:
CN_QUOTA_EXHAUSTED_PATTERNinpackages/ai/src/error/rate-limit.tsline 60 (/使用.{0,30}?上限|(?:额度|配额)已?(?:用|耗)(?:完|尽)|限额.{0,30}重置|余额不足/) classifies Zhipu’s 429 quota exhaustion responses ("429 已达到 5 小时的使用上限。您的限额将在 ... 重置。") asQUOTA_EXHAUSTED, triggering credential rotation instead of transient backoff.
Catalog model handling
- Provider Descriptor: Registered in
CATALOG_PROVIDERS(packages/catalog/src/provider-models/descriptors.tsline 539) with default modelglm-5.1,dynamicModelsAuthoritative: true, and model manager options fromzhipuCodingPlanModelManagerOptions(packages/catalog/src/provider-models/openai-compat.tslines 1689, 5764). - GLM Identity Classification: Uses
parseGlmModel(packages/catalog/src/identity/classify.tsline 145) to parseglm-<version>[v][-<variant>]into family ("glm"), version, vision flag (v), and variant (base,air,turbo,flash,flashx,preview). - Capability Gates & Policies:
isReasoningGlmModelId(packages/catalog/src/identity/family.tsline 219) gates reasoning on version >= 4.5 (base/air/turbo),isGlm52ReasoningEffortModelIdgatesreasoning_efforton version >= 5.2, andisGlmVisionModelIddetects vision models (glm-4v,glm-4.5v). Generated policy pinsglm-5.2context window to 1,000,000 tokens (packages/catalog/scripts/generated-policies.tsline 332).