@wengine-ai/ccr-provider-codex 1.0.13 → 1.0.14

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 CHANGED
@@ -24,7 +24,9 @@ Ordinary config contains the identifier `ccr-managed-codex`, **not a credential*
24
24
 
25
25
  The runtime pins requests to `https://chatgpt.com/backend-api/codex/responses`, rejects redirects, uses the host direct dispatcher, strips client auth/session headers, and injects its live access token/account. The transformer chain is `['openai-responses', 'codex']`. A rejected access token receives one forced refresh and one re-dispatch; rotated refresh tokens are persisted before use.
26
26
 
27
- Quota observations come from headers, bounded SSE observation and the explicit usage endpoint. A quota failure parks the account until its reported reset. No model table, WebSocket, zstd, account pool or CLI credential import is included.
27
+ A background maintenance loop (first cycle one minute after activation, then every 30 minutes, timers `unref`ed) proactively renews the access token while it is inside the 5-minute expiry lead, reusing the same single-flight refresh as the data plane. A healthy token costs no network, and a maintenance failure is logged without latching account health — only the data plane writes `lastError`/cooldown. The **Sync models** management call is read-only and stays available during a quota cooldown or an expired-token window (the call refreshes on demand), so refreshing the model list never requires a full re-login.
28
+
29
+ Quota observations come from headers, bounded SSE observation and the explicit usage endpoint. While parked, chat preflight and recovery probes can recheck usage through a single-flight read cached for one minute. An explicit upstream `allowed: true`, `limit_reached: false` response with complete, live, unsaturated windows releases an obsolete quota lock (including after a plan upgrade) and updates the displayed plan. Missing or failed reads preserve the lock; reauthorization and unrelated error states are never cleared by a quota read. Model sync preserves error provenance. Legacy generic cooldowns whose error reason was already erased are retained conservatively; the separate quota-observation lock can still recover. Token acquisition failures are also cached for one minute to prevent repeated preflight refresh attempts. A newer data-plane observation or account change invalidates an in-flight recovery result. No model table, WebSocket, zstd, account pool or CLI credential import is included.
28
30
 
29
31
  ## Supported path and known limitations
30
32
 
package/dist/README.md CHANGED
@@ -24,7 +24,9 @@ Ordinary config contains the identifier `ccr-managed-codex`, **not a credential*
24
24
 
25
25
  The runtime pins requests to `https://chatgpt.com/backend-api/codex/responses`, rejects redirects, uses the host direct dispatcher, strips client auth/session headers, and injects its live access token/account. The transformer chain is `['openai-responses', 'codex']`. A rejected access token receives one forced refresh and one re-dispatch; rotated refresh tokens are persisted before use.
26
26
 
27
- Quota observations come from headers, bounded SSE observation and the explicit usage endpoint. A quota failure parks the account until its reported reset. No model table, WebSocket, zstd, account pool or CLI credential import is included.
27
+ A background maintenance loop (first cycle one minute after activation, then every 30 minutes, timers `unref`ed) proactively renews the access token while it is inside the 5-minute expiry lead, reusing the same single-flight refresh as the data plane. A healthy token costs no network, and a maintenance failure is logged without latching account health — only the data plane writes `lastError`/cooldown. The **Sync models** management call is read-only and stays available during a quota cooldown or an expired-token window (the call refreshes on demand), so refreshing the model list never requires a full re-login.
28
+
29
+ Quota observations come from headers, bounded SSE observation and the explicit usage endpoint. While parked, chat preflight and recovery probes can recheck usage through a single-flight read cached for one minute. An explicit upstream `allowed: true`, `limit_reached: false` response with complete, live, unsaturated windows releases an obsolete quota lock (including after a plan upgrade) and updates the displayed plan. Missing or failed reads preserve the lock; reauthorization and unrelated error states are never cleared by a quota read. Model sync preserves error provenance. Legacy generic cooldowns whose error reason was already erased are retained conservatively; the separate quota-observation lock can still recover. Token acquisition failures are also cached for one minute to prevent repeated preflight refresh attempts. A newer data-plane observation or account change invalidates an in-flight recovery result. No model table, WebSocket, zstd, account pool or CLI credential import is included.
28
30
 
