import * as plugins from './plugins.js'; import { readOpenAiError } from './smartai.limits.openai.js'; const codexUsageLimitIdentifiers: ReadonlySet = new Set(['usage_limit_reached', 'usage_not_included']); const codexWindows = ['primary', 'secondary'] as const; interface ICodexWindow { label: string; resetsAt: number; } function formatWindowMinutes(minutes: number): string { if (minutes % 1440 === 0) return `${minutes / 1440}d`; if (minutes % 60 === 0) return `${minutes / 60}h`; return `${minutes}m`; } function readExhaustedWindow(headers: plugins.IModelCallFailure['headers']): ICodexWindow | undefined { const exhausted = codexWindows.flatMap((name): ICodexWindow[] => { const usedPercent = Number(headers[`x-codex-${name}-used-percent`]); const minutes = Number(headers[`x-codex-${name}-window-minutes`]); const resetsAt = plugins.readEpochSeconds(headers[`x-codex-${name}-reset-at`]); if (!(usedPercent >= 100) || resetsAt === undefined) return []; return [{ label: Number.isSafeInteger(minutes) && minutes > 0 ? formatWindowMinutes(minutes) : name, resetsAt }]; }); // every exhausted window must reset before a request can pass return exhausted.sort((left, right) => right.resetsAt - left.resetsAt)[0]; } function readResetsInSeconds(value: unknown, observedAt: number): number | undefined { return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? observedAt + Math.round(value * 1000) : undefined; } /** * The ChatGPT Codex backend reports a spent plan quota as `usage_limit_reached`, and a plan * without Codex access as `usage_not_included`, in the 429 body or a `response.failed` frame. */ export const classifyOpenAiChatGptLimit: plugins.TModelLimitClassifier = (failure) => { const error = readOpenAiError(failure.body); if (!error?.identifiers.some((identifier) => codexUsageLimitIdentifiers.has(identifier))) return undefined; const exhaustedWindow = readExhaustedWindow(failure.headers); const resetsAt = plugins.readEpochSeconds(error.fields.resets_at) ?? readResetsInSeconds(error.fields.resets_in_seconds, failure.observedAt) ?? exhaustedWindow?.resetsAt; const planType = error.fields.plan_type; return { kind: 'usage_limit', ...(resetsAt === undefined ? {} : { resetsAt }), ...(typeof planType === 'string' ? { planType } : {}), ...(exhaustedWindow ? { window: exhaustedWindow.label } : {}), }; };