repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/context-size/index.ts

Raw
File outline
import type {
	ContextUsage,
	ExtensionAPI,
	ExtensionContext,
	ThemeColor,
} from "@earendil-works/pi-coding-agent";

const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
const STATUS_ID = "context-size";

type FooterGlobal = typeof globalThis & {
	[FOOTER_KEY]?: { loaded?: boolean; version?: number };
};

const FOOTER_SEGMENT = {
	id: "context-size",
	icon: "",
	zone: "llm",
	order: 1,
} as const;

const LIMITS = {
	warningPercent: 70,
	errorPercent: 85,
} as const;

const TOKEN_UNIT = 1000;

const BAR = {
	width: 10,
	empty: "─",
	full: "━",
} as const;

const UPDATE_EVENTS = [
	"session_start",
	"agent_start",
	"turn_end",
	"agent_end",
	"model_select",
	"session_compact",
] as const;

type SegmentView = {
	text: string;
	color: ThemeColor;
};

function hasFooter(): boolean {
	const footer = (globalThis as FooterGlobal)[FOOTER_KEY];
	return footer?.loaded === true && (footer.version ?? 0) >= 1;
}

function clamp(value: number, min: number, max: number): number {
	return Math.min(max, Math.max(min, value));
}

function toneForPercent(percent: number | null): ThemeColor {
	if (percent === null) return "muted";
	if (percent >= LIMITS.errorPercent) return "error";
	if (percent >= LIMITS.warningPercent) return "warning";
	return "muted";
}

function barTone(textTone: ThemeColor): ThemeColor {
	return textTone === "muted" ? "dim" : textTone;
}

function renderThinBar(percent: number | null): string {
	const filled =
		percent === null
			? 0
			: clamp(Math.round((percent / 100) * BAR.width), 0, BAR.width);
	return BAR.full.repeat(filled) + BAR.empty.repeat(BAR.width - filled);
}

function formatTokenCount(tokens: number | null): string {
	if (tokens === null) return "?";
	return `${Math.round(tokens / TOKEN_UNIT)}k`;
}

function formatTokenRatio(
	tokens: number | null,
	contextWindow: number,
): string {
	return `${formatTokenCount(tokens)}/${formatTokenCount(contextWindow)}`;
}

function buildSegment(ctx: ExtensionContext, usage: ContextUsage): SegmentView {
	const percent = usage.percent ?? null;
	const textTone = toneForPercent(percent);
	const ratio = formatTokenRatio(usage.tokens, usage.contextWindow);
	const bar = ctx.ui.theme.fg(barTone(textTone), renderThinBar(percent));
	const pct = percent === null ? "?%" : `${Math.round(percent)}%`;

	return {
		text: `${bar} ${pct} ${ratio}`,
		color: textTone,
	};
}

export default function contextSizeExtension(pi: ExtensionAPI) {
	function clearSegment() {
		pi.events.emit("footer:segment", {
			id: FOOTER_SEGMENT.id,
			text: undefined,
		});
	}

	function clearPublished(ctx: ExtensionContext) {
		clearSegment();
		ctx.ui.setStatus(STATUS_ID, undefined);
	}

	function updateSegment(ctx: ExtensionContext) {
		try {
			if (!ctx.hasUI) return;

			const usage = ctx.getContextUsage();
			if (!usage) {
				clearPublished(ctx);
				return;
			}

			const view = buildSegment(ctx, usage);
			if (hasFooter()) {
				ctx.ui.setStatus(STATUS_ID, undefined);
				pi.events.emit("footer:segment", {
					...FOOTER_SEGMENT,
					text: view.text,
					variants: [
						view.text.replace(/\s+\S+\/\S+$/, ""),
						view.text.replace(/^\S+\s+/, ""),
					],
					color: view.color,
				});
				return;
			}

			clearSegment();
			ctx.ui.setStatus(STATUS_ID, view.text);
		} catch {
			// Ignore late events during reload/switch/shutdown; Pi marks old ctx/pi stale.
		}
	}

	for (const eventName of UPDATE_EVENTS) {
		pi.on(eventName as any, async (_event: any, ctx: any) =>
			updateSegment(ctx),
		);
	}

	pi.on("session_shutdown", async (_event, ctx) => {
		if (ctx.hasUI) ctx.ui.setStatus(STATUS_ID, undefined);
	});

	// Footer owns its own teardown. Emitting through `pi.events` during session_shutdown
	// can trip Pi's stale-context guard after reload/switch.
}