opencode-statboard 2.3.0 → 2.4.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.
@@ -16,7 +16,7 @@ permissions:
16
16
 
17
17
  jobs:
18
18
  publish:
19
- runs-on: ubuntu-latest
19
+ runs-on: ubuntu-24.04
20
20
  steps:
21
21
  - uses: actions/checkout@v6
22
22
  - uses: actions/setup-node@v6
package/AGENTS.md CHANGED
@@ -41,8 +41,10 @@ Token/cost attribution uses a hybrid model:
41
41
  1. **Message-level** — Each assistant message's `tokens` and `cost` from `message.data` JSON are attributed to its `time_created` local day
42
42
  2. **Session residual** — `session.tokens_* - sum(message.tokens_*)` is spread across the session's full local-day span, weighted by per-day message volume
43
43
  3. **Speed (message-level only)** — Per-model `speed` (output tok/s) = Σ completed-assistant-message `tokens.output` ÷ Σ(`time.completed - time.created`). Session residuals carry no duration and are excluded; models without usable durations report `null` (shown as —). Tracked in the same message scan, no extra query.
44
- 4. **Period speed/active/wall (report)** — `buildReportFromDb` runs one extra `GROUP BY session_id` over the merged message view (scoped to `[periodStart, attrSnapshot)`), mapped onto the same session-meta buckets: providers/agents gain period `speed`; agents gain `wallMs` (Σ full session spans — same scope as their token columns) and `activeMs` (Σ in-period message durations); `report.sessions` lists the top 20 sessions by wall time with both durations. Wall includes idle; active counts only model-running time.
45
- 5. **Savings estimate (pricing.js, shared with checks)** — Market value at paid rates from the local opencode catalog (`~/.cache/opencode/models.json`, USD/1M). Free models map to a paid basis in order: exact provider/model → strip `-free`/`-contributor-free`, same provider → same base under `opencode` → same base anywhere (sorted) → `proxy:opencode/deepseek-v4-flash` fallback. Reasoning bills at the output rate; `pricedAs` records the entry used per row. Overview and report both use session-meta grouping so the two panels agree (message-level splits would price model-switched sessions differently).
44
+ 4. **Per-message authority** — When a session's message sums exceed its session-table counters (V2 migration artifact: 455 sessions were recomputed from surviving messages and dropped pruned history; one session reports 52M input where the table says 7.3M), the measured message values win. Overview therefore reads the attribution totals, not `SUM(session.tokens_*)`, so Overview and Report(All) cannot disagree.
45
+ 5. **Period scope (report)** — `attributeUsage(start, end, periodStartMs)` slices EVERY total into `*Period` buckets alongside the all-time ones (one scan serves both views; `getAttrAll()` passes `periodStartMs = 0`). Report providers/agents/sessions are built from those period buckets — message tokens under the MESSAGE's model/agent, residual under the SESSION's — so every table column sums exactly to the summary card. `savedTotal` is Σ provider `saved`, never `lifetime market − period cost`.
46
+ 6. **Speed / active / wall** — `speed` (output tok/s) and `activeMs` come from in-period message durations; `wallMs` is the per-session span **on the message clock** (`MIN(time_created)`→`MAX(time.completed)`), NOT `session.time_updated − time_created`: subagent/fork sessions are written with both timestamps in the same millisecond, so session-table spans report ~0 wall for hours of real work. Wall includes idle; active is model-running time only, so `wall >= active` always holds (asserted in `check-report-verify.js`).
47
+ 7. **Savings estimate (pricing.js, shared with checks)** — Market value at paid rates from the local opencode catalog (`~/.cache/opencode/models.json`, USD/1M). Free models map to a paid basis in order: exact provider/model → strip `-free`/`-contributor-free`, same provider → same base under `opencode` → same base anywhere (sorted) → `proxy:opencode/deepseek-v4-flash` fallback. Reasoning bills at the output rate (verified: `tokens.output` does NOT include reasoning — 8,764 messages have reasoning > output). Pricing is per MESSAGE model, so real paid usage is no longer filed under the session's free-model label. `pricedAs` records the entry used per row.
46
48
 
47
49
  This ensures multi-day sessions (e.g. a session created Monday, updated Thursday) don't dump all tokens onto Thursday.
48
50
 
@@ -120,7 +122,7 @@ npm install -g opencode-statboard # after the Actions run is green
120
122
  - `better-sqlite3` is a native addon; must match Node.js ABI
121
123
  - `attributeUsage` does a full DB scan (~35k messages); cached 300s via `getAttrAll()`
122
124
  - Trend buckets are sliced from the same `getAttrAll()` attribution the report uses — never a separate windowed call (windowed calls inflate in-window days via residual growth; fixed 2026-09-29 after measuring +0.25–1.7M input/day). Remaining panel differences are cache ages only (trend ≤60s, report ≤10min, both timestamps shown)
123
- - V2 tool counts use `json_each` over `session_message` content (~1.2s full scan) and run on every 15s refresh; legacy V1 DBs scan `part` instead (~0.8s)
125
+ - V2 tool counts use `json_each` over `session_message` content (~1.5s full scan), cached 5min via `toolsCache` (the 15s refresh serves cache; verification accepts api<=expected so staleness never fails checks); legacy V1 DBs scan `part` instead
124
126
  - OpenCode V2 writes `cost = 0` for free/subscription providers, so $ totals only reflect paid (per-token billed) usage — same field, not a schema issue
125
127
  - `gzip` compression on all `/api/` responses (>512B, level 1 for speed)
126
128
  - Backup is deferred 30s after startup — heavy disk I/O (500MB copy+compress) during startup causes Windows to terminate the process
