repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/cost/index.ts
RawFile outline
- FOOTER_KEY line 21
- STATUS_ID line 22
- FooterGlobal line 24
- CACHE_ICON line 27
- PRICE_UNIT_TOKENS line 28
- COUNT_DECIMAL_THRESHOLD line 29
- COUNT_ROUND_THRESHOLD line 30
- LOW_COST_THRESHOLD line 31
- MEDIUM_COST_THRESHOLD line 32
- SESSION_EXT line 33
- SESSION_MONTH_RE line 34
- FOOTER line 36
- UPDATE_EVENTS line 42
- RESET_SIGNATURE_EVENTS line 47
- PriceRow line 51
- TokenUsage line 57
- UsageWithCost line 64
- AssistantLikeMessage line 68
- Branch line 75
- Snapshot line 77
- SegmentId line 84
- hasFooter line 88
- PRICING line 96
- priceFor line 116
- manualTokenCost line 128
- isAssistantMessageEntry line 146
- message line 150
- type line 150
- normalizeUsage line 157
- messageCost line 166
- sumMessageCosts line 174
- lastAssistantUsage line 182
- safeReadDir line 194
- currentMonthKey line 202
- sessionFileMonth line 206
- isSessionFileForMonth line 211
- sessionFilesForMonth line 219
- sumFileCosts line 246
- calculateMonthlyCost line 256
- formatCount line 276
- formatCost line 283
- tokenLabel line 289
- costLabel line 301
- emitSegment line 313
- statusLabel line 332
- publishSnapshot line 338
- clearSegments line 354
- clearPublished line 359
- buildSnapshot line 366
- signature line 382
- costExtension line 396
- sync line 403
- syncBestEffort line 416
- __test line 472
/**
* Cost and token footer segments.
*
* Emits into the shared footer "llm" zone:
* - tokens: last assistant turn token usage
* - cost: turn/session/monthly spend when non-zero
*/
import type { Dirent } from "node:fs";
import { readdir, readFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import type {
ExtensionAPI,
ExtensionContext,
ThemeColor,
} from "@earendil-works/pi-coding-agent";
import { parseSessionEntries } from "@earendil-works/pi-coding-agent";
// ── Constants ─────────────────────────────────────────────────────────────
const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
const STATUS_ID = "cost";
type FooterGlobal = typeof globalThis & {
[FOOTER_KEY]?: { loaded?: boolean; version?: number };
};
const CACHE_ICON = "";
const PRICE_UNIT_TOKENS = 1_000_000;
const COUNT_DECIMAL_THRESHOLD = 1_000;
const COUNT_ROUND_THRESHOLD = 10_000;
const LOW_COST_THRESHOLD = 0.01;
const MEDIUM_COST_THRESHOLD = 10;
const SESSION_EXT = ".jsonl";
const SESSION_MONTH_RE = /^(\d{4})-(\d{2})/;
const FOOTER = {
tokens: { id: "tokens", color: "muted", order: 2 },
cost: { id: "cost", color: "success", order: 3 },
zone: "llm",
} as const satisfies Record<string, unknown>;
const UPDATE_EVENTS = [
"agent_start",
"agent_end",
"tool_execution_end",
] as const;
const RESET_SIGNATURE_EVENTS = ["model_select", "session_compact"] as const;
// ── Types ─────────────────────────────────────────────────────────────────
type PriceRow = {
input: number;
cacheRead: number;
output: number;
};
type TokenUsage = {
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
};
type UsageWithCost = Partial<TokenUsage> & {
cost?: { total?: number };
};
type AssistantLikeMessage = {
role?: unknown;
usage?: UsageWithCost;
provider?: string;
model?: string;
};
type Branch = ReturnType<ExtensionContext["sessionManager"]["getBranch"]>;
type Snapshot = {
usage: TokenUsage;
turnCost: number;
sessionCost: number;
monthlyCost: number;
};
type SegmentId = "tokens" | "cost";
// ── Footer capability ─────────────────────────────────────────────────────
function hasFooter(): boolean {
const footer = (globalThis as FooterGlobal)[FOOTER_KEY];
return footer?.loaded === true && (footer.version ?? 0) >= 1;
}
// ── Pricing ───────────────────────────────────────────────────────────────
// Prices per 1M tokens. Used only when providers report $0 cost.
const PRICING: Record<string, Record<string, PriceRow>> = {
zai: {
"glm-5.1": { input: 1.4, cacheRead: 0.26, output: 4.4 },
"glm-5": { input: 1.0, cacheRead: 0.2, output: 4.0 },
"glm-5-turbo": { input: 0.5, cacheRead: 0.1, output: 2.0 },
"glm-4.7": { input: 1.0, cacheRead: 0.2, output: 4.0 },
"glm-4.7-flash": { input: 0.1, cacheRead: 0.02, output: 0.4 },
"glm-4.7-flashx": { input: 0.1, cacheRead: 0.02, output: 0.4 },
"glm-4.6": { input: 1.0, cacheRead: 0.2, output: 4.0 },
"glm-4.5": { input: 1.0, cacheRead: 0.2, output: 4.0 },
"glm-4.5-air": { input: 0.1, cacheRead: 0.02, output: 0.4 },
"glm-4.5-flash": { input: 0.1, cacheRead: 0.02, output: 0.4 },
},
minimax: {
"MiniMax-M2.7": { input: 1.0, cacheRead: 0.06, output: 4.0 },
"MiniMax-M2.7-highspeed": { input: 0.6, cacheRead: 0.06, output: 2.4 },
"MiniMax-M1": { input: 1.0, cacheRead: 0.06, output: 4.0 },
},
};
function priceFor(provider: string, model: string): PriceRow | undefined {
const providerPrices = PRICING[provider];
if (!providerPrices) return undefined;
return (
providerPrices[model] ??
Object.entries(providerPrices).find(([prefix]) =>
model.startsWith(prefix),
)?.[1]
);
}
function manualTokenCost(
provider: string,
model: string,
usage: TokenUsage,
): number {
const price = priceFor(provider, model);
if (!price) return 0;
return (
(usage.input * price.input +
usage.cacheRead * price.cacheRead +
usage.output * price.output) /
PRICE_UNIT_TOKENS
);
}
// ── Message extraction ────────────────────────────────────────────────────
function isAssistantMessageEntry(
entry: unknown,
): entry is { type: "message"; message: AssistantLikeMessage } {
const candidate = entry as
| { type?: unknown; message?: AssistantLikeMessage }
| undefined;
return (
candidate?.type === "message" && candidate.message?.role === "assistant"
);
}
function normalizeUsage(usage: UsageWithCost | undefined): TokenUsage {
return {
input: usage?.input ?? 0,
output: usage?.output ?? 0,
cacheRead: usage?.cacheRead ?? 0,
cacheWrite: usage?.cacheWrite ?? 0,
};
}
function messageCost(message: AssistantLikeMessage): number {
const usage = normalizeUsage(message.usage);
const reported = message.usage?.cost?.total ?? 0;
if (reported > 0) return reported;
return manualTokenCost(message.provider ?? "", message.model ?? "", usage);
}
function sumMessageCosts(entries: readonly unknown[]): number {
let total = 0;
for (const entry of entries) {
if (isAssistantMessageEntry(entry)) total += messageCost(entry.message);
}
return total;
}
function lastAssistantUsage(branch: Branch): TokenUsage {
for (let i = branch.length - 1; i >= 0; i--) {
const entry = branch[i];
if (!isAssistantMessageEntry(entry)) continue;
if (!entry.message.usage) continue;
return normalizeUsage(entry.message.usage);
}
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
}
// ── Session file scan ─────────────────────────────────────────────────────
async function safeReadDir(path: string): Promise<Dirent[]> {
try {
return await readdir(path, { withFileTypes: true });
} catch {
return [];
}
}
function currentMonthKey(date = new Date()): string {
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}`;
}
function sessionFileMonth(name: string): string | undefined {
const match = name.match(SESSION_MONTH_RE);
return match ? `${match[1]}-${match[2]}` : undefined;
}
function isSessionFileForMonth(file: Dirent, month: string): boolean {
return (
file.isFile() &&
file.name.endsWith(SESSION_EXT) &&
sessionFileMonth(file.name) === month
);
}
async function sessionFilesForMonth(
sessionDir: string,
month: string,
isCurrent: () => boolean,
): Promise<string[] | undefined> {
const root = dirname(sessionDir);
const files: string[] = [];
for (const entry of await safeReadDir(root)) {
if (!isCurrent()) return undefined;
if (entry.isFile() && isSessionFileForMonth(entry, month)) {
files.push(join(root, entry.name));
continue;
}
if (!entry.isDirectory()) continue;
const childDir = join(root, entry.name);
for (const file of await safeReadDir(childDir)) {
if (!isCurrent()) return undefined;
if (isSessionFileForMonth(file, month))
files.push(join(childDir, file.name));
}
}
return files;
}
async function sumFileCosts(filePath: string): Promise<number> {
try {
return sumMessageCosts(
parseSessionEntries(await readFile(filePath, "utf-8")),
);
} catch {
return 0;
}
}
async function calculateMonthlyCost(
sessionDir: string,
isCurrent: () => boolean = () => true,
): Promise<number | undefined> {
const files = await sessionFilesForMonth(
sessionDir,
currentMonthKey(),
isCurrent,
);
if (!files) return undefined;
let total = 0;
for (const file of files) {
if (!isCurrent()) return undefined;
total += await sumFileCosts(file);
}
return isCurrent() ? total : undefined;
}
// ── Formatting ────────────────────────────────────────────────────────────
function formatCount(value: number): string {
if (value < COUNT_DECIMAL_THRESHOLD) return `${value}`;
if (value < COUNT_ROUND_THRESHOLD)
return `${(value / COUNT_DECIMAL_THRESHOLD).toFixed(1)}k`;
return `${Math.round(value / COUNT_DECIMAL_THRESHOLD)}k`;
}
function formatCost(value: number): string {
if (value < LOW_COST_THRESHOLD) return `$${value.toFixed(4)}`;
if (value < MEDIUM_COST_THRESHOLD) return `$${value.toFixed(2)}`;
return `$${value.toFixed(1)}`;
}
function tokenLabel(usage: TokenUsage): string {
const totalPrompt = usage.input + usage.cacheRead;
if (totalPrompt === 0 && usage.output === 0) return "↑0";
if (usage.input === 0 && usage.cacheRead > 0)
return `◐ ${formatCount(usage.cacheRead)}`;
if (usage.cacheRead === 0)
return `↑${formatCount(usage.input)} ↓${formatCount(usage.output)}`;
const cachePercent = Math.round((usage.cacheRead / totalPrompt) * 100);
return `◐ ${formatCount(usage.input)} ↓${formatCount(usage.output)} ${CACHE_ICON} ${cachePercent}%`;
}
function costLabel(snapshot: Snapshot): string | undefined {
const parts: string[] = [];
if (snapshot.turnCost > 0) parts.push(formatCost(snapshot.turnCost));
if (snapshot.sessionCost > 0)
parts.push(`Σ${formatCost(snapshot.sessionCost)}`);
if (snapshot.monthlyCost > snapshot.sessionCost)
parts.push(` ${formatCost(snapshot.monthlyCost)}`);
return parts.length > 0 ? parts.join(" · ") : undefined;
}
// ── Footer emission ───────────────────────────────────────────────────────
function emitSegment(
pi: ExtensionAPI,
id: SegmentId,
text: string | undefined,
) {
if (text === undefined) {
pi.events.emit("footer:segment", { id: FOOTER[id].id, text: undefined });
return;
}
pi.events.emit("footer:segment", {
id: FOOTER[id].id,
text,
color: FOOTER[id].color as ThemeColor,
zone: FOOTER.zone,
order: FOOTER[id].order,
});
}
function statusLabel(snapshot: Snapshot): string {
return [tokenLabel(snapshot.usage), costLabel(snapshot)]
.filter((part): part is string => !!part)
.join(" · ");
}
function publishSnapshot(
pi: ExtensionAPI,
ctx: ExtensionContext,
snapshot: Snapshot,
) {
if (hasFooter()) {
ctx.ui.setStatus(STATUS_ID, undefined);
emitSegment(pi, "tokens", tokenLabel(snapshot.usage));
emitSegment(pi, "cost", costLabel(snapshot));
return;
}
clearSegments(pi);
ctx.ui.setStatus(STATUS_ID, statusLabel(snapshot));
}
function clearSegments(pi: ExtensionAPI) {
emitSegment(pi, "tokens", undefined);
emitSegment(pi, "cost", undefined);
}
function clearPublished(pi: ExtensionAPI, ctx?: ExtensionContext) {
clearSegments(pi);
if (ctx?.hasUI) ctx.ui.setStatus(STATUS_ID, undefined);
}
// ── Snapshot ──────────────────────────────────────────────────────────────
function buildSnapshot(
ctx: ExtensionContext,
previousSessionCost: number,
monthlyCost: number,
): Snapshot {
const branch = ctx.sessionManager.getBranch();
const sessionCost = sumMessageCosts(branch);
return {
usage: lastAssistantUsage(branch),
turnCost: Math.max(0, sessionCost - previousSessionCost),
sessionCost,
monthlyCost,
};
}
function signature(snapshot: Snapshot): string {
const usage = snapshot.usage;
return [
usage.input,
usage.output,
usage.cacheRead,
usage.cacheWrite,
snapshot.sessionCost,
snapshot.monthlyCost,
].join("|");
}
// ── Extension ─────────────────────────────────────────────────────────────
export default function costExtension(pi: ExtensionAPI) {
let previousSessionCost = 0;
let monthlyCost = 0;
let lastSignature = "";
let hasUI = false;
let generation = 0;
async function sync(ctx: ExtensionContext) {
if (!hasUI) return;
const snapshot = buildSnapshot(ctx, previousSessionCost, monthlyCost);
previousSessionCost = snapshot.sessionCost;
const nextSignature = signature(snapshot);
if (nextSignature === lastSignature) return;
lastSignature = nextSignature;
publishSnapshot(pi, ctx, snapshot);
}
async function syncBestEffort(ctx: ExtensionContext) {
try {
await sync(ctx);
} catch {
// Footer telemetry must never disturb the agent loop.
}
}
pi.on("session_start", (_event, ctx) => {
const ticket = ++generation;
hasUI = ctx.hasUI;
if (!hasUI) return;
previousSessionCost = 0;
lastSignature = "";
monthlyCost = 0;
setTimeout(() => {
if (ticket !== generation) return;
void syncBestEffort(ctx);
}, 0);
const sessionDir = ctx.sessionManager.getSessionDir();
setTimeout(() => {
void (async () => {
const total = await calculateMonthlyCost(
sessionDir,
() => ticket === generation,
);
if (total === undefined) return;
monthlyCost = total;
lastSignature = "";
await syncBestEffort(ctx);
})();
}, 0);
});
for (const eventName of UPDATE_EVENTS) {
pi.on(eventName as any, async (_event: any, ctx: any) =>
syncBestEffort(ctx),
);
}
for (const eventName of RESET_SIGNATURE_EVENTS) {
pi.on(eventName as any, async (_event: any, ctx: any) => {
lastSignature = "";
await syncBestEffort(ctx);
});
}
pi.on("session_shutdown", async (_event, ctx) => {
generation++;
clearPublished(pi, ctx);
});
}
export const __test = { calculateMonthlyCost, tokenLabel };