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/index.js
CHANGED
|
@@ -2,6 +2,80 @@
|
|
|
2
2
|
// src/index.ts
|
|
3
3
|
import { Plugin } from "@opencode/plugin";
|
|
4
4
|
|
|
5
|
+
// src/pricing.ts
|
|
6
|
+
function money(value) {
|
|
7
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
|
|
8
|
+
}
|
|
9
|
+
function tokens(value) {
|
|
10
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
|
|
11
|
+
}
|
|
12
|
+
function priceTable(models) {
|
|
13
|
+
const table = new Map;
|
|
14
|
+
if (!Array.isArray(models))
|
|
15
|
+
return table;
|
|
16
|
+
for (const model of models) {
|
|
17
|
+
if (model === null || model === undefined)
|
|
18
|
+
continue;
|
|
19
|
+
const providerID = model.providerID;
|
|
20
|
+
const modelID = model.modelID ?? model.id;
|
|
21
|
+
if (typeof providerID !== "string" || providerID === "")
|
|
22
|
+
continue;
|
|
23
|
+
if (typeof modelID !== "string" || modelID === "")
|
|
24
|
+
continue;
|
|
25
|
+
if (!Array.isArray(model.cost) || model.cost.length === 0)
|
|
26
|
+
continue;
|
|
27
|
+
const tiers = [];
|
|
28
|
+
for (const cost of model.cost) {
|
|
29
|
+
if (cost === null || cost === undefined)
|
|
30
|
+
continue;
|
|
31
|
+
let tier;
|
|
32
|
+
if (cost.tier !== undefined) {
|
|
33
|
+
const size = cost.tier.size;
|
|
34
|
+
if (typeof size !== "number" || !Number.isFinite(size))
|
|
35
|
+
continue;
|
|
36
|
+
tier = { ...cost.tier.type !== undefined ? { type: cost.tier.type } : {}, size };
|
|
37
|
+
}
|
|
38
|
+
tiers.push({
|
|
39
|
+
...tier !== undefined ? { tier } : {},
|
|
40
|
+
input: money(cost.input),
|
|
41
|
+
output: money(cost.output),
|
|
42
|
+
cacheRead: money(cost.cache?.read),
|
|
43
|
+
cacheWrite: money(cost.cache?.write)
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
if (tiers.length > 0)
|
|
47
|
+
table.set(`${providerID}/${modelID}`, { tiers });
|
|
48
|
+
}
|
|
49
|
+
return table;
|
|
50
|
+
}
|
|
51
|
+
function priceOf(table, ref) {
|
|
52
|
+
if (ref.providerID === undefined || ref.providerID === "")
|
|
53
|
+
return;
|
|
54
|
+
if (ref.modelID === undefined || ref.modelID === "")
|
|
55
|
+
return;
|
|
56
|
+
return table.get(`${ref.providerID}/${ref.modelID}`);
|
|
57
|
+
}
|
|
58
|
+
function costOf(table, ref, usage) {
|
|
59
|
+
const price = priceOf(table, ref);
|
|
60
|
+
if (price === undefined)
|
|
61
|
+
return;
|
|
62
|
+
const input = tokens(usage.input);
|
|
63
|
+
const output = tokens(usage.output);
|
|
64
|
+
const reasoning = tokens(usage.reasoning);
|
|
65
|
+
const cacheRead = tokens(usage.cacheRead);
|
|
66
|
+
const cacheWrite = tokens(usage.cacheWrite);
|
|
67
|
+
const prompt = input + cacheRead + cacheWrite;
|
|
68
|
+
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);
|
|
69
|
+
if (selected === undefined)
|
|
70
|
+
return;
|
|
71
|
+
if (selected.input === 0 && selected.output === 0 && selected.cacheRead === 0 && selected.cacheWrite === 0)
|
|
72
|
+
return 0;
|
|
73
|
+
const billed = input * selected.input + (output + reasoning) * selected.output + cacheRead * selected.cacheRead + cacheWrite * selected.cacheWrite;
|
|
74
|
+
if (!Number.isFinite(billed) || billed <= 0)
|
|
75
|
+
return;
|
|
76
|
+
return billed / 1e6;
|
|
77
|
+
}
|
|
78
|
+
|
|
5
79
|
// src/stats/db.ts
|
|
6
80
|
import { Database } from "bun:sqlite";
|
|
7
81
|
import { chmodSync, mkdirSync } from "fs";
|
|
@@ -72,7 +146,7 @@ function isToken(value, limit = 64) {
|
|
|
72
146
|
}
|
|
73
147
|
|
|
74
148
|
// src/stats/db.ts
|
|
75
|
-
var SCHEMA_VERSION =
|
|
149
|
+
var SCHEMA_VERSION = 11;
|
|
76
150
|
var LABEL_LIMIT = 4 * TEXT_LIMIT;
|
|
77
151
|
var SCHEMA = `
|
|
78
152
|
CREATE TABLE IF NOT EXISTS meta (
|
|
@@ -110,6 +184,7 @@ CREATE TABLE IF NOT EXISTS steps (
|
|
|
110
184
|
cache_read INTEGER NOT NULL DEFAULT 0,
|
|
111
185
|
cache_write INTEGER NOT NULL DEFAULT 0,
|
|
112
186
|
cost REAL NOT NULL DEFAULT 0,
|
|
187
|
+
list_cost REAL,
|
|
113
188
|
created_at INTEGER,
|
|
114
189
|
streamed_at INTEGER,
|
|
115
190
|
completed_at INTEGER,
|
|
@@ -136,8 +211,28 @@ CREATE TABLE IF NOT EXISTS events (
|
|
|
136
211
|
);
|
|
137
212
|
CREATE INDEX IF NOT EXISTS events_session ON events(session_id, at);
|
|
138
213
|
CREATE INDEX IF NOT EXISTS events_kind ON events(kind, at);
|
|
214
|
+
|
|
215
|
+
-- Usage the host reports with no assistant step of its own: the compaction
|
|
216
|
+
-- summarisation and the session-title generation. The host publishes it as
|
|
217
|
+
-- session.usage.recorded with a source other than generate, and includes it in
|
|
218
|
+
-- the session's own cost/token totals. Primary key is the host event ID, so a
|
|
219
|
+
-- replayed event never counts twice.
|
|
220
|
+
CREATE TABLE IF NOT EXISTS usage (
|
|
221
|
+
id TEXT PRIMARY KEY,
|
|
222
|
+
session_id TEXT NOT NULL,
|
|
223
|
+
source TEXT NOT NULL,
|
|
224
|
+
at INTEGER,
|
|
225
|
+
cost REAL NOT NULL DEFAULT 0,
|
|
226
|
+
input_tokens INTEGER NOT NULL DEFAULT 0,
|
|
227
|
+
output_tokens INTEGER NOT NULL DEFAULT 0,
|
|
228
|
+
reasoning_tokens INTEGER NOT NULL DEFAULT 0,
|
|
229
|
+
cache_read INTEGER NOT NULL DEFAULT 0,
|
|
230
|
+
cache_write INTEGER NOT NULL DEFAULT 0
|
|
231
|
+
);
|
|
232
|
+
CREATE INDEX IF NOT EXISTS usage_session_at ON usage(session_id, at);
|
|
233
|
+
CREATE INDEX IF NOT EXISTS usage_at ON usage(at);
|
|
139
234
|
`;
|
|
140
|
-
var TABLES = ["sessions", "prompts", "events", "steps"];
|
|
235
|
+
var TABLES = ["sessions", "prompts", "events", "steps", "usage"];
|
|
141
236
|
function jsonText(value) {
|
|
142
237
|
if (value === undefined || value === null)
|
|
143
238
|
return null;
|
|
@@ -149,6 +244,15 @@ function jsonText(value) {
|
|
|
149
244
|
return null;
|
|
150
245
|
}
|
|
151
246
|
}
|
|
247
|
+
function finite(value) {
|
|
248
|
+
return typeof value === "number" && Number.isFinite(value) ? value : 0;
|
|
249
|
+
}
|
|
250
|
+
function tokenCount(value) {
|
|
251
|
+
return Math.max(0, Math.floor(finite(value)));
|
|
252
|
+
}
|
|
253
|
+
function timestamp(value) {
|
|
254
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
255
|
+
}
|
|
152
256
|
var REMOVED_COLUMNS = ["provider_state", "upstream", "upstream_source", "upstream_model", "tps", "router"];
|
|
153
257
|
var REMOVED_EVENT_KINDS = ["execution", "step-failed", "model-selected", "usage-recorded"];
|
|
154
258
|
function dropUnused(db) {
|
|
@@ -171,8 +275,62 @@ function dropUnused(db) {
|
|
|
171
275
|
db.exec(`DELETE FROM events WHERE kind IN (${kinds})`);
|
|
172
276
|
}
|
|
173
277
|
}
|
|
278
|
+
function addMissing(db) {
|
|
279
|
+
const columns = new Set(db.query("PRAGMA table_info(steps)").all().map((column) => column.name));
|
|
280
|
+
if (columns.size > 0 && !columns.has("list_cost")) {
|
|
281
|
+
db.exec("ALTER TABLE steps ADD COLUMN list_cost REAL");
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
function dedupeEvents(db) {
|
|
285
|
+
const table = db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'events'").get();
|
|
286
|
+
if (table === null)
|
|
287
|
+
return;
|
|
288
|
+
db.exec(`DELETE FROM events
|
|
289
|
+
WHERE kind = 'compaction' AND message_id IS NULL
|
|
290
|
+
AND rowid NOT IN (
|
|
291
|
+
SELECT MIN(rowid) FROM events
|
|
292
|
+
WHERE kind = 'compaction' AND message_id IS NULL
|
|
293
|
+
GROUP BY session_id, at, data
|
|
294
|
+
)`);
|
|
295
|
+
db.exec(`DELETE FROM events
|
|
296
|
+
WHERE message_id IS NOT NULL
|
|
297
|
+
AND rowid NOT IN (
|
|
298
|
+
SELECT MIN(rowid) FROM events
|
|
299
|
+
WHERE message_id IS NOT NULL
|
|
300
|
+
GROUP BY kind, message_id
|
|
301
|
+
)`);
|
|
302
|
+
}
|
|
303
|
+
function addEventKey(db) {
|
|
304
|
+
const table = db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'events'").get();
|
|
305
|
+
if (table === null)
|
|
306
|
+
return;
|
|
307
|
+
db.exec("CREATE UNIQUE INDEX IF NOT EXISTS events_kind_message ON events(kind, message_id) WHERE message_id IS NOT NULL");
|
|
308
|
+
}
|
|
309
|
+
function backfillCompactionUsage(db) {
|
|
310
|
+
const tables = new Set(db.query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((row) => row.name));
|
|
311
|
+
if (!tables.has("events") || !tables.has("usage"))
|
|
312
|
+
return;
|
|
313
|
+
db.exec(`INSERT OR IGNORE INTO usage (
|
|
314
|
+
id, session_id, source, at, cost,
|
|
315
|
+
input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
|
|
316
|
+
)
|
|
317
|
+
SELECT 'compaction:' || rowid, session_id, 'compaction', at,
|
|
318
|
+
MAX(0, COALESCE(CAST(json_extract(data, '$.cost') AS REAL), 0)),
|
|
319
|
+
MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.input'), 0) AS INTEGER)),
|
|
320
|
+
MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.output'), 0) AS INTEGER)),
|
|
321
|
+
MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.reasoning'), 0) AS INTEGER)),
|
|
322
|
+
MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.cache.read'), 0) AS INTEGER)),
|
|
323
|
+
MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.cache.write'), 0) AS INTEGER))
|
|
324
|
+
FROM events
|
|
325
|
+
WHERE kind = 'compaction' AND message_id IS NULL AND at IS NOT NULL AND data IS NOT NULL
|
|
326
|
+
AND json_valid(data)`);
|
|
327
|
+
}
|
|
174
328
|
function migrate(db) {
|
|
175
329
|
dropUnused(db);
|
|
330
|
+
addMissing(db);
|
|
331
|
+
dedupeEvents(db);
|
|
332
|
+
backfillCompactionUsage(db);
|
|
333
|
+
addEventKey(db);
|
|
176
334
|
}
|
|
177
335
|
var POSIX = process.platform !== "win32";
|
|
178
336
|
function hardenDirectory(path) {
|
|
@@ -233,13 +391,15 @@ function openStatsDbWrite(path) {
|
|
|
233
391
|
return db;
|
|
234
392
|
}
|
|
235
393
|
function recordStep(db, record) {
|
|
394
|
+
const cost = Math.max(0, finite(record.cost));
|
|
395
|
+
const listCost = cost <= 0 && typeof record.listCost === "number" && Number.isFinite(record.listCost) && record.listCost >= 0 ? record.listCost : null;
|
|
236
396
|
db.query(`INSERT INTO steps (
|
|
237
397
|
message_id, session_id, parent_id, provider_id, model_id, variant,
|
|
238
|
-
input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost,
|
|
398
|
+
input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost, list_cost,
|
|
239
399
|
created_at, streamed_at, completed_at, finish, recorded_at
|
|
240
400
|
) VALUES (
|
|
241
401
|
$messageID, $sessionID, $parentID, $providerID, $modelID, $variant,
|
|
242
|
-
$input, $output, $reasoning, $cacheRead, $cacheWrite, $cost,
|
|
402
|
+
$input, $output, $reasoning, $cacheRead, $cacheWrite, $cost, $listCost,
|
|
243
403
|
$createdAt, $streamedAt, $completedAt, $finish, $recordedAt
|
|
244
404
|
)
|
|
245
405
|
ON CONFLICT(message_id) DO UPDATE SET
|
|
@@ -254,6 +414,9 @@ function recordStep(db, record) {
|
|
|
254
414
|
cache_read = excluded.cache_read,
|
|
255
415
|
cache_write = excluded.cache_write,
|
|
256
416
|
cost = excluded.cost,
|
|
417
|
+
-- A step that starts being charged loses its estimate; an estimate is
|
|
418
|
+
-- kept when a replayed event arrives without a price table.
|
|
419
|
+
list_cost = CASE WHEN excluded.cost > 0 THEN NULL ELSE COALESCE(excluded.list_cost, steps.list_cost) END,
|
|
257
420
|
created_at = COALESCE(excluded.created_at, steps.created_at),
|
|
258
421
|
streamed_at = COALESCE(excluded.streamed_at, steps.streamed_at),
|
|
259
422
|
completed_at = COALESCE(excluded.completed_at, steps.completed_at),
|
|
@@ -265,17 +428,40 @@ function recordStep(db, record) {
|
|
|
265
428
|
$providerID: record.providerID !== undefined && isToken(record.providerID) ? record.providerID : null,
|
|
266
429
|
$modelID: record.modelID ?? null,
|
|
267
430
|
$variant: record.variant ?? null,
|
|
268
|
-
$input: record.input
|
|
269
|
-
$output: record.output
|
|
270
|
-
$reasoning: record.reasoning
|
|
271
|
-
$cacheRead: record.cacheRead
|
|
272
|
-
$cacheWrite: record.cacheWrite
|
|
273
|
-
$cost:
|
|
274
|
-
$
|
|
275
|
-
$
|
|
276
|
-
$
|
|
431
|
+
$input: tokenCount(record.input),
|
|
432
|
+
$output: tokenCount(record.output),
|
|
433
|
+
$reasoning: tokenCount(record.reasoning),
|
|
434
|
+
$cacheRead: tokenCount(record.cacheRead),
|
|
435
|
+
$cacheWrite: tokenCount(record.cacheWrite),
|
|
436
|
+
$cost: cost,
|
|
437
|
+
$listCost: listCost,
|
|
438
|
+
$createdAt: timestamp(record.createdAt),
|
|
439
|
+
$streamedAt: timestamp(record.streamedAt),
|
|
440
|
+
$completedAt: timestamp(record.completedAt),
|
|
277
441
|
$finish: record.finish === undefined ? null : sanitizeLabel(record.finish, 64),
|
|
278
|
-
$recordedAt: record.recordedAt ?? Date.now()
|
|
442
|
+
$recordedAt: timestamp(record.recordedAt) ?? Date.now()
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
function recordUsage(db, record) {
|
|
446
|
+
if (typeof record.id !== "string" || record.id === "")
|
|
447
|
+
return;
|
|
448
|
+
if (typeof record.sessionID !== "string" || record.sessionID === "")
|
|
449
|
+
return;
|
|
450
|
+
db.query(`INSERT INTO usage (
|
|
451
|
+
id, session_id, source, at, cost, input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
|
|
452
|
+
) VALUES (
|
|
453
|
+
$id, $sessionID, $source, $at, $cost, $input, $output, $reasoning, $cacheRead, $cacheWrite
|
|
454
|
+
) ON CONFLICT(id) DO NOTHING`).run({
|
|
455
|
+
$id: record.id,
|
|
456
|
+
$sessionID: record.sessionID,
|
|
457
|
+
$source: sanitizeLabel(record.source, 64),
|
|
458
|
+
$at: timestamp(record.at) ?? Date.now(),
|
|
459
|
+
$cost: Math.max(0, finite(record.cost)),
|
|
460
|
+
$input: tokenCount(record.input),
|
|
461
|
+
$output: tokenCount(record.output),
|
|
462
|
+
$reasoning: tokenCount(record.reasoning),
|
|
463
|
+
$cacheRead: tokenCount(record.cacheRead),
|
|
464
|
+
$cacheWrite: tokenCount(record.cacheWrite)
|
|
279
465
|
});
|
|
280
466
|
}
|
|
281
467
|
function recordPrompt(db, record) {
|
|
@@ -284,16 +470,16 @@ function recordPrompt(db, record) {
|
|
|
284
470
|
ON CONFLICT(session_id, message_id) DO UPDATE SET created_at = COALESCE(excluded.created_at, prompts.created_at)`).run({
|
|
285
471
|
$sessionID: record.sessionID,
|
|
286
472
|
$messageID: record.messageID,
|
|
287
|
-
$createdAt: record.createdAt
|
|
473
|
+
$createdAt: timestamp(record.createdAt)
|
|
288
474
|
});
|
|
289
475
|
}
|
|
290
476
|
function recordEvent(db, record) {
|
|
291
|
-
db.query(`INSERT INTO events (session_id, kind, message_id, at, data)
|
|
477
|
+
db.query(`INSERT OR IGNORE INTO events (session_id, kind, message_id, at, data)
|
|
292
478
|
VALUES ($sessionID, $kind, $messageID, $at, $data)`).run({
|
|
293
479
|
$sessionID: record.sessionID,
|
|
294
480
|
$kind: sanitizeLabel(record.kind, 64),
|
|
295
481
|
$messageID: record.messageID ?? null,
|
|
296
|
-
$at: record.at ?? Date.now(),
|
|
482
|
+
$at: timestamp(record.at) ?? Date.now(),
|
|
297
483
|
$data: jsonText(record.data)
|
|
298
484
|
});
|
|
299
485
|
}
|
|
@@ -310,8 +496,8 @@ function upsertSession(db, record) {
|
|
|
310
496
|
$parentID: record.parentID ?? null,
|
|
311
497
|
$directory: record.directory === undefined ? null : sanitizeLabel(record.directory, LABEL_LIMIT),
|
|
312
498
|
$title: record.title === undefined ? null : sanitizeLabel(record.title, LABEL_LIMIT),
|
|
313
|
-
$startedAt: record.startedAt
|
|
314
|
-
$updatedAt: record.updatedAt
|
|
499
|
+
$startedAt: timestamp(record.startedAt),
|
|
500
|
+
$updatedAt: timestamp(record.updatedAt)
|
|
315
501
|
});
|
|
316
502
|
}
|
|
317
503
|
|
|
@@ -339,18 +525,27 @@ function transcriptTail(messages, count) {
|
|
|
339
525
|
segments.unshift({ assistants: current, prompt: undefined });
|
|
340
526
|
return segments;
|
|
341
527
|
}
|
|
528
|
+
function countOf(value) {
|
|
529
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
|
|
530
|
+
}
|
|
531
|
+
function amountOf(value) {
|
|
532
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
|
|
533
|
+
}
|
|
534
|
+
function stampOf(value) {
|
|
535
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
536
|
+
}
|
|
342
537
|
function tokenCounts(message) {
|
|
343
538
|
const tokens = message.tokens;
|
|
344
539
|
return {
|
|
345
|
-
input: tokens?.input
|
|
346
|
-
output: tokens?.output
|
|
347
|
-
reasoning: tokens?.reasoning
|
|
348
|
-
read: tokens?.cache?.read
|
|
349
|
-
write: tokens?.cache?.write
|
|
540
|
+
input: countOf(tokens?.input),
|
|
541
|
+
output: countOf(tokens?.output),
|
|
542
|
+
reasoning: countOf(tokens?.reasoning),
|
|
543
|
+
read: countOf(tokens?.cache?.read),
|
|
544
|
+
write: countOf(tokens?.cache?.write)
|
|
350
545
|
};
|
|
351
546
|
}
|
|
352
547
|
function totalize(steps) {
|
|
353
|
-
const totals = { input: 0, cached: 0, output: 0, reasoning: 0, cacheWrite: 0, cost: 0, steps: steps.length };
|
|
548
|
+
const totals = { input: 0, cached: 0, output: 0, reasoning: 0, cacheWrite: 0, cost: 0, listCost: 0, steps: steps.length };
|
|
354
549
|
for (const step of steps) {
|
|
355
550
|
const counts = tokenCounts(step);
|
|
356
551
|
totals.input += counts.input;
|
|
@@ -358,7 +553,8 @@ function totalize(steps) {
|
|
|
358
553
|
totals.output += counts.output;
|
|
359
554
|
totals.reasoning += counts.reasoning;
|
|
360
555
|
totals.cacheWrite += counts.write;
|
|
361
|
-
totals.cost += step.cost
|
|
556
|
+
totals.cost += amountOf(step.cost);
|
|
557
|
+
totals.listCost += amountOf(step.listCost);
|
|
362
558
|
}
|
|
363
559
|
return totals;
|
|
364
560
|
}
|
|
@@ -368,16 +564,16 @@ function identityKey(model) {
|
|
|
368
564
|
return `${model.providerID}/${model.id}${model.variant ? `#${model.variant}` : ""}`;
|
|
369
565
|
}
|
|
370
566
|
function cacheRead(message) {
|
|
371
|
-
return message?.tokens?.cache?.read
|
|
567
|
+
return countOf(message?.tokens?.cache?.read);
|
|
372
568
|
}
|
|
373
569
|
function stepCreated(message) {
|
|
374
|
-
return message?.time?.created;
|
|
570
|
+
return stampOf(message?.time?.created);
|
|
375
571
|
}
|
|
376
572
|
function stepEnd(message) {
|
|
377
573
|
const time = message?.time;
|
|
378
574
|
if (!time)
|
|
379
575
|
return;
|
|
380
|
-
return time.completed ?? time.streamed ?? time.created;
|
|
576
|
+
return stampOf(time.completed) ?? stampOf(time.streamed) ?? stampOf(time.created);
|
|
381
577
|
}
|
|
382
578
|
function cacheDrop(reference, current, scope = "provider") {
|
|
383
579
|
if (!reference)
|
|
@@ -404,9 +600,9 @@ function stepGap(reference, current) {
|
|
|
404
600
|
return Math.max(0, started - ended);
|
|
405
601
|
}
|
|
406
602
|
function tokensPerSecond(produced, from, to) {
|
|
407
|
-
if (from === undefined || to === undefined || to <= from)
|
|
603
|
+
if (from === undefined || to === undefined || !Number.isFinite(from) || !Number.isFinite(to) || to <= from)
|
|
408
604
|
return;
|
|
409
|
-
if (produced <= 0)
|
|
605
|
+
if (!Number.isFinite(produced) || produced <= 0)
|
|
410
606
|
return;
|
|
411
607
|
return produced / (to - from) * 1000;
|
|
412
608
|
}
|
|
@@ -450,7 +646,7 @@ function computeTurn(messages, session) {
|
|
|
450
646
|
return {
|
|
451
647
|
endAt: stepEnd(lastStep),
|
|
452
648
|
startAt: stepCreated(settled[0] ?? lastStep),
|
|
453
|
-
promptAt: last.prompt?.time?.created,
|
|
649
|
+
promptAt: stampOf(last.prompt?.time?.created),
|
|
454
650
|
promptGapMs: promptGap(last.prompt, previous?.prompt),
|
|
455
651
|
providerID: provider,
|
|
456
652
|
modelID: lastStep.model?.id,
|
|
@@ -467,8 +663,8 @@ function computeTurn(messages, session) {
|
|
|
467
663
|
};
|
|
468
664
|
}
|
|
469
665
|
function promptGap(current, previous) {
|
|
470
|
-
const now = current?.time?.created;
|
|
471
|
-
const before = previous?.time?.created;
|
|
666
|
+
const now = stampOf(current?.time?.created);
|
|
667
|
+
const before = stampOf(previous?.time?.created);
|
|
472
668
|
if (now === undefined || before === undefined)
|
|
473
669
|
return;
|
|
474
670
|
return Math.max(0, now - before);
|
|
@@ -489,6 +685,7 @@ var DEFAULT_LABELS = {
|
|
|
489
685
|
output: "out",
|
|
490
686
|
reasoning: "reason",
|
|
491
687
|
cost: "cost",
|
|
688
|
+
estimate: "\u2248",
|
|
492
689
|
cacheExpired: "cache expired",
|
|
493
690
|
providerChanged: "changed",
|
|
494
691
|
modelChanged: "model changed"
|
|
@@ -505,11 +702,15 @@ var DEFAULT_FIELDS = {
|
|
|
505
702
|
cacheExpiry: true
|
|
506
703
|
};
|
|
507
704
|
function formatClock(ms) {
|
|
705
|
+
if (!Number.isFinite(ms))
|
|
706
|
+
return "--:--";
|
|
508
707
|
const date = new Date(ms);
|
|
509
708
|
const pad = (value) => String(value).padStart(2, "0");
|
|
510
709
|
return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
|
511
710
|
}
|
|
512
711
|
function formatDuration(ms) {
|
|
712
|
+
if (!Number.isFinite(ms))
|
|
713
|
+
return "\u2013";
|
|
513
714
|
const totalSeconds = Math.max(0, Math.floor(ms / 1000));
|
|
514
715
|
const seconds = totalSeconds % 60;
|
|
515
716
|
const minutes = Math.floor(totalSeconds / 60) % 60;
|
|
@@ -524,7 +725,7 @@ function formatDuration(ms) {
|
|
|
524
725
|
return `${seconds}s`;
|
|
525
726
|
}
|
|
526
727
|
function formatTokens(value) {
|
|
527
|
-
const n = Math.max(0, Math.round(value));
|
|
728
|
+
const n = Number.isFinite(value) ? Math.max(0, Math.round(value)) : 0;
|
|
528
729
|
if (n < 1000)
|
|
529
730
|
return String(n);
|
|
530
731
|
if (n < 999500) {
|
|
@@ -541,12 +742,28 @@ function trimZeros(value) {
|
|
|
541
742
|
return value.includes(".") ? value.replace(/0+$/, "").replace(/\.$/, "") : value;
|
|
542
743
|
}
|
|
543
744
|
function formatCost(value) {
|
|
544
|
-
if (value <= 0)
|
|
745
|
+
if (!Number.isFinite(value) || value <= 0)
|
|
545
746
|
return "$0";
|
|
747
|
+
if (value < 0.00005)
|
|
748
|
+
return "<$0.0001";
|
|
546
749
|
if (value < 1)
|
|
547
750
|
return `$${value.toFixed(4)}`;
|
|
548
751
|
return `$${value.toFixed(2)}`;
|
|
549
752
|
}
|
|
753
|
+
function formatMoney(charged, estimated, marker = "\u2248") {
|
|
754
|
+
const paid = Number.isFinite(charged) && charged > 0 ? formatCost(charged) : undefined;
|
|
755
|
+
const estimate = Number.isFinite(estimated) && estimated > 0 ? `${marker.trim() === "" ? "" : `${marker.trim()} `}${formatCost(estimated)}` : undefined;
|
|
756
|
+
if (paid !== undefined && estimate !== undefined)
|
|
757
|
+
return `${paid} + ${estimate}`;
|
|
758
|
+
return paid ?? estimate;
|
|
759
|
+
}
|
|
760
|
+
function formatSpend(charged, estimated, marker = "\u2248") {
|
|
761
|
+
const paid = Number.isFinite(charged) ? Math.max(0, charged) : 0;
|
|
762
|
+
const estimate = Number.isFinite(estimated) ? Math.max(0, estimated) : 0;
|
|
763
|
+
if (estimate > 0)
|
|
764
|
+
return `${marker.trim()}${formatCost(paid + estimate)}`;
|
|
765
|
+
return formatCost(paid);
|
|
766
|
+
}
|
|
550
767
|
function displayTotals(totals) {
|
|
551
768
|
const prompt = totals.input + totals.cached + totals.cacheWrite;
|
|
552
769
|
return {
|
|
@@ -556,11 +773,12 @@ function displayTotals(totals) {
|
|
|
556
773
|
output: totals.output + totals.reasoning,
|
|
557
774
|
reasoning: totals.reasoning,
|
|
558
775
|
cost: totals.cost,
|
|
776
|
+
listCost: totals.listCost,
|
|
559
777
|
steps: totals.steps,
|
|
560
778
|
prompt
|
|
561
779
|
};
|
|
562
780
|
}
|
|
563
|
-
function totalsText(prefix, totals, labels, fields, stepCount = 0, cost = totals.cost) {
|
|
781
|
+
function totalsText(prefix, totals, labels, fields, stepCount = 0, cost = totals.cost, listCost = totals.listCost, estimates = true) {
|
|
564
782
|
const display = displayTotals(totals);
|
|
565
783
|
const input = display.prompt === display.input ? `${labels.input} ${formatTokens(display.input)}` : `${labels.input} ${formatTokens(display.input)} (${formatTokens(display.prompt)})`;
|
|
566
784
|
const parts = [
|
|
@@ -570,8 +788,9 @@ function totalsText(prefix, totals, labels, fields, stepCount = 0, cost = totals
|
|
|
570
788
|
];
|
|
571
789
|
if (fields.reasoning)
|
|
572
790
|
parts.push(`${labels.reasoning} ${formatTokens(display.reasoning)}`);
|
|
573
|
-
|
|
574
|
-
|
|
791
|
+
const money = fields.cost ? formatMoney(cost, estimates ? listCost : 0, labels.estimate) : undefined;
|
|
792
|
+
if (money !== undefined)
|
|
793
|
+
parts.push(`${labels.cost} ${money}`);
|
|
575
794
|
const steps = stepCount > 1 ? `${stepCount} ${stepCount === 1 ? labels.step : labels.steps}` : "";
|
|
576
795
|
const head = [prefix, steps].filter((piece) => piece !== "").join(" ");
|
|
577
796
|
const numbers = parts.join(", ");
|
|
@@ -583,6 +802,7 @@ function formatLineSegments(stats, options) {
|
|
|
583
802
|
const labels = { ...DEFAULT_LABELS, ...options?.labels };
|
|
584
803
|
const fields = { ...DEFAULT_FIELDS, ...options?.fields };
|
|
585
804
|
const turnTotals = options?.turnTotals ?? "latest";
|
|
805
|
+
const estimates = options?.estimates !== false;
|
|
586
806
|
const segments = [];
|
|
587
807
|
if (fields.clock && stats.endAt !== undefined) {
|
|
588
808
|
segments.push({ text: formatClock(stats.endAt), tone: "muted" });
|
|
@@ -605,12 +825,15 @@ function formatLineSegments(stats, options) {
|
|
|
605
825
|
if (fields.turn && stats.totals.steps > 0) {
|
|
606
826
|
const totals = turnTotals === "sum" ? stats.totals : stats.latest;
|
|
607
827
|
segments.push({
|
|
608
|
-
text: totalsText(labels.turn, totals, labels, fields, turnTotals === "sum" ? stats.totals.steps : stats.steps, stats.totals.cost),
|
|
828
|
+
text: totalsText(labels.turn, totals, labels, fields, turnTotals === "sum" ? stats.totals.steps : stats.steps, stats.totals.cost, stats.totals.listCost, estimates),
|
|
609
829
|
tone: "base"
|
|
610
830
|
});
|
|
611
831
|
}
|
|
612
832
|
if (fields.session && stats.session) {
|
|
613
|
-
segments.push({
|
|
833
|
+
segments.push({
|
|
834
|
+
text: totalsText(labels.session, stats.session, labels, fields, 0, stats.session.cost, stats.session.listCost, estimates),
|
|
835
|
+
tone: "muted"
|
|
836
|
+
});
|
|
614
837
|
}
|
|
615
838
|
if (fields.cacheExpiry && stats.cacheExpired) {
|
|
616
839
|
const count = stats.drops.length > 1 ? `\xD7${stats.drops.length}` : "";
|
|
@@ -625,6 +848,73 @@ function formatLine(stats, options) {
|
|
|
625
848
|
// src/stats/queries.ts
|
|
626
849
|
var COMPACTION_KIND = "compaction";
|
|
627
850
|
var DEFAULT_TTL_HINT_MS = 10 * 60 * 1000;
|
|
851
|
+
function spend(usage) {
|
|
852
|
+
return usage.cost + usage.listCost;
|
|
853
|
+
}
|
|
854
|
+
function sessionListCost(db, sessionID) {
|
|
855
|
+
const row = db.query("SELECT COALESCE(SUM(list_cost), 0) AS listCost FROM steps WHERE session_id = ?").get(sessionID);
|
|
856
|
+
return row?.listCost ?? 0;
|
|
857
|
+
}
|
|
858
|
+
var EMPTY_OTHER = { entries: 0, cost: 0 };
|
|
859
|
+
function hasUsageTable(db) {
|
|
860
|
+
try {
|
|
861
|
+
return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'usage'").get() !== null;
|
|
862
|
+
} catch {
|
|
863
|
+
return false;
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
function otherWhere(range, filters) {
|
|
867
|
+
if (filters?.modelID !== undefined && filters.modelID !== "")
|
|
868
|
+
return;
|
|
869
|
+
if (filters?.modelKey !== undefined && filters.modelKey !== "")
|
|
870
|
+
return;
|
|
871
|
+
if (filters?.provider !== undefined && filters.provider !== "")
|
|
872
|
+
return;
|
|
873
|
+
const span = rangeWhere(range, "at");
|
|
874
|
+
const clauses = span.where === "" ? [] : [span.where.slice("WHERE ".length)];
|
|
875
|
+
const params = [...span.params];
|
|
876
|
+
if (filters?.sessionID !== undefined && filters.sessionID !== "") {
|
|
877
|
+
clauses.push("session_id = ?");
|
|
878
|
+
params.push(filters.sessionID);
|
|
879
|
+
}
|
|
880
|
+
return { where: clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "", params };
|
|
881
|
+
}
|
|
882
|
+
function otherUsage(db, range, filters) {
|
|
883
|
+
const filter = otherWhere(range, filters);
|
|
884
|
+
if (filter === undefined || !hasUsageTable(db))
|
|
885
|
+
return { ...EMPTY_OTHER };
|
|
886
|
+
try {
|
|
887
|
+
const row = db.query(`SELECT COUNT(*) AS entries, COALESCE(SUM(cost), 0) AS cost FROM usage ${filter.where}`).get(...filter.params);
|
|
888
|
+
return { entries: row?.entries ?? 0, cost: row?.cost ?? 0 };
|
|
889
|
+
} catch {
|
|
890
|
+
return { ...EMPTY_OTHER };
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
function otherUsageBySession(db, range, filters) {
|
|
894
|
+
const out = new Map;
|
|
895
|
+
const filter = otherWhere(range, filters);
|
|
896
|
+
if (filter === undefined || !hasUsageTable(db))
|
|
897
|
+
return out;
|
|
898
|
+
try {
|
|
899
|
+
const rows = db.query(`SELECT session_id AS sessionID, COUNT(*) AS entries, COALESCE(SUM(cost), 0) AS cost
|
|
900
|
+
FROM usage ${filter.where}
|
|
901
|
+
GROUP BY session_id`).all(...filter.params);
|
|
902
|
+
for (const row of rows)
|
|
903
|
+
out.set(row.sessionID, { entries: row.entries ?? 0, cost: row.cost ?? 0 });
|
|
904
|
+
} catch {}
|
|
905
|
+
return out;
|
|
906
|
+
}
|
|
907
|
+
function otherUsageRows(db, range, filters) {
|
|
908
|
+
const filter = otherWhere(range, filters);
|
|
909
|
+
if (filter === undefined || !hasUsageTable(db))
|
|
910
|
+
return [];
|
|
911
|
+
const where = filter.where === "" ? "WHERE at IS NOT NULL" : `${filter.where} AND at IS NOT NULL`;
|
|
912
|
+
try {
|
|
913
|
+
return db.query(`SELECT session_id AS sessionID, at, cost FROM usage ${where} ORDER BY at`).all(...filter.params);
|
|
914
|
+
} catch {
|
|
915
|
+
return [];
|
|
916
|
+
}
|
|
917
|
+
}
|
|
628
918
|
var STEP_TIME = "COALESCE(created_at, recorded_at)";
|
|
629
919
|
var MODEL_KEY_SQL = "COALESCE(model_id, '(unknown)') || '#' || COALESCE(variant, '')";
|
|
630
920
|
function modelKey(modelID, variant) {
|
|
@@ -639,7 +929,8 @@ var USAGE_SELECT = `COUNT(*) AS steps,
|
|
|
639
929
|
COALESCE(SUM(cache_write), 0) AS cacheWrite,
|
|
640
930
|
COALESCE(SUM(output_tokens), 0) AS output,
|
|
641
931
|
COALESCE(SUM(reasoning_tokens), 0) AS reasoning,
|
|
642
|
-
COALESCE(SUM(cost), 0) AS cost
|
|
932
|
+
COALESCE(SUM(cost), 0) AS cost,
|
|
933
|
+
COALESCE(SUM(list_cost), 0) AS listCost`;
|
|
643
934
|
function usageFrom(row) {
|
|
644
935
|
return {
|
|
645
936
|
steps: row.steps ?? 0,
|
|
@@ -648,7 +939,8 @@ function usageFrom(row) {
|
|
|
648
939
|
cacheWrite: row.cacheWrite ?? 0,
|
|
649
940
|
output: row.output ?? 0,
|
|
650
941
|
reasoning: row.reasoning ?? 0,
|
|
651
|
-
cost: row.cost ?? 0
|
|
942
|
+
cost: row.cost ?? 0,
|
|
943
|
+
listCost: row.listCost ?? 0
|
|
652
944
|
};
|
|
653
945
|
}
|
|
654
946
|
function rangeWhere(range, column = STEP_TIME) {
|
|
@@ -700,12 +992,22 @@ function overview(db, range, filters) {
|
|
|
700
992
|
COALESCE(SUM(CASE WHEN streamed_at > created_at THEN streamed_at - created_at ELSE 0 END), 0) AS window
|
|
701
993
|
FROM steps ${steps.where}`).get(...steps.params);
|
|
702
994
|
const prompts = rangeWhere(range, "created_at");
|
|
703
|
-
const
|
|
704
|
-
const
|
|
995
|
+
const promptClauses = prompts.where === "" ? [] : [prompts.where.slice("WHERE ".length)];
|
|
996
|
+
const promptParams = [...prompts.params];
|
|
997
|
+
if (filters?.sessionID !== undefined && filters.sessionID !== "") {
|
|
998
|
+
promptClauses.push("session_id = ?");
|
|
999
|
+
promptParams.push(filters.sessionID);
|
|
1000
|
+
}
|
|
1001
|
+
const promptWhere = promptClauses.length > 0 ? `WHERE ${promptClauses.join(" AND ")}` : "";
|
|
1002
|
+
const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${promptWhere}`).get(...promptParams);
|
|
1003
|
+
const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
|
|
1004
|
+
const other = otherUsage(db, range, filters);
|
|
705
1005
|
return {
|
|
706
1006
|
...usage,
|
|
1007
|
+
cost: usage.cost + other.cost,
|
|
707
1008
|
sessions: row?.sessions ?? 0,
|
|
708
1009
|
prompts: promptRow?.prompts ?? 0,
|
|
1010
|
+
otherCost: other.cost,
|
|
709
1011
|
firstAt: row?.firstAt ?? undefined,
|
|
710
1012
|
lastAt: row?.lastAt ?? undefined,
|
|
711
1013
|
cacheHitRatio: cacheHitRatio(usage),
|
|
@@ -743,7 +1045,7 @@ function models(db, range, filters) {
|
|
|
743
1045
|
return [...models.values()].sort((a, b) => billedTokens(b.totals) - billedTokens(a.totals));
|
|
744
1046
|
}
|
|
745
1047
|
function emptyUsage() {
|
|
746
|
-
return { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0 };
|
|
1048
|
+
return { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 };
|
|
747
1049
|
}
|
|
748
1050
|
function addUsage(target, source) {
|
|
749
1051
|
target.steps += source.steps;
|
|
@@ -753,9 +1055,10 @@ function addUsage(target, source) {
|
|
|
753
1055
|
target.output += source.output;
|
|
754
1056
|
target.reasoning += source.reasoning;
|
|
755
1057
|
target.cost += source.cost;
|
|
1058
|
+
target.listCost += source.listCost;
|
|
756
1059
|
}
|
|
757
1060
|
function billedTokens(usage) {
|
|
758
|
-
return usage.input + usage.cached + usage.output;
|
|
1061
|
+
return usage.input + usage.cached + usage.cacheWrite + usage.output + usage.reasoning;
|
|
759
1062
|
}
|
|
760
1063
|
function percentile(values, p) {
|
|
761
1064
|
if (values.length === 0)
|
|
@@ -781,6 +1084,17 @@ function sessions(db, options) {
|
|
|
781
1084
|
const limit = options?.limit ?? 20;
|
|
782
1085
|
const clauses = filter.where === "" ? [] : [filter.where.slice("WHERE ".length)];
|
|
783
1086
|
const params = [...filter.params];
|
|
1087
|
+
const promptRange = [];
|
|
1088
|
+
const promptParams = [];
|
|
1089
|
+
if (range?.from !== undefined) {
|
|
1090
|
+
promptRange.push("p.created_at >= ?");
|
|
1091
|
+
promptParams.push(range.from);
|
|
1092
|
+
}
|
|
1093
|
+
if (range?.to !== undefined) {
|
|
1094
|
+
promptRange.push("p.created_at < ?");
|
|
1095
|
+
promptParams.push(range.to);
|
|
1096
|
+
}
|
|
1097
|
+
const promptClause = promptRange.length > 0 ? ` AND ${promptRange.join(" AND ")}` : "";
|
|
784
1098
|
if (options?.sessionIDs !== undefined) {
|
|
785
1099
|
const ids = options.sessionIDs.slice(0, 500);
|
|
786
1100
|
clauses.push(`st.session_id IN (${ids.map(() => "?").join(", ")})`);
|
|
@@ -789,7 +1103,7 @@ function sessions(db, options) {
|
|
|
789
1103
|
const rows = db.query(`SELECT st.session_id, s.title, s.directory, s.parent_id,
|
|
790
1104
|
GROUP_CONCAT(DISTINCT st.provider_id) AS providers,
|
|
791
1105
|
GROUP_CONCAT(DISTINCT st.model_id) AS models,
|
|
792
|
-
(SELECT COUNT(*) FROM prompts p WHERE p.session_id = st.session_id) AS prompts,
|
|
1106
|
+
(SELECT COUNT(*) FROM prompts p WHERE p.session_id = st.session_id${promptClause}) AS prompts,
|
|
793
1107
|
COUNT(*) AS steps,
|
|
794
1108
|
COALESCE(SUM(st.input_tokens), 0) AS input,
|
|
795
1109
|
COALESCE(SUM(st.cache_read), 0) AS cached,
|
|
@@ -797,6 +1111,7 @@ function sessions(db, options) {
|
|
|
797
1111
|
COALESCE(SUM(st.output_tokens), 0) AS output,
|
|
798
1112
|
COALESCE(SUM(st.reasoning_tokens), 0) AS reasoning,
|
|
799
1113
|
COALESCE(SUM(st.cost), 0) AS cost,
|
|
1114
|
+
COALESCE(SUM(st.list_cost), 0) AS listCost,
|
|
800
1115
|
MIN(COALESCE(st.created_at, st.recorded_at)) AS first_at,
|
|
801
1116
|
MAX(COALESCE(st.completed_at, st.created_at, st.recorded_at)) AS last_at
|
|
802
1117
|
FROM steps st
|
|
@@ -804,11 +1119,14 @@ function sessions(db, options) {
|
|
|
804
1119
|
${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
|
|
805
1120
|
GROUP BY st.session_id
|
|
806
1121
|
ORDER BY last_at DESC
|
|
807
|
-
LIMIT ?`).all(...params, limit);
|
|
1122
|
+
LIMIT ?`).all(...promptParams, ...params, limit);
|
|
1123
|
+
const other = otherUsageBySession(db, range, options?.filters);
|
|
808
1124
|
return rows.map((row) => {
|
|
809
1125
|
const usage = usageFrom(row);
|
|
1126
|
+
const extra = other.get(row.session_id)?.cost ?? 0;
|
|
810
1127
|
return {
|
|
811
1128
|
...usage,
|
|
1129
|
+
cost: usage.cost + extra,
|
|
812
1130
|
sessionID: row.session_id,
|
|
813
1131
|
parentID: row.parent_id ?? undefined,
|
|
814
1132
|
title: row.title ?? undefined,
|
|
@@ -816,6 +1134,7 @@ function sessions(db, options) {
|
|
|
816
1134
|
providers: row.providers ? row.providers.split(",").filter(Boolean) : [],
|
|
817
1135
|
models: row.models ? row.models.split(",").filter(Boolean) : [],
|
|
818
1136
|
prompts: row.prompts ?? 0,
|
|
1137
|
+
otherCost: extra,
|
|
819
1138
|
firstAt: row.first_at ?? undefined,
|
|
820
1139
|
lastAt: row.last_at ?? undefined,
|
|
821
1140
|
cacheHitRatio: cacheHitRatio(usage)
|
|
@@ -839,7 +1158,8 @@ function stepUsage(row) {
|
|
|
839
1158
|
cacheWrite: row.cache_write ?? 0,
|
|
840
1159
|
output: row.output_tokens ?? 0,
|
|
841
1160
|
reasoning: row.reasoning_tokens ?? 0,
|
|
842
|
-
cost: row.cost ?? 0
|
|
1161
|
+
cost: row.cost ?? 0,
|
|
1162
|
+
listCost: row.list_cost ?? 0
|
|
843
1163
|
};
|
|
844
1164
|
}
|
|
845
1165
|
function stepMessage(row) {
|
|
@@ -858,118 +1178,131 @@ function stepMessage(row) {
|
|
|
858
1178
|
};
|
|
859
1179
|
}
|
|
860
1180
|
function turns(db, options) {
|
|
861
|
-
const
|
|
1181
|
+
const requested = options?.limit ?? 50;
|
|
1182
|
+
const limit = Number.isFinite(requested) ? Math.max(0, Math.floor(requested)) : 50;
|
|
862
1183
|
const filter = buildWhere(options?.range, options?.filters);
|
|
863
|
-
const
|
|
864
|
-
const
|
|
1184
|
+
const baseClauses = filter.where === "" ? [] : [filter.where.slice("WHERE ".length)];
|
|
1185
|
+
const baseParams = [...filter.params];
|
|
865
1186
|
if (options?.sessionID !== undefined) {
|
|
866
|
-
|
|
867
|
-
|
|
1187
|
+
baseClauses.push("session_id = ?");
|
|
1188
|
+
baseParams.push(options.sessionID);
|
|
868
1189
|
}
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
created_at, streamed_at, recorded_at, completed_at, finish
|
|
877
|
-
FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
|
|
878
|
-
ORDER BY session_id, ${STEP_TIME}`).all(...params);
|
|
879
|
-
const promptClause = options?.sessionID === undefined ? "" : `WHERE session_id = ?${floor === undefined ? "" : " AND created_at >= ?"}`;
|
|
880
|
-
const promptParams = options?.sessionID === undefined ? [] : floor === undefined ? [options.sessionID] : [options.sessionID, floor];
|
|
881
|
-
const promptRows = db.query(`SELECT session_id, created_at FROM prompts ${promptClause} ORDER BY session_id, created_at`).all(...promptParams);
|
|
882
|
-
const promptsBySession = new Map;
|
|
883
|
-
for (const row of promptRows) {
|
|
884
|
-
if (row.created_at === null)
|
|
885
|
-
continue;
|
|
886
|
-
const list = promptsBySession.get(row.session_id) ?? [];
|
|
887
|
-
list.push(row.created_at);
|
|
888
|
-
promptsBySession.set(row.session_id, list);
|
|
889
|
-
}
|
|
890
|
-
const result = [];
|
|
891
|
-
let sessionID;
|
|
892
|
-
let bucket = [];
|
|
893
|
-
let promptIndex = -2;
|
|
894
|
-
let promptAt;
|
|
895
|
-
let previousPromptAt;
|
|
896
|
-
function close() {
|
|
897
|
-
const last = bucket[bucket.length - 1];
|
|
898
|
-
if (last === undefined || !turnFinished(last.finish)) {
|
|
899
|
-
bucket = [];
|
|
900
|
-
return;
|
|
901
|
-
}
|
|
902
|
-
const totals = emptyUsage();
|
|
903
|
-
for (const row of bucket)
|
|
904
|
-
addUsage(totals, stepUsage(row));
|
|
905
|
-
const drops = [];
|
|
906
|
-
let reference;
|
|
907
|
-
for (const row of bucket) {
|
|
908
|
-
const message = stepMessage(row);
|
|
909
|
-
const drop = cacheDrop(reference, message);
|
|
910
|
-
if (drop !== undefined) {
|
|
911
|
-
drops.push({ messageID: row.message_id, tokens: drop, gapMs: stepGap(reference, message) });
|
|
912
|
-
}
|
|
913
|
-
reference = message;
|
|
1190
|
+
function read(promptCount) {
|
|
1191
|
+
const clauses = [...baseClauses];
|
|
1192
|
+
const params = [...baseParams];
|
|
1193
|
+
const floor = options?.sessionID === undefined ? undefined : promptFloor(db, options.sessionID, promptCount);
|
|
1194
|
+
if (floor !== undefined) {
|
|
1195
|
+
clauses.push(`${STEP_TIME} >= ?`);
|
|
1196
|
+
params.push(floor);
|
|
914
1197
|
}
|
|
915
|
-
const
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
1198
|
+
const steps = db.query(`SELECT message_id, session_id, provider_id, model_id, variant,
|
|
1199
|
+
input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,
|
|
1200
|
+
created_at, streamed_at, recorded_at, completed_at, finish
|
|
1201
|
+
FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
|
|
1202
|
+
ORDER BY session_id, ${STEP_TIME}, message_id`).all(...params);
|
|
1203
|
+
const promptClause = options?.sessionID === undefined ? "" : `WHERE session_id = ?${floor === undefined ? "" : " AND created_at >= ?"}`;
|
|
1204
|
+
const promptParams = options?.sessionID === undefined ? [] : floor === undefined ? [options.sessionID] : [options.sessionID, floor];
|
|
1205
|
+
const promptRows = db.query(`SELECT session_id, created_at FROM prompts ${promptClause} ORDER BY session_id, created_at`).all(...promptParams);
|
|
1206
|
+
const promptsBySession = new Map;
|
|
1207
|
+
for (const row of promptRows) {
|
|
1208
|
+
if (row.created_at === null)
|
|
922
1209
|
continue;
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
const previous = result.length > 0 && result[result.length - 1].sessionID === last.session_id ? result[result.length - 1] : undefined;
|
|
927
|
-
result.push({
|
|
928
|
-
sessionID: last.session_id,
|
|
929
|
-
promptAt,
|
|
930
|
-
endAt: last.completed_at ?? last.created_at ?? last.recorded_at,
|
|
931
|
-
promptGapMs: promptAt !== undefined && previousPromptAt !== undefined ? Math.max(0, promptAt - previousPromptAt) : undefined,
|
|
932
|
-
providerID,
|
|
933
|
-
modelID,
|
|
934
|
-
variant,
|
|
935
|
-
providerChanged: previous?.providerID !== undefined && providerID !== undefined && previous.providerID !== providerID,
|
|
936
|
-
modelChanged: previous !== undefined && previous.providerID === providerID && `${previous.modelID ?? ""}#${previous.variant ?? ""}` !== `${modelID ?? ""}#${variant ?? ""}`,
|
|
937
|
-
steps: bucket.length,
|
|
938
|
-
latest: stepUsage(last),
|
|
939
|
-
totals,
|
|
940
|
-
drops,
|
|
941
|
-
finish: last.finish ?? undefined,
|
|
942
|
-
tps: tokensPerSecond(produced, 0, window)
|
|
943
|
-
});
|
|
944
|
-
bucket = [];
|
|
945
|
-
}
|
|
946
|
-
for (const row of steps) {
|
|
947
|
-
if (row.session_id !== sessionID) {
|
|
948
|
-
close();
|
|
949
|
-
sessionID = row.session_id;
|
|
950
|
-
promptIndex = -2;
|
|
951
|
-
promptAt = undefined;
|
|
952
|
-
previousPromptAt = undefined;
|
|
1210
|
+
const list = promptsBySession.get(row.session_id) ?? [];
|
|
1211
|
+
list.push(row.created_at);
|
|
1212
|
+
promptsBySession.set(row.session_id, list);
|
|
953
1213
|
}
|
|
954
|
-
const
|
|
955
|
-
|
|
956
|
-
let
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
1214
|
+
const result = [];
|
|
1215
|
+
let sessionID;
|
|
1216
|
+
let bucket = [];
|
|
1217
|
+
let promptIndex = -2;
|
|
1218
|
+
let promptAt;
|
|
1219
|
+
function close() {
|
|
1220
|
+
const last = bucket[bucket.length - 1];
|
|
1221
|
+
if (last === undefined || !turnFinished(last.finish)) {
|
|
1222
|
+
bucket = [];
|
|
1223
|
+
return;
|
|
961
1224
|
}
|
|
1225
|
+
const totals = emptyUsage();
|
|
1226
|
+
for (const row of bucket)
|
|
1227
|
+
addUsage(totals, stepUsage(row));
|
|
1228
|
+
const drops = [];
|
|
1229
|
+
let reference;
|
|
1230
|
+
for (const row of bucket) {
|
|
1231
|
+
const message = stepMessage(row);
|
|
1232
|
+
const drop = cacheDrop(reference, message);
|
|
1233
|
+
if (drop !== undefined) {
|
|
1234
|
+
drops.push({ messageID: row.message_id, tokens: drop, gapMs: stepGap(reference, message) });
|
|
1235
|
+
}
|
|
1236
|
+
reference = message;
|
|
1237
|
+
}
|
|
1238
|
+
const providerID = last.provider_id ?? undefined;
|
|
1239
|
+
const modelID = last.model_id ?? undefined;
|
|
1240
|
+
const variant = last.variant ?? undefined;
|
|
1241
|
+
let produced = 0;
|
|
1242
|
+
let window = 0;
|
|
1243
|
+
for (const row of bucket) {
|
|
1244
|
+
if (row.created_at === null || row.streamed_at === null || row.streamed_at <= row.created_at)
|
|
1245
|
+
continue;
|
|
1246
|
+
produced += (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0);
|
|
1247
|
+
window += row.streamed_at - row.created_at;
|
|
1248
|
+
}
|
|
1249
|
+
const previous = result.length > 0 && result[result.length - 1].sessionID === last.session_id ? result[result.length - 1] : undefined;
|
|
1250
|
+
result.push({
|
|
1251
|
+
sessionID: last.session_id,
|
|
1252
|
+
promptAt,
|
|
1253
|
+
endAt: last.completed_at ?? last.created_at ?? last.recorded_at,
|
|
1254
|
+
promptGapMs: promptAt !== undefined && previous?.promptAt !== undefined ? Math.max(0, promptAt - previous.promptAt) : undefined,
|
|
1255
|
+
providerID,
|
|
1256
|
+
modelID,
|
|
1257
|
+
variant,
|
|
1258
|
+
providerChanged: previous?.providerID !== undefined && providerID !== undefined && previous.providerID !== providerID,
|
|
1259
|
+
modelChanged: previous !== undefined && previous.providerID === providerID && `${previous.modelID ?? ""}#${previous.variant ?? ""}` !== `${modelID ?? ""}#${variant ?? ""}`,
|
|
1260
|
+
steps: bucket.length,
|
|
1261
|
+
latest: stepUsage(last),
|
|
1262
|
+
totals,
|
|
1263
|
+
drops,
|
|
1264
|
+
finish: last.finish ?? undefined,
|
|
1265
|
+
tps: tokensPerSecond(produced, 0, window)
|
|
1266
|
+
});
|
|
1267
|
+
bucket = [];
|
|
962
1268
|
}
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
1269
|
+
for (const row of steps) {
|
|
1270
|
+
if (row.session_id !== sessionID) {
|
|
1271
|
+
close();
|
|
1272
|
+
sessionID = row.session_id;
|
|
1273
|
+
promptIndex = -2;
|
|
1274
|
+
promptAt = undefined;
|
|
1275
|
+
}
|
|
1276
|
+
const time = row.created_at ?? row.recorded_at;
|
|
1277
|
+
const prompts = promptsBySession.get(row.session_id) ?? [];
|
|
1278
|
+
let index = -1;
|
|
1279
|
+
for (let candidate = prompts.length - 1;candidate >= 0; candidate -= 1) {
|
|
1280
|
+
if ((prompts[candidate] ?? Number.POSITIVE_INFINITY) <= time) {
|
|
1281
|
+
index = candidate;
|
|
1282
|
+
break;
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
if (index !== promptIndex) {
|
|
1286
|
+
close();
|
|
1287
|
+
promptIndex = index;
|
|
1288
|
+
promptAt = index >= 0 ? prompts[index] : undefined;
|
|
1289
|
+
}
|
|
1290
|
+
bucket.push(row);
|
|
968
1291
|
}
|
|
969
|
-
|
|
1292
|
+
close();
|
|
1293
|
+
const reachedRangeStart = options?.range?.from !== undefined && floor !== undefined && floor <= options.range.from;
|
|
1294
|
+
return { rows: result.reverse(), complete: floor === undefined || reachedRangeStart };
|
|
1295
|
+
}
|
|
1296
|
+
let promptCount = Math.max(1, limit + 1);
|
|
1297
|
+
for (;; ) {
|
|
1298
|
+
const { rows, complete } = read(promptCount);
|
|
1299
|
+
if (rows.length >= limit || complete)
|
|
1300
|
+
return rows.slice(0, limit);
|
|
1301
|
+
const next = promptCount * 2 + 1;
|
|
1302
|
+
if (!Number.isFinite(next) || next <= promptCount)
|
|
1303
|
+
return rows.slice(0, limit);
|
|
1304
|
+
promptCount = next;
|
|
970
1305
|
}
|
|
971
|
-
close();
|
|
972
|
-
return result.reverse().slice(0, limit);
|
|
973
1306
|
}
|
|
974
1307
|
function promptFloor(db, sessionID, count) {
|
|
975
1308
|
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);
|
|
@@ -1048,6 +1381,14 @@ function createRecorder(db, options) {
|
|
|
1048
1381
|
const info = pending.get(messageID);
|
|
1049
1382
|
pending.delete(messageID);
|
|
1050
1383
|
const model = info?.model ?? lastModel.get(sessionID);
|
|
1384
|
+
const charged = data.cost;
|
|
1385
|
+
const estimate = charged !== undefined && charged > 0 ? undefined : options?.price?.({ providerID: model?.providerID, modelID: model?.id }, {
|
|
1386
|
+
input: data.tokens?.input,
|
|
1387
|
+
output: data.tokens?.output,
|
|
1388
|
+
reasoning: data.tokens?.reasoning,
|
|
1389
|
+
cacheRead: data.tokens?.cache?.read,
|
|
1390
|
+
cacheWrite: data.tokens?.cache?.write
|
|
1391
|
+
});
|
|
1051
1392
|
write(() => recordStep(db, {
|
|
1052
1393
|
messageID,
|
|
1053
1394
|
sessionID,
|
|
@@ -1060,6 +1401,7 @@ function createRecorder(db, options) {
|
|
|
1060
1401
|
cacheRead: data.tokens?.cache?.read,
|
|
1061
1402
|
cacheWrite: data.tokens?.cache?.write,
|
|
1062
1403
|
cost: data.cost,
|
|
1404
|
+
listCost: estimate !== undefined && Number.isFinite(estimate) && estimate >= 0 ? estimate : undefined,
|
|
1063
1405
|
createdAt: info?.started,
|
|
1064
1406
|
streamedAt: info?.streamed,
|
|
1065
1407
|
completedAt: at,
|
|
@@ -1154,12 +1496,35 @@ function createRecorder(db, options) {
|
|
|
1154
1496
|
recordPendingStep(data.assistantMessageID, data, data.finish ?? "error", at);
|
|
1155
1497
|
return;
|
|
1156
1498
|
}
|
|
1499
|
+
case "session.usage.recorded": {
|
|
1500
|
+
if (sessionID === undefined)
|
|
1501
|
+
return;
|
|
1502
|
+
const source = typeof data.source === "string" ? data.source : undefined;
|
|
1503
|
+
if (source === undefined || source === "generate")
|
|
1504
|
+
return;
|
|
1505
|
+
const id = typeof event.id === "string" && event.id !== "" ? event.id : `${sessionID}:${source}:${at}:${data.cost ?? 0}`;
|
|
1506
|
+
write(() => recordUsage(db, {
|
|
1507
|
+
id,
|
|
1508
|
+
sessionID,
|
|
1509
|
+
source,
|
|
1510
|
+
at,
|
|
1511
|
+
cost: data.cost,
|
|
1512
|
+
input: data.tokens?.input,
|
|
1513
|
+
output: data.tokens?.output,
|
|
1514
|
+
reasoning: data.tokens?.reasoning,
|
|
1515
|
+
cacheRead: data.tokens?.cache?.read,
|
|
1516
|
+
cacheWrite: data.tokens?.cache?.write
|
|
1517
|
+
}));
|
|
1518
|
+
return;
|
|
1519
|
+
}
|
|
1157
1520
|
case "session.compaction.ended": {
|
|
1158
1521
|
if (sessionID === undefined)
|
|
1159
1522
|
return;
|
|
1523
|
+
const messageID = typeof event.id === "string" && event.id !== "" ? event.id : `compaction:${sessionID}:${at}`;
|
|
1160
1524
|
write(() => recordEvent(db, {
|
|
1161
1525
|
sessionID,
|
|
1162
1526
|
kind: COMPACTION_KIND,
|
|
1527
|
+
messageID,
|
|
1163
1528
|
at,
|
|
1164
1529
|
data: { reason: data.reason, model: data.model, tokens: data.tokens, cost: data.cost }
|
|
1165
1530
|
}));
|
|
@@ -1183,6 +1548,40 @@ function createRecorder(db, options) {
|
|
|
1183
1548
|
}
|
|
1184
1549
|
|
|
1185
1550
|
// src/index.ts
|
|
1551
|
+
var PRICE_TTL_MS = 5 * 60 * 1000;
|
|
1552
|
+
var PRICE_RETRY_MS = 30 * 1000;
|
|
1553
|
+
function createPriceSource(ctx) {
|
|
1554
|
+
let table;
|
|
1555
|
+
let refreshing = false;
|
|
1556
|
+
let lastAttempt = 0;
|
|
1557
|
+
function refresh(force = false) {
|
|
1558
|
+
if (refreshing)
|
|
1559
|
+
return;
|
|
1560
|
+
const now = Date.now();
|
|
1561
|
+
const wait = table === undefined ? PRICE_RETRY_MS : PRICE_TTL_MS;
|
|
1562
|
+
if (!force && now - lastAttempt < wait)
|
|
1563
|
+
return;
|
|
1564
|
+
lastAttempt = now;
|
|
1565
|
+
refreshing = true;
|
|
1566
|
+
(async () => {
|
|
1567
|
+
try {
|
|
1568
|
+
const payload = await ctx.model.list();
|
|
1569
|
+
const models = Array.isArray(payload) ? payload : payload?.data;
|
|
1570
|
+
if (Array.isArray(models) && models.length > 0)
|
|
1571
|
+
table = priceTable(models);
|
|
1572
|
+
} catch {} finally {
|
|
1573
|
+
refreshing = false;
|
|
1574
|
+
}
|
|
1575
|
+
})();
|
|
1576
|
+
}
|
|
1577
|
+
return {
|
|
1578
|
+
price: (ref, tokens) => {
|
|
1579
|
+
refresh();
|
|
1580
|
+
return table === undefined ? undefined : costOf(table, ref, tokens);
|
|
1581
|
+
},
|
|
1582
|
+
refresh
|
|
1583
|
+
};
|
|
1584
|
+
}
|
|
1186
1585
|
function tryOpen(path) {
|
|
1187
1586
|
try {
|
|
1188
1587
|
return openStatsDb(path);
|
|
@@ -1202,12 +1601,17 @@ var src_default = Plugin.define({
|
|
|
1202
1601
|
try {
|
|
1203
1602
|
db.exec("PRAGMA busy_timeout = 1000");
|
|
1204
1603
|
} catch {}
|
|
1205
|
-
const
|
|
1604
|
+
const pricing = options.pricing !== "off";
|
|
1605
|
+
const source = pricing ? createPriceSource(ctx) : undefined;
|
|
1606
|
+
source?.refresh(true);
|
|
1607
|
+
const recorder = createRecorder(db, source === undefined ? undefined : { price: source.price });
|
|
1206
1608
|
const abort = new AbortController;
|
|
1207
1609
|
const stream = (async () => {
|
|
1208
1610
|
try {
|
|
1209
1611
|
for await (const event of ctx.event.subscribe({ signal: abort.signal })) {
|
|
1210
1612
|
try {
|
|
1613
|
+
if (event.type === "model.updated")
|
|
1614
|
+
source?.refresh(true);
|
|
1211
1615
|
recorder.handleEvent(event);
|
|
1212
1616
|
} catch {}
|
|
1213
1617
|
}
|
|
@@ -1224,4 +1628,4 @@ export {
|
|
|
1224
1628
|
src_default as default
|
|
1225
1629
|
};
|
|
1226
1630
|
|
|
1227
|
-
//# debugId=
|
|
1631
|
+
//# debugId=54D17612579BB39464756E2164756E21
|