package/README.md CHANGED
@@ -11,6 +11,7 @@ Real-time dashboard for your [opencode](https://opencode.ai) token usage and cos
11
11
  - Usage reports: per-agent speed, wall/active time, and top-20 sessions by duration
12
12
  - Savings estimate: market value at paid catalog rates vs actual cost (per-model, per-report, overview cards)
13
13
  - Visual charts for model speed, agent wall/active time, and longest sessions
14
+ - Visual usage-report tables (providers, agents, sessions) with collapsible raw text
14
15
  - Collapsible sections (collapse state remembered in browser)
15
16
  - Daily trend chart (7D / 30D / 90D)
16
17
  - Usage reports: Daily / Weekly / Monthly / All time
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-statboard",
3
- "version": "2.3.0",
3
+ "version": "2.4.0",
4
4
  "description": "Real-time dashboard for opencode token usage and cost statistics",
5
5
  "main": "server.js",
6
6
  "bin": {
package/public/index.html CHANGED
@@ -36,6 +36,14 @@
36
36
  .bar-row { display: grid; grid-template-columns: 150px 1fr 120px; align-items: center; gap: 12px; padding: 7px 0; font-size: 13px; }
37
37
  .bar-row .name { color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
38
38
  .bar-row .val { text-align: right; font-variant-numeric: tabular-nums; }
39
+ .bar-row.wide { grid-template-columns: minmax(220px, 320px) 1fr 120px; }
40
+ .bar-row.wide .name { font-size: 12px; }
41
+ .scrollx { overflow-x: auto; }
42
+ .scrollx table { min-width: 880px; }
43
+ td.clip { max-width: 240px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
44
+ .rep-head { color: var(--muted); font-size: 12px; margin-bottom: 12px; }
45
+ .rep-hint { color: var(--muted); font-size: 12px; font-weight: 400; }
46
+ .rep-pre { font-family: monospace; font-size: 13px; line-height: 1.6; white-space: pre; overflow-x: auto; color: var(--text); margin: 0; }
39
47
  .track { background: #21262d; border-radius: 4px; height: 12px; overflow: hidden; }
40
48
  .fill { height: 100%; border-radius: 4px; transition: width .6s ease; min-width: 1px; }
41
49
  .stack { display: flex; height: 100%; }
@@ -215,7 +223,7 @@ const STRINGS = {
215
223
  totalCost: 'Total Cost', avgCostDay: 'Avg Cost / Day',
216
224
  avgTokensSession: 'Avg Tokens / Session', medianTokensSession: 'Median Tokens / Session', marketValue: 'Market Value', saved: 'Saved', savings: 'SAVINGS',
217
225
  tokenStats: 'TOKEN STATISTICS', toolUsage: 'TOOL USAGE', modelUsage: 'MODEL USAGE',
218
- thModel: 'Model', thMsgs: 'Messages', thSpeed: 'Speed', thUsage: 'Usage', thCost: 'Cost',
226
+ thModel: 'Model', thMsgs: 'Messages', thSpeed: 'Speed', thUsage: 'Usage', thCost: 'Cost', repProviders: 'PROVIDERS & MODELS', repAgents: 'AGENTS', repSessions: 'SESSIONS', repPricing: 'PRICING BASIS', repRaw: 'RAW TEXT',
219
227
  dailyTrend: 'DAILY TREND ({days} DAYS)',
220
228
  inputDay: 'Input / Day', outputDay: 'Output / Day', cacheReadDay: 'Cache Read / Day', costDay: 'Cost / Day',
221
229
  report: 'USAGE REPORT', all: 'All', daily: 'Daily', weekly: 'Weekly', monthly: 'Monthly', modelSpeed: 'MODEL SPEED', agentTime: 'AGENT TIME', topSessions: 'TOP SESSIONS',
@@ -232,7 +240,7 @@ const STRINGS = {
232
240
  totalCost: '總費用', avgCostDay: '平均費用 / 天',
233
241
  avgTokensSession: '平均 tokens / 場', medianTokensSession: '中位數 tokens / 場', marketValue: '市價', saved: '已節省', savings: '節省金額',
234
242
  tokenStats: 'Tokens 統計', toolUsage: '工具使用', modelUsage: '模型使用',
235
- thModel: '模型', thMsgs: '訊息', thSpeed: '速度', thUsage: '用量', thCost: '費用',
243
+ thModel: '模型', thMsgs: '訊息', thSpeed: '速度', thUsage: '用量', thCost: '費用', repProviders: '供應商與模型', repAgents: '代理', repSessions: '場次', repPricing: '定價依據', repRaw: '原始文字',
236
244
  dailyTrend: '近 {days} 天趨勢',
237
245
  inputDay: 'Input / 天', outputDay: 'Output / 天', cacheReadDay: 'Cache Read / 天', costDay: '費用 / 天',
238
246
  report: '用量報告', all: '全部', daily: '每日', weekly: '每週', monthly: '每月', modelSpeed: '模型速度', agentTime: '代理時間', topSessions: '最長場次',
@@ -315,6 +323,21 @@ const fmtCost = (n) => (n == null || isNaN(n)) ? '—' : '$' + n.toFixed(2);
315
323
  const fmtDur = (ms) => { const v = Math.round((ms || 0) / 1000); if (!isFinite(v) || v < 0) return '—'; const d = Math.floor(v / 86400), h = Math.floor(v % 86400 / 3600), m = Math.floor(v % 3600 / 60), s = v % 60; if (d > 0) return d + 'd' + h + 'h'; if (h > 0) return h + 'h' + String(m).padStart(2, '0') + 'm'; if (m > 0) return m + 'm' + String(s).padStart(2, '0') + 's'; return s + 's'; };
316
324
  const esc = (s) => String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
317
325
  const fmtSpeed = (n) => (n == null || isNaN(n) || !isFinite(n)) ? '—' : ((n >= 100 ? Math.round(n) : Math.round(n * 10) / 10) + ' tok/s');
326
+ const dispAgent = (n) => (n === 'unknown' ? 'legacy' : n);
327
+ const LEGACY_TIP = 'pre-2026-08 V1 legacy, $0';
328
+ function agentTip(base, name) {
329
+ if (name !== 'unknown') return base || '';
330
+ return (base ? base + ' · ' : '') + LEGACY_TIP;
331
+ }
332
+
333
+ // Skip-unchanged-redraw cache: remember last rendered generations.
334
+ let lastStatsGen = null;
335
+ let lastTrendGen = null;
336
+ const reportGenCache = {};
337
+ let displayedReportDays = null;
338
+ let cachedReport = null;
339
+ let cachedReportDays = null;
340
+ let reportChain = Promise.resolve();
318
341
 
319
342
  function barRow(name, value, max, color) {
320
343
  const pct = max > 0 ? Math.max(0.5, (value / max) * 100) : 0;
@@ -513,7 +536,7 @@ function renderReportCharts(r) {
513
536
  const fullName = (p) => p.provider + '/' + p.model;
514
537
  $('speed-bars').innerHTML = spd.length ? spd.map((p) => {
515
538
  const pct = smax > 0 && p.speed != null ? Math.max(0.5, (p.speed / smax) * 100) : 0;
516
- return `<div class="bar-row"><div class="name" title="${esc(fullName(p))}">${esc(fullName(p))}</div>
539
+ return `<div class="bar-row wide"><div class="name" title="${esc(fullName(p))}">${esc(fullName(p))}</div>
517
540
  <div class="track"><div class="fill" style="width:${pct}%;background:var(--in)"></div></div>
518
541
  <div class="val">${fmtSpeed(p.speed)}</div></div>`;
519
542
  }).join('') : '<div class="val">—</div>';
@@ -539,12 +562,61 @@ function renderReportCharts(r) {
539
562
  const pct = mmax > 0 ? Math.max(0.5, ((p.market || 0) / mmax) * 100) : 0;
540
563
  const sv = p.saved == null ? '—' : fmtCost(p.saved) + ' saved';
541
564
  const tip = 'market ' + fmtCost(p.market) + ' · actual ' + fmtCost(p.cost) + ' · via ' + (p.pricedAs || '?');
542
- return `<div class="bar-row"><div class="name" title="${esc(fullName(p))}">${esc(fullName(p))}</div>
565
+ return `<div class="bar-row wide"><div class="name" title="${esc(fullName(p))}">${esc(fullName(p))}</div>
543
566
  <div class="track"><div class="fill" style="width:${pct}%;background:var(--cost)"></div></div>
544
567
  <div class="val" title="${esc(tip)}">${sv}</div></div>`;
545
568
  }).join('') : '<div class="val">—</div>';
546
569
  }
547
570
 
571
+ function repTable(heads, rows) {
572
+ return `<div class="scrollx"><table><thead><tr>${heads.map((h) => `<th>${esc(h)}</th>`).join('')}</tr></thead><tbody>${rows.join('')}</tbody></table></div>`;
573
+ }
574
+
575
+ function repBlock(title, hint, body, isOpen) {
576
+ return `<details class="tool-section"${isOpen ? ' open' : ''}><summary><h2>${esc(title)}</h2><span class="rep-hint">${esc(hint)}</span></summary>${body}</details>`;
577
+ }
578
+
579
+ function renderReportTables(r) {
580
+ const o = (r.stats && r.stats.overview) || {};
581
+ const c = (r.stats && r.stats.cost) || {};
582
+ const genTime = r.generatedAt ? new Date(r.generatedAt).toLocaleTimeString(lang === 'zh-TW' ? 'zh-TW' : 'en', { hour12: false }) : '?';
583
+ const periodText = r.days === -1 ? 'All time' : r.days <= 1 ? 'Today (local)' : r.days <= 7 ? 'Last 7 days (local)' : 'Month to date (local)';
584
+ let h = `<div class="rep-head">OPENCODE USAGE STATEMENT · ${esc(r.label || '')} · ${esc(periodText)} · ${esc(r.stale ? '⟳ ' + t('updating') : t('cachedAt') + ' ' + genTime)}</div>`;
585
+ h += `<div class="cards">` + [
586
+ [t('sessions'), fmt(o.sessions)], [t('messages'), fmt(o.messages)],
587
+ [t('totalCost'), fmtCost(c.total)], [t('marketValue'), fmtCost(c.marketTotal)],
588
+ [t('saved'), fmtCost(c.savedTotal)],
589
+ ].map(([l, v]) => `<div class="card"><div class="l">${esc(l)}</div><div class="v" style="font-size:20px">${esc(String(v))}</div></div>`).join('') + `</div>`;
590
+
591
+ const prov = r.providers || [];
592
+ h += repBlock(t('repProviders'), prov.length + ' models' + (prov.length ? ' · ' + prov[0].provider + '/' + prov[0].model : ''),
593
+ repTable(['Model', 'Sess', 'Cost', 'In', 'Out', 'Cache', 'Speed', 'Market', 'Saved'], prov.map((p) => {
594
+ const name = p.provider + '/' + p.model;
595
+ return `<tr><td class="clip" title="${esc(name)}">${esc(name)}</td><td>${p.sessions}</td><td>${fmtCost(p.cost)}</td><td>${fmt(p.tok_in)}</td><td>${fmt(p.tok_out)}</td><td>${fmt(p.cache_read)}</td><td>${fmtSpeed(p.speed)}</td><td>${fmtCost(p.market)}</td><td>${fmtCost(p.saved)}</td></tr>`;
596
+ })), true);
597
+
598
+ const ags = r.agents || [];
599
+ h += repBlock(t('repAgents'), ags.length + ' agents' + (ags.length ? ' · ' + ags[0].agent : ''),
600
+ repTable(['Agent', 'Sess', 'Cost', 'In', 'Out', 'Speed', 'Wall', 'Active', 'Market', 'Saved'], ags.map((a) =>
601
+ `<tr><td>${esc(a.agent)}</td><td>${a.sessions}</td><td>${fmtCost(a.cost)}</td><td>${fmt(a.tok_in)}</td><td>${fmt(a.tok_out)}</td><td>${fmtSpeed(a.speed)}</td><td>${fmtDur(a.wallMs)}</td><td>${fmtDur(a.activeMs)}</td><td>${fmtCost(a.market)}</td><td>${fmtCost(a.saved)}</td></tr>`)), true);
602
+
603
+ const sess = r.sessions || [];
604
+ h += repBlock(t('repSessions'), 'top ' + sess.length + ' by wall',
605
+ repTable(['Session', 'Agent', 'Model', 'Wall', 'Active', 'Msgs', 'In', 'Out', 'Speed', 'Saved'], sess.map((s) => {
606
+ const name = s.provider + '/' + s.model;
607
+ return `<tr><td class="clip" title="${esc(s.id + ' · ' + (s.title || ''))}">${esc(String(s.id).slice(0, 12))}</td><td>${esc(s.agent)}</td><td class="clip" title="${esc(name)}">${esc(name)}</td><td>${fmtDur(s.wallMs)}</td><td>${fmtDur(s.activeMs)}</td><td>${s.messages}</td><td>${fmt(s.tok_in)}</td><td>${fmt(s.tok_out)}</td><td>${fmtSpeed(s.speed)}</td><td>${fmtCost(s.saved)}</td></tr>`;
608
+ })), true);
609
+
610
+ const basis = prov.filter((p) => p.pricedAs && p.pricedAs !== (p.provider + '/' + p.model));
611
+ if (basis.length) {
612
+ h += repBlock(t('repPricing'), basis.length + ' mappings',
613
+ repTable(['Usage', 'Basis'], basis.map((p) =>
614
+ `<tr><td class="clip" title="${esc(p.provider + '/' + p.model)}">${esc(p.provider + '/' + p.model)}</td><td class="clip" title="${esc(p.pricedAs)}">${esc(p.pricedAs)}</td></tr>`)), false);
615
+ }
616
+ h += repBlock(t('repRaw'), 'statement text', `<pre class="rep-pre">${esc(formatReport(r))}</pre>`, false);
617
+ return h;
618
+ }
619
+
548
620
  function formatReport(jr) {
549
621
  const genTime = jr.generatedAt ? new Date(jr.generatedAt).toLocaleTimeString(lang === 'zh-TW' ? 'zh-TW' : 'en', { hour12: false }) : '?';
550
622
  const cachedNote = jr.stale ? ' [⟳ ' + t('updating') + ']' : ' [' + t('cachedAt') + ' ' + genTime + ']';
@@ -624,7 +696,7 @@ async function loadReport(days) {
624
696
  return;
625
697
  }
626
698
  reportRetry = 0;
627
- $('reportContent').textContent = formatReport(j.report);
699
+ $('reportContent').innerHTML = renderReportTables(j.report);
628
700
  renderReportCharts(j.report);
629
701
  } catch (e) {
630
702
  $('reportContent').textContent = t('connFail') + ': ' + e.message;
package/server.js CHANGED
@@ -16,6 +16,7 @@ const PORT = parseInt(process.env.OC_PORT || '4868', 10);
16
16
  const REFRESH_MS = 15000;
17
17
  const TREND_MS = 60 * 1000;
18
18
  const REPORT_TTL = 10 * 60 * 1000;
19
+ const TOOLS_TTL = 5 * 60 * 1000;
19
20
  const STATS_TTL = 10 * 60 * 1000;
20
21
  const CACHE_CLEANUP_MS = 5 * 60 * 1000;
21
22
  const BACKUP_DIR = path.join(__dirname, 'backups');
@@ -300,14 +301,41 @@ function marketOf(tok, provider, model) {
300
301
  // proportional to that session's per-day message-token volume
301
302
  // (uniform across spanned days when the session has no messages).
302
303
  // Returns perDay/perModel/perAgent/perSession maps plus totals.
303
- function attributeUsage(startMs, endMs) {
304
+ // periodStartMs (optional): when set, ALSO slice every total into
305
+ // *-Period buckets covering only local days >= periodStartMs. The all-time
306
+ // buckets (perDay/perModel/perSession) are unaffected, so one scan serves both
307
+ // the trend (lifetime) and the report (period) views. Period buckets group
308
+ // message tokens by the MESSAGE's own model/agent, and spread session residual
309
+ // by the session's model/agent — so per-model report rows sum exactly to the
310
+ // period totals (self-consistent by construction).
311
+ function attributeUsage(startMs, endMs, periodStartMs) {
312
+ const periodOn = periodStartMs != null;
313
+ const inPeriod = periodOn ? (key) => dateOfKey(key).getTime() >= periodStartMs : () => false;
304
314
  const perDay = {};
305
315
  const perModel = {};
306
316
  const perAgent = {};
307
317
  const perSession = {};
318
+ const perModelPeriod = {};
319
+ const perAgentPeriod = {};
320
+ const perAgentModelPeriod = {};
321
+ const perSessionPeriod = {};
322
+ const perSessionModelPeriod = {};
308
323
  const ensureDay = (key) => perDay[key] || (perDay[key] = { date: dateOfKey(key), sessions: new Set(), messages: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 });
309
324
  const ensureModel = (n) => perModel[n] || (perModel[n] = { messages: 0, sessions: new Set(), input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0, speedOut: 0, speedMs: 0 });
310
325
  const ensureAgent = (a) => perAgent[a || 'unknown'] || (perAgent[a || 'unknown'] = { messages: 0, sessions: new Set(), input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 });
326
+ const tok = () => ({ input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 });
327
+ const ensureModelP = (n) => perModelPeriod[n] || (perModelPeriod[n] = { messages: 0, sessions: new Set(), input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0, speedOut: 0, speedMs: 0 });
328
+ const ensureAgentP = (a) => perAgentPeriod[a || 'unknown'] || (perAgentPeriod[a || 'unknown'] = { sessions: new Set(), input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0, speedOut: 0, speedMs: 0 });
329
+ const ensureAgentModelP = (a, m) => {
330
+ const k = a || 'unknown';
331
+ const bag = perAgentModelPeriod[k] || (perAgentModelPeriod[k] = {});
332
+ return bag[m] || (bag[m] = tok());
333
+ };
334
+ const ensureSessP = (sid) => perSessionPeriod[sid] || (perSessionPeriod[sid] = tok());
335
+ const ensureSessModelP = (sid, m) => {
336
+ const bag = perSessionModelPeriod[sid] || (perSessionModelPeriod[sid] = {});
337
+ return bag[m] || (bag[m] = tok());
338
+ };
311
339
 
312
340
  // 1. messages in period (exact timing)
313
341
  const msgTok = {};
@@ -341,6 +369,28 @@ function attributeUsage(startMs, endMs) {
341
369
  w.total += vol;
342
370
  w.perDay[key] = (w.perDay[key] || 0) + vol;
343
371
  }
372
+ // Period slice: message tokens under the MESSAGE's own model/agent.
373
+ if (periodOn && inPeriod(key)) {
374
+ const mName = modelNameOf(r.provider, r.model);
375
+ const aName = r.agent || 'unknown';
376
+ const MP = ensureModelP(mName);
377
+ MP.messages++;
378
+ if (r.sid) MP.sessions.add(r.sid);
379
+ MP.input += iv; MP.output += ov; MP.reasoning += rv; MP.cacheRead += crv; MP.cacheWrite += cwv; MP.cost += cv;
380
+ if (ov > 0 && t1 > t0) { MP.speedOut += ov; MP.speedMs += (t1 - t0); }
381
+ const AP = ensureAgentP(aName);
382
+ if (r.sid) AP.sessions.add(r.sid);
383
+ AP.input += iv; AP.output += ov; AP.reasoning += rv; AP.cacheRead += crv; AP.cacheWrite += cwv; AP.cost += cv;
384
+ if (ov > 0 && t1 > t0) { AP.speedOut += ov; AP.speedMs += (t1 - t0); }
385
+ const AM = ensureAgentModelP(aName, mName);
386
+ AM.input += iv; AM.output += ov; AM.reasoning += rv; AM.cacheRead += crv; AM.cacheWrite += cwv; AM.cost += cv;
387
+ if (r.sid) {
388
+ const SP = ensureSessP(r.sid);
389
+ SP.input += iv; SP.output += ov; SP.reasoning += rv; SP.cacheRead += crv; SP.cacheWrite += cwv; SP.cost += cv;
390
+ const SM = ensureSessModelP(r.sid, mName);
391
+ SM.input += iv; SM.output += ov; SM.reasoning += rv; SM.cacheRead += crv; SM.cacheWrite += cwv; SM.cost += cv;
392
+ }
393
+ }
344
394
  }
345
395
 
346
396
  // 2. sessions intersecting the period: spread residual
@@ -386,6 +436,21 @@ function attributeUsage(startMs, endMs) {
386
436
  const A = ensureAgent(aName);
387
437
  A.input += di; A.output += dout; A.reasoning += dr; A.cacheRead += dcr; A.cacheWrite += dcw; A.cost += dc;
388
438
  ps.input += di; ps.output += dout; ps.reasoning += dr; ps.cacheRead += dcr; ps.cacheWrite += dcw; ps.cost += dc;
439
+ // Period slice: residual shares land under the SESSION's model/agent
440
+ // (no per-message model exists for residual), but only on days inside
441
+ // the period, so period rows sum exactly to the period totals.
442
+ if (periodOn && inPeriod(k)) {
443
+ const MP = ensureModelP(mName);
444
+ MP.input += di; MP.output += dout; MP.reasoning += dr; MP.cacheRead += dcr; MP.cacheWrite += dcw; MP.cost += dc;
445
+ const AP = ensureAgentP(aName);
446
+ AP.input += di; AP.output += dout; AP.reasoning += dr; AP.cacheRead += dcr; AP.cacheWrite += dcw; AP.cost += dc;
447
+ const AM = ensureAgentModelP(aName, mName);
448
+ AM.input += di; AM.output += dout; AM.reasoning += dr; AM.cacheRead += dcr; AM.cacheWrite += dcw; AM.cost += dc;
449
+ const SP = ensureSessP(s.id);
450
+ SP.input += di; SP.output += dout; SP.reasoning += dr; SP.cacheRead += dcr; SP.cacheWrite += dcw; SP.cost += dc;
451
+ const SM = ensureSessModelP(s.id, mName);
452
+ SM.input += di; SM.output += dout; SM.reasoning += dr; SM.cacheRead += dcr; SM.cacheWrite += dcw; SM.cost += dc;
453
+ }
389
454
  }
390
455
  }
391
456
 
@@ -396,20 +461,45 @@ function attributeUsage(startMs, endMs) {
396
461
  totals.input += D.input; totals.output += D.output; totals.reasoning += D.reasoning;
397
462
  totals.cacheRead += D.cacheRead; totals.cacheWrite += D.cacheWrite; totals.cost += D.cost;
398
463
  }
399
- return { perDay, perModel, perAgent, perSession, totals };
464
+ return {
465
+ perDay, perModel, perAgent, perSession, totals,
466
+ perModelPeriod, perAgentPeriod, perAgentModelPeriod, perSessionPeriod, perSessionModelPeriod,
467
+ periodStartMs,
468
+ };
400
469
  }
401
470
 
402
471
  // All-time attribution, memoized 300s (expensive full DB scan; avoids
403
472
  // re-running attributeUsage on every /api/stats hit).
404
473
  let attrAllCache = null;
474
+ // Tool counts change slowly but the embedded-content scan costs ~1.5s on a
475
+ // large DB; cache it so the 15s refresh stays cheap. Keyed on schema+window.
476
+ let toolsCache = null;
405
477
  function getAttrAll() {
406
478
  const now = Date.now();
407
479
  if (attrAllCache && now - attrAllCache.at < 300000) return attrAllCache.a;
408
- const a = attributeUsage(0, now);
480
+ // periodStartMs = 0: the *Period buckets equal the all-time ones, so the
481
+ // All report can read them (single scan serves both views).
482
+ const a = attributeUsage(0, now, 0);
409
483
  attrAllCache = { at: now, a };
410
484
  return a;
411
485
  }
412
486
 
487
+ // Period-scoped attribution (same 300s TTL, one cache slot per period start).
488
+ // Report panels slice this instead of the all-time buckets so every row and
489
+ // the summary total describe the SAME period.
490
+ const attrPeriodCache = new Map();
491
+ function getAttrPeriod(startMs) {
492
+ const now = Date.now();
493
+ const hit = attrPeriodCache.get(startMs);
494
+ if (hit && now - hit.at < 300000) return hit.a;
495
+ const a = attributeUsage(0, now, startMs);
496
+ attrPeriodCache.set(startMs, { at: now, a });
497
+ if (attrPeriodCache.size > 6) {
498
+ for (const [k, v] of attrPeriodCache) if (now - v.at >= 300000) attrPeriodCache.delete(k);
499
+ }
500
+ return a;
501
+ }
502
+
413
503
  function computeMedian(arr) {
414
504
  if (!arr.length) return 0;
415
505
  const sorted = arr.slice().sort((a, b) => a - b);
@@ -427,48 +517,62 @@ function getStatsFromDb(days) {
427
517
  // NOTE: days is only ever 0 here (overview totals); per-period stats are
428
518
  // built by buildReportFromDb via attributeUsage. Local-day count so the
429
519
  // number matches the trend chart buckets.
430
- const overview = dbGet(`SELECT COUNT(*) AS sessions, COUNT(DISTINCT date(s.time_updated / 1000, 'unixepoch', 'localtime')) AS days FROM ${schema.session} s ${timeFilterWhere};`);
431
- const msgConds = [];
432
- if (startMs) msgConds.push('m.time_updated >= ' + startMs);
433
- const msgCount = dbGet(`SELECT COUNT(*) AS messages FROM ${schema.message} m ${msgConds.length ? 'WHERE ' + msgConds.join(' AND ') : ''};`);
434
- const costRow = dbGet(`SELECT COALESCE(SUM(tokens_input),0) AS input, COALESCE(SUM(tokens_output),0) AS output, COALESCE(SUM(tokens_reasoning),0) AS reasoning, COALESCE(SUM(tokens_cache_read),0) AS cacheRead, COALESCE(SUM(tokens_cache_write),0) AS cacheWrite, COALESCE(SUM(cost),0) AS total FROM ${schema.session} s ${timeFilterWhere};`);
520
+
435
521
 
436
522
  // V2: tool parts are embedded in session_message content (part table froze
437
523
  // at the upgrade and its migrated rows were rebuilt into content, so
438
524
  // querying all of part would double count — only parts of messages that
439
- // were never migrated are added from `part`).
440
- const toolRows = schema.embeddedTools
441
- ? dbQuery(`SELECT COALESCE(json_extract(je.value, '$.tool'), json_extract(je.value, '$.name')) AS tool FROM session_message sm, json_each(json_extract(sm.data, '$.content')) je WHERE json_extract(je.value, '$.type') = 'tool' ${startMs ? `AND sm.time_updated >= ${startMs}` : ''}
442
- UNION ALL
443
- SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' AND p.message_id NOT IN (SELECT id FROM session_message) ${startMs ? `AND p.time_updated >= ${startMs}` : ''};`) || []
444
- : dbQuery(`SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' ${timeFilterPart};`) || [];
445
- const toolCounts = {};
446
- for (const row of toolRows) {
447
- if (row.tool) toolCounts[row.tool] = (toolCounts[row.tool] || 0) + 1;
525
+ // were never migrated are added from `part`). Cached (see toolsCache):
526
+ // verification accepts api<=expected, so staleness never fails checks.
527
+ if (!toolsCache || now - toolsCache.at > TOOLS_TTL || toolsCache.embedded !== schema.embeddedTools || toolsCache.startMs !== startMs) {
528
+ const toolRows = schema.embeddedTools
529
+ ? dbQuery(`SELECT COALESCE(json_extract(je.value, '$.tool'), json_extract(je.value, '$.name')) AS tool FROM session_message sm, json_each(json_extract(sm.data, '$.content')) je WHERE json_extract(je.value, '$.type') = 'tool' ${startMs ? `AND sm.time_updated >= ${startMs}` : ''}
530
+ UNION ALL
531
+ SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' AND p.message_id NOT IN (SELECT id FROM session_message) ${startMs ? `AND p.time_updated >= ${startMs}` : ''};`) || []
532
+ : dbQuery(`SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' ${timeFilterPart};`) || [];
533
+ const counts = {};
534
+ for (const row of toolRows) {
535
+ if (row.tool) counts[row.tool] = (counts[row.tool] || 0) + 1;
536
+ }
537
+ toolsCache = { at: now, embedded: schema.embeddedTools, startMs, counts };
448
538
  }
539
+ const toolCounts = toolsCache.counts;
449
540
  const totalToolUse = Object.values(toolCounts).reduce((s, v) => s + v, 0) || 1;
450
541
  const tools = Object.entries(toolCounts)
451
542
  .map(([name, count]) => ({ name, count, pct: Math.round((count / totalToolUse) * 1000) / 10 }))
452
543
  .sort((a, b) => b.count - a.count);
453
544
 
454
- const tokenRows = dbQuery(`SELECT tokens_input + tokens_output + tokens_reasoning AS tokens FROM ${schema.session} s ${timeFilterWhere};`) || [];
455
- const tokenVals = tokenRows.map((r) => r.tokens).filter(Number.isFinite);
456
- const avgTokens = tokenVals.length ? tokenVals.reduce((s, v) => s + v, 0) / tokenVals.length : 0;
457
- const medianTokens = computeMedian(tokenVals);
458
- const activeDays = overview ? (overview.days || 1) : 1;
459
- const sessions = overview ? (overview.sessions || 0) : 0;
460
- const avgDayCost = costRow && costRow.total ? costRow.total / activeDays : 0;
545
+ const attr = getAttrAll();
546
+ const T = attr.totals;
547
+ // Overview = ALL TIME and uses the SAME attribution as the trend chart and
548
+ // Report(All), so the three panels cannot disagree. Per-message tokens are
549
+ // authoritative: a session whose message sums exceed its session-table
550
+ // counters (V2 migration artifact) keeps the measured message values
551
+ // instead of being clamped down to the session counters.
552
+ const sessions = T.sessions;
553
+ const messages = T.messages;
554
+ // Active days = day buckets that actually carry usage. Excludes pre-2000
555
+ // epoch artifacts (imported rows with time_created = 0).
556
+ const dayKeys = Object.keys(attr.perDay).filter((k) => attr.perDay[k].date.getFullYear() >= 2020);
557
+ const activeDays = dayKeys.length || 1;
558
+ const sessVals = Object.values(attr.perSession)
559
+ .filter((s) => s.input > 0 || s.output > 0 || s.reasoning > 0)
560
+ .map((s) => s.input + s.output + s.reasoning)
561
+ .filter(Number.isFinite);
562
+ const avgTokens = sessVals.length ? sessVals.reduce((s, v) => s + v, 0) / sessVals.length : 0;
563
+ const medianTokens = computeMedian(sessVals);
564
+ const avgDayCost = T.cost ? T.cost / activeDays : 0;
461
565
 
462
566
  // Per-model usage from hybrid attribution (message counts are TRUE message
463
567
  // counts here, not session counts; token/cost sums include residuals so
464
568
  // pruned history isn't lost).
465
- const attr = getAttrAll();
466
569
  const models = Object.entries(attr.perModel)
467
570
  .map(([name, m]) => ({
468
571
  name,
469
572
  messages: m.messages,
470
573
  input: Math.round(m.input),
471
574
  output: Math.round(m.output),
575
+ reasoning: Math.round(m.reasoning),
472
576
  cacheRead: Math.round(m.cacheRead),
473
577
  cacheWrite: Math.round(m.cacheWrite),
474
578
  cost: m.cost,
@@ -476,46 +580,41 @@ function getStatsFromDb(days) {
476
580
  }))
477
581
  .sort((a, b) => b.cost - a.cost);
478
582
 
479
- // Savings estimate: market value of all-time usage at catalog paid rates.
480
- // Basis is session-meta grouping (same rows/basis as the report providers
481
- // table) so the two panels agree; message-level model splits would price
482
- // model-switched sessions differently.
583
+ // Savings estimate: market value of all-time usage at catalog paid rates,
584
+ // priced per MESSAGE model (residual falls back to the session's model) —
585
+ // the same basis as the report providers table.
483
586
  let marketTotal = null, savedTotal = null, priceAsOf = null;
484
587
  {
485
588
  const info = pricing.catalogInfo();
486
589
  if (info.ok) {
487
590
  priceAsOf = new Date(info.mtimeMs).toISOString();
488
591
  marketTotal = 0;
489
- const grows = dbQuery(`SELECT COALESCE(json_extract(model,'$.providerID'),'unknown') AS provider, COALESCE(json_extract(model,'$.id'),'unknown') AS model, SUM(tokens_input) AS i, SUM(tokens_output) AS o, SUM(tokens_reasoning) AS r, SUM(tokens_cache_read) AS cr FROM ${schema.session} GROUP BY provider, model`) || [];
490
- for (const g of grows) {
491
- const mk = marketOf({ input: g.i, output: g.o, reasoning: g.r, cacheRead: g.cr, cost: 0 }, g.provider, g.model);
592
+ for (const [name, m] of Object.entries(attr.perModel)) {
593
+ const { provider, model } = splitModelName(name);
594
+ const mk = marketOf({ input: m.input, output: m.output, reasoning: m.reasoning, cacheRead: m.cacheRead, cost: m.cost }, provider, model);
492
595
  if (mk.market === null) { marketTotal = null; break; }
493
596
  marketTotal += mk.market;
494
597
  }
495
598
  if (marketTotal !== null) {
496
599
  marketTotal = Math.round(marketTotal * 10000) / 10000;
497
- savedTotal = Math.round((marketTotal - (costRow ? costRow.total : 0)) * 10000) / 10000;
600
+ savedTotal = Math.round((marketTotal - T.cost) * 10000) / 10000;
498
601
  } else { savedTotal = null; }
499
602
  }
500
603
  }
501
604
 
502
605
  return {
503
606
  ok: true,
504
- overview: {
505
- sessions: sessions,
506
- messages: msgCount ? (msgCount.messages || 0) : 0,
507
- days: activeDays,
508
- },
607
+ overview: { sessions, messages, days: activeDays },
509
608
  cost: {
510
- total: costRow ? costRow.total : 0,
609
+ total: T.cost,
511
610
  avgDay: avgDayCost,
512
611
  avgTokensSession: Math.round(avgTokens),
513
612
  medianTokensSession: Math.round(medianTokens),
514
- input: costRow ? costRow.input : 0,
515
- output: costRow ? costRow.output : 0,
516
- reasoning: costRow ? costRow.reasoning : 0,
517
- cacheRead: costRow ? costRow.cacheRead : 0,
518
- cacheWrite: costRow ? costRow.cacheWrite : 0,
613
+ input: Math.round(T.input),
614
+ output: Math.round(T.output),
615
+ reasoning: Math.round(T.reasoning),
616
+ cacheRead: Math.round(T.cacheRead),
617
+ cacheWrite: Math.round(T.cacheWrite),
519
618
  marketTotal, savedTotal, priceAsOf,
520
619
  },
521
620
  tools,
@@ -651,19 +750,33 @@ function buildReportFromDb(days) {
651
750
  const startMs = periodStartMs(days, now);
652
751
  const label = days === -1 ? 'All' : days <= 1 ? 'Daily' : days <= 7 ? 'Weekly' : 'Monthly';
653
752
 
654
- // Use ALL-TIME attribution so every session is seen by the same
655
- // attributeUsage call. Then sum only the perDay entries within the
656
- // requested period. This keeps per-day breakdown consistent with the
657
- // trend chart (which also uses the same full attribution).
658
- const a = getAttrAll();
659
- const aNow = attrAllCache.at; // attribution snapshot time: scope message-level stats to it
753
+ // Period-scoped attribution: every number below (summary, providers, agents,
754
+ // sessions, market/saved) is sliced to THIS period, so the tables sum to the
755
+ // card. The all-time buckets (perDay) are still used for the summary totals
756
+ // and stay identical to the trend chart for the same period.
757
+ const a = days === -1 ? getAttrAll() : getAttrPeriod(startMs);
758
+ const aNow = days === -1 ? attrAllCache.at : attrPeriodCache.get(startMs).at; // snapshot time of `a`
660
759
  // Message-level stats per session within the period (period speed + active
661
760
  // time). One GROUP BY over the merged message view, mapped onto the same
662
761
  // session-meta buckets as tokens so row sets stay identical.
762
+ // Wall time must come from the MESSAGE clock, not session.time_updated:
763
+ // subagent/fork sessions are written with time_updated == time_created
764
+ // (same millisecond), which would report ~0 wall for hours of real work.
765
+ // Query the merged message view for the period span per session.
766
+ const wallMs = {};
767
+ for (const m of (dbQuery(`SELECT session_id AS sid, MIN(time_created) AS t0, MAX(COALESCE(CAST(json_extract(data,'$.time.completed') AS INTEGER), time_updated)) AS t1 FROM ${schema.message} WHERE time_created >= ${startMs} AND time_created < ${aNow} GROUP BY session_id`) || [])) {
768
+ wallMs[m.sid] = Math.max(0, (+m.t1 || 0) - (+m.t0 || 0));
769
+ }
663
770
  const msgAgg = {};
664
771
  for (const m of (dbQuery(`SELECT session_id AS sid, COUNT(*) AS n, COALESCE(SUM(CASE WHEN CAST(json_extract(data, '$.tokens.output') AS INTEGER) > 0 AND CAST(json_extract(data, '$.time.completed') AS INTEGER) > CAST(json_extract(data, '$.time.created') AS INTEGER) THEN CAST(json_extract(data, '$.tokens.output') AS INTEGER) ELSE 0 END), 0) AS o, COALESCE(SUM(CASE WHEN CAST(json_extract(data,'$.tokens.output') AS INTEGER) > 0 AND CAST(json_extract(data,'$.time.completed') AS INTEGER) > CAST(json_extract(data,'$.time.created') AS INTEGER) THEN CAST(json_extract(data,'$.tokens.reasoning') AS INTEGER) ELSE 0 END), 0) AS rq, COALESCE(SUM(CASE WHEN CAST(json_extract(data, '$.tokens.output') AS INTEGER) > 0 AND CAST(json_extract(data, '$.time.completed') AS INTEGER) > CAST(json_extract(data, '$.time.created') AS INTEGER) THEN CAST(json_extract(data, '$.time.completed') AS INTEGER) - CAST(json_extract(data, '$.time.created') AS INTEGER) ELSE 0 END), 0) AS ms FROM ${schema.message} WHERE time_created >= ${startMs} AND time_created < ${aNow} GROUP BY sid`) || [])) {
665
772
  msgAgg[m.sid] = m;
666
773
  }
774
+ // Same aggregates per agent — the message layer can name agents that session
775
+ // meta lacks (compaction/plan), so agent speed/active come from messages.
776
+ const msgAgentAgg = {};
777
+ for (const m of (dbQuery(`SELECT COALESCE(json_extract(data,'$.agent'),'unknown') AS agent, COALESCE(SUM(CASE WHEN CAST(json_extract(data,'$.tokens.output') AS INTEGER) > 0 AND CAST(json_extract(data,'$.time.completed') AS INTEGER) > CAST(json_extract(data,'$.time.created') AS INTEGER) THEN CAST(json_extract(data,'$.tokens.output') AS INTEGER) ELSE 0 END),0) AS o, COALESCE(SUM(CASE WHEN CAST(json_extract(data,'$.tokens.output') AS INTEGER) > 0 AND CAST(json_extract(data,'$.time.completed') AS INTEGER) > CAST(json_extract(data,'$.time.created') AS INTEGER) THEN CAST(json_extract(data,'$.time.completed') AS INTEGER) - CAST(json_extract(data,'$.time.created') AS INTEGER) ELSE 0 END),0) AS ms FROM ${schema.message} WHERE time_created >= ${startMs} AND time_created < ${aNow} GROUP BY COALESCE(json_extract(data,'$.agent'),'unknown')`) || [])) {
778
+ msgAgentAgg[m.agent] = { o: m.o, ms: m.ms };
779
+ }
667
780
  const periodDays = {};
668
781
  for (const [key, val] of Object.entries(a.perDay)) {
669
782
  const dayMs = val.date.getTime();
@@ -680,12 +793,11 @@ function buildReportFromDb(days) {
680
793
  }
681
794
  const t = periodTotals;
682
795
  const activeDays = pdVals.length || 1;
683
- // Avg/median over the PERIOD's token-bearing sessions (same session set
684
- // the providers/agents tables are built from) — not all-time, so Daily and
685
- // Weekly reports differ.
796
+ // Avg/median over the PERIOD's token-bearing sessions — period buckets, so
797
+ // Daily/Weekly differ and the value matches the card and the tables.
686
798
  const periodSessionIds = [...periodTotals.sessions];
687
799
  const sessVals = periodSessionIds
688
- .map((sid) => a.perSession[sid])
800
+ .map((sid) => (a.perSessionPeriod || a.perSession)[sid])
689
801
  .filter((s) => s && (s.input > 0 || s.output > 0 || s.reasoning > 0))
690
802
  .map((s) => s.input + s.output + s.reasoning)
691
803
  .filter(Number.isFinite);
@@ -714,50 +826,23 @@ function buildReportFromDb(days) {
714
826
  const metaMap = {};
715
827
  for (const s of sessMeta) metaMap[s.id] = s;
716
828
 
717
- const agentAgg = {};
718
- const modelAgg = {};
719
829
  const sessRows = [];
720
830
  for (const sid of periodSessionIds) {
721
- const ps = a.perSession[sid];
722
- if (!ps) continue;
723
- const meta = metaMap[sid] || { agent: 'unknown', provider: 'unknown', model: 'unknown' };
724
- const agent = meta.agent || 'unknown';
725
- const modelName = `${meta.provider}/${meta.model}`;
726
- if (!agentAgg[agent]) agentAgg[agent] = { sessions: new Set(), cost: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, speedOut: 0, speedMs: 0, wallMs: 0, activeMs: 0, market: 0, saved: 0 };
727
- agentAgg[agent].sessions.add(sid);
728
- agentAgg[agent].input += ps.input; agentAgg[agent].output += ps.output;
729
- agentAgg[agent].reasoning += ps.reasoning; agentAgg[agent].cacheRead += ps.cacheRead;
730
- agentAgg[agent].cost += ps.cost;
831
+ const meta = metaMap[sid] || { agent: 'unknown', provider: 'unknown', model: 'unknown', tc: 0, tu: 0 };
731
832
  const mg = msgAgg[sid] || { n: 0, o: 0, ms: 0, rq: 0 };
732
- agentAgg[agent].speedOut += mg.o; agentAgg[agent].speedMs += mg.ms; agentAgg[agent].activeMs += mg.ms;
733
- agentAgg[agent].wallMs += Math.max(0, (meta.tu || 0) - (meta.tc || 0));
734
- const mkA = marketOf({ input: ps.input, output: ps.output, reasoning: ps.reasoning, cacheRead: ps.cacheRead, cost: ps.cost }, meta.provider || 'unknown', meta.model || 'unknown');
735
- if (mkA.market !== null) { agentAgg[agent].market += mkA.market; agentAgg[agent].saved += mkA.saved; }
736
- if (!modelAgg[modelName]) modelAgg[modelName] = { sessions: new Set(), cost: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, speedOut: 0, speedMs: 0 };
737
- modelAgg[modelName].sessions.add(sid);
738
- modelAgg[modelName].input += ps.input; modelAgg[modelName].output += ps.output;
739
- modelAgg[modelName].reasoning += ps.reasoning; modelAgg[modelName].cacheRead += ps.cacheRead;
740
- modelAgg[modelName].cost += ps.cost;
741
- modelAgg[modelName].speedOut += mg.o; modelAgg[modelName].speedMs += mg.ms;
742
- sessRows.push({ sid, meta, ps, mg });
833
+ const sm = (a.perSessionModelPeriod && a.perSessionModelPeriod[sid]) || null;
834
+ sessRows.push({ sid, meta, ps: a.perSessionPeriod ? a.perSessionPeriod[sid] : a.perSession[sid], mg, sm });
743
835
  }
744
836
 
745
- var pAgentRows = Object.entries(agentAgg)
746
- .map(([agent, m]) => ({
747
- agent, sessions: m.sessions.size, cost: r4(m.cost),
748
- tok_in: Math.round(m.input), tok_out: Math.round(m.output),
749
- tok_reasoning: Math.round(m.reasoning), cache_read: Math.round(m.cacheRead),
750
- speed: m.speedMs > 0 ? Math.round((m.speedOut / (m.speedMs / 1000)) * 10) / 10 : null,
751
- wallMs: Math.round(m.wallMs), activeMs: Math.round(m.activeMs),
752
- market: Math.round(m.market * 10000) / 10000, saved: Math.round(m.saved * 10000) / 10000,
753
- }))
754
- .sort((x, y) => y.cost - x.cost);
755
- var pProviderRows = Object.entries(modelAgg)
837
+ // Providers/agents come straight from the period buckets (message tokens
838
+ // under the message's own model; residual under the session's), so their
839
+ // columns sum EXACTLY to the summary card by construction.
840
+ var pProviderRows = Object.entries(a.perModelPeriod)
756
841
  .map(([name, m]) => {
757
842
  const { provider, model } = splitModelName(name);
758
843
  const mk = marketOf({ input: m.input, output: m.output, reasoning: m.reasoning, cacheRead: m.cacheRead, cost: m.cost }, provider, model);
759
844
  return {
760
- provider, model, sessions: m.sessions.size, cost: r4(m.cost),
845
+ provider, model, sessions: m.sessions.size, messages: m.messages, cost: r4(m.cost),
761
846
  tok_in: Math.round(m.input), tok_out: Math.round(m.output),
762
847
  tok_reasoning: Math.round(m.reasoning), cache_read: Math.round(m.cacheRead),
763
848
  speed: m.speedMs > 0 ? Math.round((m.speedOut / (m.speedMs / 1000)) * 10) / 10 : null,
@@ -765,22 +850,65 @@ function buildReportFromDb(days) {
765
850
  };
766
851
  })
767
852
  .sort((x, y) => y.cost - x.cost);
853
+
854
+ var pAgentRows = Object.entries(a.perAgentPeriod)
855
+ .map(([agent, m]) => {
856
+ let market = 0, saved = 0, priced = false;
857
+ const bag = (a.perAgentModelPeriod && a.perAgentModelPeriod[agent]) || {};
858
+ for (const [name, b] of Object.entries(bag)) {
859
+ const { provider, model } = splitModelName(name);
860
+ const mk = marketOf({ input: b.input, output: b.output, reasoning: b.reasoning, cacheRead: b.cacheRead, cost: b.cost }, provider, model);
861
+ if (mk.market === null) { market = null; break; }
862
+ market += mk.market; saved += mk.saved; priced = true;
863
+ }
864
+ // Wall = period span measured on the message clock (see wallMs above).
865
+ let agentWall = 0;
866
+ for (const sid of m.sessions) agentWall += wallMs[sid] || 0;
867
+ return {
868
+ agent, sessions: m.sessions.size, cost: r4(m.cost),
869
+ tok_in: Math.round(m.input), tok_out: Math.round(m.output),
870
+ tok_reasoning: Math.round(m.reasoning), cache_read: Math.round(m.cacheRead),
871
+ speed: msgAgentAgg[agent] && msgAgentAgg[agent].ms > 0 ? Math.round((msgAgentAgg[agent].o / (msgAgentAgg[agent].ms / 1000)) * 10) / 10 : null,
872
+ wallMs: Math.round(agentWall),
873
+ activeMs: msgAgentAgg[agent] ? Math.round(msgAgentAgg[agent].ms) : 0,
874
+ market: market === null ? null : Math.round(market * 10000) / 10000,
875
+ saved: market === null ? null : Math.round(saved * 10000) / 10000,
876
+ pricedAs: priced,
877
+ };
878
+ })
879
+ .sort((x, y) => y.cost - x.cost);
768
880
  var pSessionRows = sessRows
769
- .map(({ sid, meta, ps, mg }) => {
770
- const mkS = marketOf({ input: ps.input, output: ps.output, reasoning: mg.rq || 0, cacheRead: ps.cacheRead, cost: ps.cost }, meta.provider || 'unknown', meta.model || 'unknown');
881
+ .map(({ sid, meta, ps, mg, sm }) => {
882
+ // Price by the session's own period model mix when available
883
+ // (message tokens under the message's model), else the session's meta
884
+ // model (residual-only sessions).
885
+ let market = null, saved = null, pricedAs = null, prov = meta.provider || 'unknown', mod = meta.model || 'unknown';
886
+ const bag = sm || null;
887
+ if (bag && Object.keys(bag).length) {
888
+ const name = Object.keys(bag).sort((a, b) => {
889
+ const va = bag[a].input + bag[a].output + bag[a].cacheRead;
890
+ const vb = bag[b].input + bag[b].output + bag[b].cacheRead;
891
+ return vb - va;
892
+ })[0];
893
+ const sp = splitModelName(name);
894
+ prov = sp.provider; mod = sp.model;
895
+ }
896
+ const mkS = marketOf({ input: ps.input, output: ps.output, reasoning: mg.rq || 0, cacheRead: ps.cacheRead, cost: ps.cost }, prov, mod);
897
+ market = mkS.market; saved = mkS.saved; pricedAs = mkS.pricedAs;
898
+ // Wall from the message clock (see wallMs above).
771
899
  return {
772
- id: sid, title: (meta.title || '').slice(0, 40), agent: meta.agent || 'unknown',
773
- provider: meta.provider || 'unknown', model: meta.model || 'unknown',
774
- wallMs: Math.max(0, (meta.tu || 0) - (meta.tc || 0)),
775
- activeMs: mg.ms || 0, messages: mg.n || 0,
776
- tok_in: Math.round(ps.input), tok_out: Math.round(ps.output),
777
- tok_reasoning: Math.round(mg.rq || 0),
778
- cost: r4(ps.cost),
779
- speed: (mg.ms || 0) > 0 ? Math.round(((mg.o || 0) / (mg.ms / 1000)) * 10) / 10 : null,
780
- market: mkS.market, saved: mkS.saved, pricedAs: mkS.pricedAs,
900
+ id: sid, title: (meta.title || '').slice(0, 40), agent: meta.agent || 'unknown',
901
+ provider: prov, model: mod,
902
+ wallMs: wallMs[sid] || 0,
903
+ activeMs: mg.ms || 0, messages: mg.n || 0,
904
+ tok_in: Math.round(ps.input), tok_out: Math.round(ps.output),
905
+ tok_reasoning: Math.round(mg.rq || 0),
906
+ cost: r4(ps.cost),
907
+ speed: (mg.ms || 0) > 0 ? Math.round(((mg.o || 0) / (mg.ms / 1000)) * 10) / 10 : null,
908
+ market, saved, pricedAs,
781
909
  };
782
910
  })
783
- .sort((x, y) => y.wallMs - x.wallMs)
911
+ .sort((x, y) => y.activeMs - x.activeMs)
784
912
  .slice(0, 20);
785
913
  } else {
786
914
  var pAgentRows = [];
@@ -788,9 +916,12 @@ function buildReportFromDb(days) {
788
916
  var pSessionRows = [];
789
917
  }
790
918
 
919
+ // Period market = Σ provider rows (already period-scoped); saved = Σ provider
920
+ // saved so it can never mix a period cost with a lifetime market.
791
921
  const sumMkt = (rows) => rows.reduce((s, r) => s + (r.market || 0), 0);
922
+ const sumSaved = (rows) => rows.reduce((s, r) => s + (r.saved || 0), 0);
792
923
  statsR.cost.marketTotal = Math.round(sumMkt(pProviderRows) * 10000) / 10000;
793
- statsR.cost.savedTotal = Math.round((sumMkt(pProviderRows) - t.cost) * 10000) / 10000;
924
+ statsR.cost.savedTotal = Math.round(sumSaved(pProviderRows) * 10000) / 10000;
794
925
  statsR.cost.savedPct = statsR.cost.marketTotal > 0 ? Math.round((statsR.cost.savedTotal / statsR.cost.marketTotal) * 1000) / 10 : null;
795
926
  statsR.cost.priceAsOf = pricing.catalogInfo().ok ? new Date(pricing.catalogInfo().mtimeMs).toISOString() : null;
796
927
 
@@ -813,13 +944,16 @@ function refreshReport(days) {
813
944
  if (fresh) return { report: hit, ready: true };
814
945
  if (!reportBusy[key]) {
815
946
  reportBusy[key] = true;
816
- try {
817
- const r = buildReportFromDb(days);
818
- if (r && r.stats && r.stats.ok) {
819
- reportCache[key] = r;
947
+ setImmediate(() => {
948
+ try {
949
+ const r = buildReportFromDb(days);
950
+ if (r && r.stats && r.stats.ok) {
951
+ reportCache[key] = r;
952
+ }
953
+ } catch (_) {} finally {
954
+ delete reportBusy[key];
820
955
  }
821
- } catch (_) {}
822
- delete reportBusy[key];
956
+ });
823
957
  }
824
958
  return hit ? { report: Object.assign({}, hit, { stale: true }), ready: true } : { report: null, ready: false };
825
959
  }
@@ -838,7 +972,7 @@ const server = http.createServer(async (req, res) => {
838
972
  for (const [k, v] of Object.entries(headers)) res.setHeader(k, v);
839
973
  if (useGzip && payload.length > 512) {
840
974
  res.setHeader('Content-Encoding', 'gzip');
841
- const compressed = zlib.gzipSync(Buffer.from(payload), { level: 6 });
975
+ const compressed = zlib.gzipSync(Buffer.from(payload), { level: 1 });
842
976
  res.end(compressed);
843
977
  } else {
844
978
  res.end(payload);
@@ -940,6 +1074,7 @@ const server = http.createServer(async (req, res) => {
940
1074
  return;
941
1075
  }
942
1076
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
1077
+ res.setHeader('Cache-Control', 'no-store');
943
1078
  res.end(data.replace('__VERSION__', VERSION));
944
1079
  });
945
1080
  } else {