import { DynamicBorder, type ExtensionAPI, type ExtensionContext, } from "@earendil-works/pi-coding-agent"; import { Container, fuzzyFilter, Input, SelectList, Spacer, Text, } from "@earendil-works/pi-tui"; import { closeDebug, dbg, span } from "./src/debug.ts"; import { resolveSetting, type SettingDeclaration, } from "./src/pi-ext-settings.ts"; const DEFAULT_PICKER_SHORTCUT = "alt+m"; type ThinkingLevel = Parameters[0]; const THINKING_LEVELS = [ "off", "minimal", "low", "medium", "high", "xhigh", "max", ] as const satisfies readonly ThinkingLevel[]; type Shortcut = Parameters[0]; interface Mask { name: string; model: string; thinkingLevel: ThinkingLevel; shortcut?: string | undefined; } interface MasksConfig { pickerShortcut: string; items: Mask[]; } interface ParsedMasks { config: MasksConfig; errors: string[]; } function isRecord(value: unknown): value is Record { 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(); const shortcuts = new Set([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 }; } // Parsing keeps valid masks and collects per-field errors, so it never rejects. const MASKS_SETTING: SettingDeclaration = { key: "masks", parse: parseMasksSettings, default: parseMasksSettings(undefined), }; // Shortcuts register at load time, before any session or project trust exists, // so masks stay user-only: project settings are never read. function readMasksSettings(pi: ExtensionAPI): ParsedMasks { const setting = resolveSetting( pi, { cwd: process.cwd(), isProjectTrusted: () => false }, MASKS_SETTING, ); return setting.ok ? setting.value : { config: MASKS_SETTING.default.config, errors: [setting.error] }; } function describeMask(mask: Mask): string { const parts = [`${mask.model}:${mask.thinkingLevel}`]; if (mask.shortcut) parts.push(mask.shortcut); return parts.join(" · "); } 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 { const selectedName = await ctx.ui.custom( (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: describeMask(mask), })), 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(); }, }; }, { blocked: { kind: "question", message: "Choose a model and thinking mask", }, }, ); return items.find((mask) => mask.name === selectedName); } async function applyMask( pi: ExtensionAPI, mask: Mask, ctx: ExtensionContext, ): Promise { const end = span?.("mask.apply"); const model = ctx.modelRegistry .getAll() .find( (candidate) => `${candidate.provider}/${candidate.id}` === mask.model, ); if (!model) { end?.("error", { type: "model_missing" }); ctx.ui.notify( `Mask "${mask.name}": model ${mask.model} not found`, "error", ); return; } try { if (!(await pi.setModel(model))) { end?.("error", { type: "credentials" }); ctx.ui.notify( `Mask "${mask.name}": no credentials for ${mask.model}`, "error", ); return; } pi.setThinkingLevel(mask.thinkingLevel); end?.(); } catch (error) { end?.("error", { type: "apply" }); throw error; } } export default function masksExtension(pi: ExtensionAPI): void { const { config, errors } = readMasksSettings(pi); let switching = false; async function equip(mask: Mask, ctx: ExtensionContext): Promise { if (switching) { ctx.ui.notify("Mask switch already in progress", "warning"); return; } switching = true; try { await applyMask(pi, mask, ctx); } finally { switching = false; } } async function chooseMask(ctx: ExtensionContext): Promise { 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} ${describeMask(item)}`, ); 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 equip(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) => equip(mask, ctx), }); } pi.registerCommand("masks", { description: "Switch model and thinking mask", getArgumentCompletions: (prefix) => { const matches = config.items .filter((mask) => mask.name.startsWith(prefix)) .map((mask) => ({ value: mask.name, label: mask.name })); return matches.length ? matches : null; }, 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 equip(mask, ctx); }, }); pi.on("session_start", (_event, ctx) => { dbg?.("session.start", { mode: ctx.mode }); for (const error of errors) ctx.ui.notify(error, "warning"); }); pi.on("session_shutdown", (_event, ctx) => { dbg?.("session.shutdown", { mode: ctx.mode }); closeDebug(); }); } export const __test: { chooseFuzzyMask: typeof chooseFuzzyMask; describeMask: typeof describeMask; fuzzyMasks: typeof fuzzyMasks; parseMasksSettings: typeof parseMasksSettings; } = { chooseFuzzyMask, describeMask, fuzzyMasks, parseMasksSettings, };