tokenusage-cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +22 -0
  3. package/README.md +94 -0
  4. package/THIRD_PARTY_NOTICES.md +140 -0
  5. package/bin/tokenusage.js +69 -0
  6. package/package.json +59 -0
  7. package/src/cli.js +134 -0
  8. package/src/commands/device-login.js +205 -0
  9. package/src/commands/diagnostics.js +38 -0
  10. package/src/commands/doctor.js +110 -0
  11. package/src/commands/init.js +2436 -0
  12. package/src/commands/sessions.js +29 -0
  13. package/src/commands/status.js +1747 -0
  14. package/src/commands/sync.js +7934 -0
  15. package/src/commands/uninstall.js +312 -0
  16. package/src/lib/account-usage-dedup.js +267 -0
  17. package/src/lib/antigravity-paths.js +48 -0
  18. package/src/lib/ark-agent-plan-limits.js +438 -0
  19. package/src/lib/ark-coding-plan-limits.js +537 -0
  20. package/src/lib/async-queue-reader.js +138 -0
  21. package/src/lib/atomic-json.js +27 -0
  22. package/src/lib/bearer-token.js +11 -0
  23. package/src/lib/categorizer-utils.js +232 -0
  24. package/src/lib/claude-categorizer.js +1343 -0
  25. package/src/lib/claude-config.js +279 -0
  26. package/src/lib/claude-user-identity.js +56 -0
  27. package/src/lib/cli-ui.js +179 -0
  28. package/src/lib/cloud-account.js +541 -0
  29. package/src/lib/cloud-device-token.js +141 -0
  30. package/src/lib/cloud-sync-prefs.js +14 -0
  31. package/src/lib/cloud-usage-reset.js +115 -0
  32. package/src/lib/codex-config.js +595 -0
  33. package/src/lib/codex-context-breakdown.js +806 -0
  34. package/src/lib/codex-model-attribution.js +128 -0
  35. package/src/lib/codex-rollout-parser.js +1471 -0
  36. package/src/lib/codex-service-tier.js +49 -0
  37. package/src/lib/codex-token-refresh.js +140 -0
  38. package/src/lib/codex-token-usage.js +195 -0
  39. package/src/lib/codex-usage-record.js +195 -0
  40. package/src/lib/command-runner.js +313 -0
  41. package/src/lib/commandcode-limits.js +317 -0
  42. package/src/lib/context-health.js +124 -0
  43. package/src/lib/cursor-config.js +605 -0
  44. package/src/lib/cursor-store.js +1918 -0
  45. package/src/lib/debug-flags.js +7 -0
  46. package/src/lib/devin-limits.js +249 -0
  47. package/src/lib/devin-usage.js +212 -0
  48. package/src/lib/diagnostics.js +383 -0
  49. package/src/lib/doctor.js +385 -0
  50. package/src/lib/dumate.js +95 -0
  51. package/src/lib/fs.js +455 -0
  52. package/src/lib/function-url.js +14 -0
  53. package/src/lib/gemini-config.js +291 -0
  54. package/src/lib/git-outcomes.js +243 -0
  55. package/src/lib/grok-context-breakdown.js +890 -0
  56. package/src/lib/grok-hook.js +360 -0
  57. package/src/lib/grok-limits.js +865 -0
  58. package/src/lib/grok-usage.js +98 -0
  59. package/src/lib/heatmap-compact.js +114 -0
  60. package/src/lib/ingest-sanitize.js +41 -0
  61. package/src/lib/init-flow.js +42 -0
  62. package/src/lib/install-resolver.js +170 -0
  63. package/src/lib/jsonl-lines.js +134 -0
  64. package/src/lib/kimi-model-repair.js +173 -0
  65. package/src/lib/kimi-profile.js +61 -0
  66. package/src/lib/kimi-session.js +216 -0
  67. package/src/lib/local-api.js +3588 -0
  68. package/src/lib/machine-id.js +238 -0
  69. package/src/lib/multi-install-parser.js +113 -0
  70. package/src/lib/notify-command.js +38 -0
  71. package/src/lib/omp-hook.js +589 -0
  72. package/src/lib/openclaw-cli.js +104 -0
  73. package/src/lib/openclaw-hook.js +375 -0
  74. package/src/lib/openclaw-session-plugin.js +560 -0
  75. package/src/lib/opencode-config.js +121 -0
  76. package/src/lib/opencode-go-limits.js +807 -0
  77. package/src/lib/outcomes-engine.js +253 -0
  78. package/src/lib/passive-mode.js +219 -0
  79. package/src/lib/pet-packages.js +722 -0
  80. package/src/lib/pricing/curated-overrides.json +822 -0
  81. package/src/lib/pricing/index.js +379 -0
  82. package/src/lib/pricing/litellm-fetcher.js +172 -0
  83. package/src/lib/pricing/matcher.js +456 -0
  84. package/src/lib/pricing/seed-snapshot.json +1 -0
  85. package/src/lib/progress.js +76 -0
  86. package/src/lib/project-usage-purge.js +117 -0
  87. package/src/lib/prompt.js +24 -0
  88. package/src/lib/provider-status.js +104 -0
  89. package/src/lib/proxy-env.js +489 -0
  90. package/src/lib/proxy-settings.js +163 -0
  91. package/src/lib/qoder-cn-cli-limits.js +119 -0
  92. package/src/lib/qoder-limits.js +880 -0
  93. package/src/lib/quiet-warnings.js +26 -0
  94. package/src/lib/rollout.js +25966 -0
  95. package/src/lib/runtime-config.js +259 -0
  96. package/src/lib/scan-roots.js +277 -0
  97. package/src/lib/sentry.js +231 -0
  98. package/src/lib/session-analytics.js +2972 -0
  99. package/src/lib/session-performance.js +237 -0
  100. package/src/lib/session-upload.js +379 -0
  101. package/src/lib/skill-usage.js +267 -0
  102. package/src/lib/skills-manager.js +1591 -0
  103. package/src/lib/source-metadata.js +48 -0
  104. package/src/lib/sqlite-reader.js +215 -0
  105. package/src/lib/star-cta.js +73 -0
  106. package/src/lib/subscription-manager.js +293 -0
  107. package/src/lib/subscriptions.js +508 -0
  108. package/src/lib/telemetry.js +193 -0
  109. package/src/lib/tracker-paths.js +16 -0
  110. package/src/lib/trae-cn-config.js +548 -0
  111. package/src/lib/trae-db.js +127 -0
  112. package/src/lib/trae-snapshot.js +230 -0
  113. package/src/lib/trae-sqlite.js +143 -0
  114. package/src/lib/trae-usage.js +121 -0
  115. package/src/lib/upload-queue.js +134 -0
  116. package/src/lib/upload-throttle.js +171 -0
  117. package/src/lib/usage-limits.js +4552 -0
  118. package/src/lib/wrapped-aggregator.js +236 -0
  119. package/src/lib/wsl-probe.js +281 -0
  120. package/src/lib/zcode-limits.js +1172 -0
  121. package/src/lib/zcode-reset-credits.js +66 -0
  122. package/test/cli-smoke.test.js +53 -0
  123. package/test/ingest-sanitize.test.js +162 -0
  124. package/test/quiet-warnings.test.js +53 -0
  125. package/test/session-upload.test.js +427 -0
