@yangzhenchen/dsh-balance 0.0.0-stage → 0.4.2
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/LICENSE +21 -0
- package/README.md +210 -2
- package/cordis.patch.yml +6 -0
- package/lib/account.js +306 -0
- package/lib/client.js +1627 -0
- package/lib/index.js +382 -0
- package/lib/usage.js +333 -0
- package/package.json +58 -3
- package/preview.png +0 -0
- package/scripts/enable-bundle.mjs +69 -0
- package/scripts/repair-profile.mjs +58 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
// Host half of the sidebar balance plugin.
|
|
2
|
+
//
|
|
3
|
+
// It owns the usage route the browser row polls. Two sources back it:
|
|
4
|
+
// - local — the durable session logs through `ctx.sessionQuery`: every
|
|
5
|
+
// session is read once per Host process, then kept current from
|
|
6
|
+
// the live `session/event` feed. Exact timestamps, so the panel
|
|
7
|
+
// can show an hourly breakdown.
|
|
8
|
+
// - account — the DeepSeek platform's own usage endpoints, read with the
|
|
9
|
+
// desktop account grant. Account-wide (any machine, any API key),
|
|
10
|
+
// but only daily and bucketed by UTC.
|
|
11
|
+
// The account grant never leaves the Host.
|
|
12
|
+
import {
|
|
13
|
+
ACCOUNT_CREDENTIAL,
|
|
14
|
+
ACCOUNT_ORIGIN,
|
|
15
|
+
AccountError,
|
|
16
|
+
monthKeyOf,
|
|
17
|
+
requestAccountMonth,
|
|
18
|
+
summarizeAccount,
|
|
19
|
+
windowMonthKeys
|
|
20
|
+
} from "./account.js";
|
|
21
|
+
import { USAGE_DEFAULT_DAYS, USAGE_MAX_DAYS, USAGE_ROUTE, clampInt, foldEvent, replayUsage, summarizeUsage } from "./usage.js";
|
|
22
|
+
|
|
23
|
+
/** Sessions read concurrently while indexing. */
|
|
24
|
+
const SCAN_CONCURRENCY = 3;
|
|
25
|
+
|
|
26
|
+
/** Read attempts before one session is treated as unreadable. */
|
|
27
|
+
const MAX_READ_ATTEMPTS = 3;
|
|
28
|
+
|
|
29
|
+
/** Account month cache lifetimes: the open month moves, closed ones rarely do. */
|
|
30
|
+
const ACCOUNT_CURRENT_TTL_MS = 5 * 60 * 1000;
|
|
31
|
+
const ACCOUNT_CLOSED_TTL_MS = 6 * 60 * 60 * 1000;
|
|
32
|
+
|
|
33
|
+
/** Concurrent platform month requests. */
|
|
34
|
+
const ACCOUNT_CONCURRENCY = 3;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Answer one JSON response.
|
|
38
|
+
* @param res - server response.
|
|
39
|
+
* @param status - HTTP status code.
|
|
40
|
+
* @param value - JSON-serializable body.
|
|
41
|
+
*/
|
|
42
|
+
function sendJson(res, status, value) {
|
|
43
|
+
res.statusCode = status;
|
|
44
|
+
res.setHeader("content-type", "application/json; charset=utf-8");
|
|
45
|
+
res.setHeader("cache-control", "no-store");
|
|
46
|
+
res.end(JSON.stringify(value));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Run workers over items with a fixed concurrency; the first rejection wins.
|
|
51
|
+
* @param items - work items.
|
|
52
|
+
* @param limit - maximum in-flight workers.
|
|
53
|
+
* @param worker - per-item work.
|
|
54
|
+
*/
|
|
55
|
+
async function mapLimit(items, limit, worker) {
|
|
56
|
+
let cursor = 0;
|
|
57
|
+
const run = async () => {
|
|
58
|
+
for (;;) {
|
|
59
|
+
const index = cursor;
|
|
60
|
+
cursor += 1;
|
|
61
|
+
if (index >= items.length) return;
|
|
62
|
+
await worker(items[index]);
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
await Promise.all(Array.from({ length: Math.min(limit, Math.max(items.length, 1)) }, run));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Register the usage route once the web server, the request trust fence, and
|
|
70
|
+
* the session query service are all present. Without them the plugin keeps
|
|
71
|
+
* serving the balance row but exposes no usage endpoint.
|
|
72
|
+
* @param ctx - Host plugin context.
|
|
73
|
+
*/
|
|
74
|
+
export function apply(ctx) {
|
|
75
|
+
ctx.inject(["webServer", "connection", "sessionQuery"], (cap) => {
|
|
76
|
+
/** session id → fold state. */
|
|
77
|
+
const folds = new Map();
|
|
78
|
+
/** Sessions that published events before they were indexed. */
|
|
79
|
+
const pending = new Set();
|
|
80
|
+
/** session id → failed read attempts. */
|
|
81
|
+
const failed = new Map();
|
|
82
|
+
/** session ids with a read in flight. */
|
|
83
|
+
const reading = new Set();
|
|
84
|
+
let scanning = true;
|
|
85
|
+
let started = false;
|
|
86
|
+
let disposed = false;
|
|
87
|
+
let scanPromise = null;
|
|
88
|
+
|
|
89
|
+
/** The credentials service, once mounted. */
|
|
90
|
+
let credentialReader = null;
|
|
91
|
+
cap.inject(["credentials"], (creds) => {
|
|
92
|
+
credentialReader = creds.credentials;
|
|
93
|
+
creds.effect(() => () => {
|
|
94
|
+
credentialReader = null;
|
|
95
|
+
}, "balance: credentials binding");
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
/** month key → `{ token, at, ttl, result, inflight }`. */
|
|
99
|
+
const accountMonths = new Map();
|
|
100
|
+
let accountToken = null;
|
|
101
|
+
|
|
102
|
+
cap.effect(() => () => {
|
|
103
|
+
disposed = true;
|
|
104
|
+
}, "balance: usage lifetime");
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Read one session and replace its fold with a full replay.
|
|
108
|
+
* A read re-runs once when events landed while it was in flight.
|
|
109
|
+
* @param id - session id.
|
|
110
|
+
*/
|
|
111
|
+
const indexSession = async (id) => {
|
|
112
|
+
if (disposed || folds.has(id) || reading.has(id)) return;
|
|
113
|
+
if ((failed.get(id) ?? 0) >= MAX_READ_ATTEMPTS) return;
|
|
114
|
+
reading.add(id);
|
|
115
|
+
try {
|
|
116
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
117
|
+
pending.delete(id);
|
|
118
|
+
const loaded = await cap.sessionQuery.readSession(id);
|
|
119
|
+
const fold = replayUsage(loaded?.events, loaded?.inheritedEventCount);
|
|
120
|
+
folds.set(id, fold);
|
|
121
|
+
failed.delete(id);
|
|
122
|
+
if (!pending.has(id)) return;
|
|
123
|
+
}
|
|
124
|
+
// A live event landed after the second read: drop the fold so the next
|
|
125
|
+
// request indexes this session again instead of missing that event.
|
|
126
|
+
folds.delete(id);
|
|
127
|
+
} catch (_error) {
|
|
128
|
+
failed.set(id, (failed.get(id) ?? 0) + 1);
|
|
129
|
+
} finally {
|
|
130
|
+
reading.delete(id);
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
/** Index every session that published events before its first read. */
|
|
135
|
+
const indexPending = async () => {
|
|
136
|
+
const queue = [...pending].filter((id) => !folds.has(id) && !reading.has(id) && (failed.get(id) ?? 0) < MAX_READ_ATTEMPTS);
|
|
137
|
+
if (queue.length === 0) return;
|
|
138
|
+
const worker = async () => {
|
|
139
|
+
for (;;) {
|
|
140
|
+
const id = queue.shift();
|
|
141
|
+
if (id === undefined || disposed) return;
|
|
142
|
+
await indexSession(id);
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
await Promise.all(Array.from({ length: Math.min(SCAN_CONCURRENCY, queue.length) }, worker));
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/** Index the whole corpus newest-first, live sessions ahead of stored ones. */
|
|
149
|
+
const scan = () => {
|
|
150
|
+
if (scanPromise !== null) return scanPromise;
|
|
151
|
+
scanning = true;
|
|
152
|
+
scanPromise = (async () => {
|
|
153
|
+
try {
|
|
154
|
+
const records = await cap.sessionQuery.listSessions();
|
|
155
|
+
const ordered = Array.isArray(records) ? [...records] : [];
|
|
156
|
+
ordered.sort((left, right) => {
|
|
157
|
+
const live = Number(right?.live === true) - Number(left?.live === true);
|
|
158
|
+
if (live !== 0) return live;
|
|
159
|
+
return (right?.header?.createdAt ?? 0) - (left?.header?.createdAt ?? 0);
|
|
160
|
+
});
|
|
161
|
+
let cursor = 0;
|
|
162
|
+
const worker = async () => {
|
|
163
|
+
for (;;) {
|
|
164
|
+
if (disposed) return;
|
|
165
|
+
const index = cursor;
|
|
166
|
+
cursor += 1;
|
|
167
|
+
if (index >= ordered.length) return;
|
|
168
|
+
const id = ordered[index]?.header?.id;
|
|
169
|
+
if (typeof id !== "string" || id === "") continue;
|
|
170
|
+
await indexSession(id);
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
await Promise.all(Array.from({ length: Math.min(SCAN_CONCURRENCY, Math.max(ordered.length, 1)) }, worker));
|
|
174
|
+
} catch (_error) {
|
|
175
|
+
// A failing corpus listing leaves whatever is indexed in place.
|
|
176
|
+
} finally {
|
|
177
|
+
scanning = false;
|
|
178
|
+
scanPromise = null;
|
|
179
|
+
}
|
|
180
|
+
})();
|
|
181
|
+
return scanPromise;
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
// Every committed live event keeps its session's fold current. A session
|
|
185
|
+
// seen for the first time here is indexed on the next request.
|
|
186
|
+
cap.on("session/event", (session, event) => {
|
|
187
|
+
if (disposed) return;
|
|
188
|
+
const id = session?.id;
|
|
189
|
+
if (typeof id !== "string" || id === "") return;
|
|
190
|
+
const fold = folds.get(id);
|
|
191
|
+
if (fold !== undefined) {
|
|
192
|
+
foldEvent(fold, event);
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
pending.add(id);
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Read the desktop account grant from DSH credentials.
|
|
200
|
+
* @returns `{ token, origin }`, or null when unavailable.
|
|
201
|
+
*/
|
|
202
|
+
const readAccountGrant = async () => {
|
|
203
|
+
const reader = credentialReader;
|
|
204
|
+
if (reader === null) return null;
|
|
205
|
+
try {
|
|
206
|
+
const record = await reader.readRecord(ACCOUNT_CREDENTIAL);
|
|
207
|
+
if (record === null || record === undefined || record.kind !== "grant") return null;
|
|
208
|
+
const token = record.payload?.token;
|
|
209
|
+
if (typeof token !== "string" || token === "") return null;
|
|
210
|
+
const issuer = record.payload?.issuer;
|
|
211
|
+
const origin = typeof issuer === "string" && /^https:\/\/[^/]+$/.test(issuer) ? issuer : ACCOUNT_ORIGIN;
|
|
212
|
+
return {
|
|
213
|
+
token,
|
|
214
|
+
origin
|
|
215
|
+
};
|
|
216
|
+
} catch (_error) {
|
|
217
|
+
return null;
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Load one platform month through the TTL cache.
|
|
223
|
+
* @param grant - account grant.
|
|
224
|
+
* @param key - `YYYY-MM`.
|
|
225
|
+
* @param includeCost - whether the cost endpoint is needed.
|
|
226
|
+
* @returns the month result.
|
|
227
|
+
*/
|
|
228
|
+
const loadAccountMonth = (grant, key, includeCost) => {
|
|
229
|
+
const now = Date.now();
|
|
230
|
+
const cached = accountMonths.get(key);
|
|
231
|
+
if (cached !== undefined && cached.token !== grant.token) accountMonths.clear();
|
|
232
|
+
const entry = accountMonths.get(key);
|
|
233
|
+
if (entry !== undefined) {
|
|
234
|
+
if (entry.inflight !== null) return entry.inflight;
|
|
235
|
+
if (now - entry.at < entry.ttl) return Promise.resolve(entry.result);
|
|
236
|
+
}
|
|
237
|
+
const created = {
|
|
238
|
+
token: grant.token,
|
|
239
|
+
at: 0,
|
|
240
|
+
ttl: ACCOUNT_CLOSED_TTL_MS,
|
|
241
|
+
result: null,
|
|
242
|
+
inflight: null
|
|
243
|
+
};
|
|
244
|
+
const [year, month] = key.split("-").map(Number);
|
|
245
|
+
created.inflight = requestAccountMonth({
|
|
246
|
+
origin: grant.origin,
|
|
247
|
+
token: grant.token,
|
|
248
|
+
year,
|
|
249
|
+
month,
|
|
250
|
+
includeCost
|
|
251
|
+
}).then((result) => {
|
|
252
|
+
created.result = result;
|
|
253
|
+
created.at = Date.now();
|
|
254
|
+
created.ttl = key === monthKeyOf(Date.now()) ? ACCOUNT_CURRENT_TTL_MS : ACCOUNT_CLOSED_TTL_MS;
|
|
255
|
+
return result;
|
|
256
|
+
}).finally(() => {
|
|
257
|
+
created.inflight = null;
|
|
258
|
+
});
|
|
259
|
+
accountMonths.set(key, created);
|
|
260
|
+
return created.inflight;
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Build the account-sourced payload.
|
|
265
|
+
* @param rangeDays - trailing day count.
|
|
266
|
+
* @returns the summary payload.
|
|
267
|
+
*/
|
|
268
|
+
const accountPayload = async (rangeDays) => {
|
|
269
|
+
const grant = await readAccountGrant();
|
|
270
|
+
if (grant === null) throw new AccountError("missing");
|
|
271
|
+
if (accountToken !== grant.token) {
|
|
272
|
+
accountMonths.clear();
|
|
273
|
+
accountToken = grant.token;
|
|
274
|
+
}
|
|
275
|
+
const now = Date.now();
|
|
276
|
+
const keys = windowMonthKeys(now, rangeDays);
|
|
277
|
+
const currentKey = monthKeyOf(now);
|
|
278
|
+
const results = new Map();
|
|
279
|
+
let failures = 0;
|
|
280
|
+
try {
|
|
281
|
+
await mapLimit(keys, ACCOUNT_CONCURRENCY, async (key) => {
|
|
282
|
+
try {
|
|
283
|
+
results.set(key, await loadAccountMonth(grant, key, key === currentKey));
|
|
284
|
+
} catch (error) {
|
|
285
|
+
if (error instanceof AccountError && error.reason === "auth") throw error;
|
|
286
|
+
failures += 1;
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
} catch (error) {
|
|
290
|
+
accountMonths.clear();
|
|
291
|
+
throw error;
|
|
292
|
+
}
|
|
293
|
+
if (results.size === 0) throw new AccountError("network");
|
|
294
|
+
const days = new Map();
|
|
295
|
+
for (const result of results.values()) {
|
|
296
|
+
for (const [date, entry] of result.days) days.set(date, entry);
|
|
297
|
+
}
|
|
298
|
+
const cost = results.get(currentKey)?.cost ?? null;
|
|
299
|
+
const payload = summarizeAccount(days, cost, {
|
|
300
|
+
now,
|
|
301
|
+
rangeDays
|
|
302
|
+
});
|
|
303
|
+
payload.scanning = false;
|
|
304
|
+
payload.partial = failures > 0;
|
|
305
|
+
return payload;
|
|
306
|
+
};
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Build the local-session payload.
|
|
310
|
+
* @param rangeDays - trailing day count.
|
|
311
|
+
* @param offsetSeconds - browser local offset.
|
|
312
|
+
* @returns the summary payload.
|
|
313
|
+
*/
|
|
314
|
+
const localPayload = async (rangeDays, offsetSeconds) => {
|
|
315
|
+
if (!started) {
|
|
316
|
+
started = true;
|
|
317
|
+
scan();
|
|
318
|
+
}
|
|
319
|
+
await indexPending();
|
|
320
|
+
const payload = summarizeUsage(folds, {
|
|
321
|
+
now: Date.now(),
|
|
322
|
+
offsetSeconds,
|
|
323
|
+
days: rangeDays
|
|
324
|
+
});
|
|
325
|
+
payload.source = "local";
|
|
326
|
+
payload.granularity = "hour";
|
|
327
|
+
payload.dayBasis = "local";
|
|
328
|
+
payload.scanning = scanning;
|
|
329
|
+
payload.partial = failed.size > 0;
|
|
330
|
+
return payload;
|
|
331
|
+
};
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* Serve the usage summary for one browser request.
|
|
335
|
+
* @param req - HTTP request.
|
|
336
|
+
* @param res - HTTP response.
|
|
337
|
+
*/
|
|
338
|
+
const handler = async (req, res) => {
|
|
339
|
+
const rejection = cap.connection.requestRejection(req);
|
|
340
|
+
if (rejection !== undefined) {
|
|
341
|
+
res.statusCode = rejection;
|
|
342
|
+
res.end();
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
if (req.method !== "GET") {
|
|
346
|
+
res.statusCode = 405;
|
|
347
|
+
res.setHeader("allow", "GET");
|
|
348
|
+
res.end();
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
let url;
|
|
352
|
+
try {
|
|
353
|
+
url = new URL(String(req.url ?? USAGE_ROUTE), "http://localhost");
|
|
354
|
+
} catch (_error) {
|
|
355
|
+
sendJson(res, 400, { error: "bad-request" });
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
const days = clampInt(url.searchParams.get("days"), 1, USAGE_MAX_DAYS, USAGE_DEFAULT_DAYS);
|
|
359
|
+
const offsetSeconds = clampInt(url.searchParams.get("offset"), -86400, 86400, 0);
|
|
360
|
+
const source = url.searchParams.get("source") === "account" ? "account" : "local";
|
|
361
|
+
try {
|
|
362
|
+
const payload = source === "account" ? await accountPayload(days) : await localPayload(days, offsetSeconds);
|
|
363
|
+
sendJson(res, 200, payload);
|
|
364
|
+
} catch (error) {
|
|
365
|
+
if (error instanceof AccountError) {
|
|
366
|
+
sendJson(res, 502, {
|
|
367
|
+
error: "account-unavailable",
|
|
368
|
+
reason: error.reason
|
|
369
|
+
});
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
sendJson(res, 500, { error: "usage-unavailable" });
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
cap.effect(() => cap.webServer.register({
|
|
377
|
+
kind: "exact",
|
|
378
|
+
path: USAGE_ROUTE,
|
|
379
|
+
handler
|
|
380
|
+
}), `balance: GET ${USAGE_ROUTE}`);
|
|
381
|
+
});
|
|
382
|
+
}
|
package/lib/usage.js
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
// Pure token-usage fold and aggregation for the sidebar usage row.
|
|
2
|
+
//
|
|
3
|
+
// Host-only: this module never touches the DOM, `fetch`, or any Node builtin,
|
|
4
|
+
// so the same code runs in the Host plugin and in offline tests. It mirrors
|
|
5
|
+
// `@deepseek-ai/dsh-token-meter`'s `tokenUsage` projection: one billed sample
|
|
6
|
+
// per settled attempt, and a final sample replaces an earlier streaming sample
|
|
7
|
+
// of the same turn/step (`llm/retry-started` reopens the slot).
|
|
8
|
+
|
|
9
|
+
/** Route the Host registers and the browser polls. */
|
|
10
|
+
export const USAGE_ROUTE = "/dsh-balance/usage";
|
|
11
|
+
|
|
12
|
+
/** Longest day range a client may request (a 53-week calendar plus slack). */
|
|
13
|
+
export const USAGE_MAX_DAYS = 400;
|
|
14
|
+
|
|
15
|
+
/** Day range used when the query names none. */
|
|
16
|
+
export const USAGE_DEFAULT_DAYS = 14;
|
|
17
|
+
|
|
18
|
+
const DAY_MS = 86400000;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @returns a fresh fold state for one session log.
|
|
22
|
+
*/
|
|
23
|
+
export function createUsageFold() {
|
|
24
|
+
return {
|
|
25
|
+
/** Flat samples: `{ t, input, output, cacheRead, cacheWrite }`. */
|
|
26
|
+
samples: [],
|
|
27
|
+
/** Turn/step owning the newest sample, for in-step replacement. */
|
|
28
|
+
lastTurn: null,
|
|
29
|
+
lastStep: null,
|
|
30
|
+
/** Index in `samples` of that newest sample. */
|
|
31
|
+
lastIndex: -1,
|
|
32
|
+
/** Highest event seq folded so far. */
|
|
33
|
+
tailSeq: -1
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* @param value - candidate token count.
|
|
39
|
+
* @returns whether the value is a usable non-negative finite number.
|
|
40
|
+
*/
|
|
41
|
+
function isCount(value) {
|
|
42
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* @param usage - provider-reported usage object.
|
|
47
|
+
* @returns normalized buckets, or null when the sample is unusable.
|
|
48
|
+
*/
|
|
49
|
+
export function normalizeUsage(usage) {
|
|
50
|
+
if (usage === null || typeof usage !== "object") return null;
|
|
51
|
+
if (!isCount(usage.inputTokens) || !isCount(usage.outputTokens)) return null;
|
|
52
|
+
const input = usage.inputTokens;
|
|
53
|
+
const output = usage.outputTokens;
|
|
54
|
+
const cacheRead = isCount(usage.cacheReadTokens) ? usage.cacheReadTokens : 0;
|
|
55
|
+
const cacheWrite = isCount(usage.cacheWriteTokens) ? usage.cacheWriteTokens : 0;
|
|
56
|
+
return {
|
|
57
|
+
input,
|
|
58
|
+
output,
|
|
59
|
+
cacheRead,
|
|
60
|
+
cacheWrite,
|
|
61
|
+
total: input + output + cacheRead + cacheWrite
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Read the last provider usage sample embedded in an assistant stream.
|
|
67
|
+
* @param stream - the event's compact stream rows.
|
|
68
|
+
* @returns the usage object, or undefined.
|
|
69
|
+
*/
|
|
70
|
+
function streamUsage(stream) {
|
|
71
|
+
if (!Array.isArray(stream)) return undefined;
|
|
72
|
+
for (let index = stream.length - 1; index >= 0; index -= 1) {
|
|
73
|
+
const chunk = stream[index]?.chunk;
|
|
74
|
+
if (chunk !== null && typeof chunk === "object" && chunk.type === "usage" && chunk.usage !== undefined) return chunk.usage;
|
|
75
|
+
}
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The billed usage one durable event reports, if any.
|
|
81
|
+
* @param event - one session event.
|
|
82
|
+
* @returns the raw usage object, or undefined.
|
|
83
|
+
*/
|
|
84
|
+
export function usageOf(event) {
|
|
85
|
+
if (event === null || typeof event !== "object") return undefined;
|
|
86
|
+
const data = event.data;
|
|
87
|
+
if (data === null || typeof data !== "object") return undefined;
|
|
88
|
+
if (event.type === "assistant/message" && data.usage !== undefined) return data.usage;
|
|
89
|
+
if (event.type === "compaction/summary" && data.usage !== undefined) return data.usage;
|
|
90
|
+
if (event.type !== "assistant/message" && event.type !== "assistant/attempt") return undefined;
|
|
91
|
+
return streamUsage(data.stream);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Fold one committed event into a session's usage samples.
|
|
96
|
+
* @param fold - state from {@link createUsageFold}.
|
|
97
|
+
* @param event - one session event.
|
|
98
|
+
*/
|
|
99
|
+
export function foldEvent(fold, event) {
|
|
100
|
+
if (fold === null || typeof fold !== "object" || event === null || typeof event !== "object") return;
|
|
101
|
+
const seq = Number.isInteger(event.seq) ? event.seq : null;
|
|
102
|
+
if (seq !== null && seq > fold.tailSeq) fold.tailSeq = seq;
|
|
103
|
+
if (event.type === "llm/retry-started") {
|
|
104
|
+
const data = event.data;
|
|
105
|
+
if (fold.lastTurn !== null && data !== null && typeof data === "object" && data.turn === fold.lastTurn && data.step === fold.lastStep) {
|
|
106
|
+
fold.lastTurn = null;
|
|
107
|
+
fold.lastStep = null;
|
|
108
|
+
fold.lastIndex = -1;
|
|
109
|
+
}
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
const buckets = normalizeUsage(usageOf(event));
|
|
113
|
+
if (buckets === null) return;
|
|
114
|
+
const time = Number.isFinite(event.time) ? event.time : null;
|
|
115
|
+
if (time === null) return;
|
|
116
|
+
const compaction = event.type === "compaction/summary";
|
|
117
|
+
const turn = compaction ? null : event.data?.turn;
|
|
118
|
+
const step = compaction ? null : event.data?.step;
|
|
119
|
+
const current = fold.lastIndex >= 0 ? fold.samples[fold.lastIndex] : undefined;
|
|
120
|
+
const sameAttempt = !compaction && current !== undefined && turn !== null && turn !== undefined && fold.lastTurn === turn && fold.lastStep === step;
|
|
121
|
+
if (sameAttempt) {
|
|
122
|
+
if (current.input === buckets.input && current.output === buckets.output && current.cacheRead === buckets.cacheRead && current.cacheWrite === buckets.cacheWrite) return;
|
|
123
|
+
current.t = time;
|
|
124
|
+
current.input = buckets.input;
|
|
125
|
+
current.output = buckets.output;
|
|
126
|
+
current.cacheRead = buckets.cacheRead;
|
|
127
|
+
current.cacheWrite = buckets.cacheWrite;
|
|
128
|
+
current.total = buckets.total;
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
fold.samples.push({
|
|
132
|
+
t: time,
|
|
133
|
+
input: buckets.input,
|
|
134
|
+
output: buckets.output,
|
|
135
|
+
cacheRead: buckets.cacheRead,
|
|
136
|
+
cacheWrite: buckets.cacheWrite,
|
|
137
|
+
total: buckets.total
|
|
138
|
+
});
|
|
139
|
+
fold.lastTurn = compaction ? null : turn;
|
|
140
|
+
fold.lastStep = compaction ? null : step;
|
|
141
|
+
fold.lastIndex = fold.samples.length - 1;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Replay a whole session log into a fresh fold.
|
|
146
|
+
* Inherited events belong to the parent session and are skipped so a fork or
|
|
147
|
+
* subagent seed never counts the same request twice.
|
|
148
|
+
* @param events - the session's raw event log.
|
|
149
|
+
* @param inheritedEventCount - leading inherited events to skip.
|
|
150
|
+
* @returns the fold state.
|
|
151
|
+
*/
|
|
152
|
+
export function replayUsage(events, inheritedEventCount = 0) {
|
|
153
|
+
const fold = createUsageFold();
|
|
154
|
+
if (!Array.isArray(events)) return fold;
|
|
155
|
+
const start = clampInt(inheritedEventCount, 0, events.length, 0);
|
|
156
|
+
for (let index = start; index < events.length; index += 1) foldEvent(fold, events[index]);
|
|
157
|
+
return fold;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** @returns a zeroed bucket. */
|
|
161
|
+
function zeroTotals() {
|
|
162
|
+
return {
|
|
163
|
+
input: 0,
|
|
164
|
+
output: 0,
|
|
165
|
+
cacheRead: 0,
|
|
166
|
+
cacheWrite: 0,
|
|
167
|
+
total: 0,
|
|
168
|
+
requests: 0
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Add one sample into a bucket.
|
|
174
|
+
* @param bucket - accumulator in the zeroTotals shape.
|
|
175
|
+
* @param sample - a folded usage sample.
|
|
176
|
+
*/
|
|
177
|
+
function addSample(bucket, sample) {
|
|
178
|
+
bucket.input += sample.input;
|
|
179
|
+
bucket.output += sample.output;
|
|
180
|
+
bucket.cacheRead += sample.cacheRead;
|
|
181
|
+
bucket.cacheWrite += sample.cacheWrite;
|
|
182
|
+
bucket.total += sample.total;
|
|
183
|
+
bucket.requests += 1;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Add every numeric field of one bucket into another.
|
|
188
|
+
* @param target - destination bucket.
|
|
189
|
+
* @param source - bucket to add.
|
|
190
|
+
*/
|
|
191
|
+
function addTotals(target, source) {
|
|
192
|
+
target.input += source.input;
|
|
193
|
+
target.output += source.output;
|
|
194
|
+
target.cacheRead += source.cacheRead;
|
|
195
|
+
target.cacheWrite += source.cacheWrite;
|
|
196
|
+
target.total += source.total;
|
|
197
|
+
target.requests += source.requests;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* @param bucket - bucket or undefined.
|
|
202
|
+
* @returns the public numeric fields, or zeros.
|
|
203
|
+
*/
|
|
204
|
+
function numbers(bucket) {
|
|
205
|
+
if (bucket === undefined) return zeroTotals();
|
|
206
|
+
return {
|
|
207
|
+
input: Math.round(bucket.input),
|
|
208
|
+
output: Math.round(bucket.output),
|
|
209
|
+
cacheRead: Math.round(bucket.cacheRead),
|
|
210
|
+
cacheWrite: Math.round(bucket.cacheWrite),
|
|
211
|
+
total: Math.round(bucket.total),
|
|
212
|
+
requests: bucket.requests
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* @param index - local day index.
|
|
218
|
+
* @returns `YYYY-MM-DD` of that local day.
|
|
219
|
+
*/
|
|
220
|
+
function dateKey(index) {
|
|
221
|
+
return new Date(index * DAY_MS).toISOString().slice(0, 10);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Clamp an integer option.
|
|
226
|
+
* @param value - raw value.
|
|
227
|
+
* @param min - inclusive lower bound.
|
|
228
|
+
* @param max - inclusive upper bound.
|
|
229
|
+
* @param fallback - value for absent or unusable input.
|
|
230
|
+
* @returns a safe integer.
|
|
231
|
+
*/
|
|
232
|
+
export function clampInt(value, min, max, fallback) {
|
|
233
|
+
if (value === null || value === undefined || value === "") return fallback;
|
|
234
|
+
const parsed = Number(value);
|
|
235
|
+
if (!Number.isFinite(parsed)) return fallback;
|
|
236
|
+
return Math.min(max, Math.max(min, Math.trunc(parsed)));
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Aggregate folded samples into the row payload.
|
|
241
|
+
* @param folds - session id → fold state.
|
|
242
|
+
* @param options - `now`, `offsetSeconds` (client local offset), `days`.
|
|
243
|
+
* @returns JSON-ready summary: today/yesterday, the day series, today's hours,
|
|
244
|
+
* the 7-day and 30-day windows, and the all-time total.
|
|
245
|
+
*/
|
|
246
|
+
export function summarizeUsage(folds, options = {}) {
|
|
247
|
+
const now = Number.isFinite(options.now) ? options.now : Date.now();
|
|
248
|
+
const offsetSeconds = clampInt(options.offsetSeconds, -86400, 86400, 0);
|
|
249
|
+
const rangeDays = clampInt(options.days, 1, USAGE_MAX_DAYS, USAGE_DEFAULT_DAYS);
|
|
250
|
+
const offsetMs = offsetSeconds * 1000;
|
|
251
|
+
const todayIndex = Math.floor((now + offsetMs) / DAY_MS);
|
|
252
|
+
const windowDays = Math.max(rangeDays, 30);
|
|
253
|
+
const firstIndex = todayIndex - windowDays + 1;
|
|
254
|
+
|
|
255
|
+
const days = new Map();
|
|
256
|
+
const hours = Array.from({ length: 24 }, (_, hour) => ({ hour, ...zeroTotals() }));
|
|
257
|
+
const all = { ...zeroTotals(), sessions: new Set(), from: 0, to: 0 };
|
|
258
|
+
|
|
259
|
+
for (const [sessionId, fold] of folds) {
|
|
260
|
+
const samples = fold?.samples;
|
|
261
|
+
if (!Array.isArray(samples)) continue;
|
|
262
|
+
for (const sample of samples) {
|
|
263
|
+
if (sample === null || typeof sample !== "object" || !Number.isFinite(sample.t)) continue;
|
|
264
|
+
const time = sample.t;
|
|
265
|
+
addSample(all, sample);
|
|
266
|
+
all.sessions.add(sessionId);
|
|
267
|
+
if (all.from === 0 || time < all.from) all.from = time;
|
|
268
|
+
if (time > all.to) all.to = time;
|
|
269
|
+
const index = Math.floor((time + offsetMs) / DAY_MS);
|
|
270
|
+
if (index < firstIndex || index > todayIndex) continue;
|
|
271
|
+
let bucket = days.get(index);
|
|
272
|
+
if (bucket === undefined) {
|
|
273
|
+
bucket = { ...zeroTotals(), sessions: new Set() };
|
|
274
|
+
days.set(index, bucket);
|
|
275
|
+
}
|
|
276
|
+
addSample(bucket, sample);
|
|
277
|
+
bucket.sessions.add(sessionId);
|
|
278
|
+
if (index === todayIndex) {
|
|
279
|
+
const hour = new Date(time + offsetMs).getUTCHours();
|
|
280
|
+
addSample(hours[hour], sample);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** @param index - local day index. @returns one day entry. */
|
|
286
|
+
const dayEntry = (index) => {
|
|
287
|
+
const bucket = days.get(index);
|
|
288
|
+
return {
|
|
289
|
+
date: dateKey(index),
|
|
290
|
+
...numbers(bucket),
|
|
291
|
+
sessions: bucket === undefined ? 0 : bucket.sessions.size
|
|
292
|
+
};
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
/** @param count - trailing local days to sum. @returns window totals. */
|
|
296
|
+
const windowTotals = (count) => {
|
|
297
|
+
const total = { ...zeroTotals(), sessions: new Set() };
|
|
298
|
+
for (let index = todayIndex - count + 1; index <= todayIndex; index += 1) {
|
|
299
|
+
const bucket = days.get(index);
|
|
300
|
+
if (bucket === undefined) continue;
|
|
301
|
+
addTotals(total, bucket);
|
|
302
|
+
for (const sessionId of bucket.sessions) total.sessions.add(sessionId);
|
|
303
|
+
}
|
|
304
|
+
return {
|
|
305
|
+
...numbers(total),
|
|
306
|
+
sessions: total.sessions.size
|
|
307
|
+
};
|
|
308
|
+
};
|
|
309
|
+
|
|
310
|
+
const series = [];
|
|
311
|
+
for (let index = todayIndex - rangeDays + 1; index <= todayIndex; index += 1) series.push(dayEntry(index));
|
|
312
|
+
|
|
313
|
+
return {
|
|
314
|
+
generatedAt: now,
|
|
315
|
+
offsetSeconds,
|
|
316
|
+
rangeDays,
|
|
317
|
+
today: dayEntry(todayIndex),
|
|
318
|
+
yesterday: dayEntry(todayIndex - 1),
|
|
319
|
+
days: series,
|
|
320
|
+
hours: hours.map((bucket) => ({
|
|
321
|
+
hour: bucket.hour,
|
|
322
|
+
...numbers(bucket)
|
|
323
|
+
})),
|
|
324
|
+
week: windowTotals(7),
|
|
325
|
+
month: windowTotals(30),
|
|
326
|
+
total: {
|
|
327
|
+
...numbers(all),
|
|
328
|
+
sessions: all.sessions.size,
|
|
329
|
+
from: all.from,
|
|
330
|
+
to: all.to
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
}
|