opencode-statboard 2.0.5 → 2.0.7

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/AGENTS.md +73 -0
  2. package/package.json +1 -1
  3. package/server.js +40 -25
package/AGENTS.md ADDED
@@ -0,0 +1,73 @@
1
+ # oc-stats (opencode-statboard)
2
+
3
+ Dashboard for opencode token usage and cost statistics. Published as `opencode-statboard` on npm.
4
+
5
+ ## Quick Start
6
+
7
+ ```bash
8
+ npm install -g opencode-statboard
9
+ opencode-dashboard
10
+ # Open http://127.0.0.1:4868
11
+ ```
12
+
13
+ ## Architecture
14
+
15
+ - `server.js` — Node.js HTTP server (zero frameworks, pure `http` module)
16
+ - `public/index.html` — Single-file frontend (vanilla JS/CSS/HTML, no build step)
17
+ - `backups/` — Gzipped DB backups (auto-rotated, `OPENCODE_BACKUP_RETENTION`)
18
+
19
+ ## Key Patterns
20
+
21
+ ### Data Source
22
+
23
+ All data comes from `opencode.db` (read-only via `better-sqlite3` with WAL mode). The DB is opened once and health-checked before each query (`SELECT 1`); if the connection is stale, it re-opens automatically.
24
+
25
+ ### Hybrid Attribution (`attributeUsage`)
26
+
27
+ Token/cost attribution uses a hybrid model:
28
+ 1. **Message-level** — Each assistant message's `tokens` and `cost` from `message.data` JSON are attributed to its `time_created` local day
29
+ 2. **Session residual** — `session.tokens_* - sum(message.tokens_*)` is spread across the session's full local-day span, weighted by per-day message volume
30
+
31
+ This ensures multi-day sessions (e.g. a session created Monday, updated Thursday) don't dump all tokens onto Thursday.
32
+
33
+ ### API Endpoints
34
+
35
+ | Endpoint | Description | Cache TTL |
36
+ |----------|-------------|-----------|
37
+ | `GET /api/stats?days=7` | Overview + trend data | 60s (trend) |
38
+ | `GET /api/report?days=1\|7\|30\|-1` | Usage report (Daily/Weekly/Monthly/All) | 10min |
39
+ | `GET /api/backup` | Manual backup trigger | — |
40
+ | `GET /api/backups` | List backups | — |
41
+ | `GET /api/vacuum` | DB vacuum (skips if freelist <64MB) | — |
42
+ | `GET /api/db-info` | DB file sizes + pragma | — |
43
+
44
+ ### Environment Variables
45
+
46
+ - `OC_PORT` — Listening port (default 4868, auto-fallbacks +5)
47
+ - `OPENCODE_DATA` — Custom path to `opencode.db`
48
+ - `OPENCODE_BACKUP_RETENTION` — Max backup dirs (default 3)
49
+
50
+ ## Verification
51
+
52
+ After any change, run:
53
+ ```bash
54
+ node check-stats-verify.js
55
+ node check-trend-verify.js 7
56
+ node check-report-verify.js
57
+ ```
58
+
59
+ ## Publishing
60
+
61
+ ```bash
62
+ npm set //registry.npmjs.org/:_authToken "$NPM_TOKEN"
63
+ npm version patch --no-git-tag-version
64
+ npm publish
65
+ npm config delete //registry.npmjs.org/:_authToken
66
+ ```
67
+
68
+ ## Known Constraints
69
+
70
+ - `better-sqlite3` is a native addon; must match Node.js ABI
71
+ - `attributeUsage` does a full DB scan (~22k messages); cached 300s via `getAttrAll()`
72
+ - Trend and report share the same `getAttrAll()` cache so daily values are consistent
73
+ - `gzip` compression on all `/api/` responses (>512B, level 1 for speed)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-statboard",
3
- "version": "2.0.5",
3
+ "version": "2.0.7",
4
4
  "description": "Real-time dashboard for opencode token usage and cost statistics",
5
5
  "main": "server.js",
