opencode-usage-insights 0.1.0 → 0.1.2
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 +189 -66
- package/dist/core.d.ts +38 -31
- package/dist/index.d.ts +10 -3
- package/dist/index.js +207 -257
- package/dist/index.js.map +10 -10
- package/dist/line.d.ts +20 -7
- package/dist/panel-build.d.ts +5 -1
- package/dist/panel-data.d.ts +36 -23
- package/dist/panel.d.ts +8 -0
- package/dist/pricing.d.ts +72 -0
- package/dist/recorder.d.ts +10 -17
- package/dist/sidebar.d.ts +3 -3
- package/dist/stats/aggregates.d.ts +39 -37
- package/dist/stats/db.d.ts +17 -18
- package/dist/stats/maintenance.d.ts +17 -0
- package/dist/stats/queries.d.ts +25 -30
- package/dist/text.d.ts +5 -8
- package/dist/tui.d.ts +11 -10
- package/dist/tui.js +583 -428
- package/dist/tui.js.map +16 -15
- package/package.json +2 -2
- package/dist/endpoint.d.ts +0 -46
package/dist/index.js
CHANGED
|
@@ -2,6 +2,75 @@
|
|
|
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
|
+
const size = cost.tier?.size;
|
|
32
|
+
const tier = cost.tier !== undefined && typeof size === "number" && Number.isFinite(size) && size >= 0 ? { ...cost.tier.type !== undefined ? { type: cost.tier.type } : {}, size } : undefined;
|
|
33
|
+
tiers.push({
|
|
34
|
+
...tier !== undefined ? { tier } : {},
|
|
35
|
+
input: money(cost.input),
|
|
36
|
+
output: money(cost.output),
|
|
37
|
+
cacheRead: money(cost.cache?.read),
|
|
38
|
+
cacheWrite: money(cost.cache?.write)
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
if (tiers.length > 0)
|
|
42
|
+
table.set(`${providerID}/${modelID}`, { tiers });
|
|
43
|
+
}
|
|
44
|
+
return table;
|
|
45
|
+
}
|
|
46
|
+
function priceOf(table, ref) {
|
|
47
|
+
if (ref.providerID === undefined || ref.providerID === "")
|
|
48
|
+
return;
|
|
49
|
+
if (ref.modelID === undefined || ref.modelID === "")
|
|
50
|
+
return;
|
|
51
|
+
return table.get(`${ref.providerID}/${ref.modelID}`);
|
|
52
|
+
}
|
|
53
|
+
function costOf(table, ref, usage) {
|
|
54
|
+
const price = priceOf(table, ref);
|
|
55
|
+
if (price === undefined)
|
|
56
|
+
return;
|
|
57
|
+
const input = tokens(usage.input);
|
|
58
|
+
const output = tokens(usage.output);
|
|
59
|
+
const reasoning = tokens(usage.reasoning);
|
|
60
|
+
const cacheRead = tokens(usage.cacheRead);
|
|
61
|
+
const cacheWrite = tokens(usage.cacheWrite);
|
|
62
|
+
const prompt = input + cacheRead + cacheWrite;
|
|
63
|
+
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);
|
|
64
|
+
if (selected === undefined)
|
|
65
|
+
return;
|
|
66
|
+
if (selected.input === 0 && selected.output === 0 && selected.cacheRead === 0 && selected.cacheWrite === 0)
|
|
67
|
+
return 0;
|
|
68
|
+
const billed = input * selected.input + (output + reasoning) * selected.output + cacheRead * selected.cacheRead + cacheWrite * selected.cacheWrite;
|
|
69
|
+
if (!Number.isFinite(billed) || billed <= 0)
|
|
70
|
+
return;
|
|
71
|
+
return billed / 1e6;
|
|
72
|
+
}
|
|
73
|
+
|
|
5
74
|
// src/stats/db.ts
|
|
6
75
|
import { Database } from "bun:sqlite";
|
|
7
76
|
import { chmodSync, mkdirSync } from "fs";
|
|
@@ -70,13 +139,9 @@ var TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;
|
|
|
70
139
|
function isToken(value, limit = 64) {
|
|
71
140
|
return value.length > 0 && value.length <= limit && TOKEN.test(value);
|
|
72
141
|
}
|
|
73
|
-
function normalizeToken(value, limit = 64) {
|
|
74
|
-
const trimmed = value.trim().toLowerCase();
|
|
75
|
-
return isToken(trimmed, limit) ? trimmed : undefined;
|
|
76
|
-
}
|
|
77
142
|
|
|
78
143
|
// src/stats/db.ts
|
|
79
|
-
var SCHEMA_VERSION =
|
|
144
|
+
var SCHEMA_VERSION = 10;
|
|
80
145
|
var LABEL_LIMIT = 4 * TEXT_LIMIT;
|
|
81
146
|
var SCHEMA = `
|
|
82
147
|
CREATE TABLE IF NOT EXISTS meta (
|
|
@@ -114,17 +179,16 @@ CREATE TABLE IF NOT EXISTS steps (
|
|
|
114
179
|
cache_read INTEGER NOT NULL DEFAULT 0,
|
|
115
180
|
cache_write INTEGER NOT NULL DEFAULT 0,
|
|
116
181
|
cost REAL NOT NULL DEFAULT 0,
|
|
182
|
+
list_cost REAL,
|
|
117
183
|
created_at INTEGER,
|
|
118
184
|
streamed_at INTEGER,
|
|
119
185
|
completed_at INTEGER,
|
|
120
186
|
finish TEXT,
|
|
121
|
-
router TEXT,
|
|
122
187
|
recorded_at INTEGER NOT NULL
|
|
123
188
|
);
|
|
124
189
|
CREATE INDEX IF NOT EXISTS steps_session ON steps(session_id, created_at);
|
|
125
190
|
CREATE INDEX IF NOT EXISTS steps_model ON steps(provider_id, model_id, variant);
|
|
126
191
|
CREATE INDEX IF NOT EXISTS steps_completed ON steps(completed_at);
|
|
127
|
-
CREATE INDEX IF NOT EXISTS steps_router ON steps(router);
|
|
128
192
|
-- Every range filter and every ordering compares the step's own clock, which
|
|
129
193
|
-- falls back to the recording time for a step that was already in flight when
|
|
130
194
|
-- the plugin loaded. The index has to cover that expression, or every ranged
|
|
@@ -155,10 +219,7 @@ function jsonText(value) {
|
|
|
155
219
|
return null;
|
|
156
220
|
}
|
|
157
221
|
}
|
|
158
|
-
var
|
|
159
|
-
["router", "ALTER TABLE steps ADD COLUMN router TEXT"]
|
|
160
|
-
];
|
|
161
|
-
var REMOVED_COLUMNS = ["provider_state", "upstream", "upstream_source", "upstream_model", "tps"];
|
|
222
|
+
var REMOVED_COLUMNS = ["provider_state", "upstream", "upstream_source", "upstream_model", "tps", "router"];
|
|
162
223
|
var REMOVED_EVENT_KINDS = ["execution", "step-failed", "model-selected", "usage-recorded"];
|
|
163
224
|
function dropUnused(db) {
|
|
164
225
|
const objects = db.query("SELECT name, type FROM sqlite_master WHERE type IN ('table', 'index')").all();
|
|
@@ -168,6 +229,8 @@ function dropUnused(db) {
|
|
|
168
229
|
db.exec("DROP TABLE http_responses");
|
|
169
230
|
if (indexes.has("steps_upstream"))
|
|
170
231
|
db.exec("DROP INDEX steps_upstream");
|
|
232
|
+
if (indexes.has("steps_router"))
|
|
233
|
+
db.exec("DROP INDEX steps_router");
|
|
171
234
|
const columns = new Set(db.query("PRAGMA table_info(steps)").all().map((column) => column.name));
|
|
172
235
|
for (const name of REMOVED_COLUMNS) {
|
|
173
236
|
if (columns.has(name))
|
|
@@ -177,30 +240,16 @@ function dropUnused(db) {
|
|
|
177
240
|
const kinds = REMOVED_EVENT_KINDS.map((kind) => `'${kind}'`).join(", ");
|
|
178
241
|
db.exec(`DELETE FROM events WHERE kind IN (${kinds})`);
|
|
179
242
|
}
|
|
180
|
-
db.exec("UPDATE steps SET router = NULL WHERE router IN ('opencode', 'openrouter', 'vercel-ai-gateway')");
|
|
181
|
-
}
|
|
182
|
-
function schemaVersion(db) {
|
|
183
|
-
const row = db.query("SELECT value FROM meta WHERE key = 'schema_version'").get();
|
|
184
|
-
const parsed = row === null ? Number.NaN : Number.parseInt(row.value, 10);
|
|
185
|
-
return Number.isFinite(parsed) ? parsed : 0;
|
|
186
243
|
}
|
|
187
|
-
function
|
|
188
|
-
db.
|
|
244
|
+
function addMissing(db) {
|
|
245
|
+
const columns = new Set(db.query("PRAGMA table_info(steps)").all().map((column) => column.name));
|
|
246
|
+
if (columns.size > 0 && !columns.has("list_cost")) {
|
|
247
|
+
db.exec("ALTER TABLE steps ADD COLUMN list_cost REAL");
|
|
248
|
+
}
|
|
189
249
|
}
|
|
190
250
|
function migrate(db) {
|
|
191
|
-
const version = schemaVersion(db);
|
|
192
|
-
const steps = db.query("PRAGMA table_info(steps)").all();
|
|
193
|
-
const existing = new Set(steps.map((column) => column.name));
|
|
194
|
-
for (const [name, statement, backfill] of MIGRATIONS) {
|
|
195
|
-
if (existing.has(name))
|
|
196
|
-
continue;
|
|
197
|
-
db.exec(statement);
|
|
198
|
-
if (backfill !== undefined)
|
|
199
|
-
db.exec(backfill);
|
|
200
|
-
}
|
|
201
251
|
dropUnused(db);
|
|
202
|
-
|
|
203
|
-
normalizeRouters(db);
|
|
252
|
+
addMissing(db);
|
|
204
253
|
}
|
|
205
254
|
var POSIX = process.platform !== "win32";
|
|
206
255
|
function hardenDirectory(path) {
|
|
@@ -263,12 +312,12 @@ function openStatsDbWrite(path) {
|
|
|
263
312
|
function recordStep(db, record) {
|
|
264
313
|
db.query(`INSERT INTO steps (
|
|
265
314
|
message_id, session_id, parent_id, provider_id, model_id, variant,
|
|
266
|
-
input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost,
|
|
267
|
-
created_at, streamed_at, completed_at, finish,
|
|
315
|
+
input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost, list_cost,
|
|
316
|
+
created_at, streamed_at, completed_at, finish, recorded_at
|
|
268
317
|
) VALUES (
|
|
269
318
|
$messageID, $sessionID, $parentID, $providerID, $modelID, $variant,
|
|
270
|
-
$input, $output, $reasoning, $cacheRead, $cacheWrite, $cost,
|
|
271
|
-
$createdAt, $streamedAt, $completedAt, $finish, $
|
|
319
|
+
$input, $output, $reasoning, $cacheRead, $cacheWrite, $cost, $listCost,
|
|
320
|
+
$createdAt, $streamedAt, $completedAt, $finish, $recordedAt
|
|
272
321
|
)
|
|
273
322
|
ON CONFLICT(message_id) DO UPDATE SET
|
|
274
323
|
session_id = excluded.session_id,
|
|
@@ -282,16 +331,18 @@ function recordStep(db, record) {
|
|
|
282
331
|
cache_read = excluded.cache_read,
|
|
283
332
|
cache_write = excluded.cache_write,
|
|
284
333
|
cost = excluded.cost,
|
|
334
|
+
-- A step that starts being charged loses its estimate; an estimate is
|
|
335
|
+
-- kept when a replayed event arrives without a price table.
|
|
336
|
+
list_cost = CASE WHEN excluded.cost > 0 THEN NULL ELSE COALESCE(excluded.list_cost, steps.list_cost) END,
|
|
285
337
|
created_at = COALESCE(excluded.created_at, steps.created_at),
|
|
286
338
|
streamed_at = COALESCE(excluded.streamed_at, steps.streamed_at),
|
|
287
339
|
completed_at = COALESCE(excluded.completed_at, steps.completed_at),
|
|
288
340
|
finish = COALESCE(excluded.finish, steps.finish),
|
|
289
|
-
router = COALESCE(excluded.router, steps.router),
|
|
290
341
|
recorded_at = excluded.recorded_at`).run({
|
|
291
342
|
$messageID: record.messageID,
|
|
292
343
|
$sessionID: record.sessionID,
|
|
293
344
|
$parentID: record.parentID ?? null,
|
|
294
|
-
$providerID: record.providerID
|
|
345
|
+
$providerID: record.providerID !== undefined && isToken(record.providerID) ? record.providerID : null,
|
|
295
346
|
$modelID: record.modelID ?? null,
|
|
296
347
|
$variant: record.variant ?? null,
|
|
297
348
|
$input: record.input ?? 0,
|
|
@@ -300,11 +351,11 @@ function recordStep(db, record) {
|
|
|
300
351
|
$cacheRead: record.cacheRead ?? 0,
|
|
301
352
|
$cacheWrite: record.cacheWrite ?? 0,
|
|
302
353
|
$cost: record.cost ?? 0,
|
|
354
|
+
$listCost: (record.cost ?? 0) <= 0 && record.listCost !== undefined && Number.isFinite(record.listCost) && record.listCost >= 0 ? record.listCost : null,
|
|
303
355
|
$createdAt: record.createdAt ?? null,
|
|
304
356
|
$streamedAt: record.streamedAt ?? null,
|
|
305
357
|
$completedAt: record.completedAt ?? null,
|
|
306
358
|
$finish: record.finish === undefined ? null : sanitizeLabel(record.finish, 64),
|
|
307
|
-
$router: record.router === undefined ? null : normalizeToken(record.router) ?? null,
|
|
308
359
|
$recordedAt: record.recordedAt ?? Date.now()
|
|
309
360
|
});
|
|
310
361
|
}
|
|
@@ -344,15 +395,6 @@ function upsertSession(db, record) {
|
|
|
344
395
|
$updatedAt: record.updatedAt ?? null
|
|
345
396
|
});
|
|
346
397
|
}
|
|
347
|
-
function setStepRouterForSessionModel(db, sessionID, modelID, info) {
|
|
348
|
-
const router = info.router === undefined ? undefined : normalizeToken(info.router);
|
|
349
|
-
if (router === undefined)
|
|
350
|
-
return 0;
|
|
351
|
-
const result = db.query(`UPDATE steps
|
|
352
|
-
SET router = $router
|
|
353
|
-
WHERE session_id = $sessionID AND router IS NULL AND ($modelID IS NULL OR model_id = $modelID)`).run({ $router: router, $sessionID: sessionID, $modelID: modelID ?? null });
|
|
354
|
-
return result.changes;
|
|
355
|
-
}
|
|
356
398
|
|
|
357
399
|
// src/core.ts
|
|
358
400
|
var PROMPT_BOUNDARIES = new Set(["user", "synthetic", "system"]);
|
|
@@ -389,7 +431,7 @@ function tokenCounts(message) {
|
|
|
389
431
|
};
|
|
390
432
|
}
|
|
391
433
|
function totalize(steps) {
|
|
392
|
-
const totals = { input: 0, cached: 0, output: 0, reasoning: 0, cacheWrite: 0, cost: 0, steps: steps.length };
|
|
434
|
+
const totals = { input: 0, cached: 0, output: 0, reasoning: 0, cacheWrite: 0, cost: 0, listCost: 0, steps: steps.length };
|
|
393
435
|
for (const step of steps) {
|
|
394
436
|
const counts = tokenCounts(step);
|
|
395
437
|
totals.input += counts.input;
|
|
@@ -398,10 +440,11 @@ function totalize(steps) {
|
|
|
398
440
|
totals.reasoning += counts.reasoning;
|
|
399
441
|
totals.cacheWrite += counts.write;
|
|
400
442
|
totals.cost += step.cost ?? 0;
|
|
443
|
+
totals.listCost += step.listCost ?? 0;
|
|
401
444
|
}
|
|
402
445
|
return totals;
|
|
403
446
|
}
|
|
404
|
-
function
|
|
447
|
+
function identityKey(model) {
|
|
405
448
|
if (!model)
|
|
406
449
|
return;
|
|
407
450
|
return `${model.providerID}/${model.id}${model.variant ? `#${model.variant}` : ""}`;
|
|
@@ -418,14 +461,16 @@ function stepEnd(message) {
|
|
|
418
461
|
return;
|
|
419
462
|
return time.completed ?? time.streamed ?? time.created;
|
|
420
463
|
}
|
|
421
|
-
function cacheDrop(reference, current) {
|
|
464
|
+
function cacheDrop(reference, current, scope = "provider") {
|
|
422
465
|
if (!reference)
|
|
423
466
|
return;
|
|
424
467
|
const before = reference.model;
|
|
425
468
|
const after = current.model;
|
|
426
469
|
if (!before || !after)
|
|
427
470
|
return;
|
|
428
|
-
if (
|
|
471
|
+
if (scope === "provider" && before.providerID !== after.providerID)
|
|
472
|
+
return;
|
|
473
|
+
if (before.id !== after.id || (before.variant ?? "") !== (after.variant ?? "")) {
|
|
429
474
|
return;
|
|
430
475
|
}
|
|
431
476
|
const drop = cacheRead(reference) - cacheRead(current);
|
|
@@ -482,8 +527,8 @@ function computeTurn(messages, session) {
|
|
|
482
527
|
}
|
|
483
528
|
const provider = lastStep.model?.providerID;
|
|
484
529
|
const previousProvider = previousStep?.model?.providerID;
|
|
485
|
-
const key =
|
|
486
|
-
const previousKey =
|
|
530
|
+
const key = identityKey(lastStep.model);
|
|
531
|
+
const previousKey = identityKey(previousStep?.model);
|
|
487
532
|
return {
|
|
488
533
|
endAt: stepEnd(lastStep),
|
|
489
534
|
startAt: stepCreated(settled[0] ?? lastStep),
|
|
@@ -492,9 +537,6 @@ function computeTurn(messages, session) {
|
|
|
492
537
|
providerID: provider,
|
|
493
538
|
modelID: lastStep.model?.id,
|
|
494
539
|
variant: lastStep.model?.variant,
|
|
495
|
-
router: undefined,
|
|
496
|
-
identityChanged: false,
|
|
497
|
-
affinityKey: key,
|
|
498
540
|
providerChanged: previousProvider !== undefined && provider !== undefined && previousProvider !== provider,
|
|
499
541
|
modelChanged: previousKey !== undefined && key !== undefined && previousKey !== key && previousProvider === provider,
|
|
500
542
|
totals: totalize(settled),
|
|
@@ -503,8 +545,7 @@ function computeTurn(messages, session) {
|
|
|
503
545
|
drops,
|
|
504
546
|
cacheDropTokens: drops.reduce((sum, drop) => sum + drop.tokens, 0),
|
|
505
547
|
cacheExpired: drops.length > 0,
|
|
506
|
-
steps: settled.length
|
|
507
|
-
stepIDs: settled.map((step) => step.id)
|
|
548
|
+
steps: settled.length
|
|
508
549
|
};
|
|
509
550
|
}
|
|
510
551
|
function promptGap(current, previous) {
|
|
@@ -530,6 +571,7 @@ var DEFAULT_LABELS = {
|
|
|
530
571
|
output: "out",
|
|
531
572
|
reasoning: "reason",
|
|
532
573
|
cost: "cost",
|
|
574
|
+
estimate: "\u2248",
|
|
533
575
|
cacheExpired: "cache expired",
|
|
534
576
|
providerChanged: "changed",
|
|
535
577
|
modelChanged: "model changed"
|
|
@@ -542,7 +584,7 @@ var DEFAULT_FIELDS = {
|
|
|
542
584
|
turn: true,
|
|
543
585
|
session: true,
|
|
544
586
|
reasoning: false,
|
|
545
|
-
cost:
|
|
587
|
+
cost: true,
|
|
546
588
|
cacheExpiry: true
|
|
547
589
|
};
|
|
548
590
|
function formatClock(ms) {
|
|
@@ -588,6 +630,20 @@ function formatCost(value) {
|
|
|
588
630
|
return `$${value.toFixed(4)}`;
|
|
589
631
|
return `$${value.toFixed(2)}`;
|
|
590
632
|
}
|
|
633
|
+
function formatMoney(charged, estimated, marker = "\u2248") {
|
|
634
|
+
const paid = Number.isFinite(charged) && charged > 0 ? formatCost(charged) : undefined;
|
|
635
|
+
const estimate = Number.isFinite(estimated) && estimated > 0 ? `${marker.trim() === "" ? "" : `${marker.trim()} `}${formatCost(estimated)}` : undefined;
|
|
636
|
+
if (paid !== undefined && estimate !== undefined)
|
|
637
|
+
return `${paid} + ${estimate}`;
|
|
638
|
+
return paid ?? estimate;
|
|
639
|
+
}
|
|
640
|
+
function formatSpend(charged, estimated, marker = "\u2248") {
|
|
641
|
+
const paid = Number.isFinite(charged) ? Math.max(0, charged) : 0;
|
|
642
|
+
const estimate = Number.isFinite(estimated) ? Math.max(0, estimated) : 0;
|
|
643
|
+
if (estimate > 0)
|
|
644
|
+
return `${marker.trim()}${formatCost(paid + estimate)}`;
|
|
645
|
+
return formatCost(paid);
|
|
646
|
+
}
|
|
591
647
|
function displayTotals(totals) {
|
|
592
648
|
const prompt = totals.input + totals.cached + totals.cacheWrite;
|
|
593
649
|
return {
|
|
@@ -597,11 +653,12 @@ function displayTotals(totals) {
|
|
|
597
653
|
output: totals.output + totals.reasoning,
|
|
598
654
|
reasoning: totals.reasoning,
|
|
599
655
|
cost: totals.cost,
|
|
656
|
+
listCost: totals.listCost,
|
|
600
657
|
steps: totals.steps,
|
|
601
658
|
prompt
|
|
602
659
|
};
|
|
603
660
|
}
|
|
604
|
-
function totalsText(prefix, totals, labels, fields, stepCount = 0) {
|
|
661
|
+
function totalsText(prefix, totals, labels, fields, stepCount = 0, cost = totals.cost, listCost = totals.listCost, estimates = true) {
|
|
605
662
|
const display = displayTotals(totals);
|
|
606
663
|
const input = display.prompt === display.input ? `${labels.input} ${formatTokens(display.input)}` : `${labels.input} ${formatTokens(display.input)} (${formatTokens(display.prompt)})`;
|
|
607
664
|
const parts = [
|
|
@@ -611,8 +668,9 @@ function totalsText(prefix, totals, labels, fields, stepCount = 0) {
|
|
|
611
668
|
];
|
|
612
669
|
if (fields.reasoning)
|
|
613
670
|
parts.push(`${labels.reasoning} ${formatTokens(display.reasoning)}`);
|
|
614
|
-
|
|
615
|
-
|
|
671
|
+
const money = fields.cost ? formatMoney(cost, estimates ? listCost : 0, labels.estimate) : undefined;
|
|
672
|
+
if (money !== undefined)
|
|
673
|
+
parts.push(`${labels.cost} ${money}`);
|
|
616
674
|
const steps = stepCount > 1 ? `${stepCount} ${stepCount === 1 ? labels.step : labels.steps}` : "";
|
|
617
675
|
const head = [prefix, steps].filter((piece) => piece !== "").join(" ");
|
|
618
676
|
const numbers = parts.join(", ");
|
|
@@ -624,7 +682,7 @@ function formatLineSegments(stats, options) {
|
|
|
624
682
|
const labels = { ...DEFAULT_LABELS, ...options?.labels };
|
|
625
683
|
const fields = { ...DEFAULT_FIELDS, ...options?.fields };
|
|
626
684
|
const turnTotals = options?.turnTotals ?? "latest";
|
|
627
|
-
const
|
|
685
|
+
const estimates = options?.estimates !== false;
|
|
628
686
|
const segments = [];
|
|
629
687
|
if (fields.clock && stats.endAt !== undefined) {
|
|
630
688
|
segments.push({ text: formatClock(stats.endAt), tone: "muted" });
|
|
@@ -632,11 +690,7 @@ function formatLineSegments(stats, options) {
|
|
|
632
690
|
if (fields.delta && stats.promptGapMs !== undefined) {
|
|
633
691
|
segments.push({ text: `${labels.delta} ${formatDuration(stats.promptGapMs)}`, tone: "muted" });
|
|
634
692
|
}
|
|
635
|
-
if (
|
|
636
|
-
segments.push({ text: stats.router, tone: stats.identityChanged ? "warning" : "base" });
|
|
637
|
-
if (stats.identityChanged)
|
|
638
|
-
segments.push({ text: labels.providerChanged, tone: "warning" });
|
|
639
|
-
} else if (stats.providerID !== undefined) {
|
|
693
|
+
if (stats.providerID !== undefined) {
|
|
640
694
|
let text = stats.providerID;
|
|
641
695
|
if (fields.model && stats.modelID !== undefined)
|
|
642
696
|
text += `/${stats.modelID}`;
|
|
@@ -650,10 +704,16 @@ function formatLineSegments(stats, options) {
|
|
|
650
704
|
}
|
|
651
705
|
if (fields.turn && stats.totals.steps > 0) {
|
|
652
706
|
const totals = turnTotals === "sum" ? stats.totals : stats.latest;
|
|
653
|
-
segments.push({
|
|
707
|
+
segments.push({
|
|
708
|
+
text: totalsText(labels.turn, totals, labels, fields, turnTotals === "sum" ? stats.totals.steps : stats.steps, stats.totals.cost, stats.totals.listCost, estimates),
|
|
709
|
+
tone: "base"
|
|
710
|
+
});
|
|
654
711
|
}
|
|
655
712
|
if (fields.session && stats.session) {
|
|
656
|
-
segments.push({
|
|
713
|
+
segments.push({
|
|
714
|
+
text: totalsText(labels.session, stats.session, labels, fields, 0, stats.session.cost, stats.session.listCost, estimates),
|
|
715
|
+
tone: "muted"
|
|
716
|
+
});
|
|
657
717
|
}
|
|
658
718
|
if (fields.cacheExpiry && stats.cacheExpired) {
|
|
659
719
|
const count = stats.drops.length > 1 ? `\xD7${stats.drops.length}` : "";
|
|
@@ -668,6 +728,13 @@ function formatLine(stats, options) {
|
|
|
668
728
|
// src/stats/queries.ts
|
|
669
729
|
var COMPACTION_KIND = "compaction";
|
|
670
730
|
var DEFAULT_TTL_HINT_MS = 10 * 60 * 1000;
|
|
731
|
+
function spend(usage) {
|
|
732
|
+
return usage.cost + usage.listCost;
|
|
733
|
+
}
|
|
734
|
+
function sessionListCost(db, sessionID) {
|
|
735
|
+
const row = db.query("SELECT COALESCE(SUM(list_cost), 0) AS listCost FROM steps WHERE session_id = ?").get(sessionID);
|
|
736
|
+
return row?.listCost ?? 0;
|
|
737
|
+
}
|
|
671
738
|
var STEP_TIME = "COALESCE(created_at, recorded_at)";
|
|
672
739
|
var MODEL_KEY_SQL = "COALESCE(model_id, '(unknown)') || '#' || COALESCE(variant, '')";
|
|
673
740
|
function modelKey(modelID, variant) {
|
|
@@ -682,7 +749,8 @@ var USAGE_SELECT = `COUNT(*) AS steps,
|
|
|
682
749
|
COALESCE(SUM(cache_write), 0) AS cacheWrite,
|
|
683
750
|
COALESCE(SUM(output_tokens), 0) AS output,
|
|
684
751
|
COALESCE(SUM(reasoning_tokens), 0) AS reasoning,
|
|
685
|
-
COALESCE(SUM(cost), 0) AS cost
|
|
752
|
+
COALESCE(SUM(cost), 0) AS cost,
|
|
753
|
+
COALESCE(SUM(list_cost), 0) AS listCost`;
|
|
686
754
|
function usageFrom(row) {
|
|
687
755
|
return {
|
|
688
756
|
steps: row.steps ?? 0,
|
|
@@ -691,7 +759,8 @@ function usageFrom(row) {
|
|
|
691
759
|
cacheWrite: row.cacheWrite ?? 0,
|
|
692
760
|
output: row.output ?? 0,
|
|
693
761
|
reasoning: row.reasoning ?? 0,
|
|
694
|
-
cost: row.cost ?? 0
|
|
762
|
+
cost: row.cost ?? 0,
|
|
763
|
+
listCost: row.listCost ?? 0
|
|
695
764
|
};
|
|
696
765
|
}
|
|
697
766
|
function rangeWhere(range, column = STEP_TIME) {
|
|
@@ -719,9 +788,9 @@ function buildWhere(range, filters, column = STEP_TIME) {
|
|
|
719
788
|
clauses.push(`${MODEL_KEY_SQL} = ?`);
|
|
720
789
|
params.push(filters.modelKey);
|
|
721
790
|
}
|
|
722
|
-
if (filters?.
|
|
723
|
-
clauses.push("
|
|
724
|
-
params.push(filters.
|
|
791
|
+
if (filters?.provider !== undefined && filters.provider !== "") {
|
|
792
|
+
clauses.push("provider_id = ?");
|
|
793
|
+
params.push(filters.provider);
|
|
725
794
|
}
|
|
726
795
|
if (filters?.sessionID !== undefined && filters.sessionID !== "") {
|
|
727
796
|
clauses.push("session_id = ?");
|
|
@@ -744,7 +813,7 @@ function overview(db, range, filters) {
|
|
|
744
813
|
FROM steps ${steps.where}`).get(...steps.params);
|
|
745
814
|
const prompts = rangeWhere(range, "created_at");
|
|
746
815
|
const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${prompts.where}`).get(...prompts.params);
|
|
747
|
-
const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0 });
|
|
816
|
+
const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
|
|
748
817
|
return {
|
|
749
818
|
...usage,
|
|
750
819
|
sessions: row?.sessions ?? 0,
|
|
@@ -758,37 +827,35 @@ function overview(db, range, filters) {
|
|
|
758
827
|
function models(db, range, filters) {
|
|
759
828
|
const filter = buildWhere(range, filters);
|
|
760
829
|
const rows = db.query(`SELECT provider_id, model_id, variant,
|
|
761
|
-
GROUP_CONCAT(DISTINCT router) AS router_list,
|
|
762
830
|
${USAGE_SELECT},
|
|
763
831
|
MIN(${STEP_TIME}) AS first_at,
|
|
764
832
|
MAX(COALESCE(completed_at, recorded_at)) AS last_at
|
|
765
833
|
FROM steps ${filter.where}
|
|
766
834
|
GROUP BY provider_id, model_id, variant
|
|
767
835
|
ORDER BY steps DESC, cached DESC`).all(...filter.params);
|
|
768
|
-
const
|
|
836
|
+
const models = new Map;
|
|
769
837
|
for (const row of rows) {
|
|
770
838
|
const modelID = row.model_id ?? "(unknown)";
|
|
771
839
|
const variant = row.variant ?? undefined;
|
|
772
840
|
const key = `${modelID}#${variant ?? ""}`;
|
|
773
|
-
let model =
|
|
841
|
+
let model = models.get(key);
|
|
774
842
|
if (!model) {
|
|
775
843
|
model = { modelID, variant, providers: [], totals: emptyUsage() };
|
|
776
|
-
|
|
844
|
+
models.set(key, model);
|
|
777
845
|
}
|
|
778
846
|
const usage = usageFrom(row);
|
|
779
847
|
model.providers.push({
|
|
780
848
|
...usage,
|
|
781
849
|
providerID: row.provider_id ?? "(unknown)",
|
|
782
|
-
routers: row.router_list ? row.router_list.split(",").filter(Boolean) : [],
|
|
783
850
|
firstAt: row.first_at ?? undefined,
|
|
784
851
|
lastAt: row.last_at ?? undefined
|
|
785
852
|
});
|
|
786
853
|
addUsage(model.totals, usage);
|
|
787
854
|
}
|
|
788
|
-
return [...
|
|
855
|
+
return [...models.values()].sort((a, b) => billedTokens(b.totals) - billedTokens(a.totals));
|
|
789
856
|
}
|
|
790
857
|
function emptyUsage() {
|
|
791
|
-
return { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0 };
|
|
858
|
+
return { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 };
|
|
792
859
|
}
|
|
793
860
|
function addUsage(target, source) {
|
|
794
861
|
target.steps += source.steps;
|
|
@@ -798,6 +865,7 @@ function addUsage(target, source) {
|
|
|
798
865
|
target.output += source.output;
|
|
799
866
|
target.reasoning += source.reasoning;
|
|
800
867
|
target.cost += source.cost;
|
|
868
|
+
target.listCost += source.listCost;
|
|
801
869
|
}
|
|
802
870
|
function billedTokens(usage) {
|
|
803
871
|
return usage.input + usage.cached + usage.output;
|
|
@@ -842,6 +910,7 @@ function sessions(db, options) {
|
|
|
842
910
|
COALESCE(SUM(st.output_tokens), 0) AS output,
|
|
843
911
|
COALESCE(SUM(st.reasoning_tokens), 0) AS reasoning,
|
|
844
912
|
COALESCE(SUM(st.cost), 0) AS cost,
|
|
913
|
+
COALESCE(SUM(st.list_cost), 0) AS listCost,
|
|
845
914
|
MIN(COALESCE(st.created_at, st.recorded_at)) AS first_at,
|
|
846
915
|
MAX(COALESCE(st.completed_at, st.created_at, st.recorded_at)) AS last_at
|
|
847
916
|
FROM steps st
|
|
@@ -884,7 +953,8 @@ function stepUsage(row) {
|
|
|
884
953
|
cacheWrite: row.cache_write ?? 0,
|
|
885
954
|
output: row.output_tokens ?? 0,
|
|
886
955
|
reasoning: row.reasoning_tokens ?? 0,
|
|
887
|
-
cost: row.cost ?? 0
|
|
956
|
+
cost: row.cost ?? 0,
|
|
957
|
+
listCost: row.list_cost ?? 0
|
|
888
958
|
};
|
|
889
959
|
}
|
|
890
960
|
function stepMessage(row) {
|
|
@@ -917,8 +987,8 @@ function turns(db, options) {
|
|
|
917
987
|
params.push(floor);
|
|
918
988
|
}
|
|
919
989
|
const steps = db.query(`SELECT message_id, session_id, provider_id, model_id, variant,
|
|
920
|
-
input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost,
|
|
921
|
-
created_at, streamed_at, recorded_at, completed_at, finish
|
|
990
|
+
input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,
|
|
991
|
+
created_at, streamed_at, recorded_at, completed_at, finish
|
|
922
992
|
FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
|
|
923
993
|
ORDER BY session_id, ${STEP_TIME}`).all(...params);
|
|
924
994
|
const promptClause = options?.sessionID === undefined ? "" : `WHERE session_id = ?${floor === undefined ? "" : " AND created_at >= ?"}`;
|
|
@@ -957,18 +1027,9 @@ function turns(db, options) {
|
|
|
957
1027
|
}
|
|
958
1028
|
reference = message;
|
|
959
1029
|
}
|
|
960
|
-
const lastWith = (pick) => {
|
|
961
|
-
for (let index = bucket.length - 1;index >= 0; index -= 1) {
|
|
962
|
-
const value = pick(bucket[index]);
|
|
963
|
-
if (value !== null)
|
|
964
|
-
return value;
|
|
965
|
-
}
|
|
966
|
-
return;
|
|
967
|
-
};
|
|
968
1030
|
const providerID = last.provider_id ?? undefined;
|
|
969
1031
|
const modelID = last.model_id ?? undefined;
|
|
970
1032
|
const variant = last.variant ?? undefined;
|
|
971
|
-
const router = lastWith((row) => row.router);
|
|
972
1033
|
let produced = 0;
|
|
973
1034
|
let window = 0;
|
|
974
1035
|
for (const row of bucket) {
|
|
@@ -986,8 +1047,6 @@ function turns(db, options) {
|
|
|
986
1047
|
providerID,
|
|
987
1048
|
modelID,
|
|
988
1049
|
variant,
|
|
989
|
-
router,
|
|
990
|
-
routerChanged: previous?.router !== undefined && router !== undefined && previous.router !== router,
|
|
991
1050
|
providerChanged: previous?.providerID !== undefined && providerID !== undefined && previous.providerID !== providerID,
|
|
992
1051
|
modelChanged: previous !== undefined && previous.providerID === providerID && `${previous.modelID ?? ""}#${previous.variant ?? ""}` !== `${modelID ?? ""}#${variant ?? ""}`,
|
|
993
1052
|
steps: bucket.length,
|
|
@@ -1031,127 +1090,9 @@ function promptFloor(db, sessionID, count) {
|
|
|
1031
1090
|
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);
|
|
1032
1091
|
return rows.length === count ? rows[count - 1].created_at : undefined;
|
|
1033
1092
|
}
|
|
1034
|
-
function routerBefore(db, sessionID, at) {
|
|
1035
|
-
if (at === undefined)
|
|
1036
|
-
return;
|
|
1037
|
-
const row = db.query(`SELECT router FROM steps
|
|
1038
|
-
WHERE session_id = $sessionID AND router IS NOT NULL AND COALESCE(created_at, recorded_at) < $at
|
|
1039
|
-
ORDER BY COALESCE(created_at, recorded_at) DESC LIMIT 1`).get({ $sessionID: sessionID, $at: at });
|
|
1040
|
-
return row?.router ?? undefined;
|
|
1041
|
-
}
|
|
1042
|
-
function routerForSteps(db, sessionID, messageIDs) {
|
|
1043
|
-
if (messageIDs.length === 0)
|
|
1044
|
-
return;
|
|
1045
|
-
const placeholders = messageIDs.map(() => "?").join(", ");
|
|
1046
|
-
const row = db.query(`SELECT router FROM steps
|
|
1047
|
-
WHERE session_id = ? AND message_id IN (${placeholders}) AND router IS NOT NULL
|
|
1048
|
-
ORDER BY recorded_at DESC LIMIT 1`).get(sessionID, ...messageIDs);
|
|
1049
|
-
return row?.router ?? undefined;
|
|
1050
|
-
}
|
|
1051
1093
|
function filterOptions(db) {
|
|
1052
1094
|
const pick = (column) => db.query(`SELECT ${column} AS value, COUNT(*) AS steps FROM steps WHERE ${column} IS NOT NULL GROUP BY ${column} ORDER BY steps DESC`).all().map((row) => ({ value: row.value, steps: row.steps }));
|
|
1053
|
-
return { models: pick("model_id"),
|
|
1054
|
-
}
|
|
1055
|
-
|
|
1056
|
-
// src/endpoint.ts
|
|
1057
|
-
var ENDPOINT_HEADER = "x-opencode-endpoint-id";
|
|
1058
|
-
var ENDPOINT_MAX = 64;
|
|
1059
|
-
var KNOWN_ENDPOINT_HOSTS = [
|
|
1060
|
-
["api.fireworks.ai", "fireworks"],
|
|
1061
|
-
["api.deepseek.com", "deepseek"],
|
|
1062
|
-
["api.together.xyz", "together"],
|
|
1063
|
-
["api.groq.com", "groq"],
|
|
1064
|
-
["api.cerebras.ai", "cerebras"],
|
|
1065
|
-
["api.sambanova.ai", "sambanova"],
|
|
1066
|
-
["api.hyperbolic.xyz", "hyperbolic"],
|
|
1067
|
-
["api.deepinfra.com", "deepinfra"],
|
|
1068
|
-
["api.baseten.co", "baseten"],
|
|
1069
|
-
["api.novita.ai", "novita"],
|
|
1070
|
-
["api.parasail.io", "parasail"],
|
|
1071
|
-
["api.moonshot.ai", "moonshot"],
|
|
1072
|
-
["api.moonshot.cn", "moonshot"],
|
|
1073
|
-
["api.z.ai", "zhipu"],
|
|
1074
|
-
["open.bigmodel.cn", "zhipu"],
|
|
1075
|
-
["api.minimax.chat", "minimax"],
|
|
1076
|
-
["dashscope.aliyuncs.com", "alibaba"],
|
|
1077
|
-
["api.x.ai", "xai"],
|
|
1078
|
-
["api.anthropic.com", "anthropic"],
|
|
1079
|
-
["api.openai.com", "openai"],
|
|
1080
|
-
["openai.azure.com", "azure"],
|
|
1081
|
-
["bedrock-runtime.*.amazonaws.com", "bedrock"],
|
|
1082
|
-
["generativelanguage.googleapis.com", "google"],
|
|
1083
|
-
["aiplatform.googleapis.com", "vertex"],
|
|
1084
|
-
["api.nvidia.com", "nvidia"],
|
|
1085
|
-
["api.mistral.ai", "mistral"],
|
|
1086
|
-
["api.cloudflare.com", "cloudflare"]
|
|
1087
|
-
];
|
|
1088
|
-
function readHeader(headers, name) {
|
|
1089
|
-
const get = headers.get;
|
|
1090
|
-
if (typeof get === "function") {
|
|
1091
|
-
const value = get.call(headers, name);
|
|
1092
|
-
return value === null || value === "" ? undefined : value;
|
|
1093
|
-
}
|
|
1094
|
-
for (const key of Object.keys(headers)) {
|
|
1095
|
-
if (key.toLowerCase() !== name)
|
|
1096
|
-
continue;
|
|
1097
|
-
const value = headers[key];
|
|
1098
|
-
return value ? value : undefined;
|
|
1099
|
-
}
|
|
1100
|
-
return;
|
|
1101
|
-
}
|
|
1102
|
-
function inferFromHeaders(headers) {
|
|
1103
|
-
if (!headers)
|
|
1104
|
-
return;
|
|
1105
|
-
const value = readHeader(headers, ENDPOINT_HEADER);
|
|
1106
|
-
if (value === undefined)
|
|
1107
|
-
return;
|
|
1108
|
-
const router = normalizeToken(value, ENDPOINT_MAX);
|
|
1109
|
-
if (router === undefined)
|
|
1110
|
-
return;
|
|
1111
|
-
return { router, source: `header:${ENDPOINT_HEADER}` };
|
|
1112
|
-
}
|
|
1113
|
-
function hostMatches(host, pattern) {
|
|
1114
|
-
const hostLabels = host.split(".");
|
|
1115
|
-
const patternLabels = pattern.split(".");
|
|
1116
|
-
if (patternLabels.includes("*")) {
|
|
1117
|
-
if (hostLabels.length !== patternLabels.length)
|
|
1118
|
-
return false;
|
|
1119
|
-
return patternLabels.every((label, index) => label === "*" || label === hostLabels[index]);
|
|
1120
|
-
}
|
|
1121
|
-
if (host === pattern)
|
|
1122
|
-
return true;
|
|
1123
|
-
if (host.endsWith(`.${pattern}`))
|
|
1124
|
-
return true;
|
|
1125
|
-
return host.endsWith(`-${pattern}`);
|
|
1126
|
-
}
|
|
1127
|
-
function inferFromUrl(url) {
|
|
1128
|
-
if (url === undefined)
|
|
1129
|
-
return;
|
|
1130
|
-
let host;
|
|
1131
|
-
try {
|
|
1132
|
-
host = new URL(url).hostname.toLowerCase();
|
|
1133
|
-
} catch {
|
|
1134
|
-
return;
|
|
1135
|
-
}
|
|
1136
|
-
if (host === "")
|
|
1137
|
-
return;
|
|
1138
|
-
for (const [suffix, router] of KNOWN_ENDPOINT_HOSTS) {
|
|
1139
|
-
if (hostMatches(host, suffix))
|
|
1140
|
-
return { router, source: `endpoint:${host}` };
|
|
1141
|
-
}
|
|
1142
|
-
return;
|
|
1143
|
-
}
|
|
1144
|
-
function mergeEndpoint(...candidates) {
|
|
1145
|
-
const merged = {};
|
|
1146
|
-
for (const candidate of candidates) {
|
|
1147
|
-
if (candidate === undefined)
|
|
1148
|
-
continue;
|
|
1149
|
-
if (merged.router === undefined && candidate.router !== undefined)
|
|
1150
|
-
merged.router = candidate.router;
|
|
1151
|
-
if (merged.source === undefined && candidate.source !== undefined)
|
|
1152
|
-
merged.source = candidate.source;
|
|
1153
|
-
}
|
|
1154
|
-
return merged.router === undefined ? undefined : merged;
|
|
1095
|
+
return { models: pick("model_id"), providers: pick("provider_id") };
|
|
1155
1096
|
}
|
|
1156
1097
|
|
|
1157
1098
|
// src/recorder.ts
|
|
@@ -1160,7 +1101,6 @@ function createRecorder(db, options) {
|
|
|
1160
1101
|
const MAX_PENDING = 256;
|
|
1161
1102
|
const pending = new Map;
|
|
1162
1103
|
const lastModel = new Map;
|
|
1163
|
-
const known = new Map;
|
|
1164
1104
|
const now = options?.now ?? (() => Date.now());
|
|
1165
1105
|
const MAX_DEFERRED = 256;
|
|
1166
1106
|
const deferred = [];
|
|
@@ -1211,26 +1151,11 @@ function createRecorder(db, options) {
|
|
|
1211
1151
|
}
|
|
1212
1152
|
function forget(sessionID) {
|
|
1213
1153
|
lastModel.delete(sessionID);
|
|
1214
|
-
known.delete(sessionID);
|
|
1215
1154
|
for (const [messageID, step] of pending) {
|
|
1216
1155
|
if (step.sessionID === sessionID)
|
|
1217
1156
|
pending.delete(messageID);
|
|
1218
1157
|
}
|
|
1219
1158
|
}
|
|
1220
|
-
function strength(info) {
|
|
1221
|
-
if (info?.router === undefined)
|
|
1222
|
-
return 0;
|
|
1223
|
-
return info.source?.startsWith("header:") === true ? 2 : 1;
|
|
1224
|
-
}
|
|
1225
|
-
function noteRouter(sessionID, modelID, info) {
|
|
1226
|
-
const previous = known.get(sessionID);
|
|
1227
|
-
const merged = strength(previous?.info) > strength(info) ? previous.info : mergeEndpoint(info, previous?.info);
|
|
1228
|
-
const info2 = merged ?? info;
|
|
1229
|
-
const settled = previous !== undefined && previous.modelID === modelID && previous.info.router === info2.router;
|
|
1230
|
-
remember(known, sessionID, { modelID, info: info2 }, MAX_TRACKED_SESSIONS);
|
|
1231
|
-
if (!settled)
|
|
1232
|
-
write(() => setStepRouterForSessionModel(db, sessionID, modelID, info2));
|
|
1233
|
-
}
|
|
1234
1159
|
function recordPendingStep(messageID, data, finish, at) {
|
|
1235
1160
|
const sessionID = data.sessionID;
|
|
1236
1161
|
if (typeof sessionID !== "string")
|
|
@@ -1238,8 +1163,14 @@ function createRecorder(db, options) {
|
|
|
1238
1163
|
const info = pending.get(messageID);
|
|
1239
1164
|
pending.delete(messageID);
|
|
1240
1165
|
const model = info?.model ?? lastModel.get(sessionID);
|
|
1241
|
-
const
|
|
1242
|
-
const
|
|
1166
|
+
const charged = data.cost;
|
|
1167
|
+
const estimate = charged !== undefined && charged > 0 ? undefined : options?.price?.({ providerID: model?.providerID, modelID: model?.id }, {
|
|
1168
|
+
input: data.tokens?.input,
|
|
1169
|
+
output: data.tokens?.output,
|
|
1170
|
+
reasoning: data.tokens?.reasoning,
|
|
1171
|
+
cacheRead: data.tokens?.cache?.read,
|
|
1172
|
+
cacheWrite: data.tokens?.cache?.write
|
|
1173
|
+
});
|
|
1243
1174
|
write(() => recordStep(db, {
|
|
1244
1175
|
messageID,
|
|
1245
1176
|
sessionID,
|
|
@@ -1252,11 +1183,11 @@ function createRecorder(db, options) {
|
|
|
1252
1183
|
cacheRead: data.tokens?.cache?.read,
|
|
1253
1184
|
cacheWrite: data.tokens?.cache?.write,
|
|
1254
1185
|
cost: data.cost,
|
|
1186
|
+
listCost: estimate !== undefined && Number.isFinite(estimate) && estimate >= 0 ? estimate : undefined,
|
|
1255
1187
|
createdAt: info?.started,
|
|
1256
1188
|
streamedAt: info?.streamed,
|
|
1257
1189
|
completedAt: at,
|
|
1258
1190
|
finish,
|
|
1259
|
-
router: matched?.router,
|
|
1260
1191
|
recordedAt: now()
|
|
1261
1192
|
}));
|
|
1262
1193
|
}
|
|
@@ -1372,19 +1303,44 @@ function createRecorder(db, options) {
|
|
|
1372
1303
|
}
|
|
1373
1304
|
return found;
|
|
1374
1305
|
}
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1306
|
+
return { handleEvent, pendingFor };
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
// src/index.ts
|
|
1310
|
+
var PRICE_TTL_MS = 5 * 60 * 1000;
|
|
1311
|
+
var PRICE_RETRY_MS = 30 * 1000;
|
|
1312
|
+
function createPriceSource(ctx) {
|
|
1313
|
+
let table;
|
|
1314
|
+
let refreshing = false;
|
|
1315
|
+
let lastAttempt = 0;
|
|
1316
|
+
function refresh(force = false) {
|
|
1317
|
+
if (refreshing)
|
|
1378
1318
|
return;
|
|
1379
|
-
const
|
|
1380
|
-
|
|
1319
|
+
const now = Date.now();
|
|
1320
|
+
const wait = table === undefined ? PRICE_RETRY_MS : PRICE_TTL_MS;
|
|
1321
|
+
if (!force && now - lastAttempt < wait)
|
|
1381
1322
|
return;
|
|
1382
|
-
|
|
1323
|
+
lastAttempt = now;
|
|
1324
|
+
refreshing = true;
|
|
1325
|
+
(async () => {
|
|
1326
|
+
try {
|
|
1327
|
+
const payload = await ctx.model.list();
|
|
1328
|
+
const models = Array.isArray(payload) ? payload : payload?.data;
|
|
1329
|
+
if (Array.isArray(models) && models.length > 0)
|
|
1330
|
+
table = priceTable(models);
|
|
1331
|
+
} catch {} finally {
|
|
1332
|
+
refreshing = false;
|
|
1333
|
+
}
|
|
1334
|
+
})();
|
|
1383
1335
|
}
|
|
1384
|
-
return {
|
|
1336
|
+
return {
|
|
1337
|
+
price: (ref, tokens) => {
|
|
1338
|
+
refresh();
|
|
1339
|
+
return table === undefined ? undefined : costOf(table, ref, tokens);
|
|
1340
|
+
},
|
|
1341
|
+
refresh
|
|
1342
|
+
};
|
|
1385
1343
|
}
|
|
1386
|
-
|
|
1387
|
-
// src/index.ts
|
|
1388
1344
|
function tryOpen(path) {
|
|
1389
1345
|
try {
|
|
1390
1346
|
return openStatsDb(path);
|
|
@@ -1404,29 +1360,23 @@ var src_default = Plugin.define({
|
|
|
1404
1360
|
try {
|
|
1405
1361
|
db.exec("PRAGMA busy_timeout = 1000");
|
|
1406
1362
|
} catch {}
|
|
1407
|
-
const
|
|
1363
|
+
const pricing = options.pricing !== "off";
|
|
1364
|
+
const source = pricing ? createPriceSource(ctx) : undefined;
|
|
1365
|
+
source?.refresh(true);
|
|
1366
|
+
const recorder = createRecorder(db, source === undefined ? undefined : { price: source.price });
|
|
1408
1367
|
const abort = new AbortController;
|
|
1409
1368
|
const stream = (async () => {
|
|
1410
1369
|
try {
|
|
1411
1370
|
for await (const event of ctx.event.subscribe({ signal: abort.signal })) {
|
|
1412
1371
|
try {
|
|
1372
|
+
if (event.type === "model.updated")
|
|
1373
|
+
source?.refresh(true);
|
|
1413
1374
|
recorder.handleEvent(event);
|
|
1414
1375
|
} catch {}
|
|
1415
1376
|
}
|
|
1416
1377
|
} catch {}
|
|
1417
1378
|
})();
|
|
1418
|
-
let hook;
|
|
1419
|
-
try {
|
|
1420
|
-
hook = await ctx.session.hook("http.response", (event) => {
|
|
1421
|
-
try {
|
|
1422
|
-
recorder.handleHttpResponse(event);
|
|
1423
|
-
} catch {}
|
|
1424
|
-
});
|
|
1425
|
-
} catch {
|
|
1426
|
-
hook = undefined;
|
|
1427
|
-
}
|
|
1428
1379
|
return async () => {
|
|
1429
|
-
await hook?.dispose();
|
|
1430
1380
|
abort.abort();
|
|
1431
1381
|
await stream;
|
|
1432
1382
|
db.close();
|
|
@@ -1437,4 +1387,4 @@ export {
|
|
|
1437
1387
|
src_default as default
|
|
1438
1388
|
};
|
|
1439
1389
|
|
|
1440
|
-
//# debugId=
|
|
1390
|
+
//# debugId=453796543F95785064756E2164756E21
|