Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
22 changes: 22 additions & 0 deletions src/combos/failover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -360,10 +360,32 @@ function isProviderScopedQuotaCap(
) {
return true;
}
// A 400 or 422 is a verdict on the request, and its body echoes client values, so there the
// free-tier cap counts only as a field (see hasFreePromptCapField). Other statuses keep words.
if (status === 400 || status === 422) return hasFreePromptCapField(message);
return text.includes("err_free_prompt_cap")
|| (text.includes("free tier") && text.includes("single request"));
}

/**
* `err_free_prompt_cap` as the provider's own field: `error.code`, or `error.metadata.reason` as
* the OpenRouter-style free-tier refusal carries it, in a bounded JSON envelope after an optional
* `Provider error <status>: ` prefix. Never a word anywhere in the text.
*/
function hasFreePromptCapField(message: string): boolean {
if (message.length > 16_384) return false;
const text = message.trim().replace(/^Provider error \d{3}:\s*/, "");
let payload: unknown;
try { payload = JSON.parse(text); } catch { return false; }
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return false;
const error = (payload as Record<string, unknown>).error;
if (!error || typeof error !== "object" || Array.isArray(error)) return false;
const { code, metadata } = error as Record<string, unknown>;
if (code === "err_free_prompt_cap") return true;
return !!metadata && typeof metadata === "object" && !Array.isArray(metadata)
&& (metadata as Record<string, unknown>).reason === "err_free_prompt_cap";
}

/**
* A free-tier cap the upstream evaluates PER REQUEST rather than per account window. These
* needles used to reach only `isProviderScopedQuotaCap`, so a single oversized free-tier prompt
Expand Down
57 changes: 57 additions & 0 deletions src/lib/anthropic-extra-usage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/**
* Anthropic's quota refusal wordings: the HTTP 400s Anthropic sends for a spent account rather
* than a bad request. Shared by the pool rotation and by `classifyError`, so both read the
* refusal the same way.
*
* - Extra usage: an account whose plan AND extra usage are spent ("You're out of extra usage",
* "Third-party apps now draw from your extra usage").
* - Spend limit: usage reached an organization or workspace spend limit the customer set. Per
* https://platform.claude.com/docs/en/api/rate-limits#setting-your-own-spend-limit this is
* HTTP 400 `invalid_request_error` whose message starts with "You have reached your specified
* API usage limits" or "You have reached your specified workspace API usage limits".
*
* Only the start of `error.message` counts: a validation 400 echoes client values (tool ids,
* model names, prompt text) into its message, so a match anywhere else would let one crafted
* request pass as a spent account and cool healthy accounts or a whole combo provider.
*/
const QUOTA_REFUSAL = new RegExp(
"^(?:"
+ "you['\u2019]re out of extra usage"
+ "|third-party apps now draw from your extra usage"
+ "|you have reached your specified (?:workspace )?api usage limits"
+ ")",
"i",
);

function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}

/** Whether an already-extracted Anthropic `error.message` starts with a quota refusal wording. */
export function isAnthropicQuotaRefusalMessage(message: string): boolean {
return QUOTA_REFUSAL.test(message.trimStart());
}

/**
* Whether a parsed body is Anthropic's JSON error envelope (`type: "error"`,
* `error.type: "invalid_request_error"`) whose `error.message` starts with a quota refusal wording.
*/
export function isAnthropicQuotaRefusalEnvelope(payload: unknown): boolean {
if (!isRecord(payload) || payload.type !== "error" || !isRecord(payload.error)) return false;
const { type, message } = payload.error;
return type === "invalid_request_error"
&& typeof message === "string"
&& isAnthropicQuotaRefusalMessage(message);
}

/** {@link isAnthropicQuotaRefusalEnvelope} for a raw body; a non-JSON body is never the refusal. */
export function isAnthropicQuotaRefusalBody(body: string | null | undefined): boolean {
if (!body) return false;
let payload: unknown;
try {
payload = JSON.parse(body);
} catch {
return false;
}
return isAnthropicQuotaRefusalEnvelope(payload);
}
90 changes: 75 additions & 15 deletions src/lib/errors.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { isAnthropicQuotaRefusalEnvelope, isAnthropicQuotaRefusalMessage } from "./anthropic-extra-usage";
import { parseRetryAfterFromMessage } from "./retry-delay";

