opencode-usage-insights 0.1.1 → 0.1.3
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/README.md +204 -67
- package/dist/core.d.ts +19 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +558 -154
- package/dist/index.js.map +9 -8
- package/dist/line.d.ts +15 -5
- package/dist/panel-build.d.ts +2 -0
- package/dist/panel-data.d.ts +15 -6
- package/dist/panel.d.ts +8 -0
- package/dist/pricing.d.ts +72 -0
- package/dist/recorder.d.ts +10 -0
- package/dist/stats/aggregates.d.ts +14 -3
- package/dist/stats/db.d.ts +34 -3
- package/dist/stats/maintenance.d.ts +19 -0
- package/dist/stats/queries.d.ts +50 -5
- package/dist/tui.d.ts +7 -1
- package/dist/tui.js +924 -278
- package/dist/tui.js.map +15 -14
- package/package.json +5 -3
package/dist/tui.js
CHANGED
|
@@ -31,18 +31,27 @@ function transcriptTail(messages, count) {
|
|
|
31
31
|
segments.unshift({ assistants: current, prompt: undefined });
|
|
32
32
|
return segments;
|
|
33
33
|
}
|
|
34
|
+
function countOf(value) {
|
|
35
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
|
|
36
|
+
}
|
|
37
|
+
function amountOf(value) {
|
|
38
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
|
|
39
|
+
}
|
|
40
|
+
function stampOf(value) {
|
|
41
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
42
|
+
}
|
|
34
43
|
function tokenCounts(message) {
|
|
35
44
|
const tokens = message.tokens;
|
|
36
45
|
return {
|
|
37
|
-
input: tokens?.input
|
|
38
|
-
output: tokens?.output
|
|
39
|
-
reasoning: tokens?.reasoning
|
|
40
|
-
read: tokens?.cache?.read
|
|
41
|
-
write: tokens?.cache?.write
|
|
46
|
+
input: countOf(tokens?.input),
|
|
47
|
+
output: countOf(tokens?.output),
|
|
48
|
+
reasoning: countOf(tokens?.reasoning),
|
|
49
|
+
read: countOf(tokens?.cache?.read),
|
|
50
|
+
write: countOf(tokens?.cache?.write)
|
|
42
51
|
};
|
|
43
52
|
}
|
|
44
53
|
function totalize(steps) {
|
|
45
|
-
const totals = { input: 0, cached: 0, output: 0, reasoning: 0, cacheWrite: 0, cost: 0, steps: steps.length };
|
|
54
|
+
const totals = { input: 0, cached: 0, output: 0, reasoning: 0, cacheWrite: 0, cost: 0, listCost: 0, steps: steps.length };
|
|
46
55
|
for (const step of steps) {
|
|
47
56
|
const counts = tokenCounts(step);
|
|
48
57
|
totals.input += counts.input;
|
|
@@ -50,7 +59,8 @@ function totalize(steps) {
|
|
|
50
59
|
totals.output += counts.output;
|
|
51
60
|
totals.reasoning += counts.reasoning;
|
|
52
61
|
totals.cacheWrite += counts.write;
|
|
53
|
-
totals.cost += step.cost
|
|
62
|
+
totals.cost += amountOf(step.cost);
|
|
63
|
+
totals.listCost += amountOf(step.listCost);
|
|
54
64
|
}
|
|
55
65
|
return totals;
|
|
56
66
|
}
|
|
@@ -60,16 +70,16 @@ function identityKey(model) {
|
|
|
60
70
|
return `${model.providerID}/${model.id}${model.variant ? `#${model.variant}` : ""}`;
|
|
61
71
|
}
|
|
62
72
|
function cacheRead(message) {
|
|
63
|
-
return message?.tokens?.cache?.read
|
|
73
|
+
return countOf(message?.tokens?.cache?.read);
|
|
64
74
|
}
|
|
65
75
|
function stepCreated(message) {
|
|
66
|
-
return message?.time?.created;
|
|
76
|
+
return stampOf(message?.time?.created);
|
|
67
77
|
}
|
|
68
78
|
function stepEnd(message) {
|
|
69
79
|
const time = message?.time;
|
|
70
80
|
if (!time)
|
|
71
81
|
return;
|
|
72
|
-
return time.completed ?? time.streamed ?? time.created;
|
|
82
|
+
return stampOf(time.completed) ?? stampOf(time.streamed) ?? stampOf(time.created);
|
|
73
83
|
}
|
|
74
84
|
function cacheDrop(reference, current, scope = "provider") {
|
|
75
85
|
if (!reference)
|
|
@@ -96,9 +106,9 @@ function stepGap(reference, current) {
|
|
|
96
106
|
return Math.max(0, started - ended);
|
|
97
107
|
}
|
|
98
108
|
function tokensPerSecond(produced, from, to) {
|
|
99
|
-
if (from === undefined || to === undefined || to <= from)
|
|
109
|
+
if (from === undefined || to === undefined || !Number.isFinite(from) || !Number.isFinite(to) || to <= from)
|
|
100
110
|
return;
|
|
101
|
-
if (produced <= 0)
|
|
111
|
+
if (!Number.isFinite(produced) || produced <= 0)
|
|
102
112
|
return;
|
|
103
113
|
return produced / (to - from) * 1000;
|
|
104
114
|
}
|
|
@@ -142,7 +152,7 @@ function computeTurn(messages, session) {
|
|
|
142
152
|
return {
|
|
143
153
|
endAt: stepEnd(lastStep),
|
|
144
154
|
startAt: stepCreated(settled[0] ?? lastStep),
|
|
145
|
-
promptAt: last.prompt?.time?.created,
|
|
155
|
+
promptAt: stampOf(last.prompt?.time?.created),
|
|
146
156
|
promptGapMs: promptGap(last.prompt, previous?.prompt),
|
|
147
157
|
providerID: provider,
|
|
148
158
|
modelID: lastStep.model?.id,
|
|
@@ -159,8 +169,8 @@ function computeTurn(messages, session) {
|
|
|
159
169
|
};
|
|
160
170
|
}
|
|
161
171
|
function promptGap(current, previous) {
|
|
162
|
-
const now = current?.time?.created;
|
|
163
|
-
const before = previous?.time?.created;
|
|
172
|
+
const now = stampOf(current?.time?.created);
|
|
173
|
+
const before = stampOf(previous?.time?.created);
|
|
164
174
|
if (now === undefined || before === undefined)
|
|
165
175
|
return;
|
|
166
176
|
return Math.max(0, now - before);
|
|
@@ -181,6 +191,7 @@ var DEFAULT_LABELS = {
|
|
|
181
191
|
output: "out",
|
|
182
192
|
reasoning: "reason",
|
|
183
193
|
cost: "cost",
|
|
194
|
+
estimate: "\u2248",
|
|
184
195
|
cacheExpired: "cache expired",
|
|
185
196
|
providerChanged: "changed",
|
|
186
197
|
modelChanged: "model changed"
|
|
@@ -197,11 +208,15 @@ var DEFAULT_FIELDS = {
|
|
|
197
208
|
cacheExpiry: true
|
|
198
209
|
};
|
|
199
210
|
function formatClock(ms) {
|
|
211
|
+
if (!Number.isFinite(ms))
|
|
212
|
+
return "--:--";
|
|
200
213
|
const date = new Date(ms);
|
|
201
214
|
const pad = (value) => String(value).padStart(2, "0");
|
|
202
215
|
return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
|
203
216
|
}
|
|
204
217
|
function formatDuration(ms) {
|
|
218
|
+
if (!Number.isFinite(ms))
|
|
219
|
+
return "\u2013";
|
|
205
220
|
const totalSeconds = Math.max(0, Math.floor(ms / 1000));
|
|
206
221
|
const seconds = totalSeconds % 60;
|
|
207
222
|
const minutes = Math.floor(totalSeconds / 60) % 60;
|
|
@@ -216,7 +231,7 @@ function formatDuration(ms) {
|
|
|
216
231
|
return `${seconds}s`;
|
|
217
232
|
}
|
|
218
233
|
function formatTokens(value) {
|
|
219
|
-
const n = Math.max(0, Math.round(value));
|
|
234
|
+
const n = Number.isFinite(value) ? Math.max(0, Math.round(value)) : 0;
|
|
220
235
|
if (n < 1000)
|
|
221
236
|
return String(n);
|
|
222
237
|
if (n < 999500) {
|
|
@@ -233,12 +248,28 @@ function trimZeros(value) {
|
|
|
233
248
|
return value.includes(".") ? value.replace(/0+$/, "").replace(/\.$/, "") : value;
|
|
234
249
|
}
|
|
235
250
|
function formatCost(value) {
|
|
236
|
-
if (value <= 0)
|
|
251
|
+
if (!Number.isFinite(value) || value <= 0)
|
|
237
252
|
return "$0";
|
|
253
|
+
if (value < 0.00005)
|
|
254
|
+
return "<$0.0001";
|
|
238
255
|
if (value < 1)
|
|
239
256
|
return `$${value.toFixed(4)}`;
|
|
240
257
|
return `$${value.toFixed(2)}`;
|
|
241
258
|
}
|
|
259
|
+
function formatMoney(charged, estimated, marker = "\u2248") {
|
|
260
|
+
const paid = Number.isFinite(charged) && charged > 0 ? formatCost(charged) : undefined;
|
|
261
|
+
const estimate = Number.isFinite(estimated) && estimated > 0 ? `${marker.trim() === "" ? "" : `${marker.trim()} `}${formatCost(estimated)}` : undefined;
|
|
262
|
+
if (paid !== undefined && estimate !== undefined)
|
|
263
|
+
return `${paid} + ${estimate}`;
|
|
264
|
+
return paid ?? estimate;
|
|
265
|
+
}
|
|
266
|
+
function formatSpend(charged, estimated, marker = "\u2248") {
|
|
267
|
+
const paid = Number.isFinite(charged) ? Math.max(0, charged) : 0;
|
|
268
|
+
const estimate = Number.isFinite(estimated) ? Math.max(0, estimated) : 0;
|
|
269
|
+
if (estimate > 0)
|
|
270
|
+
return `${marker.trim()}${formatCost(paid + estimate)}`;
|
|
271
|
+
return formatCost(paid);
|
|
272
|
+
}
|
|
242
273
|
function displayTotals(totals) {
|
|
243
274
|
const prompt = totals.input + totals.cached + totals.cacheWrite;
|
|
244
275
|
return {
|
|
@@ -248,11 +279,12 @@ function displayTotals(totals) {
|
|
|
248
279
|
output: totals.output + totals.reasoning,
|
|
249
280
|
reasoning: totals.reasoning,
|
|
250
281
|
cost: totals.cost,
|
|
282
|
+
listCost: totals.listCost,
|
|
251
283
|
steps: totals.steps,
|
|
252
284
|
prompt
|
|
253
285
|
};
|
|
254
286
|
}
|
|
255
|
-
function totalsText(prefix, totals, labels, fields, stepCount = 0, cost = totals.cost) {
|
|
287
|
+
function totalsText(prefix, totals, labels, fields, stepCount = 0, cost = totals.cost, listCost = totals.listCost, estimates = true) {
|
|
256
288
|
const display = displayTotals(totals);
|
|
257
289
|
const input = display.prompt === display.input ? `${labels.input} ${formatTokens(display.input)}` : `${labels.input} ${formatTokens(display.input)} (${formatTokens(display.prompt)})`;
|
|
258
290
|
const parts = [
|
|
@@ -262,8 +294,9 @@ function totalsText(prefix, totals, labels, fields, stepCount = 0, cost = totals
|
|
|
262
294
|
];
|
|
263
295
|
if (fields.reasoning)
|
|
264
296
|
parts.push(`${labels.reasoning} ${formatTokens(display.reasoning)}`);
|
|
265
|
-
|
|
266
|
-
|
|
297
|
+
const money = fields.cost ? formatMoney(cost, estimates ? listCost : 0, labels.estimate) : undefined;
|
|
298
|
+
if (money !== undefined)
|
|
299
|
+
parts.push(`${labels.cost} ${money}`);
|
|
267
300
|
const steps = stepCount > 1 ? `${stepCount} ${stepCount === 1 ? labels.step : labels.steps}` : "";
|
|
268
301
|
const head = [prefix, steps].filter((piece) => piece !== "").join(" ");
|
|
269
302
|
const numbers = parts.join(", ");
|
|
@@ -275,6 +308,7 @@ function formatLineSegments(stats, options) {
|
|
|
275
308
|
const labels = { ...DEFAULT_LABELS, ...options?.labels };
|
|
276
309
|
const fields = { ...DEFAULT_FIELDS, ...options?.fields };
|
|
277
310
|
const turnTotals = options?.turnTotals ?? "latest";
|
|
311
|
+
const estimates = options?.estimates !== false;
|
|
278
312
|
const segments = [];
|
|
279
313
|
if (fields.clock && stats.endAt !== undefined) {
|
|
280
314
|
segments.push({ text: formatClock(stats.endAt), tone: "muted" });
|
|
@@ -297,12 +331,15 @@ function formatLineSegments(stats, options) {
|
|
|
297
331
|
if (fields.turn && stats.totals.steps > 0) {
|
|
298
332
|
const totals = turnTotals === "sum" ? stats.totals : stats.latest;
|
|
299
333
|
segments.push({
|
|
300
|
-
text: totalsText(labels.turn, totals, labels, fields, turnTotals === "sum" ? stats.totals.steps : stats.steps, stats.totals.cost),
|
|
334
|
+
text: totalsText(labels.turn, totals, labels, fields, turnTotals === "sum" ? stats.totals.steps : stats.steps, stats.totals.cost, stats.totals.listCost, estimates),
|
|
301
335
|
tone: "base"
|
|
302
336
|
});
|
|
303
337
|
}
|
|
304
338
|
if (fields.session && stats.session) {
|
|
305
|
-
segments.push({
|
|
339
|
+
segments.push({
|
|
340
|
+
text: totalsText(labels.session, stats.session, labels, fields, 0, stats.session.cost, stats.session.listCost, estimates),
|
|
341
|
+
tone: "muted"
|
|
342
|
+
});
|
|
306
343
|
}
|
|
307
344
|
if (fields.cacheExpiry && stats.cacheExpired) {
|
|
308
345
|
const count = stats.drops.length > 1 ? `\xD7${stats.drops.length}` : "";
|
|
@@ -339,7 +376,7 @@ function isToken(value, limit = 64) {
|
|
|
339
376
|
}
|
|
340
377
|
|
|
341
378
|
// src/line.ts
|
|
342
|
-
function toTranscript(messages) {
|
|
379
|
+
function toTranscript(messages, price) {
|
|
343
380
|
const transcript = [];
|
|
344
381
|
for (const message of messages) {
|
|
345
382
|
if (typeof message.id !== "string" || typeof message.type !== "string")
|
|
@@ -348,20 +385,34 @@ function toTranscript(messages) {
|
|
|
348
385
|
transcript.push({ type: message.type, id: message.id, time: message.time });
|
|
349
386
|
continue;
|
|
350
387
|
}
|
|
388
|
+
const model = toModelRef(message.model);
|
|
389
|
+
let listCost = message.listCost;
|
|
390
|
+
if (listCost === undefined && price !== undefined && model !== undefined && (message.cost === undefined || message.cost <= 0)) {
|
|
391
|
+
const estimate = price({ providerID: model.providerID, modelID: model.id }, {
|
|
392
|
+
input: message.tokens?.input,
|
|
393
|
+
output: message.tokens?.output,
|
|
394
|
+
reasoning: message.tokens?.reasoning,
|
|
395
|
+
cacheRead: message.tokens?.cache?.read,
|
|
396
|
+
cacheWrite: message.tokens?.cache?.write
|
|
397
|
+
});
|
|
398
|
+
if (estimate !== undefined && Number.isFinite(estimate) && estimate > 0)
|
|
399
|
+
listCost = estimate;
|
|
400
|
+
}
|
|
351
401
|
transcript.push({
|
|
352
402
|
type: "assistant",
|
|
353
403
|
id: message.id,
|
|
354
404
|
time: message.time,
|
|
355
|
-
model
|
|
405
|
+
model,
|
|
356
406
|
tokens: message.tokens,
|
|
357
407
|
cost: message.cost,
|
|
408
|
+
...listCost !== undefined ? { listCost } : {},
|
|
358
409
|
finish: message.finish ?? undefined,
|
|
359
410
|
rawFinish: message.rawFinish ?? undefined
|
|
360
411
|
});
|
|
361
412
|
}
|
|
362
413
|
return transcript;
|
|
363
414
|
}
|
|
364
|
-
function toTranscriptTail(messages, segments = 2) {
|
|
415
|
+
function toTranscriptTail(messages, segments = 2, price) {
|
|
365
416
|
const wanted = Math.max(2, segments);
|
|
366
417
|
const tail = [];
|
|
367
418
|
let collected = 0;
|
|
@@ -384,7 +435,7 @@ function toTranscriptTail(messages, segments = 2) {
|
|
|
384
435
|
break;
|
|
385
436
|
}
|
|
386
437
|
tail.reverse();
|
|
387
|
-
return toTranscript(tail);
|
|
438
|
+
return toTranscript(tail, price);
|
|
388
439
|
}
|
|
389
440
|
function toModelRef(model) {
|
|
390
441
|
if (model === undefined || model.providerID === undefined || model.id === undefined)
|
|
@@ -393,17 +444,24 @@ function toModelRef(model) {
|
|
|
393
444
|
return { providerID: model.providerID, id: model.id };
|
|
394
445
|
return { providerID: model.providerID, id: model.id, variant: model.variant };
|
|
395
446
|
}
|
|
396
|
-
function
|
|
447
|
+
function countOf2(value) {
|
|
448
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
|
|
449
|
+
}
|
|
450
|
+
function amountOf2(value) {
|
|
451
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
|
|
452
|
+
}
|
|
453
|
+
function sessionTotals(info, listCost = 0) {
|
|
397
454
|
if (info === undefined)
|
|
398
455
|
return;
|
|
399
456
|
const tokens = info.tokens;
|
|
400
457
|
return {
|
|
401
|
-
input: tokens?.input
|
|
402
|
-
cached: tokens?.cache?.read
|
|
403
|
-
output: tokens?.output
|
|
404
|
-
reasoning: tokens?.reasoning
|
|
405
|
-
cacheWrite: tokens?.cache?.write
|
|
406
|
-
cost: info.cost
|
|
458
|
+
input: countOf2(tokens?.input),
|
|
459
|
+
cached: countOf2(tokens?.cache?.read),
|
|
460
|
+
output: countOf2(tokens?.output),
|
|
461
|
+
reasoning: countOf2(tokens?.reasoning),
|
|
462
|
+
cacheWrite: countOf2(tokens?.cache?.write),
|
|
463
|
+
cost: amountOf2(info.cost),
|
|
464
|
+
listCost: amountOf2(listCost),
|
|
407
465
|
steps: 0
|
|
408
466
|
};
|
|
409
467
|
}
|
|
@@ -426,6 +484,73 @@ function lineText(parts) {
|
|
|
426
484
|
// src/stats/queries.ts
|
|
427
485
|
var COMPACTION_KIND = "compaction";
|
|
428
486
|
var DEFAULT_TTL_HINT_MS = 10 * 60 * 1000;
|
|
487
|
+
function spend(usage) {
|
|
488
|
+
return usage.cost + usage.listCost;
|
|
489
|
+
}
|
|
490
|
+
function sessionListCost(db, sessionID) {
|
|
491
|
+
const row = db.query("SELECT COALESCE(SUM(list_cost), 0) AS listCost FROM steps WHERE session_id = ?").get(sessionID);
|
|
492
|
+
return row?.listCost ?? 0;
|
|
493
|
+
}
|
|
494
|
+
var EMPTY_OTHER = { entries: 0, cost: 0 };
|
|
495
|
+
function hasUsageTable(db) {
|
|
496
|
+
try {
|
|
497
|
+
return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'usage'").get() !== null;
|
|
498
|
+
} catch {
|
|
499
|
+
return false;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
function otherWhere(range, filters) {
|
|
503
|
+
if (filters?.modelID !== undefined && filters.modelID !== "")
|
|
504
|
+
return;
|
|
505
|
+
if (filters?.modelKey !== undefined && filters.modelKey !== "")
|
|
506
|
+
return;
|
|
507
|
+
if (filters?.provider !== undefined && filters.provider !== "")
|
|
508
|
+
return;
|
|
509
|
+
const span = rangeWhere(range, "at");
|
|
510
|
+
const clauses = span.where === "" ? [] : [span.where.slice("WHERE ".length)];
|
|
511
|
+
const params = [...span.params];
|
|
512
|
+
if (filters?.sessionID !== undefined && filters.sessionID !== "") {
|
|
513
|
+
clauses.push("session_id = ?");
|
|
514
|
+
params.push(filters.sessionID);
|
|
515
|
+
}
|
|
516
|
+
return { where: clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "", params };
|
|
517
|
+
}
|
|
518
|
+
function otherUsage(db, range, filters) {
|
|
519
|
+
const filter = otherWhere(range, filters);
|
|
520
|
+
if (filter === undefined || !hasUsageTable(db))
|
|
521
|
+
return { ...EMPTY_OTHER };
|
|
522
|
+
try {
|
|
523
|
+
const row = db.query(`SELECT COUNT(*) AS entries, COALESCE(SUM(cost), 0) AS cost FROM usage ${filter.where}`).get(...filter.params);
|
|
524
|
+
return { entries: row?.entries ?? 0, cost: row?.cost ?? 0 };
|
|
525
|
+
} catch {
|
|
526
|
+
return { ...EMPTY_OTHER };
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
function otherUsageBySession(db, range, filters) {
|
|
530
|
+
const out = new Map;
|
|
531
|
+
const filter = otherWhere(range, filters);
|
|
532
|
+
if (filter === undefined || !hasUsageTable(db))
|
|
533
|
+
return out;
|
|
534
|
+
try {
|
|
535
|
+
const rows = db.query(`SELECT session_id AS sessionID, COUNT(*) AS entries, COALESCE(SUM(cost), 0) AS cost
|
|
536
|
+
FROM usage ${filter.where}
|
|
537
|
+
GROUP BY session_id`).all(...filter.params);
|
|
538
|
+
for (const row of rows)
|
|
539
|
+
out.set(row.sessionID, { entries: row.entries ?? 0, cost: row.cost ?? 0 });
|
|
540
|
+
} catch {}
|
|
541
|
+
return out;
|
|
542
|
+
}
|
|
543
|
+
function otherUsageRows(db, range, filters) {
|
|
544
|
+
const filter = otherWhere(range, filters);
|
|
545
|
+
if (filter === undefined || !hasUsageTable(db))
|
|
546
|
+
return [];
|
|
547
|
+
const where = filter.where === "" ? "WHERE at IS NOT NULL" : `${filter.where} AND at IS NOT NULL`;
|
|
548
|
+
try {
|
|
549
|
+
return db.query(`SELECT session_id AS sessionID, at, cost FROM usage ${where} ORDER BY at`).all(...filter.params);
|
|
550
|
+
} catch {
|
|
551
|
+
return [];
|
|
552
|
+
}
|
|
553
|
+
}
|
|
429
554
|
var STEP_TIME = "COALESCE(created_at, recorded_at)";
|
|
430
555
|
var MODEL_KEY_SQL = "COALESCE(model_id, '(unknown)') || '#' || COALESCE(variant, '')";
|
|
431
556
|
function modelKey(modelID, variant) {
|
|
@@ -440,7 +565,8 @@ var USAGE_SELECT = `COUNT(*) AS steps,
|
|
|
440
565
|
COALESCE(SUM(cache_write), 0) AS cacheWrite,
|
|
441
566
|
COALESCE(SUM(output_tokens), 0) AS output,
|
|
442
567
|
COALESCE(SUM(reasoning_tokens), 0) AS reasoning,
|
|
443
|
-
COALESCE(SUM(cost), 0) AS cost
|
|
568
|
+
COALESCE(SUM(cost), 0) AS cost,
|
|
569
|
+
COALESCE(SUM(list_cost), 0) AS listCost`;
|
|
444
570
|
function usageFrom(row) {
|
|
445
571
|
return {
|
|
446
572
|
steps: row.steps ?? 0,
|
|
@@ -449,7 +575,8 @@ function usageFrom(row) {
|
|
|
449
575
|
cacheWrite: row.cacheWrite ?? 0,
|
|
450
576
|
output: row.output ?? 0,
|
|
451
577
|
reasoning: row.reasoning ?? 0,
|
|
452
|
-
cost: row.cost ?? 0
|
|
578
|
+
cost: row.cost ?? 0,
|
|
579
|
+
listCost: row.listCost ?? 0
|
|
453
580
|
};
|
|
454
581
|
}
|
|
455
582
|
function rangeWhere(range, column = STEP_TIME) {
|
|
@@ -501,12 +628,22 @@ function overview(db, range, filters) {
|
|
|
501
628
|
COALESCE(SUM(CASE WHEN streamed_at > created_at THEN streamed_at - created_at ELSE 0 END), 0) AS window
|
|
502
629
|
FROM steps ${steps.where}`).get(...steps.params);
|
|
503
630
|
const prompts = rangeWhere(range, "created_at");
|
|
504
|
-
const
|
|
505
|
-
const
|
|
631
|
+
const promptClauses = prompts.where === "" ? [] : [prompts.where.slice("WHERE ".length)];
|
|
632
|
+
const promptParams = [...prompts.params];
|
|
633
|
+
if (filters?.sessionID !== undefined && filters.sessionID !== "") {
|
|
634
|
+
promptClauses.push("session_id = ?");
|
|
635
|
+
promptParams.push(filters.sessionID);
|
|
636
|
+
}
|
|
637
|
+
const promptWhere = promptClauses.length > 0 ? `WHERE ${promptClauses.join(" AND ")}` : "";
|
|
638
|
+
const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${promptWhere}`).get(...promptParams);
|
|
639
|
+
const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
|
|
640
|
+
const other = otherUsage(db, range, filters);
|
|
506
641
|
return {
|
|
507
642
|
...usage,
|
|
643
|
+
cost: usage.cost + other.cost,
|
|
508
644
|
sessions: row?.sessions ?? 0,
|
|
509
645
|
prompts: promptRow?.prompts ?? 0,
|
|
646
|
+
otherCost: other.cost,
|
|
510
647
|
firstAt: row?.firstAt ?? undefined,
|
|
511
648
|
lastAt: row?.lastAt ?? undefined,
|
|
512
649
|
cacheHitRatio: cacheHitRatio(usage),
|
|
@@ -544,7 +681,7 @@ function models(db, range, filters) {
|
|
|
544
681
|
return [...models.values()].sort((a, b) => billedTokens(b.totals) - billedTokens(a.totals));
|
|
545
682
|
}
|
|
546
683
|
function emptyUsage() {
|
|
547
|
-
return { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0 };
|
|
684
|
+
return { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 };
|
|
548
685
|
}
|
|
549
686
|
function addUsage(target, source) {
|
|
550
687
|
target.steps += source.steps;
|
|
@@ -554,9 +691,10 @@ function addUsage(target, source) {
|
|
|
554
691
|
target.output += source.output;
|
|
555
692
|
target.reasoning += source.reasoning;
|
|
556
693
|
target.cost += source.cost;
|
|
694
|
+
target.listCost += source.listCost;
|
|
557
695
|
}
|
|
558
696
|
function billedTokens(usage) {
|
|
559
|
-
return usage.input + usage.cached + usage.output;
|
|
697
|
+
return usage.input + usage.cached + usage.cacheWrite + usage.output + usage.reasoning;
|
|
560
698
|
}
|
|
561
699
|
function percentile(values, p) {
|
|
562
700
|
if (values.length === 0)
|
|
@@ -582,6 +720,17 @@ function sessions(db, options) {
|
|
|
582
720
|
const limit = options?.limit ?? 20;
|
|
583
721
|
const clauses = filter.where === "" ? [] : [filter.where.slice("WHERE ".length)];
|
|
584
722
|
const params = [...filter.params];
|
|
723
|
+
const promptRange = [];
|
|
724
|
+
const promptParams = [];
|
|
725
|
+
if (range?.from !== undefined) {
|
|
726
|
+
promptRange.push("p.created_at >= ?");
|
|
727
|
+
promptParams.push(range.from);
|
|
728
|
+
}
|
|
729
|
+
if (range?.to !== undefined) {
|
|
730
|
+
promptRange.push("p.created_at < ?");
|
|
731
|
+
promptParams.push(range.to);
|
|
732
|
+
}
|
|
733
|
+
const promptClause = promptRange.length > 0 ? ` AND ${promptRange.join(" AND ")}` : "";
|
|
585
734
|
if (options?.sessionIDs !== undefined) {
|
|
586
735
|
const ids = options.sessionIDs.slice(0, 500);
|
|
587
736
|
clauses.push(`st.session_id IN (${ids.map(() => "?").join(", ")})`);
|
|
@@ -590,7 +739,7 @@ function sessions(db, options) {
|
|
|
590
739
|
const rows = db.query(`SELECT st.session_id, s.title, s.directory, s.parent_id,
|
|
591
740
|
GROUP_CONCAT(DISTINCT st.provider_id) AS providers,
|
|
592
741
|
GROUP_CONCAT(DISTINCT st.model_id) AS models,
|
|
593
|
-
(SELECT COUNT(*) FROM prompts p WHERE p.session_id = st.session_id) AS prompts,
|
|
742
|
+
(SELECT COUNT(*) FROM prompts p WHERE p.session_id = st.session_id${promptClause}) AS prompts,
|
|
594
743
|
COUNT(*) AS steps,
|
|
595
744
|
COALESCE(SUM(st.input_tokens), 0) AS input,
|
|
596
745
|
COALESCE(SUM(st.cache_read), 0) AS cached,
|
|
@@ -598,6 +747,7 @@ function sessions(db, options) {
|
|
|
598
747
|
COALESCE(SUM(st.output_tokens), 0) AS output,
|
|
599
748
|
COALESCE(SUM(st.reasoning_tokens), 0) AS reasoning,
|
|
600
749
|
COALESCE(SUM(st.cost), 0) AS cost,
|
|
750
|
+
COALESCE(SUM(st.list_cost), 0) AS listCost,
|
|
601
751
|
MIN(COALESCE(st.created_at, st.recorded_at)) AS first_at,
|
|
602
752
|
MAX(COALESCE(st.completed_at, st.created_at, st.recorded_at)) AS last_at
|
|
603
753
|
FROM steps st
|
|
@@ -605,11 +755,14 @@ function sessions(db, options) {
|
|
|
605
755
|
${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
|
|
606
756
|
GROUP BY st.session_id
|
|
607
757
|
ORDER BY last_at DESC
|
|
608
|
-
LIMIT ?`).all(...params, limit);
|
|
758
|
+
LIMIT ?`).all(...promptParams, ...params, limit);
|
|
759
|
+
const other = otherUsageBySession(db, range, options?.filters);
|
|
609
760
|
return rows.map((row) => {
|
|
610
761
|
const usage = usageFrom(row);
|
|
762
|
+
const extra = other.get(row.session_id)?.cost ?? 0;
|
|
611
763
|
return {
|
|
612
764
|
...usage,
|
|
765
|
+
cost: usage.cost + extra,
|
|
613
766
|
sessionID: row.session_id,
|
|
614
767
|
parentID: row.parent_id ?? undefined,
|
|
615
768
|
title: row.title ?? undefined,
|
|
@@ -617,6 +770,7 @@ function sessions(db, options) {
|
|
|
617
770
|
providers: row.providers ? row.providers.split(",").filter(Boolean) : [],
|
|
618
771
|
models: row.models ? row.models.split(",").filter(Boolean) : [],
|
|
619
772
|
prompts: row.prompts ?? 0,
|
|
773
|
+
otherCost: extra,
|
|
620
774
|
firstAt: row.first_at ?? undefined,
|
|
621
775
|
lastAt: row.last_at ?? undefined,
|
|
622
776
|
cacheHitRatio: cacheHitRatio(usage)
|
|
@@ -640,7 +794,8 @@ function stepUsage(row) {
|
|
|
640
794
|
cacheWrite: row.cache_write ?? 0,
|
|
641
795
|
output: row.output_tokens ?? 0,
|
|
642
796
|
reasoning: row.reasoning_tokens ?? 0,
|
|
643
|
-
cost: row.cost ?? 0
|
|
797
|
+
cost: row.cost ?? 0,
|
|
798
|
+
listCost: row.list_cost ?? 0
|
|
644
799
|
};
|
|
645
800
|
}
|
|
646
801
|
function stepMessage(row) {
|
|
@@ -659,118 +814,131 @@ function stepMessage(row) {
|
|
|
659
814
|
};
|
|
660
815
|
}
|
|
661
816
|
function turns(db, options) {
|
|
662
|
-
const
|
|
817
|
+
const requested = options?.limit ?? 50;
|
|
818
|
+
const limit = Number.isFinite(requested) ? Math.max(0, Math.floor(requested)) : 50;
|
|
663
819
|
const filter = buildWhere(options?.range, options?.filters);
|
|
664
|
-
const
|
|
665
|
-
const
|
|
820
|
+
const baseClauses = filter.where === "" ? [] : [filter.where.slice("WHERE ".length)];
|
|
821
|
+
const baseParams = [...filter.params];
|
|
666
822
|
if (options?.sessionID !== undefined) {
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
}
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
created_at, streamed_at, recorded_at, completed_at, finish
|
|
678
|
-
FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
|
|
679
|
-
ORDER BY session_id, ${STEP_TIME}`).all(...params);
|
|
680
|
-
const promptClause = options?.sessionID === undefined ? "" : `WHERE session_id = ?${floor === undefined ? "" : " AND created_at >= ?"}`;
|
|
681
|
-
const promptParams = options?.sessionID === undefined ? [] : floor === undefined ? [options.sessionID] : [options.sessionID, floor];
|
|
682
|
-
const promptRows = db.query(`SELECT session_id, created_at FROM prompts ${promptClause} ORDER BY session_id, created_at`).all(...promptParams);
|
|
683
|
-
const promptsBySession = new Map;
|
|
684
|
-
for (const row of promptRows) {
|
|
685
|
-
if (row.created_at === null)
|
|
686
|
-
continue;
|
|
687
|
-
const list = promptsBySession.get(row.session_id) ?? [];
|
|
688
|
-
list.push(row.created_at);
|
|
689
|
-
promptsBySession.set(row.session_id, list);
|
|
690
|
-
}
|
|
691
|
-
const result = [];
|
|
692
|
-
let sessionID;
|
|
693
|
-
let bucket = [];
|
|
694
|
-
let promptIndex = -2;
|
|
695
|
-
let promptAt;
|
|
696
|
-
let previousPromptAt;
|
|
697
|
-
function close() {
|
|
698
|
-
const last = bucket[bucket.length - 1];
|
|
699
|
-
if (last === undefined || !turnFinished(last.finish)) {
|
|
700
|
-
bucket = [];
|
|
701
|
-
return;
|
|
823
|
+
baseClauses.push("session_id = ?");
|
|
824
|
+
baseParams.push(options.sessionID);
|
|
825
|
+
}
|
|
826
|
+
function read(promptCount) {
|
|
827
|
+
const clauses = [...baseClauses];
|
|
828
|
+
const params = [...baseParams];
|
|
829
|
+
const floor = options?.sessionID === undefined ? undefined : promptFloor(db, options.sessionID, promptCount);
|
|
830
|
+
if (floor !== undefined) {
|
|
831
|
+
clauses.push(`${STEP_TIME} >= ?`);
|
|
832
|
+
params.push(floor);
|
|
702
833
|
}
|
|
703
|
-
const
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
reference = message;
|
|
715
|
-
}
|
|
716
|
-
const providerID = last.provider_id ?? undefined;
|
|
717
|
-
const modelID = last.model_id ?? undefined;
|
|
718
|
-
const variant = last.variant ?? undefined;
|
|
719
|
-
let produced = 0;
|
|
720
|
-
let window = 0;
|
|
721
|
-
for (const row of bucket) {
|
|
722
|
-
if (row.created_at === null || row.streamed_at === null || row.streamed_at <= row.created_at)
|
|
834
|
+
const steps = db.query(`SELECT message_id, session_id, provider_id, model_id, variant,
|
|
835
|
+
input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,
|
|
836
|
+
created_at, streamed_at, recorded_at, completed_at, finish
|
|
837
|
+
FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
|
|
838
|
+
ORDER BY session_id, ${STEP_TIME}, message_id`).all(...params);
|
|
839
|
+
const promptClause = options?.sessionID === undefined ? "" : `WHERE session_id = ?${floor === undefined ? "" : " AND created_at >= ?"}`;
|
|
840
|
+
const promptParams = options?.sessionID === undefined ? [] : floor === undefined ? [options.sessionID] : [options.sessionID, floor];
|
|
841
|
+
const promptRows = db.query(`SELECT session_id, created_at FROM prompts ${promptClause} ORDER BY session_id, created_at`).all(...promptParams);
|
|
842
|
+
const promptsBySession = new Map;
|
|
843
|
+
for (const row of promptRows) {
|
|
844
|
+
if (row.created_at === null)
|
|
723
845
|
continue;
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
result
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
846
|
+
const list = promptsBySession.get(row.session_id) ?? [];
|
|
847
|
+
list.push(row.created_at);
|
|
848
|
+
promptsBySession.set(row.session_id, list);
|
|
849
|
+
}
|
|
850
|
+
const result = [];
|
|
851
|
+
let sessionID;
|
|
852
|
+
let bucket = [];
|
|
853
|
+
let promptIndex = -2;
|
|
854
|
+
let promptAt;
|
|
855
|
+
function close() {
|
|
856
|
+
const last = bucket[bucket.length - 1];
|
|
857
|
+
if (last === undefined || !turnFinished(last.finish)) {
|
|
858
|
+
bucket = [];
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
861
|
+
const totals = emptyUsage();
|
|
862
|
+
for (const row of bucket)
|
|
863
|
+
addUsage(totals, stepUsage(row));
|
|
864
|
+
const drops = [];
|
|
865
|
+
let reference;
|
|
866
|
+
for (const row of bucket) {
|
|
867
|
+
const message = stepMessage(row);
|
|
868
|
+
const drop = cacheDrop(reference, message);
|
|
869
|
+
if (drop !== undefined) {
|
|
870
|
+
drops.push({ messageID: row.message_id, tokens: drop, gapMs: stepGap(reference, message) });
|
|
871
|
+
}
|
|
872
|
+
reference = message;
|
|
873
|
+
}
|
|
874
|
+
const providerID = last.provider_id ?? undefined;
|
|
875
|
+
const modelID = last.model_id ?? undefined;
|
|
876
|
+
const variant = last.variant ?? undefined;
|
|
877
|
+
let produced = 0;
|
|
878
|
+
let window = 0;
|
|
879
|
+
for (const row of bucket) {
|
|
880
|
+
if (row.created_at === null || row.streamed_at === null || row.streamed_at <= row.created_at)
|
|
881
|
+
continue;
|
|
882
|
+
produced += (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0);
|
|
883
|
+
window += row.streamed_at - row.created_at;
|
|
762
884
|
}
|
|
885
|
+
const previous = result.length > 0 && result[result.length - 1].sessionID === last.session_id ? result[result.length - 1] : undefined;
|
|
886
|
+
result.push({
|
|
887
|
+
sessionID: last.session_id,
|
|
888
|
+
promptAt,
|
|
889
|
+
endAt: last.completed_at ?? last.created_at ?? last.recorded_at,
|
|
890
|
+
promptGapMs: promptAt !== undefined && previous?.promptAt !== undefined ? Math.max(0, promptAt - previous.promptAt) : undefined,
|
|
891
|
+
providerID,
|
|
892
|
+
modelID,
|
|
893
|
+
variant,
|
|
894
|
+
providerChanged: previous?.providerID !== undefined && providerID !== undefined && previous.providerID !== providerID,
|
|
895
|
+
modelChanged: previous !== undefined && previous.providerID === providerID && `${previous.modelID ?? ""}#${previous.variant ?? ""}` !== `${modelID ?? ""}#${variant ?? ""}`,
|
|
896
|
+
steps: bucket.length,
|
|
897
|
+
latest: stepUsage(last),
|
|
898
|
+
totals,
|
|
899
|
+
drops,
|
|
900
|
+
finish: last.finish ?? undefined,
|
|
901
|
+
tps: tokensPerSecond(produced, 0, window)
|
|
902
|
+
});
|
|
903
|
+
bucket = [];
|
|
763
904
|
}
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
905
|
+
for (const row of steps) {
|
|
906
|
+
if (row.session_id !== sessionID) {
|
|
907
|
+
close();
|
|
908
|
+
sessionID = row.session_id;
|
|
909
|
+
promptIndex = -2;
|
|
910
|
+
promptAt = undefined;
|
|
911
|
+
}
|
|
912
|
+
const time = row.created_at ?? row.recorded_at;
|
|
913
|
+
const prompts = promptsBySession.get(row.session_id) ?? [];
|
|
914
|
+
let index = -1;
|
|
915
|
+
for (let candidate = prompts.length - 1;candidate >= 0; candidate -= 1) {
|
|
916
|
+
if ((prompts[candidate] ?? Number.POSITIVE_INFINITY) <= time) {
|
|
917
|
+
index = candidate;
|
|
918
|
+
break;
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
if (index !== promptIndex) {
|
|
922
|
+
close();
|
|
923
|
+
promptIndex = index;
|
|
924
|
+
promptAt = index >= 0 ? prompts[index] : undefined;
|
|
925
|
+
}
|
|
926
|
+
bucket.push(row);
|
|
769
927
|
}
|
|
770
|
-
|
|
928
|
+
close();
|
|
929
|
+
const reachedRangeStart = options?.range?.from !== undefined && floor !== undefined && floor <= options.range.from;
|
|
930
|
+
return { rows: result.reverse(), complete: floor === undefined || reachedRangeStart };
|
|
931
|
+
}
|
|
932
|
+
let promptCount = Math.max(1, limit + 1);
|
|
933
|
+
for (;; ) {
|
|
934
|
+
const { rows, complete } = read(promptCount);
|
|
935
|
+
if (rows.length >= limit || complete)
|
|
936
|
+
return rows.slice(0, limit);
|
|
937
|
+
const next = promptCount * 2 + 1;
|
|
938
|
+
if (!Number.isFinite(next) || next <= promptCount)
|
|
939
|
+
return rows.slice(0, limit);
|
|
940
|
+
promptCount = next;
|
|
771
941
|
}
|
|
772
|
-
close();
|
|
773
|
-
return result.reverse().slice(0, limit);
|
|
774
942
|
}
|
|
775
943
|
function promptFloor(db, sessionID, count) {
|
|
776
944
|
const rows = db.query("SELECT created_at FROM prompts WHERE session_id = ? AND created_at IS NOT NULL ORDER BY created_at DESC LIMIT ?").all(sessionID, count);
|
|
@@ -843,38 +1011,44 @@ function sanitizeSettings(raw) {
|
|
|
843
1011
|
};
|
|
844
1012
|
}
|
|
845
1013
|
function formatPercent(value, digits = 1) {
|
|
846
|
-
|
|
1014
|
+
if (value === undefined || !Number.isFinite(value))
|
|
1015
|
+
return "\u2013";
|
|
1016
|
+
return `${(value * 100).toFixed(digits)}%`;
|
|
847
1017
|
}
|
|
848
1018
|
function formatCount(value) {
|
|
849
|
-
return Math.round(value).toLocaleString("en-US");
|
|
1019
|
+
return Number.isFinite(value) ? Math.round(value).toLocaleString("en-US") : "\u2013";
|
|
850
1020
|
}
|
|
851
1021
|
function formatMs(value) {
|
|
852
|
-
if (value === undefined)
|
|
1022
|
+
if (value === undefined || !Number.isFinite(value))
|
|
853
1023
|
return "\u2013";
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
1024
|
+
const ms = Math.max(0, value);
|
|
1025
|
+
if (ms < 1000)
|
|
1026
|
+
return `${Math.round(ms)}ms`;
|
|
1027
|
+
if (ms < 60000)
|
|
1028
|
+
return `${(ms / 1000).toFixed(1)}s`;
|
|
1029
|
+
return formatDuration(ms);
|
|
859
1030
|
}
|
|
860
1031
|
function formatTps(value) {
|
|
861
|
-
|
|
1032
|
+
if (value === undefined || !Number.isFinite(value) || value < 0)
|
|
1033
|
+
return "\u2013";
|
|
1034
|
+
return `${value.toFixed(1)}/s`;
|
|
862
1035
|
}
|
|
863
1036
|
function formatTpsCompact(value) {
|
|
864
|
-
if (value === undefined)
|
|
1037
|
+
if (value === undefined || !Number.isFinite(value) || value < 0)
|
|
865
1038
|
return "\u2013";
|
|
866
1039
|
return value >= 10 ? `${Math.round(value)}/s` : `${value.toFixed(1)}/s`;
|
|
867
1040
|
}
|
|
868
1041
|
function formatGap(value) {
|
|
869
|
-
if (value === undefined)
|
|
1042
|
+
if (value === undefined || !Number.isFinite(value))
|
|
870
1043
|
return "\u2013";
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
1044
|
+
const gap = Math.max(0, value);
|
|
1045
|
+
if (gap < 60000)
|
|
1046
|
+
return `${Math.round(gap / 1000)}s`;
|
|
1047
|
+
if (gap < 3600000)
|
|
1048
|
+
return `${Math.round(gap / 60000)}m`;
|
|
1049
|
+
if (gap < 86400000)
|
|
1050
|
+
return `${(gap / 3600000).toFixed(1)}h`;
|
|
1051
|
+
return `${(gap / 86400000).toFixed(1)}d`;
|
|
878
1052
|
}
|
|
879
1053
|
function truncate(value, width) {
|
|
880
1054
|
if (width <= 1)
|
|
@@ -979,6 +1153,7 @@ function usageBuckets(usage) {
|
|
|
979
1153
|
output: usage.output + usage.reasoning,
|
|
980
1154
|
reasoning: usage.reasoning,
|
|
981
1155
|
cost: usage.cost,
|
|
1156
|
+
listCost: usage.listCost ?? 0,
|
|
982
1157
|
hit: prompt > 0 ? usage.cached / prompt : undefined
|
|
983
1158
|
};
|
|
984
1159
|
}
|
|
@@ -995,7 +1170,7 @@ function viewBar(view, width = 200) {
|
|
|
995
1170
|
}
|
|
996
1171
|
function keysFor(of) {
|
|
997
1172
|
if (of === "db")
|
|
998
|
-
return "\u2191\u2193 pick a retention \xB7 enter prune
|
|
1173
|
+
return "\u2191\u2193 pick a retention \xB7 enter prune \xB7 e backfill estimates \xB7 v vacuum \xB7 r refresh \xB7 1-9 view \xB7 ? help";
|
|
999
1174
|
if (of === "periods")
|
|
1000
1175
|
return "\u2191\u2193 move \xB7 enter drill \xB7 b bucket \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
|
|
1001
1176
|
if (of === "turns")
|
|
@@ -1024,6 +1199,7 @@ function helpLines(width) {
|
|
|
1024
1199
|
{ text: " a turns scope: this session \u2194 all sessions" },
|
|
1025
1200
|
{ text: " m p filter by model / provider (x clears)" },
|
|
1026
1201
|
{ text: " r re-read the database \xB7 f full screen \xB7 escape close" },
|
|
1202
|
+
{ text: " e db: backfill list-price estimates for the $0 steps" },
|
|
1027
1203
|
{ text: "" },
|
|
1028
1204
|
{ text: "numbers \xB7 the same buckets as the live line", tone: HEADER_TONE },
|
|
1029
1205
|
{ text: " prompt everything the provider saw: cached + fresh + writes" },
|
|
@@ -1035,6 +1211,10 @@ function helpLines(width) {
|
|
|
1035
1211
|
{ text: " out everything generated: visible output + reasoning" },
|
|
1036
1212
|
{ text: " reasoning part of `out`" },
|
|
1037
1213
|
{ text: " cost money, not tokens: a turn sums every step; $0 is left out" },
|
|
1214
|
+
{ text: " other compaction/title usage: money with no assistant step;" },
|
|
1215
|
+
{ text: " overview, periods and sessions include it; model rows do not" },
|
|
1216
|
+
{ text: " \u2248 list-price estimate for steps the host reported as $0;" },
|
|
1217
|
+
{ text: " `$0.12 + \u2248 $3.40` keeps charged and estimated money apart" },
|
|
1038
1218
|
{ text: " wall request \u2192 completed step \xB7 stream request \u2192 last chunk" },
|
|
1039
1219
|
{ text: " tps out / streaming seconds, shown as p50" },
|
|
1040
1220
|
{ text: " switches how often a step's model or provider differs from the step" },
|
|
@@ -1050,12 +1230,12 @@ function helpLines(width) {
|
|
|
1050
1230
|
{ text: "database", tone: HEADER_TONE },
|
|
1051
1231
|
{ text: " the db view shows where the file lives, what it holds and how much" },
|
|
1052
1232
|
{ text: " of it is old: \u2191\u2193 pick a retention, enter prunes from its cutoff date," },
|
|
1053
|
-
{ text: " v gives the space back" },
|
|
1233
|
+
{ text: " e backfills list estimates, v gives the space back" },
|
|
1054
1234
|
{ text: " local time \xB7 SQLite in the OpenCode state directory" }
|
|
1055
1235
|
];
|
|
1056
1236
|
return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
|
|
1057
1237
|
}
|
|
1058
|
-
function usagePairs(usage) {
|
|
1238
|
+
function usagePairs(usage, estimates = true) {
|
|
1059
1239
|
if (usage === undefined)
|
|
1060
1240
|
return [];
|
|
1061
1241
|
const buckets = usageBuckets(usage);
|
|
@@ -1070,18 +1250,22 @@ function usagePairs(usage) {
|
|
|
1070
1250
|
];
|
|
1071
1251
|
if (buckets.reasoning > 0)
|
|
1072
1252
|
pairs.push(["reasoning", formatTokens(buckets.reasoning)]);
|
|
1073
|
-
pairs.push(["cost", formatCost(buckets.cost)]);
|
|
1253
|
+
pairs.push(["cost", (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost)]);
|
|
1254
|
+
const other = usage.otherCost ?? 0;
|
|
1255
|
+
if (other > 0)
|
|
1256
|
+
pairs.push(["other", `${formatCost(other)} comp/title`]);
|
|
1074
1257
|
if ("tps" in usage && usage.tps !== undefined)
|
|
1075
1258
|
pairs.push(["tps", formatTps(usage.tps)]);
|
|
1076
1259
|
return pairs;
|
|
1077
1260
|
}
|
|
1078
1261
|
function overviewLines(data, width) {
|
|
1079
1262
|
const lines = [];
|
|
1263
|
+
const estimates = data.estimates !== false;
|
|
1080
1264
|
lines.push({
|
|
1081
1265
|
text: `${rangeLabel(data.range)} \xB7 ${count(data.usage.steps, "step")} \xB7 ${count(data.usage.sessions, "session")} \xB7 ${count(data.usage.prompts, "prompt")}`,
|
|
1082
1266
|
tone: "muted"
|
|
1083
1267
|
});
|
|
1084
|
-
lines.push(...kvGrid(buildOverviewPairs(data.usage, "all"), width));
|
|
1268
|
+
lines.push(...kvGrid(buildOverviewPairs(data.usage, "all", estimates), width));
|
|
1085
1269
|
if (data.activity !== undefined && data.activity.length > 1) {
|
|
1086
1270
|
const series = reduceSeries(data.activity);
|
|
1087
1271
|
lines.push({ text: "", tone: "muted" });
|
|
@@ -1090,12 +1274,13 @@ function overviewLines(data, width) {
|
|
|
1090
1274
|
if (data.session !== undefined) {
|
|
1091
1275
|
lines.push({ text: "", tone: "muted" });
|
|
1092
1276
|
lines.push({ text: "this session", tone: HEADER_TONE });
|
|
1093
|
-
lines.push(...kvGrid(buildOverviewPairs(data.session, "session"), width));
|
|
1277
|
+
lines.push(...kvGrid(buildOverviewPairs(data.session, "session", estimates), width));
|
|
1094
1278
|
if (data.subagents !== undefined && data.subagents.length > 0) {
|
|
1095
1279
|
const steps = data.subagents.reduce((sum, row) => sum + row.steps, 0);
|
|
1096
1280
|
const cost = data.subagents.reduce((sum, row) => sum + row.cost, 0);
|
|
1281
|
+
const listCost = data.subagents.reduce((sum, row) => sum + row.listCost, 0);
|
|
1097
1282
|
lines.push({
|
|
1098
|
-
text: ` subagents ${count(data.subagents.length, "session")} \xB7 ${count(steps, "step")} \xB7 ${
|
|
1283
|
+
text: ` subagents ${count(data.subagents.length, "session")} \xB7 ${count(steps, "step")} \xB7 ${formatSpend(cost, estimates ? listCost : 0)} (their own sessions)`,
|
|
1099
1284
|
tone: "muted"
|
|
1100
1285
|
});
|
|
1101
1286
|
}
|
|
@@ -1107,8 +1292,8 @@ function overviewLines(data, width) {
|
|
|
1107
1292
|
}
|
|
1108
1293
|
return lines;
|
|
1109
1294
|
}
|
|
1110
|
-
function buildOverviewPairs(usage, scope) {
|
|
1111
|
-
const pairs = usagePairs(usage);
|
|
1295
|
+
function buildOverviewPairs(usage, scope, estimates = true) {
|
|
1296
|
+
const pairs = usagePairs(usage, estimates);
|
|
1112
1297
|
if (scope === "all") {
|
|
1113
1298
|
pairs.push(["first", usage.firstAt === undefined ? "\u2013" : new Date(usage.firstAt).toLocaleString("en-GB")]);
|
|
1114
1299
|
pairs.push(["last", usage.lastAt === undefined ? "\u2013" : new Date(usage.lastAt).toLocaleString("en-GB")]);
|
|
@@ -1142,7 +1327,7 @@ function modelColumns(width) {
|
|
|
1142
1327
|
}
|
|
1143
1328
|
return layouts[layouts.length - 1];
|
|
1144
1329
|
}
|
|
1145
|
-
function modelsLines(rows, width, extras, limit = 40) {
|
|
1330
|
+
function modelsLines(rows, width, extras, limit = 40, estimates = true) {
|
|
1146
1331
|
const columns = modelColumns(width);
|
|
1147
1332
|
const widths = [columns.model, columns.steps, columns.prompt, columns.cached];
|
|
1148
1333
|
const aligns = ["left", "right", "right", "right"];
|
|
@@ -1178,7 +1363,7 @@ function modelsLines(rows, width, extras, limit = 40) {
|
|
|
1178
1363
|
cells.push(formatPercent(cache?.hit ?? buckets.hit));
|
|
1179
1364
|
cells.push(formatTokens(buckets.output));
|
|
1180
1365
|
if (columns.cost > 0)
|
|
1181
|
-
cells.push(
|
|
1366
|
+
cells.push(formatSpend(buckets.cost, estimates ? buckets.listCost : 0));
|
|
1182
1367
|
if (columns.spread > 0)
|
|
1183
1368
|
cells.push(providers.join(", "));
|
|
1184
1369
|
lines.push({
|
|
@@ -1239,7 +1424,7 @@ function renderTable(rows, columns, width, options) {
|
|
|
1239
1424
|
lines.push({ text: `\u2026 ${count(rows.length - options.limit, "more row")}`, tone: "muted" });
|
|
1240
1425
|
return lines;
|
|
1241
1426
|
}
|
|
1242
|
-
function providerSummaryLines(rows, width, limit = 40) {
|
|
1427
|
+
function providerSummaryLines(rows, width, limit = 40, estimates = true) {
|
|
1243
1428
|
const lines = renderTable(rows, [
|
|
1244
1429
|
{ header: "provider", width: 24, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 24) },
|
|
1245
1430
|
{ header: "models", width: 13, align: "right", optional: true, cell: (row) => formatCount(row.models.length) },
|
|
@@ -1250,7 +1435,7 @@ function providerSummaryLines(rows, width, limit = 40) {
|
|
|
1250
1435
|
{ header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
|
|
1251
1436
|
{ header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
|
|
1252
1437
|
{ header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
|
|
1253
|
-
{ header: "cost", width: 9, align: "right", optional: true, cell: (row) =>
|
|
1438
|
+
{ header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
|
|
1254
1439
|
], width, {
|
|
1255
1440
|
limit,
|
|
1256
1441
|
empty: "no usage recorded for this range",
|
|
@@ -1259,7 +1444,7 @@ function providerSummaryLines(rows, width, limit = 40) {
|
|
|
1259
1444
|
});
|
|
1260
1445
|
return lines;
|
|
1261
1446
|
}
|
|
1262
|
-
function providerLines(rows, width, limit = 40) {
|
|
1447
|
+
function providerLines(rows, width, limit = 40, estimates = true) {
|
|
1263
1448
|
return renderTable(rows, [
|
|
1264
1449
|
{ header: "model", width: 26, cell: (row) => modelCell(row.modelID, row.variant, 26) },
|
|
1265
1450
|
{ header: "provider", width: 22, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 22) },
|
|
@@ -1270,7 +1455,7 @@ function providerLines(rows, width, limit = 40) {
|
|
|
1270
1455
|
{ header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
|
|
1271
1456
|
{ header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
|
|
1272
1457
|
{ header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
|
|
1273
|
-
{ header: "cost", width: 9, align: "right", optional: true, cell: (row) =>
|
|
1458
|
+
{ header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
|
|
1274
1459
|
], width, {
|
|
1275
1460
|
limit,
|
|
1276
1461
|
empty: "no usage recorded for this range",
|
|
@@ -1358,7 +1543,7 @@ function cacheLines(data, width) {
|
|
|
1358
1543
|
}
|
|
1359
1544
|
return lines;
|
|
1360
1545
|
}
|
|
1361
|
-
function periodLines(rows, width, granularity, limit = 40) {
|
|
1546
|
+
function periodLines(rows, width, granularity, limit = 40, estimates = true, totalSessions) {
|
|
1362
1547
|
const lines = [];
|
|
1363
1548
|
const totals = rows.reduce((sum, row) => {
|
|
1364
1549
|
sum.steps += row.usage.steps;
|
|
@@ -1369,8 +1554,9 @@ function periodLines(rows, width, granularity, limit = 40) {
|
|
|
1369
1554
|
sum.output += row.usage.output;
|
|
1370
1555
|
sum.reasoning += row.usage.reasoning;
|
|
1371
1556
|
sum.cost += row.usage.cost;
|
|
1557
|
+
sum.listCost += row.usage.listCost;
|
|
1372
1558
|
return sum;
|
|
1373
|
-
}, { steps: 0, sessions: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0 });
|
|
1559
|
+
}, { steps: 0, sessions: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
|
|
1374
1560
|
const overall = usageBuckets(totals);
|
|
1375
1561
|
lines.push({
|
|
1376
1562
|
text: `${granularityLabel(granularity)} \xB7 ${count(rows.length, "period")} \xB7 ${count(totals.steps, "step")} \xB7 hit ${formatPercent(overall.hit)}`,
|
|
@@ -1379,7 +1565,10 @@ function periodLines(rows, width, granularity, limit = 40) {
|
|
|
1379
1565
|
if (rows.length > 1) {
|
|
1380
1566
|
lines.push({ text: `steps ${sparkline(rows.map((row) => row.usage.steps))}`, tone: "muted" });
|
|
1381
1567
|
lines.push({ text: `cached ${sparkline(rows.map((row) => row.usage.cached))}`, tone: "muted" });
|
|
1382
|
-
lines.push({
|
|
1568
|
+
lines.push({
|
|
1569
|
+
text: `cost ${sparkline(rows.map((row) => Math.round((estimates ? row.usage.cost + row.usage.listCost : row.usage.cost) * 1e4)))}`,
|
|
1570
|
+
tone: "muted"
|
|
1571
|
+
});
|
|
1383
1572
|
}
|
|
1384
1573
|
const withSessions = tableWidths(width, [[12, 7, 7, 11, 10, 7, 9, 9]]).length === 8;
|
|
1385
1574
|
const widths = withSessions ? [12, 7, 7, 11, 10, 7, 9, 9] : [12, 7, 11, 10, 7, 9, 9];
|
|
@@ -1397,7 +1586,7 @@ function periodLines(rows, width, granularity, limit = 40) {
|
|
|
1397
1586
|
formatTokens(buckets.cached),
|
|
1398
1587
|
formatPercent(buckets.hit, 0),
|
|
1399
1588
|
formatTokens(buckets.output),
|
|
1400
|
-
|
|
1589
|
+
formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
|
|
1401
1590
|
];
|
|
1402
1591
|
lines.push({ text: formatTableRow(cells, widths, aligns), tone: "base", row: { kind: "period", value: row.key } });
|
|
1403
1592
|
}
|
|
@@ -1406,12 +1595,12 @@ function periodLines(rows, width, granularity, limit = 40) {
|
|
|
1406
1595
|
text: formatTableRow([
|
|
1407
1596
|
"total",
|
|
1408
1597
|
formatCount(totals.steps),
|
|
1409
|
-
...withSessions ? [formatCount(totals.sessions)] : [],
|
|
1598
|
+
...withSessions ? [formatCount(totalSessions ?? totals.sessions)] : [],
|
|
1410
1599
|
formatTokens(overall.prompt),
|
|
1411
1600
|
formatTokens(overall.cached),
|
|
1412
1601
|
formatPercent(overall.hit, 0),
|
|
1413
1602
|
formatTokens(overall.output),
|
|
1414
|
-
|
|
1603
|
+
formatSpend(overall.cost, estimates ? overall.listCost : 0)
|
|
1415
1604
|
], widths, aligns),
|
|
1416
1605
|
tone: HEADER_TONE
|
|
1417
1606
|
});
|
|
@@ -1419,7 +1608,7 @@ function periodLines(rows, width, granularity, limit = 40) {
|
|
|
1419
1608
|
lines.push({ text: "no usage recorded for this range", tone: "muted" });
|
|
1420
1609
|
return lines;
|
|
1421
1610
|
}
|
|
1422
|
-
function latencyLines(report, width, groups, limit = 12) {
|
|
1611
|
+
function latencyLines(report, width, groups, limit = 12, estimates = true) {
|
|
1423
1612
|
const lines = [];
|
|
1424
1613
|
lines.push({
|
|
1425
1614
|
text: formatTableRow(["wall", "p50", formatMs(report.wall.p50), "p90", formatMs(report.wall.p90), "p99", formatMs(report.wall.p99), `n ${formatCount(report.wall.count)}`], [10, 4, 9, 4, 9, 4, 9, 12]),
|
|
@@ -1449,7 +1638,16 @@ function latencyLines(report, width, groups, limit = 12) {
|
|
|
1449
1638
|
for (const row of groups.slice(0, limit)) {
|
|
1450
1639
|
const thin = row.count < 5;
|
|
1451
1640
|
lines.push({
|
|
1452
|
-
text: formatTableRow([
|
|
1641
|
+
text: formatTableRow([
|
|
1642
|
+
row.label,
|
|
1643
|
+
formatCount(row.count),
|
|
1644
|
+
formatMs(row.wall.p50),
|
|
1645
|
+
formatMs(row.wall.p90),
|
|
1646
|
+
formatMs(row.stream.p50),
|
|
1647
|
+
formatTps(row.tps.p50),
|
|
1648
|
+
formatTps(row.tps.p90),
|
|
1649
|
+
formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0)
|
|
1650
|
+
], widths, aligns),
|
|
1453
1651
|
tone: thin ? "muted" : "base",
|
|
1454
1652
|
row: { kind: "model", value: row.key }
|
|
1455
1653
|
});
|
|
@@ -1460,6 +1658,7 @@ function latencyLines(report, width, groups, limit = 12) {
|
|
|
1460
1658
|
}
|
|
1461
1659
|
function sessionsLines(rows, width, options) {
|
|
1462
1660
|
const limit = options?.limit ?? 20;
|
|
1661
|
+
const estimates = options?.estimates !== false;
|
|
1463
1662
|
const widths = [Math.max(18, Math.floor(width * 0.36)), 7, 11, 10, 7, 9, 9];
|
|
1464
1663
|
const aligns = ["left", "right", "right", "right", "right", "right", "right"];
|
|
1465
1664
|
const lines = [
|
|
@@ -1481,19 +1680,23 @@ function sessionsLines(rows, width, options) {
|
|
|
1481
1680
|
formatTokens(buckets.cached),
|
|
1482
1681
|
formatPercent(buckets.hit, 0),
|
|
1483
1682
|
formatTokens(buckets.output),
|
|
1484
|
-
|
|
1683
|
+
formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
|
|
1485
1684
|
], widths, aligns),
|
|
1486
1685
|
tone: child ? "muted" : "base",
|
|
1487
1686
|
row: { kind: "session", value: row.sessionID }
|
|
1488
1687
|
});
|
|
1489
|
-
const details = [
|
|
1688
|
+
const details = [
|
|
1689
|
+
row.directory ?? "",
|
|
1690
|
+
row.models.length > 1 ? count(row.models.length, "model") : "",
|
|
1691
|
+
(row.otherCost ?? 0) > 0 ? `other ${formatCost(row.otherCost)}` : ""
|
|
1692
|
+
].filter((part) => part !== "").join(" \xB7 ");
|
|
1490
1693
|
lines.push({ text: truncate(`${" ".repeat(child ? 2 : 0)} ${details}`, width), tone: "muted" });
|
|
1491
1694
|
}
|
|
1492
1695
|
if (options?.rollup !== undefined && options.rollup.subagentSteps > 0) {
|
|
1493
1696
|
const share = rows.reduce((sum, row) => sum + row.steps, 0);
|
|
1494
1697
|
lines.push({ text: "", tone: "muted" });
|
|
1495
1698
|
lines.push({
|
|
1496
|
-
text: `subagents ${formatCount(options.rollup.subagentSteps)} steps (${formatPercent(share > 0 ? options.rollup.subagentSteps / share : undefined)}) \xB7 ${
|
|
1699
|
+
text: `subagents ${formatCount(options.rollup.subagentSteps)} steps (${formatPercent(share > 0 ? options.rollup.subagentSteps / share : undefined)}) \xB7 ${formatSpend(options.rollup.subagentCost, estimates ? options.rollup.subagentListCost ?? 0 : 0)}`,
|
|
1497
1700
|
tone: "muted"
|
|
1498
1701
|
});
|
|
1499
1702
|
}
|
|
@@ -1522,7 +1725,13 @@ function dbLines(data, width) {
|
|
|
1522
1725
|
});
|
|
1523
1726
|
lines.push({ text: "", tone: "muted" });
|
|
1524
1727
|
lines.push({ text: "clean up", tone: HEADER_TONE });
|
|
1525
|
-
lines.push({ text: truncate(" \u2191\u2193 pick a retention \xB7 enter prunes the steps
|
|
1728
|
+
lines.push({ text: truncate(" \u2191\u2193 pick a retention \xB7 enter prunes the steps and their other usage (asks first) \xB7 v gives the space back", width), tone: "muted" });
|
|
1729
|
+
if (data.estimates !== false) {
|
|
1730
|
+
lines.push({
|
|
1731
|
+
text: truncate(data.info.schemaVersion < 10 ? " list estimates the recorder must upgrade this database first" : data.info.unpriced === 0 ? " list estimates every $0 step has a price" : ` list estimates ${formatCount(data.info.unpriced)} $0 steps without a known price \xB7 e retries`, width),
|
|
1732
|
+
tone: data.info.schemaVersion < 10 || data.info.unpriced > 0 ? "base" : "muted"
|
|
1733
|
+
});
|
|
1734
|
+
}
|
|
1526
1735
|
const widths = [10, 13, 10];
|
|
1527
1736
|
lines.push({ text: formatTableRow(["keep", "prunes", "older than"], widths, ["left", "right", "left"]), tone: "muted" });
|
|
1528
1737
|
for (const option of data.info.removable) {
|
|
@@ -1583,7 +1792,7 @@ function turnsLines(rows, width, options) {
|
|
|
1583
1792
|
lines.push({ text: "no finished turns for this range", tone: "muted" });
|
|
1584
1793
|
return lines;
|
|
1585
1794
|
}
|
|
1586
|
-
function sessionSummaryLines(usage, budget = 34) {
|
|
1795
|
+
function sessionSummaryLines(usage, budget = 34, estimates = true) {
|
|
1587
1796
|
const buckets = usageBuckets(usage);
|
|
1588
1797
|
const steps = formatCount(buckets.steps);
|
|
1589
1798
|
const input = formatTokens(buckets.input);
|
|
@@ -1591,7 +1800,7 @@ function sessionSummaryLines(usage, budget = 34) {
|
|
|
1591
1800
|
const out = formatTokens(buckets.output);
|
|
1592
1801
|
const hit = formatPercent(buckets.hit);
|
|
1593
1802
|
const tps = formatTpsCompact(usage.tps);
|
|
1594
|
-
const cost = formatCost(buckets.cost);
|
|
1803
|
+
const cost = (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost);
|
|
1595
1804
|
const first = [
|
|
1596
1805
|
` ${steps} steps \xB7 in ${input}`,
|
|
1597
1806
|
` ${steps} steps`
|
|
@@ -1624,7 +1833,7 @@ function sidebarLines(rows, options) {
|
|
|
1624
1833
|
const input = formatTokens(display.input);
|
|
1625
1834
|
const prompt = formatTokens(display.prompt);
|
|
1626
1835
|
const output = formatTokens(display.output);
|
|
1627
|
-
const cost = formatCost(turn.totals.cost);
|
|
1836
|
+
const cost = options?.estimates === false ? formatCost(turn.totals.cost) : formatMoney(turn.totals.cost, turn.totals.listCost) ?? formatCost(turn.totals.cost);
|
|
1628
1837
|
const hit = formatPercent(display.prompt > 0 ? display.cached / display.prompt : undefined).replace(/\.0%$/, "%");
|
|
1629
1838
|
const tps = turn.tps === undefined ? undefined : formatTpsCompact(turn.tps);
|
|
1630
1839
|
const suffix = turn.drops.length > 0 ? " \xB7 \u26A0" : "";
|
|
@@ -1696,6 +1905,7 @@ var STEP_COLUMNS = `message_id AS messageID, session_id AS sessionID, provider_i
|
|
|
1696
1905
|
model_id AS modelID, variant,
|
|
1697
1906
|
COALESCE(input_tokens, 0) AS input, COALESCE(cache_read, 0) AS cached, COALESCE(cache_write, 0) AS cacheWrite,
|
|
1698
1907
|
COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, COALESCE(cost, 0) AS cost,
|
|
1908
|
+
COALESCE(list_cost, 0) AS listCost,
|
|
1699
1909
|
created_at AS createdAt, streamed_at AS streamedAt, completed_at AS completedAt, ${STEP_AT} AS at`;
|
|
1700
1910
|
var STEP_OPTIONAL = ["providerID", "modelID", "variant", "createdAt", "streamedAt", "completedAt"];
|
|
1701
1911
|
var PAIR_COLUMNS = STEP_COLUMNS.replace("COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, ", "");
|
|
@@ -1755,7 +1965,7 @@ function pairsOf(rows) {
|
|
|
1755
1965
|
return pairs;
|
|
1756
1966
|
}
|
|
1757
1967
|
function usageOf(steps) {
|
|
1758
|
-
const usage = { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0 };
|
|
1968
|
+
const usage = { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 };
|
|
1759
1969
|
for (const step of steps) {
|
|
1760
1970
|
usage.steps += 1;
|
|
1761
1971
|
usage.input += step.input;
|
|
@@ -1764,6 +1974,7 @@ function usageOf(steps) {
|
|
|
1764
1974
|
usage.output += step.output;
|
|
1765
1975
|
usage.reasoning += step.reasoning;
|
|
1766
1976
|
usage.cost += step.cost;
|
|
1977
|
+
usage.listCost += step.listCost;
|
|
1767
1978
|
}
|
|
1768
1979
|
return usage;
|
|
1769
1980
|
}
|
|
@@ -1795,7 +2006,7 @@ function groupedRows(db, options) {
|
|
|
1795
2006
|
return normalize(rows, STEP_OPTIONAL);
|
|
1796
2007
|
}
|
|
1797
2008
|
function timingOf(step) {
|
|
1798
|
-
const wall = step.createdAt !== undefined && step.completedAt !== undefined ? step.completedAt - step.createdAt : undefined;
|
|
2009
|
+
const wall = step.createdAt !== undefined && step.completedAt !== undefined ? Math.max(0, step.completedAt - step.createdAt) : undefined;
|
|
1799
2010
|
const stream = step.createdAt !== undefined && step.streamedAt !== undefined && step.streamedAt > step.createdAt ? step.streamedAt - step.createdAt : undefined;
|
|
1800
2011
|
return { wall, stream, tps: tokensPerSecond(step.output + step.reasoning, step.createdAt, step.streamedAt) };
|
|
1801
2012
|
}
|
|
@@ -2062,7 +2273,14 @@ function groupValues(steps) {
|
|
|
2062
2273
|
}
|
|
2063
2274
|
function providerOf(steps, models) {
|
|
2064
2275
|
const values = groupValues(steps);
|
|
2065
|
-
|
|
2276
|
+
let firstAt;
|
|
2277
|
+
let lastAt;
|
|
2278
|
+
for (const step of steps) {
|
|
2279
|
+
if (firstAt === undefined || step.at < firstAt)
|
|
2280
|
+
firstAt = step.at;
|
|
2281
|
+
if (lastAt === undefined || step.at > lastAt)
|
|
2282
|
+
lastAt = step.at;
|
|
2283
|
+
}
|
|
2066
2284
|
return {
|
|
2067
2285
|
provider: steps[0].providerID,
|
|
2068
2286
|
models: models.split("\x00"),
|
|
@@ -2071,8 +2289,8 @@ function providerOf(steps, models) {
|
|
|
2071
2289
|
cache: values.cache,
|
|
2072
2290
|
tps: values.tps,
|
|
2073
2291
|
wall: values.wall,
|
|
2074
|
-
firstAt
|
|
2075
|
-
lastAt
|
|
2292
|
+
firstAt,
|
|
2293
|
+
lastAt
|
|
2076
2294
|
};
|
|
2077
2295
|
}
|
|
2078
2296
|
var modelNames = (steps) => [...new Set(steps.map((step) => modelKey(step.modelID ?? "(unknown)", step.variant)))].map((key) => modelLabel(key.slice(0, key.indexOf("#")), key.slice(key.indexOf("#") + 1) || undefined)).join("\x00");
|
|
@@ -2108,6 +2326,14 @@ function isoWeek(date) {
|
|
|
2108
2326
|
const week = 1 + Math.round((thursday.getTime() - firstThursday.getTime()) / (7 * 24 * 60 * 60 * 1000));
|
|
2109
2327
|
return { year: thursday.getFullYear(), week, monday };
|
|
2110
2328
|
}
|
|
2329
|
+
function periodEnd(at, granularity) {
|
|
2330
|
+
const date = new Date(at);
|
|
2331
|
+
if (granularity === "month")
|
|
2332
|
+
return new Date(date.getFullYear(), date.getMonth() + 1, 1).getTime();
|
|
2333
|
+
if (granularity === "week")
|
|
2334
|
+
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 7).getTime();
|
|
2335
|
+
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1).getTime();
|
|
2336
|
+
}
|
|
2111
2337
|
function periodStart(at, granularity) {
|
|
2112
2338
|
const date = new Date(at);
|
|
2113
2339
|
const pad = (value) => String(value).padStart(2, "0");
|
|
@@ -2123,11 +2349,11 @@ function periodStart(at, granularity) {
|
|
|
2123
2349
|
const key = `${start.getFullYear()}-${pad(start.getMonth() + 1)}-${pad(start.getDate())}`;
|
|
2124
2350
|
return { key, label: key, start: start.getTime() };
|
|
2125
2351
|
}
|
|
2126
|
-
function periodsOf(rows, granularity) {
|
|
2127
|
-
const
|
|
2352
|
+
function periodsOf(rows, granularity, otherRows = []) {
|
|
2353
|
+
const byKey = new Map;
|
|
2128
2354
|
for (const [key, steps] of groupBy(rows, (step) => periodStart(step.at, granularity).key)) {
|
|
2129
2355
|
const period = periodStart(steps[0].at, granularity);
|
|
2130
|
-
|
|
2356
|
+
byKey.set(key, {
|
|
2131
2357
|
key,
|
|
2132
2358
|
label: period.label,
|
|
2133
2359
|
at: period.start,
|
|
@@ -2137,7 +2363,27 @@ function periodsOf(rows, granularity) {
|
|
|
2137
2363
|
cache: cacheStatsOfSteps(steps)
|
|
2138
2364
|
});
|
|
2139
2365
|
}
|
|
2140
|
-
|
|
2366
|
+
for (const [key, group] of groupBy(otherRows, (row) => periodStart(row.at, granularity).key)) {
|
|
2367
|
+
const cost = group.reduce((sum, row) => sum + row.cost, 0);
|
|
2368
|
+
const existing = byKey.get(key);
|
|
2369
|
+
if (existing !== undefined) {
|
|
2370
|
+
existing.usage.cost += cost;
|
|
2371
|
+
existing.otherCost = (existing.otherCost ?? 0) + cost;
|
|
2372
|
+
continue;
|
|
2373
|
+
}
|
|
2374
|
+
const period = periodStart(group[0].at, granularity);
|
|
2375
|
+
byKey.set(key, {
|
|
2376
|
+
key,
|
|
2377
|
+
label: period.label,
|
|
2378
|
+
at: period.start,
|
|
2379
|
+
steps: 0,
|
|
2380
|
+
sessions: new Set(group.map((row) => row.sessionID)).size,
|
|
2381
|
+
usage: { ...usageOf([]), cost },
|
|
2382
|
+
cache: cacheStatsOfSteps([]),
|
|
2383
|
+
otherCost: cost
|
|
2384
|
+
});
|
|
2385
|
+
}
|
|
2386
|
+
return [...byKey.values()].sort((left, right) => left.at - right.at);
|
|
2141
2387
|
}
|
|
2142
2388
|
|
|
2143
2389
|
// src/panel-build.ts
|
|
@@ -2188,11 +2434,12 @@ function buildPanel(request) {
|
|
|
2188
2434
|
}
|
|
2189
2435
|
function build(request) {
|
|
2190
2436
|
const { db, view, now, sessionStart, width } = request;
|
|
2437
|
+
const estimates = request.estimates !== false;
|
|
2191
2438
|
const scoped = request.range === "session" && request.sessionID !== "";
|
|
2192
2439
|
const range = scoped ? undefined : request.range === "session" ? sessionStart === undefined ? undefined : { from: sessionStart } : rangeForRequest(request.range, now);
|
|
2193
2440
|
const filters = scoped ? { ...request.filters, sessionID: request.sessionID } : request.filters;
|
|
2194
2441
|
if (request.detail !== undefined)
|
|
2195
|
-
return buildDetail(request, range, filters);
|
|
2442
|
+
return buildDetail(request, range, filters, estimates);
|
|
2196
2443
|
switch (view) {
|
|
2197
2444
|
case "overview": {
|
|
2198
2445
|
const usage = overview(db, range, filters);
|
|
@@ -2204,21 +2451,22 @@ function build(request) {
|
|
|
2204
2451
|
session: sessionUsage,
|
|
2205
2452
|
...children.length > 0 ? { subagents: children } : {},
|
|
2206
2453
|
range: request.range,
|
|
2207
|
-
activity: activityOf(db, range, now),
|
|
2208
|
-
coverage: coverageOf(db, { range, filters })
|
|
2454
|
+
activity: activityOf(db, range, filters, now),
|
|
2455
|
+
coverage: coverageOf(db, { range, filters }),
|
|
2456
|
+
estimates
|
|
2209
2457
|
}, width);
|
|
2210
2458
|
}
|
|
2211
2459
|
case "models": {
|
|
2212
|
-
const rows = sortModels(models(db, range, filters), request.sort, request.sortDesc);
|
|
2460
|
+
const rows = sortModels(models(db, range, filters), request.sort, request.sortDesc, estimates);
|
|
2213
2461
|
const pairs = cachePairs(db, { range, filters });
|
|
2214
2462
|
const switches = switchesOf(pairs);
|
|
2215
2463
|
return modelsLines(rows, width, {
|
|
2216
2464
|
cache: cacheByModel(pairs),
|
|
2217
2465
|
switches: switchesByModel(switches.rows)
|
|
2218
|
-
}, 40);
|
|
2466
|
+
}, 40, estimates);
|
|
2219
2467
|
}
|
|
2220
2468
|
case "providers":
|
|
2221
|
-
return providerSummaryLines(sortProviders(providerSummaryOf(stepRows(db, { range, filters })), request.sort, request.sortDesc), width, 40);
|
|
2469
|
+
return providerSummaryLines(sortProviders(providerSummaryOf(stepRows(db, { range, filters })), request.sort, request.sortDesc, estimates), width, 40, estimates);
|
|
2222
2470
|
case "cache": {
|
|
2223
2471
|
const pairs = cachePairs(db, { range, filters });
|
|
2224
2472
|
return cacheLines({
|
|
@@ -2228,28 +2476,36 @@ function build(request) {
|
|
|
2228
2476
|
models: topCacheModels(pairs)
|
|
2229
2477
|
}, width);
|
|
2230
2478
|
}
|
|
2231
|
-
case "periods":
|
|
2232
|
-
|
|
2479
|
+
case "periods": {
|
|
2480
|
+
const rows = periodsOf(stepRows(db, { range, filters }), request.granularity, otherUsageRows(db, range, filters));
|
|
2481
|
+
const sessions = overview(db, range, filters).sessions;
|
|
2482
|
+
return periodLines(rows, width, request.granularity, 40, estimates, sessions);
|
|
2483
|
+
}
|
|
2233
2484
|
case "latency": {
|
|
2234
2485
|
const timings = timingRows(db, { range, filters });
|
|
2235
2486
|
const by = filters.modelID !== undefined ? "provider" : "model";
|
|
2236
|
-
return latencyLines(latencyOf(timings), width, sortLatency(latencyGroupsOf(timings, by), request.sort, request.sortDesc), 14);
|
|
2487
|
+
return latencyLines(latencyOf(timings), width, sortLatency(latencyGroupsOf(timings, by), request.sort, request.sortDesc), 14, estimates);
|
|
2237
2488
|
}
|
|
2238
2489
|
case "sessions": {
|
|
2239
|
-
const rows = sortSessions(sessions(db, { range, filters, limit: 200 }), request.sort, request.sortDesc);
|
|
2490
|
+
const rows = sortSessions(sessions(db, { range, filters, limit: 200 }), request.sort, request.sortDesc, estimates);
|
|
2240
2491
|
const child = rows.filter((row) => row.parentID !== undefined && rows.some((parent) => parent.sessionID === row.parentID));
|
|
2241
2492
|
return sessionsLines(rows, width, {
|
|
2242
2493
|
limit: 20,
|
|
2243
|
-
|
|
2494
|
+
estimates,
|
|
2495
|
+
rollup: {
|
|
2496
|
+
subagentSteps: child.reduce((sum, row) => sum + row.steps, 0),
|
|
2497
|
+
subagentCost: child.reduce((sum, row) => sum + row.cost, 0),
|
|
2498
|
+
subagentListCost: child.reduce((sum, row) => sum + row.listCost, 0)
|
|
2499
|
+
}
|
|
2244
2500
|
});
|
|
2245
2501
|
}
|
|
2246
2502
|
case "db":
|
|
2247
|
-
return request.database === undefined ? [{ text: "the database location is unavailable to this panel", tone: "warning" }] : dbLines({ info: request.database, busy: request.busy, now }, width);
|
|
2503
|
+
return request.database === undefined ? [{ text: "the database location is unavailable to this panel", tone: "warning" }] : dbLines({ info: request.database, busy: request.busy, now, estimates }, width);
|
|
2248
2504
|
case "turns": {
|
|
2249
2505
|
const sessionID = request.turnsScope === "session" ? request.sessionID : undefined;
|
|
2250
|
-
const rows = sortTurns(turns(db, { sessionID, range, filters, limit: 300 }), request.sort, request.sortDesc);
|
|
2506
|
+
const rows = sortTurns(turns(db, { sessionID, range, filters, limit: 300 }), request.sort, request.sortDesc, estimates);
|
|
2251
2507
|
const titles = request.turnsScope === "all" ? new Map(sessions(db, { range, filters, limit: 200 }).map((row) => [row.sessionID, row.title ?? row.sessionID])) : undefined;
|
|
2252
|
-
return turnsLines(rows.slice(0, 60), width, { ...request.format, sessionTitles: titles });
|
|
2508
|
+
return turnsLines(rows.slice(0, 60), width, { ...request.format, estimates, sessionTitles: titles });
|
|
2253
2509
|
}
|
|
2254
2510
|
}
|
|
2255
2511
|
}
|
|
@@ -2268,7 +2524,7 @@ function rangeForRequest(key, now) {
|
|
|
2268
2524
|
return;
|
|
2269
2525
|
}
|
|
2270
2526
|
}
|
|
2271
|
-
function buildDetail(request, range, filters) {
|
|
2527
|
+
function buildDetail(request, range, filters, estimates) {
|
|
2272
2528
|
const row = request.detail;
|
|
2273
2529
|
const db = request.db;
|
|
2274
2530
|
const width = request.width;
|
|
@@ -2285,16 +2541,16 @@ function buildDetail(request, range, filters) {
|
|
|
2285
2541
|
tone: "muted"
|
|
2286
2542
|
},
|
|
2287
2543
|
{ text: "", tone: "muted" },
|
|
2288
|
-
...providerLines(providerBreakdownOf(steps), width, 40),
|
|
2544
|
+
...providerLines(providerBreakdownOf(steps), width, 40, estimates),
|
|
2289
2545
|
{ text: "", tone: "muted" },
|
|
2290
|
-
...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, "provider"), 14),
|
|
2546
|
+
...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, "provider"), 14, estimates),
|
|
2291
2547
|
{ text: "", tone: "muted" },
|
|
2292
2548
|
back
|
|
2293
2549
|
];
|
|
2294
2550
|
}
|
|
2295
2551
|
if (row.kind === "session" || row.kind === "turn") {
|
|
2296
2552
|
const rows = turns(db, { sessionID: row.value, limit: 80 });
|
|
2297
|
-
return [head, { text: "", tone: "muted" }, ...turnsLines(rows, width, request.format), { text: "", tone: "muted" }, back];
|
|
2553
|
+
return [head, { text: "", tone: "muted" }, ...turnsLines(rows, width, { ...request.format, estimates }), { text: "", tone: "muted" }, back];
|
|
2298
2554
|
}
|
|
2299
2555
|
if (row.kind === "provider") {
|
|
2300
2556
|
const scoped = { ...filters, provider: row.value };
|
|
@@ -2307,9 +2563,9 @@ function buildDetail(request, range, filters) {
|
|
|
2307
2563
|
tone: "muted"
|
|
2308
2564
|
},
|
|
2309
2565
|
{ text: "", tone: "muted" },
|
|
2310
|
-
...providerLines(providerBreakdownOf(steps), width, 40),
|
|
2566
|
+
...providerLines(providerBreakdownOf(steps), width, 40, estimates),
|
|
2311
2567
|
{ text: "", tone: "muted" },
|
|
2312
|
-
...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, "model"), 14),
|
|
2568
|
+
...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, "model"), 14, estimates),
|
|
2313
2569
|
{ text: "", tone: "muted" },
|
|
2314
2570
|
back
|
|
2315
2571
|
];
|
|
@@ -2317,11 +2573,14 @@ function buildDetail(request, range, filters) {
|
|
|
2317
2573
|
if (row.kind === "period") {
|
|
2318
2574
|
const periods = periodsOf(stepRows(db, { range, filters }), request.granularity);
|
|
2319
2575
|
const period = periods.find((entry) => entry.key === row.value);
|
|
2576
|
+
const from = period === undefined ? 0 : Math.max(period.at, range?.from ?? period.at);
|
|
2577
|
+
const to = period === undefined ? 0 : Math.min(periodEnd(period.at, request.granularity), range?.to ?? Number.POSITIVE_INFINITY);
|
|
2578
|
+
const steps = period === undefined ? [] : stepRows(db, { range: { from, to }, filters });
|
|
2320
2579
|
return [
|
|
2321
2580
|
head,
|
|
2322
2581
|
{ text: `${formatCount(period?.steps ?? 0)} steps`, tone: "muted" },
|
|
2323
2582
|
{ text: "", tone: "muted" },
|
|
2324
|
-
...providerSummaryLines(providerSummaryOf(
|
|
2583
|
+
...providerSummaryLines(providerSummaryOf(steps), width, 40, estimates),
|
|
2325
2584
|
{ text: "", tone: "muted" },
|
|
2326
2585
|
back
|
|
2327
2586
|
];
|
|
@@ -2331,28 +2590,32 @@ function buildDetail(request, range, filters) {
|
|
|
2331
2590
|
function percent(value) {
|
|
2332
2591
|
return value === undefined ? "\u2013" : `${(value * 100).toFixed(1)}%`;
|
|
2333
2592
|
}
|
|
2334
|
-
function sortModels(rows, sort, desc) {
|
|
2335
|
-
const sign = desc ?
|
|
2593
|
+
function sortModels(rows, sort, desc, estimates = true) {
|
|
2594
|
+
const sign = desc ? 1 : -1;
|
|
2336
2595
|
const pick = (model) => {
|
|
2337
2596
|
if (sort === "cached")
|
|
2338
2597
|
return model.totals.cached;
|
|
2598
|
+
if (sort === "hit") {
|
|
2599
|
+
const prompt = model.totals.input + model.totals.cached + model.totals.cacheWrite;
|
|
2600
|
+
return prompt > 0 ? model.totals.cached / prompt : -1;
|
|
2601
|
+
}
|
|
2339
2602
|
if (sort === "out")
|
|
2340
|
-
return model.totals.output;
|
|
2603
|
+
return model.totals.output + model.totals.reasoning;
|
|
2341
2604
|
if (sort === "cost")
|
|
2342
|
-
return model.totals.cost;
|
|
2605
|
+
return estimates ? spend(model.totals) : model.totals.cost;
|
|
2343
2606
|
return model.totals.steps;
|
|
2344
2607
|
};
|
|
2345
2608
|
return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
|
|
2346
2609
|
}
|
|
2347
|
-
function sortProviders(rows, sort, desc) {
|
|
2348
|
-
const sign = desc ?
|
|
2610
|
+
function sortProviders(rows, sort, desc, estimates = true) {
|
|
2611
|
+
const sign = desc ? 1 : -1;
|
|
2349
2612
|
const pick = (row) => {
|
|
2350
2613
|
if (sort === "cached")
|
|
2351
2614
|
return row.cache.cached;
|
|
2352
2615
|
if (sort === "hit")
|
|
2353
2616
|
return row.cache.hit ?? -1;
|
|
2354
2617
|
if (sort === "cost")
|
|
2355
|
-
return row.usage.cost;
|
|
2618
|
+
return estimates ? spend(row.usage) : row.usage.cost;
|
|
2356
2619
|
if (sort === "share")
|
|
2357
2620
|
return row.share;
|
|
2358
2621
|
if (sort === "tps")
|
|
@@ -2362,7 +2625,7 @@ function sortProviders(rows, sort, desc) {
|
|
|
2362
2625
|
return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
|
|
2363
2626
|
}
|
|
2364
2627
|
function sortLatency(rows, sort, desc) {
|
|
2365
|
-
const sign = desc ?
|
|
2628
|
+
const sign = desc ? 1 : -1;
|
|
2366
2629
|
const pick = (row) => {
|
|
2367
2630
|
if (sort === "tps")
|
|
2368
2631
|
return row.tps.p50 ?? -1;
|
|
@@ -2372,26 +2635,26 @@ function sortLatency(rows, sort, desc) {
|
|
|
2372
2635
|
};
|
|
2373
2636
|
return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
|
|
2374
2637
|
}
|
|
2375
|
-
function sortSessions(rows, sort, desc) {
|
|
2376
|
-
const sign = desc ?
|
|
2638
|
+
function sortSessions(rows, sort, desc, estimates = true) {
|
|
2639
|
+
const sign = desc ? 1 : -1;
|
|
2377
2640
|
const pick = (row) => {
|
|
2378
2641
|
if (sort === "steps")
|
|
2379
2642
|
return row.steps;
|
|
2380
2643
|
if (sort === "cached")
|
|
2381
2644
|
return row.cached;
|
|
2382
2645
|
if (sort === "cost")
|
|
2383
|
-
return row.cost;
|
|
2646
|
+
return estimates ? spend(row) : row.cost;
|
|
2384
2647
|
return row.lastAt ?? 0;
|
|
2385
2648
|
};
|
|
2386
2649
|
return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
|
|
2387
2650
|
}
|
|
2388
|
-
function sortTurns(rows, sort, desc) {
|
|
2389
|
-
const sign = desc ?
|
|
2651
|
+
function sortTurns(rows, sort, desc, estimates = true) {
|
|
2652
|
+
const sign = desc ? 1 : -1;
|
|
2390
2653
|
const pick = (row) => {
|
|
2391
2654
|
if (sort === "cost")
|
|
2392
|
-
return row.totals.cost;
|
|
2655
|
+
return estimates ? spend(row.totals) : row.totals.cost;
|
|
2393
2656
|
if (sort === "tokens")
|
|
2394
|
-
return row.totals.cached + row.totals.input + row.totals.output;
|
|
2657
|
+
return row.totals.cached + row.totals.input + row.totals.cacheWrite + row.totals.output + row.totals.reasoning;
|
|
2395
2658
|
return row.endAt ?? 0;
|
|
2396
2659
|
};
|
|
2397
2660
|
return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
|
|
@@ -2409,17 +2672,17 @@ function switchesByModel(rows) {
|
|
|
2409
2672
|
function topCacheModels(pairs) {
|
|
2410
2673
|
return cacheStatsByModel(pairs).slice(0, 10).map((row) => ({ usage: { modelID: row.modelID, variant: row.variant }, cache: row.cache }));
|
|
2411
2674
|
}
|
|
2412
|
-
function activityOf(db, range, now) {
|
|
2413
|
-
const
|
|
2675
|
+
function activityOf(db, range, filters, now) {
|
|
2676
|
+
const filter = buildWhere(range, filters, STEP_TIME);
|
|
2677
|
+
const earliest = db.query(`SELECT MIN(${STEP_TIME}) AS at FROM steps ${filter.where}`).get(...filter.params);
|
|
2414
2678
|
const from = range?.from ?? earliest?.at ?? 0;
|
|
2415
2679
|
const to = range?.to ?? now;
|
|
2416
2680
|
const span = Math.max(1, to - from);
|
|
2417
2681
|
const ladder = [3600000, 3 * 3600000, 6 * 3600000, 12 * 3600000, 86400000, 3 * 86400000, 7 * 86400000, 30 * 86400000];
|
|
2418
2682
|
const bucket = ladder.find((size) => span / size <= 48) ?? ladder[ladder.length - 1];
|
|
2419
|
-
const rows = db.query(`SELECT CAST(
|
|
2420
|
-
FROM steps
|
|
2421
|
-
|
|
2422
|
-
GROUP BY bucket ORDER BY bucket`).all(bucket, from);
|
|
2683
|
+
const rows = db.query(`SELECT CAST(${STEP_TIME} / ? AS INTEGER) AS bucket, COUNT(*) AS steps
|
|
2684
|
+
FROM steps ${filter.where}
|
|
2685
|
+
GROUP BY bucket ORDER BY bucket`).all(bucket, ...filter.params);
|
|
2423
2686
|
if (rows.length === 0)
|
|
2424
2687
|
return [];
|
|
2425
2688
|
const first = Math.floor(from / bucket);
|
|
@@ -2480,7 +2743,7 @@ function ensureRegularFile(path) {
|
|
|
2480
2743
|
}
|
|
2481
2744
|
|
|
2482
2745
|
// src/stats/db.ts
|
|
2483
|
-
var SCHEMA_VERSION =
|
|
2746
|
+
var SCHEMA_VERSION = 11;
|
|
2484
2747
|
var LABEL_LIMIT = 4 * TEXT_LIMIT;
|
|
2485
2748
|
var SCHEMA = `
|
|
2486
2749
|
CREATE TABLE IF NOT EXISTS meta (
|
|
@@ -2518,6 +2781,7 @@ CREATE TABLE IF NOT EXISTS steps (
|
|
|
2518
2781
|
cache_read INTEGER NOT NULL DEFAULT 0,
|
|
2519
2782
|
cache_write INTEGER NOT NULL DEFAULT 0,
|
|
2520
2783
|
cost REAL NOT NULL DEFAULT 0,
|
|
2784
|
+
list_cost REAL,
|
|
2521
2785
|
created_at INTEGER,
|
|
2522
2786
|
streamed_at INTEGER,
|
|
2523
2787
|
completed_at INTEGER,
|
|
@@ -2544,8 +2808,28 @@ CREATE TABLE IF NOT EXISTS events (
|
|
|
2544
2808
|
);
|
|
2545
2809
|
CREATE INDEX IF NOT EXISTS events_session ON events(session_id, at);
|
|
2546
2810
|
CREATE INDEX IF NOT EXISTS events_kind ON events(kind, at);
|
|
2811
|
+
|
|
2812
|
+
-- Usage the host reports with no assistant step of its own: the compaction
|
|
2813
|
+
-- summarisation and the session-title generation. The host publishes it as
|
|
2814
|
+
-- session.usage.recorded with a source other than generate, and includes it in
|
|
2815
|
+
-- the session's own cost/token totals. Primary key is the host event ID, so a
|
|
2816
|
+
-- replayed event never counts twice.
|
|
2817
|
+
CREATE TABLE IF NOT EXISTS usage (
|
|
2818
|
+
id TEXT PRIMARY KEY,
|
|
2819
|
+
session_id TEXT NOT NULL,
|
|
2820
|
+
source TEXT NOT NULL,
|
|
2821
|
+
at INTEGER,
|
|
2822
|
+
cost REAL NOT NULL DEFAULT 0,
|
|
2823
|
+
input_tokens INTEGER NOT NULL DEFAULT 0,
|
|
2824
|
+
output_tokens INTEGER NOT NULL DEFAULT 0,
|
|
2825
|
+
reasoning_tokens INTEGER NOT NULL DEFAULT 0,
|
|
2826
|
+
cache_read INTEGER NOT NULL DEFAULT 0,
|
|
2827
|
+
cache_write INTEGER NOT NULL DEFAULT 0
|
|
2828
|
+
);
|
|
2829
|
+
CREATE INDEX IF NOT EXISTS usage_session_at ON usage(session_id, at);
|
|
2830
|
+
CREATE INDEX IF NOT EXISTS usage_at ON usage(at);
|
|
2547
2831
|
`;
|
|
2548
|
-
var TABLES = ["sessions", "prompts", "events", "steps"];
|
|
2832
|
+
var TABLES = ["sessions", "prompts", "events", "steps", "usage"];
|
|
2549
2833
|
function jsonText(value) {
|
|
2550
2834
|
if (value === undefined || value === null)
|
|
2551
2835
|
return null;
|
|
@@ -2557,6 +2841,15 @@ function jsonText(value) {
|
|
|
2557
2841
|
return null;
|
|
2558
2842
|
}
|
|
2559
2843
|
}
|
|
2844
|
+
function finite(value) {
|
|
2845
|
+
return typeof value === "number" && Number.isFinite(value) ? value : 0;
|
|
2846
|
+
}
|
|
2847
|
+
function tokenCount(value) {
|
|
2848
|
+
return Math.max(0, Math.floor(finite(value)));
|
|
2849
|
+
}
|
|
2850
|
+
function timestamp(value) {
|
|
2851
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
2852
|
+
}
|
|
2560
2853
|
var REMOVED_COLUMNS = ["provider_state", "upstream", "upstream_source", "upstream_model", "tps", "router"];
|
|
2561
2854
|
var REMOVED_EVENT_KINDS = ["execution", "step-failed", "model-selected", "usage-recorded"];
|
|
2562
2855
|
function dropUnused(db) {
|
|
@@ -2579,8 +2872,62 @@ function dropUnused(db) {
|
|
|
2579
2872
|
db.exec(`DELETE FROM events WHERE kind IN (${kinds})`);
|
|
2580
2873
|
}
|
|
2581
2874
|
}
|
|
2875
|
+
function addMissing(db) {
|
|
2876
|
+
const columns = new Set(db.query("PRAGMA table_info(steps)").all().map((column) => column.name));
|
|
2877
|
+
if (columns.size > 0 && !columns.has("list_cost")) {
|
|
2878
|
+
db.exec("ALTER TABLE steps ADD COLUMN list_cost REAL");
|
|
2879
|
+
}
|
|
2880
|
+
}
|
|
2881
|
+
function dedupeEvents(db) {
|
|
2882
|
+
const table = db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'events'").get();
|
|
2883
|
+
if (table === null)
|
|
2884
|
+
return;
|
|
2885
|
+
db.exec(`DELETE FROM events
|
|
2886
|
+
WHERE kind = 'compaction' AND message_id IS NULL
|
|
2887
|
+
AND rowid NOT IN (
|
|
2888
|
+
SELECT MIN(rowid) FROM events
|
|
2889
|
+
WHERE kind = 'compaction' AND message_id IS NULL
|
|
2890
|
+
GROUP BY session_id, at, data
|
|
2891
|
+
)`);
|
|
2892
|
+
db.exec(`DELETE FROM events
|
|
2893
|
+
WHERE message_id IS NOT NULL
|
|
2894
|
+
AND rowid NOT IN (
|
|
2895
|
+
SELECT MIN(rowid) FROM events
|
|
2896
|
+
WHERE message_id IS NOT NULL
|
|
2897
|
+
GROUP BY kind, message_id
|
|
2898
|
+
)`);
|
|
2899
|
+
}
|
|
2900
|
+
function addEventKey(db) {
|
|
2901
|
+
const table = db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'events'").get();
|
|
2902
|
+
if (table === null)
|
|
2903
|
+
return;
|
|
2904
|
+
db.exec("CREATE UNIQUE INDEX IF NOT EXISTS events_kind_message ON events(kind, message_id) WHERE message_id IS NOT NULL");
|
|
2905
|
+
}
|
|
2906
|
+
function backfillCompactionUsage(db) {
|
|
2907
|
+
const tables = new Set(db.query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((row) => row.name));
|
|
2908
|
+
if (!tables.has("events") || !tables.has("usage"))
|
|
2909
|
+
return;
|
|
2910
|
+
db.exec(`INSERT OR IGNORE INTO usage (
|
|
2911
|
+
id, session_id, source, at, cost,
|
|
2912
|
+
input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
|
|
2913
|
+
)
|
|
2914
|
+
SELECT 'compaction:' || rowid, session_id, 'compaction', at,
|
|
2915
|
+
MAX(0, COALESCE(CAST(json_extract(data, '$.cost') AS REAL), 0)),
|
|
2916
|
+
MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.input'), 0) AS INTEGER)),
|
|
2917
|
+
MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.output'), 0) AS INTEGER)),
|
|
2918
|
+
MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.reasoning'), 0) AS INTEGER)),
|
|
2919
|
+
MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.cache.read'), 0) AS INTEGER)),
|
|
2920
|
+
MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.cache.write'), 0) AS INTEGER))
|
|
2921
|
+
FROM events
|
|
2922
|
+
WHERE kind = 'compaction' AND message_id IS NULL AND at IS NOT NULL AND data IS NOT NULL
|
|
2923
|
+
AND json_valid(data)`);
|
|
2924
|
+
}
|
|
2582
2925
|
function migrate(db) {
|
|
2583
2926
|
dropUnused(db);
|
|
2927
|
+
addMissing(db);
|
|
2928
|
+
dedupeEvents(db);
|
|
2929
|
+
backfillCompactionUsage(db);
|
|
2930
|
+
addEventKey(db);
|
|
2584
2931
|
}
|
|
2585
2932
|
var POSIX = process.platform !== "win32";
|
|
2586
2933
|
function hardenDirectory(path) {
|
|
@@ -2641,13 +2988,15 @@ function openStatsDbWrite(path) {
|
|
|
2641
2988
|
return db;
|
|
2642
2989
|
}
|
|
2643
2990
|
function recordStep(db, record) {
|
|
2991
|
+
const cost = Math.max(0, finite(record.cost));
|
|
2992
|
+
const listCost = cost <= 0 && typeof record.listCost === "number" && Number.isFinite(record.listCost) && record.listCost >= 0 ? record.listCost : null;
|
|
2644
2993
|
db.query(`INSERT INTO steps (
|
|
2645
2994
|
message_id, session_id, parent_id, provider_id, model_id, variant,
|
|
2646
|
-
input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost,
|
|
2995
|
+
input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost, list_cost,
|
|
2647
2996
|
created_at, streamed_at, completed_at, finish, recorded_at
|
|
2648
2997
|
) VALUES (
|
|
2649
2998
|
$messageID, $sessionID, $parentID, $providerID, $modelID, $variant,
|
|
2650
|
-
$input, $output, $reasoning, $cacheRead, $cacheWrite, $cost,
|
|
2999
|
+
$input, $output, $reasoning, $cacheRead, $cacheWrite, $cost, $listCost,
|
|
2651
3000
|
$createdAt, $streamedAt, $completedAt, $finish, $recordedAt
|
|
2652
3001
|
)
|
|
2653
3002
|
ON CONFLICT(message_id) DO UPDATE SET
|
|
@@ -2662,6 +3011,9 @@ function recordStep(db, record) {
|
|
|
2662
3011
|
cache_read = excluded.cache_read,
|
|
2663
3012
|
cache_write = excluded.cache_write,
|
|
2664
3013
|
cost = excluded.cost,
|
|
3014
|
+
-- A step that starts being charged loses its estimate; an estimate is
|
|
3015
|
+
-- kept when a replayed event arrives without a price table.
|
|
3016
|
+
list_cost = CASE WHEN excluded.cost > 0 THEN NULL ELSE COALESCE(excluded.list_cost, steps.list_cost) END,
|
|
2665
3017
|
created_at = COALESCE(excluded.created_at, steps.created_at),
|
|
2666
3018
|
streamed_at = COALESCE(excluded.streamed_at, steps.streamed_at),
|
|
2667
3019
|
completed_at = COALESCE(excluded.completed_at, steps.completed_at),
|
|
@@ -2673,17 +3025,40 @@ function recordStep(db, record) {
|
|
|
2673
3025
|
$providerID: record.providerID !== undefined && isToken(record.providerID) ? record.providerID : null,
|
|
2674
3026
|
$modelID: record.modelID ?? null,
|
|
2675
3027
|
$variant: record.variant ?? null,
|
|
2676
|
-
$input: record.input
|
|
2677
|
-
$output: record.output
|
|
2678
|
-
$reasoning: record.reasoning
|
|
2679
|
-
$cacheRead: record.cacheRead
|
|
2680
|
-
$cacheWrite: record.cacheWrite
|
|
2681
|
-
$cost:
|
|
2682
|
-
$
|
|
2683
|
-
$
|
|
2684
|
-
$
|
|
3028
|
+
$input: tokenCount(record.input),
|
|
3029
|
+
$output: tokenCount(record.output),
|
|
3030
|
+
$reasoning: tokenCount(record.reasoning),
|
|
3031
|
+
$cacheRead: tokenCount(record.cacheRead),
|
|
3032
|
+
$cacheWrite: tokenCount(record.cacheWrite),
|
|
3033
|
+
$cost: cost,
|
|
3034
|
+
$listCost: listCost,
|
|
3035
|
+
$createdAt: timestamp(record.createdAt),
|
|
3036
|
+
$streamedAt: timestamp(record.streamedAt),
|
|
3037
|
+
$completedAt: timestamp(record.completedAt),
|
|
2685
3038
|
$finish: record.finish === undefined ? null : sanitizeLabel(record.finish, 64),
|
|
2686
|
-
$recordedAt: record.recordedAt ?? Date.now()
|
|
3039
|
+
$recordedAt: timestamp(record.recordedAt) ?? Date.now()
|
|
3040
|
+
});
|
|
3041
|
+
}
|
|
3042
|
+
function recordUsage(db, record) {
|
|
3043
|
+
if (typeof record.id !== "string" || record.id === "")
|
|
3044
|
+
return;
|
|
3045
|
+
if (typeof record.sessionID !== "string" || record.sessionID === "")
|
|
3046
|
+
return;
|
|
3047
|
+
db.query(`INSERT INTO usage (
|
|
3048
|
+
id, session_id, source, at, cost, input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
|
|
3049
|
+
) VALUES (
|
|
3050
|
+
$id, $sessionID, $source, $at, $cost, $input, $output, $reasoning, $cacheRead, $cacheWrite
|
|
3051
|
+
) ON CONFLICT(id) DO NOTHING`).run({
|
|
3052
|
+
$id: record.id,
|
|
3053
|
+
$sessionID: record.sessionID,
|
|
3054
|
+
$source: sanitizeLabel(record.source, 64),
|
|
3055
|
+
$at: timestamp(record.at) ?? Date.now(),
|
|
3056
|
+
$cost: Math.max(0, finite(record.cost)),
|
|
3057
|
+
$input: tokenCount(record.input),
|
|
3058
|
+
$output: tokenCount(record.output),
|
|
3059
|
+
$reasoning: tokenCount(record.reasoning),
|
|
3060
|
+
$cacheRead: tokenCount(record.cacheRead),
|
|
3061
|
+
$cacheWrite: tokenCount(record.cacheWrite)
|
|
2687
3062
|
});
|
|
2688
3063
|
}
|
|
2689
3064
|
function recordPrompt(db, record) {
|
|
@@ -2692,16 +3067,16 @@ function recordPrompt(db, record) {
|
|
|
2692
3067
|
ON CONFLICT(session_id, message_id) DO UPDATE SET created_at = COALESCE(excluded.created_at, prompts.created_at)`).run({
|
|
2693
3068
|
$sessionID: record.sessionID,
|
|
2694
3069
|
$messageID: record.messageID,
|
|
2695
|
-
$createdAt: record.createdAt
|
|
3070
|
+
$createdAt: timestamp(record.createdAt)
|
|
2696
3071
|
});
|
|
2697
3072
|
}
|
|
2698
3073
|
function recordEvent(db, record) {
|
|
2699
|
-
db.query(`INSERT INTO events (session_id, kind, message_id, at, data)
|
|
3074
|
+
db.query(`INSERT OR IGNORE INTO events (session_id, kind, message_id, at, data)
|
|
2700
3075
|
VALUES ($sessionID, $kind, $messageID, $at, $data)`).run({
|
|
2701
3076
|
$sessionID: record.sessionID,
|
|
2702
3077
|
$kind: sanitizeLabel(record.kind, 64),
|
|
2703
3078
|
$messageID: record.messageID ?? null,
|
|
2704
|
-
$at: record.at ?? Date.now(),
|
|
3079
|
+
$at: timestamp(record.at) ?? Date.now(),
|
|
2705
3080
|
$data: jsonText(record.data)
|
|
2706
3081
|
});
|
|
2707
3082
|
}
|
|
@@ -2718,8 +3093,8 @@ function upsertSession(db, record) {
|
|
|
2718
3093
|
$parentID: record.parentID ?? null,
|
|
2719
3094
|
$directory: record.directory === undefined ? null : sanitizeLabel(record.directory, LABEL_LIMIT),
|
|
2720
3095
|
$title: record.title === undefined ? null : sanitizeLabel(record.title, LABEL_LIMIT),
|
|
2721
|
-
$startedAt: record.startedAt
|
|
2722
|
-
$updatedAt: record.updatedAt
|
|
3096
|
+
$startedAt: timestamp(record.startedAt),
|
|
3097
|
+
$updatedAt: timestamp(record.updatedAt)
|
|
2723
3098
|
});
|
|
2724
3099
|
}
|
|
2725
3100
|
|
|
@@ -2733,15 +3108,27 @@ function size(path) {
|
|
|
2733
3108
|
return 0;
|
|
2734
3109
|
}
|
|
2735
3110
|
}
|
|
3111
|
+
function hasTable(db, name) {
|
|
3112
|
+
try {
|
|
3113
|
+
return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== null;
|
|
3114
|
+
} catch {
|
|
3115
|
+
return false;
|
|
3116
|
+
}
|
|
3117
|
+
}
|
|
2736
3118
|
function dbInfo(db, path, now = Date.now()) {
|
|
2737
3119
|
const tables = TABLES.map((table) => ({
|
|
2738
3120
|
name: table,
|
|
2739
|
-
rows: db.query(`SELECT COUNT(*) AS n FROM ${table}`).get().n
|
|
3121
|
+
rows: hasTable(db, table) ? db.query(`SELECT COUNT(*) AS n FROM ${table}`).get().n : 0
|
|
2740
3122
|
}));
|
|
2741
3123
|
const window = db.query(`SELECT MIN(${STEP_TIME2}) AS first, MAX(${STEP_TIME2}) AS last FROM steps`).get();
|
|
2742
3124
|
const version = db.query("SELECT value FROM meta WHERE key = 'schema_version'").get();
|
|
2743
3125
|
return {
|
|
2744
3126
|
path,
|
|
3127
|
+
unpriced: hasListCost(db) ? db.query(`SELECT COUNT(*) AS n FROM steps
|
|
3128
|
+
WHERE cost = 0 AND list_cost IS NULL
|
|
3129
|
+
AND provider_id IS NOT NULL AND provider_id <> ''
|
|
3130
|
+
AND model_id IS NOT NULL AND model_id <> ''
|
|
3131
|
+
AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`).get().n : 0,
|
|
2745
3132
|
bytes: size(path),
|
|
2746
3133
|
walBytes: path === ":memory:" ? undefined : size(`${path}-wal`) || undefined,
|
|
2747
3134
|
schemaVersion: version === null ? 0 : Number.parseInt(version.value, 10),
|
|
@@ -2770,7 +3157,8 @@ function pruneOlderThan(db, cutoff) {
|
|
|
2770
3157
|
return {
|
|
2771
3158
|
steps: deleteBatched(db, "steps", `${STEP_TIME2} < ?`, cutoff),
|
|
2772
3159
|
prompts: deleteBatched(db, "prompts", "created_at IS NOT NULL AND created_at < ?", cutoff),
|
|
2773
|
-
events: deleteBatched(db, "events", "at IS NOT NULL AND at < ?", cutoff)
|
|
3160
|
+
events: deleteBatched(db, "events", "at IS NOT NULL AND at < ?", cutoff),
|
|
3161
|
+
usage: hasTable(db, "usage") ? deleteBatched(db, "usage", "at IS NOT NULL AND at < ?", cutoff) : 0
|
|
2774
3162
|
};
|
|
2775
3163
|
}
|
|
2776
3164
|
function footprint(path) {
|
|
@@ -2783,6 +3171,61 @@ function vacuum(db, path) {
|
|
|
2783
3171
|
const after = footprint(path);
|
|
2784
3172
|
return { before, after, freed: Math.max(0, before - after) };
|
|
2785
3173
|
}
|
|
3174
|
+
function hasListCost(db) {
|
|
3175
|
+
try {
|
|
3176
|
+
return db.query("PRAGMA table_info(steps)").all().some((column) => column.name === "list_cost");
|
|
3177
|
+
} catch {
|
|
3178
|
+
return false;
|
|
3179
|
+
}
|
|
3180
|
+
}
|
|
3181
|
+
var BACKFILL_BATCH = 1000;
|
|
3182
|
+
function backfillListCost(db, price) {
|
|
3183
|
+
if (!hasListCost(db))
|
|
3184
|
+
return { candidates: 0, updated: 0 };
|
|
3185
|
+
const candidates = db.query(`SELECT COUNT(*) AS n FROM steps
|
|
3186
|
+
WHERE cost = 0 AND list_cost IS NULL
|
|
3187
|
+
AND provider_id IS NOT NULL AND provider_id <> ''
|
|
3188
|
+
AND model_id IS NOT NULL AND model_id <> ''
|
|
3189
|
+
AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`).get().n;
|
|
3190
|
+
if (candidates === 0)
|
|
3191
|
+
return { candidates: 0, updated: 0 };
|
|
3192
|
+
const select = db.query(`SELECT rowid, provider_id, model_id,
|
|
3193
|
+
input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
|
|
3194
|
+
FROM steps
|
|
3195
|
+
WHERE cost = 0 AND list_cost IS NULL AND rowid > ?
|
|
3196
|
+
AND provider_id IS NOT NULL AND provider_id <> ''
|
|
3197
|
+
AND model_id IS NOT NULL AND model_id <> ''
|
|
3198
|
+
AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0
|
|
3199
|
+
ORDER BY rowid
|
|
3200
|
+
LIMIT ?`);
|
|
3201
|
+
const update = db.query("UPDATE steps SET list_cost = ? WHERE rowid = ? AND cost = 0 AND list_cost IS NULL");
|
|
3202
|
+
let cursor = 0;
|
|
3203
|
+
let updated = 0;
|
|
3204
|
+
for (;; ) {
|
|
3205
|
+
const rows = select.all(cursor, BACKFILL_BATCH);
|
|
3206
|
+
if (rows.length === 0)
|
|
3207
|
+
break;
|
|
3208
|
+
db.transaction(() => {
|
|
3209
|
+
for (const row of rows) {
|
|
3210
|
+
const estimate = price({ providerID: row.provider_id ?? undefined, modelID: row.model_id ?? undefined }, {
|
|
3211
|
+
input: row.input_tokens ?? 0,
|
|
3212
|
+
output: row.output_tokens ?? 0,
|
|
3213
|
+
reasoning: row.reasoning_tokens ?? 0,
|
|
3214
|
+
cacheRead: row.cache_read ?? 0,
|
|
3215
|
+
cacheWrite: row.cache_write ?? 0
|
|
3216
|
+
});
|
|
3217
|
+
if (estimate === undefined || !Number.isFinite(estimate) || estimate < 0)
|
|
3218
|
+
continue;
|
|
3219
|
+
if (update.run(estimate, row.rowid).changes > 0)
|
|
3220
|
+
updated += 1;
|
|
3221
|
+
}
|
|
3222
|
+
})();
|
|
3223
|
+
cursor = rows[rows.length - 1].rowid;
|
|
3224
|
+
if (rows.length < BACKFILL_BATCH)
|
|
3225
|
+
break;
|
|
3226
|
+
}
|
|
3227
|
+
return { candidates, updated };
|
|
3228
|
+
}
|
|
2786
3229
|
|
|
2787
3230
|
// src/panel.tsx
|
|
2788
3231
|
function Panel(props) {
|
|
@@ -2845,6 +3288,7 @@ function Panel(props) {
|
|
|
2845
3288
|
sessionStart: props.deps.sessionStart(props.input.sessionID),
|
|
2846
3289
|
now: props.deps.now(),
|
|
2847
3290
|
format: props.format,
|
|
3291
|
+
estimates: props.format?.estimates !== false,
|
|
2848
3292
|
...detail() !== undefined ? {
|
|
2849
3293
|
detail: detail()
|
|
2850
3294
|
} : {},
|
|
@@ -2962,12 +3406,68 @@ function Panel(props) {
|
|
|
2962
3406
|
});
|
|
2963
3407
|
} else {
|
|
2964
3408
|
props.ctx.ui.toast.show({
|
|
2965
|
-
message: `pruned ${result.steps} steps \xB7 ${result.prompts} prompts \xB7 ${result.events} compactions`,
|
|
3409
|
+
message: `pruned ${result.steps} steps \xB7 ${result.prompts} prompts \xB7 ${result.events} compactions \xB7 ${result.usage} other usage`,
|
|
2966
3410
|
variant: "success"
|
|
2967
3411
|
});
|
|
2968
3412
|
}
|
|
2969
3413
|
setAnchor(undefined);
|
|
2970
3414
|
setTick((value) => value + 1);
|
|
3415
|
+
props.deps.bump?.();
|
|
3416
|
+
}
|
|
3417
|
+
async function backfillEstimates() {
|
|
3418
|
+
if (props.format?.estimates === false) {
|
|
3419
|
+
props.ctx.ui.toast.show({
|
|
3420
|
+
message: "list-price estimates are turned off",
|
|
3421
|
+
variant: "warning"
|
|
3422
|
+
});
|
|
3423
|
+
return;
|
|
3424
|
+
}
|
|
3425
|
+
if (sessionRunning()) {
|
|
3426
|
+
props.ctx.ui.toast.show({
|
|
3427
|
+
message: "the session is running: backfill again when it is idle",
|
|
3428
|
+
variant: "warning"
|
|
3429
|
+
});
|
|
3430
|
+
return;
|
|
3431
|
+
}
|
|
3432
|
+
const info = database();
|
|
3433
|
+
if (info !== undefined && info.schemaVersion < 10) {
|
|
3434
|
+
props.ctx.ui.toast.show({
|
|
3435
|
+
message: "the recorder must upgrade the database before estimates can be backfilled",
|
|
3436
|
+
variant: "warning"
|
|
3437
|
+
});
|
|
3438
|
+
return;
|
|
3439
|
+
}
|
|
3440
|
+
const candidates = info?.unpriced ?? 0;
|
|
3441
|
+
if (candidates === 0) {
|
|
3442
|
+
props.ctx.ui.toast.show({
|
|
3443
|
+
message: "every $0 step already has a list estimate"
|
|
3444
|
+
});
|
|
3445
|
+
return;
|
|
3446
|
+
}
|
|
3447
|
+
const confirmed = await props.ctx.ui.dialog.confirm({
|
|
3448
|
+
title: "Backfill list-price estimates",
|
|
3449
|
+
message: `${formatCount(candidates)} steps recorded at $0 have no estimate. Those with a known catalog price will be filled using today's catalog; models the catalog no longer lists stay unknown.`,
|
|
3450
|
+
label: {
|
|
3451
|
+
confirm: "Backfill",
|
|
3452
|
+
cancel: "Cancel"
|
|
3453
|
+
}
|
|
3454
|
+
});
|
|
3455
|
+
if (confirmed !== true)
|
|
3456
|
+
return;
|
|
3457
|
+
const result = props.deps.backfill?.();
|
|
3458
|
+
if (result === undefined) {
|
|
3459
|
+
props.ctx.ui.toast.show({
|
|
3460
|
+
message: "the price catalog is unavailable: try again in a moment",
|
|
3461
|
+
variant: "warning"
|
|
3462
|
+
});
|
|
3463
|
+
} else {
|
|
3464
|
+
props.ctx.ui.toast.show({
|
|
3465
|
+
message: `backfilled ${formatCount(result.updated)} of ${formatCount(result.candidates)} steps`,
|
|
3466
|
+
variant: result.updated === 0 ? "warning" : "success"
|
|
3467
|
+
});
|
|
3468
|
+
}
|
|
3469
|
+
setTick((value) => value + 1);
|
|
3470
|
+
props.deps.bump?.();
|
|
2971
3471
|
}
|
|
2972
3472
|
async function compact() {
|
|
2973
3473
|
if (sessionRunning()) {
|
|
@@ -3086,7 +3586,10 @@ function Panel(props) {
|
|
|
3086
3586
|
draft.providerID = "";
|
|
3087
3587
|
});
|
|
3088
3588
|
setAnchor(undefined);
|
|
3089
|
-
}), command("usage-insights.refresh", "Refresh", "r", () => setTick((value) => value + 1)), command("usage-insights.
|
|
3589
|
+
}), command("usage-insights.refresh", "Refresh", "r", () => setTick((value) => value + 1)), command("usage-insights.backfill", "Backfill list-price estimates", "e", () => {
|
|
3590
|
+
if (view() === "db")
|
|
3591
|
+
backfillEstimates();
|
|
3592
|
+
}), command("usage-insights.vacuum", "Compact the database", "v", () => void compact()), command("usage-insights.help", "Help", "?", () => setHelp((open) => !open)), command("usage-insights.fullscreen", "Toggle full screen", "f", () => props.input.toggleFullscreen()), command("usage-insights.close", "Close usage panel", "escape", () => props.input.close()), ...PANEL_VIEWS.map((name, index) => command(`usage-insights.view.${name}`, `View ${name}`, String((index + 1) % 10), () => {
|
|
3090
3593
|
setHelp(false);
|
|
3091
3594
|
props.update((draft) => {
|
|
3092
3595
|
draft.view = name;
|
|
@@ -3189,6 +3692,80 @@ function selectedLineIndex(lines, cursor) {
|
|
|
3189
3692
|
return -1;
|
|
3190
3693
|
}
|
|
3191
3694
|
|
|
3695
|
+
// src/pricing.ts
|
|
3696
|
+
function money(value) {
|
|
3697
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
|
|
3698
|
+
}
|
|
3699
|
+
function tokens(value) {
|
|
3700
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
|
|
3701
|
+
}
|
|
3702
|
+
function priceTable(models) {
|
|
3703
|
+
const table = new Map;
|
|
3704
|
+
if (!Array.isArray(models))
|
|
3705
|
+
return table;
|
|
3706
|
+
for (const model of models) {
|
|
3707
|
+
if (model === null || model === undefined)
|
|
3708
|
+
continue;
|
|
3709
|
+
const providerID = model.providerID;
|
|
3710
|
+
const modelID = model.modelID ?? model.id;
|
|
3711
|
+
if (typeof providerID !== "string" || providerID === "")
|
|
3712
|
+
continue;
|
|
3713
|
+
if (typeof modelID !== "string" || modelID === "")
|
|
3714
|
+
continue;
|
|
3715
|
+
if (!Array.isArray(model.cost) || model.cost.length === 0)
|
|
3716
|
+
continue;
|
|
3717
|
+
const tiers = [];
|
|
3718
|
+
for (const cost of model.cost) {
|
|
3719
|
+
if (cost === null || cost === undefined)
|
|
3720
|
+
continue;
|
|
3721
|
+
let tier;
|
|
3722
|
+
if (cost.tier !== undefined) {
|
|
3723
|
+
const size = cost.tier.size;
|
|
3724
|
+
if (typeof size !== "number" || !Number.isFinite(size))
|
|
3725
|
+
continue;
|
|
3726
|
+
tier = { ...cost.tier.type !== undefined ? { type: cost.tier.type } : {}, size };
|
|
3727
|
+
}
|
|
3728
|
+
tiers.push({
|
|
3729
|
+
...tier !== undefined ? { tier } : {},
|
|
3730
|
+
input: money(cost.input),
|
|
3731
|
+
output: money(cost.output),
|
|
3732
|
+
cacheRead: money(cost.cache?.read),
|
|
3733
|
+
cacheWrite: money(cost.cache?.write)
|
|
3734
|
+
});
|
|
3735
|
+
}
|
|
3736
|
+
if (tiers.length > 0)
|
|
3737
|
+
table.set(`${providerID}/${modelID}`, { tiers });
|
|
3738
|
+
}
|
|
3739
|
+
return table;
|
|
3740
|
+
}
|
|
3741
|
+
function priceOf(table, ref) {
|
|
3742
|
+
if (ref.providerID === undefined || ref.providerID === "")
|
|
3743
|
+
return;
|
|
3744
|
+
if (ref.modelID === undefined || ref.modelID === "")
|
|
3745
|
+
return;
|
|
3746
|
+
return table.get(`${ref.providerID}/${ref.modelID}`);
|
|
3747
|
+
}
|
|
3748
|
+
function costOf(table, ref, usage) {
|
|
3749
|
+
const price = priceOf(table, ref);
|
|
3750
|
+
if (price === undefined)
|
|
3751
|
+
return;
|
|
3752
|
+
const input = tokens(usage.input);
|
|
3753
|
+
const output = tokens(usage.output);
|
|
3754
|
+
const reasoning = tokens(usage.reasoning);
|
|
3755
|
+
const cacheRead = tokens(usage.cacheRead);
|
|
3756
|
+
const cacheWrite = tokens(usage.cacheWrite);
|
|
3757
|
+
const prompt = input + cacheRead + cacheWrite;
|
|
3758
|
+
const selected = price.tiers.filter((tier) => tier.tier?.type === "context" && prompt > tier.tier.size).sort((left, right) => (right.tier?.size ?? 0) - (left.tier?.size ?? 0))[0] ?? price.tiers.find((tier) => tier.tier === undefined);
|
|
3759
|
+
if (selected === undefined)
|
|
3760
|
+
return;
|
|
3761
|
+
if (selected.input === 0 && selected.output === 0 && selected.cacheRead === 0 && selected.cacheWrite === 0)
|
|
3762
|
+
return 0;
|
|
3763
|
+
const billed = input * selected.input + (output + reasoning) * selected.output + cacheRead * selected.cacheRead + cacheWrite * selected.cacheWrite;
|
|
3764
|
+
if (!Number.isFinite(billed) || billed <= 0)
|
|
3765
|
+
return;
|
|
3766
|
+
return billed / 1e6;
|
|
3767
|
+
}
|
|
3768
|
+
|
|
3192
3769
|
// src/sidebar.tsx
|
|
3193
3770
|
import { effect as _$effect2 } from "@opentui/solid";
|
|
3194
3771
|
import { insert as _$insert2 } from "@opentui/solid";
|
|
@@ -3218,7 +3795,7 @@ function TurnsSidebar(props) {
|
|
|
3218
3795
|
try {
|
|
3219
3796
|
const summary = sessionSummaryLines(overview(db, undefined, {
|
|
3220
3797
|
sessionID: props.sessionID
|
|
3221
|
-
}), budget);
|
|
3798
|
+
}), budget, props.options?.estimates !== false);
|
|
3222
3799
|
const history = sidebarLines(turns(db, {
|
|
3223
3800
|
sessionID: props.sessionID,
|
|
3224
3801
|
limit: props.deps.limit
|
|
@@ -3269,6 +3846,31 @@ var tui_default = Plugin.define({
|
|
|
3269
3846
|
if (options.enabled === false)
|
|
3270
3847
|
return;
|
|
3271
3848
|
const panelEnabled = options.panel !== false;
|
|
3849
|
+
const pricing = options.pricing !== "off";
|
|
3850
|
+
const PRICE_TTL_MS = 5 * 60 * 1000;
|
|
3851
|
+
let priceCache;
|
|
3852
|
+
function priceTableFor() {
|
|
3853
|
+
if (!pricing)
|
|
3854
|
+
return;
|
|
3855
|
+
const now = Date.now();
|
|
3856
|
+
if (priceCache !== undefined && now - priceCache.at < PRICE_TTL_MS)
|
|
3857
|
+
return priceCache.table;
|
|
3858
|
+
try {
|
|
3859
|
+
const models = ctx.data.location?.model?.list(ctx.location);
|
|
3860
|
+
if (models !== undefined && models.length > 0) {
|
|
3861
|
+
priceCache = {
|
|
3862
|
+
table: priceTable(models),
|
|
3863
|
+
at: now
|
|
3864
|
+
};
|
|
3865
|
+
return priceCache.table;
|
|
3866
|
+
}
|
|
3867
|
+
} catch {}
|
|
3868
|
+
return priceCache?.table;
|
|
3869
|
+
}
|
|
3870
|
+
function priceFor() {
|
|
3871
|
+
const table = priceTableFor();
|
|
3872
|
+
return table === undefined ? undefined : (ref, tokens) => costOf(table, ref, tokens);
|
|
3873
|
+
}
|
|
3272
3874
|
const [settings, updateSettings] = ctx.storage.store("panel", {
|
|
3273
3875
|
initial: DEFAULT_SETTINGS
|
|
3274
3876
|
});
|
|
@@ -3280,7 +3882,9 @@ var tui_default = Plugin.define({
|
|
|
3280
3882
|
let databaseFailed = false;
|
|
3281
3883
|
let refreshTimer;
|
|
3282
3884
|
let lastRefresh = 0;
|
|
3885
|
+
const sessionCostCache = new Map;
|
|
3283
3886
|
function bumpRefresh() {
|
|
3887
|
+
sessionCostCache.clear();
|
|
3284
3888
|
const now = Date.now();
|
|
3285
3889
|
const wait = lastRefresh + REFRESH_THROTTLE_MS - now;
|
|
3286
3890
|
if (wait <= 0) {
|
|
@@ -3310,6 +3914,28 @@ var tui_default = Plugin.define({
|
|
|
3310
3914
|
return;
|
|
3311
3915
|
}
|
|
3312
3916
|
}
|
|
3917
|
+
function sessionListCostFor(sessionID) {
|
|
3918
|
+
if (!pricing)
|
|
3919
|
+
return 0;
|
|
3920
|
+
const cached = sessionCostCache.get(sessionID);
|
|
3921
|
+
if (cached !== undefined)
|
|
3922
|
+
return cached;
|
|
3923
|
+
const handle = db();
|
|
3924
|
+
if (handle === undefined)
|
|
3925
|
+
return 0;
|
|
3926
|
+
try {
|
|
3927
|
+
const value = sessionListCost(handle, sessionID);
|
|
3928
|
+
if (sessionCostCache.size >= 512) {
|
|
3929
|
+
const oldest = sessionCostCache.keys().next();
|
|
3930
|
+
if (oldest.done !== true)
|
|
3931
|
+
sessionCostCache.delete(oldest.value);
|
|
3932
|
+
}
|
|
3933
|
+
sessionCostCache.set(sessionID, value);
|
|
3934
|
+
return value;
|
|
3935
|
+
} catch {
|
|
3936
|
+
return 0;
|
|
3937
|
+
}
|
|
3938
|
+
}
|
|
3313
3939
|
function withWrite(run) {
|
|
3314
3940
|
let handle;
|
|
3315
3941
|
try {
|
|
@@ -3321,6 +3947,14 @@ var tui_default = Plugin.define({
|
|
|
3321
3947
|
handle?.close();
|
|
3322
3948
|
}
|
|
3323
3949
|
}
|
|
3950
|
+
function backfill() {
|
|
3951
|
+
if (!pricing)
|
|
3952
|
+
return;
|
|
3953
|
+
const table = priceTableFor();
|
|
3954
|
+
if (table === undefined)
|
|
3955
|
+
return;
|
|
3956
|
+
return withWrite((handle) => backfillListCost(handle, (ref, tokens) => costOf(table, ref, tokens)));
|
|
3957
|
+
}
|
|
3324
3958
|
function sessionStart(sessionID) {
|
|
3325
3959
|
return ctx.data.session.get(sessionID)?.time.created;
|
|
3326
3960
|
}
|
|
@@ -3334,9 +3968,12 @@ var tui_default = Plugin.define({
|
|
|
3334
3968
|
function lineFor(sessionID) {
|
|
3335
3969
|
if (!sessionIdle(sessionID))
|
|
3336
3970
|
return;
|
|
3971
|
+
if (pricing)
|
|
3972
|
+
refresh();
|
|
3337
3973
|
const messages = ctx.data.session.message.list(sessionID);
|
|
3338
3974
|
const info = ctx.data.session.get(sessionID);
|
|
3339
|
-
|
|
3975
|
+
const session = info === undefined ? undefined : sessionTotals(info, sessionListCostFor(sessionID));
|
|
3976
|
+
return computeTurn(toTranscriptTail(messages, 2, priceFor()), session);
|
|
3340
3977
|
}
|
|
3341
3978
|
function toneColor(tone) {
|
|
3342
3979
|
if (tone === "warning")
|
|
@@ -3349,7 +3986,8 @@ var tui_default = Plugin.define({
|
|
|
3349
3986
|
const parts = createMemo3(() => lineParts(lineFor(props.sessionID), {
|
|
3350
3987
|
labels: options.labels,
|
|
3351
3988
|
fields: options.fields,
|
|
3352
|
-
turnTotals: options.turnTotals
|
|
3989
|
+
turnTotals: options.turnTotals,
|
|
3990
|
+
estimates: pricing
|
|
3353
3991
|
}));
|
|
3354
3992
|
return _$createComponent3(Show, {
|
|
3355
3993
|
get when() {
|
|
@@ -3392,9 +4030,11 @@ var tui_default = Plugin.define({
|
|
|
3392
4030
|
db,
|
|
3393
4031
|
dbPath: () => resolveDbPath(options.db),
|
|
3394
4032
|
withWrite,
|
|
4033
|
+
backfill,
|
|
3395
4034
|
now: () => Date.now(),
|
|
3396
4035
|
sessionStart,
|
|
3397
|
-
refresh
|
|
4036
|
+
refresh,
|
|
4037
|
+
bump: bumpRefresh
|
|
3398
4038
|
},
|
|
3399
4039
|
settings,
|
|
3400
4040
|
update: patchSettings,
|
|
@@ -3402,7 +4042,8 @@ var tui_default = Plugin.define({
|
|
|
3402
4042
|
return {
|
|
3403
4043
|
labels: options.labels,
|
|
3404
4044
|
fields: options.fields,
|
|
3405
|
-
turnTotals: options.turnTotals
|
|
4045
|
+
turnTotals: options.turnTotals,
|
|
4046
|
+
estimates: pricing
|
|
3406
4047
|
};
|
|
3407
4048
|
}
|
|
3408
4049
|
}) : null
|
|
@@ -3418,14 +4059,15 @@ var tui_default = Plugin.define({
|
|
|
3418
4059
|
return {
|
|
3419
4060
|
db,
|
|
3420
4061
|
refresh,
|
|
3421
|
-
limit: Math.max(1, Math.round(options.sidebarTurns ??
|
|
4062
|
+
limit: Math.max(1, Math.round(options.sidebarTurns ?? 8))
|
|
3422
4063
|
};
|
|
3423
4064
|
},
|
|
3424
4065
|
get options() {
|
|
3425
4066
|
return {
|
|
3426
4067
|
labels: options.labels,
|
|
3427
4068
|
fields: options.fields,
|
|
3428
|
-
turnTotals: options.turnTotals
|
|
4069
|
+
turnTotals: options.turnTotals,
|
|
4070
|
+
estimates: pricing
|
|
3429
4071
|
};
|
|
3430
4072
|
}
|
|
3431
4073
|
})
|
|
@@ -3480,12 +4122,16 @@ var tui_default = Plugin.define({
|
|
|
3480
4122
|
ctx.data.on("session.execution.succeeded", () => bumpRefresh()),
|
|
3481
4123
|
ctx.data.on("session.execution.failed", () => bumpRefresh()),
|
|
3482
4124
|
ctx.data.on("session.execution.interrupted", () => bumpRefresh()),
|
|
3483
|
-
ctx.data.on("session.compaction.ended", () => bumpRefresh())
|
|
4125
|
+
ctx.data.on("session.compaction.ended", () => bumpRefresh()),
|
|
4126
|
+
ctx.data.on("model.updated", () => {
|
|
4127
|
+
priceCache = undefined;
|
|
4128
|
+
})
|
|
3484
4129
|
];
|
|
3485
4130
|
__test.line = lineFor;
|
|
3486
4131
|
__test.lineText = (sessionID) => lineText(lineParts(lineFor(sessionID), {
|
|
3487
4132
|
labels: options.labels,
|
|
3488
|
-
fields: options.fields
|
|
4133
|
+
fields: options.fields,
|
|
4134
|
+
estimates: pricing
|
|
3489
4135
|
}));
|
|
3490
4136
|
__test.open = open;
|
|
3491
4137
|
__test.state = () => {
|
|
@@ -3512,4 +4158,4 @@ export {
|
|
|
3512
4158
|
tui_default as default
|
|
3513
4159
|
};
|
|
3514
4160
|
|
|
3515
|
-
//# debugId=
|
|
4161
|
+
//# debugId=A1CD43DA40AD35A864756E2164756E21
|