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
feat(circuit-breaker): classify 429 errors and apply per-kind cooldowns (#2116)
eleatae0928f6b371f
diff --git a/src/shared/utils/circuitBreaker.ts b/src/shared/utils/circuitBreaker.tsindex f94d73949a..e6ba3a17f2 100644--- a/src/shared/utils/circuitBreaker.ts+++ b/src/shared/utils/circuitBreaker.ts@@ -19,6 +19,7 @@ import {deleteCircuitBreakerState,deleteAllCircuitBreakerStates,} from "../../lib/db/domainState";+import type { FailureKind } from "./classify429";const STATE = {CLOSED: "CLOSED",@@ -34,6 +35,25 @@ interface CircuitBreakerOptions {halfOpenRequests?: number;onStateChange?: ((name: string, oldState: string, newState: string) => void) | null;isFailure?: (error: unknown) => boolean;+ /**+ * Per-failure-kind cooldown override (Issue #2100).+ *+ * When set, `_timeUntilReset()` and `_shouldAttemptReset()` use+ * `cooldownByKind[lastFailureKind]` instead of `resetTimeout` whenever+ * the last failure had a known kind. Use this to give a longer cooldown+ * to `quota_exhausted` (period-end may be hours away) than to+ * `rate_limit` (typically 60s).+ */+ cooldownByKind?: Partial<Record<FailureKind, number>>;+ /**+ * Optional classifier called on `execute()` errors (Issue #2100).+ * Returns the kind to record. When omitted, all failures are recorded+ * as `lastFailureKind = null` (existing behavior preserved).+ *+ * Pair with `classify429()` from `./classify429.ts` for HTTP responses,+ * or supply a custom classifier for non-HTTP errors.+ */+ classifyError?: (error: unknown) => FailureKind | undefined;}export class CircuitBreaker {@@ -48,6 +68,9 @@ export class CircuitBreaker {successCount: number;lastFailureTime: number | null;halfOpenAllowed: number;+ cooldownByKind: Partial<Record<FailureKind, number>>;+ classifyError: ((error: unknown) => FailureKind | undefined) | null;+ lastFailureKind: FailureKind | null;constructor(name: string, options: CircuitBreakerOptions = {}) {this.name = name;@@ -62,6 +85,9 @@ export class CircuitBreaker {this.successCount = 0;this.lastFailureTime = null;this.halfOpenAllowed = 0;+ this.cooldownByKind = options.cooldownByKind ?? {};+ this.classifyError = options.classifyError ?? null;+ this.lastFailureKind = null;// Try to restore state from DBthis._restoreFromDb();@@ -151,7 +177,17 @@ export class CircuitBreaker {return result;} catch (error) {if (this.isFailure(error)) {- this._onFailure();+ let kind: FailureKind | undefined;+ if (this.classifyError) {+ try {+ kind = this.classifyError(error);+ } catch {+ // A user-supplied classifier must not mask the original error+ // or change failure-counting semantics; fall back to no kind.+ kind = undefined;+ }+ }+ this._onFailure(kind);}throw error;}@@ -205,6 +241,7 @@ export class CircuitBreaker {this.failureCount = 0;this.successCount = 0;this.lastFailureTime = null;+ this.lastFailureKind = null;this._persistToDb();}@@ -218,10 +255,12 @@ export class CircuitBreaker {this.failureCount = 0;this.successCount = 0;this.lastFailureTime = null;+ this.lastFailureKind = null;} else if (this.state === STATE.HALF_OPEN) {this.successCount++;this._transition(STATE.CLOSED);this.failureCount = 0;+ this.lastFailureKind = null;} else {// In CLOSED state, just reset failure countthis.failureCount = 0;@@ -229,9 +268,10 @@ export class CircuitBreaker {this._persistToDb();}- _onFailure() {+ _onFailure(kind?: FailureKind | null) {this.failureCount++;this.lastFailureTime = Date.now();+ this.lastFailureKind = kind ?? null;if (this.state === STATE.OPEN) {// Already OPEN — just update persistence (re-tripped by combo path)@@ -245,12 +285,31 @@ export class CircuitBreaker {_shouldAttemptReset() {if (!this.lastFailureTime) return true;- return Date.now() - this.lastFailureTime >= this.resetTimeout;+ const cooldown = this._effectiveCooldown();+ return Date.now() - this.lastFailureTime >= cooldown;+ }++ /**+ * Resolve the cooldown for the current `lastFailureKind`. Falls back to+ * `resetTimeout` when no kind was recorded, no override exists for it,+ * or the override is not a finite non-negative number (NaN / Infinity /+ * negative all silently fall through to `resetTimeout`).+ * @private+ */+ _effectiveCooldown() {+ if (this.lastFailureKind !== null) {+ const override = this.cooldownByKind[this.lastFailureKind];+ if (typeof override === "number" && Number.isFinite(override) && override >= 0) {+ return override;+ }+ }+ return this.resetTimeout;}_timeUntilReset() {if (!this.lastFailureTime) return 0;- return Math.max(0, this.resetTimeout - (Date.now() - this.lastFailureTime));+ const cooldown = this._effectiveCooldown();+ return Math.max(0, cooldown - (Date.now() - this.lastFailureTime));}_refreshOpenState() {@@ -315,6 +374,18 @@ export function getCircuitBreaker(name: string, options?: CircuitBreakerOptions)if (typeof options.isFailure === "function") {breaker.isFailure = options.isFailure;}+ if (options.cooldownByKind) {+ // Merge keys, don't replace: callers that add different kinds+ // (e.g. one sets `quota_exhausted`, another `rate_limit`) should+ // not silently lose each other's overrides.+ breaker.cooldownByKind = {+ ...breaker.cooldownByKind,+ ...options.cooldownByKind,+ };+ }+ if (typeof options.classifyError === "function") {+ breaker.classifyError = options.classifyError;+ }breaker._persistToDb();}return breaker;diff --git a/src/shared/utils/classify429.ts b/src/shared/utils/classify429.tsnew file mode 100644index 0000000000..715873cd9e--- /dev/null+++ b/src/shared/utils/classify429.ts@@ -0,0 +1,164 @@+/**+ * 429 response classifier — distinguish rate-limit from quota-exhausted.+ *+ * Most LLM providers return HTTP 429 for two semantically different reasons:+ *+ * 1. **Rate-limit**: short transient back-off ("too many requests in+ * the last minute"). Fix: wait the Retry-After window and retry.+ * 2. **Quota-exhausted**: long-period cap hit ("daily/monthly limit+ * reached"). Fix: wait until the period rolls over (could be hours+ * or days). Retrying every 60s wastes calls and burns alerts.+ *+ * The HTTP status alone cannot disambiguate. This helper inspects the+ * response body and headers to return a `FailureKind` the circuit+ * breaker can use to pick the right cooldown.+ *+ * Companion to OmniRoute issue #2100.+ *+ * @module shared/utils/classify429+ */++export type FailureKind = "rate_limit" | "quota_exhausted" | "transient";++/**+ * Heuristic regexes for "explicit quota exhausted" vs "rate-limited"+ * detection in 429 error bodies. A 429 alone never implies quota+ * exhausted — only an explicit keyword does.+ *+ * Patterns observed across OpenAI, Anthropic, Groq, Cerebras, Mistral,+ * Google Gemini, and OpenRouter free-tier responses.+ */+const QUOTA_PATTERNS: ReadonlyArray<RegExp> = [+ /daily.*limit/i,+ /daily.*quota/i,+ /per.?day.*limit/i,+ /monthly.*limit/i,+ /monthly.*quota/i,+ /per.?month.*limit/i,+ /quota.*exceed/i,+ /exceed.*quota/i,+ /insufficient.*quota/i,+ /billing.*cap/i,+ /credit.*exhaust/i,+ /out of credits/i,+ /hard.?limit/i,+ /plan.*limit/i,+];++/**+ * Best-effort case-insensitive header lookup.+ */+function getHeader(headers: Record<string, string> | undefined, name: string): string | undefined {+ if (!headers) return undefined;+ const target = name.toLowerCase();+ for (const [k, v] of Object.entries(headers)) {+ if (k.toLowerCase() === target) return v;+ }+ return undefined;+}++/**+ * Coerce a body of unknown shape to a string for keyword scanning.+ * - string: returned as-is+ * - object: JSON-stringified (so nested error.message gets scanned)+ * - undefined/null: empty string+ */+function bodyToText(body: unknown): string {+ if (typeof body === "string") return body;+ if (body == null) return "";+ try {+ return JSON.stringify(body);+ } catch {+ return "";+ }+}++/**+ * Returns true if the body looks like an explicit quota-exhausted+ * error — i.e. the upstream is telling us a long-period cap was hit.+ */+export function looksLikeQuotaExhausted(body: unknown): boolean {+ const text = bodyToText(body);+ if (!text) return false;+ return QUOTA_PATTERNS.some((pat) => pat.test(text));+}++/**+ * Classify a 429 (or any) response into a `FailureKind`.+ *+ * Decision order:+ * 1. status !== 429 → `"transient"` (don't pretend to know more than+ * the caller does about non-429 failures).+ * 2. body matches a quota keyword → `"quota_exhausted"`.+ * 3. otherwise → `"rate_limit"` (default for 429 — even without+ * Retry-After, a 429 is per definition a rate-limit signal).+ *+ * @param response - the upstream response with status, optional headers,+ * optional body. Headers are looked up+ * case-insensitively.+ */+export function classify429(response: {+ status: number;+ headers?: Record<string, string>;+ body?: unknown;+}): FailureKind {+ if (response.status !== 429) return "transient";+ if (looksLikeQuotaExhausted(response.body)) return "quota_exhausted";+ return "rate_limit";+}++/**+ * Parse a `Retry-After` header value into seconds.+ *+ * Accepts:+ * - integer seconds: `"60"`+ * - HTTP date: `"Wed, 08 May 2026 03:00:00 GMT"`+ * - Groq-style relative: `"60s"`, `"5m"`, `"2h"`+ *+ * Returns `null` if unparseable.+ *+ * Note: integer seconds vs Groq relative units are easy to confuse —+ * `parseInt("5m", 10)` returns `5` (parses leading digits and ignores+ * trailing). This helper checks the relative-unit pattern FIRST.+ */+export function parseRetryAfter(headerValue: string | undefined): number | null {+ if (!headerValue) return null;+ const trimmed = headerValue.trim();+ if (!trimmed) return null;++ // Groq-style relative: must check BEFORE plain int parse.+ const relMatch = trimmed.match(/^(\d+)([smh])$/i);+ if (relMatch) {+ const n = Number(relMatch[1]);+ const unit = relMatch[2].toLowerCase();+ if (Number.isFinite(n)) {+ if (unit === "s") return n;+ if (unit === "m") return n * 60;+ if (unit === "h") return n * 3600;+ }+ }++ // Pure integer seconds.+ if (/^\d+$/.test(trimmed)) {+ const n = Number(trimmed);+ return Number.isFinite(n) ? n : null;+ }++ // HTTP date.+ const ts = Date.parse(trimmed);+ if (Number.isFinite(ts)) {+ return Math.max(0, Math.floor((ts - Date.now()) / 1000));+ }++ return null;+}++/**+ * Convenience wrapper: pull the Retry-After from a response's headers+ * and parse it to seconds. Returns null if absent or unparseable.+ */+export function retryAfterFromResponse(response: {+ headers?: Record<string, string>;+}): number | null {+ return parseRetryAfter(getHeader(response.headers, "retry-after"));+}diff --git a/tests/unit/circuit-breaker-failure-kind.test.ts b/tests/unit/circuit-breaker-failure-kind.test.tsnew file mode 100644index 0000000000..478b26db88--- /dev/null+++ b/tests/unit/circuit-breaker-failure-kind.test.ts@@ -0,0 +1,234 @@+/**+ * Tests for circuit breaker per-failure-kind cooldowns (Issue #2100).+ *+ * Each test creates a uniquely-named breaker so SQLite-backed state from+ * `loadCircuitBreakerState()` cannot leak between tests when run in any+ * order or with --test-concurrency > 1.+ */+import { test } from "node:test";+import assert from "node:assert/strict";+import {+ CircuitBreaker,+ resetAllCircuitBreakers,+ getCircuitBreaker,+} from "../../src/shared/utils/circuitBreaker.ts";+import type { FailureKind } from "../../src/shared/utils/classify429.ts";++const uniqueName = (suffix: string) =>+ `cb-test-#2100-${suffix}-${Date.now()}-${Math.floor(Math.random() * 1e6)}`;++test("default behavior unchanged when neither cooldownByKind nor classifyError is set", () => {+ const cb = new CircuitBreaker(uniqueName("legacy"), {+ failureThreshold: 2,+ resetTimeout: 30_000,+ });+ cb._onFailure();+ cb._onFailure();+ assert.equal(cb.state, "OPEN");+ assert.equal(cb.lastFailureKind, null);+ // Cooldown is the legacy resetTimeout — not biased by kind.+ const t = cb._timeUntilReset();+ assert.ok(t > 29_000 && t <= 30_000, `expected ~30s, got ${t}`);+ cb.reset();+});++test("cooldownByKind: quota_exhausted gets longer cooldown than rate_limit", () => {+ const cb = new CircuitBreaker(uniqueName("kind-cooldown"), {+ failureThreshold: 1,+ resetTimeout: 30_000,+ cooldownByKind: {+ rate_limit: 60_000,+ quota_exhausted: 3_600_000,+ },+ });++ cb._onFailure("rate_limit");+ assert.equal(cb.state, "OPEN");+ assert.equal(cb.lastFailureKind, "rate_limit");+ const tRate = cb._timeUntilReset();+ assert.ok(tRate > 59_000 && tRate <= 60_000, `rate_limit cooldown: expected ~60s, got ${tRate}`);++ cb.reset();+ cb._onFailure("quota_exhausted");+ const tQuota = cb._timeUntilReset();+ assert.ok(+ tQuota > 3_599_000 && tQuota <= 3_600_000,+ `quota_exhausted cooldown: expected ~3600s, got ${tQuota}`,+ );++ cb.reset();+});++test("cooldownByKind falls back to resetTimeout when no override for the kind", () => {+ const cb = new CircuitBreaker(uniqueName("partial-cooldown"), {+ failureThreshold: 1,+ resetTimeout: 45_000,+ cooldownByKind: {+ quota_exhausted: 3_600_000,+ // rate_limit intentionally omitted — should use resetTimeout+ },+ });+ cb._onFailure("rate_limit");+ const t = cb._timeUntilReset();+ assert.ok(t > 44_000 && t <= 45_000, `expected ~45s fallback, got ${t}`);+ cb.reset();+});++test("cooldownByKind falls back to resetTimeout when lastFailureKind is null", () => {+ const cb = new CircuitBreaker(uniqueName("null-kind"), {+ failureThreshold: 1,+ resetTimeout: 30_000,+ cooldownByKind: {+ rate_limit: 60_000,+ quota_exhausted: 3_600_000,+ },+ });+ // Old-style call site that doesn't classify — kind stays null.+ cb._onFailure();+ assert.equal(cb.lastFailureKind, null);+ const t = cb._timeUntilReset();+ assert.ok(t > 29_000 && t <= 30_000, `expected resetTimeout fallback, got ${t}`);+ cb.reset();+});++test("classifyError on execute() routes errors to the correct kind", async () => {+ const cb = new CircuitBreaker(uniqueName("classifier"), {+ failureThreshold: 1,+ resetTimeout: 1_000,+ cooldownByKind: { quota_exhausted: 600_000 },+ classifyError: (err: unknown): FailureKind | undefined => {+ if (err instanceof Error && err.message.includes("daily limit")) {+ return "quota_exhausted";+ }+ return "transient";+ },+ });++ await assert.rejects(async () => {+ await cb.execute(async () => {+ throw new Error("You exceeded your daily limit");+ });+ });++ assert.equal(cb.state, "OPEN");+ assert.equal(cb.lastFailureKind, "quota_exhausted");+ const t = cb._timeUntilReset();+ assert.ok(t > 599_000 && t <= 600_000, `expected ~600s quota cooldown, got ${t}`);+ cb.reset();+});++test("_onSuccess clears lastFailureKind on close transition", () => {+ const cb = new CircuitBreaker(uniqueName("success-clear"), {+ failureThreshold: 1,+ resetTimeout: 100,+ cooldownByKind: { rate_limit: 100 },+ });+ cb._onFailure("rate_limit");+ assert.equal(cb.lastFailureKind, "rate_limit");+ // simulate elapsed time & success path through _onSuccess (which the+ // combo path uses); after success, kind should clear and breaker close.+ cb._onSuccess();+ assert.equal(cb.lastFailureKind, null);+ assert.equal(cb.state, "CLOSED");+});++test("reset() clears lastFailureKind", () => {+ const cb = new CircuitBreaker(uniqueName("reset-clear"), {+ failureThreshold: 1,+ cooldownByKind: { rate_limit: 60_000 },+ });+ cb._onFailure("rate_limit");+ assert.equal(cb.lastFailureKind, "rate_limit");+ cb.reset();+ assert.equal(cb.lastFailureKind, null);+});++test("getCircuitBreaker registry merges new options on subsequent calls", () => {+ const name = uniqueName("registry-merge");+ const cb1 = getCircuitBreaker(name, { failureThreshold: 5 });+ // First call: no cooldownByKind, classifyError null+ assert.deepEqual(cb1.cooldownByKind, {});+ assert.equal(cb1.classifyError, null);+ // Second call: add overrides+ const cb2 = getCircuitBreaker(name, {+ cooldownByKind: { rate_limit: 60_000 },+ classifyError: () => "rate_limit" as FailureKind,+ });+ assert.equal(cb1, cb2, "registry returns same instance");+ assert.deepEqual(cb1.cooldownByKind, { rate_limit: 60_000 });+ assert.ok(typeof cb1.classifyError === "function");+ cb1.reset();+});++test("registry MERGES cooldownByKind across calls (does not replace)", () => {+ // Regression test for codex audit MEDIUM #1: if two registrations supply+ // disjoint keys, both must survive. Without spread-merge the second call+ // wiped the first.+ const name = uniqueName("registry-merge-keys");+ const cb1 = getCircuitBreaker(name, {+ cooldownByKind: { quota_exhausted: 3_600_000 },+ });+ assert.deepEqual(cb1.cooldownByKind, { quota_exhausted: 3_600_000 });+ const cb2 = getCircuitBreaker(name, {+ cooldownByKind: { rate_limit: 60_000 },+ });+ assert.equal(cb1, cb2);+ assert.deepEqual(cb1.cooldownByKind, {+ quota_exhausted: 3_600_000,+ rate_limit: 60_000,+ });+ cb1.reset();+});++test("classifyError throwing does not mask original error or skip _onFailure", async () => {+ // Regression test for codex audit MEDIUM #2.+ const cb = new CircuitBreaker(uniqueName("classifier-throws"), {+ failureThreshold: 1,+ resetTimeout: 1_000,+ classifyError: () => {+ throw new Error("classifier itself blew up");+ },+ });+ let caught: unknown;+ try {+ await cb.execute(async () => {+ throw new Error("original error");+ });+ } catch (e) {+ caught = e;+ }+ assert.ok(caught instanceof Error);+ assert.equal((caught as Error).message, "original error");+ assert.equal(cb.state, "OPEN", "failure was still recorded");+ assert.equal(cb.lastFailureKind, null, "kind defaults to null when classifier throws");+ cb.reset();+});++test("invalid cooldownByKind values (NaN, Infinity, negative) fall back to resetTimeout", () => {+ // Regression test for codex audit MEDIUM #3.+ const cb = new CircuitBreaker(uniqueName("invalid-cooldown"), {+ failureThreshold: 1,+ resetTimeout: 30_000,+ cooldownByKind: {+ rate_limit: NaN,+ quota_exhausted: -5_000,+ transient: Number.POSITIVE_INFINITY,+ },+ });+ for (const kind of ["rate_limit", "quota_exhausted", "transient"] as const) {+ cb.reset();+ cb._onFailure(kind);+ const t = cb._timeUntilReset();+ assert.ok(+ t > 29_000 && t <= 30_000,+ `expected resetTimeout fallback for ${kind}, got ${t}`,+ );+ }+ cb.reset();+});++// Cleanup: clear the registry (and SQLite-persisted breaker state) so this+// test file does not leak into others when --test-concurrency=10.+test("teardown — reset all circuit breakers", () => {+ resetAllCircuitBreakers();+});diff --git a/tests/unit/classify429.test.ts b/tests/unit/classify429.test.tsnew file mode 100644index 0000000000..bdf0e11d68--- /dev/null+++ b/tests/unit/classify429.test.ts@@ -0,0 +1,162 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import {+ classify429,+ looksLikeQuotaExhausted,+ parseRetryAfter,+ retryAfterFromResponse,+ type FailureKind,+} from "../../src/shared/utils/classify429.ts";++test("classify429: non-429 status returns 'transient'", () => {+ const out: FailureKind = classify429({ status: 500 });+ assert.equal(out, "transient");+});++test("classify429: 429 with no body or hints returns 'rate_limit'", () => {+ assert.equal(classify429({ status: 429 }), "rate_limit");+ assert.equal(classify429({ status: 429, body: "" }), "rate_limit");+ assert.equal(classify429({ status: 429, body: undefined }), "rate_limit");+});++test("classify429: 429 with quota keyword in string body returns 'quota_exhausted'", () => {+ assert.equal(+ classify429({ status: 429, body: "You exceeded your daily limit." }),+ "quota_exhausted",+ );+ assert.equal(+ classify429({ status: 429, body: "Monthly quota reached. Resets on the 1st." }),+ "quota_exhausted",+ );+ assert.equal(+ classify429({ status: 429, body: "Out of credits — top up your account." }),+ "quota_exhausted",+ );+ assert.equal(+ classify429({ status: 429, body: "plan limit reached" }),+ "quota_exhausted",+ );+});++test("classify429: 429 with quota keyword in nested object body returns 'quota_exhausted'", () => {+ assert.equal(+ classify429({+ status: 429,+ body: { error: { message: "You have exceeded your monthly quota." } },+ }),+ "quota_exhausted",+ );+ assert.equal(+ classify429({+ status: 429,+ body: { error: { type: "insufficient_quota", message: "..." } },+ }),+ "quota_exhausted",+ );+});++test("classify429: 429 without quota keyword returns 'rate_limit'", () => {+ // Plain rate-limit message — keyword 'rate' alone is NOT in QUOTA_PATTERNS+ // so classifier should default to "rate_limit" for any 429.+ assert.equal(+ classify429({ status: 429, body: "Too many requests. Try again in 60s." }),+ "rate_limit",+ );+ assert.equal(+ classify429({+ status: 429,+ body: "Rate limit reached for requests. Please retry.",+ }),+ "rate_limit",+ );+});++test("looksLikeQuotaExhausted: detects all known keyword variants", () => {+ for (const body of [+ "daily limit exceeded",+ "daily quota reached",+ "per-day limit reached",+ "monthly limit",+ "monthly quota",+ "per-month limit",+ "quota exceeded",+ "exceeded quota",+ "insufficient_quota",+ "billing cap reached",+ "credit exhausted",+ "out of credits",+ "hard limit",+ "hard-limit",+ "plan limit",+ ]) {+ assert.equal(looksLikeQuotaExhausted(body), true, `failed for: ${body}`);+ }+});++test("looksLikeQuotaExhausted: rejects empty / null / non-quota text", () => {+ assert.equal(looksLikeQuotaExhausted(undefined), false);+ assert.equal(looksLikeQuotaExhausted(null), false);+ assert.equal(looksLikeQuotaExhausted(""), false);+ assert.equal(looksLikeQuotaExhausted("rate limit, please retry in 60s"), false);+ assert.equal(looksLikeQuotaExhausted("server error 500"), false);+});++test("ambiguous 'daily rate limit' messages classify as quota_exhausted (intentional)", () => {+ // Codex audit LOW: messages combining 'daily' or 'monthly' with 'limit'+ // match the quota regex even when paired with 'rate'. This is intentional+ // because daily/monthly caps semantically warrant a long cooldown — even+ // when the upstream calls them "rate limits". Locking it down here so a+ // future regex tweak doesn't silently change the behavior.+ assert.equal(+ classify429({ status: 429, body: "daily rate limit exceeded" }),+ "quota_exhausted",+ );+ assert.equal(+ classify429({ status: 429, body: "monthly rate limit exceeded" }),+ "quota_exhausted",+ );+});++test("parseRetryAfter: integer seconds", () => {+ assert.equal(parseRetryAfter("60"), 60);+ assert.equal(parseRetryAfter("3600"), 3600);+ assert.equal(parseRetryAfter("0"), 0);+});++test("parseRetryAfter: Groq-style relative units", () => {+ // Regression for the parseInt-trap: parseInt("5m", 10) returns 5,+ // which would be wrong (5s instead of 300s). The relative-unit+ // pattern must be checked BEFORE plain integer parse.+ assert.equal(parseRetryAfter("60s"), 60);+ assert.equal(parseRetryAfter("5m"), 300);+ assert.equal(parseRetryAfter("2h"), 7200);+ assert.equal(parseRetryAfter("1H"), 3600);+});++test("parseRetryAfter: HTTP-date in the future", () => {+ const future = new Date(Date.now() + 60_000).toUTCString();+ const secs = parseRetryAfter(future);+ assert.ok(secs !== null);+ assert.ok(secs! >= 50 && secs! <= 65, `expected ~60, got ${secs}`);+});++test("parseRetryAfter: HTTP-date in the past clamps to 0", () => {+ const past = new Date(Date.now() - 5 * 60_000).toUTCString();+ assert.equal(parseRetryAfter(past), 0);+});++test("parseRetryAfter: unparseable returns null", () => {+ assert.equal(parseRetryAfter(undefined), null);+ assert.equal(parseRetryAfter(""), null);+ assert.equal(parseRetryAfter(" "), null);+ assert.equal(parseRetryAfter("not-a-date"), null);+ assert.equal(parseRetryAfter("60xyz"), null);+});++test("retryAfterFromResponse: case-insensitive header lookup", () => {+ assert.equal(retryAfterFromResponse({ headers: { "Retry-After": "30" } }), 30);+ assert.equal(retryAfterFromResponse({ headers: { "retry-after": "45" } }), 45);+ assert.equal(retryAfterFromResponse({ headers: { "RETRY-AFTER": "60s" } }), 60);+ assert.equal(retryAfterFromResponse({ headers: {} }), null);+ assert.equal(retryAfterFromResponse({}), null);+});