repositories / will

will

owned by bugabinga

feat: tokens and projected cost in the health view (cost view spec)

f6095f3719b4629861f65298817c054dccb5bcd2

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

pi agent_end events carry assistant usage; the agent now derives one
turn_usage audit event per (wake, provider/model). The service serves
GET /api/usage (daily tokens, USD at catalog prices, month-to-date and
end-of-month projection from the current daily rate). Read-only, so
AC21 stays intact. Prices are code constants; unknown models keep
token counts but withhold cost instead of guessing.

Changed files (8)

+207 / −1 text lines

Diff layout

src/agent/main.ts

Modified

+8 / −0 text lines

1919import { TelegramClient } from './telegram-client.ts'
2020import { createTelegramRuntime } from './telegram-runtime.ts'
2121import { createWillTools } from './tools.ts'
22import { sumAssistantUsage } from './usage.ts'
2223import { readWorktreeState, syncWorktree, type WorktreeStatus } from './worktree.ts'
2324import { ZaiRestClient } from './zai/client.ts'
2425import { createZaiTools } from './zai/tools.ts'
124125 const kind = e.type !== undefined ? PI_EVENT_KINDS[e.type] : undefined
125126 if (kind === undefined) return
126127 void audit(kind, event).then(() => undefined)
128 if (e.type === 'agent_end') {
129 // Derived cost-view rows: one per (wake, provider/model) (spec: tokens
130 // and projected cost surface). Raw events stay untouched.
131 for (const usage of sumAssistantUsage((event as { messages?: unknown }).messages)) {
132 void audit('turn_usage', usage).then(() => undefined)
133 }
134 }
127135 }
129137 let session: SessionPort

src/service/main.int.test.ts

Modified

+53 / −0 text lines

262262 await service.close()
263263 }
264264})
266test('usage view aggregates turn_usage rows into daily cost', async () => {
267 const { service, base, internal } = await startTestService()
268 try {
269 const ingest = (events: unknown[]) =>
270 fetch(internal('/v1/audit/ingest'), {
271 method: 'POST',
272 headers: { 'content-type': 'application/json' },
273 body: JSON.stringify({ events }),
274 })
275 const today = new Date().toISOString().slice(0, 11)
276 const res = await ingest([
277 {
278 id: 'u1',
279 ts: `${today}00:00:00Z`,
280 kind: 'turn_usage',
281 payload: {
282 provider: 'zai',
283 model: 'glm-5.3-flash',
284 input: 2_000_000,
285 output: 100_000,
286 cacheRead: 1_000_000,
287 cacheWrite: 0,
288 responses: 3,
289 },
290 },
291 {
292 id: 'u2',
293 ts: `${today}09:00:00Z`,
294 kind: 'turn_usage',
295 payload: { provider: 'other', model: 'mystery', input: 5, responses: 1 },
296 },
297 { id: 'u3', ts: new Date().toISOString(), kind: 'agent_end', payload: {} },
298 ])
299 assert.equal(res.status, 200)
301 const page = await fetch(base('/api/usage'))
302 assert.equal(page.status, 200)
303 const report = (await page.json()) as {
304 days: { date: string; input: number; responses: number; costUsd: number | null }[]
305 totals: { input: number; costUsd: number | null; responses: number }
306 projection: { todayUsd: number | null; projectedEomUsd: number | null }
307 }
308 assert.equal(report.days.length, 1)
309 assert.equal(report.days[0]?.input, 2_000_005)
310 assert.equal(report.days[0]?.responses, 4)
311 // one unpriced model among the day's rows => cost withheld for that day
312 assert.equal(report.days[0]?.costUsd, null)
313 assert.equal(report.projection.projectedEomUsd, null)
314 } finally {
315 await service.close()
316 }
317})

src/service/main.ts

Modified

+3 / −0 text lines

