opencode-statboard 2.2.0 → 2.3.1
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 +2 -1
- package/README.md +3 -0
- package/package.json +2 -2
- package/pricing.js +94 -0
- package/public/index.html +141 -36
- package/server.js +78 -15
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
|
|
|
@@ -119,7 +120,7 @@ npm install -g opencode-statboard # after the Actions run is green
|
|
|
119
120
|
- `better-sqlite3` is a native addon; must match Node.js ABI
|
|
120
121
|
- `attributeUsage` does a full DB scan (~35k messages); cached 300s via `getAttrAll()`
|
|
121
122
|
- 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)
|
|
122
|
-
- V2 tool counts use `json_each` over `session_message` content (~1.
|
|
123
|
+
- 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
|
|
123
124
|
- OpenCode V2 writes `cost = 0` for free/subscription providers, so $ totals only reflect paid (per-token billed) usage — same field, not a schema issue
|
|
124
125
|
- `gzip` compression on all `/api/` responses (>512B, level 1 for speed)
|
|
125
126
|
- 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
|
@@ -9,7 +9,10 @@ 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
|
+
- Visual usage-report tables (providers, agents, sessions) with collapsible raw text
|
|
15
|
+
- Collapsible sections (collapse state remembered in browser)
|
|
13
16
|
- Daily trend chart (7D / 30D / 90D)
|
|
14
17
|
- Usage reports: Daily / Weekly / Monthly / All time
|
|
15
18
|
- 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.
|
|
3
|
+
"version": "2.3.1",
|
|
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
|
@@ -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%; }
|
|
@@ -90,21 +98,23 @@
|
|
|
90
98
|
|
|
91
99
|
<div class="error-banner" id="errbanner"></div>
|
|
92
100
|
|
|
93
|
-
<section>
|
|
94
|
-
<h2 data-i18n="overview">OVERVIEW</h2>
|
|
101
|
+
<details class="tool-section" open id="sec-overview">
|
|
102
|
+
<summary><h2 data-i18n="overview">OVERVIEW</h2></summary>
|
|
95
103
|
<div class="cards">
|
|
96
104
|
<div class="card"><div class="l" data-i18n="sessions">Sessions</div><div class="v" id="ov-sessions">—</div></div>
|
|
97
105
|
<div class="card"><div class="l" data-i18n="messages">Messages</div><div class="v" id="ov-messages">—</div></div>
|
|
98
106
|
<div class="card"><div class="l" data-i18n="days">Days</div><div class="v" id="ov-days">—</div></div>
|
|
99
107
|
<div class="card"><div class="l" data-i18n="totalCost">Total Cost</div><div class="v" id="ov-total">—</div></div>
|
|
108
|
+
<div class="card"><div class="l" data-i18n="marketValue">Market Value</div><div class="v" id="ov-market">—</div></div>
|
|
109
|
+
<div class="card"><div class="l" data-i18n="saved">Saved</div><div class="v" id="ov-saved">—</div></div>
|
|
100
110
|
<div class="card"><div class="l" data-i18n="avgCostDay">Avg Cost / Day</div><div class="v" id="ov-avgday">—</div></div>
|
|
101
111
|
<div class="card"><div class="l" data-i18n="avgTokensSession">Avg Tokens / Session</div><div class="v" id="ov-avg">—</div></div>
|
|
102
112
|
<div class="card"><div class="l" data-i18n="medianTokensSession">Median Tokens / Session</div><div class="v" id="ov-med">—</div></div>
|
|
103
113
|
</div>
|
|
104
|
-
</
|
|
114
|
+
</details>
|
|
105
115
|
|
|
106
|
-
<section>
|
|
107
|
-
<h2 data-i18n="tokenStats">TOKEN STATISTICS</h2>
|
|
116
|
+
<details class="tool-section" open id="sec-tokens">
|
|
117
|
+
<summary><h2 data-i18n="tokenStats">TOKEN STATISTICS</h2></summary>
|
|
108
118
|
<div class="legend">
|
|
109
119
|
<span><i class="sw" style="background:var(--in)"></i>Input</span>
|
|
110
120
|
<span><i class="sw" style="background:var(--out)"></i>Output</span>
|
|
@@ -113,32 +123,32 @@
|
|
|
113
123
|
<span><i class="sw" style="background:var(--cost)"></i>Cache Write</span>
|
|
114
124
|
</div>
|
|
115
125
|
<div id="token-bars"></div>
|
|
116
|
-
</
|
|
126
|
+
</details>
|
|
117
127
|
|
|
118
|
-
<details class="tool-section" open>
|
|
128
|
+
<details class="tool-section" open id="sec-tools">
|
|
119
129
|
<summary><h2 data-i18n="toolUsage">TOOL USAGE</h2></summary>
|
|
120
130
|
<div id="tool-bars"></div>
|
|
121
131
|
</details>
|
|
122
132
|
|
|
123
|
-
<section>
|
|
124
|
-
<h2 data-i18n="modelUsage">MODEL USAGE</h2>
|
|
133
|
+
<details class="tool-section" open id="sec-models">
|
|
134
|
+
<summary><h2 data-i18n="modelUsage">MODEL USAGE</h2></summary>
|
|
125
135
|
<table>
|
|
126
136
|
<thead>
|
|
127
137
|
<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
138
|
</thead>
|
|
129
139
|
<tbody id="model-rows"></tbody>
|
|
130
140
|
</table>
|
|
131
|
-
</
|
|
141
|
+
</details>
|
|
132
142
|
|
|
133
|
-
<section>
|
|
134
|
-
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px">
|
|
143
|
+
<details class="tool-section" open id="sec-trend">
|
|
144
|
+
<summary><div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px">
|
|
135
145
|
<h2 id="trendTitle" style="margin:0"></h2>
|
|
136
146
|
<div class="range-btns" id="rangeBtns">
|
|
137
147
|
<span class="pill active" data-days="7" onclick="setRange(7)">7D</span>
|
|
138
148
|
<span class="pill" data-days="30" onclick="setRange(30)">30D</span>
|
|
139
149
|
<span class="pill" data-days="90" onclick="setRange(90)">90D</span>
|
|
140
150
|
</div>
|
|
141
|
-
</div>
|
|
151
|
+
</div></summary>
|
|
142
152
|
<div style="display:flex;gap:24px;flex-wrap:wrap">
|
|
143
153
|
<div style="flex:1;min-width:300px">
|
|
144
154
|
<div class="legend">
|
|
@@ -158,10 +168,10 @@
|
|
|
158
168
|
<div id="costZeroNote" style="display:none;font-size:12px;color:var(--muted);padding:20px 0;text-align:center"></div>
|
|
159
169
|
</div>
|
|
160
170
|
</div>
|
|
161
|
-
</
|
|
171
|
+
</details>
|
|
162
172
|
|
|
163
|
-
<section>
|
|
164
|
-
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px">
|
|
173
|
+
<details class="tool-section" open id="sec-report">
|
|
174
|
+
<summary><div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px">
|
|
165
175
|
<h2 data-i18n="report" style="margin:0">USAGE REPORT</h2>
|
|
166
176
|
<div class="range-btns" id="reportBtns">
|
|
167
177
|
<span class="pill" data-days="-1" onclick="loadReport(-1)" data-i18n="all">All</span>
|
|
@@ -169,32 +179,40 @@
|
|
|
169
179
|
<span class="pill" data-days="7" onclick="loadReport(7)" data-i18n="weekly">Weekly</span>
|
|
170
180
|
<span class="pill" data-days="30" onclick="loadReport(30)" data-i18n="monthly">Monthly</span>
|
|
171
181
|
</div>
|
|
172
|
-
</div>
|
|
182
|
+
</div></summary>
|
|
173
183
|
<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
|
-
</
|
|
184
|
+
</details>
|
|
175
185
|
|
|
176
|
-
<section>
|
|
177
|
-
<h2 data-i18n="modelSpeed">MODEL SPEED</h2>
|
|
186
|
+
<details class="tool-section" open id="sec-speed">
|
|
187
|
+
<summary><h2 data-i18n="modelSpeed">MODEL SPEED</h2></summary>
|
|
178
188
|
<div id="speed-bars"></div>
|
|
179
|
-
</
|
|
189
|
+
</details>
|
|
180
190
|
|
|
181
|
-
<section>
|
|
182
|
-
<h2 data-i18n="agentTime">AGENT TIME</h2>
|
|
191
|
+
<details class="tool-section" open id="sec-agent">
|
|
192
|
+
<summary><h2 data-i18n="agentTime">AGENT TIME</h2></summary>
|
|
183
193
|
<div class="legend">
|
|
184
194
|
<span><i class="sw" style="background:var(--cache)"></i>wall</span>
|
|
185
195
|
<span><i class="sw" style="background:var(--out)"></i>active</span>
|
|
186
196
|
</div>
|
|
187
197
|
<div id="agent-bars"></div>
|
|
188
|
-
</
|
|
198
|
+
</details>
|
|
189
199
|
|
|
190
|
-
<section>
|
|
191
|
-
<h2 data-i18n="topSessions">TOP SESSIONS</h2>
|
|
200
|
+
<details class="tool-section" open id="sec-sessions">
|
|
201
|
+
<summary><h2 data-i18n="topSessions">TOP SESSIONS</h2></summary>
|
|
192
202
|
<div class="legend">
|
|
193
203
|
<span><i class="sw" style="background:var(--cache)"></i>wall</span>
|
|
194
204
|
<span><i class="sw" style="background:var(--out)"></i>active</span>
|
|
195
205
|
</div>
|
|
196
206
|
<div id="session-bars"></div>
|
|
197
|
-
</
|
|
207
|
+
</details>
|
|
208
|
+
|
|
209
|
+
<details class="tool-section" open id="sec-savings">
|
|
210
|
+
<summary><h2 data-i18n="savings">SAVINGS</h2></summary>
|
|
211
|
+
<div class="legend">
|
|
212
|
+
<span><i class="sw" style="background:var(--cost)"></i>market value</span>
|
|
213
|
+
</div>
|
|
214
|
+
<div id="savings-bars"></div>
|
|
215
|
+
</details>
|
|
198
216
|
|
|
199
217
|
<script>
|
|
200
218
|
const STRINGS = {
|
|
@@ -203,9 +221,9 @@ const STRINGS = {
|
|
|
203
221
|
overview: 'OVERVIEW',
|
|
204
222
|
sessions: 'Sessions', messages: 'Messages', days: 'Days',
|
|
205
223
|
totalCost: 'Total Cost', avgCostDay: 'Avg Cost / Day',
|
|
206
|
-
avgTokensSession: 'Avg Tokens / Session', medianTokensSession: 'Median Tokens / Session',
|
|
224
|
+
avgTokensSession: 'Avg Tokens / Session', medianTokensSession: 'Median Tokens / Session', marketValue: 'Market Value', saved: 'Saved', savings: 'SAVINGS',
|
|
207
225
|
tokenStats: 'TOKEN STATISTICS', toolUsage: 'TOOL USAGE', modelUsage: 'MODEL USAGE',
|
|
208
|
-
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',
|
|
209
227
|
dailyTrend: 'DAILY TREND ({days} DAYS)',
|
|
210
228
|
inputDay: 'Input / Day', outputDay: 'Output / Day', cacheReadDay: 'Cache Read / Day', costDay: 'Cost / Day',
|
|
211
229
|
report: 'USAGE REPORT', all: 'All', daily: 'Daily', weekly: 'Weekly', monthly: 'Monthly', modelSpeed: 'MODEL SPEED', agentTime: 'AGENT TIME', topSessions: 'TOP SESSIONS',
|
|
@@ -220,9 +238,9 @@ const STRINGS = {
|
|
|
220
238
|
overview: '概覽',
|
|
221
239
|
sessions: '工作階段', messages: '訊息數', days: '使用天數',
|
|
222
240
|
totalCost: '總費用', avgCostDay: '平均費用 / 天',
|
|
223
|
-
avgTokensSession: '平均 tokens / 場', medianTokensSession: '中位數 tokens / 場',
|
|
241
|
+
avgTokensSession: '平均 tokens / 場', medianTokensSession: '中位數 tokens / 場', marketValue: '市價', saved: '已節省', savings: '節省金額',
|
|
224
242
|
tokenStats: 'Tokens 統計', toolUsage: '工具使用', modelUsage: '模型使用',
|
|
225
|
-
thModel: '模型', thMsgs: '訊息', thSpeed: '速度', thUsage: '用量', thCost: '費用',
|
|
243
|
+
thModel: '模型', thMsgs: '訊息', thSpeed: '速度', thUsage: '用量', thCost: '費用', repProviders: '供應商與模型', repAgents: '代理', repSessions: '場次', repPricing: '定價依據', repRaw: '原始文字',
|
|
226
244
|
dailyTrend: '近 {days} 天趨勢',
|
|
227
245
|
inputDay: 'Input / 天', outputDay: 'Output / 天', cacheReadDay: 'Cache Read / 天', costDay: '費用 / 天',
|
|
228
246
|
report: '用量報告', all: '全部', daily: '每日', weekly: '每週', monthly: '每月', modelSpeed: '模型速度', agentTime: '代理時間', topSessions: '最長場次',
|
|
@@ -249,6 +267,20 @@ function applyI18n() {
|
|
|
249
267
|
$('trendTitle').textContent = t('dailyTrend').replace('{days}', currentDays);
|
|
250
268
|
}
|
|
251
269
|
|
|
270
|
+
function restoreSections() {
|
|
271
|
+
document.querySelectorAll('#rangeBtns .pill, #reportBtns .pill').forEach((el) => {
|
|
272
|
+
el.addEventListener('click', (e) => e.stopPropagation());
|
|
273
|
+
});
|
|
274
|
+
document.querySelectorAll('details.tool-section[id]').forEach((el) => {
|
|
275
|
+
try {
|
|
276
|
+
if (localStorage.getItem('oc-sec-' + el.id) === '0') el.removeAttribute('open');
|
|
277
|
+
el.addEventListener('toggle', () => {
|
|
278
|
+
try { localStorage.setItem('oc-sec-' + el.id, el.open ? '1' : '0'); } catch (_) {}
|
|
279
|
+
});
|
|
280
|
+
} catch (_) {}
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
|
|
252
284
|
function toggleLang() {
|
|
253
285
|
lang = lang === 'en' ? 'zh-TW' : 'en';
|
|
254
286
|
localStorage.setItem('lang', lang);
|
|
@@ -305,6 +337,8 @@ function render(d, models, trend) {
|
|
|
305
337
|
$('ov-messages').textContent = fmt(o.messages);
|
|
306
338
|
$('ov-days').textContent = fmt(o.days);
|
|
307
339
|
$('ov-total').textContent = fmtCost(d.cost && d.cost.total);
|
|
340
|
+
$('ov-market').textContent = fmtCost(d.cost && d.cost.marketTotal);
|
|
341
|
+
$('ov-saved').textContent = fmtCost(d.cost && d.cost.savedTotal);
|
|
308
342
|
$('ov-avgday').textContent = fmtCost(d.cost && d.cost.avgDay);
|
|
309
343
|
$('ov-avg').textContent = fmt(d.cost && d.cost.avgTokensSession);
|
|
310
344
|
$('ov-med').textContent = fmt(d.cost && d.cost.medianTokensSession);
|
|
@@ -487,7 +521,7 @@ function renderReportCharts(r) {
|
|
|
487
521
|
const fullName = (p) => p.provider + '/' + p.model;
|
|
488
522
|
$('speed-bars').innerHTML = spd.length ? spd.map((p) => {
|
|
489
523
|
const pct = smax > 0 && p.speed != null ? Math.max(0.5, (p.speed / smax) * 100) : 0;
|
|
490
|
-
return `<div class="bar-row"><div class="name" title="${esc(fullName(p))}">${esc(fullName(p))}</div>
|
|
524
|
+
return `<div class="bar-row wide"><div class="name" title="${esc(fullName(p))}">${esc(fullName(p))}</div>
|
|
491
525
|
<div class="track"><div class="fill" style="width:${pct}%;background:var(--in)"></div></div>
|
|
492
526
|
<div class="val">${fmtSpeed(p.speed)}</div></div>`;
|
|
493
527
|
}).join('') : '<div class="val">—</div>';
|
|
@@ -506,6 +540,66 @@ function renderReportCharts(r) {
|
|
|
506
540
|
fmtDur(s.wallMs) + ' · ' + fmtSpeed(s.speed),
|
|
507
541
|
(s.title || '') + ' · ' + s.agent + ' · ' + s.provider + '/' + s.model + ' · ' + (s.messages || 0) + ' msgs')
|
|
508
542
|
).join('') : '<div class="val">—</div>';
|
|
543
|
+
|
|
544
|
+
const mkt = (r.providers || []).slice().sort((a, b) => (b.market || 0) - (a.market || 0));
|
|
545
|
+
const mmax = Math.max(0, ...mkt.map((p) => p.market || 0));
|
|
546
|
+
$('savings-bars').innerHTML = mkt.length ? mkt.map((p) => {
|
|
547
|
+
const pct = mmax > 0 ? Math.max(0.5, ((p.market || 0) / mmax) * 100) : 0;
|
|
548
|
+
const sv = p.saved == null ? '—' : fmtCost(p.saved) + ' saved';
|
|
549
|
+
const tip = 'market ' + fmtCost(p.market) + ' · actual ' + fmtCost(p.cost) + ' · via ' + (p.pricedAs || '?');
|
|
550
|
+
return `<div class="bar-row wide"><div class="name" title="${esc(fullName(p))}">${esc(fullName(p))}</div>
|
|
551
|
+
<div class="track"><div class="fill" style="width:${pct}%;background:var(--cost)"></div></div>
|
|
552
|
+
<div class="val" title="${esc(tip)}">${sv}</div></div>`;
|
|
553
|
+
}).join('') : '<div class="val">—</div>';
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
function repTable(heads, rows) {
|
|
557
|
+
return `<div class="scrollx"><table><thead><tr>${heads.map((h) => `<th>${esc(h)}</th>`).join('')}</tr></thead><tbody>${rows.join('')}</tbody></table></div>`;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
function repBlock(title, hint, body, isOpen) {
|
|
561
|
+
return `<details class="tool-section"${isOpen ? ' open' : ''}><summary><h2>${esc(title)}</h2><span class="rep-hint">${esc(hint)}</span></summary>${body}</details>`;
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
function renderReportTables(r) {
|
|
565
|
+
const o = (r.stats && r.stats.overview) || {};
|
|
566
|
+
const c = (r.stats && r.stats.cost) || {};
|
|
567
|
+
const genTime = r.generatedAt ? new Date(r.generatedAt).toLocaleTimeString(lang === 'zh-TW' ? 'zh-TW' : 'en', { hour12: false }) : '?';
|
|
568
|
+
const periodText = r.days === -1 ? 'All time' : r.days <= 1 ? 'Today (local)' : r.days <= 7 ? 'Last 7 days (local)' : 'Month to date (local)';
|
|
569
|
+
let h = `<div class="rep-head">OPENCODE USAGE STATEMENT · ${esc(r.label || '')} · ${esc(periodText)} · ${esc(r.stale ? '⟳ ' + t('updating') : t('cachedAt') + ' ' + genTime)}</div>`;
|
|
570
|
+
h += `<div class="cards">` + [
|
|
571
|
+
[t('sessions'), fmt(o.sessions)], [t('messages'), fmt(o.messages)],
|
|
572
|
+
[t('totalCost'), fmtCost(c.total)], [t('marketValue'), fmtCost(c.marketTotal)],
|
|
573
|
+
[t('saved'), fmtCost(c.savedTotal)],
|
|
574
|
+
].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>`;
|
|
575
|
+
|
|
576
|
+
const prov = r.providers || [];
|
|
577
|
+
h += repBlock(t('repProviders'), prov.length + ' models' + (prov.length ? ' · ' + prov[0].provider + '/' + prov[0].model : ''),
|
|
578
|
+
repTable(['Model', 'Sess', 'Cost', 'In', 'Out', 'Cache', 'Speed', 'Market', 'Saved'], prov.map((p) => {
|
|
579
|
+
const name = p.provider + '/' + p.model;
|
|
580
|
+
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>`;
|
|
581
|
+
})), true);
|
|
582
|
+
|
|
583
|
+
const ags = r.agents || [];
|
|
584
|
+
h += repBlock(t('repAgents'), ags.length + ' agents' + (ags.length ? ' · ' + ags[0].agent : ''),
|
|
585
|
+
repTable(['Agent', 'Sess', 'Cost', 'In', 'Out', 'Speed', 'Wall', 'Active', 'Market', 'Saved'], ags.map((a) =>
|
|
586
|
+
`<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);
|
|
587
|
+
|
|
588
|
+
const sess = r.sessions || [];
|
|
589
|
+
h += repBlock(t('repSessions'), 'top ' + sess.length + ' by wall',
|
|
590
|
+
repTable(['Session', 'Agent', 'Model', 'Wall', 'Active', 'Msgs', 'In', 'Out', 'Speed', 'Saved'], sess.map((s) => {
|
|
591
|
+
const name = s.provider + '/' + s.model;
|
|
592
|
+
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>`;
|
|
593
|
+
})), true);
|
|
594
|
+
|
|
595
|
+
const basis = prov.filter((p) => p.pricedAs && p.pricedAs !== (p.provider + '/' + p.model));
|
|
596
|
+
if (basis.length) {
|
|
597
|
+
h += repBlock(t('repPricing'), basis.length + ' mappings',
|
|
598
|
+
repTable(['Usage', 'Basis'], basis.map((p) =>
|
|
599
|
+
`<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);
|
|
600
|
+
}
|
|
601
|
+
h += repBlock(t('repRaw'), 'statement text', `<pre class="rep-pre">${esc(formatReport(r))}</pre>`, false);
|
|
602
|
+
return h;
|
|
509
603
|
}
|
|
510
604
|
|
|
511
605
|
function formatReport(jr) {
|
|
@@ -531,25 +625,35 @@ function formatReport(jr) {
|
|
|
531
625
|
out += ' Tokens In/Out ...... ' + fmtT(c.input) + ' / ' + fmtT(c.output) + '\n';
|
|
532
626
|
out += ' Tokens Reasoning ... ' + fmtT(c.reasoning) + '\n';
|
|
533
627
|
out += ' Cache Read/Write ... ' + fmtT(c.cacheRead) + ' / ' + fmtT(c.cacheWrite) + '\n';
|
|
628
|
+
out += ' Market value ..... ' + (c.marketTotal == null ? '—' : '$' + c.marketTotal.toFixed(2)) + '\n';
|
|
629
|
+
out += ' Saved ............ ' + (c.savedTotal == null ? '—' : '$' + c.savedTotal.toFixed(2)) + (c.marketTotal > 0 && c.savedPct != null ? ' (' + c.savedPct + '%)' : '') + '\n';
|
|
534
630
|
out += '\n';
|
|
535
631
|
}
|
|
536
632
|
if (jr.providers && jr.providers.length) {
|
|
537
633
|
out += 'PROVIDERS & MODELS\n';
|
|
538
634
|
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';
|
|
635
|
+
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
636
|
});
|
|
541
637
|
out += '\n';
|
|
638
|
+
const basis = (jr.providers || []).filter((p) => p.pricedAs && p.pricedAs !== (p.provider + '/' + p.model));
|
|
639
|
+
if (basis.length) {
|
|
640
|
+
out += 'PRICING (free → paid basis' + (jr.priceAsOf ? ', prices as of ' + jr.priceAsOf.slice(0, 10) : '') + ')\n';
|
|
641
|
+
basis.forEach((p) => {
|
|
642
|
+
out += ' ' + pad(p.provider + '/' + p.model, 45) + '→ ' + p.pricedAs + '\n';
|
|
643
|
+
});
|
|
644
|
+
out += '\n';
|
|
645
|
+
}
|
|
542
646
|
}
|
|
543
647
|
if (jr.agents && jr.agents.length) {
|
|
544
648
|
out += 'AGENTS\n';
|
|
545
649
|
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';
|
|
650
|
+
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
651
|
});
|
|
548
652
|
}
|
|
549
653
|
if (jr.sessions && jr.sessions.length) {
|
|
550
654
|
out += 'SESSIONS (top ' + jr.sessions.length + ' by wall time)\n';
|
|
551
655
|
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';
|
|
656
|
+
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
657
|
});
|
|
554
658
|
out += '\n';
|
|
555
659
|
}
|
|
@@ -577,7 +681,7 @@ async function loadReport(days) {
|
|
|
577
681
|
return;
|
|
578
682
|
}
|
|
579
683
|
reportRetry = 0;
|
|
580
|
-
$('reportContent').
|
|
684
|
+
$('reportContent').innerHTML = renderReportTables(j.report);
|
|
581
685
|
renderReportCharts(j.report);
|
|
582
686
|
} catch (e) {
|
|
583
687
|
$('reportContent').textContent = t('connFail') + ': ' + e.message;
|
|
@@ -586,6 +690,7 @@ async function loadReport(days) {
|
|
|
586
690
|
}
|
|
587
691
|
|
|
588
692
|
applyI18n();
|
|
693
|
+
restoreSections();
|
|
589
694
|
poll();
|
|
590
695
|
setInterval(poll, 15000);
|
|
591
696
|
loadReport(1);
|
package/server.js
CHANGED
|
@@ -10,11 +10,13 @@ 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;
|
|
16
17
|
const TREND_MS = 60 * 1000;
|
|
17
18
|
const REPORT_TTL = 10 * 60 * 1000;
|
|
19
|
+
const TOOLS_TTL = 5 * 60 * 1000;
|
|
18
20
|
const STATS_TTL = 10 * 60 * 1000;
|
|
19
21
|
const CACHE_CLEANUP_MS = 5 * 60 * 1000;
|
|
20
22
|
const BACKUP_DIR = path.join(__dirname, 'backups');
|
|
@@ -276,6 +278,18 @@ function splitModelName(name) {
|
|
|
276
278
|
return i < 0 ? { provider: 'unknown', model: String(name) } : { provider: String(name).slice(0, i), model: String(name).slice(i + 1) };
|
|
277
279
|
}
|
|
278
280
|
|
|
281
|
+
// Market estimate for token usage at catalog paid rates (USD). saved is
|
|
282
|
+
// market minus actual cost. pricedAs records the catalog entry used
|
|
283
|
+
// ("proxy:" prefix = fallback estimate). Null when no pricing catalog.
|
|
284
|
+
// Market-price engine rules live in pricing.js (shared with check scripts).
|
|
285
|
+
function marketOf(tok, provider, model) {
|
|
286
|
+
const pr = pricing.priceFor(provider, model);
|
|
287
|
+
if (!pr) return { market: null, saved: null, pricedAs: null };
|
|
288
|
+
const market = pricing.marketOf(tok, pr);
|
|
289
|
+
const r4m = (v) => Math.round(v * 10000) / 10000;
|
|
290
|
+
return { market: r4m(market), saved: r4m(market - (tok.cost || 0)), pricedAs: pr.source };
|
|
291
|
+
}
|
|
292
|
+
|
|
279
293
|
// Hybrid usage attribution over [startMs, endMs).
|
|
280
294
|
// Why hybrid: session-level totals are COMPLETE (message table only covers
|
|
281
295
|
// ~2026-08 onward; 287/469 sessions in 90d have zero messages) but a
|
|
@@ -389,6 +403,9 @@ function attributeUsage(startMs, endMs) {
|
|
|
389
403
|
// All-time attribution, memoized 300s (expensive full DB scan; avoids
|
|
390
404
|
// re-running attributeUsage on every /api/stats hit).
|
|
391
405
|
let attrAllCache = null;
|
|
406
|
+
// Tool counts change slowly but the embedded-content scan costs ~1.5s on a
|
|
407
|
+
// large DB; cache it so the 15s refresh stays cheap. Keyed on schema+window.
|
|
408
|
+
let toolsCache = null;
|
|
392
409
|
function getAttrAll() {
|
|
393
410
|
const now = Date.now();
|
|
394
411
|
if (attrAllCache && now - attrAllCache.at < 300000) return attrAllCache.a;
|
|
@@ -423,16 +440,21 @@ function getStatsFromDb(days) {
|
|
|
423
440
|
// V2: tool parts are embedded in session_message content (part table froze
|
|
424
441
|
// at the upgrade and its migrated rows were rebuilt into content, so
|
|
425
442
|
// querying all of part would double count — only parts of messages that
|
|
426
|
-
// were never migrated are added from `part`).
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
SELECT json_extract(
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
443
|
+
// were never migrated are added from `part`). Cached (see toolsCache):
|
|
444
|
+
// verification accepts api<=expected, so staleness never fails checks.
|
|
445
|
+
if (!toolsCache || now - toolsCache.at > TOOLS_TTL || toolsCache.embedded !== schema.embeddedTools || toolsCache.startMs !== startMs) {
|
|
446
|
+
const toolRows = schema.embeddedTools
|
|
447
|
+
? 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}` : ''}
|
|
448
|
+
UNION ALL
|
|
449
|
+
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}` : ''};`) || []
|
|
450
|
+
: dbQuery(`SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' ${timeFilterPart};`) || [];
|
|
451
|
+
const counts = {};
|
|
452
|
+
for (const row of toolRows) {
|
|
453
|
+
if (row.tool) counts[row.tool] = (counts[row.tool] || 0) + 1;
|
|
454
|
+
}
|
|
455
|
+
toolsCache = { at: now, embedded: schema.embeddedTools, startMs, counts };
|
|
435
456
|
}
|
|
457
|
+
const toolCounts = toolsCache.counts;
|
|
436
458
|
const totalToolUse = Object.values(toolCounts).reduce((s, v) => s + v, 0) || 1;
|
|
437
459
|
const tools = Object.entries(toolCounts)
|
|
438
460
|
.map(([name, count]) => ({ name, count, pct: Math.round((count / totalToolUse) * 1000) / 10 }))
|
|
@@ -463,6 +485,29 @@ function getStatsFromDb(days) {
|
|
|
463
485
|
}))
|
|
464
486
|
.sort((a, b) => b.cost - a.cost);
|
|
465
487
|
|
|
488
|
+
// Savings estimate: market value of all-time usage at catalog paid rates.
|
|
489
|
+
// Basis is session-meta grouping (same rows/basis as the report providers
|
|
490
|
+
// table) so the two panels agree; message-level model splits would price
|
|
491
|
+
// model-switched sessions differently.
|
|
492
|
+
let marketTotal = null, savedTotal = null, priceAsOf = null;
|
|
493
|
+
{
|
|
494
|
+
const info = pricing.catalogInfo();
|
|
495
|
+
if (info.ok) {
|
|
496
|
+
priceAsOf = new Date(info.mtimeMs).toISOString();
|
|
497
|
+
marketTotal = 0;
|
|
498
|
+
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`) || [];
|
|
499
|
+
for (const g of grows) {
|
|
500
|
+
const mk = marketOf({ input: g.i, output: g.o, reasoning: g.r, cacheRead: g.cr, cost: 0 }, g.provider, g.model);
|
|
501
|
+
if (mk.market === null) { marketTotal = null; break; }
|
|
502
|
+
marketTotal += mk.market;
|
|
503
|
+
}
|
|
504
|
+
if (marketTotal !== null) {
|
|
505
|
+
marketTotal = Math.round(marketTotal * 10000) / 10000;
|
|
506
|
+
savedTotal = Math.round((marketTotal - (costRow ? costRow.total : 0)) * 10000) / 10000;
|
|
507
|
+
} else { savedTotal = null; }
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
466
511
|
return {
|
|
467
512
|
ok: true,
|
|
468
513
|
overview: {
|
|
@@ -480,6 +525,7 @@ function getStatsFromDb(days) {
|
|
|
480
525
|
reasoning: costRow ? costRow.reasoning : 0,
|
|
481
526
|
cacheRead: costRow ? costRow.cacheRead : 0,
|
|
482
527
|
cacheWrite: costRow ? costRow.cacheWrite : 0,
|
|
528
|
+
marketTotal, savedTotal, priceAsOf,
|
|
483
529
|
},
|
|
484
530
|
tools,
|
|
485
531
|
models,
|
|
@@ -624,7 +670,7 @@ function buildReportFromDb(days) {
|
|
|
624
670
|
// time). One GROUP BY over the merged message view, mapped onto the same
|
|
625
671
|
// session-meta buckets as tokens so row sets stay identical.
|
|
626
672
|
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`) || [])) {
|
|
673
|
+
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
674
|
msgAgg[m.sid] = m;
|
|
629
675
|
}
|
|
630
676
|
const periodDays = {};
|
|
@@ -686,14 +732,16 @@ function buildReportFromDb(days) {
|
|
|
686
732
|
const meta = metaMap[sid] || { agent: 'unknown', provider: 'unknown', model: 'unknown' };
|
|
687
733
|
const agent = meta.agent || 'unknown';
|
|
688
734
|
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 };
|
|
735
|
+
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
736
|
agentAgg[agent].sessions.add(sid);
|
|
691
737
|
agentAgg[agent].input += ps.input; agentAgg[agent].output += ps.output;
|
|
692
738
|
agentAgg[agent].reasoning += ps.reasoning; agentAgg[agent].cacheRead += ps.cacheRead;
|
|
693
739
|
agentAgg[agent].cost += ps.cost;
|
|
694
|
-
const mg = msgAgg[sid] || { n: 0, o: 0, ms: 0 };
|
|
740
|
+
const mg = msgAgg[sid] || { n: 0, o: 0, ms: 0, rq: 0 };
|
|
695
741
|
agentAgg[agent].speedOut += mg.o; agentAgg[agent].speedMs += mg.ms; agentAgg[agent].activeMs += mg.ms;
|
|
696
742
|
agentAgg[agent].wallMs += Math.max(0, (meta.tu || 0) - (meta.tc || 0));
|
|
743
|
+
const mkA = marketOf({ input: ps.input, output: ps.output, reasoning: ps.reasoning, cacheRead: ps.cacheRead, cost: ps.cost }, meta.provider || 'unknown', meta.model || 'unknown');
|
|
744
|
+
if (mkA.market !== null) { agentAgg[agent].market += mkA.market; agentAgg[agent].saved += mkA.saved; }
|
|
697
745
|
if (!modelAgg[modelName]) modelAgg[modelName] = { sessions: new Set(), cost: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, speedOut: 0, speedMs: 0 };
|
|
698
746
|
modelAgg[modelName].sessions.add(sid);
|
|
699
747
|
modelAgg[modelName].input += ps.input; modelAgg[modelName].output += ps.output;
|
|
@@ -710,29 +758,37 @@ function buildReportFromDb(days) {
|
|
|
710
758
|
tok_reasoning: Math.round(m.reasoning), cache_read: Math.round(m.cacheRead),
|
|
711
759
|
speed: m.speedMs > 0 ? Math.round((m.speedOut / (m.speedMs / 1000)) * 10) / 10 : null,
|
|
712
760
|
wallMs: Math.round(m.wallMs), activeMs: Math.round(m.activeMs),
|
|
761
|
+
market: Math.round(m.market * 10000) / 10000, saved: Math.round(m.saved * 10000) / 10000,
|
|
713
762
|
}))
|
|
714
763
|
.sort((x, y) => y.cost - x.cost);
|
|
715
764
|
var pProviderRows = Object.entries(modelAgg)
|
|
716
765
|
.map(([name, m]) => {
|
|
717
766
|
const { provider, model } = splitModelName(name);
|
|
767
|
+
const mk = marketOf({ input: m.input, output: m.output, reasoning: m.reasoning, cacheRead: m.cacheRead, cost: m.cost }, provider, model);
|
|
718
768
|
return {
|
|
719
769
|
provider, model, sessions: m.sessions.size, cost: r4(m.cost),
|
|
720
770
|
tok_in: Math.round(m.input), tok_out: Math.round(m.output),
|
|
721
771
|
tok_reasoning: Math.round(m.reasoning), cache_read: Math.round(m.cacheRead),
|
|
722
772
|
speed: m.speedMs > 0 ? Math.round((m.speedOut / (m.speedMs / 1000)) * 10) / 10 : null,
|
|
773
|
+
market: mk.market, saved: mk.saved, pricedAs: mk.pricedAs,
|
|
723
774
|
};
|
|
724
775
|
})
|
|
725
776
|
.sort((x, y) => y.cost - x.cost);
|
|
726
777
|
var pSessionRows = sessRows
|
|
727
|
-
.map(({ sid, meta, ps, mg }) =>
|
|
778
|
+
.map(({ sid, meta, ps, mg }) => {
|
|
779
|
+
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');
|
|
780
|
+
return {
|
|
728
781
|
id: sid, title: (meta.title || '').slice(0, 40), agent: meta.agent || 'unknown',
|
|
729
782
|
provider: meta.provider || 'unknown', model: meta.model || 'unknown',
|
|
730
783
|
wallMs: Math.max(0, (meta.tu || 0) - (meta.tc || 0)),
|
|
731
784
|
activeMs: mg.ms || 0, messages: mg.n || 0,
|
|
732
785
|
tok_in: Math.round(ps.input), tok_out: Math.round(ps.output),
|
|
786
|
+
tok_reasoning: Math.round(mg.rq || 0),
|
|
733
787
|
cost: r4(ps.cost),
|
|
734
788
|
speed: (mg.ms || 0) > 0 ? Math.round(((mg.o || 0) / (mg.ms / 1000)) * 10) / 10 : null,
|
|
735
|
-
|
|
789
|
+
market: mkS.market, saved: mkS.saved, pricedAs: mkS.pricedAs,
|
|
790
|
+
};
|
|
791
|
+
})
|
|
736
792
|
.sort((x, y) => y.wallMs - x.wallMs)
|
|
737
793
|
.slice(0, 20);
|
|
738
794
|
} else {
|
|
@@ -741,6 +797,12 @@ function buildReportFromDb(days) {
|
|
|
741
797
|
var pSessionRows = [];
|
|
742
798
|
}
|
|
743
799
|
|
|
800
|
+
const sumMkt = (rows) => rows.reduce((s, r) => s + (r.market || 0), 0);
|
|
801
|
+
statsR.cost.marketTotal = Math.round(sumMkt(pProviderRows) * 10000) / 10000;
|
|
802
|
+
statsR.cost.savedTotal = Math.round((sumMkt(pProviderRows) - t.cost) * 10000) / 10000;
|
|
803
|
+
statsR.cost.savedPct = statsR.cost.marketTotal > 0 ? Math.round((statsR.cost.savedTotal / statsR.cost.marketTotal) * 1000) / 10 : null;
|
|
804
|
+
statsR.cost.priceAsOf = pricing.catalogInfo().ok ? new Date(pricing.catalogInfo().mtimeMs).toISOString() : null;
|
|
805
|
+
|
|
744
806
|
return {
|
|
745
807
|
label,
|
|
746
808
|
days,
|
|
@@ -748,6 +810,7 @@ function buildReportFromDb(days) {
|
|
|
748
810
|
agents: pAgentRows,
|
|
749
811
|
providers: pProviderRows,
|
|
750
812
|
sessions: pSessionRows,
|
|
813
|
+
priceAsOf: statsR.cost.priceAsOf,
|
|
751
814
|
generatedAt: now,
|
|
752
815
|
};
|
|
753
816
|
}
|
|
@@ -784,7 +847,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
784
847
|
for (const [k, v] of Object.entries(headers)) res.setHeader(k, v);
|
|
785
848
|
if (useGzip && payload.length > 512) {
|
|
786
849
|
res.setHeader('Content-Encoding', 'gzip');
|
|
787
|
-
const compressed = zlib.gzipSync(Buffer.from(payload), { level:
|
|
850
|
+
const compressed = zlib.gzipSync(Buffer.from(payload), { level: 1 });
|
|
788
851
|
res.end(compressed);
|
|
789
852
|
} else {
|
|
790
853
|
res.end(payload);
|