@juspay/neurolink 11.2.0 → 11.2.2

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.
Files changed (62) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/auth/codexOAuth.d.ts +67 -0
  3. package/dist/auth/codexOAuth.js +202 -0
  4. package/dist/auth/index.d.ts +1 -0
  5. package/dist/auth/index.js +4 -0
  6. package/dist/browser/neurolink.min.js +419 -419
  7. package/dist/cli/commands/auth.d.ts +27 -8
  8. package/dist/cli/commands/auth.js +425 -6
  9. package/dist/cli/commands/proxy.js +230 -5
  10. package/dist/cli/factories/authCommandFactory.d.ts +8 -0
  11. package/dist/cli/factories/authCommandFactory.js +74 -1
  12. package/dist/lib/auth/codexOAuth.d.ts +67 -0
  13. package/dist/lib/auth/codexOAuth.js +203 -0
  14. package/dist/lib/auth/index.d.ts +1 -0
  15. package/dist/lib/auth/index.js +4 -0
  16. package/dist/lib/providers/openaiChatCompletionsBase.js +26 -14
  17. package/dist/lib/proxy/accountCooldown.js +35 -2
  18. package/dist/lib/proxy/accountQuota.d.ts +29 -3
  19. package/dist/lib/proxy/accountQuota.js +203 -12
  20. package/dist/lib/proxy/accountUsage.js +15 -2
  21. package/dist/lib/proxy/codexAccountUsage.d.ts +26 -0
  22. package/dist/lib/proxy/codexAccountUsage.js +174 -0
  23. package/dist/lib/proxy/proxyAnalysis.js +12 -1
  24. package/dist/lib/proxy/proxyConfig.js +24 -0
  25. package/dist/lib/proxy/routingEvidence.d.ts +12 -1
  26. package/dist/lib/proxy/routingEvidence.js +23 -0
  27. package/dist/lib/proxy/runtimeConfig.js +3 -0
  28. package/dist/lib/server/routes/claudeProxyRoutes.d.ts +79 -5
  29. package/dist/lib/server/routes/claudeProxyRoutes.js +653 -72
  30. package/dist/lib/server/routes/codexProxyRoutes.d.ts +64 -0
  31. package/dist/lib/server/routes/codexProxyRoutes.js +454 -0
  32. package/dist/lib/types/cli.d.ts +7 -1
  33. package/dist/lib/types/codex.d.ts +95 -0
  34. package/dist/lib/types/codex.js +15 -0
  35. package/dist/lib/types/index.d.ts +1 -0
  36. package/dist/lib/types/index.js +1 -0
  37. package/dist/lib/types/proxy.d.ts +83 -0
  38. package/dist/lib/types/subscription.d.ts +13 -0
  39. package/dist/providers/openaiChatCompletionsBase.js +26 -14
  40. package/dist/proxy/accountCooldown.js +35 -2
  41. package/dist/proxy/accountQuota.d.ts +29 -3
  42. package/dist/proxy/accountQuota.js +203 -12
  43. package/dist/proxy/accountUsage.js +15 -2
  44. package/dist/proxy/codexAccountUsage.d.ts +26 -0
  45. package/dist/proxy/codexAccountUsage.js +173 -0
  46. package/dist/proxy/proxyAnalysis.js +12 -1
  47. package/dist/proxy/proxyConfig.js +24 -0
  48. package/dist/proxy/routingEvidence.d.ts +12 -1
  49. package/dist/proxy/routingEvidence.js +23 -0
  50. package/dist/proxy/runtimeConfig.js +3 -0
  51. package/dist/server/routes/claudeProxyRoutes.d.ts +79 -5
  52. package/dist/server/routes/claudeProxyRoutes.js +653 -72
  53. package/dist/server/routes/codexProxyRoutes.d.ts +64 -0
  54. package/dist/server/routes/codexProxyRoutes.js +453 -0
  55. package/dist/types/cli.d.ts +7 -1
  56. package/dist/types/codex.d.ts +95 -0
  57. package/dist/types/codex.js +14 -0
  58. package/dist/types/index.d.ts +1 -0
  59. package/dist/types/index.js +1 -0
  60. package/dist/types/proxy.d.ts +83 -0
  61. package/dist/types/subscription.d.ts +13 -0
  62. package/package.json +3 -1
