opencode-usage-insights 0.1.3 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONTRIBUTING.md +97 -0
- package/README.md +330 -200
- package/dist/core.d.ts +10 -0
- package/dist/gui-experimental.cjs +8 -0
- package/dist/index.d.ts +29 -4
- package/dist/index.js +3003 -50
- package/dist/index.js.map +17 -8
- package/dist/limits.d.ts +15 -0
- package/dist/panel-build.d.ts +0 -4
- package/dist/panel-data.d.ts +37 -6
- package/dist/panel.d.ts +10 -22
- package/dist/quota-client.d.ts +13 -0
- package/dist/quota.d.ts +114 -0
- package/dist/rpc-client.d.ts +24 -0
- package/dist/rpc.d.ts +1022 -0
- package/dist/rpc.js +294 -0
- package/dist/rpc.js.map +11 -0
- package/dist/service.d.ts +36 -0
- package/dist/sidebar.d.ts +7 -7
- package/dist/stats/db.d.ts +2 -2
- package/dist/stats/maintenance.d.ts +10 -0
- package/dist/stats/queries.d.ts +6 -0
- package/dist/stats-client.d.ts +65 -0
- package/dist/stats-worker.d.ts +1 -0
- package/dist/stats-worker.js +3697 -0
- package/dist/stats-worker.js.map +23 -0
- package/dist/tui.d.ts +22 -10
- package/dist/tui.js +1067 -1604
- package/dist/tui.js.map +14 -14
- package/docs/demo.md +212 -0
- package/docs/images/line.png +0 -0
- package/docs/images/panel-cache.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 +455 -0
- package/package.json +43 -18
package/dist/index.js
CHANGED
|
@@ -2,6 +2,295 @@
|
|
|
2
2
|
// src/index.ts
|
|
3
3
|
import { Plugin } from "@opencode/plugin";
|
|
4
4
|
|
|
5
|
+
// src/rpc.ts
|
|
6
|
+
import { Rpc } from "@opencode/plugin/rpc";
|
|
7
|
+
|
|
8
|
+
// src/limits.ts
|
|
9
|
+
var MAX_PANEL_WIDTH = 200;
|
|
10
|
+
var MAX_TURNS = 50;
|
|
11
|
+
function clampPanelWidth(value) {
|
|
12
|
+
if (!Number.isFinite(value))
|
|
13
|
+
return 20;
|
|
14
|
+
return Math.min(MAX_PANEL_WIDTH, Math.max(20, Math.round(value)));
|
|
15
|
+
}
|
|
16
|
+
function clampTurnsLimit(value) {
|
|
17
|
+
if (!Number.isFinite(value))
|
|
18
|
+
return 1;
|
|
19
|
+
return Math.min(MAX_TURNS, Math.max(1, Math.round(value)));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// src/rpc.ts
|
|
23
|
+
var Tone = { type: "string", enum: ["base", "muted", "warning", "accent"] };
|
|
24
|
+
var PanelRowSchema = {
|
|
25
|
+
type: "object",
|
|
26
|
+
properties: {
|
|
27
|
+
kind: { type: "string", enum: ["model", "session", "period", "provider", "turn", "prune", "wipe"] },
|
|
28
|
+
value: { type: "string", maxLength: 500 },
|
|
29
|
+
variant: { type: "string", maxLength: 200 }
|
|
30
|
+
},
|
|
31
|
+
required: ["kind", "value"],
|
|
32
|
+
additionalProperties: false
|
|
33
|
+
};
|
|
34
|
+
var PanelLineSchema = {
|
|
35
|
+
type: "object",
|
|
36
|
+
properties: {
|
|
37
|
+
text: { type: "string" },
|
|
38
|
+
tone: Tone,
|
|
39
|
+
hint: { type: "boolean" },
|
|
40
|
+
row: PanelRowSchema
|
|
41
|
+
},
|
|
42
|
+
required: ["text"],
|
|
43
|
+
additionalProperties: false
|
|
44
|
+
};
|
|
45
|
+
var PanelSettingsSchema = {
|
|
46
|
+
type: "object",
|
|
47
|
+
properties: {
|
|
48
|
+
view: { type: "string", enum: ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db", "go"] },
|
|
49
|
+
range: { type: "string", enum: ["session", "today", "7d", "30d", "all"] },
|
|
50
|
+
sort: { type: "string", maxLength: 40 },
|
|
51
|
+
sortDesc: { type: "boolean" },
|
|
52
|
+
granularity: { type: "string", enum: ["day", "week", "month"] },
|
|
53
|
+
turnsScope: { type: "string", enum: ["session", "all"] },
|
|
54
|
+
modelID: { type: "string", maxLength: 300 },
|
|
55
|
+
providerID: { type: "string", maxLength: 300 }
|
|
56
|
+
},
|
|
57
|
+
required: ["view", "range", "sort", "sortDesc", "granularity", "turnsScope", "modelID", "providerID"],
|
|
58
|
+
additionalProperties: false
|
|
59
|
+
};
|
|
60
|
+
var TableSizeSchema = {
|
|
61
|
+
type: "object",
|
|
62
|
+
properties: {
|
|
63
|
+
name: { type: "string" },
|
|
64
|
+
rows: { type: "number" }
|
|
65
|
+
},
|
|
66
|
+
required: ["name", "rows"],
|
|
67
|
+
additionalProperties: false
|
|
68
|
+
};
|
|
69
|
+
var DbInfoSchema = {
|
|
70
|
+
type: "object",
|
|
71
|
+
properties: {
|
|
72
|
+
path: { type: "string" },
|
|
73
|
+
bytes: { type: "number" },
|
|
74
|
+
walBytes: { type: "number" },
|
|
75
|
+
schemaVersion: { type: "number" },
|
|
76
|
+
tables: { type: "array", items: TableSizeSchema },
|
|
77
|
+
firstAt: { type: "number" },
|
|
78
|
+
lastAt: { type: "number" },
|
|
79
|
+
removable: {
|
|
80
|
+
type: "array",
|
|
81
|
+
items: {
|
|
82
|
+
type: "object",
|
|
83
|
+
properties: { days: { type: "number" }, steps: { type: "number" } },
|
|
84
|
+
required: ["days", "steps"],
|
|
85
|
+
additionalProperties: false
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
unpriced: { type: "number" }
|
|
89
|
+
},
|
|
90
|
+
required: ["path", "bytes", "schemaVersion", "tables", "removable", "unpriced"],
|
|
91
|
+
additionalProperties: false
|
|
92
|
+
};
|
|
93
|
+
var FilterOptionSchema = {
|
|
94
|
+
type: "object",
|
|
95
|
+
properties: { value: { type: "string" }, steps: { type: "number" } },
|
|
96
|
+
required: ["value", "steps"],
|
|
97
|
+
additionalProperties: false
|
|
98
|
+
};
|
|
99
|
+
var PruneResultSchema = {
|
|
100
|
+
type: "object",
|
|
101
|
+
properties: {
|
|
102
|
+
steps: { type: "number" },
|
|
103
|
+
prompts: { type: "number" },
|
|
104
|
+
events: { type: "number" },
|
|
105
|
+
usage: { type: "number" }
|
|
106
|
+
},
|
|
107
|
+
required: ["steps", "prompts", "events", "usage"],
|
|
108
|
+
additionalProperties: false
|
|
109
|
+
};
|
|
110
|
+
var WipeResultSchema = {
|
|
111
|
+
type: "object",
|
|
112
|
+
properties: {
|
|
113
|
+
steps: { type: "number" },
|
|
114
|
+
prompts: { type: "number" },
|
|
115
|
+
events: { type: "number" },
|
|
116
|
+
usage: { type: "number" },
|
|
117
|
+
sessions: { type: "number" }
|
|
118
|
+
},
|
|
119
|
+
required: ["steps", "prompts", "events", "usage", "sessions"],
|
|
120
|
+
additionalProperties: false
|
|
121
|
+
};
|
|
122
|
+
var BackfillResultSchema = {
|
|
123
|
+
type: "object",
|
|
124
|
+
properties: {
|
|
125
|
+
candidates: { type: "number" },
|
|
126
|
+
updated: { type: "number" }
|
|
127
|
+
},
|
|
128
|
+
required: ["candidates", "updated"],
|
|
129
|
+
additionalProperties: false
|
|
130
|
+
};
|
|
131
|
+
var VacuumResultSchema = {
|
|
132
|
+
type: "object",
|
|
133
|
+
properties: {
|
|
134
|
+
before: { type: "number" },
|
|
135
|
+
after: { type: "number" },
|
|
136
|
+
freed: { type: "number" }
|
|
137
|
+
},
|
|
138
|
+
required: ["before", "after", "freed"],
|
|
139
|
+
additionalProperties: false
|
|
140
|
+
};
|
|
141
|
+
var NoInput = { type: "object", properties: {}, additionalProperties: false };
|
|
142
|
+
var ErrorSchema = {
|
|
143
|
+
type: "object",
|
|
144
|
+
properties: { message: { type: "string", maxLength: 500 } },
|
|
145
|
+
additionalProperties: false
|
|
146
|
+
};
|
|
147
|
+
var errors = {
|
|
148
|
+
busy: ErrorSchema,
|
|
149
|
+
unavailable: ErrorSchema,
|
|
150
|
+
disabled: ErrorSchema,
|
|
151
|
+
invalid: ErrorSchema
|
|
152
|
+
};
|
|
153
|
+
var UsageInsights = Rpc.define({
|
|
154
|
+
id: "usage-insights",
|
|
155
|
+
methods: {
|
|
156
|
+
panel: {
|
|
157
|
+
input: {
|
|
158
|
+
type: "object",
|
|
159
|
+
properties: {
|
|
160
|
+
sessionID: { type: "string", maxLength: 200 },
|
|
161
|
+
settings: PanelSettingsSchema,
|
|
162
|
+
detail: PanelRowSchema,
|
|
163
|
+
width: { type: "number", minimum: 20, maximum: MAX_PANEL_WIDTH },
|
|
164
|
+
busy: { type: "boolean" }
|
|
165
|
+
},
|
|
166
|
+
required: ["sessionID", "settings", "width"],
|
|
167
|
+
additionalProperties: false
|
|
168
|
+
},
|
|
169
|
+
output: {
|
|
170
|
+
type: "object",
|
|
171
|
+
properties: {
|
|
172
|
+
lines: { type: "array", items: PanelLineSchema },
|
|
173
|
+
database: DbInfoSchema
|
|
174
|
+
},
|
|
175
|
+
required: ["lines"],
|
|
176
|
+
additionalProperties: false
|
|
177
|
+
},
|
|
178
|
+
errors
|
|
179
|
+
},
|
|
180
|
+
turns: {
|
|
181
|
+
input: {
|
|
182
|
+
type: "object",
|
|
183
|
+
properties: {
|
|
184
|
+
sessionID: { type: "string", maxLength: 200 },
|
|
185
|
+
limit: { type: "number", minimum: 1, maximum: MAX_TURNS },
|
|
186
|
+
width: { type: "number", minimum: 20, maximum: 120 }
|
|
187
|
+
},
|
|
188
|
+
required: ["sessionID", "limit", "width"],
|
|
189
|
+
additionalProperties: false
|
|
190
|
+
},
|
|
191
|
+
output: {
|
|
192
|
+
type: "object",
|
|
193
|
+
properties: {
|
|
194
|
+
summary: { type: "array", items: PanelLineSchema },
|
|
195
|
+
history: { type: "array", items: PanelLineSchema }
|
|
196
|
+
},
|
|
197
|
+
required: ["summary", "history"],
|
|
198
|
+
additionalProperties: false
|
|
199
|
+
},
|
|
200
|
+
errors
|
|
201
|
+
},
|
|
202
|
+
listCost: {
|
|
203
|
+
input: {
|
|
204
|
+
type: "object",
|
|
205
|
+
properties: { sessionID: { type: "string", maxLength: 200 } },
|
|
206
|
+
required: ["sessionID"],
|
|
207
|
+
additionalProperties: false
|
|
208
|
+
},
|
|
209
|
+
output: {
|
|
210
|
+
type: "object",
|
|
211
|
+
properties: { cost: { type: "number" } },
|
|
212
|
+
required: ["cost"],
|
|
213
|
+
additionalProperties: false
|
|
214
|
+
},
|
|
215
|
+
errors
|
|
216
|
+
},
|
|
217
|
+
filters: {
|
|
218
|
+
input: NoInput,
|
|
219
|
+
output: {
|
|
220
|
+
type: "object",
|
|
221
|
+
properties: {
|
|
222
|
+
models: { type: "array", items: FilterOptionSchema },
|
|
223
|
+
providers: { type: "array", items: FilterOptionSchema }
|
|
224
|
+
},
|
|
225
|
+
required: ["models", "providers"],
|
|
226
|
+
additionalProperties: false
|
|
227
|
+
},
|
|
228
|
+
errors
|
|
229
|
+
},
|
|
230
|
+
dbInfo: {
|
|
231
|
+
input: NoInput,
|
|
232
|
+
output: DbInfoSchema,
|
|
233
|
+
errors
|
|
234
|
+
},
|
|
235
|
+
prune: {
|
|
236
|
+
input: {
|
|
237
|
+
type: "object",
|
|
238
|
+
properties: {
|
|
239
|
+
days: { type: "number", minimum: 1, maximum: 3650 },
|
|
240
|
+
confirm: { type: "boolean", enum: [true] }
|
|
241
|
+
},
|
|
242
|
+
required: ["days", "confirm"],
|
|
243
|
+
additionalProperties: false
|
|
244
|
+
},
|
|
245
|
+
output: PruneResultSchema,
|
|
246
|
+
errors
|
|
247
|
+
},
|
|
248
|
+
wipe: {
|
|
249
|
+
input: {
|
|
250
|
+
type: "object",
|
|
251
|
+
properties: { confirm: { type: "boolean", enum: [true] } },
|
|
252
|
+
required: ["confirm"],
|
|
253
|
+
additionalProperties: false
|
|
254
|
+
},
|
|
255
|
+
output: WipeResultSchema,
|
|
256
|
+
errors
|
|
257
|
+
},
|
|
258
|
+
vacuum: {
|
|
259
|
+
input: {
|
|
260
|
+
type: "object",
|
|
261
|
+
properties: { confirm: { type: "boolean", enum: [true] } },
|
|
262
|
+
required: ["confirm"],
|
|
263
|
+
additionalProperties: false
|
|
264
|
+
},
|
|
265
|
+
output: VacuumResultSchema,
|
|
266
|
+
errors
|
|
267
|
+
},
|
|
268
|
+
backfill: {
|
|
269
|
+
input: {
|
|
270
|
+
type: "object",
|
|
271
|
+
properties: { confirm: { type: "boolean", enum: [true] } },
|
|
272
|
+
required: ["confirm"],
|
|
273
|
+
additionalProperties: false
|
|
274
|
+
},
|
|
275
|
+
output: BackfillResultSchema,
|
|
276
|
+
errors
|
|
277
|
+
}
|
|
278
|
+
},
|
|
279
|
+
events: {
|
|
280
|
+
recorded: {
|
|
281
|
+
schema: {
|
|
282
|
+
type: "object",
|
|
283
|
+
properties: {
|
|
284
|
+
sessionID: { type: "string", maxLength: 200 },
|
|
285
|
+
at: { type: "number" }
|
|
286
|
+
},
|
|
287
|
+
required: ["at"],
|
|
288
|
+
additionalProperties: false
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
});
|
|
293
|
+
|
|
5
294
|
// src/pricing.ts
|
|
6
295
|
function money(value) {
|
|
7
296
|
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
|
|
@@ -1247,10 +1536,13 @@ function turns(db, options) {
|
|
|
1247
1536
|
window += row.streamed_at - row.created_at;
|
|
1248
1537
|
}
|
|
1249
1538
|
const previous = result.length > 0 && result[result.length - 1].sessionID === last.session_id ? result[result.length - 1] : undefined;
|
|
1539
|
+
const endAt = last.completed_at ?? last.created_at ?? last.recorded_at;
|
|
1540
|
+
const firstAt = bucket[0]?.created_at ?? promptAt;
|
|
1250
1541
|
result.push({
|
|
1251
1542
|
sessionID: last.session_id,
|
|
1252
1543
|
promptAt,
|
|
1253
|
-
endAt
|
|
1544
|
+
endAt,
|
|
1545
|
+
durationMs: firstAt !== undefined && endAt > firstAt ? endAt - firstAt : undefined,
|
|
1254
1546
|
promptGapMs: promptAt !== undefined && previous?.promptAt !== undefined ? Math.max(0, promptAt - previous.promptAt) : undefined,
|
|
1255
1547
|
providerID,
|
|
1256
1548
|
modelID,
|
|
@@ -1547,63 +1839,2717 @@ function createRecorder(db, options) {
|
|
|
1547
1839
|
return { handleEvent, pendingFor };
|
|
1548
1840
|
}
|
|
1549
1841
|
|
|
1550
|
-
// src/
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1842
|
+
// src/service.ts
|
|
1843
|
+
import { basename } from "path";
|
|
1844
|
+
|
|
1845
|
+
// src/stats/aggregates.ts
|
|
1846
|
+
var STEP_AT = "COALESCE(created_at, recorded_at)";
|
|
1847
|
+
function normalize(rows, optional) {
|
|
1848
|
+
for (const row of rows) {
|
|
1849
|
+
for (const key of optional)
|
|
1850
|
+
if (row[key] === null)
|
|
1851
|
+
row[key] = undefined;
|
|
1852
|
+
}
|
|
1853
|
+
return rows;
|
|
1854
|
+
}
|
|
1855
|
+
function groupBy(items, key) {
|
|
1856
|
+
const groups = new Map;
|
|
1857
|
+
for (const item of items) {
|
|
1858
|
+
const group = key(item);
|
|
1859
|
+
const list = groups.get(group);
|
|
1860
|
+
if (list !== undefined)
|
|
1861
|
+
list.push(item);
|
|
1862
|
+
else
|
|
1863
|
+
groups.set(group, [item]);
|
|
1864
|
+
}
|
|
1865
|
+
return groups;
|
|
1866
|
+
}
|
|
1867
|
+
var STEP_COLUMNS = `message_id AS messageID, session_id AS sessionID, provider_id AS providerID,
|
|
1868
|
+
model_id AS modelID, variant,
|
|
1869
|
+
COALESCE(input_tokens, 0) AS input, COALESCE(cache_read, 0) AS cached, COALESCE(cache_write, 0) AS cacheWrite,
|
|
1870
|
+
COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, COALESCE(cost, 0) AS cost,
|
|
1871
|
+
COALESCE(list_cost, 0) AS listCost,
|
|
1872
|
+
created_at AS createdAt, streamed_at AS streamedAt, completed_at AS completedAt, ${STEP_AT} AS at`;
|
|
1873
|
+
var STEP_OPTIONAL = ["providerID", "modelID", "variant", "createdAt", "streamedAt", "completedAt"];
|
|
1874
|
+
var PAIR_COLUMNS = STEP_COLUMNS.replace("COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, ", "");
|
|
1875
|
+
function stepRows(db, options) {
|
|
1876
|
+
const filter = buildWhere(options?.range, options?.filters);
|
|
1877
|
+
const rows = db.query(`SELECT ${STEP_COLUMNS} FROM steps ${filter.where}`).all(...filter.params);
|
|
1878
|
+
return normalize(rows, STEP_OPTIONAL);
|
|
1879
|
+
}
|
|
1880
|
+
function cachePairs(db, options) {
|
|
1881
|
+
const filter = buildWhere(options?.range, options?.filters);
|
|
1882
|
+
const rows = normalize(db.query(`SELECT ${PAIR_COLUMNS} FROM steps ${filter.where} ORDER BY session_id, ${STEP_AT}, message_id`).all(...filter.params), STEP_OPTIONAL);
|
|
1883
|
+
const from = options?.range?.from;
|
|
1884
|
+
if (from === undefined || rows.length === 0)
|
|
1885
|
+
return rows;
|
|
1886
|
+
const seek = db.query(`SELECT ${PAIR_COLUMNS} FROM steps
|
|
1887
|
+
WHERE session_id = ? AND COALESCE(created_at, recorded_at) < ?
|
|
1888
|
+
ORDER BY COALESCE(created_at, recorded_at) DESC, message_id DESC LIMIT 1`);
|
|
1889
|
+
for (const sessionID of new Set(rows.map((row) => row.sessionID))) {
|
|
1890
|
+
const boundary = seek.get(sessionID, from);
|
|
1891
|
+
if (boundary === null)
|
|
1892
|
+
continue;
|
|
1893
|
+
const step = normalize([boundary], STEP_OPTIONAL)[0];
|
|
1894
|
+
step.boundary = true;
|
|
1895
|
+
rows.push(step);
|
|
1896
|
+
}
|
|
1897
|
+
rows.sort((left, right) => {
|
|
1898
|
+
if (left.sessionID !== right.sessionID)
|
|
1899
|
+
return left.sessionID < right.sessionID ? -1 : 1;
|
|
1900
|
+
if (left.at !== right.at)
|
|
1901
|
+
return left.at - right.at;
|
|
1902
|
+
return left.messageID < right.messageID ? -1 : left.messageID > right.messageID ? 1 : 0;
|
|
1903
|
+
});
|
|
1904
|
+
return rows;
|
|
1905
|
+
}
|
|
1906
|
+
function message(step) {
|
|
1907
|
+
return {
|
|
1908
|
+
type: "assistant",
|
|
1909
|
+
id: step.messageID,
|
|
1910
|
+
...step.modelID === undefined ? {} : { model: { providerID: step.providerID ?? "", id: step.modelID, ...step.variant === undefined ? {} : { variant: step.variant } } },
|
|
1911
|
+
tokens: { cache: { read: step.cached } },
|
|
1912
|
+
time: {
|
|
1913
|
+
...step.createdAt === undefined ? {} : { created: step.createdAt },
|
|
1914
|
+
...step.streamedAt === undefined ? {} : { streamed: step.streamedAt },
|
|
1915
|
+
...step.completedAt === undefined ? {} : { completed: step.completedAt }
|
|
1916
|
+
}
|
|
1917
|
+
};
|
|
1918
|
+
}
|
|
1919
|
+
function pairsOf(rows) {
|
|
1920
|
+
const pairs = [];
|
|
1921
|
+
for (let index = 1;index < rows.length; index += 1) {
|
|
1922
|
+
const previous = rows[index - 1];
|
|
1923
|
+
const current = rows[index];
|
|
1924
|
+
if (previous.sessionID !== current.sessionID)
|
|
1925
|
+
continue;
|
|
1926
|
+
pairs.push({ previous, current });
|
|
1927
|
+
}
|
|
1928
|
+
return pairs;
|
|
1929
|
+
}
|
|
1930
|
+
function usageOf(steps) {
|
|
1931
|
+
const usage = { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 };
|
|
1932
|
+
for (const step of steps) {
|
|
1933
|
+
usage.steps += 1;
|
|
1934
|
+
usage.input += step.input;
|
|
1935
|
+
usage.cached += step.cached;
|
|
1936
|
+
usage.cacheWrite += step.cacheWrite;
|
|
1937
|
+
usage.output += step.output;
|
|
1938
|
+
usage.reasoning += step.reasoning;
|
|
1939
|
+
usage.cost += step.cost;
|
|
1940
|
+
usage.listCost += step.listCost;
|
|
1941
|
+
}
|
|
1942
|
+
return usage;
|
|
1943
|
+
}
|
|
1944
|
+
function coverageOf(db, options) {
|
|
1945
|
+
const filter = buildWhere(options?.range, options?.filters);
|
|
1946
|
+
const row = db.query(`SELECT COUNT(*) AS steps,
|
|
1947
|
+
COUNT(DISTINCT CASE WHEN model_id IS NOT NULL THEN model_id || '#' || COALESCE(variant, '') END) AS models,
|
|
1948
|
+
COUNT(DISTINCT provider_id) AS providers,
|
|
1949
|
+
COALESCE(SUM(CASE WHEN model_id IS NULL THEN 1 ELSE 0 END), 0) AS missingModel,
|
|
1950
|
+
COALESCE(SUM(CASE WHEN completed_at IS NOT NULL OR finish IS NOT NULL THEN 0 ELSE 1 END), 0) AS unsettled,
|
|
1951
|
+
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,
|
|
1952
|
+
MIN(${STEP_AT}) AS firstAt,
|
|
1953
|
+
MAX(${STEP_AT}) AS lastAt
|
|
1954
|
+
FROM steps ${filter.where}`).get(...filter.params);
|
|
1955
|
+
return {
|
|
1956
|
+
steps: row.steps,
|
|
1957
|
+
models: row.models,
|
|
1958
|
+
providers: row.providers,
|
|
1959
|
+
missingModel: row.missingModel,
|
|
1960
|
+
unsettled: row.unsettled,
|
|
1961
|
+
missingTps: row.missingTps,
|
|
1962
|
+
firstAt: row.firstAt ?? undefined,
|
|
1963
|
+
lastAt: row.lastAt ?? undefined
|
|
1964
|
+
};
|
|
1965
|
+
}
|
|
1966
|
+
function groupedRows(db, options) {
|
|
1967
|
+
const filter = buildWhere(options?.range, options?.filters);
|
|
1968
|
+
const rows = db.query(`SELECT ${STEP_COLUMNS} FROM steps ${filter.where}`).all(...filter.params);
|
|
1969
|
+
return normalize(rows, STEP_OPTIONAL);
|
|
1970
|
+
}
|
|
1971
|
+
function timingOf(step) {
|
|
1972
|
+
const wall = step.createdAt !== undefined && step.completedAt !== undefined ? Math.max(0, step.completedAt - step.createdAt) : undefined;
|
|
1973
|
+
const stream = step.createdAt !== undefined && step.streamedAt !== undefined && step.streamedAt > step.createdAt ? step.streamedAt - step.createdAt : undefined;
|
|
1974
|
+
return { wall, stream, tps: tokensPerSecond(step.output + step.reasoning, step.createdAt, step.streamedAt) };
|
|
1975
|
+
}
|
|
1976
|
+
function timingRows(db, options) {
|
|
1977
|
+
return groupedRows(db, options);
|
|
1978
|
+
}
|
|
1979
|
+
function latencyOf(rows) {
|
|
1980
|
+
const wall = [];
|
|
1981
|
+
const stream = [];
|
|
1982
|
+
const tps = [];
|
|
1983
|
+
for (const step of rows) {
|
|
1984
|
+
const timing = timingOf(step);
|
|
1985
|
+
if (timing.wall !== undefined)
|
|
1986
|
+
wall.push(timing.wall);
|
|
1987
|
+
if (timing.stream !== undefined)
|
|
1988
|
+
stream.push(timing.stream);
|
|
1989
|
+
if (timing.tps !== undefined)
|
|
1990
|
+
tps.push(timing.tps);
|
|
1991
|
+
}
|
|
1992
|
+
return { wall: latencyStats(wall), stream: latencyStats(stream), tps: latencyStats(tps) };
|
|
1993
|
+
}
|
|
1994
|
+
function latencyGroupsOf(rows, by) {
|
|
1995
|
+
const key = (step) => by === "model" ? modelKey(step.modelID ?? "(unknown)", step.variant) : step.providerID ?? "(unknown)";
|
|
1996
|
+
const groups = [];
|
|
1997
|
+
for (const [group, steps] of groupBy(rows, key)) {
|
|
1998
|
+
const wall = [];
|
|
1999
|
+
const stream = [];
|
|
2000
|
+
const tps = [];
|
|
2001
|
+
for (const step of steps) {
|
|
2002
|
+
const timing = timingOf(step);
|
|
2003
|
+
if (timing.wall !== undefined)
|
|
2004
|
+
wall.push(timing.wall);
|
|
2005
|
+
if (timing.stream !== undefined)
|
|
2006
|
+
stream.push(timing.stream);
|
|
2007
|
+
if (timing.tps !== undefined)
|
|
2008
|
+
tps.push(timing.tps);
|
|
2009
|
+
}
|
|
2010
|
+
const [modelID, variant] = group.split("#");
|
|
2011
|
+
groups.push({
|
|
2012
|
+
key: group,
|
|
2013
|
+
label: by === "model" ? variant === undefined || variant === "" ? modelID : `${modelID} ${variant}` : group,
|
|
2014
|
+
count: steps.length,
|
|
2015
|
+
usage: usageOf(steps),
|
|
2016
|
+
wall: latencyStats(wall),
|
|
2017
|
+
stream: latencyStats(stream),
|
|
2018
|
+
tps: latencyStats(tps)
|
|
2019
|
+
});
|
|
2020
|
+
}
|
|
2021
|
+
return groups.sort((left, right) => right.count - left.count || left.key.localeCompare(right.key));
|
|
2022
|
+
}
|
|
2023
|
+
var EMPTY_CACHE = { steps: 0, input: 0, cached: 0, cacheWrite: 0, prompt: 0, hit: undefined, hitP50: undefined };
|
|
2024
|
+
function cacheStatsOfSteps(steps) {
|
|
2025
|
+
let input = 0;
|
|
2026
|
+
let cached = 0;
|
|
2027
|
+
let cacheWrite = 0;
|
|
2028
|
+
const ratios = [];
|
|
2029
|
+
for (const step of steps) {
|
|
2030
|
+
input += step.input;
|
|
2031
|
+
cached += step.cached;
|
|
2032
|
+
cacheWrite += step.cacheWrite;
|
|
2033
|
+
const prompt = step.input + step.cached + step.cacheWrite;
|
|
2034
|
+
if (prompt > 0)
|
|
2035
|
+
ratios.push(step.cached / prompt);
|
|
2036
|
+
}
|
|
2037
|
+
const prompt = input + cached + cacheWrite;
|
|
2038
|
+
return { steps: steps.length, input, cached, cacheWrite, prompt, hit: prompt > 0 ? cached / prompt : undefined, hitP50: percentile(ratios, 50) };
|
|
2039
|
+
}
|
|
2040
|
+
function cacheStatsOf(db, options) {
|
|
2041
|
+
const rows = stepRows(db, options);
|
|
2042
|
+
return rows.length === 0 ? EMPTY_CACHE : cacheStatsOfSteps(rows);
|
|
2043
|
+
}
|
|
2044
|
+
function cacheStatsByModel(rows) {
|
|
2045
|
+
const out = [];
|
|
2046
|
+
const inRange = rows.filter((row) => row.boundary !== true);
|
|
2047
|
+
for (const [, group] of groupBy(inRange, (row) => modelKey(row.modelID ?? "(unknown)", row.variant))) {
|
|
2048
|
+
out.push({ modelID: group[0].modelID ?? "(unknown)", variant: group[0].variant, cache: cacheStatsOfSteps(group) });
|
|
2049
|
+
}
|
|
2050
|
+
return out.sort((left, right) => right.cache.cached - left.cache.cached || left.modelID.localeCompare(right.modelID));
|
|
2051
|
+
}
|
|
2052
|
+
function switchesOf(rows) {
|
|
2053
|
+
const perModel = new Map;
|
|
2054
|
+
const totals = { pairs: 0, changes: 0, cacheLost: 0, cacheLostEvents: 0 };
|
|
2055
|
+
for (const { previous, current } of pairsOf(rows)) {
|
|
2056
|
+
if (previous.modelID === undefined || current.modelID === undefined)
|
|
2057
|
+
continue;
|
|
2058
|
+
const key = modelKey(current.modelID, current.variant);
|
|
2059
|
+
const row = perModel.get(key) ?? {
|
|
2060
|
+
modelID: current.modelID,
|
|
2061
|
+
variant: current.variant,
|
|
2062
|
+
steps: 0,
|
|
2063
|
+
pairs: 0,
|
|
2064
|
+
changes: 0,
|
|
2065
|
+
modelChanges: 0,
|
|
2066
|
+
providerChanges: 0,
|
|
2067
|
+
cacheLost: 0,
|
|
2068
|
+
cacheLostEvents: 0
|
|
2069
|
+
};
|
|
2070
|
+
row.steps += 1;
|
|
2071
|
+
row.pairs += 1;
|
|
2072
|
+
totals.pairs += 1;
|
|
2073
|
+
const modelChanged = key !== modelKey(previous.modelID, previous.variant);
|
|
2074
|
+
const providerChanged = previous.providerID !== undefined && current.providerID !== undefined && previous.providerID !== current.providerID;
|
|
2075
|
+
if (modelChanged)
|
|
2076
|
+
row.modelChanges += 1;
|
|
2077
|
+
if (providerChanged)
|
|
2078
|
+
row.providerChanges += 1;
|
|
2079
|
+
if (modelChanged || providerChanged) {
|
|
2080
|
+
row.changes += 1;
|
|
2081
|
+
totals.changes += 1;
|
|
2082
|
+
const lost = cacheDrop(message(previous), message(current), "model");
|
|
2083
|
+
if (lost !== undefined) {
|
|
2084
|
+
row.cacheLost += lost;
|
|
2085
|
+
row.cacheLostEvents += 1;
|
|
2086
|
+
totals.cacheLost += lost;
|
|
2087
|
+
totals.cacheLostEvents += 1;
|
|
1574
2088
|
}
|
|
1575
|
-
}
|
|
2089
|
+
}
|
|
2090
|
+
perModel.set(key, row);
|
|
1576
2091
|
}
|
|
1577
2092
|
return {
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
return table === undefined ? undefined : costOf(table, ref, tokens);
|
|
1581
|
-
},
|
|
1582
|
-
refresh
|
|
2093
|
+
rows: [...perModel.values()].sort((left, right) => right.changes - left.changes || right.steps - left.steps || left.modelID.localeCompare(right.modelID)),
|
|
2094
|
+
totals
|
|
1583
2095
|
};
|
|
1584
2096
|
}
|
|
1585
|
-
|
|
2097
|
+
var GAP_BUCKETS = [
|
|
2098
|
+
["<1m", 0, 60000],
|
|
2099
|
+
["1\u20135m", 60000, 5 * 60000],
|
|
2100
|
+
["5\u201315m", 5 * 60000, 15 * 60000],
|
|
2101
|
+
["15\u201360m", 15 * 60000, 60 * 60000],
|
|
2102
|
+
["1\u20136h", 60 * 60000, 6 * 60 * 60000],
|
|
2103
|
+
[">6h", 6 * 60 * 60000, undefined]
|
|
2104
|
+
];
|
|
2105
|
+
function bucketFor(gapMs) {
|
|
2106
|
+
const index = GAP_BUCKETS.findIndex(([, from, to]) => gapMs >= from && (to === undefined || gapMs < to));
|
|
2107
|
+
return index === -1 ? GAP_BUCKETS.length - 1 : index;
|
|
2108
|
+
}
|
|
2109
|
+
function gapReportOf(rows) {
|
|
2110
|
+
const buckets = GAP_BUCKETS.map(([label]) => ({ label, samples: 0, retained: 0, drops: 0, lostTokens: 0, retainedRatio: undefined }));
|
|
2111
|
+
const providers = new Map;
|
|
2112
|
+
let samples = 0;
|
|
2113
|
+
for (const { previous, current } of pairsOf(rows)) {
|
|
2114
|
+
if (previous.modelID === undefined || current.modelID === undefined)
|
|
2115
|
+
continue;
|
|
2116
|
+
if (modelKey(previous.modelID, previous.variant) !== modelKey(current.modelID, current.variant))
|
|
2117
|
+
continue;
|
|
2118
|
+
if ((previous.providerID ?? "") !== (current.providerID ?? ""))
|
|
2119
|
+
continue;
|
|
2120
|
+
const gap = stepGap(message(previous), message(current));
|
|
2121
|
+
if (gap === undefined)
|
|
2122
|
+
continue;
|
|
2123
|
+
const lost = cacheDrop(message(previous), message(current));
|
|
2124
|
+
const bucket = buckets[bucketFor(gap)];
|
|
2125
|
+
bucket.samples += 1;
|
|
2126
|
+
samples += 1;
|
|
2127
|
+
if (lost === undefined)
|
|
2128
|
+
bucket.retained += 1;
|
|
2129
|
+
else {
|
|
2130
|
+
bucket.drops += 1;
|
|
2131
|
+
bucket.lostTokens += lost;
|
|
2132
|
+
}
|
|
2133
|
+
const provider = current.providerID ?? previous.providerID ?? "(unknown)";
|
|
2134
|
+
const row = providers.get(provider) ?? { provider, samples: 0, retained: 0, drops: 0, lostTokens: 0, retainedRatio: undefined };
|
|
2135
|
+
row.samples += 1;
|
|
2136
|
+
if (lost === undefined)
|
|
2137
|
+
row.retained += 1;
|
|
2138
|
+
else {
|
|
2139
|
+
row.drops += 1;
|
|
2140
|
+
row.lostTokens += lost;
|
|
2141
|
+
}
|
|
2142
|
+
providers.set(provider, row);
|
|
2143
|
+
}
|
|
2144
|
+
for (const bucket of buckets)
|
|
2145
|
+
bucket.retainedRatio = bucket.samples > 0 ? bucket.retained / bucket.samples : undefined;
|
|
2146
|
+
for (const row of providers.values())
|
|
2147
|
+
row.retainedRatio = row.samples > 0 ? row.retained / row.samples : undefined;
|
|
2148
|
+
return {
|
|
2149
|
+
buckets,
|
|
2150
|
+
providers: [...providers.values()].sort((left, right) => right.samples - left.samples || left.provider.localeCompare(right.provider)),
|
|
2151
|
+
samples
|
|
2152
|
+
};
|
|
2153
|
+
}
|
|
2154
|
+
function ttlEvidenceOf(rows) {
|
|
2155
|
+
const evidence = new Map;
|
|
2156
|
+
for (const { previous, current } of pairsOf(rows)) {
|
|
2157
|
+
if (previous.modelID === undefined || current.modelID === undefined)
|
|
2158
|
+
continue;
|
|
2159
|
+
const key = `${current.providerID ?? ""}/${current.modelID}`;
|
|
2160
|
+
const before = `${previous.providerID ?? ""}/${previous.modelID}#${previous.variant ?? ""}`;
|
|
2161
|
+
const after = `${current.providerID ?? ""}/${current.modelID}#${current.variant ?? ""}`;
|
|
2162
|
+
if (before !== after)
|
|
2163
|
+
continue;
|
|
2164
|
+
const row = evidence.get(key) ?? {
|
|
2165
|
+
providerID: current.providerID ?? "(unknown)",
|
|
2166
|
+
modelID: current.modelID,
|
|
2167
|
+
samples: 0,
|
|
2168
|
+
maxHitGapMs: undefined,
|
|
2169
|
+
minDropGapMs: undefined
|
|
2170
|
+
};
|
|
2171
|
+
row.samples += 1;
|
|
2172
|
+
const gapMs = stepGap(message(previous), message(current));
|
|
2173
|
+
if (gapMs !== undefined) {
|
|
2174
|
+
const lost = cacheDrop(message(previous), message(current));
|
|
2175
|
+
if (lost === undefined)
|
|
2176
|
+
row.maxHitGapMs = row.maxHitGapMs === undefined ? gapMs : Math.max(row.maxHitGapMs, gapMs);
|
|
2177
|
+
else
|
|
2178
|
+
row.minDropGapMs = row.minDropGapMs === undefined ? gapMs : Math.min(row.minDropGapMs, gapMs);
|
|
2179
|
+
}
|
|
2180
|
+
evidence.set(key, row);
|
|
2181
|
+
}
|
|
2182
|
+
return [...evidence.values()].sort((left, right) => right.samples - left.samples || `${left.providerID}/${left.modelID}`.localeCompare(`${right.providerID}/${right.modelID}`));
|
|
2183
|
+
}
|
|
2184
|
+
function cacheDropsOf(db, rows, options) {
|
|
2185
|
+
const ttlHint = options?.ttlHintMs ?? DEFAULT_TTL_HINT_MS;
|
|
2186
|
+
const losses = [];
|
|
2187
|
+
for (const { previous, current } of pairsOf(rows)) {
|
|
2188
|
+
const tokens = cacheDrop(message(previous), message(current), "model");
|
|
2189
|
+
if (tokens === undefined)
|
|
2190
|
+
continue;
|
|
2191
|
+
losses.push({ previous, current, tokens, gapMs: stepGap(message(previous), message(current)) });
|
|
2192
|
+
}
|
|
2193
|
+
if (losses.length === 0)
|
|
2194
|
+
return [];
|
|
2195
|
+
const compactions = new Map;
|
|
2196
|
+
const sessionIDs = [...new Set(losses.map((loss) => loss.current.sessionID))];
|
|
2197
|
+
const events = db.query(`SELECT session_id, at FROM events
|
|
2198
|
+
WHERE kind = 'compaction' AND at IS NOT NULL AND session_id IN (${sessionIDs.map(() => "?").join(", ")})
|
|
2199
|
+
ORDER BY at`).all(...sessionIDs);
|
|
2200
|
+
for (const event of events) {
|
|
2201
|
+
const list = compactions.get(event.session_id);
|
|
2202
|
+
if (list !== undefined)
|
|
2203
|
+
list.push(event.at);
|
|
2204
|
+
else
|
|
2205
|
+
compactions.set(event.session_id, [event.at]);
|
|
2206
|
+
}
|
|
2207
|
+
return losses.map((loss) => {
|
|
2208
|
+
const ended = loss.previous.completedAt ?? loss.previous.streamedAt ?? loss.previous.createdAt;
|
|
2209
|
+
const compacted = (compactions.get(loss.current.sessionID) ?? []).some((time) => ended !== undefined && time >= ended && time <= loss.current.at);
|
|
2210
|
+
const reason = compacted ? "compaction" : loss.gapMs !== undefined && loss.gapMs >= ttlHint ? "expired" : "unknown";
|
|
2211
|
+
return {
|
|
2212
|
+
sessionID: loss.current.sessionID,
|
|
2213
|
+
messageID: loss.current.messageID,
|
|
2214
|
+
providerID: loss.current.providerID,
|
|
2215
|
+
modelID: loss.current.modelID,
|
|
2216
|
+
variant: loss.current.variant,
|
|
2217
|
+
at: loss.current.at,
|
|
2218
|
+
tokens: loss.tokens,
|
|
2219
|
+
gapMs: loss.gapMs,
|
|
2220
|
+
prevCached: loss.previous.cached,
|
|
2221
|
+
reason
|
|
2222
|
+
};
|
|
2223
|
+
}).sort((left, right) => left.at - right.at);
|
|
2224
|
+
}
|
|
2225
|
+
function groupValues(steps) {
|
|
2226
|
+
const wall = [];
|
|
2227
|
+
const tps = [];
|
|
2228
|
+
for (const step of steps) {
|
|
2229
|
+
const timing = timingOf(step);
|
|
2230
|
+
if (timing.wall !== undefined)
|
|
2231
|
+
wall.push(timing.wall);
|
|
2232
|
+
if (timing.tps !== undefined)
|
|
2233
|
+
tps.push(timing.tps);
|
|
2234
|
+
}
|
|
2235
|
+
return { cache: cacheStatsOfSteps(steps), tps: latencyStats(tps).p50, wall: latencyStats(wall).p50 };
|
|
2236
|
+
}
|
|
2237
|
+
function providerOf(steps, models) {
|
|
2238
|
+
const values = groupValues(steps);
|
|
2239
|
+
let firstAt;
|
|
2240
|
+
let lastAt;
|
|
2241
|
+
for (const step of steps) {
|
|
2242
|
+
if (firstAt === undefined || step.at < firstAt)
|
|
2243
|
+
firstAt = step.at;
|
|
2244
|
+
if (lastAt === undefined || step.at > lastAt)
|
|
2245
|
+
lastAt = step.at;
|
|
2246
|
+
}
|
|
2247
|
+
return {
|
|
2248
|
+
provider: steps[0].providerID,
|
|
2249
|
+
models: models.split("\x00"),
|
|
2250
|
+
share: 0,
|
|
2251
|
+
usage: usageOf(steps),
|
|
2252
|
+
cache: values.cache,
|
|
2253
|
+
tps: values.tps,
|
|
2254
|
+
wall: values.wall,
|
|
2255
|
+
firstAt,
|
|
2256
|
+
lastAt
|
|
2257
|
+
};
|
|
2258
|
+
}
|
|
2259
|
+
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");
|
|
2260
|
+
function providerSummaryOf(rows) {
|
|
2261
|
+
const out = [];
|
|
2262
|
+
for (const steps of groupBy(rows, (step) => step.providerID ?? "").values()) {
|
|
2263
|
+
const summary = providerOf(steps, modelNames(steps));
|
|
2264
|
+
out.push({ ...summary, share: rows.length === 0 ? 0 : steps.length / rows.length });
|
|
2265
|
+
}
|
|
2266
|
+
return out.sort((left, right) => right.usage.steps - left.usage.steps || (left.provider ?? "").localeCompare(right.provider ?? ""));
|
|
2267
|
+
}
|
|
2268
|
+
function providerBreakdownOf(rows) {
|
|
2269
|
+
const out = [];
|
|
2270
|
+
for (const [model, modelRows] of groupBy(rows, (step) => modelKey(step.modelID ?? "(unknown)", step.variant))) {
|
|
2271
|
+
for (const steps of groupBy(modelRows, (step) => step.providerID ?? "").values()) {
|
|
2272
|
+
const [modelID, variant] = [model.slice(0, model.indexOf("#")), model.slice(model.indexOf("#") + 1)];
|
|
2273
|
+
out.push({
|
|
2274
|
+
...providerOf(steps, modelNames(steps)),
|
|
2275
|
+
modelID,
|
|
2276
|
+
variant: variant === "" ? undefined : variant,
|
|
2277
|
+
share: steps.length / modelRows.length
|
|
2278
|
+
});
|
|
2279
|
+
}
|
|
2280
|
+
}
|
|
2281
|
+
return out.sort((left, right) => right.usage.steps - left.usage.steps || right.cache.cached - left.cache.cached);
|
|
2282
|
+
}
|
|
2283
|
+
function isoWeek(date) {
|
|
2284
|
+
const monday = new Date(date.getFullYear(), date.getMonth(), date.getDate());
|
|
2285
|
+
monday.setDate(monday.getDate() - (monday.getDay() + 6) % 7);
|
|
2286
|
+
const thursday = new Date(monday.getFullYear(), monday.getMonth(), monday.getDate() + 3);
|
|
2287
|
+
const firstThursday = new Date(thursday.getFullYear(), 0, 4);
|
|
2288
|
+
firstThursday.setDate(firstThursday.getDate() - (firstThursday.getDay() + 6) % 7 + 3);
|
|
2289
|
+
const week = 1 + Math.round((thursday.getTime() - firstThursday.getTime()) / (7 * 24 * 60 * 60 * 1000));
|
|
2290
|
+
return { year: thursday.getFullYear(), week, monday };
|
|
2291
|
+
}
|
|
2292
|
+
function periodEnd(at, granularity) {
|
|
2293
|
+
const date = new Date(at);
|
|
2294
|
+
if (granularity === "month")
|
|
2295
|
+
return new Date(date.getFullYear(), date.getMonth() + 1, 1).getTime();
|
|
2296
|
+
if (granularity === "week")
|
|
2297
|
+
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 7).getTime();
|
|
2298
|
+
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1).getTime();
|
|
2299
|
+
}
|
|
2300
|
+
function periodStart(at, granularity) {
|
|
2301
|
+
const date = new Date(at);
|
|
2302
|
+
const pad = (value) => String(value).padStart(2, "0");
|
|
2303
|
+
if (granularity === "month") {
|
|
2304
|
+
const start = new Date(date.getFullYear(), date.getMonth(), 1);
|
|
2305
|
+
return { key: `${start.getFullYear()}-${pad(start.getMonth() + 1)}`, label: `${start.getFullYear()}-${pad(start.getMonth() + 1)}`, start: start.getTime() };
|
|
2306
|
+
}
|
|
2307
|
+
if (granularity === "week") {
|
|
2308
|
+
const { year, week, monday } = isoWeek(date);
|
|
2309
|
+
return { key: `${year}-W${pad(week)}`, label: `${year}-W${pad(week)}`, start: monday.getTime() };
|
|
2310
|
+
}
|
|
2311
|
+
const start = new Date(date.getFullYear(), date.getMonth(), date.getDate());
|
|
2312
|
+
const key = `${start.getFullYear()}-${pad(start.getMonth() + 1)}-${pad(start.getDate())}`;
|
|
2313
|
+
return { key, label: key, start: start.getTime() };
|
|
2314
|
+
}
|
|
2315
|
+
function periodsOf(rows, granularity, otherRows = []) {
|
|
2316
|
+
const byKey = new Map;
|
|
2317
|
+
for (const [key, steps] of groupBy(rows, (step) => periodStart(step.at, granularity).key)) {
|
|
2318
|
+
const period = periodStart(steps[0].at, granularity);
|
|
2319
|
+
byKey.set(key, {
|
|
2320
|
+
key,
|
|
2321
|
+
label: period.label,
|
|
2322
|
+
at: period.start,
|
|
2323
|
+
steps: steps.length,
|
|
2324
|
+
sessions: new Set(steps.map((step) => step.sessionID)).size,
|
|
2325
|
+
usage: usageOf(steps),
|
|
2326
|
+
cache: cacheStatsOfSteps(steps)
|
|
2327
|
+
});
|
|
2328
|
+
}
|
|
2329
|
+
for (const [key, group] of groupBy(otherRows, (row) => periodStart(row.at, granularity).key)) {
|
|
2330
|
+
const cost = group.reduce((sum, row) => sum + row.cost, 0);
|
|
2331
|
+
const existing = byKey.get(key);
|
|
2332
|
+
if (existing !== undefined) {
|
|
2333
|
+
existing.usage.cost += cost;
|
|
2334
|
+
existing.otherCost = (existing.otherCost ?? 0) + cost;
|
|
2335
|
+
continue;
|
|
2336
|
+
}
|
|
2337
|
+
const period = periodStart(group[0].at, granularity);
|
|
2338
|
+
byKey.set(key, {
|
|
2339
|
+
key,
|
|
2340
|
+
label: period.label,
|
|
2341
|
+
at: period.start,
|
|
2342
|
+
steps: 0,
|
|
2343
|
+
sessions: new Set(group.map((row) => row.sessionID)).size,
|
|
2344
|
+
usage: { ...usageOf([]), cost },
|
|
2345
|
+
cache: cacheStatsOfSteps([]),
|
|
2346
|
+
otherCost: cost
|
|
2347
|
+
});
|
|
2348
|
+
}
|
|
2349
|
+
return [...byKey.values()].sort((left, right) => left.at - right.at);
|
|
2350
|
+
}
|
|
2351
|
+
|
|
2352
|
+
// src/quota.ts
|
|
2353
|
+
var QUOTA_VIEW = "go";
|
|
2354
|
+
var QUOTA_POLL_MS = 60000;
|
|
2355
|
+
var DEFAULT_QUOTA_NAME = "OpenCode Go";
|
|
2356
|
+
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
2357
|
+
var MIN_FORECAST_ELAPSED_MS = 30 * 60 * 1000;
|
|
2358
|
+
function quotaNameOf(explicit, providerName) {
|
|
2359
|
+
const custom = explicit?.trim();
|
|
2360
|
+
if (custom !== undefined && custom !== "")
|
|
2361
|
+
return custom;
|
|
2362
|
+
const provider = providerName?.trim();
|
|
2363
|
+
if (provider !== undefined && provider !== "")
|
|
2364
|
+
return provider;
|
|
2365
|
+
return DEFAULT_QUOTA_NAME;
|
|
2366
|
+
}
|
|
2367
|
+
function finite2(value) {
|
|
2368
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
2369
|
+
}
|
|
2370
|
+
function clamp(value, minimum, maximum) {
|
|
2371
|
+
return Math.min(maximum, Math.max(minimum, value));
|
|
2372
|
+
}
|
|
2373
|
+
function previousCycleStart(endAt) {
|
|
2374
|
+
if (!finite2(endAt))
|
|
2375
|
+
return endAt;
|
|
2376
|
+
const end = new Date(endAt);
|
|
2377
|
+
const year = end.getUTCFullYear();
|
|
2378
|
+
const month = end.getUTCMonth();
|
|
2379
|
+
const day = end.getUTCDate();
|
|
2380
|
+
const start = new Date(Date.UTC(year, month - 1, 1, end.getUTCHours(), end.getUTCMinutes(), end.getUTCSeconds(), end.getUTCMilliseconds()));
|
|
2381
|
+
const lastDay = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + 1, 0)).getUTCDate();
|
|
2382
|
+
start.setUTCDate(Math.min(day, lastDay));
|
|
2383
|
+
return start.getTime();
|
|
2384
|
+
}
|
|
2385
|
+
function forecastMonthly(meter, now) {
|
|
2386
|
+
const endAt = finite2(meter.resetsAt) ? meter.resetsAt : now;
|
|
2387
|
+
const startAt = previousCycleStart(endAt);
|
|
2388
|
+
const total = Math.max(1, endAt - startAt);
|
|
2389
|
+
const elapsedMs = clamp(now - startAt, 0, total);
|
|
2390
|
+
const remainingMs = Math.max(0, endAt - now);
|
|
2391
|
+
const percent = clamp(finite2(meter.percent) ? meter.percent : 0, 0, 100);
|
|
2392
|
+
const reached = meter.limited === true || percent >= 100;
|
|
2393
|
+
const ratePerDay = !reached && elapsedMs >= MIN_FORECAST_ELAPSED_MS && percent > 0 ? percent / (elapsedMs / DAY_MS) : 0;
|
|
2394
|
+
const projectedPercent = reached ? 100 : ratePerDay > 0 ? percent + ratePerDay * (remainingMs / DAY_MS) : percent;
|
|
2395
|
+
const rawExhaustAt = !reached && ratePerDay > 0 && percent < 100 ? now + (100 - percent) / ratePerDay * DAY_MS : undefined;
|
|
2396
|
+
const exhaustAt = rawExhaustAt !== undefined && rawExhaustAt < endAt ? rawExhaustAt : undefined;
|
|
2397
|
+
const willExhaust = exhaustAt !== undefined;
|
|
2398
|
+
const available = !reached && now < endAt && (elapsedMs >= MIN_FORECAST_ELAPSED_MS || percent === 0);
|
|
2399
|
+
return {
|
|
2400
|
+
startAt,
|
|
2401
|
+
endAt,
|
|
2402
|
+
elapsedMs,
|
|
2403
|
+
remainingMs,
|
|
2404
|
+
ratePerDay,
|
|
2405
|
+
projectedPercent,
|
|
2406
|
+
...exhaustAt !== undefined ? { exhaustAt } : {},
|
|
2407
|
+
reached,
|
|
2408
|
+
available,
|
|
2409
|
+
willExhaust
|
|
2410
|
+
};
|
|
2411
|
+
}
|
|
2412
|
+
function quotaBar(percent, width = 10) {
|
|
2413
|
+
const value = clamp(finite2(percent) ? percent : 0, 0, 100);
|
|
2414
|
+
const cells = Math.max(1, Math.round(width));
|
|
2415
|
+
const filled = value >= 100 ? cells : value <= 0 ? 0 : Math.min(cells, Math.max(1, Math.round(value / 100 * cells)));
|
|
2416
|
+
return `[${"#".repeat(filled)}${"-".repeat(cells - filled)}]`;
|
|
2417
|
+
}
|
|
2418
|
+
function formatRenewal(at, timeZone) {
|
|
2419
|
+
if (!finite2(at))
|
|
2420
|
+
return "\u2013";
|
|
1586
2421
|
try {
|
|
1587
|
-
return
|
|
2422
|
+
return new Intl.DateTimeFormat("en-GB", {
|
|
2423
|
+
day: "2-digit",
|
|
2424
|
+
month: "short",
|
|
2425
|
+
year: "numeric",
|
|
2426
|
+
hour: "2-digit",
|
|
2427
|
+
minute: "2-digit",
|
|
2428
|
+
hour12: false,
|
|
2429
|
+
...timeZone !== undefined ? { timeZone } : {}
|
|
2430
|
+
}).format(new Date(at)).replace(/,/g, "");
|
|
1588
2431
|
} catch {
|
|
1589
|
-
return;
|
|
2432
|
+
return "\u2013";
|
|
1590
2433
|
}
|
|
1591
2434
|
}
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
}
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
2435
|
+
function formatRenewalCompact(at, timeZone) {
|
|
2436
|
+
if (!finite2(at))
|
|
2437
|
+
return "\u2013";
|
|
2438
|
+
try {
|
|
2439
|
+
return new Intl.DateTimeFormat("en-GB", {
|
|
2440
|
+
day: "2-digit",
|
|
2441
|
+
month: "short",
|
|
2442
|
+
hour: "2-digit",
|
|
2443
|
+
minute: "2-digit",
|
|
2444
|
+
hour12: false,
|
|
2445
|
+
...timeZone !== undefined ? { timeZone } : {}
|
|
2446
|
+
}).format(new Date(at)).replace(/,/g, "");
|
|
2447
|
+
} catch {
|
|
2448
|
+
return "\u2013";
|
|
2449
|
+
}
|
|
2450
|
+
}
|
|
2451
|
+
function formatCountdown(at, now) {
|
|
2452
|
+
const remaining = at - now;
|
|
2453
|
+
if (!finite2(remaining))
|
|
2454
|
+
return "\u2013";
|
|
2455
|
+
if (remaining <= 0)
|
|
2456
|
+
return "due";
|
|
2457
|
+
return formatDuration(remaining);
|
|
2458
|
+
}
|
|
2459
|
+
function quotaStatus(quota) {
|
|
2460
|
+
const limited = [];
|
|
2461
|
+
if (quota.rolling.limited || quota.rolling.percent >= 100)
|
|
2462
|
+
limited.push("5-hour");
|
|
2463
|
+
if (quota.weekly.limited || quota.weekly.percent >= 100)
|
|
2464
|
+
limited.push("weekly");
|
|
2465
|
+
if (quota.monthly.limited || quota.monthly.percent >= 100)
|
|
2466
|
+
limited.push("monthly");
|
|
2467
|
+
return limited.length === 0 ? "active" : `${limited.join(" / ")} limit reached`;
|
|
2468
|
+
}
|
|
2469
|
+
|
|
2470
|
+
// src/panel-data.ts
|
|
2471
|
+
var PANEL_NAME = "usage-insights";
|
|
2472
|
+
var PANEL_VIEWS = ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db"];
|
|
2473
|
+
var CLIENT_VIEWS = [...PANEL_VIEWS, QUOTA_VIEW];
|
|
2474
|
+
var RANGE_KEYS = ["session", "today", "7d", "30d", "all"];
|
|
2475
|
+
var GRANULARITIES = ["day", "week", "month"];
|
|
2476
|
+
var SORT_KEYS = {
|
|
2477
|
+
models: ["steps", "cached", "hit", "out", "cost"],
|
|
2478
|
+
providers: ["steps", "cached", "hit", "cost", "share", "tps"],
|
|
2479
|
+
latency: ["n", "tps", "wall"],
|
|
2480
|
+
sessions: ["last", "steps", "cached", "cost"],
|
|
2481
|
+
turns: ["time", "cost", "tokens"]
|
|
2482
|
+
};
|
|
2483
|
+
function sortKeys(view) {
|
|
2484
|
+
return SORT_KEYS[view] ?? [];
|
|
2485
|
+
}
|
|
2486
|
+
function defaultSort(view) {
|
|
2487
|
+
return sortKeys(view)[0] ?? "";
|
|
2488
|
+
}
|
|
2489
|
+
function nextSort(view, current, step) {
|
|
2490
|
+
const keys = sortKeys(view);
|
|
2491
|
+
if (keys.length === 0)
|
|
2492
|
+
return current;
|
|
2493
|
+
const index = keys.indexOf(current);
|
|
2494
|
+
if (index === -1)
|
|
2495
|
+
return keys[0];
|
|
2496
|
+
return keys[(index + step + keys.length) % keys.length];
|
|
2497
|
+
}
|
|
2498
|
+
function parseArgs(input, views = CLIENT_VIEWS) {
|
|
2499
|
+
const parsed = {};
|
|
2500
|
+
for (const token of (input ?? "").split(/\s+/)) {
|
|
2501
|
+
const value = token.trim().toLowerCase();
|
|
2502
|
+
if (value === "")
|
|
2503
|
+
continue;
|
|
2504
|
+
if (views.includes(value))
|
|
2505
|
+
parsed.view = value;
|
|
2506
|
+
else if (RANGE_KEYS.includes(value))
|
|
2507
|
+
parsed.range = value;
|
|
2508
|
+
}
|
|
2509
|
+
return parsed;
|
|
2510
|
+
}
|
|
2511
|
+
function rangeLabel(key) {
|
|
2512
|
+
switch (key) {
|
|
2513
|
+
case "session":
|
|
2514
|
+
return "this session";
|
|
2515
|
+
case "today":
|
|
2516
|
+
return "today";
|
|
2517
|
+
case "7d":
|
|
2518
|
+
return "7 days";
|
|
2519
|
+
case "30d":
|
|
2520
|
+
return "30 days";
|
|
2521
|
+
case "all":
|
|
2522
|
+
return "all time";
|
|
2523
|
+
}
|
|
2524
|
+
}
|
|
2525
|
+
function nextIn(values, current, step) {
|
|
2526
|
+
const index = values.indexOf(current);
|
|
2527
|
+
if (index === -1)
|
|
2528
|
+
return values[0];
|
|
2529
|
+
return values[(index + step + values.length) % values.length];
|
|
2530
|
+
}
|
|
2531
|
+
var DEFAULT_SETTINGS = {
|
|
2532
|
+
view: "overview",
|
|
2533
|
+
range: "all",
|
|
2534
|
+
sort: "",
|
|
2535
|
+
sortDesc: true,
|
|
2536
|
+
granularity: "day",
|
|
2537
|
+
turnsScope: "session",
|
|
2538
|
+
modelID: "",
|
|
2539
|
+
providerID: ""
|
|
2540
|
+
};
|
|
2541
|
+
function sanitizeSettings(raw, views = CLIENT_VIEWS) {
|
|
2542
|
+
const settings = { ...DEFAULT_SETTINGS, ...raw ?? {} };
|
|
2543
|
+
return {
|
|
2544
|
+
view: views.includes(settings.view) ? settings.view : DEFAULT_SETTINGS.view,
|
|
2545
|
+
range: RANGE_KEYS.includes(settings.range) ? settings.range : DEFAULT_SETTINGS.range,
|
|
2546
|
+
sort: typeof settings.sort === "string" ? settings.sort : DEFAULT_SETTINGS.sort,
|
|
2547
|
+
sortDesc: settings.sortDesc === true,
|
|
2548
|
+
granularity: GRANULARITIES.includes(settings.granularity) ? settings.granularity : DEFAULT_SETTINGS.granularity,
|
|
2549
|
+
turnsScope: settings.turnsScope === "all" ? "all" : "session",
|
|
2550
|
+
modelID: typeof settings.modelID === "string" ? settings.modelID : "",
|
|
2551
|
+
providerID: typeof settings.providerID === "string" ? settings.providerID : ""
|
|
2552
|
+
};
|
|
2553
|
+
}
|
|
2554
|
+
function formatPercent(value, digits = 1) {
|
|
2555
|
+
if (value === undefined || !Number.isFinite(value))
|
|
2556
|
+
return "\u2013";
|
|
2557
|
+
return `${(value * 100).toFixed(digits)}%`;
|
|
2558
|
+
}
|
|
2559
|
+
function formatCount(value) {
|
|
2560
|
+
return Number.isFinite(value) ? Math.round(value).toLocaleString("en-US") : "\u2013";
|
|
2561
|
+
}
|
|
2562
|
+
function formatMs(value) {
|
|
2563
|
+
if (value === undefined || !Number.isFinite(value))
|
|
2564
|
+
return "\u2013";
|
|
2565
|
+
const ms = Math.max(0, value);
|
|
2566
|
+
if (ms < 1000)
|
|
2567
|
+
return `${Math.round(ms)}ms`;
|
|
2568
|
+
if (ms < 60000)
|
|
2569
|
+
return `${(ms / 1000).toFixed(1)}s`;
|
|
2570
|
+
return formatDuration(ms);
|
|
2571
|
+
}
|
|
2572
|
+
function formatTps(value) {
|
|
2573
|
+
if (value === undefined || !Number.isFinite(value) || value < 0)
|
|
2574
|
+
return "\u2013";
|
|
2575
|
+
return `${value.toFixed(1)}/s`;
|
|
2576
|
+
}
|
|
2577
|
+
function formatTpsCompact(value) {
|
|
2578
|
+
if (value === undefined || !Number.isFinite(value) || value < 0)
|
|
2579
|
+
return "\u2013";
|
|
2580
|
+
return value >= 10 ? `${Math.round(value)}/s` : `${value.toFixed(1)}/s`;
|
|
2581
|
+
}
|
|
2582
|
+
function formatGap(value) {
|
|
2583
|
+
if (value === undefined || !Number.isFinite(value))
|
|
2584
|
+
return "\u2013";
|
|
2585
|
+
const gap = Math.max(0, value);
|
|
2586
|
+
if (gap < 60000)
|
|
2587
|
+
return `${Math.round(gap / 1000)}s`;
|
|
2588
|
+
if (gap < 3600000)
|
|
2589
|
+
return `${Math.round(gap / 60000)}m`;
|
|
2590
|
+
if (gap < 86400000)
|
|
2591
|
+
return `${(gap / 3600000).toFixed(1)}h`;
|
|
2592
|
+
return `${(gap / 86400000).toFixed(1)}d`;
|
|
2593
|
+
}
|
|
2594
|
+
function truncate(value, width) {
|
|
2595
|
+
if (width <= 1)
|
|
2596
|
+
return "";
|
|
2597
|
+
const clean = sanitizeText(value);
|
|
2598
|
+
if (clean.length <= width)
|
|
2599
|
+
return clean;
|
|
2600
|
+
return `${clean.slice(0, width - 1).trimEnd()}\u2026`;
|
|
2601
|
+
}
|
|
2602
|
+
function truncateMiddle(value, width) {
|
|
2603
|
+
if (width <= 1)
|
|
2604
|
+
return "";
|
|
2605
|
+
const clean = sanitizeText(value);
|
|
2606
|
+
if (clean.length <= width)
|
|
2607
|
+
return clean;
|
|
2608
|
+
const head = Math.ceil((width - 1) / 2);
|
|
2609
|
+
const tail = width - 1 - head;
|
|
2610
|
+
return `${clean.slice(0, head)}\u2026${clean.slice(clean.length - tail)}`;
|
|
2611
|
+
}
|
|
2612
|
+
function tableWidths(width, layouts) {
|
|
2613
|
+
for (const layout of layouts) {
|
|
2614
|
+
const total = layout.reduce((sum, column) => sum + column, 0) + layout.length - 1;
|
|
2615
|
+
if (total <= width)
|
|
2616
|
+
return [...layout];
|
|
2617
|
+
}
|
|
2618
|
+
const last = layouts[layouts.length - 1];
|
|
2619
|
+
return last === undefined ? [] : [...last];
|
|
2620
|
+
}
|
|
2621
|
+
function modelCell(modelID, variant, width) {
|
|
2622
|
+
return truncateMiddle(variant === undefined ? modelID : `${modelID} ${variant}`, width);
|
|
2623
|
+
}
|
|
2624
|
+
function padCell(value, width, align = "left") {
|
|
2625
|
+
if (value.length >= width)
|
|
2626
|
+
return value;
|
|
2627
|
+
const padding = " ".repeat(width - value.length);
|
|
2628
|
+
return align === "right" ? `${padding}${value}` : `${value}${padding}`;
|
|
2629
|
+
}
|
|
2630
|
+
function formatTableRow(cells, widths, aligns) {
|
|
2631
|
+
const parts = [];
|
|
2632
|
+
for (let index = 0;index < cells.length; index += 1) {
|
|
2633
|
+
const width = widths[index] ?? 8;
|
|
2634
|
+
const align = aligns?.[index] ?? "left";
|
|
2635
|
+
parts.push(padCell(truncate(cells[index] ?? "", width), width, align));
|
|
2636
|
+
}
|
|
2637
|
+
return parts.join(" ");
|
|
2638
|
+
}
|
|
2639
|
+
function count(n, singular, plural = `${singular}s`) {
|
|
2640
|
+
return `${formatCount(n)} ${n === 1 ? singular : plural}`;
|
|
2641
|
+
}
|
|
2642
|
+
function kvGrid(pairs, width) {
|
|
2643
|
+
const lines = [];
|
|
2644
|
+
const label = 11;
|
|
2645
|
+
const column = Math.floor(width / 2);
|
|
2646
|
+
for (let index = 0;index < pairs.length; index += 2) {
|
|
2647
|
+
const left = pairs[index];
|
|
2648
|
+
const right = pairs[index + 1];
|
|
2649
|
+
const leftText = `${padCell(left[0], label)}${left[1]}`;
|
|
2650
|
+
if (right === undefined) {
|
|
2651
|
+
lines.push({ text: leftText, tone: "base" });
|
|
2652
|
+
continue;
|
|
2653
|
+
}
|
|
2654
|
+
const rightText = `${padCell(right[0], label)}${right[1]}`;
|
|
2655
|
+
const gap = Math.max(2, column - leftText.length);
|
|
2656
|
+
if (leftText.length + gap + rightText.length <= width) {
|
|
2657
|
+
lines.push({ text: `${leftText}${" ".repeat(gap)}${rightText}`, tone: "base" });
|
|
2658
|
+
} else {
|
|
2659
|
+
lines.push({ text: leftText, tone: "base" });
|
|
2660
|
+
lines.push({ text: rightText, tone: "base" });
|
|
2661
|
+
}
|
|
2662
|
+
}
|
|
2663
|
+
return lines;
|
|
2664
|
+
}
|
|
2665
|
+
var HEADER_TONE = "accent";
|
|
2666
|
+
var SPARK = ["\u2581", "\u2582", "\u2583", "\u2584", "\u2585", "\u2586", "\u2587", "\u2588"];
|
|
2667
|
+
function reduceSeries(values, maxBars = 48) {
|
|
2668
|
+
if (values.length <= maxBars)
|
|
2669
|
+
return [...values];
|
|
2670
|
+
const group = Math.ceil(values.length / maxBars);
|
|
2671
|
+
const reduced = [];
|
|
2672
|
+
for (let index = 0;index < values.length; index += group) {
|
|
2673
|
+
reduced.push(values.slice(index, index + group).reduce((sum, value) => sum + value, 0));
|
|
2674
|
+
}
|
|
2675
|
+
return reduced;
|
|
2676
|
+
}
|
|
2677
|
+
function sparkline(values, maxBars = 48) {
|
|
2678
|
+
if (values.length === 0)
|
|
2679
|
+
return "";
|
|
2680
|
+
const series = reduceSeries(values, maxBars);
|
|
2681
|
+
const max = Math.max(...series);
|
|
2682
|
+
if (max <= 0)
|
|
2683
|
+
return SPARK[0].repeat(series.length);
|
|
2684
|
+
return series.map((value) => SPARK[Math.min(SPARK.length - 1, Math.max(0, Math.round(value / max * (SPARK.length - 1))))]).join("");
|
|
2685
|
+
}
|
|
2686
|
+
function usageBuckets(usage) {
|
|
2687
|
+
const prompt = usage.input + usage.cached + usage.cacheWrite;
|
|
2688
|
+
return {
|
|
2689
|
+
steps: usage.steps,
|
|
2690
|
+
input: prompt - usage.cached,
|
|
2691
|
+
prompt,
|
|
2692
|
+
cached: usage.cached,
|
|
2693
|
+
cacheWrite: usage.cacheWrite,
|
|
2694
|
+
output: usage.output + usage.reasoning,
|
|
2695
|
+
reasoning: usage.reasoning,
|
|
2696
|
+
cost: usage.cost,
|
|
2697
|
+
listCost: usage.listCost ?? 0,
|
|
2698
|
+
hit: prompt > 0 ? usage.cached / prompt : undefined
|
|
2699
|
+
};
|
|
2700
|
+
}
|
|
2701
|
+
function viewBar(view, width = 200, views = CLIENT_VIEWS) {
|
|
2702
|
+
const key = (index) => String((index + 1) % 10);
|
|
2703
|
+
const full = views.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name}`);
|
|
2704
|
+
const candidates = [full, views.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name.slice(0, 3)}`)];
|
|
2705
|
+
for (const parts of candidates) {
|
|
2706
|
+
const text = parts.join(" ");
|
|
2707
|
+
if (text.length <= width)
|
|
2708
|
+
return { text, tone: "muted" };
|
|
2709
|
+
}
|
|
2710
|
+
const index = views.indexOf(view);
|
|
2711
|
+
return { text: `[${index === -1 ? "?" : key(index)} ${view}] \xB7 1-9 0 or [ ] to switch`, tone: "muted" };
|
|
2712
|
+
}
|
|
2713
|
+
function keysFor(of) {
|
|
2714
|
+
if (of === QUOTA_VIEW)
|
|
2715
|
+
return "r refresh \xB7 t range \xB7 0 view \xB7 ? help \xB7 the quotas come from OpenCode Go";
|
|
2716
|
+
if (of === "db")
|
|
2717
|
+
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";
|
|
2718
|
+
if (of === "periods")
|
|
2719
|
+
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";
|
|
2720
|
+
if (of === "turns")
|
|
2721
|
+
return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
|
|
2722
|
+
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";
|
|
2723
|
+
}
|
|
2724
|
+
function filterSummary(filters) {
|
|
2725
|
+
const parts = [];
|
|
2726
|
+
if (filters.modelID !== undefined && filters.modelID !== "")
|
|
2727
|
+
parts.push(`model=${filters.modelID}`);
|
|
2728
|
+
if (filters.providerID !== undefined && filters.providerID !== "")
|
|
2729
|
+
parts.push(`provider=${filters.providerID}`);
|
|
2730
|
+
return parts.length > 0 ? parts.join(" \xB7 ") : undefined;
|
|
2731
|
+
}
|
|
2732
|
+
function granularityLabel(granularity) {
|
|
2733
|
+
return granularity === "day" ? "per day" : granularity === "week" ? "per week" : "per month";
|
|
2734
|
+
}
|
|
2735
|
+
function helpLines(width) {
|
|
2736
|
+
const lines = [
|
|
2737
|
+
{ text: "keys", tone: HEADER_TONE },
|
|
2738
|
+
{ text: " \u2191 \u2193 j k move the cursor \xB7 enter drills in \xB7 backspace goes back" },
|
|
2739
|
+
{ text: " 1-9 0 [ ] choose a view \xB7 cycle views (9 is db, 0 is go)" },
|
|
2740
|
+
{ text: " t shift+t previous / next range" },
|
|
2741
|
+
{ text: " s shift+s cycle sort column \xB7 reverse" },
|
|
2742
|
+
{ text: " b periods bucket: day \u2192 week \u2192 month" },
|
|
2743
|
+
{ text: " a turns scope: this session \u2194 all sessions" },
|
|
2744
|
+
{ text: " m p filter by model / provider (x clears)" },
|
|
2745
|
+
{ text: " r re-read the database \xB7 f full screen \xB7 escape close" },
|
|
2746
|
+
{ text: " e db: backfill list-price estimates for the $0 steps" },
|
|
2747
|
+
{ text: "" },
|
|
2748
|
+
{ text: "go quota \xB7 the host's OpenCode Go allowance", tone: HEADER_TONE },
|
|
2749
|
+
{ text: " rolling the 5-hour window \xB7 weekly \xB7 monthly" },
|
|
2750
|
+
{ text: " forecast the monthly percentage at its reset, from the" },
|
|
2751
|
+
{ text: " cycle's average pace (not a sample history)" },
|
|
2752
|
+
{ text: " renews the monthly reset reported by the host" },
|
|
2753
|
+
{ text: " the plugin reads the host's local usage-limits endpoint;" },
|
|
2754
|
+
{ text: " it never reads your API key and never talks to the Console." },
|
|
2755
|
+
{ text: "numbers \xB7 the same buckets as the live line", tone: HEADER_TONE },
|
|
2756
|
+
{ text: " prompt everything the provider saw: cached + fresh + writes" },
|
|
2757
|
+
{ text: " in the uncached part: fresh input + cache writes" },
|
|
2758
|
+
{ text: " cached prompt read from the provider prompt cache" },
|
|
2759
|
+
{ text: " write part of `in`: prompt written into that cache" },
|
|
2760
|
+
{ text: " hit cached / prompt, weighted over the selection" },
|
|
2761
|
+
{ text: " hit p50 median of the per-step hit: spots a split pattern" },
|
|
2762
|
+
{ text: " out everything generated: visible output + reasoning" },
|
|
2763
|
+
{ text: " reasoning part of `out`" },
|
|
2764
|
+
{ text: " cost money, not tokens: a turn sums every step; $0 is left out" },
|
|
2765
|
+
{ text: " other compaction/title usage: money with no assistant step;" },
|
|
2766
|
+
{ text: " overview, periods and sessions include it; model rows do not" },
|
|
2767
|
+
{ text: " \u2248 list-price estimate for steps the host reported as $0;" },
|
|
2768
|
+
{ text: " `$0.12 + \u2248 $3.40` keeps charged and estimated money apart" },
|
|
2769
|
+
{ text: " wall request \u2192 completed step \xB7 stream request \u2192 last chunk" },
|
|
2770
|
+
{ text: " tps out / streaming seconds, shown as p50" },
|
|
2771
|
+
{ text: " switches how often a step's model or provider differs from the step" },
|
|
2772
|
+
{ text: " before it in the same session (the models view's detail), with" },
|
|
2773
|
+
{ text: " the cache a provider switch cost" },
|
|
2774
|
+
{ text: "" },
|
|
2775
|
+
{ text: "identity", tone: HEADER_TONE },
|
|
2776
|
+
{ text: " provider the provider the model ran through, as OpenCode is configured" },
|
|
2777
|
+
{ text: " (opencode, opencode-go, deepseek, \u2026). A gateway may re-route" },
|
|
2778
|
+
{ text: " a request, but the upstream that ran the inference is not" },
|
|
2779
|
+
{ text: " observable, so the provider is the identity every view shows." },
|
|
2780
|
+
{ text: "" },
|
|
2781
|
+
{ text: "database", tone: HEADER_TONE },
|
|
2782
|
+
{ text: " the db view shows where the file lives, what it holds and how much" },
|
|
2783
|
+
{ text: " of it is old: \u2191\u2193 pick a retention or wipe, enter asks before it" },
|
|
2784
|
+
{ text: " deletes, e backfills list estimates, v gives the space back" },
|
|
2785
|
+
{ text: " local time \xB7 SQLite in the OpenCode state directory" }
|
|
2786
|
+
];
|
|
2787
|
+
return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
|
|
2788
|
+
}
|
|
2789
|
+
function quotaMeterLine(label, meter, now) {
|
|
2790
|
+
const state = meter.limited || meter.percent >= 100 ? "rate-limited" : `${Math.round(meter.percent)}% used`;
|
|
2791
|
+
const countdown = formatCountdown(meter.resetsAt, now);
|
|
2792
|
+
return {
|
|
2793
|
+
text: ` ${padCell(label, 9)}${quotaBar(meter.percent)} ${state} \xB7 ${countdown === "due" ? "resets due" : `resets in ${countdown}`}`,
|
|
2794
|
+
tone: meter.limited || meter.percent >= 100 ? "warning" : "base"
|
|
2795
|
+
};
|
|
2796
|
+
}
|
|
2797
|
+
function goQuotaLines(state, options) {
|
|
2798
|
+
const { now, width, loading, error } = options;
|
|
2799
|
+
const name = options.name?.trim() || DEFAULT_QUOTA_NAME;
|
|
2800
|
+
const lines = [];
|
|
2801
|
+
const push = (text, tone = "base") => {
|
|
2802
|
+
lines.push({ text, tone });
|
|
2803
|
+
};
|
|
2804
|
+
if (state === undefined) {
|
|
2805
|
+
if (error !== undefined && error !== "")
|
|
2806
|
+
push(`Go quota unavailable: ${error}`, "warning");
|
|
2807
|
+
else if (loading === true)
|
|
2808
|
+
push("reading OpenCode Go quota\u2026", "muted");
|
|
2809
|
+
else
|
|
2810
|
+
push("OpenCode Go quota is unavailable", "muted");
|
|
2811
|
+
return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
|
|
2812
|
+
}
|
|
2813
|
+
if (state.kind === "none") {
|
|
2814
|
+
push(name, "accent");
|
|
2815
|
+
push(state.reason === "console" ? "Connect OpenCode Console with /connect to see your Go allowance." : "This workspace has no active OpenCode Go subscription.", "muted");
|
|
2816
|
+
return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
|
|
2817
|
+
}
|
|
2818
|
+
const quota = state.quota;
|
|
2819
|
+
const workspace = quota.workspace?.name ?? quota.workspace?.id ?? "workspace";
|
|
2820
|
+
const status = quotaStatus(quota);
|
|
2821
|
+
const forecast = forecastMonthly(quota.monthly, now);
|
|
2822
|
+
push(`${name} \xB7 ${workspace}`, "accent");
|
|
2823
|
+
push(`status ${status}`, status === "active" ? "base" : "warning");
|
|
2824
|
+
lines.push(quotaMeterLine("rolling", quota.rolling, now));
|
|
2825
|
+
lines.push(quotaMeterLine("weekly", quota.weekly, now));
|
|
2826
|
+
lines.push(quotaMeterLine("monthly", quota.monthly, now));
|
|
2827
|
+
push("");
|
|
2828
|
+
if (forecast.reached || quota.monthly.limited) {
|
|
2829
|
+
push(`forecast monthly limit reached \xB7 renews ${formatRenewal(quota.monthly.resetsAt)}`, "warning");
|
|
2830
|
+
} else if (now >= forecast.endAt) {
|
|
2831
|
+
push("forecast monthly reset due \xB7 refresh", "warning");
|
|
2832
|
+
} else if (!forecast.available) {
|
|
2833
|
+
push("forecast too early in the cycle to project a monthly pace", "muted");
|
|
2834
|
+
} else if (quota.monthly.percent === 0) {
|
|
2835
|
+
push("forecast no monthly usage yet this cycle", "muted");
|
|
2836
|
+
} else if (forecast.willExhaust && forecast.exhaustAt !== undefined) {
|
|
2837
|
+
push(`forecast limit before renewal ~${formatRenewal(forecast.exhaustAt)} \xB7 ${formatDuration(forecast.exhaustAt - now)} from now \xB7 ${forecast.ratePerDay.toFixed(1)}%/day`, "warning");
|
|
2838
|
+
} else {
|
|
2839
|
+
const projected = Math.min(999, Math.round(forecast.projectedPercent));
|
|
2840
|
+
const headroom = Math.max(0, Math.round(100 - forecast.projectedPercent));
|
|
2841
|
+
push(`forecast ~${projected}% at reset \xB7 ${headroom}% headroom \xB7 ${forecast.ratePerDay.toFixed(1)}%/day`);
|
|
2842
|
+
}
|
|
2843
|
+
const renewal = formatRenewal(quota.monthly.resetsAt);
|
|
2844
|
+
const countdown = formatCountdown(quota.monthly.resetsAt, now);
|
|
2845
|
+
push(`renews ${renewal} \xB7 ${countdown === "due" ? "renewal due" : `in ${countdown}`}`, "muted");
|
|
2846
|
+
if (quota.workspace?.usageURL !== undefined)
|
|
2847
|
+
push(`console ${quota.workspace.usageURL}`, "muted");
|
|
2848
|
+
const age = Math.max(0, now - quota.observedAt);
|
|
2849
|
+
push(`updated ${age < 1000 ? "just now" : `${formatDuration(age)} ago`}`, "muted");
|
|
2850
|
+
if (loading === true)
|
|
2851
|
+
push("refreshing\u2026", "muted");
|
|
2852
|
+
if (error !== undefined && error !== "")
|
|
2853
|
+
push(`quota refresh failed: ${error}`, "warning");
|
|
2854
|
+
return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
|
|
2855
|
+
}
|
|
2856
|
+
function goSidebarLines(state, now, width, name = DEFAULT_QUOTA_NAME) {
|
|
2857
|
+
if (state?.kind !== "ok" || width <= 0)
|
|
2858
|
+
return [];
|
|
2859
|
+
const quota = state.quota;
|
|
2860
|
+
const status = quotaStatus(quota);
|
|
2861
|
+
const forecast = forecastMonthly(quota.monthly, now);
|
|
2862
|
+
const base = `5h ${Math.round(quota.rolling.percent)}% \xB7 week ${Math.round(quota.weekly.percent)}% \xB7 month ${Math.round(quota.monthly.percent)}%`;
|
|
2863
|
+
const baseTone = status !== "active" || quota.monthly.percent >= 80 ? "warning" : "base";
|
|
2864
|
+
let forecastText = "forecast too early";
|
|
2865
|
+
let forecastTone = "muted";
|
|
2866
|
+
if (forecast.reached || quota.monthly.limited) {
|
|
2867
|
+
forecastText = "monthly limit reached";
|
|
2868
|
+
forecastTone = "warning";
|
|
2869
|
+
} else if (forecast.willExhaust) {
|
|
2870
|
+
forecastText = "limit before renewal";
|
|
2871
|
+
forecastTone = "warning";
|
|
2872
|
+
} else if (forecast.available && quota.monthly.percent > 0) {
|
|
2873
|
+
forecastText = `forecast ~${Math.min(999, Math.round(forecast.projectedPercent))}% at reset`;
|
|
2874
|
+
} else if (forecast.available && quota.monthly.percent === 0) {
|
|
2875
|
+
forecastText = "forecast no usage yet";
|
|
2876
|
+
}
|
|
2877
|
+
return [
|
|
2878
|
+
{ text: truncate(name, width), tone: "accent" },
|
|
2879
|
+
{ text: truncate(base, width), tone: baseTone },
|
|
2880
|
+
{ text: truncate(forecastText, width), tone: forecastTone },
|
|
2881
|
+
{ text: truncate(`renews ${formatRenewalCompact(quota.monthly.resetsAt)}`, width), tone: "muted" }
|
|
2882
|
+
];
|
|
2883
|
+
}
|
|
2884
|
+
function usagePairs(usage, estimates = true) {
|
|
2885
|
+
if (usage === undefined)
|
|
2886
|
+
return [];
|
|
2887
|
+
const buckets = usageBuckets(usage);
|
|
2888
|
+
const pairs = [
|
|
2889
|
+
["steps", formatCount(buckets.steps)],
|
|
2890
|
+
["in", formatTokens(buckets.input)],
|
|
2891
|
+
["prompt", formatTokens(buckets.prompt)],
|
|
2892
|
+
["cached", formatTokens(buckets.cached)],
|
|
2893
|
+
["hit", formatPercent(buckets.hit)],
|
|
2894
|
+
["out", formatTokens(buckets.output)],
|
|
2895
|
+
["write", formatTokens(buckets.cacheWrite)]
|
|
2896
|
+
];
|
|
2897
|
+
if (buckets.reasoning > 0)
|
|
2898
|
+
pairs.push(["reasoning", formatTokens(buckets.reasoning)]);
|
|
2899
|
+
pairs.push(["cost", (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost)]);
|
|
2900
|
+
const other = usage.otherCost ?? 0;
|
|
2901
|
+
if (other > 0)
|
|
2902
|
+
pairs.push(["other", `${formatCost(other)} comp/title`]);
|
|
2903
|
+
if ("tps" in usage && usage.tps !== undefined)
|
|
2904
|
+
pairs.push(["tps", formatTps(usage.tps)]);
|
|
2905
|
+
return pairs;
|
|
2906
|
+
}
|
|
2907
|
+
function overviewLines(data, width) {
|
|
2908
|
+
const lines = [];
|
|
2909
|
+
const estimates = data.estimates !== false;
|
|
2910
|
+
lines.push({
|
|
2911
|
+
text: `${rangeLabel(data.range)} \xB7 ${count(data.usage.steps, "step")} \xB7 ${count(data.usage.sessions, "session")} \xB7 ${count(data.usage.prompts, "prompt")}`,
|
|
2912
|
+
tone: "muted"
|
|
2913
|
+
});
|
|
2914
|
+
lines.push(...kvGrid(buildOverviewPairs(data.usage, "all", estimates), width));
|
|
2915
|
+
if (data.activity !== undefined && data.activity.length > 1) {
|
|
2916
|
+
const series = reduceSeries(data.activity);
|
|
2917
|
+
lines.push({ text: "", tone: "muted" });
|
|
2918
|
+
lines.push({ text: `activity ${sparkline(series)} ${count(series.length, "bucket")}`, tone: "muted" });
|
|
2919
|
+
}
|
|
2920
|
+
if (data.session !== undefined) {
|
|
2921
|
+
lines.push({ text: "", tone: "muted" });
|
|
2922
|
+
lines.push({ text: "this session", tone: HEADER_TONE });
|
|
2923
|
+
lines.push(...kvGrid(buildOverviewPairs(data.session, "session", estimates), width));
|
|
2924
|
+
if (data.subagents !== undefined && data.subagents.length > 0) {
|
|
2925
|
+
const steps = data.subagents.reduce((sum, row) => sum + row.steps, 0);
|
|
2926
|
+
const cost = data.subagents.reduce((sum, row) => sum + row.cost, 0);
|
|
2927
|
+
const listCost = data.subagents.reduce((sum, row) => sum + row.listCost, 0);
|
|
2928
|
+
lines.push({
|
|
2929
|
+
text: ` subagents ${count(data.subagents.length, "session")} \xB7 ${count(steps, "step")} \xB7 ${formatSpend(cost, estimates ? listCost : 0)} (their own sessions)`,
|
|
2930
|
+
tone: "muted"
|
|
2931
|
+
});
|
|
2932
|
+
}
|
|
2933
|
+
}
|
|
2934
|
+
if (data.coverage !== undefined) {
|
|
2935
|
+
lines.push({ text: "", tone: "muted" });
|
|
2936
|
+
lines.push({ text: "data coverage", tone: HEADER_TONE });
|
|
2937
|
+
lines.push(...kvGrid(coveragePairs(data.coverage), width));
|
|
2938
|
+
}
|
|
2939
|
+
return lines;
|
|
2940
|
+
}
|
|
2941
|
+
function buildOverviewPairs(usage, scope, estimates = true) {
|
|
2942
|
+
const pairs = usagePairs(usage, estimates);
|
|
2943
|
+
if (scope === "all") {
|
|
2944
|
+
pairs.push(["first", usage.firstAt === undefined ? "\u2013" : new Date(usage.firstAt).toLocaleString("en-GB")]);
|
|
2945
|
+
pairs.push(["last", usage.lastAt === undefined ? "\u2013" : new Date(usage.lastAt).toLocaleString("en-GB")]);
|
|
2946
|
+
}
|
|
2947
|
+
return pairs;
|
|
2948
|
+
}
|
|
2949
|
+
function coveragePairs(coverage) {
|
|
2950
|
+
const share = (missing) => coverage.steps === 0 ? "\u2013" : `${(missing / coverage.steps * 100).toFixed(1)}%`;
|
|
2951
|
+
return [
|
|
2952
|
+
["models", `${formatCount(coverage.models)} \xB7 unknown ${share(coverage.missingModel)}`],
|
|
2953
|
+
["providers", formatCount(coverage.providers)],
|
|
2954
|
+
["unsettled", `${formatCount(coverage.unsettled)} \xB7 no tps ${share(coverage.missingTps)}`],
|
|
2955
|
+
[
|
|
2956
|
+
"window",
|
|
2957
|
+
`${coverage.firstAt === undefined ? "\u2013" : new Date(coverage.firstAt).toLocaleString("en-GB")} \u2192 ${coverage.lastAt === undefined ? "\u2013" : new Date(coverage.lastAt).toLocaleString("en-GB")}`
|
|
2958
|
+
]
|
|
2959
|
+
];
|
|
2960
|
+
}
|
|
2961
|
+
function modelColumns(width) {
|
|
2962
|
+
const layouts = [
|
|
2963
|
+
{ model: 30, steps: 6, prompt: 10, cached: 10, hit: 7, out: 9, cost: 9, spread: 24 },
|
|
2964
|
+
{ model: 26, steps: 6, prompt: 9, cached: 9, hit: 7, out: 8, cost: 8, spread: 20 },
|
|
2965
|
+
{ model: 20, steps: 6, prompt: 9, cached: 9, hit: 6, out: 8, cost: 8, spread: 0 },
|
|
2966
|
+
{ model: 18, steps: 5, prompt: 8, cached: 8, hit: 0, out: 7, cost: 8, spread: 0 },
|
|
2967
|
+
{ model: 14, steps: 5, prompt: 8, cached: 8, hit: 0, out: 7, cost: 0, spread: 0 }
|
|
2968
|
+
];
|
|
2969
|
+
for (const layout of layouts) {
|
|
2970
|
+
const total = Object.values(layout).reduce((sum, column) => sum + column, 0) + Object.values(layout).filter((column) => column > 0).length - 1;
|
|
2971
|
+
if (total <= width)
|
|
2972
|
+
return layout;
|
|
2973
|
+
}
|
|
2974
|
+
return layouts[layouts.length - 1];
|
|
2975
|
+
}
|
|
2976
|
+
function modelsLines(rows, width, extras, limit = 40, estimates = true) {
|
|
2977
|
+
const columns = modelColumns(width);
|
|
2978
|
+
const widths = [columns.model, columns.steps, columns.prompt, columns.cached];
|
|
2979
|
+
const aligns = ["left", "right", "right", "right"];
|
|
2980
|
+
const header = ["model", "steps", "prompt", "cached"];
|
|
2981
|
+
if (columns.hit > 0) {
|
|
2982
|
+
widths.push(columns.hit);
|
|
2983
|
+
aligns.push("right");
|
|
2984
|
+
header.push("hit");
|
|
2985
|
+
}
|
|
2986
|
+
widths.push(columns.out);
|
|
2987
|
+
aligns.push("right");
|
|
2988
|
+
header.push("out");
|
|
2989
|
+
if (columns.cost > 0) {
|
|
2990
|
+
widths.push(columns.cost);
|
|
2991
|
+
aligns.push("right");
|
|
2992
|
+
header.push("cost");
|
|
2993
|
+
}
|
|
2994
|
+
if (columns.spread > 0) {
|
|
2995
|
+
widths.push(columns.spread);
|
|
2996
|
+
aligns.push("left");
|
|
2997
|
+
header.push("providers");
|
|
2998
|
+
}
|
|
2999
|
+
const lines = [{ text: formatTableRow(header, widths, aligns), tone: HEADER_TONE }];
|
|
3000
|
+
for (const model of rows.slice(0, limit)) {
|
|
3001
|
+
const key = modelKey(model.modelID, model.variant);
|
|
3002
|
+
const name = modelCell(model.modelID, model.variant, columns.model);
|
|
3003
|
+
const buckets = usageBuckets(model.totals);
|
|
3004
|
+
const providers = unique(model.providers.map((provider) => provider.providerID));
|
|
3005
|
+
const cache = extras?.cache?.get(key);
|
|
3006
|
+
const switches = extras?.switches?.get(key);
|
|
3007
|
+
const cells = [name, formatCount(buckets.steps), formatTokens(buckets.prompt), formatTokens(buckets.cached)];
|
|
3008
|
+
if (columns.hit > 0)
|
|
3009
|
+
cells.push(formatPercent(cache?.hit ?? buckets.hit));
|
|
3010
|
+
cells.push(formatTokens(buckets.output));
|
|
3011
|
+
if (columns.cost > 0)
|
|
3012
|
+
cells.push(formatSpend(buckets.cost, estimates ? buckets.listCost : 0));
|
|
3013
|
+
if (columns.spread > 0)
|
|
3014
|
+
cells.push(providers.join(", "));
|
|
3015
|
+
lines.push({
|
|
3016
|
+
text: formatTableRow(cells, widths, aligns),
|
|
3017
|
+
tone: "base",
|
|
3018
|
+
row: { kind: "model", value: model.modelID, ...model.variant !== undefined ? { variant: model.variant } : {} }
|
|
3019
|
+
});
|
|
3020
|
+
const details = [];
|
|
3021
|
+
if (cache !== undefined)
|
|
3022
|
+
details.push(`p50 hit ${formatPercent(cache.hitP50)}`);
|
|
3023
|
+
if (switches !== undefined && switches.changes > 0) {
|
|
3024
|
+
const scope = switches.providerChanges > 0 ? ` (${formatCount(switches.providerChanges)} provider)` : "";
|
|
3025
|
+
details.push(`${count(switches.changes, "switch", "switches")}${scope}`);
|
|
3026
|
+
if (switches.cacheLost > 0)
|
|
3027
|
+
details.push(`${formatTokens(switches.cacheLost)} lost on a switch`);
|
|
3028
|
+
}
|
|
3029
|
+
if (details.length > 0) {
|
|
3030
|
+
lines.push({ text: truncate(`${" ".repeat(columns.model + 1)}${details.join(" \xB7 ")}`, width), tone: "muted" });
|
|
3031
|
+
}
|
|
3032
|
+
}
|
|
3033
|
+
if (rows.length > limit)
|
|
3034
|
+
lines.push({ text: `\u2026 ${count(rows.length - limit, "more model")} \xB7 narrow the range or filter`, tone: "muted" });
|
|
3035
|
+
if (rows.length === 0)
|
|
3036
|
+
lines.push({ text: "no usage recorded for this range", tone: "muted" });
|
|
3037
|
+
return lines;
|
|
3038
|
+
}
|
|
3039
|
+
function unique(values) {
|
|
3040
|
+
return [...new Set(values)];
|
|
3041
|
+
}
|
|
3042
|
+
var tableWidth = (columns) => columns.reduce((sum, column) => sum + column.width, 0) + columns.length - 1;
|
|
3043
|
+
function fitColumns(columns, width) {
|
|
3044
|
+
const chosen = [...columns];
|
|
3045
|
+
while (chosen.length > 1 && tableWidth(chosen) > width) {
|
|
3046
|
+
const optional = [...chosen].reverse().findIndex((column) => column.optional === true);
|
|
3047
|
+
if (optional === -1)
|
|
3048
|
+
break;
|
|
3049
|
+
chosen.splice(chosen.length - 1 - optional, 1);
|
|
3050
|
+
}
|
|
3051
|
+
return chosen;
|
|
3052
|
+
}
|
|
3053
|
+
function renderTable(rows, columns, width, options) {
|
|
3054
|
+
const chosen = fitColumns(columns, width);
|
|
3055
|
+
const widths = chosen.map((column) => column.width);
|
|
3056
|
+
const aligns = chosen.map((column) => column.align ?? "left");
|
|
3057
|
+
const alignsTyped = aligns;
|
|
3058
|
+
const lines = [{ text: formatTableRow(chosen.map((column) => column.header), widths, alignsTyped), tone: HEADER_TONE }];
|
|
3059
|
+
if (rows.length === 0)
|
|
3060
|
+
lines.push({ text: options.empty, tone: "muted" });
|
|
3061
|
+
for (const row of rows.slice(0, options.limit)) {
|
|
3062
|
+
const identity = options.row?.(row);
|
|
3063
|
+
lines.push({
|
|
3064
|
+
text: formatTableRow(chosen.map((column) => column.cell(row)), widths, alignsTyped),
|
|
3065
|
+
tone: options.tone?.(row) ?? "base",
|
|
3066
|
+
...identity === undefined ? {} : { row: identity }
|
|
3067
|
+
});
|
|
3068
|
+
}
|
|
3069
|
+
if (rows.length > options.limit)
|
|
3070
|
+
lines.push({ text: `\u2026 ${count(rows.length - options.limit, "more row")}`, tone: "muted" });
|
|
3071
|
+
return lines;
|
|
3072
|
+
}
|
|
3073
|
+
function providerSummaryLines(rows, width, limit = 40, estimates = true) {
|
|
3074
|
+
const lines = renderTable(rows, [
|
|
3075
|
+
{ header: "provider", width: 24, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 24) },
|
|
3076
|
+
{ header: "models", width: 13, align: "right", optional: true, cell: (row) => formatCount(row.models.length) },
|
|
3077
|
+
{ header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.usage.steps) },
|
|
3078
|
+
{ header: "share", width: 6, align: "right", optional: true, cell: (row) => formatPercent(row.share, 0) },
|
|
3079
|
+
{ header: "prompt", width: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
|
|
3080
|
+
{ header: "cached", width: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
|
|
3081
|
+
{ header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
|
|
3082
|
+
{ header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
|
|
3083
|
+
{ header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
|
|
3084
|
+
{ header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
|
|
3085
|
+
], width, {
|
|
3086
|
+
limit,
|
|
3087
|
+
empty: "no usage recorded for this range",
|
|
3088
|
+
row: (row) => row.provider === undefined ? undefined : { kind: "provider", value: row.provider },
|
|
3089
|
+
tone: (row) => row.provider === undefined ? "muted" : "base"
|
|
3090
|
+
});
|
|
3091
|
+
return lines;
|
|
3092
|
+
}
|
|
3093
|
+
function providerLines(rows, width, limit = 40, estimates = true) {
|
|
3094
|
+
return renderTable(rows, [
|
|
3095
|
+
{ header: "model", width: 26, cell: (row) => modelCell(row.modelID, row.variant, 26) },
|
|
3096
|
+
{ header: "provider", width: 22, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 22) },
|
|
3097
|
+
{ header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.usage.steps) },
|
|
3098
|
+
{ header: "share", width: 6, align: "right", optional: true, cell: (row) => formatPercent(row.share, 0) },
|
|
3099
|
+
{ header: "prompt", width: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
|
|
3100
|
+
{ header: "cached", width: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
|
|
3101
|
+
{ header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
|
|
3102
|
+
{ header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
|
|
3103
|
+
{ header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
|
|
3104
|
+
{ header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
|
|
3105
|
+
], width, {
|
|
3106
|
+
limit,
|
|
3107
|
+
empty: "no usage recorded for this range",
|
|
3108
|
+
row: (row) => ({ kind: "model", value: row.modelID, ...row.variant !== undefined ? { variant: row.variant } : {} }),
|
|
3109
|
+
tone: (row) => row.provider === undefined ? "muted" : "base"
|
|
3110
|
+
});
|
|
3111
|
+
}
|
|
3112
|
+
function cacheLines(data, width) {
|
|
3113
|
+
const lines = [];
|
|
3114
|
+
const total = data.drops.reduce((sum, drop) => sum + drop.tokens, 0);
|
|
3115
|
+
lines.push({ text: `reuse losses ${count(data.drops.length, "event")} \xB7 ${formatTokens(total)} tokens`, tone: total > 0 ? "warning" : "base" });
|
|
3116
|
+
for (const reason of ["expired", "compaction", "unknown"]) {
|
|
3117
|
+
const group = data.drops.filter((drop) => drop.reason === reason);
|
|
3118
|
+
if (group.length === 0)
|
|
3119
|
+
continue;
|
|
3120
|
+
const tokens = group.reduce((sum, drop) => sum + drop.tokens, 0);
|
|
3121
|
+
lines.push({ text: ` ${padCell(reason, 11)}${formatCount(group.length)} \xB7 ${formatTokens(tokens)}`, tone: reason === "expired" ? "warning" : "muted" });
|
|
3122
|
+
}
|
|
3123
|
+
if (data.drops.length === 0)
|
|
3124
|
+
lines.push({ text: " none: prompt cache held through every gap", tone: "muted" });
|
|
3125
|
+
if (data.models !== undefined && data.models.length > 0) {
|
|
3126
|
+
lines.push({ text: "", tone: "muted" });
|
|
3127
|
+
lines.push({ text: "reuse by model", tone: HEADER_TONE });
|
|
3128
|
+
const widths = width >= 100 ? [30, 7, 11, 10, 8, 8, 10] : [18, 6, 9, 9, 7, 7, 9];
|
|
3129
|
+
lines.push({ text: formatTableRow(["model", "steps", "prompt", "cached", "write", "hit", "hit p50"], widths, ["left", "right", "right", "right", "right", "right", "right"]), tone: "muted" });
|
|
3130
|
+
for (const row of data.models.slice(0, 10)) {
|
|
3131
|
+
const name = modelCell(row.usage.modelID, row.usage.variant, widths[0]);
|
|
3132
|
+
lines.push({
|
|
3133
|
+
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"]),
|
|
3134
|
+
tone: "base",
|
|
3135
|
+
row: { kind: "model", value: row.usage.modelID, ...row.usage.variant !== undefined ? { variant: row.usage.variant } : {} }
|
|
3136
|
+
});
|
|
3137
|
+
}
|
|
3138
|
+
}
|
|
3139
|
+
if (data.gap !== undefined && data.gap.samples > 0) {
|
|
3140
|
+
lines.push({ text: "", tone: "muted" });
|
|
3141
|
+
lines.push({ text: "cache survival against idle time", tone: HEADER_TONE });
|
|
3142
|
+
const widths = [9, 8, 9, 9, 10];
|
|
3143
|
+
lines.push({ text: formatTableRow(["gap", "pairs", "kept", "drops", "lost"], widths, ["left", "right", "right", "right", "right"]), tone: "muted" });
|
|
3144
|
+
for (const bucket of data.gap.buckets) {
|
|
3145
|
+
if (bucket.samples === 0)
|
|
3146
|
+
continue;
|
|
3147
|
+
lines.push({
|
|
3148
|
+
text: formatTableRow([bucket.label, formatCount(bucket.samples), formatPercent(bucket.retainedRatio, 0), formatCount(bucket.drops), formatTokens(bucket.lostTokens)], widths, ["left", "right", "right", "right", "right"]),
|
|
3149
|
+
tone: bucket.drops > 0 ? "warning" : "base"
|
|
3150
|
+
});
|
|
3151
|
+
}
|
|
3152
|
+
if (data.gap.providers.length > 1) {
|
|
3153
|
+
lines.push({ text: "", tone: "muted" });
|
|
3154
|
+
lines.push({ text: "reuse kept, by provider", tone: HEADER_TONE });
|
|
3155
|
+
const providerWidths = [26, 8, 9, 9];
|
|
3156
|
+
lines.push({ text: formatTableRow(["provider", "pairs", "kept", "lost"], providerWidths, ["left", "right", "right", "right"]), tone: "muted" });
|
|
3157
|
+
for (const row of data.gap.providers.slice(0, 8)) {
|
|
3158
|
+
lines.push({
|
|
3159
|
+
text: formatTableRow([row.provider, formatCount(row.samples), formatPercent(row.retainedRatio, 0), formatTokens(row.lostTokens)], providerWidths, ["left", "right", "right", "right"]),
|
|
3160
|
+
tone: "base"
|
|
3161
|
+
});
|
|
3162
|
+
}
|
|
3163
|
+
}
|
|
3164
|
+
}
|
|
3165
|
+
lines.push({ text: "", tone: "muted" });
|
|
3166
|
+
lines.push({ text: "observed cache TTL bounds", tone: HEADER_TONE });
|
|
3167
|
+
if (data.evidence.length === 0) {
|
|
3168
|
+
lines.push({ text: " no comparable step pairs yet", tone: "muted" });
|
|
3169
|
+
} else {
|
|
3170
|
+
const widths = [Math.max(18, Math.floor(width * 0.4)), 14, 12, 9];
|
|
3171
|
+
lines.push({ text: formatTableRow(["model", "hits up to", "drops from", "samples"], widths, ["left", "right", "right", "right"]), tone: "muted" });
|
|
3172
|
+
for (const row of data.evidence.slice(0, 10)) {
|
|
3173
|
+
lines.push({
|
|
3174
|
+
text: formatTableRow([`${row.providerID}/${row.modelID}`, formatGap(row.maxHitGapMs), formatGap(row.minDropGapMs), formatCount(row.samples)], widths, ["left", "right", "right", "right"]),
|
|
3175
|
+
tone: "base"
|
|
3176
|
+
});
|
|
3177
|
+
}
|
|
3178
|
+
}
|
|
3179
|
+
if (data.drops.length > 0) {
|
|
3180
|
+
lines.push({ text: "", tone: "muted" });
|
|
3181
|
+
lines.push({ text: "recent losses", tone: HEADER_TONE });
|
|
3182
|
+
for (const drop of [...data.drops].sort((a, b) => b.at - a.at).slice(0, 8)) {
|
|
3183
|
+
const when = new Date(drop.at).toLocaleTimeString("en-GB");
|
|
3184
|
+
lines.push({
|
|
3185
|
+
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"]),
|
|
3186
|
+
tone: drop.reason === "expired" ? "warning" : "base"
|
|
3187
|
+
});
|
|
3188
|
+
}
|
|
3189
|
+
}
|
|
3190
|
+
return lines;
|
|
3191
|
+
}
|
|
3192
|
+
function periodLines(rows, width, granularity, limit = 40, estimates = true, totalSessions) {
|
|
3193
|
+
const lines = [];
|
|
3194
|
+
const totals = rows.reduce((sum, row) => {
|
|
3195
|
+
sum.steps += row.usage.steps;
|
|
3196
|
+
sum.sessions += row.sessions;
|
|
3197
|
+
sum.input += row.usage.input;
|
|
3198
|
+
sum.cached += row.usage.cached;
|
|
3199
|
+
sum.cacheWrite += row.usage.cacheWrite;
|
|
3200
|
+
sum.output += row.usage.output;
|
|
3201
|
+
sum.reasoning += row.usage.reasoning;
|
|
3202
|
+
sum.cost += row.usage.cost;
|
|
3203
|
+
sum.listCost += row.usage.listCost;
|
|
3204
|
+
return sum;
|
|
3205
|
+
}, { steps: 0, sessions: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
|
|
3206
|
+
const overall = usageBuckets(totals);
|
|
3207
|
+
lines.push({
|
|
3208
|
+
text: `${granularityLabel(granularity)} \xB7 ${count(rows.length, "period")} \xB7 ${count(totals.steps, "step")} \xB7 hit ${formatPercent(overall.hit)}`,
|
|
3209
|
+
tone: "muted"
|
|
3210
|
+
});
|
|
3211
|
+
if (rows.length > 1) {
|
|
3212
|
+
lines.push({ text: `steps ${sparkline(rows.map((row) => row.usage.steps))}`, tone: "muted" });
|
|
3213
|
+
lines.push({ text: `cached ${sparkline(rows.map((row) => row.usage.cached))}`, tone: "muted" });
|
|
3214
|
+
lines.push({
|
|
3215
|
+
text: `cost ${sparkline(rows.map((row) => Math.round((estimates ? row.usage.cost + row.usage.listCost : row.usage.cost) * 1e4)))}`,
|
|
3216
|
+
tone: "muted"
|
|
3217
|
+
});
|
|
3218
|
+
}
|
|
3219
|
+
const withSessions = tableWidths(width, [[12, 7, 7, 11, 10, 7, 9, 9]]).length === 8;
|
|
3220
|
+
const widths = withSessions ? [12, 7, 7, 11, 10, 7, 9, 9] : [12, 7, 11, 10, 7, 9, 9];
|
|
3221
|
+
const aligns = widths.map((_, index) => index === 0 ? "left" : "right");
|
|
3222
|
+
const header = withSessions ? ["period", "steps", "sess", "prompt", "cached", "hit", "out", "cost"] : ["period", "steps", "prompt", "cached", "hit", "out", "cost"];
|
|
3223
|
+
lines.push({ text: formatTableRow(header, widths, aligns), tone: HEADER_TONE });
|
|
3224
|
+
const newest = [...rows].sort((left, right) => right.at - left.at).slice(0, limit);
|
|
3225
|
+
for (const row of newest) {
|
|
3226
|
+
const buckets = usageBuckets(row.usage);
|
|
3227
|
+
const cells = [
|
|
3228
|
+
row.label,
|
|
3229
|
+
formatCount(row.steps),
|
|
3230
|
+
...withSessions ? [formatCount(row.sessions)] : [],
|
|
3231
|
+
formatTokens(buckets.prompt),
|
|
3232
|
+
formatTokens(buckets.cached),
|
|
3233
|
+
formatPercent(buckets.hit, 0),
|
|
3234
|
+
formatTokens(buckets.output),
|
|
3235
|
+
formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
|
|
3236
|
+
];
|
|
3237
|
+
lines.push({ text: formatTableRow(cells, widths, aligns), tone: "base", row: { kind: "period", value: row.key } });
|
|
3238
|
+
}
|
|
3239
|
+
lines.push({ text: "", tone: "muted" });
|
|
3240
|
+
lines.push({
|
|
3241
|
+
text: formatTableRow([
|
|
3242
|
+
"total",
|
|
3243
|
+
formatCount(totals.steps),
|
|
3244
|
+
...withSessions ? [formatCount(totalSessions ?? totals.sessions)] : [],
|
|
3245
|
+
formatTokens(overall.prompt),
|
|
3246
|
+
formatTokens(overall.cached),
|
|
3247
|
+
formatPercent(overall.hit, 0),
|
|
3248
|
+
formatTokens(overall.output),
|
|
3249
|
+
formatSpend(overall.cost, estimates ? overall.listCost : 0)
|
|
3250
|
+
], widths, aligns),
|
|
3251
|
+
tone: HEADER_TONE
|
|
3252
|
+
});
|
|
3253
|
+
if (rows.length === 0)
|
|
3254
|
+
lines.push({ text: "no usage recorded for this range", tone: "muted" });
|
|
3255
|
+
return lines;
|
|
3256
|
+
}
|
|
3257
|
+
function latencyLines(report, width, groups, limit = 12, estimates = true) {
|
|
3258
|
+
const lines = [];
|
|
3259
|
+
lines.push({
|
|
3260
|
+
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]),
|
|
3261
|
+
tone: "base"
|
|
3262
|
+
});
|
|
3263
|
+
lines.push({
|
|
3264
|
+
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]),
|
|
3265
|
+
tone: "base"
|
|
3266
|
+
});
|
|
3267
|
+
lines.push({
|
|
3268
|
+
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]),
|
|
3269
|
+
tone: "base"
|
|
3270
|
+
});
|
|
3271
|
+
lines.push({ text: "", tone: "muted" });
|
|
3272
|
+
lines.push({
|
|
3273
|
+
text: truncate("wall = request to completed \xB7 stream = request to last chunk \xB7 throughput = output+reasoning tokens/s", width),
|
|
3274
|
+
tone: "muted"
|
|
3275
|
+
});
|
|
3276
|
+
if (report.wall.count === 0)
|
|
3277
|
+
lines.push({ text: "no completed steps for this range", tone: "muted" });
|
|
3278
|
+
if (groups !== undefined && groups.length > 0) {
|
|
3279
|
+
lines.push({ text: "", tone: "muted" });
|
|
3280
|
+
lines.push({ text: "by group", tone: HEADER_TONE });
|
|
3281
|
+
const widths = width >= 110 ? [24, 6, 9, 9, 9, 9, 9, 9] : [16, 5, 8, 8, 8, 8, 8, 8];
|
|
3282
|
+
const aligns = ["left", "right", "right", "right", "right", "right", "right", "right"];
|
|
3283
|
+
lines.push({ text: formatTableRow(["group", "n", "wall p50", "wall p90", "stream", "tps p50", "tps p90", "cost"], widths, aligns), tone: "muted" });
|
|
3284
|
+
for (const row of groups.slice(0, limit)) {
|
|
3285
|
+
const thin = row.count < 5;
|
|
3286
|
+
lines.push({
|
|
3287
|
+
text: formatTableRow([
|
|
3288
|
+
row.label,
|
|
3289
|
+
formatCount(row.count),
|
|
3290
|
+
formatMs(row.wall.p50),
|
|
3291
|
+
formatMs(row.wall.p90),
|
|
3292
|
+
formatMs(row.stream.p50),
|
|
3293
|
+
formatTps(row.tps.p50),
|
|
3294
|
+
formatTps(row.tps.p90),
|
|
3295
|
+
formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0)
|
|
3296
|
+
], widths, aligns),
|
|
3297
|
+
tone: thin ? "muted" : "base",
|
|
3298
|
+
row: { kind: "model", value: row.key }
|
|
3299
|
+
});
|
|
3300
|
+
}
|
|
3301
|
+
lines.push({ text: "n < 5 is dimmed: too few samples to compare", tone: "muted" });
|
|
3302
|
+
}
|
|
3303
|
+
return lines;
|
|
3304
|
+
}
|
|
3305
|
+
function sessionsLines(rows, width, options) {
|
|
3306
|
+
const limit = options?.limit ?? 20;
|
|
3307
|
+
const estimates = options?.estimates !== false;
|
|
3308
|
+
const widths = [Math.max(18, Math.floor(width * 0.36)), 7, 11, 10, 7, 9, 9];
|
|
3309
|
+
const aligns = ["left", "right", "right", "right", "right", "right", "right"];
|
|
3310
|
+
const lines = [
|
|
3311
|
+
{ text: formatTableRow(["title", "steps", "prompt", "cached", "hit", "out", "cost"], widths, aligns), tone: HEADER_TONE }
|
|
3312
|
+
];
|
|
3313
|
+
const byID = new Map(rows.map((row) => [row.sessionID, row]));
|
|
3314
|
+
const ordered = rows.filter((row) => row.parentID === undefined || !byID.has(row.parentID));
|
|
3315
|
+
const children = rows.filter((row) => row.parentID !== undefined && byID.has(row.parentID));
|
|
3316
|
+
const orderedAll = [...ordered, ...children];
|
|
3317
|
+
for (const row of orderedAll.slice(0, limit)) {
|
|
3318
|
+
const child = row.parentID !== undefined && byID.has(row.parentID);
|
|
3319
|
+
const title = truncate(row.title ?? row.sessionID, Math.max(8, widths[0] - (child ? 2 : 0)));
|
|
3320
|
+
const buckets = usageBuckets(row);
|
|
3321
|
+
lines.push({
|
|
3322
|
+
text: formatTableRow([
|
|
3323
|
+
`${child ? "\u21B3 " : ""}${title}`,
|
|
3324
|
+
formatCount(buckets.steps),
|
|
3325
|
+
formatTokens(buckets.prompt),
|
|
3326
|
+
formatTokens(buckets.cached),
|
|
3327
|
+
formatPercent(buckets.hit, 0),
|
|
3328
|
+
formatTokens(buckets.output),
|
|
3329
|
+
formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
|
|
3330
|
+
], widths, aligns),
|
|
3331
|
+
tone: child ? "muted" : "base",
|
|
3332
|
+
row: { kind: "session", value: row.sessionID }
|
|
3333
|
+
});
|
|
3334
|
+
const details = [
|
|
3335
|
+
row.directory ?? "",
|
|
3336
|
+
row.models.length > 1 ? count(row.models.length, "model") : "",
|
|
3337
|
+
(row.otherCost ?? 0) > 0 ? `other ${formatCost(row.otherCost)}` : ""
|
|
3338
|
+
].filter((part) => part !== "").join(" \xB7 ");
|
|
3339
|
+
lines.push({ text: truncate(`${" ".repeat(child ? 2 : 0)} ${details}`, width), tone: "muted" });
|
|
3340
|
+
}
|
|
3341
|
+
if (options?.rollup !== undefined && options.rollup.subagentSteps > 0) {
|
|
3342
|
+
const share = rows.reduce((sum, row) => sum + row.steps, 0);
|
|
3343
|
+
lines.push({ text: "", tone: "muted" });
|
|
3344
|
+
lines.push({
|
|
3345
|
+
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)}`,
|
|
3346
|
+
tone: "muted"
|
|
3347
|
+
});
|
|
3348
|
+
}
|
|
3349
|
+
if (rows.length > limit)
|
|
3350
|
+
lines.push({ text: `\u2026 ${count(rows.length - limit, "more session")} \xB7 narrow the range`, tone: "muted" });
|
|
3351
|
+
if (rows.length === 0)
|
|
3352
|
+
lines.push({ text: "no sessions recorded for this range", tone: "muted" });
|
|
3353
|
+
return lines;
|
|
3354
|
+
}
|
|
3355
|
+
function dbLines(data, width) {
|
|
3356
|
+
const lines = [];
|
|
3357
|
+
const size = (bytes) => `${(bytes / 1048576).toFixed(1)} MB`;
|
|
3358
|
+
lines.push({ text: truncate(data.info.path, width), tone: "base" });
|
|
3359
|
+
lines.push({
|
|
3360
|
+
text: `${size(data.info.bytes)}${data.info.walBytes === undefined ? "" : ` + ${size(data.info.walBytes)} wal`} \xB7 schema v${data.info.schemaVersion}`,
|
|
3361
|
+
tone: "muted"
|
|
3362
|
+
});
|
|
3363
|
+
lines.push({ text: "", tone: "muted" });
|
|
3364
|
+
lines.push({ text: "what it holds", tone: HEADER_TONE });
|
|
3365
|
+
for (const table of data.info.tables) {
|
|
3366
|
+
lines.push({ text: ` ${padCell(table.name, 12)}${formatCount(table.rows)} rows`, tone: table.rows === 0 ? "muted" : "base" });
|
|
3367
|
+
}
|
|
3368
|
+
lines.push({
|
|
3369
|
+
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")}`,
|
|
3370
|
+
tone: "muted"
|
|
3371
|
+
});
|
|
3372
|
+
lines.push({ text: "", tone: "muted" });
|
|
3373
|
+
lines.push({ text: "clean up", tone: HEADER_TONE });
|
|
3374
|
+
lines.push({
|
|
3375
|
+
text: truncate(` \u2191\u2193 pick a retention \xB7 enter prunes from its cutoff \xB7 the wipe row deletes everything (asks first)${data.estimates === false ? "" : " \xB7 e backfills list estimates"} \xB7 v gives the space back`, width),
|
|
3376
|
+
tone: "muted",
|
|
3377
|
+
hint: true
|
|
3378
|
+
});
|
|
3379
|
+
if (data.estimates !== false) {
|
|
3380
|
+
lines.push({
|
|
3381
|
+
text: truncate(data.info.schemaVersion < 10 ? " list estimates the recorder must upgrade this database first" : data.info.unpriced === 0 ? " list estimates every $0 step has a price" : ` list estimates ${formatCount(data.info.unpriced)} $0 steps without a known price`, width),
|
|
3382
|
+
tone: data.info.schemaVersion < 10 || data.info.unpriced > 0 ? "base" : "muted"
|
|
3383
|
+
});
|
|
3384
|
+
}
|
|
3385
|
+
const widths = [10, 13, 10];
|
|
3386
|
+
lines.push({ text: formatTableRow(["keep", "prunes", "older than"], widths, ["left", "right", "left"]), tone: "muted" });
|
|
3387
|
+
for (const option of data.info.removable) {
|
|
3388
|
+
const before = new Date(data.now - option.days * 24 * 60 * 60 * 1000).toLocaleDateString("en-GB");
|
|
3389
|
+
lines.push({
|
|
3390
|
+
text: formatTableRow([`${option.days} days`, `${formatCount(option.steps)} steps`, before], widths, ["left", "right", "left"]),
|
|
3391
|
+
tone: option.steps === 0 ? "muted" : "base",
|
|
3392
|
+
row: { kind: "prune", value: String(option.days) }
|
|
3393
|
+
});
|
|
3394
|
+
}
|
|
3395
|
+
const steps = data.info.tables.find((table) => table.name === "steps")?.rows ?? 0;
|
|
3396
|
+
const sessions = data.info.tables.find((table) => table.name === "sessions")?.rows ?? 0;
|
|
3397
|
+
lines.push({ text: "", tone: "muted" });
|
|
3398
|
+
lines.push({
|
|
3399
|
+
text: truncate(` wipe everything \xB7 ${formatCount(steps)} steps \xB7 ${formatCount(sessions)} sessions \xB7 cannot be undone`, width),
|
|
3400
|
+
tone: steps === 0 && sessions === 0 ? "muted" : "warning",
|
|
3401
|
+
row: { kind: "wipe", value: "all" }
|
|
3402
|
+
});
|
|
3403
|
+
if (data.busy === true) {
|
|
3404
|
+
lines.push({ text: "", tone: "muted" });
|
|
3405
|
+
lines.push({ text: "the recorder is writing: try the vacuum again in a moment", tone: "warning" });
|
|
3406
|
+
}
|
|
3407
|
+
return lines;
|
|
3408
|
+
}
|
|
3409
|
+
function turnStats(turn) {
|
|
3410
|
+
return {
|
|
3411
|
+
endAt: turn.endAt,
|
|
3412
|
+
startAt: turn.promptAt ?? turn.endAt,
|
|
3413
|
+
promptAt: turn.promptAt,
|
|
3414
|
+
promptGapMs: turn.promptGapMs,
|
|
3415
|
+
providerID: turn.providerID,
|
|
3416
|
+
modelID: turn.modelID,
|
|
3417
|
+
variant: turn.variant,
|
|
3418
|
+
providerChanged: turn.providerChanged,
|
|
3419
|
+
modelChanged: turn.modelChanged,
|
|
3420
|
+
totals: turn.totals,
|
|
3421
|
+
latest: turn.latest,
|
|
3422
|
+
session: undefined,
|
|
3423
|
+
drops: turn.drops.map((drop) => ({ messageID: drop.messageID, tokens: drop.tokens, prevCached: 0, gapMs: drop.gapMs })),
|
|
3424
|
+
cacheDropTokens: turn.drops.reduce((sum, drop) => sum + drop.tokens, 0),
|
|
3425
|
+
cacheExpired: turn.drops.length > 0,
|
|
3426
|
+
steps: turn.steps
|
|
3427
|
+
};
|
|
3428
|
+
}
|
|
3429
|
+
function turnsLines(rows, width, options) {
|
|
3430
|
+
const lines = [];
|
|
3431
|
+
const warning = rows.filter((turn) => turn.drops.length > 0).length;
|
|
3432
|
+
lines.push({
|
|
3433
|
+
text: `${count(rows.length, "turn")} \xB7 newest first${warning > 0 ? ` \xB7 ${count(warning, "turn")} with a cache loss` : ""}`,
|
|
3434
|
+
tone: "muted"
|
|
3435
|
+
});
|
|
3436
|
+
const showSession = options?.sessionTitles !== undefined;
|
|
3437
|
+
for (const turn of rows) {
|
|
3438
|
+
const line = formatLine(turnStats(turn), {
|
|
3439
|
+
...options,
|
|
3440
|
+
fields: { ...options?.fields, session: false }
|
|
3441
|
+
});
|
|
3442
|
+
const title = showSession ? `${truncate(options.sessionTitles.get(turn.sessionID) ?? turn.sessionID, 18)} ` : "";
|
|
3443
|
+
lines.push({
|
|
3444
|
+
text: truncate(`${title}${line}`, width),
|
|
3445
|
+
tone: turn.drops.length > 0 || turn.providerChanged ? "warning" : "base",
|
|
3446
|
+
row: { kind: "turn", value: turn.sessionID }
|
|
3447
|
+
});
|
|
3448
|
+
}
|
|
3449
|
+
if (rows.length === 0)
|
|
3450
|
+
lines.push({ text: "no finished turns for this range", tone: "muted" });
|
|
3451
|
+
return lines;
|
|
3452
|
+
}
|
|
3453
|
+
function sessionSummaryLines(usage, budget = 34, estimates = true) {
|
|
3454
|
+
const buckets = usageBuckets(usage);
|
|
3455
|
+
const steps = formatCount(buckets.steps);
|
|
3456
|
+
const input = formatTokens(buckets.input);
|
|
3457
|
+
const cached = formatTokens(buckets.cached);
|
|
3458
|
+
const out = formatTokens(buckets.output);
|
|
3459
|
+
const hit = formatPercent(buckets.hit);
|
|
3460
|
+
const tps = formatTpsCompact(usage.tps);
|
|
3461
|
+
const cost = (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost);
|
|
3462
|
+
const first = [
|
|
3463
|
+
` ${steps} steps \xB7 in ${input}`,
|
|
3464
|
+
` ${steps} steps`
|
|
3465
|
+
].find((text) => text.length <= budget);
|
|
3466
|
+
const second = [
|
|
3467
|
+
` cached ${cached} \xB7 out ${out}`,
|
|
3468
|
+
` cached ${cached}`
|
|
3469
|
+
].find((text) => text.length <= budget);
|
|
3470
|
+
const last = [
|
|
3471
|
+
` hit ${hit} \xB7 ${tps} \xB7 ${cost}`,
|
|
3472
|
+
` hit ${hit} \xB7 ${cost}`,
|
|
3473
|
+
` ${cost}`
|
|
3474
|
+
].find((text) => text.length <= budget);
|
|
3475
|
+
return [
|
|
3476
|
+
{ text: truncate("session", budget), tone: HEADER_TONE },
|
|
3477
|
+
{ text: truncate(first ?? ` ${steps} steps`, budget), tone: "muted" },
|
|
3478
|
+
{ text: truncate(second ?? ` cached ${cached}`, budget), tone: "base" },
|
|
3479
|
+
{ text: truncate(last ?? ` ${cost}`, budget), tone: "base" },
|
|
3480
|
+
{ text: "", tone: "muted" }
|
|
3481
|
+
];
|
|
3482
|
+
}
|
|
3483
|
+
function sidebarLines(rows, options) {
|
|
3484
|
+
const budget = options?.budget ?? 34;
|
|
3485
|
+
const labels = { input: options?.labels?.input ?? "in", output: options?.labels?.output ?? "out" };
|
|
3486
|
+
const lines = [];
|
|
3487
|
+
for (const [index, turn] of rows.entries()) {
|
|
3488
|
+
const clock = turn.endAt !== undefined ? formatClock(turn.endAt).slice(0, 5) : "--:--";
|
|
3489
|
+
const provider = turn.providerID ?? "unknown";
|
|
3490
|
+
const display = displayTotals(turn.latest);
|
|
3491
|
+
const input = formatTokens(display.input);
|
|
3492
|
+
const prompt = formatTokens(display.prompt);
|
|
3493
|
+
const output = formatTokens(display.output);
|
|
3494
|
+
const cost = options?.estimates === false ? formatCost(turn.totals.cost) : formatMoney(turn.totals.cost, turn.totals.listCost) ?? formatCost(turn.totals.cost);
|
|
3495
|
+
const hit = formatPercent(display.prompt > 0 ? display.cached / display.prompt : undefined).replace(/\.0%$/, "%");
|
|
3496
|
+
const tps = turn.tps === undefined ? undefined : formatTpsCompact(turn.tps);
|
|
3497
|
+
const suffix = turn.drops.length > 0 ? " \xB7 \u26A0" : "";
|
|
3498
|
+
const header = `${clock} ${provider}`;
|
|
3499
|
+
const timed = turn.durationMs === undefined ? undefined : `${header} \xB7 ${formatMs(turn.durationMs)}`;
|
|
3500
|
+
const volumes = [
|
|
3501
|
+
` ${labels.input} ${input} (${prompt}) \xB7 ${labels.output} ${output}`,
|
|
3502
|
+
` ${labels.input} ${input} \xB7 ${labels.output} ${output}`,
|
|
3503
|
+
` ${labels.input} ${input}`
|
|
3504
|
+
];
|
|
3505
|
+
const facts = [
|
|
3506
|
+
` hit ${hit}${tps === undefined ? "" : ` \xB7 ${tps}`} \xB7 ${cost}${suffix}`,
|
|
3507
|
+
` hit ${hit}${tps === undefined ? "" : ` \xB7 ${tps}`}${suffix}`,
|
|
3508
|
+
` ${tps === undefined ? "" : `${tps} \xB7 `}${cost}${suffix}`,
|
|
3509
|
+
` hit ${hit}${suffix}`
|
|
3510
|
+
];
|
|
3511
|
+
lines.push({ text: truncate(timed !== undefined && timed.length <= budget ? timed : header, budget), tone: turn.providerChanged ? "warning" : "base" });
|
|
3512
|
+
const edge = index === 0 || index === rows.length - 1;
|
|
3513
|
+
if (edge || turn.modelChanged || turn.providerChanged) {
|
|
3514
|
+
const model = turn.modelID === undefined ? "unknown" : `${turn.modelID}${turn.variant === undefined ? "" : ` ${turn.variant}`}`;
|
|
3515
|
+
lines.push({ text: truncate(` ${model}`, budget), tone: "muted" });
|
|
3516
|
+
}
|
|
3517
|
+
lines.push({
|
|
3518
|
+
text: truncate(volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1], budget),
|
|
3519
|
+
tone: "muted"
|
|
3520
|
+
});
|
|
3521
|
+
lines.push({
|
|
3522
|
+
text: truncate(facts.find((text) => text.length <= budget) ?? facts[facts.length - 1], budget),
|
|
3523
|
+
tone: turn.drops.length > 0 ? "warning" : "muted"
|
|
3524
|
+
});
|
|
3525
|
+
}
|
|
3526
|
+
if (rows.length === 0)
|
|
3527
|
+
lines.push({ text: "no finished turns yet", tone: "muted" });
|
|
3528
|
+
return lines;
|
|
3529
|
+
}
|
|
3530
|
+
|
|
3531
|
+
// src/panel-build.ts
|
|
3532
|
+
function detailLabel(row) {
|
|
3533
|
+
switch (row.kind) {
|
|
3534
|
+
case "model":
|
|
3535
|
+
return `model ${row.variant !== undefined ? `${row.value} ${row.variant}` : row.value}`;
|
|
3536
|
+
case "session":
|
|
3537
|
+
case "turn":
|
|
3538
|
+
return `session ${row.value}`;
|
|
3539
|
+
case "period":
|
|
3540
|
+
return `period ${row.value}`;
|
|
3541
|
+
case "provider":
|
|
3542
|
+
return `provider ${row.value}`;
|
|
3543
|
+
case "prune":
|
|
3544
|
+
return `prune older than ${row.value} days`;
|
|
3545
|
+
case "wipe":
|
|
3546
|
+
return "wipe all recorded usage";
|
|
3547
|
+
}
|
|
3548
|
+
}
|
|
3549
|
+
function buildPanel(request) {
|
|
3550
|
+
try {
|
|
3551
|
+
return build(request);
|
|
3552
|
+
} catch (error) {
|
|
3553
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
3554
|
+
return [{ text: `stats query failed: ${message}`, tone: "warning" }];
|
|
3555
|
+
}
|
|
3556
|
+
}
|
|
3557
|
+
function build(request) {
|
|
3558
|
+
const { db, view, now, sessionStart, width } = request;
|
|
3559
|
+
const estimates = request.estimates !== false;
|
|
3560
|
+
const scoped = request.range === "session" && request.sessionID !== "";
|
|
3561
|
+
const range = scoped ? undefined : request.range === "session" ? sessionStart === undefined ? undefined : { from: sessionStart } : rangeForRequest(request.range, now);
|
|
3562
|
+
const filters = scoped ? { ...request.filters, sessionID: request.sessionID } : request.filters;
|
|
3563
|
+
if (request.detail !== undefined)
|
|
3564
|
+
return buildDetail(request, range, filters, estimates);
|
|
3565
|
+
switch (view) {
|
|
3566
|
+
case "overview": {
|
|
3567
|
+
const usage = overview(db, range, filters);
|
|
3568
|
+
const sessionUsage = request.sessionID === "" ? undefined : overview(db, undefined, { ...request.filters, sessionID: request.sessionID });
|
|
3569
|
+
const childIDs = request.sessionID === "" ? [] : childSessionIDs(db, request.sessionID);
|
|
3570
|
+
const children = childIDs.length === 0 ? [] : sessionUsageOf(db, childIDs);
|
|
3571
|
+
return overviewLines({
|
|
3572
|
+
usage,
|
|
3573
|
+
session: sessionUsage,
|
|
3574
|
+
...children.length > 0 ? { subagents: children } : {},
|
|
3575
|
+
range: request.range,
|
|
3576
|
+
activity: activityOf(db, range, filters, now),
|
|
3577
|
+
coverage: coverageOf(db, { range, filters }),
|
|
3578
|
+
estimates
|
|
3579
|
+
}, width);
|
|
3580
|
+
}
|
|
3581
|
+
case "models": {
|
|
3582
|
+
const rows = sortModels(models(db, range, filters), request.sort, request.sortDesc, estimates);
|
|
3583
|
+
const pairs = cachePairs(db, { range, filters });
|
|
3584
|
+
const switches = switchesOf(pairs);
|
|
3585
|
+
return modelsLines(rows, width, {
|
|
3586
|
+
cache: cacheByModel(pairs),
|
|
3587
|
+
switches: switchesByModel(switches.rows)
|
|
3588
|
+
}, 40, estimates);
|
|
3589
|
+
}
|
|
3590
|
+
case "providers":
|
|
3591
|
+
return providerSummaryLines(sortProviders(providerSummaryOf(stepRows(db, { range, filters })), request.sort, request.sortDesc, estimates), width, 40, estimates);
|
|
3592
|
+
case "cache": {
|
|
3593
|
+
const pairs = cachePairs(db, { range, filters });
|
|
3594
|
+
return cacheLines({
|
|
3595
|
+
drops: cacheDropsOf(db, pairs),
|
|
3596
|
+
evidence: ttlEvidenceOf(pairs),
|
|
3597
|
+
gap: gapReportOf(pairs),
|
|
3598
|
+
models: topCacheModels(pairs)
|
|
3599
|
+
}, width);
|
|
3600
|
+
}
|
|
3601
|
+
case "periods": {
|
|
3602
|
+
const rows = periodsOf(stepRows(db, { range, filters }), request.granularity, otherUsageRows(db, range, filters));
|
|
3603
|
+
const sessions = overview(db, range, filters).sessions;
|
|
3604
|
+
return periodLines(rows, width, request.granularity, 40, estimates, sessions);
|
|
3605
|
+
}
|
|
3606
|
+
case "latency": {
|
|
3607
|
+
const timings = timingRows(db, { range, filters });
|
|
3608
|
+
const by = filters.modelID !== undefined ? "provider" : "model";
|
|
3609
|
+
return latencyLines(latencyOf(timings), width, sortLatency(latencyGroupsOf(timings, by), request.sort, request.sortDesc), 14, estimates);
|
|
3610
|
+
}
|
|
3611
|
+
case "sessions": {
|
|
3612
|
+
const rows = sortSessions(sessions(db, { range, filters, limit: 200 }), request.sort, request.sortDesc, estimates);
|
|
3613
|
+
const child = rows.filter((row) => row.parentID !== undefined && rows.some((parent) => parent.sessionID === row.parentID));
|
|
3614
|
+
return sessionsLines(rows, width, {
|
|
3615
|
+
limit: 20,
|
|
3616
|
+
estimates,
|
|
3617
|
+
rollup: {
|
|
3618
|
+
subagentSteps: child.reduce((sum, row) => sum + row.steps, 0),
|
|
3619
|
+
subagentCost: child.reduce((sum, row) => sum + row.cost, 0),
|
|
3620
|
+
subagentListCost: child.reduce((sum, row) => sum + row.listCost, 0)
|
|
3621
|
+
}
|
|
3622
|
+
});
|
|
3623
|
+
}
|
|
3624
|
+
case "db":
|
|
3625
|
+
return request.database === undefined ? [{ text: "the database location is unavailable to this panel", tone: "warning" }] : dbLines({ info: request.database, busy: request.busy, now, estimates }, width);
|
|
3626
|
+
case "go":
|
|
3627
|
+
return [
|
|
3628
|
+
{
|
|
3629
|
+
text: "OpenCode Go quota is read by the TUI and Desktop from the host; it is not stored in this database.",
|
|
3630
|
+
tone: "muted"
|
|
3631
|
+
}
|
|
3632
|
+
];
|
|
3633
|
+
case "turns": {
|
|
3634
|
+
const sessionID = request.turnsScope === "session" ? request.sessionID : undefined;
|
|
3635
|
+
const rows = sortTurns(turns(db, { sessionID, range, filters, limit: 300 }), request.sort, request.sortDesc, estimates);
|
|
3636
|
+
const titles = request.turnsScope === "all" ? new Map(sessions(db, { range, filters, limit: 200 }).map((row) => [row.sessionID, row.title ?? row.sessionID])) : undefined;
|
|
3637
|
+
return turnsLines(rows.slice(0, 60), width, { ...request.format, estimates, sessionTitles: titles });
|
|
3638
|
+
}
|
|
3639
|
+
}
|
|
3640
|
+
}
|
|
3641
|
+
function rangeForRequest(key, now) {
|
|
3642
|
+
switch (key) {
|
|
3643
|
+
case "today": {
|
|
3644
|
+
const start = new Date(now);
|
|
3645
|
+
start.setHours(0, 0, 0, 0);
|
|
3646
|
+
return { from: start.getTime() };
|
|
3647
|
+
}
|
|
3648
|
+
case "7d":
|
|
3649
|
+
return { from: now - 7 * 24 * 60 * 60 * 1000 };
|
|
3650
|
+
case "30d":
|
|
3651
|
+
return { from: now - 30 * 24 * 60 * 60 * 1000 };
|
|
3652
|
+
default:
|
|
3653
|
+
return;
|
|
3654
|
+
}
|
|
3655
|
+
}
|
|
3656
|
+
function buildDetail(request, range, filters, estimates) {
|
|
3657
|
+
const row = request.detail;
|
|
3658
|
+
const db = request.db;
|
|
3659
|
+
const width = request.width;
|
|
3660
|
+
const head = { text: detailLabel(row), tone: "accent" };
|
|
3661
|
+
const back = { text: "backspace returns \xB7 the header shows where you came from", tone: "muted" };
|
|
3662
|
+
if (row.kind === "model") {
|
|
3663
|
+
const scoped = { ...filters, modelKey: modelKey(row.value, row.variant) };
|
|
3664
|
+
const stats = cacheStatsOf(db, { range, filters: scoped });
|
|
3665
|
+
const steps = stepRows(db, { range, filters: scoped });
|
|
3666
|
+
return [
|
|
3667
|
+
head,
|
|
3668
|
+
{
|
|
3669
|
+
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)}`,
|
|
3670
|
+
tone: "muted"
|
|
3671
|
+
},
|
|
3672
|
+
{ text: "", tone: "muted" },
|
|
3673
|
+
...providerLines(providerBreakdownOf(steps), width, 40, estimates),
|
|
3674
|
+
{ text: "", tone: "muted" },
|
|
3675
|
+
...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, "provider"), 14, estimates),
|
|
3676
|
+
{ text: "", tone: "muted" },
|
|
3677
|
+
back
|
|
3678
|
+
];
|
|
3679
|
+
}
|
|
3680
|
+
if (row.kind === "session" || row.kind === "turn") {
|
|
3681
|
+
const rows = turns(db, { sessionID: row.value, limit: 80 });
|
|
3682
|
+
return [head, { text: "", tone: "muted" }, ...turnsLines(rows, width, { ...request.format, estimates }), { text: "", tone: "muted" }, back];
|
|
3683
|
+
}
|
|
3684
|
+
if (row.kind === "provider") {
|
|
3685
|
+
const scoped = { ...filters, provider: row.value };
|
|
3686
|
+
const steps = stepRows(db, { range, filters: scoped });
|
|
3687
|
+
const stats = cacheStatsOf(db, { range, filters: scoped });
|
|
3688
|
+
return [
|
|
3689
|
+
head,
|
|
3690
|
+
{
|
|
3691
|
+
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)}`,
|
|
3692
|
+
tone: "muted"
|
|
3693
|
+
},
|
|
3694
|
+
{ text: "", tone: "muted" },
|
|
3695
|
+
...providerLines(providerBreakdownOf(steps), width, 40, estimates),
|
|
3696
|
+
{ text: "", tone: "muted" },
|
|
3697
|
+
...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, "model"), 14, estimates),
|
|
3698
|
+
{ text: "", tone: "muted" },
|
|
3699
|
+
back
|
|
3700
|
+
];
|
|
3701
|
+
}
|
|
3702
|
+
if (row.kind === "period") {
|
|
3703
|
+
const periods = periodsOf(stepRows(db, { range, filters }), request.granularity);
|
|
3704
|
+
const period = periods.find((entry) => entry.key === row.value);
|
|
3705
|
+
const from = period === undefined ? 0 : Math.max(period.at, range?.from ?? period.at);
|
|
3706
|
+
const to = period === undefined ? 0 : Math.min(periodEnd(period.at, request.granularity), range?.to ?? Number.POSITIVE_INFINITY);
|
|
3707
|
+
const steps = period === undefined ? [] : stepRows(db, { range: { from, to }, filters });
|
|
3708
|
+
return [
|
|
3709
|
+
head,
|
|
3710
|
+
{ text: `${formatCount(period?.steps ?? 0)} steps`, tone: "muted" },
|
|
3711
|
+
{ text: "", tone: "muted" },
|
|
3712
|
+
...providerSummaryLines(providerSummaryOf(steps), width, 40, estimates),
|
|
3713
|
+
{ text: "", tone: "muted" },
|
|
3714
|
+
back
|
|
3715
|
+
];
|
|
3716
|
+
}
|
|
3717
|
+
return [head, back];
|
|
3718
|
+
}
|
|
3719
|
+
function percent(value) {
|
|
3720
|
+
return value === undefined ? "\u2013" : `${(value * 100).toFixed(1)}%`;
|
|
3721
|
+
}
|
|
3722
|
+
function sortModels(rows, sort, desc, estimates = true) {
|
|
3723
|
+
const sign = desc ? 1 : -1;
|
|
3724
|
+
const pick = (model) => {
|
|
3725
|
+
if (sort === "cached")
|
|
3726
|
+
return model.totals.cached;
|
|
3727
|
+
if (sort === "hit") {
|
|
3728
|
+
const prompt = model.totals.input + model.totals.cached + model.totals.cacheWrite;
|
|
3729
|
+
return prompt > 0 ? model.totals.cached / prompt : -1;
|
|
3730
|
+
}
|
|
3731
|
+
if (sort === "out")
|
|
3732
|
+
return model.totals.output + model.totals.reasoning;
|
|
3733
|
+
if (sort === "cost")
|
|
3734
|
+
return estimates ? spend(model.totals) : model.totals.cost;
|
|
3735
|
+
return model.totals.steps;
|
|
3736
|
+
};
|
|
3737
|
+
return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
|
|
3738
|
+
}
|
|
3739
|
+
function sortProviders(rows, sort, desc, estimates = true) {
|
|
3740
|
+
const sign = desc ? 1 : -1;
|
|
3741
|
+
const pick = (row) => {
|
|
3742
|
+
if (sort === "cached")
|
|
3743
|
+
return row.cache.cached;
|
|
3744
|
+
if (sort === "hit")
|
|
3745
|
+
return row.cache.hit ?? -1;
|
|
3746
|
+
if (sort === "cost")
|
|
3747
|
+
return estimates ? spend(row.usage) : row.usage.cost;
|
|
3748
|
+
if (sort === "share")
|
|
3749
|
+
return row.share;
|
|
3750
|
+
if (sort === "tps")
|
|
3751
|
+
return row.tps ?? -1;
|
|
3752
|
+
return row.usage.steps;
|
|
3753
|
+
};
|
|
3754
|
+
return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
|
|
3755
|
+
}
|
|
3756
|
+
function sortLatency(rows, sort, desc) {
|
|
3757
|
+
const sign = desc ? 1 : -1;
|
|
3758
|
+
const pick = (row) => {
|
|
3759
|
+
if (sort === "tps")
|
|
3760
|
+
return row.tps.p50 ?? -1;
|
|
3761
|
+
if (sort === "wall")
|
|
3762
|
+
return row.wall.p50 ?? -1;
|
|
3763
|
+
return row.count;
|
|
3764
|
+
};
|
|
3765
|
+
return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
|
|
3766
|
+
}
|
|
3767
|
+
function sortSessions(rows, sort, desc, estimates = true) {
|
|
3768
|
+
const sign = desc ? 1 : -1;
|
|
3769
|
+
const pick = (row) => {
|
|
3770
|
+
if (sort === "steps")
|
|
3771
|
+
return row.steps;
|
|
3772
|
+
if (sort === "cached")
|
|
3773
|
+
return row.cached;
|
|
3774
|
+
if (sort === "cost")
|
|
3775
|
+
return estimates ? spend(row) : row.cost;
|
|
3776
|
+
return row.lastAt ?? 0;
|
|
3777
|
+
};
|
|
3778
|
+
return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
|
|
3779
|
+
}
|
|
3780
|
+
function sortTurns(rows, sort, desc, estimates = true) {
|
|
3781
|
+
const sign = desc ? 1 : -1;
|
|
3782
|
+
const pick = (row) => {
|
|
3783
|
+
if (sort === "cost")
|
|
3784
|
+
return estimates ? spend(row.totals) : row.totals.cost;
|
|
3785
|
+
if (sort === "tokens")
|
|
3786
|
+
return row.totals.cached + row.totals.input + row.totals.cacheWrite + row.totals.output + row.totals.reasoning;
|
|
3787
|
+
return row.endAt ?? 0;
|
|
3788
|
+
};
|
|
3789
|
+
return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
|
|
3790
|
+
}
|
|
3791
|
+
function cacheByModel(pairs) {
|
|
3792
|
+
const map = new Map;
|
|
3793
|
+
for (const row of cacheStatsByModel(pairs)) {
|
|
3794
|
+
map.set(modelKey(row.modelID, row.variant), row.cache);
|
|
3795
|
+
}
|
|
3796
|
+
return map;
|
|
3797
|
+
}
|
|
3798
|
+
function switchesByModel(rows) {
|
|
3799
|
+
return new Map(rows.map((row) => [modelKey(row.modelID, row.variant), row]));
|
|
3800
|
+
}
|
|
3801
|
+
function topCacheModels(pairs) {
|
|
3802
|
+
return cacheStatsByModel(pairs).slice(0, 10).map((row) => ({ usage: { modelID: row.modelID, variant: row.variant }, cache: row.cache }));
|
|
3803
|
+
}
|
|
3804
|
+
function activityOf(db, range, filters, now) {
|
|
3805
|
+
const filter = buildWhere(range, filters, STEP_TIME);
|
|
3806
|
+
const earliest = db.query(`SELECT MIN(${STEP_TIME}) AS at FROM steps ${filter.where}`).get(...filter.params);
|
|
3807
|
+
const from = range?.from ?? earliest?.at ?? 0;
|
|
3808
|
+
const to = range?.to ?? now;
|
|
3809
|
+
const span = Math.max(1, to - from);
|
|
3810
|
+
const ladder = [3600000, 3 * 3600000, 6 * 3600000, 12 * 3600000, 86400000, 3 * 86400000, 7 * 86400000, 30 * 86400000];
|
|
3811
|
+
const bucket = ladder.find((size) => span / size <= 48) ?? ladder[ladder.length - 1];
|
|
3812
|
+
const rows = db.query(`SELECT CAST(${STEP_TIME} / ? AS INTEGER) AS bucket, COUNT(*) AS steps
|
|
3813
|
+
FROM steps ${filter.where}
|
|
3814
|
+
GROUP BY bucket ORDER BY bucket`).all(bucket, ...filter.params);
|
|
3815
|
+
if (rows.length === 0)
|
|
3816
|
+
return [];
|
|
3817
|
+
const first = Math.floor(from / bucket);
|
|
3818
|
+
const last = rows[rows.length - 1].bucket;
|
|
3819
|
+
const series = [];
|
|
3820
|
+
for (let index = first;index <= last; index += 1) {
|
|
3821
|
+
series.push(rows.find((row) => row.bucket === index)?.steps ?? 0);
|
|
3822
|
+
}
|
|
3823
|
+
return series;
|
|
3824
|
+
}
|
|
3825
|
+
|
|
3826
|
+
// src/stats/maintenance.ts
|
|
3827
|
+
import { statSync as statSync2 } from "fs";
|
|
3828
|
+
var STEP_TIME2 = "COALESCE(created_at, recorded_at)";
|
|
3829
|
+
var DAY = 24 * 60 * 60 * 1000;
|
|
3830
|
+
function size(path) {
|
|
3831
|
+
try {
|
|
3832
|
+
return statSync2(path).size;
|
|
3833
|
+
} catch {
|
|
3834
|
+
return 0;
|
|
3835
|
+
}
|
|
3836
|
+
}
|
|
3837
|
+
function hasTable(db, name) {
|
|
3838
|
+
try {
|
|
3839
|
+
return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== null;
|
|
3840
|
+
} catch {
|
|
3841
|
+
return false;
|
|
3842
|
+
}
|
|
3843
|
+
}
|
|
3844
|
+
function dbInfo(db, path, now = Date.now()) {
|
|
3845
|
+
const tables = TABLES.map((table) => ({
|
|
3846
|
+
name: table,
|
|
3847
|
+
rows: hasTable(db, table) ? db.query(`SELECT COUNT(*) AS n FROM ${table}`).get().n : 0
|
|
3848
|
+
}));
|
|
3849
|
+
const window = db.query(`SELECT MIN(${STEP_TIME2}) AS first, MAX(${STEP_TIME2}) AS last FROM steps`).get();
|
|
3850
|
+
const version = db.query("SELECT value FROM meta WHERE key = 'schema_version'").get();
|
|
3851
|
+
return {
|
|
3852
|
+
path,
|
|
3853
|
+
unpriced: hasListCost(db) ? db.query(`SELECT COUNT(*) AS n FROM steps
|
|
3854
|
+
WHERE cost = 0 AND list_cost IS NULL
|
|
3855
|
+
AND provider_id IS NOT NULL AND provider_id <> ''
|
|
3856
|
+
AND model_id IS NOT NULL AND model_id <> ''
|
|
3857
|
+
AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`).get().n : 0,
|
|
3858
|
+
bytes: size(path),
|
|
3859
|
+
walBytes: path === ":memory:" ? undefined : size(`${path}-wal`) || undefined,
|
|
3860
|
+
schemaVersion: version === null ? 0 : Number.parseInt(version.value, 10),
|
|
3861
|
+
tables,
|
|
3862
|
+
firstAt: window.first ?? undefined,
|
|
3863
|
+
lastAt: window.last ?? undefined,
|
|
3864
|
+
removable: [30, 90, 365].map((days) => ({
|
|
3865
|
+
days,
|
|
3866
|
+
steps: db.query(`SELECT COUNT(*) AS n FROM steps WHERE ${STEP_TIME2} < ?`).get(now - days * DAY).n
|
|
3867
|
+
}))
|
|
3868
|
+
};
|
|
3869
|
+
}
|
|
3870
|
+
var PRUNE_BATCH = 5000;
|
|
3871
|
+
function deleteBatched(db, table, where, cutoff) {
|
|
3872
|
+
const statement = db.query(`DELETE FROM ${table} WHERE rowid IN (SELECT rowid FROM ${table} WHERE ${where} LIMIT ${PRUNE_BATCH})`);
|
|
3873
|
+
let removed = 0;
|
|
3874
|
+
for (;; ) {
|
|
3875
|
+
const changes = statement.run(cutoff).changes;
|
|
3876
|
+
removed += changes;
|
|
3877
|
+
if (changes < PRUNE_BATCH)
|
|
3878
|
+
break;
|
|
3879
|
+
}
|
|
3880
|
+
return removed;
|
|
3881
|
+
}
|
|
3882
|
+
function deleteAllBatched(db, table) {
|
|
3883
|
+
const statement = db.query(`DELETE FROM ${table} WHERE rowid IN (SELECT rowid FROM ${table} LIMIT ${PRUNE_BATCH})`);
|
|
3884
|
+
let removed = 0;
|
|
3885
|
+
for (;; ) {
|
|
3886
|
+
const changes = statement.run().changes;
|
|
3887
|
+
removed += changes;
|
|
3888
|
+
if (changes < PRUNE_BATCH)
|
|
3889
|
+
break;
|
|
3890
|
+
}
|
|
3891
|
+
return removed;
|
|
3892
|
+
}
|
|
3893
|
+
function pruneOlderThan(db, cutoff) {
|
|
3894
|
+
return {
|
|
3895
|
+
steps: deleteBatched(db, "steps", `${STEP_TIME2} < ?`, cutoff),
|
|
3896
|
+
prompts: deleteBatched(db, "prompts", "created_at IS NOT NULL AND created_at < ?", cutoff),
|
|
3897
|
+
events: deleteBatched(db, "events", "at IS NOT NULL AND at < ?", cutoff),
|
|
3898
|
+
usage: hasTable(db, "usage") ? deleteBatched(db, "usage", "at IS NOT NULL AND at < ?", cutoff) : 0
|
|
3899
|
+
};
|
|
3900
|
+
}
|
|
3901
|
+
function wipeAll(db) {
|
|
3902
|
+
return {
|
|
3903
|
+
steps: deleteAllBatched(db, "steps"),
|
|
3904
|
+
prompts: deleteAllBatched(db, "prompts"),
|
|
3905
|
+
events: deleteAllBatched(db, "events"),
|
|
3906
|
+
usage: hasTable(db, "usage") ? deleteAllBatched(db, "usage") : 0,
|
|
3907
|
+
sessions: hasTable(db, "sessions") ? deleteAllBatched(db, "sessions") : 0
|
|
3908
|
+
};
|
|
3909
|
+
}
|
|
3910
|
+
function footprint(path) {
|
|
3911
|
+
return size(path) + size(`${path}-wal`);
|
|
3912
|
+
}
|
|
3913
|
+
function vacuum(db, path) {
|
|
3914
|
+
const before = footprint(path);
|
|
3915
|
+
db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
3916
|
+
db.exec("VACUUM");
|
|
3917
|
+
const after = footprint(path);
|
|
3918
|
+
return { before, after, freed: Math.max(0, before - after) };
|
|
3919
|
+
}
|
|
3920
|
+
function hasListCost(db) {
|
|
3921
|
+
try {
|
|
3922
|
+
return db.query("PRAGMA table_info(steps)").all().some((column) => column.name === "list_cost");
|
|
3923
|
+
} catch {
|
|
3924
|
+
return false;
|
|
3925
|
+
}
|
|
3926
|
+
}
|
|
3927
|
+
var BACKFILL_BATCH = 1000;
|
|
3928
|
+
function backfillListCost(db, price) {
|
|
3929
|
+
if (!hasListCost(db))
|
|
3930
|
+
return { candidates: 0, updated: 0 };
|
|
3931
|
+
const candidates = db.query(`SELECT COUNT(*) AS n FROM steps
|
|
3932
|
+
WHERE cost = 0 AND list_cost IS NULL
|
|
3933
|
+
AND provider_id IS NOT NULL AND provider_id <> ''
|
|
3934
|
+
AND model_id IS NOT NULL AND model_id <> ''
|
|
3935
|
+
AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`).get().n;
|
|
3936
|
+
if (candidates === 0)
|
|
3937
|
+
return { candidates: 0, updated: 0 };
|
|
3938
|
+
const select = db.query(`SELECT rowid, provider_id, model_id,
|
|
3939
|
+
input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
|
|
3940
|
+
FROM steps
|
|
3941
|
+
WHERE cost = 0 AND list_cost IS NULL AND rowid > ?
|
|
3942
|
+
AND provider_id IS NOT NULL AND provider_id <> ''
|
|
3943
|
+
AND model_id IS NOT NULL AND model_id <> ''
|
|
3944
|
+
AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0
|
|
3945
|
+
ORDER BY rowid
|
|
3946
|
+
LIMIT ?`);
|
|
3947
|
+
const update = db.query("UPDATE steps SET list_cost = ? WHERE rowid = ? AND cost = 0 AND list_cost IS NULL");
|
|
3948
|
+
let cursor = 0;
|
|
3949
|
+
let updated = 0;
|
|
3950
|
+
for (;; ) {
|
|
3951
|
+
const rows = select.all(cursor, BACKFILL_BATCH);
|
|
3952
|
+
if (rows.length === 0)
|
|
3953
|
+
break;
|
|
3954
|
+
db.transaction(() => {
|
|
3955
|
+
for (const row of rows) {
|
|
3956
|
+
const estimate = price({ providerID: row.provider_id ?? undefined, modelID: row.model_id ?? undefined }, {
|
|
3957
|
+
input: row.input_tokens ?? 0,
|
|
3958
|
+
output: row.output_tokens ?? 0,
|
|
3959
|
+
reasoning: row.reasoning_tokens ?? 0,
|
|
3960
|
+
cacheRead: row.cache_read ?? 0,
|
|
3961
|
+
cacheWrite: row.cache_write ?? 0
|
|
3962
|
+
});
|
|
3963
|
+
if (estimate === undefined || !Number.isFinite(estimate) || estimate < 0)
|
|
3964
|
+
continue;
|
|
3965
|
+
if (update.run(estimate, row.rowid).changes > 0)
|
|
3966
|
+
updated += 1;
|
|
3967
|
+
}
|
|
3968
|
+
})();
|
|
3969
|
+
cursor = rows[rows.length - 1].rowid;
|
|
3970
|
+
if (rows.length < BACKFILL_BATCH)
|
|
3971
|
+
break;
|
|
3972
|
+
}
|
|
3973
|
+
return { candidates, updated };
|
|
3974
|
+
}
|
|
3975
|
+
|
|
3976
|
+
// src/service.ts
|
|
3977
|
+
var DAY2 = 24 * 60 * 60 * 1000;
|
|
3978
|
+
var MAX_DAYS = 3650;
|
|
3979
|
+
|
|
3980
|
+
class ServiceError extends Error {
|
|
3981
|
+
code;
|
|
3982
|
+
constructor(code, message) {
|
|
3983
|
+
super(message);
|
|
3984
|
+
this.name = "ServiceError";
|
|
3985
|
+
this.code = code;
|
|
3986
|
+
}
|
|
3987
|
+
}
|
|
3988
|
+
function clamp2(value, minimum, maximum) {
|
|
3989
|
+
if (!Number.isFinite(value))
|
|
3990
|
+
return minimum;
|
|
3991
|
+
return Math.min(maximum, Math.max(minimum, Math.round(value)));
|
|
3992
|
+
}
|
|
3993
|
+
function sessionStart(db, sessionID) {
|
|
3994
|
+
const session = db.query("SELECT started_at AS at FROM sessions WHERE session_id = ?").get(sessionID);
|
|
3995
|
+
if (session?.at !== null && session?.at !== undefined)
|
|
3996
|
+
return session.at;
|
|
3997
|
+
const step = db.query("SELECT MIN(COALESCE(created_at, recorded_at)) AS at FROM steps WHERE session_id = ?").get(sessionID);
|
|
3998
|
+
return step?.at ?? undefined;
|
|
3999
|
+
}
|
|
4000
|
+
function redact(info, exposePaths) {
|
|
4001
|
+
if (exposePaths)
|
|
4002
|
+
return info;
|
|
4003
|
+
return { ...info, path: basename(info.path) };
|
|
4004
|
+
}
|
|
4005
|
+
function filtersOf(settings) {
|
|
4006
|
+
return {
|
|
4007
|
+
...settings.modelID !== "" ? { modelID: settings.modelID } : {},
|
|
4008
|
+
...settings.providerID !== "" ? { provider: settings.providerID } : {}
|
|
4009
|
+
};
|
|
4010
|
+
}
|
|
4011
|
+
function writeDb(path, run) {
|
|
4012
|
+
let db;
|
|
4013
|
+
try {
|
|
4014
|
+
db = openStatsDbWrite(path);
|
|
4015
|
+
return run(db);
|
|
4016
|
+
} catch (error) {
|
|
4017
|
+
if (error instanceof ServiceError)
|
|
4018
|
+
throw error;
|
|
4019
|
+
throw new ServiceError("busy", "the database is busy; try again in a moment");
|
|
4020
|
+
} finally {
|
|
4021
|
+
db?.close();
|
|
4022
|
+
}
|
|
4023
|
+
}
|
|
4024
|
+
function createService(db, options) {
|
|
4025
|
+
const settingsOf = (input) => sanitizeSettings(input.settings);
|
|
4026
|
+
function infoOf() {
|
|
4027
|
+
return redact(dbInfo(db(), options.path), options.exposePaths);
|
|
4028
|
+
}
|
|
4029
|
+
function panel(input) {
|
|
4030
|
+
const settings = settingsOf(input);
|
|
4031
|
+
const database = settings.view === "db" ? infoOf() : undefined;
|
|
4032
|
+
const width = clampPanelWidth(input.width);
|
|
4033
|
+
const filters = filtersOf(settings);
|
|
4034
|
+
const request = {
|
|
4035
|
+
db: db(),
|
|
4036
|
+
view: settings.view,
|
|
4037
|
+
range: settings.range,
|
|
4038
|
+
filters,
|
|
4039
|
+
granularity: settings.granularity,
|
|
4040
|
+
turnsScope: settings.turnsScope,
|
|
4041
|
+
sort: settings.sort === "" ? defaultSort(settings.view) : settings.sort,
|
|
4042
|
+
sortDesc: settings.sortDesc,
|
|
4043
|
+
sessionID: input.sessionID,
|
|
4044
|
+
sessionStart: sessionStart(db(), input.sessionID),
|
|
4045
|
+
now: Date.now(),
|
|
4046
|
+
format: { ...options.format, estimates: options.pricing },
|
|
4047
|
+
estimates: options.pricing,
|
|
4048
|
+
...input.detail !== undefined ? { detail: input.detail } : {},
|
|
4049
|
+
...database !== undefined ? { database } : {},
|
|
4050
|
+
busy: input.busy === true,
|
|
4051
|
+
width
|
|
4052
|
+
};
|
|
4053
|
+
return { lines: buildPanel(request), ...database !== undefined ? { database } : {} };
|
|
4054
|
+
}
|
|
4055
|
+
function turnHistory(input) {
|
|
4056
|
+
const handle = db();
|
|
4057
|
+
const width = clamp2(input.width, 20, 120);
|
|
4058
|
+
const limit = clampTurnsLimit(input.limit);
|
|
4059
|
+
const summary = sessionSummaryLines(overview(handle, undefined, { sessionID: input.sessionID }), width, options.pricing);
|
|
4060
|
+
const history = sidebarLines(turns(handle, { sessionID: input.sessionID, limit }), {
|
|
4061
|
+
...options.format,
|
|
4062
|
+
estimates: options.pricing,
|
|
4063
|
+
budget: width
|
|
4064
|
+
});
|
|
4065
|
+
return { summary, history };
|
|
4066
|
+
}
|
|
4067
|
+
function listCost(input) {
|
|
4068
|
+
if (!options.pricing)
|
|
4069
|
+
return { cost: 0 };
|
|
4070
|
+
return { cost: sessionListCost(db(), input.sessionID) };
|
|
4071
|
+
}
|
|
4072
|
+
function filters() {
|
|
4073
|
+
return filterOptions(db());
|
|
4074
|
+
}
|
|
4075
|
+
function requireMaintenance() {
|
|
4076
|
+
if (!options.maintenance)
|
|
4077
|
+
throw new ServiceError("disabled", "database maintenance is disabled");
|
|
4078
|
+
}
|
|
4079
|
+
function requireConfirm(confirm) {
|
|
4080
|
+
if (confirm !== true)
|
|
4081
|
+
throw new ServiceError("invalid", "confirmation is required");
|
|
4082
|
+
}
|
|
4083
|
+
function prune(input) {
|
|
4084
|
+
requireMaintenance();
|
|
4085
|
+
requireConfirm(input.confirm);
|
|
4086
|
+
const days = clamp2(input.days, 1, MAX_DAYS);
|
|
4087
|
+
return writeDb(options.path, (handle) => pruneOlderThan(handle, Date.now() - days * DAY2));
|
|
4088
|
+
}
|
|
4089
|
+
function wipe(input) {
|
|
4090
|
+
requireMaintenance();
|
|
4091
|
+
requireConfirm(input.confirm);
|
|
4092
|
+
return writeDb(options.path, (handle) => wipeAll(handle));
|
|
4093
|
+
}
|
|
4094
|
+
function compact(input) {
|
|
4095
|
+
requireMaintenance();
|
|
4096
|
+
requireConfirm(input.confirm);
|
|
4097
|
+
return writeDb(options.path, (handle) => vacuum(handle, options.path));
|
|
4098
|
+
}
|
|
4099
|
+
function backfill(input, table) {
|
|
4100
|
+
if (!options.pricing)
|
|
4101
|
+
throw new ServiceError("disabled", "list-price estimates are turned off");
|
|
4102
|
+
requireMaintenance();
|
|
4103
|
+
requireConfirm(input.confirm);
|
|
4104
|
+
const prices = table ?? options.priceTable?.();
|
|
4105
|
+
if (prices === undefined)
|
|
4106
|
+
throw new ServiceError("unavailable", "the model catalog is unavailable");
|
|
4107
|
+
return writeDb(options.path, (handle) => backfillListCost(handle, (ref, tokens) => costOf(prices, ref, tokens)));
|
|
4108
|
+
}
|
|
4109
|
+
return {
|
|
4110
|
+
panel,
|
|
4111
|
+
turnHistory,
|
|
4112
|
+
listCost,
|
|
4113
|
+
filters,
|
|
4114
|
+
dbInfo: infoOf,
|
|
4115
|
+
prune,
|
|
4116
|
+
wipe,
|
|
4117
|
+
compact,
|
|
4118
|
+
backfill
|
|
4119
|
+
};
|
|
4120
|
+
}
|
|
4121
|
+
|
|
4122
|
+
// src/stats-client.ts
|
|
4123
|
+
import { existsSync } from "fs";
|
|
4124
|
+
import { fileURLToPath } from "url";
|
|
4125
|
+
|
|
4126
|
+
class StatsError extends Error {
|
|
4127
|
+
code;
|
|
4128
|
+
constructor(code, message) {
|
|
4129
|
+
super(message);
|
|
4130
|
+
this.name = "StatsError";
|
|
4131
|
+
this.code = code;
|
|
4132
|
+
}
|
|
4133
|
+
}
|
|
4134
|
+
var QUEUE_LIMIT = 8;
|
|
4135
|
+
var READ_TIMEOUT_MS = 1e4;
|
|
4136
|
+
var MAINTENANCE_TIMEOUT_MS = 5 * 60000;
|
|
4137
|
+
var START_TIMEOUT_MS = 5000;
|
|
4138
|
+
var MAINTENANCE_METHODS = new Set(["prune", "wipe", "vacuum", "backfill"]);
|
|
4139
|
+
function defaultWorkerUrl() {
|
|
4140
|
+
try {
|
|
4141
|
+
const js = new URL("./stats-worker.js", import.meta.url);
|
|
4142
|
+
if (existsSync(fileURLToPath(js)))
|
|
4143
|
+
return js;
|
|
4144
|
+
const ts = new URL("./stats-worker.ts", import.meta.url);
|
|
4145
|
+
if (existsSync(fileURLToPath(ts)))
|
|
4146
|
+
return ts;
|
|
4147
|
+
} catch {}
|
|
4148
|
+
return;
|
|
4149
|
+
}
|
|
4150
|
+
|
|
4151
|
+
class StatsClient {
|
|
4152
|
+
config;
|
|
4153
|
+
worker;
|
|
4154
|
+
startPromise;
|
|
4155
|
+
starting;
|
|
4156
|
+
startAbort;
|
|
4157
|
+
fallbackService;
|
|
4158
|
+
fallbackMode = false;
|
|
4159
|
+
stopped = false;
|
|
4160
|
+
nextID = 1;
|
|
4161
|
+
pending = new Map;
|
|
4162
|
+
constructor(config) {
|
|
4163
|
+
this.config = config;
|
|
4164
|
+
}
|
|
4165
|
+
request(method, input, options = {}) {
|
|
4166
|
+
if (this.stopped)
|
|
4167
|
+
return Promise.reject(new StatsError("unavailable", "the usage service is stopped"));
|
|
4168
|
+
if (this.fallbackMode)
|
|
4169
|
+
return Promise.resolve().then(() => this.callService(method, input));
|
|
4170
|
+
return this.ensureWorker().then(() => {
|
|
4171
|
+
if (this.stopped)
|
|
4172
|
+
throw new StatsError("unavailable", "the usage service is stopped");
|
|
4173
|
+
if (this.fallbackMode)
|
|
4174
|
+
return this.callService(method, input);
|
|
4175
|
+
if (this.pending.size >= QUEUE_LIMIT)
|
|
4176
|
+
throw new StatsError("busy", "too many usage requests are already running");
|
|
4177
|
+
return this.send(method, input, options.signal);
|
|
4178
|
+
});
|
|
4179
|
+
}
|
|
4180
|
+
stop() {
|
|
4181
|
+
if (this.stopped)
|
|
4182
|
+
return;
|
|
4183
|
+
this.stopped = true;
|
|
4184
|
+
this.rejectAll(new StatsError("unavailable", "the usage service stopped"));
|
|
4185
|
+
this.startAbort?.();
|
|
4186
|
+
this.worker?.terminate();
|
|
4187
|
+
this.worker = undefined;
|
|
4188
|
+
this.starting = undefined;
|
|
4189
|
+
this.startPromise = undefined;
|
|
4190
|
+
}
|
|
4191
|
+
callService(method, input) {
|
|
4192
|
+
const service = this.fallbackService ??= this.config.fallback();
|
|
4193
|
+
switch (method) {
|
|
4194
|
+
case "panel":
|
|
4195
|
+
return service.panel(input);
|
|
4196
|
+
case "turns":
|
|
4197
|
+
return service.turnHistory(input);
|
|
4198
|
+
case "listCost":
|
|
4199
|
+
return service.listCost(input);
|
|
4200
|
+
case "filters":
|
|
4201
|
+
return service.filters();
|
|
4202
|
+
case "dbInfo":
|
|
4203
|
+
return service.dbInfo();
|
|
4204
|
+
case "prune":
|
|
4205
|
+
return service.prune(input);
|
|
4206
|
+
case "wipe":
|
|
4207
|
+
return service.wipe(input);
|
|
4208
|
+
case "vacuum":
|
|
4209
|
+
return service.compact(input);
|
|
4210
|
+
case "backfill":
|
|
4211
|
+
return service.backfill(input, this.config.priceTable?.());
|
|
4212
|
+
}
|
|
4213
|
+
}
|
|
4214
|
+
ensureWorker() {
|
|
4215
|
+
if (this.worker !== undefined)
|
|
4216
|
+
return Promise.resolve();
|
|
4217
|
+
if (this.startPromise !== undefined)
|
|
4218
|
+
return this.startPromise;
|
|
4219
|
+
const url = this.config.workerUrl?.() ?? defaultWorkerUrl();
|
|
4220
|
+
if (url === undefined) {
|
|
4221
|
+
this.useFallback("the worker entrypoint was not found");
|
|
4222
|
+
return Promise.resolve();
|
|
4223
|
+
}
|
|
4224
|
+
const ctor = globalThis.Worker;
|
|
4225
|
+
if (ctor === undefined) {
|
|
4226
|
+
this.useFallback("this runtime has no worker support");
|
|
4227
|
+
return Promise.resolve();
|
|
4228
|
+
}
|
|
4229
|
+
this.startPromise = new Promise((resolve) => {
|
|
4230
|
+
let settled = false;
|
|
4231
|
+
let worker;
|
|
4232
|
+
try {
|
|
4233
|
+
worker = new ctor(url);
|
|
4234
|
+
} catch (error) {
|
|
4235
|
+
this.useFallback(error instanceof Error ? error.message : "the usage worker could not be created");
|
|
4236
|
+
resolve();
|
|
4237
|
+
return;
|
|
4238
|
+
}
|
|
4239
|
+
this.starting = worker;
|
|
4240
|
+
let timer;
|
|
4241
|
+
const finish = (ok, reason) => {
|
|
4242
|
+
if (settled)
|
|
4243
|
+
return;
|
|
4244
|
+
settled = true;
|
|
4245
|
+
if (timer !== undefined)
|
|
4246
|
+
clearTimeout(timer);
|
|
4247
|
+
this.startPromise = undefined;
|
|
4248
|
+
this.starting = undefined;
|
|
4249
|
+
this.startAbort = undefined;
|
|
4250
|
+
if (this.stopped) {
|
|
4251
|
+
worker.terminate();
|
|
4252
|
+
this.worker = undefined;
|
|
4253
|
+
resolve();
|
|
4254
|
+
return;
|
|
4255
|
+
}
|
|
4256
|
+
if (!ok) {
|
|
4257
|
+
worker.terminate();
|
|
4258
|
+
this.useFallback(reason ?? "the usage worker did not start");
|
|
4259
|
+
}
|
|
4260
|
+
resolve();
|
|
4261
|
+
};
|
|
4262
|
+
this.startAbort = () => finish(false, "the usage service stopped");
|
|
4263
|
+
timer = setTimeout(() => finish(false, "the usage worker did not start in time"), this.config.timeouts?.start ?? START_TIMEOUT_MS);
|
|
4264
|
+
worker.onmessage = (event) => {
|
|
4265
|
+
const message = event.data;
|
|
4266
|
+
if (message?.type === "ready") {
|
|
4267
|
+
if (settled) {
|
|
4268
|
+
worker.terminate();
|
|
4269
|
+
return;
|
|
4270
|
+
}
|
|
4271
|
+
this.worker = worker;
|
|
4272
|
+
this.attach(worker);
|
|
4273
|
+
finish(true);
|
|
4274
|
+
return;
|
|
4275
|
+
}
|
|
4276
|
+
if (message?.type === "error") {
|
|
4277
|
+
finish(false, message.error?.message ?? "the usage worker failed to start");
|
|
4278
|
+
}
|
|
4279
|
+
};
|
|
4280
|
+
worker.onerror = (event) => {
|
|
4281
|
+
finish(false, event.message || "the usage worker failed to start");
|
|
4282
|
+
};
|
|
4283
|
+
try {
|
|
4284
|
+
worker.postMessage({ type: "init", dbPath: this.config.dbPath, options: this.config.options });
|
|
4285
|
+
} catch (error) {
|
|
4286
|
+
finish(false, error instanceof Error ? error.message : "the usage worker could not be initialized");
|
|
4287
|
+
}
|
|
4288
|
+
});
|
|
4289
|
+
return this.startPromise;
|
|
4290
|
+
}
|
|
4291
|
+
attach(worker) {
|
|
4292
|
+
worker.onmessage = (event) => this.receive(event.data);
|
|
4293
|
+
worker.onerror = (event) => {
|
|
4294
|
+
this.config.log?.(`usage worker failed: ${event.message}`);
|
|
4295
|
+
this.worker = undefined;
|
|
4296
|
+
this.rejectAll(new StatsError("unavailable", "the usage worker stopped"));
|
|
4297
|
+
};
|
|
4298
|
+
}
|
|
4299
|
+
receive(message) {
|
|
4300
|
+
if (message === null || typeof message !== "object")
|
|
4301
|
+
return;
|
|
4302
|
+
const payload = message;
|
|
4303
|
+
if (typeof payload.id !== "number")
|
|
4304
|
+
return;
|
|
4305
|
+
const pending = this.pending.get(payload.id);
|
|
4306
|
+
if (pending === undefined)
|
|
4307
|
+
return;
|
|
4308
|
+
this.settle(payload.id, pending);
|
|
4309
|
+
if (payload.ok === true) {
|
|
4310
|
+
pending.resolve(payload.result);
|
|
4311
|
+
return;
|
|
4312
|
+
}
|
|
4313
|
+
const code = payload.error?.code ?? "unavailable";
|
|
4314
|
+
pending.reject(new StatsError(code, payload.error?.message ?? "the usage request failed"));
|
|
4315
|
+
}
|
|
4316
|
+
timeoutFor(method) {
|
|
4317
|
+
if (MAINTENANCE_METHODS.has(method)) {
|
|
4318
|
+
return this.config.timeouts?.maintenance ?? MAINTENANCE_TIMEOUT_MS;
|
|
4319
|
+
}
|
|
4320
|
+
return this.config.timeouts?.read ?? READ_TIMEOUT_MS;
|
|
4321
|
+
}
|
|
4322
|
+
send(method, input, signal) {
|
|
4323
|
+
const worker = this.worker;
|
|
4324
|
+
if (worker === undefined)
|
|
4325
|
+
throw new StatsError("unavailable", "the usage worker is not running");
|
|
4326
|
+
const id = this.nextID++;
|
|
4327
|
+
const prices = method === "backfill" ? this.config.priceTable?.() : undefined;
|
|
4328
|
+
return new Promise((resolve, reject) => {
|
|
4329
|
+
const pending = {
|
|
4330
|
+
resolve,
|
|
4331
|
+
reject,
|
|
4332
|
+
timer: setTimeout(() => {
|
|
4333
|
+
this.settle(id, pending);
|
|
4334
|
+
pending.reject(new StatsError("unavailable", "the usage request timed out"));
|
|
4335
|
+
this.hardReset("the usage request timed out");
|
|
4336
|
+
}, this.timeoutFor(method))
|
|
4337
|
+
};
|
|
4338
|
+
if (signal !== undefined) {
|
|
4339
|
+
if (signal.aborted) {
|
|
4340
|
+
clearTimeout(pending.timer);
|
|
4341
|
+
reject(new StatsError("unavailable", "the usage request was cancelled"));
|
|
4342
|
+
return;
|
|
4343
|
+
}
|
|
4344
|
+
const abort = () => {
|
|
4345
|
+
this.settle(id, pending);
|
|
4346
|
+
reject(new StatsError("unavailable", "the usage request was cancelled"));
|
|
4347
|
+
};
|
|
4348
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
4349
|
+
pending.removeAbort = () => signal.removeEventListener("abort", abort);
|
|
4350
|
+
}
|
|
4351
|
+
this.pending.set(id, pending);
|
|
4352
|
+
try {
|
|
4353
|
+
worker.postMessage({
|
|
4354
|
+
id,
|
|
4355
|
+
method,
|
|
4356
|
+
input,
|
|
4357
|
+
...prices !== undefined ? { prices: [...prices.entries()] } : {}
|
|
4358
|
+
});
|
|
4359
|
+
} catch {
|
|
4360
|
+
this.settle(id, pending);
|
|
4361
|
+
pending.reject(new StatsError("unavailable", "the usage worker stopped"));
|
|
4362
|
+
}
|
|
4363
|
+
});
|
|
4364
|
+
}
|
|
4365
|
+
settle(id, pending) {
|
|
4366
|
+
clearTimeout(pending.timer);
|
|
4367
|
+
pending.removeAbort?.();
|
|
4368
|
+
this.pending.delete(id);
|
|
4369
|
+
}
|
|
4370
|
+
rejectAll(error) {
|
|
4371
|
+
for (const [id, pending] of this.pending) {
|
|
4372
|
+
this.settle(id, pending);
|
|
4373
|
+
pending.reject(error);
|
|
4374
|
+
}
|
|
4375
|
+
}
|
|
4376
|
+
hardReset(message) {
|
|
4377
|
+
this.config.log?.(message);
|
|
4378
|
+
this.rejectAll(new StatsError("unavailable", message));
|
|
4379
|
+
this.worker?.terminate();
|
|
4380
|
+
this.worker = undefined;
|
|
4381
|
+
this.starting?.terminate();
|
|
4382
|
+
this.starting = undefined;
|
|
4383
|
+
this.startPromise = undefined;
|
|
4384
|
+
}
|
|
4385
|
+
useFallback(reason) {
|
|
4386
|
+
this.fallbackMode = true;
|
|
4387
|
+
this.config.log?.(`usage worker unavailable, using the in-process service: ${reason}`);
|
|
4388
|
+
}
|
|
4389
|
+
}
|
|
4390
|
+
|
|
4391
|
+
// src/index.ts
|
|
4392
|
+
var PRICE_TTL_MS = 5 * 60 * 1000;
|
|
4393
|
+
var PRICE_RETRY_MS = 30 * 1000;
|
|
4394
|
+
var RECORDED_EVENTS = new Set([
|
|
4395
|
+
"session.created",
|
|
4396
|
+
"session.renamed",
|
|
4397
|
+
"session.moved",
|
|
4398
|
+
"session.inbox.enqueued",
|
|
4399
|
+
"session.step.ended",
|
|
4400
|
+
"session.step.failed",
|
|
4401
|
+
"session.usage.recorded",
|
|
4402
|
+
"session.compaction.ended"
|
|
4403
|
+
]);
|
|
4404
|
+
function createPriceSource(ctx) {
|
|
4405
|
+
let table;
|
|
4406
|
+
let refreshing = false;
|
|
4407
|
+
let lastAttempt = 0;
|
|
4408
|
+
function refresh(force = false) {
|
|
4409
|
+
if (refreshing)
|
|
4410
|
+
return;
|
|
4411
|
+
const now = Date.now();
|
|
4412
|
+
const wait = table === undefined ? PRICE_RETRY_MS : PRICE_TTL_MS;
|
|
4413
|
+
if (!force && now - lastAttempt < wait)
|
|
4414
|
+
return;
|
|
4415
|
+
lastAttempt = now;
|
|
4416
|
+
refreshing = true;
|
|
4417
|
+
(async () => {
|
|
4418
|
+
try {
|
|
4419
|
+
const payload = await ctx.model.list();
|
|
4420
|
+
const models = Array.isArray(payload) ? payload : payload?.data;
|
|
4421
|
+
if (Array.isArray(models) && models.length > 0)
|
|
4422
|
+
table = priceTable(models);
|
|
4423
|
+
} catch {} finally {
|
|
4424
|
+
refreshing = false;
|
|
4425
|
+
}
|
|
4426
|
+
})();
|
|
4427
|
+
}
|
|
4428
|
+
return {
|
|
4429
|
+
price: (ref, tokens) => {
|
|
4430
|
+
refresh();
|
|
4431
|
+
return table === undefined ? undefined : costOf(table, ref, tokens);
|
|
4432
|
+
},
|
|
4433
|
+
table: () => table,
|
|
4434
|
+
refresh
|
|
4435
|
+
};
|
|
4436
|
+
}
|
|
4437
|
+
function tryOpen(path) {
|
|
4438
|
+
try {
|
|
4439
|
+
return openStatsDb(path);
|
|
4440
|
+
} catch {
|
|
4441
|
+
return;
|
|
4442
|
+
}
|
|
4443
|
+
}
|
|
4444
|
+
function rpcFailure(context, error) {
|
|
4445
|
+
if (error instanceof StatsError || error instanceof ServiceError)
|
|
4446
|
+
return context.error(error.code, error.message);
|
|
4447
|
+
return context.error("unavailable", "the usage database is unavailable");
|
|
4448
|
+
}
|
|
4449
|
+
var src_default = Plugin.define({
|
|
4450
|
+
id: "usage-insights",
|
|
4451
|
+
async setup(ctx) {
|
|
4452
|
+
const options = ctx.options ?? {};
|
|
4453
|
+
if (options.enabled === false)
|
|
4454
|
+
return;
|
|
4455
|
+
const path = resolveDbPath(options.db);
|
|
4456
|
+
const db = tryOpen(path);
|
|
4457
|
+
if (db === undefined)
|
|
4458
|
+
return;
|
|
4459
|
+
try {
|
|
4460
|
+
db.exec("PRAGMA busy_timeout = 1000");
|
|
4461
|
+
} catch {}
|
|
4462
|
+
const pricing = options.pricing !== "off";
|
|
4463
|
+
const maintenance = options.maintenance !== false;
|
|
4464
|
+
const exposePaths = options.exposePaths === true;
|
|
4465
|
+
const source = pricing ? createPriceSource(ctx) : undefined;
|
|
4466
|
+
source?.refresh(true);
|
|
4467
|
+
const format = {
|
|
4468
|
+
...options.labels !== undefined ? { labels: options.labels } : {},
|
|
4469
|
+
...options.fields !== undefined ? { fields: options.fields } : {},
|
|
4470
|
+
...options.turnTotals !== undefined ? { turnTotals: options.turnTotals } : {}
|
|
4471
|
+
};
|
|
4472
|
+
const serviceOptions = { pricing, maintenance, exposePaths, format };
|
|
4473
|
+
const stats = new StatsClient({
|
|
4474
|
+
dbPath: path,
|
|
4475
|
+
options: serviceOptions,
|
|
4476
|
+
priceTable: () => source?.table(),
|
|
4477
|
+
fallback: () => createService(() => db, {
|
|
4478
|
+
...serviceOptions,
|
|
4479
|
+
path,
|
|
4480
|
+
priceTable: () => source?.table()
|
|
4481
|
+
}),
|
|
4482
|
+
log: (message) => console.warn(`[usage-insights] ${message}`)
|
|
4483
|
+
});
|
|
4484
|
+
const registration = await ctx.rpc.register(UsageInsights, {
|
|
4485
|
+
panel: async (input, context) => {
|
|
4486
|
+
try {
|
|
4487
|
+
return await stats.request("panel", input);
|
|
4488
|
+
} catch (error) {
|
|
4489
|
+
return rpcFailure(context, error);
|
|
4490
|
+
}
|
|
4491
|
+
},
|
|
4492
|
+
turns: async (input, context) => {
|
|
4493
|
+
try {
|
|
4494
|
+
return await stats.request("turns", input);
|
|
4495
|
+
} catch (error) {
|
|
4496
|
+
return rpcFailure(context, error);
|
|
4497
|
+
}
|
|
4498
|
+
},
|
|
4499
|
+
listCost: async (input, context) => {
|
|
4500
|
+
try {
|
|
4501
|
+
return await stats.request("listCost", input);
|
|
4502
|
+
} catch (error) {
|
|
4503
|
+
return rpcFailure(context, error);
|
|
4504
|
+
}
|
|
4505
|
+
},
|
|
4506
|
+
filters: async (_input, context) => {
|
|
4507
|
+
try {
|
|
4508
|
+
return await stats.request("filters", {});
|
|
4509
|
+
} catch (error) {
|
|
4510
|
+
return rpcFailure(context, error);
|
|
4511
|
+
}
|
|
4512
|
+
},
|
|
4513
|
+
dbInfo: async (_input, context) => {
|
|
4514
|
+
try {
|
|
4515
|
+
return await stats.request("dbInfo", {});
|
|
4516
|
+
} catch (error) {
|
|
4517
|
+
return rpcFailure(context, error);
|
|
4518
|
+
}
|
|
4519
|
+
},
|
|
4520
|
+
prune: async (input, context) => {
|
|
4521
|
+
try {
|
|
4522
|
+
return await stats.request("prune", input);
|
|
4523
|
+
} catch (error) {
|
|
4524
|
+
return rpcFailure(context, error);
|
|
4525
|
+
}
|
|
4526
|
+
},
|
|
4527
|
+
wipe: async (input, context) => {
|
|
4528
|
+
try {
|
|
4529
|
+
return await stats.request("wipe", input);
|
|
4530
|
+
} catch (error) {
|
|
4531
|
+
return rpcFailure(context, error);
|
|
4532
|
+
}
|
|
4533
|
+
},
|
|
4534
|
+
vacuum: async (input, context) => {
|
|
4535
|
+
try {
|
|
4536
|
+
return await stats.request("vacuum", input);
|
|
4537
|
+
} catch (error) {
|
|
4538
|
+
return rpcFailure(context, error);
|
|
4539
|
+
}
|
|
4540
|
+
},
|
|
4541
|
+
backfill: async (input, context) => {
|
|
4542
|
+
try {
|
|
4543
|
+
return await stats.request("backfill", input);
|
|
4544
|
+
} catch (error) {
|
|
4545
|
+
return rpcFailure(context, error);
|
|
4546
|
+
}
|
|
4547
|
+
}
|
|
4548
|
+
}).catch((error) => {
|
|
4549
|
+
stats.stop();
|
|
4550
|
+
db.close();
|
|
4551
|
+
throw error;
|
|
4552
|
+
});
|
|
1607
4553
|
const recorder = createRecorder(db, source === undefined ? undefined : { price: source.price });
|
|
1608
4554
|
const abort = new AbortController;
|
|
1609
4555
|
const stream = (async () => {
|
|
@@ -1613,13 +4559,20 @@ var src_default = Plugin.define({
|
|
|
1613
4559
|
if (event.type === "model.updated")
|
|
1614
4560
|
source?.refresh(true);
|
|
1615
4561
|
recorder.handleEvent(event);
|
|
4562
|
+
if (RECORDED_EVENTS.has(event.type)) {
|
|
4563
|
+
const data = event.data;
|
|
4564
|
+
const sessionID = typeof data?.sessionID === "string" ? data.sessionID : undefined;
|
|
4565
|
+
registration.events.emit("recorded", { at: Date.now(), ...sessionID !== undefined ? { sessionID } : {} }).catch(() => {});
|
|
4566
|
+
}
|
|
1616
4567
|
} catch {}
|
|
1617
4568
|
}
|
|
1618
4569
|
} catch {}
|
|
1619
4570
|
})();
|
|
1620
4571
|
return async () => {
|
|
1621
4572
|
abort.abort();
|
|
4573
|
+
await registration.dispose();
|
|
1622
4574
|
await stream;
|
|
4575
|
+
stats.stop();
|
|
1623
4576
|
db.close();
|
|
1624
4577
|
};
|
|
1625
4578
|
}
|
|
@@ -1628,4 +4581,4 @@ export {
|
|
|
1628
4581
|
src_default as default
|
|
1629
4582
|
};
|
|
1630
4583
|
|
|
1631
|
-
//# debugId=
|
|
4584
|
+
//# debugId=81E9F82B0FBCADEE64756E2164756E21
|