6
6
  "bin": {
package/server.js CHANGED
@@ -30,14 +30,17 @@ function compressFile(srcPath) {
30
30
  const dstPath = srcPath + '.gz';
31
31
  const src = fs.createReadStream(srcPath);
32
32
  const dst = fs.createWriteStream(dstPath);
33
- const gzip = zlib.createGzip({ level: 6 });
33
+ const gzip = zlib.createGzip({ level: 1 });
34
34
  src.on('error', reject);
35
35
  dst.on('error', reject);
36
+ gzip.on('error', reject);
36
37
  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 });
38
+ try {
39
+ const origSize = fs.statSync(srcPath).size;
40
+ const compSize = fs.statSync(dstPath).size;
41
+ fs.unlinkSync(srcPath);
42
+ resolve({ origSize, compSize });
43
+ } catch (e) { reject(e); }
41
44
  });
42
45
  src.pipe(gzip).pipe(dst);
43
46
  });
@@ -794,8 +797,12 @@ function gracefulShutdown() {
794
797
 
795
798
  process.on('SIGINT', gracefulShutdown);
796
799
  process.on('SIGTERM', gracefulShutdown);
797
- process.on('uncaughtException', (e) => { console.error('uncaught:', e); });
798
- process.on('unhandledRejection', (e) => { console.error('unhandled:', e); });
800
+ process.on('uncaughtException', (e) => { console.error('uncaught:', e.message || e); });
801
+ process.on('unhandledRejection', (e) => { console.error('unhandled:', e && e.message ? e.message : e); });
802
+
803
+ // Keep process alive even if all timers are cleared
804
+ process.title = 'opencode-dashboard';
805
+ process.stdin.resume();
799
806
 
800
807
  setInterval(() => {
801
808
  try { cleanExpiredCache(trendCache, TREND_MS * 2); } catch (_) {}
@@ -808,7 +815,7 @@ function tryListen(port, maxPort) {
808
815
  server.once('error', (e) => {
809
816
  if (e.code === 'EADDRINUSE') {
810
817
  console.log(`port ${port} in use, trying ${port + 1}...`);
811
- server.removeAllListeners();
818
+ server.removeAllListeners('error');
812
819
  if (port < (maxPort || port + 5)) {
813
820
  resolve(tryListen(port + 1, maxPort));
814
821
  } else {
@@ -828,22 +835,30 @@ function tryListen(port, maxPort) {
828
835
  }
829
836
 
830
837
  (async () => {
831
- const actualPort = await tryListen(PORT, PORT + 5);
832
- setInterval(refresh, REFRESH_MS);
833
- setInterval(refreshModels, 60000);
834
- await refresh();
835
- await refreshModels();
836
- for (const d of [1, 7, 30]) {
837
- try {
838
- const r = buildReportFromDb(d);
839
- if (r && r.stats && r.stats.ok) reportCache[String(d)] = r;
840
- } catch (_) {}
841
- }
842
- for (const d of [7, 30, 90]) {
843
- try {
844
- const t = await generateTrend(d);
845
- if (t) trendCache[String(d)] = t;
846
- } catch (_) {}
838
+ try {
839
+ const actualPort = await tryListen(PORT, PORT + 5);
840
+ setInterval(refresh, REFRESH_MS);
841
+ setInterval(refreshModels, 60000);
842
+ await refresh();
843
+ await refreshModels();
844
+ for (const d of [1, 7, 30]) {
845
+ try {
846
+ const r = buildReportFromDb(d);
847
+ if (r && r.stats && r.stats.ok) reportCache[String(d)] = r;
848
+ } catch (_) {}
849
+ }
850
+ for (const d of [7, 30, 90]) {
851
+ try {
852
+ const t = await generateTrend(d);
853
+ if (t) trendCache[String(d)] = t;
854
+ } catch (_) {}
855
+ }
856
+ // Defer backup to avoid heavy disk I/O during startup
857
+ // (Windows may kill process for excessive I/O on large DB files).
858
+ setTimeout(() => {
859
+ autoBackupIfDue().catch((_) => {});
860
+ }, 30000);
861
+ } catch (e) {
862
+ console.error('startup error:', e.message || e);
847
863
  }
848
- await autoBackupIfDue();
849
864
  })();