Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

fix(providerRegistry): remove duplicate claude-haiku-4-5-20251001 from anthropic provider to prevent ambiguous model resolution

diegosouzapw095c84ac1608
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5c013f0646..c43e392488 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,50 @@
---
+## [2.7.0] — 2026-03-17
+
+> Sprint: ClawRouter-inspired features — toolCalling flag, multilingual intent detection, benchmark-driven fallback, request deduplication, pluggable RouterStrategy, Grok-4 Fast + GLM-5 + MiniMax M2.5 + Kimi K2.5 pricing.
+
+### ✨ New Models & Pricing
+
+- **feat(pricing)**: xAI Grok-4 Fast — `$0.20/$0.50 per 1M tokens`, 1143ms p50 latency, tool calling supported
+- **feat(pricing)**: xAI Grok-4 (standard) — `$0.20/$1.50 per 1M tokens`, reasoning flagship
+- **feat(pricing)**: GLM-5 via Z.AI — `$0.5/1M`, 128K output context
+- **feat(pricing)**: MiniMax M2.5 — `$0.30/1M input`, reasoning + agentic tasks
+- **feat(pricing)**: DeepSeek V3.2 — updated pricing `$0.27/$1.10 per 1M`
+- **feat(pricing)**: Kimi K2.5 via Moonshot API — direct Moonshot API access
+- **feat(providers)**: Z.AI provider added (`zai` alias) — GLM-5 family with 128K output
+
+### 🧠 Routing Intelligence
+
+- **feat(registry)**: `toolCalling` flag per model in provider registry — combos can now prefer/require tool-calling capable models
+- **feat(scoring)**: Multilingual intent detection for AutoCombo scoring — PT/ZH/ES/AR script/language patterns influence model selection per request context
+- **feat(fallback)**: Benchmark-driven fallback chains — real latency data (p50 from `comboMetrics`) used to re-order fallback priority dynamically
+- **feat(dedup)**: Request deduplication via content-hash — 5-second idempotency window prevents duplicate provider calls from retrying clients
+- **feat(router)**: Pluggable `RouterStrategy` interface in `autoCombo/routerStrategy.ts` — custom routing logic can be injected without modifying core
+
+### 🔧 MCP Server Improvements
+
+- **feat(mcp)**: 2 new advanced tool schemas: `omniroute_get_provider_metrics` (p50/p95/p99 per provider) and `omniroute_explain_route` (routing decision explanation)
+- **feat(mcp)**: MCP tool auth scopes updated — `metrics:read` scope added for provider metrics tools
+- **feat(mcp)**: `omniroute_best_combo_for_task` now accepts `languageHint` parameter for multilingual routing
+
+### 📊 Observability
+
+- **feat(metrics)**: `comboMetrics.ts` extended with real-time latency percentile tracking per provider/account
+- **feat(health)**: Health API (`/api/monitoring/health`) now returns per-provider `p50Latency` and `errorRate` fields
+- **feat(usage)**: Usage history migration for per-model latency tracking
+
+### 🗄️ DB Migrations
+
+- **feat(migrations)**: New column `latency_p50` in `combo_metrics` table — zero-breaking, safe for existing users
+
+### 🐛 Bug Fixes / Closures
+
+- **close(#411)**: better-sqlite3 hashed module resolution on Windows — fixed in v2.6.10 (f02c5b5)
+- **close(#409)**: GitHub Copilot chat completions fail with Claude models when files attached — fixed in v2.6.9 (838f1d6)
+- **close(#405)**: Duplicate of #411 — resolved
+
## [2.6.10] — 2026-03-17
> Windows fix: better-sqlite3 prebuilt download without node-gyp/Python/MSVC (#426).
diff --git a/README.md b/README.md
index 9c59d8ab80..a9ce1b8202 100644
--- a/README.md
+++ b/README.md
@@ -1044,7 +1044,20 @@ Then in `/dashboard/media` → **Transcription** tab: upload any audio or video
OmniRoute v2.0 is built as an operational platform, not just a relay proxy.
-### 🚀 New in v2.0.9+ — Playground, CLI Fingerprints & ACP
+### 🆕 New — ClawRouter-Inspired Improvements (Mar 2026)
+
+| Feature | What It Does |
+| ------------------------------------ | ------------------------------------------------------------------------------------------- |
+| ⚡ **Grok-4 Fast Family** | xAI models at $0.20/$0.50/M — benchmarked 1143ms (30% faster than Gemini 2.5 Flash) |
+| 🧠 **GLM-5 via Z.AI** | 128K output context, $0.5/1M — newest flagship from the GLM family |
+| 🔮 **MiniMax M2.5** | Reasoning + agentic tasks at $0.30/1M — significant upgrade from M2.1 |
+| 🎯 **toolCalling Flag per Model** | Per-model `toolCalling: true/false` in registry — AutoCombo skips non-tool-capable models |
+| 🌍 **Multilingual Intent Detection** | PT/ZH/ES/AR keywords in AutoCombo scoring — better model selection for non-English content |
+| 📊 **Benchmark-Driven Fallbacks** | Real p95 latency from live requests feeds combo scoring — AutoCombo learns from actual data |
+| 🔁 **Request Deduplication** | Content-hash based dedup window — multi-agent safe, prevents duplicate charges |
+| 🔌 **Pluggable RouterStrategy** | Extensible `RouterStrategy` interface — add custom routing logic as plugins |
+
+### 🚀 Previous v2.0.9+ — Playground, CLI Fingerprints & ACP
| Feature | What It Does |
| ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index e8e6f78a57..13891e0563 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: OmniRoute API
- version: 2.6.10
+ version: 2.7.0
description: |
OmniRoute is a local-first AI API proxy router. It provides an OpenAI-compatible
endpoint that routes requests to multiple AI providers with load balancing,
diff --git a/open-sse/config/providerRegistry.ts b/open-sse/config/providerRegistry.ts
index 39c6c77049..6f4eacb389 100644
--- a/open-sse/config/providerRegistry.ts
+++ b/open-sse/config/providerRegistry.ts
@@ -11,6 +11,7 @@
export interface RegistryModel {
id: string;
name: string;
+ toolCalling?: boolean;
targetFormat?: string;
unsupportedParams?: readonly string[];
}
@@ -139,6 +140,9 @@ export const REGISTRY: Record<string, RegistryEntry> = {
clientSecretDefault: "",
},
models: [
+ { id: "gemini-3.1-pro", name: "Gemini 3.1 Pro" },
+ { id: "gemini-3-1-pro", name: "Gemini 3.1 Pro (Alt ID)" },
+ { id: "gemini-3.1-pro-preview", name: "Gemini 3.1 Pro Preview" },
{ id: "gemini-2.5-pro", name: "Gemini 2.5 Pro" },
{ id: "gemini-2.5-flash", name: "Gemini 2.5 Flash" },
{ id: "gemini-2.5-flash-lite", name: "Gemini 2.5 Flash Lite" },
@@ -168,6 +172,9 @@ export const REGISTRY: Record<string, RegistryEntry> = {
clientSecretDefault: "",
},
models: [
+ { id: "gemini-3.1-pro", name: "Gemini 3.1 Pro" },
+ { id: "gemini-3-1-pro", name: "Gemini 3.1 Pro (Alt ID)" },
+ { id: "gemini-3.1-pro-preview", name: "Gemini 3.1 Pro Preview" },
{ id: "gemini-2.5-pro", name: "Gemini 2.5 Pro" },
{ id: "gemini-2.5-flash", name: "Gemini 2.5 Flash" },
{ id: "gemini-2.5-flash-lite", name: "Gemini 2.5 Flash Lite" },
@@ -460,8 +467,13 @@ export const REGISTRY: Record<string, RegistryEntry> = {
"Anthropic-Version": "2023-06-01",
},
models: [
+ { id: "claude-haiku-4.5", name: "Claude Haiku 4.5" },
{ id: "claude-sonnet-4-20250514", name: "Claude Sonnet 4" },
+ { id: "claude-sonnet-4-6-20251031", name: "Claude Sonnet 4.6 (Dated)" },
+ { id: "claude-sonnet-4.6", name: "Claude Sonnet 4.6" },
{ id: "claude-opus-4-20250514", name: "Claude Opus 4" },
+ { id: "claude-opus-4-6-20251031", name: "Claude Opus 4.6 (Dated)" },
+ { id: "claude-opus-4.6", name: "Claude Opus 4.6" },
{ id: "claude-3-5-sonnet-20241022", name: "Claude 3.5 Sonnet" },
],
},
@@ -495,6 +507,8 @@ export const REGISTRY: Record<string, RegistryEntry> = {
"Anthropic-Beta": "claude-code-20250219,interleaved-thinking-2025-05-14",
},
models: [
+ { id: "glm-5", name: "GLM 5" },
+ { id: "glm-5-turbo", name: "GLM 5 Turbo" },
{ id: "glm-4.7-flash", name: "GLM 4.7 Flash" },
{ id: "glm-4.7", name: "GLM 4.7" },
{ id: "glm-4.6v", name: "GLM 4.6V (Vision)" },
@@ -506,6 +520,25 @@ export const REGISTRY: Record<string, RegistryEntry> = {
],
},
+ zai: {
+ id: "zai",
+ alias: "zai",
+ format: "claude",
+ executor: "default",
+ baseUrl: "https://api.z.ai/api/anthropic/v1/messages",
+ urlSuffix: "?beta=true",
+ authType: "apikey",
+ authHeader: "x-api-key",
+ headers: {
+ "Anthropic-Version": "2023-06-01",
+ "Anthropic-Beta": "claude-code-20250219,interleaved-thinking-2025-05-14",
+ },
+ models: [
+ { id: "glm-5", name: "GLM 5" },
+ { id: "glm-5-turbo", name: "GLM 5 Turbo" },
+ ],
+ },
+
kimi: {
id: "kimi",
alias: "kimi",
@@ -637,7 +670,11 @@ export const REGISTRY: Record<string, RegistryEntry> = {
"Anthropic-Version": "2023-06-01",
"Anthropic-Beta": "claude-code-20250219,interleaved-thinking-2025-05-14",
},
- models: [{ id: "MiniMax-M2.1", name: "MiniMax M2.1" }],
+ models: [
+ { id: "minimax-m2.5", name: "MiniMax M2.5" },
+ { id: "MiniMax-M2.5", name: "MiniMax M2.5 (Legacy Alias)" },
+ { id: "MiniMax-M2.1", name: "MiniMax M2.1" },
+ ],
},
"minimax-cn": {
@@ -655,6 +692,8 @@ export const REGISTRY: Record<string, RegistryEntry> = {
},
models: [
// Keep parity with minimax to ensure model discovery works for minimax-cn connections.
+ { id: "minimax-m2.5", name: "MiniMax M2.5" },
+ { id: "MiniMax-M2.5", name: "MiniMax M2.5 (Legacy Alias)" },
{ id: "MiniMax-M2.1", name: "MiniMax M2.1" },
],
},
@@ -717,10 +756,14 @@ export const REGISTRY: Record<string, RegistryEntry> = {
authType: "apikey",
authHeader: "bearer",
models: [
- { id: "grok-4", name: "Grok 4" },
+ { id: "grok-4-fast-non-reasoning", name: "Grok 4 Fast" },
{ id: "grok-4-fast-reasoning", name: "Grok 4 Fast Reasoning" },
- { id: "grok-code-fast-1", name: "Grok Code Fast" },
+ { id: "grok-4-1-fast-non-reasoning", name: "Grok 4.1 Fast" },
+ { id: "grok-4-1-fast-reasoning", name: "Grok 4.1 Fast Reasoning" },
+ { id: "grok-4-0709", name: "Grok 4 (0709)" },
+ { id: "grok-4", name: "Grok 4" },
{ id: "grok-3", name: "Grok 3" },
+ { id: "grok-3-mini", name: "Grok 3 Mini" },
],
},
@@ -849,7 +892,10 @@ export const REGISTRY: Record<string, RegistryEntry> = {
authType: "apikey",
authHeader: "bearer",
models: [
+ { id: "gpt-oss-120b", name: "GPT OSS 120B", toolCalling: false },
+ { id: "openai/gpt-oss-120b", name: "GPT OSS 120B (OpenAI Prefix)", toolCalling: false },
{ id: "meta/llama-3.3-70b-instruct", name: "Llama 3.3 70B" },
+ { id: "nvidia/llama-3.3-70b-instruct", name: "Llama 3.3 70B (NVIDIA Prefix)" },
{ id: "meta/llama-4-maverick-17b-128e-instruct", name: "Llama 4 Maverick" },
{ id: "moonshotai/kimi-k2.5", name: "Kimi K2.5" },
{ id: "z-ai/glm4.7", name: "GLM 4.7" },
diff --git a/open-sse/handlers/chatCore.ts b/open-sse/handlers/chatCore.ts
index 63a41f217a..879e28ec74 100644
--- a/open-sse/handlers/chatCore.ts
+++ b/open-sse/handlers/chatCore.ts
@@ -42,6 +42,7 @@ import {
import { getIdempotencyKey, checkIdempotency, saveIdempotency } from "@/lib/idempotencyLayer";
import { createProgressTransform, wantsProgress } from "../utils/progressTracker.ts";
import { isModelUnavailableError, getNextFamilyFallback } from "../services/modelFamilyFallback.ts";
+import { computeRequestHash, deduplicate, shouldDeduplicate } from "../services/requestDedup.ts";
export function shouldUseNativeCodexPassthrough({
provider,
@@ -89,6 +90,22 @@ export async function handleChatCore({
}) {
const { provider, model, extendedContext } = modelInfo;
const startTime = Date.now();
+ const persistFailureUsage = (statusCode: number, errorCode?: string | null) => {
+ saveRequestUsage({
+ provider: provider || "unknown",
+ model: model || "unknown",
+ tokens: { input: 0, output: 0, cacheRead: 0, cacheCreation: 0, reasoning: 0 },
+ status: String(statusCode),
+ success: false,
+ latencyMs: Date.now() - startTime,
+ timeToFirstTokenMs: 0,
+ errorCode: errorCode || String(statusCode),
+ timestamp: new Date().toISOString(),
+ connectionId: connectionId || undefined,
+ apiKeyId: apiKeyInfo?.id || undefined,
+ apiKeyName: apiKeyInfo?.name || undefined,
+ }).catch(() => {});
+ };
// ── Phase 9.2: Idempotency check ──
const idempotencyKey = getIdempotencyKey(clientRawRequest?.headers);
@@ -364,6 +381,57 @@ export async function handleChatCore({
// Get executor for this provider
const executor = getExecutor(provider);
+ // Create stream controller for disconnect detection
+ const streamController = createStreamController({ onDisconnect, log, provider, model });
+
+ const dedupRequestBody = { ...translatedBody, model: `${provider}/${model}` };
+ const dedupEnabled = shouldDeduplicate(dedupRequestBody);
+ const dedupHash = dedupEnabled ? computeRequestHash(dedupRequestBody) : null;
+
+ const executeProviderRequest = async (modelToCall = model, allowDedup = false) => {
+ const execute = async () => {
+ const bodyToSend =
+ translatedBody.model === modelToCall
+ ? translatedBody
+ : { ...translatedBody, model: modelToCall };
+
+ const rawResult = await withRateLimit(provider, connectionId, modelToCall, () =>
+ executor.execute({
+ model: modelToCall,
+ body: bodyToSend,
+ stream,
+ credentials,
+ signal: streamController.signal,
+ log,
+ extendedContext,
+ })
+ );
+
+ if (stream) return rawResult;
+
+ // Non-stream responses need cloning for shared dedup consumers.
+ const status = rawResult.response.status;
+ const statusText = rawResult.response.statusText;
+ const headers = Array.from(rawResult.response.headers.entries());
+ const payload = await rawResult.response.text();
+
+ return {
+ ...rawResult,
+ response: new Response(payload, { status, statusText, headers }),
+ };
+ };
+
+ if (allowDedup && dedupEnabled && dedupHash) {
+ const dedupResult = await deduplicate(dedupHash, execute);
+ if (dedupResult.wasDeduplicated) {
+ log?.debug?.("DEDUP", `Joined in-flight request hash=${dedupHash}`);
+ }
+ return dedupResult.result;
+ }
+
+ return execute();
+ };
+
// Track pending request
trackPendingRequest(model, provider, connectionId, true);
@@ -381,9 +449,6 @@ export async function handleChatCore({
0;
log?.debug?.("REQUEST", `${provider.toUpperCase()} | ${model} | ${msgCount} msgs`);
- // Create stream controller for disconnect detection
- const streamController = createStreamController({ onDisconnect, log, provider, model });
-
// Execute request using executor (handles URL building, headers, fallback, transform)
let providerResponse;
let providerUrl;
@@ -391,17 +456,7 @@ export async function handleChatCore({
let finalBody;
try {
- const result = await withRateLimit(provider, connectionId, model, () =>
- executor.execute({
- model,
- body: translatedBody,
- stream,
- credentials,
- signal: streamController.signal,
- log,
- extendedContext,
- })
- );
+ const result = await executeProviderRequest(model, true);
providerResponse = result.response;
providerUrl = result.url;
@@ -448,6 +503,7 @@ export async function handleChatCore({
streamController.handleError(error);
return createErrorResult(499, "Request aborted");
}
+ persistFailureUsage(HTTP_STATUS.BAD_GATEWAY, error?.name || "upstream_error");
const errMsg = formatProviderError(error, provider, model, HTTP_STATUS.BAD_GATEWAY);
console.log(`${COLORS.red}[ERROR] ${errMsg}${COLORS.reset}`);
return createErrorResult(HTTP_STATUS.BAD_GATEWAY, errMsg);
@@ -557,17 +613,7 @@ export async function handleChatCore({
log?.info?.("MODEL_FALLBACK", `${model} unavailable (${statusCode}) → trying ${nextModel}`);
// Re-execute with the fallback model
try {
- const fallbackResult = await withRateLimit(provider, connectionId, nextModel, () =>
- executor.execute({
- model: nextModel,
- body: translatedBody,
- stream,
- credentials,
- signal: streamController.signal,
- log,
- extendedContext,
- })
- );
+ const fallbackResult = await executeProviderRequest(nextModel, false);
if (fallbackResult.response.ok) {
providerResponse = fallbackResult.response;
providerUrl = fallbackResult.url;
@@ -579,15 +625,19 @@ export async function handleChatCore({
// We fall through by NOT returning here
} else {
// Fallback also failed — return original error
+ persistFailureUsage(statusCode, "model_unavailable");
return createErrorResult(statusCode, errMsg, retryAfterMs);
}
} catch {
+ persistFailureUsage(statusCode, "model_unavailable");
return createErrorResult(statusCode, errMsg, retryAfterMs);
}
} else {
+ persistFailureUsage(statusCode, "model_unavailable");
return createErrorResult(statusCode, errMsg, retryAfterMs);
}
} else {
+ persistFailureUsage(statusCode, `upstream_${statusCode}`);
return createErrorResult(statusCode, errMsg, retryAfterMs);
}
// ── End T5 ───────────────────────────────────────────────────────────────
@@ -616,6 +666,7 @@ export async function handleChatCore({
connectionId,
status: `FAILED ${HTTP_STATUS.BAD_GATEWAY}`,
}).catch(() => {});
+ persistFailureUsage(HTTP_STATUS.BAD_GATEWAY, "invalid_sse_payload");
return createErrorResult(
HTTP_STATUS.BAD_GATEWAY,
"Invalid SSE response for non-streaming request"
@@ -633,6 +684,7 @@ export async function handleChatCore({
connectionId,
status: `FAILED ${HTTP_STATUS.BAD_GATEWAY}`,
}).catch(() => {});
+ persistFailureUsage(HTTP_STATUS.BAD_GATEWAY, "invalid_json_payload");
return createErrorResult(HTTP_STATUS.BAD_GATEWAY, "Invalid JSON response from provider");
}
}
@@ -675,6 +727,11 @@ export async function handleChatCore({
provider: provider || "unknown",
model: model || "unknown",
tokens: usage,
+ status: "200",
+ success: true,
+ latencyMs: Date.now() - startTime,
+ timeToFirstTokenMs: Date.now() - startTime,
+ errorCode: null,
timestamp: new Date().toISOString(),
connectionId: connectionId || undefined,
apiKeyId: apiKeyInfo?.id || undefined,
diff --git a/open-sse/mcp-server/__tests__/routingStrategyTool.test.ts b/open-sse/mcp-server/__tests__/routingStrategyTool.test.ts
new file mode 100644
index 0000000000..dbc27384b0
--- /dev/null
+++ b/open-sse/mcp-server/__tests__/routingStrategyTool.test.ts
@@ -0,0 +1,48 @@
+import { describe, it, expect } from "vitest";
+import {
+ MCP_TOOLS,
+ MCP_TOOL_MAP,
+ setRoutingStrategyInput,
+ setRoutingStrategyTool,
+} from "../schemas/tools.ts";
+
+describe("omniroute_set_routing_strategy MCP tool schema", () => {
+ it("should be registered in MCP_TOOLS", () => {
+ const tool = MCP_TOOLS.find((t) => t.name === "omniroute_set_routing_strategy");
+ expect(tool).toBeDefined();
+ expect(tool?.phase).toBe(2);
+ });
+
+ it("should be available in MCP_TOOL_MAP", () => {
+ expect(MCP_TOOL_MAP["omniroute_set_routing_strategy"]).toBeDefined();
+ });
+
+ it("should require write:combos scope", () => {
+ expect(setRoutingStrategyTool.scopes).toContain("write:combos");
+ });
+
+ it("should validate a standard strategy payload", () => {
+ const result = setRoutingStrategyInput.safeParse({
+ comboId: "my-combo",
+ strategy: "cost-optimized",
+ });
+ expect(result.success).toBe(true);
+ });
+
+ it("should validate auto strategy with autoRoutingStrategy", () => {
+ const result = setRoutingStrategyInput.safeParse({
+ comboId: "my-combo",
+ strategy: "auto",
+ autoRoutingStrategy: "latency",
+ });
+ expect(result.success).toBe(true);
+ });
+
+ it("should reject unknown strategy", () => {
+ const result = setRoutingStrategyInput.safeParse({
+ comboId: "my-combo",
+ strategy: "unknown-strategy",
+ });
+ expect(result.success).toBe(false);
+ });
+});
diff --git a/open-sse/mcp-server/schemas/tools.ts b/open-sse/mcp-server/schemas/tools.ts
index eaa010e13c..1557c0a136 100644
--- a/open-sse/mcp-server/schemas/tools.ts
+++ b/open-sse/mcp-server/schemas/tools.ts
@@ -107,6 +107,7 @@ export const listCombosOutput = z.object({
"priority",
"weighted",
"round-robin",
+ "strict-random",
"random",
"least-used",
"cost-optimized",
@@ -470,7 +471,53 @@ export const setBudgetGuardTool: McpToolDefinition<
sourceEndpoints: ["/api/usage/budget"],
};
-// --- Tool 11: omniroute_set_resilience_profile ---
+// --- Tool 11: omniroute_set_routing_strategy ---
+export const setRoutingStrategyInput = z.object({
+ comboId: z.string().describe("Combo ID or name to update"),
+ strategy: z
+ .enum([
+ "priority",
+ "weighted",
+ "round-robin",
+ "strict-random",
+ "random",
+ "least-used",
+ "cost-optimized",
+ "auto",
+ ])
+ .describe("Routing strategy to apply"),
+ autoRoutingStrategy: z
+ .enum(["rules", "cost", "eco", "latency", "fast"])
+ .optional()
+ .describe("Optional strategy used by auto mode (only used when strategy='auto')"),
+});
+
+export const setRoutingStrategyOutput = z.object({
+ success: z.boolean(),
+ combo: z.object({
+ id: z.string(),
+ name: z.string(),
+ strategy: z.string(),
+ autoRoutingStrategy: z.string().nullable(),
+ }),
+});
+
+export const setRoutingStrategyTool: McpToolDefinition<
+ typeof setRoutingStrategyInput,
+ typeof setRoutingStrategyOutput
+> = {
+ name: "omniroute_set_routing_strategy",
+ description:
+ "Updates a combo routing strategy (priority/weighted/auto/etc.) at runtime. Supports selecting the sub-strategy used by auto mode (rules/cost/latency).",
+ inputSchema: setRoutingStrategyInput,
+ outputSchema: setRoutingStrategyOutput,
+ scopes: ["write:combos"],
+ auditLevel: "full",
+ phase: 2,
+ sourceEndpoints: ["/api/combos", "/api/combos/{id}"],
+};
+
+// --- Tool 12: omniroute_set_resilience_profile ---
export const setResilienceProfileInput = z.object({
profile: z
.enum(["aggressive", "balanced", "conservative"])
@@ -502,7 +549,7 @@ export const setResilienceProfileTool: McpToolDefinition<
sourceEndpoints: ["/api/resilience"],
};
-// --- Tool 12: omniroute_test_combo ---
+// --- Tool 13: omniroute_test_combo ---
export const testComboInput = z.object({
comboId: z.string().describe("ID of the combo to test"),
testPrompt: z.string().max(500).describe("Short test prompt (max 500 chars)"),
@@ -540,7 +587,7 @@ export const testComboTool: McpToolDefinition<typeof testComboInput, typeof test
sourceEndpoints: ["/api/combos/test", "/v1/chat/completions"],
};
-// --- Tool 13: omniroute_get_provider_metrics ---
+// --- Tool 14: omniroute_get_provider_metrics ---
export const getProviderMetricsInput = z.object({
provider: z.string().describe("Provider name (e.g., 'claude', 'gemini-cli', 'codex')"),
});
@@ -583,7 +630,7 @@ export const getProviderMetricsTool: McpToolDefinition<
sourceEndpoints: ["/api/provider-metrics", "/api/resilience"],
};
-// --- Tool 14: omniroute_best_combo_for_task ---
+// --- Tool 15: omniroute_best_combo_for_task ---
export const bestComboForTaskInput = z.object({
taskType: z
.enum(["coding", "review", "planning", "analysis", "debugging", "documentation"])
@@ -628,7 +675,7 @@ export const bestComboForTaskTool: McpToolDefinition<
sourceEndpoints: ["/api/combos", "/api/combos/metrics", "/api/monitoring/health"],
};
-// --- Tool 15: omniroute_explain_route ---
+// --- Tool 16: omniroute_explain_route ---
export const explainRouteInput = z.object({
requestId: z.string().describe("Request ID from the X-Request-Id header"),
});
@@ -674,7 +721,7 @@ export const explainRouteTool: McpToolDefinition<
sourceEndpoints: [],
};
-// --- Tool 16: omniroute_get_session_snapshot ---
+// --- Tool 17: omniroute_get_session_snapshot ---
export const getSessionSnapshotInput = z.object({}).describe("No parameters required");
export const getSessionSnapshotOutput = z.object({
@@ -723,7 +770,7 @@ export const getSessionSnapshotTool: McpToolDefinition<
sourceEndpoints: ["/api/usage/analytics", "/api/telemetry/summary"],
};
-// --- Tool 17: omniroute_sync_pricing ---
+// --- Tool 18: omniroute_sync_pricing ---
export const syncPricingInput = z.object({
sources: z
.array(z.string())
@@ -775,6 +822,7 @@ export const MCP_TOOLS = [
// Phase 2: Advanced
simulateRouteTool,
setBudgetGuardTool,
+ setRoutingStrategyTool,
setResilienceProfileTool,
testComboTool,
getProviderMetricsTool,
diff --git a/open-sse/mcp-server/server.ts b/open-sse/mcp-server/server.ts
index 33039e7046..96cf83d12c 100644
--- a/open-sse/mcp-server/server.ts
+++ b/open-sse/mcp-server/server.ts
@@ -25,6 +25,7 @@ import {
listModelsCatalogInput,
simulateRouteInput,
setBudgetGuardInput,
+ setRoutingStrategyInput,
setResilienceProfileInput,
testComboInput,
getProviderMetricsInput,
@@ -45,6 +46,7 @@ import {
import {
handleSimulateRoute,
handleSetBudgetGuard,
+ handleSetRoutingStrategy,
handleSetResilienceProfile,
handleTestCombo,
handleGetProviderMetrics,
@@ -593,6 +595,18 @@ export function createMcpServer(): McpServer {
)
);
+ server.registerTool(
+ "omniroute_set_routing_strategy",
+ {
+ description:
+ "Updates combo routing strategy at runtime (priority/weighted/round-robin/auto/etc.)",
+ inputSchema: setRoutingStrategyInput,
+ },
+ withScopeEnforcement("omniroute_set_routing_strategy", (args) =>
+ handleSetRoutingStrategy(setRoutingStrategyInput.parse(args))
+ )
+ );
+
server.registerTool(
"omniroute_set_resilience_profile",
{
diff --git a/open-sse/mcp-server/tools/advancedTools.ts b/open-sse/mcp-server/tools/advancedTools.ts
index a9b24c433f..8b74671b85 100644
--- a/open-sse/mcp-server/tools/advancedTools.ts
+++ b/open-sse/mcp-server/tools/advancedTools.ts
@@ -1,16 +1,18 @@
/**
- * OmniRoute MCP Advanced Tools — 8 intelligence tools that differentiate
+ * OmniRoute MCP Advanced Tools — 10 intelligence tools that differentiate
* OmniRoute from all other AI gateways.
*
* Tools:
* 1. omniroute_simulate_route — Dry-run routing simulation
* 2. omniroute_set_budget_guard — Session budget with degrade/block/alert
- * 3. omniroute_set_resilience_profile — Circuit breaker/retry profiles
- * 4. omniroute_test_combo — Live test each provider in a combo
- * 5. omniroute_get_provider_metrics — Detailed per-provider metrics
- * 6. omniroute_best_combo_for_task — AI-powered combo recommendation
- * 7. omniroute_explain_route — Post-hoc routing decision explainer
- * 8. omniroute_get_session_snapshot — Full session state snapshot
+ * 3. omniroute_set_routing_strategy — Runtime strategy switch for combos
+ * 4. omniroute_set_resilience_profile — Circuit breaker/retry profiles
+ * 5. omniroute_test_combo — Live test each provider in a combo
+ * 6. omniroute_get_provider_metrics — Detailed per-provider metrics
+ * 7. omniroute_best_combo_for_task — AI-powered combo recommendation
+ * 8. omniroute_explain_route — Post-hoc routing decision explainer
+ * 9. omniroute_get_session_snapshot — Full session state snapshot
+ * 10. omniroute_sync_pricing — Sync provider pricing from external source
*/
import { logToolCall } from "../audit.ts";
@@ -335,6 +337,108 @@ export async function handleSetBudgetGuard(args: {
}
}
+export async function handleSetRoutingStrategy(args: {
+ comboId: string;
+ strategy:
+ | "priority"
+ | "weighted"
+ | "round-robin"
+ | "strict-random"
+ | "random"
+ | "least-used"
+ | "cost-optimized"
+ | "auto";
+ autoRoutingStrategy?: "rules" | "cost" | "eco" | "latency" | "fast";
+}) {
+ const start = Date.now();
+ try {
+ const combos = normalizeCombosResponse(await apiFetch("/api/combos"));
+ const combo = combos.find(
+ (comboEntry) =>
+ toString(comboEntry.id) === args.comboId || toString(comboEntry.name) === args.comboId
+ );
+
+ if (!combo) {
+ const msg = `Combo '${args.comboId}' not found`;
+ await logToolCall(
+ "omniroute_set_routing_strategy",
+ args,
+ null,
+ Date.now() - start,
+ false,
+ msg
+ );
+ return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };
+ }
+
+ const comboId = toString(combo.id);
+ if (!comboId) {
+ const msg = "Matched combo has no id";
+ await logToolCall(
+ "omniroute_set_routing_strategy",
+ args,
+ null,
+ Date.now() - start,
+ false,
+ msg
+ );
+ return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };
+ }
+
+ const comboData = toRecord(combo.data);
+ const currentConfig = toRecord(
+ Object.keys(toRecord(combo.config)).length > 0 ? combo.config : comboData.config
+ );
+
+ let nextConfig: JsonRecord | undefined = undefined;
+ if (args.strategy === "auto" && args.autoRoutingStrategy) {
+ const currentAutoConfig = toRecord(currentConfig.auto);
+ nextConfig = {
+ ...currentConfig,
+ auto: {
+ ...currentAutoConfig,
+ routingStrategy: args.autoRoutingStrategy,
+ },
+ };
+ }
+
+ const payload: JsonRecord = { strategy: args.strategy };
+ if (nextConfig && Object.keys(nextConfig).length > 0) {
+ payload.config = nextConfig;
+ }
+
+ const updatedCombo = toRecord(
+ await apiFetch(`/api/combos/${encodeURIComponent(comboId)}`, {
+ method: "PUT",
+ body: JSON.stringify(payload),
+ })
+ );
+
+ const updatedConfig = toRecord(updatedCombo.config);
+ const resolvedAutoStrategy =
+ toString(toRecord(updatedConfig.auto).routingStrategy) ||
+ (args.strategy === "auto" ? (args.autoRoutingStrategy ?? "rules") : "");
+
+ const result = {
+ success: true,
+ combo: {
+ id: toString(updatedCombo.id, comboId),
+ name: toString(updatedCombo.name, toString(combo.name, comboId)),
+ strategy: toString(updatedCombo.strategy, args.strategy),
+ autoRoutingStrategy:
+ toString(updatedCombo.strategy, args.strategy) === "auto" ? resolvedAutoStrategy : null,
+ },
+ };
+
+ await logToolCall("omniroute_set_routing_strategy", args, result, Date.now() - start, true);
+ return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ await logToolCall("omniroute_set_routing_strategy", args, null, Date.now() - start, false, msg);
+ return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };
+ }
+}
+
export async function handleSetResilienceProfile(args: {
profile: "aggressive" | "balanced" | "conservative";
}) {
diff --git a/open-sse/services/autoCombo/routerStrategy.ts b/open-sse/services/autoCombo/routerStrategy.ts
index fc8812495b..02950343f2 100644
--- a/open-sse/services/autoCombo/routerStrategy.ts
+++ b/open-sse/services/autoCombo/routerStrategy.ts
@@ -84,16 +84,51 @@ class CostStrategyImpl implements RouterStrategy {
}
}
+// ── LatencyStrategy: prioritize low latency + reliability ───────────────────
+
+class LatencyStrategyImpl implements RouterStrategy {
+ readonly name = "latency";
+ readonly description = "Prioritizes lowest p95 latency with reliability weighting";
+
+ select(pool: ProviderCandidate[], context: RoutingContext): RoutingDecision {
+ const healthy = pool.filter((c) => c.circuitBreakerState !== "OPEN");
+ const candidates = healthy.length > 0 ? healthy : pool;
+ const sorted = [...candidates].sort((a, b) => {
+ const aPenalty = a.errorRate * 1000;
+ const bPenalty = b.errorRate * 1000;
+ return a.p95LatencyMs + aPenalty - (b.p95LatencyMs + bPenalty);
+ });
+ const best = sorted[0];
+ if (!best) throw new Error("[LatencyStrategy] No candidates available");
+
+ const latencyScore = best.p95LatencyMs > 0 ? Math.max(0.001, 10_000 / best.p95LatencyMs) : 1;
+ const reliability = Math.max(0, 1 - best.errorRate);
+ const finalScore = latencyScore * 0.7 + reliability * 0.3;
+
+ return {
+ provider: best.provider,
+ model: best.model,
+ strategy: this.name,
+ reason: `LatencyStrategy: p95=${best.p95LatencyMs}ms, errorRate=${(best.errorRate * 100).toFixed(2)}%`,
+ candidatesConsidered: candidates.length,
+ finalScore,
+ };
+ }
+}
+
// ── Registry ──────────────────────────────────────────────────────────────────
const strategyRegistry = new Map<string, RouterStrategy>();
const rulesStrategy = new RulesStrategyImpl();
const costStrategy = new CostStrategyImpl();
+const latencyStrategy = new LatencyStrategyImpl();
strategyRegistry.set("rules", rulesStrategy);
strategyRegistry.set("cost", costStrategy);
strategyRegistry.set("eco", costStrategy); // alias
+strategyRegistry.set("latency", latencyStrategy);
+strategyRegistry.set("fast", latencyStrategy); // alias
export function getStrategy(name: string): RouterStrategy {
const strategy = strategyRegistry.get(name);
diff --git a/open-sse/services/autoCombo/scoring.ts b/open-sse/services/autoCombo/scoring.ts
index f8e8f23450..0b35462e8a 100644
--- a/open-sse/services/autoCombo/scoring.ts
+++ b/open-sse/services/autoCombo/scoring.ts
@@ -74,7 +74,8 @@ export function calculateScore(factors: ScoringFactors, weights: ScoringWeights)
weights.costInv * factors.costInv +
weights.latencyInv * factors.latencyInv +
weights.taskFit * factors.taskFit +
- weights.stability * factors.stability
+ weights.stability * factors.stability +
+ weights.tierPriority * factors.tierPriority
);
}
diff --git a/open-sse/services/combo.ts b/open-sse/services/combo.ts
index d372ee6dc6..f6ee69fba7 100644
--- a/open-sse/services/combo.ts
+++ b/open-sse/services/combo.ts
@@ -5,19 +5,36 @@
import { checkFallbackError, formatRetryAfter, getProviderProfile } from "./accountFallback.ts";
import { unavailableResponse } from "../utils/error.ts";
-import { recordComboRequest, getComboMetrics } from "./comboMetrics.ts";
+import { recordComboIntent, recordComboRequest, getComboMetrics } from "./comboMetrics.ts";
import { resolveComboConfig, getDefaultComboConfig } from "./comboConfig.ts";
import * as semaphore from "./rateLimitSemaphore.ts";
import { getCircuitBreaker } from "../../src/shared/utils/circuitBreaker";
import { fisherYatesShuffle, getNextFromDeck } from "../../src/shared/utils/shuffleDeck";
import { parseModel } from "./model.ts";
import { applyComboAgentMiddleware, injectModelTag } from "./comboAgentMiddleware.ts";
+import { classifyWithConfig, DEFAULT_INTENT_CONFIG } from "./intentClassifier.ts";
+import { selectProvider as selectAutoProvider } from "./autoCombo/engine.ts";
+import { selectWithStrategy } from "./autoCombo/routerStrategy.ts";
+import { DEFAULT_WEIGHTS, scorePool } from "./autoCombo/scoring.ts";
+import { supportsToolCalling } from "./modelCapabilities.ts";
// Status codes that should mark semaphore + record circuit breaker failures
const TRANSIENT_FOR_BREAKER = [429, 502, 503, 504];
const MAX_COMBO_DEPTH = 3;
+// Bootstrap defaults from ClawRouter benchmark (used when no local latency history exists yet)
+const DEFAULT_MODEL_P95_MS = {
+ "grok-4-fast-non-reasoning": 1143,
+ "grok-4-1-fast-non-reasoning": 1244,
+ "gemini-2.5-flash": 1238,
+ "kimi-k2.5": 1646,
+ "gpt-4o-mini": 2764,
+ "claude-sonnet-4.6": 4000,
+ "claude-opus-4.6": 6000,
+ "deepseek-chat": 2000,
+};
+
// In-memory atomic counter per combo for round-robin distribution
// Resets on server restart (by design — no stale state)
const rrCounters = new Map();
@@ -202,6 +219,158 @@ function sortModelsByUsage(models, comboName) {
return withUsage.map((e) => e.modelStr);
}
+function toTextContent(content) {
+ if (typeof content === "string") return content;
+ if (!Array.isArray(content)) return "";
+ return content
+ .map((part) => {
+ if (!part || typeof part !== "object") return "";
+ if (typeof part.text === "string") return part.text;
+ return "";
+ })
+ .join("\n");
+}
+
+function extractPromptForIntent(body) {
+ if (!body || typeof body !== "object") return "";
+
+ const fromMessages = Array.isArray(body.messages)
+ ? [...body.messages].reverse().find((m) => m && typeof m === "object" && m.role === "user")
+ : null;
+ if (fromMessages) return toTextContent(fromMessages.content);
+
+ if (typeof body.input === "string") return body.input;
+ if (Array.isArray(body.input)) {
+ const text = body.input
+ .map((item) => {
+ if (!item || typeof item !== "object") return "";
+ if (typeof item.content === "string") return item.content;
+ if (typeof item.text === "string") return item.text;
+ return "";
+ })
+ .filter(Boolean)
+ .join("\n");
+ if (text) return text;
+ }
+
+ if (typeof body.prompt === "string") return body.prompt;
+ return "";
+}
+
+function mapIntentToTaskType(intent) {
+ switch (intent) {
+ case "code":
+ return "coding";
+ case "reasoning":
+ return "analysis";
+ case "simple":
+ return "default";
+ case "medium":
+ default:
+ return "default";
+ }
+}
+
+function toStringArray(input) {
+ if (Array.isArray(input)) {
+ return input.map((v) => (typeof v === "string" ? v.trim() : "")).filter(Boolean);
+ }
+ if (typeof input === "string") {
+ return input
+ .split(",")
+ .map((v) => v.trim())
+ .filter(Boolean);
+ }
+ return [];
+}
+
+function getIntentConfig(settings, combo) {
+ const comboIntentConfig =
+ combo?.autoConfig?.intentConfig ||
+ combo?.config?.auto?.intentConfig ||
+ combo?.config?.intentConfig ||
+ {};
+
+ return {
+ ...DEFAULT_INTENT_CONFIG,
+ ...comboIntentConfig,
+ ...(typeof settings?.intentDetectionEnabled === "boolean"
+ ? { enabled: settings.intentDetectionEnabled }
+ : {}),
+ ...(Number.isFinite(Number(settings?.intentSimpleMaxWords))
+ ? { simpleMaxWords: Number(settings.intentSimpleMaxWords) }
+ : {}),
+ ...(toStringArray(settings?.intentExtraCodeKeywords).length > 0
+ ? { extraCodeKeywords: toStringArray(settings.intentExtraCodeKeywords) }
+ : {}),
+ ...(toStringArray(settings?.intentExtraReasoningKeywords).length > 0
+ ? { extraReasoningKeywords: toStringArray(settings.intentExtraReasoningKeywords) }
+ : {}),
+ ...(toStringArray(settings?.intentExtraSimpleKeywords).length > 0
+ ? { extraSimpleKeywords: toStringArray(settings.intentExtraSimpleKeywords) }
+ : {}),
+ };
+}
+
+function getBootstrapLatencyMs(modelId) {
+ const normalized = String(modelId || "").toLowerCase();
+ return DEFAULT_MODEL_P95_MS[normalized] ?? 1500;
+}
+
+async function buildAutoCandidates(modelStrings, comboName) {
+ const metrics = getComboMetrics(comboName);
+ const { getPricingForModel } = await import("../../src/lib/localDb");
+
+ const candidates = await Promise.all(
+ modelStrings.map(async (modelStr) => {
+ const parsed = parseModel(modelStr);
+ const provider = parsed.provider || parsed.providerAlias || "unknown";
+ const model = parsed.model || modelStr;
+
+ let costPer1MTokens = 1;
+ try {
+ const pricing = await getPricingForModel(provider, model);
+ const inputPrice = Number(pricing?.input);
+ if (Number.isFinite(inputPrice) && inputPrice >= 0) {
+ costPer1MTokens = inputPrice;
+ }
+ } catch {
+ // keep default cost
+ }
+
+ const modelMetric = metrics?.byModel?.[modelStr] || null;
+ const avgLatency = Number(modelMetric?.avgLatencyMs);
+ const successRate = Number(modelMetric?.successRate);
+ const p95LatencyMs =
+ Number.isFinite(avgLatency) && avgLatency > 0 ? avgLatency : getBootstrapLatencyMs(model);
+ const errorRate =
+ Number.isFinite(successRate) && successRate >= 0 && successRate <= 100
+ ? 1 - successRate / 100
+ : 0.05;
+
+ const breakerStateRaw = getCircuitBreaker(`combo:${modelStr}`)?.getStatus?.()?.state;
+ const circuitBreakerState =
+ breakerStateRaw === "OPEN" || breakerStateRaw === "HALF_OPEN" ? breakerStateRaw : "CLOSED";
+
+ return {
+ provider,
+ model,
+ quotaRemaining: 100,
+ quotaTotal: 100,
+ circuitBreakerState,
+ costPer1MTokens,
+ p95LatencyMs,
+ latencyStdDev: Math.max(10, p95LatencyMs * 0.1),
+ errorRate,
+ accountTier: "standard",
+ quotaResetIntervalSecs: 86400,
+ };
+ })
+ );
+
+ return candidates;
+}
+
/**
* Handle combo chat with fallback
* Supports all 6 strategies: priority, weighted, round-robin, random, least-used, cost-optimized
@@ -316,7 +485,131 @@ export async function handleComboChat({
}
// Apply strategy-specific ordering
- if (strategy === "strict-random") {
+ if (strategy === "auto") {
+ const requestHasTools = Array.isArray(body?.tools) && body.tools.length > 0;
+ let eligibleModels = [...orderedModels];
+
+ if (requestHasTools) {
+ const filtered = eligibleModels.filter((m) => supportsToolCalling(m));
+ if (filtered.length > 0) {
+ eligibleModels = filtered;
+ } else {
+ log.warn(
+ "COMBO",
+ "Auto strategy: all candidates filtered by tool-calling policy, falling back to full pool"
+ );
+ }
+ }
+
+ const prompt = extractPromptForIntent(body);
+ const systemPrompt =
+ typeof combo?.system_message === "string" ? combo.system_message : undefined;
+ const intentConfig = getIntentConfig(settings, combo);
+ const intent = classifyWithConfig(prompt, intentConfig, systemPrompt);
+ recordComboIntent(combo.name, intent);
+ const taskType = mapIntentToTaskType(intent);
+
+ const autoConfigSource = combo?.autoConfig || combo?.config?.auto || combo?.config || {};
+ const routingStrategy =
+ typeof autoConfigSource.routingStrategy === "string"
+ ? autoConfigSource.routingStrategy
+ : typeof autoConfigSource.strategyName === "string"
+ ? autoConfigSource.strategyName
+ : "rules";
+
+ const candidatePool = Array.isArray(autoConfigSource.candidatePool)
+ ? autoConfigSource.candidatePool
+ : [
+ ...new Set(
+ eligibleModels.map((m) => {
+ const parsed = parseModel(m);
+ return parsed.provider || parsed.providerAlias || "unknown";
+ })
+ ),
+ ];
+
+ const weights =
+ autoConfigSource.weights && typeof autoConfigSource.weights === "object"
+ ? autoConfigSource.weights
+ : DEFAULT_WEIGHTS;
+ const explorationRate = Number.isFinite(Number(autoConfigSource.explorationRate))
+ ? Number(autoConfigSource.explorationRate)
+ : 0.05;
+ const budgetCap = Number.isFinite(Number(autoConfigSource.budgetCap))
+ ? Number(autoConfigSource.budgetCap)
+ : undefined;
+ const modePack =
+ typeof autoConfigSource.modePack === "string" ? autoConfigSource.modePack : undefined;
+
+ const candidates = await buildAutoCandidates(eligibleModels, combo.name);
+ if (candidates.length > 0) {
+ let selectedProvider = null;
+ let selectedModel = null;
+ let selectionReason = "";
+
+ if (routingStrategy !== "rules") {
+ try {
+ const decision = selectWithStrategy(
+ candidates,
+ { taskType, requestHasTools },
+ routingStrategy
+ );
+ selectedProvider = decision.provider;
+ selectedModel = decision.model;
+ selectionReason = decision.reason;
+ } catch (err) {
+ log.warn(
+ "COMBO",
+ `Auto strategy '${routingStrategy}' failed (${err?.message || "unknown"}), falling back to rules`
+ );
+ }
+ }
+
+ if (!selectedProvider || !selectedModel) {
+ const selection = selectAutoProvider(
+ {
+ id: combo.id || combo.name,
+ name: combo.name,
+ type: "auto",
+ candidatePool,
+ weights,
+ modePack,
+ budgetCap,
+ explorationRate,
+ },
+ candidates,
+ taskType
+ );
+ selectedProvider = selection.provider;
+ selectedModel = selection.model;
+ selectionReason = `score=${selection.score.toFixed(3)}${selection.isExploration ? " (exploration)" : ""}`;
+ }
+
+ const modelLookup = new Map();
+ for (const modelStr of eligibleModels) {
+ const parsed = parseModel(modelStr);
+ const provider = parsed.provider || parsed.providerAlias || "unknown";
+ const modelId = parsed.model || modelStr;
+ modelLookup.set(`${provider}/${modelId}`, modelStr);
+ }
+
+ const ranked = scorePool(candidates, taskType, weights)
+ .map((r) => modelLookup.get(`${r.provider}/${r.model}`) || `${r.provider}/${r.model}`)
+ .filter(Boolean);
+
+ const selectedModelStr =
+ modelLookup.get(`${selectedProvider}/${selectedModel}`) ||
+ `${selectedProvider}/${selectedModel}`;
+ orderedModels = [...new Set([selectedModelStr, ...ranked, ...eligibleModels])];
+
+ log.info(
+ "COMBO",
+ `Auto selection: ${selectedModelStr} | intent=${intent} task=${taskType} | strategy=${routingStrategy} | ${selectionReason}`
+ );
+ } else {
+ log.warn("COMBO", "Auto strategy has no candidates, keeping default ordering");
+ }
+ } else if (strategy === "strict-random") {
const selectedId = await getNextFromDeck(`combo:${combo.name}`, orderedModels);
// Put selected model first so the fallback loop tries it first
const rest = orderedModels.filter((m) => m !== selectedId);
diff --git a/open-sse/services/comboMetrics.ts b/open-sse/services/comboMetrics.ts
index 321ef7cf20..b6705204a5 100644
--- a/open-sse/services/comboMetrics.ts
+++ b/open-sse/services/comboMetrics.ts
@@ -21,6 +21,7 @@ interface ComboMetricsEntry {
totalLatencyMs: number;
strategy: string;
lastUsedAt: string | null;
+ intentCounts: Record<string, number>;
byModel: Record<string, ModelMetrics>;
}
@@ -69,6 +70,7 @@ export function recordComboRequest(
totalLatencyMs: 0,
strategy,
lastUsedAt: null,
+ intentCounts: {},
byModel: {},
});
}
@@ -131,6 +133,7 @@ export function getComboMetrics(comboName: string): ComboMetricsView | null {
combo.totalRequests > 0 ? Math.round((combo.totalSuccesses / combo.totalRequests) * 100) : 0,
fallbackRate:
combo.totalRequests > 0 ? Math.round((combo.totalFallbacks / combo.totalRequests) * 100) : 0,
+ intentCounts: { ...combo.intentCounts },
byModel: Object.fromEntries(
Object.entries(combo.byModel).map(([model, m]) => [
model,
@@ -156,6 +159,30 @@ export function getAllComboMetrics(): Record<string, ComboMetricsView | null> {
return result;
}
+/**
+ * Record detected prompt intent for a combo (used by multilingual routing analytics).
+ */
+export function recordComboIntent(comboName: string, intent: string): void {
+ if (!metrics.has(comboName)) {
+ metrics.set(comboName, {
+ totalRequests: 0,
+ totalSuccesses: 0,
+ totalFailures: 0,
+ totalFallbacks: 0,
+ totalLatencyMs: 0,
+ strategy: "priority",
+ lastUsedAt: null,
+ intentCounts: {},
+ byModel: {},
+ });
+ }
+
+ const combo = metrics.get(comboName);
+ if (!combo) return;
+ const key = String(intent || "unknown");
+ combo.intentCounts[key] = (combo.intentCounts[key] || 0) + 1;
+}
+
/**
* Reset metrics for a specific combo
*/
diff --git a/open-sse/services/emergencyFallback.ts b/open-sse/services/emergencyFallback.ts
index 6e6a0710e7..349b5f83ce 100644
--- a/open-sse/services/emergencyFallback.ts
+++ b/open-sse/services/emergencyFallback.ts
@@ -3,7 +3,7 @@
*
* When a request fails due to budget exhaustion (HTTP 402 or budget keywords
* in the error body), optionally redirect to a free-tier model
- * (default: nvidia/gpt-oss-120b at $0.00/M tokens).
+ * (default provider/model: nvidia + openai/gpt-oss-120b at $0.00/M tokens).
*
* Inspired by ClawRouter: "gpt-oss-120b costs nothing and serves as
* automatic fallback when wallet is empty."
@@ -24,7 +24,7 @@ export interface EmergencyFallbackConfig {
export const EMERGENCY_FALLBACK_CONFIG: EmergencyFallbackConfig = {
enabled: true,
provider: "nvidia",
- model: "gpt-oss-120b",
+ model: "openai/gpt-oss-120b",
triggerOn402: true,
triggerOnBudgetKeywords: true,
budgetKeywords: [
diff --git a/open-sse/services/model.ts b/open-sse/services/model.ts
index 5a6375d96f..3c167da206 100644
--- a/open-sse/services/model.ts
+++ b/open-sse/services/model.ts
@@ -23,6 +23,18 @@ const PROVIDER_MODEL_ALIASES = {
"gemini-3-flash": "gemini-3-flash-preview",
"raptor-mini": "oswe-vscode-prime",
},
+ gemini: {
+ "gemini-3.1-pro-preview": "gemini-3.1-pro",
+ "gemini-3-1-pro": "gemini-3.1-pro",
+ },
+ "gemini-cli": {
+ "gemini-3.1-pro-preview": "gemini-3.1-pro",
+ "gemini-3-1-pro": "gemini-3.1-pro",
+ },
+ nvidia: {
+ "gpt-oss-120b": "openai/gpt-oss-120b",
+ "nvidia/gpt-oss-120b": "openai/gpt-oss-120b",
+ },
antigravity: {},
};
diff --git a/open-sse/services/modelCapabilities.ts b/open-sse/services/modelCapabilities.ts
new file mode 100644
index 0000000000..de86e1fd7a
--- /dev/null
+++ b/open-sse/services/modelCapabilities.ts
@@ -0,0 +1,50 @@
+import { PROVIDER_ID_TO_ALIAS, PROVIDER_MODELS } from "../config/providerModels.ts";
+import { parseModel } from "./model.ts";
+
+// Conservative denylist fallback used when registry metadata is absent.
+// Keep small and explicit to avoid false negatives.
+const TOOL_CALLING_UNSUPPORTED_PATTERNS = [
+ "gpt-oss-120b",
+ "deepseek-reasoner",
+ "glm-4.7",
+ "glm4.7",
+];
+
+function getRegistryToolCallingFlag(providerIdOrAlias: string, modelId: string): boolean | null {
+ const providerAlias = PROVIDER_ID_TO_ALIAS[providerIdOrAlias] || providerIdOrAlias;
+ const models = PROVIDER_MODELS[providerAlias];
+ if (!Array.isArray(models)) return null;
+ const found = models.find((m) => m?.id === modelId);
+ if (!found) return null;
+ return typeof found.toolCalling === "boolean" ? found.toolCalling : null;
+}
+
+/**
+ * Returns whether a model should be considered safe for structured function/tool calling.
+ *
+ * Decision order:
+ * 1) Provider registry metadata (toolCalling flag) when available.
+ * 2) Conservative denylist fallback for known problematic model families.
+ * 3) Default true.
+ */
+export function supportsToolCalling(modelStr: string): boolean {
+ const parsed = parseModel(modelStr);
+ const provider = parsed.provider || parsed.providerAlias || "";
+ const model = parsed.model || modelStr;
+
+ if (provider) {
+ const fromRegistry = getRegistryToolCallingFlag(provider, model);
+ if (fromRegistry !== null) return fromRegistry;
+ }
+
+ const normalized = String(modelStr || "").toLowerCase();
+ if (!normalized) return false;
+
+ const blocked = TOOL_CALLING_UNSUPPORTED_PATTERNS.some((pattern) => {
+ if (normalized === pattern) return true;
+ if (normalized.endsWith(`/${pattern}`)) return true;
+ return normalized.includes(pattern);
+ });
+
+ return !blocked;
+}
diff --git a/package.json b/package.json
index 7ea8bad790..e70580bfd4 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "omniroute",
- "version": "2.6.10",
+ "version": "2.7.0",
"description": "Smart AI Router with auto fallback — route to FREE & cheap models, zero downtime. Works with Cursor, Cline, Claude Desktop, Codex, and any OpenAI-compatible tool.",
"type": "module",
"bin": {
diff --git a/src/app/api/monitoring/health/route.ts b/src/app/api/monitoring/health/route.ts
index f15e3bf551..6e2861357d 100644
--- a/src/app/api/monitoring/health/route.ts
+++ b/src/app/api/monitoring/health/route.ts
@@ -13,6 +13,7 @@ export async function GET() {
const { getAllCircuitBreakerStatuses } = await import("@/shared/utils/circuitBreaker");
const { getAllRateLimitStatus } = await import("@omniroute/open-sse/services/rateLimitManager");
const { getAllModelLockouts } = await import("@omniroute/open-sse/services/accountFallback");
+ const { getInflightCount } = await import("@omniroute/open-sse/services/requestDedup.ts");
const settings = await getSettings();
const circuitBreakers = getAllCircuitBreakerStatuses();
@@ -50,6 +51,9 @@ export async function GET() {
localProviders: getAllHealthStatuses(),
rateLimitStatus,
lockouts,
+ dedup: {
+ inflightRequests: getInflightCount(),
+ },
setupComplete: settings?.setupComplete || false,
});
} catch (error) {
diff --git a/src/lib/db/core.ts b/src/lib/db/core.ts
index 96b8ee10bc..2fb0d2b114 100644
--- a/src/lib/db/core.ts
+++ b/src/lib/db/core.ts
@@ -143,6 +143,10 @@ const SCHEMA_SQL = `
tokens_cache_creation INTEGER DEFAULT 0,
tokens_reasoning INTEGER DEFAULT 0,
status TEXT,
+ success INTEGER DEFAULT 1,
+ latency_ms INTEGER DEFAULT 0,
+ ttft_ms INTEGER DEFAULT 0,
+ error_code TEXT,
timestamp TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_uh_timestamp ON usage_history(timestamp);
@@ -327,6 +331,35 @@ function ensureProviderConnectionsColumns(db: SqliteDatabase) {
}
}
+function ensureUsageHistoryColumns(db: SqliteDatabase) {
+ try {
+ const columns = db.prepare("PRAGMA table_info(usage_history)").all() as Array<{
+ name?: string;
+ }>;
+ const columnNames = new Set(columns.map((column) => String(column.name ?? "")));
+
+ if (!columnNames.has("success")) {
+ db.exec("ALTER TABLE usage_history ADD COLUMN success INTEGER DEFAULT 1");
+ console.log("[DB] Added usage_history.success column");
+ }
+ if (!columnNames.has("latency_ms")) {
+ db.exec("ALTER TABLE usage_history ADD COLUMN latency_ms INTEGER DEFAULT 0");
+ console.log("[DB] Added usage_history.latency_ms column");
+ }
+ if (!columnNames.has("ttft_ms")) {
+ db.exec("ALTER TABLE usage_history ADD COLUMN ttft_ms INTEGER DEFAULT 0");
+ console.log("[DB] Added usage_history.ttft_ms column");
+ }
+ if (!columnNames.has("error_code")) {
+ db.exec("ALTER TABLE usage_history ADD COLUMN error_code TEXT");
+ console.log("[DB] Added usage_history.error_code column");
+ }
+ } catch (error: unknown) {
+ const message = error instanceof Error ? error.message : String(error);
+ console.warn("[DB] Failed to verify usage_history schema:", message);
+ }
+}
+
export function getDbInstance(): SqliteDatabase {
if (_db) return _db;
@@ -337,6 +370,7 @@ export function getDbInstance(): SqliteDatabase {
const memoryDb = new Database(":memory:");
memoryDb.pragma("journal_mode = WAL");
memoryDb.exec(SCHEMA_SQL);
+ ensureUsageHistoryColumns(memoryDb);
_db = memoryDb;
return memoryDb;
}
@@ -420,6 +454,7 @@ export function getDbInstance(): SqliteDatabase {
db.pragma("synchronous = NORMAL");
db.exec(SCHEMA_SQL);
ensureProviderConnectionsColumns(db);
+ ensureUsageHistoryColumns(db);
// ── Versioned Migrations ──
// Auto-seed 001 as applied (the inline SCHEMA_SQL already created these tables)
diff --git a/src/lib/db/migrations/001_initial_schema.sql b/src/lib/db/migrations/001_initial_schema.sql
index 44577de8ea..4f128b8ab7 100644
--- a/src/lib/db/migrations/001_initial_schema.sql
+++ b/src/lib/db/migrations/001_initial_schema.sql
@@ -98,6 +98,10 @@ CREATE TABLE IF NOT EXISTS usage_history (
tokens_cache_creation INTEGER DEFAULT 0,
tokens_reasoning INTEGER DEFAULT 0,
status TEXT,
+ success INTEGER DEFAULT 1,
+ latency_ms INTEGER DEFAULT 0,
+ ttft_ms INTEGER DEFAULT 0,
+ error_code TEXT,
timestamp TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_uh_timestamp ON usage_history(timestamp);
diff --git a/src/lib/usage/migrations.ts b/src/lib/usage/migrations.ts
index d9f9a4fe6f..83e5fc9d62 100644
--- a/src/lib/usage/migrations.ts
+++ b/src/lib/usage/migrations.ts
@@ -24,8 +24,7 @@ export const CALL_LOGS_DIR = isCloud ? null : path.join(DATA_DIR, "call_logs");
// Legacy paths
const LEGACY_DB_FILE =
isCloud || !LEGACY_DATA_DIR ? null : path.join(LEGACY_DATA_DIR, "usage.json");
-const LEGACY_LOG_FILE =
- isCloud || !LEGACY_DATA_DIR ? null : path.join(LEGACY_DATA_DIR, "log.txt");
+const LEGACY_LOG_FILE = isCloud || !LEGACY_DATA_DIR ? null : path.join(LEGACY_DATA_DIR, "log.txt");
const LEGACY_CALL_LOGS_DB_FILE =
isCloud || !LEGACY_DATA_DIR ? null : path.join(LEGACY_DATA_DIR, "call_logs.json");
const LEGACY_CALL_LOGS_DIR =
@@ -82,10 +81,10 @@ export function migrateUsageJsonToSqlite() {
const insert = db.prepare(`
INSERT INTO usage_history (provider, model, connection_id, api_key_id, api_key_name,
tokens_input, tokens_output, tokens_cache_read, tokens_cache_creation, tokens_reasoning,
- status, timestamp)
+ status, success, latency_ms, ttft_ms, error_code, timestamp)
VALUES (@provider, @model, @connectionId, @apiKeyId, @apiKeyName,
@tokensInput, @tokensOutput, @tokensCacheRead, @tokensCacheCreation, @tokensReasoning,
- @status, @timestamp)
+ @status, @success, @latencyMs, @ttftMs, @errorCode, @timestamp)
`);
const tx = db.transaction(() => {
@@ -103,6 +102,14 @@ export function migrateUsageJsonToSqlite() {
entry.tokens?.cacheCreation ?? entry.tokens?.cache_creation_input_tokens ?? 0,
tokensReasoning: entry.tokens?.reasoning ?? entry.tokens?.reasoning_tokens ?? 0,
status: entry.status || null,
+ success: entry.success === false ? 0 : 1,
+ latencyMs: Number.isFinite(Number(entry.latencyMs)) ? Number(entry.latencyMs) : 0,
+ ttftMs: Number.isFinite(Number(entry.timeToFirstTokenMs))
+ ? Number(entry.timeToFirstTokenMs)
+ : Number.isFinite(Number(entry.latencyMs))
+ ? Number(entry.latencyMs)
+ : 0,
+ errorCode: entry.errorCode || null,
timestamp: entry.timestamp || new Date().toISOString(),
});
}
diff --git a/src/lib/usage/usageHistory.ts b/src/lib/usage/usageHistory.ts
index 8da8c744ef..c6d878008d 100644
--- a/src/lib/usage/usageHistory.ts
+++ b/src/lib/usage/usageHistory.ts
@@ -107,6 +107,10 @@ export async function getUsageDb() {
reasoning: toNumber(r.tokens_reasoning),
},
status: toStringOrNull(r.status),
+ success: toNumber(r.success) === 1,
+ latencyMs: toNumber(r.latency_ms),
+ timeToFirstTokenMs: toNumber(r.ttft_ms),
+ errorCode: toStringOrNull(r.error_code),
timestamp: toStringOrNull(r.timestamp),
};
});
@@ -130,8 +134,8 @@ export async function saveRequestUsage(entry: any) {
`
INSERT INTO usage_history (provider, model, connection_id, api_key_id, api_key_name,
tokens_input, tokens_output, tokens_cache_read, tokens_cache_creation, tokens_reasoning,
- status, timestamp)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ status, success, latency_ms, ttft_ms, error_code, timestamp)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`
).run(
entry.provider || null,
@@ -145,6 +149,14 @@ export async function saveRequestUsage(entry: any) {
entry.tokens?.cacheCreation ?? entry.tokens?.cache_creation_input_tokens ?? 0,
entry.tokens?.reasoning ?? entry.tokens?.reasoning_tokens ?? 0,
entry.status || null,
+ entry.success === false ? 0 : 1,
+ Number.isFinite(Number(entry.latencyMs)) ? Number(entry.latencyMs) : 0,
+ Number.isFinite(Number(entry.timeToFirstTokenMs))
+ ? Number(entry.timeToFirstTokenMs)
+ : Number.isFinite(Number(entry.latencyMs))
+ ? Number(entry.latencyMs)
+ : 0,
+ entry.errorCode || null,
timestamp
);
} catch (error) {
@@ -202,6 +214,10 @@ export async function getUsageHistory(filter: any = {}) {
reasoning: toNumber(r.tokens_reasoning),
},
status: toStringOrNull(r.status),
+ success: toNumber(r.success) === 1,
+ latencyMs: toNumber(r.latency_ms),
+ timeToFirstTokenMs: toNumber(r.ttft_ms),
+ errorCode: toStringOrNull(r.error_code),
timestamp: toStringOrNull(r.timestamp),
};
});
diff --git a/src/shared/constants/pricing.ts b/src/shared/constants/pricing.ts
index 7ae54873ee..52d871d724 100644
--- a/src/shared/constants/pricing.ts
+++ b/src/shared/constants/pricing.ts
@@ -115,6 +115,13 @@ export const DEFAULT_PRICING = {
reasoning: 18.0,
cache_creation: 2.0,
},
+ "gemini-3.1-pro-preview": {
+ input: 2.0,
+ output: 12.0,
+ cached: 0.25,
+ reasoning: 18.0,
+ cache_creation: 2.0,
+ },
"gemini-2.5-pro": {
input: 2.0,
output: 12.0,
@@ -209,6 +216,13 @@ export const DEFAULT_PRICING = {
reasoning: 3.0,
cache_creation: 0.5,
},
+ "deepseek-v3.2": {
+ input: 0.5,
+ output: 2.0,
+ cached: 0.25,
+ reasoning: 3.0,
+ cache_creation: 0.5,
+ },
"deepseek-v3.2-reasoner": {
input: 0.75,
output: 3.0,
@@ -524,6 +538,13 @@ export const DEFAULT_PRICING = {
reasoning: 18.0,
cache_creation: 2.0,
},
+ "gemini-3.1-pro-preview": {
+ input: 2.0,
+ output: 12.0,
+ cached: 0.25,
+ reasoning: 18.0,
+ cache_creation: 2.0,
+ },
"gemini-2.5-pro": {
input: 2.0,
output: 12.0,
@@ -601,6 +622,20 @@ export const DEFAULT_PRICING = {
// GLM
glm: {
+ "glm-5": {
+ input: 1.0,
+ output: 3.2,
+ cached: 0.5,
+ reasoning: 4.8,
+ cache_creation: 1.0,
+ },
+ "glm-5-turbo": {
+ input: 1.2,
+ output: 4.0,
+ cached: 0.6,
+ reasoning: 6.0,
+ cache_creation: 1.2,
+ },
"glm-4.7": {
input: 0.75,
output: 3.0,
@@ -653,6 +688,13 @@ export const DEFAULT_PRICING = {
// MiniMax
minimax: {
+ "minimax-m2.1": {
+ input: 0.5,
+ output: 2.0,
+ cached: 0.25,
+ reasoning: 3.0,
+ cache_creation: 0.5,
+ },
"MiniMax-M2.1": {
input: 0.5,
output: 2.0,
@@ -762,6 +804,7 @@ export const DEFAULT_PRICING = {
// Nvidia
nvidia: {
+ "nvidia/gpt-oss-120b": { input: 0, output: 0, cached: 0, reasoning: 0, cache_creation: 0 },
"openai/gpt-oss-120b": { input: 0, output: 0, cached: 0, reasoning: 0, cache_creation: 0 },
"gpt-oss-120b": { input: 0, output: 0, cached: 0, reasoning: 0, cache_creation: 0 },
"moonshotai/kimi-k2.5": { input: 0, output: 0, cached: 0, reasoning: 0, cache_creation: 0 },
diff --git a/src/shared/validation/schemas.ts b/src/shared/validation/schemas.ts
index 033ba1c384..dbe7758381 100644
--- a/src/shared/validation/schemas.ts
+++ b/src/shared/validation/schemas.ts
@@ -52,6 +52,7 @@ const comboStrategySchema = z.enum([
"least-used",
"cost-optimized",
"strict-random",
+ "auto",
]);
const comboRuntimeConfigSchema = z
@@ -139,6 +140,12 @@ export const updateSettingsSchema = z.object({
.optional(),
wildcardAliases: z.array(z.object({ pattern: z.string(), target: z.string() })).optional(),
stickyRoundRobinLimit: z.number().int().min(0).max(1000).optional(),
+ // Auto intent classifier settings (multilingual routing)
+ intentDetectionEnabled: z.boolean().optional(),
+ intentSimpleMaxWords: z.number().int().min(1).max(500).optional(),
+ intentExtraCodeKeywords: z.array(z.string().max(100)).optional(),
+ intentExtraReasoningKeywords: z.array(z.string().max(100)).optional(),
+ intentExtraSimpleKeywords: z.array(z.string().max(100)).optional(),
// Protocol toggles (default: disabled)
mcpEnabled: z.boolean().optional(),
a2aEnabled: z.boolean().optional(),
diff --git a/src/shared/validation/settingsSchemas.ts b/src/shared/validation/settingsSchemas.ts
index 0029677c90..980a9afc08 100644
--- a/src/shared/validation/settingsSchemas.ts
+++ b/src/shared/validation/settingsSchemas.ts
@@ -30,6 +30,12 @@ export const updateSettingsSchema = z.object({
.optional(),
wildcardAliases: z.array(z.object({ pattern: z.string(), target: z.string() })).optional(),
stickyRoundRobinLimit: z.number().int().min(0).max(1000).optional(),
+ // Auto intent classifier settings (multilingual routing)
+ intentDetectionEnabled: z.boolean().optional(),
+ intentSimpleMaxWords: z.number().int().min(1).max(500).optional(),
+ intentExtraCodeKeywords: z.array(z.string().max(100)).optional(),
+ intentExtraReasoningKeywords: z.array(z.string().max(100)).optional(),
+ intentExtraSimpleKeywords: z.array(z.string().max(100)).optional(),
// Protocol toggles (default: disabled)
mcpEnabled: z.boolean().optional(),
mcpTransport: z.enum(["stdio", "sse", "streamable-http"]).optional(),
diff --git a/src/sse/handlers/chat.ts b/src/sse/handlers/chat.ts
index bd0b0e59c8..79f0eeb055 100644
--- a/src/sse/handlers/chat.ts
+++ b/src/sse/handlers/chat.ts
@@ -46,6 +46,10 @@ import {
applyTaskAwareRouting,
getTaskRoutingConfig,
} from "@omniroute/open-sse/services/taskAwareRouter.ts";
+import {
+ isFallbackDecision,
+ shouldUseFallback,
+} from "@omniroute/open-sse/services/emergencyFallback.ts";
/**
* Handle chat completion request
@@ -270,7 +274,8 @@ async function handleSingleModelChat(
request: any = null,
comboName: string | null = null,
apiKeyInfo: any = null,
- telemetry: any = null
+ telemetry: any = null,
+ runtimeOptions: { emergencyFallbackTried?: boolean } = {}
) {
// 1. Resolve model → provider/model
const resolved = await resolveModelOrError(modelStr, body);
@@ -372,6 +377,53 @@ async function handleSingleModelChat(
return result.response;
}
+ // Emergency fallback for budget exhaustion (402 / billing / quota keywords):
+ // reroute to a free model (default provider/model: nvidia + openai/gpt-oss-120b) exactly once.
+ if (!runtimeOptions.emergencyFallbackTried) {
+ const fallbackDecision = shouldUseFallback(
+ Number(result.status || 0),
+ String(result.error || ""),
+ Array.isArray(body?.tools) && body.tools.length > 0
+ );
+
+ if (isFallbackDecision(fallbackDecision)) {
+ const fallbackModelStr = `${fallbackDecision.provider}/${fallbackDecision.model}`;
+ const currentModelStr = `${provider}/${model}`;
+
+ if (fallbackModelStr !== currentModelStr) {
+ const fallbackBody = { ...body, model: fallbackModelStr };
+
+ // Cap output on emergency fallback to avoid unexpected long responses.
+ const maxTokens = Math.min(
+ Number(
+ fallbackBody.max_tokens ??
+ fallbackBody.max_completion_tokens ??
+ fallbackDecision.maxOutputTokens
+ ) || fallbackDecision.maxOutputTokens,
+ fallbackDecision.maxOutputTokens
+ );
+ fallbackBody.max_tokens = maxTokens;
+ fallbackBody.max_completion_tokens = maxTokens;
+
+ log.warn(
+ "EMERGENCY_FALLBACK",
+ `${currentModelStr} -> ${fallbackModelStr} | reason=${fallbackDecision.reason}`
+ );
+
+ return handleSingleModelChat(
+ fallbackBody,
+ fallbackModelStr,
+ clientRawRequest,
+ request,
+ comboName,
+ apiKeyInfo,
+ telemetry,
+ { ...runtimeOptions, emergencyFallbackTried: true }
+ );
+ }
+ }
+ }
+
// 6. Mark account as quota-exhausted on 429 response
if (result.status === 429) {
markAccountExhaustedFrom429(credentials.connectionId, provider);