repositories / will

will

owned by bugabinga

fix: actually commit the cost-view modules (untracked files slipped past -am)

06184fe54bafa41c5da8e02c689d80fa413c4a3d

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (4)

+348 / −0 text lines

Diff layout

src/agent/usage.test.ts

Added
new file mode 100644

+49 / −0 text lines

1import assert from 'node:assert/strict'
2import { test } from 'node:test'
3import { sumAssistantUsage } from './usage.ts'
4
5const assistant = (model: string, usage: object, provider = 'zai') => ({
6 role: 'assistant',
7 provider,
8 model,
9 usage,
10})
12test('sums usage across assistant messages of one wake', () => {
13 const rows = sumAssistantUsage([
14 assistant('glm-5.3-flash', { input: 100, output: 50, cacheRead: 10, cacheWrite: 5 }),
15 { role: 'user', content: 'hi' },
16 assistant('glm-5.3-flash', { input: 200, output: 20 }),
17 ])
18 assert.deepEqual(rows, [
19 {
20 provider: 'zai',
21 model: 'glm-5.3-flash',
22 input: 300,
23 output: 70,
24 cacheRead: 10,
25 cacheWrite: 5,
26 responses: 2,
27 },
28 ])
29})
31test('splits by provider/model and tolerates junk', () => {
32 const rows = sumAssistantUsage([
33 assistant('glm-5.3-flash', { input: 1 }),
34 assistant('glm-5.3-hig', { input: 2 }, 'cloudflare-ai-gateway'),
35 assistant('glm-5.3-flash', { input: 'junk', output: null }),
36 { role: 'assistant', model: 'no-usage' },
37 'garbage',
38 42,
39 ])
40 assert.equal(rows.length, 2)
41 const flash = rows.find((r) => r.model === 'glm-5.3-flash')
42 assert.equal(flash?.input, 1)
43 assert.equal(flash?.responses, 2)
44})
46test('non-array input yields no rows', () => {
47 assert.deepEqual(sumAssistantUsage(undefined), [])
48 assert.deepEqual(sumAssistantUsage({ messages: [] }), [])
49})

src/agent/usage.ts

Added
new file mode 100644

+62 / −0 text lines

1/**
2 * Turn usage extraction (cost view spec): pi agent_end events carry every
3 * message; assistant messages embed provider usage. One derived audit event
4 * per (wake, provider/model) so the service can aggregate tokens and cost.
5 */
6
7export interface TurnUsage {
8 provider: string
9 model: string
10 input: number
11 output: number
12 cacheRead: number
13 cacheWrite: number
14 /** assistant responses aggregated into this row (one model call each) */
15 responses: number
16}
18interface UsageLike {
19 input?: unknown
20 output?: unknown
21 cacheRead?: unknown
22 cacheWrite?: unknown
23}
25interface AssistantLike {
26 role?: unknown
27 model?: unknown
28 provider?: unknown
29 usage?: unknown
30}
32const num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0)
34export function sumAssistantUsage(messages: unknown): TurnUsage[] {
35 if (!Array.isArray(messages)) return []
36 const byKey = new Map<string, TurnUsage>()
37 for (const message of messages) {
38 const m = message as AssistantLike
39 if (m?.role !== 'assistant') continue
40 if (typeof m.usage !== 'object' || m.usage === null) continue
41 const u = m.usage as UsageLike
42 const model = typeof m.model === 'string' ? m.model : 'unknown'
43 const provider = typeof m.provider === 'string' ? m.provider : 'unknown'
44 const key = `${provider}/${model}`
45 const agg = byKey.get(key) ?? {
46 provider,
47 model,
48 input: 0,
49 output: 0,
50 cacheRead: 0,
51 cacheWrite: 0,
52 responses: 0,
53 }
54 agg.input += num(u.input)
55 agg.output += num(u.output)
56 agg.cacheRead += num(u.cacheRead)
57 agg.cacheWrite += num(u.cacheWrite)
58 agg.responses += 1
59 byKey.set(key, agg)
60 }
61 return [...byKey.values()]
62}

src/service/usage.test.ts

Added
new file mode 100644

+82 / −0 text lines

