repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/context/index.ts

Raw
File outline
/**
 * Context window usage footer segment producer.
 *
 * Shows context usage percentage with a progress bar.
 * Color shifts: muted → warning (60%) → error (85%).
 * Emits footer:segment with zone "llm".
 */

import type { AgentMessage } from "@mariozechner/pi-ai";
import {
	buildSessionContext,
	estimateTokens,
	type ContextEvent,
	type ExtensionAPI,
	type ExtensionContext,
	type SessionEntry,
} from "@mariozechner/pi-coding-agent";

type Breakdown = {
	system: number;
	user: number;
	agent: number;
	tools: number;
	carried: number;
	total: number;
	turns: number;
	approximate: boolean;
};

type View = {
	tokens: number | null;
	contextWindow: number | null;
	percent: number | null;
	breakdown: Breakdown;
};

const MIX_MIN_PERCENT = 60;

function fmtCount(v: number): string {
	if (!Number.isFinite(v)) return "?";
	if (v < 1000) return `${Math.round(v)}`;
	if (v < 10_000) return `${(v / 1000).toFixed(1)}k`;
	if (v < 1_000_000) return `${Math.round(v / 1000)}k`;
	return `${(v / 1_000_000).toFixed(1)}M`;
}

function getColor(pct: number | null): string {
	if (pct === null) return "muted";
	if (pct >= 85) return "error";
	if (pct >= 60) return "warning";
	return "muted";
}

export default function contextExtension(pi: ExtensionAPI) {
	let lastSignature = "";
	let hasUI = false;

	const sync = (ctx: ExtensionContext, liveMessages?: AgentMessage[]) => {
		const view = buildView(ctx, liveMessages);
		const cw = view.contextWindow;

		if (!cw || cw <= 0 || view.tokens === null || view.percent === null) {
			const sig = "missing";
			if (sig !== lastSignature) {
				lastSignature = sig;
				pi.events.emit("footer:segment", { id: "context", text: "ctx --", color: "muted", zone: "llm", order: 1 });
				pi.events.emit("footer:segment", { id: "context-mix", text: undefined });
			}
			return;
		}

		const pct = view.percent;
		const b = view.breakdown;
		const approx = b.approximate ? "~" : "";
		const suffix = `${approx}${Math.round(pct)}%/${fmtCount(cw)} ${b.turns}t`;
		const showMix = pct >= MIX_MIN_PERCENT && b.total > 0;
		const mix = showMix
			? `S${fmtCount(b.system)} U${fmtCount(b.user)} A${fmtCount(b.agent)} T${fmtCount(b.tools)} C${fmtCount(b.carried)}`
			: "";
		const sig = `${Math.round(pct * 10) / 10}|${view.tokens}|${cw}|${suffix}|${mix}`;
		if (sig === lastSignature) return;
		lastSignature = sig;

		pi.events.emit("footer:segment", {
			id: "context",
			text: "",
			suffix,
			color: getColor(pct),
			bar: pct,
			zone: "llm",
			order: 1,
		});

		if (showMix) {
			pi.events.emit("footer:segment", {
				id: "context-mix",
				text: mix,
				color: "dim",
				zone: "llm",
				order: 1.5,
			});
		} else {
			pi.events.emit("footer:segment", { id: "context-mix", text: undefined });
		}
	};

	const safeSync = (ctx: ExtensionContext, liveMessages?: AgentMessage[]) => {
		if (!hasUI && !ctx.hasUI) return;
		try { sync(ctx, liveMessages); } catch {}
	};

	pi.on("session_start", async (_e, ctx) => { hasUI = ctx.hasUI; lastSignature = ""; safeSync(ctx); });
	pi.on("session_tree", async (_e, ctx) => { lastSignature = ""; safeSync(ctx); });
	pi.on("agent_start", async (_e, ctx) => safeSync(ctx));
	pi.on("agent_end", async (_e, ctx) => safeSync(ctx));
	pi.on("turn_end", async (_e, ctx) => safeSync(ctx));
	pi.on("model_select", async (_e, ctx) => { lastSignature = ""; safeSync(ctx); });
	pi.on("thinking_level_select", async (_e, ctx) => { lastSignature = ""; safeSync(ctx); });
	pi.on("session_compact", async (_e, ctx) => { lastSignature = ""; safeSync(ctx); });
	pi.on("context", async (event: ContextEvent, ctx) => safeSync(ctx, event.messages));
	pi.on("session_shutdown", async () => { lastSignature = ""; pi.events.emit("footer:segment", { id: "context-mix", text: undefined }); });
}

