opencode-statboard 1.0.12 → 1.1.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.
Files changed (3) hide show
  1. package/package.json +4 -1
  2. package/public/index.html +28 -0
  3. package/server.js +228 -187
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-statboard",
3
- "version": "1.0.12",
3
+ "version": "1.1.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
@@ -20,6 +20,9 @@
20
20
  .pill.err { color: #f85149; border-color: #da3633; background: rgba(248,81,73,.08); }
21
21
  .pill.lang { color: var(--text); border-color: var(--border); background: rgba(139,148,158,.08); }
22
22
  .pill.lang:hover { background: rgba(139,148,158,.18); }
23
+ .pill.backup { color: var(--cache); border-color: var(--cache); background: rgba(210,153,34,.08); }
24
+ .pill.backup:hover { background: rgba(210,153,34,.18); }
25
+ .pill.backup.busy { opacity: .6; pointer-events: none; }
23
26
  .range-btns { display: flex; gap: 4px; }
24
27
  .range-btns .pill.active { color: var(--text); border-color: #58a6ff; background: rgba(88,166,255,.12); }
25
28
  .range-btns .pill:not(.active) { color: var(--muted); border-color: var(--border); background: transparent; }
@@ -78,6 +81,7 @@
78
81
  <span id="updated">Loading…</span>
79
82
  <span class="pill ok" id="pill" data-i18n="live">Live</span>
80
83
  <span class="pill lang" id="langBtn" onclick="toggleLang()"></span>
84
+ <span class="pill backup" id="backupBtn" onclick="backupDb()" data-i18n="backup">Backup DB</span>
81
85
  </div>
82
86
  </header>
83
87
 
@@ -181,6 +185,7 @@ const STRINGS = {
181
185
  live: 'Live', loading: 'Loading…', lastUpdated: 'Last updated', dataAgo: 'data generated',
182
186
  statsFail: 'Failed to read opencode stats', connFail: 'Connection failed',
183
187
  langBtn: '繁中',
188
+ backup: 'Backup DB', backingUp: 'Backing up…', backupFail: 'Backup failed',
184
189
  },
185
190
  'zh-TW': {
186
191
  title: 'opencode 用量儀表板',
@@ -197,6 +202,7 @@ const STRINGS = {
197
202
  live: '即時更新', loading: '載入中…', lastUpdated: '更新於', dataAgo: '數據產生於',
198
203
  statsFail: 'opencode stats 讀取失敗', connFail: '連線失敗',
199
204
  langBtn: 'EN',
205
+ backup: '備份 DB', backingUp: '備份中…', backupFail: '備份失敗',
200
206
  }
201
207
  };
202
208
 
@@ -221,6 +227,28 @@ function toggleLang() {
221
227
  applyI18n();
222
228
  }
223
229
 
230
+ async function backupDb() {
231
+ const btn = $('backupBtn');
232
+ btn.classList.add('busy');
233
+ btn.textContent = t('backingUp');
234
+ try {
235
+ const r = await fetch('/api/backup', { cache: 'no-store' });
236
+ const j = await r.json();
237
+ if (j.ok && j.file) {
238
+ btn.textContent = '✓ ' + j.file;
239
+ btn.title = (j.size / 1024 / 1024).toFixed(1) + ' MB';
240
+ } else {
241
+ btn.textContent = '✗ ' + t('backupFail');
242
+ btn.title = j.error || '';
243
+ }
244
+ } catch (e) {
245
+ btn.textContent = '✗ ' + t('backupFail');
246
+ btn.title = e.message;
247
+ }
248
+ btn.classList.remove('busy');
249
+ setTimeout(() => { btn.textContent = t('backup'); }, 5000);
250
+ }
251
+
224
252
  const $ = (id) => document.getElementById(id);
225
253
  let currentDays = parseInt(localStorage.getItem('trendDays') || '7', 10);
226
254
 
package/server.js CHANGED
@@ -4,11 +4,20 @@ const http = require('http');
4
4
  const fs = require('fs');
5
5
  const path = require('path');
6
6
 
7
+ let Database;
8
+ try { Database = require('better-sqlite3'); } catch (_) { Database = null; }
9
+
7
10
  const PORT = 4868;
8
11
  const REFRESH_MS = 15000;
9
12
  const TREND_MS = 10 * 60 * 1000;
10
13
  const REPORT_TTL = 10 * 60 * 1000;
14
+ const STATS_TTL = 10 * 60 * 1000;
11
15
  const CACHE_CLEANUP_MS = 5 * 60 * 1000;
16
+ const BACKUP_DIR = path.join(__dirname, 'backups');
17
+ const BACKUP_RETENTION = parseInt(process.env.OPENCODE_BACKUP_RETENTION || '0', 10) || 0;
18
+ const BACKUP_SRC = process.env.OPENCODE_DATA
19
+ ? path.join(process.env.OPENCODE_DATA, 'opencode.db')
20
+ : path.join(process.env.USERPROFILE || process.env.HOME || '', '.local', 'share', 'opencode', 'opencode.db');
12
21
  const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
13
22
  const VERSION = pkg.version;
14
23
 
@@ -20,10 +29,25 @@ const EXE = (() => {
20
29
  return 'opencode';
21
30
  })();
22
31
 
32
+ let db = null;
33
+ function getDb() {
34
+ if (db) return db;
35
+ if (!Database) return null;
36
+ if (!fs.existsSync(BACKUP_SRC)) return null;
37
+ try {
38
+ db = new Database(BACKUP_SRC, { readonly: true, fileMustExist: true });
39
+ db.pragma('journal_mode = WAL');
40
+ return db;
41
+ } catch (_) { return null; }
42
+ }
43
+
23
44
  const state = { data: null, busy: false, error: null, updatedAt: 0, models: null, modelsBusy: false, loading: true };
24
45
 
25
46
  let indexHtmlCache = null;
26
47
 
48
+ let backupBusy = false;
49
+ let lastAutoBackupDay = '';
50
+
27
51
  function loadIndexHtml(callback) {
28
52
  if (indexHtmlCache) return callback(null, indexHtmlCache);
29
53
  fs.readFile(path.join(__dirname, 'public', 'index.html'), 'utf8', (err, data) => {
@@ -42,6 +66,18 @@ function run(args, timeout = 120000) {
42
66
  });
43
67
  }
44
68
 
69
+ function dbQuery(sql) {
70
+ const d = getDb();
71
+ if (!d) return null;
72
+ try { return d.prepare(sql).all(); } catch (_) { return null; }
73
+ }
74
+
75
+ function dbGet(sql) {
76
+ const d = getDb();
77
+ if (!d) return null;
78
+ try { return d.prepare(sql).get(); } catch (_) { return null; }
79
+ }
80
+
45
81
  const trendCache = {};
46
82
  const trendBusy = {};
47
83
  const trendPending = {};
@@ -55,57 +91,40 @@ function cleanExpiredCache(cache, ttl) {
55
91
  }
56
92
  }
57
93
 
58
- async function generateTrend(days, retries = 2) {
59
- const step = days > 30 ? 3 : 1;
60
- const points = Math.ceil(days / step);
94
+ async function generateTrend(days) {
61
95
  const now = Date.now();
62
-
63
- async function getDailyStats(dayOffset) {
64
- const startOfDay = new Date();
65
- startOfDay.setHours(0, 0, 0, 0);
66
- startOfDay.setDate(startOfDay.getDate() - dayOffset);
67
- const startMs = startOfDay.getTime();
68
-
69
- const endOfDay = new Date(startOfDay);
70
- endOfDay.setDate(endOfDay.getDate() + 1);
71
- const endMs = endOfDay.getTime();
72
-
73
- 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']);
74
- if (!r.ok) return null;
75
- const rows = parseTSV(r.out);
76
- if (!rows.length) return null;
77
- const row = rows[0];
78
- return {
79
- sessions: parseInt(row.sessions) || 0,
80
- input: parseFloat(row.input) || 0,
81
- output: parseFloat(row.output) || 0,
82
- cacheRead: parseFloat(row.cacheRead) || 0,
83
- total: parseFloat(row.total) || 0,
84
- };
85
- }
86
-
87
- const results = new Array(points);
88
- let next = 0;
89
- const worker = async () => {
90
- while (next < points) {
91
- const i = next++;
92
- results[i] = await getDailyStats(i * step);
93
- }
94
- };
95
- await Promise.all(Array.from({ length: 4 }, worker));
96
- if (results.some((r) => !r)) {
97
- if (retries > 0) {
98
- await new Promise((r) => setTimeout(r, 1000));
99
- return generateTrend(days, retries - 1);
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
+ }
100
113
  }
101
- return null;
102
114
  }
103
-
115
+
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 });
121
+ }
122
+
104
123
  return {
105
124
  generatedAt: now,
106
- step,
125
+ step: 1,
107
126
  labels: results.map((_, i) => {
108
- const d = new Date(now - (i * step) * 86400000);
127
+ const d = new Date(now - i * 86400000);
109
128
  return (d.getMonth() + 1) + '/' + d.getDate();
110
129
  }),
111
130
  sessions: results.map((b) => b.sessions),
@@ -135,172 +154,184 @@ function refreshTrend(days) {
135
154
  return { trend: hit ? Object.assign({}, hit, { stale: true }) : null, pending };
136
155
  }
137
156
 
138
- const clean = (s) => String(s).replace(/[^\x20-\x7E\n]/g, '');
139
-
140
- function toNum(s) {
141
- const t = String(s).replace(/,/g, '').trim();
142
- const m = /^([\d.]+)([KMB])?$/i.exec(t);
143
- if (!m) return NaN;
144
- let v = parseFloat(m[1]);
145
- if (m[2]) v *= { K: 1e3, M: 1e6, B: 1e9 }[m[2].toUpperCase()];
146
- return v;
157
+ function computeMedian(arr) {
158
+ if (!arr.length) return 0;
159
+ const sorted = arr.slice().sort((a, b) => a - b);
160
+ const mid = Math.floor(sorted.length / 2);
161
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
147
162
  }
148
163
 
149
- const money = (s) => {
150
- const m = /([\d.]+)/.exec(String(s));
151
- return m ? parseFloat(m[1]) : NaN;
152
- };
164
+ function getStatsFromDb(days) {
165
+ const now = Date.now();
166
+ const startMs = days > 0 ? now - days * 86400000 : 0;
167
+ const timeFilter = startMs ? `AND s.time_updated >= ${startMs}` : '';
168
+ const timeFilterPart = startMs ? `AND p.time_updated >= ${startMs}` : '';
169
+ const timeFilterWhere = startMs ? `WHERE s.time_updated >= ${startMs}` : '';
170
+
171
+ const overview = dbGet(`SELECT COUNT(*) AS sessions, COUNT(DISTINCT CAST(s.time_updated / 86400000 AS INTEGER)) AS days FROM session s ${timeFilterWhere};`);
172
+ 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};`);
174
+
175
+ const toolRows = dbQuery(`SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' ${timeFilterPart};`) || [];
176
+ const toolCounts = {};
177
+ for (const row of toolRows) {
178
+ if (row.tool) toolCounts[row.tool] = (toolCounts[row.tool] || 0) + 1;
179
+ }
180
+ const totalToolUse = Object.values(toolCounts).reduce((s, v) => s + v, 0) || 1;
181
+ const tools = Object.entries(toolCounts)
182
+ .map(([name, count]) => ({ name, count, pct: Math.round((count / totalToolUse) * 1000) / 10 }))
183
+ .sort((a, b) => b.count - a.count);
153
184
 
154
- function parseStats(text) {
155
- const c = clean(text);
156
- const grab = (re) => { const m = re.exec(c); return m ? m[1] : null; };
157
- const out = {
185
+ const tokenRows = dbQuery(`SELECT tokens_input + tokens_output AS tokens FROM session s ${timeFilterWhere};`) || [];
186
+ const tokenVals = tokenRows.map((r) => r.tokens).filter(Number.isFinite);
187
+ const avgTokens = tokenVals.length ? tokenVals.reduce((s, v) => s + v, 0) / tokenVals.length : 0;
188
+ const medianTokens = computeMedian(tokenVals);
189
+ const activeDays = overview ? (overview.days || 1) : 1;
190
+ const sessions = overview ? (overview.sessions || 0) : 0;
191
+ const avgDayCost = costRow && costRow.total ? costRow.total / activeDays : 0;
192
+
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;`) || [];
194
+
195
+ return {
196
+ ok: true,
158
197
  overview: {
159
- sessions: toNum(grab(/Sessions\s+([\d,]+)/)),
160
- messages: toNum(grab(/Messages\s+([\d,]+)/)),
161
- days: toNum(grab(/Days\s+([\d,]+)/)),
198
+ sessions: sessions,
199
+ messages: msgCount ? (msgCount.messages || 0) : 0,
200
+ days: activeDays,
162
201
  },
163
202
  cost: {
164
- total: money(grab(/Total Cost\s*\$([\d.]+)/)),
165
- avgDay: money(grab(/Avg Cost\/Day\s*\$([\d.]+)/)),
166
- avgTokensSession: toNum(grab(/Avg Tokens\/Session\s+([\d.]+[KMB]?)/)),
167
- medianTokensSession: toNum(grab(/Median Tokens\/Session\s+([\d.]+[KMB]?)/)),
168
- input: toNum(grab(/^Input\s+([\d.]+[KMB]?)/m)),
169
- output: toNum(grab(/^Output\s+([\d.]+[KMB]?)/m)),
170
- cacheRead: toNum(grab(/^Cache Read\s+([\d.]+[KMB]?)/m)),
171
- cacheWrite: toNum(grab(/^Cache Write\s+([\d.]+[KMB]?)/m)),
203
+ total: costRow ? costRow.total : 0,
204
+ avgDay: avgDayCost,
205
+ avgTokensSession: Math.round(avgTokens),
206
+ medianTokensSession: Math.round(medianTokens),
207
+ input: costRow ? costRow.input : 0,
208
+ output: costRow ? costRow.output : 0,
209
+ cacheRead: costRow ? costRow.cacheRead : 0,
210
+ cacheWrite: costRow ? costRow.cacheWrite : 0,
172
211
  },
173
- tools: [],
174
- models: [],
212
+ tools,
213
+ models,
175
214
  };
176
-
177
- for (const line of c.split('\n')) {
178
- const m = /^\s*([\w.\-]+)\s+([\d,]+)\s*\(\s*([\d.]+)%\)/.exec(line);
179
- if (m) out.tools.push({ name: m[1], count: parseInt(m[2].replace(/,/g, ''), 10), pct: parseFloat(m[3]) });
180
- }
181
-
182
- let cur = null;
183
- const setv = (cur, line, re, key, isMoney) => {
184
- const m = re.exec(line);
185
- if (m) cur[key] = isMoney ? money(m[1]) : toNum(m[1]);
186
- };
187
- for (const line of c.split('\n')) {
188
- const name = /^\s*([a-zA-Z0-9_.\-]+\/[a-zA-Z0-9_.\-]+)\s*$/.exec(line);
189
- if (name) {
190
- cur = { name: name[1], messages: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
191
- out.models.push(cur);
192
- continue;
193
- }
194
- if (!cur) continue;
195
- setv(cur, line, /Messages\s+([\d,]+)/, 'messages', false);
196
- setv(cur, line, /Input Tokens\s+([\d.]+[KMB]?)/, 'input', false);
197
- setv(cur, line, /Output Tokens\s+([\d.]+[KMB]?)/, 'output', false);
198
- setv(cur, line, /Cache Read\s+([\d.]+[KMB]?)/, 'cacheRead', false);
199
- setv(cur, line, /Cache Write\s+([\d.]+[KMB]?)/, 'cacheWrite', false);
200
- setv(cur, line, /Cost\s+(\$[\d.]+)/, 'cost', true);
201
- }
202
- return out;
203
- }
204
-
205
- function validRow(p) {
206
- return Number.isFinite(p.overview.sessions) && Number.isFinite(p.overview.messages);
207
- }
208
-
209
- async function runStats(args) {
210
- const r = await run(args);
211
- if (!r.ok) return null;
212
- const p = parseStats(r.out);
213
- if (!validRow(p)) return null;
214
- return Object.assign({ ok: true }, p);
215
215
  }
216
216
 
217
217
  async function refresh() {
218
218
  if (state.busy) return;
219
219
  state.busy = true;
220
- const p = await runStats(['stats']);
221
- if (p) {
222
- state.data = p;
223
- state.error = null;
224
- state.updatedAt = Date.now();
225
- } else {
226
- state.error = state.error || 'opencode stats failed';
220
+ try {
221
+ const p = getStatsFromDb(0);
222
+ if (p && p.ok) {
223
+ state.data = p;
224
+ state.error = null;
225
+ state.updatedAt = Date.now();
226
+ } else {
227
+ state.error = state.error || 'failed to read database';
228
+ }
229
+ } catch (e) {
230
+ state.error = e.message;
227
231
  }
228
232
  state.loading = false;
229
233
  state.busy = false;
230
234
  }
231
235
 
236
+ 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
+ }));
247
+ }
248
+
232
249
  async function refreshModels() {
233
250
  if (state.modelsBusy) return;
234
251
  state.modelsBusy = true;
235
- const p = await runStats(['stats', '--models', '10']);
236
- if (p) state.models = p.models;
252
+ try {
253
+ state.models = getModelsFromDb();
254
+ } catch (_) {}
237
255
  state.modelsBusy = false;
238
256
  }
239
257
 
240
- function clamp(n) {
241
- return Number.isFinite(n) && n > 0 ? n : 0;
258
+ function backupDirName() {
259
+ const d = new Date();
260
+ const p = (n) => String(n).padStart(2, '0');
261
+ return `opencode-${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
242
262
  }
243
263
 
244
- function safeNum(v) {
245
- return Number.isFinite(v) ? v : 0;
264
+ async function performBackup(auto) {
265
+ if (backupBusy) return { ok: false, busy: true };
266
+ backupBusy = true;
267
+ try {
268
+ if (!fs.existsSync(BACKUP_SRC)) return { ok: false, error: 'source db not found: ' + BACKUP_SRC };
269
+ const srcDir = path.dirname(BACKUP_SRC);
270
+ const files = ['opencode.db', 'opencode.db-wal', 'opencode.db-shm'].filter((n) => fs.existsSync(path.join(srcDir, n)));
271
+ const dir = backupDirName();
272
+ const destDir = path.join(BACKUP_DIR, dir);
273
+ fs.mkdirSync(destDir, { recursive: true });
274
+ let size = 0;
275
+ 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
+ }
288
+ }
289
+ }
290
+ console.log(`backup ok: ${dir} (${(size / 1024 / 1024).toFixed(1)} MB)`);
291
+ return { ok: true, file: dir, size, files };
292
+ } catch (e) {
293
+ return { ok: false, error: e.message };
294
+ } finally {
295
+ backupBusy = false;
296
+ }
246
297
  }
247
298
 
248
- function sub(a, b) {
249
- return {
250
- sessions: clamp(safeNum(a.overview.sessions) - safeNum(b.overview.sessions)),
251
- messages: clamp(safeNum(a.overview.messages) - safeNum(b.overview.messages)),
252
- total: clamp(safeNum(a.cost.total) - safeNum(b.cost.total)),
253
- input: clamp(safeNum(a.cost.input) - safeNum(b.cost.input)),
254
- output: clamp(safeNum(a.cost.output) - safeNum(b.cost.output)),
255
- cacheRead: clamp(safeNum(a.cost.cacheRead) - safeNum(b.cost.cacheRead)),
256
- };
299
+ async function autoBackupIfDue() {
300
+ const d = new Date();
301
+ 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;
304
+ 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);
307
+ return;
308
+ }
309
+ } catch (e) { /* dir not created yet */ }
310
+ await performBackup(true);
257
311
  }
