README Source History Refs Reviews Compare Notes Search Review guide CI runs feat: tokens and projected cost in the health view (cost view spec) f6095f3719b4629861f65298817c054dccb5bcd2
Oliver Jan Krylow <oliver@bugabinga.net > · 21 Sep 2026
SSH signature · not checked
Browse files Compare 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) Diff layout Auto Unified Split
src/agent/main.ts Modified +8 / −0 text lines
19 19 import { TelegramClient } from './telegram-client.ts' import { TelegramClient } from './telegram-client.ts' 20 20 import { createTelegramRuntime } from './telegram-runtime.ts' import { createTelegramRuntime } from './telegram-runtime.ts' 21 21 import { createWillTools } from './tools.ts' import { createWillTools } from './tools.ts'
22 + import { sumAssistantUsage } from './usage.ts' 22 23 import { readWorktreeState, syncWorktree, type WorktreeStatus } from './worktree.ts' import { readWorktreeState, syncWorktree, type WorktreeStatus } from './worktree.ts' 23 24 import { ZaiRestClient } from './zai/client.ts' import { ZaiRestClient } from './zai/client.ts' 24 25 import { createZaiTools } from './zai/tools.ts' import { createZaiTools } from './zai/tools.ts' 124 125 const kind = e.type !== undefined ? PI_EVENT_KINDS[e.type ] : undefined const kind = e.type !== undefined ? PI_EVENT_KINDS[e.type ] : undefined 125 126 if (kind === undefined ) return if (kind === undefined ) return 126 127 void audit (kind, event ).then (() => undefined ) void audit (kind, event ).then (() => undefined )
128 + if (e.type === 'agent_end' ) {131 + for (const usage of sumAssistantUsage ((event as { messages?: unknown }).messages)) {132 + void audit ('turn_usage' , usage).then (() => undefined )129 137 let session: SessionPort let session: SessionPort src/service/main.int.test.ts Modified +53 / −0 text lines
262 262 await service.close () await service.close ()
266 + test ('usage view aggregates turn_usage rows into daily cost' , async () => {267 + const { service, base, internal } = await startTestService ()269 + const ingest = (events: unknown []) => 270 + fetch (internal ('/v1/audit/ingest' ), {272 + headers: { 'content-type' : 'application/json' },273 + body: JSON .stringify ({ events }),275 + const today = new Date ().toISOString ().slice (0 , 11 )276 + const res = await ingest ([279 + ts: `${today}00:00:00Z` ,283 + model: 'glm-5.3-flash' ,286 + cacheRead: 1_000_000 ,293 + ts: `${today}09:00:00Z` ,295 + payload: { provider: 'other' , model: 'mystery' , input: 5 , responses: 1 },297 + { id: 'u3' , ts: new Date ().toISOString (), kind: 'agent_end' , payload: {} },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 }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 )312 + assert.equal (report.days[0 ]?.costUsd, null )313 + assert.equal (report.projection.projectedEomUsd, null )315 + await service.close ()src/service/main.ts Modified +3 / −0 text lines
262 262 lastStatus = await callOps <ServiceStatus >(worker, 'status' ) lastStatus = await callOps <ServiceStatus >(worker, 'status' )263 263 sendJson (res, 200 , lastStatus) sendJson (res, 200 , lastStatus)
265 + publicRouter.get ('/api/usage' , async (_req, res) => {266 + sendJson (res, 200 , await callOps (worker, 'usage' ))265 268 publicRouter.get ('/api/docs' , async (_req, res) => { publicRouter.get ('/api/docs' , async (_req, res) => {266 269 const manifest = await readJsonFile (join (config.docsDist, 'manifest.json' )) const manifest = await readJsonFile (join (config.docsDist, 'manifest.json' ))267 270 sendJson (res, 200 , manifest) sendJson (res, 200 , manifest)src/service/ops.ts Modified +14 / −0 text lines
32 32 segmentsOverlapping, segmentsOverlapping,33 33 } from '../shared/retention.ts' } from '../shared/retention.ts' 34 34 import { type Clock, nowIso } from '../shared/time.ts' import { type Clock, nowIso } from '../shared/time.ts'
35 + import { aggregateTurnUsage, type UsageReport } from './usage.ts' 36 37 export interface OpsDirs {export interface OpsDirs {37 38 dataDir: string dataDir: string
849 + async usage (): Promise < UsageReport> {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 (856 + payload: r.payload === null ? null : (safeParse (r.payload) ?? null ),848 862 async status (): Promise < ServiceStatus> { async status (): Promise < ServiceStatus> {849 863 const dbStat = await stat (join (dirs.dataDir, 'will.db' )) const dbStat = await stat (join (dirs.dataDir, 'will.db' ))850 864 let freeBytes = 0 let freeBytes = 0 +20 / −0 text lines
45 45 <section id="health" role="tabpanel" aria-labelledby="tab-health" tabindex="0" hidden> <section id="health" role="tabpanel" aria-labelledby="tab-health" tabindex="0" hidden>46 46 <h2 >Health</h2 > <h2 >Health</h2 >47 47 <dl id="health-facts" ></dl > <dl id="health-facts" ></dl >
48 + <h3 >Tokens & 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 >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 (USD)</th >64 + <tbody id="usage-days" ></tbody >65 + <tfoot id="usage-totals" ></tfoot >48 68 </section > </section >49 69 <section id="docs" role="tabpanel" aria-labelledby="tab-docs" tabindex="0" hidden> <section id="docs" role="tabpanel" aria-labelledby="tab-docs" tabindex="0" hidden>50 70 <h2 >Docs</h2 > <h2 >Docs</h2 >+36 / −0 text lines
278 278 padding-right : 0.75rem; padding-right : 0.75rem;
288 + border-collapse : collapse ;290 + font-variant-numeric : tabular-nums ;295 + border : 1 px solid var (--line );296 + padding : 0.25 rem 0.5 rem ;300 + #usage-table th :first-child,301 + #usage-table td :first-child {305 + #usage-table tfoot td {314 + clip-path : inset (50 % );315 + white-space : nowrap ;+70 / −1 text lines
217 + const fmtUsd = (usd: number | null ): string => 218 + usd === null ? 'n/a' : usd < 0.01 && usd > 0 ? `<$0.01` : `$${usd. toFixed (2)}` 219 + const fmtTok = (n: number ): string => 220 + n >= 1e6 ? `${(n / 1e6). toFixed (1)}M` : n >= 1e3 ? `${(n / 1e3). toFixed (1)}k` : String (n)222 + interface UsageReportRow {230 + costUsd: number | null 238 + costUsd: number | null 240 + projection: { todayUsd: number | null ; mtdUsd: number | null ; projectedEomUsd: number | null }243 + async 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)))254 + for (const d of [... report.days].reverse ()) {260 + fmtTok (d.cacheRead),261 + fmtTok (d.cacheWrite),262 + String (d.responses),267 + foot.replaceChildren (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),278 + const p = report.projection279 + $ ('#usage-projection' ).replaceChildren (281 + `today ${ fmtUsd (p.todayUsd)} · month-to-date ${ fmtUsd (p.mtdUsd)} · projected end of month ${ fmtUsd (p.projectedEomUsd)}` ,217 286 async function loadHealth (): Promise <void > {async function loadHealth (): Promise <void > {218 287 const res = await fetch ('/api/status' ) const res = await fetch ('/api/status' )219 288 const s = (await res.json ()) as StatusRow const s = (await res.json ()) as StatusRow 267 336 chat : loadChat, chat : loadChat,268 337 media : loadMedia, media : loadMedia,269 338 deployments : loadDeployments, deployments : loadDeployments,339 + health : () => Promise .all ([loadHealth (), loadUsage ()]).then (() => undefined ),271 340 docs : loadDocs, docs : loadDocs,web/tests/phenotype.spec.ts Modified +3 / −0 text lines
104 104 await page.keyboard.press ('Enter' ) await page.keyboard.press ('Enter' )105 105 await expect (page.getByRole ('heading' , { name: 'Health' })).toBeVisible () await expect (page.getByRole ('heading' , { name: 'Health' })).toBeVisible ()106 106 await expect (page.locator ('#health-facts' )).toContainText ('storage' ) await expect (page.locator ('#health-facts' )).toContainText ('storage' )
108 + await expect (page.locator ('#usage-projection' )).toContainText ('today' )109 + await expect (page.locator ('#usage-totals' )).toContainText ('total' )109 112 test ('skip link exists and docs view loads rendered markdown' , async ({ page }) => {test ('skip link exists and docs view loads rendered markdown' , async ({ page }) => {