main
1/**
2 * Cost Tracker Extension
3 *
4 * Shows total session cost and prompt-cache hit rate in the footer.
5 */
6
7import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
8
9function formatCost(cost: number): string {
10 if (cost < 0.01) return `$${cost.toFixed(4)}`;
11 if (cost < 1) return `$${cost.toFixed(3)}`;
12 return `$${cost.toFixed(2)}`;
13}
14
15export default function (pi: ExtensionAPI) {
16 let totalCost = 0;
17 let totalInput = 0;
18 let totalCacheRead = 0;
19 let totalCacheWrite = 0;
20
21 function updateStatus(ctx: { ui: any }) {
22 const totalPromptTokens = totalInput + totalCacheRead + totalCacheWrite;
23 const cacheHitPercent = totalPromptTokens === 0 ? 0 : Math.round((totalCacheRead / totalPromptTokens) * 100);
24 ctx.ui.setStatus("cost-tracker", ctx.ui.theme.fg("accent", `${formatCost(totalCost)} ↺${cacheHitPercent}%`));
25 }
26
27 function recalculate(ctx: { sessionManager: any; ui: any }) {
28 totalCost = 0;
29 totalInput = 0;
30 totalCacheRead = 0;
31 totalCacheWrite = 0;
32
33 for (const entry of ctx.sessionManager.getBranch()) {
34 if (entry.type !== "message" || entry.message.role !== "assistant") continue;
35
36 const usage = (entry.message as any).usage;
37 if (!usage) continue;
38
39 totalInput += usage.input || 0;
40 totalCacheRead += usage.cacheRead || 0;
41 totalCacheWrite += usage.cacheWrite || 0;
42 totalCost += usage.cost?.total || 0;
43 }
44 updateStatus(ctx);
45 }
46
47 pi.on("session_start", async (_event, ctx) => recalculate(ctx));
48 pi.on("turn_end", async (_event, ctx) => recalculate(ctx));
49}