258
312
 
259
313
  const reportCache = {};
260
314
  const reportBusy = {};
261
315
 
262
- function parseTSV(text) {
263
- if (!text) return [];
264
- const cleaned = text.replace(/[^\x20-\x7E\n\t]/g, '');
265
- const lines = cleaned.trim().split('\n');
266
- if (lines.length < 2) return [];
267
- const headers = lines[0].split('\t');
268
- return lines.slice(1).map((line) => {
269
- const cols = line.split('\t');
270
- const obj = {};
271
- headers.forEach((h, i) => { obj[h.trim()] = (cols[i] || '').trim(); });
272
- return obj;
273
- });
274
- }
275
-
276
- async function buildReport(days) {
316
+ function buildReportFromDb(days) {
317
+ 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
+ })();
277
321
  const label = days === -1 ? 'All' : days <= 1 ? 'Daily' : days <= 7 ? 'Weekly' : 'Monthly';
278
- const timeFilter = days === -1
279
- ? '1=1'
280
- : days <= 1
281
- ? `(strftime('%s','now','start of day') * 1000)`
282
- : days <= 7
283
- ? `(strftime('%s','now','start of day', '-${days - 1} day') * 1000)`
284
- : `(strftime('%s','now','start of month') * 1000)`;
285
- let statsR = days === -1
286
- ? await runStats(['stats', '--models', '20'])
287
- : await runStats(['stats', '--days', String(Math.max(days, 1)), '--models', '20']);
288
- if (!statsR) {
289
- await new Promise((r) => setTimeout(r, 2000));
290
- statsR = days === -1
291
- ? await runStats(['stats', '--models', '20'])
292
- : await runStats(['stats', '--days', String(Math.max(days, 1)), '--models', '20']);
293
- }
294
- const [agentR, modelR] = await Promise.all([
295
- 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']),
296
- 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']),
297
- ]);
322
+ const where = startMs ? `WHERE time_updated >= ${startMs}` : '';
323
+
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;`) || [];
327
+
298
328
  return {
299
- label: label,
300
- days: days,
329
+ label,
330
+ days,
301
331
  stats: statsR,
302
- agents: parseTSV(agentR.out),
303
- providers: parseTSV(modelR.out),
332
+ agents: agentRows,
333
+ providers: providerRows,
334
+ generatedAt: now,
304
335
  };
305
336
  }
306
337
 
@@ -311,13 +342,13 @@ function refreshReport(days) {
311
342
  if (fresh) return { report: hit, ready: true };
312
343
  if (!reportBusy[key]) {
313
344
  reportBusy[key] = true;
314
- buildReport(days).then((r) => {
345
+ try {
346
+ const r = buildReportFromDb(days);
315
347
  if (r && r.stats && r.stats.ok) {
316
- reportCache[key] = Object.assign({}, r, { generatedAt: Date.now() });
348
+ reportCache[key] = r;
317
349
  }
318
- }).catch(() => {}).finally(() => {
319
- delete reportBusy[key];
320
- });
350
+ } catch (_) {}
351
+ delete reportBusy[key];
321
352
  }
322
353
  return hit ? { report: Object.assign({}, hit, { stale: true }), ready: true } : { report: null, ready: false };
323
354
  }
@@ -351,6 +382,11 @@ const server = http.createServer(async (req, res) => {
351
382
  ready: r.ready,
352
383
  report: r.report,
353
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
+ });
354
390
  } else if (u === '/') {
355
391
  loadIndexHtml((err, data) => {
356
392
  if (err) {
@@ -369,9 +405,8 @@ const server = http.createServer(async (req, res) => {
369
405
 
370
406
  function gracefulShutdown() {
371
407
  console.log('\nShutting down...');
372
- server.close(() => {
373
- process.exit(0);
374
- });
408
+ if (db) try { db.close(); } catch (_) {}
409
+ server.close(() => { process.exit(0); });
375
410
  setTimeout(() => process.exit(1), 5000);
376
411
  }
377
412
 
@@ -381,6 +416,7 @@ process.on('SIGTERM', gracefulShutdown);
381
416
  setInterval(() => {
382
417
  cleanExpiredCache(trendCache, TREND_MS * 2);
383
418
  cleanExpiredCache(reportCache, REPORT_TTL * 2);
419
+ autoBackupIfDue();
384
420
  }, CACHE_CLEANUP_MS);
385
421
 
386
422
  (async () => {
@@ -392,11 +428,16 @@ setInterval(() => {
392
428
  await refresh();
393
429
  await refreshModels();
394
430
  for (const d of [1, 7, 30]) {
395
- const r = await buildReport(d);
396
- if (r && r.stats && r.stats.ok) reportCache[String(d)] = Object.assign({}, r, { generatedAt: Date.now() });
431
+ try {
432
+ const r = buildReportFromDb(d);
433
+ if (r && r.stats && r.stats.ok) reportCache[String(d)] = r;
434
+ } catch (_) {}
397
435
  }
398
436
  for (const d of [7, 30, 90]) {
399
- const t = await generateTrend(d);
400
- if (t) trendCache[String(d)] = t;
437
+ try {
438
+ const t = await generateTrend(d);
439
+ if (t) trendCache[String(d)] = t;
440
+ } catch (_) {}
401
441
  }
442
+ await autoBackupIfDue();
402
443
  })();