opencode-usage-insights 0.3.0 → 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 (58) 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 +2066 -1363
  6. package/dist/index.js.map +25 -18
  7. package/dist/limits.d.ts +9 -0
  8. package/dist/line.d.ts +1 -0
  9. package/dist/panel-data.d.ts +56 -7
  10. package/dist/recorder.d.ts +1 -0
  11. package/dist/rpc.d.ts +4 -4
  12. package/dist/rpc.js +7 -6
  13. package/dist/rpc.js.map +4 -4
  14. package/dist/settings-client.d.ts +29 -0
  15. package/dist/settings-rpc.d.ts +746 -0
  16. package/dist/settings.d.ts +114 -0
  17. package/dist/sidebar.d.ts +3 -3
  18. package/dist/stats/aggregates.d.ts +19 -4
  19. package/dist/stats/constants.d.ts +7 -0
  20. package/dist/stats/db.d.ts +8 -128
  21. package/dist/stats/legacy.d.ts +25 -0
  22. package/dist/stats/maintenance.d.ts +1 -1
  23. package/dist/stats/migrate.d.ts +7 -0
  24. package/dist/stats/ndjson.d.ts +16 -0
  25. package/dist/stats/open.d.ts +15 -0
  26. package/dist/stats/paths.d.ts +5 -4
  27. package/dist/stats/queries.d.ts +25 -31
  28. package/dist/stats/records.d.ts +94 -0
  29. package/dist/stats/schema.d.ts +26 -0
  30. package/dist/stats-client.d.ts +9 -0
  31. package/dist/stats-worker.js +1012 -604
  32. package/dist/stats-worker.js.map +19 -14
  33. package/dist/text.d.ts +2 -0
  34. package/dist/tui-settings.d.ts +18 -0
  35. package/dist/tui.d.ts +1 -57
  36. package/dist/tui.js +1364 -384
  37. package/dist/tui.js.map +17 -13
  38. package/docs/cli.md +24 -0
  39. package/docs/configuration.md +108 -0
  40. package/docs/costs.md +44 -0
  41. package/docs/demo.md +94 -68
  42. package/docs/desktop.md +91 -0
  43. package/docs/images/desktop-overview-annotated.png +0 -0
  44. package/docs/images/desktop-overview.png +0 -0
  45. package/docs/images/desktop-settings.png +0 -0
  46. package/docs/images/desktop-turns-go-annotated.png +0 -0
  47. package/docs/images/desktop-turns.png +0 -0
  48. package/docs/images/line.png +0 -0
  49. package/docs/images/panel-cache.png +0 -0
  50. package/docs/images/panel-help.png +0 -0
  51. package/docs/images/panel-latency.png +0 -0
  52. package/docs/images/panel-overview.png +0 -0
  53. package/docs/images/panel-providers.png +0 -0
  54. package/docs/images/sidebar.png +0 -0
  55. package/docs/internals.md +87 -36
  56. package/docs/privacy.md +60 -0
  57. package/docs/tui.md +175 -0
  58. 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;
168
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;
169
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;
215
+ }
216
+ return cleaned;
217
+ }
218
+ function sanitizeLabel(value, limit = TEXT_LIMIT) {
219
+ return sanitizeText(value, limit).trim();
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,122 +523,12 @@ 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
 
430
529
  // src/limits.ts
431
530
  var MAX_PANEL_WIDTH = 200;
531
+ var MAX_HISTORY_WIDTH = 120;
432
532
  var MAX_TURNS = 50;
433
533
  function clampPanelWidth(value) {
434
534
  if (!Number.isFinite(value))
@@ -786,7 +886,6 @@ function formatLine(stats, options) {
786
886
  }
787
887
 
788
888
  // src/stats/queries.ts
789
- var COMPACTION_KIND = "compaction";
790
889
  var DEFAULT_TTL_HINT_MS = 10 * 60 * 1000;
791
890
  function spend(usage) {
792
891
  return usage.cost + usage.listCost;
@@ -856,9 +955,10 @@ function otherUsageRows(db, range, filters) {
856
955
  }
857
956
  }
858
957
  var STEP_TIME = "COALESCE(created_at, recorded_at)";
859
- 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, '')`;
860
960
  function modelKey(modelID, variant) {
861
- return `${modelID}#${variant ?? ""}`;
961
+ return `${modelID}${MODEL_KEY_SEPARATOR}${variant ?? ""}`;
862
962
  }
