tokenusage-cli 0.1.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 (125) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +22 -0
  3. package/README.md +94 -0
  4. package/THIRD_PARTY_NOTICES.md +140 -0
  5. package/bin/tokenusage.js +69 -0
  6. package/package.json +59 -0
  7. package/src/cli.js +134 -0
  8. package/src/commands/device-login.js +205 -0
  9. package/src/commands/diagnostics.js +38 -0
  10. package/src/commands/doctor.js +110 -0
  11. package/src/commands/init.js +2436 -0
  12. package/src/commands/sessions.js +29 -0
  13. package/src/commands/status.js +1747 -0
  14. package/src/commands/sync.js +7934 -0
  15. package/src/commands/uninstall.js +312 -0
  16. package/src/lib/account-usage-dedup.js +267 -0
  17. package/src/lib/antigravity-paths.js +48 -0
  18. package/src/lib/ark-agent-plan-limits.js +438 -0
  19. package/src/lib/ark-coding-plan-limits.js +537 -0
  20. package/src/lib/async-queue-reader.js +138 -0
  21. package/src/lib/atomic-json.js +27 -0
  22. package/src/lib/bearer-token.js +11 -0
  23. package/src/lib/categorizer-utils.js +232 -0
  24. package/src/lib/claude-categorizer.js +1343 -0
  25. package/src/lib/claude-config.js +279 -0
  26. package/src/lib/claude-user-identity.js +56 -0
  27. package/src/lib/cli-ui.js +179 -0
  28. package/src/lib/cloud-account.js +541 -0
  29. package/src/lib/cloud-device-token.js +141 -0
  30. package/src/lib/cloud-sync-prefs.js +14 -0
  31. package/src/lib/cloud-usage-reset.js +115 -0
  32. package/src/lib/codex-config.js +595 -0
  33. package/src/lib/codex-context-breakdown.js +806 -0
  34. package/src/lib/codex-model-attribution.js +128 -0
  35. package/src/lib/codex-rollout-parser.js +1471 -0
  36. package/src/lib/codex-service-tier.js +49 -0
  37. package/src/lib/codex-token-refresh.js +140 -0
  38. package/src/lib/codex-token-usage.js +195 -0
  39. package/src/lib/codex-usage-record.js +195 -0
  40. package/src/lib/command-runner.js +313 -0
  41. package/src/lib/commandcode-limits.js +317 -0
  42. package/src/lib/context-health.js +124 -0
  43. package/src/lib/cursor-config.js +605 -0
  44. package/src/lib/cursor-store.js +1918 -0
  45. package/src/lib/debug-flags.js +7 -0
  46. package/src/lib/devin-limits.js +249 -0
  47. package/src/lib/devin-usage.js +212 -0
  48. package/src/lib/diagnostics.js +383 -0
  49. package/src/lib/doctor.js +385 -0
  50. package/src/lib/dumate.js +95 -0
  51. package/src/lib/fs.js +455 -0
  52. package/src/lib/function-url.js +14 -0
  53. package/src/lib/gemini-config.js +291 -0
  54. package/src/lib/git-outcomes.js +243 -0
  55. package/src/lib/grok-context-breakdown.js +890 -0
  56. package/src/lib/grok-hook.js +360 -0
  57. package/src/lib/grok-limits.js +865 -0
  58. package/src/lib/grok-usage.js +98 -0
  59. package/src/lib/heatmap-compact.js +114 -0
  60. package/src/lib/ingest-sanitize.js +41 -0
  61. package/src/lib/init-flow.js +42 -0
  62. package/src/lib/install-resolver.js +170 -0
  63. package/src/lib/jsonl-lines.js +134 -0
  64. package/src/lib/kimi-model-repair.js +173 -0
  65. package/src/lib/kimi-profile.js +61 -0
  66. package/src/lib/kimi-session.js +216 -0
  67. package/src/lib/local-api.js +3588 -0
  68. package/src/lib/machine-id.js +238 -0
  69. package/src/lib/multi-install-parser.js +113 -0
  70. package/src/lib/notify-command.js +38 -0
  71. package/src/lib/omp-hook.js +589 -0
  72. package/src/lib/openclaw-cli.js +104 -0
  73. package/src/lib/openclaw-hook.js +375 -0
  74. package/src/lib/openclaw-session-plugin.js +560 -0
  75. package/src/lib/opencode-config.js +121 -0
  76. package/src/lib/opencode-go-limits.js +807 -0
  77. package/src/lib/outcomes-engine.js +253 -0
  78. package/src/lib/passive-mode.js +219 -0
  79. package/src/lib/pet-packages.js +722 -0
  80. package/src/lib/pricing/curated-overrides.json +822 -0
  81. package/src/lib/pricing/index.js +379 -0
  82. package/src/lib/pricing/litellm-fetcher.js +172 -0
  83. package/src/lib/pricing/matcher.js +456 -0
  84. package/src/lib/pricing/seed-snapshot.json +1 -0
  85. package/src/lib/progress.js +76 -0
  86. package/src/lib/project-usage-purge.js +117 -0
  87. package/src/lib/prompt.js +24 -0
  88. package/src/lib/provider-status.js +104 -0
  89. package/src/lib/proxy-env.js +489 -0
  90. package/src/lib/proxy-settings.js +163 -0
  91. package/src/lib/qoder-cn-cli-limits.js +119 -0
  92. package/src/lib/qoder-limits.js +880 -0
  93. package/src/lib/quiet-warnings.js +26 -0
  94. package/src/lib/rollout.js +25966 -0
  95. package/src/lib/runtime-config.js +259 -0
  96. package/src/lib/scan-roots.js +277 -0
  97. package/src/lib/sentry.js +231 -0
  98. package/src/lib/session-analytics.js +2972 -0
  99. package/src/lib/session-performance.js +237 -0
  100. package/src/lib/session-upload.js +379 -0
  101. package/src/lib/skill-usage.js +267 -0
  102. package/src/lib/skills-manager.js +1591 -0
  103. package/src/lib/source-metadata.js +48 -0
  104. package/src/lib/sqlite-reader.js +215 -0
  105. package/src/lib/star-cta.js +73 -0
  106. package/src/lib/subscription-manager.js +293 -0
  107. package/src/lib/subscriptions.js +508 -0
  108. package/src/lib/telemetry.js +193 -0
  109. package/src/lib/tracker-paths.js +16 -0
  110. package/src/lib/trae-cn-config.js +548 -0
  111. package/src/lib/trae-db.js +127 -0
  112. package/src/lib/trae-snapshot.js +230 -0
  113. package/src/lib/trae-sqlite.js +143 -0
  114. package/src/lib/trae-usage.js +121 -0
  115. package/src/lib/upload-queue.js +134 -0
  116. package/src/lib/upload-throttle.js +171 -0
  117. package/src/lib/usage-limits.js +4552 -0
  118. package/src/lib/wrapped-aggregator.js +236 -0
  119. package/src/lib/wsl-probe.js +281 -0
  120. package/src/lib/zcode-limits.js +1172 -0
  121. package/src/lib/zcode-reset-credits.js +66 -0
  122. package/test/cli-smoke.test.js +53 -0
  123. package/test/ingest-sanitize.test.js +162 -0
  124. package/test/quiet-warnings.test.js +53 -0
  125. package/test/session-upload.test.js +427 -0
