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 STATUS_ID = "context-size";

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

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

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 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);
}

/** Human-readable token count: 940, 1.2k, 262k, 1.2M, 12M. */
function formatTokens(tokens: number): string {
	if (tokens < 1_000) return `${Math.round(tokens)}`;
	if (tokens < 10_000) return `${(tokens / 1_000).toFixed(1)}k`;
	if (tokens < 1_000_000) return `${Math.round(tokens / 1_000)}k`;
	if (tokens < 10_000_000) return `${(tokens / 1_000_000).toFixed(1)}M`;
	return `${Math.round(tokens / 1_000_000)}M`;
}

/**
 * TUI view: the bar alone. Its length encodes the percentage and its colour
 * encodes the pressure, so percent and token counts would only repeat it.
 */
function buildSegment(ctx: ExtensionContext, usage: ContextUsage): SegmentView {
	const percent = usage.percent ?? null;
	const textTone = toneForPercent(percent);

	return {
		text: ctx.ui.theme.fg(barTone(textTone), renderThinBar(percent)),
		color: textTone,
	};
}

/**
 * Non-TUI view: no bar and no glyphs, because RPC clients render the status
 * line as plain text in an unknown font.
 */
function buildPlainLabel(usage: ContextUsage): string {
	const percent = usage.percent ?? null;
	if (percent === null || usage.tokens === null) return "context unknown";
	const left = Math.max(0, usage.contextWindow - usage.tokens);
	return `context ${Math.round(percent)}% used, ${formatTokens(left)} left`;
}

function offerFooterSegment(pi: ExtensionAPI, segment: object): boolean {
	let accepted = false;
	pi.events.emit("footer:segment", {
		...segment,
		accept: () => {
			accepted = true;
		},
	});
	return accepted;
}

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;
			}

			if (ctx.mode !== "tui") {
				clearSegment();
				ctx.ui.setStatus(STATUS_ID, buildPlainLabel(usage));
				return;
			}

			const view = buildSegment(ctx, usage);
			const accepted = offerFooterSegment(pi, {
				...FOOTER_SEGMENT,
				text: view.text,
				color: view.color,
			});

			if (!accepted) clearSegment();
			ctx.ui.setStatus(STATUS_ID, accepted ? undefined : 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.
}

export const __test = { buildPlainLabel, formatTokens, renderThinBar };