1import assert from 'node:assert/strict'
2import { test } from 'node:test'
3import { aggregateTurnUsage, projectUsage } from './usage.ts'
4
5const row = (ts: string, over: object = {}) => ({
6 ts,
7 payload: {
8 provider: 'zai',
9 model: 'glm-5.3-flash',
10 input: 1_000_000,
11 output: 0,
12 cacheRead: 0,
13 cacheWrite: 0,
14 responses: 1,
15 ...over,
16 },
17})
19test('cost uses the price table per MTok', () => {
20 const report = aggregateTurnUsage([row('2026-09-21T10:00:00Z')], new Date('2026-09-21T18:00:00Z'))
21 // 1M input tokens at $0.15/MTok
22 assert.ok(Math.abs((report.days[0]?.costUsd ?? 0) - 0.15) < 1e-6)
23 assert.ok(Math.abs((report.totals.costUsd ?? 0) - 0.15) < 1e-6)
24})
26test('unknown model keeps tokens but marks cost unavailable', () => {
27 const report = aggregateTurnUsage(
28 [row('2026-09-21T10:00:00Z', { provider: 'x', model: 'y' })],
29 new Date('2026-09-21T18:00:00Z'),
30 )
31 assert.equal(report.days[0]?.input, 1_000_000)
32 assert.equal(report.days[0]?.costUsd, null)
33 assert.equal(report.totals.costUsd, null)
34 assert.equal(report.projection.projectedEomUsd, null)
35})
37test('days are grouped by UTC date and sorted ascending', () => {
38 const report = aggregateTurnUsage(
39 [row('2026-09-21T23:00:00Z'), row('2026-09-20T01:00:00Z'), row('2026-09-21T01:00:00Z')],
40 new Date('2026-09-21T18:00:00Z'),
41 )
42 assert.deepEqual(
43 report.days.map((d) => d.date),
44 ['2026-09-20', '2026-09-21'],
45 )
46 assert.equal(report.days[1]?.responses, 2)
47})
49test('projection extrapolates today across the remaining month', () => {
50 // at 18:00 UTC, 75% of the day elapsed; 1M input/day = $0.15/day rate
51 const days = [
52 {
53 date: '2026-09-20',
54 input: 1e6,
55 output: 0,
56 cacheRead: 0,
57 cacheWrite: 0,
58 responses: 1,
59 costUsd: 0.15,
60 },
61 {
62 date: '2026-09-21',
63 input: 1e6,
64 output: 0,
65 cacheRead: 0,
66 cacheWrite: 0,
67 responses: 1,
68 costUsd: 0.15,
69 },
70 ]
71 const p = projectUsage(days, new Date('2026-09-21T18:00:00Z'))
72 assert.ok(Math.abs((p.todayUsd ?? 0) - 0.2) < 1e-9) // 0.15 / 0.75
73 assert.ok(Math.abs((p.mtdUsd ?? 0) - 0.3) < 1e-9)
74 // 9.25 days remain until Oct 1 => 0.3 + 0.2 * 9.25
75 assert.ok(Math.abs((p.projectedEomUsd ?? 0) - 2.15) < 1e-9)
76})
78test('projection is null without a priced day today', () => {
79 const p = projectUsage([], new Date('2026-09-21T18:00:00Z'))
80 assert.equal(p.todayUsd, null)
81 assert.equal(p.projectedEomUsd, null)
82})

src/service/usage.ts

Added
new file mode 100644

+155 / −0 text lines

