Skip to content

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

3.9 KB
Raw Blame
/**
 * usage/codex.ts — Codex (OpenAI / ChatGPT backend) usage fetcher.
 *
 * Extracted from services/usage.ts (god-file decomposition): the Codex family — the ChatGPT
 * backend usage-API config and the getCodexUsage fetcher that reads the persisted workspace
 * binding and shapes quotas via buildCodexUsageQuotas. Depends only on the scalar leaf +
 * codexUsageQuotas — no host coupling — so it lives as a co-located provider leaf. usage.ts
 * imports getCodexUsage (dispatcher). Behavior-preserving move.
 */

import { buildCodexUsageQuotas } from "../codexUsageQuotas.ts";
import { fetchWithConnectionProxy } from "../connectionProxyFetch.ts";
import { getCodexBackendIdentityHeaders } from "../../config/codexClient.ts";
import { getFieldValue } from "./scalars.ts";

// Codex (OpenAI) API config
const CODEX_CONFIG = {
  usageUrl: "https://chatgpt.com/backend-api/wham/usage",
};

type CodexUsageFetch = (input: string, init: RequestInit) => Promise<Response>;
let codexUsageFetch: CodexUsageFetch = (input, init) => fetch(input, init);

/** Test-only: replace the usage request. Pass null to restore global fetch. */
export function setCodexUsageFetchForTests(fetchImpl: CodexUsageFetch | null): void {
  codexUsageFetch = fetchImpl ?? ((input, init) => fetch(input, init));
}

/**
 * Codex (OpenAI) Usage - Fetch from ChatGPT backend API
 * IMPORTANT: Uses persisted workspaceId from OAuth to ensure correct workspace binding.
 * No fallback to other workspaces - strict binding to user's selected workspace.
 */
export async function getCodexUsage(
  accessToken?: string,
  providerSpecificData: Record<string, unknown> = {},
  connectionId?: string
) {
  try {
    // Use persisted workspace ID from OAuth - NO FALLBACK
    const accountId =
      typeof providerSpecificData.workspaceId === "string"
        ? providerSpecificData.workspaceId
        : null;

    const headers: Record<string, string> = {
      Authorization: `Bearer ${accessToken}`,
      "Content-Type": "application/json",
      Accept: "application/json",
      // Same UA/version identity chain as Codex inference (sub2api v0.1.178
      // unified-outbound-identity): usage probes must not show up upstream as
      // an anonymous half-identity next to the converged inference traffic.
      ...getCodexBackendIdentityHeaders(),
    };
    if (accountId) {
      headers["chatgpt-account-id"] = accountId;
    }

    const response = connectionId
      ? await fetchWithConnectionProxy(
          connectionId,
          CODEX_CONFIG.usageUrl,
          {
            method: "GET",
            headers,
          },
          { fetchFn: codexUsageFetch }
        )
      : await codexUsageFetch(CODEX_CONFIG.usageUrl, {
          method: "GET",
          headers,
        });
    if (!response) {
      throw new Error("Codex API error: proxied request failed");
    }

    if (!response.ok) {
      if (response.status === 401 || response.status === 403) {
        return {
          message: `Codex token expired or access denied. Please re-authenticate the connection.`,
        };
      }
      throw new Error(`Codex API error: ${response.status}`);
    }

    const data = await response.json();

    const { rateLimit, quotas, bankedResetCredits, rateLimitReachedType, paidCredits } =
      buildCodexUsageQuotas(data);

    return {
      plan: String(getFieldValue(data, "plan_type", "planType") || "unknown"),
      limitReached: Boolean(getFieldValue(rateLimit, "limit_reached", "limitReached")),
      quotas,
      // Banked reset credits (display-only, eligibility-gated — issue #5199).
      // Absent for most accounts; never throws when the upstream omits it.
      ...(bankedResetCredits !== undefined ? { bankedResetCredits } : {}),
      ...(paidCredits ? { paidCredits } : {}),
      ...(rateLimitReachedType !== undefined ? { rateLimitReachedType } : {}),
    };
  } catch (error) {
    return { message: `Failed to fetch Codex usage: ${(error as Error).message}` };
  }
}