chompyy 0.4.7 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +40 -6
  2. package/dist/advice.js +2 -1
  3. package/dist/agentlimits.js +77 -0
  4. package/dist/agentusage.js +96 -0
  5. package/dist/appstate.js +72 -5
  6. package/dist/away.js +44 -5
  7. package/dist/blueprint.js +3 -7
  8. package/dist/board.js +4 -0
  9. package/dist/cli.js +328 -15
  10. package/dist/codexquota.js +106 -0
  11. package/dist/codexusage.js +10 -0
  12. package/dist/config.js +2 -0
  13. package/dist/context.js +30 -0
  14. package/dist/costs.js +1 -0
  15. package/dist/daytime.js +68 -0
  16. package/dist/demon.js +20 -0
  17. package/dist/didwork.js +46 -0
  18. package/dist/label.js +33 -0
  19. package/dist/learning.js +35 -0
  20. package/dist/menu.js +17 -0
  21. package/dist/nightcap.js +60 -0
  22. package/dist/nudge.js +47 -18
  23. package/dist/pacing.js +16 -1
  24. package/dist/questions.js +71 -0
  25. package/dist/recap.js +74 -0
  26. package/dist/receipt.js +48 -0
  27. package/dist/recipe.js +79 -0
  28. package/dist/send.js +46 -20
  29. package/dist/stamps.js +14 -0
  30. package/dist/taste.js +67 -7
  31. package/dist/triggers.js +5 -0
  32. package/dist/unkeep.js +220 -0
  33. package/dist/usage.js +21 -1
  34. package/dist/vendor/codeburn/antigravity.js +309 -0
  35. package/dist/vendor/codeburn/codex.js +429 -0
  36. package/dist/vendor/codeburn/copilot.js +292 -0
  37. package/dist/vendor/codeburn/gemini.js +195 -0
  38. package/dist/vendor/codeburn/grokbot.js +182 -0
  39. package/dist/vendor/codeburn/kimi.js +178 -0
  40. package/dist/vendor/codeburn/shims/chalk.js +14 -0
  41. package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
  42. package/dist/vendor/codeburn/src/act/backup.js +83 -0
  43. package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
  44. package/dist/vendor/codeburn/src/act/types.js +37 -0
  45. package/dist/vendor/codeburn/src/bash-utils.js +204 -0
  46. package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
  47. package/dist/vendor/codeburn/src/cache-dir.js +26 -0
  48. package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
  49. package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
  50. package/dist/vendor/codeburn/src/classifier.js +209 -0
  51. package/dist/vendor/codeburn/src/claude-identity.js +223 -0
  52. package/dist/vendor/codeburn/src/codex-cache.js +377 -0
  53. package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
  54. package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
  55. package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
  56. package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
  57. package/dist/vendor/codeburn/src/compare-stats.js +405 -0
  58. package/dist/vendor/codeburn/src/config.js +145 -0
  59. package/dist/vendor/codeburn/src/content-utils.js +56 -0
  60. package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
  61. package/dist/vendor/codeburn/src/context-tree.js +664 -0
  62. package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
  63. package/dist/vendor/codeburn/src/currency.js +189 -0
  64. package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
  65. package/dist/vendor/codeburn/src/cursor-import.js +402 -0
  66. package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
  67. package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
  68. package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
  69. package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
  70. package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
  71. package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
  72. package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
  73. package/dist/vendor/codeburn/src/format.js +118 -0
  74. package/dist/vendor/codeburn/src/fs-utils.js +270 -0
  75. package/dist/vendor/codeburn/src/git-origin.js +334 -0
  76. package/dist/vendor/codeburn/src/granular-history.js +328 -0
  77. package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
  78. package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
  79. package/dist/vendor/codeburn/src/live-sessions.js +358 -0
  80. package/dist/vendor/codeburn/src/math-utils.js +8 -0
  81. package/dist/vendor/codeburn/src/menubar-json.js +294 -0
  82. package/dist/vendor/codeburn/src/models.js +1879 -0
  83. package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
  84. package/dist/vendor/codeburn/src/optimize.js +4110 -0
  85. package/dist/vendor/codeburn/src/parse-workers.js +219 -0
  86. package/dist/vendor/codeburn/src/parser.js +6953 -0
  87. package/dist/vendor/codeburn/src/path-privacy.js +26 -0
  88. package/dist/vendor/codeburn/src/plans.js +135 -0
  89. package/dist/vendor/codeburn/src/pr-signals.js +132 -0
  90. package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
  91. package/dist/vendor/codeburn/src/provider-issues.js +30 -0
  92. package/dist/vendor/codeburn/src/providers/amp.js +286 -0
  93. package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
  94. package/dist/vendor/codeburn/src/providers/claude.js +551 -0
  95. package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
  96. package/dist/vendor/codeburn/src/providers/cline.js +63 -0
  97. package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
  98. package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
  99. package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
  100. package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
  101. package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
  102. package/dist/vendor/codeburn/src/providers/crush.js +226 -0
  103. package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
  104. package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
  105. package/dist/vendor/codeburn/src/providers/devin.js +569 -0
  106. package/dist/vendor/codeburn/src/providers/droid.js +324 -0
  107. package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
  108. package/dist/vendor/codeburn/src/providers/forge.js +245 -0
  109. package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
  110. package/dist/vendor/codeburn/src/providers/goose.js +252 -0
  111. package/dist/vendor/codeburn/src/providers/grok.js +581 -0
  112. package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
  113. package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
  114. package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
  115. package/dist/vendor/codeburn/src/providers/index.js +360 -0
  116. package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
  117. package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
  118. package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
  119. package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
  120. package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
  121. package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
  122. package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
  123. package/dist/vendor/codeburn/src/providers/mux.js +242 -0
  124. package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
  125. package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
  126. package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
  127. package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
  128. package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
  129. package/dist/vendor/codeburn/src/providers/pi.js +429 -0
  130. package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
  131. package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
  132. package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
  133. package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
  134. package/dist/vendor/codeburn/src/providers/types.js +5 -0
  135. package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
  136. package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
  137. package/dist/vendor/codeburn/src/providers/warp.js +575 -0
  138. package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
  139. package/dist/vendor/codeburn/src/providers/zed.js +187 -0
  140. package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
  141. package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
  142. package/dist/vendor/codeburn/src/quota/claude.js +244 -0
  143. package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
  144. package/dist/vendor/codeburn/src/quota/security.js +299 -0
  145. package/dist/vendor/codeburn/src/quota/types.js +1 -0
  146. package/dist/vendor/codeburn/src/scan-facts.js +99 -0
  147. package/dist/vendor/codeburn/src/session-cache.js +3040 -0
  148. package/dist/vendor/codeburn/src/session-count-label.js +14 -0
  149. package/dist/vendor/codeburn/src/session-output.js +139 -0
  150. package/dist/vendor/codeburn/src/session-population.js +30 -0
  151. package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
  152. package/dist/vendor/codeburn/src/sqlite.js +528 -0
  153. package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
  154. package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
  155. package/dist/vendor/codeburn/src/token-estimate.js +5 -0
  156. package/dist/vendor/codeburn/src/types.js +16 -0
  157. package/dist/vendor/codeburn/src/work-units.js +126 -0
  158. package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
  159. package/dist/vendor/codeburn/src/wsl.js +198 -0
  160. package/dist/vendor/codeburn/src/yield.js +666 -0
  161. package/package.json +11 -3
