@songsid/agend 2.1.2-beta.2 → 2.1.2-beta.21

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 (147) hide show
  1. package/dist/access-path.js +15 -6
  2. package/dist/access-path.js.map +1 -1
  3. package/dist/agent-endpoint.d.ts +2 -0
  4. package/dist/agent-endpoint.js +17 -1
  5. package/dist/agent-endpoint.js.map +1 -1
  6. package/dist/backend/antigravity.d.ts +18 -0
  7. package/dist/backend/antigravity.js +32 -3
  8. package/dist/backend/antigravity.js.map +1 -1
  9. package/dist/backend/claude-code.d.ts +37 -0
  10. package/dist/backend/claude-code.js +43 -1
  11. package/dist/backend/claude-code.js.map +1 -1
  12. package/dist/backend/codex.d.ts +1 -0
  13. package/dist/backend/codex.js +25 -0
  14. package/dist/backend/codex.js.map +1 -1
  15. package/dist/backend/grok.d.ts +23 -0
  16. package/dist/backend/grok.js +45 -0
  17. package/dist/backend/grok.js.map +1 -1
  18. package/dist/backend/kiro.d.ts +20 -0
  19. package/dist/backend/kiro.js +77 -2
  20. package/dist/backend/kiro.js.map +1 -1
  21. package/dist/backend/types.d.ts +34 -0
  22. package/dist/backend/types.js +1 -1
  23. package/dist/backend/types.js.map +1 -1
  24. package/dist/channel/adapters/discord.d.ts +15 -0
  25. package/dist/channel/adapters/discord.js +91 -2
  26. package/dist/channel/adapters/discord.js.map +1 -1
  27. package/dist/channel/adapters/telegram.d.ts +21 -0
  28. package/dist/channel/adapters/telegram.js +82 -0
  29. package/dist/channel/adapters/telegram.js.map +1 -1
  30. package/dist/channel/ipc-bridge.d.ts +17 -1
  31. package/dist/channel/ipc-bridge.js +53 -17
  32. package/dist/channel/ipc-bridge.js.map +1 -1
  33. package/dist/channel/ipc-timeouts.d.ts +46 -0
  34. package/dist/channel/ipc-timeouts.js +65 -0
  35. package/dist/channel/ipc-timeouts.js.map +1 -0
  36. package/dist/channel/mcp-server.js +30 -14
  37. package/dist/channel/mcp-server.js.map +1 -1
  38. package/dist/channel/mcp-tools.js +28 -1
  39. package/dist/channel/mcp-tools.js.map +1 -1
  40. package/dist/channel/reconnect-backoff.d.ts +17 -0
  41. package/dist/channel/reconnect-backoff.js +21 -0
  42. package/dist/channel/reconnect-backoff.js.map +1 -0
  43. package/dist/channel/types.d.ts +29 -0
  44. package/dist/classic-channel-manager.js +1 -5
  45. package/dist/classic-channel-manager.js.map +1 -1
  46. package/dist/cli.js +132 -52
  47. package/dist/cli.js.map +1 -1
  48. package/dist/completion.d.ts +27 -0
  49. package/dist/completion.js +121 -0
  50. package/dist/completion.js.map +1 -0
  51. package/dist/config-validator.js +9 -0
  52. package/dist/config-validator.js.map +1 -1
  53. package/dist/config.js +1 -0
  54. package/dist/config.js.map +1 -1
  55. package/dist/cost-guard.d.ts +3 -1
  56. package/dist/cost-guard.js +3 -1
  57. package/dist/cost-guard.js.map +1 -1
  58. package/dist/daemon.d.ts +219 -13
  59. package/dist/daemon.js +919 -303
  60. package/dist/daemon.js.map +1 -1
  61. package/dist/event-log.d.ts +31 -0
  62. package/dist/event-log.js +96 -0
  63. package/dist/event-log.js.map +1 -1
  64. package/dist/fleet-manager.d.ts +238 -2
  65. package/dist/fleet-manager.js +1008 -90
  66. package/dist/fleet-manager.js.map +1 -1
  67. package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +22 -0
  68. package/dist/general-knowledge/skills/model-discovery/SKILL.md +14 -23
  69. package/dist/general-knowledge/skills/session-management/SKILL.md +15 -34
  70. package/dist/hang-detector.d.ts +19 -13
  71. package/dist/hang-detector.js +19 -49
  72. package/dist/hang-detector.js.map +1 -1
  73. package/dist/instance-lifecycle.d.ts +13 -1
  74. package/dist/instance-lifecycle.js +84 -3
  75. package/dist/instance-lifecycle.js.map +1 -1
  76. package/dist/instructions.d.ts +5 -0
  77. package/dist/instructions.js +9 -11
  78. package/dist/instructions.js.map +1 -1
  79. package/dist/locale.js +2 -1
  80. package/dist/locale.js.map +1 -1
  81. package/dist/logger.js +14 -0
  82. package/dist/logger.js.map +1 -1
  83. package/dist/mcp-liveness.d.ts +21 -0
  84. package/dist/mcp-liveness.js +27 -0
  85. package/dist/mcp-liveness.js.map +1 -0
  86. package/dist/outbound-handlers.d.ts +16 -0
  87. package/dist/outbound-handlers.js +121 -27
  88. package/dist/outbound-handlers.js.map +1 -1
  89. package/dist/outbound-schemas.d.ts +8 -3
  90. package/dist/outbound-schemas.js +13 -2
  91. package/dist/outbound-schemas.js.map +1 -1
  92. package/dist/pane-write-lock.d.ts +48 -0
  93. package/dist/pane-write-lock.js +73 -0
  94. package/dist/pane-write-lock.js.map +1 -0
  95. package/dist/process-memory.d.ts +31 -0
  96. package/dist/process-memory.js +79 -0
  97. package/dist/process-memory.js.map +1 -0
  98. package/dist/quickstart.js +17 -16
  99. package/dist/quickstart.js.map +1 -1
  100. package/dist/reply-dedup.d.ts +41 -0
  101. package/dist/reply-dedup.js +0 -0
  102. package/dist/reply-dedup.js.map +1 -0
  103. package/dist/scheduler/db.js +3 -0
  104. package/dist/scheduler/db.js.map +1 -1
  105. package/dist/sd-notify.d.ts +27 -0
  106. package/dist/sd-notify.js +33 -1
  107. package/dist/sd-notify.js.map +1 -1
  108. package/dist/secret-file.d.ts +33 -0
  109. package/dist/secret-file.js +36 -0
  110. package/dist/secret-file.js.map +1 -0
  111. package/dist/setup-wizard.js +9 -7
  112. package/dist/setup-wizard.js.map +1 -1
  113. package/dist/tmux-control.d.ts +58 -5
  114. package/dist/tmux-control.js +102 -14
  115. package/dist/tmux-control.js.map +1 -1
  116. package/dist/tmux-manager.d.ts +31 -1
  117. package/dist/tmux-manager.js +40 -11
  118. package/dist/tmux-manager.js.map +1 -1
  119. package/dist/topic-commands.d.ts +50 -10
  120. package/dist/topic-commands.js +242 -106
  121. package/dist/topic-commands.js.map +1 -1
  122. package/dist/tui-glyphs.d.ts +25 -0
  123. package/dist/tui-glyphs.js +26 -0
  124. package/dist/tui-glyphs.js.map +1 -0
  125. package/dist/types.d.ts +6 -0
  126. package/dist/ui/view.html +123 -2
  127. package/dist/usage/format-rich.d.ts +11 -0
  128. package/dist/usage/format-rich.js +108 -0
  129. package/dist/usage/format-rich.js.map +1 -0
  130. package/dist/usage/providers.d.ts +97 -0
  131. package/dist/usage/providers.js +834 -0
  132. package/dist/usage/providers.js.map +1 -0
  133. package/dist/usage/usage-api.d.ts +50 -0
  134. package/dist/usage/usage-api.js +111 -0
  135. package/dist/usage/usage-api.js.map +1 -0
  136. package/dist/view-api.d.ts +3 -0
  137. package/dist/view-api.js +11 -2
  138. package/dist/view-api.js.map +1 -1
  139. package/dist/web-api.js +5 -2
  140. package/dist/web-api.js.map +1 -1
  141. package/package.json +4 -1
  142. package/dist/channel/tool-tracker.d.ts +0 -13
  143. package/dist/channel/tool-tracker.js +0 -58
  144. package/dist/channel/tool-tracker.js.map +0 -1
  145. package/dist/daemon-entry.d.ts +0 -1
  146. package/dist/daemon-entry.js +0 -30
  147. package/dist/daemon-entry.js.map +0 -1
