opencode-statboard 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 thumb2086
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,31 @@
1
+ # opencode-statboard
2
+
3
+ Real-time dashboard for your [opencode](https://opencode.ai) token usage and cost statistics, built with zero dependencies (pure Node.js + vanilla HTML/CSS/JS).
4
+
5
+ ## Features
6
+
7
+ - Live-updating overview: sessions, messages, total cost, tokens per session
8
+ - Token statistics: Input / Output / Cache Read / Cache Write
9
+ - Tool usage breakdown with percentage bars (collapsible)
10
+ - Per-model usage with cache read stats
11
+ - Daily trend chart (7D / 30D / 90D, 90D uses downsampling for speed)
12
+ - i18n: English + Traditional Chinese, auto-detects browser language
13
+
14
+ ## Requirements
15
+
16
+ - Node.js (tested on v24)
17
+ - [opencode](https://opencode.ai) CLI installed globally via npm
18
+ - No npm packages required
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ npm install -g opencode-statboard
24
+ opencode-dashboard
25
+ ```
26
+
27
+ Then open http://127.0.0.1:4868
28
+
29
+ ## License
30
+
31
+ MIT
package/package.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "opencode-statboard",
3
+ "version": "1.0.0",
4
+ "description": "Real-time dashboard for opencode token usage and cost statistics",
5
+ "main": "server.js",
6
+ "bin": {
7
+ "opencode-dashboard": "server.js"
8
+ },
9
+ "scripts": {
10
+ "start": "node server.js"
11
+ },
12
+ "keywords": ["opencode", "dashboard", "tokens", "usage", "statistics"],
13
+ "author": "thumb2086",
14
+ "license": "MIT",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/thumb2086/opencode-usage-dashboard"
18
+ }
19
+ }
@@ -0,0 +1,461 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>opencode Dashboard</title>
7
+ <style>
8
+ :root {
9
+ --bg: #0d1117; --panel: #161b22; --border: #30363d; --text: #e6edf3; --muted: #8b949e;
10
+ --in: #58a6ff; --out: #3fb950; --cache: #d29922; --cost: #f778ba; --tool: #a371f7;
11
+ }
12
+ * { box-sizing: border-box; margin: 0; padding: 0; }
13
+ body { background: var(--bg); color: var(--text); font-family: "Segoe UI", "Microsoft JhengHei", sans-serif; padding: 24px; }
14
+ header { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 10px; margin-bottom: 20px; }
15
+ h1 { font-size: 20px; font-weight: 600; }
16
+ h1 .dot { color: #3fb950; }
17
+ .status { display: flex; align-items: center; gap: 10px; color: var(--muted); font-size: 13px; }
18
+ .pill { padding: 4px 12px; border-radius: 999px; font-size: 12px; border: 1px solid var(--border); cursor: pointer; user-select: none; }
19
+ .pill.ok { color: #3fb950; border-color: #238636; background: rgba(63,185,80,.08); }
20
+ .pill.err { color: #f85149; border-color: #da3633; background: rgba(248,81,73,.08); }
21
+ .pill.lang { color: var(--text); border-color: var(--border); background: rgba(139,148,158,.08); }
22
+ .pill.lang:hover { background: rgba(139,148,158,.18); }
23
+ .range-btns { display: flex; gap: 4px; }
24
+ .range-btns .pill.active { color: var(--text); border-color: #58a6ff; background: rgba(88,166,255,.12); }
25
+ .range-btns .pill:not(.active) { color: var(--muted); border-color: var(--border); background: transparent; }
26
+ .range-btns .pill:not(.active):hover { background: rgba(139,148,158,.08); }
27
+ section { background: var(--panel); border: 1px solid var(--border); border-radius: 10px; padding: 18px; margin-bottom: 18px; }
28
+ h2 { font-size: 14px; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: .5px; margin-bottom: 14px; }
29
+ .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; }
30
+ .card { background: #0d1117; border: 1px solid var(--border); border-radius: 8px; padding: 14px; }
31
+ .card .v { font-size: 24px; font-weight: 700; margin-top: 4px; }
32
+ .card .l { font-size: 12px; color: var(--muted); }
33
+ .bar-row { display: grid; grid-template-columns: 150px 1fr 120px; align-items: center; gap: 12px; padding: 7px 0; font-size: 13px; }
34
+ .bar-row .name { color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
35
+ .bar-row .val { text-align: right; font-variant-numeric: tabular-nums; }
36
+ .track { background: #21262d; border-radius: 4px; height: 12px; overflow: hidden; }
37
+ .fill { height: 100%; border-radius: 4px; transition: width .6s ease; min-width: 1px; }
38
+ .stack { display: flex; height: 100%; }
39
+ .stack > div { height: 100%; }
40
+ .legend { display: flex; gap: 16px; font-size: 12px; color: var(--muted); margin-bottom: 12px; flex-wrap: wrap; }
41
+ .legend span { display: flex; align-items: center; gap: 6px; }
42
+ .sw { width: 12px; height: 12px; border-radius: 3px; display: inline-block; }
43
+ table { width: 100%; border-collapse: collapse; font-size: 13px; }
44
+ th, td { padding: 8px 10px; text-align: right; border-bottom: 1px solid var(--border); font-variant-numeric: tabular-nums; }
45
+ th:first-child, td:first-child { text-align: left; }
46
+ th { color: var(--muted); font-weight: 500; font-size: 12px; }
47
+ .chart { position: relative; display: flex; align-items: flex-end; gap: 2px; height: 200px; padding-top: 10px; }
48
+ .chart .col { flex: 1; display: flex; flex-direction: column; align-items: center; gap: 4px; height: 100%; justify-content: flex-end; min-width: 0; }
49
+ .chart .bars { display: flex; gap: 2px; align-items: flex-end; justify-content: center; height: 170px; width: 100%; }
50
+ .chart .bars > div { border-radius: 2px 2px 0 0; min-width: 4px; transition: height .4s ease; }
51
+ .chart .x { font-size: 10px; color: var(--muted); line-height: 1; }
52
+ .chart .tip { font-size: 10px; color: var(--muted); line-height: 1.2; text-align: center; }
53
+ .two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; }
54
+ @media (max-width: 800px) { .two-col { grid-template-columns: 1fr; } }
55
+ .error-banner { display: none; background: rgba(248,81,73,.1); border: 1px solid #da3633; color: #f85149; padding: 10px 14px; border-radius: 8px; margin-bottom: 16px; font-size: 13px; }
56
+ .error-banner.show { display: block; }
57
+ details.tool-section { background: var(--panel); border: 1px solid var(--border); border-radius: 10px; padding: 18px; margin-bottom: 18px; }
58
+ details.tool-section summary { cursor: pointer; list-style: none; display: flex; align-items: center; gap: 8px; }
59
+ details.tool-section summary::-webkit-details-marker { display: none; }
60
+ details.tool-section summary::before { content: '▸'; font-size: 12px; color: var(--muted); transition: transform .2s; }
61
+ details.tool-section[open] summary::before { transform: rotate(90deg); }
62
+ details.tool-section summary h2 { margin: 0; }
63
+ .skeleton { background: linear-gradient(90deg, #21262d 25%, #30363d 50%, #21262d 75%); background-size: 200% 100%; animation: shimmer 1.5s infinite; border-radius: 4px; }
64
+ @keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
65
+ .skeleton-text { height: 1em; margin: 4px 0; }
66
+ .skeleton-card { height: 60px; }
67
+ .trend-bar { position: absolute; bottom: 0; border-radius: 2px 2px 0 0; transition: height .4s ease; }
68
+ .trend-bar-cache { left: 0; right: 0; opacity: .2; }
69
+ .trend-bar-input { left: 25%; width: 22%; z-index: 1; }
70
+ .trend-bar-output { left: 53%; width: 22%; z-index: 1; }
71
+ </style>
72
+ </head>
73
+ <body>
74
+ <header>
75
+ <h1><span class="dot">●</span> <span data-i18n="title">opencode Dashboard</span></h1>
76
+ <div class="status">
77
+ <span id="updated">Loading…</span>
78
+ <span class="pill ok" id="pill" data-i18n="live">Live</span>
79
+ <span class="pill lang" id="langBtn" onclick="toggleLang()"></span>
80
+ </div>
81
+ </header>
82
+
83
+ <div class="error-banner" id="errbanner"></div>
84
+
85
+ <section>
86
+ <h2 data-i18n="overview">OVERVIEW</h2>
87
+ <div class="cards">
88
+ <div class="card"><div class="l" data-i18n="sessions">Sessions</div><div class="v" id="ov-sessions">—</div></div>
89
+ <div class="card"><div class="l" data-i18n="messages">Messages</div><div class="v" id="ov-messages">—</div></div>
90
+ <div class="card"><div class="l" data-i18n="days">Days</div><div class="v" id="ov-days">—</div></div>
91
+ <div class="card"><div class="l" data-i18n="totalCost">Total Cost</div><div class="v" id="ov-total">—</div></div>
92
+ <div class="card"><div class="l" data-i18n="avgCostDay">Avg Cost / Day</div><div class="v" id="ov-avgday">—</div></div>
93
+ <div class="card"><div class="l" data-i18n="avgTokensSession">Avg Tokens / Session</div><div class="v" id="ov-avg">—</div></div>
94
+ <div class="card"><div class="l" data-i18n="medianTokensSession">Median Tokens / Session</div><div class="v" id="ov-med">—</div></div>
95
+ </div>
96
+ </section>
97
+
98
+ <section>
99
+ <h2 data-i18n="tokenStats">TOKEN STATISTICS</h2>
100
+ <div class="legend">
101
+ <span><i class="sw" style="background:var(--in)"></i>Input</span>
102
+ <span><i class="sw" style="background:var(--out)"></i>Output</span>
103
+ <span><i class="sw" style="background:var(--cache)"></i>Cache Read</span>
104
+ <span><i class="sw" style="background:var(--cost)"></i>Cache Write</span>
105
+ </div>
106
+ <div id="token-bars"></div>
107
+ </section>
108
+
109
+ <details class="tool-section" open>
110
+ <summary><h2 data-i18n="toolUsage">TOOL USAGE</h2></summary>
111
+ <div id="tool-bars"></div>
112
+ </details>
113
+
114
+ <section>
115
+ <h2 data-i18n="modelUsage">MODEL USAGE</h2>
116
+ <table>
117
+ <thead>
118
+ <tr><th data-i18n="thModel">Model</th><th data-i18n="thMsgs">Messages</th><th>Input</th><th>Output</th><th>Cache Read</th><th style="width:26%" data-i18n="thUsage">Usage</th><th data-i18n="thCost">Cost</th></tr>
119
+ </thead>
120
+ <tbody id="model-rows"></tbody>
121
+ </table>
122
+ </section>
123
+
124
+ <section>
125
+ <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px">
126
+ <h2 id="trendTitle" style="margin:0"></h2>
127
+ <div class="range-btns" id="rangeBtns">
128
+ <span class="pill active" data-days="7" onclick="setRange(7)">7D</span>
129
+ <span class="pill" data-days="30" onclick="setRange(30)">30D</span>
130
+ <span class="pill" data-days="90" onclick="setRange(90)">90D</span>
131
+ </div>
132
+ </div>
133
+ <div style="display:flex;gap:24px;flex-wrap:wrap">
134
+ <div style="flex:1;min-width:300px">
135
+ <div class="legend">
136
+ <span><i class="sw" style="background:var(--in)"></i><span data-i18n="inputDay">Input / Day</span></span>
137
+ <span><i class="sw" style="background:var(--out)"></i><span data-i18n="outputDay">Output / Day</span></span>
138
+ <span><i class="sw" style="background:var(--cache)"></i><span data-i18n="cacheReadDay">Cache Read / Day</span></span>
139
+ <span id="trendStatus" style="color:var(--cache);font-size:11px"></span>
140
+ </div>
141
+ <div class="chart" id="trendTokensChart"><div class="bars" id="trend-tokens"></div></div>
142
+ <div class="bars" id="trend-token-x" style="height:auto;display:flex;justify-content:space-around;margin-top:4px"></div>
143
+ </div>
144
+ <div id="costSection" style="flex:1;min-width:200px">
145
+ <div class="legend"><span><i class="sw" style="background:var(--cost)"></i><span data-i18n="costDay">Cost / Day</span></span></div>
146
+ <div class="chart" id="trendCostChart"><div class="bars" id="trend-cost"></div></div>
147
+ <div class="bars" id="trend-cost-x" style="height:auto;display:flex;justify-content:space-around;margin-top:4px"></div>
148
+ <div id="costZeroNote" style="display:none;font-size:12px;color:var(--muted);padding:20px 0;text-align:center"></div>
149
+ </div>
150
+ </div>
151
+ </section>
152
+
153
+ <section>
154
+ <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px">
155
+ <h2 data-i18n="report" style="margin:0">USAGE REPORT</h2>
156
+ <div class="range-btns" id="reportBtns">
157
+ <span class="pill active" data-days="1" onclick="loadReport(1)" data-i18n="daily">Daily</span>
158
+ <span class="pill" data-days="7" onclick="loadReport(7)" data-i18n="weekly">Weekly</span>
159
+ <span class="pill" data-days="30" onclick="loadReport(30)" data-i18n="monthly">Monthly</span>
160
+ </div>
161
+ </div>
162
+ <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>
163
+ </section>
164
+
165
+ <script>
166
+ const STRINGS = {
167
+ en: {
168
+ title: 'opencode Dashboard',
169
+ overview: 'OVERVIEW',
170
+ sessions: 'Sessions', messages: 'Messages', days: 'Days',
171
+ totalCost: 'Total Cost', avgCostDay: 'Avg Cost / Day',
172
+ avgTokensSession: 'Avg Tokens / Session', medianTokensSession: 'Median Tokens / Session',
173
+ tokenStats: 'TOKEN STATISTICS', toolUsage: 'TOOL USAGE', modelUsage: 'MODEL USAGE',
174
+ thModel: 'Model', thMsgs: 'Messages', thUsage: 'Usage', thCost: 'Cost',
175
+ dailyTrend: 'DAILY TREND ({days} DAYS)',
176
+ inputDay: 'Input / Day', outputDay: 'Output / Day', cacheReadDay: 'Cache Read / Day', costDay: 'Cost / Day',
177
+ report: 'USAGE REPORT', daily: 'Daily', weekly: 'Weekly', monthly: 'Monthly',
178
+ updating: 'updating…', generating: 'Generating trend data…', cachedAt: 'cached at', allFree: 'All models free — no cost recorded',
179
+ live: 'Live', loading: 'Loading…', lastUpdated: 'Last updated', dataAgo: 'data generated',
180
+ statsFail: 'Failed to read opencode stats', connFail: 'Connection failed',
181
+ langBtn: '繁中',
182
+ },
183
+ 'zh-TW': {
184
+ title: 'opencode 用量儀表板',
185
+ overview: '概覽',
186
+ sessions: '工作階段', messages: '訊息數', days: '使用天數',
187
+ totalCost: '總費用', avgCostDay: '平均費用 / 天',
188
+ avgTokensSession: '平均 tokens / 場', medianTokensSession: '中位數 tokens / 場',
189
+ tokenStats: 'Tokens 統計', toolUsage: '工具使用', modelUsage: '模型使用',
190
+ thModel: '模型', thMsgs: '訊息', thUsage: '用量', thCost: '費用',
191
+ dailyTrend: '近 {days} 天趨勢',
192
+ inputDay: 'Input / 天', outputDay: 'Output / 天', cacheReadDay: 'Cache Read / 天', costDay: '費用 / 天',
193
+ report: '用量報告', daily: '每日', weekly: '每週', monthly: '每月',
194
+ updating: '更新中…', generating: '趨勢資料產生中…', cachedAt: '快取於', allFree: '全部使用免費模型,無費用紀錄',
195
+ live: '即時更新', loading: '載入中…', lastUpdated: '更新於', dataAgo: '數據產生於',
196
+ statsFail: 'opencode stats 讀取失敗', connFail: '連線失敗',
197
+ langBtn: 'EN',
198
+ }
199
+ };
200
+
201
+ let lang = localStorage.getItem('lang') ||
202
+ (navigator.language.startsWith('zh') ? 'zh-TW' : 'en');
203
+
204
+ const t = (key) => (STRINGS[lang] || STRINGS.en)[key] || key;
205
+
206
+ function applyI18n() {
207
+ document.documentElement.lang = lang === 'zh-TW' ? 'zh-Hant' : 'en';
208
+ document.querySelectorAll('[data-i18n]').forEach((el) => {
209
+ el.textContent = t(el.dataset.i18n);
210
+ });
211
+ $('langBtn').textContent = t('langBtn');
212
+ $('updated').textContent = t('loading');
213
+ $('trendTitle').textContent = t('dailyTrend').replace('{days}', currentDays);
214
+ }
215
+
216
+ function toggleLang() {
217
+ lang = lang === 'en' ? 'zh-TW' : 'en';
218
+ localStorage.setItem('lang', lang);
219
+ applyI18n();
220
+ }
221
+
222
+ const $ = (id) => document.getElementById(id);
223
+ let currentDays = parseInt(localStorage.getItem('trendDays') || '7', 10);
224
+
225
+ const fmt = (n) => {
226
+ if (n == null || isNaN(n)) return '—';
227
+ if (n >= 1e9) return (n / 1e9).toFixed(2) + 'B';
228
+ if (n >= 1e6) return (n / 1e6).toFixed(1) + 'M';
229
+ if (n >= 1e3) return (n / 1e3).toFixed(1) + 'K';
230
+ return String(Math.round(n));
231
+ };
232
+ const fmtCost = (n) => (n == null || isNaN(n)) ? '—' : '$' + n.toFixed(2);
233
+
234
+ function barRow(name, value, max, color) {
235
+ const pct = max > 0 ? Math.max(0.5, (value / max) * 100) : 0;
236
+ return `<div class="bar-row"><div class="name">${name}</div>
237
+ <div class="track"><div class="fill" style="width:${pct}%;background:${color}"></div></div>
238
+ <div class="val">${fmt(value)}</div></div>`;
239
+ }
240
+
241
+ function render(d, models, trend) {
242
+ const o = d.overview || {};
243
+ $('ov-sessions').textContent = fmt(o.sessions);
244
+ $('ov-messages').textContent = fmt(o.messages);
245
+ $('ov-days').textContent = fmt(o.days);
246
+ $('ov-total').textContent = fmtCost(d.cost && d.cost.total);
247
+ $('ov-avgday').textContent = fmtCost(d.cost && d.cost.avgDay);
248
+ $('ov-avg').textContent = fmt(d.cost && d.cost.avgTokensSession);
249
+ $('ov-med').textContent = fmt(d.cost && d.cost.medianTokensSession);
250
+
251
+ if (d.cost) {
252
+ const vals = [d.cost.input, d.cost.output, d.cost.cacheRead, d.cost.cacheWrite];
253
+ const max = Math.max(...vals.filter(Number.isFinite));
254
+ $('token-bars').innerHTML =
255
+ barRow('Input', d.cost.input, max, 'var(--in)') +
256
+ barRow('Output', d.cost.output, max, 'var(--out)') +
257
+ barRow('Cache Read', d.cost.cacheRead, max, 'var(--cache)') +
258
+ barRow('Cache Write', d.cost.cacheWrite, max, 'var(--cost)');
259
+ }
260
+
261
+ if (d.tools && d.tools.length) {
262
+ $('tool-bars').innerHTML = d.tools.map((tool) => barRow(tool.name, tool.count, d.tools[0].count, 'var(--tool)')).join('');
263
+ }
264
+
265
+ const modelList = (models && models.length ? models : (d.models || []));
266
+ if (modelList.length) {
267
+ const total = modelList.reduce((s, m) => s + m.input, 0);
268
+ $('model-rows').innerHTML = modelList.map((m) => {
269
+ const iw = total > 0 ? (m.input / total) * 100 : 0;
270
+ const ow = total > 0 ? (m.output / total) * 100 : 0;
271
+ const cw = total > 0 ? (m.cacheRead / total) * 100 : 0;
272
+ const w = Math.max(iw + ow + cw, 1);
273
+ return `<tr><td>${m.name}</td><td>${fmt(m.messages)}</td><td>${fmt(m.input)}</td>
274
+ <td>${fmt(m.output)}</td><td>${fmt(m.cacheRead)}</td>
275
+ <td><div class="track" style="height:10px"><div class="stack">
276
+ <div style="width:${(iw / w) * 100}%;background:var(--in)"></div>
277
+ <div style="width:${(ow / w) * 100}%;background:var(--out)"></div>
278
+ <div style="width:${(cw / w) * 100}%;background:var(--cache)"></div>
279
+ </div></div></td>
280
+ <td>${fmtCost(m.cost)}</td></tr>`;
281
+ }).join('');
282
+ }
283
+
284
+ if (trend && trend.input && trend.input.length) {
285
+ renderTrend(trend);
286
+ $('trendStatus').textContent = trend.stale ? ' ⟳ ' + t('updating') : '';
287
+ } else {
288
+ $('trend-tokens').innerHTML = '';
289
+ $('trend-token-x').innerHTML = '';
290
+ $('trend-cost').innerHTML = '';
291
+ $('trend-cost-x').innerHTML = '';
292
+ $('costZeroNote').style.display = 'none';
293
+ $('costSection').querySelector('.legend').style.display = '';
294
+ $('trendCostChart').style.display = '';
295
+ $('trend-cost-x').style.display = '';
296
+ $('trendStatus').textContent = '⏳ ' + t('generating');
297
+ }
298
+ }
299
+
300
+ function renderTrend(data) {
301
+ const n = data.labels.length;
302
+ const maxAll = Math.max(...data.input, ...data.output, ...data.cacheRead);
303
+ const hasCost = data.cost.some((v) => v > 0);
304
+
305
+ $('trend-tokens').innerHTML = data.labels.map((l, i) => {
306
+ const hi = maxAll > 0 ? (data.input[i] / maxAll) * 100 : 0;
307
+ const ho = maxAll > 0 ? (data.output[i] / maxAll) * 100 : 0;
308
+ const hc = maxAll > 0 ? (data.cacheRead[i] / maxAll) * 100 : 0;
309
+ const tip = l + ': In ' + fmt(data.input[i]) + ' · Out ' + fmt(data.output[i]) + ' · Cache ' + fmt(data.cacheRead[i]);
310
+ return `<div class="col" title="${tip}">
311
+ <div style="display:flex;gap:2px;align-items:flex-end;width:100%;height:170px;justify-content:center">
312
+ <div style="position:relative;width:100%;height:100%">
313
+ <div class="trend-bar trend-bar-cache" style="height:${Math.max(hc, 1)}%;background:var(--cache)"></div>
314
+ <div class="trend-bar trend-bar-input" style="height:${Math.max(hi, 1)}%;background:var(--in)"></div>
315
+ <div class="trend-bar trend-bar-output" style="height:${Math.max(ho, 1)}%;background:var(--out)"></div>
316
+ </div>
317
+ </div>
318
+ </div>`;
319
+ }).join('');
320
+
321
+ const labelStep = Math.max(1, Math.ceil(n / 14));
322
+ $('trend-token-x').innerHTML = data.labels.map((l, i) =>
323
+ `<span class="x" style="flex:1;text-align:center;${i % labelStep === 0 ? '' : 'visibility:hidden'}">${l}</span>`).join('');
324
+
325
+ if (hasCost) {
326
+ $('costSection').querySelector('.legend').style.display = '';
327
+ $('trendCostChart').style.display = '';
328
+ $('trend-cost-x').style.display = '';
329
+ $('costZeroNote').style.display = 'none';
330
+ const maxCost = Math.max(...data.cost);
331
+ $('trend-cost').innerHTML = data.labels.map((l, i) => {
332
+ const h = maxCost > 0 ? (data.cost[i] / maxCost) * 100 : 0;
333
+ const tip = l + ': $' + (data.cost[i] || 0).toFixed(2);
334
+ return `<div class="col" title="${tip}">
335
+ <div style="display:flex;align-items:flex-end;width:100%;height:170px;justify-content:center">
336
+ <div style="width:50%;height:${Math.max(h, 1)}%;background:var(--cost);border-radius:2px 2px 0 0"></div>
337
+ </div>
338
+ </div>`;
339
+ }).join('');
340
+ $('trend-cost-x').innerHTML = data.labels.map((l, i) =>
341
+ `<span class="x" style="flex:1;text-align:center;${i % labelStep === 0 ? '' : 'visibility:hidden'}">${l}</span>`).join('');
342
+ } else {
343
+ $('costSection').querySelector('.legend').style.display = 'none';
344
+ $('trendCostChart').style.display = 'none';
345
+ $('trend-cost-x').style.display = 'none';
346
+ $('costZeroNote').style.display = '';
347
+ $('costZeroNote').textContent = t('allFree');
348
+ }
349
+ }
350
+
351
+ async function poll() {
352
+ try {
353
+ const r = await fetch('/api/stats?days=' + currentDays + '&_=' + Date.now(), { cache: 'no-store' });
354
+ const j = await r.json();
355
+ if (!j.ok) {
356
+ $('errbanner').textContent = t('statsFail') + ': ' + (j.error || '');
357
+ $('errbanner').classList.add('show');
358
+ $('pill').textContent = t('statsFail');
359
+ $('pill').className = 'pill err';
360
+ return;
361
+ }
362
+ $('errbanner').classList.remove('show');
363
+ $('pill').textContent = t('live');
364
+ $('pill').className = 'pill ok';
365
+ render(j.data, j.models, j.trend);
366
+ const ago = Math.round((Date.now() - (j.generatedAt || 0)) / 1000);
367
+ const time = new Date().toLocaleTimeString(lang === 'zh-TW' ? 'zh-TW' : 'en', { hour12: false });
368
+ $('updated').textContent = t('lastUpdated') + ' ' + time + ' (' + t('dataAgo') + ' ' + ago + 's)';
369
+ } catch (e) {
370
+ $('updated').textContent = t('connFail') + ': ' + e.message;
371
+ }
372
+ }
373
+
374
+ function setRange(days) {
375
+ currentDays = days;
376
+ localStorage.setItem('trendDays', days);
377
+ document.querySelectorAll('#rangeBtns .pill').forEach((el) => {
378
+ el.classList.toggle('active', parseInt(el.dataset.days, 10) === days);
379
+ });
380
+ $('trendTitle').textContent = t('dailyTrend').replace('{days}', days);
381
+ poll();
382
+ }
383
+
384
+ let reportLoading = false;
385
+ let reportRetry = 0;
386
+ const MAX_REPORT_RETRIES = 12;
387
+
388
+ function formatReport(jr) {
389
+ const genTime = jr.generatedAt ? new Date(jr.generatedAt).toLocaleTimeString(lang === 'zh-TW' ? 'zh-TW' : 'en', { hour12: false }) : '?';
390
+ const cachedNote = jr.stale ? ' [⟳ ' + t('updating') + ']' : ' [' + t('cachedAt') + ' ' + genTime + ']';
391
+ const fmtCost = (n) => { const v = parseFloat(n); if (isNaN(v)) return '—'; return v === 0 ? '$0.00' : '$' + v.toFixed(4); };
392
+ const fmtT = (n) => { const v = parseInt(n, 10); if (isNaN(v)) return '—'; if (v >= 1e9) return (v/1e9).toFixed(2)+'B'; if (v >= 1e6) return (v/1e6).toFixed(1)+'M'; if (v >= 1e3) return (v/1e3).toFixed(1)+'K'; return String(v); };
393
+ const pad = (s, w) => { s = String(s); return s.length >= w ? s : s + ' '.repeat(w - s.length); };
394
+ const rpad = (s, w) => { s = String(s); return s.length >= w ? s : ' '.repeat(w - s.length) + s; };
395
+ let out = '';
396
+ out += 'OPENCODE USAGE STATEMENT\n';
397
+ out += 'Period: ' + jr.label + ' | Last ' + jr.days + ' day(s)' + cachedNote + '\n';
398
+ out += '---\n';
399
+ const s = jr.stats;
400
+ if (s && s.ok) {
401
+ const o = s.overview || {};
402
+ const c = s.cost || {};
403
+ out += 'SUMMARY\n';
404
+ out += ' Sessions ........... ' + (o.sessions || 0) + '\n';
405
+ out += ' Messages ........... ' + (o.messages || 0) + '\n';
406
+ out += ' Total Cost ......... $' + (c.total || 0).toFixed(2) + '\n';
407
+ out += ' Tokens In/Out ...... ' + fmtT(c.input) + ' / ' + fmtT(c.output) + '\n';
408
+ out += ' Cache Read/Write ... ' + fmtT(c.cacheRead) + ' / ' + fmtT(c.cacheWrite) + '\n';
409
+ out += '\n';
410
+ }
411
+ if (jr.providers && jr.providers.length) {
412
+ out += 'PROVIDERS & MODELS\n';
413
+ jr.providers.forEach((p) => {
414
+ 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) + '\n';
415
+ });
416
+ out += '\n';
417
+ }
418
+ if (jr.agents && jr.agents.length) {
419
+ out += 'AGENTS\n';
420
+ jr.agents.forEach((a) => {
421
+ 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) + '\n';
422
+ });
423
+ }
424
+ return out || 'No data for this period.';
425
+ }
426
+
427
+ async function loadReport(days) {
428
+ if (reportLoading) return;
429
+ reportLoading = true;
430
+ document.querySelectorAll('#reportBtns .pill').forEach((el) => {
431
+ el.classList.toggle('active', parseInt(el.dataset.days, 10) === days);
432
+ });
433
+ try {
434
+ const r = await fetch('/api/report?days=' + days + '&_=' + Date.now(), { cache: 'no-store' });
435
+ const j = await r.json();
436
+ if (!j.ok) { $('reportContent').textContent = 'Error'; reportLoading = false; return; }
437
+ if (!j.ready || !j.report) {
438
+ $('reportContent').textContent = '⏳ ' + t('generating') + '…';
439
+ reportRetry++;
440
+ if (reportRetry < MAX_REPORT_RETRIES) {
441
+ const delay = Math.min(1000 * Math.pow(1.5, reportRetry), 15000);
442
+ setTimeout(() => loadReport(days), delay);
443
+ }
444
+ reportLoading = false;
445
+ return;
446
+ }
447
+ reportRetry = 0;
448
+ $('reportContent').textContent = formatReport(j.report);
449
+ } catch (e) {
450
+ $('reportContent').textContent = t('connFail') + ': ' + e.message;
451
+ }
452
+ reportLoading = false;
453
+ }
454
+
455
+ applyI18n();
456
+ poll();
457
+ setInterval(poll, 15000);
458
+ loadReport(1);
459
+ </script>
460
+ </body>
461
+ </html>
package/server.js ADDED
@@ -0,0 +1,374 @@
1
+ #!/usr/bin/env node
2
+ const { execFile } = require('child_process');
3
+ const http = require('http');
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+
7
+ const PORT = 4868;
8
+ const REFRESH_MS = 15000;
9
+ const TREND_MS = 10 * 60 * 1000;
10
+ const REPORT_TTL = 10 * 60 * 1000;
11
+ const CACHE_CLEANUP_MS = 5 * 60 * 1000;
12
+
13
+ const EXE = (() => {
14
+ const candidates = [
15
+ path.join(process.env.APPDATA || '', 'npm', 'node_modules', 'opencode-ai', 'bin', 'opencode.exe'),
16
+ ];
17
+ for (const c of candidates) if (fs.existsSync(c)) return c;
18
+ return 'opencode';
19
+ })();
20
+
21
+ const state = { data: null, busy: false, error: null, updatedAt: 0, models: null, modelsBusy: false };
22
+
23
+ let indexHtmlCache = null;
24
+
25
+ function loadIndexHtml(callback) {
26
+ if (indexHtmlCache) return callback(null, indexHtmlCache);
27
+ fs.readFile(path.join(__dirname, 'public', 'index.html'), 'utf8', (err, data) => {
28
+ if (err) return callback(err);
29
+ indexHtmlCache = data;
30
+ callback(null, data);
31
+ });
32
+ }
33
+
34
+ function run(args, timeout = 120000) {
35
+ return new Promise((resolve) => {
36
+ execFile(EXE, args, { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, windowsHide: true, timeout }, (err, stdout) => {
37
+ if (err) return resolve({ ok: false, err: err.message, out: stdout || '' });
38
+ resolve({ ok: true, out: stdout });
39
+ });
40
+ });
41
+ }
42
+
43
+ const trendCache = {};
44
+ const trendBusy = {};
45
+ const trendPending = {};
46
+
47
+ function cleanExpiredCache(cache, ttl) {
48
+ const now = Date.now();
49
+ for (const key of Object.keys(cache)) {
50
+ if (cache[key] && cache[key].generatedAt && now - cache[key].generatedAt > ttl) {
51
+ delete cache[key];
52
+ }
53
+ }
54
+ }
55
+
56
+ async function generateTrend(days, retries = 2) {
57
+ const step = days > 30 ? 3 : 1;
58
+ const points = Math.ceil(days / step);
59
+ const results = new Array(points);
60
+ let next = 0;
61
+ const worker = async () => {
62
+ while (next < points) {
63
+ const i = next++;
64
+ const d = i * step + 1;
65
+ results[i] = await runStats(['stats', '--days', String(Math.min(d, days))]);
66
+ }
67
+ };
68
+ await Promise.all(Array.from({ length: 4 }, worker));
69
+ if (results.some((r) => !r)) {
70
+ if (retries > 0) {
71
+ await new Promise((r) => setTimeout(r, 1000));
72
+ return generateTrend(days, retries - 1);
73
+ }
74
+ return null;
75
+ }
76
+ const rows = results;
77
+ const first = rows[0];
78
+ const buckets = [{
79
+ sessions: first.overview.sessions,
80
+ messages: first.overview.messages,
81
+ total: first.cost.total,
82
+ input: first.cost.input,
83
+ output: first.cost.output,
84
+ cacheRead: first.cost.cacheRead,
85
+ }];
86
+ for (let i = 1; i < rows.length; i++) buckets.push(sub(rows[i], rows[i - 1]));
87
+ const now = Date.now();
88
+ return {
89
+ generatedAt: now,
90
+ step,
91
+ labels: buckets.map((_, i) => {
92
+ const d = new Date(now - (i * step) * 86400000);
93
+ return (d.getMonth() + 1) + '/' + d.getDate();
94
+ }),
95
+ sessions: buckets.map((b) => b.sessions),
96
+ messages: buckets.map((b) => b.messages),
97
+ input: buckets.map((b) => b.input),
98
+ output: buckets.map((b) => b.output),
99
+ cacheRead: buckets.map((b) => b.cacheRead),
100
+ cost: buckets.map((b) => b.total),
101
+ };
102
+ }
103
+
104
+ function refreshTrend(days) {
105
+ const key = String(days);
106
+ const hit = trendCache[key];
107
+ const fresh = hit && Date.now() - hit.generatedAt < TREND_MS;
108
+ if (fresh) return { trend: hit, pending: null };
109
+ let pending = trendPending[key];
110
+ if (!pending) {
111
+ pending = generateTrend(days).then((t) => {
112
+ if (t) trendCache[key] = t;
113
+ }).catch(() => {}).finally(() => {
114
+ delete trendBusy[key];
115
+ delete trendPending[key];
116
+ });
117
+ trendPending[key] = pending;
118
+ trendBusy[key] = true;
119
+ }
120
+ return { trend: hit ? Object.assign({}, hit, { stale: true }) : null, pending };
121
+ }
122
+
123
+ const clean = (s) => String(s).replace(/[^\x20-\x7E\n]/g, '');
124
+
125
+ function toNum(s) {
126
+ const t = String(s).replace(/,/g, '').trim();
127
+ const m = /^([\d.]+)([KMB])?$/i.exec(t);
128
+ if (!m) return NaN;
129
+ let v = parseFloat(m[1]);
130
+ if (m[2]) v *= { K: 1e3, M: 1e6, B: 1e9 }[m[2].toUpperCase()];
131
+ return v;
132
+ }
133
+
134
+ const money = (s) => {
135
+ const m = /([\d.]+)/.exec(String(s));
136
+ return m ? parseFloat(m[1]) : NaN;
137
+ };
138
+
139
+ function parseStats(text) {
140
+ const c = clean(text);
141
+ const grab = (re) => { const m = re.exec(c); return m ? m[1] : null; };
142
+ const out = {
143
+ overview: {
144
+ sessions: toNum(grab(/Sessions\s+([\d,]+)/)),
145
+ messages: toNum(grab(/Messages\s+([\d,]+)/)),
146
+ days: toNum(grab(/Days\s+([\d,]+)/)),
147
+ },
148
+ cost: {
149
+ total: money(grab(/Total Cost\s*\$([\d.]+)/)),
150
+ avgDay: money(grab(/Avg Cost\/Day\s*\$([\d.]+)/)),
151
+ avgTokensSession: toNum(grab(/Avg Tokens\/Session\s+([\d.]+[KMB]?)/)),
152
+ medianTokensSession: toNum(grab(/Median Tokens\/Session\s+([\d.]+[KMB]?)/)),
153
+ input: toNum(grab(/^Input\s+([\d.]+[KMB]?)/m)),
154
+ output: toNum(grab(/^Output\s+([\d.]+[KMB]?)/m)),
155
+ cacheRead: toNum(grab(/^Cache Read\s+([\d.]+[KMB]?)/m)),
156
+ cacheWrite: toNum(grab(/^Cache Write\s+([\d.]+[KMB]?)/m)),
157
+ },
158
+ tools: [],
159
+ models: [],
160
+ };
161
+
162
+ for (const line of c.split('\n')) {
163
+ const m = /^\s*([\w.\-]+)\s+([\d,]+)\s*\(\s*([\d.]+)%\)/.exec(line);
164
+ if (m) out.tools.push({ name: m[1], count: parseInt(m[2].replace(/,/g, ''), 10), pct: parseFloat(m[3]) });
165
+ }
166
+
167
+ let cur = null;
168
+ const setv = (cur, line, re, key, isMoney) => {
169
+ const m = re.exec(line);
170
+ if (m) cur[key] = isMoney ? money(m[1]) : toNum(m[1]);
171
+ };
172
+ for (const line of c.split('\n')) {
173
+ const name = /^\s*([a-zA-Z0-9_.\-]+\/[a-zA-Z0-9_.\-]+)\s*$/.exec(line);
174
+ if (name) {
175
+ cur = { name: name[1], messages: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
176
+ out.models.push(cur);
177
+ continue;
178
+ }
179
+ if (!cur) continue;
180
+ setv(cur, line, /Messages\s+([\d,]+)/, 'messages', false);
181
+ setv(cur, line, /Input Tokens\s+([\d.]+[KMB]?)/, 'input', false);
182
+ setv(cur, line, /Output Tokens\s+([\d.]+[KMB]?)/, 'output', false);
183
+ setv(cur, line, /Cache Read\s+([\d.]+[KMB]?)/, 'cacheRead', false);
184
+ setv(cur, line, /Cache Write\s+([\d.]+[KMB]?)/, 'cacheWrite', false);
185
+ setv(cur, line, /Cost\s+(\$[\d.]+)/, 'cost', true);
186
+ }
187
+ return out;
188
+ }
189
+
190
+ function validRow(p) {
191
+ return Number.isFinite(p.overview.sessions) && Number.isFinite(p.overview.messages);
192
+ }
193
+
194
+ async function runStats(args) {
195
+ const r = await run(args);
196
+ if (!r.ok) return null;
197
+ const p = parseStats(r.out);
198
+ if (!validRow(p)) return null;
199
+ return Object.assign({ ok: true }, p);
200
+ }
201
+
202
+ async function refresh() {
203
+ if (state.busy) return;
204
+ state.busy = true;
205
+ const p = await runStats(['stats']);
206
+ if (p) {
207
+ state.data = p;
208
+ state.error = null;
209
+ state.updatedAt = Date.now();
210
+ } else {
211
+ state.error = state.error || 'opencode stats failed';
212
+ }
213
+ state.busy = false;
214
+ }
215
+
216
+ async function refreshModels() {
217
+ if (state.modelsBusy) return;
218
+ state.modelsBusy = true;
219
+ const p = await runStats(['stats', '--models', '10']);
220
+ if (p) state.models = p.models;
221
+ state.modelsBusy = false;
222
+ }
223
+
224
+ function clamp(n) {
225
+ return Number.isFinite(n) && n > 0 ? n : 0;
226
+ }
227
+
228
+ function safeNum(v) {
229
+ return Number.isFinite(v) ? v : 0;
230
+ }
231
+
232
+ function sub(a, b) {
233
+ return {
234
+ sessions: clamp(safeNum(a.overview.sessions) - safeNum(b.overview.sessions)),
235
+ messages: clamp(safeNum(a.overview.messages) - safeNum(b.overview.messages)),
236
+ total: clamp(safeNum(a.cost.total) - safeNum(b.cost.total)),
237
+ input: clamp(safeNum(a.cost.input) - safeNum(b.cost.input)),
238
+ output: clamp(safeNum(a.cost.output) - safeNum(b.cost.output)),
239
+ cacheRead: clamp(safeNum(a.cost.cacheRead) - safeNum(b.cost.cacheRead)),
240
+ };
241
+ }
242
+
243
+ const reportCache = {};
244
+ const reportBusy = {};
245
+
246
+ function parseTSV(text) {
247
+ if (!text) return [];
248
+ const cleaned = text.replace(/[^\x20-\x7E\n\t]/g, '');
249
+ const lines = cleaned.trim().split('\n');
250
+ if (lines.length < 2) return [];
251
+ const headers = lines[0].split('\t');
252
+ return lines.slice(1).map((line) => {
253
+ const cols = line.split('\t');
254
+ const obj = {};
255
+ headers.forEach((h, i) => { obj[h.trim()] = (cols[i] || '').trim(); });
256
+ return obj;
257
+ });
258
+ }
259
+
260
+ async function buildReport(days) {
261
+ const label = days <= 1 ? 'Daily' : days <= 7 ? 'Weekly' : 'Monthly';
262
+ let statsR = await runStats(['stats', '--days', String(days), '--models', '20']);
263
+ if (!statsR) {
264
+ await new Promise((r) => setTimeout(r, 2000));
265
+ statsR = await runStats(['stats', '--days', String(days), '--models', '20']);
266
+ }
267
+ const [agentR, modelR] = await Promise.all([
268
+ run(['db', `SELECT agent, COUNT(*) AS sessions, ROUND(SUM(cost),4) AS cost, SUM(tokens_input) AS tok_in, SUM(tokens_output) AS tok_out, SUM(tokens_cache_read) AS cache_read FROM session WHERE agent IS NOT NULL AND time_updated >= (strftime('%s','now','-${days} day') * 1000) GROUP BY agent ORDER BY cost DESC;`, '--format', 'tsv']),
269
+ run(['db', `SELECT json_extract(model,'$.providerID') AS provider, json_extract(model,'$.id') AS model, COUNT(*) AS sessions, ROUND(SUM(cost),4) AS cost, SUM(tokens_input) AS tok_in, SUM(tokens_output) AS tok_out, SUM(tokens_cache_read) AS cache_read FROM session WHERE model IS NOT NULL AND time_updated >= (strftime('%s','now','-${days} day') * 1000) GROUP BY provider, model ORDER BY cost DESC;`, '--format', 'tsv']),
270
+ ]);
271
+ return {
272
+ label: label,
273
+ days: days,
274
+ stats: statsR,
275
+ agents: parseTSV(agentR.out),
276
+ providers: parseTSV(modelR.out),
277
+ };
278
+ }
279
+
280
+ function refreshReport(days) {
281
+ const key = String(days);
282
+ const hit = reportCache[key];
283
+ const fresh = hit && Date.now() - hit.generatedAt < REPORT_TTL;
284
+ if (fresh) return { report: hit, ready: true };
285
+ if (!reportBusy[key]) {
286
+ reportBusy[key] = true;
287
+ buildReport(days).then((r) => {
288
+ if (r && r.stats && r.stats.ok) {
289
+ reportCache[key] = Object.assign({}, r, { generatedAt: Date.now() });
290
+ }
291
+ }).catch(() => {}).finally(() => {
292
+ delete reportBusy[key];
293
+ });
294
+ }
295
+ return hit ? { report: Object.assign({}, hit, { stale: true }), ready: true } : { report: null, ready: false };
296
+ }
297
+
298
+ const server = http.createServer(async (req, res) => {
299
+ const url = new URL(req.url || '/', `http://127.0.0.1:${PORT}`);
300
+ const u = url.pathname;
301
+ if (u === '/api/stats') {
302
+ const days = parseInt(url.searchParams.get('days') || '7', 10) || 7;
303
+ const r = refreshTrend(days);
304
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
305
+ res.setHeader('Cache-Control', 'no-store');
306
+ res.end(JSON.stringify({
307
+ ok: !!state.data,
308
+ error: state.error,
309
+ generatedAt: state.updatedAt,
310
+ data: state.data,
311
+ models: state.models,
312
+ trend: r.trend,
313
+ trendReady: !!r.trend,
314
+ }));
315
+ } else if (u === '/api/report') {
316
+ const days = parseInt(url.searchParams.get('days') || '1', 10) || 1;
317
+ const r = refreshReport(days);
318
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
319
+ res.setHeader('Cache-Control', 'no-store');
320
+ res.end(JSON.stringify({
321
+ ok: true,
322
+ ready: r.ready,
323
+ report: r.report,
324
+ }));
325
+ } else if (u === '/') {
326
+ loadIndexHtml((err, data) => {
327
+ if (err) {
328
+ res.statusCode = 500;
329
+ res.end('Internal Server Error');
330
+ return;
331
+ }
332
+ res.setHeader('Content-Type', 'text/html; charset=utf-8');
333
+ res.end(data);
334
+ });
335
+ } else {
336
+ res.statusCode = 404;
337
+ res.end('Not Found');
338
+ }
339
+ });
340
+
341
+ function gracefulShutdown() {
342
+ console.log('\nShutting down...');
343
+ server.close(() => {
344
+ process.exit(0);
345
+ });
346
+ setTimeout(() => process.exit(1), 5000);
347
+ }
348
+
349
+ process.on('SIGINT', gracefulShutdown);
350
+ process.on('SIGTERM', gracefulShutdown);
351
+
352
+ setInterval(() => {
353
+ cleanExpiredCache(trendCache, TREND_MS * 2);
354
+ cleanExpiredCache(reportCache, REPORT_TTL * 2);
355
+ }, CACHE_CLEANUP_MS);
356
+
357
+ (async () => {
358
+ console.log('Loading initial stats...');
359
+ await refresh();
360
+ await refreshModels();
361
+ for (const d of [1, 7, 30]) {
362
+ const r = await buildReport(d);
363
+ if (r && r.stats && r.stats.ok) reportCache[String(d)] = Object.assign({}, r, { generatedAt: Date.now() });
364
+ }
365
+ for (const d of [7, 30, 90]) {
366
+ const t = await generateTrend(d);
367
+ if (t) trendCache[String(d)] = t;
368
+ }
369
+ setInterval(refresh, REFRESH_MS);
370
+ setInterval(refreshModels, 60000);
371
+ server.listen(PORT, '127.0.0.1', () => {
372
+ console.log(`opencode stats dashboard: http://127.0.0.1:${PORT}`);
373
+ });
374
+ })();
package/start.ps1 ADDED
@@ -0,0 +1,4 @@
1
+ $dir = Split-Path -Parent $MyInvocation.MyCommand.Path
2
+ Start-Process -FilePath "node" -ArgumentList "`"$dir\server.js`"" -WorkingDirectory $dir
3
+ Start-Sleep -Seconds 2
4
+ Start-Process "http://127.0.0.1:4868"