tokenusage-cli 0.1.0 → 0.2.1

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 (131) hide show
  1. package/CHANGELOG.md +46 -19
  2. package/LICENSE +22 -22
  3. package/README.md +123 -94
  4. package/THIRD_PARTY_NOTICES.md +140 -140
  5. package/bin/tokenusage.js +69 -69
  6. package/package.json +59 -59
  7. package/src/cli.js +146 -134
  8. package/src/commands/device-login.js +205 -205
  9. package/src/commands/diagnostics.js +38 -38
  10. package/src/commands/doctor.js +110 -110
  11. package/src/commands/init.js +2484 -2436
  12. package/src/commands/pause.js +77 -0
  13. package/src/commands/sessions.js +29 -29
  14. package/src/commands/status.js +1758 -1747
  15. package/src/commands/sync.js +8048 -7934
  16. package/src/commands/uninstall.js +322 -312
  17. package/src/lib/account-usage-dedup.js +267 -267
  18. package/src/lib/antigravity-paths.js +48 -48
  19. package/src/lib/ark-agent-plan-limits.js +438 -438
  20. package/src/lib/ark-coding-plan-limits.js +537 -537
  21. package/src/lib/async-queue-reader.js +138 -138
  22. package/src/lib/atomic-json.js +27 -27
  23. package/src/lib/bearer-token.js +11 -11
  24. package/src/lib/categorizer-utils.js +232 -232
  25. package/src/lib/claude-categorizer.js +1343 -1343
  26. package/src/lib/claude-config.js +279 -279
  27. package/src/lib/claude-user-identity.js +56 -56
  28. package/src/lib/cli-ui.js +179 -179
  29. package/src/lib/cloud-account.js +541 -541
  30. package/src/lib/cloud-device-token.js +141 -141
  31. package/src/lib/cloud-sync-prefs.js +14 -14
  32. package/src/lib/cloud-usage-reset.js +115 -115
  33. package/src/lib/codex-config.js +595 -595
  34. package/src/lib/codex-context-breakdown.js +806 -806
  35. package/src/lib/codex-model-attribution.js +128 -128
  36. package/src/lib/codex-rollout-parser.js +1471 -1471
  37. package/src/lib/codex-service-tier.js +49 -49
  38. package/src/lib/codex-token-refresh.js +140 -140
  39. package/src/lib/codex-token-usage.js +195 -195
  40. package/src/lib/codex-usage-record.js +195 -195
  41. package/src/lib/collection-pause.js +77 -0
  42. package/src/lib/command-runner.js +313 -313
  43. package/src/lib/commandcode-limits.js +317 -317
  44. package/src/lib/context-health.js +124 -124
  45. package/src/lib/cursor-config.js +605 -605
  46. package/src/lib/cursor-store.js +1918 -1918
  47. package/src/lib/debug-flags.js +7 -7
  48. package/src/lib/devin-limits.js +249 -249
  49. package/src/lib/devin-usage.js +212 -212
  50. package/src/lib/diagnostics.js +383 -383
  51. package/src/lib/doctor.js +385 -385
  52. package/src/lib/dumate.js +95 -95
  53. package/src/lib/fs.js +455 -455
  54. package/src/lib/function-url.js +14 -14
  55. package/src/lib/gemini-config.js +291 -291
  56. package/src/lib/git-outcomes.js +243 -243
  57. package/src/lib/grok-context-breakdown.js +890 -890
  58. package/src/lib/grok-hook.js +360 -360
  59. package/src/lib/grok-limits.js +865 -865
  60. package/src/lib/grok-usage.js +98 -98
  61. package/src/lib/heatmap-compact.js +114 -114
  62. package/src/lib/ingest-sanitize.js +41 -41
  63. package/src/lib/init-flow.js +42 -42
  64. package/src/lib/install-resolver.js +170 -170
  65. package/src/lib/jsonl-lines.js +134 -134
  66. package/src/lib/kimi-model-repair.js +173 -173
  67. package/src/lib/kimi-profile.js +61 -61
  68. package/src/lib/kimi-session.js +216 -216
  69. package/src/lib/local-api.js +3588 -3588
  70. package/src/lib/machine-id.js +238 -238
  71. package/src/lib/multi-install-parser.js +113 -113
  72. package/src/lib/notify-command.js +38 -38
  73. package/src/lib/omp-hook.js +589 -589
  74. package/src/lib/openclaw-cli.js +104 -104
  75. package/src/lib/openclaw-hook.js +375 -375
  76. package/src/lib/openclaw-session-plugin.js +560 -560
  77. package/src/lib/opencode-config.js +121 -121
  78. package/src/lib/opencode-go-limits.js +807 -807
  79. package/src/lib/outcomes-engine.js +253 -253
  80. package/src/lib/passive-mode.js +219 -219
  81. package/src/lib/pet-packages.js +722 -722
  82. package/src/lib/pricing/curated-overrides.json +822 -822
  83. package/src/lib/pricing/index.js +379 -379
  84. package/src/lib/pricing/litellm-fetcher.js +172 -172
  85. package/src/lib/pricing/matcher.js +456 -456
  86. package/src/lib/pricing/seed-snapshot.json +1 -1
  87. package/src/lib/progress.js +76 -76
  88. package/src/lib/project-usage-purge.js +117 -117
  89. package/src/lib/prompt.js +24 -24
  90. package/src/lib/provider-status.js +104 -104
  91. package/src/lib/proxy-env.js +489 -489
  92. package/src/lib/proxy-settings.js +163 -163
  93. package/src/lib/qoder-cn-cli-limits.js +119 -119
  94. package/src/lib/qoder-limits.js +880 -880
  95. package/src/lib/quiet-warnings.js +26 -26
  96. package/src/lib/rollout.js +26005 -25966
  97. package/src/lib/runtime-config.js +9 -4
  98. package/src/lib/scan-roots.js +277 -277
  99. package/src/lib/scheduled-task.js +145 -0
  100. package/src/lib/sentry.js +231 -231
  101. package/src/lib/session-analytics.js +2972 -2972
  102. package/src/lib/session-performance.js +237 -237
  103. package/src/lib/session-upload.js +379 -379
  104. package/src/lib/skill-usage.js +267 -267
  105. package/src/lib/skills-manager.js +1591 -1591
  106. package/src/lib/source-metadata.js +48 -48
  107. package/src/lib/sqlite-reader.js +215 -215
  108. package/src/lib/star-cta.js +73 -73
  109. package/src/lib/subscription-manager.js +293 -293
  110. package/src/lib/subscriptions.js +508 -508
  111. package/src/lib/sync-report.js +138 -0
  112. package/src/lib/telemetry.js +193 -193
  113. package/src/lib/tracker-paths.js +16 -16
  114. package/src/lib/trae-cn-config.js +548 -548
  115. package/src/lib/trae-db.js +127 -127
  116. package/src/lib/trae-snapshot.js +230 -230
  117. package/src/lib/trae-sqlite.js +143 -143
  118. package/src/lib/trae-usage.js +121 -121
  119. package/src/lib/upload-queue.js +134 -134
  120. package/src/lib/upload-throttle.js +171 -171
  121. package/src/lib/usage-limits.js +4552 -4552
  122. package/src/lib/wrapped-aggregator.js +236 -236
  123. package/src/lib/wsl-probe.js +281 -281
  124. package/src/lib/zcode-limits.js +1172 -1172
  125. package/src/lib/zcode-reset-credits.js +66 -66
  126. package/test/audit-fixes.test.js +200 -0
  127. package/test/cli-smoke.test.js +53 -53
  128. package/test/collection-controls.test.js +210 -0
  129. package/test/ingest-sanitize.test.js +162 -162
  130. package/test/quiet-warnings.test.js +53 -53
  131. package/test/session-upload.test.js +427 -427
