@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.
package/src/report.ts ADDED
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Summing usage records into reports: periods, groupings, optional prices,
3
+ * and a plain-text rendering for the `/usage` command, the tool and the CLI.
4
+ *
5
+ * @module @natgurlain/dsh-token-usage/report
6
+ */
7
+
8
+ import { basename } from 'node:path'
9
+ import type { UsageRecord } from './scan.ts'
10
+
11
+ export type GroupBy = 'day' | 'model' | 'workspace' | 'session' | 'kind'
12
+ export const GROUPS: readonly GroupBy[] = ['day', 'model', 'workspace', 'session', 'kind']
13
+
14
+ /** USD per million tokens. Cache prices default to the input price. */
15
+ export interface Price {
16
+ input: number
17
+ output: number
18
+ cacheRead?: number
19
+ cacheWrite?: number
20
+ }
21
+
22
+ export type Prices = Record<string, Price>
23
+
24
+ export interface Totals {
25
+ calls: number
26
+ input: number
27
+ output: number
28
+ cacheRead: number
29
+ cacheWrite: number
30
+ reasoning: number
31
+ total: number
32
+ /** USD; undefined when no call in the group has a price. */
33
+ cost?: number
34
+ /** Calls without a price, when some have one. */
35
+ unpriced: number
36
+ }
37
+
38
+ export interface Row extends Totals {
39
+ key: string
40
+ label: string
41
+ }
42
+
43
+ /** A half-open range of local days, `from` inclusive, `to` exclusive (YYYY-MM-DD). */
44
+ export interface Period {
45
+ label: string
46
+ from?: string
47
+ to?: string
48
+ }
49
+
50
+ export function emptyTotals(): Totals {
51
+ return { calls: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0, total: 0, unpriced: 0 }
52
+ }
53
+
54
+ /** The price of a route: `provider/model` first, then the bare model name. */
55
+ export function priceFor(prices: Prices, provider: string, model: string): Price | undefined {
56
+ return prices[`${provider}/${model}`] ?? prices[model]
57
+ }
58
+
59
+ export function costOf(record: Pick<UsageRecord, 'input' | 'output' | 'cacheRead' | 'cacheWrite'>, price: Price): number {
60
+ return (
61
+ record.input * price.input
62
+ + record.cacheRead * (price.cacheRead ?? price.input)
63
+ + record.cacheWrite * (price.cacheWrite ?? price.input)
64
+ + record.output * price.output
65
+ ) / 1_000_000
66
+ }
67
+
68
+ function add(totals: Totals, record: UsageRecord, prices: Prices): void {
69
+ totals.calls += 1
70
+ totals.input += record.input
71
+ totals.output += record.output
72
+ totals.cacheRead += record.cacheRead
73
+ totals.cacheWrite += record.cacheWrite
74
+ totals.reasoning += record.reasoning
75
+ totals.total += record.total
76
+ const price = priceFor(prices, record.provider, record.model)
77
+ if (price === undefined) totals.unpriced += 1
78
+ else totals.cost = (totals.cost ?? 0) + costOf(record, price)
79
+ }
80
+
81
+ /** The local calendar day of a time, as YYYY-MM-DD. */
82
+ export function dayOf(time: number, timeZone?: string): string {
83
+ const parts = new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' }).formatToParts(new Date(time))
84
+ const get = (type: string): string => parts.find((part) => part.type === type)?.value ?? '00'
85
+ return `${get('year')}-${get('month')}-${get('day')}`
86
+ }
87
+
88
+ /** Add days to a YYYY-MM-DD date (calendar arithmetic, no time zone involved). */
89
+ export function shiftDay(day: string, days: number): string {
90
+ const date = new Date(`${day}T00:00:00Z`)
91
+ date.setUTCDate(date.getUTCDate() + days)
92
+ return date.toISOString().slice(0, 10)
93
+ }
94
+
95
+ const DAY = /^\d{4}-\d{2}-\d{2}$/
96
+
97
+ /**
98
+ * Parse a period: `today`, `yesterday`, `week` (last 7 days), `month` (last
99
+ * 30 days), `all`, a number of days (`14`, `14d`), a day (`2026-12-01`), a
100
+ * month (`2026-12`) or a range (`2026-11-01..2026-11-30`, inclusive).
101
+ */
102
+ export function parsePeriod(input: string | undefined, today: string): Period | undefined {
103
+ const word = (input ?? '').trim().toLowerCase()
104
+ const lastDays = (n: number, label: string): Period => ({ label, from: shiftDay(today, 1 - n), to: shiftDay(today, 1) })
105
+ if (word === '' || word === 'all') return { label: 'all time' }
106
+ if (word === 'today') return lastDays(1, `today (${today})`)
107
+ if (word === 'yesterday') {
108
+ const day = shiftDay(today, -1)
109
+ return { label: `yesterday (${day})`, from: day, to: today }
110
+ }
111
+ if (word === 'week') return lastDays(7, 'the last 7 days')
112
+ if (word === 'month') return lastDays(30, 'the last 30 days')
113
+ const days = /^(\d{1,4})d?$/.exec(word)
114
+ if (days !== null) {
115
+ const n = Number(days[1])
116
+ return n >= 1 ? lastDays(n, n === 1 ? `today (${today})` : `the last ${n} days`) : undefined
117
+ }
118
+ if (DAY.test(word)) return { label: word, from: word, to: shiftDay(word, 1) }
119
+ const month = /^(\d{4})-(\d{2})$/.exec(word)
120
+ if (month !== null) {
121
+ const from = `${word}-01`
122
+ const next = new Date(`${from}T00:00:00Z`)
123
+ next.setUTCMonth(next.getUTCMonth() + 1)
124
+ return { label: word, from, to: next.toISOString().slice(0, 10) }
125
+ }
126
+ const range = /^(\d{4}-\d{2}-\d{2})\.\.(\d{4}-\d{2}-\d{2})$/.exec(word)
127
+ if (range !== null && range[1] !== undefined && range[2] !== undefined && range[1] <= range[2]) {
128
+ return { label: `${range[1]} to ${range[2]}`, from: range[1], to: shiftDay(range[2], 1) }
129
+ }
130
+ return undefined
131
+ }
132
+
133
+ export interface ReportOptions {
134
+ period: Period
135
+ by: GroupBy
136
+ prices?: Prices
137
+ timeZone?: string
138
+ /** Only sessions in this working directory. */
139
+ cwd?: string
140
+ /** Leave out subagent sessions. */
141
+ excludeSubagents?: boolean
142
+ }
143
+
144
+ export interface Report {
145
+ period: Period
146
+ by: GroupBy
147
+ rows: Row[]
148
+ totals: Totals
149
+ priced: boolean
150
+ /** Distinct sessions in the period. */
151
+ sessions: number
152
+ }
153
+
154
+ function groupKey(record: UsageRecord, by: GroupBy, timeZone: string | undefined): { key: string; label: string } {
155
+ switch (by) {
156
+ case 'day': {
157
+ const day = dayOf(record.time, timeZone)
158
+ return { key: day, label: day }
159
+ }
160
+ case 'model':
161
+ return { key: `${record.provider}/${record.model}`, label: `${record.provider}/${record.model}` }
162
+ case 'workspace':
163
+ return record.cwd === undefined ? { key: '', label: '(no folder)' } : { key: record.cwd, label: record.cwd }
164
+ case 'session': {
165
+ const name = record.title ?? record.sessionId.replace(/^session-/, '').slice(0, 8)
166
+ const where = record.cwd === undefined ? '' : ` · ${basename(record.cwd)}`
167
+ return { key: record.sessionId, label: `${name}${record.subagent ? ' (subagent)' : ''}${where}` }
168
+ }
169
+ case 'kind':
170
+ return { key: record.kind, label: record.kind === 'message' ? 'replies' : record.kind === 'attempt' ? 'failed or retried calls' : 'compaction' }
171
+ }
172
+ }
173
+
174
+ export function buildReport(records: readonly UsageRecord[], options: ReportOptions): Report {
175
+ const prices = options.prices ?? {}
176
+ const rows = new Map<string, Row>()
177
+ const totals = emptyTotals()
178
+ const sessions = new Set<string>()
179
+ for (const record of records) {
180
+ if (options.excludeSubagents === true && record.subagent) continue
181
+ if (options.cwd !== undefined && record.cwd !== options.cwd) continue
182
+ const day = dayOf(record.time, options.timeZone)
183
+ if (options.period.from !== undefined && day < options.period.from) continue
184
+ if (options.period.to !== undefined && day >= options.period.to) continue
185
+ const { key, label } = groupKey(record, options.by, options.timeZone)
186
+ let row = rows.get(key)
187
+ if (row === undefined) {
188
+ row = { key, label, ...emptyTotals() }
189
+ rows.set(key, row)
190
+ }
191
+ add(row, record, prices)
192
+ add(totals, record, prices)
193
+ sessions.add(record.sessionId)
194
+ }
195
+ const sorted = [...rows.values()]
196
+ if (options.by === 'day') sorted.sort((a, b) => b.key.localeCompare(a.key))
197
+ else sorted.sort((a, b) => b.total - a.total)
198
+ return { period: options.period, by: options.by, rows: sorted, totals, priced: totals.cost !== undefined, sessions: sessions.size }
199
+ }
200
+
201
+ /** 1234 → 1.2k, 1234567 → 1.23M. */
202
+ export function compact(n: number): string {
203
+ if (n < 1000) return String(n)
204
+ const units: Array<[number, string]> = [[1e12, 'T'], [1e9, 'B'], [1e6, 'M'], [1e3, 'k']]
205
+ for (const [size, unit] of units) {
206
+ if (n >= size) {
207
+ const value = n / size
208
+ return `${value >= 100 ? value.toFixed(0) : value >= 10 ? value.toFixed(1) : value.toFixed(2)}${unit}`
209
+ }
210
+ }
211
+ return String(n)
212
+ }
213
+
214
+ export function usd(n: number): string {
215
+ return n >= 100 ? `$${n.toFixed(0)}` : n >= 1 ? `$${n.toFixed(2)}` : `$${n.toFixed(3)}`
216
+ }
217
+
218
+ const BAR_WIDTH = 16
219
+
220
+ /** Render a report as aligned plain text. */
221
+ export function renderReport(report: Report, options: { limit?: number } = {}): string {
222
+ const { totals } = report
223
+ 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)}` : ''}.`
224
+ if (totals.calls === 0) return `${head}\nNothing recorded in this period.`
225
+ 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)})` : ''}`
226
+ const limit = options.limit ?? 30
227
+ const shown = report.rows.slice(0, limit)
228
+ const max = Math.max(...shown.map((row) => row.total), 1)
229
+ const columns = ['Total', 'Input', 'Cache rd', 'Output', 'Calls', ...(report.priced ? ['Cost'] : [])]
230
+ const cells = shown.map((row) => [
231
+ compact(row.total), compact(row.input), compact(row.cacheRead), compact(row.output), String(row.calls),
232
+ ...(report.priced ? [row.cost === undefined ? '-' : `${usd(row.cost)}${row.unpriced > 0 ? '*' : ''}`] : []),
233
+ ])
234
+ const labelWidth = Math.min(Math.max(report.by.length, ...shown.map((row) => row.label.length)), 48)
235
+ const widths = columns.map((column, i) => Math.max(column.length, ...cells.map((row) => (row[i] ?? '').length)))
236
+ const clip = (label: string): string => label.length > labelWidth ? `…${label.slice(label.length - labelWidth + 1)}` : label
237
+ const line = (label: string, values: readonly string[], bar: string): string =>
238
+ [clip(label).padEnd(labelWidth), ...values.map((value, i) => value.padStart(widths[i] ?? 0)), bar].join(' ').trimEnd()
239
+ const header = line(report.by[0]?.toUpperCase() + report.by.slice(1), columns, '')
240
+ const body = shown.map((row, i) => line(row.label, cells[i] ?? [], '█'.repeat(Math.max(1, Math.round(row.total / max * BAR_WIDTH)))))
241
+ const more = report.rows.length > shown.length ? [`… and ${report.rows.length - shown.length} more`] : []
242
+ const notes = report.priced && totals.unpriced > 0 ? [`* ${totals.unpriced} calls have no price configured and are not in the cost.`] : []
243
+ return [head, breakdown, '', header, ...body, ...more, ...notes].join('\n')
244
+ }
package/src/scan.ts ADDED
@@ -0,0 +1,289 @@
1
+ /**
2
+ * Reading token usage out of DSH's session logs.
3
+ *
4
+ * Every model call DSH makes for a conversation is logged with the usage the
5
+ * provider reported:
6
+ *
7
+ * - `assistant/message`: a completed step, `data.usage`, with the route in
8
+ * `data.message.source`.
9
+ * - `assistant/attempt`: a failed or retried call, its usage in the last
10
+ * `usage` chunk of `data.stream`. It has no route of its own, so it takes
11
+ * the route of the session's latest `request/header`.
12
+ * - `compaction/summary`: the summary call that compacts a long conversation,
13
+ * `data.usage` with `data.provider` and `data.model`.
14
+ *
15
+ * A seeded session (a fork or a resume) starts with a copy of another log
16
+ * up to `session/end-seed`; that copy is skipped so nothing counts twice.
17
+ * A session still being written (a trailing partial frame or line) yields
18
+ * what was complete.
19
+ *
20
+ * @module @natgurlain/dsh-token-usage/scan
21
+ */
22
+
23
+ import { readdir, readFile, stat } from 'node:fs/promises'
24
+ import { join } from 'node:path'
25
+ import { zstdDecompressSync } from 'node:zlib'
26
+
27
+ export type UsageKind = 'message' | 'attempt' | 'compaction'
28
+
29
+ /** One billed model call. */
30
+ export interface UsageRecord {
31
+ /** Unique across logs: message id, or session id + seq. */
32
+ key: string
33
+ /** Epoch milliseconds. */
34
+ time: number
35
+ sessionId: string
36
+ /** The session's working directory, when it has one. */
37
+ cwd?: string
38
+ /** True for subagent sessions. */
39
+ subagent: boolean
40
+ /** The session's latest title, when it has one. */
41
+ title?: string
42
+ kind: UsageKind
43
+ provider: string
44
+ model: string
45
+ /** Prompt tokens that were not read from or written to a cache. */
46
+ input: number
47
+ output: number
48
+ cacheRead: number
49
+ cacheWrite: number
50
+ /** Subset of output, when reported. */
51
+ reasoning: number
52
+ /** Prompt plus output, as the provider reported it (or the sum of the buckets). */
53
+ total: number
54
+ }
55
+
56
+ interface RawUsage {
57
+ inputTokens?: unknown
58
+ outputTokens?: unknown
59
+ totalTokens?: unknown
60
+ cacheReadTokens?: unknown
61
+ cacheWriteTokens?: unknown
62
+ reasoningTokens?: unknown
63
+ }
64
+
65
+ interface Event {
66
+ type?: unknown
67
+ seq?: unknown
68
+ time?: unknown
69
+ data?: Record<string, unknown>
70
+ [key: string]: unknown
71
+ }
72
+
73
+ const count = (value: unknown): number => typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0
74
+
75
+ /** Normalize a provider usage object; undefined when it reports nothing. */
76
+ export function normalizeUsage(raw: unknown): Pick<UsageRecord, 'input' | 'output' | 'cacheRead' | 'cacheWrite' | 'reasoning' | 'total'> | undefined {
77
+ if (raw === null || typeof raw !== 'object') return undefined
78
+ const usage = raw as RawUsage
79
+ const input = count(usage.inputTokens)
80
+ const output = count(usage.outputTokens)
81
+ const cacheRead = count(usage.cacheReadTokens)
82
+ const cacheWrite = count(usage.cacheWriteTokens)
83
+ const reasoning = Math.min(count(usage.reasoningTokens), output)
84
+ const sum = input + output + cacheRead + cacheWrite
85
+ const total = Math.max(count(usage.totalTokens), sum)
86
+ if (total === 0) return undefined
87
+ return { input, output, cacheRead, cacheWrite, reasoning, total }
88
+ }
89
+
90
+ function lastStreamUsage(stream: unknown): unknown {
91
+ if (!Array.isArray(stream)) return undefined
92
+ for (let i = stream.length - 1; i >= 0; i--) {
93
+ const entry = stream[i] as { type?: unknown; chunk?: { type?: unknown; usage?: unknown } } | undefined
94
+ if (entry?.type === 'chunk' && entry.chunk?.type === 'usage') return entry.chunk.usage
95
+ }
96
+ return undefined
97
+ }
98
+
99
+ const text = (value: unknown): string | undefined => typeof value === 'string' && value !== '' ? value : undefined
100
+
101
+ /** Fold one session's events (in log order) into usage records. */
102
+ export function recordsFromEvents(events: Iterable<Event>): UsageRecord[] {
103
+ const records: UsageRecord[] = []
104
+ let sessionId = 'unknown'
105
+ let cwd: string | undefined
106
+ let subagent = false
107
+ let seeding = false
108
+ let route = { provider: 'unknown', model: 'unknown' }
109
+ let title: string | undefined
110
+
111
+ for (const event of events) {
112
+ const type = event.type
113
+ if (type === 'session') {
114
+ sessionId = text(event.id) ?? sessionId
115
+ cwd = text(event.cwd)
116
+ subagent = event.origin === 'subagent' || count(event.delegationDepth) > 0
117
+ seeding = event.isSeeded === true
118
+ continue
119
+ }
120
+ if (type === 'session/end-seed') {
121
+ seeding = false
122
+ continue
123
+ }
124
+ if (type === 'session/title') {
125
+ title = text((event.data as { title?: unknown } | undefined)?.title) ?? title
126
+ continue
127
+ }
128
+ const data = event.data
129
+ if (data === undefined || data === null || typeof data !== 'object') continue
130
+ if (type === 'request/header') {
131
+ const config = (data.header as { config?: { provider?: unknown; model?: unknown } } | undefined)?.config
132
+ const provider = text(config?.provider)
133
+ const model = text(config?.model)
134
+ if (provider !== undefined && model !== undefined) route = { provider, model }
135
+ continue
136
+ }
137
+ if (seeding) continue
138
+
139
+ const time = typeof event.time === 'number' ? event.time : undefined
140
+ if (time === undefined) continue
141
+ const seq = typeof event.seq === 'number' ? event.seq : undefined
142
+ const base = { time, sessionId, subagent, ...(cwd === undefined ? {} : { cwd }) }
143
+
144
+ if (type === 'assistant/message') {
145
+ const usage = normalizeUsage(data.usage ?? lastStreamUsage(data.stream))
146
+ if (usage === undefined) continue
147
+ const message = data.message as { id?: unknown; source?: { provider?: unknown; model?: unknown } } | undefined
148
+ const provider = text(message?.source?.provider) ?? route.provider
149
+ const model = text(message?.source?.model) ?? route.model
150
+ route = { provider, model }
151
+ records.push({ key: text(message?.id) ?? `${sessionId}#${seq}`, kind: 'message', provider, model, ...base, ...usage })
152
+ } else if (type === 'assistant/attempt') {
153
+ const usage = normalizeUsage(lastStreamUsage(data.stream))
154
+ if (usage === undefined) continue
155
+ records.push({ key: `${sessionId}#${seq}`, kind: 'attempt', ...route, ...base, ...usage })
156
+ } else if (type === 'compaction/summary') {
157
+ const usage = normalizeUsage(data.usage)
158
+ if (usage === undefined) continue
159
+ const key = text(data.compactionId) === undefined ? `${sessionId}#${seq}` : `compaction:${data.compactionId as string}`
160
+ records.push({ key, kind: 'compaction', provider: text(data.provider) ?? route.provider, model: text(data.model) ?? route.model, ...base, ...usage })
161
+ }
162
+ }
163
+ if (title !== undefined) for (const record of records) record.title = title
164
+ return records
165
+ }
166
+
167
+ const ZSTD_MAGIC = 0xfd2fb528
168
+
169
+ /**
170
+ * Split a buffer of concatenated zstd frames. DSH appends one frame per
171
+ * write, and Node's zstd decoder stops after the first frame of its input,
172
+ * so each frame is located here and decoded on its own. Skippable frames are
173
+ * skipped; a truncated last frame (a log still being written) ends the list.
174
+ */
175
+ export function* zstdFrames(buffer: Buffer): Generator<Buffer> {
176
+ let at = 0
177
+ while (at + 8 <= buffer.length) {
178
+ const magic = buffer.readUInt32LE(at)
179
+ if ((magic & 0xfffffff0) === 0x184d2a50) {
180
+ at += 8 + buffer.readUInt32LE(at + 4)
181
+ continue
182
+ }
183
+ if (magic !== ZSTD_MAGIC) return
184
+ const descriptor = buffer[at + 4] ?? 0
185
+ const fcsFlag = descriptor >> 6
186
+ const singleSegment = (descriptor >> 5) & 1
187
+ const checksum = (descriptor >> 2) & 1
188
+ const dictFlag = descriptor & 3
189
+ let cursor = at + 5 + (singleSegment === 1 ? 0 : 1) + [0, 1, 2, 4][dictFlag]! + [singleSegment, 2, 4, 8][fcsFlag]!
190
+ for (;;) {
191
+ if (cursor + 3 > buffer.length) return
192
+ const header = buffer.readUIntLE(cursor, 3)
193
+ const last = header & 1
194
+ const type = (header >> 1) & 3
195
+ const size = header >>> 3
196
+ if (type === 3) return
197
+ cursor += 3 + (type === 1 ? 1 : size)
198
+ if (last === 1) break
199
+ }
200
+ cursor += checksum === 1 ? 4 : 0
201
+ if (cursor > buffer.length) return
202
+ yield buffer.subarray(at, cursor)
203
+ at = cursor
204
+ }
205
+ }
206
+
207
+ function* decodeLines(chunks: Iterable<Buffer>): Generator<Event> {
208
+ const decoder = new TextDecoder()
209
+ let carry = ''
210
+ const parse = function* (text: string): Generator<Event> {
211
+ for (const line of text.split('\n')) {
212
+ if (line === '') continue
213
+ try {
214
+ yield JSON.parse(line) as Event
215
+ } catch {
216
+ // A torn line at the end of a log still being written.
217
+ }
218
+ }
219
+ }
220
+ for (const chunk of chunks) {
221
+ const text = carry + decoder.decode(chunk, { stream: true })
222
+ const end = text.lastIndexOf('\n')
223
+ carry = end === -1 ? text : text.slice(end + 1)
224
+ if (end !== -1) yield* parse(text.slice(0, end))
225
+ }
226
+ yield* parse(carry + decoder.decode())
227
+ }
228
+
229
+ function* decompressFrames(buffer: Buffer): Generator<Buffer> {
230
+ for (const frame of zstdFrames(buffer)) {
231
+ try {
232
+ yield zstdDecompressSync(frame)
233
+ } catch {
234
+ return
235
+ }
236
+ }
237
+ }
238
+
239
+ const WANTED = new Set(['session', 'session/end-seed', 'session/title', 'request/header', 'assistant/message', 'assistant/attempt', 'compaction/summary'])
240
+
241
+ /** Read one session log (`session.v4.jsonl` or `.jsonl.zstd`). */
242
+ export async function readSessionLog(file: string): Promise<UsageRecord[]> {
243
+ const buffer = await readFile(file)
244
+ const chunks = file.endsWith('.zstd') ? decompressFrames(buffer) : [buffer]
245
+ const events: Event[] = []
246
+ for (const event of decodeLines(chunks)) {
247
+ // Keep only what the fold needs; assistant streams can be large.
248
+ if (typeof event.type !== 'string' || !WANTED.has(event.type)) continue
249
+ events.push(event.type === 'assistant/message' ? slimMessage(event) : event)
250
+ }
251
+ return recordsFromEvents(events)
252
+ }
253
+
254
+ function slimMessage(event: Event): Event {
255
+ const data = event.data ?? {}
256
+ const message = data.message as { id?: unknown; source?: { provider?: unknown; model?: unknown } } | undefined
257
+ return {
258
+ type: event.type,
259
+ seq: event.seq,
260
+ time: event.time,
261
+ data: {
262
+ usage: data.usage ?? lastStreamUsage(data.stream),
263
+ message: { id: message?.id, source: { provider: message?.source?.provider, model: message?.source?.model } },
264
+ },
265
+ }
266
+ }
267
+
268
+ export interface LogFile {
269
+ path: string
270
+ size: number
271
+ mtimeMs: number
272
+ }
273
+
274
+ /** Every session log under `<dsh home>/sessions/<workspace>/<session>/`. */
275
+ export async function findSessionLogs(sessionsDir: string): Promise<LogFile[]> {
276
+ const found: LogFile[] = []
277
+ const list = async (dir: string): Promise<string[]> => readdir(dir).catch(() => [])
278
+ for (const workspace of await list(sessionsDir)) {
279
+ for (const session of await list(join(sessionsDir, workspace))) {
280
+ for (const file of await list(join(sessionsDir, workspace, session))) {
281
+ if (!/^session\.v\d+\.jsonl(\.zstd)?$/.test(file)) continue
282
+ const path = join(sessionsDir, workspace, session, file)
283
+ const info = await stat(path).catch(() => undefined)
284
+ if (info?.isFile() === true) found.push({ path, size: info.size, mtimeMs: info.mtimeMs })
285
+ }
286
+ }
287
+ }
288
+ return found
289
+ }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * The Usage page's data: one JSON snapshot per period, served on dsh's
3
+ * authenticated `/api` channel as `POST /api/token-usage.report`.
4
+ *
5
+ * The page asks for a period (`today`, `week`, `month`, `90`, `all`, or any
6
+ * word `/usage` takes) and gets the totals, a zero-filled daily series for
7
+ * the chart, the overview sums, and the top models, workspaces and sessions.
8
+ *
9
+ * @module @natgurlain/dsh-token-usage/snapshot
10
+ */
11
+
12
+ import { buildReport, dayOf, emptyTotals, parsePeriod, shiftDay, type Period, type Prices, type Row, type Totals } from './report.ts'
13
+ import type { UsageRecord } from './scan.ts'
14
+
15
+ export const REPORT_API_PATH = '/api/token-usage.report'
16
+
17
+ export interface DayPoint extends Totals {
18
+ day: string
19
+ /** False for the context days a short period's chart shows before it. */
20
+ inPeriod: boolean
21
+ }
22
+
23
+ export interface UsageSnapshot {
24
+ ok: true
25
+ period: Period
26
+ today: string
27
+ priced: boolean
28
+ totals: Totals
29
+ sessions: number
30
+ overview: { today: number; week: number; month: number; all: number }
31
+ days: DayPoint[]
32
+ models: Row[]
33
+ workspaces: Row[]
34
+ sessionRows: Row[]
35
+ /** When the logs were last read (epoch ms). */
36
+ generatedAt: number
37
+ /** `provider/model` → the OpenRouter model whose list price was used. */
38
+ priceSources: Record<string, string>
39
+ /** When the OpenRouter list was fetched, when it was used. */
40
+ pricesAsOf?: number
41
+ }
42
+
43
+ /** What a report is built from. */
44
+ export interface LoadedUsage {
45
+ records: readonly UsageRecord[]
46
+ prices: Prices
47
+ priceSources?: Record<string, string>
48
+ pricesAsOf?: number
49
+ }
50
+
51
+ export interface SnapshotOptions {
52
+ prices?: Prices
53
+ timeZone?: string
54
+ now?: number
55
+ /** Most rows per breakdown table. */
56
+ limit?: number
57
+ }
58
+
59
+ /** The longest daily series the chart draws; older days are left out of the chart only. */
60
+ export const MAX_CHART_DAYS = 180
61
+ /** The shortest: a short period is drawn with the days before it for context. */
62
+ export const MIN_CHART_DAYS = 7
63
+
64
+ export function buildSnapshot(records: readonly UsageRecord[], periodWord: string, options: SnapshotOptions = {}): UsageSnapshot | undefined {
65
+ const now = options.now ?? Date.now()
66
+ const today = dayOf(now, options.timeZone)
67
+ const period = parsePeriod(periodWord, today)
68
+ if (period === undefined) return undefined
69
+ const base = {
70
+ ...(options.prices === undefined ? {} : { prices: options.prices }),
71
+ ...(options.timeZone === undefined ? {} : { timeZone: options.timeZone }),
72
+ }
73
+ const limit = options.limit ?? 50
74
+ const report = (by: 'day' | 'model' | 'workspace' | 'session') => buildReport(records, { ...base, period, by })
75
+ const byDay = report('day')
76
+ // The chart's own series: every day of its range, even idle ones, with context
77
+ // days before a short period (their totals do not count in the period's).
78
+ const chartEnd = period.to ?? shiftDay(today, 1)
79
+ const contextFrom = shiftDay(chartEnd, -MIN_CHART_DAYS)
80
+ const chartFrom = period.from === undefined ? undefined : contextFrom < period.from ? contextFrom : period.from
81
+ const chartDays = buildReport(records, { ...base, period: { label: 'chart', ...(chartFrom === undefined ? {} : { from: chartFrom }), to: chartEnd }, by: 'day' })
82
+ const total = (word: string): number => buildReport(records, { ...base, period: parsePeriod(word, today) ?? { label: word }, by: 'kind' }).totals.total
83
+
84
+ const firstActive = chartDays.rows.at(-1)?.key ?? today
85
+ const first = chartFrom ?? (contextFrom < firstActive ? contextFrom : firstActive)
86
+ const start = shiftDay(chartEnd, -MAX_CHART_DAYS) > first ? shiftDay(chartEnd, -MAX_CHART_DAYS) : first
87
+ const known = new Map(chartDays.rows.map((row) => [row.key, row]))
88
+ const days: DayPoint[] = []
89
+ for (let day = start; day < chartEnd; day = shiftDay(day, 1)) {
90
+ const row = known.get(day)
91
+ const { key: _key, label: _label, ...totals } = row ?? { key: day, label: day, ...emptyTotals() }
92
+ days.push({ day, inPeriod: (period.from === undefined || day >= period.from) && (period.to === undefined || day < period.to), ...totals })
93
+ }
94
+
95
+ return {
96
+ ok: true,
97
+ period,
98
+ today,
99
+ priced: byDay.priced,
100
+ totals: byDay.totals,
101
+ sessions: byDay.sessions,
102
+ overview: { today: total('today'), week: total('week'), month: total('month'), all: total('all') },
103
+ days,
104
+ models: report('model').rows.slice(0, limit),
105
+ workspaces: report('workspace').rows.slice(0, limit),
106
+ sessionRows: report('session').rows.slice(0, limit),
107
+ generatedAt: now,
108
+ priceSources: {},
109
+ }
110
+ }
111
+
112
+ /** The slice of `ctx.connection.fetch` used here (the same one dsh-browser-agent uses). */
113
+ export interface FetchRegistry {
114
+ register(route: {
115
+ readonly path: string
116
+ readonly methods: readonly ('GET' | 'HEAD' | 'POST')[]
117
+ readonly requestBody: 'buffered' | 'streaming'
118
+ readonly fetch: (request: Request) => Promise<Response>
119
+ }): () => unknown
120
+ }
121
+
122
+ function json(body: unknown, status = 200): Response {
123
+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store' } })
124
+ }
125
+
126
+ /**
127
+ * Handle `POST /api/token-usage.report` with `{ "period": "week" }`. dsh has
128
+ * already authenticated the caller as the host's owner; a JSON content type
129
+ * also keeps a cross-site page from sending it without a preflight.
130
+ */
131
+ export async function handleReportRequest(request: Request, load: () => Promise<LoadedUsage>, options: Omit<SnapshotOptions, 'now' | 'prices'>): Promise<Response> {
132
+ if (!/^application\/json\b/iu.test(request.headers.get('content-type') ?? '')) return json({ ok: false, error: 'bad-request' }, 415)
133
+ let body: { period?: unknown } | null
134
+ try {
135
+ body = await request.json() as { period?: unknown } | null
136
+ } catch {
137
+ return json({ ok: false, error: 'bad-request' }, 400)
138
+ }
139
+ const word = typeof body?.period === 'string' && body.period.length <= 40 ? body.period : 'month'
140
+ try {
141
+ const usage = await load()
142
+ const snapshot = buildSnapshot(usage.records, word, { ...options, prices: usage.prices })
143
+ if (snapshot === undefined) return json({ ok: false, error: 'bad-period' }, 400)
144
+ const used = new Set(snapshot.models.map((row) => row.key))
145
+ snapshot.priceSources = Object.fromEntries(Object.entries(usage.priceSources ?? {}).filter(([key]) => used.has(key)))
146
+ if (usage.pricesAsOf !== undefined && Object.keys(snapshot.priceSources).length > 0) snapshot.pricesAsOf = usage.pricesAsOf
147
+ return json(snapshot)
148
+ } catch (error) {
149
+ return json({ ok: false, error: 'failed', message: error instanceof Error ? error.message : String(error) }, 500)
150
+ }
151
+ }