262262 lastStatus = await callOps<ServiceStatus>(worker, 'status')
263263 sendJson(res, 200, lastStatus)
264264 })
265 publicRouter.get('/api/usage', async (_req, res) => {
266 sendJson(res, 200, await callOps(worker, 'usage'))
267 })
265268 publicRouter.get('/api/docs', async (_req, res) => {
266269 const manifest = await readJsonFile(join(config.docsDist, 'manifest.json'))
267270 sendJson(res, 200, manifest)

src/service/ops.ts

Modified

+14 / −0 text lines

3232 segmentsOverlapping,
3333} from '../shared/retention.ts'
3434import { type Clock, nowIso } from '../shared/time.ts'
35import { aggregateTurnUsage, type UsageReport } from './usage.ts'
3637export interface OpsDirs {
3738 dataDir: string
845846 }
846847 },
849 async usage(): Promise<UsageReport> {
850 const rows = db
851 .prepare("SELECT ts, payload FROM audit_events WHERE kind = 'turn_usage' ORDER BY ts")
852 .all() as unknown as { ts: string; payload: string | null }[]
853 return aggregateTurnUsage(
854 rows.map((r) => ({
855 ts: r.ts,
856 payload: r.payload === null ? null : (safeParse(r.payload) ?? null),
857 })),
858 clock.now(),
859 )
860 },
848862 async status(): Promise<ServiceStatus> {
849863 const dbStat = await stat(join(dirs.dataDir, 'will.db'))
850864 let freeBytes = 0

web/index.html

Modified

+20 / −0 text lines

4545 <section id="health" role="tabpanel" aria-labelledby="tab-health" tabindex="0" hidden>
4646 <h2>Health</h2>
4747 <dl id="health-facts"></dl>
48 <h3>Tokens &amp; cost</h3>
49 <div id="usage-projection" aria-live="polite"></div>
50 <div class="table-wrap">
51 <table id="usage-table">
52 <caption class="visually-hidden">Token usage and cost per day</caption>
53 <thead>
54 <tr>
55 <th scope="col">Day</th>
56 <th scope="col">In</th>
57 <th scope="col">Out</th>
58 <th scope="col">Cache read</th>
59 <th scope="col">Cache write</th>
60 <th scope="col">Responses</th>
61 <th scope="col">Cost&nbsp;(USD)</th>
62 </tr>
63 </thead>
64 <tbody id="usage-days"></tbody>
65 <tfoot id="usage-totals"></tfoot>
66 </table>
67 </div>
4868 </section>
4969 <section id="docs" role="tabpanel" aria-labelledby="tab-docs" tabindex="0" hidden>
5070 <h2>Docs</h2>

web/src/main.css

Modified

+36 / −0 text lines

278278 padding-right: 0.75rem;
279279 }
282/* usage table (health tab) */
283.table-wrap {
284 overflow-x: auto;
285}
287#usage-table {
288 border-collapse: collapse;
289 width: 100%;
290 font-variant-numeric: tabular-nums;
291}
293#usage-table th,
294#usage-table td {
295 border: 1px solid var(--line);
296 padding: 0.25rem 0.5rem;
297 text-align: right;
298}
300#usage-table th:first-child,
301#usage-table td:first-child {
302 text-align: left;
303}
305#usage-table tfoot td {
306 font-weight: 600;
307}
309.visually-hidden {
310 position: absolute;
311 width: 1px;
312 height: 1px;
313 overflow: hidden;
314 clip-path: inset(50%);
315 white-space: nowrap;
316}

web/src/main.ts

Modified

+70 / −1 text lines

214214 }
217const fmtUsd = (usd: number | null): string =>
218 usd === null ? 'n/a' : usd < 0.01 && usd > 0 ? `<$0.01` : `$${usd.toFixed(2)}`
219const fmtTok = (n: number): string =>
220 n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${(n / 1e3).toFixed(1)}k` : String(n)
222interface UsageReportRow {
223 days: {
224 date: string
225 input: number
226 output: number
227 cacheRead: number
228 cacheWrite: number
229 responses: number
230 costUsd: number | null
231 }[]
232 totals: {
233 input: number
234 output: number
235 cacheRead: number
236 cacheWrite: number
237 responses: number
238 costUsd: number | null
239 }
240 projection: { todayUsd: number | null; mtdUsd: number | null; projectedEomUsd: number | null }
241}
243async function loadUsage(): Promise<void> {
244 const res = await fetch('/api/usage')
245 const report = (await res.json()) as UsageReportRow
246 const body = $('#usage-days')
247 const foot = $('#usage-totals')
248 body.replaceChildren()
249 const row = (cells: string[]): HTMLTableRowElement => {
250 const tr = document.createElement('tr')
251 for (const c of cells) tr.append(el('td', {}, text(c)))
252 return tr
253 }
254 for (const d of [...report.days].reverse()) {
255 body.append(
256 row([
257 d.date,
258 fmtTok(d.input),
259 fmtTok(d.output),
260 fmtTok(d.cacheRead),
261 fmtTok(d.cacheWrite),
262 String(d.responses),
263 fmtUsd(d.costUsd),
264 ]),
265 )
266 }
267 foot.replaceChildren(
268 row([
269 'total',
270 fmtTok(report.totals.input),
271 fmtTok(report.totals.output),
272 fmtTok(report.totals.cacheRead),
273 fmtTok(report.totals.cacheWrite),
274 String(report.totals.responses),
275 fmtUsd(report.totals.costUsd),
276 ]),
277 )
278 const p = report.projection
279 $('#usage-projection').replaceChildren(
280 text(
281 `today ${fmtUsd(p.todayUsd)} · month-to-date ${fmtUsd(p.mtdUsd)} · projected end of month ${fmtUsd(p.projectedEomUsd)}`,
282 ),
283 )
284}
217286async function loadHealth(): Promise<void> {
218287 const res = await fetch('/api/status')
219288 const s = (await res.json()) as StatusRow
@@ -267,7 +336,7 @@ Old: loaders; new: health
267336 chat: loadChat,
268337 media: loadMedia,
269338 deployments: loadDeployments,
270 health: loadHealth,
339 health: () => Promise.all([loadHealth(), loadUsage()]).then(() => undefined),
271340 docs: loadDocs,

web/tests/phenotype.spec.ts

Modified

+3 / −0 text lines

104104 await page.keyboard.press('Enter')
105105 await expect(page.getByRole('heading', { name: 'Health' })).toBeVisible()
106106 await expect(page.locator('#health-facts')).toContainText('storage')
107 // cost view: empty storage renders the zero table, not an error
108 await expect(page.locator('#usage-projection')).toContainText('today')
109 await expect(page.locator('#usage-totals')).toContainText('total')
107110})
109112test('skip link exists and docs view loads rendered markdown', async ({ page }) => {