function buildView(ctx: ExtensionContext, liveMessages?: AgentMessage[]): View {
	const estimated = liveMessages ? buildLiveBreakdown(liveMessages, ctx) : buildCurrentBreakdown(ctx);
	const usage = ctx.getContextUsage();
	const contextWindow = usage?.contextWindow ?? ctx.model?.contextWindow ?? null;
	const canTrustUsage = !liveMessages && typeof usage?.tokens === "number";
	const actualTokens = canTrustUsage ? usage?.tokens ?? null : null;
	const tokens = actualTokens ?? estimated.total;
	const percent = canTrustUsage
		? (usage?.percent ?? (contextWindow && actualTokens !== null ? (actualTokens / contextWindow) * 100 : null))
		: contextWindow && tokens > 0
			? (tokens / contextWindow) * 100
			: null;

	return {
		tokens,
		contextWindow,
		percent,
		breakdown: {
			...scaleBreakdownToTotal(estimated, tokens),
			approximate: !canTrustUsage,
		},
	};
}

function buildCurrentBreakdown(ctx: ExtensionContext): Breakdown {
	const entries = ctx.sessionManager.getEntries() as SessionEntry[];
	const byId = new Map(entries.map((entry) => [entry.id, entry]));
	let messages: AgentMessage[];
	try {
		messages = buildSessionContext(entries, ctx.sessionManager.getLeafId(), byId).messages;
	} catch {
		messages = (ctx.sessionManager.getBranch() as SessionEntry[])
			.filter((entry) => entry.type === "message")
			.map((entry) => entry.message as AgentMessage);
	}
	const turns = countAssistantMessages(ctx.sessionManager.getBranch() as SessionEntry[]);
	return buildBreakdown(messages, ctx.getSystemPrompt() ?? "", turns);
}

function buildLiveBreakdown(messages: AgentMessage[], ctx: ExtensionContext): Breakdown {
	const turns = countAssistantMessages(ctx.sessionManager.getBranch() as SessionEntry[]) + 1;
	return buildBreakdown(messages, ctx.getSystemPrompt() ?? "", turns);
}

function buildBreakdown(messages: AgentMessage[], systemPrompt: string, turns: number): Breakdown {
	const breakdown: Breakdown = {
		system: estimateTextTokens(systemPrompt),
		user: 0,
		agent: 0,
		tools: 0,
		carried: 0,
		total: 0,
		turns,
		approximate: false,
	};

	for (const message of messages) {
		const tokens = safeEstimateMessage(message);
		switch (message.role) {
			case "user": breakdown.user += tokens; break;
			case "assistant": breakdown.agent += tokens; break;
			case "toolResult":
			case "bashExecution":
				breakdown.tools += tokens;
				break;
			case "compactionSummary":
			case "branchSummary":
			case "custom":
			default:
				breakdown.carried += tokens;
				break;
		}
	}

	breakdown.total = breakdown.system + breakdown.user + breakdown.agent + breakdown.tools + breakdown.carried;
	return breakdown;
}

function scaleBreakdownToTotal(breakdown: Breakdown, targetTotal: number | null): Breakdown {
	if (targetTotal === null || targetTotal < 0 || breakdown.total <= 0 || breakdown.total === targetTotal) {
		return breakdown;
	}

	const fields = [
		{ key: "system", value: breakdown.system },
		{ key: "user", value: breakdown.user },
		{ key: "agent", value: breakdown.agent },
		{ key: "tools", value: breakdown.tools },
		{ key: "carried", value: breakdown.carried },
	] as const;

	const scaled = fields.map((field) => {
		const raw = (field.value / breakdown.total) * targetTotal;
		return { key: field.key, value: Math.floor(raw), remainder: raw - Math.floor(raw) };
	});

	let assigned = scaled.reduce((sum, field) => sum + field.value, 0);
	for (const field of [...scaled].sort((a, b) => b.remainder - a.remainder)) {
		if (assigned >= targetTotal) break;
		field.value += 1;
		assigned += 1;
	}

	const next = { ...breakdown, total: targetTotal };
	for (const field of scaled) {
		next[field.key] = field.value;
	}
	return next;
}

function countAssistantMessages(entries: SessionEntry[]): number {
	let count = 0;
	for (const entry of entries) {
		if (entry.type === "message" && entry.message.role === "assistant") count += 1;
	}
	return count;
}

function estimateTextTokens(text: string): number {
	if (!text.trim()) return 0;
	return safeEstimateMessage({ role: "user", content: text, timestamp: Date.now() } as AgentMessage);
}

function safeEstimateMessage(message: AgentMessage): number {
	try {
		return Math.max(0, estimateTokens(message));
	} catch {
		return Math.max(0, Math.ceil(extractText(message).length / 4));
	}
}

function extractText(message: AgentMessage): string {
	const parts: string[] = [message.role];
	const anyMessage = message as any;

	if (typeof anyMessage.content === "string") {
		parts.push(anyMessage.content);
	} else if (Array.isArray(anyMessage.content)) {
		for (const block of anyMessage.content) {
			if (block.type === "text") parts.push(block.text ?? "");
			else if (block.type === "thinking") parts.push(block.thinking ?? "");
			else if (block.type === "toolCall") parts.push(block.name ?? "", JSON.stringify(block.arguments ?? {}));
			else parts.push(JSON.stringify(block));
		}
	}

	for (const key of ["toolName", "summary", "command", "customType"]) {
		if (typeof anyMessage[key] === "string") parts.push(anyMessage[key]);
	}

	return parts.join("\n");
}