7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
fix(services): read body-stated back-off in decision/search upstream errors (#1547)
tashdroid3a9ee5d8c586
diff --git a/server/src/__tests__/services/decision.test.ts b/server/src/__tests__/services/decision.test.tsindex bfcdecb4..904e7b20 100644--- a/server/src/__tests__/services/decision.test.ts+++ b/server/src/__tests__/services/decision.test.ts@@ -102,6 +102,24 @@ describe('decision service', () => {expect(logRows().map(r => r.status)).toEqual(['error', 'ok']);});+ it('honours a back-off stated in the error body when there is no header', async () => {+ addKey('cloudflare', 'acct:tok');+ // A Gemini-shaped RetryInfo in the body with no Retry-After header: the+ // chat path (buildUpstreamError) already reads it; the decision chain must too.+ mockFetch(() => json({ error: { message: 'busy', retry_delay: '45s' } }, 429));+ const err = await runDecision(REQUEST, { model: '@cf/cloudflare/clef-flash', clientAgent: null }).catch(e => e);+ expect(err).toBeInstanceOf(DecisionError);+ expect(err.status).toBe(429);+ expect(err.retryAfterMs).toBe(45_000);+ });++ it('prefers a header Retry-After over a body hint', async () => {+ addKey('cloudflare', 'acct:tok');+ mockFetch(() => json({ error: { message: 'busy', retry_delay: '45s' } }, 429, { 'retry-after': '12' }));+ const err = await runDecision(REQUEST, { model: '@cf/cloudflare/clef-flash', clientAgent: null }).catch(e => e);+ expect(err.retryAfterMs).toBe(12_000);+ });+it('skips models whose platform has no key', async () => {addKey('openrouter');const fn = mockFetch(() => json({ answers: ANSWERS, usage: {} }));diff --git a/server/src/__tests__/services/search.test.ts b/server/src/__tests__/services/search.test.tsindex f876ecca..f2d8cfc8 100644--- a/server/src/__tests__/services/search.test.ts+++ b/server/src/__tests__/services/search.test.ts@@ -264,6 +264,17 @@ describe('search service', () => {expect(err.retryAfterMs).toBe(30_000);});+ it('reads a back-off stated in the error body when there is no header', async () => {+ addKey('tavily');+ // Tavily states its cap in prose; Exa in a RetryInfo-shaped field. With no+ // Retry-After header, the chain used to fall back to the 60s heuristic.+ mockFetch(() => new Response('too many requests, try again in 15 seconds', { status: 429 }));+ const err = await runSearch('q').catch(e => e) as SearchError;+ expect(err).toBeInstanceOf(SearchError);+ expect(err.status).toBe(429);+ expect(err.retryAfterMs).toBe(15_000);+ });+it('reports a provider 401 as a 502, never as the caller’s auth failure', async () => {addKey('tavily');mockFetch(() => json({ detail: 'bad key' }, 401));diff --git a/server/src/services/decision.ts b/server/src/services/decision.tsindex 750acead..aa4a1c75 100644--- a/server/src/services/decision.ts+++ b/server/src/services/decision.ts@@ -1,5 +1,5 @@import { getDb } from '../db/index.js';-import { parseRetryAfterMs } from '../providers/base.js';+import { parseRetryAfterMs, parseStatedRetryMs } from '../providers/base.js';import { RetryHintTracker } from '../lib/retry-hint.js';import { getClientContext } from '../lib/client-context.js';import { proxyFetch } from '../lib/proxy.js';@@ -119,6 +119,16 @@ interface AdapterResult {type Adapter = (cred: ReservedProviderCredential, modelId: string, body: DecisionRequest, signal?: AbortSignal) => Promise<AdapterResult>;+/** A back-off stated inside an error body: JSON first (RetryInfo-shaped), the+ * raw text as prose otherwise. Mirrors buildUpstreamError in providers/base.ts. */+function statedBodyRetryMs(text: string): number | undefined {+ try {+ return parseStatedRetryMs(JSON.parse(text));+ } catch {+ return parseStatedRetryMs(text);+ }+}+async function upstream(url: string, platform: string, init: RequestInit, signal?: AbortSignal): Promise<unknown> {const timeoutSignal = AbortSignal.timeout(FETCH_TIMEOUT_MS);const res = await proxyFetch(@@ -130,11 +140,15 @@ async function upstream(url: string, platform: string, init: RequestInit, signal);if (!res.ok) {const text = await res.text().catch(() => '');+ // Same rule as the chat path (providers/base.ts buildUpstreamError): a+ // header Retry-After wins, then a back-off stated in the error BODY+ // (Gemini RetryInfo, prose "try again in 45 seconds"). Dropping the body+ // hint demotes an exact promise to the 60s heuristic and to no hint.throw new DecisionError(`${platform} ${res.status}: ${text.slice(0, 200)}`,res.status,undefined,- parseRetryAfterMs(res.headers?.get('retry-after') ?? null),+ parseRetryAfterMs(res.headers?.get('retry-after') ?? null) ?? statedBodyRetryMs(text),);}return res.json();diff --git a/server/src/services/search.ts b/server/src/services/search.tsindex 872c7df3..2c6d5e88 100644--- a/server/src/services/search.ts+++ b/server/src/services/search.ts@@ -1,5 +1,5 @@import { getDb, getSetting, setSetting } from '../db/index.js';-import { parseRetryAfterMs } from '../providers/base.js';+import { parseRetryAfterMs, parseStatedRetryMs } from '../providers/base.js';import { RetryHintTracker } from '../lib/retry-hint.js';import { getClientContext } from '../lib/client-context.js';import { proxyFetch } from '../lib/proxy.js';@@ -184,11 +184,19 @@ async function upstream(url: string, platform: string, init: RequestInit, signal);if (!res.ok) {const body = await res.text().catch(() => '');+ // Header first, then a back-off stated inside the body (RetryInfo or+ // prose), mirroring buildUpstreamError in providers/base.ts.+ let stated: number | undefined;+ try {+ stated = parseStatedRetryMs(JSON.parse(body));+ } catch {+ stated = parseStatedRetryMs(body);+ }throw new SearchError(`${platform} ${res.status}: ${body.slice(0, 200)}`,res.status,undefined,- parseRetryAfterMs(res.headers?.get('retry-after') ?? null),+ parseRetryAfterMs(res.headers?.get('retry-after') ?? null) ?? stated,);}// MCP servers may answer a POST as a one-event stream instead of plain JSON.