tokenusage-cli 0.1.0 → 0.2.1

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 +46 -19
  2. package/LICENSE +22 -22
  3. package/README.md +123 -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 +210 -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,267 +1,267 @@
1
- // Skill usage analytics — the one angle a token tracker uniquely owns that a
2
- // dedicated skill manager structurally cannot: "which installed skills do I
3
- // actually invoke, and what do they cost?"
4
- //
5
- // Design constraints (deliberate):
6
- // * READ-ONLY and fully DECOUPLED from the token parser. We do NOT touch
7
- // rollout.js / queue.jsonl — editing the incremental parser is this repo's
8
- // documented #1 footgun (it silently shifts token totals). This scanner
9
- // reads ~/.claude transcripts on demand and never writes to the queue.
10
- // * Privacy: only the skill NAME + token counts leave a transcript. Never
11
- // prompts, args, file contents, or message bodies.
12
- // * Claude-only v1: the {type:"tool_use",name:"Skill",input:{skill}} signal is
13
- // a Claude-transcript structure. Other providers have different log shapes;
14
- // generalizing is explicitly out of scope.
15
- // * De-dup invocations by tool_use `id` so a turn duplicated across the main
16
- // session + subagent files is counted once.
17
- // * A turn's usage is split evenly across the Skill blocks it invoked, so the
18
- // sum of per-skill cost == the cost of the invoking turns (no double count).
19
- // This is an approximate "cost of invoking turns", surfaced as such.
20
-
21
- const fs = require("node:fs");
22
- const fssync = require("node:fs");
23
- const os = require("node:os");
24
- const path = require("node:path");
25
- const crypto = require("node:crypto");
26
- const readline = require("node:readline");
27
-
28
- const USAGE_CACHE_TTL_MS = 10 * 60 * 1000; // 10 minutes
29
- const SKILL_TOKEN_KEYS = [
30
- "input_tokens",
31
- "output_tokens",
32
- "cached_input_tokens",
33
- "cache_creation_input_tokens",
34
- "reasoning_output_tokens",
35
- ];
36
-
37
- function claudeProjectsDir(home) {
38
- return path.join(home || os.homedir(), ".claude", "projects");
39
- }
40
-
41
- function dataDir(home) {
42
- return path.join(home || os.homedir(), ".tokenusage", "skills");
43
- }
44
-
45
- function usageCachePath(home) {
46
- return path.join(dataDir(home), "usage-cache.json");
47
- }
48
-
49
- function toInt(value) {
50
- const n = Number(value);
51
- return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
52
- }
53
-
54
- // Same column mapping as the Claude parser's normalizeClaudeUsage, kept local so
55
- // this module never imports the heavy rollout parser.
56
- function normalizeUsage(usage) {
57
- return {
58
- input_tokens: toInt(usage?.input_tokens),
59
- output_tokens: toInt(usage?.output_tokens),
60
- cached_input_tokens: toInt(usage?.cache_read_input_tokens),
61
- cache_creation_input_tokens: toInt(usage?.cache_creation_input_tokens),
62
- reasoning_output_tokens: 0,
63
- };
64
- }
65
-
66
- function emptyTokens() {
67
- return {
68
- input_tokens: 0,
69
- output_tokens: 0,
70
- cached_input_tokens: 0,
71
- cache_creation_input_tokens: 0,
72
- reasoning_output_tokens: 0,
73
- };
74
- }
75
-
76
- function addScaledTokens(target, delta, scale) {
77
- for (const key of SKILL_TOKEN_KEYS) {
78
- target[key] += (delta[key] || 0) * scale;
79
- }
80
- }
81
-
82
- async function listTranscriptFiles(rootDir) {
83
- const out = [];
84
- async function walk(dir) {
85
- let entries;
86
- try {
87
- entries = await fs.promises.readdir(dir, { withFileTypes: true });
88
- } catch (_e) {
89
- return;
90
- }
91
- for (const entry of entries) {
92
- const full = path.join(dir, entry.name);
93
- if (entry.isDirectory()) {
94
- await walk(full);
95
- } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
96
- let stat;
97
- try {
98
- stat = await fs.promises.stat(full);
99
- } catch (_e) {
100
- continue;
101
- }
102
- out.push({ path: full, size: stat.size, mtimeMs: Math.floor(stat.mtimeMs) });
103
- }
104
- }
105
- }
106
- await walk(rootDir);
107
- out.sort((a, b) => a.path.localeCompare(b.path));
108
- return out;
109
- }
110
-
111
- function fingerprintFiles(files) {
112
- const hash = crypto.createHash("sha256");
113
- for (const file of files) hash.update(`${file.path}:${file.size}:${file.mtimeMs}\n`);
114
- return `${files.length}:${hash.digest("hex")}`;
115
- }
116
-
117
- function ensureSkill(map, name) {
118
- let entry = map.get(name);
119
- if (!entry) {
120
- entry = {
121
- skill: name,
122
- invocations: 0,
123
- lastUsedAt: null,
124
- tokens: emptyTokens(),
125
- models: {}, // model -> token columns (for per-model pricing downstream)
126
- };
127
- map.set(name, entry);
128
- }
129
- return entry;
130
- }
131
-
132
- // Scan a single transcript for Skill tool_use blocks. Mutates `skillMap` and the
133
- // shared `seenBlockIds` set (for cross-file de-dup). String pre-filter keeps this
134
- // cheap — most lines never get JSON.parsed.
135
- async function scanFile(filePath, skillMap, seenBlockIds) {
136
- const stream = fssync.createReadStream(filePath, { encoding: "utf8" });
137
- const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
138
- try {
139
- for await (const line of rl) {
140
- if (!line || line.indexOf('"name":"Skill"') === -1) continue;
141
- let obj;
142
- try {
143
- obj = JSON.parse(line);
144
- } catch (_e) {
145
- continue;
146
- }
147
- const message = obj?.message;
148
- const content = message?.content;
149
- if (!Array.isArray(content)) continue;
150
-
151
- // Collect this turn's fresh (not-yet-seen) Skill invocations first so we
152
- // can split the turn's usage evenly across them.
153
- const blocks = [];
154
- for (const block of content) {
155
- if (!block || block.type !== "tool_use" || block.name !== "Skill") continue;
156
- const id = typeof block.id === "string" ? block.id : null;
157
- if (id && seenBlockIds.has(id)) continue;
158
- const skillName = String(block?.input?.skill || "").trim();
159
- if (!skillName) continue;
160
- if (id) seenBlockIds.add(id);
161
- blocks.push({ id, skillName });
162
- }
163
- if (!blocks.length) continue;
164
-
165
- const ts = typeof obj?.timestamp === "string" ? obj.timestamp : null;
166
- const model = String(message?.model || "").trim() || "unknown";
167
- const turnTokens = normalizeUsage(message?.usage);
168
- const share = 1 / blocks.length;
169
-
170
- for (const block of blocks) {
171
- const entry = ensureSkill(skillMap, block.skillName);
172
- entry.invocations += 1;
173
- if (ts && (!entry.lastUsedAt || ts > entry.lastUsedAt)) entry.lastUsedAt = ts;
174
- addScaledTokens(entry.tokens, turnTokens, share);
175
- if (!entry.models[model]) entry.models[model] = emptyTokens();
176
- addScaledTokens(entry.models[model], turnTokens, share);
177
- }
178
- }
179
- } finally {
180
- rl.close();
181
- stream.close?.();
182
- }
183
- }
184
-
185
- function roundTokens(tokens) {
186
- const out = {};
187
- for (const key of SKILL_TOKEN_KEYS) out[key] = Math.round(tokens[key] || 0);
188
- out.total_tokens =
189
- out.input_tokens +
190
- out.output_tokens +
191
- out.cached_input_tokens +
192
- out.cache_creation_input_tokens +
193
- out.reasoning_output_tokens;
194
- return out;
195
- }
196
-
197
- function serialize(skillMap, meta) {
198
- const skills = Array.from(skillMap.values())
199
- .map((entry) => ({
200
- skill: entry.skill,
201
- invocations: entry.invocations,
202
- lastUsedAt: entry.lastUsedAt,
203
- tokens: roundTokens(entry.tokens),
204
- models: Object.fromEntries(
205
- Object.entries(entry.models).map(([model, tokens]) => [model, roundTokens(tokens)]),
206
- ),
207
- }))
208
- .sort((a, b) => b.invocations - a.invocations);
209
- return { ...meta, skills };
210
- }
211
-
212
- // Public entry: scan (or return cached) per-skill invocation + token aggregates.
213
- // `home` override is for tests/sandboxing. Returns raw aggregates keyed by the
214
- // skill name exactly as logged — the caller joins against installed skills and
215
- // applies pricing.
216
- async function scanSkillUsage({ home, force = false } = {}) {
217
- const root = claudeProjectsDir(home);
218
- const files = await listTranscriptFiles(root);
219
- const fingerprint = fingerprintFiles(files);
220
-
221
- if (!force) {
222
- let cached = null;
223
- try {
224
- cached = JSON.parse(fssync.readFileSync(usageCachePath(home), "utf8"));
225
- } catch (_e) {
226
- cached = null;
227
- }
228
- if (
229
- cached &&
230
- cached.fingerprint === fingerprint &&
231
- Number.isFinite(cached.generatedAt) &&
232
- Date.now() - cached.generatedAt < USAGE_CACHE_TTL_MS &&
233
- Array.isArray(cached.skills)
234
- ) {
235
- return { ...cached, cached: true };
236
- }
237
- }
238
-
239
- const skillMap = new Map();
240
- const seenBlockIds = new Set();
241
- for (const file of files) {
242
- await scanFile(file.path, skillMap, seenBlockIds);
243
- }
244
-
245
- const result = serialize(skillMap, {
246
- fingerprint,
247
- generatedAt: Date.now(),
248
- scannedFiles: files.length,
249
- totalInvocations: Array.from(skillMap.values()).reduce((sum, s) => sum + s.invocations, 0),
250
- });
251
-
252
- try {
253
- fssync.mkdirSync(dataDir(home), { recursive: true });
254
- fssync.writeFileSync(usageCachePath(home), `${JSON.stringify(result)}\n`, { mode: 0o600 });
255
- } catch (_e) {
256
- // best-effort cache write
257
- }
258
-
259
- return { ...result, cached: false };
260
- }
261
-
262
- module.exports = {
263
- scanSkillUsage,
264
- // exported for tests
265
- normalizeUsage,
266
- fingerprintFiles,
267
- };
1
+ // Skill usage analytics — the one angle a token tracker uniquely owns that a
2
+ // dedicated skill manager structurally cannot: "which installed skills do I
3
+ // actually invoke, and what do they cost?"
4
+ //
5
+ // Design constraints (deliberate):
6
+ // * READ-ONLY and fully DECOUPLED from the token parser. We do NOT touch
7
+ // rollout.js / queue.jsonl — editing the incremental parser is this repo's
8
+ // documented #1 footgun (it silently shifts token totals). This scanner
9
+ // reads ~/.claude transcripts on demand and never writes to the queue.
10
+ // * Privacy: only the skill NAME + token counts leave a transcript. Never
11
+ // prompts, args, file contents, or message bodies.
12
+ // * Claude-only v1: the {type:"tool_use",name:"Skill",input:{skill}} signal is
13
+ // a Claude-transcript structure. Other providers have different log shapes;
14
+ // generalizing is explicitly out of scope.
15
+ // * De-dup invocations by tool_use `id` so a turn duplicated across the main
16
+ // session + subagent files is counted once.
17
+ // * A turn's usage is split evenly across the Skill blocks it invoked, so the
18
+ // sum of per-skill cost == the cost of the invoking turns (no double count).
19
+ // This is an approximate "cost of invoking turns", surfaced as such.
20
+
21
+ const fs = require("node:fs");
22
+ const fssync = require("node:fs");
23
+ const os = require("node:os");
24
+ const path = require("node:path");
25
+ const crypto = require("node:crypto");
26
+ const readline = require("node:readline");
27
+
28
+ const USAGE_CACHE_TTL_MS = 10 * 60 * 1000; // 10 minutes
29
+ const SKILL_TOKEN_KEYS = [
30
+ "input_tokens",
31
+ "output_tokens",
32
+ "cached_input_tokens",
33
+ "cache_creation_input_tokens",
34
+ "reasoning_output_tokens",
35
+ ];
36
+
37
+ function claudeProjectsDir(home) {
38
+ return path.join(home || os.homedir(), ".claude", "projects");
39
+ }
40
+
41
+ function dataDir(home) {
42
+ return path.join(home || os.homedir(), ".tokenusage", "skills");
43
+ }
44
+
45
+ function usageCachePath(home) {
46
+ return path.join(dataDir(home), "usage-cache.json");
47
+ }
48
+
49
+ function toInt(value) {
50
+ const n = Number(value);
51
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
52
+ }
53
+
54
+ // Same column mapping as the Claude parser's normalizeClaudeUsage, kept local so
55
+ // this module never imports the heavy rollout parser.
56
+ function normalizeUsage(usage) {
57
+ return {
58
+ input_tokens: toInt(usage?.input_tokens),
59
+ output_tokens: toInt(usage?.output_tokens),
60
+ cached_input_tokens: toInt(usage?.cache_read_input_tokens),
61
+ cache_creation_input_tokens: toInt(usage?.cache_creation_input_tokens),
62
+ reasoning_output_tokens: 0,
63
+ };
64
+ }
65
+
66
+ function emptyTokens() {
67
+ return {
68
+ input_tokens: 0,
69
+ output_tokens: 0,
70
+ cached_input_tokens: 0,
71
+ cache_creation_input_tokens: 0,
72
+ reasoning_output_tokens: 0,
73
+ };
74
+ }
75
+
76
+ function addScaledTokens(target, delta, scale) {
77
+ for (const key of SKILL_TOKEN_KEYS) {
78
+ target[key] += (delta[key] || 0) * scale;
79
+ }
80
+ }
81
+
82
+ async function listTranscriptFiles(rootDir) {
83
+ const out = [];
84
+ async function walk(dir) {
85
+ let entries;
86
+ try {
87
+ entries = await fs.promises.readdir(dir, { withFileTypes: true });
88
+ } catch (_e) {
89
+ return;
90
+ }
91
+ for (const entry of entries) {
92
+ const full = path.join(dir, entry.name);
93
+ if (entry.isDirectory()) {
94
+ await walk(full);
95
+ } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
96
+ let stat;
97
+ try {
98
+ stat = await fs.promises.stat(full);
99
+ } catch (_e) {
100
+ continue;
101
+ }
102
+ out.push({ path: full, size: stat.size, mtimeMs: Math.floor(stat.mtimeMs) });
103
+ }
104
+ }
105
+ }
106
+ await walk(rootDir);
107
+ out.sort((a, b) => a.path.localeCompare(b.path));
108
+ return out;
109
+ }
110
+
111
+ function fingerprintFiles(files) {
112
+ const hash = crypto.createHash("sha256");
113
+ for (const file of files) hash.update(`${file.path}:${file.size}:${file.mtimeMs}\n`);
114
+ return `${files.length}:${hash.digest("hex")}`;
115
+ }
116
+
117
+ function ensureSkill(map, name) {
118
+ let entry = map.get(name);
119
+ if (!entry) {
120
+ entry = {
121
+ skill: name,
122
+ invocations: 0,
123
+ lastUsedAt: null,
124
+ tokens: emptyTokens(),
125
+ models: {}, // model -> token columns (for per-model pricing downstream)
126
+ };
127
+ map.set(name, entry);
128
+ }
129
+ return entry;
130
+ }
131
+
132
+ // Scan a single transcript for Skill tool_use blocks. Mutates `skillMap` and the
133
+ // shared `seenBlockIds` set (for cross-file de-dup). String pre-filter keeps this
134
+ // cheap — most lines never get JSON.parsed.
135
+ async function scanFile(filePath, skillMap, seenBlockIds) {
136
+ const stream = fssync.createReadStream(filePath, { encoding: "utf8" });
137
+ const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
138
+ try {
139
+ for await (const line of rl) {
140
+ if (!line || line.indexOf('"name":"Skill"') === -1) continue;
141
+ let obj;
142
+ try {
143
+ obj = JSON.parse(line);
144
+ } catch (_e) {
145
+ continue;
146
+ }
147
+ const message = obj?.message;
148
+ const content = message?.content;
149
+ if (!Array.isArray(content)) continue;
150
+
151
+ // Collect this turn's fresh (not-yet-seen) Skill invocations first so we
152
+ // can split the turn's usage evenly across them.
153
+ const blocks = [];
154
+ for (const block of content) {
155
+ if (!block || block.type !== "tool_use" || block.name !== "Skill") continue;
156
+ const id = typeof block.id === "string" ? block.id : null;
157
+ if (id && seenBlockIds.has(id)) continue;
158
+ const skillName = String(block?.input?.skill || "").trim();
159
+ if (!skillName) continue;
160
+ if (id) seenBlockIds.add(id);
161
+ blocks.push({ id, skillName });
162
+ }
163
+ if (!blocks.length) continue;
164
+
165
+ const ts = typeof obj?.timestamp === "string" ? obj.timestamp : null;
166
+ const model = String(message?.model || "").trim() || "unknown";
167
+ const turnTokens = normalizeUsage(message?.usage);
168
+ const share = 1 / blocks.length;
169
+
170
+ for (const block of blocks) {
171
+ const entry = ensureSkill(skillMap, block.skillName);
172
+ entry.invocations += 1;
173
+ if (ts && (!entry.lastUsedAt || ts > entry.lastUsedAt)) entry.lastUsedAt = ts;
174
+ addScaledTokens(entry.tokens, turnTokens, share);
175
+ if (!entry.models[model]) entry.models[model] = emptyTokens();
176
+ addScaledTokens(entry.models[model], turnTokens, share);
177
+ }
178
+ }
179
+ } finally {
180
+ rl.close();
181
+ stream.close?.();
182
+ }
183
+ }
184
+
185
+ function roundTokens(tokens) {
186
+ const out = {};
187
+ for (const key of SKILL_TOKEN_KEYS) out[key] = Math.round(tokens[key] || 0);
188
+ out.total_tokens =
189
+ out.input_tokens +
190
+ out.output_tokens +
191
+ out.cached_input_tokens +
192
+ out.cache_creation_input_tokens +
193
+ out.reasoning_output_tokens;
194
+ return out;
195
+ }
196
+
197
+ function serialize(skillMap, meta) {
198
+ const skills = Array.from(skillMap.values())
199
+ .map((entry) => ({
200
+ skill: entry.skill,
201
+ invocations: entry.invocations,
202
+ lastUsedAt: entry.lastUsedAt,
203
+ tokens: roundTokens(entry.tokens),
204
+ models: Object.fromEntries(
205
+ Object.entries(entry.models).map(([model, tokens]) => [model, roundTokens(tokens)]),
206
+ ),
207
+ }))
208
+ .sort((a, b) => b.invocations - a.invocations);
209
+ return { ...meta, skills };
210
+ }
211
+
212
+ // Public entry: scan (or return cached) per-skill invocation + token aggregates.
213
+ // `home` override is for tests/sandboxing. Returns raw aggregates keyed by the
214
+ // skill name exactly as logged — the caller joins against installed skills and
215
+ // applies pricing.
216
+ async function scanSkillUsage({ home, force = false } = {}) {
217
+ const root = claudeProjectsDir(home);
218
+ const files = await listTranscriptFiles(root);
219
+ const fingerprint = fingerprintFiles(files);
220
+
221
+ if (!force) {
222
+ let cached = null;
223
+ try {
224
+ cached = JSON.parse(fssync.readFileSync(usageCachePath(home), "utf8"));
225
+ } catch (_e) {
226
+ cached = null;
227
+ }
228
+ if (
229
+ cached &&
230
+ cached.fingerprint === fingerprint &&
231
+ Number.isFinite(cached.generatedAt) &&
232
+ Date.now() - cached.generatedAt < USAGE_CACHE_TTL_MS &&
233
+ Array.isArray(cached.skills)
234
+ ) {
235
+ return { ...cached, cached: true };
236
+ }
237
+ }
238
+
239
+ const skillMap = new Map();
240
+ const seenBlockIds = new Set();
241
+ for (const file of files) {
242
+ await scanFile(file.path, skillMap, seenBlockIds);
243
+ }
244
+
245
+ const result = serialize(skillMap, {
246
+ fingerprint,
247
+ generatedAt: Date.now(),
248
+ scannedFiles: files.length,
249
+ totalInvocations: Array.from(skillMap.values()).reduce((sum, s) => sum + s.invocations, 0),
250
+ });
251
+
252
+ try {
253
+ fssync.mkdirSync(dataDir(home), { recursive: true });
254
+ fssync.writeFileSync(usageCachePath(home), `${JSON.stringify(result)}\n`, { mode: 0o600 });
255
+ } catch (_e) {
256
+ // best-effort cache write
257
+ }
258
+
259
+ return { ...result, cached: false };
260
+ }
261
+
262
+ module.exports = {
263
+ scanSkillUsage,
264
+ // exported for tests
265
+ normalizeUsage,
266
+ fingerprintFiles,
267
+ };