1/**
2 * Cost view math (read-only surface): prices come from the pi model catalog
3 * (zai coding endpoint) and every function here is pure so the projection is
4 * unit-testable without a database or a live clock.
5 */
6
7export interface TurnUsageRow {
8 ts: string
9 payload: unknown
10}
12export interface DayUsage {
13 date: string
14 input: number
15 output: number
16 cacheRead: number
17 cacheWrite: number
18 responses: number
19 /** USD; null when any contributing row used a model without a price entry */
20 costUsd: number | null
21}
23export interface UsageProjection {
24 todayUsd: number | null
25 mtdUsd: number | null
26 projectedEomUsd: number | null
27}
29export interface UsageReport {
30 days: DayUsage[]
31 totals: Omit<DayUsage, 'date'>
32 projection: UsageProjection
33}
35/** USD per MTok (input, output, cacheRead); cacheWrite unpriced (unbilled). */
36const PRICES_PER_MTOK: Record<string, { input: number; output: number; cacheRead: number }> = {
37 'zai/glm-5.3-flash': { input: 0.15, output: 0.5, cacheRead: 0.03 },
38}
40interface UsagePayload {
41 provider?: unknown
42 model?: unknown
43 input?: unknown
44 output?: unknown
45 cacheRead?: unknown
46 cacheWrite?: unknown
47 responses?: unknown
48}
50const num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0)
52function costOfRow(payload: unknown): number | null {
53 const p = payload as UsagePayload
54 const provider = typeof p?.provider === 'string' ? p.provider : 'unknown'
55 const model = typeof p?.model === 'string' ? p.model : 'unknown'
56 const price = PRICES_PER_MTOK[`${provider}/${model}`]
57 if (price === undefined) return null
58 return (
59 (num(p?.input) * price.input +
60 num(p?.output) * price.output +
61 num(p?.cacheRead) * price.cacheRead) /
62 1e6
63 )
64}
66const dayKey = (ts: string): string => ts.slice(0, 10)
68const HOUR_MS = 3_600_000
69/** Floor on elapsed-day fraction so a just-past-midnight spike cannot explode the rate */
70const MIN_ELAPSED_FRACTION = 0.5 / 24
72export function projectUsage(days: DayUsage[], now: Date): UsageProjection {
73 const todayKey = now.toISOString().slice(0, 10)
74 const today = days.find((d) => d.date === todayKey)
75 if (today === undefined || today.costUsd === null) {
76 return { todayUsd: null, mtdUsd: null, projectedEomUsd: null }
77 }
78 const midnight = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
79 const elapsed = Math.max((now.getTime() - midnight) / (24 * HOUR_MS), MIN_ELAPSED_FRACTION)
80 const todayRate = today.costUsd / elapsed
81 const month = todayKey.slice(0, 7)
82 const mtd = days
83 .filter((d) => d.date.slice(0, 7) === month && d.costUsd !== null)
84 .reduce((sum, d) => sum + (d.costUsd ?? 0), 0)
85 const monthEnd = Date.UTC(
86 now.getUTCFullYear(),
87 now.getUTCMonth() + 1,
88 1, // first day of next month == end of this one
89 )
90 const projectedEom = mtd + todayRate * ((monthEnd - now.getTime()) / (24 * HOUR_MS))
91 return { todayUsd: todayRate, mtdUsd: mtd, projectedEomUsd: projectedEom }
92}
94export function aggregateTurnUsage(rows: TurnUsageRow[], now: Date): UsageReport {
95 interface Acc extends Omit<DayUsage, 'costUsd'> {
96 priced: boolean
97 costUsd: number
98 }
99 const byDay = new Map<string, Acc>()
100 for (const row of rows) {
101 const p = row.payload as UsagePayload
102 const date = dayKey(typeof row.ts === 'string' ? row.ts : '')
103 const day = byDay.get(date) ?? {
104 date,
105 input: 0,
106 output: 0,
107 cacheRead: 0,
108 cacheWrite: 0,
109 responses: 0,
110 costUsd: 0,
111 priced: true,
112 }
113 day.input += num(p?.input)
114 day.output += num(p?.output)
115 day.cacheRead += num(p?.cacheRead)
116 day.cacheWrite += num(p?.cacheWrite)
117 day.responses += num(p?.responses)
118 const cost = costOfRow(row.payload)
119 if (cost === null) day.priced = false
120 else day.costUsd += cost
121 byDay.set(date, day)
122 }
123 const days = [...byDay.values()]
124 .map(({ priced, ...d }) => ({ ...d, costUsd: priced ? d.costUsd : null }))
125 .sort((a, b) => (a.date < b.date ? -1 : 1))
126 const totalsAcc = days.reduce(
127 (t, d) => ({
128 input: t.input + d.input,
129 output: t.output + d.output,
130 cacheRead: t.cacheRead + d.cacheRead,
131 cacheWrite: t.cacheWrite + d.cacheWrite,
132 responses: t.responses + d.responses,
133 costUsd: t.costUsd + (d.costUsd ?? 0),
134 unpriced: t.unpriced || d.costUsd === null,
135 }),
136 {
137 input: 0,
138 output: 0,
139 cacheRead: 0,
140 cacheWrite: 0,
141 responses: 0,
142 costUsd: 0,
143 unpriced: false,
144 },
145 )
146 const totals: UsageReport['totals'] = {
147 input: totalsAcc.input,
148 output: totalsAcc.output,
149 cacheRead: totalsAcc.cacheRead,
150 cacheWrite: totalsAcc.cacheWrite,
151 responses: totalsAcc.responses,
152 costUsd: totalsAcc.unpriced ? null : totalsAcc.costUsd,
153 }
154 return { days, totals, projection: projectUsage(days, now) }
155}