chompyy 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/README.md +11 -0
  2. package/dist/agentlimits.js +77 -0
  3. package/dist/agentusage.js +96 -0
  4. package/dist/appstate.js +63 -3
  5. package/dist/away.js +44 -5
  6. package/dist/blueprint.js +3 -7
  7. package/dist/board.js +1 -0
  8. package/dist/cli.js +263 -5
  9. package/dist/codexquota.js +106 -0
  10. package/dist/codexusage.js +10 -0
  11. package/dist/config.js +2 -0
  12. package/dist/context.js +30 -0
  13. package/dist/costs.js +1 -0
  14. package/dist/demon.js +20 -0
  15. package/dist/label.js +33 -0
  16. package/dist/menu.js +17 -0
  17. package/dist/nightcap.js +60 -0
  18. package/dist/nudge.js +47 -18
  19. package/dist/pacing.js +16 -1
  20. package/dist/questions.js +71 -0
  21. package/dist/recap.js +74 -0
  22. package/dist/receipt.js +48 -0
  23. package/dist/recipe.js +79 -0
  24. package/dist/stamps.js +14 -0
  25. package/dist/triggers.js +5 -0
  26. package/dist/usage.js +21 -1
  27. package/dist/vendor/codeburn/antigravity.js +309 -0
  28. package/dist/vendor/codeburn/codex.js +429 -0
  29. package/dist/vendor/codeburn/copilot.js +292 -0
  30. package/dist/vendor/codeburn/gemini.js +195 -0
  31. package/dist/vendor/codeburn/grokbot.js +182 -0
  32. package/dist/vendor/codeburn/kimi.js +178 -0
  33. package/dist/vendor/codeburn/shims/chalk.js +14 -0
  34. package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
  35. package/dist/vendor/codeburn/src/act/backup.js +83 -0
  36. package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
  37. package/dist/vendor/codeburn/src/act/types.js +37 -0
  38. package/dist/vendor/codeburn/src/bash-utils.js +204 -0
  39. package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
  40. package/dist/vendor/codeburn/src/cache-dir.js +26 -0
  41. package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
  42. package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
  43. package/dist/vendor/codeburn/src/classifier.js +209 -0
  44. package/dist/vendor/codeburn/src/claude-identity.js +223 -0
  45. package/dist/vendor/codeburn/src/codex-cache.js +377 -0
  46. package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
  47. package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
  48. package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
  49. package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
  50. package/dist/vendor/codeburn/src/compare-stats.js +405 -0
  51. package/dist/vendor/codeburn/src/config.js +145 -0
  52. package/dist/vendor/codeburn/src/content-utils.js +56 -0
  53. package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
  54. package/dist/vendor/codeburn/src/context-tree.js +664 -0
  55. package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
  56. package/dist/vendor/codeburn/src/currency.js +189 -0
  57. package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
  58. package/dist/vendor/codeburn/src/cursor-import.js +402 -0
  59. package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
  60. package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
  61. package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
  62. package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
  63. package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
  64. package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
  65. package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
  66. package/dist/vendor/codeburn/src/format.js +118 -0
  67. package/dist/vendor/codeburn/src/fs-utils.js +270 -0
  68. package/dist/vendor/codeburn/src/git-origin.js +334 -0
  69. package/dist/vendor/codeburn/src/granular-history.js +328 -0
  70. package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
  71. package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
  72. package/dist/vendor/codeburn/src/live-sessions.js +358 -0
  73. package/dist/vendor/codeburn/src/math-utils.js +8 -0
  74. package/dist/vendor/codeburn/src/menubar-json.js +294 -0
  75. package/dist/vendor/codeburn/src/models.js +1879 -0
  76. package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
  77. package/dist/vendor/codeburn/src/optimize.js +4110 -0
  78. package/dist/vendor/codeburn/src/parse-workers.js +219 -0
  79. package/dist/vendor/codeburn/src/parser.js +6953 -0
  80. package/dist/vendor/codeburn/src/path-privacy.js +26 -0
  81. package/dist/vendor/codeburn/src/plans.js +135 -0
  82. package/dist/vendor/codeburn/src/pr-signals.js +132 -0
  83. package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
  84. package/dist/vendor/codeburn/src/provider-issues.js +30 -0
  85. package/dist/vendor/codeburn/src/providers/amp.js +286 -0
  86. package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
  87. package/dist/vendor/codeburn/src/providers/claude.js +551 -0
  88. package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
  89. package/dist/vendor/codeburn/src/providers/cline.js +63 -0
  90. package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
  91. package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
  92. package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
  93. package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
  94. package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
  95. package/dist/vendor/codeburn/src/providers/crush.js +226 -0
  96. package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
  97. package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
  98. package/dist/vendor/codeburn/src/providers/devin.js +569 -0
  99. package/dist/vendor/codeburn/src/providers/droid.js +324 -0
  100. package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
  101. package/dist/vendor/codeburn/src/providers/forge.js +245 -0
  102. package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
  103. package/dist/vendor/codeburn/src/providers/goose.js +252 -0
  104. package/dist/vendor/codeburn/src/providers/grok.js +581 -0
  105. package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
  106. package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
  107. package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
  108. package/dist/vendor/codeburn/src/providers/index.js +360 -0
  109. package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
  110. package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
  111. package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
  112. package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
  113. package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
  114. package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
  115. package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
  116. package/dist/vendor/codeburn/src/providers/mux.js +242 -0
  117. package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
  118. package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
  119. package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
  120. package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
  121. package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
  122. package/dist/vendor/codeburn/src/providers/pi.js +429 -0
  123. package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
  124. package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
  125. package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
  126. package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
  127. package/dist/vendor/codeburn/src/providers/types.js +5 -0
  128. package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
  129. package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
  130. package/dist/vendor/codeburn/src/providers/warp.js +575 -0
  131. package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
  132. package/dist/vendor/codeburn/src/providers/zed.js +187 -0
  133. package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
  134. package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
  135. package/dist/vendor/codeburn/src/quota/claude.js +244 -0
  136. package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
  137. package/dist/vendor/codeburn/src/quota/security.js +299 -0
  138. package/dist/vendor/codeburn/src/quota/types.js +1 -0
  139. package/dist/vendor/codeburn/src/scan-facts.js +99 -0
  140. package/dist/vendor/codeburn/src/session-cache.js +3040 -0
  141. package/dist/vendor/codeburn/src/session-count-label.js +14 -0
  142. package/dist/vendor/codeburn/src/session-output.js +139 -0
  143. package/dist/vendor/codeburn/src/session-population.js +30 -0
  144. package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
  145. package/dist/vendor/codeburn/src/sqlite.js +528 -0
  146. package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
  147. package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
  148. package/dist/vendor/codeburn/src/token-estimate.js +5 -0
  149. package/dist/vendor/codeburn/src/types.js +16 -0
  150. package/dist/vendor/codeburn/src/work-units.js +126 -0
  151. package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
  152. package/dist/vendor/codeburn/src/wsl.js +198 -0
  153. package/dist/vendor/codeburn/src/yield.js +666 -0
  154. package/package.json +1 -1