@@ -0,0 +1,313 @@
1
+ "use strict";
2
+
3
+ // Shared command runner for local-CLI limit providers.
4
+ //
5
+ // Extracted from usage-limits.js (which keeps a require of it) so
6
+ // ark-coding-plan-limits.js and future providers don't have to copy it.
7
+ // This is a superset of both former copies: the original's `completeWhen`
8
+ // early-settlement hook, plus the hardening that previously only lived in
9
+ // the ark copy — an abort `signal` wired into the spawn lifecycle, a
10
+ // `platform` override with `where.exe` discovery on native Windows, and a
11
+ // byte-capped maxBuffer for piped spawn output.
12
+
13
+ const cp = require("node:child_process");
14
+ const fs = require("node:fs");
15
+ const os = require("node:os");
16
+ const path = require("node:path");
17
+
18
+ /** Run a command without a shell by default, optionally piping options.input to stdin. */
19
+ function runCommand(commandRunner, command, args, options = {}) {
20
+ const merged = {
21
+ encoding: "utf8",
22
+ maxBuffer: 10 * 1024 * 1024,
23
+ useShell: false,
24
+ ...options,
25
+ };
26
+ if (typeof commandRunner === "function") {
27
+ return Promise.resolve(commandRunner(command, args, merged));
28
+ }
29
+
30
+ const {
31
+ timeout,
32
+ maxBuffer,
33
+ input,
34
+ completeWhen,
35
+ completionGraceMs = 250,
36
+ killProcessGroup = false,
37
+ platform = process.platform,
38
+ signal,
39
+ useShell = false,
40
+ ...spawnOptions
41
+ } = merged;
42
+ return new Promise((resolve) => {
43
+ if (signal?.aborted) {
44
+ const error = new Error(`spawn ${command} aborted`);
45
+ error.name = "AbortError";
46
+ resolve({ status: null, stdout: "", stderr: "", error });
47
+ return;
48
+ }
49
+
50
+ const useProcessGroup = killProcessGroup && platform !== "win32";
51
+ // `useShell` is opt-in per call site. It exists for npm's Windows .cmd
52
+ // shims, which Node's spawn cannot execute directly — but shell
53
+ // execution means cmd.exe re-parses the joined command line, so any
54
+ // argument carrying shell metacharacters (e.g. a powershell -Command
55
+ // script with `|`) would be split. Default false keeps direct spawns,
56
+ // which is what every pre-existing usage-limits call site expects.
57
+ // Under shell execution quote the command unconditionally: cmd.exe
58
+ // metacharacters are not limited to whitespace (`C:\Users\a&b\...`
59
+ // has none yet splits at `&`), and Windows account names allow them.
60
+ const shellCommand = useShell && !command.startsWith('"')
61
+ ? `"${command}"`
62
+ : command;
63
+ let child;
64
+ try {
65
+ child = cp.spawn(shellCommand, args, {
66
+ ...spawnOptions,
67
+ detached: useProcessGroup || spawnOptions.detached,
68
+ shell: useShell,
69
+ stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
70
+ });
71
+ } catch (error) {
72
+ resolve({ status: null, stdout: "", stderr: "", error });
73
+ return;
74
+ }
75
+
76
+ let stdout = "";
77
+ let stderr = "";
78
+ let outputBytes = 0;
79
+ let settled = false;
80
+ let timedOut = false;
81
+ let timer = null;
82
+ let hardTimer = null;
83
+ let completionTimer = null;
84
+ let abortListener = null;
85
+
86
+ const settle = ({ status = null, error = null } = {}) => {
87
+ if (settled) return;
88
+ settled = true;
89
+ if (timer) clearTimeout(timer);
90
+ if (hardTimer) clearTimeout(hardTimer);
91
+ if (completionTimer) clearTimeout(completionTimer);
92
+ if (abortListener) signal?.removeEventListener("abort", abortListener);
93
+ let finalError = error;
94
+ if (!finalError && timedOut) {
95
+ finalError = new Error(`spawn ${command} ETIMEDOUT`);
96
+ finalError.code = "ETIMEDOUT";
97
+ }
98
+ const result = { status, stdout, stderr };
99
+ if (finalError) result.error = finalError;
100
+ resolve(result);
101
+ };
102
+
103
+ const signalChild = (killSignal) => {
104
+ try {
105
+ if (useProcessGroup && Number.isInteger(child.pid)) {
106
+ process.kill(-child.pid, killSignal);
107
+ } else {
108
+ child.kill(killSignal);
109
+ }
110
+ } catch (_error) {}
111
+ };
112
+
113
+ const stopChild = ({ timeoutExpired = false } = {}) => {
114
+ if (settled) return;
115
+ if (timeoutExpired) timedOut = true;
116
+ signalChild("SIGTERM");
117
+ // A CLI may leave descendants or inherited stdio alive after SIGTERM.
118
+ // Escalate after a short grace period and settle even if close never fires.
119
+ hardTimer = setTimeout(() => {
120
+ signalChild("SIGKILL");
121
+ settle({ status: null });
122
+ }, 1000);
123
+ if (typeof hardTimer.unref === "function") hardTimer.unref();
124
+ };
125
+
126
+ const scheduleCompletion = () => {
127
+ if (typeof completeWhen !== "function" || settled) return;
128
+ let complete = false;
129
+ try {
130
+ complete = Boolean(completeWhen(stdout, stderr));
131
+ } catch (_error) {}
132
+ if (!complete) return;
133
+ if (completionTimer) clearTimeout(completionTimer);
134
+ completionTimer = setTimeout(
135
+ () => stopChild(),
136
+ Math.max(0, Number(completionGraceMs) || 0),
137
+ );
138
+ };
139
+
140
+ const appendOutput = (key, chunk) => {
141
+ if (settled) return;
142
+ if (key === "stdout") stdout += chunk;
143
+ else stderr += chunk;
144
+ outputBytes += Buffer.byteLength(chunk, "utf8");
145
+ // Unlike exec/execFile, spawn does not apply a maxBuffer guard to piped
146
+ // streams. Enforce the combined byte cap here so a verbose CLI cannot
147
+ // grow this process without bound.
148
+ if (outputBytes > maxBuffer) {
149
+ const error = new Error(`spawn ${command} maxBuffer length exceeded`);
150
+ error.code = "ERR_CHILD_PROCESS_STDIO_MAXBUFFER";
151
+ signalChild("SIGKILL");
152
+ settle({ status: null, error });
153
+ return;
154
+ }
155
+ scheduleCompletion();
156
+ };
157
+
158
+ child.stdout?.setEncoding("utf8");
159
+ child.stderr?.setEncoding("utf8");
160
+ child.stdout?.on("data", (chunk) => appendOutput("stdout", chunk));
161
+ child.stderr?.on("data", (chunk) => appendOutput("stderr", chunk));
162
+ child.on("error", (error) => settle({ status: null, error }));
163
+ child.on("close", (code) => settle({ status: timedOut ? null : code }));
164
+
165
+ if (signal) {
166
+ abortListener = () => stopChild();
167
+ signal.addEventListener("abort", abortListener, { once: true });
168
+ if (signal.aborted) abortListener();
169
+ }
170
+ if (Number.isFinite(timeout) && timeout > 0) {
171
+ timer = setTimeout(() => stopChild({ timeoutExpired: true }), timeout);
172
+ }
173
+ if (input !== undefined) {
174
+ child.stdin?.on("error", (error) => {
175
+ signalChild("SIGKILL");
176
+ settle({ error });
177
+ });
178
+ try {
179
+ child.stdin?.end(input);
180
+ } catch (error) {
181
+ signalChild("SIGKILL");
182
+ settle({ error });
183
+ }
184
+ }
185
+ });
186
+ }
187
+
188
+ // Locate a binary on PATH. Unix uses `which`; native Windows ships no `which`
189
+ // (it has `where.exe` instead), so blindly spawning `which` there returns
190
+ // ENOENT and every provider would report itself unconfigured even when the
191
+ // binary is installed and signed in.
192
+ async function whichBinary(binary, { commandRunner, platform = process.platform, signal } = {}) {
193
+ const probe = platform === "win32" ? "where" : "which";
194
+ const result = await runCommand(commandRunner, probe, [binary], {
195
+ timeout: 2000,
196
+ signal,
197
+ platform,
198
+ killProcessGroup: true,
199
+ });
200
+ if (result?.error || result?.status !== 0) return null;
201
+ const stdout = typeof result?.stdout === "string" ? result.stdout.trim() : "";
202
+ if (!stdout) return null;
203
+ // `where` on Windows emits CRLF and may list several matches across PATH
204
+ // entries; take the first line without the trailing `\r`, or the polluted
205
+ // path would fail at spawn time.
206
+ return stdout
207
+ .split(/\r?\n/)
208
+ .map((line) => line.trim())
209
+ .find(Boolean) || null;
210
+ }
211
+
212
+ async function isBinaryAvailable(binary, { commandRunner, platform, signal } = {}) {
213
+ return (await whichBinary(binary, { commandRunner, platform, signal })) !== null;
214
+ }
215
+
216
+ // Expand a versioned install root (e.g. ~/.nvm/versions/node/<ver>/ or
217
+ // fnm's node-versions/<ver>/installation/) into its per-version bin
218
+ // directories. Returns [] when the root does not exist.
219
+ function versionedBinDirs(root, inner) {
220
+ try {
221
+ return fs.readdirSync(root, { withFileTypes: true })
222
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
223
+ .sort((a, b) => b.name.localeCompare(a.name, "en", { numeric: true }))
224
+ .map((entry) => path.join(root, entry.name, ...inner));
225
+ } catch (_error) {
226
+ return [];
227
+ }
228
+ }
229
+
230
+ // Directories where globally installed CLIs commonly live even when the
231
+ // current process has a minimal PATH (e.g. a Finder-launched macOS app does
232
+ // not inherit the login-shell PATH, so Homebrew and npm global binaries are
233
+ // unreachable through `which`). Probed with statSync — no spawn.
234
+ function commonGlobalBinDirectories({ home = os.homedir(), platform = process.platform } = {}) {
235
+ if (platform === "win32") {
236
+ return [
237
+ path.join(home, "AppData", "Roaming", "npm"),
238
+ ];
239
+ }
240
+ return [
241
+ "/opt/homebrew/bin",
242
+ "/usr/local/bin",
243
+ path.join(home, ".local", "bin"),
244
+ path.join(home, ".bun", "bin"),
245
+ path.join(home, ".npm-global", "bin"),
246
+ // volta keeps shims for every global install here
247
+ path.join(home, ".volta", "bin"),
248
+ // nvm / fnm install npm globals under a per-version prefix that a
249
+ // minimal PATH never sees; newest version first.
250
+ ...versionedBinDirs(path.join(home, ".nvm", "versions", "node"), ["bin"]),
251
+ ...versionedBinDirs(path.join(home, ".local", "share", "fnm", "node-versions"), ["installation", "bin"]),
252
+ ...(platform === "darwin"
253
+ ? versionedBinDirs(path.join(home, "Library", "Application Support", "fnm", "node-versions"), ["installation", "bin"])
254
+ : []),
255
+ ];
256
+ }
257
+
258
+ // Probe `binary` inside the given directories with statSync — no spawn.
259
+ // Exported so providers can treat a hit as install evidence without
260
+ // paying for a `which` process.
261
+ function statBinaryInDirs(binary, searchDirs, platform = process.platform) {
262
+ for (const dir of searchDirs) {
263
+ const candidate = path.join(dir, binary);
264
+ for (const suffix of platform === "win32" ? ["", ".cmd", ".exe"] : [""]) {
265
+ try {
266
+ if (fs.statSync(candidate + suffix).isFile()) return candidate + suffix;
267
+ } catch (_error) {}
268
+ }
269
+ }
270
+ return null;
271
+ }
272
+
273
+ /**
274
+ * Resolve a binary to an absolute path: `which`/`where` first, then a
275
+ * spawn-free probe of the common global-install directories above. Returns
276
+ * null when the binary cannot be found. Callers should spawn the returned
277
+ * path (not the bare name): a bare name goes through PATH search again —
278
+ * and on Windows cmd.exe searches the current directory first, which would
279
+ * let an `arkcli.bat` dropped in the server cwd hijack the spawn.
280
+ */
281
+ async function resolveBinaryPath(binary, { commandRunner, home, platform = process.platform, signal, globalBinDirs } = {}) {
282
+ let resolved = null;
283
+ try {
284
+ resolved = await whichBinary(binary, { commandRunner, platform, signal });
285
+ } catch (_error) {
286
+ resolved = null;
287
+ }
288
+ if (resolved) return resolved;
289
+ const searchDirs = Array.isArray(globalBinDirs)
290
+ ? globalBinDirs
291
+ : commonGlobalBinDirectories({ home, platform });
292
+ return statBinaryInDirs(binary, searchDirs, platform);
293
+ }
294
+
295
+ // Resolving an npm CLI's absolute path does not resolve its /usr/bin/env node
296
+ // shebang. Finder-launched apps have a minimal PATH even when the CLI lives
297
+ // beside a working nvm/fnm/Homebrew Node. Scope this environment to the child;
298
+ // preserve the install's own runtime and use our running Node as a fallback.
299
+ function resolvedCliEnvironment(binaryPath, { env = process.env, platform = process.platform } = {}) {
300
+ if (platform === "win32") return { ...env };
301
+ const dirs = [path.dirname(binaryPath), ...(env.PATH || "/usr/bin:/bin").split(path.delimiter), path.dirname(process.execPath)];
302
+ return { ...env, PATH: [...new Set(dirs.filter(Boolean))].join(path.delimiter) };
303
+ }
304
+
305
+ module.exports = {
306
+ runCommand,
307
+ whichBinary,
308
+ isBinaryAvailable,
309
+ commonGlobalBinDirectories,
310
+ statBinaryInDirs,
311
+ resolveBinaryPath,
312
+ resolvedCliEnvironment,
313
+ };
@@ -0,0 +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
+ };