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.
Files changed (57) hide show
  1. package/README.md +66 -542
  2. package/dist/core.d.ts +15 -1
  3. package/dist/gui-experimental.cjs +3 -3
  4. package/dist/index.d.ts +0 -47
  5. package/dist/index.js +1715 -1195
  6. package/dist/index.js.map +23 -16
  7. package/dist/line.d.ts +1 -0
  8. package/dist/panel-data.d.ts +8 -1
  9. package/dist/recorder.d.ts +1 -0
  10. package/dist/rpc.d.ts +4 -4
  11. package/dist/rpc.js +5 -5
  12. package/dist/rpc.js.map +3 -3
  13. package/dist/settings-client.d.ts +29 -0
  14. package/dist/settings-rpc.d.ts +746 -0
  15. package/dist/settings.d.ts +114 -0
  16. package/dist/sidebar.d.ts +3 -3
  17. package/dist/stats/aggregates.d.ts +15 -3
  18. package/dist/stats/constants.d.ts +7 -0
  19. package/dist/stats/db.d.ts +8 -128
  20. package/dist/stats/legacy.d.ts +25 -0
  21. package/dist/stats/maintenance.d.ts +1 -1
  22. package/dist/stats/migrate.d.ts +7 -0
  23. package/dist/stats/ndjson.d.ts +16 -0
  24. package/dist/stats/open.d.ts +15 -0
  25. package/dist/stats/paths.d.ts +5 -4
  26. package/dist/stats/queries.d.ts +25 -31
  27. package/dist/stats/records.d.ts +94 -0
  28. package/dist/stats/schema.d.ts +26 -0
  29. package/dist/stats-client.d.ts +9 -0
  30. package/dist/stats-worker.js +577 -352
  31. package/dist/stats-worker.js.map +17 -12
  32. package/dist/text.d.ts +2 -0
  33. package/dist/tui-settings.d.ts +18 -0
  34. package/dist/tui.d.ts +1 -57
  35. package/dist/tui.js +954 -144
  36. package/dist/tui.js.map +17 -13
  37. package/docs/cli.md +24 -0
  38. package/docs/configuration.md +108 -0
  39. package/docs/costs.md +44 -0
  40. package/docs/demo.md +94 -68
  41. package/docs/desktop.md +91 -0
  42. package/docs/images/desktop-overview-annotated.png +0 -0
  43. package/docs/images/desktop-overview.png +0 -0
  44. package/docs/images/desktop-settings.png +0 -0
  45. package/docs/images/desktop-turns-go-annotated.png +0 -0
  46. package/docs/images/desktop-turns.png +0 -0
  47. package/docs/images/line.png +0 -0
  48. package/docs/images/panel-cache.png +0 -0
  49. package/docs/images/panel-help.png +0 -0
  50. package/docs/images/panel-latency.png +0 -0
  51. package/docs/images/panel-overview.png +0 -0
  52. package/docs/images/panel-providers.png +0 -0
  53. package/docs/images/sidebar.png +0 -0
  54. package/docs/internals.md +87 -36
  55. package/docs/privacy.md +60 -0
  56. package/docs/tui.md +175 -0
  57. package/package.json +2 -1
@@ -1,76 +1,6 @@
1
1
  // @bun
2
- // src/stats/db.ts
3
- import { Database } from "bun:sqlite";
4
- import { chmodSync, mkdirSync } from "fs";
5
- import { dirname } from "path";
6
-
7
- // src/stats/paths.ts
8
- import { homedir } from "os";
9
- import { join } from "path";
10
- import { statSync } from "fs";
11
- function defaultDbPath(env = process.env, platform = process.platform) {
12
- const name = join("opencode", "opencode-usage-insights", "usage.db");
13
- if (platform === "win32") {
14
- return join(env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local"), name);
15
- }
16
- if (platform === "darwin") {
17
- return join(homedir(), "Library", "Application Support", name);
18
- }
19
- return join(env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), name);
20
- }
21
- function expandHome(path, home = homedir()) {
22
- if (path === "~")
23
- return home;
24
- if (path.startsWith("~/") || path.startsWith("~\\"))
25
- return join(home, path.slice(2));
26
- return path;
27
- }
28
- function resolveDbPath(configured, env = process.env, platform = process.platform) {
29
- const home = env.HOME ?? env.USERPROFILE ?? homedir();
30
- if (configured)
31
- return expandHome(configured, home);
32
- if (env.OPENCODE_USAGE_INSIGHTS_DB)
33
- return expandHome(env.OPENCODE_USAGE_INSIGHTS_DB, home);
34
- return defaultDbPath(env, platform);
35
- }
36
- function ensureRegularFile(path) {
37
- let stats;
38
- try {
39
- stats = statSync(path);
40
- } catch {
41
- return;
42
- }
43
- if (!stats.isFile())
44
- throw new Error(`not a regular file: ${path}`);
45
- }
46
-
47
- // src/text.ts
48
- var TEXT_LIMIT = 512;
49
- function sanitizeText(value, limit = TEXT_LIMIT) {
50
- if (limit <= 0)
51
- return "";
52
- let cleaned = "";
53
- for (const character of value) {
54
- const code = character.codePointAt(0) ?? 0;
55
- if (code <= 31 || code === 127 || code >= 128 && code <= 159)
56
- continue;
57
- cleaned += character;
58
- if (cleaned.length >= limit)
59
- break;
60
- }
61
- return cleaned;
62
- }
63
- function sanitizeLabel(value, limit = TEXT_LIMIT) {
64
- return sanitizeText(value, limit).trim();
65
- }
66
- var TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;
67
- function isToken(value, limit = 64) {
68
- return value.length > 0 && value.length <= limit && TOKEN.test(value);
69
- }
70
-
71
- // src/stats/db.ts
72
- var SCHEMA_VERSION = 11;
73
- var LABEL_LIMIT = 4 * TEXT_LIMIT;
2
+ // src/stats/schema.ts
3
+ var SCHEMA_VERSION = 14;
74
4
  var SCHEMA = `
75
5
  CREATE TABLE IF NOT EXISTS meta (
76
6
  key TEXT PRIMARY KEY,
@@ -82,8 +12,7 @@ CREATE TABLE IF NOT EXISTS sessions (
82
12
  parent_id TEXT,
83
13
  directory TEXT,
84
14
  title TEXT,
85
- started_at INTEGER,
86
- updated_at INTEGER
15
+ started_at INTEGER
87
16
  );
88
17
 
89
18
  CREATE TABLE IF NOT EXISTS prompts (
@@ -97,7 +26,6 @@ CREATE INDEX IF NOT EXISTS prompts_created ON prompts(created_at);
97
26
  CREATE TABLE IF NOT EXISTS steps (
98
27
  message_id TEXT PRIMARY KEY,
99
28
  session_id TEXT NOT NULL,
100
- parent_id TEXT,
101
29
  provider_id TEXT,
102
30
  model_id TEXT,
103
31
  variant TEXT,
@@ -109,6 +37,7 @@ CREATE TABLE IF NOT EXISTS steps (
109
37
  cost REAL NOT NULL DEFAULT 0,
110
38
  list_cost REAL,
111
39
  created_at INTEGER,
40
+ first_token_at INTEGER,
112
41
  streamed_at INTEGER,
113
42
  completed_at INTEGER,
114
43
  finish TEXT,
@@ -124,16 +53,18 @@ CREATE INDEX IF NOT EXISTS steps_completed ON steps(completed_at);
124
53
  CREATE INDEX IF NOT EXISTS steps_at ON steps(COALESCE(created_at, recorded_at));
125
54
  CREATE INDEX IF NOT EXISTS steps_session_at ON steps(session_id, COALESCE(created_at, recorded_at));
126
55
 
127
- CREATE TABLE IF NOT EXISTS events (
56
+ -- The compaction timeline: when a compaction ended, by host event ID. The
57
+ -- cost and tokens live in the usage table; the payload that used to be copied
58
+ -- here was never read. Only compactions exist in this table by construction.
59
+ CREATE TABLE IF NOT EXISTS compactions (
128
60
  id INTEGER PRIMARY KEY AUTOINCREMENT,
129
61
  session_id TEXT NOT NULL,
130
- kind TEXT NOT NULL,
131
62
  message_id TEXT,
132
- at INTEGER,
133
- data TEXT
63
+ at INTEGER
134
64
  );
135
- CREATE INDEX IF NOT EXISTS events_session ON events(session_id, at);
136
- CREATE INDEX IF NOT EXISTS events_kind ON events(kind, at);
65
+ CREATE INDEX IF NOT EXISTS compactions_session ON compactions(session_id, at);
66
+ CREATE INDEX IF NOT EXISTS compactions_at ON compactions(at);
67
+ CREATE UNIQUE INDEX IF NOT EXISTS compactions_message ON compactions(message_id) WHERE message_id IS NOT NULL;
137
68
 
138
69
  -- Usage the host reports with no assistant step of its own: the compaction
139
70
  -- summarisation and the session-title generation. The host publishes it as
@@ -155,18 +86,144 @@ CREATE TABLE IF NOT EXISTS usage (
155
86
  CREATE INDEX IF NOT EXISTS usage_session_at ON usage(session_id, at);
156
87
  CREATE INDEX IF NOT EXISTS usage_at ON usage(at);
157
88
  `;
