import { type ProviderName, type ProviderSettings, type ModelInfo, type ModelRecord, type RouterModels, anthropicModels, bedrockModels, deepSeekModels, moonshotModels, minimaxModels, mimoModels, geminiModels, mistralModels, openAiModelInfoSaneDefaults, openAiNativeModels, vertexModels, xaiModels, vscodeLlmModels, vscodeLlmDefaultModelId, openAiCodexModels, sambaNovaModels, getZAiModels, fireworksModels, friendliModels, basetenModels, qwenCodeModels, kimiCodeDefaultModelInfo, litellmDefaultModelInfo, lMStudioDefaultModelInfo, opencodeGoDefaultModelInfo, kenariDefaultModelInfo, ioIntelligenceDefaultModelInfo, nanoGptDefaultModelInfo, BEDROCK_1M_CONTEXT_MODEL_IDS, BEDROCK_DEFAULT_CONTEXT, BEDROCK_MAX_TOKENS, resolveBedrockCustomArnBaseModelId, VERTEX_1M_CONTEXT_MODEL_IDS, isDynamicProvider, isRetiredProvider, getProviderDefaultModelId, providerIdentifiers, githubCopilotLanguageModel, vscodeLlmBaselineModelInfo, } from "@roo-code/types" import { useRouterModels } from "./useRouterModels" import { useOpenRouterModelProviders } from "./useOpenRouterModelProviders" import { useLmStudioModels } from "./useLmStudioModels" import { useOllamaModels } from "./useOllamaModels" import { useGitHubCopilotModels, type GitHubCopilotModels } from "./useGitHubCopilotModels" import { useVsCodeLmModels, type VsCodeLmModels } from "./useVsCodeLmModels" /** * Helper to get a validated model ID for dynamic providers. * Returns the configured model ID if it exists in the available models, otherwise returns the default. */ function getValidatedModelId( configuredId: string | undefined, availableModels: ModelRecord | undefined, defaultModelId: string, ): string { return configuredId && availableModels?.[configuredId] ? configuredId : defaultModelId } /** * Resolves a static-catalog model for providers backed by `BaseOpenAiCompatibleProvider` * (Fireworks, Baseten, SambaNova). Mirrors the backend `getModel()`: a user-supplied custom * model ID that isn't in the static list is honored with `openAiModelInfoSaneDefaults`, so the * UI shows sensible limits (e.g. context window) instead of treating the selection as unknown. */ function getStaticCatalogModel( configuredId: string | undefined, models: Record, defaultModelId: string, ): { id: string; info: ModelInfo | undefined } { // An empty configured ID means "unset": fall back to the provider default. if (!configuredId) { return { id: defaultModelId, info: models[defaultModelId] } } if (!Object.prototype.hasOwnProperty.call(models, configuredId)) { return { id: configuredId, info: { ...openAiModelInfoSaneDefaults } } } return { id: configuredId, info: models[configuredId] } } /** * Resolves the model currently selected for the active API provider. * * Dynamic providers validate the configured model ID against the fetched * router-model list and only resolve the selection once that list is * available. LiteLLM is the exception: it fronts arbitrary models and * aliases, so a configured `litellmModelId` is the user's explicit * selection and is preserved as soon as the fetch settles, even when the * router payload has no LiteLLM entry (partial listing, failed fetch, or * renamed deployment). */ export const useSelectedModel = (apiConfiguration: ProviderSettings) => { const provider = apiConfiguration.apiProvider || providerIdentifiers.openrouter const activeProvider: ProviderName | undefined = isRetiredProvider(provider) ? undefined : provider const dynamicProvider = activeProvider && isDynamicProvider(activeProvider) ? activeProvider : undefined const openRouterModelId = activeProvider === providerIdentifiers.openrouter ? apiConfiguration.openRouterModelId : undefined const lmStudioModelId = activeProvider === providerIdentifiers.lmstudio ? apiConfiguration.lmStudioModelId : undefined const ollamaModelId = activeProvider === providerIdentifiers.ollama ? apiConfiguration.ollamaModelId : undefined // Only fetch router models for dynamic providers const shouldFetchRouterModels = !!dynamicProvider const routerModels = useRouterModels({ provider: dynamicProvider, enabled: shouldFetchRouterModels, }) const openRouterModelProviders = useOpenRouterModelProviders(openRouterModelId) const lmStudioModels = useLmStudioModels(lmStudioModelId) const ollamaModels = useOllamaModels(ollamaModelId) // Not part of readiness: until the host reports, the curated catalog describes the model. const copilotModels = useGitHubCopilotModels(activeProvider === providerIdentifiers.githubCopilot) const vsCodeLmModels = useVsCodeLmModels(activeProvider === providerIdentifiers.vscodeLm) // Compute readiness only for the data actually needed for the selected provider const needRouterModels = shouldFetchRouterModels const needOpenRouterProviders = activeProvider === providerIdentifiers.openrouter const needLmStudio = typeof lmStudioModelId !== "undefined" const needOllama = typeof ollamaModelId !== "undefined" // LiteLLM and IO Intelligence may legitimately have no entry in the router // payload (partial listing, failed fetch, renamed deployment) even though // the configured ID is a valid selection, so they only need the fetch to // settle. Other dynamic providers require a populated provider entry // before the selection is resolved. const hasValidRouterData = needRouterModels && dynamicProvider ? dynamicProvider === providerIdentifiers.friendli ? true // static friendliModels cover the window before /v1/models data arrives : dynamicProvider === providerIdentifiers.litellm || dynamicProvider === providerIdentifiers.ioIntelligence ? !routerModels.isLoading : routerModels.data && routerModels.data[dynamicProvider] !== undefined && typeof routerModels.data[dynamicProvider] === "object" && !routerModels.isLoading : true const isReady = (!needLmStudio || typeof lmStudioModels.data !== "undefined") && (!needOllama || typeof ollamaModels.data !== "undefined") && hasValidRouterData && (!needOpenRouterProviders || typeof openRouterModelProviders.data !== "undefined") const { id, info } = apiConfiguration && isReady && activeProvider ? getSelectedModel({ provider: activeProvider, apiConfiguration, routerModels: (routerModels.data || {}) as RouterModels, openRouterModelProviders: (openRouterModelProviders.data || {}) as Record, lmStudioModels: (lmStudioModels.data || undefined) as ModelRecord | undefined, ollamaModels: (ollamaModels.data || undefined) as ModelRecord | undefined, copilotModels: copilotModels.data, vsCodeLmModels: vsCodeLmModels.data, }) : activeProvider === providerIdentifiers.kimiCode && apiConfiguration ? { id: apiConfiguration.apiModelId || getProviderDefaultModelId(providerIdentifiers.kimiCode, apiConfiguration), info: kimiCodeDefaultModelInfo, } : { id: getProviderDefaultModelId( activeProvider ?? providerIdentifiers.openrouter, apiConfiguration ?? {}, ), info: undefined, } return { provider, id, info, isLoading: (needRouterModels && routerModels.isLoading) || (needOpenRouterProviders && openRouterModelProviders.isLoading) || (needLmStudio && lmStudioModels!.isLoading) || (needOllama && ollamaModels!.isLoading), isError: (needRouterModels && routerModels.isError) || (needOpenRouterProviders && openRouterModelProviders.isError) || (needLmStudio && lmStudioModels!.isError) || (needOllama && ollamaModels!.isError), } } function getSelectedModel({ provider, apiConfiguration, routerModels, openRouterModelProviders, lmStudioModels, ollamaModels, copilotModels, vsCodeLmModels, }: { provider: ProviderName apiConfiguration: ProviderSettings routerModels: RouterModels openRouterModelProviders: Record lmStudioModels: ModelRecord | undefined ollamaModels: ModelRecord | undefined copilotModels?: GitHubCopilotModels vsCodeLmModels?: VsCodeLmModels }): { id: string; info: ModelInfo | undefined } { // the `undefined` case are used to show the invalid selection to prevent // users from seeing the default model if their selection is invalid // this gives a better UX than showing the default model const defaultModelId = getProviderDefaultModelId(provider, apiConfiguration) switch (provider) { case providerIdentifiers.openrouter: { const id = getValidatedModelId( apiConfiguration.openRouterModelId, routerModels[providerIdentifiers.openrouter], defaultModelId, ) let info = routerModels[providerIdentifiers.openrouter]?.[id] const specificProvider = apiConfiguration.openRouterSpecificProvider if (specificProvider && openRouterModelProviders[specificProvider]) { // Overwrite the info with the specific provider info. Some // fields are missing the model info for `openRouterModelProviders` // so we need to merge the two. info = info ? { ...info, ...openRouterModelProviders[specificProvider] } : openRouterModelProviders[specificProvider] } return { id, info } } case providerIdentifiers.requesty: { const id = getValidatedModelId( apiConfiguration.requestyModelId, routerModels[providerIdentifiers.requesty], defaultModelId, ) const routerInfo = routerModels[providerIdentifiers.requesty]?.[id] return { id, info: routerInfo } } case providerIdentifiers.unbound: { const id = getValidatedModelId( apiConfiguration.unboundModelId, routerModels[providerIdentifiers.unbound], defaultModelId, ) const routerInfo = routerModels[providerIdentifiers.unbound]?.[id] return { id, info: routerInfo } } case providerIdentifiers.litellm: { // LiteLLM is a proxy that fronts arbitrary models and aliases, so a // configured model ID is the user's explicit selection even when it is // absent from the fetched list (custom aliases, incomplete or stale // listings, renamed deployments). Never substitute a hardcoded default // over a configured ID -- doing so silently discards the user's model // choice on the settings screen. Only fall back to the default when // nothing is configured and a populated list exists; when the list is // empty we return an empty ID so the picker shows "no selection" rather // than a phantom model that does not exist on the server. const litellmModels = routerModels[providerIdentifiers.litellm] const id = apiConfiguration.litellmModelId ?? (litellmModels && Object.keys(litellmModels).length > 0 ? defaultModelId : "") const routerInfo = litellmModels?.[id] return { id, info: routerInfo ?? litellmDefaultModelInfo } } case providerIdentifiers.xai: { const id = apiConfiguration.apiModelId ?? defaultModelId const info = xaiModels[id as keyof typeof xaiModels] return info ? { id, info } : { id, info: undefined } } case providerIdentifiers.baseten: return getStaticCatalogModel(apiConfiguration.apiModelId, basetenModels, defaultModelId) case providerIdentifiers.bedrock: { const id = apiConfiguration.apiModelId ?? defaultModelId // A custom ARN takes the capabilities of the model it points to; "Other" mirrors the provider fallback. if (id === "custom-arn") { const customArnBaseModelId = resolveBedrockCustomArnBaseModelId( apiConfiguration.awsCustomArn, apiConfiguration.awsCustomArnBaseModelId, ) if (!customArnBaseModelId) { return { id, info: { maxTokens: apiConfiguration.modelMaxTokens || BEDROCK_MAX_TOKENS, contextWindow: apiConfiguration.awsModelContextWindow || BEDROCK_DEFAULT_CONTEXT, supportsPromptCache: true, supportsImages: true, }, } } const baseInfo: ModelInfo = bedrockModels[customArnBaseModelId] // Mirror the provider: the 1M context beta switches to the first pricing tier. const use1MContext = (BEDROCK_1M_CONTEXT_MODEL_IDS as readonly string[]).includes(customArnBaseModelId) && !!apiConfiguration.awsBedrock1MContext const tier = use1MContext ? baseInfo.tiers?.[0] : undefined const customArnInfo: ModelInfo = { ...baseInfo, ...(use1MContext ? { contextWindow: tier?.contextWindow ?? 1_000_000, inputPrice: tier?.inputPrice ?? baseInfo.inputPrice, outputPrice: tier?.outputPrice ?? baseInfo.outputPrice, cacheWritesPrice: tier?.cacheWritesPrice ?? baseInfo.cacheWritesPrice, cacheReadsPrice: tier?.cacheReadsPrice ?? baseInfo.cacheReadsPrice, } : {}), ...(apiConfiguration.awsModelContextWindow ? { contextWindow: apiConfiguration.awsModelContextWindow } : {}), } return { id, info: customArnInfo } } const baseInfo = bedrockModels[id as keyof typeof bedrockModels] // Apply 1M context for supported Claude 4 models when enabled if (BEDROCK_1M_CONTEXT_MODEL_IDS.includes(id as any) && apiConfiguration.awsBedrock1MContext && baseInfo) { // Create a new ModelInfo object with updated context window const info: ModelInfo = { ...baseInfo, contextWindow: 1_000_000, } return { id, info } } return { id, info: baseInfo } } case providerIdentifiers.vertex: { const id = apiConfiguration.apiModelId ?? defaultModelId const baseInfo = vertexModels[id as keyof typeof vertexModels] // Apply 1M context for supported Claude 4 models when enabled if (VERTEX_1M_CONTEXT_MODEL_IDS.includes(id as any) && apiConfiguration.vertex1MContext && baseInfo) { const modelInfo: ModelInfo = baseInfo const tier = modelInfo.tiers?.[0] if (tier) { const info: ModelInfo = { ...modelInfo, contextWindow: tier.contextWindow, inputPrice: tier.inputPrice, outputPrice: tier.outputPrice, cacheWritesPrice: tier.cacheWritesPrice, cacheReadsPrice: tier.cacheReadsPrice, } return { id, info } } } return { id, info: baseInfo } } case providerIdentifiers.gemini: { const id = apiConfiguration.apiModelId ?? defaultModelId const info = geminiModels[id as keyof typeof geminiModels] return { id, info } } case providerIdentifiers.deepseek: { const availableModels = routerModels[providerIdentifiers.deepseek] ? { ...deepSeekModels, ...routerModels[providerIdentifiers.deepseek] } : deepSeekModels const id = getValidatedModelId(apiConfiguration.apiModelId, availableModels, defaultModelId) const routerInfo = routerModels[providerIdentifiers.deepseek]?.[id] const staticInfo = deepSeekModels[id as keyof typeof deepSeekModels] return { id, info: routerInfo ?? staticInfo } } case providerIdentifiers.moonshot: { const availableModels = routerModels[providerIdentifiers.moonshot] ? { ...moonshotModels, ...routerModels[providerIdentifiers.moonshot] } : moonshotModels const id = getValidatedModelId(apiConfiguration.apiModelId, availableModels, defaultModelId) const routerInfo = routerModels[providerIdentifiers.moonshot]?.[id] const staticInfo = moonshotModels[id as keyof typeof moonshotModels] return { id, info: routerInfo ?? staticInfo } } case providerIdentifiers.kimiCode: { const configuredId = apiConfiguration.apiModelId const availableModels = routerModels[providerIdentifiers.kimiCode] const id = configuredId || defaultModelId return { id, info: availableModels?.[id] ?? kimiCodeDefaultModelInfo } } case providerIdentifiers.minimax: { const id = apiConfiguration.apiModelId ?? defaultModelId const info = minimaxModels[id as keyof typeof minimaxModels] return { id, info } } case providerIdentifiers.mimo: { const id = apiConfiguration.apiModelId ?? defaultModelId const info = mimoModels[id as keyof typeof mimoModels] ?? mimoModels["mimo-v2.5-pro"] return { id, info } } case providerIdentifiers.zai: { const apiLine = apiConfiguration.zaiApiLine ?? "international_coding" const models = getZAiModels(apiLine) const defaultModelId = getProviderDefaultModelId(provider, apiConfiguration) const configuredId = apiConfiguration.apiModelId if (configuredId) { return { id: configuredId, info: models[configuredId] ?? openAiModelInfoSaneDefaults } } return { id: defaultModelId, info: models[defaultModelId] } } case providerIdentifiers.openaiNative: { const id = apiConfiguration.apiModelId ?? defaultModelId const info = openAiNativeModels[id as keyof typeof openAiNativeModels] return { id, info } } case providerIdentifiers.mistral: { const id = apiConfiguration.apiModelId ?? defaultModelId const info = mistralModels[id as keyof typeof mistralModels] return { id, info } } case providerIdentifiers.openai: { const id = apiConfiguration.openAiModelId ?? "" const customInfo = apiConfiguration.openAiCustomModelInfo const info = customInfo ?? openAiModelInfoSaneDefaults return { id, info } } case providerIdentifiers.ollama: { const id = apiConfiguration.ollamaModelId ?? "" const info = ollamaModels && ollamaModels[apiConfiguration.ollamaModelId!] const adjustedInfo = info?.contextWindow && apiConfiguration.ollamaNumCtx && apiConfiguration.ollamaNumCtx < info.contextWindow ? { ...info, contextWindow: apiConfiguration.ollamaNumCtx } : info return { id, info: adjustedInfo || undefined, } } case providerIdentifiers.lmstudio: { const id = apiConfiguration.lmStudioModelId ?? "" const modelInfo = lmStudioModels && lmStudioModels[apiConfiguration.lmStudioModelId!] return { id, info: modelInfo ? { ...lMStudioDefaultModelInfo, ...modelInfo } : undefined, } } case providerIdentifiers.githubCopilot: { const selector = apiConfiguration.vsCodeLmModelSelector // What the host reports now wins; the curated catalog only describes a model it has not reported. const reported = selector?.id ? copilotModels?.find((model) => model.id === selector.id) : selector?.family ? copilotModels?.find((model) => model.family === selector.family) : undefined const knownModel = selector?.family ? vscodeLlmModels[selector.family as keyof typeof vscodeLlmModels] : undefined return { id: selector?.id ?? (selector?.family ? `${githubCopilotLanguageModel.vendor}/${selector.family}` : vscodeLlmDefaultModelId), info: { ...vscodeLlmBaselineModelInfo, ...knownModel, // The extension enforces the curated input limit, so the UI must not show the larger window. ...(knownModel && { contextWindow: knownModel.maxInputTokens }), ...reported?.modelInfo, // Vision and tool support are the host's word alone, as the extension reads them; the // catalog marks every family as supporting both, which is not a host report. supportsImages: reported?.modelInfo?.supportsImages, supportsToolCalling: reported?.modelInfo?.supportsToolCalling, supportsPromptCache: false, }, } } case providerIdentifiers.vscodeLm: { const selector = apiConfiguration.vsCodeLmModelSelector const matches = vsCodeLmModels?.filter((model) => (["id", "vendor", "family", "version"] as const).every( (key) => selector?.[key] === undefined || model[key] === selector[key], ), ) // The host selects its first match; a separate listing cannot establish that order. const reported = matches?.length === 1 ? matches[0] : undefined const id = apiConfiguration.vsCodeLmModelSelector ? `${apiConfiguration.vsCodeLmModelSelector.vendor}/${apiConfiguration.vsCodeLmModelSelector.family}` : vscodeLlmDefaultModelId const modelFamily = apiConfiguration.vsCodeLmModelSelector?.family ?? vscodeLlmDefaultModelId // On a family miss, fall back to the default model entry, not openAiModelInfoSaneDefaults // (whose 128K contextWindow would diverge from the gate and skew the bar). const listedModel = vscodeLlmModels[modelFamily as keyof typeof vscodeLlmModels] ?? vscodeLlmModels[vscodeLlmDefaultModelId] // Set contextWindow = maxInputTokens so the UI bar shares one source of truth with the gate, // whose primary window is getCondenseContextWindow() (static-table maxInputTokens); this // info.contextWindow is only the gate's fallback. const info: ModelInfo = { ...openAiModelInfoSaneDefaults, ...listedModel, contextWindow: listedModel.maxInputTokens, supportsImages: reported?.modelInfo?.supportsImages, } return { id, info } } case providerIdentifiers.sambanova: return getStaticCatalogModel(apiConfiguration.apiModelId, sambaNovaModels, defaultModelId) case providerIdentifiers.fireworks: return getStaticCatalogModel(apiConfiguration.apiModelId, fireworksModels, defaultModelId) case providerIdentifiers.friendli: { const id = apiConfiguration.apiModelId || defaultModelId // Mirror the backend getModel(): own-property reads only (an ID such as "toString" must // not resolve to an inherited member), and sane defaults when neither catalog has the ID. const fetched = routerModels.friendli const info = (fetched && Object.hasOwn(fetched, id) ? fetched[id] : undefined) ?? (Object.hasOwn(friendliModels, id) ? friendliModels[id as keyof typeof friendliModels] : undefined) ?? openAiModelInfoSaneDefaults return { id, info } } case providerIdentifiers.poe: { const id = apiConfiguration.apiModelId ?? defaultModelId const info = routerModels[providerIdentifiers.poe]?.[id] return { id, info } } case providerIdentifiers.qwenCode: { const id = apiConfiguration.apiModelId ?? defaultModelId const info = qwenCodeModels[id as keyof typeof qwenCodeModels] return { id, info } } case providerIdentifiers.openaiCodex: { const id = apiConfiguration.apiModelId ?? defaultModelId const info = openAiCodexModels[id as keyof typeof openAiCodexModels] return { id, info } } case providerIdentifiers.vercelAiGateway: { const id = getValidatedModelId( apiConfiguration.vercelAiGatewayModelId, routerModels[providerIdentifiers.vercelAiGateway], defaultModelId, ) const info = routerModels[providerIdentifiers.vercelAiGateway]?.[id] return { id, info } } case providerIdentifiers.opencodeGo: { const id = getValidatedModelId( apiConfiguration.opencodeGoModelId, routerModels[providerIdentifiers.opencodeGo], defaultModelId, ) // Fall back to the provider's default ModelInfo so capability-driven UI // keeps working when the /models list is empty or unavailable. const info = routerModels[providerIdentifiers.opencodeGo]?.[id] ?? opencodeGoDefaultModelInfo return { id, info } } case providerIdentifiers.kenari: { const id = getValidatedModelId( apiConfiguration.kenariModelId, routerModels[providerIdentifiers.kenari], defaultModelId, ) // Fall back to the provider's default ModelInfo so capability-driven UI // keeps working when the /models list is empty or unavailable. const info = routerModels[providerIdentifiers.kenari]?.[id] ?? kenariDefaultModelInfo return { id, info } } case providerIdentifiers.ioIntelligence: { // A configured id is the user's explicit selection (ModelPicker's // "Use custom model" path stores ids absent from the fetched catalog) // and the handler sends requests with it, so keep it instead of // displaying a default model that requests do not use. const id = apiConfiguration.ioIntelligenceModelId || defaultModelId const info = routerModels[providerIdentifiers.ioIntelligence]?.[id] ?? ioIntelligenceDefaultModelInfo return { id, info } } case providerIdentifiers.nanogpt: { const id = getValidatedModelId( apiConfiguration.nanoGptModelId, routerModels[providerIdentifiers.nanogpt], defaultModelId, ) const info = routerModels[providerIdentifiers.nanogpt]?.[id] ?? nanoGptDefaultModelInfo return { id, info } } case providerIdentifiers.zooGateway: { const id = getValidatedModelId( apiConfiguration.zooGatewayModelId, routerModels[providerIdentifiers.zooGateway], defaultModelId, ) const info = routerModels[providerIdentifiers.zooGateway]?.[id] return { id, info } } case providerIdentifiers.anthropic: case providerIdentifiers.geminiCli: case providerIdentifiers.fakeAi: { const id = apiConfiguration.apiModelId ?? defaultModelId const baseInfo = anthropicModels[id as keyof typeof anthropicModels] // Apply 1M context beta tier pricing for supported Claude 4 models if ( provider === providerIdentifiers.anthropic && (id === "claude-sonnet-4-20250514" || id === "claude-sonnet-4-5" || id === "claude-sonnet-4-6" || id === "claude-opus-4-6") && apiConfiguration.anthropicBeta1MContext && baseInfo ) { // Type assertion since supported Claude 4 models include 1M context pricing tiers. const modelWithTiers = baseInfo as typeof baseInfo & { tiers?: Array<{ contextWindow: number inputPrice?: number outputPrice?: number cacheWritesPrice?: number cacheReadsPrice?: number }> } const tier = modelWithTiers.tiers?.[0] if (tier) { // Create a new ModelInfo object with updated values const info: ModelInfo = { ...baseInfo, contextWindow: tier.contextWindow, inputPrice: tier.inputPrice ?? baseInfo.inputPrice, outputPrice: tier.outputPrice ?? baseInfo.outputPrice, cacheWritesPrice: tier.cacheWritesPrice ?? baseInfo.cacheWritesPrice, cacheReadsPrice: tier.cacheReadsPrice ?? baseInfo.cacheReadsPrice, } return { id, info } } } return { id, info: baseInfo } } default: { provider satisfies never throw new Error(`Unsupported provider: ${provider}`) } } }