opencode-statboard 1.0.13 → 2.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-statboard",
3
- "version": "1.0.13",
3
+ "version": "2.0.0",
4
4
  "description": "Real-time dashboard for opencode token usage and cost statistics",
5
5
  "main": "server.js",
6
6
  "bin": {
@@ -21,5 +21,8 @@
21
21
  "repository": {
22
22
  "type": "git",
23
23
  "url": "https://github.com/thumb2086/opencode-usage-dashboard"
24
+ },
25
+ "dependencies": {
26
+ "better-sqlite3": "^13.0.3"
24
27
  }
25
28
  }
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>
@@ -224,6 +229,9 @@ function applyI18n() {
224
229
  function toggleLang() {
225
230
  lang = lang === 'en' ? 'zh-TW' : 'en';
226
231
  localStorage.setItem('lang', lang);
232
+ applyI18n();
233
+ }
234
+
227
235
  async function backupDb() {
228
236
  const btn = $('backupBtn');
229
237
  btn.classList.add('busy');
@@ -246,9 +254,6 @@ async function backupDb() {
246
254
  setTimeout(() => { btn.textContent = t('backup'); }, 5000);
247
255
  }
248
256
 
249
- applyI18n();
250
- }
251
-
252
257
  const $ = (id) => document.getElementById(id);
253
258
  let currentDays = parseInt(localStorage.getItem('trendDays') || '7', 10);
254
259
 
@@ -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,20 +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);
10
+
11
+ let Database;
12
+ try { Database = require('better-sqlite3'); } catch (_) { Database = null; }
6
13
 
7
14
  const PORT = 4868;
8
15
  const REFRESH_MS = 15000;
9
- const TREND_MS = 10 * 60 * 1000;
16
+ const TREND_MS = 60 * 1000;
10
17
  const REPORT_TTL = 10 * 60 * 1000;
18
+ const STATS_TTL = 10 * 60 * 1000;
11
19
  const CACHE_CLEANUP_MS = 5 * 60 * 1000;
12
20
  const BACKUP_DIR = path.join(__dirname, 'backups');
13
- 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;
14
22
  const BACKUP_SRC = process.env.OPENCODE_DATA
15
23
  ? path.join(process.env.OPENCODE_DATA, 'opencode.db')
16
24
  : path.join(process.env.USERPROFILE || process.env.HOME || '', '.local', 'share', 'opencode', 'opencode.db');
17
25
  const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
18
26
  const VERSION = pkg.version;
