claude-code-cost 1.3.2 → 1.5.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.
package/lib/costs.js ADDED
@@ -0,0 +1,1634 @@
1
+ 'use strict';
2
+
3
+ const path = require('node:path');
4
+ const fs = require('node:fs');
5
+ const { createReadStream } = fs;
6
+ const { createInterface } = require('node:readline');
7
+ const os = require('node:os');
8
+ const { probeUsage, normalizeUsage } = require('./usage-probe');
9
+
10
+ // #region CLI_ARGS
11
+
12
+ function getArg(name) {
13
+ const eqIdx = process.argv.findIndex(a => a === `--${name}` || a.startsWith(`--${name}=`));
14
+ if (eqIdx === -1) return null;
15
+ const arg = process.argv[eqIdx];
16
+ if (arg.includes('=')) return arg.split('=').slice(1).join('=');
17
+ return process.argv[eqIdx + 1] || null;
18
+ }
19
+
20
+ const claudeDirArg = getArg('dir') || process.env.CLAUDE_CONFIG_DIR || process.env.CLAUDE_DIR;
21
+ const DEFAULT_CLAUDE_DIR = path.join(os.homedir(), '.claude');
22
+ const CLAUDE_DIR = claudeDirArg ? claudeDirArg.replace(/^~/, os.homedir()) : DEFAULT_CLAUDE_DIR;
23
+
24
+ const PROJECTS_DIR = path.join(CLAUDE_DIR, 'projects');
25
+ // XDG-style location some builds used for the default profile only. A custom
26
+ // CLAUDE_CONFIG_DIR holds everything itself, so scanning it there would leak
27
+ // the home profile's sessions into the custom one.
28
+ const ALT_PROJECTS_DIR = path.resolve(CLAUDE_DIR) === path.resolve(DEFAULT_CLAUDE_DIR)
29
+ ? path.join(os.homedir(), '.config', 'claude', 'projects')
30
+ : null;
31
+
32
+ function getProjectsDirs() {
33
+ const dirs = [];
34
+ if (fs.existsSync(PROJECTS_DIR)) dirs.push(PROJECTS_DIR);
35
+ if (ALT_PROJECTS_DIR && fs.existsSync(ALT_PROJECTS_DIR)) dirs.push(ALT_PROJECTS_DIR);
36
+ return dirs;
37
+ }
38
+
39
+ // #endregion
40
+
41
+ // #region PRICING
42
+
43
+ const LITELLM_PRICING_URL =
44
+ 'https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json';
45
+
46
+ const PROVIDER_PREFIXES = ['anthropic/', 'claude-3-5-', 'claude-3-', 'claude-'];
47
+ const TIERED_THRESHOLD = 200_000;
48
+ const PRICING_REFRESH_MS = 6 * 60 * 60 * 1000;
49
+
50
+ let cachedPricing = null;
51
+ let pricingFetchedAt = 0;
52
+
53
+ const OFFLINE_PRICING = {
54
+ 'anthropic/claude-sonnet-4-20250514': {
55
+ input_cost_per_token: 3e-6, output_cost_per_token: 1.5e-5,
56
+ cache_creation_input_token_cost: 3.75e-6, cache_read_input_token_cost: 3e-7,
57
+ input_cost_per_token_above_200k_tokens: 6e-6, output_cost_per_token_above_200k_tokens: 2.25e-5,
58
+ cache_creation_input_token_cost_above_200k_tokens: 7.5e-6, cache_read_input_token_cost_above_200k_tokens: 6e-7,
59
+ },
60
+ 'anthropic/claude-opus-4-20250514': {
61
+ input_cost_per_token: 1.5e-5, output_cost_per_token: 7.5e-5,
62
+ cache_creation_input_token_cost: 1.875e-5, cache_read_input_token_cost: 1.5e-6,
63
+ input_cost_per_token_above_200k_tokens: 3e-5, output_cost_per_token_above_200k_tokens: 1.125e-4,
64
+ cache_creation_input_token_cost_above_200k_tokens: 3.75e-5, cache_read_input_token_cost_above_200k_tokens: 3e-6,
65
+ provider_specific_entry: { fast: 6.0 },
66
+ },
67
+ 'anthropic/claude-haiku-4-5-20251001': {
68
+ input_cost_per_token: 8e-7, output_cost_per_token: 4e-6,
69
+ cache_creation_input_token_cost: 1e-6, cache_read_input_token_cost: 8e-8,
70
+ input_cost_per_token_above_200k_tokens: 1.6e-6, output_cost_per_token_above_200k_tokens: 6e-6,
71
+ cache_creation_input_token_cost_above_200k_tokens: 2e-6, cache_read_input_token_cost_above_200k_tokens: 1.6e-7,
72
+ },
73
+ 'anthropic/claude-3-5-sonnet-20241022': {
74
+ input_cost_per_token: 3e-6, output_cost_per_token: 1.5e-5,
75
+ cache_creation_input_token_cost: 3.75e-6, cache_read_input_token_cost: 3e-7,
76
+ },
77
+ 'anthropic/claude-3-5-haiku-20241022': {
78
+ input_cost_per_token: 8e-7, output_cost_per_token: 4e-6,
79
+ cache_creation_input_token_cost: 1e-6, cache_read_input_token_cost: 8e-8,
80
+ },
81
+ };
82
+
83
+ async function fetchPricing() {
84
+ const now = Date.now();
85
+ if (cachedPricing && (now - pricingFetchedAt) < PRICING_REFRESH_MS) return cachedPricing;
86
+
87
+ try {
88
+ console.log('[Pricing] Fetching from LiteLLM...');
89
+ const resp = await fetch(LITELLM_PRICING_URL);
90
+ if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
91
+ const data = await resp.json();
92
+ const pricing = new Map();
93
+ for (const [name, info] of Object.entries(data)) {
94
+ if (typeof info !== 'object' || info == null) continue;
95
+ if (info.input_cost_per_token != null || info.output_cost_per_token != null) {
96
+ pricing.set(name, info);
97
+ }
98
+ }
99
+ cachedPricing = pricing;
100
+ pricingFetchedAt = now;
101
+ console.log(`[Pricing] Loaded ${pricing.size} models`);
102
+ return pricing;
103
+ } catch (err) {
104
+ console.warn('[Pricing] Fetch failed, using offline fallback:', err.message);
105
+ if (!cachedPricing) {
106
+ cachedPricing = new Map(Object.entries(OFFLINE_PRICING));
107
+ pricingFetchedAt = now;
108
+ }
109
+ return cachedPricing;
110
+ }
111
+ }
112
+
113
+ function getModelPricing(pricing, modelName) {
114
+ if (!modelName) return null;
115
+
116
+ // Exact match
117
+ const direct = pricing.get(modelName);
118
+ if (direct) return direct;
119
+
120
+ // Try with provider prefixes
121
+ for (const prefix of PROVIDER_PREFIXES) {
122
+ const candidate = pricing.get(`${prefix}${modelName}`);
123
+ if (candidate) return candidate;
124
+ }
125
+
126
+ // Fuzzy lowercase match
127
+ const lower = modelName.toLowerCase();
128
+ for (const [key, value] of pricing) {
129
+ const cmp = key.toLowerCase();
130
+ if (cmp.includes(lower) || lower.includes(cmp)) return value;
131
+ }
132
+
133
+ return null;
134
+ }
135
+
136
+ function calculateTieredCost(totalTokens, basePrice, tieredPrice, threshold = TIERED_THRESHOLD) {
137
+ if (!totalTokens || totalTokens <= 0) return 0;
138
+ if (totalTokens > threshold && tieredPrice != null) {
139
+ const below = Math.min(totalTokens, threshold);
140
+ const above = Math.max(0, totalTokens - threshold);
141
+ let cost = above * tieredPrice;
142
+ if (basePrice != null) cost += below * basePrice;
143
+ return cost;
144
+ }
145
+ if (basePrice != null) return totalTokens * basePrice;
146
+ return 0;
147
+ }
148
+
149
+ function calculateCost(tokens, modelPricing) {
150
+ const inputCost = calculateTieredCost(
151
+ tokens.input_tokens, modelPricing.input_cost_per_token,
152
+ modelPricing.input_cost_per_token_above_200k_tokens);
153
+ const outputCost = calculateTieredCost(
154
+ tokens.output_tokens, modelPricing.output_cost_per_token,
155
+ modelPricing.output_cost_per_token_above_200k_tokens);
156
+ const cacheCreationCost = calculateTieredCost(
157
+ tokens.cache_creation_input_tokens, modelPricing.cache_creation_input_token_cost,
158
+ modelPricing.cache_creation_input_token_cost_above_200k_tokens);
159
+ const cacheReadCost = calculateTieredCost(
160
+ tokens.cache_read_input_tokens, modelPricing.cache_read_input_token_cost,
161
+ modelPricing.cache_read_input_token_cost_above_200k_tokens);
162
+ return inputCost + outputCost + cacheCreationCost + cacheReadCost;
163
+ }
164
+
165
+ function calculateCostForModel(tokens, modelName, pricing, speed) {
166
+ const mp = getModelPricing(pricing, modelName);
167
+ if (!mp) return 0;
168
+ const baseCost = calculateCost(tokens, mp);
169
+ const multiplier = speed === 'fast' ? (mp.provider_specific_entry?.fast ?? 1) : 1;
170
+ return baseCost * multiplier;
171
+ }
172
+
173
+ // #endregion
174
+
175
+ // #region JSONL_PARSING
176
+
177
+ async function processJSONLFile(filePath, processLine) {
178
+ const fileStream = createReadStream(filePath, { encoding: 'utf-8' });
179
+ const rl = createInterface({ input: fileStream, crlfDelay: Infinity });
180
+ let lineNumber = 0;
181
+ for await (const line of rl) {
182
+ lineNumber++;
183
+ if (line.trim().length === 0) continue;
184
+ await processLine(line, lineNumber);
185
+ }
186
+ }
187
+
188
+
189
+ function createDedupeHash(data) {
190
+ const mid = data.message?.id;
191
+ const rid = data.requestId;
192
+ if (!mid || !rid) return null;
193
+ return `${mid}:${rid}`;
194
+ }
195
+
196
+ function extractTools(content) {
197
+ if (!Array.isArray(content)) return null;
198
+ const tools = content
199
+ .filter(c => c.type === 'tool_use' && c.name)
200
+ .map(c => c.name);
201
+ return tools.length > 0 ? tools : null;
202
+ }
203
+
204
+ function calculateEntryCost(data, pricing) {
205
+ // Auto mode: use costUSD if present, otherwise calculate
206
+ if (data.costUSD != null) return data.costUSD;
207
+ const model = data.message?.model;
208
+ if (!model) return 0;
209
+ const speed = data.message?.usage?.speed;
210
+ return calculateCostForModel(data.message.usage, model, pricing, speed);
211
+ }
212
+
213
+ // The summarization call behind a compact_boundary is not logged with usage, so its cost is an
214
+ // estimate: the whole pre-compaction context read from cache, and a summary no larger than the
215
+ // post-compaction context written out.
216
+ function estimateCompactionCost(meta, model, pricing) {
217
+ return calculateCostForModel(
218
+ { output_tokens: meta.postTokens, cache_read_input_tokens: meta.preTokens },
219
+ model, pricing);
220
+ }
221
+
222
+ function compactionFacts(parsed) {
223
+ const meta = parsed.compactMetadata || {};
224
+ const preTokens = meta.preTokens || 0;
225
+ const postTokens = meta.postTokens || 0;
226
+ return {
227
+ timestamp: parsed.timestamp,
228
+ trigger: meta.trigger || 'unknown',
229
+ preTokens,
230
+ postTokens,
231
+ droppedTokens: Math.max(0, preTokens - postTokens),
232
+ durationMs: meta.durationMs || 0,
233
+ };
234
+ }
235
+
236
+ // The first turn after a boundary rebuilds the prompt cache from the summary, so its cache
237
+ // creation is spend the compaction caused. It is already in the session total; the record only
238
+ // attributes it. Models without pricing get null, not a zero that reads as "free".
239
+ function priceCompaction(facts, msg, pricing) {
240
+ const model = isRealModel(msg.model) ? msg.model : null;
241
+ return {
242
+ ...facts,
243
+ estCost: model ? estimateCompactionCost(facts, model, pricing) : null,
244
+ rewarmTokens: msg.cacheCreationTokens,
245
+ rewarmCost: model
246
+ ? calculateCostForModel({ cache_creation_input_tokens: msg.cacheCreationTokens }, model, pricing, msg.speed)
247
+ : null,
248
+ };
249
+ }
250
+
251
+ // #endregion
252
+
253
+ // #region DATA_AGGREGATION
254
+
255
+ const CACHE_TTL = 30_000;
256
+
257
+ // Custom from/to windows make the key space unbounded, so the cache is capped, which would
258
+ // otherwise grow for the process lifetime. A Map keeps insertion order, so the oldest write is
259
+ // always the first key — no sort, no key array.
260
+ const MAX_CACHE_ENTRIES = 50;
261
+ const dataCache = new Map();
262
+
263
+ // undefined means "no usable entry": every cached payload is an object or an array, so it can
264
+ // never collide with a real one. A stale hit is dropped here rather than left resident until the
265
+ // cap pushes it out — detail_<id> entries carry a whole message array.
266
+ function getCache(key) {
267
+ const hit = dataCache.get(key);
268
+ if (!hit) return undefined;
269
+ if ((Date.now() - hit.ts) >= CACHE_TTL) {
270
+ dataCache.delete(key);
271
+ return undefined;
272
+ }
273
+ return hit.data;
274
+ }
275
+
276
+ function setCache(key, data) {
277
+ // Re-inserting moves an existing key to the back, so a rewrite resets its eviction priority.
278
+ dataCache.delete(key);
279
+ dataCache.set(key, { data, ts: Date.now() });
280
+ while (dataCache.size > MAX_CACHE_ENTRIES) {
281
+ dataCache.delete(dataCache.keys().next().value);
282
+ }
283
+ }
284
+
285
+ function invalidateAllCache() {
286
+ dataCache.clear();
287
+ }
288
+
289
+ function localDateStr(d) {
290
+ const y = d.getFullYear();
291
+ const m = String(d.getMonth() + 1).padStart(2, '0');
292
+ const day = String(d.getDate()).padStart(2, '0');
293
+ return `${y}-${m}-${day}`;
294
+ }
295
+
296
+ function localHourStr(d) {
297
+ return `${localDateStr(d)}T${String(d.getHours()).padStart(2, '0')}`;
298
+ }
299
+
300
+ // Cost is bucketed by one of these; the key doubles as the aggregation key and the wire label.
301
+ // An hour key extends the day key (YYYY-MM-DD -> YYYY-MM-DDTHH), so a startsWith test on a day
302
+ // string matches either granularity.
303
+ const BUCKETS = {
304
+ day: {
305
+ key: localDateStr,
306
+ floor: (d) => d.setHours(0, 0, 0, 0),
307
+ next: (d) => d.setDate(d.getDate() + 1),
308
+ },
309
+ hour: {
310
+ key: localHourStr,
311
+ floor: (d) => d.setMinutes(0, 0, 0),
312
+ next: (d) => d.setHours(d.getHours() + 1),
313
+ },
314
+ };
315
+
316
+ // A one-day window collapses the daily chart into a single bar, so those ranges bucket by hour.
317
+ function rangeBucket(range) {
318
+ if (isCustomRange(range)) return range.from === range.to ? 'hour' : 'day';
319
+ return range === 'today' || range === '24h' || range === 1 ? 'hour' : 'day';
320
+ }
321
+
322
+ // Non-real (synthetic) models group under 'other' so the series still sums to the true
323
+ // bucket total, unlike modelDistribution which drops them entirely.
324
+ function addBucketModelCost(acc, key, model, cost) {
325
+ const mk = isRealModel(model) ? model : 'other';
326
+ acc[key] ||= {};
327
+ acc[key][mk] = (acc[key][mk] || 0) + cost;
328
+ }
329
+
330
+ // Gap-filled so empty buckets stay visible in the chart. The bucket total is derived from
331
+ // the per-model map, so the two can never disagree.
332
+ function buildCostSeries(modelCostsByBucket, start, end, bucket) {
333
+ const b = BUCKETS[bucket];
334
+ const points = [];
335
+ if (Object.keys(modelCostsByBucket).length === 0) return points;
336
+ const d = new Date(start);
337
+ b.floor(d);
338
+ for (; d <= end; b.next(d)) {
339
+ const k = b.key(d);
340
+ const byModel = modelCostsByBucket[k] || {};
341
+ points.push({ key: k, cost: Object.values(byModel).reduce((s, v) => s + v, 0), byModel });
342
+ }
343
+ return points;
344
+ }
345
+
346
+ function buildModelDistribution(modelCosts) {
347
+ return Object.entries(modelCosts)
348
+ .filter(([model, cost]) => cost > 0 && isRealModel(model))
349
+ .map(([model, cost]) => ({ model, cost }))
350
+ .sort((a, b) => b.cost - a.cost);
351
+ }
352
+
353
+ // onlyKey narrows the scan to encoded project dirs, comma-separated: a repo and its linked
354
+ // worktrees are separate dirs. The dir name *is* the key, so this skips the per-project readdir
355
+ // and per-file statSync for everything else.
356
+ function scanProjectDirs(cutoffDate, onlyKey) {
357
+ const projects = new Map();
358
+ const cutoffMs = cutoffDate ? cutoffDate.getTime() : 0;
359
+ const only = onlyKey ? new Set(onlyKey.split(',')) : null;
360
+ for (const baseDir of getProjectsDirs()) {
361
+ try {
362
+ const entries = fs.readdirSync(baseDir, { withFileTypes: true });
363
+ for (const entry of entries) {
364
+ if (!entry.isDirectory()) continue;
365
+ if (only && !only.has(entry.name)) continue;
366
+ const projDir = path.join(baseDir, entry.name);
367
+ const files = [];
368
+ try {
369
+ for (const f of fs.readdirSync(projDir)) {
370
+ if (!f.endsWith('.jsonl')) continue;
371
+ const filePath = path.join(projDir, f);
372
+ // Skip files not modified since cutoff date
373
+ if (cutoffMs) {
374
+ try {
375
+ const mtime = fs.statSync(filePath).mtimeMs;
376
+ if (mtime < cutoffMs) continue;
377
+ } catch { continue; }
378
+ }
379
+ files.push(filePath);
380
+ }
381
+ } catch { /* ignore */ }
382
+ if (files.length > 0) {
383
+ const key = entry.name;
384
+ if (!projects.has(key)) {
385
+ projects.set(key, { encodedPath: key, dir: projDir, files });
386
+ } else {
387
+ projects.get(key).files.push(...files);
388
+ }
389
+ }
390
+ }
391
+ } catch { /* dir doesn't exist */ }
392
+ }
393
+ return projects;
394
+ }
395
+
396
+ function decodeProjectPath(encoded) {
397
+ try {
398
+ // Claude encodes paths as: C--Users-name-dev-project
399
+ // "C--" = drive prefix, then "-" separates path segments
400
+ // But hyphens in actual folder names also become "-" (ambiguous)
401
+ // Strategy: strip known prefixes to reveal project name
402
+ let name = encoded;
403
+ // Strip drive + common base paths: C--Users-username-dev- or similar
404
+ name = name.replace(/^[A-Z]--[^-]+-[^-]+-(dev|src|repos|projects|work|code)-/, '');
405
+ // Strip C--Users-username--config- or C--Users-username--claude- patterns
406
+ name = name.replace(/^[A-Z]--[^-]+-[^-]+--([^-]+)-/, '$1/');
407
+ // Strip C--Users-username- if still there
408
+ name = name.replace(/^[A-Z]--[^-]+-[^-]+-/, '');
409
+ return name || encoded;
410
+ } catch { return encoded; }
411
+ }
412
+
413
+ // The folder name is lossy (separators and hyphens both become "-"), so the cwd a transcript
414
+ // records names the project; the decode is the fallback for folders with no cwd line.
415
+ const CWD_RE = /"cwd":"((?:[^"\\]|\\.)*)"/;
416
+ const projectNames = new Map();
417
+
418
+ function readCwd(filePath) {
419
+ let fd;
420
+ try {
421
+ fd = fs.openSync(filePath, 'r');
422
+ const buf = Buffer.alloc(64 * 1024);
423
+ const n = fs.readSync(fd, buf, 0, buf.length, 0);
424
+ const m = buf.toString('utf-8', 0, n).match(CWD_RE);
425
+ return m ? JSON.parse(`"${m[1]}"`) : null;
426
+ } catch { return null; } finally {
427
+ if (fd !== undefined) fs.closeSync(fd);
428
+ }
429
+ }
430
+
431
+ function projectName(encodedPath, files) {
432
+ if (projectNames.has(encodedPath)) return projectNames.get(encodedPath);
433
+ const cwd = files.slice(0, 3).map(readCwd).find(Boolean);
434
+ if (!cwd) return decodeProjectPath(encodedPath);
435
+ const name = cwd.split(/[\\/]/).filter(Boolean).pop() || decodeProjectPath(encodedPath);
436
+ projectNames.set(encodedPath, name);
437
+ return name;
438
+ }
439
+
440
+ function getSessionIdFromFile(filePath) {
441
+ return path.basename(filePath, '.jsonl');
442
+ }
443
+
444
+ function readdirSafe(dir) {
445
+ try { return fs.readdirSync(dir, { withFileTypes: true }); } catch { return []; }
446
+ }
447
+
448
+ // Agents sit at subagents/agent-*.jsonl, but a Workflow run nests its own under
449
+ // subagents/workflows/<wfId>/ — and a workflow that starts a workflow nests deeper still, so walk
450
+ // rather than hard-code the depth. Descending only into a listed entry also keeps the common
451
+ // no-workflow session at one readdir.
452
+ function collectAgents(dir, workflowId, out) {
453
+ for (const e of readdirSafe(dir)) {
454
+ if (e.isDirectory()) {
455
+ if (e.name !== 'workflows') continue;
456
+ const runsDir = path.join(dir, e.name);
457
+ for (const run of readdirSafe(runsDir)) {
458
+ if (run.isDirectory()) collectAgents(path.join(runsDir, run.name), run.name, out);
459
+ }
460
+ continue;
461
+ }
462
+ // A workflow run also drops its journal.jsonl next to the agents; only `agent-*.jsonl` is a
463
+ // transcript, and counting the journal inflated the run's agent count by one and stretched its
464
+ // span, since a file with no priced turns falls back to the session's own start time.
465
+ if (!e.name.startsWith('agent-') || !e.name.endsWith('.jsonl')) continue;
466
+ const agentId = e.name.replace('.jsonl', '');
467
+ let meta = {};
468
+ try { meta = JSON.parse(fs.readFileSync(path.join(dir, `${agentId}.meta.json`), 'utf-8')); } catch { /* no meta */ }
469
+ out.push({
470
+ agentId,
471
+ filePath: path.join(dir, e.name),
472
+ agentType: meta.agentType || 'unknown',
473
+ description: meta.description || '',
474
+ workflowId,
475
+ });
476
+ }
477
+ }
478
+
479
+ function scanSubagentDir(sessionDir) {
480
+ const result = [];
481
+ collectAgents(path.join(sessionDir, 'subagents'), null, result);
482
+ return result;
483
+ }
484
+
485
+ // The run's script is saved as <name>-<wfId>.js under a session dir keyed by the workflow's cwd,
486
+ // which need not be the project the session file lives in — so the session's own project dir is
487
+ // only the likely home, and a miss falls back to sweeping the rest.
488
+ function findWorkflowNames(sessionId, wantedIds, likelyProjectDir) {
489
+ const names = new Map();
490
+ const wanted = new Set(wantedIds);
491
+ const scan = (projectDir) => {
492
+ for (const f of readdirSafe(path.join(projectDir, sessionId, 'workflows', 'scripts'))) {
493
+ const m = f.name.match(/^(.*)-(wf_.+)\.js$/);
494
+ if (m && wanted.has(m[2])) names.set(m[2], m[1]);
495
+ }
496
+ return names.size === wanted.size;
497
+ };
498
+ for (const baseDir of getProjectsDirs()) {
499
+ if (scan(path.join(baseDir, likelyProjectDir))) return names;
500
+ }
501
+ for (const baseDir of getProjectsDirs()) {
502
+ for (const e of readdirSafe(baseDir)) {
503
+ if (e.isDirectory() && e.name !== likelyProjectDir && scan(path.join(baseDir, e.name))) return names;
504
+ }
505
+ }
506
+ return names;
507
+ }
508
+
509
+ // `<synthetic>` and friends are Claude Code bookkeeping entries, not models the user chose.
510
+ function isRealModel(model) {
511
+ return !!model && !model.startsWith('<');
512
+ }
513
+
514
+ function mostFrequentModel(counts) {
515
+ return Object.entries(counts).sort((a, b) => b[1] - a[1])[0]?.[0] || 'unknown';
516
+ }
517
+
518
+ // An agent log writes one line per streamed content block, each carrying the usage as it stood
519
+ // then, so a turn's first line can report one output token and its last the whole reply: the
520
+ // turn is the largest usage logged for its (message.id, requestId). The session log repeats the
521
+ // final usage on every line, which is why first-wins reads the same there.
522
+ // Session and project loads read every agent log for its totals alone, so tools are opt-in.
523
+ async function readAgentTurns(filePath, pricing, { withTools = false } = {}) {
524
+ const kept = new Map();
525
+ const unhashed = [];
526
+ await processJSONLFile(filePath, async (line) => {
527
+ let parsed;
528
+ try { parsed = JSON.parse(line); } catch { return; }
529
+ const usage = parsed.message?.usage;
530
+ if (!usage?.input_tokens && usage?.input_tokens !== 0) return;
531
+ if (!parsed.timestamp) return;
532
+
533
+ // Only what the turn needs: `parsed` also holds the turn's content blocks.
534
+ const entry = { costUSD: parsed.costUSD, timestamp: parsed.timestamp, message: { model: parsed.message.model, usage }, tools: null };
535
+ const tools = withTools ? extractTools(parsed.message?.content) : null;
536
+ const hash = createDedupeHash(parsed);
537
+ if (!hash) { entry.tools = tools; unhashed.push(entry); return; }
538
+ const prev = kept.get(hash);
539
+ const allTools = prev?.tools && tools ? prev.tools.concat(tools) : prev?.tools || tools;
540
+ if (!prev || (usage.output_tokens || 0) > (prev.message.usage.output_tokens || 0)) kept.set(hash, entry);
541
+ kept.get(hash).tools = allTools;
542
+ });
543
+ return [...kept.values(), ...unhashed].map(e => ({
544
+ cost: calculateEntryCost(e, pricing),
545
+ inputTokens: e.message.usage.input_tokens || 0,
546
+ outputTokens: e.message.usage.output_tokens || 0,
547
+ cacheCreationTokens: e.message.usage.cache_creation_input_tokens || 0,
548
+ cacheReadTokens: e.message.usage.cache_read_input_tokens || 0,
549
+ speed: e.message.usage.speed || 'standard',
550
+ model: e.message.model || 'unknown',
551
+ timestamp: e.timestamp,
552
+ tools: e.tools,
553
+ }));
554
+ }
555
+
556
+ const SKILL_TEXT_MAX = 200;
557
+
558
+ // Claude Code cuts a forked skill's description in its .meta.json. The parent's Skill call holds
559
+ // the full args, and the call's result names the agent it started.
560
+ function noteSkillAgent(parsed, calls, texts) {
561
+ const content = parsed.message?.content;
562
+ if (!Array.isArray(content)) return;
563
+ if (parsed.type === 'assistant') {
564
+ for (const b of content) {
565
+ if (b.type === 'tool_use' && b.name === 'Skill' && b.input?.skill) {
566
+ const text = `/${b.input.skill} ${b.input.args || ''}`.replace(/\s+/g, ' ').trim();
567
+ calls.set(b.id, { skill: b.input.skill, text: text.length > SKILL_TEXT_MAX ? `${text.slice(0, SKILL_TEXT_MAX - 1)}…` : text });
568
+ }
569
+ }
570
+ return;
571
+ }
572
+ const agentId = parsed.toolUseResult?.agentId;
573
+ if (!agentId) return;
574
+ const call = calls.get(content.find(b => b.type === 'tool_result')?.tool_use_id);
575
+ if (call) texts.set(`agent-${agentId}`, call);
576
+ }
577
+
578
+ async function loadSubagentData(subagentInfos, pricing) {
579
+ return Promise.all(subagentInfos.map(async (info) => {
580
+ const agent = {
581
+ agentId: info.agentId,
582
+ agentType: info.agentType,
583
+ description: info.description,
584
+ workflowId: info.workflowId || null,
585
+ totalCost: 0,
586
+ inputTokens: 0, outputTokens: 0,
587
+ cacheCreationTokens: 0, cacheReadTokens: 0,
588
+ messageCount: 0,
589
+ models: new Set(),
590
+ firstTimestamp: null,
591
+ lastTimestamp: null,
592
+ };
593
+ const turns = await readAgentTurns(info.filePath, pricing);
594
+ Object.assign(agent, summarizeMessages(turns));
595
+ for (const t of turns) {
596
+ agent.models.add(t.model);
597
+ if (!agent.firstTimestamp || t.timestamp < agent.firstTimestamp) agent.firstTimestamp = t.timestamp;
598
+ if (!agent.lastTimestamp || t.timestamp > agent.lastTimestamp) agent.lastTimestamp = t.timestamp;
599
+ }
600
+ agent.models = [...agent.models];
601
+ return agent;
602
+ }));
603
+ }
604
+
605
+ async function loadProjectData(files, pricing) {
606
+ const sessions = new Map();
607
+ // hash -> pushed message, so tool_use blocks from duplicate lines can be folded in.
608
+ const seen = new Map();
609
+
610
+ for (const file of files) {
611
+ const sessionId = getSessionIdFromFile(file);
612
+ if (!sessions.has(sessionId)) {
613
+ sessions.set(sessionId, {
614
+ sessionId,
615
+ totalCost: 0,
616
+ inputTokens: 0, outputTokens: 0,
617
+ cacheCreationTokens: 0, cacheReadTokens: 0,
618
+ messages: [],
619
+ models: new Set(),
620
+ firstPrompt: '',
621
+ customTitle: null,
622
+ firstTimestamp: null,
623
+ lastTimestamp: null,
624
+ });
625
+ }
626
+ const session = sessions.get(sessionId);
627
+ // A boundary is attributed to the next counted turn, so the message list is the only record
628
+ // of compactions; a boundary with no turn after it has nothing to price and is dropped.
629
+ let pendingCompaction = null;
630
+ const skillCalls = new Map();
631
+ const skillAgents = new Map();
632
+
633
+ await processJSONLFile(file, async (line) => {
634
+ let parsed;
635
+ try { parsed = JSON.parse(line); } catch { return; }
636
+
637
+ noteSkillAgent(parsed, skillCalls, skillAgents);
638
+
639
+ if (parsed.type === 'custom-title' && parsed.customTitle) {
640
+ session.customTitle = parsed.customTitle;
641
+ return;
642
+ }
643
+
644
+ if (parsed.type === 'system' && parsed.subtype === 'compact_boundary' && parsed.timestamp) {
645
+ pendingCompaction = compactionFacts(parsed);
646
+ return;
647
+ }
648
+
649
+ if (!parsed.message?.usage?.input_tokens && parsed.message?.usage?.input_tokens !== 0) return;
650
+ if (!parsed.timestamp) return;
651
+
652
+ const hash = createDedupeHash(parsed);
653
+ if (hash && seen.has(hash)) {
654
+ // Streaming writes one JSONL line per content block of the same API message. Usage is
655
+ // identical on every line (deduped), but each line carries different tool_use blocks,
656
+ // so tools must be unioned across duplicates or most calls are lost.
657
+ const dupTools = extractTools(parsed.message?.content);
658
+ if (dupTools) {
659
+ const orig = seen.get(hash);
660
+ orig.tools = (orig.tools || []).concat(dupTools);
661
+ }
662
+ return;
663
+ }
664
+
665
+ const cost = calculateEntryCost(parsed, pricing);
666
+ const usage = parsed.message.usage;
667
+ const model = parsed.message?.model || 'unknown';
668
+ const ts = parsed.timestamp;
669
+
670
+ session.totalCost += cost;
671
+ session.inputTokens += usage.input_tokens || 0;
672
+ session.outputTokens += usage.output_tokens || 0;
673
+ session.cacheCreationTokens += (usage.cache_creation_input_tokens || 0);
674
+ session.cacheReadTokens += (usage.cache_read_input_tokens || 0);
675
+ if (isRealModel(model)) session.models.add(model);
676
+
677
+ if (!session.firstTimestamp || ts < session.firstTimestamp) session.firstTimestamp = ts;
678
+ if (!session.lastTimestamp || ts > session.lastTimestamp) session.lastTimestamp = ts;
679
+
680
+ const msg = {
681
+ timestamp: ts,
682
+ model,
683
+ cost,
684
+ inputTokens: usage.input_tokens || 0,
685
+ outputTokens: usage.output_tokens || 0,
686
+ cacheCreationTokens: usage.cache_creation_input_tokens || 0,
687
+ cacheReadTokens: usage.cache_read_input_tokens || 0,
688
+ speed: usage.speed || 'standard',
689
+ tools: extractTools(parsed.message?.content),
690
+ };
691
+ if (pendingCompaction) {
692
+ msg.compaction = priceCompaction(pendingCompaction, msg, pricing);
693
+ pendingCompaction = null;
694
+ }
695
+ session.messages.push(msg);
696
+ if (hash) seen.set(hash, msg);
697
+
698
+ // Capture first user prompt from the JSONL (look for human/user messages)
699
+ if (!session.firstPrompt && parsed.type === 'human' && parsed.message?.content) {
700
+ const content = Array.isArray(parsed.message.content)
701
+ ? parsed.message.content.map(c => c.text || '').join(' ')
702
+ : (typeof parsed.message.content === 'string' ? parsed.message.content : '');
703
+ if (content.trim()) {
704
+ session.firstPrompt = content.trim().slice(0, 120);
705
+ }
706
+ }
707
+ });
708
+
709
+ // Fold subagent costs into session totals
710
+ const sessionDir = path.join(path.dirname(file), sessionId);
711
+ const subagentInfos = scanSubagentDir(sessionDir);
712
+ if (subagentInfos.length > 0) {
713
+ const subagents = await loadSubagentData(subagentInfos, pricing);
714
+ for (const sa of subagents) {
715
+ // An agent log with no priced turns — empty, truncated, or a crash before the first
716
+ // response — would fold in as a zero-cost message dated at the session's own start,
717
+ // which stretches every span it lands in.
718
+ if (sa.messageCount === 0) continue;
719
+ const skill = skillAgents.get(sa.agentId);
720
+ session.totalCost += sa.totalCost;
721
+ session.inputTokens += sa.inputTokens;
722
+ session.outputTokens += sa.outputTokens;
723
+ session.cacheCreationTokens += sa.cacheCreationTokens;
724
+ session.cacheReadTokens += sa.cacheReadTokens;
725
+ for (const m of sa.models) if (isRealModel(m)) session.models.add(m);
726
+ session.messages.push({
727
+ timestamp: sa.firstTimestamp || session.firstTimestamp,
728
+ model: sa.models[0] || 'unknown',
729
+ cost: sa.totalCost,
730
+ inputTokens: sa.inputTokens,
731
+ outputTokens: sa.outputTokens,
732
+ cacheCreationTokens: sa.cacheCreationTokens,
733
+ cacheReadTokens: sa.cacheReadTokens,
734
+ speed: 'standard',
735
+ _subagent: { agentId: sa.agentId, agentType: sa.agentType, skill: skill?.skill || null, description: skill?.text || sa.description, messageCount: sa.messageCount, workflowId: sa.workflowId, lastTimestamp: sa.lastTimestamp },
736
+ });
737
+ }
738
+ }
739
+ }
740
+
741
+ return sessions;
742
+ }
743
+
744
+ // A range is either a preset — 'today', '24h', the last N calendar days, or null for all time, all
745
+ // anchored to the request — or a custom window of two local YYYY-MM-DD dates.
746
+ function isCustomRange(range) {
747
+ return !!range && typeof range === 'object' && !!range.from && !!range.to;
748
+ }
749
+
750
+ function localDayStart(dateStr) {
751
+ const [y, m, d] = dateStr.split('-').map(Number);
752
+ return new Date(y, m - 1, d, 0, 0, 0, 0);
753
+ }
754
+
755
+ // `to` names a whole day, so the window runs through the end of it — a midnight bound would
756
+ // silently drop that day's data.
757
+ function localDayEnd(dateStr) {
758
+ const d = localDayStart(dateStr);
759
+ d.setHours(23, 59, 59, 999);
760
+ return d;
761
+ }
762
+
763
+ function rangeToCutoff(range, now) {
764
+ if (isCustomRange(range)) return localDayStart(range.from);
765
+ if (range === 'today') {
766
+ const c = new Date(now);
767
+ c.setHours(0, 0, 0, 0);
768
+ return c;
769
+ }
770
+ // The one rolling preset left, and the reason it is labelled in hours: no midnight snap, so it
771
+ // spans two calendar days.
772
+ if (range === '24h') return new Date(now.getTime() - 24 * 60 * 60 * 1000);
773
+ if (!range) return null;
774
+ // N calendar days ending today: identical to from=today-(N-1)&to=today, so the chart draws
775
+ // exactly N buckets instead of N+1 with a partial leading one.
776
+ const c = new Date(now);
777
+ c.setDate(c.getDate() - (range - 1));
778
+ c.setHours(0, 0, 0, 0);
779
+ return c;
780
+ }
781
+
782
+ // The window's upper bound, which used to be an implicit `now` in six places. Presets are rolling,
783
+ // so theirs still is; a custom window ends with its `to` day.
784
+ function rangeToEnd(range, now) {
785
+ return isCustomRange(range) ? localDayEnd(range.to) : new Date(now);
786
+ }
787
+
788
+ // Presets keep an open upper bound: they end at "whenever this request lands", so filtering
789
+ // against a captured `now` would only ever drop rows a live session wrote mid-request.
790
+ function windowEndStr(range, windowEnd) {
791
+ return isCustomRange(range) ? windowEnd.toISOString() : null;
792
+ }
793
+
794
+ // True when today falls inside the window. A null cutoff means open toward the past.
795
+ function windowContainsToday(cutoff, windowEnd, now) {
796
+ const todayStr = localDateStr(now);
797
+ return (!cutoff || localDateStr(cutoff) <= todayStr) && localDateStr(windowEnd) >= todayStr;
798
+ }
799
+
800
+ // Everything a range resolves to, anchored to one captured `now` so the bounds of a single request
801
+ // can never disagree with each other. `cutoff` stays null for the all-time range.
802
+ function resolveWindow(range, now = new Date()) {
803
+ const cutoff = rangeToCutoff(range, now);
804
+ const end = rangeToEnd(range, now);
805
+ return {
806
+ now, cutoff, end,
807
+ cutoffStr: cutoff ? cutoff.toISOString() : null,
808
+ endStr: windowEndStr(range, end),
809
+ hasToday: windowContainsToday(cutoff, end, now),
810
+ };
811
+ }
812
+
813
+ const byTimestamp = (a, b) => a.timestamp.localeCompare(b.timestamp);
814
+
815
+ // Two-sided when the window has an end, so a window that stops in the past excludes later
816
+ // messages. A null bound means open in that direction.
817
+ function filterWindow(messages, fromStr, toStr) {
818
+ if (!fromStr && !toStr) return messages;
819
+ return messages.filter((m) => (!fromStr || m.timestamp >= fromStr) && (!toStr || m.timestamp <= toStr));
820
+ }
821
+
822
+ // Custom windows key by their dates, which is why the cache is capped (see MAX_CACHE_ENTRIES).
823
+ function rangeKey(range) {
824
+ if (isCustomRange(range)) return `${range.from}_${range.to}`;
825
+ return range || 'all';
826
+ }
827
+
828
+ // True when the window is exactly today — a preset 'today' or a single-day pick landing on it.
829
+ function isTodayRange(range, now) {
830
+ if (isCustomRange(range)) return range.from === range.to && range.to === localDateStr(now);
831
+ return range === 'today';
832
+ }
833
+
834
+ function summarizeMessages(msgs) {
835
+ const sum = { messageCount: msgs.length, totalCost: 0, inputTokens: 0, outputTokens: 0, cacheCreationTokens: 0, cacheReadTokens: 0 };
836
+ for (const m of msgs) {
837
+ sum.totalCost += m.cost;
838
+ sum.inputTokens += m.inputTokens;
839
+ sum.outputTokens += m.outputTokens;
840
+ sum.cacheCreationTokens += m.cacheCreationTokens;
841
+ sum.cacheReadTokens += m.cacheReadTokens;
842
+ }
843
+ return sum;
844
+ }
845
+
846
+ function summarizeCompactions(msgs) {
847
+ const sum = { count: 0, auto: 0, totalCost: 0, estCost: 0, rewarmCost: 0, rewarmTokens: 0, droppedTokens: 0 };
848
+ for (const { compaction: c } of msgs) {
849
+ if (!c) continue;
850
+ sum.count++;
851
+ if (c.trigger === 'auto') sum.auto++;
852
+ sum.estCost += c.estCost || 0;
853
+ sum.rewarmCost += c.rewarmCost || 0;
854
+ sum.rewarmTokens += c.rewarmTokens;
855
+ sum.droppedTokens += c.droppedTokens;
856
+ }
857
+ sum.totalCost = sum.estCost + sum.rewarmCost;
858
+ return sum;
859
+ }
860
+
861
+ async function getOverviewData(range, projectFilter) {
862
+ const cacheKey = `overview_${rangeKey(range)}_${projectFilter || 'all'}`;
863
+ const cached = getCache(cacheKey);
864
+ if (cached !== undefined) return cached;
865
+
866
+ const pricing = await fetchPricing();
867
+ const w = resolveWindow(range);
868
+ const now = w.now;
869
+ // The series needs a concrete start even for the all-time range, so a null cutoff falls back to
870
+ // now. Deliberately local: pushing it into resolveWindow would hand the other callers a non-null
871
+ // all-time cutoff and change what they filter on.
872
+ const cutoff = w.cutoff || w.now;
873
+ const windowEnd = w.end;
874
+ const projects = scanProjectDirs(cutoff, projectFilter);
875
+ const cutoffStr = cutoff.toISOString();
876
+ const endStr = w.endStr;
877
+
878
+ let totalCost = 0, totalSessions = 0;
879
+ let totalInput = 0, totalOutput = 0, totalCacheCreation = 0, totalCacheRead = 0;
880
+ const bucket = rangeBucket(range);
881
+ const bucketKey = BUCKETS[bucket].key;
882
+ const bucketModelCosts = {};
883
+ const modelCosts = {};
884
+ const projectSummaries = [];
885
+
886
+ for (const [encodedPath, proj] of projects) {
887
+ const sessions = await loadProjectData(proj.files, pricing);
888
+ let projCost = 0, projSessions = 0, projLastActive = null;
889
+ const projModels = new Set();
890
+
891
+ for (const [, session] of sessions) {
892
+ // Filter messages within date range
893
+ const inRange = filterWindow(session.messages, cutoffStr, endStr);
894
+ if (inRange.length === 0) continue;
895
+
896
+ let sessionCost = 0, sessionInput = 0, sessionOutput = 0, sessionCacheCreation = 0, sessionCacheRead = 0;
897
+ for (const m of inRange) {
898
+ sessionCost += m.cost;
899
+ sessionInput += m.inputTokens;
900
+ sessionOutput += m.outputTokens;
901
+ sessionCacheCreation += m.cacheCreationTokens;
902
+ sessionCacheRead += m.cacheReadTokens;
903
+ const k = bucketKey(new Date(m.timestamp));
904
+ addBucketModelCost(bucketModelCosts, k, m.model, m.cost);
905
+ if (isRealModel(m.model)) {
906
+ modelCosts[m.model] = (modelCosts[m.model] || 0) + m.cost;
907
+ projModels.add(m.model);
908
+ }
909
+ if (!projLastActive || m.timestamp > projLastActive) projLastActive = m.timestamp;
910
+ }
911
+
912
+ totalCost += sessionCost;
913
+ totalInput += sessionInput;
914
+ totalOutput += sessionOutput;
915
+ totalCacheCreation += sessionCacheCreation;
916
+ totalCacheRead += sessionCacheRead;
917
+ totalSessions++;
918
+ projCost += sessionCost;
919
+ projSessions++;
920
+ }
921
+
922
+ if (projSessions > 0) {
923
+ projectSummaries.push({
924
+ encodedPath,
925
+ name: projectName(encodedPath, proj.files),
926
+ totalCost: projCost,
927
+ sessionCount: projSessions,
928
+ lastActive: projLastActive,
929
+ primaryModel: [...projModels].sort((a, b) => (modelCosts[b] || 0) - (modelCosts[a] || 0))[0] || 'unknown',
930
+ });
931
+ }
932
+ }
933
+
934
+ const costSeries = buildCostSeries(bucketModelCosts, cutoff, windowEnd, bucket);
935
+
936
+ // The today slice is scoped to the window. A window that ends before today has no today bucket,
937
+ // and a 0 there reads as "nothing spent today" rather than "outside the selected window" — so it
938
+ // is reported as null and the card is dropped instead.
939
+ const todayStr = localDateStr(now);
940
+ const todayCost = w.hasToday
941
+ ? costSeries.filter((p) => p.key.startsWith(todayStr)).reduce((s, p) => s + p.cost, 0)
942
+ : null;
943
+
944
+ const totalInputAll = totalInput + totalCacheCreation + totalCacheRead;
945
+ const cacheEfficiency = totalInputAll > 0 ? totalCacheRead / totalInputAll : 0;
946
+
947
+ const modelDistribution = buildModelDistribution(modelCosts);
948
+
949
+ const result = {
950
+ summary: {
951
+ totalCost, todayCost,
952
+ totalSessions,
953
+ totalTokens: totalInput + totalOutput + totalCacheCreation + totalCacheRead,
954
+ totalInput, totalOutput, totalCacheCreation, totalCacheRead,
955
+ cacheEfficiency,
956
+ },
957
+ costSeries: { bucket, points: costSeries },
958
+ modelDistribution,
959
+ projects: projectSummaries.sort((a, b) => b.totalCost - a.totalCost),
960
+ };
961
+
962
+ setCache(cacheKey, result);
963
+ return result;
964
+ }
965
+
966
+ async function getProjectsData(range, projectFilter) {
967
+ const cacheKey = `projects_${rangeKey(range)}_${projectFilter || 'all'}`;
968
+ const cached = getCache(cacheKey);
969
+ if (cached !== undefined) return cached;
970
+
971
+ const pricing = await fetchPricing();
972
+ const w = resolveWindow(range);
973
+ const projects = scanProjectDirs(w.cutoff, projectFilter);
974
+ const result = [];
975
+
976
+ for (const [encodedPath, proj] of projects) {
977
+ const sessions = await loadProjectData(proj.files, pricing);
978
+ let totalCost = 0, sessionCount = 0, lastActive = null;
979
+ const projModelCounts = {};
980
+
981
+ for (const [, session] of sessions) {
982
+ const msgs = filterWindow(session.messages, w.cutoffStr, w.endStr);
983
+ if (msgs.length === 0) continue;
984
+
985
+ const cost = msgs.reduce((s, m) => s + m.cost, 0);
986
+ totalCost += cost;
987
+ sessionCount++;
988
+ for (const m of msgs) {
989
+ if (isRealModel(m.model)) {
990
+ projModelCounts[m.model] = (projModelCounts[m.model] || 0) + 1;
991
+ }
992
+ }
993
+ if (!lastActive || (session.lastTimestamp && session.lastTimestamp > lastActive)) {
994
+ lastActive = session.lastTimestamp;
995
+ }
996
+ }
997
+
998
+ if (sessionCount > 0) {
999
+ result.push({
1000
+ encodedPath,
1001
+ name: projectName(encodedPath, proj.files),
1002
+ totalCost,
1003
+ sessionCount,
1004
+ lastActive,
1005
+ primaryModel: mostFrequentModel(projModelCounts),
1006
+ });
1007
+ }
1008
+ }
1009
+
1010
+ const sorted = result.sort((a, b) => b.totalCost - a.totalCost);
1011
+ setCache(cacheKey, sorted);
1012
+ return sorted;
1013
+ }
1014
+
1015
+ function sessionRow(session, msgs) {
1016
+ const sum = summarizeMessages(msgs);
1017
+ const modelCounts = {};
1018
+ for (const m of msgs) {
1019
+ if (isRealModel(m.model)) modelCounts[m.model] = (modelCounts[m.model] || 0) + 1;
1020
+ }
1021
+ const durationMs = session.firstTimestamp && session.lastTimestamp
1022
+ ? new Date(session.lastTimestamp) - new Date(session.firstTimestamp)
1023
+ : 0;
1024
+ return {
1025
+ sessionId: session.sessionId,
1026
+ customTitle: session.customTitle,
1027
+ ...sum,
1028
+ totalTokens: sum.inputTokens + sum.outputTokens + sum.cacheCreationTokens + sum.cacheReadTokens,
1029
+ models: [...session.models],
1030
+ primaryModel: mostFrequentModel(modelCounts),
1031
+ firstPrompt: session.firstPrompt,
1032
+ firstTimestamp: session.firstTimestamp,
1033
+ lastTimestamp: session.lastTimestamp,
1034
+ durationMinutes: Math.round(durationMs / 60000),
1035
+ compactions: summarizeCompactions(msgs),
1036
+ };
1037
+ }
1038
+
1039
+ async function getAllSessionsData(range) {
1040
+ const cacheKey = `sessions_all_${rangeKey(range)}`;
1041
+ const cached = getCache(cacheKey);
1042
+ if (cached !== undefined) return cached;
1043
+
1044
+ const pricing = await fetchPricing();
1045
+ const w = resolveWindow(range);
1046
+ const result = [];
1047
+ for (const [encodedPath, proj] of scanProjectDirs(w.cutoff)) {
1048
+ const name = projectName(encodedPath, proj.files);
1049
+ for (const [, session] of await loadProjectData(proj.files, pricing)) {
1050
+ const msgs = filterWindow(session.messages, w.cutoffStr, w.endStr);
1051
+ if (msgs.length) result.push({ ...sessionRow(session, msgs), projectName: name, encodedProjectPath: encodedPath });
1052
+ }
1053
+ }
1054
+ const response = { sessions: result.sort((a, b) => b.totalCost - a.totalCost) };
1055
+ setCache(cacheKey, response);
1056
+ return response;
1057
+ }
1058
+
1059
+ // Subagents grouped by what started them: the skill, else the agent type. Workflow agents group
1060
+ // apart, since one run starts many of them.
1061
+ async function getAgentsData(range, projectFilter) {
1062
+ const cacheKey = `agents_${rangeKey(range)}_${projectFilter || 'all'}`;
1063
+ const cached = getCache(cacheKey);
1064
+ if (cached !== undefined) return cached;
1065
+
1066
+ const pricing = await fetchPricing();
1067
+ const w = resolveWindow(range);
1068
+ const groups = new Map();
1069
+ for (const [encodedPath, proj] of scanProjectDirs(w.cutoff, projectFilter)) {
1070
+ for (const [, session] of await loadProjectData(proj.files, pricing)) {
1071
+ for (const m of filterWindow(session.messages, w.cutoffStr, w.endStr)) {
1072
+ const sa = m._subagent;
1073
+ if (!sa) continue;
1074
+ const kind = sa.skill ? 'skill' : sa.workflowId ? 'workflow' : 'agent';
1075
+ const name = sa.skill || sa.agentType;
1076
+ const key = `${kind}:${name}`;
1077
+ if (!groups.has(key)) groups.set(key, { kind, name, runs: 0, totalCost: 0, sessions: new Set(), costliest: null });
1078
+ const g = groups.get(key);
1079
+ g.runs++;
1080
+ g.totalCost += m.cost;
1081
+ g.sessions.add(session.sessionId);
1082
+ if (!g.costliest || m.cost > g.costliest.cost) {
1083
+ g.costliest = { cost: m.cost, sessionId: session.sessionId, agentId: sa.agentId, description: sa.description, encodedProjectPath: encodedPath };
1084
+ }
1085
+ }
1086
+ }
1087
+ }
1088
+ const agents = [...groups.values()]
1089
+ .map(({ sessions, ...g }) => ({ ...g, sessionCount: sessions.size, avgCost: g.totalCost / g.runs }))
1090
+ .sort((a, b) => b.totalCost - a.totalCost);
1091
+ const response = { agents };
1092
+ setCache(cacheKey, response);
1093
+ return response;
1094
+ }
1095
+
1096
+ async function getProjectSessionsData(encodedPath, range) {
1097
+ const cacheKey = `sessions_${encodedPath}_${rangeKey(range)}`;
1098
+ const cached = getCache(cacheKey);
1099
+ if (cached !== undefined) return cached;
1100
+
1101
+ const pricing = await fetchPricing();
1102
+ const w = resolveWindow(range);
1103
+ const projects = scanProjectDirs(w.cutoff, encodedPath);
1104
+ const bucket = rangeBucket(range);
1105
+ if (!projects.size) return { sessions: [], costSeries: { bucket, points: [] }, modelDistribution: [] };
1106
+
1107
+ const sessions = await loadProjectData([...projects.values()].flatMap((p) => p.files), pricing);
1108
+ const result = [];
1109
+ const bucketKey = BUCKETS[bucket].key;
1110
+ const bucketModelCosts = {};
1111
+ const modelCosts = {};
1112
+
1113
+ for (const [, session] of sessions) {
1114
+ const msgs = filterWindow(session.messages, w.cutoffStr, w.endStr);
1115
+ if (msgs.length === 0) continue;
1116
+
1117
+ for (const m of msgs) {
1118
+ const k = bucketKey(new Date(m.timestamp));
1119
+ addBucketModelCost(bucketModelCosts, k, m.model, m.cost);
1120
+ if (isRealModel(m.model)) modelCosts[m.model] = (modelCosts[m.model] || 0) + m.cost;
1121
+ }
1122
+ result.push(sessionRow(session, msgs));
1123
+ }
1124
+
1125
+ // No range means "everything", so the series starts at the first bucket that has cost.
1126
+ let seriesStart = w.cutoff;
1127
+ if (!seriesStart) {
1128
+ const keys = Object.keys(bucketModelCosts).sort();
1129
+ seriesStart = keys.length ? new Date(`${keys[0]}T00:00:00`) : w.now;
1130
+ }
1131
+ const costSeries = buildCostSeries(bucketModelCosts, seriesStart, w.end, bucket);
1132
+
1133
+ const modelDistribution = buildModelDistribution(modelCosts);
1134
+
1135
+ const sorted = result.sort((a, b) => (b.lastTimestamp || '').localeCompare(a.lastTimestamp || ''));
1136
+ const response = {
1137
+ sessions: sorted,
1138
+ costSeries: { bucket, points: costSeries },
1139
+ modelDistribution,
1140
+ };
1141
+ setCache(cacheKey, response);
1142
+ return response;
1143
+ }
1144
+
1145
+ // The detail view is always the whole session, unlike every other view. `inRange`/`today` carry
1146
+ // the slices the UI needs to reconcile itself with the range-scoped session row that linked here,
1147
+ // instead of silently disagreeing with it. They are derived outside the cache so switching ranges
1148
+ // does not re-parse the session's JSONL.
1149
+ function withSessionSlices(base, range) {
1150
+ const w = resolveWindow(range);
1151
+ const slice = (fromStr) => summarizeMessages(filterWindow(base.messages, fromStr, w.endStr));
1152
+ const inRange = w.cutoffStr ? slice(w.cutoffStr) : null;
1153
+ const todayStart = rangeToCutoff('today', w.now);
1154
+ // Scoped to the window like the overview's today card: a window ending in the past has no
1155
+ // today to report, and a zeroed slice would read as "nothing spent today".
1156
+ return {
1157
+ ...base,
1158
+ range,
1159
+ inRange,
1160
+ today: isTodayRange(range, w.now) ? inRange : w.hasToday ? slice(todayStart.toISOString()) : null,
1161
+ };
1162
+ }
1163
+
1164
+ async function getSessionDetailData(sessionId) {
1165
+ const cacheKey = `detail_${sessionId}`;
1166
+ const cached = getCache(cacheKey);
1167
+ if (cached !== undefined) return cached;
1168
+
1169
+ const pricing = await fetchPricing();
1170
+ const projects = scanProjectDirs();
1171
+
1172
+ // Find the session across all projects
1173
+ for (const [encodedPath, proj] of projects) {
1174
+ const matchingFile = proj.files.find(f => getSessionIdFromFile(f) === sessionId);
1175
+ if (!matchingFile) continue;
1176
+
1177
+ const sessions = await loadProjectData([matchingFile], pricing);
1178
+ const session = sessions.get(sessionId);
1179
+ if (!session) continue;
1180
+
1181
+ // Sort messages by timestamp
1182
+ // Add cumulative cost
1183
+ const messages = withRunningCost(session.messages);
1184
+
1185
+ // One folded-in message per agent, and `messages` is already sorted, so a group's ends are
1186
+ // the run's first and last agent.
1187
+ const byWorkflow = new Map();
1188
+ for (const m of messages) {
1189
+ const wf = m._subagent?.workflowId;
1190
+ if (!wf) continue;
1191
+ if (!byWorkflow.has(wf)) byWorkflow.set(wf, []);
1192
+ byWorkflow.get(wf).push(m);
1193
+ }
1194
+ const names = byWorkflow.size > 0
1195
+ ? findWorkflowNames(sessionId, byWorkflow.keys(), encodedPath)
1196
+ : new Map();
1197
+ const workflows = [...byWorkflow].map(([id, msgs]) => {
1198
+ const { messageCount, ...totals } = summarizeMessages(msgs);
1199
+ // A folded message carries its agent's start time, so the run ends at the latest agent's
1200
+ // own last turn — the last folded message only says when that agent started.
1201
+ const end = msgs.reduce((max, m) => {
1202
+ const t = m._subagent.lastTimestamp || m.timestamp;
1203
+ return t > max ? t : max;
1204
+ }, msgs[0].timestamp);
1205
+ return {
1206
+ id,
1207
+ name: names.get(id) || id,
1208
+ agents: messageCount,
1209
+ firstTimestamp: msgs[0].timestamp,
1210
+ lastTimestamp: end,
1211
+ // Where the run sits in `messages`, for the timeline band.
1212
+ startIndex: msgs[0].index,
1213
+ endIndex: msgs.at(-1).index,
1214
+ ...totals,
1215
+ };
1216
+ }).sort((a, b) => b.totalCost - a.totalCost);
1217
+
1218
+ const result = {
1219
+ sessionId,
1220
+ customTitle: session.customTitle,
1221
+ projectPath: projectName(encodedPath, [matchingFile]),
1222
+ encodedProjectPath: encodedPath,
1223
+ totalCost: session.totalCost,
1224
+ inputTokens: session.inputTokens,
1225
+ outputTokens: session.outputTokens,
1226
+ cacheCreationTokens: session.cacheCreationTokens,
1227
+ cacheReadTokens: session.cacheReadTokens,
1228
+ models: [...session.models],
1229
+ firstPrompt: session.firstPrompt,
1230
+ firstTimestamp: session.firstTimestamp,
1231
+ lastTimestamp: session.lastTimestamp,
1232
+ workflows,
1233
+ compactions: summarizeCompactions(messages),
1234
+ messages,
1235
+ };
1236
+
1237
+ setCache(cacheKey, result);
1238
+ return result;
1239
+ }
1240
+
1241
+ return null;
1242
+ }
1243
+
1244
+ function withRunningCost(msgs) {
1245
+ let cumulative = 0;
1246
+ return msgs.sort(byTimestamp).map((m, i) => {
1247
+ cumulative += m.cost;
1248
+ return { ...m, index: i + 1, cumulativeCost: cumulative };
1249
+ });
1250
+ }
1251
+
1252
+ // Most agents sit directly in subagents/; only a workflow's agents need the walk.
1253
+ function findAgentFile(session, agentId) {
1254
+ if (!/^agent-[\w-]+$/.test(agentId)) return null;
1255
+ for (const baseDir of getProjectsDirs()) {
1256
+ const sessionDir = path.join(baseDir, session.encodedProjectPath, session.sessionId);
1257
+ const direct = path.join(sessionDir, 'subagents', `${agentId}.jsonl`);
1258
+ if (fs.existsSync(direct)) return direct;
1259
+ const nested = scanSubagentDir(sessionDir).find(a => a.agentId === agentId);
1260
+ if (nested) return nested.filePath;
1261
+ }
1262
+ return null;
1263
+ }
1264
+
1265
+ // Same shape as a session detail, so the detail view renders one agent's turns unchanged.
1266
+ async function getAgentDetailData(sessionId, agentId) {
1267
+ const cacheKey = `agent_${sessionId}_${agentId}`;
1268
+ const cached = getCache(cacheKey);
1269
+ if (cached !== undefined) return cached;
1270
+
1271
+ const session = await getSessionDetailData(sessionId);
1272
+ const filePath = session && findAgentFile(session, agentId);
1273
+ if (!filePath) return null;
1274
+ const folded = session.messages.find(m => m._subagent?.agentId === agentId)?._subagent;
1275
+
1276
+ const pricing = await fetchPricing();
1277
+ const messages = withRunningCost(await readAgentTurns(filePath, pricing, { withTools: true }));
1278
+ const { messageCount, ...totals } = summarizeMessages(messages);
1279
+ const result = {
1280
+ sessionId,
1281
+ agentId,
1282
+ agentType: folded?.agentType || 'unknown',
1283
+ description: folded?.description || '',
1284
+ sessionTitle: session.customTitle || session.firstPrompt || sessionId,
1285
+ projectPath: session.projectPath,
1286
+ encodedProjectPath: session.encodedProjectPath,
1287
+ ...totals,
1288
+ models: [...new Set(messages.map(m => m.model).filter(isRealModel))],
1289
+ firstTimestamp: messages[0]?.timestamp || null,
1290
+ lastTimestamp: messages.at(-1)?.timestamp || null,
1291
+ messages,
1292
+ };
1293
+ setCache(cacheKey, result);
1294
+ return result;
1295
+ }
1296
+
1297
+ // Claude's usage limits work in rolling 5-hour billing windows. A block starts at the first
1298
+ // activity (floored to the hour, mirroring ccusage) and spans exactly 5h; activity past the end
1299
+ // opens a new block anchored to its own hour.
1300
+ const BLOCK_MS = 5 * 60 * 60 * 1000;
1301
+ const HEATMAP_DAYS = 7;
1302
+ const MAX_BLOCKS = 24;
1303
+ const MAX_TOOLS = 20;
1304
+
1305
+ // The real window boundary comes from Claude Code's statusline payload (rate_limits.five_hour),
1306
+ // spied to disk by the cck plugin. The ccusage hour-floor heuristic can be hours off the actual
1307
+ // API window, so when a live resets_at is available it anchors the active block instead.
1308
+ function readRateLimits(now) {
1309
+ const dir = path.join(CLAUDE_DIR, '.cck', 'context-status');
1310
+ let newest = null;
1311
+ try {
1312
+ for (const f of fs.readdirSync(dir)) {
1313
+ if (!f.endsWith('.json')) continue;
1314
+ const fp = path.join(dir, f);
1315
+ try {
1316
+ const mtime = fs.statSync(fp).mtimeMs;
1317
+ if (!newest || mtime > newest.mtime) newest = { fp, mtime };
1318
+ } catch { /* ignore */ }
1319
+ }
1320
+ } catch { return null; }
1321
+ if (!newest) return null;
1322
+ try {
1323
+ const rl = JSON.parse(fs.readFileSync(newest.fp, 'utf8'))?.rate_limits;
1324
+ const fh = rl?.five_hour;
1325
+ // A resets_at in the past means the snapshot predates the current window — don't trust it.
1326
+ if (!fh?.resets_at || fh.resets_at * 1000 <= now.getTime()) return null;
1327
+ return { usedPct: fh.used_percentage ?? null, resetsAtMs: fh.resets_at * 1000 };
1328
+ } catch { return null; }
1329
+ }
1330
+
1331
+ function computeBlocks(messages, now, realResetMs) {
1332
+ // When the API told us the live window, the active block spans exactly [reset-5h, reset].
1333
+ const activeStartMs = realResetMs && now.getTime() < realResetMs ? realResetMs - BLOCK_MS : null;
1334
+ const blocks = [];
1335
+ let cur = null;
1336
+ for (const m of messages) {
1337
+ const t = new Date(m.timestamp).getTime();
1338
+ if (!Number.isFinite(t)) continue;
1339
+ if (activeStartMs !== null && t >= activeStartMs) {
1340
+ if (!cur || cur.startMs !== activeStartMs) {
1341
+ cur = { startMs: activeStartMs, real: true, lastMs: t, cost: 0, tokens: 0, messageCount: 0, models: new Set() };
1342
+ blocks.push(cur);
1343
+ }
1344
+ } else if (!cur || t >= cur.startMs + BLOCK_MS) {
1345
+ const start = new Date(t);
1346
+ start.setMinutes(0, 0, 0);
1347
+ cur = { startMs: start.getTime(), lastMs: t, cost: 0, tokens: 0, messageCount: 0, models: new Set() };
1348
+ blocks.push(cur);
1349
+ }
1350
+ if (t > cur.lastMs) cur.lastMs = t;
1351
+ cur.cost += m.cost;
1352
+ cur.tokens += m.inputTokens + m.outputTokens + m.cacheCreationTokens + m.cacheReadTokens;
1353
+ cur.messageCount++;
1354
+ if (isRealModel(m.model)) cur.models.add(m.model);
1355
+ }
1356
+ // A live window with no in-range messages yet still exists — surface it as an empty block.
1357
+ if (activeStartMs !== null && !blocks.some((b) => b.startMs === activeStartMs)) {
1358
+ blocks.push({ startMs: activeStartMs, real: true, lastMs: activeStartMs, cost: 0, tokens: 0, messageCount: 0, models: new Set() });
1359
+ }
1360
+ const nowMs = now.getTime();
1361
+ return blocks
1362
+ .reverse()
1363
+ .slice(0, MAX_BLOCKS)
1364
+ .map((b) => {
1365
+ const endMs = b.startMs + BLOCK_MS;
1366
+ // Only the API-anchored window counts as active: the hour-floor heuristic can be hours
1367
+ // off the real boundary, so without live data no block is presented as current.
1368
+ const active = b.real === true && nowMs < endMs;
1369
+ // Floored at 1 so a block opened seconds ago doesn't project an absurd rate.
1370
+ const elapsedMin = active ? Math.max(1, (nowMs - b.startMs) / 60000) : null;
1371
+ return {
1372
+ start: new Date(b.startMs).toISOString(),
1373
+ end: new Date(endMs).toISOString(),
1374
+ lastActivity: new Date(b.lastMs).toISOString(),
1375
+ cost: b.cost,
1376
+ tokens: b.tokens,
1377
+ messageCount: b.messageCount,
1378
+ models: [...b.models],
1379
+ active,
1380
+ burn: active
1381
+ ? {
1382
+ costPerHour: (b.cost / elapsedMin) * 60,
1383
+ tokensPerMin: b.tokens / elapsedMin,
1384
+ projectedCost: (b.cost / elapsedMin) * (BLOCK_MS / 60000),
1385
+ remainingMin: Math.round((endMs - nowMs) / 60000),
1386
+ }
1387
+ : null,
1388
+ };
1389
+ });
1390
+ }
1391
+
1392
+ async function getInsightsData(range, projectFilter) {
1393
+ const cacheKey = `insights_${rangeKey(range)}_${projectFilter || 'all'}`;
1394
+ const cached = getCache(cacheKey);
1395
+ if (cached !== undefined) return cached;
1396
+
1397
+ const pricing = await fetchPricing();
1398
+ const w = resolveWindow(range);
1399
+
1400
+ // The heatmap covers the last 7 real days ending at the selected window's end — each row
1401
+ // is an actual date, so a short range (today, 3d) still shows a full week of context.
1402
+ const windowEnd = w.end < w.now ? w.end : w.now;
1403
+ const hmStart = new Date(windowEnd);
1404
+ hmStart.setHours(0, 0, 0, 0);
1405
+ hmStart.setDate(hmStart.getDate() - (HEATMAP_DAYS - 1));
1406
+ const hmStartStr = hmStart.toISOString();
1407
+ const scanCutoff = w.cutoff === null ? null : w.cutoff < hmStart ? w.cutoff : hmStart;
1408
+ const projects = scanProjectDirs(scanCutoff, projectFilter);
1409
+
1410
+ // When the cost window already covers the heatmap window, the heatmap rows are a subset of
1411
+ // `all` — filter it instead of re-scanning every session a second time.
1412
+ const hmInAll = w.cutoff === null || w.cutoff <= hmStart;
1413
+ const allParts = [];
1414
+ const hmParts = [];
1415
+ for (const [, proj] of projects) {
1416
+ const sessions = await loadProjectData(proj.files, pricing);
1417
+ for (const [, session] of sessions) {
1418
+ allParts.push(filterWindow(session.messages, w.cutoffStr, w.endStr));
1419
+ if (!hmInAll) hmParts.push(filterWindow(session.messages, hmStartStr, w.endStr));
1420
+ }
1421
+ }
1422
+ const all = allParts.flat().sort(byTimestamp);
1423
+ const hmMsgs = hmInAll ? all.filter((m) => m.timestamp >= hmStartStr) : hmParts.flat();
1424
+
1425
+ // The live 5h window can open before the selected range starts (a Today filter after midnight
1426
+ // cuts a block that opened the evening before), so block stats are computed over the block's
1427
+ // own span. A live block always starts within the last 5h, inside the heatmap window, so its
1428
+ // messages are a subset of hmMsgs — no extra scan needed.
1429
+ const limits = w.hasToday ? readRateLimits(w.now) : null;
1430
+ const blockStart = limits ? new Date(limits.resetsAtMs - BLOCK_MS) : null;
1431
+ const blockInAll = !blockStart || w.cutoff === null || w.cutoff <= blockStart;
1432
+ let blockMsgs = all;
1433
+ if (!blockInAll) {
1434
+ const fromStr = blockStart.toISOString();
1435
+ blockMsgs = hmMsgs.filter((m) => m.timestamp >= fromStr).sort(byTimestamp);
1436
+ }
1437
+
1438
+ const sum = summarizeMessages(all);
1439
+ const tokens = { input: sum.inputTokens, output: sum.outputTokens, cacheCreation: sum.cacheCreationTokens, cacheRead: sum.cacheReadTokens };
1440
+ let cacheSavings = 0;
1441
+ // One row per real day, oldest first; row index = whole days since hmStart.
1442
+ const heatmap = Array.from({ length: HEATMAP_DAYS }, () => new Array(24).fill(0));
1443
+ const heatmapDays = Array.from({ length: HEATMAP_DAYS }, (_, i) => {
1444
+ const d = new Date(hmStart);
1445
+ d.setDate(d.getDate() + i);
1446
+ return localDateStr(d);
1447
+ });
1448
+ const toolCounts = {};
1449
+ let mainCost = 0;
1450
+ let subagentCost = 0;
1451
+ let workflowCost = 0;
1452
+ const workflowRuns = new Set();
1453
+ const weekly = {};
1454
+
1455
+ // getModelPricing falls back to a linear scan of the whole LiteLLM map on a miss, so resolve
1456
+ // it once per distinct model rather than once per message.
1457
+ const priceMemo = new Map();
1458
+ for (const m of all) {
1459
+ // What the same tokens would have cost as fresh input, minus what cache reads actually cost.
1460
+ if (m.cacheReadTokens > 0) {
1461
+ if (!priceMemo.has(m.model)) priceMemo.set(m.model, getModelPricing(pricing, m.model));
1462
+ const mp = priceMemo.get(m.model);
1463
+ if (mp?.input_cost_per_token != null && mp?.cache_read_input_token_cost != null) {
1464
+ cacheSavings += m.cacheReadTokens * (mp.input_cost_per_token - mp.cache_read_input_token_cost);
1465
+ }
1466
+ }
1467
+
1468
+ const monday = new Date(m.timestamp);
1469
+ monday.setHours(0, 0, 0, 0);
1470
+ monday.setDate(monday.getDate() - ((monday.getDay() + 6) % 7));
1471
+ const wk = localDateStr(monday);
1472
+ weekly[wk] = (weekly[wk] || 0) + m.cost;
1473
+
1474
+ if (m._subagent) {
1475
+ subagentCost += m.cost;
1476
+ if (m._subagent.workflowId) {
1477
+ workflowCost += m.cost;
1478
+ workflowRuns.add(m._subagent.workflowId);
1479
+ }
1480
+ } else {
1481
+ mainCost += m.cost;
1482
+ if (m.tools) for (const t of m.tools) toolCounts[t] = (toolCounts[t] || 0) + 1;
1483
+ }
1484
+ }
1485
+
1486
+ for (const m of hmMsgs) {
1487
+ const d = new Date(m.timestamp);
1488
+ const day = new Date(d);
1489
+ day.setHours(0, 0, 0, 0);
1490
+ // Round to survive DST shifts making a "day" 23/25 hours.
1491
+ const idx = Math.round((day - hmStart) / 86400000);
1492
+ if (idx >= 0 && idx < HEATMAP_DAYS) heatmap[idx][d.getHours()] += m.cost;
1493
+ }
1494
+
1495
+ // A window ending in the past has no "current" block — limits are only read when the window
1496
+ // reaches today, so the live block is never synthesized for a historical range.
1497
+ const blocks = computeBlocks(blockMsgs, w.now, limits?.resetsAtMs || null);
1498
+ const activeBlk = blocks.find((b) => b.active);
1499
+ if (activeBlk) activeBlk.usedPct = limits?.usedPct ?? null;
1500
+
1501
+ // Run-rate over the window actually observed: a custom window ending in the past uses its own
1502
+ // span; open-ended ranges run from the first message (all-time) or the cutoff to now.
1503
+ const windowStart = w.cutoff || (all.length ? new Date(all[0].timestamp) : w.now);
1504
+ const dayCount = Math.max(1, Math.ceil((windowEnd - windowStart) / 86400000));
1505
+ const dailyAvg = sum.totalCost / dayCount;
1506
+
1507
+ const result = {
1508
+ tokens,
1509
+ cacheSavings,
1510
+ runRate: { dailyAvg, projectedMonthly: dailyAvg * 30, days: dayCount },
1511
+ blocks,
1512
+ heatmap,
1513
+ heatmapDays,
1514
+ heatmapToday: localDateStr(w.now),
1515
+ tools: Object.entries(toolCounts)
1516
+ .map(([name, count]) => ({ name, count }))
1517
+ .sort((a, b) => b.count - a.count)
1518
+ .slice(0, MAX_TOOLS),
1519
+ // workflowCost is the slice of subagentCost spent inside Workflow runs, not a third peer —
1520
+ // mainCost + subagentCost is still the whole.
1521
+ subagents: { mainCost, subagentCost, workflowCost, workflowRuns: workflowRuns.size },
1522
+ compactions: summarizeCompactions(all),
1523
+ weekly: Object.entries(weekly)
1524
+ .sort(([a], [b]) => a.localeCompare(b))
1525
+ .map(([weekStart, cost]) => ({ weekStart, cost })),
1526
+ };
1527
+
1528
+ setCache(cacheKey, result);
1529
+ return result;
1530
+ }
1531
+
1532
+ // #endregion
1533
+
1534
+ // #region QUERY_PARAMS
1535
+
1536
+ function parseRange(raw, fallback = null) {
1537
+ if (raw === 'today') return 'today';
1538
+ if (raw === '24h') return '24h';
1539
+ const n = parseInt(raw, 10);
1540
+ return Number.isFinite(n) ? n : fallback;
1541
+ }
1542
+
1543
+ const DATE_PARAM = /^\d{4}-\d{2}-\d{2}$/;
1544
+
1545
+ // A local calendar date, normalized so it can safely reach a cache key — same discipline as
1546
+ // parseProject. Returns undefined for absent, null for malformed.
1547
+ function parseDateParam(raw) {
1548
+ if (raw === undefined || raw === '') return undefined;
1549
+ if (typeof raw !== 'string' || !DATE_PARAM.test(raw)) return null;
1550
+ return localDateStr(localDayStart(raw)) === raw ? raw : null;
1551
+ }
1552
+
1553
+ // A custom window, if the request asked for one: `from`/`to` take precedence over `range`.
1554
+ // Reversed pairs are ordered and both ends clamped to today — there is no cost data ahead of now,
1555
+ // and an inverted window would otherwise render as an unexplained empty chart.
1556
+ // Returns undefined when no window was requested, null when one was but is malformed.
1557
+ function parseCustomRange(query) {
1558
+ const from = parseDateParam(query.from);
1559
+ const to = parseDateParam(query.to);
1560
+ if (from === null || to === null) return null;
1561
+ if (from === undefined && to === undefined) return undefined;
1562
+ if (from === undefined || to === undefined) return null;
1563
+ const today = localDateStr(new Date());
1564
+ const [lo, hi] = from <= to ? [from, to] : [to, from];
1565
+ return { from: lo > today ? today : lo, to: hi > today ? today : hi };
1566
+ }
1567
+
1568
+ // Encoded project-dir name (the hub sends it pre-encoded — see encodeProjectPath in the hub's
1569
+ // public/app.js; this regex must stay a superset of that transform's output). Only ever used as
1570
+ // a Map key, never joined into a path — the regex exists to keep unbounded strings out of the
1571
+ // cache keys.
1572
+ // Returns undefined for absent, null for malformed, so callers can 400 instead of silently
1573
+ // dropping the scope.
1574
+ function parseProject(raw) {
1575
+ if (raw === undefined || raw === '') return undefined;
1576
+ if (typeof raw !== 'string' || !/^[A-Za-z0-9._-]+(,[A-Za-z0-9._-]+)*$/.test(raw)) return null;
1577
+ return raw;
1578
+ }
1579
+
1580
+ // #endregion
1581
+
1582
+ // #region USAGE_LIMITS
1583
+
1584
+ // Each probe spawns a CLI process and fires the config dir's SessionStart hooks, so we cache the
1585
+ // result and let concurrent callers share one in-flight run.
1586
+ //
1587
+ // The TTL mirrors the CLI's own: it refetches plan utilization at most every 5 minutes and shares
1588
+ // the answer through an on-disk cache, so probing faster re-reads the same numbers. A manual
1589
+ // refresh bypasses this cache but still cannot beat that floor.
1590
+ const USAGE_TTL_MS = 5 * 60 * 1000;
1591
+ let usageCache = null;
1592
+ let usageInFlight = null;
1593
+
1594
+ function loadUsage(force = false) {
1595
+ if (!force && usageCache && Date.now() - usageCache.ts < USAGE_TTL_MS) {
1596
+ return Promise.resolve(usageCache.data);
1597
+ }
1598
+ // A forced call still joins an in-flight probe: two spawns would only race for the same answer.
1599
+ if (usageInFlight) return usageInFlight;
1600
+ usageInFlight = probeUsage({ claudeDir: CLAUDE_DIR })
1601
+ .then((raw) => {
1602
+ const data = normalizeUsage(raw);
1603
+ if (data) usageCache = { data, ts: Date.now() };
1604
+ return data;
1605
+ })
1606
+ .finally(() => {
1607
+ usageInFlight = null;
1608
+ });
1609
+ return usageInFlight;
1610
+ }
1611
+
1612
+ // #endregion
1613
+
1614
+ module.exports = {
1615
+ getArg,
1616
+ CLAUDE_DIR,
1617
+ fetchPricing,
1618
+ invalidateAllCache,
1619
+ getOverviewData,
1620
+ getInsightsData,
1621
+ getProjectsData,
1622
+ getProjectSessionsData,
1623
+ getAllSessionsData,
1624
+ getAgentsData,
1625
+ getSessionDetailData,
1626
+ getAgentDetailData,
1627
+ withSessionSlices,
1628
+ loadUsage,
1629
+ parseRange,
1630
+ parseCustomRange,
1631
+ parseProject,
1632
+ resolveWindow,
1633
+ localDateStr,
1634
+ };