claude-code-cost 0.14.0 → 0.16.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 CHANGED
@@ -214,21 +214,37 @@ function calculateEntryCost(data, pricing) {
214
214
  // #region DATA_AGGREGATION
215
215
 
216
216
  const CACHE_TTL = 30_000;
217
- let dataCache = {};
218
- let cacheTimestamps = {};
219
217
 
220
- function isCacheValid(key) {
221
- return cacheTimestamps[key] && (Date.now() - cacheTimestamps[key]) < CACHE_TTL;
218
+ // Custom from/to windows make the key space unbounded, so the cache is capped, which would
219
+ // otherwise grow for the process lifetime. A Map keeps insertion order, so the oldest write is
220
+ // always the first key — no sort, no key array.
221
+ const MAX_CACHE_ENTRIES = 50;
222
+ const dataCache = new Map();
223
+
224
+ // undefined means "no usable entry": every cached payload is an object or an array, so it can
225
+ // never collide with a real one. A stale hit is dropped here rather than left resident until the
226
+ // cap pushes it out — detail_<id> entries carry a whole message array.
227
+ function getCache(key) {
228
+ const hit = dataCache.get(key);
229
+ if (!hit) return undefined;
230
+ if ((Date.now() - hit.ts) >= CACHE_TTL) {
231
+ dataCache.delete(key);
232
+ return undefined;
233
+ }
234
+ return hit.data;
222
235
  }
223
236
 
224
237
  function setCache(key, data) {
225
- dataCache[key] = data;
226
- cacheTimestamps[key] = Date.now();
238
+ // Re-inserting moves an existing key to the back, so a rewrite resets its eviction priority.
239
+ dataCache.delete(key);
240
+ dataCache.set(key, { data, ts: Date.now() });
241
+ while (dataCache.size > MAX_CACHE_ENTRIES) {
242
+ dataCache.delete(dataCache.keys().next().value);
243
+ }
227
244
  }
228
245
 
229
246
  function invalidateAllCache() {
230
- dataCache = {};
231
- cacheTimestamps = {};
247
+ dataCache.clear();
232
248
  }
233
249
 
234
250
  function localDateStr(d) {
@@ -260,19 +276,29 @@ const BUCKETS = {
260
276
 
261
277
  // A one-day window collapses the daily chart into a single bar, so those ranges bucket by hour.
262
278
  function rangeBucket(range) {
263
- return range === 'today' || range === 1 ? 'hour' : 'day';
279
+ if (isCustomRange(range)) return range.from === range.to ? 'hour' : 'day';
280
+ return range === 'today' || range === '24h' || range === 1 ? 'hour' : 'day';
281
+ }
282
+
283
+ // Non-real (synthetic) models group under 'other' so the series still sums to the true
284
+ // bucket total, unlike modelDistribution which drops them entirely.
285
+ function addBucketModelCost(acc, key, model, cost) {
286
+ const mk = isRealModel(model) ? model : 'other';
287
+ (acc[key] ||= {})[mk] = (acc[key][mk] || 0) + cost;
264
288
  }
265
289
 
266
- // Gap-filled so empty buckets stay visible in the chart.
267
- function buildCostSeries(costs, start, end, bucket) {
290
+ // Gap-filled so empty buckets stay visible in the chart. The bucket total is derived from
291
+ // the per-model map, so the two can never disagree.
292
+ function buildCostSeries(modelCostsByBucket, start, end, bucket) {
268
293
  const b = BUCKETS[bucket];
269
294
  const points = [];
270
- if (Object.keys(costs).length === 0) return points;
295
+ if (Object.keys(modelCostsByBucket).length === 0) return points;
271
296
  const d = new Date(start);
272
297
  b.floor(d);
273
298
  for (; d <= end; b.next(d)) {
274
299
  const k = b.key(d);
275
- points.push({ key: k, cost: costs[k] || 0 });
300
+ const byModel = modelCostsByBucket[k] || {};
301
+ points.push({ key: k, cost: Object.values(byModel).reduce((s, v) => s + v, 0), byModel });
276
302
  }
277
303
  return points;
278
304
  }
@@ -420,7 +446,8 @@ async function loadSubagentData(subagentInfos, pricing) {
420
446
 
421
447
  async function loadProjectData(files, pricing) {
422
448
  const sessions = new Map();
423
- const seen = new Set();
449
+ // hash -> pushed message, so tool_use blocks from duplicate lines can be folded in.
450
+ const seen = new Map();
424
451
 
425
452
  for (const file of files) {
426
453
  const sessionId = getSessionIdFromFile(file);
@@ -453,8 +480,17 @@ async function loadProjectData(files, pricing) {
453
480
  if (!parsed.timestamp) return;
454
481
 
455
482
  const hash = createDedupeHash(parsed);
456
- if (hash && seen.has(hash)) return;
457
- if (hash) seen.add(hash);
483
+ if (hash && seen.has(hash)) {
484
+ // Streaming writes one JSONL line per content block of the same API message. Usage is
485
+ // identical on every line (deduped), but each line carries different tool_use blocks,
486
+ // so tools must be unioned across duplicates or most calls are lost.
487
+ const dupTools = extractTools(parsed.message?.content);
488
+ if (dupTools) {
489
+ const orig = seen.get(hash);
490
+ orig.tools = (orig.tools || []).concat(dupTools);
491
+ }
492
+ return;
493
+ }
458
494
 
459
495
  const cost = calculateEntryCost(parsed, pricing);
460
496
  const usage = parsed.message.usage;
@@ -471,7 +507,7 @@ async function loadProjectData(files, pricing) {
471
507
  if (!session.firstTimestamp || ts < session.firstTimestamp) session.firstTimestamp = ts;
472
508
  if (!session.lastTimestamp || ts > session.lastTimestamp) session.lastTimestamp = ts;
473
509
 
474
- session.messages.push({
510
+ const msg = {
475
511
  timestamp: ts,
476
512
  model,
477
513
  cost,
@@ -481,7 +517,9 @@ async function loadProjectData(files, pricing) {
481
517
  cacheReadTokens: usage.cache_read_input_tokens || 0,
482
518
  speed: usage.speed || 'standard',
483
519
  tools: extractTools(parsed.message?.content),
484
- });
520
+ };
521
+ session.messages.push(msg);
522
+ if (hash) seen.set(hash, msg);
485
523
 
486
524
  // Capture first user prompt from the JSONL (look for human/user messages)
487
525
  if (!session.firstPrompt && parsed.type === 'human' && parsed.message?.content) {
@@ -524,18 +562,94 @@ async function loadProjectData(files, pricing) {
524
562
  return sessions;
525
563
  }
526
564
 
565
+ // A range is either a preset — 'today', '24h', the last N calendar days, or null for all time, all
566
+ // anchored to the request — or a custom window of two local YYYY-MM-DD dates.
567
+ function isCustomRange(range) {
568
+ return !!range && typeof range === 'object' && !!range.from && !!range.to;
569
+ }
570
+
571
+ function localDayStart(dateStr) {
572
+ const [y, m, d] = dateStr.split('-').map(Number);
573
+ return new Date(y, m - 1, d, 0, 0, 0, 0);
574
+ }
575
+
576
+ // `to` names a whole day, so the window runs through the end of it — a midnight bound would
577
+ // silently drop that day's data.
578
+ function localDayEnd(dateStr) {
579
+ const d = localDayStart(dateStr);
580
+ d.setHours(23, 59, 59, 999);
581
+ return d;
582
+ }
583
+
527
584
  function rangeToCutoff(range, now) {
585
+ if (isCustomRange(range)) return localDayStart(range.from);
528
586
  if (range === 'today') {
529
587
  const c = new Date(now);
530
588
  c.setHours(0, 0, 0, 0);
531
589
  return c;
532
590
  }
591
+ // The one rolling preset left, and the reason it is labelled in hours: no midnight snap, so it
592
+ // spans two calendar days.
593
+ if (range === '24h') return new Date(now.getTime() - 24 * 60 * 60 * 1000);
533
594
  if (!range) return null;
595
+ // N calendar days ending today: identical to from=today-(N-1)&to=today, so the chart draws
596
+ // exactly N buckets instead of N+1 with a partial leading one.
534
597
  const c = new Date(now);
535
- c.setDate(c.getDate() - range);
598
+ c.setDate(c.getDate() - (range - 1));
599
+ c.setHours(0, 0, 0, 0);
536
600
  return c;
537
601
  }
538
602
 
603
+ // The window's upper bound, which used to be an implicit `now` in six places. Presets are rolling,
604
+ // so theirs still is; a custom window ends with its `to` day.
605
+ function rangeToEnd(range, now) {
606
+ return isCustomRange(range) ? localDayEnd(range.to) : new Date(now);
607
+ }
608
+
609
+ // Presets keep an open upper bound: they end at "whenever this request lands", so filtering
610
+ // against a captured `now` would only ever drop rows a live session wrote mid-request.
611
+ function windowEndStr(range, windowEnd) {
612
+ return isCustomRange(range) ? windowEnd.toISOString() : null;
613
+ }
614
+
615
+ // True when today falls inside the window. A null cutoff means open toward the past.
616
+ function windowContainsToday(cutoff, windowEnd, now) {
617
+ const todayStr = localDateStr(now);
618
+ return (!cutoff || localDateStr(cutoff) <= todayStr) && localDateStr(windowEnd) >= todayStr;
619
+ }
620
+
621
+ // Everything a range resolves to, anchored to one captured `now` so the bounds of a single request
622
+ // can never disagree with each other. `cutoff` stays null for the all-time range.
623
+ function resolveWindow(range, now = new Date()) {
624
+ const cutoff = rangeToCutoff(range, now);
625
+ const end = rangeToEnd(range, now);
626
+ return {
627
+ now, cutoff, end,
628
+ cutoffStr: cutoff ? cutoff.toISOString() : null,
629
+ endStr: windowEndStr(range, end),
630
+ hasToday: windowContainsToday(cutoff, end, now),
631
+ };
632
+ }
633
+
634
+ // Two-sided when the window has an end, so a window that stops in the past excludes later
635
+ // messages. A null bound means open in that direction.
636
+ function filterWindow(messages, fromStr, toStr) {
637
+ if (!fromStr && !toStr) return messages;
638
+ return messages.filter((m) => (!fromStr || m.timestamp >= fromStr) && (!toStr || m.timestamp <= toStr));
639
+ }
640
+
641
+ // Custom windows key by their dates, which is why the cache is capped (see MAX_CACHE_ENTRIES).
642
+ function rangeKey(range) {
643
+ if (isCustomRange(range)) return `${range.from}_${range.to}`;
644
+ return range || 'all';
645
+ }
646
+
647
+ // True when the window is exactly today — a preset 'today' or a single-day pick landing on it.
648
+ function isTodayRange(range, now) {
649
+ if (isCustomRange(range)) return range.from === range.to && range.to === localDateStr(now);
650
+ return range === 'today';
651
+ }
652
+
539
653
  function summarizeMessages(msgs) {
540
654
  const sum = { messageCount: msgs.length, totalCost: 0, inputTokens: 0, outputTokens: 0, cacheCreationTokens: 0, cacheReadTokens: 0 };
541
655
  for (const m of msgs) {
@@ -549,20 +663,27 @@ function summarizeMessages(msgs) {
549
663
  }
550
664
 
551
665
  async function getOverviewData(range, projectFilter) {
552
- const cacheKey = `overview_${range}_${projectFilter || 'all'}`;
553
- if (isCacheValid(cacheKey)) return dataCache[cacheKey];
666
+ const cacheKey = `overview_${rangeKey(range)}_${projectFilter || 'all'}`;
667
+ const cached = getCache(cacheKey);
668
+ if (cached !== undefined) return cached;
554
669
 
555
670
  const pricing = await fetchPricing();
556
- const now = new Date();
557
- const cutoff = rangeToCutoff(range, now) || new Date(now);
671
+ const w = resolveWindow(range);
672
+ const now = w.now;
673
+ // The series needs a concrete start even for the all-time range, so a null cutoff falls back to
674
+ // now. Deliberately local: pushing it into resolveWindow would hand the other callers a non-null
675
+ // all-time cutoff and change what they filter on.
676
+ const cutoff = w.cutoff || w.now;
677
+ const windowEnd = w.end;
558
678
  const projects = scanProjectDirs(cutoff, projectFilter);
559
679
  const cutoffStr = cutoff.toISOString();
680
+ const endStr = w.endStr;
560
681
 
561
682
  let totalCost = 0, totalSessions = 0;
562
683
  let totalInput = 0, totalOutput = 0, totalCacheCreation = 0, totalCacheRead = 0;
563
684
  const bucket = rangeBucket(range);
564
685
  const bucketKey = BUCKETS[bucket].key;
565
- const bucketCosts = {};
686
+ const bucketModelCosts = {};
566
687
  const modelCosts = {};
567
688
  const projectSummaries = [];
568
689
 
@@ -573,7 +694,7 @@ async function getOverviewData(range, projectFilter) {
573
694
 
574
695
  for (const [, session] of sessions) {
575
696
  // Filter messages within date range
576
- const inRange = session.messages.filter(m => m.timestamp >= cutoffStr);
697
+ const inRange = filterWindow(session.messages, cutoffStr, endStr);
577
698
  if (inRange.length === 0) continue;
578
699
 
579
700
  let sessionCost = 0, sessionInput = 0, sessionOutput = 0, sessionCacheCreation = 0, sessionCacheRead = 0;
@@ -584,7 +705,7 @@ async function getOverviewData(range, projectFilter) {
584
705
  sessionCacheCreation += m.cacheCreationTokens;
585
706
  sessionCacheRead += m.cacheReadTokens;
586
707
  const k = bucketKey(new Date(m.timestamp));
587
- bucketCosts[k] = (bucketCosts[k] || 0) + m.cost;
708
+ addBucketModelCost(bucketModelCosts, k, m.model, m.cost);
588
709
  if (isRealModel(m.model)) {
589
710
  modelCosts[m.model] = (modelCosts[m.model] || 0) + m.cost;
590
711
  projModels.add(m.model);
@@ -614,12 +735,15 @@ async function getOverviewData(range, projectFilter) {
614
735
  }
615
736
  }
616
737
 
617
- const costSeries = buildCostSeries(bucketCosts, cutoff, now, bucket);
738
+ const costSeries = buildCostSeries(bucketModelCosts, cutoff, windowEnd, bucket);
618
739
 
740
+ // The today slice is scoped to the window. A window that ends before today has no today bucket,
741
+ // and a 0 there reads as "nothing spent today" rather than "outside the selected window" — so it
742
+ // is reported as null and the card is dropped instead.
619
743
  const todayStr = localDateStr(now);
620
- const todayCost = Object.entries(bucketCosts)
621
- .filter(([k]) => k.startsWith(todayStr))
622
- .reduce((s, [, c]) => s + c, 0);
744
+ const todayCost = w.hasToday
745
+ ? costSeries.filter((p) => p.key.startsWith(todayStr)).reduce((s, p) => s + p.cost, 0)
746
+ : null;
623
747
 
624
748
  const totalInputAll = totalInput + totalCacheCreation + totalCacheRead;
625
749
  const cacheEfficiency = totalInputAll > 0 ? totalCacheRead / totalInputAll : 0;
@@ -644,14 +768,13 @@ async function getOverviewData(range, projectFilter) {
644
768
  }
645
769
 
646
770
  async function getProjectsData(range, projectFilter) {
647
- const cacheKey = `projects_${range || 'all'}_${projectFilter || 'all'}`;
648
- if (isCacheValid(cacheKey)) return dataCache[cacheKey];
771
+ const cacheKey = `projects_${rangeKey(range)}_${projectFilter || 'all'}`;
772
+ const cached = getCache(cacheKey);
773
+ if (cached !== undefined) return cached;
649
774
 
650
775
  const pricing = await fetchPricing();
651
- const now = new Date();
652
- const cutoff = rangeToCutoff(range, now);
653
- const projects = scanProjectDirs(cutoff, projectFilter);
654
- const cutoffStr = cutoff ? cutoff.toISOString() : null;
776
+ const w = resolveWindow(range);
777
+ const projects = scanProjectDirs(w.cutoff, projectFilter);
655
778
  const result = [];
656
779
 
657
780
  for (const [encodedPath, proj] of projects) {
@@ -660,9 +783,7 @@ async function getProjectsData(range, projectFilter) {
660
783
  const projModelCounts = {};
661
784
 
662
785
  for (const [, session] of sessions) {
663
- const msgs = cutoffStr
664
- ? session.messages.filter(m => m.timestamp >= cutoffStr)
665
- : session.messages;
786
+ const msgs = filterWindow(session.messages, w.cutoffStr, w.endStr);
666
787
  if (msgs.length === 0) continue;
667
788
 
668
789
  const cost = msgs.reduce((s, m) => s + m.cost, 0);
@@ -696,35 +817,32 @@ async function getProjectsData(range, projectFilter) {
696
817
  }
697
818
 
698
819
  async function getProjectSessionsData(encodedPath, range) {
699
- const cacheKey = `sessions_${encodedPath}_${range || 'all'}`;
700
- if (isCacheValid(cacheKey)) return dataCache[cacheKey];
820
+ const cacheKey = `sessions_${encodedPath}_${rangeKey(range)}`;
821
+ const cached = getCache(cacheKey);
822
+ if (cached !== undefined) return cached;
701
823
 
702
824
  const pricing = await fetchPricing();
703
- const now = new Date();
704
- const cutoff = rangeToCutoff(range, now);
705
- const projects = scanProjectDirs(cutoff);
825
+ const w = resolveWindow(range);
826
+ const projects = scanProjectDirs(w.cutoff);
706
827
  const proj = projects.get(encodedPath);
707
828
  const bucket = rangeBucket(range);
708
829
  if (!proj) return { sessions: [], costSeries: { bucket, points: [] }, modelDistribution: [] };
709
830
 
710
831
  const sessions = await loadProjectData(proj.files, pricing);
711
- const cutoffStr = cutoff ? cutoff.toISOString() : null;
712
832
  const result = [];
713
833
  const bucketKey = BUCKETS[bucket].key;
714
- const bucketCosts = {};
834
+ const bucketModelCosts = {};
715
835
  const modelCosts = {};
716
836
 
717
837
  for (const [, session] of sessions) {
718
- const msgs = cutoffStr
719
- ? session.messages.filter(m => m.timestamp >= cutoffStr)
720
- : session.messages;
838
+ const msgs = filterWindow(session.messages, w.cutoffStr, w.endStr);
721
839
  if (msgs.length === 0) continue;
722
840
 
723
841
  const sum = summarizeMessages(msgs);
724
842
  const sessionModelCounts = {};
725
843
  for (const m of msgs) {
726
844
  const k = bucketKey(new Date(m.timestamp));
727
- bucketCosts[k] = (bucketCosts[k] || 0) + m.cost;
845
+ addBucketModelCost(bucketModelCosts, k, m.model, m.cost);
728
846
  if (isRealModel(m.model)) {
729
847
  modelCosts[m.model] = (modelCosts[m.model] || 0) + m.cost;
730
848
  sessionModelCounts[m.model] = (sessionModelCounts[m.model] || 0) + 1;
@@ -750,12 +868,12 @@ async function getProjectSessionsData(encodedPath, range) {
750
868
  }
751
869
 
752
870
  // No range means "everything", so the series starts at the first bucket that has cost.
753
- let seriesStart = cutoff;
871
+ let seriesStart = w.cutoff;
754
872
  if (!seriesStart) {
755
- const keys = Object.keys(bucketCosts).sort();
756
- seriesStart = keys.length ? new Date(`${keys[0]}T00:00:00`) : now;
873
+ const keys = Object.keys(bucketModelCosts).sort();
874
+ seriesStart = keys.length ? new Date(`${keys[0]}T00:00:00`) : w.now;
757
875
  }
758
- const costSeries = buildCostSeries(bucketCosts, seriesStart, now, bucket);
876
+ const costSeries = buildCostSeries(bucketModelCosts, seriesStart, w.end, bucket);
759
877
 
760
878
  const modelDistribution = buildModelDistribution(modelCosts);
761
879
 
@@ -774,21 +892,24 @@ async function getProjectSessionsData(encodedPath, range) {
774
892
  // instead of silently disagreeing with it. They are derived outside the cache so switching ranges
775
893
  // does not re-parse the session's JSONL.
776
894
  function withSessionSlices(base, range) {
777
- const now = new Date();
778
- const cutoff = rangeToCutoff(range, now);
779
- const sliceFrom = (from) => summarizeMessages(base.messages.filter(m => m.timestamp >= from));
780
- const inRange = cutoff ? sliceFrom(cutoff.toISOString()) : null;
895
+ const w = resolveWindow(range);
896
+ const slice = (fromStr) => summarizeMessages(filterWindow(base.messages, fromStr, w.endStr));
897
+ const inRange = w.cutoffStr ? slice(w.cutoffStr) : null;
898
+ const todayStart = rangeToCutoff('today', w.now);
899
+ // Scoped to the window like the overview's today card: a window ending in the past has no
900
+ // today to report, and a zeroed slice would read as "nothing spent today".
781
901
  return {
782
902
  ...base,
783
903
  range,
784
904
  inRange,
785
- today: range === 'today' ? inRange : sliceFrom(rangeToCutoff('today', now).toISOString()),
905
+ today: isTodayRange(range, w.now) ? inRange : w.hasToday ? slice(todayStart.toISOString()) : null,
786
906
  };
787
907
  }
788
908
 
789
909
  async function getSessionDetailData(sessionId) {
790
910
  const cacheKey = `detail_${sessionId}`;
791
- if (isCacheValid(cacheKey)) return dataCache[cacheKey];
911
+ const cached = getCache(cacheKey);
912
+ if (cached !== undefined) return cached;
792
913
 
793
914
  const pricing = await fetchPricing();
794
915
  const projects = scanProjectDirs();
@@ -836,6 +957,219 @@ async function getSessionDetailData(sessionId) {
836
957
  return null;
837
958
  }
838
959
 
960
+ // Claude's usage limits work in rolling 5-hour billing windows. A block starts at the first
961
+ // activity (floored to the hour, mirroring ccusage) and spans exactly 5h; activity past the end
962
+ // opens a new block anchored to its own hour.
963
+ const BLOCK_MS = 5 * 60 * 60 * 1000;
964
+ const HEATMAP_DAYS = 7;
965
+ const MAX_BLOCKS = 24;
966
+ const MAX_TOOLS = 20;
967
+
968
+ // The real window boundary comes from Claude Code's statusline payload (rate_limits.five_hour),
969
+ // spied to disk by the cck plugin. The ccusage hour-floor heuristic can be hours off the actual
970
+ // API window, so when a live resets_at is available it anchors the active block instead.
971
+ function readRateLimits(now) {
972
+ const dir = path.join(CLAUDE_DIR, '.cck', 'context-status');
973
+ let newest = null;
974
+ try {
975
+ for (const f of fs.readdirSync(dir)) {
976
+ if (!f.endsWith('.json')) continue;
977
+ const fp = path.join(dir, f);
978
+ try {
979
+ const mtime = fs.statSync(fp).mtimeMs;
980
+ if (!newest || mtime > newest.mtime) newest = { fp, mtime };
981
+ } catch { /* ignore */ }
982
+ }
983
+ } catch { return null; }
984
+ if (!newest) return null;
985
+ try {
986
+ const rl = JSON.parse(fs.readFileSync(newest.fp, 'utf8'))?.rate_limits;
987
+ const fh = rl?.five_hour;
988
+ // A resets_at in the past means the snapshot predates the current window — don't trust it.
989
+ if (!fh?.resets_at || fh.resets_at * 1000 <= now.getTime()) return null;
990
+ return { usedPct: fh.used_percentage ?? null, resetsAtMs: fh.resets_at * 1000 };
991
+ } catch { return null; }
992
+ }
993
+
994
+ function computeBlocks(messages, now, realResetMs) {
995
+ // When the API told us the live window, the active block spans exactly [reset-5h, reset].
996
+ const activeStartMs = realResetMs && now.getTime() < realResetMs ? realResetMs - BLOCK_MS : null;
997
+ const blocks = [];
998
+ let cur = null;
999
+ for (const m of messages) {
1000
+ const t = new Date(m.timestamp).getTime();
1001
+ if (!Number.isFinite(t)) continue;
1002
+ if (activeStartMs !== null && t >= activeStartMs) {
1003
+ if (!cur || cur.startMs !== activeStartMs) {
1004
+ cur = { startMs: activeStartMs, real: true, lastMs: t, cost: 0, tokens: 0, messageCount: 0, models: new Set() };
1005
+ blocks.push(cur);
1006
+ }
1007
+ } else if (!cur || t >= cur.startMs + BLOCK_MS) {
1008
+ const start = new Date(t);
1009
+ start.setMinutes(0, 0, 0);
1010
+ cur = { startMs: start.getTime(), lastMs: t, cost: 0, tokens: 0, messageCount: 0, models: new Set() };
1011
+ blocks.push(cur);
1012
+ }
1013
+ if (t > cur.lastMs) cur.lastMs = t;
1014
+ cur.cost += m.cost;
1015
+ cur.tokens += m.inputTokens + m.outputTokens + m.cacheCreationTokens + m.cacheReadTokens;
1016
+ cur.messageCount++;
1017
+ if (isRealModel(m.model)) cur.models.add(m.model);
1018
+ }
1019
+ // A live window with no in-range messages yet still exists — surface it as an empty block.
1020
+ if (activeStartMs !== null && !blocks.some((b) => b.startMs === activeStartMs)) {
1021
+ blocks.push({ startMs: activeStartMs, real: true, lastMs: activeStartMs, cost: 0, tokens: 0, messageCount: 0, models: new Set() });
1022
+ }
1023
+ const nowMs = now.getTime();
1024
+ return blocks
1025
+ .reverse()
1026
+ .slice(0, MAX_BLOCKS)
1027
+ .map((b) => {
1028
+ const endMs = b.startMs + BLOCK_MS;
1029
+ // Only the API-anchored window counts as active: the hour-floor heuristic can be hours
1030
+ // off the real boundary, so without live data no block is presented as current.
1031
+ const active = b.real === true && nowMs < endMs;
1032
+ // Floored at 1 so a block opened seconds ago doesn't project an absurd rate.
1033
+ const elapsedMin = active ? Math.max(1, (nowMs - b.startMs) / 60000) : null;
1034
+ return {
1035
+ start: new Date(b.startMs).toISOString(),
1036
+ end: new Date(endMs).toISOString(),
1037
+ lastActivity: new Date(b.lastMs).toISOString(),
1038
+ cost: b.cost,
1039
+ tokens: b.tokens,
1040
+ messageCount: b.messageCount,
1041
+ models: [...b.models],
1042
+ active,
1043
+ burn: active
1044
+ ? {
1045
+ costPerHour: (b.cost / elapsedMin) * 60,
1046
+ tokensPerMin: b.tokens / elapsedMin,
1047
+ projectedCost: (b.cost / elapsedMin) * (BLOCK_MS / 60000),
1048
+ remainingMin: Math.round((endMs - nowMs) / 60000),
1049
+ }
1050
+ : null,
1051
+ };
1052
+ });
1053
+ }
1054
+
1055
+ async function getInsightsData(range, projectFilter) {
1056
+ const cacheKey = `insights_${rangeKey(range)}_${projectFilter || 'all'}`;
1057
+ const cached = getCache(cacheKey);
1058
+ if (cached !== undefined) return cached;
1059
+
1060
+ const pricing = await fetchPricing();
1061
+ const w = resolveWindow(range);
1062
+
1063
+ // The heatmap covers the last 7 real days ending at the selected window's end — each row
1064
+ // is an actual date, so a short range (today, 3d) still shows a full week of context.
1065
+ const windowEnd = w.end < w.now ? w.end : w.now;
1066
+ const hmStart = new Date(windowEnd);
1067
+ hmStart.setHours(0, 0, 0, 0);
1068
+ hmStart.setDate(hmStart.getDate() - (HEATMAP_DAYS - 1));
1069
+ const hmStartStr = hmStart.toISOString();
1070
+ const scanCutoff = w.cutoff === null ? null : w.cutoff < hmStart ? w.cutoff : hmStart;
1071
+ const projects = scanProjectDirs(scanCutoff, projectFilter);
1072
+
1073
+ // When the cost window already covers the heatmap window, the heatmap rows are a subset of
1074
+ // `all` — filter it instead of re-scanning every session a second time.
1075
+ const hmInAll = w.cutoff === null || w.cutoff <= hmStart;
1076
+ const allParts = [];
1077
+ const hmParts = [];
1078
+ for (const [, proj] of projects) {
1079
+ const sessions = await loadProjectData(proj.files, pricing);
1080
+ for (const [, session] of sessions) {
1081
+ allParts.push(filterWindow(session.messages, w.cutoffStr, w.endStr));
1082
+ if (!hmInAll) hmParts.push(filterWindow(session.messages, hmStartStr, w.endStr));
1083
+ }
1084
+ }
1085
+ const all = allParts.flat().sort((a, b) => a.timestamp.localeCompare(b.timestamp));
1086
+ const hmMsgs = hmInAll ? all.filter((m) => m.timestamp >= hmStartStr) : hmParts.flat();
1087
+
1088
+ const sum = summarizeMessages(all);
1089
+ const tokens = { input: sum.inputTokens, output: sum.outputTokens, cacheCreation: sum.cacheCreationTokens, cacheRead: sum.cacheReadTokens };
1090
+ let cacheSavings = 0;
1091
+ // One row per real day, oldest first; row index = whole days since hmStart.
1092
+ const heatmap = Array.from({ length: HEATMAP_DAYS }, () => new Array(24).fill(0));
1093
+ const heatmapDays = Array.from({ length: HEATMAP_DAYS }, (_, i) => {
1094
+ const d = new Date(hmStart);
1095
+ d.setDate(d.getDate() + i);
1096
+ return localDateStr(d);
1097
+ });
1098
+ const toolCounts = {};
1099
+ let mainCost = 0;
1100
+ let subagentCost = 0;
1101
+ const weekly = {};
1102
+
1103
+ // getModelPricing falls back to a linear scan of the whole LiteLLM map on a miss, so resolve
1104
+ // it once per distinct model rather than once per message.
1105
+ const priceMemo = new Map();
1106
+ for (const m of all) {
1107
+ // What the same tokens would have cost as fresh input, minus what cache reads actually cost.
1108
+ if (m.cacheReadTokens > 0) {
1109
+ if (!priceMemo.has(m.model)) priceMemo.set(m.model, getModelPricing(pricing, m.model));
1110
+ const mp = priceMemo.get(m.model);
1111
+ if (mp?.input_cost_per_token != null && mp?.cache_read_input_token_cost != null) {
1112
+ cacheSavings += m.cacheReadTokens * (mp.input_cost_per_token - mp.cache_read_input_token_cost);
1113
+ }
1114
+ }
1115
+
1116
+ const monday = new Date(m.timestamp);
1117
+ monday.setHours(0, 0, 0, 0);
1118
+ monday.setDate(monday.getDate() - ((monday.getDay() + 6) % 7));
1119
+ const wk = localDateStr(monday);
1120
+ weekly[wk] = (weekly[wk] || 0) + m.cost;
1121
+
1122
+ if (m._subagent) {
1123
+ subagentCost += m.cost;
1124
+ } else {
1125
+ mainCost += m.cost;
1126
+ if (m.tools) for (const t of m.tools) toolCounts[t] = (toolCounts[t] || 0) + 1;
1127
+ }
1128
+ }
1129
+
1130
+ for (const m of hmMsgs) {
1131
+ const d = new Date(m.timestamp);
1132
+ const day = new Date(d);
1133
+ day.setHours(0, 0, 0, 0);
1134
+ // Round to survive DST shifts making a "day" 23/25 hours.
1135
+ const idx = Math.round((day - hmStart) / 86400000);
1136
+ if (idx >= 0 && idx < HEATMAP_DAYS) heatmap[idx][d.getHours()] += m.cost;
1137
+ }
1138
+
1139
+ const limits = readRateLimits(w.now);
1140
+ // A window ending in the past has no "current" block — don't synthesize the live window there.
1141
+ const blocks = computeBlocks(all, w.now, w.hasToday ? limits?.resetsAtMs || null : null);
1142
+ const activeBlk = blocks.find((b) => b.active);
1143
+ if (activeBlk) activeBlk.usedPct = limits?.usedPct ?? null;
1144
+
1145
+ // Run-rate over the window actually observed: a custom window ending in the past uses its own
1146
+ // span; open-ended ranges run from the first message (all-time) or the cutoff to now.
1147
+ const windowStart = w.cutoff || (all.length ? new Date(all[0].timestamp) : w.now);
1148
+ const dayCount = Math.max(1, Math.ceil((windowEnd - windowStart) / 86400000));
1149
+ const dailyAvg = sum.totalCost / dayCount;
1150
+
1151
+ const result = {
1152
+ tokens,
1153
+ cacheSavings,
1154
+ runRate: { dailyAvg, projectedMonthly: dailyAvg * 30, days: dayCount },
1155
+ blocks,
1156
+ heatmap,
1157
+ heatmapDays,
1158
+ heatmapToday: localDateStr(w.now),
1159
+ tools: Object.entries(toolCounts)
1160
+ .map(([name, count]) => ({ name, count }))
1161
+ .sort((a, b) => b.count - a.count)
1162
+ .slice(0, MAX_TOOLS),
1163
+ subagents: { mainCost, subagentCost },
1164
+ weekly: Object.entries(weekly)
1165
+ .sort(([a], [b]) => a.localeCompare(b))
1166
+ .map(([weekStart, cost]) => ({ weekStart, cost })),
1167
+ };
1168
+
1169
+ setCache(cacheKey, result);
1170
+ return result;
1171
+ }
1172
+
839
1173
  // #endregion
840
1174
 
841
1175
  // #region EXPRESS
@@ -857,10 +1191,36 @@ app.get('/hub-config', (_req, res) => {
857
1191
 
858
1192
  function parseRange(raw, fallback = null) {
859
1193
  if (raw === 'today') return 'today';
1194
+ if (raw === '24h') return '24h';
860
1195
  const n = parseInt(raw, 10);
861
1196
  return Number.isFinite(n) ? n : fallback;
862
1197
  }
863
1198
 
1199
+ const DATE_PARAM = /^\d{4}-\d{2}-\d{2}$/;
1200
+
1201
+ // A local calendar date, normalized so it can safely reach a cache key — same discipline as
1202
+ // parseProject. Returns undefined for absent, null for malformed.
1203
+ function parseDateParam(raw) {
1204
+ if (raw === undefined || raw === '') return undefined;
1205
+ if (typeof raw !== 'string' || !DATE_PARAM.test(raw)) return null;
1206
+ return localDateStr(localDayStart(raw)) === raw ? raw : null;
1207
+ }
1208
+
1209
+ // A custom window, if the request asked for one: `from`/`to` take precedence over `range`.
1210
+ // Reversed pairs are ordered and both ends clamped to today — there is no cost data ahead of now,
1211
+ // and an inverted window would otherwise render as an unexplained empty chart.
1212
+ // Returns undefined when no window was requested, null when one was but is malformed.
1213
+ function parseCustomRange(query) {
1214
+ const from = parseDateParam(query.from);
1215
+ const to = parseDateParam(query.to);
1216
+ if (from === null || to === null) return null;
1217
+ if (from === undefined && to === undefined) return undefined;
1218
+ if (from === undefined || to === undefined) return null;
1219
+ const today = localDateStr(new Date());
1220
+ const [lo, hi] = from <= to ? [from, to] : [to, from];
1221
+ return { from: lo > today ? today : lo, to: hi > today ? today : hi };
1222
+ }
1223
+
864
1224
  // Encoded project-dir name (the hub sends it pre-encoded — see encodeProjectPath in the hub's
865
1225
  // public/app.js; this regex must stay a superset of that transform's output). Only ever used as
866
1226
  // a Map key, never joined into a path — the regex exists to keep unbounded strings out of the
@@ -873,12 +1233,23 @@ function parseProject(raw) {
873
1233
  return raw;
874
1234
  }
875
1235
 
876
- app.get('/api/overview', async (req, res) => {
1236
+ // Resolves a request's range onto req.range: a custom from/to window wins over `range`. A resolved
1237
+ // range cannot signal malformed input with null (null *is* the all-time range), so the rejection
1238
+ // happens here, ahead of the handler, instead of being threaded back to it as a sentinel value.
1239
+ // Only the range — a route that also scopes by project keeps its own parseProject guard, because
1240
+ // the routes that don't call parseProject must go on ignoring a malformed `project`.
1241
+ const withRange = (fallback = null) => (req, res, next) => {
1242
+ const custom = parseCustomRange(req.query);
1243
+ if (custom === null) return res.status(400).json({ error: 'Invalid date range' });
1244
+ req.range = custom || parseRange(req.query.range, fallback);
1245
+ next();
1246
+ };
1247
+
1248
+ app.get('/api/overview', withRange(30), async (req, res) => {
877
1249
  try {
878
- const range = parseRange(req.query.range, 30);
879
1250
  const project = parseProject(req.query.project);
880
1251
  if (project === null) return res.status(400).json({ error: 'Invalid project' });
881
- const data = await getOverviewData(range, project);
1252
+ const data = await getOverviewData(req.range, project);
882
1253
  res.json(data);
883
1254
  } catch (err) {
884
1255
  console.error('[API] overview error:', err);
@@ -886,12 +1257,23 @@ app.get('/api/overview', async (req, res) => {
886
1257
  }
887
1258
  });
888
1259
 
889
- app.get('/api/projects', async (req, res) => {
1260
+ app.get('/api/insights', withRange(30), async (req, res) => {
1261
+ try {
1262
+ const project = parseProject(req.query.project);
1263
+ if (project === null) return res.status(400).json({ error: 'Invalid project' });
1264
+ const data = await getInsightsData(req.range, project);
1265
+ res.json(data);
1266
+ } catch (err) {
1267
+ console.error('[API] insights error:', err);
1268
+ res.status(500).json({ error: 'Failed to load insights data' });
1269
+ }
1270
+ });
1271
+
1272
+ app.get('/api/projects', withRange(), async (req, res) => {
890
1273
  try {
891
- const range = parseRange(req.query.range);
892
1274
  const project = parseProject(req.query.project);
893
1275
  if (project === null) return res.status(400).json({ error: 'Invalid project' });
894
- const data = await getProjectsData(range, project);
1276
+ const data = await getProjectsData(req.range, project);
895
1277
  res.json(data);
896
1278
  } catch (err) {
897
1279
  console.error('[API] projects error:', err);
@@ -899,10 +1281,9 @@ app.get('/api/projects', async (req, res) => {
899
1281
  }
900
1282
  });
901
1283
 
902
- app.get('/api/projects/:path/sessions', async (req, res) => {
1284
+ app.get('/api/projects/:path/sessions', withRange(), async (req, res) => {
903
1285
  try {
904
- const range = parseRange(req.query.range);
905
- const data = await getProjectSessionsData(req.params.path, range);
1286
+ const data = await getProjectSessionsData(req.params.path, req.range);
906
1287
  res.json(data);
907
1288
  } catch (err) {
908
1289
  console.error('[API] sessions error:', err);
@@ -910,11 +1291,11 @@ app.get('/api/projects/:path/sessions', async (req, res) => {
910
1291
  }
911
1292
  });
912
1293
 
913
- app.get('/api/sessions/:id', async (req, res) => {
1294
+ app.get('/api/sessions/:id', withRange(), async (req, res) => {
914
1295
  try {
915
1296
  const base = await getSessionDetailData(req.params.id);
916
1297
  if (!base) return res.status(404).json({ error: 'Session not found' });
917
- res.json(withSessionSlices(base, parseRange(req.query.range)));
1298
+ res.json(withSessionSlices(base, req.range));
918
1299
  } catch (err) {
919
1300
  console.error('[API] session detail error:', err);
920
1301
  res.status(500).json({ error: 'Failed to load session detail' });