opencode-statboard 2.5.0 → 2.6.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 +1 -1
- package/public/index.html +37 -10
- package/server.js +348 -155
package/package.json
CHANGED
package/public/index.html
CHANGED
|
@@ -61,6 +61,13 @@
|
|
|
61
61
|
td.clip { max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
62
62
|
.track { background: #21262d; border-radius: 4px; height: 12px; overflow: hidden; }
|
|
63
63
|
.track.share { min-width: 90px; height: 10px; }
|
|
64
|
+
/* horizontal bar list (tools). The container must NOT be a .bar-row — each
|
|
65
|
+
child is a grid item, so a grid container here collapses all rows into
|
|
66
|
+
one column and renders as a single giant bar. */
|
|
67
|
+
.bar-list { display: block; }
|
|
68
|
+
.bar-row { display: grid; grid-template-columns: 170px 1fr 150px; align-items: center; gap: 12px; padding: 5px 0; font-size: 13px; }
|
|
69
|
+
.bar-row .name { color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
|
70
|
+
.bar-row .val { text-align: right; font-variant-numeric: tabular-nums; }
|
|
64
71
|
.stack { display: flex; height: 100%; }
|
|
65
72
|
.stack > div { height: 100%; }
|
|
66
73
|
table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
|
@@ -255,7 +262,7 @@
|
|
|
255
262
|
<!-- 4. TOOLS -->
|
|
256
263
|
<details class="tool-section secondary" open id="sec-tools">
|
|
257
264
|
<summary><h2 data-i18n="toolUsage">TOOLS</h2><span class="scope-tag" id="tag-tools"></span></summary>
|
|
258
|
-
<div class="bar-
|
|
265
|
+
<div class="bar-list" id="tool-bars"></div>
|
|
259
266
|
</details>
|
|
260
267
|
|
|
261
268
|
<!-- 5. PRICING BASIS (collapsed by default) -->
|
|
@@ -293,12 +300,13 @@ const STRINGS = {
|
|
|
293
300
|
scope: 'Scope', all: 'All time', today: 'Today', last7: '7 days', mtd: 'Month to date',
|
|
294
301
|
scopeSuffix: { '-1': 'All time', '1': 'Today (local)', '7': 'Last 7 days (local)', '30': 'Month to date (local)' },
|
|
295
302
|
trendScope: '{n}-day buckets · today leftmost',
|
|
303
|
+
toolsOther: '{n} more tools',
|
|
296
304
|
allTimeTrend: 'All time · 90-day buckets · today leftmost',
|
|
297
305
|
toolsScope: '{scope} · tool counts are all-time',
|
|
298
306
|
headline: 'HEADLINE', trend: 'TREND', breakdown: 'BREAKDOWN', toolUsage: 'TOOLS',
|
|
299
307
|
pricingBasis: 'PRICING BASIS', rawText: 'RAW TEXT',
|
|
300
308
|
rawHint: 'Plain-text statement, same numbers as the tables above.',
|
|
301
|
-
tokens: 'Tokens', tIn: 'in', tOut: 'out', tReasoning: 'reasoning', tCache: 'cache',
|
|
309
|
+
tokens: 'Tokens (excl. cache re-reads)', tIn: 'in', tOut: 'out', tReasoning: 'reasoning', tCache: 'cache re-reads',
|
|
302
310
|
totalCost: 'Total Cost', marketValue: 'Market Value', saved: 'Saved',
|
|
303
311
|
costShare: 'actual paid', atCatalog: 'same usage at catalog list prices',
|
|
304
312
|
savedOf: '{pct}% of market value',
|
|
@@ -338,12 +346,13 @@ const STRINGS = {
|
|
|
338
346
|
scope: '範圍', all: '全期', today: '今天', last7: '近 7 天', mtd: '本月至今',
|
|
339
347
|
scopeSuffix: { '-1': '全期', '1': '今天(本地)', '7': '近 7 天(本地)', '30': '本月至今(本地)' },
|
|
340
348
|
trendScope: '{n} 天分桶 · 今天在最左',
|
|
349
|
+
toolsOther: '其他 {n} 個工具',
|
|
341
350
|
allTimeTrend: '全期 · 90 天分桶 · 今天在最左',
|
|
342
351
|
toolsScope: '{scope} · 工具統計一律為全期',
|
|
343
352
|
headline: '重點指標', trend: '趨勢', breakdown: '明細', toolUsage: '工具',
|
|
344
353
|
pricingBasis: '定價依據', rawText: '原始文字',
|
|
345
354
|
rawHint: '純文字報表,數字與上方表格一致。',
|
|
346
|
-
tokens: 'Tokens', tIn: '輸入', tOut: '輸出', tReasoning: '推理', tCache: '
|
|
355
|
+
tokens: 'Tokens(不含快取重讀)', tIn: '輸入', tOut: '輸出', tReasoning: '推理', tCache: '快取重讀',
|
|
347
356
|
totalCost: '總費用', marketValue: '市價', saved: '已節省',
|
|
348
357
|
costShare: '實際付費', atCatalog: '同等用量依牌價換算',
|
|
349
358
|
savedOf: '占市價 {pct}%',
|
|
@@ -521,7 +530,9 @@ function renderReport(rep) {
|
|
|
521
530
|
const o = (rep.stats && rep.stats.overview) || {};
|
|
522
531
|
const cacheAll = (c.cacheRead || 0) + (c.cacheWrite || 0);
|
|
523
532
|
|
|
524
|
-
|
|
533
|
+
// Cache reads are context RE-reads (the same prefix counted again on every
|
|
534
|
+
// turn), so they must not inflate the headline token count.
|
|
535
|
+
$('hl-tokens').textContent = fmt((c.input || 0) + (c.output || 0) + (c.reasoning || 0));
|
|
525
536
|
$('hl-in').textContent = fmt(c.input);
|
|
526
537
|
$('hl-out').textContent = fmt(c.output);
|
|
527
538
|
$('hl-reasoning').textContent = fmt(c.reasoning);
|
|
@@ -723,18 +734,34 @@ function renderTrend(data) {
|
|
|
723
734
|
}
|
|
724
735
|
|
|
725
736
|
// ---- tools (all-time; the API cannot slice them) -----------------------
|
|
737
|
+
// Long tail (48 tools, most under 0.1%) is folded into one "other" row:
|
|
738
|
+
// a 48-row list of near-empty bars is visual noise, not information.
|
|
739
|
+
const TOOL_TOP_N = 12;
|
|
740
|
+
|
|
726
741
|
function renderTools(tools) {
|
|
727
742
|
if (!tools || !tools.length) {
|
|
728
743
|
$('tool-bars').innerHTML = lastStats ? '<div class="empty">' + esc(t('noData')) + '</div>' : '';
|
|
729
744
|
return;
|
|
730
745
|
}
|
|
731
|
-
const
|
|
732
|
-
|
|
746
|
+
const sorted = tools.slice().sort((a, b) => (b.count || 0) - (a.count || 0));
|
|
747
|
+
const top = sorted.slice(0, TOOL_TOP_N);
|
|
748
|
+
const rest = sorted.slice(TOOL_TOP_N);
|
|
749
|
+
const rows = top.slice();
|
|
750
|
+
if (rest.length) {
|
|
751
|
+
const restCount = rest.reduce((s, x) => s + (x.count || 0), 0);
|
|
752
|
+
const total = tools.reduce((s, x) => s + (x.count || 0), 0);
|
|
753
|
+
const restPct = total > 0 ? Math.round((restCount / total) * 1000) / 10 : 0;
|
|
754
|
+
rows.push({ name: t('toolsOther').replace('{n}', String(rest.length)), count: restCount, pct: restPct, rest: true });
|
|
755
|
+
}
|
|
756
|
+
const max = Math.max.apply(null, rows.map((x) => x.count || 0));
|
|
757
|
+
$('tool-bars').innerHTML = rows.map((tool) => {
|
|
733
758
|
const pct = max > 0 ? Math.max(0.5, ((tool.count || 0) / max) * 100) : 0;
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
+ `<div
|
|
759
|
+
const color = tool.rest ? 'var(--muted)' : 'var(--tool)';
|
|
760
|
+
const dim = tool.rest ? ' style="color:var(--muted)"' : '';
|
|
761
|
+
return `<div class="bar-row">`
|
|
762
|
+
+ `<div class="name"${dim} title="${esc(tool.name || '')}">${esc(tool.name || '')}</div>`
|
|
763
|
+
+ `<div class="track"><div class="fill" style="width:${pct}%;background:${color}"></div></div>`
|
|
764
|
+
+ `<div class="val">${fmt(tool.count)} · ${fmtPct(tool.pct)}</div></div>`;
|
|
738
765
|
}).join('');
|
|
739
766
|
}
|
|
740
767
|
|
package/server.js
CHANGED
|
@@ -80,13 +80,13 @@ const EXE = (() => {
|
|
|
80
80
|
|
|
81
81
|
// OpenCode V2 writes sessions to session_v2 and messages to session_message
|
|
82
82
|
// (tool parts embedded in message content); V1 used session/message/part and
|
|
83
|
-
// froze at the upgrade. The V2 migration is LOSSY, so merge
|
|
83
|
+
// froze at the upgrade. The V2 migration is LOSSY, so merge ??never switch:
|
|
84
84
|
// - 455/734 migrated sessions LOST their lifetime totals (196M input tokens):
|
|
85
85
|
// V2 recomputed them from surviving messages, dropping pruned compaction
|
|
86
86
|
// history (sessions whose messages were fully pruned went to 0). V1's frozen
|
|
87
87
|
// totals are the authoritative record, so take per-field MAX of the shared
|
|
88
|
-
// rows (same lifetime counter
|
|
89
|
-
// - 30 messages were never migrated (4.3M input tokens)
|
|
88
|
+
// rows (same lifetime counter ??never SUM, that would double count).
|
|
89
|
+
// - 30 messages were never migrated (4.3M input tokens) ??union them in.
|
|
90
90
|
// - Tool parts: embedded content already covers migrated V1 parts, so only
|
|
91
91
|
// parts of never-migrated messages are added from `part` (everything else
|
|
92
92
|
// would double count).
|
|
@@ -212,13 +212,13 @@ function cleanExpiredCache(cache, ttl) {
|
|
|
212
212
|
async function generateTrend(days) {
|
|
213
213
|
// Buckets: local midnights, today -> (days-1) days ago.
|
|
214
214
|
// Values are sliced from the SHARED all-time attribution (getAttrAll(),
|
|
215
|
-
// the same object the usage report uses)
|
|
215
|
+
// the same object the usage report uses) ??never a separate windowed
|
|
216
216
|
// attributeUsage call. Windowed attribution inflates in-window days:
|
|
217
217
|
// messages before the window are excluded from msgTok, so the session
|
|
218
218
|
// residual grows and lands entirely on windowed days (measured
|
|
219
|
-
// +0.25
|
|
219
|
+
// +0.25??.7M input/day on 2026-09-29). One shared attribution makes
|
|
220
220
|
// trend buckets and report periods structurally identical; any remaining
|
|
221
|
-
// panel difference is only cache age (trend
|
|
221
|
+
// panel difference is only cache age (trend ??0s, report ??0min, both
|
|
222
222
|
// timestamps shown in the UI).
|
|
223
223
|
const buckets = [];
|
|
224
224
|
const today = new Date();
|
|
@@ -279,7 +279,7 @@ function splitModelName(name) {
|
|
|
279
279
|
}
|
|
280
280
|
|
|
281
281
|
// Market estimate for token usage at catalog paid rates (USD). saved is
|
|
282
|
-
// market minus actual cost. kind is 'exact' | 'sibling' | 'proxy'
|
|
282
|
+
// market minus actual cost. kind is 'exact' | 'sibling' | 'proxy' ??how the
|
|
283
283
|
// rate was found; null (kind 'unpriced') when the catalog has NO comparable
|
|
284
284
|
// paid listing, in which case we report no money at all rather than inventing
|
|
285
285
|
// a rate (that fake rate once turned a $0 model into $212 of phantom savings).
|
|
@@ -308,105 +308,161 @@ function marketOf(tok, provider, model) {
|
|
|
308
308
|
// buckets (perDay/perModel/perSession) are unaffected, so one scan serves both
|
|
309
309
|
// the trend (lifetime) and the report (period) views. Period buckets group
|
|
310
310
|
// message tokens by the MESSAGE's own model/agent, and spread session residual
|
|
311
|
-
// by the session's model/agent
|
|
311
|
+
// by the session's model/agent ??so per-model report rows sum exactly to the
|
|
312
312
|
// period totals (self-consistent by construction).
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
313
|
+
// Hybrid attribution over [startMs, endMs), message layer + session residual.
|
|
314
|
+
//
|
|
315
|
+
// PERFORMANCE (measured 2026-10-11 on 62k messages / 993MB of JSON):
|
|
316
|
+
// message rows are fetched as raw `data` and parsed ONCE in Node. Doing the
|
|
317
|
+
// same work with a dozen json_extract() calls per row costs 43.6s in SQLite
|
|
318
|
+
// (it re-parses the whole content blob for every call) versus 1.6s + 0.9s
|
|
319
|
+
// this way. Period slices are folded in the same pass, so the trend, the
|
|
320
|
+
// overview and every report period share ONE scan per ATTR_TTL instead of
|
|
321
|
+
// paying for their own.
|
|
322
|
+
//
|
|
323
|
+
// Message tokens go to their exact local day; each session's residual
|
|
324
|
+
// (session totals minus its message sums, clamped >= 0) is spread across the
|
|
325
|
+
// session's full local-day span, weighted by its per-day message volume
|
|
326
|
+
// (uniform across spanned days when the session has no messages).
|
|
327
|
+
//
|
|
328
|
+
// periodStartsMs: optional ARRAY of local-midnight boundaries. Boundaries are
|
|
329
|
+
// NESTED (today ⊂ 7d ⊂ MTD ⊂ all), so a day feeds every boundary at or
|
|
330
|
+
// before it. Per-period buckets group message tokens by the MESSAGE's own
|
|
331
|
+
// model/agent and spread residual by the session's, so report rows sum
|
|
332
|
+
// exactly to the period totals. Each slice also carries msgAgg (per session:
|
|
333
|
+
// message count, output, reasoning, active ms, wall span on the MESSAGE clock)
|
|
334
|
+
// and msgAgentAgg, so reports need no extra queries.
|
|
335
|
+
const ATTR_TTL = 300000;
|
|
336
|
+
// Tool counts change slowly but the embedded-content scan costs ~1.5s on a
|
|
337
|
+
// large DB; cache it so the 15s refresh stays cheap. Keyed on schema+window.
|
|
338
|
+
let toolsCache = null;
|
|
339
|
+
const yieldToLoop = () => new Promise((r) => setImmediate(r));
|
|
340
|
+
|
|
341
|
+
function newTokBucket() {
|
|
342
|
+
return { input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
|
|
343
|
+
}
|
|
344
|
+
function addTok(b, iv, ov, rv, crv, cwv, cv) {
|
|
345
|
+
b.input += iv; b.output += ov; b.reasoning += rv; b.cacheRead += crv; b.cacheWrite += cwv; b.cost += cv;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
async function attributeUsage(startMs, endMs, periodStartsMs) {
|
|
349
|
+
const starts = (Array.isArray(periodStartsMs) ? periodStartsMs : [periodStartsMs])
|
|
350
|
+
.filter((x) => x != null).sort((a, b) => a - b);
|
|
351
|
+
|
|
316
352
|
const perDay = {};
|
|
317
353
|
const perModel = {};
|
|
318
354
|
const perAgent = {};
|
|
319
355
|
const perSession = {};
|
|
320
|
-
const perModelPeriod = {};
|
|
321
|
-
const perAgentPeriod = {};
|
|
322
|
-
const perAgentModelPeriod = {};
|
|
323
|
-
const perSessionPeriod = {};
|
|
324
|
-
const perSessionModelPeriod = {};
|
|
325
|
-
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 });
|
|
326
|
-
const ensureModel = (n) => perModel[n] || (perModel[n] = { messages: 0, sessions: new Set(), input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0, speedOut: 0, speedMs: 0 });
|
|
327
|
-
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 });
|
|
328
|
-
const tok = () => ({ input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 });
|
|
329
|
-
const ensureModelP = (n) => perModelPeriod[n] || (perModelPeriod[n] = { messages: 0, sessions: new Set(), input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0, speedOut: 0, speedMs: 0 });
|
|
330
|
-
const ensureAgentP = (a) => perAgentPeriod[a || 'unknown'] || (perAgentPeriod[a || 'unknown'] = { sessions: new Set(), input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0, speedOut: 0, speedMs: 0 });
|
|
331
|
-
const ensureAgentModelP = (a, m) => {
|
|
332
|
-
const k = a || 'unknown';
|
|
333
|
-
const bag = perAgentModelPeriod[k] || (perAgentModelPeriod[k] = {});
|
|
334
|
-
return bag[m] || (bag[m] = tok());
|
|
335
|
-
};
|
|
336
|
-
const ensureSessP = (sid) => perSessionPeriod[sid] || (perSessionPeriod[sid] = tok());
|
|
337
|
-
const ensureSessModelP = (sid, m) => {
|
|
338
|
-
const bag = perSessionModelPeriod[sid] || (perSessionModelPeriod[sid] = {});
|
|
339
|
-
return bag[m] || (bag[m] = tok());
|
|
340
|
-
};
|
|
341
|
-
|
|
342
|
-
// 1. messages in period (exact timing)
|
|
343
356
|
const msgTok = {};
|
|
344
357
|
const msgW = {};
|
|
345
|
-
const
|
|
346
|
-
|
|
347
|
-
|
|
358
|
+
const ensureDay = (key) => perDay[key] || (perDay[key] = { date: dateOfKey(key), sessions: new Set(), messages: 0, ...newTokBucket() });
|
|
359
|
+
const ensureModel = (n) => perModel[n] || (perModel[n] = { messages: 0, sessions: new Set(), ...newTokBucket(), speedOut: 0, speedMs: 0 });
|
|
360
|
+
const ensureAgent = (a) => perAgent[a || 'unknown'] || (perAgent[a || 'unknown'] = { messages: 0, sessions: new Set(), ...newTokBucket() });
|
|
361
|
+
|
|
362
|
+
const slices = starts.map((s) => {
|
|
363
|
+
const perModelP = {}, perAgentP = {}, perAgentModelP = {}, perSessionP = {}, perSessionModelP = {};
|
|
364
|
+
const msgAgg = {}, msgAgentAgg = {};
|
|
365
|
+
return {
|
|
366
|
+
start: s,
|
|
367
|
+
perModel: perModelP, perAgent: perAgentP, perAgentModel: perAgentModelP,
|
|
368
|
+
perSession: perSessionP, perSessionModel: perSessionModelP,
|
|
369
|
+
msgAgg, msgAgentAgg,
|
|
370
|
+
model: (n) => perModelP[n] || (perModelP[n] = { messages: 0, sessions: new Set(), ...newTokBucket(), speedOut: 0, speedMs: 0 }),
|
|
371
|
+
agent: (a) => perAgentP[a || 'unknown'] || (perAgentP[a || 'unknown'] = { sessions: new Set(), ...newTokBucket(), speedOut: 0, speedMs: 0 }),
|
|
372
|
+
agentModel: (a, m) => {
|
|
373
|
+
const k = a || 'unknown';
|
|
374
|
+
const bag = perAgentModelP[k] || (perAgentModelP[k] = {});
|
|
375
|
+
return bag[m] || (bag[m] = newTokBucket());
|
|
376
|
+
},
|
|
377
|
+
sess: (sid) => perSessionP[sid] || (perSessionP[sid] = newTokBucket()),
|
|
378
|
+
sessModel: (sid, m) => {
|
|
379
|
+
const bag = perSessionModelP[sid] || (perSessionModelP[sid] = {});
|
|
380
|
+
return bag[m] || (bag[m] = newTokBucket());
|
|
381
|
+
},
|
|
382
|
+
};
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
const rows = dbQuery(`SELECT time_created AS t, session_id AS sid, data FROM ${schema.message} WHERE time_created >= ${startMs} AND time_created < ${endMs};`) || [];
|
|
386
|
+
let processed = 0;
|
|
387
|
+
for (const row of rows) {
|
|
388
|
+
let d = null;
|
|
389
|
+
try { d = JSON.parse(row.data); } catch (_) { d = null; }
|
|
390
|
+
processed++;
|
|
391
|
+
if (!d) continue;
|
|
392
|
+
const key = localDayKey(new Date(row.t));
|
|
393
|
+
const dayMs = dateOfKey(key).getTime();
|
|
394
|
+
const tk = d.tokens || {};
|
|
395
|
+
const cache = tk.cache || {};
|
|
396
|
+
const iv = +tk.input || 0, ov = +tk.output || 0, rv = +tk.reasoning || 0;
|
|
397
|
+
const crv = +cache.read || 0, cwv = +cache.write || 0, cv = +d.cost || 0;
|
|
398
|
+
const md = d.model || {};
|
|
399
|
+
const provider = d.providerID || md.providerID || 'unknown';
|
|
400
|
+
const model = d.modelID || md.modelID || md.id || 'unknown';
|
|
401
|
+
const agent = d.agent || 'unknown';
|
|
402
|
+
const mName = `${provider || 'unknown'}/${model || 'unknown'}`;
|
|
403
|
+
const dm = d.time || {};
|
|
404
|
+
const t0 = +dm.created || 0, t1 = +dm.completed || 0;
|
|
405
|
+
const hasDur = ov > 0 && t1 > t0;
|
|
406
|
+
|
|
348
407
|
const D = ensureDay(key);
|
|
349
408
|
D.messages++;
|
|
350
|
-
if (
|
|
351
|
-
|
|
352
|
-
const
|
|
353
|
-
D.input += iv; D.output += ov; D.reasoning += rv; D.cacheRead += crv; D.cacheWrite += cwv; D.cost += cv;
|
|
354
|
-
const M = ensureModel(modelNameOf(r.provider, r.model));
|
|
409
|
+
if (row.sid) D.sessions.add(row.sid);
|
|
410
|
+
addTok(D, iv, ov, rv, crv, cwv, cv);
|
|
411
|
+
const M = ensureModel(mName);
|
|
355
412
|
M.messages++;
|
|
356
|
-
if (
|
|
357
|
-
M
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
const t0 = +r.t0 || 0, t1 = +r.t1 || 0;
|
|
361
|
-
if (ov > 0 && t1 > t0) { M.speedOut += ov; M.speedMs += (t1 - t0); }
|
|
362
|
-
const A = ensureAgent(r.agent);
|
|
413
|
+
if (row.sid) M.sessions.add(row.sid);
|
|
414
|
+
addTok(M, iv, ov, rv, crv, cwv, cv);
|
|
415
|
+
if (hasDur) { M.speedOut += ov; M.speedMs += (t1 - t0); }
|
|
416
|
+
const A = ensureAgent(agent);
|
|
363
417
|
A.messages++;
|
|
364
|
-
if (
|
|
365
|
-
A
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
418
|
+
if (row.sid) A.sessions.add(row.sid);
|
|
419
|
+
addTok(A, iv, ov, rv, crv, cwv, cv);
|
|
420
|
+
|
|
421
|
+
if (row.sid) {
|
|
422
|
+
const mt = msgTok[row.sid] || (msgTok[row.sid] = newTokBucket());
|
|
423
|
+
addTok(mt, iv, ov, rv, crv, cwv, cv);
|
|
424
|
+
const w = msgW[row.sid] || (msgW[row.sid] = { total: 0, perDay: {} });
|
|
370
425
|
const vol = iv + ov + rv + crv + cwv;
|
|
371
426
|
w.total += vol;
|
|
372
427
|
w.perDay[key] = (w.perDay[key] || 0) + vol;
|
|
373
428
|
}
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
const
|
|
378
|
-
const MP = ensureModelP(mName);
|
|
429
|
+
|
|
430
|
+
for (const sl of slices) {
|
|
431
|
+
if (dayMs < sl.start) continue;
|
|
432
|
+
const MP = sl.model(mName);
|
|
379
433
|
MP.messages++;
|
|
380
|
-
if (
|
|
381
|
-
MP
|
|
382
|
-
if (
|
|
383
|
-
const AP =
|
|
384
|
-
if (
|
|
385
|
-
AP
|
|
386
|
-
if (
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
434
|
+
if (row.sid) MP.sessions.add(row.sid);
|
|
435
|
+
addTok(MP, iv, ov, rv, crv, cwv, cv);
|
|
436
|
+
if (hasDur) { MP.speedOut += ov; MP.speedMs += (t1 - t0); }
|
|
437
|
+
const AP = sl.agent(agent);
|
|
438
|
+
if (row.sid) AP.sessions.add(row.sid);
|
|
439
|
+
addTok(AP, iv, ov, rv, crv, cwv, cv);
|
|
440
|
+
if (hasDur) { AP.speedOut += ov; AP.speedMs += (t1 - t0); }
|
|
441
|
+
addTok(sl.agentModel(agent, mName), iv, ov, rv, crv, cwv, cv);
|
|
442
|
+
if (row.sid) {
|
|
443
|
+
addTok(sl.sess(row.sid), iv, ov, rv, crv, cwv, cv);
|
|
444
|
+
addTok(sl.sessModel(row.sid, mName), iv, ov, rv, crv, cwv, cv);
|
|
445
|
+
const ma = sl.msgAgg[row.sid] || (sl.msgAgg[row.sid] = { n: 0, o: 0, rq: 0, ms: 0, w0: Infinity, w1: 0 });
|
|
446
|
+
ma.n++;
|
|
447
|
+
if (hasDur) { ma.o += ov; ma.rq += rv; ma.ms += (t1 - t0); }
|
|
448
|
+
if (row.t < ma.w0) ma.w0 = row.t;
|
|
449
|
+
if (t1 > ma.w1) ma.w1 = t1;
|
|
394
450
|
}
|
|
451
|
+
const ag = sl.msgAgentAgg[agent] || (sl.msgAgentAgg[agent] = { o: 0, ms: 0 });
|
|
452
|
+
if (hasDur) { ag.o += ov; ag.ms += (t1 - t0); }
|
|
395
453
|
}
|
|
454
|
+
if ((processed & 0x3fff) === 0) await yieldToLoop();
|
|
396
455
|
}
|
|
397
456
|
|
|
398
|
-
// 2. sessions intersecting the period: spread residual
|
|
399
457
|
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};`) || [];
|
|
458
|
+
let sessProcessed = 0;
|
|
400
459
|
for (const s of srows) {
|
|
401
|
-
// Use the session's FULL span for residual distribution. All consumers
|
|
402
|
-
// share one all-time attribution (getAttrAll), so per-day values are
|
|
403
|
-
// identical whichever period slices them.
|
|
404
460
|
const d0 = new Date(new Date(s.tc).setHours(0, 0, 0, 0));
|
|
405
461
|
const d1 = new Date(new Date(s.tu).setHours(0, 0, 0, 0));
|
|
406
462
|
const spanKeys = [];
|
|
407
463
|
for (let d = new Date(d0); d <= d1; d.setDate(d.getDate() + 1)) spanKeys.push(localDayKey(d));
|
|
408
|
-
if (!spanKeys.length) continue;
|
|
409
|
-
const mt = msgTok[s.id] ||
|
|
464
|
+
if (!spanKeys.length) { sessProcessed++; continue; }
|
|
465
|
+
const mt = msgTok[s.id] || newTokBucket();
|
|
410
466
|
const res = {
|
|
411
467
|
input: Math.max(0, (+s.si || 0) - mt.input),
|
|
412
468
|
output: Math.max(0, (+s.so || 0) - mt.output),
|
|
@@ -415,7 +471,7 @@ function attributeUsage(startMs, endMs, periodStartMs) {
|
|
|
415
471
|
cacheWrite: Math.max(0, (+s.scw || 0) - mt.cacheWrite),
|
|
416
472
|
cost: Math.max(0, (+s.sc || 0) - mt.cost),
|
|
417
473
|
};
|
|
418
|
-
const ps = perSession[s.id] || (perSession[s.id] = {
|
|
474
|
+
const ps = perSession[s.id] || (perSession[s.id] = { ...mt });
|
|
419
475
|
const w = msgW[s.id];
|
|
420
476
|
let wTotal = 0;
|
|
421
477
|
if (w) { for (const k of spanKeys) wTotal += w.perDay[k] || 0; }
|
|
@@ -424,7 +480,7 @@ function attributeUsage(startMs, endMs, periodStartMs) {
|
|
|
424
480
|
} else {
|
|
425
481
|
ensureDay(localDayKey(new Date(s.tu))).sessions.add(s.id);
|
|
426
482
|
}
|
|
427
|
-
const mName =
|
|
483
|
+
const mName = `${s.provider || 'unknown'}/${s.model || 'unknown'}`;
|
|
428
484
|
const aName = s.agent || 'unknown';
|
|
429
485
|
for (const k of spanKeys) {
|
|
430
486
|
const share = wTotal > 0 ? ((w.perDay[k] || 0) / wTotal) : 1 / spanKeys.length;
|
|
@@ -432,76 +488,188 @@ function attributeUsage(startMs, endMs, periodStartMs) {
|
|
|
432
488
|
const D = ensureDay(k);
|
|
433
489
|
const di = res.input * share, dout = res.output * share, dr = res.reasoning * share;
|
|
434
490
|
const dcr = res.cacheRead * share, dcw = res.cacheWrite * share, dc = res.cost * share;
|
|
435
|
-
D
|
|
491
|
+
addTok(D, di, dout, dr, dcr, dcw, dc);
|
|
436
492
|
const M = ensureModel(mName);
|
|
437
|
-
M
|
|
493
|
+
addTok(M, di, dout, dr, dcr, dcw, dc);
|
|
438
494
|
const A = ensureAgent(aName);
|
|
439
|
-
A
|
|
440
|
-
ps
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
const AM = ensureAgentModelP(aName, mName);
|
|
450
|
-
AM.input += di; AM.output += dout; AM.reasoning += dr; AM.cacheRead += dcr; AM.cacheWrite += dcw; AM.cost += dc;
|
|
451
|
-
const SP = ensureSessP(s.id);
|
|
452
|
-
SP.input += di; SP.output += dout; SP.reasoning += dr; SP.cacheRead += dcr; SP.cacheWrite += dcw; SP.cost += dc;
|
|
453
|
-
const SM = ensureSessModelP(s.id, mName);
|
|
454
|
-
SM.input += di; SM.output += dout; SM.reasoning += dr; SM.cacheRead += dcr; SM.cacheWrite += dcw; SM.cost += dc;
|
|
495
|
+
addTok(A, di, dout, dr, dcr, dcw, dc);
|
|
496
|
+
addTok(ps, di, dout, dr, dcr, dcw, dc);
|
|
497
|
+
const dayMs = D.date.getTime();
|
|
498
|
+
for (const sl of slices) {
|
|
499
|
+
if (dayMs < sl.start) continue;
|
|
500
|
+
addTok(sl.model(mName), di, dout, dr, dcr, dcw, dc);
|
|
501
|
+
addTok(sl.agent(aName), di, dout, dr, dcr, dcw, dc);
|
|
502
|
+
addTok(sl.agentModel(aName, mName), di, dout, dr, dcr, dcw, dc);
|
|
503
|
+
addTok(sl.sess(s.id), di, dout, dr, dcr, dcw, dc);
|
|
504
|
+
addTok(sl.sessModel(s.id, mName), di, dout, dr, dcr, dcw, dc);
|
|
455
505
|
}
|
|
456
506
|
}
|
|
507
|
+
if ((++sessProcessed & 0x3f) === 0) await yieldToLoop();
|
|
457
508
|
}
|
|
458
509
|
|
|
459
|
-
const totals = { sessions: Object.keys(perSession).length, messages: 0,
|
|
510
|
+
const totals = { sessions: Object.keys(perSession).length, messages: 0, ...newTokBucket() };
|
|
460
511
|
for (const k of Object.keys(perDay)) {
|
|
461
512
|
const D = perDay[k];
|
|
462
513
|
totals.messages += D.messages;
|
|
463
|
-
totals
|
|
464
|
-
totals.cacheRead += D.cacheRead; totals.cacheWrite += D.cacheWrite; totals.cost += D.cost;
|
|
514
|
+
addTok(totals, D.input, D.output, D.reasoning, D.cacheRead, D.cacheWrite, D.cost);
|
|
465
515
|
}
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
516
|
+
|
|
517
|
+
const out = { perDay, perModel, perAgent, perSession, totals, periods: new Map() };
|
|
518
|
+
for (const sl of slices) {
|
|
519
|
+
// Every slice also carries the all-time day buckets: the report sums its
|
|
520
|
+
// periodDays off perDay, and period 0 (all-time) IS the all-time view.
|
|
521
|
+
out.periods.set(sl.start, {
|
|
522
|
+
start: sl.start,
|
|
523
|
+
perDay,
|
|
524
|
+
perModelPeriod: sl.perModel,
|
|
525
|
+
perAgentPeriod: sl.perAgent,
|
|
526
|
+
perAgentModelPeriod: sl.perAgentModel,
|
|
527
|
+
perSessionPeriod: sl.perSession,
|
|
528
|
+
perSessionModelPeriod: sl.perSessionModel,
|
|
529
|
+
msgAgg: sl.msgAgg,
|
|
530
|
+
msgAgentAgg: sl.msgAgentAgg,
|
|
531
|
+
});
|
|
532
|
+
if (sl.start === 0) {
|
|
533
|
+
// period 0 == all-time: expose the bucket names the report reads.
|
|
534
|
+
out.perModelPeriod = sl.perModel;
|
|
535
|
+
out.perAgentPeriod = sl.perAgent;
|
|
536
|
+
out.perAgentModelPeriod = sl.perAgentModel;
|
|
537
|
+
out.perSessionPeriod = sl.perSession;
|
|
538
|
+
out.perSessionModelPeriod = sl.perSessionModel;
|
|
539
|
+
out.msgAgg = sl.msgAgg;
|
|
540
|
+
out.msgAgentAgg = sl.msgAgentAgg;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
return out;
|
|
471
544
|
}
|
|
472
545
|
|
|
473
|
-
//
|
|
474
|
-
//
|
|
546
|
+
// ---- shared attribution bundle cache ----------------------------------
|
|
547
|
+
// One scan serves overview, trend and every report period. Memoized ATTR_TTL;
|
|
548
|
+
// rebuilds run detached (and yield internally), so request handlers never pay
|
|
549
|
+
// for the scan inline and the UI stays responsive while it happens.
|
|
475
550
|
let attrAllCache = null;
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
551
|
+
let attrBundlePending = false;
|
|
552
|
+
let attrLastSave = 0;
|
|
553
|
+
const EMPTY_ATTR = {
|
|
554
|
+
perDay: {}, perModel: {}, perAgent: {}, perSession: {},
|
|
555
|
+
totals: { sessions: 0, messages: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 },
|
|
556
|
+
periods: new Map(), msgAgg: {}, msgAgentAgg: {},
|
|
557
|
+
};
|
|
558
|
+
function periodStartsFor(now) {
|
|
559
|
+
return {
|
|
560
|
+
1: periodStartMs(1, now),
|
|
561
|
+
7: periodStartMs(7, now),
|
|
562
|
+
30: periodStartMs(30, now),
|
|
563
|
+
'-1': 0,
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
async function buildAttrBundle(now) {
|
|
567
|
+
const a = await attributeUsage(0, now, Object.values(periodStartsFor(now)));
|
|
568
|
+
a.byPeriodStart = periodStartsFor(now);
|
|
486
569
|
return a;
|
|
487
570
|
}
|
|
488
571
|
|
|
489
|
-
//
|
|
490
|
-
//
|
|
491
|
-
//
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
572
|
+
// ---- on-disk bundle cache ---------------------------------------------
|
|
573
|
+
// Scanning the live DB costs 5–26s (WAL + concurrent opencode writes), so the
|
|
574
|
+
// computed bundle is persisted and loaded on startup; a stale bundle still
|
|
575
|
+
// serves every request while a fresh one is rebuilt in the background.
|
|
576
|
+
const BUNDLE_FILE = path.join(__dirname, '.attr-bundle.json');
|
|
577
|
+
const BUNDLE_SAVE_MS = 60000; // don't hammer the disk while chatting
|
|
578
|
+
// Cache is bound to the exact database it was computed from, so pointing
|
|
579
|
+
// OPENCODE_DATA at another DB (tests, a restored copy) never reuses it.
|
|
580
|
+
function dbFingerprint() {
|
|
581
|
+
try {
|
|
582
|
+
const st = fs.statSync(BACKUP_SRC);
|
|
583
|
+
return `${BACKUP_SRC}|${st.size}|${Math.round(st.mtimeMs)}`;
|
|
584
|
+
} catch (_) { return BACKUP_SRC; }
|
|
585
|
+
}
|
|
586
|
+
function serializeBundle(a) {
|
|
587
|
+
const setToArr = (obj) => {
|
|
588
|
+
for (const k of Object.keys(obj)) if (obj[k] && obj[k].sessions) obj[k].sessions = [...obj[k].sessions];
|
|
589
|
+
return obj;
|
|
590
|
+
};
|
|
591
|
+
const days = {};
|
|
592
|
+
for (const [k, v] of Object.entries(a.perDay)) days[k] = { ...v, dateMs: +v.date, date: undefined, sessions: [...v.sessions] };
|
|
593
|
+
const periods = {};
|
|
594
|
+
for (const [s, sl] of a.periods) periods[s] = {
|
|
595
|
+
...sl,
|
|
596
|
+
perModelPeriod: setToArr(sl.perModelPeriod),
|
|
597
|
+
perAgentPeriod: setToArr(sl.perAgentPeriod),
|
|
598
|
+
};
|
|
599
|
+
return JSON.stringify({
|
|
600
|
+
v: 2, builtAt: a.builtAt, db: dbFingerprint(), byPeriodStart: a.byPeriodStart,
|
|
601
|
+
perDay: days,
|
|
602
|
+
perModel: setToArr(a.perModel), perAgent: setToArr(a.perAgent),
|
|
603
|
+
perSession: a.perSession, totals: a.totals, periods,
|
|
604
|
+
perModelPeriod: setToArr(a.perModelPeriod), perAgentPeriod: setToArr(a.perAgentPeriod),
|
|
605
|
+
perAgentModelPeriod: a.perAgentModelPeriod, perSessionPeriod: a.perSessionPeriod,
|
|
606
|
+
perSessionModelPeriod: a.perSessionModelPeriod,
|
|
607
|
+
msgAgg: a.msgAgg, msgAgentAgg: a.msgAgentAgg,
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
function reviveBundle(o) {
|
|
611
|
+
const fixDays = (d) => {
|
|
612
|
+
const out = {};
|
|
613
|
+
for (const [k, v] of Object.entries(d)) out[k] = { ...v, date: new Date(v.dateMs), dateMs: undefined, sessions: new Set(v.sessions) };
|
|
614
|
+
return out;
|
|
615
|
+
};
|
|
616
|
+
const fixSets = (obj) => {
|
|
617
|
+
for (const k of Object.keys(obj || {})) if (obj[k] && Array.isArray(obj[k].sessions)) obj[k].sessions = new Set(obj[k].sessions);
|
|
618
|
+
return obj || {};
|
|
619
|
+
};
|
|
620
|
+
const periods = new Map();
|
|
621
|
+
for (const [s, sl] of Object.entries(o.periods || {})) {
|
|
622
|
+
periods.set(+s, { ...sl, perDay: fixDays(o.perDay), perModelPeriod: fixSets(sl.perModelPeriod), perAgentPeriod: fixSets(sl.perAgentPeriod) });
|
|
501
623
|
}
|
|
624
|
+
const a = {
|
|
625
|
+
...o,
|
|
626
|
+
perDay: fixDays(o.perDay),
|
|
627
|
+
perModel: fixSets(o.perModel), perAgent: fixSets(o.perAgent),
|
|
628
|
+
perModelPeriod: fixSets(o.perModelPeriod), perAgentPeriod: fixSets(o.perAgentPeriod),
|
|
629
|
+
periods,
|
|
630
|
+
};
|
|
502
631
|
return a;
|
|
503
632
|
}
|
|
504
|
-
|
|
633
|
+
function saveBundleCache(a) {
|
|
634
|
+
try { fs.writeFileSync(BUNDLE_FILE, serializeBundle(a)); } catch (_) {}
|
|
635
|
+
}
|
|
636
|
+
function loadBundleCache() {
|
|
637
|
+
try {
|
|
638
|
+
const raw = fs.readFileSync(BUNDLE_FILE, 'utf8');
|
|
639
|
+
const o = JSON.parse(raw);
|
|
640
|
+
if (o && o.v === 2 && o.db === dbFingerprint() && o.periods && Object.keys(o.periods).length) {
|
|
641
|
+
console.log(`attr bundle loaded from cache (built ${Math.round((Date.now() - o.builtAt) / 60000)} min ago)`);
|
|
642
|
+
return { at: o.builtAt, a: reviveBundle(o) };
|
|
643
|
+
}
|
|
644
|
+
} catch (_) {}
|
|
645
|
+
return null;
|
|
646
|
+
}
|
|
647
|
+
function getAttrAll() {
|
|
648
|
+
if (!attrAllCache) refreshAttrBundle();
|
|
649
|
+
return attrAllCache ? attrAllCache.a : EMPTY_ATTR;
|
|
650
|
+
}
|
|
651
|
+
function getAttrPeriod(startMs) {
|
|
652
|
+
if (!attrAllCache) refreshAttrBundle();
|
|
653
|
+
if (!attrAllCache) return EMPTY_ATTR;
|
|
654
|
+
return attrAllCache.a.periods.get(startMs) || attrAllCache.a;
|
|
655
|
+
}
|
|
656
|
+
function refreshAttrBundle() {
|
|
657
|
+
if (attrBundlePending) return attrAllCache ? attrAllCache.a : null;
|
|
658
|
+
const now = Date.now();
|
|
659
|
+
if (attrAllCache && now - attrAllCache.at < ATTR_TTL) return attrAllCache.a;
|
|
660
|
+
attrBundlePending = true;
|
|
661
|
+
buildAttrBundle(now).then((a) => {
|
|
662
|
+
a.builtAt = now;
|
|
663
|
+
attrAllCache = { at: now, a };
|
|
664
|
+
attrBundlePending = false;
|
|
665
|
+
console.log(`attr bundle rebuilt in ${Date.now() - now}ms`);
|
|
666
|
+
if (now - (attrLastSave || 0) > BUNDLE_SAVE_MS) { attrLastSave = now; saveBundleCache(a); }
|
|
667
|
+
}).catch((e) => {
|
|
668
|
+
attrBundlePending = false;
|
|
669
|
+
console.error('attr bundle failed:', e.message);
|
|
670
|
+
});
|
|
671
|
+
return attrAllCache ? attrAllCache.a : null;
|
|
672
|
+
}
|
|
505
673
|
function computeMedian(arr) {
|
|
506
674
|
if (!arr.length) return 0;
|
|
507
675
|
const sorted = arr.slice().sort((a, b) => a - b);
|
|
@@ -523,7 +691,7 @@ function getStatsFromDb(days) {
|
|
|
523
691
|
|
|
524
692
|
// V2: tool parts are embedded in session_message content (part table froze
|
|
525
693
|
// at the upgrade and its migrated rows were rebuilt into content, so
|
|
526
|
-
// querying all of part would double count
|
|
694
|
+
// querying all of part would double count ??only parts of messages that
|
|
527
695
|
// were never migrated are added from `part`). Cached (see toolsCache):
|
|
528
696
|
// verification accepts api<=expected, so staleness never fails checks.
|
|
529
697
|
if (!toolsCache || now - toolsCache.at > TOOLS_TTL || toolsCache.embedded !== schema.embeddedTools || toolsCache.startMs !== startMs) {
|
|
@@ -583,8 +751,7 @@ function getStatsFromDb(days) {
|
|
|
583
751
|
.sort((a, b) => b.cost - a.cost);
|
|
584
752
|
|
|
585
753
|
// Savings estimate: market value of all-time usage at catalog paid rates,
|
|
586
|
-
// priced per MESSAGE model (residual falls back to the session's model)
|
|
587
|
-
// the same basis as the report providers table. Rows the catalog cannot
|
|
754
|
+
// priced per MESSAGE model (residual falls back to the session's model) ?? // the same basis as the report providers table. Rows the catalog cannot
|
|
588
755
|
// price are EXCLUDED and disclosed (unpricedTokens/unpricedRows) instead of
|
|
589
756
|
// being valued at a made-up rate; proxyShare is how much of the priced
|
|
590
757
|
// total comes from cross-provider estimates.
|
|
@@ -767,8 +934,8 @@ function buildReportFromDb(days) {
|
|
|
767
934
|
// sessions, market/saved) is sliced to THIS period, so the tables sum to the
|
|
768
935
|
// card. The all-time buckets (perDay) are still used for the summary totals
|
|
769
936
|
// and stay identical to the trend chart for the same period.
|
|
770
|
-
const a =
|
|
771
|
-
const aNow =
|
|
937
|
+
const a = getAttrPeriod(startMs);
|
|
938
|
+
const aNow = attrAllCache.at; // snapshot time of the shared bundle
|
|
772
939
|
// Message-level stats per session within the period (period speed + active
|
|
773
940
|
// time). One GROUP BY over the merged message view, mapped onto the same
|
|
774
941
|
// session-meta buckets as tokens so row sets stay identical.
|
|
@@ -776,19 +943,17 @@ function buildReportFromDb(days) {
|
|
|
776
943
|
// subagent/fork sessions are written with time_updated == time_created
|
|
777
944
|
// (same millisecond), which would report ~0 wall for hours of real work.
|
|
778
945
|
// Query the merged message view for the period span per session.
|
|
946
|
+
// Speed / active / wall come from the shared attribution bundle (the same
|
|
947
|
+
// message pass that produced these period buckets), so switching scope costs
|
|
948
|
+
// no SQL at all. Wall uses the MESSAGE clock: subagent/fork sessions are
|
|
949
|
+
// written with time_updated == time_created, which would read as ~0 wall.
|
|
950
|
+
const msgAgg = a.msgAgg || {};
|
|
951
|
+
const msgAgentAgg = a.msgAgentAgg || {};
|
|
779
952
|
const wallMs = {};
|
|
780
|
-
for (const
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
for (const m of (dbQuery(`SELECT session_id AS sid, COUNT(*) AS n, COALESCE(SUM(CASE WHEN CAST(json_extract(data, '$.tokens.output') AS INTEGER) > 0 AND CAST(json_extract(data, '$.time.completed') AS INTEGER) > CAST(json_extract(data, '$.time.created') AS INTEGER) THEN CAST(json_extract(data, '$.tokens.output') AS INTEGER) ELSE 0 END), 0) AS o, COALESCE(SUM(CASE WHEN CAST(json_extract(data,'$.tokens.output') AS INTEGER) > 0 AND CAST(json_extract(data,'$.time.completed') AS INTEGER) > CAST(json_extract(data,'$.time.created') AS INTEGER) THEN CAST(json_extract(data,'$.tokens.reasoning') AS INTEGER) ELSE 0 END), 0) AS rq, COALESCE(SUM(CASE WHEN CAST(json_extract(data, '$.tokens.output') AS INTEGER) > 0 AND CAST(json_extract(data, '$.time.completed') AS INTEGER) > CAST(json_extract(data, '$.time.created') AS INTEGER) THEN CAST(json_extract(data, '$.time.completed') AS INTEGER) - CAST(json_extract(data, '$.time.created') AS INTEGER) ELSE 0 END), 0) AS ms FROM ${schema.message} WHERE time_created >= ${startMs} AND time_created < ${aNow} GROUP BY sid`) || [])) {
|
|
785
|
-
msgAgg[m.sid] = m;
|
|
786
|
-
}
|
|
787
|
-
// Same aggregates per agent — the message layer can name agents that session
|
|
788
|
-
// meta lacks (compaction/plan), so agent speed/active come from messages.
|
|
789
|
-
const msgAgentAgg = {};
|
|
790
|
-
for (const m of (dbQuery(`SELECT COALESCE(json_extract(data,'$.agent'),'unknown') AS agent, COALESCE(SUM(CASE WHEN CAST(json_extract(data,'$.tokens.output') AS INTEGER) > 0 AND CAST(json_extract(data,'$.time.completed') AS INTEGER) > CAST(json_extract(data,'$.time.created') AS INTEGER) THEN CAST(json_extract(data,'$.tokens.output') AS INTEGER) ELSE 0 END),0) AS o, COALESCE(SUM(CASE WHEN CAST(json_extract(data,'$.tokens.output') AS INTEGER) > 0 AND CAST(json_extract(data,'$.time.completed') AS INTEGER) > CAST(json_extract(data,'$.time.created') AS INTEGER) THEN CAST(json_extract(data,'$.time.completed') AS INTEGER) - CAST(json_extract(data,'$.time.created') AS INTEGER) ELSE 0 END),0) AS ms FROM ${schema.message} WHERE time_created >= ${startMs} AND time_created < ${aNow} GROUP BY COALESCE(json_extract(data,'$.agent'),'unknown')`) || [])) {
|
|
791
|
-
msgAgentAgg[m.agent] = { o: m.o, ms: m.ms };
|
|
953
|
+
for (const sid of Object.keys(msgAgg)) {
|
|
954
|
+
const m = msgAgg[sid];
|
|
955
|
+
const w0 = m.w0 === Infinity ? 0 : m.w0;
|
|
956
|
+
wallMs[sid] = Math.max(0, (+m.w1 || 0) - w0);
|
|
792
957
|
}
|
|
793
958
|
const periodDays = {};
|
|
794
959
|
for (const [key, val] of Object.entries(a.perDay)) {
|
|
@@ -806,7 +971,7 @@ function buildReportFromDb(days) {
|
|
|
806
971
|
}
|
|
807
972
|
const t = periodTotals;
|
|
808
973
|
const activeDays = pdVals.length || 1;
|
|
809
|
-
// Avg/median over the PERIOD's token-bearing sessions
|
|
974
|
+
// Avg/median over the PERIOD's token-bearing sessions ??period buckets, so
|
|
810
975
|
// Daily/Weekly differ and the value matches the card and the tables.
|
|
811
976
|
const periodSessionIds = [...periodTotals.sessions];
|
|
812
977
|
const sessVals = periodSessionIds
|
|
@@ -931,7 +1096,7 @@ function buildReportFromDb(days) {
|
|
|
931
1096
|
var pSessionRows = [];
|
|
932
1097
|
}
|
|
933
1098
|
|
|
934
|
-
// Period market =
|
|
1099
|
+
// Period market = 峉 priced provider rows (already period-scoped); saved = 峉
|
|
935
1100
|
// provider saved so it can never mix a period cost with a lifetime market.
|
|
936
1101
|
// Unpriced rows are disclosed, not valued.
|
|
937
1102
|
const sumMkt = (rows) => rows.reduce((s, r) => s + (r.market || 0), 0);
|
|
@@ -969,8 +1134,14 @@ function refreshReport(days) {
|
|
|
969
1134
|
const r = buildReportFromDb(days);
|
|
970
1135
|
if (r && r.stats && r.stats.ok) {
|
|
971
1136
|
reportCache[key] = r;
|
|
1137
|
+
} else {
|
|
1138
|
+
console.error(`report build failed for days=${days}`);
|
|
972
1139
|
}
|
|
973
|
-
} catch (
|
|
1140
|
+
} catch (e) {
|
|
1141
|
+
// Never swallow silently: a broken report must not look like "still
|
|
1142
|
+
// generating" forever while the frontend retries.
|
|
1143
|
+
console.error(`report build threw for days=${days}:`, e && e.stack ? e.stack.split('\n')[0] : e);
|
|
1144
|
+
} finally {
|
|
974
1145
|
delete reportBusy[key];
|
|
975
1146
|
}
|
|
976
1147
|
});
|
|
@@ -1154,9 +1325,32 @@ function tryListen(port, maxPort) {
|
|
|
1154
1325
|
const actualPort = await tryListen(PORT, PORT + 5);
|
|
1155
1326
|
setInterval(refresh, REFRESH_MS);
|
|
1156
1327
|
setInterval(refreshModels, 60000);
|
|
1328
|
+
// Serve from the persisted bundle immediately (startup is instant even when a
|
|
1329
|
+
// live scan would take 5–26s), then refresh in the background when stale.
|
|
1330
|
+
attrBundlePending = true;
|
|
1331
|
+
const cached = loadBundleCache();
|
|
1332
|
+
attrAllCache = cached || null;
|
|
1333
|
+
if (cached) refreshAttrBundle();
|
|
1334
|
+
setInterval(refreshAttrBundle, 60000);
|
|
1157
1335
|
await refresh();
|
|
1158
1336
|
await refreshModels();
|
|
1159
|
-
|
|
1337
|
+
if (!cached) {
|
|
1338
|
+
// Cold start (no cache file yet): one blocking scan, then persist it so
|
|
1339
|
+
// every later start is instant.
|
|
1340
|
+
attrBundlePending = true;
|
|
1341
|
+
const warmT0 = Date.now();
|
|
1342
|
+
attrAllCache = { at: warmT0, a: await buildAttrBundle(Date.now()) };
|
|
1343
|
+
attrAllCache.a.builtAt = warmT0;
|
|
1344
|
+
attrBundlePending = false;
|
|
1345
|
+
attrLastSave = warmT0;
|
|
1346
|
+
saveBundleCache(attrAllCache.a);
|
|
1347
|
+
console.log(`attr bundle warm in ${Date.now() - warmT0}ms (cached to disk)`);
|
|
1348
|
+
await refresh();
|
|
1349
|
+
await refreshModels();
|
|
1350
|
+
}
|
|
1351
|
+
// Today's report eagerly (the common first view). Other periods build on
|
|
1352
|
+
// demand in the background via refreshReport stale-while-revalidate.
|
|
1353
|
+
for (const d of [1]) {
|
|
1160
1354
|
try {
|
|
1161
1355
|
const r = buildReportFromDb(d);
|
|
1162
1356
|
if (r && r.stats && r.stats.ok) reportCache[String(d)] = r;
|
|
@@ -1168,7 +1362,6 @@ function tryListen(port, maxPort) {
|
|
|
1168
1362
|
if (t) trendCache[String(d)] = t;
|
|
1169
1363
|
} catch (_) {}
|
|
1170
1364
|
}
|
|
1171
|
-
// Defer backup to avoid heavy disk I/O during startup
|
|
1172
1365
|
// (Windows may kill process for excessive I/O on large DB files).
|
|
1173
1366
|
setTimeout(() => {
|
|
1174
1367
|
autoBackupIfDue().catch((_) => {});
|