19
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
+
20
63
  const EXE = (() => {
21
64
  const candidates = [
22
65
  path.join(process.env.APPDATA || '', 'npm', 'node_modules', 'opencode-ai', 'bin', 'opencode.exe'),
@@ -25,11 +68,31 @@ const EXE = (() => {
25
68
  return 'opencode';
26
69
  })();
27
70
 
71
+ let db = null;
72
+ function getDb() {
73
+ if (db) return db;
74
+ if (!Database) return null;
75
+ if (!fs.existsSync(BACKUP_SRC)) return null;
76
+ try {
77
+ db = new Database(BACKUP_SRC, { readonly: true, fileMustExist: true });
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 (_) {}
86
+ return db;
87
+ } catch (_) { return null; }
88
+ }
89
+
28
90
  const state = { data: null, busy: false, error: null, updatedAt: 0, models: null, modelsBusy: false, loading: true };
29
91
 
30
92
  let indexHtmlCache = null;
31
93
 
32
94
  let backupBusy = false;
95
+ let vacuumBusy = false;
33
96
  let lastAutoBackupDay = '';
34
97
 
35
98
  function loadIndexHtml(callback) {
@@ -50,6 +113,23 @@ function run(args, timeout = 120000) {
50
113
  });
51
114
  }
52
115
 
116
+ function dbQuery(sql, params) {
117
+ const d = getDb();
118
+ if (!d) return null;
119
+ try { return params ? d.prepare(sql).all(...params) : d.prepare(sql).all(); } catch (_) { return null; }
120
+ }
121
+
122
+ function dbGet(sql, params) {
123
+ const d = getDb();
124
+ if (!d) 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();
131
+ }
132
+
53
133
  const trendCache = {};
54
134
  const trendBusy = {};
55
135
  const trendPending = {};
@@ -63,64 +143,41 @@ function cleanExpiredCache(cache, ttl) {
63
143
  }
64
144
  }
65
145
 
66
- async function generateTrend(days, retries = 2) {
67
- const step = days > 30 ? 3 : 1;
68
- const points = Math.ceil(days / step);
146
+ async function generateTrend(days) {
69
147
  const now = Date.now();
70
-
71
- async function getDailyStats(dayOffset) {
72
- const startOfDay = new Date();
73
- startOfDay.setHours(0, 0, 0, 0);
74
- startOfDay.setDate(startOfDay.getDate() - dayOffset);
75
- const startMs = startOfDay.getTime();
76
-
77
- const endOfDay = new Date(startOfDay);
78
- endOfDay.setDate(endOfDay.getDate() + 1);
79
- const endMs = endOfDay.getTime();
80
-
81
- const r = await run(['db', `SELECT 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} AND time_updated < ${endMs};`, '--format', 'tsv']);
82
- if (!r.ok) return null;
83
- const rows = parseTSV(r.out);
84
- if (!rows.length) return null;
85
- const row = rows[0];
86
- return {
87
- sessions: parseInt(row.sessions) || 0,
88
- input: parseFloat(row.input) || 0,
89
- output: parseFloat(row.output) || 0,
90
- cacheRead: parseFloat(row.cacheRead) || 0,
91
- total: parseFloat(row.total) || 0,
92
- };
148
+
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);
93
160
  }
94
-
95
- const results = new Array(points);
96
- let next = 0;
97
- const worker = async () => {
98
- while (next < points) {
99
- const i = next++;
100
- results[i] = await getDailyStats(i * step);
101
- }
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;
102
165
  };
103
- await Promise.all(Array.from({ length: 4 }, worker));
104
- if (results.some((r) => !r)) {
105
- if (retries > 0) {
106
- await new Promise((r) => setTimeout(r, 1000));
107
- return generateTrend(days, retries - 1);
108
- }
109
- return null;
110
- }
111
-
166
+ const sess = (b) => {
167
+ const D = a.perDay[localDayKey(b)];
168
+ return D ? D.sessions.size : 0;
169
+ };
170
+
112
171
  return {
113
172
  generatedAt: now,
114
- step,
115
- labels: results.map((_, i) => {
116
- const d = new Date(now - (i * step) * 86400000);
117
- return (d.getMonth() + 1) + '/' + d.getDate();
118
- }),
119
- sessions: results.map((b) => b.sessions),
120
- input: results.map((b) => b.input),
121
- output: results.map((b) => b.output),
122
- cacheRead: results.map((b) => b.cacheRead),
123
- cost: results.map((b) => b.total),
173
+ step: 1,
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')),
124
181
  };
125
182
  }
126
183
 
@@ -143,105 +200,249 @@ function refreshTrend(days) {
143
200
  return { trend: hit ? Object.assign({}, hit, { stale: true }) : null, pending };
144
201
  }
145
202
 
146
- const clean = (s) => String(s).replace(/[^\x20-\x7E\n]/g, '');
147
-
148
- function toNum(s) {
149
- const t = String(s).replace(/,/g, '').trim();
150
- const m = /^([\d.]+)([KMB])?$/i.exec(t);
151
- if (!m) return NaN;
152
- let v = parseFloat(m[1]);
153
- if (m[2]) v *= { K: 1e3, M: 1e6, B: 1e9 }[m[2].toUpperCase()];
154
- return v;
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) };
155
209
  }
156
210
 
157
- const money = (s) => {
158
- const m = /([\d.]+)/.exec(String(s));
159
- return m ? parseFloat(m[1]) : NaN;
160
- };
161
-
162
- function parseStats(text) {
163
- const c = clean(text);
164
- const grab = (re) => { const m = re.exec(c); return m ? m[1] : null; };
165
- const out = {
166
- overview: {
167
- sessions: toNum(grab(/Sessions\s+([\d,]+)/)),
168
- messages: toNum(grab(/Messages\s+([\d,]+)/)),
169
- days: toNum(grab(/Days\s+([\d,]+)/)),
170
- },
171
- cost: {
172
- total: money(grab(/Total Cost\s*\$([\d.]+)/)),
173
- avgDay: money(grab(/Avg Cost\/Day\s*\$([\d.]+)/)),
174
- avgTokensSession: toNum(grab(/Avg Tokens\/Session\s+([\d.]+[KMB]?)/)),
175
- medianTokensSession: toNum(grab(/Median Tokens\/Session\s+([\d.]+[KMB]?)/)),
176
- input: toNum(grab(/^Input\s+([\d.]+[KMB]?)/m)),
177
- output: toNum(grab(/^Output\s+([\d.]+[KMB]?)/m)),
178
- cacheRead: toNum(grab(/^Cache Read\s+([\d.]+[KMB]?)/m)),
179
- cacheWrite: toNum(grab(/^Cache Write\s+([\d.]+[KMB]?)/m)),
180
- },
181
- tools: [],
182
- models: [],
183
- };
184
-
185
- for (const line of c.split('\n')) {
186
- const m = /^\s*([\w.\-]+)\s+([\d,]+)\s*\(\s*([\d.]+)%\)/.exec(line);
187
- if (m) out.tools.push({ name: m[1], count: parseInt(m[2].replace(/,/g, ''), 10), pct: parseFloat(m[3]) });
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
+ }
188
259
  }
