import { fetchJson } from "../http.ts"; import { amount, durationLabel, epoch, finite, headerNumber, label, list, numeric, object, percent, windowBucket, } from "../parse.ts"; import type { ProviderQuota, QuotaBucket, QuotaProvider } from "../types.ts"; export function codexAccountId(token: string): string | undefined { if (token.length > 64000) return undefined; const parts = token.split("."); if (parts.length !== 3 || !parts[1] || parts[1].length > 22000) return undefined; try { const payload = object( JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8")), ); const id = object(payload["https://api.openai.com/auth"])[ "chatgpt_account_id" ]; return typeof id === "string" && id.length > 0 && id.length <= 256 && !/[\u0000-\u001f\u007f]/.test(id) ? id : undefined; } catch { return undefined; } } function windows( data: unknown, prefix = "codex", scope?: string, ): QuotaBucket[] { const limits = object(data); const buckets: QuotaBucket[] = []; for (const name of ["primary", "secondary"] as const) { const raw = limits[`${name}_window`]; if (raw == null) continue; const w = object(raw); const seconds = finite(w["limit_window_seconds"]); const duration = seconds !== undefined && seconds > 0 ? finite(seconds * 1000) : undefined; // Missing duration is not evidence of a five-hour or weekly window. const title = durationLabel( duration, name === "primary" ? "Primary" : "Secondary", ); buckets.push( windowBucket( `${prefix}:${name}`, title, percent(w["used_percent"]), duration, epoch(w["reset_at"], 1000), scope, ), ); } return buckets; } export function parseCodex(data: unknown): ProviderQuota { const d = object(data); const buckets = windows(d["rate_limit"]); for (const raw of list(d["additional_rate_limits"])) { const extra = object(raw); const id = label(extra["metered_feature"]) ?? label(extra["limit_name"]); if (!id) continue; buckets.push( ...windows( extra["rate_limit"], `additional:${id}`, label(extra["limit_name"]) ?? id, ), ); } buckets.push( ...windows(d["code_review_rate_limit"], "code-review", "Code review"), ); if (d["credits"] != null) { const credits = object(d["credits"]); buckets.push({ id: "credits", label: "Credits", kind: "balance", observedAt: Date.now(), value: credits["unlimited"] === true ? { state: "unlimited" } : amount( "credits", undefined, undefined, numeric(credits["balance"]), ), }); } const cap = object(d["spend_control"])["individual_limit"]; if (cap != null) { const limit = object(cap); buckets.push({ id: "spend-cap", label: "Monthly credit limit", kind: "spend-cap", observedAt: Date.now(), period: { label: "Monthly", resetsAt: epoch(limit["reset_at"], 1000) }, value: amount( "credits", numeric(limit["used"]), numeric(limit["limit"]), numeric(limit["remaining"]), ), }); } return { provider: "openai-codex", name: "OpenAI Codex", buckets, observedAt: Date.now(), }; } export function parseCodexHeaders( headers: Record, ): ProviderQuota | undefined { const buckets: QuotaBucket[] = []; const prefixes = new Set(["codex"]); for (const key of Object.keys(headers).slice(0, 512)) { const match = /^x-(codex(?:-[a-z0-9-]+)?)-(?:primary|secondary)-used-percent$/.exec( key, ); if (match?.[1]) prefixes.add(match[1]); } for (const prefix of prefixes) { for (const name of ["primary", "secondary"] as const) { const base = `x-${prefix}-${name}`; const used = headerNumber(headers, `${base}-used-percent`); if (used === undefined) continue; const minutes = headerNumber(headers, `${base}-window-minutes`); const resetAt = headerNumber(headers, `${base}-reset-at`); // Codex emits zero-valued placeholders for windows that do not exist. if (used === 0 && (minutes ?? 0) === 0 && resetAt === undefined) continue; const duration = minutes !== undefined && minutes > 0 ? finite(minutes * 60000) : undefined; const id = prefix === "codex" ? prefix : `additional:${prefix.replaceAll("-", "_")}`; buckets.push( windowBucket( `${id}:${name}`, durationLabel(duration, name === "primary" ? "Primary" : "Secondary"), percent(used), duration, epoch(resetAt, 1000), prefix === "codex" ? undefined : (label(headers[`x-${prefix}-limit-name`]) ?? prefix), ), ); } } if (buckets.length === 0) return undefined; return { provider: "openai-codex", name: "OpenAI Codex", buckets, observedAt: Date.now(), }; } export const codex: QuotaProvider = { name: "OpenAI Codex", headers: parseCodexHeaders, async fetch(key) { const accountId = codexAccountId(key); if (!accountId) throw new Error("Codex account unavailable"); return parseCodex( await fetchJson("https://chatgpt.com/backend-api/wham/usage", { headers: { Authorization: `Bearer ${key}`, "ChatGPT-Account-Id": accountId, Accept: "application/json", Origin: "https://chatgpt.com", Referer: "https://chatgpt.com/", "User-Agent": "Mozilla/5.0", }, }), ); }, };