@@ -0,0 +1,310 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ // Live Antigravity quota from LOCAL surfaces only - the Antigravity app's own
3
+ // language server or a signed-in `agy` CLI's embedded server. The local
4
+ // Antigravity language-server protocol is undocumented and
5
+ // experimental). No Google OAuth fallback in v1: when no local server answers,
6
+ // the provider reports disconnected and the UI shows its Connect affordance.
7
+ //
8
+ // Endpoints (localhost only, Connect-RPC JSON):
9
+ // - POST https://127.0.0.1:<port>/exa.language_server_pb.LanguageServerService/RetrieveUserQuotaSummary
10
+ // (preferred windows; the tier and fallback windows come from)
11
+ // - POST https://127.0.0.1:<port>/exa.language_server_pb.LanguageServerService/GetUserStatus
12
+ //
13
+ // Discovery lists processes to find candidates (app language servers need a
14
+ // CSRF token, from `--csrf_token` or a daemon file; the `agy` CLI needs none), then lists each
15
+ // pid's listening TCP ports: `ps` and `lsof` on POSIX, Win32_Process and
16
+ // `netstat` on Windows, which has neither. Local HTTPS uses a self-signed cert,
17
+ // so TLS verification is relaxed ONLY for the 127.0.0.1 loopback probes.
18
+ import { execFile } from 'node:child_process';
19
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
20
+ import http from 'node:http';
21
+ import https from 'node:https';
22
+ import { homedir } from 'node:os';
23
+ import { join } from 'node:path';
24
+ import { promisify } from 'node:util';
25
+ import { fraction, sanitizeError } from './security.js';
26
+ const SUMMARY_PATH = '/exa.language_server_pb.LanguageServerService/RetrieveUserQuotaSummary';
27
+ const STATUS_PATH = '/exa.language_server_pb.LanguageServerService/GetUserStatus';
28
+ const LOCAL_TIMEOUT_MS = 3_000;
29
+ const execFileAsync = promisify(execFile);
30
+ function postLocal(port, tls, pathName, body, csrf) {
31
+ return new Promise(resolve => {
32
+ const request = (tls ? https : http).request({
33
+ host: '127.0.0.1',
34
+ port,
35
+ method: 'POST',
36
+ path: pathName,
37
+ ...(tls ? { rejectUnauthorized: false } : {}),
38
+ headers: {
39
+ 'Content-Type': 'application/json',
40
+ 'Connect-Protocol-Version': '1',
41
+ ...(csrf ? { 'X-Codeium-Csrf-Token': csrf } : {}),
42
+ },
43
+ timeout: LOCAL_TIMEOUT_MS,
44
+ }, response => {
45
+ let text = '';
46
+ response.setEncoding('utf8');
47
+ response.on('data', chunk => { text += chunk; });
48
+ response.on('end', () => resolve({ status: response.statusCode ?? 0, text }));
49
+ });
50
+ request.on('timeout', () => { request.destroy(); resolve(null); });
51
+ request.on('error', () => resolve(null));
52
+ request.end(body);
53
+ });
54
+ }
55
+ const defaults = {
56
+ execFile: execFileAsync,
57
+ request: postLocal,
58
+ platform: process.platform,
59
+ };
60
+ function empty(connection) {
61
+ return { provider: 'antigravity', connection, primary: null, details: [], planLabel: null, footerLines: [] };
62
+ }
63
+ // Process kinds distinguish the app language server from standalone processes.
64
+ // carries richer quota data than the IDE variant, so IDE matches are skipped;
65
+ // a CLI (`agy`) match is accepted because its tokenless server exposes the
66
+ // same summary payload.
67
+ const LANGUAGE_SERVER = /language[_-]server(_macos)?(_arm)?/;
68
+ const IDE_MARKER = /antigravity[-_]ide/i;
69
+ const CLI_MARKER = /antigravity[-_]cli/i;
70
+ const AGY_BINARY = /(^|\/|\s)agy(\s|$)/;
71
+ const APP_MARKER = /--app_data_dir[= ]"?antigravity(?![\w-])|\/antigravity\//i;
72
+ function flagValue(line, flag) {
73
+ const match = line.match(new RegExp(`${flag}[= ]([^\\s]+)`));
74
+ return match?.[1];
75
+ }
76
+ /// Newer app servers keep the token off the command line and write it, with their pid, to
77
+ /// `hub_<port>.json` here. Files from exited servers stay behind, so only the newest one
78
+ /// naming this pid counts.
79
+ export function daemonHub(pid, dir = join(homedir(), '.gemini', 'antigravity', 'daemon')) {
80
+ let names;
81
+ try {
82
+ names = readdirSync(dir);
83
+ }
84
+ catch {
85
+ return undefined;
86
+ }
87
+ let found;
88
+ let newest = -Infinity;
89
+ for (const name of names) {
90
+ if (!/^hub_\d+\.json$/.test(name))
91
+ continue;
92
+ try {
93
+ const file = join(dir, name);
94
+ const hub = JSON.parse(readFileSync(file, 'utf8'));
95
+ const modified = statSync(file).mtimeMs;
96
+ if (hub?.pid !== Number(pid) || typeof hub.csrfToken !== 'string' || !/^[\w-]+$/.test(hub.csrfToken) || modified <= newest)
97
+ continue;
98
+ found = { csrfToken: hub.csrfToken, httpsPort: Number(hub.httpsPort) };
99
+ newest = modified;
100
+ }
101
+ catch { /* unreadable or malformed */ }
102
+ }
103
+ return found;
104
+ }
105
+ export function classifyProcessLine(line, daemonDir) {
106
+ const isServer = LANGUAGE_SERVER.test(line);
107
+ const isCli = !isServer && (CLI_MARKER.test(line) || AGY_BINARY.test(line));
108
+ if (!isServer && !isCli)
109
+ return null;
110
+ const pid = line.trim().match(/^(\d+)/)?.[1];
111
+ if (!pid)
112
+ return null;
113
+ // A desktop language server with no token anywhere is skipped so a later,
114
+ // valid server can be found; the CLI exposes no CSRF flag and needs none. IDE
115
+ // language servers are excluded too - their payloads lack the weekly groups.
116
+ if (!isCli && (!APP_MARKER.test(line) || IDE_MARKER.test(line)))
117
+ return null;
118
+ const csrf = flagValue(line, '--csrf_token') ?? (isCli ? undefined : daemonHub(pid, daemonDir)?.csrfToken);
119
+ if (!isCli && !csrf)
120
+ return null;
121
+ const extPort = Number(flagValue(line, '--extension_server_port'));
122
+ return { pid, cli: isCli, csrf, extPort: Number.isFinite(extPort) && extPort > 0 ? extPort : undefined };
123
+ }
124
+ /// Windows has no `ps`, and asking for one is a spawn failure rather than an empty answer:
125
+ /// every quota poll there printed `ps: unknown option -- x` and reported a transient failure.
126
+ /// Win32_Process is the same listing by another name, and it is already how
127
+ /// src/providers/antigravity.ts finds these servers. The Where-Object is only a prefilter to
128
+ /// keep the output small; `classifyProcessLine` still decides what counts.
129
+ const WINDOWS_PROCESS_SCRIPT = [
130
+ "$ErrorActionPreference = 'SilentlyContinue'",
131
+ '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8',
132
+ 'Get-CimInstance Win32_Process'
133
+ + " | Where-Object { $_.CommandLine -and ($_.CommandLine -like '*antigravity*'"
134
+ + " -or $_.CommandLine -like '*language_server*' -or $_.CommandLine -like '*agy*') }"
135
+ + ' | ForEach-Object { "$($_.ProcessId) $($_.CommandLine)" }',
136
+ ].join('; ');
137
+ /// Windows searches the current directory before PATH, so a system tool by bare name lets
138
+ /// anything dropped beside the caller answer for it.
139
+ function system32(exe, env = process.env) {
140
+ const root = env.SystemRoot;
141
+ const base = root && /^[a-zA-Z]:[\\/]/.test(root) ? root.replace(/[\\/]+$/, '') : 'C:\\Windows';
142
+ return `${base}\\System32\\${exe}`;
143
+ }
144
+ /// One line per process, `<pid> <command line>`, on every platform.
145
+ async function listProcesses(deps) {
146
+ if (deps.platform === 'win32') {
147
+ const { stdout } = await deps.execFile(system32('WindowsPowerShell\\v1.0\\powershell.exe'), [
148
+ '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', WINDOWS_PROCESS_SCRIPT,
149
+ ]);
150
+ return stdout;
151
+ }
152
+ const { stdout } = await deps.execFile('ps', ['-ax', '-o', 'pid=,command=']);
153
+ return stdout;
154
+ }
155
+ /// `netstat -ano` rows are `Proto Local Foreign State PID`. The state word is localized,
156
+ /// so it is not matched on: a row for this pid that is not listening only gives a port the
157
+ /// probe then fails to reach, which costs one refused connection and no wrong answer.
158
+ export function parseNetstatPorts(stdout, pid) {
159
+ const ports = new Set();
160
+ for (const line of stdout.split(/\r?\n/)) {
161
+ const parts = line.trim().split(/\s+/);
162
+ if (parts.length < 5 || !/^TCP$/i.test(parts[0]) || parts[parts.length - 1] !== pid)
163
+ continue;
164
+ const port = Number(parts[1].split(':').pop());
165
+ if (Number.isFinite(port) && port > 0)
166
+ ports.add(port);
167
+ }
168
+ return [...ports];
169
+ }
170
+ async function discoverCandidates(deps) {
171
+ const stdout = await listProcesses(deps);
172
+ const seen = new Set();
173
+ const candidates = [];
174
+ for (const line of stdout.split('\n')) {
175
+ const candidate = classifyProcessLine(line);
176
+ if (!candidate || seen.has(candidate.pid))
177
+ continue;
178
+ seen.add(candidate.pid);
179
+ candidates.push(candidate);
180
+ }
181
+ // The app source ranks above the CLI: richer quota data beats availability.
182
+ return candidates.sort((a, b) => Number(a.cli) - Number(b.cli));
183
+ }
184
+ async function listeningPorts(deps, pid) {
185
+ try {
186
+ // No lsof on Windows either; netstat is the listing that ships with it.
187
+ if (deps.platform === 'win32') {
188
+ const { stdout } = await deps.execFile(system32('netstat.exe'), ['-ano', '-p', 'TCP']);
189
+ return parseNetstatPorts(stdout, pid);
190
+ }
191
+ const { stdout } = await deps.execFile('lsof', ['-nP', '-iTCP', '-sTCP:LISTEN', '-a', '-p', pid]);
192
+ const ports = [...stdout.matchAll(/:(\d+)\s/g)].map(match => Number(match[1]));
193
+ return [...new Set(ports)].filter(port => Number.isFinite(port) && port > 0);
194
+ }
195
+ catch {
196
+ return [];
197
+ }
198
+ }
199
+ function resetTimeOf(value) {
200
+ if (typeof value === 'number' && Number.isFinite(value)) {
201
+ const date = new Date(value > 1e12 ? value : value * 1000);
202
+ return Number.isNaN(date.getTime()) ? null : date.toISOString();
203
+ }
204
+ if (typeof value === 'string' && !Number.isNaN(Date.parse(value)))
205
+ return new Date(value).toISOString();
206
+ return null;
207
+ }
208
+ function windowOf(label, remainingFraction, resetTime) {
209
+ const remaining = fraction(typeof remainingFraction === 'number' ? (1 - remainingFraction) * 100 : NaN);
210
+ if (remaining === null)
211
+ return null;
212
+ return { label, percent: remaining, resetsAt: resetTimeOf(resetTime ?? null) };
213
+ }
214
+ /** Preferred payload: two named quota groups of model buckets. */
215
+ export function decodeAntigravitySummary(body) {
216
+ const data = body && typeof body === 'object' ? body : {};
217
+ // 2.16+ wraps the groups in `response`; older local servers return them directly.
218
+ const groups = Array.isArray(data.response?.groups) ? data.response.groups : data.groups;
219
+ const windows = [];
220
+ for (const group of Array.isArray(groups) ? groups : []) {
221
+ const groupName = typeof group?.displayName === 'string' ? group.displayName : '';
222
+ for (const bucket of Array.isArray(group?.buckets) ? group.buckets : []) {
223
+ const name = [groupName, typeof bucket?.displayName === 'string' ? bucket.displayName : bucket?.bucketId]
224
+ .filter(Boolean).join(' · ');
225
+ if (!name)
226
+ continue;
227
+ const window = windowOf(name, bucket?.remainingFraction ?? bucket?.remaining?.remainingFraction, bucket?.resetTime ?? bucket?.remaining?.resetTime);
228
+ if (window)
229
+ windows.push(window);
230
+ }
231
+ }
232
+ return windows;
233
+ }
234
+ /** Legacy payload: flat per-model quota rows under GetUserStatus. */
235
+ export function decodeAntigravityStatus(body) {
236
+ const data = body && typeof body === 'object' ? body : {};
237
+ const configs = data.userStatus?.cascadeModelConfigData?.clientModelConfigs;
238
+ const windows = [];
239
+ for (const config of Array.isArray(configs) ? configs : []) {
240
+ // Current servers expose the display name as `label`, not `modelName`.
241
+ const name = typeof config?.label === 'string' && config.label.trim() ? config.label
242
+ : typeof config?.modelName === 'string' ? config.modelName : '';
243
+ if (!name)
244
+ continue;
245
+ const window = windowOf(name, config?.quotaInfo?.remainingFraction, config?.quotaInfo?.resetTime);
246
+ if (window)
247
+ windows.push(window);
248
+ }
249
+ return windows;
250
+ }
251
+ function planFromStatus(body) {
252
+ const data = body && typeof body === 'object' ? body : {};
253
+ // userTier is the Google subscription; planStatus.planInfo.planName says "Pro" even on the free tier.
254
+ const plan = [data.userStatus?.userTier?.name, data.planName, data.userStatus?.planName, data.account_plan]
255
+ .find(value => typeof value === 'string' && value.trim());
256
+ return plan ? plan.trim() : null;
257
+ }
258
+ async function probePort(deps, port, csrf) {
259
+ const body = JSON.stringify({});
260
+ for (const tls of [true, false]) {
261
+ const summary = await deps.request(port, tls, SUMMARY_PATH, body, csrf);
262
+ const summaryWindows = summary?.status === 200 ? decodeAntigravitySummary(parseJson(summary.text)) : [];
263
+ // The summary payload carries no tier, so GetUserStatus is asked either way.
264
+ const status = await deps.request(port, tls, STATUS_PATH, body, csrf);
265
+ const parsed = status?.status === 200 ? parseJson(status.text) : null;
266
+ const windows = summaryWindows.length > 0 ? summaryWindows : decodeAntigravityStatus(parsed);
267
+ if (windows.length > 0)
268
+ return { windows, planLabel: planFromStatus(parsed) };
269
+ }
270
+ return null;
271
+ }
272
+ function parseJson(text) {
273
+ try {
274
+ return JSON.parse(text);
275
+ }
276
+ catch {
277
+ return null;
278
+ }
279
+ }
280
+ export async function fetchAntigravityQuota(deps = {}) {
281
+ const resolved = { ...defaults, ...deps };
282
+ try {
283
+ const candidates = await discoverCandidates(resolved);
284
+ if (candidates.length === 0)
285
+ return empty('disconnected');
286
+ for (const candidate of candidates) {
287
+ const ports = await listeningPorts(resolved, candidate.pid);
288
+ if (candidate.extPort !== undefined && !ports.includes(candidate.extPort))
289
+ ports.push(candidate.extPort);
290
+ for (const port of ports) {
291
+ const found = await probePort(resolved, port, candidate.csrf);
292
+ if (found) {
293
+ const windows = [...found.windows].sort((a, b) => b.percent - a.percent);
294
+ return {
295
+ provider: 'antigravity', connection: 'connected',
296
+ primary: windows[0] ?? null,
297
+ details: windows,
298
+ planLabel: found.planLabel,
299
+ footerLines: [],
300
+ };
301
+ }
302
+ }
303
+ }
304
+ return empty('disconnected');
305
+ }
306
+ catch (error) {
307
+ console.warn(`Antigravity quota unavailable: ${sanitizeError(error)}`);
308
+ return empty('transientFailure');
309
+ }
310
+ }
@@ -0,0 +1,244 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { createHash } from 'node:crypto';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { wslHomes } from '../wsl.js';
6
+ import { fraction, quotaRequestSignal, readKeychainPassword, readSecureFile, sanitizeError } from './security.js';
7
+ const ENDPOINT = 'https://api.anthropic.com/api/oauth/usage';
8
+ const KEYCHAIN_SERVICE = 'Claude Code-credentials';
9
+ const EXPIRED_FOOTER = ['Claude Code login expired. Run Claude Code once, then refresh.'];
10
+ const REFUSED_FOOTER = {
11
+ denied: ['Keychain access to the Claude Code login was denied.'],
12
+ unanswered: ['The Keychain prompt for the Claude Code login was not answered.'],
13
+ };
14
+ const defaults = {
15
+ fetch: globalThis.fetch,
16
+ wslCredentialPaths: () => wslHomes().map(home => `${home}\\.claude\\.credentials.json`),
17
+ readFile: readSecureFile,
18
+ now: Date.now,
19
+ };
20
+ /** Claude Code keeps the login of any config dir but ~/.claude under its own Keychain
21
+ * item, suffixed with the first 8 hex chars of the SHA-256 of the dir's NFC path. */
22
+ export function claudeKeychainService(configDir) {
23
+ if (path.resolve(configDir) === path.resolve(os.homedir(), '.claude'))
24
+ return KEYCHAIN_SERVICE;
25
+ return `${KEYCHAIN_SERVICE}-${createHash('sha256').update(configDir.normalize('NFC')).digest('hex').slice(0, 8)}`;
26
+ }
27
+ function empty(connection, footerLines = []) {
28
+ return { provider: 'claude', connection, primary: null, details: [], planLabel: null, footerLines };
29
+ }
30
+ function expiredLogin() {
31
+ return { ...empty('terminalFailure', EXPIRED_FOOTER), loginExpired: true };
32
+ }
33
+ function isExpired(credential, deps) {
34
+ return credential.expiresAt !== undefined && credential.expiresAt <= deps.now();
35
+ }
36
+ function parseCredential(raw) {
37
+ const clean = raw.replace(/\r/g, '').replace(/\n[ \t]*/g, '');
38
+ const oauth = JSON.parse(clean).claudeAiOauth;
39
+ if (!oauth || typeof oauth.accessToken !== 'string' || oauth.accessToken.length === 0)
40
+ return null;
41
+ return {
42
+ accessToken: oauth.accessToken,
43
+ expiresAt: typeof oauth.expiresAt === 'number' ? oauth.expiresAt : undefined,
44
+ rateLimitTier: typeof oauth.rateLimitTier === 'string' ? oauth.rateLimitTier : undefined,
45
+ subscriptionType: typeof oauth.subscriptionType === 'string' ? oauth.subscriptionType : undefined,
46
+ };
47
+ }
48
+ async function credentialAt(file, deps) {
49
+ const raw = await deps.readFile(file, 64 * 1024);
50
+ return raw ? parseCredential(raw) : null;
51
+ }
52
+ // A 9P share whose distro is going down can stall a read; the quota poll must
53
+ // never wait on it. The abandoned read settles (or not) on its own.
54
+ const WSL_READ_TIMEOUT_MS = 2000;
55
+ function wslCredentialAt(file, deps) {
56
+ let timer;
57
+ const timeout = new Promise(resolve => { timer = setTimeout(resolve, WSL_READ_TIMEOUT_MS, null); });
58
+ return Promise.race([credentialAt(file, deps).catch(() => null), timeout]).finally(() => clearTimeout(timer));
59
+ }
60
+ /**
61
+ * The Windows-home credential plus one per running WSL distro home. A user can
62
+ * be logged in on both sides; the one expiring last is the one Claude Code
63
+ * renewed most recently. A broken WSL file is skipped; a broken Windows file
64
+ * still surfaces its error when nothing else is usable.
65
+ */
66
+ async function credentialFromFiles(deps) {
67
+ let nativeError;
68
+ const native = credentialAt(deps.credentialPath, deps).catch(error => { nativeError = error; return null; });
69
+ const paths = [deps.credentialPath, ...deps.wslCredentialPaths()];
70
+ const found = await Promise.all([native, ...paths.slice(1).map(file => wslCredentialAt(file, deps))]);
71
+ let best = null;
72
+ for (const [i, credential] of found.entries()) {
73
+ if (credential && (!best || (credential.expiresAt ?? -Infinity) > (best.credential.expiresAt ?? -Infinity))) {
74
+ best = { credential, path: paths[i] };
75
+ }
76
+ }
77
+ if (!best && nativeError !== undefined)
78
+ throw nativeError;
79
+ return best;
80
+ }
81
+ /**
82
+ * Re-read whichever store the credential came from. On macOS the credential
83
+ * usually lives in the Keychain and no file exists at all, so re-reading the
84
+ * file after a 401 could never see the token Claude Code has since renewed.
85
+ * A denied Keychain on a re-read needs no state of its own: the first read
86
+ * already decided whether that store is reachable.
87
+ */
88
+ async function credentialFrom(source, file, deps) {
89
+ if (source === 'file')
90
+ return file === deps.credentialPath ? credentialAt(file, deps) : wslCredentialAt(file, deps);
91
+ const outcome = await deps.keychain();
92
+ return outcome.status === 'found' ? parseCredential(outcome.value) : null;
93
+ }
94
+ export async function readClaudeKeychain(service) {
95
+ // Claude Code has written the item under both `$USER` (2.1.x) and the older
96
+ // hardcoded "agentseal" account; a user-scoped miss must fall through to the
97
+ // service-only lookup rather than reporting disconnected.
98
+ const user = process.env.USER;
99
+ return readKeychainPassword(service, user ? [user, null] : [null]);
100
+ }
101
+ function windowOf(label, value) {
102
+ if (!value || typeof value !== 'object')
103
+ return null;
104
+ const row = value;
105
+ const percent = fraction(row.utilization);
106
+ if (percent === null)
107
+ return null;
108
+ const resetsAt = typeof row.resets_at === 'string' && !Number.isNaN(Date.parse(row.resets_at))
109
+ ? new Date(row.resets_at).toISOString() : null;
110
+ return { label, percent, resetsAt };
111
+ }
112
+ export function planLabel(credential) {
113
+ const subscriptionType = credential.subscriptionType?.toLowerCase() ?? '';
114
+ const tier = credential.rateLimitTier?.toLowerCase() ?? '';
115
+ const multiplier = tier.match(/max[_-]?(\d+)x/)?.[1];
116
+ const hasMax = tier.includes('max');
117
+ if (subscriptionType === 'team' || (subscriptionType === '' && tier.includes('team'))) {
118
+ return hasMax ? 'Team Premium' : 'Team';
119
+ }
120
+ if (subscriptionType === 'enterprise' || (subscriptionType === '' && tier.includes('enterprise'))) {
121
+ return hasMax ? 'Enterprise Premium' : 'Enterprise';
122
+ }
123
+ if (tier.includes('ultra'))
124
+ return 'Ultra';
125
+ if (multiplier === '20')
126
+ return 'Ultra';
127
+ if (multiplier)
128
+ return `Max ${multiplier}x`;
129
+ if (subscriptionType === 'max' || hasMax)
130
+ return 'Max';
131
+ if (subscriptionType === 'pro' || tier.includes('pro')) {
132
+ return 'Pro';
133
+ }
134
+ const readable = tier.replace(/^default_claude_/, '').replace(/_/g, ' ');
135
+ return readable ? readable[0].toUpperCase() + readable.slice(1) : 'Subscription';
136
+ }
137
+ export async function readClaudePlan(configDir) {
138
+ try {
139
+ const raw = await readSecureFile(path.join(configDir, '.credentials.json'));
140
+ const credential = raw ? parseCredential(raw) : null;
141
+ return credential ? planLabel(credential) : undefined;
142
+ }
143
+ catch {
144
+ return undefined;
145
+ }
146
+ }
147
+ export function decodeClaudeUsage(body, credential) {
148
+ const data = body && typeof body === 'object' ? body : {};
149
+ const five = windowOf('5-hour', data.five_hour);
150
+ const weekly = windowOf('Weekly', data.seven_day);
151
+ const opus = windowOf('Weekly · Opus', data.seven_day_opus);
152
+ const sonnet = windowOf('Weekly · Sonnet', data.seven_day_sonnet);
153
+ const scoped = [];
154
+ if (Array.isArray(data.limits)) {
155
+ for (const item of data.limits) {
156
+ if (!item || typeof item !== 'object')
157
+ continue;
158
+ const row = item;
159
+ const display = row.scope?.model?.display_name;
160
+ const percent = fraction(row.percent);
161
+ if (row.kind !== 'weekly_scoped' || typeof display !== 'string' || percent === null)
162
+ continue;
163
+ const resetsAt = typeof row.resets_at === 'string' && !Number.isNaN(Date.parse(row.resets_at))
164
+ ? new Date(row.resets_at).toISOString() : null;
165
+ scoped.push({ label: `Weekly · ${display}`, percent, resetsAt });
166
+ }
167
+ }
168
+ return {
169
+ provider: 'claude', connection: 'connected', primary: weekly,
170
+ details: [five, weekly, opus, sonnet].filter((row) => row !== null).concat(scoped),
171
+ planLabel: planLabel(credential), footerLines: [],
172
+ };
173
+ }
174
+ async function request(token, deps, parent) {
175
+ return deps.fetch(ENDPOINT, {
176
+ method: 'GET', signal: quotaRequestSignal(parent),
177
+ headers: {
178
+ Authorization: `Bearer ${token}`,
179
+ Accept: 'application/json',
180
+ 'anthropic-beta': 'oauth-2025-04-20',
181
+ 'User-Agent': 'claude-code/2.1.0',
182
+ },
183
+ });
184
+ }
185
+ export async function fetchClaudeQuota(options = {}) {
186
+ const configDir = options.configDir ?? path.join(os.homedir(), '.claude');
187
+ const deps = { ...defaults, credentialPath: path.join(configDir, '.credentials.json'), keychain: () => readClaudeKeychain(claudeKeychainService(configDir)), ...options };
188
+ try {
189
+ const fromFile = await credentialFromFiles(deps);
190
+ let credential = fromFile?.credential ?? null;
191
+ let source = 'file';
192
+ // A file left from before Claude Code moved the login into the Keychain keeps an
193
+ // expired token: the Keychain's login wins, and without one the file still answers.
194
+ const fileExpired = credential?.expiresAt !== undefined && credential.expiresAt <= deps.now();
195
+ if ((!credential || fileExpired) && options.allowKeychain && process.platform === 'darwin') {
196
+ const outcome = await deps.keychain();
197
+ if (outcome.status === 'accessDenied')
198
+ return { quota: empty('accessDenied', outcome.reason ? REFUSED_FOOTER[outcome.reason] : []) };
199
+ const fromKeychain = outcome.status === 'found' ? parseCredential(outcome.value) : null;
200
+ if (fromKeychain) {
201
+ credential = fromKeychain;
202
+ source = 'keychain';
203
+ }
204
+ }
205
+ if (!credential)
206
+ return { quota: empty('disconnected') };
207
+ let response = await request(credential.accessToken, deps, options.signal);
208
+ if (response.status === 401) {
209
+ const reread = await credentialFrom(source, fromFile?.path ?? deps.credentialPath, deps);
210
+ if (!reread || reread.accessToken === credential.accessToken) {
211
+ // Nothing but a fresh login can clear a 401 on a credential whose life is
212
+ // already over, so it is reported as terminal rather than as the blip its
213
+ // consumers are meant to retry and to keep their last numbers through. A
214
+ // token that has not expired is a real blip and keeps that backoff.
215
+ return { quota: isExpired(credential, deps) ? expiredLogin() : empty('transientFailure') };
216
+ }
217
+ credential = reread;
218
+ response = await request(credential.accessToken, deps, options.signal);
219
+ }
220
+ // A 429 or other refusal of an expired token says nothing about the account;
221
+ // the fix is a fresh login, not waiting.
222
+ if (!response.ok && isExpired(credential, deps))
223
+ return { quota: expiredLogin() };
224
+ if (response.status === 429) {
225
+ let hint;
226
+ try {
227
+ hint = (await response.json()).retry_after;
228
+ }
229
+ catch {
230
+ hint = undefined;
231
+ }
232
+ const parsed = typeof hint === 'number' ? hint : typeof hint === 'string' ? Number(hint) : NaN;
233
+ return { quota: empty('transientFailure'), retryAfterSeconds: Math.max(Number.isFinite(parsed) ? parsed : 300, 60) };
234
+ }
235
+ if (!response.ok)
236
+ return { quota: empty(response.status >= 400 && response.status < 500 ? 'terminalFailure' : 'transientFailure') };
237
+ return { quota: decodeClaudeUsage(await response.json(), credential) };
238
+ }
239
+ catch (error) {
240
+ // Deliberately sanitize before the only diagnostic sink. Tokens are never returned.
241
+ console.warn(`Claude quota unavailable: ${sanitizeError(error)}`);
242
+ return { quota: empty('transientFailure') };
243
+ }
244
+ }