189
260
 
190
- let cur = null;
191
- const setv = (cur, line, re, key, isMoney) => {
192
- const m = re.exec(line);
193
- if (m) cur[key] = isMoney ? money(m[1]) : toNum(m[1]);
194
- };
195
- for (const line of c.split('\n')) {
196
- const name = /^\s*([a-zA-Z0-9_.\-]+\/[a-zA-Z0-9_.\-]+)\s*$/.exec(line);
197
- if (name) {
198
- cur = { name: name[1], messages: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
199
- out.models.push(cur);
200
- continue;
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;
201
303
  }
202
- if (!cur) continue;
203
- setv(cur, line, /Messages\s+([\d,]+)/, 'messages', false);
204
- setv(cur, line, /Input Tokens\s+([\d.]+[KMB]?)/, 'input', false);
205
- setv(cur, line, /Output Tokens\s+([\d.]+[KMB]?)/, 'output', false);
206
- setv(cur, line, /Cache Read\s+([\d.]+[KMB]?)/, 'cacheRead', false);
207
- setv(cur, line, /Cache Write\s+([\d.]+[KMB]?)/, 'cacheWrite', false);
208
- setv(cur, line, /Cost\s+(\$[\d.]+)/, 'cost', true);
209
304
  }
210
- return out;
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 };
211
314
  }
212
315
 
213
- function validRow(p) {
214
- return Number.isFinite(p.overview.sessions) && Number.isFinite(p.overview.messages);
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;
215
325
  }
216
326
 
217
- async function runStats(args) {
218
- const r = await run(args);
219
- if (!r.ok) return null;
220
- const p = parseStats(r.out);
221
- if (!validRow(p)) return null;
222
- return Object.assign({ ok: true }, p);
327
+ function computeMedian(arr) {
328
+ if (!arr.length) return 0;
329
+ const sorted = arr.slice().sort((a, b) => a - b);
330
+ const mid = Math.floor(sorted.length / 2);
331
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
332
+ }
333
+
334
+ function getStatsFromDb(days) {
335
+ const now = Date.now();
336
+ const startMs = days > 0 ? now - days * 86400000 : 0;
337
+ const timeFilter = startMs ? `AND s.time_updated >= ${startMs}` : '';
338
+ const timeFilterPart = startMs ? `AND p.time_updated >= ${startMs}` : '';
339
+ const timeFilterWhere = startMs ? `WHERE s.time_updated >= ${startMs}` : '';
340
+
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};`);
345
+ const msgCount = dbGet(`SELECT COUNT(*) AS messages FROM message m ${startMs ? `WHERE m.time_updated >= ${startMs}` : ''};`);
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};`);
347
+
348
+ const toolRows = dbQuery(`SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' ${timeFilterPart};`) || [];
349
+ const toolCounts = {};
350
+ for (const row of toolRows) {
351
+ if (row.tool) toolCounts[row.tool] = (toolCounts[row.tool] || 0) + 1;
352
+ }
353
+ const totalToolUse = Object.values(toolCounts).reduce((s, v) => s + v, 0) || 1;
354
+ const tools = Object.entries(toolCounts)
355
+ .map(([name, count]) => ({ name, count, pct: Math.round((count / totalToolUse) * 1000) / 10 }))
356
+ .sort((a, b) => b.count - a.count);
357
+
358
+ const tokenRows = dbQuery(`SELECT tokens_input + tokens_output + tokens_reasoning AS tokens FROM session s ${timeFilterWhere};`) || [];
359
+ const tokenVals = tokenRows.map((r) => r.tokens).filter(Number.isFinite);
360
+ const avgTokens = tokenVals.length ? tokenVals.reduce((s, v) => s + v, 0) / tokenVals.length : 0;
361
+ const medianTokens = computeMedian(tokenVals);
362
+ const activeDays = overview ? (overview.days || 1) : 1;
363
+ const sessions = overview ? (overview.sessions || 0) : 0;
364
+ const avgDayCost = costRow && costRow.total ? costRow.total / activeDays : 0;
365
+
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);
381
+
382
+ return {
383
+ ok: true,
384
+ overview: {
385
+ sessions: sessions,
386
+ messages: msgCount ? (msgCount.messages || 0) : 0,
387
+ days: activeDays,
388
+ },
389
+ cost: {
390
+ total: costRow ? costRow.total : 0,
391
+ avgDay: avgDayCost,
392
+ avgTokensSession: Math.round(avgTokens),
393
+ medianTokensSession: Math.round(medianTokens),
394
+ input: costRow ? costRow.input : 0,
395
+ output: costRow ? costRow.output : 0,
396
+ reasoning: costRow ? costRow.reasoning : 0,
397
+ cacheRead: costRow ? costRow.cacheRead : 0,
398
+ cacheWrite: costRow ? costRow.cacheWrite : 0,
399
+ },
400
+ tools,
401
+ models,
402
+ };
223
403
  }