@@ -1,865 +1,865 @@
1
- const fs = require("node:fs");
2
- const os = require("node:os");
3
- const path = require("node:path");
4
-
5
- const DEFAULT_BILLING_BASE_URL = "https://cli-chat-proxy.grok.com";
6
- const DEFAULT_BILLING_TIMEOUT_MS = 15_000;
7
- const DEFAULT_SETTINGS_TIMEOUT_MS = 2_000;
8
- const DEFAULT_OIDC_ISSUER = "https://auth.x.ai";
9
- const DEFAULT_TOKEN_ENDPOINT = "https://auth.x.ai/oauth2/token";
10
- // Refresh slightly before wall-clock expiry so Limits doesn't race a just-expired JWT.
11
- const ACCESS_TOKEN_EXPIRY_SKEW_MS = 60_000;
12
-
13
- function grokAuthError() {
14
- const error = new Error("Not logged in to Grok Build. Run `grok login` in Terminal to authenticate.");
15
- error.code = "GROK_AUTH_REQUIRED";
16
- return error;
17
- }
18
-
19
- function grokReauthError() {
20
- const error = new Error(
21
- "Grok session expired. Run `grok login` in Terminal to re-authenticate.",
22
- );
23
- error.code = "GROK_REAUTH_REQUIRED";
24
- return error;
25
- }
26
-
27
- function grokBillingTimeoutError() {
28
- const error = new Error("Grok billing request timed out.");
29
- error.code = "GROK_BILLING_TIMEOUT";
30
- return error;
31
- }
32
-
33
- async function runBeforeBillingDeadline(operation, deadlineMs) {
34
- const remainingMs = Math.ceil(deadlineMs - Date.now());
35
- if (remainingMs <= 0) throw grokBillingTimeoutError();
36
-
37
- const controller = new AbortController();
38
- let timer;
39
- const timeout = new Promise((_, reject) => {
40
- timer = setTimeout(() => {
41
- const error = grokBillingTimeoutError();
42
- controller.abort(error);
43
- reject(error);
44
- }, remainingMs);
45
- });
46
-
47
- try {
48
- return await Promise.race([operation(controller.signal), timeout]);
49
- } finally {
50
- clearTimeout(timer);
51
- }
52
- }
53
-
54
- async function fetchGrokBillingAttempt(fetchImpl, url, headers, deadlineMs) {
55
- return runBeforeBillingDeadline(async (signal) => {
56
- const response = await fetchImpl(url, { method: "GET", headers, signal });
57
- if (!response.ok) {
58
- try {
59
- await response.body?.cancel?.();
60
- } catch (_error) {
61
- // The status remains authoritative even if discarding the body fails.
62
- }
63
- if (response.status === 401 || response.status === 403) throw grokAuthError();
64
- return { ok: false, status: response.status };
65
- }
66
- return { ok: true, body: await response.json() };
67
- }, deadlineMs);
68
- }
69
-
70
- function resolveGrokHome({ home, env = process.env } = {}) {
71
- if (typeof env.TOKENUSAGE_GROK_HOME === "string" && env.TOKENUSAGE_GROK_HOME.trim()) {
72
- return path.resolve(env.TOKENUSAGE_GROK_HOME.trim());
73
- }
74
- if (typeof env.GROK_HOME === "string" && env.GROK_HOME.trim()) {
75
- return path.resolve(env.GROK_HOME.trim());
76
- }
77
- return path.join(home || os.homedir(), ".grok");
78
- }
79
-
80
- function resolveGrokBillingBaseUrl(env = process.env) {
81
- const explicit =
82
- typeof env.GROK_CLI_CHAT_PROXY_BASE_URL === "string"
83
- ? env.GROK_CLI_CHAT_PROXY_BASE_URL.trim()
84
- : typeof env.TOKENUSAGE_GROK_BILLING_BASE_URL === "string"
85
- ? env.TOKENUSAGE_GROK_BILLING_BASE_URL.trim()
86
- : "";
87
- if (explicit) return explicit.replace(/\/$/, "");
88
- return DEFAULT_BILLING_BASE_URL;
89
- }
90
-
91
- function grokValNumber(value) {
92
- if (value == null) return null;
93
- if (typeof value === "object" && "val" in value) {
94
- return grokValNumber(value.val);
95
- }
96
- const n = Number(value);
97
- return Number.isFinite(n) ? n : null;
98
- }
99
-
100
- function grokIsoReset(value) {
101
- if (typeof value !== "string" || !value.trim()) return null;
102
- const ts = Date.parse(value.trim());
103
- return Number.isFinite(ts) && ts > 0 ? new Date(ts).toISOString() : null;
104
- }
105
-
106
- function clampPercent(value) {
107
- if (value === null || value === undefined || value === "") return null;
108
- const n = Number(value);
109
- if (!Number.isFinite(n)) return null;
110
- if (n <= 0) return 0;
111
- if (n >= 100) return 100;
112
- return n;
113
- }
114
-
115
- function buildWindow({ usedPercent, resetAt }) {
116
- const pct = clampPercent(usedPercent);
117
- if (pct === null) return null;
118
- return {
119
- used_percent: pct,
120
- reset_at: typeof resetAt === "string" && resetAt ? resetAt : null,
121
- };
122
- }
123
-
124
- /**
125
- * Map Grok's USAGE_PERIOD_TYPE_* enum (or a bare "weekly"/"monthly" string)
126
- * into a short period key the UI can switch labels on.
127
- *
128
- * Only daily / weekly / monthly are recognized end-to-end (dashboard + macOS).
129
- * Hourly (and other unknown) types return null so UIs fall back to the generic
130
- * Month label rather than inventing an unsupported period key.
131
- */
132
- function normalizeGrokPeriodType(value) {
133
- if (typeof value !== "string" || !value.trim()) return null;
134
- const upper = value.trim().toUpperCase();
135
- if (upper.includes("WEEK")) return "weekly";
136
- if (upper.includes("MONTH")) return "monthly";
137
- // Prefer explicit DAILY / DAY over accidental "HOUR_OF_DAY" style matches.
138
- if (upper.includes("DAILY") || /(^|_)DAY($|_)/.test(upper) || upper === "DAY") return "daily";
139
- return null;
140
- }
141
-
142
- /**
143
- * Infer daily / weekly / monthly from period length when the API omits
144
- * `currentPeriod.type` (legacy payloads only expose start/end dates).
145
- *
146
- * Windows used by Grok today: ~1d, ~7d, ~calendar month. Boundaries leave
147
- * gaps for odd lengths (e.g. 12d, 2h) so we do not mislabel them.
148
- */
149
- function inferGrokPeriodTypeFromDates(startIso, endIso) {
150
- if (!startIso || !endIso) return null;
151
- const startMs = Date.parse(startIso);
152
- const endMs = Date.parse(endIso);
153
- if (!Number.isFinite(startMs) || !Number.isFinite(endMs) || endMs <= startMs) return null;
154
- const days = (endMs - startMs) / 86_400_000;
155
- if (days > 0.5 && days <= 1.5) return "daily";
156
- if (days > 1.5 && days <= 8) return "weekly";
157
- if (days >= 25 && days <= 35) return "monthly";
158
- return null;
159
- }
160
-
161
- /**
162
- * Sum per-product attribution percentages into the shared pool total.
163
- * productUsage breaks down the same cap (GrokBuild + GrokChat + …), not
164
- * independent quotas — a single product entry undercounts the pool.
165
- */
166
- function sumProductUsagePercent(productUsage) {
167
- if (!Array.isArray(productUsage)) return null;
168
- let sum = 0;
169
- let sawAny = false;
170
- for (const entry of productUsage) {
171
- if (!entry || typeof entry !== "object") continue;
172
- const pct = clampPercent(entry.usagePercent);
173
- if (pct === null) continue;
174
- sawAny = true;
175
- sum += pct;
176
- }
177
- return sawAny ? clampPercent(sum) : null;
178
- }
179
-
180
- function isGrokInstalled({ home, env } = {}) {
181
- const grokHome = resolveGrokHome({ home, env });
182
- const authPath = path.join(grokHome, "auth.json");
183
- if (fs.existsSync(authPath)) return true;
184
- return fs.existsSync(path.join(grokHome, "sessions"));
185
- }
186
-
187
- function loadGrokAuthEntry({ home, env } = {}) {
188
- const authPath = path.join(resolveGrokHome({ home, env }), "auth.json");
189
- if (!fs.existsSync(authPath)) return null;
190
- let fallback = null;
191
- try {
192
- const parsed = JSON.parse(fs.readFileSync(authPath, "utf8"));
193
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
194
- for (const [scopeKey, value] of Object.entries(parsed)) {
195
- if (!value || typeof value !== "object" || Array.isArray(value)) continue;
196
- const key = typeof value.key === "string" ? value.key.trim() : "";
197
- const refreshToken =
198
- typeof value.refresh_token === "string" ? value.refresh_token.trim() : "";
199
- // Entries with an access token win outright. A refresh-token-only entry
200
- // is only usable when a client id is resolvable, and must not shadow a
201
- // later keyed entry — keep it as a fallback instead.
202
- if (key) {
203
- return { entry: value, authPath, scopeKey, authFile: parsed };
204
- }
205
- if (refreshToken && !fallback && resolveGrokOidcClientId(value, scopeKey)) {
206
- fallback = { entry: value, authPath, scopeKey, authFile: parsed };
207
- }
208
- }
209
- } catch (_error) {
210
- return null;
211
- }
212
- return fallback;
213
- }
214
-
215
- function readGrokAccessToken({ home, env } = {}) {
216
- const loaded = loadGrokAuthEntry({ home, env });
217
- const key = typeof loaded?.entry?.key === "string" ? loaded.entry.key.trim() : "";
218
- return key || null;
219
- }
220
-
221
- function isGrokAccessTokenExpired(expiresAt, nowMs = Date.now(), skewMs = ACCESS_TOKEN_EXPIRY_SKEW_MS) {
222
- if (expiresAt == null || expiresAt === "") return false;
223
- const ts = typeof expiresAt === "number" ? expiresAt : Date.parse(String(expiresAt));
224
- if (!Number.isFinite(ts)) return false;
225
- const skew = Number.isFinite(skewMs) && skewMs >= 0 ? skewMs : ACCESS_TOKEN_EXPIRY_SKEW_MS;
226
- return ts <= nowMs + skew;
227
- }
228
-
229
- function resolveGrokOidcClientId(entry, scopeKey) {
230
- if (entry && typeof entry.oidc_client_id === "string" && entry.oidc_client_id.trim()) {
231
- return entry.oidc_client_id.trim();
232
- }
233
- if (typeof scopeKey === "string" && scopeKey.includes("::")) {
234
- const suffix = scopeKey.slice(scopeKey.lastIndexOf("::") + 2).trim();
235
- if (suffix) return suffix;
236
- }
237
- return null;
238
- }
239
-
240
- function resolveGrokOidcIssuer(entry) {
241
- if (entry && typeof entry.oidc_issuer === "string" && entry.oidc_issuer.trim()) {
242
- return entry.oidc_issuer.trim().replace(/\/$/, "");
243
- }
244
- return DEFAULT_OIDC_ISSUER;
245
- }
246
-
247
- function resolveGrokTokenEndpoint(entry, env = process.env) {
248
- if (typeof env.TOKENUSAGE_GROK_TOKEN_ENDPOINT === "string" && env.TOKENUSAGE_GROK_TOKEN_ENDPOINT.trim()) {
249
- return env.TOKENUSAGE_GROK_TOKEN_ENDPOINT.trim();
250
- }
251
- if (typeof env.GROK_OIDC_TOKEN_ENDPOINT === "string" && env.GROK_OIDC_TOKEN_ENDPOINT.trim()) {
252
- return env.GROK_OIDC_TOKEN_ENDPOINT.trim();
253
- }
254
- const issuer = resolveGrokOidcIssuer(entry);
255
- if (issuer === DEFAULT_OIDC_ISSUER) return DEFAULT_TOKEN_ENDPOINT;
256
- return `${issuer}/oauth2/token`;
257
- }
258
-
259
- function grokEntryRefreshToken(entry) {
260
- return entry && typeof entry.refresh_token === "string" ? entry.refresh_token.trim() : "";
261
- }
262
-
263
- function grokEntryAccessToken(entry) {
264
- return entry && typeof entry.key === "string" ? entry.key.trim() : "";
265
- }
266
-
267
- /**
268
- * Public xAI OIDC client refresh (auth method "none").
269
- * Matches Grok Build CLI's refresh against https://auth.x.ai/oauth2/token.
270
- */
271
- async function refreshGrokTokens({
272
- refreshToken,
273
- clientId,
274
- tokenEndpoint = DEFAULT_TOKEN_ENDPOINT,
275
- fetchImpl = fetch,
276
- timeoutMs = DEFAULT_BILLING_TIMEOUT_MS,
277
- } = {}) {
278
- if (typeof refreshToken !== "string" || !refreshToken.trim()) {
279
- const err = new Error("Grok refresh skipped: no refresh_token in auth.json");
280
- err.code = "NO_REFRESH_TOKEN";
281
- throw err;
282
- }
283
- if (typeof clientId !== "string" || !clientId.trim()) {
284
- const err = new Error("Grok refresh skipped: missing oidc_client_id");
285
- err.code = "NO_CLIENT_ID";
286
- throw err;
287
- }
288
-
289
- const body = new URLSearchParams({
290
- grant_type: "refresh_token",
291
- refresh_token: refreshToken.trim(),
292
- client_id: clientId.trim(),
293
- });
294
-
295
- // Same abort deadline discipline as fetchGrokBilling — a stalled token
296
- // endpoint must not block fetchGrokLimits (and its poller) indefinitely.
297
- // The timer stays armed through the body reads below, not just the headers.
298
- const normalizedTimeoutMs =
299
- Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : DEFAULT_BILLING_TIMEOUT_MS;
300
- const controller = new AbortController();
301
- const timeoutError = new Error("Grok token refresh timed out.");
302
- timeoutError.code = "GROK_REFRESH_TIMEOUT";
303
- const timer = setTimeout(() => controller.abort(timeoutError), normalizedTimeoutMs);
304
-
305
- try {
306
- const res = await fetchImpl(tokenEndpoint, {
307
- method: "POST",
308
- headers: {
309
- "Content-Type": "application/x-www-form-urlencoded",
310
- Accept: "application/json",
311
- },
312
- body: body.toString(),
313
- signal: controller.signal,
314
- });
315
-
316
- if (res.status === 400 || res.status === 401) {
317
- let oauthError = null;
318
- try {
319
- const payload = await res.json();
320
- oauthError =
321
- (typeof payload?.error === "string" && payload.error) ||
322
- (payload?.error && typeof payload.error === "object" && payload.error.code) ||
323
- null;
324
- } catch (_error) {
325
- // Status remains authoritative.
326
- }
327
- const err = grokReauthError();
328
- err.oauthError = oauthError;
329
- err.status = res.status;
330
- throw err;
331
- }
332
-
333
- if (!res.ok) {
334
- const err = new Error(`Grok token refresh failed: HTTP ${res.status}`);
335
- err.code = "REFRESH_HTTP_ERROR";
336
- err.status = res.status;
337
- throw err;
338
- }
339
-
340
- const payload = await res.json();
341
- const accessToken =
342
- typeof payload?.access_token === "string" ? payload.access_token.trim() : "";
343
- if (!accessToken) {
344
- const err = new Error("Grok token refresh response missing access_token");
345
- err.code = "REFRESH_INVALID_RESPONSE";
346
- throw err;
347
- }
348
-
349
- const nextRefresh =
350
- typeof payload?.refresh_token === "string" && payload.refresh_token.trim()
351
- ? payload.refresh_token.trim()
352
- : refreshToken.trim();
353
-
354
- let expiresAt = null;
355
- const expiresIn = Number(payload?.expires_in);
356
- if (Number.isFinite(expiresIn) && expiresIn > 0) {
357
- expiresAt = new Date(Date.now() + expiresIn * 1000).toISOString();
358
- } else if (typeof payload?.expires_at === "string" && payload.expires_at.trim()) {
359
- const parsed = Date.parse(payload.expires_at.trim());
360
- if (Number.isFinite(parsed)) expiresAt = new Date(parsed).toISOString();
361
- }
362
-
363
- return {
364
- access_token: accessToken,
365
- refresh_token: nextRefresh,
366
- expires_at: expiresAt,
367
- token_type: typeof payload?.token_type === "string" ? payload.token_type : null,
368
- };
369
- } catch (error) {
370
- if (controller.signal.aborted && controller.signal.reason === timeoutError) {
371
- throw timeoutError;
372
- }
373
- throw error;
374
- } finally {
375
- clearTimeout(timer);
376
- }
377
- }
378
-
379
- async function persistGrokRefreshedAuth(authPath, authFile, scopeKey, entry, newTokens) {
380
- if (!authPath || !scopeKey || !entry || !newTokens?.access_token) {
381
- throw new Error("Grok auth persist requires auth path, scope, entry, and access_token");
382
- }
383
- const nextEntry = {
384
- ...entry,
385
- key: newTokens.access_token,
386
- refresh_token: newTokens.refresh_token || entry.refresh_token,
387
- };
388
- if (newTokens.expires_at) {
389
- nextEntry.expires_at = newTokens.expires_at;
390
- } else {
391
- // Unknown new lifetime: drop the stale timestamp, otherwise the next poll
392
- // sees an already-expired expires_at next to a fresh key and refreshes
393
- // again on every cycle (burning a rotation each time).
394
- delete nextEntry.expires_at;
395
- }
396
- const merged = {
397
- ...authFile,
398
- [scopeKey]: nextEntry,
399
- };
400
- const tmp = `${authPath}.tmp.${process.pid}.${Date.now()}`;
401
- try {
402
- await fs.promises.writeFile(tmp, `${JSON.stringify(merged, null, 2)}\n`, { mode: 0o600 });
403
- await fs.promises.rename(tmp, authPath);
404
- } catch (error) {
405
- // Never leave a tmp file holding fresh tokens behind.
406
- await fs.promises.rm(tmp, { force: true }).catch(() => {});
407
- throw error;
408
- }
409
- try {
410
- await fs.promises.chmod(authPath, 0o600);
411
- } catch (_error) {
412
- // Best-effort; some filesystems reject chmod on rename targets.
413
- }
414
- return { entry: nextEntry, authFile: merged, authPath, scopeKey };
415
- }
416
-
417
- /**
418
- * Return a usable access token, refreshing via OIDC when expired or forced.
419
- * Does not throw for missing install; throws GROK_REAUTH_REQUIRED when refresh is rejected.
420
- */
421
- async function resolveGrokAccessToken({
422
- home,
423
- env = process.env,
424
- fetchImpl = fetch,
425
- forceRefresh = false,
426
- nowMs = Date.now(),
427
- } = {}) {
428
- const loaded = loadGrokAuthEntry({ home, env });
429
- if (!loaded) {
430
- return {
431
- accessToken: null,
432
- configured: false,
433
- canRefresh: false,
434
- refreshed: false,
435
- };
436
- }
437
-
438
- const accessToken = grokEntryAccessToken(loaded.entry);
439
- const refreshToken = grokEntryRefreshToken(loaded.entry);
440
- const expired = isGrokAccessTokenExpired(loaded.entry.expires_at, nowMs);
441
- const canRefresh = Boolean(refreshToken && resolveGrokOidcClientId(loaded.entry, loaded.scopeKey));
442
- const needsRefresh = forceRefresh || !accessToken || expired;
443
-
444
- if (!needsRefresh) {
445
- return {
446
- accessToken,
447
- configured: true,
448
- canRefresh,
449
- refreshed: false,
450
- loaded,
451
- };
452
- }
453
-
454
- if (!canRefresh) {
455
- if (accessToken) {
456
- // Stale key still present — let billing decide (may 401).
457
- return {
458
- accessToken,
459
- configured: true,
460
- canRefresh: false,
461
- refreshed: false,
462
- loaded,
463
- };
464
- }
465
- return {
466
- accessToken: null,
467
- configured: true,
468
- canRefresh: false,
469
- refreshed: false,
470
- loaded,
471
- error: grokAuthError(),
472
- };
473
- }
474
-
475
- const clientId = resolveGrokOidcClientId(loaded.entry, loaded.scopeKey);
476
- const tokens = await refreshGrokTokens({
477
- refreshToken,
478
- clientId,
479
- tokenEndpoint: resolveGrokTokenEndpoint(loaded.entry, env),
480
- fetchImpl,
481
- });
482
- const persisted = await persistGrokRefreshedAuth(
483
- loaded.authPath,
484
- loaded.authFile,
485
- loaded.scopeKey,
486
- loaded.entry,
487
- tokens,
488
- );
489
-
490
- return {
491
- accessToken: tokens.access_token,
492
- configured: true,
493
- canRefresh: true,
494
- refreshed: true,
495
- loaded: persisted,
496
- };
497
- }
498
-
499
- // Grok Build enriches billing with a display tier from remote settings. The
500
- // billing HTTP response itself may contain only `config`.
501
- const GROK_PLAN_TIERS = new Map([
502
- ["supergrokheavy", "SuperGrok Heavy"],
503
- ["supergrokplus", "SuperGrok Plus"],
504
- ["supergroklite", "SuperGrok Lite"],
505
- ["supergrok", "SuperGrok"],
506
- ["xpremiumplus", "X Premium+"],
507
- ["premiumplus", "X Premium+"],
508
- ["xpremium", "X Premium+"],
509
- ["apikey", "API Key"],
510
- ["free", "Free"],
511
- ]);
512
-
513
- /**
514
- * Map xAI's subscription tier to the name its own UI shows.
515
- *
516
- * Separators are folded away before matching so the same table covers whichever
517
- * casing the API returns ("SuperGrok Heavy", "SUPER_GROK_HEAVY", "superGrokHeavy").
518
- * Unknown values return null rather than being passed through: the Limits panel
519
- * falls back to the bare brand name, which is better than rendering a raw enum
520
- * (issue #130 shipped "Kimi Type_event" that way).
521
- */
522
- function deriveGrokPlanLabel(rawTier) {
523
- if (rawTier == null) return null;
524
- const key = String(rawTier).toLowerCase().replace(/[^a-z0-9]+/g, "");
525
- if (!key) return null;
526
- // Exact match only. Prefix matching would read an unseen tier such as
527
- // "SuperGrok Business" as plain "SuperGrok", and a confidently wrong plan on
528
- // the card is worse than no plan at all.
529
- return GROK_PLAN_TIERS.get(key) ?? null;
530
- }
531
-
532
- // Billing product ids → the name grok.com shows in the usage legend.
533
- // Unknown ids are humanized below so a new product still gets a row.
534
- const GROK_PRODUCT_LABELS = new Map([
535
- ["GrokBuild", "Grok Build"],
536
- ["GrokBot", "Grok Bot"],
537
- ["GrokChat", "Chat"],
538
- ["GrokImagine", "Imagine"],
539
- ["Cursor", "Cursor"],
540
- ]);
541
-
542
- function normalizeGrokProductId(value) {
543
- if (typeof value !== "string") return null;
544
- const id = value.trim();
545
- if (!/^[A-Za-z][A-Za-z0-9]{0,31}$/.test(id)) return null;
546
- return id;
547
- }
548
-
549
- function humanizeGrokProductId(productId) {
550
- const spaced = productId
551
- .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
552
- .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
553
- .replace(/[_-]+/g, " ")
554
- .replace(/\s+/g, " ")
555
- .trim();
556
- return spaced.slice(0, 40) || null;
557
- }
558
-
559
- /**
560
- * Per-product shares of the same pool as creditUsagePercent.
561
- * A 12% Grok Bot row is 12 points of the weekly cap, not its own 100% quota.
562
- * Zero and non-finite rows are omitted (grok.com hides unused products).
563
- * API order is preserved; a repeated product id keeps the first finite row.
564
- */
565
- function normalizeGrokProductUsage(productUsage, resetAt) {
566
- if (!Array.isArray(productUsage)) return [];
567
- const seen = new Set();
568
- const products = [];
569
- for (const entry of productUsage) {
570
- if (!entry || typeof entry !== "object") continue;
571
- const product = normalizeGrokProductId(entry.product);
572
- if (!product || seen.has(product)) continue;
573
- const raw = Number(entry.usagePercent);
574
- if (!Number.isFinite(raw) || raw <= 0) continue;
575
- const window = buildWindow({ usedPercent: raw, resetAt });
576
- if (!window || !(window.used_percent > 0)) continue;
577
- const label = GROK_PRODUCT_LABELS.get(product) || humanizeGrokProductId(product);
578
- if (!label) continue;
579
- seen.add(product);
580
- products.push({ product, label, window });
581
- }
582
- return products;
583
- }
584
-
585
- /**
586
- * Parse either:
587
- * - Unified billing (`?format=credits`): weekly/monthly period + creditUsagePercent
588
- * - Legacy monthly credits: monthlyLimit / used + calendar-month billingPeriod*
589
- *
590
- * Prefer the unified shape; legacy remains as a fallback for older accounts.
591
- */
592
- function normalizeGrokBillingResponse(body) {
593
- const config = body?.config;
594
- if (!config || typeof config !== "object") {
595
- throw new Error("Could not parse Grok billing: missing config");
596
- }
597
-
598
- const currentPeriod =
599
- config.currentPeriod && typeof config.currentPeriod === "object" ? config.currentPeriod : null;
600
-
601
- const periodStart =
602
- grokIsoReset(currentPeriod?.start) || grokIsoReset(config.billingPeriodStart);
603
- const resetAt = grokIsoReset(currentPeriod?.end) || grokIsoReset(config.billingPeriodEnd);
604
-
605
- let periodType = normalizeGrokPeriodType(currentPeriod?.type);
606
- if (!periodType) {
607
- periodType = inferGrokPeriodTypeFromDates(periodStart, resetAt);
608
- }
609
-
610
- // Unified billing: overall pool percent is what gates "You hit your weekly limit".
611
- // productUsage is attribution across products that share the same pool — sum it.
612
- let usedPercent = clampPercent(config.creditUsagePercent);
613
- if (usedPercent === null) {
614
- usedPercent = sumProductUsagePercent(config.productUsage);
615
- }
616
-
617
- // Legacy monthly credit counters (pre-unified / non-format=credits responses).
618
- const monthlyLimit = grokValNumber(config.monthlyLimit);
619
- const used = grokValNumber(config.used);
620
- if (usedPercent === null && Number.isFinite(monthlyLimit) && monthlyLimit > 0 && Number.isFinite(used)) {
621
- usedPercent = (used / monthlyLimit) * 100;
622
- if (!periodType) periodType = "monthly";
623
- }
624
-
625
- // Unified billing omits creditUsagePercent (and productUsage) entirely when
626
- // nothing was used this period. A valid currentPeriod window with the usage
627
- // fields absent means 0%, not an unparseable response. Present-but-malformed
628
- // fields still fall through to the parse error below.
629
- if (
630
- usedPercent === null &&
631
- currentPeriod &&
632
- (periodStart || resetAt) &&
633
- config.creditUsagePercent === undefined &&
634
- config.productUsage === undefined
635
- ) {
636
- usedPercent = 0;
637
- }
638
-
639
- const onDemandCap = grokValNumber(config.onDemandCap);
640
- const onDemandUsed = grokValNumber(config.onDemandUsed);
641
-
642
- const primaryWindow = buildWindow({ usedPercent, resetAt });
643
-
644
- let secondaryWindow = null;
645
- if (Number.isFinite(onDemandCap) && onDemandCap > 0 && Number.isFinite(onDemandUsed)) {
646
- secondaryWindow = buildWindow({
647
- usedPercent: (onDemandUsed / onDemandCap) * 100,
648
- resetAt,
649
- });
650
- }
651
-
652
- if (!primaryWindow && !secondaryWindow) {
653
- throw new Error("Could not parse Grok billing: no quota windows in response");
654
- }
655
-
656
- return {
657
- // Read from the response root, not from `config`.
658
- plan_label: deriveGrokPlanLabel(body?.subscriptionTier),
659
- period_type: periodType,
660
- monthly_credits_limit: monthlyLimit,
661
- monthly_credits_used: used,
662
- // Effective percent used for the primary bar (API creditUsagePercent, or
663
- // productUsage / legacy monthly counters when the raw field is absent).
664
- credit_usage_percent: usedPercent == null ? null : clampPercent(usedPercent),
665
- on_demand_cap: onDemandCap,
666
- on_demand_used: onDemandUsed,
667
- billing_period_start: periodStart,
668
- primary_window: primaryWindow,
669
- secondary_window: secondaryWindow,
670
- // Shares of primary_window. Do not add these on top of credit_usage_percent.
671
- products: normalizeGrokProductUsage(config.productUsage, resetAt),
672
- };
673
- }
674
-
675
- /**
676
- * Fetch Grok billing. Prefer `?format=credits` (unified weekly/monthly pool
677
- * used by the Grok Build TUI). Fall back to the bare `/v1/billing` payload for
678
- * older accounts that only expose monthlyLimit/used.
679
- */
680
- async function fetchGrokBilling(
681
- accessToken,
682
- { fetchImpl = fetch, baseUrl, env, timeoutMs = DEFAULT_BILLING_TIMEOUT_MS } = {},
683
- ) {
684
- const root = (baseUrl || resolveGrokBillingBaseUrl(env)).replace(/\/$/, "");
685
- const headers = {
686
- Authorization: `Bearer ${accessToken}`,
687
- Accept: "application/json",
688
- };
689
- const normalizedTimeoutMs =
690
- Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : DEFAULT_BILLING_TIMEOUT_MS;
691
- const deadlineMs = Date.now() + normalizedTimeoutMs;
692
-
693
- const creditsUrl = `${root}/v1/billing?format=credits`;
694
- let creditsFailure = "request failed";
695
- try {
696
- const creditsResult = await fetchGrokBillingAttempt(
697
- fetchImpl,
698
- creditsUrl,
699
- headers,
700
- deadlineMs,
701
- );
702
- if (creditsResult.ok) {
703
- // Keep the unified pool even when its fields are malformed. The caller
704
- // must surface its parse error rather than substitute a legacy pool.
705
- if (creditsResult.body?.config?.currentPeriod) return creditsResult.body;
706
- try {
707
- // Only a response without a unified period is eligible for shape
708
- // fallback; a parseable legacy response can already be used as-is.
709
- normalizeGrokBillingResponse(creditsResult.body);
710
- return creditsResult.body;
711
- } catch (error) {
712
- creditsFailure = `unrecognized response (${error?.message || "invalid billing data"})`;
713
- }
714
- } else {
715
- creditsFailure = `HTTP ${creditsResult.status}`;
716
- }
717
- } catch (error) {
718
- if (error?.code === "GROK_AUTH_REQUIRED") throw error;
719
- if (error?.code === "GROK_BILLING_TIMEOUT") throw error;
720
- }
721
-
722
- // Non-auth HTTP, network, response-decoding, or shape failure → try the
723
- // legacy shape once, while sharing the original request deadline.
724
- let legacyResult;
725
- try {
726
- legacyResult = await fetchGrokBillingAttempt(
727
- fetchImpl,
728
- `${root}/v1/billing`,
729
- headers,
730
- deadlineMs,
731
- );
732
- } catch (error) {
733
- if (error?.code === "GROK_AUTH_REQUIRED" || error?.code === "GROK_BILLING_TIMEOUT") throw error;
734
- throw new Error(`Grok billing request failed (format=credits: ${creditsFailure})`, {
735
- cause: error,
736
- });
737
- }
738
- if (!legacyResult.ok) {
739
- throw new Error(
740
- `Grok billing API returned ${legacyResult.status} (format=credits: ${creditsFailure})`,
741
- );
742
- }
743
- return legacyResult.body;
744
- }
745
-
746
- async function fetchGrokPlanLabel(accessToken, { fetchImpl = fetch, env, timeoutMs } = {}) {
747
- const root = resolveGrokBillingBaseUrl(env);
748
- if (timeoutMs <= 0) return null;
749
- try {
750
- const result = await fetchGrokBillingAttempt(
751
- fetchImpl,
752
- `${root}/v1/settings`,
753
- { Authorization: `Bearer ${accessToken}`, Accept: "application/json" },
754
- Date.now() + Math.min(timeoutMs || DEFAULT_SETTINGS_TIMEOUT_MS, DEFAULT_SETTINGS_TIMEOUT_MS),
755
- );
756
- if (!result.ok) return null;
757
- return deriveGrokPlanLabel(
758
- result.body?.subscription_tier_display ?? result.body?.subscription_tier,
759
- );
760
- } catch (_error) {
761
- // A failed settings lookup must not hide a successfully fetched quota.
762
- return null;
763
- }
764
- }
765
-
766
- async function fetchGrokLimits({ home, env, fetchImpl = fetch, timeoutMs, nowMs } = {}) {
767
- if (!isGrokInstalled({ home, env })) {
768
- return { configured: false };
769
- }
770
-
771
- let resolved;
772
- try {
773
- resolved = await resolveGrokAccessToken({ home, env, fetchImpl, nowMs });
774
- } catch (error) {
775
- return {
776
- configured: true,
777
- error: error?.message || "Unknown error",
778
- };
779
- }
780
-
781
- if (!resolved.configured) {
782
- return { configured: false };
783
- }
784
- if (!resolved.accessToken) {
785
- return {
786
- configured: true,
787
- error: resolved.error?.message || grokAuthError().message,
788
- };
789
- }
790
-
791
- const startedAtMs = Date.now();
792
- try {
793
- let body;
794
- let accessToken = resolved.accessToken;
795
- try {
796
- body = await fetchGrokBilling(resolved.accessToken, { fetchImpl, env, timeoutMs });
797
- } catch (error) {
798
- // Access token rejected — refresh once when a refresh_token is available.
799
- if (
800
- error?.code === "GROK_AUTH_REQUIRED" &&
801
- resolved.canRefresh &&
802
- !resolved.refreshed
803
- ) {
804
- const retry = await resolveGrokAccessToken({
805
- home,
806
- env,
807
- fetchImpl,
808
- forceRefresh: true,
809
- nowMs,
810
- });
811
- if (!retry.accessToken) {
812
- throw retry.error || grokReauthError();
813
- }
814
- accessToken = retry.accessToken;
815
- body = await fetchGrokBilling(retry.accessToken, { fetchImpl, env, timeoutMs });
816
- } else {
817
- throw error;
818
- }
819
- }
820
- const limits = normalizeGrokBillingResponse(body);
821
- if (!limits.plan_label) {
822
- const remainingMs = Number.isFinite(timeoutMs)
823
- ? timeoutMs - (Date.now() - startedAtMs) - 100
824
- : DEFAULT_SETTINGS_TIMEOUT_MS;
825
- limits.plan_label = await fetchGrokPlanLabel(accessToken, {
826
- fetchImpl, env, timeoutMs: remainingMs,
827
- });
828
- }
829
- return {
830
- configured: true,
831
- error: null,
832
- ...limits,
833
- };
834
- } catch (error) {
835
- return {
836
- configured: true,
837
- error: error?.message || "Unknown error",
838
- };
839
- }
840
- }
841
-
842
- module.exports = {
843
- resolveGrokHome,
844
- resolveGrokBillingBaseUrl,
845
- DEFAULT_TOKEN_ENDPOINT,
846
- ACCESS_TOKEN_EXPIRY_SKEW_MS,
847
- isGrokInstalled,
848
- loadGrokAuthEntry,
849
- readGrokAccessToken,
850
- isGrokAccessTokenExpired,
851
- resolveGrokOidcClientId,
852
- resolveGrokOidcIssuer,
853
- resolveGrokTokenEndpoint,
854
- refreshGrokTokens,
855
- persistGrokRefreshedAuth,
856
- resolveGrokAccessToken,
857
- normalizeGrokPeriodType,
858
- inferGrokPeriodTypeFromDates,
859
- sumProductUsagePercent,
860
- deriveGrokPlanLabel,
861
- normalizeGrokProductUsage,
862
- normalizeGrokBillingResponse,
863
- fetchGrokBilling,
864
- fetchGrokLimits,
865
- };
1
+ const fs = require("node:fs");
2
+ const os = require("node:os");
3
+ const path = require("node:path");
4
+
5
+ const DEFAULT_BILLING_BASE_URL = "https://cli-chat-proxy.grok.com";
6
+ const DEFAULT_BILLING_TIMEOUT_MS = 15_000;
7
+ const DEFAULT_SETTINGS_TIMEOUT_MS = 2_000;
8
+ const DEFAULT_OIDC_ISSUER = "https://auth.x.ai";
9
+ const DEFAULT_TOKEN_ENDPOINT = "https://auth.x.ai/oauth2/token";
10
+ // Refresh slightly before wall-clock expiry so Limits doesn't race a just-expired JWT.
11
+ const ACCESS_TOKEN_EXPIRY_SKEW_MS = 60_000;
12
+
13
+ function grokAuthError() {
14
+ const error = new Error("Not logged in to Grok Build. Run `grok login` in Terminal to authenticate.");
15
+ error.code = "GROK_AUTH_REQUIRED";
16
+ return error;
17
+ }
18
+
19
+ function grokReauthError() {
20
+ const error = new Error(
21
+ "Grok session expired. Run `grok login` in Terminal to re-authenticate.",
22
+ );
23
+ error.code = "GROK_REAUTH_REQUIRED";
24
+ return error;
25
+ }
26
+
27
+ function grokBillingTimeoutError() {
28
+ const error = new Error("Grok billing request timed out.");
29
+ error.code = "GROK_BILLING_TIMEOUT";
30
+ return error;
31
+ }
32
+
33
+ async function runBeforeBillingDeadline(operation, deadlineMs) {
34
+ const remainingMs = Math.ceil(deadlineMs - Date.now());
35
+ if (remainingMs <= 0) throw grokBillingTimeoutError();
36
+
37
+ const controller = new AbortController();
38
+ let timer;
39
+ const timeout = new Promise((_, reject) => {
40
+ timer = setTimeout(() => {
41
+ const error = grokBillingTimeoutError();
42
+ controller.abort(error);
43
+ reject(error);
44
+ }, remainingMs);
45
+ });
46
+
47
+ try {
48
+ return await Promise.race([operation(controller.signal), timeout]);
49
+ } finally {
50
+ clearTimeout(timer);
51
+ }
52
+ }
53
+
54
+ async function fetchGrokBillingAttempt(fetchImpl, url, headers, deadlineMs) {
55
+ return runBeforeBillingDeadline(async (signal) => {
56
+ const response = await fetchImpl(url, { method: "GET", headers, signal });
57
+ if (!response.ok) {
58
+ try {
59
+ await response.body?.cancel?.();
60
+ } catch (_error) {
61
+ // The status remains authoritative even if discarding the body fails.
62
+ }
63
+ if (response.status === 401 || response.status === 403) throw grokAuthError();
64
+ return { ok: false, status: response.status };
65
+ }
66
+ return { ok: true, body: await response.json() };
67
+ }, deadlineMs);
68
+ }
69
+
70
+ function resolveGrokHome({ home, env = process.env } = {}) {
71
+ if (typeof env.TOKENUSAGE_GROK_HOME === "string" && env.TOKENUSAGE_GROK_HOME.trim()) {
72
+ return path.resolve(env.TOKENUSAGE_GROK_HOME.trim());
73
+ }
74
+ if (typeof env.GROK_HOME === "string" && env.GROK_HOME.trim()) {
75
+ return path.resolve(env.GROK_HOME.trim());
76
+ }
77
+ return path.join(home || os.homedir(), ".grok");
78
+ }
79
+
80
+ function resolveGrokBillingBaseUrl(env = process.env) {
81
+ const explicit =
82
+ typeof env.GROK_CLI_CHAT_PROXY_BASE_URL === "string"
83
+ ? env.GROK_CLI_CHAT_PROXY_BASE_URL.trim()
84
+ : typeof env.TOKENUSAGE_GROK_BILLING_BASE_URL === "string"
85
+ ? env.TOKENUSAGE_GROK_BILLING_BASE_URL.trim()
86
+ : "";
87
+ if (explicit) return explicit.replace(/\/$/, "");
88
+ return DEFAULT_BILLING_BASE_URL;
89
+ }
90
+
91
+ function grokValNumber(value) {
92
+ if (value == null) return null;
93
+ if (typeof value === "object" && "val" in value) {
94
+ return grokValNumber(value.val);
95
+ }
96
+ const n = Number(value);
97
+ return Number.isFinite(n) ? n : null;
98
+ }
99
+
100
+ function grokIsoReset(value) {
101
+ if (typeof value !== "string" || !value.trim()) return null;
102
+ const ts = Date.parse(value.trim());
103
+ return Number.isFinite(ts) && ts > 0 ? new Date(ts).toISOString() : null;
104
+ }
105
+
106
+ function clampPercent(value) {
107
+ if (value === null || value === undefined || value === "") return null;
108
+ const n = Number(value);
109
+ if (!Number.isFinite(n)) return null;
110
+ if (n <= 0) return 0;
111
+ if (n >= 100) return 100;
112
+ return n;
113
+ }
114
+
115
+ function buildWindow({ usedPercent, resetAt }) {
116
+ const pct = clampPercent(usedPercent);
117
+ if (pct === null) return null;
118
+ return {
119
+ used_percent: pct,
120
+ reset_at: typeof resetAt === "string" && resetAt ? resetAt : null,
121
+ };
122
+ }
123
+
124
+ /**
125
+ * Map Grok's USAGE_PERIOD_TYPE_* enum (or a bare "weekly"/"monthly" string)
126
+ * into a short period key the UI can switch labels on.
127
+ *
128
+ * Only daily / weekly / monthly are recognized end-to-end (dashboard + macOS).
129
+ * Hourly (and other unknown) types return null so UIs fall back to the generic
130
+ * Month label rather than inventing an unsupported period key.
131
+ */
132
+ function normalizeGrokPeriodType(value) {
133
+ if (typeof value !== "string" || !value.trim()) return null;
134
+ const upper = value.trim().toUpperCase();
135
+ if (upper.includes("WEEK")) return "weekly";
136
+ if (upper.includes("MONTH")) return "monthly";
137
+ // Prefer explicit DAILY / DAY over accidental "HOUR_OF_DAY" style matches.
138
+ if (upper.includes("DAILY") || /(^|_)DAY($|_)/.test(upper) || upper === "DAY") return "daily";
139
+ return null;
140
+ }
141
+
142
+ /**
143
+ * Infer daily / weekly / monthly from period length when the API omits
144
+ * `currentPeriod.type` (legacy payloads only expose start/end dates).
145
+ *
146
+ * Windows used by Grok today: ~1d, ~7d, ~calendar month. Boundaries leave
147
+ * gaps for odd lengths (e.g. 12d, 2h) so we do not mislabel them.
148
+ */
149
+ function inferGrokPeriodTypeFromDates(startIso, endIso) {
150
+ if (!startIso || !endIso) return null;
151
+ const startMs = Date.parse(startIso);
152
+ const endMs = Date.parse(endIso);
153
+ if (!Number.isFinite(startMs) || !Number.isFinite(endMs) || endMs <= startMs) return null;
154
+ const days = (endMs - startMs) / 86_400_000;
155
+ if (days > 0.5 && days <= 1.5) return "daily";
156
+ if (days > 1.5 && days <= 8) return "weekly";
157
+ if (days >= 25 && days <= 35) return "monthly";
158
+ return null;
159
+ }
160
+
161
+ /**
162
+ * Sum per-product attribution percentages into the shared pool total.
163
+ * productUsage breaks down the same cap (GrokBuild + GrokChat + …), not
164
+ * independent quotas — a single product entry undercounts the pool.
165
+ */
166
+ function sumProductUsagePercent(productUsage) {
167
+ if (!Array.isArray(productUsage)) return null;
168
+ let sum = 0;
169
+ let sawAny = false;
170
+ for (const entry of productUsage) {
171
+ if (!entry || typeof entry !== "object") continue;
172
+ const pct = clampPercent(entry.usagePercent);
173
+ if (pct === null) continue;
174
+ sawAny = true;
175
+ sum += pct;
176
+ }
177
+ return sawAny ? clampPercent(sum) : null;
178
+ }
179
+
180
+ function isGrokInstalled({ home, env } = {}) {
181
+ const grokHome = resolveGrokHome({ home, env });
182
+ const authPath = path.join(grokHome, "auth.json");
183
+ if (fs.existsSync(authPath)) return true;
184
+ return fs.existsSync(path.join(grokHome, "sessions"));
185
+ }
186
+
187
+ function loadGrokAuthEntry({ home, env } = {}) {
188
+ const authPath = path.join(resolveGrokHome({ home, env }), "auth.json");
189
+ if (!fs.existsSync(authPath)) return null;
190
+ let fallback = null;
191
+ try {
192
+ const parsed = JSON.parse(fs.readFileSync(authPath, "utf8"));
193
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
194
+ for (const [scopeKey, value] of Object.entries(parsed)) {
195
+ if (!value || typeof value !== "object" || Array.isArray(value)) continue;
196
+ const key = typeof value.key === "string" ? value.key.trim() : "";
197
+ const refreshToken =
198
+ typeof value.refresh_token === "string" ? value.refresh_token.trim() : "";
199
+ // Entries with an access token win outright. A refresh-token-only entry
200
+ // is only usable when a client id is resolvable, and must not shadow a
201
+ // later keyed entry — keep it as a fallback instead.
202
+ if (key) {
203
+ return { entry: value, authPath, scopeKey, authFile: parsed };
204
+ }
205
+ if (refreshToken && !fallback && resolveGrokOidcClientId(value, scopeKey)) {
206
+ fallback = { entry: value, authPath, scopeKey, authFile: parsed };
207
+ }
208
+ }
209
+ } catch (_error) {
210
+ return null;
211
+ }
212
+ return fallback;
213
+ }
214
+
215
+ function readGrokAccessToken({ home, env } = {}) {
216
+ const loaded = loadGrokAuthEntry({ home, env });
217
+ const key = typeof loaded?.entry?.key === "string" ? loaded.entry.key.trim() : "";
218
+ return key || null;
219
+ }
220
+
221
+ function isGrokAccessTokenExpired(expiresAt, nowMs = Date.now(), skewMs = ACCESS_TOKEN_EXPIRY_SKEW_MS) {
222
+ if (expiresAt == null || expiresAt === "") return false;
223
+ const ts = typeof expiresAt === "number" ? expiresAt : Date.parse(String(expiresAt));
224
+ if (!Number.isFinite(ts)) return false;
225
+ const skew = Number.isFinite(skewMs) && skewMs >= 0 ? skewMs : ACCESS_TOKEN_EXPIRY_SKEW_MS;
226
+ return ts <= nowMs + skew;
227
+ }
228
+
229
+ function resolveGrokOidcClientId(entry, scopeKey) {
230
+ if (entry && typeof entry.oidc_client_id === "string" && entry.oidc_client_id.trim()) {
231
+ return entry.oidc_client_id.trim();
232
+ }
233
+ if (typeof scopeKey === "string" && scopeKey.includes("::")) {
234
+ const suffix = scopeKey.slice(scopeKey.lastIndexOf("::") + 2).trim();
235
+ if (suffix) return suffix;
236
+ }
237
+ return null;
238
+ }
239
+
240
+ function resolveGrokOidcIssuer(entry) {
241
+ if (entry && typeof entry.oidc_issuer === "string" && entry.oidc_issuer.trim()) {
242
+ return entry.oidc_issuer.trim().replace(/\/$/, "");
243
+ }
244
+ return DEFAULT_OIDC_ISSUER;
245
+ }
246
+
247
+ function resolveGrokTokenEndpoint(entry, env = process.env) {
248
+ if (typeof env.TOKENUSAGE_GROK_TOKEN_ENDPOINT === "string" && env.TOKENUSAGE_GROK_TOKEN_ENDPOINT.trim()) {
249
+ return env.TOKENUSAGE_GROK_TOKEN_ENDPOINT.trim();
250
+ }
251
+ if (typeof env.GROK_OIDC_TOKEN_ENDPOINT === "string" && env.GROK_OIDC_TOKEN_ENDPOINT.trim()) {
252
+ return env.GROK_OIDC_TOKEN_ENDPOINT.trim();
253
+ }
254
+ const issuer = resolveGrokOidcIssuer(entry);
255
+ if (issuer === DEFAULT_OIDC_ISSUER) return DEFAULT_TOKEN_ENDPOINT;
256
+ return `${issuer}/oauth2/token`;
257
+ }
258
+
259
+ function grokEntryRefreshToken(entry) {
260
+ return entry && typeof entry.refresh_token === "string" ? entry.refresh_token.trim() : "";
261
+ }
262
+
263
+ function grokEntryAccessToken(entry) {
264
+ return entry && typeof entry.key === "string" ? entry.key.trim() : "";
265
+ }
266
+
267
+ /**
268
+ * Public xAI OIDC client refresh (auth method "none").
269
+ * Matches Grok Build CLI's refresh against https://auth.x.ai/oauth2/token.
270
+ */
271
+ async function refreshGrokTokens({
272
+ refreshToken,
273
+ clientId,
274
+ tokenEndpoint = DEFAULT_TOKEN_ENDPOINT,
275
+ fetchImpl = fetch,
276
+ timeoutMs = DEFAULT_BILLING_TIMEOUT_MS,
277
+ } = {}) {
278
+ if (typeof refreshToken !== "string" || !refreshToken.trim()) {
279
+ const err = new Error("Grok refresh skipped: no refresh_token in auth.json");
280
+ err.code = "NO_REFRESH_TOKEN";
281
+ throw err;
282
+ }
283
+ if (typeof clientId !== "string" || !clientId.trim()) {
284
+ const err = new Error("Grok refresh skipped: missing oidc_client_id");
285
+ err.code = "NO_CLIENT_ID";
286
+ throw err;
287
+ }
288
+
289
+ const body = new URLSearchParams({
290
+ grant_type: "refresh_token",
291
+ refresh_token: refreshToken.trim(),
292
+ client_id: clientId.trim(),
293
+ });
294
+
295
+ // Same abort deadline discipline as fetchGrokBilling — a stalled token
296
+ // endpoint must not block fetchGrokLimits (and its poller) indefinitely.
297
+ // The timer stays armed through the body reads below, not just the headers.
298
+ const normalizedTimeoutMs =
299
+ Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : DEFAULT_BILLING_TIMEOUT_MS;
300
+ const controller = new AbortController();
301
+ const timeoutError = new Error("Grok token refresh timed out.");
302
+ timeoutError.code = "GROK_REFRESH_TIMEOUT";
303
+ const timer = setTimeout(() => controller.abort(timeoutError), normalizedTimeoutMs);
304
+
305
+ try {
306
+ const res = await fetchImpl(tokenEndpoint, {
307
+ method: "POST",
308
+ headers: {
309
+ "Content-Type": "application/x-www-form-urlencoded",
310
+ Accept: "application/json",
311
+ },
312
+ body: body.toString(),
313
+ signal: controller.signal,
314
+ });
315
+
316
+ if (res.status === 400 || res.status === 401) {
317
+ let oauthError = null;
318
+ try {
319
+ const payload = await res.json();
320
+ oauthError =
321
+ (typeof payload?.error === "string" && payload.error) ||
322
+ (payload?.error && typeof payload.error === "object" && payload.error.code) ||
323
+ null;
324
+ } catch (_error) {
325
+ // Status remains authoritative.
326
+ }
327
+ const err = grokReauthError();
328
+ err.oauthError = oauthError;
329
+ err.status = res.status;
330
+ throw err;
331
+ }
332
+
333
+ if (!res.ok) {
334
+ const err = new Error(`Grok token refresh failed: HTTP ${res.status}`);
335
+ err.code = "REFRESH_HTTP_ERROR";
336
+ err.status = res.status;
337
+ throw err;
338
+ }
339
+
340
+ const payload = await res.json();
341
+ const accessToken =
342
+ typeof payload?.access_token === "string" ? payload.access_token.trim() : "";
343
+ if (!accessToken) {
344
+ const err = new Error("Grok token refresh response missing access_token");
345
+ err.code = "REFRESH_INVALID_RESPONSE";
346
+ throw err;
347
+ }
348
+
349
+ const nextRefresh =
350
+ typeof payload?.refresh_token === "string" && payload.refresh_token.trim()
351
+ ? payload.refresh_token.trim()
352
+ : refreshToken.trim();
353
+
354
+ let expiresAt = null;
355
+ const expiresIn = Number(payload?.expires_in);
356
+ if (Number.isFinite(expiresIn) && expiresIn > 0) {
357
+ expiresAt = new Date(Date.now() + expiresIn * 1000).toISOString();
358
+ } else if (typeof payload?.expires_at === "string" && payload.expires_at.trim()) {
359
+ const parsed = Date.parse(payload.expires_at.trim());
360
+ if (Number.isFinite(parsed)) expiresAt = new Date(parsed).toISOString();
361
+ }
362
+
363
+ return {
364
+ access_token: accessToken,
365
+ refresh_token: nextRefresh,
366
+ expires_at: expiresAt,
367
+ token_type: typeof payload?.token_type === "string" ? payload.token_type : null,
368
+ };
369
+ } catch (error) {
370
+ if (controller.signal.aborted && controller.signal.reason === timeoutError) {
371
+ throw timeoutError;
372
+ }
373
+ throw error;
374
+ } finally {
375
+ clearTimeout(timer);
376
+ }
377
+ }
378
+
379
+ async function persistGrokRefreshedAuth(authPath, authFile, scopeKey, entry, newTokens) {
380
+ if (!authPath || !scopeKey || !entry || !newTokens?.access_token) {
381
+ throw new Error("Grok auth persist requires auth path, scope, entry, and access_token");
382
+ }
383
+ const nextEntry = {
384
+ ...entry,
385
+ key: newTokens.access_token,
386
+ refresh_token: newTokens.refresh_token || entry.refresh_token,
387
+ };
388
+ if (newTokens.expires_at) {
389
+ nextEntry.expires_at = newTokens.expires_at;
390
+ } else {
391
+ // Unknown new lifetime: drop the stale timestamp, otherwise the next poll
392
+ // sees an already-expired expires_at next to a fresh key and refreshes
393
+ // again on every cycle (burning a rotation each time).
394
+ delete nextEntry.expires_at;
395
+ }
396
+ const merged = {
397
+ ...authFile,
398
+ [scopeKey]: nextEntry,
399
+ };
400
+ const tmp = `${authPath}.tmp.${process.pid}.${Date.now()}`;
401
+ try {
402
+ await fs.promises.writeFile(tmp, `${JSON.stringify(merged, null, 2)}\n`, { mode: 0o600 });
403
+ await fs.promises.rename(tmp, authPath);
404
+ } catch (error) {
405
+ // Never leave a tmp file holding fresh tokens behind.
406
+ await fs.promises.rm(tmp, { force: true }).catch(() => {});
407
+ throw error;
408
+ }
409
+ try {
410
+ await fs.promises.chmod(authPath, 0o600);
411
+ } catch (_error) {
412
+ // Best-effort; some filesystems reject chmod on rename targets.
413
+ }
414
+ return { entry: nextEntry, authFile: merged, authPath, scopeKey };
415
+ }
416
+
417
+ /**
418
+ * Return a usable access token, refreshing via OIDC when expired or forced.
419
+ * Does not throw for missing install; throws GROK_REAUTH_REQUIRED when refresh is rejected.
420
+ */
421
+ async function resolveGrokAccessToken({
422
+ home,
423
+ env = process.env,
424
+ fetchImpl = fetch,
425
+ forceRefresh = false,
426
+ nowMs = Date.now(),
427
+ } = {}) {
428
+ const loaded = loadGrokAuthEntry({ home, env });
429
+ if (!loaded) {
430
+ return {
431
+ accessToken: null,
432
+ configured: false,
433
+ canRefresh: false,
434
+ refreshed: false,
435
+ };
436
+ }
437
+
438
+ const accessToken = grokEntryAccessToken(loaded.entry);
439
+ const refreshToken = grokEntryRefreshToken(loaded.entry);
440
+ const expired = isGrokAccessTokenExpired(loaded.entry.expires_at, nowMs);
441
+ const canRefresh = Boolean(refreshToken && resolveGrokOidcClientId(loaded.entry, loaded.scopeKey));
442
+ const needsRefresh = forceRefresh || !accessToken || expired;
443
+
444
+ if (!needsRefresh) {
445
+ return {
446
+ accessToken,
447
+ configured: true,
448
+ canRefresh,
449
+ refreshed: false,
450
+ loaded,
451
+ };
452
+ }
453
+
454
+ if (!canRefresh) {
455
+ if (accessToken) {
456
+ // Stale key still present — let billing decide (may 401).
457
+ return {
458
+ accessToken,
459
+ configured: true,
460
+ canRefresh: false,
461
+ refreshed: false,
462
+ loaded,
463
+ };
464
+ }
465
+ return {
466
+ accessToken: null,
467
+ configured: true,
468
+ canRefresh: false,
469
+ refreshed: false,
470
+ loaded,
471
+ error: grokAuthError(),
472
+ };
473
+ }
474
+
475
+ const clientId = resolveGrokOidcClientId(loaded.entry, loaded.scopeKey);
476
+ const tokens = await refreshGrokTokens({
477
+ refreshToken,
478
+ clientId,
479
+ tokenEndpoint: resolveGrokTokenEndpoint(loaded.entry, env),
480
+ fetchImpl,
481
+ });
482
+ const persisted = await persistGrokRefreshedAuth(
483
+ loaded.authPath,
484
+ loaded.authFile,
485
+ loaded.scopeKey,
486
+ loaded.entry,
487
+ tokens,
488
+ );
489
+
490
+ return {
491
+ accessToken: tokens.access_token,
492
+ configured: true,
493
+ canRefresh: true,
494
+ refreshed: true,
495
+ loaded: persisted,
496
+ };
497
+ }
498
+
499
+ // Grok Build enriches billing with a display tier from remote settings. The
500
+ // billing HTTP response itself may contain only `config`.
501
+ const GROK_PLAN_TIERS = new Map([
502
+ ["supergrokheavy", "SuperGrok Heavy"],
503
+ ["supergrokplus", "SuperGrok Plus"],
504
+ ["supergroklite", "SuperGrok Lite"],
505
+ ["supergrok", "SuperGrok"],
506
+ ["xpremiumplus", "X Premium+"],
507
+ ["premiumplus", "X Premium+"],
508
+ ["xpremium", "X Premium+"],
509
+ ["apikey", "API Key"],
510
+ ["free", "Free"],
511
+ ]);
512
+
513
+ /**
514
+ * Map xAI's subscription tier to the name its own UI shows.
515
+ *
516
+ * Separators are folded away before matching so the same table covers whichever
517
+ * casing the API returns ("SuperGrok Heavy", "SUPER_GROK_HEAVY", "superGrokHeavy").
518
+ * Unknown values return null rather than being passed through: the Limits panel
519
+ * falls back to the bare brand name, which is better than rendering a raw enum
520
+ * (issue #130 shipped "Kimi Type_event" that way).
521
+ */
522
+ function deriveGrokPlanLabel(rawTier) {
523
+ if (rawTier == null) return null;
524
+ const key = String(rawTier).toLowerCase().replace(/[^a-z0-9]+/g, "");
525
+ if (!key) return null;
526
+ // Exact match only. Prefix matching would read an unseen tier such as
527
+ // "SuperGrok Business" as plain "SuperGrok", and a confidently wrong plan on
528
+ // the card is worse than no plan at all.
529
+ return GROK_PLAN_TIERS.get(key) ?? null;
530
+ }
531
+
532
+ // Billing product ids → the name grok.com shows in the usage legend.
533
+ // Unknown ids are humanized below so a new product still gets a row.
534
+ const GROK_PRODUCT_LABELS = new Map([
535
+ ["GrokBuild", "Grok Build"],
536
+ ["GrokBot", "Grok Bot"],
537
+ ["GrokChat", "Chat"],
538
+ ["GrokImagine", "Imagine"],
539
+ ["Cursor", "Cursor"],
540
+ ]);
541
+
542
+ function normalizeGrokProductId(value) {
543
+ if (typeof value !== "string") return null;
544
+ const id = value.trim();
545
+ if (!/^[A-Za-z][A-Za-z0-9]{0,31}$/.test(id)) return null;
546
+ return id;
547
+ }
548
+
549
+ function humanizeGrokProductId(productId) {
550
+ const spaced = productId
551
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
552
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
553
+ .replace(/[_-]+/g, " ")
554
+ .replace(/\s+/g, " ")
555
+ .trim();
556
+ return spaced.slice(0, 40) || null;
557
+ }
558
+
559
+ /**
560
+ * Per-product shares of the same pool as creditUsagePercent.
561
+ * A 12% Grok Bot row is 12 points of the weekly cap, not its own 100% quota.
562
+ * Zero and non-finite rows are omitted (grok.com hides unused products).
563
+ * API order is preserved; a repeated product id keeps the first finite row.
564
+ */
565
+ function normalizeGrokProductUsage(productUsage, resetAt) {
566
+ if (!Array.isArray(productUsage)) return [];
567
+ const seen = new Set();
568
+ const products = [];
569
+ for (const entry of productUsage) {
570
+ if (!entry || typeof entry !== "object") continue;
571
+ const product = normalizeGrokProductId(entry.product);
572
+ if (!product || seen.has(product)) continue;
573
+ const raw = Number(entry.usagePercent);
574
+ if (!Number.isFinite(raw) || raw <= 0) continue;
575
+ const window = buildWindow({ usedPercent: raw, resetAt });
576
+ if (!window || !(window.used_percent > 0)) continue;
577
+ const label = GROK_PRODUCT_LABELS.get(product) || humanizeGrokProductId(product);
578
+ if (!label) continue;
579
+ seen.add(product);
580
+ products.push({ product, label, window });
581
+ }
582
+ return products;
583
+ }
584
+
585
+ /**
586
+ * Parse either:
587
+ * - Unified billing (`?format=credits`): weekly/monthly period + creditUsagePercent
588
+ * - Legacy monthly credits: monthlyLimit / used + calendar-month billingPeriod*
589
+ *
590
+ * Prefer the unified shape; legacy remains as a fallback for older accounts.
591
+ */
592
+ function normalizeGrokBillingResponse(body) {
593
+ const config = body?.config;
594
+ if (!config || typeof config !== "object") {
595
+ throw new Error("Could not parse Grok billing: missing config");
596
+ }
597
+
598
+ const currentPeriod =
599
+ config.currentPeriod && typeof config.currentPeriod === "object" ? config.currentPeriod : null;
600
+
601
+ const periodStart =
602
+ grokIsoReset(currentPeriod?.start) || grokIsoReset(config.billingPeriodStart);
603
+ const resetAt = grokIsoReset(currentPeriod?.end) || grokIsoReset(config.billingPeriodEnd);
604
+
605
+ let periodType = normalizeGrokPeriodType(currentPeriod?.type);
606
+ if (!periodType) {
607
+ periodType = inferGrokPeriodTypeFromDates(periodStart, resetAt);
608
+ }
609
+
610
+ // Unified billing: overall pool percent is what gates "You hit your weekly limit".
611
+ // productUsage is attribution across products that share the same pool — sum it.
612
+ let usedPercent = clampPercent(config.creditUsagePercent);
613
+ if (usedPercent === null) {
614
+ usedPercent = sumProductUsagePercent(config.productUsage);
615
+ }
616
+
617
+ // Legacy monthly credit counters (pre-unified / non-format=credits responses).
618
+ const monthlyLimit = grokValNumber(config.monthlyLimit);
619
+ const used = grokValNumber(config.used);
620
+ if (usedPercent === null && Number.isFinite(monthlyLimit) && monthlyLimit > 0 && Number.isFinite(used)) {
621
+ usedPercent = (used / monthlyLimit) * 100;
622
+ if (!periodType) periodType = "monthly";
623
+ }
624
+
625
+ // Unified billing omits creditUsagePercent (and productUsage) entirely when
626
+ // nothing was used this period. A valid currentPeriod window with the usage
627
+ // fields absent means 0%, not an unparseable response. Present-but-malformed
628
+ // fields still fall through to the parse error below.
629
+ if (
630
+ usedPercent === null &&
631
+ currentPeriod &&
632
+ (periodStart || resetAt) &&
633
+ config.creditUsagePercent === undefined &&
634
+ config.productUsage === undefined
635
+ ) {
636
+ usedPercent = 0;
637
+ }
638
+
639
+ const onDemandCap = grokValNumber(config.onDemandCap);
640
+ const onDemandUsed = grokValNumber(config.onDemandUsed);
641
+
642
+ const primaryWindow = buildWindow({ usedPercent, resetAt });
643
+
644
+ let secondaryWindow = null;
645
+ if (Number.isFinite(onDemandCap) && onDemandCap > 0 && Number.isFinite(onDemandUsed)) {
646
+ secondaryWindow = buildWindow({
647
+ usedPercent: (onDemandUsed / onDemandCap) * 100,
648
+ resetAt,
649
+ });
650
+ }
651
+
652
+ if (!primaryWindow && !secondaryWindow) {
653
+ throw new Error("Could not parse Grok billing: no quota windows in response");
654
+ }
655
+
656
+ return {
657
+ // Read from the response root, not from `config`.
658
+ plan_label: deriveGrokPlanLabel(body?.subscriptionTier),
659
+ period_type: periodType,
660
+ monthly_credits_limit: monthlyLimit,
661
+ monthly_credits_used: used,
662
+ // Effective percent used for the primary bar (API creditUsagePercent, or
663
+ // productUsage / legacy monthly counters when the raw field is absent).
664
+ credit_usage_percent: usedPercent == null ? null : clampPercent(usedPercent),
665
+ on_demand_cap: onDemandCap,
666
+ on_demand_used: onDemandUsed,
667
+ billing_period_start: periodStart,
668
+ primary_window: primaryWindow,
669
+ secondary_window: secondaryWindow,
670
+ // Shares of primary_window. Do not add these on top of credit_usage_percent.
671
+ products: normalizeGrokProductUsage(config.productUsage, resetAt),
672
+ };
673
+ }
674
+
675
+ /**
676
+ * Fetch Grok billing. Prefer `?format=credits` (unified weekly/monthly pool
677
+ * used by the Grok Build TUI). Fall back to the bare `/v1/billing` payload for
678
+ * older accounts that only expose monthlyLimit/used.
679
+ */
680
+ async function fetchGrokBilling(
681
+ accessToken,
682
+ { fetchImpl = fetch, baseUrl, env, timeoutMs = DEFAULT_BILLING_TIMEOUT_MS } = {},
683
+ ) {
684
+ const root = (baseUrl || resolveGrokBillingBaseUrl(env)).replace(/\/$/, "");
685
+ const headers = {
686
+ Authorization: `Bearer ${accessToken}`,
687
+ Accept: "application/json",
688
+ };
689
+ const normalizedTimeoutMs =
690
+ Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : DEFAULT_BILLING_TIMEOUT_MS;
691
+ const deadlineMs = Date.now() + normalizedTimeoutMs;
692
+
693
+ const creditsUrl = `${root}/v1/billing?format=credits`;
694
+ let creditsFailure = "request failed";
695
+ try {
696
+ const creditsResult = await fetchGrokBillingAttempt(
697
+ fetchImpl,
698
+ creditsUrl,
699
+ headers,
700
+ deadlineMs,
701
+ );
702
+ if (creditsResult.ok) {
703
+ // Keep the unified pool even when its fields are malformed. The caller
704
+ // must surface its parse error rather than substitute a legacy pool.
705
+ if (creditsResult.body?.config?.currentPeriod) return creditsResult.body;
706
+ try {
707
+ // Only a response without a unified period is eligible for shape
708
+ // fallback; a parseable legacy response can already be used as-is.
709
+ normalizeGrokBillingResponse(creditsResult.body);
710
+ return creditsResult.body;
711
+ } catch (error) {
712
+ creditsFailure = `unrecognized response (${error?.message || "invalid billing data"})`;
713
+ }
714
+ } else {
715
+ creditsFailure = `HTTP ${creditsResult.status}`;
716
+ }
717
+ } catch (error) {
718
+ if (error?.code === "GROK_AUTH_REQUIRED") throw error;
719
+ if (error?.code === "GROK_BILLING_TIMEOUT") throw error;
720
+ }
721
+
722
+ // Non-auth HTTP, network, response-decoding, or shape failure → try the
723
+ // legacy shape once, while sharing the original request deadline.
724
+ let legacyResult;
725
+ try {
726
+ legacyResult = await fetchGrokBillingAttempt(
727
+ fetchImpl,
728
+ `${root}/v1/billing`,
729
+ headers,
730
+ deadlineMs,
731
+ );
732
+ } catch (error) {
733
+ if (error?.code === "GROK_AUTH_REQUIRED" || error?.code === "GROK_BILLING_TIMEOUT") throw error;
734
+ throw new Error(`Grok billing request failed (format=credits: ${creditsFailure})`, {
735
+ cause: error,
736
+ });
737
+ }
738
+ if (!legacyResult.ok) {
739
+ throw new Error(
740
+ `Grok billing API returned ${legacyResult.status} (format=credits: ${creditsFailure})`,
741
+ );
742
+ }
743
+ return legacyResult.body;
744
+ }
745
+
746
+ async function fetchGrokPlanLabel(accessToken, { fetchImpl = fetch, env, timeoutMs } = {}) {
747
+ const root = resolveGrokBillingBaseUrl(env);
748
+ if (timeoutMs <= 0) return null;
749
+ try {
750
+ const result = await fetchGrokBillingAttempt(
751
+ fetchImpl,
752
+ `${root}/v1/settings`,
753
+ { Authorization: `Bearer ${accessToken}`, Accept: "application/json" },
754
+ Date.now() + Math.min(timeoutMs || DEFAULT_SETTINGS_TIMEOUT_MS, DEFAULT_SETTINGS_TIMEOUT_MS),
755
+ );
756
+ if (!result.ok) return null;
757
+ return deriveGrokPlanLabel(
758
+ result.body?.subscription_tier_display ?? result.body?.subscription_tier,
759
+ );
760
+ } catch (_error) {
761
+ // A failed settings lookup must not hide a successfully fetched quota.
762
+ return null;
763
+ }
764
+ }
765
+
766
+ async function fetchGrokLimits({ home, env, fetchImpl = fetch, timeoutMs, nowMs } = {}) {
767
+ if (!isGrokInstalled({ home, env })) {
768
+ return { configured: false };
769
+ }
770
+
771
+ let resolved;
772
+ try {
773
+ resolved = await resolveGrokAccessToken({ home, env, fetchImpl, nowMs });
774
+ } catch (error) {
775
+ return {
776
+ configured: true,
777
+ error: error?.message || "Unknown error",
778
+ };
779
+ }
780
+
781
+ if (!resolved.configured) {
782
+ return { configured: false };
783
+ }
784
+ if (!resolved.accessToken) {
785
+ return {
786
+ configured: true,
787
+ error: resolved.error?.message || grokAuthError().message,
788
+ };
789
+ }
790
+
791
+ const startedAtMs = Date.now();
792
+ try {
793
+ let body;
794
+ let accessToken = resolved.accessToken;
795
+ try {
796
+ body = await fetchGrokBilling(resolved.accessToken, { fetchImpl, env, timeoutMs });
797
+ } catch (error) {
798
+ // Access token rejected — refresh once when a refresh_token is available.
799
+ if (
800
+ error?.code === "GROK_AUTH_REQUIRED" &&
801
+ resolved.canRefresh &&
802
+ !resolved.refreshed
803
+ ) {
804
+ const retry = await resolveGrokAccessToken({
805
+ home,
806
+ env,
807
+ fetchImpl,
808
+ forceRefresh: true,
809
+ nowMs,
810
+ });
811
+ if (!retry.accessToken) {
812
+ throw retry.error || grokReauthError();
813
+ }
814
+ accessToken = retry.accessToken;
815
+ body = await fetchGrokBilling(retry.accessToken, { fetchImpl, env, timeoutMs });
816
+ } else {
817
+ throw error;
818
+ }
819
+ }
820
+ const limits = normalizeGrokBillingResponse(body);
821
+ if (!limits.plan_label) {
822
+ const remainingMs = Number.isFinite(timeoutMs)
823
+ ? timeoutMs - (Date.now() - startedAtMs) - 100
824
+ : DEFAULT_SETTINGS_TIMEOUT_MS;
825
+ limits.plan_label = await fetchGrokPlanLabel(accessToken, {
826
+ fetchImpl, env, timeoutMs: remainingMs,
827
+ });
828
+ }
829
+ return {
830
+ configured: true,
831
+ error: null,
832
+ ...limits,
833
+ };
834
+ } catch (error) {
835
+ return {
836
+ configured: true,
837
+ error: error?.message || "Unknown error",
838
+ };
839
+ }
840
+ }
841
+
842
+ module.exports = {
843
+ resolveGrokHome,
844
+ resolveGrokBillingBaseUrl,
845
+ DEFAULT_TOKEN_ENDPOINT,
846
+ ACCESS_TOKEN_EXPIRY_SKEW_MS,
847
+ isGrokInstalled,
848
+ loadGrokAuthEntry,
849
+ readGrokAccessToken,
850
+ isGrokAccessTokenExpired,
851
+ resolveGrokOidcClientId,
852
+ resolveGrokOidcIssuer,
853
+ resolveGrokTokenEndpoint,
854
+ refreshGrokTokens,
855
+ persistGrokRefreshedAuth,
856
+ resolveGrokAccessToken,
857
+ normalizeGrokPeriodType,
858
+ inferGrokPeriodTypeFromDates,
859
+ sumProductUsagePercent,
860
+ deriveGrokPlanLabel,
861
+ normalizeGrokProductUsage,
862
+ normalizeGrokBillingResponse,
863
+ fetchGrokBilling,
864
+ fetchGrokLimits,
865
+ };