opencode-statboard 2.3.1 → 2.5.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/pricing.js +67 -33
- package/public/index.html +673 -456
- package/server.js +254 -108
package/server.js
CHANGED
|
@@ -279,15 +279,17 @@ 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.
|
|
283
|
-
//
|
|
282
|
+
// market minus actual cost. kind is 'exact' | 'sibling' | 'proxy' — how the
|
|
283
|
+
// rate was found; null (kind 'unpriced') when the catalog has NO comparable
|
|
284
|
+
// paid listing, in which case we report no money at all rather than inventing
|
|
285
|
+
// a rate (that fake rate once turned a $0 model into $212 of phantom savings).
|
|
284
286
|
// Market-price engine rules live in pricing.js (shared with check scripts).
|
|
285
287
|
function marketOf(tok, provider, model) {
|
|
286
288
|
const pr = pricing.priceFor(provider, model);
|
|
287
|
-
if (!pr) return { market: null, saved: null, pricedAs: null };
|
|
289
|
+
if (!pr) return { market: null, saved: null, pricedAs: null, priced: false, kind: 'unpriced' };
|
|
288
290
|
const market = pricing.marketOf(tok, pr);
|
|
289
291
|
const r4m = (v) => Math.round(v * 10000) / 10000;
|
|
290
|
-
return { market: r4m(market), saved: r4m(market - (tok.cost || 0)), pricedAs: pr.source };
|
|
292
|
+
return { market: r4m(market), saved: r4m(market - (tok.cost || 0)), pricedAs: pr.source, priced: true, kind: pr.kind };
|
|
291
293
|
}
|
|
292
294
|
|
|
293
295
|
// Hybrid usage attribution over [startMs, endMs).
|
|
@@ -301,14 +303,41 @@ function marketOf(tok, provider, model) {
|
|
|
301
303
|
// proportional to that session's per-day message-token volume
|
|
302
304
|
// (uniform across spanned days when the session has no messages).
|
|
303
305
|
// Returns perDay/perModel/perAgent/perSession maps plus totals.
|
|
304
|
-
|
|
306
|
+
// periodStartMs (optional): when set, ALSO slice every total into
|
|
307
|
+
// *-Period buckets covering only local days >= periodStartMs. The all-time
|
|
308
|
+
// buckets (perDay/perModel/perSession) are unaffected, so one scan serves both
|
|
309
|
+
// the trend (lifetime) and the report (period) views. Period buckets group
|
|
310
|
+
// message tokens by the MESSAGE's own model/agent, and spread session residual
|
|
311
|
+
// by the session's model/agent — so per-model report rows sum exactly to the
|
|
312
|
+
// period totals (self-consistent by construction).
|
|
313
|
+
function attributeUsage(startMs, endMs, periodStartMs) {
|
|
314
|
+
const periodOn = periodStartMs != null;
|
|
315
|
+
const inPeriod = periodOn ? (key) => dateOfKey(key).getTime() >= periodStartMs : () => false;
|
|
305
316
|
const perDay = {};
|
|
306
317
|
const perModel = {};
|
|
307
318
|
const perAgent = {};
|
|
308
319
|
const perSession = {};
|
|
320
|
+
const perModelPeriod = {};
|
|
321
|
+
const perAgentPeriod = {};
|
|
322
|
+
const perAgentModelPeriod = {};
|
|
323
|
+
const perSessionPeriod = {};
|
|
324
|
+
const perSessionModelPeriod = {};
|
|
309
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 });
|
|
310
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 });
|
|
311
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
|
+
};
|
|
312
341
|
|
|
313
342
|
// 1. messages in period (exact timing)
|
|
314
343
|
const msgTok = {};
|
|
@@ -342,6 +371,28 @@ function attributeUsage(startMs, endMs) {
|
|
|
342
371
|
w.total += vol;
|
|
343
372
|
w.perDay[key] = (w.perDay[key] || 0) + vol;
|
|
344
373
|
}
|
|
374
|
+
// Period slice: message tokens under the MESSAGE's own model/agent.
|
|
375
|
+
if (periodOn && inPeriod(key)) {
|
|
376
|
+
const mName = modelNameOf(r.provider, r.model);
|
|
377
|
+
const aName = r.agent || 'unknown';
|
|
378
|
+
const MP = ensureModelP(mName);
|
|
379
|
+
MP.messages++;
|
|
380
|
+
if (r.sid) MP.sessions.add(r.sid);
|
|
381
|
+
MP.input += iv; MP.output += ov; MP.reasoning += rv; MP.cacheRead += crv; MP.cacheWrite += cwv; MP.cost += cv;
|
|
382
|
+
if (ov > 0 && t1 > t0) { MP.speedOut += ov; MP.speedMs += (t1 - t0); }
|
|
383
|
+
const AP = ensureAgentP(aName);
|
|
384
|
+
if (r.sid) AP.sessions.add(r.sid);
|
|
385
|
+
AP.input += iv; AP.output += ov; AP.reasoning += rv; AP.cacheRead += crv; AP.cacheWrite += cwv; AP.cost += cv;
|
|
386
|
+
if (ov > 0 && t1 > t0) { AP.speedOut += ov; AP.speedMs += (t1 - t0); }
|
|
387
|
+
const AM = ensureAgentModelP(aName, mName);
|
|
388
|
+
AM.input += iv; AM.output += ov; AM.reasoning += rv; AM.cacheRead += crv; AM.cacheWrite += cwv; AM.cost += cv;
|
|
389
|
+
if (r.sid) {
|
|
390
|
+
const SP = ensureSessP(r.sid);
|
|
391
|
+
SP.input += iv; SP.output += ov; SP.reasoning += rv; SP.cacheRead += crv; SP.cacheWrite += cwv; SP.cost += cv;
|
|
392
|
+
const SM = ensureSessModelP(r.sid, mName);
|
|
393
|
+
SM.input += iv; SM.output += ov; SM.reasoning += rv; SM.cacheRead += crv; SM.cacheWrite += cwv; SM.cost += cv;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
345
396
|
}
|
|
346
397
|
|
|
347
398
|
// 2. sessions intersecting the period: spread residual
|
|
@@ -387,6 +438,21 @@ function attributeUsage(startMs, endMs) {
|
|
|
387
438
|
const A = ensureAgent(aName);
|
|
388
439
|
A.input += di; A.output += dout; A.reasoning += dr; A.cacheRead += dcr; A.cacheWrite += dcw; A.cost += dc;
|
|
389
440
|
ps.input += di; ps.output += dout; ps.reasoning += dr; ps.cacheRead += dcr; ps.cacheWrite += dcw; ps.cost += dc;
|
|
441
|
+
// Period slice: residual shares land under the SESSION's model/agent
|
|
442
|
+
// (no per-message model exists for residual), but only on days inside
|
|
443
|
+
// the period, so period rows sum exactly to the period totals.
|
|
444
|
+
if (periodOn && inPeriod(k)) {
|
|
445
|
+
const MP = ensureModelP(mName);
|
|
446
|
+
MP.input += di; MP.output += dout; MP.reasoning += dr; MP.cacheRead += dcr; MP.cacheWrite += dcw; MP.cost += dc;
|
|
447
|
+
const AP = ensureAgentP(aName);
|
|
448
|
+
AP.input += di; AP.output += dout; AP.reasoning += dr; AP.cacheRead += dcr; AP.cacheWrite += dcw; AP.cost += dc;
|
|
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;
|
|
455
|
+
}
|
|
390
456
|
}
|
|
391
457
|
}
|
|
392
458
|
|
|
@@ -397,7 +463,11 @@ function attributeUsage(startMs, endMs) {
|
|
|
397
463
|
totals.input += D.input; totals.output += D.output; totals.reasoning += D.reasoning;
|
|
398
464
|
totals.cacheRead += D.cacheRead; totals.cacheWrite += D.cacheWrite; totals.cost += D.cost;
|
|
399
465
|
}
|
|
400
|
-
return {
|
|
466
|
+
return {
|
|
467
|
+
perDay, perModel, perAgent, perSession, totals,
|
|
468
|
+
perModelPeriod, perAgentPeriod, perAgentModelPeriod, perSessionPeriod, perSessionModelPeriod,
|
|
469
|
+
periodStartMs,
|
|
470
|
+
};
|
|
401
471
|
}
|
|
402
472
|
|
|
403
473
|
// All-time attribution, memoized 300s (expensive full DB scan; avoids
|
|
@@ -409,11 +479,29 @@ let toolsCache = null;
|
|
|
409
479
|
function getAttrAll() {
|
|
410
480
|
const now = Date.now();
|
|
411
481
|
if (attrAllCache && now - attrAllCache.at < 300000) return attrAllCache.a;
|
|
412
|
-
|
|
482
|
+
// periodStartMs = 0: the *Period buckets equal the all-time ones, so the
|
|
483
|
+
// All report can read them (single scan serves both views).
|
|
484
|
+
const a = attributeUsage(0, now, 0);
|
|
413
485
|
attrAllCache = { at: now, a };
|
|
414
486
|
return a;
|
|
415
487
|
}
|
|
416
488
|
|
|
489
|
+
// Period-scoped attribution (same 300s TTL, one cache slot per period start).
|
|
490
|
+
// Report panels slice this instead of the all-time buckets so every row and
|
|
491
|
+
// the summary total describe the SAME period.
|
|
492
|
+
const attrPeriodCache = new Map();
|
|
493
|
+
function getAttrPeriod(startMs) {
|
|
494
|
+
const now = Date.now();
|
|
495
|
+
const hit = attrPeriodCache.get(startMs);
|
|
496
|
+
if (hit && now - hit.at < 300000) return hit.a;
|
|
497
|
+
const a = attributeUsage(0, now, startMs);
|
|
498
|
+
attrPeriodCache.set(startMs, { at: now, a });
|
|
499
|
+
if (attrPeriodCache.size > 6) {
|
|
500
|
+
for (const [k, v] of attrPeriodCache) if (now - v.at >= 300000) attrPeriodCache.delete(k);
|
|
501
|
+
}
|
|
502
|
+
return a;
|
|
503
|
+
}
|
|
504
|
+
|
|
417
505
|
function computeMedian(arr) {
|
|
418
506
|
if (!arr.length) return 0;
|
|
419
507
|
const sorted = arr.slice().sort((a, b) => a - b);
|
|
@@ -431,11 +519,7 @@ function getStatsFromDb(days) {
|
|
|
431
519
|
// NOTE: days is only ever 0 here (overview totals); per-period stats are
|
|
432
520
|
// built by buildReportFromDb via attributeUsage. Local-day count so the
|
|
433
521
|
// 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};`);
|
|
522
|
+
|
|
439
523
|
|
|
440
524
|
// V2: tool parts are embedded in session_message content (part table froze
|
|
441
525
|
// at the upgrade and its migrated rows were rebuilt into content, so
|
|
@@ -460,24 +544,37 @@ function getStatsFromDb(days) {
|
|
|
460
544
|
.map(([name, count]) => ({ name, count, pct: Math.round((count / totalToolUse) * 1000) / 10 }))
|
|
461
545
|
.sort((a, b) => b.count - a.count);
|
|
462
546
|
|
|
463
|
-
const
|
|
464
|
-
const
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
547
|
+
const attr = getAttrAll();
|
|
548
|
+
const T = attr.totals;
|
|
549
|
+
// Overview = ALL TIME and uses the SAME attribution as the trend chart and
|
|
550
|
+
// Report(All), so the three panels cannot disagree. Per-message tokens are
|
|
551
|
+
// authoritative: a session whose message sums exceed its session-table
|
|
552
|
+
// counters (V2 migration artifact) keeps the measured message values
|
|
553
|
+
// instead of being clamped down to the session counters.
|
|
554
|
+
const sessions = T.sessions;
|
|
555
|
+
const messages = T.messages;
|
|
556
|
+
// Active days = day buckets that actually carry usage. Excludes pre-2000
|
|
557
|
+
// epoch artifacts (imported rows with time_created = 0).
|
|
558
|
+
const dayKeys = Object.keys(attr.perDay).filter((k) => attr.perDay[k].date.getFullYear() >= 2020);
|
|
559
|
+
const activeDays = dayKeys.length || 1;
|
|
560
|
+
const sessVals = Object.values(attr.perSession)
|
|
561
|
+
.filter((s) => s.input > 0 || s.output > 0 || s.reasoning > 0)
|
|
562
|
+
.map((s) => s.input + s.output + s.reasoning)
|
|
563
|
+
.filter(Number.isFinite);
|
|
564
|
+
const avgTokens = sessVals.length ? sessVals.reduce((s, v) => s + v, 0) / sessVals.length : 0;
|
|
565
|
+
const medianTokens = computeMedian(sessVals);
|
|
566
|
+
const avgDayCost = T.cost ? T.cost / activeDays : 0;
|
|
470
567
|
|
|
471
568
|
// Per-model usage from hybrid attribution (message counts are TRUE message
|
|
472
569
|
// counts here, not session counts; token/cost sums include residuals so
|
|
473
570
|
// pruned history isn't lost).
|
|
474
|
-
const attr = getAttrAll();
|
|
475
571
|
const models = Object.entries(attr.perModel)
|
|
476
572
|
.map(([name, m]) => ({
|
|
477
573
|
name,
|
|
478
574
|
messages: m.messages,
|
|
479
575
|
input: Math.round(m.input),
|
|
480
576
|
output: Math.round(m.output),
|
|
577
|
+
reasoning: Math.round(m.reasoning),
|
|
481
578
|
cacheRead: Math.round(m.cacheRead),
|
|
482
579
|
cacheWrite: Math.round(m.cacheWrite),
|
|
483
580
|
cost: m.cost,
|
|
@@ -485,47 +582,53 @@ function getStatsFromDb(days) {
|
|
|
485
582
|
}))
|
|
486
583
|
.sort((a, b) => b.cost - a.cost);
|
|
487
584
|
|
|
488
|
-
// Savings estimate: market value of all-time usage at catalog paid rates
|
|
489
|
-
//
|
|
490
|
-
//
|
|
491
|
-
//
|
|
585
|
+
// 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
|
|
588
|
+
// price are EXCLUDED and disclosed (unpricedTokens/unpricedRows) instead of
|
|
589
|
+
// being valued at a made-up rate; proxyShare is how much of the priced
|
|
590
|
+
// total comes from cross-provider estimates.
|
|
492
591
|
let marketTotal = null, savedTotal = null, priceAsOf = null;
|
|
592
|
+
let unpricedRows = 0, unpricedTokens = 0, proxyMarket = 0;
|
|
493
593
|
{
|
|
494
594
|
const info = pricing.catalogInfo();
|
|
495
595
|
if (info.ok) {
|
|
496
596
|
priceAsOf = new Date(info.mtimeMs).toISOString();
|
|
497
597
|
marketTotal = 0;
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
const
|
|
501
|
-
|
|
598
|
+
for (const [name, m] of Object.entries(attr.perModel)) {
|
|
599
|
+
const { provider, model } = splitModelName(name);
|
|
600
|
+
const tok = { input: m.input, output: m.output, reasoning: m.reasoning, cacheRead: m.cacheRead, cost: m.cost };
|
|
601
|
+
const mk = marketOf(tok, provider, model);
|
|
602
|
+
if (!mk.priced) {
|
|
603
|
+
unpricedRows++;
|
|
604
|
+
unpricedTokens += tok.input + tok.output + tok.reasoning + tok.cacheRead;
|
|
605
|
+
continue;
|
|
606
|
+
}
|
|
502
607
|
marketTotal += mk.market;
|
|
608
|
+
if (mk.kind === 'proxy') proxyMarket += mk.market;
|
|
503
609
|
}
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
} else { savedTotal = null; }
|
|
610
|
+
marketTotal = Math.round(marketTotal * 10000) / 10000;
|
|
611
|
+
savedTotal = Math.round((marketTotal - T.cost) * 10000) / 10000;
|
|
612
|
+
proxyMarket = Math.round(proxyMarket * 10000) / 10000;
|
|
508
613
|
}
|
|
509
614
|
}
|
|
510
615
|
|
|
511
616
|
return {
|
|
512
617
|
ok: true,
|
|
513
|
-
overview: {
|
|
514
|
-
sessions: sessions,
|
|
515
|
-
messages: msgCount ? (msgCount.messages || 0) : 0,
|
|
516
|
-
days: activeDays,
|
|
517
|
-
},
|
|
618
|
+
overview: { sessions, messages, days: activeDays },
|
|
518
619
|
cost: {
|
|
519
|
-
total:
|
|
620
|
+
total: T.cost,
|
|
520
621
|
avgDay: avgDayCost,
|
|
521
622
|
avgTokensSession: Math.round(avgTokens),
|
|
522
623
|
medianTokensSession: Math.round(medianTokens),
|
|
523
|
-
input:
|
|
524
|
-
output:
|
|
525
|
-
reasoning:
|
|
526
|
-
cacheRead:
|
|
527
|
-
cacheWrite:
|
|
624
|
+
input: Math.round(T.input),
|
|
625
|
+
output: Math.round(T.output),
|
|
626
|
+
reasoning: Math.round(T.reasoning),
|
|
627
|
+
cacheRead: Math.round(T.cacheRead),
|
|
628
|
+
cacheWrite: Math.round(T.cacheWrite),
|
|
528
629
|
marketTotal, savedTotal, priceAsOf,
|
|
630
|
+
unpricedRows, unpricedTokens, proxyMarket,
|
|
631
|
+
proxyShare: marketTotal > 0 ? Math.round((proxyMarket / marketTotal) * 1000) / 10 : null,
|
|
529
632
|
},
|
|
530
633
|
tools,
|
|
531
634
|
models,
|
|
@@ -660,19 +763,33 @@ function buildReportFromDb(days) {
|
|
|
660
763
|
const startMs = periodStartMs(days, now);
|
|
661
764
|
const label = days === -1 ? 'All' : days <= 1 ? 'Daily' : days <= 7 ? 'Weekly' : 'Monthly';
|
|
662
765
|
|
|
663
|
-
//
|
|
664
|
-
//
|
|
665
|
-
//
|
|
666
|
-
// trend chart
|
|
667
|
-
const a = getAttrAll();
|
|
668
|
-
const aNow = attrAllCache.at; //
|
|
766
|
+
// Period-scoped attribution: every number below (summary, providers, agents,
|
|
767
|
+
// sessions, market/saved) is sliced to THIS period, so the tables sum to the
|
|
768
|
+
// card. The all-time buckets (perDay) are still used for the summary totals
|
|
769
|
+
// and stay identical to the trend chart for the same period.
|
|
770
|
+
const a = days === -1 ? getAttrAll() : getAttrPeriod(startMs);
|
|
771
|
+
const aNow = days === -1 ? attrAllCache.at : attrPeriodCache.get(startMs).at; // snapshot time of `a`
|
|
669
772
|
// Message-level stats per session within the period (period speed + active
|
|
670
773
|
// time). One GROUP BY over the merged message view, mapped onto the same
|
|
671
774
|
// session-meta buckets as tokens so row sets stay identical.
|
|
775
|
+
// Wall time must come from the MESSAGE clock, not session.time_updated:
|
|
776
|
+
// subagent/fork sessions are written with time_updated == time_created
|
|
777
|
+
// (same millisecond), which would report ~0 wall for hours of real work.
|
|
778
|
+
// Query the merged message view for the period span per session.
|
|
779
|
+
const wallMs = {};
|
|
780
|
+
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`) || [])) {
|
|
781
|
+
wallMs[m.sid] = Math.max(0, (+m.t1 || 0) - (+m.t0 || 0));
|
|
782
|
+
}
|
|
672
783
|
const msgAgg = {};
|
|
673
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`) || [])) {
|
|
674
785
|
msgAgg[m.sid] = m;
|
|
675
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 };
|
|
792
|
+
}
|
|
676
793
|
const periodDays = {};
|
|
677
794
|
for (const [key, val] of Object.entries(a.perDay)) {
|
|
678
795
|
const dayMs = val.date.getTime();
|
|
@@ -689,12 +806,11 @@ function buildReportFromDb(days) {
|
|
|
689
806
|
}
|
|
690
807
|
const t = periodTotals;
|
|
691
808
|
const activeDays = pdVals.length || 1;
|
|
692
|
-
// Avg/median over the PERIOD's token-bearing sessions
|
|
693
|
-
//
|
|
694
|
-
// Weekly reports differ.
|
|
809
|
+
// Avg/median over the PERIOD's token-bearing sessions — period buckets, so
|
|
810
|
+
// Daily/Weekly differ and the value matches the card and the tables.
|
|
695
811
|
const periodSessionIds = [...periodTotals.sessions];
|
|
696
812
|
const sessVals = periodSessionIds
|
|
697
|
-
.map((sid) => a.perSession[sid])
|
|
813
|
+
.map((sid) => (a.perSessionPeriod || a.perSession)[sid])
|
|
698
814
|
.filter((s) => s && (s.input > 0 || s.output > 0 || s.reasoning > 0))
|
|
699
815
|
.map((s) => s.input + s.output + s.reasoning)
|
|
700
816
|
.filter(Number.isFinite);
|
|
@@ -723,73 +839,91 @@ function buildReportFromDb(days) {
|
|
|
723
839
|
const metaMap = {};
|
|
724
840
|
for (const s of sessMeta) metaMap[s.id] = s;
|
|
725
841
|
|
|
726
|
-
const agentAgg = {};
|
|
727
|
-
const modelAgg = {};
|
|
728
842
|
const sessRows = [];
|
|
729
843
|
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;
|
|
844
|
+
const meta = metaMap[sid] || { agent: 'unknown', provider: 'unknown', model: 'unknown', tc: 0, tu: 0 };
|
|
740
845
|
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 });
|
|
846
|
+
const sm = (a.perSessionModelPeriod && a.perSessionModelPeriod[sid]) || null;
|
|
847
|
+
sessRows.push({ sid, meta, ps: a.perSessionPeriod ? a.perSessionPeriod[sid] : a.perSession[sid], mg, sm });
|
|
752
848
|
}
|
|
753
849
|
|
|
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)
|
|
850
|
+
// Providers/agents come straight from the period buckets (message tokens
|
|
851
|
+
// under the message's own model; residual under the session's), so their
|
|
852
|
+
// columns sum EXACTLY to the summary card by construction.
|
|
853
|
+
var pProviderRows = Object.entries(a.perModelPeriod)
|
|
765
854
|
.map(([name, m]) => {
|
|
766
855
|
const { provider, model } = splitModelName(name);
|
|
767
856
|
const mk = marketOf({ input: m.input, output: m.output, reasoning: m.reasoning, cacheRead: m.cacheRead, cost: m.cost }, provider, model);
|
|
768
857
|
return {
|
|
769
|
-
provider, model, sessions: m.sessions.size, cost: r4(m.cost),
|
|
858
|
+
provider, model, sessions: m.sessions.size, messages: m.messages, cost: r4(m.cost),
|
|
770
859
|
tok_in: Math.round(m.input), tok_out: Math.round(m.output),
|
|
771
860
|
tok_reasoning: Math.round(m.reasoning), cache_read: Math.round(m.cacheRead),
|
|
772
861
|
speed: m.speedMs > 0 ? Math.round((m.speedOut / (m.speedMs / 1000)) * 10) / 10 : null,
|
|
773
|
-
market: mk.market, saved: mk.saved, pricedAs: mk.pricedAs,
|
|
862
|
+
market: mk.market, saved: mk.saved, pricedAs: mk.pricedAs, priced: mk.priced, kind: mk.kind,
|
|
863
|
+
};
|
|
864
|
+
})
|
|
865
|
+
.sort((x, y) => y.cost - x.cost);
|
|
866
|
+
|
|
867
|
+
var pAgentRows = Object.entries(a.perAgentPeriod)
|
|
868
|
+
.map(([agent, m]) => {
|
|
869
|
+
let market = 0, saved = 0, pricedAny = false, unpriced = 0, proxy = 0;
|
|
870
|
+
const bag = (a.perAgentModelPeriod && a.perAgentModelPeriod[agent]) || {};
|
|
871
|
+
for (const [name, b] of Object.entries(bag)) {
|
|
872
|
+
const { provider, model } = splitModelName(name);
|
|
873
|
+
const mk = marketOf({ input: b.input, output: b.output, reasoning: b.reasoning, cacheRead: b.cacheRead, cost: b.cost }, provider, model);
|
|
874
|
+
if (!mk.priced) { unpriced++; continue; }
|
|
875
|
+
market += mk.market; saved += mk.saved; pricedAny = true;
|
|
876
|
+
if (mk.kind === 'proxy') proxy += mk.market;
|
|
877
|
+
}
|
|
878
|
+
// Wall = period span measured on the message clock (see wallMs above).
|
|
879
|
+
let agentWall = 0;
|
|
880
|
+
for (const sid of m.sessions) agentWall += wallMs[sid] || 0;
|
|
881
|
+
return {
|
|
882
|
+
agent, sessions: m.sessions.size, cost: r4(m.cost),
|
|
883
|
+
tok_in: Math.round(m.input), tok_out: Math.round(m.output),
|
|
884
|
+
tok_reasoning: Math.round(m.reasoning), cache_read: Math.round(m.cacheRead),
|
|
885
|
+
speed: msgAgentAgg[agent] && msgAgentAgg[agent].ms > 0 ? Math.round((msgAgentAgg[agent].o / (msgAgentAgg[agent].ms / 1000)) * 10) / 10 : null,
|
|
886
|
+
wallMs: Math.round(agentWall),
|
|
887
|
+
activeMs: msgAgentAgg[agent] ? Math.round(msgAgentAgg[agent].ms) : 0,
|
|
888
|
+
market: pricedAny ? Math.round(market * 10000) / 10000 : null,
|
|
889
|
+
saved: pricedAny ? Math.round(saved * 10000) / 10000 : null,
|
|
890
|
+
pricedAs: pricedAny ? (proxy > 0 && proxy >= market - 0.01 ? 'mixed' : 'exact') : null,
|
|
891
|
+
priced: pricedAny, kind: !pricedAny ? 'unpriced' : (unpriced > 0 ? 'partial' : (proxy > 0 ? 'proxy' : 'exact')),
|
|
774
892
|
};
|
|
775
893
|
})
|
|
776
894
|
.sort((x, y) => y.cost - x.cost);
|
|
777
895
|
var pSessionRows = sessRows
|
|
778
|
-
.map(({ sid, meta, ps, mg }) => {
|
|
779
|
-
|
|
896
|
+
.map(({ sid, meta, ps, mg, sm }) => {
|
|
897
|
+
// Price by the session's own period model mix when available
|
|
898
|
+
// (message tokens under the message's model), else the session's meta
|
|
899
|
+
// model (residual-only sessions).
|
|
900
|
+
let market = null, saved = null, pricedAs = null, prov = meta.provider || 'unknown', mod = meta.model || 'unknown';
|
|
901
|
+
const bag = sm || null;
|
|
902
|
+
if (bag && Object.keys(bag).length) {
|
|
903
|
+
const name = Object.keys(bag).sort((a, b) => {
|
|
904
|
+
const va = bag[a].input + bag[a].output + bag[a].cacheRead;
|
|
905
|
+
const vb = bag[b].input + bag[b].output + bag[b].cacheRead;
|
|
906
|
+
return vb - va;
|
|
907
|
+
})[0];
|
|
908
|
+
const sp = splitModelName(name);
|
|
909
|
+
prov = sp.provider; mod = sp.model;
|
|
910
|
+
}
|
|
911
|
+
const mkS = marketOf({ input: ps.input, output: ps.output, reasoning: mg.rq || 0, cacheRead: ps.cacheRead, cost: ps.cost }, prov, mod);
|
|
912
|
+
market = mkS.market; saved = mkS.saved; pricedAs = mkS.pricedAs;
|
|
913
|
+
// Wall from the message clock (see wallMs above).
|
|
780
914
|
return {
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
915
|
+
id: sid, title: (meta.title || '').slice(0, 40), agent: meta.agent || 'unknown',
|
|
916
|
+
provider: prov, model: mod,
|
|
917
|
+
wallMs: wallMs[sid] || 0,
|
|
918
|
+
activeMs: mg.ms || 0, messages: mg.n || 0,
|
|
919
|
+
tok_in: Math.round(ps.input), tok_out: Math.round(ps.output),
|
|
920
|
+
tok_reasoning: Math.round(mg.rq || 0),
|
|
921
|
+
cost: r4(ps.cost),
|
|
922
|
+
speed: (mg.ms || 0) > 0 ? Math.round(((mg.o || 0) / (mg.ms / 1000)) * 10) / 10 : null,
|
|
923
|
+
market, saved, pricedAs, priced: mkS.priced, kind: mkS.kind,
|
|
790
924
|
};
|
|
791
925
|
})
|
|
792
|
-
.sort((x, y) => y.
|
|
926
|
+
.sort((x, y) => y.activeMs - x.activeMs)
|
|
793
927
|
.slice(0, 20);
|
|
794
928
|
} else {
|
|
795
929
|
var pAgentRows = [];
|
|
@@ -797,11 +931,19 @@ function buildReportFromDb(days) {
|
|
|
797
931
|
var pSessionRows = [];
|
|
798
932
|
}
|
|
799
933
|
|
|
934
|
+
// Period market = Σ priced provider rows (already period-scoped); saved = Σ
|
|
935
|
+
// provider saved so it can never mix a period cost with a lifetime market.
|
|
936
|
+
// Unpriced rows are disclosed, not valued.
|
|
800
937
|
const sumMkt = (rows) => rows.reduce((s, r) => s + (r.market || 0), 0);
|
|
938
|
+
const sumSaved = (rows) => rows.reduce((s, r) => s + (r.saved || 0), 0);
|
|
801
939
|
statsR.cost.marketTotal = Math.round(sumMkt(pProviderRows) * 10000) / 10000;
|
|
802
|
-
statsR.cost.savedTotal = Math.round((
|
|
940
|
+
statsR.cost.savedTotal = Math.round(sumSaved(pProviderRows) * 10000) / 10000;
|
|
803
941
|
statsR.cost.savedPct = statsR.cost.marketTotal > 0 ? Math.round((statsR.cost.savedTotal / statsR.cost.marketTotal) * 1000) / 10 : null;
|
|
804
942
|
statsR.cost.priceAsOf = pricing.catalogInfo().ok ? new Date(pricing.catalogInfo().mtimeMs).toISOString() : null;
|
|
943
|
+
statsR.cost.unpricedRows = pProviderRows.filter((r) => !r.priced).length;
|
|
944
|
+
statsR.cost.unpricedTokens = pProviderRows.filter((r) => !r.priced).reduce((s, r) => s + r.tok_in + r.tok_out + r.tok_reasoning + r.cache_read, 0);
|
|
945
|
+
const proxyMkt = pProviderRows.filter((r) => r.kind === 'proxy').reduce((s, r) => s + (r.market || 0), 0);
|
|
946
|
+
statsR.cost.proxyShare = statsR.cost.marketTotal > 0 ? Math.round((proxyMkt / statsR.cost.marketTotal) * 1000) / 10 : null;
|
|
805
947
|
|
|
806
948
|
return {
|
|
807
949
|
label,
|
|
@@ -822,13 +964,16 @@ function refreshReport(days) {
|
|
|
822
964
|
if (fresh) return { report: hit, ready: true };
|
|
823
965
|
if (!reportBusy[key]) {
|
|
824
966
|
reportBusy[key] = true;
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
967
|
+
setImmediate(() => {
|
|
968
|
+
try {
|
|
969
|
+
const r = buildReportFromDb(days);
|
|
970
|
+
if (r && r.stats && r.stats.ok) {
|
|
971
|
+
reportCache[key] = r;
|
|
972
|
+
}
|
|
973
|
+
} catch (_) {} finally {
|
|
974
|
+
delete reportBusy[key];
|
|
829
975
|
}
|
|
830
|
-
}
|
|
831
|
-
delete reportBusy[key];
|
|
976
|
+
});
|
|
832
977
|
}
|
|
833
978
|
return hit ? { report: Object.assign({}, hit, { stale: true }), ready: true } : { report: null, ready: false };
|
|
834
979
|
}
|
|
@@ -949,6 +1094,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
949
1094
|
return;
|
|
950
1095
|
}
|
|
951
1096
|
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
1097
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
952
1098
|
res.end(data.replace('__VERSION__', VERSION));
|
|
953
1099
|
});
|
|
954
1100
|
} else {
|