claude-code-cost 0.19.1 → 0.20.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.19.1",
3
+ "version": "0.20.0",
4
4
  "description": "Cost dashboard for Claude Code usage",
5
5
  "main": "server.js",
6
6
  "bin": {
package/public/app.js CHANGED
@@ -877,7 +877,7 @@ function renderInsights() {
877
877
  <div class="card-label">Subagent Share</div>
878
878
  <div class="card-value">${subPct}%</div>
879
879
  ${agentTotal > 0 ? meter(subPct, { ariaLabel: `subagents are ${subPct}% of ${formatCost(agentTotal)} in agent cost` }) : ''}
880
- <div class="card-sub"><strong>${formatCost(sub.subagentCost)}</strong> of ${formatCost(agentTotal)}</div>
880
+ <div class="card-sub"><strong>${formatCost(sub.subagentCost)}</strong> of ${formatCost(agentTotal)}${sub.workflowRuns ? ` &middot; ${formatCost(sub.workflowCost)} in ${sub.workflowRuns} workflow${sub.workflowRuns === 1 ? '' : 's'}` : ''}</div>
881
881
  </div>
882
882
  </div>
883
883
 
@@ -1015,7 +1015,7 @@ function renderSessions() {
1015
1015
  <td class="truncate" title="${esc(s.customTitle || s.firstPrompt || s.sessionId)}">${esc(s.customTitle || s.firstPrompt || s.sessionId)}</td>
1016
1016
  <td class="cost-cell">${formatCost(s.totalCost)}</td>
1017
1017
  <td>${formatTokens(s.totalTokens)}</td>
1018
- <td>${s.messageCount}</td>
1018
+ <td>${s.messageCount}${s.compactions?.count ? ` <span class="compaction-tag" title="${esc(`${s.compactions.count} compaction(s), ~${formatCost(s.compactions.totalCost)}`)}">${s.compactions.count}&times; compact</span>` : ''}</td>
1019
1019
  <td class="muted">${formatDuration(s.durationMinutes)}</td>
1020
1020
  <td><span class="model-badge">${esc(shortModel(s.primaryModel))}</span></td>
1021
1021
  <td class="muted">${timeAgo(s.lastTimestamp)}</td>
@@ -1090,9 +1090,12 @@ function renderDetail() {
1090
1090
  <div class="detail-label">Models</div>
1091
1091
  <div class="detail-value">${esc(d.models.map((m) => shortModel(m)).join(', '))}</div>
1092
1092
  </div>
1093
+ ${compactionStat(d.compactions)}
1093
1094
  </div>
1094
1095
 
1095
1096
  ${detailRangeNote(d)}
1097
+ ${compactionNote(d.compactions)}
1098
+ ${workflowsSection(d)}
1096
1099
 
1097
1100
  <div class="charts-row" style="margin-bottom:20px">
1098
1101
  <div class="chart-box">
@@ -1107,7 +1110,7 @@ function renderDetail() {
1107
1110
 
1108
1111
  ${rangeBrushHtml(d.messages.length)}
1109
1112
 
1110
- <div class="section-title">Messages (${d.messages.length})</div>
1113
+ <div class="section-title" id="messagesTitle"></div>
1111
1114
  <table class="messages-table">
1112
1115
  <thead><tr>
1113
1116
  <th>#</th>
@@ -1120,9 +1123,7 @@ function renderDetail() {
1120
1123
  <th>Cost</th>
1121
1124
  <th>Cumulative</th>
1122
1125
  </tr></thead>
1123
- <tbody>
1124
- ${buildMessageRowsWithSubagents(d)}
1125
- </tbody>
1126
+ <tbody id="messagesBody"></tbody>
1126
1127
  </table>
1127
1128
  </div>`;
1128
1129
 
@@ -1151,18 +1152,92 @@ function detailRangeNote(d) {
1151
1152
  return `<div class="detail-range-note">Totals above are all-time &middot; ${parts.join(' &middot; ')}</div>`;
1152
1153
  }
1153
1154
 
1154
- function buildMessageRowsWithSubagents(d) {
1155
- return [...d.messages]
1156
- .reverse()
1157
- .map((m) => buildMessageRow(m))
1155
+ function compactionStat(c) {
1156
+ if (!c?.count) return '';
1157
+ return `<div class="detail-stat">
1158
+ <div class="detail-label">Compactions</div>
1159
+ <div class="detail-value">${c.count}<span class="detail-label detail-scope">~${formatCost(c.totalCost)}</span></div>
1160
+ </div>`;
1161
+ }
1162
+
1163
+ // The summarizer call is not in the JSONL, so its share is an estimate; the re-warm share is real
1164
+ // spend already inside the total. Both are spelled out so the header number is not read as exact.
1165
+ function compactionNote(c) {
1166
+ if (!c?.count) return '';
1167
+ const trigger =
1168
+ c.auto === c.count ? 'all auto' : c.auto === 0 ? 'all manual' : `${c.auto} auto, ${c.count - c.auto} manual`;
1169
+ return `<div class="detail-range-note compaction-note">
1170
+ <span class="scope-label">compaction</span> ${trigger} &middot;
1171
+ dropped <strong>${formatTokens(c.droppedTokens)}</strong> tokens &middot;
1172
+ summarizer <strong>~${formatCost(c.estCost)}</strong> (estimate, not in total) &middot;
1173
+ cache re-warm <strong>${formatCost(c.rewarmCost)}</strong> / ${formatTokens(c.rewarmTokens)} (in total)
1174
+ </div>`;
1175
+ }
1176
+
1177
+ function compactionRow(c) {
1178
+ return `<tr class="compaction-row">
1179
+ <td></td>
1180
+ <td class="muted">${localTime(c.timestamp)}</td>
1181
+ <td colspan="5"><span class="compaction-tag">${esc(c.trigger)} compact</span>
1182
+ ${formatTokens(c.preTokens)} &rarr; ${formatTokens(c.postTokens)} (&minus;${formatPct(c.preTokens - c.postTokens, c.preTokens)}%) &middot; ${Math.round(c.durationMs / 1000)}s</td>
1183
+ <td class="cost-cell">~${formatCost(c.estCost)}</td>
1184
+ <td class="cumulative">est.</td>
1185
+ </tr>`;
1186
+ }
1187
+
1188
+ // A Workflow run fans out to tens of agents, each folded into one message row — so the run itself
1189
+ // is the unit worth reading, not the rows.
1190
+ function workflowsSection(d) {
1191
+ if (!d.workflows?.length) return '';
1192
+ const rows = d.workflows
1193
+ .map((w) => {
1194
+ const pct = d.totalCost > 0 ? Math.round((w.totalCost / d.totalCost) * 100) : 0;
1195
+ const mins = Math.round((new Date(w.lastTimestamp) - new Date(w.firstTimestamp)) / 60000);
1196
+ return `<tr>
1197
+ <td>${esc(w.name)}</td>
1198
+ <td>${w.agents}</td>
1199
+ <td class="muted">${mins} min</td>
1200
+ <td>${formatTokens(w.inputTokens + w.cacheCreationTokens + w.cacheReadTokens)}</td>
1201
+ <td>${formatTokens(w.outputTokens)}</td>
1202
+ <td class="cost-cell">${formatCost(w.totalCost)}</td>
1203
+ <td>${meter(pct, { label: `${pct}%`, ariaLabel: `${pct}% of session cost` })}</td>
1204
+ </tr>`;
1205
+ })
1158
1206
  .join('');
1207
+ return `
1208
+ <div class="section-title">Workflows (${d.workflows.length})</div>
1209
+ <table class="messages-table" style="margin-bottom:20px">
1210
+ <thead><tr>
1211
+ <th>Workflow</th>
1212
+ <th>Agents</th>
1213
+ <th>Span</th>
1214
+ <th>Input</th>
1215
+ <th>Output</th>
1216
+ <th>Cost</th>
1217
+ <th>Share</th>
1218
+ </tr></thead>
1219
+ <tbody>${rows}</tbody>
1220
+ </table>`;
1221
+ }
1222
+
1223
+ function renderMessageRows(slice, total) {
1224
+ const body = document.getElementById('messagesBody');
1225
+ if (!body) return;
1226
+ document.getElementById('messagesTitle').textContent =
1227
+ slice.length === total ? `Messages (${total})` : `Messages (${slice.length} of ${total})`;
1228
+ const rows = [];
1229
+ for (let i = slice.length - 1; i >= 0; i--) {
1230
+ const m = slice[i];
1231
+ rows.push(buildMessageRow(m) + (m.compaction ? compactionRow(m.compaction) : ''));
1232
+ }
1233
+ body.innerHTML = rows.join('');
1159
1234
  }
1160
1235
 
1161
1236
  function buildMessageRow(m) {
1162
1237
  const sa = m._subagent;
1163
1238
  const toolTags = !sa && m.tools ? m.tools.map((t) => `<span class="tool-tag">${esc(t)}</span>`).join(' ') : '';
1164
1239
  const modelCol = sa
1165
- ? `<span class="model-badge">${esc(shortModel(m.model))}</span> <span class="subagent-tag">${esc(sa.agentType)}</span>`
1240
+ ? `<span class="model-badge">${esc(shortModel(m.model))}</span> <span class="subagent-tag">${esc(sa.workflowId ? 'workflow' : sa.agentType)}</span>`
1166
1241
  : `<span class="model-badge">${esc(shortModel(m.model))}</span>${toolTags ? ` ${toolTags}` : ''}`;
1167
1242
  return `<tr>
1168
1243
  <td class="muted">${m.index}</td>
@@ -1468,6 +1543,43 @@ function tokenBreakdownChartData(messages, c) {
1468
1543
  };
1469
1544
  }
1470
1545
 
1546
+ // Draws a dashed vertical line just before each turn that followed a compaction, so the flat
1547
+ // stretch in cache-read and the cache-create spike next to it read as one event, not noise.
1548
+ // Reads chart.$compactions, set by markCompactions, so a draw costs no style lookup or scan.
1549
+ const compactionMarkers = {
1550
+ id: 'compactionMarkers',
1551
+ afterDatasetsDraw(chart) {
1552
+ const marks = chart.$compactions;
1553
+ if (!marks?.indices.length) return;
1554
+ const { ctx, chartArea, scales } = chart;
1555
+ ctx.save();
1556
+ ctx.strokeStyle = marks.color;
1557
+ ctx.lineWidth = 1;
1558
+ ctx.setLineDash([4, 3]);
1559
+ ctx.font = `9px ${marks.font}`;
1560
+ ctx.fillStyle = marks.color;
1561
+ ctx.textAlign = 'center';
1562
+ for (const i of marks.indices) {
1563
+ const p = scales.x.getPixelForValue(i);
1564
+ const x = i > 0 ? (p + scales.x.getPixelForValue(i - 1)) / 2 : p;
1565
+ ctx.beginPath();
1566
+ ctx.moveTo(x, chartArea.top);
1567
+ ctx.lineTo(x, chartArea.bottom);
1568
+ ctx.stroke();
1569
+ ctx.fillText('compact', x, chartArea.top - 2);
1570
+ }
1571
+ ctx.restore();
1572
+ },
1573
+ };
1574
+
1575
+ function markCompactions(chart, messages, c) {
1576
+ chart.$compactions = {
1577
+ indices: messages.flatMap((m, i) => (m.compaction ? [i] : [])),
1578
+ color: c.chart5,
1579
+ font: c.mono,
1580
+ };
1581
+ }
1582
+
1471
1583
  function renderCumulativeChart(messages) {
1472
1584
  const canvas = document.getElementById('cumulativeChart');
1473
1585
  if (!canvas || !messages?.length) return;
@@ -1479,6 +1591,7 @@ function renderCumulativeChart(messages) {
1479
1591
  charts.cumulative = new Chart(canvas, {
1480
1592
  type: 'line',
1481
1593
  data: cumulativeChartData(messages, c),
1594
+ plugins: [compactionMarkers],
1482
1595
  options: {
1483
1596
  ...defaults,
1484
1597
  plugins: withTooltip(defaults, { title: (items) => messageTooltipTitle(detailSlice, items) }),
@@ -1495,6 +1608,7 @@ function renderCumulativeChart(messages) {
1495
1608
  },
1496
1609
  },
1497
1610
  });
1611
+ markCompactions(charts.cumulative, messages, c);
1498
1612
  }
1499
1613
 
1500
1614
  function renderTokenBreakdownChart(messages) {
@@ -1508,6 +1622,7 @@ function renderTokenBreakdownChart(messages) {
1508
1622
  charts.tokenBreakdown = new Chart(canvas, {
1509
1623
  type: 'bar',
1510
1624
  data: tokenBreakdownChartData(messages, c),
1625
+ plugins: [compactionMarkers],
1511
1626
  options: {
1512
1627
  ...defaults,
1513
1628
  plugins: {
@@ -1535,6 +1650,7 @@ function renderTokenBreakdownChart(messages) {
1535
1650
  },
1536
1651
  },
1537
1652
  });
1653
+ markCompactions(charts.tokenBreakdown, messages, c);
1538
1654
  }
1539
1655
 
1540
1656
  // #region RANGE BRUSH
@@ -1559,14 +1675,25 @@ function median(sorted) {
1559
1675
  const CACHE_BURST_RATIO = 4;
1560
1676
  const CACHE_BURST_MIN_TOKENS = 20000;
1561
1677
 
1562
- function cacheBurstIndices(messages) {
1678
+ // A compaction explains the burst on the turn that follows it, so that turn is labelled
1679
+ // `compaction`; `burst` is left for the re-caches with no boundary behind them.
1680
+ function notableEvents(messages) {
1563
1681
  const writes = messages
1564
1682
  .filter((m) => !m._subagent && m.cacheCreationTokens > 0)
1565
1683
  .map((m) => m.cacheCreationTokens)
1566
1684
  .sort((a, b) => a - b);
1567
- if (writes.length < 5) return [];
1568
- const threshold = Math.max(CACHE_BURST_MIN_TOKENS, median(writes) * CACHE_BURST_RATIO);
1569
- return messages.flatMap((m, i) => (!m._subagent && m.cacheCreationTokens >= threshold ? [i] : []));
1685
+ const threshold = writes.length < 5 ? Infinity : Math.max(CACHE_BURST_MIN_TOKENS, median(writes) * CACHE_BURST_RATIO);
1686
+ return messages.flatMap((m, i) => {
1687
+ if (m.compaction) {
1688
+ const c = m.compaction;
1689
+ const tip = `#${m.index} · ${c.trigger} compaction ${formatTokens(c.preTokens)} → ${formatTokens(c.postTokens)} · ~${formatCost(c.estCost)}`;
1690
+ return [{ i, kind: 'compaction', tip }];
1691
+ }
1692
+ if (!m._subagent && m.cacheCreationTokens >= threshold) {
1693
+ return [{ i, kind: 'burst', tip: `#${m.index} · cache write ${formatTokens(m.cacheCreationTokens)}` }];
1694
+ }
1695
+ return [];
1696
+ });
1570
1697
  }
1571
1698
 
1572
1699
  function clampRange(start, end, total) {
@@ -1586,12 +1713,15 @@ function detailRangeFor(d) {
1586
1713
 
1587
1714
  function applyDetailRange(messages, range) {
1588
1715
  detailSlice = messages.slice(range.start, range.end);
1716
+ renderMessageRows(detailSlice, messages.length);
1589
1717
  const c = getChartColors();
1590
1718
  if (charts.cumulative && charts.tokenBreakdown) {
1591
1719
  charts.cumulative.data = cumulativeChartData(detailSlice, c);
1592
- charts.cumulative.update('none');
1593
1720
  charts.tokenBreakdown.data = tokenBreakdownChartData(detailSlice, c);
1594
- charts.tokenBreakdown.update('none');
1721
+ for (const chart of [charts.cumulative, charts.tokenBreakdown]) {
1722
+ markCompactions(chart, detailSlice, c);
1723
+ chart.update('none');
1724
+ }
1595
1725
  } else {
1596
1726
  renderCumulativeChart(detailSlice);
1597
1727
  renderTokenBreakdownChart(detailSlice);
@@ -1646,19 +1776,25 @@ function initRangeBrush(messages) {
1646
1776
 
1647
1777
  drawRangeOverview(q('.rb-overview'), messages);
1648
1778
 
1649
- const bursts = cacheBurstIndices(messages);
1779
+ const markers = notableEvents(messages);
1650
1780
  const burstsEl = q('.rb-bursts');
1651
- burstsEl.innerHTML = bursts
1652
- .map((i) => {
1653
- const m = messages[i];
1654
- const tip = `#${m.index} · cache write ${formatTokens(m.cacheCreationTokens)}`;
1655
- return `<button type="button" class="rb-burst" data-i="${i}" style="left:${((i + 0.5) / total) * 100}%" title="${esc(tip)}" aria-label="${esc(tip)}"></button>`;
1656
- })
1781
+ burstsEl.innerHTML = markers
1782
+ .map(
1783
+ (k) =>
1784
+ `<button type="button" class="rb-burst${k.kind === 'compaction' ? ' compact' : ''}" data-i="${esc(String(k.i))}" style="left:${((k.i + 0.5) / total) * 100}%" title="${esc(k.tip)}" aria-label="${esc(k.tip)}"></button>`,
1785
+ )
1657
1786
  .join('');
1658
- const burstEls = [...burstsEl.children].map((el, k) => ({ el, i: bursts[k] }));
1659
- if (bursts.length) {
1787
+ const burstEls = [...burstsEl.children].map((el, k) => ({ el, i: markers[k].i }));
1788
+ const counts = [
1789
+ ['burst', 'cache burst', ''],
1790
+ ['compaction', 'compaction', ' class="compact"'],
1791
+ ].flatMap(([kind, label, attr]) => {
1792
+ const n = markers.filter((k) => k.kind === kind).length;
1793
+ return n ? [`<span${attr}><i></i>${n} ${label}${n === 1 ? '' : 's'}</span>`] : [];
1794
+ });
1795
+ if (counts.length) {
1660
1796
  burstCount.hidden = false;
1661
- burstCount.append(`${bursts.length} cache burst${bursts.length === 1 ? '' : 's'}`);
1797
+ burstCount.innerHTML = counts.join('<span class="rb-sep">·</span>');
1662
1798
  }
1663
1799
 
1664
1800
  const layout = () => {
package/public/style.css CHANGED
@@ -29,6 +29,7 @@
29
29
  --chart-4: #f0b429;
30
30
  --chart-5: #b784f5;
31
31
  --chart-6: #fb7185;
32
+ --compact: var(--chart-5);
32
33
  }
33
34
 
34
35
  /* #endregion */
@@ -823,6 +824,22 @@ body {
823
824
  vertical-align: middle;
824
825
  }
825
826
 
827
+ .rb-burst-count .compact {
828
+ color: var(--compact);
829
+ }
830
+
831
+ .rb-burst-count .compact i,
832
+ .rb-burst.compact::after {
833
+ border-radius: 1px;
834
+ transform: rotate(45deg);
835
+ background: var(--compact);
836
+ }
837
+
838
+ .rb-burst-count .rb-sep {
839
+ margin: 0 6px;
840
+ color: var(--text-muted);
841
+ }
842
+
826
843
  .rb-presets {
827
844
  display: flex;
828
845
  gap: 4px;
@@ -936,6 +953,10 @@ body {
936
953
  left: 2.5px;
937
954
  }
938
955
 
956
+ .rb-burst.compact::before {
957
+ background: var(--compact);
958
+ }
959
+
939
960
  /* The shade outside the window is the window's own shadow, clipped by the track. */
940
961
  .rb-window {
941
962
  position: absolute;
@@ -1209,32 +1230,47 @@ body.light .rb-window {
1209
1230
  font-size: 10px;
1210
1231
  }
1211
1232
 
1233
+ .compaction-tag {
1234
+ text-transform: uppercase;
1235
+ color: var(--compact);
1236
+ background: color-mix(in srgb, var(--compact) 14%, transparent);
1237
+ white-space: nowrap;
1238
+ }
1239
+
1240
+ .compaction-row td {
1241
+ background: color-mix(in srgb, var(--compact) 6%, transparent);
1242
+ color: var(--text-muted);
1243
+ }
1244
+
1245
+ .compaction-row td:first-child {
1246
+ border-left: 2px solid var(--compact);
1247
+ }
1248
+
1212
1249
  /* #endregion */
1213
1250
 
1214
1251
  /* #region SUBAGENT */
1215
1252
 
1216
- .subagent-tag {
1253
+ .subagent-tag,
1254
+ .tool-tag,
1255
+ .compaction-tag {
1217
1256
  font-size: 9px;
1218
- text-transform: uppercase;
1219
1257
  letter-spacing: 0.03em;
1220
- color: var(--text-muted);
1221
- background: var(--bg-hover);
1222
1258
  padding: 1px 5px;
1223
1259
  border-radius: 3px;
1224
1260
  margin-left: 4px;
1225
1261
  vertical-align: middle;
1226
1262
  }
1227
1263
 
1264
+ .subagent-tag {
1265
+ text-transform: uppercase;
1266
+ color: var(--text-muted);
1267
+ background: var(--bg-hover);
1268
+ }
1269
+
1228
1270
  .tool-tag {
1229
- font-size: 9px;
1230
1271
  text-transform: lowercase;
1231
- letter-spacing: 0.03em;
1232
1272
  color: var(--chart-2, #60a5fa);
1233
1273
  background: rgba(96, 165, 250, 0.12);
1234
- padding: 1px 5px;
1235
- border-radius: 3px;
1236
- margin-left: 4px;
1237
- vertical-align: middle;
1238
1274
  }
1239
1275
 
1240
1276
  /* #endregion */
package/server.js CHANGED
@@ -209,6 +209,44 @@ function calculateEntryCost(data, pricing) {
209
209
  return calculateCostForModel(data.message.usage, model, pricing, speed);
210
210
  }
211
211
 
212
+ // The summarization call behind a compact_boundary is not logged with usage, so its cost is an
213
+ // estimate: the whole pre-compaction context read from cache, and a summary no larger than the
214
+ // post-compaction context written out.
215
+ function estimateCompactionCost(meta, model, pricing) {
216
+ return calculateCostForModel(
217
+ { output_tokens: meta.postTokens, cache_read_input_tokens: meta.preTokens },
218
+ model, pricing);
219
+ }
220
+
221
+ function compactionFacts(parsed) {
222
+ const meta = parsed.compactMetadata || {};
223
+ const preTokens = meta.preTokens || 0;
224
+ const postTokens = meta.postTokens || 0;
225
+ return {
226
+ timestamp: parsed.timestamp,
227
+ trigger: meta.trigger || 'unknown',
228
+ preTokens,
229
+ postTokens,
230
+ droppedTokens: Math.max(0, preTokens - postTokens),
231
+ durationMs: meta.durationMs || 0,
232
+ };
233
+ }
234
+
235
+ // The first turn after a boundary rebuilds the prompt cache from the summary, so its cache
236
+ // creation is spend the compaction caused. It is already in the session total; the record only
237
+ // attributes it. Models without pricing get null, not a zero that reads as "free".
238
+ function priceCompaction(facts, msg, pricing) {
239
+ const model = isRealModel(msg.model) ? msg.model : null;
240
+ return {
241
+ ...facts,
242
+ estCost: model ? estimateCompactionCost(facts, model, pricing) : null,
243
+ rewarmTokens: msg.cacheCreationTokens,
244
+ rewarmCost: model
245
+ ? calculateCostForModel({ cache_creation_input_tokens: msg.cacheCreationTokens }, model, pricing, msg.speed)
246
+ : null,
247
+ };
248
+ }
249
+
212
250
  // #endregion
213
251
 
214
252
  // #region DATA_AGGREGATION
@@ -372,27 +410,68 @@ function getSessionIdFromFile(filePath) {
372
410
  return path.basename(filePath, '.jsonl');
373
411
  }
374
412
 
413
+ function readdirSafe(dir) {
414
+ try { return fs.readdirSync(dir, { withFileTypes: true }); } catch { return []; }
415
+ }
416
+
417
+ // Agents sit at subagents/agent-*.jsonl, but a Workflow run nests its own under
418
+ // subagents/workflows/<wfId>/ — and a workflow that starts a workflow nests deeper still, so walk
419
+ // rather than hard-code the depth. Descending only into a listed entry also keeps the common
420
+ // no-workflow session at one readdir.
421
+ function collectAgents(dir, workflowId, out) {
422
+ for (const e of readdirSafe(dir)) {
423
+ if (e.isDirectory()) {
424
+ if (e.name !== 'workflows') continue;
425
+ const runsDir = path.join(dir, e.name);
426
+ for (const run of readdirSafe(runsDir)) {
427
+ if (run.isDirectory()) collectAgents(path.join(runsDir, run.name), run.name, out);
428
+ }
429
+ continue;
430
+ }
431
+ if (!e.name.endsWith('.jsonl')) continue;
432
+ const agentId = e.name.replace('.jsonl', '');
433
+ let meta = {};
434
+ try { meta = JSON.parse(fs.readFileSync(path.join(dir, `${agentId}.meta.json`), 'utf-8')); } catch { /* no meta */ }
435
+ out.push({
436
+ agentId,
437
+ filePath: path.join(dir, e.name),
438
+ agentType: meta.agentType || 'unknown',
439
+ description: meta.description || '',
440
+ workflowId,
441
+ });
442
+ }
443
+ }
444
+
375
445
  function scanSubagentDir(sessionDir) {
376
- const subagentsDir = path.join(sessionDir, 'subagents');
377
446
  const result = [];
378
- try {
379
- for (const f of fs.readdirSync(subagentsDir)) {
380
- if (!f.endsWith('.jsonl')) continue;
381
- const agentId = f.replace('.jsonl', '');
382
- const metaPath = path.join(subagentsDir, `${agentId}.meta.json`);
383
- let meta = {};
384
- try { meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8')); } catch { /* no meta */ }
385
- result.push({
386
- agentId,
387
- filePath: path.join(subagentsDir, f),
388
- agentType: meta.agentType || 'unknown',
389
- description: meta.description || '',
390
- });
391
- }
392
- } catch { /* dir doesn't exist or unreadable */ }
447
+ collectAgents(path.join(sessionDir, 'subagents'), null, result);
393
448
  return result;
394
449
  }
395
450
 
451
+ // The run's script is saved as <name>-<wfId>.js under a session dir keyed by the workflow's cwd,
452
+ // which need not be the project the session file lives in — so the session's own project dir is
453
+ // only the likely home, and a miss falls back to sweeping the rest.
454
+ function findWorkflowNames(sessionId, wantedIds, likelyProjectDir) {
455
+ const names = new Map();
456
+ const wanted = new Set(wantedIds);
457
+ const scan = (projectDir) => {
458
+ for (const f of readdirSafe(path.join(projectDir, sessionId, 'workflows', 'scripts'))) {
459
+ const m = f.name.match(/^(.*)-(wf_.+)\.js$/);
460
+ if (m && wanted.has(m[2])) names.set(m[2], m[1]);
461
+ }
462
+ return names.size === wanted.size;
463
+ };
464
+ for (const baseDir of getProjectsDirs()) {
465
+ if (scan(path.join(baseDir, likelyProjectDir))) return names;
466
+ }
467
+ for (const baseDir of getProjectsDirs()) {
468
+ for (const e of readdirSafe(baseDir)) {
469
+ if (e.isDirectory() && e.name !== likelyProjectDir && scan(path.join(baseDir, e.name))) return names;
470
+ }
471
+ }
472
+ return names;
473
+ }
474
+
396
475
  // `<synthetic>` and friends are Claude Code bookkeeping entries, not models the user chose.
397
476
  function isRealModel(model) {
398
477
  return !!model && !model.startsWith('<');
@@ -408,6 +487,7 @@ async function loadSubagentData(subagentInfos, pricing) {
408
487
  agentId: info.agentId,
409
488
  agentType: info.agentType,
410
489
  description: info.description,
490
+ workflowId: info.workflowId || null,
411
491
  totalCost: 0,
412
492
  inputTokens: 0, outputTokens: 0,
413
493
  cacheCreationTokens: 0, cacheReadTokens: 0,
@@ -466,6 +546,9 @@ async function loadProjectData(files, pricing) {
466
546
  });
467
547
  }
468
548
  const session = sessions.get(sessionId);
549
+ // A boundary is attributed to the next counted turn, so the message list is the only record
550
+ // of compactions; a boundary with no turn after it has nothing to price and is dropped.
551
+ let pendingCompaction = null;
469
552
 
470
553
  await processJSONLFile(file, async (line) => {
471
554
  let parsed;
@@ -476,6 +559,11 @@ async function loadProjectData(files, pricing) {
476
559
  return;
477
560
  }
478
561
 
562
+ if (parsed.type === 'system' && parsed.subtype === 'compact_boundary' && parsed.timestamp) {
563
+ pendingCompaction = compactionFacts(parsed);
564
+ return;
565
+ }
566
+
479
567
  if (!parsed.message?.usage?.input_tokens && parsed.message?.usage?.input_tokens !== 0) return;
480
568
  if (!parsed.timestamp) return;
481
569
 
@@ -518,6 +606,10 @@ async function loadProjectData(files, pricing) {
518
606
  speed: usage.speed || 'standard',
519
607
  tools: extractTools(parsed.message?.content),
520
608
  };
609
+ if (pendingCompaction) {
610
+ msg.compaction = priceCompaction(pendingCompaction, msg, pricing);
611
+ pendingCompaction = null;
612
+ }
521
613
  session.messages.push(msg);
522
614
  if (hash) seen.set(hash, msg);
523
615
 
@@ -553,7 +645,7 @@ async function loadProjectData(files, pricing) {
553
645
  cacheCreationTokens: sa.cacheCreationTokens,
554
646
  cacheReadTokens: sa.cacheReadTokens,
555
647
  speed: 'standard',
556
- _subagent: { agentId: sa.agentId, agentType: sa.agentType, description: sa.description, messageCount: sa.messageCount },
648
+ _subagent: { agentId: sa.agentId, agentType: sa.agentType, description: sa.description, messageCount: sa.messageCount, workflowId: sa.workflowId },
557
649
  });
558
650
  }
559
651
  }
@@ -664,6 +756,21 @@ function summarizeMessages(msgs) {
664
756
  return sum;
665
757
  }
666
758
 
759
+ function summarizeCompactions(msgs) {
760
+ const sum = { count: 0, auto: 0, totalCost: 0, estCost: 0, rewarmCost: 0, rewarmTokens: 0, droppedTokens: 0 };
761
+ for (const { compaction: c } of msgs) {
762
+ if (!c) continue;
763
+ sum.count++;
764
+ if (c.trigger === 'auto') sum.auto++;
765
+ sum.estCost += c.estCost || 0;
766
+ sum.rewarmCost += c.rewarmCost || 0;
767
+ sum.rewarmTokens += c.rewarmTokens;
768
+ sum.droppedTokens += c.droppedTokens;
769
+ }
770
+ sum.totalCost = sum.estCost + sum.rewarmCost;
771
+ return sum;
772
+ }
773
+
667
774
  async function getOverviewData(range, projectFilter) {
668
775
  const cacheKey = `overview_${rangeKey(range)}_${projectFilter || 'all'}`;
669
776
  const cached = getCache(cacheKey);
@@ -866,6 +973,7 @@ async function getProjectSessionsData(encodedPath, range) {
866
973
  firstTimestamp: session.firstTimestamp,
867
974
  lastTimestamp: session.lastTimestamp,
868
975
  durationMinutes: Math.round(durationMs / 60000),
976
+ compactions: summarizeCompactions(msgs),
869
977
  });
870
978
  }
871
979
 
@@ -935,6 +1043,30 @@ async function getSessionDetailData(sessionId) {
935
1043
  return { ...m, index: i + 1, cumulativeCost: cumulative };
936
1044
  });
937
1045
 
1046
+ // One folded-in message per agent, and `messages` is already sorted, so a group's ends are
1047
+ // the run's first and last agent.
1048
+ const byWorkflow = new Map();
1049
+ for (const m of messages) {
1050
+ const wf = m._subagent?.workflowId;
1051
+ if (!wf) continue;
1052
+ if (!byWorkflow.has(wf)) byWorkflow.set(wf, []);
1053
+ byWorkflow.get(wf).push(m);
1054
+ }
1055
+ const names = byWorkflow.size > 0
1056
+ ? findWorkflowNames(sessionId, byWorkflow.keys(), encodedPath)
1057
+ : new Map();
1058
+ const workflows = [...byWorkflow].map(([id, msgs]) => {
1059
+ const { messageCount, ...totals } = summarizeMessages(msgs);
1060
+ return {
1061
+ id,
1062
+ name: names.get(id) || id,
1063
+ agents: messageCount,
1064
+ firstTimestamp: msgs[0].timestamp,
1065
+ lastTimestamp: msgs.at(-1).timestamp,
1066
+ ...totals,
1067
+ };
1068
+ }).sort((a, b) => b.totalCost - a.totalCost);
1069
+
938
1070
  const result = {
939
1071
  sessionId,
940
1072
  customTitle: session.customTitle,
@@ -949,6 +1081,8 @@ async function getSessionDetailData(sessionId) {
949
1081
  firstPrompt: session.firstPrompt,
950
1082
  firstTimestamp: session.firstTimestamp,
951
1083
  lastTimestamp: session.lastTimestamp,
1084
+ workflows,
1085
+ compactions: summarizeCompactions(messages),
952
1086
  messages,
953
1087
  };
954
1088
 
@@ -1113,6 +1247,8 @@ async function getInsightsData(range, projectFilter) {
1113
1247
  const toolCounts = {};
1114
1248
  let mainCost = 0;
1115
1249
  let subagentCost = 0;
1250
+ let workflowCost = 0;
1251
+ const workflowRuns = new Set();
1116
1252
  const weekly = {};
1117
1253
 
1118
1254
  // getModelPricing falls back to a linear scan of the whole LiteLLM map on a miss, so resolve
@@ -1136,6 +1272,10 @@ async function getInsightsData(range, projectFilter) {
1136
1272
 
1137
1273
  if (m._subagent) {
1138
1274
  subagentCost += m.cost;
1275
+ if (m._subagent.workflowId) {
1276
+ workflowCost += m.cost;
1277
+ workflowRuns.add(m._subagent.workflowId);
1278
+ }
1139
1279
  } else {
1140
1280
  mainCost += m.cost;
1141
1281
  if (m.tools) for (const t of m.tools) toolCounts[t] = (toolCounts[t] || 0) + 1;
@@ -1175,7 +1315,9 @@ async function getInsightsData(range, projectFilter) {
1175
1315
  .map(([name, count]) => ({ name, count }))
1176
1316
  .sort((a, b) => b.count - a.count)
1177
1317
  .slice(0, MAX_TOOLS),
1178
- subagents: { mainCost, subagentCost },
1318
+ // workflowCost is the slice of subagentCost spent inside Workflow runs, not a third peer —
1319
+ // mainCost + subagentCost is still the whole.
1320
+ subagents: { mainCost, subagentCost, workflowCost, workflowRuns: workflowRuns.size },
1179
1321
  weekly: Object.entries(weekly)
1180
1322
  .sort(([a], [b]) => a.localeCompare(b))
1181
1323
  .map(([weekStart, cost]) => ({ weekStart, cost })),