claude-code-cost 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server.js ADDED
@@ -0,0 +1,734 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const express = require('express');
5
+ const path = require('path');
6
+ const fs = require('fs');
7
+ const { createReadStream } = require('fs');
8
+ const { createInterface } = require('readline');
9
+ const os = require('os');
10
+
11
+ // #region CLI_ARGS
12
+
13
+ function getArg(name) {
14
+ const eqIdx = process.argv.findIndex(a => a === `--${name}` || a.startsWith(`--${name}=`));
15
+ if (eqIdx === -1) return null;
16
+ const arg = process.argv[eqIdx];
17
+ if (arg.includes('=')) return arg.split('=').slice(1).join('=');
18
+ return process.argv[eqIdx + 1] || null;
19
+ }
20
+
21
+ const PORT = getArg('port') || process.env.PORT || 3458;
22
+ const claudeDirArg = getArg('dir');
23
+ const CLAUDE_DIR = claudeDirArg
24
+ ? claudeDirArg.replace(/^~/, os.homedir())
25
+ : path.join(os.homedir(), '.claude');
26
+
27
+ const PROJECTS_DIR = path.join(CLAUDE_DIR, 'projects');
28
+ const ALT_PROJECTS_DIR = path.join(os.homedir(), '.config', 'claude', 'projects');
29
+
30
+ function getProjectsDirs() {
31
+ const dirs = [];
32
+ if (fs.existsSync(PROJECTS_DIR)) dirs.push(PROJECTS_DIR);
33
+ if (fs.existsSync(ALT_PROJECTS_DIR)) dirs.push(ALT_PROJECTS_DIR);
34
+ return dirs;
35
+ }
36
+
37
+ // #endregion
38
+
39
+ // #region PRICING
40
+
41
+ const LITELLM_PRICING_URL =
42
+ 'https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json';
43
+
44
+ const PROVIDER_PREFIXES = ['anthropic/', 'claude-3-5-', 'claude-3-', 'claude-'];
45
+ const TIERED_THRESHOLD = 200_000;
46
+ const PRICING_REFRESH_MS = 6 * 60 * 60 * 1000;
47
+
48
+ let cachedPricing = null;
49
+ let pricingFetchedAt = 0;
50
+
51
+ const OFFLINE_PRICING = {
52
+ 'anthropic/claude-sonnet-4-20250514': {
53
+ input_cost_per_token: 3e-6, output_cost_per_token: 1.5e-5,
54
+ cache_creation_input_token_cost: 3.75e-6, cache_read_input_token_cost: 3e-7,
55
+ input_cost_per_token_above_200k_tokens: 6e-6, output_cost_per_token_above_200k_tokens: 2.25e-5,
56
+ cache_creation_input_token_cost_above_200k_tokens: 7.5e-6, cache_read_input_token_cost_above_200k_tokens: 6e-7,
57
+ },
58
+ 'anthropic/claude-opus-4-20250514': {
59
+ input_cost_per_token: 1.5e-5, output_cost_per_token: 7.5e-5,
60
+ cache_creation_input_token_cost: 1.875e-5, cache_read_input_token_cost: 1.5e-6,
61
+ input_cost_per_token_above_200k_tokens: 3e-5, output_cost_per_token_above_200k_tokens: 1.125e-4,
62
+ cache_creation_input_token_cost_above_200k_tokens: 3.75e-5, cache_read_input_token_cost_above_200k_tokens: 3e-6,
63
+ provider_specific_entry: { fast: 6.0 },
64
+ },
65
+ 'anthropic/claude-haiku-4-5-20251001': {
66
+ input_cost_per_token: 8e-7, output_cost_per_token: 4e-6,
67
+ cache_creation_input_token_cost: 1e-6, cache_read_input_token_cost: 8e-8,
68
+ input_cost_per_token_above_200k_tokens: 1.6e-6, output_cost_per_token_above_200k_tokens: 6e-6,
69
+ cache_creation_input_token_cost_above_200k_tokens: 2e-6, cache_read_input_token_cost_above_200k_tokens: 1.6e-7,
70
+ },
71
+ 'anthropic/claude-3-5-sonnet-20241022': {
72
+ input_cost_per_token: 3e-6, output_cost_per_token: 1.5e-5,
73
+ cache_creation_input_token_cost: 3.75e-6, cache_read_input_token_cost: 3e-7,
74
+ },
75
+ 'anthropic/claude-3-5-haiku-20241022': {
76
+ input_cost_per_token: 8e-7, output_cost_per_token: 4e-6,
77
+ cache_creation_input_token_cost: 1e-6, cache_read_input_token_cost: 8e-8,
78
+ },
79
+ };
80
+
81
+ async function fetchPricing() {
82
+ const now = Date.now();
83
+ if (cachedPricing && (now - pricingFetchedAt) < PRICING_REFRESH_MS) return cachedPricing;
84
+
85
+ try {
86
+ console.log('[Pricing] Fetching from LiteLLM...');
87
+ const resp = await fetch(LITELLM_PRICING_URL);
88
+ if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
89
+ const data = await resp.json();
90
+ const pricing = new Map();
91
+ for (const [name, info] of Object.entries(data)) {
92
+ if (typeof info !== 'object' || info == null) continue;
93
+ if (info.input_cost_per_token != null || info.output_cost_per_token != null) {
94
+ pricing.set(name, info);
95
+ }
96
+ }
97
+ cachedPricing = pricing;
98
+ pricingFetchedAt = now;
99
+ console.log(`[Pricing] Loaded ${pricing.size} models`);
100
+ return pricing;
101
+ } catch (err) {
102
+ console.warn('[Pricing] Fetch failed, using offline fallback:', err.message);
103
+ if (!cachedPricing) {
104
+ cachedPricing = new Map(Object.entries(OFFLINE_PRICING));
105
+ pricingFetchedAt = now;
106
+ }
107
+ return cachedPricing;
108
+ }
109
+ }
110
+
111
+ function getModelPricing(pricing, modelName) {
112
+ if (!modelName) return null;
113
+
114
+ // Exact match
115
+ const direct = pricing.get(modelName);
116
+ if (direct) return direct;
117
+
118
+ // Try with provider prefixes
119
+ for (const prefix of PROVIDER_PREFIXES) {
120
+ const candidate = pricing.get(`${prefix}${modelName}`);
121
+ if (candidate) return candidate;
122
+ }
123
+
124
+ // Fuzzy lowercase match
125
+ const lower = modelName.toLowerCase();
126
+ for (const [key, value] of pricing) {
127
+ const cmp = key.toLowerCase();
128
+ if (cmp.includes(lower) || lower.includes(cmp)) return value;
129
+ }
130
+
131
+ return null;
132
+ }
133
+
134
+ function calculateTieredCost(totalTokens, basePrice, tieredPrice, threshold = TIERED_THRESHOLD) {
135
+ if (!totalTokens || totalTokens <= 0) return 0;
136
+ if (totalTokens > threshold && tieredPrice != null) {
137
+ const below = Math.min(totalTokens, threshold);
138
+ const above = Math.max(0, totalTokens - threshold);
139
+ let cost = above * tieredPrice;
140
+ if (basePrice != null) cost += below * basePrice;
141
+ return cost;
142
+ }
143
+ if (basePrice != null) return totalTokens * basePrice;
144
+ return 0;
145
+ }
146
+
147
+ function calculateCost(tokens, modelPricing) {
148
+ const inputCost = calculateTieredCost(
149
+ tokens.input_tokens, modelPricing.input_cost_per_token,
150
+ modelPricing.input_cost_per_token_above_200k_tokens);
151
+ const outputCost = calculateTieredCost(
152
+ tokens.output_tokens, modelPricing.output_cost_per_token,
153
+ modelPricing.output_cost_per_token_above_200k_tokens);
154
+ const cacheCreationCost = calculateTieredCost(
155
+ tokens.cache_creation_input_tokens, modelPricing.cache_creation_input_token_cost,
156
+ modelPricing.cache_creation_input_token_cost_above_200k_tokens);
157
+ const cacheReadCost = calculateTieredCost(
158
+ tokens.cache_read_input_tokens, modelPricing.cache_read_input_token_cost,
159
+ modelPricing.cache_read_input_token_cost_above_200k_tokens);
160
+ return inputCost + outputCost + cacheCreationCost + cacheReadCost;
161
+ }
162
+
163
+ function calculateCostForModel(tokens, modelName, pricing, speed) {
164
+ const mp = getModelPricing(pricing, modelName);
165
+ if (!mp) return 0;
166
+ const baseCost = calculateCost(tokens, mp);
167
+ const multiplier = speed === 'fast' ? (mp.provider_specific_entry?.fast ?? 1) : 1;
168
+ return baseCost * multiplier;
169
+ }
170
+
171
+ // #endregion
172
+
173
+ // #region JSONL_PARSING
174
+
175
+ async function processJSONLFile(filePath, processLine) {
176
+ const fileStream = createReadStream(filePath, { encoding: 'utf-8' });
177
+ const rl = createInterface({ input: fileStream, crlfDelay: Infinity });
178
+ let lineNumber = 0;
179
+ for await (const line of rl) {
180
+ lineNumber++;
181
+ if (line.trim().length === 0) continue;
182
+ await processLine(line, lineNumber);
183
+ }
184
+ }
185
+
186
+ function parseUsageLine(line) {
187
+ try {
188
+ const data = JSON.parse(line);
189
+ if (!data.message?.usage?.input_tokens && data.message?.usage?.input_tokens !== 0) return null;
190
+ if (!data.timestamp) return null;
191
+ return data;
192
+ } catch { return null; }
193
+ }
194
+
195
+ function createDedupeHash(data) {
196
+ const mid = data.message?.id;
197
+ const rid = data.requestId;
198
+ if (!mid || !rid) return null;
199
+ return `${mid}:${rid}`;
200
+ }
201
+
202
+ function calculateEntryCost(data, pricing) {
203
+ // Auto mode: use costUSD if present, otherwise calculate
204
+ if (data.costUSD != null) return data.costUSD;
205
+ const model = data.message?.model;
206
+ if (!model) return 0;
207
+ const speed = data.message?.usage?.speed;
208
+ return calculateCostForModel(data.message.usage, model, pricing, speed);
209
+ }
210
+
211
+ // #endregion
212
+
213
+ // #region DATA_AGGREGATION
214
+
215
+ const CACHE_TTL = 30_000;
216
+ let dataCache = {};
217
+ let cacheTimestamps = {};
218
+
219
+ function isCacheValid(key) {
220
+ return cacheTimestamps[key] && (Date.now() - cacheTimestamps[key]) < CACHE_TTL;
221
+ }
222
+
223
+ function setCache(key, data) {
224
+ dataCache[key] = data;
225
+ cacheTimestamps[key] = Date.now();
226
+ }
227
+
228
+ function invalidateAllCache() {
229
+ dataCache = {};
230
+ cacheTimestamps = {};
231
+ }
232
+
233
+ function localDateStr(d) {
234
+ const y = d.getFullYear();
235
+ const m = String(d.getMonth() + 1).padStart(2, '0');
236
+ const day = String(d.getDate()).padStart(2, '0');
237
+ return `${y}-${m}-${day}`;
238
+ }
239
+
240
+ function scanProjectDirs(cutoffDate) {
241
+ const projects = new Map();
242
+ const cutoffMs = cutoffDate ? cutoffDate.getTime() : 0;
243
+ for (const baseDir of getProjectsDirs()) {
244
+ try {
245
+ const entries = fs.readdirSync(baseDir, { withFileTypes: true });
246
+ for (const entry of entries) {
247
+ if (!entry.isDirectory()) continue;
248
+ const projDir = path.join(baseDir, entry.name);
249
+ const files = [];
250
+ try {
251
+ for (const f of fs.readdirSync(projDir)) {
252
+ if (!f.endsWith('.jsonl')) continue;
253
+ const filePath = path.join(projDir, f);
254
+ // Skip files not modified since cutoff date
255
+ if (cutoffMs) {
256
+ try {
257
+ const mtime = fs.statSync(filePath).mtimeMs;
258
+ if (mtime < cutoffMs) continue;
259
+ } catch { continue; }
260
+ }
261
+ files.push(filePath);
262
+ }
263
+ } catch { /* ignore */ }
264
+ if (files.length > 0) {
265
+ const key = entry.name;
266
+ if (!projects.has(key)) {
267
+ projects.set(key, { encodedPath: key, dir: projDir, files });
268
+ } else {
269
+ projects.get(key).files.push(...files);
270
+ }
271
+ }
272
+ }
273
+ } catch { /* dir doesn't exist */ }
274
+ }
275
+ return projects;
276
+ }
277
+
278
+ function decodeProjectPath(encoded) {
279
+ try {
280
+ // Claude encodes paths as: C--Users-name-dev-project
281
+ // "C--" = drive prefix, then "-" separates path segments
282
+ // But hyphens in actual folder names also become "-" (ambiguous)
283
+ // Strategy: strip known prefixes to reveal project name
284
+ let name = encoded;
285
+ // Strip drive + common base paths: C--Users-username-dev- or similar
286
+ name = name.replace(/^[A-Z]--[^-]+-[^-]+-(dev|src|repos|projects|work|code)-/, '');
287
+ // Strip C--Users-username--config- or C--Users-username--claude- patterns
288
+ name = name.replace(/^[A-Z]--[^-]+-[^-]+--([^-]+)-/, '$1/');
289
+ // Strip C--Users-username- if still there
290
+ name = name.replace(/^[A-Z]--[^-]+-[^-]+-/, '');
291
+ return name || encoded;
292
+ } catch { return encoded; }
293
+ }
294
+
295
+ function getSessionIdFromFile(filePath) {
296
+ return path.basename(filePath, '.jsonl');
297
+ }
298
+
299
+ async function loadProjectData(files, pricing) {
300
+ const sessions = new Map();
301
+ const seen = new Set();
302
+
303
+ for (const file of files) {
304
+ const sessionId = getSessionIdFromFile(file);
305
+ if (!sessions.has(sessionId)) {
306
+ sessions.set(sessionId, {
307
+ sessionId,
308
+ totalCost: 0,
309
+ inputTokens: 0, outputTokens: 0,
310
+ cacheCreationTokens: 0, cacheReadTokens: 0,
311
+ messages: [],
312
+ models: new Set(),
313
+ firstPrompt: '',
314
+ firstTimestamp: null,
315
+ lastTimestamp: null,
316
+ });
317
+ }
318
+ const session = sessions.get(sessionId);
319
+
320
+ await processJSONLFile(file, async (line) => {
321
+ const data = parseUsageLine(line);
322
+ if (!data) return;
323
+
324
+ const hash = createDedupeHash(data);
325
+ if (hash && seen.has(hash)) return;
326
+ if (hash) seen.add(hash);
327
+
328
+ const cost = calculateEntryCost(data, pricing);
329
+ const usage = data.message.usage;
330
+ const model = data.message?.model || 'unknown';
331
+ const ts = data.timestamp;
332
+
333
+ session.totalCost += cost;
334
+ session.inputTokens += usage.input_tokens || 0;
335
+ session.outputTokens += usage.output_tokens || 0;
336
+ session.cacheCreationTokens += (usage.cache_creation_input_tokens || 0);
337
+ session.cacheReadTokens += (usage.cache_read_input_tokens || 0);
338
+ session.models.add(model);
339
+
340
+ if (!session.firstTimestamp || ts < session.firstTimestamp) session.firstTimestamp = ts;
341
+ if (!session.lastTimestamp || ts > session.lastTimestamp) session.lastTimestamp = ts;
342
+
343
+ session.messages.push({
344
+ timestamp: ts,
345
+ model,
346
+ cost,
347
+ inputTokens: usage.input_tokens || 0,
348
+ outputTokens: usage.output_tokens || 0,
349
+ cacheCreationTokens: usage.cache_creation_input_tokens || 0,
350
+ cacheReadTokens: usage.cache_read_input_tokens || 0,
351
+ speed: usage.speed || 'standard',
352
+ });
353
+
354
+ // Capture first user prompt from the JSONL (look for human/user messages)
355
+ if (!session.firstPrompt && data.type === 'human' && data.message?.content) {
356
+ const content = Array.isArray(data.message.content)
357
+ ? data.message.content.map(c => c.text || '').join(' ')
358
+ : (typeof data.message.content === 'string' ? data.message.content : '');
359
+ if (content.trim()) {
360
+ session.firstPrompt = content.trim().slice(0, 120);
361
+ }
362
+ }
363
+ });
364
+ }
365
+
366
+ return sessions;
367
+ }
368
+
369
+ async function getOverviewData(days) {
370
+ const cacheKey = `overview_${days}`;
371
+ if (isCacheValid(cacheKey)) return dataCache[cacheKey];
372
+
373
+ const pricing = await fetchPricing();
374
+ const now = new Date();
375
+ const cutoff = new Date(now);
376
+ cutoff.setDate(cutoff.getDate() - days);
377
+ const projects = scanProjectDirs(cutoff);
378
+ const cutoffStr = cutoff.toISOString();
379
+
380
+ let totalCost = 0, totalSessions = 0;
381
+ let totalInput = 0, totalOutput = 0, totalCacheCreation = 0, totalCacheRead = 0;
382
+ const dailyCosts = {};
383
+ const modelCosts = {};
384
+ const projectSummaries = [];
385
+
386
+ for (const [encodedPath, proj] of projects) {
387
+ const sessions = await loadProjectData(proj.files, pricing);
388
+ let projCost = 0, projSessions = 0, projLastActive = null;
389
+ const projModels = new Set();
390
+
391
+ for (const [, session] of sessions) {
392
+ // Filter messages within date range
393
+ const inRange = session.messages.filter(m => m.timestamp >= cutoffStr);
394
+ if (inRange.length === 0) continue;
395
+
396
+ let sessionCost = 0, sessionInput = 0, sessionOutput = 0, sessionCacheCreation = 0, sessionCacheRead = 0;
397
+ for (const m of inRange) {
398
+ sessionCost += m.cost;
399
+ sessionInput += m.inputTokens;
400
+ sessionOutput += m.outputTokens;
401
+ sessionCacheCreation += m.cacheCreationTokens;
402
+ sessionCacheRead += m.cacheReadTokens;
403
+ const day = localDateStr(new Date(m.timestamp));
404
+ dailyCosts[day] = (dailyCosts[day] || 0) + m.cost;
405
+ if (m.model && !m.model.startsWith('<')) {
406
+ modelCosts[m.model] = (modelCosts[m.model] || 0) + m.cost;
407
+ projModels.add(m.model);
408
+ }
409
+ if (!projLastActive || m.timestamp > projLastActive) projLastActive = m.timestamp;
410
+ }
411
+
412
+ totalCost += sessionCost;
413
+ totalInput += sessionInput;
414
+ totalOutput += sessionOutput;
415
+ totalCacheCreation += sessionCacheCreation;
416
+ totalCacheRead += sessionCacheRead;
417
+ totalSessions++;
418
+ projCost += sessionCost;
419
+ projSessions++;
420
+ }
421
+
422
+ if (projSessions > 0) {
423
+ projectSummaries.push({
424
+ encodedPath,
425
+ name: decodeProjectPath(encodedPath),
426
+ totalCost: projCost,
427
+ sessionCount: projSessions,
428
+ lastActive: projLastActive,
429
+ primaryModel: [...projModels].sort((a, b) => (modelCosts[b] || 0) - (modelCosts[a] || 0))[0] || 'unknown',
430
+ });
431
+ }
432
+ }
433
+
434
+ // Build sorted daily array
435
+ const filledDaily = [];
436
+ if (Object.keys(dailyCosts).length > 0) {
437
+ const start = new Date(cutoff);
438
+ start.setHours(0, 0, 0, 0);
439
+ for (let d = new Date(start); d <= now; d.setDate(d.getDate() + 1)) {
440
+ const ds = localDateStr(d);
441
+ filledDaily.push({ date: ds, cost: dailyCosts[ds] || 0 });
442
+ }
443
+ }
444
+
445
+ const todayStr = localDateStr(now);
446
+ const todayCost = dailyCosts[todayStr] || 0;
447
+
448
+ const totalInputAll = totalInput + totalCacheCreation + totalCacheRead;
449
+ const cacheEfficiency = totalInputAll > 0 ? totalCacheRead / totalInputAll : 0;
450
+
451
+ // Model distribution sorted by cost
452
+ const modelDistribution = Object.entries(modelCosts)
453
+ .filter(([model, cost]) => cost > 0 && !model.startsWith('<'))
454
+ .map(([model, cost]) => ({ model, cost }))
455
+ .sort((a, b) => b.cost - a.cost);
456
+
457
+ const result = {
458
+ summary: {
459
+ totalCost, todayCost,
460
+ totalSessions,
461
+ totalTokens: totalInput + totalOutput + totalCacheCreation + totalCacheRead,
462
+ totalInput, totalOutput, totalCacheCreation, totalCacheRead,
463
+ cacheEfficiency,
464
+ },
465
+ daily: filledDaily,
466
+ modelDistribution,
467
+ projects: projectSummaries.sort((a, b) => b.totalCost - a.totalCost),
468
+ };
469
+
470
+ setCache(cacheKey, result);
471
+ return result;
472
+ }
473
+
474
+ async function getProjectsData(days) {
475
+ const cacheKey = `projects_${days || 'all'}`;
476
+ if (isCacheValid(cacheKey)) return dataCache[cacheKey];
477
+
478
+ const pricing = await fetchPricing();
479
+ const now = new Date();
480
+ const cutoff = days ? new Date(now) : null;
481
+ if (cutoff) cutoff.setDate(cutoff.getDate() - days);
482
+ const projects = scanProjectDirs(cutoff);
483
+ const cutoffStr = cutoff ? cutoff.toISOString() : null;
484
+ const result = [];
485
+
486
+ for (const [encodedPath, proj] of projects) {
487
+ const sessions = await loadProjectData(proj.files, pricing);
488
+ let totalCost = 0, sessionCount = 0, lastActive = null;
489
+ const models = new Set();
490
+
491
+ for (const [, session] of sessions) {
492
+ const msgs = cutoffStr
493
+ ? session.messages.filter(m => m.timestamp >= cutoffStr)
494
+ : session.messages;
495
+ if (msgs.length === 0) continue;
496
+
497
+ const cost = msgs.reduce((s, m) => s + m.cost, 0);
498
+ totalCost += cost;
499
+ sessionCount++;
500
+ for (const m of session.models) models.add(m);
501
+ if (!lastActive || (session.lastTimestamp && session.lastTimestamp > lastActive)) {
502
+ lastActive = session.lastTimestamp;
503
+ }
504
+ }
505
+
506
+ if (sessionCount > 0) {
507
+ result.push({
508
+ encodedPath,
509
+ name: decodeProjectPath(encodedPath),
510
+ totalCost,
511
+ sessionCount,
512
+ lastActive,
513
+ primaryModel: [...models][0] || 'unknown',
514
+ });
515
+ }
516
+ }
517
+
518
+ const sorted = result.sort((a, b) => b.totalCost - a.totalCost);
519
+ setCache(cacheKey, sorted);
520
+ return sorted;
521
+ }
522
+
523
+ async function getProjectSessionsData(encodedPath, days) {
524
+ const cacheKey = `sessions_${encodedPath}_${days || 'all'}`;
525
+ if (isCacheValid(cacheKey)) return dataCache[cacheKey];
526
+
527
+ const pricing = await fetchPricing();
528
+ const now = new Date();
529
+ const cutoff = days ? new Date(now) : null;
530
+ if (cutoff) cutoff.setDate(cutoff.getDate() - days);
531
+ const projects = scanProjectDirs(cutoff);
532
+ const proj = projects.get(encodedPath);
533
+ if (!proj) return [];
534
+
535
+ const sessions = await loadProjectData(proj.files, pricing);
536
+ const cutoffStr = cutoff ? cutoff.toISOString() : null;
537
+ const result = [];
538
+
539
+ for (const [, session] of sessions) {
540
+ const msgs = cutoffStr
541
+ ? session.messages.filter(m => m.timestamp >= cutoffStr)
542
+ : session.messages;
543
+ if (msgs.length === 0) continue;
544
+
545
+ let cost = 0, input = 0, output = 0, cacheCreation = 0, cacheRead = 0;
546
+ for (const m of msgs) {
547
+ cost += m.cost; input += m.inputTokens; output += m.outputTokens;
548
+ cacheCreation += m.cacheCreationTokens; cacheRead += m.cacheReadTokens;
549
+ }
550
+ const durationMs = session.firstTimestamp && session.lastTimestamp
551
+ ? new Date(session.lastTimestamp) - new Date(session.firstTimestamp)
552
+ : 0;
553
+
554
+ result.push({
555
+ sessionId: session.sessionId,
556
+ totalCost: cost,
557
+ inputTokens: input,
558
+ outputTokens: output,
559
+ cacheCreationTokens: cacheCreation,
560
+ cacheReadTokens: cacheRead,
561
+ totalTokens: input + output + cacheCreation + cacheRead,
562
+ messageCount: msgs.length,
563
+ models: [...session.models],
564
+ primaryModel: [...session.models][0] || 'unknown',
565
+ firstPrompt: session.firstPrompt,
566
+ firstTimestamp: session.firstTimestamp,
567
+ lastTimestamp: session.lastTimestamp,
568
+ durationMinutes: Math.round(durationMs / 60000),
569
+ });
570
+ }
571
+
572
+ const sorted = result.sort((a, b) => (b.lastTimestamp || '').localeCompare(a.lastTimestamp || ''));
573
+ setCache(cacheKey, sorted);
574
+ return sorted;
575
+ }
576
+
577
+ async function getSessionDetailData(sessionId) {
578
+ const cacheKey = `detail_${sessionId}`;
579
+ if (isCacheValid(cacheKey)) return dataCache[cacheKey];
580
+
581
+ const pricing = await fetchPricing();
582
+ const projects = scanProjectDirs();
583
+
584
+ // Find the session across all projects
585
+ for (const [encodedPath, proj] of projects) {
586
+ const matchingFile = proj.files.find(f => getSessionIdFromFile(f) === sessionId);
587
+ if (!matchingFile) continue;
588
+
589
+ const sessions = await loadProjectData([matchingFile], pricing);
590
+ const session = sessions.get(sessionId);
591
+ if (!session) continue;
592
+
593
+ // Sort messages by timestamp
594
+ session.messages.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
595
+
596
+ // Add cumulative cost
597
+ let cumulative = 0;
598
+ const messages = session.messages.map((m, i) => {
599
+ cumulative += m.cost;
600
+ return { ...m, index: i + 1, cumulativeCost: cumulative };
601
+ });
602
+
603
+ const result = {
604
+ sessionId,
605
+ projectPath: decodeProjectPath(encodedPath),
606
+ encodedProjectPath: encodedPath,
607
+ totalCost: session.totalCost,
608
+ inputTokens: session.inputTokens,
609
+ outputTokens: session.outputTokens,
610
+ cacheCreationTokens: session.cacheCreationTokens,
611
+ cacheReadTokens: session.cacheReadTokens,
612
+ models: [...session.models],
613
+ firstPrompt: session.firstPrompt,
614
+ firstTimestamp: session.firstTimestamp,
615
+ lastTimestamp: session.lastTimestamp,
616
+ messages,
617
+ };
618
+
619
+ setCache(cacheKey, result);
620
+ return result;
621
+ }
622
+
623
+ return null;
624
+ }
625
+
626
+ // #endregion
627
+
628
+ // #region EXPRESS
629
+
630
+ const app = express();
631
+ app.use(express.json());
632
+ app.use(express.static(path.join(__dirname, 'public')));
633
+
634
+ app.get('/hub-config', (_req, res) => {
635
+ res.json({ enabled: !!process.env.CLAUDE_HUB, url: process.env.HUB_URL || null });
636
+ });
637
+
638
+ app.get('/api/overview', async (req, res) => {
639
+ try {
640
+ const range = parseInt(req.query.range) || 30;
641
+ const data = await getOverviewData(range);
642
+ res.json(data);
643
+ } catch (err) {
644
+ console.error('[API] overview error:', err);
645
+ res.status(500).json({ error: 'Failed to load overview data' });
646
+ }
647
+ });
648
+
649
+ app.get('/api/projects', async (req, res) => {
650
+ try {
651
+ const range = req.query.range ? parseInt(req.query.range) : null;
652
+ const data = await getProjectsData(range);
653
+ res.json(data);
654
+ } catch (err) {
655
+ console.error('[API] projects error:', err);
656
+ res.status(500).json({ error: 'Failed to load projects data' });
657
+ }
658
+ });
659
+
660
+ app.get('/api/projects/:path/sessions', async (req, res) => {
661
+ try {
662
+ const range = req.query.range ? parseInt(req.query.range) : null;
663
+ const data = await getProjectSessionsData(req.params.path, range);
664
+ res.json(data);
665
+ } catch (err) {
666
+ console.error('[API] sessions error:', err);
667
+ res.status(500).json({ error: 'Failed to load sessions data' });
668
+ }
669
+ });
670
+
671
+ app.get('/api/sessions/:id', async (req, res) => {
672
+ try {
673
+ const data = await getSessionDetailData(req.params.id);
674
+ if (!data) return res.status(404).json({ error: 'Session not found' });
675
+ res.json(data);
676
+ } catch (err) {
677
+ console.error('[API] session detail error:', err);
678
+ res.status(500).json({ error: 'Failed to load session detail' });
679
+ }
680
+ });
681
+
682
+ app.get('/api/pricing', async (_req, res) => {
683
+ try {
684
+ const pricing = await fetchPricing();
685
+ const models = {};
686
+ for (const [name, info] of pricing) {
687
+ if (name.startsWith('anthropic/') || name.startsWith('claude')) {
688
+ models[name] = info;
689
+ }
690
+ }
691
+ res.json(models);
692
+ } catch (err) {
693
+ console.error('[API] pricing error:', err);
694
+ res.status(500).json({ error: 'Failed to load pricing data' });
695
+ }
696
+ });
697
+
698
+ app.post('/api/refresh', (_req, res) => {
699
+ invalidateAllCache();
700
+ res.json({ ok: true });
701
+ });
702
+
703
+ // #endregion
704
+
705
+ // #region STARTUP
706
+
707
+ const server = app.listen(PORT, () => {
708
+ const actualPort = server.address().port;
709
+ console.log(`Claude Code Cost Dashboard running at http://localhost:${actualPort}`);
710
+
711
+ if (process.argv.includes('--open')) {
712
+ import('open').then(mod => mod.default(`http://localhost:${actualPort}`));
713
+ }
714
+ });
715
+
716
+ server.on('error', (err) => {
717
+ if (err.code === 'EADDRINUSE') {
718
+ console.log(`Port ${PORT} in use, trying random port...`);
719
+ const fallback = app.listen(0, () => {
720
+ const p = fallback.address().port;
721
+ console.log(`Claude Code Cost Dashboard running at http://localhost:${p}`);
722
+ if (process.argv.includes('--open')) {
723
+ import('open').then(mod => mod.default(`http://localhost:${p}`));
724
+ }
725
+ });
726
+ } else {
727
+ throw err;
728
+ }
729
+ });
730
+
731
+ // Pre-fetch pricing on startup
732
+ fetchPricing().catch(() => {});
733
+
734
+ // #endregion