import { environmentsEncryptionKeyBytes, type Settings } from "@opengeni/config"; import { type CodexTokenSnapshot, type CodexUsagePayload, type CodexFetch, type CodexRateLimitResetCreditsDetails, type ResetCreditFetchFailureReason, refreshCodexToken } from "@opengeni/codex"; import { encryptEnvironmentValue } from "./environment-crypto.js"; import type { CodexPlanEntitlementExclusion } from "./codex-plan-entitlement.js"; import type { Database } from "./database.js"; export type CodexCredentialTokens = { accessToken: string; refreshToken: string; idToken: string; }; export type CodexCredentialCooldownKind = "quota" | "rate_limit"; export type CodexCredentialForRun = { id: string; version: number; workspaceId: string; tokens: CodexCredentialTokens; chatgptAccountId: string | null; scopes: string | null; planType: string | null; /** Plan before the most recent recorded plan change (see migration 0524). */ planPreviousType?: string | null; planChangedAt?: Date | null; /** Models the recorded plan was proven not to include, expired or not. */ planEntitlementExclusion?: CodexPlanEntitlementExclusion | null; isFedramp: boolean; expiresAt: Date | null; lastRefreshAt: Date | null; status: string; lastError: string | null; exhaustedUntil: Date | null; exhaustedKind: CodexCredentialCooldownKind | null; exhaustedRevision: number; }; export type CodexAccountUsageSnapshot = { primaryUsedPercent?: number | null; primaryResetAt?: Date | null; secondaryUsedPercent?: number | null; secondaryResetAt?: Date | null; checkedAt?: Date; resetCreditAvailableCount?: number | null; resetCreditsCheckedAt?: Date | null; /** * Provider-reported current ChatGPT plan (`plan_type`). Persisted with * `planCheckedAt`; a changed plan retires any plan entitlement exclusion. */ planType?: string | null; planCheckedAt?: Date; /** * Clear only a quota cooldown with this exact revision. Set solely after a * live provider response proves allowance is open; a concurrent refusal * advances the revision and makes this observation stale. */ clearQuotaCooldownRevision?: number; }; type CodexCredentialRefreshInput = { id: string; version: number; workspaceId: string; credentialEncrypted: string; expiresAt: Date | null; lastRefreshAt: Date; /** `chatgpt_plan_type` from a rotated id_token; omitted when none was returned. */ planType?: string | null; }; type CodexCredentialStatusTarget = { id: string; version: number; }; export type CodexCredentialTokenSnapshot = CodexTokenSnapshot & { /** Exact credential-row version whose bearer is about to reach the provider. */ credentialVersion: number; /** Plan recorded for that version (from the id_token of the latest refresh). */ planType?: string | null; }; export type CodexTokenDeadlineClock = { setTimeout: (callback: () => void, delayMs: number) => ReturnType; clearTimeout: (handle: ReturnType) => void; }; export type CodexTokenDeadlineOptions = { timeoutMs?: number | undefined; signal?: AbortSignal | undefined; clock?: CodexTokenDeadlineClock | undefined; }; /** * Bound a refresh promise without abandoning its rejection handler when the * deadline or cancellation wins. The provider promise is observed exactly * once, while the observer itself always fulfills, so a late provider failure * cannot become an unhandled rejection or replace the authoritative outcome. */ export declare function withCodexTokenDeadline(operation: Promise, options?: CodexTokenDeadlineOptions): Promise; export type CodexAuthDeps = { loadCredential: (db: Database, settings: Settings, workspaceId: string, credentialId: string) => Promise; recordRefresh: (db: Database, input: CodexCredentialRefreshInput) => Promise; setStatus: (db: Database, workspaceId: string, status: "active" | "needs_relogin" | "error", lastError: string | null, target: CodexCredentialStatusTarget) => Promise; refresh: typeof refreshCodexToken; encrypt: typeof encryptEnvironmentValue; keyBytes: typeof environmentsEncryptionKeyBytes; withRefreshLock: (db: Database, workspaceId: string, credentialId: string, fn: (lockedDb: Database) => Promise) => Promise; recordUsage?: (db: Database, workspaceId: string, credentialId: string, snapshot: CodexAccountUsageSnapshot) => Promise; /** * A token refresh observed a different plan on a credential that carried a * plan exclusion, which that write retired. Called after the refresh lock is * released so capacity waiters blocked by the exclusion can re-evaluate. */ onPlanExclusionRetired?: (db: Database, workspaceId: string, credentialId: string) => Promise; /** * Separates local refresh single-flight between resolvers that load the same * row under different authorities (for example Codex Apps versus inference), * so one caller never adopts another authority's outcome. The database refresh * lock still serializes them; the second re-reads the version and skips the * provider refresh. */ refreshKeyScope?: string; }; export declare function buildCodexTokenResolver(db: Database, settings: Settings, workspaceId: string, credentialId: string, deps: CodexAuthDeps): { getToken: () => Promise; refresh: () => Promise; }; /** * THE single per-account usage path both the api route and an (optional) worker * poll call, so the refresh discipline and the cache-write can never drift. * * 1. resolve a REFRESHING bearer for THIS account (proactive staleness refresh, * single-flight, (id,version) CAS-persist) — this is what stops an idle * account's expired JWT from 401-ing the usage read. * 2. fetch GET /wham/usage with that bearer. * 3. normalize (§3) into the P2/P3 contract. * 4. on any windows present, write the usage cache and conditionally reconcile * the exact older typed quota cooldown observed before provider I/O. * * A refresh that stamps needs_relogin returns { status:"error", reason } and never * hits the provider; a transient refresh error returns a plain error payload. */ export declare function fetchCodexUsageForAccount(db: Database, settings: Settings, workspaceId: string, credentialId: string, deps: CodexAuthDeps, fetchImpl?: CodexFetch): Promise; export type CodexCredentialPlanRecheck = { /** Plan recorded before this re-check (null when never observed). */ previousPlanType: string | null; /** Freshly observed plan, or null when neither provider source reported one. */ planType: string | null; source: "usage" | "token_refresh" | null; /** Credential version the observation belongs to (after any refresh). */ credentialVersion: number | null; /** * The credential's most recent recorded plan change after this observation * was persisted (including one this re-check itself observed). Ordinary * observers of an unchanged plan never overwrite it. */ planChangedFrom: string | null; planChangedAt: Date | null; /** Plan exclusion after this observation, including expired entries. */ exclusion: CodexPlanEntitlementExclusion | null; }; /** * Re-read one credential's CURRENT ChatGPT plan from the provider and persist * it. /wham/usage `plan_type` is tried first because it rotates no token; when * it reports no plan, one forced token refresh reads `chatgpt_plan_type` from * the new id_token (under the shared refresh lock and version CAS). Provider * failures produce `planType: null`, never an exception, so a caller can fall * back to its existing terminal behavior. The returned change record and * exclusion are read back after the observation is persisted. */ export declare function recheckCodexCredentialPlan(db: Database, settings: Settings, workspaceId: string, credentialId: string, deps: CodexAuthDeps, fetchImpl?: CodexFetch): Promise; export type CodexRateLimitResetCreditsAccountResult = { ok: true; status: number; details: CodexRateLimitResetCreditsDetails; } | { ok: false; status: number; reason: ResetCreditFetchFailureReason | "needs_relogin"; }; /** * Fresh detailed reset-credit inventory for one exact workspace credential. * The token is refreshed through the same resolver as usage and never escapes * this server-side function. Detailed rows are returned to the route only and * are never persisted as redemption authority. */ export declare function fetchCodexRateLimitResetCreditsForAccount(db: Database, settings: Settings, workspaceId: string, credentialId: string, deps: CodexAuthDeps, fetchImpl?: CodexFetch): Promise; export {};