863
963
  function modelLabel(modelID, variant) {
864
964
  return variant === undefined ? modelID : `${modelID} ${variant}`;
@@ -929,7 +1029,10 @@ function overview(db, range, filters) {
929
1029
  MIN(${STEP_TIME}) AS firstAt,
930
1030
  MAX(COALESCE(completed_at, ${STEP_TIME})) AS lastAt,
931
1031
  COALESCE(SUM(CASE WHEN streamed_at > created_at THEN output_tokens + reasoning_tokens ELSE 0 END), 0) AS produced,
932
- 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
933
1036
  FROM steps ${steps.where}`).get(...steps.params);
934
1037
  const prompts = rangeWhere(range, "created_at");
935
1038
  const promptClauses = prompts.where === "" ? [] : [prompts.where.slice("WHERE ".length)];
@@ -940,6 +1043,10 @@ function overview(db, range, filters) {
940
1043
  }
941
1044
  const promptWhere = promptClauses.length > 0 ? `WHERE ${promptClauses.join(" AND ")}` : "";
942
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);
943
1050
  const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
944
1051
  const other = otherUsage(db, range, filters);
945
1052
  return {
@@ -951,7 +1058,9 @@ function overview(db, range, filters) {
951
1058
  firstAt: row?.firstAt ?? undefined,
952
1059
  lastAt: row?.lastAt ?? undefined,
953
1060
  cacheHitRatio: cacheHitRatio(usage),
954
- 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
955
1064
  };
956
1065
  }
957
1066
  function models(db, range, filters) {
@@ -1106,7 +1215,11 @@ function stepMessage(row) {
1106
1215
  return {
1107
1216
  type: "assistant",
1108
1217
  id: row.message_id,
1109
- 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
+ },
1110
1223
  model: row.provider_id !== null && row.model_id !== null ? { providerID: row.provider_id, id: row.model_id, variant: row.variant ?? undefined } : undefined,
1111
1224
  tokens: {
1112
1225
  input: row.input_tokens ?? 0,
@@ -1137,7 +1250,7 @@ function turns(db, options) {
1137
1250
  }
1138
1251
  const steps = db.query(`SELECT message_id, session_id, provider_id, model_id, variant,
1139
1252
  input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,
1140
- created_at, streamed_at, recorded_at, completed_at, finish
1253
+ created_at, first_token_at, streamed_at, recorded_at, completed_at, finish
1141
1254
  FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
1142
1255
  ORDER BY session_id, ${STEP_TIME}, message_id`).all(...params);
1143
1256
  const promptClause = options?.sessionID === undefined ? "" : `WHERE session_id = ?${floor === undefined ? "" : " AND created_at >= ?"}`;
@@ -1180,12 +1293,22 @@ function turns(db, options) {
1180
1293
  const variant = last.variant ?? undefined;
1181
1294
  let produced = 0;
1182
1295
  let window = 0;
1296
+ let decodeProduced = 0;
1297
+ let decodeWindow = 0;
1183
1298
  for (const row of bucket) {
1184
- if (row.created_at === null || row.streamed_at === null || row.streamed_at <= row.created_at)
1185
- continue;
1186
- produced += (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0);
1187
- 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
+ }
1188
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;
1189
1312
  const previous = result.length > 0 && result[result.length - 1].sessionID === last.session_id ? result[result.length - 1] : undefined;
1190
1313
  const endAt = last.completed_at ?? last.created_at ?? last.recorded_at;
1191
1314
  const firstAt = bucket[0]?.created_at ?? promptAt;
@@ -1205,7 +1328,9 @@ function turns(db, options) {
1205
1328
  totals,
1206
1329
  drops,
1207
1330
  finish: last.finish ?? undefined,
1208
- tps: tokensPerSecond(produced, 0, window)
1331
+ tps: tokensPerSecond(decodeProduced, 0, decodeWindow),
1332
+ requestTps: tokensPerSecond(produced, 0, window),
1333
+ ttft
1209
1334
  });
1210
1335
  bucket = [];
1211
1336
  }
@@ -1283,8 +1408,9 @@ var STEP_COLUMNS = `message_id AS messageID, session_id AS sessionID, provider_i
1283
1408
  COALESCE(input_tokens, 0) AS input, COALESCE(cache_read, 0) AS cached, COALESCE(cache_write, 0) AS cacheWrite,
1284
1409
  COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, COALESCE(cost, 0) AS cost,
1285
1410
  COALESCE(list_cost, 0) AS listCost,
1286
- created_at AS createdAt, streamed_at AS streamedAt, completed_at AS completedAt, ${STEP_AT} AS at`;
1287
- 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"];
1288
1414
  var PAIR_COLUMNS = STEP_COLUMNS.replace("COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, ", "");
1289
1415
  function stepRows(db, options) {
1290
1416
  const filter = buildWhere(options?.range, options?.filters);
@@ -1363,6 +1489,7 @@ function coverageOf(db, options) {
1363
1489
  COALESCE(SUM(CASE WHEN model_id IS NULL THEN 1 ELSE 0 END), 0) AS missingModel,
1364
1490
  COALESCE(SUM(CASE WHEN completed_at IS NOT NULL OR finish IS NOT NULL THEN 0 ELSE 1 END), 0) AS unsettled,
1365
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,
1366
1493
  MIN(${STEP_AT}) AS firstAt,
1367
1494
  MAX(${STEP_AT}) AS lastAt
1368
1495
  FROM steps ${filter.where}`).get(...filter.params);
@@ -1373,6 +1500,7 @@ function coverageOf(db, options) {
1373
1500
  missingModel: row.missingModel,
1374
1501
  unsettled: row.unsettled,
1375
1502
  missingTps: row.missingTps,
1503
+ missingFirstToken: row.missingFirstToken,
1376
1504
  firstAt: row.firstAt ?? undefined,
1377
1505
  lastAt: row.lastAt ?? undefined
1378
1506
  };
@@ -1385,7 +1513,14 @@ function groupedRows(db, options) {
1385
1513
  function timingOf(step) {
1386
1514
  const wall = step.createdAt !== undefined && step.completedAt !== undefined ? Math.max(0, step.completedAt - step.createdAt) : undefined;
1387
1515
  const stream = step.createdAt !== undefined && step.streamedAt !== undefined && step.streamedAt > step.createdAt ? step.streamedAt - step.createdAt : undefined;
1388
- 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
+ };
1389
1524
  }
1390
1525
  function timingRows(db, options) {
1391
1526
  return groupedRows(db, options);
@@ -1393,17 +1528,29 @@ function timingRows(db, options) {
1393
1528
  function latencyOf(rows) {
1394
1529
  const wall = [];
1395
1530
  const stream = [];
1531
+ const ttft = [];
1396
1532
  const tps = [];
1533
+ const requestTps = [];
1397
1534
  for (const step of rows) {
1398
1535
  const timing = timingOf(step);
1399
1536
  if (timing.wall !== undefined)
1400
1537
  wall.push(timing.wall);
1401
1538
  if (timing.stream !== undefined)
1402
1539
  stream.push(timing.stream);
1540
+ if (timing.ttft !== undefined)
1541
+ ttft.push(timing.ttft);
1403
1542
  if (timing.tps !== undefined)
1404
1543
  tps.push(timing.tps);
1544
+ if (timing.requestTps !== undefined)
1545
+ requestTps.push(timing.requestTps);
1405
1546
  }
1406
- 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
+ };
1407
1554
  }
1408
1555
  function latencyGroupsOf(rows, by) {
1409
1556
  const key = (step) => by === "model" ? modelKey(step.modelID ?? "(unknown)", step.variant) : step.providerID ?? "(unknown)";
@@ -1411,25 +1558,33 @@ function latencyGroupsOf(rows, by) {
1411
1558
  for (const [group, steps] of groupBy(rows, key)) {
1412
1559
  const wall = [];
1413
1560
  const stream = [];
1561
+ const ttft = [];
1414
1562
  const tps = [];
1563
+ const requestTps = [];
1415
1564
  for (const step of steps) {
1416
1565
  const timing = timingOf(step);
1417
1566
  if (timing.wall !== undefined)
1418
1567
  wall.push(timing.wall);
1419
1568
  if (timing.stream !== undefined)
1420
1569
  stream.push(timing.stream);
1570
+ if (timing.ttft !== undefined)
1571
+ ttft.push(timing.ttft);
1421
1572
  if (timing.tps !== undefined)
1422
1573
  tps.push(timing.tps);
1574
+ if (timing.requestTps !== undefined)
1575
+ requestTps.push(timing.requestTps);
1423
1576
  }
1424
- const [modelID, variant] = group.split("#");
1577
+ const { modelID, variant } = splitModelKey(group);
1425
1578
  groups.push({
1426
1579
  key: group,
1427
- label: by === "model" ? variant === undefined || variant === "" ? modelID : `${modelID} ${variant}` : group,
1580
+ label: by === "model" ? variant === undefined ? modelID : `${modelID} ${variant}` : group,
1428
1581
  count: steps.length,
1429
1582
  usage: usageOf(steps),
1430
1583
  wall: latencyStats(wall),
1431
1584
  stream: latencyStats(stream),
1432
- tps: latencyStats(tps)
1585
+ ttft: latencyStats(ttft),
1586
+ tps: latencyStats(tps),
1587
+ requestTps: latencyStats(requestTps)
1433
1588
  });
1434
1589
  }
1435
1590
  return groups.sort((left, right) => right.count - left.count || left.key.localeCompare(right.key));
@@ -1512,7 +1667,10 @@ var GAP_BUCKETS = [
1512
1667
  ["<1m", 0, 60000],
1513
1668
  ["1\u20135m", 60000, 5 * 60000],
1514
1669
  ["5\u201315m", 5 * 60000, 15 * 60000],
1515
- ["15\u201360m", 15 * 60000, 60 * 60000],
1670
+ ["15\u201320m", 15 * 60000, 20 * 60000],
1671
+ ["20\u201330m", 20 * 60000, 30 * 60000],
1672
+ ["30\u201345m", 30 * 60000, 45 * 60000],
1673
+ ["45\u201360m", 45 * 60000, 60 * 60000],
1516
1674
  ["1\u20136h", 60 * 60000, 6 * 60 * 60000],
1517
1675
  [">6h", 6 * 60 * 60000, undefined]
1518
1676
  ];
@@ -1606,21 +1764,21 @@ function cacheDropsOf(db, rows, options) {
1606
1764
  }
1607
1765
  if (losses.length === 0)
1608
1766
  return [];
1609
- const compactions = new Map;
1767
+ const times = new Map;
1610
1768
  const sessionIDs = [...new Set(losses.map((loss) => loss.current.sessionID))];
1611
- const events = db.query(`SELECT session_id, at FROM events
1612
- 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(", ")})
1613
1771
  ORDER BY at`).all(...sessionIDs);
1614
- for (const event of events) {
1615
- const list = compactions.get(event.session_id);
1772
+ for (const row of timeline) {
1773
+ const list = times.get(row.session_id);
1616
1774
  if (list !== undefined)
1617
- list.push(event.at);
1775
+ list.push(row.at);
1618
1776
  else
1619
- compactions.set(event.session_id, [event.at]);
1777
+ times.set(row.session_id, [row.at]);
1620
1778
  }
1621
1779
  return losses.map((loss) => {
1622
1780
  const ended = loss.previous.completedAt ?? loss.previous.streamedAt ?? loss.previous.createdAt;
1623
- 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);
1624
1782
  const reason = compacted ? "compaction" : loss.gapMs !== undefined && loss.gapMs >= ttlHint ? "expired" : "unknown";
1625
1783
  return {
1626
1784
  sessionID: loss.current.sessionID,
@@ -1639,14 +1797,34 @@ function cacheDropsOf(db, rows, options) {
1639
1797
  function groupValues(steps) {
1640
1798
  const wall = [];
1641
1799
  const tps = [];
1800
+ const requestTps = [];
1801
+ const ttft = [];
1642
1802
  for (const step of steps) {
1643
1803
  const timing = timingOf(step);
1644
1804
  if (timing.wall !== undefined)
1645
1805
  wall.push(timing.wall);
1646
1806
  if (timing.tps !== undefined)
1647
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);
1648
1812
  }
1649
- 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 };
1650
1828
  }
1651
1829
  function providerOf(steps, models) {
1652
1830
  const values = groupValues(steps);
@@ -1660,17 +1838,22 @@ function providerOf(steps, models) {
1660
1838
  }
1661
1839
  return {
1662
1840
  provider: steps[0].providerID,
1663
- models: models.split("\x00"),
1841
+ models: models.split(MODEL_LIST_SEPARATOR),
1664
1842
  share: 0,
1665
1843
  usage: usageOf(steps),
1666
1844
  cache: values.cache,
1667
1845
  tps: values.tps,
1846
+ requestTps: values.requestTps,
1847
+ ttft: values.ttft,
1668
1848
  wall: values.wall,
1669
1849
  firstAt,
1670
1850
  lastAt
1671
1851
  };
1672
1852
  }
1673
- 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);
1674
1857
  function providerSummaryOf(rows) {
1675
1858
  const out = [];
1676
1859
  for (const steps of groupBy(rows, (step) => step.providerID ?? "").values()) {
@@ -1683,7 +1866,7 @@ function providerBreakdownOf(rows) {
1683
1866
  const out = [];
1684
1867
  for (const [model, modelRows] of groupBy(rows, (step) => modelKey(step.modelID ?? "(unknown)", step.variant))) {
1685
1868
  for (const steps of groupBy(modelRows, (step) => step.providerID ?? "").values()) {
1686
- const [modelID, variant] = [model.slice(0, model.indexOf("#")), model.slice(model.indexOf("#") + 1)];
1869
+ const { modelID, variant } = splitModelKey(model);
1687
1870
  out.push({
1688
1871
  ...providerOf(steps, modelNames(steps)),
1689
1872
  modelID,
@@ -1889,8 +2072,8 @@ var RANGE_KEYS = ["session", "today", "7d", "30d", "all"];
1889
2072
  var GRANULARITIES = ["day", "week", "month"];
1890
2073
  var SORT_KEYS = {
1891
2074
  models: ["steps", "cached", "hit", "out", "cost"],
1892
- providers: ["steps", "cached", "hit", "cost", "share", "tps"],
1893
- latency: ["n", "tps", "wall"],
2075
+ providers: ["steps", "cached", "hit", "cost", "share", "tps", "ttft"],
2076
+ latency: ["n", "tps", "ttft", "wall"],
1894
2077
  sessions: ["last", "steps", "cached", "cost"],
1895
2078
  turns: ["time", "cost", "tokens"]
1896
2079
  };
@@ -1988,10 +2171,10 @@ function formatTps(value) {
1988
2171
  return "\u2013";
1989
2172
  return `${value.toFixed(1)}/s`;
1990
2173
  }
1991
- function formatTpsCompact(value) {
2174
+ function formatRateValue(value) {
1992
2175
  if (value === undefined || !Number.isFinite(value) || value < 0)
1993
2176
  return "\u2013";
1994
- return value >= 10 ? `${Math.round(value)}/s` : `${value.toFixed(1)}/s`;
2177
+ return value >= 10 ? String(Math.round(value)) : value.toFixed(1);
1995
2178
  }
1996
2179
  function formatGap(value) {
1997
2180
  if (value === undefined || !Number.isFinite(value))
@@ -2023,15 +2206,6 @@ function truncateMiddle(value, width) {
2023
2206
  const tail = width - 1 - head;
2024
2207
  return `${clean.slice(0, head)}\u2026${clean.slice(clean.length - tail)}`;
2025
2208
  }
2026
- function tableWidths(width, layouts) {
2027
- for (const layout of layouts) {
2028
- const total = layout.reduce((sum, column) => sum + column, 0) + layout.length - 1;
2029
- if (total <= width)
2030
- return [...layout];
2031
- }
2032
- const last = layouts[layouts.length - 1];
2033
- return last === undefined ? [] : [...last];
2034
- }
2035
2209
  function modelCell(modelID, variant, width) {
2036
2210
  return truncateMiddle(variant === undefined ? modelID : `${modelID} ${variant}`, width);
2037
2211
  }
@@ -2050,6 +2224,47 @@ function formatTableRow(cells, widths, aligns) {
2050
2224
  }
2051
2225
  return parts.join(" ");
2052
2226
  }
2227
+ function fitTableColumns(columns, width) {
2228
+ const chosen = new Set;
2229
+ for (let index = 0;index < columns.length; index += 1) {
2230
+ if (columns[index].priority === undefined)
2231
+ chosen.add(index);
2232
+ }
2233
+ if (chosen.size === 0)
2234
+ return [];
2235
+ const total = () => {
2236
+ let sum = chosen.size - 1;
2237
+ for (const index of chosen)
2238
+ sum += columns[index].width;
2239
+ return sum;
2240
+ };
2241
+ const optional = columns.map((column, index) => ({ column, index })).filter((entry) => entry.column.priority !== undefined).sort((left, right) => left.column.priority - right.column.priority || left.index - right.index);
2242
+ for (const { column, index } of optional) {
2243
+ if (total() + column.width + 1 + (column.reserve ?? 0) <= width)
2244
+ chosen.add(index);
2245
+ }
2246
+ while (chosen.size > 1 && total() > width)
2247
+ chosen.delete(Math.max(...chosen));
2248
+ const widths = new Map;
2249
+ let room = width - total();
2250
+ for (let index = 0;index < columns.length && room > 0; index += 1) {
2251
+ if (!chosen.has(index))
2252
+ continue;
2253
+ const column = columns[index];
2254
+ const grow = Math.min(room, (column.max ?? column.width) - column.width);
2255
+ if (grow <= 0)
2256
+ continue;
2257
+ widths.set(index, column.width + grow);
2258
+ room -= grow;
2259
+ }
2260
+ return [...chosen].sort((left, right) => left - right).map((index) => ({ index, width: widths.get(index) ?? columns[index].width }));
2261
+ }
2262
+ function fitTable(columns, width) {
2263
+ return fitTableColumns(columns, width).map(({ index, width: fitted }) => {
2264
+ const column = columns[index];
2265
+ return { index, header: column.header, width: fitted, align: column.align ?? "left", cell: column.cell };
2266
+ });
2267
+ }
2053
2268
  function count(n, singular, plural = `${singular}s`) {
2054
2269
  return `${formatCount(n)} ${n === 1 ? singular : plural}`;
2055
2270
  }
@@ -2057,21 +2272,30 @@ function kvGrid(pairs, width) {
2057
2272
  const lines = [];
2058
2273
  const label = 11;
2059
2274
  const column = Math.floor(width / 2);
2275
+ const pairLines = (pair) => {
2276
+ const text = `${padCell(pair[0], label)}${pair[1]}`;
2277
+ if (text.length <= width)
2278
+ return [text];
2279
+ return [padCell(pair[0], label), ` ${pair[1]}`].map((line) => truncate(line, width));
2280
+ };
2060
2281
  for (let index = 0;index < pairs.length; index += 2) {
2061
2282
  const left = pairs[index];
2062
2283
  const right = pairs[index + 1];
2063
- const leftText = `${padCell(left[0], label)}${left[1]}`;
2064
2284
  if (right === undefined) {
2065
- lines.push({ text: leftText, tone: "base" });
2285
+ for (const text of pairLines(left))
2286
+ lines.push({ text, tone: "base" });
2066
2287
  continue;
2067
2288
  }
2289
+ const leftText = `${padCell(left[0], label)}${left[1]}`;
2068
2290
  const rightText = `${padCell(right[0], label)}${right[1]}`;
2069
2291
  const gap = Math.max(2, column - leftText.length);
2070
2292
  if (leftText.length + gap + rightText.length <= width) {
2071
2293
  lines.push({ text: `${leftText}${" ".repeat(gap)}${rightText}`, tone: "base" });
2072
2294
  } else {
2073
- lines.push({ text: leftText, tone: "base" });
2074
- lines.push({ text: rightText, tone: "base" });
2295
+ for (const text of pairLines(left))
2296
+ lines.push({ text, tone: "base" });
2297
+ for (const text of pairLines(right))
2298
+ lines.push({ text, tone: "base" });
2075
2299
  }
2076
2300
  }
2077
2301
  return lines;
@@ -2181,7 +2405,11 @@ function helpLines(width) {
2181
2405
  { text: " \u2248 list-price estimate for steps the host reported as $0;" },
2182
2406
  { text: " `$0.12 + \u2248 $3.40` keeps charged and estimated money apart" },
2183
2407
  { text: " wall request \u2192 completed step \xB7 stream request \u2192 last chunk" },
2184
- { 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" },
2185
2413
  { text: " switches how often a step's model or provider differs from the step" },
2186
2414
  { text: " before it in the same session (the models view's detail), with" },
2187
2415
  { text: " the cache a provider switch cost" },
@@ -2310,26 +2538,32 @@ function usagePairs(usage, estimates = true) {
2310
2538
  ];
2311
2539
  if (buckets.reasoning > 0)
2312
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)]);
2313
2547
  pairs.push(["cost", (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost)]);
2314
2548
  const other = usage.otherCost ?? 0;
2315
2549
  if (other > 0)
2316
2550
  pairs.push(["other", `${formatCost(other)} comp/title`]);
2317
- if ("tps" in usage && usage.tps !== undefined)
2318
- pairs.push(["tps", formatTps(usage.tps)]);
2319
2551
  return pairs;
2320
2552
  }
2321
2553
  function overviewLines(data, width) {
2322
2554
  const lines = [];
2323
2555
  const estimates = data.estimates !== false;
2324
2556
  lines.push({
2325
- text: `${rangeLabel(data.range)} \xB7 ${count(data.usage.steps, "step")} \xB7 ${count(data.usage.sessions, "session")} \xB7 ${count(data.usage.prompts, "prompt")}`,
2557
+ text: truncate(`${rangeLabel(data.range)} \xB7 ${count(data.usage.steps, "step")} \xB7 ${count(data.usage.sessions, "session")} \xB7 ${count(data.usage.prompts, "prompt")}`, width),
2326
2558
  tone: "muted"
2327
2559
  });
2328
2560
  lines.push(...kvGrid(buildOverviewPairs(data.usage, "all", estimates), width));
2329
2561
  if (data.activity !== undefined && data.activity.length > 1) {
2330
- const series = reduceSeries(data.activity);
2562
+ const suffix = ` ${count(data.activity.length, "bucket")}`;
2563
+ const bars = Math.max(4, width - "activity ".length - suffix.length);
2564
+ const series = reduceSeries(data.activity, bars);
2331
2565
  lines.push({ text: "", tone: "muted" });
2332
- lines.push({ text: `activity ${sparkline(series)} ${count(series.length, "bucket")}`, tone: "muted" });
2566
+ lines.push({ text: truncate(`activity ${sparkline(series)}${suffix}`, width), tone: "muted" });
2333
2567
  }
2334
2568
  if (data.session !== undefined) {
2335
2569
  lines.push({ text: "", tone: "muted" });
@@ -2340,7 +2574,7 @@ function overviewLines(data, width) {
2340
2574
  const cost = data.subagents.reduce((sum, row) => sum + row.cost, 0);
2341
2575
  const listCost = data.subagents.reduce((sum, row) => sum + row.listCost, 0);
2342
2576
  lines.push({
2343
- text: ` subagents ${count(data.subagents.length, "session")} \xB7 ${count(steps, "step")} \xB7 ${formatSpend(cost, estimates ? listCost : 0)} (their own sessions)`,
2577
+ text: truncate(` subagents ${count(data.subagents.length, "session")} \xB7 ${count(steps, "step")} \xB7 ${formatSpend(cost, estimates ? listCost : 0)} (their own sessions)`, width),
2344
2578
  tone: "muted"
2345
2579
  });
2346
2580
  }
@@ -2366,71 +2600,40 @@ function coveragePairs(coverage) {
2366
2600
  ["models", `${formatCount(coverage.models)} \xB7 unknown ${share(coverage.missingModel)}`],
2367
2601
  ["providers", formatCount(coverage.providers)],
2368
2602
  ["unsettled", `${formatCount(coverage.unsettled)} \xB7 no tps ${share(coverage.missingTps)}`],
2603
+ ["no ttft", share(coverage.missingFirstToken)],
2369
2604
  [
2370
2605
  "window",
2371
2606
  `${coverage.firstAt === undefined ? "\u2013" : new Date(coverage.firstAt).toLocaleString("en-GB")} \u2192 ${coverage.lastAt === undefined ? "\u2013" : new Date(coverage.lastAt).toLocaleString("en-GB")}`
2372
2607
  ]
2373
2608
  ];
2374
2609
  }
2375
- function modelColumns(width) {
2376
- const layouts = [
2377
- { model: 30, steps: 6, prompt: 10, cached: 10, hit: 7, out: 9, cost: 9, spread: 24 },
2378
- { model: 26, steps: 6, prompt: 9, cached: 9, hit: 7, out: 8, cost: 8, spread: 20 },
2379
- { model: 20, steps: 6, prompt: 9, cached: 9, hit: 6, out: 8, cost: 8, spread: 0 },
2380
- { model: 18, steps: 5, prompt: 8, cached: 8, hit: 0, out: 7, cost: 8, spread: 0 },
2381
- { model: 14, steps: 5, prompt: 8, cached: 8, hit: 0, out: 7, cost: 0, spread: 0 }
2382
- ];
2383
- for (const layout of layouts) {
2384
- const total = Object.values(layout).reduce((sum, column) => sum + column, 0) + Object.values(layout).filter((column) => column > 0).length - 1;
2385
- if (total <= width)
2386
- return layout;
2387
- }
2388
- return layouts[layouts.length - 1];
2389
- }
2390
2610
  function modelsLines(rows, width, extras, limit = 40, estimates = true) {
2391
- const columns = modelColumns(width);
2392
- const widths = [columns.model, columns.steps, columns.prompt, columns.cached];
2393
- const aligns = ["left", "right", "right", "right"];
2394
- const header = ["model", "steps", "prompt", "cached"];
2395
- if (columns.hit > 0) {
2396
- widths.push(columns.hit);
2397
- aligns.push("right");
2398
- header.push("hit");
2399
- }
2400
- widths.push(columns.out);
2401
- aligns.push("right");
2402
- header.push("out");
2403
- if (columns.cost > 0) {
2404
- widths.push(columns.cost);
2405
- aligns.push("right");
2406
- header.push("cost");
2407
- }
2408
- if (columns.spread > 0) {
2409
- widths.push(columns.spread);
2410
- aligns.push("left");
2411
- header.push("providers");
2412
- }
2413
- const lines = [{ text: formatTableRow(header, widths, aligns), tone: HEADER_TONE }];
2611
+ let modelWidth = 14;
2612
+ const columns = fitTable([
2613
+ { header: "model", width: 14, max: 36, cell: (row) => modelCell(row.modelID, row.variant, modelWidth) },
2614
+ { header: "steps", width: 6, align: "right", cell: (row) => row.steps },
2615
+ { header: "prompt", width: 7, max: 10, align: "right", cell: (row) => row.prompt },
2616
+ { header: "cached", width: 7, max: 10, align: "right", cell: (row) => row.cached },
2617
+ { header: "hit", width: 6, max: 7, priority: 2, reserve: 10, align: "right", cell: (row) => row.hit },
2618
+ { header: "out", width: 7, max: 9, priority: 3, reserve: 10, align: "right", cell: (row) => row.output },
2619
+ { header: "cost", width: 8, max: 9, priority: 1, align: "right", cell: (row) => row.cost },
2620
+ { header: "providers", width: 18, max: 24, priority: 4, reserve: 22, cell: (row) => row.providers }
2621
+ ], width);
2622
+ modelWidth = columns.find((column) => column.index === 0)?.width ?? 0;
2623
+ if (columns.length === 0)
2624
+ return [{ text: truncate("no room for a table at this width", width), tone: "muted" }];
2625
+ const lines = [
2626
+ {
2627
+ text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)),
2628
+ tone: HEADER_TONE
2629
+ }
2630
+ ];
2414
2631
  for (const model of rows.slice(0, limit)) {
2415
2632
  const key = modelKey(model.modelID, model.variant);
2416
- const name = modelCell(model.modelID, model.variant, columns.model);
2417
2633
  const buckets = usageBuckets(model.totals);
2418
2634
  const providers = unique(model.providers.map((provider) => provider.providerID));
2419
2635
  const cache = extras?.cache?.get(key);
2420
2636
  const switches = extras?.switches?.get(key);
2421
- const cells = [name, formatCount(buckets.steps), formatTokens(buckets.prompt), formatTokens(buckets.cached)];
2422
- if (columns.hit > 0)
2423
- cells.push(formatPercent(cache?.hit ?? buckets.hit));
2424
- cells.push(formatTokens(buckets.output));
2425
- if (columns.cost > 0)
2426
- cells.push(formatSpend(buckets.cost, estimates ? buckets.listCost : 0));
2427
- if (columns.spread > 0)
2428
- cells.push(providers.join(", "));
2429
- lines.push({
2430
- text: formatTableRow(cells, widths, aligns),
2431
- tone: "base",
2432
- row: { kind: "model", value: model.modelID, ...model.variant !== undefined ? { variant: model.variant } : {} }
2433
- });
2434
2637
  const details = [];
2435
2638
  if (cache !== undefined)
2436
2639
  details.push(`p50 hit ${formatPercent(cache.hitP50)}`);
@@ -2440,62 +2643,77 @@ function modelsLines(rows, width, extras, limit = 40, estimates = true) {
2440
2643
  if (switches.cacheLost > 0)
2441
2644
  details.push(`${formatTokens(switches.cacheLost)} lost on a switch`);
2442
2645
  }
2443
- if (details.length > 0) {
2444
- lines.push({ text: truncate(`${" ".repeat(columns.model + 1)}${details.join(" \xB7 ")}`, width), tone: "muted" });
2646
+ const view = {
2647
+ modelID: model.modelID,
2648
+ variant: model.variant,
2649
+ steps: formatCount(buckets.steps),
2650
+ prompt: formatTokens(buckets.prompt),
2651
+ cached: formatTokens(buckets.cached),
2652
+ hit: formatPercent(cache?.hit ?? buckets.hit),
2653
+ output: formatTokens(buckets.output),
2654
+ cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0),
2655
+ providers: providers.join(", "),
2656
+ detail: details.join(" \xB7 ")
2657
+ };
2658
+ lines.push({
2659
+ text: formatTableRow(columns.map((column) => column.cell(view)), columns.map((column) => column.width), columns.map((column) => column.align)),
2660
+ tone: "base",
2661
+ row: { kind: "model", value: model.modelID, ...model.variant !== undefined ? { variant: model.variant } : {} }
2662
+ });
2663
+ if (view.detail !== "") {
2664
+ lines.push({ text: truncate(`${" ".repeat(modelWidth + 1)}${view.detail}`, width), tone: "muted" });
2445
2665
  }
2446
2666
  }
2447
2667
  if (rows.length > limit)
2448
- lines.push({ text: `\u2026 ${count(rows.length - limit, "more model")} \xB7 narrow the range or filter`, tone: "muted" });
2668
+ lines.push({ text: truncate(`\u2026 ${count(rows.length - limit, "more model")} \xB7 narrow the range or filter`, width), tone: "muted" });
2449
2669
  if (rows.length === 0)
2450
- lines.push({ text: "no usage recorded for this range", tone: "muted" });
2670
+ lines.push({ text: truncate("no usage recorded for this range", width), tone: "muted" });
2451
2671
  return lines;
2452
2672
  }
2453
2673
  function unique(values) {
2454
2674
  return [...new Set(values)];
2455
2675
  }
2456
- var tableWidth = (columns) => columns.reduce((sum, column) => sum + column.width, 0) + columns.length - 1;
2457
- function fitColumns(columns, width) {
2458
- const chosen = [...columns];
2459
- while (chosen.length > 1 && tableWidth(chosen) > width) {
2460
- const optional = [...chosen].reverse().findIndex((column) => column.optional === true);
2461
- if (optional === -1)
2462
- break;
2463
- chosen.splice(chosen.length - 1 - optional, 1);
2464
- }
2465
- return chosen;
2466
- }
2467
2676
  function renderTable(rows, columns, width, options) {
2468
- const chosen = fitColumns(columns, width);
2677
+ const chosen = fitTableColumns(columns, width).map(({ index, width: fitted }) => {
2678
+ const column = columns[index];
2679
+ const align = column.align ?? "left";
2680
+ return { ...column, width: fitted, align };
2681
+ });
2682
+ if (chosen.length === 0)
2683
+ return [{ text: truncate(options.empty, width), tone: "muted" }];
2469
2684
  const widths = chosen.map((column) => column.width);
2470
- const aligns = chosen.map((column) => column.align ?? "left");
2471
- const alignsTyped = aligns;
2472
- const lines = [{ text: formatTableRow(chosen.map((column) => column.header), widths, alignsTyped), tone: HEADER_TONE }];
2685
+ const aligns = chosen.map((column) => column.align);
2686
+ const lines = [
2687
+ { text: formatTableRow(chosen.map((column) => column.header), widths, aligns), tone: HEADER_TONE }
2688
+ ];
2473
2689
  if (rows.length === 0)
2474
- lines.push({ text: options.empty, tone: "muted" });
2690
+ lines.push({ text: truncate(options.empty, width), tone: "muted" });
2475
2691
  for (const row of rows.slice(0, options.limit)) {
2476
2692
  const identity = options.row?.(row);
2477
2693
  lines.push({
2478
- text: formatTableRow(chosen.map((column) => column.cell(row)), widths, alignsTyped),
2694
+ text: formatTableRow(chosen.map((column) => column.cell(row, column.width)), widths, aligns),
2479
2695
  tone: options.tone?.(row) ?? "base",
2480
2696
  ...identity === undefined ? {} : { row: identity }
2481
2697
  });
2482
2698
  }
2483
- if (rows.length > options.limit)
2484
- lines.push({ text: `\u2026 ${count(rows.length - options.limit, "more row")}`, tone: "muted" });
2699
+ if (rows.length > options.limit) {
2700
+ lines.push({ text: truncate(`\u2026 ${count(rows.length - options.limit, "more row")}`, width), tone: "muted" });
2701
+ }
2485
2702
  return lines;
2486
2703
  }
2487
2704
  function providerSummaryLines(rows, width, limit = 40, estimates = true) {
2488
2705
  const lines = renderTable(rows, [
2489
- { header: "provider", width: 24, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 24) },
2490
- { header: "models", width: 13, align: "right", optional: true, cell: (row) => formatCount(row.models.length) },
2706
+ { header: "provider", width: 14, max: 32, cell: (row, column) => truncate(row.provider ?? "\u2013 (unknown)", column) },
2707
+ { header: "models", width: 6, align: "right", priority: 4, cell: (row) => formatCount(row.models.length) },
2491
2708
  { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.usage.steps) },
2492
- { header: "share", width: 6, align: "right", optional: true, cell: (row) => formatPercent(row.share, 0) },
2493
- { header: "prompt", width: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
2494
- { header: "cached", width: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
2495
- { header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
2496
- { header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
2497
- { header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
2498
- { header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
2709
+ { header: "share", width: 6, align: "right", priority: 3, cell: (row) => formatPercent(row.share, 0) },
2710
+ { header: "prompt", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
2711
+ { header: "cached", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
2712
+ { header: "hit", width: 6, max: 7, align: "right", priority: 2, cell: (row) => formatPercent(row.cache.hit) },
2713
+ { header: "tps p50", width: 8, align: "right", priority: 5, cell: (row) => formatTps(row.tps) },
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) },
2716
+ { header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
2499
2717
  ], width, {
2500
2718
  limit,
2501
2719
  empty: "no usage recorded for this range",
@@ -2506,16 +2724,17 @@ function providerSummaryLines(rows, width, limit = 40, estimates = true) {
2506
2724
  }
2507
2725
  function providerLines(rows, width, limit = 40, estimates = true) {
2508
2726
  return renderTable(rows, [
2509
- { header: "model", width: 26, cell: (row) => modelCell(row.modelID, row.variant, 26) },
2510
- { header: "provider", width: 22, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 22) },
2727
+ { header: "model", width: 24, max: 30, cell: (row, column) => modelCell(row.modelID, row.variant, column) },
2728
+ { header: "provider", width: 12, max: 24, cell: (row, column) => truncate(row.provider ?? "\u2013 (unknown)", column) },
2511
2729
  { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.usage.steps) },
2512
- { header: "share", width: 6, align: "right", optional: true, cell: (row) => formatPercent(row.share, 0) },
2513
- { header: "prompt", width: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
2514
- { header: "cached", width: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
2515
- { header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
2516
- { header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
2517
- { header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
2518
- { header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
2730
+ { header: "share", width: 6, align: "right", priority: 5, cell: (row) => formatPercent(row.share, 0) },
2731
+ { header: "prompt", width: 7, max: 10, align: "right", priority: 2, cell: (row) => formatTokens(row.cache.prompt) },
2732
+ { header: "cached", width: 7, max: 10, align: "right", priority: 3, cell: (row) => formatTokens(row.cache.cached) },
2733
+ { header: "hit", width: 6, max: 7, align: "right", priority: 4, cell: (row) => formatPercent(row.cache.hit) },
2734
+ { header: "tps p50", width: 8, align: "right", priority: 6, cell: (row) => formatTps(row.tps) },
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) },
2737
+ { header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
2519
2738
  ], width, {
2520
2739
  limit,
2521
2740
  empty: "no usage recorded for this range",
@@ -2525,80 +2744,126 @@ function providerLines(rows, width, limit = 40, estimates = true) {
2525
2744
  }
2526
2745
  function cacheLines(data, width) {
2527
2746
  const lines = [];
2747
+ const push = (text, tone = "base") => {
2748
+ lines.push({ text: truncate(text, width), tone });
2749
+ };
2528
2750
  const total = data.drops.reduce((sum, drop) => sum + drop.tokens, 0);
2529
- lines.push({ text: `reuse losses ${count(data.drops.length, "event")} \xB7 ${formatTokens(total)} tokens`, tone: total > 0 ? "warning" : "base" });
2751
+ push(`reuse losses ${count(data.drops.length, "event")} \xB7 ${formatTokens(total)} tokens`, total > 0 ? "warning" : "base");
2530
2752
  for (const reason of ["expired", "compaction", "unknown"]) {
2531
2753
  const group = data.drops.filter((drop) => drop.reason === reason);
2532
2754
  if (group.length === 0)
2533
2755
  continue;
2534
2756
  const tokens = group.reduce((sum, drop) => sum + drop.tokens, 0);
2535
- lines.push({ text: ` ${padCell(reason, 11)}${formatCount(group.length)} \xB7 ${formatTokens(tokens)}`, tone: reason === "expired" ? "warning" : "muted" });
2757
+ push(` ${padCell(reason, 11)}${formatCount(group.length)} \xB7 ${formatTokens(tokens)}`, reason === "expired" ? "warning" : "muted");
2536
2758
  }
2537
2759
  if (data.drops.length === 0)
2538
- lines.push({ text: " none: prompt cache held through every gap", tone: "muted" });
2760
+ push(" none: prompt cache held through every gap", "muted");
2539
2761
  if (data.models !== undefined && data.models.length > 0) {
2540
2762
  lines.push({ text: "", tone: "muted" });
2541
- lines.push({ text: "reuse by model", tone: HEADER_TONE });
2542
- const widths = width >= 100 ? [30, 7, 11, 10, 8, 8, 10] : [18, 6, 9, 9, 7, 7, 9];
2543
- lines.push({ text: formatTableRow(["model", "steps", "prompt", "cached", "write", "hit", "hit p50"], widths, ["left", "right", "right", "right", "right", "right", "right"]), tone: "muted" });
2544
- for (const row of data.models.slice(0, 10)) {
2545
- const name = modelCell(row.usage.modelID, row.usage.variant, widths[0]);
2546
- lines.push({
2547
- text: formatTableRow([name, formatCount(row.cache.steps), formatTokens(row.cache.prompt), formatTokens(row.cache.cached), formatTokens(row.cache.cacheWrite), formatPercent(row.cache.hit), formatPercent(row.cache.hitP50)], widths, ["left", "right", "right", "right", "right", "right", "right"]),
2548
- tone: "base",
2549
- row: { kind: "model", value: row.usage.modelID, ...row.usage.variant !== undefined ? { variant: row.usage.variant } : {} }
2550
- });
2763
+ push("reuse by model", HEADER_TONE);
2764
+ let modelWidth = 12;
2765
+ const reuse = fitTable([
2766
+ { header: "model", width: 12, max: 30, cell: (row) => modelCell(row.usage.modelID, row.usage.variant, modelWidth) },
2767
+ { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.cache.steps) },
2768
+ { header: "prompt", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
2769
+ { header: "cached", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
2770
+ { header: "write", width: 6, max: 8, align: "right", priority: 1, cell: (row) => formatTokens(row.cache.cacheWrite) },
2771
+ { header: "hit", width: 6, max: 7, align: "right", priority: 2, cell: (row) => formatPercent(row.cache.hit) },
2772
+ { header: "hit p50", width: 7, max: 9, align: "right", priority: 3, cell: (row) => formatPercent(row.cache.hitP50) }
2773
+ ], width);
2774
+ modelWidth = reuse.find((column) => column.index === 0)?.width ?? 0;
2775
+ if (reuse.length > 0) {
2776
+ lines.push({ text: formatTableRow(reuse.map((column) => column.header), reuse.map((column) => column.width), reuse.map((column) => column.align)), tone: "muted" });
2777
+ for (const row of data.models.slice(0, 10)) {
2778
+ lines.push({
2779
+ text: formatTableRow(reuse.map((column) => column.cell(row)), reuse.map((column) => column.width), reuse.map((column) => column.align)),
2780
+ tone: "base",
2781
+ row: { kind: "model", value: row.usage.modelID, ...row.usage.variant !== undefined ? { variant: row.usage.variant } : {} }
2782
+ });
2783
+ }
2551
2784
  }
2552
2785
  }
2553
2786
  if (data.gap !== undefined && data.gap.samples > 0) {
2554
2787
  lines.push({ text: "", tone: "muted" });
2555
- lines.push({ text: "cache survival against idle time", tone: HEADER_TONE });
2556
- const widths = [9, 8, 9, 9, 10];
2557
- lines.push({ text: formatTableRow(["gap", "pairs", "kept", "drops", "lost"], widths, ["left", "right", "right", "right", "right"]), tone: "muted" });
2558
- for (const bucket of data.gap.buckets) {
2559
- if (bucket.samples === 0)
2560
- continue;
2561
- lines.push({
2562
- text: formatTableRow([bucket.label, formatCount(bucket.samples), formatPercent(bucket.retainedRatio, 0), formatCount(bucket.drops), formatTokens(bucket.lostTokens)], widths, ["left", "right", "right", "right", "right"]),
2563
- tone: bucket.drops > 0 ? "warning" : "base"
2564
- });
2788
+ push("cache survival against idle time", HEADER_TONE);
2789
+ const buckets = data.gap.buckets;
2790
+ const survival = fitTable([
2791
+ { header: "gap", width: 8, max: 12, cell: (bucket) => bucket.label },
2792
+ { header: "pairs", width: 6, align: "right", cell: (bucket) => formatCount(bucket.samples) },
2793
+ { header: "kept", width: 7, align: "right", cell: (bucket) => formatPercent(bucket.retainedRatio, 0) },
2794
+ { header: "drops", width: 7, align: "right", cell: (bucket) => formatCount(bucket.drops) },
2795
+ { header: "lost", width: 8, align: "right", cell: (bucket) => formatTokens(bucket.lostTokens) }
2796
+ ], width);
2797
+ if (survival.length > 0) {
2798
+ lines.push({ text: formatTableRow(survival.map((column) => column.header), survival.map((column) => column.width), survival.map((column) => column.align)), tone: "muted" });
2799
+ for (const bucket of buckets) {
2800
+ if (bucket.samples === 0)
2801
+ continue;
2802
+ lines.push({
2803
+ text: formatTableRow(survival.map((column) => column.cell(bucket)), survival.map((column) => column.width), survival.map((column) => column.align)),
2804
+ tone: bucket.drops > 0 ? "warning" : "base"
2805
+ });
2806
+ }
2565
2807
  }
2566
2808
  if (data.gap.providers.length > 1) {
2567
2809
  lines.push({ text: "", tone: "muted" });
2568
- lines.push({ text: "reuse kept, by provider", tone: HEADER_TONE });
2569
- const providerWidths = [26, 8, 9, 9];
2570
- lines.push({ text: formatTableRow(["provider", "pairs", "kept", "lost"], providerWidths, ["left", "right", "right", "right"]), tone: "muted" });
2571
- for (const row of data.gap.providers.slice(0, 8)) {
2572
- lines.push({
2573
- text: formatTableRow([row.provider, formatCount(row.samples), formatPercent(row.retainedRatio, 0), formatTokens(row.lostTokens)], providerWidths, ["left", "right", "right", "right"]),
2574
- tone: "base"
2575
- });
2810
+ push("reuse kept, by provider", HEADER_TONE);
2811
+ const providers = data.gap.providers;
2812
+ const reuse = fitTable([
2813
+ { header: "provider", width: 12, max: 30, cell: (row) => row.provider },
2814
+ { header: "pairs", width: 6, align: "right", cell: (row) => formatCount(row.samples) },
2815
+ { header: "kept", width: 7, align: "right", cell: (row) => formatPercent(row.retainedRatio, 0) },
2816
+ { header: "lost", width: 8, align: "right", cell: (row) => formatTokens(row.lostTokens) }
2817
+ ], width);
2818
+ if (reuse.length > 0) {
2819
+ lines.push({ text: formatTableRow(reuse.map((column) => column.header), reuse.map((column) => column.width), reuse.map((column) => column.align)), tone: "muted" });
2820
+ for (const row of providers.slice(0, 8)) {
2821
+ lines.push({
2822
+ text: formatTableRow(reuse.map((column) => column.cell(row)), reuse.map((column) => column.width), reuse.map((column) => column.align)),
2823
+ tone: "base"
2824
+ });
2825
+ }
2576
2826
  }
2577
2827
  }
2578
2828
  }
2579
2829
  lines.push({ text: "", tone: "muted" });
2580
- lines.push({ text: "observed cache TTL bounds", tone: HEADER_TONE });
2830
+ push("observed cache TTL bounds", HEADER_TONE);
2581
2831
  if (data.evidence.length === 0) {
2582
- lines.push({ text: " no comparable step pairs yet", tone: "muted" });
2832
+ push(" no comparable step pairs yet", "muted");
2583
2833
  } else {
2584
- const widths = [Math.max(18, Math.floor(width * 0.4)), 14, 12, 9];
2585
- lines.push({ text: formatTableRow(["model", "hits up to", "drops from", "samples"], widths, ["left", "right", "right", "right"]), tone: "muted" });
2586
- for (const row of data.evidence.slice(0, 10)) {
2587
- lines.push({
2588
- text: formatTableRow([`${row.providerID}/${row.modelID}`, formatGap(row.maxHitGapMs), formatGap(row.minDropGapMs), formatCount(row.samples)], widths, ["left", "right", "right", "right"]),
2589
- tone: "base"
2590
- });
2834
+ const evidence = fitTable([
2835
+ { header: "model", width: 12, max: 44, cell: (row) => `${row.providerID}/${row.modelID}` },
2836
+ { header: "hits up to", width: 10, align: "right", cell: (row) => formatGap(row.maxHitGapMs) },
2837
+ { header: "drops from", width: 10, align: "right", cell: (row) => formatGap(row.minDropGapMs) },
2838
+ { header: "samples", width: 7, align: "right", priority: 1, cell: (row) => formatCount(row.samples) }
2839
+ ], width);
2840
+ if (evidence.length > 0) {
2841
+ lines.push({ text: formatTableRow(evidence.map((column) => column.header), evidence.map((column) => column.width), evidence.map((column) => column.align)), tone: "muted" });
2842
+ for (const row of data.evidence.slice(0, 10)) {
2843
+ lines.push({
2844
+ text: formatTableRow(evidence.map((column) => column.cell(row)), evidence.map((column) => column.width), evidence.map((column) => column.align)),
2845
+ tone: "base"
2846
+ });
2847
+ }
2591
2848
  }
2592
2849
  }
2593
2850
  if (data.drops.length > 0) {
2594
2851
  lines.push({ text: "", tone: "muted" });
2595
- lines.push({ text: "recent losses", tone: HEADER_TONE });
2596
- for (const drop of [...data.drops].sort((a, b) => b.at - a.at).slice(0, 8)) {
2597
- const when = new Date(drop.at).toLocaleTimeString("en-GB");
2598
- lines.push({
2599
- text: formatTableRow([when, `${drop.providerID ?? ""}/${drop.modelID ?? ""}`, `\u2212${formatTokens(drop.tokens)}`, `${formatGap(drop.gapMs)} idle \xB7 ${drop.reason}`], [10, Math.max(20, Math.floor(width * 0.42)), 10, 24], ["left", "left", "right", "left"]),
2600
- tone: drop.reason === "expired" ? "warning" : "base"
2601
- });
2852
+ push("recent losses", HEADER_TONE);
2853
+ const losses = fitTable([
2854
+ { header: "when", width: 8, cell: (drop) => new Date(drop.at).toLocaleTimeString("en-GB") },
2855
+ { header: "provider/model", width: 14, max: 40, cell: (drop) => `${drop.providerID ?? ""}/${drop.modelID ?? ""}` },
2856
+ { header: "tokens", width: 7, align: "right", cell: (drop) => `\u2212${formatTokens(drop.tokens)}` },
2857
+ { header: "idle", width: 12, max: 24, priority: 1, cell: (drop) => `${formatGap(drop.gapMs)} idle \xB7 ${drop.reason}` }
2858
+ ], width);
2859
+ if (losses.length > 0) {
2860
+ lines.push({ text: formatTableRow(losses.map((column) => column.header), losses.map((column) => column.width), losses.map((column) => column.align)), tone: "muted" });
2861
+ for (const drop of [...data.drops].sort((left, right) => right.at - left.at).slice(0, 8)) {
2862
+ lines.push({
2863
+ text: formatTableRow(losses.map((column) => column.cell(drop)), losses.map((column) => column.width), losses.map((column) => column.align)),
2864
+ tone: drop.reason === "expired" ? "warning" : "base"
2865
+ });
2866
+ }
2602
2867
  }
2603
2868
  }
2604
2869
  return lines;
@@ -2619,110 +2884,183 @@ function periodLines(rows, width, granularity, limit = 40, estimates = true, tot
2619
2884
  }, { steps: 0, sessions: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
2620
2885
  const overall = usageBuckets(totals);
2621
2886
  lines.push({
2622
- text: `${granularityLabel(granularity)} \xB7 ${count(rows.length, "period")} \xB7 ${count(totals.steps, "step")} \xB7 hit ${formatPercent(overall.hit)}`,
2887
+ text: truncate(`${granularityLabel(granularity)} \xB7 ${count(rows.length, "period")} \xB7 ${count(totals.steps, "step")} \xB7 hit ${formatPercent(overall.hit)}`, width),
2623
2888
  tone: "muted"
2624
2889
  });
2625
2890
  if (rows.length > 1) {
2626
- lines.push({ text: `steps ${sparkline(rows.map((row) => row.usage.steps))}`, tone: "muted" });
2627
- lines.push({ text: `cached ${sparkline(rows.map((row) => row.usage.cached))}`, tone: "muted" });
2891
+ const bars = Math.max(4, width - 8);
2892
+ lines.push({ text: truncate(`steps ${sparkline(rows.map((row) => row.usage.steps), bars)}`, width), tone: "muted" });
2893
+ lines.push({ text: truncate(`cached ${sparkline(rows.map((row) => row.usage.cached), bars)}`, width), tone: "muted" });
2628
2894
  lines.push({
2629
- text: `cost ${sparkline(rows.map((row) => Math.round((estimates ? row.usage.cost + row.usage.listCost : row.usage.cost) * 1e4)))}`,
2895
+ text: truncate(`cost ${sparkline(rows.map((row) => Math.round((estimates ? row.usage.cost + row.usage.listCost : row.usage.cost) * 1e4)), bars)}`, width),
2630
2896
  tone: "muted"
2631
2897
  });
2632
2898
  }
2633
- const withSessions = tableWidths(width, [[12, 7, 7, 11, 10, 7, 9, 9]]).length === 8;
2634
- const widths = withSessions ? [12, 7, 7, 11, 10, 7, 9, 9] : [12, 7, 11, 10, 7, 9, 9];
2635
- const aligns = widths.map((_, index) => index === 0 ? "left" : "right");
2636
- const header = withSessions ? ["period", "steps", "sess", "prompt", "cached", "hit", "out", "cost"] : ["period", "steps", "prompt", "cached", "hit", "out", "cost"];
2637
- lines.push({ text: formatTableRow(header, widths, aligns), tone: HEADER_TONE });
2899
+ const columns = fitTable([
2900
+ { header: "period", width: 10, max: 24, cell: (row) => row.label },
2901
+ { header: "steps", width: 6, align: "right", cell: (row) => row.steps },
2902
+ { header: "sess", width: 6, align: "right", priority: 5, cell: (row) => row.sessions },
2903
+ { header: "prompt", width: 7, max: 10, align: "right", priority: 1, cell: (row) => row.prompt },
2904
+ { header: "cached", width: 7, max: 10, align: "right", priority: 2, cell: (row) => row.cached },
2905
+ { header: "hit", width: 6, max: 7, align: "right", priority: 3, cell: (row) => row.hit },
2906
+ { header: "out", width: 7, max: 9, align: "right", priority: 4, cell: (row) => row.output },
2907
+ { header: "cost", width: 8, max: 9, align: "right", cell: (row) => row.cost }
2908
+ ], width);
2909
+ if (columns.length === 0)
2910
+ return [...lines, { text: truncate("no room for a table at this width", width), tone: "muted" }];
2911
+ const header = formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align));
2912
+ lines.push({ text: header, tone: HEADER_TONE });
2638
2913
  const newest = [...rows].sort((left, right) => right.at - left.at).slice(0, limit);
2639
2914
  for (const row of newest) {
2640
2915
  const buckets = usageBuckets(row.usage);
2641
- const cells = [
2642
- row.label,
2643
- formatCount(row.steps),
2644
- ...withSessions ? [formatCount(row.sessions)] : [],
2645
- formatTokens(buckets.prompt),
2646
- formatTokens(buckets.cached),
2647
- formatPercent(buckets.hit, 0),
2648
- formatTokens(buckets.output),
2649
- formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
2650
- ];
2651
- lines.push({ text: formatTableRow(cells, widths, aligns), tone: "base", row: { kind: "period", value: row.key } });
2916
+ const view = {
2917
+ label: row.label,
2918
+ steps: formatCount(row.steps),
2919
+ sessions: formatCount(row.sessions),
2920
+ prompt: formatTokens(buckets.prompt),
2921
+ cached: formatTokens(buckets.cached),
2922
+ hit: formatPercent(buckets.hit, 0),
2923
+ output: formatTokens(buckets.output),
2924
+ cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
2925
+ };
2926
+ lines.push({
2927
+ text: formatTableRow(columns.map((column) => column.cell(view)), columns.map((column) => column.width), columns.map((column) => column.align)),
2928
+ tone: "base",
2929
+ row: { kind: "period", value: row.key }
2930
+ });
2652
2931
  }
2653
2932
  lines.push({ text: "", tone: "muted" });
2933
+ const total = {
2934
+ label: "total",
2935
+ steps: formatCount(totals.steps),
2936
+ sessions: formatCount(totalSessions ?? totals.sessions),
2937
+ prompt: formatTokens(overall.prompt),
2938
+ cached: formatTokens(overall.cached),
2939
+ hit: formatPercent(overall.hit, 0),
2940
+ output: formatTokens(overall.output),
2941
+ cost: formatSpend(overall.cost, estimates ? overall.listCost : 0)
2942
+ };
2654
2943
  lines.push({
2655
- text: formatTableRow([
2656
- "total",
2657
- formatCount(totals.steps),
2658
- ...withSessions ? [formatCount(totalSessions ?? totals.sessions)] : [],
2659
- formatTokens(overall.prompt),
2660
- formatTokens(overall.cached),
2661
- formatPercent(overall.hit, 0),
2662
- formatTokens(overall.output),
2663
- formatSpend(overall.cost, estimates ? overall.listCost : 0)
2664
- ], widths, aligns),
2944
+ text: formatTableRow(columns.map((column) => column.cell(total)), columns.map((column) => column.width), columns.map((column) => column.align)),
2665
2945
  tone: HEADER_TONE
2666
2946
  });
2667
2947
  if (rows.length === 0)
2668
- lines.push({ text: "no usage recorded for this range", tone: "muted" });
2948
+ lines.push({ text: truncate("no usage recorded for this range", width), tone: "muted" });
2669
2949
  return lines;
2670
2950
  }
2951
+ function latencyMetric(label, values, width) {
2952
+ const prefix = padCell(label, 11);
2953
+ let text = `${prefix}${values[0] ?? "\u2013"}`;
2954
+ for (let index = 1;index < values.length; index += 1) {
2955
+ const next = `${text} \xB7 ${values[index]}`;
2956
+ if (next.length > width)
2957
+ break;
2958
+ text = next;
2959
+ }
2960
+ return text;
2961
+ }
2671
2962
  function latencyLines(report, width, groups, limit = 12, estimates = true) {
2672
2963
  const lines = [];
2964
+ if (width >= 68) {
2965
+ lines.push({
2966
+ text: formatTableRow(["wall", "p50", formatMs(report.wall.p50), "p90", formatMs(report.wall.p90), "p99", formatMs(report.wall.p99), `n ${formatCount(report.wall.count)}`], [10, 4, 9, 4, 9, 4, 9, 12]),
2967
+ tone: "base"
2968
+ });
2969
+ lines.push({
2970
+ text: formatTableRow(["stream", "p50", formatMs(report.stream.p50), "p90", formatMs(report.stream.p90), "p99", formatMs(report.stream.p99)], [10, 4, 9, 4, 9, 4, 9]),
2971
+ tone: "base"
2972
+ });
2973
+ lines.push({
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]),
2983
+ tone: "base"
2984
+ });
2985
+ } else {
2986
+ lines.push({
2987
+ text: latencyMetric("wall", [`p50 ${formatMs(report.wall.p50)}`, `p90 ${formatMs(report.wall.p90)}`, `p99 ${formatMs(report.wall.p99)}`, `n ${formatCount(report.wall.count)}`], width),
2988
+ tone: "base"
2989
+ });
2990
+ lines.push({
2991
+ text: latencyMetric("stream", [`p50 ${formatMs(report.stream.p50)}`, `p90 ${formatMs(report.stream.p90)}`, `p99 ${formatMs(report.stream.p99)}`], width),
2992
+ tone: "base"
2993
+ });
2994
+ lines.push({
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),
3004
+ tone: "base"
3005
+ });
3006
+ }
3007
+ lines.push({ text: "", tone: "muted" });
2673
3008
  lines.push({
2674
- text: formatTableRow(["wall", "p50", formatMs(report.wall.p50), "p90", formatMs(report.wall.p90), "p99", formatMs(report.wall.p99), `n ${formatCount(report.wall.count)}`], [10, 4, 9, 4, 9, 4, 9, 12]),
2675
- tone: "base"
2676
- });
2677
- lines.push({
2678
- text: formatTableRow(["stream", "p50", formatMs(report.stream.p50), "p90", formatMs(report.stream.p90), "p99", formatMs(report.stream.p99)], [10, 4, 9, 4, 9, 4, 9]),
2679
- tone: "base"
2680
- });
2681
- lines.push({
2682
- 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]),
2683
- tone: "base"
3009
+ text: truncate("wall = request to completed \xB7 stream = request to last chunk", width),
3010
+ tone: "muted"
2684
3011
  });
2685
- lines.push({ text: "", tone: "muted" });
2686
3012
  lines.push({
2687
- text: truncate("wall = request to completed \xB7 stream = request to last chunk \xB7 throughput = output+reasoning tokens/s", width),
3013
+ text: truncate("ttft = request to first token \xB7 tps = first token to last chunk \xB7 rtps = request to last chunk", width),
2688
3014
  tone: "muted"
2689
3015
  });
2690
3016
  if (report.wall.count === 0)
2691
- lines.push({ text: "no completed steps for this range", tone: "muted" });
3017
+ lines.push({ text: truncate("no completed steps for this range", width), tone: "muted" });
2692
3018
  if (groups !== undefined && groups.length > 0) {
2693
3019
  lines.push({ text: "", tone: "muted" });
2694
3020
  lines.push({ text: "by group", tone: HEADER_TONE });
2695
- const widths = width >= 110 ? [24, 6, 9, 9, 9, 9, 9, 9] : [16, 5, 8, 8, 8, 8, 8, 8];
2696
- const aligns = ["left", "right", "right", "right", "right", "right", "right", "right"];
2697
- lines.push({ text: formatTableRow(["group", "n", "wall p50", "wall p90", "stream", "tps p50", "tps p90", "cost"], widths, aligns), tone: "muted" });
2698
- for (const row of groups.slice(0, limit)) {
2699
- const thin = row.count < 5;
2700
- lines.push({
2701
- text: formatTableRow([
2702
- row.label,
2703
- formatCount(row.count),
2704
- formatMs(row.wall.p50),
2705
- formatMs(row.wall.p90),
2706
- formatMs(row.stream.p50),
2707
- formatTps(row.tps.p50),
2708
- formatTps(row.tps.p90),
2709
- formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0)
2710
- ], widths, aligns),
2711
- tone: thin ? "muted" : "base",
2712
- row: { kind: "model", value: row.key }
2713
- });
3021
+ const columns = fitTable([
3022
+ { header: "group", width: 8, max: 32, cell: (row) => row.label },
3023
+ { header: "n", width: 4, align: "right", cell: (row) => formatCount(row.count) },
3024
+ { header: "wall p50", width: 8, align: "right", cell: (row) => formatMs(row.wall.p50) },
3025
+ { header: "wall p90", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatMs(row.wall.p90) },
3026
+ { header: "stream", width: 6, max: 9, align: "right", priority: 2, cell: (row) => formatMs(row.stream.p50) },
3027
+ { header: "tps p50", width: 8, max: 9, align: "right", cell: (row) => formatTps(row.tps.p50) },
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) },
3030
+ { header: "cost", width: 8, max: 9, align: "right", cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
3031
+ ], width);
3032
+ if (columns.length > 0) {
3033
+ lines.push({ text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)), tone: "muted" });
3034
+ for (const row of groups.slice(0, limit)) {
3035
+ const thin = row.count < 5;
3036
+ lines.push({
3037
+ text: formatTableRow(columns.map((column) => column.cell(row)), columns.map((column) => column.width), columns.map((column) => column.align)),
3038
+ tone: thin ? "muted" : "base",
3039
+ row: { kind: "model", value: row.key }
3040
+ });
3041
+ }
2714
3042
  }
2715
- lines.push({ text: "n < 5 is dimmed: too few samples to compare", tone: "muted" });
3043
+ lines.push({ text: truncate("n < 5 is dimmed: too few samples to compare", width), tone: "muted" });
2716
3044
  }
2717
3045
  return lines;
2718
3046
  }
2719
3047
  function sessionsLines(rows, width, options) {
2720
3048
  const limit = options?.limit ?? 20;
2721
3049
  const estimates = options?.estimates !== false;
2722
- const widths = [Math.max(18, Math.floor(width * 0.36)), 7, 11, 10, 7, 9, 9];
2723
- const aligns = ["left", "right", "right", "right", "right", "right", "right"];
3050
+ const columns = fitTable([
3051
+ { header: "title", width: 10, max: 48, cell: (row) => row.title },
3052
+ { header: "steps", width: 6, align: "right", cell: (row) => row.steps },
3053
+ { header: "prompt", width: 7, max: 10, align: "right", priority: 1, cell: (row) => row.prompt },
3054
+ { header: "cached", width: 7, max: 10, align: "right", priority: 2, cell: (row) => row.cached },
3055
+ { header: "hit", width: 6, max: 7, align: "right", priority: 3, cell: (row) => row.hit },
3056
+ { header: "out", width: 7, max: 9, align: "right", priority: 4, cell: (row) => row.output },
3057
+ { header: "cost", width: 8, max: 9, align: "right", cell: (row) => row.cost }
3058
+ ], width);
2724
3059
  const lines = [
2725
- { text: formatTableRow(["title", "steps", "prompt", "cached", "hit", "out", "cost"], widths, aligns), tone: HEADER_TONE }
3060
+ {
3061
+ text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)),
3062
+ tone: HEADER_TONE
3063
+ }
2726
3064
  ];
2727
3065
  const byID = new Map(rows.map((row) => [row.sessionID, row]));
2728
3066
  const ordered = rows.filter((row) => row.parentID === undefined || !byID.has(row.parentID));
@@ -2730,18 +3068,18 @@ function sessionsLines(rows, width, options) {
2730
3068
  const orderedAll = [...ordered, ...children];
2731
3069
  for (const row of orderedAll.slice(0, limit)) {
2732
3070
  const child = row.parentID !== undefined && byID.has(row.parentID);
2733
- const title = truncate(row.title ?? row.sessionID, Math.max(8, widths[0] - (child ? 2 : 0)));
2734
3071
  const buckets = usageBuckets(row);
3072
+ const view = {
3073
+ title: `${child ? "\u21B3 " : ""}${row.title ?? row.sessionID}`,
3074
+ steps: formatCount(buckets.steps),
3075
+ prompt: formatTokens(buckets.prompt),
3076
+ cached: formatTokens(buckets.cached),
3077
+ hit: formatPercent(buckets.hit, 0),
3078
+ output: formatTokens(buckets.output),
3079
+ cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
3080
+ };
2735
3081
  lines.push({
2736
- text: formatTableRow([
2737
- `${child ? "\u21B3 " : ""}${title}`,
2738
- formatCount(buckets.steps),
2739
- formatTokens(buckets.prompt),
2740
- formatTokens(buckets.cached),
2741
- formatPercent(buckets.hit, 0),
2742
- formatTokens(buckets.output),
2743
- formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
2744
- ], widths, aligns),
3082
+ text: formatTableRow(columns.map((column) => column.cell(view)), columns.map((column) => column.width), columns.map((column) => column.align)),
2745
3083
  tone: child ? "muted" : "base",
2746
3084
  row: { kind: "session", value: row.sessionID }
2747
3085
  });
@@ -2756,14 +3094,14 @@ function sessionsLines(rows, width, options) {
2756
3094
  const share = rows.reduce((sum, row) => sum + row.steps, 0);
2757
3095
  lines.push({ text: "", tone: "muted" });
2758
3096
  lines.push({
2759
- text: `subagents ${formatCount(options.rollup.subagentSteps)} steps (${formatPercent(share > 0 ? options.rollup.subagentSteps / share : undefined)}) \xB7 ${formatSpend(options.rollup.subagentCost, estimates ? options.rollup.subagentListCost ?? 0 : 0)}`,
3097
+ text: truncate(`subagents ${formatCount(options.rollup.subagentSteps)} steps (${formatPercent(share > 0 ? options.rollup.subagentSteps / share : undefined)}) \xB7 ${formatSpend(options.rollup.subagentCost, estimates ? options.rollup.subagentListCost ?? 0 : 0)}`, width),
2760
3098
  tone: "muted"
2761
3099
  });
2762
3100
  }
2763
3101
  if (rows.length > limit)
2764
- lines.push({ text: `\u2026 ${count(rows.length - limit, "more session")} \xB7 narrow the range`, tone: "muted" });
3102
+ lines.push({ text: truncate(`\u2026 ${count(rows.length - limit, "more session")} \xB7 narrow the range`, width), tone: "muted" });
2765
3103
  if (rows.length === 0)
2766
- lines.push({ text: "no sessions recorded for this range", tone: "muted" });
3104
+ lines.push({ text: truncate("no sessions recorded for this range", width), tone: "muted" });
2767
3105
  return lines;
2768
3106
  }
2769
3107
  function dbLines(data, width) {
@@ -2771,16 +3109,16 @@ function dbLines(data, width) {
2771
3109
  const size = (bytes) => `${(bytes / 1048576).toFixed(1)} MB`;
2772
3110
  lines.push({ text: truncate(data.info.path, width), tone: "base" });
2773
3111
  lines.push({
2774
- text: `${size(data.info.bytes)}${data.info.walBytes === undefined ? "" : ` + ${size(data.info.walBytes)} wal`} \xB7 schema v${data.info.schemaVersion}`,
3112
+ text: truncate(`${size(data.info.bytes)}${data.info.walBytes === undefined ? "" : ` + ${size(data.info.walBytes)} wal`} \xB7 schema v${data.info.schemaVersion}`, width),
2775
3113
  tone: "muted"
2776
3114
  });
2777
3115
  lines.push({ text: "", tone: "muted" });
2778
3116
  lines.push({ text: "what it holds", tone: HEADER_TONE });
2779
3117
  for (const table of data.info.tables) {
2780
- lines.push({ text: ` ${padCell(table.name, 12)}${formatCount(table.rows)} rows`, tone: table.rows === 0 ? "muted" : "base" });
3118
+ lines.push({ text: truncate(` ${padCell(table.name, 12)}${formatCount(table.rows)} rows`, width), tone: table.rows === 0 ? "muted" : "base" });
2781
3119
  }
2782
3120
  lines.push({
2783
- text: ` window ${data.info.firstAt === undefined ? "\u2013" : new Date(data.info.firstAt).toLocaleDateString("en-GB")} \u2192 ${data.info.lastAt === undefined ? "\u2013" : new Date(data.info.lastAt).toLocaleDateString("en-GB")}`,
3121
+ text: truncate(` window ${data.info.firstAt === undefined ? "\u2013" : new Date(data.info.firstAt).toLocaleDateString("en-GB")} \u2192 ${data.info.lastAt === undefined ? "\u2013" : new Date(data.info.lastAt).toLocaleDateString("en-GB")}`, width),
2784
3122
  tone: "muted"
2785
3123
  });
2786
3124
  lines.push({ text: "", tone: "muted" });
@@ -2796,7 +3134,7 @@ function dbLines(data, width) {
2796
3134
  tone: data.info.schemaVersion < 10 || data.info.unpriced > 0 ? "base" : "muted"
2797
3135
  });
2798
3136
  }
2799
- const widths = [10, 13, 10];
3137
+ const widths = [9, 11, 10];
2800
3138
  lines.push({ text: formatTableRow(["keep", "prunes", "older than"], widths, ["left", "right", "left"]), tone: "muted" });
2801
3139
  for (const option of data.info.removable) {
2802
3140
  const before = new Date(data.now - option.days * 24 * 60 * 60 * 1000).toLocaleDateString("en-GB");
@@ -2816,7 +3154,7 @@ function dbLines(data, width) {
2816
3154
  });
2817
3155
  if (data.busy === true) {
2818
3156
  lines.push({ text: "", tone: "muted" });
2819
- lines.push({ text: "the recorder is writing: try the vacuum again in a moment", tone: "warning" });
3157
+ lines.push({ text: truncate("the recorder is writing: try the vacuum again in a moment", width), tone: "warning" });
2820
3158
  }
2821
3159
  return lines;
2822
3160
  }
@@ -2840,28 +3178,74 @@ function turnStats(turn) {
2840
3178
  steps: turn.steps
2841
3179
  };
2842
3180
  }
3181
+ function compactTurnLine(stats, width, options) {
3182
+ const labels = { ...DEFAULT_LABELS, ...options?.labels };
3183
+ const fields = { ...DEFAULT_FIELDS, ...options?.fields };
3184
+ const estimates = options?.estimates !== false;
3185
+ const headParts = [];
3186
+ if (fields.clock && stats.endAt !== undefined)
3187
+ headParts.push(formatClock(stats.endAt));
3188
+ if (stats.providerID !== undefined) {
3189
+ let identity = stats.providerID;
3190
+ if (fields.model && stats.modelID !== undefined)
3191
+ identity += `/${stats.modelID}`;
3192
+ if (fields.variant && stats.variant)
3193
+ identity += ` ${stats.variant}`;
3194
+ headParts.push(identity);
3195
+ }
3196
+ let head = headParts.join(" ");
3197
+ const totals = options?.turnTotals === "sum" ? stats.totals : stats.latest;
3198
+ const display = displayTotals(totals);
3199
+ const money = fields.cost ? formatMoney(stats.totals.cost, estimates ? stats.totals.listCost : 0, labels.estimate) : undefined;
3200
+ const cost = money === undefined ? undefined : `${labels.cost} ${money}`.trim();
3201
+ const warning = fields.cacheExpiry && stats.cacheExpired ? `\u26A0 ${labels.cacheExpired} (\u2212${formatTokens(stats.cacheDropTokens)}${stats.drops.length > 1 ? ` \xD7${stats.drops.length}` : ""})` : undefined;
3202
+ let suffix = [warning, cost].filter((part) => part !== undefined).join(" \xB7 ");
3203
+ if (suffix !== "" && suffix.length + 3 > width)
3204
+ suffix = cost ?? suffix;
3205
+ head = truncate(head, Math.max(0, width - (suffix === "" ? 0 : suffix.length + 3)));
3206
+ if (!fields.turn || stats.totals.steps === 0)
3207
+ return [head, suffix].filter((part) => part !== "").join(" \xB7 ");
3208
+ const input = display.prompt === display.input ? `${labels.input} ${formatTokens(display.input)}` : `${labels.input} ${formatTokens(display.input)} (${formatTokens(display.prompt)})`;
3209
+ const volumes = [
3210
+ input,
3211
+ `${labels.cached} ${formatTokens(display.cached)}`,
3212
+ `${labels.output} ${formatTokens(display.output)}`,
3213
+ ...fields.reasoning ? [`${labels.reasoning} ${formatTokens(display.reasoning)}`] : []
3214
+ ];
3215
+ let numbers = "";
3216
+ for (const volume of volumes) {
3217
+ const next = numbers === "" ? volume : `${numbers}, ${volume}`;
3218
+ if ([head, next, suffix].filter((part) => part !== "").join(" \xB7 ").length > width)
3219
+ break;
3220
+ numbers = next;
3221
+ }
3222
+ return [head, numbers, suffix].filter((part) => part !== "").join(" \xB7 ");
3223
+ }
2843
3224
  function turnsLines(rows, width, options) {
2844
3225
  const lines = [];
2845
3226
  const warning = rows.filter((turn) => turn.drops.length > 0).length;
2846
3227
  lines.push({
2847
- text: `${count(rows.length, "turn")} \xB7 newest first${warning > 0 ? ` \xB7 ${count(warning, "turn")} with a cache loss` : ""}`,
3228
+ text: truncate(`${count(rows.length, "turn")} \xB7 newest first${warning > 0 ? ` \xB7 ${count(warning, "turn")} with a cache loss` : ""}`, width),
2848
3229
  tone: "muted"
2849
3230
  });
2850
3231
  const showSession = options?.sessionTitles !== undefined;
2851
3232
  for (const turn of rows) {
2852
- const line = formatLine(turnStats(turn), {
3233
+ const stats = turnStats(turn);
3234
+ const line = formatLine(stats, {
2853
3235
  ...options,
2854
3236
  fields: { ...options?.fields, session: false }
2855
3237
  });
2856
3238
  const title = showSession ? `${truncate(options.sessionTitles.get(turn.sessionID) ?? turn.sessionID, 18)} ` : "";
3239
+ const available = Math.max(0, width - title.length);
3240
+ const text = `${title}${line.length <= available ? line : compactTurnLine(stats, available, { ...options, fields: { ...options?.fields, session: false } })}`;
2857
3241
  lines.push({
2858
- text: truncate(`${title}${line}`, width),
3242
+ text: truncate(text, width),
2859
3243
  tone: turn.drops.length > 0 || turn.providerChanged ? "warning" : "base",
2860
3244
  row: { kind: "turn", value: turn.sessionID }
2861
3245
  });
2862
3246
  }
2863
3247
  if (rows.length === 0)
2864
- lines.push({ text: "no finished turns for this range", tone: "muted" });
3248
+ lines.push({ text: truncate("no finished turns for this range", width), tone: "muted" });
2865
3249
  return lines;
2866
3250
  }
2867
3251
  function sessionSummaryLines(usage, budget = 34, estimates = true) {
@@ -2871,7 +3255,9 @@ function sessionSummaryLines(usage, budget = 34, estimates = true) {
2871
3255
  const cached = formatTokens(buckets.cached);
2872
3256
  const out = formatTokens(buckets.output);
2873
3257
  const hit = formatPercent(buckets.hit);
2874
- 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)}`;
2875
3261
  const cost = (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost);
2876
3262
  const first = [
2877
3263
  ` ${steps} steps \xB7 in ${input}`,
@@ -2881,16 +3267,22 @@ function sessionSummaryLines(usage, budget = 34, estimates = true) {
2881
3267
  ` cached ${cached} \xB7 out ${out}`,
2882
3268
  ` cached ${cached}`
2883
3269
  ].find((text) => text.length <= budget);
2884
- const last = [
2885
- ` hit ${hit} \xB7 ${tps} \xB7 ${cost}`,
2886
- ` hit ${hit} \xB7 ${cost}`,
2887
- ` ${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}`
2888
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);
2889
3280
  return [
2890
3281
  { text: truncate("session", budget), tone: HEADER_TONE },
2891
3282
  { text: truncate(first ?? ` ${steps} steps`, budget), tone: "muted" },
2892
3283
  { text: truncate(second ?? ` cached ${cached}`, budget), tone: "base" },
2893
- { text: truncate(last ?? ` ${cost}`, budget), tone: "base" },
3284
+ { text: truncate(rateLine ?? ` hit ${hit}`, budget), tone: "base" },
3285
+ { text: truncate(tail ?? ` ${cost}`, budget), tone: "base" },
2894
3286
  { text: "", tone: "muted" }
2895
3287
  ];
2896
3288
  }
@@ -2907,20 +3299,28 @@ function sidebarLines(rows, options) {
2907
3299
  const output = formatTokens(display.output);
2908
3300
  const cost = options?.estimates === false ? formatCost(turn.totals.cost) : formatMoney(turn.totals.cost, turn.totals.listCost) ?? formatCost(turn.totals.cost);
2909
3301
  const hit = formatPercent(display.prompt > 0 ? display.cached / display.prompt : undefined).replace(/\.0%$/, "%");
2910
- 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 ");
2911
3305
  const suffix = turn.drops.length > 0 ? " \xB7 \u26A0" : "";
2912
3306
  const header = `${clock} ${provider}`;
2913
3307
  const timed = turn.durationMs === undefined ? undefined : `${header} \xB7 ${formatMs(turn.durationMs)}`;
3308
+ const join = (...parts) => parts.filter((part) => part !== undefined && part !== "").join(" \xB7 ");
2914
3309
  const volumes = [
2915
- ` ${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}`,
2916
3312
  ` ${labels.input} ${input} \xB7 ${labels.output} ${output}`,
2917
3313
  ` ${labels.input} ${input}`
2918
3314
  ];
3315
+ const volume = volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1];
3316
+ const hitPart = volume.includes(`hit ${hit}`) ? undefined : `hit ${hit}`;
2919
3317
  const facts = [
2920
- ` hit ${hit}${tps === undefined ? "" : ` \xB7 ${tps}`} \xB7 ${cost}${suffix}`,
2921
- ` hit ${hit}${tps === undefined ? "" : ` \xB7 ${tps}`}${suffix}`,
2922
- ` ${tps === undefined ? "" : `${tps} \xB7 `}${cost}${suffix}`,
2923
- ` 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}`)}`
2924
3324
  ];
2925
3325
  lines.push({ text: truncate(timed !== undefined && timed.length <= budget ? timed : header, budget), tone: turn.providerChanged ? "warning" : "base" });
2926
3326
  const edge = index === 0 || index === rows.length - 1;
@@ -2928,10 +3328,7 @@ function sidebarLines(rows, options) {
2928
3328
  const model = turn.modelID === undefined ? "unknown" : `${turn.modelID}${turn.variant === undefined ? "" : ` ${turn.variant}`}`;
2929
3329
  lines.push({ text: truncate(` ${model}`, budget), tone: "muted" });
2930
3330
  }
2931
- lines.push({
2932
- text: truncate(volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1], budget),
2933
- tone: "muted"
2934
- });
3331
+ lines.push({ text: truncate(volume, budget), tone: "muted" });
2935
3332
  lines.push({
2936
3333
  text: truncate(facts.find((text) => text.length <= budget) ?? facts[facts.length - 1], budget),
2937
3334
  tone: turn.drops.length > 0 ? "warning" : "muted"
@@ -2961,11 +3358,12 @@ function detailLabel(row) {
2961
3358
  }
2962
3359
  }
2963
3360
  function buildPanel(request) {
3361
+ const width = clampPanelWidth(request.width);
2964
3362
  try {
2965
- return build(request);
3363
+ return build({ ...request, width }).map((line) => line.text.length <= width ? line : { ...line, text: truncate(line.text, width) });
2966
3364
  } catch (error) {
2967
3365
  const message = error instanceof Error ? error.message : String(error);
2968
- return [{ text: `stats query failed: ${message}`, tone: "warning" }];
3366
+ return [{ text: truncate(`stats query failed: ${message}`, width), tone: "warning" }];
2969
3367
  }
2970
3368
  }
2971
3369
  function build(request) {
@@ -3079,10 +3477,15 @@ function buildDetail(request, range, filters, estimates) {
3079
3477
  const steps = stepRows(db, { range, filters: scoped });
3080
3478
  return [
3081
3479
  head,
3082
- {
3083
- text: `steps ${stats.steps} \xB7 in ${formatTokens(stats.prompt - stats.cached)} \xB7 prompt ${formatTokens(stats.prompt)} \xB7 cached ${formatTokens(stats.cached)} \xB7 write ${formatTokens(stats.cacheWrite)} \xB7 hit ${percent(stats.hit)} \xB7 p50 ${percent(stats.hitP50)}`,
3084
- tone: "muted"
3085
- },
3480
+ ...kvGrid([
3481
+ ["steps", formatCount(stats.steps)],
3482
+ ["in", formatTokens(stats.prompt - stats.cached)],
3483
+ ["prompt", formatTokens(stats.prompt)],
3484
+ ["cached", formatTokens(stats.cached)],
3485
+ ["write", formatTokens(stats.cacheWrite)],
3486
+ ["hit", percent(stats.hit)],
3487
+ ["p50", percent(stats.hitP50)]
3488
+ ], width),
3086
3489
  { text: "", tone: "muted" },
3087
3490
  ...providerLines(providerBreakdownOf(steps), width, 40, estimates),
3088
3491
  { text: "", tone: "muted" },
@@ -3101,10 +3504,14 @@ function buildDetail(request, range, filters, estimates) {
3101
3504
  const stats = cacheStatsOf(db, { range, filters: scoped });
3102
3505
  return [
3103
3506
  head,
3104
- {
3105
- text: `steps ${stats.steps} \xB7 in ${formatTokens(stats.prompt - stats.cached)} \xB7 prompt ${formatTokens(stats.prompt)} \xB7 cached ${formatTokens(stats.cached)} \xB7 hit ${percent(stats.hit)} \xB7 p50 ${percent(stats.hitP50)}`,
3106
- tone: "muted"
3107
- },
3507
+ ...kvGrid([
3508
+ ["steps", formatCount(stats.steps)],
3509
+ ["in", formatTokens(stats.prompt - stats.cached)],
3510
+ ["prompt", formatTokens(stats.prompt)],
3511
+ ["cached", formatTokens(stats.cached)],
3512
+ ["hit", percent(stats.hit)],
3513
+ ["p50", percent(stats.hitP50)]
3514
+ ], width),
3108
3515
  { text: "", tone: "muted" },
3109
3516
  ...providerLines(providerBreakdownOf(steps), width, 40, estimates),
3110
3517
  { text: "", tone: "muted" },
@@ -3163,6 +3570,8 @@ function sortProviders(rows, sort, desc, estimates = true) {
3163
3570
  return row.share;
3164
3571
  if (sort === "tps")
3165
3572
  return row.tps ?? -1;
3573
+ if (sort === "ttft")
3574
+ return row.ttft ?? -1;
3166
3575
  return row.usage.steps;
3167
3576
  };
3168
3577
  return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
@@ -3172,6 +3581,8 @@ function sortLatency(rows, sort, desc) {
3172
3581
  const pick = (row) => {
3173
3582
  if (sort === "tps")
3174
3583
  return row.tps.p50 ?? -1;
3584
+ if (sort === "ttft")
3585
+ return row.ttft.p50 ?? -1;
3175
3586
  if (sort === "wall")
3176
3587
  return row.wall.p50 ?? -1;
3177
3588
  return row.count;
@@ -3322,13 +3733,6 @@ function size(path) {
3322
3733
  return 0;
3323
3734
  }
3324
3735
  }
3325
- function hasTable(db, name) {
3326
- try {
3327
- return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== null;
3328
- } catch {
3329
- return false;
3330
- }
3331
- }
3332
3736
  function dbInfo(db, path, now = Date.now()) {
3333
3737
  const tables = TABLES.map((table) => ({
3334
3738
  name: table,
@@ -3382,7 +3786,7 @@ function pruneOlderThan(db, cutoff) {
3382
3786
  return {
3383
3787
  steps: deleteBatched(db, "steps", `${STEP_TIME2} < ?`, cutoff),
3384
3788
  prompts: deleteBatched(db, "prompts", "created_at IS NOT NULL AND created_at < ?", cutoff),
3385
- events: deleteBatched(db, "events", "at IS NOT NULL AND at < ?", cutoff),
3789
+ compactions: deleteBatched(db, "compactions", "at IS NOT NULL AND at < ?", cutoff),
3386
3790
  usage: hasTable(db, "usage") ? deleteBatched(db, "usage", "at IS NOT NULL AND at < ?", cutoff) : 0
3387
3791
  };
3388
3792
  }
@@ -3390,7 +3794,7 @@ function wipeAll(db) {
3390
3794
  return {
3391
3795
  steps: deleteAllBatched(db, "steps"),
3392
3796
  prompts: deleteAllBatched(db, "prompts"),
3393
- events: deleteAllBatched(db, "events"),
3797
+ compactions: deleteAllBatched(db, "compactions"),
3394
3798
  usage: hasTable(db, "usage") ? deleteAllBatched(db, "usage") : 0,
3395
3799
  sessions: hasTable(db, "sessions") ? deleteAllBatched(db, "sessions") : 0
3396
3800
  };
@@ -3413,23 +3817,41 @@ function hasListCost(db) {
3413
3817
  }
3414
3818
  }
3415
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
+ }
3416
3845
  function backfillListCost(db, price) {
3417
3846
  if (!hasListCost(db))
3418
3847
  return { candidates: 0, updated: 0 };
3419
- const candidates = db.query(`SELECT COUNT(*) AS n FROM steps
3420
- WHERE cost = 0 AND list_cost IS NULL
3421
- AND provider_id IS NOT NULL AND provider_id <> ''
3422
- AND model_id IS NOT NULL AND model_id <> ''
3423
- 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;
3424
3849
  if (candidates === 0)
3425
3850
  return { candidates: 0, updated: 0 };
3426
3851
  const select = db.query(`SELECT rowid, provider_id, model_id,
3427
3852
  input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
3428
3853
  FROM steps
3429
- WHERE cost = 0 AND list_cost IS NULL AND rowid > ?
3430
- AND provider_id IS NOT NULL AND provider_id <> ''
3431
- AND model_id IS NOT NULL AND model_id <> ''
3432
- AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0
3854
+ WHERE ${UNPRICED_WHERE} AND rowid > ?
3433
3855
  ORDER BY rowid
3434
3856
  LIMIT ?`);
3435
3857
  const update = db.query("UPDATE steps SET list_cost = ? WHERE rowid = ? AND cost = 0 AND list_cost IS NULL");
@@ -3439,21 +3861,7 @@ function backfillListCost(db, price) {
3439
3861
  const rows = select.all(cursor, BACKFILL_BATCH);
3440
3862
  if (rows.length === 0)
3441
3863
  break;
3442
- db.transaction(() => {
3443
- for (const row of rows) {
3444
- const estimate = price({ providerID: row.provider_id ?? undefined, modelID: row.model_id ?? undefined }, {
3445
- input: row.input_tokens ?? 0,
3446
- output: row.output_tokens ?? 0,
3447
- reasoning: row.reasoning_tokens ?? 0,
3448
- cacheRead: row.cache_read ?? 0,
3449
- cacheWrite: row.cache_write ?? 0
3450
- });
3451
- if (estimate === undefined || !Number.isFinite(estimate) || estimate < 0)
3452
- continue;
3453
- if (update.run(estimate, row.rowid).changes > 0)
3454
- updated += 1;
3455
- }
3456
- })();
3864
+ updated += backfillBatch(db, rows, price, (estimate, rowid) => update.run(estimate, rowid).changes);
3457
3865
  cursor = rows[rows.length - 1].rowid;
3458
3866
  if (rows.length < BACKFILL_BATCH)
3459
3867
  break;
@@ -3542,7 +3950,7 @@ function createService(db, options) {
3542
3950
  }
3543
3951
  function turnHistory(input) {
3544
3952
  const handle = db();
3545
- const width = clamp2(input.width, 20, 120);
3953
+ const width = clamp2(input.width, 20, MAX_HISTORY_WIDTH);
3546
3954
  const limit = clampTurnsLimit(input.limit);
3547
3955
  const summary = sessionSummaryLines(overview(handle, undefined, { sessionID: input.sessionID }), width, options.pricing);
3548
3956
  const history = sidebarLines(turns(handle, { sessionID: input.sessionID, limit }), {
@@ -3694,4 +4102,4 @@ scope.onmessage = (event) => {
3694
4102
  }
3695
4103
  };
3696
4104
 
3697
- //# debugId=008189B5EA042DE564756E2164756E21
4105
+ //# debugId=E499AA8C5F2EFBAF64756E2164756E21