opencode-statboard 2.3.1 → 2.4.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/.github/workflows/publish.yml +1 -1
- package/AGENTS.md +4 -2
- package/package.json +1 -1
- package/public/index.html +15 -0
- package/server.js +225 -99
package/AGENTS.md
CHANGED
|
@@ -41,8 +41,10 @@ Token/cost attribution uses a hybrid model:
|
|
|
41
41
|
1. **Message-level** — Each assistant message's `tokens` and `cost` from `message.data` JSON are attributed to its `time_created` local day
|
|
42
42
|
2. **Session residual** — `session.tokens_* - sum(message.tokens_*)` is spread across the session's full local-day span, weighted by per-day message volume
|
|
43
43
|
3. **Speed (message-level only)** — Per-model `speed` (output tok/s) = Σ completed-assistant-message `tokens.output` ÷ Σ(`time.completed - time.created`). Session residuals carry no duration and are excluded; models without usable durations report `null` (shown as —). Tracked in the same message scan, no extra query.
|
|
44
|
-
4. **
|
|
45
|
-
5. **
|
|
44
|
+
4. **Per-message authority** — When a session's message sums exceed its session-table counters (V2 migration artifact: 455 sessions were recomputed from surviving messages and dropped pruned history; one session reports 52M input where the table says 7.3M), the measured message values win. Overview therefore reads the attribution totals, not `SUM(session.tokens_*)`, so Overview and Report(All) cannot disagree.
|
|
45
|
+
5. **Period scope (report)** — `attributeUsage(start, end, periodStartMs)` slices EVERY total into `*Period` buckets alongside the all-time ones (one scan serves both views; `getAttrAll()` passes `periodStartMs = 0`). Report providers/agents/sessions are built from those period buckets — message tokens under the MESSAGE's model/agent, residual under the SESSION's — so every table column sums exactly to the summary card. `savedTotal` is Σ provider `saved`, never `lifetime market − period cost`.
|
|
46
|
+
6. **Speed / active / wall** — `speed` (output tok/s) and `activeMs` come from in-period message durations; `wallMs` is the per-session span **on the message clock** (`MIN(time_created)`→`MAX(time.completed)`), NOT `session.time_updated − time_created`: subagent/fork sessions are written with both timestamps in the same millisecond, so session-table spans report ~0 wall for hours of real work. Wall includes idle; active is model-running time only, so `wall >= active` always holds (asserted in `check-report-verify.js`).
|
|
47
|
+
7. **Savings estimate (pricing.js, shared with checks)** — Market value at paid rates from the local opencode catalog (`~/.cache/opencode/models.json`, USD/1M). Free models map to a paid basis in order: exact provider/model → strip `-free`/`-contributor-free`, same provider → same base under `opencode` → same base anywhere (sorted) → `proxy:opencode/deepseek-v4-flash` fallback. Reasoning bills at the output rate (verified: `tokens.output` does NOT include reasoning — 8,764 messages have reasoning > output). Pricing is per MESSAGE model, so real paid usage is no longer filed under the session's free-model label. `pricedAs` records the entry used per row.
|
|
46
48
|
|
|
47
49
|
This ensures multi-day sessions (e.g. a session created Monday, updated Thursday) don't dump all tokens onto Thursday.
|
|
48
50
|
|
package/package.json
CHANGED
package/public/index.html
CHANGED
|
@@ -323,6 +323,21 @@ const fmtCost = (n) => (n == null || isNaN(n)) ? '—' : '$' + n.toFixed(2);
|
|
|
323
323
|
const fmtDur = (ms) => { const v = Math.round((ms || 0) / 1000); if (!isFinite(v) || v < 0) return '—'; const d = Math.floor(v / 86400), h = Math.floor(v % 86400 / 3600), m = Math.floor(v % 3600 / 60), s = v % 60; if (d > 0) return d + 'd' + h + 'h'; if (h > 0) return h + 'h' + String(m).padStart(2, '0') + 'm'; if (m > 0) return m + 'm' + String(s).padStart(2, '0') + 's'; return s + 's'; };
|
|
324
324
|
const esc = (s) => String(s == null ? '' : s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
325
325
|
const fmtSpeed = (n) => (n == null || isNaN(n) || !isFinite(n)) ? '—' : ((n >= 100 ? Math.round(n) : Math.round(n * 10) / 10) + ' tok/s');
|
|
326
|
+
const dispAgent = (n) => (n === 'unknown' ? 'legacy' : n);
|
|
327
|
+
const LEGACY_TIP = 'pre-2026-08 V1 legacy, $0';
|
|
328
|
+
function agentTip(base, name) {
|
|
329
|
+
if (name !== 'unknown') return base || '';
|
|
330
|
+
return (base ? base + ' · ' : '') + LEGACY_TIP;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// Skip-unchanged-redraw cache: remember last rendered generations.
|
|
334
|
+
let lastStatsGen = null;
|
|
335
|
+
let lastTrendGen = null;
|
|
336
|
+
const reportGenCache = {};
|
|
337
|
+
let displayedReportDays = null;
|
|
338
|
+
let cachedReport = null;
|
|
339
|
+
let cachedReportDays = null;
|
|
340
|
+
let reportChain = Promise.resolve();
|
|
326
341
|
|
|
327
342
|
function barRow(name, value, max, color) {
|
|
328
343
|
const pct = max > 0 ? Math.max(0.5, (value / max) * 100) : 0;
|
package/server.js
CHANGED
|
@@ -301,14 +301,41 @@ function marketOf(tok, provider, model) {
|
|
|
301
301
|
// proportional to that session's per-day message-token volume
|
|
302
302
|
// (uniform across spanned days when the session has no messages).
|
|
303
303
|
// Returns perDay/perModel/perAgent/perSession maps plus totals.
|
|
304
|
-
|
|
304
|
+
// periodStartMs (optional): when set, ALSO slice every total into
|
|
305
|
+
// *-Period buckets covering only local days >= periodStartMs. The all-time
|
|
306
|
+
// buckets (perDay/perModel/perSession) are unaffected, so one scan serves both
|
|
307
|
+
// the trend (lifetime) and the report (period) views. Period buckets group
|
|
308
|
+
// message tokens by the MESSAGE's own model/agent, and spread session residual
|
|
309
|
+
// by the session's model/agent — so per-model report rows sum exactly to the
|
|
310
|
+
// period totals (self-consistent by construction).
|
|
311
|
+
function attributeUsage(startMs, endMs, periodStartMs) {
|
|
312
|
+
const periodOn = periodStartMs != null;
|
|
313
|
+
const inPeriod = periodOn ? (key) => dateOfKey(key).getTime() >= periodStartMs : () => false;
|
|
305
314
|
const perDay = {};
|
|
306
315
|
const perModel = {};
|
|
307
316
|
const perAgent = {};
|
|
308
317
|
const perSession = {};
|
|
318
|
+
const perModelPeriod = {};
|
|
319
|
+
const perAgentPeriod = {};
|
|
320
|
+
const perAgentModelPeriod = {};
|
|
321
|
+
const perSessionPeriod = {};
|
|
322
|
+
const perSessionModelPeriod = {};
|
|
309
323
|
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 });
|
|
310
324
|
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 });
|
|
311
325
|
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 });
|
|
326
|
+
const tok = () => ({ input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 });
|
|
327
|
+
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 });
|
|
328
|
+
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 });
|
|
329
|
+
const ensureAgentModelP = (a, m) => {
|
|
330
|
+
const k = a || 'unknown';
|
|
331
|
+
const bag = perAgentModelPeriod[k] || (perAgentModelPeriod[k] = {});
|
|
332
|
+
return bag[m] || (bag[m] = tok());
|
|
333
|
+
};
|
|
334
|
+
const ensureSessP = (sid) => perSessionPeriod[sid] || (perSessionPeriod[sid] = tok());
|
|
335
|
+
const ensureSessModelP = (sid, m) => {
|
|
336
|
+
const bag = perSessionModelPeriod[sid] || (perSessionModelPeriod[sid] = {});
|
|
337
|
+
return bag[m] || (bag[m] = tok());
|
|
338
|
+
};
|
|
312
339
|
|
|
313
340
|
// 1. messages in period (exact timing)
|
|
314
341
|
const msgTok = {};
|
|
@@ -342,6 +369,28 @@ function attributeUsage(startMs, endMs) {
|
|
|
342
369
|
w.total += vol;
|
|
343
370
|
w.perDay[key] = (w.perDay[key] || 0) + vol;
|
|
344
371
|
}
|
|
372
|
+
// Period slice: message tokens under the MESSAGE's own model/agent.
|
|
373
|
+
if (periodOn && inPeriod(key)) {
|
|
374
|
+
const mName = modelNameOf(r.provider, r.model);
|
|
375
|
+
const aName = r.agent || 'unknown';
|
|
376
|
+
const MP = ensureModelP(mName);
|
|
377
|
+
MP.messages++;
|
|
378
|
+
if (r.sid) MP.sessions.add(r.sid);
|
|
379
|
+
MP.input += iv; MP.output += ov; MP.reasoning += rv; MP.cacheRead += crv; MP.cacheWrite += cwv; MP.cost += cv;
|
|
380
|
+
if (ov > 0 && t1 > t0) { MP.speedOut += ov; MP.speedMs += (t1 - t0); }
|
|
381
|
+
const AP = ensureAgentP(aName);
|
|
382
|
+
if (r.sid) AP.sessions.add(r.sid);
|
|
383
|
+
AP.input += iv; AP.output += ov; AP.reasoning += rv; AP.cacheRead += crv; AP.cacheWrite += cwv; AP.cost += cv;
|
|
384
|
+
if (ov > 0 && t1 > t0) { AP.speedOut += ov; AP.speedMs += (t1 - t0); }
|
|
385
|
+
const AM = ensureAgentModelP(aName, mName);
|
|
386
|
+
AM.input += iv; AM.output += ov; AM.reasoning += rv; AM.cacheRead += crv; AM.cacheWrite += cwv; AM.cost += cv;
|
|
387
|
+
if (r.sid) {
|
|
388
|
+
const SP = ensureSessP(r.sid);
|
|
389
|
+
SP.input += iv; SP.output += ov; SP.reasoning += rv; SP.cacheRead += crv; SP.cacheWrite += cwv; SP.cost += cv;
|
|
390
|
+
const SM = ensureSessModelP(r.sid, mName);
|
|
391
|
+
SM.input += iv; SM.output += ov; SM.reasoning += rv; SM.cacheRead += crv; SM.cacheWrite += cwv; SM.cost += cv;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
345
394
|
}
|
|
346
395
|
|
|
347
396
|
// 2. sessions intersecting the period: spread residual
|
|
@@ -387,6 +436,21 @@ function attributeUsage(startMs, endMs) {
|
|
|
387
436
|
const A = ensureAgent(aName);
|
|
388
437
|
A.input += di; A.output += dout; A.reasoning += dr; A.cacheRead += dcr; A.cacheWrite += dcw; A.cost += dc;
|
|
389
438
|
ps.input += di; ps.output += dout; ps.reasoning += dr; ps.cacheRead += dcr; ps.cacheWrite += dcw; ps.cost += dc;
|
|
439
|
+
// Period slice: residual shares land under the SESSION's model/agent
|
|
440
|
+
// (no per-message model exists for residual), but only on days inside
|
|
441
|
+
// the period, so period rows sum exactly to the period totals.
|
|
442
|
+
if (periodOn && inPeriod(k)) {
|
|
443
|
+
const MP = ensureModelP(mName);
|
|
444
|
+
MP.input += di; MP.output += dout; MP.reasoning += dr; MP.cacheRead += dcr; MP.cacheWrite += dcw; MP.cost += dc;
|
|
445
|
+
const AP = ensureAgentP(aName);
|
|
446
|
+
AP.input += di; AP.output += dout; AP.reasoning += dr; AP.cacheRead += dcr; AP.cacheWrite += dcw; AP.cost += dc;
|
|
447
|
+
const AM = ensureAgentModelP(aName, mName);
|
|
448
|
+
AM.input += di; AM.output += dout; AM.reasoning += dr; AM.cacheRead += dcr; AM.cacheWrite += dcw; AM.cost += dc;
|
|
449
|
+
const SP = ensureSessP(s.id);
|
|
450
|
+
SP.input += di; SP.output += dout; SP.reasoning += dr; SP.cacheRead += dcr; SP.cacheWrite += dcw; SP.cost += dc;
|
|
451
|
+
const SM = ensureSessModelP(s.id, mName);
|
|
452
|
+
SM.input += di; SM.output += dout; SM.reasoning += dr; SM.cacheRead += dcr; SM.cacheWrite += dcw; SM.cost += dc;
|
|
453
|
+
}
|
|
390
454
|
}
|
|
391
455
|
}
|
|
392
456
|
|
|
@@ -397,7 +461,11 @@ function attributeUsage(startMs, endMs) {
|
|
|
397
461
|
totals.input += D.input; totals.output += D.output; totals.reasoning += D.reasoning;
|
|
398
462
|
totals.cacheRead += D.cacheRead; totals.cacheWrite += D.cacheWrite; totals.cost += D.cost;
|
|
399
463
|
}
|
|
400
|
-
return {
|
|
464
|
+
return {
|
|
465
|
+
perDay, perModel, perAgent, perSession, totals,
|
|
466
|
+
perModelPeriod, perAgentPeriod, perAgentModelPeriod, perSessionPeriod, perSessionModelPeriod,
|
|
467
|
+
periodStartMs,
|
|
468
|
+
};
|
|
401
469
|
}
|
|
402
470
|
|
|
403
471
|
// All-time attribution, memoized 300s (expensive full DB scan; avoids
|
|
@@ -409,11 +477,29 @@ let toolsCache = null;
|
|
|
409
477
|
function getAttrAll() {
|
|
410
478
|
const now = Date.now();
|
|
411
479
|
if (attrAllCache && now - attrAllCache.at < 300000) return attrAllCache.a;
|
|
412
|
-
|
|
480
|
+
// periodStartMs = 0: the *Period buckets equal the all-time ones, so the
|
|
481
|
+
// All report can read them (single scan serves both views).
|
|
482
|
+
const a = attributeUsage(0, now, 0);
|
|
413
483
|
attrAllCache = { at: now, a };
|
|
414
484
|
return a;
|
|
415
485
|
}
|
|
416
486
|
|
|
487
|
+
// Period-scoped attribution (same 300s TTL, one cache slot per period start).
|
|
488
|
+
// Report panels slice this instead of the all-time buckets so every row and
|
|
489
|
+
// the summary total describe the SAME period.
|
|
490
|
+
const attrPeriodCache = new Map();
|
|
491
|
+
function getAttrPeriod(startMs) {
|
|
492
|
+
const now = Date.now();
|
|
493
|
+
const hit = attrPeriodCache.get(startMs);
|
|
494
|
+
if (hit && now - hit.at < 300000) return hit.a;
|
|
495
|
+
const a = attributeUsage(0, now, startMs);
|
|
496
|
+
attrPeriodCache.set(startMs, { at: now, a });
|
|
497
|
+
if (attrPeriodCache.size > 6) {
|
|
498
|
+
for (const [k, v] of attrPeriodCache) if (now - v.at >= 300000) attrPeriodCache.delete(k);
|
|
499
|
+
}
|
|
500
|
+
return a;
|
|
501
|
+
}
|
|
502
|
+
|
|
417
503
|
function computeMedian(arr) {
|
|
418
504
|
if (!arr.length) return 0;
|
|
419
505
|
const sorted = arr.slice().sort((a, b) => a - b);
|
|
@@ -431,11 +517,7 @@ function getStatsFromDb(days) {
|
|
|
431
517
|
// NOTE: days is only ever 0 here (overview totals); per-period stats are
|
|
432
518
|
// built by buildReportFromDb via attributeUsage. Local-day count so the
|
|
433
519
|
// number matches the trend chart buckets.
|
|
434
|
-
|
|
435
|
-
const msgConds = [];
|
|
436
|
-
if (startMs) msgConds.push('m.time_updated >= ' + startMs);
|
|
437
|
-
const msgCount = dbGet(`SELECT COUNT(*) AS messages FROM ${schema.message} m ${msgConds.length ? 'WHERE ' + msgConds.join(' AND ') : ''};`);
|
|
438
|
-
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};`);
|
|
520
|
+
|
|
439
521
|
|
|
440
522
|
// V2: tool parts are embedded in session_message content (part table froze
|
|
441
523
|
// at the upgrade and its migrated rows were rebuilt into content, so
|
|
@@ -460,24 +542,37 @@ function getStatsFromDb(days) {
|
|
|
460
542
|
.map(([name, count]) => ({ name, count, pct: Math.round((count / totalToolUse) * 1000) / 10 }))
|
|
461
543
|
.sort((a, b) => b.count - a.count);
|
|
462
544
|
|
|
463
|
-
const
|
|
464
|
-
const
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
545
|
+
const attr = getAttrAll();
|
|
546
|
+
const T = attr.totals;
|
|
547
|
+
// Overview = ALL TIME and uses the SAME attribution as the trend chart and
|
|
548
|
+
// Report(All), so the three panels cannot disagree. Per-message tokens are
|
|
549
|
+
// authoritative: a session whose message sums exceed its session-table
|
|
550
|
+
// counters (V2 migration artifact) keeps the measured message values
|
|
551
|
+
// instead of being clamped down to the session counters.
|
|
552
|
+
const sessions = T.sessions;
|
|
553
|
+
const messages = T.messages;
|
|
554
|
+
// Active days = day buckets that actually carry usage. Excludes pre-2000
|
|
555
|
+
// epoch artifacts (imported rows with time_created = 0).
|
|
556
|
+
const dayKeys = Object.keys(attr.perDay).filter((k) => attr.perDay[k].date.getFullYear() >= 2020);
|
|
557
|
+
const activeDays = dayKeys.length || 1;
|
|
558
|
+
const sessVals = Object.values(attr.perSession)
|
|
559
|
+
.filter((s) => s.input > 0 || s.output > 0 || s.reasoning > 0)
|
|
560
|
+
.map((s) => s.input + s.output + s.reasoning)
|
|
561
|
+
.filter(Number.isFinite);
|
|
562
|
+
const avgTokens = sessVals.length ? sessVals.reduce((s, v) => s + v, 0) / sessVals.length : 0;
|
|
563
|
+
const medianTokens = computeMedian(sessVals);
|
|
564
|
+
const avgDayCost = T.cost ? T.cost / activeDays : 0;
|
|
470
565
|
|
|
471
566
|
// Per-model usage from hybrid attribution (message counts are TRUE message
|
|
472
567
|
// counts here, not session counts; token/cost sums include residuals so
|
|
473
568
|
// pruned history isn't lost).
|
|
474
|
-
const attr = getAttrAll();
|
|
475
569
|
const models = Object.entries(attr.perModel)
|
|
476
570
|
.map(([name, m]) => ({
|
|
477
571
|
name,
|
|
478
572
|
messages: m.messages,
|
|
479
573
|
input: Math.round(m.input),
|
|
480
574
|
output: Math.round(m.output),
|
|
575
|
+
reasoning: Math.round(m.reasoning),
|
|
481
576
|
cacheRead: Math.round(m.cacheRead),
|
|
482
577
|
cacheWrite: Math.round(m.cacheWrite),
|
|
483
578
|
cost: m.cost,
|
|
@@ -485,46 +580,41 @@ function getStatsFromDb(days) {
|
|
|
485
580
|
}))
|
|
486
581
|
.sort((a, b) => b.cost - a.cost);
|
|
487
582
|
|
|
488
|
-
// Savings estimate: market value of all-time usage at catalog paid rates
|
|
489
|
-
//
|
|
490
|
-
//
|
|
491
|
-
// model-switched sessions differently.
|
|
583
|
+
// Savings estimate: market value of all-time usage at catalog paid rates,
|
|
584
|
+
// priced per MESSAGE model (residual falls back to the session's model) —
|
|
585
|
+
// the same basis as the report providers table.
|
|
492
586
|
let marketTotal = null, savedTotal = null, priceAsOf = null;
|
|
493
587
|
{
|
|
494
588
|
const info = pricing.catalogInfo();
|
|
495
589
|
if (info.ok) {
|
|
496
590
|
priceAsOf = new Date(info.mtimeMs).toISOString();
|
|
497
591
|
marketTotal = 0;
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
const mk = marketOf({ input:
|
|
592
|
+
for (const [name, m] of Object.entries(attr.perModel)) {
|
|
593
|
+
const { provider, model } = splitModelName(name);
|
|
594
|
+
const mk = marketOf({ input: m.input, output: m.output, reasoning: m.reasoning, cacheRead: m.cacheRead, cost: m.cost }, provider, model);
|
|
501
595
|
if (mk.market === null) { marketTotal = null; break; }
|
|
502
596
|
marketTotal += mk.market;
|
|
503
597
|
}
|
|
504
598
|
if (marketTotal !== null) {
|
|
505
599
|
marketTotal = Math.round(marketTotal * 10000) / 10000;
|
|
506
|
-
savedTotal = Math.round((marketTotal -
|
|
600
|
+
savedTotal = Math.round((marketTotal - T.cost) * 10000) / 10000;
|
|
507
601
|
} else { savedTotal = null; }
|
|
508
602
|
}
|
|
509
603
|
}
|
|
510
604
|
|
|
511
605
|
return {
|
|
512
606
|
ok: true,
|
|
513
|
-
overview: {
|
|
514
|
-
sessions: sessions,
|
|
515
|
-
messages: msgCount ? (msgCount.messages || 0) : 0,
|
|
516
|
-
days: activeDays,
|
|
517
|
-
},
|
|
607
|
+
overview: { sessions, messages, days: activeDays },
|
|
518
608
|
cost: {
|
|
519
|
-
total:
|
|
609
|
+
total: T.cost,
|
|
520
610
|
avgDay: avgDayCost,
|
|
521
611
|
avgTokensSession: Math.round(avgTokens),
|
|
522
612
|
medianTokensSession: Math.round(medianTokens),
|
|
523
|
-
input:
|
|
524
|
-
output:
|
|
525
|
-
reasoning:
|
|
526
|
-
cacheRead:
|
|
527
|
-
cacheWrite:
|
|
613
|
+
input: Math.round(T.input),
|
|
614
|
+
output: Math.round(T.output),
|
|
615
|
+
reasoning: Math.round(T.reasoning),
|
|
616
|
+
cacheRead: Math.round(T.cacheRead),
|
|
617
|
+
cacheWrite: Math.round(T.cacheWrite),
|
|
528
618
|
marketTotal, savedTotal, priceAsOf,
|
|
529
619
|
},
|
|
530
620
|
tools,
|
|
@@ -660,19 +750,33 @@ function buildReportFromDb(days) {
|
|
|
660
750
|
const startMs = periodStartMs(days, now);
|
|
661
751
|
const label = days === -1 ? 'All' : days <= 1 ? 'Daily' : days <= 7 ? 'Weekly' : 'Monthly';
|
|
662
752
|
|
|
663
|
-
//
|
|
664
|
-
//
|
|
665
|
-
//
|
|
666
|
-
// trend chart
|
|
667
|
-
const a = getAttrAll();
|
|
668
|
-
const aNow = attrAllCache.at; //
|
|
753
|
+
// Period-scoped attribution: every number below (summary, providers, agents,
|
|
754
|
+
// sessions, market/saved) is sliced to THIS period, so the tables sum to the
|
|
755
|
+
// card. The all-time buckets (perDay) are still used for the summary totals
|
|
756
|
+
// and stay identical to the trend chart for the same period.
|
|
757
|
+
const a = days === -1 ? getAttrAll() : getAttrPeriod(startMs);
|
|
758
|
+
const aNow = days === -1 ? attrAllCache.at : attrPeriodCache.get(startMs).at; // snapshot time of `a`
|
|
669
759
|
// Message-level stats per session within the period (period speed + active
|
|
670
760
|
// time). One GROUP BY over the merged message view, mapped onto the same
|
|
671
761
|
// session-meta buckets as tokens so row sets stay identical.
|
|
762
|
+
// Wall time must come from the MESSAGE clock, not session.time_updated:
|
|
763
|
+
// subagent/fork sessions are written with time_updated == time_created
|
|
764
|
+
// (same millisecond), which would report ~0 wall for hours of real work.
|
|
765
|
+
// Query the merged message view for the period span per session.
|
|
766
|
+
const wallMs = {};
|
|
767
|
+
for (const m of (dbQuery(`SELECT session_id AS sid, MIN(time_created) AS t0, MAX(COALESCE(CAST(json_extract(data,'$.time.completed') AS INTEGER), time_updated)) AS t1 FROM ${schema.message} WHERE time_created >= ${startMs} AND time_created < ${aNow} GROUP BY session_id`) || [])) {
|
|
768
|
+
wallMs[m.sid] = Math.max(0, (+m.t1 || 0) - (+m.t0 || 0));
|
|
769
|
+
}
|
|
672
770
|
const msgAgg = {};
|
|
673
771
|
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`) || [])) {
|
|
674
772
|
msgAgg[m.sid] = m;
|
|
675
773
|
}
|
|
774
|
+
// Same aggregates per agent — the message layer can name agents that session
|
|
775
|
+
// meta lacks (compaction/plan), so agent speed/active come from messages.
|
|
776
|
+
const msgAgentAgg = {};
|
|
777
|
+
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')`) || [])) {
|
|
778
|
+
msgAgentAgg[m.agent] = { o: m.o, ms: m.ms };
|
|
779
|
+
}
|
|
676
780
|
const periodDays = {};
|
|
677
781
|
for (const [key, val] of Object.entries(a.perDay)) {
|
|
678
782
|
const dayMs = val.date.getTime();
|
|
@@ -689,12 +793,11 @@ function buildReportFromDb(days) {
|
|
|
689
793
|
}
|
|
690
794
|
const t = periodTotals;
|
|
691
795
|
const activeDays = pdVals.length || 1;
|
|
692
|
-
// Avg/median over the PERIOD's token-bearing sessions
|
|
693
|
-
//
|
|
694
|
-
// Weekly reports differ.
|
|
796
|
+
// Avg/median over the PERIOD's token-bearing sessions — period buckets, so
|
|
797
|
+
// Daily/Weekly differ and the value matches the card and the tables.
|
|
695
798
|
const periodSessionIds = [...periodTotals.sessions];
|
|
696
799
|
const sessVals = periodSessionIds
|
|
697
|
-
.map((sid) => a.perSession[sid])
|
|
800
|
+
.map((sid) => (a.perSessionPeriod || a.perSession)[sid])
|
|
698
801
|
.filter((s) => s && (s.input > 0 || s.output > 0 || s.reasoning > 0))
|
|
699
802
|
.map((s) => s.input + s.output + s.reasoning)
|
|
700
803
|
.filter(Number.isFinite);
|
|
@@ -723,50 +826,23 @@ function buildReportFromDb(days) {
|
|
|
723
826
|
const metaMap = {};
|
|
724
827
|
for (const s of sessMeta) metaMap[s.id] = s;
|
|
725
828
|
|
|
726
|
-
const agentAgg = {};
|
|
727
|
-
const modelAgg = {};
|
|
728
829
|
const sessRows = [];
|
|
729
830
|
for (const sid of periodSessionIds) {
|
|
730
|
-
const
|
|
731
|
-
if (!ps) continue;
|
|
732
|
-
const meta = metaMap[sid] || { agent: 'unknown', provider: 'unknown', model: 'unknown' };
|
|
733
|
-
const agent = meta.agent || 'unknown';
|
|
734
|
-
const modelName = `${meta.provider}/${meta.model}`;
|
|
735
|
-
if (!agentAgg[agent]) agentAgg[agent] = { sessions: new Set(), cost: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, speedOut: 0, speedMs: 0, wallMs: 0, activeMs: 0, market: 0, saved: 0 };
|
|
736
|
-
agentAgg[agent].sessions.add(sid);
|
|
737
|
-
agentAgg[agent].input += ps.input; agentAgg[agent].output += ps.output;
|
|
738
|
-
agentAgg[agent].reasoning += ps.reasoning; agentAgg[agent].cacheRead += ps.cacheRead;
|
|
739
|
-
agentAgg[agent].cost += ps.cost;
|
|
831
|
+
const meta = metaMap[sid] || { agent: 'unknown', provider: 'unknown', model: 'unknown', tc: 0, tu: 0 };
|
|
740
832
|
const mg = msgAgg[sid] || { n: 0, o: 0, ms: 0, rq: 0 };
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
const mkA = marketOf({ input: ps.input, output: ps.output, reasoning: ps.reasoning, cacheRead: ps.cacheRead, cost: ps.cost }, meta.provider || 'unknown', meta.model || 'unknown');
|
|
744
|
-
if (mkA.market !== null) { agentAgg[agent].market += mkA.market; agentAgg[agent].saved += mkA.saved; }
|
|
745
|
-
if (!modelAgg[modelName]) modelAgg[modelName] = { sessions: new Set(), cost: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, speedOut: 0, speedMs: 0 };
|
|
746
|
-
modelAgg[modelName].sessions.add(sid);
|
|
747
|
-
modelAgg[modelName].input += ps.input; modelAgg[modelName].output += ps.output;
|
|
748
|
-
modelAgg[modelName].reasoning += ps.reasoning; modelAgg[modelName].cacheRead += ps.cacheRead;
|
|
749
|
-
modelAgg[modelName].cost += ps.cost;
|
|
750
|
-
modelAgg[modelName].speedOut += mg.o; modelAgg[modelName].speedMs += mg.ms;
|
|
751
|
-
sessRows.push({ sid, meta, ps, mg });
|
|
833
|
+
const sm = (a.perSessionModelPeriod && a.perSessionModelPeriod[sid]) || null;
|
|
834
|
+
sessRows.push({ sid, meta, ps: a.perSessionPeriod ? a.perSessionPeriod[sid] : a.perSession[sid], mg, sm });
|
|
752
835
|
}
|
|
753
836
|
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
tok_reasoning: Math.round(m.reasoning), cache_read: Math.round(m.cacheRead),
|
|
759
|
-
speed: m.speedMs > 0 ? Math.round((m.speedOut / (m.speedMs / 1000)) * 10) / 10 : null,
|
|
760
|
-
wallMs: Math.round(m.wallMs), activeMs: Math.round(m.activeMs),
|
|
761
|
-
market: Math.round(m.market * 10000) / 10000, saved: Math.round(m.saved * 10000) / 10000,
|
|
762
|
-
}))
|
|
763
|
-
.sort((x, y) => y.cost - x.cost);
|
|
764
|
-
var pProviderRows = Object.entries(modelAgg)
|
|
837
|
+
// Providers/agents come straight from the period buckets (message tokens
|
|
838
|
+
// under the message's own model; residual under the session's), so their
|
|
839
|
+
// columns sum EXACTLY to the summary card by construction.
|
|
840
|
+
var pProviderRows = Object.entries(a.perModelPeriod)
|
|
765
841
|
.map(([name, m]) => {
|
|
766
842
|
const { provider, model } = splitModelName(name);
|
|
767
843
|
const mk = marketOf({ input: m.input, output: m.output, reasoning: m.reasoning, cacheRead: m.cacheRead, cost: m.cost }, provider, model);
|
|
768
844
|
return {
|
|
769
|
-
provider, model, sessions: m.sessions.size, cost: r4(m.cost),
|
|
845
|
+
provider, model, sessions: m.sessions.size, messages: m.messages, cost: r4(m.cost),
|
|
770
846
|
tok_in: Math.round(m.input), tok_out: Math.round(m.output),
|
|
771
847
|
tok_reasoning: Math.round(m.reasoning), cache_read: Math.round(m.cacheRead),
|
|
772
848
|
speed: m.speedMs > 0 ? Math.round((m.speedOut / (m.speedMs / 1000)) * 10) / 10 : null,
|
|
@@ -774,22 +850,65 @@ function buildReportFromDb(days) {
|
|
|
774
850
|
};
|
|
775
851
|
})
|
|
776
852
|
.sort((x, y) => y.cost - x.cost);
|
|
853
|
+
|
|
854
|
+
var pAgentRows = Object.entries(a.perAgentPeriod)
|
|
855
|
+
.map(([agent, m]) => {
|
|
856
|
+
let market = 0, saved = 0, priced = false;
|
|
857
|
+
const bag = (a.perAgentModelPeriod && a.perAgentModelPeriod[agent]) || {};
|
|
858
|
+
for (const [name, b] of Object.entries(bag)) {
|
|
859
|
+
const { provider, model } = splitModelName(name);
|
|
860
|
+
const mk = marketOf({ input: b.input, output: b.output, reasoning: b.reasoning, cacheRead: b.cacheRead, cost: b.cost }, provider, model);
|
|
861
|
+
if (mk.market === null) { market = null; break; }
|
|
862
|
+
market += mk.market; saved += mk.saved; priced = true;
|
|
863
|
+
}
|
|
864
|
+
// Wall = period span measured on the message clock (see wallMs above).
|
|
865
|
+
let agentWall = 0;
|
|
866
|
+
for (const sid of m.sessions) agentWall += wallMs[sid] || 0;
|
|
867
|
+
return {
|
|
868
|
+
agent, sessions: m.sessions.size, cost: r4(m.cost),
|
|
869
|
+
tok_in: Math.round(m.input), tok_out: Math.round(m.output),
|
|
870
|
+
tok_reasoning: Math.round(m.reasoning), cache_read: Math.round(m.cacheRead),
|
|
871
|
+
speed: msgAgentAgg[agent] && msgAgentAgg[agent].ms > 0 ? Math.round((msgAgentAgg[agent].o / (msgAgentAgg[agent].ms / 1000)) * 10) / 10 : null,
|
|
872
|
+
wallMs: Math.round(agentWall),
|
|
873
|
+
activeMs: msgAgentAgg[agent] ? Math.round(msgAgentAgg[agent].ms) : 0,
|
|
874
|
+
market: market === null ? null : Math.round(market * 10000) / 10000,
|
|
875
|
+
saved: market === null ? null : Math.round(saved * 10000) / 10000,
|
|
876
|
+
pricedAs: priced,
|
|
877
|
+
};
|
|
878
|
+
})
|
|
879
|
+
.sort((x, y) => y.cost - x.cost);
|
|
777
880
|
var pSessionRows = sessRows
|
|
778
|
-
.map(({ sid, meta, ps, mg }) => {
|
|
779
|
-
|
|
881
|
+
.map(({ sid, meta, ps, mg, sm }) => {
|
|
882
|
+
// Price by the session's own period model mix when available
|
|
883
|
+
// (message tokens under the message's model), else the session's meta
|
|
884
|
+
// model (residual-only sessions).
|
|
885
|
+
let market = null, saved = null, pricedAs = null, prov = meta.provider || 'unknown', mod = meta.model || 'unknown';
|
|
886
|
+
const bag = sm || null;
|
|
887
|
+
if (bag && Object.keys(bag).length) {
|
|
888
|
+
const name = Object.keys(bag).sort((a, b) => {
|
|
889
|
+
const va = bag[a].input + bag[a].output + bag[a].cacheRead;
|
|
890
|
+
const vb = bag[b].input + bag[b].output + bag[b].cacheRead;
|
|
891
|
+
return vb - va;
|
|
892
|
+
})[0];
|
|
893
|
+
const sp = splitModelName(name);
|
|
894
|
+
prov = sp.provider; mod = sp.model;
|
|
895
|
+
}
|
|
896
|
+
const mkS = marketOf({ input: ps.input, output: ps.output, reasoning: mg.rq || 0, cacheRead: ps.cacheRead, cost: ps.cost }, prov, mod);
|
|
897
|
+
market = mkS.market; saved = mkS.saved; pricedAs = mkS.pricedAs;
|
|
898
|
+
// Wall from the message clock (see wallMs above).
|
|
780
899
|
return {
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
900
|
+
id: sid, title: (meta.title || '').slice(0, 40), agent: meta.agent || 'unknown',
|
|
901
|
+
provider: prov, model: mod,
|
|
902
|
+
wallMs: wallMs[sid] || 0,
|
|
903
|
+
activeMs: mg.ms || 0, messages: mg.n || 0,
|
|
904
|
+
tok_in: Math.round(ps.input), tok_out: Math.round(ps.output),
|
|
905
|
+
tok_reasoning: Math.round(mg.rq || 0),
|
|
906
|
+
cost: r4(ps.cost),
|
|
907
|
+
speed: (mg.ms || 0) > 0 ? Math.round(((mg.o || 0) / (mg.ms / 1000)) * 10) / 10 : null,
|
|
908
|
+
market, saved, pricedAs,
|
|
790
909
|
};
|
|
791
910
|
})
|
|
792
|
-
.sort((x, y) => y.
|
|
911
|
+
.sort((x, y) => y.activeMs - x.activeMs)
|
|
793
912
|
.slice(0, 20);
|
|
794
913
|
} else {
|
|
795
914
|
var pAgentRows = [];
|
|
@@ -797,9 +916,12 @@ function buildReportFromDb(days) {
|
|
|
797
916
|
var pSessionRows = [];
|
|
798
917
|
}
|
|
799
918
|
|
|
919
|
+
// Period market = Σ provider rows (already period-scoped); saved = Σ provider
|
|
920
|
+
// saved so it can never mix a period cost with a lifetime market.
|
|
800
921
|
const sumMkt = (rows) => rows.reduce((s, r) => s + (r.market || 0), 0);
|
|
922
|
+
const sumSaved = (rows) => rows.reduce((s, r) => s + (r.saved || 0), 0);
|
|
801
923
|
statsR.cost.marketTotal = Math.round(sumMkt(pProviderRows) * 10000) / 10000;
|
|
802
|
-
statsR.cost.savedTotal = Math.round((
|
|
924
|
+
statsR.cost.savedTotal = Math.round(sumSaved(pProviderRows) * 10000) / 10000;
|
|
803
925
|
statsR.cost.savedPct = statsR.cost.marketTotal > 0 ? Math.round((statsR.cost.savedTotal / statsR.cost.marketTotal) * 1000) / 10 : null;
|
|
804
926
|
statsR.cost.priceAsOf = pricing.catalogInfo().ok ? new Date(pricing.catalogInfo().mtimeMs).toISOString() : null;
|
|
805
927
|
|
|
@@ -822,13 +944,16 @@ function refreshReport(days) {
|
|
|
822
944
|
if (fresh) return { report: hit, ready: true };
|
|
823
945
|
if (!reportBusy[key]) {
|
|
824
946
|
reportBusy[key] = true;
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
947
|
+
setImmediate(() => {
|
|
948
|
+
try {
|
|
949
|
+
const r = buildReportFromDb(days);
|
|
950
|
+
if (r && r.stats && r.stats.ok) {
|
|
951
|
+
reportCache[key] = r;
|
|
952
|
+
}
|
|
953
|
+
} catch (_) {} finally {
|
|
954
|
+
delete reportBusy[key];
|
|
829
955
|
}
|
|
830
|
-
}
|
|
831
|
-
delete reportBusy[key];
|
|
956
|
+
});
|
|
832
957
|
}
|
|
833
958
|
return hit ? { report: Object.assign({}, hit, { stale: true }), ready: true } : { report: null, ready: false };
|
|
834
959
|
}
|
|
@@ -949,6 +1074,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
949
1074
|
return;
|
|
950
1075
|
}
|
|
951
1076
|
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
1077
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
952
1078
|
res.end(data.replace('__VERSION__', VERSION));
|
|
953
1079
|
});
|
|
954
1080
|
} else {
|