@@ -0,0 +1,429 @@
1
+ import os from 'node:os';
2
+ import path from 'node:path';
3
+ import { atomicWriteSecureFileSync, fraction, quotaRequestSignal, readKeychainPassword, readSecureFile, readSecureFileSync, sanitizeError } from './security.js';
4
+ const USAGE_ENDPOINT = 'https://chatgpt.com/backend-api/wham/usage';
5
+ const TOKEN_ENDPOINT = 'https://auth.openai.com/oauth/token';
6
+ const CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann';
7
+ const EIGHT_DAYS = 8 * 24 * 60 * 60_000;
8
+ // The CodeBurn menubar caches its ChatGPT-mode Codex OAuth here as a
9
+ // `CredentialRecord` JSON blob (accessToken/refreshToken/idToken/accountId/…),
10
+ // account "default". Same brand, same machine, already consented and preferred
11
+ // over any OpenAI-owned storage.
12
+ const MENUBAR_KEYCHAIN_SERVICE = 'org.agentseal.codeburn.menubar.codex.oauth.v1';
13
+ const defaults = {
14
+ fetch: globalThis.fetch,
15
+ authPath: path.join(os.homedir(), '.codex', 'auth.json'),
16
+ openaiAuthPath: path.join(os.homedir(), 'Library', 'Application Support', 'com.openai.codex', 'auth.json'),
17
+ readFile: readSecureFile,
18
+ readFileSync: readSecureFileSync,
19
+ writeFileSync: atomicWriteSecureFileSync,
20
+ keychain: service => readKeychainPassword(service, ['default', null]),
21
+ now: Date.now,
22
+ };
23
+ function empty(connection) {
24
+ return { provider: 'codex', connection, primary: null, details: [], planLabel: null, footerLines: [] };
25
+ }
26
+ async function readAuth(deps, filePath = deps.authPath) {
27
+ const raw = await deps.readFile(filePath, 64 * 1024);
28
+ return raw ? JSON.parse(raw) : null;
29
+ }
30
+ // The menubar stores a Swift `CredentialRecord` (camelCase, Date fields as
31
+ // numbers) rather than the CLI's snake_case auth.json. Normalize to AuthDoc and
32
+ // mark it chatgpt-mode (the menubar only ever caches ChatGPT subscriptions).
33
+ function authFromMenubarRecord(raw) {
34
+ let record;
35
+ try {
36
+ record = JSON.parse(raw);
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ const access = typeof record.accessToken === 'string' ? record.accessToken : '';
42
+ if (!access)
43
+ return null;
44
+ return {
45
+ auth_mode: 'chatgpt',
46
+ tokens: {
47
+ access_token: access,
48
+ refresh_token: typeof record.refreshToken === 'string' ? record.refreshToken : undefined,
49
+ id_token: typeof record.idToken === 'string' ? record.idToken : undefined,
50
+ account_id: typeof record.accountId === 'string' ? record.accountId : undefined,
51
+ },
52
+ };
53
+ }
54
+ async function discoverSource(deps, allowKeychain) {
55
+ let denied = false;
56
+ // (a) CodeBurn menubar's own cached Codex OAuth. Read-only: the menubar owns
57
+ // rotation, so we never write it back and never proactively refresh it.
58
+ if (allowKeychain && process.platform === 'darwin') {
59
+ const outcome = await deps.keychain(MENUBAR_KEYCHAIN_SERVICE);
60
+ if (outcome.status === 'accessDenied')
61
+ denied = true;
62
+ else if (outcome.status === 'found') {
63
+ const auth = authFromMenubarRecord(outcome.value);
64
+ if (auth) {
65
+ return {
66
+ name: 'menubarKeychain', auth, writable: false,
67
+ reread: async () => {
68
+ const next = await deps.keychain(MENUBAR_KEYCHAIN_SERVICE);
69
+ return next.status === 'found' ? authFromMenubarRecord(next.value) : null;
70
+ },
71
+ };
72
+ }
73
+ }
74
+ }
75
+ // (b) The Codex CLI's own ~/.codex/auth.json. We own rotation + write-back.
76
+ const fileAuth = await readAuth(deps);
77
+ if (fileAuth)
78
+ return { name: 'authFile', auth: fileAuth, writable: true, reread: () => readAuth(deps) };
79
+ // (c) com.openai.codex App Support, only if it holds a plaintext auth JSON
80
+ // with a usable token. Tokens encrypted via "Codex Safe Storage" have no
81
+ // plaintext access_token here, so they fall through, and we never decrypt.
82
+ const openaiAuth = await readAuth(deps, deps.openaiAuthPath).catch(() => null);
83
+ if (openaiAuth?.tokens?.access_token) {
84
+ return { name: 'openaiAppSupport', auth: openaiAuth, writable: false, reread: () => readAuth(deps, deps.openaiAuthPath).catch(() => null) };
85
+ }
86
+ return denied ? 'accessDenied' : null;
87
+ }
88
+ function labelForSeconds(value) {
89
+ const seconds = typeof value === 'number' ? Math.max(0, Math.trunc(value)) : 0;
90
+ if (seconds < 3600)
91
+ return 'Hourly';
92
+ if (seconds < 7200)
93
+ return 'Hour';
94
+ if (seconds >= 18_000 && seconds < 19_000)
95
+ return '5-hour';
96
+ if (seconds >= 86_400 && seconds < 87_000)
97
+ return 'Daily';
98
+ if (seconds >= 604_800 && seconds < 605_000)
99
+ return 'Weekly';
100
+ const hours = Math.floor(seconds / 3600);
101
+ return hours < 24 ? `${hours}-hour` : `${Math.floor(hours / 24)}-day`;
102
+ }
103
+ function windowOf(value, override) {
104
+ if (!value || typeof value !== 'object')
105
+ return null;
106
+ const row = value;
107
+ const percent = fraction(row.used_percent);
108
+ if (percent === null)
109
+ return null;
110
+ const reset = typeof row.reset_at === 'number' && Number.isFinite(row.reset_at)
111
+ ? new Date(row.reset_at * 1000).toISOString() : null;
112
+ return { label: override ?? labelForSeconds(row.limit_window_seconds), percent, resetsAt: reset };
113
+ }
114
+ // chatgpt.com mixes encodings inside one payload. `Number('')` is 0, not NaN,
115
+ // so blank is rejected or an absent `used` decodes as a confident zero.
116
+ function num(value) {
117
+ if (typeof value === 'string' && !value.trim())
118
+ return null;
119
+ const parsed = typeof value === 'number' ? value : typeof value === 'string' ? Number(value.trim()) : NaN;
120
+ return Number.isFinite(parsed) ? parsed : null;
121
+ }
122
+ // Credit-based-pricing tiers arrive composite (`enterprise_cbp_usage_based`).
123
+ function normalizePlanType(value) {
124
+ return value
125
+ .replace(/[_-]usage[_-]based$/, '')
126
+ .replace(/^self[_-]serve[_-]/, '')
127
+ .replace(/[_-]cbp$/, '')
128
+ .replace(/[_-]cbp[_-]/g, '_');
129
+ }
130
+ function planLabel(value) {
131
+ if (typeof value !== 'string' || !value.trim())
132
+ return null;
133
+ const raw = value.trim();
134
+ const lower = normalizePlanType(raw.toLowerCase());
135
+ const known = {
136
+ guest: 'Guest', free: 'Free', go: 'Go', plus: 'Plus', pro: 'Pro',
137
+ prolite: 'Pro Lite', pro_lite: 'Pro Lite', 'pro-lite': 'Pro Lite',
138
+ free_workspace: 'Free Workspace', team: 'Team', business: 'Business',
139
+ education: 'Education', quorum: 'Quorum', k12: 'K-12', enterprise: 'Enterprise', edu: 'Edu',
140
+ };
141
+ return known[lower] ?? lower.replace(/(^|[_-])\w/g, match => match.replace(/[_-]/, ' ').toUpperCase());
142
+ }
143
+ // The admin-set monthly allowance, the only limit a credit-metered workspace
144
+ // has. `spend_control` is the live position, the others forward-compat. `any`
145
+ // because this walks six optional-chained hops, all validated by `num()`.
146
+ function spendControlWindow(data) {
147
+ // `find`/`num` per alias, not `??`: a non-null garbage value would stop `??`
148
+ // and mask a valid alias further down. Object-shaped garbage still wins the
149
+ // position, matching Swift, which likewise commits to the first that decodes.
150
+ const row = [
151
+ data.spend_control?.individual_limit,
152
+ data.spend_control?.individualLimit,
153
+ data.individual_limit,
154
+ data.individualLimit,
155
+ data.rate_limit?.individual_limit,
156
+ data.rate_limit?.individualLimit,
157
+ ].find(candidate => candidate && typeof candidate === 'object');
158
+ if (!row)
159
+ return null;
160
+ const limit = num(row.limit);
161
+ if (limit === null || limit <= 0)
162
+ return null;
163
+ const remainingPercent = num(row.remaining_percent) ?? num(row.remainingPercent);
164
+ const used = num(row.used);
165
+ const rawPercent = num(row.used_percent) ?? num(row.usedPercent)
166
+ ?? (remainingPercent === null ? null : 100 - remainingPercent)
167
+ ?? (used === null ? null : (used / limit) * 100);
168
+ if (rawPercent === null)
169
+ return null;
170
+ const percent = Math.min(1, Math.max(0, rawPercent / 100));
171
+ const resetRaw = num(row.reset_at) ?? num(row.resets_at) ?? num(row.resetsAt);
172
+ // Past 8.64e15 ms `toISOString()` throws RangeError.
173
+ const resetsAt = resetRaw !== null && resetRaw > 0 && resetRaw * 1000 <= 8.64e15
174
+ ? new Date(resetRaw * 1000).toISOString()
175
+ : null;
176
+ // Unclamped percent, so a 120% draw still reports 12,000 of 10,000.
177
+ const spent = used ?? limit * Math.max(0, rawPercent) / 100;
178
+ const round = (n) => Math.round(n).toLocaleString('en-US');
179
+ const reached = data.spend_control?.reached === true;
180
+ const label = `Monthly usage limit · ${round(spent)} / ${round(limit)} credits`;
181
+ return { label: reached ? `${label} · limit reached` : label, percent, resetsAt };
182
+ }
183
+ export function decodeCodexUsage(body) {
184
+ const data = body && typeof body === 'object' ? body : {};
185
+ const primaryRaw = windowOf(data.rate_limit?.primary_window);
186
+ const secondaryRaw = windowOf(data.rate_limit?.secondary_window);
187
+ const primary = primaryRaw ?? secondaryRaw;
188
+ const details = [];
189
+ if (primaryRaw)
190
+ details.push(primaryRaw);
191
+ if (secondaryRaw && secondaryRaw !== primary)
192
+ details.push(secondaryRaw);
193
+ else if (!primaryRaw && secondaryRaw)
194
+ details.push(secondaryRaw);
195
+ if (Array.isArray(data.additional_rate_limits)) {
196
+ for (const additional of data.additional_rate_limits) {
197
+ if (!additional || typeof additional !== 'object' || typeof additional.limit_name !== 'string')
198
+ continue;
199
+ for (const key of ['primary_window', 'secondary_window']) {
200
+ const raw = additional.rate_limit?.[key];
201
+ const base = windowOf(raw);
202
+ if (base && base.percent > 0)
203
+ details.push({ ...base, label: `${additional.limit_name} · ${base.label}` });
204
+ }
205
+ }
206
+ }
207
+ const credits = spendControlWindow(data);
208
+ if (credits)
209
+ details.push(credits);
210
+ const balance = num(data.credits?.balance);
211
+ // Credit-settled accounts denominate in credits, so no currency symbol.
212
+ const hasCredits = data.credits?.has_credits === true;
213
+ const footerLines = [];
214
+ if (balance !== null && balance > 0) {
215
+ footerLines.push(`Credits remaining · ${hasCredits ? Math.round(balance).toLocaleString('en-US') : balance.toLocaleString('en-US', { style: 'currency', currency: 'USD' })}`);
216
+ }
217
+ // Uncapped on purpose, so a bar-less card does not read as a failed fetch.
218
+ if (!credits && data.credits?.unlimited === true)
219
+ footerLines.push('Credits · Unlimited');
220
+ return {
221
+ provider: 'codex', connection: 'connected', primary: primary ?? credits, details,
222
+ planLabel: planLabel(data.plan_type),
223
+ footerLines,
224
+ };
225
+ }
226
+ function str(value) {
227
+ return typeof value === 'string' && value ? value : null;
228
+ }
229
+ /** The `sub` claim of a JWT id_token, or null when it is absent or does not
230
+ * decode. Defensive at every step: a malformed id_token is evidence of nothing,
231
+ * so it must never itself read as a login mismatch. */
232
+ function idTokenSubject(token) {
233
+ if (typeof token !== 'string')
234
+ return null;
235
+ const payload = token.split('.')[1];
236
+ if (!payload)
237
+ return null;
238
+ try {
239
+ const claims = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
240
+ return typeof claims.sub === 'string' && claims.sub ? claims.sub : null;
241
+ }
242
+ catch {
243
+ return null;
244
+ }
245
+ }
246
+ /** Whether two documents belong to the same Codex login. A field counts as a
247
+ * mismatch only when it is a non-empty string on both sides and the two values
248
+ * differ: a document that merely omits account_id, refresh_token or id_token is
249
+ * not proof of a different login, and treating it as one would drop a rotated
250
+ * refresh token and sign the user out. Taken to its limit that means a document
251
+ * carrying NONE of the three reads as the same login and is written over. That
252
+ * is the deliberate side to err on: the alternative discards a live credential
253
+ * every time the file on disk cannot identify itself. */
254
+ function sameLogin(held, latest) {
255
+ const differs = (a, b) => typeof a === 'string' && a !== '' && typeof b === 'string' && b !== '' && a !== b;
256
+ if (differs(held.tokens?.account_id, latest.tokens?.account_id))
257
+ return false;
258
+ if (differs(held.tokens?.refresh_token, latest.tokens?.refresh_token))
259
+ return false;
260
+ return !differs(idTokenSubject(held.tokens?.id_token), idTokenSubject(latest.tokens?.id_token));
261
+ }
262
+ /** The document the rotated tokens are merged into: whatever the Codex CLI has
263
+ * on disk right now, so a login it wrote since our own read is not clobbered.
264
+ * `null` means writing would be wrong: the login this rotation belongs to is
265
+ * gone (file removed, or no longer ChatGPT mode), or the file now holds a
266
+ * different login (the user ran `codex login` and switched accounts, or another
267
+ * process rotated the credential while our grant was in flight) and merging our
268
+ * tokens in would splice one account's account_id onto another's refresh token.
269
+ * An unreadable or unparseable file is NOT one of those cases: it falls back to
270
+ * the document we already hold, because a lineage check may only fire on a file
271
+ * that reads cleanly, and dropping a rotated refresh token signs the user out. */
272
+ function mergeBase(auth, deps) {
273
+ let raw;
274
+ try {
275
+ raw = deps.readFileSync(deps.authPath);
276
+ }
277
+ catch {
278
+ return auth;
279
+ }
280
+ if (raw === null)
281
+ return null;
282
+ let latest;
283
+ try {
284
+ latest = JSON.parse(raw);
285
+ }
286
+ catch {
287
+ return auth;
288
+ }
289
+ if (!latest || typeof latest !== 'object')
290
+ return auth;
291
+ const doc = latest;
292
+ if (doc.auth_mode !== 'chatgpt')
293
+ return null;
294
+ // Serializing refreshes across processes with a file lock would also stop the
295
+ // wasted double grant, but the lineage check is what closes the corrupt-write
296
+ // hole on its own, so the lock is left out as more than the minimum here.
297
+ return sameLogin(auth, doc) ? doc : null;
298
+ }
299
+ /**
300
+ * Merges the rotated tokens into auth.json and writes them, synchronously and
301
+ * atomically. Synchronous from the moment the token response is parsed to the
302
+ * moment the file is renamed into place: the grant has already invalidated the
303
+ * refresh token on disk, so an abort, a per-provider timeout or the `quota`
304
+ * command's `process.exit` landing in an await here would leave the user with
305
+ * nothing but a dead token, which reads as being signed out of Codex.
306
+ */
307
+ function persistRotated(auth, rotated, deps) {
308
+ const base = mergeBase(auth, deps);
309
+ if (!base) {
310
+ console.error(`Codex refreshed its login but the credential at ${deps.authPath} no longer holds the ChatGPT login this rotation belongs to, so the new token was discarded. Run \`codex login\` if Codex signs you out.`);
311
+ return null;
312
+ }
313
+ const merged = {
314
+ ...base,
315
+ tokens: {
316
+ ...base.tokens,
317
+ ...(rotated.access ? { access_token: rotated.access } : {}),
318
+ ...(rotated.refresh ? { refresh_token: rotated.refresh } : {}),
319
+ ...(rotated.id ? { id_token: rotated.id } : {}),
320
+ },
321
+ last_refresh: new Date(deps.now()).toISOString(),
322
+ };
323
+ try {
324
+ deps.writeFileSync(deps.authPath, `${JSON.stringify(merged, null, 2)}\n`);
325
+ }
326
+ catch (error) {
327
+ // Never silent: the token still on disk is the one the grant just killed,
328
+ // so the user has to be told why Codex will ask them to sign in again.
329
+ console.error(`Codex refresh token rotated but could not be saved to ${deps.authPath}: ${sanitizeError(error)}. Run \`codex login\` if Codex signs you out.`);
330
+ return null;
331
+ }
332
+ return merged;
333
+ }
334
+ async function refresh(auth, deps) {
335
+ const refreshToken = auth.tokens?.refresh_token;
336
+ if (!refreshToken)
337
+ return null;
338
+ // Deliberately not the caller's abort signal, only this request's own
339
+ // timeout: the grant retires the refresh token on disk the moment the
340
+ // endpoint accepts it, so a per-provider timeout firing while the response
341
+ // is still arriving would cancel a rotation we can no longer undo. A slow
342
+ // grant costs the caller nothing, since its own race has already given up.
343
+ const response = await deps.fetch(TOKEN_ENDPOINT, {
344
+ method: 'POST', signal: quotaRequestSignal(),
345
+ headers: { 'Content-Type': 'application/json' },
346
+ body: JSON.stringify({ client_id: CLIENT_ID, grant_type: 'refresh_token', refresh_token: refreshToken, scope: 'openid profile email' }),
347
+ });
348
+ if (!response.ok)
349
+ return null;
350
+ const next = await response.json();
351
+ const rotated = { access: str(next.access_token), refresh: str(next.refresh_token), id: str(next.id_token) };
352
+ // A rotated refresh token is persisted even when the access token is missing
353
+ // or malformed: the grant has already retired the one on disk either way.
354
+ if (!rotated.access && !rotated.refresh)
355
+ return null;
356
+ const merged = persistRotated(auth, rotated, deps);
357
+ return merged?.tokens?.access_token ? merged : null;
358
+ }
359
+ async function usage(auth, deps, signal) {
360
+ const token = auth.tokens?.access_token;
361
+ if (!token)
362
+ return null;
363
+ const headers = { Authorization: `Bearer ${token}`, Accept: 'application/json', 'User-Agent': 'chompyy/0.1 (+https://github.com/BranchWork-HQ/Chompyy)' };
364
+ if (auth.tokens?.account_id)
365
+ headers['ChatGPT-Account-Id'] = auth.tokens.account_id;
366
+ return deps.fetch(USAGE_ENDPOINT, { method: 'GET', headers, signal: quotaRequestSignal(signal) });
367
+ }
368
+ export async function fetchCodexQuota(options = {}) {
369
+ const deps = { ...defaults, ...options };
370
+ try {
371
+ const discovered = await discoverSource(deps, Boolean(options.allowKeychain));
372
+ if (discovered === 'accessDenied')
373
+ return { quota: empty('accessDenied') };
374
+ if (!discovered)
375
+ return { quota: empty('disconnected') };
376
+ const source = discovered;
377
+ let auth = source.auth;
378
+ if (auth.auth_mode !== 'chatgpt')
379
+ return { quota: empty('terminalFailure') };
380
+ if (!auth.tokens?.access_token)
381
+ return { quota: empty('disconnected') };
382
+ // Proactive staleness refresh only for the source whose rotation we own.
383
+ if (source.writable) {
384
+ const refreshedAt = typeof auth.last_refresh === 'string' ? Date.parse(auth.last_refresh) : NaN;
385
+ if (!Number.isFinite(refreshedAt) || deps.now() - refreshedAt > EIGHT_DAYS) {
386
+ const next = await refresh(auth, deps);
387
+ if (next)
388
+ auth = next;
389
+ }
390
+ }
391
+ let response = await usage(auth, deps, options.signal);
392
+ if (!response)
393
+ return { quota: empty('disconnected') };
394
+ if (response.status === 401) {
395
+ const reread = await source.reread();
396
+ if (reread?.tokens?.access_token && reread.tokens.access_token !== auth.tokens?.access_token) {
397
+ auth = reread;
398
+ }
399
+ else if (source.writable) {
400
+ const next = await refresh(reread ?? auth, deps);
401
+ if (!next)
402
+ return { quota: empty('transientFailure') };
403
+ auth = next;
404
+ }
405
+ else {
406
+ // Read-only source: the owner (menubar) rotates tokens on its own
407
+ // cadence, so re-read once and otherwise wait for the next poll.
408
+ return { quota: empty('transientFailure') };
409
+ }
410
+ response = await usage(auth, deps, options.signal);
411
+ if (!response)
412
+ return { quota: empty('transientFailure') };
413
+ }
414
+ if (response.status === 429) {
415
+ const raw = response.headers.get('Retry-After');
416
+ let seconds = raw === null ? NaN : Number(raw);
417
+ if (!Number.isFinite(seconds) && raw)
418
+ seconds = (Date.parse(raw) - deps.now()) / 1000;
419
+ return { quota: empty('transientFailure'), retryAfterSeconds: Math.max(Number.isFinite(seconds) ? Math.ceil(seconds) : 300, 60) };
420
+ }
421
+ if (!response.ok)
422
+ return { quota: { ...empty(response.status >= 400 && response.status < 500 ? 'terminalFailure' : 'transientFailure'), ...(response.status === 401 || response.status === 403 ? { connectable: true } : {}) } };
423
+ return { quota: decodeCodexUsage(await response.json()) };
424
+ }
425
+ catch (error) {
426
+ console.warn(`Codex quota unavailable: ${sanitizeError(error)}`);
427
+ return { quota: empty('transientFailure') };
428
+ }
429
+ }