claude-code-cost 0.14.0 → 0.15.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';
264
281
  }
265
282
 
266
- // Gap-filled so empty buckets stay visible in the chart.
267
- function buildCostSeries(costs, start, end, bucket) {
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;
288
+ }
289
+
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
  }
@@ -524,18 +550,94 @@ async function loadProjectData(files, pricing) {
524
550
  return sessions;
525
551
  }
526
552
 
553
+ // A range is either a preset — 'today', '24h', the last N calendar days, or null for all time, all
554
+ // anchored to the request — or a custom window of two local YYYY-MM-DD dates.
555
+ function isCustomRange(range) {
556
+ return !!range && typeof range === 'object' && !!range.from && !!range.to;
557
+ }
558
+
559
+ function localDayStart(dateStr) {
560
+ const [y, m, d] = dateStr.split('-').map(Number);
561
+ return new Date(y, m - 1, d, 0, 0, 0, 0);
562
+ }
563
+
564
+ // `to` names a whole day, so the window runs through the end of it — a midnight bound would
565
+ // silently drop that day's data.
566
+ function localDayEnd(dateStr) {
567
+ const d = localDayStart(dateStr);
568
+ d.setHours(23, 59, 59, 999);
569
+ return d;
570
+ }
571
+
527
572
  function rangeToCutoff(range, now) {
573
+ if (isCustomRange(range)) return localDayStart(range.from);
528
574
  if (range === 'today') {
529
575
  const c = new Date(now);
530
576
  c.setHours(0, 0, 0, 0);
531
577
  return c;
532
578
  }
579
+ // The one rolling preset left, and the reason it is labelled in hours: no midnight snap, so it
580
+ // spans two calendar days.
581
+ if (range === '24h') return new Date(now.getTime() - 24 * 60 * 60 * 1000);
533
582
  if (!range) return null;
583
+ // N calendar days ending today: identical to from=today-(N-1)&to=today, so the chart draws
584
+ // exactly N buckets instead of N+1 with a partial leading one.
534
585
  const c = new Date(now);
535
- c.setDate(c.getDate() - range);
586
+ c.setDate(c.getDate() - (range - 1));
587
+ c.setHours(0, 0, 0, 0);
536
588
  return c;
537
589
  }
538
590
 
