opencode-statboard 2.0.2 → 2.0.4
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/job.log +0 -0
- package/package.json +1 -1
- package/server.js +99 -36
package/job.log
ADDED
|
Binary file
|
package/package.json
CHANGED
package/server.js
CHANGED
|
@@ -70,13 +70,16 @@ const EXE = (() => {
|
|
|
70
70
|
|
|
71
71
|
let db = null;
|
|
72
72
|
function getDb() {
|
|
73
|
-
if (db) return db;
|
|
74
73
|
if (!Database) return null;
|
|
74
|
+
// Re-open if previous connection was lost (e.g. WAL checkpoint reset).
|
|
75
|
+
if (db) {
|
|
76
|
+
try { db.prepare('SELECT 1').get(); return db; } catch (_) { try { db.close(); } catch (_) {} db = null; }
|
|
77
|
+
}
|
|
75
78
|
if (!fs.existsSync(BACKUP_SRC)) return null;
|
|
76
79
|
try {
|
|
77
80
|
db = new Database(BACKUP_SRC, { readonly: true, fileMustExist: true });
|
|
78
81
|
db.pragma('journal_mode = WAL');
|
|
79
|
-
|
|
82
|
+
db.pragma('busy_timeout = 5000');
|
|
80
83
|
try {
|
|
81
84
|
db.exec("CREATE INDEX IF NOT EXISTS idx_message_time_created ON message(time_created)");
|
|
82
85
|
db.exec("CREATE INDEX IF NOT EXISTS idx_message_session_time ON message(session_id, time_created)");
|
|
@@ -125,6 +128,12 @@ function dbGet(sql, params) {
|
|
|
125
128
|
try { return params ? d.prepare(sql).get(...params) : d.prepare(sql).get(); } catch (_) { return null; }
|
|
126
129
|
}
|
|
127
130
|
|
|
131
|
+
function dbExec(sql) {
|
|
132
|
+
const d = getDb();
|
|
133
|
+
if (!d) return null;
|
|
134
|
+
try { d.exec(sql); return true; } catch (_) { return false; }
|
|
135
|
+
}
|
|
136
|
+
|
|
128
137
|
function ensureIndexes() {
|
|
129
138
|
// Indexes are created inside getDb() on open; kept for explicit warmup call.
|
|
130
139
|
getDb();
|
|
@@ -261,10 +270,12 @@ function attributeUsage(startMs, endMs) {
|
|
|
261
270
|
// 2. sessions intersecting the period: spread residual
|
|
262
271
|
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
272
|
for (const s of srows) {
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
273
|
+
// Use the session's FULL span for residual distribution so that
|
|
274
|
+
// trend (7d window) and report (1d window) distribute the same
|
|
275
|
+
// residual across the same days. This keeps daily breakdown
|
|
276
|
+
// consistent regardless of the caller's time window.
|
|
277
|
+
const d0 = new Date(new Date(s.tc).setHours(0, 0, 0, 0));
|
|
278
|
+
const d1 = new Date(new Date(s.tu).setHours(0, 0, 0, 0));
|
|
268
279
|
const spanKeys = [];
|
|
269
280
|
for (let d = new Date(d0); d <= d1; d.setDate(d.getDate() + 1)) spanKeys.push(localDayKey(d));
|
|
270
281
|
if (!spanKeys.length) continue;
|
|
@@ -284,7 +295,7 @@ function attributeUsage(startMs, endMs) {
|
|
|
284
295
|
if (wTotal > 0) {
|
|
285
296
|
for (const k of spanKeys) if ((w.perDay[k] || 0) > 0) ensureDay(k).sessions.add(s.id);
|
|
286
297
|
} else {
|
|
287
|
-
ensureDay(localDayKey(new Date(
|
|
298
|
+
ensureDay(localDayKey(new Date(s.tu))).sessions.add(s.id);
|
|
288
299
|
}
|
|
289
300
|
const mName = modelNameOf(s.provider, s.model);
|
|
290
301
|
const aName = s.agent || 'unknown';
|
|
@@ -529,18 +540,35 @@ function buildReportFromDb(days) {
|
|
|
529
540
|
const startMs = periodStartMs(days, now);
|
|
530
541
|
const label = days === -1 ? 'All' : days <= 1 ? 'Daily' : days <= 7 ? 'Weekly' : 'Monthly';
|
|
531
542
|
|
|
532
|
-
//
|
|
533
|
-
//
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
const
|
|
543
|
+
// Use ALL-TIME attribution so every session is seen by the same
|
|
544
|
+
// attributeUsage call. Then sum only the perDay entries within the
|
|
545
|
+
// requested period. This keeps per-day breakdown consistent with the
|
|
546
|
+
// trend chart (which also uses the same full attribution).
|
|
547
|
+
const a = getAttrAll();
|
|
548
|
+
const periodDays = {};
|
|
549
|
+
for (const [key, val] of Object.entries(a.perDay)) {
|
|
550
|
+
const dayMs = val.date.getTime();
|
|
551
|
+
if (days === -1 || dayMs >= startMs) periodDays[key] = val;
|
|
552
|
+
}
|
|
553
|
+
// Sum totals from periodDays (not all-time a.totals)
|
|
554
|
+
const pdVals = Object.values(periodDays);
|
|
555
|
+
const periodTotals = { sessions: new Set(), messages: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
|
|
556
|
+
for (const pd of pdVals) {
|
|
557
|
+
for (const sid of pd.sessions) periodTotals.sessions.add(sid);
|
|
558
|
+
periodTotals.messages += pd.messages;
|
|
559
|
+
periodTotals.input += pd.input; periodTotals.output += pd.output; periodTotals.reasoning += pd.reasoning;
|
|
560
|
+
periodTotals.cacheRead += pd.cacheRead; periodTotals.cacheWrite += pd.cacheWrite; periodTotals.cost += pd.cost;
|
|
561
|
+
}
|
|
562
|
+
const t = periodTotals;
|
|
563
|
+
const activeDays = pdVals.length || 1;
|
|
537
564
|
const sessVals = Object.values(a.perSession)
|
|
565
|
+
.filter((s) => s.input > 0 || s.output > 0 || s.reasoning > 0)
|
|
538
566
|
.map((s) => s.input + s.output + s.reasoning)
|
|
539
567
|
.filter(Number.isFinite);
|
|
540
568
|
const avgTokens = sessVals.length ? sessVals.reduce((x, v) => x + v, 0) / sessVals.length : 0;
|
|
541
569
|
const statsR = {
|
|
542
570
|
ok: true,
|
|
543
|
-
overview: { sessions: t.sessions, messages: t.messages, days: activeDays },
|
|
571
|
+
overview: { sessions: t.sessions.size, messages: t.messages, days: activeDays },
|
|
544
572
|
cost: {
|
|
545
573
|
total: t.cost, avgDay: t.cost / activeDays,
|
|
546
574
|
avgTokensSession: Math.round(avgTokens),
|
|
@@ -552,32 +580,65 @@ function buildReportFromDb(days) {
|
|
|
552
580
|
tools: [], models: [],
|
|
553
581
|
};
|
|
554
582
|
const r4 = (v) => Math.round((v || 0) * 10000) / 10000;
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
583
|
+
|
|
584
|
+
// Rebuild per-agent and per-model for the period.
|
|
585
|
+
// Collect session IDs active in the period, then query their actual
|
|
586
|
+
// agent/model from the session table (since perSession doesn't store that).
|
|
587
|
+
const periodSessionIds = [...periodTotals.sessions];
|
|
588
|
+
if (periodSessionIds.length) {
|
|
589
|
+
const placeholders = periodSessionIds.map(() => '?').join(',');
|
|
590
|
+
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) || [];
|
|
591
|
+
const metaMap = {};
|
|
592
|
+
for (const s of sessMeta) metaMap[s.id] = s;
|
|
593
|
+
|
|
594
|
+
const agentAgg = {};
|
|
595
|
+
const modelAgg = {};
|
|
596
|
+
for (const sid of periodSessionIds) {
|
|
597
|
+
const ps = a.perSession[sid];
|
|
598
|
+
if (!ps) continue;
|
|
599
|
+
const meta = metaMap[sid] || { agent: 'unknown', provider: 'unknown', model: 'unknown' };
|
|
600
|
+
const agent = meta.agent || 'unknown';
|
|
601
|
+
const modelName = `${meta.provider}/${meta.model}`;
|
|
602
|
+
if (!agentAgg[agent]) agentAgg[agent] = { sessions: new Set(), cost: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0 };
|
|
603
|
+
agentAgg[agent].sessions.add(sid);
|
|
604
|
+
agentAgg[agent].input += ps.input; agentAgg[agent].output += ps.output;
|
|
605
|
+
agentAgg[agent].reasoning += ps.reasoning; agentAgg[agent].cacheRead += ps.cacheRead;
|
|
606
|
+
agentAgg[agent].cost += ps.cost;
|
|
607
|
+
if (!modelAgg[modelName]) modelAgg[modelName] = { sessions: new Set(), cost: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0 };
|
|
608
|
+
modelAgg[modelName].sessions.add(sid);
|
|
609
|
+
modelAgg[modelName].input += ps.input; modelAgg[modelName].output += ps.output;
|
|
610
|
+
modelAgg[modelName].reasoning += ps.reasoning; modelAgg[modelName].cacheRead += ps.cacheRead;
|
|
611
|
+
modelAgg[modelName].cost += ps.cost;
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
var pAgentRows = Object.entries(agentAgg)
|
|
615
|
+
.map(([agent, m]) => ({
|
|
616
|
+
agent, sessions: m.sessions.size, cost: r4(m.cost),
|
|
568
617
|
tok_in: Math.round(m.input), tok_out: Math.round(m.output),
|
|
569
|
-
tok_reasoning: Math.round(m.reasoning),
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
618
|
+
tok_reasoning: Math.round(m.reasoning), cache_read: Math.round(m.cacheRead),
|
|
619
|
+
}))
|
|
620
|
+
.sort((x, y) => y.cost - x.cost);
|
|
621
|
+
var pProviderRows = Object.entries(modelAgg)
|
|
622
|
+
.map(([name, m]) => {
|
|
623
|
+
const { provider, model } = splitModelName(name);
|
|
624
|
+
return {
|
|
625
|
+
provider, model, sessions: m.sessions.size, cost: r4(m.cost),
|
|
626
|
+
tok_in: Math.round(m.input), tok_out: Math.round(m.output),
|
|
627
|
+
tok_reasoning: Math.round(m.reasoning), cache_read: Math.round(m.cacheRead),
|
|
628
|
+
};
|
|
629
|
+
})
|
|
630
|
+
.sort((x, y) => y.cost - x.cost);
|
|
631
|
+
} else {
|
|
632
|
+
var pAgentRows = [];
|
|
633
|
+
var pProviderRows = [];
|
|
634
|
+
}
|
|
574
635
|
|
|
575
636
|
return {
|
|
576
637
|
label,
|
|
577
638
|
days,
|
|
578
639
|
stats: statsR,
|
|
579
|
-
agents:
|
|
580
|
-
providers:
|
|
640
|
+
agents: pAgentRows,
|
|
641
|
+
providers: pProviderRows,
|
|
581
642
|
generatedAt: now,
|
|
582
643
|
};
|
|
583
644
|
}
|
|
@@ -733,11 +794,13 @@ function gracefulShutdown() {
|
|
|
733
794
|
|
|
734
795
|
process.on('SIGINT', gracefulShutdown);
|
|
735
796
|
process.on('SIGTERM', gracefulShutdown);
|
|
797
|
+
process.on('uncaughtException', (e) => { console.error('uncaught:', e); });
|
|
798
|
+
process.on('unhandledRejection', (e) => { console.error('unhandled:', e); });
|
|
736
799
|
|
|
737
800
|
setInterval(() => {
|
|
738
|
-
cleanExpiredCache(trendCache, TREND_MS * 2);
|
|
739
|
-
cleanExpiredCache(reportCache, REPORT_TTL * 2);
|
|
740
|
-
autoBackupIfDue();
|
|
801
|
+
try { cleanExpiredCache(trendCache, TREND_MS * 2); } catch (_) {}
|
|
802
|
+
try { cleanExpiredCache(reportCache, REPORT_TTL * 2); } catch (_) {}
|
|
803
|
+
try { autoBackupIfDue(); } catch (_) {}
|
|
741
804
|
}, CACHE_CLEANUP_MS);
|
|
742
805
|
|
|
743
806
|
function tryListen(port, maxPort) {
|