tokenusage-cli 0.1.0 → 0.2.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 (131) hide show
  1. package/CHANGELOG.md +39 -19
  2. package/LICENSE +22 -22
  3. package/README.md +94 -94
  4. package/THIRD_PARTY_NOTICES.md +140 -140
  5. package/bin/tokenusage.js +69 -69
  6. package/package.json +59 -59
  7. package/src/cli.js +146 -134
  8. package/src/commands/device-login.js +205 -205
  9. package/src/commands/diagnostics.js +38 -38
  10. package/src/commands/doctor.js +110 -110
  11. package/src/commands/init.js +2484 -2436
  12. package/src/commands/pause.js +77 -0
  13. package/src/commands/sessions.js +29 -29
  14. package/src/commands/status.js +1758 -1747
  15. package/src/commands/sync.js +8048 -7934
  16. package/src/commands/uninstall.js +322 -312
  17. package/src/lib/account-usage-dedup.js +267 -267
  18. package/src/lib/antigravity-paths.js +48 -48
  19. package/src/lib/ark-agent-plan-limits.js +438 -438
  20. package/src/lib/ark-coding-plan-limits.js +537 -537
  21. package/src/lib/async-queue-reader.js +138 -138
  22. package/src/lib/atomic-json.js +27 -27
  23. package/src/lib/bearer-token.js +11 -11
  24. package/src/lib/categorizer-utils.js +232 -232
  25. package/src/lib/claude-categorizer.js +1343 -1343
  26. package/src/lib/claude-config.js +279 -279
  27. package/src/lib/claude-user-identity.js +56 -56
  28. package/src/lib/cli-ui.js +179 -179
  29. package/src/lib/cloud-account.js +541 -541
  30. package/src/lib/cloud-device-token.js +141 -141
  31. package/src/lib/cloud-sync-prefs.js +14 -14
  32. package/src/lib/cloud-usage-reset.js +115 -115
  33. package/src/lib/codex-config.js +595 -595
  34. package/src/lib/codex-context-breakdown.js +806 -806
  35. package/src/lib/codex-model-attribution.js +128 -128
  36. package/src/lib/codex-rollout-parser.js +1471 -1471
  37. package/src/lib/codex-service-tier.js +49 -49
  38. package/src/lib/codex-token-refresh.js +140 -140
  39. package/src/lib/codex-token-usage.js +195 -195
  40. package/src/lib/codex-usage-record.js +195 -195
  41. package/src/lib/collection-pause.js +77 -0
  42. package/src/lib/command-runner.js +313 -313
  43. package/src/lib/commandcode-limits.js +317 -317
  44. package/src/lib/context-health.js +124 -124
  45. package/src/lib/cursor-config.js +605 -605
  46. package/src/lib/cursor-store.js +1918 -1918
  47. package/src/lib/debug-flags.js +7 -7
  48. package/src/lib/devin-limits.js +249 -249
  49. package/src/lib/devin-usage.js +212 -212
  50. package/src/lib/diagnostics.js +383 -383
  51. package/src/lib/doctor.js +385 -385
  52. package/src/lib/dumate.js +95 -95
  53. package/src/lib/fs.js +455 -455
  54. package/src/lib/function-url.js +14 -14
  55. package/src/lib/gemini-config.js +291 -291
  56. package/src/lib/git-outcomes.js +243 -243
  57. package/src/lib/grok-context-breakdown.js +890 -890
  58. package/src/lib/grok-hook.js +360 -360
  59. package/src/lib/grok-limits.js +865 -865
  60. package/src/lib/grok-usage.js +98 -98
  61. package/src/lib/heatmap-compact.js +114 -114
  62. package/src/lib/ingest-sanitize.js +41 -41
  63. package/src/lib/init-flow.js +42 -42
  64. package/src/lib/install-resolver.js +170 -170
  65. package/src/lib/jsonl-lines.js +134 -134
  66. package/src/lib/kimi-model-repair.js +173 -173
  67. package/src/lib/kimi-profile.js +61 -61
  68. package/src/lib/kimi-session.js +216 -216
  69. package/src/lib/local-api.js +3588 -3588
  70. package/src/lib/machine-id.js +238 -238
  71. package/src/lib/multi-install-parser.js +113 -113
  72. package/src/lib/notify-command.js +38 -38
  73. package/src/lib/omp-hook.js +589 -589
  74. package/src/lib/openclaw-cli.js +104 -104
  75. package/src/lib/openclaw-hook.js +375 -375
  76. package/src/lib/openclaw-session-plugin.js +560 -560
  77. package/src/lib/opencode-config.js +121 -121
  78. package/src/lib/opencode-go-limits.js +807 -807
  79. package/src/lib/outcomes-engine.js +253 -253
  80. package/src/lib/passive-mode.js +219 -219
  81. package/src/lib/pet-packages.js +722 -722
  82. package/src/lib/pricing/curated-overrides.json +822 -822
  83. package/src/lib/pricing/index.js +379 -379
  84. package/src/lib/pricing/litellm-fetcher.js +172 -172
  85. package/src/lib/pricing/matcher.js +456 -456
  86. package/src/lib/pricing/seed-snapshot.json +1 -1
  87. package/src/lib/progress.js +76 -76
  88. package/src/lib/project-usage-purge.js +117 -117
  89. package/src/lib/prompt.js +24 -24
  90. package/src/lib/provider-status.js +104 -104
  91. package/src/lib/proxy-env.js +489 -489
  92. package/src/lib/proxy-settings.js +163 -163
  93. package/src/lib/qoder-cn-cli-limits.js +119 -119
  94. package/src/lib/qoder-limits.js +880 -880
  95. package/src/lib/quiet-warnings.js +26 -26
  96. package/src/lib/rollout.js +26005 -25966
  97. package/src/lib/runtime-config.js +9 -4
  98. package/src/lib/scan-roots.js +277 -277
  99. package/src/lib/scheduled-task.js +145 -0
  100. package/src/lib/sentry.js +231 -231
  101. package/src/lib/session-analytics.js +2972 -2972
  102. package/src/lib/session-performance.js +237 -237
  103. package/src/lib/session-upload.js +379 -379
  104. package/src/lib/skill-usage.js +267 -267
  105. package/src/lib/skills-manager.js +1591 -1591
  106. package/src/lib/source-metadata.js +48 -48
  107. package/src/lib/sqlite-reader.js +215 -215
  108. package/src/lib/star-cta.js +73 -73
  109. package/src/lib/subscription-manager.js +293 -293
  110. package/src/lib/subscriptions.js +508 -508
  111. package/src/lib/sync-report.js +138 -0
  112. package/src/lib/telemetry.js +193 -193
  113. package/src/lib/tracker-paths.js +16 -16
  114. package/src/lib/trae-cn-config.js +548 -548
  115. package/src/lib/trae-db.js +127 -127
  116. package/src/lib/trae-snapshot.js +230 -230
  117. package/src/lib/trae-sqlite.js +143 -143
  118. package/src/lib/trae-usage.js +121 -121
  119. package/src/lib/upload-queue.js +134 -134
  120. package/src/lib/upload-throttle.js +171 -171
  121. package/src/lib/usage-limits.js +4552 -4552
  122. package/src/lib/wrapped-aggregator.js +236 -236
  123. package/src/lib/wsl-probe.js +281 -281
  124. package/src/lib/zcode-limits.js +1172 -1172
  125. package/src/lib/zcode-reset-credits.js +66 -66
  126. package/test/audit-fixes.test.js +200 -0
  127. package/test/cli-smoke.test.js +53 -53
  128. package/test/collection-controls.test.js +181 -0
  129. package/test/ingest-sanitize.test.js +162 -162
  130. package/test/quiet-warnings.test.js +53 -53
  131. package/test/session-upload.test.js +427 -427
