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): normalize upstream Headers for Node 24 undici interop (#2751) (#2823)
Diego Rodrigues de Sa e Souzac02b6ea00881
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 480ce042d1..513d558f71 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -40,6 +40,7 @@- **gemini:** translate signature-less Gemini thinking model tool calls to text parts to prevent `400 "missing thought_signature"` errors (#2801 — thanks @herjarsa)- **translator:** strip `safety_identifier` from `/v1/responses` body before forwarding to Chat Completions upstream; fixes LobeHub-originated `400` errors (#2770)- **warning-cleanup:** relax node engine constraint to `>=22.0.0` and clean dependencies (keeping `marked-terminal` to prevent TUI REPL crash) (#2792 — thanks @oyi77)+- **combo:** normalize upstream Headers into a plain object before classification to avoid Node 24 / undici cross-instance `Cannot read private member #headers` crash on combo failover (#2751)- **translator:** silently drop `tool_search` built-in tool type instead of returning 400 — newer Codex clients send `tool_search` as a Responses API built-in with no Chat Completions equivalent (#2766)- **usage:** un-invert GitHub Copilot Free / limited plan quota — `limited_user_quotas` is the *remaining* count, not used, so the dashboard now shows 100% when the quota is untouched and 0% when fully exhausted (#2876 — thanks @androw)- **fix(cli):** register openclaw in the CLI tool-detector so it appears in `omniroute status` alongside its existing API and config support ([#2833](https://github.com/diegosouzapw/OmniRoute/issues/2833))diff --git a/open-sse/executors/codex.ts b/open-sse/executors/codex.tsindex d3dddc7e7e..f7b5ba3192 100644--- a/open-sse/executors/codex.ts+++ b/open-sse/executors/codex.ts@@ -155,13 +155,15 @@ export interface CodexQuotaSnapshot {* x-codex-5h-usage / x-codex-5h-limit / x-codex-5h-reset-at* x-codex-7d-usage / x-codex-7d-limit / x-codex-7d-reset-at*/-export function parseCodexQuotaHeaders(headers: Headers): CodexQuotaSnapshot | null {- const usage5h = headers.get("x-codex-5h-usage");- const limit5h = headers.get("x-codex-5h-limit");- const resetAt5h = headers.get("x-codex-5h-reset-at");- const usage7d = headers.get("x-codex-7d-usage");- const limit7d = headers.get("x-codex-7d-limit");- const resetAt7d = headers.get("x-codex-7d-reset-at");+export function parseCodexQuotaHeaders(+ headers: Record<string, string>+): CodexQuotaSnapshot | null {+ const usage5h = headers["x-codex-5h-usage"] ?? null;+ const limit5h = headers["x-codex-5h-limit"] ?? null;+ const resetAt5h = headers["x-codex-5h-reset-at"] ?? null;+ const usage7d = headers["x-codex-7d-usage"] ?? null;+ const limit7d = headers["x-codex-7d-limit"] ?? null;+ const resetAt7d = headers["x-codex-7d-reset-at"] ?? null;// Return null if none of the quota headers are present (not a quota-aware response)if (!usage5h && !limit5h && !resetAt5h && !usage7d && !limit7d && !resetAt7d) {diff --git a/open-sse/handlers/chatCore.ts b/open-sse/handlers/chatCore.tsindex a8d0d665c9..26f8dded0b 100644--- a/open-sse/handlers/chatCore.ts+++ b/open-sse/handlers/chatCore.ts@@ -1,4 +1,5 @@import { CORS_HEADERS } from "../utils/cors.ts";+import { normalizeHeaders } from "../utils/headers.ts";import { detectFormatFromEndpoint, getTargetFormat } from "../services/provider.ts";import { injectSystemPrompt } from "../services/systemPrompt.ts";import { translateRequest, needsTranslation } from "../translator/index.ts";@@ -1618,13 +1619,13 @@ export async function handleChatCore({};const persistCodexQuotaState = async (- headers: Headers | Record<string, string> | null,+ headers: Record<string, string> | null,status = 0) => {if (provider !== "codex" || !connectionId || !headers) return;try {- const quota = parseCodexQuotaHeaders(headers as Headers);+ const quota = parseCodexQuotaHeaders(headers);if (!quota) return;const existingProviderData =@@ -3667,9 +3668,10 @@ export async function handleChatCore({.clone().text().catch(() => "");- const decision = classifyModelScope429(bodyPeek, res.response.headers);+ const normalizedHeaders = normalizeHeaders(res.response.headers);+ const decision = classifyModelScope429(bodyPeek, normalizedHeaders);if (decision.retryable) {- const delay = getModelScopeRetryDelayMs(res.response.headers, attempts);+ const delay = getModelScopeRetryDelayMs(normalizedHeaders, attempts);log?.warn?.("MODELSCOPE_RETRY",`429 ${decision.kind}; retrying in ${delay}ms (model remaining: ${decision.snapshot.modelRemaining ?? "unknown"})`@@ -3688,7 +3690,8 @@ export async function handleChatCore({attempts < maxAttempts - 1) {const failedConnectionId = credentials?.connectionId || connectionId;- const retryAfterHeader = res.response.headers.get("retry-after");+ const normalizedHeaders = normalizeHeaders(res.response.headers);+ const retryAfterHeader = normalizedHeaders["retry-after"] ?? null;const retryAfterMs = retryAfterHeader? Number.parseFloat(retryAfterHeader) * 1000: null;@@ -3806,27 +3809,7 @@ export async function handleChatCore({}const statusText = rawResult.response.statusText;- const rawHeaders = rawResult.response.headers;- const headersObj: Record<string, string> = {};- if (rawHeaders) {- if (typeof rawHeaders.forEach === "function") {- try {- rawHeaders.forEach((v: string, k: string) => {- headersObj[k] = v;- });- } catch {- try {- for (const [k, v] of rawHeaders as unknown as Iterable<[string, string]>) {- headersObj[k] = v;- }- } catch {- Object.assign(headersObj, rawHeaders);- }- }- } else {- Object.assign(headersObj, rawHeaders);- }- }+ const headersObj = normalizeHeaders(rawResult.response.headers);const headers = new Headers(headersObj);stripStaleForwardingHeaders(headers);const contentType = (headers.get("content-type") || "").toLowerCase();@@ -4174,7 +4157,7 @@ export async function handleChatCore({}}- await persistCodexQuotaState(providerResponse.headers, providerResponse.status);+ await persistCodexQuotaState(normalizeHeaders(providerResponse.headers), providerResponse.status);// Check provider response - return error info for fallback handlingif (!providerResponse.ok) {@@ -4203,7 +4186,7 @@ export async function handleChatCore({// T06/T10/T36: classify provider errors and persist terminal account states.let errorType = classifyProviderError(statusCode, message, provider);if (statusCode === 429 && isModelScope()) {- const decision = classifyModelScope429(message, providerResponse.headers);+ const decision = classifyModelScope429(message, normalizeHeaders(providerResponse.headers));errorType =decision.kind === "quota_exhausted"? PROVIDER_ERROR_TYPES.QUOTA_EXHAUSTEDdiff --git a/open-sse/services/modelscopePolicy.ts b/open-sse/services/modelscopePolicy.tsindex af284aa347..44da231b17 100644--- a/open-sse/services/modelscopePolicy.ts+++ b/open-sse/services/modelscopePolicy.ts@@ -48,18 +48,27 @@ export function isModelScopeProvider(return MODELSCOPE_HOST_MARKERS.some((marker) => baseUrl.includes(marker));}-export function parseModelScopeRateLimitHeaders(headers: Headers): ModelScopeRateLimitSnapshot {+export function parseModelScopeRateLimitHeaders(+ headers: Record<string, string>+): ModelScopeRateLimitSnapshot {return {modelRemaining: parseHeaderInteger(- headers.get("modelscope-ratelimit-model-requests-remaining")+ headers["modelscope-ratelimit-model-requests-remaining"] ?? null),- modelLimit: parseHeaderInteger(headers.get("modelscope-ratelimit-model-requests-limit")),- totalRemaining: parseHeaderInteger(headers.get("modelscope-ratelimit-requests-remaining")),- totalLimit: parseHeaderInteger(headers.get("modelscope-ratelimit-requests-limit")),+ modelLimit: parseHeaderInteger(+ headers["modelscope-ratelimit-model-requests-limit"] ?? null+ ),+ totalRemaining: parseHeaderInteger(+ headers["modelscope-ratelimit-requests-remaining"] ?? null+ ),+ totalLimit: parseHeaderInteger(headers["modelscope-ratelimit-requests-limit"] ?? null),};}-export function classifyModelScope429(errorText: string, headers: Headers): ModelScope429Decision {+export function classifyModelScope429(+ errorText: string,+ headers: Record<string, string>+): ModelScope429Decision {const snapshot = parseModelScopeRateLimitHeaders(headers);const lower = String(errorText || "").toLowerCase();@@ -78,8 +87,8 @@ export function classifyModelScope429(errorText: string, headers: Headers): Modereturn { kind: "rate_limited", retryable: true, snapshot };}-export function getModelScopeRetryDelayMs(headers: Headers, attempt: number): number {- const retryAfter = headers.get("retry-after");+export function getModelScopeRetryDelayMs(headers: Record<string, string>, attempt: number): number {+ const retryAfter = headers["retry-after"] ?? null;if (retryAfter) {const parsed = Number.parseFloat(retryAfter);if (Number.isFinite(parsed) && parsed > 0) return parsed * 1000;diff --git a/open-sse/utils/headers.ts b/open-sse/utils/headers.tsnew file mode 100644index 0000000000..d9853aafac--- /dev/null+++ b/open-sse/utils/headers.ts@@ -0,0 +1,61 @@+/**+ * normalizeHeaders — cross-undici-instance Headers normalizer.+ *+ * On Node 24, accessing an undici-backed `Headers` object that was constructed+ * by a *different* undici copy (e.g. a mock global `Response` in tests, or a+ * version mismatch between undici instances bundled into different workspaces)+ * throws `Cannot read private member #headers` because undici guards its internal+ * state with private class fields.+ *+ * This helper avoids that crash by iterating through the public iterable API+ * (`forEach`, then `entries`) first, falling back to plain-object enumeration+ * for any non-standard map-like value.+ *+ * Always returns a plain `Record<string, string>` with lower-cased keys so+ * callers never need to worry about header case sensitivity.+ */+export function normalizeHeaders(h: unknown): Record<string, string> {+ if (!h) return {};+ const out: Record<string, string> = {};++ // Preferred path: forEach avoids creating an iterator object+ try {+ if (typeof (h as Headers).forEach === "function") {+ (h as Headers).forEach((value: string, key: string) => {+ out[key.toLowerCase()] = value;+ });+ return out;+ }+ } catch {+ // fall through — different undici instance, try next approach+ }++ // Second path: entries() iterator+ try {+ if (typeof (h as Headers).entries === "function") {+ for (const [k, v] of (h as Headers).entries()) {+ out[k.toLowerCase()] = String(v);+ }+ return out;+ }+ } catch {+ // fall through — try plain object enumeration+ }++ // Final fallback: treat as plain object+ if (typeof h === "object") {+ for (const [k, v] of Object.entries(h as Record<string, unknown>)) {+ out[k.toLowerCase()] = String(v ?? "");+ }+ }+ return out;+}++/**+ * Convenience wrapper: get a header value from any headers-like object.+ * Returns null (same contract as `Headers.prototype.get`) when absent.+ */+export function getHeader(h: unknown, name: string): string | null {+ const plain = normalizeHeaders(h);+ return plain[name.toLowerCase()] ?? null;+}diff --git a/tests/unit/combo-provider-cooldown.test.ts b/tests/unit/combo-provider-cooldown.test.tsindex db41824120..046e15aef8 100644--- a/tests/unit/combo-provider-cooldown.test.ts+++ b/tests/unit/combo-provider-cooldown.test.ts@@ -1,6 +1,7 @@import test from "node:test";import assert from "node:assert/strict";+import { normalizeHeaders } from "../../open-sse/utils/headers.ts";import { createChatPipelineHarness } from "../integration/_chatPipelineHarness.ts";const harness = await createChatPipelineHarness("combo-provider-cooldown");@@ -14,33 +15,6 @@ const {settingsDb,} = harness;-function toPlainHeaders(headers) {- if (!headers) return {};- const plain = {};- if (typeof headers.forEach === "function") {- try {- headers.forEach((value, key) => {- plain[key.toLowerCase()] = value;- });- return plain;- } catch (e) {}- }- if (typeof headers.entries === "function") {- try {- for (const [key, value] of headers.entries()) {- plain[key.toLowerCase()] = value;- }- return plain;- } catch (e) {}- }- try {- for (const [key, value] of Object.entries(headers)) {- plain[key.toLowerCase()] = value == null ? "" : String(value);- }- } catch (e) {}- return plain;-}-test.beforeEach(async () => {await resetStorage();});@@ -76,7 +50,7 @@ test("combo failover skips the cooled provider target on the next request", asynlet claudeCalls = 0;globalThis.fetch = async (_url, init = {}) => {- const headers = toPlainHeaders(init.headers);+ const headers = normalizeHeaders(init.headers);const authHeader = headers.authorization ?? headers.Authorization;const apiKeyHeader = headers["x-api-key"] ?? headers["X-Api-Key"];diff --git a/tests/unit/executor-codex.test.ts b/tests/unit/executor-codex.test.tsindex a875f1ecc7..95431399a0 100644--- a/tests/unit/executor-codex.test.ts+++ b/tests/unit/executor-codex.test.ts@@ -71,16 +71,14 @@ async function withEnv<T>(entries: Record<string, string | undefined>, fn: () =>}test("Codex helper functions isolate rate-limit scopes and parse quota headers", () => {- const quota = parseCodexQuotaHeaders(- new Headers({- "x-codex-5h-usage": "100",- "x-codex-5h-limit": "500",- "x-codex-5h-reset-at": new Date(Date.now() + 60_000).toISOString(),- "x-codex-7d-usage": "1000",- "x-codex-7d-limit": "5000",- "x-codex-7d-reset-at": new Date(Date.now() + 120_000).toISOString(),- })- );+ const quota = parseCodexQuotaHeaders({+ "x-codex-5h-usage": "100",+ "x-codex-5h-limit": "500",+ "x-codex-5h-reset-at": new Date(Date.now() + 60_000).toISOString(),+ "x-codex-7d-usage": "1000",+ "x-codex-7d-limit": "5000",+ "x-codex-7d-reset-at": new Date(Date.now() + 120_000).toISOString(),+ });assert.equal(getCodexModelScope("codex-spark-mini"), "spark");assert.equal(getCodexModelScope("gpt-5.3-codex"), "codex");diff --git a/tests/unit/headers-normalize.test.ts b/tests/unit/headers-normalize.test.tsnew file mode 100644index 0000000000..5aa9b665cf--- /dev/null+++ b/tests/unit/headers-normalize.test.ts@@ -0,0 +1,70 @@+import test from "node:test";+import assert from "node:assert/strict";++const { normalizeHeaders, getHeader } = await import("../../open-sse/utils/headers.ts");++test("normalizeHeaders flattens a global Headers instance to plain object with lower-cased keys", () => {+ const h = new Headers({+ "Content-Type": "application/json",+ "Retry-After": "10",+ "X-Custom": "value",+ });++ const plain = normalizeHeaders(h);++ assert.deepEqual(plain, {+ "content-type": "application/json",+ "retry-after": "10",+ "x-custom": "value",+ });+});++test("normalizeHeaders accepts a plain object and lower-cases its keys", () => {+ const plain = normalizeHeaders({+ "X-Codex-5h-Usage": "42",+ "Retry-After": "5",+ });++ assert.equal(plain["x-codex-5h-usage"], "42");+ assert.equal(plain["retry-after"], "5");+});++test("normalizeHeaders returns {} for null / undefined / empty inputs", () => {+ assert.deepEqual(normalizeHeaders(null), {});+ assert.deepEqual(normalizeHeaders(undefined), {});+ assert.deepEqual(normalizeHeaders({}), {});+});++test("normalizeHeaders survives an object that throws on forEach (cross-undici-instance simulation)", () => {+ // Simulate the failure mode described in #2751: an object that *looks* like Headers+ // but throws when .forEach is called (because the private #headers slot belongs to a+ // different undici copy). The helper must fall back to entries(), then plain enum.+ const throwingForEach = {+ forEach: () => {+ throw new TypeError("Cannot read private member #headers");+ },+ entries: () => [+ ["X-Survived", "yes"],+ ["Retry-After", "1"],+ ][Symbol.iterator](),+ };++ const plain = normalizeHeaders(throwingForEach as unknown as Headers);+ assert.equal(plain["x-survived"], "yes");+ assert.equal(plain["retry-after"], "1");+});++test("normalizeHeaders falls back to Object.entries when neither forEach nor entries works", () => {+ const noIterators = { "X-Plain": "ok", "Other": "value" };+ const plain = normalizeHeaders(noIterators);+ assert.equal(plain["x-plain"], "ok");+ assert.equal(plain["other"], "value");+});++test("getHeader returns the value (case-insensitive) or null", () => {+ const h = new Headers({ "Retry-After": "30" });+ assert.equal(getHeader(h, "retry-after"), "30");+ assert.equal(getHeader(h, "Retry-After"), "30");+ assert.equal(getHeader(h, "missing"), null);+ assert.equal(getHeader(null, "any"), null);+});diff --git a/tests/unit/modelscope-policy.test.ts b/tests/unit/modelscope-policy.test.tsindex 39ea704f85..16e961945d 100644--- a/tests/unit/modelscope-policy.test.ts+++ b/tests/unit/modelscope-policy.test.ts@@ -7,6 +7,7 @@ const {isModelScopeProvider,parseModelScopeRateLimitHeaders,} = await import("../../open-sse/services/modelscopePolicy.ts");+const { normalizeHeaders } = await import("../../open-sse/utils/headers.ts");test("ModelScope policy detects provider ids and ModelScope host markers", () => {assert.equal(isModelScopeProvider("modelscope"), true);@@ -20,14 +21,12 @@ test("ModelScope policy detects provider ids and ModelScope host markers", () =>});test("ModelScope policy parses per-model and total rate-limit headers", () => {- const snapshot = parseModelScopeRateLimitHeaders(- new Headers({- "modelscope-ratelimit-model-requests-remaining": "0",- "modelscope-ratelimit-model-requests-limit": "10",- "modelscope-ratelimit-requests-remaining": "17",- "modelscope-ratelimit-requests-limit": "20",- })- );+ const snapshot = parseModelScopeRateLimitHeaders({+ "modelscope-ratelimit-model-requests-remaining": "0",+ "modelscope-ratelimit-model-requests-limit": "10",+ "modelscope-ratelimit-requests-remaining": "17",+ "modelscope-ratelimit-requests-limit": "20",+ });assert.deepEqual(snapshot, {modelRemaining: 0,@@ -40,10 +39,10 @@ test("ModelScope policy parses per-model and total rate-limit headers", () => {test("ModelScope policy keeps temporary 429 headers retryable", () => {const decision = classifyModelScope429("Throttling: current batch requests reached the limit",- new Headers({+ {"modelscope-ratelimit-model-requests-remaining": "0","modelscope-ratelimit-model-requests-limit": "10",- })+ });assert.equal(decision.kind, "rate_limited");@@ -52,13 +51,26 @@ test("ModelScope policy keeps temporary 429 headers retryable", () => {});test("ModelScope policy treats explicit free quota exhaustion as terminal", () => {- const decision = classifyModelScope429("Free allocated quota exceeded", new Headers());+ const decision = classifyModelScope429("Free allocated quota exceeded", {});assert.equal(decision.kind, "quota_exhausted");assert.equal(decision.retryable, false);});test("ModelScope retry delay respects Retry-After seconds before backoff fallback", () => {- assert.equal(getModelScopeRetryDelayMs(new Headers({ "retry-after": "2.5" }), 0), 2500);- assert.equal(getModelScopeRetryDelayMs(new Headers(), 1), 6000);+ assert.equal(getModelScopeRetryDelayMs({ "retry-after": "2.5" }, 0), 2500);+ assert.equal(getModelScopeRetryDelayMs({}, 1), 6000);+});++test("ModelScope policy accepts headers normalized via normalizeHeaders (Node 24 undici interop)", () => {+ // Simulate a Headers object from a different undici instance via the helper.+ const upstreamHeaders = new Headers({+ "modelscope-ratelimit-model-requests-remaining": "3",+ "retry-after": "1.5",+ });+ const normalized = normalizeHeaders(upstreamHeaders);++ const snapshot = parseModelScopeRateLimitHeaders(normalized);+ assert.equal(snapshot.modelRemaining, 3);+ assert.equal(getModelScopeRetryDelayMs(normalized, 0), 1500);});