diff --git a/src/api/providers/__tests__/anthropic-vertex.spec.ts b/src/api/providers/__tests__/anthropic-vertex.spec.ts index 564ad3a320..38b877cfae 100644 --- a/src/api/providers/__tests__/anthropic-vertex.spec.ts +++ b/src/api/providers/__tests__/anthropic-vertex.spec.ts @@ -4,7 +4,7 @@ import { Anthropic } from "@anthropic-ai/sdk" import { AnthropicVertex } from "@anthropic-ai/vertex-sdk" import { GoogleAuth } from "google-auth-library" -import { VERTEX_1M_CONTEXT_MODEL_IDS } from "@roo-code/types" +import { VERTEX_1M_CONTEXT_MODEL_IDS, vertexDefaultModelId } from "@roo-code/types" import { AnthropicVertexHandler } from "../anthropic-vertex" import { MAX_TIMEOUT_MS } from "../utils/abort-signal" @@ -2435,3 +2435,82 @@ describe("VertexHandler", () => { }) }) }) + +describe("AnthropicVertexHandler model resolution", () => { + const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "user message" }] + + const stubCreate = (handler: AnthropicVertexHandler, mockCreate: ReturnType) => { + // The handler's client is private; reach it once here rather than casting at + // each call site. `messages.create` is replaced with a plain vitest mock. + const client = handler["client"] as unknown as { messages: { create: unknown } } + client.messages.create = mockCreate + } + + it("stops createMessage with an error that names the provider and requested model ID", async () => { + const handler = new AnthropicVertexHandler({ + apiModelId: "claude-unknown-99", + vertexProjectId: "test-project", + }) + const mockCreate = vitest.fn() + stubCreate(handler, mockCreate) + + await expect(collectStream(handler.createMessage("system prompt", messages))).rejects.toThrow( + 'Anthropic Vertex: the selected model "claude-unknown-99" is not in the model registry', + ) + + expect(mockCreate).not.toHaveBeenCalled() + }) + + it("stops completePrompt with the same error when the selected model is not in the model list", async () => { + const handler = new AnthropicVertexHandler({ + apiModelId: "claude-unknown-99", + vertexProjectId: "test-project", + }) + const mockCreate = vitest.fn() + stubCreate(handler, mockCreate) + + await expect(handler.completePrompt("test prompt")).rejects.toThrow( + 'Anthropic Vertex: the selected model "claude-unknown-99" is not in the model registry', + ) + + expect(mockCreate).not.toHaveBeenCalled() + }) + + it("resolves the provider default when no model was selected", async () => { + const handler = new AnthropicVertexHandler({ vertexProjectId: "test-project" }) + const mockCreate = vitest.fn().mockImplementation(async () => + asyncStreamFrom([ + { + type: "message_start", + message: { usage: { input_tokens: 10, output_tokens: 5 } }, + }, + ]), + ) + stubCreate(handler, mockCreate) + + await collectStream(handler.createMessage("system prompt", messages)) + + expect(mockCreate).toHaveBeenCalled() + expect(mockCreate.mock.calls[0][0]).toMatchObject({ model: vertexDefaultModelId }) + }) + + it("sends a registered model ID unchanged", async () => { + const handler = new AnthropicVertexHandler({ + apiModelId: "claude-3-5-sonnet-v2@20241022", + vertexProjectId: "test-project", + }) + const mockCreate = vitest.fn().mockImplementation(async () => + asyncStreamFrom([ + { + type: "message_start", + message: { usage: { input_tokens: 10, output_tokens: 5 } }, + }, + ]), + ) + stubCreate(handler, mockCreate) + + await collectStream(handler.createMessage("system prompt", messages)) + + expect(mockCreate.mock.calls[0][0]).toMatchObject({ model: "claude-3-5-sonnet-v2@20241022" }) + }) +}) diff --git a/src/api/providers/__tests__/bedrock-unresolved-model.spec.ts b/src/api/providers/__tests__/bedrock-unresolved-model.spec.ts new file mode 100644 index 0000000000..8070bd3755 --- /dev/null +++ b/src/api/providers/__tests__/bedrock-unresolved-model.spec.ts @@ -0,0 +1,168 @@ +// npx vitest run src/api/providers/__tests__/bedrock-unresolved-model.spec.ts + +import { ApiHandlerOptions } from "../../../shared/api" +import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" +import { clearAllMocks } from "../../../test-utils/reset" + +import { bedrockDefaultModelId } from "@roo-code/types" + +import { AwsBedrockHandler } from "../bedrock" + +// Mock AWS SDK credential providers and Bedrock client +vitest.mock("@aws-sdk/credential-providers", () => ({ + fromIni: vitest.fn().mockReturnValue({ + accessKeyId: "test-access-key", + secretAccessKey: "test-secret-key", + }), +})) + +// Payloads handed to the Converse commands, for outbound model ID assertions. +const mockCommandInputs: Record[] = [] + +// Mock Smithy client +vitest.mock("@smithy/smithy-client", () => ({ + throwDefaultError: vitest.fn(), +})) + +// Create a mock send function that we can reference +const mockSend = vitest.fn().mockImplementation(async () => { + return { + $metadata: { + httpStatusCode: 200, + requestId: "mock-request-id", + }, + stream: asyncStreamFrom([ + { + metadata: { + usage: { + inputTokens: 10, + outputTokens: 5, + }, + }, + }, + ]), + } +}) + +// Mock AWS SDK modules +vitest.mock("@aws-sdk/client-bedrock-runtime", () => { + const asCommand = (params: Record) => ({ + ...params, + input: params, + middlewareStack: { + clone: () => ({ resolve: () => {} }), + use: () => {}, + }, + }) + + return { + BedrockRuntimeClient: vitest.fn().mockImplementation(function () { + return { + send: mockSend, + config: { region: "us-east-1" }, + middlewareStack: { + clone: () => ({ resolve: () => {} }), + use: () => {}, + }, + } + }), + ConverseStreamCommand: vitest.fn(function (params: Record) { + mockCommandInputs.push(params) + return asCommand(params) + }), + ConverseCommand: vitest.fn(function (params: Record) { + mockCommandInputs.push(params) + return asCommand(params) + }), + } +}) + +describe("AwsBedrockHandler model resolution", () => { + const baseOptions: ApiHandlerOptions = { + awsAccessKey: "test-access-key", + awsSecretKey: "test-secret-key", + awsRegion: "us-east-1", + } + + const messages = [{ role: "user" as const, content: "user message" }] + + beforeEach(() => { + clearAllMocks() + mockCommandInputs.length = 0 + }) + + it("stops createMessage with an error that names the provider and requested model ID", async () => { + const handler = new AwsBedrockHandler({ ...baseOptions, apiModelId: "amazon.ergo-99.0" }) + + await expect(collectStream(handler.createMessage("system prompt", messages))).rejects.toThrow( + 'Bedrock: the selected model "amazon.ergo-99.0" is not in the model registry', + ) + + expect(mockSend).not.toHaveBeenCalled() + }) + + it("stops completePrompt with the same error when the selected model is not in the registry", async () => { + const handler = new AwsBedrockHandler({ ...baseOptions, apiModelId: "amazon.ergo-99.0" }) + + await expect(handler.completePrompt("test prompt")).rejects.toThrow( + 'Bedrock: the selected model "amazon.ergo-99.0" is not in the model registry', + ) + + expect(mockSend).not.toHaveBeenCalled() + }) + + it("resolves the provider default when no model was selected", async () => { + const handler = new AwsBedrockHandler({ ...baseOptions }) + + expect(handler.getModel().id).toBe(bedrockDefaultModelId) + + await collectStream(handler.createMessage("system prompt", messages)) + + expect(mockSend).toHaveBeenCalledTimes(1) + expect(mockCommandInputs[0]?.modelId).toBe(bedrockDefaultModelId) + }) + + it("keeps the non-foundation-model ARN passthrough", async () => { + const arn = "arn:aws:bedrock:us-east-1:123456789012:inference-profile/my-custom-profile" + const handler = new AwsBedrockHandler({ ...baseOptions, awsCustomArn: arn }) + + await collectStream(handler.createMessage("system prompt", messages)) + + expect(mockSend).toHaveBeenCalledTimes(1) + expect(mockCommandInputs[0]?.modelId).toBe(arn) + }) + + it("stops the request when a foundation-model ARN names an unregistered model", async () => { + const arn = "arn:aws:bedrock:us-east-1::foundation-model/amazon.ergo-99.0" + const handler = new AwsBedrockHandler({ ...baseOptions, awsCustomArn: arn }) + + await expect(collectStream(handler.createMessage("system prompt", messages))).rejects.toThrow( + `Bedrock: the selected model "${arn}" is not in the model registry`, + ) + + expect(mockSend).not.toHaveBeenCalled() + }) + + it("sends a registered model ID unchanged", async () => { + const handler = new AwsBedrockHandler({ + ...baseOptions, + apiModelId: "anthropic.claude-3-5-sonnet-20241022-v2:0", + }) + + await collectStream(handler.createMessage("system prompt", messages)) + + expect(mockSend).toHaveBeenCalledTimes(1) + expect(mockCommandInputs[0]?.modelId).toBe("anthropic.claude-3-5-sonnet-20241022-v2:0") + }) + + it("accepts an inference-profile prefixed ID whose base model is registered", async () => { + const handler = new AwsBedrockHandler({ + ...baseOptions, + apiModelId: "us.anthropic.claude-3-5-sonnet-20241022-v2:0", + }) + + await expect(collectStream(handler.createMessage("system prompt", messages))).resolves.toBeDefined() + + expect(mockSend).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/api/providers/__tests__/minimax.spec.ts b/src/api/providers/__tests__/minimax.spec.ts index 7564ec5362..fd5ca18295 100644 --- a/src/api/providers/__tests__/minimax.spec.ts +++ b/src/api/providers/__tests__/minimax.spec.ts @@ -881,3 +881,65 @@ describe("MiniMaxHandler", () => { }) }) }) + +describe("MiniMaxHandler model resolution", () => { + const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "user message" }] + + // The SDK mock shares one `messages.create` mock across all client instances. + const sharedCreateMock = () => { + const instance = (Anthropic as unknown as () => { messages: { create: unknown } })() + return instance.messages.create as ReturnType + } + + beforeEach(() => { + clearAllMocks() + }) + + it("stops createMessage with an error that names the provider and requested model ID", async () => { + const handler = new MiniMaxHandler({ apiModelId: "MiniMax-Unknown-99", minimaxApiKey: "test-api-key" }) + const mockCreate = sharedCreateMock() + + await expect(collectStream(handler.createMessage("system prompt", messages))).rejects.toThrow( + 'MiniMax: the selected model "MiniMax-Unknown-99" is not in the model registry', + ) + + expect(mockCreate).not.toHaveBeenCalled() + }) + + it("stops completePrompt with the same error when the selected model is not in the model list", async () => { + const handler = new MiniMaxHandler({ apiModelId: "MiniMax-Unknown-99", minimaxApiKey: "test-api-key" }) + const mockCreate = sharedCreateMock() + + await expect(handler.completePrompt("test prompt")).rejects.toThrow( + 'MiniMax: the selected model "MiniMax-Unknown-99" is not in the model registry', + ) + + expect(mockCreate).not.toHaveBeenCalled() + }) + + it("resolves the provider default when no model was selected", async () => { + const handler = new MiniMaxHandler({ minimaxApiKey: "test-api-key" }) + const mockCreate = sharedCreateMock() + mockCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: "response" }], + }) + + const result = await handler.completePrompt("test prompt") + + expect(result).toBe("response") + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: minimaxDefaultModelId }), undefined) + }) + + it("sends a registered model ID unchanged", async () => { + const handler = new MiniMaxHandler({ apiModelId: "MiniMax-M2", minimaxApiKey: "test-api-key" }) + const mockCreate = sharedCreateMock() + mockCreate.mockResolvedValueOnce({ + content: [{ type: "text", text: "response" }], + }) + + const result = await handler.completePrompt("test prompt") + + expect(result).toBe("response") + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: "MiniMax-M2" }), undefined) + }) +}) diff --git a/src/api/providers/__tests__/openai-codex-native-tool-calls.spec.ts b/src/api/providers/__tests__/openai-codex-native-tool-calls.spec.ts index 39afbbcca7..d80c9df5ef 100644 --- a/src/api/providers/__tests__/openai-codex-native-tool-calls.spec.ts +++ b/src/api/providers/__tests__/openai-codex-native-tool-calls.spec.ts @@ -18,7 +18,7 @@ describe("OpenAiCodexHandler native tool calls", () => { vi.restoreAllMocks() mockOptions = { - apiModelId: "gpt-5.2-2025-12-11", + apiModelId: "gpt-5.6-sol", // minimal settings; OAuth is mocked below } handler = new OpenAiCodexHandler(mockOptions) diff --git a/src/api/providers/__tests__/openai-codex.spec.ts b/src/api/providers/__tests__/openai-codex.spec.ts index 216bf07c41..5b8345de2f 100644 --- a/src/api/providers/__tests__/openai-codex.spec.ts +++ b/src/api/providers/__tests__/openai-codex.spec.ts @@ -30,6 +30,62 @@ function createCompletedStream() { ]) } +describe("OpenAiCodexHandler model resolution", () => { + afterEach(() => { + vitest.restoreAllMocks() + }) + + it("stops createMessage with an error that names the provider and requested model ID", async () => { + const handler = new OpenAiCodexHandler({ apiModelId: "not-a-real-model" }) + const mockCreate = vitest.fn() + Reflect.set(handler, "client", { responses: { create: mockCreate } }) + vitest.spyOn(openAiCodexOAuthManager, "getAccessToken").mockResolvedValue("test-token") + + await expect(collectStream(handler.createMessage("System prompt", []))).rejects.toThrow( + 'OpenAI Codex: the selected model "not-a-real-model" is not in the model registry', + ) + + expect(mockCreate).not.toHaveBeenCalled() + }) + + it("stops completePrompt with the same error when the selected model is not in the model list", async () => { + const handler = new OpenAiCodexHandler({ apiModelId: "not-a-real-model" }) + const mockCreate = vitest.fn() + Reflect.set(handler, "client", { responses: { create: mockCreate } }) + vitest.spyOn(openAiCodexOAuthManager, "getAccessToken").mockResolvedValue("test-token") + + await expect(handler.completePrompt("Test prompt")).rejects.toThrow( + 'OpenAI Codex: the selected model "not-a-real-model" is not in the model registry', + ) + + expect(mockCreate).not.toHaveBeenCalled() + }) + + it("resolves the provider default when no model was selected", async () => { + const handler = new OpenAiCodexHandler({}) + const mockCreate = vitest.fn().mockResolvedValue(createCompletedStream()) + Reflect.set(handler, "client", { responses: { create: mockCreate } }) + vitest.spyOn(openAiCodexOAuthManager, "getAccessToken").mockResolvedValue("test-token") + + await collectStream(handler.createMessage("System prompt", [])) + + expect(mockCreate).toHaveBeenCalled() + const [body] = mockCreate.mock.calls[0] + expect(body).toMatchObject({ model: "gpt-5.6-sol" }) + }) + + it("sends a registered model ID unchanged", async () => { + const handler = new OpenAiCodexHandler({ apiModelId: "gpt-5.1-codex" }) + const mockCreate = vitest.fn().mockResolvedValue(createCompletedStream()) + Reflect.set(handler, "client", { responses: { create: mockCreate } }) + vitest.spyOn(openAiCodexOAuthManager, "getAccessToken").mockResolvedValue("test-token") + + await collectStream(handler.createMessage("System prompt", [])) + + expect(mockCreate.mock.calls[0][0]).toMatchObject({ model: "gpt-5.1-codex" }) + }) +}) + describe("OpenAiCodexHandler.getModel", () => { it.each(["gpt-5.1", "gpt-5", "gpt-5.1-codex", "gpt-5-codex", "gpt-5-codex-mini", "gpt-5.3-codex-spark"])( "should return specified model when a valid model id is provided: %s", @@ -1097,7 +1153,7 @@ describe("OpenAiCodexHandler Responses Lite requests", () => { expect(mockFetch).toHaveBeenCalledTimes(1) }) - it.each(["gpt-5.5", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna-alias"])( + it.each(["gpt-5.5", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-6-luna"])( "does not apply Luna behavior to %s", async (apiModelId) => { const handler = new OpenAiCodexHandler({ apiModelId }) diff --git a/src/api/providers/__tests__/openai-native.spec.ts b/src/api/providers/__tests__/openai-native.spec.ts index b02752d757..2c8e8f8771 100644 --- a/src/api/providers/__tests__/openai-native.spec.ts +++ b/src/api/providers/__tests__/openai-native.spec.ts @@ -17,6 +17,7 @@ import { ApiProviderError, OpenAiServiceTier, SERVICE_TIER_KEY, + openAiNativeDefaultModelId, openAiNativeModels, serviceTiers, } from "@roo-code/types" @@ -4425,3 +4426,77 @@ describe("GPT-5 streaming event coverage (additional)", () => { }) }) }) + +describe("OpenAiNativeHandler model resolution", () => { + const systemPrompt = "You are a helpful assistant." + const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hello!" }] + + beforeEach(() => { + mockResponsesCreate.mockReset() + deleteGlobalFetch() + }) + + afterEach(() => { + deleteGlobalFetch() + }) + + it("stops createMessage with an error that names the provider and requested model ID", async () => { + const handler = new OpenAiNativeHandler({ + apiModelId: "not-a-real-openai-model", + openAiNativeApiKey: "test-api-key", + }) + + await expect(collectStream(handler.createMessage(systemPrompt, messages))).rejects.toThrow( + 'OpenAI Native: the selected model "not-a-real-openai-model" is not in the model registry', + ) + + expect(mockResponsesCreate).not.toHaveBeenCalled() + }) + + it("stops completePrompt with the same error when the selected model is not in the model list", async () => { + const handler = new OpenAiNativeHandler({ + apiModelId: "not-a-real-openai-model", + openAiNativeApiKey: "test-api-key", + }) + + await expect(handler.completePrompt("Test prompt")).rejects.toThrow( + 'OpenAI Native: the selected model "not-a-real-openai-model" is not in the model registry', + ) + + expect(mockResponsesCreate).not.toHaveBeenCalled() + }) + + it("resolves the provider default when no model was selected", async () => { + const handler = new OpenAiNativeHandler({ openAiNativeApiKey: "test-api-key" }) + mockResponsesCreate.mockResolvedValue({ + output: [{ type: "message", content: [{ type: "output_text", text: "done" }] }], + }) + + const result = await handler.completePrompt("Test prompt") + + expect(result).toBe("done") + expect(mockResponsesCreate).toHaveBeenCalledWith( + expectRequestObjectContaining({ model: openAiNativeDefaultModelId }), + expect.any(Object), + ) + }) + + it("keeps the deployment-name flow working when the selected model is not in the model list", async () => { + const handler = new OpenAiNativeHandler({ + apiModelId: "not-a-real-openai-model", + openAiNativeApiKey: "test-api-key", + openAiNativeDeploymentName: "my-deployment", + }) + mockResponsesCreate.mockResolvedValue({ + output: [{ type: "message", content: [{ type: "output_text", text: "done" }] }], + }) + + const result = await handler.completePrompt("Test prompt") + + expect(result).toBe("done") + expect(mockResponsesCreate).toHaveBeenCalledWith( + expectRequestObjectContaining({ model: "my-deployment" }), + expect.any(Object), + ) + }) +}) diff --git a/src/api/providers/anthropic-vertex.ts b/src/api/providers/anthropic-vertex.ts index d58f2bf42a..d649e3290e 100644 --- a/src/api/providers/anthropic-vertex.ts +++ b/src/api/providers/anthropic-vertex.ts @@ -26,6 +26,7 @@ import { import { BaseProvider } from "./base-provider" import { bridgeExternalAbortSignal, hasUsableTimeout, toSdkTimeoutMs } from "./utils/abort-signal" +import { assertModelResolved } from "./utils/model-resolution" import { NOT_PROVIDED } from "./constants" import { parseVertexJsonCredentials } from "./utils/vertex-credentials" import type { SingleCompletionHandler, ApiHandlerCreateMessageMetadata, CompletePromptOptions } from "../index" @@ -77,6 +78,7 @@ export class AnthropicVertexHandler extends BaseProvider implements SingleComple metadata?: ApiHandlerCreateMessageMetadata, ): ApiStream { const { id, info, temperature, maxTokens, reasoning: thinking, betas } = this.getModel() + this.validateModelResolution() const { supportsPromptCache } = info @@ -258,6 +260,15 @@ export class AnthropicVertexHandler extends BaseProvider implements SingleComple } } + /** + * Stops the request when an explicitly selected model ID is not in the + * Vertex model list. A missing selection still resolves the default model. + */ + private validateModelResolution(): void { + const requestedModelId = this.options.apiModelId + assertModelResolved("Anthropic Vertex", requestedModelId, !requestedModelId || requestedModelId in vertexModels) + } + getModel() { const modelId = this.options.apiModelId const id = modelId && modelId in vertexModels ? (modelId as VertexModelId) : vertexDefaultModelId @@ -324,6 +335,7 @@ export class AnthropicVertexHandler extends BaseProvider implements SingleComple } async completePrompt(prompt: string, options?: CompletePromptOptions) { + this.validateModelResolution() try { const { id, diff --git a/src/api/providers/bedrock.ts b/src/api/providers/bedrock.ts index be74f07693..7e9fcb28fd 100644 --- a/src/api/providers/bedrock.ts +++ b/src/api/providers/bedrock.ts @@ -59,6 +59,7 @@ import { getSystemProxyUrl } from "../../utils/networkProxy" import type { SingleCompletionHandler, ApiHandlerCreateMessageMetadata, CompletePromptOptions } from "../index" import { mergeAbortSignalAndTimeout } from "./utils/abort-signal" import { OutputTokenLimitError } from "./utils/output-token-limit-error" +import { assertModelResolved } from "./utils/model-resolution" /************************************************************************************ * @@ -434,6 +435,7 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH }, ): ApiStream { const modelConfig = this.getModel() + this.validateModelResolution() this.validateInferenceProfile(modelConfig.ergoRoute) const usePromptCache = Boolean( (this.options.awsUsePromptCache ?? true) && this.supportsAwsPromptCache(modelConfig), @@ -903,8 +905,39 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH } } + /** + * Stops the request when an explicitly selected model ID cannot be resolved + * in the Bedrock registry. A missing selection still resolves the provider + * default, and a non-foundation-model ARN passes through as the request ID, + * so registry state only affects its metadata. + */ + private validateModelResolution(): void { + if (this.options.awsCustomArn) { + if (this.arnInfo.modelType !== "foundation-model") { + // The ARN itself is the request ID; keep the passthrough. + return + } + // A foundation-model ARN selects the model it names, like the dropdown. + const arnModelId = this.arnInfo.modelId as string + assertModelResolved( + this.providerName, + this.options.awsCustomArn, + this.parseBaseModelId(arnModelId) in bedrockModels, + ) + return + } + + const requestedModelId = this.options.apiModelId + assertModelResolved( + this.providerName, + requestedModelId, + !requestedModelId || this.parseBaseModelId(requestedModelId) in bedrockModels, + ) + } + async completePrompt(prompt: string, options?: CompletePromptOptions): Promise { const modelConfig = this.getModel() + this.validateModelResolution() this.validateInferenceProfile(modelConfig.ergoRoute) try { const inferenceConfig: BedrockInferenceConfig = { @@ -1225,7 +1258,13 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH const baseModelId = this.parseBaseModelId(modelId) as BedrockModelId let model - if (baseModelId in bedrockModels) { + if (!modelId) { + // No model was selected: the provider default is the correct resolution. + model = { + id: bedrockDefaultModelId, + info: JSON.parse(JSON.stringify(bedrockModels[bedrockDefaultModelId])), + } + } else if (baseModelId in bedrockModels) { //Do a deep copy of the model info so that later in the code the model id and maxTokens can be set. // The bedrockModels array is a constant and updating the model ID from the returned invokedModelID value // in a prompt router response isn't possible on the constant. diff --git a/src/api/providers/minimax.ts b/src/api/providers/minimax.ts index 76a7355709..8b84eb200f 100644 --- a/src/api/providers/minimax.ts +++ b/src/api/providers/minimax.ts @@ -15,6 +15,7 @@ import { filterNonAnthropicBlocks } from "../transform/anthropic-filter" import { BaseProvider } from "./base-provider" import { bridgeExternalAbortSignal, hasUsableTimeout, toSdkTimeoutMs } from "./utils/abort-signal" +import { assertModelResolved } from "./utils/model-resolution" import type { SingleCompletionHandler, ApiHandlerCreateMessageMetadata, CompletePromptOptions } from "../index" import { calculateApiCostAnthropic } from "../../shared/cost" import { convertOpenAIToolsToAnthropic } from "../../core/prompts/tools/native-tools/converters" @@ -88,6 +89,7 @@ export class MiniMaxHandler extends BaseProvider implements SingleCompletionHand ): ApiStream { const cacheControl: CacheControlEphemeral = { type: "ephemeral" } const { id: modelId, info, maxTokens, temperature } = this.getModel() + this.validateModelResolution() this.lastThoughtSignature = undefined // Bridge the external abort signal from request metadata into a per-request @@ -310,6 +312,15 @@ export class MiniMaxHandler extends BaseProvider implements SingleCompletionHand }) } + /** + * Stops the request when an explicitly selected model ID is not in the + * MiniMax model list. A missing selection still resolves the default model. + */ + private validateModelResolution(): void { + const requestedModelId = this.options.apiModelId + assertModelResolved("MiniMax", requestedModelId, !requestedModelId || requestedModelId in minimaxModels) + } + getModel() { const modelId = this.options.apiModelId const id = modelId && modelId in minimaxModels ? (modelId as MinimaxModelId) : minimaxDefaultModelId @@ -331,6 +342,7 @@ export class MiniMaxHandler extends BaseProvider implements SingleCompletionHand } async completePrompt(prompt: string, options?: CompletePromptOptions) { + this.validateModelResolution() const { id: model, temperature } = this.getModel() // Build request options with abortSignal and/or timeout handling diff --git a/src/api/providers/openai-codex.ts b/src/api/providers/openai-codex.ts index 65a32f3928..0d229ca76b 100644 --- a/src/api/providers/openai-codex.ts +++ b/src/api/providers/openai-codex.ts @@ -36,6 +36,7 @@ import { rejectOnAbort, throwIfAborted, } from "./utils/abort-signal" +import { assertModelResolved } from "./utils/model-resolution" export type OpenAiCodexModel = ReturnType @@ -241,6 +242,7 @@ export class OpenAiCodexHandler extends BaseProvider implements SingleCompletion metadata?: ApiHandlerCreateMessageMetadata, ): ApiStream { const model = this.getModel() + this.validateModelResolution() yield* this.handleResponsesApiMessage(model, systemPrompt, messages, metadata, metadata?.abortSignal) } @@ -1386,6 +1388,19 @@ export class OpenAiCodexHandler extends BaseProvider implements SingleCompletion } } + /** + * Stops the request when an explicitly selected model ID is not in the + * Codex model list. A missing selection still resolves the default model. + */ + private validateModelResolution(): void { + const requestedModelId = this.options.apiModelId + assertModelResolved( + this.providerName, + requestedModelId, + !requestedModelId || requestedModelId in openAiCodexModels, + ) + } + override getModel() { const modelId = this.options.apiModelId @@ -1433,6 +1448,7 @@ export class OpenAiCodexHandler extends BaseProvider implements SingleCompletion * from having to be duplicated here. */ async completePrompt(prompt: string, options?: CompletePromptOptions): Promise { + this.validateModelResolution() // Fast-fail if the caller's stop signal already fired before we started: a cancelled // request must not spend the OAuth setup (token and account fetch) or an SDK request on // a completion that is already gone. diff --git a/src/api/providers/openai-native.ts b/src/api/providers/openai-native.ts index aacac3b1f4..67e314e858 100644 --- a/src/api/providers/openai-native.ts +++ b/src/api/providers/openai-native.ts @@ -35,6 +35,7 @@ import type { SingleCompletionHandler, ApiHandlerCreateMessageMetadata, Complete import { isMcpTool } from "../../utils/mcp-name" import { sanitizeOpenAiCallId } from "../../utils/tool-id" import { createAbortError, isRequestAborted, mergeAbortSignalAndTimeout } from "./utils/abort-signal" +import { assertModelResolved } from "./utils/model-resolution" import { createTimeoutError, getRequestTimeoutMs } from "./utils/request-timeout" import { getNumericHttpStatus, hasNumericHttpStatus } from "./utils/error-handler" @@ -222,6 +223,7 @@ export class OpenAiNativeHandler extends BaseProvider implements SingleCompletio metadata?: ApiHandlerCreateMessageMetadata, ): ApiStream { const model = this.getModel() + this.validateModelResolution() // Use Responses API for ALL models yield* this.handleResponsesApiMessage(model, systemPrompt, messages, metadata) @@ -1776,6 +1778,25 @@ export class OpenAiNativeHandler extends BaseProvider implements SingleCompletio return deploymentName ? deploymentName : model.id } + /** + * Stops the request when an explicitly selected model ID is not in the + * OpenAI model list. A missing selection still resolves the default model. + * A configured deployment name replaces the catalog ID on the wire, so the + * registry miss would not change the outbound model; that flow keeps + * working. + */ + private validateModelResolution(): void { + if (this.options.openAiNativeDeploymentName?.trim()) { + return + } + const requestedModelId = this.options.apiModelId + assertModelResolved( + this.providerName, + requestedModelId, + !requestedModelId || requestedModelId in openAiNativeModels, + ) + } + override getModel() { const modelId = this.options.apiModelId @@ -1841,6 +1862,7 @@ export class OpenAiNativeHandler extends BaseProvider implements SingleCompletio * @returns The completed text content */ async completePrompt(prompt: string, options?: CompletePromptOptions): Promise { + this.validateModelResolution() // Request-local abort signal: merges the external abort signal with an optional // timeout without touching this.abortController (owned by streaming requests). const requestSignal = diff --git a/src/api/providers/utils/model-resolution.ts b/src/api/providers/utils/model-resolution.ts new file mode 100644 index 0000000000..7b5948bee0 --- /dev/null +++ b/src/api/providers/utils/model-resolution.ts @@ -0,0 +1,34 @@ +/** + * Error thrown when a request is stopped because the user explicitly selected + * a model ID that the provider's model registry cannot resolve. The request is + * not sent: a silent fallback to the provider's default model would make later + * provider errors point at a model the user never selected. + */ +export class UnresolvedModelIdError extends Error { + constructor(providerName: string, requestedModelId: string) { + super( + `${providerName}: the selected model "${requestedModelId}" is not in the model registry. ` + + "No request was sent. Select a model from the provider's list, or update the model ID.", + ) + this.name = "UnresolvedModelIdError" + // Maintains proper prototype chain for instanceof checks + Object.setPrototypeOf(this, UnresolvedModelIdError.prototype) + } +} + +/** + * Stops a request when an explicitly selected model ID misses the provider's + * model registry. No selection keeps the provider default, and a registered + * selection resolves normally. Call it at request time, before anything is + * sent, so no request leaves the client with a substituted model. + */ +export function assertModelResolved( + providerName: string, + requestedModelId: string | undefined, + isRegistered: boolean, +): void { + if (!requestedModelId || isRegistered) { + return + } + throw new UnresolvedModelIdError(providerName, requestedModelId) +}