591
+ // The window's upper bound, which used to be an implicit `now` in six places. Presets are rolling,
592
+ // so theirs still is; a custom window ends with its `to` day.
593
+ function rangeToEnd(range, now) {
594
+ return isCustomRange(range) ? localDayEnd(range.to) : new Date(now);
595
+ }
596
+
597
+ // Presets keep an open upper bound: they end at "whenever this request lands", so filtering
598
+ // against a captured `now` would only ever drop rows a live session wrote mid-request.
599
+ function windowEndStr(range, windowEnd) {
600
+ return isCustomRange(range) ? windowEnd.toISOString() : null;
601
+ }
602
+
603
+ // True when today falls inside the window. A null cutoff means open toward the past.
604
+ function windowContainsToday(cutoff, windowEnd, now) {
605
+ const todayStr = localDateStr(now);
606
+ return (!cutoff || localDateStr(cutoff) <= todayStr) && localDateStr(windowEnd) >= todayStr;
607
+ }
608
+
609
+ // Everything a range resolves to, anchored to one captured `now` so the bounds of a single request
610
+ // can never disagree with each other. `cutoff` stays null for the all-time range.
611
+ function resolveWindow(range, now = new Date()) {
612
+ const cutoff = rangeToCutoff(range, now);
613
+ const end = rangeToEnd(range, now);
614
+ return {
615
+ now, cutoff, end,
616
+ cutoffStr: cutoff ? cutoff.toISOString() : null,
617
+ endStr: windowEndStr(range, end),
618
+ hasToday: windowContainsToday(cutoff, end, now),
619
+ };
620
+ }
621
+
622
+ // Two-sided when the window has an end, so a window that stops in the past excludes later
623
+ // messages. A null bound means open in that direction.
624
+ function filterWindow(messages, fromStr, toStr) {
625
+ if (!fromStr && !toStr) return messages;
626
+ return messages.filter((m) => (!fromStr || m.timestamp >= fromStr) && (!toStr || m.timestamp <= toStr));
627
+ }
628
+
629
+ // Custom windows key by their dates, which is why the cache is capped (see MAX_CACHE_ENTRIES).
630
+ function rangeKey(range) {
631
+ if (isCustomRange(range)) return `${range.from}_${range.to}`;
632
+ return range || 'all';
633
+ }
634
+
635
+ // True when the window is exactly today — a preset 'today' or a single-day pick landing on it.
636
+ function isTodayRange(range, now) {
637
+ if (isCustomRange(range)) return range.from === range.to && range.to === localDateStr(now);
638
+ return range === 'today';
639
+ }
640
+
539
641
  function summarizeMessages(msgs) {
540
642
  const sum = { messageCount: msgs.length, totalCost: 0, inputTokens: 0, outputTokens: 0, cacheCreationTokens: 0, cacheReadTokens: 0 };
541
643
  for (const m of msgs) {
@@ -549,20 +651,27 @@ function summarizeMessages(msgs) {
549
651
  }
550
652
 
551
653
  async function getOverviewData(range, projectFilter) {
552
- const cacheKey = `overview_${range}_${projectFilter || 'all'}`;
553
- if (isCacheValid(cacheKey)) return dataCache[cacheKey];
654
+ const cacheKey = `overview_${rangeKey(range)}_${projectFilter || 'all'}`;
655
+ const cached = getCache(cacheKey);
656
+ if (cached !== undefined) return cached;
554
657
 
555
658
  const pricing = await fetchPricing();
556
- const now = new Date();
557
- const cutoff = rangeToCutoff(range, now) || new Date(now);
659
+ const w = resolveWindow(range);
660
+ const now = w.now;
661
+ // The series needs a concrete start even for the all-time range, so a null cutoff falls back to
662
+ // now. Deliberately local: pushing it into resolveWindow would hand the other callers a non-null
663
+ // all-time cutoff and change what they filter on.
664
+ const cutoff = w.cutoff || w.now;
665
+ const windowEnd = w.end;
558
666
  const projects = scanProjectDirs(cutoff, projectFilter);
559
667
  const cutoffStr = cutoff.toISOString();
668
+ const endStr = w.endStr;
560
669
 
561
670
  let totalCost = 0, totalSessions = 0;
562
671
  let totalInput = 0, totalOutput = 0, totalCacheCreation = 0, totalCacheRead = 0;
563
672
  const bucket = rangeBucket(range);
564
673
  const bucketKey = BUCKETS[bucket].key;
565
- const bucketCosts = {};
674
+ const bucketModelCosts = {};
566
675
  const modelCosts = {};
567
676
  const projectSummaries = [];
568
677
 
@@ -573,7 +682,7 @@ async function getOverviewData(range, projectFilter) {
573
682
 
574
683
  for (const [, session] of sessions) {
575
684
  // Filter messages within date range
576
- const inRange = session.messages.filter(m => m.timestamp >= cutoffStr);
685
+ const inRange = filterWindow(session.messages, cutoffStr, endStr);
577
686
  if (inRange.length === 0) continue;
578
687
 
579
688
  let sessionCost = 0, sessionInput = 0, sessionOutput = 0, sessionCacheCreation = 0, sessionCacheRead = 0;
@@ -584,7 +693,7 @@ async function getOverviewData(range, projectFilter) {
584
693
  sessionCacheCreation += m.cacheCreationTokens;
585
694
  sessionCacheRead += m.cacheReadTokens;
586
695
  const k = bucketKey(new Date(m.timestamp));
587
- bucketCosts[k] = (bucketCosts[k] || 0) + m.cost;
696
+ addBucketModelCost(bucketModelCosts, k, m.model, m.cost);
588
697
  if (isRealModel(m.model)) {
589
698
  modelCosts[m.model] = (modelCosts[m.model] || 0) + m.cost;
590
699
  projModels.add(m.model);
@@ -614,12 +723,15 @@ async function getOverviewData(range, projectFilter) {
614
723
  }
615
724
  }
616
725
 
617
- const costSeries = buildCostSeries(bucketCosts, cutoff, now, bucket);
726
+ const costSeries = buildCostSeries(bucketModelCosts, cutoff, windowEnd, bucket);
618
727
 
728
+ // The today slice is scoped to the window. A window that ends before today has no today bucket,
729
+ // and a 0 there reads as "nothing spent today" rather than "outside the selected window" — so it
730
+ // is reported as null and the card is dropped instead.
619
731
  const todayStr = localDateStr(now);
620
- const todayCost = Object.entries(bucketCosts)
621
- .filter(([k]) => k.startsWith(todayStr))
622
- .reduce((s, [, c]) => s + c, 0);
732
+ const todayCost = w.hasToday
733
+ ? costSeries.filter((p) => p.key.startsWith(todayStr)).reduce((s, p) => s + p.cost, 0)
734
+ : null;
623
735
 
624
736
  const totalInputAll = totalInput + totalCacheCreation + totalCacheRead;
625
737
  const cacheEfficiency = totalInputAll > 0 ? totalCacheRead / totalInputAll : 0;
@@ -644,14 +756,13 @@ async function getOverviewData(range, projectFilter) {
644
756
  }
645
757
 
646
758
  async function getProjectsData(range, projectFilter) {
647
- const cacheKey = `projects_${range || 'all'}_${projectFilter || 'all'}`;
648
- if (isCacheValid(cacheKey)) return dataCache[cacheKey];
759
+ const cacheKey = `projects_${rangeKey(range)}_${projectFilter || 'all'}`;
760
+ const cached = getCache(cacheKey);
761
+ if (cached !== undefined) return cached;
649
762
 
650
763
  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;
764
+ const w = resolveWindow(range);
765
+ const projects = scanProjectDirs(w.cutoff, projectFilter);
655
766
  const result = [];
656
767
 
657
768
  for (const [encodedPath, proj] of projects) {
@@ -660,9 +771,7 @@ async function getProjectsData(range, projectFilter) {
660
771
  const projModelCounts = {};
661
772
 
662
773
  for (const [, session] of sessions) {
663
- const msgs = cutoffStr
664
- ? session.messages.filter(m => m.timestamp >= cutoffStr)
665
- : session.messages;
774
+ const msgs = filterWindow(session.messages, w.cutoffStr, w.endStr);
666
775
  if (msgs.length === 0) continue;
667
776
 
668
777
  const cost = msgs.reduce((s, m) => s + m.cost, 0);
@@ -696,35 +805,32 @@ async function getProjectsData(range, projectFilter) {
696
805
  }
697
806
 
698
807
  async function getProjectSessionsData(encodedPath, range) {
699
- const cacheKey = `sessions_${encodedPath}_${range || 'all'}`;
700
- if (isCacheValid(cacheKey)) return dataCache[cacheKey];
808
+ const cacheKey = `sessions_${encodedPath}_${rangeKey(range)}`;
809
+ const cached = getCache(cacheKey);
810
+ if (cached !== undefined) return cached;
701
811
 
702
812
  const pricing = await fetchPricing();
703
- const now = new Date();
704
- const cutoff = rangeToCutoff(range, now);
705
- const projects = scanProjectDirs(cutoff);
813
+ const w = resolveWindow(range);
814
+ const projects = scanProjectDirs(w.cutoff);
706
815
  const proj = projects.get(encodedPath);
707
816
  const bucket = rangeBucket(range);
708
817
  if (!proj) return { sessions: [], costSeries: { bucket, points: [] }, modelDistribution: [] };
709
818
 
710
819
  const sessions = await loadProjectData(proj.files, pricing);
711
- const cutoffStr = cutoff ? cutoff.toISOString() : null;
712
820
  const result = [];
713
821
  const bucketKey = BUCKETS[bucket].key;
714
- const bucketCosts = {};
822
+ const bucketModelCosts = {};
715
823
  const modelCosts = {};
716
824
 
717
825
  for (const [, session] of sessions) {
718
- const msgs = cutoffStr
719
- ? session.messages.filter(m => m.timestamp >= cutoffStr)
720
- : session.messages;
826
+ const msgs = filterWindow(session.messages, w.cutoffStr, w.endStr);
721
827
  if (msgs.length === 0) continue;
722
828
 
723
829
  const sum = summarizeMessages(msgs);
724
830
  const sessionModelCounts = {};
725
831
  for (const m of msgs) {
726
832
  const k = bucketKey(new Date(m.timestamp));
727
- bucketCosts[k] = (bucketCosts[k] || 0) + m.cost;
833
+ addBucketModelCost(bucketModelCosts, k, m.model, m.cost);
728
834
  if (isRealModel(m.model)) {
729
835
  modelCosts[m.model] = (modelCosts[m.model] || 0) + m.cost;
730
836
  sessionModelCounts[m.model] = (sessionModelCounts[m.model] || 0) + 1;
@@ -750,12 +856,12 @@ async function getProjectSessionsData(encodedPath, range) {
750
856
  }
751
857
 
752
858
  // No range means "everything", so the series starts at the first bucket that has cost.
753
- let seriesStart = cutoff;
859
+ let seriesStart = w.cutoff;
754
860
  if (!seriesStart) {
755
- const keys = Object.keys(bucketCosts).sort();
756
- seriesStart = keys.length ? new Date(`${keys[0]}T00:00:00`) : now;
861
+ const keys = Object.keys(bucketModelCosts).sort();
862
+ seriesStart = keys.length ? new Date(`${keys[0]}T00:00:00`) : w.now;
757
863
  }
758
- const costSeries = buildCostSeries(bucketCosts, seriesStart, now, bucket);
864
+ const costSeries = buildCostSeries(bucketModelCosts, seriesStart, w.end, bucket);
759
865
 
760
866
  const modelDistribution = buildModelDistribution(modelCosts);
761
867
 
@@ -774,21 +880,24 @@ async function getProjectSessionsData(encodedPath, range) {
774
880
  // instead of silently disagreeing with it. They are derived outside the cache so switching ranges
775
881
  // does not re-parse the session's JSONL.
776
882
  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;
883
+ const w = resolveWindow(range);
884
+ const slice = (fromStr) => summarizeMessages(filterWindow(base.messages, fromStr, w.endStr));
885
+ const inRange = w.cutoffStr ? slice(w.cutoffStr) : null;
886
+ const todayStart = rangeToCutoff('today', w.now);
887
+ // Scoped to the window like the overview's today card: a window ending in the past has no
888
+ // today to report, and a zeroed slice would read as "nothing spent today".
781
889
  return {
782
890
  ...base,
783
891
  range,
784
892
  inRange,
785
- today: range === 'today' ? inRange : sliceFrom(rangeToCutoff('today', now).toISOString()),
893
+ today: isTodayRange(range, w.now) ? inRange : w.hasToday ? slice(todayStart.toISOString()) : null,
786
894
  };
787
895
  }
788
896
 
789
897
  async function getSessionDetailData(sessionId) {
790
898
  const cacheKey = `detail_${sessionId}`;
791
- if (isCacheValid(cacheKey)) return dataCache[cacheKey];
899
+ const cached = getCache(cacheKey);
900
+ if (cached !== undefined) return cached;
792
901
 
793
902
  const pricing = await fetchPricing();
794
903
  const projects = scanProjectDirs();
@@ -857,10 +966,36 @@ app.get('/hub-config', (_req, res) => {
857
966
 
858
967
  function parseRange(raw, fallback = null) {
859
968
  if (raw === 'today') return 'today';
969
+ if (raw === '24h') return '24h';
860
970
  const n = parseInt(raw, 10);
861
971
  return Number.isFinite(n) ? n : fallback;
862
972
  }
863
973
 
974
+ const DATE_PARAM = /^\d{4}-\d{2}-\d{2}$/;
975
+
976
+ // A local calendar date, normalized so it can safely reach a cache key — same discipline as
977
+ // parseProject. Returns undefined for absent, null for malformed.
978
+ function parseDateParam(raw) {
979
+ if (raw === undefined || raw === '') return undefined;
980
+ if (typeof raw !== 'string' || !DATE_PARAM.test(raw)) return null;
981
+ return localDateStr(localDayStart(raw)) === raw ? raw : null;
982
+ }
983
+
984
+ // A custom window, if the request asked for one: `from`/`to` take precedence over `range`.
985
+ // Reversed pairs are ordered and both ends clamped to today — there is no cost data ahead of now,
986
+ // and an inverted window would otherwise render as an unexplained empty chart.
987
+ // Returns undefined when no window was requested, null when one was but is malformed.
988
+ function parseCustomRange(query) {
989
+ const from = parseDateParam(query.from);
990
+ const to = parseDateParam(query.to);
991
+ if (from === null || to === null) return null;
992
+ if (from === undefined && to === undefined) return undefined;
993
+ if (from === undefined || to === undefined) return null;
994
+ const today = localDateStr(new Date());
995
+ const [lo, hi] = from <= to ? [from, to] : [to, from];
996
+ return { from: lo > today ? today : lo, to: hi > today ? today : hi };
997
+ }
998
+
864
999
  // Encoded project-dir name (the hub sends it pre-encoded — see encodeProjectPath in the hub's
865
1000
  // public/app.js; this regex must stay a superset of that transform's output). Only ever used as
866
1001
  // a Map key, never joined into a path — the regex exists to keep unbounded strings out of the
@@ -873,12 +1008,23 @@ function parseProject(raw) {
873
1008
  return raw;
874
1009
  }
875
1010
 
876
- app.get('/api/overview', async (req, res) => {
1011
+ // Resolves a request's range onto req.range: a custom from/to window wins over `range`. A resolved
1012
+ // range cannot signal malformed input with null (null *is* the all-time range), so the rejection
1013
+ // happens here, ahead of the handler, instead of being threaded back to it as a sentinel value.
1014
+ // Only the range — a route that also scopes by project keeps its own parseProject guard, because
1015
+ // the routes that don't call parseProject must go on ignoring a malformed `project`.
1016
+ const withRange = (fallback = null) => (req, res, next) => {
1017
+ const custom = parseCustomRange(req.query);
1018
+ if (custom === null) return res.status(400).json({ error: 'Invalid date range' });
1019
+ req.range = custom || parseRange(req.query.range, fallback);
1020
+ next();
1021
+ };
1022
+
1023
+ app.get('/api/overview', withRange(30), async (req, res) => {
877
1024
  try {
878
- const range = parseRange(req.query.range, 30);
879
1025
  const project = parseProject(req.query.project);
880
1026
  if (project === null) return res.status(400).json({ error: 'Invalid project' });
881
- const data = await getOverviewData(range, project);
1027
+ const data = await getOverviewData(req.range, project);
882
1028
  res.json(data);
883
1029
  } catch (err) {
884
1030
  console.error('[API] overview error:', err);
@@ -886,12 +1032,11 @@ app.get('/api/overview', async (req, res) => {
886
1032
  }
887
1033
  });
888
1034
 
889
- app.get('/api/projects', async (req, res) => {
1035
+ app.get('/api/projects', withRange(), async (req, res) => {
890
1036
  try {
891
- const range = parseRange(req.query.range);
892
1037
  const project = parseProject(req.query.project);
893
1038
  if (project === null) return res.status(400).json({ error: 'Invalid project' });
894
- const data = await getProjectsData(range, project);
1039
+ const data = await getProjectsData(req.range, project);
895
1040
  res.json(data);
896
1041
  } catch (err) {
897
1042
  console.error('[API] projects error:', err);
@@ -899,10 +1044,9 @@ app.get('/api/projects', async (req, res) => {
899
1044
  }
900
1045
  });
901
1046
 
902
- app.get('/api/projects/:path/sessions', async (req, res) => {
1047
+ app.get('/api/projects/:path/sessions', withRange(), async (req, res) => {
903
1048
  try {
904
- const range = parseRange(req.query.range);
905
- const data = await getProjectSessionsData(req.params.path, range);
1049
+ const data = await getProjectSessionsData(req.params.path, req.range);
906
1050
  res.json(data);
907
1051
  } catch (err) {
908
1052
  console.error('[API] sessions error:', err);
@@ -910,11 +1054,11 @@ app.get('/api/projects/:path/sessions', async (req, res) => {
910
1054
  }
911
1055
  });
912
1056
 
913
- app.get('/api/sessions/:id', async (req, res) => {
1057
+ app.get('/api/sessions/:id', withRange(), async (req, res) => {
914
1058
  try {
915
1059
  const base = await getSessionDetailData(req.params.id);
916
1060
  if (!base) return res.status(404).json({ error: 'Session not found' });
917
- res.json(withSessionSlices(base, parseRange(req.query.range)));
1061
+ res.json(withSessionSlices(base, req.range));
918
1062
  } catch (err) {
919
1063
  console.error('[API] session detail error:', err);
920
1064
  res.status(500).json({ error: 'Failed to load session detail' });