ccdeck 3.51.0 → 3.53.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.
- package/README.md +13 -4
- package/bin/cli/help.js +1 -1
- package/bin/cli/one-shot.js +3 -2
- package/bin/cli/second-start.js +2 -2
- package/bin/cli/uninstall.js +1 -1
- package/bin/codex-profile.js +21 -0
- package/bin/deck.js +4 -3
- package/dist/web/assets/BrowserWatchModal-CKN9jBCT.js +1 -0
- package/dist/web/assets/IntegrationModal-Cb9MgsP1.js +7 -0
- package/dist/web/assets/RadioPanel-D8h6qba-.js +1 -0
- package/dist/web/assets/TrafficRadar-3_aX8BI6.js +8 -0
- package/dist/web/assets/UsageHistoryModal-DgMXDORj.js +1 -0
- package/dist/web/assets/app-BwJGP2ic.js +358 -0
- package/dist/web/assets/app-xTrs4aEH.css +1 -0
- package/dist/web/assets/{index-CWUj8Kqh.js → index-C8fQC4Vq.js} +1 -1
- package/dist/web/index.html +3 -3
- package/package.json +2 -1
- package/release-notes.json +36 -0
- package/src/server/account-routes.mjs +99 -0
- package/src/server/account-watch.mjs +1 -1
- package/src/server/cli-versions.mjs +3 -3
- package/src/server/codex-auth.mjs +51 -9
- package/src/server/codex-auto.mjs +196 -0
- package/src/server/codex-login.mjs +117 -0
- package/src/server/codex-native-account.mjs +288 -0
- package/src/server/codex-profiles.mjs +243 -0
- package/src/server/codex-quota.mjs +370 -251
- package/src/server/codex-selection.mjs +371 -0
- package/src/server/codex-terminal-runner.mjs +78 -0
- package/src/server/codex-terminal.mjs +109 -0
- package/src/server/codex-watch.mjs +38 -22
- package/src/server/depth-facts.mjs +1 -1
- package/src/server/discovery.mjs +13 -0
- package/src/server/index.mjs +19 -1
- package/src/server/installer.mjs +11 -5
- package/src/server/log-election.mjs +32 -3
- package/src/server/login-service.mjs +1 -1
- package/src/server/memory-files.mjs +2 -2
- package/src/server/pinned-build.mjs +3 -0
- package/src/server/request-gates.mjs +9 -0
- package/src/server/running-deck.mjs +12 -1
- package/src/server/session-enrichment.mjs +2 -2
- package/src/server/tool-audit.mjs +15 -1
- package/src/server/usage-routes.mjs +1 -1
- package/dist/web/assets/BrowserWatchModal-CDpunrq9.js +0 -1
- package/dist/web/assets/IntegrationModal-BctMcNU8.js +0 -7
- package/dist/web/assets/RadioPanel-DQNFtYOx.js +0 -1
- package/dist/web/assets/TrafficRadar-DRt3Al7E.js +0 -8
- package/dist/web/assets/UsageHistoryModal-DlgPufgs.js +0 -1
- package/dist/web/assets/app-4x4wTE-L.js +0 -321
- package/dist/web/assets/app-o4kL0FgZ.css +0 -1
|
@@ -13,31 +13,22 @@ import { readFile } from "node:fs/promises";
|
|
|
13
13
|
// quota-oauth.mjs, which owns it, rather than through quota.mjs, which only
|
|
14
14
|
// re-exported it and brings the whole Claude quota chain with it.
|
|
15
15
|
import { cooldownFromHeader } from "./quota-oauth.mjs";
|
|
16
|
-
import { join } from "node:path";
|
|
16
|
+
import { join, resolve } from "node:path";
|
|
17
17
|
import { CODEX_HOME } from "./codex-dir.mjs";
|
|
18
|
-
import {
|
|
18
|
+
import { readCodexSelection } from "./codex-selection.mjs";
|
|
19
|
+
import { usesNativeCodexAccount, decodeJwt, codexCredentialFingerprint, getCodexAuth, forceCodexRefresh, isCredentialHost } from "./codex-auth.mjs";
|
|
19
20
|
import { PRODUCT } from "./brand.mjs";
|
|
20
21
|
import { resetLabel } from "./reset-label.mjs";
|
|
22
|
+
import { readNativeCodexAccount } from "./codex-native-account.mjs";
|
|
21
23
|
|
|
22
24
|
// Resolved by codex-dir.mjs rather than here. This file used to spell it
|
|
23
25
|
// `process.env.CODEX_HOME ?? join(homedir(), ".codex")`, which keeps an empty
|
|
24
26
|
// CODEX_HOME instead of falling back — and then read a CWD-relative
|
|
25
27
|
// "config.toml" for the base URL every credential below is sent to (#375).
|
|
26
|
-
const CONFIG_PATH = join(CODEX_HOME, "config.toml");
|
|
27
28
|
const DEFAULT_BASE = "https://chatgpt.com/backend-api";
|
|
28
29
|
|
|
29
|
-
let _cache = null;
|
|
30
|
-
let _cacheAt = 0;
|
|
31
30
|
const CACHE_MS = 60_000;
|
|
32
|
-
|
|
33
|
-
// failures. A 429 is the backend asking for a pause, not a statement that the
|
|
34
|
-
// lanes read a minute ago have stopped being true, so they are what is held
|
|
35
|
-
// through it — as quota.mjs keeps its own `_lastGood` for the same case.
|
|
36
|
-
let _lastGood = null;
|
|
37
|
-
|
|
38
|
-
// The last base URL we refused, so the refusal is said once rather than once a
|
|
39
|
-
// minute for as long as the config stays that way.
|
|
40
|
-
let _warnedBase = null;
|
|
31
|
+
const FORCE_POLL_MS = 60_000;
|
|
41
32
|
|
|
42
33
|
// ── base URL ───────────────────────────────────────────────────────────────
|
|
43
34
|
// `chatgpt_base_url` in config.toml can point at a proxy, and the path style
|
|
@@ -51,10 +42,10 @@ let _warnedBase = null;
|
|
|
51
42
|
// anything able to write that TOML (or to set $CODEX_HOME and point it at its
|
|
52
43
|
// own) could redirect the token to a host of its choosing, over plaintext http
|
|
53
44
|
// if it liked. isCredentialHost is where the two rules live.
|
|
54
|
-
async function readBaseUrl() {
|
|
45
|
+
async function readBaseUrl(home = CODEX_HOME) {
|
|
55
46
|
let raw = null;
|
|
56
47
|
try {
|
|
57
|
-
const text = await readFile(
|
|
48
|
+
const text = await readFile(join(home, "config.toml"), "utf8");
|
|
58
49
|
for (const line of text.split("\n")) {
|
|
59
50
|
const m = line.replace(/#.*$/, "").match(/^\s*chatgpt_base_url\s*=\s*(.+?)\s*$/);
|
|
60
51
|
if (m) { raw = m[1].replace(/^["']|["']$/g, "").trim(); break; }
|
|
@@ -248,56 +239,6 @@ async function requestUsage(base, auth) {
|
|
|
248
239
|
});
|
|
249
240
|
}
|
|
250
241
|
|
|
251
|
-
// One outstanding fetch at a time. Several browser tabs mounting at once
|
|
252
|
-
// otherwise each force their own round trip — and each one is another chance
|
|
253
|
-
// to race over the single-use refresh token.
|
|
254
|
-
let _inflight = null;
|
|
255
|
-
|
|
256
|
-
// ── what a forced read may cost ────────────────────────────────────────────
|
|
257
|
-
// The floor between two reads WE pay for, and it is the same number and the
|
|
258
|
-
// same rule quota.mjs gives the Claude half — see FORCE_POLL_MS and maySelfPoll
|
|
259
|
-
// there. The two routes are four lines apart in the router and had no business
|
|
260
|
-
// disagreeing about what `?refresh=1` costs.
|
|
261
|
-
//
|
|
262
|
-
// `force` used to mean "skip the cache", and the cache was the ONLY thing
|
|
263
|
-
// between a caller and chatgpt.com. `_inflight` deduplicates callers that
|
|
264
|
-
// overlap and nothing else, so a caller that waits for one fetch to settle and
|
|
265
|
-
// then asks again got a fresh round trip every time — two authenticated HTTPS
|
|
266
|
-
// GETs carrying the user's live ChatGPT session, as fast as the round trip
|
|
267
|
-
// allows, from any page the user happens to have open (#580). Reads on this
|
|
268
|
-
// server were deliberately open (isTrustedRead), so "any page" was the real
|
|
269
|
-
// threat model rather than a hypothetical one. The route is a guarded read now
|
|
270
|
-
// (GUARDED_READS in request-gates.mjs), and the floor stays for the callers
|
|
271
|
-
// that still reach it: the deck's own page and a client holding the token.
|
|
272
|
-
//
|
|
273
|
-
// The sharper half is the credential rather than the traffic. On a 401
|
|
274
|
-
// doFetchCodexQuota spends the SINGLE-USE refresh token via forceCodexRefresh,
|
|
275
|
-
// and `staleAccessToken` only stops that happening twice for the same rejected
|
|
276
|
-
// token — every turn re-reads auth.json and sees the token the previous turn
|
|
277
|
-
// rotated to, so a backend that keeps answering 401 rotated a fresh credential
|
|
278
|
-
// once per request, racing the Codex CLI for each one. codex-auth.mjs's own
|
|
279
|
-
// EXPIRY_SKEW_MS comment says what losing that race costs the user: a
|
|
280
|
-
// `refresh_token_reused` that reads as "your login is broken", recoverable only
|
|
281
|
-
// with `codex login`.
|
|
282
|
-
const FORCE_POLL_MS = 60_000;
|
|
283
|
-
|
|
284
|
-
// Set from a 429 or a rejected refresh: a backend that is refusing us must not
|
|
285
|
-
// be asked once per request, whoever is asking. Same shape as quota.mjs's
|
|
286
|
-
// _rateLimitedUntil, which is likewise never beaten by force.
|
|
287
|
-
let _rateLimitedUntil = 0;
|
|
288
|
-
const COOLDOWN_MS = 5 * 60_000;
|
|
289
|
-
// Set when the cooldown above is for a refused login rather than a 429: the
|
|
290
|
-
// fingerprint of the credential auth.json held when it was refused. That wait
|
|
291
|
-
// is about the credential, and `codex login` — the very thing the panel tells
|
|
292
|
-
// the user to run — replaces it; held to the clock alone, ↻ was answered with
|
|
293
|
-
// the old refusal for five minutes after the login that fixed it.
|
|
294
|
-
let _refusedWith = null;
|
|
295
|
-
|
|
296
|
-
// Stamped when a fetch STARTS rather than when it lands: what the floor is
|
|
297
|
-
// rationing is the round trip, and one that is still in flight has already been
|
|
298
|
-
// paid for.
|
|
299
|
-
let _lastFetchAt = 0;
|
|
300
|
-
|
|
301
242
|
/**
|
|
302
243
|
* Whether we may spend a request of the user's ChatGPT session right now.
|
|
303
244
|
*
|
|
@@ -310,210 +251,388 @@ export function mayFetchQuota({ now, lastFetchAt, rateLimitedUntil }) {
|
|
|
310
251
|
return now - lastFetchAt >= FORCE_POLL_MS;
|
|
311
252
|
}
|
|
312
253
|
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
* quota.mjs does with `{ ...held, stale: true }`. The timestamp stays the one
|
|
319
|
-
* the data was fetched at, so the panel's age label keeps telling the truth
|
|
320
|
-
* instead of vouching for a reading it did not take.
|
|
321
|
-
*/
|
|
322
|
-
function heldReading(now) {
|
|
323
|
-
if (_cache) return { ..._cache, stale: true };
|
|
324
|
-
// Only reachable before the first fetch has ever landed — `finish` caches
|
|
325
|
-
// every outcome, failures included — and spelled the way the Claude side
|
|
326
|
-
// spells the same two states.
|
|
327
|
-
return { ok: false, reason: now < _rateLimitedUntil ? "rate_limited" : "waiting", fetchedAt: now };
|
|
328
|
-
}
|
|
254
|
+
// Which account a reading was taken for — the ChatGPT account id and the
|
|
255
|
+
// address — kept beside it rather than on it, as quota.mjs keeps Claude's, so
|
|
256
|
+
// the panel is sent nothing new. A reading held over and re-served as stale is
|
|
257
|
+
// a copy and is not tagged.
|
|
258
|
+
const _accountOfQuota = new WeakMap();
|
|
329
259
|
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
260
|
+
|
|
261
|
+
/** Independent quota state for one credential home. Selected readers never refresh. */
|
|
262
|
+
export function createCodexQuotaReader({ home = CODEX_HOME, allowRefresh = false } = {}) {
|
|
263
|
+
allowRefresh = allowRefresh && resolve(home) === resolve(CODEX_HOME);
|
|
264
|
+
let _cache = null;
|
|
265
|
+
let _cacheAt = 0;
|
|
266
|
+
let _lastGood = null;
|
|
267
|
+
let _warnedBase = null;
|
|
268
|
+
let credentialFingerprint;
|
|
269
|
+
let credentialGeneration = 0;
|
|
270
|
+
|
|
271
|
+
// One outstanding fetch at a time. Several browser tabs mounting at once
|
|
272
|
+
// otherwise each force their own round trip — and each one is another chance
|
|
273
|
+
// to race over the single-use refresh token.
|
|
274
|
+
let _inflight = null;
|
|
275
|
+
|
|
276
|
+
// ── what a forced read may cost ────────────────────────────────────────────
|
|
277
|
+
// The floor between two reads WE pay for, and it is the same number and the
|
|
278
|
+
// same rule quota.mjs gives the Claude half — see FORCE_POLL_MS and maySelfPoll
|
|
279
|
+
// there. The two routes are four lines apart in the router and had no business
|
|
280
|
+
// disagreeing about what `?refresh=1` costs.
|
|
281
|
+
//
|
|
282
|
+
// `force` used to mean "skip the cache", and the cache was the ONLY thing
|
|
283
|
+
// between a caller and chatgpt.com. `_inflight` deduplicates callers that
|
|
284
|
+
// overlap and nothing else, so a caller that waits for one fetch to settle and
|
|
285
|
+
// then asks again got a fresh round trip every time — two authenticated HTTPS
|
|
286
|
+
// GETs carrying the user's live ChatGPT session, as fast as the round trip
|
|
287
|
+
// allows, from any page the user happens to have open (#580). Reads on this
|
|
288
|
+
// server were deliberately open (isTrustedRead), so "any page" was the real
|
|
289
|
+
// threat model rather than a hypothetical one. The route is a guarded read now
|
|
290
|
+
// (GUARDED_READS in request-gates.mjs), and the floor stays for the callers
|
|
291
|
+
// that still reach it: the deck's own page and a client holding the token.
|
|
292
|
+
//
|
|
293
|
+
// The sharper half is the credential rather than the traffic. On a 401
|
|
294
|
+
// doFetchCodexQuota spends the SINGLE-USE refresh token via forceCodexRefresh,
|
|
295
|
+
// and `staleAccessToken` only stops that happening twice for the same rejected
|
|
296
|
+
// token — every turn re-reads auth.json and sees the token the previous turn
|
|
297
|
+
// rotated to, so a backend that keeps answering 401 rotated a fresh credential
|
|
298
|
+
// once per request, racing the Codex CLI for each one. codex-auth.mjs's own
|
|
299
|
+
// EXPIRY_SKEW_MS comment says what losing that race costs the user: a
|
|
300
|
+
// `refresh_token_reused` that reads as "your login is broken", recoverable only
|
|
301
|
+
// with `codex login`.
|
|
302
|
+
|
|
303
|
+
// Set from a 429 or a rejected refresh: a backend that is refusing us must not
|
|
304
|
+
// be asked once per request, whoever is asking. Same shape as quota.mjs's
|
|
305
|
+
// _rateLimitedUntil, which is likewise never beaten by force.
|
|
306
|
+
let _rateLimitedUntil = 0;
|
|
307
|
+
const COOLDOWN_MS = 5 * 60_000;
|
|
308
|
+
// Set when the cooldown above is for a refused login rather than a 429: the
|
|
309
|
+
// fingerprint of the credential auth.json held when it was refused. That wait
|
|
310
|
+
// is about the credential, and `codex login` — the very thing the panel tells
|
|
311
|
+
// the user to run — replaces it; held to the clock alone, ↻ was answered with
|
|
312
|
+
// the old refusal for five minutes after the login that fixed it.
|
|
313
|
+
let _refusedWith = null;
|
|
314
|
+
|
|
315
|
+
// Stamped when a fetch STARTS rather than when it lands: what the floor is
|
|
316
|
+
// rationing is the round trip, and one that is still in flight has already been
|
|
317
|
+
// paid for.
|
|
318
|
+
let _lastFetchAt = 0;
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* The answer to a read the floor refused.
|
|
322
|
+
*
|
|
323
|
+
* A reading, not an error — a user who clicks ↻ twice in a second must get the
|
|
324
|
+
* numbers they already have rather than a red hint, which is exactly what
|
|
325
|
+
* quota.mjs does with `{ ...held, stale: true }`. The timestamp stays the one
|
|
326
|
+
* the data was fetched at, so the panel's age label keeps telling the truth
|
|
327
|
+
* instead of vouching for a reading it did not take.
|
|
328
|
+
*/
|
|
329
|
+
function heldReading(now) {
|
|
330
|
+
if (_cache) return { ..._cache, stale: true };
|
|
331
|
+
// Only reachable before the first fetch has ever landed — `finish` caches
|
|
332
|
+
// every outcome, failures included — and spelled the way the Claude side
|
|
333
|
+
// spells the same two states.
|
|
334
|
+
return { ok: false, reason: now < _rateLimitedUntil ? "rate_limited" : "waiting", fetchedAt: now };
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function fetchQuota({ force = false } = {}) {
|
|
338
|
+
const now = Date.now();
|
|
339
|
+
if (!force && _cache && now - _cacheAt < CACHE_MS) return Promise.resolve(_cache);
|
|
340
|
+
// Joining a run already in flight costs nothing, so it is offered before the
|
|
341
|
+
// floor: what refresh asks for is a reading newer than the cache, and a fetch
|
|
342
|
+
// that has not landed yet is one.
|
|
343
|
+
if (_inflight) return _inflight;
|
|
344
|
+
if (!mayFetchQuota({ now, lastFetchAt: _lastFetchAt, rateLimitedUntil: _rateLimitedUntil })) {
|
|
345
|
+
// Past the floor and inside a refused login's cooldown, the one question
|
|
346
|
+
// worth asking is whether auth.json still holds what was refused — a local
|
|
347
|
+
// read, and the wire stays quiet unless the answer is no.
|
|
348
|
+
if (_refusedWith && mayFetchQuota({ now, lastFetchAt: _lastFetchAt, rateLimitedUntil: 0 })) {
|
|
349
|
+
return track((async () => {
|
|
350
|
+
if (await codexCredentialFingerprint({ home }) === _refusedWith) return heldReading(Date.now());
|
|
351
|
+
_rateLimitedUntil = 0;
|
|
352
|
+
_refusedWith = null;
|
|
353
|
+
_lastFetchAt = Date.now();
|
|
354
|
+
return doFetchCodexQuota();
|
|
355
|
+
})());
|
|
356
|
+
}
|
|
357
|
+
return Promise.resolve(heldReading(now));
|
|
349
358
|
}
|
|
350
|
-
|
|
359
|
+
_lastFetchAt = now;
|
|
360
|
+
return track(doFetchCodexQuota());
|
|
351
361
|
}
|
|
352
|
-
_lastFetchAt = now;
|
|
353
|
-
return track(doFetchCodexQuota());
|
|
354
|
-
}
|
|
355
362
|
|
|
356
|
-
/** `run`, as the one outstanding fetch every caller joins until it settles. */
|
|
357
|
-
function track(run) {
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
363
|
+
/** `run`, as the one outstanding fetch every caller joins until it settles. */
|
|
364
|
+
function track(run) {
|
|
365
|
+
const pending = run.finally(() => { if (_inflight === pending) _inflight = null; });
|
|
366
|
+
_inflight = pending;
|
|
367
|
+
return pending;
|
|
368
|
+
}
|
|
361
369
|
|
|
362
|
-
async function doFetchCodexQuota() {
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
//
|
|
384
|
-
//
|
|
385
|
-
//
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
370
|
+
async function doFetchCodexQuota() {
|
|
371
|
+
const generation = credentialGeneration;
|
|
372
|
+
const started = Date.now();
|
|
373
|
+
// Stamped at completion, not at entry: the two calls below can take up to
|
|
374
|
+
// 17s between them, and a cache entry that is already stale on arrival
|
|
375
|
+
// shortens the effective TTL for no reason.
|
|
376
|
+
const finish = (r) => {
|
|
377
|
+
if (!allowRefresh && generation !== credentialGeneration) return { ok: false, reason: "profile_changed" };
|
|
378
|
+
_cache = r;
|
|
379
|
+
_cacheAt = Date.now();
|
|
380
|
+
if (r.ok && !r.stale) {
|
|
381
|
+
noteQuotaHistory("codex", _accountOfQuota.get(r), r);
|
|
382
|
+
_lastGood = r;
|
|
383
|
+
} else if (allowRefresh && ["no_token", "api_key_mode", "refresh_rejected"].includes(r.reason)) {
|
|
384
|
+
// Only the ambient login's loss ends its history; a selected profile
|
|
385
|
+
// going quiet says nothing about the account the deck reads by default.
|
|
386
|
+
forgetQuotaHistoryAccount("codex");
|
|
387
|
+
}
|
|
388
|
+
return r;
|
|
389
|
+
};
|
|
390
|
+
const fail = (reason) => finish({ ok: false, reason, fetchedAt: started });
|
|
391
|
+
// A refusal we were told about, rather than one we inferred: back off further
|
|
392
|
+
// than the ordinary floor before asking again. `retry-after` is honoured when
|
|
393
|
+
// the backend sends one, because it knows better than the constant does.
|
|
394
|
+
const cooldown = (res) => {
|
|
395
|
+
if (!allowRefresh && generation !== credentialGeneration) return;
|
|
396
|
+
// Clamped, for the reason quota-oauth.mjs states at cooldownFromHeader: a `0`
|
|
397
|
+
// defeats the cooldown a 429 exists to impose, and a day freezes this
|
|
398
|
+
// poller for the life of the process.
|
|
399
|
+
_rateLimitedUntil = Date.now() + cooldownFromHeader(res?.headers?.get?.("retry-after"), COOLDOWN_MS);
|
|
400
|
+
_refusedWith = null;
|
|
401
|
+
};
|
|
402
|
+
// The same wait for a login that was refused, stamped with the credential it
|
|
403
|
+
// was refused for, so a new one ends it (see fetchCodexQuota).
|
|
404
|
+
const refused = async (res) => {
|
|
405
|
+
cooldown(res);
|
|
406
|
+
const fingerprint = await codexCredentialFingerprint({ home });
|
|
407
|
+
if (allowRefresh || generation === credentialGeneration) _refusedWith = fingerprint;
|
|
408
|
+
};
|
|
409
|
+
|
|
410
|
+
let auth, base, res;
|
|
411
|
+
try {
|
|
412
|
+
auth = await getCodexAuth({ home, allowRefresh });
|
|
413
|
+
if (!auth.ok) return fail(auth.reason);
|
|
395
414
|
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
if (auth.apiKeyMode) return fail("api_key_mode");
|
|
404
|
-
|
|
405
|
-
base = await readBaseUrl();
|
|
406
|
-
// Refused before the first byte goes out, and reported rather than
|
|
407
|
-
// swallowed: a panel that says "Codex quota is off because the configured
|
|
408
|
-
// base URL is not an OpenAI one" is a bug report the user can act on, where
|
|
409
|
-
// a silently empty gauge is a mystery. Logged once per distinct value so a
|
|
410
|
-
// 60-second poll does not turn a misconfiguration into a log flood.
|
|
411
|
-
if (!isCredentialHost(base)) {
|
|
412
|
-
if (_warnedBase !== base) {
|
|
413
|
-
_warnedBase = base;
|
|
414
|
-
console.error(
|
|
415
|
-
`${PRODUCT} codex-quota: not sending the ChatGPT token to ${base} — ` +
|
|
416
|
-
`chatgpt_base_url must be an https OpenAI host`,
|
|
417
|
-
);
|
|
415
|
+
// An API key in auth.json is a platform credential, not a ChatGPT session —
|
|
416
|
+
// sending it here only produces a confusing 401.
|
|
417
|
+
if (auth.apiKeyMode) return fail("api_key_mode");
|
|
418
|
+
|
|
419
|
+
if (!allowRefresh) {
|
|
420
|
+
const exp = decodeJwt(auth.accessToken)?.exp;
|
|
421
|
+
if (typeof exp === "number" && exp * 1000 <= Date.now()) return fail("expired");
|
|
418
422
|
}
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
// The credential is gone and only `codex login` brings it back, so
|
|
435
|
-
// rotating another single-use token at the next request would burn the
|
|
436
|
-
// one the CLI is still holding. Wait.
|
|
437
|
-
if (refreshed.reason === "refresh_rejected") await refused(null);
|
|
438
|
-
return fail(refreshed.reason);
|
|
423
|
+
base = await readBaseUrl(home);
|
|
424
|
+
// Refused before the first byte goes out, and reported rather than
|
|
425
|
+
// swallowed: a panel that says "Codex quota is off because the configured
|
|
426
|
+
// base URL is not an OpenAI one" is a bug report the user can act on, where
|
|
427
|
+
// a silently empty gauge is a mystery. Logged once per distinct value so a
|
|
428
|
+
// 60-second poll does not turn a misconfiguration into a log flood.
|
|
429
|
+
if (!isCredentialHost(base)) {
|
|
430
|
+
if (_warnedBase !== base) {
|
|
431
|
+
_warnedBase = base;
|
|
432
|
+
console.error(
|
|
433
|
+
`${PRODUCT} codex-quota: not sending the ChatGPT token to ${base} — ` +
|
|
434
|
+
`chatgpt_base_url must be an https OpenAI host`,
|
|
435
|
+
);
|
|
436
|
+
}
|
|
437
|
+
return fail("untrusted_base_url");
|
|
439
438
|
}
|
|
440
|
-
auth = refreshed;
|
|
441
439
|
res = await requestUsage(base, auth);
|
|
442
|
-
}
|
|
443
440
|
|
|
444
|
-
|
|
445
|
-
//
|
|
446
|
-
//
|
|
447
|
-
//
|
|
448
|
-
//
|
|
449
|
-
//
|
|
450
|
-
// a
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
441
|
+
// The JWT's own `exp` is not the last word: OpenAI revokes server-side, so
|
|
442
|
+
// a token that looks valid locally can still come back expired. One forced
|
|
443
|
+
// refresh + retry turns that from "bar goes dark" into a hiccup.
|
|
444
|
+
//
|
|
445
|
+
// 401 only. A 403 from chatgpt.com is usually a bot check or a blocked
|
|
446
|
+
// egress IP rather than a bad token, and rotating a single-use credential
|
|
447
|
+
// once a minute against a network-layer block is how a working login gets
|
|
448
|
+
// destroyed.
|
|
449
|
+
if (res.status === 401 && allowRefresh) {
|
|
450
|
+
const refreshed = await forceCodexRefresh(auth.accessToken);
|
|
451
|
+
if (!refreshed.ok) {
|
|
452
|
+
// The credential is gone and only `codex login` brings it back, so
|
|
453
|
+
// rotating another single-use token at the next request would burn the
|
|
454
|
+
// one the CLI is still holding. Wait.
|
|
455
|
+
if (refreshed.reason === "refresh_rejected") await refused(null);
|
|
456
|
+
return fail(refreshed.reason);
|
|
457
|
+
}
|
|
458
|
+
auth = refreshed;
|
|
459
|
+
res = await requestUsage(base, auth);
|
|
454
460
|
}
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
461
|
+
|
|
462
|
+
if (!res.ok) {
|
|
463
|
+
// A second 401 means the token we just rotated to was rejected as well —
|
|
464
|
+
// the case that turned into one rotation per request. 429 is the backend
|
|
465
|
+
// saying the same thing in the ordinary way, and it says nothing against
|
|
466
|
+
// the lanes already read: they are held, stale, through the wait, and
|
|
467
|
+
// without any the panel is told the deck is waiting rather than to press
|
|
468
|
+
// a ↻ the cooldown refuses.
|
|
469
|
+
if (res.status === 401) {
|
|
470
|
+
await refused(res);
|
|
471
|
+
return fail(allowRefresh ? "refresh_rejected" : "reauth_required");
|
|
472
|
+
}
|
|
473
|
+
if (res.status === 429) {
|
|
474
|
+
cooldown(res);
|
|
475
|
+
return _lastGood ? finish({ ..._lastGood, stale: true }) : fail("rate_limited");
|
|
476
|
+
}
|
|
477
|
+
return fail(`http_${res.status}`);
|
|
458
478
|
}
|
|
459
|
-
|
|
479
|
+
} catch (err) {
|
|
480
|
+
console.error(`${PRODUCT} codex-quota: fetch failed:`, err?.message ?? err);
|
|
481
|
+
return fail("fetch_error");
|
|
460
482
|
}
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
483
|
+
|
|
484
|
+
let data;
|
|
485
|
+
try { data = await res.json(); }
|
|
486
|
+
catch { return fail("decode_error"); }
|
|
487
|
+
|
|
488
|
+
const rl = data?.rate_limit;
|
|
489
|
+
const windows = windowsFrom(rl);
|
|
490
|
+
const { extras, damaged } = extraLimits(data);
|
|
491
|
+
const creditsRaw = data?.credits;
|
|
492
|
+
const balance = num(creditsRaw?.balance);
|
|
493
|
+
|
|
494
|
+
const result = {
|
|
495
|
+
ok: true,
|
|
496
|
+
limitReached: rl?.limit_reached ?? false,
|
|
497
|
+
allowed: rl?.allowed ?? true,
|
|
498
|
+
|
|
499
|
+
// Lanes, already ordered session → weekly → monthly and labelled by the
|
|
500
|
+
// window duration the API actually reported.
|
|
501
|
+
windows,
|
|
502
|
+
extraWindows: extras,
|
|
503
|
+
|
|
504
|
+
plan: data?.plan_type ?? auth.planType ?? null,
|
|
505
|
+
planLabel: planLabel(data?.plan_type ?? auth.planType),
|
|
506
|
+
email: data?.email ?? auth.email ?? null,
|
|
507
|
+
|
|
508
|
+
creditsBalance: balance != null && balance > 0 ? String(creditsRaw.balance) : null,
|
|
509
|
+
creditsUnlimited: creditsRaw?.unlimited === true,
|
|
510
|
+
overageReached: creditsRaw?.overage_limit_reached === true,
|
|
511
|
+
creditLimit: creditLimitFrom(data),
|
|
512
|
+
|
|
513
|
+
spendControlReached: data?.spend_control?.reached === true,
|
|
514
|
+
reachedType: data?.rate_limit_reached_type?.type ?? data?.rate_limit_reached_type ?? null,
|
|
515
|
+
promo: data?.promo?.message ?? null,
|
|
516
|
+
|
|
517
|
+
// True when something in the payload did not decode — the UI says "partial"
|
|
518
|
+
// rather than pretending the missing lanes do not exist.
|
|
519
|
+
partial: damaged || windows.length === 0,
|
|
520
|
+
refreshed: auth.refreshed === true,
|
|
521
|
+
fetchedAt: started,
|
|
522
|
+
};
|
|
523
|
+
|
|
524
|
+
result.resetCredits = await fetchResetCredits(base, auth);
|
|
525
|
+
if (allowRefresh) _accountOfQuota.set(result, { accountId: auth.accountId ?? null, email: result.email });
|
|
526
|
+
|
|
527
|
+
return finish(result);
|
|
464
528
|
}
|
|
465
529
|
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
// True when something in the payload did not decode — the UI says "partial"
|
|
500
|
-
// rather than pretending the missing lanes do not exist.
|
|
501
|
-
partial: damaged || windows.length === 0,
|
|
502
|
-
refreshed: auth.refreshed === true,
|
|
503
|
-
fetchedAt: started,
|
|
504
|
-
};
|
|
530
|
+
// A re-login invalidates every kind of held state, including refused-login
|
|
531
|
+
// cooldowns and pending requests. An older request may finish, but cannot cache.
|
|
532
|
+
async function fetchReadOnlyQuota(options) {
|
|
533
|
+
const fingerprint = await codexCredentialFingerprint({ home });
|
|
534
|
+
if (fingerprint !== credentialFingerprint) {
|
|
535
|
+
credentialFingerprint = fingerprint;
|
|
536
|
+
credentialGeneration++;
|
|
537
|
+
_cache = null;
|
|
538
|
+
_cacheAt = 0;
|
|
539
|
+
_lastGood = null;
|
|
540
|
+
_inflight = null;
|
|
541
|
+
_rateLimitedUntil = 0;
|
|
542
|
+
_refusedWith = null;
|
|
543
|
+
_lastFetchAt = 0;
|
|
544
|
+
}
|
|
545
|
+
const generation = credentialGeneration;
|
|
546
|
+
const result = await fetchQuota(options);
|
|
547
|
+
if (generation !== credentialGeneration || await codexCredentialFingerprint({ home }) !== fingerprint) {
|
|
548
|
+
return { ok: false, reason: "profile_changed" };
|
|
549
|
+
}
|
|
550
|
+
if (result.ok && !result.stale) {
|
|
551
|
+
const auth = await getCodexAuth({ home, allowRefresh: false });
|
|
552
|
+
if (await codexCredentialFingerprint({ home }) !== fingerprint) return { ok: false, reason: "profile_changed" };
|
|
553
|
+
if (auth.ok && !auth.apiKeyMode) {
|
|
554
|
+
_accountOfQuota.set(result, { accountId: auth.accountId ?? null, email: result.email });
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
return result;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
return { fetch: allowRefresh ? fetchQuota : fetchReadOnlyQuota };
|
|
561
|
+
}
|
|
505
562
|
|
|
506
|
-
|
|
507
|
-
|
|
563
|
+
const legacyReader = createCodexQuotaReader({ allowRefresh: true });
|
|
564
|
+
const selectedReaders = new Map();
|
|
508
565
|
|
|
509
|
-
|
|
566
|
+
const MAX_SELECTED_READERS = 64;
|
|
567
|
+
|
|
568
|
+
// Keep active readers so repeated calls still share their in-flight request.
|
|
569
|
+
// Removed roster homes and the least recently used idle readers can be rebuilt.
|
|
570
|
+
function selectedReader(selection) {
|
|
571
|
+
if (Array.isArray(selection.homes)) {
|
|
572
|
+
const homes = new Set(selection.homes);
|
|
573
|
+
for (const [home, entry] of selectedReaders) {
|
|
574
|
+
if (!homes.has(home) && entry.active === 0) selectedReaders.delete(home);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
let entry = selectedReaders.get(selection.home);
|
|
578
|
+
if (entry) {
|
|
579
|
+
selectedReaders.delete(selection.home);
|
|
580
|
+
selectedReaders.set(selection.home, entry);
|
|
581
|
+
return entry;
|
|
582
|
+
}
|
|
583
|
+
if (selectedReaders.size >= MAX_SELECTED_READERS) {
|
|
584
|
+
const idle = [...selectedReaders].find(([, entry]) => entry.active === 0);
|
|
585
|
+
if (!idle) return null;
|
|
586
|
+
selectedReaders.delete(idle[0]);
|
|
587
|
+
}
|
|
588
|
+
entry = { reader: createCodexQuotaReader({ home: selection.home }), active: 0 };
|
|
589
|
+
selectedReaders.set(selection.home, entry);
|
|
590
|
+
return entry;
|
|
510
591
|
}
|
|
511
592
|
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
593
|
+
/** Capture the selected target once; reject a completion from any old revision. */
|
|
594
|
+
export async function fetchCodexQuota({ force = false, readSelection: read = readCodexSelection, enableNative = false, nativeRead = readNativeCodexAccount } = {}) {
|
|
595
|
+
let selected;
|
|
596
|
+
try { selected = await read(); }
|
|
597
|
+
catch { return { ok: false, reason: "selection_unavailable" }; }
|
|
598
|
+
const home = selected.selectionEnabled ? selected.home : CODEX_HOME;
|
|
599
|
+
if (typeof home !== "string" || !home.trim()) return { ok: false, reason: "selection_unavailable" };
|
|
600
|
+
if (selected.available === false) return { ok: false, reason: "profile_unavailable" };
|
|
601
|
+
const authoritative = enableNative && await usesNativeCodexAccount(home, selected.selectionEnabled);
|
|
602
|
+
let entry = null;
|
|
603
|
+
if (selected.selectionEnabled && !authoritative) {
|
|
604
|
+
entry = selectedReader(selected);
|
|
605
|
+
if (!entry) return { ok: false, reason: "waiting", fetchedAt: Date.now() };
|
|
606
|
+
entry.active++;
|
|
607
|
+
}
|
|
608
|
+
let result;
|
|
609
|
+
try { result = authoritative ? { ok: false, reason: "no_token" } : await (entry?.reader ?? legacyReader).fetch({ force }); }
|
|
610
|
+
finally { if (entry) entry.active--; }
|
|
611
|
+
if (enableNative && result.reason === "no_token") {
|
|
612
|
+
const fingerprint = authoritative ? null : await codexCredentialFingerprint({ home });
|
|
613
|
+
const native = await nativeRead(home, { includeQuota: true, force: true });
|
|
614
|
+
if (!authoritative && await codexCredentialFingerprint({ home }) !== fingerprint) {
|
|
615
|
+
return { ok: false, reason: 'profile_changed' };
|
|
616
|
+
}
|
|
617
|
+
if (native.ok && native.signedIn && native.plan !== 'api') {
|
|
618
|
+
const windows = native.windows.map(window => toWindow({
|
|
619
|
+
used_percent: window.usedPercent, limit_window_seconds: window.seconds, resets_at: window.resetAt,
|
|
620
|
+
})).filter(Boolean).sort((a, b) => a.rank - b.rank);
|
|
621
|
+
result = { ok: true, windows, extraWindows: [], plan: native.plan, planLabel: planLabel(native.plan),
|
|
622
|
+
email: native.label, partial: true, coverage: "standard_limits", refreshed: false, fetchedAt: native.fetchedAt,
|
|
623
|
+
...(native.stale ? { stale: true } : {}) };
|
|
624
|
+
_accountOfQuota.set(result, { accountId: `profile:${selected.profileId}`, profileId: selected.profileId, email: native.label });
|
|
625
|
+
} else result = { ok: false, reason: native.reason ?? (native.plan === 'api' ? 'api_key_mode' : 'no_token'), fetchedAt: native.fetchedAt,
|
|
626
|
+
...(native.stale ? { stale: true } : {}) };
|
|
627
|
+
}
|
|
628
|
+
let current;
|
|
629
|
+
try { current = await read(); }
|
|
630
|
+
catch { return { ok: false, reason: "selection_unavailable" }; }
|
|
631
|
+
if (current.selectionEnabled !== selected.selectionEnabled || (selected.selectionEnabled && (
|
|
632
|
+
current.home !== selected.home || current.profileId !== selected.profileId || current.revision !== selected.revision
|
|
633
|
+
))) return { ok: false, reason: "profile_changed" };
|
|
634
|
+
return result;
|
|
635
|
+
}
|
|
517
636
|
|
|
518
637
|
/** The account a fetchCodexQuota reading was taken for, or null — for
|
|
519
638
|
* account-watch.mjs, whose notifications are about one account at a time. */
|