fix: actually commit the cost-view modules (untracked files slipped past -am)
06184fe54bafa41c5da8e02c689d80fa413c4a3d
Oliver Jan Krylow <oliver@bugabinga.net> ·
SSH signature · not checked
- Parent 1: c937470720fc
06184fe54bafa41c5da8e02c689d80fa413c4a3d
Oliver Jan Krylow <oliver@bugabinga.net> ·
SSH signature · not checked
+348 / −0 text lines
new file mode 100644+49 / −0 text lines
import assert from 'node:assert/strict'import { test } from 'node:test'import { sumAssistantUsage } from './usage.ts'const assistant = (model: string, usage: object, provider = 'zai') => ({ role: 'assistant', provider, model, usage,})test('sums usage across assistant messages of one wake', () => { const rows = sumAssistantUsage([ assistant('glm-5.3-flash', { input: 100, output: 50, cacheRead: 10, cacheWrite: 5 }), { role: 'user', content: 'hi' }, assistant('glm-5.3-flash', { input: 200, output: 20 }), ]) assert.deepEqual(rows, [ { provider: 'zai', model: 'glm-5.3-flash', input: 300, output: 70, cacheRead: 10, cacheWrite: 5, responses: 2, }, ])})test('splits by provider/model and tolerates junk', () => { const rows = sumAssistantUsage([ assistant('glm-5.3-flash', { input: 1 }), assistant('glm-5.3-hig', { input: 2 }, 'cloudflare-ai-gateway'), assistant('glm-5.3-flash', { input: 'junk', output: null }), { role: 'assistant', model: 'no-usage' }, 'garbage', 42, ]) assert.equal(rows.length, 2) const flash = rows.find((r) => r.model === 'glm-5.3-flash') assert.equal(flash?.input, 1) assert.equal(flash?.responses, 2)})test('non-array input yields no rows', () => { assert.deepEqual(sumAssistantUsage(undefined), []) assert.deepEqual(sumAssistantUsage({ messages: [] }), [])})new file mode 100644+62 / −0 text lines
/** * Turn usage extraction (cost view spec): pi agent_end events carry every * message; assistant messages embed provider usage. One derived audit event * per (wake, provider/model) so the service can aggregate tokens and cost. */export interface TurnUsage { provider: string model: string input: number output: number cacheRead: number cacheWrite: number /** assistant responses aggregated into this row (one model call each) */ responses: number}interface UsageLike { input?: unknown output?: unknown cacheRead?: unknown cacheWrite?: unknown}interface AssistantLike { role?: unknown model?: unknown provider?: unknown usage?: unknown}const num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0)export function sumAssistantUsage(messages: unknown): TurnUsage[] { if (!Array.isArray(messages)) return [] const byKey = new Map<string, TurnUsage>() for (const message of messages) { const m = message as AssistantLike if (m?.role !== 'assistant') continue if (typeof m.usage !== 'object' || m.usage === null) continue const u = m.usage as UsageLike const model = typeof m.model === 'string' ? m.model : 'unknown' const provider = typeof m.provider === 'string' ? m.provider : 'unknown' const key = `${provider}/${model}` const agg = byKey.get(key) ?? { provider, model, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, responses: 0, } agg.input += num(u.input) agg.output += num(u.output) agg.cacheRead += num(u.cacheRead) agg.cacheWrite += num(u.cacheWrite) agg.responses += 1 byKey.set(key, agg) } return [...byKey.values()]}new file mode 100644+82 / −0 text lines
import assert from 'node:assert/strict'import { test } from 'node:test'import { aggregateTurnUsage, projectUsage } from './usage.ts'const row = (ts: string, over: object = {}) => ({ ts, payload: { provider: 'zai', model: 'glm-5.3-flash', input: 1_000_000, output: 0, cacheRead: 0, cacheWrite: 0, responses: 1, ...over, },})test('cost uses the price table per MTok', () => { const report = aggregateTurnUsage([row('2026-09-21T10:00:00Z')], new Date('2026-09-21T18:00:00Z')) // 1M input tokens at $0.15/MTok assert.ok(Math.abs((report.days[0]?.costUsd ?? 0) - 0.15) < 1e-6) assert.ok(Math.abs((report.totals.costUsd ?? 0) - 0.15) < 1e-6)})test('unknown model keeps tokens but marks cost unavailable', () => { const report = aggregateTurnUsage( [row('2026-09-21T10:00:00Z', { provider: 'x', model: 'y' })], new Date('2026-09-21T18:00:00Z'), ) assert.equal(report.days[0]?.input, 1_000_000) assert.equal(report.days[0]?.costUsd, null) assert.equal(report.totals.costUsd, null) assert.equal(report.projection.projectedEomUsd, null)})test('days are grouped by UTC date and sorted ascending', () => { const report = aggregateTurnUsage( [row('2026-09-21T23:00:00Z'), row('2026-09-20T01:00:00Z'), row('2026-09-21T01:00:00Z')], new Date('2026-09-21T18:00:00Z'), ) assert.deepEqual( report.days.map((d) => d.date), ['2026-09-20', '2026-09-21'], ) assert.equal(report.days[1]?.responses, 2)})test('projection extrapolates today across the remaining month', () => { // at 18:00 UTC, 75% of the day elapsed; 1M input/day = $0.15/day rate const days = [ { date: '2026-09-20', input: 1e6, output: 0, cacheRead: 0, cacheWrite: 0, responses: 1, costUsd: 0.15, }, { date: '2026-09-21', input: 1e6, output: 0, cacheRead: 0, cacheWrite: 0, responses: 1, costUsd: 0.15, }, ] const p = projectUsage(days, new Date('2026-09-21T18:00:00Z')) assert.ok(Math.abs((p.todayUsd ?? 0) - 0.2) < 1e-9) // 0.15 / 0.75 assert.ok(Math.abs((p.mtdUsd ?? 0) - 0.3) < 1e-9) // 9.25 days remain until Oct 1 => 0.3 + 0.2 * 9.25 assert.ok(Math.abs((p.projectedEomUsd ?? 0) - 2.15) < 1e-9)})test('projection is null without a priced day today', () => { const p = projectUsage([], new Date('2026-09-21T18:00:00Z')) assert.equal(p.todayUsd, null) assert.equal(p.projectedEomUsd, null)})new file mode 100644+155 / −0 text lines
/** * Cost view math (read-only surface): prices come from the pi model catalog * (zai coding endpoint) and every function here is pure so the projection is * unit-testable without a database or a live clock. */export interface TurnUsageRow { ts: string payload: unknown}export interface DayUsage { date: string input: number output: number cacheRead: number cacheWrite: number responses: number /** USD; null when any contributing row used a model without a price entry */ costUsd: number | null}export interface UsageProjection { todayUsd: number | null mtdUsd: number | null projectedEomUsd: number | null}export interface UsageReport { days: DayUsage[] totals: Omit<DayUsage, 'date'> projection: UsageProjection}/** USD per MTok (input, output, cacheRead); cacheWrite unpriced (unbilled). */const PRICES_PER_MTOK: Record<string, { input: number; output: number; cacheRead: number }> = { 'zai/glm-5.3-flash': { input: 0.15, output: 0.5, cacheRead: 0.03 },}interface UsagePayload { provider?: unknown model?: unknown input?: unknown output?: unknown cacheRead?: unknown cacheWrite?: unknown responses?: unknown}const num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0)function costOfRow(payload: unknown): number | null { const p = payload as UsagePayload const provider = typeof p?.provider === 'string' ? p.provider : 'unknown' const model = typeof p?.model === 'string' ? p.model : 'unknown' const price = PRICES_PER_MTOK[`${provider}/${model}`] if (price === undefined) return null return ( (num(p?.input) * price.input + num(p?.output) * price.output + num(p?.cacheRead) * price.cacheRead) / 1e6 )}const dayKey = (ts: string): string => ts.slice(0, 10)const HOUR_MS = 3_600_000/** Floor on elapsed-day fraction so a just-past-midnight spike cannot explode the rate */const MIN_ELAPSED_FRACTION = 0.5 / 24export function projectUsage(days: DayUsage[], now: Date): UsageProjection { const todayKey = now.toISOString().slice(0, 10) const today = days.find((d) => d.date === todayKey) if (today === undefined || today.costUsd === null) { return { todayUsd: null, mtdUsd: null, projectedEomUsd: null } } const midnight = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()) const elapsed = Math.max((now.getTime() - midnight) / (24 * HOUR_MS), MIN_ELAPSED_FRACTION) const todayRate = today.costUsd / elapsed const month = todayKey.slice(0, 7) const mtd = days .filter((d) => d.date.slice(0, 7) === month && d.costUsd !== null) .reduce((sum, d) => sum + (d.costUsd ?? 0), 0) const monthEnd = Date.UTC( now.getUTCFullYear(), now.getUTCMonth() + 1, 1, // first day of next month == end of this one ) const projectedEom = mtd + todayRate * ((monthEnd - now.getTime()) / (24 * HOUR_MS)) return { todayUsd: todayRate, mtdUsd: mtd, projectedEomUsd: projectedEom }}export function aggregateTurnUsage(rows: TurnUsageRow[], now: Date): UsageReport { interface Acc extends Omit<DayUsage, 'costUsd'> { priced: boolean costUsd: number } const byDay = new Map<string, Acc>() for (const row of rows) { const p = row.payload as UsagePayload const date = dayKey(typeof row.ts === 'string' ? row.ts : '') const day = byDay.get(date) ?? { date, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, responses: 0, costUsd: 0, priced: true, } day.input += num(p?.input) day.output += num(p?.output) day.cacheRead += num(p?.cacheRead) day.cacheWrite += num(p?.cacheWrite) day.responses += num(p?.responses) const cost = costOfRow(row.payload) if (cost === null) day.priced = false else day.costUsd += cost byDay.set(date, day) } const days = [...byDay.values()] .map(({ priced, ...d }) => ({ ...d, costUsd: priced ? d.costUsd : null })) .sort((a, b) => (a.date < b.date ? -1 : 1)) const totalsAcc = days.reduce( (t, d) => ({ input: t.input + d.input, output: t.output + d.output, cacheRead: t.cacheRead + d.cacheRead, cacheWrite: t.cacheWrite + d.cacheWrite, responses: t.responses + d.responses, costUsd: t.costUsd + (d.costUsd ?? 0), unpriced: t.unpriced || d.costUsd === null, }), { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, responses: 0, costUsd: 0, unpriced: false, }, ) const totals: UsageReport['totals'] = { input: totalsAcc.input, output: totalsAcc.output, cacheRead: totalsAcc.cacheRead, cacheWrite: totalsAcc.cacheWrite, responses: totalsAcc.responses, costUsd: totalsAcc.unpriced ? null : totalsAcc.costUsd, } return { days, totals, projection: projectUsage(days, now) }}