From 0a50a626f2ad38bf83c789ff011e84b0a46618de Mon Sep 17 00:00:00 2001 From: diegosouzapw Date: Thu, 28 May 2026 00:36:08 -0300 Subject: [PATCH 1/2] fix(combo): normalize upstream Headers for Node 24 undici interop (#2751) --- CHANGELOG.md | 1 + open-sse/executors/codex.ts | 16 +++--- open-sse/handlers/chatCore.ts | 38 ++++----------- open-sse/services/modelscopePolicy.ts | 25 +++++++--- open-sse/utils/headers.ts | 61 +++++++++++++++++++++++ tests/unit/executor-codex.test.ts | 18 +++---- tests/unit/headers-normalize.test.ts | 70 +++++++++++++++++++++++++++ tests/unit/modelscope-policy.test.ts | 38 ++++++++++----- 8 files changed, 201 insertions(+), 66 deletions(-) create mode 100644 open-sse/utils/headers.ts create mode 100644 tests/unit/headers-normalize.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index b56334bcfb54..b7c833a64d08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ - **combos:** fix combo handling so transient 429 rate limit errors do not poison or persist the rate limited state for the same-provider connection (#2800 โ€” thanks @apoapostolov) - **gemini:** translate signature-less Gemini thinking model tool calls to text parts to prevent `400 "missing thought_signature"` errors (#2801 โ€” thanks @herjarsa) - **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) ### ๐Ÿงน Chores diff --git a/open-sse/executors/codex.ts b/open-sse/executors/codex.ts index d3dddc7e7e23..f7b5ba31926b 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 +): 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.ts index 8d5a4cca0869..b645ce5cca53 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"; @@ -1617,13 +1618,13 @@ export async function handleChatCore({ }; const persistCodexQuotaState = async ( - headers: Headers | Record | null, + headers: Record | 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 = @@ -3643,9 +3644,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"})` @@ -3664,7 +3666,7 @@ export async function handleChatCore({ attempts < maxAttempts - 1 ) { const failedConnectionId = credentials?.connectionId || connectionId; - const retryAfterHeader = res.response.headers.get("retry-after"); + const retryAfterHeader = normalizeHeaders(res.response.headers)["retry-after"] ?? null; const retryAfterMs = retryAfterHeader ? Number.parseFloat(retryAfterHeader) * 1000 : null; @@ -3782,27 +3784,7 @@ export async function handleChatCore({ } const statusText = rawResult.response.statusText; - const rawHeaders = rawResult.response.headers; - const headersObj: Record = {}; - 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(); @@ -4150,7 +4132,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 handling if (!providerResponse.ok) { @@ -4179,7 +4161,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_EXHAUSTED diff --git a/open-sse/services/modelscopePolicy.ts b/open-sse/services/modelscopePolicy.ts index af284aa347f1..44da231b175e 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 +): 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 +): ModelScope429Decision { const snapshot = parseModelScopeRateLimitHeaders(headers); const lower = String(errorText || "").toLowerCase(); @@ -78,8 +87,8 @@ export function classifyModelScope429(errorText: string, headers: Headers): Mode return { 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, 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.ts new file mode 100644 index 000000000000..d9853aafacd3 --- /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` with lower-cased keys so + * callers never need to worry about header case sensitivity. + */ +export function normalizeHeaders(h: unknown): Record { + if (!h) return {}; + const out: Record = {}; + + // 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)) { + 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/executor-codex.test.ts b/tests/unit/executor-codex.test.ts index a875f1ecc701..95431399a018 100644 --- a/tests/unit/executor-codex.test.ts +++ b/tests/unit/executor-codex.test.ts @@ -71,16 +71,14 @@ async function withEnv(entries: Record, 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.ts new file mode 100644 index 000000000000..5aa9b665cf9d --- /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.ts index 39ea704f851d..16e961945d94 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); }); From a18e8fafbe5c4c31c203e6761773dc4aceb16091 Mon Sep 17 00:00:00 2001 From: diegosouzapw Date: Fri, 29 May 2026 01:31:37 -0300 Subject: [PATCH 2/2] fix(review): apply PR review suggestions for #2823 --- open-sse/handlers/chatCore.ts | 3 ++- tests/unit/combo-provider-cooldown.test.ts | 30 ++-------------------- 2 files changed, 4 insertions(+), 29 deletions(-) diff --git a/open-sse/handlers/chatCore.ts b/open-sse/handlers/chatCore.ts index b645ce5cca53..2cbc3cfe3199 100644 --- a/open-sse/handlers/chatCore.ts +++ b/open-sse/handlers/chatCore.ts @@ -3666,7 +3666,8 @@ export async function handleChatCore({ attempts < maxAttempts - 1 ) { const failedConnectionId = credentials?.connectionId || connectionId; - const retryAfterHeader = normalizeHeaders(res.response.headers)["retry-after"] ?? null; + const normalizedHeaders = normalizeHeaders(res.response.headers); + const retryAfterHeader = normalizedHeaders["retry-after"] ?? null; const retryAfterMs = retryAfterHeader ? Number.parseFloat(retryAfterHeader) * 1000 : null; diff --git a/tests/unit/combo-provider-cooldown.test.ts b/tests/unit/combo-provider-cooldown.test.ts index db418241208f..046e15aef89b 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", asyn let 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"];