224
404
 
225
405
  async function refresh() {
226
406
  if (state.busy) return;
227
407
  state.busy = true;
228
- const p = await runStats(['stats']);
229
- if (p) {
230
- state.data = p;
231
- state.error = null;
232
- state.updatedAt = Date.now();
233
- } else {
234
- state.error = state.error || 'opencode stats failed';
408
+ try {
409
+ const p = getStatsFromDb(0);
410
+ if (p && p.ok) {
411
+ state.data = p;
412
+ state.error = null;
413
+ state.updatedAt = Date.now();
414
+ } else {
415
+ state.error = state.error || 'failed to read database';
416
+ }
417
+ } catch (e) {
418
+ state.error = e.message;
235
419
  }
236
420
  state.loading = false;
237
421
  state.busy = false;
238
422
  }
239
423
 
424
+ function getModelsFromDb() {
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);
438
+ }
439
+
240
440
  async function refreshModels() {
241
441
  if (state.modelsBusy) return;
242
442
  state.modelsBusy = true;
243
- const p = await runStats(['stats', '--models', '10']);
244
- if (p) state.models = p.models;
443
+ try {
444
+ state.models = getModelsFromDb();
445
+ } catch (_) {}
245
446
  state.modelsBusy = false;
246
447
  }
247
448
 
@@ -252,7 +453,7 @@ function backupDirName() {
252
453
  }
253
454
 
