opencode-usage-insights 0.3.1 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +67 -542
- package/dist/core.d.ts +15 -1
- package/dist/gui-experimental.cjs +3 -3
- package/dist/index.d.ts +0 -47
- package/dist/index.js +1734 -1209
- package/dist/index.js.map +23 -16
- package/dist/line.d.ts +1 -0
- package/dist/panel-data.d.ts +9 -2
- package/dist/recorder.d.ts +1 -0
- package/dist/rpc.d.ts +4 -4
- package/dist/rpc.js +5 -5
- package/dist/rpc.js.map +3 -3
- package/dist/settings-client.d.ts +29 -0
- package/dist/settings-rpc.d.ts +746 -0
- package/dist/settings.d.ts +114 -0
- package/dist/sidebar.d.ts +3 -3
- package/dist/stats/aggregates.d.ts +15 -3
- package/dist/stats/constants.d.ts +7 -0
- package/dist/stats/db.d.ts +8 -128
- package/dist/stats/legacy.d.ts +25 -0
- package/dist/stats/maintenance.d.ts +1 -1
- package/dist/stats/migrate.d.ts +7 -0
- package/dist/stats/ndjson.d.ts +16 -0
- package/dist/stats/open.d.ts +15 -0
- package/dist/stats/paths.d.ts +5 -4
- package/dist/stats/queries.d.ts +30 -35
- package/dist/stats/records.d.ts +94 -0
- package/dist/stats/schema.d.ts +26 -0
- package/dist/stats-client.d.ts +9 -0
- package/dist/stats-worker.js +597 -367
- package/dist/stats-worker.js.map +17 -12
- package/dist/text.d.ts +2 -0
- package/dist/tui-settings.d.ts +18 -0
- package/dist/tui.d.ts +1 -57
- package/dist/tui.js +974 -158
- package/dist/tui.js.map +17 -13
- package/docs/cli.md +24 -0
- package/docs/configuration.md +108 -0
- package/docs/costs.md +44 -0
- package/docs/demo.md +94 -68
- package/docs/desktop.md +91 -0
- package/docs/images/desktop-overview-annotated.png +0 -0
- package/docs/images/desktop-overview.png +0 -0
- package/docs/images/desktop-settings.png +0 -0
- package/docs/images/desktop-turns-go-annotated.png +0 -0
- package/docs/images/desktop-turns.png +0 -0
- package/docs/images/line.png +0 -0
- package/docs/images/panel-cache.png +0 -0
- package/docs/images/panel-help.png +0 -0
- package/docs/images/panel-latency.png +0 -0
- package/docs/images/panel-overview.png +0 -0
- package/docs/images/panel-providers.png +0 -0
- package/docs/images/sidebar.png +0 -0
- package/docs/internals.md +87 -36
- package/docs/privacy.md +60 -0
- package/docs/tui.md +175 -0
- package/package.json +8 -7
package/dist/stats-worker.js
CHANGED
|
@@ -1,76 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
// src/stats/
|
|
3
|
-
|
|
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
|
-
|
|
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
|
|
136
|
-
CREATE INDEX IF NOT EXISTS
|
|
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", "
|
|
159
|
-
function
|
|
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) {
|
|
164
91
|
try {
|
|
165
|
-
return
|
|
92
|
+
return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== null;
|
|
166
93
|
} catch {
|
|
167
|
-
return
|
|
94
|
+
return false;
|
|
168
95
|
}
|
|
169
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;
|
|
138
|
+
try {
|
|
139
|
+
stats = statSync(path);
|
|
140
|
+
} catch {
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
if (!stats.isFile())
|
|
144
|
+
throw new Error(`not a regular file: ${path}`);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// src/stats/constants.ts
|
|
148
|
+
var COMPACTION_KIND = "compaction";
|
|
149
|
+
|
|
150
|
+
// src/stats/legacy.ts
|
|
151
|
+
function importTimestamp(value) {
|
|
152
|
+
if (typeof value === "number")
|
|
153
|
+
return Number.isFinite(value) ? value : undefined;
|
|
154
|
+
if (typeof value !== "string")
|
|
155
|
+
return;
|
|
156
|
+
const trimmed = value.trim();
|
|
157
|
+
if (trimmed === "")
|
|
158
|
+
return;
|
|
159
|
+
const parsed = Number(trimmed);
|
|
160
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
161
|
+
}
|
|
162
|
+
function numberOrZero(value) {
|
|
163
|
+
const parsed = importTimestamp(value);
|
|
164
|
+
return parsed === undefined ? 0 : Math.max(0, parsed);
|
|
165
|
+
}
|
|
166
|
+
function legacyCompactionUsage(row) {
|
|
167
|
+
if (row.kind !== COMPACTION_KIND)
|
|
168
|
+
return;
|
|
169
|
+
if (row.message_id !== undefined && row.message_id !== null && row.message_id !== "")
|
|
170
|
+
return;
|
|
171
|
+
if (typeof row.session_id !== "string" || row.session_id === "")
|
|
172
|
+
return;
|
|
173
|
+
const at = importTimestamp(row.at);
|
|
174
|
+
if (at === undefined)
|
|
175
|
+
return;
|
|
176
|
+
let payload = row.data;
|
|
177
|
+
if (typeof payload === "string") {
|
|
178
|
+
try {
|
|
179
|
+
payload = JSON.parse(payload);
|
|
180
|
+
} catch {
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (typeof payload !== "object" || payload === null)
|
|
185
|
+
return;
|
|
186
|
+
const record = payload;
|
|
187
|
+
const tokens = typeof record.tokens === "object" && record.tokens !== null ? record.tokens : {};
|
|
188
|
+
const cache = typeof tokens.cache === "object" && tokens.cache !== null ? tokens.cache : {};
|
|
189
|
+
return {
|
|
190
|
+
sessionID: row.session_id,
|
|
191
|
+
at,
|
|
192
|
+
cost: numberOrZero(record.cost),
|
|
193
|
+
input: Math.floor(numberOrZero(tokens.input)),
|
|
194
|
+
output: Math.floor(numberOrZero(tokens.output)),
|
|
195
|
+
reasoning: Math.floor(numberOrZero(tokens.reasoning)),
|
|
196
|
+
cacheRead: Math.floor(numberOrZero(cache.read)),
|
|
197
|
+
cacheWrite: Math.floor(numberOrZero(cache.write))
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// src/text.ts
|
|
202
|
+
var TEXT_LIMIT = 512;
|
|
203
|
+
var LABEL_LIMIT = 4 * TEXT_LIMIT;
|
|
204
|
+
function sanitizeText(value, limit = TEXT_LIMIT) {
|
|
205
|
+
if (limit <= 0)
|
|
206
|
+
return "";
|
|
207
|
+
let cleaned = "";
|
|
208
|
+
for (const character of value) {
|
|
209
|
+
const code = character.codePointAt(0) ?? 0;
|
|
210
|
+
if (code <= 31 || code === 127 || code >= 128 && code <= 159)
|
|
211
|
+
continue;
|
|
212
|
+
cleaned += character;
|
|
213
|
+
if (cleaned.length >= limit)
|
|
214
|
+
break;
|
|
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
|
|
180
|
-
|
|
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 (
|
|
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
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
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 =
|
|
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
|
|
208
|
-
|
|
209
|
-
if (table === null)
|
|
384
|
+
function dedupeLegacyCompactions(db) {
|
|
385
|
+
if (!hasTable(db, "events"))
|
|
210
386
|
return;
|
|
211
|
-
db
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
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
|
|
412
|
+
GROUP BY message_id
|
|
224
413
|
)`);
|
|
225
414
|
}
|
|
226
|
-
function
|
|
227
|
-
|
|
228
|
-
if (table === null)
|
|
415
|
+
function backfillCompactionUsage(db) {
|
|
416
|
+
if (!hasTable(db, "events") || !hasTable(db, "usage"))
|
|
229
417
|
return;
|
|
230
|
-
|
|
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
|
|
233
|
-
|
|
234
|
-
|
|
442
|
+
function migrateLegacyCompactions(db) {
|
|
443
|
+
if (!hasTable(db, "events"))
|
|
444
|
+
return;
|
|
445
|
+
const columns = columnsOf(db, "events");
|
|
446
|
+
if (!["session_id", "kind", "message_id", "at"].every((name) => columns.has(name)))
|
|
235
447
|
return;
|
|
236
|
-
db.
|
|
237
|
-
|
|
238
|
-
|
|
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)`);
|
|
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
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
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
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
491
|
+
try {
|
|
492
|
+
db.exec("PRAGMA journal_mode = WAL");
|
|
493
|
+
db.exec("PRAGMA busy_timeout = 5000");
|
|
494
|
+
db.exec("PRAGMA synchronous = NORMAL");
|
|
495
|
+
db.exec(SCHEMA);
|
|
496
|
+
migrate(db);
|
|
497
|
+
db.query("INSERT INTO meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(SCHEMA_VERSION));
|
|
498
|
+
hardenFiles(path);
|
|
499
|
+
return db;
|
|
500
|
+
} catch (error) {
|
|
501
|
+
db.close();
|
|
502
|
+
throw error;
|
|
503
|
+
}
|
|
294
504
|
}
|
|
295
505
|
function openStatsDbReadOnly(path) {
|
|
296
506
|
ensureRegularFile(path);
|
|
@@ -313,117 +523,6 @@ function openStatsDbWrite(path) {
|
|
|
313
523
|
hardenFiles(path);
|
|
314
524
|
return db;
|
|
315
525
|
}
|
|
316
|
-
function recordStep(db, record) {
|
|
317
|
-
const cost = Math.max(0, finite(record.cost));
|
|
318
|
-
const listCost = cost <= 0 && typeof record.listCost === "number" && Number.isFinite(record.listCost) && record.listCost >= 0 ? record.listCost : null;
|
|
319
|
-
db.query(`INSERT INTO steps (
|
|
320
|
-
message_id, session_id, parent_id, provider_id, model_id, variant,
|
|
321
|
-
input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost, list_cost,
|
|
322
|
-
created_at, streamed_at, completed_at, finish, recorded_at
|
|
323
|
-
) VALUES (
|
|
324
|
-
$messageID, $sessionID, $parentID, $providerID, $modelID, $variant,
|
|
325
|
-
$input, $output, $reasoning, $cacheRead, $cacheWrite, $cost, $listCost,
|
|
326
|
-
$createdAt, $streamedAt, $completedAt, $finish, $recordedAt
|
|
327
|
-
)
|
|
328
|
-
ON CONFLICT(message_id) DO UPDATE SET
|
|
329
|
-
session_id = excluded.session_id,
|
|
330
|
-
parent_id = COALESCE(excluded.parent_id, steps.parent_id),
|
|
331
|
-
provider_id = COALESCE(excluded.provider_id, steps.provider_id),
|
|
332
|
-
model_id = COALESCE(excluded.model_id, steps.model_id),
|
|
333
|
-
variant = COALESCE(excluded.variant, steps.variant),
|
|
334
|
-
input_tokens = excluded.input_tokens,
|
|
335
|
-
output_tokens = excluded.output_tokens,
|
|
336
|
-
reasoning_tokens = excluded.reasoning_tokens,
|
|
337
|
-
cache_read = excluded.cache_read,
|
|
338
|
-
cache_write = excluded.cache_write,
|
|
339
|
-
cost = excluded.cost,
|
|
340
|
-
-- A step that starts being charged loses its estimate; an estimate is
|
|
341
|
-
-- kept when a replayed event arrives without a price table.
|
|
342
|
-
list_cost = CASE WHEN excluded.cost > 0 THEN NULL ELSE COALESCE(excluded.list_cost, steps.list_cost) END,
|
|
343
|
-
created_at = COALESCE(excluded.created_at, steps.created_at),
|
|
344
|
-
streamed_at = COALESCE(excluded.streamed_at, steps.streamed_at),
|
|
345
|
-
completed_at = COALESCE(excluded.completed_at, steps.completed_at),
|
|
346
|
-
finish = COALESCE(excluded.finish, steps.finish),
|
|
347
|
-
recorded_at = excluded.recorded_at`).run({
|
|
348
|
-
$messageID: record.messageID,
|
|
349
|
-
$sessionID: record.sessionID,
|
|
350
|
-
$parentID: record.parentID ?? null,
|
|
351
|
-
$providerID: record.providerID !== undefined && isToken(record.providerID) ? record.providerID : null,
|
|
352
|
-
$modelID: record.modelID ?? null,
|
|
353
|
-
$variant: record.variant ?? null,
|
|
354
|
-
$input: tokenCount(record.input),
|
|
355
|
-
$output: tokenCount(record.output),
|
|
356
|
-
$reasoning: tokenCount(record.reasoning),
|
|
357
|
-
$cacheRead: tokenCount(record.cacheRead),
|
|
358
|
-
$cacheWrite: tokenCount(record.cacheWrite),
|
|
359
|
-
$cost: cost,
|
|
360
|
-
$listCost: listCost,
|
|
361
|
-
$createdAt: timestamp(record.createdAt),
|
|
362
|
-
$streamedAt: timestamp(record.streamedAt),
|
|
363
|
-
$completedAt: timestamp(record.completedAt),
|
|
364
|
-
$finish: record.finish === undefined ? null : sanitizeLabel(record.finish, 64),
|
|
365
|
-
$recordedAt: timestamp(record.recordedAt) ?? Date.now()
|
|
366
|
-
});
|
|
367
|
-
}
|
|
368
|
-
function recordUsage(db, record) {
|
|
369
|
-
if (typeof record.id !== "string" || record.id === "")
|
|
370
|
-
return;
|
|
371
|
-
if (typeof record.sessionID !== "string" || record.sessionID === "")
|
|
372
|
-
return;
|
|
373
|
-
db.query(`INSERT INTO usage (
|
|
374
|
-
id, session_id, source, at, cost, input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
|
|
375
|
-
) VALUES (
|
|
376
|
-
$id, $sessionID, $source, $at, $cost, $input, $output, $reasoning, $cacheRead, $cacheWrite
|
|
377
|
-
) ON CONFLICT(id) DO NOTHING`).run({
|
|
378
|
-
$id: record.id,
|
|
379
|
-
$sessionID: record.sessionID,
|
|
380
|
-
$source: sanitizeLabel(record.source, 64),
|
|
381
|
-
$at: timestamp(record.at) ?? Date.now(),
|
|
382
|
-
$cost: Math.max(0, finite(record.cost)),
|
|
383
|
-
$input: tokenCount(record.input),
|
|
384
|
-
$output: tokenCount(record.output),
|
|
385
|
-
$reasoning: tokenCount(record.reasoning),
|
|
386
|
-
$cacheRead: tokenCount(record.cacheRead),
|
|
387
|
-
$cacheWrite: tokenCount(record.cacheWrite)
|
|
388
|
-
});
|
|
389
|
-
}
|
|
390
|
-
function recordPrompt(db, record) {
|
|
391
|
-
db.query(`INSERT INTO prompts (session_id, message_id, created_at)
|
|
392
|
-
VALUES ($sessionID, $messageID, $createdAt)
|
|
393
|
-
ON CONFLICT(session_id, message_id) DO UPDATE SET created_at = COALESCE(excluded.created_at, prompts.created_at)`).run({
|
|
394
|
-
$sessionID: record.sessionID,
|
|
395
|
-
$messageID: record.messageID,
|
|
396
|
-
$createdAt: timestamp(record.createdAt)
|
|
397
|
-
});
|
|
398
|
-
}
|
|
399
|
-
function recordEvent(db, record) {
|
|
400
|
-
db.query(`INSERT OR IGNORE INTO events (session_id, kind, message_id, at, data)
|
|
401
|
-
VALUES ($sessionID, $kind, $messageID, $at, $data)`).run({
|
|
402
|
-
$sessionID: record.sessionID,
|
|
403
|
-
$kind: sanitizeLabel(record.kind, 64),
|
|
404
|
-
$messageID: record.messageID ?? null,
|
|
405
|
-
$at: timestamp(record.at) ?? Date.now(),
|
|
406
|
-
$data: jsonText(record.data)
|
|
407
|
-
});
|
|
408
|
-
}
|
|
409
|
-
function upsertSession(db, record) {
|
|
410
|
-
db.query(`INSERT INTO sessions (session_id, parent_id, directory, title, started_at, updated_at)
|
|
411
|
-
VALUES ($sessionID, $parentID, $directory, $title, $startedAt, $updatedAt)
|
|
412
|
-
ON CONFLICT(session_id) DO UPDATE SET
|
|
413
|
-
parent_id = COALESCE(excluded.parent_id, sessions.parent_id),
|
|
414
|
-
directory = COALESCE(excluded.directory, sessions.directory),
|
|
415
|
-
title = COALESCE(excluded.title, sessions.title),
|
|
416
|
-
started_at = COALESCE(sessions.started_at, excluded.started_at),
|
|
417
|
-
updated_at = COALESCE(excluded.updated_at, sessions.updated_at)`).run({
|
|
418
|
-
$sessionID: record.sessionID,
|
|
419
|
-
$parentID: record.parentID ?? null,
|
|
420
|
-
$directory: record.directory === undefined ? null : sanitizeLabel(record.directory, LABEL_LIMIT),
|
|
421
|
-
$title: record.title === undefined ? null : sanitizeLabel(record.title, LABEL_LIMIT),
|
|
422
|
-
$startedAt: timestamp(record.startedAt),
|
|
423
|
-
$updatedAt: timestamp(record.updatedAt)
|
|
424
|
-
});
|
|
425
|
-
}
|
|
426
|
-
|
|
427
526
|
// src/service.ts
|
|
428
527
|
import { basename } from "path";
|
|
429
528
|
|
|
@@ -787,7 +886,6 @@ function formatLine(stats, options) {
|
|
|
787
886
|
}
|
|
788
887
|
|
|
789
888
|
// src/stats/queries.ts
|
|
790
|
-
var COMPACTION_KIND = "compaction";
|
|
791
889
|
var DEFAULT_TTL_HINT_MS = 10 * 60 * 1000;
|
|
792
890
|
function spend(usage) {
|
|
793
891
|
return usage.cost + usage.listCost;
|
|
@@ -857,9 +955,12 @@ function otherUsageRows(db, range, filters) {
|
|
|
857
955
|
}
|
|
858
956
|
}
|
|
859
957
|
var STEP_TIME = "COALESCE(created_at, recorded_at)";
|
|
860
|
-
var
|
|
958
|
+
var MODEL_KEY_SEPARATOR = "#";
|
|
959
|
+
function modelKeySQL(prefix = "") {
|
|
960
|
+
return `COALESCE(${prefix}model_id, '(unknown)') || '${MODEL_KEY_SEPARATOR}' || COALESCE(${prefix}variant, '')`;
|
|
961
|
+
}
|
|
861
962
|
function modelKey(modelID, variant) {
|
|
862
|
-
return `${modelID}
|
|
963
|
+
return `${modelID}${MODEL_KEY_SEPARATOR}${variant ?? ""}`;
|
|
863
964
|
}
|
|
864
965
|
function modelLabel(modelID, variant) {
|
|
865
966
|
return variant === undefined ? modelID : `${modelID} ${variant}`;
|
|
@@ -897,24 +998,24 @@ function rangeWhere(range, column = STEP_TIME) {
|
|
|
897
998
|
}
|
|
898
999
|
return { where: clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "", params };
|
|
899
1000
|
}
|
|
900
|
-
function buildWhere(range, filters, column = STEP_TIME) {
|
|
1001
|
+
function buildWhere(range, filters, column = STEP_TIME, prefix = "") {
|
|
901
1002
|
const rangeClause = rangeWhere(range, column);
|
|
902
1003
|
const clauses = rangeClause.where === "" ? [] : [rangeClause.where.slice("WHERE ".length)];
|
|
903
1004
|
const params = [...rangeClause.params];
|
|
904
1005
|
if (filters?.modelID !== undefined && filters.modelID !== "") {
|
|
905
|
-
clauses.push(
|
|
1006
|
+
clauses.push(`${prefix}model_id = ?`);
|
|
906
1007
|
params.push(filters.modelID);
|
|
907
1008
|
}
|
|
908
1009
|
if (filters?.modelKey !== undefined && filters.modelKey !== "") {
|
|
909
|
-
clauses.push(`${
|
|
1010
|
+
clauses.push(`${modelKeySQL(prefix)} = ?`);
|
|
910
1011
|
params.push(filters.modelKey);
|
|
911
1012
|
}
|
|
912
1013
|
if (filters?.provider !== undefined && filters.provider !== "") {
|
|
913
|
-
clauses.push(
|
|
1014
|
+
clauses.push(`${prefix}provider_id = ?`);
|
|
914
1015
|
params.push(filters.provider);
|
|
915
1016
|
}
|
|
916
1017
|
if (filters?.sessionID !== undefined && filters.sessionID !== "") {
|
|
917
|
-
clauses.push(
|
|
1018
|
+
clauses.push(`${prefix}session_id = ?`);
|
|
918
1019
|
params.push(filters.sessionID);
|
|
919
1020
|
}
|
|
920
1021
|
return { where: clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "", params };
|
|
@@ -930,7 +1031,10 @@ function overview(db, range, filters) {
|
|
|
930
1031
|
MIN(${STEP_TIME}) AS firstAt,
|
|
931
1032
|
MAX(COALESCE(completed_at, ${STEP_TIME})) AS lastAt,
|
|
932
1033
|
COALESCE(SUM(CASE WHEN streamed_at > created_at THEN output_tokens + reasoning_tokens ELSE 0 END), 0) AS produced,
|
|
933
|
-
COALESCE(SUM(CASE WHEN streamed_at > created_at THEN streamed_at - created_at ELSE 0 END), 0) AS window
|
|
1034
|
+
COALESCE(SUM(CASE WHEN streamed_at > created_at THEN streamed_at - created_at ELSE 0 END), 0) AS window,
|
|
1035
|
+
COALESCE(SUM(CASE WHEN streamed_at > COALESCE(first_token_at, created_at) THEN output_tokens + reasoning_tokens ELSE 0 END), 0) AS decodeProduced,
|
|
1036
|
+
COALESCE(SUM(CASE WHEN streamed_at > COALESCE(first_token_at, created_at)
|
|
1037
|
+
THEN streamed_at - COALESCE(first_token_at, created_at) ELSE 0 END), 0) AS decodeWindow
|
|
934
1038
|
FROM steps ${steps.where}`).get(...steps.params);
|
|
935
1039
|
const prompts = rangeWhere(range, "created_at");
|
|
936
1040
|
const promptClauses = prompts.where === "" ? [] : [prompts.where.slice("WHERE ".length)];
|
|
@@ -941,6 +1045,10 @@ function overview(db, range, filters) {
|
|
|
941
1045
|
}
|
|
942
1046
|
const promptWhere = promptClauses.length > 0 ? `WHERE ${promptClauses.join(" AND ")}` : "";
|
|
943
1047
|
const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${promptWhere}`).get(...promptParams);
|
|
1048
|
+
const ttftFilter = steps.where === "" ? "WHERE" : `${steps.where} AND`;
|
|
1049
|
+
const ttftRows = db.query(`SELECT MAX(0, first_token_at - created_at) AS ttft
|
|
1050
|
+
FROM steps ${ttftFilter} created_at IS NOT NULL AND first_token_at IS NOT NULL`).all(...steps.params);
|
|
1051
|
+
const ttft = ttftRows.length === 0 ? undefined : percentile(ttftRows.map((entry) => entry.ttft), 50);
|
|
944
1052
|
const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
|
|
945
1053
|
const other = otherUsage(db, range, filters);
|
|
946
1054
|
return {
|
|
@@ -952,7 +1060,9 @@ function overview(db, range, filters) {
|
|
|
952
1060
|
firstAt: row?.firstAt ?? undefined,
|
|
953
1061
|
lastAt: row?.lastAt ?? undefined,
|
|
954
1062
|
cacheHitRatio: cacheHitRatio(usage),
|
|
955
|
-
tps: row === null ? undefined : tokensPerSecond(row.
|
|
1063
|
+
tps: row === null ? undefined : tokensPerSecond(row.decodeProduced ?? 0, 0, row.decodeWindow ?? 0),
|
|
1064
|
+
requestTps: row === null ? undefined : tokensPerSecond(row.produced ?? 0, 0, row.window ?? 0),
|
|
1065
|
+
ttft
|
|
956
1066
|
};
|
|
957
1067
|
}
|
|
958
1068
|
function models(db, range, filters) {
|
|
@@ -1021,7 +1131,7 @@ function sessions(db, options) {
|
|
|
1021
1131
|
if (options?.sessionIDs !== undefined && options.sessionIDs.length === 0)
|
|
1022
1132
|
return [];
|
|
1023
1133
|
const range = options?.range;
|
|
1024
|
-
const filter = buildWhere(range, options?.filters, "COALESCE(st.created_at, st.recorded_at)");
|
|
1134
|
+
const filter = buildWhere(range, options?.filters, "COALESCE(st.created_at, st.recorded_at)", "st.");
|
|
1025
1135
|
const limit = options?.limit ?? 20;
|
|
1026
1136
|
const clauses = filter.where === "" ? [] : [filter.where.slice("WHERE ".length)];
|
|
1027
1137
|
const params = [...filter.params];
|
|
@@ -1085,8 +1195,8 @@ function sessions(db, options) {
|
|
|
1085
1195
|
function childSessionIDs(db, parentID) {
|
|
1086
1196
|
return db.query("SELECT session_id FROM sessions WHERE parent_id = ? ORDER BY session_id").all(parentID).map((row) => row.session_id);
|
|
1087
1197
|
}
|
|
1088
|
-
function sessionUsageOf(db, sessionIDs) {
|
|
1089
|
-
return sessions(db, { sessionIDs, limit: sessionIDs.length });
|
|
1198
|
+
function sessionUsageOf(db, sessionIDs, filters) {
|
|
1199
|
+
return sessions(db, { sessionIDs, limit: sessionIDs.length, filters });
|
|
1090
1200
|
}
|
|
1091
1201
|
function turnFinished(finish) {
|
|
1092
1202
|
return finish !== null && finish !== "" && finish !== "tool-calls";
|
|
@@ -1107,7 +1217,11 @@ function stepMessage(row) {
|
|
|
1107
1217
|
return {
|
|
1108
1218
|
type: "assistant",
|
|
1109
1219
|
id: row.message_id,
|
|
1110
|
-
time: {
|
|
1220
|
+
time: {
|
|
1221
|
+
created: row.created_at ?? row.recorded_at,
|
|
1222
|
+
firstToken: row.first_token_at ?? undefined,
|
|
1223
|
+
completed: row.completed_at ?? undefined
|
|
1224
|
+
},
|
|
1111
1225
|
model: row.provider_id !== null && row.model_id !== null ? { providerID: row.provider_id, id: row.model_id, variant: row.variant ?? undefined } : undefined,
|
|
1112
1226
|
tokens: {
|
|
1113
1227
|
input: row.input_tokens ?? 0,
|
|
@@ -1138,7 +1252,7 @@ function turns(db, options) {
|
|
|
1138
1252
|
}
|
|
1139
1253
|
const steps = db.query(`SELECT message_id, session_id, provider_id, model_id, variant,
|
|
1140
1254
|
input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,
|
|
1141
|
-
created_at, streamed_at, recorded_at, completed_at, finish
|
|
1255
|
+
created_at, first_token_at, streamed_at, recorded_at, completed_at, finish
|
|
1142
1256
|
FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
|
|
1143
1257
|
ORDER BY session_id, ${STEP_TIME}, message_id`).all(...params);
|
|
1144
1258
|
const promptClause = options?.sessionID === undefined ? "" : `WHERE session_id = ?${floor === undefined ? "" : " AND created_at >= ?"}`;
|
|
@@ -1181,12 +1295,22 @@ function turns(db, options) {
|
|
|
1181
1295
|
const variant = last.variant ?? undefined;
|
|
1182
1296
|
let produced = 0;
|
|
1183
1297
|
let window = 0;
|
|
1298
|
+
let decodeProduced = 0;
|
|
1299
|
+
let decodeWindow = 0;
|
|
1184
1300
|
for (const row of bucket) {
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1301
|
+
const tokens = (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0);
|
|
1302
|
+
if (row.created_at !== null && row.streamed_at !== null && row.streamed_at > row.created_at) {
|
|
1303
|
+
produced += tokens;
|
|
1304
|
+
window += row.streamed_at - row.created_at;
|
|
1305
|
+
}
|
|
1306
|
+
const start = row.first_token_at ?? row.created_at;
|
|
1307
|
+
if (start !== null && row.streamed_at !== null && row.streamed_at > start) {
|
|
1308
|
+
decodeProduced += tokens;
|
|
1309
|
+
decodeWindow += row.streamed_at - start;
|
|
1310
|
+
}
|
|
1189
1311
|
}
|
|
1312
|
+
const first = bucket[0];
|
|
1313
|
+
const ttft = first !== undefined && first.created_at !== null && first.first_token_at !== null ? Math.max(0, first.first_token_at - first.created_at) : undefined;
|
|
1190
1314
|
const previous = result.length > 0 && result[result.length - 1].sessionID === last.session_id ? result[result.length - 1] : undefined;
|
|
1191
1315
|
const endAt = last.completed_at ?? last.created_at ?? last.recorded_at;
|
|
1192
1316
|
const firstAt = bucket[0]?.created_at ?? promptAt;
|
|
@@ -1206,7 +1330,9 @@ function turns(db, options) {
|
|
|
1206
1330
|
totals,
|
|
1207
1331
|
drops,
|
|
1208
1332
|
finish: last.finish ?? undefined,
|
|
1209
|
-
tps: tokensPerSecond(
|
|
1333
|
+
tps: tokensPerSecond(decodeProduced, 0, decodeWindow),
|
|
1334
|
+
requestTps: tokensPerSecond(produced, 0, window),
|
|
1335
|
+
ttft
|
|
1210
1336
|
});
|
|
1211
1337
|
bucket = [];
|
|
1212
1338
|
}
|
|
@@ -1284,8 +1410,9 @@ var STEP_COLUMNS = `message_id AS messageID, session_id AS sessionID, provider_i
|
|
|
1284
1410
|
COALESCE(input_tokens, 0) AS input, COALESCE(cache_read, 0) AS cached, COALESCE(cache_write, 0) AS cacheWrite,
|
|
1285
1411
|
COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, COALESCE(cost, 0) AS cost,
|
|
1286
1412
|
COALESCE(list_cost, 0) AS listCost,
|
|
1287
|
-
created_at AS createdAt,
|
|
1288
|
-
|
|
1413
|
+
created_at AS createdAt, first_token_at AS firstTokenAt, streamed_at AS streamedAt,
|
|
1414
|
+
completed_at AS completedAt, ${STEP_AT} AS at`;
|
|
1415
|
+
var STEP_OPTIONAL = ["providerID", "modelID", "variant", "createdAt", "firstTokenAt", "streamedAt", "completedAt"];
|
|
1289
1416
|
var PAIR_COLUMNS = STEP_COLUMNS.replace("COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, ", "");
|
|
1290
1417
|
function stepRows(db, options) {
|
|
1291
1418
|
const filter = buildWhere(options?.range, options?.filters);
|
|
@@ -1364,6 +1491,7 @@ function coverageOf(db, options) {
|
|
|
1364
1491
|
COALESCE(SUM(CASE WHEN model_id IS NULL THEN 1 ELSE 0 END), 0) AS missingModel,
|
|
1365
1492
|
COALESCE(SUM(CASE WHEN completed_at IS NOT NULL OR finish IS NOT NULL THEN 0 ELSE 1 END), 0) AS unsettled,
|
|
1366
1493
|
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,
|
|
1494
|
+
COALESCE(SUM(CASE WHEN (output_tokens + reasoning_tokens) > 0 AND created_at IS NOT NULL AND streamed_at IS NOT NULL AND streamed_at > created_at AND first_token_at IS NULL THEN 1 ELSE 0 END), 0) AS missingFirstToken,
|
|
1367
1495
|
MIN(${STEP_AT}) AS firstAt,
|
|
1368
1496
|
MAX(${STEP_AT}) AS lastAt
|
|
1369
1497
|
FROM steps ${filter.where}`).get(...filter.params);
|
|
@@ -1374,6 +1502,7 @@ function coverageOf(db, options) {
|
|
|
1374
1502
|
missingModel: row.missingModel,
|
|
1375
1503
|
unsettled: row.unsettled,
|
|
1376
1504
|
missingTps: row.missingTps,
|
|
1505
|
+
missingFirstToken: row.missingFirstToken,
|
|
1377
1506
|
firstAt: row.firstAt ?? undefined,
|
|
1378
1507
|
lastAt: row.lastAt ?? undefined
|
|
1379
1508
|
};
|
|
@@ -1386,7 +1515,14 @@ function groupedRows(db, options) {
|
|
|
1386
1515
|
function timingOf(step) {
|
|
1387
1516
|
const wall = step.createdAt !== undefined && step.completedAt !== undefined ? Math.max(0, step.completedAt - step.createdAt) : undefined;
|
|
1388
1517
|
const stream = step.createdAt !== undefined && step.streamedAt !== undefined && step.streamedAt > step.createdAt ? step.streamedAt - step.createdAt : undefined;
|
|
1389
|
-
|
|
1518
|
+
const ttft = step.createdAt !== undefined && step.firstTokenAt !== undefined ? Math.max(0, step.firstTokenAt - step.createdAt) : undefined;
|
|
1519
|
+
return {
|
|
1520
|
+
wall,
|
|
1521
|
+
stream,
|
|
1522
|
+
ttft,
|
|
1523
|
+
tps: tokensPerSecond(step.output + step.reasoning, step.firstTokenAt ?? step.createdAt, step.streamedAt),
|
|
1524
|
+
requestTps: tokensPerSecond(step.output + step.reasoning, step.createdAt, step.streamedAt)
|
|
1525
|
+
};
|
|
1390
1526
|
}
|
|
1391
1527
|
function timingRows(db, options) {
|
|
1392
1528
|
return groupedRows(db, options);
|
|
@@ -1394,17 +1530,29 @@ function timingRows(db, options) {
|
|
|
1394
1530
|
function latencyOf(rows) {
|
|
1395
1531
|
const wall = [];
|
|
1396
1532
|
const stream = [];
|
|
1533
|
+
const ttft = [];
|
|
1397
1534
|
const tps = [];
|
|
1535
|
+
const requestTps = [];
|
|
1398
1536
|
for (const step of rows) {
|
|
1399
1537
|
const timing = timingOf(step);
|
|
1400
1538
|
if (timing.wall !== undefined)
|
|
1401
1539
|
wall.push(timing.wall);
|
|
1402
1540
|
if (timing.stream !== undefined)
|
|
1403
1541
|
stream.push(timing.stream);
|
|
1542
|
+
if (timing.ttft !== undefined)
|
|
1543
|
+
ttft.push(timing.ttft);
|
|
1404
1544
|
if (timing.tps !== undefined)
|
|
1405
1545
|
tps.push(timing.tps);
|
|
1546
|
+
if (timing.requestTps !== undefined)
|
|
1547
|
+
requestTps.push(timing.requestTps);
|
|
1406
1548
|
}
|
|
1407
|
-
return {
|
|
1549
|
+
return {
|
|
1550
|
+
wall: latencyStats(wall),
|
|
1551
|
+
stream: latencyStats(stream),
|
|
1552
|
+
ttft: latencyStats(ttft),
|
|
1553
|
+
tps: latencyStats(tps),
|
|
1554
|
+
requestTps: latencyStats(requestTps)
|
|
1555
|
+
};
|
|
1408
1556
|
}
|
|
1409
1557
|
function latencyGroupsOf(rows, by) {
|
|
1410
1558
|
const key = (step) => by === "model" ? modelKey(step.modelID ?? "(unknown)", step.variant) : step.providerID ?? "(unknown)";
|
|
@@ -1412,25 +1560,33 @@ function latencyGroupsOf(rows, by) {
|
|
|
1412
1560
|
for (const [group, steps] of groupBy(rows, key)) {
|
|
1413
1561
|
const wall = [];
|
|
1414
1562
|
const stream = [];
|
|
1563
|
+
const ttft = [];
|
|
1415
1564
|
const tps = [];
|
|
1565
|
+
const requestTps = [];
|
|
1416
1566
|
for (const step of steps) {
|
|
1417
1567
|
const timing = timingOf(step);
|
|
1418
1568
|
if (timing.wall !== undefined)
|
|
1419
1569
|
wall.push(timing.wall);
|
|
1420
1570
|
if (timing.stream !== undefined)
|
|
1421
1571
|
stream.push(timing.stream);
|
|
1572
|
+
if (timing.ttft !== undefined)
|
|
1573
|
+
ttft.push(timing.ttft);
|
|
1422
1574
|
if (timing.tps !== undefined)
|
|
1423
1575
|
tps.push(timing.tps);
|
|
1576
|
+
if (timing.requestTps !== undefined)
|
|
1577
|
+
requestTps.push(timing.requestTps);
|
|
1424
1578
|
}
|
|
1425
|
-
const
|
|
1579
|
+
const { modelID, variant } = splitModelKey(group);
|
|
1426
1580
|
groups.push({
|
|
1427
1581
|
key: group,
|
|
1428
|
-
label: by === "model" ? variant === undefined
|
|
1582
|
+
label: by === "model" ? variant === undefined ? modelID : `${modelID} ${variant}` : group,
|
|
1429
1583
|
count: steps.length,
|
|
1430
1584
|
usage: usageOf(steps),
|
|
1431
1585
|
wall: latencyStats(wall),
|
|
1432
1586
|
stream: latencyStats(stream),
|
|
1433
|
-
|
|
1587
|
+
ttft: latencyStats(ttft),
|
|
1588
|
+
tps: latencyStats(tps),
|
|
1589
|
+
requestTps: latencyStats(requestTps)
|
|
1434
1590
|
});
|
|
1435
1591
|
}
|
|
1436
1592
|
return groups.sort((left, right) => right.count - left.count || left.key.localeCompare(right.key));
|
|
@@ -1610,21 +1766,21 @@ function cacheDropsOf(db, rows, options) {
|
|
|
1610
1766
|
}
|
|
1611
1767
|
if (losses.length === 0)
|
|
1612
1768
|
return [];
|
|
1613
|
-
const
|
|
1769
|
+
const times = new Map;
|
|
1614
1770
|
const sessionIDs = [...new Set(losses.map((loss) => loss.current.sessionID))];
|
|
1615
|
-
const
|
|
1616
|
-
WHERE
|
|
1771
|
+
const timeline = db.query(`SELECT session_id, at FROM compactions
|
|
1772
|
+
WHERE at IS NOT NULL AND session_id IN (${sessionIDs.map(() => "?").join(", ")})
|
|
1617
1773
|
ORDER BY at`).all(...sessionIDs);
|
|
1618
|
-
for (const
|
|
1619
|
-
const list =
|
|
1774
|
+
for (const row of timeline) {
|
|
1775
|
+
const list = times.get(row.session_id);
|
|
1620
1776
|
if (list !== undefined)
|
|
1621
|
-
list.push(
|
|
1777
|
+
list.push(row.at);
|
|
1622
1778
|
else
|
|
1623
|
-
|
|
1779
|
+
times.set(row.session_id, [row.at]);
|
|
1624
1780
|
}
|
|
1625
1781
|
return losses.map((loss) => {
|
|
1626
1782
|
const ended = loss.previous.completedAt ?? loss.previous.streamedAt ?? loss.previous.createdAt;
|
|
1627
|
-
const compacted = (
|
|
1783
|
+
const compacted = (times.get(loss.current.sessionID) ?? []).some((time) => ended !== undefined && time >= ended && time <= loss.current.at);
|
|
1628
1784
|
const reason = compacted ? "compaction" : loss.gapMs !== undefined && loss.gapMs >= ttlHint ? "expired" : "unknown";
|
|
1629
1785
|
return {
|
|
1630
1786
|
sessionID: loss.current.sessionID,
|
|
@@ -1643,14 +1799,34 @@ function cacheDropsOf(db, rows, options) {
|
|
|
1643
1799
|
function groupValues(steps) {
|
|
1644
1800
|
const wall = [];
|
|
1645
1801
|
const tps = [];
|
|
1802
|
+
const requestTps = [];
|
|
1803
|
+
const ttft = [];
|
|
1646
1804
|
for (const step of steps) {
|
|
1647
1805
|
const timing = timingOf(step);
|
|
1648
1806
|
if (timing.wall !== undefined)
|
|
1649
1807
|
wall.push(timing.wall);
|
|
1650
1808
|
if (timing.tps !== undefined)
|
|
1651
1809
|
tps.push(timing.tps);
|
|
1810
|
+
if (timing.requestTps !== undefined)
|
|
1811
|
+
requestTps.push(timing.requestTps);
|
|
1812
|
+
if (timing.ttft !== undefined)
|
|
1813
|
+
ttft.push(timing.ttft);
|
|
1652
1814
|
}
|
|
1653
|
-
return {
|
|
1815
|
+
return {
|
|
1816
|
+
cache: cacheStatsOfSteps(steps),
|
|
1817
|
+
tps: latencyStats(tps).p50,
|
|
1818
|
+
requestTps: latencyStats(requestTps).p50,
|
|
1819
|
+
ttft: latencyStats(ttft).p50,
|
|
1820
|
+
wall: latencyStats(wall).p50
|
|
1821
|
+
};
|
|
1822
|
+
}
|
|
1823
|
+
var MODEL_LIST_SEPARATOR = "\x00";
|
|
1824
|
+
function splitModelKey(key) {
|
|
1825
|
+
const separator = key.indexOf(MODEL_KEY_SEPARATOR);
|
|
1826
|
+
if (separator === -1)
|
|
1827
|
+
return { modelID: key, variant: undefined };
|
|
1828
|
+
const variant = key.slice(separator + 1);
|
|
1829
|
+
return { modelID: key.slice(0, separator), variant: variant === "" ? undefined : variant };
|
|
1654
1830
|
}
|
|
1655
1831
|
function providerOf(steps, models) {
|
|
1656
1832
|
const values = groupValues(steps);
|
|
@@ -1664,17 +1840,22 @@ function providerOf(steps, models) {
|
|
|
1664
1840
|
}
|
|
1665
1841
|
return {
|
|
1666
1842
|
provider: steps[0].providerID,
|
|
1667
|
-
models: models.split(
|
|
1843
|
+
models: models.split(MODEL_LIST_SEPARATOR),
|
|
1668
1844
|
share: 0,
|
|
1669
1845
|
usage: usageOf(steps),
|
|
1670
1846
|
cache: values.cache,
|
|
1671
1847
|
tps: values.tps,
|
|
1848
|
+
requestTps: values.requestTps,
|
|
1849
|
+
ttft: values.ttft,
|
|
1672
1850
|
wall: values.wall,
|
|
1673
1851
|
firstAt,
|
|
1674
1852
|
lastAt
|
|
1675
1853
|
};
|
|
1676
1854
|
}
|
|
1677
|
-
var modelNames = (steps) => [...new Set(steps.map((step) => modelKey(step.modelID ?? "(unknown)", step.variant)))].map((key) =>
|
|
1855
|
+
var modelNames = (steps) => [...new Set(steps.map((step) => modelKey(step.modelID ?? "(unknown)", step.variant)))].map((key) => {
|
|
1856
|
+
const { modelID, variant } = splitModelKey(key);
|
|
1857
|
+
return modelLabel(modelID, variant);
|
|
1858
|
+
}).join(MODEL_LIST_SEPARATOR);
|
|
1678
1859
|
function providerSummaryOf(rows) {
|
|
1679
1860
|
const out = [];
|
|
1680
1861
|
for (const steps of groupBy(rows, (step) => step.providerID ?? "").values()) {
|
|
@@ -1687,7 +1868,7 @@ function providerBreakdownOf(rows) {
|
|
|
1687
1868
|
const out = [];
|
|
1688
1869
|
for (const [model, modelRows] of groupBy(rows, (step) => modelKey(step.modelID ?? "(unknown)", step.variant))) {
|
|
1689
1870
|
for (const steps of groupBy(modelRows, (step) => step.providerID ?? "").values()) {
|
|
1690
|
-
const
|
|
1871
|
+
const { modelID, variant } = splitModelKey(model);
|
|
1691
1872
|
out.push({
|
|
1692
1873
|
...providerOf(steps, modelNames(steps)),
|
|
1693
1874
|
modelID,
|
|
@@ -1893,8 +2074,8 @@ var RANGE_KEYS = ["session", "today", "7d", "30d", "all"];
|
|
|
1893
2074
|
var GRANULARITIES = ["day", "week", "month"];
|
|
1894
2075
|
var SORT_KEYS = {
|
|
1895
2076
|
models: ["steps", "cached", "hit", "out", "cost"],
|
|
1896
|
-
providers: ["steps", "cached", "hit", "cost", "share", "tps"],
|
|
1897
|
-
latency: ["n", "tps", "wall"],
|
|
2077
|
+
providers: ["steps", "cached", "hit", "cost", "share", "tps", "ttft"],
|
|
2078
|
+
latency: ["n", "tps", "ttft", "wall"],
|
|
1898
2079
|
sessions: ["last", "steps", "cached", "cost"],
|
|
1899
2080
|
turns: ["time", "cost", "tokens"]
|
|
1900
2081
|
};
|
|
@@ -1992,10 +2173,10 @@ function formatTps(value) {
|
|
|
1992
2173
|
return "\u2013";
|
|
1993
2174
|
return `${value.toFixed(1)}/s`;
|
|
1994
2175
|
}
|
|
1995
|
-
function
|
|
2176
|
+
function formatRateValue(value) {
|
|
1996
2177
|
if (value === undefined || !Number.isFinite(value) || value < 0)
|
|
1997
2178
|
return "\u2013";
|
|
1998
|
-
return value >= 10 ?
|
|
2179
|
+
return value >= 10 ? String(Math.round(value)) : value.toFixed(1);
|
|
1999
2180
|
}
|
|
2000
2181
|
function formatGap(value) {
|
|
2001
2182
|
if (value === undefined || !Number.isFinite(value))
|
|
@@ -2169,15 +2350,16 @@ function viewBar(view, width = 200, views = CLIENT_VIEWS) {
|
|
|
2169
2350
|
const index = views.indexOf(view);
|
|
2170
2351
|
return { text: `[${index === -1 ? "?" : key(index)} ${view}] \xB7 1-9 0 or [ ] to switch`, tone: "muted" };
|
|
2171
2352
|
}
|
|
2172
|
-
function keysFor(of) {
|
|
2353
|
+
function keysFor(of, range) {
|
|
2173
2354
|
if (of === QUOTA_VIEW)
|
|
2174
2355
|
return "r refresh \xB7 t range \xB7 0 view \xB7 ? help \xB7 the quotas come from OpenCode Go";
|
|
2175
2356
|
if (of === "db")
|
|
2176
2357
|
return "\u2191\u2193 pick a retention \xB7 enter prune \xB7 the last row wipes \xB7 e backfill \xB7 v vacuum \xB7 r refresh \xB7 1-9 0 view \xB7 ? help";
|
|
2177
2358
|
if (of === "periods")
|
|
2178
2359
|
return "\u2191\u2193 move \xB7 enter drill \xB7 b bucket \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
|
|
2179
|
-
if (of === "turns")
|
|
2180
|
-
return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
|
|
2360
|
+
if (of === "turns") {
|
|
2361
|
+
return range === "session" ? "\u2191\u2193 move \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help" : "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
|
|
2362
|
+
}
|
|
2181
2363
|
return "\u2191\u2193 move \xB7 enter drill \xB7 s sort \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
|
|
2182
2364
|
}
|
|
2183
2365
|
function filterSummary(filters) {
|
|
@@ -2199,7 +2381,7 @@ function helpLines(width) {
|
|
|
2199
2381
|
{ text: " t shift+t previous / next range" },
|
|
2200
2382
|
{ text: " s shift+s cycle sort column \xB7 reverse" },
|
|
2201
2383
|
{ text: " b periods bucket: day \u2192 week \u2192 month" },
|
|
2202
|
-
{ text: " a turns scope: this session \u2194 all sessions" },
|
|
2384
|
+
{ text: " a turns scope: this session \u2194 all sessions (time ranges)" },
|
|
2203
2385
|
{ text: " m p filter by model / provider (x clears)" },
|
|
2204
2386
|
{ text: " r re-read the database \xB7 f full screen \xB7 escape close" },
|
|
2205
2387
|
{ text: " e db: backfill list-price estimates for the $0 steps" },
|
|
@@ -2226,7 +2408,11 @@ function helpLines(width) {
|
|
|
2226
2408
|
{ text: " \u2248 list-price estimate for steps the host reported as $0;" },
|
|
2227
2409
|
{ text: " `$0.12 + \u2248 $3.40` keeps charged and estimated money apart" },
|
|
2228
2410
|
{ text: " wall request \u2192 completed step \xB7 stream request \u2192 last chunk" },
|
|
2229
|
-
{ text: "
|
|
2411
|
+
{ text: " ttft request \u2192 first streamed token" },
|
|
2412
|
+
{ text: " tps output+reasoning / first token \u2192 last chunk (OpenCode)" },
|
|
2413
|
+
{ text: " rtps output+reasoning / request \u2192 last chunk (includes TTFT)" },
|
|
2414
|
+
{ text: " turn 200 tps \xB7 2.1s ttft \xB7 cost" },
|
|
2415
|
+
{ text: " session 200 tps \xB7 167 rtps \xB7 ttft p50 \xB7 cost" },
|
|
2230
2416
|
{ text: " switches how often a step's model or provider differs from the step" },
|
|
2231
2417
|
{ text: " before it in the same session (the models view's detail), with" },
|
|
2232
2418
|
{ text: " the cache a provider switch cost" },
|
|
@@ -2355,12 +2541,16 @@ function usagePairs(usage, estimates = true) {
|
|
|
2355
2541
|
];
|
|
2356
2542
|
if (buckets.reasoning > 0)
|
|
2357
2543
|
pairs.push(["reasoning", formatTokens(buckets.reasoning)]);
|
|
2544
|
+
if ("tps" in usage && usage.tps !== undefined)
|
|
2545
|
+
pairs.push(["tps", formatTps(usage.tps)]);
|
|
2546
|
+
if ("requestTps" in usage && usage.requestTps !== undefined)
|
|
2547
|
+
pairs.push(["rtps", formatTps(usage.requestTps)]);
|
|
2548
|
+
if ("ttft" in usage && usage.ttft !== undefined)
|
|
2549
|
+
pairs.push(["ttft p50", formatMs(usage.ttft)]);
|
|
2358
2550
|
pairs.push(["cost", (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost)]);
|
|
2359
2551
|
const other = usage.otherCost ?? 0;
|
|
2360
2552
|
if (other > 0)
|
|
2361
2553
|
pairs.push(["other", `${formatCost(other)} comp/title`]);
|
|
2362
|
-
if ("tps" in usage && usage.tps !== undefined)
|
|
2363
|
-
pairs.push(["tps", formatTps(usage.tps)]);
|
|
2364
2554
|
return pairs;
|
|
2365
2555
|
}
|
|
2366
2556
|
function overviewLines(data, width) {
|
|
@@ -2413,6 +2603,7 @@ function coveragePairs(coverage) {
|
|
|
2413
2603
|
["models", `${formatCount(coverage.models)} \xB7 unknown ${share(coverage.missingModel)}`],
|
|
2414
2604
|
["providers", formatCount(coverage.providers)],
|
|
2415
2605
|
["unsettled", `${formatCount(coverage.unsettled)} \xB7 no tps ${share(coverage.missingTps)}`],
|
|
2606
|
+
["no ttft", share(coverage.missingFirstToken)],
|
|
2416
2607
|
[
|
|
2417
2608
|
"window",
|
|
2418
2609
|
`${coverage.firstAt === undefined ? "\u2013" : new Date(coverage.firstAt).toLocaleString("en-GB")} \u2192 ${coverage.lastAt === undefined ? "\u2013" : new Date(coverage.lastAt).toLocaleString("en-GB")}`
|
|
@@ -2523,7 +2714,8 @@ function providerSummaryLines(rows, width, limit = 40, estimates = true) {
|
|
|
2523
2714
|
{ header: "cached", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
|
|
2524
2715
|
{ header: "hit", width: 6, max: 7, align: "right", priority: 2, cell: (row) => formatPercent(row.cache.hit) },
|
|
2525
2716
|
{ header: "tps p50", width: 8, align: "right", priority: 5, cell: (row) => formatTps(row.tps) },
|
|
2526
|
-
{ header: "
|
|
2717
|
+
{ header: "ttft p50", width: 8, max: 9, align: "right", priority: 6, cell: (row) => formatMs(row.ttft) },
|
|
2718
|
+
{ header: "wall", width: 7, align: "right", priority: 7, cell: (row) => formatMs(row.wall) },
|
|
2527
2719
|
{ header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
|
|
2528
2720
|
], width, {
|
|
2529
2721
|
limit,
|
|
@@ -2543,7 +2735,8 @@ function providerLines(rows, width, limit = 40, estimates = true) {
|
|
|
2543
2735
|
{ header: "cached", width: 7, max: 10, align: "right", priority: 3, cell: (row) => formatTokens(row.cache.cached) },
|
|
2544
2736
|
{ header: "hit", width: 6, max: 7, align: "right", priority: 4, cell: (row) => formatPercent(row.cache.hit) },
|
|
2545
2737
|
{ header: "tps p50", width: 8, align: "right", priority: 6, cell: (row) => formatTps(row.tps) },
|
|
2546
|
-
{ header: "
|
|
2738
|
+
{ header: "ttft p50", width: 8, max: 9, align: "right", priority: 7, cell: (row) => formatMs(row.ttft) },
|
|
2739
|
+
{ header: "wall", width: 7, align: "right", priority: 8, cell: (row) => formatMs(row.wall) },
|
|
2547
2740
|
{ header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
|
|
2548
2741
|
], width, {
|
|
2549
2742
|
limit,
|
|
@@ -2781,7 +2974,15 @@ function latencyLines(report, width, groups, limit = 12, estimates = true) {
|
|
|
2781
2974
|
tone: "base"
|
|
2782
2975
|
});
|
|
2783
2976
|
lines.push({
|
|
2784
|
-
text: formatTableRow(["
|
|
2977
|
+
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]),
|
|
2978
|
+
tone: "base"
|
|
2979
|
+
});
|
|
2980
|
+
lines.push({
|
|
2981
|
+
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]),
|
|
2982
|
+
tone: "base"
|
|
2983
|
+
});
|
|
2984
|
+
lines.push({
|
|
2985
|
+
text: formatTableRow(["rtps", "p50", formatTps(report.requestTps.p50), "p90", formatTps(report.requestTps.p90), "p99", formatTps(report.requestTps.p99)], [10, 4, 9, 4, 9, 4, 9]),
|
|
2785
2986
|
tone: "base"
|
|
2786
2987
|
});
|
|
2787
2988
|
} else {
|
|
@@ -2794,13 +2995,25 @@ function latencyLines(report, width, groups, limit = 12, estimates = true) {
|
|
|
2794
2995
|
tone: "base"
|
|
2795
2996
|
});
|
|
2796
2997
|
lines.push({
|
|
2797
|
-
text: latencyMetric("
|
|
2998
|
+
text: latencyMetric("ttft", [`p50 ${formatMs(report.ttft.p50)}`, `p90 ${formatMs(report.ttft.p90)}`, `p99 ${formatMs(report.ttft.p99)}`], width),
|
|
2999
|
+
tone: "base"
|
|
3000
|
+
});
|
|
3001
|
+
lines.push({
|
|
3002
|
+
text: latencyMetric("tps", [`p50 ${formatTps(report.tps.p50)}`, `p90 ${formatTps(report.tps.p90)}`, `p99 ${formatTps(report.tps.p99)}`], width),
|
|
3003
|
+
tone: "base"
|
|
3004
|
+
});
|
|
3005
|
+
lines.push({
|
|
3006
|
+
text: latencyMetric("rtps", [`p50 ${formatTps(report.requestTps.p50)}`, `p90 ${formatTps(report.requestTps.p90)}`, `p99 ${formatTps(report.requestTps.p99)}`], width),
|
|
2798
3007
|
tone: "base"
|
|
2799
3008
|
});
|
|
2800
3009
|
}
|
|
2801
3010
|
lines.push({ text: "", tone: "muted" });
|
|
2802
3011
|
lines.push({
|
|
2803
|
-
text: truncate("wall = request to completed \xB7 stream = request to last chunk
|
|
3012
|
+
text: truncate("wall = request to completed \xB7 stream = request to last chunk", width),
|
|
3013
|
+
tone: "muted"
|
|
3014
|
+
});
|
|
3015
|
+
lines.push({
|
|
3016
|
+
text: truncate("ttft = request to first token \xB7 tps = first token to last chunk \xB7 rtps = request to last chunk", width),
|
|
2804
3017
|
tone: "muted"
|
|
2805
3018
|
});
|
|
2806
3019
|
if (report.wall.count === 0)
|
|
@@ -2815,7 +3028,8 @@ function latencyLines(report, width, groups, limit = 12, estimates = true) {
|
|
|
2815
3028
|
{ header: "wall p90", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatMs(row.wall.p90) },
|
|
2816
3029
|
{ header: "stream", width: 6, max: 9, align: "right", priority: 2, cell: (row) => formatMs(row.stream.p50) },
|
|
2817
3030
|
{ header: "tps p50", width: 8, max: 9, align: "right", cell: (row) => formatTps(row.tps.p50) },
|
|
2818
|
-
{ header: "tps p90", width: 8, max: 9, align: "right", priority:
|
|
3031
|
+
{ header: "tps p90", width: 8, max: 9, align: "right", priority: 4, cell: (row) => formatTps(row.tps.p90) },
|
|
3032
|
+
{ header: "ttft p50", width: 8, max: 9, align: "right", priority: 3, cell: (row) => formatMs(row.ttft.p50) },
|
|
2819
3033
|
{ header: "cost", width: 8, max: 9, align: "right", cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
|
|
2820
3034
|
], width);
|
|
2821
3035
|
if (columns.length > 0) {
|
|
@@ -3044,7 +3258,9 @@ function sessionSummaryLines(usage, budget = 34, estimates = true) {
|
|
|
3044
3258
|
const cached = formatTokens(buckets.cached);
|
|
3045
3259
|
const out = formatTokens(buckets.output);
|
|
3046
3260
|
const hit = formatPercent(buckets.hit);
|
|
3047
|
-
const tps =
|
|
3261
|
+
const tps = usage.tps === undefined ? undefined : `${formatRateValue(usage.tps)} tps`;
|
|
3262
|
+
const rtps = usage.requestTps === undefined ? undefined : `${formatRateValue(usage.requestTps)} rtps`;
|
|
3263
|
+
const ttft = usage.ttft === undefined ? undefined : `ttft p50 ${formatMs(usage.ttft)}`;
|
|
3048
3264
|
const cost = (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost);
|
|
3049
3265
|
const first = [
|
|
3050
3266
|
` ${steps} steps \xB7 in ${input}`,
|
|
@@ -3054,16 +3270,22 @@ function sessionSummaryLines(usage, budget = 34, estimates = true) {
|
|
|
3054
3270
|
` cached ${cached} \xB7 out ${out}`,
|
|
3055
3271
|
` cached ${cached}`
|
|
3056
3272
|
].find((text) => text.length <= budget);
|
|
3057
|
-
const
|
|
3058
|
-
|
|
3059
|
-
` hit ${hit} \xB7 ${
|
|
3060
|
-
` ${
|
|
3273
|
+
const rates = [tps, rtps].filter((part) => part !== undefined);
|
|
3274
|
+
const rateLine = [
|
|
3275
|
+
` hit ${hit}${rates.length > 0 ? ` \xB7 ${rates.join(" \xB7 ")}` : ""}`,
|
|
3276
|
+
` hit ${hit}${rates[0] !== undefined ? ` \xB7 ${rates[0]}` : ""}`,
|
|
3277
|
+
` hit ${hit}`
|
|
3061
3278
|
].find((text) => text.length <= budget);
|
|
3279
|
+
const tail = [
|
|
3280
|
+
ttft === undefined ? undefined : ` ${ttft} \xB7 ${cost}`,
|
|
3281
|
+
` ${cost}`
|
|
3282
|
+
].filter((text) => text !== undefined).find((text) => text.length <= budget);
|
|
3062
3283
|
return [
|
|
3063
3284
|
{ text: truncate("session", budget), tone: HEADER_TONE },
|
|
3064
3285
|
{ text: truncate(first ?? ` ${steps} steps`, budget), tone: "muted" },
|
|
3065
3286
|
{ text: truncate(second ?? ` cached ${cached}`, budget), tone: "base" },
|
|
3066
|
-
{ text: truncate(
|
|
3287
|
+
{ text: truncate(rateLine ?? ` hit ${hit}`, budget), tone: "base" },
|
|
3288
|
+
{ text: truncate(tail ?? ` ${cost}`, budget), tone: "base" },
|
|
3067
3289
|
{ text: "", tone: "muted" }
|
|
3068
3290
|
];
|
|
3069
3291
|
}
|
|
@@ -3080,20 +3302,28 @@ function sidebarLines(rows, options) {
|
|
|
3080
3302
|
const output = formatTokens(display.output);
|
|
3081
3303
|
const cost = options?.estimates === false ? formatCost(turn.totals.cost) : formatMoney(turn.totals.cost, turn.totals.listCost) ?? formatCost(turn.totals.cost);
|
|
3082
3304
|
const hit = formatPercent(display.prompt > 0 ? display.cached / display.prompt : undefined).replace(/\.0%$/, "%");
|
|
3083
|
-
const tps = turn.tps === undefined ? undefined :
|
|
3305
|
+
const tps = turn.tps === undefined ? undefined : `${formatRateValue(turn.tps)} tps`;
|
|
3306
|
+
const ttft = turn.ttft === undefined ? undefined : `${formatMs(turn.ttft)} ttft`;
|
|
3307
|
+
const rate = [tps, ttft].filter((part) => part !== undefined).join(" \xB7 ");
|
|
3084
3308
|
const suffix = turn.drops.length > 0 ? " \xB7 \u26A0" : "";
|
|
3085
3309
|
const header = `${clock} ${provider}`;
|
|
3086
3310
|
const timed = turn.durationMs === undefined ? undefined : `${header} \xB7 ${formatMs(turn.durationMs)}`;
|
|
3311
|
+
const join = (...parts) => parts.filter((part) => part !== undefined && part !== "").join(" \xB7 ");
|
|
3087
3312
|
const volumes = [
|
|
3088
|
-
` ${labels.input} ${input} (${prompt}) \xB7 ${labels.output} ${output}`,
|
|
3313
|
+
` ${labels.input} ${input} (${prompt}) \xB7 ${labels.output} ${output} \xB7 hit ${hit}`,
|
|
3314
|
+
` ${labels.input} ${input} \xB7 ${labels.output} ${output} \xB7 hit ${hit}`,
|
|
3089
3315
|
` ${labels.input} ${input} \xB7 ${labels.output} ${output}`,
|
|
3090
3316
|
` ${labels.input} ${input}`
|
|
3091
3317
|
];
|
|
3318
|
+
const volume = volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1];
|
|
3319
|
+
const hitPart = volume.includes(`hit ${hit}`) ? undefined : `hit ${hit}`;
|
|
3092
3320
|
const facts = [
|
|
3093
|
-
`
|
|
3094
|
-
`
|
|
3095
|
-
` ${tps
|
|
3096
|
-
`
|
|
3321
|
+
` ${join(hitPart, rate, `${cost}${suffix}`)}`,
|
|
3322
|
+
` ${join(hitPart, tps, `${cost}${suffix}`)}`,
|
|
3323
|
+
` ${join(tps, `${cost}${suffix}`)}`,
|
|
3324
|
+
` ${join(tps)}`,
|
|
3325
|
+
` ${join(hitPart, `${cost}${suffix}`)}`,
|
|
3326
|
+
` ${join(`${cost}${suffix}`)}`
|
|
3097
3327
|
];
|
|
3098
3328
|
lines.push({ text: truncate(timed !== undefined && timed.length <= budget ? timed : header, budget), tone: turn.providerChanged ? "warning" : "base" });
|
|
3099
3329
|
const edge = index === 0 || index === rows.length - 1;
|
|
@@ -3101,10 +3331,7 @@ function sidebarLines(rows, options) {
|
|
|
3101
3331
|
const model = turn.modelID === undefined ? "unknown" : `${turn.modelID}${turn.variant === undefined ? "" : ` ${turn.variant}`}`;
|
|
3102
3332
|
lines.push({ text: truncate(` ${model}`, budget), tone: "muted" });
|
|
3103
3333
|
}
|
|
3104
|
-
lines.push({
|
|
3105
|
-
text: truncate(volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1], budget),
|
|
3106
|
-
tone: "muted"
|
|
3107
|
-
});
|
|
3334
|
+
lines.push({ text: truncate(volume, budget), tone: "muted" });
|
|
3108
3335
|
lines.push({
|
|
3109
3336
|
text: truncate(facts.find((text) => text.length <= budget) ?? facts[facts.length - 1], budget),
|
|
3110
3337
|
tone: turn.drops.length > 0 ? "warning" : "muted"
|
|
@@ -3155,7 +3382,8 @@ function build(request) {
|
|
|
3155
3382
|
const usage = overview(db, range, filters);
|
|
3156
3383
|
const sessionUsage = request.sessionID === "" ? undefined : overview(db, undefined, { ...request.filters, sessionID: request.sessionID });
|
|
3157
3384
|
const childIDs = request.sessionID === "" ? [] : childSessionIDs(db, request.sessionID);
|
|
3158
|
-
const
|
|
3385
|
+
const childFilters = { ...request.filters, sessionID: undefined };
|
|
3386
|
+
const children = childIDs.length === 0 ? [] : sessionUsageOf(db, childIDs, childFilters);
|
|
3159
3387
|
return overviewLines({
|
|
3160
3388
|
usage,
|
|
3161
3389
|
session: sessionUsage,
|
|
@@ -3219,9 +3447,10 @@ function build(request) {
|
|
|
3219
3447
|
}
|
|
3220
3448
|
];
|
|
3221
3449
|
case "turns": {
|
|
3222
|
-
const
|
|
3450
|
+
const scope = scoped ? "session" : request.turnsScope;
|
|
3451
|
+
const sessionID = scope === "session" ? request.sessionID : undefined;
|
|
3223
3452
|
const rows = sortTurns(turns(db, { sessionID, range, filters, limit: 300 }), request.sort, request.sortDesc, estimates);
|
|
3224
|
-
const titles =
|
|
3453
|
+
const titles = scope === "all" ? new Map(sessions(db, { range, filters, limit: 200 }).map((row) => [row.sessionID, row.title ?? row.sessionID])) : undefined;
|
|
3225
3454
|
return turnsLines(rows.slice(0, 60), width, { ...request.format, estimates, sessionTitles: titles });
|
|
3226
3455
|
}
|
|
3227
3456
|
}
|
|
@@ -3346,6 +3575,8 @@ function sortProviders(rows, sort, desc, estimates = true) {
|
|
|
3346
3575
|
return row.share;
|
|
3347
3576
|
if (sort === "tps")
|
|
3348
3577
|
return row.tps ?? -1;
|
|
3578
|
+
if (sort === "ttft")
|
|
3579
|
+
return row.ttft ?? -1;
|
|
3349
3580
|
return row.usage.steps;
|
|
3350
3581
|
};
|
|
3351
3582
|
return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
|
|
@@ -3355,6 +3586,8 @@ function sortLatency(rows, sort, desc) {
|
|
|
3355
3586
|
const pick = (row) => {
|
|
3356
3587
|
if (sort === "tps")
|
|
3357
3588
|
return row.tps.p50 ?? -1;
|
|
3589
|
+
if (sort === "ttft")
|
|
3590
|
+
return row.ttft.p50 ?? -1;
|
|
3358
3591
|
if (sort === "wall")
|
|
3359
3592
|
return row.wall.p50 ?? -1;
|
|
3360
3593
|
return row.count;
|
|
@@ -3505,13 +3738,6 @@ function size(path) {
|
|
|
3505
3738
|
return 0;
|
|
3506
3739
|
}
|
|
3507
3740
|
}
|
|
3508
|
-
function hasTable(db, name) {
|
|
3509
|
-
try {
|
|
3510
|
-
return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== null;
|
|
3511
|
-
} catch {
|
|
3512
|
-
return false;
|
|
3513
|
-
}
|
|
3514
|
-
}
|
|
3515
3741
|
function dbInfo(db, path, now = Date.now()) {
|
|
3516
3742
|
const tables = TABLES.map((table) => ({
|
|
3517
3743
|
name: table,
|
|
@@ -3565,7 +3791,7 @@ function pruneOlderThan(db, cutoff) {
|
|
|
3565
3791
|
return {
|
|
3566
3792
|
steps: deleteBatched(db, "steps", `${STEP_TIME2} < ?`, cutoff),
|
|
3567
3793
|
prompts: deleteBatched(db, "prompts", "created_at IS NOT NULL AND created_at < ?", cutoff),
|
|
3568
|
-
|
|
3794
|
+
compactions: deleteBatched(db, "compactions", "at IS NOT NULL AND at < ?", cutoff),
|
|
3569
3795
|
usage: hasTable(db, "usage") ? deleteBatched(db, "usage", "at IS NOT NULL AND at < ?", cutoff) : 0
|
|
3570
3796
|
};
|
|
3571
3797
|
}
|
|
@@ -3573,7 +3799,7 @@ function wipeAll(db) {
|
|
|
3573
3799
|
return {
|
|
3574
3800
|
steps: deleteAllBatched(db, "steps"),
|
|
3575
3801
|
prompts: deleteAllBatched(db, "prompts"),
|
|
3576
|
-
|
|
3802
|
+
compactions: deleteAllBatched(db, "compactions"),
|
|
3577
3803
|
usage: hasTable(db, "usage") ? deleteAllBatched(db, "usage") : 0,
|
|
3578
3804
|
sessions: hasTable(db, "sessions") ? deleteAllBatched(db, "sessions") : 0
|
|
3579
3805
|
};
|
|
@@ -3596,23 +3822,41 @@ function hasListCost(db) {
|
|
|
3596
3822
|
}
|
|
3597
3823
|
}
|
|
3598
3824
|
var BACKFILL_BATCH = 1000;
|
|
3825
|
+
var UNPRICED_WHERE = `cost = 0 AND list_cost IS NULL
|
|
3826
|
+
AND provider_id IS NOT NULL AND provider_id <> ''
|
|
3827
|
+
AND model_id IS NOT NULL AND model_id <> ''
|
|
3828
|
+
AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`;
|
|
3829
|
+
function priceStep(step, price) {
|
|
3830
|
+
const estimate = price({ providerID: step.provider_id ?? undefined, modelID: step.model_id ?? undefined }, {
|
|
3831
|
+
input: step.input_tokens ?? 0,
|
|
3832
|
+
output: step.output_tokens ?? 0,
|
|
3833
|
+
reasoning: step.reasoning_tokens ?? 0,
|
|
3834
|
+
cacheRead: step.cache_read ?? 0,
|
|
3835
|
+
cacheWrite: step.cache_write ?? 0
|
|
3836
|
+
});
|
|
3837
|
+
return estimate !== undefined && Number.isFinite(estimate) && estimate >= 0 ? estimate : undefined;
|
|
3838
|
+
}
|
|
3839
|
+
function backfillBatch(db, rows, price, update) {
|
|
3840
|
+
let updated = 0;
|
|
3841
|
+
db.transaction(() => {
|
|
3842
|
+
for (const row of rows) {
|
|
3843
|
+
const estimate = priceStep(row, price);
|
|
3844
|
+
if (estimate !== undefined && update(estimate, row.rowid) > 0)
|
|
3845
|
+
updated += 1;
|
|
3846
|
+
}
|
|
3847
|
+
})();
|
|
3848
|
+
return updated;
|
|
3849
|
+
}
|
|
3599
3850
|
function backfillListCost(db, price) {
|
|
3600
3851
|
if (!hasListCost(db))
|
|
3601
3852
|
return { candidates: 0, updated: 0 };
|
|
3602
|
-
const candidates = db.query(`SELECT COUNT(*) AS n FROM steps
|
|
3603
|
-
WHERE cost = 0 AND list_cost IS NULL
|
|
3604
|
-
AND provider_id IS NOT NULL AND provider_id <> ''
|
|
3605
|
-
AND model_id IS NOT NULL AND model_id <> ''
|
|
3606
|
-
AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`).get().n;
|
|
3853
|
+
const candidates = db.query(`SELECT COUNT(*) AS n FROM steps WHERE ${UNPRICED_WHERE}`).get().n;
|
|
3607
3854
|
if (candidates === 0)
|
|
3608
3855
|
return { candidates: 0, updated: 0 };
|
|
3609
3856
|
const select = db.query(`SELECT rowid, provider_id, model_id,
|
|
3610
3857
|
input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
|
|
3611
3858
|
FROM steps
|
|
3612
|
-
WHERE
|
|
3613
|
-
AND provider_id IS NOT NULL AND provider_id <> ''
|
|
3614
|
-
AND model_id IS NOT NULL AND model_id <> ''
|
|
3615
|
-
AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0
|
|
3859
|
+
WHERE ${UNPRICED_WHERE} AND rowid > ?
|
|
3616
3860
|
ORDER BY rowid
|
|
3617
3861
|
LIMIT ?`);
|
|
3618
3862
|
const update = db.query("UPDATE steps SET list_cost = ? WHERE rowid = ? AND cost = 0 AND list_cost IS NULL");
|
|
@@ -3622,21 +3866,7 @@ function backfillListCost(db, price) {
|
|
|
3622
3866
|
const rows = select.all(cursor, BACKFILL_BATCH);
|
|
3623
3867
|
if (rows.length === 0)
|
|
3624
3868
|
break;
|
|
3625
|
-
db
|
|
3626
|
-
for (const row of rows) {
|
|
3627
|
-
const estimate = price({ providerID: row.provider_id ?? undefined, modelID: row.model_id ?? undefined }, {
|
|
3628
|
-
input: row.input_tokens ?? 0,
|
|
3629
|
-
output: row.output_tokens ?? 0,
|
|
3630
|
-
reasoning: row.reasoning_tokens ?? 0,
|
|
3631
|
-
cacheRead: row.cache_read ?? 0,
|
|
3632
|
-
cacheWrite: row.cache_write ?? 0
|
|
3633
|
-
});
|
|
3634
|
-
if (estimate === undefined || !Number.isFinite(estimate) || estimate < 0)
|
|
3635
|
-
continue;
|
|
3636
|
-
if (update.run(estimate, row.rowid).changes > 0)
|
|
3637
|
-
updated += 1;
|
|
3638
|
-
}
|
|
3639
|
-
})();
|
|
3869
|
+
updated += backfillBatch(db, rows, price, (estimate, rowid) => update.run(estimate, rowid).changes);
|
|
3640
3870
|
cursor = rows[rows.length - 1].rowid;
|
|
3641
3871
|
if (rows.length < BACKFILL_BATCH)
|
|
3642
3872
|
break;
|
|
@@ -3877,4 +4107,4 @@ scope.onmessage = (event) => {
|
|
|
3877
4107
|
}
|
|
3878
4108
|
};
|
|
3879
4109
|
|
|
3880
|
-
//# debugId=
|
|
4110
|
+
//# debugId=B70242210F34271964756E2164756E21
|