repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/masks/index.ts

Raw
File outline
import { readFileSync } from "node:fs";
import type {
	ExtensionAPI,
	ExtensionContext,
} from "@earendil-works/pi-coding-agent";
import {
	DynamicBorder,
	parseFrontmatter,
	SettingsManager,
} from "@earendil-works/pi-coding-agent";
import {
	Container,
	fuzzyFilter,
	Input,
	SelectList,
	Spacer,
	Text,
} from "@earendil-works/pi-tui";

const SETTINGS_KEY = "masks";
const DEFAULT_PICKER_SHORTCUT = "alt+m";
const THINKING_LEVELS = [
	"off",
	"minimal",
	"low",
	"medium",
	"high",
	"xhigh",
	"max",
] as const;

type ThinkingLevel = (typeof THINKING_LEVELS)[number];
type Shortcut = Parameters<ExtensionAPI["registerShortcut"]>[0];

interface Mask {
	name: string;
	model: string;
	thinkingLevel: ThinkingLevel;
	shortcut?: string;
}

interface MasksConfig {
	pickerShortcut: string;
	items: Mask[];
}

interface ParsedMasks {
	config: MasksConfig;
	errors: string[];
}

function isRecord(value: unknown): value is Record<string, unknown> {
	return typeof value === "object" && value !== null && !Array.isArray(value);
}

function nonEmptyString(value: unknown): string | undefined {
	return typeof value === "string" && value.trim() ? value.trim() : undefined;
}

function isThinkingLevel(value: unknown): value is ThinkingLevel {
	return THINKING_LEVELS.includes(value as ThinkingLevel);
}

function parseMasksSettings(value: unknown): ParsedMasks {
	const errors: string[] = [];
	const config: MasksConfig = {
		pickerShortcut: DEFAULT_PICKER_SHORTCUT,
		items: [],
	};
	if (value === undefined) return { config, errors };
	if (!isRecord(value)) {
		return { config, errors: ["masks must be an object"] };
	}

	if (value.pickerShortcut !== undefined) {
		const shortcut = nonEmptyString(value.pickerShortcut);
		if (shortcut) config.pickerShortcut = shortcut;
		else errors.push("masks.pickerShortcut must be a non-empty string");
	}

	if (value.items === undefined) return { config, errors };
	if (!Array.isArray(value.items)) {
		errors.push("masks.items must be an array");
		return { config, errors };
	}

	const names = new Set<string>();
	const shortcuts = new Set<string>([config.pickerShortcut]);
	for (const [index, valueItem] of value.items.entries()) {
		const path = `masks.items[${index}]`;
		if (!isRecord(valueItem)) {
			errors.push(`${path} must be an object`);
			continue;
		}

		const name = nonEmptyString(valueItem.name);
		const model = nonEmptyString(valueItem.model);
		const thinkingLevel = valueItem.thinkingLevel;
		let valid = true;
		if (!name) {
			errors.push(`${path}.name must be a non-empty string`);
			valid = false;
		} else if (names.has(name)) {
			errors.push(`${path}.name duplicates "${name}"`);
			valid = false;
		}
		if (
			!model ||
			model.startsWith("/") ||
			model.endsWith("/") ||
			!model.includes("/")
		) {
			errors.push(`${path}.model must be provider/model`);
			valid = false;
		}
		if (!isThinkingLevel(thinkingLevel)) {
			errors.push(`${path}.thinkingLevel is invalid`);
			valid = false;
		}
		if (!valid || !name || !model || !isThinkingLevel(thinkingLevel)) continue;

		let shortcut: string | undefined;
		if (valueItem.shortcut !== undefined) {
			shortcut = nonEmptyString(valueItem.shortcut);
			if (!shortcut) {
				errors.push(`${path}.shortcut must be a non-empty string`);
			} else if (shortcuts.has(shortcut)) {
				errors.push(`${path}.shortcut duplicates "${shortcut}"`);
				shortcut = undefined;
			}
		}

		names.add(name);
		if (shortcut) shortcuts.add(shortcut);
		config.items.push({ name, model, thinkingLevel, shortcut });
	}
	return { config, errors };
}

function readMasksSettings(): ParsedMasks {
	const settings = SettingsManager.create(
		process.cwd(),
	).getGlobalSettings() as Record<string, unknown>;
	return parseMasksSettings(settings[SETTINGS_KEY]);
}

