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
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
fix(combo): sessionless combo stickiness + reasoning-aware readiness (#3825) (#3847)
Diego Rodrigues de Sa e Souza70319eb8315b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cf1c80c7a0..7d8257096d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@### 🐛 Fixed- **fix(intelligence): run pricing + models.dev sync from the live startup path** — like the Arena ELO sync (v3.8.24), the external **pricing sync** (`PRICING_SYNC_ENABLED`) and the **models.dev capability sync** (Settings → AI toggle) were only initialized from `server-init.ts`, which the Next standalone runtime never executes — and models.dev had no caller at all. Their toggles were inert in production. Both are now initialized from `instrumentation-node.ts` (self-gated, opt-in preserved, non-blocking, never fatal). (thanks @diegosouzapw)+- **fix(combo): restore sessionless combo stickiness + reasoning-aware readiness (504 / TPS regression after v3.8.14)** — #3399 (v3.8.16) replaced the `<omniModel>`-tag combo pinning with a server-side context-cache pin gated on a client `sessionId`. Clients that send no session id (most OpenAI-compatible tools) lost combo stickiness, so combos re-ran strategy selection every turn → upstream prompt-cache misses → cold high-reasoning starts (~78s) → intermittent `[504] Upstream request did not return response headers` + TPS collapse (only on combos). The pin now falls back to a stable per-conversation fingerprint (`extractSessionAffinityKey(body)`) when no session id is present — **only when `context_cache_protection` is on**, so #3399's anti-leak behaviour is preserved. Separately, the stream-readiness window now grants the +30s reasoning budget **unconditionally** for high-reasoning Codex GPT-5.x (small high-reasoning prompts were 504-ing at the 80s base regardless of stickiness). ([#3825](https://github.com/diegosouzapw/OmniRoute/issues/3825) — thanks @bypanghu)- **test(combo): cover the `skipProviderBreaker` consumer gate** — the producer was tested but the consumer (whether a failed combo target trips the whole-provider circuit breaker) was not; the breaker decision is now an exported pure predicate (`shouldRecordProviderBreakerFailure`, behaviour-identical) with direct tests asserting a `connection_cooldown` 503 does not trip the breaker while a plain 503 does. Closes another deferred test gap from [#2743](https://github.com/diegosouzapw/OmniRoute/issues/2743). (thanks @diegosouzapw)- **fix(providers): surface the real Devin error + correct the Windsurf auth instructions** — Devin chat returned a generic 502 "Invalid SSE response for non-streaming request" that swallowed the real cause (e.g. "Devin CLI not found"): an error-only SSE chunk (no `choices`) is now propagated with its sanitized message. The Windsurf "Visit windsurf.com/show-auth-token" instruction (the bare URL shows no token without an IDE-supplied `?state=`) now directs users to the `Windsurf: Provide Auth Token` command-palette flow. ([#3324](https://github.com/diegosouzapw/OmniRoute/issues/3324) — thanks @mikmaneggahommie)- **fix(grok-web): clearer 403 message for anti-bot / IP-reputation blocks** — a Grok Web subscription validating from a flagged datacenter/VPS IP got a 403 that read like an invalid cookie, sending users to chase a cookie that was actually fine. A non-auth 403 (Cloudflare challenge / anti-bot body) now returns a message stating the cookie is likely OK and the block is IP-reputation-based — retry from a residential IP or configure a proxy (auth-shaped 403s keep the re-paste guidance). ([#3474](https://github.com/diegosouzapw/OmniRoute/issues/3474) — thanks @friedtofu1608)diff --git a/file-size-baseline.json b/file-size-baseline.jsonindex 1d3ab53a83..39e3377f15 100644--- a/file-size-baseline.json+++ b/file-size-baseline.json@@ -28,7 +28,7 @@"open-sse/services/batchProcessor.ts": 828,"open-sse/services/browserBackedChat.ts": 850,"open-sse/services/claudeCodeCompatible.ts": 1202,- "open-sse/services/combo.ts": 5164,+ "open-sse/services/combo.ts": 5198,"open-sse/services/rateLimitManager.ts": 1017,"open-sse/services/tokenRefresh.ts": 1997,"open-sse/services/usage.ts": 3394,@@ -122,5 +122,6 @@"_rebaseline_2026_06_13_3324_windsurf_devin": "Re-baseline #3324 (windsurf auth text + devin error propagation): route.ts 897→903 (+6, texto da instrução windsurf→fluxo command-palette) + sseParser.ts ADICIONADO como frozen 812 (era 746, +66 = helper extractSSEErrorMessage que faz surface do erro real SSE em vez do 502 genérico). 812 fica 12 acima do cap 800 — helper coeso no parser de SSE, congelado com justificativa (precedente providerLimits/useProviderConnections).","_rebaseline_2026_06_13_2743d_skipbreaker": "Re-baseline #2743 gap-d (testar consumer do skipProviderBreaker): combo.ts 5131→5162 (+31). Crescimento = extração do boolean inline da decisão de circuit-breaker para o predicado puro EXPORTADO shouldRecordProviderBreakerFailure() (byte-idêntico) + JSDoc, para torná-lo unit-testável sem o harness completo de combo. Shrink estrutural segue com #3501.","_rebaseline_2026_06_13_v3825_prettier_reconcile": "Reconciliação tardia: o prettier do pre-commit reformatou 3 arquivos DEPOIS da medição de file-size dos PRs, inflando linhas além do baseline setado — OAuthModal.tsx 956→960 e providers.ts 3146→3147 (#3324), combo.ts 5162→5164 (#2743d). Bumps de reformatação automática (sem lógica nova). LIÇÃO: medir file-size pós-commit (pós-prettier), não antes.",- "_rebaseline_2026_06_14_3826_release_drift": "Re-baseline release/v3.8.25 drift already documented from #3809 owner changes: ProxyRegistryManager.tsx 1072→1089, sidebarVisibility.ts 990→1006, schemas.ts 2519→2522. This PR does not touch those source files; updating the frozen values restores Fast Quality Gates on the current release branch."+ "_rebaseline_2026_06_14_3826_release_drift": "Re-baseline release/v3.8.25 drift already documented from #3809 owner changes: ProxyRegistryManager.tsx 1072→1089, sidebarVisibility.ts 990→1006, schemas.ts 2519→2522. This PR does not touch those source files; updating the frozen values restores Fast Quality Gates on the current release branch.",+ "_rebaseline_2026_06_14_3825_combo_stickiness": "Re-baseline #3825 (sessionless combo stickiness + reasoning-aware readiness): combo.ts 5164→5198 (+34, pós-prettier). Crescimento = deriveComboSessionKey() + effectiveSessionId threading nos sites de read/write do pin server-side. streamReadinessPolicy.ts não-frozen (sob cap). Lógica coesa no handler de combo; não-extraível."}diff --git a/open-sse/services/combo.ts b/open-sse/services/combo.tsindex 5503e5e7e5..431efd2a02 100644--- a/open-sse/services/combo.ts+++ b/open-sse/services/combo.ts@@ -52,6 +52,7 @@ import {getLastSessionModel,getHandoff,} from "../../src/lib/db/contextHandoffs.ts";+import { extractSessionAffinityKey } from "@/sse/services/auth";import { resolveModelLockoutSettings } from "../../src/lib/resilience/modelLockoutSettings";import { fetchCodexQuota } from "./codexQuotaFetcher.ts";import { getQuotaFetcher } from "./quotaPreflight.ts";@@ -3033,6 +3034,28 @@ export async function expandAutoComboCandidatePool(return eligibleTargets;}+/**+ * Derive a STABLE per-conversation session key for combo context-cache pinning when+ * the client did not provide an explicit session id (#3825).+ *+ * Most OpenAI-compatible clients send no session id, so the server-side pin added by+ * #3399 (gated on `relayOptions?.sessionId`) never engaged → combos rotated every turn,+ * causing upstream prompt-cache misses, cold high-reasoning starts and intermittent+ * 504s. We reuse `extractSessionAffinityKey(body)` (the same conversation fingerprint+ * used for codex failover affinity), which hashes the first user/system message — stable+ * across turns of the same conversation and identical on turn 2 of a continued chat.+ *+ * Returns null when no stable fingerprint is available (e.g. empty body), in which case+ * the caller falls back to NO pinning — preserving prior behavior rather than guessing.+ */+function deriveComboSessionKey(body: Record<string, unknown>): string | null {+ try {+ return extractSessionAffinityKey(body) ?? null;+ } catch {+ return null;+ }+}+/*** Handle combo chat with fallback.* @param {Object} options@@ -3073,13 +3096,22 @@ export async function handleComboChat({);// ── Server-side context cache pinning (replaces <omniModel> tag roundtrip) ─// Uses session_model_history — no client-side tag injection, no visible output pollution.+ //+ // #3825: when the client sends no session id (most OpenAI-compatible clients), fall+ // back to a stable conversation fingerprint derived from the body so the combo still+ // re-pins to the same model across turns. ONLY engaged when context_cache_protection+ // is truthy — when the toggle is off, behavior is unchanged (combos rotate as before,+ // no pin read/write, no <omniModel> tag).+ const effectiveSessionId: string | null = combo.context_cache_protection+ ? (relayOptions?.sessionId ?? deriveComboSessionKey(body))+ : null;let pinnedModel: string | null = null;if (combo.context_cache_protection &&- relayOptions?.sessionId &&+ effectiveSessionId &&!(body as Record<string, unknown>)?.[SKIP_UNIVERSAL_HANDOFF_FLAG]) {- const pinned = getLastSessionModel(relayOptions.sessionId, combo.name);+ const pinned = getLastSessionModel(effectiveSessionId, combo.name);if (pinned) {body = { ...body, model: pinned };pinnedModel = pinned;@@ -4053,13 +4085,15 @@ export async function handleComboChat({// Context cache pinning: record model usage for session-based pinning// (independent of universal handoff — always fires when context_cache_protection is on)+ // #3825: write under the SAME effectiveSessionId used by the read site so a+ // sessionless conversation re-pins to this model on its next turn.if (combo.context_cache_protection &&- relayOptions?.sessionId &&+ effectiveSessionId &&!(body as Record<string, unknown>)?.[SKIP_UNIVERSAL_HANDOFF_FLAG]) {recordSessionModelUsage(- relayOptions.sessionId,+ effectiveSessionId,combo.name,modelStr,provider,diff --git a/open-sse/utils/streamReadinessPolicy.ts b/open-sse/utils/streamReadinessPolicy.tsindex ba3370b4d3..065256044b 100644--- a/open-sse/utils/streamReadinessPolicy.ts+++ b/open-sse/utils/streamReadinessPolicy.ts@@ -35,10 +35,37 @@ function estimateBodyChars(body: StreamReadinessBody): number {}}-function isCodexGpt55(provider?: string | null, model?: string | null): boolean {+function isCodexGpt5x(provider?: string | null, model?: string | null): boolean {const normalizedProvider = (provider || "").toLowerCase();const normalizedModel = (model || "").toLowerCase();- return normalizedProvider === "codex" && normalizedModel.includes("gpt-5.5");+ // Match the gpt-5.x family (gpt-5, gpt-5.1, gpt-5.5, ...) on the codex provider.+ return normalizedProvider === "codex" && /gpt-5(\.\d+)?/.test(normalizedModel);+}++/**+ * High-reasoning Codex GPT-5.x targets do a cold, expensive reasoning warm-up+ * (~78s TTFB) even for small prompts. Detect "high" reasoning effort either from+ * the model alias suffix (`...-high`) or from the request body's reasoning effort+ * field (OpenAI `reasoning_effort` or Responses API `reasoning.effort`).+ */+function isHighReasoningEffort(+ model: string | null | undefined,+ body: StreamReadinessBody+): boolean {+ const normalizedModel = (model || "").toLowerCase();+ if (/-high\b/.test(normalizedModel) || normalizedModel.endsWith("-high")) return true;++ const effort = (() => {+ const direct = body?.["reasoning_effort"];+ if (typeof direct === "string") return direct;+ const reasoning = body?.["reasoning"];+ if (reasoning && typeof reasoning === "object") {+ const nested = (reasoning as Record<string, unknown>)["effort"];+ if (typeof nested === "string") return nested;+ }+ return "";+ })();+ return effort.toLowerCase() === "high";}export function resolveStreamReadinessTimeout(@@ -58,7 +85,8 @@ export function resolveStreamReadinessTimeout(const itemCount = Math.max(inputCount, messageCount);const toolCount = countArrayField(input.body, "tools");const estimatedChars = estimateBodyChars(input.body);- const codexGpt55 = isCodexGpt55(input.provider, input.model);+ const codexGpt5x = isCodexGpt5x(input.provider, input.model);+ const codexHighReasoning = codexGpt5x && isHighReasoningEffort(input.model, input.body);if (itemCount > VERY_LARGE_ITEM_THRESHOLD) {timeoutMs += 45_000;@@ -81,7 +109,18 @@ export function resolveStreamReadinessTimeout(reasons.push("large_payload");}- if (codexGpt55 && (itemCount > LARGE_ITEM_THRESHOLD || toolCount >= TOOL_HEAVY_THRESHOLD)) {+ // #3825: high-reasoning Codex GPT-5.x cold-starts at ~78s TTFB even for tiny+ // prompts, so the +30s readiness budget must fire UNCONDITIONALLY for the+ // high-effort case — the 80s base alone produced intermittent 504s at the+ // readiness window. The legacy large-request bump still applies to non-high+ // codex GPT-5.x requests (large history / tool-heavy).+ if (codexHighReasoning) {+ timeoutMs += 30_000;+ reasons.push("codex_gpt_5_5_high_reasoning");+ } else if (+ codexGpt5x &&+ (itemCount > LARGE_ITEM_THRESHOLD || toolCount >= TOOL_HEAVY_THRESHOLD)+ ) {timeoutMs += 30_000;reasons.push("codex_gpt_5_5_large_responses");}diff --git a/tests/unit/combo-sessionless-pin-3825.test.ts b/tests/unit/combo-sessionless-pin-3825.test.tsnew file mode 100644index 0000000000..d8bcd2207f--- /dev/null+++ b/tests/unit/combo-sessionless-pin-3825.test.ts@@ -0,0 +1,184 @@+import test from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";++// Regression for #3825: PR #3399 disabled the <omniModel>-tag history pinning and+// replaced it with a server-side session pin in combo.ts that is gated on+// `relayOptions?.sessionId`. Most OpenAI-compatible clients send no session id, so+// the read/write never fired → combos lost model stickiness → every turn re-ran the+// strategy (round-robin rotated) → upstream prompt-cache misses, cold high-reasoning+// starts, intermittent 504s. The fix derives a stable per-conversation key from the+// request body when no session id is present, so a combo re-pins to the same model+// across turns of the same conversation — but ONLY when context_cache_protection is on.++const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-combo-pin-3825-"));+const ORIGINAL_DATA_DIR = process.env.DATA_DIR;+process.env.DATA_DIR = TEST_DATA_DIR;++const { handleComboChat } = await import("../../open-sse/services/combo.ts");+const { clearSessions } = await import("../../open-sse/services/sessionManager.ts");+const core = await import("../../src/lib/db/core.ts");++function createLog() {+ const entries: any[] = [];+ return {+ info: (tag: any, msg: any) => entries.push({ level: "info", tag, msg }),+ warn: (tag: any, msg: any) => entries.push({ level: "warn", tag, msg }),+ error: (tag: any, msg: any) => entries.push({ level: "error", tag, msg }),+ debug: (tag: any, msg: any) => entries.push({ level: "debug", tag, msg }),+ entries,+ };+}++function okResponse(body: any = { choices: [{ message: { content: "ok" } }] }) {+ return new Response(JSON.stringify(body), {+ status: 200,+ headers: { "content-type": "application/json" },+ });+}++function waitForBackgroundWork() {+ return new Promise((resolve) => setTimeout(resolve, 25));+}++// A stable conversation body — the first user message is identical across turns so+// extractSessionAffinityKey() fingerprints the same conversation each time.+function conversationBody() {+ return {+ messages: [{ role: "user", content: "Refactor the streaming handler for combos." }],+ };+}++async function cleanupTestDataDir() {+ let lastError;+ for (let attempt = 0; attempt < 5; attempt += 1) {+ try {+ core.resetDbInstance();+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+ return;+ } catch (error: any) {+ lastError = error;+ await new Promise((resolve) => setTimeout(resolve, 25));+ }+ }+ if (lastError) throw lastError;+}++test.beforeEach(async () => {+ clearSessions();+ await cleanupTestDataDir();+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });+});++test.after(async () => {+ clearSessions();+ if (ORIGINAL_DATA_DIR === undefined) {+ delete process.env.DATA_DIR;+ } else {+ process.env.DATA_DIR = ORIGINAL_DATA_DIR;+ }+ await cleanupTestDataDir();+});++test("context_cache_protection ON + NO sessionId: combo re-pins to the same model across turns (#3825)", async () => {+ const calls: string[] = [];+ // Priority strategy: turn 1 deterministically tries model-a first, but model-a returns+ // an empty (quality-failed) response so the combo falls through to model-b and records+ // model-b as the session model (this exercises the real main-loop write site).+ const combo = {+ name: "sticky-priority",+ strategy: "priority",+ context_cache_protection: true,+ models: ["model-a", "model-b"],+ config: { maxRetries: 0 },+ };++ const handleSingleModel = async (_body: any, modelStr: string) => {+ calls.push(modelStr);+ if (modelStr === "model-a") {+ return okResponse({ choices: [{ message: { content: "" } }] }); // empty → fall through+ }+ return okResponse({ choices: [{ message: { content: "fallback ok" } }] });+ };++ // Two sequential turns of the SAME conversation, NO relayOptions.sessionId.+ for (let turn = 0; turn < 2; turn += 1) {+ const result = await handleComboChat({+ body: conversationBody(),+ combo,+ handleSingleModel: handleSingleModel as any,+ isModelAvailable: async () => true,+ log: createLog(),+ settings: null,+ relayOptions: null as any,+ allCombos: null,+ });+ assert.equal(result.ok, true);+ // Let the best-effort session-model write settle before the next turn reads it.+ await waitForBackgroundWork();+ }++ // Turn 1 records model-b (the model that actually succeeded). With the fix, turn 2 reads+ // that pin via the derived sessionless key and dispatches model-b DIRECTLY, skipping+ // model-a entirely → calls === [a, b, b]. Without the fix the derived key is never used,+ // so turn 2 re-runs priority from the top → calls === [a, b, a, b].+ assert.deepEqual(+ calls,+ ["model-a", "model-b", "model-b"],+ "turn 2 must re-pin to model-b (turn 1's selected model) and skip model-a"+ );+});++test("context_cache_protection OFF + NO sessionId: no pin, strategy re-runs each turn, no <omniModel> tag (#3825 scope guard)", async () => {+ const calls: string[] = [];+ const forwardedContents: string[] = [];+ // Identical priority+failover setup as the positive case, but with the toggle OFF.+ const combo = {+ name: "unprotected-priority",+ strategy: "priority",+ // context_cache_protection intentionally omitted (falsy) — #3399 behavior preserved.+ models: ["model-a", "model-b"],+ config: { maxRetries: 0 },+ };++ const handleSingleModel = async (forwardedBody: any, modelStr: string) => {+ calls.push(modelStr);+ const msgs = Array.isArray(forwardedBody?.messages) ? forwardedBody.messages : [];+ for (const m of msgs) {+ if (typeof m?.content === "string") forwardedContents.push(m.content);+ }+ if (modelStr === "model-a") {+ return okResponse({ choices: [{ message: { content: "" } }] });+ }+ return okResponse({ choices: [{ message: { content: "fallback ok" } }] });+ };++ for (let turn = 0; turn < 2; turn += 1) {+ const result = await handleComboChat({+ body: conversationBody(),+ combo,+ handleSingleModel: handleSingleModel as any,+ isModelAvailable: async () => true,+ log: createLog(),+ settings: null,+ relayOptions: null as any,+ allCombos: null,+ });+ assert.equal(result.ok, true);+ await waitForBackgroundWork();+ }++ // Toggle OFF → no pin is recorded or read → turn 2 re-runs priority from the top,+ // re-trying model-a before falling through to model-b → [a, b, a, b].+ assert.deepEqual(+ calls,+ ["model-a", "model-b", "model-a", "model-b"],+ "with protection OFF the combo must re-run strategy each turn (no sessionless pin)"+ );+ assert.ok(+ forwardedContents.every((c) => !c.includes("<omniModel>")),+ "no <omniModel> tag may be injected into the forwarded body (#454/#3399)"+ );+});diff --git a/tests/unit/stream-readiness-policy.test.ts b/tests/unit/stream-readiness-policy.test.tsindex 904b37e011..04b636d01b 100644--- a/tests/unit/stream-readiness-policy.test.ts+++ b/tests/unit/stream-readiness-policy.test.ts@@ -63,6 +63,49 @@ test("gives Codex GPT-5.5 large Responses requests extra readiness budget", () =assert.ok(result.reasons.includes("codex_gpt_5_5_large_responses"));});+test("gives high-reasoning Codex GPT-5.x extra readiness budget even for SMALL requests (#3825)", () => {+ // Regression for #3825: a small-prompt high-reasoning codex target has ~78s TTFB+ // (cold high-reasoning start). Before the fix it only received the 80s base and 504'd+ // at the readiness window. The reasoning-aware bump must fire UNCONDITIONALLY for+ // high-effort codex, regardless of request size.+ const result = resolveStreamReadinessTimeout({+ baseTimeoutMs: 80_000,+ provider: "codex",+ model: "gpt-5.5-high",+ body: { messages: items(3), tools: tools(2) },+ });++ assert.ok(+ result.timeoutMs >= 110_000,+ `expected >= 110000ms for small high-reasoning codex, got ${result.timeoutMs}`+ );+ assert.ok(result.reasons.includes("codex_gpt_5_5_high_reasoning"));+});++test("does NOT bump small NON-high codex requests (#3825 scope guard)", () => {+ const result = resolveStreamReadinessTimeout({+ baseTimeoutMs: 80_000,+ provider: "codex",+ model: "gpt-5.5",+ body: { messages: items(3), tools: tools(2) },+ });++ assert.equal(result.timeoutMs, 80_000);+ assert.deepEqual(result.reasons, ["base"]);+});++test("does NOT bump small high-reasoning NON-codex requests (#3825 scope guard)", () => {+ const result = resolveStreamReadinessTimeout({+ baseTimeoutMs: 80_000,+ provider: "openai",+ model: "gpt-5.5-high",+ body: { messages: items(3), tools: tools(2) },+ });++ assert.equal(result.timeoutMs, 80_000);+ assert.deepEqual(result.reasons, ["base"]);+});+test("caps adaptive timeout at maxTimeoutMs", () => {const result = resolveStreamReadinessTimeout({baseTimeoutMs: 30_000,