import { getAgentDir, type ExtensionAPI, type Theme } from '@earendil-works/pi-coding-agent'; import { visibleWidth, truncateToWidth, matchesKey, Key } from '@earendil-works/pi-tui'; import * as fs from 'node:fs'; import * as path from 'node:path'; import * as readline from 'node:readline'; interface DailyCost { date: string; input: number; output: number; cacheRead: number; cacheWrite: number; total: number; requests: number; } interface ProviderCost { provider: string; displayName: string; days: DailyCost[]; totalCost: number; totalRequests: number; models: Map; } const PROVIDER_DISPLAY_NAMES: Record = { anthropic: 'Claude', 'anthropic-multi': 'Claude Multi', openai: 'OpenAI', 'openai-codex': 'Codex', 'openai-codex-multi': 'Codex Multi', google: 'Gemini', 'google-gemini-cli': 'Gemini', 'github-copilot': 'Copilot', }; const MULTI_PROVIDER_BASES: Record = { 'anthropic-multi': 'anthropic', 'openai-codex-multi': 'openai-codex', }; function formatProviderName(provider: string): string { return PROVIDER_DISPLAY_NAMES[provider] || provider; } function getEffectiveProvider( loggedProvider: string, selectedProvider?: string, loggedModel?: string, selectedModel?: string, ): string { if (!selectedProvider) return loggedProvider; if (loggedProvider === selectedProvider) return loggedProvider; const baseProvider = MULTI_PROVIDER_BASES[selectedProvider]; if (!baseProvider || loggedProvider !== baseProvider) return loggedProvider; if (selectedModel && loggedModel && selectedModel !== loggedModel) return loggedProvider; return selectedProvider; } async function scanSessionLogs(daysBack: number | null = 30): Promise { const sessionsDir = path.join(getAgentDir(), 'sessions'); const providerCosts = new Map(); const cutoffDate = new Date(); if (daysBack !== null) { cutoffDate.setDate(cutoffDate.getDate() - daysBack); } else { cutoffDate.setTime(0); } let sessionEntries: fs.Dirent[]; try { sessionEntries = await fs.promises.readdir(sessionsDir, { withFileTypes: true, }); } catch { return []; } const sessionDirs = sessionEntries .filter((d) => d.isDirectory()) .map((d) => path.join(sessionsDir, d.name)); for (const dir of sessionDirs) { let dirEntries: fs.Dirent[]; try { dirEntries = await fs.promises.readdir(dir, { withFileTypes: true }); } catch { continue; } const files = dirEntries .filter((f) => f.isFile() && f.name.endsWith('.jsonl')) .map((f) => path.join(dir, f.name)); for (const file of files) { await scanSessionFile(file, cutoffDate, providerCosts).catch(() => {}); } } return Array.from(providerCosts.values()).sort((a, b) => b.totalCost - a.totalCost); } async function scanSessionFile( filePath: string, cutoffDate: Date, providerCosts: Map, ): Promise { const fileStream = fs.createReadStream(filePath); const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity, }); let selectedProvider: string | undefined; let selectedModel: string | undefined; for await (const line of rl) { try { const entry = JSON.parse(line); if (entry.type === 'model_change') { selectedProvider = entry.provider || selectedProvider; selectedModel = entry.modelId || selectedModel; continue; } if (entry.type === 'message' && entry.message?.role === 'assistant') { const msg = entry.message; const timestamp = new Date(entry.timestamp || msg.timestamp); if (timestamp < cutoffDate) continue; const model = msg.model || 'unknown'; const provider = getEffectiveProvider( msg.provider || 'unknown', selectedProvider, model, selectedModel, ); const usage = msg.usage; if (!usage?.cost) continue; const dateKey = timestamp.toISOString().slice(0, 10); if (!providerCosts.has(provider)) { providerCosts.set(provider, { provider, displayName: formatProviderName(provider), days: [], totalCost: 0, totalRequests: 0, models: new Map(), }); } const pc = providerCosts.get(provider)!; let day = pc.days.find((d) => d.date === dateKey); if (!day) { day = { date: dateKey, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, requests: 0, }; pc.days.push(day); } day.input += usage.cost.input || 0; day.output += usage.cost.output || 0; day.cacheRead += usage.cost.cacheRead || 0; day.cacheWrite += usage.cost.cacheWrite || 0; day.total += usage.cost.total || 0; day.requests += 1; pc.totalCost += usage.cost.total || 0; pc.totalRequests += 1; const modelCost = pc.models.get(model) || 0; pc.models.set(model, modelCost + (usage.cost.total || 0)); } } catch { // Skip malformed lines } } } async function deleteProviderFromSessions(provider: string): Promise { const sessionsDir = path.join(getAgentDir(), 'sessions'); let sessionEntries: fs.Dirent[]; try { sessionEntries = await fs.promises.readdir(sessionsDir, { withFileTypes: true, }); } catch { return; } const sessionDirs = sessionEntries .filter((d) => d.isDirectory()) .map((d) => path.join(sessionsDir, d.name)); for (const dir of sessionDirs) { let dirEntries: fs.Dirent[]; try { dirEntries = await fs.promises.readdir(dir, { withFileTypes: true }); } catch { continue; } const files = dirEntries .filter((f) => f.isFile() && f.name.endsWith('.jsonl')) .map((f) => path.join(dir, f.name)); for (const file of files) { const fileStream = fs.createReadStream(file); const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity, }); const kept: string[] = []; let modified = false; let selectedProvider: string | undefined; let selectedModel: string | undefined; for await (const line of rl) { if (!line.trim()) continue; try { const entry = JSON.parse(line); if (entry.type === 'model_change') { selectedProvider = entry.provider || selectedProvider; selectedModel = entry.modelId || selectedModel; kept.push(line); continue; } if (entry.type === 'message' && entry.message?.role === 'assistant') { const model = entry.message.model || 'unknown'; const effectiveProvider = getEffectiveProvider( entry.message.provider || 'unknown', selectedProvider, model, selectedModel, ); if (effectiveProvider === provider) { modified = true; continue; } } kept.push(line); } catch { kept.push(line); } } if (modified) { await fs.promises.writeFile(file, kept.join('\n') + '\n'); } } } } class CostComponent { private costs: ProviderCost[] = []; private loading = true; private tui: { requestRender: () => void }; private theme: Theme; private onClose: () => void; private expanded: string | null = null; private cursor = 0; private currentTab = 0; private loadId = 0; private tabs: { label: string; days: number | null }[] = [ { label: 'day', days: 1 }, { label: 'week', days: 7 }, { label: 'month', days: 30 }, { label: 'all', days: null }, ]; constructor( tui: { requestRender: () => void }, theme: Theme, onClose: () => void, daysBack: number, ) { this.tui = tui; this.theme = theme; this.onClose = onClose; this.currentTab = this.tabs.findIndex((t) => t.days === daysBack); if (this.currentTab === -1) this.currentTab = 0; this.load(); } private async load() { const days = this.tabs[this.currentTab]?.days ?? null; const id = ++this.loadId; const costs = await scanSessionLogs(days); if (id !== this.loadId) return; this.costs = costs; this.cursor = Math.min(this.cursor, Math.max(0, this.costs.length - 1)); this.loading = false; this.tui.requestRender(); } handleInput(data: string): void { if (matchesKey(data, Key.escape)) { this.onClose(); } else if (matchesKey(data, Key.left)) { if (this.tabs.length > 1) { this.currentTab = (this.currentTab - 1 + this.tabs.length) % this.tabs.length; this.load(); } } else if (matchesKey(data, Key.right)) { if (this.tabs.length > 1) { this.currentTab = (this.currentTab + 1) % this.tabs.length; this.load(); } } else if (matchesKey(data, Key.up)) { if (this.costs.length > 0) { this.cursor = (this.cursor - 1 + this.costs.length) % this.costs.length; this.tui.requestRender(); } } else if (matchesKey(data, Key.down)) { if (this.costs.length > 0) { this.cursor = (this.cursor + 1) % this.costs.length; this.tui.requestRender(); } } else if (matchesKey(data, Key.enter)) { const pc = this.costs[this.cursor]; if (pc) { this.expanded = this.expanded === pc.provider ? null : pc.provider; this.tui.requestRender(); } } else if (matchesKey(data, Key.backspace)) { const pc = this.costs[this.cursor]; if (pc && !this.loading) { this.costs.splice(this.cursor, 1); if (this.cursor >= this.costs.length) { this.cursor = Math.max(0, this.costs.length - 1); } this.tui.requestRender(); deleteProviderFromSessions(pc.provider).catch(() => this.load()); } } } invalidate(): void {} render(width: number): string[] { const t = this.theme; const dim = (s: string) => t.fg('muted', s); const bold = (s: string) => t.bold(s); const accent = (s: string) => t.fg('accent', s); const success = (s: string) => t.fg('success', s); const warning = (s: string) => t.fg('warning', s); const totalW = width; const innerW = totalW - 4; const hLine = '─'.repeat(totalW - 2); const box = (content: string) => { const truncated = truncateToWidth(content, innerW); const contentW = visibleWidth(truncated); const pad = Math.max(0, innerW - contentW); return dim('│ ') + truncated + ' '.repeat(pad) + dim(' │'); }; const lines: string[] = []; lines.push(dim(`╭${hLine}╮`)); lines.push(box(bold(accent(`cost`)))); const tabLine: string[] = []; for (const [i, tab] of this.tabs.entries()) { const isActive = i === this.currentTab; const tabText = isActive ? bold(tab.label) : dim(tab.label); tabLine.push(tabText); if (i < this.tabs.length - 1) { tabLine.push(dim('·')); } } lines.push(box(tabLine.join(' '))); lines.push(dim(`├${hLine}┤`)); if (this.loading) { lines.push(box('scanning session logs...')); } else if (this.costs.length === 0) { lines.push(box(dim('no usage data found'))); } else { let grandTotal = 0; let idx = 0; for (const pc of this.costs) { grandTotal += pc.totalCost; const costStr = `$${pc.totalCost.toFixed(4)}`; const color = pc.totalCost > 1 ? warning : success; const cursorMark = idx === this.cursor ? bold(accent('> ')) : ' '; lines.push( box( `${cursorMark}${bold(pc.displayName.toLowerCase())} ${color(costStr)} ${dim(`(${pc.totalRequests} requests)`)}`, ), ); if (this.expanded === pc.provider) { const sortedModels = Array.from(pc.models.entries()) .sort((a, b) => b[1] - a[1]) .slice(0, 3); for (const [model, cost] of sortedModels) { const shortModel = model.length > 25 ? model.substring(0, 22) + '...' : model; lines.push(box(dim(` ${shortModel.toLowerCase()}: $${cost.toFixed(4)}`))); } } idx++; } lines.push(dim(`├${hLine}┤`)); const totalColor = grandTotal > 10 ? warning : success; lines.push(box(`${bold('total:')} ${totalColor(`$${grandTotal.toFixed(4)}`)}`)); } lines.push(dim(`├${hLine}┤`)); const helpText = '←→ tabs ↑↓ navigate enter expand backspace delete esc close'; const truncatedHelp = truncateToWidth(helpText, innerW); lines.push(box(dim(truncatedHelp))); lines.push(dim(`╰${hLine}╯`)); return lines; } dispose(): void {} } export default function (pi: ExtensionAPI) { pi.registerCommand('cost', { description: 'Show cost report from session logs', handler: async (args, ctx) => { if (ctx.mode !== 'tui') { ctx.ui.notify('/cost requires interactive mode', 'error'); return; } const daysBack = parseInt(args || '1') || 1; await ctx.ui.custom((tui, theme, _kb, done) => { return new CostComponent(tui, theme, () => done(undefined), daysBack); }); }, }); }