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,76 @@
1
+ function createProgress({ stream } = {}) {
2
+ const out = stream || process.stdout;
3
+ const enabled = Boolean(out && out.isTTY);
4
+ const frames = ["|", "/", "-", "\\"];
5
+ const intervalMs = 90;
6
+
7
+ let timer = null;
8
+ let text = "";
9
+ let frame = 0;
10
+ let lastLen = 0;
11
+
12
+ function render() {
13
+ if (!enabled) return;
14
+ const line = `${frames[frame++ % frames.length]} ${text}`;
15
+ const pad = lastLen > line.length ? " ".repeat(lastLen - line.length) : "";
16
+ lastLen = line.length;
17
+ out.write(`\r${line}${pad}`);
18
+ }
19
+
20
+ function start(initialText) {
21
+ if (!enabled) return;
22
+ text = initialText || "";
23
+ if (timer) clearInterval(timer);
24
+ timer = setInterval(render, intervalMs);
25
+ render();
26
+ }
27
+
28
+ function update(nextText) {
29
+ text = nextText || "";
30
+ render();
31
+ }
32
+
33
+ function stop() {
34
+ if (!enabled) return;
35
+ if (timer) clearInterval(timer);
36
+ timer = null;
37
+ out.write(`\r${" ".repeat(lastLen)}\r`);
38
+ lastLen = 0;
39
+ }
40
+
41
+ return { enabled, start, update, stop };
42
+ }
43
+
44
+ function renderBar(progress, width = 20) {
45
+ const p = Number.isFinite(progress) ? Math.min(1, Math.max(0, progress)) : 0;
46
+ const filled = Math.round(p * width);
47
+ const empty = Math.max(0, width - filled);
48
+ return `[${"=".repeat(filled)}${"-".repeat(empty)}] ${Math.round(p * 100)}%`;
49
+ }
50
+
51
+ function formatNumber(n) {
52
+ const v = Number(n);
53
+ if (!Number.isFinite(v)) return "0";
54
+ return Math.trunc(v).toLocaleString("en-US");
55
+ }
56
+
57
+ function formatBytes(bytes) {
58
+ const n = Number(bytes);
59
+ if (!Number.isFinite(n) || n <= 0) return "0 B";
60
+ const units = ["B", "KB", "MB", "GB", "TB"];
61
+ let v = n;
62
+ let i = 0;
63
+ while (v >= 1024 && i < units.length - 1) {
64
+ v /= 1024;
65
+ i += 1;
66
+ }
67
+ const fixed = i === 0 ? String(Math.trunc(v)) : v.toFixed(v >= 10 ? 1 : 2);
68
+ return `${fixed} ${units[i]}`;
69
+ }
70
+
71
+ module.exports = {
72
+ createProgress,
73
+ renderBar,
74
+ formatNumber,
75
+ formatBytes,
76
+ };
@@ -0,0 +1,117 @@
1
+ const fs = require("node:fs");
2
+ const fsp = require("node:fs/promises");
3
+ const path = require("node:path");
4
+ const readline = require("node:readline");
5
+
6
+ async function purgeProjectUsage({
7
+ projectKey,
8
+ projectQueuePath,
9
+ projectQueueStatePath,
10
+ projectState,
11
+ cursors,
12
+ }) {
13
+ if (!projectKey || !projectQueuePath || !projectQueueStatePath || !projectState) {
14
+ return { removed: 0, kept: 0, removedBuckets: 0, removedProjectCursors: 0 };
15
+ }
16
+
17
+ let previousOffset = 0;
18
+ const previousState = await fsp.readFile(projectQueueStatePath, "utf8").catch(() => null);
19
+ if (previousState) {
20
+ try {
21
+ const parsed = JSON.parse(previousState);
22
+ const offset = Number(parsed?.offset || 0);
23
+ if (Number.isFinite(offset) && offset >= 0) previousOffset = offset;
24
+ } catch (_err) {
25
+ previousOffset = 0;
26
+ }
27
+ }
28
+
29
+ const buckets =
30
+ projectState.buckets && typeof projectState.buckets === "object" ? projectState.buckets : {};
31
+ let removedBuckets = 0;
32
+ const prefix = `${projectKey}|`;
33
+ for (const key of Object.keys(buckets)) {
34
+ if (key.startsWith(prefix)) {
35
+ delete buckets[key];
36
+ removedBuckets += 1;
37
+ }
38
+ }
39
+ projectState.buckets = buckets;
40
+
41
+ let removedProjectCursors = 0;
42
+ const files = cursors?.files && typeof cursors.files === "object" ? cursors.files : {};
43
+ for (const cursor of Object.values(files)) {
44
+ if (!cursor || typeof cursor !== "object") continue;
45
+ if (cursor.project?.projectKey === projectKey) {
46
+ delete cursor.project;
47
+ removedProjectCursors += 1;
48
+ }
49
+ }
50
+
51
+ let removed = 0;
52
+ let kept = 0;
53
+ let nextOffset = 0;
54
+ const st = await fsp.stat(projectQueuePath).catch(() => null);
55
+ if (st && st.isFile()) {
56
+ const tmpPath = `${projectQueuePath}.tmp`;
57
+ await fsp.mkdir(path.dirname(projectQueuePath), { recursive: true });
58
+ const input = fs.createReadStream(projectQueuePath, "utf8");
59
+ const output = fs.createWriteStream(tmpPath, { encoding: "utf8" });
60
+ const rl = readline.createInterface({ input, crlfDelay: Infinity });
61
+
62
+ let inputOffset = 0;
63
+ let outputOffset = 0;
64
+ for await (const line of rl) {
65
+ const trimmed = line.trim();
66
+ const inputBytes = Buffer.byteLength(line, "utf8") + 1;
67
+ inputOffset += inputBytes;
68
+ if (!trimmed) continue;
69
+ let parsed = null;
70
+ try {
71
+ parsed = JSON.parse(trimmed);
72
+ } catch (_err) {
73
+ const entry = trimmed + "\n";
74
+ output.write(entry);
75
+ outputOffset += Buffer.byteLength(entry, "utf8");
76
+ kept += 1;
77
+ if (inputOffset <= previousOffset) {
78
+ nextOffset = outputOffset;
79
+ }
80
+ continue;
81
+ }
82
+ if (parsed && parsed.project_key === projectKey) {
83
+ removed += 1;
84
+ if (inputOffset <= previousOffset) {
85
+ nextOffset = outputOffset;
86
+ }
87
+ continue;
88
+ }
89
+ const entry = JSON.stringify(parsed) + "\n";
90
+ output.write(entry);
91
+ outputOffset += Buffer.byteLength(entry, "utf8");
92
+ kept += 1;
93
+ if (inputOffset <= previousOffset) {
94
+ nextOffset = outputOffset;
95
+ }
96
+ }
97
+
98
+ await new Promise((resolve, reject) => {
99
+ output.end(resolve);
100
+ output.on("error", reject);
101
+ });
102
+
103
+ await fsp.rename(tmpPath, projectQueuePath);
104
+ if (previousOffset >= inputOffset) {
105
+ nextOffset = outputOffset;
106
+ }
107
+ } else {
108
+ await fsp.writeFile(projectQueuePath, "", "utf8");
109
+ nextOffset = 0;
110
+ }
111
+
112
+ await fsp.writeFile(projectQueueStatePath, JSON.stringify({ offset: nextOffset }), "utf8");
113
+
114
+ return { removed, kept, removedBuckets, removedProjectCursors };
115
+ }
116
+
117
+ module.exports = { purgeProjectUsage };
@@ -0,0 +1,24 @@
1
+ const readline = require("node:readline");
2
+
3
+ async function prompt(label) {
4
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
5
+ const value = await new Promise((resolve) => rl.question(label, resolve));
6
+ rl.close();
7
+ return String(value || "").trim();
8
+ }
9
+
10
+ async function promptHidden(label) {
11
+ const rl = readline.createInterface({
12
+ input: process.stdin,
13
+ output: process.stdout,
14
+ terminal: true,
15
+ });
16
+ const value = await new Promise((resolve) => {
17
+ rl._writeToOutput = function _writeToOutput() {};
18
+ rl.question(label, (answer) => resolve(answer));
19
+ });
20
+ rl.close();
21
+ return String(value || "").trim();
22
+ }
23
+
24
+ module.exports = { prompt, promptHidden };
@@ -0,0 +1,104 @@
1
+ // Provider service-status probes (Statuspage.io-style), CodexBar-inspired.
2
+ //
3
+ // Answers "is the provider itself down?" so the limits panel can explain
4
+ // upstream failures instead of leaving users guessing (issue: users read a
5
+ // red/stale Claude limits row as a Token Usage bug during Anthropic
6
+ // incidents). Fail-soft by design: a probe failure never breaks the limits
7
+ // response — callers get the last good reading or null, never a throw.
8
+ //
9
+ // Statuspage.io contract (`/api/v2/status.json`):
10
+ // { "page": { "updated_at": ISO }, "status": { "indicator": "none|minor|major|critical", "description": "..." } }
11
+
12
+ const STATUS_PROBE_TIMEOUT_MS = 6_000;
13
+ // Status pages change on incident timescales; 5 minutes keeps the limits
14
+ // poll (2-min TTL upstream) from hammering statuspage.io every cycle.
15
+ const STATUS_CACHE_TTL_MS = 5 * 60 * 1000;
16
+ // Serve a stale last-good reading for up to 30 minutes when probes fail, so a
17
+ // transient network blip doesn't flap the incident row on and off.
18
+ const STATUS_LAST_GOOD_MAX_AGE_MS = 30 * 60 * 1000;
19
+
20
+ const STATUS_PAGE_SPECS = {
21
+ claude: {
22
+ // status.anthropic.com 302-redirects here; use the canonical host directly.
23
+ apiUrl: "https://status.claude.com/api/v2/status.json",
24
+ pageUrl: "https://status.claude.com",
25
+ },
26
+ };
27
+
28
+ const VALID_INDICATORS = new Set(["none", "minor", "major", "critical"]);
29
+
30
+ // providerId -> { data, fetchedAtMs } (data may be null after a failed probe
31
+ // with no last-good to fall back on).
32
+ let statusCache = new Map();
33
+
34
+ function normalizeStatusPayload(payload, spec, nowMs) {
35
+ const indicator = payload?.status?.indicator;
36
+ if (typeof indicator !== "string" || !VALID_INDICATORS.has(indicator)) return null;
37
+ const description = typeof payload?.status?.description === "string"
38
+ ? payload.status.description.trim()
39
+ : "";
40
+ const updatedAt = typeof payload?.page?.updated_at === "string" && payload.page.updated_at
41
+ ? payload.page.updated_at
42
+ : new Date(nowMs).toISOString();
43
+ return {
44
+ indicator,
45
+ description: description || null,
46
+ updated_at: updatedAt,
47
+ url: spec.pageUrl,
48
+ };
49
+ }
50
+
51
+ /**
52
+ * Fetch a provider's public service status. Never throws; returns
53
+ * `{ indicator, description, updated_at, url }` or null when the provider has
54
+ * no status page, the probe fails with no usable last-good reading, or the
55
+ * payload is malformed.
56
+ */
57
+ async function fetchProviderServiceStatus(providerId, { fetchImpl = fetch, nowMs = Date.now() } = {}) {
58
+ const spec = STATUS_PAGE_SPECS[providerId];
59
+ if (!spec) return null;
60
+
61
+ const cached = statusCache.get(providerId);
62
+ if (cached && nowMs - cached.fetchedAtMs < STATUS_CACHE_TTL_MS) {
63
+ return cached.data;
64
+ }
65
+
66
+ let data = null;
67
+ try {
68
+ const controller = new AbortController();
69
+ const timer = setTimeout(() => controller.abort(), STATUS_PROBE_TIMEOUT_MS);
70
+ try {
71
+ const res = await fetchImpl(spec.apiUrl, {
72
+ method: "GET",
73
+ headers: { Accept: "application/json" },
74
+ signal: controller.signal,
75
+ });
76
+ if (res.ok) {
77
+ data = normalizeStatusPayload(await res.json(), spec, nowMs);
78
+ }
79
+ } finally {
80
+ clearTimeout(timer);
81
+ }
82
+ } catch (_error) {
83
+ // fall through to last-good handling below
84
+ }
85
+
86
+ if (!data && cached?.data && nowMs - cached.fetchedAtMs < STATUS_LAST_GOOD_MAX_AGE_MS) {
87
+ // Probe failed: keep serving the previous reading (without refreshing its
88
+ // clock, so a dead status page eventually ages out to null).
89
+ return cached.data;
90
+ }
91
+
92
+ statusCache.set(providerId, { data, fetchedAtMs: nowMs });
93
+ return data;
94
+ }
95
+
96
+ function resetProviderStatusCache() {
97
+ statusCache = new Map();
98
+ }
99
+
100
+ module.exports = {
101
+ fetchProviderServiceStatus,
102
+ resetProviderStatusCache,
103
+ STATUS_PAGE_SPECS,
104
+ };