Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
16 changes: 9 additions & 7 deletions open-sse/executors/codex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
38 changes: 10 additions & 28 deletions open-sse/handlers/chatCore.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -1617,13 +1618,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 =
Expand Down Expand Up @@ -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"})`
Expand All @@ -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;
Expand Down Expand Up @@ -3782,27 +3784,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();
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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
Expand Down
25 changes: 17 additions & 8 deletions open-sse/services/modelscopePolicy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand All @@ -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<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;
Expand Down
61 changes: 61 additions & 0 deletions open-sse/utils/headers.ts
Original file line number Diff line number Diff line change
@@ -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;
}
Comment on lines +17 to +52

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Isolating the out object creation inside each try/catch block ensures that if any of the iteration methods (like forEach or entries()) throw an error halfway through execution, we do not return a partially populated or corrupted out object. Additionally, converting the value to a string using String(value) in the forEach path ensures strict type safety and consistency with the other paths, preventing non-string values from leaking into the returned Record<string, string>.

export function normalizeHeaders(h: unknown): Record<string, string> {
  if (!h) return {};

  // Preferred path: forEach avoids creating an iterator object
  try {
    if (typeof (h as Headers).forEach === "function") {
      const out: Record<string, string> = {};
      (h as Headers).forEach((value: string, key: string) => {
        out[key.toLowerCase()] = String(value);
      });
      return out;
    }
  } catch {
    // fall through — different undici instance, try next approach
  }

  // Second path: entries() iterator
  try {
    if (typeof (h as Headers).entries === "function") {
      const out: Record<string, string> = {};
      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
  const out: Record<string, string> = {};
  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;
}
18 changes: 8 additions & 10 deletions tests/unit/executor-codex.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
70 changes: 70 additions & 0 deletions tests/unit/headers-normalize.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
38 changes: 25 additions & 13 deletions tests/unit/modelscope-policy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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,
Expand All @@ -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");
Expand All @@ -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);
});