From 33cd297e57be8247d904482033b04b98ceeef3b4 Mon Sep 17 00:00:00 2001 From: Roomote Date: Wed, 25 Nov 2026 00:05:04 +0000 Subject: [PATCH] [Refactor] Remove no-explicit-any suppressions: batch 4 (api/providers, part 1) --- .../__tests__/anthropic-vertex.spec.ts | 83 +- .../__tests__/bedrock-custom-arn.spec.ts | 38 +- .../__tests__/bedrock-error-handling.spec.ts | 31 +- .../bedrock-inference-profiles.spec.ts | 62 +- .../__tests__/bedrock-native-tools.spec.ts | 100 +- .../__tests__/bedrock-reasoning.spec.ts | 38 +- src/api/providers/__tests__/bedrock.spec.ts | 106 +- src/api/providers/__tests__/deepseek.spec.ts | 35 +- .../__tests__/gemini-handler.spec.ts | 104 +- src/api/providers/__tests__/gemini.spec.ts | 113 +- src/api/providers/__tests__/mimo.spec.ts | 79 +- src/api/providers/__tests__/moonshot.spec.ts | 77 +- .../providers/__tests__/native-ollama.spec.ts | 95 +- .../openai-codex-native-tool-calls.spec.ts | 598 ++++---- .../providers/__tests__/openai-codex.spec.ts | 123 +- .../__tests__/openai-native-tools.spec.ts | 94 +- .../__tests__/openai-native-usage.spec.ts | 60 +- .../providers/__tests__/openai-native.spec.ts | 1357 ++++++++--------- .../providers/__tests__/openrouter.spec.ts | 79 +- src/api/providers/bedrock.ts | 149 +- src/api/providers/moonshot.ts | 16 +- src/api/providers/openai-codex.ts | 263 +++- src/api/providers/openai-native.ts | 45 +- .../utils/__tests__/error-handler.spec.ts | 122 +- .../utils/__tests__/image-generation.spec.ts | 34 +- src/api/providers/utils/error-handler.ts | 48 +- .../transform/__tests__/openai-format.spec.ts | 259 ++-- .../__tests__/cache-strategy.spec.ts | 88 +- src/api/transform/openai-format.ts | 2 +- src/api/transform/r1-format.ts | 12 +- src/eslint-suppressions.json | 142 +- 31 files changed, 2391 insertions(+), 2061 deletions(-) diff --git a/src/api/providers/__tests__/anthropic-vertex.spec.ts b/src/api/providers/__tests__/anthropic-vertex.spec.ts index 564ad3a3206..82a21d17331 100644 --- a/src/api/providers/__tests__/anthropic-vertex.spec.ts +++ b/src/api/providers/__tests__/anthropic-vertex.spec.ts @@ -1,5 +1,6 @@ // npx vitest run src/api/providers/__tests__/anthropic-vertex.spec.ts +import type { Mock } from "vitest" import { Anthropic } from "@anthropic-ai/sdk" import { AnthropicVertex } from "@anthropic-ai/vertex-sdk" import { GoogleAuth } from "google-auth-library" @@ -12,6 +13,14 @@ import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" import { makeCreateMessageMetadata } from "../../../test-utils/api" import type { ApiStreamChunk } from "../../../api/transform/stream" +/** + * Replaces the typed SDK messages.create with a bare vi.fn stub; routed through + * unknown because the stub provides only that one SDK member. + */ +function stubMessagesCreate(handler: AnthropicVertexHandler, stub: Mock): void { + handler["client"].messages.create = stub as unknown as AnthropicVertex["messages"]["create"] +} + vitest.mock("../utils/timeout-config", () => ({ getApiRequestTimeout: vitest.fn().mockReturnValue(300_000), })) @@ -70,8 +79,8 @@ describe("VertexHandler", () => { describe("constructor", () => { beforeEach(() => { - ;(AnthropicVertex as any).mockClear() - ;(GoogleAuth as any).mockClear() + vi.mocked(AnthropicVertex).mockClear() + vi.mocked(GoogleAuth).mockClear() }) it("should initialize with provided config for Claude", () => { @@ -197,7 +206,7 @@ describe("VertexHandler", () => { const asyncIterator = asyncStreamFrom(mockStream) const mockCreate = vitest.fn().mockResolvedValue(asyncIterator) - ;(handler["client"].messages as any).create = mockCreate + stubMessagesCreate(handler, mockCreate) const stream = handler.createMessage(systemPrompt, mockMessages) const chunks = await collectStream(stream) @@ -391,7 +400,7 @@ describe("VertexHandler", () => { const asyncIterator = asyncStreamFrom(mockStream) const mockCreate = vitest.fn().mockResolvedValue(asyncIterator) - ;(handler["client"].messages as any).create = mockCreate + stubMessagesCreate(handler, mockCreate) const stream = handler.createMessage(systemPrompt, mockMessages) const chunks = await collectStream(stream) @@ -420,7 +429,7 @@ describe("VertexHandler", () => { const mockError = new Error("Vertex API error") const mockCreate = vitest.fn().mockRejectedValue(mockError) - ;(handler["client"].messages as any).create = mockCreate + stubMessagesCreate(handler, mockCreate) const stream = handler.createMessage(systemPrompt, mockMessages) @@ -474,7 +483,7 @@ describe("VertexHandler", () => { const asyncIterator = asyncStreamFrom(mockStream) const mockCreate = vitest.fn().mockResolvedValue(asyncIterator) - ;(handler["client"].messages as any).create = mockCreate + stubMessagesCreate(handler, mockCreate) const stream = handler.createMessage(systemPrompt, [ { @@ -623,7 +632,7 @@ describe("VertexHandler", () => { const asyncIterator = asyncStreamFrom(mockStream) const mockCreate = vitest.fn().mockResolvedValue(asyncIterator) - ;(handler["client"].messages as any).create = mockCreate + stubMessagesCreate(handler, mockCreate) const stream = handler.createMessage(systemPrompt, mockMessages) const chunks = await collectStream(stream) @@ -692,7 +701,7 @@ describe("VertexHandler", () => { const asyncIterator = asyncStreamFrom(mockStream) const mockCreate = vitest.fn().mockResolvedValue(asyncIterator) - ;(handler["client"].messages as any).create = mockCreate + stubMessagesCreate(handler, mockCreate) const stream = handler.createMessage(systemPrompt, mockMessages) const chunks = await collectStream(stream) @@ -739,7 +748,7 @@ describe("VertexHandler", () => { const asyncIterator = asyncStreamFrom(mockStream) const mockCreate = vitest.fn().mockResolvedValue(asyncIterator) - ;(handler["client"].messages as any).create = mockCreate + stubMessagesCreate(handler, mockCreate) const stream = handler.createMessage(systemPrompt, mockMessages) const chunks = await collectStream(stream) @@ -787,7 +796,7 @@ describe("VertexHandler", () => { }, ]), ) - ;(handler["client"].messages as any).create = mockCreate + stubMessagesCreate(handler, mockCreate) // Messages with internal reasoning blocks (from stored conversation history) const messagesWithReasoning: Anthropic.Messages.MessageParam[] = [ @@ -799,7 +808,9 @@ describe("VertexHandler", () => { role: "assistant", content: [ { - type: "reasoning" as any, + // Extension reasoning block filtered by the converter; routed through + // unknown to stay inside MessageParam. + type: "reasoning" as unknown as "text", text: "This is internal reasoning that should be filtered", }, { @@ -818,7 +829,7 @@ describe("VertexHandler", () => { await collectStream(stream) // Verify the API was called with filtered messages (no reasoning blocks) - const calledMessages = mockCreate.mock.calls[0][0].messages + const calledMessages: Anthropic.MessageParam[] = mockCreate.mock.calls[0][0].messages expect(calledMessages).toHaveLength(3) // Check user message 1 @@ -827,12 +838,12 @@ describe("VertexHandler", () => { }) // Check assistant message - should have reasoning block filtered out - const assistantMessage = calledMessages.find((m: any) => m.role === "assistant") + const assistantMessage = calledMessages.find((m) => m.role === "assistant") expect(assistantMessage).toBeDefined() - expect(assistantMessage.content).toEqual([{ type: "text", text: "This is the response" }]) + expect(assistantMessage!.content).toEqual([{ type: "text", text: "This is the response" }]) // Verify reasoning blocks were NOT sent to the API - expect(assistantMessage.content).not.toContainEqual(expect.objectContaining({ type: "reasoning" })) + expect(assistantMessage!.content).not.toContainEqual(expect.objectContaining({ type: "reasoning" })) }) it("should filter empty messages after removing all reasoning blocks", async () => { @@ -855,7 +866,7 @@ describe("VertexHandler", () => { }, ]), ) - ;(handler["client"].messages as any).create = mockCreate + stubMessagesCreate(handler, mockCreate) // Message with only reasoning content (should be completely filtered) const messagesWithOnlyReasoning: Anthropic.Messages.MessageParam[] = [ @@ -867,7 +878,9 @@ describe("VertexHandler", () => { role: "assistant", content: [ { - type: "reasoning" as any, + // Extension reasoning block filtered by the converter; routed through + // unknown to stay inside MessageParam. + type: "reasoning" as unknown as "text", text: "Only reasoning, no actual text", }, ], @@ -882,9 +895,9 @@ describe("VertexHandler", () => { await collectStream(stream) // Verify empty message was filtered out - const calledMessages = mockCreate.mock.calls[0][0].messages + const calledMessages: Anthropic.MessageParam[] = mockCreate.mock.calls[0][0].messages expect(calledMessages).toHaveLength(2) // Only the two user messages - expect(calledMessages.every((m: any) => m.role === "user")).toBe(true) + expect(calledMessages.every((m) => m.role === "user")).toBe(true) }) it("should reject with AbortError when createMessage is called with an already-aborted signal", async () => { @@ -1117,7 +1130,7 @@ describe("VertexHandler", () => { const mockError = new Error("Vertex API error") const mockCreate = vitest.fn().mockRejectedValue(mockError) - ;(handler["client"].messages as any).create = mockCreate + stubMessagesCreate(handler, mockCreate) await expect(handler.completePrompt("Test prompt")).rejects.toThrow( "Vertex completion error: Vertex API error", @@ -1134,7 +1147,7 @@ describe("VertexHandler", () => { const mockCreate = vitest.fn().mockResolvedValue({ content: [{ type: "image" }], }) - ;(handler["client"].messages as any).create = mockCreate + stubMessagesCreate(handler, mockCreate) const result = await handler.completePrompt("Test prompt") expect(result).toBe("") @@ -1150,7 +1163,7 @@ describe("VertexHandler", () => { const mockCreate = vitest.fn().mockResolvedValue({ content: [{ type: "text", text: "" }], }) - ;(handler["client"].messages as any).create = mockCreate + stubMessagesCreate(handler, mockCreate) const result = await handler.completePrompt("Test prompt") expect(result).toBe("") @@ -1264,7 +1277,7 @@ describe("VertexHandler", () => { const mockCreate = vitest.fn().mockResolvedValue({ content: [], }) - ;(handler["client"].messages as any).create = mockCreate + stubMessagesCreate(handler, mockCreate) const result = await handler.completePrompt("Test prompt") expect(result).toBe("") @@ -1283,7 +1296,7 @@ describe("VertexHandler", () => { { type: "text", text: "visible response" }, ], }) - ;(handler["client"].messages as any).create = mockCreate + stubMessagesCreate(handler, mockCreate) const result = await handler.completePrompt("Test prompt") expect(result).toBe("visible response") @@ -1599,7 +1612,7 @@ describe("VertexHandler", () => { const asyncIterator = asyncStreamFrom(mockStream) const mockCreate = vitest.fn().mockResolvedValue(asyncIterator) - ;(handler["client"].messages as any).create = mockCreate + stubMessagesCreate(handler, mockCreate) const stream = handler.createMessage(systemPrompt, mockMessages) @@ -1637,7 +1650,7 @@ describe("VertexHandler", () => { const asyncIterator = asyncStreamFrom(mockStream) const mockCreate = vitest.fn().mockResolvedValue(asyncIterator) - ;(handler["client"].messages as any).create = mockCreate + stubMessagesCreate(handler, mockCreate) const stream = handler.createMessage(systemPrompt, mockMessages) @@ -1721,7 +1734,7 @@ describe("VertexHandler", () => { { type: "message_start", message: { usage: { input_tokens: 10, output_tokens: 5 } } }, ]) }) - ;(thinkingHandler["client"].messages as any).create = mockCreate + stubMessagesCreate(thinkingHandler, mockCreate) await thinkingHandler .createMessage("You are a helpful assistant", [{ role: "user", content: "Hello" }]) @@ -1751,7 +1764,7 @@ describe("VertexHandler", () => { { type: "message_start", message: { usage: { input_tokens: 10, output_tokens: 5 } } }, ]), ) - ;(opus48Handler["client"].messages as any).create = mockCreate + stubMessagesCreate(opus48Handler, mockCreate) await opus48Handler .createMessage("You are a helpful assistant", [{ role: "user", content: "Hello" }]) @@ -1815,7 +1828,7 @@ describe("VertexHandler", () => { { type: "message_start", message: { usage: { input_tokens: 10, output_tokens: 5 } } }, ]), ) - ;(fableHandler["client"].messages as any).create = mockCreate + stubMessagesCreate(fableHandler, mockCreate) await fableHandler.createMessage("You are a helpful assistant", [{ role: "user", content: "Hello" }]).next() @@ -1846,7 +1859,7 @@ describe("VertexHandler", () => { { type: "message_start", message: { usage: { input_tokens: 10, output_tokens: 5 } } }, ]), ) - ;(sonnetHandler["client"].messages as any).create = mockCreate + stubMessagesCreate(sonnetHandler, mockCreate) await sonnetHandler .createMessage("You are a helpful assistant", [{ role: "user", content: "Hello" }]) @@ -1915,7 +1928,7 @@ describe("VertexHandler", () => { { type: "message_start", message: { usage: { input_tokens: 10, output_tokens: 5 } } }, ]), ) - ;(opusHandler["client"].messages as any).create = mockCreate + stubMessagesCreate(opusHandler, mockCreate) await opusHandler.createMessage("You are a helpful assistant", [{ role: "user", content: "Hello" }]).next() @@ -2216,7 +2229,7 @@ describe("VertexHandler", () => { const asyncIterator = asyncStreamFrom(mockStream) const mockCreate = vitest.fn().mockResolvedValue(asyncIterator) - ;(handler["client"].messages as any).create = mockCreate + stubMessagesCreate(handler, mockCreate) const stream = handler.createMessage(systemPrompt, messages, { taskId: "test-task", @@ -2268,7 +2281,7 @@ describe("VertexHandler", () => { const asyncIterator = asyncStreamFrom(mockStream) const mockCreate = vitest.fn().mockResolvedValue(asyncIterator) - ;(handler["client"].messages as any).create = mockCreate + stubMessagesCreate(handler, mockCreate) const stream = handler.createMessage(systemPrompt, messages, { taskId: "test-task", @@ -2322,7 +2335,7 @@ describe("VertexHandler", () => { const asyncIterator = asyncStreamFrom(mockStream) const mockCreate = vitest.fn().mockResolvedValue(asyncIterator) - ;(handler["client"].messages as any).create = mockCreate + stubMessagesCreate(handler, mockCreate) const stream = handler.createMessage(systemPrompt, messages, { taskId: "test-task", @@ -2394,7 +2407,7 @@ describe("VertexHandler", () => { const asyncIterator = asyncStreamFrom(mockStream) const mockCreate = vitest.fn().mockResolvedValue(asyncIterator) - ;(handler["client"].messages as any).create = mockCreate + stubMessagesCreate(handler, mockCreate) const stream = handler.createMessage(systemPrompt, messages, { taskId: "test-task", diff --git a/src/api/providers/__tests__/bedrock-custom-arn.spec.ts b/src/api/providers/__tests__/bedrock-custom-arn.spec.ts index dfad54c1fd0..91516509d0a 100644 --- a/src/api/providers/__tests__/bedrock-custom-arn.spec.ts +++ b/src/api/providers/__tests__/bedrock-custom-arn.spec.ts @@ -24,24 +24,22 @@ vitest.mock("../../../utils/logging", () => ({ // Mock AWS SDK vitest.mock("@aws-sdk/client-bedrock-runtime", () => { + const mockSend = vitest.fn().mockImplementation(async function () { + return { + output: new TextEncoder().encode(JSON.stringify({ content: "Test response" })), + } + }) const mockModule = { - lastCommandInput: null as Record | null, - mockSend: vitest.fn().mockImplementation(async function () { - return { - output: new TextEncoder().encode(JSON.stringify({ content: "Test response" })), - } - }), - mockConverseCommand: vitest.fn(function (input) { - mockModule.lastCommandInput = input + mockSend, + mockConverseCommand: vitest.fn(function (input: Record) { return { input } }), MockBedrockRuntimeClient: class { - public config: any - public send: any + public config: { region?: string } + public send = mockSend constructor(config: { region?: string }) { this.config = config - this.send = mockModule.mockSend } }, } @@ -73,7 +71,7 @@ describe("Bedrock ARN Handling", () => { const arn = "arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3-sonnet-20240229-v1:0" // Access the private method using type casting - const result = (handler as any).parseArn(arn, "us-east-1") + const result = handler["parseArn"](arn, "us-east-1") // Verify the result contains the expected values expect(result.isValid).toBe(true) @@ -89,7 +87,7 @@ describe("Bedrock ARN Handling", () => { const arn = "arn:aws:bedrock:us-west-2:123456789012:inference-profile/custom-profile" // Access the private method using type casting - const result = (handler as any).parseArn(arn, "us-west-2") + const result = handler["parseArn"](arn, "us-west-2") // Verify the result contains the expected values expect(result.isValid).toBe(true) @@ -104,7 +102,7 @@ describe("Bedrock ARN Handling", () => { const arn = "arn:aws:bedrock:eu-west-1:123456789012:prompt-router/custom-router-name" // Access the private method using type casting - const result = (handler as any).parseArn(arn, "eu-west-1") + const result = handler["parseArn"](arn, "eu-west-1") // Verify the result contains the expected values expect(result.isValid).toBe(true) @@ -120,7 +118,7 @@ describe("Bedrock ARN Handling", () => { "arn:aws:bedrock:us-east-1:123456789012:foundation-model/us.anthropic.claude-3-sonnet-20240229-v1:0" // Access the private method using type casting - const result = (handler as any).parseArn(arn, "us-east-1") + const result = handler["parseArn"](arn, "us-east-1") // Verify crossRegionInference is true expect(result.crossRegionInference).toBe(true) @@ -138,7 +136,7 @@ describe("Bedrock ARN Handling", () => { "arn:aws:bedrock:ap-east-1:123456789012:foundation-model/apac.anthropic.claude-3-sonnet-20240229-v1:0" // Access the private method using type casting - const result = (handler as any).parseArn(arn, "us-east-1") + const result = handler["parseArn"](arn, "us-east-1") // Verify crossRegionInference is true expect(result.crossRegionInference).toBe(true) @@ -151,7 +149,7 @@ describe("Bedrock ARN Handling", () => { const arn = "arn:aws:bedrock:eu-west-1::foundation-model/anthropic.claude-3-sonnet-20240229-v1:0" // Access the private method using type casting with mismatched region - const result = (handler as any).parseArn(arn, "us-east-1") + const result = handler["parseArn"](arn, "us-east-1") // Verify the result contains the expected values including error message expect(result.isValid).toBe(true) @@ -168,7 +166,7 @@ describe("Bedrock ARN Handling", () => { const arn = "arn:aws:bedrock:us-east-1:123456789012:some-other-resource" // Access the private method using type casting - const result = (handler as any).parseArn(arn, "us-east-1") + const result = handler["parseArn"](arn, "us-east-1") // Verify the result indicates invalid ARN expect(result.isValid).toBe(false) @@ -184,7 +182,7 @@ describe("Bedrock ARN Handling", () => { const arn = "invalid-arn-format" // Access the private method using type casting - const result = (handler as any).parseArn(arn) + const result = handler["parseArn"](arn) // Verify the result indicates invalid ARN expect(result.isValid).toBe(false) @@ -225,7 +223,7 @@ describe("Bedrock ARN Handling", () => { }) // Verify the client was created with the ARN region, not the provided region - expect((handler as any).client.config.region).toBe("eu-west-1") + expect(handler["client"].config.region).toBe("eu-west-1") }) it("should log region mismatch warning when ARN region differs from provided region", () => { diff --git a/src/api/providers/__tests__/bedrock-error-handling.spec.ts b/src/api/providers/__tests__/bedrock-error-handling.spec.ts index 4420947e509..71a24f8f950 100644 --- a/src/api/providers/__tests__/bedrock-error-handling.spec.ts +++ b/src/api/providers/__tests__/bedrock-error-handling.spec.ts @@ -32,10 +32,17 @@ vi.mock("@aws-sdk/client-bedrock-runtime", () => ({ })) import { AwsBedrockHandler } from "../bedrock" +import type { ApiStreamChunk } from "../../transform/stream" import { Anthropic } from "@anthropic-ai/sdk" import { collectStream } from "../../../test-utils/stream" import { clearAllMocks } from "../../../test-utils/reset" +/** Shape of the AWS-style errors the handler rethrows. */ +type AwsErrorShape = Error & { + status?: number + $metadata?: { requestId?: string } +} + describe("AwsBedrockHandler Error Handling", () => { let handler: AwsBedrockHandler @@ -60,15 +67,15 @@ describe("AwsBedrockHandler Error Handling", () => { requestId?: string extendedRequestId?: string cfId?: string - [key: string]: any // Allow additional properties + [key: string]: unknown } }): Error => { - const error = new Error(options.message || "Test error") as any - if (options.name) error.name = options.name - if (options.status) error.status = options.status - if (options.__type) error.__type = options.__type - if (options.$metadata) error.$metadata = options.$metadata - return error + return Object.assign(new Error(options.message || "Test error"), { + ...(options.name ? { name: options.name } : {}), + ...(options.status ? { status: options.status } : {}), + ...(options.__type ? { __type: options.__type } : {}), + ...(options.$metadata ? { $metadata: options.$metadata } : {}), + }) } describe("Throttling Error Detection", () => { @@ -323,7 +330,7 @@ describe("AwsBedrockHandler Error Handling", () => { const generator = handler.createMessage("system", [{ role: "user", content: "test" }]) - const chunks: any[] = [] + const chunks: ApiStreamChunk[] = [] try { for await (const chunk of generator) { chunks.push(chunk) @@ -411,8 +418,8 @@ describe("AwsBedrockHandler Error Handling", () => { // Should contain the verbose message template expect(error.message).toContain("Request was throttled or rate limited") // Should preserve original error properties - expect((error as any).status).toBe(429) - expect((error as any).$metadata.requestId).toBe("test-request-id-12345") + expect((error as AwsErrorShape).status).toBe(429) + expect((error as AwsErrorShape).$metadata?.requestId).toBe("test-request-id-12345") } }) @@ -448,7 +455,7 @@ describe("AwsBedrockHandler Error Handling", () => { expect(error.message).toContain("Too many tokens") // Should preserve original error properties expect(error.name).toBe("ValidationException") - expect((error as any).$metadata.requestId).toBe("token-error-id-67890") + expect((error as AwsErrorShape).$metadata?.requestId).toBe("token-error-id-67890") } }) }) @@ -497,7 +504,7 @@ describe("AwsBedrockHandler Error Handling", () => { // Should be treated as throttling due to 429 status taking priority expect(error.message).toContain("throttled or rate limited") // Should still preserve metadata - expect((error as any).$metadata?.requestId).toBe("mixed-error-id") + expect((error as AwsErrorShape).$metadata?.requestId).toBe("mixed-error-id") } }) diff --git a/src/api/providers/__tests__/bedrock-inference-profiles.spec.ts b/src/api/providers/__tests__/bedrock-inference-profiles.spec.ts index 4704cbc7d80..b700885cae7 100644 --- a/src/api/providers/__tests__/bedrock-inference-profiles.spec.ts +++ b/src/api/providers/__tests__/bedrock-inference-profiles.spec.ts @@ -60,68 +60,60 @@ describe("Amazon Bedrock Inference Profiles", () => { describe("getPrefixForRegion function", () => { it("should return correct prefix for US government regions", () => { - const handler = createHandler() - expect((handler as any).constructor.getPrefixForRegion("us-gov-east-1")).toBe("ug.") - expect((handler as any).constructor.getPrefixForRegion("us-gov-west-1")).toBe("ug.") + expect(AwsBedrockHandler["getPrefixForRegion"]("us-gov-east-1")).toBe("ug.") + expect(AwsBedrockHandler["getPrefixForRegion"]("us-gov-west-1")).toBe("ug.") }) it("should return correct prefix for US commercial regions", () => { - const handler = createHandler() - expect((handler as any).constructor.getPrefixForRegion("us-east-1")).toBe("us.") - expect((handler as any).constructor.getPrefixForRegion("us-west-1")).toBe("us.") - expect((handler as any).constructor.getPrefixForRegion("us-west-2")).toBe("us.") + expect(AwsBedrockHandler["getPrefixForRegion"]("us-east-1")).toBe("us.") + expect(AwsBedrockHandler["getPrefixForRegion"]("us-west-1")).toBe("us.") + expect(AwsBedrockHandler["getPrefixForRegion"]("us-west-2")).toBe("us.") }) it("should return correct prefix for European regions", () => { - const handler = createHandler() - expect((handler as any).constructor.getPrefixForRegion("eu-west-1")).toBe("eu.") - expect((handler as any).constructor.getPrefixForRegion("eu-central-1")).toBe("eu.") - expect((handler as any).constructor.getPrefixForRegion("eu-north-1")).toBe("eu.") - expect((handler as any).constructor.getPrefixForRegion("eu-south-1")).toBe("eu.") + expect(AwsBedrockHandler["getPrefixForRegion"]("eu-west-1")).toBe("eu.") + expect(AwsBedrockHandler["getPrefixForRegion"]("eu-central-1")).toBe("eu.") + expect(AwsBedrockHandler["getPrefixForRegion"]("eu-north-1")).toBe("eu.") + expect(AwsBedrockHandler["getPrefixForRegion"]("eu-south-1")).toBe("eu.") }) it("should return correct prefix for Asia Pacific regions", () => { - const handler = createHandler() // Australia regions (Sydney and Melbourne) get au. prefix - expect((handler as any).constructor.getPrefixForRegion("ap-southeast-2")).toBe("au.") - expect((handler as any).constructor.getPrefixForRegion("ap-southeast-4")).toBe("au.") + expect(AwsBedrockHandler["getPrefixForRegion"]("ap-southeast-2")).toBe("au.") + expect(AwsBedrockHandler["getPrefixForRegion"]("ap-southeast-4")).toBe("au.") // Japan regions (Tokyo and Osaka) get jp. prefix - expect((handler as any).constructor.getPrefixForRegion("ap-northeast-1")).toBe("jp.") - expect((handler as any).constructor.getPrefixForRegion("ap-northeast-3")).toBe("jp.") + expect(AwsBedrockHandler["getPrefixForRegion"]("ap-northeast-1")).toBe("jp.") + expect(AwsBedrockHandler["getPrefixForRegion"]("ap-northeast-3")).toBe("jp.") // Other APAC regions get apac. prefix - expect((handler as any).constructor.getPrefixForRegion("ap-southeast-1")).toBe("apac.") - expect((handler as any).constructor.getPrefixForRegion("ap-south-1")).toBe("apac.") - expect((handler as any).constructor.getPrefixForRegion("ap-east-1")).toBe("apac.") + expect(AwsBedrockHandler["getPrefixForRegion"]("ap-southeast-1")).toBe("apac.") + expect(AwsBedrockHandler["getPrefixForRegion"]("ap-south-1")).toBe("apac.") + expect(AwsBedrockHandler["getPrefixForRegion"]("ap-east-1")).toBe("apac.") }) it("should return correct prefix for Canada regions", () => { - const handler = createHandler() - expect((handler as any).constructor.getPrefixForRegion("ca-central-1")).toBe("ca.") - expect((handler as any).constructor.getPrefixForRegion("ca-west-1")).toBe("ca.") + expect(AwsBedrockHandler["getPrefixForRegion"]("ca-central-1")).toBe("ca.") + expect(AwsBedrockHandler["getPrefixForRegion"]("ca-west-1")).toBe("ca.") }) it("should return correct prefix for South America regions", () => { - const handler = createHandler() - expect((handler as any).constructor.getPrefixForRegion("sa-east-1")).toBe("sa.") + expect(AwsBedrockHandler["getPrefixForRegion"]("sa-east-1")).toBe("sa.") }) it("should return undefined for unsupported regions", () => { - const handler = createHandler() - expect((handler as any).constructor.getPrefixForRegion("af-south-1")).toBeUndefined() - expect((handler as any).constructor.getPrefixForRegion("me-south-1")).toBeUndefined() - expect((handler as any).constructor.getPrefixForRegion("cn-north-1")).toBeUndefined() - expect((handler as any).constructor.getPrefixForRegion("invalid-region")).toBeUndefined() + expect(AwsBedrockHandler["getPrefixForRegion"]("af-south-1")).toBeUndefined() + expect(AwsBedrockHandler["getPrefixForRegion"]("me-south-1")).toBeUndefined() + expect(AwsBedrockHandler["getPrefixForRegion"]("cn-north-1")).toBeUndefined() + expect(AwsBedrockHandler["getPrefixForRegion"]("invalid-region")).toBeUndefined() }) it("should prioritize longer patterns over shorter ones", () => { - const handler = createHandler() // us-gov- should be matched before us- - expect((handler as any).constructor.getPrefixForRegion("us-gov-east-1")).toBe("ug.") - expect((handler as any).constructor.getPrefixForRegion("us-gov-west-1")).toBe("ug.") + expect(AwsBedrockHandler["getPrefixForRegion"]("us-gov-east-1")).toBe("ug.") + expect(AwsBedrockHandler["getPrefixForRegion"]("us-gov-west-1")).toBe("ug.") // Regular us- regions should still work - expect((handler as any).constructor.getPrefixForRegion("us-east-1")).toBe("us.") - expect((handler as any).constructor.getPrefixForRegion("us-west-2")).toBe("us.") + expect(AwsBedrockHandler["getPrefixForRegion"]("us-east-1")).toBe("us.") + expect(AwsBedrockHandler["getPrefixForRegion"]("us-west-2")).toBe("us.") }) }) diff --git a/src/api/providers/__tests__/bedrock-native-tools.spec.ts b/src/api/providers/__tests__/bedrock-native-tools.spec.ts index 52a28c59fff..a9350774c6a 100644 --- a/src/api/providers/__tests__/bedrock-native-tools.spec.ts +++ b/src/api/providers/__tests__/bedrock-native-tools.spec.ts @@ -29,11 +29,35 @@ vi.mock("@aws-sdk/client-bedrock-runtime", () => { }) import { AwsBedrockHandler } from "../bedrock" +import type OpenAI from "openai" +import type { Tool } from "@aws-sdk/client-bedrock-runtime" +import type { ApiStreamChunk } from "../../transform/stream" import { ConverseStreamCommand } from "@aws-sdk/client-bedrock-runtime" import type { ApiHandlerCreateMessageMetadata } from "../../index" import { clearAllMocks } from "../../../test-utils/reset" +/** Reads additionalModelRequestFields as a record; the handler builds it as an object. */ +function additionalFieldsOf(commandArg: { additionalModelRequestFields?: unknown }): Record { + return (commandArg.additionalModelRequestFields ?? {}) as Record +} + +/** JSON-schema shape this suite asserts on for converted tool input specs. */ +interface ToolSchemaShape { + type?: string + description?: string + anyOf?: Array> + properties: Record + required?: string[] + additionalProperties?: boolean + [key: string]: unknown +} + +/** Extracts the JSON schema of a converted tool's input spec. */ +function toolSchema(tool: Tool): ToolSchemaShape { + return tool.toolSpec!.inputSchema!.json as ToolSchemaShape +} + const mockConverseStreamCommand = vi.mocked(ConverseStreamCommand) // Test tool definitions in OpenAI format @@ -92,26 +116,27 @@ describe("AwsBedrockHandler Native Tool Calling", () => { describe("convertToolsForBedrock", () => { it("should convert OpenAI tools to Bedrock format", () => { // Access private method - const convertToolsForBedrock = (handler as any).convertToolsForBedrock.bind(handler) + const convertToolsForBedrock = handler["convertToolsForBedrock"].bind(handler) const bedrockTools = convertToolsForBedrock(testTools) expect(bedrockTools).toHaveLength(2) // Check structure and key properties (normalizeToolSchema adds additionalProperties: false) - const tool = bedrockTools[0] - expect(tool.toolSpec.name).toBe("read_file") - expect(tool.toolSpec.description).toBe("Read a file from the filesystem") - expect(tool.toolSpec.inputSchema.json.type).toBe("object") - expect(tool.toolSpec.inputSchema.json.properties.path.type).toBe("string") - expect(tool.toolSpec.inputSchema.json.properties.path.description).toBe("The path to the file") - expect(tool.toolSpec.inputSchema.json.required).toEqual(["path"]) + const spec = bedrockTools[0]!.toolSpec! + expect(spec.name).toBe("read_file") + expect(spec.description).toBe("Read a file from the filesystem") + const schema = toolSchema(bedrockTools[0]!) + expect(schema.type).toBe("object") + expect(schema.properties!.path.type).toBe("string") + expect(schema.properties!.path.description).toBe("The path to the file") + expect(schema.required).toEqual(["path"]) // normalizeToolSchema adds additionalProperties: false by default - expect(tool.toolSpec.inputSchema.json.additionalProperties).toBe(false) + expect(schema.additionalProperties).toBe(false) }) it("should transform type arrays to anyOf for JSON Schema 2020-12 compliance", () => { - const convertToolsForBedrock = (handler as any).convertToolsForBedrock.bind(handler) + const convertToolsForBedrock = handler["convertToolsForBedrock"].bind(handler) // Tools with type: ["string", "null"] syntax (valid in draft-07 but not 2020-12) const toolsWithNullableTypes = [ @@ -163,13 +188,13 @@ describe("AwsBedrockHandler Native Tool Calling", () => { expect(bedrockTools).toHaveLength(2) // First tool: cwd should be transformed from type: ["string", "null"] to anyOf - const executeCommandSchema = bedrockTools[0].toolSpec.inputSchema.json as any + const executeCommandSchema = toolSchema(bedrockTools[0]!) expect(executeCommandSchema.properties.cwd.anyOf).toEqual([{ type: "string" }, { type: "null" }]) expect(executeCommandSchema.properties.cwd.type).toBeUndefined() expect(executeCommandSchema.properties.cwd.description).toBe("Working directory (optional)") // Second tool: nested nullable object should be transformed from type: ["object", "null"] to anyOf - const readFileSchema = bedrockTools[1].toolSpec.inputSchema.json as any + const readFileSchema = toolSchema(bedrockTools[1]!) const indentation = readFileSchema.properties.indentation expect(indentation.anyOf).toBeDefined() expect(indentation.type).toBeUndefined() @@ -179,11 +204,12 @@ describe("AwsBedrockHandler Native Tool Calling", () => { }) it("should filter non-function tools", () => { - const convertToolsForBedrock = (handler as any).convertToolsForBedrock.bind(handler) + const convertToolsForBedrock = handler["convertToolsForBedrock"].bind(handler) const mixedTools = [ ...testTools, - { type: "other" as any, something: {} }, // Should be filtered out + // Non-function tool double; routed through unknown to stay in ChatCompletionTool. + { type: "other", something: {} } as unknown as OpenAI.Chat.ChatCompletionTool, ] const bedrockTools = convertToolsForBedrock(mixedTools) @@ -194,7 +220,7 @@ describe("AwsBedrockHandler Native Tool Calling", () => { describe("convertToolChoiceForBedrock", () => { it("should convert 'auto' to Bedrock auto format", () => { - const convertToolChoiceForBedrock = (handler as any).convertToolChoiceForBedrock.bind(handler) + const convertToolChoiceForBedrock = handler["convertToolChoiceForBedrock"].bind(handler) const result = convertToolChoiceForBedrock("auto") @@ -202,7 +228,7 @@ describe("AwsBedrockHandler Native Tool Calling", () => { }) it("should convert 'required' to Bedrock any format", () => { - const convertToolChoiceForBedrock = (handler as any).convertToolChoiceForBedrock.bind(handler) + const convertToolChoiceForBedrock = handler["convertToolChoiceForBedrock"].bind(handler) const result = convertToolChoiceForBedrock("required") @@ -210,7 +236,7 @@ describe("AwsBedrockHandler Native Tool Calling", () => { }) it("should return undefined for 'none'", () => { - const convertToolChoiceForBedrock = (handler as any).convertToolChoiceForBedrock.bind(handler) + const convertToolChoiceForBedrock = handler["convertToolChoiceForBedrock"].bind(handler) const result = convertToolChoiceForBedrock("none") @@ -218,7 +244,7 @@ describe("AwsBedrockHandler Native Tool Calling", () => { }) it("should convert specific tool choice to Bedrock tool format", () => { - const convertToolChoiceForBedrock = (handler as any).convertToolChoiceForBedrock.bind(handler) + const convertToolChoiceForBedrock = handler["convertToolChoiceForBedrock"].bind(handler) const result = convertToolChoiceForBedrock({ type: "function", @@ -233,7 +259,7 @@ describe("AwsBedrockHandler Native Tool Calling", () => { }) it("should default to auto for undefined toolChoice", () => { - const convertToolChoiceForBedrock = (handler as any).convertToolChoiceForBedrock.bind(handler) + const convertToolChoiceForBedrock = handler["convertToolChoiceForBedrock"].bind(handler) const result = convertToolChoiceForBedrock(undefined) @@ -264,12 +290,12 @@ describe("AwsBedrockHandler Native Tool Calling", () => { await generator.next() expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] as any + const commandArg = mockConverseStreamCommand.mock.calls[0][0] expect(commandArg.toolConfig).toBeDefined() - expect(commandArg.toolConfig.tools).toHaveLength(2) - expect(commandArg.toolConfig.tools[0].toolSpec.name).toBe("read_file") - expect(commandArg.toolConfig.toolChoice).toEqual({ auto: {} }) + expect(commandArg.toolConfig!.tools).toHaveLength(2) + expect(commandArg.toolConfig!.tools![0].toolSpec!.name).toBe("read_file") + expect(commandArg.toolConfig!.toolChoice).toEqual({ auto: {} }) }) it("should always include toolConfig (tools are always present after PR #10841)", async () => { @@ -294,12 +320,12 @@ describe("AwsBedrockHandler Native Tool Calling", () => { await generator.next() expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] as any + const commandArg = mockConverseStreamCommand.mock.calls[0][0] // Tools are now always present expect(commandArg.toolConfig).toBeDefined() - expect(commandArg.toolConfig.tools).toBeDefined() - expect(commandArg.toolConfig.toolChoice).toEqual({ auto: {} }) + expect(commandArg.toolConfig!.tools).toBeDefined() + expect(commandArg.toolConfig!.toolChoice).toEqual({ auto: {} }) }) it("should include toolConfig with undefined toolChoice when tool_choice is none", async () => { @@ -325,11 +351,11 @@ describe("AwsBedrockHandler Native Tool Calling", () => { await generator.next() expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] as any + const commandArg = mockConverseStreamCommand.mock.calls[0][0] // toolConfig is still provided but toolChoice is undefined for "none" expect(commandArg.toolConfig).toBeDefined() - expect(commandArg.toolConfig.toolChoice).toBeUndefined() + expect(commandArg.toolConfig!.toolChoice).toBeUndefined() }) it("should include fine-grained tool streaming beta for Claude models with native tools", async () => { @@ -354,13 +380,11 @@ describe("AwsBedrockHandler Native Tool Calling", () => { await generator.next() expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] as any + const commandArg = mockConverseStreamCommand.mock.calls[0][0] // Should include the fine-grained tool streaming beta expect(commandArg.additionalModelRequestFields).toBeDefined() - expect(commandArg.additionalModelRequestFields.anthropic_beta).toContain( - "fine-grained-tool-streaming-2025-05-14", - ) + expect(additionalFieldsOf(commandArg).anthropic_beta).toContain("fine-grained-tool-streaming-2025-05-14") }) it("should always include fine-grained tool streaming beta for Claude models", async () => { @@ -385,13 +409,11 @@ describe("AwsBedrockHandler Native Tool Calling", () => { await generator.next() expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] as any + const commandArg = mockConverseStreamCommand.mock.calls[0][0] // Should always include anthropic_beta with fine-grained-tool-streaming for Claude models expect(commandArg.additionalModelRequestFields).toBeDefined() - expect(commandArg.additionalModelRequestFields.anthropic_beta).toContain( - "fine-grained-tool-streaming-2025-05-14", - ) + expect(additionalFieldsOf(commandArg).anthropic_beta).toContain("fine-grained-tool-streaming-2025-05-14") }) }) @@ -443,7 +465,7 @@ describe("AwsBedrockHandler Native Tool Calling", () => { { role: "user", content: "Read the file" }, ]) - const results: any[] = [] + const results: ApiStreamChunk[] = [] for await (const chunk of generator) { results.push(chunk) } @@ -508,7 +530,7 @@ describe("AwsBedrockHandler Native Tool Calling", () => { { role: "user", content: "Write a file" }, ]) - const results: any[] = [] + const results: ApiStreamChunk[] = [] for await (const chunk of generator) { results.push(chunk) } @@ -589,7 +611,7 @@ describe("AwsBedrockHandler Native Tool Calling", () => { { role: "user", content: "Read the example file" }, ]) - const results: any[] = [] + const results: ApiStreamChunk[] = [] for await (const chunk of generator) { results.push(chunk) } diff --git a/src/api/providers/__tests__/bedrock-reasoning.spec.ts b/src/api/providers/__tests__/bedrock-reasoning.spec.ts index e4f30a1d964..6a01c9421a4 100644 --- a/src/api/providers/__tests__/bedrock-reasoning.spec.ts +++ b/src/api/providers/__tests__/bedrock-reasoning.spec.ts @@ -11,8 +11,18 @@ import { providerIdentifiers } from "@roo-code/types/provider-identifiers" vi.mock("@aws-sdk/client-bedrock-runtime") vi.mock("../../../utils/logging") -// Store the command payload for verification -let capturedPayload: any = null +// Store the command payload for verification. The test reads the extension's +// reasoning fields off the Converse input; they are asserted via the structural shape. +interface CapturedBedrockPayload { + additionalModelRequestFields?: { + thinking?: unknown + anthropic_beta?: unknown + anthropic_version?: unknown + } + inferenceConfig?: unknown + [key: string]: unknown +} +let capturedPayload: CapturedBedrockPayload | null = null describe("AwsBedrockHandler - Extended Thinking", () => { let handler: AwsBedrockHandler @@ -96,8 +106,8 @@ describe("AwsBedrockHandler - Extended Thinking", () => { // Verify the command was called with the correct payload expect(mockSend).toHaveBeenCalledTimes(1) expect(capturedPayload).toBeDefined() - expect(capturedPayload.additionalModelRequestFields).toBeDefined() - expect(capturedPayload.additionalModelRequestFields.thinking).toEqual({ + expect(capturedPayload!.additionalModelRequestFields).toBeDefined() + expect(capturedPayload!.additionalModelRequestFields!.thinking).toEqual({ type: "enabled", budget_tokens: 4096, // Uses the full modelMaxThinkingTokens value }) @@ -109,7 +119,7 @@ describe("AwsBedrockHandler - Extended Thinking", () => { expect(reasoningChunks[1].text).toBe(" about this problem.") // Verify that topP is NOT present when thinking is enabled - expect(capturedPayload.inferenceConfig).not.toHaveProperty("topP") + expect(capturedPayload!.inferenceConfig).not.toHaveProperty("topP") }) it("should pass thinking parameters from metadata", async () => { @@ -145,14 +155,14 @@ describe("AwsBedrockHandler - Extended Thinking", () => { // Verify the thinking parameter was passed correctly expect(mockSend).toHaveBeenCalledTimes(1) expect(capturedPayload).toBeDefined() - expect(capturedPayload.additionalModelRequestFields).toBeDefined() - expect(capturedPayload.additionalModelRequestFields.thinking).toEqual({ + expect(capturedPayload!.additionalModelRequestFields).toBeDefined() + expect(capturedPayload!.additionalModelRequestFields!.thinking).toEqual({ type: "enabled", budget_tokens: 8192, }) // Verify that topP is NOT present when thinking is enabled via metadata - expect(capturedPayload.inferenceConfig).not.toHaveProperty("topP") + expect(capturedPayload!.inferenceConfig).not.toHaveProperty("topP") }) it("should log when extended thinking is enabled", async () => { @@ -224,11 +234,11 @@ describe("AwsBedrockHandler - Extended Thinking", () => { // Verify that topP is NOT present for any model (removed globally) expect(mockSend).toHaveBeenCalledTimes(1) expect(capturedPayload).toBeDefined() - expect(capturedPayload.inferenceConfig).not.toHaveProperty("topP") + expect(capturedPayload!.inferenceConfig).not.toHaveProperty("topP") // Verify that additionalModelRequestFields contains fine-grained-tool-streaming for Claude models - expect(capturedPayload.additionalModelRequestFields).toBeDefined() - expect(capturedPayload.additionalModelRequestFields.anthropic_beta).toContain( + expect(capturedPayload!.additionalModelRequestFields).toBeDefined() + expect(capturedPayload!.additionalModelRequestFields!.anthropic_beta).toContain( "fine-grained-tool-streaming-2025-05-14", ) }) @@ -271,14 +281,14 @@ describe("AwsBedrockHandler - Extended Thinking", () => { // Verify thinking was enabled via settings expect(mockSend).toHaveBeenCalledTimes(1) expect(capturedPayload).toBeDefined() - expect(capturedPayload.additionalModelRequestFields).toBeDefined() - expect(capturedPayload.additionalModelRequestFields.thinking).toEqual({ + expect(capturedPayload!.additionalModelRequestFields).toBeDefined() + expect(capturedPayload!.additionalModelRequestFields!.thinking).toEqual({ type: "enabled", budget_tokens: 4096, }) // Verify that topP is NOT present when thinking is enabled via settings - expect(capturedPayload.inferenceConfig).not.toHaveProperty("topP") + expect(capturedPayload!.inferenceConfig).not.toHaveProperty("topP") // Verify reasoning chunks were yielded const reasoningChunks = chunks.filter((c) => c.type === "reasoning") diff --git a/src/api/providers/__tests__/bedrock.spec.ts b/src/api/providers/__tests__/bedrock.spec.ts index b5d241537c0..95682e5d41b 100644 --- a/src/api/providers/__tests__/bedrock.spec.ts +++ b/src/api/providers/__tests__/bedrock.spec.ts @@ -54,6 +54,7 @@ vi.mock("@aws-sdk/client-bedrock-runtime", () => { import { AwsBedrockHandler } from "../bedrock" import { ConverseStreamCommand, BedrockRuntimeClient, ConverseCommand } from "@aws-sdk/client-bedrock-runtime" +import type { ConverseStreamCommandInput } from "@aws-sdk/client-bedrock-runtime" import { BEDROCK_1M_CONTEXT_MODEL_IDS, BEDROCK_SERVICE_TIER_MODEL_IDS, @@ -86,6 +87,15 @@ const mockNodeHttpHandler = vi.mocked(NodeHttpHandler) const mockHttpProxyAgent = vi.mocked(HttpProxyAgent) const mockHttpsProxyAgent = vi.mocked(HttpsProxyAgent) +/** + * The handler builds additionalModelRequestFields as a plain object; the SDK types + * it as the Smithy Document union, so the object shape is asserted at extraction. + */ +type ConverseInputWithExtensionFields = ConverseStreamCommandInput & { + additionalModelRequestFields: Record + [SERVICE_TIER_KEY]?: unknown +} + describe("AwsBedrockHandler", () => { let handler: AwsBedrockHandler @@ -327,7 +337,7 @@ describe("AwsBedrockHandler", () => { describe("getPrefixForRegion", () => { it("should return correct prefix for US regions", () => { // Access private static method using type casting - const getPrefixForRegion = (AwsBedrockHandler as any).getPrefixForRegion + const getPrefixForRegion = AwsBedrockHandler["getPrefixForRegion"] expect(getPrefixForRegion("us-east-1")).toBe("us.") expect(getPrefixForRegion("us-west-2")).toBe("us.") @@ -335,7 +345,7 @@ describe("AwsBedrockHandler", () => { }) it("should return correct prefix for EU regions", () => { - const getPrefixForRegion = (AwsBedrockHandler as any).getPrefixForRegion + const getPrefixForRegion = AwsBedrockHandler["getPrefixForRegion"] expect(getPrefixForRegion("eu-west-1")).toBe("eu.") expect(getPrefixForRegion("eu-central-1")).toBe("eu.") @@ -343,7 +353,7 @@ describe("AwsBedrockHandler", () => { }) it("should return correct prefix for APAC regions", () => { - const getPrefixForRegion = (AwsBedrockHandler as any).getPrefixForRegion + const getPrefixForRegion = AwsBedrockHandler["getPrefixForRegion"] // Australia regions (Sydney and Melbourne) get au. prefix expect(getPrefixForRegion("ap-southeast-2")).toBe("au.") @@ -357,7 +367,7 @@ describe("AwsBedrockHandler", () => { }) it("should return undefined for unsupported regions", () => { - const getPrefixForRegion = (AwsBedrockHandler as any).getPrefixForRegion + const getPrefixForRegion = AwsBedrockHandler["getPrefixForRegion"] expect(getPrefixForRegion("unknown-region")).toBeUndefined() expect(getPrefixForRegion("")).toBeUndefined() @@ -367,7 +377,7 @@ describe("AwsBedrockHandler", () => { describe("isSystemInferenceProfile", () => { it("should return true for AWS inference profile prefixes", () => { - const isSystemInferenceProfile = (AwsBedrockHandler as any).isSystemInferenceProfile + const isSystemInferenceProfile = AwsBedrockHandler["isSystemInferenceProfile"] expect(isSystemInferenceProfile("us.")).toBe(true) expect(isSystemInferenceProfile("eu.")).toBe(true) @@ -375,7 +385,7 @@ describe("AwsBedrockHandler", () => { }) it("should return false for other prefixes", () => { - const isSystemInferenceProfile = (AwsBedrockHandler as any).isSystemInferenceProfile + const isSystemInferenceProfile = AwsBedrockHandler["isSystemInferenceProfile"] expect(isSystemInferenceProfile("ap.")).toBe(false) expect(isSystemInferenceProfile("apne1.")).toBe(false) @@ -395,7 +405,7 @@ describe("AwsBedrockHandler", () => { }) // Access private method using type casting - const parseBaseModelId = (handler as any).parseBaseModelId.bind(handler) + const parseBaseModelId = handler["parseBaseModelId"].bind(handler) expect(parseBaseModelId("us.anthropic.claude-3-5-sonnet-20241022-v2:0")).toBe( "anthropic.claude-3-5-sonnet-20241022-v2:0", @@ -416,7 +426,7 @@ describe("AwsBedrockHandler", () => { awsRegion: "us-east-1", }) - const parseBaseModelId = (handler as any).parseBaseModelId.bind(handler) + const parseBaseModelId = handler["parseBaseModelId"].bind(handler) expect(parseBaseModelId("anthropic.claude-3-5-sonnet-20241022-v2:0")).toBe( "anthropic.claude-3-5-sonnet-20241022-v2:0", @@ -432,7 +442,7 @@ describe("AwsBedrockHandler", () => { awsRegion: "us-east-1", }) - const parseBaseModelId = (handler as any).parseBaseModelId.bind(handler) + const parseBaseModelId = handler["parseBaseModelId"].bind(handler) // Other prefixes should be preserved as part of the model ID expect(parseBaseModelId("ap.anthropic.claude-3-5-sonnet-20241022-v2:0")).toBe( @@ -518,7 +528,7 @@ describe("AwsBedrockHandler", () => { awsRegion: "us-east-1", }) - const parseArn = (handler as any).parseArn.bind(handler) + const parseArn = handler["parseArn"].bind(handler) const result = parseArn( "arn:aws:bedrock:us-east-1:123456789012:foundation-model/us.anthropic.claude-3-5-sonnet-20241022-v2:0", @@ -537,7 +547,7 @@ describe("AwsBedrockHandler", () => { awsRegion: "us-east-1", }) - const parseArn = (handler as any).parseArn.bind(handler) + const parseArn = handler["parseArn"].bind(handler) const result = parseArn( "arn:aws:bedrock:us-east-1:123456789012:foundation-model/anthropic.claude-3-5-sonnet-20241022-v2:0", @@ -556,7 +566,7 @@ describe("AwsBedrockHandler", () => { awsRegion: "us-east-1", }) - const parseArn = (handler as any).parseArn.bind(handler) + const parseArn = handler["parseArn"].bind(handler) const euResult = parseArn( "arn:aws:bedrock:eu-west-1:123456789012:foundation-model/eu.anthropic.claude-3-5-sonnet-20241022-v2:0", @@ -580,7 +590,7 @@ describe("AwsBedrockHandler", () => { awsRegion: "us-east-1", }) - const parseArn = (handler as any).parseArn.bind(handler) + const parseArn = handler["parseArn"].bind(handler) // Other prefixes should not trigger cross-region inference detection const result = parseArn( @@ -601,7 +611,7 @@ describe("AwsBedrockHandler", () => { awsRegion: "us-gov-west-1", }) - const parseArn = (handler as any).parseArn.bind(handler) + const parseArn = handler["parseArn"].bind(handler) const result = parseArn( "arn:aws-us-gov:bedrock:us-gov-west-1:123456789012:inference-profile/us-gov.anthropic.claude-sonnet-4-5-20250929-v1:0", @@ -620,7 +630,7 @@ describe("AwsBedrockHandler", () => { awsRegion: "cn-north-1", }) - const parseArn = (handler as any).parseArn.bind(handler) + const parseArn = handler["parseArn"].bind(handler) const result = parseArn( "arn:aws-cn:bedrock:cn-north-1:123456789012:inference-profile/anthropic.claude-3-sonnet-20240229-v1:0", @@ -675,7 +685,7 @@ describe("AwsBedrockHandler", () => { awsRegion: "us-east-1", }) - const parseArn = (handler as any).parseArn.bind(handler) + const parseArn = handler["parseArn"].bind(handler) // Region in ARN (us-gov-west-1) doesn't match provided region (us-east-1) const result = parseArn( @@ -724,7 +734,7 @@ describe("AwsBedrockHandler", () => { // Verify the command was created with the right payload expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] + const commandArg = mockConverseStreamCommand.mock.calls[0][0] as ConverseInputWithExtensionFields // Verify the image was properly formatted const imageBlock = commandArg.messages![0].content![0] @@ -793,7 +803,7 @@ describe("AwsBedrockHandler", () => { // Verify the command was created with the right payload expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] + const commandArg = mockConverseStreamCommand.mock.calls[0][0] as ConverseInputWithExtensionFields // Verify both images were properly formatted const firstImage = commandArg.messages![0].content![0] @@ -1247,7 +1257,7 @@ describe("AwsBedrockHandler", () => { // Verify the command was created with the right payload expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] as any + const commandArg = mockConverseStreamCommand.mock.calls[0][0] as ConverseInputWithExtensionFields // Should include anthropic_beta in additionalModelRequestFields with both 1M context and fine-grained-tool-streaming expect(commandArg.additionalModelRequestFields).toBeDefined() @@ -1280,7 +1290,7 @@ describe("AwsBedrockHandler", () => { // Verify the command was created with the right payload expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] as any + const commandArg = mockConverseStreamCommand.mock.calls[0][0] as ConverseInputWithExtensionFields // Should include anthropic_beta with fine-grained-tool-streaming for Claude models expect(commandArg.additionalModelRequestFields).toBeDefined() @@ -1312,7 +1322,7 @@ describe("AwsBedrockHandler", () => { // Verify the command was created with the right payload expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] as any + const commandArg = mockConverseStreamCommand.mock.calls[0][0] as ConverseInputWithExtensionFields // Should include anthropic_beta with fine-grained-tool-streaming for Claude models (even non-Sonnet 4) expect(commandArg.additionalModelRequestFields).toBeDefined() @@ -1365,7 +1375,7 @@ describe("AwsBedrockHandler", () => { expect(mockConverseStreamCommand).toHaveBeenCalled() const commandArg = mockConverseStreamCommand.mock.calls[ mockConverseStreamCommand.mock.calls.length - 1 - ][0] as any + ][0] as ConverseInputWithExtensionFields // Should include anthropic_beta in additionalModelRequestFields with both 1M context and fine-grained-tool-streaming expect(commandArg.additionalModelRequestFields).toBeDefined() @@ -1494,7 +1504,7 @@ describe("AwsBedrockHandler", () => { // Per AWS documentation, service_tier must be a top-level parameter, not inside additionalModelRequestFields // https://docs.aws.amazon.com/bedrock/latest/userguide/service-tiers-inference.html expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] as any + const commandArg = mockConverseStreamCommand.mock.calls[0][0] as ConverseInputWithExtensionFields // service_tier should be at the top level of the payload expect(commandArg[SERVICE_TIER_KEY]).toBe("PRIORITY") @@ -1524,7 +1534,7 @@ describe("AwsBedrockHandler", () => { await generator.next() // Start the generator expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] as any + const commandArg = mockConverseStreamCommand.mock.calls[0][0] as ConverseInputWithExtensionFields // service_tier should be at the top level of the payload expect(commandArg[SERVICE_TIER_KEY]).toBe("FLEX") @@ -1555,7 +1565,7 @@ describe("AwsBedrockHandler", () => { await generator.next() // Start the generator expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] as any + const commandArg = mockConverseStreamCommand.mock.calls[0][0] as ConverseInputWithExtensionFields // Service tier should NOT be included for unsupported models (at top level or in additionalModelRequestFields) expect(commandArg[SERVICE_TIER_KEY]).toBeUndefined() @@ -1584,7 +1594,7 @@ describe("AwsBedrockHandler", () => { await generator.next() // Start the generator expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] as any + const commandArg = mockConverseStreamCommand.mock.calls[0][0] as ConverseInputWithExtensionFields // Service tier should NOT be included when not specified (at top level or in additionalModelRequestFields) expect(commandArg[SERVICE_TIER_KEY]).toBeUndefined() @@ -1774,11 +1784,11 @@ describe("AwsBedrockHandler", () => { await generator.next() // Start the generator expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] as any + const commandArg = mockConverseStreamCommand.mock.calls[0][0] as ConverseInputWithExtensionFields // System content should include a cachePoint entry since prompt caching defaults to ON const systemBlocks = commandArg.system - const hasCachePoint = systemBlocks?.some((block: any) => block.cachePoint !== undefined) + const hasCachePoint = systemBlocks?.some((block) => block.cachePoint !== undefined) expect(hasCachePoint).toBe(true) }) @@ -1795,11 +1805,11 @@ describe("AwsBedrockHandler", () => { await generator.next() // Start the generator expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] as any + const commandArg = mockConverseStreamCommand.mock.calls[0][0] as ConverseInputWithExtensionFields // System content should NOT include cachePoint since caching is explicitly disabled const systemBlocks = commandArg.system - const hasCachePoint = systemBlocks?.some((block: any) => block.cachePoint !== undefined) + const hasCachePoint = systemBlocks?.some((block) => block.cachePoint !== undefined) expect(hasCachePoint).toBe(false) }) }) @@ -1824,7 +1834,7 @@ describe("AwsBedrockHandler", () => { await generator.next() expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] as any + const commandArg = mockConverseStreamCommand.mock.calls[0][0] as ConverseInputWithExtensionFields // Adaptive thinking — no budget_tokens, must use effort levels. expect(commandArg.additionalModelRequestFields?.thinking).toEqual({ @@ -1849,7 +1859,7 @@ describe("AwsBedrockHandler", () => { await generator.next() expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] as any + const commandArg = mockConverseStreamCommand.mock.calls[0][0] as ConverseInputWithExtensionFields // 4.8 inherits the 4.7 adaptive-thinking contract — no breaking API changes. expect(commandArg.additionalModelRequestFields?.thinking).toEqual({ @@ -1878,7 +1888,7 @@ describe("AwsBedrockHandler", () => { await generator.next() expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] as any + const commandArg = mockConverseStreamCommand.mock.calls[0][0] as ConverseInputWithExtensionFields // Sonnet 5 uses the same adaptive-thinking contract as Opus 4.7/4.8 — // budget_tokens causes a 400, so thinking.type is "adaptive" with effort. @@ -1929,7 +1939,7 @@ describe("AwsBedrockHandler", () => { await generator.next() expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] as any + const commandArg = mockConverseStreamCommand.mock.calls[0][0] as ConverseInputWithExtensionFields // Opus 5 uses the same adaptive-thinking contract as Opus 4.7/4.8 — // budget_tokens causes a 400, so thinking.type is "adaptive" with effort. @@ -1959,7 +1969,7 @@ describe("AwsBedrockHandler", () => { await generator.next() expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] + const commandArg = mockConverseStreamCommand.mock.calls[0][0] as ConverseInputWithExtensionFields expect(commandArg.additionalModelRequestFields).toEqual( expect.objectContaining({ @@ -1977,7 +1987,7 @@ describe("AwsBedrockHandler", () => { }) await collectStream(provider.createMessage("System prompt", messages)) - const commandArg = mockConverseStreamCommand.mock.calls[0][0] + const commandArg = mockConverseStreamCommand.mock.calls[0][0] as ConverseInputWithExtensionFields expect(commandArg.additionalModelRequestFields).not.toHaveProperty("thinking") expect(commandArg.inferenceConfig?.temperature).toBeUndefined() }) @@ -1996,7 +2006,7 @@ describe("AwsBedrockHandler", () => { }) await collectStream(provider.createMessage("System prompt", messages)) - const commandArg = mockConverseStreamCommand.mock.calls[0][0] + const commandArg = mockConverseStreamCommand.mock.calls[0][0] as ConverseInputWithExtensionFields expect(commandArg.additionalModelRequestFields).toEqual( expect.objectContaining({ thinking: { type: "disabled" } }), ) @@ -2034,7 +2044,7 @@ describe("AwsBedrockHandler", () => { }) await collectStream(provider.createMessage("System prompt", messages)) - const commandArg = mockConverseStreamCommand.mock.calls[0][0] + const commandArg = mockConverseStreamCommand.mock.calls[0][0] as ConverseInputWithExtensionFields expect(commandArg.additionalModelRequestFields ?? {}).not.toHaveProperty("thinking") expect(commandArg.inferenceConfig?.temperature).toBeUndefined() }) @@ -2053,11 +2063,15 @@ describe("AwsBedrockHandler", () => { await generator.next() expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] as any + const commandArg = mockConverseStreamCommand.mock.calls[0][0] as ConverseInputWithExtensionFields // 4.6 still uses the budget_tokens-based thinking format. - expect(commandArg.additionalModelRequestFields?.thinking?.type).toBe("enabled") - expect(commandArg.additionalModelRequestFields?.thinking?.budget_tokens).toBeGreaterThan(0) + const thinking = commandArg.additionalModelRequestFields?.thinking as { + type?: string + budget_tokens?: number + } + expect(thinking?.type).toBe("enabled") + expect(thinking?.budget_tokens).toBeGreaterThan(0) // 4.6 still accepts temperature. expect(commandArg.inferenceConfig?.temperature).toBeDefined() }) @@ -2078,7 +2092,7 @@ describe("AwsBedrockHandler", () => { await generator.next() expect(mockConverseStreamCommand).toHaveBeenCalled() - const commandArg = mockConverseStreamCommand.mock.calls[0][0] as any + const commandArg = mockConverseStreamCommand.mock.calls[0][0] as ConverseInputWithExtensionFields // Model ID should carry the cross-region prefix. expect(commandArg.modelId).toBe("us.anthropic.claude-opus-4-8") @@ -2106,7 +2120,7 @@ describe("AwsBedrockHandler", () => { await opus48Handler.completePrompt("Test prompt") expect(mockConverseCommand).toHaveBeenCalled() - const commandArg = mockConverseCommand.mock.calls[0][0] as any + const commandArg = mockConverseCommand.mock.calls[0][0] as ConverseStreamCommandInput // 4.8 must NOT receive temperature in the non-stream inferenceConfig. expect(commandArg.inferenceConfig?.temperature).toBeUndefined() @@ -2128,7 +2142,7 @@ describe("AwsBedrockHandler", () => { await haiku55Handler.completePrompt("Test prompt") expect(mockConverseCommand).toHaveBeenCalled() - const commandArg = mockConverseCommand.mock.calls[0][0] + const commandArg = mockConverseCommand.mock.calls[0][0] as ConverseStreamCommandInput // Haiku 5.5 must NOT receive temperature in the non-stream inferenceConfig. expect(commandArg.inferenceConfig?.temperature).toBeUndefined() @@ -2149,7 +2163,7 @@ describe("AwsBedrockHandler", () => { await opus46Handler.completePrompt("Test prompt") expect(mockConverseCommand).toHaveBeenCalled() - const commandArg = mockConverseCommand.mock.calls[0][0] as any + const commandArg = mockConverseCommand.mock.calls[0][0] as ConverseStreamCommandInput // 4.6 must still receive temperature. expect(commandArg.inferenceConfig?.temperature).toBeDefined() @@ -2333,7 +2347,7 @@ describe("AwsBedrockHandler", () => { awsSecretKey: "test", awsRegion: "us-east-1", }) - const isAdaptiveThinkingModel = (handler as any).isAdaptiveThinkingModel.bind(handler) + const isAdaptiveThinkingModel = handler["isAdaptiveThinkingModel"].bind(handler) it("returns true for all adaptive-thinking model patterns (opus/sonnet 4.7 and 4.8)", () => { expect(isAdaptiveThinkingModel("anthropic.claude-opus-4-7")).toBe(true) diff --git a/src/api/providers/__tests__/deepseek.spec.ts b/src/api/providers/__tests__/deepseek.spec.ts index 3b6c2496c93..851f2d35fd2 100644 --- a/src/api/providers/__tests__/deepseek.spec.ts +++ b/src/api/providers/__tests__/deepseek.spec.ts @@ -1,5 +1,15 @@ // Mocks must come first, before imports import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" +/** Mirror of the DeepSeek usage payload shape for typed test doubles. */ +interface MoonshotUsage { + prompt_tokens?: number + completion_tokens?: number + total_tokens?: number + prompt_cache_hit_tokens?: number + prompt_cache_miss_tokens?: number + prompt_tokens_details?: { cached_tokens?: number; cache_miss_tokens?: number } | null +} +import type { ProviderError } from "../utils/error-handler" import { clearAllMocks } from "../../../test-utils/reset" import { expectNoLoneSurrogates } from "../../../test-utils/surrogates" @@ -363,7 +373,7 @@ describe("DeepSeekHandler", () => { ] it("should handle streaming responses", async () => { - const chunks: any[] = await collectStream(handler.createMessage(systemPrompt, messages)) + const chunks = await collectStream(handler.createMessage(systemPrompt, messages)) expect(chunks.length).toBeGreaterThan(0) const textChunks = chunks.filter((chunk) => chunk.type === "text") @@ -429,7 +439,7 @@ describe("DeepSeekHandler", () => { }) it("should include usage information", async () => { - const chunks: any[] = await collectStream(handler.createMessage(systemPrompt, messages)) + const chunks = await collectStream(handler.createMessage(systemPrompt, messages)) const usageChunks = chunks.filter((chunk) => chunk.type === "usage") expect(usageChunks.length).toBeGreaterThan(0) @@ -438,7 +448,7 @@ describe("DeepSeekHandler", () => { }) it("should include cache metrics in usage information", async () => { - const chunks: any[] = await collectStream(handler.createMessage(systemPrompt, messages)) + const chunks = await collectStream(handler.createMessage(systemPrompt, messages)) const usageChunks = chunks.filter((chunk) => chunk.type === "usage") expect(usageChunks.length).toBeGreaterThan(0) @@ -458,7 +468,7 @@ describe("DeepSeekHandler", () => { ]), ) - const chunks: any[] = await collectStream(handler.createMessage(systemPrompt, messages)) + const chunks = await collectStream(handler.createMessage(systemPrompt, messages)) expect(chunks).toContainEqual({ type: "reasoning", text: "thinking..." }) }) @@ -474,7 +484,7 @@ describe("DeepSeekHandler", () => { ]), ) - const chunks: any[] = await collectStream(handler.createMessage(systemPrompt, messages)) + const chunks = await collectStream(handler.createMessage(systemPrompt, messages)) expect(chunks).toContainEqual({ type: "reasoning", text: "router-style thought" }) }) @@ -487,7 +497,7 @@ describe("DeepSeekHandler", () => { const err = await stream.next().catch((e) => e) expect(err.message).toBe("DeepSeek completion error: Invalid API key") - expect((err as any).status).toBe(401) + expect((err as ProviderError).status).toBe(401) }) it("prefers delta.reasoning_content over delta.reasoning when both are present", async () => { @@ -511,7 +521,7 @@ describe("DeepSeekHandler", () => { ]), ) - const chunks: any[] = await collectStream(handler.createMessage(systemPrompt, messages)) + const chunks = await collectStream(handler.createMessage(systemPrompt, messages)) const reasoningChunks = chunks.filter((chunk) => chunk.type === "reasoning") expect(reasoningChunks).toEqual([{ type: "reasoning", text: "primary thought" }]) @@ -520,14 +530,15 @@ describe("DeepSeekHandler", () => { describe("processUsageMetrics", () => { class TestDeepSeekHandler extends DeepSeekHandler { - public testProcessUsageMetrics(usage: any) { + public testProcessUsageMetrics(usage: MoonshotUsage | null | undefined) { return this.processUsageMetrics(usage) } } // mockOptions is assigned in beforeEach, so the handler must be built // per test rather than at describe-collection time. - const processUsage = (usage: any) => new TestDeepSeekHandler(mockOptions).testProcessUsageMetrics(usage) + const processUsage = (usage: MoonshotUsage | null | undefined) => + new TestDeepSeekHandler(mockOptions).testProcessUsageMetrics(usage) // DeepSeek's OpenAPI marks prompt_cache_hit_tokens and // prompt_cache_miss_tokens as required top-level members, and declares @@ -636,7 +647,7 @@ describe("DeepSeekHandler", () => { }) const stream = reasonerHandler.createMessage(systemPrompt, messages) - const chunks: any[] = await collectStream(stream) + const chunks = await collectStream(stream) // Should have reasoning chunks const reasoningChunks = chunks.filter((chunk) => chunk.type === "reasoning") @@ -735,7 +746,7 @@ describe("DeepSeekHandler", () => { apiModelId: "deepseek-v4-pro", }) - const tools: any[] = [ + const tools: OpenAI.Chat.ChatCompletionTool[] = [ { type: "function", function: { @@ -747,7 +758,7 @@ describe("DeepSeekHandler", () => { ] const stream = reasonerHandler.createMessage(systemPrompt, messages, { taskId: "test", tools }) - const chunks: any[] = await collectStream(stream) + const chunks = await collectStream(stream) // Should have reasoning chunks const reasoningChunks = chunks.filter((chunk) => chunk.type === "reasoning") diff --git a/src/api/providers/__tests__/gemini-handler.spec.ts b/src/api/providers/__tests__/gemini-handler.spec.ts index 5b1b6c91c45..d512269800c 100644 --- a/src/api/providers/__tests__/gemini-handler.spec.ts +++ b/src/api/providers/__tests__/gemini-handler.spec.ts @@ -1,5 +1,7 @@ import { t } from "i18next" import { FunctionCallingConfigMode } from "@google/genai" +import type { Mock } from "vitest" +import type { Anthropic } from "@anthropic-ai/sdk" const mockCaptureException = vi.fn() @@ -12,6 +14,15 @@ vi.mock("@roo-code/telemetry", () => ({ })) import { GeminiHandler } from "../gemini" + +/** + * Replaces models.generateContentStream with a bare vi.fn stub; routed through + * unknown because the stub provides only that one SDK member. + */ +function stubGeminiStream(handler: GeminiHandler, stub: Mock): void { + const models = handler["client"].models + models.generateContentStream = stub as unknown as typeof models.generateContentStream +} import { makeApiHandlerOptions } from "../../../test-utils/api" describe("GeminiHandler backend support", () => { @@ -26,9 +37,8 @@ describe("GeminiHandler backend support", () => { const options = makeApiHandlerOptions() const handler = new GeminiHandler(options) const stub = vi.fn().mockReturnValue((async function* () {})()) - // @ts-ignore access private client - handler["client"].models.generateContentStream = stub - await handler.createMessage("instr", [] as any).next() + stubGeminiStream(handler, stub) + await handler.createMessage("instr", []).next() const config = stub.mock.calls[0][0].config // createMessage always uses function declarations only // (tools are always present from ALWAYS_AVAILABLE_TOOLS) @@ -39,7 +49,6 @@ describe("GeminiHandler backend support", () => { const options = makeApiHandlerOptions() const handler = new GeminiHandler(options) const stub = vi.fn().mockResolvedValue({ text: "ok" }) - // @ts-ignore access private client handler["client"].models.generateContent = stub const res = await handler.completePrompt("hi") expect(res).toBe("ok") @@ -97,11 +106,10 @@ describe("GeminiHandler backend support", () => { } const stub = vi.fn().mockReturnValue(mockStream()) - // @ts-ignore access private client - handler["client"].models.generateContentStream = stub + stubGeminiStream(handler, stub) const messages = [] - for await (const chunk of handler.createMessage("test", [] as any)) { + for await (const chunk of handler.createMessage("test", [])) { messages.push(chunk) } @@ -133,11 +141,10 @@ describe("GeminiHandler backend support", () => { } const stub = vi.fn().mockReturnValue(mockStream()) - // @ts-ignore access private client - handler["client"].models.generateContentStream = stub + stubGeminiStream(handler, stub) const messages = [] - for await (const chunk of handler.createMessage("test", [] as any)) { + for await (const chunk of handler.createMessage("test", [])) { messages.push(chunk) } @@ -164,11 +171,10 @@ describe("GeminiHandler backend support", () => { const mockError = new Error("API rate limit exceeded") const stub = vi.fn().mockRejectedValue(mockError) - // @ts-ignore access private client - handler["client"].models.generateContentStream = stub + stubGeminiStream(handler, stub) await expect(async () => { - const generator = handler.createMessage("test", [] as any) + const generator = handler.createMessage("test", []) await generator.next() }).rejects.toThrow(t("common:errors.gemini.generate_stream", { error: "API rate limit exceeded" })) }) @@ -206,11 +212,10 @@ describe("GeminiHandler backend support", () => { const options = makeApiHandlerOptions() const handler = new GeminiHandler(options) const stub = vi.fn().mockReturnValue((async function* () {})()) - // @ts-ignore access private client - handler["client"].models.generateContentStream = stub + stubGeminiStream(handler, stub) await handler - .createMessage("test", [] as any, { + .createMessage("test", [], { taskId: "test-task", tools: testTools, allowedFunctionNames: ["read_file", "write_to_file"], @@ -225,11 +230,10 @@ describe("GeminiHandler backend support", () => { const options = makeApiHandlerOptions() const handler = new GeminiHandler(options) const stub = vi.fn().mockReturnValue((async function* () {})()) - // @ts-ignore access private client - handler["client"].models.generateContentStream = stub + stubGeminiStream(handler, stub) await handler - .createMessage("test", [] as any, { + .createMessage("test", [], { taskId: "test-task", tools: testTools, allowedFunctionNames: ["read_file"], @@ -246,8 +250,7 @@ describe("GeminiHandler backend support", () => { const options = makeApiHandlerOptions() const handler = new GeminiHandler(options) const stub = vi.fn().mockReturnValue((async function* () {})()) - // @ts-ignore access private client - handler["client"].models.generateContentStream = stub + stubGeminiStream(handler, stub) const manyTools = Array.from({ length: 30 }, (_, index) => ({ type: "function" as const, @@ -259,7 +262,7 @@ describe("GeminiHandler backend support", () => { })) await handler - .createMessage("test", [] as any, { + .createMessage("test", [], { taskId: "test-task", tools: manyTools, allowedFunctionNames: manyTools.map((tool) => tool.function.name), @@ -275,8 +278,7 @@ describe("GeminiHandler backend support", () => { const options = makeApiHandlerOptions() const handler = new GeminiHandler(options) const stub = vi.fn().mockReturnValue((async function* () {})()) - // @ts-ignore access private client - handler["client"].models.generateContentStream = stub + stubGeminiStream(handler, stub) const manyTools = Array.from({ length: 30 }, (_, index) => ({ type: "function" as const, @@ -286,7 +288,7 @@ describe("GeminiHandler backend support", () => { parameters: { type: "object", properties: {} }, }, })) - const messages = [ + const messages: Anthropic.Messages.MessageParam[] = [ { role: "assistant", content: [{ type: "tool_use", id: "tool-call-29", name: "tool_29", input: {} }], @@ -294,7 +296,7 @@ describe("GeminiHandler backend support", () => { ] await handler - .createMessage("test", messages as any, { + .createMessage("test", messages, { taskId: "test-task", tools: manyTools, allowedFunctionNames: manyTools.slice(0, 29).map((tool) => tool.function.name), @@ -310,11 +312,10 @@ describe("GeminiHandler backend support", () => { const options = makeApiHandlerOptions() const handler = new GeminiHandler(options) const stub = vi.fn().mockReturnValue((async function* () {})()) - // @ts-ignore access private client - handler["client"].models.generateContentStream = stub + stubGeminiStream(handler, stub) await handler - .createMessage("test", [] as any, { + .createMessage("test", [], { taskId: "test-task", tools: testTools, tool_choice: "auto", @@ -331,11 +332,10 @@ describe("GeminiHandler backend support", () => { const options = makeApiHandlerOptions() const handler = new GeminiHandler(options) const stub = vi.fn().mockReturnValue((async function* () {})()) - // @ts-ignore access private client - handler["client"].models.generateContentStream = stub + stubGeminiStream(handler, stub) await handler - .createMessage("test", [] as any, { + .createMessage("test", [], { taskId: "test-task", tools: testTools, tool_choice: "auto", @@ -353,11 +353,10 @@ describe("GeminiHandler backend support", () => { const options = makeApiHandlerOptions() const handler = new GeminiHandler(options) const stub = vi.fn().mockReturnValue((async function* () {})()) - // @ts-ignore access private client - handler["client"].models.generateContentStream = stub + stubGeminiStream(handler, stub) await handler - .createMessage("test", [] as any, { + .createMessage("test", [], { taskId: "test-task", tools: testTools, }) @@ -374,11 +373,10 @@ describe("GeminiHandler backend support", () => { const options = makeApiHandlerOptions() const handler = new GeminiHandler(options) const stub = vi.fn().mockReturnValue((async function* () {})()) - // @ts-ignore access private client - handler["client"].models.generateContentStream = stub + stubGeminiStream(handler, stub) await handler - .createMessage("test", [] as any, { + .createMessage("test", [], { taskId: "test-task", tools: [ { @@ -433,11 +431,10 @@ describe("GeminiHandler backend support", () => { const options = makeApiHandlerOptions() const handler = new GeminiHandler(options) const stub = vi.fn().mockReturnValue((async function* () {})()) - // @ts-ignore access private client - handler["client"].models.generateContentStream = stub + stubGeminiStream(handler, stub) await handler - .createMessage("test", [] as any, { + .createMessage("test", [], { taskId: "test-task", tools: [ { @@ -492,11 +489,10 @@ describe("GeminiHandler backend support", () => { const options = makeApiHandlerOptions() const handler = new GeminiHandler(options) const stub = vi.fn().mockReturnValue((async function* () {})()) - // @ts-ignore access private client - handler["client"].models.generateContentStream = stub + stubGeminiStream(handler, stub) await handler - .createMessage("test", [] as any, { + .createMessage("test", [], { taskId: "test-task", tools: [ { @@ -537,11 +533,10 @@ describe("GeminiHandler backend support", () => { const options = makeApiHandlerOptions() const handler = new GeminiHandler(options) const stub = vi.fn().mockReturnValue((async function* () {})()) - // @ts-ignore access private client - handler["client"].models.generateContentStream = stub + stubGeminiStream(handler, stub) await handler - .createMessage("test", [] as any, { + .createMessage("test", [], { taskId: "test-task", tools: [ { @@ -586,11 +581,10 @@ describe("GeminiHandler backend support", () => { const options = makeApiHandlerOptions() const handler = new GeminiHandler(options) const stub = vi.fn().mockReturnValue((async function* () {})()) - // @ts-ignore access private client - handler["client"].models.generateContentStream = stub + stubGeminiStream(handler, stub) await handler - .createMessage("test", [] as any, { + .createMessage("test", [], { taskId: "test-task", tools: [ { @@ -628,11 +622,10 @@ describe("GeminiHandler backend support", () => { const options = makeApiHandlerOptions() const handler = new GeminiHandler(options) const stub = vi.fn().mockReturnValue((async function* () {})()) - // @ts-ignore access private client - handler["client"].models.generateContentStream = stub + stubGeminiStream(handler, stub) await handler - .createMessage("test", [] as any, { + .createMessage("test", [], { taskId: "test-task", tools: [ { @@ -680,11 +673,10 @@ describe("GeminiHandler backend support", () => { const options = makeApiHandlerOptions() const handler = new GeminiHandler(options) const stub = vi.fn().mockReturnValue((async function* () {})()) - // @ts-ignore access private client - handler["client"].models.generateContentStream = stub + stubGeminiStream(handler, stub) await handler - .createMessage("test", [] as any, { + .createMessage("test", [], { taskId: "test-task", tools: [ { diff --git a/src/api/providers/__tests__/gemini.spec.ts b/src/api/providers/__tests__/gemini.spec.ts index 9a2ed7d3c21..7c950757732 100644 --- a/src/api/providers/__tests__/gemini.spec.ts +++ b/src/api/providers/__tests__/gemini.spec.ts @@ -12,7 +12,7 @@ vitest.mock("@roo-code/telemetry", () => ({ import { Anthropic } from "@anthropic-ai/sdk" -import type { GenerateContentResponse } from "@google/genai" +import type { Content, GenerateContentResponse, GoogleGenAI } from "@google/genai" import { type ModelInfo, geminiDefaultModelId, ApiProviderError } from "@roo-code/types" @@ -31,6 +31,14 @@ const GEMINI_MODEL_NAME = geminiDefaultModelId // cast is the least-friction way to satisfy the class type in mocks. const stubGenerateContentResponse = (text: string) => ({ text }) as unknown as GenerateContentResponse +/** + * Yields structural GenerateContentResponse doubles (candidates/usageMetadata); + * routed through unknown because only those members are consumed. + */ +function makeStream(chunks: unknown[]): AsyncGenerator { + return asyncStreamFrom(chunks) as AsyncGenerator +} + describe("GeminiHandler", () => { let handler: GeminiHandler let mockGenerateContentStream: ReturnType @@ -51,13 +59,15 @@ describe("GeminiHandler", () => { }) // Replace the client with our mock + // Double provides models.generateContentStream/generateContent/getGenerativeModel, + // the only members these tests exercise. handler["client"] = { models: { generateContentStream: mockGenerateContentStream, generateContent: mockGenerateContent, getGenerativeModel: mockGetGenerativeModel, }, - } as any + } as unknown as GoogleGenAI }) describe("constructor", () => { @@ -69,12 +79,11 @@ describe("GeminiHandler", () => { describe("thoughtSignature round-trip (issue #536)", () => { const systemPrompt = "You are a helpful assistant" - const toolMetadata = { tools: [{ function: { name: "read_file", description: "", parameters: {} } }] } as any + const toolMetadata = makeCreateMessageMetadata({ + tools: [{ type: "function" as const, function: { name: "read_file", description: "", parameters: {} } }], + }) // Helper: build a mock async-iterable stream from chunks - function makeStream(chunks: unknown[]) { - return asyncStreamFrom(chunks) - } // Simulate a Gemini 3.x response: thoughtSignature arrives on its own part, // alongside a functionCall part (the way the real Gemini 3 API returns it). @@ -96,7 +105,7 @@ describe("GeminiHandler", () => { ]) it("captures thoughtSignature from the stream after turn 1", async () => { - ;(handler["client"].models.generateContentStream as any).mockResolvedValue(turn1Response) + vi.mocked(handler["client"].models.generateContentStream).mockResolvedValue(turn1Response) const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Read foo.ts" }] @@ -117,7 +126,12 @@ describe("GeminiHandler", () => { // tool_use block + appended thoughtSignature block content: [ { type: "tool_use", id: "call-1", name: "read_file", input: { path: "foo.ts" } }, - { type: "thoughtSignature", thoughtSignature: "sig-abc123" } as any, + // Extension history block (ThoughtSignatureContentBlock) carried through + // convertAnthropicContentToGemini; routed through unknown to stay in MessageParam. + { + type: "thoughtSignature", + thoughtSignature: "sig-abc123", + } as unknown as Anthropic.ContentBlockParam, ], }, { @@ -126,7 +140,7 @@ describe("GeminiHandler", () => { }, ] - ;(handler["client"].models.generateContentStream as any).mockResolvedValue( + vi.mocked(handler["client"].models.generateContentStream).mockResolvedValue( makeStream([ { candidates: [{ content: { parts: [{ text: "Done." }] } }] }, { usageMetadata: { promptTokenCount: 20, candidatesTokenCount: 5 } }, @@ -135,15 +149,17 @@ describe("GeminiHandler", () => { await collectStream(handler.createMessage(systemPrompt, historyAfterTurn1, toolMetadata)) - const callArgs = (handler["client"].models.generateContentStream as any).mock.calls[0][0] - const contents: any[] = callArgs.contents + const callArgs = vi.mocked(handler["client"].models.generateContentStream).mock.calls[0][0] + const contents = Array.isArray(callArgs.contents) ? callArgs.contents : [callArgs.contents] // The model turn in the outgoing request must carry the thoughtSignature on its functionCall part - const modelTurn = contents.find((c: any) => c.role === "model") + const modelTurn = contents.find( + (c): c is Content => typeof c === "object" && "role" in c && c.role === "model", + ) expect(modelTurn).toBeDefined() - const fnPart = modelTurn.parts.find((p: any) => p.functionCall) + const fnPart = modelTurn!.parts!.find((p) => p.functionCall) expect(fnPart).toBeDefined() - expect(fnPart.thoughtSignature).toBe("sig-abc123") + expect((fnPart as { thoughtSignature?: string }).thoughtSignature).toBe("sig-abc123") }) it("falls back to base64-encoded skip_thought_signature_validator when history has no signature", async () => { @@ -162,7 +178,7 @@ describe("GeminiHandler", () => { }, ] - ;(handler["client"].models.generateContentStream as any).mockResolvedValue( + vi.mocked(handler["client"].models.generateContentStream).mockResolvedValue( makeStream([ { candidates: [{ content: { parts: [{ text: "Done." }] } }] }, { usageMetadata: { promptTokenCount: 20, candidatesTokenCount: 5 } }, @@ -171,13 +187,15 @@ describe("GeminiHandler", () => { await collectStream(handler.createMessage(systemPrompt, historyNoSig, toolMetadata)) - const callArgs = (handler["client"].models.generateContentStream as any).mock.calls[0][0] - const contents: any[] = callArgs.contents - const modelTurn = contents.find((c: any) => c.role === "model") - const fnPart = modelTurn?.parts.find((p: any) => p.functionCall) + const callArgs = vi.mocked(handler["client"].models.generateContentStream).mock.calls[0][0] + const contents = Array.isArray(callArgs.contents) ? callArgs.contents : [callArgs.contents] + const modelTurn = contents.find( + (c): c is Content => typeof c === "object" && "role" in c && c.role === "model", + ) + const fnPart = modelTurn?.parts?.find((p) => p.functionCall) expect(fnPart).toBeDefined() const expectedBypass = Buffer.from("skip_thought_signature_validator").toString("base64") - expect(fnPart.thoughtSignature).toBe(expectedBypass) + expect((fnPart as { thoughtSignature?: string }).thoughtSignature).toBe(expectedBypass) }) it("sends thoughtSignature even when reasoningEffort is disabled", async () => { @@ -189,9 +207,9 @@ describe("GeminiHandler", () => { apiKey: "test-key", geminiApiKey: "test-key", apiModelId: GEMINI_MODEL_NAME, - reasoningEffort: "disable" as any, + reasoningEffort: "disable", }) - handlerNoReasoning["client"] = handler["client"] as any + handlerNoReasoning["client"] = handler["client"] const historyWithSig: Anthropic.Messages.MessageParam[] = [ { role: "user", content: "Read foo.ts" }, @@ -199,7 +217,12 @@ describe("GeminiHandler", () => { role: "assistant", content: [ { type: "tool_use", id: "call-1", name: "read_file", input: { path: "foo.ts" } }, - { type: "thoughtSignature", thoughtSignature: "sig-xyz" } as any, + // Extension history block (ThoughtSignatureContentBlock) carried through + // convertAnthropicContentToGemini; routed through unknown to stay in MessageParam. + { + type: "thoughtSignature", + thoughtSignature: "sig-xyz", + } as unknown as Anthropic.ContentBlockParam, ], }, { @@ -208,7 +231,7 @@ describe("GeminiHandler", () => { }, ] - ;(handler["client"].models.generateContentStream as any).mockResolvedValue( + vi.mocked(handler["client"].models.generateContentStream).mockResolvedValue( makeStream([ { candidates: [{ content: { parts: [{ text: "Done." }] } }] }, { usageMetadata: { promptTokenCount: 20, candidatesTokenCount: 5 } }, @@ -217,12 +240,14 @@ describe("GeminiHandler", () => { await collectStream(handlerNoReasoning.createMessage(systemPrompt, historyWithSig, toolMetadata)) - const callArgs = (handler["client"].models.generateContentStream as any).mock.calls[0][0] - const contents: any[] = callArgs.contents - const modelTurn = contents.find((c: any) => c.role === "model") - const fnPart = modelTurn?.parts.find((p: any) => p.functionCall) + const callArgs = vi.mocked(handler["client"].models.generateContentStream).mock.calls[0][0] + const contents = Array.isArray(callArgs.contents) ? callArgs.contents : [callArgs.contents] + const modelTurn = contents.find( + (c): c is Content => typeof c === "object" && "role" in c && c.role === "model", + ) + const fnPart = modelTurn?.parts?.find((p) => p.functionCall) expect(fnPart).toBeDefined() - expect(fnPart.thoughtSignature).toBe("sig-xyz") + expect((fnPart as { thoughtSignature?: string }).thoughtSignature).toBe("sig-xyz") }) it("does NOT capture thoughtSignature when there are no tools in metadata", async () => { @@ -232,10 +257,10 @@ describe("GeminiHandler", () => { apiKey: "test-key", geminiApiKey: "test-key", apiModelId: GEMINI_MODEL_NAME, - reasoningEffort: "disable" as any, + reasoningEffort: "disable", }) - handlerNoReasoning["client"] = handler["client"] as any - ;(handler["client"].models.generateContentStream as any).mockResolvedValue( + handlerNoReasoning["client"] = handler["client"] + vi.mocked(handler["client"].models.generateContentStream).mockResolvedValue( makeStream([ { candidates: [ @@ -276,8 +301,8 @@ describe("GeminiHandler", () => { it("should handle text messages correctly", async () => { // Setup the mock implementation to return an async generator - ;(handler["client"].models.generateContentStream as any).mockResolvedValue( - asyncStreamFrom([ + vi.mocked(handler["client"].models.generateContentStream).mockResolvedValue( + makeStream([ { text: "Hello" }, { text: " world!" }, { usageMetadata: { promptTokenCount: 10, candidatesTokenCount: 5 } }, @@ -391,7 +416,7 @@ describe("GeminiHandler", () => { it("should handle API errors", async () => { const mockError = new Error("Gemini API error") - ;(handler["client"].models.generateContentStream as any).mockRejectedValue(mockError) + vi.mocked(handler["client"].models.generateContentStream).mockRejectedValue(mockError) const stream = handler.createMessage(systemPrompt, mockMessages) @@ -402,9 +427,9 @@ describe("GeminiHandler", () => { describe("completePrompt", () => { it("should complete prompt successfully", async () => { // Mock the response with text property - ;(handler["client"].models.generateContent as any).mockResolvedValue({ - text: "Test response", - }) + vi.mocked(handler["client"].models.generateContent).mockResolvedValue( + stubGenerateContentResponse("Test response"), + ) const result = await handler.completePrompt("Test prompt") expect(result).toBe("Test response") @@ -422,7 +447,7 @@ describe("GeminiHandler", () => { it("should handle API errors", async () => { const mockError = new Error("Gemini API error") - ;(handler["client"].models.generateContent as any).mockRejectedValue(mockError) + vi.mocked(handler["client"].models.generateContent).mockRejectedValue(mockError) await expect(handler.completePrompt("Test prompt")).rejects.toThrow( t("common:errors.gemini.generate_complete_prompt", { error: "Gemini API error" }), @@ -431,9 +456,7 @@ describe("GeminiHandler", () => { it("should handle empty response", async () => { // Mock the response with empty text - ;(handler["client"].models.generateContent as any).mockResolvedValue({ - text: "", - }) + vi.mocked(handler["client"].models.generateContent).mockResolvedValue(stubGenerateContentResponse("")) const result = await handler.completePrompt("Test prompt") expect(result).toBe("") @@ -1635,7 +1658,7 @@ describe("GeminiHandler", () => { it("should capture telemetry on createMessage error", async () => { const mockError = new Error("Gemini API error") - ;(handler["client"].models.generateContentStream as any).mockRejectedValue(mockError) + vi.mocked(handler["client"].models.generateContentStream).mockRejectedValue(mockError) const stream = handler.createMessage(systemPrompt, mockMessages) @@ -1699,7 +1722,7 @@ describe("GeminiHandler", () => { it("should capture telemetry on completePrompt error", async () => { const mockError = new Error("Gemini completion error") - ;(handler["client"].models.generateContent as any).mockRejectedValue(mockError) + vi.mocked(handler["client"].models.generateContent).mockRejectedValue(mockError) await expect(handler.completePrompt("Test prompt")).rejects.toThrow() @@ -1721,7 +1744,7 @@ describe("GeminiHandler", () => { it("should still throw the error after capturing telemetry", async () => { const mockError = new Error("Gemini API error") - ;(handler["client"].models.generateContentStream as any).mockRejectedValue(mockError) + vi.mocked(handler["client"].models.generateContentStream).mockRejectedValue(mockError) const stream = handler.createMessage(systemPrompt, mockMessages) diff --git a/src/api/providers/__tests__/mimo.spec.ts b/src/api/providers/__tests__/mimo.spec.ts index 062d2fd9228..c67f791a8c3 100644 --- a/src/api/providers/__tests__/mimo.spec.ts +++ b/src/api/providers/__tests__/mimo.spec.ts @@ -1,5 +1,6 @@ const mockCreate = vi.fn() import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" +import { makeCreateMessageMetadata } from "../../../test-utils/api" import { clearAllMocks } from "../../../test-utils/reset" vi.mock("openai", () => { return { @@ -35,7 +36,19 @@ vi.mock("openai", () => { import type { Anthropic } from "@anthropic-ai/sdk" import { mimoDefaultModelId, mimoModels } from "@roo-code/types" import type { ApiHandlerOptions } from "../../../shared/api" +import type OpenAI from "openai" import { MimoHandler } from "../mimo" +/** Assistant message carrying the reasoning_content passthrough convertToR1Format attaches. */ +type AssistantMessageWithReasoning = OpenAI.Chat.ChatCompletionAssistantMessageParam & { + reasoning_content?: string + reasoning_details?: unknown[] +} + +/** Anthropic history message with the extension's reasoning_content passthrough. */ +type AnthropicMessageWithReasoning = Anthropic.Messages.MessageParam & { + reasoning_content?: string +} + import { convertToR1Format } from "../../transform/r1-format" import { sanitizeOpenAiCallId } from "../../../utils/tool-id" @@ -69,13 +82,13 @@ describe("MimoHandler", () => { it("should use Singapore base URL if not provided", () => { const h = new MimoHandler({ ...mockOptions, mimoBaseUrl: undefined }) - expect((h as any).options.openAiBaseUrl).toBe("https://token-plan-sgp.xiaomimimo.com/v1") + expect(h["options"].openAiBaseUrl).toBe("https://token-plan-sgp.xiaomimimo.com/v1") }) it("should use custom base URL when provided", () => { const customUrl = "https://api.xiaomimimo.com/v1" const h = new MimoHandler({ ...mockOptions, mimoBaseUrl: customUrl }) - expect((h as any).options.openAiBaseUrl).toBe(customUrl) + expect(h["options"].openAiBaseUrl).toBe(customUrl) }) }) @@ -117,7 +130,12 @@ describe("MimoHandler", () => { { role: "assistant", content: [ - { type: "reasoning" as const, text: "Let me think..." } as any, + // Extension reasoning block the converter narrows by `type`; routed through + // unknown to stay inside MessageParam. + { + type: "reasoning" as const, + text: "Let me think...", + } as unknown as Anthropic.ContentBlockParam, { type: "text" as const, text: "Here is the answer" }, ], }, @@ -126,7 +144,7 @@ describe("MimoHandler", () => { expect(result).toHaveLength(1) expect(result[0].role).toBe("assistant") expect(result[0].content).toBe("Here is the answer") - expect((result[0] as any).reasoning_content).toBe("Let me think...") + expect((result[0] as AssistantMessageWithReasoning).reasoning_content).toBe("Let me think...") }) it("should convert assistant message with tool_use blocks", () => { @@ -146,11 +164,12 @@ describe("MimoHandler", () => { ] const result = convert(messages) expect(result).toHaveLength(1) - const msg = result[0] as any + const msg = result[0] as AssistantMessageWithReasoning + const toolCall = msg.tool_calls![0] as OpenAI.Chat.ChatCompletionMessageFunctionToolCall expect(msg.tool_calls).toHaveLength(1) - expect(msg.tool_calls[0].id).toBe("call_123") - expect(msg.tool_calls[0].function.name).toBe("read_file") - expect(msg.tool_calls[0].function.arguments).toBe('{"path":"README.md"}') + expect(toolCall.id).toBe("call_123") + expect(toolCall.function.name).toBe("read_file") + expect(toolCall.function.arguments).toBe('{"path":"README.md"}') }) it("should handle string-input tool_use (JSON string)", () => { @@ -168,10 +187,11 @@ describe("MimoHandler", () => { }, ] const result = convert(messages) - const msg = result[0] as any + const msg = result[0] as AssistantMessageWithReasoning + const toolCall = msg.tool_calls![0] as OpenAI.Chat.ChatCompletionMessageFunctionToolCall expect(msg.tool_calls).toHaveLength(1) - expect(msg.tool_calls[0].function.name).toBe("read_file") - expect(msg.tool_calls[0].function.arguments).toContain("test.ts") + expect(toolCall.function.name).toBe("read_file") + expect(toolCall.function.arguments).toContain("test.ts") }) it("should handle assistant message with string content", () => { @@ -188,28 +208,28 @@ describe("MimoHandler", () => { }) it("should handle assistant string content with reasoning_content", () => { - const messages = [ + const messages: AnthropicMessageWithReasoning[] = [ { - role: "assistant" as const, + role: "assistant", content: "Response after thinking", reasoning_content: "My reasoning", }, - ] as any[] + ] const result = convert(messages) expect(result).toHaveLength(1) - expect((result[0] as any).reasoning_content).toBe("My reasoning") + expect((result[0] as AssistantMessageWithReasoning).reasoning_content).toBe("My reasoning") }) it("should not add reasoning_content if empty string", () => { - const messages = [ + const messages: AnthropicMessageWithReasoning[] = [ { - role: "assistant" as const, + role: "assistant", content: "Response", reasoning_content: "", }, - ] as any[] + ] const result = convert(messages) - expect((result[0] as any).reasoning_content).toBeUndefined() + expect((result[0] as AssistantMessageWithReasoning).reasoning_content).toBeUndefined() }) it("should convert user messages with tool_result blocks", () => { @@ -226,7 +246,7 @@ describe("MimoHandler", () => { }, ] const result = convert(messages) - const msg = result[0] as any + const msg = result[0] as OpenAI.Chat.ChatCompletionToolMessageParam expect(msg.role).toBe("tool") expect(msg.tool_call_id).toBe("call_123") expect(msg.content).toBe("File contents here") @@ -325,7 +345,12 @@ describe("MimoHandler", () => { { role: "assistant", content: [ - { type: "reasoning" as const, text: "User wants to read a file" } as any, + // Extension reasoning block the converter narrows by `type`; routed through + // unknown to stay inside MessageParam. + { + type: "reasoning" as const, + text: "User wants to read a file", + } as unknown as Anthropic.ContentBlockParam, { type: "text" as const, text: "I'll read it" }, { type: "tool_use" as const, @@ -352,11 +377,11 @@ describe("MimoHandler", () => { expect(result[0].role).toBe("user") // assistant with reasoning + tool_calls expect(result[1].role).toBe("assistant") - expect((result[1] as any).reasoning_content).toBe("User wants to read a file") - expect((result[1] as any).tool_calls).toHaveLength(1) + expect((result[1] as AssistantMessageWithReasoning).reasoning_content).toBe("User wants to read a file") + expect((result[1] as AssistantMessageWithReasoning).tool_calls).toHaveLength(1) // tool result expect(result[2].role).toBe("tool") - expect((result[2] as any).tool_call_id).toBe("call_1") + expect((result[2] as OpenAI.Chat.ChatCompletionToolMessageParam).tool_call_id).toBe("call_1") }) }) @@ -421,7 +446,7 @@ describe("MimoHandler", () => { }, ] - const stream = handler.createMessage("System prompt", messages, { tools } as any) + const stream = handler.createMessage("System prompt", messages, makeCreateMessageMetadata({ tools })) await collectStream(stream) const params = mockCreate.mock.calls[0][0] @@ -757,7 +782,7 @@ describe("MimoHandler", () => { ]), ) - const tools: any[] = [ + const tools: OpenAI.Chat.ChatCompletionTool[] = [ { type: "function", function: { name: "read_file", description: "Read", parameters: {} }, @@ -832,7 +857,7 @@ describe("MimoHandler", () => { ]), ) - const tools: any[] = [ + const tools: OpenAI.Chat.ChatCompletionTool[] = [ { type: "function", function: { name: "test_tool", description: "Test", parameters: {} }, diff --git a/src/api/providers/__tests__/moonshot.spec.ts b/src/api/providers/__tests__/moonshot.spec.ts index af82c86c8ef..9bb1109ecff 100644 --- a/src/api/providers/__tests__/moonshot.spec.ts +++ b/src/api/providers/__tests__/moonshot.spec.ts @@ -7,6 +7,23 @@ import type { ApiHandlerOptions } from "../../../shared/api" import { MoonshotHandler } from "../moonshot" import { clearAllMocks } from "../../../test-utils/reset" +import { collectStream } from "../../../test-utils/stream" +import type OpenAI from "openai" +import type { ModelInfo } from "@roo-code/types" + +/** Mirror of MoonshotHandler's MoonshotUsage payload shape for typed test doubles. */ +interface MoonshotUsage { + prompt_tokens?: number + completion_tokens?: number + prompt_tokens_details?: { cached_tokens?: number } | null + cached_tokens?: number +} + +/** + * Request options accepted by addMaxTokensIfNeeded. Tests seed a minimal valid + * non-streaming params object; the handler only sets `max_tokens`. + */ +type MoonshotRequestOptions = OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming describe("MoonshotHandler", () => { let handler: MoonshotHandler @@ -131,15 +148,12 @@ describe("MoonshotHandler", () => { create: vi.fn().mockResolvedValue(mockStream()), }, }, - } + } // Double provides chat.completions.create, the only member createMessage exercises. - ;(handler as any).client = mockClient + handler["client"] = mockClient as unknown as OpenAI const stream = handler.createMessage(systemPrompt, messages) - const chunks: any[] = [] - for await (const chunk of stream) { - chunks.push(chunk) - } + const chunks = await collectStream(stream) const textChunks = chunks.filter((chunk) => chunk.type === "text") expect(textChunks).toHaveLength(1) @@ -160,15 +174,12 @@ describe("MoonshotHandler", () => { create: vi.fn().mockResolvedValue(mockStream()), }, }, - } + } // Double provides chat.completions.create, the only member createMessage exercises. - ;(handler as any).client = mockClient + handler["client"] = mockClient as unknown as OpenAI const stream = handler.createMessage(systemPrompt, messages) - const chunks: any[] = [] - for await (const chunk of stream) { - chunks.push(chunk) - } + const chunks = await collectStream(stream) const usageChunks = chunks.filter((chunk) => chunk.type === "usage") expect(usageChunks.length).toBeGreaterThan(0) @@ -194,15 +205,12 @@ describe("MoonshotHandler", () => { create: vi.fn().mockResolvedValue(mockStream()), }, }, - } + } // Double provides chat.completions.create, the only member createMessage exercises. - ;(handler as any).client = mockClient + handler["client"] = mockClient as unknown as OpenAI const stream = handler.createMessage(systemPrompt, messages) - const chunks: any[] = [] - for await (const chunk of stream) { - chunks.push(chunk) - } + const chunks = await collectStream(stream) const usageChunks = chunks.filter((chunk) => chunk.type === "usage") expect(usageChunks.length).toBeGreaterThan(0) @@ -221,9 +229,9 @@ describe("MoonshotHandler", () => { }), }, }, - } + } // Double provides chat.completions.create, the only member createMessage exercises. - ;(handler as any).client = mockClient + handler["client"] = mockClient as unknown as OpenAI const result = await handler.completePrompt("Test prompt") @@ -241,7 +249,7 @@ describe("MoonshotHandler", () => { describe("processUsageMetrics", () => { it("should correctly process usage metrics including cache information", () => { class TestMoonshotHandler extends MoonshotHandler { - public testProcessUsageMetrics(usage: any) { + public testProcessUsageMetrics(usage: MoonshotUsage | null | undefined) { return this.processUsageMetrics(usage) } } @@ -267,7 +275,7 @@ describe("MoonshotHandler", () => { it("should handle missing cache metrics gracefully", () => { class TestMoonshotHandler extends MoonshotHandler { - public testProcessUsageMetrics(usage: any) { + public testProcessUsageMetrics(usage: MoonshotUsage | null | undefined) { return this.processUsageMetrics(usage) } } @@ -290,7 +298,7 @@ describe("MoonshotHandler", () => { it("should handle cached_tokens at top level (not in prompt_tokens_details)", () => { class TestMoonshotHandler extends MoonshotHandler { - public testProcessUsageMetrics(usage: any) { + public testProcessUsageMetrics(usage: MoonshotUsage | null | undefined) { return this.processUsageMetrics(usage) } } @@ -310,7 +318,7 @@ describe("MoonshotHandler", () => { it("should handle null usage gracefully", () => { class TestMoonshotHandler extends MoonshotHandler { - public testProcessUsageMetrics(usage: any) { + public testProcessUsageMetrics(usage: MoonshotUsage | null | undefined) { return this.processUsageMetrics(usage) } } @@ -328,13 +336,13 @@ describe("MoonshotHandler", () => { describe("addMaxTokensIfNeeded", () => { it("should use max_tokens (not max_completion_tokens) for Moonshot", () => { class TestMoonshotHandler extends MoonshotHandler { - public testAddMaxTokensIfNeeded(requestOptions: any, modelInfo: any) { + public testAddMaxTokensIfNeeded(requestOptions: MoonshotRequestOptions, modelInfo: ModelInfo) { return this.addMaxTokensIfNeeded(requestOptions, modelInfo) } } const testHandler = new TestMoonshotHandler(mockOptions) - const requestOptions: any = {} + const requestOptions: MoonshotRequestOptions = { model: "kimi-k2", messages: [] } testHandler.testAddMaxTokensIfNeeded(requestOptions, handler.getModel().info) expect(requestOptions.max_tokens).toBe(16384) @@ -343,7 +351,7 @@ describe("MoonshotHandler", () => { it("should use modelMaxTokens override when provided", () => { class TestMoonshotHandler extends MoonshotHandler { - public testAddMaxTokensIfNeeded(requestOptions: any, modelInfo: any) { + public testAddMaxTokensIfNeeded(requestOptions: MoonshotRequestOptions, modelInfo: ModelInfo) { return this.addMaxTokensIfNeeded(requestOptions, modelInfo) } } @@ -353,7 +361,7 @@ describe("MoonshotHandler", () => { ...mockOptions, modelMaxTokens: customMaxTokens, }) - const requestOptions: any = {} + const requestOptions: MoonshotRequestOptions = { model: "kimi-k2", messages: [] } testHandler.testAddMaxTokensIfNeeded(requestOptions, handler.getModel().info) expect(requestOptions.max_tokens).toBe(customMaxTokens) @@ -361,7 +369,7 @@ describe("MoonshotHandler", () => { it("should not send maxTokens for unknown model IDs", () => { class TestMoonshotHandler extends MoonshotHandler { - public testAddMaxTokensIfNeeded(requestOptions: any, modelInfo: any) { + public testAddMaxTokensIfNeeded(requestOptions: MoonshotRequestOptions, modelInfo: ModelInfo) { return this.addMaxTokensIfNeeded(requestOptions, modelInfo) } } @@ -370,7 +378,7 @@ describe("MoonshotHandler", () => { ...mockOptions, apiModelId: "future-moonshot-model", }) - const requestOptions: any = {} + const requestOptions: MoonshotRequestOptions = { model: "kimi-k2", messages: [] } testHandler.testAddMaxTokensIfNeeded(requestOptions, testHandler.getModel().info) expect(requestOptions.max_tokens).toBeUndefined() @@ -417,9 +425,9 @@ describe("MoonshotHandler", () => { create: vi.fn().mockResolvedValue(mockStream()), }, }, - } + } // Double provides chat.completions.create, the only member createMessage exercises. - ;(handler as any).client = mockClient + handler["client"] = mockClient as unknown as OpenAI const stream = handler.createMessage(systemPrompt, messages, { taskId: "test-task", @@ -439,10 +447,7 @@ describe("MoonshotHandler", () => { ], }) - const chunks: any[] = [] - for await (const chunk of stream) { - chunks.push(chunk) - } + const chunks = await collectStream(stream) const partialChunks = chunks.filter((c) => c.type === "tool_call_partial") const endChunks = chunks.filter((c) => c.type === "tool_call_end") diff --git a/src/api/providers/__tests__/native-ollama.spec.ts b/src/api/providers/__tests__/native-ollama.spec.ts index 3f2a5cba4ac..d1c40d05601 100644 --- a/src/api/providers/__tests__/native-ollama.spec.ts +++ b/src/api/providers/__tests__/native-ollama.spec.ts @@ -3,6 +3,7 @@ import { Anthropic } from "@anthropic-ai/sdk" import { NativeOllamaHandler } from "../native-ollama" +import type { ChatRequest } from "ollama" import { ApiHandlerOptions } from "../../../shared/api" import { getOllamaModels } from "../fetchers/ollama" import { MODEL_CATALOG_FETCH_TIMEOUT_MS } from "../fetchers/modelCache" @@ -243,11 +244,11 @@ describe("NativeOllamaHandler", () => { ) // The tool result message itself must not carry an images field. - const callArgs = mockChat.mock.calls[0][0] as any - const toolResultMessage = callArgs.messages.find( - (m: any) => typeof m.content === "string" && m.content.includes("line one"), + const callArgs = mockChat.mock.calls[0][0] as ChatRequest + const toolResultMessage = callArgs.messages!.find( + (m) => typeof m.content === "string" && m.content.includes("line one"), ) - expect(toolResultMessage.images).toBeUndefined() + expect(toolResultMessage!.images).toBeUndefined() }) it("should drop unknown block types in tool_result content (empty string contribution)", async () => { @@ -264,7 +265,9 @@ describe("NativeOllamaHandler", () => { tool_use_id: "tool-1", content: [ { type: "text", text: "before" }, - { type: "document" } as any, + // Extension/Anthropic-protocol history block the converter narrows by `type`; + // routed through unknown to stay inside the tool_result content union. + { type: "document" } as unknown as Anthropic.TextBlockParam, { type: "text", text: "after" }, ], }, @@ -556,7 +559,13 @@ describe("NativeOllamaHandler", () => { { role: "assistant", content: [ - { type: "reasoning", text: "Prior reasoning", summary: [] } as any, + // Extension/Anthropic-protocol history block the converter narrows by `type`; + // routed through unknown to stay inside MessageParam. + { + type: "reasoning", + text: "Prior reasoning", + summary: [], + } as unknown as Anthropic.ContentBlockParam, { type: "text", text: "Prior answer" }, ], }, @@ -589,7 +598,12 @@ describe("NativeOllamaHandler", () => { { role: "assistant", content: [ - { type: "thinking", thinking: "Anthropic thinking text" } as any, + // Extension/Anthropic-protocol history block the converter narrows by `type`; + // routed through unknown to stay inside MessageParam. + { + type: "thinking", + thinking: "Anthropic thinking text", + } as unknown as Anthropic.ContentBlockParam, { type: "text", text: "Prior answer" }, ], }, @@ -622,8 +636,16 @@ describe("NativeOllamaHandler", () => { { role: "assistant", content: [ - { type: "reasoning", text: "First reasoning", summary: [] } as any, - { type: "thinking", thinking: "Second thinking" } as any, + // Extension/Anthropic-protocol history block the converter narrows by `type`; + // routed through unknown to stay inside MessageParam. + { + type: "reasoning", + text: "First reasoning", + summary: [], + } as unknown as Anthropic.ContentBlockParam, + // Extension/Anthropic-protocol history block the converter narrows by `type`; + // routed through unknown to stay inside MessageParam. + { type: "thinking", thinking: "Second thinking" } as unknown as Anthropic.ContentBlockParam, { type: "text", text: "Answer" }, ], }, @@ -656,8 +678,12 @@ describe("NativeOllamaHandler", () => { { role: "assistant", content: [ - { type: "reasoning", text: "", summary: [] } as any, - { type: "thinking", thinking: "" } as any, + // Extension/Anthropic-protocol history block the converter narrows by `type`; + // routed through unknown to stay inside MessageParam. + { type: "reasoning", text: "", summary: [] } as unknown as Anthropic.ContentBlockParam, + // Extension/Anthropic-protocol history block the converter narrows by `type`; + // routed through unknown to stay inside MessageParam. + { type: "thinking", thinking: "" } as unknown as Anthropic.ContentBlockParam, { type: "text", text: "Answer" }, ], }, @@ -725,7 +751,8 @@ describe("NativeOllamaHandler", () => { ollamaModelId: "qwen3", ollamaBaseUrl: "http://localhost:11434", enableReasoningEffort: true, - reasoningEffort: "bogus" as any, + // Deliberately out-of-contract value; exercises the effort fallback path. + reasoningEffort: "bogus" as unknown as ApiHandlerOptions["reasoningEffort"], } handler = new NativeOllamaHandler(options) @@ -1253,8 +1280,7 @@ describe("NativeOllamaHandler", () => { describe("error handling", () => { it("should handle connection refused errors", async () => { - const error = new Error("ECONNREFUSED") as any - error.code = "ECONNREFUSED" + const error = Object.assign(new Error("ECONNREFUSED"), { code: "ECONNREFUSED" }) mockChat.mockRejectedValue(error) const stream = handler.createMessage("System", [{ role: "user" as const, content: "Test" }]) @@ -1265,8 +1291,7 @@ describe("NativeOllamaHandler", () => { }) it("should handle model not found errors", async () => { - const error = new Error("Not found") as any - error.status = 404 + const error = Object.assign(new Error("Not found"), { status: 404 }) mockChat.mockRejectedValue(error) const stream = handler.createMessage("System", [{ role: "user" as const, content: "Test" }]) @@ -1311,8 +1336,7 @@ describe("NativeOllamaHandler", () => { it("should rethrow non-ECONNREFUSED non-404 errors from chat()", async () => { // Covers the fall-through `throw error` branch in the outer catch // when the error is neither ECONNREFUSED nor a 404. - const error = new Error("something else") as any - error.status = 500 + const error = Object.assign(new Error("something else"), { status: 500 }) mockChat.mockRejectedValue(error) const stream = handler.createMessage("System", [{ role: "user" as const, content: "Test" }]) @@ -2058,8 +2082,8 @@ describe("NativeOllamaHandler", () => { ) // Explicitly verify additionalProperties is not present - const callArgs = mockChat.mock.calls[0][0] as any - expect(callArgs.tools[0].function.parameters).not.toHaveProperty("additionalProperties") + const callArgs = mockChat.mock.calls[0][0] as ChatRequest + expect(callArgs.tools![0].function.parameters).not.toHaveProperty("additionalProperties") }) it("should recursively strip additionalProperties from nested tool schema parameters", async () => { @@ -2118,15 +2142,20 @@ describe("NativeOllamaHandler", () => { await collectStream(stream) - const callArgs = mockChat.mock.calls[0][0] as any - const params = callArgs.tools[0].function.parameters + const callArgs = mockChat.mock.calls[0][0] as ChatRequest + // The ollama SDK types tool parameters narrowly; the sanitizer works on the + // full JSON-schema shape the handler builds. + const params = callArgs.tools![0].function.parameters as { + additionalProperties?: unknown + properties?: Record }> + } // Top-level additionalProperties stripped expect(params).not.toHaveProperty("additionalProperties") // Nested additionalProperties also stripped - expect(params.properties.options).not.toHaveProperty("additionalProperties") - expect(params.properties.options.properties.dry_run).toEqual({ type: "boolean" }) + expect(params.properties!.options).not.toHaveProperty("additionalProperties") + expect(params.properties!.options.properties?.dry_run).toEqual({ type: "boolean" }) }) it("should keep tool results text-only and move images onto the adjacent user message", async () => { @@ -2172,17 +2201,17 @@ describe("NativeOllamaHandler", () => { const stream = handler.createMessage("System", messages) await collectStream(stream) - const callArgs = mockChat.mock.calls[0][0] as any + const callArgs = mockChat.mock.calls[0][0] as ChatRequest // The tool result uses the native "tool" role and is text-only. - const toolMessage = callArgs.messages.find((m: any) => m.role === "tool") + const toolMessage = callArgs.messages!.find((m) => m.role === "tool") expect(toolMessage).toBeDefined() - expect(toolMessage.tool_name).toBe("read_file") - expect(toolMessage.images).toBeUndefined() + expect(toolMessage!.tool_name).toBe("read_file") + expect(toolMessage!.images).toBeUndefined() // The image is carried by the adjacent user message. - const userMessage = callArgs.messages.find( - (m: any) => m.role === "user" && Array.isArray(m.images) && m.images.includes("imgdata"), + const userMessage = callArgs.messages!.find( + (m) => m.role === "user" && Array.isArray(m.images) && (m.images as string[]).includes("imgdata"), ) expect(userMessage).toBeDefined() }) @@ -2226,8 +2255,8 @@ describe("NativeOllamaHandler", () => { const stream = handler.createMessage("System", messages) await collectStream(stream) - const callArgs = mockChat.mock.calls[0][0] as any - const toolMessages = callArgs.messages.filter((m: any) => m.role === "tool") + const callArgs = mockChat.mock.calls[0][0] as ChatRequest + const toolMessages = callArgs.messages!.filter((m) => m.role === "tool") // Neither tool result should carry an images field. expect(toolMessages).toHaveLength(2) @@ -2236,7 +2265,7 @@ describe("NativeOllamaHandler", () => { } // The single image is delivered once via the adjacent user message. - const userImageMessages = callArgs.messages.filter((m: any) => m.role === "user" && Array.isArray(m.images)) + const userImageMessages = callArgs.messages!.filter((m) => m.role === "user" && Array.isArray(m.images)) expect(userImageMessages).toHaveLength(1) expect(userImageMessages[0].images).toEqual(["img-a"]) }) 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 39afbbcca7b..d24861f31ba 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 @@ -2,6 +2,9 @@ import { beforeEach, describe, expect, it, vi } from "vitest" +import type { Mock } from "vitest" +import type OpenAI from "openai" +import type { Anthropic } from "@anthropic-ai/sdk" import { OpenAiCodexHandler } from "../openai-codex" import type { ApiHandlerOptions } from "../../../shared/api" import { NativeToolCallParser } from "../../../core/assistant-message/NativeToolCallParser" @@ -10,6 +13,14 @@ import { Package } from "../../../shared/package" import type { ApiStreamChunk } from "../../../api/transform/stream" import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" +/** + * Replaces the handler's OpenAI client with a stub providing responses.create, + * the only member these tests exercise; routed through unknown. + */ +function stubCodexClient(handler: OpenAiCodexHandler, create: Mock): void { + handler["client"] = { responses: { create } } as unknown as OpenAI +} + describe("OpenAiCodexHandler native tool calls", () => { let handler: OpenAiCodexHandler let mockOptions: ApiHandlerOptions @@ -29,51 +40,52 @@ describe("OpenAiCodexHandler native tool calls", () => { vi.spyOn(openAiCodexOAuthManager, "getAccountId").mockResolvedValue("acct_test") // Mock OpenAI SDK streaming (preferred path). - ;(handler as any).client = { - responses: { - create: vi.fn().mockResolvedValue( - asyncStreamFrom([ - { - type: "response.output_item.added", - item: { + const stubCreate = vi.fn().mockResolvedValue( + asyncStreamFrom([ + { + type: "response.output_item.added", + item: { + type: "function_call", + call_id: "call_1", + name: "attempt_completion", + arguments: "", + }, + output_index: 0, + }, + { + type: "response.function_call_arguments.delta", + delta: '{"result":"hi"}', + item_id: "fc_1", + output_index: 0, + }, + { + type: "response.completed", + response: { + id: "resp_1", + status: "completed", + output: [ + { type: "function_call", call_id: "call_1", name: "attempt_completion", - arguments: "", + arguments: '{"result":"hi"}', }, - output_index: 0, - }, - { - type: "response.function_call_arguments.delta", - delta: '{"result":"hi"}', - item_id: "fc_1", - output_index: 0, - }, - { - type: "response.completed", - response: { - id: "resp_1", - status: "completed", - output: [ - { - type: "function_call", - call_id: "call_1", - name: "attempt_completion", - arguments: '{"result":"hi"}', - }, - ], - usage: { input_tokens: 1, output_tokens: 1 }, - }, - }, - ]), - ), - }, - } + ], + usage: { input_tokens: 1, output_tokens: 1 }, + }, + }, + ]), + ) + stubCodexClient(handler, stubCreate) - const stream = handler.createMessage("system", [{ role: "user", content: "hello" } as any], { - taskId: "t", - tools: [], - }) + const stream = handler.createMessage( + "system", + [{ role: "user", content: "hello" }] as Anthropic.Messages.MessageParam[], + { + taskId: "t", + tools: [], + }, + ) const parserScope = NativeToolCallParser.createScope() const chunks: ApiStreamChunk[] = [] @@ -105,43 +117,44 @@ describe("OpenAiCodexHandler native tool calls", () => { it("yields text when Codex emits assistant message only in response.output_item.done", async () => { vi.spyOn(openAiCodexOAuthManager, "getAccessToken").mockResolvedValue("test-token") vi.spyOn(openAiCodexOAuthManager, "getAccountId").mockResolvedValue("acct_test") - ;(handler as any).client = { - responses: { - create: vi.fn().mockResolvedValue( - asyncStreamFrom([ - { - type: "response.output_item.done", - item: { + const stubCreate = vi.fn().mockResolvedValue( + asyncStreamFrom([ + { + type: "response.output_item.done", + item: { + type: "message", + role: "assistant", + content: [{ type: "output_text", text: "hello from spark" }], + }, + output_index: 0, + }, + { + type: "response.completed", + response: { + id: "resp_done_only", + status: "completed", + output: [ + { type: "message", role: "assistant", content: [{ type: "output_text", text: "hello from spark" }], }, - output_index: 0, - }, - { - type: "response.completed", - response: { - id: "resp_done_only", - status: "completed", - output: [ - { - type: "message", - role: "assistant", - content: [{ type: "output_text", text: "hello from spark" }], - }, - ], - usage: { input_tokens: 1, output_tokens: 2 }, - }, - }, - ]), - ), - }, - } + ], + usage: { input_tokens: 1, output_tokens: 2 }, + }, + }, + ]), + ) + stubCodexClient(handler, stubCreate) - const stream = handler.createMessage("system", [{ role: "user", content: "test" } as any], { - taskId: "t", - tools: [], - }) + const stream = handler.createMessage( + "system", + [{ role: "user", content: "test" }] as Anthropic.Messages.MessageParam[], + { + taskId: "t", + tools: [], + }, + ) const chunks = await collectStream(stream) @@ -153,34 +166,35 @@ describe("OpenAiCodexHandler native tool calls", () => { it("yields text when Codex emits assistant message only in response.completed output", async () => { vi.spyOn(openAiCodexOAuthManager, "getAccessToken").mockResolvedValue("test-token") vi.spyOn(openAiCodexOAuthManager, "getAccountId").mockResolvedValue("acct_test") - ;(handler as any).client = { - responses: { - create: vi.fn().mockResolvedValue( - asyncStreamFrom([ - { - type: "response.completed", - response: { - id: "resp_completed_only", - status: "completed", - output: [ - { - type: "message", - role: "assistant", - content: [{ type: "output_text", text: "final payload only" }], - }, - ], - usage: { input_tokens: 1, output_tokens: 2 }, + const stubCreate = vi.fn().mockResolvedValue( + asyncStreamFrom([ + { + type: "response.completed", + response: { + id: "resp_completed_only", + status: "completed", + output: [ + { + type: "message", + role: "assistant", + content: [{ type: "output_text", text: "final payload only" }], }, - }, - ]), - ), - }, - } + ], + usage: { input_tokens: 1, output_tokens: 2 }, + }, + }, + ]), + ) + stubCodexClient(handler, stubCreate) - const stream = handler.createMessage("system", [{ role: "user", content: "test" } as any], { - taskId: "t", - tools: [], - }) + const stream = handler.createMessage( + "system", + [{ role: "user", content: "test" }] as Anthropic.Messages.MessageParam[], + { + taskId: "t", + tools: [], + }, + ) const chunks = await collectStream(stream) @@ -192,32 +206,33 @@ describe("OpenAiCodexHandler native tool calls", () => { it("yields text when Codex emits response.output_text.done without deltas", async () => { vi.spyOn(openAiCodexOAuthManager, "getAccessToken").mockResolvedValue("test-token") vi.spyOn(openAiCodexOAuthManager, "getAccountId").mockResolvedValue("acct_test") - ;(handler as any).client = { - responses: { - create: vi.fn().mockResolvedValue( - asyncStreamFrom([ - { - type: "response.output_text.done", - text: "done-event text only", - }, - { - type: "response.completed", - response: { - id: "resp_done_text_only", - status: "completed", - output: [], - usage: { input_tokens: 1, output_tokens: 2 }, - }, - }, - ]), - ), - }, - } + const stubCreate = vi.fn().mockResolvedValue( + asyncStreamFrom([ + { + type: "response.output_text.done", + text: "done-event text only", + }, + { + type: "response.completed", + response: { + id: "resp_done_text_only", + status: "completed", + output: [], + usage: { input_tokens: 1, output_tokens: 2 }, + }, + }, + ]), + ) + stubCodexClient(handler, stubCreate) - const stream = handler.createMessage("system", [{ role: "user", content: "test" } as any], { - taskId: "t", - tools: [], - }) + const stream = handler.createMessage( + "system", + [{ role: "user", content: "test" }] as Anthropic.Messages.MessageParam[], + { + taskId: "t", + tools: [], + }, + ) const chunks = await collectStream(stream) @@ -229,38 +244,39 @@ describe("OpenAiCodexHandler native tool calls", () => { it("yields tool_call when Codex emits function_call only in response.output_item.done", async () => { vi.spyOn(openAiCodexOAuthManager, "getAccessToken").mockResolvedValue("test-token") vi.spyOn(openAiCodexOAuthManager, "getAccountId").mockResolvedValue("acct_test") - ;(handler as any).client = { - responses: { - create: vi.fn().mockResolvedValue( - asyncStreamFrom([ - { - type: "response.output_item.done", - item: { - type: "function_call", - call_id: "call_done_only", - name: "attempt_completion", - arguments: '{"result":"ok"}', - }, - output_index: 0, - }, - { - type: "response.completed", - response: { - id: "resp_done_tool_only", - status: "completed", - output: [], - usage: { input_tokens: 1, output_tokens: 2 }, - }, - }, - ]), - ), - }, - } + const stubCreate = vi.fn().mockResolvedValue( + asyncStreamFrom([ + { + type: "response.output_item.done", + item: { + type: "function_call", + call_id: "call_done_only", + name: "attempt_completion", + arguments: '{"result":"ok"}', + }, + output_index: 0, + }, + { + type: "response.completed", + response: { + id: "resp_done_tool_only", + status: "completed", + output: [], + usage: { input_tokens: 1, output_tokens: 2 }, + }, + }, + ]), + ) + stubCodexClient(handler, stubCreate) - const stream = handler.createMessage("system", [{ role: "user", content: "test" } as any], { - taskId: "t", - tools: [], - }) + const stream = handler.createMessage( + "system", + [{ role: "user", content: "test" }] as Anthropic.Messages.MessageParam[], + { + taskId: "t", + tools: [], + }, + ) const chunks = await collectStream(stream) @@ -276,37 +292,38 @@ describe("OpenAiCodexHandler native tool calls", () => { it("yields text when Codex emits response.content_part.added", async () => { vi.spyOn(openAiCodexOAuthManager, "getAccessToken").mockResolvedValue("test-token") vi.spyOn(openAiCodexOAuthManager, "getAccountId").mockResolvedValue("acct_test") - ;(handler as any).client = { - responses: { - create: vi.fn().mockResolvedValue( - asyncStreamFrom([ - { - type: "response.content_part.added", - part: { - type: "output_text", - text: "content part text", - }, - output_index: 0, - content_index: 0, - }, - { - type: "response.completed", - response: { - id: "resp_content_part", - status: "completed", - output: [], - usage: { input_tokens: 1, output_tokens: 2 }, - }, - }, - ]), - ), - }, - } + const stubCreate = vi.fn().mockResolvedValue( + asyncStreamFrom([ + { + type: "response.content_part.added", + part: { + type: "output_text", + text: "content part text", + }, + output_index: 0, + content_index: 0, + }, + { + type: "response.completed", + response: { + id: "resp_content_part", + status: "completed", + output: [], + usage: { input_tokens: 1, output_tokens: 2 }, + }, + }, + ]), + ) + stubCodexClient(handler, stubCreate) - const stream = handler.createMessage("system", [{ role: "user", content: "test" } as any], { - taskId: "t", - tools: [], - }) + const stream = handler.createMessage( + "system", + [{ role: "user", content: "test" }] as Anthropic.Messages.MessageParam[], + { + taskId: "t", + tools: [], + }, + ) const chunks = await collectStream(stream) @@ -318,31 +335,32 @@ describe("OpenAiCodexHandler native tool calls", () => { it("does not duplicate text when Codex emits delta and output_text.done", async () => { vi.spyOn(openAiCodexOAuthManager, "getAccessToken").mockResolvedValue("test-token") vi.spyOn(openAiCodexOAuthManager, "getAccountId").mockResolvedValue("acct_test") - ;(handler as any).client = { - responses: { - create: vi.fn().mockResolvedValue( - asyncStreamFrom([ - { type: "response.output_text.delta", delta: "hello " }, - { type: "response.output_text.delta", delta: "world" }, - { type: "response.output_text.done", text: "hello world" }, - { - type: "response.completed", - response: { - id: "resp_delta_done", - status: "completed", - output: [], - usage: { input_tokens: 1, output_tokens: 2 }, - }, - }, - ]), - ), - }, - } + const stubCreate = vi.fn().mockResolvedValue( + asyncStreamFrom([ + { type: "response.output_text.delta", delta: "hello " }, + { type: "response.output_text.delta", delta: "world" }, + { type: "response.output_text.done", text: "hello world" }, + { + type: "response.completed", + response: { + id: "resp_delta_done", + status: "completed", + output: [], + usage: { input_tokens: 1, output_tokens: 2 }, + }, + }, + ]), + ) + stubCodexClient(handler, stubCreate) - const stream = handler.createMessage("system", [{ role: "user", content: "test" } as any], { - taskId: "t", - tools: [], - }) + const stream = handler.createMessage( + "system", + [{ role: "user", content: "test" }] as Anthropic.Messages.MessageParam[], + { + taskId: "t", + tools: [], + }, + ) const chunks = await collectStream(stream) @@ -353,35 +371,36 @@ describe("OpenAiCodexHandler native tool calls", () => { it("does not duplicate text when Codex emits delta and content_part.added", async () => { vi.spyOn(openAiCodexOAuthManager, "getAccessToken").mockResolvedValue("test-token") vi.spyOn(openAiCodexOAuthManager, "getAccountId").mockResolvedValue("acct_test") - ;(handler as any).client = { - responses: { - create: vi.fn().mockResolvedValue( - asyncStreamFrom([ - { type: "response.output_text.delta", delta: "hello world" }, - { - type: "response.content_part.added", - part: { type: "output_text", text: "hello world" }, - output_index: 0, - content_index: 0, - }, - { - type: "response.completed", - response: { - id: "resp_delta_content_part", - status: "completed", - output: [], - usage: { input_tokens: 1, output_tokens: 2 }, - }, - }, - ]), - ), - }, - } + const stubCreate = vi.fn().mockResolvedValue( + asyncStreamFrom([ + { type: "response.output_text.delta", delta: "hello world" }, + { + type: "response.content_part.added", + part: { type: "output_text", text: "hello world" }, + output_index: 0, + content_index: 0, + }, + { + type: "response.completed", + response: { + id: "resp_delta_content_part", + status: "completed", + output: [], + usage: { input_tokens: 1, output_tokens: 2 }, + }, + }, + ]), + ) + stubCodexClient(handler, stubCreate) - const stream = handler.createMessage("system", [{ role: "user", content: "test" } as any], { - taskId: "t", - tools: [], - }) + const stream = handler.createMessage( + "system", + [{ role: "user", content: "test" }] as Anthropic.Messages.MessageParam[], + { + taskId: "t", + tools: [], + }, + ) const chunks = await collectStream(stream) @@ -407,12 +426,16 @@ describe("OpenAiCodexHandler native tool calls", () => { }, ]), ) - ;(handler as any).client = { responses: { create: mockCreate } } + stubCodexClient(handler, mockCreate) - const stream = handler.createMessage("system", [{ role: "user", content: "headers" } as any], { - taskId: "task-123", - tools: [], - }) + const stream = handler.createMessage( + "system", + [{ role: "user", content: "headers" }] as Anthropic.Messages.MessageParam[], + { + taskId: "task-123", + tools: [], + }, + ) await collectStream(stream) expect(mockCreate).toHaveBeenCalledWith( @@ -432,33 +455,37 @@ describe("OpenAiCodexHandler native tool calls", () => { vi.spyOn(openAiCodexOAuthManager, "getAccessToken").mockResolvedValue("test-token") vi.spyOn(openAiCodexOAuthManager, "getAccountId").mockResolvedValue("acct_test") - const mockFetch = vi.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode('data: {"type":"response.output_text.delta","delta":"fallback"}\n\n'), - ) - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.completed","response":{"id":"resp_fetch_headers","status":"completed","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}\n\n', - ), - ) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any - ;(handler as any).client = { - responses: { - create: vi.fn().mockRejectedValue(new Error("SDK unavailable")), - }, - } + const mockFetch = vi.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_text.delta","delta":"fallback"}\n\n', + ), + ) + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.completed","response":{"id":"resp_fetch_headers","status":"completed","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}\n\n', + ), + ) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch + const stubCreate = vi.fn().mockRejectedValue(new Error("SDK unavailable")) + stubCodexClient(handler, stubCreate) - const stream = handler.createMessage("system", [{ role: "user", content: "fallback" } as any], { - taskId: "task-456", - tools: [], - }) + const stream = handler.createMessage( + "system", + [{ role: "user", content: "fallback" }] as Anthropic.Messages.MessageParam[], + { + taskId: "task-456", + tools: [], + }, + ) await collectStream(stream) expect(mockFetch).toHaveBeenCalledWith( @@ -483,23 +510,24 @@ describe("OpenAiCodexHandler native tool calls", () => { Reflect.set(handler, "client", { responses: { create: vi.fn().mockRejectedValue(new Error("SDK unavailable")) }, }) - const mockFetch = vi.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode('data: {"type":"response.output_text.delta","delta":"done"}\n\n'), - ) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vi.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode('data: {"type":"response.output_text.delta","delta":"done"}\n\n'), + ) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch await expect(handler.completePrompt("Test prompt")).resolves.toBe("done") - const fetchOptions = mockFetch.mock.calls[0][1] - const body = JSON.parse(fetchOptions.body) + const fetchOptions = mockFetch.mock.calls[0]![1] + const body = JSON.parse(fetchOptions!.body as string) expect(body.input).toEqual([ { role: "user", @@ -510,10 +538,10 @@ describe("OpenAiCodexHandler native tool calls", () => { expect(body.reasoning?.context).toBeUndefined() expect(body.input).not.toContainEqual(expect.objectContaining({ type: "additional_tools" })) expect(body.input).not.toContainEqual(expect.objectContaining({ role: "developer" })) - expect(fetchOptions.headers).not.toHaveProperty("session-id") - expect(fetchOptions.headers).not.toHaveProperty("x-session-affinity") - expect(fetchOptions.headers).not.toHaveProperty("version") - expect(fetchOptions.headers).not.toHaveProperty("x-openai-internal-codex-responses-lite") + expect(fetchOptions!.headers).not.toHaveProperty("session-id") + expect(fetchOptions!.headers).not.toHaveProperty("x-session-affinity") + expect(fetchOptions!.headers).not.toHaveProperty("version") + expect(fetchOptions!.headers).not.toHaveProperty("x-openai-internal-codex-responses-lite") expect(mockFetch).toHaveBeenCalledWith( expect.stringContaining("/responses"), expect.objectContaining({ diff --git a/src/api/providers/__tests__/openai-codex.spec.ts b/src/api/providers/__tests__/openai-codex.spec.ts index 216bf07c411..897249d6533 100644 --- a/src/api/providers/__tests__/openai-codex.spec.ts +++ b/src/api/providers/__tests__/openai-codex.spec.ts @@ -15,6 +15,32 @@ import { OpenAiCodexHandler, transformResponsesLiteBody } from "../openai-codex" import { openAiCodexOAuthManager } from "../../../integrations/openai-codex/oauth" import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" import { flushMacrotasks } from "../../../test-utils/timers" +import type { Mock, MockInstance } from "vitest" +import type OpenAI from "openai" + +/** Mirror of the codex Responses request-body shape the tests capture. */ +interface ResponsesRequestBody { + input?: ResponseInputItemTest[] + [key: string]: unknown +} + +/** Input item carrying the `role` field the assertions read. */ +interface ResponseInputItemTest { + role?: string + content?: unknown +} + +interface UserInputItem extends ResponseInputItemTest { + role: "user" +} + +/** + * Replaces the handler's OpenAI client with a stub providing responses.create, + * the only member these tests exercise; routed through unknown. + */ +function stubCodexClient(handler: OpenAiCodexHandler, create: Mock): void { + handler["client"] = { responses: { create } } as unknown as OpenAI +} function createCompletedStream() { return asyncStreamFrom([ @@ -173,32 +199,29 @@ describe("OpenAiCodexHandler.createMessage", () => { vitest.spyOn(openAiCodexOAuthManager, "getAccessToken").mockResolvedValue("test-token") vitest.spyOn(openAiCodexOAuthManager, "getAccountId").mockResolvedValue("acct_test") - const capturedInput: any[] = [] - ;(handler as any).client = { - responses: { - create: vitest.fn().mockImplementation(async (body: any) => { - capturedInput.push(...(body.input ?? [])) - return asyncStreamFrom([ - { - type: "response.completed", - response: { - id: "r1", - status: "completed", - output: [], - usage: { input_tokens: 1, output_tokens: 1 }, - }, - }, - ]) - }), - }, - } + const capturedInput: ResponseInputItemTest[] = [] + const stubCreate = vitest.fn().mockImplementation(async (body: ResponsesRequestBody) => { + capturedInput.push(...(body.input ?? [])) + return asyncStreamFrom([ + { + type: "response.completed", + response: { + id: "r1", + status: "completed", + output: [], + usage: { input_tokens: 1, output_tokens: 1 }, + }, + }, + ]) + }) + stubCodexClient(handler, stubCreate) const messages: Anthropic.Messages.MessageParam[] = [ { role: "user", content: [ { type: "text", text: "Look at this:" }, - { type: "image", source: { type: "url", url: "https://example.com/img.png" } as any }, + { type: "image", source: { type: "url", url: "https://example.com/img.png" } }, ], }, ] @@ -206,7 +229,7 @@ describe("OpenAiCodexHandler.createMessage", () => { await collectStream(handler.createMessage("system", messages)) // URL image is skipped; only the text input_text block should be present - const userMsg = capturedInput.find((item: any) => item.role === "user") + const userMsg = capturedInput.find((item): item is UserInputItem => item.role === "user") expect(userMsg?.content).toEqual([{ type: "input_text", text: "Look at this:" }]) expect(JSON.stringify(capturedInput)).not.toContain("input_image") }) @@ -217,25 +240,22 @@ describe("OpenAiCodexHandler.createMessage", () => { vitest.spyOn(openAiCodexOAuthManager, "getAccessToken").mockResolvedValue("test-token") vitest.spyOn(openAiCodexOAuthManager, "getAccountId").mockResolvedValue("acct_test") - const capturedInput: any[] = [] - ;(handler as any).client = { - responses: { - create: vitest.fn().mockImplementation(async (body: any) => { - capturedInput.push(...(body.input ?? [])) - return asyncStreamFrom([ - { - type: "response.completed", - response: { - id: "r1", - status: "completed", - output: [], - usage: { input_tokens: 1, output_tokens: 1 }, - }, - }, - ]) - }), - }, - } + const capturedInput: ResponseInputItemTest[] = [] + const stubCreate = vitest.fn().mockImplementation(async (body: ResponsesRequestBody) => { + capturedInput.push(...(body.input ?? [])) + return asyncStreamFrom([ + { + type: "response.completed", + response: { + id: "r1", + status: "completed", + output: [], + usage: { input_tokens: 1, output_tokens: 1 }, + }, + }, + ]) + }) + stubCodexClient(handler, stubCreate) const messages: Anthropic.Messages.MessageParam[] = [ { @@ -249,7 +269,7 @@ describe("OpenAiCodexHandler.createMessage", () => { await collectStream(handler.createMessage("system", messages)) - const userMsg = capturedInput.find((item: any) => item.role === "user") + const userMsg = capturedInput.find((item): item is UserInputItem => item.role === "user") expect(userMsg?.content).toContainEqual({ type: "input_image", image_url: "data:image/png;base64,abc123", @@ -894,7 +914,7 @@ describe("OpenAiCodexHandler Responses Lite requests", () => { vitest.spyOn(openAiCodexOAuthManager, "getAccessToken").mockResolvedValue("test-token") vitest.spyOn(openAiCodexOAuthManager, "getAccountId").mockResolvedValue("acct_test") const mockCreate = vitest.fn().mockResolvedValue(createCompletedStream()) - ;(handler as any).client = { responses: { create: mockCreate } } + stubCodexClient(handler, mockCreate) await collectStream( handler.createMessage("Luna instructions", [{ role: "user", content: "Hello" }], { @@ -950,12 +970,12 @@ describe("OpenAiCodexHandler Responses Lite requests", () => { const handler = new OpenAiCodexHandler({ apiModelId: "gpt-5.6-luna" }) vitest.spyOn(openAiCodexOAuthManager, "getAccessToken").mockResolvedValue("test-token") vitest.spyOn(openAiCodexOAuthManager, "getAccountId").mockResolvedValue("acct_test") - let sdkBody: any - const mockCreate = vitest.fn().mockImplementation((body: any) => { + let sdkBody: ResponsesRequestBody | undefined + const mockCreate = vitest.fn().mockImplementation((body: ResponsesRequestBody) => { sdkBody = body throw new Error("SDK unavailable") }) - ;(handler as any).client = { responses: { create: mockCreate } } + stubCodexClient(handler, mockCreate) const mockFetch = vitest.fn().mockResolvedValue({ ok: true, body: new ReadableStream({ @@ -988,18 +1008,19 @@ describe("OpenAiCodexHandler Responses Lite requests", () => { version: "0.144.0", "x-openai-internal-codex-responses-lite": "true", }) - expect(sdkBody.prompt_cache_key).toBe("task-fallback") + expect(sdkBody!.prompt_cache_key).toBe("task-fallback") }) it("preserves Luna session affinity while retrying with refreshed authentication", async () => { const handler = new OpenAiCodexHandler({ apiModelId: "gpt-5.6-luna" }) - const transformSpy = vitest.spyOn(handler as any, "buildResponsesLiteRequestBody") + // Spies on the private Lite-transform; the method name routes through never + // because private members are outside keyof, and the bound behavior is unchanged. + const transformSpy = vitest.spyOn(handler, "buildResponsesLiteRequestBody" as never) as MockInstance vitest.spyOn(openAiCodexOAuthManager, "getAccessToken").mockResolvedValue("expired-token") vitest.spyOn(openAiCodexOAuthManager, "forceRefreshAccessToken").mockResolvedValue("refreshed-token") vitest.spyOn(openAiCodexOAuthManager, "getAccountId").mockResolvedValue("acct_test") - ;(handler as any).client = { - responses: { create: vitest.fn().mockRejectedValue(new Error("SDK unavailable")) }, - } + const stubCreate = vitest.fn().mockRejectedValue(new Error("SDK unavailable")) + stubCodexClient(handler, stubCreate) const mockFetch = vitest .fn() .mockResolvedValueOnce({ @@ -1104,7 +1125,7 @@ describe("OpenAiCodexHandler Responses Lite requests", () => { vitest.spyOn(openAiCodexOAuthManager, "getAccessToken").mockResolvedValue("test-token") vitest.spyOn(openAiCodexOAuthManager, "getAccountId").mockResolvedValue("acct_test") const mockCreate = vitest.fn().mockResolvedValue(createCompletedStream()) - ;(handler as any).client = { responses: { create: mockCreate } } + stubCodexClient(handler, mockCreate) await collectStream( handler.createMessage("Normal instructions", [{ role: "user", content: "Hello" }], { diff --git a/src/api/providers/__tests__/openai-native-tools.spec.ts b/src/api/providers/__tests__/openai-native-tools.spec.ts index 8bacca0dbdb..e25be0df26a 100644 --- a/src/api/providers/__tests__/openai-native-tools.spec.ts +++ b/src/api/providers/__tests__/openai-native-tools.spec.ts @@ -1,3 +1,4 @@ +import type { Anthropic } from "@anthropic-ai/sdk" import OpenAI from "openai" import { OpenAiHandler } from "../openai" @@ -5,6 +6,31 @@ import { OpenAiNativeHandler } from "../openai-native" import type { ApiHandlerOptions } from "../../../shared/api" import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" +/** MCP tool schema shape this suite asserts on. */ +interface McpParameterSchema { + additionalProperties?: unknown + properties?: Record + required?: string[] + items?: { additionalProperties?: unknown } + [key: string]: unknown +} + +interface McpToolSchema { + name?: string + strict?: boolean + parameters?: McpParameterSchema +} + +/** Native Responses stream event doubles fed through the handler. */ +interface NativeStreamEvent { + type?: string + delta?: string + text?: string + item?: Record + response?: Record + [key: string]: unknown +} + describe("OpenAiHandler native tools", () => { it("includes tools in request when tools are provided via metadata (regression test)", async () => { const mockCreate = vi @@ -67,7 +93,7 @@ describe("OpenAiHandler native tools", () => { describe("OpenAiNativeHandler MCP tool schema handling", () => { it("should add additionalProperties: false to MCP tools while keeping strict: false", async () => { - let capturedRequestBody: any + let capturedRequestBody: { tools?: McpToolSchema[] } | undefined const handler = new OpenAiNativeHandler({ openAiNativeApiKey: "test-key", @@ -77,7 +103,7 @@ describe("OpenAiNativeHandler MCP tool schema handling", () => { // Mock the responses API call const mockClient = { responses: { - create: vi.fn().mockImplementation((body: any) => { + create: vi.fn().mockImplementation((body: Record) => { capturedRequestBody = body return asyncStreamFrom([ { @@ -91,7 +117,7 @@ describe("OpenAiNativeHandler MCP tool schema handling", () => { }), }, } - ;(handler as any).client = mockClient + handler["client"] = mockClient as unknown as OpenAI const mcpTools: OpenAI.Chat.ChatCompletionTool[] = [ { @@ -118,18 +144,18 @@ describe("OpenAiNativeHandler MCP tool schema handling", () => { await collectStream(stream) // Verify the request body - expect(capturedRequestBody.tools).toBeDefined() - expect(capturedRequestBody.tools.length).toBe(1) + expect(capturedRequestBody!.tools).toBeDefined() + expect(capturedRequestBody!.tools!.length).toBe(1) - const tool = capturedRequestBody.tools[0] + const tool = capturedRequestBody!.tools![0] expect(tool.name).toBe("mcp--github--get_me") expect(tool.strict).toBe(false) // MCP tools should have strict: false - expect(tool.parameters.additionalProperties).toBe(false) // Should have additionalProperties: false - expect(tool.parameters.required).toEqual(["token"]) // Should preserve original required array + expect(tool.parameters!.additionalProperties).toBe(false) // Should have additionalProperties: false + expect(tool.parameters!.required).toEqual(["token"]) // Should preserve original required array }) it("should add additionalProperties: false and required array to non-MCP tools with strict: true", async () => { - let capturedRequestBody: any + let capturedRequestBody: { tools?: McpToolSchema[] } | undefined const handler = new OpenAiNativeHandler({ openAiNativeApiKey: "test-key", @@ -139,7 +165,7 @@ describe("OpenAiNativeHandler MCP tool schema handling", () => { // Mock the responses API call const mockClient = { responses: { - create: vi.fn().mockImplementation((body: any) => { + create: vi.fn().mockImplementation((body: Record) => { capturedRequestBody = body return asyncStreamFrom([ { @@ -153,7 +179,7 @@ describe("OpenAiNativeHandler MCP tool schema handling", () => { }), }, } - ;(handler as any).client = mockClient + handler["client"] = mockClient as unknown as OpenAI const regularTools: OpenAI.Chat.ChatCompletionTool[] = [ { @@ -180,18 +206,18 @@ describe("OpenAiNativeHandler MCP tool schema handling", () => { await collectStream(stream) // Verify the request body - expect(capturedRequestBody.tools).toBeDefined() - expect(capturedRequestBody.tools.length).toBe(1) + expect(capturedRequestBody!.tools).toBeDefined() + expect(capturedRequestBody!.tools!.length).toBe(1) - const tool = capturedRequestBody.tools[0] + const tool = capturedRequestBody!.tools![0] expect(tool.name).toBe("read_file") expect(tool.strict).toBe(true) // Non-MCP tools should have strict: true - expect(tool.parameters.additionalProperties).toBe(false) // Should have additionalProperties: false - expect(tool.parameters.required).toEqual(["path", "encoding"]) // Should have all properties as required + expect(tool.parameters!.additionalProperties).toBe(false) // Should have additionalProperties: false + expect(tool.parameters!.required).toEqual(["path", "encoding"]) // Should have all properties as required }) it("should recursively add additionalProperties: false to nested objects in MCP tools", async () => { - let capturedRequestBody: any + let capturedRequestBody: { tools?: McpToolSchema[] } | undefined const handler = new OpenAiNativeHandler({ openAiNativeApiKey: "test-key", @@ -201,7 +227,7 @@ describe("OpenAiNativeHandler MCP tool schema handling", () => { // Mock the responses API call const mockClient = { responses: { - create: vi.fn().mockImplementation((body: any) => { + create: vi.fn().mockImplementation((body: Record) => { capturedRequestBody = body return asyncStreamFrom([ { @@ -215,7 +241,7 @@ describe("OpenAiNativeHandler MCP tool schema handling", () => { }), }, } - ;(handler as any).client = mockClient + handler["client"] = mockClient as unknown as OpenAI const mcpToolsWithNestedObjects: OpenAI.Chat.ChatCompletionTool[] = [ { @@ -256,11 +282,11 @@ describe("OpenAiNativeHandler MCP tool schema handling", () => { await collectStream(stream) // Verify the request body - const tool = capturedRequestBody.tools[0] + const tool = capturedRequestBody!.tools![0] expect(tool.strict).toBe(false) // MCP tool should have strict: false - expect(tool.parameters.additionalProperties).toBe(false) // Root level - expect(tool.parameters.properties.metadata.additionalProperties).toBe(false) // Nested object - expect(tool.parameters.properties.metadata.properties.labels.items.additionalProperties).toBe(false) // Array items + expect(tool.parameters!.additionalProperties).toBe(false) // Root level + expect(tool.parameters!.properties!.metadata!.additionalProperties).toBe(false) // Nested object + expect(tool.parameters!.properties!.metadata!.properties!.labels!.items!.additionalProperties).toBe(false) // Array items }) it("should handle missing call_id and name in tool_call_arguments.delta by using pending tool identity", async () => { @@ -303,7 +329,7 @@ describe("OpenAiNativeHandler MCP tool schema handling", () => { }), }, } - ;(handler as any).client = mockClient + handler["client"] = mockClient as unknown as OpenAI const stream = handler.createMessage("system prompt", [], { taskId: "test-task-id", @@ -330,27 +356,31 @@ describe("OpenAiNativeHandler MCP tool schema handling", () => { }) describe("OpenAiNativeHandler done-event fallbacks", () => { - const createHandlerWithEvents = (events: any[]) => { + const createHandlerWithEvents = (events: NativeStreamEvent[]) => { const handler = new OpenAiNativeHandler({ openAiNativeApiKey: "test-key", apiModelId: "gpt-4o", } as ApiHandlerOptions) - ;(handler as any).client = { + handler["client"] = { responses: { create: vi.fn().mockResolvedValue(asyncStreamFrom(events)), }, - } + } as unknown as OpenAI return handler } - const collectChunksFromEvents = async (events: any[]) => { + const collectChunksFromEvents = async (events: NativeStreamEvent[]) => { const handler = createHandlerWithEvents(events) - const stream = handler.createMessage("system", [{ role: "user", content: "test" } as any], { - taskId: "t", - tools: [], - }) + const stream = handler.createMessage( + "system", + [{ role: "user", content: "test" }] as Anthropic.Messages.MessageParam[], + { + taskId: "t", + tools: [], + }, + ) return collectStream(stream) } diff --git a/src/api/providers/__tests__/openai-native-usage.spec.ts b/src/api/providers/__tests__/openai-native-usage.spec.ts index b79145efdd5..499e4370a24 100644 --- a/src/api/providers/__tests__/openai-native-usage.spec.ts +++ b/src/api/providers/__tests__/openai-native-usage.spec.ts @@ -34,7 +34,7 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { }, } - const result = (handler as any).normalizeUsage(usage, mockModel) + const result = handler["normalizeUsage"](usage, mockModel) expect(result).toMatchObject({ type: "usage", @@ -55,7 +55,7 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { }, } - const result = (handler as any).normalizeUsage(usage, mockModel) + const result = handler["normalizeUsage"](usage, mockModel) expect(result).toMatchObject({ type: "usage", @@ -76,7 +76,7 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { }, } - const result = (handler as any).normalizeUsage(usage, mockModel) + const result = handler["normalizeUsage"](usage, mockModel) expect(result).toMatchObject({ type: "usage", @@ -98,7 +98,7 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { }, } - const result = (handler as any).normalizeUsage(usage, mockModel) + const result = handler["normalizeUsage"](usage, mockModel) expect(result).toMatchObject({ type: "usage", @@ -157,7 +157,7 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { }, } - const result = (handler as any).normalizeUsage(usage, mockModel) + const result = handler["normalizeUsage"](usage, mockModel) expect(result).toMatchObject({ type: "usage", @@ -177,7 +177,7 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { cache_read_input_tokens: 30, } - const result = (handler as any).normalizeUsage(usage, mockModel) + const result = handler["normalizeUsage"](usage, mockModel) expect(result).toMatchObject({ type: "usage", @@ -196,7 +196,7 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { cache_read_tokens: 30, } - const result = (handler as any).normalizeUsage(usage, mockModel) + const result = handler["normalizeUsage"](usage, mockModel) expect(result).toMatchObject({ type: "usage", @@ -214,7 +214,7 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { cached_tokens: 30, } - const result = (handler as any).normalizeUsage(usage, mockModel) + const result = handler["normalizeUsage"](usage, mockModel) expect(result).toMatchObject({ type: "usage", @@ -230,7 +230,7 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { completion_tokens: 50, } - const result = (handler as any).normalizeUsage(usage, mockModel) + const result = handler["normalizeUsage"](usage, mockModel) expect(result).toMatchObject({ type: "usage", @@ -249,7 +249,7 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { output_tokens: 50, } - const result = (handler as any).normalizeUsage(usage, mockModel) + const result = handler["normalizeUsage"](usage, mockModel) expect(result).toMatchObject({ type: "usage", @@ -266,7 +266,7 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { completion_tokens: 50, } - const result = (handler as any).normalizeUsage(usage, mockModel) + const result = handler["normalizeUsage"](usage, mockModel) expect(result).toMatchObject({ type: "usage", @@ -280,19 +280,19 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { describe("edge cases", () => { it("should handle undefined usage", () => { - const result = (handler as any).normalizeUsage(undefined, mockModel) + const result = handler["normalizeUsage"](undefined, mockModel) expect(result).toBeUndefined() }) it("should handle null usage", () => { - const result = (handler as any).normalizeUsage(null, mockModel) + const result = handler["normalizeUsage"](null, mockModel) expect(result).toBeUndefined() }) it("should handle empty usage object", () => { const usage = {} - const result = (handler as any).normalizeUsage(usage, mockModel) + const result = handler["normalizeUsage"](usage, mockModel) expect(result).toMatchObject({ type: "usage", @@ -311,7 +311,7 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { // No input_tokens_details } - const result = (handler as any).normalizeUsage(usage, mockModel) + const result = handler["normalizeUsage"](usage, mockModel) expect(result).toMatchObject({ type: "usage", @@ -333,7 +333,7 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { }, } - const result = (handler as any).normalizeUsage(usage, mockModel) + const result = handler["normalizeUsage"](usage, mockModel) // The implementation uses nullish coalescing, so it will use the first non-nullish value: // cache_read_input_tokens ?? cache_read_tokens ?? cached_tokens ?? cachedFromDetails @@ -358,7 +358,7 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { }, } - const result = (handler as any).normalizeUsage(usage, mockModel) + const result = handler["normalizeUsage"](usage, mockModel) expect(result).toMatchObject({ type: "usage", @@ -379,7 +379,7 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { }, } - const result = (handler as any).normalizeUsage(usage, mockModel) + const result = handler["normalizeUsage"](usage, mockModel) expect(result).toMatchObject({ type: "usage", @@ -402,10 +402,10 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { const buildRequestBodyForModel = (modelId: string) => { // Force the handler to use the requested model ID - ;(handler as any).options.apiModelId = modelId + handler["options"].apiModelId = modelId const model = handler.getModel() // Minimal formatted input/systemPrompt/verbosity/metadata for building the body - return (handler as any).buildRequestBody(model, [], "", model.verbosity, undefined, undefined) + return handler["buildRequestBody"](model, [], "", model.verbosity, undefined, undefined) } it("should set prompt_cache_retention=24h for gpt-5.1 models that support prompt caching", () => { @@ -568,10 +568,10 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { cache_creation_input_tokens: 20, } - const result = (handler as any).normalizeUsage(usage, mockModel) + const result = handler["normalizeUsage"](usage, mockModel) expect(result).toHaveProperty("totalCost") - expect(result.totalCost).toBeGreaterThan(0) + expect(result!.totalCost).toBeGreaterThan(0) // calculateApiCostOpenAI handles subtracting cache tokens internally // It will compute: 100 - 30 - 20 = 50 uncached input tokens }) @@ -582,10 +582,10 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { output_tokens: 50, } - const result = (handler as any).normalizeUsage(usage, mockModel) + const result = handler["normalizeUsage"](usage, mockModel) expect(result).toHaveProperty("totalCost") - expect(result.totalCost).toBeGreaterThan(0) + expect(result!.totalCost).toBeGreaterThan(0) // Cost should be calculated with full input tokens since no cache reads }) @@ -596,7 +596,7 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { cache_read_input_tokens: 20_000, } - const result = (handler as any).normalizeUsage(usage, gpt54Model) + const result = handler["normalizeUsage"](usage, gpt54Model) expect(result).toMatchObject({ type: "usage", @@ -604,7 +604,7 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { outputTokens: 1_000, cacheReadTokens: 20_000, }) - expect(result.totalCost).toBeCloseTo(0.22, 6) + expect(result!.totalCost).toBeCloseTo(0.22, 6) }) it("should apply GPT-5.4 long-context pricing above the threshold", () => { @@ -614,7 +614,7 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { cache_read_input_tokens: 100_000, } - const result = (handler as any).normalizeUsage(usage, gpt54Model) + const result = handler["normalizeUsage"](usage, gpt54Model) expect(result).toMatchObject({ type: "usage", @@ -622,7 +622,7 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { outputTokens: 1_000, cacheReadTokens: 100_000, }) - expect(result.totalCost).toBeCloseTo(1.0475, 6) + expect(result!.totalCost).toBeCloseTo(1.0475, 6) }) it("should not apply GPT-5.4 long-context pricing to priority tier", () => { @@ -637,7 +637,7 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { cache_read_input_tokens: 100_000, } - const result = (handler as any).normalizeUsage(usage, gpt54Model) + const result = handler["normalizeUsage"](usage, gpt54Model) expect(result).toMatchObject({ type: "usage", @@ -645,7 +645,7 @@ describe("OpenAiNativeHandler - normalizeUsage", () => { outputTokens: 1_000, cacheReadTokens: 100_000, }) - expect(result.totalCost).toBeCloseTo(1.08, 6) + expect(result!.totalCost).toBeCloseTo(1.08, 6) }) }) diff --git a/src/api/providers/__tests__/openai-native.spec.ts b/src/api/providers/__tests__/openai-native.spec.ts index fa32c85dd94..c697b1038a5 100644 --- a/src/api/providers/__tests__/openai-native.spec.ts +++ b/src/api/providers/__tests__/openai-native.spec.ts @@ -197,8 +197,8 @@ describe("OpenAiNativeHandler", () => { tools: [{ type: "function", name: "read_file", strict: true }], }) expect(body.temperature).toBeUndefined() - expect(body.top_p).toBeUndefined() - expect(body.logprobs).toBeUndefined() + expect(body).not.toHaveProperty("top_p") + expect(body).not.toHaveProperty("logprobs") expect(body.text).toBeUndefined() }) @@ -326,26 +326,27 @@ describe("OpenAiNativeHandler", () => { "requests $requestedTier but prices manual SSE fallback usage using OpenAI's resolved $resolvedTier tier", async ({ requestedTier, resolvedTier, expectedCost }) => { mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode( - `data: ${JSON.stringify({ - type: "response.done", - response: { - [SERVICE_TIER_KEY]: resolvedTier, - usage: { input_tokens: 100, output_tokens: 20 }, - }, - })}\n\n`, - ), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + `data: ${JSON.stringify({ + type: "response.done", + response: { + [SERVICE_TIER_KEY]: resolvedTier, + usage: { input_tokens: 100, output_tokens: 20 }, + }, + })}\n\n`, + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) global.fetch = mockFetch as typeof fetch handler = new OpenAiNativeHandler({ ...mockOptions, @@ -355,8 +356,8 @@ describe("OpenAiNativeHandler", () => { const chunks = await collectStream(handler.createMessage(systemPrompt, messages)) - const [, request] = mockFetch.mock.calls[0] - expect(JSON.parse(request.body)).toMatchObject({ [SERVICE_TIER_KEY]: requestedTier }) + const request = mockFetch.mock.calls[0]?.[1] + expect(JSON.parse(request?.body as string)).toMatchObject({ [SERVICE_TIER_KEY]: requestedTier }) const usage = chunks.find((chunk) => chunk.type === "usage") expect(usage?.totalCost).toBeCloseTo(expectedCost, 10) }, @@ -366,31 +367,32 @@ describe("OpenAiNativeHandler", () => { "captures resolved $resolvedTier tier from a manual SSE completion event when $requestedTier was requested", async ({ requestedTier, resolvedTier, expectedCost }) => { mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode( - `data: ${JSON.stringify({ - type: "response.completed", - response: { [SERVICE_TIER_KEY]: resolvedTier }, - })}\n\n`, - ), - ) - controller.enqueue( - new TextEncoder().encode( - `data: ${JSON.stringify({ - type: "response.usage", - usage: { input_tokens: 100, output_tokens: 20 }, - })}\n\n`, - ), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + `data: ${JSON.stringify({ + type: "response.completed", + response: { [SERVICE_TIER_KEY]: resolvedTier }, + })}\n\n`, + ), + ) + controller.enqueue( + new TextEncoder().encode( + `data: ${JSON.stringify({ + type: "response.usage", + usage: { input_tokens: 100, output_tokens: 20 }, + })}\n\n`, + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) global.fetch = mockFetch as typeof fetch handler = new OpenAiNativeHandler({ ...mockOptions, @@ -408,27 +410,30 @@ describe("OpenAiNativeHandler", () => { it("should handle streaming responses via Responses API", async () => { // Mock fetch for Responses API fallback - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode('data: {"type":"response.text.delta","delta":"Test"}\n\n'), - ) - controller.enqueue( - new TextEncoder().encode('data: {"type":"response.text.delta","delta":" response"}\n\n'), - ) - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.done","response":{"usage":{"prompt_tokens":10,"completion_tokens":2}}}\n\n', - ), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode('data: {"type":"response.text.delta","delta":"Test"}\n\n'), + ) + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.text.delta","delta":" response"}\n\n', + ), + ) + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.done","response":{"usage":{"prompt_tokens":10,"completion_tokens":2}}}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Mock SDK to fail so it falls back to fetch mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -444,12 +449,10 @@ describe("OpenAiNativeHandler", () => { it("should handle API errors", async () => { // Mock fetch to return error - const mockFetch = vitest.fn().mockResolvedValue({ - ok: false, - status: 500, - text: async () => "Internal Server Error", - }) - global.fetch = mockFetch as any + const mockFetch = vitest + .fn() + .mockResolvedValue(new Response("Internal Server Error", { status: 500 })) + global.fetch = mockFetch // Mock SDK to fail mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -2524,37 +2527,38 @@ describe("OpenAiNativeHandler", () => { describe("GPT-5 models", () => { it("should handle GPT-5 model with Responses API", async () => { // Mock fetch for Responses API - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - // Simulate actual GPT-5 Responses API SSE stream format - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.created","response":{"id":"test","status":"in_progress"}}\n\n', - ), - ) - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_item.added","item":{"type":"text","text":"Hello"}}\n\n', - ), - ) - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_item.added","item":{"type":"text","text":" world"}}\n\n', - ), - ) - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.done","response":{"usage":{"prompt_tokens":10,"completion_tokens":2}}}\n\n', - ), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + // Simulate actual GPT-5 Responses API SSE stream format + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.created","response":{"id":"test","status":"in_progress"}}\n\n', + ), + ) + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_item.added","item":{"type":"text","text":"Hello"}}\n\n', + ), + ) + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_item.added","item":{"type":"text","text":" world"}}\n\n', + ), + ) + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.done","response":{"usage":{"prompt_tokens":10,"completion_tokens":2}}}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Mock SDK to fail so it uses fetch mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -2565,10 +2569,7 @@ describe("OpenAiNativeHandler", () => { }) const stream = handler.createMessage(systemPrompt, messages) - const chunks: any[] = [] - for await (const chunk of stream) { - chunks.push(chunk) - } + const chunks = await collectStream(stream) // Verify Responses API is called with correct parameters expect(mockFetch).toHaveBeenCalledWith( @@ -2582,7 +2583,7 @@ describe("OpenAiNativeHandler", () => { body: expect.any(String), }), ) - const body1 = (mockFetch.mock.calls[0][1] as any).body as string + const body1 = mockFetch.mock.calls[0][1]?.body as string const parsedBody = JSON.parse(body1) expect(parsedBody.model).toBe("gpt-5.1") expect(parsedBody.instructions).toBe("You are a helpful assistant.") @@ -2608,21 +2609,22 @@ describe("OpenAiNativeHandler", () => { }) it("should handle GPT-5.5 model with Responses API", async () => { - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_item.added","item":{"type":"text","text":"GPT-5.5 reply"}}\n\n', - ), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_item.added","item":{"type":"text","text":"GPT-5.5 reply"}}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -2632,10 +2634,7 @@ describe("OpenAiNativeHandler", () => { }) const stream = handler.createMessage(systemPrompt, messages) - const chunks: any[] = [] - for await (const chunk of stream) { - chunks.push(chunk) - } + const chunks = await collectStream(stream) expect(mockFetch).toHaveBeenCalledWith( "https://api.openai.com/v1/responses", @@ -2643,7 +2642,7 @@ describe("OpenAiNativeHandler", () => { body: expect.any(String), }), ) - const body = (mockFetch.mock.calls[0][1] as any).body as string + const body = mockFetch.mock.calls[0][1]?.body as string const parsedBody = JSON.parse(body) expect(parsedBody.model).toBe("gpt-5.5") expect(parsedBody.max_output_tokens).toBe(128000) @@ -2658,21 +2657,22 @@ describe("OpenAiNativeHandler", () => { }) it("should handle GPT-5.4 model with Responses API", async () => { - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_item.added","item":{"type":"text","text":"GPT-5.4 reply"}}\n\n', - ), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_item.added","item":{"type":"text","text":"GPT-5.4 reply"}}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -2682,10 +2682,7 @@ describe("OpenAiNativeHandler", () => { }) const stream = handler.createMessage(systemPrompt, messages) - const chunks: any[] = [] - for await (const chunk of stream) { - chunks.push(chunk) - } + const chunks = await collectStream(stream) expect(mockFetch).toHaveBeenCalledWith( "https://api.openai.com/v1/responses", @@ -2693,7 +2690,7 @@ describe("OpenAiNativeHandler", () => { body: expect.any(String), }), ) - const body = (mockFetch.mock.calls[0][1] as any).body as string + const body = mockFetch.mock.calls[0][1]?.body as string const parsedBody = JSON.parse(body) expect(parsedBody.model).toBe("gpt-5.4") expect(parsedBody.max_output_tokens).toBe(128000) @@ -2709,21 +2706,22 @@ describe("OpenAiNativeHandler", () => { it("should handle GPT-5.3 Chat model with Responses API", async () => { // Mock fetch for Responses API - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_item.added","item":{"type":"text","text":"Chat reply"}}\n\n', - ), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_item.added","item":{"type":"text","text":"Chat reply"}}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Mock SDK to fail so it uses fetch mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -2734,10 +2732,7 @@ describe("OpenAiNativeHandler", () => { }) const stream = handler.createMessage(systemPrompt, messages) - const chunks: any[] = [] - for await (const chunk of stream) { - chunks.push(chunk) - } + const chunks = await collectStream(stream) expect(mockFetch).toHaveBeenCalledWith( "https://api.openai.com/v1/responses", @@ -2745,7 +2740,7 @@ describe("OpenAiNativeHandler", () => { body: expect.any(String), }), ) - const body = (mockFetch.mock.calls[0][1] as any).body as string + const body = mockFetch.mock.calls[0][1]?.body as string const parsedBody = JSON.parse(body) expect(parsedBody.model).toBe("gpt-5.3-chat-latest") expect(parsedBody.max_output_tokens).toBe(16_384) @@ -2760,21 +2755,22 @@ describe("OpenAiNativeHandler", () => { it("should handle GPT-5-mini model with Responses API", async () => { // Mock fetch for Responses API - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_item.added","item":{"type":"text","text":"Response"}}\n\n', - ), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_item.added","item":{"type":"text","text":"Response"}}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Mock SDK to fail mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -2785,10 +2781,7 @@ describe("OpenAiNativeHandler", () => { }) const stream = handler.createMessage(systemPrompt, messages) - const chunks: any[] = [] - for await (const chunk of stream) { - chunks.push(chunk) - } + await collectStream(stream) // Verify correct model and default parameters expect(mockFetch).toHaveBeenCalledWith( @@ -2801,21 +2794,22 @@ describe("OpenAiNativeHandler", () => { it("should handle GPT-5-nano model with Responses API", async () => { // Mock fetch for Responses API - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_item.added","item":{"type":"text","text":"Nano response"}}\n\n', - ), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_item.added","item":{"type":"text","text":"Nano response"}}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Mock SDK to fail mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -2826,10 +2820,7 @@ describe("OpenAiNativeHandler", () => { }) const stream = handler.createMessage(systemPrompt, messages) - const chunks: any[] = [] - for await (const chunk of stream) { - chunks.push(chunk) - } + await collectStream(stream) // Verify correct model expect(mockFetch).toHaveBeenCalledWith( @@ -2842,21 +2833,22 @@ describe("OpenAiNativeHandler", () => { it("should support verbosity control for GPT-5", async () => { // Mock fetch for Responses API - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_item.added","item":{"type":"text","text":"Low verbosity"}}\n\n', - ), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_item.added","item":{"type":"text","text":"Low verbosity"}}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Mock SDK to fail mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -2869,10 +2861,7 @@ describe("OpenAiNativeHandler", () => { // Create a message to verify verbosity is passed const stream = handler.createMessage(systemPrompt, messages) - const chunks: any[] = [] - for await (const chunk of stream) { - chunks.push(chunk) - } + await collectStream(stream) // Verify that verbosity is passed in the request expect(mockFetch).toHaveBeenCalledWith( @@ -2885,21 +2874,22 @@ describe("OpenAiNativeHandler", () => { it("should replace an unsupported GPT-5.1 reasoning effort with the model default", async () => { // Mock fetch for Responses API - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_item.added","item":{"type":"text","text":"Minimal effort"}}\n\n', - ), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_item.added","item":{"type":"text","text":"Minimal effort"}}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Mock SDK to fail mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -2907,14 +2897,11 @@ describe("OpenAiNativeHandler", () => { handler = new OpenAiNativeHandler({ ...mockOptions, apiModelId: "gpt-5.1", - reasoningEffort: "minimal" as any, // GPT-5 supports minimal + reasoningEffort: "minimal", // GPT-5 supports minimal }) const stream = handler.createMessage(systemPrompt, messages) - const chunks: any[] = [] - for await (const chunk of stream) { - chunks.push(chunk) - } + await collectStream(stream) // GPT-5.1 does not support minimal, so use the catalog's medium default. expect(mockFetch).toHaveBeenCalledWith( @@ -2927,21 +2914,22 @@ describe("OpenAiNativeHandler", () => { it("should support xhigh reasoning effort for GPT-5.1 Codex Max", async () => { // Mock fetch for Responses API - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_item.added","item":{"type":"text","text":"XHigh effort"}}\n\n', - ), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_item.added","item":{"type":"text","text":"XHigh effort"}}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Mock SDK to fail mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -2967,21 +2955,22 @@ describe("OpenAiNativeHandler", () => { it("should omit reasoning when selection is 'disable'", async () => { // Mock fetch for Responses API - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_item.added","item":{"type":"text","text":"No reasoning"}}\n\n', - ), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_item.added","item":{"type":"text","text":"No reasoning"}}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Mock SDK to fail mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -2989,7 +2978,7 @@ describe("OpenAiNativeHandler", () => { const handler = new OpenAiNativeHandler({ ...mockOptions, apiModelId: "gpt-5.1", - reasoningEffort: "disable" as any, + reasoningEffort: "disable", }) const stream = handler.createMessage(systemPrompt, messages) @@ -2997,7 +2986,7 @@ describe("OpenAiNativeHandler", () => { // drain } - const bodyStr = (mockFetch.mock.calls[0][1] as any).body as string + const bodyStr = mockFetch.mock.calls[0][1]?.body as string const parsed = JSON.parse(bodyStr) expect(parsed.reasoning).toBeUndefined() expect(parsed.include).toBeUndefined() @@ -3005,21 +2994,22 @@ describe("OpenAiNativeHandler", () => { it("should support low reasoning effort for GPT-5", async () => { // Mock fetch for Responses API - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_item.added","item":{"type":"text","text":"Low effort response"}}\n\n', - ), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_item.added","item":{"type":"text","text":"Low effort response"}}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Mock SDK to fail mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -3031,10 +3021,7 @@ describe("OpenAiNativeHandler", () => { }) const stream = handler.createMessage(systemPrompt, messages) - const chunks: any[] = [] - for await (const chunk of stream) { - chunks.push(chunk) - } + await collectStream(stream) // Should use Responses API with low reasoning effort expect(mockFetch).toHaveBeenCalledWith( @@ -3043,7 +3030,7 @@ describe("OpenAiNativeHandler", () => { body: expect.any(String), }), ) - const body2 = (mockFetch.mock.calls[0][1] as any).body as string + const body2 = mockFetch.mock.calls[0][1]?.body as string const parsedBody = JSON.parse(body2) expect(parsedBody.model).toBe("gpt-5.1") expect(parsedBody.reasoning?.effort).toBe("low") @@ -3056,21 +3043,22 @@ describe("OpenAiNativeHandler", () => { it("should support verbosity while normalizing an unsupported GPT-5 effort", async () => { // Mock fetch for Responses API - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_item.added","item":{"type":"text","text":"High verbosity minimal effort"}}\n\n', - ), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_item.added","item":{"type":"text","text":"High verbosity minimal effort"}}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Mock SDK to fail mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -3079,14 +3067,11 @@ describe("OpenAiNativeHandler", () => { ...mockOptions, apiModelId: "gpt-5.1", verbosity: "high", - reasoningEffort: "minimal" as any, + reasoningEffort: "minimal", }) const stream = handler.createMessage(systemPrompt, messages) - const chunks: any[] = [] - for await (const chunk of stream) { - chunks.push(chunk) - } + await collectStream(stream) // Should use Responses API with both parameters expect(mockFetch).toHaveBeenCalledWith( @@ -3095,7 +3080,7 @@ describe("OpenAiNativeHandler", () => { body: expect.any(String), }), ) - const body3 = (mockFetch.mock.calls[0][1] as any).body as string + const body3 = mockFetch.mock.calls[0][1]?.body as string const parsedBody = JSON.parse(body3) expect(parsedBody.model).toBe("gpt-5.1") expect(parsedBody.reasoning?.effort).toBe("medium") @@ -3108,47 +3093,48 @@ describe("OpenAiNativeHandler", () => { it("should handle actual GPT-5 Responses API format", async () => { // Mock fetch with actual response format from GPT-5 - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - // Test actual GPT-5 response format - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.created","response":{"id":"test","status":"in_progress"}}\n\n', - ), - ) - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.in_progress","response":{"status":"in_progress"}}\n\n', - ), - ) - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_item.added","item":{"type":"text","text":"First text"}}\n\n', - ), - ) - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_item.added","item":{"type":"text","text":" Second text"}}\n\n', - ), - ) - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_item.added","item":{"type":"reasoning","text":"Some reasoning"}}\n\n', - ), - ) - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.done","response":{"usage":{"prompt_tokens":100,"completion_tokens":20}}}\n\n', - ), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + // Test actual GPT-5 response format + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.created","response":{"id":"test","status":"in_progress"}}\n\n', + ), + ) + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.in_progress","response":{"status":"in_progress"}}\n\n', + ), + ) + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_item.added","item":{"type":"text","text":"First text"}}\n\n', + ), + ) + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_item.added","item":{"type":"text","text":" Second text"}}\n\n', + ), + ) + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_item.added","item":{"type":"reasoning","text":"Some reasoning"}}\n\n', + ), + ) + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.done","response":{"usage":{"prompt_tokens":100,"completion_tokens":20}}}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Mock SDK to fail mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -3159,10 +3145,7 @@ describe("OpenAiNativeHandler", () => { }) const stream = handler.createMessage(systemPrompt, messages) - const chunks: any[] = [] - for await (const chunk of stream) { - chunks.push(chunk) - } + const chunks = await collectStream(stream) // Should handle the actual format correctly const textChunks = chunks.filter((c) => c.type === "text") @@ -3194,17 +3177,18 @@ describe("OpenAiNativeHandler", () => { it("should handle Responses API with no content gracefully", async () => { // Mock fetch with empty response - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode('data: {"someField":"value"}\n\n')) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('data: {"someField":"value"}\n\n')) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Mock SDK to fail mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -3215,7 +3199,7 @@ describe("OpenAiNativeHandler", () => { }) const stream = handler.createMessage(systemPrompt, messages) - const chunks: any[] = [] + const chunks: ApiStreamChunk[] = [] // Should not throw, just warn for await (const chunk of stream) { @@ -3230,26 +3214,29 @@ describe("OpenAiNativeHandler", () => { it("should handle unhandled stream events gracefully", async () => { // Mock fetch for the fallback SSE path - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_item.added","item":{"type":"text","text":"Hello"}}\n\n', - ), - ) - // This event is not handled, so it should be ignored - controller.enqueue( - new TextEncoder().encode('data: {"type":"response.audio.delta","delta":"..."}\n\n'), - ) - controller.enqueue(new TextEncoder().encode('data: {"type":"response.done","response":{}}\n\n')) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_item.added","item":{"type":"text","text":"Hello"}}\n\n', + ), + ) + // This event is not handled, so it should be ignored + controller.enqueue( + new TextEncoder().encode('data: {"type":"response.audio.delta","delta":"..."}\n\n'), + ) + controller.enqueue( + new TextEncoder().encode('data: {"type":"response.done","response":{}}\n\n'), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Mock SDK to fail mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -3260,8 +3247,8 @@ describe("OpenAiNativeHandler", () => { }) const stream = handler.createMessage(systemPrompt, messages) - const chunks: any[] = [] - const errors: any[] = [] + const chunks: ApiStreamChunk[] = [] + const errors: unknown[] = [] try { for await (const chunk of stream) { @@ -3278,21 +3265,22 @@ describe("OpenAiNativeHandler", () => { }) it("should format full conversation correctly", async () => { - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_item.added","item":{"type":"text","text":"Response"}}\n\n', - ), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_item.added","item":{"type":"text","text":"Response"}}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) const gpt5Handler = new OpenAiNativeHandler({ @@ -3307,7 +3295,7 @@ describe("OpenAiNativeHandler", () => { // consume } - const callBody = JSON.parse(mockFetch.mock.calls[0][1].body) + const callBody = JSON.parse(mockFetch.mock.calls[0][1]?.body as string) expect(callBody.input).toEqual([ { role: "user", @@ -3318,15 +3306,16 @@ describe("OpenAiNativeHandler", () => { }) it("sends a task-scoped prompt_cache_key in the body and no session_id header", async () => { - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) global.fetch = mockFetch as typeof fetch // Force the hand-built SSE path so the wire body and headers are inspectable. mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -3339,7 +3328,7 @@ describe("OpenAiNativeHandler", () => { } } - const bodies = mockFetch.mock.calls.map(([, init]) => JSON.parse(init.body)) + const bodies = mockFetch.mock.calls.map(([, init]) => JSON.parse(init?.body as string)) expect(bodies).toHaveLength(3) expect(bodies[0].prompt_cache_key).toBe("task-cache-one") // Same task, second turn: the key must not drift, or the growing prefix loses affinity. @@ -3354,7 +3343,7 @@ describe("OpenAiNativeHandler", () => { // The affinity header is gone: OpenAI ignores it for caching and hardened // gateways reject underscore header names outright. for (const [, init] of mockFetch.mock.calls) { - expect(init.headers).not.toHaveProperty("session_id") + expect(init?.headers).not.toHaveProperty("session_id") } }) @@ -3362,15 +3351,16 @@ describe("OpenAiNativeHandler", () => { // Task ids are uuidv7 today (36 chars), so this guards the wire contract for // any caller that sends a longer id: a 64-char slice drops the distinguishing // tail, so two ids sharing a 64-char prefix would land in one routing bucket. - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) global.fetch = mockFetch as typeof fetch mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -3385,7 +3375,7 @@ describe("OpenAiNativeHandler", () => { } } - const bodies = mockFetch.mock.calls.map(([, init]) => JSON.parse(init.body)) + const bodies = mockFetch.mock.calls.map(([, init]) => JSON.parse(init?.body as string)) expect(bodies).toHaveLength(2) // OpenAI rejects keys over 64 characters, so the key must still fit. expect(bodies[0].prompt_cache_key.length).toBeLessThanOrEqual(64) @@ -3459,7 +3449,7 @@ describe("OpenAiNativeHandler", () => { statusText: "Error", text: async () => JSON.stringify({ error: { message: "Test error" } }), }) - global.fetch = mockFetch as any + global.fetch = mockFetch // Mock SDK to fail mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -3478,7 +3468,7 @@ describe("OpenAiNativeHandler", () => { }).rejects.toThrow(expectedMessage) // Clean up - delete (global as any).fetch + deleteGlobalFetch() } }) }) @@ -3557,12 +3547,10 @@ describe("OpenAiNativeHandler", () => { it("should capture telemetry on createMessage error", async () => { // Mock fetch to return error - const mockFetch = vitest.fn().mockResolvedValue({ - ok: false, - status: 500, - text: async () => "Internal Server Error", - }) - global.fetch = mockFetch as any + const mockFetch = vitest + .fn() + .mockResolvedValue(new Response("Internal Server Error", { status: 500 })) + global.fetch = mockFetch // Mock SDK to fail so it falls back to fetch mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -3593,20 +3581,21 @@ describe("OpenAiNativeHandler", () => { it("should capture telemetry on stream processing error", async () => { // Mock fetch to return a stream with an error event - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.error","error":{"message":"Model overloaded"}}\n\n', - ), - ) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.error","error":{"message":"Model overloaded"}}\n\n', + ), + ) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Mock SDK to fail so it falls back to fetch mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -3622,8 +3611,8 @@ describe("OpenAiNativeHandler", () => { // A stream failure must be captured exactly once (handleStreamResponse rethrows to createMessage). expect(mockCaptureException).toHaveBeenCalledTimes(1) - const streamErrorCall = mockCaptureException.mock.calls.find((call: any[]) => - call[0]?.message?.includes("Model overloaded"), + const streamErrorCall = mockCaptureException.mock.calls.find( + (call) => call[0] instanceof ApiProviderError && call[0].message.includes("Model overloaded"), ) expect(streamErrorCall).toBeDefined() expect(streamErrorCall![0]).toMatchObject({ @@ -3660,12 +3649,10 @@ describe("OpenAiNativeHandler", () => { it("should still throw the error after capturing telemetry", async () => { // Mock fetch to return error - const mockFetch = vitest.fn().mockResolvedValue({ - ok: false, - status: 500, - text: async () => "Internal Server Error", - }) - global.fetch = mockFetch as any + const mockFetch = vitest + .fn() + .mockResolvedValue(new Response("Internal Server Error", { status: 500 })) + global.fetch = mockFetch // Mock SDK to fail mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -3730,30 +3717,31 @@ describe("OpenAiNativeHandler", () => { // Additional tests for GPT-5 streaming event coverage describe("GPT-5 streaming event coverage (additional)", () => { afterEach(() => { - if ((global as any).fetch) { - delete (global as any).fetch - } + deleteGlobalFetch() }) it("should handle reasoning delta events for GPT-5", async () => { - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.reasoning.delta","delta":"Thinking about the problem..."}\n\n', - ), - ) - controller.enqueue( - new TextEncoder().encode('data: {"type":"response.text.delta","delta":"The answer is..."}\n\n'), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.reasoning.delta","delta":"Thinking about the problem..."}\n\n', + ), + ) + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.text.delta","delta":"The answer is..."}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Mock SDK to fail mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -3767,10 +3755,7 @@ describe("GPT-5 streaming event coverage (additional)", () => { const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hello!" }] const stream = handler.createMessage(systemPrompt, messages) - const chunks: any[] = [] - for await (const chunk of stream) { - chunks.push(chunk) - } + const chunks = await collectStream(stream) const reasoningChunks = chunks.filter((c) => c.type === "reasoning") const textChunks = chunks.filter((c) => c.type === "text") @@ -3782,21 +3767,22 @@ describe("GPT-5 streaming event coverage (additional)", () => { }) it("should handle refusal delta events for GPT-5 and prefix output", async () => { - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.refusal.delta","delta":"I cannot comply with this request."}\n\n', - ), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.refusal.delta","delta":"I cannot comply with this request."}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Mock SDK to fail mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -3810,10 +3796,7 @@ describe("GPT-5 streaming event coverage (additional)", () => { const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Do something disallowed" }] const stream = handler.createMessage(systemPrompt, messages) - const chunks: any[] = [] - for await (const chunk of stream) { - chunks.push(chunk) - } + const chunks = await collectStream(stream) const textChunks = chunks.filter((c) => c.type === "text") expect(textChunks).toHaveLength(1) @@ -3821,31 +3804,32 @@ describe("GPT-5 streaming event coverage (additional)", () => { }) it("should ignore malformed JSON lines in SSE stream", async () => { - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_item.added","item":{"type":"text","text":"Before"}}\n\n', - ), - ) - // Malformed JSON line - controller.enqueue( - new TextEncoder().encode('data: {"type":"response.text.delta","delta":"Bad"\n\n'), - ) - // Valid line after malformed - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_item.added","item":{"type":"text","text":"After"}}\n\n', - ), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_item.added","item":{"type":"text","text":"Before"}}\n\n', + ), + ) + // Malformed JSON line + controller.enqueue( + new TextEncoder().encode('data: {"type":"response.text.delta","delta":"Bad"\n\n'), + ) + // Valid line after malformed + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_item.added","item":{"type":"text","text":"After"}}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Mock SDK to fail mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -3859,14 +3843,11 @@ describe("GPT-5 streaming event coverage (additional)", () => { const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hello!" }] const stream = handler.createMessage(systemPrompt, messages) - const chunks: any[] = [] - for await (const chunk of stream) { - chunks.push(chunk) - } + const chunks = await collectStream(stream) // It should not throw and still capture the valid texts around the malformed line const textChunks = chunks.filter((c) => c.type === "text") - expect(textChunks.map((c: any) => c.text)).toEqual(["Before", "After"]) + expect(textChunks.map((c) => c.text)).toEqual(["Before", "After"]) }) describe("Codex Mini Model", () => { @@ -3878,38 +3859,43 @@ describe("GPT-5 streaming event coverage (additional)", () => { it("should handle codex-mini-latest streaming response", async () => { // Mock fetch for Codex Mini responses API - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - // Codex Mini uses the same responses API format - controller.enqueue( - new TextEncoder().encode('data: {"type":"response.output_text.delta","delta":"Hello"}\n\n'), - ) - controller.enqueue( - new TextEncoder().encode('data: {"type":"response.output_text.delta","delta":" from"}\n\n'), - ) - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_text.delta","delta":" Codex"}\n\n', - ), - ) - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_text.delta","delta":" Mini!"}\n\n', - ), - ) - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.done","response":{"usage":{"prompt_tokens":50,"completion_tokens":10}}}\n\n', - ), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + // Codex Mini uses the same responses API format + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_text.delta","delta":"Hello"}\n\n', + ), + ) + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_text.delta","delta":" from"}\n\n', + ), + ) + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_text.delta","delta":" Codex"}\n\n', + ), + ) + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_text.delta","delta":" Mini!"}\n\n', + ), + ) + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.done","response":{"usage":{"prompt_tokens":50,"completion_tokens":10}}}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Mock SDK to fail mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -3925,10 +3911,7 @@ describe("GPT-5 streaming event coverage (additional)", () => { ] const stream = handler.createMessage(systemPrompt, messages) - const chunks: any[] = [] - for await (const chunk of stream) { - chunks.push(chunk) - } + const chunks = await collectStream(stream) // Verify text chunks const textChunks = chunks.filter((c) => c.type === "text") @@ -3962,7 +3945,7 @@ describe("GPT-5 streaming event coverage (additional)", () => { }), ) - const requestBody = JSON.parse(mockFetch.mock.calls[0][1].body) + const requestBody = JSON.parse(mockFetch.mock.calls[0][1]?.body as string) expect(requestBody).toMatchObject({ model: "codex-mini-latest", instructions: "You are a helpful coding assistant.", @@ -4014,13 +3997,12 @@ describe("GPT-5 streaming event coverage (additional)", () => { it("should handle codex-mini-latest API errors", async () => { // Mock fetch with error response - const mockFetch = vitest.fn().mockResolvedValue({ - ok: false, - status: 429, - statusText: "Too Many Requests", - text: async () => "Rate limit exceeded", - }) - global.fetch = mockFetch as any + const mockFetch = vitest + .fn() + .mockResolvedValue( + new Response("Rate limit exceeded", { status: 429, statusText: "Too Many Requests" }), + ) + global.fetch = mockFetch // Mock SDK to fail mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -4045,22 +4027,23 @@ describe("GPT-5 streaming event coverage (additional)", () => { it("should handle codex-mini-latest with multiple user messages", async () => { // Mock fetch for streaming response - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_text.delta","delta":"Combined response"}\n\n', - ), - ) - controller.enqueue(new TextEncoder().encode('data: {"type":"response.completed"}\n\n')) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_text.delta","delta":"Combined response"}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode('data: {"type":"response.completed"}\n\n')) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Mock SDK to fail mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -4078,13 +4061,10 @@ describe("GPT-5 streaming event coverage (additional)", () => { ] const stream = handler.createMessage(systemPrompt, messages) - const chunks: any[] = [] - for await (const chunk of stream) { - chunks.push(chunk) - } + await collectStream(stream) // Verify the request body includes full conversation in structured format (without embedding system prompt) - const requestBody = JSON.parse(mockFetch.mock.calls[0][1].body) + const requestBody = JSON.parse(mockFetch.mock.calls[0][1]?.body as string) expect(requestBody.instructions).toBe("You are a helpful assistant.") expect(requestBody.input).toEqual([ { @@ -4104,26 +4084,27 @@ describe("GPT-5 streaming event coverage (additional)", () => { it("should handle codex-mini-latest stream error events", async () => { // Mock fetch with error event in stream - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.output_text.delta","delta":"Partial"}\n\n', - ), - ) - controller.enqueue( - new TextEncoder().encode( - 'data: {"type":"response.error","error":{"message":"Model overloaded"}}\n\n', - ), - ) - // The error handler will throw, but we still need to close the stream - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_text.delta","delta":"Partial"}\n\n', + ), + ) + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.error","error":{"message":"Model overloaded"}}\n\n', + ), + ) + // The error handler will throw, but we still need to close the stream + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Mock SDK to fail mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -4147,19 +4128,20 @@ describe("GPT-5 streaming event coverage (additional)", () => { // New tests: ensure text.verbosity is omitted for models without supportsVerbosity describe("Verbosity gating for non-GPT-5 models", () => { it("should omit text.verbosity for gpt-4.1", async () => { - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode('data: {"type":"response.done","response":{}}\n\n'), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - ;(global as any).fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode('data: {"type":"response.done","response":{}}\n\n'), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Force SDK path to fail so we use fetch fallback mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -4178,7 +4160,7 @@ describe("GPT-5 streaming event coverage (additional)", () => { // drain } - const bodyStr = (mockFetch.mock.calls[0][1] as any).body as string + const bodyStr = mockFetch.mock.calls[0][1]?.body as string const parsedBody = JSON.parse(bodyStr) expect(parsedBody.model).toBe("gpt-4.1") expect(parsedBody.text).toBeUndefined() @@ -4186,19 +4168,20 @@ describe("GPT-5 streaming event coverage (additional)", () => { }) it("should omit text.verbosity for gpt-4o", async () => { - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode('data: {"type":"response.done","response":{}}\n\n'), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - ;(global as any).fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode('data: {"type":"response.done","response":{}}\n\n'), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch // Force SDK path to fail so we use fetch fallback mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -4217,7 +4200,7 @@ describe("GPT-5 streaming event coverage (additional)", () => { // drain } - const bodyStr = (mockFetch.mock.calls[0][1] as any).body as string + const bodyStr = mockFetch.mock.calls[0][1]?.body as string const parsedBody = JSON.parse(bodyStr) expect(parsedBody.model).toBe("gpt-4o") expect(parsedBody.text).toBeUndefined() @@ -4228,19 +4211,22 @@ describe("GPT-5 streaming event coverage (additional)", () => { describe("URL image handling", () => { it("should skip URL-sourced images in formatFullConversation (only base64 emits input_image)", async () => { - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode('data: {"type":"response.output_text.delta","delta":"ok"}\n\n'), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_text.delta","delta":"ok"}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -4256,7 +4242,7 @@ describe("GPT-5 streaming event coverage (additional)", () => { { type: "text", text: "Look at this:" }, { type: "image", - source: { type: "url", url: "https://example.com/img.png" } as any, + source: { type: "url", url: "https://example.com/img.png" }, }, ], }, @@ -4267,7 +4253,7 @@ describe("GPT-5 streaming event coverage (additional)", () => { // consume } - const bodyStr = (mockFetch.mock.calls[0][1] as any).body as string + const bodyStr = mockFetch.mock.calls[0][1]?.body as string const parsedBody = JSON.parse(bodyStr) // URL image is skipped; only the text part is in the input const userMsg = parsedBody.input[0] @@ -4276,19 +4262,22 @@ describe("GPT-5 streaming event coverage (additional)", () => { }) it("should emit input_image for base64 images in formatFullConversation", async () => { - const mockFetch = vitest.fn().mockResolvedValue({ - ok: true, - body: new ReadableStream({ - start(controller) { - controller.enqueue( - new TextEncoder().encode('data: {"type":"response.output_text.delta","delta":"ok"}\n\n'), - ) - controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) - controller.close() - }, - }), - }) - global.fetch = mockFetch as any + const mockFetch = vitest.fn().mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue( + new TextEncoder().encode( + 'data: {"type":"response.output_text.delta","delta":"ok"}\n\n', + ), + ) + controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n")) + controller.close() + }, + }), + ), + ) + global.fetch = mockFetch mockResponsesCreate.mockRejectedValue(new Error("SDK not available")) @@ -4312,7 +4301,7 @@ describe("GPT-5 streaming event coverage (additional)", () => { // consume } - const bodyStr = (mockFetch.mock.calls[0][1] as any).body as string + const bodyStr = mockFetch.mock.calls[0][1]?.body as string const parsedBody = JSON.parse(bodyStr) const userMsg = parsedBody.input[0] expect(userMsg.content).toContainEqual({ diff --git a/src/api/providers/__tests__/openrouter.spec.ts b/src/api/providers/__tests__/openrouter.spec.ts index ec4a175a53e..3e5c1df9c62 100644 --- a/src/api/providers/__tests__/openrouter.spec.ts +++ b/src/api/providers/__tests__/openrouter.spec.ts @@ -26,6 +26,7 @@ import { applyOpenRouterMoonshotK3Profile } from "../fetchers/openrouter" import { OpenRouterHandler } from "../openrouter" import { Package } from "../../../shared/package" import { makeApiHandlerOptions } from "../../../test-utils/api" +import type { Mock } from "vitest" import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" import { collectStreamAndParseToolCalls } from "../../../test-utils/native-tool-call-stream" import { clearAllMocks } from "../../../test-utils/reset" @@ -37,6 +38,14 @@ vitest.mock("delay", () => ({ }), })) +/** Replaces the auto-mocked OpenAI class's inherited chat namespace with a stub. */ +function stubOpenAiChatPrototype(create: Mock): void { + // The auto-mocked class is structurally incompatible with the narrow stub; the + // double assertion routes through unknown and names the one member provided. + const prototype = OpenAI as unknown as { prototype: { chat?: unknown } } + prototype.prototype.chat = { completions: { create } } +} + const mockCaptureException = vitest.fn() vitest.mock("@roo-code/telemetry", () => ({ @@ -403,9 +412,7 @@ describe("OpenRouterHandler", () => { // Mock OpenAI chat.completions.create const mockCreate = vitest.fn().mockResolvedValue(mockStream) - ;(OpenAI as any).prototype.chat = { - completions: { create: mockCreate }, - } as any + stubOpenAiChatPrototype(mockCreate) const systemPrompt = "test system prompt" const messages: Anthropic.Messages.MessageParam[] = [{ role: "user" as const, content: "test message" }] @@ -459,9 +466,7 @@ describe("OpenRouterHandler", () => { ]) const mockCreate = vitest.fn().mockResolvedValue(mockStream) - ;(OpenAI as any).prototype.chat = { - completions: { create: mockCreate }, - } as any + stubOpenAiChatPrototype(mockCreate) const messages: Anthropic.Messages.MessageParam[] = [ { role: "user", content: "message 1" }, @@ -600,9 +605,7 @@ describe("OpenRouterHandler", () => { const mockStream = asyncStreamFrom([{ error: { message: "API Error", code: 500 } }]) const mockCreate = vitest.fn().mockResolvedValue(mockStream) - ;(OpenAI as any).prototype.chat = { - completions: { create: mockCreate }, - } as any + stubOpenAiChatPrototype(mockCreate) const generator = handler.createMessage("test", []) await expect(generator.next()).rejects.toThrow("openrouter API Error 500: API Error") @@ -641,9 +644,7 @@ describe("OpenRouterHandler", () => { it("captures telemetry when createMessage throws an exception", async () => { const handler = new OpenRouterHandler(mockOptions) const mockCreate = vitest.fn().mockRejectedValue(new Error("Connection failed")) - ;(OpenAI as any).prototype.chat = { - completions: { create: mockCreate }, - } as any + stubOpenAiChatPrototype(mockCreate) const generator = handler.createMessage("test", []) await expect(generator.next()).rejects.toThrow() @@ -660,13 +661,10 @@ describe("OpenRouterHandler", () => { it("passes SDK exceptions with status 429 to telemetry (filtering happens in PostHogTelemetryClient)", async () => { const handler = new OpenRouterHandler(mockOptions) - const error = new Error("Rate limit exceeded: free-models-per-day") as any - error.status = 429 + const error = Object.assign(new Error("Rate limit exceeded: free-models-per-day"), { status: 429 }) const mockCreate = vitest.fn().mockRejectedValue(error) - ;(OpenAI as any).prototype.chat = { - completions: { create: mockCreate }, - } as any + stubOpenAiChatPrototype(mockCreate) const generator = handler.createMessage("test", []) await expect(generator.next()).rejects.toThrow("Rate limit exceeded") @@ -685,9 +683,7 @@ describe("OpenRouterHandler", () => { const handler = new OpenRouterHandler(mockOptions) const error = new Error("429 Rate limit exceeded: free-models-per-day") const mockCreate = vitest.fn().mockRejectedValue(error) - ;(OpenAI as any).prototype.chat = { - completions: { create: mockCreate }, - } as any + stubOpenAiChatPrototype(mockCreate) const generator = handler.createMessage("test", []) await expect(generator.next()).rejects.toThrow("429 Rate limit exceeded") @@ -706,9 +702,7 @@ describe("OpenRouterHandler", () => { const handler = new OpenRouterHandler(mockOptions) const error = new Error("Request failed due to rate limit") const mockCreate = vitest.fn().mockRejectedValue(error) - ;(OpenAI as any).prototype.chat = { - completions: { create: mockCreate }, - } as any + stubOpenAiChatPrototype(mockCreate) const generator = handler.createMessage("test", []) await expect(generator.next()).rejects.toThrow("rate limit") @@ -728,9 +722,7 @@ describe("OpenRouterHandler", () => { const mockStream = asyncStreamFrom([{ error: { message: "Rate limit exceeded", code: 429 } }]) const mockCreate = vitest.fn().mockResolvedValue(mockStream) - ;(OpenAI as any).prototype.chat = { - completions: { create: mockCreate }, - } as any + stubOpenAiChatPrototype(mockCreate) const generator = handler.createMessage("test", []) await expect(generator.next()).rejects.toThrow("openrouter API Error 429: Rate limit exceeded") @@ -855,9 +847,7 @@ describe("OpenRouterHandler", () => { ]) const mockCreate = vitest.fn().mockResolvedValue(mockStream) - ;(OpenAI as any).prototype.chat = { - completions: { create: mockCreate }, - } as any + stubOpenAiChatPrototype(mockCreate) const generator = handler.createMessage("test", []) const parserScope = NativeToolCallParser.createScope() @@ -1069,9 +1059,7 @@ describe("OpenRouterHandler", () => { const mockResponse = { choices: [{ message: { content: "test completion" } }] } const mockCreate = vitest.fn().mockResolvedValue(mockResponse) - ;(OpenAI as any).prototype.chat = { - completions: { create: mockCreate }, - } as any + stubOpenAiChatPrototype(mockCreate) const result = await handler.completePrompt("test prompt") @@ -1099,9 +1087,7 @@ describe("OpenRouterHandler", () => { } const mockCreate = vitest.fn().mockResolvedValue(mockError) - ;(OpenAI as any).prototype.chat = { - completions: { create: mockCreate }, - } as any + stubOpenAiChatPrototype(mockCreate) await expect(handler.completePrompt("test prompt")).rejects.toThrow("openrouter API Error 500: API Error") @@ -1122,9 +1108,7 @@ describe("OpenRouterHandler", () => { const handler = new OpenRouterHandler(mockOptions) const error = new Error("Unexpected error") const mockCreate = vitest.fn().mockRejectedValue(error) - ;(OpenAI as any).prototype.chat = { - completions: { create: mockCreate }, - } as any + stubOpenAiChatPrototype(mockCreate) await expect(handler.completePrompt("test prompt")).rejects.toThrow("Unexpected error") @@ -1141,12 +1125,9 @@ describe("OpenRouterHandler", () => { it("passes SDK exceptions with status 429 to telemetry (filtering happens in PostHogTelemetryClient)", async () => { const handler = new OpenRouterHandler(mockOptions) - const error = new Error("Rate limit exceeded: free-models-per-day") as any - error.status = 429 + const error = Object.assign(new Error("Rate limit exceeded: free-models-per-day"), { status: 429 }) const mockCreate = vitest.fn().mockRejectedValue(error) - ;(OpenAI as any).prototype.chat = { - completions: { create: mockCreate }, - } as any + stubOpenAiChatPrototype(mockCreate) await expect(handler.completePrompt("test prompt")).rejects.toThrow("Rate limit exceeded") @@ -1165,9 +1146,7 @@ describe("OpenRouterHandler", () => { const handler = new OpenRouterHandler(mockOptions) const error = new Error("429 Rate limit exceeded: free-models-per-day") const mockCreate = vitest.fn().mockRejectedValue(error) - ;(OpenAI as any).prototype.chat = { - completions: { create: mockCreate }, - } as any + stubOpenAiChatPrototype(mockCreate) await expect(handler.completePrompt("test prompt")).rejects.toThrow("429 Rate limit exceeded") @@ -1186,9 +1165,7 @@ describe("OpenRouterHandler", () => { const handler = new OpenRouterHandler(mockOptions) const error = new Error("Request failed due to rate limit") const mockCreate = vitest.fn().mockRejectedValue(error) - ;(OpenAI as any).prototype.chat = { - completions: { create: mockCreate }, - } as any + stubOpenAiChatPrototype(mockCreate) await expect(handler.completePrompt("test prompt")).rejects.toThrow("rate limit") @@ -1213,9 +1190,7 @@ describe("OpenRouterHandler", () => { } const mockCreate = vitest.fn().mockResolvedValue(mockError) - ;(OpenAI as any).prototype.chat = { - completions: { create: mockCreate }, - } as any + stubOpenAiChatPrototype(mockCreate) await expect(handler.completePrompt("test prompt")).rejects.toThrow( "openrouter API Error 429: Rate limit exceeded", diff --git a/src/api/providers/bedrock.ts b/src/api/providers/bedrock.ts index 2bb083cc7db..e8a29803836 100644 --- a/src/api/providers/bedrock.ts +++ b/src/api/providers/bedrock.ts @@ -56,18 +56,46 @@ import type { SingleCompletionHandler, ApiHandlerCreateMessageMetadata, Complete import { mergeAbortSignalAndTimeout } from "./utils/abort-signal" import { OutputTokenLimitError } from "./utils/output-token-limit-error" +import type { ProviderError } from "./utils/error-handler" +import type { ApiStreamChunk } from "../transform/stream" +import type { CachePointPlacement } from "../transform/cache-strategy/types" +import type { AnthropicReasoningParams } from "../transform/reasoning" /************************************************************************************ * * TYPES * *************************************************************************************/ +/** Parsed details of a custom ARN's resource path and region compatibility. */ +interface BedrockArnInfo { + isValid: boolean + region?: string + modelType?: string + modelId?: string + errorMessage?: string + crossRegionInference: boolean +} + +/** Fields the handler preserves from AWS SDK errors when rethrowing. */ +interface AwsSdkErrorShape { + status?: unknown + $metadata?: unknown + name?: string + __type?: unknown +} + // Define interface for Bedrock inference config interface BedrockInferenceConfig { maxTokens: number temperature?: number } +/** + * Local mirror of the SDK's Smithy DocumentType union. The SDK does not + * re-export it and @smithy/types is not a direct dependency. + */ +type DocumentType = null | boolean | number | string | DocumentType[] | { [prop: string]: DocumentType } + // Define interface for Bedrock additional model request fields // This includes thinking configuration, 1M context beta, and other model-specific parameters interface BedrockAdditionalModelFields { @@ -89,7 +117,6 @@ interface BedrockAdditionalModelFields { effort: string } anthropic_beta?: string[] - [key: string]: any // Add index signature to be compatible with DocumentType } // Define interface for Bedrock payload @@ -99,7 +126,7 @@ interface BedrockPayload { system?: SystemContentBlock[] inferenceConfig: BedrockInferenceConfig anthropic_version?: string - additionalModelRequestFields?: BedrockAdditionalModelFields + additionalModelRequestFields?: DocumentType toolConfig?: ToolConfiguration } @@ -222,7 +249,7 @@ export type UsageType = { export class AwsBedrockHandler extends BaseProvider implements SingleCompletionHandler { protected options: ProviderSettings private client: BedrockRuntimeClient - private arnInfo: any + private arnInfo!: BedrockArnInfo private readonly providerName = "Bedrock" constructor(options: ProviderSettings) { @@ -255,7 +282,7 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH // We will use the ARNs region, so execution can continue, but log an info statement. // Log a warning if there's a region mismatch between the ARN and the region selected by the user // We will use the ARNs region, so execution can continue, but log an info statement. - logger.info(this.arnInfo.errorMessage, { + logger.info(this.arnInfo.errorMessage ?? "", { ctx: "bedrock", selectedRegion: this.options.awsRegion, arnRegion: this.arnInfo.region, @@ -265,7 +292,6 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH } this.options.apiModelId = this.arnInfo.modelId - if (this.arnInfo.awsUseCrossRegionInference) this.options.awsUseCrossRegionInference = true } if (!this.options.modelTemperature) { @@ -519,11 +545,13 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH // Check if 1M context is enabled for supported Claude 4 models // Use parseBaseModelId to handle cross-region inference prefixes (computed above) const is1MContextEnabled = - BEDROCK_1M_CONTEXT_MODEL_IDS.includes(baseModelId as any) && this.options.awsBedrock1MContext + (BEDROCK_1M_CONTEXT_MODEL_IDS as readonly string[]).includes(baseModelId) && + this.options.awsBedrock1MContext // Determine if service tier should be applied (checked later when building payload) const useServiceTier = - this.options.awsBedrockServiceTier && BEDROCK_SERVICE_TIER_MODEL_IDS.includes(baseModelId as any) + this.options.awsBedrockServiceTier && + (BEDROCK_SERVICE_TIER_MODEL_IDS as readonly string[]).includes(baseModelId) if (useServiceTier) { logger.info("Service tier specified for Bedrock request", { ctx: "bedrock", @@ -568,7 +596,11 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH messages: formatted.messages, system: formatted.system, inferenceConfig, - ...(additionalModelRequestFields && { additionalModelRequestFields }), + ...(additionalModelRequestFields && { + // The SDK types this field as the Smithy Document union; the built object is + // structurally a Document, so the boundary routes through unknown. + additionalModelRequestFields: additionalModelRequestFields as unknown as DocumentType, + }), // Add anthropic_version at top level when using thinking features ...(thinkingEnabled && { anthropic_version: "bedrock-2023-05-31" }), toolConfig, @@ -847,26 +879,24 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH const errorChunks = this.handleBedrockError(error, true) // true for streaming context // Yield each chunk individually to ensure type compatibility for (const chunk of errorChunks) { - yield chunk as any // Cast to any to bypass type checking since we know the structure is correct + yield chunk } // Re-throw with enhanced error message for retry system const enhancedErrorMessage = this.formatErrorMessage(error, this.getErrorType(error), true) if (error instanceof Error) { - const enhancedError = new Error(enhancedErrorMessage) + const enhancedError = new Error(enhancedErrorMessage) as ProviderError // Preserve important properties from the original error enhancedError.name = error.name // Validate and preserve status property - if ("status" in error && typeof (error as any).status === "number") { - ;(enhancedError as any).status = (error as any).status + const sourceError = error as AwsSdkErrorShape + if ("status" in error && typeof sourceError.status === "number") { + enhancedError.status = sourceError.status } // Validate and preserve $metadata property - if ( - "$metadata" in error && - typeof (error as any).$metadata === "object" && - (error as any).$metadata !== null - ) { - ;(enhancedError as any).$metadata = (error as any).$metadata + const metadata = sourceError.$metadata + if ("$metadata" in error && typeof metadata === "object" && metadata !== null) { + enhancedError.$metadata = metadata } throw enhancedError } else { @@ -954,26 +984,23 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH TelemetryService.instance.captureException(apiError) // Use the extracted error handling method for all errors - const errorResult = this.handleBedrockError(error, false) // false for non-streaming context - // Since we're in a non-streaming context, we know the result is a string - const errorMessage = errorResult as string + // In a non-streaming context the overload resolves to the plain message. + const errorMessage = this.handleBedrockError(error, false) // Create enhanced error for retry system - const enhancedError = new Error(errorMessage) + const enhancedError = new Error(errorMessage) as ProviderError if (error instanceof Error) { // Preserve important properties from the original error enhancedError.name = error.name // Validate and preserve status property - if ("status" in error && typeof (error as any).status === "number") { - ;(enhancedError as any).status = (error as any).status + const sourceError = error as AwsSdkErrorShape + if ("status" in error && typeof sourceError.status === "number") { + enhancedError.status = sourceError.status } // Validate and preserve $metadata property - if ( - "$metadata" in error && - typeof (error as any).$metadata === "object" && - (error as any).$metadata !== null - ) { - ;(enhancedError as any).$metadata = (error as any).$metadata + const metadata = sourceError.$metadata + if ("$metadata" in error && typeof metadata === "object" && metadata !== null) { + enhancedError.$metadata = metadata } } throw enhancedError @@ -987,7 +1014,7 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH anthropicMessages: Anthropic.Messages.MessageParam[] | { role: string; content: string }[], systemMessage?: string, usePromptCache: boolean = false, - modelInfo?: any, + modelInfo?: ModelInfo, conversationId?: string, // Optional conversation ID to track cache points across messages ): { system: SystemContentBlock[]; messages: Message[] } { // First convert messages using shared converter for proper image handling @@ -1008,7 +1035,9 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH supportsPromptCache: modelInfo?.supportsPromptCache || false, maxCachePoints: modelInfo?.maxCachePoints || 0, minTokensPerCachePoint: modelInfo?.minTokensPerCachePoint || 50, - cachableFields: modelInfo?.cachableFields || [], + // ModelInfo declares cachableFields as string[]; the cache strategy tracks the + // three known fields, so narrow here where the model catalog guarantees them. + cachableFields: (modelInfo?.cachableFields ?? []) as CacheModelInfo["cachableFields"], } // Get previous cache point placements for this conversation if available @@ -1064,7 +1093,7 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH info: { maxTokens: 0, contextWindow: 0, supportsPromptCache: false, supportsImages: false }, } - private parseArn(arn: string, region?: string) { + private parseArn(arn: string, region?: string): BedrockArnInfo { /* * VIA Roo analysis: platform-independent Regex. It's designed to parse Amazon Bedrock ARNs and doesn't rely on any platform-specific features * like file path separators, line endings, or case sensitivity behaviors. The forward slashes in the regex are properly escaped and @@ -1095,14 +1124,7 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH if (match && match[1] && match[3] && match[4]) { // Create the result object - const result: { - isValid: boolean - region?: string - modelType?: string - modelId?: string - errorMessage?: string - crossRegionInference: boolean - } = { + const result: BedrockArnInfo = { isValid: true, crossRegionInference: false, // Default to false } @@ -1148,7 +1170,7 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH */ private getCustomArnLookupModelId(): string { if (this.arnInfo.modelType === "foundation-model") { - return this.arnInfo.modelId + return this.arnInfo.modelId! } const baseModelId = resolveBedrockCustomArnBaseModelId( @@ -1161,7 +1183,7 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH return this.options.awsCustomArnBaseModelId === BEDROCK_CUSTOM_ARN_OTHER_BASE_MODEL ? BEDROCK_CUSTOM_ARN_OTHER_BASE_MODEL - : this.arnInfo.modelId + : this.arnInfo.modelId! } /** @@ -1244,7 +1266,7 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH info: ModelInfo maxTokens?: number temperature?: number - reasoning?: any + reasoning?: AnthropicReasoningParams reasoningBudget?: number } { if (this.costModelConfig?.id?.trim().length > 0) { @@ -1277,7 +1299,7 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH const baseIdForGlobal = this.parseBaseModelId(modelConfig.id) if ( this.options.awsUseGlobalInference && - BEDROCK_GLOBAL_INFERENCE_MODEL_IDS.includes(baseIdForGlobal as any) + (BEDROCK_GLOBAL_INFERENCE_MODEL_IDS as readonly string[]).includes(baseIdForGlobal) ) { modelConfig.id = `global.${baseIdForGlobal}` } @@ -1293,7 +1315,10 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH // Check if 1M context is enabled for supported Claude 4 models // getCapabilityModelId handles cross-region prefixes and custom ARNs const baseModelId = this.getCapabilityModelId(modelConfig.id) - if (BEDROCK_1M_CONTEXT_MODEL_IDS.includes(baseModelId as any) && this.options.awsBedrock1MContext) { + if ( + (BEDROCK_1M_CONTEXT_MODEL_IDS as readonly string[]).includes(baseModelId) && + this.options.awsBedrock1MContext + ) { // Update context window and pricing to 1M tier when 1M context beta is enabled const tier = modelConfig.info.tiers?.[0] modelConfig.info = { @@ -1321,7 +1346,10 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH // Apply service tier pricing if specified and model supports it const baseModelIdForTier = this.getCapabilityModelId(modelConfig.id) - if (this.options.awsBedrockServiceTier && BEDROCK_SERVICE_TIER_MODEL_IDS.includes(baseModelIdForTier as any)) { + if ( + this.options.awsBedrockServiceTier && + (BEDROCK_SERVICE_TIER_MODEL_IDS as readonly string[]).includes(baseModelIdForTier) + ) { const pricingMultiplier = BEDROCK_SERVICE_TIER_PRICING[this.options.awsBedrockServiceTier] if (pricingMultiplier && pricingMultiplier !== 1.0) { // Apply pricing multiplier to all price fields @@ -1349,7 +1377,7 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH info: ModelInfo maxTokens?: number temperature?: number - reasoning?: any + reasoning?: AnthropicReasoningParams reasoningBudget?: number } } @@ -1361,17 +1389,14 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH *************************************************************************************/ // Store previous cache point placements for maintaining consistency across consecutive messages - private previousCachePointPlacements: { [conversationId: string]: any[] } = {} + private previousCachePointPlacements: { [conversationId: string]: CachePointPlacement[] } = {} private supportsAwsPromptCache(modelConfig: { id: BedrockModelId | string; info: ModelInfo }): boolean | undefined { - // Check if the model supports prompt cache - // The cachableFields property is not part of the ModelInfo type in schemas - // but it's used in the bedrockModels object in shared/api.ts + // Check if the model supports prompt cache via the optional cachableFields list return ( modelConfig?.info?.supportsPromptCache && - // Use optional chaining and type assertion to access cachableFields - (modelConfig?.info as any)?.cachableFields && - (modelConfig?.info as any)?.cachableFields?.length > 0 + !!modelConfig?.info?.cachableFields && + modelConfig.info.cachableFields.length > 0 ) } @@ -1649,12 +1674,13 @@ Please check: } // Check for HTTP 429 status code (Too Many Requests) - if ((error as any).status === 429 || (error as any).$metadata?.httpStatusCode === 429) { + const awsError = error as AwsSdkErrorShape & { $metadata?: { httpStatusCode?: unknown } } + if (awsError.status === 429 || awsError.$metadata?.httpStatusCode === 429) { return "THROTTLING" } // Check for Amazon Bedrock specific throttling exception names - if ((error as any).name === "ThrottlingException" || (error as any).__type === "ThrottlingException") { + if (awsError.name === "ThrottlingException" || awsError.__type === "ThrottlingException") { return "THROTTLING" } @@ -1728,10 +1754,11 @@ Please check: * @param isStreamContext Whether the error occurred in a streaming context (true) or not (false) * @returns Error message string for non-streaming context or array of stream chunks for streaming context */ - private handleBedrockError( - error: unknown, - isStreamContext: boolean, - ): string | Array<{ type: string; text?: string; inputTokens?: number; outputTokens?: number }> { + // Streaming callers receive the error as yieldable chunks; completePrompt reads + // the plain message. The overloads keep each call site on the precise shape. + private handleBedrockError(error: unknown, isStreamContext: true): ApiStreamChunk[] + private handleBedrockError(error: unknown, isStreamContext: false): string + private handleBedrockError(error: unknown, isStreamContext: boolean): string | ApiStreamChunk[] { // Determine error type const errorType = this.getErrorType(error) diff --git a/src/api/providers/moonshot.ts b/src/api/providers/moonshot.ts index c0143308f92..04e7b153b35 100644 --- a/src/api/providers/moonshot.ts +++ b/src/api/providers/moonshot.ts @@ -12,6 +12,17 @@ import { OpenAiHandler } from "./openai" import { NOT_PROVIDED } from "./constants" import { getMoonshotModels } from "./fetchers/moonshot" +/** + * Moonshot usage payload. Cache hits arrive in `prompt_tokens_details.cached_tokens` + * (OpenAI-style); some gateways also surface a top-level `cached_tokens`. + */ +interface MoonshotUsage { + prompt_tokens?: number + completion_tokens?: number + prompt_tokens_details?: { cached_tokens?: number } | null + cached_tokens?: number +} + export class MoonshotHandler extends OpenAiHandler { constructor(options: ApiHandlerOptions) { // Map Moonshot-specific options to the OpenAI-compatible options that @@ -75,7 +86,10 @@ export class MoonshotHandler extends OpenAiHandler { * Override to handle Moonshot's usage metrics, including caching. * Moonshot returns cached_tokens in a different location than standard OpenAI. */ - protected override processUsageMetrics(usage: any, _modelInfo?: ModelInfo): ApiStreamUsageChunk { + protected override processUsageMetrics( + usage: MoonshotUsage | null | undefined, + _modelInfo?: ModelInfo, + ): ApiStreamUsageChunk { return { type: "usage", inputTokens: usage?.prompt_tokens || 0, diff --git a/src/api/providers/openai-codex.ts b/src/api/providers/openai-codex.ts index 65a32f3928e..a27f28ff8aa 100644 --- a/src/api/providers/openai-codex.ts +++ b/src/api/providers/openai-codex.ts @@ -39,6 +39,140 @@ import { export type OpenAiCodexModel = ReturnType +/** Cache-detail fields shared by the Chat Completions and Responses usage payloads. */ +interface OpenAiUsageTokenDetails { + cached_tokens?: number + cache_miss_tokens?: number + cache_write_tokens?: number + /** + * TTL split of cache writes on the Responses API. Not declared by the installed + * SDK types, so it is read defensively. + */ + cache_write_tokens_details?: { ttl_12h_tokens?: number } +} + +/** + * Usage payload this handler normalizes, covering the Responses API + * (input_tokens/output_tokens) and Chat Completions (prompt_tokens/completion_tokens) + * families. Every field is optional because normalizeUsage guards each read. + */ +interface OpenAiUsage { + input_tokens?: number + output_tokens?: number + prompt_tokens?: number + completion_tokens?: number + input_tokens_details?: OpenAiUsageTokenDetails + prompt_tokens_details?: OpenAiUsageTokenDetails + output_tokens_details?: { reasoning_tokens?: number } + completion_tokens_details?: { reasoning_tokens?: number } + // Anthropic-style top-level cache fields also flow through normalizeUsage. + cache_creation_input_tokens?: number + cache_write_tokens?: number + cache_read_input_tokens?: number + cache_read_tokens?: number + cached_tokens?: number +} + +/** Output content parts this handler inspects across SDK and variant payloads. */ +interface ResponsesOutputContent { + type?: string + text?: string +} + +/** Output items this handler inspects: a superset of the SDK union and variant payloads. */ +interface ResponsesOutputItem { + type?: string + text?: string + id?: string + call_id?: string + tool_call_id?: string + name?: string + function_name?: string + function?: { name?: string; arguments?: string } + arguments?: string | Record + input?: string + content?: ResponsesOutputContent[] + encrypted_content?: string +} + +/** + * Stream events this handler processes: a superset of the SDK ResponseStreamEvent + * union and the non-standard variant payloads (alternate event names, flat usage, + * chat-style choices) that the fallback paths feed through processEvent. + */ +interface ResponsesStreamEvent { + type?: string + delta?: string + text?: string + output_text?: string + arguments?: string + index?: number + id?: string + call_id?: string + tool_call_id?: string + name?: string + function_name?: string + function?: { name?: string; arguments?: string } + item?: ResponsesOutputItem + part?: { type?: string; text?: string | { value?: string } } + response?: { + id?: string + output?: ResponsesOutputItem[] + usage?: OpenAiUsage + } + usage?: OpenAiUsage + choices?: Array<{ delta?: { content?: string } }> +} + +/** Conversation input items built by formatFullConversation for the Responses API. */ +type ResponsesInputItem = + | { + role: "user" + content: Array<{ type: "input_text"; text: string } | { type: "input_image"; image_url: string }> + } + | { role: "assistant"; content: Array<{ type: "output_text"; text: string }> } + | { type: "function_call"; call_id: string; name: string; arguments: string } + | { type: "function_call_output"; call_id: string; output: string } + | { type: "message"; role: "developer"; content: Array<{ type: "input_text"; text: string }> } + | { type: "additional_tools"; role: "developer"; tools: NonNullable } + // Reasoning items already formatted in the API history pass through as-is. + | Anthropic.Messages.MessageParam + +/** JSON-schema fragment shape used by the OpenAI strict-mode parameter processors. */ +interface OpenAiToolParameterSchema { + type?: string + properties?: Record + items?: OpenAiToolParameterSchema + additionalProperties?: boolean | OpenAiToolParameterSchema + required?: string[] + [key: string]: unknown +} + +/** Request body built for the Codex Responses API (including Responses Lite fields). */ +interface ResponsesRequestBody { + model: string + input: ResponsesInputItem[] + stream: boolean + reasoning?: { effort?: ReasoningEffortExtended; summary?: "auto"; context?: string } + text?: { verbosity: VerbosityLevel } + temperature?: number + store?: boolean + instructions?: string + [SERVICE_TIER_KEY]?: OpenAiCodexRequestServiceTier + include?: string[] + prompt_cache_key?: string + session_id?: string + tools?: Array<{ + type: "function" + name: string + description?: string + parameters?: OpenAiToolParameterSchema + strict?: boolean + }> + tool_choice?: OpenAI.Chat.ChatCompletionCreateParams["tool_choice"] + parallel_tool_calls?: boolean +} + type OpenAiCodexRequestServiceTier = typeof OpenAiCodexServiceTier.Priority /** @@ -69,7 +203,7 @@ const getOpenAiCodexServiceTier = (options: ApiHandlerOptions): OpenAiCodexReque ? OpenAiCodexServiceTier.Priority : undefined -function stripInputImageDetail(value: any): any { +function stripInputImageDetail(value: unknown): unknown { if (Array.isArray(value)) { return value.map(stripInputImageDetail) } @@ -80,41 +214,43 @@ function stripInputImageDetail(value: any): any { return Object.fromEntries( Object.entries(value) - .filter(([key]) => value.type !== "input_image" || key !== "detail") + .filter(([key]) => (value as { type?: unknown }).type !== "input_image" || key !== "detail") .map(([key, child]) => [key, stripInputImageDetail(child)]), ) } -export function transformResponsesLiteBody(requestBody: any, effectiveSessionId: string): any { - if (!Array.isArray(requestBody.input)) { +export function transformResponsesLiteBody(requestBody: unknown, effectiveSessionId: string): ResponsesRequestBody { + // The Lite transform validates locally (callers may pass arbitrary bodies), so + // the raw input is narrowed to the request-body shape after each guard. + const body = requestBody as ResponsesRequestBody + if (!Array.isArray(body.input)) { throw new Error("Invalid Responses Lite request: input must be an array.") } - if (requestBody.tools !== undefined && !Array.isArray(requestBody.tools)) { + if (body.tools !== undefined && !Array.isArray(body.tools)) { throw new Error("Invalid Responses Lite request: tools must be an array when provided.") } - if (requestBody.instructions !== undefined && typeof requestBody.instructions !== "string") { + if (body.instructions !== undefined && typeof body.instructions !== "string") { throw new Error("Invalid Responses Lite request: instructions must be a string when provided.") } - const { tools, instructions, ...rest } = requestBody - const transformedInput = stripInputImageDetail(requestBody.input) + const { tools, instructions, ...rest } = body + // The walker is shape-preserving: it only drops `detail` keys from input_image parts. + const transformedInput = stripInputImageDetail(body.input) as ResponsesInputItem[] const reasoning = - requestBody.reasoning && typeof requestBody.reasoning === "object" && !Array.isArray(requestBody.reasoning) - ? requestBody.reasoning - : {} + body.reasoning && typeof body.reasoning === "object" && !Array.isArray(body.reasoning) ? body.reasoning : {} return { ...rest, input: [ { type: "additional_tools", role: "developer", tools: tools ?? [] }, ...(typeof instructions === "string" && instructions.length > 0 - ? [ + ? ([ { type: "message", role: "developer", content: [{ type: "input_text", text: instructions }], }, - ] + ] satisfies ResponsesInputItem[]) : []), ...transformedInput, ], @@ -144,7 +280,7 @@ export class OpenAiCodexHandler extends BaseProvider implements SingleCompletion private readonly providerName = "OpenAI Codex" private client?: OpenAI // Complete response output array - private lastResponseOutput: any[] | undefined + private lastResponseOutput: ResponsesOutputItem[] | undefined // Last top-level response id private lastResponseId: string | undefined // Session ID for the Codex API (persists for the lifetime of the handler) @@ -197,15 +333,16 @@ export class OpenAiCodexHandler extends BaseProvider implements SingleCompletion this.sessionId = uuidv7() } - private normalizeUsage(usage: any, _model: OpenAiCodexModel): ApiStreamUsageChunk | undefined { + private normalizeUsage( + usage: OpenAiUsage | null | undefined, + _model: OpenAiCodexModel, + ): ApiStreamUsageChunk | undefined { if (!usage) return undefined const inputDetails = usage.input_tokens_details ?? usage.prompt_tokens_details - const hasCachedTokens = typeof inputDetails?.cached_tokens === "number" - const hasCacheMissTokens = typeof inputDetails?.cache_miss_tokens === "number" - const cachedFromDetails = hasCachedTokens ? inputDetails.cached_tokens : 0 - const missFromDetails = hasCacheMissTokens ? inputDetails.cache_miss_tokens : 0 + const cachedFromDetails = typeof inputDetails?.cached_tokens === "number" ? inputDetails.cached_tokens : 0 + const missFromDetails = typeof inputDetails?.cache_miss_tokens === "number" ? inputDetails.cache_miss_tokens : 0 let totalInputTokens = usage.input_tokens ?? usage.prompt_tokens ?? 0 if (totalInputTokens === 0 && inputDetails && (cachedFromDetails > 0 || missFromDetails > 0)) { @@ -305,7 +442,7 @@ export class OpenAiCodexHandler extends BaseProvider implements SingleCompletion // Notably: max_output_tokens and prompt_cache_retention may be rejected const effectiveSessionId = metadata?.taskId || this.sessionId const baseRequestBody = this.buildRequestBody(model, formattedInput, systemPrompt, reasoningEffort, metadata) - let requestBody: any + let requestBody: ResponsesRequestBody try { requestBody = RESPONSES_LITE_MODEL_IDS.has(model.id) ? this.buildResponsesLiteRequestBody(baseRequestBody, effectiveSessionId) @@ -363,18 +500,21 @@ export class OpenAiCodexHandler extends BaseProvider implements SingleCompletion } } - private buildResponsesLiteRequestBody(baseRequestBody: any, effectiveSessionId: string): any { + private buildResponsesLiteRequestBody( + baseRequestBody: ResponsesRequestBody, + effectiveSessionId: string, + ): ResponsesRequestBody { return transformResponsesLiteBody(baseRequestBody, effectiveSessionId) } private buildRequestBody( model: OpenAiCodexModel, - formattedInput: any, + formattedInput: ResponsesInputItem[], systemPrompt: string, reasoningEffort: ReasoningEffortExtended | undefined, metadata?: ApiHandlerCreateMessageMetadata, - ): any { - const ensureAllRequired = (schema: any): any => { + ): ResponsesRequestBody { + const ensureAllRequired = (schema: OpenAiToolParameterSchema): OpenAiToolParameterSchema => { if (!schema || typeof schema !== "object" || schema.type !== "object") { return schema } @@ -406,7 +546,7 @@ export class OpenAiCodexHandler extends BaseProvider implements SingleCompletion return result } - const ensureAdditionalPropertiesFalse = (schema: any): any => { + const ensureAdditionalPropertiesFalse = (schema: OpenAiToolParameterSchema): OpenAiToolParameterSchema => { if (!schema || typeof schema !== "object" || schema.type !== "object") { return schema } @@ -435,28 +575,6 @@ export class OpenAiCodexHandler extends BaseProvider implements SingleCompletion return result } - interface ResponsesRequestBody { - model: string - input: Array<{ role: "user" | "assistant"; content: any[] } | { type: string; content: string }> - stream: boolean - [SERVICE_TIER_KEY]?: OpenAiCodexRequestServiceTier - reasoning?: { effort?: ReasoningEffortExtended; summary?: "auto" } - temperature?: number - store?: boolean - instructions?: string - include?: string[] - tools?: Array<{ - type: "function" - name: string - description?: string - parameters?: any - strict?: boolean - }> - tool_choice?: any - parallel_tool_calls?: boolean - text?: { verbosity: VerbosityLevel } - } - // Per the implementation guide: Codex backend may reject max_output_tokens // and prompt_cache_retention, so we omit them const serviceTier = getOpenAiCodexServiceTier(this.options) @@ -486,8 +604,8 @@ export class OpenAiCodexHandler extends BaseProvider implements SingleCompletion name: tool.function.name, description: tool.function.description, parameters: isMcp - ? ensureAdditionalPropertiesFalse(tool.function.parameters) - : ensureAllRequired(tool.function.parameters), + ? ensureAdditionalPropertiesFalse(tool.function.parameters as OpenAiToolParameterSchema) + : ensureAllRequired(tool.function.parameters as OpenAiToolParameterSchema), strict: !isMcp, } }), @@ -504,7 +622,7 @@ export class OpenAiCodexHandler extends BaseProvider implements SingleCompletion } private async *executeRequest( - requestBody: any, + requestBody: ResponsesRequestBody, model: OpenAiCodexModel, accessToken: string, effectiveSessionId: string, @@ -554,13 +672,19 @@ export class OpenAiCodexHandler extends BaseProvider implements SingleCompletion timeout: this.timeoutMs, }) - const stream = (await (client as any).responses.create(requestBody, { - signal: abortController.signal, - // If the SDK supports per-request overrides, ensure headers are present. - headers: codexHeaders, - })) as AsyncIterable - - if (typeof (stream as any)?.[Symbol.asyncIterator] !== "function") { + // The SDK's params type does not declare the Codex custom body fields; the + // boundary routes through unknown, and stream events are parsed as the + // ResponsesStreamEvent superset. + const stream = (await client.responses.create( + requestBody as unknown as OpenAI.Responses.ResponseCreateParamsStreaming, + { + signal: abortController.signal, + // If the SDK supports per-request overrides, ensure headers are present. + headers: codexHeaders, + }, + )) as AsyncIterable + + if (typeof stream?.[Symbol.asyncIterator] !== "function") { throw new Error( "OpenAI SDK did not return an AsyncIterable for Responses API streaming. Falling back to SSE.", ) @@ -613,19 +737,24 @@ export class OpenAiCodexHandler extends BaseProvider implements SingleCompletion } } - private formatFullConversation(_systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): any { - const formattedInput: any[] = [] + private formatFullConversation( + _systemPrompt: string, + messages: Anthropic.Messages.MessageParam[], + ): ResponsesInputItem[] { + const formattedInput: ResponsesInputItem[] = [] for (const message of messages) { // Check if this is a reasoning item - if ((message as any).type === "reasoning") { + if ((message as { type?: unknown }).type === "reasoning") { formattedInput.push(message) continue } if (message.role === "user") { - const content: any[] = [] - const toolResults: any[] = [] + const content: Array< + { type: "input_text"; text: string } | { type: "input_image"; image_url: string } + > = [] + const toolResults: Array<{ type: "function_call_output"; call_id: string; output: string }> = [] if (typeof message.content === "string") { content.push({ type: "input_text", text: message.content }) @@ -662,8 +791,8 @@ export class OpenAiCodexHandler extends BaseProvider implements SingleCompletion formattedInput.push(...toolResults) } } else if (message.role === "assistant") { - const content: any[] = [] - const toolCalls: any[] = [] + const content: Array<{ type: "output_text"; text: string }> = [] + const toolCalls: Array<{ type: "function_call"; call_id: string; name: string; arguments: string }> = [] if (typeof message.content === "string") { content.push({ type: "output_text", text: message.content }) @@ -697,7 +826,7 @@ export class OpenAiCodexHandler extends BaseProvider implements SingleCompletion } private async *makeCodexRequest( - requestBody: any, + requestBody: ResponsesRequestBody, model: OpenAiCodexModel, accessToken: string, effectiveSessionId: string, @@ -1103,12 +1232,12 @@ export class OpenAiCodexHandler extends BaseProvider implements SingleCompletion } } - private async *processEvent(event: any, model: OpenAiCodexModel): ApiStream { + private async *processEvent(event: ResponsesStreamEvent, model: OpenAiCodexModel): ApiStream { if (event?.response?.output && Array.isArray(event.response.output)) { this.lastResponseOutput = event.response.output } if (event?.response?.id) { - this.lastResponseId = event.response.id as string + this.lastResponseId = event.response.id } // Handle text deltas diff --git a/src/api/providers/openai-native.ts b/src/api/providers/openai-native.ts index 777c614f610..4e27d1b576f 100644 --- a/src/api/providers/openai-native.ts +++ b/src/api/providers/openai-native.ts @@ -40,6 +40,40 @@ import { getNumericHttpStatus, hasNumericHttpStatus } from "./utils/error-handle export type OpenAiNativeModel = ReturnType +/** Cache-detail fields shared by the Chat Completions and Responses usage payloads. */ +interface OpenAiUsageTokenDetails { + cached_tokens?: number + cache_miss_tokens?: number + cache_write_tokens?: number + /** + * TTL split of cache writes on the Responses API. Not declared by the installed + * SDK types (openai@5.23.2), so it is read defensively. + */ + cache_write_tokens_details?: { ttl_12h_tokens?: number } +} + +/** + * Usage payload this handler normalizes, covering the Responses API + * (input_tokens/output_tokens) and Chat Completions (prompt_tokens/completion_tokens) + * families. Every field is optional because normalizeUsage guards each read. + */ +interface OpenAiUsage { + input_tokens?: number + output_tokens?: number + prompt_tokens?: number + completion_tokens?: number + input_tokens_details?: OpenAiUsageTokenDetails + prompt_tokens_details?: OpenAiUsageTokenDetails + output_tokens_details?: { reasoning_tokens?: number } + completion_tokens_details?: { reasoning_tokens?: number } + // Anthropic-style top-level cache fields also flow through normalizeUsage. + cache_creation_input_tokens?: number + cache_write_tokens?: number + cache_read_input_tokens?: number + cache_read_tokens?: number + cached_tokens?: number +} + /** * OpenAI caps `prompt_cache_key` at 64 characters; longer values are rejected with a 400. * Task ids are uuidv7 today (36 chars), so this is a guard rather than a routine truncation. @@ -133,17 +167,18 @@ export class OpenAiNativeHandler extends BaseProvider implements SingleCompletio }) } - private normalizeUsage(usage: any, model: OpenAiNativeModel): ApiStreamUsageChunk | undefined { + private normalizeUsage( + usage: OpenAiUsage | null | undefined, + model: Pick, + ): ApiStreamUsageChunk | undefined { if (!usage) return undefined // Prefer detailed shapes when available (Responses API) const inputDetails = usage.input_tokens_details ?? usage.prompt_tokens_details // Extract cache information from details with better readability - const hasCachedTokens = typeof inputDetails?.cached_tokens === "number" - const hasCacheMissTokens = typeof inputDetails?.cache_miss_tokens === "number" - const cachedFromDetails = hasCachedTokens ? inputDetails.cached_tokens : 0 - const missFromDetails = hasCacheMissTokens ? inputDetails.cache_miss_tokens : 0 + const cachedFromDetails = typeof inputDetails?.cached_tokens === "number" ? inputDetails.cached_tokens : 0 + const missFromDetails = typeof inputDetails?.cache_miss_tokens === "number" ? inputDetails.cache_miss_tokens : 0 const writesFromDetails = typeof inputDetails?.cache_write_tokens === "number" ? inputDetails.cache_write_tokens : 0 diff --git a/src/api/providers/utils/__tests__/error-handler.spec.ts b/src/api/providers/utils/__tests__/error-handler.spec.ts index 3e6bfc9271a..12b68730141 100644 --- a/src/api/providers/utils/__tests__/error-handler.spec.ts +++ b/src/api/providers/utils/__tests__/error-handler.spec.ts @@ -5,25 +5,25 @@ describe("handleProviderError", () => { describe("HTTP status preservation", () => { it("should preserve status code from Error with status field", () => { - const error = new Error("API request failed") as any - error.status = 401 + const error = Object.assign(new Error("API request failed"), { status: 401 }) const result = handleProviderError(error, providerName) expect(result).toBeInstanceOf(Error) expect(result.message).toContain("TestProvider completion error") - expect((result as any).status).toBe(401) + expect(result.status).toBe(401) }) it("should preserve status code from Error with nested error structure", () => { - const error = new Error("Wrapped error") as any - error.status = 429 - error.errorDetails = [{ "@type": "type.googleapis.com/google.rpc.RetryInfo" }] + const error = Object.assign(new Error("Wrapped error"), { + status: 429, + errorDetails: [{ "@type": "type.googleapis.com/google.rpc.RetryInfo" }], + }) const result = handleProviderError(error, providerName) - expect((result as any).status).toBe(429) - expect((result as any).errorDetails).toBeDefined() + expect(result.status).toBe(429) + expect(result.errorDetails).toBeDefined() }) it("should preserve status from non-Error exception", () => { @@ -35,7 +35,7 @@ describe("handleProviderError", () => { const result = handleProviderError(error, providerName) expect(result).toBeInstanceOf(Error) - expect((result as any).status).toBe(500) + expect(result.status).toBe(500) }) it("should not add status field if original error lacks it", () => { @@ -44,7 +44,7 @@ describe("handleProviderError", () => { const result = handleProviderError(error, providerName) expect(result).toBeInstanceOf(Error) - expect((result as any).status).toBeUndefined() + expect(result.status).toBeUndefined() }) // AI SDK APICallError exposes the HTTP status as statusCode, not status — the same @@ -125,31 +125,32 @@ describe("handleProviderError", () => { describe("errorDetails preservation", () => { it("should preserve errorDetails array from original error", () => { - const error = new Error("Rate limited") as any - error.status = 429 - error.errorDetails = [{ "@type": "type.googleapis.com/google.rpc.RetryInfo", retryDelay: "5s" }] + const error = Object.assign(new Error("Rate limited"), { + status: 429, + errorDetails: [{ "@type": "type.googleapis.com/google.rpc.RetryInfo", retryDelay: "5s" }], + }) const result = handleProviderError(error, providerName) - expect((result as any).errorDetails).toEqual(error.errorDetails) + expect(result.errorDetails).toEqual(error.errorDetails) }) it("should preserve code field from original error", () => { - const error = new Error("Bad request") as any - error.code = "invalid_request" + const error = Object.assign(new Error("Bad request"), { code: "invalid_request" }) const result = handleProviderError(error, providerName) - expect((result as any).code).toBe("invalid_request") + expect(result.code).toBe("invalid_request") }) it("should preserve AWS $metadata from original error", () => { - const error = new Error("AWS error") as any - error.$metadata = { httpStatusCode: 403, requestId: "test-123" } + const error = Object.assign(new Error("AWS error"), { + $metadata: { httpStatusCode: 403, requestId: "test-123" }, + }) const result = handleProviderError(error, providerName) - expect((result as any).$metadata).toEqual(error.$metadata) + expect(result.$metadata).toEqual(error.$metadata) }) }) @@ -183,15 +184,14 @@ describe("handleProviderError", () => { }) it("should preserve status even with custom transformer", () => { - const error = new Error("Rate limited") as any - error.status = 429 + const error = Object.assign(new Error("Rate limited"), { status: 429 }) const result = handleProviderError(error, providerName, { messageTransformer: (msg) => `Transformed: ${msg}`, }) expect(result.message).toBe("Transformed: Rate limited") - expect((result as any).status).toBe(429) + expect(result.status).toBe(429) }) }) @@ -207,14 +207,13 @@ describe("handleProviderError", () => { }) it("should preserve status even for ByteString errors", () => { - const error = new Error("Cannot convert argument to a ByteString") as any - error.status = 400 + const error = Object.assign(new Error("Cannot convert argument to a ByteString"), { status: 400 }) const result = handleProviderError(error, providerName) // Even though ByteString errors are typically client-side, // we preserve any status metadata that exists for debugging purposes - expect((result as any).status).toBe(400) + expect(result.status).toBe(400) }) }) @@ -228,12 +227,13 @@ describe("handleProviderError", () => { }) it("should handle error with nested metadata", () => { - const error = new Error("Network error") as any - error.error = { - metadata: { - raw: "Connection refused", + const error = Object.assign(new Error("Network error"), { + error: { + metadata: { + raw: "Connection refused", + }, }, - } + }) const result = handleProviderError(error, providerName) @@ -263,39 +263,39 @@ describe("handleProviderError", () => { describe("real-world error scenarios", () => { it("should handle 401 Unauthorized with status and message", () => { - const error = new Error("Unauthorized") as any - error.status = 401 + const error = Object.assign(new Error("Unauthorized"), { status: 401 }) const result = handleProviderError(error, providerName) expect(result.message).toContain("Unauthorized") - expect((result as any).status).toBe(401) + expect(result.status).toBe(401) }) it("should handle 429 Rate Limit with RetryInfo", () => { - const error = new Error("Rate limit exceeded") as any - error.status = 429 - error.errorDetails = [ - { - "@type": "type.googleapis.com/google.rpc.RetryInfo", - retryDelay: "10s", - }, - ] + const error = Object.assign(new Error("Rate limit exceeded"), { + status: 429, + errorDetails: [ + { + "@type": "type.googleapis.com/google.rpc.RetryInfo", + retryDelay: "10s", + }, + ], + }) const result = handleProviderError(error, providerName) - expect((result as any).status).toBe(429) - expect((result as any).errorDetails).toBeDefined() - expect((result as any).errorDetails[0].retryDelay).toBe("10s") + expect(result.status).toBe(429) + expect(result.errorDetails).toBeDefined() + const errorDetails = result.errorDetails as Array<{ retryDelay?: string }> + expect(errorDetails[0].retryDelay).toBe("10s") }) it("should handle 500 Internal Server Error", () => { - const error = new Error("Internal server error") as any - error.status = 500 + const error = Object.assign(new Error("Internal server error"), { status: 500 }) const result = handleProviderError(error, providerName) - expect((result as any).status).toBe(500) + expect(result.status).toBe(500) expect(result.message).toContain("Internal server error") }) @@ -305,30 +305,30 @@ describe("handleProviderError", () => { const result = handleProviderError(error, providerName) expect(result).toBeInstanceOf(Error) - expect((result as any).status).toBeUndefined() + expect(result.status).toBeUndefined() expect(result.message).toContain("Network connectivity issue") }) it("should handle Gemini-specific errors with custom transformer", () => { - const error = new Error("Model not found") as any - error.status = 404 + const error = Object.assign(new Error("Model not found"), { status: 404 }) const result = handleProviderError(error, "Gemini", { messageTransformer: (msg) => `Gemini API Error: ${msg}`, }) expect(result.message).toBe("Gemini API Error: Model not found") - expect((result as any).status).toBe(404) + expect(result.status).toBe(404) }) it("should handle Anthropic SDK errors", () => { - const error = new Error("Invalid API key") as any - error.status = 401 - error.error = { type: "authentication_error" } + const error = Object.assign(new Error("Invalid API key"), { + status: 401, + error: { type: "authentication_error" }, + }) const result = handleProviderError(error, "Anthropic") - expect((result as any).status).toBe(401) + expect(result.status).toBe(401) expect(result.message).toContain("Invalid API key") }) }) @@ -336,24 +336,22 @@ describe("handleProviderError", () => { describe("handleOpenAIError (backward compatibility)", () => { it("should be an alias for handleProviderError with completion prefix", () => { - const error = new Error("API failed") as any - error.status = 500 + const error = Object.assign(new Error("API failed"), { status: 500 }) const result = handleOpenAIError(error, "OpenAI") expect(result).toBeInstanceOf(Error) expect(result.message).toContain("OpenAI completion error") - expect((result as any).status).toBe(500) + expect(result.status).toBe(500) }) it("should preserve backward compatibility for existing callers", () => { - const error = new Error("Authentication failed") as any - error.status = 401 + const error = Object.assign(new Error("Authentication failed"), { status: 401 }) const result = handleOpenAIError(error, "Roo Code Cloud") expect(result.message).toBe("Roo Code Cloud completion error: Authentication failed") - expect((result as any).status).toBe(401) + expect(result.status).toBe(401) }) }) diff --git a/src/api/providers/utils/__tests__/image-generation.spec.ts b/src/api/providers/utils/__tests__/image-generation.spec.ts index 434c2f85b84..8564064707d 100644 --- a/src/api/providers/utils/__tests__/image-generation.spec.ts +++ b/src/api/providers/utils/__tests__/image-generation.spec.ts @@ -3,7 +3,7 @@ import { generateImageWithImagesApi, generateImageWithProvider } from "../image- // Mock the i18n module vi.mock("../../../i18n", () => ({ - t: (key: string, options?: any) => { + t: (key: string, options?: { message?: string }) => { // Return a sensible mock for i18n if (key === "tools:generateImage.failedWithMessage" && options?.message) { return options.message @@ -18,8 +18,8 @@ global.FormData = vi.fn(function () { return { append: vi.fn(), } -}) as any -global.Blob = vi.fn() as any +}) as unknown as { new (form?: HTMLFormElement, submitter?: HTMLElement | null): FormData; prototype: FormData } +global.Blob = vi.fn() as unknown as { new (): Blob; prototype: Blob } global.atob = vi.fn((str: string) => { return Buffer.from(str, "base64").toString("binary") }) @@ -43,7 +43,7 @@ describe("generateImageWithImagesApi", () => { }), } - vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) + vi.mocked(global.fetch).mockResolvedValue(mockResponse as unknown as Response) const result = await generateImageWithImagesApi({ baseURL: "https://api.example.com/v1", @@ -78,7 +78,7 @@ describe("generateImageWithImagesApi", () => { text: vi.fn().mockResolvedValue("{}"), } - vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) + vi.mocked(global.fetch).mockResolvedValue(mockResponse as unknown as Response) const result = await generateImageWithImagesApi({ baseURL: "https://api.example.com/v1", @@ -99,7 +99,7 @@ describe("generateImageWithImagesApi", () => { }), } - vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) + vi.mocked(global.fetch).mockResolvedValue(mockResponse as unknown as Response) const result = await generateImageWithImagesApi({ baseURL: "https://api.example.com/v1", @@ -120,7 +120,7 @@ describe("generateImageWithImagesApi", () => { }), } - vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) + vi.mocked(global.fetch).mockResolvedValue(mockResponse as unknown as Response) const result = await generateImageWithImagesApi({ baseURL: "https://api.example.com/v1", @@ -142,7 +142,7 @@ describe("generateImageWithImagesApi", () => { }), } - vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) + vi.mocked(global.fetch).mockResolvedValue(mockResponse as unknown as Response) const result = await generateImageWithImagesApi({ baseURL: "https://api.example.com/v1", @@ -165,7 +165,7 @@ describe("generateImageWithImagesApi", () => { }), } - vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) + vi.mocked(global.fetch).mockResolvedValue(mockResponse as unknown as Response) const result = await generateImageWithImagesApi({ baseURL: "https://api.example.com/v1", @@ -189,7 +189,7 @@ describe("generateImageWithImagesApi", () => { }), } - vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) + vi.mocked(global.fetch).mockResolvedValue(mockResponse as unknown as Response) const result = await generateImageWithImagesApi({ baseURL: "https://api.example.com/v1", @@ -211,7 +211,7 @@ describe("generateImageWithImagesApi", () => { }), } - vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) + vi.mocked(global.fetch).mockResolvedValue(mockResponse as unknown as Response) const result = await generateImageWithImagesApi({ baseURL: "https://api.example.com/v1", @@ -257,7 +257,7 @@ describe("generateImageWithImagesApi", () => { }), } - vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) + vi.mocked(global.fetch).mockResolvedValue(mockResponse as unknown as Response) const inputImageDataUrl = `data:image/png;base64,${mockBase64}` @@ -285,7 +285,7 @@ describe("generateImageWithImagesApi", () => { text: vi.fn().mockResolvedValue("{}"), } - vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) + vi.mocked(global.fetch).mockResolvedValue(mockResponse as unknown as Response) const inputImageDataUrl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==" @@ -313,7 +313,7 @@ describe("generateImageWithImagesApi", () => { }), } - vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) + vi.mocked(global.fetch).mockResolvedValue(mockResponse as unknown as Response) const result = await generateImageWithImagesApi({ baseURL: "https://api.example.com/v1", @@ -335,7 +335,7 @@ describe("generateImageWithImagesApi", () => { }), } - vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) + vi.mocked(global.fetch).mockResolvedValue(mockResponse as unknown as Response) const result = await generateImageWithImagesApi({ baseURL: "https://api.example.com/v1", @@ -380,7 +380,7 @@ describe("generateImageWithProvider (chat completions)", () => { }), } - vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) + vi.mocked(global.fetch).mockResolvedValue(mockResponse as unknown as Response) const result = await generateImageWithProvider({ baseURL: "https://api.example.com/v1", @@ -404,7 +404,7 @@ describe("generateImageWithProvider (chat completions)", () => { }), } - vi.mocked(global.fetch).mockResolvedValue(mockResponse as any) + vi.mocked(global.fetch).mockResolvedValue(mockResponse as unknown as Response) const result = await generateImageWithProvider({ baseURL: "https://api.example.com/v1", diff --git a/src/api/providers/utils/error-handler.ts b/src/api/providers/utils/error-handler.ts index 2247ed182c4..29b659f4380 100644 --- a/src/api/providers/utils/error-handler.ts +++ b/src/api/providers/utils/error-handler.ts @@ -11,6 +11,28 @@ import i18n from "../../../i18n/setup" +/** + * Error with the provider metadata handleProviderError preserves for retry + * logic and UI display (status, errorDetails, code, $metadata). + */ +export type ProviderError = Error & { + status?: number + statusCode?: number + errorDetails?: unknown + code?: unknown + $metadata?: unknown +} + +/** Shape handleProviderError reads off unknown thrown values. */ +type UnknownErrorShape = Error & { + status?: unknown + statusCode?: unknown + errorDetails?: unknown + code?: unknown + $metadata?: unknown + error?: { metadata?: { raw?: string } } +} + /** * Handles API provider errors and transforms them into user-friendly messages * while preserving important metadata for retry logic and UI display. @@ -78,11 +100,11 @@ export function handleProviderError( /** Custom message transformer */ messageTransformer?: (msg: string) => string }, -): Error { +): ProviderError { const messagePrefix = options?.messagePrefix || "completion" if (error instanceof Error) { - const anyErr = error as any + const anyErr = error as UnknownErrorShape const msg = anyErr?.error?.metadata?.raw || error.message || "" // Log the original error details for debugging @@ -94,18 +116,18 @@ export function handleProviderError( statusCode: anyErr.statusCode, }) - let wrapped: Error + let wrapped: ProviderError // Special case: Invalid character/ByteString conversion error in API key // This is specific to OpenAI-compatible SDKs if (msg.includes("Cannot convert argument to a ByteString")) { - wrapped = new Error(i18n.t("common:errors.api.invalidKeyInvalidChars")) + wrapped = new Error(i18n.t("common:errors.api.invalidKeyInvalidChars")) as ProviderError } else { // Apply custom transformer if provided, otherwise use default format const finalMessage = options?.messageTransformer ? options.messageTransformer(msg) : `${providerName} ${messagePrefix} error: ${msg}` - wrapped = new Error(finalMessage) + wrapped = new Error(finalMessage) as ProviderError } // Preserve HTTP status and structured details for retry/backoff + UI @@ -120,17 +142,17 @@ export function handleProviderError( const numericStatusCode = typeof anyErr.statusCode === "number" ? anyErr.statusCode : undefined const preservedStatus = numericStatus !== undefined ? numericStatus : numericStatusCode if (preservedStatus !== undefined) { - ;(wrapped as any).status = preservedStatus + wrapped.status = preservedStatus } if (anyErr.errorDetails !== undefined) { - ;(wrapped as any).errorDetails = anyErr.errorDetails + wrapped.errorDetails = anyErr.errorDetails } if (anyErr.code !== undefined) { - ;(wrapped as any).code = anyErr.code + wrapped.code = anyErr.code } // Preserve AWS-specific metadata if present (for Bedrock) if (anyErr.$metadata !== undefined) { - ;(wrapped as any).$metadata = anyErr.$metadata + wrapped.$metadata = anyErr.$metadata } return wrapped @@ -138,11 +160,11 @@ export function handleProviderError( // Non-Error: wrap with provider-specific prefix console.error(`[${providerName}] Non-Error exception:`, error) - const wrapped = new Error(`${providerName} ${messagePrefix} error: ${String(error)}`) + const wrapped = new Error(`${providerName} ${messagePrefix} error: ${String(error)}`) as ProviderError // Also try to preserve status for non-Error exceptions (e.g., plain objects with // status or statusCode, matching the AI SDK APICallError shape) - const anyErr = error as any + const anyErr = error as Pick const plainStatus = typeof anyErr?.status === "number" ? anyErr.status @@ -150,7 +172,7 @@ export function handleProviderError( ? anyErr.statusCode : undefined if (plainStatus !== undefined) { - ;(wrapped as any).status = plainStatus + wrapped.status = plainStatus } return wrapped @@ -160,6 +182,6 @@ export function handleProviderError( * Specialized handler for OpenAI-compatible providers * Re-exports with OpenAI-specific defaults for backward compatibility */ -export function handleOpenAIError(error: unknown, providerName: string): Error { +export function handleOpenAIError(error: unknown, providerName: string) { return handleProviderError(error, providerName, { messagePrefix: "completion" }) } diff --git a/src/api/transform/__tests__/openai-format.spec.ts b/src/api/transform/__tests__/openai-format.spec.ts index 8a473e6cbc6..cd474881275 100644 --- a/src/api/transform/__tests__/openai-format.spec.ts +++ b/src/api/transform/__tests__/openai-format.spec.ts @@ -12,6 +12,20 @@ import { import { normalizeMistralToolCallId } from "../mistral-format" import { expectNoLoneSurrogates } from "../../../test-utils/surrogates" +/** Anthropic history message with the extension's reasoning passthrough fields. */ +interface AnthropicMessageWithReasoning extends Anthropic.Messages.MessageParam { + reasoning_details?: ReasoningDetail[] + reasoning_content?: string +} + +/** Assistant message carrying the reasoning passthrough fields convertToOpenAiMessages attaches. */ +interface AssistantMessageWithReasoning extends OpenAI.Chat.ChatCompletionAssistantMessageParam { + reasoning_details?: ReasoningDetail[] + reasoning_content?: string + /** Legacy top-level reasoning field the converter no longer emits. */ + reasoning?: unknown +} + describe("convertToOpenAiMessages", () => { it("should convert simple text messages", () => { const anthropicMessages: Anthropic.Messages.MessageParam[] = [ @@ -85,7 +99,7 @@ describe("convertToOpenAiMessages", () => { { type: "text", text: "What is in this image?" }, { type: "image", - source: { type: "url", url: "https://example.com/image.png" } as any, + source: { type: "url", url: "https://example.com/image.png" }, }, ], }, @@ -107,7 +121,8 @@ describe("convertToOpenAiMessages", () => { content: [ { type: "image", - source: { type: "file" } as any, + // Partial source double for the non-base64 branch; routed through unknown. + source: { type: "file" } as unknown as Anthropic.Messages.ImageBlockParam["source"], }, ], }, @@ -129,10 +144,12 @@ describe("convertToOpenAiMessages", () => { tool_use_id: "tool-1", content: [ { type: "text", text: "some text" }, + // Document blocks inside tool_result content are routed through unknown + // because the SDK content union only lists text and image parts. { type: "document", source: { type: "base64", media_type: "application/pdf", data: "abc" }, - } as any, + } as unknown as Anthropic.TextBlockParam, ], }, ], @@ -141,7 +158,7 @@ describe("convertToOpenAiMessages", () => { const openAiMessages = convertToOpenAiMessages(anthropicMessages) expect(openAiMessages[0].role).toBe("tool") - expect((openAiMessages[0] as any).content).toBe("some text\n") + expect(openAiMessages[0].content).toBe("some text\n") }) it("should handle base64 image in tool result with placeholder", () => { @@ -167,7 +184,7 @@ describe("convertToOpenAiMessages", () => { expect(openAiMessages[0].role).toBe("tool") // base64 images in tool results emit a placeholder; the image itself is // flushed in a separate user message (see comment block in openai-format.ts) - expect((openAiMessages[0] as any).content).toBe("(see following user message for image)") + expect(openAiMessages[0].content).toBe("(see following user message for image)") }) it("should render [Image] placeholder for URL image in tool result", () => { @@ -181,7 +198,7 @@ describe("convertToOpenAiMessages", () => { content: [ { type: "image", - source: { type: "url", url: "https://example.com/img.png" } as any, + source: { type: "url", url: "https://example.com/img.png" }, }, ], }, @@ -191,7 +208,7 @@ describe("convertToOpenAiMessages", () => { const openAiMessages = convertToOpenAiMessages(anthropicMessages) expect(openAiMessages[0].role).toBe("tool") - expect((openAiMessages[0] as any).content).toBe("[Image]") + expect(openAiMessages[0].content).toBe("[Image]") }) it("should handle assistant messages with tool use (no normalization without normalizeToolCallId)", () => { @@ -219,7 +236,7 @@ describe("convertToOpenAiMessages", () => { const assistantMessage = openAiMessages[0] as OpenAI.Chat.ChatCompletionAssistantMessageParam expect(assistantMessage.role).toBe("assistant") expect(assistantMessage.content).toBe("Let me check the weather.") - expect(assistantMessage.tool_calls).toHaveLength(1) + expect(assistantMessage.tool_calls!).toHaveLength(1) expect(assistantMessage.tool_calls![0]).toEqual({ id: "weather-123", // Not normalized without normalizeToolCallId function type: "function", @@ -374,7 +391,7 @@ describe("convertToOpenAiMessages", () => { expect(assistantMessage.role).toBe("assistant") // Content should be an empty string, NOT undefined expect(assistantMessage.content).toBe("") - expect(assistantMessage.tool_calls).toHaveLength(1) + expect(assistantMessage.tool_calls!).toHaveLength(1) expect(assistantMessage.tool_calls![0].id).toBe("tool-123") }) @@ -741,22 +758,22 @@ describe("convertToOpenAiMessages", () => { }, ], }, - ] as any + ] const openAiMessages = convertToOpenAiMessages(anthropicMessages) expect(openAiMessages).toHaveLength(1) - const assistantMessage = openAiMessages[0] as any + const assistantMessage = openAiMessages[0] as AssistantMessageWithReasoning expect(assistantMessage.role).toBe("assistant") expect(assistantMessage.content).toBe("Why don't scientists trust atoms? Because they make up everything!") - expect(assistantMessage.reasoning_details).toHaveLength(2) - expect(assistantMessage.reasoning_details[0].type).toBe("reasoning.summary") - expect(assistantMessage.reasoning_details[1].type).toBe("reasoning.encrypted") - expect(assistantMessage.reasoning_details[1].id).toBe("rs_abc") + expect(assistantMessage.reasoning_details!).toHaveLength(2) + expect(assistantMessage.reasoning_details![0].type).toBe("reasoning.summary") + expect(assistantMessage.reasoning_details![1].type).toBe("reasoning.encrypted") + expect(assistantMessage.reasoning_details![1].id).toBe("rs_abc") }) it("should strip id from openai-responses-v1 blocks even when assistant content is a string", () => { - const anthropicMessages = [ + const anthropicMessages: AnthropicMessageWithReasoning[] = [ { role: "assistant" as const, content: "Ok.", @@ -771,21 +788,21 @@ describe("convertToOpenAiMessages", () => { }, ], }, - ] as any + ] const openAiMessages = convertToOpenAiMessages(anthropicMessages) expect(openAiMessages).toHaveLength(1) - const assistantMessage = openAiMessages[0] as any - expect(assistantMessage.reasoning_details).toHaveLength(1) - expect(assistantMessage.reasoning_details[0].format).toBe("openai-responses-v1") - expect(assistantMessage.reasoning_details[0].id).toBeUndefined() + const assistantMessage = openAiMessages[0] as AssistantMessageWithReasoning + expect(assistantMessage.reasoning_details!).toHaveLength(1) + expect(assistantMessage.reasoning_details![0].format).toBe("openai-responses-v1") + expect(assistantMessage.reasoning_details![0].id).toBeUndefined() }) it("should pass through all reasoning_details without extracting to top-level reasoning", () => { // This simulates the stored format after receiving from xAI/Roo API // The provider (roo.ts) now consolidates all reasoning into reasoning_details - const anthropicMessages = [ + const anthropicMessages: AnthropicMessageWithReasoning[] = [ { role: "assistant" as const, content: [{ type: "text" as const, text: "I'll help you with that." }], @@ -805,26 +822,26 @@ describe("convertToOpenAiMessages", () => { }, ], }, - ] as any + ] const openAiMessages = convertToOpenAiMessages(anthropicMessages) expect(openAiMessages).toHaveLength(1) - const assistantMessage = openAiMessages[0] as any + const assistantMessage = openAiMessages[0] as AssistantMessageWithReasoning expect(assistantMessage.role).toBe("assistant") // Should NOT have top-level reasoning field - we only use reasoning_details now expect(assistantMessage.reasoning).toBeUndefined() // Should pass through all reasoning_details preserving all fields - expect(assistantMessage.reasoning_details).toHaveLength(2) - expect(assistantMessage.reasoning_details[0].type).toBe("reasoning.summary") - expect(assistantMessage.reasoning_details[0].summary).toBe( + expect(assistantMessage.reasoning_details!).toHaveLength(2) + expect(assistantMessage.reasoning_details![0].type).toBe("reasoning.summary") + expect(assistantMessage.reasoning_details![0].summary).toBe( '\n\n## Reviewing task progress', ) - expect(assistantMessage.reasoning_details[1].type).toBe("reasoning.encrypted") - expect(assistantMessage.reasoning_details[1].id).toBe("rs_ce73018c-40cc-49b1-c589-902c53f4a16a") - expect(assistantMessage.reasoning_details[1].data).toBe( + expect(assistantMessage.reasoning_details![1].type).toBe("reasoning.encrypted") + expect(assistantMessage.reasoning_details![1].id).toBe("rs_ce73018c-40cc-49b1-c589-902c53f4a16a") + expect(assistantMessage.reasoning_details![1].data).toBe( "PParvy65fOb8AhUd9an7yZ3wBF2KCQPL3zhjPNve8parmyG/Xw2K7HZn...", ) }) @@ -834,7 +851,7 @@ describe("convertToOpenAiMessages", () => { // reasoning blocks with format "openai-responses-v1" because we don't use // `store: true` (we handle conversation state client-side). The error message is: // "'{id}' not found. Items are not persisted when `store` is set to false." - const anthropicMessages = [ + const anthropicMessages: AnthropicMessageWithReasoning[] = [ { role: "assistant" as const, content: [ @@ -858,37 +875,39 @@ describe("convertToOpenAiMessages", () => { }, ], }, - ] as any + ] const openAiMessages = convertToOpenAiMessages(anthropicMessages) expect(openAiMessages).toHaveLength(1) - const assistantMessage = openAiMessages[0] as any + const assistantMessage = openAiMessages[0] as AssistantMessageWithReasoning // Should NOT have top-level reasoning field - we only use reasoning_details now expect(assistantMessage.reasoning).toBeUndefined() // Should pass through reasoning_details preserving most fields BUT stripping id - expect(assistantMessage.reasoning_details).toHaveLength(1) - expect(assistantMessage.reasoning_details[0].type).toBe("reasoning.summary") + expect(assistantMessage.reasoning_details!).toHaveLength(1) + expect(assistantMessage.reasoning_details![0].type).toBe("reasoning.summary") // id should be STRIPPED for openai-responses-v1 format to avoid 404 errors - expect(assistantMessage.reasoning_details[0].id).toBeUndefined() - expect(assistantMessage.reasoning_details[0].summary).toBe( + expect(assistantMessage.reasoning_details![0].id).toBeUndefined() + expect(assistantMessage.reasoning_details![0].summary).toBe( "It looks like I need to make sure I'm using the tool every time.", ) - expect(assistantMessage.reasoning_details[0].data).toBe( + expect(assistantMessage.reasoning_details![0].data).toBe( "gAAAAABpStjXioDMX8RUobc7k-eKqax9WrI97bok93IkBI6X6eBY...", ) - expect(assistantMessage.reasoning_details[0].format).toBe("openai-responses-v1") + expect(assistantMessage.reasoning_details![0].format).toBe("openai-responses-v1") // Should have tool_calls - expect(assistantMessage.tool_calls).toHaveLength(1) - expect(assistantMessage.tool_calls[0].id).toBe("call_Tb4KVEmEpEAA8W1QcxjyD5Nh") + expect(assistantMessage.tool_calls!).toHaveLength(1) + expect((assistantMessage.tool_calls![0] as OpenAI.Chat.ChatCompletionMessageFunctionToolCall).id).toBe( + "call_Tb4KVEmEpEAA8W1QcxjyD5Nh", + ) }) it("should preserve id for non-openai-responses-v1 formats (e.g., xai-responses-v1)", () => { // For other formats like xai-responses-v1, we should preserve the id - const anthropicMessages = [ + const anthropicMessages: AnthropicMessageWithReasoning[] = [ { role: "assistant" as const, content: [{ type: "text" as const, text: "Response" }], @@ -902,22 +921,22 @@ describe("convertToOpenAiMessages", () => { }, ], }, - ] as any + ] const openAiMessages = convertToOpenAiMessages(anthropicMessages) expect(openAiMessages).toHaveLength(1) - const assistantMessage = openAiMessages[0] as any + const assistantMessage = openAiMessages[0] as AssistantMessageWithReasoning // Should preserve id for xai-responses-v1 format - expect(assistantMessage.reasoning_details).toHaveLength(1) - expect(assistantMessage.reasoning_details[0].id).toBe("rs_ce73018c-40cc-49b1-c589-902c53f4a16a") - expect(assistantMessage.reasoning_details[0].format).toBe("xai-responses-v1") + expect(assistantMessage.reasoning_details!).toHaveLength(1) + expect(assistantMessage.reasoning_details![0].id).toBe("rs_ce73018c-40cc-49b1-c589-902c53f4a16a") + expect(assistantMessage.reasoning_details![0].format).toBe("xai-responses-v1") }) it("should handle assistant messages with tool_calls and reasoning_details", () => { // This simulates a message with both tool calls and reasoning - const anthropicMessages = [ + const anthropicMessages: AnthropicMessageWithReasoning[] = [ { role: "assistant" as const, content: [ @@ -944,27 +963,31 @@ describe("convertToOpenAiMessages", () => { }, ], }, - ] as any + ] const openAiMessages = convertToOpenAiMessages(anthropicMessages) expect(openAiMessages).toHaveLength(1) - const assistantMessage = openAiMessages[0] as any + const assistantMessage = openAiMessages[0] as AssistantMessageWithReasoning // Should NOT have top-level reasoning field expect(assistantMessage.reasoning).toBeUndefined() // Should pass through all reasoning_details - expect(assistantMessage.reasoning_details).toHaveLength(2) + expect(assistantMessage.reasoning_details!).toHaveLength(2) // Should have tool_calls - expect(assistantMessage.tool_calls).toHaveLength(1) - expect(assistantMessage.tool_calls[0].id).toBe("call_62462410") - expect(assistantMessage.tool_calls[0].function.name).toBe("read_file") + expect(assistantMessage.tool_calls!).toHaveLength(1) + expect((assistantMessage.tool_calls![0] as OpenAI.Chat.ChatCompletionMessageFunctionToolCall).id).toBe( + "call_62462410", + ) + expect( + (assistantMessage.tool_calls![0] as OpenAI.Chat.ChatCompletionMessageFunctionToolCall).function.name, + ).toBe("read_file") }) it("should pass through reasoning_details with only encrypted blocks", () => { - const anthropicMessages = [ + const anthropicMessages: AnthropicMessageWithReasoning[] = [ { role: "assistant" as const, content: [{ type: "text" as const, text: "Response text" }], @@ -978,23 +1001,23 @@ describe("convertToOpenAiMessages", () => { }, ], }, - ] as any + ] const openAiMessages = convertToOpenAiMessages(anthropicMessages) expect(openAiMessages).toHaveLength(1) - const assistantMessage = openAiMessages[0] as any + const assistantMessage = openAiMessages[0] as AssistantMessageWithReasoning // Should NOT have reasoning field expect(assistantMessage.reasoning).toBeUndefined() // Should still pass through reasoning_details - expect(assistantMessage.reasoning_details).toHaveLength(1) - expect(assistantMessage.reasoning_details[0].type).toBe("reasoning.encrypted") + expect(assistantMessage.reasoning_details!).toHaveLength(1) + expect(assistantMessage.reasoning_details![0].type).toBe("reasoning.encrypted") }) it("should pass through reasoning_details even when only summary blocks exist (no encrypted)", () => { - const anthropicMessages = [ + const anthropicMessages: AnthropicMessageWithReasoning[] = [ { role: "assistant" as const, content: [{ type: "text" as const, text: "Response text" }], @@ -1007,20 +1030,20 @@ describe("convertToOpenAiMessages", () => { }, ], }, - ] as any + ] const openAiMessages = convertToOpenAiMessages(anthropicMessages) expect(openAiMessages).toHaveLength(1) - const assistantMessage = openAiMessages[0] as any + const assistantMessage = openAiMessages[0] as AssistantMessageWithReasoning // Should NOT have top-level reasoning field expect(assistantMessage.reasoning).toBeUndefined() // Should pass through reasoning_details preserving the summary block - expect(assistantMessage.reasoning_details).toHaveLength(1) - expect(assistantMessage.reasoning_details[0].type).toBe("reasoning.summary") - expect(assistantMessage.reasoning_details[0].summary).toBe("Just a summary, no encrypted content") + expect(assistantMessage.reasoning_details!).toHaveLength(1) + expect(assistantMessage.reasoning_details![0].type).toBe("reasoning.summary") + expect(assistantMessage.reasoning_details![0].summary).toBe("Just a summary, no encrypted content") }) it("should handle messages without reasoning_details", () => { @@ -1034,7 +1057,7 @@ describe("convertToOpenAiMessages", () => { const openAiMessages = convertToOpenAiMessages(anthropicMessages) expect(openAiMessages).toHaveLength(1) - const assistantMessage = openAiMessages[0] as any + const assistantMessage = openAiMessages[0] as AssistantMessageWithReasoning // Should not have reasoning or reasoning_details expect(assistantMessage.reasoning).toBeUndefined() @@ -1042,7 +1065,7 @@ describe("convertToOpenAiMessages", () => { }) it("should pass through multiple reasoning_details blocks preserving all fields", () => { - const anthropicMessages = [ + const anthropicMessages: AnthropicMessageWithReasoning[] = [ { role: "assistant" as const, content: [{ type: "text" as const, text: "Response" }], @@ -1068,38 +1091,40 @@ describe("convertToOpenAiMessages", () => { }, ], }, - ] as any + ] const openAiMessages = convertToOpenAiMessages(anthropicMessages) expect(openAiMessages).toHaveLength(1) - const assistantMessage = openAiMessages[0] as any + const assistantMessage = openAiMessages[0] as AssistantMessageWithReasoning // Should NOT have top-level reasoning field expect(assistantMessage.reasoning).toBeUndefined() // Should pass through all reasoning_details - expect(assistantMessage.reasoning_details).toHaveLength(3) - expect(assistantMessage.reasoning_details[0].summary).toBe("First part of thinking. ") - expect(assistantMessage.reasoning_details[1].summary).toBe("Second part of thinking.") - expect(assistantMessage.reasoning_details[2].data).toBe("encrypted_data") + expect(assistantMessage.reasoning_details!).toHaveLength(3) + expect(assistantMessage.reasoning_details![0].summary).toBe("First part of thinking. ") + expect(assistantMessage.reasoning_details![1].summary).toBe("Second part of thinking.") + expect(assistantMessage.reasoning_details![2].data).toBe("encrypted_data") }) }) describe("reasoning_content round-trip for DeepSeek / Z.ai thinking mode", () => { it("should pass through top-level reasoning_content on assistant messages", () => { - const anthropicMessages = [ + const anthropicMessages: AnthropicMessageWithReasoning[] = [ { role: "assistant" as const, content: "Here is my answer.", reasoning_content: "Let me think about this carefully...", }, - ] as any as Anthropic.Messages.MessageParam[] + ] const result = convertToOpenAiMessages(anthropicMessages) expect(result).toHaveLength(1) - expect((result[0] as any).reasoning_content).toBe("Let me think about this carefully...") + expect((result[0] as AssistantMessageWithReasoning).reasoning_content).toBe( + "Let me think about this carefully...", + ) }) it("should extract reasoning_content from reasoning content block", () => { @@ -1112,12 +1137,11 @@ describe("convertToOpenAiMessages", () => { { type: "text", text: "My answer." }, ], }, - ] as any as Anthropic.Messages.MessageParam[] - + ] as unknown as Anthropic.Messages.MessageParam[] const result = convertToOpenAiMessages(anthropicMessages) expect(result).toHaveLength(1) - const msg = result[0] as any + const msg = result[0] as AssistantMessageWithReasoning expect(msg.reasoning_content).toBe("Let me think...") expect(msg.content).toBe("My answer.") }) @@ -1139,15 +1163,14 @@ describe("convertToOpenAiMessages", () => { }, ], }, - ] as any as Anthropic.Messages.MessageParam[] - + ] as unknown as Anthropic.Messages.MessageParam[] const result = convertToOpenAiMessages(anthropicMessages) expect(result).toHaveLength(1) - const msg = result[0] as any + const msg = result[0] as AssistantMessageWithReasoning expect(msg.reasoning_content).toBe("I need to read a file.") - expect(msg.tool_calls).toHaveLength(1) - expect(msg.tool_calls[0].id).toBe("call_abc") + expect(msg.tool_calls!).toHaveLength(1) + expect((msg.tool_calls![0] as OpenAI.Chat.ChatCompletionMessageFunctionToolCall).id).toBe("call_abc") }) it("should accumulate multiple reasoning blocks in order, separated by a tool call", () => { @@ -1168,15 +1191,14 @@ describe("convertToOpenAiMessages", () => { { type: "reasoning", text: "Now I know what to do next.", summary: [] }, ], }, - ] as any as Anthropic.Messages.MessageParam[] - + ] as unknown as Anthropic.Messages.MessageParam[] const result = convertToOpenAiMessages(anthropicMessages) expect(result).toHaveLength(1) - const msg = result[0] as any + const msg = result[0] as AssistantMessageWithReasoning expect(msg.reasoning_content).toBe("First, I should check the file.Now I know what to do next.") - expect(msg.tool_calls).toHaveLength(1) - expect(msg.tool_calls[0].id).toBe("call_abc") + expect(msg.tool_calls!).toHaveLength(1) + expect((msg.tool_calls![0] as OpenAI.Chat.ChatCompletionMessageFunctionToolCall).id).toBe("call_abc") }) it("should prefer top-level reasoning_content over content block", () => { @@ -1189,11 +1211,10 @@ describe("convertToOpenAiMessages", () => { ], reasoning_content: "top-level reasoning", }, - ] as any as Anthropic.Messages.MessageParam[] - + ] as unknown as Anthropic.Messages.MessageParam[] const result = convertToOpenAiMessages(anthropicMessages) - expect((result[0] as any).reasoning_content).toBe("top-level reasoning") + expect((result[0] as AssistantMessageWithReasoning).reasoning_content).toBe("top-level reasoning") }) it("should not set reasoning_content when there is none", () => { @@ -1214,24 +1235,25 @@ describe("convertToOpenAiMessages", () => { const result = convertToOpenAiMessages(anthropicMessages) expect(result).toHaveLength(1) - expect((result[0] as any).reasoning_content).toBeUndefined() + expect((result[0] as AssistantMessageWithReasoning).reasoning_content).toBeUndefined() }) it("should ignore non-object content parts without crashing (defensive guard)", () => { // getReasoningBlockText guards against non-object parts (e.g. a stray // string in the content array). Such parts are not reasoning blocks and // must be skipped rather than crashing or being misread as reasoning. - const anthropicMessages = [ + const anthropicMessages: AnthropicMessageWithReasoning[] = [ { role: "assistant" as const, - content: ["not-a-block" as any, { type: "text", text: "answer" }], + // Malformed string part (not a block) routed through unknown on purpose. + content: ["not-a-block" as unknown as Anthropic.TextBlockParam, { type: "text", text: "answer" }], }, - ] as any as Anthropic.Messages.MessageParam[] + ] const result = convertToOpenAiMessages(anthropicMessages) expect(result).toHaveLength(1) - const msg = result[0] as any + const msg = result[0] as AssistantMessageWithReasoning expect(msg.content).toBe("answer") expect(msg.reasoning_content).toBeUndefined() }) @@ -1244,7 +1266,7 @@ describe("consolidateReasoningDetails", () => { }) it("should return empty array for undefined input", () => { - expect(consolidateReasoningDetails(undefined as any)).toEqual([]) + expect(consolidateReasoningDetails(undefined)).toEqual([]) }) it("should filter out corrupted encrypted blocks (missing data field)", () => { @@ -1264,7 +1286,6 @@ describe("consolidateReasoningDetails", () => { index: 0, }, ] - const result = consolidateReasoningDetails(details) // Should only have the text block, not the corrupted encrypted block @@ -1409,7 +1430,7 @@ describe("sanitizeGeminiMessages", () => { }) it("should drop tool calls without reasoning_details for Gemini models", () => { - const messages = [ + const messages: (AssistantMessageWithReasoning | OpenAI.Chat.ChatCompletionMessageParam)[] = [ { role: "system", content: "You are helpful" }, { role: "assistant", @@ -1433,11 +1454,11 @@ describe("sanitizeGeminiMessages", () => { expect(result).toHaveLength(2) expect(result[0].role).toBe("system") expect(result[1].role).toBe("assistant") - expect((result[1] as any).tool_calls).toBeUndefined() + expect((result[1] as AssistantMessageWithReasoning).tool_calls).toBeUndefined() }) it("should filter reasoning_details to only include entries matching tool call IDs", () => { - const messages = [ + const messages: (AssistantMessageWithReasoning | OpenAI.Chat.ChatCompletionMessageParam)[] = [ { role: "assistant", content: "", @@ -1465,19 +1486,19 @@ describe("sanitizeGeminiMessages", () => { }, ], }, - ] as any + ] const result = sanitizeGeminiMessages(messages, "google/gemini-3-flash-preview") expect(result).toHaveLength(1) - const assistantMsg = result[0] as any - expect(assistantMsg.tool_calls).toHaveLength(1) - expect(assistantMsg.reasoning_details).toHaveLength(1) - expect(assistantMsg.reasoning_details[0].id).toBe("call_abc") + const assistantMsg = result[0] as AssistantMessageWithReasoning + expect(assistantMsg.tool_calls!).toHaveLength(1) + expect(assistantMsg.reasoning_details!).toHaveLength(1) + expect(assistantMsg.reasoning_details![0].id).toBe("call_abc") }) it("should drop tool calls without matching reasoning_details", () => { - const messages = [ + const messages: (AssistantMessageWithReasoning | OpenAI.Chat.ChatCompletionMessageParam)[] = [ { role: "assistant", content: "Some text", @@ -1505,24 +1526,24 @@ describe("sanitizeGeminiMessages", () => { }, { role: "tool", tool_call_id: "call_abc", content: "result a" }, { role: "tool", tool_call_id: "call_def", content: "result b" }, - ] as any + ] const result = sanitizeGeminiMessages(messages, "google/gemini-3-flash-preview") // Should have: assistant with 1 tool_call, 1 tool message expect(result).toHaveLength(2) - const assistantMsg = result[0] as any - expect(assistantMsg.tool_calls).toHaveLength(1) - expect(assistantMsg.tool_calls[0].id).toBe("call_abc") + const assistantMsg = result[0] as AssistantMessageWithReasoning + expect(assistantMsg.tool_calls!).toHaveLength(1) + expect((assistantMsg.tool_calls![0] as OpenAI.Chat.ChatCompletionMessageFunctionToolCall).id).toBe("call_abc") // Only the tool result for call_abc should remain expect(result[1].role).toBe("tool") - expect((result[1] as any).tool_call_id).toBe("call_abc") + expect((result[1] as OpenAI.Chat.ChatCompletionToolMessageParam).tool_call_id).toBe("call_abc") }) it("should include reasoning_details without id (legacy format)", () => { - const messages = [ + const messages: (AssistantMessageWithReasoning | OpenAI.Chat.ChatCompletionMessageParam)[] = [ { role: "assistant", content: "", @@ -1550,18 +1571,18 @@ describe("sanitizeGeminiMessages", () => { }, ], }, - ] as any + ] const result = sanitizeGeminiMessages(messages, "google/gemini-3-flash-preview") expect(result).toHaveLength(1) - const assistantMsg = result[0] as any + const assistantMsg = result[0] as AssistantMessageWithReasoning // Both details should be included (one by matching id, one by having no id) - expect(assistantMsg.reasoning_details.length).toBeGreaterThanOrEqual(1) + expect(assistantMsg.reasoning_details!.length).toBeGreaterThanOrEqual(1) }) it("should preserve messages without tool_calls", () => { - const messages = [ + const messages: (AssistantMessageWithReasoning | OpenAI.Chat.ChatCompletionMessageParam)[] = [ { role: "system", content: "You are helpful" }, { role: "user", content: "Hello" }, { role: "assistant", content: "Hi there!" }, @@ -1701,7 +1722,7 @@ describe("convertToOpenAiMessages lone surrogate sanitization (#461)", () => { // The "reasoning" block is a DeepSeek / Z.ai shape outside Anthropic's // ContentBlockParam union, so the array needs one explicit widening. Double // assertion (not `any`) keeps this file's lint suppression count unchanged. - const anthropicMessages = [ + const anthropicMessages: AnthropicMessageWithReasoning[] = [ { role: "assistant" as const, content: [ diff --git a/src/api/transform/cache-strategy/__tests__/cache-strategy.spec.ts b/src/api/transform/cache-strategy/__tests__/cache-strategy.spec.ts index 14c34913cbc..a368a32feaa 100644 --- a/src/api/transform/cache-strategy/__tests__/cache-strategy.spec.ts +++ b/src/api/transform/cache-strategy/__tests__/cache-strategy.spec.ts @@ -1,8 +1,9 @@ +import type { Mock } from "vitest" import { ContentBlock, SystemContentBlock, BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime" import { Anthropic } from "@anthropic-ai/sdk" import { MultiPointStrategy } from "../multi-point-strategy" -import { CacheStrategyConfig, ModelInfo, CachePointPlacement } from "../types" +import { CacheStrategyConfig, ModelInfo, CachePointPlacement, CacheResult } from "../types" import { AwsBedrockHandler } from "../../../providers/bedrock" // Common test utilities @@ -43,15 +44,15 @@ const hasCachePoint = (block: ContentBlock | SystemContentBlock): boolean => { // Create a mock object to store the last config passed to convertToBedrockConverseMessages interface CacheConfig { - modelInfo: any + modelInfo?: CacheStrategyConfig["modelInfo"] systemPrompt?: string - messages: any[] + messages: Anthropic.Messages.MessageParam[] usePromptCache: boolean } const convertToBedrockConverseMessagesMock = { lastConfig: null as CacheConfig | null, - result: null as any, + result: null as CacheResult | null, } describe("Cache Strategy", () => { @@ -326,11 +327,14 @@ describe("Cache Strategy", () => { } as unknown as BedrockRuntimeClient // Mock the convertToBedrockConverseMessages method to capture the config - vitest.spyOn(handler as any, "convertToBedrockConverseMessages").mockImplementation((...args: any[]) => { - const messages = args[0] - const systemMessage = args[1] - const usePromptCache = args[2] - const modelInfo = args[3] + const convertSpy = vitest.spyOn(handler, "convertToBedrockConverseMessages" as never) as unknown as Mock + convertSpy.mockImplementation((...args: unknown[]) => { + const [messages, systemMessage, usePromptCache, modelInfo] = args as [ + CacheConfig["messages"], + string | undefined, + boolean, + CacheStrategyConfig["modelInfo"], + ] // Store the config for later inspection const config: CacheConfig = { @@ -343,7 +347,7 @@ describe("Cache Strategy", () => { // Create a strategy based on the config // Use MultiPointStrategy for all cases - const strategy = new MultiPointStrategy(config as any) + const strategy = new MultiPointStrategy(config as unknown as CacheStrategyConfig) // Store the result const result = strategy.determineOptimalCachePoints() @@ -375,7 +379,9 @@ describe("Cache Strategy", () => { // Verify that the config would result in a MultiPointStrategy expect(convertToBedrockConverseMessagesMock.lastConfig).not.toBeNull() if (convertToBedrockConverseMessagesMock.lastConfig) { - const strategy = new MultiPointStrategy(convertToBedrockConverseMessagesMock.lastConfig as any) + const strategy = new MultiPointStrategy( + convertToBedrockConverseMessagesMock.lastConfig as unknown as CacheStrategyConfig, + ) expect(strategy).toBeInstanceOf(MultiPointStrategy) } }) @@ -416,7 +422,9 @@ describe("Cache Strategy", () => { // Verify that the config would result in a MultiPointStrategy expect(convertToBedrockConverseMessagesMock.lastConfig).not.toBeNull() if (convertToBedrockConverseMessagesMock.lastConfig) { - const strategy = new MultiPointStrategy(convertToBedrockConverseMessagesMock.lastConfig as any) + const strategy = new MultiPointStrategy( + convertToBedrockConverseMessagesMock.lastConfig as unknown as CacheStrategyConfig, + ) expect(strategy).toBeInstanceOf(MultiPointStrategy) } }) @@ -467,11 +475,14 @@ describe("Cache Strategy", () => { } as unknown as BedrockRuntimeClient // Mock the convertToBedrockConverseMessages method again for the new handler - vitest.spyOn(handler as any, "convertToBedrockConverseMessages").mockImplementation((...args: any[]) => { - const messages = args[0] - const systemMessage = args[1] - const usePromptCache = args[2] - const modelInfo = args[3] + const convertSpy = vitest.spyOn(handler, "convertToBedrockConverseMessages" as never) as unknown as Mock + convertSpy.mockImplementation((...args: unknown[]) => { + const [messages, systemMessage, usePromptCache, modelInfo] = args as [ + CacheConfig["messages"], + string | undefined, + boolean, + CacheConfig["modelInfo"], + ] // Store the config for later inspection const config: CacheConfig = { @@ -484,7 +495,7 @@ describe("Cache Strategy", () => { // Create a strategy based on the config // Use MultiPointStrategy for all cases - const strategy = new MultiPointStrategy(config as any) + const strategy = new MultiPointStrategy(config as unknown as CacheStrategyConfig) // Store the result const result = strategy.determineOptimalCachePoints() @@ -510,18 +521,32 @@ describe("Cache Strategy", () => { // Verify that the config would result in a MultiPointStrategy expect(convertToBedrockConverseMessagesMock.lastConfig).not.toBeNull() if (convertToBedrockConverseMessagesMock.lastConfig) { - const strategy = new MultiPointStrategy(convertToBedrockConverseMessagesMock.lastConfig as any) + const strategy = new MultiPointStrategy( + convertToBedrockConverseMessagesMock.lastConfig as unknown as CacheStrategyConfig, + ) expect(strategy).toBeInstanceOf(MultiPointStrategy) } }) it("should include cachePoint nodes in API request when using MultiPointStrategy", async () => { // Mock the convertToBedrockConverseMessages method to return a result with cache points - ;(handler as any).convertToBedrockConverseMessages.mockReturnValueOnce({ + // The typed spy instance is held through unknown to restate the private access. + ;( + vitest.mocked(handler["convertToBedrockConverseMessages"]) as unknown as { + mockReturnValueOnce: (v: unknown) => unknown + } + ).mockReturnValueOnce({ system: [{ text: systemPrompt }, { cachePoint: { type: "default" } }], - messages: mockMessages.map((msg: any) => ({ + messages: mockMessages.map((msg: Anthropic.Messages.MessageParam) => ({ role: msg.role, - content: [{ text: typeof msg.content === "string" ? msg.content : msg.content[0].text }], + content: [ + { + text: + typeof msg.content === "string" + ? msg.content + : (msg.content[0] as Anthropic.TextBlockParam).text, + }, + ], })), }) @@ -572,11 +597,22 @@ describe("Cache Strategy", () => { it("should yield usage results with cache tokens when using MultiPointStrategy", async () => { // Mock the convertToBedrockConverseMessages method to return a result with cache points - ;(handler as any).convertToBedrockConverseMessages.mockReturnValueOnce({ + ;( + vitest.mocked(handler["convertToBedrockConverseMessages"]) as unknown as { + mockReturnValueOnce: (v: unknown) => unknown + } + ).mockReturnValueOnce({ system: [{ text: systemPrompt }, { cachePoint: { type: "default" } }], - messages: mockMessages.map((msg: any) => ({ + messages: mockMessages.map((msg: Anthropic.Messages.MessageParam) => ({ role: msg.role, - content: [{ text: typeof msg.content === "string" ? msg.content : msg.content[0].text }], + content: [ + { + text: + typeof msg.content === "string" + ? msg.content + : (msg.content[0] as Anthropic.TextBlockParam).text, + }, + ], })), }) @@ -655,7 +691,7 @@ describe("Cache Strategy", () => { } // Helper to log cache point placements for debugging - const logPlacements = (placements: any[]) => { + const logPlacements = (placements: CachePointPlacement[]) => { console.log( "Cache point placements:", placements.map((p) => `index: ${p.index}, tokens: ${p.tokensCovered}`), diff --git a/src/api/transform/openai-format.ts b/src/api/transform/openai-format.ts index d91f6917d20..e0048b0398f 100644 --- a/src/api/transform/openai-format.ts +++ b/src/api/transform/openai-format.ts @@ -40,7 +40,7 @@ export type ReasoningDetail = { * @returns Consolidated array of reasoning details * @see https://github.com/cline/cline/issues/8214 */ -export function consolidateReasoningDetails(reasoningDetails: ReasoningDetail[]): ReasoningDetail[] { +export function consolidateReasoningDetails(reasoningDetails: ReasoningDetail[] | undefined): ReasoningDetail[] { if (!reasoningDetails || reasoningDetails.length === 0) { return [] } diff --git a/src/api/transform/r1-format.ts b/src/api/transform/r1-format.ts index 021ea7d26ce..69e4f600f8c 100644 --- a/src/api/transform/r1-format.ts +++ b/src/api/transform/r1-format.ts @@ -200,9 +200,13 @@ export function convertToR1Format( arguments: JSON.stringify(sanitizeSurrogatesDeep(part.input)), }, }) - } else if ((part as any).type === "reasoning" && (part as any).text) { + } else { + // Extension reasoning block stored by Task; narrow the shape defensively. // Extract reasoning from content blocks (Task stores it this way) - extractedReasoning = sanitizeSurrogates((part as any).text) + const block = part as { type?: unknown; text?: unknown } + if (block.type === "reasoning" && typeof block.text === "string" && block.text) { + extractedReasoning = sanitizeSurrogates(block.text) + } } } @@ -219,7 +223,7 @@ export function convertToR1Format( // Check if we can merge with the last message (only if no tool calls) const lastMessage = result[result.length - 1] - if (lastMessage?.role === "assistant" && !toolCalls.length && !(lastMessage as any).tool_calls) { + if (lastMessage?.role === "assistant" && !toolCalls.length && !lastMessage.tool_calls) { // Merge text content if (typeof lastMessage.content === "string" && typeof assistantMessage.content === "string") { lastMessage.content += `\n${assistantMessage.content}` @@ -238,7 +242,7 @@ export function convertToR1Format( // Simple string content const safeContent = sanitizeSurrogates(message.content) const lastMessage = result[result.length - 1] - if (lastMessage?.role === "assistant" && !(lastMessage as any).tool_calls) { + if (lastMessage?.role === "assistant" && !lastMessage.tool_calls) { if (typeof lastMessage.content === "string") { lastMessage.content += `\n${safeContent}` } else { diff --git a/src/eslint-suppressions.json b/src/eslint-suppressions.json index 1f8e2094258..3dc71527725 100644 --- a/src/eslint-suppressions.json +++ b/src/eslint-suppressions.json @@ -1,9 +1,4 @@ { - "api/providers/__tests__/anthropic-vertex.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 31 - } - }, "api/providers/__tests__/anthropic.spec.ts": { "@typescript-eslint/no-explicit-any": { "count": 7 @@ -24,51 +19,6 @@ "count": 4 } }, - "api/providers/__tests__/bedrock-custom-arn.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 12 - } - }, - "api/providers/__tests__/bedrock-error-handling.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 7 - } - }, - "api/providers/__tests__/bedrock-inference-profiles.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 27 - } - }, - "api/providers/__tests__/bedrock-native-tools.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 19 - } - }, - "api/providers/__tests__/bedrock-reasoning.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "api/providers/__tests__/bedrock.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 37 - } - }, - "api/providers/__tests__/deepseek.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 12 - } - }, - "api/providers/__tests__/gemini-handler.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 18 - } - }, - "api/providers/__tests__/gemini.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 33 - } - }, "api/providers/__tests__/kenari.spec.ts": { "@typescript-eslint/no-explicit-any": { "count": 1 @@ -84,51 +34,11 @@ "count": 26 } }, - "api/providers/__tests__/mimo.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 18 - } - }, "api/providers/__tests__/minimax.spec.ts": { "@typescript-eslint/no-explicit-any": { "count": 2 } }, - "api/providers/__tests__/moonshot.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 22 - } - }, - "api/providers/__tests__/native-ollama.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 21 - } - }, - "api/providers/__tests__/openai-codex-native-tool-calls.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 22 - } - }, - "api/providers/__tests__/openai-codex.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 16 - } - }, - "api/providers/__tests__/openai-native-tools.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 14 - } - }, - "api/providers/__tests__/openai-native-usage.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 25 - } - }, - "api/providers/__tests__/openai-native.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 74 - } - }, "api/providers/__tests__/openai-timeout.spec.ts": { "@typescript-eslint/no-explicit-any": { "count": 5 @@ -144,11 +54,6 @@ "count": 3 } }, - "api/providers/__tests__/openrouter.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 34 - } - }, "api/providers/__tests__/poe.spec.ts": { "@typescript-eslint/no-explicit-any": { "count": 1 @@ -204,11 +109,6 @@ "count": 4 } }, - "api/providers/bedrock.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 32 - } - }, "api/providers/deepseek.ts": { "@typescript-eslint/no-explicit-any": { "count": 2 @@ -284,24 +184,14 @@ "count": 5 } }, - "api/providers/moonshot.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, "api/providers/native-ollama.ts": { "@typescript-eslint/no-explicit-any": { "count": 2 } }, - "api/providers/openai-codex.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 31 - } - }, "api/providers/openai-native.ts": { "@typescript-eslint/no-explicit-any": { - "count": 27 + "count": 26 } }, "api/providers/openai.ts": { @@ -329,26 +219,11 @@ "count": 3 } }, - "api/providers/utils/__tests__/error-handler.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 35 - } - }, - "api/providers/utils/__tests__/image-generation.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 17 - } - }, "api/providers/utils/__tests__/timeout-config.spec.ts": { "@typescript-eslint/no-explicit-any": { "count": 2 } }, - "api/providers/utils/error-handler.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 7 - } - }, "api/providers/xai.ts": { "@typescript-eslint/no-explicit-any": { "count": 4 @@ -384,11 +259,6 @@ "count": 8 } }, - "api/transform/__tests__/openai-format.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 49 - } - }, "api/transform/__tests__/r1-format.spec.ts": { "@typescript-eslint/no-explicit-any": { "count": 8 @@ -419,11 +289,6 @@ "count": 2 } }, - "api/transform/cache-strategy/__tests__/cache-strategy.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 17 - } - }, "api/transform/caching/__tests__/gemini.spec.ts": { "@typescript-eslint/no-explicit-any": { "count": 1 @@ -439,11 +304,6 @@ "count": 7 } }, - "api/transform/r1-format.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, "api/transform/responses-api-input.ts": { "@typescript-eslint/no-explicit-any": { "count": 6