158
- var TABLES = ["sessions", "prompts", "events", "steps", "usage"];
159
- function jsonText(value) {
160
- if (value === undefined || value === null)
161
- return null;
162
- if (typeof value === "string")
163
- return value;
89
+ var TABLES = ["sessions", "prompts", "compactions", "steps", "usage"];
90
+ function hasTable(db, name) {
91
+ try {
92
+ return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== null;
93
+ } catch {
94
+ return false;
95
+ }
96
+ }
97
+ function columnsOf(db, table) {
98
+ if (!hasTable(db, table))
99
+ return new Set;
100
+ return new Set(db.query(`PRAGMA table_info(${table})`).all().map((column) => column.name));
101
+ }
102
+ // src/stats/open.ts
103
+ import { Database } from "bun:sqlite";
104
+ import { chmodSync, mkdirSync } from "fs";
105
+ import { dirname } from "path";
106
+
107
+ // src/stats/paths.ts
108
+ import { homedir } from "os";
109
+ import { join } from "path";
110
+ import { statSync } from "fs";
111
+ function defaultDbPath(env = process.env, platform = process.platform) {
112
+ const name = join("opencode", "opencode-usage-insights", "usage.db");
113
+ if (platform === "win32") {
114
+ return join(env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local"), name);
115
+ }
116
+ if (platform === "darwin") {
117
+ return join(homedir(), "Library", "Application Support", name);
118
+ }
119
+ return join(env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), name);
120
+ }
121
+ function expandHome(path, home = homedir()) {
122
+ if (path === "~")
123
+ return home;
124
+ if (path.startsWith("~/") || path.startsWith("~\\"))
125
+ return join(home, path.slice(2));
126
+ return path;
127
+ }
128
+ function resolveDbPath(configured, env = process.env, platform = process.platform) {
129
+ const home = env.HOME ?? env.USERPROFILE ?? homedir();
130
+ if (configured)
131
+ return expandHome(configured, home);
132
+ if (env.OPENCODE_USAGE_INSIGHTS_DB)
133
+ return expandHome(env.OPENCODE_USAGE_INSIGHTS_DB, home);
134
+ return defaultDbPath(env, platform);
135
+ }
136
+ function ensureRegularFile(path) {
137
+ let stats;
164
138
  try {
165
- return JSON.stringify(value);
139
+ stats = statSync(path);
166
140
  } catch {
167
- return null;
141
+ return;
142
+ }
143
+ if (!stats.isFile())
144
+ throw new Error(`not a regular file: ${path}`);
145
+ }
146
+
147
+ // src/stats/constants.ts
148
+ var COMPACTION_KIND = "compaction";
149
+
150
+ // src/stats/legacy.ts
151
+ function importTimestamp(value) {
152
+ if (typeof value === "number")
153
+ return Number.isFinite(value) ? value : undefined;
154
+ if (typeof value !== "string")
155
+ return;
156
+ const trimmed = value.trim();
157
+ if (trimmed === "")
158
+ return;
159
+ const parsed = Number(trimmed);
160
+ return Number.isFinite(parsed) ? parsed : undefined;
161
+ }
162
+ function numberOrZero(value) {
163
+ const parsed = importTimestamp(value);
164
+ return parsed === undefined ? 0 : Math.max(0, parsed);
165
+ }
166
+ function legacyCompactionUsage(row) {
167
+ if (row.kind !== COMPACTION_KIND)
168
+ return;
169
+ if (row.message_id !== undefined && row.message_id !== null && row.message_id !== "")
170
+ return;
171
+ if (typeof row.session_id !== "string" || row.session_id === "")
172
+ return;
173
+ const at = importTimestamp(row.at);
174
+ if (at === undefined)
175
+ return;
176
+ let payload = row.data;
177
+ if (typeof payload === "string") {
178
+ try {
179
+ payload = JSON.parse(payload);
180
+ } catch {
181
+ return;
182
+ }
183
+ }
184
+ if (typeof payload !== "object" || payload === null)
185
+ return;
186
+ const record = payload;
187
+ const tokens = typeof record.tokens === "object" && record.tokens !== null ? record.tokens : {};
188
+ const cache = typeof tokens.cache === "object" && tokens.cache !== null ? tokens.cache : {};
189
+ return {
190
+ sessionID: row.session_id,
191
+ at,
192
+ cost: numberOrZero(record.cost),
193
+ input: Math.floor(numberOrZero(tokens.input)),
194
+ output: Math.floor(numberOrZero(tokens.output)),
195
+ reasoning: Math.floor(numberOrZero(tokens.reasoning)),
196
+ cacheRead: Math.floor(numberOrZero(cache.read)),
197
+ cacheWrite: Math.floor(numberOrZero(cache.write))
198
+ };
199
+ }
200
+
201
+ // src/text.ts
202
+ var TEXT_LIMIT = 512;
203
+ var LABEL_LIMIT = 4 * TEXT_LIMIT;
204
+ function sanitizeText(value, limit = TEXT_LIMIT) {
205
+ if (limit <= 0)
206
+ return "";
207
+ let cleaned = "";
208
+ for (const character of value) {
209
+ const code = character.codePointAt(0) ?? 0;
210
+ if (code <= 31 || code === 127 || code >= 128 && code <= 159)
211
+ continue;
212
+ cleaned += character;
213
+ if (cleaned.length >= limit)
214
+ break;
168
215
  }
216
+ return cleaned;
217
+ }
218
+ function sanitizeLabel(value, limit = TEXT_LIMIT) {
219
+ return sanitizeText(value, limit).trim();
169
220
  }
221
+ var TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;
222
+ function isToken(value, limit = 64) {
223
+ return value.length > 0 && value.length <= limit && TOKEN.test(value);
224
+ }
225
+
226
+ // src/stats/records.ts
170
227
  function finite(value) {
171
228
  return typeof value === "number" && Number.isFinite(value) ? value : 0;
172
229
  }
@@ -176,85 +233,233 @@ function tokenCount(value) {
176
233
  function timestamp(value) {
177
234
  return typeof value === "number" && Number.isFinite(value) ? value : null;
178
235
  }
179
- var REMOVED_COLUMNS = ["provider_state", "upstream", "upstream_source", "upstream_model", "tps", "router"];
180
- var REMOVED_EVENT_KINDS = ["execution", "step-failed", "model-selected", "usage-recorded"];
236
+ var STEP_UPSERT = `
237
+ INSERT INTO steps (
238
+ message_id, session_id, provider_id, model_id, variant,
239
+ input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost, list_cost,
240
+ created_at, first_token_at, streamed_at, completed_at, finish, recorded_at
241
+ ) VALUES (
242
+ $messageID, $sessionID, $providerID, $modelID, $variant,
243
+ $input, $output, $reasoning, $cacheRead, $cacheWrite, $cost, $listCost,
244
+ $createdAt, $firstTokenAt, $streamedAt, $completedAt, $finish, $recordedAt
245
+ )
246
+ ON CONFLICT(message_id) DO UPDATE SET
247
+ session_id = excluded.session_id,
248
+ provider_id = COALESCE(excluded.provider_id, steps.provider_id),
249
+ model_id = COALESCE(excluded.model_id, steps.model_id),
250
+ variant = COALESCE(excluded.variant, steps.variant),
251
+ input_tokens = excluded.input_tokens,
252
+ output_tokens = excluded.output_tokens,
253
+ reasoning_tokens = excluded.reasoning_tokens,
254
+ cache_read = excluded.cache_read,
255
+ cache_write = excluded.cache_write,
256
+ cost = excluded.cost,
257
+ -- A step that starts being charged loses its estimate; an estimate is
258
+ -- kept when a replayed event arrives without a price table.
259
+ list_cost = CASE WHEN excluded.cost > 0 THEN NULL ELSE COALESCE(excluded.list_cost, steps.list_cost) END,
260
+ created_at = COALESCE(excluded.created_at, steps.created_at),
261
+ first_token_at = COALESCE(excluded.first_token_at, steps.first_token_at),
262
+ streamed_at = COALESCE(excluded.streamed_at, steps.streamed_at),
263
+ completed_at = COALESCE(excluded.completed_at, steps.completed_at),
264
+ finish = COALESCE(excluded.finish, steps.finish),
265
+ recorded_at = excluded.recorded_at
266
+ `;
267
+ function stepCost(record) {
268
+ const cost = Math.max(0, finite(record.cost));
269
+ const listCost = cost <= 0 && typeof record.listCost === "number" && Number.isFinite(record.listCost) && record.listCost >= 0 ? record.listCost : null;
270
+ return { cost, listCost };
271
+ }
272
+ function stepParams(record, cost, listCost) {
273
+ return {
274
+ $messageID: record.messageID,
275
+ $sessionID: record.sessionID,
276
+ $providerID: record.providerID !== undefined && isToken(record.providerID) ? record.providerID : null,
277
+ $modelID: record.modelID ?? null,
278
+ $variant: record.variant ?? null,
279
+ $input: tokenCount(record.input),
280
+ $output: tokenCount(record.output),
281
+ $reasoning: tokenCount(record.reasoning),
282
+ $cacheRead: tokenCount(record.cacheRead),
283
+ $cacheWrite: tokenCount(record.cacheWrite),
284
+ $cost: cost,
285
+ $listCost: listCost,
286
+ $createdAt: timestamp(record.createdAt),
287
+ $firstTokenAt: timestamp(record.firstTokenAt),
288
+ $streamedAt: timestamp(record.streamedAt),
289
+ $completedAt: timestamp(record.completedAt),
290
+ $finish: record.finish === undefined ? null : sanitizeLabel(record.finish, 64),
291
+ $recordedAt: timestamp(record.recordedAt) ?? Date.now()
292
+ };
293
+ }
294
+ function recordStep(db, record) {
295
+ const { cost, listCost } = stepCost(record);
296
+ db.query(STEP_UPSERT).run(stepParams(record, cost, listCost));
297
+ }
298
+ function recordUsage(db, record) {
299
+ if (typeof record.id !== "string" || record.id === "")
300
+ return;
301
+ if (typeof record.sessionID !== "string" || record.sessionID === "")
302
+ return;
303
+ db.query(`INSERT INTO usage (
304
+ id, session_id, source, at, cost, input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
305
+ ) VALUES (
306
+ $id, $sessionID, $source, $at, $cost, $input, $output, $reasoning, $cacheRead, $cacheWrite
307
+ ) ON CONFLICT(id) DO NOTHING`).run({
308
+ $id: record.id,
309
+ $sessionID: record.sessionID,
310
+ $source: sanitizeLabel(record.source, 64),
311
+ $at: timestamp(record.at) ?? Date.now(),
312
+ $cost: Math.max(0, finite(record.cost)),
313
+ $input: tokenCount(record.input),
314
+ $output: tokenCount(record.output),
315
+ $reasoning: tokenCount(record.reasoning),
316
+ $cacheRead: tokenCount(record.cacheRead),
317
+ $cacheWrite: tokenCount(record.cacheWrite)
318
+ });
319
+ }
320
+ function recordPrompt(db, record) {
321
+ db.query(`INSERT INTO prompts (session_id, message_id, created_at)
322
+ VALUES ($sessionID, $messageID, $createdAt)
323
+ ON CONFLICT(session_id, message_id) DO UPDATE SET created_at = COALESCE(excluded.created_at, prompts.created_at)`).run({
324
+ $sessionID: record.sessionID,
325
+ $messageID: record.messageID,
326
+ $createdAt: timestamp(record.createdAt)
327
+ });
328
+ }
329
+ function recordCompaction(db, record) {
330
+ db.query(`INSERT OR IGNORE INTO compactions (session_id, message_id, at)
331
+ VALUES ($sessionID, $messageID, $at)`).run({
332
+ $sessionID: record.sessionID,
333
+ $messageID: record.messageID ?? null,
334
+ $at: timestamp(record.at) ?? Date.now()
335
+ });
336
+ }
337
+ function upsertSession(db, record) {
338
+ db.query(`INSERT INTO sessions (session_id, parent_id, directory, title, started_at)
339
+ VALUES ($sessionID, $parentID, $directory, $title, $startedAt)
340
+ ON CONFLICT(session_id) DO UPDATE SET
341
+ parent_id = COALESCE(excluded.parent_id, sessions.parent_id),
342
+ directory = COALESCE(excluded.directory, sessions.directory),
343
+ title = COALESCE(excluded.title, sessions.title),
344
+ started_at = COALESCE(sessions.started_at, excluded.started_at)`).run({
345
+ $sessionID: record.sessionID,
346
+ $parentID: record.parentID ?? null,
347
+ $directory: record.directory === undefined ? null : sanitizeLabel(record.directory, LABEL_LIMIT),
348
+ $title: record.title === undefined ? null : sanitizeLabel(record.title, LABEL_LIMIT),
349
+ $startedAt: timestamp(record.startedAt)
350
+ });
351
+ }
352
+
353
+ // src/stats/migrate.ts
354
+ var REMOVED_COLUMNS = {
355
+ steps: ["provider_state", "upstream", "upstream_source", "upstream_model", "tps", "router", "parent_id"],
356
+ sessions: ["updated_at"]
357
+ };
181
358
  function dropUnused(db) {
182
359
  const objects = db.query("SELECT name, type FROM sqlite_master WHERE type IN ('table', 'index')").all();
183
- const tables = new Set(objects.filter((row) => row.type === "table").map((row) => row.name));
184
360
  const indexes = new Set(objects.filter((row) => row.type === "index").map((row) => row.name));
185
- if (tables.has("http_responses"))
361
+ if (hasTable(db, "http_responses"))
186
362
  db.exec("DROP TABLE http_responses");
187
363
  if (indexes.has("steps_upstream"))
188
364
  db.exec("DROP INDEX steps_upstream");
189
365
  if (indexes.has("steps_router"))
190
366
  db.exec("DROP INDEX steps_router");
191
- const columns = new Set(db.query("PRAGMA table_info(steps)").all().map((column) => column.name));
192
- for (const name of REMOVED_COLUMNS) {
193
- if (columns.has(name))
194
- db.exec(`ALTER TABLE steps DROP COLUMN ${name}`);
195
- }
196
- if (tables.has("events")) {
197
- const kinds = REMOVED_EVENT_KINDS.map((kind) => `'${kind}'`).join(", ");
198
- db.exec(`DELETE FROM events WHERE kind IN (${kinds})`);
367
+ for (const [table, names] of Object.entries(REMOVED_COLUMNS)) {
368
+ const columns = columnsOf(db, table);
369
+ for (const name of names) {
370
+ if (columns.has(name))
371
+ db.exec(`ALTER TABLE ${table} DROP COLUMN ${name}`);
372
+ }
199
373
  }
200
374
  }
201
375
  function addMissing(db) {
202
- const columns = new Set(db.query("PRAGMA table_info(steps)").all().map((column) => column.name));
376
+ const columns = columnsOf(db, "steps");
203
377
  if (columns.size > 0 && !columns.has("list_cost")) {
204
378
  db.exec("ALTER TABLE steps ADD COLUMN list_cost REAL");
205
379
  }
380
+ if (columns.size > 0 && !columns.has("first_token_at")) {
381
+ db.exec("ALTER TABLE steps ADD COLUMN first_token_at INTEGER");
382
+ }
206
383
  }
207
- function dedupeEvents(db) {
208
- const table = db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'events'").get();
209
- if (table === null)
384
+ function dedupeLegacyCompactions(db) {
385
+ if (!hasTable(db, "events"))
210
386
  return;
211
- db.exec(`DELETE FROM events
212
- WHERE kind = 'compaction' AND message_id IS NULL
213
- AND rowid NOT IN (
214
- SELECT MIN(rowid) FROM events
215
- WHERE kind = 'compaction' AND message_id IS NULL
216
- GROUP BY session_id, at, data
217
- )`);
387
+ const columns = columnsOf(db, "events");
388
+ if (!["session_id", "kind", "message_id", "at"].every((name) => columns.has(name)))
389
+ return;
390
+ if (columns.has("data")) {
391
+ db.query(`DELETE FROM events
392
+ WHERE kind = ? AND message_id IS NULL
393
+ AND rowid NOT IN (
394
+ SELECT MIN(rowid) FROM events
395
+ WHERE kind = ? AND message_id IS NULL
396
+ GROUP BY session_id, at, data
397
+ )`).run(COMPACTION_KIND, COMPACTION_KIND);
398
+ } else {
399
+ db.query(`DELETE FROM events
400
+ WHERE kind = ? AND message_id IS NULL AND at IS NOT NULL
401
+ AND rowid NOT IN (
402
+ SELECT MIN(rowid) FROM events
403
+ WHERE kind = ? AND message_id IS NULL AND at IS NOT NULL
404
+ GROUP BY session_id, at
405
+ )`).run(COMPACTION_KIND, COMPACTION_KIND);
406
+ }
218
407
  db.exec(`DELETE FROM events
219
408
  WHERE message_id IS NOT NULL
220
409
  AND rowid NOT IN (
221
410
  SELECT MIN(rowid) FROM events
222
411
  WHERE message_id IS NOT NULL
223
- GROUP BY kind, message_id
412
+ GROUP BY message_id
224
413
  )`);
225
414
  }
226
- function addEventKey(db) {
227
- const table = db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'events'").get();
228
- if (table === null)
415
+ function backfillCompactionUsage(db) {
416
+ if (!hasTable(db, "events") || !hasTable(db, "usage"))
229
417
  return;
230
- db.exec("CREATE UNIQUE INDEX IF NOT EXISTS events_kind_message ON events(kind, message_id) WHERE message_id IS NOT NULL");
418
+ const columns = columnsOf(db, "events");
419
+ if (!["session_id", "kind", "message_id", "at", "data"].every((name) => columns.has(name)))
420
+ return;
421
+ const rows = db.query(`SELECT rowid AS id, session_id, kind, message_id, at, data
422
+ FROM events
423
+ WHERE kind = ? AND message_id IS NULL AND at IS NOT NULL AND data IS NOT NULL`).all(COMPACTION_KIND);
424
+ for (const row of rows) {
425
+ const legacy = legacyCompactionUsage(row);
426
+ if (legacy === undefined)
427
+ continue;
428
+ recordUsage(db, {
429
+ id: `compaction:${String(row.id)}`,
430
+ sessionID: legacy.sessionID,
431
+ source: COMPACTION_KIND,
432
+ at: legacy.at,
433
+ cost: legacy.cost,
434
+ input: legacy.input,
435
+ output: legacy.output,
436
+ reasoning: legacy.reasoning,
437
+ cacheRead: legacy.cacheRead,
438
+ cacheWrite: legacy.cacheWrite
439
+ });
440
+ }
231
441
  }
232
- function backfillCompactionUsage(db) {
233
- const tables = new Set(db.query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((row) => row.name));
234
- if (!tables.has("events") || !tables.has("usage"))
442
+ function migrateLegacyCompactions(db) {
443
+ if (!hasTable(db, "events"))
235
444
  return;
236
- db.exec(`INSERT OR IGNORE INTO usage (
237
- id, session_id, source, at, cost,
238
- input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
239
- )
240
- SELECT 'compaction:' || rowid, session_id, 'compaction', at,
241
- MAX(0, COALESCE(CAST(json_extract(data, '$.cost') AS REAL), 0)),
242
- MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.input'), 0) AS INTEGER)),
243
- MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.output'), 0) AS INTEGER)),
244
- MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.reasoning'), 0) AS INTEGER)),
245
- MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.cache.read'), 0) AS INTEGER)),
246
- MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.cache.write'), 0) AS INTEGER))
247
- FROM events
248
- WHERE kind = 'compaction' AND message_id IS NULL AND at IS NOT NULL AND data IS NOT NULL
249
- AND json_valid(data)`);
445
+ const columns = columnsOf(db, "events");
446
+ if (!["session_id", "kind", "message_id", "at"].every((name) => columns.has(name)))
447
+ return;
448
+ db.query(`INSERT OR IGNORE INTO compactions (session_id, message_id, at)
449
+ SELECT session_id, message_id, at FROM events WHERE kind = ?`).run(COMPACTION_KIND);
450
+ db.exec("DROP TABLE events");
250
451
  }
251
452
  function migrate(db) {
252
- dropUnused(db);
253
- addMissing(db);
254
- dedupeEvents(db);
255
- backfillCompactionUsage(db);
256
- addEventKey(db);
453
+ db.transaction(() => {
454
+ dropUnused(db);
455
+ addMissing(db);
456
+ dedupeLegacyCompactions(db);
457
+ backfillCompactionUsage(db);
458
+ migrateLegacyCompactions(db);
459
+ })();
257
460
  }
461
+
462
+ // src/stats/open.ts
258
463
  var POSIX = process.platform !== "win32";
259
464
  function hardenDirectory(path) {
260
465
  if (!POSIX)
@@ -283,14 +488,19 @@ function openStatsDb(path) {
283
488
  ensureRegularFile(path);
284
489
  prepareDirectory(path);
285
490
  const db = new Database(path, { create: true });
286
- db.exec("PRAGMA journal_mode = WAL");
287
- db.exec("PRAGMA busy_timeout = 5000");
288
- db.exec("PRAGMA synchronous = NORMAL");
289
- db.exec(SCHEMA);
290
- migrate(db);
291
- db.query("INSERT INTO meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(SCHEMA_VERSION));
292
- hardenFiles(path);
293
- return db;
491
+ try {
492
+ db.exec("PRAGMA journal_mode = WAL");
493
+ db.exec("PRAGMA busy_timeout = 5000");
494
+ db.exec("PRAGMA synchronous = NORMAL");
495
+ db.exec(SCHEMA);
496
+ migrate(db);
497
+ db.query("INSERT INTO meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(SCHEMA_VERSION));
498
+ hardenFiles(path);
499
+ return db;
500
+ } catch (error) {
501
+ db.close();
502
+ throw error;
503
+ }
294
504
  }
295
505
  function openStatsDbReadOnly(path) {
296
506
  ensureRegularFile(path);
@@ -313,117 +523,6 @@ function openStatsDbWrite(path) {
313
523
  hardenFiles(path);
314
524
  return db;
315
525
  }
316
- function recordStep(db, record) {
317
- const cost = Math.max(0, finite(record.cost));
318
- const listCost = cost <= 0 && typeof record.listCost === "number" && Number.isFinite(record.listCost) && record.listCost >= 0 ? record.listCost : null;
319
- db.query(`INSERT INTO steps (
320
- message_id, session_id, parent_id, provider_id, model_id, variant,
321
- input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost, list_cost,
322
- created_at, streamed_at, completed_at, finish, recorded_at
323
- ) VALUES (
324
- $messageID, $sessionID, $parentID, $providerID, $modelID, $variant,
325
- $input, $output, $reasoning, $cacheRead, $cacheWrite, $cost, $listCost,
326
- $createdAt, $streamedAt, $completedAt, $finish, $recordedAt
327
- )
328
- ON CONFLICT(message_id) DO UPDATE SET
329
- session_id = excluded.session_id,
330
- parent_id = COALESCE(excluded.parent_id, steps.parent_id),
331
- provider_id = COALESCE(excluded.provider_id, steps.provider_id),
332
- model_id = COALESCE(excluded.model_id, steps.model_id),
333
- variant = COALESCE(excluded.variant, steps.variant),
334
- input_tokens = excluded.input_tokens,
335
- output_tokens = excluded.output_tokens,
336
- reasoning_tokens = excluded.reasoning_tokens,
337
- cache_read = excluded.cache_read,
338
- cache_write = excluded.cache_write,
339
- cost = excluded.cost,
340
- -- A step that starts being charged loses its estimate; an estimate is
341
- -- kept when a replayed event arrives without a price table.
342
- list_cost = CASE WHEN excluded.cost > 0 THEN NULL ELSE COALESCE(excluded.list_cost, steps.list_cost) END,
343
- created_at = COALESCE(excluded.created_at, steps.created_at),
344
- streamed_at = COALESCE(excluded.streamed_at, steps.streamed_at),
345
- completed_at = COALESCE(excluded.completed_at, steps.completed_at),
346
- finish = COALESCE(excluded.finish, steps.finish),
347
- recorded_at = excluded.recorded_at`).run({
348
- $messageID: record.messageID,
349
- $sessionID: record.sessionID,
350
- $parentID: record.parentID ?? null,
351
- $providerID: record.providerID !== undefined && isToken(record.providerID) ? record.providerID : null,
352
- $modelID: record.modelID ?? null,
353
- $variant: record.variant ?? null,
354
- $input: tokenCount(record.input),
355
- $output: tokenCount(record.output),
356
- $reasoning: tokenCount(record.reasoning),
357
- $cacheRead: tokenCount(record.cacheRead),
358
- $cacheWrite: tokenCount(record.cacheWrite),
359
- $cost: cost,
360
- $listCost: listCost,
361
- $createdAt: timestamp(record.createdAt),
362
- $streamedAt: timestamp(record.streamedAt),
363
- $completedAt: timestamp(record.completedAt),
364
- $finish: record.finish === undefined ? null : sanitizeLabel(record.finish, 64),
365
- $recordedAt: timestamp(record.recordedAt) ?? Date.now()
366
- });
367
- }
368
- function recordUsage(db, record) {
369
- if (typeof record.id !== "string" || record.id === "")
370
- return;
371
- if (typeof record.sessionID !== "string" || record.sessionID === "")
372
- return;
373
- db.query(`INSERT INTO usage (
374
- id, session_id, source, at, cost, input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
375
- ) VALUES (
376
- $id, $sessionID, $source, $at, $cost, $input, $output, $reasoning, $cacheRead, $cacheWrite
377
- ) ON CONFLICT(id) DO NOTHING`).run({
378
- $id: record.id,
379
- $sessionID: record.sessionID,
380
- $source: sanitizeLabel(record.source, 64),
381
- $at: timestamp(record.at) ?? Date.now(),
382
- $cost: Math.max(0, finite(record.cost)),
383
- $input: tokenCount(record.input),
384
- $output: tokenCount(record.output),
385
- $reasoning: tokenCount(record.reasoning),
386
- $cacheRead: tokenCount(record.cacheRead),
387
- $cacheWrite: tokenCount(record.cacheWrite)
388
- });
389
- }
390
- function recordPrompt(db, record) {
391
- db.query(`INSERT INTO prompts (session_id, message_id, created_at)
392
- VALUES ($sessionID, $messageID, $createdAt)
393
- ON CONFLICT(session_id, message_id) DO UPDATE SET created_at = COALESCE(excluded.created_at, prompts.created_at)`).run({
394
- $sessionID: record.sessionID,
395
- $messageID: record.messageID,
396
- $createdAt: timestamp(record.createdAt)
397
- });
398
- }
399
- function recordEvent(db, record) {
400
- db.query(`INSERT OR IGNORE INTO events (session_id, kind, message_id, at, data)
401
- VALUES ($sessionID, $kind, $messageID, $at, $data)`).run({
402
- $sessionID: record.sessionID,
403
- $kind: sanitizeLabel(record.kind, 64),
404
- $messageID: record.messageID ?? null,
405
- $at: timestamp(record.at) ?? Date.now(),
406
- $data: jsonText(record.data)
407
- });
408
- }
409
- function upsertSession(db, record) {
410
- db.query(`INSERT INTO sessions (session_id, parent_id, directory, title, started_at, updated_at)
411
- VALUES ($sessionID, $parentID, $directory, $title, $startedAt, $updatedAt)
412
- ON CONFLICT(session_id) DO UPDATE SET
413
- parent_id = COALESCE(excluded.parent_id, sessions.parent_id),
414
- directory = COALESCE(excluded.directory, sessions.directory),
415
- title = COALESCE(excluded.title, sessions.title),
416
- started_at = COALESCE(sessions.started_at, excluded.started_at),
417
- updated_at = COALESCE(excluded.updated_at, sessions.updated_at)`).run({
418
- $sessionID: record.sessionID,
419
- $parentID: record.parentID ?? null,
420
- $directory: record.directory === undefined ? null : sanitizeLabel(record.directory, LABEL_LIMIT),
421
- $title: record.title === undefined ? null : sanitizeLabel(record.title, LABEL_LIMIT),
422
- $startedAt: timestamp(record.startedAt),
423
- $updatedAt: timestamp(record.updatedAt)
424
- });
425
- }
426
-
427
526
  // src/service.ts
428
527
  import { basename } from "path";
429
528
 
@@ -787,7 +886,6 @@ function formatLine(stats, options) {
787
886
  }
788
887
 
789
888
  // src/stats/queries.ts
790
- var COMPACTION_KIND = "compaction";
791
889
  var DEFAULT_TTL_HINT_MS = 10 * 60 * 1000;
792
890
  function spend(usage) {
793
891
  return usage.cost + usage.listCost;
@@ -857,9 +955,10 @@ function otherUsageRows(db, range, filters) {
857
955
  }
858
956
  }
859
957
  var STEP_TIME = "COALESCE(created_at, recorded_at)";
860
- var MODEL_KEY_SQL = "COALESCE(model_id, '(unknown)') || '#' || COALESCE(variant, '')";
958
+ var MODEL_KEY_SEPARATOR = "#";
959
+ var MODEL_KEY_SQL = `COALESCE(model_id, '(unknown)') || '${MODEL_KEY_SEPARATOR}' || COALESCE(variant, '')`;
861
960
  function modelKey(modelID, variant) {
862
- return `${modelID}#${variant ?? ""}`;
961
+ return `${modelID}${MODEL_KEY_SEPARATOR}${variant ?? ""}`;
863
962
  }
864
963
  function modelLabel(modelID, variant) {
865
964
  return variant === undefined ? modelID : `${modelID} ${variant}`;
@@ -930,7 +1029,10 @@ function overview(db, range, filters) {
930
1029
  MIN(${STEP_TIME}) AS firstAt,
931
1030
  MAX(COALESCE(completed_at, ${STEP_TIME})) AS lastAt,
932
1031
  COALESCE(SUM(CASE WHEN streamed_at > created_at THEN output_tokens + reasoning_tokens ELSE 0 END), 0) AS produced,
933
- COALESCE(SUM(CASE WHEN streamed_at > created_at THEN streamed_at - created_at ELSE 0 END), 0) AS window
1032
+ COALESCE(SUM(CASE WHEN streamed_at > created_at THEN streamed_at - created_at ELSE 0 END), 0) AS window,
1033
+ COALESCE(SUM(CASE WHEN streamed_at > COALESCE(first_token_at, created_at) THEN output_tokens + reasoning_tokens ELSE 0 END), 0) AS decodeProduced,
1034
+ COALESCE(SUM(CASE WHEN streamed_at > COALESCE(first_token_at, created_at)
1035
+ THEN streamed_at - COALESCE(first_token_at, created_at) ELSE 0 END), 0) AS decodeWindow
934
1036
  FROM steps ${steps.where}`).get(...steps.params);
935
1037
  const prompts = rangeWhere(range, "created_at");
936
1038
  const promptClauses = prompts.where === "" ? [] : [prompts.where.slice("WHERE ".length)];
@@ -941,6 +1043,10 @@ function overview(db, range, filters) {
941
1043
  }
942
1044
  const promptWhere = promptClauses.length > 0 ? `WHERE ${promptClauses.join(" AND ")}` : "";
943
1045
  const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${promptWhere}`).get(...promptParams);
1046
+ const ttftFilter = steps.where === "" ? "WHERE" : `${steps.where} AND`;
1047
+ const ttftRows = db.query(`SELECT MAX(0, first_token_at - created_at) AS ttft
1048
+ FROM steps ${ttftFilter} created_at IS NOT NULL AND first_token_at IS NOT NULL`).all(...steps.params);
1049
+ const ttft = ttftRows.length === 0 ? undefined : percentile(ttftRows.map((entry) => entry.ttft), 50);
944
1050
  const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
945
1051
  const other = otherUsage(db, range, filters);
946
1052
  return {
@@ -952,7 +1058,9 @@ function overview(db, range, filters) {
952
1058
  firstAt: row?.firstAt ?? undefined,
953
1059
  lastAt: row?.lastAt ?? undefined,
954
1060
  cacheHitRatio: cacheHitRatio(usage),
955
- tps: row === null ? undefined : tokensPerSecond(row.produced ?? 0, 0, row.window ?? 0)
1061
+ tps: row === null ? undefined : tokensPerSecond(row.decodeProduced ?? 0, 0, row.decodeWindow ?? 0),
1062
+ requestTps: row === null ? undefined : tokensPerSecond(row.produced ?? 0, 0, row.window ?? 0),
1063
+ ttft
956
1064
  };
957
1065
  }
958
1066
  function models(db, range, filters) {
@@ -1107,7 +1215,11 @@ function stepMessage(row) {
1107
1215
  return {
1108
1216
  type: "assistant",
1109
1217
  id: row.message_id,
1110
- time: { created: row.created_at ?? row.recorded_at, completed: row.completed_at ?? undefined },
1218
+ time: {
1219
+ created: row.created_at ?? row.recorded_at,
1220
+ firstToken: row.first_token_at ?? undefined,
1221
+ completed: row.completed_at ?? undefined
1222
+ },
1111
1223
  model: row.provider_id !== null && row.model_id !== null ? { providerID: row.provider_id, id: row.model_id, variant: row.variant ?? undefined } : undefined,
1112
1224
  tokens: {
1113
1225
  input: row.input_tokens ?? 0,
@@ -1138,7 +1250,7 @@ function turns(db, options) {
1138
1250
  }
1139
1251
  const steps = db.query(`SELECT message_id, session_id, provider_id, model_id, variant,
1140
1252
  input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,
1141
- created_at, streamed_at, recorded_at, completed_at, finish
1253
+ created_at, first_token_at, streamed_at, recorded_at, completed_at, finish
1142
1254
  FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
1143
1255
  ORDER BY session_id, ${STEP_TIME}, message_id`).all(...params);
1144
1256
  const promptClause = options?.sessionID === undefined ? "" : `WHERE session_id = ?${floor === undefined ? "" : " AND created_at >= ?"}`;
@@ -1181,12 +1293,22 @@ function turns(db, options) {
1181
1293
  const variant = last.variant ?? undefined;
1182
1294
  let produced = 0;
1183
1295
  let window = 0;
1296
+ let decodeProduced = 0;
1297
+ let decodeWindow = 0;
1184
1298
  for (const row of bucket) {
1185
- if (row.created_at === null || row.streamed_at === null || row.streamed_at <= row.created_at)
1186
- continue;
1187
- produced += (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0);
1188
- window += row.streamed_at - row.created_at;
1299
+ const tokens = (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0);
1300
+ if (row.created_at !== null && row.streamed_at !== null && row.streamed_at > row.created_at) {
1301
+ produced += tokens;
1302
+ window += row.streamed_at - row.created_at;
1303
+ }
1304
+ const start = row.first_token_at ?? row.created_at;
1305
+ if (start !== null && row.streamed_at !== null && row.streamed_at > start) {
1306
+ decodeProduced += tokens;
1307
+ decodeWindow += row.streamed_at - start;
1308
+ }
1189
1309
  }
1310
+ const first = bucket[0];
1311
+ const ttft = first !== undefined && first.created_at !== null && first.first_token_at !== null ? Math.max(0, first.first_token_at - first.created_at) : undefined;
1190
1312
  const previous = result.length > 0 && result[result.length - 1].sessionID === last.session_id ? result[result.length - 1] : undefined;
1191
1313
  const endAt = last.completed_at ?? last.created_at ?? last.recorded_at;
1192
1314
  const firstAt = bucket[0]?.created_at ?? promptAt;
@@ -1206,7 +1328,9 @@ function turns(db, options) {
1206
1328
  totals,
1207
1329
  drops,
1208
1330
  finish: last.finish ?? undefined,
1209
- tps: tokensPerSecond(produced, 0, window)
1331
+ tps: tokensPerSecond(decodeProduced, 0, decodeWindow),
1332
+ requestTps: tokensPerSecond(produced, 0, window),
1333
+ ttft
1210
1334
  });
1211
1335
  bucket = [];
1212
1336
  }
@@ -1284,8 +1408,9 @@ var STEP_COLUMNS = `message_id AS messageID, session_id AS sessionID, provider_i
1284
1408
  COALESCE(input_tokens, 0) AS input, COALESCE(cache_read, 0) AS cached, COALESCE(cache_write, 0) AS cacheWrite,
1285
1409
  COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, COALESCE(cost, 0) AS cost,
1286
1410
  COALESCE(list_cost, 0) AS listCost,
1287
- created_at AS createdAt, streamed_at AS streamedAt, completed_at AS completedAt, ${STEP_AT} AS at`;
1288
- var STEP_OPTIONAL = ["providerID", "modelID", "variant", "createdAt", "streamedAt", "completedAt"];
1411
+ created_at AS createdAt, first_token_at AS firstTokenAt, streamed_at AS streamedAt,
1412
+ completed_at AS completedAt, ${STEP_AT} AS at`;
1413
+ var STEP_OPTIONAL = ["providerID", "modelID", "variant", "createdAt", "firstTokenAt", "streamedAt", "completedAt"];
1289
1414
  var PAIR_COLUMNS = STEP_COLUMNS.replace("COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, ", "");
1290
1415
  function stepRows(db, options) {
1291
1416
  const filter = buildWhere(options?.range, options?.filters);
@@ -1364,6 +1489,7 @@ function coverageOf(db, options) {
1364
1489
  COALESCE(SUM(CASE WHEN model_id IS NULL THEN 1 ELSE 0 END), 0) AS missingModel,
1365
1490
  COALESCE(SUM(CASE WHEN completed_at IS NOT NULL OR finish IS NOT NULL THEN 0 ELSE 1 END), 0) AS unsettled,
1366
1491
  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,
1492
+ 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,
1367
1493
  MIN(${STEP_AT}) AS firstAt,
1368
1494
  MAX(${STEP_AT}) AS lastAt
1369
1495
  FROM steps ${filter.where}`).get(...filter.params);
@@ -1374,6 +1500,7 @@ function coverageOf(db, options) {
1374
1500
  missingModel: row.missingModel,
1375
1501
  unsettled: row.unsettled,
1376
1502
  missingTps: row.missingTps,
1503
+ missingFirstToken: row.missingFirstToken,
1377
1504
  firstAt: row.firstAt ?? undefined,
1378
1505
  lastAt: row.lastAt ?? undefined
1379
1506
  };
@@ -1386,7 +1513,14 @@ function groupedRows(db, options) {
1386
1513
  function timingOf(step) {
1387
1514
  const wall = step.createdAt !== undefined && step.completedAt !== undefined ? Math.max(0, step.completedAt - step.createdAt) : undefined;
1388
1515
  const stream = step.createdAt !== undefined && step.streamedAt !== undefined && step.streamedAt > step.createdAt ? step.streamedAt - step.createdAt : undefined;
1389
- return { wall, stream, tps: tokensPerSecond(step.output + step.reasoning, step.createdAt, step.streamedAt) };
1516
+ const ttft = step.createdAt !== undefined && step.firstTokenAt !== undefined ? Math.max(0, step.firstTokenAt - step.createdAt) : undefined;
1517
+ return {
1518
+ wall,
1519
+ stream,
1520
+ ttft,
1521
+ tps: tokensPerSecond(step.output + step.reasoning, step.firstTokenAt ?? step.createdAt, step.streamedAt),
1522
+ requestTps: tokensPerSecond(step.output + step.reasoning, step.createdAt, step.streamedAt)
1523
+ };
1390
1524
  }
1391
1525
  function timingRows(db, options) {
1392
1526
  return groupedRows(db, options);
@@ -1394,17 +1528,29 @@ function timingRows(db, options) {
1394
1528
  function latencyOf(rows) {
1395
1529
  const wall = [];
1396
1530
  const stream = [];
1531
+ const ttft = [];
1397
1532
  const tps = [];
1533
+ const requestTps = [];
1398
1534
  for (const step of rows) {
1399
1535
  const timing = timingOf(step);
1400
1536
  if (timing.wall !== undefined)
1401
1537
  wall.push(timing.wall);
1402
1538
  if (timing.stream !== undefined)
1403
1539
  stream.push(timing.stream);
1540
+ if (timing.ttft !== undefined)
1541
+ ttft.push(timing.ttft);
1404
1542
  if (timing.tps !== undefined)
1405
1543
  tps.push(timing.tps);
1544
+ if (timing.requestTps !== undefined)
1545
+ requestTps.push(timing.requestTps);
1406
1546
  }
1407
- return { wall: latencyStats(wall), stream: latencyStats(stream), tps: latencyStats(tps) };
1547
+ return {
1548
+ wall: latencyStats(wall),
1549
+ stream: latencyStats(stream),
1550
+ ttft: latencyStats(ttft),
1551
+ tps: latencyStats(tps),
1552
+ requestTps: latencyStats(requestTps)
1553
+ };
1408
1554
  }
1409
1555
  function latencyGroupsOf(rows, by) {
1410
1556
  const key = (step) => by === "model" ? modelKey(step.modelID ?? "(unknown)", step.variant) : step.providerID ?? "(unknown)";
@@ -1412,25 +1558,33 @@ function latencyGroupsOf(rows, by) {
1412
1558
  for (const [group, steps] of groupBy(rows, key)) {
1413
1559
  const wall = [];
1414
1560
  const stream = [];
1561
+ const ttft = [];
1415
1562
  const tps = [];
1563
+ const requestTps = [];
1416
1564
  for (const step of steps) {
1417
1565
  const timing = timingOf(step);
1418
1566
  if (timing.wall !== undefined)
1419
1567
  wall.push(timing.wall);
1420
1568
  if (timing.stream !== undefined)
1421
1569
  stream.push(timing.stream);
1570
+ if (timing.ttft !== undefined)
1571
+ ttft.push(timing.ttft);
1422
1572
  if (timing.tps !== undefined)
1423
1573
  tps.push(timing.tps);
1574
+ if (timing.requestTps !== undefined)
1575
+ requestTps.push(timing.requestTps);
1424
1576
  }
1425
- const [modelID, variant] = group.split("#");
1577
+ const { modelID, variant } = splitModelKey(group);
1426
1578
  groups.push({
1427
1579
  key: group,
1428
- label: by === "model" ? variant === undefined || variant === "" ? modelID : `${modelID} ${variant}` : group,
1580
+ label: by === "model" ? variant === undefined ? modelID : `${modelID} ${variant}` : group,
1429
1581
  count: steps.length,
1430
1582
  usage: usageOf(steps),
1431
1583
  wall: latencyStats(wall),
1432
1584
  stream: latencyStats(stream),
1433
- tps: latencyStats(tps)
1585
+ ttft: latencyStats(ttft),
1586
+ tps: latencyStats(tps),
1587
+ requestTps: latencyStats(requestTps)
1434
1588
  });
1435
1589
  }
1436
1590
  return groups.sort((left, right) => right.count - left.count || left.key.localeCompare(right.key));
@@ -1610,21 +1764,21 @@ function cacheDropsOf(db, rows, options) {
1610
1764
  }
1611
1765
  if (losses.length === 0)
1612
1766
  return [];
1613
- const compactions = new Map;
1767
+ const times = new Map;
1614
1768
  const sessionIDs = [...new Set(losses.map((loss) => loss.current.sessionID))];
1615
- const events = db.query(`SELECT session_id, at FROM events
1616
- WHERE kind = 'compaction' AND at IS NOT NULL AND session_id IN (${sessionIDs.map(() => "?").join(", ")})
1769
+ const timeline = db.query(`SELECT session_id, at FROM compactions
1770
+ WHERE at IS NOT NULL AND session_id IN (${sessionIDs.map(() => "?").join(", ")})
1617
1771
  ORDER BY at`).all(...sessionIDs);
1618
- for (const event of events) {
1619
- const list = compactions.get(event.session_id);
1772
+ for (const row of timeline) {
1773
+ const list = times.get(row.session_id);
1620
1774
  if (list !== undefined)
1621
- list.push(event.at);
1775
+ list.push(row.at);
1622
1776
  else
1623
- compactions.set(event.session_id, [event.at]);
1777
+ times.set(row.session_id, [row.at]);
1624
1778
  }
1625
1779
  return losses.map((loss) => {
1626
1780
  const ended = loss.previous.completedAt ?? loss.previous.streamedAt ?? loss.previous.createdAt;
1627
- const compacted = (compactions.get(loss.current.sessionID) ?? []).some((time) => ended !== undefined && time >= ended && time <= loss.current.at);
1781
+ const compacted = (times.get(loss.current.sessionID) ?? []).some((time) => ended !== undefined && time >= ended && time <= loss.current.at);
1628
1782
  const reason = compacted ? "compaction" : loss.gapMs !== undefined && loss.gapMs >= ttlHint ? "expired" : "unknown";
1629
1783
  return {
1630
1784
  sessionID: loss.current.sessionID,
@@ -1643,14 +1797,34 @@ function cacheDropsOf(db, rows, options) {
1643
1797
  function groupValues(steps) {
1644
1798
  const wall = [];
1645
1799
  const tps = [];
1800
+ const requestTps = [];
1801
+ const ttft = [];
1646
1802
  for (const step of steps) {
1647
1803
  const timing = timingOf(step);
1648
1804
  if (timing.wall !== undefined)
1649
1805
  wall.push(timing.wall);
1650
1806
  if (timing.tps !== undefined)
1651
1807
  tps.push(timing.tps);
1808
+ if (timing.requestTps !== undefined)
1809
+ requestTps.push(timing.requestTps);
1810
+ if (timing.ttft !== undefined)
1811
+ ttft.push(timing.ttft);
1652
1812
  }
1653
- return { cache: cacheStatsOfSteps(steps), tps: latencyStats(tps).p50, wall: latencyStats(wall).p50 };
1813
+ return {
1814
+ cache: cacheStatsOfSteps(steps),
1815
+ tps: latencyStats(tps).p50,
1816
+ requestTps: latencyStats(requestTps).p50,
1817
+ ttft: latencyStats(ttft).p50,
1818
+ wall: latencyStats(wall).p50
1819
+ };
1820
+ }
1821
+ var MODEL_LIST_SEPARATOR = "\x00";
1822
+ function splitModelKey(key) {
1823
+ const separator = key.indexOf(MODEL_KEY_SEPARATOR);
1824
+ if (separator === -1)
1825
+ return { modelID: key, variant: undefined };
1826
+ const variant = key.slice(separator + 1);
1827
+ return { modelID: key.slice(0, separator), variant: variant === "" ? undefined : variant };
1654
1828
  }
1655
1829
  function providerOf(steps, models) {
1656
1830
  const values = groupValues(steps);
@@ -1664,17 +1838,22 @@ function providerOf(steps, models) {
1664
1838
  }
1665
1839
  return {
1666
1840
  provider: steps[0].providerID,
1667
- models: models.split("\x00"),
1841
+ models: models.split(MODEL_LIST_SEPARATOR),
1668
1842
  share: 0,
1669
1843
  usage: usageOf(steps),
1670
1844
  cache: values.cache,
1671
1845
  tps: values.tps,
1846
+ requestTps: values.requestTps,
1847
+ ttft: values.ttft,
1672
1848
  wall: values.wall,
1673
1849
  firstAt,
1674
1850
  lastAt
1675
1851
  };
1676
1852
  }
1677
- var modelNames = (steps) => [...new Set(steps.map((step) => modelKey(step.modelID ?? "(unknown)", step.variant)))].map((key) => modelLabel(key.slice(0, key.indexOf("#")), key.slice(key.indexOf("#") + 1) || undefined)).join("\x00");
1853
+ var modelNames = (steps) => [...new Set(steps.map((step) => modelKey(step.modelID ?? "(unknown)", step.variant)))].map((key) => {
1854
+ const { modelID, variant } = splitModelKey(key);
1855
+ return modelLabel(modelID, variant);
1856
+ }).join(MODEL_LIST_SEPARATOR);
1678
1857
  function providerSummaryOf(rows) {
1679
1858
  const out = [];
1680
1859
  for (const steps of groupBy(rows, (step) => step.providerID ?? "").values()) {
@@ -1687,7 +1866,7 @@ function providerBreakdownOf(rows) {
1687
1866
  const out = [];
1688
1867
  for (const [model, modelRows] of groupBy(rows, (step) => modelKey(step.modelID ?? "(unknown)", step.variant))) {
1689
1868
  for (const steps of groupBy(modelRows, (step) => step.providerID ?? "").values()) {
1690
- const [modelID, variant] = [model.slice(0, model.indexOf("#")), model.slice(model.indexOf("#") + 1)];
1869
+ const { modelID, variant } = splitModelKey(model);
1691
1870
  out.push({
1692
1871
  ...providerOf(steps, modelNames(steps)),
1693
1872
  modelID,
@@ -1893,8 +2072,8 @@ var RANGE_KEYS = ["session", "today", "7d", "30d", "all"];
1893
2072
  var GRANULARITIES = ["day", "week", "month"];
1894
2073
  var SORT_KEYS = {
1895
2074
  models: ["steps", "cached", "hit", "out", "cost"],
1896
- providers: ["steps", "cached", "hit", "cost", "share", "tps"],
1897
- latency: ["n", "tps", "wall"],
2075
+ providers: ["steps", "cached", "hit", "cost", "share", "tps", "ttft"],
2076
+ latency: ["n", "tps", "ttft", "wall"],
1898
2077
  sessions: ["last", "steps", "cached", "cost"],
1899
2078
  turns: ["time", "cost", "tokens"]
1900
2079
  };
@@ -1992,10 +2171,10 @@ function formatTps(value) {
1992
2171
  return "\u2013";
1993
2172
  return `${value.toFixed(1)}/s`;
1994
2173
  }
1995
- function formatTpsCompact(value) {
2174
+ function formatRateValue(value) {
1996
2175
  if (value === undefined || !Number.isFinite(value) || value < 0)
1997
2176
  return "\u2013";
1998
- return value >= 10 ? `${Math.round(value)}/s` : `${value.toFixed(1)}/s`;
2177
+ return value >= 10 ? String(Math.round(value)) : value.toFixed(1);
1999
2178
  }
2000
2179
  function formatGap(value) {
2001
2180
  if (value === undefined || !Number.isFinite(value))
@@ -2226,7 +2405,11 @@ function helpLines(width) {
2226
2405
  { text: " \u2248 list-price estimate for steps the host reported as $0;" },
2227
2406
  { text: " `$0.12 + \u2248 $3.40` keeps charged and estimated money apart" },
2228
2407
  { text: " wall request \u2192 completed step \xB7 stream request \u2192 last chunk" },
2229
- { text: " tps out / streaming seconds, shown as p50" },
2408
+ { text: " ttft request \u2192 first streamed token" },
2409
+ { text: " tps output+reasoning / first token \u2192 last chunk (OpenCode)" },
2410
+ { text: " rtps output+reasoning / request \u2192 last chunk (includes TTFT)" },
2411
+ { text: " turn 200 tps \xB7 2.1s ttft \xB7 cost" },
2412
+ { text: " session 200 tps \xB7 167 rtps \xB7 ttft p50 \xB7 cost" },
2230
2413
  { text: " switches how often a step's model or provider differs from the step" },
2231
2414
  { text: " before it in the same session (the models view's detail), with" },
2232
2415
  { text: " the cache a provider switch cost" },
@@ -2355,12 +2538,16 @@ function usagePairs(usage, estimates = true) {
2355
2538
  ];
2356
2539
  if (buckets.reasoning > 0)
2357
2540
  pairs.push(["reasoning", formatTokens(buckets.reasoning)]);
2541
+ if ("tps" in usage && usage.tps !== undefined)
2542
+ pairs.push(["tps", formatTps(usage.tps)]);
2543
+ if ("requestTps" in usage && usage.requestTps !== undefined)
2544
+ pairs.push(["rtps", formatTps(usage.requestTps)]);
2545
+ if ("ttft" in usage && usage.ttft !== undefined)
2546
+ pairs.push(["ttft p50", formatMs(usage.ttft)]);
2358
2547
  pairs.push(["cost", (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost)]);
2359
2548
  const other = usage.otherCost ?? 0;
2360
2549
  if (other > 0)
2361
2550
  pairs.push(["other", `${formatCost(other)} comp/title`]);
2362
- if ("tps" in usage && usage.tps !== undefined)
2363
- pairs.push(["tps", formatTps(usage.tps)]);
2364
2551
  return pairs;
2365
2552
  }
2366
2553
  function overviewLines(data, width) {
@@ -2413,6 +2600,7 @@ function coveragePairs(coverage) {
2413
2600
  ["models", `${formatCount(coverage.models)} \xB7 unknown ${share(coverage.missingModel)}`],
2414
2601
  ["providers", formatCount(coverage.providers)],
2415
2602
  ["unsettled", `${formatCount(coverage.unsettled)} \xB7 no tps ${share(coverage.missingTps)}`],
2603
+ ["no ttft", share(coverage.missingFirstToken)],
2416
2604
  [
2417
2605
  "window",
2418
2606
  `${coverage.firstAt === undefined ? "\u2013" : new Date(coverage.firstAt).toLocaleString("en-GB")} \u2192 ${coverage.lastAt === undefined ? "\u2013" : new Date(coverage.lastAt).toLocaleString("en-GB")}`
@@ -2523,7 +2711,8 @@ function providerSummaryLines(rows, width, limit = 40, estimates = true) {
2523
2711
  { header: "cached", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
2524
2712
  { header: "hit", width: 6, max: 7, align: "right", priority: 2, cell: (row) => formatPercent(row.cache.hit) },
2525
2713
  { header: "tps p50", width: 8, align: "right", priority: 5, cell: (row) => formatTps(row.tps) },
2526
- { header: "wall", width: 7, align: "right", priority: 6, cell: (row) => formatMs(row.wall) },
2714
+ { header: "ttft p50", width: 8, max: 9, align: "right", priority: 6, cell: (row) => formatMs(row.ttft) },
2715
+ { header: "wall", width: 7, align: "right", priority: 7, cell: (row) => formatMs(row.wall) },
2527
2716
  { header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
2528
2717
  ], width, {
2529
2718
  limit,
@@ -2543,7 +2732,8 @@ function providerLines(rows, width, limit = 40, estimates = true) {
2543
2732
  { header: "cached", width: 7, max: 10, align: "right", priority: 3, cell: (row) => formatTokens(row.cache.cached) },
2544
2733
  { header: "hit", width: 6, max: 7, align: "right", priority: 4, cell: (row) => formatPercent(row.cache.hit) },
2545
2734
  { header: "tps p50", width: 8, align: "right", priority: 6, cell: (row) => formatTps(row.tps) },
2546
- { header: "wall", width: 7, align: "right", priority: 7, cell: (row) => formatMs(row.wall) },
2735
+ { header: "ttft p50", width: 8, max: 9, align: "right", priority: 7, cell: (row) => formatMs(row.ttft) },
2736
+ { header: "wall", width: 7, align: "right", priority: 8, cell: (row) => formatMs(row.wall) },
2547
2737
  { header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
2548
2738
  ], width, {
2549
2739
  limit,
@@ -2781,7 +2971,15 @@ function latencyLines(report, width, groups, limit = 12, estimates = true) {
2781
2971
  tone: "base"
2782
2972
  });
2783
2973
  lines.push({
2784
- text: formatTableRow(["throughput", "p50", formatTps(report.tps.p50), "p90", formatTps(report.tps.p90), "p99", formatTps(report.tps.p99)], [10, 4, 9, 4, 9, 4, 9]),
2974
+ 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]),
2975
+ tone: "base"
2976
+ });
2977
+ lines.push({
2978
+ 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]),
2979
+ tone: "base"
2980
+ });
2981
+ lines.push({
2982
+ 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]),
2785
2983
  tone: "base"
2786
2984
  });
2787
2985
  } else {
@@ -2794,13 +2992,25 @@ function latencyLines(report, width, groups, limit = 12, estimates = true) {
2794
2992
  tone: "base"
2795
2993
  });
2796
2994
  lines.push({
2797
- text: latencyMetric("throughput", [`p50 ${formatTps(report.tps.p50)}`, `p90 ${formatTps(report.tps.p90)}`, `p99 ${formatTps(report.tps.p99)}`], width),
2995
+ text: latencyMetric("ttft", [`p50 ${formatMs(report.ttft.p50)}`, `p90 ${formatMs(report.ttft.p90)}`, `p99 ${formatMs(report.ttft.p99)}`], width),
2996
+ tone: "base"
2997
+ });
2998
+ lines.push({
2999
+ text: latencyMetric("tps", [`p50 ${formatTps(report.tps.p50)}`, `p90 ${formatTps(report.tps.p90)}`, `p99 ${formatTps(report.tps.p99)}`], width),
3000
+ tone: "base"
3001
+ });
3002
+ lines.push({
3003
+ text: latencyMetric("rtps", [`p50 ${formatTps(report.requestTps.p50)}`, `p90 ${formatTps(report.requestTps.p90)}`, `p99 ${formatTps(report.requestTps.p99)}`], width),
2798
3004
  tone: "base"
2799
3005
  });
2800
3006
  }
2801
3007
  lines.push({ text: "", tone: "muted" });
2802
3008
  lines.push({
2803
- text: truncate("wall = request to completed \xB7 stream = request to last chunk \xB7 throughput = output+reasoning tokens/s", width),
3009
+ text: truncate("wall = request to completed \xB7 stream = request to last chunk", width),
3010
+ tone: "muted"
3011
+ });
3012
+ lines.push({
3013
+ text: truncate("ttft = request to first token \xB7 tps = first token to last chunk \xB7 rtps = request to last chunk", width),
2804
3014
  tone: "muted"
2805
3015
  });
2806
3016
  if (report.wall.count === 0)
@@ -2815,7 +3025,8 @@ function latencyLines(report, width, groups, limit = 12, estimates = true) {
2815
3025
  { header: "wall p90", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatMs(row.wall.p90) },
2816
3026
  { header: "stream", width: 6, max: 9, align: "right", priority: 2, cell: (row) => formatMs(row.stream.p50) },
2817
3027
  { header: "tps p50", width: 8, max: 9, align: "right", cell: (row) => formatTps(row.tps.p50) },
2818
- { header: "tps p90", width: 8, max: 9, align: "right", priority: 3, cell: (row) => formatTps(row.tps.p90) },
3028
+ { header: "tps p90", width: 8, max: 9, align: "right", priority: 4, cell: (row) => formatTps(row.tps.p90) },
3029
+ { header: "ttft p50", width: 8, max: 9, align: "right", priority: 3, cell: (row) => formatMs(row.ttft.p50) },
2819
3030
  { header: "cost", width: 8, max: 9, align: "right", cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
2820
3031
  ], width);
2821
3032
  if (columns.length > 0) {
@@ -3044,7 +3255,9 @@ function sessionSummaryLines(usage, budget = 34, estimates = true) {
3044
3255
  const cached = formatTokens(buckets.cached);
3045
3256
  const out = formatTokens(buckets.output);
3046
3257
  const hit = formatPercent(buckets.hit);
3047
- const tps = formatTpsCompact(usage.tps);
3258
+ const tps = usage.tps === undefined ? undefined : `${formatRateValue(usage.tps)} tps`;
3259
+ const rtps = usage.requestTps === undefined ? undefined : `${formatRateValue(usage.requestTps)} rtps`;
3260
+ const ttft = usage.ttft === undefined ? undefined : `ttft p50 ${formatMs(usage.ttft)}`;
3048
3261
  const cost = (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost);
3049
3262
  const first = [
3050
3263
  ` ${steps} steps \xB7 in ${input}`,
@@ -3054,16 +3267,22 @@ function sessionSummaryLines(usage, budget = 34, estimates = true) {
3054
3267
  ` cached ${cached} \xB7 out ${out}`,
3055
3268
  ` cached ${cached}`
3056
3269
  ].find((text) => text.length <= budget);
3057
- const last = [
3058
- ` hit ${hit} \xB7 ${tps} \xB7 ${cost}`,
3059
- ` hit ${hit} \xB7 ${cost}`,
3060
- ` ${cost}`
3270
+ const rates = [tps, rtps].filter((part) => part !== undefined);
3271
+ const rateLine = [
3272
+ ` hit ${hit}${rates.length > 0 ? ` \xB7 ${rates.join(" \xB7 ")}` : ""}`,
3273
+ ` hit ${hit}${rates[0] !== undefined ? ` \xB7 ${rates[0]}` : ""}`,
3274
+ ` hit ${hit}`
3061
3275
  ].find((text) => text.length <= budget);
3276
+ const tail = [
3277
+ ttft === undefined ? undefined : ` ${ttft} \xB7 ${cost}`,
3278
+ ` ${cost}`
3279
+ ].filter((text) => text !== undefined).find((text) => text.length <= budget);
3062
3280
  return [
3063
3281
  { text: truncate("session", budget), tone: HEADER_TONE },
3064
3282
  { text: truncate(first ?? ` ${steps} steps`, budget), tone: "muted" },
3065
3283
  { text: truncate(second ?? ` cached ${cached}`, budget), tone: "base" },
3066
- { text: truncate(last ?? ` ${cost}`, budget), tone: "base" },
3284
+ { text: truncate(rateLine ?? ` hit ${hit}`, budget), tone: "base" },
3285
+ { text: truncate(tail ?? ` ${cost}`, budget), tone: "base" },
3067
3286
  { text: "", tone: "muted" }
3068
3287
  ];
3069
3288
  }
@@ -3080,20 +3299,28 @@ function sidebarLines(rows, options) {
3080
3299
  const output = formatTokens(display.output);
3081
3300
  const cost = options?.estimates === false ? formatCost(turn.totals.cost) : formatMoney(turn.totals.cost, turn.totals.listCost) ?? formatCost(turn.totals.cost);
3082
3301
  const hit = formatPercent(display.prompt > 0 ? display.cached / display.prompt : undefined).replace(/\.0%$/, "%");
3083
- const tps = turn.tps === undefined ? undefined : formatTpsCompact(turn.tps);
3302
+ const tps = turn.tps === undefined ? undefined : `${formatRateValue(turn.tps)} tps`;
3303
+ const ttft = turn.ttft === undefined ? undefined : `${formatMs(turn.ttft)} ttft`;
3304
+ const rate = [tps, ttft].filter((part) => part !== undefined).join(" \xB7 ");
3084
3305
  const suffix = turn.drops.length > 0 ? " \xB7 \u26A0" : "";
3085
3306
  const header = `${clock} ${provider}`;
3086
3307
  const timed = turn.durationMs === undefined ? undefined : `${header} \xB7 ${formatMs(turn.durationMs)}`;
3308
+ const join = (...parts) => parts.filter((part) => part !== undefined && part !== "").join(" \xB7 ");
3087
3309
  const volumes = [
3088
- ` ${labels.input} ${input} (${prompt}) \xB7 ${labels.output} ${output}`,
3310
+ ` ${labels.input} ${input} (${prompt}) \xB7 ${labels.output} ${output} \xB7 hit ${hit}`,
3311
+ ` ${labels.input} ${input} \xB7 ${labels.output} ${output} \xB7 hit ${hit}`,
3089
3312
  ` ${labels.input} ${input} \xB7 ${labels.output} ${output}`,
3090
3313
  ` ${labels.input} ${input}`
3091
3314
  ];
3315
+ const volume = volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1];
3316
+ const hitPart = volume.includes(`hit ${hit}`) ? undefined : `hit ${hit}`;
3092
3317
  const facts = [
3093
- ` hit ${hit}${tps === undefined ? "" : ` \xB7 ${tps}`} \xB7 ${cost}${suffix}`,
3094
- ` hit ${hit}${tps === undefined ? "" : ` \xB7 ${tps}`}${suffix}`,
3095
- ` ${tps === undefined ? "" : `${tps} \xB7 `}${cost}${suffix}`,
3096
- ` hit ${hit}${suffix}`
3318
+ ` ${join(hitPart, rate, `${cost}${suffix}`)}`,
3319
+ ` ${join(hitPart, tps, `${cost}${suffix}`)}`,
3320
+ ` ${join(tps, `${cost}${suffix}`)}`,
3321
+ ` ${join(tps)}`,
3322
+ ` ${join(hitPart, `${cost}${suffix}`)}`,
3323
+ ` ${join(`${cost}${suffix}`)}`
3097
3324
  ];
3098
3325
  lines.push({ text: truncate(timed !== undefined && timed.length <= budget ? timed : header, budget), tone: turn.providerChanged ? "warning" : "base" });
3099
3326
  const edge = index === 0 || index === rows.length - 1;
@@ -3101,10 +3328,7 @@ function sidebarLines(rows, options) {
3101
3328
  const model = turn.modelID === undefined ? "unknown" : `${turn.modelID}${turn.variant === undefined ? "" : ` ${turn.variant}`}`;
3102
3329
  lines.push({ text: truncate(` ${model}`, budget), tone: "muted" });
3103
3330
  }
3104
- lines.push({
3105
- text: truncate(volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1], budget),
3106
- tone: "muted"
3107
- });
3331
+ lines.push({ text: truncate(volume, budget), tone: "muted" });
3108
3332
  lines.push({
3109
3333
  text: truncate(facts.find((text) => text.length <= budget) ?? facts[facts.length - 1], budget),
3110
3334
  tone: turn.drops.length > 0 ? "warning" : "muted"
@@ -3346,6 +3570,8 @@ function sortProviders(rows, sort, desc, estimates = true) {
3346
3570
  return row.share;
3347
3571
  if (sort === "tps")
3348
3572
  return row.tps ?? -1;
3573
+ if (sort === "ttft")
3574
+ return row.ttft ?? -1;
3349
3575
  return row.usage.steps;
3350
3576
  };
3351
3577
  return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
@@ -3355,6 +3581,8 @@ function sortLatency(rows, sort, desc) {
3355
3581
  const pick = (row) => {
3356
3582
  if (sort === "tps")
3357
3583
  return row.tps.p50 ?? -1;
3584
+ if (sort === "ttft")
3585
+ return row.ttft.p50 ?? -1;
3358
3586
  if (sort === "wall")
3359
3587
  return row.wall.p50 ?? -1;
3360
3588
  return row.count;
@@ -3505,13 +3733,6 @@ function size(path) {
3505
3733
  return 0;
3506
3734
  }
3507
3735
  }
3508
- function hasTable(db, name) {
3509
- try {
3510
- return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== null;
3511
- } catch {
3512
- return false;
3513
- }
3514
- }
3515
3736
  function dbInfo(db, path, now = Date.now()) {
3516
3737
  const tables = TABLES.map((table) => ({
3517
3738
  name: table,
@@ -3565,7 +3786,7 @@ function pruneOlderThan(db, cutoff) {
3565
3786
  return {
3566
3787
  steps: deleteBatched(db, "steps", `${STEP_TIME2} < ?`, cutoff),
3567
3788
  prompts: deleteBatched(db, "prompts", "created_at IS NOT NULL AND created_at < ?", cutoff),
3568
- events: deleteBatched(db, "events", "at IS NOT NULL AND at < ?", cutoff),
3789
+ compactions: deleteBatched(db, "compactions", "at IS NOT NULL AND at < ?", cutoff),
3569
3790
  usage: hasTable(db, "usage") ? deleteBatched(db, "usage", "at IS NOT NULL AND at < ?", cutoff) : 0
3570
3791
  };
3571
3792
  }
@@ -3573,7 +3794,7 @@ function wipeAll(db) {
3573
3794
  return {
3574
3795
  steps: deleteAllBatched(db, "steps"),
3575
3796
  prompts: deleteAllBatched(db, "prompts"),
3576
- events: deleteAllBatched(db, "events"),
3797
+ compactions: deleteAllBatched(db, "compactions"),
3577
3798
  usage: hasTable(db, "usage") ? deleteAllBatched(db, "usage") : 0,
3578
3799
  sessions: hasTable(db, "sessions") ? deleteAllBatched(db, "sessions") : 0
3579
3800
  };
@@ -3596,23 +3817,41 @@ function hasListCost(db) {
3596
3817
  }
3597
3818
  }
3598
3819
  var BACKFILL_BATCH = 1000;
3820
+ var UNPRICED_WHERE = `cost = 0 AND list_cost IS NULL
3821
+ AND provider_id IS NOT NULL AND provider_id <> ''
3822
+ AND model_id IS NOT NULL AND model_id <> ''
3823
+ AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`;
3824
+ function priceStep(step, price) {
3825
+ const estimate = price({ providerID: step.provider_id ?? undefined, modelID: step.model_id ?? undefined }, {
3826
+ input: step.input_tokens ?? 0,
3827
+ output: step.output_tokens ?? 0,
3828
+ reasoning: step.reasoning_tokens ?? 0,
3829
+ cacheRead: step.cache_read ?? 0,
3830
+ cacheWrite: step.cache_write ?? 0
3831
+ });
3832
+ return estimate !== undefined && Number.isFinite(estimate) && estimate >= 0 ? estimate : undefined;
3833
+ }
3834
+ function backfillBatch(db, rows, price, update) {
3835
+ let updated = 0;
3836
+ db.transaction(() => {
3837
+ for (const row of rows) {
3838
+ const estimate = priceStep(row, price);
3839
+ if (estimate !== undefined && update(estimate, row.rowid) > 0)
3840
+ updated += 1;
3841
+ }
3842
+ })();
3843
+ return updated;
3844
+ }
3599
3845
  function backfillListCost(db, price) {
3600
3846
  if (!hasListCost(db))
3601
3847
  return { candidates: 0, updated: 0 };
3602
- const candidates = db.query(`SELECT COUNT(*) AS n FROM steps
3603
- WHERE cost = 0 AND list_cost IS NULL
3604
- AND provider_id IS NOT NULL AND provider_id <> ''
3605
- AND model_id IS NOT NULL AND model_id <> ''
3606
- AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`).get().n;
3848
+ const candidates = db.query(`SELECT COUNT(*) AS n FROM steps WHERE ${UNPRICED_WHERE}`).get().n;
3607
3849
  if (candidates === 0)
3608
3850
  return { candidates: 0, updated: 0 };
3609
3851
  const select = db.query(`SELECT rowid, provider_id, model_id,
3610
3852
  input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
3611
3853
  FROM steps
3612
- WHERE cost = 0 AND list_cost IS NULL AND rowid > ?
3613
- AND provider_id IS NOT NULL AND provider_id <> ''
3614
- AND model_id IS NOT NULL AND model_id <> ''
3615
- AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0
3854
+ WHERE ${UNPRICED_WHERE} AND rowid > ?
3616
3855
  ORDER BY rowid
3617
3856
  LIMIT ?`);
3618
3857
  const update = db.query("UPDATE steps SET list_cost = ? WHERE rowid = ? AND cost = 0 AND list_cost IS NULL");
@@ -3622,21 +3861,7 @@ function backfillListCost(db, price) {
3622
3861
  const rows = select.all(cursor, BACKFILL_BATCH);
3623
3862
  if (rows.length === 0)
3624
3863
  break;
3625
- db.transaction(() => {
3626
- for (const row of rows) {
3627
- const estimate = price({ providerID: row.provider_id ?? undefined, modelID: row.model_id ?? undefined }, {
3628
- input: row.input_tokens ?? 0,
3629
- output: row.output_tokens ?? 0,
3630
- reasoning: row.reasoning_tokens ?? 0,
3631
- cacheRead: row.cache_read ?? 0,
3632
- cacheWrite: row.cache_write ?? 0
3633
- });
3634
- if (estimate === undefined || !Number.isFinite(estimate) || estimate < 0)
3635
- continue;
3636
- if (update.run(estimate, row.rowid).changes > 0)
3637
- updated += 1;
3638
- }
3639
- })();
3864
+ updated += backfillBatch(db, rows, price, (estimate, rowid) => update.run(estimate, rowid).changes);
3640
3865
  cursor = rows[rows.length - 1].rowid;
3641
3866
  if (rows.length < BACKFILL_BATCH)
3642
3867
  break;
@@ -3877,4 +4102,4 @@ scope.onmessage = (event) => {
3877
4102
  }
3878
4103
  };
3879
4104
 
3880
- //# debugId=0FF21E19CAE9E2DE64756E2164756E21
4105
+ //# debugId=E499AA8C5F2EFBAF64756E2164756E21