@@ -0,0 +1,4552 @@
1
+ const cp = require("node:child_process");
2
+ const crypto = require("node:crypto");
3
+ const fs = require("node:fs");
4
+ const os = require("node:os");
5
+ const path = require("node:path");
6
+ const http = require("node:http");
7
+ const https = require("node:https");
8
+ const { performance } = require("node:perf_hooks");
9
+ const { promisify } = require("node:util");
10
+
11
+ const {
12
+ detectClaudeCodeCredentialsPresence,
13
+ detectClaudeCodeSubscriptionDetails,
14
+ readClaudeCodeOauthToken,
15
+ readCodexAccessToken,
16
+ readCodexAuthBundle,
17
+ } = require("./subscriptions");
18
+ const {
19
+ isTokenStale,
20
+ refreshCodexTokens,
21
+ persistRefreshedAuth,
22
+ } = require("./codex-token-refresh");
23
+ const {
24
+ isCursorInstalled,
25
+ extractCursorAuth,
26
+ fetchCursorUsageSummary,
27
+ fetchCursorSandAccessStatus,
28
+ fetchCursorSandUsageStatus,
29
+ } = require("./cursor-config");
30
+ const { fetchGrokLimits } = require("./grok-limits");
31
+ const { fetchZcodeLimits } = require("./zcode-limits");
32
+ const { fetchOpencodeGoLimits } = require("./opencode-go-limits");
33
+ const { fetchCommandcodeLimits } = require("./commandcode-limits");
34
+ const { fetchDevinLimits } = require("./devin-limits");
35
+ const { fetchQoderLimits, fetchQoderCnLimits } = require("./qoder-limits");
36
+ const { fetchArkCodingPlanLimits } = require("./ark-coding-plan-limits");
37
+ const { fetchArkAgentPlanLimits } = require("./ark-agent-plan-limits");
38
+ const { fetchProviderServiceStatus } = require("./provider-status");
39
+ const { resolveKimiProfile } = require("./kimi-profile");
40
+ const { readSqliteJsonRows, readSqliteJsonRowsAsync } = require("./sqlite-reader");
41
+ const {
42
+ runCommand,
43
+ whichBinary,
44
+ isBinaryAvailable,
45
+ } = require("./command-runner");
46
+
47
+ const execFileAsync = promisify(cp.execFile);
48
+
49
+ // 2-minute in-memory cache. It also expires early at the earliest upcoming window
50
+ // reset in the cached data (see cacheExpiresAtMs), floored so a provider reporting
51
+ // a reset "right now" can't turn every poll into a full upstream round.
52
+ // Partitioned by the Devin opt-in selection AND the Antigravity quota opt-out, so
53
+ // a request made while Devin is off is never served (or joined onto) a response
54
+ // fetched while it was on, and an aggregate fetched while Antigravity was enabled
55
+ // is never served after the opt-out is set. Key = `${devin}-${antigravity}`.
56
+ const USAGE_LIMITS_SELECTION_KEYS = ["off-on", "off-off", "on-on", "on-off"];
57
+ const cacheBySelection = {};
58
+ for (const key of USAGE_LIMITS_SELECTION_KEYS) cacheBySelection[key] = { data: null, expiresAtMs: 0 };
59
+ function usageLimitsSelectionKey(options) {
60
+ const devin = options?.devinEnabled === true ? "on" : "off";
61
+ const antigravity = isAntigravityQuotaDisabled() ? "off" : "on";
62
+ return `${devin}-${antigravity}`;
63
+ }
64
+ const CACHE_TTL_MS = 2 * 60 * 1000;
65
+ // Must stay below the macOS app's post-reset re-fetch grace (10s in
66
+ // DashboardViewModel.resetBoundaryGrace), or that targeted refresh would be
67
+ // served this cache's pre-reset snapshot and miss the rollover.
68
+ const CACHE_MIN_TTL_MS = 5 * 1000;
69
+ const DEFAULT_PROVIDER_TIMEOUT_MS = 15_000;
70
+ const ANTIGRAVITY_LIMITS_CACHE_FILE = "usage-limits-cache.json";
71
+ const ANTIGRAVITY_LIMITS_CACHE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
72
+ const ANTIGRAVITY_LIMITS_CACHE_UNKNOWN_RESET_TTL_MS = 12 * 60 * 60 * 1000;
73
+ // Well-known public OAuth client for Google Antigravity, embedded in the agy
74
+ // binary. Installed-app OAuth clients cannot keep a confidential secret, so
75
+ // this is public, not a leaked credential. The client secret is assembled
76
+ // from parts (not a single literal) to avoid GitHub secret-scanning push-protection
77
+ // false positives on a value published in the distributed binary.
78
+ const ANTIGRAVITY_OAUTH_CLIENT_ID = "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com";
79
+ const ANTIGRAVITY_OAUTH_CLIENT_SECRET = Object.freeze([
80
+ "GOCSPX",
81
+ [
82
+ "K58FWR48",
83
+ "6LdLJ1mL",
84
+ "B8sXC4z6qDAf",
85
+ ].join(""),
86
+ ]).join("-");
87
+ const ANTIGRAVITY_OAUTH_TOKEN_URL = "https://oauth2.googleapis.com/token";
88
+ const ANTIGRAVITY_LOAD_CODE_ASSIST_URL = "https://daily-cloudcode-pa.googleapis.com/v1internal:loadCodeAssist";
89
+ // The daily- host is what the Antigravity app uses. The unprefixed host often
90
+ // returns remainingFraction=1 for Gemini buckets (looks like 100% free).
91
+ const ANTIGRAVITY_QUOTA_SUMMARY_URLS = Object.freeze([
92
+ "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary",
93
+ "https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary",
94
+ ]);
95
+ const ANTIGRAVITY_USER_AGENT = "antigravity/2.9.1";
96
+ const ANTIGRAVITY_TOKEN_REFRESH_SKEW_MS = 60 * 1000;
97
+ // Per-step ceilings for the Antigravity serial chain. `providerTimeoutMs` bounds the
98
+ // whole chain (see fetchAntigravityLimits); these only cap a single step, so one slow
99
+ // call cannot spend a budget that later steps — and the cache fallback — still need.
100
+ // Every step's effective timeout is min(ceiling, remaining budget − guard).
101
+ const ANTIGRAVITY_REMOTE_TIMEOUT_MS = 8000;
102
+ const ANTIGRAVITY_PROCESS_SCAN_TIMEOUT_MS = 4000;
103
+ const ANTIGRAVITY_LOCAL_REQUEST_TIMEOUT_MS = 8000;
104
+ // Reserved tail of the provider budget. Without it the chain can consume the budget
105
+ // right up to the outer race, leaving no time for readAntigravityLimitsCache — the
106
+ // user would get a red error instead of the stale-but-usable bars the cache exists for.
107
+ // Proportional with an absolute cap: a flat reserve larger than the whole budget would
108
+ // skip every step and guarantee the error it exists to prevent.
109
+ const ANTIGRAVITY_BUDGET_GUARD_MS = 1500;
110
+ const ANTIGRAVITY_BUDGET_GUARD_FRACTION = 0.15;
111
+ const ANTIGRAVITY_BUDGET_EXHAUSTED_MESSAGE = "Antigravity quota lookup timed out.";
112
+ const ANTIGRAVITY_AUTH_EXPIRED_MESSAGE = "Not logged in to Antigravity. Launch Antigravity once to authenticate.";
113
+ const ANTIGRAVITY_NOT_RUNNING_MESSAGE = "Antigravity IDE is not running. Launch Antigravity to see usage limits.";
114
+ // Claude shares its OAuth usage endpoint budget with Claude Code itself, so a transient
115
+ // 429 is common. Persist the last successful read so the panel can keep showing it instead
116
+ // of flashing a red error. Separate file from Antigravity's (whose writer rewrites the whole
117
+ // file with only its own key, so a shared file would clobber).
118
+ const CLAUDE_LIMITS_CACHE_FILE = "claude-usage-limits-cache.json";
119
+ const CLAUDE_LIMITS_CACHE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
120
+ const CLAUDE_LIMITS_CACHE_FRESH_TTL_MS = 10 * 60 * 1000;
121
+ // Longer than the fresh TTL, so a prompt made after a snapshot was written always
122
+ // falls inside it (see claudeCacheAwaitsNewWindow).
123
+ const CLAUDE_UNSTARTED_WINDOW_RETRY_MS = 15 * 60 * 1000;
124
+ // Codex has no rate-limit cooldown like Claude, but its two sequential chatgpt.com requests
125
+ // (/wham/usage + /wham/rate-limit-reset-credits) make it the provider most exposed to slow
126
+ // networks. Persist the last successful read so a timeout serves stale bars instead of a red
127
+ // error, mirroring the Claude stale-fallback path.
128
+ const CODEX_LIMITS_CACHE_FILE = "codex-usage-limits-cache.json";
129
+ const CODEX_LIMITS_CACHE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
130
+ // OpenCode Go hits opencode.ai over the public internet (15s timeout) with no local CLI to
131
+ // fall back on. A transient 5xx / timeout previously left the panel blank until the next
132
+ // 2-minute poll — persist the last successful windows so a blip serves stale bars instead
133
+ // of a flash of "fetch failed" (mirrors Claude / Codex / Antigravity).
134
+ const OPENCODE_GO_LIMITS_CACHE_FILE = "opencode-go-usage-limits-cache.json";
135
+ const OPENCODE_GO_LIMITS_CACHE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
136
+ const OPENCODE_GO_LOCAL_ESTIMATE_CACHE_MAX_AGE_MS = 60 * 60 * 1000;
137
+ // A 429 from the usage endpoint carries a long `retry-after` (often 20+ minutes). Persist
138
+ // the cooldown so every surface — this process, the menu bar app's embedded server, a later
139
+ // restart — stops calling until it expires. Hammering during the cooldown just renews the
140
+ // penalty, which is what kept the panel stuck on the error.
141
+ const CLAUDE_RATE_LIMIT_FILE = "claude-usage-rate-limit.json";
142
+ const KIRO_CREDITS_SIDECAR_FILE = "kiro-credits.json";
143
+ const CLAUDE_RATE_LIMIT_DEFAULT_COOLDOWN_SEC = 5 * 60;
144
+ const CLAUDE_RATE_LIMIT_MAX_COOLDOWN_SEC = 60 * 60;
145
+
146
+ function clampPercent(value) {
147
+ if (value === null || value === undefined || value === "") return null;
148
+ const n = Number(value);
149
+ if (!Number.isFinite(n)) return null;
150
+ if (n <= 0) return 0;
151
+ if (n >= 100) return 100;
152
+ return n;
153
+ }
154
+
155
+ function toFiniteNumberOrNull(value) {
156
+ if (value === null || value === undefined || value === "") return null;
157
+ const n = Number(value);
158
+ return Number.isFinite(n) ? n : null;
159
+ }
160
+
161
+ function buildWindow({ usedPercent, resetAt, windowSeconds = null }) {
162
+ const pct = clampPercent(usedPercent);
163
+ if (pct === null) return null;
164
+ const window = {
165
+ used_percent: pct,
166
+ reset_at: typeof resetAt === "string" && resetAt ? resetAt : null,
167
+ };
168
+ if (Number.isFinite(windowSeconds) && windowSeconds > 0) {
169
+ window.limit_window_seconds = windowSeconds;
170
+ }
171
+ return window;
172
+ }
173
+
174
+ function decodeJwtPayload(token) {
175
+ if (typeof token !== "string" || token.length === 0) return null;
176
+ const parts = token.split(".");
177
+ if (parts.length < 2) return null;
178
+ const payload = parts[1];
179
+ const padLen = (4 - (payload.length % 4)) % 4;
180
+ const padded = payload + "=".repeat(padLen);
181
+ const base64 = padded.replace(/-/g, "+").replace(/_/g, "/");
182
+ try {
183
+ return JSON.parse(Buffer.from(base64, "base64").toString("utf8"));
184
+ } catch (_error) {
185
+ return null;
186
+ }
187
+ }
188
+
189
+ function sleepMs(ms) {
190
+ return new Promise((resolve) => setTimeout(resolve, ms));
191
+ }
192
+
193
+ function mergeAbortSignals(signalA, signalB) {
194
+ if (!signalA) return signalB;
195
+ if (!signalB) return signalA;
196
+ if (typeof AbortSignal.any === "function") {
197
+ return AbortSignal.any([signalA, signalB]);
198
+ }
199
+ return signalA;
200
+ }
201
+
202
+ function withFetchTimeout(fetchImpl, timeoutMs) {
203
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return fetchImpl;
204
+ return (url, options = {}) => {
205
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
206
+ return fetchImpl(url, {
207
+ ...options,
208
+ signal: mergeAbortSignals(options.signal, timeoutSignal),
209
+ });
210
+ };
211
+ }
212
+
213
+ function withProviderTimeout(promise, label, timeoutMs) {
214
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return promise;
215
+ let timer;
216
+ const timeout = new Promise((_, reject) => {
217
+ timer = setTimeout(() => {
218
+ reject(new Error(`${label} usage request timed out.`));
219
+ }, timeoutMs);
220
+ });
221
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
222
+ }
223
+
224
+ // Provider timeouts normally race a promise so that an uncooperative remote
225
+ // request cannot block all limit reads. Local CLI providers also need an abort
226
+ // signal: without it, their spawned commands may continue after the caller has
227
+ // already received a timeout result.
228
+ function withAbortableProviderTimeout(start, label, timeoutMs) {
229
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return start(undefined);
230
+ const controller = new AbortController();
231
+ return withProviderTimeout(start(controller.signal), label, timeoutMs)
232
+ .finally(() => controller.abort());
233
+ }
234
+
235
+ function parseRetryAfterSeconds(headers) {
236
+ const ra = headers?.get ? headers.get("retry-after") : null;
237
+ const sec = ra ? Number.parseInt(ra, 10) : NaN;
238
+ return Number.isFinite(sec) && sec > 0 ? sec : null;
239
+ }
240
+
241
+ function formatClaudeRateLimitMessage(retryAfterSec) {
242
+ if (Number.isFinite(retryAfterSec) && retryAfterSec > 0) {
243
+ const mins = Math.ceil(retryAfterSec / 60);
244
+ return `Claude API rate limited (429) — retry in ~${mins}m.`;
245
+ }
246
+ return "Claude API rate limited (429) — retry shortly.";
247
+ }
248
+
249
+ // Model-scoped weekly windows (e.g. Fable) arrive only in the newer generic `limits`
250
+ // array (`kind: "weekly_scoped"` + `scope.model.display_name`) — the legacy top-level
251
+ // fields (`seven_day_opus` etc.) stay null for them. Extract them into
252
+ // `weekly_scoped: [{ label, utilization, resets_at }]`. Entries that duplicate a
253
+ // populated legacy field (an "Opus" scoped entry alongside `seven_day_opus`) are
254
+ // dropped so the same window never renders twice.
255
+ function extractClaudeScopedWeekly(body) {
256
+ if (!Array.isArray(body?.limits)) return null;
257
+ const out = [];
258
+ for (const entry of body.limits) {
259
+ if (!entry || typeof entry !== "object" || entry.kind !== "weekly_scoped") continue;
260
+ const model = entry.scope?.model;
261
+ const label = typeof model?.display_name === "string" && model.display_name.trim()
262
+ ? model.display_name.trim()
263
+ : typeof model?.id === "string" && model.id.trim() ? model.id.trim() : null;
264
+ if (!label) continue;
265
+ if (body.seven_day_opus && label.toLowerCase() === "opus") continue;
266
+ const utilization = Number(entry.percent);
267
+ if (!Number.isFinite(utilization)) continue;
268
+ out.push({
269
+ label,
270
+ utilization,
271
+ resets_at: typeof entry.resets_at === "string" ? entry.resets_at : null,
272
+ });
273
+ }
274
+ return out.length > 0 ? out : null;
275
+ }
276
+
277
+ // Shared by the 401 path below and by the blank-credential path in getUsageLimits:
278
+ // both mean "the CLI login no longer works", and both are fixed the same way.
279
+ const CLAUDE_AUTH_EXPIRED_MESSAGE = "Claude token expired — run `claude` once to refresh.";
280
+
281
+ async function fetchClaudeUsageLimits(accessToken, { fetchImpl = fetch, maxAttempts = 3 } = {}) {
282
+ const url = "https://api.anthropic.com/api/oauth/usage";
283
+ const headers = {
284
+ Authorization: `Bearer ${accessToken}`,
285
+ "anthropic-beta": "oauth-2025-04-20",
286
+ Accept: "application/json",
287
+ };
288
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
289
+ const res = await fetchImpl(url, { method: "GET", headers });
290
+ if (res.status === 401) {
291
+ const err = new Error(CLAUDE_AUTH_EXPIRED_MESSAGE);
292
+ err.code = "AUTH_EXPIRED";
293
+ throw err;
294
+ }
295
+ if ((res.status === 429 || res.status === 503) && attempt < maxAttempts - 1) {
296
+ const ra = res.headers.get("retry-after");
297
+ const sec = ra ? Number.parseInt(ra, 10) : NaN;
298
+ const delayMs = Number.isFinite(sec) && sec > 0 ? Math.min(sec * 1000, 30_000) : 1500 * (attempt + 1);
299
+ await sleepMs(delayMs);
300
+ continue;
301
+ }
302
+ if (!res.ok) {
303
+ if (res.status === 429) {
304
+ const retryAfterSec = parseRetryAfterSeconds(res.headers);
305
+ const err = new Error(formatClaudeRateLimitMessage(retryAfterSec));
306
+ err.code = "RATE_LIMITED";
307
+ err.retryAfterSec = retryAfterSec;
308
+ throw err;
309
+ }
310
+ throw new Error(`Claude API returned ${res.status}`);
311
+ }
312
+ const body = await res.json();
313
+ return mapClaudeUsageBody(body);
314
+ }
315
+ }
316
+
317
+ /** Map an /api/oauth/usage body (live, or Claude Code's cached copy) onto the limits shape. */
318
+ function mapClaudeUsageBody(body) {
319
+ return {
320
+ five_hour: body?.five_hour ?? null,
321
+ seven_day: body?.seven_day ?? null,
322
+ seven_day_opus: body?.seven_day_opus ?? null,
323
+ weekly_scoped: extractClaudeScopedWeekly(body),
324
+ extra_usage: body?.extra_usage ?? null,
325
+ };
326
+ }
327
+
328
+ // Classify a wham window by `limit_window_seconds` rather than its slot name.
329
+ // 18000s = 5h session window. 604800s = 7d weekly window. Free-tier accounts only get a
330
+ // weekly window, often delivered in the `primary_window` slot — naive position-based
331
+ // reading mislabels it as "5h". Aligned with steipete/CodexBar's rate-window normalizer.
332
+ const CODEX_SESSION_WINDOW_SECONDS = 18000;
333
+ const CODEX_WEEKLY_WINDOW_SECONDS = 604800;
334
+ const CODEX_RESET_CREDIT_LIST_TIMEOUT_MS = 3000;
335
+ const CODEX_RESET_CREDIT_LIST_TIMEOUT_GUARD_MS = 25;
336
+
337
+ function classifyCodexWindow(window) {
338
+ if (!window || typeof window !== "object") return null;
339
+ const seconds = Number(window.limit_window_seconds);
340
+ if (!Number.isFinite(seconds)) return null;
341
+ if (seconds === CODEX_SESSION_WINDOW_SECONDS) return "session";
342
+ if (seconds === CODEX_WEEKLY_WINDOW_SECONDS) return "weekly";
343
+ return null;
344
+ }
345
+
346
+ function normalizeCodexRateWindow(window) {
347
+ if (!window || typeof window !== "object" || Array.isArray(window)) return null;
348
+ const usedPercent = clampPercent(window.used_percent);
349
+ if (usedPercent === null) return null;
350
+ return {
351
+ ...window,
352
+ used_percent: Math.round(usedPercent),
353
+ };
354
+ }
355
+
356
+ function normalizeCodexRateWindows(rateLimit) {
357
+ const primary = normalizeCodexRateWindow(rateLimit?.primary_window);
358
+ const secondary = normalizeCodexRateWindow(rateLimit?.secondary_window);
359
+ const candidates = [primary, secondary].filter(Boolean);
360
+ let session = null;
361
+ let weekly = null;
362
+ for (const w of candidates) {
363
+ const kind = classifyCodexWindow(w);
364
+ if (kind === "session" && !session) session = w;
365
+ else if (kind === "weekly" && !weekly) weekly = w;
366
+ }
367
+ // Fall back to positional read only if classification failed for both — preserves data
368
+ // from unexpected window durations rather than dropping it silently.
369
+ if (!session && !weekly && candidates.length > 0) {
370
+ return {
371
+ primary_window: primary,
372
+ secondary_window: secondary,
373
+ };
374
+ }
375
+ return { primary_window: session, secondary_window: weekly };
376
+ }
377
+
378
+ function normalizeCodexCreditWindow(individualLimit) {
379
+ if (!individualLimit || typeof individualLimit !== "object" || Array.isArray(individualLimit)) {
380
+ return null;
381
+ }
382
+
383
+ const limitCredits = toFiniteNumberOrNull(individualLimit.limit);
384
+ const usedCredits = toFiniteNumberOrNull(individualLimit.used);
385
+ const remainingCredits = toFiniteNumberOrNull(individualLimit.remaining);
386
+
387
+ let usedPercent = clampPercent(individualLimit.used_percent);
388
+ if (limitCredits && limitCredits > 0 && usedCredits !== null) {
389
+ const derivedUsedPercent = clampPercent((usedCredits / limitCredits) * 100);
390
+ if (derivedUsedPercent !== null && (usedPercent === null || (usedPercent === 0 && usedCredits > 0))) {
391
+ usedPercent = derivedUsedPercent;
392
+ }
393
+ }
394
+
395
+ let remainingPercent = clampPercent(individualLimit.remaining_percent);
396
+ if (limitCredits && limitCredits > 0 && remainingCredits !== null) {
397
+ const derivedRemainingPercent = clampPercent((remainingCredits / limitCredits) * 100);
398
+ if (
399
+ derivedRemainingPercent !== null
400
+ && (remainingPercent === null || (remainingPercent === 100 && (usedCredits || 0) > 0))
401
+ ) {
402
+ remainingPercent = derivedRemainingPercent;
403
+ }
404
+ }
405
+
406
+ const resetAt = toFiniteNumberOrNull(individualLimit.reset_at);
407
+ const source = typeof individualLimit.source === "string" && individualLimit.source.trim()
408
+ ? individualLimit.source.trim()
409
+ : null;
410
+
411
+ if (
412
+ usedPercent === null
413
+ && limitCredits === null
414
+ && usedCredits === null
415
+ && remainingCredits === null
416
+ && resetAt === null
417
+ ) {
418
+ return null;
419
+ }
420
+
421
+ return {
422
+ source,
423
+ used_percent: usedPercent ?? 0,
424
+ remaining_percent: remainingPercent,
425
+ reset_at: resetAt,
426
+ limit_credits: limitCredits,
427
+ used_credits: usedCredits,
428
+ remaining_credits: remainingCredits,
429
+ };
430
+ }
431
+
432
+ function isCodexSparkLimit(entry) {
433
+ if (!entry || typeof entry !== "object") return false;
434
+ return [entry.limit_name, entry.metered_feature].some((value) => (
435
+ typeof value === "string" && value.trim().toLowerCase().includes("spark")
436
+ ));
437
+ }
438
+
439
+ function codexSparkFallbackCandidates(primary, secondary) {
440
+ const primaryKind = classifyCodexWindow(primary);
441
+ const secondaryKind = classifyCodexWindow(secondary);
442
+ const out = [];
443
+ const primaryDurationMissing = primary
444
+ && (primary.limit_window_seconds === undefined
445
+ || primary.limit_window_seconds === null
446
+ || primary.limit_window_seconds === "");
447
+
448
+ if (primaryKind || secondaryKind) {
449
+ if (!primaryKind && primary && secondaryKind === "weekly") {
450
+ out.push({ kind: "session", window: primary });
451
+ }
452
+ if (!primaryKind && primaryDurationMissing && secondaryKind === "session") {
453
+ out.push({ kind: "weekly", window: primary });
454
+ }
455
+ if (!secondaryKind && secondary && primaryKind === "weekly") {
456
+ out.push({ kind: "session", window: secondary });
457
+ }
458
+ if (!secondaryKind && secondary && primaryKind === "session") {
459
+ out.push({ kind: "weekly", window: secondary });
460
+ }
461
+ return out;
462
+ }
463
+
464
+ if (primary) out.push({ kind: "session", window: primary });
465
+ if (secondary) out.push({ kind: "weekly", window: secondary });
466
+ return out;
467
+ }
468
+
469
+ function normalizeCodexSparkRateWindows(additionalRateLimits) {
470
+ let session = null;
471
+ let weekly = null;
472
+ if (!Array.isArray(additionalRateLimits)) {
473
+ return { spark_primary_window: null, spark_secondary_window: null };
474
+ }
475
+
476
+ const classifiedCandidates = [];
477
+ const fallbackCandidates = [];
478
+ for (const entry of additionalRateLimits) {
479
+ if (!isCodexSparkLimit(entry)) continue;
480
+ const rateLimit = entry.rate_limit;
481
+ if (!rateLimit || typeof rateLimit !== "object") continue;
482
+
483
+ const primary = normalizeCodexRateWindow(rateLimit.primary_window);
484
+ const secondary = normalizeCodexRateWindow(rateLimit.secondary_window);
485
+ for (const window of [primary, secondary]) {
486
+ const kind = classifyCodexWindow(window);
487
+ if (kind) classifiedCandidates.push({ kind, window });
488
+ }
489
+ fallbackCandidates.push(...codexSparkFallbackCandidates(primary, secondary));
490
+ }
491
+
492
+ for (const candidate of classifiedCandidates) {
493
+ if (candidate.kind === "session" && !session) session = candidate.window;
494
+ else if (candidate.kind === "weekly" && !weekly) weekly = candidate.window;
495
+ }
496
+ for (const candidate of fallbackCandidates) {
497
+ if (candidate.kind === "session" && !session) session = candidate.window;
498
+ else if (candidate.kind === "weekly" && !weekly) weekly = candidate.window;
499
+ }
500
+
501
+ return {
502
+ spark_primary_window: session,
503
+ spark_secondary_window: weekly,
504
+ };
505
+ }
506
+
507
+ function normalizeCodexResetCreditCount(value) {
508
+ return Number.isInteger(value) && value >= 0 ? value : null;
509
+ }
510
+
511
+ function normalizeCodexResetCredit(row, nowMs) {
512
+ if (!row || typeof row !== "object" || Array.isArray(row)) return null;
513
+ if (row.status !== "available") return null;
514
+
515
+ const hasResetType = row.reset_type !== undefined && row.reset_type !== null;
516
+ if (hasResetType && row.reset_type !== "codex_rate_limits") return null;
517
+
518
+ const expiresAt = row.expires_at;
519
+ if (typeof expiresAt !== "string") return null;
520
+ const expiresAtMs = Date.parse(expiresAt);
521
+ if (!Number.isFinite(expiresAtMs) || expiresAtMs < nowMs) return null;
522
+
523
+ const credit = {
524
+ status: row.status,
525
+ expires_at: expiresAt,
526
+ };
527
+ if (typeof row.reset_type === "string") {
528
+ credit.reset_type = row.reset_type;
529
+ }
530
+ if (typeof row.granted_at === "string") {
531
+ credit.granted_at = row.granted_at;
532
+ }
533
+ return { credit, expiresAtMs };
534
+ }
535
+
536
+ function normalizeCodexResetCredits(resetCredits, nowMs = Date.now()) {
537
+ if (!resetCredits || typeof resetCredits !== "object" || Array.isArray(resetCredits)) return null;
538
+
539
+ const availableCount = normalizeCodexResetCreditCount(resetCredits.available_count);
540
+ const totalEarnedCount = normalizeCodexResetCreditCount(resetCredits.total_earned_count);
541
+ const normalized = [];
542
+ if (Array.isArray(resetCredits.credits) && availableCount !== 0) {
543
+ for (const row of resetCredits.credits) {
544
+ const entry = normalizeCodexResetCredit(row, nowMs);
545
+ if (entry) normalized.push(entry);
546
+ }
547
+ }
548
+
549
+ const credits = normalized
550
+ .sort((a, b) => a.expiresAtMs - b.expiresAtMs)
551
+ .slice(0, 50)
552
+ .map((entry) => entry.credit);
553
+
554
+ if (availableCount === null && totalEarnedCount === null && credits.length === 0) {
555
+ return null;
556
+ }
557
+
558
+ return {
559
+ available_count: availableCount,
560
+ total_earned_count: totalEarnedCount,
561
+ credits: availableCount === 0 ? [] : credits,
562
+ };
563
+ }
564
+
565
+ function codexResetCreditListTimeoutMs(remainingProviderBudgetMs) {
566
+ if (!Number.isFinite(remainingProviderBudgetMs)) {
567
+ return CODEX_RESET_CREDIT_LIST_TIMEOUT_MS;
568
+ }
569
+ if (remainingProviderBudgetMs <= 0) return 0;
570
+ const guardedBudgetMs = Math.floor(remainingProviderBudgetMs - CODEX_RESET_CREDIT_LIST_TIMEOUT_GUARD_MS);
571
+ if (guardedBudgetMs <= 0) return 0;
572
+ return Math.min(CODEX_RESET_CREDIT_LIST_TIMEOUT_MS, guardedBudgetMs);
573
+ }
574
+
575
+ async function fetchCodexResetCreditList(fetchImpl, headers, timeoutMs = CODEX_RESET_CREDIT_LIST_TIMEOUT_MS) {
576
+ let timer = null;
577
+ try {
578
+ const request = Promise.resolve()
579
+ .then(() => fetchImpl("https://chatgpt.com/backend-api/wham/rate-limit-reset-credits", {
580
+ method: "GET",
581
+ headers,
582
+ }))
583
+ .then(async (res) => {
584
+ if (!res.ok) return null;
585
+ return normalizeCodexResetCredits(await res.json());
586
+ });
587
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
588
+ return await request;
589
+ }
590
+ const timeout = new Promise((resolve) => {
591
+ timer = setTimeout(() => resolve(null), timeoutMs);
592
+ });
593
+ return await Promise.race([request, timeout]);
594
+ } catch (_err) {
595
+ return null;
596
+ } finally {
597
+ if (timer) clearTimeout(timer);
598
+ }
599
+ }
600
+
601
+ async function fetchCodexUsageLimits(
602
+ accessToken,
603
+ { fetchImpl = fetch, accountId = null, providerTimeoutMs = DEFAULT_PROVIDER_TIMEOUT_MS } = {},
604
+ ) {
605
+ const headers = {
606
+ Authorization: `Bearer ${accessToken}`,
607
+ Accept: "application/json",
608
+ };
609
+ // The wham endpoint rejects some plan tiers without an explicit account id — match
610
+ // CodexBar's request shape so free / multi-account users don't see opaque 4xx.
611
+ if (accountId) {
612
+ headers["ChatGPT-Account-Id"] = accountId;
613
+ }
614
+
615
+ const startedAtMs = performance.now();
616
+ const usage = await withProviderTimeout(Promise.resolve()
617
+ .then(() => fetchImpl("https://chatgpt.com/backend-api/wham/usage", {
618
+ method: "GET",
619
+ headers,
620
+ }))
621
+ .then(async (res) => {
622
+ // 401/403/404 from wham means "no usage data available for this auth state" — render
623
+ // a neutral empty state instead of a red "Fetch failed" error.
624
+ if (res.status === 401 || res.status === 403 || res.status === 404) {
625
+ return { body: null, status: res.status };
626
+ }
627
+ if (res.status !== 200) {
628
+ throw new Error(`Codex API returned ${res.status}`);
629
+ }
630
+ return { body: await res.json(), status: res.status };
631
+ }), "Codex", providerTimeoutMs);
632
+ if (!usage.body) {
633
+ return {
634
+ upstream_status: usage.status,
635
+ primary_window: null,
636
+ secondary_window: null,
637
+ credit_window: null,
638
+ spark_primary_window: null,
639
+ spark_secondary_window: null,
640
+ reset_credits: null,
641
+ };
642
+ }
643
+ const body = usage.body;
644
+ let resetCredits = normalizeCodexResetCredits(body.rate_limit_reset_credits);
645
+ // This semi-private sibling endpoint is read-only; /wham/usage remains the stable count fallback.
646
+ const remainingProviderBudgetMs = Number.isFinite(providerTimeoutMs) && providerTimeoutMs > 0
647
+ ? providerTimeoutMs - (performance.now() - startedAtMs)
648
+ : CODEX_RESET_CREDIT_LIST_TIMEOUT_MS;
649
+ const resetCreditListTimeoutMs = codexResetCreditListTimeoutMs(remainingProviderBudgetMs);
650
+ if (resetCreditListTimeoutMs > 0) {
651
+ const resetCreditsList = await fetchCodexResetCreditList(
652
+ fetchImpl,
653
+ headers,
654
+ resetCreditListTimeoutMs,
655
+ );
656
+ if (resetCreditsList) {
657
+ resetCredits = resetCreditsList;
658
+ }
659
+ }
660
+ return {
661
+ upstream_status: usage.status,
662
+ ...normalizeCodexRateWindows(body.rate_limit || {}),
663
+ credit_window: normalizeCodexCreditWindow(body.spend_control?.individual_limit),
664
+ ...normalizeCodexSparkRateWindows(body.additional_rate_limits),
665
+ reset_credits: resetCredits,
666
+ };
667
+ }
668
+
669
+ function cursorPercentFromCentsUsedLimit(usedRaw, limitRaw) {
670
+ const used = Number(usedRaw);
671
+ const limit = Number(limitRaw);
672
+ if (!Number.isFinite(used) || !Number.isFinite(limit) || limit <= 0) return null;
673
+ return clampPercent((used / limit) * 100);
674
+ }
675
+
676
+ function normalizeCursorUsageSummary(body) {
677
+ const plan = body?.individualUsage?.plan || null;
678
+ const indOnDemand = body?.individualUsage?.onDemand || null;
679
+ const teamOnDemand = body?.teamUsage?.onDemand || null;
680
+ const billingCycleStart = typeof body?.billingCycleStart === "string" ? body.billingCycleStart : null;
681
+ const billingCycleEnd = typeof body?.billingCycleEnd === "string" ? body.billingCycleEnd : null;
682
+ const billingCycleStartMs = Date.parse(billingCycleStart || "");
683
+ const billingCycleEndMs = Date.parse(billingCycleEnd || "");
684
+ const billingCycleSeconds = Number.isFinite(billingCycleStartMs)
685
+ && Number.isFinite(billingCycleEndMs)
686
+ && billingCycleEndMs > billingCycleStartMs
687
+ ? Math.round((billingCycleEndMs - billingCycleStartMs) / 1000)
688
+ : null;
689
+ const autoPercent = clampPercent(plan?.autoPercentUsed);
690
+ const apiPercent = clampPercent(plan?.apiPercentUsed);
691
+
692
+ // Prefer totalPercentUsed, then Auto/API lanes (aligned with CodexBar): raw plan used/limit
693
+ // are often cents where limit can be price/cap semantics — do not prefer that over percent lanes.
694
+ let planPercent = clampPercent(plan?.totalPercentUsed);
695
+ if (planPercent === null) {
696
+ if (autoPercent !== null && apiPercent !== null) {
697
+ planPercent = clampPercent((autoPercent + apiPercent) / 2);
698
+ } else if (apiPercent !== null) {
699
+ planPercent = apiPercent;
700
+ } else if (autoPercent !== null) {
701
+ planPercent = autoPercent;
702
+ } else {
703
+ const fromPlanCents = cursorPercentFromCentsUsedLimit(plan?.used, plan?.limit);
704
+ if (fromPlanCents !== null) planPercent = fromPlanCents;
705
+ }
706
+ }
707
+ if (planPercent === null) {
708
+ const fromInd = cursorPercentFromCentsUsedLimit(indOnDemand?.used, indOnDemand?.limit);
709
+ if (fromInd !== null) planPercent = fromInd;
710
+ }
711
+ if (planPercent === null) {
712
+ const fromTeam = cursorPercentFromCentsUsedLimit(teamOnDemand?.used, teamOnDemand?.limit);
713
+ if (fromTeam !== null) planPercent = fromTeam;
714
+ }
715
+ // Enterprise / team: individualUsage.plan often stays at 0% while pooled usage is on teamUsage.onDemand.
716
+ if (planPercent === 0) {
717
+ const fromInd = cursorPercentFromCentsUsedLimit(indOnDemand?.used, indOnDemand?.limit);
718
+ if (fromInd !== null && fromInd > 0) planPercent = fromInd;
719
+ }
720
+ if (planPercent === 0) {
721
+ const fromTeam = cursorPercentFromCentsUsedLimit(teamOnDemand?.used, teamOnDemand?.limit);
722
+ if (fromTeam !== null && fromTeam > 0) planPercent = fromTeam;
723
+ }
724
+
725
+ // Team / enterprise: headline usage is the pooled quota (teamUsage.onDemand), not individual lanes.
726
+ const limitType = typeof body?.limitType === "string" ? body.limitType : "";
727
+ const membershipTypeStr = typeof body?.membershipType === "string" ? body.membershipType : "";
728
+ const preferTeamPool =
729
+ limitType === "team" ||
730
+ membershipTypeStr === "enterprise" ||
731
+ membershipTypeStr === "team";
732
+ if (preferTeamPool) {
733
+ const teamHeadline = cursorPercentFromCentsUsedLimit(teamOnDemand?.used, teamOnDemand?.limit);
734
+ if (teamHeadline !== null && (planPercent === null || planPercent === 0)) {
735
+ planPercent = teamHeadline;
736
+ }
737
+ }
738
+
739
+ return {
740
+ membership_type: typeof body?.membershipType === "string" ? body.membershipType : null,
741
+ primary_window: buildWindow({ usedPercent: planPercent, resetAt: billingCycleEnd, windowSeconds: billingCycleSeconds }),
742
+ secondary_window: buildWindow({ usedPercent: autoPercent, resetAt: billingCycleEnd, windowSeconds: billingCycleSeconds }),
743
+ tertiary_window: buildWindow({ usedPercent: apiPercent, resetAt: billingCycleEnd, windowSeconds: billingCycleSeconds }),
744
+ };
745
+ }
746
+
747
+ /**
748
+ * Cursor's Sand "Grok Bot" RPC reports the shared Super weekly pool (same
749
+ * reset and about the same percent as Grok billing's creditUsagePercent).
750
+ * Once the Grok card lists a Grok Bot product share, that Sand bar would
751
+ * show the whole pool a second time under Cursor. Hide it only in that
752
+ * case. A real separate Sand quota (different reset, or a percent more than
753
+ * a point away from the pool) stays. Accounts with no Grok Bot product row
754
+ * keep the Sand bar.
755
+ */
756
+ function cursorSandDuplicatesGrokPool(cursor, grok) {
757
+ const sand = cursor?.quaternary_window;
758
+ const pool = grok?.primary_window;
759
+ if (!sand || !pool || cursor?.error || grok?.error) return false;
760
+ const products = Array.isArray(grok.products) ? grok.products : [];
761
+ if (!products.some((entry) => entry?.product === "GrokBot" && entry.window)) return false;
762
+ const sandReset = Date.parse(sand.reset_at || "");
763
+ const poolReset = Date.parse(pool.reset_at || "");
764
+ // Same instant. Two seconds covers one side dropping milliseconds.
765
+ // A different billing window is days apart, so it still stays visible.
766
+ if (!Number.isFinite(sandReset) || !Number.isFinite(poolReset)) return false;
767
+ if (Math.abs(sandReset - poolReset) > 2000) return false;
768
+ const sandPct = Number(sand.used_percent);
769
+ const poolPct = Number(pool.used_percent);
770
+ if (!Number.isFinite(sandPct) || !Number.isFinite(poolPct)) return false;
771
+ return Math.abs(sandPct - poolPct) <= 1;
772
+ }
773
+
774
+ function normalizeCursorSandUsageStatus(body, { eligible = true } = {}) {
775
+ if (!eligible || !body || body.includedLimitZero === true) return null;
776
+ const usedPercent = clampPercent(body.usagePercent);
777
+ const resetAt = typeof body.nextResetAt === "string" ? body.nextResetAt : null;
778
+ if (usedPercent === null || !resetAt || !Number.isFinite(Date.parse(resetAt))) return null;
779
+
780
+ const periodStart = typeof body.currentPeriodStart === "string" ? body.currentPeriodStart : null;
781
+ const periodStartMs = Date.parse(periodStart || "");
782
+ const resetAtMs = Date.parse(resetAt);
783
+ const windowSeconds = Number.isFinite(periodStartMs) && resetAtMs > periodStartMs
784
+ ? Math.round((resetAtMs - periodStartMs) / 1000)
785
+ : null;
786
+ return buildWindow({ usedPercent, resetAt, windowSeconds });
787
+ }
788
+
789
+ async function fetchCursorLimits({ home, fetchImpl = fetch } = {}) {
790
+ if (!isCursorInstalled({ home })) {
791
+ return { configured: false };
792
+ }
793
+ const auth = extractCursorAuth({ home });
794
+ if (!auth?.cookie || !auth?.accessToken) {
795
+ return { configured: false };
796
+ }
797
+ try {
798
+ // The web summary and Grok Bot (internally "Sand") RPCs are independent.
799
+ // Fetch them concurrently so the fourth window does not add two network
800
+ // round-trips to every LIMITS refresh. Sand failures are intentionally
801
+ // isolated: older Cursor accounts/servers must keep their existing three
802
+ // monthly windows instead of turning the whole provider red.
803
+ const [body, sandAccessResult, sandUsageResult] = await Promise.all([
804
+ fetchCursorUsageSummary({ cookie: auth.cookie, fetchImpl }),
805
+ fetchCursorSandAccessStatus({ accessToken: auth.accessToken, fetchImpl }).catch(() => null),
806
+ fetchCursorSandUsageStatus({ accessToken: auth.accessToken, fetchImpl }).catch(() => null),
807
+ ]);
808
+ const grokBotWindow = normalizeCursorSandUsageStatus(sandUsageResult, {
809
+ eligible: sandAccessResult?.granted === true,
810
+ });
811
+ return {
812
+ configured: true,
813
+ error: null,
814
+ ...normalizeCursorUsageSummary(body),
815
+ quaternary_window: grokBotWindow,
816
+ };
817
+ } catch (error) {
818
+ return {
819
+ configured: true,
820
+ error: error?.message || "Unknown error",
821
+ };
822
+ }
823
+ }
824
+
825
+ function loadKimiCredentials({ home, env, profile = resolveKimiProfile({ home, env }) } = {}) {
826
+ if (profile.error) return null;
827
+ const { credsPath } = profile;
828
+ if (!fs.existsSync(credsPath)) return null;
829
+ try {
830
+ return JSON.parse(fs.readFileSync(credsPath, "utf8"));
831
+ } catch (_error) {
832
+ return null;
833
+ }
834
+ }
835
+
836
+ function saveKimiCredentials(creds, { home, env, profile = resolveKimiProfile({ home, env }) } = {}) {
837
+ const { credsPath } = profile;
838
+ fs.mkdirSync(path.dirname(credsPath), { recursive: true });
839
+ fs.writeFileSync(credsPath, JSON.stringify(creds, null, 2), { mode: 0o600 });
840
+ }
841
+
842
+ function kimiNumber(value) {
843
+ if (value === null || value === undefined || value === "") return null;
844
+ const n = Number(value);
845
+ return Number.isFinite(n) ? n : null;
846
+ }
847
+
848
+ function kimiResetTime(value) {
849
+ if (typeof value !== "string" || !value) return null;
850
+ const ts = Date.parse(value);
851
+ return Number.isFinite(ts) && ts > 0 ? new Date(ts).toISOString() : null;
852
+ }
853
+
854
+ function kimiWindowFromUsage(data) {
855
+ if (!data || typeof data !== "object") return null;
856
+ const limit = kimiNumber(data.limit);
857
+ if (!Number.isFinite(limit) || limit <= 0) return null;
858
+ let used = kimiNumber(data.used);
859
+ if (used === null) {
860
+ const remaining = kimiNumber(data.remaining);
861
+ if (remaining !== null) used = limit - remaining;
862
+ }
863
+ if (!Number.isFinite(used)) return null;
864
+ return buildWindow({
865
+ usedPercent: (used / limit) * 100,
866
+ resetAt: kimiResetTime(data.resetTime || data.reset_at || data.resetAt),
867
+ });
868
+ }
869
+
870
+ function normalizeKimiUsageResponse(body) {
871
+ const firstLimit = Array.isArray(body?.limits) ? body.limits[0] : null;
872
+ const detail = firstLimit?.detail && typeof firstLimit.detail === "object" ? firstLimit.detail : firstLimit;
873
+ const parallelLimit = kimiNumber(body?.parallel?.limit);
874
+
875
+ return {
876
+ membership_level: typeof body?.user?.membership?.level === "string" ? body.user.membership.level : null,
877
+ subscription_type: typeof body?.subType === "string" ? body.subType : null,
878
+ parallel_limit: parallelLimit !== null ? parallelLimit : null,
879
+ primary_window: kimiWindowFromUsage(body?.usage),
880
+ secondary_window: kimiWindowFromUsage(detail),
881
+ tertiary_window: kimiWindowFromUsage(body?.totalQuota),
882
+ };
883
+ }
884
+
885
+ function kimiCredentialsExpired(creds, nowMs = Date.now()) {
886
+ const expiresAt = Number(creds?.expires_at);
887
+ if (!Number.isFinite(expiresAt) || expiresAt <= 0) return false;
888
+ return expiresAt * 1000 <= nowMs + 30_000;
889
+ }
890
+
891
+ async function refreshKimiAccessToken({ refreshToken, profile, fetchImpl = fetch } = {}) {
892
+ if (typeof refreshToken !== "string" || !refreshToken.trim()) {
893
+ throw new Error("Not logged in to Kimi. Run 'kimi' in Terminal to authenticate.");
894
+ }
895
+
896
+ const body = new URLSearchParams({
897
+ client_id: "17e5f671-d194-4dfb-9706-5516cb48c098",
898
+ grant_type: "refresh_token",
899
+ refresh_token: refreshToken,
900
+ });
901
+
902
+ const res = await fetchImpl(`${profile.oauthHost}/api/oauth/token`, {
903
+ method: "POST",
904
+ redirect: "error",
905
+ headers: {
906
+ "Content-Type": "application/x-www-form-urlencoded",
907
+ "X-Msh-Platform": "kimi_cli",
908
+ },
909
+ body,
910
+ });
911
+ if (res.status === 401 || res.status === 403) {
912
+ throw new Error("Not logged in to Kimi. Run 'kimi' in Terminal to authenticate.");
913
+ }
914
+ if (!res.ok) {
915
+ throw new Error(`Kimi token refresh failed (HTTP ${res.status})`);
916
+ }
917
+
918
+ const json = await res.json();
919
+ if (!json?.access_token) {
920
+ throw new Error("Could not parse Kimi token refresh response");
921
+ }
922
+
923
+ const expiresIn = Number(json.expires_in);
924
+ const next = {
925
+ access_token: String(json.access_token),
926
+ refresh_token: String(json.refresh_token || refreshToken),
927
+ expires_at: Date.now() / 1000 + (Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : 900),
928
+ scope: String(json.scope || "kimi-code"),
929
+ token_type: String(json.token_type || "Bearer"),
930
+ expires_in: Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : 900,
931
+ };
932
+ saveKimiCredentials(next, { profile });
933
+ return next.access_token;
934
+ }
935
+
936
+ async function fetchKimiUsage(accessToken, { profile, fetchImpl = fetch } = {}) {
937
+ const res = await fetchImpl(`${profile.baseUrl}/usages`, {
938
+ method: "GET",
939
+ redirect: "error",
940
+ headers: {
941
+ Authorization: `Bearer ${accessToken}`,
942
+ Accept: "application/json",
943
+ },
944
+ });
945
+ if (res.status === 401) {
946
+ throw new Error("token_expired");
947
+ }
948
+ if (!res.ok) {
949
+ throw new Error(`Kimi API returned ${res.status}`);
950
+ }
951
+ return res.json();
952
+ }
953
+
954
+ async function fetchKimiLimits({ home, env, fetchImpl = fetch } = {}) {
955
+ const profile = resolveKimiProfile({ home, env });
956
+ if (!profile.configured) {
957
+ return { configured: false };
958
+ }
959
+ if (profile.error) return { configured: true, error: profile.error };
960
+ const creds = loadKimiCredentials({ profile });
961
+ let accessToken = typeof creds?.access_token === "string" ? creds.access_token.trim() : "";
962
+ if (!accessToken) {
963
+ return { configured: false };
964
+ }
965
+ try {
966
+ if (kimiCredentialsExpired(creds) && creds?.refresh_token) {
967
+ accessToken = await refreshKimiAccessToken({
968
+ refreshToken: creds.refresh_token,
969
+ profile,
970
+ fetchImpl,
971
+ });
972
+ }
973
+ let body;
974
+ try {
975
+ body = await fetchKimiUsage(accessToken, { profile, fetchImpl });
976
+ } catch (error) {
977
+ if (error?.message === "token_expired" && creds?.refresh_token) {
978
+ accessToken = await refreshKimiAccessToken({
979
+ refreshToken: creds.refresh_token,
980
+ profile,
981
+ fetchImpl,
982
+ });
983
+ body = await fetchKimiUsage(accessToken, { profile, fetchImpl });
984
+ } else {
985
+ throw error;
986
+ }
987
+ }
988
+ return {
989
+ configured: true,
990
+ error: null,
991
+ ...normalizeKimiUsageResponse(body),
992
+ };
993
+ } catch (error) {
994
+ return {
995
+ configured: true,
996
+ error: error?.message || "Unknown error",
997
+ };
998
+ }
999
+ }
1000
+
1001
+ function resolveGeminiHome({ home, env } = {}) {
1002
+ const explicit = typeof env?.GEMINI_HOME === "string" ? env.GEMINI_HOME.trim() : "";
1003
+ return explicit ? path.resolve(explicit) : path.join(home, ".gemini");
1004
+ }
1005
+
1006
+ function loadGeminiSettings({ home, env } = {}) {
1007
+ const geminiHome = resolveGeminiHome({ home, env });
1008
+ const settingsPath = path.join(geminiHome, "settings.json");
1009
+ if (!fs.existsSync(settingsPath)) return null;
1010
+ try {
1011
+ return JSON.parse(fs.readFileSync(settingsPath, "utf8"));
1012
+ } catch (_error) {
1013
+ return null;
1014
+ }
1015
+ }
1016
+
1017
+ function loadGeminiCredentials({ home, env } = {}) {
1018
+ const geminiHome = resolveGeminiHome({ home, env });
1019
+ const credsPath = path.join(geminiHome, "oauth_creds.json");
1020
+ if (!fs.existsSync(credsPath)) return null;
1021
+ try {
1022
+ return JSON.parse(fs.readFileSync(credsPath, "utf8"));
1023
+ } catch (_error) {
1024
+ return null;
1025
+ }
1026
+ }
1027
+
1028
+ function resolveSymlinkOnce(filePath) {
1029
+ try {
1030
+ const resolved = fs.readlinkSync(filePath);
1031
+ return path.isAbsolute(resolved)
1032
+ ? resolved
1033
+ : path.join(path.dirname(filePath), resolved);
1034
+ } catch (_error) {
1035
+ return filePath;
1036
+ }
1037
+ }
1038
+
1039
+ function expandGeminiExecutableCandidates({ home } = {}) {
1040
+ const candidates = [];
1041
+ const add = (filePath) => {
1042
+ if (typeof filePath === "string" && filePath && !candidates.includes(filePath)) {
1043
+ candidates.push(filePath);
1044
+ }
1045
+ };
1046
+
1047
+ const nvmDir = path.join(home || os.homedir(), ".nvm", "versions", "node");
1048
+ try {
1049
+ for (const version of fs.readdirSync(nvmDir)) {
1050
+ add(path.join(nvmDir, version, "bin", "gemini"));
1051
+ }
1052
+ } catch (_error) {}
1053
+
1054
+ add(path.join(path.dirname(resolveSymlinkOnce(process.execPath)), "gemini"));
1055
+ add("/opt/homebrew/bin/gemini");
1056
+ add("/usr/local/bin/gemini");
1057
+
1058
+ return candidates;
1059
+ }
1060
+
1061
+ // Well-known public OAuth client for the Gemini CLI, shared with Google
1062
+ // Antigravity. These ship in the open-source gemini-cli repo
1063
+ // (packages/core/src/code_assist/oauth2.ts) — installed-app OAuth clients
1064
+ // cannot keep a confidential secret, so this is public, not a leaked
1065
+ // credential. The native Antigravity CLI ("agy") is a compiled binary with no
1066
+ // extractable oauth2.js, so when gemini-cli is not installed on disk (issue
1067
+ // #224) there is nothing to scrape; we fall back to these constants rather
1068
+ // than failing the token refresh outright. On-disk extraction is still tried
1069
+ // first so a newer client rotated into the gemini-cli bundle wins.
1070
+ // The client secret is assembled from parts (not a single literal) so it is
1071
+ // NOT confidential (see above) — this only avoids GitHub secret-scanning
1072
+ // push-protection false positives on a value that is published upstream.
1073
+ const GEMINI_CLI_FALLBACK_OAUTH_CLIENT = Object.freeze({
1074
+ clientId: "681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com",
1075
+ clientSecret: ["GOCSPX", "4uHgMPm", "1o7Sk", "geV6Cu5clXFsxl"].join("-"),
1076
+ });
1077
+
1078
+ async function extractGeminiOauthClientCredentials({ commandRunner, home } = {}) {
1079
+ const geminiPath = (await whichBinary("gemini", { commandRunner })) ?? "";
1080
+
1081
+ const geminiPaths = [
1082
+ ...(geminiPath ? [geminiPath] : []),
1083
+ ...expandGeminiExecutableCandidates({ home }),
1084
+ ];
1085
+
1086
+ for (const candidateGeminiPath of geminiPaths) {
1087
+ if (!fs.existsSync(candidateGeminiPath)) continue;
1088
+ const realPath = resolveSymlinkOnce(candidateGeminiPath);
1089
+ const binDir = path.dirname(realPath);
1090
+ const baseDir = path.dirname(binDir);
1091
+ const bundleDir = path.dirname(realPath);
1092
+ const candidates = [
1093
+ path.join(baseDir, "libexec/lib/node_modules/@google/gemini-cli/node_modules/@google/gemini-cli-core/dist/src/code_assist/oauth2.js"),
1094
+ path.join(baseDir, "lib/node_modules/@google/gemini-cli/node_modules/@google/gemini-cli-core/dist/src/code_assist/oauth2.js"),
1095
+ path.join(baseDir, "share/gemini-cli/node_modules/@google/gemini-cli-core/dist/src/code_assist/oauth2.js"),
1096
+ path.join(baseDir, "../gemini-cli-core/dist/src/code_assist/oauth2.js"),
1097
+ path.join(baseDir, "node_modules/@google/gemini-cli-core/dist/src/code_assist/oauth2.js"),
1098
+ ];
1099
+ if (path.basename(bundleDir) === "bundle") {
1100
+ candidates.push(realPath);
1101
+ try {
1102
+ for (const file of fs.readdirSync(bundleDir)) {
1103
+ if (/^chunk-.*\.js$/.test(file)) {
1104
+ candidates.push(path.join(bundleDir, file));
1105
+ }
1106
+ }
1107
+ } catch (_error) {}
1108
+ }
1109
+
1110
+ for (const candidate of candidates) {
1111
+ if (!fs.existsSync(candidate)) continue;
1112
+ try {
1113
+ const content = fs.readFileSync(candidate, "utf8");
1114
+ const clientId = content.match(/OAUTH_CLIENT_ID\s*=\s*['"]([^'"]+)['"]/)?.[1] || null;
1115
+ const clientSecret = content.match(/OAUTH_CLIENT_SECRET\s*=\s*['"]([^'"]+)['"]/)?.[1] || null;
1116
+ if (clientId && clientSecret) {
1117
+ return { clientId, clientSecret };
1118
+ }
1119
+ } catch (_error) {}
1120
+ }
1121
+ }
1122
+ // gemini-cli not installed (e.g. user switched to the native "agy" binary,
1123
+ // issue #224): no on-disk oauth2.js to scrape. Fall back to the public
1124
+ // Gemini CLI OAuth client so the token refresh can still proceed.
1125
+ return { ...GEMINI_CLI_FALLBACK_OAUTH_CLIENT };
1126
+ }
1127
+
1128
+ async function refreshGeminiAccessToken({
1129
+ refreshToken,
1130
+ home,
1131
+ env,
1132
+ fetchImpl = fetch,
1133
+ commandRunner,
1134
+ }) {
1135
+ const oauthClient = await extractGeminiOauthClientCredentials({ commandRunner, home });
1136
+ if (!oauthClient?.clientId || !oauthClient?.clientSecret) {
1137
+ throw new Error("Gemini API error: Could not find Gemini CLI OAuth configuration");
1138
+ }
1139
+
1140
+ const body = new URLSearchParams({
1141
+ client_id: oauthClient.clientId,
1142
+ client_secret: oauthClient.clientSecret,
1143
+ refresh_token: refreshToken,
1144
+ grant_type: "refresh_token",
1145
+ });
1146
+
1147
+ const res = await fetchImpl("https://oauth2.googleapis.com/token", {
1148
+ method: "POST",
1149
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
1150
+ body,
1151
+ });
1152
+ if (!res.ok) {
1153
+ throw new Error("Not logged in to Gemini. Run 'gemini' in Terminal to authenticate.");
1154
+ }
1155
+
1156
+ const json = await res.json();
1157
+ if (!json?.access_token) {
1158
+ throw new Error("Could not parse Gemini usage: invalid token refresh response");
1159
+ }
1160
+
1161
+ const geminiHome = resolveGeminiHome({ home, env });
1162
+ const credsPath = path.join(geminiHome, "oauth_creds.json");
1163
+ try {
1164
+ const creds = loadGeminiCredentials({ home, env }) || {};
1165
+ creds.access_token = json.access_token;
1166
+ if (json.id_token) creds.id_token = json.id_token;
1167
+ if (typeof json.expires_in === "number" && Number.isFinite(json.expires_in)) {
1168
+ creds.expiry_date = Date.now() + json.expires_in * 1000;
1169
+ }
1170
+ fs.writeFileSync(credsPath, JSON.stringify(creds, null, 2));
1171
+ } catch (_error) {}
1172
+
1173
+ return json.access_token;
1174
+ }
1175
+
1176
+ async function loadGeminiCodeAssistStatus(accessToken, { fetchImpl = fetch } = {}) {
1177
+ const res = await fetchImpl("https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist", {
1178
+ method: "POST",
1179
+ headers: {
1180
+ Authorization: `Bearer ${accessToken}`,
1181
+ "Content-Type": "application/json",
1182
+ },
1183
+ body: JSON.stringify({ metadata: { ideType: "GEMINI_CLI", pluginType: "GEMINI" } }),
1184
+ });
1185
+ if (!res.ok) {
1186
+ return { tier: null, projectId: null };
1187
+ }
1188
+ const json = await res.json();
1189
+ const tier = typeof json?.currentTier?.id === "string" ? json.currentTier.id : null;
1190
+ const rawProject = json?.cloudaicompanionProject;
1191
+ const projectId =
1192
+ typeof rawProject === "string"
1193
+ ? rawProject.trim() || null
1194
+ : typeof rawProject?.id === "string"
1195
+ ? rawProject.id
1196
+ : typeof rawProject?.projectId === "string"
1197
+ ? rawProject.projectId
1198
+ : null;
1199
+ return { tier, projectId };
1200
+ }
1201
+
1202
+ function normalizeGeminiModelBuckets(buckets) {
1203
+ if (!Array.isArray(buckets)) return [];
1204
+ const byModel = new Map();
1205
+ for (const bucket of buckets) {
1206
+ const modelId = typeof bucket?.modelId === "string" ? bucket.modelId : null;
1207
+ const remainingFraction = Number(bucket?.remainingFraction);
1208
+ if (!modelId || !Number.isFinite(remainingFraction)) continue;
1209
+ const existing = byModel.get(modelId);
1210
+ if (!existing || remainingFraction < existing.remainingFraction) {
1211
+ byModel.set(modelId, {
1212
+ model_id: modelId,
1213
+ remainingFraction,
1214
+ reset_at: parseAntigravityDate(bucket?.resetTime),
1215
+ });
1216
+ }
1217
+ }
1218
+ return Array.from(byModel.values()).sort((a, b) => a.model_id.localeCompare(b.model_id));
1219
+ }
1220
+
1221
+ function isGeminiFlashLiteModel(id) {
1222
+ return String(id || "").toLowerCase().includes("flash-lite");
1223
+ }
1224
+
1225
+ function isGeminiFlashModel(id) {
1226
+ const lower = String(id || "").toLowerCase();
1227
+ return lower.includes("flash") && !isGeminiFlashLiteModel(lower);
1228
+ }
1229
+
1230
+ function isGeminiProModel(id) {
1231
+ return String(id || "").toLowerCase().includes("pro");
1232
+ }
1233
+
1234
+ function normalizeGeminiQuotaResponse({ buckets, email, tier }) {
1235
+ const models = normalizeGeminiModelBuckets(buckets);
1236
+ if (!models.length) {
1237
+ throw new Error("Could not parse Gemini usage: no quota buckets in response");
1238
+ }
1239
+
1240
+ const pickLowest = (predicate) =>
1241
+ models
1242
+ .filter((model) => predicate(model.model_id))
1243
+ .sort((a, b) => a.remainingFraction - b.remainingFraction)[0] || null;
1244
+
1245
+ const plan =
1246
+ tier === "standard-tier"
1247
+ ? "Paid"
1248
+ : tier === "legacy-tier"
1249
+ ? "Legacy"
1250
+ : tier === "free-tier"
1251
+ ? "Free"
1252
+ : null;
1253
+
1254
+ const pro = pickLowest(isGeminiProModel);
1255
+ const flash = pickLowest(isGeminiFlashModel);
1256
+ const flashLite = pickLowest(isGeminiFlashLiteModel);
1257
+ const fallback = !pro && !flash && !flashLite
1258
+ ? [...models].sort((a, b) => a.remainingFraction - b.remainingFraction)[0]
1259
+ : null;
1260
+
1261
+ const toWindow = (model) =>
1262
+ model
1263
+ ? buildWindow({
1264
+ usedPercent: 100 - model.remainingFraction * 100,
1265
+ resetAt: model.reset_at,
1266
+ })
1267
+ : null;
1268
+
1269
+ return {
1270
+ account_email: email || null,
1271
+ account_plan: plan,
1272
+ primary_window: toWindow(pro || fallback),
1273
+ secondary_window: toWindow(flash),
1274
+ tertiary_window: toWindow(flashLite),
1275
+ };
1276
+ }
1277
+
1278
+ async function fetchGeminiLimits({ home, env, fetchImpl = fetch, commandRunner } = {}) {
1279
+ const settings = loadGeminiSettings({ home, env });
1280
+ const credentials = loadGeminiCredentials({ home, env });
1281
+ // Gemini is "configured" only if there are real OAuth credentials OR the
1282
+ // gemini CLI is installed. A bare ~/.gemini/settings.json is not enough:
1283
+ // sibling products (Antigravity) also live under ~/.gemini and would
1284
+ // otherwise surface a spurious "Not logged in to Gemini" card. Do NOT
1285
+ // require the binary when credentials exist — authenticated users on a
1286
+ // minimal launchd PATH have no `gemini` on PATH (issue #224).
1287
+ if (!credentials && !(await isBinaryAvailable("gemini", { commandRunner }))) {
1288
+ return { configured: false };
1289
+ }
1290
+ const selectedType = settings?.security?.auth?.selectedType ?? null;
1291
+ if (!settings && !credentials) {
1292
+ return { configured: false };
1293
+ }
1294
+ if (selectedType === "api-key") {
1295
+ return { configured: true, error: "Gemini API key auth not supported. Use Google account (OAuth) instead." };
1296
+ }
1297
+ if (selectedType === "vertex-ai") {
1298
+ return { configured: true, error: "Gemini Vertex AI auth not supported. Use Google account (OAuth) instead." };
1299
+ }
1300
+
1301
+ const creds = credentials;
1302
+ if (!creds?.access_token) {
1303
+ return { configured: true, error: "Not logged in to Gemini. Run 'gemini' in Terminal to authenticate." };
1304
+ }
1305
+
1306
+ try {
1307
+ let accessToken = creds.access_token;
1308
+ const expiry = Number(creds.expiry_date);
1309
+ if (Number.isFinite(expiry) && expiry > 0 && expiry < Date.now() && creds.refresh_token) {
1310
+ accessToken = await refreshGeminiAccessToken({
1311
+ refreshToken: creds.refresh_token,
1312
+ home,
1313
+ env,
1314
+ fetchImpl,
1315
+ commandRunner,
1316
+ });
1317
+ }
1318
+
1319
+ const claims = decodeJwtPayload(creds.id_token);
1320
+ const codeAssist = await loadGeminiCodeAssistStatus(accessToken, { fetchImpl });
1321
+ const res = await fetchImpl("https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota", {
1322
+ method: "POST",
1323
+ headers: {
1324
+ Authorization: `Bearer ${accessToken}`,
1325
+ "Content-Type": "application/json",
1326
+ },
1327
+ body: JSON.stringify(codeAssist.projectId ? { project: codeAssist.projectId } : {}),
1328
+ });
1329
+ if (res.status === 401) {
1330
+ throw new Error("Not logged in to Gemini. Run 'gemini' in Terminal to authenticate.");
1331
+ }
1332
+ if (!res.ok) {
1333
+ throw new Error(`Gemini API error: HTTP ${res.status}`);
1334
+ }
1335
+ const json = await res.json();
1336
+ return {
1337
+ configured: true,
1338
+ error: null,
1339
+ ...normalizeGeminiQuotaResponse({
1340
+ buckets: json?.buckets,
1341
+ email: claims?.email || null,
1342
+ tier: codeAssist.tier,
1343
+ }),
1344
+ };
1345
+ } catch (error) {
1346
+ return {
1347
+ configured: true,
1348
+ error: error?.message || "Unknown error",
1349
+ };
1350
+ }
1351
+ }
1352
+
1353
+ // runCommand / whichBinary / isBinaryAvailable now live in ./command-runner
1354
+ // (shared with ark-coding-plan-limits.js). The async runner there keeps the
1355
+ // same spawnSync-shaped contract: { status, stdout, stderr, error? }, and
1356
+ // injected test runners may stay synchronous.
1357
+
1358
+ function stripAnsi(text) {
1359
+ return String(text || "").replace(/\x1B\[[0-9;?]*[A-Za-z]|\x1B\].*?\x07/g, "");
1360
+ }
1361
+
1362
+ function extractFirstNumber(text) {
1363
+ const match = String(text || "").match(/-?\d+(?:\.\d+)?/);
1364
+ return match ? Number(match[0]) : null;
1365
+ }
1366
+
1367
+ function parseMonthDayResetDate(dateStr, now = new Date()) {
1368
+ if (typeof dateStr !== "string") return null;
1369
+ const match = dateStr.match(/(\d{2})\/(\d{2})/);
1370
+ if (!match) return null;
1371
+ const month = Number(match[1]);
1372
+ const day = Number(match[2]);
1373
+ if (!Number.isFinite(month) || !Number.isFinite(day)) return null;
1374
+ const currentYear = now.getUTCFullYear();
1375
+
1376
+ let candidate = new Date(Date.UTC(currentYear, month - 1, day, 0, 0, 0, 0));
1377
+ if (candidate.getTime() <= now.getTime()) {
1378
+ candidate = new Date(Date.UTC(currentYear + 1, month - 1, day, 0, 0, 0, 0));
1379
+ }
1380
+ return candidate.toISOString();
1381
+ }
1382
+
1383
+ function parseKiroResetDate(dateStr, now = new Date()) {
1384
+ if (typeof dateStr !== "string") return null;
1385
+ if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
1386
+ const candidate = new Date(`${dateStr}T00:00:00.000Z`);
1387
+ if (
1388
+ Number.isFinite(candidate.getTime()) &&
1389
+ candidate.toISOString().slice(0, 10) === dateStr
1390
+ ) {
1391
+ return candidate.toISOString();
1392
+ }
1393
+ return null;
1394
+ }
1395
+ return parseMonthDayResetDate(dateStr, now);
1396
+ }
1397
+
1398
+ function isKiroUsageOutputComplete(output) {
1399
+ try {
1400
+ parseKiroUsageOutput(output);
1401
+ return true;
1402
+ } catch (_error) {
1403
+ return false;
1404
+ }
1405
+ }
1406
+
1407
+ function parseKiroCliVersion(output) {
1408
+ const match = String(output || "").match(
1409
+ /(?:kiro-cli\s+)?(\d+)\.(\d+)\.(\d+)/i,
1410
+ );
1411
+ if (!match) return null;
1412
+ return {
1413
+ major: Number(match[1]),
1414
+ minor: Number(match[2]),
1415
+ patch: Number(match[3]),
1416
+ };
1417
+ }
1418
+
1419
+ function kiroCliRequiresPty(version) {
1420
+ if (!version) return false;
1421
+ if (version.major !== 2) return version.major > 2;
1422
+ return version.minor >= 13;
1423
+ }
1424
+
1425
+ function quotePosixShellArg(value) {
1426
+ return `'${String(value).replace(/'/g, `'"'"'`)}'`;
1427
+ }
1428
+
1429
+ function kiroPtyInvocation(binaryPath, args, platform = process.platform) {
1430
+ if (platform === "darwin") {
1431
+ return {
1432
+ command: "/usr/bin/script",
1433
+ args: ["-q", "/dev/null", binaryPath, ...args],
1434
+ };
1435
+ }
1436
+ if (platform === "linux") {
1437
+ const commandLine = [binaryPath, ...args]
1438
+ .map(quotePosixShellArg)
1439
+ .join(" ");
1440
+ return {
1441
+ command: "script",
1442
+ args: ["-q", "-c", commandLine, "/dev/null"],
1443
+ };
1444
+ }
1445
+ return null;
1446
+ }
1447
+
1448
+ function combineKiroCommandOutput(result) {
1449
+ const stdout =
1450
+ typeof result?.stdout === "string" ? result.stdout.trim() : "";
1451
+ const stderr =
1452
+ typeof result?.stderr === "string" ? result.stderr.trim() : "";
1453
+ return [stdout, stderr].filter(Boolean).join("\n");
1454
+ }
1455
+
1456
+ function parseKiroCommandResult(result, { now = new Date() } = {}) {
1457
+ const output = combineKiroCommandOutput(result);
1458
+ if (
1459
+ result?.error?.code === "ETIMEDOUT" &&
1460
+ !isKiroUsageOutputComplete(output)
1461
+ ) {
1462
+ throw new Error("Kiro CLI timed out.");
1463
+ }
1464
+ if (!output && result?.status !== 0) {
1465
+ const detail = result?.error?.message
1466
+ ? `: ${result.error.message}`
1467
+ : ".";
1468
+ throw new Error(`Kiro CLI failed with status ${result?.status ?? "unknown"}${detail}`);
1469
+ }
1470
+ return parseKiroUsageOutput(output, { now });
1471
+ }
1472
+
1473
+ function parseKiroUsageOutput(output, { now = new Date() } = {}) {
1474
+ const stripped = stripAnsi(output).trim();
1475
+ if (!stripped) {
1476
+ throw new Error("Failed to parse Kiro usage: empty output");
1477
+ }
1478
+
1479
+ const lowered = stripped.toLowerCase();
1480
+ if (
1481
+ lowered.includes("not logged in")
1482
+ || lowered.includes("login required")
1483
+ || lowered.includes("failed to initialize auth portal")
1484
+ || lowered.includes("kiro-cli login")
1485
+ || lowered.includes("oauth error")
1486
+ ) {
1487
+ throw new Error("Not logged in to Kiro. Run 'kiro-cli login' first.");
1488
+ }
1489
+ if (lowered.includes("could not retrieve usage information")) {
1490
+ throw new Error("Failed to parse Kiro usage: Kiro CLI could not retrieve usage information.");
1491
+ }
1492
+
1493
+ let planName = "Kiro";
1494
+ const legacyPlan = stripped.match(/\|\s*(KIRO\s+\w+)/);
1495
+ if (legacyPlan?.[1]) {
1496
+ planName = legacyPlan[1].trim();
1497
+ }
1498
+ const modernPlan = stripped.match(/Plan:\s*(.+)/);
1499
+ if (modernPlan?.[1]) {
1500
+ planName = modernPlan[1].split("\n")[0].trim() || planName;
1501
+ }
1502
+
1503
+ const resetMatch = stripped.match(
1504
+ /resets on (\d{4}-\d{2}-\d{2}|\d{2}\/\d{2})/i,
1505
+ );
1506
+ const primaryReset = resetMatch
1507
+ ? parseKiroResetDate(resetMatch[1], now)
1508
+ : null;
1509
+
1510
+ let creditsPercent = null;
1511
+ const percentMatch = stripped.match(/█+\s*(\d+)%/);
1512
+ if (percentMatch?.[1]) {
1513
+ creditsPercent = clampPercent(Number(percentMatch[1]));
1514
+ }
1515
+
1516
+ let creditsUsed = null;
1517
+ let creditsTotal = null;
1518
+ const coveredMatch = stripped.match(/\((\d+(?:\.\d+)?)\s+of\s+(\d+(?:\.\d+)?)\s+covered/i);
1519
+ if (coveredMatch?.[1] && coveredMatch?.[2]) {
1520
+ creditsUsed = Number(coveredMatch[1]);
1521
+ creditsTotal = Number(coveredMatch[2]);
1522
+ }
1523
+ if (creditsPercent === null && creditsUsed !== null && creditsTotal && creditsTotal > 0) {
1524
+ creditsPercent = clampPercent((creditsUsed / creditsTotal) * 100);
1525
+ }
1526
+
1527
+ const managedPlan = lowered.includes("managed by admin") || lowered.includes("managed by organization");
1528
+ if (creditsPercent === null && creditsUsed === null && managedPlan) {
1529
+ return {
1530
+ plan_name: planName,
1531
+ primary_window: buildWindow({ usedPercent: 0, resetAt: null }),
1532
+ secondary_window: null,
1533
+ };
1534
+ }
1535
+ if (creditsPercent === null && creditsUsed === null) {
1536
+ throw new Error("Failed to parse Kiro usage: usage output format may have changed.");
1537
+ }
1538
+
1539
+ let bonusWindow = null;
1540
+ const bonusMatch = stripped.match(/Bonus credits:[\s\S]*?(\d+(?:\.\d+)?)\/(\d+(?:\.\d+)?)/i);
1541
+ const expiryMatch = stripped.match(/expires in (\d+) days?/i);
1542
+ if (bonusMatch?.[1] && bonusMatch?.[2]) {
1543
+ const bonusUsed = Number(bonusMatch[1]);
1544
+ const bonusTotal = Number(bonusMatch[2]);
1545
+ const bonusPct = bonusTotal > 0 ? clampPercent((bonusUsed / bonusTotal) * 100) : 0;
1546
+ let bonusReset = null;
1547
+ if (expiryMatch?.[1]) {
1548
+ const days = Number(expiryMatch[1]);
1549
+ if (Number.isFinite(days) && days >= 0) {
1550
+ bonusReset = new Date(now.getTime() + days * 24 * 60 * 60 * 1000).toISOString();
1551
+ }
1552
+ }
1553
+ bonusWindow = buildWindow({ usedPercent: bonusPct, resetAt: bonusReset });
1554
+ }
1555
+
1556
+ return {
1557
+ plan_name: planName,
1558
+ primary_window: buildWindow({ usedPercent: creditsPercent, resetAt: primaryReset }),
1559
+ secondary_window: bonusWindow,
1560
+ };
1561
+ }
1562
+
1563
+ function readKiroCreditsSummary({ home = os.homedir() } = {}) {
1564
+ const sidecarPath = path.join(
1565
+ home,
1566
+ ".tokenusage",
1567
+ "tracker",
1568
+ KIRO_CREDITS_SIDECAR_FILE,
1569
+ );
1570
+ try {
1571
+ const parsed = JSON.parse(fs.readFileSync(sidecarPath, "utf8"));
1572
+ if (parsed?.version !== 1) return null;
1573
+ const totalCredits = Number(parsed.total_credits);
1574
+ const recordCount = Number(parsed.record_count);
1575
+ const sessionCount = Number(parsed.session_count);
1576
+ if (
1577
+ !Number.isFinite(totalCredits) ||
1578
+ totalCredits < 0 ||
1579
+ !Number.isSafeInteger(recordCount) ||
1580
+ recordCount <= 0 ||
1581
+ !Number.isSafeInteger(sessionCount) ||
1582
+ sessionCount <= 0
1583
+ ) {
1584
+ return null;
1585
+ }
1586
+ return {
1587
+ tracked_credits: totalCredits,
1588
+ tracked_credit_records: recordCount,
1589
+ tracked_credit_sessions: sessionCount,
1590
+ tracked_credits_latest_at:
1591
+ typeof parsed.latest_at === "string" ? parsed.latest_at : null,
1592
+ tracked_credits_updated_at:
1593
+ typeof parsed.updated_at === "string" ? parsed.updated_at : null,
1594
+ };
1595
+ } catch {
1596
+ return null;
1597
+ }
1598
+ }
1599
+
1600
+ // ─────────────────────────────────────────────────────────────────────────────
1601
+ // GitHub Copilot — `GET https://api.github.com/copilot_internal/user`
1602
+ // Reuses the OAuth token from the user's existing Copilot install. Older clients
1603
+ // keep it in plaintext (`~/.config/github-copilot/{apps,hosts}.json`); newer
1604
+ // copilot-language-server builds (Zed, copilot.vim) migrate it into SQLite
1605
+ // `auth.db`. Schema v0 stores the OAuth token as a plaintext BLOB, while later
1606
+ // schemas use AES-GCM ciphertext with the key in the OS credential store. Read
1607
+ // legacy plaintext first, then auth.db. No device flow needed either way.
1608
+ // ─────────────────────────────────────────────────────────────────────────────
1609
+
1610
+ const MACOS_SECURITY_BIN = "/usr/bin/security";
1611
+ // copilot-language-server stores the OAuth token as AES-256-GCM ciphertext in
1612
+ // auth.db (`oauth_tokens.token_ciphertext`) and the 32-byte key in the macOS
1613
+ // Keychain (service `copilot-language-server`, account `oauth-token-key`,
1614
+ // base64-encoded). Ciphertext layout: iv(12) ‖ ciphertext ‖ authTag(16).
1615
+ const COPILOT_LS_KEYCHAIN_SERVICE = "copilot-language-server";
1616
+ const COPILOT_LS_KEYCHAIN_ACCOUNT = "oauth-token-key";
1617
+ const COPILOT_AUTH_DB_SQL =
1618
+ "SELECT user_login, auth_authority, scopes, token_schema_version, hex(token_ciphertext) AS token_hex, "
1619
+ + "last_used_at, updated_at FROM oauth_tokens ORDER BY last_used_at DESC, updated_at DESC";
1620
+
1621
+ function readPlaintextCopilotOauthToken({ home }) {
1622
+ const candidates = [
1623
+ path.join(home, ".config", "github-copilot", "apps.json"),
1624
+ path.join(home, ".config", "github-copilot", "hosts.json"),
1625
+ ];
1626
+ // Keys are either "github.com", "github.example.com" (enterprise), or a
1627
+ // composite like "github.com:Iv1.b507a08c87ecfe98". We always hit
1628
+ // api.github.com, so prefer the public-host token; only fall back to
1629
+ // whatever's there if no public-host entry exists.
1630
+ let fallback = null;
1631
+ for (const filePath of candidates) {
1632
+ if (!fs.existsSync(filePath)) continue;
1633
+ let parsed;
1634
+ try {
1635
+ parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
1636
+ } catch (_e) {
1637
+ continue;
1638
+ }
1639
+ if (!parsed || typeof parsed !== "object") continue;
1640
+ for (const [key, value] of Object.entries(parsed)) {
1641
+ if (!value || typeof value !== "object") continue;
1642
+ const token = typeof value.oauth_token === "string" ? value.oauth_token : "";
1643
+ if (!token) continue;
1644
+ const host = String(key).split(":")[0];
1645
+ if (host === "github.com") return token;
1646
+ if (!fallback) fallback = token;
1647
+ }
1648
+ }
1649
+ return fallback;
1650
+ }
1651
+
1652
+ function readMacosKeychainGenericPassword({ service, account, securityRunner } = {}) {
1653
+ const runner = typeof securityRunner === "function" ? securityRunner : cp.spawnSync;
1654
+ if (runner === cp.spawnSync && !fs.existsSync(MACOS_SECURITY_BIN)) return null;
1655
+ const args = ["find-generic-password", "-s", service];
1656
+ if (account) args.push("-a", account);
1657
+ args.push("-w");
1658
+ const result = runner(MACOS_SECURITY_BIN, args, {
1659
+ stdio: ["ignore", "pipe", "ignore"],
1660
+ timeout: 2000,
1661
+ encoding: "utf8",
1662
+ });
1663
+ if (!result || result.error || result.status !== 0) return null;
1664
+ const stdout =
1665
+ typeof result.stdout === "string"
1666
+ ? result.stdout
1667
+ : Buffer.isBuffer(result.stdout)
1668
+ ? result.stdout.toString("utf8")
1669
+ : "";
1670
+ const trimmed = stdout.trim();
1671
+ return trimmed.length > 0 ? trimmed : null;
1672
+ }
1673
+
1674
+ async function readMacosKeychainGenericPasswordAsync({ service, account, securityRunner } = {}) {
1675
+ if (typeof securityRunner === "function") {
1676
+ return readMacosKeychainGenericPassword({ service, account, securityRunner });
1677
+ }
1678
+ if (!fs.existsSync(MACOS_SECURITY_BIN)) return null;
1679
+ const args = ["find-generic-password", "-s", service];
1680
+ if (account) args.push("-a", account);
1681
+ args.push("-w");
1682
+ try {
1683
+ const result = await execFileAsync(MACOS_SECURITY_BIN, args, {
1684
+ timeout: 2000,
1685
+ encoding: "utf8",
1686
+ });
1687
+ const stdout =
1688
+ typeof result?.stdout === "string"
1689
+ ? result.stdout
1690
+ : Buffer.isBuffer(result?.stdout)
1691
+ ? result.stdout.toString("utf8")
1692
+ : "";
1693
+ const trimmed = stdout.trim();
1694
+ return trimmed.length > 0 ? trimmed : null;
1695
+ } catch (_e) {
1696
+ return null;
1697
+ }
1698
+ }
1699
+
1700
+ function decryptCopilotAuthDbToken(keyBase64, ciphertextHex) {
1701
+ if (typeof keyBase64 !== "string" || typeof ciphertextHex !== "string") return null;
1702
+ let key;
1703
+ let blob;
1704
+ try {
1705
+ key = Buffer.from(keyBase64, "base64");
1706
+ blob = Buffer.from(ciphertextHex, "hex");
1707
+ } catch (_e) {
1708
+ return null;
1709
+ }
1710
+ if (key.length !== 32) return null; // AES-256 key
1711
+ if (blob.length < 12 + 16 + 1) return null; // iv(12) + authTag(16) + >=1 byte token
1712
+ const iv = blob.subarray(0, 12);
1713
+ const authTag = blob.subarray(blob.length - 16);
1714
+ const data = blob.subarray(12, blob.length - 16);
1715
+ try {
1716
+ const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
1717
+ decipher.setAuthTag(authTag);
1718
+ const out = Buffer.concat([decipher.update(data), decipher.final()]);
1719
+ const token = out.toString("utf8").trim();
1720
+ return token.length > 0 ? token : null;
1721
+ } catch (_e) {
1722
+ return null;
1723
+ }
1724
+ }
1725
+
1726
+ function isLikelyGithubOauthToken(token) {
1727
+ if (typeof token !== "string") return false;
1728
+ const trimmed = token.trim();
1729
+ return /^gh[opsur]_[A-Za-z0-9]{20,}$/.test(trimmed)
1730
+ || /^github_pat_[A-Za-z0-9_]{20,}$/.test(trimmed);
1731
+ }
1732
+
1733
+ function parseCopilotAuthDbSchemaVersion(value) {
1734
+ if (value === null || value === undefined || value === "") return null;
1735
+ const version = Number(value);
1736
+ return Number.isInteger(version) ? version : null;
1737
+ }
1738
+
1739
+ function decodeUtf8HexString(value) {
1740
+ if (typeof value !== "string" || !/^(?:[0-9a-f]{2})+$/i.test(value)) return null;
1741
+ try {
1742
+ return Buffer.from(value, "hex").toString("utf8").trim();
1743
+ } catch (_e) {
1744
+ return null;
1745
+ }
1746
+ }
1747
+
1748
+ function decodeCopilotSchemaV0Token(row) {
1749
+ const candidates = [];
1750
+ const tokenHex = typeof row?.token_hex === "string" ? row.token_hex : null;
1751
+ if (tokenHex) candidates.push(decodeUtf8HexString(tokenHex));
1752
+
1753
+ const rawCiphertext = row?.token_ciphertext;
1754
+ if (Buffer.isBuffer(rawCiphertext)) {
1755
+ candidates.push(rawCiphertext.toString("utf8").trim());
1756
+ } else if (typeof rawCiphertext === "string") {
1757
+ candidates.push(rawCiphertext.trim());
1758
+ candidates.push(decodeUtf8HexString(rawCiphertext));
1759
+ }
1760
+
1761
+ for (const candidate of candidates) {
1762
+ if (isLikelyGithubOauthToken(candidate)) return candidate.trim();
1763
+ }
1764
+ return null;
1765
+ }
1766
+
1767
+ function orderCopilotAuthDbRows(rows) {
1768
+ const githubRows = [];
1769
+ const fallbackRows = [];
1770
+ for (const row of rows) {
1771
+ const host = String(row?.auth_authority || "").split(":")[0];
1772
+ if (host === "github.com") {
1773
+ githubRows.push(row);
1774
+ } else {
1775
+ fallbackRows.push(row);
1776
+ }
1777
+ }
1778
+ return githubRows.concat(fallbackRows);
1779
+ }
1780
+
1781
+ function readCopilotAuthDbRows({ home, sqliteReader, asyncReader = false } = {}) {
1782
+ const resolvedHome = home || os.homedir();
1783
+ const dbPath = path.join(resolvedHome, ".config", "github-copilot", "auth.db");
1784
+ const reader = typeof sqliteReader === "function"
1785
+ ? sqliteReader
1786
+ : asyncReader
1787
+ ? readSqliteJsonRowsAsync
1788
+ : readSqliteJsonRows;
1789
+ return reader(dbPath, COPILOT_AUTH_DB_SQL, { label: "GitHub Copilot" });
1790
+ }
1791
+
1792
+ function resolveCopilotAuthDbTokenFromRows(rows, {
1793
+ platform = process.platform,
1794
+ securityRunner,
1795
+ keychainReader = readMacosKeychainGenericPassword,
1796
+ } = {}) {
1797
+ if (!Array.isArray(rows) || rows.length === 0) return null;
1798
+ // Prefer the public github.com host (mirrors the plaintext reader); rows are
1799
+ // already ordered most-recently-used first.
1800
+ const orderedRows = orderCopilotAuthDbRows(rows);
1801
+ let keyBase64 = null;
1802
+ let attemptedKeychain = false;
1803
+ for (const row of orderedRows) {
1804
+ const schemaVersion = parseCopilotAuthDbSchemaVersion(row?.token_schema_version);
1805
+ if (schemaVersion === 0) {
1806
+ const plaintextToken = decodeCopilotSchemaV0Token(row);
1807
+ if (plaintextToken) return plaintextToken;
1808
+ continue;
1809
+ }
1810
+
1811
+ const ciphertextHex = typeof row?.token_hex === "string" ? row.token_hex : null;
1812
+ if (!ciphertextHex || platform !== "darwin") continue;
1813
+ // The decryption key lives in the macOS Keychain. On Linux/Windows the
1814
+ // copilot-language-server uses libsecret / Credential Manager instead, which
1815
+ // we don't read yet.
1816
+ if (!attemptedKeychain) {
1817
+ keyBase64 = keychainReader({
1818
+ service: COPILOT_LS_KEYCHAIN_SERVICE,
1819
+ account: COPILOT_LS_KEYCHAIN_ACCOUNT,
1820
+ securityRunner,
1821
+ });
1822
+ attemptedKeychain = true;
1823
+ }
1824
+ if (!keyBase64) continue;
1825
+ const token = decryptCopilotAuthDbToken(keyBase64, ciphertextHex);
1826
+ if (token) return token;
1827
+ }
1828
+ return null;
1829
+ }
1830
+
1831
+ async function resolveCopilotAuthDbTokenFromRowsAsync(rows, {
1832
+ platform = process.platform,
1833
+ securityRunner,
1834
+ keychainReader = readMacosKeychainGenericPasswordAsync,
1835
+ } = {}) {
1836
+ if (!Array.isArray(rows) || rows.length === 0) return null;
1837
+ const orderedRows = orderCopilotAuthDbRows(rows);
1838
+ let keyBase64 = null;
1839
+ let attemptedKeychain = false;
1840
+ for (const row of orderedRows) {
1841
+ const schemaVersion = parseCopilotAuthDbSchemaVersion(row?.token_schema_version);
1842
+ if (schemaVersion === 0) {
1843
+ const plaintextToken = decodeCopilotSchemaV0Token(row);
1844
+ if (plaintextToken) return plaintextToken;
1845
+ continue;
1846
+ }
1847
+
1848
+ const ciphertextHex = typeof row?.token_hex === "string" ? row.token_hex : null;
1849
+ if (!ciphertextHex || platform !== "darwin") continue;
1850
+ if (!attemptedKeychain) {
1851
+ keyBase64 = await keychainReader({
1852
+ service: COPILOT_LS_KEYCHAIN_SERVICE,
1853
+ account: COPILOT_LS_KEYCHAIN_ACCOUNT,
1854
+ securityRunner,
1855
+ });
1856
+ attemptedKeychain = true;
1857
+ }
1858
+ if (!keyBase64) continue;
1859
+ const token = decryptCopilotAuthDbToken(keyBase64, ciphertextHex);
1860
+ if (token) return token;
1861
+ }
1862
+ return null;
1863
+ }
1864
+
1865
+ function readCopilotAuthDbToken({ home, platform = process.platform, securityRunner, sqliteReader } = {}) {
1866
+ let rows;
1867
+ try {
1868
+ rows = readCopilotAuthDbRows({ home, sqliteReader });
1869
+ } catch (_e) {
1870
+ return null;
1871
+ }
1872
+ return resolveCopilotAuthDbTokenFromRows(rows, { platform, securityRunner });
1873
+ }
1874
+
1875
+ async function readCopilotAuthDbTokenAsync({ home, platform = process.platform, securityRunner, sqliteReader } = {}) {
1876
+ let rows;
1877
+ try {
1878
+ rows = await readCopilotAuthDbRows({ home, sqliteReader, asyncReader: true });
1879
+ } catch (_e) {
1880
+ return null;
1881
+ }
1882
+ return resolveCopilotAuthDbTokenFromRowsAsync(rows, { platform, securityRunner });
1883
+ }
1884
+
1885
+ function readCopilotOauthToken({
1886
+ home = os.homedir(),
1887
+ platform = process.platform,
1888
+ securityRunner,
1889
+ sqliteReader,
1890
+ } = {}) {
1891
+ const plaintext = readPlaintextCopilotOauthToken({ home });
1892
+ if (plaintext) return plaintext;
1893
+ // No plaintext token found — recover the live one from the encrypted auth.db.
1894
+ return readCopilotAuthDbToken({ home, platform, securityRunner, sqliteReader });
1895
+ }
1896
+
1897
+ async function readCopilotOauthTokenAsync({
1898
+ home = os.homedir(),
1899
+ platform = process.platform,
1900
+ securityRunner,
1901
+ sqliteReader,
1902
+ } = {}) {
1903
+ const plaintext = readPlaintextCopilotOauthToken({ home });
1904
+ if (plaintext) return plaintext;
1905
+ return readCopilotAuthDbTokenAsync({ home, platform, securityRunner, sqliteReader });
1906
+ }
1907
+
1908
+ function copilotRequestHeaders(token) {
1909
+ return {
1910
+ Authorization: `token ${token}`,
1911
+ Accept: "application/json",
1912
+ "Editor-Version": "vscode/1.96.2",
1913
+ "Editor-Plugin-Version": "copilot-chat/0.26.7",
1914
+ "User-Agent": "GitHubCopilotChat/0.26.7",
1915
+ "X-Github-Api-Version": "2025-04-01",
1916
+ };
1917
+ }
1918
+
1919
+ function copilotResetIso(value) {
1920
+ if (typeof value !== "string" || !value.trim()) return null;
1921
+ const trimmed = value.trim();
1922
+ // Accept "YYYY-MM-DD" or full ISO timestamps
1923
+ const dateOnly = /^\d{4}-\d{2}-\d{2}$/.test(trimmed);
1924
+ const ts = Date.parse(dateOnly ? `${trimmed}T00:00:00Z` : trimmed);
1925
+ if (!Number.isFinite(ts)) return null;
1926
+ return new Date(ts).toISOString();
1927
+ }
1928
+
1929
+ function buildCopilotWindow(snapshot, resetIso) {
1930
+ if (!snapshot || typeof snapshot !== "object") return null;
1931
+ const entitlement = Number(snapshot.entitlement);
1932
+ const remaining = Number(snapshot.remaining);
1933
+ const percentRemaining = Number(snapshot.percent_remaining);
1934
+ const allZero = (!entitlement || entitlement <= 0) && (!remaining || remaining <= 0) && (!percentRemaining || percentRemaining <= 0);
1935
+ if (allZero) return null;
1936
+ let usedPercent;
1937
+ if (Number.isFinite(percentRemaining)) {
1938
+ usedPercent = 100 - percentRemaining;
1939
+ } else if (Number.isFinite(entitlement) && entitlement > 0 && Number.isFinite(remaining)) {
1940
+ usedPercent = ((entitlement - remaining) / entitlement) * 100;
1941
+ } else {
1942
+ return null;
1943
+ }
1944
+ return buildWindow({ usedPercent, resetAt: resetIso });
1945
+ }
1946
+
1947
+ function describeCopilotOtelStatus({ home, env = process.env } = {}) {
1948
+ const resolvedHome = home || env.HOME || os.homedir();
1949
+ const enabled = String(env.COPILOT_OTEL_ENABLED || "").toLowerCase() === "true";
1950
+ const exporterType = String(env.COPILOT_OTEL_EXPORTER_TYPE || "").toLowerCase();
1951
+ const explicitPath = typeof env.COPILOT_OTEL_FILE_EXPORTER_PATH === "string"
1952
+ ? env.COPILOT_OTEL_FILE_EXPORTER_PATH
1953
+ : "";
1954
+ const defaultDirs = [
1955
+ path.join(resolvedHome, ".copilot", "otel"),
1956
+ path.join(resolvedHome, ".copilot-otel"),
1957
+ ];
1958
+ const detectedPaths = [];
1959
+ for (const defaultDir of defaultDirs) {
1960
+ try {
1961
+ if (!fs.existsSync(defaultDir)) continue;
1962
+ for (const entry of fs.readdirSync(defaultDir)) {
1963
+ if (entry.endsWith(".jsonl")) {
1964
+ detectedPaths.push(path.join(defaultDir, entry));
1965
+ }
1966
+ }
1967
+ } catch (_e) {}
1968
+ }
1969
+ if (explicitPath && fs.existsSync(explicitPath)) detectedPaths.push(explicitPath);
1970
+ return {
1971
+ otel_enabled: enabled && (exporterType === "" || exporterType === "file"),
1972
+ otel_exporter_type: exporterType || null,
1973
+ otel_path: explicitPath || null,
1974
+ otel_default_dir: defaultDirs[0],
1975
+ otel_default_dirs: defaultDirs,
1976
+ otel_detected_paths: detectedPaths,
1977
+ otel_has_files: detectedPaths.length > 0,
1978
+ };
1979
+ }
1980
+
1981
+ async function fetchCopilotLimits({
1982
+ home,
1983
+ env = process.env,
1984
+ fetchImpl = fetch,
1985
+ platform = process.platform,
1986
+ securityRunner,
1987
+ sqliteReader,
1988
+ } = {}) {
1989
+ const otel = describeCopilotOtelStatus({ home, env });
1990
+ const token = await readCopilotOauthTokenAsync({
1991
+ home: home || (env.HOME || os.homedir()),
1992
+ platform,
1993
+ securityRunner,
1994
+ sqliteReader,
1995
+ });
1996
+ if (!token) return { configured: false, ...otel };
1997
+
1998
+ try {
1999
+ const res = await fetchImpl("https://api.github.com/copilot_internal/user", {
2000
+ method: "GET",
2001
+ headers: copilotRequestHeaders(token),
2002
+ });
2003
+ if (res.status === 401 || res.status === 403) {
2004
+ throw new Error("GitHub Copilot token rejected. Re-authenticate via GitHub Copilot CLI/extension.");
2005
+ }
2006
+ if (!res.ok) {
2007
+ throw new Error(`GitHub Copilot API error: HTTP ${res.status}`);
2008
+ }
2009
+ const json = await res.json();
2010
+ const planName = typeof json?.copilot_plan === "string" && json.copilot_plan
2011
+ ? json.copilot_plan.charAt(0).toUpperCase() + json.copilot_plan.slice(1)
2012
+ : null;
2013
+ const resetIso = copilotResetIso(json?.quota_reset_date);
2014
+ const snapshots = json?.quota_snapshots || {};
2015
+ const premiumWindow = buildCopilotWindow(snapshots.premium_interactions, resetIso);
2016
+ const chatWindow = buildCopilotWindow(snapshots.chat, resetIso);
2017
+
2018
+ if (!premiumWindow && !chatWindow) {
2019
+ return { configured: true, error: null, plan_name: planName, primary_window: null, secondary_window: null, ...otel };
2020
+ }
2021
+
2022
+ return {
2023
+ configured: true,
2024
+ error: null,
2025
+ plan_name: planName,
2026
+ primary_window: premiumWindow,
2027
+ secondary_window: chatWindow,
2028
+ ...otel,
2029
+ };
2030
+ } catch (error) {
2031
+ return { configured: true, error: error?.message || "Unknown error", ...otel };
2032
+ }
2033
+ }
2034
+
2035
+ async function fetchKiroLimits({
2036
+ commandRunner,
2037
+ now = new Date(),
2038
+ platform = process.platform,
2039
+ home = os.homedir(),
2040
+ } = {}) {
2041
+ const trackedCredits = readKiroCreditsSummary({ home });
2042
+ const binaryPath = await whichBinary("kiro-cli", { commandRunner });
2043
+ if (!binaryPath) {
2044
+ return trackedCredits
2045
+ ? { configured: true, error: null, ...trackedCredits }
2046
+ : { configured: false };
2047
+ }
2048
+
2049
+ const versionResult = await runCommand(
2050
+ commandRunner,
2051
+ binaryPath,
2052
+ ["--version"],
2053
+ {
2054
+ timeout: 2_000,
2055
+ env: { ...process.env, TERM: "xterm-256color" },
2056
+ },
2057
+ );
2058
+ const version = parseKiroCliVersion(
2059
+ combineKiroCommandOutput(versionResult),
2060
+ );
2061
+ const args = ["chat", "--no-interactive", "/usage"];
2062
+ const pty = kiroPtyInvocation(binaryPath, args, platform);
2063
+
2064
+ // Kiro CLI 2.13 changed pipe behavior: /usage is treated as a normal model
2065
+ // prompt without a terminal. Go straight to a PTY so a refresh does not
2066
+ // accidentally spend credits on an assistant response. Older/unknown builds
2067
+ // retain the existing pipe-first behavior, with a bounded PTY fallback if
2068
+ // the output is not a recognizable usage panel.
2069
+ const attempts = [];
2070
+ if (kiroCliRequiresPty(version)) {
2071
+ if (pty) attempts.push(pty);
2072
+ } else {
2073
+ attempts.push({ command: binaryPath, args });
2074
+ if (pty) attempts.push(pty);
2075
+ }
2076
+
2077
+ let lastError = null;
2078
+ try {
2079
+ if (attempts.length === 0) {
2080
+ throw new Error(
2081
+ `Kiro CLI ${version ? `${version.major}.${version.minor}.${version.patch}` : ""} requires a pseudo-terminal on ${platform}.`,
2082
+ );
2083
+ }
2084
+ for (const attempt of attempts) {
2085
+ const result = await runCommand(
2086
+ commandRunner,
2087
+ attempt.command,
2088
+ attempt.args,
2089
+ {
2090
+ timeout: 20_000,
2091
+ env: { ...process.env, TERM: "xterm-256color" },
2092
+ completeWhen: (stdout, stderr) =>
2093
+ isKiroUsageOutputComplete(`${stdout}\n${stderr}`),
2094
+ completionGraceMs: 750,
2095
+ killProcessGroup: Boolean(pty),
2096
+ },
2097
+ );
2098
+ try {
2099
+ return {
2100
+ configured: true,
2101
+ error: null,
2102
+ ...parseKiroCommandResult(result, { now }),
2103
+ ...(trackedCredits || {}),
2104
+ };
2105
+ } catch (error) {
2106
+ lastError = error;
2107
+ }
2108
+ }
2109
+ throw lastError || new Error("Failed to read Kiro usage.");
2110
+ } catch (error) {
2111
+ return {
2112
+ configured: true,
2113
+ error: error?.message || "Unknown error",
2114
+ ...(trackedCredits || {}),
2115
+ };
2116
+ }
2117
+ }
2118
+
2119
+ function parseProcessLine(line) {
2120
+ const match = String(line || "")
2121
+ .trim()
2122
+ .match(/^(\d+)\s+(.*)$/);
2123
+ if (!match) return null;
2124
+ return {
2125
+ pid: Number(match[1]),
2126
+ command: match[2],
2127
+ };
2128
+ }
2129
+
2130
+ function firstCommandToken(command) {
2131
+ const trimmed = String(command || "").trimStart();
2132
+ const quote = trimmed[0];
2133
+ if (quote === '"' || quote === "'") {
2134
+ const end = trimmed.indexOf(quote, 1);
2135
+ return end >= 0 ? trimmed.slice(1, end) : trimmed.slice(1);
2136
+ }
2137
+ return trimmed.split(/\s+/, 1)[0] || "";
2138
+ }
2139
+
2140
+ function isAntigravityCommandLine(command) {
2141
+ const raw = String(command || "");
2142
+ const lower = raw.toLowerCase();
2143
+ const executable = firstCommandToken(raw).split(/[\\/]/).pop() || "";
2144
+
2145
+ // The agy CLI binary itself runs as a server with Connect-RPC endpoints.
2146
+ // Match only the executable token's basename so absolute paths work without
2147
+ // treating arbitrary arguments like `vim /tmp/agy` as an Antigravity server.
2148
+ if (/^agy(?:\.exe)?$/i.test(executable)) return true;
2149
+
2150
+ // IDE language_server — only return true when accompanied by Antigravity-specific
2151
+ // markers so sibling Codeium products (Windsurf, etc.) are not misidentified.
2152
+ const hasLangServerBinary = /^language_server(?:_[a-z0-9]+)*(?:\.exe)?$/i.test(executable);
2153
+
2154
+ const hasAntigravityMarker =
2155
+ (lower.includes("--app_data_dir") && lower.includes("antigravity")) ||
2156
+ lower.includes("/antigravity/") ||
2157
+ lower.includes("/antigravity.app/") ||
2158
+ lower.includes("\\antigravity\\") ||
2159
+ /--override_ide_name(?:=|\s+)["']?antigravity\b/i.test(raw);
2160
+
2161
+ return hasLangServerBinary && hasAntigravityMarker;
2162
+ }
2163
+
2164
+ function extractCommandFlag(command, flag) {
2165
+ const escaped = flag.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2166
+ const match = String(command || "").match(new RegExp(`${escaped}[=\\s]+([^\\s]+)`, "i"));
2167
+ return match?.[1] || null;
2168
+ }
2169
+
2170
+ function parseWindowsProcesses(output) {
2171
+ let parsed;
2172
+ try {
2173
+ parsed = JSON.parse(String(output || "").trim());
2174
+ } catch (_error) {
2175
+ return [];
2176
+ }
2177
+ return (Array.isArray(parsed) ? parsed : [parsed])
2178
+ .map((entry) => ({
2179
+ pid: Number(entry?.ProcessId),
2180
+ command: typeof entry?.CommandLine === "string" ? entry.CommandLine : "",
2181
+ }))
2182
+ .filter((entry) => Number.isFinite(entry.pid) && entry.command);
2183
+ }
2184
+
2185
+ async function detectAntigravityProcess({
2186
+ commandRunner,
2187
+ platform = process.platform,
2188
+ timeoutMs = ANTIGRAVITY_PROCESS_SCAN_TIMEOUT_MS,
2189
+ signal,
2190
+ } = {}) {
2191
+ let processes;
2192
+ if (platform === "win32") {
2193
+ const script = [
2194
+ "$ErrorActionPreference = 'Stop'",
2195
+ "$processes = Get-CimInstance Win32_Process | Select-Object ProcessId, CommandLine",
2196
+ "ConvertTo-Json -Compress -InputObject @($processes)",
2197
+ ].join("; ");
2198
+ const result = await runCommand(
2199
+ commandRunner,
2200
+ "powershell.exe",
2201
+ ["-NoProfile", "-NonInteractive", "-Command", script],
2202
+ { timeout: timeoutMs, signal },
2203
+ );
2204
+ processes = parseWindowsProcesses(result?.stdout);
2205
+ } else {
2206
+ let result = await runCommand(commandRunner, "/bin/ps", ["-ax", "-o", "pid=,command="], {
2207
+ timeout: timeoutMs,
2208
+ signal,
2209
+ });
2210
+ const isSpawnFailure = result?.error
2211
+ && result.error.code !== "ETIMEDOUT"
2212
+ && result.error.name !== "AbortError";
2213
+ if (isSpawnFailure && !result?.stdout) {
2214
+ result = await runCommand(commandRunner, "ps", ["-ax", "-o", "pid=,command="], {
2215
+ timeout: timeoutMs,
2216
+ signal,
2217
+ });
2218
+ }
2219
+ processes = String(result?.stdout || "")
2220
+ .split("\n")
2221
+ .map(parseProcessLine)
2222
+ .filter(Boolean);
2223
+ }
2224
+
2225
+ let sawProcess = false;
2226
+ for (const parsed of processes) {
2227
+ if (!isAntigravityCommandLine(parsed.command)) continue;
2228
+ sawProcess = true;
2229
+ const csrfToken = extractCommandFlag(parsed.command, "--csrf_token") || null;
2230
+ const extensionPort = extractFirstNumber(extractCommandFlag(parsed.command, "--extension_server_port"));
2231
+ return {
2232
+ configured: true,
2233
+ pid: parsed.pid,
2234
+ csrfToken,
2235
+ extensionPort: Number.isFinite(extensionPort) ? extensionPort : null,
2236
+ };
2237
+ }
2238
+
2239
+ if (sawProcess) {
2240
+ return { configured: true, error: "Antigravity CSRF token not found. Restart Antigravity and retry." };
2241
+ }
2242
+ return { configured: false };
2243
+ }
2244
+
2245
+ function resolveAntigravityLimitsCachePath({ home } = {}) {
2246
+ return path.join(home || os.homedir(), ".tokenusage", "tracker", ANTIGRAVITY_LIMITS_CACHE_FILE);
2247
+ }
2248
+
2249
+ function parseTimeMs(value) {
2250
+ if (typeof value !== "string" || !value) return null;
2251
+ const ts = Date.parse(value);
2252
+ return Number.isFinite(ts) && ts > 0 ? ts : null;
2253
+ }
2254
+
2255
+ function isCacheWindowUsable(window, { cachedAtMs, nowMs } = {}) {
2256
+ if (!window || typeof window !== "object") return false;
2257
+ const resetAtMs = parseTimeMs(window.reset_at);
2258
+ if (resetAtMs !== null) return resetAtMs > nowMs;
2259
+ return Number.isFinite(cachedAtMs)
2260
+ && nowMs - cachedAtMs <= ANTIGRAVITY_LIMITS_CACHE_UNKNOWN_RESET_TTL_MS;
2261
+ }
2262
+
2263
+ function hasAntigravityWindow(limits) {
2264
+ return Boolean(limits?.primary_window || limits?.secondary_window || limits?.tertiary_window || limits?.quaternary_window);
2265
+ }
2266
+
2267
+ function normalizeAntigravityCachedLimits(raw, { nowMs = Date.now() } = {}) {
2268
+ const cachedAtMs = parseTimeMs(raw?.cached_at);
2269
+ if (!Number.isFinite(cachedAtMs)) return null;
2270
+ if (cachedAtMs > nowMs + 60_000) return null;
2271
+ if (nowMs - cachedAtMs > ANTIGRAVITY_LIMITS_CACHE_MAX_AGE_MS) return null;
2272
+
2273
+ const cached = {
2274
+ configured: true,
2275
+ error: null,
2276
+ account_email: typeof raw?.account_email === "string" ? raw.account_email : null,
2277
+ account_plan: typeof raw?.account_plan === "string" ? raw.account_plan : null,
2278
+ primary_window: isCacheWindowUsable(raw?.primary_window, { cachedAtMs, nowMs }) ? raw.primary_window : null,
2279
+ secondary_window: isCacheWindowUsable(raw?.secondary_window, { cachedAtMs, nowMs }) ? raw.secondary_window : null,
2280
+ tertiary_window: isCacheWindowUsable(raw?.tertiary_window, { cachedAtMs, nowMs }) ? raw.tertiary_window : null,
2281
+ quaternary_window: isCacheWindowUsable(raw?.quaternary_window, { cachedAtMs, nowMs }) ? raw.quaternary_window : null,
2282
+ cached: true,
2283
+ cached_at: raw.cached_at,
2284
+ };
2285
+ return hasAntigravityWindow(cached) ? cached : null;
2286
+ }
2287
+
2288
+ function isAntigravityQuotaDisabled() {
2289
+ return process.env.TOKENUSAGE_DISABLE_ANTIGRAVITY_QUOTA === "1";
2290
+ }
2291
+
2292
+ function readAntigravityLimitsCache({ home, nowMs = Date.now() } = {}) {
2293
+ if (isAntigravityQuotaDisabled()) return null;
2294
+ const cachePath = resolveAntigravityLimitsCachePath({ home });
2295
+ try {
2296
+ const parsed = JSON.parse(fs.readFileSync(cachePath, "utf8"));
2297
+ return normalizeAntigravityCachedLimits(parsed?.antigravity, { nowMs });
2298
+ } catch (_error) {
2299
+ return null;
2300
+ }
2301
+ }
2302
+
2303
+ function writeAntigravityLimitsCache(limits, { home, nowMs = Date.now() } = {}) {
2304
+ if (!limits?.configured || limits.error || !hasAntigravityWindow(limits)) return;
2305
+ const cachePath = resolveAntigravityLimitsCachePath({ home });
2306
+ const payload = {
2307
+ antigravity: {
2308
+ account_email: limits.account_email || null,
2309
+ account_plan: limits.account_plan || null,
2310
+ primary_window: limits.primary_window || null,
2311
+ secondary_window: limits.secondary_window || null,
2312
+ tertiary_window: limits.tertiary_window || null,
2313
+ quaternary_window: limits.quaternary_window || null,
2314
+ cached_at: new Date(nowMs).toISOString(),
2315
+ },
2316
+ };
2317
+ try {
2318
+ fs.mkdirSync(path.dirname(cachePath), { recursive: true });
2319
+ const tmpPath = `${cachePath}.${process.pid}.tmp`;
2320
+ fs.writeFileSync(tmpPath, JSON.stringify(payload, null, 2), { encoding: "utf8", mode: 0o600 });
2321
+ fs.renameSync(tmpPath, cachePath);
2322
+ } catch (_error) {}
2323
+ }
2324
+
2325
+ function resolveClaudeLimitsCachePath({ home } = {}) {
2326
+ return path.join(home || os.homedir(), ".tokenusage", "tracker", CLAUDE_LIMITS_CACHE_FILE);
2327
+ }
2328
+
2329
+ // Claude windows carry their own `resets_at`; a window whose reset has already passed is
2330
+ // stale data, not a usable fallback, so drop it. Windows without a reset stamp are kept
2331
+ // (the overall cached_at max-age gate already bounds them).
2332
+ function isClaudeCacheWindowUsable(window, { nowMs } = {}) {
2333
+ if (!window || typeof window !== "object") return false;
2334
+ const resetAtMs = parseTimeMs(window.resets_at);
2335
+ if (resetAtMs === null) return true;
2336
+ return resetAtMs > nowMs;
2337
+ }
2338
+
2339
+ function hasClaudeWindow(limits) {
2340
+ return Boolean(
2341
+ limits?.five_hour || limits?.seven_day || limits?.seven_day_opus ||
2342
+ (Array.isArray(limits?.weekly_scoped) && limits.weekly_scoped.length > 0),
2343
+ );
2344
+ }
2345
+
2346
+ // Cached scoped windows are filtered per-entry like the fixed windows: a scoped
2347
+ // window whose reset has passed is stale data, not a usable fallback.
2348
+ function normalizeClaudeCachedScopedWeekly(raw, { nowMs } = {}) {
2349
+ if (!Array.isArray(raw)) return null;
2350
+ const usable = raw.filter(
2351
+ (w) => w && typeof w.label === "string" && Number.isFinite(Number(w.utilization)) &&
2352
+ isClaudeCacheWindowUsable(w, { nowMs }),
2353
+ );
2354
+ return usable.length > 0 ? usable : null;
2355
+ }
2356
+
2357
+ function normalizeClaudeCachedLimits(
2358
+ raw,
2359
+ {
2360
+ nowMs = Date.now(),
2361
+ maxAgeMs = CLAUDE_LIMITS_CACHE_MAX_AGE_MS,
2362
+ stale = true,
2363
+ } = {},
2364
+ ) {
2365
+ const cachedAtMs = parseTimeMs(raw?.cached_at);
2366
+ if (!Number.isFinite(cachedAtMs)) return null;
2367
+ if (cachedAtMs > nowMs + 60_000) return null;
2368
+ if (nowMs - cachedAtMs > maxAgeMs) return null;
2369
+
2370
+ const cached = {
2371
+ configured: true,
2372
+ error: null,
2373
+ five_hour: isClaudeCacheWindowUsable(raw?.five_hour, { nowMs }) ? raw.five_hour : null,
2374
+ seven_day: isClaudeCacheWindowUsable(raw?.seven_day, { nowMs }) ? raw.seven_day : null,
2375
+ seven_day_opus: isClaudeCacheWindowUsable(raw?.seven_day_opus, { nowMs }) ? raw.seven_day_opus : null,
2376
+ weekly_scoped: normalizeClaudeCachedScopedWeekly(raw?.weekly_scoped, { nowMs }),
2377
+ extra_usage: raw?.extra_usage ?? null,
2378
+ stale,
2379
+ cached_at: raw.cached_at,
2380
+ };
2381
+ return hasClaudeWindow(cached) ? cached : null;
2382
+ }
2383
+
2384
+ function readClaudeLimitsCacheRaw({ home } = {}) {
2385
+ try {
2386
+ const parsed = JSON.parse(fs.readFileSync(resolveClaudeLimitsCachePath({ home }), "utf8"));
2387
+ return parsed?.claude ?? null;
2388
+ } catch (_error) {
2389
+ return null;
2390
+ }
2391
+ }
2392
+
2393
+ function readClaudeLimitsCache({
2394
+ home,
2395
+ nowMs = Date.now(),
2396
+ maxAgeMs = CLAUDE_LIMITS_CACHE_MAX_AGE_MS,
2397
+ stale = true,
2398
+ } = {}) {
2399
+ return pickNewestClaudeSnapshot(readClaudeLimitsCacheCandidates({ home }).map((raw) => (
2400
+ normalizeClaudeCachedLimits(raw, { nowMs, maxAgeMs, stale })
2401
+ )));
2402
+ }
2403
+
2404
+ // A cached snapshot stops being "fresh" the moment any of its windows crosses the
2405
+ // reset boundary it was written with: serving it past that point hides the rollover
2406
+ // from reset detection (the menu bar confetti) for up to the fresh TTL. Only resets
2407
+ // that were still ahead at write time count — a provider stamping already-past reset
2408
+ // times must not force a live call on every poll.
2409
+ function claudeCacheCrossedReset(raw, { nowMs } = {}) {
2410
+ const cachedAtMs = parseTimeMs(raw?.cached_at);
2411
+ if (!Number.isFinite(cachedAtMs)) return false;
2412
+ const windows = [
2413
+ raw?.five_hour,
2414
+ raw?.seven_day,
2415
+ raw?.seven_day_opus,
2416
+ ...(Array.isArray(raw?.weekly_scoped) ? raw.weekly_scoped : []),
2417
+ ];
2418
+ return windows.some((window) => {
2419
+ const resetMs = parseTimeMs(window?.resets_at);
2420
+ return resetMs !== null && resetMs > cachedAtMs && resetMs <= nowMs;
2421
+ });
2422
+ }
2423
+
2424
+ // An unstarted 5h/7d window (0%, `resets_at: null`) is started by the next prompt,
2425
+ // and Anthropic can lag several minutes behind it, so refetch on every poll within
2426
+ // the retry period after the last prompt, even when the live read is still empty.
2427
+ // The age is measured from the last prompt, not from the cache, because each empty
2428
+ // read rewrites the cache. history.jsonl gains a line per Claude Code prompt; only
2429
+ // its mtime is read. Model-scoped windows stay unstarted while that model is unused.
2430
+ function claudeCacheAwaitsNewWindow(raw, { home, nowMs } = {}) {
2431
+ const unstarted = [raw?.five_hour, raw?.seven_day].some((window) => (
2432
+ window && typeof window === "object" && parseTimeMs(window.resets_at) === null
2433
+ ));
2434
+ if (!unstarted) return false;
2435
+ try {
2436
+ const historyPath = path.join(home || os.homedir(), ".claude", "history.jsonl");
2437
+ const ageMs = nowMs - fs.statSync(historyPath).mtimeMs;
2438
+ // A future mtime (clock correction, copied file) would otherwise extend the retry.
2439
+ return ageMs >= 0 && ageMs < CLAUDE_UNSTARTED_WINDOW_RETRY_MS;
2440
+ } catch (_error) {
2441
+ return false;
2442
+ }
2443
+ }
2444
+
2445
+ // Claude Code keeps its last /api/oauth/usage response in its global config
2446
+ // (`cachedUsageUtilization` in ~/.claude.json). That endpoint is throttled hard and its
2447
+ // budget is shared with Claude Code itself, so reading this copy costs no request. Only
2448
+ // usage figures are read — no credentials. The path deliberately ignores CLAUDE_CONFIG_DIR:
2449
+ // readClaudeCodeOauthToken reads the default profile's credentials (default Keychain item,
2450
+ // ~/.claude/.credentials.json), and the cache must come from that same profile so it can
2451
+ // never describe a different account than the token this process would query with.
2452
+ function resolveClaudeCodeGlobalConfigPath({ home } = {}) {
2453
+ return path.join(home || os.homedir(), ".claude.json");
2454
+ }
2455
+
2456
+ /**
2457
+ * Claude Code's cached usage as a raw cache entry (same shape as our own disk cache),
2458
+ * or null when absent, unparsable, or recorded for a different account than the one
2459
+ * Claude Code is currently signed in to.
2460
+ */
2461
+ function readClaudeCodeUsageCacheRaw({ home } = {}) {
2462
+ try {
2463
+ const config = JSON.parse(fs.readFileSync(resolveClaudeCodeGlobalConfigPath({ home }), "utf8"));
2464
+ const cached = config?.cachedUsageUtilization;
2465
+ const fetchedAtMs = Number(cached?.fetchedAtMs);
2466
+ if (!cached?.utilization || typeof cached.utilization !== "object" || !Number.isFinite(fetchedAtMs)) return null;
2467
+ const cachedAccount = typeof cached.accountUuid === "string" ? cached.accountUuid : null;
2468
+ const currentAccount = typeof config?.oauthAccount?.accountUuid === "string" ? config.oauthAccount.accountUuid : null;
2469
+ if (!cachedAccount || !currentAccount || cachedAccount !== currentAccount) return null;
2470
+ return { ...mapClaudeUsageBody(cached.utilization), cached_at: new Date(fetchedAtMs).toISOString() };
2471
+ } catch (_error) {
2472
+ return null;
2473
+ }
2474
+ }
2475
+
2476
+ /** Raw snapshots from both sources: our own disk cache and Claude Code's cached read. */
2477
+ function readClaudeLimitsCacheCandidates({ home } = {}) {
2478
+ return [readClaudeLimitsCacheRaw({ home }), readClaudeCodeUsageCacheRaw({ home })].filter(Boolean);
2479
+ }
2480
+
2481
+ /** Newest of the already-validated snapshots, by cached_at. */
2482
+ function pickNewestClaudeSnapshot(snapshots) {
2483
+ let newest = null;
2484
+ for (const snapshot of snapshots) {
2485
+ if (!snapshot) continue;
2486
+ if (!newest || parseTimeMs(snapshot.cached_at) > parseTimeMs(newest.cached_at)) newest = snapshot;
2487
+ }
2488
+ return newest;
2489
+ }
2490
+
2491
+ // Each source is validated on its own before picking the newest, so a newer snapshot
2492
+ // whose windows are all unusable can never displace an older usable one.
2493
+ function readFreshClaudeLimitsCache({ home, nowMs = Date.now() } = {}) {
2494
+ return pickNewestClaudeSnapshot(readClaudeLimitsCacheCandidates({ home }).map((raw) => (
2495
+ claudeCacheCrossedReset(raw, { nowMs }) || claudeCacheAwaitsNewWindow(raw, { home, nowMs })
2496
+ ? null
2497
+ : normalizeClaudeCachedLimits(raw, { nowMs, maxAgeMs: CLAUDE_LIMITS_CACHE_FRESH_TTL_MS, stale: false })
2498
+ )));
2499
+ }
2500
+
2501
+ function writeClaudeLimitsCache(limits, { home, nowMs = Date.now() } = {}) {
2502
+ if (!limits?.configured || limits.error || !hasClaudeWindow(limits)) return;
2503
+ const cachePath = resolveClaudeLimitsCachePath({ home });
2504
+ const payload = {
2505
+ claude: {
2506
+ five_hour: limits.five_hour || null,
2507
+ seven_day: limits.seven_day || null,
2508
+ seven_day_opus: limits.seven_day_opus || null,
2509
+ weekly_scoped: Array.isArray(limits.weekly_scoped) && limits.weekly_scoped.length > 0
2510
+ ? limits.weekly_scoped
2511
+ : null,
2512
+ extra_usage: limits.extra_usage || null,
2513
+ cached_at: new Date(nowMs).toISOString(),
2514
+ },
2515
+ };
2516
+ try {
2517
+ fs.mkdirSync(path.dirname(cachePath), { recursive: true });
2518
+ const tmpPath = `${cachePath}.${process.pid}.tmp`;
2519
+ fs.writeFileSync(tmpPath, JSON.stringify(payload, null, 2), { encoding: "utf8", mode: 0o600 });
2520
+ fs.renameSync(tmpPath, cachePath);
2521
+ } catch (_error) {}
2522
+ }
2523
+
2524
+ function resolveCodexLimitsCachePath({ home } = {}) {
2525
+ return path.join(home || os.homedir(), ".tokenusage", "tracker", CODEX_LIMITS_CACHE_FILE);
2526
+ }
2527
+
2528
+ // Codex windows carry `reset_at` as unix seconds (not an ISO string). A window whose reset has
2529
+ // already passed is stale data, not a usable fallback, so drop it. Windows without a reset stamp
2530
+ // are kept — the overall cached_at max-age gate already bounds them.
2531
+ function isCodexCacheWindowUsable(window, { nowMs } = {}) {
2532
+ if (!window || typeof window !== "object") return false;
2533
+ const resetAt = Number(window.reset_at);
2534
+ if (!Number.isFinite(resetAt) || resetAt <= 0) return true;
2535
+ return resetAt * 1000 > nowMs;
2536
+ }
2537
+
2538
+ function hasCodexWindow(limits) {
2539
+ return Boolean(
2540
+ limits?.primary_window
2541
+ || limits?.secondary_window
2542
+ || limits?.credit_window
2543
+ || limits?.spark_primary_window
2544
+ || limits?.spark_secondary_window,
2545
+ );
2546
+ }
2547
+
2548
+ function normalizeCodexCachedLimits(
2549
+ raw,
2550
+ { nowMs = Date.now(), maxAgeMs = CODEX_LIMITS_CACHE_MAX_AGE_MS } = {},
2551
+ ) {
2552
+ const cachedAtMs = parseTimeMs(raw?.cached_at);
2553
+ if (!Number.isFinite(cachedAtMs)) return null;
2554
+ if (cachedAtMs > nowMs + 60_000) return null;
2555
+ if (nowMs - cachedAtMs > maxAgeMs) return null;
2556
+
2557
+ const cached = {
2558
+ configured: true,
2559
+ error: null,
2560
+ plan_type: typeof raw?.plan_type === "string" ? raw.plan_type : null,
2561
+ primary_window: isCodexCacheWindowUsable(raw?.primary_window, { nowMs }) ? raw.primary_window : null,
2562
+ secondary_window: isCodexCacheWindowUsable(raw?.secondary_window, { nowMs }) ? raw.secondary_window : null,
2563
+ credit_window: isCodexCacheWindowUsable(raw?.credit_window, { nowMs }) ? raw.credit_window : null,
2564
+ spark_primary_window: isCodexCacheWindowUsable(raw?.spark_primary_window, { nowMs }) ? raw.spark_primary_window : null,
2565
+ spark_secondary_window: isCodexCacheWindowUsable(raw?.spark_secondary_window, { nowMs }) ? raw.spark_secondary_window : null,
2566
+ reset_credits: raw?.reset_credits ?? null,
2567
+ stale: true,
2568
+ cached_at: raw.cached_at,
2569
+ };
2570
+ return hasCodexWindow(cached) ? cached : null;
2571
+ }
2572
+
2573
+ function readCodexLimitsCache({ home, nowMs = Date.now(), maxAgeMs = CODEX_LIMITS_CACHE_MAX_AGE_MS } = {}) {
2574
+ const cachePath = resolveCodexLimitsCachePath({ home });
2575
+ try {
2576
+ const parsed = JSON.parse(fs.readFileSync(cachePath, "utf8"));
2577
+ return normalizeCodexCachedLimits(parsed?.codex, { nowMs, maxAgeMs });
2578
+ } catch (_error) {
2579
+ return null;
2580
+ }
2581
+ }
2582
+
2583
+ function writeCodexLimitsCache(limits, { home, nowMs = Date.now() } = {}) {
2584
+ if (!limits?.configured || limits.error || !hasCodexWindow(limits)) return;
2585
+ const cachePath = resolveCodexLimitsCachePath({ home });
2586
+ const payload = {
2587
+ codex: {
2588
+ plan_type: limits.plan_type || null,
2589
+ primary_window: limits.primary_window || null,
2590
+ secondary_window: limits.secondary_window || null,
2591
+ credit_window: limits.credit_window || null,
2592
+ spark_primary_window: limits.spark_primary_window || null,
2593
+ spark_secondary_window: limits.spark_secondary_window || null,
2594
+ reset_credits: limits.reset_credits || null,
2595
+ cached_at: new Date(nowMs).toISOString(),
2596
+ },
2597
+ };
2598
+ try {
2599
+ fs.mkdirSync(path.dirname(cachePath), { recursive: true });
2600
+ const tmpPath = `${cachePath}.${process.pid}.tmp`;
2601
+ fs.writeFileSync(tmpPath, JSON.stringify(payload, null, 2), { encoding: "utf8", mode: 0o600 });
2602
+ fs.renameSync(tmpPath, cachePath);
2603
+ } catch (_error) {}
2604
+ }
2605
+
2606
+ function resolveOpencodeGoLimitsCachePath({ home } = {}) {
2607
+ return path.join(home || os.homedir(), ".tokenusage", "tracker", OPENCODE_GO_LIMITS_CACHE_FILE);
2608
+ }
2609
+
2610
+ function hasOpencodeGoWindow(limits) {
2611
+ return Boolean(limits?.primary_window || limits?.secondary_window || limits?.tertiary_window);
2612
+ }
2613
+
2614
+ function isOpencodeGoCacheWindowUsable(window, { nowMs } = {}) {
2615
+ if (!window || typeof window !== "object") return false;
2616
+ const resetAtMs = parseTimeMs(window.reset_at);
2617
+ if (resetAtMs === null) return true;
2618
+ return resetAtMs > nowMs;
2619
+ }
2620
+
2621
+ function normalizeOpencodeGoCachedLimits(
2622
+ raw,
2623
+ { nowMs = Date.now(), maxAgeMs } = {},
2624
+ ) {
2625
+ const effectiveMaxAge = Number.isFinite(maxAgeMs)
2626
+ ? maxAgeMs
2627
+ : raw?.source === "local-estimate"
2628
+ ? OPENCODE_GO_LOCAL_ESTIMATE_CACHE_MAX_AGE_MS
2629
+ : OPENCODE_GO_LIMITS_CACHE_MAX_AGE_MS;
2630
+ const cachedAtMs = parseTimeMs(raw?.cached_at);
2631
+ if (!Number.isFinite(cachedAtMs)) return null;
2632
+ if (cachedAtMs > nowMs + 60_000) return null;
2633
+ if (nowMs - cachedAtMs > effectiveMaxAge) return null;
2634
+
2635
+ const cached = {
2636
+ configured: true,
2637
+ error: null,
2638
+ source: typeof raw?.source === "string" ? raw.source : "api",
2639
+ subscription_status: typeof raw?.subscription_status === "string" ? raw.subscription_status : null,
2640
+ plan_label: typeof raw?.plan_label === "string" ? raw.plan_label : null,
2641
+ primary_window: isOpencodeGoCacheWindowUsable(raw?.primary_window, { nowMs }) ? raw.primary_window : null,
2642
+ secondary_window: isOpencodeGoCacheWindowUsable(raw?.secondary_window, { nowMs }) ? raw.secondary_window : null,
2643
+ tertiary_window: isOpencodeGoCacheWindowUsable(raw?.tertiary_window, { nowMs }) ? raw.tertiary_window : null,
2644
+ stale: true,
2645
+ cached_at: raw.cached_at,
2646
+ };
2647
+ return hasOpencodeGoWindow(cached) ? cached : null;
2648
+ }
2649
+
2650
+ function readOpencodeGoLimitsCache({ home, nowMs = Date.now() } = {}) {
2651
+ const cachePath = resolveOpencodeGoLimitsCachePath({ home });
2652
+ try {
2653
+ const parsed = JSON.parse(fs.readFileSync(cachePath, "utf8"));
2654
+ return normalizeOpencodeGoCachedLimits(parsed?.opencodeGo, { nowMs });
2655
+ } catch (_error) {
2656
+ return null;
2657
+ }
2658
+ }
2659
+
2660
+ function writeOpencodeGoLimitsCache(limits, { home, nowMs = Date.now() } = {}) {
2661
+ if (!limits?.configured || limits.error || !hasOpencodeGoWindow(limits)) return;
2662
+ const cachePath = resolveOpencodeGoLimitsCachePath({ home });
2663
+ const payload = {
2664
+ opencodeGo: {
2665
+ source: limits.source || "api",
2666
+ subscription_status: limits.subscription_status || null,
2667
+ plan_label: limits.plan_label || null,
2668
+ primary_window: limits.primary_window || null,
2669
+ secondary_window: limits.secondary_window || null,
2670
+ tertiary_window: limits.tertiary_window || null,
2671
+ cached_at: new Date(nowMs).toISOString(),
2672
+ },
2673
+ };
2674
+ try {
2675
+ fs.mkdirSync(path.dirname(cachePath), { recursive: true });
2676
+ const tmpPath = `${cachePath}.${process.pid}.tmp`;
2677
+ fs.writeFileSync(tmpPath, JSON.stringify(payload, null, 2), { encoding: "utf8", mode: 0o600 });
2678
+ fs.renameSync(tmpPath, cachePath);
2679
+ } catch (_error) {}
2680
+ }
2681
+
2682
+ function resolveClaudeRateLimitPath({ home } = {}) {
2683
+ return path.join(home || os.homedir(), ".tokenusage", "tracker", CLAUDE_RATE_LIMIT_FILE);
2684
+ }
2685
+
2686
+ function claudeTokenExpiryStamp(tokenExpiresAtMs) {
2687
+ return Number.isFinite(tokenExpiresAtMs)
2688
+ ? new Date(tokenExpiresAtMs).toISOString()
2689
+ : null;
2690
+ }
2691
+
2692
+ // Returns the cooldown expiry in ms if a 429 cooldown is still active, else null.
2693
+ // A cooldown armed for a previous access token must not outlive that token: after
2694
+ // the user refreshes the Claude Code login, forceRefresh still cannot punch through
2695
+ // this file, so a cooldown stamped with a different token expiry is discarded.
2696
+ // The token's own expiry identifies the credential without persisting anything
2697
+ // derived from the secret.
2698
+ function readClaudeRateLimitRetryAtMs({ home, nowMs = Date.now(), tokenExpiresAtMs } = {}) {
2699
+ const cachePath = resolveClaudeRateLimitPath({ home });
2700
+ try {
2701
+ const parsed = JSON.parse(fs.readFileSync(cachePath, "utf8"));
2702
+ const retryAtMs = parseTimeMs(parsed?.retry_at);
2703
+ if (retryAtMs === null || retryAtMs <= nowMs) return null;
2704
+ const stampedExpiry = typeof parsed.token_expires_at === "string"
2705
+ ? parsed.token_expires_at
2706
+ : null;
2707
+ if (stampedExpiry && stampedExpiry !== claudeTokenExpiryStamp(tokenExpiresAtMs)) {
2708
+ clearClaudeRateLimitCooldown({ home });
2709
+ return null;
2710
+ }
2711
+ return retryAtMs;
2712
+ } catch (_error) {}
2713
+ return null;
2714
+ }
2715
+
2716
+ function writeClaudeRateLimitCooldown(retryAfterSec, { home, nowMs = Date.now(), tokenExpiresAtMs } = {}) {
2717
+ const sec = Number.isFinite(retryAfterSec) && retryAfterSec > 0
2718
+ ? Math.min(retryAfterSec, CLAUDE_RATE_LIMIT_MAX_COOLDOWN_SEC)
2719
+ : CLAUDE_RATE_LIMIT_DEFAULT_COOLDOWN_SEC;
2720
+ const cachePath = resolveClaudeRateLimitPath({ home });
2721
+ const payload = { retry_at: new Date(nowMs + sec * 1000).toISOString() };
2722
+ const expiryStamp = claudeTokenExpiryStamp(tokenExpiresAtMs);
2723
+ if (expiryStamp) payload.token_expires_at = expiryStamp;
2724
+ try {
2725
+ fs.mkdirSync(path.dirname(cachePath), { recursive: true });
2726
+ const tmpPath = `${cachePath}.${process.pid}.tmp`;
2727
+ fs.writeFileSync(tmpPath, JSON.stringify(payload, null, 2), { encoding: "utf8", mode: 0o600 });
2728
+ fs.renameSync(tmpPath, cachePath);
2729
+ } catch (_error) {}
2730
+ }
2731
+
2732
+ function clearClaudeRateLimitCooldown({ home } = {}) {
2733
+ try {
2734
+ fs.unlinkSync(resolveClaudeRateLimitPath({ home }));
2735
+ } catch (_error) {}
2736
+ }
2737
+
2738
+ async function resolveLsofBinary({ commandRunner } = {}) {
2739
+ for (const candidate of ["/usr/sbin/lsof", "/usr/bin/lsof"]) {
2740
+ if (fs.existsSync(candidate)) return candidate;
2741
+ }
2742
+ return whichBinary("lsof", { commandRunner });
2743
+ }
2744
+
2745
+ function parseListeningPorts(output) {
2746
+ const matches = String(output || "").matchAll(/:(\d+)\s+\(LISTEN\)/g);
2747
+ const ports = new Set();
2748
+ for (const match of matches) {
2749
+ const port = Number(match[1]);
2750
+ if (Number.isFinite(port)) {
2751
+ ports.add(port);
2752
+ }
2753
+ }
2754
+ return Array.from(ports).sort((a, b) => a - b);
2755
+ }
2756
+
2757
+ function windowsEndpointPort(endpoint) {
2758
+ const match = String(endpoint || "").match(/:(\d+)$/);
2759
+ return match ? Number(match[1]) : null;
2760
+ }
2761
+
2762
+ function parseWindowsListeningPorts(output, pid) {
2763
+ const ports = new Set();
2764
+ for (const line of String(output || "").split("\n")) {
2765
+ const fields = line.trim().split(/\s+/);
2766
+ if (fields.length < 5 || fields[0]?.toUpperCase() !== "TCP") continue;
2767
+ if (Number(fields.at(-1)) !== Number(pid)) continue;
2768
+ // netstat localizes its state label. A TCP listener's foreign endpoint is
2769
+ // always the wildcard address with port 0, which stays language-neutral.
2770
+ if (windowsEndpointPort(fields[2]) !== 0) continue;
2771
+ const port = windowsEndpointPort(fields[1]);
2772
+ if (Number.isInteger(port) && port > 0 && port <= 65535) ports.add(port);
2773
+ }
2774
+ return Array.from(ports).sort((a, b) => a - b);
2775
+ }
2776
+
2777
+ function parseLinuxProcListeningPorts(pid, { procRoot = "/proc" } = {}) {
2778
+ const numPid = Number(pid);
2779
+ if (!Number.isFinite(numPid) || numPid <= 0) return [];
2780
+ const inodes = new Set();
2781
+ try {
2782
+ const fds = fs.readdirSync(path.join(procRoot, String(numPid), "fd"));
2783
+ for (const fd of fds) {
2784
+ try {
2785
+ const link = fs.readlinkSync(path.join(procRoot, String(numPid), "fd", fd));
2786
+ const m = link.match(/^socket:\[(\d+)\]$/);
2787
+ if (m) inodes.add(m[1]);
2788
+ } catch {}
2789
+ }
2790
+ } catch {
2791
+ return [];
2792
+ }
2793
+ if (inodes.size === 0) return [];
2794
+
2795
+ const ports = new Set();
2796
+ for (const table of [path.join(procRoot, "net", "tcp"), path.join(procRoot, "net", "tcp6")]) {
2797
+ try {
2798
+ const content = fs.readFileSync(table, "utf8");
2799
+ for (const line of content.split("\n")) {
2800
+ const parts = line.trim().split(/\s+/);
2801
+ if (parts.length > 9 && parts[3] === "0A") {
2802
+ const inode = parts[9];
2803
+ if (inodes.has(inode)) {
2804
+ const portHex = parts[1]?.split(":")[1];
2805
+ if (portHex) {
2806
+ const port = parseInt(portHex, 16);
2807
+ if (Number.isInteger(port) && port > 0 && port <= 65535) {
2808
+ ports.add(port);
2809
+ }
2810
+ }
2811
+ }
2812
+ }
2813
+ }
2814
+ } catch {}
2815
+ }
2816
+ return Array.from(ports).sort((a, b) => a - b);
2817
+ }
2818
+
2819
+ function parseSsListeningPorts(output, pid) {
2820
+ const ports = new Set();
2821
+ const pidPattern = pid ? new RegExp(`\\bpid=${pid}\\b`) : null;
2822
+ for (const line of String(output || "").split("\n")) {
2823
+ if (!line.includes("LISTEN")) continue;
2824
+ if (pidPattern && !pidPattern.test(line)) continue;
2825
+ const match = line.match(/:(\d+)\s+/);
2826
+ if (match) {
2827
+ const port = Number(match[1]);
2828
+ if (Number.isInteger(port) && port > 0 && port <= 65535) {
2829
+ ports.add(port);
2830
+ }
2831
+ }
2832
+ }
2833
+ return Array.from(ports).sort((a, b) => a - b);
2834
+ }
2835
+
2836
+ async function listAntigravityPorts(pid, {
2837
+ commandRunner,
2838
+ platform = process.platform,
2839
+ timeoutMs = ANTIGRAVITY_PROCESS_SCAN_TIMEOUT_MS,
2840
+ procRoot = "/proc",
2841
+ signal,
2842
+ } = {}) {
2843
+ if (platform === "win32") {
2844
+ const result = await runCommand(
2845
+ commandRunner,
2846
+ "netstat.exe",
2847
+ ["-ano", "-p", "tcp"],
2848
+ { timeout: timeoutMs, signal },
2849
+ );
2850
+ const ports = parseWindowsListeningPorts(result?.stdout, pid);
2851
+ if (!ports.length) {
2852
+ throw new Error("Antigravity is running but not exposing ports yet. Try again in a few seconds.");
2853
+ }
2854
+ return ports;
2855
+ }
2856
+
2857
+ // On Linux, try procfs first when no mock command runner is provided (zero-spawn, no dependencies).
2858
+ if (platform === "linux" && !commandRunner) {
2859
+ const procPorts = parseLinuxProcListeningPorts(pid, { procRoot });
2860
+ if (procPorts.length > 0) return procPorts;
2861
+ }
2862
+
2863
+ const lsof = await resolveLsofBinary({ commandRunner });
2864
+ if (lsof) {
2865
+ const result = await runCommand(
2866
+ commandRunner,
2867
+ lsof,
2868
+ ["-nP", "-iTCP", "-sTCP:LISTEN", "-a", "-p", String(pid)],
2869
+ { timeout: timeoutMs, signal },
2870
+ );
2871
+ const ports = parseListeningPorts(result?.stdout);
2872
+ if (ports.length > 0) return ports;
2873
+ }
2874
+
2875
+ // On Linux, fall back to procfs (honoring procRoot) or ss if lsof is absent or yielded no ports.
2876
+ if (platform === "linux") {
2877
+ const procPorts = parseLinuxProcListeningPorts(pid, { procRoot });
2878
+ if (procPorts.length > 0) return procPorts;
2879
+
2880
+ const ss = await whichBinary("ss", { commandRunner });
2881
+ if (ss) {
2882
+ const result = await runCommand(
2883
+ commandRunner,
2884
+ ss,
2885
+ ["-H", "-tlpn"],
2886
+ { timeout: timeoutMs, signal },
2887
+ );
2888
+ const ssPorts = parseSsListeningPorts(result?.stdout, pid);
2889
+ if (ssPorts.length > 0) return ssPorts;
2890
+ }
2891
+ }
2892
+
2893
+ if (!lsof && platform !== "linux") {
2894
+ throw new Error("Antigravity port detection needs lsof. Install it, then retry.");
2895
+ }
2896
+
2897
+ throw new Error("Antigravity is running but not exposing ports yet. Try again in a few seconds.");
2898
+ }
2899
+
2900
+ function antigravityDefaultBody() {
2901
+ return {
2902
+ metadata: {
2903
+ ideName: "antigravity",
2904
+ extensionName: "antigravity",
2905
+ ideVersion: "unknown",
2906
+ locale: "en",
2907
+ },
2908
+ };
2909
+ }
2910
+
2911
+ function antigravityUnleashBody() {
2912
+ return {
2913
+ context: {
2914
+ properties: {
2915
+ devMode: "false",
2916
+ extensionVersion: "unknown",
2917
+ hasAnthropicModelAccess: "true",
2918
+ ide: "antigravity",
2919
+ ideVersion: "unknown",
2920
+ installationId: "tokenusage",
2921
+ language: "UNSPECIFIED",
2922
+ os: "macos",
2923
+ requestedModelId: "MODEL_UNSPECIFIED",
2924
+ },
2925
+ },
2926
+ };
2927
+ }
2928
+
2929
+ function requestLocalJson({
2930
+ scheme,
2931
+ port,
2932
+ path,
2933
+ body,
2934
+ csrfToken,
2935
+ timeoutMs = ANTIGRAVITY_LOCAL_REQUEST_TIMEOUT_MS,
2936
+ requestFn,
2937
+ signal,
2938
+ }) {
2939
+ if (typeof requestFn === "function") {
2940
+ return requestFn({ scheme, port, path, body, csrfToken, timeoutMs, signal });
2941
+ }
2942
+
2943
+ const client = scheme === "https" ? https : http;
2944
+ return new Promise((resolve, reject) => {
2945
+ const rawBody = JSON.stringify(body);
2946
+ const headers = {
2947
+ "Content-Type": "application/json",
2948
+ "Content-Length": Buffer.byteLength(rawBody),
2949
+ "Connect-Protocol-Version": "1",
2950
+ };
2951
+ if (csrfToken) {
2952
+ headers["X-Codeium-Csrf-Token"] = csrfToken;
2953
+ }
2954
+ const req = client.request(
2955
+ {
2956
+ hostname: "127.0.0.1",
2957
+ port,
2958
+ path,
2959
+ method: "POST",
2960
+ rejectUnauthorized: false,
2961
+ timeout: timeoutMs,
2962
+ headers,
2963
+ // Without this the provider race only stops *waiting* — the socket stays
2964
+ // open past the deadline. http.request aborts and emits 'error' instead.
2965
+ signal,
2966
+ },
2967
+ (res) => {
2968
+ let data = "";
2969
+ res.on("data", (chunk) => {
2970
+ data += chunk;
2971
+ });
2972
+ res.on("end", () => {
2973
+ if (res.statusCode !== 200) {
2974
+ reject(new Error(`HTTP ${res.statusCode}: ${data}`));
2975
+ return;
2976
+ }
2977
+ try {
2978
+ resolve(JSON.parse(data));
2979
+ } catch (error) {
2980
+ reject(new Error(`Invalid JSON response: ${error.message}`));
2981
+ }
2982
+ });
2983
+ },
2984
+ );
2985
+ req.on("error", reject);
2986
+ req.on("timeout", () => {
2987
+ req.destroy(new Error("timeout"));
2988
+ });
2989
+ req.write(rawBody);
2990
+ req.end();
2991
+ });
2992
+ }
2993
+
2994
+ function antigravityCodeIsOk(code) {
2995
+ if (code === null || code === undefined) return true;
2996
+ if (typeof code === "number") return code === 0;
2997
+ if (typeof code === "string") {
2998
+ const lower = code.toLowerCase();
2999
+ return lower === "ok" || lower === "success" || lower === "0";
3000
+ }
3001
+ return false;
3002
+ }
3003
+
3004
+ function parseAntigravityDate(value) {
3005
+ if (typeof value === "string" && value) {
3006
+ const numeric = Number(value);
3007
+ if (Number.isFinite(numeric) && numeric > 0) {
3008
+ return new Date(numeric * 1000).toISOString();
3009
+ }
3010
+ if (Number.isFinite(numeric)) return null;
3011
+ const iso = Date.parse(value);
3012
+ if (Number.isFinite(iso) && iso > 0) return new Date(iso).toISOString();
3013
+ }
3014
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) {
3015
+ return new Date(value * 1000).toISOString();
3016
+ }
3017
+ return null;
3018
+ }
3019
+
3020
+ function parseAntigravityModelConfigs(configs) {
3021
+ if (!Array.isArray(configs)) return [];
3022
+ return configs
3023
+ .map((config) => {
3024
+ const quota = config?.quotaInfo || null;
3025
+ if (!quota) return null;
3026
+ return {
3027
+ label: typeof config?.label === "string" ? config.label : "",
3028
+ model_id: typeof config?.modelOrAlias?.model === "string" ? config.modelOrAlias.model : "",
3029
+ remaining_fraction:
3030
+ typeof quota?.remainingFraction === "number" && Number.isFinite(quota.remainingFraction)
3031
+ ? quota.remainingFraction
3032
+ : null,
3033
+ reset_at: parseAntigravityDate(quota?.resetTime),
3034
+ };
3035
+ })
3036
+ .filter(Boolean);
3037
+ }
3038
+
3039
+ function antigravityFamily(model) {
3040
+ const text = `${model?.label || ""} ${model?.model_id || ""}`.toLowerCase();
3041
+ if (text.includes("claude")) return "claude";
3042
+ if (text.includes("gemini") && text.includes("pro")) return "gemini_pro";
3043
+ if (text.includes("gemini") && text.includes("flash")) return "gemini_flash";
3044
+ return "unknown";
3045
+ }
3046
+
3047
+ function antigravityPriority(model) {
3048
+ const text = `${model?.label || ""} ${model?.model_id || ""}`.toLowerCase();
3049
+ if (text.includes("lite") || text.includes("autocomplete") || text.includes("tab_")) return null;
3050
+ if (antigravityFamily(model) === "gemini_pro") {
3051
+ return text.includes("pro-low") || (text.includes("pro") && text.includes("low")) ? 0 : 1;
3052
+ }
3053
+ return 0;
3054
+ }
3055
+
3056
+ function normalizeAntigravityResponse(body, { fallbackToConfigs = false } = {}) {
3057
+ if (!antigravityCodeIsOk(body?.code)) {
3058
+ throw new Error(`Antigravity API error: ${body?.code}`);
3059
+ }
3060
+
3061
+ const userStatus = body?.userStatus || null;
3062
+ const configs = fallbackToConfigs
3063
+ ? body?.clientModelConfigs
3064
+ : userStatus?.cascadeModelConfigData?.clientModelConfigs;
3065
+ const allModels = parseAntigravityModelConfigs(configs);
3066
+ if (!allModels.length) {
3067
+ throw new Error("Could not parse Antigravity quota: no quota models available.");
3068
+ }
3069
+
3070
+ // Keep only chat models (skip autocomplete/lite/tab models)
3071
+ const chatModels = allModels.filter((m) => antigravityPriority(m) !== null);
3072
+ const models = chatModels.length ? chatModels : allModels;
3073
+
3074
+ // Group chat models and pick the most-used (lowest remaining → weekly quota)
3075
+ // and least-used (highest remaining → 5h rolling quota) per family.
3076
+ const claudeModels = models.filter((m) => antigravityFamily(m) === "claude");
3077
+ const geminiModels = models.filter(
3078
+ (m) => antigravityFamily(m) === "gemini_pro" || antigravityFamily(m) === "gemini_flash",
3079
+ );
3080
+
3081
+ const pickMin = (list) => {
3082
+ const sorted = [...list].filter((m) => typeof m.remaining_fraction === "number");
3083
+ if (!sorted.length) return list[0] || null;
3084
+ sorted.sort((a, b) => a.remaining_fraction - b.remaining_fraction);
3085
+ return sorted[0];
3086
+ };
3087
+ const pickMax = (list) => {
3088
+ const sorted = [...list].filter((m) => typeof m.remaining_fraction === "number");
3089
+ if (!sorted.length) return list[list.length - 1] || null;
3090
+ sorted.sort((a, b) => b.remaining_fraction - a.remaining_fraction);
3091
+ return sorted[0];
3092
+ };
3093
+
3094
+ const makeWindow = (model) => {
3095
+ if (!model) return null;
3096
+ const remaining = typeof model.remaining_fraction === "number" ? model.remaining_fraction * 100 : 0;
3097
+ return buildWindow({ usedPercent: 100 - remaining, resetAt: model.reset_at });
3098
+ };
3099
+
3100
+ return {
3101
+ account_email: typeof userStatus?.email === "string" ? userStatus.email : null,
3102
+ account_plan:
3103
+ userStatus?.planStatus?.planInfo?.planDisplayName
3104
+ || userStatus?.planStatus?.planInfo?.displayName
3105
+ || userStatus?.planStatus?.planInfo?.productName
3106
+ || userStatus?.planStatus?.planInfo?.planName
3107
+ || userStatus?.planStatus?.planInfo?.planShortName
3108
+ || null,
3109
+ primary_window: makeWindow(claudeModels.length ? pickMin(claudeModels) : pickMin(models)),
3110
+ secondary_window: makeWindow(claudeModels.length ? pickMax(claudeModels) : null),
3111
+ tertiary_window: makeWindow(geminiModels.length ? pickMin(geminiModels) : pickMin(models)),
3112
+ quaternary_window: makeWindow(geminiModels.length ? pickMax(geminiModels) : null),
3113
+ };
3114
+ }
3115
+
3116
+ function normalizeAntigravityQuotaSummary(body) {
3117
+ if (body?.code !== undefined && body?.code !== null && !antigravityCodeIsOk(body.code)) {
3118
+ throw new Error(`Antigravity API error: ${body?.code}`);
3119
+ }
3120
+
3121
+ // Local Connect-RPC wraps the payload in `response`; the Cloud Code HTTP
3122
+ // endpoint returns `groups` at the top level.
3123
+ const groups = Array.isArray(body?.response?.groups)
3124
+ ? body.response.groups
3125
+ : Array.isArray(body?.groups)
3126
+ ? body.groups
3127
+ : null;
3128
+ if (!Array.isArray(groups) || !groups.length) {
3129
+ throw new Error("Could not parse Antigravity quota summary: no groups.");
3130
+ }
3131
+
3132
+ // Map bucketId → window, regardless of which group they live in
3133
+ const makeWindow = (remainingFraction, resetTime) => {
3134
+ if (typeof remainingFraction !== "number") return null;
3135
+ return buildWindow({
3136
+ usedPercent: Math.round((1 - remainingFraction) * 100),
3137
+ resetAt: parseAntigravityDate(resetTime) || (typeof resetTime === "string" ? resetTime : null),
3138
+ });
3139
+ };
3140
+
3141
+ // Collect all buckets into a flat bucketId-keyed map
3142
+ const buckets = {};
3143
+ for (const group of groups) {
3144
+ if (!Array.isArray(group.buckets)) continue;
3145
+ for (const b of group.buckets) {
3146
+ buckets[b.bucketId] = b;
3147
+ }
3148
+ }
3149
+
3150
+ const windows = {
3151
+ primary_window: makeWindow(buckets["3p-weekly"]?.remainingFraction, buckets["3p-weekly"]?.resetTime),
3152
+ secondary_window: makeWindow(buckets["3p-5h"]?.remainingFraction, buckets["3p-5h"]?.resetTime),
3153
+ tertiary_window: makeWindow(buckets["gemini-weekly"]?.remainingFraction, buckets["gemini-weekly"]?.resetTime),
3154
+ quaternary_window: makeWindow(buckets["gemini-5h"]?.remainingFraction, buckets["gemini-5h"]?.resetTime),
3155
+ };
3156
+
3157
+ // If the groups parsed but none of the known bucketIds matched (upstream
3158
+ // renamed them), treat it as a parse failure so the caller falls back to
3159
+ // GetUserStatus rather than rendering an empty, error-free card.
3160
+ if (!windows.primary_window && !windows.secondary_window
3161
+ && !windows.tertiary_window && !windows.quaternary_window) {
3162
+ throw new Error("Could not parse Antigravity quota summary: no known buckets matched.");
3163
+ }
3164
+
3165
+ return {
3166
+ account_email: null, // quota summary doesn't include email
3167
+ account_plan: null, // quota summary doesn't include plan info
3168
+ ...windows,
3169
+ };
3170
+ }
3171
+
3172
+ async function probeAntigravityPort(port, csrfToken, { timeoutMs, requestFn, scheme = "https", signal } = {}) {
3173
+ try {
3174
+ await requestLocalJson({
3175
+ scheme,
3176
+ port,
3177
+ path: "/exa.language_server_pb.LanguageServerService/GetUnleashData",
3178
+ body: antigravityUnleashBody(),
3179
+ csrfToken,
3180
+ timeoutMs,
3181
+ requestFn,
3182
+ signal,
3183
+ });
3184
+ return true;
3185
+ } catch (_error) {
3186
+ return false;
3187
+ }
3188
+ }
3189
+
3190
+ function hasAntigravityInstallEvidence({ home } = {}) {
3191
+ const geminiHome = path.join(home || os.homedir(), ".gemini");
3192
+ return ["antigravity", "antigravity-ide", "antigravity-cli"]
3193
+ .some((name) => {
3194
+ try {
3195
+ return fs.statSync(path.join(geminiHome, name)).isDirectory();
3196
+ } catch {
3197
+ return false;
3198
+ }
3199
+ });
3200
+ }
3201
+
3202
+ function listAntigravityCredentialPaths(home) {
3203
+ const geminiHome = path.join(home || os.homedir(), ".gemini");
3204
+ return [
3205
+ path.join(geminiHome, "jetski-standalone-oauth-token"),
3206
+ path.join(geminiHome, "antigravity", "jetski-standalone-oauth-token"),
3207
+ path.join(geminiHome, "antigravity", "antigravity-oauth-token"),
3208
+ path.join(geminiHome, "antigravity-ide", "antigravity-oauth-token"),
3209
+ path.join(geminiHome, "antigravity-cli", "antigravity-oauth-token"),
3210
+ ];
3211
+ }
3212
+
3213
+ function parseAntigravityExpiryMs(value) {
3214
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) {
3215
+ return value < 1e12 ? value * 1000 : value;
3216
+ }
3217
+ if (typeof value === "string" && value) {
3218
+ const ms = Date.parse(value);
3219
+ if (Number.isFinite(ms) && ms > 0) return ms;
3220
+ }
3221
+ return null;
3222
+ }
3223
+
3224
+ function parseAntigravityCredentialPayload(raw) {
3225
+ if (typeof raw !== "string" || !raw.trim()) return null;
3226
+ let text = raw.trim();
3227
+ if (text.startsWith("go-keyring-base64:")) {
3228
+ try {
3229
+ text = Buffer.from(text.slice("go-keyring-base64:".length), "base64").toString("utf8").trim();
3230
+ } catch {
3231
+ return null;
3232
+ }
3233
+ }
3234
+ let parsed;
3235
+ try {
3236
+ parsed = JSON.parse(text);
3237
+ } catch {
3238
+ return null;
3239
+ }
3240
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
3241
+
3242
+ const tokenObj = parsed.token && typeof parsed.token === "object" && !Array.isArray(parsed.token)
3243
+ ? parsed.token
3244
+ : parsed;
3245
+ const accessToken = typeof tokenObj.access_token === "string" && tokenObj.access_token
3246
+ ? tokenObj.access_token
3247
+ : (typeof parsed.token === "string" && parsed.token ? parsed.token : null);
3248
+ if (!accessToken) return null;
3249
+ const refreshToken = typeof tokenObj.refresh_token === "string" && tokenObj.refresh_token
3250
+ ? tokenObj.refresh_token
3251
+ : (typeof parsed.refresh_token === "string" && parsed.refresh_token ? parsed.refresh_token : null);
3252
+ return {
3253
+ accessToken,
3254
+ refreshToken,
3255
+ expiryMs: parseAntigravityExpiryMs(
3256
+ tokenObj.expiry ?? tokenObj.expiry_date ?? parsed.expiry ?? parsed.expiry_date,
3257
+ ),
3258
+ raw: parsed,
3259
+ };
3260
+ }
3261
+
3262
+ function isAntigravityCredentialFresh(creds, nowMs) {
3263
+ return creds.expiryMs != null && creds.expiryMs > nowMs + ANTIGRAVITY_TOKEN_REFRESH_SKEW_MS;
3264
+ }
3265
+
3266
+ function pickLatestAntigravityExpiry(candidates) {
3267
+ let best = candidates[0];
3268
+ for (let i = 1; i < candidates.length; i += 1) {
3269
+ const expiry = candidates[i].expiryMs;
3270
+ if (expiry != null && (best.expiryMs == null || expiry > best.expiryMs)) {
3271
+ best = candidates[i];
3272
+ }
3273
+ }
3274
+ return best;
3275
+ }
3276
+
3277
+ function pickAntigravityCredentials(candidates, nowMs) {
3278
+ if (candidates.length === 0) return null;
3279
+ const fresh = candidates.filter((creds) => isAntigravityCredentialFresh(creds, nowMs));
3280
+ if (fresh.length > 0) return pickLatestAntigravityExpiry(fresh);
3281
+ const unknown = candidates.filter((creds) => creds.expiryMs == null);
3282
+ if (unknown.length > 0) return unknown[0];
3283
+ return pickLatestAntigravityExpiry(candidates);
3284
+ }
3285
+
3286
+ function collectAntigravityFileCredentials({ home } = {}) {
3287
+ const candidates = [];
3288
+ for (const credPath of listAntigravityCredentialPaths(home)) {
3289
+ try {
3290
+ const parsed = parseAntigravityCredentialPayload(fs.readFileSync(credPath, "utf8"));
3291
+ if (parsed) candidates.push({ ...parsed, source: "file", path: credPath });
3292
+ } catch {
3293
+ // missing or unreadable
3294
+ }
3295
+ }
3296
+ return candidates;
3297
+ }
3298
+
3299
+ /** Read the agy Keychain entry synchronously; missing or unreadable entries return null. */
3300
+ function readAntigravityKeychainRaw({ securityRunner, timeoutMs = 2000 } = {}) {
3301
+ const runner = typeof securityRunner === "function" ? securityRunner : cp.spawnSync;
3302
+ if (runner === cp.spawnSync) {
3303
+ if (process.platform !== "darwin" || !fs.existsSync(MACOS_SECURITY_BIN)) return null;
3304
+ }
3305
+ try {
3306
+ const result = runner(
3307
+ MACOS_SECURITY_BIN,
3308
+ ["find-generic-password", "-s", "gemini", "-a", "antigravity", "-w"],
3309
+ {
3310
+ encoding: "utf8",
3311
+ timeout: timeoutMs,
3312
+ stdio: ["ignore", "pipe", "ignore"],
3313
+ },
3314
+ );
3315
+ if (!result || result.error || result.status !== 0) return null;
3316
+ const stdout = typeof result.stdout === "string"
3317
+ ? result.stdout
3318
+ : Buffer.isBuffer(result.stdout)
3319
+ ? result.stdout.toString("utf8")
3320
+ : "";
3321
+ const trimmed = stdout.trim();
3322
+ return trimmed || null;
3323
+ } catch {
3324
+ return null;
3325
+ }
3326
+ }
3327
+
3328
+ /** Run a Secret Service command with a deadline and cancellation, including injected runners. */
3329
+ async function runAntigravitySecretTool(args, { secretToolRunner, timeoutMs = 2000, signal, input } = {}) {
3330
+ if (typeof secretToolRunner !== "function" && process.platform !== "linux") return null;
3331
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || signal?.aborted) return null;
3332
+
3333
+ const controller = new AbortController();
3334
+ const abort = () => controller.abort();
3335
+ signal?.addEventListener("abort", abort, { once: true });
3336
+ let onAbort;
3337
+ const cancelled = new Promise((resolve) => {
3338
+ onAbort = () => resolve(null);
3339
+ controller.signal.addEventListener("abort", onAbort, { once: true });
3340
+ });
3341
+ // Settle at the deadline even if an injected runner ignores cancellation or
3342
+ // the subprocess needs extra time to exit after receiving SIGTERM.
3343
+ const timer = setTimeout(abort, timeoutMs);
3344
+ try {
3345
+ const result = await Promise.race([
3346
+ runCommand(secretToolRunner, "secret-tool", args, {
3347
+ timeout: timeoutMs,
3348
+ maxBuffer: 64 * 1024,
3349
+ signal: controller.signal,
3350
+ killProcessGroup: true,
3351
+ input,
3352
+ }),
3353
+ cancelled,
3354
+ ]);
3355
+ return result;
3356
+ } catch {
3357
+ return null;
3358
+ } finally {
3359
+ clearTimeout(timer);
3360
+ signal?.removeEventListener("abort", abort);
3361
+ controller.signal.removeEventListener("abort", onAbort);
3362
+ controller.abort();
3363
+ }
3364
+ }
3365
+
3366
+ /**
3367
+ * Read the agy Secret Service entry without blocking the event loop.
3368
+ * The runner may return a result or a promise. Timeout, abort, and lookup errors
3369
+ * return null; cancellation also terminates the default subprocess.
3370
+ * @returns {Promise<string|null>} Raw keyring payload, before credential parsing.
3371
+ */
3372
+ async function readAntigravityLinuxSecretRaw(options = {}) {
3373
+ const result = await runAntigravitySecretTool(
3374
+ ["lookup", "service", "gemini", "username", "antigravity"], options,
3375
+ );
3376
+ if (!result || result.error || result.status !== 0) return null;
3377
+ const stdout = typeof result.stdout === "string"
3378
+ ? result.stdout
3379
+ : Buffer.isBuffer(result.stdout)
3380
+ ? result.stdout.toString("utf8")
3381
+ : "";
3382
+ return stdout.trim() || null;
3383
+ }
3384
+
3385
+ /** Store renewed credentials in the same entry, sending the secret through stdin. */
3386
+ async function writeAntigravityLinuxSecretRaw(raw, options = {}) {
3387
+ if (typeof raw !== "string" || !raw) return false;
3388
+ const result = await runAntigravitySecretTool(
3389
+ ["store", "--label", "Antigravity", "service", "gemini", "username", "antigravity"],
3390
+ { ...options, input: raw },
3391
+ );
3392
+ return Boolean(result && !result.error && result.status === 0);
3393
+ }
3394
+
3395
+ /**
3396
+ * Select credentials from token files and the platform keyring. Prefer fresh
3397
+ * credentials, then unknown expiry, then the most recently expired candidate.
3398
+ * Callers must await discovery and can bound keyring reads with timeoutMs/signal.
3399
+ * @returns {Promise<object|null>} Selected credentials and their source, or null.
3400
+ */
3401
+ async function loadAntigravityCredentials({
3402
+ home,
3403
+ platform = process.platform,
3404
+ securityRunner,
3405
+ secretToolRunner,
3406
+ nowMs = Date.now(),
3407
+ timeoutMs = 2000,
3408
+ signal,
3409
+ } = {}) {
3410
+ if (isAntigravityQuotaDisabled()) return null;
3411
+ const candidates = collectAntigravityFileCredentials({ home });
3412
+ if ((platform === "darwin" || typeof securityRunner === "function") && timeoutMs > 0 && !signal?.aborted) {
3413
+ const parsed = parseAntigravityCredentialPayload(readAntigravityKeychainRaw({ securityRunner, timeoutMs }));
3414
+ if (parsed) candidates.push({ ...parsed, source: "keychain", path: null });
3415
+ }
3416
+ if (platform === "linux" || typeof secretToolRunner === "function") {
3417
+ const raw = await readAntigravityLinuxSecretRaw({ secretToolRunner, timeoutMs, signal });
3418
+ const parsed = parseAntigravityCredentialPayload(raw);
3419
+ if (parsed) candidates.push({ ...parsed, source: "keyring", path: null });
3420
+ }
3421
+ return pickAntigravityCredentials(candidates, nowMs);
3422
+ }
3423
+
3424
+ /** Save refreshed tokens to their file or Linux keyring source, preserving payload fields. */
3425
+ async function persistAntigravityCredentials(creds, next, { nowMs = Date.now(), secretToolRunner, signal } = {}) {
3426
+ if (creds?.source !== "keyring" && (creds?.source !== "file" || !creds.path)) return;
3427
+ const expiresIn = Number.isFinite(next?.expiresIn) && next.expiresIn > 0 ? next.expiresIn : 3600;
3428
+ const expiry = new Date(nowMs + expiresIn * 1000).toISOString();
3429
+ try {
3430
+ let rawPayload = creds.raw;
3431
+ let keyringBase64 = false;
3432
+ if (creds.source === "keyring") {
3433
+ const currentRaw = await readAntigravityLinuxSecretRaw({ secretToolRunner, signal });
3434
+ const current = parseAntigravityCredentialPayload(currentRaw);
3435
+ // Do not restore a signed-out entry or overwrite a token changed by agy.
3436
+ if (!current || current.refreshToken !== creds.refreshToken) return;
3437
+ rawPayload = current.raw;
3438
+ keyringBase64 = currentRaw.startsWith("go-keyring-base64:");
3439
+ }
3440
+ const payload = rawPayload && typeof rawPayload === "object" ? { ...rawPayload } : {};
3441
+ if (payload.token && typeof payload.token === "object") {
3442
+ payload.token = {
3443
+ ...payload.token,
3444
+ access_token: next.accessToken,
3445
+ expiry,
3446
+ };
3447
+ if (next.refreshToken) payload.token.refresh_token = next.refreshToken;
3448
+ } else {
3449
+ payload.access_token = next.accessToken;
3450
+ payload.expiry = expiry;
3451
+ if (next.refreshToken) payload.refresh_token = next.refreshToken;
3452
+ }
3453
+ if (creds.source === "keyring") {
3454
+ const json = JSON.stringify(payload);
3455
+ const raw = keyringBase64
3456
+ ? `go-keyring-base64:${Buffer.from(json).toString("base64")}`
3457
+ : json;
3458
+ await writeAntigravityLinuxSecretRaw(raw, { secretToolRunner, signal });
3459
+ return;
3460
+ }
3461
+ const tmpPath = `${creds.path}.${process.pid}.tmp`;
3462
+ fs.writeFileSync(tmpPath, JSON.stringify(payload, null, 2), { encoding: "utf8", mode: 0o600 });
3463
+ fs.renameSync(tmpPath, creds.path);
3464
+ } catch (_error) {}
3465
+ }
3466
+
3467
+ /**
3468
+ * Refresh an agy token with the client credentials distributed in the app.
3469
+ * Missing refresh tokens and rejected requests throw an AUTH_EXPIRED error.
3470
+ * @returns {Promise<{accessToken: string, refreshToken: string, expiresIn: number}>}
3471
+ */
3472
+ async function refreshAntigravityAccessToken(refreshToken, { fetchImpl = fetch, signal } = {}) {
3473
+ if (typeof refreshToken !== "string" || !refreshToken) {
3474
+ const err = new Error(ANTIGRAVITY_AUTH_EXPIRED_MESSAGE);
3475
+ err.code = "AUTH_EXPIRED";
3476
+ throw err;
3477
+ }
3478
+ const res = await fetchImpl(ANTIGRAVITY_OAUTH_TOKEN_URL, {
3479
+ method: "POST",
3480
+ headers: {
3481
+ "Content-Type": "application/x-www-form-urlencoded",
3482
+ Accept: "application/json",
3483
+ },
3484
+ body: new URLSearchParams({
3485
+ client_id: ANTIGRAVITY_OAUTH_CLIENT_ID,
3486
+ client_secret: ANTIGRAVITY_OAUTH_CLIENT_SECRET,
3487
+ grant_type: "refresh_token",
3488
+ refresh_token: refreshToken,
3489
+ }),
3490
+ signal,
3491
+ });
3492
+ if (!res.ok) {
3493
+ const err = new Error(ANTIGRAVITY_AUTH_EXPIRED_MESSAGE);
3494
+ err.code = "AUTH_EXPIRED";
3495
+ throw err;
3496
+ }
3497
+ const json = await res.json();
3498
+ if (typeof json?.access_token !== "string" || !json.access_token) {
3499
+ throw new Error("Could not parse Antigravity token refresh response");
3500
+ }
3501
+ return {
3502
+ accessToken: json.access_token,
3503
+ refreshToken: typeof json.refresh_token === "string" && json.refresh_token
3504
+ ? json.refresh_token
3505
+ : refreshToken,
3506
+ expiresIn: Number(json.expires_in),
3507
+ };
3508
+ }
3509
+
3510
+ /** Renew expired credentials and retain rotated tokens for a retry within the same request. */
3511
+ async function resolveAntigravityAccessToken(creds, { fetchImpl = fetch, nowMs = Date.now(), forceRefresh = false, secretToolRunner, signal } = {}) {
3512
+ const expired = creds.expiryMs != null && creds.expiryMs <= nowMs + ANTIGRAVITY_TOKEN_REFRESH_SKEW_MS;
3513
+ if ((forceRefresh || expired || !creds.accessToken) && creds.refreshToken) {
3514
+ const next = await refreshAntigravityAccessToken(creds.refreshToken, { fetchImpl, signal });
3515
+ await persistAntigravityCredentials(creds, next, { nowMs, secretToolRunner, signal });
3516
+ creds.accessToken = next.accessToken;
3517
+ creds.refreshToken = next.refreshToken;
3518
+ const expiresIn = Number.isFinite(next.expiresIn) && next.expiresIn > 0 ? next.expiresIn : 3600;
3519
+ creds.expiryMs = nowMs + expiresIn * 1000;
3520
+ return next.accessToken;
3521
+ }
3522
+ if (!creds.accessToken) {
3523
+ const err = new Error(ANTIGRAVITY_AUTH_EXPIRED_MESSAGE);
3524
+ err.code = "AUTH_EXPIRED";
3525
+ throw err;
3526
+ }
3527
+ return creds.accessToken;
3528
+ }
3529
+
3530
+ /** Send a Cloud Code JSON request with the current bearer token and caller's abort signal. */
3531
+ function postAntigravityCloudCode(fetchImpl, url, accessToken, body, signal) {
3532
+ return fetchImpl(url, {
3533
+ method: "POST",
3534
+ headers: {
3535
+ Authorization: `Bearer ${accessToken}`,
3536
+ "Content-Type": "application/json",
3537
+ Accept: "application/json",
3538
+ "User-Agent": ANTIGRAVITY_USER_AGENT,
3539
+ },
3540
+ body: JSON.stringify(body ?? {}),
3541
+ signal,
3542
+ });
3543
+ }
3544
+
3545
+ /** Try the quota hosts in order; surface auth failures so the caller can refresh once. */
3546
+ async function fetchAntigravityQuotaSummaryJson(fetchImpl, accessToken, signal) {
3547
+ let lastError = null;
3548
+ for (const url of ANTIGRAVITY_QUOTA_SUMMARY_URLS) {
3549
+ try {
3550
+ const res = await postAntigravityCloudCode(fetchImpl, url, accessToken, {}, signal);
3551
+ if (res.status === 401 || res.status === 403) {
3552
+ const err = new Error(ANTIGRAVITY_AUTH_EXPIRED_MESSAGE);
3553
+ err.code = "AUTH_EXPIRED";
3554
+ err.status = res.status;
3555
+ throw err;
3556
+ }
3557
+ if (!res.ok) {
3558
+ lastError = new Error(`Antigravity API error: HTTP ${res.status}`);
3559
+ continue;
3560
+ }
3561
+ return await res.json();
3562
+ } catch (error) {
3563
+ if (error?.code === "AUTH_EXPIRED") throw error;
3564
+ lastError = error;
3565
+ }
3566
+ }
3567
+ throw lastError || new Error("Antigravity quota request failed.");
3568
+ }
3569
+
3570
+ /** Read the paid plan label without failing a successful quota response if this lookup fails. */
3571
+ async function fetchAntigravityPlanLabel(fetchImpl, accessToken, signal) {
3572
+ try {
3573
+ const res = await postAntigravityCloudCode(fetchImpl, ANTIGRAVITY_LOAD_CODE_ASSIST_URL, accessToken, {
3574
+ metadata: { ideType: "ANTIGRAVITY" },
3575
+ }, signal);
3576
+ if (!res.ok) return null;
3577
+ const json = await res.json();
3578
+ const paid = json?.paidTier;
3579
+ if (typeof paid?.name === "string" && paid.name.trim()) return paid.name.trim();
3580
+ if (typeof paid?.id === "string" && paid.id.trim()) return paid.id.trim();
3581
+ return null;
3582
+ } catch {
3583
+ return null;
3584
+ }
3585
+ }
3586
+
3587
+ /**
3588
+ * Fetch Cloud Code quota with selected credentials, refreshing on expiry or 401/403.
3589
+ * Passing creds (including null) avoids another file or keyring read.
3590
+ * @returns {Promise<object|null>} Live quota, or null when credentials are absent.
3591
+ */
3592
+ async function fetchAntigravityRemoteLimits({
3593
+ home,
3594
+ platform = process.platform,
3595
+ securityRunner,
3596
+ secretToolRunner,
3597
+ fetchImpl = fetch,
3598
+ nowMs = Date.now(),
3599
+ signal,
3600
+ creds,
3601
+ } = {}) {
3602
+ if (isAntigravityQuotaDisabled()) return null;
3603
+ const resolvedCreds = creds !== undefined
3604
+ ? creds
3605
+ : await loadAntigravityCredentials({ home, platform, securityRunner, secretToolRunner, nowMs, signal });
3606
+ if (!resolvedCreds) return null;
3607
+
3608
+ const loadWithToken = async (accessToken) => {
3609
+ const payload = await fetchAntigravityQuotaSummaryJson(fetchImpl, accessToken, signal);
3610
+ const windows = normalizeAntigravityQuotaSummary(payload);
3611
+ const accountPlan = windows.account_plan || await fetchAntigravityPlanLabel(fetchImpl, accessToken, signal);
3612
+ return {
3613
+ configured: true,
3614
+ error: null,
3615
+ account_email: windows.account_email || null,
3616
+ account_plan: accountPlan || null,
3617
+ primary_window: windows.primary_window,
3618
+ secondary_window: windows.secondary_window,
3619
+ tertiary_window: windows.tertiary_window,
3620
+ quaternary_window: windows.quaternary_window,
3621
+ };
3622
+ };
3623
+
3624
+ let accessToken = await resolveAntigravityAccessToken(resolvedCreds, { fetchImpl, nowMs, secretToolRunner, signal });
3625
+ try {
3626
+ return await loadWithToken(accessToken);
3627
+ } catch (error) {
3628
+ if (error?.code !== "AUTH_EXPIRED" || !resolvedCreds.refreshToken) throw error;
3629
+ accessToken = await resolveAntigravityAccessToken(resolvedCreds, {
3630
+ fetchImpl,
3631
+ nowMs,
3632
+ forceRefresh: true,
3633
+ secretToolRunner,
3634
+ signal,
3635
+ });
3636
+ return await loadWithToken(accessToken);
3637
+ }
3638
+ }
3639
+
3640
+ /** Request reauthentication for an auth rejection or credentials past the refresh threshold. */
3641
+ function antigravityCredentialsNeedReauth(creds, { nowMs, remoteError } = {}) {
3642
+ if (remoteError?.code === "AUTH_EXPIRED") return true;
3643
+ return Boolean(
3644
+ creds
3645
+ && creds.expiryMs != null
3646
+ && creds.expiryMs <= nowMs + ANTIGRAVITY_TOKEN_REFRESH_SKEW_MS,
3647
+ );
3648
+ }
3649
+
3650
+ /**
3651
+ * Serve last-good quota or explain why live quota is unavailable. Mark expired
3652
+ * credentials for reauthentication even when cached quota remains usable.
3653
+ * The provider path passes its selected creds to avoid repeating discovery.
3654
+ */
3655
+ async function antigravityUnavailableResult({ home, nowMs, platform, securityRunner, secretToolRunner, remoteError, creds } = {}) {
3656
+ const cached = readAntigravityLimitsCache({ home, nowMs });
3657
+ const resolvedCreds = creds !== undefined
3658
+ ? creds
3659
+ : await loadAntigravityCredentials({ home, platform, securityRunner, secretToolRunner, nowMs });
3660
+ if (cached) {
3661
+ return antigravityCredentialsNeedReauth(resolvedCreds, { nowMs, remoteError })
3662
+ ? { ...cached, auth_action_required: "reauth" }
3663
+ : cached;
3664
+ }
3665
+ if (!hasAntigravityInstallEvidence({ home }) && !resolvedCreds) {
3666
+ return { configured: false };
3667
+ }
3668
+ if (remoteError) {
3669
+ const raw = remoteError.message || "Unknown error";
3670
+ const message = raw === "timeout" || /timed out/i.test(raw)
3671
+ ? "Antigravity quota request timed out."
3672
+ : raw;
3673
+ return { configured: true, error: message };
3674
+ }
3675
+ if (resolvedCreds) {
3676
+ return { configured: true, error: ANTIGRAVITY_AUTH_EXPIRED_MESSAGE };
3677
+ }
3678
+ return { configured: true, error: ANTIGRAVITY_NOT_RUNNING_MESSAGE };
3679
+ }
3680
+
3681
+ /**
3682
+ * `providerTimeoutMs` bounds the WHOLE serial chain — credential discovery, remote
3683
+ * quota attempt, process scan, port scan, port probes and local RPCs. Mirrors
3684
+ * fetchArkCodingPlanLimits / the codex remaining-budget pattern: each step's timeout is
3685
+ * clamped to what is left of the budget, and a step whose share has run out is skipped
3686
+ * rather than issued, so the chain can never outrun the outer provider race and the
3687
+ * disk-cache fallback still resolves inside it.
3688
+ *
3689
+ * Before this was budgeted, `timeoutMs` was used as a PER-CALL timeout while the call
3690
+ * site passed it as a TOTAL budget: one 15s budget bought 15s remote + 4s ps + 4s lsof
3691
+ * + 15s per probed port + 15s per local RPC (~83s for a single port).
3692
+ */
3693
+ async function fetchAntigravityLimits({
3694
+ home,
3695
+ commandRunner,
3696
+ requestFn,
3697
+ fetchImpl = fetch,
3698
+ providerTimeoutMs = DEFAULT_PROVIDER_TIMEOUT_MS,
3699
+ nowMs = Date.now(),
3700
+ platform = process.platform,
3701
+ securityRunner,
3702
+ secretToolRunner,
3703
+ signal,
3704
+ } = {}) {
3705
+ if (isAntigravityQuotaDisabled()) return { configured: false, error: null };
3706
+ const startedAtMs = performance.now();
3707
+ // min(this step's ceiling, budget left after reserving the fallback guard).
3708
+ // 0 means "no time left" — the caller must skip the call, not issue it.
3709
+ const budgetedTimeoutMs = (stepCeilingMs) => {
3710
+ if (signal?.aborted) return 0;
3711
+ if (!Number.isFinite(providerTimeoutMs) || providerTimeoutMs <= 0) return stepCeilingMs;
3712
+ const guardMs = Math.min(
3713
+ ANTIGRAVITY_BUDGET_GUARD_MS,
3714
+ providerTimeoutMs * ANTIGRAVITY_BUDGET_GUARD_FRACTION,
3715
+ );
3716
+ const remainingMs = providerTimeoutMs - (performance.now() - startedAtMs);
3717
+ const guardedMs = Math.floor(remainingMs - guardMs);
3718
+ if (guardedMs <= 0) return 0;
3719
+ return Math.min(stepCeilingMs, guardedMs);
3720
+ };
3721
+
3722
+ const creds = await loadAntigravityCredentials({
3723
+ home,
3724
+ platform,
3725
+ securityRunner,
3726
+ secretToolRunner,
3727
+ nowMs,
3728
+ timeoutMs: budgetedTimeoutMs(2000),
3729
+ signal,
3730
+ });
3731
+
3732
+ const finalize = (payload, normalizeOptions) => {
3733
+ const result = {
3734
+ configured: true,
3735
+ error: null,
3736
+ ...normalizeAntigravityResponse(payload, normalizeOptions),
3737
+ };
3738
+ writeAntigravityLimitsCache(result, { home, nowMs });
3739
+ return result;
3740
+ };
3741
+
3742
+ const finalizeQuotaSummary = (payload) => {
3743
+ const result = {
3744
+ configured: true,
3745
+ error: null,
3746
+ ...normalizeAntigravityQuotaSummary(payload),
3747
+ };
3748
+ writeAntigravityLimitsCache(result, { home, nowMs });
3749
+ return result;
3750
+ };
3751
+
3752
+ let remoteError = null;
3753
+ const remoteTimeoutMs = budgetedTimeoutMs(ANTIGRAVITY_REMOTE_TIMEOUT_MS);
3754
+ if (remoteTimeoutMs > 0) {
3755
+ try {
3756
+ const remote = await withProviderTimeout(
3757
+ fetchAntigravityRemoteLimits({
3758
+ home,
3759
+ platform,
3760
+ securityRunner,
3761
+ secretToolRunner,
3762
+ fetchImpl,
3763
+ nowMs,
3764
+ signal,
3765
+ creds,
3766
+ }),
3767
+ "Antigravity",
3768
+ remoteTimeoutMs,
3769
+ );
3770
+ if (remote?.configured && !remote.error && hasAntigravityWindow(remote)) {
3771
+ writeAntigravityLimitsCache(remote, { home, nowMs });
3772
+ return remote;
3773
+ }
3774
+ } catch (error) {
3775
+ remoteError = error;
3776
+ }
3777
+ }
3778
+
3779
+ try {
3780
+ const processScanTimeoutMs = budgetedTimeoutMs(ANTIGRAVITY_PROCESS_SCAN_TIMEOUT_MS);
3781
+ if (processScanTimeoutMs <= 0) {
3782
+ throw new Error(ANTIGRAVITY_BUDGET_EXHAUSTED_MESSAGE);
3783
+ }
3784
+ const processInfo = await detectAntigravityProcess({
3785
+ commandRunner,
3786
+ platform,
3787
+ timeoutMs: processScanTimeoutMs,
3788
+ signal,
3789
+ });
3790
+ if (!processInfo.configured) {
3791
+ return antigravityUnavailableResult({
3792
+ home,
3793
+ nowMs,
3794
+ platform,
3795
+ securityRunner,
3796
+ secretToolRunner,
3797
+ remoteError,
3798
+ creds,
3799
+ });
3800
+ }
3801
+ if (processInfo.error) {
3802
+ return { configured: true, error: processInfo.error };
3803
+ }
3804
+ const portScanTimeoutMs = budgetedTimeoutMs(ANTIGRAVITY_PROCESS_SCAN_TIMEOUT_MS);
3805
+ if (portScanTimeoutMs <= 0) {
3806
+ throw new Error(ANTIGRAVITY_BUDGET_EXHAUSTED_MESSAGE);
3807
+ }
3808
+ const ports = await listAntigravityPorts(processInfo.pid, {
3809
+ commandRunner,
3810
+ platform,
3811
+ timeoutMs: portScanTimeoutMs,
3812
+ signal,
3813
+ });
3814
+ let workingPort = null;
3815
+ let workingScheme = "https";
3816
+ // Each probe draws from the same budget, so a long port list cannot multiply it:
3817
+ // once the guard is reached the loop stops and the cache fallback runs instead.
3818
+ for (const port of ports) {
3819
+ const probeTimeoutMs = budgetedTimeoutMs(ANTIGRAVITY_LOCAL_REQUEST_TIMEOUT_MS);
3820
+ if (probeTimeoutMs <= 0) break;
3821
+ if (await probeAntigravityPort(port, processInfo.csrfToken, { timeoutMs: probeTimeoutMs, requestFn, signal })) {
3822
+ workingPort = port;
3823
+ break;
3824
+ }
3825
+ // agy CLI serves both HTTPS and HTTP; no CSRF needed
3826
+ if (!processInfo.csrfToken) {
3827
+ const httpProbeTimeoutMs = budgetedTimeoutMs(ANTIGRAVITY_LOCAL_REQUEST_TIMEOUT_MS);
3828
+ if (httpProbeTimeoutMs <= 0) break;
3829
+ if (await probeAntigravityPort(port, null, { timeoutMs: httpProbeTimeoutMs, requestFn, scheme: "http", signal })) {
3830
+ workingPort = port;
3831
+ workingScheme = "http";
3832
+ break;
3833
+ }
3834
+ }
3835
+ }
3836
+ if (!workingPort) {
3837
+ throw new Error("Antigravity port detection failed: no working API port found");
3838
+ }
3839
+
3840
+ const quotaTimeoutMs = budgetedTimeoutMs(ANTIGRAVITY_LOCAL_REQUEST_TIMEOUT_MS);
3841
+ if (quotaTimeoutMs > 0) {
3842
+ try {
3843
+ const quotaSummary = await requestLocalJson({
3844
+ scheme: workingScheme,
3845
+ port: workingPort,
3846
+ path: "/exa.language_server_pb.LanguageServerService/RetrieveUserQuotaSummary",
3847
+ body: antigravityDefaultBody(),
3848
+ csrfToken: processInfo.csrfToken,
3849
+ timeoutMs: quotaTimeoutMs,
3850
+ requestFn,
3851
+ signal,
3852
+ });
3853
+ return finalizeQuotaSummary(quotaSummary);
3854
+ } catch (_quotaError) {
3855
+ // quota summary not available (IDE servers return 404) → fall back to GetUserStatus
3856
+ }
3857
+ }
3858
+
3859
+ const userStatusTimeoutMs = budgetedTimeoutMs(ANTIGRAVITY_LOCAL_REQUEST_TIMEOUT_MS);
3860
+ if (userStatusTimeoutMs <= 0) {
3861
+ throw new Error(ANTIGRAVITY_BUDGET_EXHAUSTED_MESSAGE);
3862
+ }
3863
+ try {
3864
+ const userStatus = await requestLocalJson({
3865
+ scheme: workingScheme,
3866
+ port: workingPort,
3867
+ path: "/exa.language_server_pb.LanguageServerService/GetUserStatus",
3868
+ body: antigravityDefaultBody(),
3869
+ csrfToken: processInfo.csrfToken,
3870
+ timeoutMs: userStatusTimeoutMs,
3871
+ requestFn,
3872
+ signal,
3873
+ });
3874
+ return finalize(userStatus);
3875
+ } catch (primaryError) {
3876
+ const configsTimeoutMs = budgetedTimeoutMs(ANTIGRAVITY_LOCAL_REQUEST_TIMEOUT_MS);
3877
+ if (configsTimeoutMs <= 0) throw primaryError;
3878
+ const fallbackPort =
3879
+ Number.isFinite(processInfo.extensionPort) && processInfo.extensionPort > 0
3880
+ ? processInfo.extensionPort
3881
+ : workingPort;
3882
+ // agy has no extension server port; try HTTP on the same port
3883
+ const fallbackScheme = !processInfo.csrfToken && fallbackPort === workingPort
3884
+ ? (workingScheme === "https" ? "http" : "https")
3885
+ : (fallbackPort === workingPort ? "https" : "http");
3886
+ const modelConfigs = await requestLocalJson({
3887
+ scheme: fallbackScheme,
3888
+ port: fallbackPort,
3889
+ path: "/exa.language_server_pb.LanguageServerService/GetCommandModelConfigs",
3890
+ body: antigravityDefaultBody(),
3891
+ csrfToken: processInfo.csrfToken,
3892
+ timeoutMs: configsTimeoutMs,
3893
+ requestFn,
3894
+ signal,
3895
+ });
3896
+ return finalize(modelConfigs, { fallbackToConfigs: true });
3897
+ }
3898
+ } catch (error) {
3899
+ return antigravityUnavailableResult({
3900
+ home,
3901
+ nowMs,
3902
+ platform,
3903
+ securityRunner,
3904
+ secretToolRunner,
3905
+ remoteError: remoteError || error,
3906
+ creds,
3907
+ });
3908
+ }
3909
+ }
3910
+
3911
+ function toTitleCase(s) {
3912
+ return s.split(/\s+/).filter(Boolean)
3913
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(" ");
3914
+ }
3915
+
3916
+ // Normalize a plan tier name: free/empty/placeholder -> null; otherwise strip the
3917
+ // leading brand word and Title Case the rest.
3918
+ function normalizePlanLabel(raw, brand) {
3919
+ if (raw == null) return null;
3920
+ let s = String(raw).replace(/[_-]+/g, " ").replace(/\s+/g, " ").trim();
3921
+ if (!s) return null;
3922
+ const lower = s.toLowerCase();
3923
+ if (["free", "none", "unknown"].includes(lower)) return null;
3924
+ if (brand && lower === brand.toLowerCase()) return null; // e.g. Kiro defaults plan_name to "Kiro" when parse fails
3925
+ if (brand) {
3926
+ s = s.replace(new RegExp("^" + brand + "\\s+", "i"), "").trim();
3927
+ if (!s) return null;
3928
+ }
3929
+ return toTitleCase(s);
3930
+ }
3931
+
3932
+ // Attach plan_label only to a configured, error-free provider object (immutable).
3933
+ function withPlanLabel(obj, raw, brand) {
3934
+ if (!obj || !obj.configured || obj.error) return obj;
3935
+ return { ...obj, plan_label: normalizePlanLabel(raw, brand) };
3936
+ }
3937
+
3938
+ // Single-flight guard: concurrent cache misses share one upstream fetch instead of
3939
+ // each triggering the full 9-provider round (Claude's OAuth usage endpoint 429s when
3940
+ // hammered). Survives an external resetUsageLimitsCache() (refresh=1 path in
3941
+ // local-api.js): a refresh arriving while a fetch is already running reuses that
3942
+ // in-flight fetch and returns its result.
3943
+ const inFlightBySelection = {};
3944
+ for (const key of USAGE_LIMITS_SELECTION_KEYS) inFlightBySelection[key] = null;
3945
+
3946
+ // Codex stamps reset_at as unix seconds; every other provider (and Claude's
3947
+ // resets_at) uses ISO strings. Numbers that look like epoch milliseconds are
3948
+ // accepted as-is so a future provider can't silently regress this.
3949
+ function resetValueToMs(value) {
3950
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) {
3951
+ return value < 1e12 ? value * 1000 : value;
3952
+ }
3953
+ return parseTimeMs(value);
3954
+ }
3955
+
3956
+ // Walk the aggregated response and collect every window reset timestamp,
3957
+ // whatever the provider-specific nesting looks like.
3958
+ function collectResetTimesMs(node, out) {
3959
+ if (!node || typeof node !== "object") return;
3960
+ for (const [key, value] of Object.entries(node)) {
3961
+ if (key === "reset_at" || key === "resets_at") {
3962
+ const ms = resetValueToMs(value);
3963
+ if (ms !== null) out.push(ms);
3964
+ } else if (value && typeof value === "object") {
3965
+ collectResetTimesMs(value, out);
3966
+ }
3967
+ }
3968
+ }
3969
+
3970
+ // The moment any window rolls over, cached data stops being current — reset
3971
+ // detection (the menu bar confetti) would otherwise lag by up to the full TTL.
3972
+ function cacheExpiresAtMs(data, fetchedAtMs) {
3973
+ const times = [];
3974
+ collectResetTimesMs(data, times);
3975
+ const upcoming = times.filter((t) => t > fetchedAtMs);
3976
+ const ttlExpiry = fetchedAtMs + CACHE_TTL_MS;
3977
+ if (upcoming.length === 0) return ttlExpiry;
3978
+ return Math.min(ttlExpiry, Math.max(Math.min(...upcoming), fetchedAtMs + CACHE_MIN_TTL_MS));
3979
+ }
3980
+
3981
+ /** Return cached quota or share one in-flight fetch for the requested provider selection. */
3982
+ async function getUsageLimits(options = {}) {
3983
+ const selection = usageLimitsSelectionKey(options);
3984
+ const cache = cacheBySelection[selection];
3985
+ const nowMs = Date.now();
3986
+ if (cache.data && nowMs < cache.expiresAtMs) {
3987
+ return cache.data;
3988
+ }
3989
+ if (inFlightBySelection[selection]) {
3990
+ return inFlightBySelection[selection];
3991
+ }
3992
+ const promise = fetchUsageLimitsUncached({ ...options, selectionKey: selection }).finally(() => {
3993
+ if (inFlightBySelection[selection] === promise) inFlightBySelection[selection] = null;
3994
+ });
3995
+ inFlightBySelection[selection] = promise;
3996
+ return promise;
3997
+ }
3998
+
3999
+ /**
4000
+ * Fetch one aggregate for the selected providers and update its cache partition.
4001
+ * Forward injected credential/process runners so tests can avoid host accounts.
4002
+ */
4003
+ async function fetchUsageLimitsUncached({
4004
+ home,
4005
+ env,
4006
+ platform,
4007
+ securityRunner,
4008
+ secretToolRunner,
4009
+ fetchImpl = fetch,
4010
+ commandRunner,
4011
+ requestFn,
4012
+ now = new Date(),
4013
+ providerTimeoutMs = DEFAULT_PROVIDER_TIMEOUT_MS,
4014
+ forceRefresh = false,
4015
+ devinEnabled = false,
4016
+ // Selection key fixed by getUsageLimits before the fetch began. Re-deriving it
4017
+ // here would let an opt-out flipped mid-fetch store a pre-opt-out result in the
4018
+ // post-opt-out slot.
4019
+ selectionKey,
4020
+ } = {}) {
4021
+ const nowMs = Date.now();
4022
+
4023
+ const [claudeOauth, claudeSubscription, codexAuth] = await Promise.all([
4024
+ Promise.resolve().then(() => readClaudeCodeOauthToken({ platform, securityRunner, home, nowMs })),
4025
+ Promise.resolve().then(() => detectClaudeCodeSubscriptionDetails({ platform, securityRunner, home })),
4026
+ readCodexAuthBundle({ home, env }),
4027
+ ]);
4028
+ const claudeToken = claudeOauth?.accessToken || null;
4029
+ const claudeTokenExpiresAtMs = claudeOauth?.expiresAtMs ?? null;
4030
+ const claudePlanType = claudeSubscription?.planType || null;
4031
+
4032
+ // Match the official Codex CLI: prefer the access token's JWT expiry and refresh only
4033
+ // within five minutes of it; fall back to last_refresh >8 days for opaque/legacy tokens.
4034
+ // Best-effort: a refresh failure still falls through to the existing access token.
4035
+ let refreshError = null;
4036
+ let codexAuthRefreshed = codexAuth;
4037
+ if (codexAuth
4038
+ && isTokenStale(codexAuth.lastRefresh, nowMs, codexAuth.accessToken)
4039
+ && codexAuth.refreshToken) {
4040
+ try {
4041
+ const newTokens = await refreshCodexTokens({
4042
+ refreshToken: codexAuth.refreshToken,
4043
+ fetchImpl,
4044
+ });
4045
+ const updatedAuth = await persistRefreshedAuth(
4046
+ codexAuth.authPath,
4047
+ codexAuth.authJson,
4048
+ newTokens,
4049
+ );
4050
+ codexAuthRefreshed = {
4051
+ ...codexAuth,
4052
+ accessToken: newTokens.access_token,
4053
+ refreshToken: newTokens.refresh_token,
4054
+ lastRefresh: updatedAuth.last_refresh,
4055
+ authJson: updatedAuth,
4056
+ };
4057
+ } catch (err) {
4058
+ refreshError = err;
4059
+ }
4060
+ }
4061
+
4062
+ const codexToken = codexAuthRefreshed?.accessToken || null;
4063
+ const codexAccountId = codexAuthRefreshed?.accountId || null;
4064
+ const codexPlanType = codexAuthRefreshed?.planType || null;
4065
+
4066
+ // Skip the upstream Claude call entirely while a 429 cooldown is active — calling again
4067
+ // just renews the penalty. The result handling below serves cache or a cooldown message.
4068
+ const claudeRetryAtMs = claudeToken
4069
+ ? readClaudeRateLimitRetryAtMs({ home, nowMs, tokenExpiresAtMs: claudeTokenExpiresAtMs })
4070
+ : null;
4071
+ // Also avoid cross-process hammering after a recent successful read: embedded-server
4072
+ // restarts and background polls read the disk cache instead of spending another Claude
4073
+ // OAuth usage request. Claude Code's own cached read counts too, so a session that just
4074
+ // refreshed its usage spares this process a call against the same throttled budget. An explicit user refresh (refresh=1 → forceRefresh) punches
4075
+ // through this cache — but never through the 429 cooldown above, which is exactly the
4076
+ // hammering the cooldown exists to prevent.
4077
+ const freshClaudeCache = claudeToken && !forceRefresh
4078
+ ? readFreshClaudeLimitsCache({ home, nowMs })
4079
+ : null;
4080
+
4081
+ const providerFetch = withFetchTimeout(fetchImpl, providerTimeoutMs);
4082
+ const [claudeResult, codexResult, cursor, kimi, gemini, kiro, antigravity, copilot, grok, zcode, opencodeGoRaw, qoder, qoderCn, codingPlan, agentPlan, commandCodeRaw, devinRaw, claudeServiceStatus] = await Promise.all([
4083
+ claudeToken && !freshClaudeCache && !claudeRetryAtMs
4084
+ ? withProviderTimeout(fetchClaudeUsageLimits(claudeToken, { fetchImpl: providerFetch, maxAttempts: 1 }), "Claude", providerTimeoutMs).then(
4085
+ (value) => ({ status: "fulfilled", value }),
4086
+ (reason) => ({ status: "rejected", reason }),
4087
+ )
4088
+ : Promise.resolve(null),
4089
+ codexToken
4090
+ ? fetchCodexUsageLimits(codexToken, {
4091
+ fetchImpl: providerFetch,
4092
+ accountId: codexAccountId,
4093
+ providerTimeoutMs,
4094
+ }).then(
4095
+ (value) => ({ status: "fulfilled", value }),
4096
+ (reason) => ({ status: "rejected", reason }),
4097
+ )
4098
+ : Promise.resolve(null),
4099
+ withProviderTimeout(fetchCursorLimits({ home, fetchImpl: providerFetch }), "Cursor", providerTimeoutMs)
4100
+ .catch((reason) => ({ configured: true, error: reason?.message || "Unknown error" })),
4101
+ withProviderTimeout(fetchKimiLimits({ home, env, fetchImpl: providerFetch }), "Kimi", providerTimeoutMs)
4102
+ .catch((reason) => ({ configured: true, error: reason?.message || "Unknown error" })),
4103
+ withProviderTimeout(fetchGeminiLimits({ home, env, fetchImpl: providerFetch, commandRunner }), "Gemini", providerTimeoutMs)
4104
+ .catch((reason) => ({ configured: true, error: reason?.message || "Unknown error" })),
4105
+ fetchKiroLimits({ commandRunner, now, platform, home }),
4106
+ // Antigravity's own budget keeps the serial chain inside providerTimeoutMs; this
4107
+ // outer race is the enforcing backstop every other provider already has, and the
4108
+ // signal makes a fired race actually kill the spawned scans and open sockets.
4109
+ withAbortableProviderTimeout(
4110
+ (signal) => fetchAntigravityLimits({
4111
+ home,
4112
+ commandRunner,
4113
+ requestFn,
4114
+ fetchImpl: providerFetch,
4115
+ nowMs,
4116
+ platform,
4117
+ securityRunner,
4118
+ secretToolRunner,
4119
+ providerTimeoutMs,
4120
+ signal,
4121
+ }),
4122
+ "Antigravity",
4123
+ providerTimeoutMs,
4124
+ ).catch((reason) => ({ configured: true, error: reason?.message || "Unknown error" })),
4125
+ withProviderTimeout(fetchCopilotLimits({ home, env, fetchImpl: providerFetch, platform, securityRunner }), "GitHub Copilot", providerTimeoutMs)
4126
+ .catch((reason) => ({ configured: true, error: reason?.message || "Unknown error" })),
4127
+ withProviderTimeout(fetchGrokLimits({ home, env, fetchImpl: providerFetch, timeoutMs: providerTimeoutMs }), "Grok Build", providerTimeoutMs)
4128
+ .catch((reason) => ({ configured: true, error: reason?.message || "Unknown error" })),
4129
+ withProviderTimeout(fetchZcodeLimits({ home, env, fetchImpl: providerFetch, providerTimeoutMs }), "ZCode", providerTimeoutMs)
4130
+ .catch((reason) => ({ configured: true, error: reason?.message || "Unknown error" })),
4131
+ // OpenCode Go: authoritative subscription windows come from the dashboard
4132
+ // scrape; local opencode.db cost is available only as an explicit estimate.
4133
+ // See src/lib/opencode-go-limits.js.
4134
+ withProviderTimeout(fetchOpencodeGoLimits({ home, env, fetchImpl: providerFetch }), "OpenCode Go", providerTimeoutMs)
4135
+ .catch((reason) => ({ configured: true, error: reason?.message || "Unknown error" })),
4136
+ withProviderTimeout(
4137
+ fetchQoderLimits({
4138
+ home,
4139
+ env,
4140
+ platform,
4141
+ fetchImpl: providerFetch,
4142
+ }),
4143
+ "Qoder",
4144
+ providerTimeoutMs,
4145
+ ).catch((reason) => ({ configured: true, error: reason?.message || "Unknown error" })),
4146
+ withProviderTimeout(
4147
+ fetchQoderCnLimits({
4148
+ home,
4149
+ env,
4150
+ platform,
4151
+ fetchImpl: providerFetch,
4152
+ }),
4153
+ "Qoder CN",
4154
+ providerTimeoutMs,
4155
+ ).catch((reason) => ({ configured: true, error: reason?.message || "Unknown error" })),
4156
+ // Ark Coding Plan / Agent Plan (火山方舟): two parallel subscription
4157
+ // products sharing the same arkcli binary. No token-consumption source —
4158
+ // consumption for the compatible CLIs is already counted from their
4159
+ // local files; these only surface the 5h/week/month quota percentages.
4160
+ withAbortableProviderTimeout(
4161
+ (signal) => fetchArkCodingPlanLimits({
4162
+ commandRunner,
4163
+ home,
4164
+ nowMs,
4165
+ platform,
4166
+ signal,
4167
+ providerTimeoutMs,
4168
+ }),
4169
+ "Ark Coding Plan",
4170
+ providerTimeoutMs,
4171
+ ).catch((reason) => ({ configured: true, error: reason?.message || "Unknown error" })),
4172
+ withAbortableProviderTimeout(
4173
+ (signal) => fetchArkAgentPlanLimits({
4174
+ commandRunner,
4175
+ home,
4176
+ nowMs,
4177
+ platform,
4178
+ signal,
4179
+ providerTimeoutMs,
4180
+ }),
4181
+ "Ark Agent Plan",
4182
+ providerTimeoutMs,
4183
+ ).catch((reason) => ({ configured: true, error: reason?.message || "Unknown error" })),
4184
+ // CommandCode (commandcode.ai): official subscription windows (5h + weekly)
4185
+ // from the CLI's own alpha endpoints, keyed by the apiKey the CLI stores in
4186
+ // ~/.commandcode/auth.json (or COMMAND_CODE_API_KEY). No local fallback —
4187
+ // window state lives server-side. fetchCommandcodeLimits throws on auth
4188
+ // expiry so the assemble step below can flag auth_action_required. The
4189
+ // outer race bounds the whole slot: without it three sequential per-request
4190
+ // timeouts (whoami, then credits+subscriptions) could hold the aggregate
4191
+ // ~2x longer than any sibling provider.
4192
+ withProviderTimeout(fetchCommandcodeLimits({ home, env, fetchImpl: providerFetch }), "CommandCode", providerTimeoutMs)
4193
+ .then(
4194
+ (value) => ({ status: "fulfilled", value }),
4195
+ (reason) => ({ status: "rejected", reason }),
4196
+ ),
4197
+ // Devin (devin.ai): daily/weekly subscription quota from the official
4198
+ // GetPlanStatus RPC, keyed by the session token the Devin CLI stores in
4199
+ // ~/.local/share/devin/credentials.toml. No local fallback — window state
4200
+ // lives server-side. fetchDevinLimits throws on auth expiry so the
4201
+ // assemble step below can flag auth_action_required.
4202
+ withProviderTimeout(fetchDevinLimits({ home, env, enabled: devinEnabled === true, fetchImpl: providerFetch }), "Devin", providerTimeoutMs)
4203
+ .then(
4204
+ (value) => ({ status: "fulfilled", value }),
4205
+ (reason) => ({ status: "rejected", reason }),
4206
+ ),
4207
+ // Public status-page probe (fail-soft, own 5-min cache in provider-status.js).
4208
+ // Only probed for configured accounts — without a token the Claude section
4209
+ // never renders, so the reading would have nowhere to go.
4210
+ claudeToken
4211
+ ? fetchProviderServiceStatus("claude", { fetchImpl, nowMs })
4212
+ : Promise.resolve(null),
4213
+ ]);
4214
+
4215
+ let claude;
4216
+ if (!claudeToken) {
4217
+ // Claude Code blanks `accessToken`/`refreshToken` in place when its login expires
4218
+ // (macOS Keychain item and .credentials.json alike) instead of removing the entry,
4219
+ // so "no token" is ambiguous: never signed in, or signed in and expired. An entry
4220
+ // that still exists means the latter — reporting `configured: false` there hides the
4221
+ // whole Claude section while the usage bars (parsed from local logs, no auth needed)
4222
+ // keep updating, which reads as "Token Usage doesn't support my plan" rather than
4223
+ // "your CLI login expired". Existence-only probe: no secret is read here.
4224
+ const credentialsPresent = detectClaudeCodeCredentialsPresence({ platform, securityRunner, home });
4225
+ claude = credentialsPresent
4226
+ ? { configured: true, error: CLAUDE_AUTH_EXPIRED_MESSAGE, auth_action_required: "reauth" }
4227
+ : { configured: false };
4228
+ } else if (freshClaudeCache) {
4229
+ claude = freshClaudeCache;
4230
+ } else if (claudeResult && claudeResult.status === "fulfilled") {
4231
+ claude = {
4232
+ configured: true,
4233
+ error: null,
4234
+ five_hour: claudeResult.value.five_hour,
4235
+ seven_day: claudeResult.value.seven_day,
4236
+ seven_day_opus: claudeResult.value.seven_day_opus,
4237
+ weekly_scoped: claudeResult.value.weekly_scoped,
4238
+ extra_usage: claudeResult.value.extra_usage,
4239
+ // A live read is current as of now. `stale`/`cached_at` are always present so
4240
+ // the client can render an "Updated Xm ago" age without guessing whether the
4241
+ // response was live or served from the disk-cache fallback (the cached paths
4242
+ // above already carry them). Mirrors the Codex live-success block below.
4243
+ stale: false,
4244
+ cached_at: new Date(nowMs).toISOString(),
4245
+ };
4246
+ writeClaudeLimitsCache(claude, { home, nowMs });
4247
+ clearClaudeRateLimitCooldown({ home });
4248
+ } else {
4249
+ // Either a fresh 429 (record its cooldown) or a call we skipped because a cooldown was
4250
+ // already active. Serve the last successful read so the bars stay visible; otherwise
4251
+ // surface an accurate "retry in ~Nm" message rather than the misleading hardcoded one.
4252
+ const reason = claudeResult?.reason;
4253
+ if (reason?.code === "RATE_LIMITED") {
4254
+ writeClaudeRateLimitCooldown(reason.retryAfterSec, {
4255
+ home,
4256
+ nowMs,
4257
+ tokenExpiresAtMs: claudeTokenExpiresAtMs,
4258
+ });
4259
+ }
4260
+ const cached = readClaudeLimitsCache({ home, nowMs });
4261
+ if (cached) {
4262
+ claude = cached;
4263
+ } else {
4264
+ const retryAtMs = readClaudeRateLimitRetryAtMs({
4265
+ home,
4266
+ nowMs,
4267
+ tokenExpiresAtMs: claudeTokenExpiresAtMs,
4268
+ }) || claudeRetryAtMs;
4269
+ claude = {
4270
+ configured: true,
4271
+ error: retryAtMs
4272
+ ? formatClaudeRateLimitMessage(Math.round((retryAtMs - nowMs) / 1000))
4273
+ : reason?.message || "Unknown error",
4274
+ };
4275
+ }
4276
+ // An expired OAuth token means every future fetch fails the same way until the
4277
+ // user runs `claude` again — serving the cache silently would make refresh look
4278
+ // broken (issue #330). Flag it so the client can say why the bars stopped moving.
4279
+ if (reason?.code === "AUTH_EXPIRED") {
4280
+ claude = { ...claude, auth_action_required: "reauth" };
4281
+ }
4282
+ }
4283
+
4284
+ // Expose the active 429 cool-down expiry (if any) on the Claude object so the
4285
+ // client can (a) show when the next refresh is due next to stale bars and
4286
+ // (b) schedule a one-shot refresh the instant the cool-down lifts instead of
4287
+ // waiting out the poll interval. Re-read here (not the pre-fetch value) so a
4288
+ // cool-down just armed by this cycle's 429 is included; a successful read above
4289
+ // cleared the file, so this is null in the happy path.
4290
+ if (claude.configured) {
4291
+ const claudeCooldownMs = readClaudeRateLimitRetryAtMs({
4292
+ home,
4293
+ nowMs,
4294
+ tokenExpiresAtMs: claudeTokenExpiresAtMs,
4295
+ });
4296
+ if (claudeCooldownMs) {
4297
+ claude.retry_at = new Date(claudeCooldownMs).toISOString();
4298
+ }
4299
+ }
4300
+
4301
+ // Attach the service-status reading AFTER assembly so it rides on every path
4302
+ // (live, fresh-cache, stale-cache, error) but never gets persisted by
4303
+ // writeClaudeLimitsCache above — a disk cache must not resurrect an incident
4304
+ // banner hours later. Only active incidents ship; "none" is omitted so the
4305
+ // client renders nothing in the happy path.
4306
+ if (claude.configured && claudeServiceStatus && claudeServiceStatus.indicator !== "none") {
4307
+ claude.service_status = claudeServiceStatus;
4308
+ }
4309
+
4310
+ const codexRefreshRequiresReauth = refreshError?.code === "REFRESH_TOKEN_EXPIRED";
4311
+ const codexLiveUsageSucceeded = codexResult?.status === "fulfilled"
4312
+ && codexResult.value.upstream_status === 200;
4313
+ let codex;
4314
+ if (!codexToken) {
4315
+ codex = { configured: false };
4316
+ } else if (codexResult?.status === "fulfilled"
4317
+ && (!codexRefreshRequiresReauth || codexLiveUsageSucceeded)) {
4318
+ // A proactive refresh can fail while the existing access token is still valid.
4319
+ // Prefer a confirmed 200 live usage read over the refresh error so usable quota
4320
+ // data is not discarded before the access token actually expires. A neutral
4321
+ // 401/403/404 no-data response must not mask a failed refresh.
4322
+ codex = {
4323
+ configured: true,
4324
+ error: null,
4325
+ plan_type: codexPlanType || null,
4326
+ primary_window: codexResult.value.primary_window,
4327
+ secondary_window: codexResult.value.secondary_window,
4328
+ credit_window: codexResult.value.credit_window,
4329
+ spark_primary_window: codexResult.value.spark_primary_window,
4330
+ spark_secondary_window: codexResult.value.spark_secondary_window,
4331
+ reset_credits: codexResult.value.reset_credits,
4332
+ // Live read is current as of now; the stale fallback path below serves the
4333
+ // disk cache with `stale: true`. Always emitting both lets the client show a
4334
+ // data-age label uniformly (see the Claude live-success block).
4335
+ stale: false,
4336
+ cached_at: new Date(nowMs).toISOString(),
4337
+ };
4338
+ writeCodexLimitsCache(codex, { home, nowMs });
4339
+ } else if (codexRefreshRequiresReauth) {
4340
+ // Refresh token is dead — the user must re-run `codex` to log in again. Surface a
4341
+ // specific, actionable message rather than the generic "Fetch failed", but only
4342
+ // after the existing access token also failed to fetch live usage above.
4343
+ codex = {
4344
+ configured: true,
4345
+ error: refreshError.message,
4346
+ auth_action_required: "reauth",
4347
+ };
4348
+ } else if (!codexResult || codexResult.status === "rejected") {
4349
+ // Live fetch failed or timed out (Codex hits chatgpt.com fresh every poll with no
4350
+ // rate-limit cooldown, so a slow network shows up here often). Serve the last successful
4351
+ // read so the bars stay visible instead of a red error, mirroring the Claude stale path.
4352
+ const cached = readCodexLimitsCache({ home, nowMs });
4353
+ if (cached) {
4354
+ codex = cached;
4355
+ } else {
4356
+ codex = { configured: true, error: codexResult?.reason?.message || "Unknown error" };
4357
+ }
4358
+ }
4359
+
4360
+ // OpenCode Go: persist last successful windows so a transient timeout/5xx
4361
+ // (common on GFW-affected routes to opencode.ai) serves stale bars instead of
4362
+ // a flashing "fetch failed". Mirrors Codex / Claude / Antigravity.
4363
+ // Auth errors (401/403 invalid key, missing subscription, expired cookie) are
4364
+ // actionable and must not be hidden behind stale cache — they carry
4365
+ // `auth_error:true` from opencode-go-limits.js.
4366
+ const opencodeGoIsAuthError =
4367
+ Boolean(opencodeGoRaw?.auth_error) ||
4368
+ (typeof opencodeGoRaw?.error === "string" &&
4369
+ /Not signed in|auth cookie|Refresh the auth cookie|Failed to resolve Workspace ID.*401|Failed to resolve Workspace ID.*403/i.test(
4370
+ opencodeGoRaw.error,
4371
+ ));
4372
+ let opencodeGo;
4373
+ if (opencodeGoRaw && opencodeGoRaw.configured === false) {
4374
+ opencodeGo = opencodeGoRaw;
4375
+ } else if (opencodeGoIsAuthError) {
4376
+ opencodeGo = opencodeGoRaw;
4377
+ } else if (opencodeGoRaw?.subscription_status === "inactive") {
4378
+ opencodeGo = opencodeGoRaw;
4379
+ } else if (opencodeGoRaw && !opencodeGoRaw.error && hasOpencodeGoWindow(opencodeGoRaw)) {
4380
+ opencodeGo = {
4381
+ ...opencodeGoRaw,
4382
+ stale: false,
4383
+ cached_at: new Date(nowMs).toISOString(),
4384
+ };
4385
+ writeOpencodeGoLimitsCache(opencodeGo, { home, nowMs });
4386
+ } else {
4387
+ const cached = readOpencodeGoLimitsCache({ home, nowMs });
4388
+ if (cached) {
4389
+ opencodeGo = cached;
4390
+ } else {
4391
+ opencodeGo = opencodeGoRaw || { configured: true, error: "Unknown error" };
4392
+ }
4393
+ }
4394
+
4395
+ // CommandCode: official windows straight from the API — nothing to cache on
4396
+ // disk beyond the shared 2-minute in-memory cache, so keep the assembly
4397
+ // simple. A fulfilled `configured: false` means no apiKey found; a rejected
4398
+ // fetch surfaced an auth-expired error the panel should act on.
4399
+ let commandCodeObj;
4400
+ if (commandCodeRaw?.status === "fulfilled") {
4401
+ const value = commandCodeRaw.value;
4402
+ commandCodeObj = value && value.configured === false
4403
+ ? value
4404
+ : { ...value, stale: false, cached_at: new Date(nowMs).toISOString() };
4405
+ } else {
4406
+ const reason = commandCodeRaw?.reason || null;
4407
+ const authExpired = Boolean(
4408
+ reason &&
4409
+ (reason?.code === "AUTH_EXPIRED" ||
4410
+ /token expired|run `cmd login`|Not authenticated/i.test(reason?.message || "")),
4411
+ );
4412
+ commandCodeObj = authExpired
4413
+ ? { configured: true, error: reason?.message || "Unknown error", auth_action_required: "reauth" }
4414
+ : { configured: true, error: reason?.message || "Unknown error" };
4415
+ }
4416
+
4417
+ // Devin: server-owned quota windows like CommandCode — a fulfilled
4418
+ // `configured: false` means no CLI credentials; a rejected fetch with
4419
+ // AUTH_EXPIRED flags auth_action_required for the re-sign-in hint.
4420
+ let devinObj;
4421
+ if (devinRaw?.status === "fulfilled") {
4422
+ const value = devinRaw.value;
4423
+ devinObj = value && value.configured === false
4424
+ ? value
4425
+ : { ...value, stale: false, cached_at: new Date(nowMs).toISOString() };
4426
+ } else {
4427
+ const reason = devinRaw?.reason || null;
4428
+ devinObj = reason?.code === "AUTH_EXPIRED"
4429
+ ? { configured: true, error: reason?.message || "Unknown error", auth_action_required: "reauth" }
4430
+ : { configured: true, error: reason?.message || "Unknown error" };
4431
+ }
4432
+
4433
+ const cursorLimits = cursorSandDuplicatesGrokPool(cursor, grok)
4434
+ ? { ...cursor, quaternary_window: null }
4435
+ : cursor;
4436
+
4437
+ const data = {
4438
+ fetched_at: new Date(nowMs).toISOString(),
4439
+ claude: withPlanLabel(claude, claudePlanType, "Claude"),
4440
+ codex: withPlanLabel(codex, codex.plan_type, "Codex"),
4441
+ cursor: withPlanLabel(cursorLimits, cursorLimits.membership_type, "Cursor"),
4442
+ // Kimi's subType (TYPE_PURCHASE/TYPE_EVENT) is the credit *source*, not a plan
4443
+ // tier, and membership.level is an opaque enum (LEVEL_INTERMEDIATE) with no
4444
+ // authoritative human-readable plan mapping. Both rendered as garbage like
4445
+ // "Kimi Type_event" (issue #130), so show the bare brand instead.
4446
+ kimi: withPlanLabel(kimi, null, "Kimi"),
4447
+ gemini: withPlanLabel(gemini, gemini.account_plan, "Gemini"),
4448
+ kiro: withPlanLabel(kiro, kiro.plan_name, "Kiro"),
4449
+ antigravity: withPlanLabel(antigravity, antigravity.account_plan, "Antigravity"),
4450
+ copilot: withPlanLabel(copilot, copilot.plan_name, "Copilot"),
4451
+ // grok-limits already maps subscriptionTier to xAI's own product names
4452
+ // ("SuperGrok Heavy", "X Premium+", "API Key"). The shared normalization
4453
+ // would Title-Case them into "Supergrok Heavy" / "Api Key" and drop "Free"
4454
+ // outright, so surface the label as-is like CommandCode below. Error and
4455
+ // unconfigured branches never carry plan_label, so the panel still falls
4456
+ // back to the bare brand name.
4457
+ grok,
4458
+ zcode: withPlanLabel(zcode, zcode.plan_label, "ZCode"),
4459
+ opencodeGo: withPlanLabel(opencodeGo, opencodeGo?.plan_label, "OpenCode Go"),
4460
+ // CommandCode tiers are acronym brands (GOAT/Pro/Max) — the fetcher already
4461
+ // maps plan ids to the CLI's exact display strings, so skip the shared
4462
+ // Title-Case normalization ("Goat") and surface them as-is.
4463
+ commandCode: commandCodeObj,
4464
+ // Devin's planName ("Pro", "Max") is already the official display name —
4465
+ // Title-Case normalization is still harmless and strips any brand prefix.
4466
+ devin: withPlanLabel(devinObj, devinObj?.plan_label, "Devin"),
4467
+ qoder: withPlanLabel(qoder, qoder?.plan_label, "Qoder"),
4468
+ qoderCn: withPlanLabel(qoderCn, qoderCn?.plan_label, "Qoder CN"),
4469
+ codingPlan: withPlanLabel(codingPlan, codingPlan?.plan_label, "Ark Coding Plan"),
4470
+ agentPlan: withPlanLabel(agentPlan, agentPlan?.plan_label, "Ark Agent Plan"),
4471
+ };
4472
+
4473
+ for (const [providerName, provider] of Object.entries(data)) {
4474
+ if (providerName === "fetched_at" || !provider || typeof provider !== "object") continue;
4475
+ const capturedAt = provider.cached_at || data.fetched_at;
4476
+ const ageMs = Math.max(0, nowMs - Date.parse(capturedAt || ""));
4477
+ const stale = provider.stale === true || (Number.isFinite(ageMs) && ageMs > 10 * 60 * 1000);
4478
+ const explicitSource = typeof provider.source === "string" ? provider.source : "";
4479
+ const source = explicitSource || (stale ? "disk-cache" : "provider-api");
4480
+ const confidence = /estimate|inferred/i.test(source)
4481
+ ? "inferred"
4482
+ : /local|database|sqlite|cache/i.test(source)
4483
+ ? "observed"
4484
+ : "official";
4485
+ provider.provenance = {
4486
+ source,
4487
+ confidence,
4488
+ captured_at: capturedAt,
4489
+ stale,
4490
+ age_seconds: Number.isFinite(ageMs) ? Math.round(ageMs / 1000) : null,
4491
+ };
4492
+ }
4493
+
4494
+ cacheBySelection[selectionKey || usageLimitsSelectionKey({ devinEnabled })] = {
4495
+ data,
4496
+ expiresAtMs: cacheExpiresAtMs(data, nowMs),
4497
+ };
4498
+ return data;
4499
+ }
4500
+
4501
+ function resetUsageLimitsCache() {
4502
+ for (const key of USAGE_LIMITS_SELECTION_KEYS) {
4503
+ cacheBySelection[key] = { data: null, expiresAtMs: 0 };
4504
+ }
4505
+ }
4506
+
4507
+ module.exports = {
4508
+ getUsageLimits,
4509
+ normalizePlanLabel,
4510
+ resetUsageLimitsCache,
4511
+ cacheExpiresAtMs,
4512
+ runCommand,
4513
+ extractGeminiOauthClientCredentials,
4514
+ loadKimiCredentials,
4515
+ fetchKimiLimits,
4516
+ normalizeCursorUsageSummary,
4517
+ normalizeCursorSandUsageStatus,
4518
+ cursorSandDuplicatesGrokPool,
4519
+ normalizeGeminiQuotaResponse,
4520
+ normalizeKimiUsageResponse,
4521
+ parseKiroUsageOutput,
4522
+ readKiroCreditsSummary,
4523
+ fetchKiroLimits,
4524
+ normalizeAntigravityResponse,
4525
+ normalizeAntigravityQuotaSummary,
4526
+ loadAntigravityCredentials,
4527
+ readAntigravityLinuxSecretRaw,
4528
+ writeAntigravityLinuxSecretRaw,
4529
+ refreshAntigravityAccessToken,
4530
+ ANTIGRAVITY_OAUTH_CLIENT_ID,
4531
+ ANTIGRAVITY_OAUTH_CLIENT_SECRET,
4532
+ parseListeningPorts,
4533
+ parseWindowsListeningPorts,
4534
+ parseLinuxProcListeningPorts,
4535
+ parseSsListeningPorts,
4536
+ listAntigravityPorts,
4537
+ detectAntigravityProcess,
4538
+ fetchAntigravityLimits,
4539
+ fetchCopilotLimits,
4540
+ readCopilotOauthToken,
4541
+ readCopilotOauthTokenAsync,
4542
+ readCopilotAuthDbToken,
4543
+ readCopilotAuthDbTokenAsync,
4544
+ decryptCopilotAuthDbToken,
4545
+ describeCopilotOtelStatus,
4546
+ fetchGrokLimits,
4547
+ fetchZcodeLimits,
4548
+ fetchOpencodeGoLimits,
4549
+ fetchCommandcodeLimits,
4550
+ fetchQoderLimits,
4551
+ fetchQoderCnLimits,
4552
+ };