opencode-statboard 1.1.0 → 2.0.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/README.md CHANGED
@@ -1,31 +1,48 @@
1
1
  # opencode-statboard
2
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).
3
+ Real-time dashboard for your [opencode](https://opencode.ai) token usage and cost statistics.
4
4
 
5
5
  ## Features
6
6
 
7
7
  - Live-updating overview: sessions, messages, total cost, tokens per session
8
- - Token statistics: Input / Output / Cache Read / Cache Write
8
+ - Token statistics: Input / Output / Reasoning / Cache Read / Cache Write
9
9
  - Tool usage breakdown with percentage bars (collapsible)
10
10
  - Per-model usage with cache read stats
11
- - Daily trend chart (7D / 30D / 90D, 90D uses downsampling for speed)
11
+ - Daily trend chart (7D / 30D / 90D)
12
+ - Usage reports: Daily / Weekly / Monthly / All time
12
13
  - i18n: English + Traditional Chinese, auto-detects browser language
14
+ - Gzip compressed API responses
15
+ - Auto port fallback if 4868 is in use
13
16
 
14
17
  ## Requirements
15
18
 
16
19
  - Node.js (tested on v24)
17
20
  - [opencode](https://opencode.ai) CLI installed globally via npm
18
- - No npm packages required
19
21
 
20
22
  ## Install
21
23
 
22
24
  ```bash
23
25
  npm install -g opencode-statboard
26
+ ```
27
+
28
+ ## Start
29
+
30
+ ```bash
24
31
  opencode-dashboard
25
32
  ```
26
33
 
27
34
  Then open http://127.0.0.1:4868
28
35
 
36
+ ## Update
37
+
38
+ ```bash
39
+ npm update -g opencode-statboard
40
+ ```
41
+
42
+ ## Options
43
+
44
+ - `OC_PORT` — change the listening port (default: 4868, auto-fallbacks to next available)
45
+
29
46
  ## License
30
47
 
31
48
  MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-statboard",
3
- "version": "1.1.0",
3
+ "version": "2.0.1",
4
4
  "description": "Real-time dashboard for opencode token usage and cost statistics",
5
5
  "main": "server.js",
6
6
  "bin": {
package/public/index.html CHANGED
@@ -53,6 +53,8 @@
53
53
  .chart .bars > div { border-radius: 2px 2px 0 0; min-width: 4px; transition: height .4s ease; }
54
54
  .chart .x { font-size: 10px; color: var(--muted); line-height: 1; }
55
55
  .chart .tip { font-size: 10px; color: var(--muted); line-height: 1.2; text-align: center; }
56
+ .trend-x { display: flex; height: 16px; margin-top: 4px; }
57
+ .trend-x span { flex: 1; text-align: center; font-size: 10px; color: var(--muted); line-height: 16px; overflow: hidden; text-overflow: clip; white-space: nowrap; }
56
58
  .two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; }
57
59
  @media (max-width: 800px) { .two-col { grid-template-columns: 1fr; } }
58
60
  .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; }
@@ -72,6 +74,7 @@
72
74
  .version { font-size: 11px; color: var(--muted); background: var(--panel); border: 1px solid var(--border); padding: 2px 8px; border-radius: 4px; }
73
75
  .trend-bar-input { left: 25%; width: 22%; z-index: 1; }
74
76
  .trend-bar-output { left: 53%; width: 22%; z-index: 1; }
77
+ .trend-bar-reasoning { left: 76%; width: 22%; z-index: 1; }
75
78
  </style>
76
79
  </head>
77
80
  <body>
@@ -105,6 +108,7 @@
105
108
  <div class="legend">
106
109
  <span><i class="sw" style="background:var(--in)"></i>Input</span>
107
110
  <span><i class="sw" style="background:var(--out)"></i>Output</span>
111
+ <span><i class="sw" style="background:var(--tool)"></i>Reasoning</span>
108
112
  <span><i class="sw" style="background:var(--cache)"></i>Cache Read</span>
109
113
  <span><i class="sw" style="background:var(--cost)"></i>Cache Write</span>
110
114
  </div>
@@ -140,16 +144,17 @@
140
144
  <div class="legend">
141
145
  <span><i class="sw" style="background:var(--in)"></i><span data-i18n="inputDay">Input / Day</span></span>
142
146
  <span><i class="sw" style="background:var(--out)"></i><span data-i18n="outputDay">Output / Day</span></span>
147
+ <span><i class="sw" style="background:var(--tool)"></i>Reasoning / Day</span>
143
148
  <span><i class="sw" style="background:var(--cache)"></i><span data-i18n="cacheReadDay">Cache Read / Day</span></span>
144
149
  <span id="trendStatus" style="color:var(--cache);font-size:11px"></span>
145
150
  </div>
146
151
  <div class="chart" id="trendTokensChart"><div class="bars" id="trend-tokens"></div></div>
147
- <div class="bars" id="trend-token-x" style="height:auto;display:flex;justify-content:space-around;margin-top:4px"></div>
152
+ <div class="trend-x" id="trend-token-x"></div>
148
153
  </div>
149
154
  <div id="costSection" style="flex:1;min-width:200px">
150
155
  <div class="legend"><span><i class="sw" style="background:var(--cost)"></i><span data-i18n="costDay">Cost / Day</span></span></div>
151
156
  <div class="chart" id="trendCostChart"><div class="bars" id="trend-cost"></div></div>
152
- <div class="bars" id="trend-cost-x" style="height:auto;display:flex;justify-content:space-around;margin-top:4px"></div>
157
+ <div class="trend-x" id="trend-cost-x"></div>
153
158
  <div id="costZeroNote" style="display:none;font-size:12px;color:var(--muted);padding:20px 0;text-align:center"></div>
154
159
  </div>
155
160
  </div>
@@ -279,11 +284,12 @@ function render(d, models, trend) {
279
284
  $('ov-med').textContent = fmt(d.cost && d.cost.medianTokensSession);
280
285
 
281
286
  if (d.cost) {
282
- const vals = [d.cost.input, d.cost.output, d.cost.cacheRead, d.cost.cacheWrite];
287
+ const vals = [d.cost.input, d.cost.output, d.cost.reasoning, d.cost.cacheRead, d.cost.cacheWrite];
283
288
  const max = Math.max(...vals.filter(Number.isFinite));
284
289
  $('token-bars').innerHTML =
285
290
  barRow('Input', d.cost.input, max, 'var(--in)') +
286
291
  barRow('Output', d.cost.output, max, 'var(--out)') +
292
+ barRow('Reasoning', d.cost.reasoning, max, 'var(--tool)') +
287
293
  barRow('Cache Read', d.cost.cacheRead, max, 'var(--cache)') +
288
294
  barRow('Cache Write', d.cost.cacheWrite, max, 'var(--cost)');
289
295
  }
@@ -329,46 +335,63 @@ function render(d, models, trend) {
329
335
 
330
336
  function renderTrend(data) {
331
337
  const n = data.labels.length;
332
- const maxAll = Math.max(...data.input, ...data.output, ...data.cacheRead);
333
- const hasCost = data.cost.some((v) => v > 0);
338
+ const maxAll = Math.max(...data.input, ...data.output, ...(data.reasoning || []), ...data.cacheRead);
339
+ const hasCost = data.cost.some((v) => v >= 0.0001);
334
340
 
335
341
  $('trend-tokens').innerHTML = data.labels.map((l, i) => {
336
342
  const hi = maxAll > 0 ? (data.input[i] / maxAll) * 100 : 0;
337
343
  const ho = maxAll > 0 ? (data.output[i] / maxAll) * 100 : 0;
344
+ const hr = maxAll > 0 && data.reasoning ? (data.reasoning[i] / maxAll) * 100 : 0;
338
345
  const hc = maxAll > 0 ? (data.cacheRead[i] / maxAll) * 100 : 0;
339
- const tip = l + ': In ' + fmt(data.input[i]) + ' · Out ' + fmt(data.output[i]) + ' · Cache ' + fmt(data.cacheRead[i]);
346
+ const tip = l + ': In ' + fmt(data.input[i]) + ' · Out ' + fmt(data.output[i]) + ' · Reas ' + fmt(data.reasoning ? data.reasoning[i] : 0) + ' · Cache ' + fmt(data.cacheRead[i]);
340
347
  return `<div class="col" title="${tip}">
341
348
  <div style="display:flex;gap:2px;align-items:flex-end;width:100%;height:170px;justify-content:center">
342
349
  <div style="position:relative;width:100%;height:100%">
343
350
  <div class="trend-bar trend-bar-cache" style="height:${Math.max(hc, 1)}%;background:var(--cache)"></div>
344
351
  <div class="trend-bar trend-bar-input" style="height:${Math.max(hi, 1)}%;background:var(--in)"></div>
345
352
  <div class="trend-bar trend-bar-output" style="height:${Math.max(ho, 1)}%;background:var(--out)"></div>
353
+ <div class="trend-bar trend-bar-reasoning" style="height:${Math.max(hr, 1)}%;background:var(--tool)"></div>
346
354
  </div>
347
355
  </div>
348
356
  </div>`;
349
357
  }).join('');
350
358
 
351
359
  const labelStep = Math.max(1, Math.ceil(n / 14));
352
- $('trend-token-x').innerHTML = data.labels.map((l, i) =>
353
- `<span class="x" style="flex:1;text-align:center;${i % labelStep === 0 ? '' : 'visibility:hidden'}">${l}</span>`).join('');
360
+ $('trend-token-x').innerHTML = data.labels.map((l, i) => {
361
+ const vis = i % labelStep === 0 ? '' : 'visibility:hidden';
362
+ return `<span style="${vis}">${l}</span>`;
363
+ }).join('');
354
364
 
355
365
  if (hasCost) {
356
366
  $('costSection').querySelector('.legend').style.display = '';
357
367
  $('trendCostChart').style.display = '';
358
368
  $('trend-cost-x').style.display = '';
359
369
  $('costZeroNote').style.display = 'none';
360
- const maxCost = Math.max(...data.cost);
361
- $('trend-cost').innerHTML = data.labels.map((l, i) => {
362
- const h = maxCost > 0 ? (data.cost[i] / maxCost) * 100 : 0;
363
- const tip = l + ': $' + (data.cost[i] || 0).toFixed(2);
364
- return `<div class="col" title="${tip}">
365
- <div style="display:flex;align-items:flex-end;width:100%;height:170px;justify-content:center">
366
- <div style="width:50%;height:${Math.max(h, 1)}%;background:var(--cost);border-radius:2px 2px 0 0"></div>
367
- </div>
368
- </div>`;
369
- }).join('');
370
- $('trend-cost-x').innerHTML = data.labels.map((l, i) =>
371
- `<span class="x" style="flex:1;text-align:center;${i % labelStep === 0 ? '' : 'visibility:hidden'}">${l}</span>`).join('');
370
+ const costThreshold = 0.0001;
371
+ const displayCost = data.cost.map((v) => v < costThreshold ? 0 : v);
372
+ const hasRealCost = displayCost.some((v) => v > 0);
373
+ if (!hasRealCost) {
374
+ $('costSection').querySelector('.legend').style.display = 'none';
375
+ $('trendCostChart').style.display = 'none';
376
+ $('trend-cost-x').style.display = 'none';
377
+ $('costZeroNote').style.display = '';
378
+ $('costZeroNote').textContent = t('allFree');
379
+ } else {
380
+ const maxCost = Math.max(...displayCost);
381
+ $('trend-cost').innerHTML = data.labels.map((l, i) => {
382
+ const h = maxCost > 0 ? (displayCost[i] / maxCost) * 100 : 0;
383
+ const tip = l + ': $' + (displayCost[i] || 0).toFixed(4);
384
+ return `<div class="col" title="${tip}">
385
+ <div style="display:flex;align-items:flex-end;width:100%;height:170px;justify-content:center">
386
+ <div style="width:50%;height:${Math.max(h, 1)}%;background:var(--cost);border-radius:2px 2px 0 0"></div>
387
+ </div>
388
+ </div>`;
389
+ }).join('');
390
+ $('trend-cost-x').innerHTML = data.labels.map((l, i) => {
391
+ const vis = i % labelStep === 0 ? '' : 'visibility:hidden';
392
+ return `<span style="${vis}">${l}</span>`;
393
+ }).join('');
394
+ }
372
395
  } else {
373
396
  $('costSection').querySelector('.legend').style.display = 'none';
374
397
  $('trendCostChart').style.display = 'none';
@@ -430,7 +453,8 @@ function formatReport(jr) {
430
453
  const rpad = (s, w) => { s = String(s); return s.length >= w ? s : ' '.repeat(w - s.length) + s; };
431
454
  let out = '';
432
455
  out += 'OPENCODE USAGE STATEMENT\n';
433
- out += 'Period: ' + jr.label + (jr.days >= 0 ? ' | Last ' + jr.days + ' day(s)' : '') + cachedNote + '\n';
456
+ const periodText = jr.days === -1 ? 'All time' : jr.days <= 1 ? 'Today (local)' : jr.days <= 7 ? 'Last 7 days (local)' : 'Month to date (local)';
457
+ out += 'Period: ' + jr.label + ' | ' + periodText + cachedNote + '\n';
434
458
  out += '---\n';
435
459
  const s = jr.stats;
436
460
  if (s && s.ok) {
@@ -441,6 +465,7 @@ function formatReport(jr) {
441
465
  out += ' Messages ........... ' + (o.messages || 0) + '\n';
442
466
  out += ' Total Cost ......... $' + (c.total || 0).toFixed(2) + '\n';
443
467
  out += ' Tokens In/Out ...... ' + fmtT(c.input) + ' / ' + fmtT(c.output) + '\n';
468
+ out += ' Tokens Reasoning ... ' + fmtT(c.reasoning) + '\n';
444
469
  out += ' Cache Read/Write ... ' + fmtT(c.cacheRead) + ' / ' + fmtT(c.cacheWrite) + '\n';
445
470
  out += '\n';
446
471
  }
@@ -492,6 +517,11 @@ applyI18n();
492
517
  poll();
493
518
  setInterval(poll, 15000);
494
519
  loadReport(1);
520
+ // Preload report data for other periods so tab switching is instant.
521
+ // Load with delays to avoid competing with the first poll for bandwidth.
522
+ setTimeout(() => loadReport(7), 1500);
523
+ setTimeout(() => loadReport(30), 3000);
524
+ setTimeout(() => loadReport(-1), 4500);
495
525
  </script>
496
526
  </body>
497
527
  </html>
package/server.js CHANGED
@@ -3,24 +3,63 @@ const { execFile } = require('child_process');
3
3
  const http = require('http');
4
4
  const fs = require('fs');
5
5
  const path = require('path');
6
+ const zlib = require('zlib');
7
+ const { pipeline } = require('stream');
8
+ const { promisify } = require('util');
9
+ const pipelineAsync = promisify(pipeline);
6
10
 
7
11
  let Database;
8
12
  try { Database = require('better-sqlite3'); } catch (_) { Database = null; }
9
13
 
10
- const PORT = 4868;
14
+ const PORT = parseInt(process.env.OC_PORT || '4868', 10);
11
15
  const REFRESH_MS = 15000;
12
- const TREND_MS = 10 * 60 * 1000;
16
+ const TREND_MS = 60 * 1000;
13
17
  const REPORT_TTL = 10 * 60 * 1000;
14
18
  const STATS_TTL = 10 * 60 * 1000;
15
19
  const CACHE_CLEANUP_MS = 5 * 60 * 1000;
16
20
  const BACKUP_DIR = path.join(__dirname, 'backups');
17
- const BACKUP_RETENTION = parseInt(process.env.OPENCODE_BACKUP_RETENTION || '0', 10) || 0;
21
+ const BACKUP_RETENTION = parseInt(process.env.OPENCODE_BACKUP_RETENTION || '3', 10) || 3;
18
22
  const BACKUP_SRC = process.env.OPENCODE_DATA
19
23
  ? path.join(process.env.OPENCODE_DATA, 'opencode.db')
20
24
  : path.join(process.env.USERPROFILE || process.env.HOME || '', '.local', 'share', 'opencode', 'opencode.db');
21
25
  const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
22
26
  const VERSION = pkg.version;
23
27
 
28
+ function compressFile(srcPath) {
29
+ return new Promise((resolve, reject) => {
30
+ const dstPath = srcPath + '.gz';
31
+ const src = fs.createReadStream(srcPath);
32
+ const dst = fs.createWriteStream(dstPath);
33
+ const gzip = zlib.createGzip({ level: 6 });
34
+ src.on('error', reject);
35
+ dst.on('error', reject);
36
+ dst.on('finish', () => {
37
+ const origSize = fs.statSync(srcPath).size;
38
+ const compSize = fs.statSync(dstPath).size;
39
+ fs.unlinkSync(srcPath);
40
+ resolve({ origSize, compSize });
41
+ });
42
+ src.pipe(gzip).pipe(dst);
43
+ });
44
+ }
45
+
46
+ function cleanupOldBackups() {
47
+ if (BACKUP_RETENTION <= 0) return;
48
+ try {
49
+ const dirs = fs.readdirSync(BACKUP_DIR)
50
+ .filter((f) => f.startsWith('opencode-') && fs.statSync(path.join(BACKUP_DIR, f)).isDirectory())
51
+ .sort();
52
+ if (dirs.length > BACKUP_RETENTION) {
53
+ const toDelete = dirs.slice(0, dirs.length - BACKUP_RETENTION);
54
+ for (const f of toDelete) {
55
+ const dirPath = path.join(BACKUP_DIR, f);
56
+ fs.rmSync(dirPath, { recursive: true, force: true });
57
+ console.log(`backup cleaned: ${f}`);
58
+ }
59
+ }
60
+ } catch (_) {}
61
+ }
62
+
24
63
  const EXE = (() => {
25
64
  const candidates = [
26
65
  path.join(process.env.APPDATA || '', 'npm', 'node_modules', 'opencode-ai', 'bin', 'opencode.exe'),
@@ -37,6 +76,13 @@ function getDb() {
37
76
  try {
38
77
  db = new Database(BACKUP_SRC, { readonly: true, fileMustExist: true });
39
78
  db.pragma('journal_mode = WAL');
79
+ // Create indexes on first open (persisted in DB file).
80
+ try {
81
+ db.exec("CREATE INDEX IF NOT EXISTS idx_message_time_created ON message(time_created)");
82
+ db.exec("CREATE INDEX IF NOT EXISTS idx_message_session_time ON message(session_id, time_created)");
83
+ db.exec("CREATE INDEX IF NOT EXISTS idx_session_time ON session(time_created, time_updated)");
84
+ db.exec("CREATE INDEX IF NOT EXISTS idx_part_time_tool ON part(time_updated)");
85
+ } catch (_) {}
40
86
  return db;
41
87
  } catch (_) { return null; }
42
88
  }
@@ -46,6 +92,7 @@ const state = { data: null, busy: false, error: null, updatedAt: 0, models: null
46
92
  let indexHtmlCache = null;
47
93
 
48
94
  let backupBusy = false;
95
+ let vacuumBusy = false;
49
96
  let lastAutoBackupDay = '';
50
97
 
51
98
  function loadIndexHtml(callback) {
@@ -66,16 +113,21 @@ function run(args, timeout = 120000) {
66
113
  });
67
114
  }
68
115
 
69
- function dbQuery(sql) {
116
+ function dbQuery(sql, params) {
70
117
  const d = getDb();
71
118
  if (!d) return null;
72
- try { return d.prepare(sql).all(); } catch (_) { return null; }
119
+ try { return params ? d.prepare(sql).all(...params) : d.prepare(sql).all(); } catch (_) { return null; }
73
120
  }
74
121
 
75
- function dbGet(sql) {
122
+ function dbGet(sql, params) {
76
123
  const d = getDb();
77
124
  if (!d) return null;
78
- try { return d.prepare(sql).get(); } catch (_) { return null; }
125
+ try { return params ? d.prepare(sql).get(...params) : d.prepare(sql).get(); } catch (_) { return null; }
126
+ }
127
+
128
+ function ensureIndexes() {
129
+ // Indexes are created inside getDb() on open; kept for explicit warmup call.
130
+ getDb();
79
131
  }
80
132
 
81
133
  const trendCache = {};
@@ -93,45 +145,39 @@ function cleanExpiredCache(cache, ttl) {
93
145
 
94
146
  async function generateTrend(days) {
95
147
  const now = Date.now();
96
- const startMs = now - days * 86400000;
97
-
98
- const rows = dbQuery(`SELECT CAST((time_updated / 86400000) AS INTEGER) AS day_key, COUNT(*) AS sessions, COALESCE(SUM(tokens_input),0) AS input, COALESCE(SUM(tokens_output),0) AS output, COALESCE(SUM(tokens_cache_read),0) AS cacheRead, COALESCE(SUM(cost),0) AS total FROM session WHERE time_updated >= ${startMs} GROUP BY day_key ORDER BY day_key ASC;`);
99
-
100
- const byDay = {};
101
- if (rows) {
102
- for (const row of rows) {
103
- const key = parseInt(row.day_key);
104
- if (!isNaN(key)) {
105
- byDay[key] = {
106
- sessions: parseInt(row.sessions) || 0,
107
- input: parseFloat(row.input) || 0,
108
- output: parseFloat(row.output) || 0,
109
- cacheRead: parseFloat(row.cacheRead) || 0,
110
- total: parseFloat(row.total) || 0,
111
- };
112
- }
113
- }
114
- }
115
148
 
116
- const startKey = Math.floor(startMs / 86400000);
117
- const todayKey = Math.floor(now / 86400000);
118
- const results = [];
119
- for (let k = todayKey; k >= startKey; k--) {
120
- results.push(byDay[k] || { sessions: 0, input: 0, output: 0, cacheRead: 0, total: 0 });
149
+ // Buckets: local midnights, today -> (days-1) days ago.
150
+ // Values come from attributeUsage (hybrid message+session-residual
151
+ // attribution), so multi-day sessions don't dump everything on one day
152
+ // and pruned (message-less) history isn't lost either.
153
+ const buckets = [];
154
+ const today = new Date();
155
+ for (let i = 0; i < days; i++) {
156
+ const d = new Date(today);
157
+ d.setDate(d.getDate() - i);
158
+ d.setHours(0, 0, 0, 0);
159
+ buckets.push(d);
121
160
  }
161
+ const a = attributeUsage(buckets[buckets.length - 1].getTime(), now);
162
+ const at = (b, f) => {
163
+ const D = a.perDay[localDayKey(b)];
164
+ return D ? D[f] : 0;
165
+ };
166
+ const sess = (b) => {
167
+ const D = a.perDay[localDayKey(b)];
168
+ return D ? D.sessions.size : 0;
169
+ };
122
170
 
123
171
  return {
124
172
  generatedAt: now,
125
173
  step: 1,
126
- labels: results.map((_, i) => {
127
- const d = new Date(now - i * 86400000);
128
- return (d.getMonth() + 1) + '/' + d.getDate();
129
- }),
130
- sessions: results.map((b) => b.sessions),
131
- input: results.map((b) => b.input),
132
- output: results.map((b) => b.output),
133
- cacheRead: results.map((b) => b.cacheRead),
134
- cost: results.map((b) => b.total),
174
+ labels: buckets.map((b) => (b.getMonth() + 1) + '/' + b.getDate()),
175
+ sessions: buckets.map(sess),
176
+ input: buckets.map((b) => at(b, 'input')),
177
+ output: buckets.map((b) => at(b, 'output')),
178
+ reasoning: buckets.map((b) => at(b, 'reasoning')),
179
+ cacheRead: buckets.map((b) => at(b, 'cacheRead')),
180
+ cost: buckets.map((b) => at(b, 'cost')),
135
181
  };
136
182
  }
137
183
 
@@ -154,6 +200,130 @@ function refreshTrend(days) {
154
200
  return { trend: hit ? Object.assign({}, hit, { stale: true }) : null, pending };
155
201
  }
156
202
 
203
+ function localDayKey(d) { return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`; }
204
+ function dateOfKey(k) { const [y, m, d] = k.split('-').map(Number); return new Date(y, m, d); }
205
+ function modelNameOf(provider, model) { return `${provider || 'unknown'}/${model || 'unknown'}`; }
206
+ function splitModelName(name) {
207
+ const i = String(name).indexOf('/');
208
+ return i < 0 ? { provider: 'unknown', model: String(name) } : { provider: String(name).slice(0, i), model: String(name).slice(i + 1) };
209
+ }
210
+
211
+ // Hybrid usage attribution over [startMs, endMs).
212
+ // Why hybrid: session-level totals are COMPLETE (message table only covers
213
+ // ~2026-08 onward; 287/469 sessions in 90d have zero messages) but a
214
+ // multi-day session dumps all its tokens onto time_updated day (e.g. a 45.9M
215
+ // session created 9/9 updated 9/13). Message rows carry exact per-message
216
+ // tokens+cost+time but are incomplete. So: message tokens go to their exact
217
+ // local day; each session's residual (session totals minus its message sums,
218
+ // clamped >= 0) is spread across the local days the session spans,
219
+ // proportional to that session's per-day message-token volume
220
+ // (uniform across spanned days when the session has no messages).
221
+ // Returns perDay/perModel/perAgent/perSession maps plus totals.
222
+ function attributeUsage(startMs, endMs) {
223
+ const perDay = {};
224
+ const perModel = {};
225
+ const perAgent = {};
226
+ const perSession = {};
227
+ const ensureDay = (key) => perDay[key] || (perDay[key] = { date: dateOfKey(key), sessions: new Set(), messages: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 });
228
+ const ensureModel = (n) => perModel[n] || (perModel[n] = { messages: 0, sessions: new Set(), input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 });
229
+ const ensureAgent = (a) => perAgent[a || 'unknown'] || (perAgent[a || 'unknown'] = { messages: 0, sessions: new Set(), input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 });
230
+
231
+ // 1. messages in period (exact timing)
232
+ const msgTok = {};
233
+ const msgW = {};
234
+ const mrows = dbQuery(`SELECT time_created AS t, session_id AS sid, COALESCE(json_extract(data, '$.agent'), 'unknown') AS agent, COALESCE(json_extract(data, '$.providerID'), json_extract(data, '$.model.providerID'), 'unknown') AS provider, COALESCE(json_extract(data, '$.modelID'), json_extract(data, '$.model.modelID'), 'unknown') AS model, COALESCE(CAST(json_extract(data, '$.tokens.input') AS INTEGER), 0) AS input, COALESCE(CAST(json_extract(data, '$.tokens.output') AS INTEGER), 0) AS output, COALESCE(CAST(json_extract(data, '$.tokens.reasoning') AS INTEGER), 0) AS reasoning, COALESCE(CAST(json_extract(data, '$.tokens.cache.read') AS INTEGER), 0) AS cacheRead, COALESCE(CAST(json_extract(data, '$.tokens.cache.write') AS INTEGER), 0) AS cacheWrite, COALESCE(CAST(json_extract(data, '$.cost') AS REAL), 0) AS cost FROM message WHERE time_created >= ${startMs} AND time_created < ${endMs};`) || [];
235
+ for (const r of mrows) {
236
+ const key = localDayKey(new Date(r.t));
237
+ const D = ensureDay(key);
238
+ D.messages++;
239
+ if (r.sid) D.sessions.add(r.sid);
240
+ const iv = +r.input || 0, ov = +r.output || 0, rv = +r.reasoning || 0;
241
+ const crv = +r.cacheRead || 0, cwv = +r.cacheWrite || 0, cv = +r.cost || 0;
242
+ D.input += iv; D.output += ov; D.reasoning += rv; D.cacheRead += crv; D.cacheWrite += cwv; D.cost += cv;
243
+ const M = ensureModel(modelNameOf(r.provider, r.model));
244
+ M.messages++;
245
+ if (r.sid) M.sessions.add(r.sid);
246
+ M.input += iv; M.output += ov; M.reasoning += rv; M.cacheRead += crv; M.cacheWrite += cwv; M.cost += cv;
247
+ const A = ensureAgent(r.agent);
248
+ A.messages++;
249
+ if (r.sid) A.sessions.add(r.sid);
250
+ A.input += iv; A.output += ov; A.reasoning += rv; A.cacheRead += crv; A.cacheWrite += cwv; A.cost += cv;
251
+ if (r.sid) {
252
+ const mt = msgTok[r.sid] || (msgTok[r.sid] = { input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 });
253
+ mt.input += iv; mt.output += ov; mt.reasoning += rv; mt.cacheRead += crv; mt.cacheWrite += cwv; mt.cost += cv;
254
+ const w = msgW[r.sid] || (msgW[r.sid] = { total: 0, perDay: {} });
255
+ const vol = iv + ov + rv + crv + cwv;
256
+ w.total += vol;
257
+ w.perDay[key] = (w.perDay[key] || 0) + vol;
258
+ }
259
+ }
260
+
261
+ // 2. sessions intersecting the period: spread residual
262
+ const srows = dbQuery(`SELECT id, agent, COALESCE(json_extract(model, '$.providerID'), 'unknown') AS provider, COALESCE(json_extract(model, '$.id'), 'unknown') AS model, time_created AS tc, time_updated AS tu, tokens_input AS si, tokens_output AS so, tokens_reasoning AS sr, tokens_cache_read AS scr, tokens_cache_write AS scw, cost AS sc FROM session WHERE time_updated >= ${startMs} AND time_created < ${endMs};`) || [];
263
+ for (const s of srows) {
264
+ const lo = Math.max(s.tc, startMs), hi = Math.min(s.tu, endMs - 1);
265
+ if (hi < lo) continue;
266
+ const d0 = new Date(new Date(lo).setHours(0, 0, 0, 0));
267
+ const d1 = new Date(new Date(hi).setHours(0, 0, 0, 0));
268
+ const spanKeys = [];
269
+ for (let d = new Date(d0); d <= d1; d.setDate(d.getDate() + 1)) spanKeys.push(localDayKey(d));
270
+ if (!spanKeys.length) continue;
271
+ const mt = msgTok[s.id] || { input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
272
+ const res = {
273
+ input: Math.max(0, (+s.si || 0) - mt.input),
274
+ output: Math.max(0, (+s.so || 0) - mt.output),
275
+ reasoning: Math.max(0, (+s.sr || 0) - mt.reasoning),
276
+ cacheRead: Math.max(0, (+s.scr || 0) - mt.cacheRead),
277
+ cacheWrite: Math.max(0, (+s.scw || 0) - mt.cacheWrite),
278
+ cost: Math.max(0, (+s.sc || 0) - mt.cost),
279
+ };
280
+ const ps = perSession[s.id] || (perSession[s.id] = { input: mt.input, output: mt.output, reasoning: mt.reasoning, cacheRead: mt.cacheRead, cacheWrite: mt.cacheWrite, cost: mt.cost });
281
+ const w = msgW[s.id];
282
+ let wTotal = 0;
283
+ if (w) { for (const k of spanKeys) wTotal += w.perDay[k] || 0; }
284
+ if (wTotal > 0) {
285
+ for (const k of spanKeys) if ((w.perDay[k] || 0) > 0) ensureDay(k).sessions.add(s.id);
286
+ } else {
287
+ ensureDay(localDayKey(new Date(Math.min(s.tu, endMs - 1)))).sessions.add(s.id);
288
+ }
289
+ const mName = modelNameOf(s.provider, s.model);
290
+ const aName = s.agent || 'unknown';
291
+ for (const k of spanKeys) {
292
+ const share = wTotal > 0 ? ((w.perDay[k] || 0) / wTotal) : 1 / spanKeys.length;
293
+ if (share === 0) continue;
294
+ const D = ensureDay(k);
295
+ const di = res.input * share, dout = res.output * share, dr = res.reasoning * share;
296
+ const dcr = res.cacheRead * share, dcw = res.cacheWrite * share, dc = res.cost * share;
297
+ D.input += di; D.output += dout; D.reasoning += dr; D.cacheRead += dcr; D.cacheWrite += dcw; D.cost += dc;
298
+ const M = ensureModel(mName);
299
+ M.input += di; M.output += dout; M.reasoning += dr; M.cacheRead += dcr; M.cacheWrite += dcw; M.cost += dc;
300
+ const A = ensureAgent(aName);
301
+ A.input += di; A.output += dout; A.reasoning += dr; A.cacheRead += dcr; A.cacheWrite += dcw; A.cost += dc;
302
+ ps.input += di; ps.output += dout; ps.reasoning += dr; ps.cacheRead += dcr; ps.cacheWrite += dcw; ps.cost += dc;
303
+ }
304
+ }
305
+
306
+ const totals = { sessions: Object.keys(perSession).length, messages: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
307
+ for (const k of Object.keys(perDay)) {
308
+ const D = perDay[k];
309
+ totals.messages += D.messages;
310
+ totals.input += D.input; totals.output += D.output; totals.reasoning += D.reasoning;
311
+ totals.cacheRead += D.cacheRead; totals.cacheWrite += D.cacheWrite; totals.cost += D.cost;
312
+ }
313
+ return { perDay, perModel, perAgent, perSession, totals };
314
+ }
315
+
316
+ // All-time attribution, memoized 300s (expensive full DB scan; avoids
317
+ // re-running attributeUsage on every /api/stats hit).
318
+ let attrAllCache = null;
319
+ function getAttrAll() {
320
+ const now = Date.now();
321
+ if (attrAllCache && now - attrAllCache.at < 300000) return attrAllCache.a;
322
+ const a = attributeUsage(0, now);
323
+ attrAllCache = { at: now, a };
324
+ return a;
325
+ }
326
+
157
327
  function computeMedian(arr) {
158
328
  if (!arr.length) return 0;
159
329
  const sorted = arr.slice().sort((a, b) => a - b);
@@ -168,9 +338,12 @@ function getStatsFromDb(days) {
168
338
  const timeFilterPart = startMs ? `AND p.time_updated >= ${startMs}` : '';
169
339
  const timeFilterWhere = startMs ? `WHERE s.time_updated >= ${startMs}` : '';
170
340
 
171
- const overview = dbGet(`SELECT COUNT(*) AS sessions, COUNT(DISTINCT CAST(s.time_updated / 86400000 AS INTEGER)) AS days FROM session s ${timeFilterWhere};`);
341
+ // NOTE: days is only ever 0 here (overview totals); per-period stats are
342
+ // built by buildReportFromDb via attributeUsage. Local-day count so the
343
+ // number matches the trend chart buckets.
344
+ const overview = dbGet(`SELECT COUNT(*) AS sessions, COUNT(DISTINCT date(s.time_updated / 1000, 'unixepoch', 'localtime')) AS days FROM session s ${timeFilterWhere};`);
172
345
  const msgCount = dbGet(`SELECT COUNT(*) AS messages FROM message m ${startMs ? `WHERE m.time_updated >= ${startMs}` : ''};`);
173
- const costRow = dbGet(`SELECT COALESCE(SUM(tokens_input),0) AS input, COALESCE(SUM(tokens_output),0) AS output, COALESCE(SUM(tokens_cache_read),0) AS cacheRead, COALESCE(SUM(tokens_cache_write),0) AS cacheWrite, COALESCE(SUM(cost),0) AS total FROM session s ${timeFilterWhere};`);
346
+ const costRow = dbGet(`SELECT COALESCE(SUM(tokens_input),0) AS input, COALESCE(SUM(tokens_output),0) AS output, COALESCE(SUM(tokens_reasoning),0) AS reasoning, COALESCE(SUM(tokens_cache_read),0) AS cacheRead, COALESCE(SUM(tokens_cache_write),0) AS cacheWrite, COALESCE(SUM(cost),0) AS total FROM session s ${timeFilterWhere};`);
174
347
 
175
348
  const toolRows = dbQuery(`SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' ${timeFilterPart};`) || [];
176
349
  const toolCounts = {};
@@ -182,7 +355,7 @@ function getStatsFromDb(days) {
182
355
  .map(([name, count]) => ({ name, count, pct: Math.round((count / totalToolUse) * 1000) / 10 }))
183
356
  .sort((a, b) => b.count - a.count);
184
357
 
185
- const tokenRows = dbQuery(`SELECT tokens_input + tokens_output AS tokens FROM session s ${timeFilterWhere};`) || [];
358
+ const tokenRows = dbQuery(`SELECT tokens_input + tokens_output + tokens_reasoning AS tokens FROM session s ${timeFilterWhere};`) || [];
186
359
  const tokenVals = tokenRows.map((r) => r.tokens).filter(Number.isFinite);
187
360
  const avgTokens = tokenVals.length ? tokenVals.reduce((s, v) => s + v, 0) / tokenVals.length : 0;
188
361
  const medianTokens = computeMedian(tokenVals);
@@ -190,7 +363,21 @@ function getStatsFromDb(days) {
190
363
  const sessions = overview ? (overview.sessions || 0) : 0;
191
364
  const avgDayCost = costRow && costRow.total ? costRow.total / activeDays : 0;
192
365
 
193
- const models = dbQuery(`SELECT COALESCE(json_extract(model,'$.providerID'), 'unknown') || '/' || COALESCE(json_extract(model,'$.id'), 'unknown') AS name, COUNT(*) AS messages, COALESCE(SUM(tokens_input),0) AS input, COALESCE(SUM(tokens_output),0) AS output, COALESCE(SUM(tokens_cache_read),0) AS cacheRead, COALESCE(SUM(tokens_cache_write),0) AS cacheWrite, COALESCE(SUM(cost),0) AS cost FROM session s ${timeFilterWhere} GROUP BY name ORDER BY COALESCE(SUM(cost),0) DESC;`) || [];
366
+ // Per-model usage from hybrid attribution (message counts are TRUE message
367
+ // counts here, not session counts; token/cost sums include residuals so
368
+ // pruned history isn't lost).
369
+ const attr = getAttrAll();
370
+ const models = Object.entries(attr.perModel)
371
+ .map(([name, m]) => ({
372
+ name,
373
+ messages: m.messages,
374
+ input: Math.round(m.input),
375
+ output: Math.round(m.output),
376
+ cacheRead: Math.round(m.cacheRead),
377
+ cacheWrite: Math.round(m.cacheWrite),
378
+ cost: m.cost,
379
+ }))
380
+ .sort((a, b) => b.cost - a.cost);
194
381
 
195
382
  return {
196
383
  ok: true,
@@ -206,6 +393,7 @@ function getStatsFromDb(days) {
206
393
  medianTokensSession: Math.round(medianTokens),
207
394
  input: costRow ? costRow.input : 0,
208
395
  output: costRow ? costRow.output : 0,
396
+ reasoning: costRow ? costRow.reasoning : 0,
209
397
  cacheRead: costRow ? costRow.cacheRead : 0,
210
398
  cacheWrite: costRow ? costRow.cacheWrite : 0,
211
399
  },
@@ -234,16 +422,19 @@ async function refresh() {
234
422
  }
235
423
 
236
424
  function getModelsFromDb() {
237
- const rows = dbQuery(`SELECT COALESCE(json_extract(model,'$.providerID'), 'unknown') AS provider, COALESCE(json_extract(model,'$.id'), 'unknown') AS model, COUNT(*) AS messages, COALESCE(SUM(tokens_input),0) AS input, COALESCE(SUM(tokens_output),0) AS output, COALESCE(SUM(tokens_cache_read),0) AS cacheRead, COALESCE(SUM(cost),0) AS cost FROM session GROUP BY provider, model ORDER BY COALESCE(SUM(cost),0) DESC LIMIT 10;`) || [];
238
- return rows.map((r) => ({
239
- name: r.provider + '/' + r.model,
240
- messages: r.messages || 0,
241
- input: r.input || 0,
242
- output: r.output || 0,
243
- cacheRead: r.cacheRead || 0,
244
- cacheWrite: 0,
245
- cost: r.cost || 0,
246
- }));
425
+ const attr = getAttrAll();
426
+ return Object.entries(attr.perModel)
427
+ .map(([name, m]) => ({
428
+ name,
429
+ messages: m.messages,
430
+ input: Math.round(m.input),
431
+ output: Math.round(m.output),
432
+ cacheRead: Math.round(m.cacheRead),
433
+ cacheWrite: Math.round(m.cacheWrite),
434
+ cost: m.cost,
435
+ }))
436
+ .sort((a, b) => b.cost - a.cost)
437
+ .slice(0, 10);
247
438
  }
248
439
 
249
440
  async function refreshModels() {
@@ -262,7 +453,7 @@ function backupDirName() {
262
453
  }
263
454
 
264
455
  async function performBackup(auto) {
265
- if (backupBusy) return { ok: false, busy: true };
456
+ if (backupBusy || vacuumBusy) return { ok: false, busy: true };
266
457
  backupBusy = true;
267
458
  try {
268
459
  if (!fs.existsSync(BACKUP_SRC)) return { ok: false, error: 'source db not found: ' + BACKUP_SRC };
@@ -271,24 +462,33 @@ async function performBackup(auto) {
271
462
  const dir = backupDirName();
272
463
  const destDir = path.join(BACKUP_DIR, dir);
273
464
  fs.mkdirSync(destDir, { recursive: true });
274
- let size = 0;
465
+ let totalOrigSize = 0;
466
+ let totalCompSize = 0;
467
+ const compressedFiles = [];
275
468
  for (const n of files) {
276
- fs.copyFileSync(path.join(srcDir, n), path.join(destDir, n));
277
- size += fs.statSync(path.join(destDir, n)).size;
278
- }
279
- if (auto) lastAutoBackupDay = dir.slice(9, 17);
280
- if (BACKUP_RETENTION > 0) {
281
- const dirs = fs.readdirSync(BACKUP_DIR)
282
- .filter((f) => f.startsWith('opencode-') && fs.statSync(path.join(BACKUP_DIR, f)).isDirectory())
283
- .sort();
284
- if (dirs.length > BACKUP_RETENTION) {
285
- for (const f of dirs.slice(0, dirs.length - BACKUP_RETENTION)) {
286
- fs.rmSync(path.join(BACKUP_DIR, f), { recursive: true, force: true });
287
- }
469
+ const srcPath = path.join(srcDir, n);
470
+ const dstPath = path.join(destDir, n);
471
+ fs.copyFileSync(srcPath, dstPath);
472
+ try {
473
+ const { origSize, compSize } = await compressFile(dstPath);
474
+ totalOrigSize += origSize;
475
+ totalCompSize += compSize;
476
+ compressedFiles.push(n + '.gz');
477
+ } catch (_) {
478
+ totalOrigSize += fs.statSync(dstPath).size;
479
+ totalCompSize += fs.statSync(dstPath).size;
480
+ compressedFiles.push(n);
288
481
  }
289
482
  }
290
- console.log(`backup ok: ${dir} (${(size / 1024 / 1024).toFixed(1)} MB)`);
291
- return { ok: true, file: dir, size, files };
483
+ if (auto) {
484
+ const d = new Date();
485
+ const p = (n) => String(n).padStart(2, '0');
486
+ lastAutoBackupDay = `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}`;
487
+ }
488
+ cleanupOldBackups();
489
+ const ratio = totalOrigSize > 0 ? ((1 - totalCompSize / totalOrigSize) * 100).toFixed(1) : 0;
490
+ console.log(`backup ok: ${dir} (${(totalCompSize / 1024 / 1024).toFixed(1)} MB, compressed ${ratio}%)`);
491
+ return { ok: true, file: dir, size: totalCompSize, origSize: totalOrigSize, files: compressedFiles };
292
492
  } catch (e) {
293
493
  return { ok: false, error: e.message };
294
494
  } finally {
@@ -299,11 +499,12 @@ async function performBackup(auto) {
299
499
  async function autoBackupIfDue() {
300
500
  const d = new Date();
301
501
  const p = (n) => String(n).padStart(2, '0');
302
- const day = `opencode-${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}`;
303
- if (lastAutoBackupDay === day.slice(9, 17)) return;
502
+ const day = `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}`;
503
+ if (lastAutoBackupDay === day) return;
304
504
  try {
305
- if (fs.readdirSync(BACKUP_DIR).some((f) => f.startsWith(day) && fs.statSync(path.join(BACKUP_DIR, f)).isDirectory())) {
306
- lastAutoBackupDay = day.slice(9, 17);
505
+ const existing = fs.readdirSync(BACKUP_DIR).some((f) => f.startsWith(`opencode-${day}`) && fs.statSync(path.join(BACKUP_DIR, f)).isDirectory());
506
+ if (existing) {
507
+ lastAutoBackupDay = day;
307
508
  return;
308
509
  }
309
510
  } catch (e) { /* dir not created yet */ }
@@ -313,17 +514,63 @@ async function autoBackupIfDue() {
313
514
  const reportCache = {};
314
515
  const reportBusy = {};
315
516
 
517
+ function periodStartMs(days, now) {
518
+ if (days === -1) return 0;
519
+ const d = new Date(now);
520
+ d.setHours(0, 0, 0, 0);
521
+ if (days <= 1) return d.getTime(); // Daily = today (local)
522
+ if (days <= 7) { d.setDate(d.getDate() - 6); return d.getTime(); } // Weekly = 7 local days
523
+ d.setDate(1);
524
+ return d.getTime(); // Monthly = month-to-date (local)
525
+ }
526
+
316
527
  function buildReportFromDb(days) {
317
528
  const now = Date.now();
318
- const startMs = days === -1 ? 0 : days <= 1 ? now - 86400000 : days <= 7 ? now - days * 86400000 : (() => {
319
- const d = new Date(); d.setDate(1); d.setHours(0, 0, 0, 0); return d.getTime();
320
- })();
529
+ const startMs = periodStartMs(days, now);
321
530
  const label = days === -1 ? 'All' : days <= 1 ? 'Daily' : days <= 7 ? 'Weekly' : 'Monthly';
322
- const where = startMs ? `WHERE time_updated >= ${startMs}` : '';
323
531
 
324
- const statsR = getStatsFromDb(days);
325
- const agentRows = dbQuery(`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 ${startMs ? `AND time_updated >= ${startMs}` : ''} GROUP BY agent ORDER BY cost DESC;`) || [];
326
- const providerRows = dbQuery(`SELECT COALESCE(json_extract(model,'$.providerID'), 'unknown') AS provider, COALESCE(json_extract(model,'$.id'), 'unknown') 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} GROUP BY provider, model ORDER BY cost DESC;`) || [];
532
+ // All breakdowns come from hybrid attribution over local-day boundaries,
533
+ // so cross-day sessions don't leak their full totals into one period.
534
+ const a = attributeUsage(startMs, now);
535
+ const t = a.totals;
536
+ const activeDays = Object.keys(a.perDay).length || 1;
537
+ const sessVals = Object.values(a.perSession)
538
+ .map((s) => s.input + s.output + s.reasoning)
539
+ .filter(Number.isFinite);
540
+ const avgTokens = sessVals.length ? sessVals.reduce((x, v) => x + v, 0) / sessVals.length : 0;
541
+ const statsR = {
542
+ ok: true,
543
+ overview: { sessions: t.sessions, messages: t.messages, days: activeDays },
544
+ cost: {
545
+ total: t.cost, avgDay: t.cost / activeDays,
546
+ avgTokensSession: Math.round(avgTokens),
547
+ medianTokensSession: Math.round(computeMedian(sessVals)),
548
+ input: Math.round(t.input), output: Math.round(t.output),
549
+ reasoning: Math.round(t.reasoning),
550
+ cacheRead: Math.round(t.cacheRead), cacheWrite: Math.round(t.cacheWrite),
551
+ },
552
+ tools: [], models: [],
553
+ };
554
+ const r4 = (v) => Math.round((v || 0) * 10000) / 10000;
555
+ const agentRows = Object.entries(a.perAgent)
556
+ .map(([agent, m]) => ({
557
+ agent, sessions: m.sessions.size, cost: r4(m.cost),
558
+ tok_in: Math.round(m.input), tok_out: Math.round(m.output),
559
+ tok_reasoning: Math.round(m.reasoning),
560
+ cache_read: Math.round(m.cacheRead),
561
+ }))
562
+ .sort((x, y) => y.cost - x.cost);
563
+ const providerRows = Object.entries(a.perModel)
564
+ .map(([name, m]) => {
565
+ const { provider, model } = splitModelName(name);
566
+ return {
567
+ provider, model, sessions: m.sessions.size, cost: r4(m.cost),
568
+ tok_in: Math.round(m.input), tok_out: Math.round(m.output),
569
+ tok_reasoning: Math.round(m.reasoning),
570
+ cache_read: Math.round(m.cacheRead),
571
+ };
572
+ })
573
+ .sort((x, y) => y.cost - x.cost);
327
574
 
328
575
  return {
329
576
  label,
@@ -356,12 +603,28 @@ function refreshReport(days) {
356
603
  const server = http.createServer(async (req, res) => {
357
604
  const url = new URL(req.url || '/', `http://127.0.0.1:${PORT}`);
358
605
  const u = url.pathname;
606
+
607
+ // Gzip compress JSON responses
608
+ const acceptEncoding = req.headers['accept-encoding'] || '';
609
+ const useGzip = acceptEncoding.includes('gzip') && u.startsWith('/api/');
610
+ const respond = (data, headers = {}) => {
611
+ const payload = typeof data === 'string' ? data : JSON.stringify(data);
612
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
613
+ res.setHeader('Cache-Control', 'no-store');
614
+ for (const [k, v] of Object.entries(headers)) res.setHeader(k, v);
615
+ if (useGzip && payload.length > 512) {
616
+ res.setHeader('Content-Encoding', 'gzip');
617
+ const compressed = zlib.gzipSync(Buffer.from(payload), { level: 6 });
618
+ res.end(compressed);
619
+ } else {
620
+ res.end(payload);
621
+ }
622
+ };
623
+
359
624
  if (u === '/api/stats') {
360
625
  const days = parseInt(url.searchParams.get('days') || '7', 10) || 7;
361
626
  const r = refreshTrend(days);
362
- res.setHeader('Content-Type', 'application/json; charset=utf-8');
363
- res.setHeader('Cache-Control', 'no-store');
364
- res.end(JSON.stringify({
627
+ respond({
365
628
  ok: !!state.data,
366
629
  loading: state.loading,
367
630
  error: state.error,
@@ -370,23 +633,81 @@ const server = http.createServer(async (req, res) => {
370
633
  models: state.models,
371
634
  trend: r.trend,
372
635
  trendReady: !!r.trend,
373
- }));
636
+ });
374
637
  } else if (u === '/api/report') {
375
638
  const daysParam = url.searchParams.get('days');
376
639
  const days = daysParam !== null ? (parseInt(daysParam, 10) || 0) : 0;
377
640
  const r = refreshReport(days);
378
- res.setHeader('Content-Type', 'application/json; charset=utf-8');
379
- res.setHeader('Cache-Control', 'no-store');
380
- res.end(JSON.stringify({
641
+ respond({
381
642
  ok: true,
382
643
  ready: r.ready,
383
644
  report: r.report,
384
- }));
385
- } else if (u === '/api/backup') {
386
- performBackup(false).then((r) => {
387
- res.setHeader('Content-Type', 'application/json; charset=utf-8');
388
- res.end(JSON.stringify(r));
389
645
  });
646
+ } else if (u === '/api/backup') {
647
+ performBackup(false).then((r) => { respond(r); });
648
+ } else if (u === '/api/backups') {
649
+ try {
650
+ const dirs = fs.readdirSync(BACKUP_DIR)
651
+ .filter((f) => f.startsWith('opencode-') && fs.statSync(path.join(BACKUP_DIR, f)).isDirectory())
652
+ .sort().reverse()
653
+ .map((f) => {
654
+ const dirPath = path.join(BACKUP_DIR, f);
655
+ const files = fs.readdirSync(dirPath);
656
+ let totalSize = 0;
657
+ for (const file of files) totalSize += fs.statSync(path.join(dirPath, file)).size;
658
+ return { name: f, size: totalSize, files };
659
+ });
660
+ respond({ ok: true, backups: dirs, retention: BACKUP_RETENTION });
661
+ } catch (e) { respond({ ok: false, error: e.message }); }
662
+ } else if (u === '/api/vacuum') {
663
+ if (!Database) { respond({ ok: false, error: 'better-sqlite3 not available' }); return; }
664
+ if (backupBusy || vacuumBusy) { respond({ ok: false, busy: true, error: 'backup or vacuum already running' }); return; }
665
+ vacuumBusy = true;
666
+ try {
667
+ const sizeBefore = fs.statSync(BACKUP_SRC).size;
668
+ const probe = new Database(BACKUP_SRC, { readonly: true, fileMustExist: true, timeout: 5000 });
669
+ let freelist = 0, pageSize = 4096, pageCount = 0;
670
+ try {
671
+ freelist = probe.prepare('PRAGMA freelist_count').get().freelist_count || 0;
672
+ pageSize = probe.prepare('PRAGMA page_size').get().page_size || 4096;
673
+ pageCount = probe.prepare('PRAGMA page_count').get().page_count || 0;
674
+ } finally { probe.close(); }
675
+ const reclaimable = freelist * pageSize;
676
+ if (reclaimable < 64 * 1024 * 1024) {
677
+ vacuumBusy = false;
678
+ console.log(`vacuum skipped: freelist ${(reclaimable / 1024 / 1024).toFixed(1)} MB < 64 MB (nothing to reclaim)`);
679
+ respond({ ok: false, skipped: true, reason: 'freelist too small, nothing to reclaim', freelistBytes: reclaimable, pageCount, pageSize });
680
+ return;
681
+ }
682
+ const d = new Database(BACKUP_SRC, { timeout: 15000 });
683
+ try { d.pragma('busy_timeout = 15000'); d.pragma('VACUUM'); } finally { d.close(); }
684
+ const sizeAfter = fs.statSync(BACKUP_SRC).size;
685
+ const saved = sizeBefore - sizeAfter;
686
+ console.log(`vacuum ok: ${(sizeBefore / 1024 / 1024).toFixed(1)} MB -> ${(sizeAfter / 1024 / 1024).toFixed(1)} MB (saved ${(saved / 1024 / 1024).toFixed(1)} MB)`);
687
+ respond({ ok: true, before: sizeBefore, after: sizeAfter, saved });
688
+ } catch (e) { respond({ ok: false, error: e.message }); } finally { vacuumBusy = false; }
689
+ } else if (u === '/api/db-info') {
690
+ try {
691
+ const dbPath = BACKUP_SRC;
692
+ const dbDir = path.dirname(dbPath);
693
+ const files = ['opencode.db', 'opencode.db-wal', 'opencode.db-shm']
694
+ .filter((n) => fs.existsSync(path.join(dbDir, n)))
695
+ .map((n) => { const stat = fs.statSync(path.join(dbDir, n)); return { name: n, size: stat.size, modified: stat.mtime }; });
696
+ const totalSize = files.reduce((s, f) => s + f.size, 0);
697
+ let pragma = null;
698
+ if (Database && fs.existsSync(dbPath)) {
699
+ try {
700
+ const probe = new Database(dbPath, { readonly: true, fileMustExist: true, timeout: 5000 });
701
+ try {
702
+ const freelist = probe.prepare('PRAGMA freelist_count').get().freelist_count || 0;
703
+ const pageSize = probe.prepare('PRAGMA page_size').get().page_size || 4096;
704
+ const pageCount = probe.prepare('PRAGMA page_count').get().page_count || 0;
705
+ pragma = { freelistBytes: freelist * pageSize, pageCount, pageSize };
706
+ } finally { probe.close(); }
707
+ } catch (_) {}
708
+ }
709
+ respond({ ok: true, path: dbPath, files, totalSize, pragma });
710
+ } catch (e) { respond({ ok: false, error: e.message }); }
390
711
  } else if (u === '/') {
391
712
  loadIndexHtml((err, data) => {
392
713
  if (err) {
@@ -419,10 +740,32 @@ setInterval(() => {
419
740
  autoBackupIfDue();
420
741
  }, CACHE_CLEANUP_MS);
421
742
 
422
- (async () => {
423
- server.listen(PORT, '127.0.0.1', () => {
424
- console.log(`opencode stats dashboard: http://127.0.0.1:${PORT}`);
743
+ function tryListen(port, maxPort) {
744
+ return new Promise((resolve) => {
745
+ server.once('error', (e) => {
746
+ if (e.code === 'EADDRINUSE') {
747
+ console.log(`port ${port} in use, trying ${port + 1}...`);
748
+ server.removeAllListeners();
749
+ if (port < (maxPort || port + 5)) {
750
+ resolve(tryListen(port + 1, maxPort));
751
+ } else {
752
+ console.error(`all ports ${PORT}-${maxPort || PORT + 5} in use`);
753
+ process.exit(1);
754
+ }
755
+ } else {
756
+ console.error(e);
757
+ process.exit(1);
758
+ }
759
+ });
760
+ server.listen(port, '127.0.0.1', () => {
761
+ console.log(`opencode stats dashboard: http://127.0.0.1:${port}`);
762
+ resolve(port);
763
+ });
425
764
  });
765
+ }
766
+
767
+ (async () => {
768
+ const actualPort = await tryListen(PORT, PORT + 5);
426
769
  setInterval(refresh, REFRESH_MS);
427
770
  setInterval(refreshModels, 60000);
428
771
  await refresh();
package/start.ps1 CHANGED
@@ -1,4 +1,4 @@
1
1
  $dir = Split-Path -Parent $MyInvocation.MyCommand.Path
2
- Start-Process -FilePath "node" -ArgumentList "`"$dir\server.js`"" -WorkingDirectory $dir
2
+ Start-Process -FilePath "node" -ArgumentList "`"$dir\server.js`"" -WorkingDirectory $dir -WindowStyle Hidden -RedirectStandardOutput "$dir\server.out.log" -RedirectStandardError "$dir\server.err.log"
3
3
  Start-Sleep -Seconds 2
4
4
  Start-Process "http://127.0.0.1:4868"