import * as plugins from './plugins.js'; const unifiedWindows = ['5h', '7d'] as const; /** HTTP bodies wrap the error as `{ type: 'error', error }`; stream error parts carry it bare. */ function readAnthropicErrorType(body: unknown): string | undefined { const envelope = plugins.readJsonRecord(body); const type = (plugins.readJsonRecord(envelope?.error) ?? envelope)?.type; return typeof type === 'string' ? type : undefined; } function unifiedHeader(headers: plugins.IModelCallFailure['headers'], name: string): string | undefined { return headers[`anthropic-ratelimit-unified-${name}`]; } /** The subscription window whose reset time equals the unified reset. */ function readUnifiedWindow(headers: plugins.IModelCallFailure['headers'], resetsAt: number | undefined): string | undefined { return unifiedWindows.find((window) => resetsAt !== undefined && plugins.readEpochSeconds(unifiedHeader(headers, `${window}-reset`)) === resetsAt); } /** * Anthropic subscriptions reject requests with `anthropic-ratelimit-unified-status: rejected` until * the unified reset; API keys answer throttling with 429 `rate_limit_error` and `retry-after`. */ export const classifyAnthropicLimit: plugins.TModelLimitClassifier = (failure) => { if (unifiedHeader(failure.headers, 'status') === 'rejected') { const resetsAt = plugins.readEpochSeconds(unifiedHeader(failure.headers, 'reset')); const window = readUnifiedWindow(failure.headers, resetsAt); return { kind: 'usage_limit', ...(resetsAt === undefined ? {} : { resetsAt }), ...(window === undefined ? {} : { window }), }; } if (failure.statusCode === 429 || readAnthropicErrorType(failure.body) === 'rate_limit_error') { return { kind: 'rate_limit' }; } return undefined; };