opencode-usage-insights 0.3.1 → 0.4.1
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 +67 -542
- package/dist/core.d.ts +15 -1
- package/dist/gui-experimental.cjs +3 -3
- package/dist/index.d.ts +0 -47
- package/dist/index.js +1734 -1209
- package/dist/index.js.map +23 -16
- package/dist/line.d.ts +1 -0
- package/dist/panel-data.d.ts +9 -2
- package/dist/recorder.d.ts +1 -0
- package/dist/rpc.d.ts +4 -4
- package/dist/rpc.js +5 -5
- package/dist/rpc.js.map +3 -3
- package/dist/settings-client.d.ts +29 -0
- package/dist/settings-rpc.d.ts +746 -0
- package/dist/settings.d.ts +114 -0
- package/dist/sidebar.d.ts +3 -3
- package/dist/stats/aggregates.d.ts +15 -3
- package/dist/stats/constants.d.ts +7 -0
- package/dist/stats/db.d.ts +8 -128
- package/dist/stats/legacy.d.ts +25 -0
- package/dist/stats/maintenance.d.ts +1 -1
- package/dist/stats/migrate.d.ts +7 -0
- package/dist/stats/ndjson.d.ts +16 -0
- package/dist/stats/open.d.ts +15 -0
- package/dist/stats/paths.d.ts +5 -4
- package/dist/stats/queries.d.ts +30 -35
- package/dist/stats/records.d.ts +94 -0
- package/dist/stats/schema.d.ts +26 -0
- package/dist/stats-client.d.ts +9 -0
- package/dist/stats-worker.js +597 -367
- package/dist/stats-worker.js.map +17 -12
- package/dist/text.d.ts +2 -0
- package/dist/tui-settings.d.ts +18 -0
- package/dist/tui.d.ts +1 -57
- package/dist/tui.js +974 -158
- package/dist/tui.js.map +17 -13
- package/docs/cli.md +24 -0
- package/docs/configuration.md +108 -0
- package/docs/costs.md +44 -0
- package/docs/demo.md +94 -68
- package/docs/desktop.md +91 -0
- package/docs/images/desktop-overview-annotated.png +0 -0
- package/docs/images/desktop-overview.png +0 -0
- package/docs/images/desktop-settings.png +0 -0
- package/docs/images/desktop-turns-go-annotated.png +0 -0
- package/docs/images/desktop-turns.png +0 -0
- package/docs/images/line.png +0 -0
- package/docs/images/panel-cache.png +0 -0
- package/docs/images/panel-help.png +0 -0
- package/docs/images/panel-latency.png +0 -0
- package/docs/images/panel-overview.png +0 -0
- package/docs/images/panel-providers.png +0 -0
- package/docs/images/sidebar.png +0 -0
- package/docs/internals.md +87 -36
- package/docs/privacy.md +60 -0
- package/docs/tui.md +175 -0
- package/package.json +8 -7
package/dist/index.js
CHANGED
|
@@ -102,10 +102,10 @@ var PruneResultSchema = {
|
|
|
102
102
|
properties: {
|
|
103
103
|
steps: { type: "number" },
|
|
104
104
|
prompts: { type: "number" },
|
|
105
|
-
|
|
105
|
+
compactions: { type: "number" },
|
|
106
106
|
usage: { type: "number" }
|
|
107
107
|
},
|
|
108
|
-
required: ["steps", "prompts", "
|
|
108
|
+
required: ["steps", "prompts", "compactions", "usage"],
|
|
109
109
|
additionalProperties: false
|
|
110
110
|
};
|
|
111
111
|
var WipeResultSchema = {
|
|
@@ -113,11 +113,11 @@ var WipeResultSchema = {
|
|
|
113
113
|
properties: {
|
|
114
114
|
steps: { type: "number" },
|
|
115
115
|
prompts: { type: "number" },
|
|
116
|
-
|
|
116
|
+
compactions: { type: "number" },
|
|
117
117
|
usage: { type: "number" },
|
|
118
118
|
sessions: { type: "number" }
|
|
119
119
|
},
|
|
120
|
-
required: ["steps", "prompts", "
|
|
120
|
+
required: ["steps", "prompts", "compactions", "usage", "sessions"],
|
|
121
121
|
additionalProperties: false
|
|
122
122
|
};
|
|
123
123
|
var BackfillResultSchema = {
|
|
@@ -292,137 +292,366 @@ var UsageInsights = Rpc.define({
|
|
|
292
292
|
}
|
|
293
293
|
});
|
|
294
294
|
|
|
295
|
-
// src/
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
if (model === null || model === undefined)
|
|
308
|
-
continue;
|
|
309
|
-
const providerID = model.providerID;
|
|
310
|
-
const modelID = model.modelID ?? model.id;
|
|
311
|
-
if (typeof providerID !== "string" || providerID === "")
|
|
295
|
+
// src/settings-rpc.ts
|
|
296
|
+
import { Rpc as Rpc2 } from "@opencode/plugin/rpc";
|
|
297
|
+
|
|
298
|
+
// src/core.ts
|
|
299
|
+
var PROMPT_BOUNDARIES = new Set(["user", "synthetic", "system"]);
|
|
300
|
+
function transcriptTail(messages, count) {
|
|
301
|
+
const segments = [];
|
|
302
|
+
let current = [];
|
|
303
|
+
for (let index = messages.length - 1;index >= 0; index -= 1) {
|
|
304
|
+
const message = messages[index];
|
|
305
|
+
if (message.type === "assistant") {
|
|
306
|
+
current.unshift(message);
|
|
312
307
|
continue;
|
|
313
|
-
|
|
308
|
+
}
|
|
309
|
+
if (!PROMPT_BOUNDARIES.has(message.type))
|
|
314
310
|
continue;
|
|
315
|
-
if (
|
|
311
|
+
if (current.length === 0)
|
|
316
312
|
continue;
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
let tier;
|
|
322
|
-
if (cost.tier !== undefined) {
|
|
323
|
-
const size = cost.tier.size;
|
|
324
|
-
if (typeof size !== "number" || !Number.isFinite(size))
|
|
325
|
-
continue;
|
|
326
|
-
tier = { ...cost.tier.type !== undefined ? { type: cost.tier.type } : {}, size };
|
|
327
|
-
}
|
|
328
|
-
tiers.push({
|
|
329
|
-
...tier !== undefined ? { tier } : {},
|
|
330
|
-
input: money(cost.input),
|
|
331
|
-
output: money(cost.output),
|
|
332
|
-
cacheRead: money(cost.cache?.read),
|
|
333
|
-
cacheWrite: money(cost.cache?.write)
|
|
334
|
-
});
|
|
335
|
-
}
|
|
336
|
-
if (tiers.length > 0)
|
|
337
|
-
table.set(`${providerID}/${modelID}`, { tiers });
|
|
313
|
+
segments.unshift({ assistants: current, prompt: message });
|
|
314
|
+
if (segments.length >= count)
|
|
315
|
+
return segments;
|
|
316
|
+
current = [];
|
|
338
317
|
}
|
|
339
|
-
|
|
318
|
+
if (current.length > 0 && segments.length < count)
|
|
319
|
+
segments.unshift({ assistants: current, prompt: undefined });
|
|
320
|
+
return segments;
|
|
340
321
|
}
|
|
341
|
-
function
|
|
342
|
-
|
|
322
|
+
function countOf(value) {
|
|
323
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
|
|
324
|
+
}
|
|
325
|
+
function amountOf(value) {
|
|
326
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
|
|
327
|
+
}
|
|
328
|
+
function stampOf(value) {
|
|
329
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
330
|
+
}
|
|
331
|
+
function tokenCounts(message) {
|
|
332
|
+
const tokens = message.tokens;
|
|
333
|
+
return {
|
|
334
|
+
input: countOf(tokens?.input),
|
|
335
|
+
output: countOf(tokens?.output),
|
|
336
|
+
reasoning: countOf(tokens?.reasoning),
|
|
337
|
+
read: countOf(tokens?.cache?.read),
|
|
338
|
+
write: countOf(tokens?.cache?.write)
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
function totalize(steps) {
|
|
342
|
+
const totals = { input: 0, cached: 0, output: 0, reasoning: 0, cacheWrite: 0, cost: 0, listCost: 0, steps: steps.length };
|
|
343
|
+
for (const step of steps) {
|
|
344
|
+
const counts = tokenCounts(step);
|
|
345
|
+
totals.input += counts.input;
|
|
346
|
+
totals.cached += counts.read;
|
|
347
|
+
totals.output += counts.output;
|
|
348
|
+
totals.reasoning += counts.reasoning;
|
|
349
|
+
totals.cacheWrite += counts.write;
|
|
350
|
+
totals.cost += amountOf(step.cost);
|
|
351
|
+
totals.listCost += amountOf(step.listCost);
|
|
352
|
+
}
|
|
353
|
+
return totals;
|
|
354
|
+
}
|
|
355
|
+
function identityKey(model) {
|
|
356
|
+
if (!model)
|
|
343
357
|
return;
|
|
344
|
-
|
|
358
|
+
return `${model.providerID}/${model.id}${model.variant ? `#${model.variant}` : ""}`;
|
|
359
|
+
}
|
|
360
|
+
function cacheRead(message) {
|
|
361
|
+
return countOf(message?.tokens?.cache?.read);
|
|
362
|
+
}
|
|
363
|
+
function stepCreated(message) {
|
|
364
|
+
return stampOf(message?.time?.created);
|
|
365
|
+
}
|
|
366
|
+
function stepEnd(message) {
|
|
367
|
+
const time = message?.time;
|
|
368
|
+
if (!time)
|
|
345
369
|
return;
|
|
346
|
-
return
|
|
370
|
+
return stampOf(time.completed) ?? stampOf(time.streamed) ?? stampOf(time.created);
|
|
347
371
|
}
|
|
348
|
-
function
|
|
349
|
-
|
|
350
|
-
if (price === undefined)
|
|
372
|
+
function cacheDrop(reference, current, scope = "provider") {
|
|
373
|
+
if (!reference)
|
|
351
374
|
return;
|
|
352
|
-
const
|
|
353
|
-
const
|
|
354
|
-
|
|
355
|
-
const cacheRead = tokens(usage.cacheRead);
|
|
356
|
-
const cacheWrite = tokens(usage.cacheWrite);
|
|
357
|
-
const prompt = input + cacheRead + cacheWrite;
|
|
358
|
-
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);
|
|
359
|
-
if (selected === undefined)
|
|
375
|
+
const before = reference.model;
|
|
376
|
+
const after = current.model;
|
|
377
|
+
if (!before || !after)
|
|
360
378
|
return;
|
|
361
|
-
if (
|
|
362
|
-
return
|
|
363
|
-
|
|
364
|
-
if (!Number.isFinite(billed) || billed <= 0)
|
|
379
|
+
if (scope === "provider" && before.providerID !== after.providerID)
|
|
380
|
+
return;
|
|
381
|
+
if (before.id !== after.id || (before.variant ?? "") !== (after.variant ?? "")) {
|
|
365
382
|
return;
|
|
366
|
-
return billed / 1e6;
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
// src/stats/db.ts
|
|
370
|
-
import { Database } from "bun:sqlite";
|
|
371
|
-
import { chmodSync, mkdirSync } from "fs";
|
|
372
|
-
import { dirname } from "path";
|
|
373
|
-
|
|
374
|
-
// src/stats/paths.ts
|
|
375
|
-
import { homedir } from "os";
|
|
376
|
-
import { join } from "path";
|
|
377
|
-
import { statSync } from "fs";
|
|
378
|
-
function defaultDbPath(env = process.env, platform = process.platform) {
|
|
379
|
-
const name = join("opencode", "opencode-usage-insights", "usage.db");
|
|
380
|
-
if (platform === "win32") {
|
|
381
|
-
return join(env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local"), name);
|
|
382
|
-
}
|
|
383
|
-
if (platform === "darwin") {
|
|
384
|
-
return join(homedir(), "Library", "Application Support", name);
|
|
385
383
|
}
|
|
386
|
-
|
|
384
|
+
const drop = cacheRead(reference) - cacheRead(current);
|
|
385
|
+
if (isNoiseDrop(after.providerID, drop))
|
|
386
|
+
return;
|
|
387
|
+
return drop > 0 ? drop : undefined;
|
|
387
388
|
}
|
|
388
|
-
function
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
if (
|
|
392
|
-
return
|
|
393
|
-
return
|
|
389
|
+
function stepGap(reference, current) {
|
|
390
|
+
const ended = stepEnd(reference);
|
|
391
|
+
const started = stepCreated(current);
|
|
392
|
+
if (ended === undefined || started === undefined)
|
|
393
|
+
return;
|
|
394
|
+
return Math.max(0, started - ended);
|
|
394
395
|
}
|
|
395
|
-
function
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
return defaultDbPath(env, platform);
|
|
396
|
+
function tokensPerSecond(produced, from, to) {
|
|
397
|
+
if (from === undefined || to === undefined || !Number.isFinite(from) || !Number.isFinite(to) || to <= from)
|
|
398
|
+
return;
|
|
399
|
+
if (!Number.isFinite(produced) || produced <= 0)
|
|
400
|
+
return;
|
|
401
|
+
return produced / (to - from) * 1000;
|
|
402
402
|
}
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
403
|
+
var DROP_EXEMPT_PROVIDERS = new Set(["openai"]);
|
|
404
|
+
function isSettledStep(message) {
|
|
405
|
+
if (message.time?.completed !== undefined)
|
|
406
|
+
return true;
|
|
407
|
+
return message.finish !== undefined && message.finish !== null;
|
|
408
|
+
}
|
|
409
|
+
function computeTurn(messages, session) {
|
|
410
|
+
const segments = transcriptTail(messages, 2);
|
|
411
|
+
const last = segments[segments.length - 1];
|
|
412
|
+
if (!last)
|
|
413
|
+
return;
|
|
414
|
+
const previous = segments[segments.length - 2];
|
|
415
|
+
const lastStep = last.assistants[last.assistants.length - 1];
|
|
416
|
+
if (!lastStep)
|
|
417
|
+
return;
|
|
418
|
+
if (!isSettledStep(lastStep))
|
|
408
419
|
return;
|
|
420
|
+
const previousStep = previous?.assistants[previous.assistants.length - 1];
|
|
421
|
+
const settled = last.assistants.filter(isSettledStep);
|
|
422
|
+
const drops = [];
|
|
423
|
+
let reference = previousStep !== undefined && isSettledStep(previousStep) ? previousStep : undefined;
|
|
424
|
+
for (const step of settled) {
|
|
425
|
+
const drop = cacheDrop(reference, step);
|
|
426
|
+
if (drop !== undefined) {
|
|
427
|
+
drops.push({
|
|
428
|
+
messageID: step.id,
|
|
429
|
+
tokens: drop,
|
|
430
|
+
prevCached: cacheRead(reference),
|
|
431
|
+
gapMs: stepGap(reference, step)
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
reference = step;
|
|
409
435
|
}
|
|
410
|
-
|
|
411
|
-
|
|
436
|
+
const provider = lastStep.model?.providerID;
|
|
437
|
+
const previousProvider = previousStep?.model?.providerID;
|
|
438
|
+
const key = identityKey(lastStep.model);
|
|
439
|
+
const previousKey = identityKey(previousStep?.model);
|
|
440
|
+
return {
|
|
441
|
+
endAt: stepEnd(lastStep),
|
|
442
|
+
startAt: stepCreated(settled[0] ?? lastStep),
|
|
443
|
+
promptAt: stampOf(last.prompt?.time?.created),
|
|
444
|
+
promptGapMs: promptGap(last.prompt, previous?.prompt),
|
|
445
|
+
providerID: provider,
|
|
446
|
+
modelID: lastStep.model?.id,
|
|
447
|
+
variant: lastStep.model?.variant,
|
|
448
|
+
providerChanged: previousProvider !== undefined && provider !== undefined && previousProvider !== provider,
|
|
449
|
+
modelChanged: previousKey !== undefined && key !== undefined && previousKey !== key && previousProvider === provider,
|
|
450
|
+
totals: totalize(settled),
|
|
451
|
+
latest: totalize([lastStep]),
|
|
452
|
+
session,
|
|
453
|
+
drops,
|
|
454
|
+
cacheDropTokens: drops.reduce((sum, drop) => sum + drop.tokens, 0),
|
|
455
|
+
cacheExpired: drops.length > 0,
|
|
456
|
+
steps: settled.length
|
|
457
|
+
};
|
|
412
458
|
}
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
459
|
+
function promptGap(current, previous) {
|
|
460
|
+
const now = stampOf(current?.time?.created);
|
|
461
|
+
const before = stampOf(previous?.time?.created);
|
|
462
|
+
if (now === undefined || before === undefined)
|
|
463
|
+
return;
|
|
464
|
+
return Math.max(0, now - before);
|
|
465
|
+
}
|
|
466
|
+
function isNoiseDrop(providerID, drop) {
|
|
467
|
+
if (providerID === undefined)
|
|
468
|
+
return false;
|
|
469
|
+
return DROP_EXEMPT_PROVIDERS.has(providerID) && drop >= 1024 && drop <= 2048;
|
|
470
|
+
}
|
|
471
|
+
var DEFAULT_LABELS = {
|
|
472
|
+
delta: "\u0394",
|
|
473
|
+
turn: "",
|
|
474
|
+
session: "sess",
|
|
475
|
+
step: "step",
|
|
476
|
+
steps: "steps",
|
|
477
|
+
input: "in",
|
|
478
|
+
cached: "cached",
|
|
479
|
+
output: "out",
|
|
480
|
+
reasoning: "reason",
|
|
481
|
+
cost: "cost",
|
|
482
|
+
estimate: "\u2248",
|
|
483
|
+
cacheExpired: "cache expired",
|
|
484
|
+
providerChanged: "changed",
|
|
485
|
+
modelChanged: "model changed"
|
|
486
|
+
};
|
|
487
|
+
var DEFAULT_FIELDS = {
|
|
488
|
+
clock: true,
|
|
489
|
+
delta: true,
|
|
490
|
+
model: true,
|
|
491
|
+
variant: true,
|
|
492
|
+
turn: true,
|
|
493
|
+
session: true,
|
|
494
|
+
reasoning: false,
|
|
495
|
+
cost: true,
|
|
496
|
+
cacheExpiry: true
|
|
497
|
+
};
|
|
498
|
+
function formatClock(ms) {
|
|
499
|
+
if (!Number.isFinite(ms))
|
|
500
|
+
return "--:--";
|
|
501
|
+
const date = new Date(ms);
|
|
502
|
+
const pad = (value) => String(value).padStart(2, "0");
|
|
503
|
+
return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
|
504
|
+
}
|
|
505
|
+
function formatDuration(ms) {
|
|
506
|
+
if (!Number.isFinite(ms))
|
|
507
|
+
return "\u2013";
|
|
508
|
+
const totalSeconds = Math.max(0, Math.floor(ms / 1000));
|
|
509
|
+
const seconds = totalSeconds % 60;
|
|
510
|
+
const minutes = Math.floor(totalSeconds / 60) % 60;
|
|
511
|
+
const hours = Math.floor(totalSeconds / 3600) % 24;
|
|
512
|
+
const days = Math.floor(totalSeconds / 86400);
|
|
513
|
+
if (days > 0)
|
|
514
|
+
return `${days}d${hours}h`;
|
|
515
|
+
if (hours > 0)
|
|
516
|
+
return `${hours}h${String(minutes).padStart(2, "0")}m`;
|
|
517
|
+
if (minutes > 0)
|
|
518
|
+
return `${minutes}m${String(seconds).padStart(2, "0")}s`;
|
|
519
|
+
return `${seconds}s`;
|
|
520
|
+
}
|
|
521
|
+
function formatTokens(value) {
|
|
522
|
+
const n = Number.isFinite(value) ? Math.max(0, Math.round(value)) : 0;
|
|
523
|
+
if (n < 1000)
|
|
524
|
+
return String(n);
|
|
525
|
+
if (n < 999500) {
|
|
526
|
+
const k = n / 1000;
|
|
527
|
+
return `${trimZeros(k.toFixed(k < 10 ? 2 : 1))}k`;
|
|
528
|
+
}
|
|
529
|
+
if (n < 999500000) {
|
|
530
|
+
const m = n / 1e6;
|
|
531
|
+
return `${trimZeros(m.toFixed(m < 10 ? 2 : 1))}M`;
|
|
532
|
+
}
|
|
533
|
+
return `${Math.round(n / 1e6)}M`;
|
|
534
|
+
}
|
|
535
|
+
function trimZeros(value) {
|
|
536
|
+
return value.includes(".") ? value.replace(/0+$/, "").replace(/\.$/, "") : value;
|
|
537
|
+
}
|
|
538
|
+
function formatCost(value) {
|
|
539
|
+
if (!Number.isFinite(value) || value <= 0)
|
|
540
|
+
return "$0";
|
|
541
|
+
if (value < 0.00005)
|
|
542
|
+
return "<$0.0001";
|
|
543
|
+
if (value < 1)
|
|
544
|
+
return `$${value.toFixed(4)}`;
|
|
545
|
+
return `$${value.toFixed(2)}`;
|
|
546
|
+
}
|
|
547
|
+
function formatMoney(charged, estimated, marker = "\u2248") {
|
|
548
|
+
const paid = Number.isFinite(charged) && charged > 0 ? formatCost(charged) : undefined;
|
|
549
|
+
const estimate = Number.isFinite(estimated) && estimated > 0 ? `${marker.trim() === "" ? "" : `${marker.trim()} `}${formatCost(estimated)}` : undefined;
|
|
550
|
+
if (paid !== undefined && estimate !== undefined)
|
|
551
|
+
return `${paid} + ${estimate}`;
|
|
552
|
+
return paid ?? estimate;
|
|
553
|
+
}
|
|
554
|
+
function formatSpend(charged, estimated, marker = "\u2248") {
|
|
555
|
+
const paid = Number.isFinite(charged) ? Math.max(0, charged) : 0;
|
|
556
|
+
const estimate = Number.isFinite(estimated) ? Math.max(0, estimated) : 0;
|
|
557
|
+
if (estimate > 0)
|
|
558
|
+
return `${marker.trim()}${formatCost(paid + estimate)}`;
|
|
559
|
+
return formatCost(paid);
|
|
560
|
+
}
|
|
561
|
+
function displayTotals(totals) {
|
|
562
|
+
const prompt = totals.input + totals.cached + totals.cacheWrite;
|
|
563
|
+
return {
|
|
564
|
+
input: prompt - totals.cached,
|
|
565
|
+
cached: totals.cached,
|
|
566
|
+
cacheWrite: totals.cacheWrite,
|
|
567
|
+
output: totals.output + totals.reasoning,
|
|
568
|
+
reasoning: totals.reasoning,
|
|
569
|
+
cost: totals.cost,
|
|
570
|
+
listCost: totals.listCost,
|
|
571
|
+
steps: totals.steps,
|
|
572
|
+
prompt
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
function totalsText(prefix, totals, labels, fields, stepCount = 0, cost = totals.cost, listCost = totals.listCost, estimates = true) {
|
|
576
|
+
const display = displayTotals(totals);
|
|
577
|
+
const input = display.prompt === display.input ? `${labels.input} ${formatTokens(display.input)}` : `${labels.input} ${formatTokens(display.input)} (${formatTokens(display.prompt)})`;
|
|
578
|
+
const parts = [
|
|
579
|
+
input,
|
|
580
|
+
`${labels.cached} ${formatTokens(display.cached)}`,
|
|
581
|
+
`${labels.output} ${formatTokens(display.output)}`
|
|
582
|
+
];
|
|
583
|
+
if (fields.reasoning)
|
|
584
|
+
parts.push(`${labels.reasoning} ${formatTokens(display.reasoning)}`);
|
|
585
|
+
const money = fields.cost ? formatMoney(cost, estimates ? listCost : 0, labels.estimate) : undefined;
|
|
586
|
+
if (money !== undefined)
|
|
587
|
+
parts.push(`${labels.cost} ${money}`);
|
|
588
|
+
const steps = stepCount > 1 ? `${stepCount} ${stepCount === 1 ? labels.step : labels.steps}` : "";
|
|
589
|
+
const head = [prefix, steps].filter((piece) => piece !== "").join(" ");
|
|
590
|
+
const numbers = parts.join(", ");
|
|
591
|
+
if (head === "")
|
|
592
|
+
return numbers;
|
|
593
|
+
return stepCount > 1 ? `${head} \xB7 ${numbers}` : `${head} ${numbers}`;
|
|
594
|
+
}
|
|
595
|
+
function formatLineSegments(stats, options) {
|
|
596
|
+
const labels = { ...DEFAULT_LABELS, ...options?.labels };
|
|
597
|
+
const fields = { ...DEFAULT_FIELDS, ...options?.fields };
|
|
598
|
+
const turnTotals = options?.turnTotals ?? "latest";
|
|
599
|
+
const estimates = options?.estimates !== false;
|
|
600
|
+
const segments = [];
|
|
601
|
+
if (fields.clock && stats.endAt !== undefined) {
|
|
602
|
+
segments.push({ text: formatClock(stats.endAt), tone: "muted" });
|
|
603
|
+
}
|
|
604
|
+
if (fields.delta && stats.promptGapMs !== undefined) {
|
|
605
|
+
segments.push({ text: `${labels.delta} ${formatDuration(stats.promptGapMs)}`, tone: "muted" });
|
|
606
|
+
}
|
|
607
|
+
if (stats.providerID !== undefined) {
|
|
608
|
+
let text = stats.providerID;
|
|
609
|
+
if (fields.model && stats.modelID !== undefined)
|
|
610
|
+
text += `/${stats.modelID}`;
|
|
611
|
+
if (fields.variant && stats.variant)
|
|
612
|
+
text += ` ${stats.variant}`;
|
|
613
|
+
segments.push({ text, tone: stats.providerChanged ? "warning" : "base" });
|
|
614
|
+
if (stats.providerChanged)
|
|
615
|
+
segments.push({ text: labels.providerChanged, tone: "warning" });
|
|
616
|
+
else if (stats.modelChanged)
|
|
617
|
+
segments.push({ text: labels.modelChanged, tone: "muted" });
|
|
618
|
+
}
|
|
619
|
+
if (fields.turn && stats.totals.steps > 0) {
|
|
620
|
+
const totals = turnTotals === "sum" ? stats.totals : stats.latest;
|
|
621
|
+
segments.push({
|
|
622
|
+
text: totalsText(labels.turn, totals, labels, fields, turnTotals === "sum" ? stats.totals.steps : stats.steps, stats.totals.cost, stats.totals.listCost, estimates),
|
|
623
|
+
tone: "base"
|
|
624
|
+
});
|
|
625
|
+
}
|
|
626
|
+
if (fields.session && stats.session) {
|
|
627
|
+
segments.push({
|
|
628
|
+
text: totalsText(labels.session, stats.session, labels, fields, 0, stats.session.cost, stats.session.listCost, estimates),
|
|
629
|
+
tone: "muted"
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
if (fields.cacheExpiry && stats.cacheExpired) {
|
|
633
|
+
const count = stats.drops.length > 1 ? `\xD7${stats.drops.length}` : "";
|
|
634
|
+
segments.push({ text: `\u26A0 ${labels.cacheExpired} (\u2212${formatTokens(stats.cacheDropTokens)}${count})`, tone: "warning" });
|
|
635
|
+
}
|
|
636
|
+
return segments;
|
|
637
|
+
}
|
|
638
|
+
function formatLine(stats, options) {
|
|
639
|
+
return formatLineSegments(stats, options).map((segment) => segment.text).join(" \xB7 ");
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
// src/text.ts
|
|
643
|
+
var TEXT_LIMIT = 512;
|
|
644
|
+
var LABEL_LIMIT = 4 * TEXT_LIMIT;
|
|
645
|
+
function sanitizeText(value, limit = TEXT_LIMIT) {
|
|
646
|
+
if (limit <= 0)
|
|
647
|
+
return "";
|
|
648
|
+
let cleaned = "";
|
|
649
|
+
for (const character of value) {
|
|
650
|
+
const code = character.codePointAt(0) ?? 0;
|
|
651
|
+
if (code <= 31 || code === 127 || code >= 128 && code <= 159)
|
|
652
|
+
continue;
|
|
653
|
+
cleaned += character;
|
|
654
|
+
if (cleaned.length >= limit)
|
|
426
655
|
break;
|
|
427
656
|
}
|
|
428
657
|
return cleaned;
|
|
@@ -435,47 +664,375 @@ function isToken(value, limit = 64) {
|
|
|
435
664
|
return value.length > 0 && value.length <= limit && TOKEN.test(value);
|
|
436
665
|
}
|
|
437
666
|
|
|
438
|
-
// src/
|
|
439
|
-
var
|
|
440
|
-
var
|
|
441
|
-
var
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
);
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
)
|
|
462
|
-
|
|
667
|
+
// src/settings.ts
|
|
668
|
+
var SETTINGS_STORAGE_KEY = "settings";
|
|
669
|
+
var MAX_LABEL_LENGTH = 80;
|
|
670
|
+
var MAX_QUOTA_NAME_LENGTH = 120;
|
|
671
|
+
var DEFAULT_SIDEBAR_TURNS = 8;
|
|
672
|
+
var TURN_TOTALS = ["latest", "sum"];
|
|
673
|
+
var FIELD_KEYS = Object.keys(DEFAULT_FIELDS);
|
|
674
|
+
var LABEL_KEYS = Object.keys(DEFAULT_LABELS);
|
|
675
|
+
var DEFAULT_SERVER_POLICY = {
|
|
676
|
+
maintenance: true,
|
|
677
|
+
exposePaths: false
|
|
678
|
+
};
|
|
679
|
+
var DEFAULT_USAGE_SETTINGS = {
|
|
680
|
+
pricing: true,
|
|
681
|
+
turnTotals: "latest",
|
|
682
|
+
fields: { ...DEFAULT_FIELDS },
|
|
683
|
+
labels: { ...DEFAULT_LABELS },
|
|
684
|
+
panel: true,
|
|
685
|
+
sidebar: true,
|
|
686
|
+
sidebarTurns: DEFAULT_SIDEBAR_TURNS,
|
|
687
|
+
quota: true,
|
|
688
|
+
quotaName: ""
|
|
689
|
+
};
|
|
690
|
+
function defaultUsageSettings() {
|
|
691
|
+
return {
|
|
692
|
+
...DEFAULT_USAGE_SETTINGS,
|
|
693
|
+
fields: { ...DEFAULT_USAGE_SETTINGS.fields },
|
|
694
|
+
labels: { ...DEFAULT_USAGE_SETTINGS.labels }
|
|
695
|
+
};
|
|
696
|
+
}
|
|
697
|
+
function defaultSettingsEnvelope(policy = DEFAULT_SERVER_POLICY) {
|
|
698
|
+
return { settings: defaultUsageSettings(), policy: { ...policy } };
|
|
699
|
+
}
|
|
700
|
+
function isRecord(value) {
|
|
701
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
702
|
+
}
|
|
703
|
+
function sanitizeSidebarTurns(value) {
|
|
704
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
705
|
+
return clampTurnsLimit(value);
|
|
706
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
707
|
+
const parsed = Number(value);
|
|
708
|
+
if (Number.isFinite(parsed))
|
|
709
|
+
return clampTurnsLimit(parsed);
|
|
710
|
+
}
|
|
711
|
+
return DEFAULT_SIDEBAR_TURNS;
|
|
712
|
+
}
|
|
713
|
+
function sanitizeLabels(value) {
|
|
714
|
+
const labels = { ...DEFAULT_LABELS };
|
|
715
|
+
if (!isRecord(value))
|
|
716
|
+
return labels;
|
|
717
|
+
for (const key of LABEL_KEYS) {
|
|
718
|
+
const entry = value[key];
|
|
719
|
+
if (typeof entry === "string")
|
|
720
|
+
labels[key] = sanitizeText(entry, MAX_LABEL_LENGTH);
|
|
721
|
+
}
|
|
722
|
+
return labels;
|
|
723
|
+
}
|
|
724
|
+
function sanitizeFields(value) {
|
|
725
|
+
const fields = { ...DEFAULT_FIELDS };
|
|
726
|
+
if (!isRecord(value))
|
|
727
|
+
return fields;
|
|
728
|
+
for (const key of FIELD_KEYS) {
|
|
729
|
+
const entry = value[key];
|
|
730
|
+
if (typeof entry === "boolean")
|
|
731
|
+
fields[key] = entry;
|
|
732
|
+
}
|
|
733
|
+
return fields;
|
|
734
|
+
}
|
|
735
|
+
function sanitizeUsageSettings(value) {
|
|
736
|
+
if (!isRecord(value))
|
|
737
|
+
return defaultUsageSettings();
|
|
738
|
+
return {
|
|
739
|
+
pricing: typeof value.pricing === "boolean" ? value.pricing : DEFAULT_USAGE_SETTINGS.pricing,
|
|
740
|
+
turnTotals: TURN_TOTALS.includes(value.turnTotals) ? value.turnTotals : DEFAULT_USAGE_SETTINGS.turnTotals,
|
|
741
|
+
fields: sanitizeFields(value.fields),
|
|
742
|
+
labels: sanitizeLabels(value.labels),
|
|
743
|
+
panel: typeof value.panel === "boolean" ? value.panel : DEFAULT_USAGE_SETTINGS.panel,
|
|
744
|
+
sidebar: typeof value.sidebar === "boolean" ? value.sidebar : DEFAULT_USAGE_SETTINGS.sidebar,
|
|
745
|
+
sidebarTurns: sanitizeSidebarTurns(value.sidebarTurns),
|
|
746
|
+
quota: typeof value.quota === "boolean" ? value.quota : DEFAULT_USAGE_SETTINGS.quota,
|
|
747
|
+
quotaName: typeof value.quotaName === "string" ? sanitizeText(value.quotaName.trim(), MAX_QUOTA_NAME_LENGTH) : DEFAULT_USAGE_SETTINGS.quotaName
|
|
748
|
+
};
|
|
749
|
+
}
|
|
750
|
+
function sanitizeServerPolicy(value) {
|
|
751
|
+
if (!isRecord(value))
|
|
752
|
+
return { ...DEFAULT_SERVER_POLICY };
|
|
753
|
+
return {
|
|
754
|
+
maintenance: typeof value.maintenance === "boolean" ? value.maintenance : DEFAULT_SERVER_POLICY.maintenance,
|
|
755
|
+
exposePaths: typeof value.exposePaths === "boolean" ? value.exposePaths : DEFAULT_SERVER_POLICY.exposePaths
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
function sanitizeSettingsEnvelope(value) {
|
|
759
|
+
return {
|
|
760
|
+
settings: sanitizeUsageSettings(isRecord(value) ? value.settings : undefined),
|
|
761
|
+
policy: sanitizeServerPolicy(isRecord(value) ? value.policy : undefined)
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
function mergeUsageSettings(current, patch) {
|
|
765
|
+
const next = {
|
|
766
|
+
...current,
|
|
767
|
+
...typeof patch.pricing === "boolean" ? { pricing: patch.pricing } : {},
|
|
768
|
+
...TURN_TOTALS.includes(patch.turnTotals) ? { turnTotals: patch.turnTotals } : {},
|
|
769
|
+
...isRecord(patch.fields) ? { fields: { ...current.fields, ...patch.fields } } : {},
|
|
770
|
+
...isRecord(patch.labels) ? { labels: { ...current.labels, ...patch.labels } } : {},
|
|
771
|
+
...typeof patch.panel === "boolean" ? { panel: patch.panel } : {},
|
|
772
|
+
...typeof patch.sidebar === "boolean" ? { sidebar: patch.sidebar } : {},
|
|
773
|
+
...patch.sidebarTurns !== undefined ? { sidebarTurns: patch.sidebarTurns } : {},
|
|
774
|
+
...typeof patch.quota === "boolean" ? { quota: patch.quota } : {},
|
|
775
|
+
...typeof patch.quotaName === "string" ? { quotaName: patch.quotaName } : {}
|
|
776
|
+
};
|
|
777
|
+
return sanitizeUsageSettings(next);
|
|
778
|
+
}
|
|
779
|
+
function resolveUsageSettings(settings) {
|
|
780
|
+
return {
|
|
781
|
+
format: {
|
|
782
|
+
labels: settings.labels,
|
|
783
|
+
fields: settings.fields,
|
|
784
|
+
turnTotals: settings.turnTotals,
|
|
785
|
+
estimates: settings.pricing
|
|
786
|
+
},
|
|
787
|
+
sidebarTurns: clampTurnsLimit(settings.sidebarTurns),
|
|
788
|
+
quotaName: settings.quotaName.trim() || undefined
|
|
789
|
+
};
|
|
790
|
+
}
|
|
791
|
+
function isValidSidebarTurns(raw) {
|
|
792
|
+
const value = Number(raw);
|
|
793
|
+
return raw.trim() !== "" && Number.isInteger(value) && value >= 1 && value <= 50;
|
|
794
|
+
}
|
|
795
|
+
function parseSidebarTurns(raw) {
|
|
796
|
+
if (!isValidSidebarTurns(raw))
|
|
797
|
+
return;
|
|
798
|
+
return clampTurnsLimit(Number(raw));
|
|
799
|
+
}
|
|
800
|
+
var TRUE_VALUES = new Set(["1", "true", "on", "yes", "y"]);
|
|
801
|
+
var FALSE_VALUES = new Set(["0", "false", "off", "no", "n"]);
|
|
802
|
+
function envFlag(value, fallback) {
|
|
803
|
+
if (value === undefined || value.trim() === "")
|
|
804
|
+
return fallback;
|
|
805
|
+
const normalized = value.trim().toLowerCase();
|
|
806
|
+
if (TRUE_VALUES.has(normalized))
|
|
807
|
+
return true;
|
|
808
|
+
if (FALSE_VALUES.has(normalized))
|
|
809
|
+
return false;
|
|
810
|
+
return fallback;
|
|
811
|
+
}
|
|
812
|
+
function serverPolicy(env = process.env) {
|
|
813
|
+
return {
|
|
814
|
+
maintenance: envFlag(env.OPENCODE_USAGE_INSIGHTS_MAINTENANCE, true),
|
|
815
|
+
exposePaths: envFlag(env.OPENCODE_USAGE_INSIGHTS_EXPOSE_PATHS, false)
|
|
816
|
+
};
|
|
817
|
+
}
|
|
463
818
|
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
819
|
+
// src/settings-rpc.ts
|
|
820
|
+
var LineFields = {
|
|
821
|
+
type: "object",
|
|
822
|
+
properties: {
|
|
823
|
+
clock: { type: "boolean" },
|
|
824
|
+
delta: { type: "boolean" },
|
|
825
|
+
model: { type: "boolean" },
|
|
826
|
+
variant: { type: "boolean" },
|
|
827
|
+
turn: { type: "boolean" },
|
|
828
|
+
session: { type: "boolean" },
|
|
829
|
+
reasoning: { type: "boolean" },
|
|
830
|
+
cost: { type: "boolean" },
|
|
831
|
+
cacheExpiry: { type: "boolean" }
|
|
832
|
+
},
|
|
833
|
+
additionalProperties: false
|
|
834
|
+
};
|
|
835
|
+
var LineLabels = {
|
|
836
|
+
type: "object",
|
|
837
|
+
properties: {
|
|
838
|
+
delta: { type: "string", maxLength: MAX_LABEL_LENGTH },
|
|
839
|
+
turn: { type: "string", maxLength: MAX_LABEL_LENGTH },
|
|
840
|
+
session: { type: "string", maxLength: MAX_LABEL_LENGTH },
|
|
841
|
+
step: { type: "string", maxLength: MAX_LABEL_LENGTH },
|
|
842
|
+
steps: { type: "string", maxLength: MAX_LABEL_LENGTH },
|
|
843
|
+
input: { type: "string", maxLength: MAX_LABEL_LENGTH },
|
|
844
|
+
cached: { type: "string", maxLength: MAX_LABEL_LENGTH },
|
|
845
|
+
output: { type: "string", maxLength: MAX_LABEL_LENGTH },
|
|
846
|
+
reasoning: { type: "string", maxLength: MAX_LABEL_LENGTH },
|
|
847
|
+
cost: { type: "string", maxLength: MAX_LABEL_LENGTH },
|
|
848
|
+
estimate: { type: "string", maxLength: MAX_LABEL_LENGTH },
|
|
849
|
+
cacheExpired: { type: "string", maxLength: MAX_LABEL_LENGTH },
|
|
850
|
+
providerChanged: { type: "string", maxLength: MAX_LABEL_LENGTH },
|
|
851
|
+
modelChanged: { type: "string", maxLength: MAX_LABEL_LENGTH }
|
|
852
|
+
},
|
|
853
|
+
additionalProperties: false
|
|
854
|
+
};
|
|
855
|
+
var Settings = {
|
|
856
|
+
type: "object",
|
|
857
|
+
properties: {
|
|
858
|
+
pricing: { type: "boolean" },
|
|
859
|
+
turnTotals: { type: "string", enum: ["latest", "sum"] },
|
|
860
|
+
fields: LineFields,
|
|
861
|
+
labels: LineLabels,
|
|
862
|
+
panel: { type: "boolean" },
|
|
863
|
+
sidebar: { type: "boolean" },
|
|
864
|
+
sidebarTurns: { type: "number", minimum: 1, maximum: 50 },
|
|
865
|
+
quota: { type: "boolean" },
|
|
866
|
+
quotaName: { type: "string", maxLength: MAX_QUOTA_NAME_LENGTH }
|
|
867
|
+
},
|
|
868
|
+
required: ["pricing", "turnTotals", "fields", "labels", "panel", "sidebar", "sidebarTurns", "quota", "quotaName"],
|
|
869
|
+
additionalProperties: false
|
|
870
|
+
};
|
|
871
|
+
var Patch = {
|
|
872
|
+
type: "object",
|
|
873
|
+
properties: {
|
|
874
|
+
pricing: { type: "boolean" },
|
|
875
|
+
turnTotals: { type: "string", enum: ["latest", "sum"] },
|
|
876
|
+
fields: LineFields,
|
|
877
|
+
labels: LineLabels,
|
|
878
|
+
panel: { type: "boolean" },
|
|
879
|
+
sidebar: { type: "boolean" },
|
|
880
|
+
sidebarTurns: { type: "number", minimum: 1, maximum: 50 },
|
|
881
|
+
quota: { type: "boolean" },
|
|
882
|
+
quotaName: { type: "string", maxLength: MAX_QUOTA_NAME_LENGTH }
|
|
883
|
+
},
|
|
884
|
+
additionalProperties: false
|
|
885
|
+
};
|
|
886
|
+
var Policy = {
|
|
887
|
+
type: "object",
|
|
888
|
+
properties: {
|
|
889
|
+
maintenance: { type: "boolean" },
|
|
890
|
+
exposePaths: { type: "boolean" }
|
|
891
|
+
},
|
|
892
|
+
required: ["maintenance", "exposePaths"],
|
|
893
|
+
additionalProperties: false
|
|
894
|
+
};
|
|
895
|
+
var Envelope = {
|
|
896
|
+
type: "object",
|
|
897
|
+
properties: {
|
|
898
|
+
settings: Settings,
|
|
899
|
+
policy: Policy
|
|
900
|
+
},
|
|
901
|
+
required: ["settings", "policy"],
|
|
902
|
+
additionalProperties: false
|
|
903
|
+
};
|
|
904
|
+
var Empty = { type: "object", properties: {}, additionalProperties: false };
|
|
905
|
+
var SetInput = {
|
|
906
|
+
type: "object",
|
|
907
|
+
properties: { patch: Patch },
|
|
908
|
+
required: ["patch"],
|
|
909
|
+
additionalProperties: false
|
|
910
|
+
};
|
|
911
|
+
var UsageInsightsSettings = Rpc2.define({
|
|
912
|
+
id: "usage-insights.settings",
|
|
913
|
+
methods: {
|
|
914
|
+
get: { input: Empty, output: Envelope },
|
|
915
|
+
set: { input: SetInput, output: Envelope },
|
|
916
|
+
reset: { input: Empty, output: Envelope }
|
|
917
|
+
},
|
|
918
|
+
events: {
|
|
919
|
+
updated: { schema: Envelope }
|
|
920
|
+
}
|
|
921
|
+
});
|
|
922
|
+
|
|
923
|
+
// src/pricing.ts
|
|
924
|
+
function money(value) {
|
|
925
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
|
|
926
|
+
}
|
|
927
|
+
function tokens(value) {
|
|
928
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
|
|
929
|
+
}
|
|
930
|
+
function priceTable(models) {
|
|
931
|
+
const table = new Map;
|
|
932
|
+
if (!Array.isArray(models))
|
|
933
|
+
return table;
|
|
934
|
+
for (const model of models) {
|
|
935
|
+
if (model === null || model === undefined)
|
|
936
|
+
continue;
|
|
937
|
+
const providerID = model.providerID;
|
|
938
|
+
const modelID = model.modelID ?? model.id;
|
|
939
|
+
if (typeof providerID !== "string" || providerID === "")
|
|
940
|
+
continue;
|
|
941
|
+
if (typeof modelID !== "string" || modelID === "")
|
|
942
|
+
continue;
|
|
943
|
+
if (!Array.isArray(model.cost) || model.cost.length === 0)
|
|
944
|
+
continue;
|
|
945
|
+
const tiers = [];
|
|
946
|
+
for (const cost of model.cost) {
|
|
947
|
+
if (cost === null || cost === undefined)
|
|
948
|
+
continue;
|
|
949
|
+
let tier;
|
|
950
|
+
if (cost.tier !== undefined) {
|
|
951
|
+
const size = cost.tier.size;
|
|
952
|
+
if (typeof size !== "number" || !Number.isFinite(size))
|
|
953
|
+
continue;
|
|
954
|
+
tier = { ...cost.tier.type !== undefined ? { type: cost.tier.type } : {}, size };
|
|
955
|
+
}
|
|
956
|
+
tiers.push({
|
|
957
|
+
...tier !== undefined ? { tier } : {},
|
|
958
|
+
input: money(cost.input),
|
|
959
|
+
output: money(cost.output),
|
|
960
|
+
cacheRead: money(cost.cache?.read),
|
|
961
|
+
cacheWrite: money(cost.cache?.write)
|
|
962
|
+
});
|
|
963
|
+
}
|
|
964
|
+
if (tiers.length > 0)
|
|
965
|
+
table.set(`${providerID}/${modelID}`, { tiers });
|
|
966
|
+
}
|
|
967
|
+
return table;
|
|
968
|
+
}
|
|
969
|
+
function priceOf(table, ref) {
|
|
970
|
+
if (ref.providerID === undefined || ref.providerID === "")
|
|
971
|
+
return;
|
|
972
|
+
if (ref.modelID === undefined || ref.modelID === "")
|
|
973
|
+
return;
|
|
974
|
+
return table.get(`${ref.providerID}/${ref.modelID}`);
|
|
975
|
+
}
|
|
976
|
+
function costOf(table, ref, usage) {
|
|
977
|
+
const price = priceOf(table, ref);
|
|
978
|
+
if (price === undefined)
|
|
979
|
+
return;
|
|
980
|
+
const input = tokens(usage.input);
|
|
981
|
+
const output = tokens(usage.output);
|
|
982
|
+
const reasoning = tokens(usage.reasoning);
|
|
983
|
+
const cacheRead = tokens(usage.cacheRead);
|
|
984
|
+
const cacheWrite = tokens(usage.cacheWrite);
|
|
985
|
+
const prompt = input + cacheRead + cacheWrite;
|
|
986
|
+
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);
|
|
987
|
+
if (selected === undefined)
|
|
988
|
+
return;
|
|
989
|
+
if (selected.input === 0 && selected.output === 0 && selected.cacheRead === 0 && selected.cacheWrite === 0)
|
|
990
|
+
return 0;
|
|
991
|
+
const billed = input * selected.input + (output + reasoning) * selected.output + cacheRead * selected.cacheRead + cacheWrite * selected.cacheWrite;
|
|
992
|
+
if (!Number.isFinite(billed) || billed <= 0)
|
|
993
|
+
return;
|
|
994
|
+
return billed / 1e6;
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
// src/stats/schema.ts
|
|
998
|
+
var SCHEMA_VERSION = 14;
|
|
999
|
+
var SCHEMA = `
|
|
1000
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
1001
|
+
key TEXT PRIMARY KEY,
|
|
1002
|
+
value TEXT NOT NULL
|
|
1003
|
+
);
|
|
1004
|
+
|
|
1005
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
1006
|
+
session_id TEXT PRIMARY KEY,
|
|
1007
|
+
parent_id TEXT,
|
|
1008
|
+
directory TEXT,
|
|
1009
|
+
title TEXT,
|
|
1010
|
+
started_at INTEGER
|
|
1011
|
+
);
|
|
1012
|
+
|
|
1013
|
+
CREATE TABLE IF NOT EXISTS prompts (
|
|
1014
|
+
session_id TEXT NOT NULL,
|
|
1015
|
+
message_id TEXT NOT NULL,
|
|
1016
|
+
created_at INTEGER,
|
|
1017
|
+
PRIMARY KEY (session_id, message_id)
|
|
1018
|
+
);
|
|
1019
|
+
CREATE INDEX IF NOT EXISTS prompts_created ON prompts(created_at);
|
|
1020
|
+
|
|
1021
|
+
CREATE TABLE IF NOT EXISTS steps (
|
|
1022
|
+
message_id TEXT PRIMARY KEY,
|
|
1023
|
+
session_id TEXT NOT NULL,
|
|
1024
|
+
provider_id TEXT,
|
|
1025
|
+
model_id TEXT,
|
|
1026
|
+
variant TEXT,
|
|
1027
|
+
input_tokens INTEGER NOT NULL DEFAULT 0,
|
|
1028
|
+
output_tokens INTEGER NOT NULL DEFAULT 0,
|
|
1029
|
+
reasoning_tokens INTEGER NOT NULL DEFAULT 0,
|
|
1030
|
+
cache_read INTEGER NOT NULL DEFAULT 0,
|
|
475
1031
|
cache_write INTEGER NOT NULL DEFAULT 0,
|
|
476
1032
|
cost REAL NOT NULL DEFAULT 0,
|
|
477
1033
|
list_cost REAL,
|
|
478
1034
|
created_at INTEGER,
|
|
1035
|
+
first_token_at INTEGER,
|
|
479
1036
|
streamed_at INTEGER,
|
|
480
1037
|
completed_at INTEGER,
|
|
481
1038
|
finish TEXT,
|
|
@@ -491,16 +1048,18 @@ CREATE INDEX IF NOT EXISTS steps_completed ON steps(completed_at);
|
|
|
491
1048
|
CREATE INDEX IF NOT EXISTS steps_at ON steps(COALESCE(created_at, recorded_at));
|
|
492
1049
|
CREATE INDEX IF NOT EXISTS steps_session_at ON steps(session_id, COALESCE(created_at, recorded_at));
|
|
493
1050
|
|
|
494
|
-
|
|
1051
|
+
-- The compaction timeline: when a compaction ended, by host event ID. The
|
|
1052
|
+
-- cost and tokens live in the usage table; the payload that used to be copied
|
|
1053
|
+
-- here was never read. Only compactions exist in this table by construction.
|
|
1054
|
+
CREATE TABLE IF NOT EXISTS compactions (
|
|
495
1055
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
496
1056
|
session_id TEXT NOT NULL,
|
|
497
|
-
kind TEXT NOT NULL,
|
|
498
1057
|
message_id TEXT,
|
|
499
|
-
at INTEGER
|
|
500
|
-
data TEXT
|
|
1058
|
+
at INTEGER
|
|
501
1059
|
);
|
|
502
|
-
CREATE INDEX IF NOT EXISTS
|
|
503
|
-
CREATE INDEX IF NOT EXISTS
|
|
1060
|
+
CREATE INDEX IF NOT EXISTS compactions_session ON compactions(session_id, at);
|
|
1061
|
+
CREATE INDEX IF NOT EXISTS compactions_at ON compactions(at);
|
|
1062
|
+
CREATE UNIQUE INDEX IF NOT EXISTS compactions_message ON compactions(message_id) WHERE message_id IS NOT NULL;
|
|
504
1063
|
|
|
505
1064
|
-- Usage the host reports with no assistant step of its own: the compaction
|
|
506
1065
|
-- summarisation and the session-title generation. The host publishes it as
|
|
@@ -522,199 +1081,168 @@ CREATE TABLE IF NOT EXISTS usage (
|
|
|
522
1081
|
CREATE INDEX IF NOT EXISTS usage_session_at ON usage(session_id, at);
|
|
523
1082
|
CREATE INDEX IF NOT EXISTS usage_at ON usage(at);
|
|
524
1083
|
`;
|
|
525
|
-
var TABLES = ["sessions", "prompts", "
|
|
526
|
-
function
|
|
527
|
-
if (value === undefined || value === null)
|
|
528
|
-
return null;
|
|
529
|
-
if (typeof value === "string")
|
|
530
|
-
return value;
|
|
1084
|
+
var TABLES = ["sessions", "prompts", "compactions", "steps", "usage"];
|
|
1085
|
+
function hasTable(db, name) {
|
|
531
1086
|
try {
|
|
532
|
-
return
|
|
1087
|
+
return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== null;
|
|
533
1088
|
} catch {
|
|
534
|
-
return
|
|
1089
|
+
return false;
|
|
535
1090
|
}
|
|
536
1091
|
}
|
|
537
|
-
function
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
return Math.max(0, Math.floor(finite(value)));
|
|
542
|
-
}
|
|
543
|
-
function timestamp(value) {
|
|
544
|
-
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
1092
|
+
function columnsOf(db, table) {
|
|
1093
|
+
if (!hasTable(db, table))
|
|
1094
|
+
return new Set;
|
|
1095
|
+
return new Set(db.query(`PRAGMA table_info(${table})`).all().map((column) => column.name));
|
|
545
1096
|
}
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
for (const name of REMOVED_COLUMNS) {
|
|
560
|
-
if (columns.has(name))
|
|
561
|
-
db.exec(`ALTER TABLE steps DROP COLUMN ${name}`);
|
|
1097
|
+
// src/stats/open.ts
|
|
1098
|
+
import { Database } from "bun:sqlite";
|
|
1099
|
+
import { chmodSync, mkdirSync } from "fs";
|
|
1100
|
+
import { dirname } from "path";
|
|
1101
|
+
|
|
1102
|
+
// src/stats/paths.ts
|
|
1103
|
+
import { homedir } from "os";
|
|
1104
|
+
import { join } from "path";
|
|
1105
|
+
import { statSync } from "fs";
|
|
1106
|
+
function defaultDbPath(env = process.env, platform = process.platform) {
|
|
1107
|
+
const name = join("opencode", "opencode-usage-insights", "usage.db");
|
|
1108
|
+
if (platform === "win32") {
|
|
1109
|
+
return join(env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local"), name);
|
|
562
1110
|
}
|
|
563
|
-
if (
|
|
564
|
-
|
|
565
|
-
db.exec(`DELETE FROM events WHERE kind IN (${kinds})`);
|
|
1111
|
+
if (platform === "darwin") {
|
|
1112
|
+
return join(homedir(), "Library", "Application Support", name);
|
|
566
1113
|
}
|
|
1114
|
+
return join(env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), name);
|
|
567
1115
|
}
|
|
568
|
-
function
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
1116
|
+
function expandHome(path, home = homedir()) {
|
|
1117
|
+
if (path === "~")
|
|
1118
|
+
return home;
|
|
1119
|
+
if (path.startsWith("~/") || path.startsWith("~\\"))
|
|
1120
|
+
return join(home, path.slice(2));
|
|
1121
|
+
return path;
|
|
573
1122
|
}
|
|
574
|
-
function
|
|
575
|
-
const
|
|
576
|
-
if (
|
|
577
|
-
return;
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
SELECT MIN(rowid) FROM events
|
|
582
|
-
WHERE kind = 'compaction' AND message_id IS NULL
|
|
583
|
-
GROUP BY session_id, at, data
|
|
584
|
-
)`);
|
|
585
|
-
db.exec(`DELETE FROM events
|
|
586
|
-
WHERE message_id IS NOT NULL
|
|
587
|
-
AND rowid NOT IN (
|
|
588
|
-
SELECT MIN(rowid) FROM events
|
|
589
|
-
WHERE message_id IS NOT NULL
|
|
590
|
-
GROUP BY kind, message_id
|
|
591
|
-
)`);
|
|
1123
|
+
function resolveDbPath(configured, env = process.env, platform = process.platform) {
|
|
1124
|
+
const home = env.HOME ?? env.USERPROFILE ?? homedir();
|
|
1125
|
+
if (configured)
|
|
1126
|
+
return expandHome(configured, home);
|
|
1127
|
+
if (env.OPENCODE_USAGE_INSIGHTS_DB)
|
|
1128
|
+
return expandHome(env.OPENCODE_USAGE_INSIGHTS_DB, home);
|
|
1129
|
+
return defaultDbPath(env, platform);
|
|
592
1130
|
}
|
|
593
|
-
function
|
|
594
|
-
|
|
595
|
-
|
|
1131
|
+
function ensureRegularFile(path) {
|
|
1132
|
+
let stats;
|
|
1133
|
+
try {
|
|
1134
|
+
stats = statSync(path);
|
|
1135
|
+
} catch {
|
|
596
1136
|
return;
|
|
597
|
-
|
|
1137
|
+
}
|
|
1138
|
+
if (!stats.isFile())
|
|
1139
|
+
throw new Error(`not a regular file: ${path}`);
|
|
598
1140
|
}
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
1141
|
+
|
|
1142
|
+
// src/stats/constants.ts
|
|
1143
|
+
var COMPACTION_KIND = "compaction";
|
|
1144
|
+
|
|
1145
|
+
// src/stats/legacy.ts
|
|
1146
|
+
function importTimestamp(value) {
|
|
1147
|
+
if (typeof value === "number")
|
|
1148
|
+
return Number.isFinite(value) ? value : undefined;
|
|
1149
|
+
if (typeof value !== "string")
|
|
602
1150
|
return;
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
MAX(0, COALESCE(CAST(json_extract(data, '$.cost') AS REAL), 0)),
|
|
609
|
-
MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.input'), 0) AS INTEGER)),
|
|
610
|
-
MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.output'), 0) AS INTEGER)),
|
|
611
|
-
MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.reasoning'), 0) AS INTEGER)),
|
|
612
|
-
MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.cache.read'), 0) AS INTEGER)),
|
|
613
|
-
MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.cache.write'), 0) AS INTEGER))
|
|
614
|
-
FROM events
|
|
615
|
-
WHERE kind = 'compaction' AND message_id IS NULL AND at IS NOT NULL AND data IS NOT NULL
|
|
616
|
-
AND json_valid(data)`);
|
|
1151
|
+
const trimmed = value.trim();
|
|
1152
|
+
if (trimmed === "")
|
|
1153
|
+
return;
|
|
1154
|
+
const parsed = Number(trimmed);
|
|
1155
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
617
1156
|
}
|
|
618
|
-
function
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
dedupeEvents(db);
|
|
622
|
-
backfillCompactionUsage(db);
|
|
623
|
-
addEventKey(db);
|
|
1157
|
+
function numberOrZero(value) {
|
|
1158
|
+
const parsed = importTimestamp(value);
|
|
1159
|
+
return parsed === undefined ? 0 : Math.max(0, parsed);
|
|
624
1160
|
}
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
if (!POSIX)
|
|
1161
|
+
function legacyCompactionUsage(row) {
|
|
1162
|
+
if (row.kind !== COMPACTION_KIND)
|
|
628
1163
|
return;
|
|
629
|
-
|
|
630
|
-
chmodSync(path, 448);
|
|
631
|
-
} catch {}
|
|
632
|
-
}
|
|
633
|
-
function hardenFiles(path) {
|
|
634
|
-
if (!POSIX || path === ":memory:")
|
|
1164
|
+
if (row.message_id !== undefined && row.message_id !== null && row.message_id !== "")
|
|
635
1165
|
return;
|
|
636
|
-
|
|
1166
|
+
if (typeof row.session_id !== "string" || row.session_id === "")
|
|
1167
|
+
return;
|
|
1168
|
+
const at = importTimestamp(row.at);
|
|
1169
|
+
if (at === undefined)
|
|
1170
|
+
return;
|
|
1171
|
+
let payload = row.data;
|
|
1172
|
+
if (typeof payload === "string") {
|
|
637
1173
|
try {
|
|
638
|
-
|
|
639
|
-
} catch {
|
|
1174
|
+
payload = JSON.parse(payload);
|
|
1175
|
+
} catch {
|
|
1176
|
+
return;
|
|
1177
|
+
}
|
|
640
1178
|
}
|
|
641
|
-
|
|
642
|
-
function prepareDirectory(path) {
|
|
643
|
-
if (path === ":memory:")
|
|
1179
|
+
if (typeof payload !== "object" || payload === null)
|
|
644
1180
|
return;
|
|
645
|
-
|
|
646
|
-
|
|
1181
|
+
const record = payload;
|
|
1182
|
+
const tokens = typeof record.tokens === "object" && record.tokens !== null ? record.tokens : {};
|
|
1183
|
+
const cache = typeof tokens.cache === "object" && tokens.cache !== null ? tokens.cache : {};
|
|
1184
|
+
return {
|
|
1185
|
+
sessionID: row.session_id,
|
|
1186
|
+
at,
|
|
1187
|
+
cost: numberOrZero(record.cost),
|
|
1188
|
+
input: Math.floor(numberOrZero(tokens.input)),
|
|
1189
|
+
output: Math.floor(numberOrZero(tokens.output)),
|
|
1190
|
+
reasoning: Math.floor(numberOrZero(tokens.reasoning)),
|
|
1191
|
+
cacheRead: Math.floor(numberOrZero(cache.read)),
|
|
1192
|
+
cacheWrite: Math.floor(numberOrZero(cache.write))
|
|
1193
|
+
};
|
|
647
1194
|
}
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
const db = new Database(path, { create: true });
|
|
653
|
-
db.exec("PRAGMA journal_mode = WAL");
|
|
654
|
-
db.exec("PRAGMA busy_timeout = 5000");
|
|
655
|
-
db.exec("PRAGMA synchronous = NORMAL");
|
|
656
|
-
db.exec(SCHEMA);
|
|
657
|
-
migrate(db);
|
|
658
|
-
db.query("INSERT INTO meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(SCHEMA_VERSION));
|
|
659
|
-
hardenFiles(path);
|
|
660
|
-
return db;
|
|
1195
|
+
|
|
1196
|
+
// src/stats/records.ts
|
|
1197
|
+
function finite(value) {
|
|
1198
|
+
return typeof value === "number" && Number.isFinite(value) ? value : 0;
|
|
661
1199
|
}
|
|
662
|
-
function
|
|
663
|
-
|
|
664
|
-
const db = new Database(path, { readonly: true });
|
|
665
|
-
try {
|
|
666
|
-
db.query("SELECT 1 FROM steps LIMIT 1").get();
|
|
667
|
-
} catch (error) {
|
|
668
|
-
db.close();
|
|
669
|
-
throw error;
|
|
670
|
-
}
|
|
671
|
-
return db;
|
|
1200
|
+
function tokenCount(value) {
|
|
1201
|
+
return Math.max(0, Math.floor(finite(value)));
|
|
672
1202
|
}
|
|
673
|
-
function
|
|
674
|
-
|
|
675
|
-
ensureRegularFile(path);
|
|
676
|
-
prepareDirectory(path);
|
|
677
|
-
const db = new Database(path, { create: true });
|
|
678
|
-
db.exec("PRAGMA busy_timeout = 250");
|
|
679
|
-
db.exec("PRAGMA synchronous = NORMAL");
|
|
680
|
-
hardenFiles(path);
|
|
681
|
-
return db;
|
|
1203
|
+
function timestamp(value) {
|
|
1204
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
682
1205
|
}
|
|
683
|
-
|
|
1206
|
+
var STEP_UPSERT = `
|
|
1207
|
+
INSERT INTO steps (
|
|
1208
|
+
message_id, session_id, provider_id, model_id, variant,
|
|
1209
|
+
input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost, list_cost,
|
|
1210
|
+
created_at, first_token_at, streamed_at, completed_at, finish, recorded_at
|
|
1211
|
+
) VALUES (
|
|
1212
|
+
$messageID, $sessionID, $providerID, $modelID, $variant,
|
|
1213
|
+
$input, $output, $reasoning, $cacheRead, $cacheWrite, $cost, $listCost,
|
|
1214
|
+
$createdAt, $firstTokenAt, $streamedAt, $completedAt, $finish, $recordedAt
|
|
1215
|
+
)
|
|
1216
|
+
ON CONFLICT(message_id) DO UPDATE SET
|
|
1217
|
+
session_id = excluded.session_id,
|
|
1218
|
+
provider_id = COALESCE(excluded.provider_id, steps.provider_id),
|
|
1219
|
+
model_id = COALESCE(excluded.model_id, steps.model_id),
|
|
1220
|
+
variant = COALESCE(excluded.variant, steps.variant),
|
|
1221
|
+
input_tokens = excluded.input_tokens,
|
|
1222
|
+
output_tokens = excluded.output_tokens,
|
|
1223
|
+
reasoning_tokens = excluded.reasoning_tokens,
|
|
1224
|
+
cache_read = excluded.cache_read,
|
|
1225
|
+
cache_write = excluded.cache_write,
|
|
1226
|
+
cost = excluded.cost,
|
|
1227
|
+
-- A step that starts being charged loses its estimate; an estimate is
|
|
1228
|
+
-- kept when a replayed event arrives without a price table.
|
|
1229
|
+
list_cost = CASE WHEN excluded.cost > 0 THEN NULL ELSE COALESCE(excluded.list_cost, steps.list_cost) END,
|
|
1230
|
+
created_at = COALESCE(excluded.created_at, steps.created_at),
|
|
1231
|
+
first_token_at = COALESCE(excluded.first_token_at, steps.first_token_at),
|
|
1232
|
+
streamed_at = COALESCE(excluded.streamed_at, steps.streamed_at),
|
|
1233
|
+
completed_at = COALESCE(excluded.completed_at, steps.completed_at),
|
|
1234
|
+
finish = COALESCE(excluded.finish, steps.finish),
|
|
1235
|
+
recorded_at = excluded.recorded_at
|
|
1236
|
+
`;
|
|
1237
|
+
function stepCost(record) {
|
|
684
1238
|
const cost = Math.max(0, finite(record.cost));
|
|
685
1239
|
const listCost = cost <= 0 && typeof record.listCost === "number" && Number.isFinite(record.listCost) && record.listCost >= 0 ? record.listCost : null;
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
) VALUES (
|
|
691
|
-
$messageID, $sessionID, $parentID, $providerID, $modelID, $variant,
|
|
692
|
-
$input, $output, $reasoning, $cacheRead, $cacheWrite, $cost, $listCost,
|
|
693
|
-
$createdAt, $streamedAt, $completedAt, $finish, $recordedAt
|
|
694
|
-
)
|
|
695
|
-
ON CONFLICT(message_id) DO UPDATE SET
|
|
696
|
-
session_id = excluded.session_id,
|
|
697
|
-
parent_id = COALESCE(excluded.parent_id, steps.parent_id),
|
|
698
|
-
provider_id = COALESCE(excluded.provider_id, steps.provider_id),
|
|
699
|
-
model_id = COALESCE(excluded.model_id, steps.model_id),
|
|
700
|
-
variant = COALESCE(excluded.variant, steps.variant),
|
|
701
|
-
input_tokens = excluded.input_tokens,
|
|
702
|
-
output_tokens = excluded.output_tokens,
|
|
703
|
-
reasoning_tokens = excluded.reasoning_tokens,
|
|
704
|
-
cache_read = excluded.cache_read,
|
|
705
|
-
cache_write = excluded.cache_write,
|
|
706
|
-
cost = excluded.cost,
|
|
707
|
-
-- A step that starts being charged loses its estimate; an estimate is
|
|
708
|
-
-- kept when a replayed event arrives without a price table.
|
|
709
|
-
list_cost = CASE WHEN excluded.cost > 0 THEN NULL ELSE COALESCE(excluded.list_cost, steps.list_cost) END,
|
|
710
|
-
created_at = COALESCE(excluded.created_at, steps.created_at),
|
|
711
|
-
streamed_at = COALESCE(excluded.streamed_at, steps.streamed_at),
|
|
712
|
-
completed_at = COALESCE(excluded.completed_at, steps.completed_at),
|
|
713
|
-
finish = COALESCE(excluded.finish, steps.finish),
|
|
714
|
-
recorded_at = excluded.recorded_at`).run({
|
|
1240
|
+
return { cost, listCost };
|
|
1241
|
+
}
|
|
1242
|
+
function stepParams(record, cost, listCost) {
|
|
1243
|
+
return {
|
|
715
1244
|
$messageID: record.messageID,
|
|
716
1245
|
$sessionID: record.sessionID,
|
|
717
|
-
$parentID: record.parentID ?? null,
|
|
718
1246
|
$providerID: record.providerID !== undefined && isToken(record.providerID) ? record.providerID : null,
|
|
719
1247
|
$modelID: record.modelID ?? null,
|
|
720
1248
|
$variant: record.variant ?? null,
|
|
@@ -726,11 +1254,16 @@ function recordStep(db, record) {
|
|
|
726
1254
|
$cost: cost,
|
|
727
1255
|
$listCost: listCost,
|
|
728
1256
|
$createdAt: timestamp(record.createdAt),
|
|
1257
|
+
$firstTokenAt: timestamp(record.firstTokenAt),
|
|
729
1258
|
$streamedAt: timestamp(record.streamedAt),
|
|
730
1259
|
$completedAt: timestamp(record.completedAt),
|
|
731
1260
|
$finish: record.finish === undefined ? null : sanitizeLabel(record.finish, 64),
|
|
732
1261
|
$recordedAt: timestamp(record.recordedAt) ?? Date.now()
|
|
733
|
-
}
|
|
1262
|
+
};
|
|
1263
|
+
}
|
|
1264
|
+
function recordStep(db, record) {
|
|
1265
|
+
const { cost, listCost } = stepCost(record);
|
|
1266
|
+
db.query(STEP_UPSERT).run(stepParams(record, cost, listCost));
|
|
734
1267
|
}
|
|
735
1268
|
function recordUsage(db, record) {
|
|
736
1269
|
if (typeof record.id !== "string" || record.id === "")
|
|
@@ -763,384 +1296,448 @@ function recordPrompt(db, record) {
|
|
|
763
1296
|
$createdAt: timestamp(record.createdAt)
|
|
764
1297
|
});
|
|
765
1298
|
}
|
|
766
|
-
function
|
|
767
|
-
db.query(`INSERT OR IGNORE INTO
|
|
768
|
-
VALUES ($sessionID, $
|
|
1299
|
+
function recordCompaction(db, record) {
|
|
1300
|
+
db.query(`INSERT OR IGNORE INTO compactions (session_id, message_id, at)
|
|
1301
|
+
VALUES ($sessionID, $messageID, $at)`).run({
|
|
769
1302
|
$sessionID: record.sessionID,
|
|
770
|
-
$kind: sanitizeLabel(record.kind, 64),
|
|
771
1303
|
$messageID: record.messageID ?? null,
|
|
772
|
-
$at: timestamp(record.at) ?? Date.now()
|
|
773
|
-
$data: jsonText(record.data)
|
|
1304
|
+
$at: timestamp(record.at) ?? Date.now()
|
|
774
1305
|
});
|
|
775
1306
|
}
|
|
776
1307
|
function upsertSession(db, record) {
|
|
777
|
-
db.query(`INSERT INTO sessions (session_id, parent_id, directory, title, started_at
|
|
778
|
-
VALUES ($sessionID, $parentID, $directory, $title, $startedAt
|
|
1308
|
+
db.query(`INSERT INTO sessions (session_id, parent_id, directory, title, started_at)
|
|
1309
|
+
VALUES ($sessionID, $parentID, $directory, $title, $startedAt)
|
|
779
1310
|
ON CONFLICT(session_id) DO UPDATE SET
|
|
780
1311
|
parent_id = COALESCE(excluded.parent_id, sessions.parent_id),
|
|
781
1312
|
directory = COALESCE(excluded.directory, sessions.directory),
|
|
782
1313
|
title = COALESCE(excluded.title, sessions.title),
|
|
783
|
-
started_at = COALESCE(sessions.started_at, excluded.started_at)
|
|
784
|
-
updated_at = COALESCE(excluded.updated_at, sessions.updated_at)`).run({
|
|
1314
|
+
started_at = COALESCE(sessions.started_at, excluded.started_at)`).run({
|
|
785
1315
|
$sessionID: record.sessionID,
|
|
786
1316
|
$parentID: record.parentID ?? null,
|
|
787
1317
|
$directory: record.directory === undefined ? null : sanitizeLabel(record.directory, LABEL_LIMIT),
|
|
788
1318
|
$title: record.title === undefined ? null : sanitizeLabel(record.title, LABEL_LIMIT),
|
|
789
|
-
$startedAt: timestamp(record.startedAt)
|
|
790
|
-
$updatedAt: timestamp(record.updatedAt)
|
|
1319
|
+
$startedAt: timestamp(record.startedAt)
|
|
791
1320
|
});
|
|
792
1321
|
}
|
|
793
1322
|
|
|
794
|
-
// src/
|
|
795
|
-
var
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
1323
|
+
// src/stats/migrate.ts
|
|
1324
|
+
var REMOVED_COLUMNS = {
|
|
1325
|
+
steps: ["provider_state", "upstream", "upstream_source", "upstream_model", "tps", "router", "parent_id"],
|
|
1326
|
+
sessions: ["updated_at"]
|
|
1327
|
+
};
|
|
1328
|
+
function dropUnused(db) {
|
|
1329
|
+
const objects = db.query("SELECT name, type FROM sqlite_master WHERE type IN ('table', 'index')").all();
|
|
1330
|
+
const indexes = new Set(objects.filter((row) => row.type === "index").map((row) => row.name));
|
|
1331
|
+
if (hasTable(db, "http_responses"))
|
|
1332
|
+
db.exec("DROP TABLE http_responses");
|
|
1333
|
+
if (indexes.has("steps_upstream"))
|
|
1334
|
+
db.exec("DROP INDEX steps_upstream");
|
|
1335
|
+
if (indexes.has("steps_router"))
|
|
1336
|
+
db.exec("DROP INDEX steps_router");
|
|
1337
|
+
for (const [table, names] of Object.entries(REMOVED_COLUMNS)) {
|
|
1338
|
+
const columns = columnsOf(db, table);
|
|
1339
|
+
for (const name of names) {
|
|
1340
|
+
if (columns.has(name))
|
|
1341
|
+
db.exec(`ALTER TABLE ${table} DROP COLUMN ${name}`);
|
|
804
1342
|
}
|
|
805
|
-
if (!PROMPT_BOUNDARIES.has(message.type))
|
|
806
|
-
continue;
|
|
807
|
-
if (current.length === 0)
|
|
808
|
-
continue;
|
|
809
|
-
segments.unshift({ assistants: current, prompt: message });
|
|
810
|
-
if (segments.length >= count)
|
|
811
|
-
return segments;
|
|
812
|
-
current = [];
|
|
813
1343
|
}
|
|
814
|
-
if (current.length > 0 && segments.length < count)
|
|
815
|
-
segments.unshift({ assistants: current, prompt: undefined });
|
|
816
|
-
return segments;
|
|
817
1344
|
}
|
|
818
|
-
function
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
826
|
-
}
|
|
827
|
-
function tokenCounts(message) {
|
|
828
|
-
const tokens = message.tokens;
|
|
829
|
-
return {
|
|
830
|
-
input: countOf(tokens?.input),
|
|
831
|
-
output: countOf(tokens?.output),
|
|
832
|
-
reasoning: countOf(tokens?.reasoning),
|
|
833
|
-
read: countOf(tokens?.cache?.read),
|
|
834
|
-
write: countOf(tokens?.cache?.write)
|
|
835
|
-
};
|
|
836
|
-
}
|
|
837
|
-
function totalize(steps) {
|
|
838
|
-
const totals = { input: 0, cached: 0, output: 0, reasoning: 0, cacheWrite: 0, cost: 0, listCost: 0, steps: steps.length };
|
|
839
|
-
for (const step of steps) {
|
|
840
|
-
const counts = tokenCounts(step);
|
|
841
|
-
totals.input += counts.input;
|
|
842
|
-
totals.cached += counts.read;
|
|
843
|
-
totals.output += counts.output;
|
|
844
|
-
totals.reasoning += counts.reasoning;
|
|
845
|
-
totals.cacheWrite += counts.write;
|
|
846
|
-
totals.cost += amountOf(step.cost);
|
|
847
|
-
totals.listCost += amountOf(step.listCost);
|
|
1345
|
+
function addMissing(db) {
|
|
1346
|
+
const columns = columnsOf(db, "steps");
|
|
1347
|
+
if (columns.size > 0 && !columns.has("list_cost")) {
|
|
1348
|
+
db.exec("ALTER TABLE steps ADD COLUMN list_cost REAL");
|
|
1349
|
+
}
|
|
1350
|
+
if (columns.size > 0 && !columns.has("first_token_at")) {
|
|
1351
|
+
db.exec("ALTER TABLE steps ADD COLUMN first_token_at INTEGER");
|
|
848
1352
|
}
|
|
849
|
-
return totals;
|
|
850
1353
|
}
|
|
851
|
-
function
|
|
852
|
-
if (!
|
|
1354
|
+
function dedupeLegacyCompactions(db) {
|
|
1355
|
+
if (!hasTable(db, "events"))
|
|
853
1356
|
return;
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
function cacheRead(message) {
|
|
857
|
-
return countOf(message?.tokens?.cache?.read);
|
|
858
|
-
}
|
|
859
|
-
function stepCreated(message) {
|
|
860
|
-
return stampOf(message?.time?.created);
|
|
861
|
-
}
|
|
862
|
-
function stepEnd(message) {
|
|
863
|
-
const time = message?.time;
|
|
864
|
-
if (!time)
|
|
1357
|
+
const columns = columnsOf(db, "events");
|
|
1358
|
+
if (!["session_id", "kind", "message_id", "at"].every((name) => columns.has(name)))
|
|
865
1359
|
return;
|
|
866
|
-
|
|
1360
|
+
if (columns.has("data")) {
|
|
1361
|
+
db.query(`DELETE FROM events
|
|
1362
|
+
WHERE kind = ? AND message_id IS NULL
|
|
1363
|
+
AND rowid NOT IN (
|
|
1364
|
+
SELECT MIN(rowid) FROM events
|
|
1365
|
+
WHERE kind = ? AND message_id IS NULL
|
|
1366
|
+
GROUP BY session_id, at, data
|
|
1367
|
+
)`).run(COMPACTION_KIND, COMPACTION_KIND);
|
|
1368
|
+
} else {
|
|
1369
|
+
db.query(`DELETE FROM events
|
|
1370
|
+
WHERE kind = ? AND message_id IS NULL AND at IS NOT NULL
|
|
1371
|
+
AND rowid NOT IN (
|
|
1372
|
+
SELECT MIN(rowid) FROM events
|
|
1373
|
+
WHERE kind = ? AND message_id IS NULL AND at IS NOT NULL
|
|
1374
|
+
GROUP BY session_id, at
|
|
1375
|
+
)`).run(COMPACTION_KIND, COMPACTION_KIND);
|
|
1376
|
+
}
|
|
1377
|
+
db.exec(`DELETE FROM events
|
|
1378
|
+
WHERE message_id IS NOT NULL
|
|
1379
|
+
AND rowid NOT IN (
|
|
1380
|
+
SELECT MIN(rowid) FROM events
|
|
1381
|
+
WHERE message_id IS NOT NULL
|
|
1382
|
+
GROUP BY message_id
|
|
1383
|
+
)`);
|
|
867
1384
|
}
|
|
868
|
-
function
|
|
869
|
-
if (!
|
|
870
|
-
return;
|
|
871
|
-
const before = reference.model;
|
|
872
|
-
const after = current.model;
|
|
873
|
-
if (!before || !after)
|
|
874
|
-
return;
|
|
875
|
-
if (scope === "provider" && before.providerID !== after.providerID)
|
|
1385
|
+
function backfillCompactionUsage(db) {
|
|
1386
|
+
if (!hasTable(db, "events") || !hasTable(db, "usage"))
|
|
876
1387
|
return;
|
|
877
|
-
|
|
1388
|
+
const columns = columnsOf(db, "events");
|
|
1389
|
+
if (!["session_id", "kind", "message_id", "at", "data"].every((name) => columns.has(name)))
|
|
878
1390
|
return;
|
|
1391
|
+
const rows = db.query(`SELECT rowid AS id, session_id, kind, message_id, at, data
|
|
1392
|
+
FROM events
|
|
1393
|
+
WHERE kind = ? AND message_id IS NULL AND at IS NOT NULL AND data IS NOT NULL`).all(COMPACTION_KIND);
|
|
1394
|
+
for (const row of rows) {
|
|
1395
|
+
const legacy = legacyCompactionUsage(row);
|
|
1396
|
+
if (legacy === undefined)
|
|
1397
|
+
continue;
|
|
1398
|
+
recordUsage(db, {
|
|
1399
|
+
id: `compaction:${String(row.id)}`,
|
|
1400
|
+
sessionID: legacy.sessionID,
|
|
1401
|
+
source: COMPACTION_KIND,
|
|
1402
|
+
at: legacy.at,
|
|
1403
|
+
cost: legacy.cost,
|
|
1404
|
+
input: legacy.input,
|
|
1405
|
+
output: legacy.output,
|
|
1406
|
+
reasoning: legacy.reasoning,
|
|
1407
|
+
cacheRead: legacy.cacheRead,
|
|
1408
|
+
cacheWrite: legacy.cacheWrite
|
|
1409
|
+
});
|
|
879
1410
|
}
|
|
880
|
-
const drop = cacheRead(reference) - cacheRead(current);
|
|
881
|
-
if (isNoiseDrop(after.providerID, drop))
|
|
882
|
-
return;
|
|
883
|
-
return drop > 0 ? drop : undefined;
|
|
884
|
-
}
|
|
885
|
-
function stepGap(reference, current) {
|
|
886
|
-
const ended = stepEnd(reference);
|
|
887
|
-
const started = stepCreated(current);
|
|
888
|
-
if (ended === undefined || started === undefined)
|
|
889
|
-
return;
|
|
890
|
-
return Math.max(0, started - ended);
|
|
891
1411
|
}
|
|
892
|
-
function
|
|
893
|
-
if (
|
|
1412
|
+
function migrateLegacyCompactions(db) {
|
|
1413
|
+
if (!hasTable(db, "events"))
|
|
894
1414
|
return;
|
|
895
|
-
|
|
1415
|
+
const columns = columnsOf(db, "events");
|
|
1416
|
+
if (!["session_id", "kind", "message_id", "at"].every((name) => columns.has(name)))
|
|
896
1417
|
return;
|
|
897
|
-
|
|
1418
|
+
db.query(`INSERT OR IGNORE INTO compactions (session_id, message_id, at)
|
|
1419
|
+
SELECT session_id, message_id, at FROM events WHERE kind = ?`).run(COMPACTION_KIND);
|
|
1420
|
+
db.exec("DROP TABLE events");
|
|
898
1421
|
}
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
1422
|
+
function migrate(db) {
|
|
1423
|
+
db.transaction(() => {
|
|
1424
|
+
dropUnused(db);
|
|
1425
|
+
addMissing(db);
|
|
1426
|
+
dedupeLegacyCompactions(db);
|
|
1427
|
+
backfillCompactionUsage(db);
|
|
1428
|
+
migrateLegacyCompactions(db);
|
|
1429
|
+
})();
|
|
904
1430
|
}
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
const previous = segments[segments.length - 2];
|
|
911
|
-
const lastStep = last.assistants[last.assistants.length - 1];
|
|
912
|
-
if (!lastStep)
|
|
1431
|
+
|
|
1432
|
+
// src/stats/open.ts
|
|
1433
|
+
var POSIX = process.platform !== "win32";
|
|
1434
|
+
function hardenDirectory(path) {
|
|
1435
|
+
if (!POSIX)
|
|
913
1436
|
return;
|
|
914
|
-
|
|
1437
|
+
try {
|
|
1438
|
+
chmodSync(path, 448);
|
|
1439
|
+
} catch {}
|
|
1440
|
+
}
|
|
1441
|
+
function hardenFiles(path) {
|
|
1442
|
+
if (!POSIX || path === ":memory:")
|
|
915
1443
|
return;
|
|
916
|
-
const
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
for (const step of settled) {
|
|
921
|
-
const drop = cacheDrop(reference, step);
|
|
922
|
-
if (drop !== undefined) {
|
|
923
|
-
drops.push({
|
|
924
|
-
messageID: step.id,
|
|
925
|
-
tokens: drop,
|
|
926
|
-
prevCached: cacheRead(reference),
|
|
927
|
-
gapMs: stepGap(reference, step)
|
|
928
|
-
});
|
|
929
|
-
}
|
|
930
|
-
reference = step;
|
|
1444
|
+
for (const file of [path, `${path}-wal`, `${path}-shm`]) {
|
|
1445
|
+
try {
|
|
1446
|
+
chmodSync(file, 384);
|
|
1447
|
+
} catch {}
|
|
931
1448
|
}
|
|
932
|
-
const provider = lastStep.model?.providerID;
|
|
933
|
-
const previousProvider = previousStep?.model?.providerID;
|
|
934
|
-
const key = identityKey(lastStep.model);
|
|
935
|
-
const previousKey = identityKey(previousStep?.model);
|
|
936
|
-
return {
|
|
937
|
-
endAt: stepEnd(lastStep),
|
|
938
|
-
startAt: stepCreated(settled[0] ?? lastStep),
|
|
939
|
-
promptAt: stampOf(last.prompt?.time?.created),
|
|
940
|
-
promptGapMs: promptGap(last.prompt, previous?.prompt),
|
|
941
|
-
providerID: provider,
|
|
942
|
-
modelID: lastStep.model?.id,
|
|
943
|
-
variant: lastStep.model?.variant,
|
|
944
|
-
providerChanged: previousProvider !== undefined && provider !== undefined && previousProvider !== provider,
|
|
945
|
-
modelChanged: previousKey !== undefined && key !== undefined && previousKey !== key && previousProvider === provider,
|
|
946
|
-
totals: totalize(settled),
|
|
947
|
-
latest: totalize([lastStep]),
|
|
948
|
-
session,
|
|
949
|
-
drops,
|
|
950
|
-
cacheDropTokens: drops.reduce((sum, drop) => sum + drop.tokens, 0),
|
|
951
|
-
cacheExpired: drops.length > 0,
|
|
952
|
-
steps: settled.length
|
|
953
|
-
};
|
|
954
1449
|
}
|
|
955
|
-
function
|
|
956
|
-
|
|
957
|
-
const before = stampOf(previous?.time?.created);
|
|
958
|
-
if (now === undefined || before === undefined)
|
|
1450
|
+
function prepareDirectory(path) {
|
|
1451
|
+
if (path === ":memory:")
|
|
959
1452
|
return;
|
|
960
|
-
|
|
1453
|
+
mkdirSync(dirname(path), { recursive: true, mode: 448 });
|
|
1454
|
+
hardenDirectory(dirname(path));
|
|
961
1455
|
}
|
|
962
|
-
function
|
|
963
|
-
if (
|
|
964
|
-
|
|
965
|
-
|
|
1456
|
+
function openStatsDb(path) {
|
|
1457
|
+
if (path !== ":memory:")
|
|
1458
|
+
ensureRegularFile(path);
|
|
1459
|
+
prepareDirectory(path);
|
|
1460
|
+
const db = new Database(path, { create: true });
|
|
1461
|
+
try {
|
|
1462
|
+
db.exec("PRAGMA journal_mode = WAL");
|
|
1463
|
+
db.exec("PRAGMA busy_timeout = 5000");
|
|
1464
|
+
db.exec("PRAGMA synchronous = NORMAL");
|
|
1465
|
+
db.exec(SCHEMA);
|
|
1466
|
+
migrate(db);
|
|
1467
|
+
db.query("INSERT INTO meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(SCHEMA_VERSION));
|
|
1468
|
+
hardenFiles(path);
|
|
1469
|
+
return db;
|
|
1470
|
+
} catch (error) {
|
|
1471
|
+
db.close();
|
|
1472
|
+
throw error;
|
|
1473
|
+
}
|
|
966
1474
|
}
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
cost: "cost",
|
|
978
|
-
estimate: "\u2248",
|
|
979
|
-
cacheExpired: "cache expired",
|
|
980
|
-
providerChanged: "changed",
|
|
981
|
-
modelChanged: "model changed"
|
|
982
|
-
};
|
|
983
|
-
var DEFAULT_FIELDS = {
|
|
984
|
-
clock: true,
|
|
985
|
-
delta: true,
|
|
986
|
-
model: true,
|
|
987
|
-
variant: true,
|
|
988
|
-
turn: true,
|
|
989
|
-
session: true,
|
|
990
|
-
reasoning: false,
|
|
991
|
-
cost: true,
|
|
992
|
-
cacheExpiry: true
|
|
993
|
-
};
|
|
994
|
-
function formatClock(ms) {
|
|
995
|
-
if (!Number.isFinite(ms))
|
|
996
|
-
return "--:--";
|
|
997
|
-
const date = new Date(ms);
|
|
998
|
-
const pad = (value) => String(value).padStart(2, "0");
|
|
999
|
-
return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
|
1475
|
+
function openStatsDbReadOnly(path) {
|
|
1476
|
+
ensureRegularFile(path);
|
|
1477
|
+
const db = new Database(path, { readonly: true });
|
|
1478
|
+
try {
|
|
1479
|
+
db.query("SELECT 1 FROM steps LIMIT 1").get();
|
|
1480
|
+
} catch (error) {
|
|
1481
|
+
db.close();
|
|
1482
|
+
throw error;
|
|
1483
|
+
}
|
|
1484
|
+
return db;
|
|
1000
1485
|
}
|
|
1001
|
-
function
|
|
1002
|
-
if (
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
const
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
return `${days}d${hours}h`;
|
|
1011
|
-
if (hours > 0)
|
|
1012
|
-
return `${hours}h${String(minutes).padStart(2, "0")}m`;
|
|
1013
|
-
if (minutes > 0)
|
|
1014
|
-
return `${minutes}m${String(seconds).padStart(2, "0")}s`;
|
|
1015
|
-
return `${seconds}s`;
|
|
1486
|
+
function openStatsDbWrite(path) {
|
|
1487
|
+
if (path !== ":memory:")
|
|
1488
|
+
ensureRegularFile(path);
|
|
1489
|
+
prepareDirectory(path);
|
|
1490
|
+
const db = new Database(path, { create: true });
|
|
1491
|
+
db.exec("PRAGMA busy_timeout = 250");
|
|
1492
|
+
db.exec("PRAGMA synchronous = NORMAL");
|
|
1493
|
+
hardenFiles(path);
|
|
1494
|
+
return db;
|
|
1016
1495
|
}
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1496
|
+
// src/recorder.ts
|
|
1497
|
+
function createRecorder(db, options) {
|
|
1498
|
+
const MAX_TRACKED_SESSIONS = 512;
|
|
1499
|
+
const MAX_PENDING = 256;
|
|
1500
|
+
const pending = new Map;
|
|
1501
|
+
const lastModel = new Map;
|
|
1502
|
+
const now = options?.now ?? (() => Date.now());
|
|
1503
|
+
const MAX_DEFERRED = 256;
|
|
1504
|
+
const deferred = [];
|
|
1505
|
+
function isBusy(error) {
|
|
1506
|
+
const code = error?.code;
|
|
1507
|
+
return code === "SQLITE_BUSY" || code === "SQLITE_LOCKED";
|
|
1024
1508
|
}
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1509
|
+
function enqueue(run) {
|
|
1510
|
+
if (deferred.length >= MAX_DEFERRED)
|
|
1511
|
+
deferred.shift();
|
|
1512
|
+
deferred.push(run);
|
|
1028
1513
|
}
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
if (value < 1)
|
|
1040
|
-
return `$${value.toFixed(4)}`;
|
|
1041
|
-
return `$${value.toFixed(2)}`;
|
|
1042
|
-
}
|
|
1043
|
-
function formatMoney(charged, estimated, marker = "\u2248") {
|
|
1044
|
-
const paid = Number.isFinite(charged) && charged > 0 ? formatCost(charged) : undefined;
|
|
1045
|
-
const estimate = Number.isFinite(estimated) && estimated > 0 ? `${marker.trim() === "" ? "" : `${marker.trim()} `}${formatCost(estimated)}` : undefined;
|
|
1046
|
-
if (paid !== undefined && estimate !== undefined)
|
|
1047
|
-
return `${paid} + ${estimate}`;
|
|
1048
|
-
return paid ?? estimate;
|
|
1049
|
-
}
|
|
1050
|
-
function formatSpend(charged, estimated, marker = "\u2248") {
|
|
1051
|
-
const paid = Number.isFinite(charged) ? Math.max(0, charged) : 0;
|
|
1052
|
-
const estimate = Number.isFinite(estimated) ? Math.max(0, estimated) : 0;
|
|
1053
|
-
if (estimate > 0)
|
|
1054
|
-
return `${marker.trim()}${formatCost(paid + estimate)}`;
|
|
1055
|
-
return formatCost(paid);
|
|
1056
|
-
}
|
|
1057
|
-
function displayTotals(totals) {
|
|
1058
|
-
const prompt = totals.input + totals.cached + totals.cacheWrite;
|
|
1059
|
-
return {
|
|
1060
|
-
input: prompt - totals.cached,
|
|
1061
|
-
cached: totals.cached,
|
|
1062
|
-
cacheWrite: totals.cacheWrite,
|
|
1063
|
-
output: totals.output + totals.reasoning,
|
|
1064
|
-
reasoning: totals.reasoning,
|
|
1065
|
-
cost: totals.cost,
|
|
1066
|
-
listCost: totals.listCost,
|
|
1067
|
-
steps: totals.steps,
|
|
1068
|
-
prompt
|
|
1069
|
-
};
|
|
1070
|
-
}
|
|
1071
|
-
function totalsText(prefix, totals, labels, fields, stepCount = 0, cost = totals.cost, listCost = totals.listCost, estimates = true) {
|
|
1072
|
-
const display = displayTotals(totals);
|
|
1073
|
-
const input = display.prompt === display.input ? `${labels.input} ${formatTokens(display.input)}` : `${labels.input} ${formatTokens(display.input)} (${formatTokens(display.prompt)})`;
|
|
1074
|
-
const parts = [
|
|
1075
|
-
input,
|
|
1076
|
-
`${labels.cached} ${formatTokens(display.cached)}`,
|
|
1077
|
-
`${labels.output} ${formatTokens(display.output)}`
|
|
1078
|
-
];
|
|
1079
|
-
if (fields.reasoning)
|
|
1080
|
-
parts.push(`${labels.reasoning} ${formatTokens(display.reasoning)}`);
|
|
1081
|
-
const money = fields.cost ? formatMoney(cost, estimates ? listCost : 0, labels.estimate) : undefined;
|
|
1082
|
-
if (money !== undefined)
|
|
1083
|
-
parts.push(`${labels.cost} ${money}`);
|
|
1084
|
-
const steps = stepCount > 1 ? `${stepCount} ${stepCount === 1 ? labels.step : labels.steps}` : "";
|
|
1085
|
-
const head = [prefix, steps].filter((piece) => piece !== "").join(" ");
|
|
1086
|
-
const numbers = parts.join(", ");
|
|
1087
|
-
if (head === "")
|
|
1088
|
-
return numbers;
|
|
1089
|
-
return stepCount > 1 ? `${head} \xB7 ${numbers}` : `${head} ${numbers}`;
|
|
1090
|
-
}
|
|
1091
|
-
function formatLineSegments(stats, options) {
|
|
1092
|
-
const labels = { ...DEFAULT_LABELS, ...options?.labels };
|
|
1093
|
-
const fields = { ...DEFAULT_FIELDS, ...options?.fields };
|
|
1094
|
-
const turnTotals = options?.turnTotals ?? "latest";
|
|
1095
|
-
const estimates = options?.estimates !== false;
|
|
1096
|
-
const segments = [];
|
|
1097
|
-
if (fields.clock && stats.endAt !== undefined) {
|
|
1098
|
-
segments.push({ text: formatClock(stats.endAt), tone: "muted" });
|
|
1514
|
+
function flushDeferred() {
|
|
1515
|
+
while (deferred.length > 0) {
|
|
1516
|
+
const next = deferred[0];
|
|
1517
|
+
try {
|
|
1518
|
+
next();
|
|
1519
|
+
} catch {
|
|
1520
|
+
return;
|
|
1521
|
+
}
|
|
1522
|
+
deferred.shift();
|
|
1523
|
+
}
|
|
1099
1524
|
}
|
|
1100
|
-
|
|
1101
|
-
|
|
1525
|
+
function write(run) {
|
|
1526
|
+
if (deferred.length > 0) {
|
|
1527
|
+
flushDeferred();
|
|
1528
|
+
if (deferred.length > 0) {
|
|
1529
|
+
enqueue(run);
|
|
1530
|
+
return;
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
try {
|
|
1534
|
+
run();
|
|
1535
|
+
} catch (error) {
|
|
1536
|
+
if (isBusy(error))
|
|
1537
|
+
enqueue(run);
|
|
1538
|
+
}
|
|
1102
1539
|
}
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
else if (stats.modelChanged)
|
|
1113
|
-
segments.push({ text: labels.modelChanged, tone: "muted" });
|
|
1540
|
+
function remember(map, key, value, limit) {
|
|
1541
|
+
map.delete(key);
|
|
1542
|
+
map.set(key, value);
|
|
1543
|
+
while (map.size > limit) {
|
|
1544
|
+
const oldest = map.keys().next();
|
|
1545
|
+
if (oldest.done === true)
|
|
1546
|
+
break;
|
|
1547
|
+
map.delete(oldest.value);
|
|
1548
|
+
}
|
|
1114
1549
|
}
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
}
|
|
1550
|
+
function forget(sessionID) {
|
|
1551
|
+
lastModel.delete(sessionID);
|
|
1552
|
+
for (const [messageID, step] of pending) {
|
|
1553
|
+
if (step.sessionID === sessionID)
|
|
1554
|
+
pending.delete(messageID);
|
|
1555
|
+
}
|
|
1121
1556
|
}
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1557
|
+
function recordPendingStep(messageID, data, finish, at) {
|
|
1558
|
+
const sessionID = data.sessionID;
|
|
1559
|
+
if (typeof sessionID !== "string")
|
|
1560
|
+
return;
|
|
1561
|
+
const info = pending.get(messageID);
|
|
1562
|
+
pending.delete(messageID);
|
|
1563
|
+
const model = info?.model ?? lastModel.get(sessionID);
|
|
1564
|
+
const charged = data.cost;
|
|
1565
|
+
const estimate = charged !== undefined && charged > 0 ? undefined : options?.price?.({ providerID: model?.providerID, modelID: model?.id }, {
|
|
1566
|
+
input: data.tokens?.input,
|
|
1567
|
+
output: data.tokens?.output,
|
|
1568
|
+
reasoning: data.tokens?.reasoning,
|
|
1569
|
+
cacheRead: data.tokens?.cache?.read,
|
|
1570
|
+
cacheWrite: data.tokens?.cache?.write
|
|
1126
1571
|
});
|
|
1572
|
+
write(() => recordStep(db, {
|
|
1573
|
+
messageID,
|
|
1574
|
+
sessionID,
|
|
1575
|
+
providerID: model?.providerID,
|
|
1576
|
+
modelID: model?.id,
|
|
1577
|
+
variant: model?.variant,
|
|
1578
|
+
input: data.tokens?.input,
|
|
1579
|
+
output: data.tokens?.output,
|
|
1580
|
+
reasoning: data.tokens?.reasoning,
|
|
1581
|
+
cacheRead: data.tokens?.cache?.read,
|
|
1582
|
+
cacheWrite: data.tokens?.cache?.write,
|
|
1583
|
+
cost: data.cost,
|
|
1584
|
+
listCost: estimate !== undefined && Number.isFinite(estimate) && estimate >= 0 ? estimate : undefined,
|
|
1585
|
+
createdAt: info?.started,
|
|
1586
|
+
firstTokenAt: info?.firstToken,
|
|
1587
|
+
streamedAt: info?.streamed,
|
|
1588
|
+
completedAt: at,
|
|
1589
|
+
finish,
|
|
1590
|
+
recordedAt: now()
|
|
1591
|
+
}));
|
|
1127
1592
|
}
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1593
|
+
function handleEvent(event) {
|
|
1594
|
+
if (deferred.length > 0)
|
|
1595
|
+
flushDeferred();
|
|
1596
|
+
const data = event.data ?? {};
|
|
1597
|
+
const at = typeof event.created === "number" ? event.created : now();
|
|
1598
|
+
const sessionID = typeof data.sessionID === "string" ? data.sessionID : undefined;
|
|
1599
|
+
switch (event.type) {
|
|
1600
|
+
case "session.created": {
|
|
1601
|
+
if (sessionID === undefined)
|
|
1602
|
+
return;
|
|
1603
|
+
write(() => upsertSession(db, {
|
|
1604
|
+
sessionID,
|
|
1605
|
+
parentID: data.parentID,
|
|
1606
|
+
directory: data.location?.directory,
|
|
1607
|
+
title: data.title,
|
|
1608
|
+
startedAt: at
|
|
1609
|
+
}));
|
|
1610
|
+
if (data.model !== undefined)
|
|
1611
|
+
remember(lastModel, sessionID, data.model, MAX_TRACKED_SESSIONS);
|
|
1612
|
+
return;
|
|
1613
|
+
}
|
|
1614
|
+
case "session.deleted": {
|
|
1615
|
+
if (sessionID !== undefined)
|
|
1616
|
+
forget(sessionID);
|
|
1617
|
+
return;
|
|
1618
|
+
}
|
|
1619
|
+
case "session.renamed": {
|
|
1620
|
+
if (sessionID === undefined)
|
|
1621
|
+
return;
|
|
1622
|
+
write(() => upsertSession(db, { sessionID, title: data.title }));
|
|
1623
|
+
return;
|
|
1624
|
+
}
|
|
1625
|
+
case "session.moved": {
|
|
1626
|
+
if (sessionID === undefined)
|
|
1627
|
+
return;
|
|
1628
|
+
write(() => upsertSession(db, { sessionID, directory: data.location?.directory }));
|
|
1629
|
+
return;
|
|
1630
|
+
}
|
|
1631
|
+
case "session.inbox.enqueued": {
|
|
1632
|
+
if (sessionID === undefined)
|
|
1633
|
+
return;
|
|
1634
|
+
if (data.item?.type !== "user" && data.item?.type !== "synthetic")
|
|
1635
|
+
return;
|
|
1636
|
+
const inboxID = data.inboxID;
|
|
1637
|
+
if (typeof inboxID !== "string")
|
|
1638
|
+
return;
|
|
1639
|
+
write(() => recordPrompt(db, { sessionID, messageID: inboxID, createdAt: at }));
|
|
1640
|
+
return;
|
|
1641
|
+
}
|
|
1642
|
+
case "session.model.selected": {
|
|
1643
|
+
if (sessionID !== undefined && data.model !== undefined)
|
|
1644
|
+
remember(lastModel, sessionID, data.model, MAX_TRACKED_SESSIONS);
|
|
1645
|
+
return;
|
|
1646
|
+
}
|
|
1647
|
+
case "session.step.started": {
|
|
1648
|
+
if (sessionID === undefined || typeof data.assistantMessageID !== "string")
|
|
1649
|
+
return;
|
|
1650
|
+
remember(pending, data.assistantMessageID, {
|
|
1651
|
+
messageID: data.assistantMessageID,
|
|
1652
|
+
sessionID,
|
|
1653
|
+
started: typeof data.started === "number" ? data.started : undefined,
|
|
1654
|
+
firstToken: undefined,
|
|
1655
|
+
streamed: undefined,
|
|
1656
|
+
model: data.model
|
|
1657
|
+
}, MAX_PENDING);
|
|
1658
|
+
return;
|
|
1659
|
+
}
|
|
1660
|
+
case "session.step.first-token": {
|
|
1661
|
+
if (typeof data.assistantMessageID !== "string")
|
|
1662
|
+
return;
|
|
1663
|
+
const info = pending.get(data.assistantMessageID);
|
|
1664
|
+
if (info !== undefined)
|
|
1665
|
+
info.firstToken = at;
|
|
1666
|
+
return;
|
|
1667
|
+
}
|
|
1668
|
+
case "session.step.streamed": {
|
|
1669
|
+
if (typeof data.assistantMessageID !== "string")
|
|
1670
|
+
return;
|
|
1671
|
+
const info = pending.get(data.assistantMessageID);
|
|
1672
|
+
if (info !== undefined)
|
|
1673
|
+
info.streamed = at;
|
|
1674
|
+
return;
|
|
1675
|
+
}
|
|
1676
|
+
case "session.step.ended": {
|
|
1677
|
+
if (typeof data.assistantMessageID !== "string")
|
|
1678
|
+
return;
|
|
1679
|
+
recordPendingStep(data.assistantMessageID, data, data.finish ?? "unknown", at);
|
|
1680
|
+
return;
|
|
1681
|
+
}
|
|
1682
|
+
case "session.step.failed": {
|
|
1683
|
+
if (typeof data.assistantMessageID !== "string")
|
|
1684
|
+
return;
|
|
1685
|
+
recordPendingStep(data.assistantMessageID, data, data.finish ?? "error", at);
|
|
1686
|
+
return;
|
|
1687
|
+
}
|
|
1688
|
+
case "session.usage.recorded": {
|
|
1689
|
+
if (sessionID === undefined)
|
|
1690
|
+
return;
|
|
1691
|
+
const source = typeof data.source === "string" ? data.source : undefined;
|
|
1692
|
+
if (source === undefined || source === "generate")
|
|
1693
|
+
return;
|
|
1694
|
+
const id = typeof event.id === "string" && event.id !== "" ? event.id : `${sessionID}:${source}:${at}:${data.cost ?? 0}`;
|
|
1695
|
+
write(() => recordUsage(db, {
|
|
1696
|
+
id,
|
|
1697
|
+
sessionID,
|
|
1698
|
+
source,
|
|
1699
|
+
at,
|
|
1700
|
+
cost: data.cost,
|
|
1701
|
+
input: data.tokens?.input,
|
|
1702
|
+
output: data.tokens?.output,
|
|
1703
|
+
reasoning: data.tokens?.reasoning,
|
|
1704
|
+
cacheRead: data.tokens?.cache?.read,
|
|
1705
|
+
cacheWrite: data.tokens?.cache?.write
|
|
1706
|
+
}));
|
|
1707
|
+
return;
|
|
1708
|
+
}
|
|
1709
|
+
case "session.compaction.ended": {
|
|
1710
|
+
if (sessionID === undefined)
|
|
1711
|
+
return;
|
|
1712
|
+
const messageID = typeof event.id === "string" && event.id !== "" ? event.id : `compaction:${sessionID}:${at}`;
|
|
1713
|
+
write(() => recordCompaction(db, { sessionID, messageID, at }));
|
|
1714
|
+
return;
|
|
1715
|
+
}
|
|
1716
|
+
default:
|
|
1717
|
+
return;
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
function pendingFor(sessionID) {
|
|
1721
|
+
let found;
|
|
1722
|
+
for (const item of pending.values()) {
|
|
1723
|
+
if (item.sessionID !== sessionID)
|
|
1724
|
+
continue;
|
|
1725
|
+
if (found === undefined || (item.started ?? 0) >= (found.started ?? 0))
|
|
1726
|
+
found = item;
|
|
1727
|
+
}
|
|
1728
|
+
return found;
|
|
1729
|
+
}
|
|
1730
|
+
return { handleEvent, pendingFor };
|
|
1731
|
+
}
|
|
1732
|
+
|
|
1733
|
+
// src/service.ts
|
|
1734
|
+
import { basename } from "path";
|
|
1735
|
+
|
|
1736
|
+
// src/stats/queries.ts
|
|
1737
|
+
var DEFAULT_TTL_HINT_MS = 10 * 60 * 1000;
|
|
1738
|
+
function spend(usage) {
|
|
1739
|
+
return usage.cost + usage.listCost;
|
|
1740
|
+
}
|
|
1144
1741
|
function sessionListCost(db, sessionID) {
|
|
1145
1742
|
const row = db.query("SELECT COALESCE(SUM(list_cost), 0) AS listCost FROM steps WHERE session_id = ?").get(sessionID);
|
|
1146
1743
|
return row?.listCost ?? 0;
|
|
@@ -1206,9 +1803,12 @@ function otherUsageRows(db, range, filters) {
|
|
|
1206
1803
|
}
|
|
1207
1804
|
}
|
|
1208
1805
|
var STEP_TIME = "COALESCE(created_at, recorded_at)";
|
|
1209
|
-
var
|
|
1806
|
+
var MODEL_KEY_SEPARATOR = "#";
|
|
1807
|
+
function modelKeySQL(prefix = "") {
|
|
1808
|
+
return `COALESCE(${prefix}model_id, '(unknown)') || '${MODEL_KEY_SEPARATOR}' || COALESCE(${prefix}variant, '')`;
|
|
1809
|
+
}
|
|
1210
1810
|
function modelKey(modelID, variant) {
|
|
1211
|
-
return `${modelID}
|
|
1811
|
+
return `${modelID}${MODEL_KEY_SEPARATOR}${variant ?? ""}`;
|
|
1212
1812
|
}
|
|
1213
1813
|
function modelLabel(modelID, variant) {
|
|
1214
1814
|
return variant === undefined ? modelID : `${modelID} ${variant}`;
|
|
@@ -1246,24 +1846,24 @@ function rangeWhere(range, column = STEP_TIME) {
|
|
|
1246
1846
|
}
|
|
1247
1847
|
return { where: clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "", params };
|
|
1248
1848
|
}
|
|
1249
|
-
function buildWhere(range, filters, column = STEP_TIME) {
|
|
1849
|
+
function buildWhere(range, filters, column = STEP_TIME, prefix = "") {
|
|
1250
1850
|
const rangeClause = rangeWhere(range, column);
|
|
1251
1851
|
const clauses = rangeClause.where === "" ? [] : [rangeClause.where.slice("WHERE ".length)];
|
|
1252
1852
|
const params = [...rangeClause.params];
|
|
1253
1853
|
if (filters?.modelID !== undefined && filters.modelID !== "") {
|
|
1254
|
-
clauses.push(
|
|
1854
|
+
clauses.push(`${prefix}model_id = ?`);
|
|
1255
1855
|
params.push(filters.modelID);
|
|
1256
1856
|
}
|
|
1257
1857
|
if (filters?.modelKey !== undefined && filters.modelKey !== "") {
|
|
1258
|
-
clauses.push(`${
|
|
1858
|
+
clauses.push(`${modelKeySQL(prefix)} = ?`);
|
|
1259
1859
|
params.push(filters.modelKey);
|
|
1260
1860
|
}
|
|
1261
1861
|
if (filters?.provider !== undefined && filters.provider !== "") {
|
|
1262
|
-
clauses.push(
|
|
1862
|
+
clauses.push(`${prefix}provider_id = ?`);
|
|
1263
1863
|
params.push(filters.provider);
|
|
1264
1864
|
}
|
|
1265
1865
|
if (filters?.sessionID !== undefined && filters.sessionID !== "") {
|
|
1266
|
-
clauses.push(
|
|
1866
|
+
clauses.push(`${prefix}session_id = ?`);
|
|
1267
1867
|
params.push(filters.sessionID);
|
|
1268
1868
|
}
|
|
1269
1869
|
return { where: clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "", params };
|
|
@@ -1279,7 +1879,10 @@ function overview(db, range, filters) {
|
|
|
1279
1879
|
MIN(${STEP_TIME}) AS firstAt,
|
|
1280
1880
|
MAX(COALESCE(completed_at, ${STEP_TIME})) AS lastAt,
|
|
1281
1881
|
COALESCE(SUM(CASE WHEN streamed_at > created_at THEN output_tokens + reasoning_tokens ELSE 0 END), 0) AS produced,
|
|
1282
|
-
COALESCE(SUM(CASE WHEN streamed_at > created_at THEN streamed_at - created_at ELSE 0 END), 0) AS window
|
|
1882
|
+
COALESCE(SUM(CASE WHEN streamed_at > created_at THEN streamed_at - created_at ELSE 0 END), 0) AS window,
|
|
1883
|
+
COALESCE(SUM(CASE WHEN streamed_at > COALESCE(first_token_at, created_at) THEN output_tokens + reasoning_tokens ELSE 0 END), 0) AS decodeProduced,
|
|
1884
|
+
COALESCE(SUM(CASE WHEN streamed_at > COALESCE(first_token_at, created_at)
|
|
1885
|
+
THEN streamed_at - COALESCE(first_token_at, created_at) ELSE 0 END), 0) AS decodeWindow
|
|
1283
1886
|
FROM steps ${steps.where}`).get(...steps.params);
|
|
1284
1887
|
const prompts = rangeWhere(range, "created_at");
|
|
1285
1888
|
const promptClauses = prompts.where === "" ? [] : [prompts.where.slice("WHERE ".length)];
|
|
@@ -1290,6 +1893,10 @@ function overview(db, range, filters) {
|
|
|
1290
1893
|
}
|
|
1291
1894
|
const promptWhere = promptClauses.length > 0 ? `WHERE ${promptClauses.join(" AND ")}` : "";
|
|
1292
1895
|
const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${promptWhere}`).get(...promptParams);
|
|
1896
|
+
const ttftFilter = steps.where === "" ? "WHERE" : `${steps.where} AND`;
|
|
1897
|
+
const ttftRows = db.query(`SELECT MAX(0, first_token_at - created_at) AS ttft
|
|
1898
|
+
FROM steps ${ttftFilter} created_at IS NOT NULL AND first_token_at IS NOT NULL`).all(...steps.params);
|
|
1899
|
+
const ttft = ttftRows.length === 0 ? undefined : percentile(ttftRows.map((entry) => entry.ttft), 50);
|
|
1293
1900
|
const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
|
|
1294
1901
|
const other = otherUsage(db, range, filters);
|
|
1295
1902
|
return {
|
|
@@ -1301,7 +1908,9 @@ function overview(db, range, filters) {
|
|
|
1301
1908
|
firstAt: row?.firstAt ?? undefined,
|
|
1302
1909
|
lastAt: row?.lastAt ?? undefined,
|
|
1303
1910
|
cacheHitRatio: cacheHitRatio(usage),
|
|
1304
|
-
tps: row === null ? undefined : tokensPerSecond(row.
|
|
1911
|
+
tps: row === null ? undefined : tokensPerSecond(row.decodeProduced ?? 0, 0, row.decodeWindow ?? 0),
|
|
1912
|
+
requestTps: row === null ? undefined : tokensPerSecond(row.produced ?? 0, 0, row.window ?? 0),
|
|
1913
|
+
ttft
|
|
1305
1914
|
};
|
|
1306
1915
|
}
|
|
1307
1916
|
function models(db, range, filters) {
|
|
@@ -1370,7 +1979,7 @@ function sessions(db, options) {
|
|
|
1370
1979
|
if (options?.sessionIDs !== undefined && options.sessionIDs.length === 0)
|
|
1371
1980
|
return [];
|
|
1372
1981
|
const range = options?.range;
|
|
1373
|
-
const filter = buildWhere(range, options?.filters, "COALESCE(st.created_at, st.recorded_at)");
|
|
1982
|
+
const filter = buildWhere(range, options?.filters, "COALESCE(st.created_at, st.recorded_at)", "st.");
|
|
1374
1983
|
const limit = options?.limit ?? 20;
|
|
1375
1984
|
const clauses = filter.where === "" ? [] : [filter.where.slice("WHERE ".length)];
|
|
1376
1985
|
const params = [...filter.params];
|
|
@@ -1434,8 +2043,8 @@ function sessions(db, options) {
|
|
|
1434
2043
|
function childSessionIDs(db, parentID) {
|
|
1435
2044
|
return db.query("SELECT session_id FROM sessions WHERE parent_id = ? ORDER BY session_id").all(parentID).map((row) => row.session_id);
|
|
1436
2045
|
}
|
|
1437
|
-
function sessionUsageOf(db, sessionIDs) {
|
|
1438
|
-
return sessions(db, { sessionIDs, limit: sessionIDs.length });
|
|
2046
|
+
function sessionUsageOf(db, sessionIDs, filters) {
|
|
2047
|
+
return sessions(db, { sessionIDs, limit: sessionIDs.length, filters });
|
|
1439
2048
|
}
|
|
1440
2049
|
function turnFinished(finish) {
|
|
1441
2050
|
return finish !== null && finish !== "" && finish !== "tool-calls";
|
|
@@ -1456,7 +2065,11 @@ function stepMessage(row) {
|
|
|
1456
2065
|
return {
|
|
1457
2066
|
type: "assistant",
|
|
1458
2067
|
id: row.message_id,
|
|
1459
|
-
time: {
|
|
2068
|
+
time: {
|
|
2069
|
+
created: row.created_at ?? row.recorded_at,
|
|
2070
|
+
firstToken: row.first_token_at ?? undefined,
|
|
2071
|
+
completed: row.completed_at ?? undefined
|
|
2072
|
+
},
|
|
1460
2073
|
model: row.provider_id !== null && row.model_id !== null ? { providerID: row.provider_id, id: row.model_id, variant: row.variant ?? undefined } : undefined,
|
|
1461
2074
|
tokens: {
|
|
1462
2075
|
input: row.input_tokens ?? 0,
|
|
@@ -1486,362 +2099,137 @@ function turns(db, options) {
|
|
|
1486
2099
|
params.push(floor);
|
|
1487
2100
|
}
|
|
1488
2101
|
const steps = db.query(`SELECT message_id, session_id, provider_id, model_id, variant,
|
|
1489
|
-
input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,
|
|
1490
|
-
created_at, streamed_at, recorded_at, completed_at, finish
|
|
1491
|
-
FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
|
|
1492
|
-
ORDER BY session_id, ${STEP_TIME}, message_id`).all(...params);
|
|
1493
|
-
const promptClause = options?.sessionID === undefined ? "" : `WHERE session_id = ?${floor === undefined ? "" : " AND created_at >= ?"}`;
|
|
1494
|
-
const promptParams = options?.sessionID === undefined ? [] : floor === undefined ? [options.sessionID] : [options.sessionID, floor];
|
|
1495
|
-
const promptRows = db.query(`SELECT session_id, created_at FROM prompts ${promptClause} ORDER BY session_id, created_at`).all(...promptParams);
|
|
1496
|
-
const promptsBySession = new Map;
|
|
1497
|
-
for (const row of promptRows) {
|
|
1498
|
-
if (row.created_at === null)
|
|
1499
|
-
continue;
|
|
1500
|
-
const list = promptsBySession.get(row.session_id) ?? [];
|
|
1501
|
-
list.push(row.created_at);
|
|
1502
|
-
promptsBySession.set(row.session_id, list);
|
|
1503
|
-
}
|
|
1504
|
-
const result = [];
|
|
1505
|
-
let sessionID;
|
|
1506
|
-
let bucket = [];
|
|
1507
|
-
let promptIndex = -2;
|
|
1508
|
-
let promptAt;
|
|
1509
|
-
function close() {
|
|
1510
|
-
const last = bucket[bucket.length - 1];
|
|
1511
|
-
if (last === undefined || !turnFinished(last.finish)) {
|
|
1512
|
-
bucket = [];
|
|
1513
|
-
return;
|
|
1514
|
-
}
|
|
1515
|
-
const totals = emptyUsage();
|
|
1516
|
-
for (const row of bucket)
|
|
1517
|
-
addUsage(totals, stepUsage(row));
|
|
1518
|
-
const drops = [];
|
|
1519
|
-
let reference;
|
|
1520
|
-
for (const row of bucket) {
|
|
1521
|
-
const message = stepMessage(row);
|
|
1522
|
-
const drop = cacheDrop(reference, message);
|
|
1523
|
-
if (drop !== undefined) {
|
|
1524
|
-
drops.push({ messageID: row.message_id, tokens: drop, gapMs: stepGap(reference, message) });
|
|
1525
|
-
}
|
|
1526
|
-
reference = message;
|
|
1527
|
-
}
|
|
1528
|
-
const providerID = last.provider_id ?? undefined;
|
|
1529
|
-
const modelID = last.model_id ?? undefined;
|
|
1530
|
-
const variant = last.variant ?? undefined;
|
|
1531
|
-
let produced = 0;
|
|
1532
|
-
let window = 0;
|
|
1533
|
-
for (const row of bucket) {
|
|
1534
|
-
if (row.created_at === null || row.streamed_at === null || row.streamed_at <= row.created_at)
|
|
1535
|
-
continue;
|
|
1536
|
-
produced += (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0);
|
|
1537
|
-
window += row.streamed_at - row.created_at;
|
|
1538
|
-
}
|
|
1539
|
-
const previous = result.length > 0 && result[result.length - 1].sessionID === last.session_id ? result[result.length - 1] : undefined;
|
|
1540
|
-
const endAt = last.completed_at ?? last.created_at ?? last.recorded_at;
|
|
1541
|
-
const firstAt = bucket[0]?.created_at ?? promptAt;
|
|
1542
|
-
result.push({
|
|
1543
|
-
sessionID: last.session_id,
|
|
1544
|
-
promptAt,
|
|
1545
|
-
endAt,
|
|
1546
|
-
durationMs: firstAt !== undefined && endAt > firstAt ? endAt - firstAt : undefined,
|
|
1547
|
-
promptGapMs: promptAt !== undefined && previous?.promptAt !== undefined ? Math.max(0, promptAt - previous.promptAt) : undefined,
|
|
1548
|
-
providerID,
|
|
1549
|
-
modelID,
|
|
1550
|
-
variant,
|
|
1551
|
-
providerChanged: previous?.providerID !== undefined && providerID !== undefined && previous.providerID !== providerID,
|
|
1552
|
-
modelChanged: previous !== undefined && previous.providerID === providerID && `${previous.modelID ?? ""}#${previous.variant ?? ""}` !== `${modelID ?? ""}#${variant ?? ""}`,
|
|
1553
|
-
steps: bucket.length,
|
|
1554
|
-
latest: stepUsage(last),
|
|
1555
|
-
totals,
|
|
1556
|
-
drops,
|
|
1557
|
-
finish: last.finish ?? undefined,
|
|
1558
|
-
tps: tokensPerSecond(produced, 0, window)
|
|
1559
|
-
});
|
|
1560
|
-
bucket = [];
|
|
1561
|
-
}
|
|
1562
|
-
for (const row of steps) {
|
|
1563
|
-
if (row.session_id !== sessionID) {
|
|
1564
|
-
close();
|
|
1565
|
-
sessionID = row.session_id;
|
|
1566
|
-
promptIndex = -2;
|
|
1567
|
-
promptAt = undefined;
|
|
1568
|
-
}
|
|
1569
|
-
const time = row.created_at ?? row.recorded_at;
|
|
1570
|
-
const prompts = promptsBySession.get(row.session_id) ?? [];
|
|
1571
|
-
let index = -1;
|
|
1572
|
-
for (let candidate = prompts.length - 1;candidate >= 0; candidate -= 1) {
|
|
1573
|
-
if ((prompts[candidate] ?? Number.POSITIVE_INFINITY) <= time) {
|
|
1574
|
-
index = candidate;
|
|
1575
|
-
break;
|
|
1576
|
-
}
|
|
1577
|
-
}
|
|
1578
|
-
if (index !== promptIndex) {
|
|
1579
|
-
close();
|
|
1580
|
-
promptIndex = index;
|
|
1581
|
-
promptAt = index >= 0 ? prompts[index] : undefined;
|
|
1582
|
-
}
|
|
1583
|
-
bucket.push(row);
|
|
1584
|
-
}
|
|
1585
|
-
close();
|
|
1586
|
-
const reachedRangeStart = options?.range?.from !== undefined && floor !== undefined && floor <= options.range.from;
|
|
1587
|
-
return { rows: result.reverse(), complete: floor === undefined || reachedRangeStart };
|
|
1588
|
-
}
|
|
1589
|
-
let promptCount = Math.max(1, limit + 1);
|
|
1590
|
-
for (;; ) {
|
|
1591
|
-
const { rows, complete } = read(promptCount);
|
|
1592
|
-
if (rows.length >= limit || complete)
|
|
1593
|
-
return rows.slice(0, limit);
|
|
1594
|
-
const next = promptCount * 2 + 1;
|
|
1595
|
-
if (!Number.isFinite(next) || next <= promptCount)
|
|
1596
|
-
return rows.slice(0, limit);
|
|
1597
|
-
promptCount = next;
|
|
1598
|
-
}
|
|
1599
|
-
}
|
|
1600
|
-
function promptFloor(db, sessionID, count) {
|
|
1601
|
-
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);
|
|
1602
|
-
return rows.length === count ? rows[count - 1].created_at : undefined;
|
|
1603
|
-
}
|
|
1604
|
-
function filterOptions(db) {
|
|
1605
|
-
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 }));
|
|
1606
|
-
return { models: pick("model_id"), providers: pick("provider_id") };
|
|
1607
|
-
}
|
|
1608
|
-
|
|
1609
|
-
// src/recorder.ts
|
|
1610
|
-
function createRecorder(db, options) {
|
|
1611
|
-
const MAX_TRACKED_SESSIONS = 512;
|
|
1612
|
-
const MAX_PENDING = 256;
|
|
1613
|
-
const pending = new Map;
|
|
1614
|
-
const lastModel = new Map;
|
|
1615
|
-
const now = options?.now ?? (() => Date.now());
|
|
1616
|
-
const MAX_DEFERRED = 256;
|
|
1617
|
-
const deferred = [];
|
|
1618
|
-
function isBusy(error) {
|
|
1619
|
-
const code = error?.code;
|
|
1620
|
-
return code === "SQLITE_BUSY" || code === "SQLITE_LOCKED";
|
|
1621
|
-
}
|
|
1622
|
-
function enqueue(run) {
|
|
1623
|
-
if (deferred.length >= MAX_DEFERRED)
|
|
1624
|
-
deferred.shift();
|
|
1625
|
-
deferred.push(run);
|
|
1626
|
-
}
|
|
1627
|
-
function flushDeferred() {
|
|
1628
|
-
while (deferred.length > 0) {
|
|
1629
|
-
const next = deferred[0];
|
|
1630
|
-
try {
|
|
1631
|
-
next();
|
|
1632
|
-
} catch {
|
|
1633
|
-
return;
|
|
1634
|
-
}
|
|
1635
|
-
deferred.shift();
|
|
1636
|
-
}
|
|
1637
|
-
}
|
|
1638
|
-
function write(run) {
|
|
1639
|
-
if (deferred.length > 0) {
|
|
1640
|
-
flushDeferred();
|
|
1641
|
-
if (deferred.length > 0) {
|
|
1642
|
-
enqueue(run);
|
|
1643
|
-
return;
|
|
1644
|
-
}
|
|
1645
|
-
}
|
|
1646
|
-
try {
|
|
1647
|
-
run();
|
|
1648
|
-
} catch (error) {
|
|
1649
|
-
if (isBusy(error))
|
|
1650
|
-
enqueue(run);
|
|
1651
|
-
}
|
|
1652
|
-
}
|
|
1653
|
-
function remember(map, key, value, limit) {
|
|
1654
|
-
map.delete(key);
|
|
1655
|
-
map.set(key, value);
|
|
1656
|
-
while (map.size > limit) {
|
|
1657
|
-
const oldest = map.keys().next();
|
|
1658
|
-
if (oldest.done === true)
|
|
1659
|
-
break;
|
|
1660
|
-
map.delete(oldest.value);
|
|
1661
|
-
}
|
|
1662
|
-
}
|
|
1663
|
-
function forget(sessionID) {
|
|
1664
|
-
lastModel.delete(sessionID);
|
|
1665
|
-
for (const [messageID, step] of pending) {
|
|
1666
|
-
if (step.sessionID === sessionID)
|
|
1667
|
-
pending.delete(messageID);
|
|
1668
|
-
}
|
|
1669
|
-
}
|
|
1670
|
-
function recordPendingStep(messageID, data, finish, at) {
|
|
1671
|
-
const sessionID = data.sessionID;
|
|
1672
|
-
if (typeof sessionID !== "string")
|
|
1673
|
-
return;
|
|
1674
|
-
const info = pending.get(messageID);
|
|
1675
|
-
pending.delete(messageID);
|
|
1676
|
-
const model = info?.model ?? lastModel.get(sessionID);
|
|
1677
|
-
const charged = data.cost;
|
|
1678
|
-
const estimate = charged !== undefined && charged > 0 ? undefined : options?.price?.({ providerID: model?.providerID, modelID: model?.id }, {
|
|
1679
|
-
input: data.tokens?.input,
|
|
1680
|
-
output: data.tokens?.output,
|
|
1681
|
-
reasoning: data.tokens?.reasoning,
|
|
1682
|
-
cacheRead: data.tokens?.cache?.read,
|
|
1683
|
-
cacheWrite: data.tokens?.cache?.write
|
|
1684
|
-
});
|
|
1685
|
-
write(() => recordStep(db, {
|
|
1686
|
-
messageID,
|
|
1687
|
-
sessionID,
|
|
1688
|
-
providerID: model?.providerID,
|
|
1689
|
-
modelID: model?.id,
|
|
1690
|
-
variant: model?.variant,
|
|
1691
|
-
input: data.tokens?.input,
|
|
1692
|
-
output: data.tokens?.output,
|
|
1693
|
-
reasoning: data.tokens?.reasoning,
|
|
1694
|
-
cacheRead: data.tokens?.cache?.read,
|
|
1695
|
-
cacheWrite: data.tokens?.cache?.write,
|
|
1696
|
-
cost: data.cost,
|
|
1697
|
-
listCost: estimate !== undefined && Number.isFinite(estimate) && estimate >= 0 ? estimate : undefined,
|
|
1698
|
-
createdAt: info?.started,
|
|
1699
|
-
streamedAt: info?.streamed,
|
|
1700
|
-
completedAt: at,
|
|
1701
|
-
finish,
|
|
1702
|
-
recordedAt: now()
|
|
1703
|
-
}));
|
|
1704
|
-
}
|
|
1705
|
-
function handleEvent(event) {
|
|
1706
|
-
if (deferred.length > 0)
|
|
1707
|
-
flushDeferred();
|
|
1708
|
-
const data = event.data ?? {};
|
|
1709
|
-
const at = typeof event.created === "number" ? event.created : now();
|
|
1710
|
-
const sessionID = typeof data.sessionID === "string" ? data.sessionID : undefined;
|
|
1711
|
-
switch (event.type) {
|
|
1712
|
-
case "session.created": {
|
|
1713
|
-
if (sessionID === undefined)
|
|
1714
|
-
return;
|
|
1715
|
-
write(() => upsertSession(db, {
|
|
1716
|
-
sessionID,
|
|
1717
|
-
parentID: data.parentID,
|
|
1718
|
-
directory: data.location?.directory,
|
|
1719
|
-
title: data.title,
|
|
1720
|
-
startedAt: at,
|
|
1721
|
-
updatedAt: at
|
|
1722
|
-
}));
|
|
1723
|
-
if (data.model !== undefined)
|
|
1724
|
-
remember(lastModel, sessionID, data.model, MAX_TRACKED_SESSIONS);
|
|
1725
|
-
return;
|
|
1726
|
-
}
|
|
1727
|
-
case "session.deleted": {
|
|
1728
|
-
if (sessionID !== undefined)
|
|
1729
|
-
forget(sessionID);
|
|
1730
|
-
return;
|
|
1731
|
-
}
|
|
1732
|
-
case "session.renamed": {
|
|
1733
|
-
if (sessionID === undefined)
|
|
1734
|
-
return;
|
|
1735
|
-
write(() => upsertSession(db, { sessionID, title: data.title, updatedAt: at }));
|
|
1736
|
-
return;
|
|
1737
|
-
}
|
|
1738
|
-
case "session.moved": {
|
|
1739
|
-
if (sessionID === undefined)
|
|
1740
|
-
return;
|
|
1741
|
-
write(() => upsertSession(db, { sessionID, directory: data.location?.directory, updatedAt: at }));
|
|
1742
|
-
return;
|
|
1743
|
-
}
|
|
1744
|
-
case "session.inbox.enqueued": {
|
|
1745
|
-
if (sessionID === undefined)
|
|
1746
|
-
return;
|
|
1747
|
-
if (data.item?.type !== "user" && data.item?.type !== "synthetic")
|
|
1748
|
-
return;
|
|
1749
|
-
const inboxID = data.inboxID;
|
|
1750
|
-
if (typeof inboxID !== "string")
|
|
1751
|
-
return;
|
|
1752
|
-
write(() => recordPrompt(db, { sessionID, messageID: inboxID, createdAt: at }));
|
|
1753
|
-
return;
|
|
1754
|
-
}
|
|
1755
|
-
case "session.model.selected": {
|
|
1756
|
-
if (sessionID !== undefined && data.model !== undefined)
|
|
1757
|
-
remember(lastModel, sessionID, data.model, MAX_TRACKED_SESSIONS);
|
|
1758
|
-
return;
|
|
1759
|
-
}
|
|
1760
|
-
case "session.step.started": {
|
|
1761
|
-
if (sessionID === undefined || typeof data.assistantMessageID !== "string")
|
|
1762
|
-
return;
|
|
1763
|
-
remember(pending, data.assistantMessageID, {
|
|
1764
|
-
messageID: data.assistantMessageID,
|
|
1765
|
-
sessionID,
|
|
1766
|
-
started: typeof data.started === "number" ? data.started : undefined,
|
|
1767
|
-
streamed: undefined,
|
|
1768
|
-
model: data.model
|
|
1769
|
-
}, MAX_PENDING);
|
|
2102
|
+
input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,
|
|
2103
|
+
created_at, first_token_at, streamed_at, recorded_at, completed_at, finish
|
|
2104
|
+
FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
|
|
2105
|
+
ORDER BY session_id, ${STEP_TIME}, message_id`).all(...params);
|
|
2106
|
+
const promptClause = options?.sessionID === undefined ? "" : `WHERE session_id = ?${floor === undefined ? "" : " AND created_at >= ?"}`;
|
|
2107
|
+
const promptParams = options?.sessionID === undefined ? [] : floor === undefined ? [options.sessionID] : [options.sessionID, floor];
|
|
2108
|
+
const promptRows = db.query(`SELECT session_id, created_at FROM prompts ${promptClause} ORDER BY session_id, created_at`).all(...promptParams);
|
|
2109
|
+
const promptsBySession = new Map;
|
|
2110
|
+
for (const row of promptRows) {
|
|
2111
|
+
if (row.created_at === null)
|
|
2112
|
+
continue;
|
|
2113
|
+
const list = promptsBySession.get(row.session_id) ?? [];
|
|
2114
|
+
list.push(row.created_at);
|
|
2115
|
+
promptsBySession.set(row.session_id, list);
|
|
2116
|
+
}
|
|
2117
|
+
const result = [];
|
|
2118
|
+
let sessionID;
|
|
2119
|
+
let bucket = [];
|
|
2120
|
+
let promptIndex = -2;
|
|
2121
|
+
let promptAt;
|
|
2122
|
+
function close() {
|
|
2123
|
+
const last = bucket[bucket.length - 1];
|
|
2124
|
+
if (last === undefined || !turnFinished(last.finish)) {
|
|
2125
|
+
bucket = [];
|
|
1770
2126
|
return;
|
|
1771
2127
|
}
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
2128
|
+
const totals = emptyUsage();
|
|
2129
|
+
for (const row of bucket)
|
|
2130
|
+
addUsage(totals, stepUsage(row));
|
|
2131
|
+
const drops = [];
|
|
2132
|
+
let reference;
|
|
2133
|
+
for (const row of bucket) {
|
|
2134
|
+
const message = stepMessage(row);
|
|
2135
|
+
const drop = cacheDrop(reference, message);
|
|
2136
|
+
if (drop !== undefined) {
|
|
2137
|
+
drops.push({ messageID: row.message_id, tokens: drop, gapMs: stepGap(reference, message) });
|
|
2138
|
+
}
|
|
2139
|
+
reference = message;
|
|
1779
2140
|
}
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
2141
|
+
const providerID = last.provider_id ?? undefined;
|
|
2142
|
+
const modelID = last.model_id ?? undefined;
|
|
2143
|
+
const variant = last.variant ?? undefined;
|
|
2144
|
+
let produced = 0;
|
|
2145
|
+
let window = 0;
|
|
2146
|
+
let decodeProduced = 0;
|
|
2147
|
+
let decodeWindow = 0;
|
|
2148
|
+
for (const row of bucket) {
|
|
2149
|
+
const tokens = (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0);
|
|
2150
|
+
if (row.created_at !== null && row.streamed_at !== null && row.streamed_at > row.created_at) {
|
|
2151
|
+
produced += tokens;
|
|
2152
|
+
window += row.streamed_at - row.created_at;
|
|
2153
|
+
}
|
|
2154
|
+
const start = row.first_token_at ?? row.created_at;
|
|
2155
|
+
if (start !== null && row.streamed_at !== null && row.streamed_at > start) {
|
|
2156
|
+
decodeProduced += tokens;
|
|
2157
|
+
decodeWindow += row.streamed_at - start;
|
|
2158
|
+
}
|
|
1785
2159
|
}
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
2160
|
+
const first = bucket[0];
|
|
2161
|
+
const ttft = first !== undefined && first.created_at !== null && first.first_token_at !== null ? Math.max(0, first.first_token_at - first.created_at) : undefined;
|
|
2162
|
+
const previous = result.length > 0 && result[result.length - 1].sessionID === last.session_id ? result[result.length - 1] : undefined;
|
|
2163
|
+
const endAt = last.completed_at ?? last.created_at ?? last.recorded_at;
|
|
2164
|
+
const firstAt = bucket[0]?.created_at ?? promptAt;
|
|
2165
|
+
result.push({
|
|
2166
|
+
sessionID: last.session_id,
|
|
2167
|
+
promptAt,
|
|
2168
|
+
endAt,
|
|
2169
|
+
durationMs: firstAt !== undefined && endAt > firstAt ? endAt - firstAt : undefined,
|
|
2170
|
+
promptGapMs: promptAt !== undefined && previous?.promptAt !== undefined ? Math.max(0, promptAt - previous.promptAt) : undefined,
|
|
2171
|
+
providerID,
|
|
2172
|
+
modelID,
|
|
2173
|
+
variant,
|
|
2174
|
+
providerChanged: previous?.providerID !== undefined && providerID !== undefined && previous.providerID !== providerID,
|
|
2175
|
+
modelChanged: previous !== undefined && previous.providerID === providerID && `${previous.modelID ?? ""}#${previous.variant ?? ""}` !== `${modelID ?? ""}#${variant ?? ""}`,
|
|
2176
|
+
steps: bucket.length,
|
|
2177
|
+
latest: stepUsage(last),
|
|
2178
|
+
totals,
|
|
2179
|
+
drops,
|
|
2180
|
+
finish: last.finish ?? undefined,
|
|
2181
|
+
tps: tokensPerSecond(decodeProduced, 0, decodeWindow),
|
|
2182
|
+
requestTps: tokensPerSecond(produced, 0, window),
|
|
2183
|
+
ttft
|
|
2184
|
+
});
|
|
2185
|
+
bucket = [];
|
|
2186
|
+
}
|
|
2187
|
+
for (const row of steps) {
|
|
2188
|
+
if (row.session_id !== sessionID) {
|
|
2189
|
+
close();
|
|
2190
|
+
sessionID = row.session_id;
|
|
2191
|
+
promptIndex = -2;
|
|
2192
|
+
promptAt = undefined;
|
|
1791
2193
|
}
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
if (
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
id,
|
|
1801
|
-
sessionID,
|
|
1802
|
-
source,
|
|
1803
|
-
at,
|
|
1804
|
-
cost: data.cost,
|
|
1805
|
-
input: data.tokens?.input,
|
|
1806
|
-
output: data.tokens?.output,
|
|
1807
|
-
reasoning: data.tokens?.reasoning,
|
|
1808
|
-
cacheRead: data.tokens?.cache?.read,
|
|
1809
|
-
cacheWrite: data.tokens?.cache?.write
|
|
1810
|
-
}));
|
|
1811
|
-
return;
|
|
2194
|
+
const time = row.created_at ?? row.recorded_at;
|
|
2195
|
+
const prompts = promptsBySession.get(row.session_id) ?? [];
|
|
2196
|
+
let index = -1;
|
|
2197
|
+
for (let candidate = prompts.length - 1;candidate >= 0; candidate -= 1) {
|
|
2198
|
+
if ((prompts[candidate] ?? Number.POSITIVE_INFINITY) <= time) {
|
|
2199
|
+
index = candidate;
|
|
2200
|
+
break;
|
|
2201
|
+
}
|
|
1812
2202
|
}
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
write(() => recordEvent(db, {
|
|
1818
|
-
sessionID,
|
|
1819
|
-
kind: COMPACTION_KIND,
|
|
1820
|
-
messageID,
|
|
1821
|
-
at,
|
|
1822
|
-
data: { reason: data.reason, model: data.model, tokens: data.tokens, cost: data.cost }
|
|
1823
|
-
}));
|
|
1824
|
-
return;
|
|
2203
|
+
if (index !== promptIndex) {
|
|
2204
|
+
close();
|
|
2205
|
+
promptIndex = index;
|
|
2206
|
+
promptAt = index >= 0 ? prompts[index] : undefined;
|
|
1825
2207
|
}
|
|
1826
|
-
|
|
1827
|
-
return;
|
|
2208
|
+
bucket.push(row);
|
|
1828
2209
|
}
|
|
2210
|
+
close();
|
|
2211
|
+
const reachedRangeStart = options?.range?.from !== undefined && floor !== undefined && floor <= options.range.from;
|
|
2212
|
+
return { rows: result.reverse(), complete: floor === undefined || reachedRangeStart };
|
|
1829
2213
|
}
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
2214
|
+
let promptCount = Math.max(1, limit + 1);
|
|
2215
|
+
for (;; ) {
|
|
2216
|
+
const { rows, complete } = read(promptCount);
|
|
2217
|
+
if (rows.length >= limit || complete)
|
|
2218
|
+
return rows.slice(0, limit);
|
|
2219
|
+
const next = promptCount * 2 + 1;
|
|
2220
|
+
if (!Number.isFinite(next) || next <= promptCount)
|
|
2221
|
+
return rows.slice(0, limit);
|
|
2222
|
+
promptCount = next;
|
|
1839
2223
|
}
|
|
1840
|
-
return { handleEvent, pendingFor };
|
|
1841
2224
|
}
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
2225
|
+
function promptFloor(db, sessionID, count) {
|
|
2226
|
+
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);
|
|
2227
|
+
return rows.length === count ? rows[count - 1].created_at : undefined;
|
|
2228
|
+
}
|
|
2229
|
+
function filterOptions(db) {
|
|
2230
|
+
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 }));
|
|
2231
|
+
return { models: pick("model_id"), providers: pick("provider_id") };
|
|
2232
|
+
}
|
|
1845
2233
|
|
|
1846
2234
|
// src/stats/aggregates.ts
|
|
1847
2235
|
var STEP_AT = "COALESCE(created_at, recorded_at)";
|
|
@@ -1870,8 +2258,9 @@ var STEP_COLUMNS = `message_id AS messageID, session_id AS sessionID, provider_i
|
|
|
1870
2258
|
COALESCE(input_tokens, 0) AS input, COALESCE(cache_read, 0) AS cached, COALESCE(cache_write, 0) AS cacheWrite,
|
|
1871
2259
|
COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, COALESCE(cost, 0) AS cost,
|
|
1872
2260
|
COALESCE(list_cost, 0) AS listCost,
|
|
1873
|
-
created_at AS createdAt,
|
|
1874
|
-
|
|
2261
|
+
created_at AS createdAt, first_token_at AS firstTokenAt, streamed_at AS streamedAt,
|
|
2262
|
+
completed_at AS completedAt, ${STEP_AT} AS at`;
|
|
2263
|
+
var STEP_OPTIONAL = ["providerID", "modelID", "variant", "createdAt", "firstTokenAt", "streamedAt", "completedAt"];
|
|
1875
2264
|
var PAIR_COLUMNS = STEP_COLUMNS.replace("COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, ", "");
|
|
1876
2265
|
function stepRows(db, options) {
|
|
1877
2266
|
const filter = buildWhere(options?.range, options?.filters);
|
|
@@ -1950,6 +2339,7 @@ function coverageOf(db, options) {
|
|
|
1950
2339
|
COALESCE(SUM(CASE WHEN model_id IS NULL THEN 1 ELSE 0 END), 0) AS missingModel,
|
|
1951
2340
|
COALESCE(SUM(CASE WHEN completed_at IS NOT NULL OR finish IS NOT NULL THEN 0 ELSE 1 END), 0) AS unsettled,
|
|
1952
2341
|
COALESCE(SUM(CASE WHEN (output_tokens + reasoning_tokens) > 0 AND created_at IS NOT NULL AND streamed_at IS NOT NULL AND streamed_at > created_at THEN 0 ELSE 1 END), 0) AS missingTps,
|
|
2342
|
+
COALESCE(SUM(CASE WHEN (output_tokens + reasoning_tokens) > 0 AND created_at IS NOT NULL AND streamed_at IS NOT NULL AND streamed_at > created_at AND first_token_at IS NULL THEN 1 ELSE 0 END), 0) AS missingFirstToken,
|
|
1953
2343
|
MIN(${STEP_AT}) AS firstAt,
|
|
1954
2344
|
MAX(${STEP_AT}) AS lastAt
|
|
1955
2345
|
FROM steps ${filter.where}`).get(...filter.params);
|
|
@@ -1960,6 +2350,7 @@ function coverageOf(db, options) {
|
|
|
1960
2350
|
missingModel: row.missingModel,
|
|
1961
2351
|
unsettled: row.unsettled,
|
|
1962
2352
|
missingTps: row.missingTps,
|
|
2353
|
+
missingFirstToken: row.missingFirstToken,
|
|
1963
2354
|
firstAt: row.firstAt ?? undefined,
|
|
1964
2355
|
lastAt: row.lastAt ?? undefined
|
|
1965
2356
|
};
|
|
@@ -1972,7 +2363,14 @@ function groupedRows(db, options) {
|
|
|
1972
2363
|
function timingOf(step) {
|
|
1973
2364
|
const wall = step.createdAt !== undefined && step.completedAt !== undefined ? Math.max(0, step.completedAt - step.createdAt) : undefined;
|
|
1974
2365
|
const stream = step.createdAt !== undefined && step.streamedAt !== undefined && step.streamedAt > step.createdAt ? step.streamedAt - step.createdAt : undefined;
|
|
1975
|
-
|
|
2366
|
+
const ttft = step.createdAt !== undefined && step.firstTokenAt !== undefined ? Math.max(0, step.firstTokenAt - step.createdAt) : undefined;
|
|
2367
|
+
return {
|
|
2368
|
+
wall,
|
|
2369
|
+
stream,
|
|
2370
|
+
ttft,
|
|
2371
|
+
tps: tokensPerSecond(step.output + step.reasoning, step.firstTokenAt ?? step.createdAt, step.streamedAt),
|
|
2372
|
+
requestTps: tokensPerSecond(step.output + step.reasoning, step.createdAt, step.streamedAt)
|
|
2373
|
+
};
|
|
1976
2374
|
}
|
|
1977
2375
|
function timingRows(db, options) {
|
|
1978
2376
|
return groupedRows(db, options);
|
|
@@ -1980,17 +2378,29 @@ function timingRows(db, options) {
|
|
|
1980
2378
|
function latencyOf(rows) {
|
|
1981
2379
|
const wall = [];
|
|
1982
2380
|
const stream = [];
|
|
2381
|
+
const ttft = [];
|
|
1983
2382
|
const tps = [];
|
|
2383
|
+
const requestTps = [];
|
|
1984
2384
|
for (const step of rows) {
|
|
1985
2385
|
const timing = timingOf(step);
|
|
1986
2386
|
if (timing.wall !== undefined)
|
|
1987
2387
|
wall.push(timing.wall);
|
|
1988
2388
|
if (timing.stream !== undefined)
|
|
1989
2389
|
stream.push(timing.stream);
|
|
2390
|
+
if (timing.ttft !== undefined)
|
|
2391
|
+
ttft.push(timing.ttft);
|
|
1990
2392
|
if (timing.tps !== undefined)
|
|
1991
2393
|
tps.push(timing.tps);
|
|
2394
|
+
if (timing.requestTps !== undefined)
|
|
2395
|
+
requestTps.push(timing.requestTps);
|
|
1992
2396
|
}
|
|
1993
|
-
return {
|
|
2397
|
+
return {
|
|
2398
|
+
wall: latencyStats(wall),
|
|
2399
|
+
stream: latencyStats(stream),
|
|
2400
|
+
ttft: latencyStats(ttft),
|
|
2401
|
+
tps: latencyStats(tps),
|
|
2402
|
+
requestTps: latencyStats(requestTps)
|
|
2403
|
+
};
|
|
1994
2404
|
}
|
|
1995
2405
|
function latencyGroupsOf(rows, by) {
|
|
1996
2406
|
const key = (step) => by === "model" ? modelKey(step.modelID ?? "(unknown)", step.variant) : step.providerID ?? "(unknown)";
|
|
@@ -1998,25 +2408,33 @@ function latencyGroupsOf(rows, by) {
|
|
|
1998
2408
|
for (const [group, steps] of groupBy(rows, key)) {
|
|
1999
2409
|
const wall = [];
|
|
2000
2410
|
const stream = [];
|
|
2411
|
+
const ttft = [];
|
|
2001
2412
|
const tps = [];
|
|
2413
|
+
const requestTps = [];
|
|
2002
2414
|
for (const step of steps) {
|
|
2003
2415
|
const timing = timingOf(step);
|
|
2004
2416
|
if (timing.wall !== undefined)
|
|
2005
2417
|
wall.push(timing.wall);
|
|
2006
2418
|
if (timing.stream !== undefined)
|
|
2007
2419
|
stream.push(timing.stream);
|
|
2420
|
+
if (timing.ttft !== undefined)
|
|
2421
|
+
ttft.push(timing.ttft);
|
|
2008
2422
|
if (timing.tps !== undefined)
|
|
2009
2423
|
tps.push(timing.tps);
|
|
2424
|
+
if (timing.requestTps !== undefined)
|
|
2425
|
+
requestTps.push(timing.requestTps);
|
|
2010
2426
|
}
|
|
2011
|
-
const
|
|
2427
|
+
const { modelID, variant } = splitModelKey(group);
|
|
2012
2428
|
groups.push({
|
|
2013
2429
|
key: group,
|
|
2014
|
-
label: by === "model" ? variant === undefined
|
|
2430
|
+
label: by === "model" ? variant === undefined ? modelID : `${modelID} ${variant}` : group,
|
|
2015
2431
|
count: steps.length,
|
|
2016
2432
|
usage: usageOf(steps),
|
|
2017
2433
|
wall: latencyStats(wall),
|
|
2018
2434
|
stream: latencyStats(stream),
|
|
2019
|
-
|
|
2435
|
+
ttft: latencyStats(ttft),
|
|
2436
|
+
tps: latencyStats(tps),
|
|
2437
|
+
requestTps: latencyStats(requestTps)
|
|
2020
2438
|
});
|
|
2021
2439
|
}
|
|
2022
2440
|
return groups.sort((left, right) => right.count - left.count || left.key.localeCompare(right.key));
|
|
@@ -2196,21 +2614,21 @@ function cacheDropsOf(db, rows, options) {
|
|
|
2196
2614
|
}
|
|
2197
2615
|
if (losses.length === 0)
|
|
2198
2616
|
return [];
|
|
2199
|
-
const
|
|
2617
|
+
const times = new Map;
|
|
2200
2618
|
const sessionIDs = [...new Set(losses.map((loss) => loss.current.sessionID))];
|
|
2201
|
-
const
|
|
2202
|
-
WHERE
|
|
2619
|
+
const timeline = db.query(`SELECT session_id, at FROM compactions
|
|
2620
|
+
WHERE at IS NOT NULL AND session_id IN (${sessionIDs.map(() => "?").join(", ")})
|
|
2203
2621
|
ORDER BY at`).all(...sessionIDs);
|
|
2204
|
-
for (const
|
|
2205
|
-
const list =
|
|
2622
|
+
for (const row of timeline) {
|
|
2623
|
+
const list = times.get(row.session_id);
|
|
2206
2624
|
if (list !== undefined)
|
|
2207
|
-
list.push(
|
|
2625
|
+
list.push(row.at);
|
|
2208
2626
|
else
|
|
2209
|
-
|
|
2627
|
+
times.set(row.session_id, [row.at]);
|
|
2210
2628
|
}
|
|
2211
2629
|
return losses.map((loss) => {
|
|
2212
2630
|
const ended = loss.previous.completedAt ?? loss.previous.streamedAt ?? loss.previous.createdAt;
|
|
2213
|
-
const compacted = (
|
|
2631
|
+
const compacted = (times.get(loss.current.sessionID) ?? []).some((time) => ended !== undefined && time >= ended && time <= loss.current.at);
|
|
2214
2632
|
const reason = compacted ? "compaction" : loss.gapMs !== undefined && loss.gapMs >= ttlHint ? "expired" : "unknown";
|
|
2215
2633
|
return {
|
|
2216
2634
|
sessionID: loss.current.sessionID,
|
|
@@ -2229,14 +2647,34 @@ function cacheDropsOf(db, rows, options) {
|
|
|
2229
2647
|
function groupValues(steps) {
|
|
2230
2648
|
const wall = [];
|
|
2231
2649
|
const tps = [];
|
|
2650
|
+
const requestTps = [];
|
|
2651
|
+
const ttft = [];
|
|
2232
2652
|
for (const step of steps) {
|
|
2233
2653
|
const timing = timingOf(step);
|
|
2234
2654
|
if (timing.wall !== undefined)
|
|
2235
2655
|
wall.push(timing.wall);
|
|
2236
2656
|
if (timing.tps !== undefined)
|
|
2237
2657
|
tps.push(timing.tps);
|
|
2658
|
+
if (timing.requestTps !== undefined)
|
|
2659
|
+
requestTps.push(timing.requestTps);
|
|
2660
|
+
if (timing.ttft !== undefined)
|
|
2661
|
+
ttft.push(timing.ttft);
|
|
2238
2662
|
}
|
|
2239
|
-
return {
|
|
2663
|
+
return {
|
|
2664
|
+
cache: cacheStatsOfSteps(steps),
|
|
2665
|
+
tps: latencyStats(tps).p50,
|
|
2666
|
+
requestTps: latencyStats(requestTps).p50,
|
|
2667
|
+
ttft: latencyStats(ttft).p50,
|
|
2668
|
+
wall: latencyStats(wall).p50
|
|
2669
|
+
};
|
|
2670
|
+
}
|
|
2671
|
+
var MODEL_LIST_SEPARATOR = "\x00";
|
|
2672
|
+
function splitModelKey(key) {
|
|
2673
|
+
const separator = key.indexOf(MODEL_KEY_SEPARATOR);
|
|
2674
|
+
if (separator === -1)
|
|
2675
|
+
return { modelID: key, variant: undefined };
|
|
2676
|
+
const variant = key.slice(separator + 1);
|
|
2677
|
+
return { modelID: key.slice(0, separator), variant: variant === "" ? undefined : variant };
|
|
2240
2678
|
}
|
|
2241
2679
|
function providerOf(steps, models) {
|
|
2242
2680
|
const values = groupValues(steps);
|
|
@@ -2250,17 +2688,22 @@ function providerOf(steps, models) {
|
|
|
2250
2688
|
}
|
|
2251
2689
|
return {
|
|
2252
2690
|
provider: steps[0].providerID,
|
|
2253
|
-
models: models.split(
|
|
2691
|
+
models: models.split(MODEL_LIST_SEPARATOR),
|
|
2254
2692
|
share: 0,
|
|
2255
2693
|
usage: usageOf(steps),
|
|
2256
2694
|
cache: values.cache,
|
|
2257
2695
|
tps: values.tps,
|
|
2696
|
+
requestTps: values.requestTps,
|
|
2697
|
+
ttft: values.ttft,
|
|
2258
2698
|
wall: values.wall,
|
|
2259
2699
|
firstAt,
|
|
2260
2700
|
lastAt
|
|
2261
2701
|
};
|
|
2262
2702
|
}
|
|
2263
|
-
var modelNames = (steps) => [...new Set(steps.map((step) => modelKey(step.modelID ?? "(unknown)", step.variant)))].map((key) =>
|
|
2703
|
+
var modelNames = (steps) => [...new Set(steps.map((step) => modelKey(step.modelID ?? "(unknown)", step.variant)))].map((key) => {
|
|
2704
|
+
const { modelID, variant } = splitModelKey(key);
|
|
2705
|
+
return modelLabel(modelID, variant);
|
|
2706
|
+
}).join(MODEL_LIST_SEPARATOR);
|
|
2264
2707
|
function providerSummaryOf(rows) {
|
|
2265
2708
|
const out = [];
|
|
2266
2709
|
for (const steps of groupBy(rows, (step) => step.providerID ?? "").values()) {
|
|
@@ -2273,7 +2716,7 @@ function providerBreakdownOf(rows) {
|
|
|
2273
2716
|
const out = [];
|
|
2274
2717
|
for (const [model, modelRows] of groupBy(rows, (step) => modelKey(step.modelID ?? "(unknown)", step.variant))) {
|
|
2275
2718
|
for (const steps of groupBy(modelRows, (step) => step.providerID ?? "").values()) {
|
|
2276
|
-
const
|
|
2719
|
+
const { modelID, variant } = splitModelKey(model);
|
|
2277
2720
|
out.push({
|
|
2278
2721
|
...providerOf(steps, modelNames(steps)),
|
|
2279
2722
|
modelID,
|
|
@@ -2479,8 +2922,8 @@ var RANGE_KEYS = ["session", "today", "7d", "30d", "all"];
|
|
|
2479
2922
|
var GRANULARITIES = ["day", "week", "month"];
|
|
2480
2923
|
var SORT_KEYS = {
|
|
2481
2924
|
models: ["steps", "cached", "hit", "out", "cost"],
|
|
2482
|
-
providers: ["steps", "cached", "hit", "cost", "share", "tps"],
|
|
2483
|
-
latency: ["n", "tps", "wall"],
|
|
2925
|
+
providers: ["steps", "cached", "hit", "cost", "share", "tps", "ttft"],
|
|
2926
|
+
latency: ["n", "tps", "ttft", "wall"],
|
|
2484
2927
|
sessions: ["last", "steps", "cached", "cost"],
|
|
2485
2928
|
turns: ["time", "cost", "tokens"]
|
|
2486
2929
|
};
|
|
@@ -2578,10 +3021,10 @@ function formatTps(value) {
|
|
|
2578
3021
|
return "\u2013";
|
|
2579
3022
|
return `${value.toFixed(1)}/s`;
|
|
2580
3023
|
}
|
|
2581
|
-
function
|
|
3024
|
+
function formatRateValue(value) {
|
|
2582
3025
|
if (value === undefined || !Number.isFinite(value) || value < 0)
|
|
2583
3026
|
return "\u2013";
|
|
2584
|
-
return value >= 10 ?
|
|
3027
|
+
return value >= 10 ? String(Math.round(value)) : value.toFixed(1);
|
|
2585
3028
|
}
|
|
2586
3029
|
function formatGap(value) {
|
|
2587
3030
|
if (value === undefined || !Number.isFinite(value))
|
|
@@ -2755,15 +3198,16 @@ function viewBar(view, width = 200, views = CLIENT_VIEWS) {
|
|
|
2755
3198
|
const index = views.indexOf(view);
|
|
2756
3199
|
return { text: `[${index === -1 ? "?" : key(index)} ${view}] \xB7 1-9 0 or [ ] to switch`, tone: "muted" };
|
|
2757
3200
|
}
|
|
2758
|
-
function keysFor(of) {
|
|
3201
|
+
function keysFor(of, range) {
|
|
2759
3202
|
if (of === QUOTA_VIEW)
|
|
2760
3203
|
return "r refresh \xB7 t range \xB7 0 view \xB7 ? help \xB7 the quotas come from OpenCode Go";
|
|
2761
3204
|
if (of === "db")
|
|
2762
3205
|
return "\u2191\u2193 pick a retention \xB7 enter prune \xB7 the last row wipes \xB7 e backfill \xB7 v vacuum \xB7 r refresh \xB7 1-9 0 view \xB7 ? help";
|
|
2763
3206
|
if (of === "periods")
|
|
2764
3207
|
return "\u2191\u2193 move \xB7 enter drill \xB7 b bucket \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
|
|
2765
|
-
if (of === "turns")
|
|
2766
|
-
return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
|
|
3208
|
+
if (of === "turns") {
|
|
3209
|
+
return range === "session" ? "\u2191\u2193 move \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help" : "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
|
|
3210
|
+
}
|
|
2767
3211
|
return "\u2191\u2193 move \xB7 enter drill \xB7 s sort \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
|
|
2768
3212
|
}
|
|
2769
3213
|
function filterSummary(filters) {
|
|
@@ -2785,7 +3229,7 @@ function helpLines(width) {
|
|
|
2785
3229
|
{ text: " t shift+t previous / next range" },
|
|
2786
3230
|
{ text: " s shift+s cycle sort column \xB7 reverse" },
|
|
2787
3231
|
{ text: " b periods bucket: day \u2192 week \u2192 month" },
|
|
2788
|
-
{ text: " a turns scope: this session \u2194 all sessions" },
|
|
3232
|
+
{ text: " a turns scope: this session \u2194 all sessions (time ranges)" },
|
|
2789
3233
|
{ text: " m p filter by model / provider (x clears)" },
|
|
2790
3234
|
{ text: " r re-read the database \xB7 f full screen \xB7 escape close" },
|
|
2791
3235
|
{ text: " e db: backfill list-price estimates for the $0 steps" },
|
|
@@ -2812,7 +3256,11 @@ function helpLines(width) {
|
|
|
2812
3256
|
{ text: " \u2248 list-price estimate for steps the host reported as $0;" },
|
|
2813
3257
|
{ text: " `$0.12 + \u2248 $3.40` keeps charged and estimated money apart" },
|
|
2814
3258
|
{ text: " wall request \u2192 completed step \xB7 stream request \u2192 last chunk" },
|
|
2815
|
-
{ text: "
|
|
3259
|
+
{ text: " ttft request \u2192 first streamed token" },
|
|
3260
|
+
{ text: " tps output+reasoning / first token \u2192 last chunk (OpenCode)" },
|
|
3261
|
+
{ text: " rtps output+reasoning / request \u2192 last chunk (includes TTFT)" },
|
|
3262
|
+
{ text: " turn 200 tps \xB7 2.1s ttft \xB7 cost" },
|
|
3263
|
+
{ text: " session 200 tps \xB7 167 rtps \xB7 ttft p50 \xB7 cost" },
|
|
2816
3264
|
{ text: " switches how often a step's model or provider differs from the step" },
|
|
2817
3265
|
{ text: " before it in the same session (the models view's detail), with" },
|
|
2818
3266
|
{ text: " the cache a provider switch cost" },
|
|
@@ -2941,12 +3389,16 @@ function usagePairs(usage, estimates = true) {
|
|
|
2941
3389
|
];
|
|
2942
3390
|
if (buckets.reasoning > 0)
|
|
2943
3391
|
pairs.push(["reasoning", formatTokens(buckets.reasoning)]);
|
|
3392
|
+
if ("tps" in usage && usage.tps !== undefined)
|
|
3393
|
+
pairs.push(["tps", formatTps(usage.tps)]);
|
|
3394
|
+
if ("requestTps" in usage && usage.requestTps !== undefined)
|
|
3395
|
+
pairs.push(["rtps", formatTps(usage.requestTps)]);
|
|
3396
|
+
if ("ttft" in usage && usage.ttft !== undefined)
|
|
3397
|
+
pairs.push(["ttft p50", formatMs(usage.ttft)]);
|
|
2944
3398
|
pairs.push(["cost", (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost)]);
|
|
2945
3399
|
const other = usage.otherCost ?? 0;
|
|
2946
3400
|
if (other > 0)
|
|
2947
3401
|
pairs.push(["other", `${formatCost(other)} comp/title`]);
|
|
2948
|
-
if ("tps" in usage && usage.tps !== undefined)
|
|
2949
|
-
pairs.push(["tps", formatTps(usage.tps)]);
|
|
2950
3402
|
return pairs;
|
|
2951
3403
|
}
|
|
2952
3404
|
function overviewLines(data, width) {
|
|
@@ -2999,6 +3451,7 @@ function coveragePairs(coverage) {
|
|
|
2999
3451
|
["models", `${formatCount(coverage.models)} \xB7 unknown ${share(coverage.missingModel)}`],
|
|
3000
3452
|
["providers", formatCount(coverage.providers)],
|
|
3001
3453
|
["unsettled", `${formatCount(coverage.unsettled)} \xB7 no tps ${share(coverage.missingTps)}`],
|
|
3454
|
+
["no ttft", share(coverage.missingFirstToken)],
|
|
3002
3455
|
[
|
|
3003
3456
|
"window",
|
|
3004
3457
|
`${coverage.firstAt === undefined ? "\u2013" : new Date(coverage.firstAt).toLocaleString("en-GB")} \u2192 ${coverage.lastAt === undefined ? "\u2013" : new Date(coverage.lastAt).toLocaleString("en-GB")}`
|
|
@@ -3109,7 +3562,8 @@ function providerSummaryLines(rows, width, limit = 40, estimates = true) {
|
|
|
3109
3562
|
{ header: "cached", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
|
|
3110
3563
|
{ header: "hit", width: 6, max: 7, align: "right", priority: 2, cell: (row) => formatPercent(row.cache.hit) },
|
|
3111
3564
|
{ header: "tps p50", width: 8, align: "right", priority: 5, cell: (row) => formatTps(row.tps) },
|
|
3112
|
-
{ header: "
|
|
3565
|
+
{ header: "ttft p50", width: 8, max: 9, align: "right", priority: 6, cell: (row) => formatMs(row.ttft) },
|
|
3566
|
+
{ header: "wall", width: 7, align: "right", priority: 7, cell: (row) => formatMs(row.wall) },
|
|
3113
3567
|
{ header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
|
|
3114
3568
|
], width, {
|
|
3115
3569
|
limit,
|
|
@@ -3129,7 +3583,8 @@ function providerLines(rows, width, limit = 40, estimates = true) {
|
|
|
3129
3583
|
{ header: "cached", width: 7, max: 10, align: "right", priority: 3, cell: (row) => formatTokens(row.cache.cached) },
|
|
3130
3584
|
{ header: "hit", width: 6, max: 7, align: "right", priority: 4, cell: (row) => formatPercent(row.cache.hit) },
|
|
3131
3585
|
{ header: "tps p50", width: 8, align: "right", priority: 6, cell: (row) => formatTps(row.tps) },
|
|
3132
|
-
{ header: "
|
|
3586
|
+
{ header: "ttft p50", width: 8, max: 9, align: "right", priority: 7, cell: (row) => formatMs(row.ttft) },
|
|
3587
|
+
{ header: "wall", width: 7, align: "right", priority: 8, cell: (row) => formatMs(row.wall) },
|
|
3133
3588
|
{ header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
|
|
3134
3589
|
], width, {
|
|
3135
3590
|
limit,
|
|
@@ -3367,7 +3822,15 @@ function latencyLines(report, width, groups, limit = 12, estimates = true) {
|
|
|
3367
3822
|
tone: "base"
|
|
3368
3823
|
});
|
|
3369
3824
|
lines.push({
|
|
3370
|
-
text: formatTableRow(["
|
|
3825
|
+
text: formatTableRow(["ttft", "p50", formatMs(report.ttft.p50), "p90", formatMs(report.ttft.p90), "p99", formatMs(report.ttft.p99)], [10, 4, 9, 4, 9, 4, 9]),
|
|
3826
|
+
tone: "base"
|
|
3827
|
+
});
|
|
3828
|
+
lines.push({
|
|
3829
|
+
text: formatTableRow(["tps", "p50", formatTps(report.tps.p50), "p90", formatTps(report.tps.p90), "p99", formatTps(report.tps.p99)], [10, 4, 9, 4, 9, 4, 9]),
|
|
3830
|
+
tone: "base"
|
|
3831
|
+
});
|
|
3832
|
+
lines.push({
|
|
3833
|
+
text: formatTableRow(["rtps", "p50", formatTps(report.requestTps.p50), "p90", formatTps(report.requestTps.p90), "p99", formatTps(report.requestTps.p99)], [10, 4, 9, 4, 9, 4, 9]),
|
|
3371
3834
|
tone: "base"
|
|
3372
3835
|
});
|
|
3373
3836
|
} else {
|
|
@@ -3380,13 +3843,25 @@ function latencyLines(report, width, groups, limit = 12, estimates = true) {
|
|
|
3380
3843
|
tone: "base"
|
|
3381
3844
|
});
|
|
3382
3845
|
lines.push({
|
|
3383
|
-
text: latencyMetric("
|
|
3846
|
+
text: latencyMetric("ttft", [`p50 ${formatMs(report.ttft.p50)}`, `p90 ${formatMs(report.ttft.p90)}`, `p99 ${formatMs(report.ttft.p99)}`], width),
|
|
3847
|
+
tone: "base"
|
|
3848
|
+
});
|
|
3849
|
+
lines.push({
|
|
3850
|
+
text: latencyMetric("tps", [`p50 ${formatTps(report.tps.p50)}`, `p90 ${formatTps(report.tps.p90)}`, `p99 ${formatTps(report.tps.p99)}`], width),
|
|
3851
|
+
tone: "base"
|
|
3852
|
+
});
|
|
3853
|
+
lines.push({
|
|
3854
|
+
text: latencyMetric("rtps", [`p50 ${formatTps(report.requestTps.p50)}`, `p90 ${formatTps(report.requestTps.p90)}`, `p99 ${formatTps(report.requestTps.p99)}`], width),
|
|
3384
3855
|
tone: "base"
|
|
3385
3856
|
});
|
|
3386
3857
|
}
|
|
3387
3858
|
lines.push({ text: "", tone: "muted" });
|
|
3388
3859
|
lines.push({
|
|
3389
|
-
text: truncate("wall = request to completed \xB7 stream = request to last chunk
|
|
3860
|
+
text: truncate("wall = request to completed \xB7 stream = request to last chunk", width),
|
|
3861
|
+
tone: "muted"
|
|
3862
|
+
});
|
|
3863
|
+
lines.push({
|
|
3864
|
+
text: truncate("ttft = request to first token \xB7 tps = first token to last chunk \xB7 rtps = request to last chunk", width),
|
|
3390
3865
|
tone: "muted"
|
|
3391
3866
|
});
|
|
3392
3867
|
if (report.wall.count === 0)
|
|
@@ -3401,7 +3876,8 @@ function latencyLines(report, width, groups, limit = 12, estimates = true) {
|
|
|
3401
3876
|
{ header: "wall p90", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatMs(row.wall.p90) },
|
|
3402
3877
|
{ header: "stream", width: 6, max: 9, align: "right", priority: 2, cell: (row) => formatMs(row.stream.p50) },
|
|
3403
3878
|
{ header: "tps p50", width: 8, max: 9, align: "right", cell: (row) => formatTps(row.tps.p50) },
|
|
3404
|
-
{ header: "tps p90", width: 8, max: 9, align: "right", priority:
|
|
3879
|
+
{ header: "tps p90", width: 8, max: 9, align: "right", priority: 4, cell: (row) => formatTps(row.tps.p90) },
|
|
3880
|
+
{ header: "ttft p50", width: 8, max: 9, align: "right", priority: 3, cell: (row) => formatMs(row.ttft.p50) },
|
|
3405
3881
|
{ header: "cost", width: 8, max: 9, align: "right", cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
|
|
3406
3882
|
], width);
|
|
3407
3883
|
if (columns.length > 0) {
|
|
@@ -3630,7 +4106,9 @@ function sessionSummaryLines(usage, budget = 34, estimates = true) {
|
|
|
3630
4106
|
const cached = formatTokens(buckets.cached);
|
|
3631
4107
|
const out = formatTokens(buckets.output);
|
|
3632
4108
|
const hit = formatPercent(buckets.hit);
|
|
3633
|
-
const tps =
|
|
4109
|
+
const tps = usage.tps === undefined ? undefined : `${formatRateValue(usage.tps)} tps`;
|
|
4110
|
+
const rtps = usage.requestTps === undefined ? undefined : `${formatRateValue(usage.requestTps)} rtps`;
|
|
4111
|
+
const ttft = usage.ttft === undefined ? undefined : `ttft p50 ${formatMs(usage.ttft)}`;
|
|
3634
4112
|
const cost = (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost);
|
|
3635
4113
|
const first = [
|
|
3636
4114
|
` ${steps} steps \xB7 in ${input}`,
|
|
@@ -3640,16 +4118,22 @@ function sessionSummaryLines(usage, budget = 34, estimates = true) {
|
|
|
3640
4118
|
` cached ${cached} \xB7 out ${out}`,
|
|
3641
4119
|
` cached ${cached}`
|
|
3642
4120
|
].find((text) => text.length <= budget);
|
|
3643
|
-
const
|
|
3644
|
-
|
|
3645
|
-
` hit ${hit} \xB7 ${
|
|
3646
|
-
` ${
|
|
4121
|
+
const rates = [tps, rtps].filter((part) => part !== undefined);
|
|
4122
|
+
const rateLine = [
|
|
4123
|
+
` hit ${hit}${rates.length > 0 ? ` \xB7 ${rates.join(" \xB7 ")}` : ""}`,
|
|
4124
|
+
` hit ${hit}${rates[0] !== undefined ? ` \xB7 ${rates[0]}` : ""}`,
|
|
4125
|
+
` hit ${hit}`
|
|
3647
4126
|
].find((text) => text.length <= budget);
|
|
4127
|
+
const tail = [
|
|
4128
|
+
ttft === undefined ? undefined : ` ${ttft} \xB7 ${cost}`,
|
|
4129
|
+
` ${cost}`
|
|
4130
|
+
].filter((text) => text !== undefined).find((text) => text.length <= budget);
|
|
3648
4131
|
return [
|
|
3649
4132
|
{ text: truncate("session", budget), tone: HEADER_TONE },
|
|
3650
4133
|
{ text: truncate(first ?? ` ${steps} steps`, budget), tone: "muted" },
|
|
3651
4134
|
{ text: truncate(second ?? ` cached ${cached}`, budget), tone: "base" },
|
|
3652
|
-
{ text: truncate(
|
|
4135
|
+
{ text: truncate(rateLine ?? ` hit ${hit}`, budget), tone: "base" },
|
|
4136
|
+
{ text: truncate(tail ?? ` ${cost}`, budget), tone: "base" },
|
|
3653
4137
|
{ text: "", tone: "muted" }
|
|
3654
4138
|
];
|
|
3655
4139
|
}
|
|
@@ -3666,20 +4150,28 @@ function sidebarLines(rows, options) {
|
|
|
3666
4150
|
const output = formatTokens(display.output);
|
|
3667
4151
|
const cost = options?.estimates === false ? formatCost(turn.totals.cost) : formatMoney(turn.totals.cost, turn.totals.listCost) ?? formatCost(turn.totals.cost);
|
|
3668
4152
|
const hit = formatPercent(display.prompt > 0 ? display.cached / display.prompt : undefined).replace(/\.0%$/, "%");
|
|
3669
|
-
const tps = turn.tps === undefined ? undefined :
|
|
4153
|
+
const tps = turn.tps === undefined ? undefined : `${formatRateValue(turn.tps)} tps`;
|
|
4154
|
+
const ttft = turn.ttft === undefined ? undefined : `${formatMs(turn.ttft)} ttft`;
|
|
4155
|
+
const rate = [tps, ttft].filter((part) => part !== undefined).join(" \xB7 ");
|
|
3670
4156
|
const suffix = turn.drops.length > 0 ? " \xB7 \u26A0" : "";
|
|
3671
4157
|
const header = `${clock} ${provider}`;
|
|
3672
4158
|
const timed = turn.durationMs === undefined ? undefined : `${header} \xB7 ${formatMs(turn.durationMs)}`;
|
|
4159
|
+
const join = (...parts) => parts.filter((part) => part !== undefined && part !== "").join(" \xB7 ");
|
|
3673
4160
|
const volumes = [
|
|
3674
|
-
` ${labels.input} ${input} (${prompt}) \xB7 ${labels.output} ${output}`,
|
|
4161
|
+
` ${labels.input} ${input} (${prompt}) \xB7 ${labels.output} ${output} \xB7 hit ${hit}`,
|
|
4162
|
+
` ${labels.input} ${input} \xB7 ${labels.output} ${output} \xB7 hit ${hit}`,
|
|
3675
4163
|
` ${labels.input} ${input} \xB7 ${labels.output} ${output}`,
|
|
3676
4164
|
` ${labels.input} ${input}`
|
|
3677
4165
|
];
|
|
4166
|
+
const volume = volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1];
|
|
4167
|
+
const hitPart = volume.includes(`hit ${hit}`) ? undefined : `hit ${hit}`;
|
|
3678
4168
|
const facts = [
|
|
3679
|
-
`
|
|
3680
|
-
`
|
|
3681
|
-
` ${tps
|
|
3682
|
-
`
|
|
4169
|
+
` ${join(hitPart, rate, `${cost}${suffix}`)}`,
|
|
4170
|
+
` ${join(hitPart, tps, `${cost}${suffix}`)}`,
|
|
4171
|
+
` ${join(tps, `${cost}${suffix}`)}`,
|
|
4172
|
+
` ${join(tps)}`,
|
|
4173
|
+
` ${join(hitPart, `${cost}${suffix}`)}`,
|
|
4174
|
+
` ${join(`${cost}${suffix}`)}`
|
|
3683
4175
|
];
|
|
3684
4176
|
lines.push({ text: truncate(timed !== undefined && timed.length <= budget ? timed : header, budget), tone: turn.providerChanged ? "warning" : "base" });
|
|
3685
4177
|
const edge = index === 0 || index === rows.length - 1;
|
|
@@ -3687,10 +4179,7 @@ function sidebarLines(rows, options) {
|
|
|
3687
4179
|
const model = turn.modelID === undefined ? "unknown" : `${turn.modelID}${turn.variant === undefined ? "" : ` ${turn.variant}`}`;
|
|
3688
4180
|
lines.push({ text: truncate(` ${model}`, budget), tone: "muted" });
|
|
3689
4181
|
}
|
|
3690
|
-
lines.push({
|
|
3691
|
-
text: truncate(volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1], budget),
|
|
3692
|
-
tone: "muted"
|
|
3693
|
-
});
|
|
4182
|
+
lines.push({ text: truncate(volume, budget), tone: "muted" });
|
|
3694
4183
|
lines.push({
|
|
3695
4184
|
text: truncate(facts.find((text) => text.length <= budget) ?? facts[facts.length - 1], budget),
|
|
3696
4185
|
tone: turn.drops.length > 0 ? "warning" : "muted"
|
|
@@ -3741,7 +4230,8 @@ function build(request) {
|
|
|
3741
4230
|
const usage = overview(db, range, filters);
|
|
3742
4231
|
const sessionUsage = request.sessionID === "" ? undefined : overview(db, undefined, { ...request.filters, sessionID: request.sessionID });
|
|
3743
4232
|
const childIDs = request.sessionID === "" ? [] : childSessionIDs(db, request.sessionID);
|
|
3744
|
-
const
|
|
4233
|
+
const childFilters = { ...request.filters, sessionID: undefined };
|
|
4234
|
+
const children = childIDs.length === 0 ? [] : sessionUsageOf(db, childIDs, childFilters);
|
|
3745
4235
|
return overviewLines({
|
|
3746
4236
|
usage,
|
|
3747
4237
|
session: sessionUsage,
|
|
@@ -3805,9 +4295,10 @@ function build(request) {
|
|
|
3805
4295
|
}
|
|
3806
4296
|
];
|
|
3807
4297
|
case "turns": {
|
|
3808
|
-
const
|
|
4298
|
+
const scope = scoped ? "session" : request.turnsScope;
|
|
4299
|
+
const sessionID = scope === "session" ? request.sessionID : undefined;
|
|
3809
4300
|
const rows = sortTurns(turns(db, { sessionID, range, filters, limit: 300 }), request.sort, request.sortDesc, estimates);
|
|
3810
|
-
const titles =
|
|
4301
|
+
const titles = scope === "all" ? new Map(sessions(db, { range, filters, limit: 200 }).map((row) => [row.sessionID, row.title ?? row.sessionID])) : undefined;
|
|
3811
4302
|
return turnsLines(rows.slice(0, 60), width, { ...request.format, estimates, sessionTitles: titles });
|
|
3812
4303
|
}
|
|
3813
4304
|
}
|
|
@@ -3932,6 +4423,8 @@ function sortProviders(rows, sort, desc, estimates = true) {
|
|
|
3932
4423
|
return row.share;
|
|
3933
4424
|
if (sort === "tps")
|
|
3934
4425
|
return row.tps ?? -1;
|
|
4426
|
+
if (sort === "ttft")
|
|
4427
|
+
return row.ttft ?? -1;
|
|
3935
4428
|
return row.usage.steps;
|
|
3936
4429
|
};
|
|
3937
4430
|
return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
|
|
@@ -3941,6 +4434,8 @@ function sortLatency(rows, sort, desc) {
|
|
|
3941
4434
|
const pick = (row) => {
|
|
3942
4435
|
if (sort === "tps")
|
|
3943
4436
|
return row.tps.p50 ?? -1;
|
|
4437
|
+
if (sort === "ttft")
|
|
4438
|
+
return row.ttft.p50 ?? -1;
|
|
3944
4439
|
if (sort === "wall")
|
|
3945
4440
|
return row.wall.p50 ?? -1;
|
|
3946
4441
|
return row.count;
|
|
@@ -4017,13 +4512,6 @@ function size(path) {
|
|
|
4017
4512
|
return 0;
|
|
4018
4513
|
}
|
|
4019
4514
|
}
|
|
4020
|
-
function hasTable(db, name) {
|
|
4021
|
-
try {
|
|
4022
|
-
return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== null;
|
|
4023
|
-
} catch {
|
|
4024
|
-
return false;
|
|
4025
|
-
}
|
|
4026
|
-
}
|
|
4027
4515
|
function dbInfo(db, path, now = Date.now()) {
|
|
4028
4516
|
const tables = TABLES.map((table) => ({
|
|
4029
4517
|
name: table,
|
|
@@ -4077,7 +4565,7 @@ function pruneOlderThan(db, cutoff) {
|
|
|
4077
4565
|
return {
|
|
4078
4566
|
steps: deleteBatched(db, "steps", `${STEP_TIME2} < ?`, cutoff),
|
|
4079
4567
|
prompts: deleteBatched(db, "prompts", "created_at IS NOT NULL AND created_at < ?", cutoff),
|
|
4080
|
-
|
|
4568
|
+
compactions: deleteBatched(db, "compactions", "at IS NOT NULL AND at < ?", cutoff),
|
|
4081
4569
|
usage: hasTable(db, "usage") ? deleteBatched(db, "usage", "at IS NOT NULL AND at < ?", cutoff) : 0
|
|
4082
4570
|
};
|
|
4083
4571
|
}
|
|
@@ -4085,7 +4573,7 @@ function wipeAll(db) {
|
|
|
4085
4573
|
return {
|
|
4086
4574
|
steps: deleteAllBatched(db, "steps"),
|
|
4087
4575
|
prompts: deleteAllBatched(db, "prompts"),
|
|
4088
|
-
|
|
4576
|
+
compactions: deleteAllBatched(db, "compactions"),
|
|
4089
4577
|
usage: hasTable(db, "usage") ? deleteAllBatched(db, "usage") : 0,
|
|
4090
4578
|
sessions: hasTable(db, "sessions") ? deleteAllBatched(db, "sessions") : 0
|
|
4091
4579
|
};
|
|
@@ -4108,23 +4596,41 @@ function hasListCost(db) {
|
|
|
4108
4596
|
}
|
|
4109
4597
|
}
|
|
4110
4598
|
var BACKFILL_BATCH = 1000;
|
|
4599
|
+
var UNPRICED_WHERE = `cost = 0 AND list_cost IS NULL
|
|
4600
|
+
AND provider_id IS NOT NULL AND provider_id <> ''
|
|
4601
|
+
AND model_id IS NOT NULL AND model_id <> ''
|
|
4602
|
+
AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`;
|
|
4603
|
+
function priceStep(step, price) {
|
|
4604
|
+
const estimate = price({ providerID: step.provider_id ?? undefined, modelID: step.model_id ?? undefined }, {
|
|
4605
|
+
input: step.input_tokens ?? 0,
|
|
4606
|
+
output: step.output_tokens ?? 0,
|
|
4607
|
+
reasoning: step.reasoning_tokens ?? 0,
|
|
4608
|
+
cacheRead: step.cache_read ?? 0,
|
|
4609
|
+
cacheWrite: step.cache_write ?? 0
|
|
4610
|
+
});
|
|
4611
|
+
return estimate !== undefined && Number.isFinite(estimate) && estimate >= 0 ? estimate : undefined;
|
|
4612
|
+
}
|
|
4613
|
+
function backfillBatch(db, rows, price, update) {
|
|
4614
|
+
let updated = 0;
|
|
4615
|
+
db.transaction(() => {
|
|
4616
|
+
for (const row of rows) {
|
|
4617
|
+
const estimate = priceStep(row, price);
|
|
4618
|
+
if (estimate !== undefined && update(estimate, row.rowid) > 0)
|
|
4619
|
+
updated += 1;
|
|
4620
|
+
}
|
|
4621
|
+
})();
|
|
4622
|
+
return updated;
|
|
4623
|
+
}
|
|
4111
4624
|
function backfillListCost(db, price) {
|
|
4112
4625
|
if (!hasListCost(db))
|
|
4113
4626
|
return { candidates: 0, updated: 0 };
|
|
4114
|
-
const candidates = db.query(`SELECT COUNT(*) AS n FROM steps
|
|
4115
|
-
WHERE cost = 0 AND list_cost IS NULL
|
|
4116
|
-
AND provider_id IS NOT NULL AND provider_id <> ''
|
|
4117
|
-
AND model_id IS NOT NULL AND model_id <> ''
|
|
4118
|
-
AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`).get().n;
|
|
4627
|
+
const candidates = db.query(`SELECT COUNT(*) AS n FROM steps WHERE ${UNPRICED_WHERE}`).get().n;
|
|
4119
4628
|
if (candidates === 0)
|
|
4120
4629
|
return { candidates: 0, updated: 0 };
|
|
4121
4630
|
const select = db.query(`SELECT rowid, provider_id, model_id,
|
|
4122
4631
|
input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
|
|
4123
4632
|
FROM steps
|
|
4124
|
-
WHERE
|
|
4125
|
-
AND provider_id IS NOT NULL AND provider_id <> ''
|
|
4126
|
-
AND model_id IS NOT NULL AND model_id <> ''
|
|
4127
|
-
AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0
|
|
4633
|
+
WHERE ${UNPRICED_WHERE} AND rowid > ?
|
|
4128
4634
|
ORDER BY rowid
|
|
4129
4635
|
LIMIT ?`);
|
|
4130
4636
|
const update = db.query("UPDATE steps SET list_cost = ? WHERE rowid = ? AND cost = 0 AND list_cost IS NULL");
|
|
@@ -4134,21 +4640,7 @@ function backfillListCost(db, price) {
|
|
|
4134
4640
|
const rows = select.all(cursor, BACKFILL_BATCH);
|
|
4135
4641
|
if (rows.length === 0)
|
|
4136
4642
|
break;
|
|
4137
|
-
db
|
|
4138
|
-
for (const row of rows) {
|
|
4139
|
-
const estimate = price({ providerID: row.provider_id ?? undefined, modelID: row.model_id ?? undefined }, {
|
|
4140
|
-
input: row.input_tokens ?? 0,
|
|
4141
|
-
output: row.output_tokens ?? 0,
|
|
4142
|
-
reasoning: row.reasoning_tokens ?? 0,
|
|
4143
|
-
cacheRead: row.cache_read ?? 0,
|
|
4144
|
-
cacheWrite: row.cache_write ?? 0
|
|
4145
|
-
});
|
|
4146
|
-
if (estimate === undefined || !Number.isFinite(estimate) || estimate < 0)
|
|
4147
|
-
continue;
|
|
4148
|
-
if (update.run(estimate, row.rowid).changes > 0)
|
|
4149
|
-
updated += 1;
|
|
4150
|
-
}
|
|
4151
|
-
})();
|
|
4643
|
+
updated += backfillBatch(db, rows, price, (estimate, rowid) => update.run(estimate, rowid).changes);
|
|
4152
4644
|
cursor = rows[rows.length - 1].rowid;
|
|
4153
4645
|
if (rows.length < BACKFILL_BATCH)
|
|
4154
4646
|
break;
|
|
@@ -4337,6 +4829,7 @@ class StatsClient {
|
|
|
4337
4829
|
startPromise;
|
|
4338
4830
|
starting;
|
|
4339
4831
|
startAbort;
|
|
4832
|
+
abortStart;
|
|
4340
4833
|
fallbackService;
|
|
4341
4834
|
fallbackMode = false;
|
|
4342
4835
|
stopped = false;
|
|
@@ -4345,6 +4838,13 @@ class StatsClient {
|
|
|
4345
4838
|
constructor(config) {
|
|
4346
4839
|
this.config = config;
|
|
4347
4840
|
}
|
|
4841
|
+
reconfigure(options) {
|
|
4842
|
+
this.config.options = options;
|
|
4843
|
+
this.fallbackService = undefined;
|
|
4844
|
+
if (this.worker !== undefined || this.starting !== undefined) {
|
|
4845
|
+
this.hardReset("the usage service was reconfigured", false);
|
|
4846
|
+
}
|
|
4847
|
+
}
|
|
4348
4848
|
request(method, input, options = {}) {
|
|
4349
4849
|
if (this.stopped)
|
|
4350
4850
|
return Promise.reject(new StatsError("unavailable", "the usage service is stopped"));
|
|
@@ -4365,7 +4865,9 @@ class StatsClient {
|
|
|
4365
4865
|
return;
|
|
4366
4866
|
this.stopped = true;
|
|
4367
4867
|
this.rejectAll(new StatsError("unavailable", "the usage service stopped"));
|
|
4868
|
+
this.abortStart?.();
|
|
4368
4869
|
this.startAbort?.();
|
|
4870
|
+
this.abortStart = undefined;
|
|
4369
4871
|
this.worker?.terminate();
|
|
4370
4872
|
this.worker = undefined;
|
|
4371
4873
|
this.starting = undefined;
|
|
@@ -4421,7 +4923,7 @@ class StatsClient {
|
|
|
4421
4923
|
}
|
|
4422
4924
|
this.starting = worker;
|
|
4423
4925
|
let timer;
|
|
4424
|
-
const finish = (ok, reason) => {
|
|
4926
|
+
const finish = (ok, reason, useFallback = true) => {
|
|
4425
4927
|
if (settled)
|
|
4426
4928
|
return;
|
|
4427
4929
|
settled = true;
|
|
@@ -4430,6 +4932,7 @@ class StatsClient {
|
|
|
4430
4932
|
this.startPromise = undefined;
|
|
4431
4933
|
this.starting = undefined;
|
|
4432
4934
|
this.startAbort = undefined;
|
|
4935
|
+
this.abortStart = undefined;
|
|
4433
4936
|
if (this.stopped) {
|
|
4434
4937
|
worker.terminate();
|
|
4435
4938
|
this.worker = undefined;
|
|
@@ -4438,11 +4941,13 @@ class StatsClient {
|
|
|
4438
4941
|
}
|
|
4439
4942
|
if (!ok) {
|
|
4440
4943
|
worker.terminate();
|
|
4441
|
-
|
|
4944
|
+
if (useFallback)
|
|
4945
|
+
this.useFallback(reason ?? "the usage worker did not start");
|
|
4442
4946
|
}
|
|
4443
4947
|
resolve();
|
|
4444
4948
|
};
|
|
4445
|
-
this.startAbort = () => finish(false, "the usage service stopped");
|
|
4949
|
+
this.startAbort = () => finish(false, "the usage service stopped", false);
|
|
4950
|
+
this.abortStart = () => finish(false, "the usage service was reconfigured", false);
|
|
4446
4951
|
timer = setTimeout(() => finish(false, "the usage worker did not start in time"), this.config.timeouts?.start ?? START_TIMEOUT_MS);
|
|
4447
4952
|
worker.onmessage = (event) => {
|
|
4448
4953
|
const message = event.data;
|
|
@@ -4556,9 +5061,12 @@ class StatsClient {
|
|
|
4556
5061
|
pending.reject(error);
|
|
4557
5062
|
}
|
|
4558
5063
|
}
|
|
4559
|
-
hardReset(message) {
|
|
4560
|
-
|
|
5064
|
+
hardReset(message, log = true) {
|
|
5065
|
+
if (log)
|
|
5066
|
+
this.config.log?.(message);
|
|
4561
5067
|
this.rejectAll(new StatsError("unavailable", message));
|
|
5068
|
+
this.abortStart?.();
|
|
5069
|
+
this.abortStart = undefined;
|
|
4562
5070
|
this.worker?.terminate();
|
|
4563
5071
|
this.worker = undefined;
|
|
4564
5072
|
this.starting?.terminate();
|
|
@@ -4629,123 +5137,140 @@ function rpcFailure(context, error) {
|
|
|
4629
5137
|
return context.error(error.code, error.message);
|
|
4630
5138
|
return context.error("unavailable", "the usage database is unavailable");
|
|
4631
5139
|
}
|
|
5140
|
+
function serviceOptionsFor(settings, policy) {
|
|
5141
|
+
return {
|
|
5142
|
+
pricing: settings.pricing,
|
|
5143
|
+
maintenance: policy.maintenance,
|
|
5144
|
+
exposePaths: policy.exposePaths,
|
|
5145
|
+
format: {
|
|
5146
|
+
labels: settings.labels,
|
|
5147
|
+
fields: settings.fields,
|
|
5148
|
+
turnTotals: settings.turnTotals,
|
|
5149
|
+
estimates: settings.pricing
|
|
5150
|
+
}
|
|
5151
|
+
};
|
|
5152
|
+
}
|
|
4632
5153
|
var src_default = Plugin.define({
|
|
4633
5154
|
id: "usage-insights",
|
|
4634
5155
|
async setup(ctx) {
|
|
4635
|
-
|
|
4636
|
-
|
|
4637
|
-
|
|
4638
|
-
const
|
|
4639
|
-
const
|
|
4640
|
-
|
|
5156
|
+
if (Object.keys(ctx.options ?? {}).length > 0) {
|
|
5157
|
+
console.warn("[usage-insights] plugin options in opencode.json(c) are no longer read; edit the settings in the TUI or Desktop instead");
|
|
5158
|
+
}
|
|
5159
|
+
const policy = serverPolicy();
|
|
5160
|
+
const path = resolveDbPath();
|
|
5161
|
+
const stored = await ctx.storage.get(SETTINGS_STORAGE_KEY).catch(() => {
|
|
5162
|
+
console.warn("[usage-insights] could not read the shared settings; using the defaults");
|
|
4641
5163
|
return;
|
|
4642
|
-
try {
|
|
4643
|
-
db.exec("PRAGMA busy_timeout = 1000");
|
|
4644
|
-
} catch {}
|
|
4645
|
-
const pricing = options.pricing !== "off";
|
|
4646
|
-
const maintenance = options.maintenance !== false;
|
|
4647
|
-
const exposePaths = options.exposePaths === true;
|
|
4648
|
-
const source = pricing ? createPriceSource(ctx) : undefined;
|
|
4649
|
-
source?.refresh(true);
|
|
4650
|
-
const format = {
|
|
4651
|
-
...options.labels !== undefined ? { labels: options.labels } : {},
|
|
4652
|
-
...options.fields !== undefined ? { fields: options.fields } : {},
|
|
4653
|
-
...options.turnTotals !== undefined ? { turnTotals: options.turnTotals } : {}
|
|
4654
|
-
};
|
|
4655
|
-
const serviceOptions = { pricing, maintenance, exposePaths, format };
|
|
4656
|
-
const stats = new StatsClient({
|
|
4657
|
-
dbPath: path,
|
|
4658
|
-
options: serviceOptions,
|
|
4659
|
-
priceTable: () => source?.table(),
|
|
4660
|
-
fallback: () => createService(() => db, {
|
|
4661
|
-
...serviceOptions,
|
|
4662
|
-
path,
|
|
4663
|
-
priceTable: () => source?.table()
|
|
4664
|
-
}),
|
|
4665
|
-
log: (message) => console.warn(`[usage-insights] ${message}`)
|
|
4666
5164
|
});
|
|
4667
|
-
|
|
4668
|
-
|
|
4669
|
-
|
|
4670
|
-
|
|
4671
|
-
|
|
4672
|
-
|
|
4673
|
-
|
|
4674
|
-
|
|
4675
|
-
|
|
4676
|
-
|
|
4677
|
-
|
|
4678
|
-
|
|
4679
|
-
|
|
4680
|
-
|
|
4681
|
-
|
|
4682
|
-
|
|
4683
|
-
|
|
4684
|
-
|
|
4685
|
-
|
|
4686
|
-
|
|
4687
|
-
|
|
4688
|
-
|
|
4689
|
-
|
|
4690
|
-
|
|
4691
|
-
|
|
4692
|
-
|
|
4693
|
-
|
|
4694
|
-
|
|
4695
|
-
|
|
4696
|
-
|
|
4697
|
-
|
|
4698
|
-
|
|
4699
|
-
|
|
4700
|
-
|
|
4701
|
-
|
|
4702
|
-
}
|
|
4703
|
-
|
|
4704
|
-
|
|
4705
|
-
|
|
4706
|
-
|
|
4707
|
-
|
|
4708
|
-
|
|
4709
|
-
|
|
4710
|
-
|
|
4711
|
-
|
|
4712
|
-
|
|
4713
|
-
|
|
4714
|
-
|
|
4715
|
-
|
|
4716
|
-
|
|
4717
|
-
|
|
4718
|
-
|
|
4719
|
-
|
|
4720
|
-
|
|
4721
|
-
|
|
4722
|
-
|
|
5165
|
+
let settings = sanitizeUsageSettings(stored);
|
|
5166
|
+
const source = createPriceSource(ctx);
|
|
5167
|
+
if (settings.pricing)
|
|
5168
|
+
source.refresh(true);
|
|
5169
|
+
let runtime;
|
|
5170
|
+
let serviceOptions = serviceOptionsFor(settings, policy);
|
|
5171
|
+
let nextOpenAttempt = 0;
|
|
5172
|
+
function ensureRuntime() {
|
|
5173
|
+
if (runtime !== undefined)
|
|
5174
|
+
return runtime;
|
|
5175
|
+
const now = Date.now();
|
|
5176
|
+
if (now < nextOpenAttempt)
|
|
5177
|
+
return;
|
|
5178
|
+
const db = tryOpen(path);
|
|
5179
|
+
if (db === undefined) {
|
|
5180
|
+
nextOpenAttempt = now + 5000;
|
|
5181
|
+
return;
|
|
5182
|
+
}
|
|
5183
|
+
try {
|
|
5184
|
+
db.exec("PRAGMA busy_timeout = 1000");
|
|
5185
|
+
} catch {}
|
|
5186
|
+
const stats = new StatsClient({
|
|
5187
|
+
dbPath: path,
|
|
5188
|
+
options: serviceOptions,
|
|
5189
|
+
priceTable: () => source.table(),
|
|
5190
|
+
fallback: () => createService(() => db, {
|
|
5191
|
+
...serviceOptions,
|
|
5192
|
+
path,
|
|
5193
|
+
priceTable: () => source.table()
|
|
5194
|
+
}),
|
|
5195
|
+
log: (message) => console.warn(`[usage-insights] ${message}`)
|
|
5196
|
+
});
|
|
5197
|
+
const recorder = createRecorder(db, {
|
|
5198
|
+
price: (ref, tokens) => settings.pricing ? source.price(ref, tokens) : undefined
|
|
5199
|
+
});
|
|
5200
|
+
runtime = { db, stats, recorder };
|
|
5201
|
+
return runtime;
|
|
5202
|
+
}
|
|
5203
|
+
function applySettings(next) {
|
|
5204
|
+
const previous = settings;
|
|
5205
|
+
settings = next;
|
|
5206
|
+
if (next.pricing && !previous.pricing)
|
|
5207
|
+
source.refresh(true);
|
|
5208
|
+
const serverChanged = previous.pricing !== next.pricing || previous.turnTotals !== next.turnTotals || JSON.stringify(previous.fields) !== JSON.stringify(next.fields) || JSON.stringify(previous.labels) !== JSON.stringify(next.labels);
|
|
5209
|
+
if (!serverChanged)
|
|
5210
|
+
return;
|
|
5211
|
+
serviceOptions = serviceOptionsFor(settings, policy);
|
|
5212
|
+
runtime?.stats.reconfigure(serviceOptions);
|
|
5213
|
+
}
|
|
5214
|
+
const envelope = () => ({ settings, policy });
|
|
5215
|
+
let notifySettings;
|
|
5216
|
+
const settingsRegistration = await ctx.rpc.register(UsageInsightsSettings, {
|
|
5217
|
+
get: async () => envelope(),
|
|
5218
|
+
set: async (input) => {
|
|
5219
|
+
const next = mergeUsageSettings(settings, input.patch);
|
|
5220
|
+
await ctx.storage.set(SETTINGS_STORAGE_KEY, next);
|
|
5221
|
+
applySettings(next);
|
|
5222
|
+
const saved = envelope();
|
|
5223
|
+
await notifySettings?.(saved).catch(() => {});
|
|
5224
|
+
return saved;
|
|
4723
5225
|
},
|
|
4724
|
-
|
|
4725
|
-
|
|
4726
|
-
|
|
4727
|
-
|
|
4728
|
-
|
|
4729
|
-
|
|
5226
|
+
reset: async () => {
|
|
5227
|
+
await ctx.storage.remove(SETTINGS_STORAGE_KEY);
|
|
5228
|
+
applySettings(defaultUsageSettings());
|
|
5229
|
+
const saved = envelope();
|
|
5230
|
+
await notifySettings?.(saved).catch(() => {});
|
|
5231
|
+
return saved;
|
|
5232
|
+
}
|
|
5233
|
+
});
|
|
5234
|
+
notifySettings = (next) => settingsRegistration.events.emit("updated", next);
|
|
5235
|
+
async function request(method, input, context) {
|
|
5236
|
+
const current = ensureRuntime();
|
|
5237
|
+
if (current === undefined)
|
|
5238
|
+
return context.error("unavailable", "the usage database is unavailable");
|
|
5239
|
+
try {
|
|
5240
|
+
return await current.stats.request(method, input);
|
|
5241
|
+
} catch (error) {
|
|
5242
|
+
return rpcFailure(context, error);
|
|
4730
5243
|
}
|
|
4731
|
-
}
|
|
4732
|
-
|
|
4733
|
-
|
|
5244
|
+
}
|
|
5245
|
+
const dataRegistration = await ctx.rpc.register(UsageInsights, {
|
|
5246
|
+
panel: (input, context) => request("panel", input, context),
|
|
5247
|
+
turns: (input, context) => request("turns", input, context),
|
|
5248
|
+
listCost: (input, context) => request("listCost", input, context),
|
|
5249
|
+
filters: (_input, context) => request("filters", {}, context),
|
|
5250
|
+
dbInfo: (_input, context) => request("dbInfo", {}, context),
|
|
5251
|
+
prune: (input, context) => request("prune", input, context),
|
|
5252
|
+
wipe: (input, context) => request("wipe", input, context),
|
|
5253
|
+
vacuum: (input, context) => request("vacuum", input, context),
|
|
5254
|
+
backfill: (input, context) => request("backfill", input, context)
|
|
5255
|
+
}).catch(async (error) => {
|
|
5256
|
+
await settingsRegistration.dispose().catch(() => {});
|
|
5257
|
+
runtime?.stats.stop();
|
|
5258
|
+
runtime?.db.close();
|
|
4734
5259
|
throw error;
|
|
4735
5260
|
});
|
|
4736
|
-
|
|
5261
|
+
ensureRuntime();
|
|
4737
5262
|
const abort = new AbortController;
|
|
4738
5263
|
const stream = (async () => {
|
|
4739
5264
|
try {
|
|
4740
5265
|
for await (const event of ctx.event.subscribe({ signal: abort.signal })) {
|
|
4741
5266
|
try {
|
|
4742
|
-
if (event.type === "model.updated")
|
|
4743
|
-
source
|
|
4744
|
-
recorder.handleEvent(event);
|
|
5267
|
+
if (event.type === "model.updated" && settings.pricing)
|
|
5268
|
+
source.refresh(true);
|
|
5269
|
+
runtime?.recorder.handleEvent(event);
|
|
4745
5270
|
if (RECORDED_EVENTS.has(event.type)) {
|
|
4746
5271
|
const data = event.data;
|
|
4747
5272
|
const sessionID = typeof data?.sessionID === "string" ? data.sessionID : undefined;
|
|
4748
|
-
|
|
5273
|
+
dataRegistration.events.emit("recorded", { at: Date.now(), ...sessionID !== undefined ? { sessionID } : {} }).catch(() => {});
|
|
4749
5274
|
}
|
|
4750
5275
|
} catch {}
|
|
4751
5276
|
}
|
|
@@ -4753,10 +5278,10 @@ var src_default = Plugin.define({
|
|
|
4753
5278
|
})();
|
|
4754
5279
|
return async () => {
|
|
4755
5280
|
abort.abort();
|
|
4756
|
-
await
|
|
5281
|
+
await Promise.allSettled([dataRegistration.dispose(), settingsRegistration.dispose()]);
|
|
4757
5282
|
await stream;
|
|
4758
|
-
stats.stop();
|
|
4759
|
-
db.close();
|
|
5283
|
+
runtime?.stats.stop();
|
|
5284
|
+
runtime?.db.close();
|
|
4760
5285
|
};
|
|
4761
5286
|
}
|
|
4762
5287
|
});
|
|
@@ -4764,4 +5289,4 @@ export {
|
|
|
4764
5289
|
src_default as default
|
|
4765
5290
|
};
|
|
4766
5291
|
|
|
4767
|
-
//# debugId=
|
|
5292
|
+
//# debugId=E4A1A33EDF4C638464756E2164756E21
|