ccdeck 1.43.0 → 1.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,171 @@
1
+ // Where OpenAI Codex lives on this machine: its home directory, its rollout
2
+ // tree, and the walk over that tree — the Codex-side mirror of claude-dir.mjs.
3
+ //
4
+ // CODEX_HOME relocates ~/.codex wholesale, exactly as CLAUDE_CONFIG_DIR does on
5
+ // the Claude side, and five modules used to answer the question for themselves
6
+ // in three different spellings (#375):
7
+ //
8
+ // index.mjs CODEX_HOME ? resolve(CODEX_HOME) : join(homedir(), ".codex")
9
+ // installer.mjs the same
10
+ // codex-usage.mjs CODEX_HOME ? CODEX_HOME : join(homedir(), ".codex")
11
+ // codex-auth.mjs CODEX_HOME ?? join(homedir(), ".codex")
12
+ // codex-quota.mjs the same
13
+ //
14
+ // The three spellings disagree on two inputs that a shell profile produces by
15
+ // accident rather than by intent, and both disagreements are silent:
16
+ //
17
+ // CODEX_HOME="" — what `export CODEX_HOME=$SOME_UNSET_VAR` leaves behind.
18
+ // `??` only falls back on null and undefined, so the two modules spelled
19
+ // that way kept the empty string and then joined onto it: join("",
20
+ // "auth.json") is "auth.json", a CWD-RELATIVE path. codex-auth.mjs is the
21
+ // module that writes the rotated OpenAI refresh token back to disk, and
22
+ // OpenAI rotates that token single-use — so writing it to whatever
23
+ // directory the deck happened to be started from does not merely lose a
24
+ // read, it burns the credential and costs the user a `codex login`.
25
+ //
26
+ // CODEX_HOME=./relative — kept verbatim by three of the five, so the tree
27
+ // they read was resolved against the CWD at the moment of each readdir()
28
+ // rather than once at startup. Two modules therefore read a different
29
+ // directory than the other three whenever the deck was started from
30
+ // anywhere but the parent of that relative path.
31
+ //
32
+ // This module is the single answer to all of it, and every reader now imports
33
+ // it. The rule is the `resolve()` + truthiness form index.mjs and installer.mjs
34
+ // already used, because it is the one the installer writes against and the one
35
+ // that treats an empty value as "not set" — see codexHome() for why that is the
36
+ // right way round rather than merely the majority.
37
+ import { readdir } from "node:fs/promises";
38
+ import { homedir } from "node:os";
39
+ import { join, posix as posixPath, win32 as winPath } from "node:path";
40
+
41
+ /**
42
+ * Absolute path of the Codex home directory: $CODEX_HOME or ~/.codex.
43
+ *
44
+ * WHY AN EMPTY VALUE FALLS BACK. An empty environment variable is not a path.
45
+ * It is what a shell leaves behind when the variable it was assigned from does
46
+ * not exist, and treating it as "the current directory" turns a typo in a
47
+ * profile into a deck that reads and WRITES Codex state in whatever directory
48
+ * it was launched from. Falling back to ~/.codex is the only reading that can
49
+ * be right by accident; there is no user who means "put my Codex credentials in
50
+ * $PWD" and spells it by leaving the variable empty.
51
+ *
52
+ * WHY IT IS TRIMMED. Same argument one step further: `CODEX_HOME=" "` is the
53
+ * same accident with a stray space in the profile line, and claudeConfigDir()
54
+ * has trimmed for exactly this reason since it was written. Trimming only ever
55
+ * removes leading and trailing whitespace, so a real path that CONTAINS spaces
56
+ * — `/Users/me/Library/Application Support/codex` — is untouched, which is the
57
+ * case worth protecting on macOS and Windows both.
58
+ *
59
+ * WHY resolve() AND NOT realpath(). resolve() makes a relative value absolute
60
+ * once, here, instead of leaving every later readdir() to resolve it against
61
+ * whatever the CWD is by then. It deliberately does NOT follow symlinks:
62
+ * ~/.codex is often a link into a dotfiles repo or an encrypted volume, and
63
+ * canonicalising it would (a) require the directory to already exist, which it
64
+ * does not before the first `codex login`, and (b) make the deck rename over
65
+ * the link's target instead of through the link — the very thing codex-auth.mjs
66
+ * resolves symlinks at WRITE time to avoid. A symlinked CODEX_HOME therefore
67
+ * stays spelled the way the user spelled it, on purpose.
68
+ *
69
+ * The environment, home directory and platform are parameters purely so this
70
+ * rule can be checked for a machine the author is not sitting at: the Windows
71
+ * answer — drive letters, backslashes, a trailing `\` — is only ever verifiable
72
+ * from a POSIX box if the path flavour follows the argument rather than the
73
+ * host, the same trick exec.mjs and claudeCliCandidates() already use. Every
74
+ * caller in the deck passes nothing and gets the real machine's answer.
75
+ */
76
+ export function codexHome(env = process.env, home = homedir(), platform = process.platform) {
77
+ // The path flavour follows the PLATFORM ARGUMENT, not the host, so that a
78
+ // Windows value is normalised by Windows rules even when the check runs on a
79
+ // Mac. On a real machine `platform` is `process.platform`, which makes this
80
+ // the same `join`/`resolve` the module would have imported anyway.
81
+ const path = platform === "win32" ? winPath : posixPath;
82
+ const override = env.CODEX_HOME?.trim();
83
+ return override ? path.resolve(override) : path.join(home, ".codex");
84
+ }
85
+
86
+ /**
87
+ * Absolute path of the rollout tree: $CODEX_HOME/sessions.
88
+ *
89
+ * Codex writes one append-only JSONL file per session under
90
+ * sessions/YYYY/MM/DD/, and this directory is the root of every walk below. It
91
+ * lives here rather than being spelled `join(CODEX_HOME, "sessions")` at each
92
+ * of the three walkers, because that spelling was already duplicated verbatim
93
+ * in index.mjs and codex-usage.mjs and had no owner to drift away from.
94
+ */
95
+ export function codexSessionsDir(env = process.env, home = homedir(), platform = process.platform) {
96
+ const path = platform === "win32" ? winPath : posixPath;
97
+ return path.join(codexHome(env, home, platform), "sessions");
98
+ }
99
+
100
+ /**
101
+ * The answers for THIS process, resolved once at load.
102
+ *
103
+ * Every consumer imports these constants rather than calling the functions,
104
+ * which is what makes it impossible for two modules to disagree: there is now a
105
+ * single evaluation in the whole process instead of one per importing module.
106
+ * The functions above stay exported because the constants cannot be re-derived
107
+ * for a hypothetical environment, and the rule they encode is the thing worth
108
+ * pinning against every shape a CODEX_HOME can take.
109
+ */
110
+ export const CODEX_HOME = codexHome();
111
+ export const CODEX_SESSIONS_DIR = codexSessionsDir();
112
+
113
+ /**
114
+ * Returned from a walkRolloutDays visitor to end the walk immediately.
115
+ *
116
+ * A symbol rather than `true` because two of the three callers build their
117
+ * result by pushing into an array inside the visitor, and `Array.prototype.push`
118
+ * returns a number — a truthy-return protocol would have made "I collected two
119
+ * files" indistinguishable from "stop now".
120
+ */
121
+ export const STOP = Symbol("stop-rollout-walk");
122
+
123
+ /**
124
+ * Walk $CODEX_HOME/sessions/YYYY/MM/DD newest-first, handing each day directory
125
+ * and the names inside it to `onDay(dir, files)`.
126
+ *
127
+ * Three callers walked this tree with the same four nested readdir-and-continue
128
+ * blocks and differed only in the last few lines: find the file carrying a given
129
+ * session id (index.mjs), collect everything in the newest two day directories
130
+ * (index.mjs again, for the watcher), and collect everything whose filename
131
+ * timestamp falls inside a rolling window (codex-usage.mjs). The walk is the
132
+ * part that has to agree — a deck that tails one set of files and reports usage
133
+ * from another is reporting on a session it is not showing.
134
+ *
135
+ * EVERY LEVEL SWALLOWS ITS OWN ERROR, which is deliberate rather than lazy. The
136
+ * tree is written by another process while this one reads it: a day directory
137
+ * can be created between the listing of its month and the listing of itself, a
138
+ * year directory can be a broken symlink on a restored backup, and none of that
139
+ * is a reason to stop reading the other 364 days. A missing sessions/ directory
140
+ * is not an error at all — it is simply a machine where Codex has not run yet.
141
+ *
142
+ * `onYear` exists for the one caller that can rule out a whole year without
143
+ * opening it. Years arrive newest-first, so returning STOP from it ends the
144
+ * walk rather than skipping a year, which is what the caller wants: once the
145
+ * years are older than the window, so is everything after them.
146
+ */
147
+ export async function walkRolloutDays(onDay, { sessionsDir = CODEX_SESSIONS_DIR, onYear = null } = {}) {
148
+ let years;
149
+ // Only four-digit names are Codex's own. The filter also keeps a stray
150
+ // `.DS_Store` or a `latest` symlink from costing a readdir that would fail.
151
+ try { years = (await readdir(sessionsDir)).filter(d => /^\d{4}$/.test(d)).sort().reverse(); }
152
+ catch { return; }
153
+ for (const year of years) {
154
+ if (onYear && (await onYear(year)) === STOP) return;
155
+ let months;
156
+ try { months = (await readdir(join(sessionsDir, year))).sort().reverse(); }
157
+ catch { continue; }
158
+ for (const month of months) {
159
+ let days;
160
+ try { days = (await readdir(join(sessionsDir, year, month))).sort().reverse(); }
161
+ catch { continue; }
162
+ for (const day of days) {
163
+ const dir = join(sessionsDir, year, month, day);
164
+ let files;
165
+ try { files = await readdir(dir); }
166
+ catch { continue; }
167
+ if ((await onDay(dir, files)) === STOP) return;
168
+ }
169
+ }
170
+ }
171
+ }
@@ -0,0 +1,445 @@
1
+ // Fetches Codex/ChatGPT quota from the same endpoint the Codex CLI uses.
2
+ // Auth (including token refresh) lives in codex-auth.mjs.
3
+ //
4
+ // The response is deliberately parsed defensively: OpenAI ships new plan
5
+ // types, new limit families and new numeric encodings without warning, and a
6
+ // menu-bar-style readout is worth more when it degrades to "some lanes" than
7
+ // when one unrecognised field blanks the whole panel. So every section is
8
+ // optional, unknown values pass through verbatim, and a `partial` flag tells
9
+ // the UI when something was dropped instead of silently showing less.
10
+ import { readFile } from "node:fs/promises";
11
+ import { join } from "node:path";
12
+ import { CODEX_HOME } from "./codex-dir.mjs";
13
+ import { getCodexAuth, forceCodexRefresh, isCredentialHost } from "./codex-auth.mjs";
14
+ import { PRODUCT } from "./brand.mjs";
15
+ import { resetLabel } from "./reset-label.mjs";
16
+
17
+ // Resolved by codex-dir.mjs rather than here. This file used to spell it
18
+ // `process.env.CODEX_HOME ?? join(homedir(), ".codex")`, which keeps an empty
19
+ // CODEX_HOME instead of falling back — and then read a CWD-relative
20
+ // "config.toml" for the base URL every credential below is sent to (#375).
21
+ const CONFIG_PATH = join(CODEX_HOME, "config.toml");
22
+ const DEFAULT_BASE = "https://chatgpt.com/backend-api";
23
+
24
+ let _cache = null;
25
+ let _cacheAt = 0;
26
+ const CACHE_MS = 60_000;
27
+
28
+ // The last base URL we refused, so the refusal is said once rather than once a
29
+ // minute for as long as the config stays that way.
30
+ let _warnedBase = null;
31
+
32
+ // ── base URL ───────────────────────────────────────────────────────────────
33
+ // `chatgpt_base_url` in config.toml can point at a proxy, and the path style
34
+ // follows from its shape exactly as in the CLI: a /backend-api base speaks
35
+ // /wham/*, anything else speaks /api/codex/*.
36
+ //
37
+ // Whatever it says, the request below carries `Authorization: Bearer
38
+ // <accessToken>` — a live ChatGPT session — so the value is not just a routing
39
+ // preference, it is the answer to "who gets the credential". It was taken
40
+ // verbatim: a line regex, quotes stripped, straight into fetch(), which meant
41
+ // anything able to write that TOML (or to set $CODEX_HOME and point it at its
42
+ // own) could redirect the token to a host of its choosing, over plaintext http
43
+ // if it liked. isCredentialHost is where the two rules live.
44
+ async function readBaseUrl() {
45
+ let raw = null;
46
+ try {
47
+ const text = await readFile(CONFIG_PATH, "utf8");
48
+ for (const line of text.split("\n")) {
49
+ const m = line.replace(/#.*$/, "").match(/^\s*chatgpt_base_url\s*=\s*(.+?)\s*$/);
50
+ if (m) { raw = m[1].replace(/^["']|["']$/g, "").trim(); break; }
51
+ }
52
+ } catch { /* no config.toml — use the default */ }
53
+
54
+ let base = (raw || DEFAULT_BASE).replace(/\/+$/, "");
55
+ if (/^https:\/\/(chatgpt\.com|chat\.openai\.com)/.test(base) && !base.includes("/backend-api")) {
56
+ base += "/backend-api";
57
+ }
58
+ return base;
59
+ }
60
+
61
+ function usagePath(base) { return base.includes("/backend-api") ? "/wham/usage" : "/api/codex/usage"; }
62
+ function resetCreditsPath(base) { return base.includes("/backend-api") ? "/wham/rate-limit-reset-credits" : "/api/codex/rate-limit-reset-credits"; }
63
+
64
+ // ── lenient field readers ──────────────────────────────────────────────────
65
+ // Team and enterprise payloads send numbers as strings ("limit": "1000"), and
66
+ // reset timestamps answer to three different spellings depending on which
67
+ // sub-object you are in.
68
+ function num(v) {
69
+ if (typeof v === "number") return Number.isFinite(v) ? v : null;
70
+ if (typeof v === "string" && v.trim() !== "") {
71
+ const n = Number(v);
72
+ return Number.isFinite(n) ? n : null;
73
+ }
74
+ return null;
75
+ }
76
+ function resetAt(o) {
77
+ return num(o?.resets_at) ?? num(o?.resetsAt) ?? num(o?.reset_at) ?? null;
78
+ }
79
+
80
+ /** "Jun 18, 4:09pm" — matches the Claude quota formatting so both read alike.
81
+ *
82
+ * It did not, and the sentence above is why #374 called this one out: this
83
+ * copy passed the same options to `toLocaleString` and then stripped the comma
84
+ * and lower-cased the whole string, so it printed "jun 18 4:09pm" where the
85
+ * Claude lane one row up printed "Jun 18, 4:09pm". Swept over 2,794 instants
86
+ * the two disagreed on every one. Both read from reset-label.mjs now, and the
87
+ * claim above is true for the first time. */
88
+ const fmtReset = resetLabel;
89
+
90
+ // ── window classification ──────────────────────────────────────────────────
91
+ // Slot position is NOT the lane. Free plans return a weekly window in the
92
+ // primary slot, and a 30-day lane can arrive in either slot — labelling by
93
+ // slot is how a weekly cap ends up displayed as a 5-hour one. Duration is the
94
+ // only trustworthy signal.
95
+ const HOUR = 3600;
96
+ function laneFor(windowSec) {
97
+ if (windowSec == null || windowSec <= 0) return { key: "unknown", label: "Rate limit", rank: 9 };
98
+ if (windowSec <= 6 * HOUR) return { key: "session", label: `${Math.round(windowSec / HOUR)}-hour window`, rank: 0 };
99
+ if (windowSec <= 8 * 24 * HOUR) return { key: "weekly", label: "7-day window", rank: 1 };
100
+ return { key: "monthly", label: "30-day window", rank: 2 };
101
+ }
102
+
103
+ /** One rate-limit lane, or null when the window carries no usable reading. */
104
+ function toWindow(w, idFallback) {
105
+ const pct = num(w?.used_percent ?? w?.usedPercent);
106
+ if (pct == null) return null;
107
+ const windowSec = num(w?.limit_window_seconds ?? w?.limitWindowSeconds);
108
+ const lane = laneFor(windowSec);
109
+ const reset = resetAt(w);
110
+ return {
111
+ id: idFallback ? `${idFallback}-${lane.key}` : lane.key,
112
+ key: lane.key,
113
+ label: lane.label,
114
+ rank: lane.rank,
115
+ pct, // never clamped — over-quota is real information
116
+ windowSec: windowSec ?? null,
117
+ resetAt: reset,
118
+ reset: fmtReset(reset),
119
+ };
120
+ }
121
+
122
+ /** Both slots of a rate_limit object, ordered by lane rather than by slot. */
123
+ function windowsFrom(rl, idPrefix) {
124
+ return [toWindow(rl?.primary_window, idPrefix), toWindow(rl?.secondary_window, idPrefix)]
125
+ .filter(Boolean)
126
+ .sort((a, b) => a.rank - b.rank);
127
+ }
128
+
129
+ // ── spend control / monthly credit limit ───────────────────────────────────
130
+ // Three places can carry it, in this precedence. Whichever answers first wins.
131
+ function creditLimitFrom(data) {
132
+ const src = data?.individual_limit
133
+ ?? data?.rate_limit?.individual_limit
134
+ ?? data?.spend_control?.individual_limit;
135
+ const limit = num(src?.limit);
136
+ if (!limit || limit <= 0) return null;
137
+
138
+ const remainingPct = num(src?.remaining_percent ?? src?.remainingPercent);
139
+ const used = num(src?.used) ?? (remainingPct != null ? limit * Math.max(0, Math.min(100, 100 - remainingPct)) / 100 : 0);
140
+ const pct = remainingPct != null ? Math.max(0, Math.min(100, 100 - remainingPct)) : (used / limit) * 100;
141
+ const reset = resetAt(src);
142
+
143
+ return {
144
+ limit,
145
+ used,
146
+ usedPct: pct,
147
+ remaining: num(src?.remaining) ?? Math.max(0, limit - used),
148
+ source: src?.source ?? null,
149
+ resetAt: reset,
150
+ reset: fmtReset(reset),
151
+ };
152
+ }
153
+
154
+ // ── plan labels ────────────────────────────────────────────────────────────
155
+ // OpenAI's marketing names, since "pro" alone tells the user nothing about
156
+ // which of the two Pro tiers they are on.
157
+ const PLAN_LABELS = { pro: "Pro 20x", prolite: "Pro 5x", pro_lite: "Pro 5x", "pro-lite": "Pro 5x" };
158
+ function planLabel(plan) {
159
+ if (!plan || typeof plan !== "string") return null;
160
+ const k = plan.toLowerCase().replace(/\s+/g, "_");
161
+ if (PLAN_LABELS[k]) return PLAN_LABELS[k];
162
+ if (k === "k12" || k === "cbp") return k.toUpperCase();
163
+ return k.split(/[_-]/).map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(" ");
164
+ }
165
+
166
+ // ── extra limit families (Codex Spark and friends) ────────────────────────
167
+ // `additional_rate_limits` is an ARRAY of {limit_name, metered_feature,
168
+ // rate_limit}, not a map. Decoded element-wise so one malformed entry costs
169
+ // only itself.
170
+ function extraLimits(data) {
171
+ const arr = data?.additional_rate_limits;
172
+ if (!Array.isArray(arr)) return { extras: [], damaged: arr != null };
173
+
174
+ const extras = [];
175
+ let damaged = false;
176
+ for (const entry of arr) {
177
+ try {
178
+ const slug = String(entry?.metered_feature ?? entry?.limit_name ?? "extra")
179
+ .toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
180
+ const title = entry?.limit_name ?? entry?.metered_feature ?? "Codex extra limit";
181
+ for (const w of windowsFrom(entry?.rate_limit, slug)) {
182
+ extras.push({ ...w, label: `${title} · ${w.label}`, family: slug });
183
+ }
184
+ } catch { damaged = true; }
185
+ }
186
+ return { extras, damaged };
187
+ }
188
+
189
+ // ── fetch ──────────────────────────────────────────────────────────────────
190
+ function authHeaders(auth, { accountIdHeader = "ChatGPT-Account-Id", extra = {} } = {}) {
191
+ const h = {
192
+ "Authorization": `Bearer ${auth.accessToken}`,
193
+ "Accept": "application/json",
194
+ "User-Agent": "codex-cli",
195
+ ...extra,
196
+ };
197
+ if (auth.accountId) h[accountIdHeader] = auth.accountId;
198
+ if (auth.isFedramp) h["X-OpenAI-Fedramp"] = "true";
199
+ return h;
200
+ }
201
+
202
+ /**
203
+ * Reset credits ("one free rate limit reset" grants). Best-effort and short-
204
+ * timeout: it is a nice-to-have next to the gauges, never a reason to fail
205
+ * the quota read. Read-only — we never redeem.
206
+ */
207
+ async function fetchResetCredits(base, auth) {
208
+ try {
209
+ const res = await fetch(base + resetCreditsPath(base), {
210
+ // This endpoint alone wants the uppercase-ID spelling and the beta
211
+ // headers; sending the wham/usage set here returns nothing useful.
212
+ headers: authHeaders(auth, {
213
+ accountIdHeader: "ChatGPT-Account-ID",
214
+ extra: { "OpenAI-Beta": "codex-1", "originator": "Codex Desktop" },
215
+ }),
216
+ signal: AbortSignal.timeout(5_000),
217
+ });
218
+ if (!res.ok) return null;
219
+ const body = await res.json();
220
+ const count = num(body?.available_count);
221
+ if (count == null || count < 0) return null;
222
+ const next = (body?.credits ?? [])
223
+ .filter(c => c?.status === "available" && c?.expires_at)
224
+ .map(c => Date.parse(c.expires_at))
225
+ .filter(t => !isNaN(t))
226
+ .sort((a, b) => a - b)[0] ?? null;
227
+ return { availableCount: count, nextExpiryAt: next };
228
+ } catch { return null; }
229
+ }
230
+
231
+ async function requestUsage(base, auth) {
232
+ return fetch(base + usagePath(base), {
233
+ headers: authHeaders(auth),
234
+ // Quota is per-account state; a cached response is how one account's
235
+ // gauges end up shown for another.
236
+ cache: "no-store",
237
+ signal: AbortSignal.timeout(12_000),
238
+ });
239
+ }
240
+
241
+ // One outstanding fetch at a time. Several browser tabs mounting at once
242
+ // otherwise each force their own round trip — and each one is another chance
243
+ // to race over the single-use refresh token.
244
+ let _inflight = null;
245
+
246
+ // ── what a forced read may cost ────────────────────────────────────────────
247
+ // The floor between two reads WE pay for, and it is the same number and the
248
+ // same rule quota.mjs gives the Claude half — see FORCE_POLL_MS and maySelfPoll
249
+ // there. The two routes are four lines apart in the router and had no business
250
+ // disagreeing about what `?refresh=1` costs.
251
+ //
252
+ // `force` used to mean "skip the cache", and the cache was the ONLY thing
253
+ // between a caller and chatgpt.com. `_inflight` deduplicates callers that
254
+ // overlap and nothing else, so a caller that waits for one fetch to settle and
255
+ // then asks again got a fresh round trip every time — two authenticated HTTPS
256
+ // GETs carrying the user's live ChatGPT session, as fast as the round trip
257
+ // allows, from any page the user happens to have open (#580). Reads on this
258
+ // server are deliberately open (isTrustedRead), so "any page" is the real
259
+ // threat model rather than a hypothetical one.
260
+ //
261
+ // The sharper half is the credential rather than the traffic. On a 401
262
+ // doFetchCodexQuota spends the SINGLE-USE refresh token via forceCodexRefresh,
263
+ // and `staleAccessToken` only stops that happening twice for the same rejected
264
+ // token — every turn re-reads auth.json and sees the token the previous turn
265
+ // rotated to, so a backend that keeps answering 401 rotated a fresh credential
266
+ // once per request, racing the Codex CLI for each one. codex-auth.mjs's own
267
+ // EXPIRY_SKEW_MS comment says what losing that race costs the user: a
268
+ // `refresh_token_reused` that reads as "your login is broken", recoverable only
269
+ // with `codex login`.
270
+ const FORCE_POLL_MS = 60_000;
271
+
272
+ // Set from a 429 or a rejected refresh: a backend that is refusing us must not
273
+ // be asked once per request, whoever is asking. Same shape as quota.mjs's
274
+ // _rateLimitedUntil, which is likewise never beaten by force.
275
+ let _rateLimitedUntil = 0;
276
+ const COOLDOWN_MS = 5 * 60_000;
277
+
278
+ // Stamped when a fetch STARTS rather than when it lands: what the floor is
279
+ // rationing is the round trip, and one that is still in flight has already been
280
+ // paid for.
281
+ let _lastFetchAt = 0;
282
+
283
+ /**
284
+ * Whether we may spend a request of the user's ChatGPT session right now.
285
+ *
286
+ * Exported for tests, for the same reason quota.mjs exports maySelfPoll: this
287
+ * is the rule, it is pure, and it is worth pinning down away from the fetch it
288
+ * guards.
289
+ */
290
+ export function mayFetchQuota({ now, lastFetchAt, rateLimitedUntil }) {
291
+ if (now < rateLimitedUntil) return false;
292
+ return now - lastFetchAt >= FORCE_POLL_MS;
293
+ }
294
+
295
+ /**
296
+ * The answer to a read the floor refused.
297
+ *
298
+ * A reading, not an error — a user who clicks ↻ twice in a second must get the
299
+ * numbers they already have rather than a red hint, which is exactly what
300
+ * quota.mjs does with `{ ...held, stale: true }`. The timestamp stays the one
301
+ * the data was fetched at, so the panel's age label keeps telling the truth
302
+ * instead of vouching for a reading it did not take.
303
+ */
304
+ function heldReading(now) {
305
+ if (_cache) return { ..._cache, stale: true };
306
+ // Only reachable before the first fetch has ever landed — `finish` caches
307
+ // every outcome, failures included — and spelled the way the Claude side
308
+ // spells the same two states.
309
+ return { ok: false, reason: now < _rateLimitedUntil ? "rate_limited" : "waiting", fetchedAt: now };
310
+ }
311
+
312
+ export function fetchCodexQuota({ force = false } = {}) {
313
+ const now = Date.now();
314
+ if (!force && _cache && now - _cacheAt < CACHE_MS) return Promise.resolve(_cache);
315
+ // Joining a run already in flight costs nothing, so it is offered before the
316
+ // floor: what refresh asks for is a reading newer than the cache, and a fetch
317
+ // that has not landed yet is one.
318
+ if (_inflight) return _inflight;
319
+ if (!mayFetchQuota({ now, lastFetchAt: _lastFetchAt, rateLimitedUntil: _rateLimitedUntil })) {
320
+ return Promise.resolve(heldReading(now));
321
+ }
322
+ _lastFetchAt = now;
323
+ _inflight = doFetchCodexQuota().finally(() => { _inflight = null; });
324
+ return _inflight;
325
+ }
326
+
327
+ async function doFetchCodexQuota() {
328
+ const started = Date.now();
329
+ // Stamped at completion, not at entry: the two calls below can take up to
330
+ // 17s between them, and a cache entry that is already stale on arrival
331
+ // shortens the effective TTL for no reason.
332
+ const finish = (r) => { _cache = r; _cacheAt = Date.now(); return r; };
333
+ const fail = (reason) => finish({ ok: false, reason, fetchedAt: started });
334
+ // A refusal we were told about, rather than one we inferred: back off further
335
+ // than the ordinary floor before asking again. `retry-after` is honoured when
336
+ // the backend sends one, because it knows better than the constant does.
337
+ const cooldown = (res) => {
338
+ const after = parseInt(res?.headers?.get?.("retry-after") ?? "", 10);
339
+ _rateLimitedUntil = Date.now() + (Number.isFinite(after) ? after * 1000 : COOLDOWN_MS);
340
+ };
341
+
342
+ let auth, base, res;
343
+ try {
344
+ auth = await getCodexAuth();
345
+ if (!auth.ok) return fail(auth.reason);
346
+
347
+ // An API key in auth.json is a platform credential, not a ChatGPT session —
348
+ // sending it here only produces a confusing 401.
349
+ if (auth.apiKeyMode) return fail("api_key_mode");
350
+
351
+ base = await readBaseUrl();
352
+ // Refused before the first byte goes out, and reported rather than
353
+ // swallowed: a panel that says "Codex quota is off because the configured
354
+ // base URL is not an OpenAI one" is a bug report the user can act on, where
355
+ // a silently empty gauge is a mystery. Logged once per distinct value so a
356
+ // 60-second poll does not turn a misconfiguration into a log flood.
357
+ if (!isCredentialHost(base)) {
358
+ if (_warnedBase !== base) {
359
+ _warnedBase = base;
360
+ console.error(
361
+ `${PRODUCT} codex-quota: not sending the ChatGPT token to ${base} — ` +
362
+ `chatgpt_base_url must be an https OpenAI host`,
363
+ );
364
+ }
365
+ return fail("untrusted_base_url");
366
+ }
367
+ res = await requestUsage(base, auth);
368
+
369
+ // The JWT's own `exp` is not the last word: OpenAI revokes server-side, so
370
+ // a token that looks valid locally can still come back expired. One forced
371
+ // refresh + retry turns that from "bar goes dark" into a hiccup.
372
+ //
373
+ // 401 only. A 403 from chatgpt.com is usually a bot check or a blocked
374
+ // egress IP rather than a bad token, and rotating a single-use credential
375
+ // once a minute against a network-layer block is how a working login gets
376
+ // destroyed.
377
+ if (res.status === 401) {
378
+ const refreshed = await forceCodexRefresh(auth.accessToken);
379
+ if (!refreshed.ok) {
380
+ // The credential is gone and only `codex login` brings it back, so
381
+ // rotating another single-use token at the next request would burn the
382
+ // one the CLI is still holding. Wait.
383
+ if (refreshed.reason === "refresh_rejected") cooldown(null);
384
+ return fail(refreshed.reason);
385
+ }
386
+ auth = refreshed;
387
+ res = await requestUsage(base, auth);
388
+ }
389
+
390
+ if (!res.ok) {
391
+ // A second 401 means the token we just rotated to was rejected as well —
392
+ // the case that turned into one rotation per request. 429 is the backend
393
+ // saying the same thing in the ordinary way.
394
+ if (res.status === 401 || res.status === 429) cooldown(res);
395
+ return fail(res.status === 401 ? "refresh_rejected" : `http_${res.status}`);
396
+ }
397
+ } catch (err) {
398
+ console.error(`${PRODUCT} codex-quota: fetch failed:`, err?.message ?? err);
399
+ return fail("fetch_error");
400
+ }
401
+
402
+ let data;
403
+ try { data = await res.json(); }
404
+ catch { return fail("decode_error"); }
405
+
406
+ const rl = data?.rate_limit;
407
+ const windows = windowsFrom(rl);
408
+ const { extras, damaged } = extraLimits(data);
409
+ const creditsRaw = data?.credits;
410
+ const balance = num(creditsRaw?.balance);
411
+
412
+ const result = {
413
+ ok: true,
414
+ limitReached: rl?.limit_reached ?? false,
415
+ allowed: rl?.allowed ?? true,
416
+
417
+ // Lanes, already ordered session → weekly → monthly and labelled by the
418
+ // window duration the API actually reported.
419
+ windows,
420
+ extraWindows: extras,
421
+
422
+ plan: data?.plan_type ?? auth.planType ?? null,
423
+ planLabel: planLabel(data?.plan_type ?? auth.planType),
424
+ email: data?.email ?? auth.email ?? null,
425
+
426
+ creditsBalance: balance != null && balance > 0 ? String(creditsRaw.balance) : null,
427
+ creditsUnlimited: creditsRaw?.unlimited === true,
428
+ overageReached: creditsRaw?.overage_limit_reached === true,
429
+ creditLimit: creditLimitFrom(data),
430
+
431
+ spendControlReached: data?.spend_control?.reached === true,
432
+ reachedType: data?.rate_limit_reached_type?.type ?? data?.rate_limit_reached_type ?? null,
433
+ promo: data?.promo?.message ?? null,
434
+
435
+ // True when something in the payload did not decode — the UI says "partial"
436
+ // rather than pretending the missing lanes do not exist.
437
+ partial: damaged || windows.length === 0,
438
+ refreshed: auth.refreshed === true,
439
+ fetchedAt: started,
440
+ };
441
+
442
+ result.resetCredits = await fetchResetCredits(base, auth);
443
+
444
+ return finish(result);
445
+ }