opencode-usage-insights 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +66 -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 +1715 -1195
- package/dist/index.js.map +23 -16
- package/dist/line.d.ts +1 -0
- package/dist/panel-data.d.ts +8 -1
- 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 +25 -31
- 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 +577 -352
- 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 +954 -144
- 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 +2 -1
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,10 @@ 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
|
+
var MODEL_KEY_SQL = `COALESCE(model_id, '(unknown)') || '${MODEL_KEY_SEPARATOR}' || COALESCE(variant, '')`;
|
|
1210
1808
|
function modelKey(modelID, variant) {
|
|
1211
|
-
return `${modelID}
|
|
1809
|
+
return `${modelID}${MODEL_KEY_SEPARATOR}${variant ?? ""}`;
|
|
1212
1810
|
}
|
|
1213
1811
|
function modelLabel(modelID, variant) {
|
|
1214
1812
|
return variant === undefined ? modelID : `${modelID} ${variant}`;
|
|
@@ -1279,7 +1877,10 @@ function overview(db, range, filters) {
|
|
|
1279
1877
|
MIN(${STEP_TIME}) AS firstAt,
|
|
1280
1878
|
MAX(COALESCE(completed_at, ${STEP_TIME})) AS lastAt,
|
|
1281
1879
|
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
|
|
1880
|
+
COALESCE(SUM(CASE WHEN streamed_at > created_at THEN streamed_at - created_at ELSE 0 END), 0) AS window,
|
|
1881
|
+
COALESCE(SUM(CASE WHEN streamed_at > COALESCE(first_token_at, created_at) THEN output_tokens + reasoning_tokens ELSE 0 END), 0) AS decodeProduced,
|
|
1882
|
+
COALESCE(SUM(CASE WHEN streamed_at > COALESCE(first_token_at, created_at)
|
|
1883
|
+
THEN streamed_at - COALESCE(first_token_at, created_at) ELSE 0 END), 0) AS decodeWindow
|
|
1283
1884
|
FROM steps ${steps.where}`).get(...steps.params);
|
|
1284
1885
|
const prompts = rangeWhere(range, "created_at");
|
|
1285
1886
|
const promptClauses = prompts.where === "" ? [] : [prompts.where.slice("WHERE ".length)];
|
|
@@ -1290,6 +1891,10 @@ function overview(db, range, filters) {
|
|
|
1290
1891
|
}
|
|
1291
1892
|
const promptWhere = promptClauses.length > 0 ? `WHERE ${promptClauses.join(" AND ")}` : "";
|
|
1292
1893
|
const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${promptWhere}`).get(...promptParams);
|
|
1894
|
+
const ttftFilter = steps.where === "" ? "WHERE" : `${steps.where} AND`;
|
|
1895
|
+
const ttftRows = db.query(`SELECT MAX(0, first_token_at - created_at) AS ttft
|
|
1896
|
+
FROM steps ${ttftFilter} created_at IS NOT NULL AND first_token_at IS NOT NULL`).all(...steps.params);
|
|
1897
|
+
const ttft = ttftRows.length === 0 ? undefined : percentile(ttftRows.map((entry) => entry.ttft), 50);
|
|
1293
1898
|
const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
|
|
1294
1899
|
const other = otherUsage(db, range, filters);
|
|
1295
1900
|
return {
|
|
@@ -1301,7 +1906,9 @@ function overview(db, range, filters) {
|
|
|
1301
1906
|
firstAt: row?.firstAt ?? undefined,
|
|
1302
1907
|
lastAt: row?.lastAt ?? undefined,
|
|
1303
1908
|
cacheHitRatio: cacheHitRatio(usage),
|
|
1304
|
-
tps: row === null ? undefined : tokensPerSecond(row.
|
|
1909
|
+
tps: row === null ? undefined : tokensPerSecond(row.decodeProduced ?? 0, 0, row.decodeWindow ?? 0),
|
|
1910
|
+
requestTps: row === null ? undefined : tokensPerSecond(row.produced ?? 0, 0, row.window ?? 0),
|
|
1911
|
+
ttft
|
|
1305
1912
|
};
|
|
1306
1913
|
}
|
|
1307
1914
|
function models(db, range, filters) {
|
|
@@ -1456,7 +2063,11 @@ function stepMessage(row) {
|
|
|
1456
2063
|
return {
|
|
1457
2064
|
type: "assistant",
|
|
1458
2065
|
id: row.message_id,
|
|
1459
|
-
time: {
|
|
2066
|
+
time: {
|
|
2067
|
+
created: row.created_at ?? row.recorded_at,
|
|
2068
|
+
firstToken: row.first_token_at ?? undefined,
|
|
2069
|
+
completed: row.completed_at ?? undefined
|
|
2070
|
+
},
|
|
1460
2071
|
model: row.provider_id !== null && row.model_id !== null ? { providerID: row.provider_id, id: row.model_id, variant: row.variant ?? undefined } : undefined,
|
|
1461
2072
|
tokens: {
|
|
1462
2073
|
input: row.input_tokens ?? 0,
|
|
@@ -1485,363 +2096,138 @@ function turns(db, options) {
|
|
|
1485
2096
|
clauses.push(`${STEP_TIME} >= ?`);
|
|
1486
2097
|
params.push(floor);
|
|
1487
2098
|
}
|
|
1488
|
-
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);
|
|
2099
|
+
const steps = db.query(`SELECT message_id, session_id, provider_id, model_id, variant,
|
|
2100
|
+
input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,
|
|
2101
|
+
created_at, first_token_at, streamed_at, recorded_at, completed_at, finish
|
|
2102
|
+
FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
|
|
2103
|
+
ORDER BY session_id, ${STEP_TIME}, message_id`).all(...params);
|
|
2104
|
+
const promptClause = options?.sessionID === undefined ? "" : `WHERE session_id = ?${floor === undefined ? "" : " AND created_at >= ?"}`;
|
|
2105
|
+
const promptParams = options?.sessionID === undefined ? [] : floor === undefined ? [options.sessionID] : [options.sessionID, floor];
|
|
2106
|
+
const promptRows = db.query(`SELECT session_id, created_at FROM prompts ${promptClause} ORDER BY session_id, created_at`).all(...promptParams);
|
|
2107
|
+
const promptsBySession = new Map;
|
|
2108
|
+
for (const row of promptRows) {
|
|
2109
|
+
if (row.created_at === null)
|
|
2110
|
+
continue;
|
|
2111
|
+
const list = promptsBySession.get(row.session_id) ?? [];
|
|
2112
|
+
list.push(row.created_at);
|
|
2113
|
+
promptsBySession.set(row.session_id, list);
|
|
2114
|
+
}
|
|
2115
|
+
const result = [];
|
|
2116
|
+
let sessionID;
|
|
2117
|
+
let bucket = [];
|
|
2118
|
+
let promptIndex = -2;
|
|
2119
|
+
let promptAt;
|
|
2120
|
+
function close() {
|
|
2121
|
+
const last = bucket[bucket.length - 1];
|
|
2122
|
+
if (last === undefined || !turnFinished(last.finish)) {
|
|
2123
|
+
bucket = [];
|
|
1770
2124
|
return;
|
|
1771
2125
|
}
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
2126
|
+
const totals = emptyUsage();
|
|
2127
|
+
for (const row of bucket)
|
|
2128
|
+
addUsage(totals, stepUsage(row));
|
|
2129
|
+
const drops = [];
|
|
2130
|
+
let reference;
|
|
2131
|
+
for (const row of bucket) {
|
|
2132
|
+
const message = stepMessage(row);
|
|
2133
|
+
const drop = cacheDrop(reference, message);
|
|
2134
|
+
if (drop !== undefined) {
|
|
2135
|
+
drops.push({ messageID: row.message_id, tokens: drop, gapMs: stepGap(reference, message) });
|
|
2136
|
+
}
|
|
2137
|
+
reference = message;
|
|
1779
2138
|
}
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
2139
|
+
const providerID = last.provider_id ?? undefined;
|
|
2140
|
+
const modelID = last.model_id ?? undefined;
|
|
2141
|
+
const variant = last.variant ?? undefined;
|
|
2142
|
+
let produced = 0;
|
|
2143
|
+
let window = 0;
|
|
2144
|
+
let decodeProduced = 0;
|
|
2145
|
+
let decodeWindow = 0;
|
|
2146
|
+
for (const row of bucket) {
|
|
2147
|
+
const tokens = (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0);
|
|
2148
|
+
if (row.created_at !== null && row.streamed_at !== null && row.streamed_at > row.created_at) {
|
|
2149
|
+
produced += tokens;
|
|
2150
|
+
window += row.streamed_at - row.created_at;
|
|
2151
|
+
}
|
|
2152
|
+
const start = row.first_token_at ?? row.created_at;
|
|
2153
|
+
if (start !== null && row.streamed_at !== null && row.streamed_at > start) {
|
|
2154
|
+
decodeProduced += tokens;
|
|
2155
|
+
decodeWindow += row.streamed_at - start;
|
|
2156
|
+
}
|
|
1785
2157
|
}
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
2158
|
+
const first = bucket[0];
|
|
2159
|
+
const ttft = first !== undefined && first.created_at !== null && first.first_token_at !== null ? Math.max(0, first.first_token_at - first.created_at) : undefined;
|
|
2160
|
+
const previous = result.length > 0 && result[result.length - 1].sessionID === last.session_id ? result[result.length - 1] : undefined;
|
|
2161
|
+
const endAt = last.completed_at ?? last.created_at ?? last.recorded_at;
|
|
2162
|
+
const firstAt = bucket[0]?.created_at ?? promptAt;
|
|
2163
|
+
result.push({
|
|
2164
|
+
sessionID: last.session_id,
|
|
2165
|
+
promptAt,
|
|
2166
|
+
endAt,
|
|
2167
|
+
durationMs: firstAt !== undefined && endAt > firstAt ? endAt - firstAt : undefined,
|
|
2168
|
+
promptGapMs: promptAt !== undefined && previous?.promptAt !== undefined ? Math.max(0, promptAt - previous.promptAt) : undefined,
|
|
2169
|
+
providerID,
|
|
2170
|
+
modelID,
|
|
2171
|
+
variant,
|
|
2172
|
+
providerChanged: previous?.providerID !== undefined && providerID !== undefined && previous.providerID !== providerID,
|
|
2173
|
+
modelChanged: previous !== undefined && previous.providerID === providerID && `${previous.modelID ?? ""}#${previous.variant ?? ""}` !== `${modelID ?? ""}#${variant ?? ""}`,
|
|
2174
|
+
steps: bucket.length,
|
|
2175
|
+
latest: stepUsage(last),
|
|
2176
|
+
totals,
|
|
2177
|
+
drops,
|
|
2178
|
+
finish: last.finish ?? undefined,
|
|
2179
|
+
tps: tokensPerSecond(decodeProduced, 0, decodeWindow),
|
|
2180
|
+
requestTps: tokensPerSecond(produced, 0, window),
|
|
2181
|
+
ttft
|
|
2182
|
+
});
|
|
2183
|
+
bucket = [];
|
|
2184
|
+
}
|
|
2185
|
+
for (const row of steps) {
|
|
2186
|
+
if (row.session_id !== sessionID) {
|
|
2187
|
+
close();
|
|
2188
|
+
sessionID = row.session_id;
|
|
2189
|
+
promptIndex = -2;
|
|
2190
|
+
promptAt = undefined;
|
|
1791
2191
|
}
|
|
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;
|
|
2192
|
+
const time = row.created_at ?? row.recorded_at;
|
|
2193
|
+
const prompts = promptsBySession.get(row.session_id) ?? [];
|
|
2194
|
+
let index = -1;
|
|
2195
|
+
for (let candidate = prompts.length - 1;candidate >= 0; candidate -= 1) {
|
|
2196
|
+
if ((prompts[candidate] ?? Number.POSITIVE_INFINITY) <= time) {
|
|
2197
|
+
index = candidate;
|
|
2198
|
+
break;
|
|
2199
|
+
}
|
|
1812
2200
|
}
|
|
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;
|
|
2201
|
+
if (index !== promptIndex) {
|
|
2202
|
+
close();
|
|
2203
|
+
promptIndex = index;
|
|
2204
|
+
promptAt = index >= 0 ? prompts[index] : undefined;
|
|
1825
2205
|
}
|
|
1826
|
-
|
|
1827
|
-
return;
|
|
2206
|
+
bucket.push(row);
|
|
1828
2207
|
}
|
|
2208
|
+
close();
|
|
2209
|
+
const reachedRangeStart = options?.range?.from !== undefined && floor !== undefined && floor <= options.range.from;
|
|
2210
|
+
return { rows: result.reverse(), complete: floor === undefined || reachedRangeStart };
|
|
1829
2211
|
}
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
2212
|
+
let promptCount = Math.max(1, limit + 1);
|
|
2213
|
+
for (;; ) {
|
|
2214
|
+
const { rows, complete } = read(promptCount);
|
|
2215
|
+
if (rows.length >= limit || complete)
|
|
2216
|
+
return rows.slice(0, limit);
|
|
2217
|
+
const next = promptCount * 2 + 1;
|
|
2218
|
+
if (!Number.isFinite(next) || next <= promptCount)
|
|
2219
|
+
return rows.slice(0, limit);
|
|
2220
|
+
promptCount = next;
|
|
1839
2221
|
}
|
|
1840
|
-
return { handleEvent, pendingFor };
|
|
1841
2222
|
}
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
2223
|
+
function promptFloor(db, sessionID, count) {
|
|
2224
|
+
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);
|
|
2225
|
+
return rows.length === count ? rows[count - 1].created_at : undefined;
|
|
2226
|
+
}
|
|
2227
|
+
function filterOptions(db) {
|
|
2228
|
+
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 }));
|
|
2229
|
+
return { models: pick("model_id"), providers: pick("provider_id") };
|
|
2230
|
+
}
|
|
1845
2231
|
|
|
1846
2232
|
// src/stats/aggregates.ts
|
|
1847
2233
|
var STEP_AT = "COALESCE(created_at, recorded_at)";
|
|
@@ -1870,8 +2256,9 @@ var STEP_COLUMNS = `message_id AS messageID, session_id AS sessionID, provider_i
|
|
|
1870
2256
|
COALESCE(input_tokens, 0) AS input, COALESCE(cache_read, 0) AS cached, COALESCE(cache_write, 0) AS cacheWrite,
|
|
1871
2257
|
COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, COALESCE(cost, 0) AS cost,
|
|
1872
2258
|
COALESCE(list_cost, 0) AS listCost,
|
|
1873
|
-
created_at AS createdAt,
|
|
1874
|
-
|
|
2259
|
+
created_at AS createdAt, first_token_at AS firstTokenAt, streamed_at AS streamedAt,
|
|
2260
|
+
completed_at AS completedAt, ${STEP_AT} AS at`;
|
|
2261
|
+
var STEP_OPTIONAL = ["providerID", "modelID", "variant", "createdAt", "firstTokenAt", "streamedAt", "completedAt"];
|
|
1875
2262
|
var PAIR_COLUMNS = STEP_COLUMNS.replace("COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, ", "");
|
|
1876
2263
|
function stepRows(db, options) {
|
|
1877
2264
|
const filter = buildWhere(options?.range, options?.filters);
|
|
@@ -1950,6 +2337,7 @@ function coverageOf(db, options) {
|
|
|
1950
2337
|
COALESCE(SUM(CASE WHEN model_id IS NULL THEN 1 ELSE 0 END), 0) AS missingModel,
|
|
1951
2338
|
COALESCE(SUM(CASE WHEN completed_at IS NOT NULL OR finish IS NOT NULL THEN 0 ELSE 1 END), 0) AS unsettled,
|
|
1952
2339
|
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,
|
|
2340
|
+
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
2341
|
MIN(${STEP_AT}) AS firstAt,
|
|
1954
2342
|
MAX(${STEP_AT}) AS lastAt
|
|
1955
2343
|
FROM steps ${filter.where}`).get(...filter.params);
|
|
@@ -1960,6 +2348,7 @@ function coverageOf(db, options) {
|
|
|
1960
2348
|
missingModel: row.missingModel,
|
|
1961
2349
|
unsettled: row.unsettled,
|
|
1962
2350
|
missingTps: row.missingTps,
|
|
2351
|
+
missingFirstToken: row.missingFirstToken,
|
|
1963
2352
|
firstAt: row.firstAt ?? undefined,
|
|
1964
2353
|
lastAt: row.lastAt ?? undefined
|
|
1965
2354
|
};
|
|
@@ -1972,7 +2361,14 @@ function groupedRows(db, options) {
|
|
|
1972
2361
|
function timingOf(step) {
|
|
1973
2362
|
const wall = step.createdAt !== undefined && step.completedAt !== undefined ? Math.max(0, step.completedAt - step.createdAt) : undefined;
|
|
1974
2363
|
const stream = step.createdAt !== undefined && step.streamedAt !== undefined && step.streamedAt > step.createdAt ? step.streamedAt - step.createdAt : undefined;
|
|
1975
|
-
|
|
2364
|
+
const ttft = step.createdAt !== undefined && step.firstTokenAt !== undefined ? Math.max(0, step.firstTokenAt - step.createdAt) : undefined;
|
|
2365
|
+
return {
|
|
2366
|
+
wall,
|
|
2367
|
+
stream,
|
|
2368
|
+
ttft,
|
|
2369
|
+
tps: tokensPerSecond(step.output + step.reasoning, step.firstTokenAt ?? step.createdAt, step.streamedAt),
|
|
2370
|
+
requestTps: tokensPerSecond(step.output + step.reasoning, step.createdAt, step.streamedAt)
|
|
2371
|
+
};
|
|
1976
2372
|
}
|
|
1977
2373
|
function timingRows(db, options) {
|
|
1978
2374
|
return groupedRows(db, options);
|
|
@@ -1980,17 +2376,29 @@ function timingRows(db, options) {
|
|
|
1980
2376
|
function latencyOf(rows) {
|
|
1981
2377
|
const wall = [];
|
|
1982
2378
|
const stream = [];
|
|
2379
|
+
const ttft = [];
|
|
1983
2380
|
const tps = [];
|
|
2381
|
+
const requestTps = [];
|
|
1984
2382
|
for (const step of rows) {
|
|
1985
2383
|
const timing = timingOf(step);
|
|
1986
2384
|
if (timing.wall !== undefined)
|
|
1987
2385
|
wall.push(timing.wall);
|
|
1988
2386
|
if (timing.stream !== undefined)
|
|
1989
2387
|
stream.push(timing.stream);
|
|
2388
|
+
if (timing.ttft !== undefined)
|
|
2389
|
+
ttft.push(timing.ttft);
|
|
1990
2390
|
if (timing.tps !== undefined)
|
|
1991
2391
|
tps.push(timing.tps);
|
|
2392
|
+
if (timing.requestTps !== undefined)
|
|
2393
|
+
requestTps.push(timing.requestTps);
|
|
1992
2394
|
}
|
|
1993
|
-
return {
|
|
2395
|
+
return {
|
|
2396
|
+
wall: latencyStats(wall),
|
|
2397
|
+
stream: latencyStats(stream),
|
|
2398
|
+
ttft: latencyStats(ttft),
|
|
2399
|
+
tps: latencyStats(tps),
|
|
2400
|
+
requestTps: latencyStats(requestTps)
|
|
2401
|
+
};
|
|
1994
2402
|
}
|
|
1995
2403
|
function latencyGroupsOf(rows, by) {
|
|
1996
2404
|
const key = (step) => by === "model" ? modelKey(step.modelID ?? "(unknown)", step.variant) : step.providerID ?? "(unknown)";
|
|
@@ -1998,25 +2406,33 @@ function latencyGroupsOf(rows, by) {
|
|
|
1998
2406
|
for (const [group, steps] of groupBy(rows, key)) {
|
|
1999
2407
|
const wall = [];
|
|
2000
2408
|
const stream = [];
|
|
2409
|
+
const ttft = [];
|
|
2001
2410
|
const tps = [];
|
|
2411
|
+
const requestTps = [];
|
|
2002
2412
|
for (const step of steps) {
|
|
2003
2413
|
const timing = timingOf(step);
|
|
2004
2414
|
if (timing.wall !== undefined)
|
|
2005
2415
|
wall.push(timing.wall);
|
|
2006
2416
|
if (timing.stream !== undefined)
|
|
2007
2417
|
stream.push(timing.stream);
|
|
2418
|
+
if (timing.ttft !== undefined)
|
|
2419
|
+
ttft.push(timing.ttft);
|
|
2008
2420
|
if (timing.tps !== undefined)
|
|
2009
2421
|
tps.push(timing.tps);
|
|
2422
|
+
if (timing.requestTps !== undefined)
|
|
2423
|
+
requestTps.push(timing.requestTps);
|
|
2010
2424
|
}
|
|
2011
|
-
const
|
|
2425
|
+
const { modelID, variant } = splitModelKey(group);
|
|
2012
2426
|
groups.push({
|
|
2013
2427
|
key: group,
|
|
2014
|
-
label: by === "model" ? variant === undefined
|
|
2428
|
+
label: by === "model" ? variant === undefined ? modelID : `${modelID} ${variant}` : group,
|
|
2015
2429
|
count: steps.length,
|
|
2016
2430
|
usage: usageOf(steps),
|
|
2017
2431
|
wall: latencyStats(wall),
|
|
2018
2432
|
stream: latencyStats(stream),
|
|
2019
|
-
|
|
2433
|
+
ttft: latencyStats(ttft),
|
|
2434
|
+
tps: latencyStats(tps),
|
|
2435
|
+
requestTps: latencyStats(requestTps)
|
|
2020
2436
|
});
|
|
2021
2437
|
}
|
|
2022
2438
|
return groups.sort((left, right) => right.count - left.count || left.key.localeCompare(right.key));
|
|
@@ -2196,21 +2612,21 @@ function cacheDropsOf(db, rows, options) {
|
|
|
2196
2612
|
}
|
|
2197
2613
|
if (losses.length === 0)
|
|
2198
2614
|
return [];
|
|
2199
|
-
const
|
|
2615
|
+
const times = new Map;
|
|
2200
2616
|
const sessionIDs = [...new Set(losses.map((loss) => loss.current.sessionID))];
|
|
2201
|
-
const
|
|
2202
|
-
WHERE
|
|
2617
|
+
const timeline = db.query(`SELECT session_id, at FROM compactions
|
|
2618
|
+
WHERE at IS NOT NULL AND session_id IN (${sessionIDs.map(() => "?").join(", ")})
|
|
2203
2619
|
ORDER BY at`).all(...sessionIDs);
|
|
2204
|
-
for (const
|
|
2205
|
-
const list =
|
|
2620
|
+
for (const row of timeline) {
|
|
2621
|
+
const list = times.get(row.session_id);
|
|
2206
2622
|
if (list !== undefined)
|
|
2207
|
-
list.push(
|
|
2623
|
+
list.push(row.at);
|
|
2208
2624
|
else
|
|
2209
|
-
|
|
2625
|
+
times.set(row.session_id, [row.at]);
|
|
2210
2626
|
}
|
|
2211
2627
|
return losses.map((loss) => {
|
|
2212
2628
|
const ended = loss.previous.completedAt ?? loss.previous.streamedAt ?? loss.previous.createdAt;
|
|
2213
|
-
const compacted = (
|
|
2629
|
+
const compacted = (times.get(loss.current.sessionID) ?? []).some((time) => ended !== undefined && time >= ended && time <= loss.current.at);
|
|
2214
2630
|
const reason = compacted ? "compaction" : loss.gapMs !== undefined && loss.gapMs >= ttlHint ? "expired" : "unknown";
|
|
2215
2631
|
return {
|
|
2216
2632
|
sessionID: loss.current.sessionID,
|
|
@@ -2229,14 +2645,34 @@ function cacheDropsOf(db, rows, options) {
|
|
|
2229
2645
|
function groupValues(steps) {
|
|
2230
2646
|
const wall = [];
|
|
2231
2647
|
const tps = [];
|
|
2648
|
+
const requestTps = [];
|
|
2649
|
+
const ttft = [];
|
|
2232
2650
|
for (const step of steps) {
|
|
2233
2651
|
const timing = timingOf(step);
|
|
2234
2652
|
if (timing.wall !== undefined)
|
|
2235
2653
|
wall.push(timing.wall);
|
|
2236
2654
|
if (timing.tps !== undefined)
|
|
2237
2655
|
tps.push(timing.tps);
|
|
2656
|
+
if (timing.requestTps !== undefined)
|
|
2657
|
+
requestTps.push(timing.requestTps);
|
|
2658
|
+
if (timing.ttft !== undefined)
|
|
2659
|
+
ttft.push(timing.ttft);
|
|
2238
2660
|
}
|
|
2239
|
-
return {
|
|
2661
|
+
return {
|
|
2662
|
+
cache: cacheStatsOfSteps(steps),
|
|
2663
|
+
tps: latencyStats(tps).p50,
|
|
2664
|
+
requestTps: latencyStats(requestTps).p50,
|
|
2665
|
+
ttft: latencyStats(ttft).p50,
|
|
2666
|
+
wall: latencyStats(wall).p50
|
|
2667
|
+
};
|
|
2668
|
+
}
|
|
2669
|
+
var MODEL_LIST_SEPARATOR = "\x00";
|
|
2670
|
+
function splitModelKey(key) {
|
|
2671
|
+
const separator = key.indexOf(MODEL_KEY_SEPARATOR);
|
|
2672
|
+
if (separator === -1)
|
|
2673
|
+
return { modelID: key, variant: undefined };
|
|
2674
|
+
const variant = key.slice(separator + 1);
|
|
2675
|
+
return { modelID: key.slice(0, separator), variant: variant === "" ? undefined : variant };
|
|
2240
2676
|
}
|
|
2241
2677
|
function providerOf(steps, models) {
|
|
2242
2678
|
const values = groupValues(steps);
|
|
@@ -2250,17 +2686,22 @@ function providerOf(steps, models) {
|
|
|
2250
2686
|
}
|
|
2251
2687
|
return {
|
|
2252
2688
|
provider: steps[0].providerID,
|
|
2253
|
-
models: models.split(
|
|
2689
|
+
models: models.split(MODEL_LIST_SEPARATOR),
|
|
2254
2690
|
share: 0,
|
|
2255
2691
|
usage: usageOf(steps),
|
|
2256
2692
|
cache: values.cache,
|
|
2257
2693
|
tps: values.tps,
|
|
2694
|
+
requestTps: values.requestTps,
|
|
2695
|
+
ttft: values.ttft,
|
|
2258
2696
|
wall: values.wall,
|
|
2259
2697
|
firstAt,
|
|
2260
2698
|
lastAt
|
|
2261
2699
|
};
|
|
2262
2700
|
}
|
|
2263
|
-
var modelNames = (steps) => [...new Set(steps.map((step) => modelKey(step.modelID ?? "(unknown)", step.variant)))].map((key) =>
|
|
2701
|
+
var modelNames = (steps) => [...new Set(steps.map((step) => modelKey(step.modelID ?? "(unknown)", step.variant)))].map((key) => {
|
|
2702
|
+
const { modelID, variant } = splitModelKey(key);
|
|
2703
|
+
return modelLabel(modelID, variant);
|
|
2704
|
+
}).join(MODEL_LIST_SEPARATOR);
|
|
2264
2705
|
function providerSummaryOf(rows) {
|
|
2265
2706
|
const out = [];
|
|
2266
2707
|
for (const steps of groupBy(rows, (step) => step.providerID ?? "").values()) {
|
|
@@ -2273,7 +2714,7 @@ function providerBreakdownOf(rows) {
|
|
|
2273
2714
|
const out = [];
|
|
2274
2715
|
for (const [model, modelRows] of groupBy(rows, (step) => modelKey(step.modelID ?? "(unknown)", step.variant))) {
|
|
2275
2716
|
for (const steps of groupBy(modelRows, (step) => step.providerID ?? "").values()) {
|
|
2276
|
-
const
|
|
2717
|
+
const { modelID, variant } = splitModelKey(model);
|
|
2277
2718
|
out.push({
|
|
2278
2719
|
...providerOf(steps, modelNames(steps)),
|
|
2279
2720
|
modelID,
|
|
@@ -2479,8 +2920,8 @@ var RANGE_KEYS = ["session", "today", "7d", "30d", "all"];
|
|
|
2479
2920
|
var GRANULARITIES = ["day", "week", "month"];
|
|
2480
2921
|
var SORT_KEYS = {
|
|
2481
2922
|
models: ["steps", "cached", "hit", "out", "cost"],
|
|
2482
|
-
providers: ["steps", "cached", "hit", "cost", "share", "tps"],
|
|
2483
|
-
latency: ["n", "tps", "wall"],
|
|
2923
|
+
providers: ["steps", "cached", "hit", "cost", "share", "tps", "ttft"],
|
|
2924
|
+
latency: ["n", "tps", "ttft", "wall"],
|
|
2484
2925
|
sessions: ["last", "steps", "cached", "cost"],
|
|
2485
2926
|
turns: ["time", "cost", "tokens"]
|
|
2486
2927
|
};
|
|
@@ -2578,10 +3019,10 @@ function formatTps(value) {
|
|
|
2578
3019
|
return "\u2013";
|
|
2579
3020
|
return `${value.toFixed(1)}/s`;
|
|
2580
3021
|
}
|
|
2581
|
-
function
|
|
3022
|
+
function formatRateValue(value) {
|
|
2582
3023
|
if (value === undefined || !Number.isFinite(value) || value < 0)
|
|
2583
3024
|
return "\u2013";
|
|
2584
|
-
return value >= 10 ?
|
|
3025
|
+
return value >= 10 ? String(Math.round(value)) : value.toFixed(1);
|
|
2585
3026
|
}
|
|
2586
3027
|
function formatGap(value) {
|
|
2587
3028
|
if (value === undefined || !Number.isFinite(value))
|
|
@@ -2812,7 +3253,11 @@ function helpLines(width) {
|
|
|
2812
3253
|
{ text: " \u2248 list-price estimate for steps the host reported as $0;" },
|
|
2813
3254
|
{ text: " `$0.12 + \u2248 $3.40` keeps charged and estimated money apart" },
|
|
2814
3255
|
{ text: " wall request \u2192 completed step \xB7 stream request \u2192 last chunk" },
|
|
2815
|
-
{ text: "
|
|
3256
|
+
{ text: " ttft request \u2192 first streamed token" },
|
|
3257
|
+
{ text: " tps output+reasoning / first token \u2192 last chunk (OpenCode)" },
|
|
3258
|
+
{ text: " rtps output+reasoning / request \u2192 last chunk (includes TTFT)" },
|
|
3259
|
+
{ text: " turn 200 tps \xB7 2.1s ttft \xB7 cost" },
|
|
3260
|
+
{ text: " session 200 tps \xB7 167 rtps \xB7 ttft p50 \xB7 cost" },
|
|
2816
3261
|
{ text: " switches how often a step's model or provider differs from the step" },
|
|
2817
3262
|
{ text: " before it in the same session (the models view's detail), with" },
|
|
2818
3263
|
{ text: " the cache a provider switch cost" },
|
|
@@ -2941,12 +3386,16 @@ function usagePairs(usage, estimates = true) {
|
|
|
2941
3386
|
];
|
|
2942
3387
|
if (buckets.reasoning > 0)
|
|
2943
3388
|
pairs.push(["reasoning", formatTokens(buckets.reasoning)]);
|
|
3389
|
+
if ("tps" in usage && usage.tps !== undefined)
|
|
3390
|
+
pairs.push(["tps", formatTps(usage.tps)]);
|
|
3391
|
+
if ("requestTps" in usage && usage.requestTps !== undefined)
|
|
3392
|
+
pairs.push(["rtps", formatTps(usage.requestTps)]);
|
|
3393
|
+
if ("ttft" in usage && usage.ttft !== undefined)
|
|
3394
|
+
pairs.push(["ttft p50", formatMs(usage.ttft)]);
|
|
2944
3395
|
pairs.push(["cost", (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost)]);
|
|
2945
3396
|
const other = usage.otherCost ?? 0;
|
|
2946
3397
|
if (other > 0)
|
|
2947
3398
|
pairs.push(["other", `${formatCost(other)} comp/title`]);
|
|
2948
|
-
if ("tps" in usage && usage.tps !== undefined)
|
|
2949
|
-
pairs.push(["tps", formatTps(usage.tps)]);
|
|
2950
3399
|
return pairs;
|
|
2951
3400
|
}
|
|
2952
3401
|
function overviewLines(data, width) {
|
|
@@ -2999,6 +3448,7 @@ function coveragePairs(coverage) {
|
|
|
2999
3448
|
["models", `${formatCount(coverage.models)} \xB7 unknown ${share(coverage.missingModel)}`],
|
|
3000
3449
|
["providers", formatCount(coverage.providers)],
|
|
3001
3450
|
["unsettled", `${formatCount(coverage.unsettled)} \xB7 no tps ${share(coverage.missingTps)}`],
|
|
3451
|
+
["no ttft", share(coverage.missingFirstToken)],
|
|
3002
3452
|
[
|
|
3003
3453
|
"window",
|
|
3004
3454
|
`${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 +3559,8 @@ function providerSummaryLines(rows, width, limit = 40, estimates = true) {
|
|
|
3109
3559
|
{ header: "cached", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
|
|
3110
3560
|
{ header: "hit", width: 6, max: 7, align: "right", priority: 2, cell: (row) => formatPercent(row.cache.hit) },
|
|
3111
3561
|
{ header: "tps p50", width: 8, align: "right", priority: 5, cell: (row) => formatTps(row.tps) },
|
|
3112
|
-
{ header: "
|
|
3562
|
+
{ header: "ttft p50", width: 8, max: 9, align: "right", priority: 6, cell: (row) => formatMs(row.ttft) },
|
|
3563
|
+
{ header: "wall", width: 7, align: "right", priority: 7, cell: (row) => formatMs(row.wall) },
|
|
3113
3564
|
{ header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
|
|
3114
3565
|
], width, {
|
|
3115
3566
|
limit,
|
|
@@ -3129,7 +3580,8 @@ function providerLines(rows, width, limit = 40, estimates = true) {
|
|
|
3129
3580
|
{ header: "cached", width: 7, max: 10, align: "right", priority: 3, cell: (row) => formatTokens(row.cache.cached) },
|
|
3130
3581
|
{ header: "hit", width: 6, max: 7, align: "right", priority: 4, cell: (row) => formatPercent(row.cache.hit) },
|
|
3131
3582
|
{ header: "tps p50", width: 8, align: "right", priority: 6, cell: (row) => formatTps(row.tps) },
|
|
3132
|
-
{ header: "
|
|
3583
|
+
{ header: "ttft p50", width: 8, max: 9, align: "right", priority: 7, cell: (row) => formatMs(row.ttft) },
|
|
3584
|
+
{ header: "wall", width: 7, align: "right", priority: 8, cell: (row) => formatMs(row.wall) },
|
|
3133
3585
|
{ header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
|
|
3134
3586
|
], width, {
|
|
3135
3587
|
limit,
|
|
@@ -3367,7 +3819,15 @@ function latencyLines(report, width, groups, limit = 12, estimates = true) {
|
|
|
3367
3819
|
tone: "base"
|
|
3368
3820
|
});
|
|
3369
3821
|
lines.push({
|
|
3370
|
-
text: formatTableRow(["
|
|
3822
|
+
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]),
|
|
3823
|
+
tone: "base"
|
|
3824
|
+
});
|
|
3825
|
+
lines.push({
|
|
3826
|
+
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]),
|
|
3827
|
+
tone: "base"
|
|
3828
|
+
});
|
|
3829
|
+
lines.push({
|
|
3830
|
+
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
3831
|
tone: "base"
|
|
3372
3832
|
});
|
|
3373
3833
|
} else {
|
|
@@ -3380,13 +3840,25 @@ function latencyLines(report, width, groups, limit = 12, estimates = true) {
|
|
|
3380
3840
|
tone: "base"
|
|
3381
3841
|
});
|
|
3382
3842
|
lines.push({
|
|
3383
|
-
text: latencyMetric("
|
|
3843
|
+
text: latencyMetric("ttft", [`p50 ${formatMs(report.ttft.p50)}`, `p90 ${formatMs(report.ttft.p90)}`, `p99 ${formatMs(report.ttft.p99)}`], width),
|
|
3844
|
+
tone: "base"
|
|
3845
|
+
});
|
|
3846
|
+
lines.push({
|
|
3847
|
+
text: latencyMetric("tps", [`p50 ${formatTps(report.tps.p50)}`, `p90 ${formatTps(report.tps.p90)}`, `p99 ${formatTps(report.tps.p99)}`], width),
|
|
3848
|
+
tone: "base"
|
|
3849
|
+
});
|
|
3850
|
+
lines.push({
|
|
3851
|
+
text: latencyMetric("rtps", [`p50 ${formatTps(report.requestTps.p50)}`, `p90 ${formatTps(report.requestTps.p90)}`, `p99 ${formatTps(report.requestTps.p99)}`], width),
|
|
3384
3852
|
tone: "base"
|
|
3385
3853
|
});
|
|
3386
3854
|
}
|
|
3387
3855
|
lines.push({ text: "", tone: "muted" });
|
|
3388
3856
|
lines.push({
|
|
3389
|
-
text: truncate("wall = request to completed \xB7 stream = request to last chunk
|
|
3857
|
+
text: truncate("wall = request to completed \xB7 stream = request to last chunk", width),
|
|
3858
|
+
tone: "muted"
|
|
3859
|
+
});
|
|
3860
|
+
lines.push({
|
|
3861
|
+
text: truncate("ttft = request to first token \xB7 tps = first token to last chunk \xB7 rtps = request to last chunk", width),
|
|
3390
3862
|
tone: "muted"
|
|
3391
3863
|
});
|
|
3392
3864
|
if (report.wall.count === 0)
|
|
@@ -3401,7 +3873,8 @@ function latencyLines(report, width, groups, limit = 12, estimates = true) {
|
|
|
3401
3873
|
{ header: "wall p90", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatMs(row.wall.p90) },
|
|
3402
3874
|
{ header: "stream", width: 6, max: 9, align: "right", priority: 2, cell: (row) => formatMs(row.stream.p50) },
|
|
3403
3875
|
{ 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:
|
|
3876
|
+
{ header: "tps p90", width: 8, max: 9, align: "right", priority: 4, cell: (row) => formatTps(row.tps.p90) },
|
|
3877
|
+
{ header: "ttft p50", width: 8, max: 9, align: "right", priority: 3, cell: (row) => formatMs(row.ttft.p50) },
|
|
3405
3878
|
{ header: "cost", width: 8, max: 9, align: "right", cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
|
|
3406
3879
|
], width);
|
|
3407
3880
|
if (columns.length > 0) {
|
|
@@ -3630,7 +4103,9 @@ function sessionSummaryLines(usage, budget = 34, estimates = true) {
|
|
|
3630
4103
|
const cached = formatTokens(buckets.cached);
|
|
3631
4104
|
const out = formatTokens(buckets.output);
|
|
3632
4105
|
const hit = formatPercent(buckets.hit);
|
|
3633
|
-
const tps =
|
|
4106
|
+
const tps = usage.tps === undefined ? undefined : `${formatRateValue(usage.tps)} tps`;
|
|
4107
|
+
const rtps = usage.requestTps === undefined ? undefined : `${formatRateValue(usage.requestTps)} rtps`;
|
|
4108
|
+
const ttft = usage.ttft === undefined ? undefined : `ttft p50 ${formatMs(usage.ttft)}`;
|
|
3634
4109
|
const cost = (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost);
|
|
3635
4110
|
const first = [
|
|
3636
4111
|
` ${steps} steps \xB7 in ${input}`,
|
|
@@ -3640,16 +4115,22 @@ function sessionSummaryLines(usage, budget = 34, estimates = true) {
|
|
|
3640
4115
|
` cached ${cached} \xB7 out ${out}`,
|
|
3641
4116
|
` cached ${cached}`
|
|
3642
4117
|
].find((text) => text.length <= budget);
|
|
3643
|
-
const
|
|
3644
|
-
|
|
3645
|
-
` hit ${hit} \xB7 ${
|
|
3646
|
-
` ${
|
|
4118
|
+
const rates = [tps, rtps].filter((part) => part !== undefined);
|
|
4119
|
+
const rateLine = [
|
|
4120
|
+
` hit ${hit}${rates.length > 0 ? ` \xB7 ${rates.join(" \xB7 ")}` : ""}`,
|
|
4121
|
+
` hit ${hit}${rates[0] !== undefined ? ` \xB7 ${rates[0]}` : ""}`,
|
|
4122
|
+
` hit ${hit}`
|
|
3647
4123
|
].find((text) => text.length <= budget);
|
|
4124
|
+
const tail = [
|
|
4125
|
+
ttft === undefined ? undefined : ` ${ttft} \xB7 ${cost}`,
|
|
4126
|
+
` ${cost}`
|
|
4127
|
+
].filter((text) => text !== undefined).find((text) => text.length <= budget);
|
|
3648
4128
|
return [
|
|
3649
4129
|
{ text: truncate("session", budget), tone: HEADER_TONE },
|
|
3650
4130
|
{ text: truncate(first ?? ` ${steps} steps`, budget), tone: "muted" },
|
|
3651
4131
|
{ text: truncate(second ?? ` cached ${cached}`, budget), tone: "base" },
|
|
3652
|
-
{ text: truncate(
|
|
4132
|
+
{ text: truncate(rateLine ?? ` hit ${hit}`, budget), tone: "base" },
|
|
4133
|
+
{ text: truncate(tail ?? ` ${cost}`, budget), tone: "base" },
|
|
3653
4134
|
{ text: "", tone: "muted" }
|
|
3654
4135
|
];
|
|
3655
4136
|
}
|
|
@@ -3666,20 +4147,28 @@ function sidebarLines(rows, options) {
|
|
|
3666
4147
|
const output = formatTokens(display.output);
|
|
3667
4148
|
const cost = options?.estimates === false ? formatCost(turn.totals.cost) : formatMoney(turn.totals.cost, turn.totals.listCost) ?? formatCost(turn.totals.cost);
|
|
3668
4149
|
const hit = formatPercent(display.prompt > 0 ? display.cached / display.prompt : undefined).replace(/\.0%$/, "%");
|
|
3669
|
-
const tps = turn.tps === undefined ? undefined :
|
|
4150
|
+
const tps = turn.tps === undefined ? undefined : `${formatRateValue(turn.tps)} tps`;
|
|
4151
|
+
const ttft = turn.ttft === undefined ? undefined : `${formatMs(turn.ttft)} ttft`;
|
|
4152
|
+
const rate = [tps, ttft].filter((part) => part !== undefined).join(" \xB7 ");
|
|
3670
4153
|
const suffix = turn.drops.length > 0 ? " \xB7 \u26A0" : "";
|
|
3671
4154
|
const header = `${clock} ${provider}`;
|
|
3672
4155
|
const timed = turn.durationMs === undefined ? undefined : `${header} \xB7 ${formatMs(turn.durationMs)}`;
|
|
4156
|
+
const join = (...parts) => parts.filter((part) => part !== undefined && part !== "").join(" \xB7 ");
|
|
3673
4157
|
const volumes = [
|
|
3674
|
-
` ${labels.input} ${input} (${prompt}) \xB7 ${labels.output} ${output}`,
|
|
4158
|
+
` ${labels.input} ${input} (${prompt}) \xB7 ${labels.output} ${output} \xB7 hit ${hit}`,
|
|
4159
|
+
` ${labels.input} ${input} \xB7 ${labels.output} ${output} \xB7 hit ${hit}`,
|
|
3675
4160
|
` ${labels.input} ${input} \xB7 ${labels.output} ${output}`,
|
|
3676
4161
|
` ${labels.input} ${input}`
|
|
3677
4162
|
];
|
|
4163
|
+
const volume = volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1];
|
|
4164
|
+
const hitPart = volume.includes(`hit ${hit}`) ? undefined : `hit ${hit}`;
|
|
3678
4165
|
const facts = [
|
|
3679
|
-
`
|
|
3680
|
-
`
|
|
3681
|
-
` ${tps
|
|
3682
|
-
`
|
|
4166
|
+
` ${join(hitPart, rate, `${cost}${suffix}`)}`,
|
|
4167
|
+
` ${join(hitPart, tps, `${cost}${suffix}`)}`,
|
|
4168
|
+
` ${join(tps, `${cost}${suffix}`)}`,
|
|
4169
|
+
` ${join(tps)}`,
|
|
4170
|
+
` ${join(hitPart, `${cost}${suffix}`)}`,
|
|
4171
|
+
` ${join(`${cost}${suffix}`)}`
|
|
3683
4172
|
];
|
|
3684
4173
|
lines.push({ text: truncate(timed !== undefined && timed.length <= budget ? timed : header, budget), tone: turn.providerChanged ? "warning" : "base" });
|
|
3685
4174
|
const edge = index === 0 || index === rows.length - 1;
|
|
@@ -3687,10 +4176,7 @@ function sidebarLines(rows, options) {
|
|
|
3687
4176
|
const model = turn.modelID === undefined ? "unknown" : `${turn.modelID}${turn.variant === undefined ? "" : ` ${turn.variant}`}`;
|
|
3688
4177
|
lines.push({ text: truncate(` ${model}`, budget), tone: "muted" });
|
|
3689
4178
|
}
|
|
3690
|
-
lines.push({
|
|
3691
|
-
text: truncate(volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1], budget),
|
|
3692
|
-
tone: "muted"
|
|
3693
|
-
});
|
|
4179
|
+
lines.push({ text: truncate(volume, budget), tone: "muted" });
|
|
3694
4180
|
lines.push({
|
|
3695
4181
|
text: truncate(facts.find((text) => text.length <= budget) ?? facts[facts.length - 1], budget),
|
|
3696
4182
|
tone: turn.drops.length > 0 ? "warning" : "muted"
|
|
@@ -3932,6 +4418,8 @@ function sortProviders(rows, sort, desc, estimates = true) {
|
|
|
3932
4418
|
return row.share;
|
|
3933
4419
|
if (sort === "tps")
|
|
3934
4420
|
return row.tps ?? -1;
|
|
4421
|
+
if (sort === "ttft")
|
|
4422
|
+
return row.ttft ?? -1;
|
|
3935
4423
|
return row.usage.steps;
|
|
3936
4424
|
};
|
|
3937
4425
|
return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
|
|
@@ -3941,6 +4429,8 @@ function sortLatency(rows, sort, desc) {
|
|
|
3941
4429
|
const pick = (row) => {
|
|
3942
4430
|
if (sort === "tps")
|
|
3943
4431
|
return row.tps.p50 ?? -1;
|
|
4432
|
+
if (sort === "ttft")
|
|
4433
|
+
return row.ttft.p50 ?? -1;
|
|
3944
4434
|
if (sort === "wall")
|
|
3945
4435
|
return row.wall.p50 ?? -1;
|
|
3946
4436
|
return row.count;
|
|
@@ -4017,13 +4507,6 @@ function size(path) {
|
|
|
4017
4507
|
return 0;
|
|
4018
4508
|
}
|
|
4019
4509
|
}
|
|
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
4510
|
function dbInfo(db, path, now = Date.now()) {
|
|
4028
4511
|
const tables = TABLES.map((table) => ({
|
|
4029
4512
|
name: table,
|
|
@@ -4077,7 +4560,7 @@ function pruneOlderThan(db, cutoff) {
|
|
|
4077
4560
|
return {
|
|
4078
4561
|
steps: deleteBatched(db, "steps", `${STEP_TIME2} < ?`, cutoff),
|
|
4079
4562
|
prompts: deleteBatched(db, "prompts", "created_at IS NOT NULL AND created_at < ?", cutoff),
|
|
4080
|
-
|
|
4563
|
+
compactions: deleteBatched(db, "compactions", "at IS NOT NULL AND at < ?", cutoff),
|
|
4081
4564
|
usage: hasTable(db, "usage") ? deleteBatched(db, "usage", "at IS NOT NULL AND at < ?", cutoff) : 0
|
|
4082
4565
|
};
|
|
4083
4566
|
}
|
|
@@ -4085,7 +4568,7 @@ function wipeAll(db) {
|
|
|
4085
4568
|
return {
|
|
4086
4569
|
steps: deleteAllBatched(db, "steps"),
|
|
4087
4570
|
prompts: deleteAllBatched(db, "prompts"),
|
|
4088
|
-
|
|
4571
|
+
compactions: deleteAllBatched(db, "compactions"),
|
|
4089
4572
|
usage: hasTable(db, "usage") ? deleteAllBatched(db, "usage") : 0,
|
|
4090
4573
|
sessions: hasTable(db, "sessions") ? deleteAllBatched(db, "sessions") : 0
|
|
4091
4574
|
};
|
|
@@ -4108,23 +4591,41 @@ function hasListCost(db) {
|
|
|
4108
4591
|
}
|
|
4109
4592
|
}
|
|
4110
4593
|
var BACKFILL_BATCH = 1000;
|
|
4594
|
+
var UNPRICED_WHERE = `cost = 0 AND list_cost IS NULL
|
|
4595
|
+
AND provider_id IS NOT NULL AND provider_id <> ''
|
|
4596
|
+
AND model_id IS NOT NULL AND model_id <> ''
|
|
4597
|
+
AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`;
|
|
4598
|
+
function priceStep(step, price) {
|
|
4599
|
+
const estimate = price({ providerID: step.provider_id ?? undefined, modelID: step.model_id ?? undefined }, {
|
|
4600
|
+
input: step.input_tokens ?? 0,
|
|
4601
|
+
output: step.output_tokens ?? 0,
|
|
4602
|
+
reasoning: step.reasoning_tokens ?? 0,
|
|
4603
|
+
cacheRead: step.cache_read ?? 0,
|
|
4604
|
+
cacheWrite: step.cache_write ?? 0
|
|
4605
|
+
});
|
|
4606
|
+
return estimate !== undefined && Number.isFinite(estimate) && estimate >= 0 ? estimate : undefined;
|
|
4607
|
+
}
|
|
4608
|
+
function backfillBatch(db, rows, price, update) {
|
|
4609
|
+
let updated = 0;
|
|
4610
|
+
db.transaction(() => {
|
|
4611
|
+
for (const row of rows) {
|
|
4612
|
+
const estimate = priceStep(row, price);
|
|
4613
|
+
if (estimate !== undefined && update(estimate, row.rowid) > 0)
|
|
4614
|
+
updated += 1;
|
|
4615
|
+
}
|
|
4616
|
+
})();
|
|
4617
|
+
return updated;
|
|
4618
|
+
}
|
|
4111
4619
|
function backfillListCost(db, price) {
|
|
4112
4620
|
if (!hasListCost(db))
|
|
4113
4621
|
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;
|
|
4622
|
+
const candidates = db.query(`SELECT COUNT(*) AS n FROM steps WHERE ${UNPRICED_WHERE}`).get().n;
|
|
4119
4623
|
if (candidates === 0)
|
|
4120
4624
|
return { candidates: 0, updated: 0 };
|
|
4121
4625
|
const select = db.query(`SELECT rowid, provider_id, model_id,
|
|
4122
4626
|
input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
|
|
4123
4627
|
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
|
|
4628
|
+
WHERE ${UNPRICED_WHERE} AND rowid > ?
|
|
4128
4629
|
ORDER BY rowid
|
|
4129
4630
|
LIMIT ?`);
|
|
4130
4631
|
const update = db.query("UPDATE steps SET list_cost = ? WHERE rowid = ? AND cost = 0 AND list_cost IS NULL");
|
|
@@ -4134,21 +4635,7 @@ function backfillListCost(db, price) {
|
|
|
4134
4635
|
const rows = select.all(cursor, BACKFILL_BATCH);
|
|
4135
4636
|
if (rows.length === 0)
|
|
4136
4637
|
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
|
-
})();
|
|
4638
|
+
updated += backfillBatch(db, rows, price, (estimate, rowid) => update.run(estimate, rowid).changes);
|
|
4152
4639
|
cursor = rows[rows.length - 1].rowid;
|
|
4153
4640
|
if (rows.length < BACKFILL_BATCH)
|
|
4154
4641
|
break;
|
|
@@ -4337,6 +4824,7 @@ class StatsClient {
|
|
|
4337
4824
|
startPromise;
|
|
4338
4825
|
starting;
|
|
4339
4826
|
startAbort;
|
|
4827
|
+
abortStart;
|
|
4340
4828
|
fallbackService;
|
|
4341
4829
|
fallbackMode = false;
|
|
4342
4830
|
stopped = false;
|
|
@@ -4345,6 +4833,13 @@ class StatsClient {
|
|
|
4345
4833
|
constructor(config) {
|
|
4346
4834
|
this.config = config;
|
|
4347
4835
|
}
|
|
4836
|
+
reconfigure(options) {
|
|
4837
|
+
this.config.options = options;
|
|
4838
|
+
this.fallbackService = undefined;
|
|
4839
|
+
if (this.worker !== undefined || this.starting !== undefined) {
|
|
4840
|
+
this.hardReset("the usage service was reconfigured", false);
|
|
4841
|
+
}
|
|
4842
|
+
}
|
|
4348
4843
|
request(method, input, options = {}) {
|
|
4349
4844
|
if (this.stopped)
|
|
4350
4845
|
return Promise.reject(new StatsError("unavailable", "the usage service is stopped"));
|
|
@@ -4365,7 +4860,9 @@ class StatsClient {
|
|
|
4365
4860
|
return;
|
|
4366
4861
|
this.stopped = true;
|
|
4367
4862
|
this.rejectAll(new StatsError("unavailable", "the usage service stopped"));
|
|
4863
|
+
this.abortStart?.();
|
|
4368
4864
|
this.startAbort?.();
|
|
4865
|
+
this.abortStart = undefined;
|
|
4369
4866
|
this.worker?.terminate();
|
|
4370
4867
|
this.worker = undefined;
|
|
4371
4868
|
this.starting = undefined;
|
|
@@ -4421,7 +4918,7 @@ class StatsClient {
|
|
|
4421
4918
|
}
|
|
4422
4919
|
this.starting = worker;
|
|
4423
4920
|
let timer;
|
|
4424
|
-
const finish = (ok, reason) => {
|
|
4921
|
+
const finish = (ok, reason, useFallback = true) => {
|
|
4425
4922
|
if (settled)
|
|
4426
4923
|
return;
|
|
4427
4924
|
settled = true;
|
|
@@ -4430,6 +4927,7 @@ class StatsClient {
|
|
|
4430
4927
|
this.startPromise = undefined;
|
|
4431
4928
|
this.starting = undefined;
|
|
4432
4929
|
this.startAbort = undefined;
|
|
4930
|
+
this.abortStart = undefined;
|
|
4433
4931
|
if (this.stopped) {
|
|
4434
4932
|
worker.terminate();
|
|
4435
4933
|
this.worker = undefined;
|
|
@@ -4438,11 +4936,13 @@ class StatsClient {
|
|
|
4438
4936
|
}
|
|
4439
4937
|
if (!ok) {
|
|
4440
4938
|
worker.terminate();
|
|
4441
|
-
|
|
4939
|
+
if (useFallback)
|
|
4940
|
+
this.useFallback(reason ?? "the usage worker did not start");
|
|
4442
4941
|
}
|
|
4443
4942
|
resolve();
|
|
4444
4943
|
};
|
|
4445
|
-
this.startAbort = () => finish(false, "the usage service stopped");
|
|
4944
|
+
this.startAbort = () => finish(false, "the usage service stopped", false);
|
|
4945
|
+
this.abortStart = () => finish(false, "the usage service was reconfigured", false);
|
|
4446
4946
|
timer = setTimeout(() => finish(false, "the usage worker did not start in time"), this.config.timeouts?.start ?? START_TIMEOUT_MS);
|
|
4447
4947
|
worker.onmessage = (event) => {
|
|
4448
4948
|
const message = event.data;
|
|
@@ -4556,9 +5056,12 @@ class StatsClient {
|
|
|
4556
5056
|
pending.reject(error);
|
|
4557
5057
|
}
|
|
4558
5058
|
}
|
|
4559
|
-
hardReset(message) {
|
|
4560
|
-
|
|
5059
|
+
hardReset(message, log = true) {
|
|
5060
|
+
if (log)
|
|
5061
|
+
this.config.log?.(message);
|
|
4561
5062
|
this.rejectAll(new StatsError("unavailable", message));
|
|
5063
|
+
this.abortStart?.();
|
|
5064
|
+
this.abortStart = undefined;
|
|
4562
5065
|
this.worker?.terminate();
|
|
4563
5066
|
this.worker = undefined;
|
|
4564
5067
|
this.starting?.terminate();
|
|
@@ -4629,123 +5132,140 @@ function rpcFailure(context, error) {
|
|
|
4629
5132
|
return context.error(error.code, error.message);
|
|
4630
5133
|
return context.error("unavailable", "the usage database is unavailable");
|
|
4631
5134
|
}
|
|
5135
|
+
function serviceOptionsFor(settings, policy) {
|
|
5136
|
+
return {
|
|
5137
|
+
pricing: settings.pricing,
|
|
5138
|
+
maintenance: policy.maintenance,
|
|
5139
|
+
exposePaths: policy.exposePaths,
|
|
5140
|
+
format: {
|
|
5141
|
+
labels: settings.labels,
|
|
5142
|
+
fields: settings.fields,
|
|
5143
|
+
turnTotals: settings.turnTotals,
|
|
5144
|
+
estimates: settings.pricing
|
|
5145
|
+
}
|
|
5146
|
+
};
|
|
5147
|
+
}
|
|
4632
5148
|
var src_default = Plugin.define({
|
|
4633
5149
|
id: "usage-insights",
|
|
4634
5150
|
async setup(ctx) {
|
|
4635
|
-
|
|
4636
|
-
|
|
4637
|
-
|
|
4638
|
-
const
|
|
4639
|
-
const
|
|
4640
|
-
|
|
5151
|
+
if (Object.keys(ctx.options ?? {}).length > 0) {
|
|
5152
|
+
console.warn("[usage-insights] plugin options in opencode.json(c) are no longer read; edit the settings in the TUI or Desktop instead");
|
|
5153
|
+
}
|
|
5154
|
+
const policy = serverPolicy();
|
|
5155
|
+
const path = resolveDbPath();
|
|
5156
|
+
const stored = await ctx.storage.get(SETTINGS_STORAGE_KEY).catch(() => {
|
|
5157
|
+
console.warn("[usage-insights] could not read the shared settings; using the defaults");
|
|
4641
5158
|
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
5159
|
});
|
|
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
|
-
|
|
5160
|
+
let settings = sanitizeUsageSettings(stored);
|
|
5161
|
+
const source = createPriceSource(ctx);
|
|
5162
|
+
if (settings.pricing)
|
|
5163
|
+
source.refresh(true);
|
|
5164
|
+
let runtime;
|
|
5165
|
+
let serviceOptions = serviceOptionsFor(settings, policy);
|
|
5166
|
+
let nextOpenAttempt = 0;
|
|
5167
|
+
function ensureRuntime() {
|
|
5168
|
+
if (runtime !== undefined)
|
|
5169
|
+
return runtime;
|
|
5170
|
+
const now = Date.now();
|
|
5171
|
+
if (now < nextOpenAttempt)
|
|
5172
|
+
return;
|
|
5173
|
+
const db = tryOpen(path);
|
|
5174
|
+
if (db === undefined) {
|
|
5175
|
+
nextOpenAttempt = now + 5000;
|
|
5176
|
+
return;
|
|
5177
|
+
}
|
|
5178
|
+
try {
|
|
5179
|
+
db.exec("PRAGMA busy_timeout = 1000");
|
|
5180
|
+
} catch {}
|
|
5181
|
+
const stats = new StatsClient({
|
|
5182
|
+
dbPath: path,
|
|
5183
|
+
options: serviceOptions,
|
|
5184
|
+
priceTable: () => source.table(),
|
|
5185
|
+
fallback: () => createService(() => db, {
|
|
5186
|
+
...serviceOptions,
|
|
5187
|
+
path,
|
|
5188
|
+
priceTable: () => source.table()
|
|
5189
|
+
}),
|
|
5190
|
+
log: (message) => console.warn(`[usage-insights] ${message}`)
|
|
5191
|
+
});
|
|
5192
|
+
const recorder = createRecorder(db, {
|
|
5193
|
+
price: (ref, tokens) => settings.pricing ? source.price(ref, tokens) : undefined
|
|
5194
|
+
});
|
|
5195
|
+
runtime = { db, stats, recorder };
|
|
5196
|
+
return runtime;
|
|
5197
|
+
}
|
|
5198
|
+
function applySettings(next) {
|
|
5199
|
+
const previous = settings;
|
|
5200
|
+
settings = next;
|
|
5201
|
+
if (next.pricing && !previous.pricing)
|
|
5202
|
+
source.refresh(true);
|
|
5203
|
+
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);
|
|
5204
|
+
if (!serverChanged)
|
|
5205
|
+
return;
|
|
5206
|
+
serviceOptions = serviceOptionsFor(settings, policy);
|
|
5207
|
+
runtime?.stats.reconfigure(serviceOptions);
|
|
5208
|
+
}
|
|
5209
|
+
const envelope = () => ({ settings, policy });
|
|
5210
|
+
let notifySettings;
|
|
5211
|
+
const settingsRegistration = await ctx.rpc.register(UsageInsightsSettings, {
|
|
5212
|
+
get: async () => envelope(),
|
|
5213
|
+
set: async (input) => {
|
|
5214
|
+
const next = mergeUsageSettings(settings, input.patch);
|
|
5215
|
+
await ctx.storage.set(SETTINGS_STORAGE_KEY, next);
|
|
5216
|
+
applySettings(next);
|
|
5217
|
+
const saved = envelope();
|
|
5218
|
+
await notifySettings?.(saved).catch(() => {});
|
|
5219
|
+
return saved;
|
|
4723
5220
|
},
|
|
4724
|
-
|
|
4725
|
-
|
|
4726
|
-
|
|
4727
|
-
|
|
4728
|
-
|
|
4729
|
-
|
|
5221
|
+
reset: async () => {
|
|
5222
|
+
await ctx.storage.remove(SETTINGS_STORAGE_KEY);
|
|
5223
|
+
applySettings(defaultUsageSettings());
|
|
5224
|
+
const saved = envelope();
|
|
5225
|
+
await notifySettings?.(saved).catch(() => {});
|
|
5226
|
+
return saved;
|
|
5227
|
+
}
|
|
5228
|
+
});
|
|
5229
|
+
notifySettings = (next) => settingsRegistration.events.emit("updated", next);
|
|
5230
|
+
async function request(method, input, context) {
|
|
5231
|
+
const current = ensureRuntime();
|
|
5232
|
+
if (current === undefined)
|
|
5233
|
+
return context.error("unavailable", "the usage database is unavailable");
|
|
5234
|
+
try {
|
|
5235
|
+
return await current.stats.request(method, input);
|
|
5236
|
+
} catch (error) {
|
|
5237
|
+
return rpcFailure(context, error);
|
|
4730
5238
|
}
|
|
4731
|
-
}
|
|
4732
|
-
|
|
4733
|
-
|
|
5239
|
+
}
|
|
5240
|
+
const dataRegistration = await ctx.rpc.register(UsageInsights, {
|
|
5241
|
+
panel: (input, context) => request("panel", input, context),
|
|
5242
|
+
turns: (input, context) => request("turns", input, context),
|
|
5243
|
+
listCost: (input, context) => request("listCost", input, context),
|
|
5244
|
+
filters: (_input, context) => request("filters", {}, context),
|
|
5245
|
+
dbInfo: (_input, context) => request("dbInfo", {}, context),
|
|
5246
|
+
prune: (input, context) => request("prune", input, context),
|
|
5247
|
+
wipe: (input, context) => request("wipe", input, context),
|
|
5248
|
+
vacuum: (input, context) => request("vacuum", input, context),
|
|
5249
|
+
backfill: (input, context) => request("backfill", input, context)
|
|
5250
|
+
}).catch(async (error) => {
|
|
5251
|
+
await settingsRegistration.dispose().catch(() => {});
|
|
5252
|
+
runtime?.stats.stop();
|
|
5253
|
+
runtime?.db.close();
|
|
4734
5254
|
throw error;
|
|
4735
5255
|
});
|
|
4736
|
-
|
|
5256
|
+
ensureRuntime();
|
|
4737
5257
|
const abort = new AbortController;
|
|
4738
5258
|
const stream = (async () => {
|
|
4739
5259
|
try {
|
|
4740
5260
|
for await (const event of ctx.event.subscribe({ signal: abort.signal })) {
|
|
4741
5261
|
try {
|
|
4742
|
-
if (event.type === "model.updated")
|
|
4743
|
-
source
|
|
4744
|
-
recorder.handleEvent(event);
|
|
5262
|
+
if (event.type === "model.updated" && settings.pricing)
|
|
5263
|
+
source.refresh(true);
|
|
5264
|
+
runtime?.recorder.handleEvent(event);
|
|
4745
5265
|
if (RECORDED_EVENTS.has(event.type)) {
|
|
4746
5266
|
const data = event.data;
|
|
4747
5267
|
const sessionID = typeof data?.sessionID === "string" ? data.sessionID : undefined;
|
|
4748
|
-
|
|
5268
|
+
dataRegistration.events.emit("recorded", { at: Date.now(), ...sessionID !== undefined ? { sessionID } : {} }).catch(() => {});
|
|
4749
5269
|
}
|
|
4750
5270
|
} catch {}
|
|
4751
5271
|
}
|
|
@@ -4753,10 +5273,10 @@ var src_default = Plugin.define({
|
|
|
4753
5273
|
})();
|
|
4754
5274
|
return async () => {
|
|
4755
5275
|
abort.abort();
|
|
4756
|
-
await
|
|
5276
|
+
await Promise.allSettled([dataRegistration.dispose(), settingsRegistration.dispose()]);
|
|
4757
5277
|
await stream;
|
|
4758
|
-
stats.stop();
|
|
4759
|
-
db.close();
|
|
5278
|
+
runtime?.stats.stop();
|
|
5279
|
+
runtime?.db.close();
|
|
4760
5280
|
};
|
|
4761
5281
|
}
|
|
4762
5282
|
});
|
|
@@ -4764,4 +5284,4 @@ export {
|
|
|
4764
5284
|
src_default as default
|
|
4765
5285
|
};
|
|
4766
5286
|
|
|
4767
|
-
//# debugId=
|
|
5287
|
+
//# debugId=416DE53B4E3B355564756E2164756E21
|