opencode-statboard 2.2.0 → 2.3.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/AGENTS.md CHANGED
@@ -42,6 +42,7 @@ Token/cost attribution uses a hybrid model:
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
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).
45
46
 
46
47
  This ensures multi-day sessions (e.g. a session created Monday, updated Thursday) don't dump all tokens onto Thursday.
47
48
 
package/README.md CHANGED
@@ -9,7 +9,9 @@ Real-time dashboard for your [opencode](https://opencode.ai) token usage and cos
9
9
  - Tool usage breakdown with percentage bars (collapsible)
10
10
  - Per-model usage with cache read stats and generation speed (output tok/s)
11
11
  - Usage reports: per-agent speed, wall/active time, and top-20 sessions by duration
12
+ - Savings estimate: market value at paid catalog rates vs actual cost (per-model, per-report, overview cards)
12
13
  - Visual charts for model speed, agent wall/active time, and longest sessions
14
+ - Collapsible sections (collapse state remembered in browser)
13
15
  - Daily trend chart (7D / 30D / 90D)
14
16
  - Usage reports: Daily / Weekly / Monthly / All time
15
17
  - i18n: English + Traditional Chinese, auto-detects browser language
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-statboard",
3
- "version": "2.2.0",
3
+ "version": "2.3.0",
4
4
  "description": "Real-time dashboard for opencode token usage and cost statistics",
5
5
  "main": "server.js",
6
6
  "bin": {
@@ -8,7 +8,7 @@
8
8
  },
9
9
  "scripts": {
10
10
  "start": "node server.js",
11
- "test": "node --check server.js && node --check check-lib.js && node --check check-stats-verify.js && node --check check-trend-verify.js && node --check check-report-verify.js && node --check check-frontend-smoke.js"
11
+ "test": "node --check server.js && node --check check-lib.js && node --check pricing.js && node --check check-stats-verify.js && node --check check-trend-verify.js && node --check check-report-verify.js && node --check check-frontend-smoke.js"
12
12
  },
13
13
  "keywords": [
14
14
  "opencode",
package/pricing.js ADDED
@@ -0,0 +1,94 @@
1
+ // Shared market-price engine for the "how much did I save" feature.
2
+ // Pricing comes from the user's local opencode models catalog
3
+ // (~/.cache/opencode/models.json):
4
+ // { provider: { models: { name: { cost: { input, output, cache_read } } } } }
5
+ // in USD per 1M tokens. Free variants (cost 0) are mapped to a paid basis:
6
+ // 1. exact provider/model with nonzero cost
7
+ // 2. strip -free / -contributor-free suffix, same provider, nonzero cost
8
+ // 3. same base name under provider 'opencode', nonzero cost
9
+ // 4. same base name under any provider (sorted, first nonzero)
10
+ // 5. proxy fallback: opencode/deepseek-v4-flash rates (marked "proxy:")
11
+ // Reasoning tokens have no catalog rate and are billed at the output rate.
12
+ // cache_write is always 0 in the DB and contributes nothing.
13
+ const fs = require('fs');
14
+ const path = require('path');
15
+
16
+ function catalogCandidates() {
17
+ const homes = [process.env.USERPROFILE, process.env.HOME].filter(Boolean);
18
+ const out = [];
19
+ for (const h of homes) out.push(path.join(h, '.cache', 'opencode', 'models.json'));
20
+ return [...new Set(out)];
21
+ }
22
+
23
+ let cache = { mtimeMs: 0, data: null, path: null };
24
+
25
+ function loadCatalog() {
26
+ for (const p of catalogCandidates()) {
27
+ try {
28
+ const st = fs.statSync(p);
29
+ if (cache.data && cache.path === p && cache.mtimeMs === st.mtimeMs) return cache;
30
+ const data = JSON.parse(fs.readFileSync(p, 'utf8'));
31
+ cache = { mtimeMs: st.mtimeMs, data, path: p };
32
+ return cache;
33
+ } catch (_) { /* try next candidate */ }
34
+ }
35
+ cache = { mtimeMs: 0, data: null, path: null };
36
+ return cache;
37
+ }
38
+
39
+ function nonzero(cost) {
40
+ if (!cost) return false;
41
+ return (cost.input || 0) > 0 || (cost.output || 0) > 0 || (cost.cache_read || 0) > 0;
42
+ }
43
+
44
+ function ratesOf(data, provider, model) {
45
+ const cost = data[provider] && data[provider].models && data[provider].models[model] && data[provider].models[model].cost;
46
+ if (!nonzero(cost)) return null;
47
+ return { input: cost.input || 0, output: cost.output || 0, cacheRead: cost.cache_read || 0, source: `${provider}/${model}` };
48
+ }
49
+
50
+ // Map a usage model (provider/model as seen in the DB) to paid rates.
51
+ // Returns { input, output, cacheRead, source, exact } or null when no catalog.
52
+ function priceFor(provider, model) {
53
+ const cat = loadCatalog();
54
+ if (!cat.data) return null;
55
+ const data = cat.data;
56
+ provider = provider || 'unknown';
57
+ model = model || 'unknown';
58
+ let r = ratesOf(data, provider, model);
59
+ if (r) return { ...r, exact: true };
60
+ if (model === 'unknown') {
61
+ const fb = ratesOf(data, 'opencode', 'deepseek-v4-flash');
62
+ return fb ? { ...fb, source: 'proxy:opencode/deepseek-v4-flash', exact: false } : null;
63
+ }
64
+ const base = String(model).replace(/-contributor-free$/, '').replace(/-free$/, '');
65
+ const cands = [];
66
+ if (base !== model) cands.push([provider, base]);
67
+ cands.push(['opencode', base]);
68
+ for (const pid of Object.keys(data).sort()) {
69
+ if (pid !== provider && pid !== 'opencode') cands.push([pid, base]);
70
+ }
71
+ for (const [p, m] of cands) {
72
+ r = ratesOf(data, p, m);
73
+ if (r) return { ...r, exact: false };
74
+ }
75
+ const fb = ratesOf(data, 'opencode', 'deepseek-v4-flash');
76
+ return fb ? { ...fb, source: 'proxy:opencode/deepseek-v4-flash', exact: false } : null;
77
+ }
78
+
79
+ // Market value (USD) of token usage at the given rates.
80
+ function marketOf(tok, rates) {
81
+ if (!rates) return null;
82
+ const m = (tok.input || 0) / 1e6 * rates.input
83
+ + (tok.output || 0) / 1e6 * rates.output
84
+ + (tok.reasoning || 0) / 1e6 * rates.output
85
+ + (tok.cacheRead || 0) / 1e6 * rates.cacheRead;
86
+ return Math.round(m * 10000) / 10000;
87
+ }
88
+
89
+ function catalogInfo() {
90
+ const cat = loadCatalog();
91
+ return cat.data ? { ok: true, path: cat.path, mtimeMs: cat.mtimeMs } : { ok: false };
92
+ }
93
+
94
+ module.exports = { priceFor, marketOf, catalogInfo };
package/public/index.html CHANGED
@@ -90,21 +90,23 @@
90
90
 
91
91
  <div class="error-banner" id="errbanner"></div>
92
92
 
93
- <section>
94
- <h2 data-i18n="overview">OVERVIEW</h2>
93
+ <details class="tool-section" open id="sec-overview">
94
+ <summary><h2 data-i18n="overview">OVERVIEW</h2></summary>
95
95
  <div class="cards">
96
96
  <div class="card"><div class="l" data-i18n="sessions">Sessions</div><div class="v" id="ov-sessions">—</div></div>
97
97
  <div class="card"><div class="l" data-i18n="messages">Messages</div><div class="v" id="ov-messages">—</div></div>
98
98
  <div class="card"><div class="l" data-i18n="days">Days</div><div class="v" id="ov-days">—</div></div>
99
99
  <div class="card"><div class="l" data-i18n="totalCost">Total Cost</div><div class="v" id="ov-total">—</div></div>
100
+ <div class="card"><div class="l" data-i18n="marketValue">Market Value</div><div class="v" id="ov-market">—</div></div>
101
+ <div class="card"><div class="l" data-i18n="saved">Saved</div><div class="v" id="ov-saved">—</div></div>
100
102
  <div class="card"><div class="l" data-i18n="avgCostDay">Avg Cost / Day</div><div class="v" id="ov-avgday">—</div></div>
101
103
  <div class="card"><div class="l" data-i18n="avgTokensSession">Avg Tokens / Session</div><div class="v" id="ov-avg">—</div></div>
102
104
  <div class="card"><div class="l" data-i18n="medianTokensSession">Median Tokens / Session</div><div class="v" id="ov-med">—</div></div>
103
105
  </div>
104
- </section>
106
+ </details>
105
107
 
106
- <section>
107
- <h2 data-i18n="tokenStats">TOKEN STATISTICS</h2>
108
+ <details class="tool-section" open id="sec-tokens">
109
+ <summary><h2 data-i18n="tokenStats">TOKEN STATISTICS</h2></summary>
108
110
  <div class="legend">
109
111
  <span><i class="sw" style="background:var(--in)"></i>Input</span>
110
112
  <span><i class="sw" style="background:var(--out)"></i>Output</span>
@@ -113,32 +115,32 @@
113
115
  <span><i class="sw" style="background:var(--cost)"></i>Cache Write</span>
114
116
  </div>
115
117
  <div id="token-bars"></div>
116
- </section>
118
+ </details>
117
119
 
118
- <details class="tool-section" open>
120
+ <details class="tool-section" open id="sec-tools">
119
121
  <summary><h2 data-i18n="toolUsage">TOOL USAGE</h2></summary>
120
122
  <div id="tool-bars"></div>
121
123
  </details>
122
124
 
123
- <section>
124
- <h2 data-i18n="modelUsage">MODEL USAGE</h2>
125
+ <details class="tool-section" open id="sec-models">
126
+ <summary><h2 data-i18n="modelUsage">MODEL USAGE</h2></summary>
125
127
  <table>
126
128
  <thead>
127
129
  <tr><th data-i18n="thModel">Model</th><th data-i18n="thMsgs">Messages</th><th>Input</th><th>Output</th><th>Cache Read</th><th data-i18n="thSpeed">Speed</th><th style="width:26%" data-i18n="thUsage">Usage</th><th data-i18n="thCost">Cost</th></tr>
128
130
  </thead>
129
131
  <tbody id="model-rows"></tbody>
130
132
  </table>
131
- </section>
133
+ </details>
132
134
 
133
- <section>
134
- <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px">
135
+ <details class="tool-section" open id="sec-trend">
136
+ <summary><div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px">
135
137
  <h2 id="trendTitle" style="margin:0"></h2>
136
138
  <div class="range-btns" id="rangeBtns">
137
139
  <span class="pill active" data-days="7" onclick="setRange(7)">7D</span>
138
140
  <span class="pill" data-days="30" onclick="setRange(30)">30D</span>
139
141
  <span class="pill" data-days="90" onclick="setRange(90)">90D</span>
140
142
  </div>
141
- </div>
143
+ </div></summary>
142
144
  <div style="display:flex;gap:24px;flex-wrap:wrap">
143
145
  <div style="flex:1;min-width:300px">
144
146
  <div class="legend">
@@ -158,10 +160,10 @@
158
160
  <div id="costZeroNote" style="display:none;font-size:12px;color:var(--muted);padding:20px 0;text-align:center"></div>
159
161
  </div>
160
162
  </div>
161
- </section>
163
+ </details>
162
164
 
163
- <section>
164
- <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px">
165
+ <details class="tool-section" open id="sec-report">
166
+ <summary><div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px">
165
167
  <h2 data-i18n="report" style="margin:0">USAGE REPORT</h2>
166
168
  <div class="range-btns" id="reportBtns">
167
169
  <span class="pill" data-days="-1" onclick="loadReport(-1)" data-i18n="all">All</span>
@@ -169,32 +171,40 @@
169
171
  <span class="pill" data-days="7" onclick="loadReport(7)" data-i18n="weekly">Weekly</span>
170
172
  <span class="pill" data-days="30" onclick="loadReport(30)" data-i18n="monthly">Monthly</span>
171
173
  </div>
172
- </div>
174
+ </div></summary>
173
175
  <div id="reportContent" style="font-family:monospace;font-size:13px;line-height:1.6;white-space:pre;overflow-x:auto;color:var(--text)">Loading…</div>
174
- </section>
176
+ </details>
175
177
 
176
- <section>
177
- <h2 data-i18n="modelSpeed">MODEL SPEED</h2>
178
+ <details class="tool-section" open id="sec-speed">
179
+ <summary><h2 data-i18n="modelSpeed">MODEL SPEED</h2></summary>
178
180
  <div id="speed-bars"></div>
179
- </section>
181
+ </details>
180
182
 
181
- <section>
182
- <h2 data-i18n="agentTime">AGENT TIME</h2>
183
+ <details class="tool-section" open id="sec-agent">
184
+ <summary><h2 data-i18n="agentTime">AGENT TIME</h2></summary>
183
185
  <div class="legend">
184
186
  <span><i class="sw" style="background:var(--cache)"></i>wall</span>
185
187
  <span><i class="sw" style="background:var(--out)"></i>active</span>
186
188
  </div>
187
189
  <div id="agent-bars"></div>
188
- </section>
190
+ </details>
189
191
 
190
- <section>
191
- <h2 data-i18n="topSessions">TOP SESSIONS</h2>
192
+ <details class="tool-section" open id="sec-sessions">
193
+ <summary><h2 data-i18n="topSessions">TOP SESSIONS</h2></summary>
192
194
  <div class="legend">
193
195
  <span><i class="sw" style="background:var(--cache)"></i>wall</span>
194
196
  <span><i class="sw" style="background:var(--out)"></i>active</span>
195
197
  </div>
196
198
  <div id="session-bars"></div>
197
- </section>
199
+ </details>
200
+
201
+ <details class="tool-section" open id="sec-savings">
202
+ <summary><h2 data-i18n="savings">SAVINGS</h2></summary>
203
+ <div class="legend">
204
+ <span><i class="sw" style="background:var(--cost)"></i>market value</span>
205
+ </div>
206
+ <div id="savings-bars"></div>
207
+ </details>
198
208
 
199
209
  <script>
200
210
  const STRINGS = {
@@ -203,7 +213,7 @@ const STRINGS = {
203
213
  overview: 'OVERVIEW',
204
214
  sessions: 'Sessions', messages: 'Messages', days: 'Days',
205
215
  totalCost: 'Total Cost', avgCostDay: 'Avg Cost / Day',
206
- avgTokensSession: 'Avg Tokens / Session', medianTokensSession: 'Median Tokens / Session',
216
+ avgTokensSession: 'Avg Tokens / Session', medianTokensSession: 'Median Tokens / Session', marketValue: 'Market Value', saved: 'Saved', savings: 'SAVINGS',
207
217
  tokenStats: 'TOKEN STATISTICS', toolUsage: 'TOOL USAGE', modelUsage: 'MODEL USAGE',
208
218
  thModel: 'Model', thMsgs: 'Messages', thSpeed: 'Speed', thUsage: 'Usage', thCost: 'Cost',
209
219
  dailyTrend: 'DAILY TREND ({days} DAYS)',
@@ -220,7 +230,7 @@ const STRINGS = {
220
230
  overview: '概覽',
221
231
  sessions: '工作階段', messages: '訊息數', days: '使用天數',
222
232
  totalCost: '總費用', avgCostDay: '平均費用 / 天',
223
- avgTokensSession: '平均 tokens / 場', medianTokensSession: '中位數 tokens / 場',
233
+ avgTokensSession: '平均 tokens / 場', medianTokensSession: '中位數 tokens / 場', marketValue: '市價', saved: '已節省', savings: '節省金額',
224
234
  tokenStats: 'Tokens 統計', toolUsage: '工具使用', modelUsage: '模型使用',
225
235
  thModel: '模型', thMsgs: '訊息', thSpeed: '速度', thUsage: '用量', thCost: '費用',
226
236
  dailyTrend: '近 {days} 天趨勢',
@@ -249,6 +259,20 @@ function applyI18n() {
249
259
  $('trendTitle').textContent = t('dailyTrend').replace('{days}', currentDays);
250
260
  }
251
261
 
262
+ function restoreSections() {
263
+ document.querySelectorAll('#rangeBtns .pill, #reportBtns .pill').forEach((el) => {
264
+ el.addEventListener('click', (e) => e.stopPropagation());
265
+ });
266
+ document.querySelectorAll('details.tool-section[id]').forEach((el) => {
267
+ try {
268
+ if (localStorage.getItem('oc-sec-' + el.id) === '0') el.removeAttribute('open');
269
+ el.addEventListener('toggle', () => {
270
+ try { localStorage.setItem('oc-sec-' + el.id, el.open ? '1' : '0'); } catch (_) {}
271
+ });
272
+ } catch (_) {}
273
+ });
274
+ }
275
+
252
276
  function toggleLang() {
253
277
  lang = lang === 'en' ? 'zh-TW' : 'en';
254
278
  localStorage.setItem('lang', lang);
@@ -305,6 +329,8 @@ function render(d, models, trend) {
305
329
  $('ov-messages').textContent = fmt(o.messages);
306
330
  $('ov-days').textContent = fmt(o.days);
307
331
  $('ov-total').textContent = fmtCost(d.cost && d.cost.total);
332
+ $('ov-market').textContent = fmtCost(d.cost && d.cost.marketTotal);
333
+ $('ov-saved').textContent = fmtCost(d.cost && d.cost.savedTotal);
308
334
  $('ov-avgday').textContent = fmtCost(d.cost && d.cost.avgDay);
309
335
  $('ov-avg').textContent = fmt(d.cost && d.cost.avgTokensSession);
310
336
  $('ov-med').textContent = fmt(d.cost && d.cost.medianTokensSession);
@@ -506,6 +532,17 @@ function renderReportCharts(r) {
506
532
  fmtDur(s.wallMs) + ' · ' + fmtSpeed(s.speed),
507
533
  (s.title || '') + ' · ' + s.agent + ' · ' + s.provider + '/' + s.model + ' · ' + (s.messages || 0) + ' msgs')
508
534
  ).join('') : '<div class="val">—</div>';
535
+
536
+ const mkt = (r.providers || []).slice().sort((a, b) => (b.market || 0) - (a.market || 0));
537
+ const mmax = Math.max(0, ...mkt.map((p) => p.market || 0));
538
+ $('savings-bars').innerHTML = mkt.length ? mkt.map((p) => {
539
+ const pct = mmax > 0 ? Math.max(0.5, ((p.market || 0) / mmax) * 100) : 0;
540
+ const sv = p.saved == null ? '—' : fmtCost(p.saved) + ' saved';
541
+ 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>
543
+ <div class="track"><div class="fill" style="width:${pct}%;background:var(--cost)"></div></div>
544
+ <div class="val" title="${esc(tip)}">${sv}</div></div>`;
545
+ }).join('') : '<div class="val">—</div>';
509
546
  }
510
547
 
511
548
  function formatReport(jr) {
@@ -531,25 +568,35 @@ function formatReport(jr) {
531
568
  out += ' Tokens In/Out ...... ' + fmtT(c.input) + ' / ' + fmtT(c.output) + '\n';
532
569
  out += ' Tokens Reasoning ... ' + fmtT(c.reasoning) + '\n';
533
570
  out += ' Cache Read/Write ... ' + fmtT(c.cacheRead) + ' / ' + fmtT(c.cacheWrite) + '\n';
571
+ out += ' Market value ..... ' + (c.marketTotal == null ? '—' : '$' + c.marketTotal.toFixed(2)) + '\n';
572
+ out += ' Saved ............ ' + (c.savedTotal == null ? '—' : '$' + c.savedTotal.toFixed(2)) + (c.marketTotal > 0 && c.savedPct != null ? ' (' + c.savedPct + '%)' : '') + '\n';
534
573
  out += '\n';
535
574
  }
536
575
  if (jr.providers && jr.providers.length) {
537
576
  out += 'PROVIDERS & MODELS\n';
538
577
  jr.providers.forEach((p) => {
539
- out += ' ' + pad(p.provider + '/' + p.model, 45) + pad(p.sessions + ' sessions', 14) + ' ' + rpad(fmtCost(p.cost), 10) + ' ' + rpad(fmtT(p.tok_in), 8) + ' in / ' + rpad(fmtT(p.tok_out), 8) + ' out cache: ' + rpad(fmtT(p.cache_read), 8) + ' ' + rpad(fmtSpeed(p.speed), 11) + '\n';
578
+ out += ' ' + pad(p.provider + '/' + p.model, 45) + pad(p.sessions + ' sessions', 14) + ' ' + rpad(fmtCost(p.cost), 10) + ' ' + rpad(fmtT(p.tok_in), 8) + ' in / ' + rpad(fmtT(p.tok_out), 8) + ' out cache: ' + rpad(fmtT(p.cache_read), 8) + ' ' + rpad(fmtSpeed(p.speed), 11) + ' mkt:' + rpad(fmtCost(p.market), 11) + ' svd:' + rpad(fmtCost(p.saved), 11) + '\n';
540
579
  });
541
580
  out += '\n';
581
+ const basis = (jr.providers || []).filter((p) => p.pricedAs && p.pricedAs !== (p.provider + '/' + p.model));
582
+ if (basis.length) {
583
+ out += 'PRICING (free → paid basis' + (jr.priceAsOf ? ', prices as of ' + jr.priceAsOf.slice(0, 10) : '') + ')\n';
584
+ basis.forEach((p) => {
585
+ out += ' ' + pad(p.provider + '/' + p.model, 45) + '→ ' + p.pricedAs + '\n';
586
+ });
587
+ out += '\n';
588
+ }
542
589
  }
543
590
  if (jr.agents && jr.agents.length) {
544
591
  out += 'AGENTS\n';
545
592
  jr.agents.forEach((a) => {
546
- out += ' ' + pad(a.agent, 45) + pad(a.sessions + ' sessions', 14) + ' ' + rpad(fmtCost(a.cost), 10) + ' ' + rpad(fmtT(a.tok_in), 8) + ' in / ' + rpad(fmtT(a.tok_out), 8) + ' out cache: ' + rpad(fmtT(a.cache_read), 8) + ' ' + rpad(fmtSpeed(a.speed), 11) + ' wall:' + rpad(fmtDur(a.wallMs), 9) + 'act:' + rpad(fmtDur(a.activeMs), 9) + '\n';
593
+ out += ' ' + pad(a.agent, 45) + pad(a.sessions + ' sessions', 14) + ' ' + rpad(fmtCost(a.cost), 10) + ' ' + rpad(fmtT(a.tok_in), 8) + ' in / ' + rpad(fmtT(a.tok_out), 8) + ' out cache: ' + rpad(fmtT(a.cache_read), 8) + ' ' + rpad(fmtSpeed(a.speed), 11) + ' wall:' + rpad(fmtDur(a.wallMs), 9) + 'act:' + rpad(fmtDur(a.activeMs), 9) + ' mkt:' + rpad(fmtCost(a.market), 11) + ' svd:' + rpad(fmtCost(a.saved), 11) + '\n';
547
594
  });
548
595
  }
549
596
  if (jr.sessions && jr.sessions.length) {
550
597
  out += 'SESSIONS (top ' + jr.sessions.length + ' by wall time)\n';
551
598
  jr.sessions.forEach((s) => {
552
- out += ' ' + pad(String(s.id).slice(0, 12), 13) + pad((s.title || '').slice(0, 28), 29) + pad(s.agent, 9) + pad((s.provider + '/' + s.model).slice(0, 30), 31) + 'wall:' + rpad(fmtDur(s.wallMs), 9) + 'act:' + rpad(fmtDur(s.activeMs), 9) + rpad(s.messages + 'msgs', 8) + rpad(fmtT(s.tok_in), 8) + ' in / ' + rpad(fmtT(s.tok_out), 8) + ' out ' + rpad(fmtSpeed(s.speed), 11) + ' ' + rpad(fmtCost(s.cost), 10) + '\n';
599
+ out += ' ' + pad(String(s.id).slice(0, 12), 13) + pad((s.title || '').slice(0, 28), 29) + pad(s.agent, 9) + pad((s.provider + '/' + s.model).slice(0, 30), 31) + 'wall:' + rpad(fmtDur(s.wallMs), 9) + 'act:' + rpad(fmtDur(s.activeMs), 9) + rpad(s.messages + 'msgs', 8) + rpad(fmtT(s.tok_in), 8) + ' in / ' + rpad(fmtT(s.tok_out), 8) + ' out ' + rpad(fmtSpeed(s.speed), 11) + ' ' + rpad(fmtCost(s.cost), 10) + ' mkt:' + rpad(fmtCost(s.market), 11) + ' svd:' + rpad(fmtCost(s.saved), 11) + '\n';
553
600
  });
554
601
  out += '\n';
555
602
  }
@@ -586,6 +633,7 @@ async function loadReport(days) {
586
633
  }
587
634
 
588
635
  applyI18n();
636
+ restoreSections();
589
637
  poll();
590
638
  setInterval(poll, 15000);
591
639
  loadReport(1);
package/server.js CHANGED
@@ -10,6 +10,7 @@ const pipelineAsync = promisify(pipeline);
10
10
 
11
11
  let Database;
12
12
  try { Database = require('better-sqlite3'); } catch (_) { Database = null; }
13
+ const pricing = require('./pricing');
13
14
 
14
15
  const PORT = parseInt(process.env.OC_PORT || '4868', 10);
15
16
  const REFRESH_MS = 15000;
@@ -276,6 +277,18 @@ function splitModelName(name) {
276
277
  return i < 0 ? { provider: 'unknown', model: String(name) } : { provider: String(name).slice(0, i), model: String(name).slice(i + 1) };
277
278
  }
278
279
 
280
+ // Market estimate for token usage at catalog paid rates (USD). saved is
281
+ // market minus actual cost. pricedAs records the catalog entry used
282
+ // ("proxy:" prefix = fallback estimate). Null when no pricing catalog.
283
+ // Market-price engine rules live in pricing.js (shared with check scripts).
284
+ function marketOf(tok, provider, model) {
285
+ const pr = pricing.priceFor(provider, model);
286
+ if (!pr) return { market: null, saved: null, pricedAs: null };
287
+ const market = pricing.marketOf(tok, pr);
288
+ const r4m = (v) => Math.round(v * 10000) / 10000;
289
+ return { market: r4m(market), saved: r4m(market - (tok.cost || 0)), pricedAs: pr.source };
290
+ }
291
+
279
292
  // Hybrid usage attribution over [startMs, endMs).
280
293
  // Why hybrid: session-level totals are COMPLETE (message table only covers
281
294
  // ~2026-08 onward; 287/469 sessions in 90d have zero messages) but a
@@ -463,6 +476,29 @@ function getStatsFromDb(days) {
463
476
  }))
464
477
  .sort((a, b) => b.cost - a.cost);
465
478
 
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.
483
+ let marketTotal = null, savedTotal = null, priceAsOf = null;
484
+ {
485
+ const info = pricing.catalogInfo();
486
+ if (info.ok) {
487
+ priceAsOf = new Date(info.mtimeMs).toISOString();
488
+ 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);
492
+ if (mk.market === null) { marketTotal = null; break; }
493
+ marketTotal += mk.market;
494
+ }
495
+ if (marketTotal !== null) {
496
+ marketTotal = Math.round(marketTotal * 10000) / 10000;
497
+ savedTotal = Math.round((marketTotal - (costRow ? costRow.total : 0)) * 10000) / 10000;
498
+ } else { savedTotal = null; }
499
+ }
500
+ }
501
+
466
502
  return {
467
503
  ok: true,
468
504
  overview: {
@@ -480,6 +516,7 @@ function getStatsFromDb(days) {
480
516
  reasoning: costRow ? costRow.reasoning : 0,
481
517
  cacheRead: costRow ? costRow.cacheRead : 0,
482
518
  cacheWrite: costRow ? costRow.cacheWrite : 0,
519
+ marketTotal, savedTotal, priceAsOf,
483
520
  },
484
521
  tools,
485
522
  models,
@@ -624,7 +661,7 @@ function buildReportFromDb(days) {
624
661
  // time). One GROUP BY over the merged message view, mapped onto the same
625
662
  // session-meta buckets as tokens so row sets stay identical.
626
663
  const msgAgg = {};
627
- 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, '$.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`) || [])) {
664
+ 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`) || [])) {
628
665
  msgAgg[m.sid] = m;
629
666
  }
630
667
  const periodDays = {};
@@ -686,14 +723,16 @@ function buildReportFromDb(days) {
686
723
  const meta = metaMap[sid] || { agent: 'unknown', provider: 'unknown', model: 'unknown' };
687
724
  const agent = meta.agent || 'unknown';
688
725
  const modelName = `${meta.provider}/${meta.model}`;
689
- 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 };
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 };
690
727
  agentAgg[agent].sessions.add(sid);
691
728
  agentAgg[agent].input += ps.input; agentAgg[agent].output += ps.output;
692
729
  agentAgg[agent].reasoning += ps.reasoning; agentAgg[agent].cacheRead += ps.cacheRead;
693
730
  agentAgg[agent].cost += ps.cost;
694
- const mg = msgAgg[sid] || { n: 0, o: 0, ms: 0 };
731
+ const mg = msgAgg[sid] || { n: 0, o: 0, ms: 0, rq: 0 };
695
732
  agentAgg[agent].speedOut += mg.o; agentAgg[agent].speedMs += mg.ms; agentAgg[agent].activeMs += mg.ms;
696
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; }
697
736
  if (!modelAgg[modelName]) modelAgg[modelName] = { sessions: new Set(), cost: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, speedOut: 0, speedMs: 0 };
698
737
  modelAgg[modelName].sessions.add(sid);
699
738
  modelAgg[modelName].input += ps.input; modelAgg[modelName].output += ps.output;
@@ -710,29 +749,37 @@ function buildReportFromDb(days) {
710
749
  tok_reasoning: Math.round(m.reasoning), cache_read: Math.round(m.cacheRead),
711
750
  speed: m.speedMs > 0 ? Math.round((m.speedOut / (m.speedMs / 1000)) * 10) / 10 : null,
712
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,
713
753
  }))
714
754
  .sort((x, y) => y.cost - x.cost);
715
755
  var pProviderRows = Object.entries(modelAgg)
716
756
  .map(([name, m]) => {
717
757
  const { provider, model } = splitModelName(name);
758
+ const mk = marketOf({ input: m.input, output: m.output, reasoning: m.reasoning, cacheRead: m.cacheRead, cost: m.cost }, provider, model);
718
759
  return {
719
760
  provider, model, sessions: m.sessions.size, cost: r4(m.cost),
720
761
  tok_in: Math.round(m.input), tok_out: Math.round(m.output),
721
762
  tok_reasoning: Math.round(m.reasoning), cache_read: Math.round(m.cacheRead),
722
763
  speed: m.speedMs > 0 ? Math.round((m.speedOut / (m.speedMs / 1000)) * 10) / 10 : null,
764
+ market: mk.market, saved: mk.saved, pricedAs: mk.pricedAs,
723
765
  };
724
766
  })
725
767
  .sort((x, y) => y.cost - x.cost);
726
768
  var pSessionRows = sessRows
727
- .map(({ sid, meta, ps, mg }) => ({
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');
771
+ return {
728
772
  id: sid, title: (meta.title || '').slice(0, 40), agent: meta.agent || 'unknown',
729
773
  provider: meta.provider || 'unknown', model: meta.model || 'unknown',
730
774
  wallMs: Math.max(0, (meta.tu || 0) - (meta.tc || 0)),
731
775
  activeMs: mg.ms || 0, messages: mg.n || 0,
732
776
  tok_in: Math.round(ps.input), tok_out: Math.round(ps.output),
777
+ tok_reasoning: Math.round(mg.rq || 0),
733
778
  cost: r4(ps.cost),
734
779
  speed: (mg.ms || 0) > 0 ? Math.round(((mg.o || 0) / (mg.ms / 1000)) * 10) / 10 : null,
735
- }))
780
+ market: mkS.market, saved: mkS.saved, pricedAs: mkS.pricedAs,
781
+ };
782
+ })
736
783
  .sort((x, y) => y.wallMs - x.wallMs)
737
784
  .slice(0, 20);
738
785
  } else {
@@ -741,6 +788,12 @@ function buildReportFromDb(days) {
741
788
  var pSessionRows = [];
742
789
  }
743
790
 
791
+ const sumMkt = (rows) => rows.reduce((s, r) => s + (r.market || 0), 0);
792
+ statsR.cost.marketTotal = Math.round(sumMkt(pProviderRows) * 10000) / 10000;
793
+ statsR.cost.savedTotal = Math.round((sumMkt(pProviderRows) - t.cost) * 10000) / 10000;
794
+ statsR.cost.savedPct = statsR.cost.marketTotal > 0 ? Math.round((statsR.cost.savedTotal / statsR.cost.marketTotal) * 1000) / 10 : null;
795
+ statsR.cost.priceAsOf = pricing.catalogInfo().ok ? new Date(pricing.catalogInfo().mtimeMs).toISOString() : null;
796
+
744
797
  return {
745
798
  label,
746
799
  days,
@@ -748,6 +801,7 @@ function buildReportFromDb(days) {
748
801
  agents: pAgentRows,
749
802
  providers: pProviderRows,
750
803
  sessions: pSessionRows,
804
+ priceAsOf: statsR.cost.priceAsOf,
751
805
  generatedAt: now,
752
806
  };
753
807
  }