export interface OcxErrorPayload {
Expand Down Expand Up @@ -355,6 +356,47 @@ export function isUpstreamResetReplayRefusedMessage(text: string): boolean {
);
}

/** This proxy's prefix for an upstream 400/422 error, and the `type: ` lead a bridge formatter adds. */
const PROVIDER_ERROR_400_PREFIX = /^Provider error (?:400|422):\s*/i;
const INVALID_REQUEST_TYPE_LEAD = /^invalid_request_error:\s*/i;

/**
* Quota evidence in an HTTP 400 or 422, read from fields, never from words anywhere in the text.
*
* A 400/422 is a verdict on the request, and providers echo client values into it: Anthropic's
* validation errors quote tool ids and content ("messages.3.content...: toolu_insufficient_quota").
* Matching quota words anywhere let one crafted request read as a spent account and cool a whole
* combo provider for ten minutes. So a 400/422 is quota only when, after this proxy's
* `Provider error 400: ` (or `422: `) prefix:
* - it is a JSON error envelope whose `error.code` or `error.type` FIELD is `insufficient_quota`
* (OpenAI/Codex, and this proxy's own re-wrapped error), whose `error.code` is Volcengine Ark's
* `InvalidSubscription` (HTTP 400, Coding Plan not subscribed or expired:
* https://www.volcengine.com/docs/82379/1299023), or Anthropic's envelope whose `error.message`
* starts with a quota refusal wording (src/lib/anthropic-extra-usage.ts); an envelope whose
* `error.message` is again `Provider error 400: ...` is read the same way, at most three deep;
* - or it is not JSON and STARTS with such a wording (optionally after `invalid_request_error: `),
* which is a caller passing the already-extracted `error.message`.
* A truncated or malformed JSON body is never quota.
*/
function isQuotaBadRequestMessage(message: string): boolean {
let text = message.trim();
for (let depth = 0; depth < 3; depth += 1) {
text = text.replace(PROVIDER_ERROR_400_PREFIX, "");
if (!text.startsWith("{")) return isAnthropicQuotaRefusalMessage(text.replace(INVALID_REQUEST_TYPE_LEAD, ""));
let payload: unknown;
try { payload = JSON.parse(text); } catch { return false; }
if (isAnthropicQuotaRefusalEnvelope(payload)) return true;
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return false;
const error = (payload as { error?: unknown }).error;
if (!error || typeof error !== "object" || Array.isArray(error)) return false;
const { code, type, message: inner } = error as Record<string, unknown>;
if (code === "insufficient_quota" || type === "insufficient_quota" || code === "InvalidSubscription") return true;
if (typeof inner !== "string" || !PROVIDER_ERROR_400_PREFIX.test(inner.trim())) return false;
text = inner.trim();
}
return false;
}