@@ -14,6 +14,7 @@ export { ANTHROPIC_OAUTH_BASE_URL, DEFAULT_SCOPES, DEFAULT_REDIRECT_URI, DEFAULT
14
14
  export { AnthropicOAuth } from "./anthropicOAuth.js";
15
15
  export { OAuthError, OAuthConfigurationError, OAuthTokenExchangeError, OAuthTokenRefreshError, OAuthTokenValidationError, OAuthTokenRevocationError, OAuthCallbackServerError, } from "../types/index.js";
16
16
  export { createAnthropicOAuth, createAnthropicOAuthConfig, hasAnthropicOAuthCredentials, startCallbackServer, stopCallbackServer, performOAuthFlow, } from "./anthropicOAuth.js";
17
+ export { CODEX_CLIENT_ID, CODEX_AUTH_URL, CODEX_TOKEN_URL, CODEX_REDIRECT_URI, CODEX_DEFAULT_SCOPES, CODEX_BACKEND_BASE_URL, CODEX_RESPONSES_URL, CODEX_USAGE_URL, CODEX_USER_AGENT, CODEX_ORIGINATOR, decodeCodexAccessToken, decodeCodexEmail, resolveCodexAccountId, importCodexAuthFile, refreshCodexToken, codexTokenNeedsRefresh, } from "./codexOAuth.js";
17
18
  export { TokenStore, tokenStore, defaultTokenStore } from "./tokenStore.js";
18
19
  export { TokenStoreError } from "../types/index.js";
19
20
  export { AccountPool } from "./accountPool.js";
@@ -23,6 +23,10 @@ export { OAuthError, OAuthConfigurationError, OAuthTokenExchangeError, OAuthToke
23
23
  export { createAnthropicOAuth, createAnthropicOAuthConfig, hasAnthropicOAuthCredentials, startCallbackServer, stopCallbackServer, performOAuthFlow, } from "./anthropicOAuth.js";
24
24
  // OAuth types (canonical definitions in types/subscriptionTypes.ts)
25
25
  // =============================================================================
26
+ // CODEX (ChatGPT) OAUTH - subscription pool support
27
+ // =============================================================================
28
+ export { CODEX_CLIENT_ID, CODEX_AUTH_URL, CODEX_TOKEN_URL, CODEX_REDIRECT_URI, CODEX_DEFAULT_SCOPES, CODEX_BACKEND_BASE_URL, CODEX_RESPONSES_URL, CODEX_USAGE_URL, CODEX_USER_AGENT, CODEX_ORIGINATOR, decodeCodexAccessToken, decodeCodexEmail, resolveCodexAccountId, importCodexAuthFile, refreshCodexToken, codexTokenNeedsRefresh, } from "./codexOAuth.js";
29
+ // =============================================================================
26
30
  // TOKEN STORE - Secure Token Storage
27
31
  // =============================================================================
28
32
  // Main TokenStore class and instances
@@ -464,15 +464,22 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
464
464
  const apiErr = await buildAPIError(url, body, res);
465
465
  // One-shot 400 retry. The overflow corrector runs FIRST (it can
466
466
  // re-fit max_tokens from the provider's own numbers and also
467
- // self-heals the runtime window registry); otherwise a subclass
468
- // may strip a rejected field and return a modified body (e.g.
469
- // NIM's chat_template / reasoning_budget). The retry runs under
470
- // the SAME timeout controller as the first attempt, so the
471
- // configured timeout caps the overall call matching the
472
- // streaming path, which reuses its composed signal for the retry.
467
+ // self-heals the runtime window registry); its output then feeds
468
+ // a subclass hook that may strip a rejected field (e.g. NIM's
469
+ // chat_template / reasoning_budget), so a body that needs BOTH
470
+ // fixes gets both a plain `??` between the two would let
471
+ // whichever ran first silently win and drop the other's fix. The
472
+ // retry runs under the SAME timeout controller as the first
473
+ // attempt, so the configured timeout caps the overall call —
474
+ // matching the streaming path, which reuses its composed signal
475
+ // for the retry.
473
476
  const retryBody = res.status === 400
474
- ? (correctBodyAfterContextOverflow(body, apiErr) ??
475
- adjustBodyAfter400(body, apiErr))
477
+ ? (() => {
478
+ const typedErr = apiErr;
479
+ const overflowCorrected = correctBodyAfterContextOverflow(body, typedErr);
480
+ return (adjustBodyAfter400(overflowCorrected ?? body, typedErr) ??
481
+ overflowCorrected);
482
+ })()
476
483
  : undefined;
477
484
  if (!retryBody) {
478
485
  throw apiErr;
@@ -967,13 +974,18 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
967
974
  // consumed inside doFetch's closure, either returned on success or
968
975
  // discarded after buildAPIError read its body on failure.
969
976
  const apiErr = err;
970
- // Overflow corrector first (re-fits max_tokens from the provider's
971
- // own numbers + self-heals the window registry), then the subclass
972
- // hook (e.g. NIM strips chat_template / reasoning_budget when a model
973
- // rejects them).
977
+ // Overflow corrector first (re-fits max_tokens from the provider's own
978
+ // numbers + self-heals the window registry); its output then feeds the
979
+ // subclass hook (e.g. NIM strips chat_template / reasoning_budget when
980
+ // a model rejects them), so a body needing BOTH fixes gets both — a
981
+ // plain `??` between the two would let whichever ran first silently
982
+ // win and drop the other's fix.
974
983
  const retryBody = apiErr.statusCode === 400
975
- ? (this.correctBodyAfterContextOverflow(body, apiErr) ??
976
- this.adjustBodyAfter400(body, apiErr))
984
+ ? (() => {
985
+ const overflowCorrected = this.correctBodyAfterContextOverflow(body, apiErr);
986
+ return (this.adjustBodyAfter400(overflowCorrected ?? body, apiErr) ??
987
+ overflowCorrected);
988
+ })()
977
989
  : undefined;
978
990
  if (!retryBody) {
979
991
  throw apiErr;
@@ -2,7 +2,8 @@ import { readFile } from "node:fs/promises";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { AsyncMutex } from "../utils/asyncMutex.js";
5
- import { ACCOUNT_COOLING_REASONS } from "./routingEvidence.js";
5
+ import { logger } from "../utils/logger.js";
6
+ import { ACCOUNT_COOLING_REASONS, MAX_COOLDOWN_MS_BY_REASON, } from "./routingEvidence.js";
6
7
  import { writeJsonSnapshotAtomically } from "./snapshotPersistence.js";
7
8
  const COOLDOWN_FILE = "account-cooldowns.json";
8
9
  const VALID_REASONS = new Set(ACCOUNT_COOLING_REASONS);
@@ -32,13 +33,45 @@ function isPersistedCooldown(value) {
32
33
  typeof candidate.reason === "string" &&
33
34
  VALID_REASONS.has(candidate.reason));
34
35
  }
36
+ /**
37
+ * Cap a persisted cooldown at what its reason can plausibly mean, measured from
38
+ * when it was written.
39
+ *
40
+ * Entries written before per-reason ceilings existed can hold a wildly
41
+ * out-of-range wait — a "session" cooldown running for days, from a single stale
42
+ * reset timestamp. Clamping on load heals those without operator action.
43
+ * Clamping rather than dropping keeps a legitimate long weekly cooldown intact.
44
+ */
45
+ function sanitizePersistedCooldown(accountKey, entry) {
46
+ const ceiling = MAX_COOLDOWN_MS_BY_REASON[entry.reason];
47
+ if (ceiling === undefined) {
48
+ return entry;
49
+ }
50
+ const latest = entry.updatedAt + ceiling;
51
+ if (entry.coolingUntil <= latest) {
52
+ return entry;
53
+ }
54
+ // Announce it: an account silently parked far beyond what its reason can mean
55
+ // is exactly the condition that is hard to diagnose from the outside, and this
56
+ // runs once per process so it cannot become noise.
57
+ const hours = (ms) => (ms / 3_600_000).toFixed(1);
58
+ logger.always(`[proxy] cooldown clamp: ${accountKey} ${entry.reason} entry healed from ` +
59
+ `${hours(entry.coolingUntil - entry.updatedAt)}h to ` +
60
+ `${hours(ceiling)}h — the stored wait exceeded what "${entry.reason}" can mean`);
61
+ return { ...entry, coolingUntil: latest };
62
+ }
35
63
  async function ensureAccountCooldownsLoaded() {
36
64
  if (!cacheLoaded) {
37
65
  if (!cacheLoadPromise) {
38
66
  cacheLoadPromise = (async () => {
39
67
  try {
40
68
  const parsed = JSON.parse(await readFile(getCooldownFilePath(), "utf8"));
41
- memoryCache = Object.fromEntries(Object.entries(parsed).filter((entry) => isPersistedCooldown(entry[1])));
69
+ memoryCache = Object.fromEntries(Object.entries(parsed)
70
+ .filter((entry) => isPersistedCooldown(entry[1]))
71
+ .map(([key, entry]) => [
72
+ key,
73
+ sanitizePersistedCooldown(key, entry),
74
+ ]));
42
75
  }
43
76
  catch {
44
77
  memoryCache = {};
@@ -9,7 +9,14 @@
9
9
  * updates an in-memory cache and debounces disk writes so the request/response
10
10
  * path is never blocked by file I/O.
11
11
  */
12
- import type { AccountQuota } from "../types/index.js";
12
+ import type { AccountQuota, AccountQuotaWindow } from "../types/index.js";
13
+ /**
14
+ * Collapse a wire model id to its family by dropping the snapshot date, so
15
+ * `claude-fable-5-20260115` and `claude-fable-5-20260320` both tag the same
16
+ * scoped window. Without this a window would stop matching the day Anthropic
17
+ * ships a new snapshot.
18
+ */
19
+ export declare function modelFamilyToken(model: string): string;
13
20
  /** Read and normalize Anthropic's authoritative top-level unified status. */
14
21
  export declare function getUnifiedRateLimitStatus(headers: Headers | Record<string, string>): string | undefined;
15
22
  /**
@@ -20,13 +27,32 @@ export declare function getUnifiedRateLimitStatus(headers: Headers | Record<stri
20
27
  * fallback percentage together with an allowed overage status, which is the
21
28
  * equivalent provider state.
22
29
  */
23
- export declare function isQuotaOverageAvailable(quota: Pick<AccountQuota, "fallbackPercentage" | "fallbackStatus" | "overageStatus" | "overageInUse" | "upgradePaths"> | null | undefined): boolean;
30
+ export declare function isQuotaOverageAvailable(quota: Pick<AccountQuota, "fallbackPercentage" | "fallbackStatus" | "overageStatus" | "overageInUse" | "overageEnabled" | "overageDisabledReason" | "upgradePaths"> | null | undefined): boolean;
24
31
  /**
25
32
  * Parse Anthropic rate-limit / quota headers into an `AccountQuota`.
26
33
  * Returns `null` when key headers are absent.
27
34
  * Pure computation — no I/O, no blocking.
28
35
  */
29
- export declare function parseQuotaHeaders(headers: Headers | Record<string, string>): AccountQuota | null;
36
+ export declare function parseQuotaHeaders(headers: Headers | Record<string, string>, opts?: {
37
+ model?: string;
38
+ now?: number;
39
+ }): AccountQuota | null;
40
+ /**
41
+ * Merge dynamic limit windows across snapshots from different sources.
42
+ *
43
+ * The two sources see different things and neither is a superset: the usage API
44
+ * reports every plan bucket but only when explicitly refreshed, while response
45
+ * headers report only the window(s) touched by the request just served — but do
46
+ * so continuously. A plain overwrite in either direction loses real data, which
47
+ * is why a header capture used to erase the model-scoped windows a `/limits`
48
+ * refresh had just fetched.
49
+ */
50
+ export declare function mergeQuotaWindows(existing: AccountQuotaWindow[] | undefined, incoming: AccountQuotaWindow[] | undefined): AccountQuotaWindow[] | undefined;
51
+ /**
52
+ * Fold a freshly observed snapshot onto the previous one for the same account,
53
+ * preserving dynamic windows the new snapshot does not carry.
54
+ */
55
+ export declare function mergeQuotaSnapshot(previous: AccountQuota | undefined, incoming: AccountQuota): AccountQuota;
30
56
  /**
31
57
  * Initialise the quota module with a custom file path.
32
58
  * When set, all reads/writes go to this path instead of the default
@@ -33,6 +33,82 @@ function getHeader(headers, name) {
33
33
  }
34
34
  return undefined;
35
35
  }
36
+ /** Enumerate header names, working for both `Headers` and a plain record. */
37
+ function forEachHeaderName(headers, visit) {
38
+ if (typeof headers.forEach === "function") {
39
+ headers.forEach((_value, name) => visit(name));
40
+ return;
41
+ }
42
+ for (const name of Object.keys(headers)) {
43
+ visit(name);
44
+ }
45
+ }
46
+ /**
47
+ * Collapse a wire model id to its family by dropping the snapshot date, so
48
+ * `claude-fable-5-20260115` and `claude-fable-5-20260320` both tag the same
49
+ * scoped window. Without this a window would stop matching the day Anthropic
50
+ * ships a new snapshot.
51
+ */
52
+ export function modelFamilyToken(model) {
53
+ return model
54
+ .trim()
55
+ .replace(/[-_](latest)$/i, "")
56
+ .replace(/-\d{6,8}$/, "");
57
+ }
58
+ /** Unified header window tokens that map to the flat session/weekly fields. */
59
+ const FLAT_UNIFIED_WINDOW_TOKENS = new Set(["5h", "7d"]);
60
+ const UNIFIED_UTILIZATION_HEADER = /^anthropic-ratelimit-unified-([a-z0-9_]+)-utilization$/;
61
+ /**
62
+ * Discover model-scoped rate-limit windows from response headers.
63
+ *
64
+ * Anthropic reports a per-model weekly cap as its own header family — today
65
+ * `anthropic-ratelimit-unified-7d_oi-*`, sent only on responses for the model
66
+ * that cap applies to. The token is matched generically rather than hardcoded
67
+ * so a future `7d_xx` is captured without a code change, mirroring how
68
+ * `mapUsageLimit` preserves the provider's vocabulary verbatim.
69
+ *
70
+ * Requires the request's model: the header states a limit but never says which
71
+ * model it scopes, and an untagged window cannot be matched to a later request.
72
+ */
73
+ function parseScopedQuotaWindows(headers, model, now) {
74
+ if (!model) {
75
+ return [];
76
+ }
77
+ const scopeModel = modelFamilyToken(model);
78
+ if (!scopeModel) {
79
+ return [];
80
+ }
81
+ const tokens = [];
82
+ forEachHeaderName(headers, (name) => {
83
+ const match = UNIFIED_UTILIZATION_HEADER.exec(name.toLowerCase());
84
+ if (match?.[1] && !FLAT_UNIFIED_WINDOW_TOKENS.has(match[1])) {
85
+ tokens.push(match[1]);
86
+ }
87
+ });
88
+ const windows = [];
89
+ for (const token of tokens) {
90
+ const P = `anthropic-ratelimit-unified-${token}-`;
91
+ const used = parseFloat(getHeader(headers, `${P}utilization`) ?? "");
92
+ if (Number.isNaN(used)) {
93
+ continue;
94
+ }
95
+ const resetRaw = getHeader(headers, `${P}reset`);
96
+ const status = getHeader(headers, `${P}status`)?.trim().toLowerCase();
97
+ windows.push({
98
+ kind: token.startsWith("7d") ? "weekly_scoped" : "session_scoped",
99
+ group: token.startsWith("7d") ? "weekly" : "session",
100
+ used,
101
+ status: status ?? "unknown",
102
+ resetsAt: resetRaw ? parseInt(resetRaw, 10) || 0 : 0,
103
+ scopeModel,
104
+ scopeModelId: model,
105
+ headerWindow: token,
106
+ source: "headers",
107
+ updatedAt: now,
108
+ });
109
+ }
110
+ return windows;
111
+ }
36
112
  /** Read and normalize Anthropic's authoritative top-level unified status. */
37
113
  export function getUnifiedRateLimitStatus(headers) {
38
114
  const value = getHeader(headers, "anthropic-ratelimit-unified-status");
@@ -48,7 +124,25 @@ export function getUnifiedRateLimitStatus(headers) {
48
124
  * equivalent provider state.
49
125
  */
50
126
  export function isQuotaOverageAvailable(quota) {
51
- if (quota?.overageStatus?.trim().toLowerCase() !== "allowed") {
127
+ // `extra_usage.is_enabled` from the usage API is the account's own setting and
128
+ // is reported even for an account that has never served a request, which the
129
+ // header signals below cannot cover. Positive only: it is refreshed far less
130
+ // often than headers are, so a stale `false` must not veto live evidence that
131
+ // overage is actually serving.
132
+ //
133
+ // It is also sticky — the merge carries it forward whenever a payload omits
134
+ // `extra_usage` — so a live header saying overage is switched off must be
135
+ // able to veto it. Without that veto an org disabling extra usage would leave
136
+ // the flag true forever, suppressing every cooldown and sending request after
137
+ // request that is certain to 429.
138
+ const overageStatus = quota?.overageStatus?.trim().toLowerCase();
139
+ const providerDisabledOverage = overageStatus === "rejected" || quota?.overageDisabledReason !== undefined;
140
+ if (quota?.overageEnabled === true && !providerDisabledOverage) {
141
+ return true;
142
+ }
143
+ // Explicit null check: overageStatus is now read before this point, so the
144
+ // optional-chain no longer narrows `quota` for the accesses below.
145
+ if (!quota || overageStatus !== "allowed") {
52
146
  return false;
53
147
  }
54
148
  if (quota.overageInUse === true) {
@@ -69,7 +163,7 @@ export function isQuotaOverageAvailable(quota) {
69
163
  * Returns `null` when key headers are absent.
70
164
  * Pure computation — no I/O, no blocking.
71
165
  */
72
- export function parseQuotaHeaders(headers) {
166
+ export function parseQuotaHeaders(headers, opts) {
73
167
  // Anthropic prefixes all quota headers with "anthropic-ratelimit-"
74
168
  const P = "anthropic-ratelimit-";
75
169
  const sessionUtilRaw = getHeader(headers, `${P}unified-5h-utilization`);
@@ -85,6 +179,10 @@ export function parseQuotaHeaders(headers) {
85
179
  const sessionResetRaw = getHeader(headers, `${P}unified-5h-reset`);
86
180
  const weeklyResetRaw = getHeader(headers, `${P}unified-7d-reset`);
87
181
  const fallbackRaw = getHeader(headers, `${P}unified-fallback-percentage`);
182
+ const now = opts?.now ?? Date.now();
183
+ const scopedWindows = parseScopedQuotaWindows(headers, opts?.model, now);
184
+ const overageDisabledReason = getHeader(headers, `${P}unified-overage-disabled-reason`);
185
+ const representativeClaim = getHeader(headers, `${P}unified-representative-claim`);
88
186
  return {
89
187
  unifiedStatus: getUnifiedRateLimitStatus(headers),
90
188
  sessionUsed,
@@ -94,15 +192,114 @@ export function parseQuotaHeaders(headers) {
94
192
  weeklyStatus: getHeader(headers, `${P}unified-7d-status`) ?? "unknown",
95
193
  weeklyResetAt: weeklyResetRaw ? parseInt(weeklyResetRaw, 10) || 0 : 0,
96
194
  fallbackPercentage: fallbackRaw ? parseFloat(fallbackRaw) || 0 : 0,
195
+ // Anthropic does not send `unified-fallback` on the current wire, so this is
196
+ // always "unknown" in practice, which keeps the legacy back-compat branch of
197
+ // isQuotaOverageAvailable inert. Left as-is deliberately: making that branch
198
+ // reachable would stop cooling accounts that today park correctly, and the
199
+ // authoritative extra-usage signal now comes from `overageEnabled` instead.
97
200
  fallbackStatus: getHeader(headers, `${P}unified-fallback`) ?? "unknown",
98
201
  upgradePaths: getHeader(headers, `${P}unified-upgrade-paths`),
99
202
  overageStatus: getHeader(headers, `${P}unified-overage-status`) ?? "unknown",
100
203
  overageInUse: getHeader(headers, `${P}unified-overage-in-use`)?.trim().toLowerCase() ===
101
204
  "true",
102
- lastUpdated: Date.now(),
205
+ ...(overageDisabledReason ? { overageDisabledReason } : {}),
206
+ ...(representativeClaim ? { representativeClaim } : {}),
207
+ lastUpdated: now,
103
208
  source: "headers",
209
+ ...(scopedWindows.length > 0 ? { windows: scopedWindows } : {}),
104
210
  };
105
211
  }
212
+ /**
213
+ * Identity of a window across refreshes.
214
+ *
215
+ * Scope identity uses `scopeModel` — the model *family* on header-derived
216
+ * windows — ahead of the dated wire id, so a new model snapshot updates the
217
+ * existing window instead of appending a second one for the same cap and
218
+ * growing the array on every release. `source` keeps the two providers' views
219
+ * of the same cap distinct, since they name it differently and are reconciled
220
+ * by freshness rather than merged.
221
+ */
222
+ function quotaWindowKey(window) {
223
+ return [
224
+ window.kind,
225
+ window.source ?? "usage-api",
226
+ window.headerWindow ?? "",
227
+ window.scopeModel ?? window.scopeModelId ?? "",
228
+ window.scopeSurface ?? "",
229
+ ].join("|");
230
+ }
231
+ /**
232
+ * Merge dynamic limit windows across snapshots from different sources.
233
+ *
234
+ * The two sources see different things and neither is a superset: the usage API
235
+ * reports every plan bucket but only when explicitly refreshed, while response
236
+ * headers report only the window(s) touched by the request just served — but do
237
+ * so continuously. A plain overwrite in either direction loses real data, which
238
+ * is why a header capture used to erase the model-scoped windows a `/limits`
239
+ * refresh had just fetched.
240
+ */
241
+ export function mergeQuotaWindows(existing, incoming) {
242
+ if (!incoming?.length) {
243
+ return existing;
244
+ }
245
+ if (!existing?.length) {
246
+ return incoming;
247
+ }
248
+ const merged = new Map();
249
+ const incomingFromUsageApi = incoming.some((window) => (window.source ?? "usage-api") === "usage-api");
250
+ for (const window of existing) {
251
+ // A usage-API sweep is authoritative for every bucket it reports, but it
252
+ // never reports the header-only scoped windows — so those are carried over.
253
+ if (incomingFromUsageApi && (window.source ?? "usage-api") !== "headers") {
254
+ continue;
255
+ }
256
+ merged.set(quotaWindowKey(window), window);
257
+ }
258
+ for (const window of incoming) {
259
+ merged.set(quotaWindowKey(window), window);
260
+ }
261
+ return [...merged.values()];
262
+ }
263
+ /**
264
+ * Fold a freshly observed snapshot onto the previous one for the same account,
265
+ * preserving dynamic windows the new snapshot does not carry.
266
+ */
267
+ export function mergeQuotaSnapshot(previous, incoming) {
268
+ if (!previous) {
269
+ return incoming;
270
+ }
271
+ const windows = mergeQuotaWindows(previous.windows, incoming.windows);
272
+ const next = { ...incoming };
273
+ if (windows !== undefined) {
274
+ next.windows = windows;
275
+ }
276
+ // Account configuration, not per-response state: each source reports only
277
+ // some of these, so a plain overwrite makes the value flicker in and out
278
+ // depending on which source wrote last. `overageEnabled` comes only from the
279
+ // usage API and `overageDisabledReason` only from response headers, so
280
+ // whichever wrote last would otherwise erase the other's field.
281
+ if (next.overageEnabled === undefined &&
282
+ previous.overageEnabled !== undefined) {
283
+ next.overageEnabled = previous.overageEnabled;
284
+ }
285
+ if (next.overageDisabledReason === undefined &&
286
+ previous.overageDisabledReason !== undefined) {
287
+ next.overageDisabledReason = previous.overageDisabledReason;
288
+ }
289
+ if (next.representativeClaim === undefined &&
290
+ previous.representativeClaim !== undefined) {
291
+ next.representativeClaim = previous.representativeClaim;
292
+ }
293
+ // windowsUpdatedAt tracks the last full usage-API sweep; a header capture
294
+ // adds one window and must not claim to have refreshed all of them.
295
+ const windowsUpdatedAt = incoming.source === "usage-api"
296
+ ? incoming.windowsUpdatedAt
297
+ : (incoming.windowsUpdatedAt ?? previous.windowsUpdatedAt);
298
+ if (windowsUpdatedAt !== undefined) {
299
+ next.windowsUpdatedAt = windowsUpdatedAt;
300
+ }
301
+ return next;
302
+ }
106
303
  // ---------------------------------------------------------------------------
107
304
  // In-memory cache + debounced async persistence
108
305
  // ---------------------------------------------------------------------------
@@ -236,15 +433,9 @@ export async function loadAccountQuota(accountKey) {
236
433
  export async function saveAccountQuota(accountKey, quota) {
237
434
  await stateMutex.runExclusive(async () => {
238
435
  await ensureAccountQuotasLoaded();
239
- const next = { ...quota };
240
- // Header-sourced saves carry no dynamic windows; a passive capture right
241
- // after a usage-API refresh must not erase the refreshed buckets.
242
- const existing = memoryCache[accountKey];
243
- if (next.windows === undefined && existing?.windows !== undefined) {
244
- next.windows = existing.windows;
245
- next.windowsUpdatedAt = existing.windowsUpdatedAt;
246
- }
247
- memoryCache[accountKey] = next;
436
+ // A header capture reports only the windows the served request touched, so
437
+ // it must fold onto the existing snapshot rather than replace it.
438
+ memoryCache[accountKey] = mergeQuotaSnapshot(memoryCache[accountKey], quota);
248
439
  dirty = true;
249
440
  cacheVersion += 1;
250
441
  });
@@ -199,12 +199,14 @@ function toFraction(percent) {
199
199
  ? percent / 100
200
200
  : undefined;
201
201
  }
202
- function mapUsageLimit(entry) {
202
+ function mapUsageLimit(entry, now) {
203
203
  const window = {
204
204
  kind: entry.kind ?? "unknown",
205
205
  used: toFraction(entry.percent) ?? 0,
206
206
  status: deriveWindowStatus(entry.percent, entry.severity),
207
207
  resetsAt: isoToEpochSeconds(entry.resets_at),
208
+ source: "usage-api",
209
+ updatedAt: now,
208
210
  };
209
211
  if (entry.group !== undefined) {
210
212
  window.group = entry.group;
@@ -219,6 +221,13 @@ function mapUsageLimit(entry) {
219
221
  if (scopeModel) {
220
222
  window.scopeModel = scopeModel;
221
223
  }
224
+ // The wire id matches a request's `model` exactly, so keeping it lets routing
225
+ // skip the fuzzy display-name match ("Fable" vs "claude-fable-5-20260115").
226
+ // Often null in practice, which is why the display-name path still exists.
227
+ const scopeModelId = entry.scope?.model?.id;
228
+ if (scopeModelId) {
229
+ window.scopeModelId = scopeModelId;
230
+ }
222
231
  const scopeSurface = entry.scope?.surface;
223
232
  if (scopeSurface) {
224
233
  window.scopeSurface = scopeSurface;
@@ -242,7 +251,7 @@ export function usageToQuota(usage, opts) {
242
251
  return null;
243
252
  }
244
253
  const { now, prior } = opts;
245
- const windows = limits.map(mapUsageLimit);
254
+ const windows = limits.map((entry) => mapUsageLimit(entry, now));
246
255
  const sessionLimit = limits.find((entry) => entry.kind === "session");
247
256
  const weeklyLimit = limits.find((entry) => entry.kind === "weekly_all");
248
257
  const sessionPct = usage.five_hour?.utilization ?? sessionLimit?.percent ?? undefined;
@@ -273,6 +282,10 @@ export function usageToQuota(usage, opts) {
273
282
  weeklyResetAt,
274
283
  fallbackPercentage: prior?.fallbackPercentage ?? 0,
275
284
  overageStatus,
285
+ // Authoritative: the header trio the legacy overage checks rely on is only
286
+ // ever sent on a served response, so an account refreshed but not yet used
287
+ // would otherwise look overage-ineligible even with extra usage switched on.
288
+ ...(typeof overageEnabled === "boolean" ? { overageEnabled } : {}),
276
289
  lastUpdated: now,
277
290
  windows,
278
291
  windowsUpdatedAt: now,
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Codex account enumeration + usage/quota normalisation.
3
+ *
4
+ * Mirrors `accountUsage.ts` (Anthropic) for the Codex pool. Codex reports two
5
+ * rate-limit windows — `primary` (short) and `secondary` (weekly) — which we
6
+ * map onto the shared AccountQuota session/weekly fields so the same routing,
7
+ * cooldown, and display code works for both providers.
8
+ */
9
+ import type { AccountQuota, CodexRateLimits, CodexUsageFetchResult, ProxyPassthroughAccount } from "../types/index.js";
10
+ export declare const CODEX_ACCOUNT_PREFIX = "codex:";
11
+ /** Enumerate Codex OAuth accounts from the token store for usage refresh. */
12
+ export declare function listCodexAccountsForUsage(): Promise<ProxyPassthroughAccount[]>;
13
+ /** Normalise a Codex rate-limit block into the shared AccountQuota shape. */
14
+ export declare function codexRateLimitsToQuota(rateLimits: CodexRateLimits | null | undefined, now?: number): AccountQuota;
15
+ /**
16
+ * Parse Codex rate-limit information from response headers. The ChatGPT backend
17
+ * returns a JSON rate-limit blob in `x-codex-ratelimit` / `x-codex-active-limit`
18
+ * on some responses; parse defensively and return null when absent.
19
+ */
20
+ export declare function parseCodexRateLimitHeaders(headers: Headers, now?: number): AccountQuota | null;
21
+ /** Fetch the usage/limits window for one Codex account. */
22
+ export declare function fetchCodexAccountUsage(account: ProxyPassthroughAccount, options?: {
23
+ timeoutMs?: number;
24
+ }): Promise<CodexUsageFetchResult>;
25
+ /** Decode plan type from an account's access token (display convenience). */
26
+ export declare function codexAccountPlanType(account: ProxyPassthroughAccount): string | undefined;