function splitModelRef(model: string): [provider: string, modelId: string] {
	const separator = model.indexOf("/");
	return [model.slice(0, separator), model.slice(separator + 1)];
}

function fuzzyMasks(items: Mask[], query: string): Mask[] {
	if (!query.trim()) return items;
	return fuzzyFilter(
		items,
		query,
		(mask) =>
			`${mask.name} ${mask.model} ${mask.thinkingLevel} ${mask.shortcut ?? ""}`,
	);
}

async function chooseFuzzyMask(
	items: Mask[],
	ctx: ExtensionContext,
): Promise<Mask | undefined> {
	const selectedName = await ctx.ui.custom<string | undefined>(
		(tui, theme, keybindings, done) => {
			const container = new Container();
			const input = new Input();
			input.focused = true;
			let list: SelectList;

			function rebuild(): void {
				const filtered = fuzzyMasks(items, input.getValue());
				list = new SelectList(
					filtered.map((mask) => ({
						value: mask.name,
						label: mask.name,
						description: `${mask.model}:${mask.thinkingLevel}${mask.shortcut ? ` · ${mask.shortcut}` : ""}`,
					})),
					Math.min(Math.max(filtered.length, 1), 8),
					{
						selectedPrefix: (text) => theme.fg("accent", text),
						selectedText: (text) => theme.fg("accent", text),
						description: (text) => theme.fg("muted", text),
						scrollInfo: (text) => theme.fg("dim", text),
						noMatch: (text) => theme.fg("warning", text),
					},
				);
				list.onSelect = (item) => done(item.value);
				list.onCancel = () => done(undefined);

				container.clear();
				container.addChild(
					new DynamicBorder((text) => theme.fg("accent", text)),
				);
				container.addChild(
					new Text(theme.fg("accent", theme.bold("Masks")), 1, 0),
				);
				container.addChild(new Text(theme.fg("dim", "Fuzzy filter"), 1, 0));
				container.addChild(input);
				container.addChild(new Spacer(1));
				container.addChild(list);
				container.addChild(
					new Text(
						theme.fg(
							"dim",
							"type to filter · ↑↓ select · enter equip · esc cancel",
						),
						1,
						0,
					),
				);
				container.addChild(
					new DynamicBorder((text) => theme.fg("accent", text)),
				);
			}

			rebuild();
			return {
				render: (width: number) => container.render(width),
				invalidate: () => container.invalidate(),
				handleInput(data: string) {
					if (
						keybindings.matches(data, "tui.select.up") ||
						keybindings.matches(data, "tui.select.down")
					) {
						list.handleInput(data);
						tui.requestRender();
						return;
					}
					if (keybindings.matches(data, "tui.select.confirm")) {
						const selected = list.getSelectedItem();
						if (selected) done(selected.value);
						return;
					}
					if (keybindings.matches(data, "tui.select.cancel")) {
						done(undefined);
						return;
					}

					const previous = input.getValue();
					input.handleInput(data);
					if (input.getValue() !== previous) rebuild();
					tui.requestRender();
				},
			};
		},
	);
	return items.find((mask) => mask.name === selectedName);
}

function promptCommandName(text: string): string | undefined {
	return /^\/([^\s]+)(?:\s|$)/u.exec(text)?.[1];
}

async function applyMask(
	pi: ExtensionAPI,
	mask: Mask,
	ctx: ExtensionContext,
): Promise<boolean> {
	const [provider, modelId] = splitModelRef(mask.model);
	const model = ctx.modelRegistry.find(provider, modelId);
	if (!model) {
		ctx.ui.notify(
			`Mask "${mask.name}": model ${mask.model} not found`,
			"error",
		);
		return false;
	}
	if (!(await pi.setModel(model))) {
		ctx.ui.notify(
			`Mask "${mask.name}": no credentials for ${mask.model}`,
			"error",
		);
		return false;
	}
	pi.setThinkingLevel(mask.thinkingLevel);
	return true;
}

