@natgurlain/dsh-token-usage 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,855 @@
1
+ import { basename, dirname, join } from "node:path";
2
+ import { mkdir, readFile, readdir, rename, stat, writeFile } from "node:fs/promises";
3
+ import { zstdDecompressSync } from "node:zlib";
4
+ //#region lib/types/scan.js
5
+ /**
6
+ * Reading token usage out of DSH's session logs.
7
+ *
8
+ * Every model call DSH makes for a conversation is logged with the usage the
9
+ * provider reported:
10
+ *
11
+ * - `assistant/message`: a completed step, `data.usage`, with the route in
12
+ * `data.message.source`.
13
+ * - `assistant/attempt`: a failed or retried call, its usage in the last
14
+ * `usage` chunk of `data.stream`. It has no route of its own, so it takes
15
+ * the route of the session's latest `request/header`.
16
+ * - `compaction/summary`: the summary call that compacts a long conversation,
17
+ * `data.usage` with `data.provider` and `data.model`.
18
+ *
19
+ * A seeded session (a fork or a resume) starts with a copy of another log
20
+ * up to `session/end-seed`; that copy is skipped so nothing counts twice.
21
+ * A session still being written (a trailing partial frame or line) yields
22
+ * what was complete.
23
+ *
24
+ * @module @natgurlain/dsh-token-usage/scan
25
+ */
26
+ const count = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
27
+ /** Normalize a provider usage object; undefined when it reports nothing. */
28
+ function normalizeUsage(raw) {
29
+ if (raw === null || typeof raw !== "object") return void 0;
30
+ const usage = raw;
31
+ const input = count(usage.inputTokens);
32
+ const output = count(usage.outputTokens);
33
+ const cacheRead = count(usage.cacheReadTokens);
34
+ const cacheWrite = count(usage.cacheWriteTokens);
35
+ const reasoning = Math.min(count(usage.reasoningTokens), output);
36
+ const sum = input + output + cacheRead + cacheWrite;
37
+ const total = Math.max(count(usage.totalTokens), sum);
38
+ if (total === 0) return void 0;
39
+ return {
40
+ input,
41
+ output,
42
+ cacheRead,
43
+ cacheWrite,
44
+ reasoning,
45
+ total
46
+ };
47
+ }
48
+ function lastStreamUsage(stream) {
49
+ if (!Array.isArray(stream)) return void 0;
50
+ for (let i = stream.length - 1; i >= 0; i--) {
51
+ const entry = stream[i];
52
+ if (entry?.type === "chunk" && entry.chunk?.type === "usage") return entry.chunk.usage;
53
+ }
54
+ }
55
+ const text = (value) => typeof value === "string" && value !== "" ? value : void 0;
56
+ /** Fold one session's events (in log order) into usage records. */
57
+ function recordsFromEvents(events) {
58
+ const records = [];
59
+ let sessionId = "unknown";
60
+ let cwd;
61
+ let subagent = false;
62
+ let seeding = false;
63
+ let route = {
64
+ provider: "unknown",
65
+ model: "unknown"
66
+ };
67
+ let title;
68
+ for (const event of events) {
69
+ const type = event.type;
70
+ if (type === "session") {
71
+ sessionId = text(event.id) ?? sessionId;
72
+ cwd = text(event.cwd);
73
+ subagent = event.origin === "subagent" || count(event.delegationDepth) > 0;
74
+ seeding = event.isSeeded === true;
75
+ continue;
76
+ }
77
+ if (type === "session/end-seed") {
78
+ seeding = false;
79
+ continue;
80
+ }
81
+ if (type === "session/title") {
82
+ title = text(event.data?.title) ?? title;
83
+ continue;
84
+ }
85
+ const data = event.data;
86
+ if (data === void 0 || data === null || typeof data !== "object") continue;
87
+ if (type === "request/header") {
88
+ const config = data.header?.config;
89
+ const provider = text(config?.provider);
90
+ const model = text(config?.model);
91
+ if (provider !== void 0 && model !== void 0) route = {
92
+ provider,
93
+ model
94
+ };
95
+ continue;
96
+ }
97
+ if (seeding) continue;
98
+ const time = typeof event.time === "number" ? event.time : void 0;
99
+ if (time === void 0) continue;
100
+ const seq = typeof event.seq === "number" ? event.seq : void 0;
101
+ const base = {
102
+ time,
103
+ sessionId,
104
+ subagent,
105
+ ...cwd === void 0 ? {} : { cwd }
106
+ };
107
+ if (type === "assistant/message") {
108
+ const usage = normalizeUsage(data.usage ?? lastStreamUsage(data.stream));
109
+ if (usage === void 0) continue;
110
+ const message = data.message;
111
+ const provider = text(message?.source?.provider) ?? route.provider;
112
+ const model = text(message?.source?.model) ?? route.model;
113
+ route = {
114
+ provider,
115
+ model
116
+ };
117
+ records.push({
118
+ key: text(message?.id) ?? `${sessionId}#${seq}`,
119
+ kind: "message",
120
+ provider,
121
+ model,
122
+ ...base,
123
+ ...usage
124
+ });
125
+ } else if (type === "assistant/attempt") {
126
+ const usage = normalizeUsage(lastStreamUsage(data.stream));
127
+ if (usage === void 0) continue;
128
+ records.push({
129
+ key: `${sessionId}#${seq}`,
130
+ kind: "attempt",
131
+ ...route,
132
+ ...base,
133
+ ...usage
134
+ });
135
+ } else if (type === "compaction/summary") {
136
+ const usage = normalizeUsage(data.usage);
137
+ if (usage === void 0) continue;
138
+ const key = text(data.compactionId) === void 0 ? `${sessionId}#${seq}` : `compaction:${data.compactionId}`;
139
+ records.push({
140
+ key,
141
+ kind: "compaction",
142
+ provider: text(data.provider) ?? route.provider,
143
+ model: text(data.model) ?? route.model,
144
+ ...base,
145
+ ...usage
146
+ });
147
+ }
148
+ }
149
+ if (title !== void 0) for (const record of records) record.title = title;
150
+ return records;
151
+ }
152
+ const ZSTD_MAGIC = 4247762216;
153
+ /**
154
+ * Split a buffer of concatenated zstd frames. DSH appends one frame per
155
+ * write, and Node's zstd decoder stops after the first frame of its input,
156
+ * so each frame is located here and decoded on its own. Skippable frames are
157
+ * skipped; a truncated last frame (a log still being written) ends the list.
158
+ */
159
+ function* zstdFrames(buffer) {
160
+ let at = 0;
161
+ while (at + 8 <= buffer.length) {
162
+ const magic = buffer.readUInt32LE(at);
163
+ if ((magic & 4294967280) === 407710288) {
164
+ at += 8 + buffer.readUInt32LE(at + 4);
165
+ continue;
166
+ }
167
+ if (magic !== ZSTD_MAGIC) return;
168
+ const descriptor = buffer[at + 4] ?? 0;
169
+ const fcsFlag = descriptor >> 6;
170
+ const singleSegment = descriptor >> 5 & 1;
171
+ const checksum = descriptor >> 2 & 1;
172
+ const dictFlag = descriptor & 3;
173
+ let cursor = at + 5 + (singleSegment === 1 ? 0 : 1) + [
174
+ 0,
175
+ 1,
176
+ 2,
177
+ 4
178
+ ][dictFlag] + [
179
+ singleSegment,
180
+ 2,
181
+ 4,
182
+ 8
183
+ ][fcsFlag];
184
+ for (;;) {
185
+ if (cursor + 3 > buffer.length) return;
186
+ const header = buffer.readUIntLE(cursor, 3);
187
+ const last = header & 1;
188
+ const type = header >> 1 & 3;
189
+ const size = header >>> 3;
190
+ if (type === 3) return;
191
+ cursor += 3 + (type === 1 ? 1 : size);
192
+ if (last === 1) break;
193
+ }
194
+ cursor += checksum === 1 ? 4 : 0;
195
+ if (cursor > buffer.length) return;
196
+ yield buffer.subarray(at, cursor);
197
+ at = cursor;
198
+ }
199
+ }
200
+ function* decodeLines(chunks) {
201
+ const decoder = new TextDecoder();
202
+ let carry = "";
203
+ const parse = function* (text) {
204
+ for (const line of text.split("\n")) {
205
+ if (line === "") continue;
206
+ try {
207
+ yield JSON.parse(line);
208
+ } catch {}
209
+ }
210
+ };
211
+ for (const chunk of chunks) {
212
+ const text = carry + decoder.decode(chunk, { stream: true });
213
+ const end = text.lastIndexOf("\n");
214
+ carry = end === -1 ? text : text.slice(end + 1);
215
+ if (end !== -1) yield* parse(text.slice(0, end));
216
+ }
217
+ yield* parse(carry + decoder.decode());
218
+ }
219
+ function* decompressFrames(buffer) {
220
+ for (const frame of zstdFrames(buffer)) try {
221
+ yield zstdDecompressSync(frame);
222
+ } catch {
223
+ return;
224
+ }
225
+ }
226
+ const WANTED = /* @__PURE__ */ new Set([
227
+ "session",
228
+ "session/end-seed",
229
+ "session/title",
230
+ "request/header",
231
+ "assistant/message",
232
+ "assistant/attempt",
233
+ "compaction/summary"
234
+ ]);
235
+ /** Read one session log (`session.v4.jsonl` or `.jsonl.zstd`). */
236
+ async function readSessionLog(file) {
237
+ const buffer = await readFile(file);
238
+ const chunks = file.endsWith(".zstd") ? decompressFrames(buffer) : [buffer];
239
+ const events = [];
240
+ for (const event of decodeLines(chunks)) {
241
+ if (typeof event.type !== "string" || !WANTED.has(event.type)) continue;
242
+ events.push(event.type === "assistant/message" ? slimMessage(event) : event);
243
+ }
244
+ return recordsFromEvents(events);
245
+ }
246
+ function slimMessage(event) {
247
+ const data = event.data ?? {};
248
+ const message = data.message;
249
+ return {
250
+ type: event.type,
251
+ seq: event.seq,
252
+ time: event.time,
253
+ data: {
254
+ usage: data.usage ?? lastStreamUsage(data.stream),
255
+ message: {
256
+ id: message?.id,
257
+ source: {
258
+ provider: message?.source?.provider,
259
+ model: message?.source?.model
260
+ }
261
+ }
262
+ }
263
+ };
264
+ }
265
+ /** Every session log under `<dsh home>/sessions/<workspace>/<session>/`. */
266
+ async function findSessionLogs(sessionsDir) {
267
+ const found = [];
268
+ const list = async (dir) => readdir(dir).catch(() => []);
269
+ for (const workspace of await list(sessionsDir)) for (const session of await list(join(sessionsDir, workspace))) for (const file of await list(join(sessionsDir, workspace, session))) {
270
+ if (!/^session\.v\d+\.jsonl(\.zstd)?$/.test(file)) continue;
271
+ const path = join(sessionsDir, workspace, session, file);
272
+ const info = await stat(path).catch(() => void 0);
273
+ if (info?.isFile() === true) found.push({
274
+ path,
275
+ size: info.size,
276
+ mtimeMs: info.mtimeMs
277
+ });
278
+ }
279
+ return found;
280
+ }
281
+ //#endregion
282
+ //#region lib/types/ledger.js
283
+ /**
284
+ * The usage ledger: every billed model call across all session logs, kept
285
+ * current incrementally. A log is read again only when its size or
286
+ * modification time changed; the per-log results are saved to an index file
287
+ * (`<root>/index.json`, 0600) so a restart does not re-read old logs.
288
+ *
289
+ * @module @natgurlain/dsh-token-usage/ledger
290
+ */
291
+ const INDEX_VERSION = 2;
292
+ var UsageLedger = class {
293
+ options;
294
+ logs = /* @__PURE__ */ new Map();
295
+ loaded = false;
296
+ pending;
297
+ constructor(options) {
298
+ this.options = options;
299
+ }
300
+ /** All records, after reading any log that changed. Concurrent calls share one refresh. */
301
+ records() {
302
+ this.pending ??= this.refresh().finally(() => {
303
+ this.pending = void 0;
304
+ });
305
+ return this.pending;
306
+ }
307
+ async load() {
308
+ if (this.loaded) return;
309
+ this.loaded = true;
310
+ if (this.options.indexFile === void 0) return;
311
+ try {
312
+ const parsed = JSON.parse(await readFile(this.options.indexFile, "utf8"));
313
+ if (parsed.version === INDEX_VERSION && parsed.logs !== null && typeof parsed.logs === "object") this.logs = new Map(Object.entries(parsed.logs));
314
+ } catch {}
315
+ }
316
+ async save() {
317
+ const file = this.options.indexFile;
318
+ if (file === void 0) return;
319
+ await mkdir(dirname(file), {
320
+ recursive: true,
321
+ mode: 448
322
+ });
323
+ const temp = join(dirname(file), `.index.${process.pid}.${Date.now()}.tmp`);
324
+ const body = {
325
+ version: INDEX_VERSION,
326
+ logs: Object.fromEntries(this.logs)
327
+ };
328
+ await writeFile(temp, JSON.stringify(body), { mode: 384 });
329
+ await rename(temp, file);
330
+ }
331
+ async refresh() {
332
+ await this.load();
333
+ const files = await findSessionLogs(this.options.sessionsDir);
334
+ let changed = false;
335
+ for (const file of files) {
336
+ const known = this.logs.get(file.path);
337
+ if (known !== void 0 && known.size === file.size && known.mtimeMs === file.mtimeMs) continue;
338
+ const records = await readSessionLog(file.path).catch(() => void 0);
339
+ if (records === void 0) continue;
340
+ this.logs.set(file.path, {
341
+ size: file.size,
342
+ mtimeMs: file.mtimeMs,
343
+ records
344
+ });
345
+ changed = true;
346
+ }
347
+ if (changed) await this.save().catch(() => void 0);
348
+ const seen = /* @__PURE__ */ new Set();
349
+ const all = [];
350
+ for (const entry of this.logs.values()) for (const record of entry.records) {
351
+ if (seen.has(record.key)) continue;
352
+ seen.add(record.key);
353
+ all.push(record);
354
+ }
355
+ all.sort((a, b) => a.time - b.time);
356
+ return all;
357
+ }
358
+ };
359
+ //#endregion
360
+ //#region lib/types/report.js
361
+ /**
362
+ * Summing usage records into reports: periods, groupings, optional prices,
363
+ * and a plain-text rendering for the `/usage` command, the tool and the CLI.
364
+ *
365
+ * @module @natgurlain/dsh-token-usage/report
366
+ */
367
+ const GROUPS = [
368
+ "day",
369
+ "model",
370
+ "workspace",
371
+ "session",
372
+ "kind"
373
+ ];
374
+ function emptyTotals() {
375
+ return {
376
+ calls: 0,
377
+ input: 0,
378
+ output: 0,
379
+ cacheRead: 0,
380
+ cacheWrite: 0,
381
+ reasoning: 0,
382
+ total: 0,
383
+ unpriced: 0
384
+ };
385
+ }
386
+ /** The price of a route: `provider/model` first, then the bare model name. */
387
+ function priceFor(prices, provider, model) {
388
+ return prices[`${provider}/${model}`] ?? prices[model];
389
+ }
390
+ function costOf(record, price) {
391
+ return (record.input * price.input + record.cacheRead * (price.cacheRead ?? price.input) + record.cacheWrite * (price.cacheWrite ?? price.input) + record.output * price.output) / 1e6;
392
+ }
393
+ function add(totals, record, prices) {
394
+ totals.calls += 1;
395
+ totals.input += record.input;
396
+ totals.output += record.output;
397
+ totals.cacheRead += record.cacheRead;
398
+ totals.cacheWrite += record.cacheWrite;
399
+ totals.reasoning += record.reasoning;
400
+ totals.total += record.total;
401
+ const price = priceFor(prices, record.provider, record.model);
402
+ if (price === void 0) totals.unpriced += 1;
403
+ else totals.cost = (totals.cost ?? 0) + costOf(record, price);
404
+ }
405
+ /** The local calendar day of a time, as YYYY-MM-DD. */
406
+ function dayOf(time, timeZone) {
407
+ const parts = new Intl.DateTimeFormat("en-CA", {
408
+ timeZone,
409
+ year: "numeric",
410
+ month: "2-digit",
411
+ day: "2-digit"
412
+ }).formatToParts(new Date(time));
413
+ const get = (type) => parts.find((part) => part.type === type)?.value ?? "00";
414
+ return `${get("year")}-${get("month")}-${get("day")}`;
415
+ }
416
+ /** Add days to a YYYY-MM-DD date (calendar arithmetic, no time zone involved). */
417
+ function shiftDay(day, days) {
418
+ const date = /* @__PURE__ */ new Date(`${day}T00:00:00Z`);
419
+ date.setUTCDate(date.getUTCDate() + days);
420
+ return date.toISOString().slice(0, 10);
421
+ }
422
+ const DAY = /^\d{4}-\d{2}-\d{2}$/;
423
+ /**
424
+ * Parse a period: `today`, `yesterday`, `week` (last 7 days), `month` (last
425
+ * 30 days), `all`, a number of days (`14`, `14d`), a day (`2026-12-01`), a
426
+ * month (`2026-12`) or a range (`2026-11-01..2026-11-30`, inclusive).
427
+ */
428
+ function parsePeriod(input, today) {
429
+ const word = (input ?? "").trim().toLowerCase();
430
+ const lastDays = (n, label) => ({
431
+ label,
432
+ from: shiftDay(today, 1 - n),
433
+ to: shiftDay(today, 1)
434
+ });
435
+ if (word === "" || word === "all") return { label: "all time" };
436
+ if (word === "today") return lastDays(1, `today (${today})`);
437
+ if (word === "yesterday") {
438
+ const day = shiftDay(today, -1);
439
+ return {
440
+ label: `yesterday (${day})`,
441
+ from: day,
442
+ to: today
443
+ };
444
+ }
445
+ if (word === "week") return lastDays(7, "the last 7 days");
446
+ if (word === "month") return lastDays(30, "the last 30 days");
447
+ const days = /^(\d{1,4})d?$/.exec(word);
448
+ if (days !== null) {
449
+ const n = Number(days[1]);
450
+ return n >= 1 ? lastDays(n, n === 1 ? `today (${today})` : `the last ${n} days`) : void 0;
451
+ }
452
+ if (DAY.test(word)) return {
453
+ label: word,
454
+ from: word,
455
+ to: shiftDay(word, 1)
456
+ };
457
+ if (/^(\d{4})-(\d{2})$/.exec(word) !== null) {
458
+ const from = `${word}-01`;
459
+ const next = /* @__PURE__ */ new Date(`${from}T00:00:00Z`);
460
+ next.setUTCMonth(next.getUTCMonth() + 1);
461
+ return {
462
+ label: word,
463
+ from,
464
+ to: next.toISOString().slice(0, 10)
465
+ };
466
+ }
467
+ const range = /^(\d{4}-\d{2}-\d{2})\.\.(\d{4}-\d{2}-\d{2})$/.exec(word);
468
+ if (range !== null && range[1] !== void 0 && range[2] !== void 0 && range[1] <= range[2]) return {
469
+ label: `${range[1]} to ${range[2]}`,
470
+ from: range[1],
471
+ to: shiftDay(range[2], 1)
472
+ };
473
+ }
474
+ function groupKey(record, by, timeZone) {
475
+ switch (by) {
476
+ case "day": {
477
+ const day = dayOf(record.time, timeZone);
478
+ return {
479
+ key: day,
480
+ label: day
481
+ };
482
+ }
483
+ case "model": return {
484
+ key: `${record.provider}/${record.model}`,
485
+ label: `${record.provider}/${record.model}`
486
+ };
487
+ case "workspace": return record.cwd === void 0 ? {
488
+ key: "",
489
+ label: "(no folder)"
490
+ } : {
491
+ key: record.cwd,
492
+ label: record.cwd
493
+ };
494
+ case "session": {
495
+ const name = record.title ?? record.sessionId.replace(/^session-/, "").slice(0, 8);
496
+ const where = record.cwd === void 0 ? "" : ` · ${basename(record.cwd)}`;
497
+ return {
498
+ key: record.sessionId,
499
+ label: `${name}${record.subagent ? " (subagent)" : ""}${where}`
500
+ };
501
+ }
502
+ case "kind": return {
503
+ key: record.kind,
504
+ label: record.kind === "message" ? "replies" : record.kind === "attempt" ? "failed or retried calls" : "compaction"
505
+ };
506
+ }
507
+ }
508
+ function buildReport(records, options) {
509
+ const prices = options.prices ?? {};
510
+ const rows = /* @__PURE__ */ new Map();
511
+ const totals = emptyTotals();
512
+ const sessions = /* @__PURE__ */ new Set();
513
+ for (const record of records) {
514
+ if (options.excludeSubagents === true && record.subagent) continue;
515
+ if (options.cwd !== void 0 && record.cwd !== options.cwd) continue;
516
+ const day = dayOf(record.time, options.timeZone);
517
+ if (options.period.from !== void 0 && day < options.period.from) continue;
518
+ if (options.period.to !== void 0 && day >= options.period.to) continue;
519
+ const { key, label } = groupKey(record, options.by, options.timeZone);
520
+ let row = rows.get(key);
521
+ if (row === void 0) {
522
+ row = {
523
+ key,
524
+ label,
525
+ ...emptyTotals()
526
+ };
527
+ rows.set(key, row);
528
+ }
529
+ add(row, record, prices);
530
+ add(totals, record, prices);
531
+ sessions.add(record.sessionId);
532
+ }
533
+ const sorted = [...rows.values()];
534
+ if (options.by === "day") sorted.sort((a, b) => b.key.localeCompare(a.key));
535
+ else sorted.sort((a, b) => b.total - a.total);
536
+ return {
537
+ period: options.period,
538
+ by: options.by,
539
+ rows: sorted,
540
+ totals,
541
+ priced: totals.cost !== void 0,
542
+ sessions: sessions.size
543
+ };
544
+ }
545
+ /** 1234 → 1.2k, 1234567 → 1.23M. */
546
+ function compact(n) {
547
+ if (n < 1e3) return String(n);
548
+ for (const [size, unit] of [
549
+ [0xe8d4a51000, "T"],
550
+ [1e9, "B"],
551
+ [1e6, "M"],
552
+ [1e3, "k"]
553
+ ]) if (n >= size) {
554
+ const value = n / size;
555
+ return `${value >= 100 ? value.toFixed(0) : value >= 10 ? value.toFixed(1) : value.toFixed(2)}${unit}`;
556
+ }
557
+ return String(n);
558
+ }
559
+ function usd(n) {
560
+ return n >= 100 ? `$${n.toFixed(0)}` : n >= 1 ? `$${n.toFixed(2)}` : `$${n.toFixed(3)}`;
561
+ }
562
+ const BAR_WIDTH = 16;
563
+ /** Render a report as aligned plain text. */
564
+ function renderReport(report, options = {}) {
565
+ const { totals } = report;
566
+ const head = `Token usage, ${report.period.label}: ${compact(totals.total)} tokens in ${totals.calls} model calls across ${report.sessions} sessions${report.priced ? `, about ${usd(totals.cost ?? 0)}` : ""}.`;
567
+ if (totals.calls === 0) return `${head}\nNothing recorded in this period.`;
568
+ const breakdown = `Input ${compact(totals.input)} · cache read ${compact(totals.cacheRead)} · cache write ${compact(totals.cacheWrite)} · output ${compact(totals.output)}${totals.reasoning > 0 ? ` (reasoning ${compact(totals.reasoning)})` : ""}`;
569
+ const limit = options.limit ?? 30;
570
+ const shown = report.rows.slice(0, limit);
571
+ const max = Math.max(...shown.map((row) => row.total), 1);
572
+ const columns = [
573
+ "Total",
574
+ "Input",
575
+ "Cache rd",
576
+ "Output",
577
+ "Calls",
578
+ ...report.priced ? ["Cost"] : []
579
+ ];
580
+ const cells = shown.map((row) => [
581
+ compact(row.total),
582
+ compact(row.input),
583
+ compact(row.cacheRead),
584
+ compact(row.output),
585
+ String(row.calls),
586
+ ...report.priced ? [row.cost === void 0 ? "-" : `${usd(row.cost)}${row.unpriced > 0 ? "*" : ""}`] : []
587
+ ]);
588
+ const labelWidth = Math.min(Math.max(report.by.length, ...shown.map((row) => row.label.length)), 48);
589
+ const widths = columns.map((column, i) => Math.max(column.length, ...cells.map((row) => (row[i] ?? "").length)));
590
+ const clip = (label) => label.length > labelWidth ? `…${label.slice(label.length - labelWidth + 1)}` : label;
591
+ const line = (label, values, bar) => [
592
+ clip(label).padEnd(labelWidth),
593
+ ...values.map((value, i) => value.padStart(widths[i] ?? 0)),
594
+ bar
595
+ ].join(" ").trimEnd();
596
+ const header = line(report.by[0]?.toUpperCase() + report.by.slice(1), columns, "");
597
+ const body = shown.map((row, i) => line(row.label, cells[i] ?? [], "█".repeat(Math.max(1, Math.round(row.total / max * BAR_WIDTH)))));
598
+ const more = report.rows.length > shown.length ? [`… and ${report.rows.length - shown.length} more`] : [];
599
+ const notes = report.priced && totals.unpriced > 0 ? [`* ${totals.unpriced} calls have no price configured and are not in the cost.`] : [];
600
+ return [
601
+ head,
602
+ breakdown,
603
+ "",
604
+ header,
605
+ ...body,
606
+ ...more,
607
+ ...notes
608
+ ].join("\n");
609
+ }
610
+ //#endregion
611
+ //#region lib/types/query.js
612
+ /**
613
+ * One query language for the `/usage` command, the `token_usage` tool and
614
+ * the CLI: a period word, a grouping, and `here` for this workspace only.
615
+ *
616
+ * ```
617
+ * /usage overview, then the last 14 days by day
618
+ * /usage today | week | month one period, by day
619
+ * /usage 30 by model the last 30 days, by model
620
+ * /usage 2026-11 workspaces November, by workspace
621
+ * /usage week sessions here this workspace's sessions this week
622
+ * ```
623
+ *
624
+ * @module @natgurlain/dsh-token-usage/query
625
+ */
626
+ const ALIASES = {
627
+ day: "day",
628
+ days: "day",
629
+ daily: "day",
630
+ model: "model",
631
+ models: "model",
632
+ workspace: "workspace",
633
+ workspaces: "workspace",
634
+ folder: "workspace",
635
+ folders: "workspace",
636
+ project: "workspace",
637
+ projects: "workspace",
638
+ session: "session",
639
+ sessions: "session",
640
+ conversation: "session",
641
+ conversations: "session",
642
+ kind: "kind",
643
+ kinds: "kind",
644
+ type: "kind"
645
+ };
646
+ /** Parse command words; returns an error message for words it does not know. */
647
+ function parseQuery(words) {
648
+ const query = {};
649
+ for (const raw of words) {
650
+ const word = raw.toLowerCase();
651
+ if (word === "by" || word === "per") continue;
652
+ if (word === "here") query.here = true;
653
+ else if (word === "nosub" || word === "no-subagents") query.noSubagents = true;
654
+ else if (ALIASES[word] !== void 0) query.by = ALIASES[word];
655
+ else if (query.period === void 0) query.period = word;
656
+ else return `Unknown word "${raw}".`;
657
+ }
658
+ return query;
659
+ }
660
+ const USAGE_HINT = "[today | yesterday | week | month | all | <days> | <YYYY-MM[-DD]> | <from>..<to>] [by day | model | workspace | session | kind] [here]";
661
+ /** Answer a query as plain text. */
662
+ function answer(records, query, context = {}) {
663
+ const today = dayOf(context.now ?? Date.now(), context.timeZone);
664
+ if (query.here === true && context.cwd === void 0) return "This conversation has no working directory, so \"here\" has nothing to filter by.";
665
+ const scope = {
666
+ ...context.prices === void 0 ? {} : { prices: context.prices },
667
+ ...context.timeZone === void 0 ? {} : { timeZone: context.timeZone },
668
+ ...query.here === true && context.cwd !== void 0 ? { cwd: context.cwd } : {},
669
+ ...query.noSubagents === true ? { excludeSubagents: true } : {}
670
+ };
671
+ const where = scope.cwd === void 0 ? "" : ` in ${scope.cwd}`;
672
+ if (query.period === void 0 && query.by === void 0) {
673
+ const sum = (word) => {
674
+ const period = parsePeriod(word, today);
675
+ const report = buildReport(records, {
676
+ ...scope,
677
+ period: period ?? { label: word },
678
+ by: "kind"
679
+ });
680
+ return `${compact(report.totals.total)}${report.priced ? ` (${usd(report.totals.cost ?? 0)})` : ""}`;
681
+ };
682
+ const overview = `Today ${sum("today")} · 7 days ${sum("week")} · 30 days ${sum("month")} · all time ${sum("all")} tokens${where}`;
683
+ const recent = buildReport(records, {
684
+ ...scope,
685
+ period: parsePeriod("14", today) ?? { label: "the last 14 days" },
686
+ by: "day"
687
+ });
688
+ return withNote(`${overview}\n\n${renderReport(recent, query.limit === void 0 ? {} : { limit: query.limit })}`, recent.priced, context.priceNote);
689
+ }
690
+ const period = parsePeriod(query.period ?? (query.by === void 0 || query.by === "day" ? "30" : "all"), today);
691
+ if (period === void 0) return `Unknown period "${query.period ?? ""}". Usage: /usage ${USAGE_HINT}`;
692
+ const report = buildReport(records, {
693
+ ...scope,
694
+ period: {
695
+ ...period,
696
+ label: `${period.label}${where}`
697
+ },
698
+ by: query.by ?? "day"
699
+ });
700
+ return withNote(renderReport(report, query.limit === void 0 ? {} : { limit: query.limit }), report.priced, context.priceNote);
701
+ }
702
+ function withNote(text, priced, note) {
703
+ return priced && note !== void 0 ? `${text}\n${note}` : text;
704
+ }
705
+ //#endregion
706
+ //#region lib/types/openrouter.js
707
+ /**
708
+ * OpenRouter list prices, to estimate what a model would cost there: useful
709
+ * for models you run yourself (a local GPU server), which have no bill.
710
+ *
711
+ * The public `GET https://openrouter.ai/api/v1/models` list is fetched at most
712
+ * once per `refreshHours` and only when a report needs prices; nothing about
713
+ * the user or their sessions is sent. A failed fetch falls back to the last
714
+ * saved copy. A DSH route matches an OpenRouter model by its bare model name
715
+ * (`inkling-local/qwen4-35b-a3b` → `qwen/qwen4-35b-a3b`), case-insensitively,
716
+ * ignoring variants like `:batch`; `models` in the config maps routes by hand.
717
+ *
718
+ * @module @natgurlain/dsh-token-usage/openrouter
719
+ */
720
+ const OPENROUTER_MODELS_URL = "https://openrouter.ai/api/v1/models";
721
+ /** USD per token as a string → USD per million tokens; undefined when unusable. */
722
+ function perMillion(value) {
723
+ if (value === void 0) return void 0;
724
+ const n = Number(value);
725
+ return Number.isFinite(n) && n >= 0 ? Math.round(n * 1e6 * 1e6) / 1e6 : void 0;
726
+ }
727
+ /** Turn OpenRouter's list into prices; models without prompt and completion prices (or priced below zero, like the router) are left out. */
728
+ function parseModels(models) {
729
+ const out = [];
730
+ for (const model of models) {
731
+ if (typeof model?.id !== "string") continue;
732
+ const input = perMillion(model.pricing?.prompt);
733
+ const output = perMillion(model.pricing?.completion);
734
+ if (input === void 0 || output === void 0) continue;
735
+ const cacheRead = perMillion(model.pricing?.input_cache_read);
736
+ const cacheWrite = perMillion(model.pricing?.input_cache_write);
737
+ out.push({
738
+ id: model.id,
739
+ price: {
740
+ input,
741
+ output,
742
+ ...cacheRead === void 0 ? {} : { cacheRead },
743
+ ...cacheWrite === void 0 ? {} : { cacheWrite }
744
+ }
745
+ });
746
+ }
747
+ return out;
748
+ }
749
+ const bare = (id) => (id.split(":")[0] ?? id).split("/").at(-1)?.toLowerCase() ?? "";
750
+ /**
751
+ * The OpenRouter model a DSH route corresponds to: an explicit mapping, the
752
+ * same id (an `openrouter` provider), or the one base model (no `:variant`,
753
+ * no `~` alias) with the same bare name. Two candidates are ambiguous: none.
754
+ */
755
+ function matchModel(provider, model, ids, mapping = {}) {
756
+ const mapped = mapping[`${provider}/${model}`] ?? mapping[model];
757
+ if (mapped !== void 0) return ids.has(mapped) ? mapped : void 0;
758
+ const lower = model.toLowerCase();
759
+ if (ids.has(lower)) return lower;
760
+ if (ids.has(model)) return model;
761
+ const name = bare(model);
762
+ if (name === "") return void 0;
763
+ const candidates = [...ids].filter((id) => !id.includes(":") && !id.startsWith("~") && bare(id) === name);
764
+ return candidates.length === 1 ? candidates[0] : void 0;
765
+ }
766
+ var OpenRouterPrices = class {
767
+ options;
768
+ cache;
769
+ loading;
770
+ constructor(options) {
771
+ this.options = options;
772
+ }
773
+ /** When the list in use was fetched; undefined before any list is known. */
774
+ get fetchedAt() {
775
+ return this.cache?.fetchedAt;
776
+ }
777
+ async read() {
778
+ try {
779
+ const parsed = JSON.parse(await readFile(this.options.cacheFile, "utf8"));
780
+ return typeof parsed.fetchedAt === "number" && Array.isArray(parsed.models) ? parsed : void 0;
781
+ } catch {
782
+ return;
783
+ }
784
+ }
785
+ async refresh() {
786
+ const now = this.options.now?.() ?? Date.now();
787
+ const maxAge = (this.options.refreshHours ?? 24) * 36e5;
788
+ this.cache ??= await this.read();
789
+ if (this.cache !== void 0 && now - this.cache.fetchedAt < maxAge) return;
790
+ try {
791
+ const response = await (this.options.fetch ?? fetch)(OPENROUTER_MODELS_URL, {
792
+ signal: AbortSignal.timeout(15e3),
793
+ headers: { accept: "application/json" }
794
+ });
795
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
796
+ const body = await response.json();
797
+ const models = parseModels(Array.isArray(body.data) ? body.data : []);
798
+ if (models.length === 0) throw new Error("empty model list");
799
+ this.cache = {
800
+ fetchedAt: now,
801
+ models
802
+ };
803
+ await mkdir(dirname(this.options.cacheFile), {
804
+ recursive: true,
805
+ mode: 448
806
+ });
807
+ const temp = join(dirname(this.options.cacheFile), `.openrouter.${process.pid}.${now}.tmp`);
808
+ await writeFile(temp, JSON.stringify(this.cache), { mode: 384 });
809
+ await rename(temp, this.options.cacheFile);
810
+ } catch {}
811
+ }
812
+ /** Make sure a list is loaded (fetching it when stale); concurrent calls share one fetch. */
813
+ async ready() {
814
+ this.loading ??= this.refresh().finally(() => {
815
+ this.loading = void 0;
816
+ });
817
+ await this.loading;
818
+ }
819
+ /** OpenRouter prices for the given routes, keyed `provider/model`. Call {@link ready} first. */
820
+ pricesFor(routes) {
821
+ const prices = {};
822
+ const sources = {};
823
+ if (this.cache === void 0) return {
824
+ prices,
825
+ sources
826
+ };
827
+ const byId = new Map(this.cache.models.map((entry) => [entry.id, entry.price]));
828
+ const ids = new Set(byId.keys());
829
+ for (const { provider, model } of routes) {
830
+ const key = `${provider}/${model}`;
831
+ if (key in prices) continue;
832
+ const id = matchModel(provider, model, ids, this.options.models);
833
+ const price = id === void 0 ? void 0 : byId.get(id);
834
+ if (id === void 0 || price === void 0) continue;
835
+ prices[key] = price;
836
+ sources[key] = {
837
+ openRouterId: id,
838
+ price
839
+ };
840
+ }
841
+ return {
842
+ prices,
843
+ sources
844
+ };
845
+ }
846
+ };
847
+ /** Configured prices win; OpenRouter fills in the routes they leave unpriced. */
848
+ function mergePrices(configured, fromOpenRouter) {
849
+ const merged = { ...fromOpenRouter };
850
+ for (const [key, price] of Object.entries(configured)) merged[key] = price;
851
+ for (const key of Object.keys(fromOpenRouter)) if (configured[key.slice(key.indexOf("/") + 1)] !== void 0) delete merged[key];
852
+ return merged;
853
+ }
854
+ //#endregion
855
+ export { findSessionLogs as _, USAGE_HINT as a, recordsFromEvents as b, GROUPS as c, emptyTotals as d, parsePeriod as f, UsageLedger as g, shiftDay as h, parseModels as i, buildReport as l, renderReport as m, matchModel as n, answer as o, priceFor as p, mergePrices as r, parseQuery as s, OpenRouterPrices as t, dayOf as u, normalizeUsage as v, readSessionLog as y };