@wengine-ai/ccr-provider-codex 1.0.12 → 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
@@ -37,6 +37,10 @@ function parseCodexStatus(value) {
37
37
  const coolingUntil = finiteNumber(value.coolingUntil);
38
38
  if (coolingUntil !== null) next.coolingUntil = coolingUntil;
39
39
  if (typeof value.lastError === "string") next.lastError = value.lastError;
40
+ if (typeof value.lastErrorCode === "string" && value.lastErrorCode) {
41
+ const code = sanitizeCodexErrorCode(value.lastErrorCode);
42
+ if (code) next.lastErrorCode = code;
43
+ }
40
44
  return next;
41
45
  }
42
46
  function parseCodexLoginStart(value) {
@@ -94,6 +98,37 @@ function parseCodexMutation(value) {
94
98
  if (modelCount !== null) next.modelCount = modelCount;
95
99
  return next;
96
100
  }
101
+ function parseCodexResetCredits(value) {
102
+ if (!isRecord(value)) return null;
103
+ const availableCount = finiteNumber(value.availableCount);
104
+ if (availableCount === null || availableCount < 0 || !Number.isInteger(availableCount)) return null;
105
+ const credits = [];
106
+ if (Array.isArray(value.credits)) {
107
+ if (value.credits.length > 256) return null;
108
+ for (const raw of value.credits) {
109
+ if (!isRecord(raw)) return null;
110
+ const id = typeof raw.id === "string" && raw.id.length > 0 && raw.id.length <= 256 ? raw.id : null;
111
+ const status = typeof raw.status === "string" && raw.status.length > 0 && raw.status.length <= 32 ? raw.status : null;
112
+ if (!id || !status) return null;
113
+ const expiresAt = finiteNumber(raw.expiresAt);
114
+ const title = typeof raw.title === "string" && raw.title.trim() ? raw.title.trim().slice(0, 200) : void 0;
115
+ credits.push({ id, status, ...expiresAt !== null && expiresAt > 0 ? { expiresAt } : {}, ...title ? { title } : {} });
116
+ }
117
+ }
118
+ return { credits, availableCount };
119
+ }
120
+ function parseCodexResetConsume(value) {
121
+ if (!isRecord(value)) return null;
122
+ const outcome = value.outcome;
123
+ if (outcome !== "reset" && outcome !== "nothing_to_reset" && outcome !== "no_credit" && outcome !== "already_redeemed") return null;
124
+ const windowsReset = finiteNumber(value.windowsReset);
125
+ const availableCount = finiteNumber(value.availableCount);
126
+ return {
127
+ outcome,
128
+ windowsReset: windowsReset !== null && windowsReset >= 0 ? Math.floor(windowsReset) : 0,
129
+ ...availableCount !== null && availableCount >= 0 ? { availableCount: Math.floor(availableCount) } : {}
130
+ };
131
+ }
97
132
  function sanitizeCodexErrorCode(value) {
98
133
  if (typeof value !== "string") return null;
99
134
  if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(value)) return null;
@@ -293,6 +328,16 @@ var codexLocales = {
293
328
  usage_plan: "Plan: {{plan}}",
294
329
  usage_unavailable: "Quota information is not available right now.",
295
330
  usage_updated: "Updated {{time}}",
331
+ reset_available: "Usage resets: {{count}} available",
332
+ reset_expires: "next expires {{time}}",
333
+ reset_button: "Reset usage limits",
334
+ reset_title: "Use a usage reset?",
335
+ reset_warning: "This spends one gifted reset ({{count}} available) and immediately restores your usage limits. This cannot be undone.",
336
+ reset_confirm: "Use reset",
337
+ reset_done: "Usage limits reset. {{count}} resets remaining.",
338
+ reset_already: "This reset was already used. {{count}} resets remaining.",
339
+ reset_none_left: "No usage resets are available.",
340
+ reset_nothing: "Nothing to reset \u2014 your usage limits are already fresh.",
296
341
  window: {
297
342
  minutes: "{{count}} min",
298
343
  hours: "{{count}} h",
@@ -315,7 +360,18 @@ var codexLocales = {
315
360
  restore_failed: "Restoring the model failed.",
316
361
  callback_invalid: "That does not look like a valid callback URL (expected code and state parameters).",
317
362
  callback_rejected: "The callback was rejected. Please copy the full address and try again.",
318
- reconciliation_failed: "Applied, but the local settings draft could not be refreshed \u2014 reload the page to see the change."
363
+ reconciliation_failed: "Applied, but the local settings draft could not be refreshed \u2014 reload the page to see the change.",
364
+ codex_usage_limit: "This account has reached its Codex usage limit \u2014 the window resets automatically; the card recovers on the next request.",
365
+ codex_rate_limited: "Codex is rate limiting this account temporarily.",
366
+ codex_overloaded: "Codex upstream is temporarily unavailable.",
367
+ codex_request_rejected: "Codex rejected the request.",
368
+ codex_upstream_error: "Codex upstream request failed.",
369
+ reset_failed: "The usage reset failed. Please try again.",
370
+ codex_reset_busy: "A usage reset is already running \u2014 wait for it to finish.",
371
+ codex_reset_no_credit: "No usage resets are available.",
372
+ codex_reset_unavailable: "The reset service is unavailable right now. Please try again.",
373
+ codex_reset_invalid: "The reset request was invalid.",
374
+ codex_reauth_required: "The sign-in has expired. Reconnect to refresh the authorization."
319
375
  }
320
376
  }
321
377
  },
@@ -379,6 +435,16 @@ var codexLocales = {
379
435
  usage_plan: "\u5957\u9910\uFF1A{{plan}}",
380
436
  usage_unavailable: "\u6682\u65F6\u65E0\u6CD5\u83B7\u53D6\u914D\u989D\u4FE1\u606F\u3002",
381
437
  usage_updated: "\u66F4\u65B0\u4E8E {{time}}",
438
+ reset_available: "\u7528\u91CF\u91CD\u7F6E\uFF1A\u5269\u4F59 {{count}} \u6B21",
439
+ reset_expires: "\u6700\u8FD1\u5230\u671F {{time}}",
440
+ reset_button: "\u91CD\u7F6E\u7528\u91CF\u9650\u989D",
441
+ reset_title: "\u4F7F\u7528\u4E00\u6B21\u7528\u91CF\u91CD\u7F6E\uFF1F",
442
+ reset_warning: "\u5C06\u6D88\u8017\u4E00\u6B21\u8D60\u9001\u7684\u91CD\u7F6E\u673A\u4F1A\uFF08\u5269\u4F59 {{count}} \u6B21\uFF09\uFF0C\u7ACB\u5373\u6062\u590D\u7528\u91CF\u9650\u989D\u3002\u6B64\u64CD\u4F5C\u4E0D\u53EF\u64A4\u9500\u3002",
443
+ reset_confirm: "\u4F7F\u7528\u91CD\u7F6E",
444
+ reset_done: "\u7528\u91CF\u9650\u989D\u5DF2\u91CD\u7F6E\u3002\u5269\u4F59 {{count}} \u6B21\u3002",
445
+ reset_already: "\u8BE5\u91CD\u7F6E\u673A\u4F1A\u5DF2\u88AB\u4F7F\u7528\u3002\u5269\u4F59 {{count}} \u6B21\u3002",
446
+ reset_none_left: "\u6CA1\u6709\u53EF\u7528\u7684\u7528\u91CF\u91CD\u7F6E\u673A\u4F1A\u3002",
447
+ reset_nothing: "\u65E0\u9700\u91CD\u7F6E\u2014\u2014\u5F53\u524D\u7528\u91CF\u9650\u989D\u5C1A\u672A\u7528\u5C3D\u3002",
382
448
  window: {
383
449
  minutes: "{{count}} \u5206\u949F",
384
450
  hours: "{{count}} \u5C0F\u65F6",
@@ -401,7 +467,18 @@ var codexLocales = {
401
467
  restore_failed: "\u6062\u590D\u6A21\u578B\u5931\u8D25\u3002",
402
468
  callback_invalid: "\u8FD9\u770B\u8D77\u6765\u4E0D\u662F\u6709\u6548\u7684\u56DE\u8C03\u5730\u5740\uFF08\u5E94\u5305\u542B code \u4E0E state \u53C2\u6570\uFF09\u3002",
403
469
  callback_rejected: "\u56DE\u8C03\u88AB\u62D2\u7EDD\uFF0C\u8BF7\u590D\u5236\u5B8C\u6574\u5730\u5740\u540E\u91CD\u8BD5\u3002",
404
- reconciliation_failed: "\u5DF2\u751F\u6548\uFF0C\u4F46\u672C\u5730\u8BBE\u7F6E\u8349\u7A3F\u672A\u80FD\u5237\u65B0\u2014\u2014\u5237\u65B0\u9875\u9762\u5373\u53EF\u770B\u5230\u53D8\u66F4\u3002"
470
+ reconciliation_failed: "\u5DF2\u751F\u6548\uFF0C\u4F46\u672C\u5730\u8BBE\u7F6E\u8349\u7A3F\u672A\u80FD\u5237\u65B0\u2014\u2014\u5237\u65B0\u9875\u9762\u5373\u53EF\u770B\u5230\u53D8\u66F4\u3002",
471
+ codex_usage_limit: "\u8D26\u53F7\u5DF2\u8FBE\u5230 Codex \u7528\u91CF\u4E0A\u9650\u2014\u2014\u7A97\u53E3\u4F1A\u81EA\u52A8\u91CD\u7F6E\uFF0C\u4E0B\u4E00\u6B21\u8BF7\u6C42\u6062\u590D\u663E\u793A\u3002",
472
+ codex_rate_limited: "Codex \u6B63\u5728\u4E34\u65F6\u9650\u6D41\u8BE5\u8D26\u53F7\u3002",
473
+ codex_overloaded: "Codex \u4E0A\u6E38\u6682\u65F6\u4E0D\u53EF\u7528\u3002",
474
+ codex_request_rejected: "Codex \u62D2\u7EDD\u4E86\u8BE5\u8BF7\u6C42\u3002",
475
+ codex_upstream_error: "Codex \u4E0A\u6E38\u8BF7\u6C42\u5931\u8D25\u3002",
476
+ reset_failed: "\u7528\u91CF\u91CD\u7F6E\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002",
477
+ codex_reset_busy: "\u5DF2\u6709\u7528\u91CF\u91CD\u7F6E\u6B63\u5728\u8FDB\u884C\u2014\u2014\u8BF7\u7B49\u5F85\u5B8C\u6210\u3002",
478
+ codex_reset_no_credit: "\u6CA1\u6709\u53EF\u7528\u7684\u7528\u91CF\u91CD\u7F6E\u673A\u4F1A\u3002",
479
+ codex_reset_unavailable: "\u91CD\u7F6E\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",
480
+ codex_reset_invalid: "\u91CD\u7F6E\u8BF7\u6C42\u65E0\u6548\u3002",
481
+ codex_reauth_required: "\u767B\u5F55\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u8FDE\u63A5\u4EE5\u5237\u65B0\u6388\u6743\u3002"
405
482
  }
406
483
  }
407
484
  }
@@ -584,6 +661,24 @@ function mount(el, props) {
584
661
  let toast = null;
585
662
  let reconcileFailed = false;
586
663
  let confirmDisconnect = false;
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
+ };
680
+ let resetCredits = null;
681
+ let resetPhase = "idle";
587
682
  let login = null;
588
683
  let cancelling = false;
589
684
  let pasteField = null;
@@ -604,6 +699,8 @@ function mount(el, props) {
604
699
  const BADGE_BASE = "inline-flex items-center rounded-lg border px-2.5 py-0.5 text-[10px] font-bold transition-colors";
605
700
  const BADGE_OUTLINE = "border-white/10 text-foreground bg-white/5";
606
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";
607
704
  const node = (tag, text) => {
608
705
  const result = document.createElement(tag);
609
706
  if (text !== void 0) result.textContent = text;
@@ -722,6 +819,10 @@ function mount(el, props) {
722
819
  const parsed = parseCodexUsage(raw);
723
820
  rememberCodexUsage(parsed);
724
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
+ }
725
826
  } catch {
726
827
  if (alive && generation === id) showUsage(null, null);
727
828
  } finally {
@@ -744,6 +845,28 @@ function mount(el, props) {
744
845
  const id = generation;
745
846
  await readUsage(id, true);
746
847
  };
848
+ const readResetCredits = async (id) => {
849
+ resetPhase = "reading";
850
+ try {
851
+ const raw = await props.callApi("/reset-credits", { timeoutMs: 1e4 });
852
+ const parsed = parseCodexResetCredits(raw);
853
+ if (alive && generation === id) {
854
+ resetCredits = parsed;
855
+ resetPhase = parsed ? "ready" : "unavailable";
856
+ }
857
+ } catch {
858
+ if (alive && generation === id) {
859
+ resetCredits = null;
860
+ resetPhase = "unavailable";
861
+ }
862
+ }
863
+ if (alive) render();
864
+ };
865
+ const oldestResetCredit = () => {
866
+ const available = (resetCredits?.credits ?? []).filter((c) => c.status === "available");
867
+ if (!available.length) return null;
868
+ return available.slice().sort((a, b) => (a.expiresAt ?? Infinity) - (b.expiresAt ?? Infinity))[0];
869
+ };
747
870
  const run = async (kind, argument) => {
748
871
  if (!alive || locked || loading || props.disabled) return;
749
872
  if (kind === "usage") {
@@ -771,6 +894,35 @@ function mount(el, props) {
771
894
  reconcileFailed = false;
772
895
  render();
773
896
  try {
897
+ if (kind === "reset") {
898
+ const creditId = argument || void 0;
899
+ const result = parseCodexResetConsume(await post("/reset-credits/consume", creditId ? { creditId } : {}, void 0, 6e4));
900
+ if (!alive || generation !== id) return;
901
+ confirmReset = false;
902
+ if (!result) {
903
+ errorKey = "reset_failed";
904
+ return;
905
+ }
906
+ if (result.outcome === "reset" || result.outcome === "already_redeemed") {
907
+ clearCodexUsageCache();
908
+ usage = null;
909
+ usageUpdatedAt = null;
910
+ usagePhase = "idle";
911
+ resetPhase = "idle";
912
+ void readResetCredits(generation);
913
+ void readUsage(generation, true);
914
+ toast = t(result.outcome === "reset" ? "reset_done" : "reset_already", {
915
+ count: String(result.availableCount ?? resetCredits?.availableCount ?? 0)
916
+ });
917
+ } else if (result.outcome === "no_credit") {
918
+ resetCredits = { credits: [], availableCount: 0 };
919
+ resetPhase = "ready";
920
+ toast = t("reset_none_left");
921
+ } else {
922
+ toast = t("reset_nothing");
923
+ }
924
+ return;
925
+ }
774
926
  if (kind === "login") {
775
927
  const current = createCodexLogin({
776
928
  start: () => post("/login/start", {}),
@@ -808,6 +960,9 @@ function mount(el, props) {
808
960
  usage = null;
809
961
  usageUpdatedAt = null;
810
962
  usagePhase = "idle";
963
+ resetCredits = null;
964
+ resetPhase = "idle";
965
+ confirmReset = false;
811
966
  const { fresh, reconcileFailed: failed } = await settle(id);
812
967
  if (!alive || generation !== id) return;
813
968
  reconcileFailed = failed;
@@ -854,18 +1009,21 @@ function mount(el, props) {
854
1009
  return;
855
1010
  }
856
1011
  clearCodexUsageCache();
857
- const { fresh, reconcileFailed: failed } = await settle(id);
1012
+ const { reconcileFailed: failed } = await settle(id);
858
1013
  if (!alive || generation !== id) return;
859
1014
  reconcileFailed = failed;
860
1015
  usage = null;
861
1016
  usagePhase = "idle";
862
1017
  usageUpdatedAt = null;
1018
+ resetCredits = null;
1019
+ resetPhase = "idle";
1020
+ confirmReset = false;
863
1021
  toast = t("disconnected");
864
1022
  }
865
1023
  } catch (error) {
866
1024
  if (alive && generation === id) {
867
1025
  const reason = error?.reason;
868
- errorKey = sanitizeCodexErrorCode(typeof reason === "string" ? reason : null) ?? (kind === "login" ? "login_failed" : kind === "sync" ? "sync_failed" : kind === "hide" ? "hide_failed" : kind === "restore" ? "restore_failed" : "disconnect_failed");
1026
+ errorKey = sanitizeCodexErrorCode(typeof reason === "string" ? reason : null) ?? (kind === "login" ? "login_failed" : kind === "sync" ? "sync_failed" : kind === "hide" ? "hide_failed" : kind === "restore" ? "restore_failed" : kind === "reset" ? "reset_failed" : "disconnect_failed");
869
1027
  }
870
1028
  } finally {
871
1029
  endBusy();
@@ -926,6 +1084,7 @@ function mount(el, props) {
926
1084
  const state = loading ? "loading" : loadFailed && !status ? "error" : codexStateKey(status);
927
1085
  const connected = !loading && codexConnected(status);
928
1086
  const canDisconnect = !!status && (status.status !== "not_connected" || status.models.length > 0);
1087
+ const canSync = !loading && !!status && status.status !== "not_connected";
929
1088
  const busy = loading || action !== null;
930
1089
  const disabled = busy || props.disabled;
931
1090
  const pendingHide = (model) => action?.kind === "hide" && action.model === model;
@@ -957,7 +1116,7 @@ function mount(el, props) {
957
1116
  t("managed_provider", { name: status?.providerName || CODEX_PROVIDER_NAME })
958
1117
  ));
959
1118
  body.append(styled("p", "max-w-md text-xs text-muted-foreground", t("description")));
960
- const showAccountSurface = !loading && !!status && (connected || state === "cooldown");
1119
+ const showAccountSurface = !loading && !!status && (connected || state === "cooldown" || state === "error");
961
1120
  if (showAccountSurface && status) {
962
1121
  const rows = styled("dl", "grid max-w-md grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 text-xs");
963
1122
  const account = maskCodexAccountId(status.accountId) ?? t("unknown");
@@ -1026,12 +1185,34 @@ function mount(el, props) {
1026
1185
  } else if (usagePhase === "unavailable") {
1027
1186
  usageBox.append(styled("p", "text-[11px] text-muted-foreground", t("usage_unavailable")));
1028
1187
  }
1188
+ if (resetPhase === "ready" && resetCredits) {
1189
+ const row = styled("div", "flex flex-wrap items-center justify-between gap-2 border-t border-white/5 pt-1.5");
1190
+ const target = oldestResetCredit();
1191
+ const remaining = resetCredits.availableCount;
1192
+ row.append(styled("span", "text-[11px] text-muted-foreground", t("reset_available", { count: String(remaining) })));
1193
+ if (target?.expiresAt) {
1194
+ const expiry = formatCodexClock(target.expiresAt, locale);
1195
+ if (expiry) row.append(styled("span", "text-[10px] text-muted-foreground/60", t("reset_expires", { time: expiry })));
1196
+ }
1197
+ button(
1198
+ row,
1199
+ t("reset_button"),
1200
+ () => {
1201
+ confirmReset = true;
1202
+ render();
1203
+ },
1204
+ disabled || remaining <= 0 || !target,
1205
+ "outline",
1206
+ "h-7 px-2 text-[11px]"
1207
+ );
1208
+ usageBox.append(row);
1209
+ }
1029
1210
  body.append(usageBox);
1030
1211
  }
1031
1212
  const cooldown = status?.coolingUntil !== void 0 && state === "cooldown" ? formatCodexClock(status.coolingUntil, locale) : null;
1032
1213
  if (cooldown) body.append(styled("p", "text-xs font-medium text-yellow-600", t("cooldown_until", { time: cooldown })));
1033
1214
  if (state === "needs_relogin") body.append(styled("p", "text-xs text-yellow-600", t("needs_relogin_help")));
1034
- if (!connected && status?.lastError) body.append(errorAlert(errorText(status.lastError)));
1215
+ if (!connected && status?.lastError) body.append(errorAlert(errorText(status.lastErrorCode ?? status.lastError)));
1035
1216
  if (errorKey) body.append(errorAlert(errorText(errorKey)));
1036
1217
  if (reconcileFailed) body.append(errorAlert(t("errors.reconciliation_failed")));
1037
1218
  if (login) {
@@ -1106,7 +1287,7 @@ function mount(el, props) {
1106
1287
  actions,
1107
1288
  t("sync"),
1108
1289
  () => void run("sync"),
1109
- disabled || !connected,
1290
+ disabled || !canSync,
1110
1291
  "outline",
1111
1292
  "h-8 w-full text-xs",
1112
1293
  refreshCwIcon(`mr-1 h-3.5 w-3.5 ${action?.kind === "sync" ? "animate-spin" : ""}`)
@@ -1124,10 +1305,16 @@ function mount(el, props) {
1124
1305
  el.append(message);
1125
1306
  }
1126
1307
  if (confirmDisconnect) {
1127
- 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");
1128
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);
1129
1316
  panel.append(
1130
- styled("h3", "text-sm font-semibold tracking-tight text-foreground", t("disconnect_title")),
1317
+ title,
1131
1318
  styled("p", "text-xs text-muted-foreground", t("disconnect_warning"))
1132
1319
  );
1133
1320
  const footer = styled("div", "flex justify-end gap-2");
@@ -1148,12 +1335,50 @@ function mount(el, props) {
1148
1335
  "h-8 text-xs"
1149
1336
  );
1150
1337
  panel.append(footer);
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();
1347
+ }
1348
+ if (confirmReset) {
1349
+ const panel = styled("div", "max-w-md space-y-2 rounded-xl border border-primary/30 bg-primary/5 p-4");
1350
+ panel.setAttribute("role", "alertdialog");
1351
+ panel.setAttribute("aria-label", t("reset_title"));
1352
+ const target = oldestResetCredit();
1353
+ panel.append(
1354
+ styled("h3", "text-sm font-semibold tracking-tight text-foreground", t("reset_title")),
1355
+ styled("p", "text-xs text-muted-foreground", t("reset_warning", { count: String(resetCredits?.availableCount ?? 0) }))
1356
+ );
1357
+ const footer = styled("div", "flex justify-end gap-2");
1358
+ button(footer, t("cancel"), () => {
1359
+ if (!action) {
1360
+ confirmReset = false;
1361
+ render();
1362
+ }
1363
+ }, !!action, "outline", "h-8 text-xs");
1364
+ button(
1365
+ footer,
1366
+ action ? t("working") : t("reset_confirm"),
1367
+ () => {
1368
+ if (confirmReset) void run("reset", target?.id);
1369
+ },
1370
+ loading || action !== null || props.disabled || !target || (resetCredits?.availableCount ?? 0) <= 0,
1371
+ "primary",
1372
+ "h-8 text-xs"
1373
+ );
1374
+ panel.append(footer);
1151
1375
  el.append(panel);
1152
1376
  }
1153
1377
  };
1154
1378
  mounted.set(el, () => {
1155
1379
  alive = false;
1156
1380
  confirmDisconnect = false;
1381
+ removeConfirmOverlay();
1157
1382
  unsubscribeHost?.();
1158
1383
  unsubscribeHost = null;
1159
1384
  void session?.cancel().catch(() => {
@@ -1186,7 +1411,10 @@ function mount(el, props) {
1186
1411
  loading = false;
1187
1412
  render();
1188
1413
  const mountState = codexStateKey(status);
1189
- if (mountState === "connected" || mountState === "cooldown") void autoReadUsage();
1414
+ if (mountState === "connected" || mountState === "cooldown") {
1415
+ void autoReadUsage();
1416
+ void readResetCredits(generation);
1417
+ }
1190
1418
  });
1191
1419
  };
1192
1420
  mountRead(false);
package/dist/plugin.js CHANGED
@@ -33,7 +33,7 @@ function clearCodexRouterRefs(router, hidden, firstVisible) {
33
33
 
34
34
  // src/auth-service.ts
35
35
  import { createServer } from "node:http";
36
- import { randomBytes as randomBytes2 } from "node:crypto";
36
+ import { randomBytes as randomBytes2, randomUUID } from "node:crypto";
37
37
  import { promises as fs, constants } from "node:fs";
38
38
  import { dirname, join } from "node:path";
39
39
 
@@ -50,6 +50,9 @@ var CODEX_REFRESH_SCOPE = "openid profile email";
50
50
  var CODEX_AUTHORIZE_PATH = "/oauth/authorize";
51
51
  var CODEX_TOKEN_PATH = "/oauth/token";
52
52
  var CODEX_BACKEND_BASE = "https://chatgpt.com/backend-api/codex";
53
+ var CODEX_CHATGPT_ORIGIN = "https://chatgpt.com";
54
+ var CODEX_RESET_CREDITS_PATH = "/backend-api/wham/rate-limit-reset-credits";
55
+ var CODEX_RESET_CONSUME_PATH = "/backend-api/wham/rate-limit-reset-credits/consume";
53
56
  var CODEX_WHAM_USAGE_PATH = "/backend-api/wham/usage";
54
57
  var CODEX_DEFAULT_CLIENT_VERSION = "0.160.1";
55
58
  var CODEX_UPSTREAM_URL = `${CODEX_BACKEND_BASE}/responses`;
@@ -150,12 +153,11 @@ function classifyCodexError(status, body, _systemText) {
150
153
  const resetInSeconds = Number(err?.resets_in_seconds ?? json?.resets_in_seconds);
151
154
  const resetInMs = Number.isFinite(resetInSeconds) && resetInSeconds > 0 ? resetInSeconds * 1e3 : void 0;
152
155
  const quotaCooldown = () => {
153
- const now2 = Date.now();
154
- if (resetMs && resetMs > now2) return Math.max(resetMs - now2, 6e4);
156
+ const now = Date.now();
157
+ if (resetMs && resetMs > now) return Math.max(resetMs - now, 6e4);
155
158
  if (resetInMs) return Math.max(resetInMs, 6e4);
156
159
  return void 0;
157
160
  };
158
- const now = Date.now();
159
161
  if (/usage_limit_reached|RESOURCE_EXHAUSTED|limit reached/i.test(errType) || status === 429 && /usage_limit_reached|limit reached/i.test(message)) {
160
162
  return {
161
163
  code: "codex_usage_limit",
@@ -370,7 +372,13 @@ function parseCodexUsage(raw) {
370
372
  const primary = readUsageWindow(rateLimit.primary_window ?? rateLimit.primaryWindow);
371
373
  const secondary = readUsageWindow(rateLimit.secondary_window ?? rateLimit.secondaryWindow);
372
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
+ });
373
380
  return {
381
+ ...canResume ? { canResume: true } : {},
374
382
  plan,
375
383
  ...primary ? { primary } : {},
376
384
  ...secondary ? { secondary } : {}
@@ -397,6 +405,109 @@ function rateLimitsSaturated(limits, now) {
397
405
  }
398
406
  return false;
399
407
  }
408
+ var RESET_CREDIT_TITLES = {
409
+ codex_rate_limits: "Full reset"
410
+ };
411
+ function parseResetCredit(raw) {
412
+ if (!raw || typeof raw !== "object") return null;
413
+ if (typeof raw.id !== "string" || !raw.id || raw.id.length > 256) return null;
414
+ if (typeof raw.status !== "string" || !raw.status || raw.status.length > 32) return null;
415
+ const expires = typeof raw.expires_at === "string" && raw.expires_at ? Date.parse(raw.expires_at) : NaN;
416
+ const title = typeof raw.title === "string" && raw.title.trim() ? raw.title.trim().slice(0, 200) : RESET_CREDIT_TITLES[typeof raw.reset_type === "string" ? raw.reset_type : ""];
417
+ const description = typeof raw.description === "string" && raw.description.trim() ? raw.description.trim().slice(0, 300) : void 0;
418
+ return {
419
+ id: raw.id,
420
+ status: raw.status,
421
+ ...Number.isFinite(expires) && expires > 0 ? { expiresAt: expires } : {},
422
+ ...title ? { title } : {},
423
+ ...description ? { description } : {}
424
+ };
425
+ }
426
+ function parseCodexResetCredits(raw) {
427
+ if (!raw || typeof raw !== "object") return null;
428
+ const r = raw;
429
+ const availableCount = typeof r.available_count === "number" && Number.isFinite(r.available_count) ? Math.max(0, Math.floor(r.available_count)) : null;
430
+ if (availableCount === null) return null;
431
+ const credits = [];
432
+ if (Array.isArray(r.credits)) {
433
+ if (r.credits.length > 256) return null;
434
+ for (const item of r.credits) {
435
+ const credit = parseResetCredit(item);
436
+ if (!credit) return null;
437
+ credits.push(credit);
438
+ }
439
+ }
440
+ return { credits, availableCount };
441
+ }
442
+ function parseResetOutcome(code) {
443
+ switch (code) {
444
+ case "reset":
445
+ return "reset";
446
+ case "nothing_to_reset":
447
+ return "nothing_to_reset";
448
+ case "no_credit":
449
+ return "no_credit";
450
+ case "already_redeemed":
451
+ return "already_redeemed";
452
+ default:
453
+ return null;
454
+ }
455
+ }
456
+ async function resetCreditsFetch(params) {
457
+ const res = await params.fetchImpl(params.url, boundedFetchInit({
458
+ method: params.method,
459
+ headers: {
460
+ ...codexManagementHeaders(params.accessToken, params.accountId),
461
+ ...params.body !== void 0 ? { "Content-Type": "application/json" } : {}
462
+ },
463
+ ...params.body !== void 0 ? { body: JSON.stringify(params.body) } : {}
464
+ }));
465
+ const text = await res.text().catch(() => "");
466
+ let json = null;
467
+ try {
468
+ json = text ? JSON.parse(text) : null;
469
+ } catch {
470
+ json = null;
471
+ }
472
+ return { ok: res.ok, status: res.status, json };
473
+ }
474
+ async function fetchCodexResetCredits(params) {
475
+ const origin = params.origin ?? CODEX_CHATGPT_ORIGIN;
476
+ const res = await resetCreditsFetch({
477
+ url: `${origin}${CODEX_RESET_CREDITS_PATH}`,
478
+ method: "GET",
479
+ accessToken: params.accessToken,
480
+ accountId: params.accountId,
481
+ fetchImpl: params.fetchImpl
482
+ });
483
+ if (!res.ok) return null;
484
+ return parseCodexResetCredits(res.json);
485
+ }
486
+ async function consumeCodexResetCredit(params) {
487
+ const origin = params.origin ?? CODEX_CHATGPT_ORIGIN;
488
+ const res = await resetCreditsFetch({
489
+ url: `${origin}${CODEX_RESET_CONSUME_PATH}`,
490
+ method: "POST",
491
+ body: { redeem_request_id: params.redeemRequest, ...params.creditId ? { credit_id: params.creditId } : {} },
492
+ accessToken: params.accessToken,
493
+ accountId: params.accountId,
494
+ fetchImpl: params.fetchImpl
495
+ });
496
+ if (res.status === 401 || res.status === 403) {
497
+ throw codexError({ code: "codex_reauth_required", message: CODEX_SAFE_MESSAGES.codex_reauth_required, httpStatus: 401 });
498
+ }
499
+ const outcome = res.ok && res.json ? parseResetOutcome(res.json.code) : null;
500
+ if (!outcome) {
501
+ throw codexError({
502
+ code: "codex_upstream_error",
503
+ message: `Codex reset consume failed (HTTP ${res.status}).`,
504
+ httpStatus: 502,
505
+ retryable: res.status >= 500 || res.status === 429
506
+ });
507
+ }
508
+ const windowsReset = typeof res.json.windows_reset === "number" && Number.isFinite(res.json.windows_reset) ? Math.max(0, Math.floor(res.json.windows_reset)) : 0;
509
+ return { outcome, windowsReset };
510
+ }
400
511
  function isCodexModelId(value) {
401
512
  return typeof value === "string" && value.length > 0 && value.length <= 256 && !/[\x00-\x1f\x7f,]/.test(value);
402
513
  }
@@ -639,6 +750,24 @@ var CodexAuthService = class {
639
750
  refreshFlight = null;
640
751
  forceRefreshRequested = false;
641
752
  usageCache = null;
753
+ /** Reject quota reads overtaken by a new data-plane observation. */
754
+ quotaRevision = 0;
755
+ usageFlight = null;
756
+ /** Reset-credit listing cache (same short-TTL shape as usage). */
757
+ resetCache = null;
758
+ /** Single-flight for reset consumption: a queued second consume could
759
+ * redeem a second credit — reject instead. Assigned SYNCHRONOUSLY before
760
+ * any await (no race window). Key = in-flight redeem id. */
761
+ resetFlight = null;
762
+ /** Pending confirmation state: the redeem key survives a transport failure
763
+ * so a user-initiated retry reuses the SAME idempotency key until a
764
+ * terminal outcome (upstream dedupes per key — a lost response therefore
765
+ * cannot double-spend). Cleared on terminal outcomes and disconnect. */
766
+ pendingReset = null;
767
+ /** Locally marked spent credits: written only on a CONFIRMED terminal
768
+ * outcome; prevents re-consumption of a known-spent credit within this
769
+ * service lifetime. Upstream stays authoritative. */
770
+ spentResetCredits = /* @__PURE__ */ new Set();
642
771
  get now() {
643
772
  return (this.options.now ?? Date.now)();
644
773
  }
@@ -711,8 +840,11 @@ var CodexAuthService = class {
711
840
  return { status: "not_connected", providerName: CODEX_PROVIDER_NAME2, models, modelCount: models.length, hiddenModels: [] };
712
841
  }
713
842
  const coolingUntil = this.latestCooldown(data);
843
+ const latch = account.lastError;
844
+ const latchStale = !!latch && latch.code !== "codex_reauth_required" && typeof account.cooldownUntil === "number" && account.cooldownUntil <= now && !(typeof account.rateLimitCooldownUntil === "number" && account.rateLimitCooldownUntil > now);
714
845
  let status = "connected";
715
- if (account.lastError) status = "error";
846
+ const latchActive = !!latch && !latchStale;
847
+ if (latchActive) status = "error";
716
848
  else if (typeof account.accessExp === "number" && account.accessExp <= now) status = "expired";
717
849
  return {
718
850
  status,
@@ -724,7 +856,10 @@ var CodexAuthService = class {
724
856
  modelCount: models.length,
725
857
  hiddenModels: [...data?.hiddenModels ?? []],
726
858
  ...coolingUntil ? { coolingUntil } : {},
727
- lastError: account.lastError ? CODEX_SAFE_MESSAGES[account.lastError.code] ?? null : null
859
+ ...latchActive ? {
860
+ lastError: CODEX_SAFE_MESSAGES[latch.code] ?? null,
861
+ ...latch.code ? { lastErrorCode: latch.code } : {}
862
+ } : { lastError: null }
728
863
  };
729
864
  }
730
865
  latestCooldown(data) {
@@ -1265,6 +1400,9 @@ var CodexAuthService = class {
1265
1400
  this.refreshFlight = null;
1266
1401
  this.forceRefreshRequested = false;
1267
1402
  this.usageCache = null;
1403
+ this.resetCache = null;
1404
+ this.spentResetCredits.clear();
1405
+ this.pendingReset = null;
1268
1406
  const result = { status: "connected", models: registered, modelCount: registered.length };
1269
1407
  job.result = result;
1270
1408
  this.lastResult.set(job.loginId, result);
@@ -1350,6 +1488,32 @@ var CodexAuthService = class {
1350
1488
  this.forceRefreshRequested = true;
1351
1489
  await this.getAccessToken();
1352
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
+ }
1353
1517
  async getAccountId() {
1354
1518
  const data = await this.ensureLoaded();
1355
1519
  if (!data?.account) throw codexAdminError("codex_not_connected", 409);
@@ -1385,7 +1549,8 @@ var CodexAuthService = class {
1385
1549
  registered = slugs.filter((s) => !hidden.has(s));
1386
1550
  await this.saveData({
1387
1551
  ...current,
1388
- account: { ...current.account, lastError: null },
1552
+ // Model discovery does not prove chat quota or request limits recovered.
1553
+ account: current.account,
1389
1554
  models: visible.map((m) => ({
1390
1555
  slug: m.slug,
1391
1556
  displayName: m.displayName,
@@ -1402,26 +1567,154 @@ var CodexAuthService = class {
1402
1567
  }
1403
1568
  // ------------------------------------------------------------------- usage -
1404
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;
1405
1582
  const data = await this.ensureLoaded();
1406
1583
  if (!data?.account) return null;
1407
1584
  if (this.usageCache && this.now - this.usageCache.at < USAGE_CACHE_MS) {
1408
1585
  return this.usageCache.value;
1409
1586
  }
1410
1587
  const accessToken = await this.getAccessToken().catch(() => null);
1411
- 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
+ }
1412
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;
1413
1596
  const usage = await fetchCodexUsage({
1414
1597
  accessToken,
1415
1598
  accountId: fresh?.account.accountId || void 0,
1416
1599
  fetchImpl: (url, init) => this.directFetch(url, init)
1417
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;
1418
1624
  this.usageCache = { at: this.now, value: usage };
1419
1625
  return usage;
1420
1626
  }
1627
+ // ------------------------------------------------------ reset credits -
1628
+ /**
1629
+ * Available gifted usage resets. Null = surface absent/unreadable or the
1630
+ * caller is not connected. Short-TTL cached like usage; locally marked
1631
+ * spent credits are excluded from the visible availability.
1632
+ */
1633
+ async getResetCredits() {
1634
+ const data = await this.ensureLoaded();
1635
+ if (!data?.account) return null;
1636
+ if (this.resetCache && this.now - this.resetCache.at < USAGE_CACHE_MS) {
1637
+ return this.resetCache.value;
1638
+ }
1639
+ const accessToken = await this.getAccessToken().catch(() => null);
1640
+ if (!accessToken) return null;
1641
+ const fresh = await this.ensureLoaded(true);
1642
+ const listing = await fetchCodexResetCredits({
1643
+ accessToken,
1644
+ accountId: fresh?.account.accountId || void 0,
1645
+ fetchImpl: (url, init) => this.directFetch(url, init)
1646
+ }).catch(() => null);
1647
+ const value = listing && listing.credits.length ? { ...listing, credits: listing.credits.filter((c) => !this.spentResetCredits.has(c.id)) } : listing;
1648
+ this.resetCache = { at: this.now, value };
1649
+ return value;
1650
+ }
1651
+ /**
1652
+ * Consume ONE gifted reset credit. Explicit user action only — never called
1653
+ * by mount/poll/refresh. Single-flight: a second concurrent consume is
1654
+ * rejected (two queued consumes could redeem two credits). The idempotency
1655
+ * key is minted here at confirmation time and retained across user-initiated
1656
+ * retries of the same confirmation (upstream dedupes on it), so a lost
1657
+ * response cannot double-spend. Outcomes map to the upstream taxonomy;
1658
+ * `reset`/`already_redeemed` clear the usage cache and locally mark the
1659
+ * credit spent, then the caller re-lists for the authoritative count.
1660
+ */
1661
+ async consumeResetCredit(creditId) {
1662
+ if (this.resetFlight) throw codexAdminError("codex_reset_busy", 429);
1663
+ const redeemRequest = this.pendingReset && this.pendingReset.creditId === creditId ? this.pendingReset.redeemRequest : randomUUID();
1664
+ const promise = (async () => {
1665
+ try {
1666
+ const data = await this.ensureLoaded();
1667
+ if (!data?.account) throw codexAdminError("codex_not_connected", 409);
1668
+ if (creditId && this.spentResetCredits.has(creditId)) {
1669
+ throw codexAdminError("codex_reset_no_credit", 409);
1670
+ }
1671
+ const accessToken = await this.getAccessToken();
1672
+ const fresh = await this.ensureLoaded(true);
1673
+ const accountId = fresh?.account.accountId || void 0;
1674
+ return await consumeCodexResetCredit({
1675
+ redeemRequest,
1676
+ ...creditId ? { creditId } : {},
1677
+ accessToken,
1678
+ accountId,
1679
+ fetchImpl: (url, init) => this.directFetch(url, init)
1680
+ });
1681
+ } catch (error) {
1682
+ if (error?.code === "codex_reauth_required") throw codexAdminError("codex_reauth_required", 422);
1683
+ if (error?.code === "codex_upstream_error") throw codexAdminError("codex_reset_unavailable", 502);
1684
+ throw error;
1685
+ }
1686
+ })();
1687
+ this.pendingReset = { redeemRequest, ...creditId ? { creditId } : {} };
1688
+ this.resetFlight = { redeemRequest, promise };
1689
+ try {
1690
+ const result = await this.resetFlight.promise;
1691
+ if (result.outcome === "reset" || result.outcome === "already_redeemed") {
1692
+ if (creditId) this.spentResetCredits.add(creditId);
1693
+ this.usageCache = null;
1694
+ this.resetCache = null;
1695
+ } else if (result.outcome === "no_credit") {
1696
+ this.resetCache = { at: this.now, value: { credits: [], availableCount: 0 } };
1697
+ }
1698
+ this.pendingReset = null;
1699
+ let availableCount;
1700
+ if (result.outcome === "reset" || result.outcome === "already_redeemed") {
1701
+ const listing = await this.getResetCredits().catch(() => null);
1702
+ availableCount = listing?.availableCount;
1703
+ }
1704
+ return { ...result, ...availableCount !== void 0 ? { availableCount } : {} };
1705
+ } finally {
1706
+ if (this.resetFlight?.redeemRequest === redeemRequest) this.resetFlight = null;
1707
+ }
1708
+ }
1421
1709
  // -------------------------------------------------------------- cooling/... -
1422
1710
  async isAccountCooling() {
1423
1711
  const data = await this.ensureLoaded();
1424
- 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;
1425
1718
  }
1426
1719
  /**
1427
1720
  * Data-plane success channel: clears non-sticky failure residue once the
@@ -1451,6 +1744,8 @@ var CodexAuthService = class {
1451
1744
  }
1452
1745
  /** Data-plane error channel (usage_limit_reached, 401, …). Never throws. */
1453
1746
  noteUpstreamError(info) {
1747
+ this.quotaRevision++;
1748
+ this.usageCache = null;
1454
1749
  return this.enqueueMutation(async () => {
1455
1750
  const current = await this.store.load().catch(() => null);
1456
1751
  if (!current) return;
@@ -1473,6 +1768,8 @@ var CodexAuthService = class {
1473
1768
  * Never throws.
1474
1769
  */
1475
1770
  noteRateLimits(limits) {
1771
+ this.quotaRevision++;
1772
+ this.usageCache = null;
1476
1773
  return (async () => {
1477
1774
  const clean = normalizeRateLimits(limits);
1478
1775
  if (!clean) return;
@@ -1504,6 +1801,7 @@ var CodexAuthService = class {
1504
1801
  async disconnect() {
1505
1802
  const job = this.pending;
1506
1803
  this.epoch++;
1804
+ this.usageFlight = null;
1507
1805
  if (job) {
1508
1806
  this.terminalize(job, { status: "cancelled" });
1509
1807
  job.rejectCode(codexAdminError("codex_login_cancelled", 409));
@@ -1544,6 +1842,9 @@ var CodexAuthService = class {
1544
1842
  this.refreshFlight = null;
1545
1843
  this.forceRefreshRequested = false;
1546
1844
  this.usageCache = null;
1845
+ this.resetCache = null;
1846
+ this.spentResetCredits.clear();
1847
+ this.pendingReset = null;
1547
1848
  return { success: true };
1548
1849
  });
1549
1850
  }
@@ -2273,7 +2574,12 @@ function registerCodexAdminRoutes(app, deps) {
2273
2574
  codex_config_write_failed: 500,
2274
2575
  codex_models_fetch_failed: 422,
2275
2576
  codex_reauth_required: 422,
2276
- codex_model_invalid: 422
2577
+ codex_model_invalid: 422,
2578
+ codex_reset_busy: 429,
2579
+ codex_reset_no_credit: 409,
2580
+ codex_reset_unavailable: 502,
2581
+ codex_reset_invalid: 422,
2582
+ codex_reset_failed: 500
2277
2583
  };
2278
2584
  const isCodexErrorCode = (value) => typeof value === "string" && Object.prototype.hasOwnProperty.call(CODEX_ERROR_STATUS, value);
2279
2585
  function codexRouteError(error, reply, route, fallbackCode) {
@@ -2443,6 +2749,38 @@ function registerCodexAdminRoutes(app, deps) {
2443
2749
  return codexRouteError(error, reply, "usage", "codex_request_failed");
2444
2750
  }
2445
2751
  });
2752
+ app.get("/api/codex/reset-credits", async (req, reply) => {
2753
+ try {
2754
+ assertLocalCodexRequest(req);
2755
+ const service = deps.getService();
2756
+ if (!service) {
2757
+ reply.status(503);
2758
+ return { ok: false, success: false, error: "codex_request_failed" };
2759
+ }
2760
+ reply.status(200);
2761
+ return await service.getResetCredits();
2762
+ } catch (error) {
2763
+ return codexRouteError(error, reply, "reset-credits", "codex_request_failed");
2764
+ }
2765
+ });
2766
+ app.post("/api/codex/reset-credits/consume", async (req, reply) => {
2767
+ try {
2768
+ assertLocalCodexRequest(req);
2769
+ const service = deps.getService();
2770
+ if (!service) {
2771
+ reply.status(503);
2772
+ return { ok: false, success: false, error: "codex_request_failed" };
2773
+ }
2774
+ const raw = req.body?.creditId;
2775
+ const creditId = raw === void 0 || raw === null || raw === "" ? void 0 : typeof raw === "string" && raw.length > 0 && raw.length <= 256 ? raw : (() => {
2776
+ throw codexAdminError("codex_reset_invalid", 422);
2777
+ })();
2778
+ const result = await service.consumeResetCredit(creditId);
2779
+ return { ok: true, success: true, ...result };
2780
+ } catch (error) {
2781
+ return codexRouteError(error, reply, "reset-credits/consume", "codex_reset_failed");
2782
+ }
2783
+ });
2446
2784
  app.post("/api/codex/disconnect", async (req, reply) => {
2447
2785
  try {
2448
2786
  assertLocalCodexRequest(req);
@@ -2520,6 +2858,16 @@ var codexLocales = {
2520
2858
  usage_plan: "Plan: {{plan}}",
2521
2859
  usage_unavailable: "Quota information is not available right now.",
2522
2860
  usage_updated: "Updated {{time}}",
2861
+ reset_available: "Usage resets: {{count}} available",
2862
+ reset_expires: "next expires {{time}}",
2863
+ reset_button: "Reset usage limits",
2864
+ reset_title: "Use a usage reset?",
2865
+ reset_warning: "This spends one gifted reset ({{count}} available) and immediately restores your usage limits. This cannot be undone.",
2866
+ reset_confirm: "Use reset",
2867
+ reset_done: "Usage limits reset. {{count}} resets remaining.",
2868
+ reset_already: "This reset was already used. {{count}} resets remaining.",
2869
+ reset_none_left: "No usage resets are available.",
2870
+ reset_nothing: "Nothing to reset \u2014 your usage limits are already fresh.",
2523
2871
  window: {
2524
2872
  minutes: "{{count}} min",
2525
2873
  hours: "{{count}} h",
@@ -2542,7 +2890,18 @@ var codexLocales = {
2542
2890
  restore_failed: "Restoring the model failed.",
2543
2891
  callback_invalid: "That does not look like a valid callback URL (expected code and state parameters).",
2544
2892
  callback_rejected: "The callback was rejected. Please copy the full address and try again.",
2545
- reconciliation_failed: "Applied, but the local settings draft could not be refreshed \u2014 reload the page to see the change."
2893
+ reconciliation_failed: "Applied, but the local settings draft could not be refreshed \u2014 reload the page to see the change.",
2894
+ codex_usage_limit: "This account has reached its Codex usage limit \u2014 the window resets automatically; the card recovers on the next request.",
2895
+ codex_rate_limited: "Codex is rate limiting this account temporarily.",
2896
+ codex_overloaded: "Codex upstream is temporarily unavailable.",
2897
+ codex_request_rejected: "Codex rejected the request.",
2898
+ codex_upstream_error: "Codex upstream request failed.",
2899
+ reset_failed: "The usage reset failed. Please try again.",
2900
+ codex_reset_busy: "A usage reset is already running \u2014 wait for it to finish.",
2901
+ codex_reset_no_credit: "No usage resets are available.",
2902
+ codex_reset_unavailable: "The reset service is unavailable right now. Please try again.",
2903
+ codex_reset_invalid: "The reset request was invalid.",
2904
+ codex_reauth_required: "The sign-in has expired. Reconnect to refresh the authorization."
2546
2905
  }
2547
2906
  }
2548
2907
  },
@@ -2606,6 +2965,16 @@ var codexLocales = {
2606
2965
  usage_plan: "\u5957\u9910\uFF1A{{plan}}",
2607
2966
  usage_unavailable: "\u6682\u65F6\u65E0\u6CD5\u83B7\u53D6\u914D\u989D\u4FE1\u606F\u3002",
2608
2967
  usage_updated: "\u66F4\u65B0\u4E8E {{time}}",
2968
+ reset_available: "\u7528\u91CF\u91CD\u7F6E\uFF1A\u5269\u4F59 {{count}} \u6B21",
2969
+ reset_expires: "\u6700\u8FD1\u5230\u671F {{time}}",
2970
+ reset_button: "\u91CD\u7F6E\u7528\u91CF\u9650\u989D",
2971
+ reset_title: "\u4F7F\u7528\u4E00\u6B21\u7528\u91CF\u91CD\u7F6E\uFF1F",
2972
+ reset_warning: "\u5C06\u6D88\u8017\u4E00\u6B21\u8D60\u9001\u7684\u91CD\u7F6E\u673A\u4F1A\uFF08\u5269\u4F59 {{count}} \u6B21\uFF09\uFF0C\u7ACB\u5373\u6062\u590D\u7528\u91CF\u9650\u989D\u3002\u6B64\u64CD\u4F5C\u4E0D\u53EF\u64A4\u9500\u3002",
2973
+ reset_confirm: "\u4F7F\u7528\u91CD\u7F6E",
2974
+ reset_done: "\u7528\u91CF\u9650\u989D\u5DF2\u91CD\u7F6E\u3002\u5269\u4F59 {{count}} \u6B21\u3002",
2975
+ reset_already: "\u8BE5\u91CD\u7F6E\u673A\u4F1A\u5DF2\u88AB\u4F7F\u7528\u3002\u5269\u4F59 {{count}} \u6B21\u3002",
2976
+ reset_none_left: "\u6CA1\u6709\u53EF\u7528\u7684\u7528\u91CF\u91CD\u7F6E\u673A\u4F1A\u3002",
2977
+ reset_nothing: "\u65E0\u9700\u91CD\u7F6E\u2014\u2014\u5F53\u524D\u7528\u91CF\u9650\u989D\u5C1A\u672A\u7528\u5C3D\u3002",
2609
2978
  window: {
2610
2979
  minutes: "{{count}} \u5206\u949F",
2611
2980
  hours: "{{count}} \u5C0F\u65F6",
@@ -2628,16 +2997,95 @@ var codexLocales = {
2628
2997
  restore_failed: "\u6062\u590D\u6A21\u578B\u5931\u8D25\u3002",
2629
2998
  callback_invalid: "\u8FD9\u770B\u8D77\u6765\u4E0D\u662F\u6709\u6548\u7684\u56DE\u8C03\u5730\u5740\uFF08\u5E94\u5305\u542B code \u4E0E state \u53C2\u6570\uFF09\u3002",
2630
2999
  callback_rejected: "\u56DE\u8C03\u88AB\u62D2\u7EDD\uFF0C\u8BF7\u590D\u5236\u5B8C\u6574\u5730\u5740\u540E\u91CD\u8BD5\u3002",
2631
- reconciliation_failed: "\u5DF2\u751F\u6548\uFF0C\u4F46\u672C\u5730\u8BBE\u7F6E\u8349\u7A3F\u672A\u80FD\u5237\u65B0\u2014\u2014\u5237\u65B0\u9875\u9762\u5373\u53EF\u770B\u5230\u53D8\u66F4\u3002"
3000
+ reconciliation_failed: "\u5DF2\u751F\u6548\uFF0C\u4F46\u672C\u5730\u8BBE\u7F6E\u8349\u7A3F\u672A\u80FD\u5237\u65B0\u2014\u2014\u5237\u65B0\u9875\u9762\u5373\u53EF\u770B\u5230\u53D8\u66F4\u3002",
3001
+ codex_usage_limit: "\u8D26\u53F7\u5DF2\u8FBE\u5230 Codex \u7528\u91CF\u4E0A\u9650\u2014\u2014\u7A97\u53E3\u4F1A\u81EA\u52A8\u91CD\u7F6E\uFF0C\u4E0B\u4E00\u6B21\u8BF7\u6C42\u6062\u590D\u663E\u793A\u3002",
3002
+ codex_rate_limited: "Codex \u6B63\u5728\u4E34\u65F6\u9650\u6D41\u8BE5\u8D26\u53F7\u3002",
3003
+ codex_overloaded: "Codex \u4E0A\u6E38\u6682\u65F6\u4E0D\u53EF\u7528\u3002",
3004
+ codex_request_rejected: "Codex \u62D2\u7EDD\u4E86\u8BE5\u8BF7\u6C42\u3002",
3005
+ codex_upstream_error: "Codex \u4E0A\u6E38\u8BF7\u6C42\u5931\u8D25\u3002",
3006
+ reset_failed: "\u7528\u91CF\u91CD\u7F6E\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002",
3007
+ codex_reset_busy: "\u5DF2\u6709\u7528\u91CF\u91CD\u7F6E\u6B63\u5728\u8FDB\u884C\u2014\u2014\u8BF7\u7B49\u5F85\u5B8C\u6210\u3002",
3008
+ codex_reset_no_credit: "\u6CA1\u6709\u53EF\u7528\u7684\u7528\u91CF\u91CD\u7F6E\u673A\u4F1A\u3002",
3009
+ codex_reset_unavailable: "\u91CD\u7F6E\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",
3010
+ codex_reset_invalid: "\u91CD\u7F6E\u8BF7\u6C42\u65E0\u6548\u3002",
3011
+ codex_reauth_required: "\u767B\u5F55\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u8FDE\u63A5\u4EE5\u5237\u65B0\u6388\u6743\u3002"
3012
+ }
3013
+ }
3014
+ }
3015
+ };
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);
2632
3075
  }
2633
3076
  }
2634
3077
  }
2635
3078
  };
3079
+ var currentMaintenance;
3080
+ function replaceCodexTokenMaintenance(next) {
3081
+ if (currentMaintenance && currentMaintenance !== next) currentMaintenance.stop();
3082
+ currentMaintenance = next;
3083
+ }
2636
3084
 
2637
3085
  // src/plugin.ts
2638
3086
  var manifest = {
2639
3087
  name: "codex",
2640
- version: "1.0.11",
3088
+ version: "1.0.14",
2641
3089
  coreApi: "1",
2642
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."
2643
3091
  };
@@ -2657,6 +3105,12 @@ async function activate(ctx) {
2657
3105
  }
2658
3106
  }
2659
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);
2660
3114
  ctx.registerTransformer(ActivatedCodexTransformer);
2661
3115
  ctx.registerManagedRuntime(runtime);
2662
3116
  ctx.registerAdminRoutes((app) => registerCodexAdminRoutes(app, { getService: () => service }));
package/dist/plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex",
3
- "version": "1.0.11",
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.12",
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",