29
31
  ## Supported path and known limitations
30
32
 
package/dist/card.js CHANGED
@@ -662,6 +662,21 @@ function mount(el, props) {
662
662
  let reconcileFailed = false;
663
663
  let confirmDisconnect = false;
664
664
  let confirmReset = false;
665
+ let confirmOverlay = null;
666
+ const cancelDisconnectConfirm = () => {
667
+ if (action || !confirmDisconnect) return;
668
+ confirmDisconnect = false;
669
+ render();
670
+ };
671
+ const onConfirmKeydown = (event) => {
672
+ if (event?.key === "Escape") cancelDisconnectConfirm();
673
+ };
674
+ const removeConfirmOverlay = () => {
675
+ if (!confirmOverlay) return;
676
+ confirmOverlay.remove();
677
+ confirmOverlay = null;
678
+ document.removeEventListener("keydown", onConfirmKeydown);
679
+ };
665
680
  let resetCredits = null;
666
681
  let resetPhase = "idle";
667
682
  let login = null;
@@ -684,6 +699,8 @@ function mount(el, props) {
684
699
  const BADGE_BASE = "inline-flex items-center rounded-lg border px-2.5 py-0.5 text-[10px] font-bold transition-colors";
685
700
  const BADGE_OUTLINE = "border-white/10 text-foreground bg-white/5";
686
701
  const BADGE_SECONDARY = "border-white/5 bg-white/5 text-muted-foreground";
702
+ const CONFIRM_OVERLAY_CLASS = "fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-4";
703
+ const CONFIRM_TITLE_ID = "codex-disconnect-confirm-title";
687
704
  const node = (tag, text) => {
688
705
  const result = document.createElement(tag);
689
706
  if (text !== void 0) result.textContent = text;
@@ -802,6 +819,10 @@ function mount(el, props) {
802
819
  const parsed = parseCodexUsage(raw);
803
820
  rememberCodexUsage(parsed);
804
821
  if (alive && generation === id) showUsage(parsed, parsed ? Date.now() : null);
822
+ if (parsed && !background) {
823
+ const fresh = await readStatus().catch(() => null);
824
+ if (fresh && alive && generation === id) status = fresh;
825
+ }
805
826
  } catch {
806
827
  if (alive && generation === id) showUsage(null, null);
807
828
  } finally {
@@ -1063,6 +1084,7 @@ function mount(el, props) {
1063
1084
  const state = loading ? "loading" : loadFailed && !status ? "error" : codexStateKey(status);
1064
1085
  const connected = !loading && codexConnected(status);
1065
1086
  const canDisconnect = !!status && (status.status !== "not_connected" || status.models.length > 0);
1087
+ const canSync = !loading && !!status && status.status !== "not_connected";
1066
1088
  const busy = loading || action !== null;
1067
1089
  const disabled = busy || props.disabled;
1068
1090
  const pendingHide = (model) => action?.kind === "hide" && action.model === model;
@@ -1265,7 +1287,7 @@ function mount(el, props) {
1265
1287
  actions,
1266
1288
  t("sync"),
1267
1289
  () => void run("sync"),
1268
- disabled || !connected,
1290
+ disabled || !canSync,
1269
1291
  "outline",
1270
1292
  "h-8 w-full text-xs",
1271
1293
  refreshCwIcon(`mr-1 h-3.5 w-3.5 ${action?.kind === "sync" ? "animate-spin" : ""}`)
@@ -1283,10 +1305,16 @@ function mount(el, props) {
1283
1305
  el.append(message);
1284
1306
  }
1285
1307
  if (confirmDisconnect) {
1286
- const panel = styled("div", "glass-card mt-3 max-w-lg space-y-3 rounded-2xl p-5");
1308
+ removeConfirmOverlay();
1309
+ const overlay = styled("div", CONFIRM_OVERLAY_CLASS);
1310
+ const panel = styled("div", "glass-card max-w-lg space-y-3 rounded-2xl p-5");
1287
1311
  panel.setAttribute("role", "dialog");
1312
+ panel.setAttribute("aria-modal", "true");
1313
+ panel.setAttribute("aria-labelledby", CONFIRM_TITLE_ID);
1314
+ const title = styled("h3", "text-sm font-semibold tracking-tight text-foreground", t("disconnect_title"));
1315
+ title.setAttribute("id", CONFIRM_TITLE_ID);
1288
1316
  panel.append(
1289
- styled("h3", "text-sm font-semibold tracking-tight text-foreground", t("disconnect_title")),
1317
+ title,
1290
1318
  styled("p", "text-xs text-muted-foreground", t("disconnect_warning"))
1291
1319
  );
1292
1320
  const footer = styled("div", "flex justify-end gap-2");
@@ -1307,7 +1335,15 @@ function mount(el, props) {
1307
1335
  "h-8 text-xs"
1308
1336
  );
1309
1337
  panel.append(footer);
1310
- el.append(panel);
1338
+ overlay.append(panel);
1339
+ overlay.onclick = (event) => {
1340
+ if (event?.target === overlay) cancelDisconnectConfirm();
1341
+ };
1342
+ document.body.append(overlay);
1343
+ confirmOverlay = overlay;
1344
+ document.addEventListener("keydown", onConfirmKeydown);
1345
+ } else {
1346
+ removeConfirmOverlay();
1311
1347
  }
1312
1348
  if (confirmReset) {
1313
1349
  const panel = styled("div", "max-w-md space-y-2 rounded-xl border border-primary/30 bg-primary/5 p-4");
@@ -1342,6 +1378,7 @@ function mount(el, props) {
1342
1378
  mounted.set(el, () => {
1343
1379
  alive = false;
1344
1380
  confirmDisconnect = false;
1381
+ removeConfirmOverlay();
1345
1382
  unsubscribeHost?.();
1346
1383
  unsubscribeHost = null;
1347
1384
  void session?.cancel().catch(() => {
@@ -1393,4 +1430,3 @@ export {
1393
1430
  mount,
1394
1431
  unmount
1395
1432
  };
1396
- //# sourceMappingURL=card.js.map
package/dist/plugin.js CHANGED
@@ -372,7 +372,13 @@ function parseCodexUsage(raw) {
372
372
  const primary = readUsageWindow(rateLimit.primary_window ?? rateLimit.primaryWindow);
373
373
  const secondary = readUsageWindow(rateLimit.secondary_window ?? rateLimit.secondaryWindow);
374
374
  if (!plan && !primary && !secondary) return null;
375
+ const windows = [rateLimit.primary_window ?? rateLimit.primaryWindow, rateLimit.secondary_window ?? rateLimit.secondaryWindow].filter((w) => w != null);
376
+ const canResume = rateLimit.allowed === true && rateLimit.limit_reached === false && windows.length > 0 && windows.every((w) => {
377
+ const parsed = readUsageWindow(w);
378
+ return parsed && Number.isFinite(parsed.usedPercent) && parsed.usedPercent >= 0 && parsed.usedPercent < 100 && Number.isFinite(parsed.windowSeconds) && parsed.windowSeconds > 0 && parsed.resetAt > Date.now();
379
+ });
375
380
  return {
381
+ ...canResume ? { canResume: true } : {},
376
382
  plan,
377
383
  ...primary ? { primary } : {},
378
384
  ...secondary ? { secondary } : {}
@@ -744,6 +750,9 @@ var CodexAuthService = class {
744
750
  refreshFlight = null;
745
751
  forceRefreshRequested = false;
746
752
  usageCache = null;
753
+ /** Reject quota reads overtaken by a new data-plane observation. */
754
+ quotaRevision = 0;
755
+ usageFlight = null;
747
756
  /** Reset-credit listing cache (same short-TTL shape as usage). */
748
757
  resetCache = null;
749
758
  /** Single-flight for reset consumption: a queued second consume could
@@ -1479,6 +1488,32 @@ var CodexAuthService = class {
1479
1488
  this.forceRefreshRequested = true;
1480
1489
  await this.getAccessToken();
1481
1490
  }
1491
+ /**
1492
+ * Background maintenance entry point for CodexTokenMaintenance.
1493
+ *
1494
+ * Renews ONLY when the 5-minute lead has elapsed — the exact gate used by
1495
+ * getAccessToken — and reuses its single-flight refresh, so a healthy token
1496
+ * costs no network and a background cycle overlapping a data-plane refresh
1497
+ * shares the same grant. A disconnected service is a quiet no-op. The
1498
+ * forced-refresh flag belongs to the 401 seam and is deliberately not
1499
+ * consumed here.
1500
+ *
1501
+ * This never writes lastError/cooldown: account health is owned
1502
+ * exclusively by the data plane. A rejected refresh (e.g.
1503
+ * codex_reauth_required) propagates to the scheduler, which logs it without
1504
+ * latching anything; the next real request or card status read surfaces the
1505
+ * sticky reauth state through the normal channels.
1506
+ */
1507
+ async runTokenMaintenanceCycle() {
1508
+ const data = await this.ensureLoaded();
1509
+ const account = data?.account;
1510
+ if (!account) return { refreshed: false };
1511
+ const fresh = typeof account.accessExp === "number" && account.accessExp - this.now > CODEX_REFRESH_LEAD_MS;
1512
+ if (fresh) return { refreshed: false };
1513
+ const before = account.accessToken;
1514
+ await this.getAccessToken();
1515
+ return { refreshed: this.data?.account.accessToken !== before };
1516
+ }
1482
1517
  async getAccountId() {
1483
1518
  const data = await this.ensureLoaded();
1484
1519
  if (!data?.account) throw codexAdminError("codex_not_connected", 409);
@@ -1514,7 +1549,8 @@ var CodexAuthService = class {
1514
1549
  registered = slugs.filter((s) => !hidden.has(s));
1515
1550
  await this.saveData({
1516
1551
  ...current,
1517
- account: { ...current.account, lastError: null },
1552
+ // Model discovery does not prove chat quota or request limits recovered.
1553
+ account: current.account,
1518
1554
  models: visible.map((m) => ({
1519
1555
  slug: m.slug,
1520
1556
  displayName: m.displayName,
@@ -1531,19 +1567,60 @@ var CodexAuthService = class {
1531
1567
  }
1532
1568
  // ------------------------------------------------------------------- usage -
1533
1569
  async getUsage() {
1570
+ if (this.usageFlight) return this.usageFlight;
1571
+ const flight = this.readUsageAndReconcile();
1572
+ this.usageFlight = flight;
1573
+ try {
1574
+ return await flight;
1575
+ } finally {
1576
+ if (this.usageFlight === flight) this.usageFlight = null;
1577
+ }
1578
+ }
1579
+ async readUsageAndReconcile() {
1580
+ const revision = this.quotaRevision;
1581
+ const epoch = this.epoch;
1534
1582
  const data = await this.ensureLoaded();
1535
1583
  if (!data?.account) return null;
1536
1584
  if (this.usageCache && this.now - this.usageCache.at < USAGE_CACHE_MS) {
1537
1585
  return this.usageCache.value;
1538
1586
  }
1539
1587
  const accessToken = await this.getAccessToken().catch(() => null);
1540
- if (!accessToken) return null;
1588
+ if (!accessToken) {
1589
+ if (this.epoch === epoch && this.quotaRevision === revision && this.data?.account === data.account) {
1590
+ this.usageCache = { at: this.now, value: null };
1591
+ }
1592
+ return null;
1593
+ }
1541
1594
  const fresh = await this.ensureLoaded(true);
1595
+ if (this.epoch !== epoch || fresh?.account.accountId !== data.account.accountId || fresh?.account.connectedAt !== data.account.connectedAt) return null;
1542
1596
  const usage = await fetchCodexUsage({
1543
1597
  accessToken,
1544
1598
  accountId: fresh?.account.accountId || void 0,
1545
1599
  fetchImpl: (url, init) => this.directFetch(url, init)
1546
1600
  }).catch(() => null);
1601
+ const matches = (current) => !!current && !!fresh && this.epoch === epoch && this.quotaRevision === revision && current.account.connectedAt === fresh.account.connectedAt && current.account.accountId === fresh.account.accountId && current.account.refreshToken === fresh.account.refreshToken;
1602
+ let accepted = false;
1603
+ await this.enqueueMutation(async () => {
1604
+ const current = await this.store.load().catch(() => null);
1605
+ if (!matches(current) || !current) return;
1606
+ accepted = true;
1607
+ const code = current.account.lastError?.code;
1608
+ const recover = usage?.canResume === true && (!code || code === "codex_usage_limit");
1609
+ const clearErrorCooldown = recover && code === "codex_usage_limit";
1610
+ const plan = usage?.plan || current.account.plan;
1611
+ if (plan !== current.account.plan || recover && (current.account.cooldownUntil || current.account.rateLimitCooldownUntil || code === "codex_usage_limit" || current.rateLimits)) {
1612
+ await this.saveData({
1613
+ ...current,
1614
+ ...recover ? { rateLimits: null } : {},
1615
+ account: { ...current.account, plan, ...recover ? {
1616
+ cooldownUntil: clearErrorCooldown ? null : current.account.cooldownUntil,
1617
+ rateLimitCooldownUntil: null,
1618
+ lastError: null
1619
+ } : {} }
1620
+ });
1621
+ }
1622
+ });
1623
+ if (!accepted || this.quotaRevision !== revision || this.epoch !== epoch) return null;
1547
1624
  this.usageCache = { at: this.now, value: usage };
1548
1625
  return usage;
1549
1626
  }
@@ -1632,7 +1709,12 @@ var CodexAuthService = class {
1632
1709
  // -------------------------------------------------------------- cooling/... -
1633
1710
  async isAccountCooling() {
1634
1711
  const data = await this.ensureLoaded();
1635
- return this.latestCooldown(data) !== void 0;
1712
+ if (this.latestCooldown(data) === void 0) return false;
1713
+ const code = data?.account.lastError?.code;
1714
+ if (!code || code === "codex_usage_limit") {
1715
+ await this.getUsage().catch(() => null);
1716
+ }
1717
+ return this.latestCooldown(this.data) !== void 0;
1636
1718
  }
1637
1719
  /**
1638
1720
  * Data-plane success channel: clears non-sticky failure residue once the
@@ -1662,6 +1744,8 @@ var CodexAuthService = class {
1662
1744
  }
1663
1745
  /** Data-plane error channel (usage_limit_reached, 401, …). Never throws. */
1664
1746
  noteUpstreamError(info) {
1747
+ this.quotaRevision++;
1748
+ this.usageCache = null;
1665
1749
  return this.enqueueMutation(async () => {
1666
1750
  const current = await this.store.load().catch(() => null);
1667
1751
  if (!current) return;
@@ -1684,6 +1768,8 @@ var CodexAuthService = class {
1684
1768
  * Never throws.
1685
1769
  */
1686
1770
  noteRateLimits(limits) {
1771
+ this.quotaRevision++;
1772
+ this.usageCache = null;
1687
1773
  return (async () => {
1688
1774
  const clean = normalizeRateLimits(limits);
1689
1775
  if (!clean) return;
@@ -1715,6 +1801,7 @@ var CodexAuthService = class {
1715
1801
  async disconnect() {
1716
1802
  const job = this.pending;
1717
1803
  this.epoch++;
1804
+ this.usageFlight = null;
1718
1805
  if (job) {
1719
1806
  this.terminalize(job, { status: "cancelled" });
1720
1807
  job.rejectCode(codexAdminError("codex_login_cancelled", 409));
@@ -2927,10 +3014,78 @@ var codexLocales = {
2927
3014
  }
2928
3015
  };
2929
3016
 
3017
+ // src/token-maintenance.ts
3018
+ var CODEX_TOKEN_MAINTENANCE_INITIAL_MS = 6e4;
3019
+ var CODEX_TOKEN_MAINTENANCE_INTERVAL_MS = 30 * 6e4;
3020
+ var CodexTokenMaintenance = class {
3021
+ constructor(cycle, logger, options = {}) {
3022
+ this.cycle = cycle;
3023
+ this.logger = logger;
3024
+ this.setTimer = options.setTimer ?? ((cb, ms) => setTimeout(cb, ms));
3025
+ this.clearTimer = options.clearTimer ?? ((handle) => clearTimeout(handle));
3026
+ this.initialDelayMs = options.initialDelayMs ?? CODEX_TOKEN_MAINTENANCE_INITIAL_MS;
3027
+ this.intervalMs = options.intervalMs ?? CODEX_TOKEN_MAINTENANCE_INTERVAL_MS;
3028
+ }
3029
+ timer;
3030
+ running = false;
3031
+ generation = 0;
3032
+ setTimer;
3033
+ clearTimer;
3034
+ initialDelayMs;
3035
+ intervalMs;
3036
+ start() {
3037
+ this.stop();
3038
+ this.running = true;
3039
+ const generation = this.generation;
3040
+ this.arm(this.initialDelayMs, generation);
3041
+ }
3042
+ stop() {
3043
+ this.running = false;
3044
+ this.generation++;
3045
+ if (this.timer !== void 0) {
3046
+ this.clearTimer(this.timer);
3047
+ this.timer = void 0;
3048
+ }
3049
+ }
3050
+ get isRunning() {
3051
+ return this.running;
3052
+ }
3053
+ arm(delayMs, generation) {
3054
+ const handle = this.setTimer(() => {
3055
+ this.timer = void 0;
3056
+ void this.tick(generation);
3057
+ }, delayMs);
3058
+ handle.unref?.();
3059
+ this.timer = handle;
3060
+ }
3061
+ async tick(generation) {
3062
+ if (!this.running || generation !== this.generation) return;
3063
+ try {
3064
+ const result = await this.cycle();
3065
+ if (result?.refreshed) {
3066
+ this.logger.info?.("[codex] background token refresh succeeded");
3067
+ }
3068
+ } catch (error) {
3069
+ this.logger.warn(
3070
+ `[codex] background token maintenance failed: ${error?.code ?? error?.message ?? "unknown"}`
3071
+ );
3072
+ } finally {
3073
+ if (this.running && generation === this.generation) {
3074
+ this.arm(this.intervalMs, generation);
3075
+ }
3076
+ }
3077
+ }
3078
+ };
3079
+ var currentMaintenance;
3080
+ function replaceCodexTokenMaintenance(next) {
3081
+ if (currentMaintenance && currentMaintenance !== next) currentMaintenance.stop();
3082
+ currentMaintenance = next;
3083
+ }
3084
+
2930
3085
  // src/plugin.ts
2931
3086
  var manifest = {
2932
3087
  name: "codex",
2933
- version: "1.0.11",
3088
+ version: "1.0.14",
2934
3089
  coreApi: "1",
2935
3090
  description: "Codex subscription managed provider: chatgpt.com backend-api/codex data plane, browser OAuth login (PKCE, loopback 1455/1457 + paste), model sync, usage and admin routes."
2936
3091
  };
@@ -2950,6 +3105,12 @@ async function activate(ctx) {
2950
3105
  }
2951
3106
  }
2952
3107
  const runtime = createCodexManagedRuntime({ service, host: upstreamHost, log: ctx.log });
3108
+ const maintenance = new CodexTokenMaintenance(
3109
+ () => service.runTokenMaintenanceCycle(),
3110
+ { warn: (message) => ctx.log.warn(message), info: (message) => ctx.log.info(message) }
3111
+ );
3112
+ maintenance.start();
3113
+ replaceCodexTokenMaintenance(maintenance);
2953
3114
  ctx.registerTransformer(ActivatedCodexTransformer);
2954
3115
  ctx.registerManagedRuntime(runtime);
2955
3116
  ctx.registerAdminRoutes((app) => registerCodexAdminRoutes(app, { getService: () => service }));
@@ -2965,4 +3126,3 @@ export {
2965
3126
  plugin_default as default,
2966
3127
  manifest
2967
3128
  };
2968
- //# sourceMappingURL=plugin.js.map
package/dist/plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex",
3
- "version": "1.0.13",
3
+ "version": "1.0.14",
4
4
  "coreApi": "1",
5
5
  "description": "Codex subscription managed provider: chatgpt.com backend-api/codex data plane, browser OAuth login (PKCE, loopback 1455/1457 + paste), model sync, usage and admin routes."
6
6
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wengine-ai/ccr-provider-codex",
3
- "version": "1.0.13",
3
+ "version": "1.0.14",
4
4
  "description": "Codex subscription provider plugin for claude-code-router: browser OAuth login, fixed-origin responses data plane, transformer, managed runtime, admin routes, config protector and UI card.",
5
5
  "type": "module",
6
6
  "main": "dist/plugin.js",