diff --git a/apps/cli/src/lib/utils/__tests__/context-window.test.ts b/apps/cli/src/lib/utils/__tests__/context-window.test.ts index 83420592ef2..abbfe778d93 100644 --- a/apps/cli/src/lib/utils/__tests__/context-window.test.ts +++ b/apps/cli/src/lib/utils/__tests__/context-window.test.ts @@ -14,6 +14,7 @@ describe("getContextWindow", () => { [providerIdentifiers.vercelAiGateway, "vercelAiGatewayModelId"], [providerIdentifiers.opencodeGo, "opencodeGoModelId"], [providerIdentifiers.kenari, "kenariModelId"], + [providerIdentifiers.infer, "inferModelId"], [providerIdentifiers.nanogpt, "nanoGptModelId"], [providerIdentifiers.zooGateway, "zooGatewayModelId"], ] as const)("uses the provider-specific model field for %s", (provider, modelField) => { diff --git a/packages/types/src/__tests__/infer.test.ts b/packages/types/src/__tests__/infer.test.ts new file mode 100644 index 00000000000..150fcbc7f9b --- /dev/null +++ b/packages/types/src/__tests__/infer.test.ts @@ -0,0 +1,27 @@ +import { + dynamicProviders, + getModelId, + getProviderDefaultModelId, + inferDefaultModelId, + isSecretStateKey, + providerIdentifiers, + providerSettingsSchema, +} from "../index.js" + +describe("Infer shared contract", () => { + it("registers the stable dynamic-provider identity and default model", () => { + expect(providerIdentifiers.infer).toBe("infer") + expect(dynamicProviders).toContain(providerIdentifiers.infer) + expect(getProviderDefaultModelId(providerIdentifiers.infer, {})).toBe(inferDefaultModelId) + expect(inferDefaultModelId).toBe("infer/claude-opus-5-5:low-cost") + }) + + it("classifies the API key as secret and resolves the configured model", () => { + expect(isSecretStateKey("inferApiKey")).toBe(true) + const settings = providerSettingsSchema.parse({ + apiProvider: providerIdentifiers.infer, + inferModelId: "infer/model:stable", + }) + expect(getModelId(settings)).toBe("infer/model:stable") + }) +}) diff --git a/packages/types/src/__tests__/provider-identifiers.test.ts b/packages/types/src/__tests__/provider-identifiers.test.ts index 92494a56bc0..39ba18e0684 100644 --- a/packages/types/src/__tests__/provider-identifiers.test.ts +++ b/packages/types/src/__tests__/provider-identifiers.test.ts @@ -35,6 +35,7 @@ const expectedProviderIdentifiers = [ "opencode-go", "kenari", "nanogpt", + "infer", "ollama", "lmstudio", "vscode-lm", @@ -112,6 +113,7 @@ describe("provider identifiers", () => { providerIdentifiers.opencodeGo, providerIdentifiers.kenari, providerIdentifiers.nanogpt, + providerIdentifiers.infer, providerIdentifiers.kimiCode, providerIdentifiers.friendli, ]) diff --git a/packages/types/src/__tests__/provider-model-id.test.ts b/packages/types/src/__tests__/provider-model-id.test.ts index e25341e4c3d..040fee1b70d 100644 --- a/packages/types/src/__tests__/provider-model-id.test.ts +++ b/packages/types/src/__tests__/provider-model-id.test.ts @@ -21,6 +21,7 @@ const expectedModelIdKeys = [ "opencodeGoModelId", "kenariModelId", "nanoGptModelId", + "inferModelId", "zooGatewayModelId", ] as const diff --git a/packages/types/src/global-settings.ts b/packages/types/src/global-settings.ts index ef812b01bbd..4fa45a02039 100644 --- a/packages/types/src/global-settings.ts +++ b/packages/types/src/global-settings.ts @@ -385,6 +385,7 @@ export const SECRET_STATE_KEYS = [ "vercelAiGatewayApiKey", "opencodeGoApiKey", "kenariApiKey", + "inferApiKey", "nanoGptApiKey", "basetenApiKey", ] as const diff --git a/packages/types/src/provider-identifiers.ts b/packages/types/src/provider-identifiers.ts index 50646bb6dc0..bdbc0a488a0 100644 --- a/packages/types/src/provider-identifiers.ts +++ b/packages/types/src/provider-identifiers.ts @@ -15,6 +15,7 @@ export const providerIdentifiers = { opencodeGo: "opencode-go", kenari: "kenari", nanogpt: "nanogpt", + infer: "infer", ollama: "ollama", lmstudio: "lmstudio", vscodeLm: "vscode-lm", diff --git a/packages/types/src/provider-settings.ts b/packages/types/src/provider-settings.ts index c31a3948b24..014f1d14ba7 100644 --- a/packages/types/src/provider-settings.ts +++ b/packages/types/src/provider-settings.ts @@ -101,6 +101,7 @@ export const dynamicProviders = [ providerIdentifiers.opencodeGo, providerIdentifiers.kenari, providerIdentifiers.nanogpt, + providerIdentifiers.infer, providerIdentifiers.kimiCode, providerIdentifiers.friendli, ] as const @@ -316,6 +317,7 @@ export const modelIdKeys = [ "opencodeGoModelId", "kenariModelId", "nanoGptModelId", + "inferModelId", "zooGatewayModelId", ] as const satisfies readonly ModelIdKey[] @@ -557,6 +559,7 @@ export const MODELS_BY_PROVIDER: Record< }, [providerIdentifiers.opencodeGo]: { id: providerIdentifiers.opencodeGo, label: "Opencode Go", models: [] }, [providerIdentifiers.kenari]: { id: providerIdentifiers.kenari, label: "Kenari", models: [] }, + [providerIdentifiers.infer]: { id: providerIdentifiers.infer, label: "Infer", models: [] }, [providerIdentifiers.nanogpt]: { id: providerIdentifiers.nanogpt, label: "NanoGPT", models: [] }, [providerIdentifiers.zooGateway]: { id: providerIdentifiers.zooGateway, label: "Zoo Gateway", models: [] }, diff --git a/packages/types/src/providers/index.ts b/packages/types/src/providers/index.ts index cae4f12b288..807d0f005c9 100644 --- a/packages/types/src/providers/index.ts +++ b/packages/types/src/providers/index.ts @@ -29,6 +29,7 @@ export * from "./xai.js" export * from "./vercel-ai-gateway.js" export * from "./opencode-go.js" export * from "./kenari.js" +export * from "./infer.js" export * from "./nanogpt.js" export * from "./kimi-code.js" export * from "./zai.js" @@ -46,6 +47,7 @@ import { fakeAiProviderDefinition } from "./fake-ai.js" import { fireworksProviderDefinition } from "./fireworks.js" import { friendliProviderDefinition } from "./friendli.js" import { geminiProviderDefinition } from "./gemini.js" +import { inferProviderDefinition } from "./infer.js" import { kenariProviderDefinition } from "./kenari.js" import { kimiCodeProviderDefinition } from "./kimi-code.js" import { litellmProviderDefinition } from "./litellm.js" @@ -109,6 +111,7 @@ export const providerDefinitionList = [ opencodeGoProviderDefinition, kenariProviderDefinition, nanoGptProviderDefinition, + inferProviderDefinition, zooGatewayProviderDefinition, basetenProviderDefinition, ] as const satisfies readonly ProviderDefinition[] diff --git a/packages/types/src/providers/infer.ts b/packages/types/src/providers/infer.ts new file mode 100644 index 00000000000..730b264e02e --- /dev/null +++ b/packages/types/src/providers/infer.ts @@ -0,0 +1,44 @@ +import { z } from "zod" + +import { type ModelInfo } from "../model.js" +import { providerIdentifiers } from "../provider-identifiers.js" +import { baseProviderSettingsShape, createModelIdAccessor, createProviderDefinition } from "./common.js" + +// Infer: OpenAI-compatible gateway to OpenAI, Anthropic, Google and xAI models. +// https://infer.flow7.org/docs · base URL: https://infer.flow7.org/v1 +// +// A model id selects a model and a route, for example `infer/claude-opus-5-5:low-cost`. +// The routes are Low cost, Balanced, Stable and Official, at different prices. +// The public catalog lists each route with its prices and limits, so the model list +// is fetched at runtime. The values below are only a fallback for the time before +// the catalog resolves. + +export const INFER_BASE_URL = "https://infer.flow7.org/v1" + +export const INFER_CATALOG_URL = "https://infer.flow7.org/api/public/catalog" + +export const inferDefaultModelId = "infer/claude-opus-5-5:low-cost" + +export const inferDefaultModelInfo: ModelInfo = { + maxTokens: 128_000, + contextWindow: 1_000_000, + supportsImages: false, + supportsPromptCache: false, + // Prices are intentionally omitted: they come only from the live catalog, so a + // fallback never shows a stale price. + description: "Infer model. Routes, prices and limits are resolved dynamically from the public catalog.", +} + +const INFER_MODEL_ID_FIELD = "inferModelId" + +export const inferProviderDefinition = createProviderDefinition({ + apiProvider: providerIdentifiers.infer, + modelIdKey: INFER_MODEL_ID_FIELD, + getModelId: createModelIdAccessor(INFER_MODEL_ID_FIELD), + getDefaultModelId: () => inferDefaultModelId, + schema: { + ...baseProviderSettingsShape, + inferApiKey: z.string().optional(), + [INFER_MODEL_ID_FIELD]: z.string().optional(), + }, +}) diff --git a/src/api/__tests__/index.spec.ts b/src/api/__tests__/index.spec.ts index 303c8f8ec84..074b5487bf3 100644 --- a/src/api/__tests__/index.spec.ts +++ b/src/api/__tests__/index.spec.ts @@ -56,6 +56,7 @@ import { FireworksHandler, FriendliHandler, GeminiHandler, + InferHandler, KenariHandler, KimiCodeHandler, LiteLLMHandler, @@ -117,6 +118,7 @@ const expectedHandlers = { [providerIdentifiers.vercelAiGateway]: VercelAiGatewayHandler, [providerIdentifiers.opencodeGo]: OpencodeGoHandler, [providerIdentifiers.kenari]: KenariHandler, + [providerIdentifiers.infer]: InferHandler, [providerIdentifiers.nanogpt]: NanoGptHandler, [providerIdentifiers.zooGateway]: ZooGatewayHandler, [providerIdentifiers.minimax]: MiniMaxHandler, diff --git a/src/api/index.ts b/src/api/index.ts index f2e52979015..c1253704da4 100644 --- a/src/api/index.ts +++ b/src/api/index.ts @@ -45,6 +45,7 @@ import { VercelAiGatewayHandler, OpencodeGoHandler, KenariHandler, + InferHandler, NanoGptHandler, ZooGatewayHandler, MiniMaxHandler, @@ -285,6 +286,8 @@ export function buildApiHandler(configuration: ProviderSettings): ApiHandler { return new OpencodeGoHandler(options) case providerIdentifiers.kenari: return new KenariHandler(options) + case providerIdentifiers.infer: + return new InferHandler(options) case providerIdentifiers.nanogpt: return new NanoGptHandler(options) case providerIdentifiers.zooGateway: diff --git a/src/api/providers/__tests__/infer.spec.ts b/src/api/providers/__tests__/infer.spec.ts new file mode 100644 index 00000000000..087b197b53b --- /dev/null +++ b/src/api/providers/__tests__/infer.spec.ts @@ -0,0 +1,430 @@ +vi.mock("vscode", () => ({ + workspace: { getConfiguration: () => ({ get: (_key: string, defaultValue?: unknown) => defaultValue }) }, +})) + +import { Anthropic } from "@anthropic-ai/sdk" +import OpenAI from "openai" + +import { INFER_BASE_URL, inferDefaultModelId, providerIdentifiers } from "@roo-code/types" + +import { buildApiHandler } from "../../index" +import { prepareApiConversationMessage } from "../../../core/task/apiConversationHistory" +import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" +import { clearAllMocks } from "../../../test-utils/reset" +import { InferHandler } from "../infer" +import { getModels } from "../fetchers/modelCache" + +const MODEL_ID = "infer/test-model:low-cost" +const MODEL_INFO = { maxTokens: 128_000, contextWindow: 1_000_000, supportsImages: false, supportsPromptCache: true } + +vi.mock("openai") +vi.mock("../fetchers/modelCache", () => ({ + getModels: vi.fn(), + getModelsFromCache: vi.fn(), + refreshModels: vi.fn().mockResolvedValue({}), +})) + +const mockCreate = vi.fn() +vi.mocked(OpenAI).mockImplementation(function () { + return { chat: { completions: { create: mockCreate } } } as unknown as OpenAI +}) + +const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hello" }] + +/** Flattens every argument of every console.error call into one searchable string. */ +const loggedText = (spy: { mock: { calls: unknown[][] } }) => + spy.mock.calls + .flat() + .map((arg) => (typeof arg === "string" ? arg : JSON.stringify(arg))) + .join("\n") + +describe("InferHandler", () => { + beforeEach(() => { + clearAllMocks() + vi.mocked(getModels).mockResolvedValue({ [MODEL_ID]: MODEL_INFO }) + mockCreate.mockResolvedValue(asyncStreamFrom([])) + }) + + it("is constructed by the backend provider registry", () => { + expect(buildApiHandler({ apiProvider: providerIdentifiers.infer })).toBeInstanceOf(InferHandler) + }) + + it("shares one model cache across URLs, keys and auth, because the catalog is public", () => { + expect(new InferHandler({ inferApiKey: "test-key" }).getModelCacheScope()).toEqual({ + urlScoped: false, + keyScoped: false, + authScoped: false, + }) + }) + + it("sends requests to the fixed Infer endpoint with the configured key", () => { + new InferHandler({ inferApiKey: "test-key" }) + expect(vi.mocked(OpenAI)).toHaveBeenCalledWith( + expect.objectContaining({ baseURL: INFER_BASE_URL, apiKey: "test-key" }), + ) + }) + + it("resolves the default model when none is configured", async () => { + const handler = new InferHandler({}) + await collectStream(handler.createMessage("system", messages)) + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: inferDefaultModelId }), { + signal: undefined, + }) + }) + + it("uses the configured route selector and streams text, reasoning, and tool calls", async () => { + mockCreate.mockResolvedValue( + asyncStreamFrom([ + { choices: [{ delta: { role: "assistant", content: "" } }] }, + { choices: [{ delta: { reasoning: "thinking" } }] }, + { choices: [{ delta: { content: "answer" } }] }, + { + choices: [ + { + delta: { + tool_calls: [ + { + index: 0, + id: "call-1", + type: "function", + function: { name: "read_file", arguments: "" }, + }, + ], + }, + }, + ], + }, + { choices: [{ delta: { tool_calls: [{ index: 0, function: { arguments: '{"path":' } }] } }] }, + ]), + ) + const chunks = await collectStream(new InferHandler({ inferModelId: MODEL_ID }).createMessage("sys", messages)) + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ model: MODEL_ID }), { signal: undefined }) + expect(chunks).toEqual([ + { type: "reasoning", text: "thinking" }, + { type: "text", text: "answer" }, + { type: "tool_call_partial", index: 0, id: "call-1", name: "read_file", arguments: "" }, + { type: "tool_call_partial", index: 0, id: undefined, name: undefined, arguments: '{"path":' }, + ]) + }) + + it("forwards native tools, usage streaming, session affinity, and cancellation without an output cap", async () => { + const signal = new AbortController().signal + const tools: OpenAI.Chat.ChatCompletionTool[] = [ + { type: "function", function: { name: "read_file", description: "Read", parameters: { type: "object" } } }, + ] + const handler = new InferHandler({ inferModelId: MODEL_ID, modelTemperature: 0.7 }) + await collectStream( + handler.createMessage("sys", messages, { + taskId: "task-1", + tools, + tool_choice: "required", + parallelToolCalls: false, + abortSignal: signal, + }), + ) + expect(mockCreate).toHaveBeenCalledWith( + expect.objectContaining({ + model: MODEL_ID, + messages: [ + { role: "system", content: "sys" }, + { role: "user", content: "Hello" }, + ], + stream: true, + stream_options: { include_usage: true }, + temperature: 0.7, + tools: [ + expect.objectContaining({ + type: "function", + function: expect.objectContaining({ name: "read_file", description: "Read" }), + }), + ], + tool_choice: "required", + parallel_tool_calls: false, + }), + { signal, headers: { "X-Session-Affinity": "task-1" } }, + ) + // Infer holds the cost of the output cap before the request, so no cap is sent. + expect(mockCreate.mock.calls[0][0]).not.toHaveProperty("max_tokens") + expect(mockCreate.mock.calls[0][0]).not.toHaveProperty("max_completion_tokens") + }) + + it("maps usage, cache writes, and the settled charge from the final chunk", async () => { + mockCreate.mockResolvedValue( + asyncStreamFrom([ + { choices: [{ delta: {}, finish_reason: "stop" }], relay: { customer_cost_usd: 0.0042 } }, + { + choices: [], + usage: { + prompt_tokens: 1000, + completion_tokens: 50, + prompt_tokens_details: { cached_tokens: 600, cache_write_tokens: 300 }, + }, + relay: { customer_cost_usd: 0.0042 }, + }, + ]), + ) + expect( + await collectStream(new InferHandler({ inferModelId: MODEL_ID }).createMessage("sys", messages)), + ).toEqual([ + { + type: "usage", + inputTokens: 1000, + outputTokens: 50, + cacheReadTokens: 600, + cacheWriteTokens: 300, + totalCost: 0.0042, + }, + ]) + }) + + it("preserves zero cache counts and omits the charge when the chunk has none", async () => { + mockCreate.mockResolvedValue( + asyncStreamFrom([ + { + choices: [], + usage: { + prompt_tokens: 20, + completion_tokens: 10, + prompt_tokens_details: { cached_tokens: 0, cache_write_tokens: 0 }, + }, + }, + ]), + ) + expect( + await collectStream(new InferHandler({ inferModelId: MODEL_ID }).createMessage("sys", messages)), + ).toEqual([{ type: "usage", inputTokens: 20, outputTokens: 10, cacheReadTokens: 0, cacheWriteTokens: 0 }]) + }) + + it("reports a settled charge of zero as a total cost of zero", async () => { + mockCreate.mockResolvedValue( + asyncStreamFrom([ + { + choices: [], + usage: { prompt_tokens: 20, completion_tokens: 10 }, + relay: { customer_cost_usd: 0 }, + }, + ]), + ) + expect( + await collectStream(new InferHandler({ inferModelId: MODEL_ID }).createMessage("sys", messages)), + ).toEqual([{ type: "usage", inputTokens: 20, outputTokens: 10, totalCost: 0 }]) + }) + + it.each(["0.0042", Number.POSITIVE_INFINITY, null])( + "does not report a charge that is not a finite number (%s)", + async (charge) => { + mockCreate.mockResolvedValue( + asyncStreamFrom([ + { + choices: [], + usage: { prompt_tokens: 20, completion_tokens: 10 }, + relay: { customer_cost_usd: charge }, + }, + ]), + ) + const [usage] = await collectStream( + new InferHandler({ inferModelId: MODEL_ID }).createMessage("sys", messages), + ) + expect(usage).toEqual({ type: "usage", inputTokens: 20, outputTokens: 10 }) + expect(usage).not.toHaveProperty("totalCost") + }, + ) + + it("redacts the API key from streaming errors and from the logged error", async () => { + const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + try { + mockCreate.mockRejectedValue(new Error("upstream rejected secret-key")) + const handler = new InferHandler({ inferApiKey: "secret-key", inferModelId: MODEL_ID }) + await expect(collectStream(handler.createMessage("sys", messages))).rejects.toMatchObject({ + message: "Infer streaming error: upstream rejected [REDACTED]", + }) + // The error handler logs message + stack before the transformer runs, + // so the key must already be gone from both. + expect(consoleErrorSpy).toHaveBeenCalledWith( + "[Infer] API error:", + expect.objectContaining({ + message: "upstream rejected [REDACTED]", + stack: expect.stringContaining("[REDACTED]"), + }), + ) + expect(loggedText(consoleErrorSpy)).not.toContain("secret-key") + } finally { + consoleErrorSpy.mockRestore() + } + }) + + it("serializes and redacts an object-valued raw error body and keeps the status", async () => { + const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + try { + mockCreate.mockRejectedValue( + Object.assign(new Error("Request failed"), { + status: 402, + error: { metadata: { raw: { detail: "insufficient credits for secret-key" } } }, + }), + ) + const handler = new InferHandler({ inferApiKey: "secret-key", inferModelId: MODEL_ID }) + await expect(collectStream(handler.createMessage("sys", messages))).rejects.toMatchObject({ + message: 'Infer streaming error: {"detail":"insufficient credits for [REDACTED]"}', + status: 402, + }) + expect(loggedText(consoleErrorSpy)).not.toContain("secret-key") + } finally { + consoleErrorSpy.mockRestore() + } + }) + + it("redacts the API key from non-Error rejections and their log line", async () => { + const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + try { + mockCreate.mockRejectedValue("upstream rejected secret-key") + const handler = new InferHandler({ inferApiKey: "secret-key", inferModelId: MODEL_ID }) + await expect(collectStream(handler.createMessage("sys", messages))).rejects.toMatchObject({ + message: "Infer streaming error: upstream rejected [REDACTED]", + }) + expect(consoleErrorSpy).toHaveBeenCalledWith("[Infer] Non-Error exception:", "upstream rejected [REDACTED]") + expect(loggedText(consoleErrorSpy)).not.toContain("secret-key") + } finally { + consoleErrorSpy.mockRestore() + } + }) + + it("completePrompt wraps upstream errors without a configured key", async () => { + const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + try { + mockCreate.mockRejectedValue(new Error("boom")) + const handler = new InferHandler({ inferModelId: MODEL_ID }) + await expect(handler.completePrompt("ping")).rejects.toMatchObject({ + message: "Infer completion error: boom", + }) + } finally { + consoleErrorSpy.mockRestore() + } + }) + + it("completePrompt sends the prompt as a single user message without an output cap", async () => { + mockCreate.mockResolvedValue({ choices: [{ message: { role: "assistant", content: "ok" } }] }) + const handler = new InferHandler({ inferModelId: MODEL_ID }) + expect(await handler.completePrompt("ping")).toBe("ok") + // A bare call passes no request options: the OpenAI SDK rejects a present-but-undefined `timeout`. + expect(mockCreate).toHaveBeenCalledWith( + { model: MODEL_ID, messages: [{ role: "user", content: "ping" }], stream: false }, + undefined, + ) + }) + + it("completePrompt returns an empty string when the response has no choices", async () => { + mockCreate.mockResolvedValue({ choices: [] }) + const handler = new InferHandler({ inferModelId: MODEL_ID }) + expect(await handler.completePrompt("ping")).toBe("") + }) + + it("completePrompt forwards abort and timeout options when provided", async () => { + mockCreate.mockResolvedValue({ choices: [{ message: { role: "assistant", content: "ok" } }] }) + const signal = new AbortController().signal + const handler = new InferHandler({ inferModelId: MODEL_ID }) + await handler.completePrompt("ping", { abortSignal: signal, timeoutMs: 5_000 }) + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ stream: false }), { signal, timeout: 5_000 }) + }) + + it.each([0, -5, Number.NaN, Number.POSITIVE_INFINITY])( + "completePrompt does not forward an unusable timeoutMs (%s)", + async (timeoutMs) => { + mockCreate.mockResolvedValue({ choices: [{ message: { role: "assistant", content: "ok" } }] }) + const handler = new InferHandler({ inferModelId: MODEL_ID }) + await handler.completePrompt("ping", { timeoutMs }) + expect(mockCreate.mock.calls[0][1]).toBeUndefined() + }, + ) + + it.each([ + { + entry: "createMessage", + run: (h: InferHandler, signal: AbortSignal) => + h.createMessage("system", messages, { taskId: "t", abortSignal: signal }).next(), + }, + { + entry: "completePrompt", + run: (h: InferHandler, signal: AbortSignal) => h.completePrompt("ping", { abortSignal: signal }), + }, + ])("$entry stops waiting for a cold catalog when the caller aborts", async ({ run }) => { + vi.mocked(getModels).mockReturnValueOnce(new Promise(() => {})) + const controller = new AbortController() + const handler = new InferHandler({ inferModelId: MODEL_ID }) + const pending = run(handler, controller.signal) + + controller.abort() + + await expect(pending).rejects.toMatchObject({ name: "AbortError" }) + expect(mockCreate).not.toHaveBeenCalled() + }) + + it("does not send the OpenAI Compatible custom headers to the fixed endpoint", () => { + new InferHandler({ inferApiKey: "test-key", openAiHeaders: { "X-Custom-Header": "leaked" } }) + expect(vi.mocked(OpenAI)).toHaveBeenCalledTimes(1) + const clientOptions = vi.mocked(OpenAI).mock.calls[0][0] + expect(clientOptions?.defaultHeaders).not.toHaveProperty("X-Custom-Header") + }) + + it("omits a cleared (null) temperature in both request paths", async () => { + const handler = new InferHandler({ inferModelId: MODEL_ID, modelTemperature: null }) + + await collectStream(handler.createMessage("system", messages)) + expect(mockCreate.mock.calls[0][0]).not.toHaveProperty("temperature") + + mockCreate.mockClear() + mockCreate.mockResolvedValue({ choices: [{ message: { role: "assistant", content: "ok" } }] }) + expect(await handler.completePrompt("ping")).toBe("ok") + expect(mockCreate.mock.calls[0][0]).not.toHaveProperty("temperature") + }) + + it("completePrompt forwards the configured temperature", async () => { + mockCreate.mockResolvedValue({ choices: [{ message: { role: "assistant", content: "ok" } }] }) + const handler = new InferHandler({ inferModelId: MODEL_ID, modelTemperature: 0.7 }) + expect(await handler.completePrompt("ping")).toBe("ok") + expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({ stream: false, temperature: 0.7 }), undefined) + }) + + it.each(["reasoning_effort", "reasoning", "thinking", "include_reasoning"])( + "sends no %s parameter, even when the profile turns reasoning on", + async (field) => { + // Zoo Code cannot send a model's reasoning back to Infer on the next turn, so the + // handler never asks a model to reason, whatever the profile or the model info says. + vi.mocked(getModels).mockResolvedValue({ + [MODEL_ID]: { + ...MODEL_INFO, + supportsReasoningEffort: true, + reasoningEffort: "high", + supportsReasoningBudget: true, + }, + }) + const handler = new InferHandler({ + inferModelId: MODEL_ID, + enableReasoningEffort: true, + reasoningEffort: "high", + modelMaxThinkingTokens: 8_192, + }) + + await collectStream(handler.createMessage("sys", messages)) + mockCreate.mockResolvedValue({ choices: [{ message: { role: "assistant", content: "ok" } }] }) + await handler.completePrompt("ping") + + expect(mockCreate).toHaveBeenCalledTimes(2) + expect(mockCreate.mock.calls[0][0]).not.toHaveProperty(field) + expect(mockCreate.mock.calls[1][0]).not.toHaveProperty(field) + }, + ) + + it("keeps no reasoning state for the next turn", () => { + // Zoo Code sends reasoning_details back only when the handler returned them. The streamed + // reply has reasoning text only, so the stored assistant turn carries none. + const stored = prepareApiConversationMessage({ + message: { role: "assistant", content: [{ type: "text", text: "answer" }] }, + reasoning: "thinking", + api: new InferHandler({ inferModelId: MODEL_ID }), + apiConfiguration: { apiProvider: providerIdentifiers.infer, inferModelId: MODEL_ID }, + apiConversationHistory: [], + }) + + expect(stored).not.toHaveProperty("reasoning_details") + }) +}) diff --git a/src/api/providers/__tests__/model-catalog-adapters.spec.ts b/src/api/providers/__tests__/model-catalog-adapters.spec.ts index 61224791142..5c8ee4423ea 100644 --- a/src/api/providers/__tests__/model-catalog-adapters.spec.ts +++ b/src/api/providers/__tests__/model-catalog-adapters.spec.ts @@ -11,6 +11,7 @@ import type { ApiHandler, ModelCacheScope } from "../../index" const fetchers = vi.hoisted(() => ({ getDeepSeekModels: vi.fn(), + getInferModels: vi.fn(), getKenariModels: vi.fn(), getKimiCodeModels: vi.fn(), getLiteLLMModels: vi.fn(), @@ -45,6 +46,10 @@ vi.mock("../fetchers/deepseek", async (importOriginal) => ({ ...(await importOriginal()), getDeepSeekModels: fetchers.getDeepSeekModels, })) +vi.mock("../fetchers/infer", async (importOriginal) => ({ + ...(await importOriginal()), + getInferModels: fetchers.getInferModels, +})) vi.mock("../fetchers/kenari", async (importOriginal) => ({ ...(await importOriginal()), getKenariModels: fetchers.getKenariModels, @@ -104,6 +109,7 @@ vi.mock("../fetchers/zoo-gateway", async (importOriginal) => ({ import { AnthropicHandler } from "../anthropic" import { DeepSeekHandler } from "../deepseek" +import { InferHandler } from "../infer" import { KenariHandler } from "../kenari" import { KimiCodeHandler } from "../kimi-code" import { LiteLLMHandler } from "../lite-llm" @@ -149,6 +155,16 @@ const cases: AdapterCase[] = [ forwardsSignal: true, prewarms: false, }, + { + name: "Infer", + create: () => new InferHandler({ inferApiKey: API_KEY }), + fetcher: "getInferModels", + // The public catalog is the same for every key, so the key is not sent with it. + scope: { urlScoped: false, keyScoped: false, authScoped: false }, + expectedArgs: [], + forwardsSignal: true, + prewarms: false, + }, { name: "Kenari", create: () => new KenariHandler({ kenariApiKey: API_KEY }), diff --git a/src/api/providers/fetchers/__tests__/infer.spec.ts b/src/api/providers/fetchers/__tests__/infer.spec.ts new file mode 100644 index 00000000000..2c337ad06bf --- /dev/null +++ b/src/api/providers/fetchers/__tests__/infer.spec.ts @@ -0,0 +1,273 @@ +import axios from "axios" + +import { INFER_CATALOG_URL, openAiModelInfoSaneDefaults } from "@roo-code/types" + +import { getInferModels } from "../infer" + +vi.mock("axios") + +/** A route as the public catalog publishes it, with overridable fields. */ +const route = (selector: string, overrides: Record = {}) => ({ + selector, + available: true, + input_per_million_usd: 2, + cached_input_per_million_usd: 0.2, + cache_write_per_million_usd: 2.5, + output_per_million_usd: 10, + runtime: { max_context_tokens: null, max_output_tokens: null, vision: false, tools: true, streaming: true }, + ...overrides, +}) + +/** A text model with model-level limits and the given routes. */ +const model = (slug: string, tiers: Record, overrides: Record = {}) => ({ + slug, + name: slug, + kind: "exact", + runtime: { max_context_tokens: 200_000, max_output_tokens: 64_000, vision: false, tools: true, streaming: true }, + tiers, + ...overrides, +}) + +const mockCatalog = (models: unknown[]) => vi.mocked(axios.get).mockResolvedValue({ data: { models } }) + +describe("Infer model fetcher", () => { + beforeEach(() => vi.clearAllMocks()) + + it("requests the public catalog without credentials", async () => { + mockCatalog([]) + await getInferModels() + expect(axios.get).toHaveBeenCalledWith(INFER_CATALOG_URL, { timeout: 10_000, signal: undefined }) + }) + + it("forwards the caller's abort signal to the request", async () => { + mockCatalog([]) + const controller = new AbortController() + + await getInferModels({ signal: controller.signal }) + + expect(axios.get).toHaveBeenCalledWith(INFER_CATALOG_URL, { timeout: 10_000, signal: controller.signal }) + }) + + it("rejects with an AbortError when the signal aborts the pending request", async () => { + const controller = new AbortController() + vi.mocked(axios.get).mockImplementation((_url, config) => { + // Mirror the HTTP client: a pending request rejects when its signal fires. + return new Promise((_resolve, reject) => { + config?.signal?.addEventListener?.("abort", () => reject(new Error("canceled")), { once: true }) + }) + }) + + const fetchPromise = getInferModels({ signal: controller.signal }) + controller.abort() + + await expect(fetchPromise).rejects.toMatchObject({ name: "AbortError" }) + }) + + it("lists each available route under its selector with exact per-million prices and route limits", async () => { + mockCatalog([ + model("model-a", { + "low-cost": route("infer/model-a:low-cost"), + official: route("infer/model-a:official", { + input_per_million_usd: 5, + cached_input_per_million_usd: 0.5, + cache_write_per_million_usd: 6.25, + output_per_million_usd: 25, + runtime: { + max_context_tokens: 1_000_000, + max_output_tokens: 128_000, + vision: true, + tools: true, + streaming: true, + }, + }), + }), + ]) + + const models = await getInferModels() + + expect(Object.keys(models)).toEqual(["infer/model-a:low-cost", "infer/model-a:official"]) + // A discount route publishes no limits of its own, so the model-level limits apply. + expect(models["infer/model-a:low-cost"]).toEqual({ + contextWindow: 200_000, + maxTokens: 64_000, + supportsImages: false, + supportsPromptCache: true, + inputPrice: 2, + outputPrice: 10, + cacheReadsPrice: 0.2, + cacheWritesPrice: 2.5, + displayName: "model-a (Low cost)", + }) + expect(models["infer/model-a:official"]).toEqual({ + contextWindow: 1_000_000, + maxTokens: 128_000, + supportsImages: true, + supportsPromptCache: true, + inputPrice: 5, + outputPrice: 25, + cacheReadsPrice: 0.5, + cacheWritesPrice: 6.25, + displayName: "model-a (Official)", + }) + }) + + it.each([ + ["omitted", undefined], + ["zero", 0], + ])("prices cache writes at the input rate when the cache-write rate is %s", async (_label, rate) => { + const overrides: Record = + rate === undefined ? { cache_write_per_million_usd: undefined } : { cache_write_per_million_usd: rate } + mockCatalog([model("model-a", { "low-cost": route("infer/model-a:low-cost", overrides) })]) + + const models = await getInferModels() + + expect(models["infer/model-a:low-cost"].cacheWritesPrice).toBe(2) + }) + + it("omits the cache-write price when the route publishes no prices", async () => { + mockCatalog([ + model("model-a", { + "low-cost": route("infer/model-a:low-cost", { + input_per_million_usd: undefined, + cache_write_per_million_usd: undefined, + }), + }), + ]) + + const models = await getInferModels() + + expect(models["infer/model-a:low-cost"]).not.toHaveProperty("cacheWritesPrice") + }) + + it.each([ + ["balanced", "Balanced"], + ["stable", "Stable"], + ["future-route", "future-route"], + ["constructor", "constructor"], + ])("labels the %s route as %s", async (routeId, label) => { + mockCatalog([model("model-a", { [routeId]: route(`infer/model-a:${routeId}`) }, { name: "Model A" })]) + const models = await getInferModels() + expect(models[`infer/model-a:${routeId}`].displayName).toBe(`Model A (${label})`) + }) + + it.each([ + "supportsReasoningEffort", + "supportsReasoningBudget", + "supportsReasoningBinary", + "requiredReasoningEffort", + "requiredReasoningBudget", + "reasoningEffort", + "preserveReasoning", + "supportsMaxTokens", + ])("sets no %s flag on any route, so the settings show no reasoning control", async (flag) => { + mockCatalog([ + model("model-a", { + "low-cost": route("infer/model-a:low-cost"), + official: route("infer/model-a:official", { runtime: { vision: true, tools: true, streaming: true } }), + }), + ]) + + const models = await getInferModels() + + expect(models["infer/model-a:low-cost"]).not.toHaveProperty(flag) + expect(models["infer/model-a:official"]).not.toHaveProperty(flag) + }) + + it("falls back to the default context window and omits the output limit when no limit is published", async () => { + mockCatalog([ + model( + "model-b", + { stable: route("infer/model-b:stable", { cached_input_per_million_usd: 0 }) }, + { name: undefined, runtime: { max_context_tokens: null, max_output_tokens: 0 } }, + ), + ]) + + const info = (await getInferModels())["infer/model-b:stable"] + + expect(info.contextWindow).toBe(openAiModelInfoSaneDefaults.contextWindow) + expect(info).not.toHaveProperty("maxTokens") + // No cache-read price means the route does not bill cached input separately. + expect(info.supportsPromptCache).toBe(false) + expect(info.displayName).toBe("model-b (Stable)") + }) + + it("skips generation models and routes that are unavailable, lack tools, or cannot stream", async () => { + mockCatalog([ + model("video-model", { stable: route("infer/video-model:stable") }, { kind: "video_generation" }), + model("image-model", { stable: route("infer/image-model:stable") }, { kind: "image_generation" }), + model("text-model", { + "low-cost": route("infer/text-model:low-cost"), + balanced: route("infer/text-model:balanced", { available: false }), + stable: route("infer/text-model:stable", { runtime: { tools: false } }), + official: route("infer/text-model:official", { runtime: { streaming: false } }), + }), + model("unflagged-model", { stable: route("infer/unflagged-model:stable", { runtime: undefined }) }), + ]) + + expect(Object.keys(await getInferModels())).toEqual([ + "infer/text-model:low-cost", + "infer/unflagged-model:stable", + ]) + }) + + it("leaves out Gemini routes and keeps the Claude ones", async () => { + mockCatalog([ + model("gemini-3.8-flash", { + "low-cost": route("infer/gemini-3.8-flash:low-cost"), + official: route("infer/gemini-3.8-flash:official"), + }), + model("claude-opus-5-5", { + "low-cost": route("infer/claude-opus-5-5:low-cost"), + official: route("infer/claude-opus-5-5:official"), + }), + ]) + + expect(Object.keys(await getInferModels())).toEqual([ + "infer/claude-opus-5-5:low-cost", + "infer/claude-opus-5-5:official", + ]) + }) + + it("skips malformed models and routes", async () => { + mockCatalog([ + { name: "missing slug", tiers: {} }, + model("model-c", { + "low-cost": route("infer/model-c:low-cost"), + balanced: { available: true }, + stable: route("infer/model-c:stable", { input_per_million_usd: -1 }), + }), + ]) + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined) + + expect(Object.keys(await getInferModels())).toEqual(["infer/model-c:low-cost"]) + expect(warning).toHaveBeenCalledTimes(3) + warning.mockRestore() + }) + + it("keeps a hostile selector as an own entry instead of polluting the prototype chain", async () => { + mockCatalog([model("hostile", { stable: route("__proto__"), official: route("constructor") })]) + const models = await getInferModels() + expect(Object.getPrototypeOf(models)).toBeNull() + expect(Object.keys(models)).toEqual(["__proto__", "constructor"]) + expect(models["__proto__"]).toMatchObject({ inputPrice: 2 }) + expect(({} as Record).inputPrice).toBeUndefined() + }) + + it.each([{ models: null }, [], null])("returns no models for invalid top-level data %#", async (data) => { + vi.mocked(axios.get).mockResolvedValue({ data }) + const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined) + expect(await getInferModels()).toEqual({}) + warning.mockRestore() + }) + + it.each([new Error("network unavailable"), "network unavailable"])( + "returns no models on network failure", + async (error) => { + vi.mocked(axios.get).mockRejectedValue(error) + const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined) + expect(await getInferModels()).toEqual({}) + expect(consoleError).toHaveBeenCalledWith("Error fetching Infer models: network unavailable") + consoleError.mockRestore() + }, + ) +}) diff --git a/src/api/providers/fetchers/__tests__/modelCache.spec.ts b/src/api/providers/fetchers/__tests__/modelCache.spec.ts index e9818cb7091..a1e9a1850ce 100644 --- a/src/api/providers/fetchers/__tests__/modelCache.spec.ts +++ b/src/api/providers/fetchers/__tests__/modelCache.spec.ts @@ -77,6 +77,7 @@ const OPENROUTER_SCOPE: ModelCacheScope = { urlScoped: false, keyScoped: false, const LITELLM_SCOPE: ModelCacheScope = { urlScoped: true, keyScoped: true, authScoped: false } const REQUESTY_SCOPE: ModelCacheScope = { urlScoped: true, keyScoped: true, authScoped: false } const NANOGPT_SCOPE: ModelCacheScope = { urlScoped: false, keyScoped: true, authScoped: false } +const INFER_SCOPE: ModelCacheScope = { urlScoped: false, keyScoped: false, authScoped: false } const ZOO_SCOPE: ModelCacheScope = { urlScoped: true, keyScoped: true, authScoped: true } const MOONSHOT_SCOPE: ModelCacheScope = { urlScoped: true, keyScoped: true, authScoped: false } @@ -229,6 +230,24 @@ describe("getModels with new GetModelsOptions", () => { expect(result).toEqual(mockModels) }) + it("dispatches Infer's public catalog without an API key", async () => { + const mockModels = { + "infer/test-model:low-cost": { + maxTokens: 8192, + contextWindow: 128000, + supportsPromptCache: false, + }, + } + const fetchModels = vi.fn().mockResolvedValue(mockModels) + const handler = makeHandler(INFER_SCOPE, fetchModels) + + const options = { provider: providerIdentifiers.infer } as const + const result = await getModels(options, handler) + + expect(fetchModels).toHaveBeenCalledWith(options, expect.any(AbortSignal)) + expect(result).toEqual(mockModels) + }) + it("handles errors and re-throws them", async () => { const expectedError = new Error("LiteLLM connection failed") const fetchModels = vi.fn().mockRejectedValue(expectedError) @@ -1238,6 +1257,30 @@ describe("NanoGPT key-scoped cache isolation", () => { }) }) +describe("Infer shared public catalog cache", () => { + const inferModels = { + "infer/test-model:low-cost": { maxTokens: 8_192, contextWindow: 128_000, supportsPromptCache: false }, + } + + let handler: ApiHandler + + beforeEach(() => { + vi.clearAllMocks() + handler = makeHandler(INFER_SCOPE, vi.fn().mockResolvedValue(inferModels)) + }) + + it("stores one catalog under the bare provider key whatever key is supplied", async () => { + const mockCache = vi.mocked(new (vi.mocked(NodeCache))()) + mockCache.get.mockReturnValue(undefined) + + await getModels({ provider: providerIdentifiers.infer }, handler) + await getModels({ provider: providerIdentifiers.infer, apiKey: "infer-key-a" }, handler) + + const cacheKeys = mockCache.set.mock.calls.map(([key]) => key as string) + expect(new Set(cacheKeys)).toEqual(new Set([providerIdentifiers.infer])) + }) +}) + describe("compound cache key derivation across scoping dimensions", () => { // Exercises every branch of getCacheKey via the public getModels() entry point. // litellm is url-scoped AND key-scoped; openrouter is neither, so it hits the bare diff --git a/src/api/providers/fetchers/infer.ts b/src/api/providers/fetchers/infer.ts new file mode 100644 index 00000000000..a7906f82492 --- /dev/null +++ b/src/api/providers/fetchers/infer.ts @@ -0,0 +1,151 @@ +import axios from "axios" +import { z } from "zod" + +import { INFER_CATALOG_URL, openAiModelInfoSaneDefaults, type ModelInfo, type ModelRecord } from "@roo-code/types" + +import { throwIfAborted } from "../utils/abort-signal" + +// Each catalog route has an id. The model picker shows its label after the model name. +const INFER_ROUTE_LABELS = new Map([ + ["low-cost", "Low cost"], + ["balanced", "Balanced"], + ["stable", "Stable"], + ["official", "Official"], +]) + +// Image and video generation models use their own endpoints, not chat completions. +const INFER_GENERATION_KINDS = new Set(["image_generation", "video_generation"]) + +const inferRuntimeSchema = z.object({ + max_context_tokens: z.number().nullish(), + max_output_tokens: z.number().nullish(), + vision: z.boolean().optional(), + tools: z.boolean().optional(), + streaming: z.boolean().optional(), +}) + +const inferRouteSchema = z.object({ + selector: z.string().min(1), + available: z.boolean().optional(), + input_per_million_usd: z.number().nonnegative().optional(), + cached_input_per_million_usd: z.number().nonnegative().optional(), + cache_write_per_million_usd: z.number().nonnegative().optional(), + output_per_million_usd: z.number().nonnegative().optional(), + runtime: inferRuntimeSchema.optional(), +}) + +const inferModelSchema = z.object({ + slug: z.string().min(1), + name: z.string().optional(), + kind: z.string().optional(), + runtime: inferRuntimeSchema.optional(), + tiers: z.record(z.string(), z.unknown()), +}) + +const inferCatalogSchema = z.object({ + models: z.array(z.unknown()), +}) + +type InferModel = z.infer +type InferRoute = z.infer +type InferLimit = "max_context_tokens" | "max_output_tokens" + +/** A route limit wins over the model limit. A missing or non-positive value means "not published". */ +const getLimit = (model: InferModel, route: InferRoute, limit: InferLimit): number | undefined => + [route.runtime?.[limit], model.runtime?.[limit]].find( + (value): value is number => typeof value === "number" && value > 0, + ) + +/** Maps one catalog route to model info. Prices are published per 1M tokens in USD, as ModelInfo expects. */ +export const parseInferRoute = (model: InferModel, routeId: string, route: InferRoute): ModelInfo => { + const maxTokens = getLimit(model, route, "max_output_tokens") + // Infer bills cache writes at the input rate when a route has no separate cache-write + // price. The catalog shows that as an omitted or zero rate. + const cacheWritesPrice = + route.cache_write_per_million_usd !== undefined && route.cache_write_per_million_usd > 0 + ? route.cache_write_per_million_usd + : route.input_per_million_usd + + return { + contextWindow: getLimit(model, route, "max_context_tokens") ?? openAiModelInfoSaneDefaults.contextWindow, + ...(maxTokens !== undefined ? { maxTokens } : {}), + // Only some routes accept images, so the flag comes from the route, not the model. + supportsImages: route.runtime?.vision === true, + supportsPromptCache: (route.cached_input_per_million_usd ?? 0) > 0, + ...(route.input_per_million_usd !== undefined ? { inputPrice: route.input_per_million_usd } : {}), + ...(route.output_per_million_usd !== undefined ? { outputPrice: route.output_per_million_usd } : {}), + ...(route.cached_input_per_million_usd !== undefined + ? { cacheReadsPrice: route.cached_input_per_million_usd } + : {}), + ...(cacheWritesPrice !== undefined ? { cacheWritesPrice } : {}), + // The name is a remote string and ModelInfo.description is rendered as Markdown, + // so it is only surfaced as the plain-text displayName. + displayName: `${model.name ?? model.slug} (${INFER_ROUTE_LABELS.get(routeId) ?? routeId})`, + } +} + +/** + * Fetches the public Infer catalog and lists each available text route as a model. + * + * The catalog needs no API key and is the same for every account, so no key is sent. + * The model id of a route is its `selector`, for example `infer/claude-opus-5-5:low-cost`. + * + * @param opts - Optional per-request controls; `signal` cancels the in-flight request. + */ +export async function getInferModels(opts?: { signal?: AbortSignal }): Promise { + try { + const response = await axios.get(INFER_CATALOG_URL, { timeout: 10_000, signal: opts?.signal }) + const catalogResult = inferCatalogSchema.safeParse(response.data) + if (!catalogResult.success) { + console.warn("Infer catalog response did not match the expected top-level schema") + return {} + } + + // Use null-prototype object to prevent prototype pollution + const models: ModelRecord = Object.create(null) + for (const rawModel of catalogResult.data.models) { + const modelResult = inferModelSchema.safeParse(rawModel) + if (!modelResult.success) { + console.warn("Skipping invalid Infer catalog model entry") + continue + } + + const model = modelResult.data + if (model.kind !== undefined && INFER_GENERATION_KINDS.has(model.kind)) { + continue + } + + // Gemini models need their thought signatures back on the turn after a tool call, + // and this provider sends no reasoning back, so Gemini routes are left out for now. + if (model.slug.startsWith("gemini-")) { + continue + } + + for (const [routeId, rawRoute] of Object.entries(model.tiers)) { + const routeResult = inferRouteSchema.safeParse(rawRoute) + if (!routeResult.success) { + console.warn("Skipping invalid Infer catalog route entry") + continue + } + + const route = routeResult.data + // Tasks stream their replies and depend on tool calls, so an explicit false + // is authoritative. An omitted flag is unknown and stays eligible. + if (route.available !== true || route.runtime?.tools === false || route.runtime?.streaming === false) { + continue + } + + models[route.selector] = parseInferRoute(model, routeId, route) + } + } + + return models + } catch (error) { + // Surface cancellation as a rejection: logging and returning here would + // present an aborted fetch to callers as a successful (empty) catalog. + throwIfAborted(opts?.signal) + + console.error(`Error fetching Infer models: ${error instanceof Error ? error.message : String(error)}`) + return {} + } +} diff --git a/src/api/providers/index.ts b/src/api/providers/index.ts index 33d90b1c16c..6ce57c21f24 100644 --- a/src/api/providers/index.ts +++ b/src/api/providers/index.ts @@ -30,6 +30,7 @@ export { FriendliHandler } from "./friendli" export { VercelAiGatewayHandler } from "./vercel-ai-gateway" export { OpencodeGoHandler } from "./opencode-go" export { KenariHandler } from "./kenari" +export { InferHandler } from "./infer" export { NanoGptHandler } from "./nanogpt" export { ZooGatewayHandler } from "./zoo-gateway" export { MiniMaxHandler } from "./minimax" diff --git a/src/api/providers/infer.ts b/src/api/providers/infer.ts new file mode 100644 index 00000000000..ea5e0890089 --- /dev/null +++ b/src/api/providers/infer.ts @@ -0,0 +1,249 @@ +import { Anthropic } from "@anthropic-ai/sdk" +import OpenAI from "openai" + +import { + INFER_BASE_URL, + inferDefaultModelId, + inferDefaultModelInfo, + providerIdentifiers, + type ModelInfo, + type ModelRecord, +} from "@roo-code/types" + +import type { ApiHandlerOptions, GetModelsOptions } from "../../shared/api" + +import type { ApiStream, ApiStreamUsageChunk } from "../transform/stream" +import { convertToOpenAiMessages } from "../transform/openai-format" +import type { + ApiHandlerCreateMessageMetadata, + CompletePromptOptions, + ModelCacheScope, + SingleCompletionHandler, +} from "../index" +import { RouterProvider } from "./router-provider" +import { getInferModels } from "./fetchers/infer" +import { handleProviderError } from "./utils/error-handler" +import { extractReasoningFromDelta } from "./utils/extract-reasoning" +import { hasUsableTimeout, toSdkTimeoutMs } from "./utils/abort-signal" + +/** Infer reports cache writes next to cache reads. */ +type InferUsage = OpenAI.CompletionUsage & { + prompt_tokens_details?: OpenAI.CompletionUsage["prompt_tokens_details"] & { cache_write_tokens?: number } +} + +/** The final chunks also carry `relay`, with the charge that Infer settled for the request. */ +type InferChunk = OpenAI.Chat.ChatCompletionChunk & { relay?: { customer_cost_usd?: number } } + +function mapInferUsage(usage: InferUsage, customerCost: number | undefined): ApiStreamUsageChunk { + return { + type: "usage", + // prompt_tokens includes the cache read and cache write tokens. + inputTokens: usage.prompt_tokens || 0, + outputTokens: usage.completion_tokens || 0, + cacheReadTokens: usage.prompt_tokens_details?.cached_tokens ?? undefined, + cacheWriteTokens: usage.prompt_tokens_details?.cache_write_tokens ?? undefined, + ...(typeof customerCost === "number" && Number.isFinite(customerCost) ? { totalCost: customerCost } : {}), + } +} + +/** + * Infer provider. + * + * OpenAI-compatible Chat Completions endpoint: + * https://infer.flow7.org/v1/chat/completions + * + * A model id selects a model and a route (`infer/:`). The routes are + * listed in the public catalog, which is fetched dynamically. Supports text + * generation, reasoning content, tool calls, and non-streaming prompt completion. + */ +export class InferHandler extends RouterProvider implements SingleCompletionHandler { + /** Creates a new handler bound to the user's API key and selected model. */ + constructor(options: ApiHandlerOptions) { + super({ + // The endpoint is fixed, so the custom headers configured for the + // OpenAI Compatible provider must not be sent to it. + options: { ...options, openAiHeaders: undefined }, + name: providerIdentifiers.infer, + baseURL: INFER_BASE_URL, + apiKey: options.inferApiKey, + modelId: options.inferModelId, + defaultModelId: inferDefaultModelId, + defaultModelInfo: inferDefaultModelInfo, + }) + } + + override getModelCacheScope(): ModelCacheScope { + // The public catalog is the same for every account and needs no key. + return { urlScoped: false, keyScoped: false, authScoped: false } + } + + async fetchModels(_options: GetModelsOptions, signal?: AbortSignal): Promise { + const fetchOpts: [] | [{ signal: AbortSignal }] = signal ? [{ signal }] : [] + return getInferModels(...fetchOpts) + } + + private createSafeError(operation: string, error: unknown): Error { + const apiKey = this.options.inferApiKey + const redact = (text: string) => (apiKey ? text.replaceAll(apiKey, "[REDACTED]") : text) + + // handleProviderError logs the message, stack and the SDK's raw error + // metadata before it applies the transformer, so the key has to be + // scrubbed from the error itself first. + if (error instanceof Error) { + error.message = redact(error.message) + if (error.stack) { + error.stack = redact(error.stack) + } + // handleProviderError calls string methods on this field, so an + // object-valued upstream body is serialized before it is redacted. + const metadata = (error as { error?: { metadata?: { raw?: unknown } } }).error?.metadata + if (metadata && metadata.raw !== undefined && metadata.raw !== null) { + const raw = metadata.raw + metadata.raw = redact(typeof raw === "string" ? raw : (JSON.stringify(raw) ?? String(raw))) + } + } + const safeError = error instanceof Error ? error : redact(String(error)) + + return handleProviderError(safeError, "Infer", { + messagePrefix: operation, + // The transformer input can also come from `error.error.metadata.raw`. + messageTransformer: (message) => `Infer ${operation} error: ${redact(message)}`, + }) + } + + /** A cleared temperature setting is stored as null, so only a number is sent. */ + private getTemperature(modelId: string, info: ModelInfo): number | undefined { + const temperature = this.options.modelTemperature + return typeof temperature === "number" && + info.supportsTemperature !== false && + this.supportsTemperature(modelId) + ? temperature + : undefined + } + + /** + * Streams a chat completion response, yielding typed chunks for text, + * reasoning, partial tool calls, and token usage. + */ + override async *createMessage( + systemPrompt: string, + messages: Anthropic.Messages.MessageParam[], + metadata?: ApiHandlerCreateMessageMetadata, + ): ApiStream { + // A cancelled task stops waiting for the catalog. The shared catalog fetch continues. + await this.ensureModelFetched(metadata?.abortSignal) + const { id: modelId, info } = this.getModel() + + const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [ + { role: "system", content: systemPrompt }, + ...convertToOpenAiMessages(messages), + ] + + // max_tokens is not sent. Infer holds the cost of the output cap from the wallet + // before a request starts. Without a cap, Infer sets one from the route's output + // room (32,768 tokens at most), so the full output limit of a large model is not held. + const body: OpenAI.Chat.ChatCompletionCreateParamsStreaming = { + model: modelId, + messages: openAiMessages, + stream: true, + stream_options: { include_usage: true }, + tools: this.convertToolsForOpenAI(metadata?.tools), + tool_choice: metadata?.tool_choice, + parallel_tool_calls: metadata?.parallelToolCalls ?? true, + } + + const temperature = this.getTemperature(modelId, info) + if (temperature !== undefined) { + body.temperature = temperature + } + + try { + const completion = await this.client.chat.completions.create(body, { + signal: metadata?.abortSignal, + // Infer keeps the requests of one session on the same route while it is + // healthy. This helps later requests in a task reuse the prompt cache of the route. + ...(metadata?.taskId ? { headers: { "X-Session-Affinity": metadata.taskId } } : {}), + }) + + for await (const chunk of completion) { + const delta = chunk.choices[0]?.delta + + // Infer streams reasoning text in `delta.reasoning`. + const reasoningText = extractReasoningFromDelta(delta) + if (reasoningText) { + yield { type: "reasoning", text: reasoningText } + } + + if (delta?.content) { + yield { type: "text", text: delta.content } + } + + // Emit raw tool call chunks - NativeToolCallParser handles state management. + if (delta?.tool_calls) { + for (const toolCall of delta.tool_calls) { + yield { + type: "tool_call_partial", + index: toolCall.index, + id: toolCall.id, + name: toolCall.function?.name, + arguments: toolCall.function?.arguments, + } + } + } + + if (chunk.usage) { + yield mapInferUsage(chunk.usage, (chunk as InferChunk).relay?.customer_cost_usd) + } + } + } catch (error) { + throw this.createSafeError("streaming", error) + } + } + + /** + * Performs a non-streaming chat completion and returns the full response text. + * + * @param prompt - The user prompt to send as a single user message. + * @returns The model's reply text, or an empty string if no content is returned. + * @throws Error with an Infer prefix if the request fails. + */ + async completePrompt(prompt: string, options?: CompletePromptOptions): Promise { + await this.ensureModelFetched(options?.abortSignal) + const { id: modelId, info } = this.getModel() + + try { + // max_tokens is not sent, for the same reason as in createMessage. + const requestOptions: OpenAI.Chat.ChatCompletionCreateParamsNonStreaming = { + model: modelId, + messages: [{ role: "user", content: prompt }], + stream: false, + } + + const temperature = this.getTemperature(modelId, info) + if (temperature !== undefined) { + requestOptions.temperature = temperature + } + + // The OpenAI SDK validates a present-but-undefined `timeout` key, so + // request options are only forwarded when they carry a real value. + const completionOptions: OpenAI.RequestOptions = {} + if (options?.abortSignal !== undefined) { + completionOptions.signal = options.abortSignal + } + const timeoutMs = options?.timeoutMs + if (hasUsableTimeout(timeoutMs)) { + completionOptions.timeout = toSdkTimeoutMs(timeoutMs) + } + const hasCompletionOptions = + completionOptions.signal !== undefined || completionOptions.timeout !== undefined + + const response = await this.client.chat.completions.create( + requestOptions, + hasCompletionOptions ? completionOptions : undefined, + ) + return response.choices[0]?.message.content || "" + } catch (error) { + throw this.createSafeError("completion", error) + } + } +} diff --git a/src/core/config/__tests__/ContextProxy.spec.ts b/src/core/config/__tests__/ContextProxy.spec.ts index 4766f87112f..93143b46719 100644 --- a/src/core/config/__tests__/ContextProxy.spec.ts +++ b/src/core/config/__tests__/ContextProxy.spec.ts @@ -739,6 +739,22 @@ describe("ContextProxy", () => { }) describe("setProviderSettings", () => { + it("stores and returns the complete Infer configuration across secret and global state", async () => { + await proxy.setProviderSettings({ + apiProvider: providerIdentifiers.infer, + inferApiKey: "infer-secret", + inferModelId: "infer/claude-opus-5-5:low-cost", + }) + + expect(mockSecrets.store).toHaveBeenCalledWith("inferApiKey", "infer-secret") + expect(mockGlobalState.update).toHaveBeenCalledWith("inferModelId", "infer/claude-opus-5-5:low-cost") + expect(proxy.getProviderSettings()).toMatchObject({ + apiProvider: providerIdentifiers.infer, + inferApiKey: "infer-secret", + inferModelId: "infer/claude-opus-5-5:low-cost", + }) + }) + it("stores and returns the complete NanoGPT configuration across secret and global state", async () => { await proxy.setProviderSettings({ apiProvider: providerIdentifiers.nanogpt, diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index b364b5baa79..ec571a93e7c 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -7312,6 +7312,7 @@ describe("ClineProvider - Router Models", () => { moonshot: {}, "opencode-go": mockModels, kenari: mockModels, + infer: {}, nanogpt: mockModels, "kimi-code": {}, friendli: mockModels, @@ -7370,6 +7371,7 @@ describe("ClineProvider - Router Models", () => { moonshot: {}, "opencode-go": mockModels, kenari: mockModels, + infer: {}, nanogpt: mockModels, "kimi-code": {}, friendli: mockModels, @@ -7476,6 +7478,7 @@ describe("ClineProvider - Router Models", () => { moonshot: {}, "opencode-go": mockModels, kenari: mockModels, + infer: {}, nanogpt: mockModels, "kimi-code": {}, friendli: mockModels, diff --git a/src/core/webview/__tests__/webviewMessageHandler.routerModels.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.routerModels.spec.ts index b7da723414f..1c915462b3f 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.routerModels.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.routerModels.spec.ts @@ -134,6 +134,8 @@ describe("webviewMessageHandler - requestRouterModels provider filter", () => { return { "requesty/model": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.vercelAiGateway: return { "vercel/model": { contextWindow: 8192, supportsPromptCache: false } } + case providerIdentifiers.infer: + return { "infer/model:low-cost": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.litellm: return { "litellm/model": { contextWindow: 8192, supportsPromptCache: false } } default: @@ -204,6 +206,8 @@ describe("webviewMessageHandler - requestRouterModels provider filter", () => { return { "requesty/model": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.vercelAiGateway: return { "vercel/model": { contextWindow: 8192, supportsPromptCache: false } } + case providerIdentifiers.infer: + return { "infer/model:low-cost": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.litellm: return { "litellm/model": { contextWindow: 8192, supportsPromptCache: false } } default: @@ -255,6 +259,8 @@ describe("webviewMessageHandler - requestRouterModels provider filter", () => { return { "requesty/model": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.vercelAiGateway: return { "vercel/model": { contextWindow: 8192, supportsPromptCache: false } } + case providerIdentifiers.infer: + return { "infer/model:low-cost": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.litellm: return { "litellm/model": { contextWindow: 8192, supportsPromptCache: false } } default: @@ -307,6 +313,55 @@ describe("webviewMessageHandler - requestRouterModels provider filter", () => { expect(getModelsMock.mock.calls[0][1]).toBe(handlerForProvider(providerIdentifiers.openrouter)) }) + it("filters to Infer and fetches its public catalog without the stored key", async () => { + mockProvider.getState.mockResolvedValue({ apiConfiguration: { inferApiKey: "stored-infer-key" } }) + + await webviewMessageHandler(mockProvider, { + type: RouterModelsMessageType.requestRouterModels, + values: { provider: providerIdentifiers.infer }, + }) + + // The catalog is the same for every key, so the stored key is never sent with it. + expect(getModelsMock).toHaveBeenCalledTimes(1) + expect(getModelsMock.mock.calls[0][0]).toStrictEqual({ provider: providerIdentifiers.infer }) + expect(getModelsMock.mock.calls[0][1]).toBe(handlerForProvider(providerIdentifiers.infer)) + expect(flushModelsMock).not.toHaveBeenCalled() + + const response = mockProvider.postMessageToWebview.mock.calls.find( + (call) => call[0]?.type === RouterModelsMessageType.routerModels, + ) + if (!response) throw new Error("Expected routerModels response") + expect(response[0].routerModels).toEqual({ + [providerIdentifiers.infer]: { + "infer/model:low-cost": { contextWindow: 8192, supportsPromptCache: false }, + }, + }) + }) + + it.each([ + ["uses Infer", { apiProvider: providerIdentifiers.infer, inferApiKey: "stored-infer-key" }, true], + [ + "uses another provider", + { apiProvider: providerIdentifiers.anthropic, inferApiKey: "stored-infer-key" }, + false, + ], + ] as const)( + "fetches Infer's catalog in an aggregate request only when the profile %s", + async (_label, apiConfiguration, fetched) => { + mockProvider.getState.mockResolvedValue({ apiConfiguration }) + + await webviewMessageHandler(mockProvider, { type: RouterModelsMessageType.requestRouterModels }) + + // A Zoo Code install that does not use Infer must not contact it. + const inferCalls = getModelsMock.mock.calls.filter( + ([options]) => options?.provider === providerIdentifiers.infer, + ) + expect(inferCalls.map(([options]) => options)).toStrictEqual( + fetched ? [{ provider: providerIdentifiers.infer }] : [], + ) + }, + ) + it("filters to Kimi Code and dispatches an explicit API key without reading the OAuth token", async () => { const kimiModels = { "kimi-for-coding": { contextWindow: 262_144, supportsPromptCache: true } } getModelsMock.mockResolvedValue(kimiModels) @@ -525,6 +580,8 @@ describe("webviewMessageHandler - requestRouterModels provider filter", () => { return { "requesty/model": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.vercelAiGateway: return { "vercel/model": { contextWindow: 8192, supportsPromptCache: false } } + case providerIdentifiers.infer: + return { "infer/model:low-cost": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.litellm: return { "litellm/model": { contextWindow: 8192, supportsPromptCache: false } } default: @@ -615,6 +672,8 @@ describe("webviewMessageHandler - requestRouterModels provider filter", () => { return { "requesty/model": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.vercelAiGateway: return { "vercel/model": { contextWindow: 8192, supportsPromptCache: false } } + case providerIdentifiers.infer: + return { "infer/model:low-cost": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.litellm: return { "litellm/model": { contextWindow: 8192, supportsPromptCache: false } } default: @@ -666,6 +725,8 @@ describe("webviewMessageHandler - requestRouterModels provider filter", () => { return { "requesty/model": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.vercelAiGateway: return { "vercel/model": { contextWindow: 8192, supportsPromptCache: false } } + case providerIdentifiers.infer: + return { "infer/model:low-cost": { contextWindow: 8192, supportsPromptCache: false } } case providerIdentifiers.litellm: return { "litellm/model": { contextWindow: 8192, supportsPromptCache: false } } default: diff --git a/src/core/webview/__tests__/webviewMessageHandler.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.spec.ts index e1cc7dc8445..2deb71566fb 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.spec.ts @@ -1186,6 +1186,11 @@ describe("webviewMessageHandler - requestRouterModels", () => { expect.objectContaining({ provider: providerIdentifiers.kenari }), expect.anything(), ) + // Infer's catalog is fetched only for Infer, so an aggregate request for another profile skips it. + expect(mockGetModels).not.toHaveBeenCalledWith( + expect.objectContaining({ provider: providerIdentifiers.infer }), + expect.anything(), + ) // NanoGPT's detailed catalog is public and may optionally be scoped by a key. expect(mockGetModels).toHaveBeenCalledWith( { provider: providerIdentifiers.nanogpt, apiKey: undefined }, @@ -1209,6 +1214,7 @@ describe("webviewMessageHandler - requestRouterModels", () => { moonshot: {}, "opencode-go": mockModels, kenari: mockModels, + infer: {}, nanogpt: mockModels, "kimi-code": {}, friendli: mockModels, @@ -1508,6 +1514,7 @@ describe("webviewMessageHandler - requestRouterModels", () => { moonshot: {}, "opencode-go": mockModels, kenari: mockModels, + infer: {}, nanogpt: mockModels, "kimi-code": {}, friendli: mockModels, @@ -1574,6 +1581,7 @@ describe("webviewMessageHandler - requestRouterModels", () => { moonshot: {}, "opencode-go": mockModels, kenari: mockModels, + infer: {}, nanogpt: mockModels, "kimi-code": {}, friendli: mockModels, diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 6641ff259f1..6bbdd6573d8 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -1222,6 +1222,7 @@ export const webviewMessageHandler = async ( [providerIdentifiers.moonshot]: {}, [providerIdentifiers.opencodeGo]: {}, [providerIdentifiers.kenari]: {}, + [providerIdentifiers.infer]: {}, [providerIdentifiers.nanogpt]: {}, [providerIdentifiers.kimiCode]: {}, [providerIdentifiers.friendli]: {}, @@ -1405,6 +1406,16 @@ export const webviewMessageHandler = async ( options: { provider: providerIdentifiers.kenari, apiKey: kenariApiKey }, }) + // Infer's catalog is public and the same for every key, so no key is sent. It is + // fetched only for a request that names Infer or for a profile that uses Infer, so + // an aggregate request from another profile does not contact Infer. + if ( + providerFilter === providerIdentifiers.infer || + apiConfiguration.apiProvider === providerIdentifiers.infer + ) { + candidates.push({ key: providerIdentifiers.infer, options: { provider: providerIdentifiers.infer } }) + } + // NanoGPT's detailed catalog is public, while an optional key can expose a // different allowlist. Prefer an explicitly supplied unsaved key and use the // same key-scoped options for refresh and retrieval. diff --git a/src/shared/__tests__/ProfileValidator.spec.ts b/src/shared/__tests__/ProfileValidator.spec.ts index d9b4c4c5d8a..b1a4644b2ca 100644 --- a/src/shared/__tests__/ProfileValidator.spec.ts +++ b/src/shared/__tests__/ProfileValidator.spec.ts @@ -31,6 +31,7 @@ describe("ProfileValidator", () => { ["ollama", { ollamaModelId: "model" }], ["requesty", { requestyModelId: "model" }], ["unbound", { unboundModelId: "model" }], + ["infer", { inferModelId: "model" }], ["poe", { apiModelId: "model" }], ["moonshot", { apiModelId: "model" }], ["kimiCode", { apiModelId: "model" }], @@ -300,6 +301,25 @@ describe("ProfileValidator", () => { expect(ProfileValidator.isProfileAllowed(profile, allowList)).toBe(true) }) + // Test for infer provider which uses inferModelId + it(`should extract inferModelId for infer provider`, () => { + const allowList: OrganizationAllowList = { + allowAll: false, + providers: { + [providerIdentifiers.infer]: { allowAll: false, models: ["infer/test-model:stable"] }, + }, + } + const profile: ProviderSettings = { + apiProvider: providerIdentifiers.infer, + inferModelId: "infer/test-model:stable", + } + + expect(ProfileValidator.isProfileAllowed(profile, allowList)).toBe(true) + expect( + ProfileValidator.isProfileAllowed({ ...profile, inferModelId: "infer/test-model:official" }, allowList), + ).toBe(false) + }) + it("should extract vsCodeLmModelSelector.id for vscode-lm provider", () => { const allowList: OrganizationAllowList = { allowAll: false, diff --git a/src/shared/api.ts b/src/shared/api.ts index d65ee30aced..28a795dfbcd 100644 --- a/src/shared/api.ts +++ b/src/shared/api.ts @@ -184,6 +184,7 @@ const _dynamicProviderExtras = { [providerIdentifiers.moonshot]: {} as { apiKey?: string; baseUrl?: string }, [providerIdentifiers.opencodeGo]: {} as { apiKey?: string }, [providerIdentifiers.kenari]: {} as { apiKey?: string }, + [providerIdentifiers.infer]: {} as object, [providerIdentifiers.nanogpt]: {} as { apiKey?: string }, [providerIdentifiers.kimiCode]: {} as { apiKey?: string }, [providerIdentifiers.friendli]: {} as object, diff --git a/webview-ui/playwright/gallery/stories.tsx b/webview-ui/playwright/gallery/stories.tsx index 9dca3490895..fe53a3e8d37 100644 --- a/webview-ui/playwright/gallery/stories.tsx +++ b/webview-ui/playwright/gallery/stories.tsx @@ -320,6 +320,39 @@ export const stories: Record = { ) }, + "infer-settings": async () => { + const [{ AppProviders }, { Infer }, { providerIdentifiers }] = await Promise.all([ + import("../AppProviders"), + import("@/components/settings/providers/Infer"), + import("@roo-code/types"), + ]) + type ProviderSettings = React.ComponentProps["apiConfiguration"] + + function InferSettingsStory() { + const [apiConfiguration, setApiConfiguration] = useState({ + apiProvider: providerIdentifiers.infer, + }) + return ( +
+
+ + setApiConfiguration((current) => ({ ...current, [field]: value })) + } + organizationAllowList={{ allowAll: true, providers: {} }} + /> +
+
+ ) + } + + return ( + + + + ) + }, "layout-clipped-text": () => (
diff --git a/webview-ui/src/components/settings/ApiOptions.tsx b/webview-ui/src/components/settings/ApiOptions.tsx index aff93a377ba..fcd5c0f5d41 100644 --- a/webview-ui/src/components/settings/ApiOptions.tsx +++ b/webview-ui/src/components/settings/ApiOptions.tsx @@ -86,6 +86,7 @@ import { VercelAiGateway, OpenCodeGo, Kenari, + Infer, NanoGPT, ZooGateway, MiniMax, @@ -715,6 +716,17 @@ const ApiOptions = ({ /> )} + {selectedProvider === providerIdentifiers.infer && ( + + )} + {selectedProvider === providerIdentifiers.nanogpt && ( { VercelAiGateway: provider("provider-vercel-ai-gateway"), OpenCodeGo: provider("provider-opencode-go"), Kenari: provider("provider-kenari"), + Infer: provider("provider-infer"), NanoGPT: provider("provider-nanogpt"), ZooGateway: provider("provider-zoo-gateway"), MiniMax: provider("provider-minimax"), @@ -403,6 +404,7 @@ describe("ApiOptions interactions", () => { providerIdentifiers.vercelAiGateway, providerIdentifiers.opencodeGo, providerIdentifiers.kenari, + providerIdentifiers.infer, providerIdentifiers.nanogpt, providerIdentifiers.zooGateway, providerIdentifiers.fireworks, diff --git a/webview-ui/src/components/settings/__tests__/ApiOptions.provider-filtering.spec.tsx b/webview-ui/src/components/settings/__tests__/ApiOptions.provider-filtering.spec.tsx index 90f62f5fee5..d8b126299ac 100644 --- a/webview-ui/src/components/settings/__tests__/ApiOptions.provider-filtering.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/ApiOptions.provider-filtering.spec.tsx @@ -292,6 +292,7 @@ describe("ApiOptions Provider Filtering", () => { expect(providerValues).toContain("ollama") expect(providerValues).toContain("lmstudio") expect(providerValues).toContain("litellm") + expect(providerValues).toContain("infer") expect(providerValues).toContain("requesty") }) diff --git a/webview-ui/src/components/settings/__tests__/ApiOptions.spec.tsx b/webview-ui/src/components/settings/__tests__/ApiOptions.spec.tsx index f9d55fc4699..c5b8f135be7 100644 --- a/webview-ui/src/components/settings/__tests__/ApiOptions.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/ApiOptions.spec.tsx @@ -4,7 +4,12 @@ import { retiredProviderIdentifiers, providerIdentifiers } from "@roo-code/types import { renderWithExtensionState, screen, fireEvent, within } from "@/utils/test-utils" import { type ModelInfo, type ProviderSettings, openAiModelInfoSaneDefaults } from "@roo-code/types" -import { openAiCodexDefaultModelId, opencodeGoModels, zooGatewayDefaultModelId } from "@roo-code/types" +import { + inferDefaultModelId, + openAiCodexDefaultModelId, + opencodeGoModels, + zooGatewayDefaultModelId, +} from "@roo-code/types" import { useSelectedModel } from "@src/components/ui/hooks/useSelectedModel" @@ -365,6 +370,25 @@ describe("ApiOptions", () => { expect(mockSetApiConfigurationField).toHaveBeenCalledWith("zooGatewayModelId", zooGatewayDefaultModelId, false) }) + it.each([ + { stored: undefined, expected: inferDefaultModelId }, + { stored: "infer/claude-opus-5-5:official", expected: undefined }, + ])("stores the default Infer route on switch only when none is stored ($stored)", ({ stored, expected }) => { + const mockSetApiConfigurationField = vi.fn() + + renderApiOptions({ + apiConfiguration: { apiProvider: providerIdentifiers.anthropic, inferApiKey: "key", inferModelId: stored }, + setApiConfigurationField: mockSetApiConfigurationField, + }) + + const providerSelect = screen.getByTestId("provider-select").querySelector("select") as HTMLSelectElement + fireEvent.change(providerSelect, { target: { value: providerIdentifiers.infer } }) + + expect(mockSetApiConfigurationField).toHaveBeenCalledWith("apiProvider", providerIdentifiers.infer) + const modelIdWrites = mockSetApiConfigurationField.mock.calls.filter(([field]) => field === "inferModelId") + expect(modelIdWrites).toEqual(expected === undefined ? [] : [["inferModelId", expected, false]]) + }) + it("renders the Friendli provider form when friendli is selected", () => { renderApiOptions({ apiConfiguration: { @@ -517,6 +541,7 @@ describe("ApiOptions", () => { expect(optionTexts).toContain("OpenAI") expect(optionTexts).toContain("Anthropic") expect(optionTexts).toContain("NanoGPT") + expect(optionTexts).toContain("Infer") // Note: The mock doesn't implement search functionality, so we're just verifying // that the select element is rendered with the expected options diff --git a/webview-ui/src/components/settings/__tests__/ModelPicker.spec.tsx b/webview-ui/src/components/settings/__tests__/ModelPicker.spec.tsx index 2dce9555e99..9e766d68a9f 100644 --- a/webview-ui/src/components/settings/__tests__/ModelPicker.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/ModelPicker.spec.tsx @@ -7,6 +7,7 @@ import { type Mock } from "vitest" import { bedrockDefaultModelId, + inferDefaultModelId, litellmDefaultModelId, type ModelInfo, type ProviderSettings, @@ -371,6 +372,43 @@ describe("ModelPicker", () => { }) }) + describe("Infer route selection", () => { + const inferModels: Record = { + "infer/test-model:low-cost": { displayName: "test-model (Low cost)", ...modelInfo }, + "infer/test-model:official": { displayName: "test-model (Official)", ...modelInfo }, + } + + beforeEach(() => { + mockUseRouterModels.mockReturnValue(createRouterModelsResult({ [providerIdentifiers.infer]: inferModels })) + }) + + it("keeps a stored route that the catalog no longer lists instead of reverting to the default", async () => { + // A route can leave the catalog for a while. Requests still use the stored + // selector, so the picker must keep displaying it. + const storedRoute = "infer/test-model:balanced" + const setField = vi.fn() + + await act(async () => { + renderWithExtensionState( + , + { queryClient }, + ) + }) + + expect(screen.getByTestId("model-picker-button")).toHaveTextContent(storedRoute) + expect(setField).not.toHaveBeenCalledWith("inferModelId", inferDefaultModelId, false) + }) + }) + describe("Bedrock pasted ARN", () => { const appProfileArn = "arn:aws:bedrock:us-west-2:123456789012:application-inference-profile/abcd1234efgh" const bedrockModels = getStaticModelsForProvider(providerIdentifiers.bedrock) diff --git a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx index 758161c1488..a31d3f9861d 100644 --- a/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/SettingsView.unsaved-changes.spec.tsx @@ -757,4 +757,85 @@ describe("SettingsView - Unsaved Changes Detection", () => { expect(onDone).toHaveBeenCalledOnce() expect(postMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "upsertApiConfiguration" })) }) + + it("buffers and saves the complete Infer provider configuration from cached state", async () => { + const liveApiConfiguration = { + apiProvider: providerIdentifiers.infer, + inferApiKey: "original-key", + inferModelId: "infer/original:low-cost", + } + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + apiConfiguration: liveApiConfiguration, + }) + vi.mocked(ApiOptions).mockImplementation(({ apiConfiguration, setApiConfigurationField }) => ( +
+ setApiConfigurationField("inferApiKey", event.target.value)} + /> + setApiConfigurationField("inferModelId", event.target.value)} + /> +
+ )) + + renderWithExtensionState(, { queryClient }) + + expect(await screen.findByTestId("cached-infer-key")).toHaveValue("original-key") + expect(screen.getByTestId("cached-infer-model")).toHaveValue("infer/original:low-cost") + + fireEvent.change(screen.getByTestId("cached-infer-key"), { target: { value: "unsaved-key" } }) + fireEvent.change(screen.getByTestId("cached-infer-model"), { target: { value: "infer/next:official" } }) + + expect(liveApiConfiguration).toEqual({ + apiProvider: providerIdentifiers.infer, + inferApiKey: "original-key", + inferModelId: "infer/original:low-cost", + }) + expect(postMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "upsertApiConfiguration" })) + + fireEvent.click(screen.getByTestId("save-button")) + + expect(postMessage).toHaveBeenCalledWith({ + type: "upsertApiConfiguration", + text: "default", + apiConfiguration: { + apiProvider: providerIdentifiers.infer, + inferApiKey: "unsaved-key", + inferModelId: "infer/next:official", + }, + }) + }) + + it("discards Infer cached edits and restores the extension values", async () => { + const onDone = vi.fn() + ;(useExtensionState as ReturnType).mockReturnValue({ + ...defaultExtensionState, + apiConfiguration: { + apiProvider: providerIdentifiers.infer, + inferApiKey: "saved-key", + inferModelId: "infer/saved:stable", + }, + }) + vi.mocked(ApiOptions).mockImplementation(({ apiConfiguration, setApiConfigurationField }) => ( + setApiConfigurationField("inferApiKey", event.target.value)} + /> + )) + + renderWithExtensionState(, { queryClient }) + fireEvent.change(await screen.findByTestId("cached-infer-key"), { target: { value: "discard-me" } }) + fireEvent.click(screen.getByText("settings:common.done")) + fireEvent.click(await screen.findByText("settings:unsavedChangesDialog.discardButton")) + + await waitFor(() => expect(screen.getByTestId("cached-infer-key")).toHaveValue("saved-key")) + expect(onDone).toHaveBeenCalledOnce() + expect(postMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "upsertApiConfiguration" })) + }) }) diff --git a/webview-ui/src/components/settings/__tests__/ThinkingBudget.spec.tsx b/webview-ui/src/components/settings/__tests__/ThinkingBudget.spec.tsx index 26fec820f2b..b60288ffba3 100644 --- a/webview-ui/src/components/settings/__tests__/ThinkingBudget.spec.tsx +++ b/webview-ui/src/components/settings/__tests__/ThinkingBudget.spec.tsx @@ -1,4 +1,4 @@ -import { bedrockModels, providerIdentifiers } from "@roo-code/types" +import { bedrockModels, inferDefaultModelInfo, providerIdentifiers } from "@roo-code/types" // npx vitest src/components/settings/__tests__/ThinkingBudget.spec.tsx import React from "react" @@ -755,4 +755,35 @@ describe("ThinkingBudget", () => { expect(screen.getByTestId("reasoning-effort")).toBeInTheDocument() }) }) + + // Infer sends no reasoning parameters, so its routes must not offer a reasoning control. + it.each([ + ["the fallback", inferDefaultModelInfo], + [ + "a catalog route", + { + contextWindow: 1_000_000, + maxTokens: 128_000, + supportsImages: false, + supportsPromptCache: true, + inputPrice: 1.97, + outputPrice: 9.81, + displayName: "claude-opus-5-5 (Low cost)", + }, + ], + ])("renders no reasoning control for Infer with %s model info", (_label, modelInfo) => { + const { container } = render( + , + ) + + expect(container).toBeEmptyDOMElement() + }) }) diff --git a/webview-ui/src/components/settings/constants.ts b/webview-ui/src/components/settings/constants.ts index 468010ef6b2..52a33572df9 100644 --- a/webview-ui/src/components/settings/constants.ts +++ b/webview-ui/src/components/settings/constants.ts @@ -71,6 +71,7 @@ export const PROVIDERS: Array<{ value: string; label: string; proxy: boolean }> { value: providerIdentifiers.vercelAiGateway, label: "Vercel AI Gateway", proxy: false }, { value: providerIdentifiers.opencodeGo, label: "Opencode Go", proxy: false }, { value: providerIdentifiers.kenari, label: "Kenari", proxy: false }, + { value: providerIdentifiers.infer, label: "Infer", proxy: false }, { value: providerIdentifiers.nanogpt, label: "NanoGPT", proxy: false }, { value: providerIdentifiers.zooGateway, label: "Zoo Gateway", proxy: false }, { value: providerIdentifiers.minimax, label: "MiniMax", proxy: false }, diff --git a/webview-ui/src/components/settings/providers/Infer.tsx b/webview-ui/src/components/settings/providers/Infer.tsx new file mode 100644 index 00000000000..e1ee5ff9334 --- /dev/null +++ b/webview-ui/src/components/settings/providers/Infer.tsx @@ -0,0 +1,84 @@ +import { useCallback } from "react" +import { VSCodeTextField } from "@vscode/webview-ui-toolkit/react" + +import { + type OrganizationAllowList, + type ProviderSettings, + type RouterModels, + inferDefaultModelId, + providerIdentifiers, +} from "@roo-code/types" + +import { VSCodeButtonLink } from "@src/components/common/VSCodeButtonLink" +import { useAppTranslation } from "@src/i18n/TranslationContext" + +import { ModelPicker } from "../ModelPicker" +import { inputEventTransform } from "../transforms" + +type InferProps = { + apiConfiguration: ProviderSettings + setApiConfigurationField: (field: K, value: ProviderSettings[K]) => void + routerModels?: RouterModels + organizationAllowList: OrganizationAllowList + modelValidationError?: string + simplifySettings?: boolean +} + +// The model list comes from Infer's public catalog. The catalog is the same for every +// key, so editing the key does not request a new model list. +export const Infer = ({ + apiConfiguration, + setApiConfigurationField, + routerModels, + organizationAllowList, + modelValidationError, + simplifySettings, +}: InferProps) => { + const { t } = useAppTranslation() + + const handleInputChange = useCallback( + ( + field: K, + transform: (event: E) => ProviderSettings[K] = inputEventTransform, + ) => + (event: E | Event) => { + setApiConfigurationField(field, transform(event as E)) + }, + [setApiConfigurationField], + ) + + return ( + <> + + + +
+ {t("settings:providers.apiKeyStorageNotice")} +
+ {!apiConfiguration.inferApiKey && ( + + {t("settings:providers.infer.getApiKey")} + + )} + + + + ) +} diff --git a/webview-ui/src/components/settings/providers/__tests__/Infer.spec.tsx b/webview-ui/src/components/settings/providers/__tests__/Infer.spec.tsx new file mode 100644 index 00000000000..4a1057f526e --- /dev/null +++ b/webview-ui/src/components/settings/providers/__tests__/Infer.spec.tsx @@ -0,0 +1,137 @@ +import { fireEvent, render, screen } from "@testing-library/react" + +import { + type ModelRecord, + type OrganizationAllowList, + type ProviderSettings, + type RouterModels, + inferDefaultModelId, + providerIdentifiers, +} from "@roo-code/types" + +import { Infer } from "../Infer" + +const { postMessageMock } = vi.hoisted(() => ({ postMessageMock: vi.fn() })) + +vi.mock("@src/utils/vscode", () => ({ vscode: { postMessage: postMessageMock } })) + +vi.mock("@src/i18n/TranslationContext", () => ({ + useAppTranslation: () => ({ t: (key: string) => key }), +})) + +vi.mock("@vscode/webview-ui-toolkit/react", () => ({ + VSCodeTextField: ({ + children, + value, + onInput, + type, + }: React.ComponentProps<"input"> & { children: React.ReactNode }) => ( +
+ {children} + +
+ ), +})) + +vi.mock("@src/components/common/VSCodeButtonLink", () => ({ + VSCodeButtonLink: ({ children, href }: React.ComponentProps<"a">) => ( + + {children} + + ), +})) + +vi.mock("../../ModelPicker", () => ({ + ModelPicker: ({ + defaultModelId, + models, + modelIdKey, + serviceName, + serviceUrl, + }: { + defaultModelId: string + models: object + modelIdKey: string + serviceName: string + serviceUrl: string + }) => ( +
+ ), +})) + +describe("Infer", () => { + const organizationAllowList: OrganizationAllowList = { allowAll: true, providers: {} } + const setApiConfigurationField = vi.fn() + const inferModels: ModelRecord = { + "infer/test-model:low-cost": { contextWindow: 1_000_000, maxTokens: 128_000, supportsPromptCache: true }, + "infer/test-model:official": { contextWindow: 1_000_000, maxTokens: 128_000, supportsPromptCache: true }, + } + // The component reads only its own catalog, so the other router entries are left out. + const routerModels = { [providerIdentifiers.infer]: inferModels } as RouterModels + + const renderComponent = (apiConfiguration: ProviderSettings = {}) => + render( + , + ) + + beforeEach(() => vi.clearAllMocks()) + + it("renders the secret key input, the storage notice, and the catalog model picker", () => { + renderComponent({ inferApiKey: "stored" }) + + expect(screen.getByTestId("infer-api-key")).toHaveAttribute("type", "password") + expect(screen.getByText("settings:providers.infer.apiKey")).toBeInTheDocument() + expect(screen.getByText("settings:providers.apiKeyStorageNotice")).toBeInTheDocument() + expect(screen.queryByTestId("infer-get-key")).not.toBeInTheDocument() + + const picker = screen.getByTestId("model-picker") + expect(picker).toHaveAttribute("data-default-model-id", inferDefaultModelId) + expect(picker).toHaveAttribute("data-model-id-key", "inferModelId") + expect(picker).toHaveAttribute("data-model-count", "2") + expect(picker).toHaveAttribute("data-service-name", "settings:providers.infer.provider") + expect(picker).toHaveAttribute("data-service-url", "https://infer.flow7.org/models") + }) + + it("shows the get-key link to the API keys page only when no key is configured", () => { + renderComponent({}) + + expect(screen.getByTestId("infer-get-key")).toHaveAttribute("href", "https://infer.flow7.org/app#/keys") + expect(screen.getByText("settings:providers.infer.getApiKey")).toBeInTheDocument() + }) + + it("updates the cached key with exact values", () => { + renderComponent({ inferApiKey: "" }) + + fireEvent.input(screen.getByTestId("infer-api-key"), { target: { value: "new-secret" } }) + + expect(setApiConfigurationField).toHaveBeenCalledWith("inferApiKey", "new-secret") + }) + + it("does not request a new model list when the key changes", () => { + // The public catalog is the same for every key, so a key edit has nothing to refresh. + const { rerender } = renderComponent({ inferApiKey: "first-key" }) + + rerender( + , + ) + + expect(postMessageMock).not.toHaveBeenCalled() + }) +}) diff --git a/webview-ui/src/components/settings/providers/__tests__/Infer.visual.tsx b/webview-ui/src/components/settings/providers/__tests__/Infer.visual.tsx new file mode 100644 index 00000000000..9a6a507fef6 --- /dev/null +++ b/webview-ui/src/components/settings/providers/__tests__/Infer.visual.tsx @@ -0,0 +1,10 @@ +import { expect, test } from "../../../../../playwright/coverage-fixture" +import { mountedStory } from "../../../../../playwright/mounted-story" + +test("renders the Infer settings for an unconfigured profile", async ({ mount, page }) => { + await page.setViewportSize({ width: 480, height: 480 }) + const component = mountedStory(await mount("infer-settings")) + const story = component.getByTestId("infer-settings-story") + + await expect(story).toHaveScreenshot("infer-settings.png") +}) diff --git a/webview-ui/src/components/settings/providers/__tests__/NanoGPT.spec.tsx b/webview-ui/src/components/settings/providers/__tests__/NanoGPT.spec.tsx index bdc76a0addd..67429bfd84b 100644 --- a/webview-ui/src/components/settings/providers/__tests__/NanoGPT.spec.tsx +++ b/webview-ui/src/components/settings/providers/__tests__/NanoGPT.spec.tsx @@ -103,6 +103,7 @@ describe("NanoGPT", () => { "opencode-go": {}, kenari: {}, nanogpt: { "openai/test": { contextWindow: 1, maxTokens: 1, supportsPromptCache: false } }, + infer: {}, "kimi-code": {}, friendli: {}, ollama: {}, diff --git a/webview-ui/src/components/settings/providers/__tests__/__screenshots__/infer-settings.png b/webview-ui/src/components/settings/providers/__tests__/__screenshots__/infer-settings.png new file mode 100644 index 00000000000..1efdd115be5 Binary files /dev/null and b/webview-ui/src/components/settings/providers/__tests__/__screenshots__/infer-settings.png differ diff --git a/webview-ui/src/components/settings/providers/index.ts b/webview-ui/src/components/settings/providers/index.ts index 12ea4cd7861..b0aa1ba7144 100644 --- a/webview-ui/src/components/settings/providers/index.ts +++ b/webview-ui/src/components/settings/providers/index.ts @@ -26,6 +26,7 @@ export { Friendli } from "./Friendli" export { VercelAiGateway } from "./VercelAiGateway" export { OpenCodeGo } from "./OpenCodeGo" export { Kenari } from "./Kenari" +export { Infer } from "./Infer" export { NanoGPT } from "./NanoGPT" export { ZooGateway } from "./ZooGateway" export { MiniMax } from "./MiniMax" diff --git a/webview-ui/src/components/settings/utils/__tests__/providerModelConfig.spec.ts b/webview-ui/src/components/settings/utils/__tests__/providerModelConfig.spec.ts index 5ee319ada19..227d5223ad5 100644 --- a/webview-ui/src/components/settings/utils/__tests__/providerModelConfig.spec.ts +++ b/webview-ui/src/components/settings/utils/__tests__/providerModelConfig.spec.ts @@ -2,6 +2,7 @@ import { type RouterModels, anthropicDefaultModelId, friendliModels, + inferDefaultModelId, mainlandZAiDefaultModelId, nanoGptDefaultModelId, providerIdentifiers, @@ -186,6 +187,13 @@ describe("providerModelConfig", () => { default: nanoGptDefaultModelId, }) }) + + it("returns Infer's dynamic model field and fallback", () => { + expect(getProviderModelConfig(providerIdentifiers.infer)).toEqual({ + field: "inferModelId", + default: inferDefaultModelId, + }) + }) }) describe("getProviderDocsSlug", () => { diff --git a/webview-ui/src/components/settings/utils/providerModelConfig.ts b/webview-ui/src/components/settings/utils/providerModelConfig.ts index c70a36a90dc..0f4bb00c13f 100644 --- a/webview-ui/src/components/settings/utils/providerModelConfig.ts +++ b/webview-ui/src/components/settings/utils/providerModelConfig.ts @@ -28,6 +28,7 @@ import { vercelAiGatewayDefaultModelId, opencodeGoDefaultModelId, kenariDefaultModelId, + inferDefaultModelId, nanoGptDefaultModelId, zooGatewayDefaultModelId, getZAiModels, @@ -143,6 +144,7 @@ const PROVIDER_MODEL_CONFIG: Partial> }, [providerIdentifiers.opencodeGo]: { field: "opencodeGoModelId", default: opencodeGoDefaultModelId }, [providerIdentifiers.kenari]: { field: "kenariModelId", default: kenariDefaultModelId }, + [providerIdentifiers.infer]: { field: "inferModelId", default: inferDefaultModelId }, [providerIdentifiers.nanogpt]: { field: "nanoGptModelId", default: nanoGptDefaultModelId }, [providerIdentifiers.zooGateway]: { field: "zooGatewayModelId", default: zooGatewayDefaultModelId }, [providerIdentifiers.openai]: { field: "openAiModelId" }, diff --git a/webview-ui/src/components/ui/hooks/__tests__/useSelectedModel.spec.ts b/webview-ui/src/components/ui/hooks/__tests__/useSelectedModel.spec.ts index 619664b7c6c..b8e067cd27a 100644 --- a/webview-ui/src/components/ui/hooks/__tests__/useSelectedModel.spec.ts +++ b/webview-ui/src/components/ui/hooks/__tests__/useSelectedModel.spec.ts @@ -18,6 +18,8 @@ import { BEDROCK_MAX_TOKENS, bedrockModels, litellmDefaultModelInfo, + inferDefaultModelId, + inferDefaultModelInfo, kenariDefaultModelId, kenariDefaultModelInfo, nanoGptDefaultModelId, @@ -1290,6 +1292,98 @@ describe("useSelectedModel", () => { }) }) + describe("infer provider", () => { + beforeEach(() => { + mockUseOpenRouterModelProviders.mockReturnValue(createOpenRouterModelProvidersResult({})) + }) + + it("uses the catalog metadata of the configured Infer route", () => { + const routeInfo: ModelInfo = { + maxTokens: 128_000, + contextWindow: 1_000_000, + supportsImages: true, + supportsPromptCache: true, + inputPrice: 5, + outputPrice: 25, + displayName: "test-model (Official)", + } + mockUseRouterModels.mockReturnValue( + createRouterModelsResult({ [providerIdentifiers.infer]: { "infer/test-model:official": routeInfo } }), + ) + + const { result } = renderHook( + () => + useSelectedModel({ + apiProvider: providerIdentifiers.infer, + inferModelId: "infer/test-model:official", + }), + { wrapper: createWrapper() }, + ) + + expect(result.current.id).toBe("infer/test-model:official") + expect(result.current.info).toEqual(routeInfo) + }) + + it("uses Infer's shared fallback when its catalog is empty", () => { + mockUseRouterModels.mockReturnValue(createRouterModelsResult({ [providerIdentifiers.infer]: {} })) + + const { result } = renderHook( + () => + useSelectedModel({ + apiProvider: providerIdentifiers.infer, + // inferModelId intentionally omitted + }), + { wrapper: createWrapper() }, + ) + + expect(result.current.id).toBe(inferDefaultModelId) + expect(result.current.info).toEqual(inferDefaultModelInfo) + }) + + it("preserves a configured route that is absent from the fetched catalog", () => { + mockUseRouterModels.mockReturnValue( + createRouterModelsResult({ + [providerIdentifiers.infer]: { + "infer/test-model:low-cost": { contextWindow: 1_000_000, supportsPromptCache: true }, + }, + }), + ) + + const { result } = renderHook( + () => + useSelectedModel({ + apiProvider: providerIdentifiers.infer, + inferModelId: "infer/test-model:balanced", + }), + { wrapper: createWrapper() }, + ) + + // A route can leave the catalog for a while. Requests still use the stored + // selector, so the picker shows it; only the metadata falls back. + expect(result.current.id).toBe("infer/test-model:balanced") + expect(result.current.info).toEqual(inferDefaultModelInfo) + }) + + it("preserves the configured route when the catalog fetch errors", () => { + mockUseRouterModels.mockReturnValue( + createRouterModelsResult(undefined, { isLoading: false, isError: true }), + ) + + const { result } = renderHook( + () => + useSelectedModel({ + apiProvider: providerIdentifiers.infer, + inferModelId: "infer/test-model:stable", + }), + { wrapper: createWrapper() }, + ) + + expect(result.current.id).toBe("infer/test-model:stable") + expect(result.current.info).toEqual(inferDefaultModelInfo) + expect(result.current.isError).toBe(true) + }) + }) + describe("openai provider", () => { beforeEach(() => { mockUseRouterModels.mockReturnValue(createRouterModelsResult({ openrouter: {}, requesty: {}, litellm: {} })) diff --git a/webview-ui/src/components/ui/hooks/useSelectedModel.ts b/webview-ui/src/components/ui/hooks/useSelectedModel.ts index 5eb3c64b2ea..43cfa0b935a 100644 --- a/webview-ui/src/components/ui/hooks/useSelectedModel.ts +++ b/webview-ui/src/components/ui/hooks/useSelectedModel.ts @@ -30,6 +30,7 @@ import { lMStudioDefaultModelInfo, opencodeGoDefaultModelInfo, kenariDefaultModelInfo, + inferDefaultModelInfo, nanoGptDefaultModelInfo, BEDROCK_1M_CONTEXT_MODEL_IDS, BEDROCK_DEFAULT_CONTEXT, @@ -125,16 +126,17 @@ export const useSelectedModel = (apiConfiguration: ProviderSettings) => { const needLmStudio = typeof lmStudioModelId !== "undefined" const needOllama = typeof ollamaModelId !== "undefined" - // LiteLLM may legitimately have no entry in the router payload (partial - // listing, failed fetch, renamed deployment) even though the configured ID - // is a valid selection, so it only needs the fetch to settle. Other - // dynamic providers require a populated provider entry before the - // selection is resolved. + // LiteLLM and Infer may legitimately have no entry in the router payload + // (partial listing, failed fetch, renamed deployment, a route that is out + // of the catalog for a while) even though the configured ID is a valid + // selection, so they only need the fetch to settle. Other dynamic + // providers require a populated provider entry before the selection is + // resolved. const hasValidRouterData = needRouterModels && dynamicProvider ? dynamicProvider === providerIdentifiers.friendli ? true // static friendliModels cover the window before /v1/models data arrives - : dynamicProvider === providerIdentifiers.litellm + : dynamicProvider === providerIdentifiers.litellm || dynamicProvider === providerIdentifiers.infer ? !routerModels.isLoading : routerModels.data && routerModels.data[dynamicProvider] !== undefined && @@ -569,6 +571,14 @@ function getSelectedModel({ const info = routerModels[providerIdentifiers.kenari]?.[id] ?? kenariDefaultModelInfo return { id, info } } + case providerIdentifiers.infer: { + // Keep the configured route selector even when the catalog does not list it: + // the handler sends requests with it, and a route can be out of the catalog + // for a while. Only the metadata falls back. + const id = apiConfiguration.inferModelId || defaultModelId + const info = routerModels[providerIdentifiers.infer]?.[id] ?? inferDefaultModelInfo + return { id, info } + } case providerIdentifiers.nanogpt: { const id = getValidatedModelId( apiConfiguration.nanoGptModelId, diff --git a/webview-ui/src/i18n/locales/ca/settings.json b/webview-ui/src/i18n/locales/ca/settings.json index 77898bd46ee..468dadd2393 100644 --- a/webview-ui/src/i18n/locales/ca/settings.json +++ b/webview-ui/src/i18n/locales/ca/settings.json @@ -392,6 +392,12 @@ "getOpencodeGoApiKey": "Obtenir clau API de Opencode Go", "kenariApiKey": "Clau API de Kenari", "getKenariApiKey": "Obtenir clau API de Kenari", + "infer": { + "provider": "Infer", + "apiKey": "Clau API d'Infer", + "getApiKey": "Obtenir clau API d'Infer", + "model": "Model" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "Clau API de NanoGPT", diff --git a/webview-ui/src/i18n/locales/de/settings.json b/webview-ui/src/i18n/locales/de/settings.json index a62232017d9..f73dec09cf5 100644 --- a/webview-ui/src/i18n/locales/de/settings.json +++ b/webview-ui/src/i18n/locales/de/settings.json @@ -391,6 +391,12 @@ "getOpencodeGoApiKey": "Opencode Go API-Schlüssel erhalten", "kenariApiKey": "Kenari API-Schlüssel", "getKenariApiKey": "Kenari API-Schlüssel erhalten", + "infer": { + "provider": "Infer", + "apiKey": "Infer API-Schlüssel", + "getApiKey": "Infer API-Schlüssel holen", + "model": "Modell" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "NanoGPT API-Schlüssel", diff --git a/webview-ui/src/i18n/locales/en/settings.json b/webview-ui/src/i18n/locales/en/settings.json index ab1d9020dc5..722aedf9b50 100644 --- a/webview-ui/src/i18n/locales/en/settings.json +++ b/webview-ui/src/i18n/locales/en/settings.json @@ -464,6 +464,12 @@ "getOpencodeGoApiKey": "Get Opencode Go API Key", "kenariApiKey": "Kenari API Key", "getKenariApiKey": "Get Kenari API Key", + "infer": { + "provider": "Infer", + "apiKey": "Infer API Key", + "getApiKey": "Get Infer API Key", + "model": "Model" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "NanoGPT API Key", diff --git a/webview-ui/src/i18n/locales/es/settings.json b/webview-ui/src/i18n/locales/es/settings.json index 978d51427dc..374545edd1a 100644 --- a/webview-ui/src/i18n/locales/es/settings.json +++ b/webview-ui/src/i18n/locales/es/settings.json @@ -392,6 +392,12 @@ "getOpencodeGoApiKey": "Obtener clave API de Opencode Go", "kenariApiKey": "Clave API de Kenari", "getKenariApiKey": "Obtener clave API de Kenari", + "infer": { + "provider": "Infer", + "apiKey": "Clave API de Infer", + "getApiKey": "Obtener clave API de Infer", + "model": "Modelo" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "Clave API de NanoGPT", diff --git a/webview-ui/src/i18n/locales/fr/settings.json b/webview-ui/src/i18n/locales/fr/settings.json index 5114ab8605b..f8c7488efd0 100644 --- a/webview-ui/src/i18n/locales/fr/settings.json +++ b/webview-ui/src/i18n/locales/fr/settings.json @@ -392,6 +392,12 @@ "getOpencodeGoApiKey": "Obtenir la clé API Opencode Go", "kenariApiKey": "Clé API Kenari", "getKenariApiKey": "Obtenir la clé API Kenari", + "infer": { + "provider": "Infer", + "apiKey": "Clé API Infer", + "getApiKey": "Obtenir une clé API Infer", + "model": "Modèle" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "Clé API NanoGPT", diff --git a/webview-ui/src/i18n/locales/hi/settings.json b/webview-ui/src/i18n/locales/hi/settings.json index 8d05339db00..0d5f190c509 100644 --- a/webview-ui/src/i18n/locales/hi/settings.json +++ b/webview-ui/src/i18n/locales/hi/settings.json @@ -391,6 +391,12 @@ "getOpencodeGoApiKey": "Opencode Go API कुंजी प्राप्त करें", "kenariApiKey": "Kenari API कुंजी", "getKenariApiKey": "Kenari API कुंजी प्राप्त करें", + "infer": { + "provider": "Infer", + "apiKey": "Infer API कुंजी", + "getApiKey": "Infer API कुंजी प्राप्त करें", + "model": "मॉडल" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "NanoGPT API कुंजी", diff --git a/webview-ui/src/i18n/locales/id/settings.json b/webview-ui/src/i18n/locales/id/settings.json index df4e4545dc8..58338f8fb90 100644 --- a/webview-ui/src/i18n/locales/id/settings.json +++ b/webview-ui/src/i18n/locales/id/settings.json @@ -390,6 +390,12 @@ "getOpencodeGoApiKey": "Dapatkan Opencode Go API Key", "kenariApiKey": "Kenari API Key", "getKenariApiKey": "Dapatkan Kenari API Key", + "infer": { + "provider": "Infer", + "apiKey": "Kunci API Infer", + "getApiKey": "Dapatkan Kunci API Infer", + "model": "Model" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "NanoGPT API Key", diff --git a/webview-ui/src/i18n/locales/it/settings.json b/webview-ui/src/i18n/locales/it/settings.json index 451c8af29be..6065f778079 100644 --- a/webview-ui/src/i18n/locales/it/settings.json +++ b/webview-ui/src/i18n/locales/it/settings.json @@ -392,6 +392,12 @@ "getOpencodeGoApiKey": "Ottieni chiave API Opencode Go", "kenariApiKey": "Chiave API Kenari", "getKenariApiKey": "Ottieni chiave API Kenari", + "infer": { + "provider": "Infer", + "apiKey": "Chiave API Infer", + "getApiKey": "Ottieni chiave API Infer", + "model": "Modello" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "Chiave API NanoGPT", diff --git a/webview-ui/src/i18n/locales/ja/settings.json b/webview-ui/src/i18n/locales/ja/settings.json index 0bdf8d6de36..4389f3d5176 100644 --- a/webview-ui/src/i18n/locales/ja/settings.json +++ b/webview-ui/src/i18n/locales/ja/settings.json @@ -390,6 +390,12 @@ "getOpencodeGoApiKey": "Opencode Go APIキーを取得", "kenariApiKey": "Kenari APIキー", "getKenariApiKey": "Kenari APIキーを取得", + "infer": { + "provider": "Infer", + "apiKey": "Infer APIキー", + "getApiKey": "Infer APIキーを取得", + "model": "モデル" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "NanoGPT APIキー", diff --git a/webview-ui/src/i18n/locales/ko/settings.json b/webview-ui/src/i18n/locales/ko/settings.json index d0f1bd28103..9de5f937ff5 100644 --- a/webview-ui/src/i18n/locales/ko/settings.json +++ b/webview-ui/src/i18n/locales/ko/settings.json @@ -390,6 +390,12 @@ "getOpencodeGoApiKey": "Opencode Go API 키 받기", "kenariApiKey": "Kenari API 키", "getKenariApiKey": "Kenari API 키 받기", + "infer": { + "provider": "Infer", + "apiKey": "Infer API 키", + "getApiKey": "Infer API 키 받기", + "model": "모델" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "NanoGPT API 키", diff --git a/webview-ui/src/i18n/locales/nl/settings.json b/webview-ui/src/i18n/locales/nl/settings.json index 880a2784d7d..7af26e4f0f3 100644 --- a/webview-ui/src/i18n/locales/nl/settings.json +++ b/webview-ui/src/i18n/locales/nl/settings.json @@ -391,6 +391,12 @@ "getOpencodeGoApiKey": "Opencode Go API-sleutel ophalen", "kenariApiKey": "Kenari API-sleutel", "getKenariApiKey": "Kenari API-sleutel ophalen", + "infer": { + "provider": "Infer", + "apiKey": "Infer API-sleutel", + "getApiKey": "Infer API-sleutel ophalen", + "model": "Model" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "NanoGPT API-sleutel", diff --git a/webview-ui/src/i18n/locales/pl/settings.json b/webview-ui/src/i18n/locales/pl/settings.json index 58b5b024c8a..a017b4bb03d 100644 --- a/webview-ui/src/i18n/locales/pl/settings.json +++ b/webview-ui/src/i18n/locales/pl/settings.json @@ -393,6 +393,12 @@ "getOpencodeGoApiKey": "Uzyskaj klucz API Opencode Go", "kenariApiKey": "Klucz API Kenari", "getKenariApiKey": "Uzyskaj klucz API Kenari", + "infer": { + "provider": "Infer", + "apiKey": "Klucz API Infer", + "getApiKey": "Uzyskaj klucz API Infer", + "model": "Model" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "Klucz API NanoGPT", diff --git a/webview-ui/src/i18n/locales/pt-BR/settings.json b/webview-ui/src/i18n/locales/pt-BR/settings.json index 356690664fa..9445c33590b 100644 --- a/webview-ui/src/i18n/locales/pt-BR/settings.json +++ b/webview-ui/src/i18n/locales/pt-BR/settings.json @@ -392,6 +392,12 @@ "getOpencodeGoApiKey": "Obter chave API do Opencode Go", "kenariApiKey": "Chave API do Kenari", "getKenariApiKey": "Obter chave API do Kenari", + "infer": { + "provider": "Infer", + "apiKey": "Chave de API do Infer", + "getApiKey": "Obter chave de API do Infer", + "model": "Modelo" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "Chave API do NanoGPT", diff --git a/webview-ui/src/i18n/locales/ru/settings.json b/webview-ui/src/i18n/locales/ru/settings.json index 6e98db3dea6..abef5db2ea7 100644 --- a/webview-ui/src/i18n/locales/ru/settings.json +++ b/webview-ui/src/i18n/locales/ru/settings.json @@ -393,6 +393,12 @@ "getOpencodeGoApiKey": "Получить ключ API Opencode Go", "kenariApiKey": "Ключ API Kenari", "getKenariApiKey": "Получить ключ API Kenari", + "infer": { + "provider": "Infer", + "apiKey": "API-ключ Infer", + "getApiKey": "Получить API-ключ Infer", + "model": "Модель" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "Ключ API NanoGPT", diff --git a/webview-ui/src/i18n/locales/tr/settings.json b/webview-ui/src/i18n/locales/tr/settings.json index b95babadde3..8596d008ef4 100644 --- a/webview-ui/src/i18n/locales/tr/settings.json +++ b/webview-ui/src/i18n/locales/tr/settings.json @@ -391,6 +391,12 @@ "getOpencodeGoApiKey": "Opencode Go API Anahtarı Al", "kenariApiKey": "Kenari API Anahtarı", "getKenariApiKey": "Kenari API Anahtarı Al", + "infer": { + "provider": "Infer", + "apiKey": "Infer API Anahtarı", + "getApiKey": "Infer API Anahtarı Al", + "model": "Model" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "NanoGPT API Anahtarı", diff --git a/webview-ui/src/i18n/locales/vi/settings.json b/webview-ui/src/i18n/locales/vi/settings.json index d73715351c1..756361128c6 100644 --- a/webview-ui/src/i18n/locales/vi/settings.json +++ b/webview-ui/src/i18n/locales/vi/settings.json @@ -390,6 +390,12 @@ "getOpencodeGoApiKey": "Lấy khóa API Opencode Go", "kenariApiKey": "Khóa API Kenari", "getKenariApiKey": "Lấy khóa API Kenari", + "infer": { + "provider": "Infer", + "apiKey": "Khóa API Infer", + "getApiKey": "Lấy khóa API Infer", + "model": "Mô hình" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "Khóa API NanoGPT", diff --git a/webview-ui/src/i18n/locales/zh-CN/settings.json b/webview-ui/src/i18n/locales/zh-CN/settings.json index 096d0cfabd6..98defd469c1 100644 --- a/webview-ui/src/i18n/locales/zh-CN/settings.json +++ b/webview-ui/src/i18n/locales/zh-CN/settings.json @@ -390,6 +390,12 @@ "getOpencodeGoApiKey": "获取 Opencode Go API 密钥", "kenariApiKey": "Kenari API 密钥", "getKenariApiKey": "获取 Kenari API 密钥", + "infer": { + "provider": "Infer", + "apiKey": "Infer API 密钥", + "getApiKey": "获取 Infer API 密钥", + "model": "模型" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "NanoGPT API 密钥", diff --git a/webview-ui/src/i18n/locales/zh-TW/settings.json b/webview-ui/src/i18n/locales/zh-TW/settings.json index ec1f23f7219..db1670b9c86 100644 --- a/webview-ui/src/i18n/locales/zh-TW/settings.json +++ b/webview-ui/src/i18n/locales/zh-TW/settings.json @@ -417,6 +417,12 @@ "getOpencodeGoApiKey": "取得 Opencode Go API 金鑰", "kenariApiKey": "Kenari API 金鑰", "getKenariApiKey": "取得 Kenari API 金鑰", + "infer": { + "provider": "Infer", + "apiKey": "Infer API 金鑰", + "getApiKey": "取得 Infer API 金鑰", + "model": "模型" + }, "nanoGpt": { "provider": "NanoGPT", "apiKey": "NanoGPT API 金鑰", diff --git a/webview-ui/src/utils/__tests__/validate.spec.ts b/webview-ui/src/utils/__tests__/validate.spec.ts index 816d0cefc5b..48dfddebfb5 100644 --- a/webview-ui/src/utils/__tests__/validate.spec.ts +++ b/webview-ui/src/utils/__tests__/validate.spec.ts @@ -49,6 +49,7 @@ describe("Model Validation Functions", () => { requesty: {}, unbound: {}, litellm: {}, + infer: {}, ollama: {}, lmstudio: {}, "vercel-ai-gateway": {}, @@ -470,6 +471,46 @@ describe("Model Validation Functions", () => { }) }) + describe("Infer validation", () => { + it("returns an apiKey error when the Infer API key is unset", () => { + const config: ProviderSettings = { + apiProvider: providerIdentifiers.infer, + inferModelId: "infer/test-model:low-cost", + } + + expect(validateApiConfiguration(config, t, mockRouterModels)).toBe("settings:validation.apiKey") + }) + + it("accepts an Infer API key and selected route", () => { + const config: ProviderSettings = { + apiProvider: providerIdentifiers.infer, + inferApiKey: "valid-key", + inferModelId: "infer/test-model:low-cost", + } + + expect(validateApiConfiguration(config, t, mockRouterModels)).toBeUndefined() + }) + + it("reports a selected route that the fetched catalog no longer lists", () => { + const config: ProviderSettings = { + apiProvider: providerIdentifiers.infer, + inferApiKey: "valid-key", + inferModelId: "infer/test-model:balanced", + } + const routerModels: RouterModels = { + ...mockRouterModels, + infer: { + "infer/test-model:low-cost": { contextWindow: 128_000, supportsPromptCache: false }, + "infer/test-model:official": { contextWindow: 128_000, supportsPromptCache: false }, + }, + } + + expect(getModelValidationError(config, t, routerModels, allowAllOrganization)).toBe( + "settings:validation.modelAvailability modelId=infer/test-model:balanced", + ) + }) + }) + describe("NanoGPT validation", () => { it("returns an apiKey error when the NanoGPT API key is missing", () => { const config: ProviderSettings = { diff --git a/webview-ui/src/utils/validate.ts b/webview-ui/src/utils/validate.ts index aa34fa4e8d3..119c3d46b72 100644 --- a/webview-ui/src/utils/validate.ts +++ b/webview-ui/src/utils/validate.ts @@ -191,6 +191,11 @@ function validateModelsAndKeysProvided( return t("settings:validation.apiKey") } break + case providerIdentifiers.infer: + if (!apiConfiguration.inferApiKey) { + return t("settings:validation.apiKey") + } + break case providerIdentifiers.nanogpt: if (!apiConfiguration.nanoGptApiKey) { return t("settings:validation.apiKey")