@@ -1,317 +1,317 @@
1
- // CommandCode subscription usage limits.
2
- //
3
- // Data source (authoritative, mirrors the CLI's own `/usage` overlay in
4
- // command-code 1.49.1):
5
- //
6
- // GET https://api.commandcode.ai/alpha/whoami?limits=1
7
- // GET https://api.commandcode.ai/alpha/billing/credits[?orgId=...]
8
- // GET https://api.commandcode.ai/alpha/billing/subscriptions[?orgId=...]
9
- //
10
- // with `Authorization: Bearer <apiKey>`. The credits payload carries
11
- // `windowLimits: { limited, fiveHour: { used, cap, resetAt }, weekly: {...} }`
12
- // (resetAt is epoch milliseconds) plus a `credits` balance object; the
13
- // subscription payload carries `{ data: { planId, status, ... } }`.
14
- //
15
- // Auth resolution mirrors the CLI: `COMMAND_CODE_API_KEY` wins, otherwise the
16
- // `apiKey` field of `~/.commandcode/auth.json` (prod; written 0600 by
17
- // `cmd login`, never edited by hand). No key -> `{ configured: false }` so the
18
- // Limits panel hides the section instead of erroring.
19
- //
20
- // The API exposes 5h + weekly rolling caps; extra pay-as-you-go credits
21
- // bypass the caps server-side, so the reported used/cap needs no adjustment.
22
-
23
- const fs = require("node:fs");
24
- const path = require("node:path");
25
-
26
- const COMMANDCODE_API_BASE_URL = "https://api.commandcode.ai";
27
- const COMMANDCODE_API_KEY_ENV = "COMMAND_CODE_API_KEY";
28
- const COMMANDCODE_AUTH_DIRNAME = ".commandcode";
29
- const COMMANDCODE_AUTH_FILENAME = "auth.json";
30
-
31
- // Request timeouts are enforced by the caller: usage-limits.js passes a
32
- // withFetchTimeout-wrapped fetchImpl (per-request AbortSignal timeout), so this
33
- // module takes no timeout of its own.
34
-
35
- // Rolling window lengths are plan-independent and documented
36
- // (https://commandcode.ai/docs/resources/usage-limits): 5h + 7d.
37
- const COMMANDCODE_SESSION_WINDOW_SECONDS = 5 * 60 * 60;
38
- const COMMANDCODE_WEEKLY_WINDOW_SECONDS = 7 * 24 * 60 * 60;
39
-
40
- function isNonEmptyString(value) {
41
- return typeof value === "string" && value.trim().length > 0;
42
- }
43
-
44
- // Explicit `home`/env HOME only — never os.homedir() — so a synthetic test env
45
- // (no home, no HOME) discovers nothing and tests stay isolated from the
46
- // developer's real ~/.commandcode (cf. resolveOpencodeDataDir).
47
- function resolveCommandcodeHome({ home, env = process.env } = {}) {
48
- if (isNonEmptyString(home)) return home.trim();
49
- const envHome = env && typeof env === "object" ? env.HOME : null;
50
- if (isNonEmptyString(envHome)) return envHome.trim();
51
- return null;
52
- }
53
-
54
- function resolveCommandcodeAuthPath({ home, env = process.env } = {}) {
55
- const dir = resolveCommandcodeHome({ home, env });
56
- if (!dir) return null;
57
- return path.join(dir, COMMANDCODE_AUTH_DIRNAME, COMMANDCODE_AUTH_FILENAME);
58
- }
59
-
60
- function readCommandcodeApiKey({ home, env = process.env } = {}) {
61
- const fromEnv =
62
- env && typeof env === "object" ? env[COMMANDCODE_API_KEY_ENV] : null;
63
- if (isNonEmptyString(fromEnv)) return fromEnv.trim();
64
- const authPath = resolveCommandcodeAuthPath({ home, env });
65
- if (!authPath) return null;
66
- let raw;
67
- try {
68
- raw = fs.readFileSync(authPath, "utf8");
69
- } catch {
70
- return null;
71
- }
72
- let parsed;
73
- try {
74
- parsed = JSON.parse(raw);
75
- } catch {
76
- return null;
77
- }
78
- return isNonEmptyString(parsed?.apiKey) ? parsed.apiKey.trim() : null;
79
- }
80
-
81
- function normalizeResetAt(value) {
82
- if (value === null || value === undefined || value === "") return null;
83
- if (
84
- typeof value === "number" ||
85
- /^\d+(?:\.\d+)?$/.test(String(value).trim())
86
- ) {
87
- const raw = Number(value);
88
- if (!Number.isFinite(raw) || raw <= 0) return null;
89
- const milliseconds = raw > 10_000_000_000 ? raw : raw * 1000;
90
- const date = new Date(milliseconds);
91
- return Number.isFinite(date.getTime()) ? date.toISOString() : null;
92
- }
93
- const timestamp = Date.parse(String(value));
94
- return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : null;
95
- }
96
-
97
- function clampPercent(value) {
98
- if (value === null || value === undefined || value === "") return null;
99
- const n = Number(value);
100
- if (!Number.isFinite(n)) return null;
101
- if (n <= 0) return 0;
102
- if (n >= 100) return 100;
103
- return n;
104
- }
105
-
106
- function buildWindow({ usedPercent, resetAt, windowSeconds = null }) {
107
- const pct = clampPercent(usedPercent);
108
- if (pct === null) return null;
109
- const window = {
110
- used_percent: pct,
111
- reset_at: typeof resetAt === "string" && resetAt ? resetAt : null,
112
- };
113
- if (Number.isFinite(windowSeconds) && windowSeconds > 0) {
114
- window.limit_window_seconds = windowSeconds;
115
- }
116
- return window;
117
- }
118
-
119
- // Upstream window rows are `{ used, cap, resetAt }` (epoch ms). Tolerate the
120
- // snake_case spellings other providers use so a server rename stays a miss on
121
- // one window, not a crash.
122
- function normalizeCommandcodeWindow(raw, windowSeconds) {
123
- if (!raw || typeof raw !== "object") return null;
124
- // Missing or malformed usage is unknown, not an unused (0%) window.
125
- const numeric = (value) => typeof value === "number"
126
- || (typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value)));
127
- if (!numeric(raw.used) || !numeric(raw.cap ?? raw.total ?? raw.limit)) return null;
128
- const used = Number(raw.used);
129
- const cap = Number(raw.cap ?? raw.total ?? raw.limit);
130
- if (!Number.isFinite(used) || !Number.isFinite(cap) || cap <= 0 || used < 0)
131
- return null;
132
- return buildWindow({
133
- usedPercent: (used / cap) * 100,
134
- resetAt: normalizeResetAt(raw.resetAt ?? raw.reset_at ?? raw.reset),
135
- windowSeconds,
136
- });
137
- }
138
-
139
- // Plan tiers (longest prefix first, mirroring the CLI's own getPlanInfo
140
- // matching in command-code). Unknown ids -> null, so the Limits panel renders
141
- // the bare "Command Code" brand (cf. Kimi/Grok — a raw id like
142
- // `individual-pro-v1` reads as garbage).
143
- const COMMANDCODE_PLAN_TIERS = [
144
- ["individual-pro-v1", "Pro"],
145
- ["individual-provider", "Provider"],
146
- ["individual-goat", "GOAT"],
147
- ["individual-go", "Go"],
148
- ["individual-pro", "Pro"],
149
- ["individual-max", "Max"],
150
- ["individual-ultra", "Ultra"],
151
- ["teams-pro", "Teams Pro"],
152
- ];
153
-
154
- function deriveCommandcodePlanLabel(rawPlanId) {
155
- if (!isNonEmptyString(rawPlanId)) return null;
156
- const normalized = rawPlanId.trim().toLowerCase().replace(/_/g, "-");
157
- for (const [prefix, label] of COMMANDCODE_PLAN_TIERS) {
158
- if (normalized.startsWith(prefix)) return label;
159
- }
160
- return null;
161
- }
162
-
163
- function normalizeCommandcodeWindowLimits(windowLimits) {
164
- if (!windowLimits || typeof windowLimits !== "object") return null;
165
- const fiveHour = normalizeCommandcodeWindow(
166
- windowLimits.fiveHour ?? windowLimits.five_hour,
167
- COMMANDCODE_SESSION_WINDOW_SECONDS,
168
- );
169
- const weekly = normalizeCommandcodeWindow(
170
- windowLimits.weekly,
171
- COMMANDCODE_WEEKLY_WINDOW_SECONDS,
172
- );
173
- if (!fiveHour && !weekly) return null;
174
-
175
- return { fiveHour, weekly };
176
- }
177
-
178
- // The Bearer apiKey travels on every request, so the origin must be https.
179
- // Plain http is accepted for loopback only (local staging/dev servers).
180
- function resolveCommandcodeOrigin(baseUrl) {
181
- const origin = String(baseUrl || COMMANDCODE_API_BASE_URL).replace(
182
- /\/+$/,
183
- "",
184
- );
185
- let parsed;
186
- try {
187
- parsed = new URL(origin);
188
- } catch {
189
- throw new Error("CommandCode API base URL is invalid.");
190
- }
191
- const loopback = /^(localhost|127\.\d+\.\d+\.\d+|\[::1\])$/i.test(
192
- parsed.hostname,
193
- );
194
- if (parsed.protocol !== "https:" && !loopback) {
195
- throw new Error(
196
- "CommandCode API base URL must use https (http is loopback-only).",
197
- );
198
- }
199
- return origin;
200
- }
201
-
202
- function commandcodeHeaders(apiKey) {
203
- return {
204
- Accept: "application/json",
205
- Authorization: `Bearer ${apiKey}`,
206
- };
207
- }
208
-
209
- async function fetchCommandcodeJson({ url, apiKey, fetchImpl, label }) {
210
- let response;
211
- try {
212
- response = await fetchImpl(url, { headers: commandcodeHeaders(apiKey) });
213
- } catch (error) {
214
- throw new Error(
215
- `CommandCode ${label} request failed: ${error?.message || "network error"}`,
216
- );
217
- }
218
- if (response?.status === 401 || response?.status === 403) {
219
- const error = new Error(
220
- "CommandCode token expired — run `cmd login` (macOS/Linux) or `cmdc auth login` (Windows) to refresh.",
221
- );
222
- error.code = "AUTH_EXPIRED";
223
- throw error;
224
- }
225
- if (!response?.ok) {
226
- throw new Error(
227
- `CommandCode ${label} request failed (HTTP ${response?.status ?? "?"}).`,
228
- );
229
- }
230
- try {
231
- return await response.json();
232
- } catch {
233
- throw new Error(`${label} response was not JSON.`);
234
- }
235
- }
236
-
237
- function withOrgParam(route, orgId) {
238
- if (orgId === null || orgId === undefined || String(orgId).trim() === "")
239
- return route;
240
- return `${route}?orgId=${encodeURIComponent(String(orgId).trim())}`;
241
- }
242
-
243
- // Returns `{ configured: false }` without credentials, or the normalized limits
244
- // object on success. Auth expiry throws with `code: "AUTH_EXPIRED"` and every
245
- // other transport/schema failure throws a readable Error — the aggregator in
246
- // usage-limits.js converts both into the panel row.
247
- async function fetchCommandcodeLimits({
248
- home,
249
- env = process.env,
250
- fetchImpl = fetch,
251
- baseUrl = COMMANDCODE_API_BASE_URL,
252
- } = {}) {
253
- const apiKey = readCommandcodeApiKey({ home, env });
254
- if (!apiKey) return { configured: false };
255
-
256
- const origin = resolveCommandcodeOrigin(baseUrl);
257
- const whoami = await fetchCommandcodeJson({
258
- url: `${origin}/alpha/whoami?limits=1`,
259
- apiKey,
260
- fetchImpl,
261
- label: "account lookup",
262
- });
263
- const orgId = whoami?.data?.org?.id ?? whoami?.org?.id ?? null;
264
-
265
- const [creditsBody, subscriptionBody] = await Promise.all([
266
- fetchCommandcodeJson({
267
- url: `${origin}${withOrgParam("/alpha/billing/credits", orgId)}`,
268
- apiKey,
269
- fetchImpl,
270
- label: "credits lookup",
271
- }),
272
- fetchCommandcodeJson({
273
- url: `${origin}${withOrgParam("/alpha/billing/subscriptions", orgId)}`,
274
- apiKey,
275
- fetchImpl,
276
- label: "subscription lookup",
277
- }),
278
- ]);
279
-
280
- const windows = normalizeCommandcodeWindowLimits(creditsBody?.windowLimits);
281
- if (!windows) {
282
- throw new Error("CommandCode credits response is missing windowLimits.");
283
- }
284
- const subscription = subscriptionBody?.data ?? subscriptionBody ?? null;
285
- const planId = isNonEmptyString(subscription?.planId)
286
- ? subscription.planId.trim()
287
- : null;
288
-
289
- return {
290
- configured: true,
291
- error: null,
292
- plan_label: deriveCommandcodePlanLabel(planId),
293
- subscription_status: isNonEmptyString(subscription?.status)
294
- ? subscription.status.trim()
295
- : null,
296
- primary_window: windows.fiveHour,
297
- secondary_window: windows.weekly,
298
- stale: false,
299
- cached_at: new Date().toISOString(),
300
- };
301
- }
302
-
303
- module.exports = {
304
- COMMANDCODE_API_BASE_URL,
305
- COMMANDCODE_API_KEY_ENV,
306
- COMMANDCODE_SESSION_WINDOW_SECONDS,
307
- COMMANDCODE_WEEKLY_WINDOW_SECONDS,
308
- resolveCommandcodeHome,
309
- resolveCommandcodeAuthPath,
310
- readCommandcodeApiKey,
311
- deriveCommandcodePlanLabel,
312
- normalizeResetAt,
313
- normalizeCommandcodeWindow,
314
- normalizeCommandcodeWindowLimits,
315
- resolveCommandcodeOrigin,
316
- fetchCommandcodeLimits,
317
- };
1
+ // CommandCode subscription usage limits.
2
+ //
3
+ // Data source (authoritative, mirrors the CLI's own `/usage` overlay in
4
+ // command-code 1.49.1):
5
+ //
6
+ // GET https://api.commandcode.ai/alpha/whoami?limits=1
7
+ // GET https://api.commandcode.ai/alpha/billing/credits[?orgId=...]
8
+ // GET https://api.commandcode.ai/alpha/billing/subscriptions[?orgId=...]
9
+ //
10
+ // with `Authorization: Bearer <apiKey>`. The credits payload carries
11
+ // `windowLimits: { limited, fiveHour: { used, cap, resetAt }, weekly: {...} }`
12
+ // (resetAt is epoch milliseconds) plus a `credits` balance object; the
13
+ // subscription payload carries `{ data: { planId, status, ... } }`.
14
+ //
15
+ // Auth resolution mirrors the CLI: `COMMAND_CODE_API_KEY` wins, otherwise the
16
+ // `apiKey` field of `~/.commandcode/auth.json` (prod; written 0600 by
17
+ // `cmd login`, never edited by hand). No key -> `{ configured: false }` so the
18
+ // Limits panel hides the section instead of erroring.
19
+ //
20
+ // The API exposes 5h + weekly rolling caps; extra pay-as-you-go credits
21
+ // bypass the caps server-side, so the reported used/cap needs no adjustment.
22
+
23
+ const fs = require("node:fs");
24
+ const path = require("node:path");
25
+
26
+ const COMMANDCODE_API_BASE_URL = "https://api.commandcode.ai";
27
+ const COMMANDCODE_API_KEY_ENV = "COMMAND_CODE_API_KEY";
28
+ const COMMANDCODE_AUTH_DIRNAME = ".commandcode";
29
+ const COMMANDCODE_AUTH_FILENAME = "auth.json";
30
+
31
+ // Request timeouts are enforced by the caller: usage-limits.js passes a
32
+ // withFetchTimeout-wrapped fetchImpl (per-request AbortSignal timeout), so this
33
+ // module takes no timeout of its own.
34
+
35
+ // Rolling window lengths are plan-independent and documented
36
+ // (https://commandcode.ai/docs/resources/usage-limits): 5h + 7d.
37
+ const COMMANDCODE_SESSION_WINDOW_SECONDS = 5 * 60 * 60;
38
+ const COMMANDCODE_WEEKLY_WINDOW_SECONDS = 7 * 24 * 60 * 60;
39
+
40
+ function isNonEmptyString(value) {
41
+ return typeof value === "string" && value.trim().length > 0;
42
+ }
43
+
44
+ // Explicit `home`/env HOME only — never os.homedir() — so a synthetic test env
45
+ // (no home, no HOME) discovers nothing and tests stay isolated from the
46
+ // developer's real ~/.commandcode (cf. resolveOpencodeDataDir).
47
+ function resolveCommandcodeHome({ home, env = process.env } = {}) {
48
+ if (isNonEmptyString(home)) return home.trim();
49
+ const envHome = env && typeof env === "object" ? env.HOME : null;
50
+ if (isNonEmptyString(envHome)) return envHome.trim();
51
+ return null;
52
+ }
53
+
54
+ function resolveCommandcodeAuthPath({ home, env = process.env } = {}) {
55
+ const dir = resolveCommandcodeHome({ home, env });
56
+ if (!dir) return null;
57
+ return path.join(dir, COMMANDCODE_AUTH_DIRNAME, COMMANDCODE_AUTH_FILENAME);
58
+ }
59
+
60
+ function readCommandcodeApiKey({ home, env = process.env } = {}) {
61
+ const fromEnv =
62
+ env && typeof env === "object" ? env[COMMANDCODE_API_KEY_ENV] : null;
63
+ if (isNonEmptyString(fromEnv)) return fromEnv.trim();
64
+ const authPath = resolveCommandcodeAuthPath({ home, env });
65
+ if (!authPath) return null;
66
+ let raw;
67
+ try {
68
+ raw = fs.readFileSync(authPath, "utf8");
69
+ } catch {
70
+ return null;
71
+ }
72
+ let parsed;
73
+ try {
74
+ parsed = JSON.parse(raw);
75
+ } catch {
76
+ return null;
77
+ }
78
+ return isNonEmptyString(parsed?.apiKey) ? parsed.apiKey.trim() : null;
79
+ }
80
+
81
+ function normalizeResetAt(value) {
82
+ if (value === null || value === undefined || value === "") return null;
83
+ if (
84
+ typeof value === "number" ||
85
+ /^\d+(?:\.\d+)?$/.test(String(value).trim())
86
+ ) {
87
+ const raw = Number(value);
88
+ if (!Number.isFinite(raw) || raw <= 0) return null;
89
+ const milliseconds = raw > 10_000_000_000 ? raw : raw * 1000;
90
+ const date = new Date(milliseconds);
91
+ return Number.isFinite(date.getTime()) ? date.toISOString() : null;
92
+ }
93
+ const timestamp = Date.parse(String(value));
94
+ return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : null;
95
+ }
96
+
97
+ function clampPercent(value) {
98
+ if (value === null || value === undefined || value === "") return null;
99
+ const n = Number(value);
100
+ if (!Number.isFinite(n)) return null;
101
+ if (n <= 0) return 0;
102
+ if (n >= 100) return 100;
103
+ return n;
104
+ }
105
+
106
+ function buildWindow({ usedPercent, resetAt, windowSeconds = null }) {
107
+ const pct = clampPercent(usedPercent);
108
+ if (pct === null) return null;
109
+ const window = {
110
+ used_percent: pct,
111
+ reset_at: typeof resetAt === "string" && resetAt ? resetAt : null,
112
+ };
113
+ if (Number.isFinite(windowSeconds) && windowSeconds > 0) {
114
+ window.limit_window_seconds = windowSeconds;
115
+ }
116
+ return window;
117
+ }
118
+
119
+ // Upstream window rows are `{ used, cap, resetAt }` (epoch ms). Tolerate the
120
+ // snake_case spellings other providers use so a server rename stays a miss on
121
+ // one window, not a crash.
122
+ function normalizeCommandcodeWindow(raw, windowSeconds) {
123
+ if (!raw || typeof raw !== "object") return null;
124
+ // Missing or malformed usage is unknown, not an unused (0%) window.
125
+ const numeric = (value) => typeof value === "number"
126
+ || (typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value)));
127
+ if (!numeric(raw.used) || !numeric(raw.cap ?? raw.total ?? raw.limit)) return null;
128
+ const used = Number(raw.used);
129
+ const cap = Number(raw.cap ?? raw.total ?? raw.limit);
130
+ if (!Number.isFinite(used) || !Number.isFinite(cap) || cap <= 0 || used < 0)
131
+ return null;
132
+ return buildWindow({
133
+ usedPercent: (used / cap) * 100,
134
+ resetAt: normalizeResetAt(raw.resetAt ?? raw.reset_at ?? raw.reset),
135
+ windowSeconds,
136
+ });
137
+ }
138
+
139
+ // Plan tiers (longest prefix first, mirroring the CLI's own getPlanInfo
140
+ // matching in command-code). Unknown ids -> null, so the Limits panel renders
141
+ // the bare "Command Code" brand (cf. Kimi/Grok — a raw id like
142
+ // `individual-pro-v1` reads as garbage).
143
+ const COMMANDCODE_PLAN_TIERS = [
144
+ ["individual-pro-v1", "Pro"],
145
+ ["individual-provider", "Provider"],
146
+ ["individual-goat", "GOAT"],
147
+ ["individual-go", "Go"],
148
+ ["individual-pro", "Pro"],
149
+ ["individual-max", "Max"],
150
+ ["individual-ultra", "Ultra"],
151
+ ["teams-pro", "Teams Pro"],
152
+ ];
153
+
154
+ function deriveCommandcodePlanLabel(rawPlanId) {
155
+ if (!isNonEmptyString(rawPlanId)) return null;
156
+ const normalized = rawPlanId.trim().toLowerCase().replace(/_/g, "-");
157
+ for (const [prefix, label] of COMMANDCODE_PLAN_TIERS) {
158
+ if (normalized.startsWith(prefix)) return label;
159
+ }
160
+ return null;
161
+ }
162
+
163
+ function normalizeCommandcodeWindowLimits(windowLimits) {
164
+ if (!windowLimits || typeof windowLimits !== "object") return null;
165
+ const fiveHour = normalizeCommandcodeWindow(
166
+ windowLimits.fiveHour ?? windowLimits.five_hour,
167
+ COMMANDCODE_SESSION_WINDOW_SECONDS,
168
+ );
169
+ const weekly = normalizeCommandcodeWindow(
170
+ windowLimits.weekly,
171
+ COMMANDCODE_WEEKLY_WINDOW_SECONDS,
172
+ );
173
+ if (!fiveHour && !weekly) return null;
174
+
175
+ return { fiveHour, weekly };
176
+ }
177
+
178
+ // The Bearer apiKey travels on every request, so the origin must be https.
179
+ // Plain http is accepted for loopback only (local staging/dev servers).
180
+ function resolveCommandcodeOrigin(baseUrl) {
181
+ const origin = String(baseUrl || COMMANDCODE_API_BASE_URL).replace(
182
+ /\/+$/,
183
+ "",
184
+ );
185
+ let parsed;
186
+ try {
187
+ parsed = new URL(origin);
188
+ } catch {
189
+ throw new Error("CommandCode API base URL is invalid.");
190
+ }
191
+ const loopback = /^(localhost|127\.\d+\.\d+\.\d+|\[::1\])$/i.test(
192
+ parsed.hostname,
193
+ );
194
+ if (parsed.protocol !== "https:" && !loopback) {
195
+ throw new Error(
196
+ "CommandCode API base URL must use https (http is loopback-only).",
197
+ );
198
+ }
199
+ return origin;
200
+ }
201
+
202
+ function commandcodeHeaders(apiKey) {
203
+ return {
204
+ Accept: "application/json",
205
+ Authorization: `Bearer ${apiKey}`,
206
+ };
207
+ }
208
+
209
+ async function fetchCommandcodeJson({ url, apiKey, fetchImpl, label }) {
210
+ let response;
211
+ try {
212
+ response = await fetchImpl(url, { headers: commandcodeHeaders(apiKey) });
213
+ } catch (error) {
214
+ throw new Error(
215
+ `CommandCode ${label} request failed: ${error?.message || "network error"}`,
216
+ );
217
+ }
218
+ if (response?.status === 401 || response?.status === 403) {
219
+ const error = new Error(
220
+ "CommandCode token expired — run `cmd login` (macOS/Linux) or `cmdc auth login` (Windows) to refresh.",
221
+ );
222
+ error.code = "AUTH_EXPIRED";
223
+ throw error;
224
+ }
225
+ if (!response?.ok) {
226
+ throw new Error(
227
+ `CommandCode ${label} request failed (HTTP ${response?.status ?? "?"}).`,
228
+ );
229
+ }
230
+ try {
231
+ return await response.json();
232
+ } catch {
233
+ throw new Error(`${label} response was not JSON.`);
234
+ }
235
+ }
236
+
237
+ function withOrgParam(route, orgId) {
238
+ if (orgId === null || orgId === undefined || String(orgId).trim() === "")
239
+ return route;
240
+ return `${route}?orgId=${encodeURIComponent(String(orgId).trim())}`;
241
+ }
242
+
243
+ // Returns `{ configured: false }` without credentials, or the normalized limits
244
+ // object on success. Auth expiry throws with `code: "AUTH_EXPIRED"` and every
245
+ // other transport/schema failure throws a readable Error — the aggregator in
246
+ // usage-limits.js converts both into the panel row.
247
+ async function fetchCommandcodeLimits({
248
+ home,
249
+ env = process.env,
250
+ fetchImpl = fetch,
251
+ baseUrl = COMMANDCODE_API_BASE_URL,
252
+ } = {}) {
253
+ const apiKey = readCommandcodeApiKey({ home, env });
254
+ if (!apiKey) return { configured: false };
255
+
256
+ const origin = resolveCommandcodeOrigin(baseUrl);
257
+ const whoami = await fetchCommandcodeJson({
258
+ url: `${origin}/alpha/whoami?limits=1`,
259
+ apiKey,
260
+ fetchImpl,
261
+ label: "account lookup",
262
+ });
263
+ const orgId = whoami?.data?.org?.id ?? whoami?.org?.id ?? null;
264
+
265
+ const [creditsBody, subscriptionBody] = await Promise.all([
266
+ fetchCommandcodeJson({
267
+ url: `${origin}${withOrgParam("/alpha/billing/credits", orgId)}`,
268
+ apiKey,
269
+ fetchImpl,
270
+ label: "credits lookup",
271
+ }),
272
+ fetchCommandcodeJson({
273
+ url: `${origin}${withOrgParam("/alpha/billing/subscriptions", orgId)}`,
274
+ apiKey,
275
+ fetchImpl,
276
+ label: "subscription lookup",
277
+ }),
278
+ ]);
279
+
280
+ const windows = normalizeCommandcodeWindowLimits(creditsBody?.windowLimits);
281
+ if (!windows) {
282
+ throw new Error("CommandCode credits response is missing windowLimits.");
283
+ }
284
+ const subscription = subscriptionBody?.data ?? subscriptionBody ?? null;
285
+ const planId = isNonEmptyString(subscription?.planId)
286
+ ? subscription.planId.trim()
287
+ : null;
288
+
289
+ return {
290
+ configured: true,
291
+ error: null,
292
+ plan_label: deriveCommandcodePlanLabel(planId),
293
+ subscription_status: isNonEmptyString(subscription?.status)
294
+ ? subscription.status.trim()
295
+ : null,
296
+ primary_window: windows.fiveHour,
297
+ secondary_window: windows.weekly,
298
+ stale: false,
299
+ cached_at: new Date().toISOString(),
300
+ };
301
+ }
302
+
303
+ module.exports = {
304
+ COMMANDCODE_API_BASE_URL,
305
+ COMMANDCODE_API_KEY_ENV,
306
+ COMMANDCODE_SESSION_WINDOW_SECONDS,
307
+ COMMANDCODE_WEEKLY_WINDOW_SECONDS,
308
+ resolveCommandcodeHome,
309
+ resolveCommandcodeAuthPath,
310
+ readCommandcodeApiKey,
311
+ deriveCommandcodePlanLabel,
312
+ normalizeResetAt,
313
+ normalizeCommandcodeWindow,
314
+ normalizeCommandcodeWindowLimits,
315
+ resolveCommandcodeOrigin,
316
+ fetchCommandcodeLimits,
317
+ };