export default function masksExtension(pi: ExtensionAPI): void {
	const { config, errors } = readMasksSettings();
	let pendingMask: Mask | undefined;
	let restoreState:
		| {
				model: NonNullable<ExtensionContext["model"]>;
				thinkingLevel: ThinkingLevel;
		  }
		| undefined;

	async function chooseMask(ctx: ExtensionContext): Promise<void> {
		if (config.items.length === 0) {
			ctx.ui.notify("No masks configured in settings.json", "warning");
			return;
		}
		let mask: Mask | undefined;
		if (ctx.mode === "tui") {
			mask = await chooseFuzzyMask(config.items, ctx);
		} else {
			const options = config.items.map(
				(item) => `${item.name}  ${item.model}:${item.thinkingLevel}`,
			);
			const selected = await ctx.ui.select("Masks", options);
			const index = selected === undefined ? -1 : options.indexOf(selected);
			mask = index >= 0 ? config.items[index] : undefined;
		}
		if (mask) await applyMask(pi, mask, ctx);
	}

	pi.registerShortcut(config.pickerShortcut as Shortcut, {
		description: "Choose model and thinking mask",
		handler: chooseMask,
	});
	for (const mask of config.items) {
		if (!mask.shortcut) continue;
		pi.registerShortcut(mask.shortcut as Shortcut, {
			description: `Equip mask ${mask.name}`,
			handler: async (ctx) => {
				await applyMask(pi, mask, ctx);
			},
		});
	}

	pi.registerCommand("masks", {
		description: "Switch model and thinking mask",
		handler: async (args, ctx) => {
			const name = args?.trim();
			if (!name) {
				await chooseMask(ctx);
				return;
			}
			const mask = config.items.find((item) => item.name === name);
			if (!mask) {
				ctx.ui.notify(`Unknown mask "${name}"`, "error");
				return;
			}
			await applyMask(pi, mask, ctx);
		},
	});

	pi.on("input", (event, ctx) => {
		pendingMask = undefined;
		const commandName = promptCommandName(event.text);
		if (!commandName) return { action: "continue" };
		const command = pi
			.getCommands()
			.find((item) => item.source === "prompt" && item.name === commandName);
		if (!command) return { action: "continue" };

		let frontmatter: Record<string, unknown>;
		try {
			frontmatter = parseFrontmatter(
				readFileSync(command.sourceInfo.path, "utf8"),
			).frontmatter;
		} catch (error) {
			ctx.ui.notify(
				`Prompt /${commandName}: ${error instanceof Error ? error.message : String(error)}`,
				"error",
			);
			return { action: "handled" };
		}
		if (!Object.hasOwn(frontmatter, "mask")) return { action: "continue" };
		const maskName = nonEmptyString(frontmatter.mask);
		if (!maskName) {
			ctx.ui.notify(
				`Prompt /${commandName}: mask must be a non-empty string`,
				"error",
			);
			return { action: "handled" };
		}
		const mask = config.items.find((item) => item.name === maskName);
		if (!mask) {
			ctx.ui.notify(
				`Prompt /${commandName}: unknown mask "${maskName}"`,
				"error",
			);
			return { action: "handled" };
		}
		if (!ctx.isIdle()) {
			ctx.ui.notify(
				`Prompt /${commandName}: masked prompts cannot be queued mid-run`,
				"warning",
			);
			return { action: "handled" };
		}
		pendingMask = mask;
		return { action: "continue" };
	});

	pi.on("before_agent_start", async (_event, ctx) => {
		const mask = pendingMask;
		pendingMask = undefined;
		if (!mask) return;
		if (!ctx.model) {
			ctx.ui.notify(
				`Mask "${mask.name}": no current model to restore`,
				"error",
			);
			return;
		}
		const previous = {
			model: ctx.model,
			thinkingLevel: pi.getThinkingLevel(),
		};
		if (await applyMask(pi, mask, ctx)) restoreState = previous;
	});

	async function restoreTemporaryMask(ctx: ExtensionContext): Promise<void> {
		const previous = restoreState;
		restoreState = undefined;
		if (!previous) return;
		if (!(await pi.setModel(previous.model))) {
			ctx.ui.notify("Failed to restore model after prompt mask", "error");
			return;
		}
		pi.setThinkingLevel(previous.thinkingLevel);
	}

	pi.on("agent_end", async (_event, ctx) => restoreTemporaryMask(ctx));
	pi.on("session_start", (_event, ctx) => {
		for (const error of errors) ctx.ui.notify(error, "warning");
	});
	pi.on("session_shutdown", async (_event, ctx) => {
		pendingMask = undefined;
		await restoreTemporaryMask(ctx);
	});
}

export const __test = {
	applyMask,
	chooseFuzzyMask,
	fuzzyMasks,
	parseMasksSettings,
	promptCommandName,
	splitModelRef,
};