254
455
  async function performBackup(auto) {
255
- if (backupBusy) return { ok: false, busy: true };
456
+ if (backupBusy || vacuumBusy) return { ok: false, busy: true };
256
457
  backupBusy = true;
257
458
  try {
258
459
  if (!fs.existsSync(BACKUP_SRC)) return { ok: false, error: 'source db not found: ' + BACKUP_SRC };
@@ -261,24 +462,33 @@ async function performBackup(auto) {
261
462
  const dir = backupDirName();
262
463
  const destDir = path.join(BACKUP_DIR, dir);
263
464
  fs.mkdirSync(destDir, { recursive: true });
264
- let size = 0;
465
+ let totalOrigSize = 0;
466
+ let totalCompSize = 0;
467
+ const compressedFiles = [];
265
468
  for (const n of files) {
266
- fs.copyFileSync(path.join(srcDir, n), path.join(destDir, n));
267
- size += fs.statSync(path.join(destDir, n)).size;
268
- }
269
- if (auto) lastAutoBackupDay = dir.slice(9, 17);
270
- if (BACKUP_RETENTION > 0) {
271
- const dirs = fs.readdirSync(BACKUP_DIR)
272
- .filter((f) => f.startsWith('opencode-') && fs.statSync(path.join(BACKUP_DIR, f)).isDirectory())
273
- .sort();
274
- if (dirs.length > BACKUP_RETENTION) {
275
- for (const f of dirs.slice(0, dirs.length - BACKUP_RETENTION)) {
276
- fs.rmSync(path.join(BACKUP_DIR, f), { recursive: true, force: true });
277
- }
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);
278
481
  }
279
482
  }
280
- console.log(`backup ok: ${dir} (${(size / 1024 / 1024).toFixed(1)} MB)`);
281
- 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 };
282
492
  } catch (e) {
283
493
  return { ok: false, error: e.message };
284
494
  } finally {
@@ -289,81 +499,86 @@ async function performBackup(auto) {
289
499
  async function autoBackupIfDue() {
290
500
  const d = new Date();
291
501
  const p = (n) => String(n).padStart(2, '0');
292
- const day = `opencode-${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}`;
293
- if (lastAutoBackupDay === day.slice(9, 17)) return;
502
+ const day = `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}`;
503
+ if (lastAutoBackupDay === day) return;
294
504
  try {
295
- if (fs.readdirSync(BACKUP_DIR).some((f) => f.startsWith(day) && fs.statSync(path.join(BACKUP_DIR, f)).isDirectory())) {
296
- 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;
297
508
  return;
298
509
  }
299
510
  } catch (e) { /* dir not created yet */ }
300
511
  await performBackup(true);
301
512
  }
302
513
 
303
- function clamp(n) {
304
- return Number.isFinite(n) && n > 0 ? n : 0;
305
- }
306
-
307
- function safeNum(v) {
308
- return Number.isFinite(v) ? v : 0;
309
- }
310
-
311
- function sub(a, b) {
312
- return {
313
- sessions: clamp(safeNum(a.overview.sessions) - safeNum(b.overview.sessions)),
314
- messages: clamp(safeNum(a.overview.messages) - safeNum(b.overview.messages)),
315
- total: clamp(safeNum(a.cost.total) - safeNum(b.cost.total)),
316
- input: clamp(safeNum(a.cost.input) - safeNum(b.cost.input)),
317
- output: clamp(safeNum(a.cost.output) - safeNum(b.cost.output)),
318
- cacheRead: clamp(safeNum(a.cost.cacheRead) - safeNum(b.cost.cacheRead)),
319
- };
320
- }
321
-
322
514
  const reportCache = {};
323
515
  const reportBusy = {};
324
516
 
325
- function parseTSV(text) {
326
- if (!text) return [];
327
- const cleaned = text.replace(/[^\x20-\x7E\n\t]/g, '');
328
- const lines = cleaned.trim().split('\n');
329
- if (lines.length < 2) return [];
330
- const headers = lines[0].split('\t');
331
- return lines.slice(1).map((line) => {
332
- const cols = line.split('\t');
333
- const obj = {};
334
- headers.forEach((h, i) => { obj[h.trim()] = (cols[i] || '').trim(); });
335
- return obj;
336
- });
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)
337
525
  }
338
526
 
339
- async function buildReport(days) {
527
+ function buildReportFromDb(days) {
528
+ const now = Date.now();
529
+ const startMs = periodStartMs(days, now);
340
530
  const label = days === -1 ? 'All' : days <= 1 ? 'Daily' : days <= 7 ? 'Weekly' : 'Monthly';
341
- const timeFilter = days === -1
342
- ? '1=1'
343
- : days <= 1
344
- ? `(strftime('%s','now','start of day') * 1000)`
345
- : days <= 7
346
- ? `(strftime('%s','now','start of day', '-${days - 1} day') * 1000)`
347
- : `(strftime('%s','now','start of month') * 1000)`;
348
- let statsR = days === -1
349
- ? await runStats(['stats', '--models', '20'])
350
- : await runStats(['stats', '--days', String(Math.max(days, 1)), '--models', '20']);
351
- if (!statsR) {
352
- await new Promise((r) => setTimeout(r, 2000));
353
- statsR = days === -1
354
- ? await runStats(['stats', '--models', '20'])
355
- : await runStats(['stats', '--days', String(Math.max(days, 1)), '--models', '20']);
356
- }
357
- const [agentR, modelR] = await Promise.all([
358
- 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 >= ${timeFilter} GROUP BY 1 ORDER BY cost DESC;`, '--format', 'tsv']),
359
- run(['db', `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 time_updated >= ${timeFilter} GROUP BY 1, 2 ORDER BY cost DESC;`, '--format', 'tsv']),
360
- ]);
531
+
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);
574
+
361
575
  return {
362
- label: label,
363
- days: days,
576
+ label,
577
+ days,
364
578
  stats: statsR,
365
- agents: parseTSV(agentR.out),
366
- providers: parseTSV(modelR.out),
579
+ agents: agentRows,
580
+ providers: providerRows,
581
+ generatedAt: now,
367
582
  };
368
583
  }
369
584
 
@@ -374,13 +589,13 @@ function refreshReport(days) {
374
589
  if (fresh) return { report: hit, ready: true };
375
590
  if (!reportBusy[key]) {
376
591
  reportBusy[key] = true;
377
- buildReport(days).then((r) => {
592
+ try {
593
+ const r = buildReportFromDb(days);
378
594
  if (r && r.stats && r.stats.ok) {
379
- reportCache[key] = Object.assign({}, r, { generatedAt: Date.now() });
595
+ reportCache[key] = r;
380
596
  }
381
- }).catch(() => {}).finally(() => {
382
- delete reportBusy[key];
383
- });
597
+ } catch (_) {}
598
+ delete reportBusy[key];
384
599
  }
385
600
  return hit ? { report: Object.assign({}, hit, { stale: true }), ready: true } : { report: null, ready: false };
386
601
  }
@@ -388,12 +603,28 @@ function refreshReport(days) {
388
603
  const server = http.createServer(async (req, res) => {
389
604
  const url = new URL(req.url || '/', `http://127.0.0.1:${PORT}`);
390
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
+
391
624
  if (u === '/api/stats') {
392
625
  const days = parseInt(url.searchParams.get('days') || '7', 10) || 7;
393
626
  const r = refreshTrend(days);
394
- res.setHeader('Content-Type', 'application/json; charset=utf-8');
395
- res.setHeader('Cache-Control', 'no-store');
396
- res.end(JSON.stringify({
627
+ respond({
397
628
  ok: !!state.data,
398
629
  loading: state.loading,
399
630
  error: state.error,
@@ -402,23 +633,81 @@ const server = http.createServer(async (req, res) => {
402
633
  models: state.models,
403
634
  trend: r.trend,
404
635
  trendReady: !!r.trend,
405
- }));
636
+ });
406
637
  } else if (u === '/api/report') {
407
638
  const daysParam = url.searchParams.get('days');
408
639
  const days = daysParam !== null ? (parseInt(daysParam, 10) || 0) : 0;
409
640
  const r = refreshReport(days);
410
- res.setHeader('Content-Type', 'application/json; charset=utf-8');
411
- res.setHeader('Cache-Control', 'no-store');
412
- res.end(JSON.stringify({
641
+ respond({
413
642
  ok: true,
414
643
  ready: r.ready,
415
644
  report: r.report,
416
- }));
417
- } else if (u === '/api/backup') {
418
- performBackup(false).then((r) => {
419
- res.setHeader('Content-Type', 'application/json; charset=utf-8');
420
- res.end(JSON.stringify(r));
421
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 }); }
422
711
  } else if (u === '/') {
423
712
  loadIndexHtml((err, data) => {
424
713
  if (err) {
@@ -437,9 +726,8 @@ const server = http.createServer(async (req, res) => {
437
726
 
438
727
  function gracefulShutdown() {
439
728
  console.log('\nShutting down...');
440
- server.close(() => {
441
- process.exit(0);
442
- });
729
+ if (db) try { db.close(); } catch (_) {}
730
+ server.close(() => { process.exit(0); });
443
731
  setTimeout(() => process.exit(1), 5000);
444
732
  }
445
733
 
@@ -461,12 +749,16 @@ setInterval(() => {
461
749
  await refresh();
462
750
  await refreshModels();
463
751
  for (const d of [1, 7, 30]) {
464
- const r = await buildReport(d);
465
- if (r && r.stats && r.stats.ok) reportCache[String(d)] = Object.assign({}, r, { generatedAt: Date.now() });
752
+ try {
753
+ const r = buildReportFromDb(d);
754
+ if (r && r.stats && r.stats.ok) reportCache[String(d)] = r;
755
+ } catch (_) {}
466
756
  }
467
757
  for (const d of [7, 30, 90]) {
468
- const t = await generateTrend(d);
469
- if (t) trendCache[String(d)] = t;
758
+ try {
759
+ const t = await generateTrend(d);
760
+ if (t) trendCache[String(d)] = t;
761
+ } catch (_) {}
470
762
  }
471
763
  await autoBackupIfDue();
472
764
  })();
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"