@@ -0,0 +1,834 @@
1
+ /**
2
+ * AI subscription usage providers — read the credentials the CLI backends
3
+ * already saved on this machine and fetch live plan usage from each vendor's
4
+ * own usage endpoint. Powers `GET /api/ai-usage` (usage-api.ts) and the
5
+ * Usage panel on /view.
6
+ *
7
+ * Vendored from ai-usage-board (https://github.com/songsid/ai-usage-board, MIT),
8
+ * whose provider protocol logic is in turn ported from OpenUsage
9
+ * (https://github.com/robinebers/openusage, MIT, © Robin Ebers). See LICENSE.md
10
+ * in this directory. Not affiliated with or endorsed by OpenUsage.
11
+ *
12
+ * Token policy:
13
+ * - Claude/Codex: read-only, never refreshed — those vendors rotate refresh
14
+ * tokens, and refreshing behind the CLI's back could invalidate its login.
15
+ * Their credential files stay fresh as long as the CLIs are used (which, in
16
+ * a running fleet, they are).
17
+ * - Grok: access tokens expire within hours, so we refresh exactly like the
18
+ * Grok CLI does and persist rotated tokens back to auth.json — refusing to
19
+ * refresh at all when the file isn't writable, rather than risk the login.
20
+ */
21
+ import { readFile, writeFile, access, constants } from "node:fs/promises";
22
+ import { join } from "node:path";
23
+ import { homedir } from "node:os";
24
+ import Database from "better-sqlite3";
25
+ const WEEK_MS = 7 * 24 * 60 * 60 * 1000;
26
+ const SESSION_MS = 5 * 60 * 60 * 1000;
27
+ function jwtExpiryMs(token) {
28
+ try {
29
+ const payload = JSON.parse(Buffer.from(token.split(".")[1], "base64url").toString("utf8"));
30
+ return typeof payload.exp === "number" ? payload.exp * 1000 : null;
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ // ── Claude ───────────────────────────────────────────────────────────────────
37
+ const CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
38
+ function claudeResetIso(value) {
39
+ if (typeof value === "string" && value.trim()) {
40
+ const d = new Date(value);
41
+ if (!Number.isNaN(d.getTime()))
42
+ return d.toISOString();
43
+ }
44
+ if (typeof value === "number" && Number.isFinite(value)) {
45
+ const ms = Math.abs(value) < 1e10 ? value * 1000 : value;
46
+ return new Date(ms).toISOString();
47
+ }
48
+ return null;
49
+ }
50
+ /**
51
+ * Where the Claude OAuth bearer comes from, in preference order:
52
+ *
53
+ * 1. `~/.claude/.credentials.json` (`claudeAiOauth.accessToken`) when present and
54
+ * unexpired — the interactive `/login` flow. Carries plan metadata.
55
+ * 2. `CLAUDE_CODE_OAUTH_TOKEN` — the long-lived (annual) token minted by
56
+ * `claude setup-token`. Users on this flow often have NO credentials file at
57
+ * all (or a stale one from an old login), which is why /usage showed them
58
+ * "not logged in" / "token expired" while their CLI worked fine. Same token
59
+ * family (`sk-ant-oat…`), same usage endpoint; it just carries no plan
60
+ * metadata, so plan shows unknown.
61
+ * 3. An expired file token with no env fallback stays an explicit error.
62
+ * 4. `ANTHROPIC_API_KEY` alone is named in the hint but NOT used: console API
63
+ * keys are pay-per-token and have no subscription usage to query — the OAuth
64
+ * endpoint rejects them, and pretending otherwise would render a misleading
65
+ * error instead of an accurate "log in" hint.
66
+ */
67
+ export function resolveClaudeAuth(file, env = process.env) {
68
+ let plan = null;
69
+ if (file?.subscriptionType?.trim()) {
70
+ plan = file.subscriptionType.trim().replace(/^./, c => c.toUpperCase());
71
+ const tier = file.rateLimitTier?.match(/\d+x/);
72
+ if (tier)
73
+ plan += ` ${tier[0]}`;
74
+ }
75
+ const fileFresh = !!file?.accessToken && !(file.expiresAt && file.expiresAt < Date.now());
76
+ if (file?.accessToken && fileFresh)
77
+ return { token: file.accessToken.trim(), plan };
78
+ const envToken = env.CLAUDE_CODE_OAUTH_TOKEN?.trim();
79
+ if (envToken)
80
+ return { token: envToken, plan };
81
+ if (file?.accessToken) {
82
+ return { error: "Access token expired. Run `claude` once to refresh it.", plan };
83
+ }
84
+ return null;
85
+ }
86
+ async function fetchClaudeUsage() {
87
+ const home = process.env.CLAUDE_HOME || join(homedir(), ".claude");
88
+ let file;
89
+ try {
90
+ file = JSON.parse(await readFile(join(home, ".credentials.json"), "utf8")).claudeAiOauth ?? null;
91
+ }
92
+ catch {
93
+ file = null;
94
+ }
95
+ const auth = resolveClaudeAuth(file);
96
+ if (auth === null) {
97
+ const hint = process.env.ANTHROPIC_API_KEY
98
+ ? "API-key login has no subscription usage. Use `claude /login` or set CLAUDE_CODE_OAUTH_TOKEN (from `claude setup-token`)."
99
+ : "Log in with the Claude Code CLI (`claude`).";
100
+ return { status: "no-credentials", hint, metrics: [] };
101
+ }
102
+ if ("error" in auth) {
103
+ return { status: "error", plan: auth.plan, error: auth.error, metrics: [] };
104
+ }
105
+ const plan = auth.plan;
106
+ let res;
107
+ try {
108
+ res = await fetch(CLAUDE_USAGE_URL, {
109
+ headers: {
110
+ Authorization: `Bearer ${auth.token}`,
111
+ Accept: "application/json",
112
+ "Content-Type": "application/json",
113
+ "anthropic-beta": "oauth-2025-04-20",
114
+ "User-Agent": "claude-code/2.1.69",
115
+ },
116
+ signal: AbortSignal.timeout(10_000),
117
+ });
118
+ }
119
+ catch {
120
+ return { status: "error", plan, error: "Could not reach api.anthropic.com.", metrics: [] };
121
+ }
122
+ if (res.status === 401 || res.status === 403) {
123
+ return { status: "error", plan, error: "Token rejected. Run `claude` once to refresh the login.", metrics: [] };
124
+ }
125
+ if (res.status === 429) {
126
+ return { status: "error", plan, error: "Rate limited by Anthropic — try again later.", metrics: [] };
127
+ }
128
+ if (!res.ok)
129
+ return { status: "error", plan, error: `Usage request failed (HTTP ${res.status}).`, metrics: [] };
130
+ let body;
131
+ try {
132
+ body = await res.json();
133
+ }
134
+ catch {
135
+ return { status: "error", plan, error: "Invalid response from usage endpoint.", metrics: [] };
136
+ }
137
+ const metrics = [];
138
+ const window = (obj, label, windowMs) => {
139
+ const o = obj;
140
+ if (typeof o?.utilization !== "number")
141
+ return;
142
+ metrics.push({ label, type: "percent", used: o.utilization, resetsAt: claudeResetIso(o.resets_at), windowMs });
143
+ };
144
+ window(body.five_hour, "Session", SESSION_MS);
145
+ window(body.seven_day, "Weekly", WEEK_MS);
146
+ window(body.seven_day_sonnet, "Sonnet (weekly)", WEEK_MS);
147
+ // Per-model weekly windows live in the `limits` array (kind: weekly_scoped).
148
+ for (const entry of Array.isArray(body.limits) ? body.limits : []) {
149
+ const e = entry;
150
+ if (e?.kind !== "weekly_scoped")
151
+ continue;
152
+ const model = e.scope?.model?.display_name;
153
+ if (!model || typeof e.percent !== "number")
154
+ continue;
155
+ metrics.push({ label: `${model} (weekly)`, type: "percent", used: e.percent, resetsAt: claudeResetIso(e.resets_at), windowMs: WEEK_MS });
156
+ }
157
+ const extra = body.extra_usage;
158
+ if (extra?.is_enabled === true && typeof extra.used_credits === "number") {
159
+ const used = extra.used_credits / 100;
160
+ const limit = typeof extra.monthly_limit === "number" && extra.monthly_limit > 0 ? extra.monthly_limit / 100 : null;
161
+ if (limit)
162
+ metrics.push({ label: "Extra usage", type: "dollars", used, limit });
163
+ else if (used > 0)
164
+ metrics.push({ label: "Extra usage", type: "dollars", used });
165
+ }
166
+ return { status: "ok", plan, metrics };
167
+ }
168
+ // ── Antigravity ──────────────────────────────────────────────────────────────
169
+ //
170
+ // Cloud Code quota API, verified live against this machine's real agy login
171
+ // (2026-08-02): refresh the Google OAuth token, then POST
172
+ // `retrieveUserQuotaSummary`. The flow and the installed-app client pair come
173
+ // from OpenUsage's Antigravity provider; for installed-app OAuth clients Google
174
+ // does not treat the "secret" as confidential (it ships inside every copy of
175
+ // the app), so embedding it is the accepted norm, not a leaked key. It is
176
+ // required for the refresh-token grant.
177
+ const AGY_TOKEN_FILE = ["antigravity-cli", "antigravity-oauth-token"];
178
+ const AGY_CLOUDCODE_URLS = [
179
+ "https://daily-cloudcode-pa.googleapis.com",
180
+ "https://cloudcode-pa.googleapis.com",
181
+ ];
182
+ /**
183
+ * The Google installed-app OAuth client pair, READ FROM THE INSTALLED agy
184
+ * BINARY rather than committed here.
185
+ *
186
+ * Installed-app clients embed their "secret" in every copy, so Google does not
187
+ * treat it as confidential — but that does not make it ours to publish, and
188
+ * GitHub's push protection agrees. Scanning the binary we are already
189
+ * authenticating on behalf of keeps the credential where its owner put it: if
190
+ * agy is not installed, we simply cannot refresh, which is the correct answer
191
+ * anyway. ~180MB scans in well under a second and the result is cached.
192
+ */
193
+ /**
194
+ * Refresh the Google OAuth token — only when the operator has supplied the
195
+ * installed-app client pair.
196
+ *
197
+ * agy stores a Google OAuth token that expires hourly and refreshes it whenever
198
+ * agy itself runs. Refreshing it ourselves needs the app's installed-app client
199
+ * pair, and there is no honest way for AgEnD to obtain it: it is not recoverable
200
+ * from the shipped binary (the strings that look like it are a different
201
+ * client), and hard-coding the published pair would mean committing a
202
+ * credential to a public repo — which GitHub push protection blocks, correctly.
203
+ *
204
+ * So it is opt-in. Without it, an expired token yields a clear "run `agy` once"
205
+ * hint rather than a broken panel — and in the case this provider actually
206
+ * exists for (a fleet with a live agy instance), agy is running and keeping its
207
+ * own token fresh, so the refresh is rarely needed at all.
208
+ */
209
+ function agyOAuthClient(env = process.env) {
210
+ const id = env.AGY_OAUTH_CLIENT_ID?.trim();
211
+ const secret = env.AGY_OAUTH_CLIENT_SECRET?.trim();
212
+ return id && secret ? { id, secret } : null;
213
+ }
214
+ /** Refreshed bearer, cached until shortly before expiry. The CLI's token file is
215
+ * never written back — it belongs to agy; refresh tokens are reusable. */
216
+ let agyTokenCache = null;
217
+ /**
218
+ * Pool the summary's buckets into at most four metrics.
219
+ *
220
+ * Two payload shapes exist. Older accounts report pooled ids (`gemini-5h`,
221
+ * `gemini-weekly`, `3p-5h`, `3p-weekly`), which map 1:1. This machine's live
222
+ * response instead lists PER-MODEL buckets (`gemini-3.6-flash-high`,
223
+ * `claude-sonnet-4-6`, `gpt-oss-120b-medium`, …) — those aggregate into a
224
+ * Gemini pool and an everything-else pool, keeping each pool's WORST remaining
225
+ * fraction, because eleven per-model meters is noise and the binding constraint
226
+ * is the one that runs out first.
227
+ */
228
+ export function agyPoolMetrics(buckets) {
229
+ const POOLED = {
230
+ "gemini-5h": "Gemini (session)", "gemini-weekly": "Gemini (weekly)",
231
+ "3p-5h": "Claude & others (session)", "3p-weekly": "Claude & others (weekly)",
232
+ };
233
+ const direct = [];
234
+ const pools = new Map();
235
+ for (const b of buckets) {
236
+ if (!b.bucketId || typeof b.remainingFraction !== "number" || !Number.isFinite(b.remainingFraction))
237
+ continue;
238
+ const reset = b.resetTime ?? null;
239
+ const pooledLabel = POOLED[b.bucketId];
240
+ if (pooledLabel) {
241
+ direct.push({ label: pooledLabel, type: "percent", used: (1 - b.remainingFraction) * 100, resetsAt: reset });
242
+ continue;
243
+ }
244
+ const pool = b.bucketId.startsWith("gemini") ? "Gemini" : "Claude & others";
245
+ const existing = pools.get(pool);
246
+ if (!existing || b.remainingFraction < existing.fraction) {
247
+ pools.set(pool, { fraction: b.remainingFraction, resetsAt: reset });
248
+ }
249
+ }
250
+ if (direct.length)
251
+ return direct;
252
+ return [...pools.entries()].map(([label, p]) => ({
253
+ label, type: "percent", used: (1 - p.fraction) * 100, resetsAt: p.resetsAt,
254
+ }));
255
+ }
256
+ async function agyAccessToken() {
257
+ const home = process.env.GEMINI_HOME || join(homedir(), ".gemini");
258
+ let file;
259
+ try {
260
+ file = JSON.parse(await readFile(join(home, ...AGY_TOKEN_FILE), "utf8"));
261
+ }
262
+ catch {
263
+ return null; // no agy login on this machine
264
+ }
265
+ const t = file.token ?? {};
266
+ const expiryMs = t.expiry ? new Date(t.expiry).getTime() : 0;
267
+ if (t.access_token && expiryMs > Date.now() + 60_000)
268
+ return { token: t.access_token };
269
+ if (agyTokenCache && agyTokenCache.until > Date.now())
270
+ return { token: agyTokenCache.token };
271
+ const client = agyOAuthClient();
272
+ if (!t.refresh_token || !client) {
273
+ if (!t.access_token)
274
+ return null;
275
+ return {
276
+ error: client
277
+ ? "Access token expired and no refresh token is stored. Run `agy` once."
278
+ : "Access token expired. Run `agy` once to refresh it (or set AGY_OAUTH_CLIENT_ID/SECRET to refresh automatically).",
279
+ };
280
+ }
281
+ try {
282
+ const res = await fetch("https://oauth2.googleapis.com/token", {
283
+ method: "POST",
284
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
285
+ body: new URLSearchParams({
286
+ client_id: client.id,
287
+ client_secret: client.secret,
288
+ refresh_token: t.refresh_token,
289
+ grant_type: "refresh_token",
290
+ }),
291
+ signal: AbortSignal.timeout(15_000),
292
+ });
293
+ if (!res.ok)
294
+ return { error: "Google sign-in expired. Run `agy` once to log in again." };
295
+ const body = await res.json();
296
+ if (!body.access_token)
297
+ return { error: "Google token refresh returned no token." };
298
+ agyTokenCache = { token: body.access_token, until: Date.now() + Math.max(60, (body.expires_in ?? 3600) - 120) * 1000 };
299
+ return { token: body.access_token };
300
+ }
301
+ catch {
302
+ return { error: "Could not reach oauth2.googleapis.com." };
303
+ }
304
+ }
305
+ async function fetchAntigravityUsage() {
306
+ const auth = await agyAccessToken();
307
+ if (auth === null) {
308
+ return { status: "no-credentials", hint: "Log in with the Antigravity CLI (`agy`).", metrics: [] };
309
+ }
310
+ if ("error" in auth)
311
+ return { status: "error", error: auth.error, metrics: [] };
312
+ for (const base of AGY_CLOUDCODE_URLS) {
313
+ let res;
314
+ try {
315
+ res = await fetch(`${base}/v1internal:retrieveUserQuotaSummary`, {
316
+ method: "POST",
317
+ headers: {
318
+ Authorization: `Bearer ${auth.token}`,
319
+ "Content-Type": "application/json",
320
+ "User-Agent": "antigravity",
321
+ },
322
+ body: "{}",
323
+ signal: AbortSignal.timeout(15_000),
324
+ });
325
+ }
326
+ catch {
327
+ continue;
328
+ }
329
+ if (res.status === 401 || res.status === 403) {
330
+ return { status: "error", error: "Token rejected. Run `agy` once to refresh the login.", metrics: [] };
331
+ }
332
+ if (!res.ok)
333
+ continue; // try the other base
334
+ let body;
335
+ try {
336
+ body = await res.json();
337
+ }
338
+ catch {
339
+ continue;
340
+ }
341
+ const buckets = (body.groups ?? []).flatMap(g => g.buckets ?? []);
342
+ const metrics = agyPoolMetrics(buckets);
343
+ return metrics.length
344
+ ? { status: "ok", plan: null, metrics }
345
+ : { status: "ok", plan: null, hint: "No quota information reported for this account.", metrics: [] };
346
+ }
347
+ return { status: "error", error: "Could not reach the Cloud Code quota endpoints.", metrics: [] };
348
+ }
349
+ // ── Codex ────────────────────────────────────────────────────────────────────
350
+ const CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
351
+ const CREDIT_USD_RATE = 0.04;
352
+ function codexResetIso(win, nowMs) {
353
+ if (typeof win.reset_at === "number" && Number.isFinite(win.reset_at))
354
+ return new Date(win.reset_at * 1000).toISOString();
355
+ if (typeof win.reset_after_seconds === "number" && Number.isFinite(win.reset_after_seconds)) {
356
+ return new Date(nowMs + win.reset_after_seconds * 1000).toISOString();
357
+ }
358
+ return null;
359
+ }
360
+ // Codex normally puts the 5-hour window in primary and weekly in secondary, but
361
+ // a window's own limit_window_seconds wins when present. Some plans (e.g. Team)
362
+ // report a monthly window — label by actual duration, never by slot.
363
+ function codexWindows(rateLimit, labels, nowMs) {
364
+ const candidates = [
365
+ { win: rateLimit?.primary_window, fallback: "session" },
366
+ { win: rateLimit?.secondary_window, fallback: "weekly" },
367
+ ].filter(c => c.win && typeof c.win === "object");
368
+ const metrics = [];
369
+ for (const { win, fallback } of candidates) {
370
+ if (!win || typeof win.used_percent !== "number")
371
+ continue;
372
+ const explicitMs = typeof win.limit_window_seconds === "number" && Number.isFinite(win.limit_window_seconds)
373
+ ? win.limit_window_seconds * 1000 : null;
374
+ const windowMs = explicitMs ?? (fallback === "session" ? SESSION_MS : WEEK_MS);
375
+ let label;
376
+ if (windowMs === SESSION_MS)
377
+ label = labels.session;
378
+ else if (windowMs === WEEK_MS)
379
+ label = labels.weekly;
380
+ else if (windowMs >= 27 * 864e5 && windowMs <= 32 * 864e5)
381
+ label = labels.monthly;
382
+ else if (explicitMs)
383
+ label = labels.other(Math.round(windowMs / 864e5));
384
+ else
385
+ label = fallback === "session" ? labels.session : labels.weekly;
386
+ metrics.push({ label, type: "percent", used: win.used_percent, resetsAt: codexResetIso(win, nowMs), windowMs });
387
+ }
388
+ return metrics;
389
+ }
390
+ function codexPlan(planType) {
391
+ if (typeof planType !== "string" || !planType.trim())
392
+ return null;
393
+ switch (planType.trim().toLowerCase()) {
394
+ case "prolite": return "Pro 5x";
395
+ case "pro": return "Pro 20x";
396
+ default: return planType.trim().split("_").map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
397
+ }
398
+ }
399
+ async function fetchCodexUsage() {
400
+ const home = process.env.CODEX_HOME || join(homedir(), ".codex");
401
+ let auth;
402
+ try {
403
+ auth = JSON.parse(await readFile(join(home, "auth.json"), "utf8"));
404
+ }
405
+ catch {
406
+ return { status: "no-credentials", hint: "Log in with the Codex CLI (`codex`).", metrics: [] };
407
+ }
408
+ const accessToken = auth?.tokens?.access_token;
409
+ if (!accessToken) {
410
+ return { status: "no-credentials", hint: "auth.json has no OAuth login (API-key-only auth cannot read usage).", metrics: [] };
411
+ }
412
+ const exp = jwtExpiryMs(accessToken);
413
+ if (exp && exp < Date.now()) {
414
+ return { status: "error", error: "Access token expired. Run `codex` once to refresh it.", metrics: [] };
415
+ }
416
+ const headers = {
417
+ Authorization: `Bearer ${accessToken}`,
418
+ Accept: "application/json",
419
+ "User-Agent": "agend-usage",
420
+ };
421
+ if (auth.tokens?.account_id)
422
+ headers["ChatGPT-Account-Id"] = auth.tokens.account_id;
423
+ let res;
424
+ try {
425
+ res = await fetch(CODEX_USAGE_URL, { headers, signal: AbortSignal.timeout(10_000) });
426
+ }
427
+ catch {
428
+ return { status: "error", error: "Could not reach chatgpt.com.", metrics: [] };
429
+ }
430
+ if (res.status === 401 || res.status === 403) {
431
+ return { status: "error", error: "Token rejected. Run `codex` once to refresh the login.", metrics: [] };
432
+ }
433
+ if (!res.ok)
434
+ return { status: "error", error: `Usage request failed (HTTP ${res.status}).`, metrics: [] };
435
+ let body;
436
+ try {
437
+ body = await res.json();
438
+ }
439
+ catch {
440
+ return { status: "error", error: "Invalid response from usage endpoint.", metrics: [] };
441
+ }
442
+ const nowMs = Date.now();
443
+ const metrics = codexWindows(body.rate_limit, {
444
+ session: "Session", weekly: "Weekly", monthly: "Monthly", other: d => `${d}-day window`,
445
+ }, nowMs);
446
+ // Model-specific limits (e.g. Spark) ride in additional_rate_limits, same window shape.
447
+ for (const entry of Array.isArray(body.additional_rate_limits) ? body.additional_rate_limits : []) {
448
+ const e = entry;
449
+ if (!e || typeof e !== "object" || !e.rate_limit)
450
+ continue;
451
+ const rawName = e.limit_name || e.metered_feature || "Model limit";
452
+ metrics.push(...codexWindows(e.rate_limit, {
453
+ session: rawName, weekly: `${rawName} (weekly)`, monthly: `${rawName} (monthly)`, other: d => `${rawName} (${d}d)`,
454
+ }, nowMs));
455
+ }
456
+ const resets = body.rate_limit_reset_credits;
457
+ if (typeof resets?.available_count === "number" && resets.available_count >= 0) {
458
+ metrics.push({ label: "Rate limit resets", type: "count", value: Math.floor(resets.available_count), unit: "available" });
459
+ }
460
+ const credits = body.credits;
461
+ let remaining = null;
462
+ if (typeof credits?.balance === "number")
463
+ remaining = credits.balance;
464
+ else if (credits?.has_credits === false)
465
+ remaining = 0;
466
+ if (remaining !== null) {
467
+ const count = Math.max(0, Math.floor(remaining));
468
+ metrics.push({ label: "Credits", type: "count", value: count, unit: "credits", note: `≈ $${(count * CREDIT_USD_RATE).toFixed(2)}` });
469
+ }
470
+ return { status: "ok", plan: codexPlan(body.plan_type), metrics };
471
+ }
472
+ // ── Grok ─────────────────────────────────────────────────────────────────────
473
+ const GROK_CREDITS_URL = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
474
+ const GROK_SETTINGS_URL = "https://cli-chat-proxy.grok.com/v1/settings";
475
+ const GROK_REFRESH_URL = "https://auth.x.ai/oauth2/token";
476
+ const GROK_DEFAULT_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828";
477
+ const GROK_WEEKLY_PERIOD = "USAGE_PERIOD_TYPE_WEEKLY";
478
+ const GROK_REFRESH_BUFFER_MS = 5 * 60 * 1000;
479
+ function grokEntryExpiryMs(entry, token) {
480
+ const fromJwt = jwtExpiryMs(token);
481
+ if (fromJwt)
482
+ return fromJwt;
483
+ const raw = entry.expires_at || entry.expires;
484
+ if (typeof raw === "string") {
485
+ const ms = new Date(raw).getTime();
486
+ if (!Number.isNaN(ms))
487
+ return ms;
488
+ }
489
+ return null;
490
+ }
491
+ async function grokRefreshAndPersist(file, auth, entryKey, entry) {
492
+ // Refuse to refresh unless the rotated tokens can be written back — a rotated
493
+ // refresh token that only lives in our memory would break `grok` itself.
494
+ try {
495
+ await access(file, constants.W_OK);
496
+ }
497
+ catch {
498
+ return { error: "Token expired and auth.json is read-only. Run `grok` once to refresh it." };
499
+ }
500
+ const refreshToken = (entry.refresh_token || entry.refresh || "").trim();
501
+ if (!refreshToken)
502
+ return { error: "Token expired and no refresh token found. Run `grok login`." };
503
+ const clientId = entry.oidc_client_id?.trim()
504
+ || entryKey.split("::").pop()?.trim()
505
+ || GROK_DEFAULT_CLIENT_ID;
506
+ let res;
507
+ try {
508
+ res = await fetch(GROK_REFRESH_URL, {
509
+ method: "POST",
510
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
511
+ body: new URLSearchParams({ grant_type: "refresh_token", client_id: clientId, refresh_token: refreshToken }),
512
+ signal: AbortSignal.timeout(15_000),
513
+ });
514
+ }
515
+ catch {
516
+ return { error: "Could not reach auth.x.ai to refresh the token." };
517
+ }
518
+ if (!res.ok)
519
+ return { error: "Grok session expired. Run `grok login` again." };
520
+ let body;
521
+ try {
522
+ body = await res.json();
523
+ }
524
+ catch {
525
+ return { error: "Invalid refresh response from auth.x.ai." };
526
+ }
527
+ if (!body.access_token)
528
+ return { error: "Grok session expired. Run `grok login` again." };
529
+ // Update only this entry's fields, preserving everything else in the file
530
+ // (other accounts' entries included).
531
+ const updated = { ...(auth[entryKey] ?? {}) };
532
+ updated.key = body.access_token;
533
+ if (body.refresh_token)
534
+ updated.refresh_token = body.refresh_token;
535
+ if (body.id_token)
536
+ updated.id_token = body.id_token;
537
+ if (typeof body.expires_in === "number")
538
+ updated.expires_at = new Date(Date.now() + body.expires_in * 1000).toISOString();
539
+ try {
540
+ await writeFile(file, JSON.stringify({ ...auth, [entryKey]: updated }, null, 2));
541
+ }
542
+ catch {
543
+ return { error: "Refreshed but could not write auth.json — refusing to continue without persisting. Run `grok` once instead." };
544
+ }
545
+ return { token: body.access_token };
546
+ }
547
+ function grokHeaders(token) {
548
+ return {
549
+ Authorization: `Bearer ${token.trim()}`,
550
+ "X-XAI-Token-Auth": "xai-grok-cli",
551
+ Accept: "application/json",
552
+ "User-Agent": "agend-usage",
553
+ };
554
+ }
555
+ async function fetchGrokUsage() {
556
+ const home = process.env.GROK_HOME || join(homedir(), ".grok");
557
+ const file = join(home, "auth.json");
558
+ let auth;
559
+ try {
560
+ auth = JSON.parse(await readFile(file, "utf8"));
561
+ }
562
+ catch {
563
+ return { status: "no-credentials", hint: "Log in with the Grok CLI (`grok login`).", metrics: [] };
564
+ }
565
+ const entries = Object.entries(auth).filter(([, e]) => typeof e?.key === "string" && e.key.trim());
566
+ if (!entries.length)
567
+ return { status: "no-credentials", hint: "auth.json has no usable login. Run `grok login`.", metrics: [] };
568
+ const [entryKey, entry] = entries[0];
569
+ let token = entry.key.trim();
570
+ const expiry = grokEntryExpiryMs(entry, token);
571
+ if (expiry && expiry - Date.now() <= GROK_REFRESH_BUFFER_MS) {
572
+ const refreshed = await grokRefreshAndPersist(file, auth, entryKey, entry);
573
+ if (refreshed.error)
574
+ return { status: "error", error: refreshed.error, metrics: [] };
575
+ token = refreshed.token;
576
+ }
577
+ const fetchBoth = async (tok) => {
578
+ const [credits, settings] = await Promise.all([
579
+ fetch(GROK_CREDITS_URL, { headers: grokHeaders(tok), signal: AbortSignal.timeout(10_000) }),
580
+ fetch(GROK_SETTINGS_URL, { headers: grokHeaders(tok), signal: AbortSignal.timeout(10_000) }).catch(() => null),
581
+ ]);
582
+ return { credits, settings };
583
+ };
584
+ let credits, settings;
585
+ try {
586
+ ({ credits, settings } = await fetchBoth(token));
587
+ if (credits.status === 401 || credits.status === 403) {
588
+ const refreshed = await grokRefreshAndPersist(file, auth, entryKey, entry);
589
+ if (refreshed.error)
590
+ return { status: "error", error: refreshed.error, metrics: [] };
591
+ token = refreshed.token;
592
+ ({ credits, settings } = await fetchBoth(token));
593
+ }
594
+ }
595
+ catch {
596
+ return { status: "error", error: "Could not reach cli-chat-proxy.grok.com.", metrics: [] };
597
+ }
598
+ if (credits.status === 401 || credits.status === 403) {
599
+ return { status: "error", error: "Grok session expired. Run `grok login` again.", metrics: [] };
600
+ }
601
+ if (!credits.ok)
602
+ return { status: "error", error: `Billing request failed (HTTP ${credits.status}).`, metrics: [] };
603
+ let body;
604
+ try {
605
+ body = await credits.json();
606
+ }
607
+ catch {
608
+ return { status: "error", error: "Invalid response from billing endpoint.", metrics: [] };
609
+ }
610
+ const config = body?.config;
611
+ const period = config?.currentPeriod;
612
+ if (!config || !period?.type)
613
+ return { status: "error", error: "Grok billing response changed.", metrics: [] };
614
+ const metrics = [];
615
+ if (period.type === GROK_WEEKLY_PERIOD) {
616
+ // proto-JSON drops zero-valued fields: an absent creditUsagePercent means 0%.
617
+ const pct = typeof config.creditUsagePercent === "number" ? config.creditUsagePercent : 0;
618
+ const start = new Date(period.start ?? "").getTime();
619
+ const end = new Date(period.end ?? "").getTime();
620
+ metrics.push({
621
+ label: "Weekly limit",
622
+ type: "percent",
623
+ used: Math.min(100, Math.max(0, pct)),
624
+ resetsAt: Number.isNaN(end) ? null : new Date(end).toISOString(),
625
+ windowMs: Number.isNaN(end - start) ? null : end - start,
626
+ });
627
+ }
628
+ const cap = typeof config.onDemandCap?.val === "number" ? config.onDemandCap.val : 0;
629
+ metrics.push({ label: "Pay as you go", type: "text", value: cap > 0 ? `${cap} cap` : "Disabled" });
630
+ let plan = null;
631
+ if (settings?.ok) {
632
+ try {
633
+ const s = await settings.json();
634
+ if (typeof s.subscription_tier_display === "string" && s.subscription_tier_display.trim()) {
635
+ plan = s.subscription_tier_display.trim();
636
+ }
637
+ }
638
+ catch { /* plan is optional */ }
639
+ }
640
+ return { status: "ok", plan, metrics };
641
+ }
642
+ // ── Kiro (Amazon Q Developer) ────────────────────────────────────────────────
643
+ // Original research, no OpenUsage upstream: the Kiro CLI stores its login in
644
+ // data.sqlite3 `auth_kv` (social or Identity Center token) and usage rides on
645
+ // the CodeWhisperer GetUsageLimits API — the exact call the CLI itself makes.
646
+ // Read-only: the CLI refreshes its own tokens.
647
+ const KIRO_TARGET = "AmazonCodeWhispererService.GetUsageLimits";
648
+ export function kiroAuthKind(token) {
649
+ return typeof token.start_url === "string" && token.start_url.trim().length > 0
650
+ ? "q-developer-pro"
651
+ : "builder-id";
652
+ }
653
+ function readKiroToken() {
654
+ const home = process.env.KIRO_CLI_HOME || join(homedir(), ".local", "share", "kiro-cli");
655
+ let db;
656
+ try {
657
+ db = new Database(join(home, "data.sqlite3"), { readonly: true, fileMustExist: true });
658
+ }
659
+ catch {
660
+ return { missing: true };
661
+ }
662
+ try {
663
+ const rows = db.prepare("SELECT key, value FROM auth_kv WHERE key IN ('kirocli:social:token','codewhisperer:odic:token')").all();
664
+ const byKey = Object.fromEntries(rows.map(r => [r.key, r.value]));
665
+ const parse = (raw) => {
666
+ if (!raw)
667
+ return null;
668
+ try {
669
+ const t = JSON.parse(raw);
670
+ return t.access_token ? t : null;
671
+ }
672
+ catch {
673
+ return null;
674
+ }
675
+ };
676
+ const candidates = [parse(byKey["kirocli:social:token"]), parse(byKey["codewhisperer:odic:token"])]
677
+ .filter((t) => t !== null);
678
+ if (candidates.length === 0)
679
+ return { missing: true };
680
+ // Switching login type leaves the old token behind, so "first key wins"
681
+ // could report a stale account. Prefer a token that has not expired, then
682
+ // the one that expires latest.
683
+ const expiry = (t) => (t.expires_at ? new Date(t.expires_at).getTime() : 0);
684
+ const now = Date.now();
685
+ const live = candidates.filter(t => expiry(t) > now);
686
+ const token = (live.length ? live : candidates).sort((a, b) => expiry(b) - expiry(a))[0];
687
+ return { token, kind: kiroAuthKind(token) };
688
+ }
689
+ catch {
690
+ return { missing: true };
691
+ }
692
+ finally {
693
+ try {
694
+ db.close();
695
+ }
696
+ catch { /* best-effort */ }
697
+ }
698
+ }
699
+ function kiroTitleCase(s) {
700
+ return s.toLowerCase().replace(/(^|\s)\S/g, c => c.toUpperCase());
701
+ }
702
+ function kiroEpochIso(sec) {
703
+ return typeof sec === "number" && Number.isFinite(sec) && sec > 0
704
+ ? new Date(sec * 1000).toISOString()
705
+ : null;
706
+ }
707
+ /** Exported for tests: the Q-Pro and expired paths return without any network call. */
708
+ export async function fetchKiroUsage() {
709
+ const { token, kind, missing } = readKiroToken();
710
+ if (missing || !token) {
711
+ return { status: "no-credentials", hint: "Log in with the Kiro CLI (`kiro-cli`).", metrics: [] };
712
+ }
713
+ const expiresAt = token.expires_at ? new Date(token.expires_at).getTime() : null;
714
+ if (expiresAt && expiresAt < Date.now()) {
715
+ // Not an error state: kiro-cli refreshes its own login on next use, and the
716
+ // panel showing a red failure for a routine token rollover is just noise.
717
+ return { status: "no-credentials", hint: "Sign-in needed — run `kiro-cli` once and it refreshes itself.", metrics: [] };
718
+ }
719
+ if (kind === "q-developer-pro") {
720
+ // Seat-licensed subscription: GetUsageLimits describes Builder-ID credit
721
+ // buckets, not this, so there is nothing to meter and no call to make.
722
+ return {
723
+ status: "ok",
724
+ plan: "Q Developer Pro",
725
+ hint: "Subscription — no credit usage to report.",
726
+ metrics: [],
727
+ };
728
+ }
729
+ const region = token.region
730
+ || (typeof token.profile_arn === "string" ? token.profile_arn.split(":")[3] : "")
731
+ || "us-east-1";
732
+ let res;
733
+ try {
734
+ res = await fetch(`https://codewhisperer.${region}.amazonaws.com/`, {
735
+ method: "POST",
736
+ headers: {
737
+ "Content-Type": "application/x-amz-json-1.0",
738
+ "X-Amz-Target": KIRO_TARGET,
739
+ Authorization: `Bearer ${token.access_token}`,
740
+ },
741
+ body: JSON.stringify(token.profile_arn ? { profileArn: token.profile_arn } : {}),
742
+ signal: AbortSignal.timeout(15_000),
743
+ });
744
+ }
745
+ catch {
746
+ return { status: "error", error: `Could not reach codewhisperer.${region}.amazonaws.com.`, metrics: [] };
747
+ }
748
+ if (res.status === 401 || res.status === 403) {
749
+ return { status: "error", error: "Token rejected. Use `kiro-cli` once to refresh the login.", metrics: [] };
750
+ }
751
+ if (!res.ok)
752
+ return { status: "error", error: `Usage request failed (HTTP ${res.status}).`, metrics: [] };
753
+ let body;
754
+ try {
755
+ body = await res.json();
756
+ }
757
+ catch {
758
+ return { status: "error", error: "Invalid response from GetUsageLimits.", metrics: [] };
759
+ }
760
+ const plan = typeof body.subscriptionInfo?.subscriptionTitle === "string"
761
+ ? kiroTitleCase(body.subscriptionInfo.subscriptionTitle)
762
+ : null;
763
+ const metrics = [];
764
+ for (const ub of Array.isArray(body.usageBreakdownList) ? body.usageBreakdownList : []) {
765
+ const unit = (ub.displayNamePlural || ub.displayName || "credits").toLowerCase();
766
+ const used = ub.currentUsageWithPrecision ?? ub.currentUsage ?? null;
767
+ const limit = ub.usageLimitWithPrecision ?? ub.usageLimit ?? null;
768
+ if (used !== null && limit !== null && limit > 0) {
769
+ metrics.push({
770
+ label: `${ub.displayNamePlural || ub.displayName || "Usage"} (monthly)`,
771
+ type: "percent",
772
+ used: Math.min(100, (used / limit) * 100),
773
+ resetsAt: kiroEpochIso(ub.nextDateReset ?? body.nextDateReset),
774
+ note: `${+used.toFixed(1)} / ${+limit.toFixed(0)} ${unit}`,
775
+ });
776
+ }
777
+ // Bonus / gift credits (redeemed promo codes), aggregated across active codes.
778
+ const bonuses = (ub.bonuses ?? []).filter(b => b?.status === "ACTIVE");
779
+ if (bonuses.length) {
780
+ const bUsed = bonuses.reduce((s, b) => s + (b.currentUsage ?? 0), 0);
781
+ const bLimit = bonuses.reduce((s, b) => s + (b.usageLimit ?? 0), 0);
782
+ const expiries = bonuses.map(b => b.expiresAt).filter((e) => typeof e === "number" && e > 0);
783
+ if (bLimit > 0) {
784
+ metrics.push({
785
+ label: "Bonus credits",
786
+ type: "percent",
787
+ used: Math.min(100, (bUsed / bLimit) * 100),
788
+ resetsAt: expiries.length ? kiroEpochIso(Math.min(...expiries)) : null,
789
+ note: `${+bUsed.toFixed(1)} / ${+bLimit.toFixed(0)} ${unit} · ${bonuses.length} codes`,
790
+ });
791
+ }
792
+ }
793
+ const overages = ub.currentOveragesWithPrecision ?? ub.currentOverages ?? 0;
794
+ if (overages > 0 && typeof ub.overageCharges === "number") {
795
+ metrics.push({ label: "Overage charges", type: "dollars", used: ub.overageCharges });
796
+ }
797
+ }
798
+ const overageStatus = body.overageConfiguration?.overageStatus;
799
+ if (typeof overageStatus === "string") {
800
+ metrics.push({ label: "Pay-per-use", type: "text", value: kiroTitleCase(overageStatus.replace(/_/g, " ")) });
801
+ }
802
+ if (metrics.length === 0) {
803
+ // Amazon Q logins whose account type reports no credit buckets (#398's
804
+ // sibling case): an OK answer with nothing in it must say so, not render an
805
+ // empty row that reads like a failure.
806
+ return { status: "ok", plan: plan ?? "Amazon Q", hint: "No quota information available for this account type.", metrics: [] };
807
+ }
808
+ return { status: "ok", plan, metrics };
809
+ }
810
+ // ── Registry ─────────────────────────────────────────────────────────────────
811
+ const PROVIDERS = [
812
+ { id: "claude", name: "Claude", fetch: fetchClaudeUsage },
813
+ { id: "antigravity", name: "Antigravity", fetch: fetchAntigravityUsage },
814
+ { id: "codex", name: "Codex", fetch: fetchCodexUsage },
815
+ { id: "grok", name: "Grok", fetch: fetchGrokUsage },
816
+ { id: "kiro", name: "Kiro", fetch: fetchKiroUsage },
817
+ ];
818
+ /** Fetch every provider in parallel. Providers without local credentials are
819
+ * skipped (per the panel's contract: absent CLIs simply don't show). */
820
+ export async function fetchAllUsage() {
821
+ const results = await Promise.all(PROVIDERS.map(async (p) => {
822
+ try {
823
+ return { id: p.id, name: p.name, ...(await p.fetch()) };
824
+ }
825
+ catch (err) {
826
+ return { id: p.id, name: p.name, status: "error", error: String(err?.message ?? err), metrics: [] };
827
+ }
828
+ }));
829
+ return {
830
+ fetchedAt: new Date().toISOString(),
831
+ providers: results.filter(r => r.status !== "no-credentials"),
832
+ };
833
+ }
834
+ //# sourceMappingURL=providers.js.map