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,537 @@
1
+ "use strict";
2
+
3
+ // Ark Coding Plan (火山方舟 Coding Plan) quota monitoring.
4
+ //
5
+ // Coding Plan (Lite/Pro) and Agent Plan (Small/Medium/Large/Max) are
6
+ // two parallel subscription products that each refresh on three windows —
7
+ // 5-hour (session for Coding Plan, 5h for Agent Plan), weekly and monthly —
8
+ // and are shared by compatible coding tools (Claude Code, Codex CLI,
9
+ // OpenCode, TRAE, ...). Official docs present them as parallel, not
10
+ // successor/replacement. Token Usage already counts those tools' token
11
+ // consumption from their local files, so this module deliberately adds
12
+ // NO consumption source. It only surfaces the subscription quota
13
+ // percentage, which is otherwise only visible in the Volcano console web
14
+ // page. Agent Plan is handled by a separate provider module
15
+ // `ark-agent-plan-limits.js` (dual Provider, issue #555).
16
+ //
17
+ // The quota is read through the user's own `arkcli` binary
18
+ // (`arkcli usage plan --format json`), which is already installed and logged
19
+ // in for users of the Ark CLI ecosystem. Feature-detected: when `arkcli` is
20
+ // missing, the provider simply reports `configured: false` and stays out of
21
+ // the way. Mirrors qoder-limits.js; shares the command runner with
22
+ // usage-limits.js through ./command-runner (no circular dependency).
23
+
24
+ const fs = require("node:fs");
25
+ const os = require("node:os");
26
+ const path = require("node:path");
27
+
28
+ const { runCommand, resolveBinaryPath, statBinaryInDirs, commonGlobalBinDirectories, resolvedCliEnvironment } = require("./command-runner");
29
+
30
+ const ARK_LIMITS_CACHE_FILE = "ark-coding-plan-limits-cache.json";
31
+ const ARK_LIMITS_CACHE_UNKNOWN_RESET_TTL_MS = 12 * 60 * 60 * 1000;
32
+ const ARK_USAGE_PLAN_TIMEOUT_MS = 10_000;
33
+ // `profile show` only runs on the cache-guard path, after `usage plan`
34
+ // already failed. It must not push the total past the outer provider
35
+ // timeout (the whole point of the fallback is to still serve the disk
36
+ // cache), so it gets a much shorter leash.
37
+ const ARK_PROFILE_SHOW_TIMEOUT_MS = 2_500;
38
+ const ARK_CLI_STDERR_TRIM = 400;
39
+ // Mirrors usage-limits.js DEFAULT_PROVIDER_TIMEOUT_MS, which is what the
40
+ // production caller passes in; kept local to avoid a circular require.
41
+ const ARK_PROVIDER_TIMEOUT_MS = 15_000;
42
+ // A runCommand whose timeout fires still takes up to ~1s to hard-kill
43
+ // (SIGTERM -> SIGKILL escalation). Reserve that plus slack so the serial
44
+ // chain (discovery -> usage plan -> plans get / profile show -> cache
45
+ // read) always settles inside the provider budget and the disk-cache
46
+ // fallback actually gets served instead of losing the outer race.
47
+ // Same shape as codexResetCreditListTimeoutMs's guard in usage-limits.js.
48
+ const ARK_PROVIDER_BUDGET_GUARD_MS = 1_500;
49
+
50
+ // arkcli period label -> canonical window slot.
51
+ // Coding Plan uses `session` for the 5-hour rolling window; Agent Plan
52
+ // uses `5h`. `weekly` and `monthly` are shared. `daily` (Agent Plan
53
+ // visual quota) is intentionally not surfaced — it is a separate
54
+ // per-day visual bucket that does not fit the three-window panel.
55
+ const ARK_PERIOD_WINDOW = {
56
+ session: "primary_window",
57
+ "5h": "primary_window",
58
+ weekly: "secondary_window",
59
+ monthly: "tertiary_window",
60
+ };
61
+
62
+ // Coding Plan personal product. Team products (coding-plan-team) are
63
+ // seat-scoped and not surfaced in this personal-quota panel.
64
+ const ARK_PERSONAL_PRODUCTS = ["coding-plan"];
65
+ const ARK_PRODUCT_PRIORITY = ["coding-plan"];
66
+
67
+ function clampPercent(value) {
68
+ return Math.max(0, Math.min(100, value));
69
+ }
70
+
71
+ function normalizeResetAt(value) {
72
+ if (value === null || value === undefined || value === "") return null;
73
+ if (typeof value === "number" || /^\d+(?:\.\d+)?$/.test(String(value).trim())) {
74
+ const raw = Number(value);
75
+ if (!Number.isFinite(raw)) return null;
76
+ const milliseconds = raw > 10_000_000_000 ? raw : raw * 1000;
77
+ const date = new Date(milliseconds);
78
+ return Number.isFinite(date.getTime()) ? date.toISOString() : null;
79
+ }
80
+ const timestamp = Date.parse(String(value));
81
+ return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : null;
82
+ }
83
+
84
+ // The provider's display name is already "Ark Coding Plan", so the plan label
85
+ // carries only the tier — otherwise the panel title would read
86
+ // "Ark Coding Plan Coding Plan Lite".
87
+ function planLabelForTier(tier) {
88
+ const normalized = String(tier || "").trim().toLowerCase();
89
+ const mapping = {
90
+ pro: "Pro",
91
+ lite: "Lite",
92
+ small: "Small",
93
+ medium: "Medium",
94
+ large: "Large",
95
+ max: "Max",
96
+ };
97
+ if (mapping[normalized]) return mapping[normalized];
98
+ return tier && String(tier).trim() ? String(tier).trim() : null;
99
+ }
100
+
101
+ /**
102
+ * Normalize the JSON payload returned by `arkcli plans get --format json`.
103
+ * The tier ("lite" / "pro" for Coding Plan) lives on the plans payload,
104
+ * not on the usage payload, so it is resolved here and merged into the
105
+ * plan label.
106
+ * Returns null when there is no Coding Plan entry.
107
+ */
108
+ function normalizeArkPlansResponse(body) {
109
+ if (!body || typeof body !== "object") return null;
110
+ const plans = Array.isArray(body.plans) ? body.plans : [];
111
+ for (const key of ARK_PRODUCT_PRIORITY) {
112
+ const plan = plans.find((entry) => entry?.key === key);
113
+ if (plan?.tier) return String(plan.tier);
114
+ }
115
+ return null;
116
+ }
117
+
118
+ function arkProfileIdentity(body) {
119
+ const profile = body?.profile && typeof body.profile === "object" ? body.profile : body;
120
+ const name = typeof body?.profile === "string"
121
+ ? body.profile
122
+ : profile?.name || profile?.profile || profile?.profile_name;
123
+ let userId = profile?.user_id || profile?.userId || body?.user_id || body?.userId;
124
+ if (!userId) {
125
+ // `arkcli profile show` reports the account through owner_trn /
126
+ // identity_key (e.g. "trn:iam::1234567890:root" / "volc-1234567890")
127
+ // instead of a user_id field — extract the numeric id so identities
128
+ // coming from `usage plan`'s viewer and from `profile show` compare
129
+ // equal.
130
+ const trnMatch = String(profile?.owner_trn || "").match(/::(\d+):/);
131
+ if (trnMatch) userId = trnMatch[1];
132
+ else {
133
+ const keyMatch = String(profile?.identity_key || "").match(/-(\d+)$/);
134
+ if (keyMatch) userId = keyMatch[1];
135
+ }
136
+ }
137
+ const identity = [name, userId].filter(Boolean).join(":");
138
+ return identity || null;
139
+ }
140
+
141
+ function resolveArkProductItem(items) {
142
+ for (const product of ARK_PRODUCT_PRIORITY) {
143
+ const item = items.find((entry) => entry?.product === product && entry?.subscribed === true);
144
+ if (item) return item;
145
+ }
146
+ return null;
147
+ }
148
+
149
+ function percentFromPeriod(period) {
150
+ // null / undefined / blank percent must fall through to the used/total
151
+ // fallback: Number(null) and Number("") both coerce to 0, which would
152
+ // otherwise report a fake fresh 0% window instead of deriving real usage
153
+ // (Agent Plan's 5h period can omit percent entirely, #555).
154
+ const rawPercent = period?.percent;
155
+ if (rawPercent !== null && rawPercent !== undefined && String(rawPercent).trim() !== "") {
156
+ const direct = Number(rawPercent);
157
+ if (Number.isFinite(direct)) return direct;
158
+ }
159
+ const used = Number(period?.used);
160
+ const total = Number(period?.total);
161
+ if (Number.isFinite(used) && Number.isFinite(total) && total > 0) {
162
+ return (used / total) * 100;
163
+ }
164
+ return NaN;
165
+ }
166
+
167
+ /**
168
+ * Normalize the JSON payload returned by `arkcli usage plan --format json`.
169
+ * Returns `null` when the account has no active Coding Plan subscription
170
+ * (caller reports `configured: false`). Throws when the payload shape is
171
+ * unusable so the caller can fall back to the disk cache.
172
+ * Only `coding-plan` (Lite/Pro, session label) is handled here;
173
+ * Agent Plan is handled by `ark-agent-plan-limits.js`.
174
+ */
175
+ function normalizeArkCodingPlanResponse(body) {
176
+ if (!body || typeof body !== "object") {
177
+ throw new Error("Ark Coding Plan response is not an object.");
178
+ }
179
+ const items = Array.isArray(body.items) ? body.items : [];
180
+ const item = resolveArkProductItem(items);
181
+ if (!item) return null;
182
+
183
+ const windows = {};
184
+ const periods = Array.isArray(item.periods) ? item.periods : [];
185
+ for (const period of periods) {
186
+ // Agent Plan `daily` is a visual-only quota not shown in the 3-window panel.
187
+ if (period?.label === "daily") continue;
188
+ const slot = ARK_PERIOD_WINDOW[period?.label];
189
+ if (!slot) continue;
190
+ const percent = percentFromPeriod(period);
191
+ if (!Number.isFinite(percent)) continue;
192
+ windows[slot] = {
193
+ used_percent: clampPercent(percent),
194
+ reset_at: normalizeResetAt(period.reset_at),
195
+ unit: "calls",
196
+ };
197
+ }
198
+ if (!windows.primary_window && !windows.secondary_window && !windows.tertiary_window) {
199
+ throw new Error("Ark Coding Plan response contains no usable quota periods.");
200
+ }
201
+
202
+ return {
203
+ configured: true,
204
+ error: null,
205
+ plan_label: planLabelForTier(item.tier),
206
+ product: item.product || null,
207
+ primary_window: windows.primary_window || null,
208
+ secondary_window: windows.secondary_window || null,
209
+ tertiary_window: windows.tertiary_window || null,
210
+ source: "provider-api",
211
+ profile_identity: arkProfileIdentity(body.viewer),
212
+ };
213
+ }
214
+
215
+ function arkCodingPlanCachePath({ home = os.homedir() } = {}) {
216
+ return path.join(home, ".tokenusage", "tracker", ARK_LIMITS_CACHE_FILE);
217
+ }
218
+
219
+ function readArkCodingPlanLimitsCache({ home = os.homedir(), nowMs = Date.now(), profileIdentity } = {}) {
220
+ try {
221
+ const parsed = JSON.parse(fs.readFileSync(arkCodingPlanCachePath({ home }), "utf8"));
222
+ // Deliberately fail-open: the guard only applies when `profile show`
223
+ // could establish the current identity. When it also failed, serving
224
+ // the stale cache beats erroring out — availability over strictness.
225
+ if (profileIdentity && parsed?.profile_identity !== profileIdentity) return null;
226
+ const cachedAtMs = Date.parse(parsed?.cached_at || "");
227
+ if (!Number.isFinite(cachedAtMs) || cachedAtMs > nowMs + 60_000) return null;
228
+ // A window whose reset_at has passed is stale — the quota has already
229
+ // rolled over, so serving its old used_percent would mislead. Drop it.
230
+ const windows = [parsed?.primary_window, parsed?.secondary_window, parsed?.tertiary_window];
231
+ const surviving = windows.map((window) => {
232
+ if (!window) return null;
233
+ const resetAtMs = Date.parse(window.reset_at || "");
234
+ if (Number.isFinite(resetAtMs) && resetAtMs <= nowMs) return null;
235
+ return window;
236
+ });
237
+ if (surviving.every((window) => !window)) return null;
238
+ // Undated windows can't be checked against a reset, so drop each one when
239
+ // the snapshot is too old. A future-dated sibling must not keep it alive.
240
+ const bounded = surviving.map((window) => {
241
+ if (!window) return null;
242
+ return Number.isFinite(Date.parse(window.reset_at || ""))
243
+ || nowMs - cachedAtMs <= ARK_LIMITS_CACHE_UNKNOWN_RESET_TTL_MS
244
+ ? window
245
+ : null;
246
+ });
247
+ if (bounded.every((window) => !window)) return null;
248
+ return {
249
+ configured: true,
250
+ error: null,
251
+ plan_label: typeof parsed?.plan_label === "string" ? parsed.plan_label : null,
252
+ product: typeof parsed?.product === "string" ? parsed.product : null,
253
+ primary_window: bounded[0],
254
+ secondary_window: bounded[1],
255
+ tertiary_window: bounded[2],
256
+ cached: true,
257
+ stale: true,
258
+ cached_at: parsed.cached_at,
259
+ source: "disk-cache",
260
+ };
261
+ } catch (_error) {
262
+ return null;
263
+ }
264
+ }
265
+
266
+ function writeArkCodingPlanLimitsCache(limits, { home = os.homedir(), nowMs = Date.now() } = {}) {
267
+ if (!limits?.configured || limits.error) return;
268
+ const cachePath = arkCodingPlanCachePath({ home });
269
+ const payload = {
270
+ plan_label: limits.plan_label || null,
271
+ product: limits.product || null,
272
+ profile_identity: limits.profile_identity || null,
273
+ primary_window: limits.primary_window || null,
274
+ secondary_window: limits.secondary_window || null,
275
+ tertiary_window: limits.tertiary_window || null,
276
+ cached_at: new Date(nowMs).toISOString(),
277
+ };
278
+ try {
279
+ fs.mkdirSync(path.dirname(cachePath), { recursive: true });
280
+ const tmpPath = `${cachePath}.${process.pid}.tmp`;
281
+ fs.writeFileSync(tmpPath, JSON.stringify(payload, null, 2), { encoding: "utf8", mode: 0o600 });
282
+ fs.renameSync(tmpPath, cachePath);
283
+ } catch (_error) {}
284
+ }
285
+
286
+ // runCommand / whichBinary / resolveBinaryPath now live in ./command-runner,
287
+ // shared with usage-limits.js (single implementation, no forked copies).
288
+
289
+ // arkcli keeps its config and credentials under ~/.arkcli (plus a couple of
290
+ // platform-typical alternates). Checking for these directories is a
291
+ // spawn-free way to tell "arkcli has never been installed" apart from
292
+ // "installed but the quota call failed" — machines without the CLI skip the
293
+ // binary probe entirely on every poll, so the 5s refresh cadence never pays
294
+ // a `which` spawn for a provider they cannot use.
295
+ function hasArkCliInstallEvidence({ home = os.homedir(), platform = process.platform } = {}) {
296
+ const candidates = [
297
+ path.join(home, ".arkcli"),
298
+ path.join(home, ".config", "arkcli"),
299
+ ];
300
+ if (platform === "win32") {
301
+ candidates.push(path.join(home, "AppData", "Roaming", "arkcli"));
302
+ }
303
+ for (const dir of candidates) {
304
+ try {
305
+ if (fs.statSync(dir).isDirectory()) return true;
306
+ } catch (_error) {}
307
+ }
308
+ return false;
309
+ }
310
+
311
+ function trimStderr(stderr) {
312
+ const text = String(stderr || "").trim();
313
+ if (!text) return null;
314
+ return text.length > ARK_CLI_STDERR_TRIM
315
+ ? `${text.slice(0, ARK_CLI_STDERR_TRIM)}…`
316
+ : text;
317
+ }
318
+
319
+ /**
320
+ * Fetch Ark Coding Plan quota windows from the local `arkcli` binary.
321
+ *
322
+ * Resolution order:
323
+ * 1. no config-dir evidence AND no arkcli in the global bin dirs
324
+ * -> { configured: false }, zero spawns
325
+ * 2. arkcli binary not resolvable -> { configured: false }
326
+ * 3. `arkcli usage plan` succeeds but no subscription -> { configured: false }
327
+ * 4. live success -> { configured: true, ...windows }
328
+ * 5. command/parse failure -> bounded disk cache -> { configured: true, ...stale }
329
+ * 6. nothing usable -> { configured: true, error }
330
+ *
331
+ * Only `usage plan` runs on the happy path. `plans get` (tier label) runs
332
+ * only when the usage response carries no tier, and `profile show` (the
333
+ * cross-account cache guard) only when the disk cache is consulted.
334
+ *
335
+ * `providerTimeoutMs` bounds the whole serial chain (mirrors the codex
336
+ * remaining-budget pattern): each CLI call's timeout is clamped to what
337
+ * is left of the budget, and calls whose share has run out are skipped
338
+ * so the disk-cache fallback still resolves inside the outer race.
339
+ */
340
+ async function fetchArkCodingPlanLimits({
341
+ commandRunner,
342
+ home = os.homedir(),
343
+ nowMs = Date.now(),
344
+ platform = process.platform,
345
+ signal,
346
+ globalBinDirs,
347
+ providerTimeoutMs = ARK_PROVIDER_TIMEOUT_MS,
348
+ } = {}) {
349
+ // Mirror of codexResetCreditListTimeoutMs: every CLI call in the serial
350
+ // chain gets a timeout clamped to what is left of the provider budget,
351
+ // so the chain can never outrun the outer provider race and starve the
352
+ // disk-cache fallback.
353
+ const startedAtMs = performance.now();
354
+ const budgetedTimeoutMs = (fullTimeoutMs) => {
355
+ if (!Number.isFinite(providerTimeoutMs) || providerTimeoutMs <= 0) return fullTimeoutMs;
356
+ const remainingMs = providerTimeoutMs - (performance.now() - startedAtMs);
357
+ if (remainingMs <= 0) return 0;
358
+ const guardedMs = Math.floor(remainingMs - ARK_PROVIDER_BUDGET_GUARD_MS);
359
+ if (guardedMs <= 0) return 0;
360
+ return Math.min(fullTimeoutMs, guardedMs);
361
+ };
362
+
363
+ const searchDirs = () => Array.isArray(globalBinDirs)
364
+ ? globalBinDirs
365
+ : commonGlobalBinDirectories({ home, platform });
366
+
367
+ let arkcliPath;
368
+ if (hasArkCliInstallEvidence({ home, platform })) {
369
+ try {
370
+ arkcliPath = await resolveBinaryPath("arkcli", { commandRunner, home, platform, signal, globalBinDirs });
371
+ } catch (_error) {
372
+ arkcliPath = null;
373
+ }
374
+ } else {
375
+ // No config-dir evidence — still resolve spawn-free first: an arkcli
376
+ // found in a global bin directory counts as install evidence too (the
377
+ // CLI may keep its config somewhere we don't know about). Only when
378
+ // that also misses do we bail, so machines without the CLI still pay
379
+ // zero spawns per poll.
380
+ arkcliPath = statBinaryInDirs("arkcli", searchDirs(), platform);
381
+ }
382
+ if (!arkcliPath) return { configured: false };
383
+
384
+ const commandOptions = {
385
+ env: resolvedCliEnvironment(arkcliPath, { platform }),
386
+ signal,
387
+ killProcessGroup: true,
388
+ platform,
389
+ // npm installs CLI entrypoints as .cmd shims on Windows, which a direct
390
+ // spawn cannot execute. Every argument here is a constant with no shell
391
+ // metacharacters, so shell execution is safe for this call site only —
392
+ // it must stay opt-in (see command-runner.js).
393
+ useShell: platform === "win32",
394
+ };
395
+
396
+ // Budget already drained before the primary call could run: report the
397
+ // timeout without touching the cache — an unverified cache (profile
398
+ // identity unknown) must not be served on this path, mirroring the
399
+ // outer provider race's behavior. The verified-cache fallback below is
400
+ // what keeps hung-CLI polls serving last-known data.
401
+ const usageTimeoutMs = budgetedTimeoutMs(ARK_USAGE_PLAN_TIMEOUT_MS);
402
+ if (usageTimeoutMs <= 0) {
403
+ return { configured: true, error: "Ark Coding Plan provider timed out before arkcli could run." };
404
+ }
405
+
406
+ // Spawn the resolved absolute path, never the bare name: on Windows
407
+ // cmd.exe searches the current directory before PATH, so a bare
408
+ // `arkcli` would let an `arkcli.bat` dropped in the server cwd hijack
409
+ // the spawn.
410
+ const result = await runCommand(
411
+ commandRunner,
412
+ arkcliPath,
413
+ ["usage", "plan", "--format", "json"],
414
+ { ...commandOptions, timeout: usageTimeoutMs },
415
+ );
416
+
417
+ const failWithCache = async (message) => {
418
+ // Short leash, further clamped to the remaining provider budget: this
419
+ // runs after `usage plan` already burned most of the budget; a slow or
420
+ // hung arkcli here must not starve the cache read that the caller is
421
+ // actually waiting for. When no budget is left the spawn is skipped
422
+ // entirely and the cache is read fail-open (identity unknown).
423
+ const profileTimeoutMs = budgetedTimeoutMs(ARK_PROFILE_SHOW_TIMEOUT_MS);
424
+ const profileIdentity = profileTimeoutMs > 0
425
+ ? await runCommand(
426
+ commandRunner,
427
+ arkcliPath,
428
+ ["profile", "show", "--format", "json"],
429
+ { ...commandOptions, timeout: profileTimeoutMs },
430
+ ).then((profileResult) => {
431
+ if (profileResult?.error || profileResult?.status !== 0) return null;
432
+ try {
433
+ return arkProfileIdentity(JSON.parse(String(profileResult.stdout || "")));
434
+ } catch (_error) {
435
+ return null;
436
+ }
437
+ }).catch(() => null)
438
+ : null;
439
+ const cached = readArkCodingPlanLimitsCache({ home, nowMs, profileIdentity });
440
+ if (cached) return cached;
441
+ return { configured: true, error: message };
442
+ };
443
+
444
+ if (result?.error || result?.status !== 0) {
445
+ const isExit127 = result?.status === 127;
446
+ const baseDetail = result?.error?.message
447
+ || (result?.status !== 0 && result?.status !== null
448
+ ? `arkcli exited with code ${result.status}`
449
+ : "arkcli usage plan failed");
450
+ // Exit 127 can mean a missing interpreter as well as an outdated CLI.
451
+ // Preserve stderr so users can distinguish runtime and command failures.
452
+ const detail = isExit127
453
+ ? "arkcli exited with code 127 — check its runtime/PATH or update arkcli: npm i -g @volcengine/ark-cli"
454
+ : baseDetail;
455
+ const stderr = trimStderr(result?.stderr);
456
+ const message = stderr ? `${detail}: ${stderr}` : detail;
457
+ return failWithCache(message);
458
+ }
459
+
460
+ let body;
461
+ try {
462
+ body = JSON.parse(String(result?.stdout || ""));
463
+ } catch (_error) {
464
+ return failWithCache("arkcli usage plan returned invalid JSON.");
465
+ }
466
+
467
+ let limits;
468
+ try {
469
+ limits = normalizeArkCodingPlanResponse(body);
470
+ } catch (error) {
471
+ return failWithCache(error?.message || "Ark Coding Plan response could not be parsed.");
472
+ }
473
+ if (!limits) {
474
+ // Only a response that explicitly carries an Ark product entry with
475
+ // `subscribed: false` confirms the plan was retired — drop the cache
476
+ // then, or a later transient CLI failure would resurrect the retired
477
+ // plan's numbers through failWithCache. A payload with *no* Ark entry
478
+ // at all (`{}`, `{"items":[]}` — not logged in, backend degraded,
479
+ // product key renamed) is ambiguous and must NOT destroy the cache:
480
+ // transient signals never drive persistent state.
481
+ // Only coding-plan is considered here; agent-plan is handled by the
482
+ // parallel provider `ark-agent-plan-limits.js`.
483
+ const entry = Array.isArray(body?.items)
484
+ ? body.items.find(
485
+ (candidate) =>
486
+ ARK_PERSONAL_PRODUCTS.includes(candidate?.product) && candidate?.subscribed === false,
487
+ )
488
+ : null;
489
+ if (entry) {
490
+ try {
491
+ fs.unlinkSync(arkCodingPlanCachePath({ home }));
492
+ } catch (_error) {}
493
+ }
494
+ return { configured: false };
495
+ }
496
+
497
+ if (!limits.plan_label) {
498
+ // The tier ("lite" / "pro") lives on the `plans get` payload; fetch it
499
+ // only when the usage response did not carry one, and only while the
500
+ // provider budget still has room for the spawn. A skipped fetch just
501
+ // leaves the label null — never worth losing the live data over.
502
+ const plansTimeoutMs = budgetedTimeoutMs(ARK_USAGE_PLAN_TIMEOUT_MS);
503
+ if (plansTimeoutMs > 0) {
504
+ const plansResult = await runCommand(
505
+ commandRunner,
506
+ arkcliPath,
507
+ ["plans", "get", "--format", "json"],
508
+ { ...commandOptions, timeout: plansTimeoutMs },
509
+ );
510
+ if (!plansResult?.error && plansResult?.status === 0) {
511
+ try {
512
+ const tier = normalizeArkPlansResponse(JSON.parse(String(plansResult.stdout || "")));
513
+ if (tier) limits.plan_label = planLabelForTier(tier);
514
+ } catch (_error) {}
515
+ }
516
+ }
517
+ }
518
+
519
+ writeArkCodingPlanLimitsCache(limits, { home, nowMs });
520
+ return limits;
521
+ }
522
+
523
+ module.exports = {
524
+ ARK_PERIOD_WINDOW,
525
+ ARK_PERSONAL_PRODUCTS,
526
+ ARK_PRODUCT_PRIORITY,
527
+ normalizeArkPlansResponse,
528
+ arkProfileIdentity,
529
+ normalizeArkCodingPlanResponse,
530
+ readArkCodingPlanLimitsCache,
531
+ writeArkCodingPlanLimitsCache,
532
+ hasArkCliInstallEvidence,
533
+ fetchArkCodingPlanLimits,
534
+ // exposed for testing
535
+ resolveArkProductItem,
536
+ percentFromPeriod,
537
+ };
@@ -0,0 +1,138 @@
1
+ const fs = require("node:fs/promises");
2
+ const { createHash } = require("node:crypto");
3
+ const { StringDecoder } = require("node:string_decoder");
4
+ const { setImmediate: yieldToRequests } = require("node:timers/promises");
5
+
6
+ const CHUNK_BYTES = 64 * 1024;
7
+
8
+ function signature(stat) {
9
+ return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
10
+ }
11
+
12
+ // One in-flight read per path shares the dashboard's request fan-out. Parsing
13
+ // yields between bounded chunks so a cold/replaced queue cannot monopolize the
14
+ // HTTP event loop. Keep committed newline-terminated rows separate from a tail
15
+ // that a concurrent writer may still be completing.
16
+ function createAsyncQueueReader({ parseRow, label, maxEntries = 4 }) {
17
+ const cache = new Map();
18
+ const pending = new Map();
19
+
20
+ async function hashPrefix(file, length) {
21
+ const hash = createHash("sha256");
22
+ const buffer = Buffer.allocUnsafe(CHUNK_BYTES);
23
+ let position = 0;
24
+ while (position < length) {
25
+ const { bytesRead } = await file.read(buffer, 0, Math.min(CHUNK_BYTES, length - position), position);
26
+ if (!bytesRead) throw new Error("Queue truncated during validation");
27
+ hash.update(buffer.subarray(0, bytesRead));
28
+ position += bytesRead;
29
+ await yieldToRequests();
30
+ }
31
+ return hash;
32
+ }
33
+
34
+ async function load(queuePath) {
35
+ const cached = cache.get(queuePath);
36
+ let file;
37
+ try {
38
+ file = await fs.open(queuePath, "r");
39
+ // Stat the opened file, rather than a path which can be atomically replaced
40
+ // between stat and open. Its signature always describes the bytes we read.
41
+ const stat = await file.stat({ bigint: true });
42
+ const nextSignature = signature(stat);
43
+ const identity = `${stat.dev}:${stat.ino}`;
44
+ const size = Number(stat.size);
45
+ if (cached?.signature === nextSignature) {
46
+ // Windows can reuse mtime/ctime for same-size writes anywhere in the
47
+ // file. Validate every byte before reusing the parsed snapshot.
48
+ const hash = await hashPrefix(file, size);
49
+ if (hash.digest("hex") === cached.digest) return cached.rows;
50
+ }
51
+ let offset = 0;
52
+ let seen = new Map();
53
+ let hash = createHash("sha256");
54
+ if (cached && cached.identity === identity && size > cached.size && cached.consumedBytes > 0) {
55
+ // Growth can include an interior rewrite, so verify the entire old
56
+ // committed prefix before parsing only the new tail.
57
+ const prefixHash = await hashPrefix(file, cached.consumedBytes);
58
+ if (prefixHash.copy().digest("hex") === cached.committedDigest) {
59
+ offset = cached.consumedBytes;
60
+ seen = cached.seen;
61
+ hash = prefixHash;
62
+ }
63
+ }
64
+ let committedHash = hash.copy();
65
+
66
+ const changes = new Map();
67
+ let malformed = 0;
68
+ function parse(line, target) {
69
+ if (!line.trim()) return;
70
+ try {
71
+ const entry = parseRow(JSON.parse(line));
72
+ if (entry) target.set(entry.key, entry.row);
73
+ } catch { malformed++; }
74
+ }
75
+
76
+ const decoder = new StringDecoder("utf8");
77
+ const buffer = Buffer.allocUnsafe(CHUNK_BYTES);
78
+ let remainder = "";
79
+ let position = offset;
80
+ let consumedBytes = offset;
81
+ while (position < size) {
82
+ const length = Math.min(CHUNK_BYTES, size - position);
83
+ const { bytesRead } = await file.read(buffer, 0, length, position);
84
+ if (!bytesRead) throw new Error("Queue truncated during read");
85
+ const newline = buffer.lastIndexOf(0x0a, bytesRead - 1);
86
+ const chunk = buffer.subarray(0, bytesRead);
87
+ if (newline >= 0) {
88
+ consumedBytes = position + newline + 1;
89
+ committedHash = hash.copy().update(chunk.subarray(0, newline + 1));
90
+ }
91
+ hash.update(chunk);
92
+ position += bytesRead;
93
+ remainder += decoder.write(chunk);
94
+ let start = 0;
95
+ let end;
96
+ while ((end = remainder.indexOf("\n", start)) !== -1) {
97
+ parse(remainder.slice(start, end), changes);
98
+ start = end + 1;
99
+ }
100
+ remainder = remainder.slice(start);
101
+ await yieldToRequests();
102
+ }
103
+ remainder += decoder.end();
104
+ for (const [key, row] of changes) seen.set(key, row);
105
+ const tail = new Map();
106
+ parse(remainder, tail);
107
+ // Legacy files without a final newline are readable, but their provisional
108
+ // key never enters the committed map (completion may change that key).
109
+ const rows = tail.size ? Array.from(new Map([...seen, ...tail]).values()) : Array.from(seen.values());
110
+ cache.delete(queuePath);
111
+ cache.set(queuePath, {
112
+ signature: nextSignature, identity, size, consumedBytes,
113
+ digest: hash.digest("hex"), committedDigest: committedHash.digest("hex"), seen, rows,
114
+ });
115
+ while (cache.size > maxEntries) cache.delete(cache.keys().next().value);
116
+ if (malformed) console.error(`[LocalAPI] ${label}: skipped ${malformed} malformed line(s)`);
117
+ return rows;
118
+ } catch (error) {
119
+ if (error.code === "ENOENT") {
120
+ cache.delete(queuePath);
121
+ return [];
122
+ }
123
+ console.error(`[LocalAPI] ${label}: failed to read queue:`, error.message);
124
+ return cached?.rows || [];
125
+ } finally {
126
+ if (file) await file.close();
127
+ }
128
+ }
129
+
130
+ return function read(queuePath) {
131
+ if (pending.has(queuePath)) return pending.get(queuePath);
132
+ const task = load(queuePath).finally(() => pending.delete(queuePath));
133
+ pending.set(queuePath, task);
134
+ return task;
135
+ };
136
+ }
137
+
138
+ module.exports = { createAsyncQueueReader };