export function classifyError(status: number, type: string, message: string): OcxErrorPayload {
const text = message.toLowerCase();
if (type === "previous_response_not_found") {
Expand Down Expand Up @@ -419,23 +461,27 @@ export function classifyError(status: number, type: string, message: string): Oc
// The Cursor adapter's classified rate-limit prefix is authoritative: its DETAIL may echo
// quota wording ("... quota exhausted") that would otherwise hit the insufficient_quota
// branch below and break the planned retry-with-backoff contract (WP3 review blocker 1).
if (text.includes("cursor rate limit exceeded")) {
//
// No quota or rate verdict on a 400 or 422 comes from words anywhere in its text: see
// isQuotaBadRequestMessage. Those verdicts hop a combo and cool its target or provider.
const badRequest = status === 400 || status === 422;
if (!badRequest && text.includes("cursor rate limit exceeded")) {
return { message, type: "rate_limit_error", code: "rate_limit_exceeded" };
}
if (
if (badRequest ? isQuotaBadRequestMessage(message) : (
text.includes("insufficient_quota") ||
text.includes("exceeded your current quota") ||
text.includes("quota exhausted") ||
text.includes("account quota exceeded") ||
text.includes("monthly quota exceeded") ||
text.includes("daily quota exceeded") ||
// Anthropic answers a spent plan with HTTP 400, not 429; without this it classifies as
// invalid_request_error, a hard stop, and a combo never hops to its next tier.
// Anthropic answers a spent plan with HTTP 400, not 429 (a 400 is read by
// isQuotaBadRequestMessage above); these cover callers without the upstream status.
text.includes("out of extra usage") ||
// Same spent-plan state, newer wording: a third-party client is refused with HTTP 400 because
// its usage now bills against extra usage, not the plan limits.
text.includes("third-party apps now draw from your extra usage")
) {
)) {
return { message, type: "insufficient_quota", code: "insufficient_quota" };
}
// A refusal this proxy made itself, kept apart from the provider rate limits below. The HTTP
Expand All @@ -447,14 +493,15 @@ export function classifyError(status: number, type: string, message: string): Oc
return { message, type: "rate_limit_error", code: SEND_BUDGET_EXHAUSTED_CODE };
}
if (
status === 429 ||
text.includes("rate limit") ||
text.includes("rate limited") ||
text.includes("too many requests") ||
text.includes("resource_exhausted") ||
text.includes("resource exhausted") ||
text.includes("throttlingexception") ||
text.includes("throttling")
status === 429 || (!badRequest && (
text.includes("rate limit") ||
text.includes("rate limited") ||
text.includes("too many requests") ||
text.includes("resource_exhausted") ||
text.includes("resource exhausted") ||
text.includes("throttlingexception") ||
text.includes("throttling")
))
) {
return { message, type: "rate_limit_error", code: "rate_limit_exceeded" };
}
Expand Down Expand Up @@ -529,14 +576,20 @@ export function classifyError(status: number, type: string, message: string): Oc
return { message, type, code: type || null };
}

/** `Provider error <status>` or `Provider error <status>: <body>`, exactly as this proxy writes it. */
const EXPLICIT_PROVIDER_STATUS = /^Provider error ([1-5]\d\d)(?::|$)/;

/**
* True when a provider failure should participate in rate-limit / quota health blocking.
* Reuses {@link classifyError} so generic 429 wording and quota phrases stay aligned.
*/
export function isRateLimitOrQuotaFailureMessage(message: string): boolean {
const normalized = String(message ?? "").trim();
if (!normalized) return false;
const numericStatus = Number(normalized);
// This proxy's `Provider error <status>` prefix states the status; the body after it echoes
// client values, so an explicit 400 is read by classifyError's 400 rules, not by its words.
const explicit = EXPLICIT_PROVIDER_STATUS.exec(normalized);
const numericStatus = explicit ? Number(explicit[1]) : Number(normalized);
if (numericStatus === 429 || numericStatus === 402) return true;
const statusHint = Number.isInteger(numericStatus) && numericStatus > 0 ? numericStatus : 0;
const classified = classifyError(statusHint, "", normalized);
Expand All @@ -548,7 +601,9 @@ export function isRateLimitOrQuotaFailureMessage(message: string): boolean {
) {
return true;
}
// Retained quota cue used by subagent health before classifyError covered it.
// Retained quota cue used by subagent health before classifyError covered it. Not for an
// explicit other 4xx: that is a verdict on the request, and the words may be the client's.
if (explicit && statusHint >= 400 && statusHint < 500) return false;
return normalized.toLowerCase().includes("usage limit");
}

Expand All @@ -561,6 +616,11 @@ export function inferHttpStatusFromAdapterMessage(message: string): number {
if (isClientClosedMessage(lower)) return 499;
// Codex Transport maps cyber_policy only on HTTP 400 (SSE is code-based).
if (isCyberPolicyMessage(lower)) return 400;
// This proxy's own `Provider error <status>` prefix states the upstream status outright. The
// text after it is the provider's body, which echoes client values, so a 400 that quotes
// "rate limit" must stay 400 rather than turn into a 429 that cools a combo target.
const explicit = EXPLICIT_PROVIDER_STATUS.exec(message.trimStart());
if (explicit) return Number(explicit[1]);
// See classifyError: this prefix now only means explicit request-size overflow (400);
// quota-style Cursor resource exhaustion carries the rate-limit prefix and maps to 429.
if (lower.includes("cursor resource limit exceeded")) return 400;
Expand Down
40 changes: 10 additions & 30 deletions src/oauth/anthropic-pool-rotation.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,25 @@
import { isAnthropicQuotaRefusalBody } from "../lib/anthropic-extra-usage";
import { readQuotaResetAt } from "../providers/key-failover";

/**
* Why an upstream answer may move a request to the next Anthropic pool account.
*
* - `"429"`: a rate or quota limit, the original trigger.
* - `"quota-400"`: Anthropic answers an account whose plan AND extra usage are spent with
* HTTP 400 ("You're out of extra usage", "Third-party apps now draw from your extra usage"),
* not 429. The account is spent; another pool account may not be.
* - `"quota-400"`: Anthropic answers a spent account with HTTP 400, not 429: plan AND extra
* usage spent ("You're out of extra usage", "Third-party apps now draw from your extra usage"),
* or a spend limit the customer set ("You have reached your specified [workspace] API usage
* limits"). The account is spent; another pool account may not be.
*/
export type AnthropicPoolRotationTrigger = "429" | "quota-400";

/**
* Anthropic's spent-extra-usage wordings, anchored at the start of `error.message`. Only the
* start counts: a validation 400 echoes client values (tool ids, model names, text) into its
* message, so a match anywhere else would let one crafted request cool every pool account.
*/
const EXTRA_USAGE_REFUSAL = /^(?:you['\u2019]re out of extra usage|third-party apps now draw from your extra usage)/i;

function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}

/**
* Whether a 400 body is Anthropic's out-of-extra-usage refusal. It must be Anthropic's JSON error
* envelope (`type: "error"`, `error.type: "invalid_request_error"`) whose `error.message` starts
* with one of the two wordings. Anything else, including a non-JSON body, is a request-shape
* failure that would fail the same way on any account and must not rotate.
* Whether a 400 body is Anthropic's quota refusal: Anthropic's JSON error envelope whose
* `error.message` starts with one of its quota refusal wordings (src/lib/anthropic-extra-usage.ts).
* Anything else, including a non-JSON body, is a request-shape failure that would fail the same
* way on any account and must not rotate.
*/
export function isQuotaExhaustedBadRequest(status: number, body: string | null | undefined): boolean {
if (status !== 400 || !body) return false;
let payload: unknown;
try {
payload = JSON.parse(body);
} catch {
return false;
}
if (!isRecord(payload) || payload.type !== "error" || !isRecord(payload.error)) return false;
const { type, message } = payload.error;
return type === "invalid_request_error"
&& typeof message === "string"
&& EXTRA_USAGE_REFUSAL.test(message.trimStart());
return status === 400 && isAnthropicQuotaRefusalBody(body);
}

/** The pool-rotation trigger for an upstream status and (for a 400) its body, or null. */
Expand Down
3 changes: 2 additions & 1 deletion src/server/responses/compact.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1345,7 +1345,8 @@ export async function handleResponsesCompact(
const bodyInferredQuota = !replayRefused
&& !buffered.ok
&& !explicitQuotaStatus
&& isRateLimitOrQuotaFailureMessage(bufferedErrorText);
// With the real status, so an echoing 400/422 body is read by its fields, not its words.
&& isRateLimitOrQuotaFailureMessage(`Provider error ${buffered.status}: ${bufferedErrorText}`);
const quotaFailure = explicitQuotaStatus || bodyInferredQuota;
// Record pool health only after the body is fully delivered (or definitively failed).
// A premature 200 would clear soft-avoid while the client still sees a buffer 502.
Expand Down
Loading
Loading