opencode-statboard 2.0.7 → 2.0.9
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/.github/workflows/publish.yml +34 -0
- package/AGENTS.md +55 -4
- package/README.md +1 -0
- package/package.json +4 -3
- package/server.js +95 -30
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# npm trusted publishing (OIDC) — no token needed.
|
|
2
|
+
# Requires: npmjs.com → opencode-statboard → Settings → Trusted Publisher →
|
|
3
|
+
# GitHub Actions: org `thumb2086`, repo `opencode-usage-dashboard`,
|
|
4
|
+
# workflow filename `publish.yml`, no environment,
|
|
5
|
+
# Allowed actions: enable BOTH `npm stage publish` AND `npm publish`.
|
|
6
|
+
name: Publish Package
|
|
7
|
+
|
|
8
|
+
on:
|
|
9
|
+
push:
|
|
10
|
+
tags:
|
|
11
|
+
- 'v*'
|
|
12
|
+
|
|
13
|
+
permissions:
|
|
14
|
+
id-token: write # required for OIDC token exchange with npm
|
|
15
|
+
contents: read
|
|
16
|
+
|
|
17
|
+
jobs:
|
|
18
|
+
publish:
|
|
19
|
+
runs-on: ubuntu-latest
|
|
20
|
+
steps:
|
|
21
|
+
- uses: actions/checkout@v6
|
|
22
|
+
- uses: actions/setup-node@v6
|
|
23
|
+
with:
|
|
24
|
+
node-version: '24'
|
|
25
|
+
registry-url: 'https://registry.npmjs.org'
|
|
26
|
+
package-manager-cache: false # never use caching in release builds
|
|
27
|
+
- run: npm ci
|
|
28
|
+
- run: npm test
|
|
29
|
+
# Fail fast if the tag and package.json version disagree, so the tag
|
|
30
|
+
# always identifies exactly what gets published.
|
|
31
|
+
- run: node -e "const v=require('./package.json').version; const t=process.env.GITHUB_REF_NAME; if (t !== 'v'+v) { console.error('tag '+t+' != package.json v'+v); process.exit(1); }"
|
|
32
|
+
# OIDC auth is automatic with npm >= 11.5.1; provenance is generated
|
|
33
|
+
# automatically for public repos — no token, no --provenance flag.
|
|
34
|
+
- run: npm publish
|
package/AGENTS.md
CHANGED
|
@@ -22,6 +22,19 @@ opencode-dashboard
|
|
|
22
22
|
|
|
23
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
24
|
|
|
25
|
+
`detectSchema()` runs on every open and picks the table set:
|
|
26
|
+
|
|
27
|
+
- **OpenCode V2** — sessions in `session_v2`, messages in `session_message`, tool parts embedded in `session_message.data.content[]` (part objects use `name`, e.g. `{"type":"tool","name":"shell",...}`). Model IDs are nested (`data.model.id` / `data.model.providerID`). Message rows have a `type` column (`user`/`assistant` plus non-chat `idle`/`synthetic`/`compaction`/...), filtered to `user`/`assistant` to keep V1 counting semantics.
|
|
28
|
+
- **OpenCode V1 (fallback)** — `session`, `message`, `part` tables; `data.modelID`/`data.providerID` top-level; tool parts in `part` (`{"type":"tool","tool":"bash",...}`).
|
|
29
|
+
|
|
30
|
+
**V1+V2 merge — never switch.** The V2 migration is lossy, so the schema expressions combine both eras (verified 2026-09 against the live DB):
|
|
31
|
+
|
|
32
|
+
- `session` → per-field `MAX(v2, v1)` over shared rows + V1-only rows. **455/734 migrated sessions lost their lifetime totals (−196M input tokens)**: V2 recomputed totals from surviving messages, dropping pruned compaction history (fully-pruned sessions went to 0; V1's frozen totals are authoritative). MAX, never SUM — shared rows are the same lifetime counter. No shared session continued after the freeze, so MAX is exact. Result: all-time input is ~467M (V1 439.96M + 29 post-upgrade sessions), not 270M.
|
|
33
|
+
- `message` → `session_message(user/assistant)` ∪ V1 rows whose ids are not in `session_message` (30 rows, 4.3M input, never migrated; their sessions all exist in `session_v2`).
|
|
34
|
+
- tools → embedded content (already covers migrated V1 parts — dedup by id is impossible because migration rewrote `prt_` ids to `call_`) ∪ `part` rows whose `message_id` is absent from `session_message` (the double-count-safe remainder, currently 1 part).
|
|
35
|
+
|
|
36
|
+
On a V1-only database every expression collapses to the plain V1 tables.
|
|
37
|
+
|
|
25
38
|
### Hybrid Attribution (`attributeUsage`)
|
|
26
39
|
|
|
27
40
|
Token/cost attribution uses a hybrid model:
|
|
@@ -56,18 +69,56 @@ node check-trend-verify.js 7
|
|
|
56
69
|
node check-report-verify.js
|
|
57
70
|
```
|
|
58
71
|
|
|
72
|
+
Checks time-travel via API `generatedAt`, so live chat (sessions mutating mid-check) can still cause drift. For exact verification while chatting, run both server and checks against a frozen snapshot:
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
# 1. snapshot the live DB (SQLite backup API = consistent even on a live WAL DB;
|
|
76
|
+
# a raw file copy can tear)
|
|
77
|
+
node -e "const D=require('better-sqlite3'),p=require('path'),f=require('fs');const s=p.join(process.env.USERPROFILE,'.local/share/opencode/opencode.db');const d=p.join(f.mkdtempSync(p.join(f.realpathSync(require('os').tmpdir()),'oc-snap-')),'opencode.db');new D(s,{readonly:true}).backup(d).then(()=>console.log(d))"
|
|
78
|
+
|
|
79
|
+
# 2. server reads the snapshot: OPENCODE_DATA=<snapdir> node server.js
|
|
80
|
+
# 3. checks read the snapshot: OC_STATS_SNAP_DB=<snapdir>\opencode.db node check-stats-verify.js
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`check-lib.js` honors `OC_STATS_SNAP_DB`; `server.js` honors `OPENCODE_DATA` (both expect a directory containing `opencode.db`).
|
|
84
|
+
|
|
59
85
|
## Publishing
|
|
60
86
|
|
|
87
|
+
Publishing is automated via GitHub Actions + npm **trusted publishing (OIDC)** — no npm token involved. Workflow: `.github/workflows/publish.yml`, triggered by pushing a `v*` tag.
|
|
88
|
+
|
|
89
|
+
One-time setup on npmjs.com → `opencode-statboard` → Settings → **Trusted Publisher** → GitHub Actions:
|
|
90
|
+
|
|
91
|
+
| Field | Value |
|
|
92
|
+
|-------|-------|
|
|
93
|
+
| Organization or user | `thumb2086` |
|
|
94
|
+
| Repository | `opencode-usage-dashboard` |
|
|
95
|
+
| Workflow filename | `publish.yml` (exact, with extension) |
|
|
96
|
+
| Environment name | leave empty |
|
|
97
|
+
| Allowed actions | enable **both** `npm stage publish` **and** `npm publish` (configs made after Sep 2026 default to stage-only, which rejects `npm publish`) |
|
|
98
|
+
|
|
99
|
+
Release flow:
|
|
100
|
+
|
|
61
101
|
```bash
|
|
62
|
-
npm set //registry.npmjs.org/:_authToken "$NPM_TOKEN"
|
|
63
102
|
npm version patch --no-git-tag-version
|
|
64
|
-
|
|
65
|
-
|
|
103
|
+
git commit -am "vX.Y.Z"
|
|
104
|
+
git tag vX.Y.Z
|
|
105
|
+
git push --follow-tags # tag push runs publish.yml → npm publish (OIDC)
|
|
106
|
+
npm install -g opencode-statboard # after the Actions run is green
|
|
66
107
|
```
|
|
67
108
|
|
|
109
|
+
- The workflow fails fast if the tag doesn't match `package.json` version.
|
|
110
|
+
- `repository.url` must exactly match the GitHub repo (npm requirement for OIDC publishes) — `npm pkg fix` keeps it normalized.
|
|
111
|
+
- Provenance attestations are generated automatically for public repos; no `--provenance` flag.
|
|
112
|
+
- Requires npm CLI ≥ 11.5.1 / Node ≥ 22.14 (CI uses Node 24).
|
|
113
|
+
- The old `NPM_TOKEN` flow is retired (token revoked 2026-09); revoke leftover tokens on npmjs.com.
|
|
114
|
+
|
|
68
115
|
## Known Constraints
|
|
69
116
|
|
|
70
117
|
- `better-sqlite3` is a native addon; must match Node.js ABI
|
|
71
|
-
- `attributeUsage` does a full DB scan (~
|
|
118
|
+
- `attributeUsage` does a full DB scan (~31k messages); cached 300s via `getAttrAll()`
|
|
72
119
|
- Trend and report share the same `getAttrAll()` cache so daily values are consistent
|
|
120
|
+
- V2 tool counts use `json_each` over `session_message` content (~1.2s full scan) and run on every 15s refresh; legacy V1 DBs scan `part` instead (~0.8s)
|
|
121
|
+
- OpenCode V2 writes `cost = 0` for free/subscription providers, so $ totals only reflect paid (per-token billed) usage — same field, not a schema issue
|
|
73
122
|
- `gzip` compression on all `/api/` responses (>512B, level 1 for speed)
|
|
123
|
+
- Backup is deferred 30s after startup — heavy disk I/O (500MB copy+compress) during startup causes Windows to terminate the process
|
|
124
|
+
- Backup file ops are async (`fs.promises.copyFile`/`rm`): with the DB now ~2.7GB, synchronous copy+`rmSync` cleanup starved the event loop during the daily auto-backup and the process was terminated mid-cleanup (no log output, exit 1)
|
package/README.md
CHANGED
|
@@ -18,6 +18,7 @@ Real-time dashboard for your [opencode](https://opencode.ai) token usage and cos
|
|
|
18
18
|
|
|
19
19
|
- Node.js (tested on v24)
|
|
20
20
|
- [opencode](https://opencode.ai) CLI installed globally via npm
|
|
21
|
+
- Reads the local `opencode.db`; supports both OpenCode V2 (`session_v2` / `session_message`) and legacy V1 (`session` / `message` / `part`) database schemas
|
|
21
22
|
|
|
22
23
|
## Install
|
|
23
24
|
|
package/package.json
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-statboard",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.9",
|
|
4
4
|
"description": "Real-time dashboard for opencode token usage and cost statistics",
|
|
5
5
|
"main": "server.js",
|
|
6
6
|
"bin": {
|
|
7
7
|
"opencode-dashboard": "server.js"
|
|
8
8
|
},
|
|
9
9
|
"scripts": {
|
|
10
|
-
"start": "node server.js"
|
|
10
|
+
"start": "node server.js",
|
|
11
|
+
"test": "node --check server.js && node --check check-lib.js && node --check check-stats-verify.js && node --check check-trend-verify.js && node --check check-report-verify.js"
|
|
11
12
|
},
|
|
12
13
|
"keywords": [
|
|
13
14
|
"opencode",
|
|
@@ -20,7 +21,7 @@
|
|
|
20
21
|
"license": "MIT",
|
|
21
22
|
"repository": {
|
|
22
23
|
"type": "git",
|
|
23
|
-
"url": "https://github.com/thumb2086/opencode-usage-dashboard"
|
|
24
|
+
"url": "git+https://github.com/thumb2086/opencode-usage-dashboard.git"
|
|
24
25
|
},
|
|
25
26
|
"dependencies": {
|
|
26
27
|
"better-sqlite3": "^13.0.3"
|
package/server.js
CHANGED
|
@@ -47,20 +47,25 @@ function compressFile(srcPath) {
|
|
|
47
47
|
}
|
|
48
48
|
|
|
49
49
|
function cleanupOldBackups() {
|
|
50
|
-
if (BACKUP_RETENTION <= 0) return;
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
const
|
|
59
|
-
|
|
60
|
-
|
|
50
|
+
if (BACKUP_RETENTION <= 0) return Promise.resolve();
|
|
51
|
+
return (async () => {
|
|
52
|
+
try {
|
|
53
|
+
const dirs = fs.readdirSync(BACKUP_DIR)
|
|
54
|
+
.filter((f) => f.startsWith('opencode-') && fs.statSync(path.join(BACKUP_DIR, f)).isDirectory())
|
|
55
|
+
.sort();
|
|
56
|
+
if (dirs.length > BACKUP_RETENTION) {
|
|
57
|
+
const toDelete = dirs.slice(0, dirs.length - BACKUP_RETENTION);
|
|
58
|
+
for (const f of toDelete) {
|
|
59
|
+
const dirPath = path.join(BACKUP_DIR, f);
|
|
60
|
+
// Async: recursive rm of multi-hundred-MB gzip dirs is slow on
|
|
61
|
+
// Windows; doing it synchronously starves the event loop long
|
|
62
|
+
// enough that the process gets terminated during backup cleanup.
|
|
63
|
+
await fs.promises.rm(dirPath, { recursive: true, force: true });
|
|
64
|
+
console.log(`backup cleaned: ${f}`);
|
|
65
|
+
}
|
|
61
66
|
}
|
|
62
|
-
}
|
|
63
|
-
}
|
|
67
|
+
} catch (_) {}
|
|
68
|
+
})();
|
|
64
69
|
}
|
|
65
70
|
|
|
66
71
|
const EXE = (() => {
|
|
@@ -71,6 +76,51 @@ const EXE = (() => {
|
|
|
71
76
|
return 'opencode';
|
|
72
77
|
})();
|
|
73
78
|
|
|
79
|
+
// OpenCode V2 writes sessions to session_v2 and messages to session_message
|
|
80
|
+
// (tool parts embedded in message content); V1 used session/message/part and
|
|
81
|
+
// froze at the upgrade. The V2 migration is LOSSY, so merge — never switch:
|
|
82
|
+
// - 455/734 migrated sessions LOST their lifetime totals (196M input tokens):
|
|
83
|
+
// V2 recomputed them from surviving messages, dropping pruned compaction
|
|
84
|
+
// history (sessions whose messages were fully pruned went to 0). V1's frozen
|
|
85
|
+
// totals are the authoritative record, so take per-field MAX of the shared
|
|
86
|
+
// rows (same lifetime counter — never SUM, that would double count).
|
|
87
|
+
// - 30 messages were never migrated (4.3M input tokens) → union them in.
|
|
88
|
+
// - Tool parts: embedded content already covers migrated V1 parts, so only
|
|
89
|
+
// parts of never-migrated messages are added from `part` (everything else
|
|
90
|
+
// would double count).
|
|
91
|
+
const schema = { session: 'session', message: 'message', embeddedTools: false };
|
|
92
|
+
function detectSchema(d) {
|
|
93
|
+
const has = (t) => !!d.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(t);
|
|
94
|
+
const sV2 = has('session_v2'), sV1 = has('session');
|
|
95
|
+
const mV2 = has('session_message'), mV1 = has('message');
|
|
96
|
+
schema.embeddedTools = mV2;
|
|
97
|
+
schema.session = (sV2 && sV1)
|
|
98
|
+
? `(SELECT v.id AS id, v.agent AS agent, v.model AS model,
|
|
99
|
+
v.time_created AS time_created,
|
|
100
|
+
MAX(v.time_updated, COALESCE(s.time_updated, 0)) AS time_updated,
|
|
101
|
+
MAX(v.tokens_input, COALESCE(s.tokens_input, 0)) AS tokens_input,
|
|
102
|
+
MAX(v.tokens_output, COALESCE(s.tokens_output, 0)) AS tokens_output,
|
|
103
|
+
MAX(v.tokens_reasoning, COALESCE(s.tokens_reasoning, 0)) AS tokens_reasoning,
|
|
104
|
+
MAX(v.tokens_cache_read, COALESCE(s.tokens_cache_read, 0)) AS tokens_cache_read,
|
|
105
|
+
MAX(v.tokens_cache_write, COALESCE(s.tokens_cache_write, 0)) AS tokens_cache_write,
|
|
106
|
+
MAX(v.cost, COALESCE(s.cost, 0)) AS cost
|
|
107
|
+
FROM session_v2 v LEFT JOIN session s ON s.id = v.id
|
|
108
|
+
UNION ALL
|
|
109
|
+
SELECT id, agent, model, time_created, time_updated, tokens_input, tokens_output,
|
|
110
|
+
tokens_reasoning, tokens_cache_read, tokens_cache_write, cost
|
|
111
|
+
FROM session WHERE id NOT IN (SELECT id FROM session_v2))`
|
|
112
|
+
: sV2 ? 'session_v2' : 'session';
|
|
113
|
+
// V2 adds non-chat message types (idle/synthetic/compaction/...): keep V1
|
|
114
|
+
// user+assistant semantics by filtering inside the union.
|
|
115
|
+
schema.message = (mV2 && mV1)
|
|
116
|
+
? `(SELECT id, session_id, time_created, time_updated, data
|
|
117
|
+
FROM session_message WHERE type IN ('user','assistant')
|
|
118
|
+
UNION ALL
|
|
119
|
+
SELECT id, session_id, time_created, time_updated, data
|
|
120
|
+
FROM message WHERE id NOT IN (SELECT id FROM session_message))`
|
|
121
|
+
: mV2 ? 'session_message' : 'message';
|
|
122
|
+
}
|
|
123
|
+
|
|
74
124
|
let db = null;
|
|
75
125
|
function getDb() {
|
|
76
126
|
if (!Database) return null;
|
|
@@ -83,6 +133,7 @@ function getDb() {
|
|
|
83
133
|
db = new Database(BACKUP_SRC, { readonly: true, fileMustExist: true });
|
|
84
134
|
db.pragma('journal_mode = WAL');
|
|
85
135
|
db.pragma('busy_timeout = 5000');
|
|
136
|
+
detectSchema(db);
|
|
86
137
|
try {
|
|
87
138
|
db.exec("CREATE INDEX IF NOT EXISTS idx_message_time_created ON message(time_created)");
|
|
88
139
|
db.exec("CREATE INDEX IF NOT EXISTS idx_message_session_time ON message(session_id, time_created)");
|
|
@@ -243,7 +294,7 @@ function attributeUsage(startMs, endMs) {
|
|
|
243
294
|
// 1. messages in period (exact timing)
|
|
244
295
|
const msgTok = {};
|
|
245
296
|
const msgW = {};
|
|
246
|
-
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};`) || [];
|
|
297
|
+
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'), json_extract(data, '$.model.id'), '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 ${schema.message} WHERE time_created >= ${startMs} AND time_created < ${endMs};`) || [];
|
|
247
298
|
for (const r of mrows) {
|
|
248
299
|
const key = localDayKey(new Date(r.t));
|
|
249
300
|
const D = ensureDay(key);
|
|
@@ -271,7 +322,7 @@ function attributeUsage(startMs, endMs) {
|
|
|
271
322
|
}
|
|
272
323
|
|
|
273
324
|
// 2. sessions intersecting the period: spread residual
|
|
274
|
-
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};`) || [];
|
|
325
|
+
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 ${schema.session} WHERE time_updated >= ${startMs} AND time_created < ${endMs};`) || [];
|
|
275
326
|
for (const s of srows) {
|
|
276
327
|
// Use the session's FULL span for residual distribution so that
|
|
277
328
|
// trend (7d window) and report (1d window) distribute the same
|
|
@@ -355,11 +406,21 @@ function getStatsFromDb(days) {
|
|
|
355
406
|
// NOTE: days is only ever 0 here (overview totals); per-period stats are
|
|
356
407
|
// built by buildReportFromDb via attributeUsage. Local-day count so the
|
|
357
408
|
// number matches the trend chart buckets.
|
|
358
|
-
const overview = dbGet(`SELECT COUNT(*) AS sessions, COUNT(DISTINCT date(s.time_updated / 1000, 'unixepoch', 'localtime')) AS days FROM session s ${timeFilterWhere};`);
|
|
359
|
-
const
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
const
|
|
409
|
+
const overview = dbGet(`SELECT COUNT(*) AS sessions, COUNT(DISTINCT date(s.time_updated / 1000, 'unixepoch', 'localtime')) AS days FROM ${schema.session} s ${timeFilterWhere};`);
|
|
410
|
+
const msgConds = [];
|
|
411
|
+
if (startMs) msgConds.push('m.time_updated >= ' + startMs);
|
|
412
|
+
const msgCount = dbGet(`SELECT COUNT(*) AS messages FROM ${schema.message} m ${msgConds.length ? 'WHERE ' + msgConds.join(' AND ') : ''};`);
|
|
413
|
+
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 ${schema.session} s ${timeFilterWhere};`);
|
|
414
|
+
|
|
415
|
+
// V2: tool parts are embedded in session_message content (part table froze
|
|
416
|
+
// at the upgrade and its migrated rows were rebuilt into content, so
|
|
417
|
+
// querying all of part would double count — only parts of messages that
|
|
418
|
+
// were never migrated are added from `part`).
|
|
419
|
+
const toolRows = schema.embeddedTools
|
|
420
|
+
? dbQuery(`SELECT COALESCE(json_extract(je.value, '$.tool'), json_extract(je.value, '$.name')) AS tool FROM session_message sm, json_each(json_extract(sm.data, '$.content')) je WHERE json_extract(je.value, '$.type') = 'tool' ${startMs ? `AND sm.time_updated >= ${startMs}` : ''}
|
|
421
|
+
UNION ALL
|
|
422
|
+
SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' AND p.message_id NOT IN (SELECT id FROM session_message) ${startMs ? `AND p.time_updated >= ${startMs}` : ''};`) || []
|
|
423
|
+
: dbQuery(`SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' ${timeFilterPart};`) || [];
|
|
363
424
|
const toolCounts = {};
|
|
364
425
|
for (const row of toolRows) {
|
|
365
426
|
if (row.tool) toolCounts[row.tool] = (toolCounts[row.tool] || 0) + 1;
|
|
@@ -369,7 +430,7 @@ function getStatsFromDb(days) {
|
|
|
369
430
|
.map(([name, count]) => ({ name, count, pct: Math.round((count / totalToolUse) * 1000) / 10 }))
|
|
370
431
|
.sort((a, b) => b.count - a.count);
|
|
371
432
|
|
|
372
|
-
const tokenRows = dbQuery(`SELECT tokens_input + tokens_output + tokens_reasoning AS tokens FROM session s ${timeFilterWhere};`) || [];
|
|
433
|
+
const tokenRows = dbQuery(`SELECT tokens_input + tokens_output + tokens_reasoning AS tokens FROM ${schema.session} s ${timeFilterWhere};`) || [];
|
|
373
434
|
const tokenVals = tokenRows.map((r) => r.tokens).filter(Number.isFinite);
|
|
374
435
|
const avgTokens = tokenVals.length ? tokenVals.reduce((s, v) => s + v, 0) / tokenVals.length : 0;
|
|
375
436
|
const medianTokens = computeMedian(tokenVals);
|
|
@@ -482,7 +543,7 @@ async function performBackup(auto) {
|
|
|
482
543
|
for (const n of files) {
|
|
483
544
|
const srcPath = path.join(srcDir, n);
|
|
484
545
|
const dstPath = path.join(destDir, n);
|
|
485
|
-
fs.
|
|
546
|
+
await fs.promises.copyFile(srcPath, dstPath);
|
|
486
547
|
try {
|
|
487
548
|
const { origSize, compSize } = await compressFile(dstPath);
|
|
488
549
|
totalOrigSize += origSize;
|
|
@@ -499,7 +560,7 @@ async function performBackup(auto) {
|
|
|
499
560
|
const p = (n) => String(n).padStart(2, '0');
|
|
500
561
|
lastAutoBackupDay = `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}`;
|
|
501
562
|
}
|
|
502
|
-
cleanupOldBackups();
|
|
563
|
+
await cleanupOldBackups();
|
|
503
564
|
const ratio = totalOrigSize > 0 ? ((1 - totalCompSize / totalOrigSize) * 100).toFixed(1) : 0;
|
|
504
565
|
console.log(`backup ok: ${dir} (${(totalCompSize / 1024 / 1024).toFixed(1)} MB, compressed ${ratio}%)`);
|
|
505
566
|
return { ok: true, file: dir, size: totalCompSize, origSize: totalOrigSize, files: compressedFiles };
|
|
@@ -564,8 +625,13 @@ function buildReportFromDb(days) {
|
|
|
564
625
|
}
|
|
565
626
|
const t = periodTotals;
|
|
566
627
|
const activeDays = pdVals.length || 1;
|
|
567
|
-
|
|
568
|
-
|
|
628
|
+
// Avg/median over the PERIOD's token-bearing sessions (same session set
|
|
629
|
+
// the providers/agents tables are built from) — not all-time, so Daily and
|
|
630
|
+
// Weekly reports differ.
|
|
631
|
+
const periodSessionIds = [...periodTotals.sessions];
|
|
632
|
+
const sessVals = periodSessionIds
|
|
633
|
+
.map((sid) => a.perSession[sid])
|
|
634
|
+
.filter((s) => s && (s.input > 0 || s.output > 0 || s.reasoning > 0))
|
|
569
635
|
.map((s) => s.input + s.output + s.reasoning)
|
|
570
636
|
.filter(Number.isFinite);
|
|
571
637
|
const avgTokens = sessVals.length ? sessVals.reduce((x, v) => x + v, 0) / sessVals.length : 0;
|
|
@@ -584,13 +650,12 @@ function buildReportFromDb(days) {
|
|
|
584
650
|
};
|
|
585
651
|
const r4 = (v) => Math.round((v || 0) * 10000) / 10000;
|
|
586
652
|
|
|
587
|
-
// Rebuild per-agent and per-model for the period
|
|
588
|
-
//
|
|
589
|
-
//
|
|
590
|
-
const periodSessionIds = [...periodTotals.sessions];
|
|
653
|
+
// Rebuild per-agent and per-model for the period from session-table meta
|
|
654
|
+
// (perSession doesn't store agent/model). periodSessionIds was computed
|
|
655
|
+
// above for avg/median.
|
|
591
656
|
if (periodSessionIds.length) {
|
|
592
657
|
const placeholders = periodSessionIds.map(() => '?').join(',');
|
|
593
|
-
const sessMeta = dbQuery(`SELECT id, agent, COALESCE(json_extract(model,'$.providerID'),'unknown') AS provider, COALESCE(json_extract(model,'$.id'),'unknown') AS model FROM session WHERE id IN (${placeholders})`, periodSessionIds) || [];
|
|
658
|
+
const sessMeta = dbQuery(`SELECT id, agent, COALESCE(json_extract(model,'$.providerID'),'unknown') AS provider, COALESCE(json_extract(model,'$.id'),'unknown') AS model FROM ${schema.session} WHERE id IN (${placeholders})`, periodSessionIds) || [];
|
|
594
659
|
const metaMap = {};
|
|
595
660
|
for (const s of sessMeta) metaMap[s.id] = s;
|
|
596
661
|
|