Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(ai): retry OpenRouter HTTP-200 rate-limit envelopes as real errors (#5478)

time-attacka8a7b4b1c771
diff --git a/src/core/ai/errors.ts b/src/core/ai/errors.ts
index 2a227d7fd7..93dd607dff 100644
--- a/src/core/ai/errors.ts
+++ b/src/core/ai/errors.ts
@@ -327,7 +327,9 @@ function statusToClass(status: number): GlobalLlmErrorClass | null {
* halt instead of accumulating one swallowed warning per item.
*
* Matching is conservative by design: numeric status properties on the error
- * (or its `cause` chain), STRUCTURED status forms in the message, or specific
+ * (or its `cause` chain, falling back to RetryError's `lastError`, where the
+ * AI SDK keeps the final attempt's status once its retries are spent:
+ * #5473), STRUCTURED status forms in the message, or specific
* provider phrases. Plain 400s (context length, malformed request) stay
* per-item — they can genuinely differ page to page. Billing phrases outrank
* a 429 status because a monthly spend limit surfaces as 429 but is a billing
@@ -343,7 +345,8 @@ export function classifyGlobalLlmError(err: unknown): GlobalLlmErrorClass | null
else if (typeof (cur as { message?: unknown }).message === 'string') {
messages.push((cur as { message: string }).message);
}
- cur = (cur as { cause?: unknown }).cause;
+ const next = cur as { cause?: unknown; lastError?: unknown };
+ cur = next.cause ?? next.lastError;
}
const message = messages.join('\n');
// Phrase regexes (and the prose-shaped status forms) only see text BEFORE
diff --git a/src/core/ai/recipes/openrouter.ts b/src/core/ai/recipes/openrouter.ts
index 8749a0bfc2..46f4e6a991 100644
--- a/src/core/ai/recipes/openrouter.ts
+++ b/src/core/ai/recipes/openrouter.ts
@@ -106,14 +106,55 @@ function withSystemCacheControl(body: unknown): unknown {
return { ...record, messages: next };
}
+/**
+ * OpenRouter reports upstream rate limits and some provider outages inside
+ * an HTTP 200 body: `{ error: { message, code, metadata? } }` (#5473). The
+ * AI SDK validates that body against the chat-completion schema and throws
+ * an `APICallError` with `statusCode: 200`, so neither the SDK's
+ * status-keyed retry nor gbrain's status-keyed classification sees the real
+ * condition.
+ *
+ * Only a 200 `application/json` body whose integer `error.code` is 429 or
+ * 5xx gets that code as its HTTP status. A success payload, an unparseable
+ * body, a 4xx code, a non-integer code and any non-JSON (SSE) response pass
+ * through untouched. An existing `Retry-After` header is kept as it is; a
+ * finite non-negative `error.metadata.retry_after`/`retryAfter` is promoted
+ * to one when absent. Fail-open: any parse problem returns the original
+ * response.
+ */
+async function rewriteOpenRouterErrorEnvelopeStatus(res: Response): Promise<Response> {
+ if (res.status !== 200) return res;
+ if (!(res.headers.get('content-type') ?? '').includes('application/json')) return res;
+ try {
+ const text = await res.clone().text();
+ const error = JSON.parse(text)?.error;
+ const code = error?.code;
+ if (!Number.isInteger(code)) return res;
+ if (code !== 429 && (code < 500 || code >= 600)) return res;
+ const headers = new Headers(res.headers);
+ if (!headers.has('retry-after')) {
+ const meta = error.metadata;
+ const retryAfter = meta?.retry_after ?? meta?.retryAfter;
+ if (typeof retryAfter === 'number' && Number.isFinite(retryAfter) && retryAfter >= 0) {
+ headers.set('retry-after', String(retryAfter));
+ }
+ }
+ return new Response(text, { status: code, statusText: res.statusText, headers });
+ } catch {
+ return res;
+ }
+}
+
/**
* Compat fetch: (1) honors the OPENROUTER_CACHE_HEADER marker by splicing an
* Anthropic cache_control breakpoint onto the system block, then strips the
* marker; (2) composes the native DeepSeek `reasoning_content` promote so
* OpenRouter-hosted thinking models (DeepSeek V4, etc.) do not arrive at the
- * AI SDK adapter as empty `content` (#4753). Fail-open: any parse problem
- * sends the original body unchanged. Tool-call turns are never promoted
- * (that logic lives in `deepseekReasoningContentCompatFetch`).
+ * AI SDK adapter as empty `content` (#4753); (3) gives an HTTP-200
+ * rate-limit or outage envelope its real status (#5473, see
+ * `rewriteOpenRouterErrorEnvelopeStatus`). Fail-open: any parse problem
+ * sends the original body or response unchanged. Tool-call turns are never
+ * promoted (that logic lives in `deepseekReasoningContentCompatFetch`).
*
* @internal exported for tests. Cast through `unknown` because TS's
* `typeof fetch` includes a `preconnect` member (matches azure-openai.ts).
@@ -122,8 +163,10 @@ export const openrouterCompatFetch = (async (
input: RequestInfo | URL,
init?: RequestInit,
): Promise<Response> => {
- const promote = (nextInit?: RequestInit) =>
- deepseekReasoningContentCompatFetch(input as any, nextInit as any);
+ const promote = async (nextInit?: RequestInit): Promise<Response> =>
+ rewriteOpenRouterErrorEnvelopeStatus(
+ await deepseekReasoningContentCompatFetch(input as any, nextInit as any),
+ );
if (!init?.headers) return promote(init);
const headers = new Headers(init.headers as any);
if (!headers.has(OPENROUTER_CACHE_HEADER)) return promote(init);
diff --git a/test/ai/classify-global-llm-error.test.ts b/test/ai/classify-global-llm-error.test.ts
index 1fe497eaed..62eef816d1 100644
--- a/test/ai/classify-global-llm-error.test.ts
+++ b/test/ai/classify-global-llm-error.test.ts
@@ -13,7 +13,23 @@
*/
import { describe, test, expect } from 'bun:test';
-import { classifyGlobalLlmError, AIConfigError } from '../../src/core/ai/errors.ts';
+import { APICallError, RetryError } from 'ai';
+import { classifyGlobalLlmError, createGlobalLlmHaltTracker, AIConfigError, RATE_LIMIT_HALT_STREAK } from '../../src/core/ai/errors.ts';
+
+function sdkRetriesExhausted(statusCode: number, message = `synthetic provider error ${statusCode}`): RetryError {
+ const attempt = () => new APICallError({
+ message,
+ url: 'https://provider.example.invalid/v1/chat/completions',
+ requestBodyValues: {},
+ statusCode,
+ isRetryable: statusCode === 429 || statusCode >= 500,
+ });
+ return new RetryError({
+ message: 'Failed after 3 attempts. Last error: upstream busy',
+ reason: 'maxRetriesExceeded',
+ errors: [attempt(), attempt(), attempt()],
+ });
+}
function errWithStatus(message: string, status: number): Error {
return Object.assign(new Error(message), { status });
@@ -40,6 +56,55 @@ describe('classifyGlobalLlmError — positives', () => {
expect(classifyGlobalLlmError(Object.assign(new Error('request failed'), { api_error_status: 401 }))).toBe('auth');
});
+ // #5473: after the AI SDK's own retries exhaust, it throws `RetryError`
+ // whose final attempt's status lives on `.lastError` — a SIBLING field,
+ // not `.cause` (verified against node_modules/ai's RetryError class). The
+ // top-level RetryError message here deliberately carries no rate-limit
+ // phrasing ("upstream busy") so only the `lastError` walk can classify it.
+ test('RetryError-shaped wrapper: status lives on .lastError (not .cause), no rate-limit phrase in the message', () => {
+ const retryError = Object.assign(new Error('Failed after 3 attempts. Last error: upstream busy'), {
+ name: 'AI_RetryError',
+ reason: 'maxRetriesExceeded',
+ errors: [],
+ lastError: Object.assign(new Error('upstream busy'), { statusCode: 429 }),
+ });
+ expect(classifyGlobalLlmError(retryError)).toBe('rate_limit');
+ });
+
+ test('RetryError-shaped wrapper: a 5xx on .lastError does not falsely classify (no auth/billing/rate_limit class for 5xx)', () => {
+ const retryError = Object.assign(new Error('Failed after 3 attempts. Last error: gateway down'), {
+ name: 'AI_RetryError',
+ lastError: Object.assign(new Error('gateway down'), { statusCode: 503 }),
+ });
+ expect(classifyGlobalLlmError(retryError)).toBeNull();
+ });
+
+ test('AI SDK RetryError whose lastError is a 404 classifies as model_not_found, not transient or auth (#5473)', () => {
+ expect(classifyGlobalLlmError(sdkRetriesExhausted(404))).toBe('model_not_found');
+ });
+
+ test('AI SDK RetryError: a 429 lastError is rate_limit, but a spend-limit phrase on it still outranks the 429 as billing', () => {
+ expect(classifyGlobalLlmError(sdkRetriesExhausted(429))).toBe('rate_limit');
+ expect(classifyGlobalLlmError(sdkRetriesExhausted(429, 'You have reached your monthly spend limit'))).toBe('billing');
+ });
+
+ test('AI SDK RetryError: lastError 401 is auth', () => {
+ expect(classifyGlobalLlmError(sdkRetriesExhausted(401))).toBe('auth');
+ });
+
+ test('a rate-limited RetryError counts toward the halt streak, and a success resets it', () => {
+ const tracker = createGlobalLlmHaltTracker();
+ for (let i = 1; i < RATE_LIMIT_HALT_STREAK; i++) {
+ expect(tracker.observe(sdkRetriesExhausted(429))).toBe('continue');
+ }
+ expect(tracker.lastClass()).toBe('rate_limit');
+ tracker.reset();
+ expect(tracker.observe(sdkRetriesExhausted(429))).toBe('continue');
+ const unreset = createGlobalLlmHaltTracker();
+ for (let i = 1; i < RATE_LIMIT_HALT_STREAK; i++) unreset.observe(sdkRetriesExhausted(429));
+ expect(unreset.observe(sdkRetriesExhausted(429))).toBe('halt-rate_limit');
+ });
+
test('AIConfigError classifies structurally as auth (missing-key gateway errors carry no status, no phrase)', () => {
expect(classifyGlobalLlmError(new AIConfigError('OpenAI chat requires OPENAI_API_KEY.'))).toBe('auth');
expect(classifyGlobalLlmError(new AIConfigError('Anthropic chat requires ANTHROPIC_API_KEY.'))).toBe('auth');
@@ -146,6 +211,14 @@ describe('classifyGlobalLlmError — negatives (per-item errors stay per-item)',
).toBeNull();
});
+ test('null for a rate-limit phrase inside the raw slice of a RetryError lastError with no status', () => {
+ const retryError = Object.assign(new Error('Failed after 3 attempts.'), {
+ name: 'AI_RetryError',
+ lastError: new Error('claude-cli returned malformed output\n--- raw ---\nthe rate limit should be raised: too many requests'),
+ });
+ expect(classifyGlobalLlmError(retryError)).toBeNull();
+ });
+
test('null for prose-shaped status forms inside a --- raw --- slice', () => {
// The quoted `"api_error_status":NNN` JSON form scans the full message
// (pinned above); the prose forms only scan the pre-raw slice — model
diff --git a/test/ai/recipe-openrouter.test.ts b/test/ai/recipe-openrouter.test.ts
index aeda279d8d..56b96c3896 100644
--- a/test/ai/recipe-openrouter.test.ts
+++ b/test/ai/recipe-openrouter.test.ts
@@ -264,7 +264,7 @@ describe('recipe: openrouter', () => {
test('16. fetch shim promotes reasoning_content when content is empty (DeepSeek-via-OpenRouter, #4753)', async () => {
const originalFetch = globalThis.fetch;
- globalThis.fetch = (async () =>
+ globalThis.fetch = (async (_input: RequestInfo | URL, _init?: RequestInit) =>
new Response(JSON.stringify({
choices: [{ message: { role: 'assistant', content: '', reasoning_content: 'the answer' } }],
}), { status: 200, headers: { 'content-type': 'application/json' } })) as unknown as typeof fetch;
@@ -400,6 +400,188 @@ describe('recipe: openrouter', () => {
globalThis.fetch = originalFetch;
}
});
+
+ // #5473: OpenRouter reports upstream rate limits / provider outages as an
+ // `error` object inside an HTTP 200 body. The AI SDK's openai-compatible
+ // provider reads `res.status` (via `compat.fetch`, exactly the function
+ // under test here — not a separate helper) to decide retryability, so
+ // these tests exercise the same boundary the SDK actually calls.
+ test('21. #5473 — HTTP-200 error.code 429 is rewritten to a real 429 Response', async () => {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = (async (_input: RequestInfo | URL, _init?: RequestInit) =>
+ new Response(
+ JSON.stringify({
+ error: {
+ message: 'openai/gpt-6-luna is temporarily rate-limited upstream.',
+ code: 429,
+ metadata: { error_type: 'rate_limit_exceeded' },
+ },
+ }),
+ { status: 200, headers: { 'content-type': 'application/json' } },
+ )) as typeof fetch;
+ try {
+ const res = await openrouterCompatFetch('https://openrouter.ai/api/v1/chat/completions');
+ expect(res.status).toBe(429);
+ expect(res.ok).toBe(false);
+ expect((await res.json()).error.code).toBe(429);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ });
+
+ test('22. #5473 — HTTP-200 error.code 503 is rewritten to a real 503 Response (retryable 5xx)', async () => {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = (async (_input: RequestInfo | URL, _init?: RequestInit) =>
+ new Response(JSON.stringify({ error: { message: 'upstream unavailable', code: 503 } }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })) as typeof fetch;
+ try {
+ const res = await openrouterCompatFetch('https://openrouter.ai/api/v1/chat/completions');
+ expect(res.status).toBe(503);
+ expect(res.ok).toBe(false);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ });
+
+ test('23. #5473 — an existing Retry-After header on the 200 response is preserved verbatim', async () => {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = (async (_input: RequestInfo | URL, _init?: RequestInit) =>
+ new Response(JSON.stringify({ error: { message: 'rate limited', code: 429 } }), {
+ status: 200,
+ headers: { 'content-type': 'application/json', 'retry-after': '17' },
+ })) as typeof fetch;
+ try {
+ const res = await openrouterCompatFetch('https://openrouter.ai/api/v1/chat/completions');
+ expect(res.status).toBe(429);
+ expect(res.headers.get('retry-after')).toBe('17');
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ });
+
+ test('24. #5473 — a numeric error.metadata.retry_after is promoted to a Retry-After header when none is present', async () => {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = (async (_input: RequestInfo | URL, _init?: RequestInit) =>
+ new Response(
+ JSON.stringify({ error: { message: 'rate limited', code: 429, metadata: { retry_after: 5 } } }),
+ { status: 200, headers: { 'content-type': 'application/json' } },
+ )) as typeof fetch;
+ try {
+ const res = await openrouterCompatFetch('https://openrouter.ai/api/v1/chat/completions');
+ expect(res.status).toBe(429);
+ expect(res.headers.get('retry-after')).toBe('5');
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ });
+
+ test('25. #5473 — malformed/missing error.metadata does not block the status rewrite', async () => {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = (async (_input: RequestInfo | URL, _init?: RequestInit) =>
+ new Response(JSON.stringify({ error: { message: 'rate limited', code: 429, metadata: 'not an object' } }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })) as typeof fetch;
+ try {
+ const res = await openrouterCompatFetch('https://openrouter.ai/api/v1/chat/completions');
+ expect(res.status).toBe(429);
+ expect(res.headers.has('retry-after')).toBe(false);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ });
+
+ test('26. #5473 — a 4xx error.code (config-level) is left as HTTP 200, not rewritten', async () => {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = (async (_input: RequestInfo | URL, _init?: RequestInit) =>
+ new Response(JSON.stringify({ error: { message: 'bad request', code: 400 } }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })) as typeof fetch;
+ try {
+ const res = await openrouterCompatFetch('https://openrouter.ai/api/v1/chat/completions');
+ expect(res.status).toBe(200);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ });
+
+ test('27. #5473 — a real success payload (no error key) regresses unchanged', async () => {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = (async (_input: RequestInfo | URL, _init?: RequestInit) =>
+ new Response(JSON.stringify({ choices: [{ message: { role: 'assistant', content: 'hi' } }] }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })) as typeof fetch;
+ try {
+ const res = await openrouterCompatFetch('https://openrouter.ai/api/v1/chat/completions');
+ expect(res.status).toBe(200);
+ expect((await res.json()).choices[0].message.content).toBe('hi');
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ });
+
+ test('28a. #5473 — a non-finite or negative metadata.retry_after is not promoted', async () => {
+ const originalFetch = globalThis.fetch;
+ for (const retryAfter of [-1, '5', null]) {
+ globalThis.fetch = (async (_input: RequestInfo | URL, _init?: RequestInit) =>
+ new Response(JSON.stringify({ error: { message: 'rate limited', code: 429, metadata: { retry_after: retryAfter } } }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })) as typeof fetch;
+ try {
+ const res = await openrouterCompatFetch('https://openrouter.ai/api/v1/chat/completions');
+ expect(res.status).toBe(429);
+ expect(res.headers.has('retry-after')).toBe(false);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ }
+ });
+
+ test('28b. #5473 — a streamed (non-JSON) 200 response and an unparseable JSON body pass through untouched', async () => {
+ const originalFetch = globalThis.fetch;
+ const bodies: Array<[string, string]> = [
+ ['text/event-stream', 'data: {"error":{"code":429}}\n\n'],
+ ['application/json', '{"error":{"code":429'],
+ ];
+ for (const [ctype, body] of bodies) {
+ globalThis.fetch = (async (_input: RequestInfo | URL, _init?: RequestInit) =>
+ new Response(body, { status: 200, headers: { 'content-type': ctype } })) as typeof fetch;
+ try {
+ const res = await openrouterCompatFetch('https://openrouter.ai/api/v1/chat/completions');
+ expect(res.status).toBe(200);
+ expect(await res.text()).toBe(body);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ }
+ });
+
+ test('28. #5473 — the envelope rewrite composes with the cache-header + reasoning_content shims unchanged', async () => {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = (async (_input: RequestInfo | URL, _init?: RequestInit) =>
+ new Response(JSON.stringify({ error: { message: 'rate limited', code: 429 } }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })) as typeof fetch;
+ try {
+ const res = await openrouterCompatFetch('https://openrouter.ai/api/v1/chat/completions', {
+ method: 'POST',
+ headers: { [OPENROUTER_CACHE_HEADER]: '1' },
+ body: JSON.stringify({
+ model: 'anthropic/claude-sonnet-4.6',
+ messages: [{ role: 'system', content: 'stable' }, { role: 'user', content: 'hi' }],
+ }),
+ });
+ expect(res.status).toBe(429);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ });
});
// gbrain#4727: Z.ai's GLM-4.5+/5.x think by default and OpenRouter bills