claude-code-cost 0.4.1 → 0.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-code-cost",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "Cost dashboard for Claude Code usage",
5
5
  "main": "server.js",
6
6
  "bin": {
@@ -21,5 +21,30 @@
21
21
  "devDependencies": {
22
22
  "husky": "^9.0.0"
23
23
  },
24
- "license": "MIT"
24
+ "keywords": [
25
+ "claude",
26
+ "claude-code",
27
+ "cost",
28
+ "dashboard",
29
+ "anthropic",
30
+ "ai",
31
+ "cli",
32
+ "usage"
33
+ ],
34
+ "homepage": "https://github.com/NikiforovAll/claude-code-cost",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/NikiforovAll/claude-code-cost.git"
38
+ },
39
+ "bugs": {
40
+ "url": "https://github.com/NikiforovAll/claude-code-cost/issues"
41
+ },
42
+ "author": "NikiforovAll",
43
+ "license": "MIT",
44
+ "files": [
45
+ "server.js",
46
+ "public/",
47
+ "README.md",
48
+ "LICENSE"
49
+ ]
25
50
  }
package/public/app.js CHANGED
@@ -72,7 +72,10 @@ function shortDate(dateStr) {
72
72
 
73
73
  function shortModel(model) {
74
74
  if (!model) return 'unknown';
75
- return model.replace('anthropic/', '').replace(/-\d{8}$/, '');
75
+ return model
76
+ .replace('anthropic/', '')
77
+ .replace(/^claude-/, '')
78
+ .replace(/-\d{8}$/, '');
76
79
  }
77
80
 
78
81
  function sortCompare(a, b, field, order) {
@@ -121,7 +124,11 @@ function focusPreviousRow(view) {
121
124
  // #region URL_STATE
122
125
 
123
126
  function getUrlState() {
124
- const p = new URLSearchParams(window.location.search);
127
+ let p = new URLSearchParams(window.location.search);
128
+ if (!p.has('view') && !p.has('session') && !p.has('project')) {
129
+ const saved = sessionStorage.getItem('cc-cost:nav');
130
+ if (saved) p = new URLSearchParams(saved);
131
+ }
125
132
  return {
126
133
  view: p.get('view') || 'overview',
127
134
  project: p.get('project'),
@@ -142,8 +149,8 @@ function saveDateRange(val) {
142
149
  localStorage.setItem('cc-cost:range', String(val));
143
150
  }
144
151
 
145
- function loadSort(view) {
146
- const raw = localStorage.getItem(`cc-cost:sort:${view}`);
152
+ function loadSort() {
153
+ const raw = localStorage.getItem('cc-cost:sort');
147
154
  if (raw) {
148
155
  try {
149
156
  const { field, order } = JSON.parse(raw);
@@ -155,8 +162,8 @@ function loadSort(view) {
155
162
  }
156
163
  }
157
164
 
158
- function saveSort(view) {
159
- localStorage.setItem(`cc-cost:sort:${view}`, JSON.stringify({ field: sortField, order: sortOrder }));
165
+ function saveSort() {
166
+ localStorage.setItem('cc-cost:sort', JSON.stringify({ field: sortField, order: sortOrder }));
160
167
  }
161
168
 
162
169
  function updateUrl() {
@@ -170,6 +177,7 @@ function updateUrl() {
170
177
  if (sortOrder !== 'desc') p.set('order', sortOrder);
171
178
  const qs = p.toString();
172
179
  history.replaceState(null, '', qs ? `?${qs}` : '/');
180
+ sessionStorage.setItem('cc-cost:nav', qs);
173
181
  }
174
182
 
175
183
  // #endregion
@@ -560,7 +568,10 @@ function renderDetail() {
560
568
  </div>
561
569
  <div class="detail-stat">
562
570
  <div class="detail-label">Models</div>
563
- <div class="detail-value">${d.models.map((m) => shortModel(m)).join(', ')}</div>
571
+ <div class="detail-value">${d.models
572
+ .map((m) => shortModel(m))
573
+ .filter(Boolean)
574
+ .join(', ')}</div>
564
575
  </div>
565
576
  </div>
566
577
 
@@ -589,33 +600,43 @@ function renderDetail() {
589
600
  <th>Cumulative</th>
590
601
  </tr></thead>
591
602
  <tbody>
592
- ${[...d.messages]
593
- .reverse()
594
- .map(
595
- (m) => `
596
- <tr>
597
- <td class="muted">${m.index}</td>
598
- <td class="muted">${new Date(m.timestamp).toLocaleTimeString()}</td>
599
- <td><span class="model-badge">${esc(shortModel(m.model))}</span></td>
600
- <td>${formatTokens(m.inputTokens)}</td>
601
- <td>${formatTokens(m.outputTokens)}</td>
602
- <td>${formatTokens(m.cacheCreationTokens)}</td>
603
- <td>${formatTokens(m.cacheReadTokens)}</td>
604
- <td class="cost-cell">${formatCost(m.cost)}</td>
605
- <td class="cumulative">${formatCost(m.cumulativeCost)}</td>
606
- </tr>`,
607
- )
608
- .join('')}
603
+ ${buildMessageRowsWithSubagents(d)}
609
604
  </tbody>
610
605
  </table>
611
606
  </div>`;
612
607
 
613
608
  requestAnimationFrame(() => {
614
- renderCumulativeChart(d.messages);
615
- renderTokenBreakdownChart(d.messages);
609
+ const parentMessages = d.messages.filter((m) => !m._subagent);
610
+ renderCumulativeChart(parentMessages);
611
+ renderTokenBreakdownChart(parentMessages);
616
612
  });
617
613
  }
618
614
 
615
+ function buildMessageRowsWithSubagents(d) {
616
+ return [...d.messages]
617
+ .reverse()
618
+ .map((m) => buildMessageRow(m))
619
+ .join('');
620
+ }
621
+
622
+ function buildMessageRow(m) {
623
+ const sa = m._subagent;
624
+ const modelCol = sa
625
+ ? `<span class="model-badge">${esc(shortModel(m.model))}</span> <span class="subagent-tag">${esc(sa.agentType)}</span>`
626
+ : `<span class="model-badge">${esc(shortModel(m.model))}</span>`;
627
+ return `<tr>
628
+ <td class="muted">${m.index}</td>
629
+ <td class="muted">${new Date(m.timestamp).toLocaleTimeString()}</td>
630
+ <td>${modelCol}</td>
631
+ <td>${formatTokens(m.inputTokens)}</td>
632
+ <td>${formatTokens(m.outputTokens)}</td>
633
+ <td>${formatTokens(m.cacheCreationTokens)}</td>
634
+ <td>${formatTokens(m.cacheReadTokens)}</td>
635
+ <td class="cost-cell">${formatCost(m.cost)}</td>
636
+ <td class="cumulative">${formatCost(m.cumulativeCost)}</td>
637
+ </tr>`;
638
+ }
639
+
619
640
  // #endregion
620
641
 
621
642
  // #region CHARTS
@@ -909,7 +930,7 @@ function showView(viewId) {
909
930
 
910
931
  async function navigate(view, params) {
911
932
  currentView = view;
912
- loadSort(view);
933
+ loadSort();
913
934
  if (params?.project) currentProjectPath = params.project;
914
935
  if (params?.projectName) currentProjectName = params.projectName;
915
936
  if (params?.session) currentSessionId = params.session;
@@ -958,7 +979,7 @@ function sortBy(field) {
958
979
  sortOrder = 'desc';
959
980
  }
960
981
  lastRenderHash[currentView] = null;
961
- saveSort(currentView);
982
+ saveSort();
962
983
  updateUrl();
963
984
  if (currentView === 'overview') renderOverview();
964
985
  else if (currentView === 'sessions') renderSessions();
@@ -1296,7 +1317,7 @@ document.addEventListener('DOMContentLoaded', async () => {
1296
1317
  window.addEventListener('popstate', () => {
1297
1318
  const state = getUrlState();
1298
1319
  currentView = state.view || 'overview';
1299
- loadSort(currentView);
1320
+ loadSort();
1300
1321
  parentView = state.parentView;
1301
1322
  currentProjectPath = state.project;
1302
1323
  currentProjectName = state.projectName;
package/public/style.css CHANGED
@@ -533,6 +533,22 @@ body {
533
533
 
534
534
  /* #endregion */
535
535
 
536
+ /* #region SUBAGENT */
537
+
538
+ .subagent-tag {
539
+ font-size: 9px;
540
+ text-transform: uppercase;
541
+ letter-spacing: 0.03em;
542
+ color: var(--text-muted);
543
+ background: var(--bg-hover);
544
+ padding: 1px 5px;
545
+ border-radius: 3px;
546
+ margin-left: 4px;
547
+ vertical-align: middle;
548
+ }
549
+
550
+ /* #endregion */
551
+
536
552
  /* #region LOADING */
537
553
 
538
554
  .loading-state {
package/server.js CHANGED
@@ -306,6 +306,73 @@ function getSessionIdFromFile(filePath) {
306
306
  return path.basename(filePath, '.jsonl');
307
307
  }
308
308
 
309
+ function scanSubagentDir(sessionDir) {
310
+ const subagentsDir = path.join(sessionDir, 'subagents');
311
+ const result = [];
312
+ try {
313
+ for (const f of fs.readdirSync(subagentsDir)) {
314
+ if (!f.endsWith('.jsonl')) continue;
315
+ const agentId = f.replace('.jsonl', '');
316
+ const metaPath = path.join(subagentsDir, `${agentId}.meta.json`);
317
+ let meta = {};
318
+ try { meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8')); } catch { /* no meta */ }
319
+ result.push({
320
+ agentId,
321
+ filePath: path.join(subagentsDir, f),
322
+ agentType: meta.agentType || 'unknown',
323
+ description: meta.description || '',
324
+ });
325
+ }
326
+ } catch { /* dir doesn't exist or unreadable */ }
327
+ return result;
328
+ }
329
+
330
+ function mostFrequentModel(counts) {
331
+ return Object.entries(counts).sort((a, b) => b[1] - a[1])[0]?.[0] || 'unknown';
332
+ }
333
+
334
+ async function loadSubagentData(subagentInfos, pricing) {
335
+ return Promise.all(subagentInfos.map(async (info) => {
336
+ const agent = {
337
+ agentId: info.agentId,
338
+ agentType: info.agentType,
339
+ description: info.description,
340
+ totalCost: 0,
341
+ inputTokens: 0, outputTokens: 0,
342
+ cacheCreationTokens: 0, cacheReadTokens: 0,
343
+ messageCount: 0,
344
+ models: new Set(),
345
+ firstTimestamp: null,
346
+ };
347
+ const seen = new Set();
348
+ await processJSONLFile(info.filePath, async (line) => {
349
+ let parsed;
350
+ try { parsed = JSON.parse(line); } catch { return; }
351
+ if (!parsed.message?.usage?.input_tokens && parsed.message?.usage?.input_tokens !== 0) return;
352
+ if (!parsed.timestamp) return;
353
+
354
+ const hash = createDedupeHash(parsed);
355
+ if (hash && seen.has(hash)) return;
356
+ if (hash) seen.add(hash);
357
+
358
+ const cost = calculateEntryCost(parsed, pricing);
359
+ const usage = parsed.message.usage;
360
+ agent.totalCost += cost;
361
+ agent.inputTokens += usage.input_tokens || 0;
362
+ agent.outputTokens += usage.output_tokens || 0;
363
+ agent.cacheCreationTokens += (usage.cache_creation_input_tokens || 0);
364
+ agent.cacheReadTokens += (usage.cache_read_input_tokens || 0);
365
+ agent.messageCount++;
366
+ agent.models.add(parsed.message?.model || 'unknown');
367
+ if (!agent.firstTimestamp || parsed.timestamp < agent.firstTimestamp) {
368
+ agent.firstTimestamp = parsed.timestamp;
369
+ }
370
+ });
371
+ agent.models = [...agent.models];
372
+ return agent;
373
+ }));
374
+ }
375
+
309
376
  async function loadProjectData(files, pricing) {
310
377
  const sessions = new Map();
311
378
  const seen = new Set();
@@ -380,6 +447,32 @@ async function loadProjectData(files, pricing) {
380
447
  }
381
448
  }
382
449
  });
450
+
451
+ // Fold subagent costs into session totals
452
+ const sessionDir = path.join(path.dirname(file), sessionId);
453
+ const subagentInfos = scanSubagentDir(sessionDir);
454
+ if (subagentInfos.length > 0) {
455
+ const subagents = await loadSubagentData(subagentInfos, pricing);
456
+ for (const sa of subagents) {
457
+ session.totalCost += sa.totalCost;
458
+ session.inputTokens += sa.inputTokens;
459
+ session.outputTokens += sa.outputTokens;
460
+ session.cacheCreationTokens += sa.cacheCreationTokens;
461
+ session.cacheReadTokens += sa.cacheReadTokens;
462
+ for (const m of sa.models) session.models.add(m);
463
+ session.messages.push({
464
+ timestamp: sa.firstTimestamp || session.firstTimestamp,
465
+ model: sa.models[0] || 'unknown',
466
+ cost: sa.totalCost,
467
+ inputTokens: sa.inputTokens,
468
+ outputTokens: sa.outputTokens,
469
+ cacheCreationTokens: sa.cacheCreationTokens,
470
+ cacheReadTokens: sa.cacheReadTokens,
471
+ speed: 'standard',
472
+ _subagent: { agentId: sa.agentId, agentType: sa.agentType, description: sa.description, messageCount: sa.messageCount },
473
+ });
474
+ }
475
+ }
383
476
  }
384
477
 
385
478
  return sessions;
@@ -494,7 +587,7 @@ async function getProjectsData(days) {
494
587
  for (const [encodedPath, proj] of projects) {
495
588
  const sessions = await loadProjectData(proj.files, pricing);
496
589
  let totalCost = 0, sessionCount = 0, lastActive = null;
497
- const models = new Set();
590
+ const projModelCounts = {};
498
591
 
499
592
  for (const [, session] of sessions) {
500
593
  const msgs = cutoffStr
@@ -505,7 +598,11 @@ async function getProjectsData(days) {
505
598
  const cost = msgs.reduce((s, m) => s + m.cost, 0);
506
599
  totalCost += cost;
507
600
  sessionCount++;
508
- for (const m of session.models) models.add(m);
601
+ for (const m of msgs) {
602
+ if (m.model && !m.model.startsWith('<')) {
603
+ projModelCounts[m.model] = (projModelCounts[m.model] || 0) + 1;
604
+ }
605
+ }
509
606
  if (!lastActive || (session.lastTimestamp && session.lastTimestamp > lastActive)) {
510
607
  lastActive = session.lastTimestamp;
511
608
  }
@@ -518,7 +615,7 @@ async function getProjectsData(days) {
518
615
  totalCost,
519
616
  sessionCount,
520
617
  lastActive,
521
- primaryModel: [...models][0] || 'unknown',
618
+ primaryModel: mostFrequentModel(projModelCounts),
522
619
  });
523
620
  }
524
621
  }
@@ -553,6 +650,7 @@ async function getProjectSessionsData(encodedPath, days) {
553
650
  if (msgs.length === 0) continue;
554
651
 
555
652
  let cost = 0, input = 0, output = 0, cacheCreation = 0, cacheRead = 0;
653
+ const sessionModelCounts = {};
556
654
  for (const m of msgs) {
557
655
  cost += m.cost; input += m.inputTokens; output += m.outputTokens;
558
656
  cacheCreation += m.cacheCreationTokens; cacheRead += m.cacheReadTokens;
@@ -560,11 +658,13 @@ async function getProjectSessionsData(encodedPath, days) {
560
658
  dailyCosts[day] = (dailyCosts[day] || 0) + m.cost;
561
659
  if (m.model && !m.model.startsWith('<')) {
562
660
  modelCosts[m.model] = (modelCosts[m.model] || 0) + m.cost;
661
+ sessionModelCounts[m.model] = (sessionModelCounts[m.model] || 0) + 1;
563
662
  }
564
663
  }
565
664
  const durationMs = session.firstTimestamp && session.lastTimestamp
566
665
  ? new Date(session.lastTimestamp) - new Date(session.firstTimestamp)
567
666
  : 0;
667
+ const primaryModel = mostFrequentModel(sessionModelCounts);
568
668
 
569
669
  result.push({
570
670
  sessionId: session.sessionId,
@@ -577,7 +677,7 @@ async function getProjectSessionsData(encodedPath, days) {
577
677
  totalTokens: input + output + cacheCreation + cacheRead,
578
678
  messageCount: msgs.length,
579
679
  models: [...session.models],
580
- primaryModel: [...session.models][0] || 'unknown',
680
+ primaryModel,
581
681
  firstPrompt: session.firstPrompt,
582
682
  firstTimestamp: session.firstTimestamp,
583
683
  lastTimestamp: session.lastTimestamp,
@@ -1,54 +0,0 @@
1
- ---
2
- description: Bump version, tag, push, and create a GitHub release with auto-generated notes
3
- argument-hint: "[version e.g. 1.13.0 or rc4]"
4
- ---
5
-
6
- # Release
7
-
8
- Create a new release for this project.
9
-
10
- ## Inputs
11
-
12
- - `$ARGUMENTS` — target version or shorthand. Examples:
13
- - `1.13.0` — full version
14
- - `rc4` — shorthand for next RC (e.g. if current is `1.19.0-rc.3`, becomes `1.19.0-rc.4`)
15
- - If not provided, ask the user.
16
-
17
- ## Steps
18
-
19
- 1. **Determine version**: Use `$ARGUMENTS` or ask user. Handle `rc<N>` shorthand by reading current version from `package.json` and replacing/appending the RC suffix. Validate it's different from the current version.
20
-
21
- 2. **Detect prerelease**: If version contains `-rc.`, `-alpha.`, `-beta.`, treat as prerelease.
22
-
23
- 3. **Check working tree**: Run `git status`. If there are uncommitted changes, warn the user and stop.
24
-
25
- 4. **Bump version**:
26
- ```
27
- npm version <version> --no-git-tag-version
28
- ```
29
-
30
- 5. **Commit & push** (push to current branch, not hardcoded `main`):
31
- ```
32
- git add package.json package-lock.json
33
- git commit -m "🔖 chore: Bump version to <version>"
34
- git push origin HEAD
35
- ```
36
-
37
- 6. **Tag & push tag**:
38
- ```
39
- git tag v<version>
40
- git push origin v<version>
41
- ```
42
-
43
- 7. **Generate release notes**: Collect commits since the previous tag using `git log --oneline <prev-tag>..HEAD`. Write a **user-facing summary** grouped by:
44
- - Features (✨) — describe what was added, not raw commit messages
45
- - Fixes (🐛)
46
- - Other notable changes
47
- Include a "Full Changelog" compare link at the bottom.
48
-
49
- 8. **Create GitHub release** (add `--prerelease` flag for RC/alpha/beta):
50
- ```
51
- gh release create v<version> --title "v<version>" --notes "<notes>" [--prerelease]
52
- ```
53
-
54
- 9. **Report**: Show the release URL to the user.
@@ -1,39 +0,0 @@
1
- name: Deploy to GitHub Pages
2
-
3
- on:
4
- push:
5
- branches: [main]
6
- paths:
7
- - 'docs/**'
8
- - 'assets/**'
9
- workflow_dispatch:
10
-
11
- permissions:
12
- contents: read
13
- pages: write
14
- id-token: write
15
-
16
- concurrency:
17
- group: pages
18
- cancel-in-progress: false
19
-
20
- jobs:
21
- deploy:
22
- environment:
23
- name: github-pages
24
- url: ${{ steps.deployment.outputs.page_url }}
25
- runs-on: ubuntu-latest
26
- steps:
27
- - uses: actions/checkout@v4
28
-
29
- - name: Copy assets into docs for flat serving
30
- run: cp -r assets docs/assets
31
-
32
- - uses: actions/configure-pages@v5
33
-
34
- - uses: actions/upload-pages-artifact@v3
35
- with:
36
- path: docs
37
-
38
- - id: deployment
39
- uses: actions/deploy-pages@v4
package/.husky/pre-commit DELETED
@@ -1 +0,0 @@
1
- npx @biomejs/biome check --error-on-warnings public/app.js public/style.css
package/CLAUDE.md DELETED
@@ -1,42 +0,0 @@
1
- # Claude Code Cost Dashboard
2
-
3
- Cost visualization dashboard for Claude Code usage. Reads JSONL session files from `~/.claude/projects/` and displays costs with top-down drill-down: total → project → session → message.
4
-
5
- ## Commands
6
-
7
- ```bash
8
- npm start # Start server on port 3458
9
- npm run dev # Start with --open flag
10
- node server.js --port 3000 --open # Custom port
11
- ```
12
-
13
- ## Architecture
14
-
15
- - **server.js** — Express server with pricing module, JSONL parsing, data aggregation
16
- - **public/app.js** — Vanilla JS SPA with Chart.js, no build step
17
- - **public/style.css** — CSS variables, dark/light theme (matches cck + marketplace)
18
-
19
- ## Data Flow
20
-
21
- ```
22
- ~/.claude/projects/**/*.jsonl → server.js (parse + aggregate) → REST API → app.js (render + Chart.js)
23
- ```
24
-
25
- ## Pricing
26
-
27
- Dynamic pricing from LiteLLM (`model_prices_and_context_window.json`). Supports tiered pricing (200k threshold), cache token costs, fast mode multiplier. Offline fallback included.
28
-
29
- ## Conventions
30
-
31
- - Vanilla JS only, no frameworks, no build step
32
- - `#region` markers in all JS/CSS files
33
- - CSS variables for theming (shared with cck/marketplace)
34
- - Hub integration via `/hub-config` + `window.__HUB__`
35
-
36
- ## app.js Regions
37
-
38
- STATE, UTILS, URL_STATE, FETCH, RENDER_OVERVIEW, RENDER_PROJECTS, RENDER_SESSIONS, RENDER_DETAIL, CHARTS, THEME, ROUTER, TOAST, HUB_INTEGRATION, INIT
39
-
40
- ## style.css Regions
41
-
42
- VARIABLES, RESET, SCROLLBAR, TOPBAR, LAYOUT, CARDS, CHARTS, TABLE, BREADCRUMB, DETAIL, LOADING, TOAST, LIGHT_THEME, RESPONSIVE
package/PLAN-CONTEXT.md DELETED
@@ -1,83 +0,0 @@
1
- # Claude Code Cost Dashboard — Planning Context
2
-
3
- ## What
4
- Build `claude-code-cost` — a cost dashboard web app for Claude Code Hub. It visualizes Claude Code usage costs with a **top-down drill-down** approach: total costs → per-project → per-session.
5
-
6
- ## Why
7
- The ecosystem has 10+ CLI/TUI cost tools (ccusage, ccburn, ccost, tokscale) but **no polished embeddable web dashboard**. This fills that gap as a new tab in Claude Code Hub alongside kanban and marketplace.
8
-
9
- ## How
10
-
11
- ### Architecture (match sibling apps exactly)
12
- Follow the same Express + vanilla JS + no-build-step pattern used by:
13
- - `../cck/` — kanban app (Express + chokidar + SSE + vanilla JS)
14
- - `../claude-code-marketplace/` — marketplace app (Express + vanilla JS)
15
-
16
- Study these reference codebases (available via --add-dir):
17
- - **Server pattern**: `server.js` with Express, CLI args (--port, --open), `/hub-config` endpoint, static serving
18
- - **Frontend pattern**: `public/app.js` with #region markers, vanilla JS, HTML string rendering, no frameworks
19
- - **Theme system**: CSS variables, dark/light toggle, IBM Plex Mono + Playfair Display fonts, orange accent (#e86f33)
20
- - **Hub integration**: `/hub-config` endpoint, `window.__HUB__`, postMessage forwarding (Ctrl+Alt+Arrow, Alt+1-9)
21
- - **Real-time updates**: chokidar file watchers + SSE broadcasting (from cck)
22
-
23
- ### Pricing — CRITICAL
24
- **DO NOT hardcode model prices.** Study `../ccusage-reference/` source code to understand how ccusage handles pricing dynamically. Use the same approach (whether it's a pricing module, API fetch, or configurable table). The dashboard must stay accurate as models/prices evolve.
25
-
26
- ### Data Sources (all local filesystem, no external APIs)
27
-
28
- 1. **~/.claude/projects/{path}/{session-id}.jsonl** — Raw conversation logs. Each assistant message has:
29
- ```json
30
- "usage": {
31
- "input_tokens": 3,
32
- "cache_creation_input_tokens": 15696,
33
- "cache_read_input_tokens": 0,
34
- "output_tokens": 143
35
- }
36
- ```
37
- Plus `model`, `timestamp`, `sessionId`. This is the primary source for accurate cost calculation.
38
-
39
- 2. **~/.claude/stats-cache.json** — Pre-computed daily aggregates:
40
- - `dailyActivity[]`: date, messageCount, sessionCount, toolCallCount
41
- - `dailyModelTokens[]`: date, tokensByModel (model name → total tokens)
42
-
43
- 3. **~/.claude/usage-data/session-meta/{id}.json** — Per-session metadata:
44
- - input_tokens, output_tokens, project_path, start_time, duration_minutes
45
- - tool_counts, first_prompt, uses_mcp, uses_web_search, lines_added/removed
46
-
47
- 4. **~/.claude/usage-data/facets/{id}.json** — Session quality/outcome metadata
48
-
49
- ### UI — Top-Down Drill-Down
50
- The dashboard should flow top-down:
51
- 1. **Overview cards** — Total cost today/this week/this month, total sessions, total tokens
52
- 2. **Daily cost trend** — Line/bar chart with 7-day moving average
53
- 3. **Per-project breakdown** — Table/cards showing cost per project, sortable
54
- 4. **Per-session details** — Click project to see sessions, click session for message-level cost
55
- 5. **Supporting charts** — Token breakdown (input/output/cache stacked bar), model distribution (donut), cache efficiency ratio, activity heatmap
56
-
57
- ### Tech Stack
58
- - Express.js + chokidar + SSE (server)
59
- - Vanilla JS with #region markers (frontend)
60
- - Chart.js via CDN (charts)
61
- - CSS variables for dark/light theme
62
- - PWA-ready (manifest.json, sw.js, icons/)
63
-
64
- ## When (Scope)
65
- - Plan mode only — design the full implementation plan
66
- - Core cost dashboard features first
67
- - Hub integration included from the start
68
- - No external API dependencies (all local data)
69
-
70
- ## Target Structure
71
- ```
72
- claude-code-cost/
73
- ├── server.js
74
- ├── package.json
75
- ├── CLAUDE.md
76
- ├── public/
77
- │ ├── index.html
78
- │ ├── app.js
79
- │ ├── style.css
80
- │ ├── sw.js
81
- │ ├── manifest.json
82
- │ └── icons/
83
- ```
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
package/biome.json DELETED
@@ -1,33 +0,0 @@
1
- {
2
- "$schema": "https://biomejs.dev/schemas/2.4.10/schema.json",
3
- "formatter": {
4
- "enabled": true,
5
- "indentStyle": "space",
6
- "indentWidth": 2,
7
- "lineWidth": 120
8
- },
9
- "linter": {
10
- "enabled": true,
11
- "rules": {
12
- "style": {
13
- "noDescendingSpecificity": "off"
14
- },
15
- "suspicious": {
16
- "useIterableCallbackReturn": "off"
17
- }
18
- }
19
- },
20
- "javascript": {
21
- "formatter": {
22
- "quoteStyle": "single"
23
- }
24
- },
25
- "css": {
26
- "formatter": {
27
- "quoteStyle": "single"
28
- }
29
- },
30
- "files": {
31
- "includes": ["public/app.js", "public/style.css"]
32
- }
33
- }
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file