repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/model-info/index.ts

Raw
File outline
/**
 * Model and thinking footer segment.
 *
 * Owns footer segment `model` in the `llm` zone.
 */

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

const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
const STATUS_ID = "model-info";
const SEGMENT_ID = "model";

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

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

function modelLabel(ctx: Pick<ExtensionContext, "model">): string {
	const modelId = ctx.model?.id ?? "no-model";
	return modelId.split("/").pop() ?? modelId;
}

function thinkingLevelFromBranch(
	ctx: Pick<ExtensionContext, "sessionManager">,
): string {
	const branch = ctx.sessionManager.getBranch();
	for (let i = branch.length - 1; i >= 0; i--) {
		const entry = branch[i] as
			| { type?: unknown; thinkingLevel?: unknown }
			| undefined;
		if (
			entry?.type === "thinking_level_change" &&
			typeof entry.thinkingLevel === "string"
		)
			return entry.thinkingLevel;
	}
	return "off";
}

function modelInfoLabel(
	ctx: Pick<ExtensionContext, "model" | "sessionManager">,
	thinking?: string,
): string {
	return `${modelLabel(ctx)}:${thinking ?? thinkingLevelFromBranch(ctx)}`;
}

function publish(
	pi: ExtensionAPI,
	ctx: ExtensionContext,
	thinking?: string,
): void {
	const text = modelInfoLabel(ctx, thinking);

	if (hasFooter()) {
		ctx.ui.setStatus(STATUS_ID, undefined);
		pi.events.emit("footer:segment", {
			id: SEGMENT_ID,
			text,
			color: "syntaxKeyword" as ThemeColor,
			zone: "llm",
			order: 0,
		});
		return;
	}

	pi.events.emit("footer:segment", { id: SEGMENT_ID, text: undefined });
	ctx.ui.setStatus(STATUS_ID, text);
}

function clear(pi: ExtensionAPI, ctx?: ExtensionContext): void {
	pi.events.emit("footer:segment", { id: SEGMENT_ID, text: undefined });
	if (ctx?.hasUI) ctx.ui.setStatus(STATUS_ID, undefined);
}

export default function modelInfoExtension(pi: ExtensionAPI): void {
	function refresh(ctx: ExtensionContext, thinking?: string): void {
		if (!ctx.hasUI) return;
		publish(pi, ctx, thinking ?? ctx.thinkingLevel);
	}

	pi.on("session_start", (_event, ctx) => refresh(ctx));
	pi.on("model_select", (_event, ctx) => refresh(ctx));
	pi.on("thinking_level_select", (event, ctx) => refresh(ctx, event.level));
	pi.on("session_compact", (_event, ctx) => refresh(ctx));
	pi.on("session_shutdown", (_event, ctx) => clear(pi, ctx));
}

export const __test = {
	modelInfoLabel,
	modelLabel,
	thinkingLevelFromBranch,
};