import { readdir, readFile } from "node:fs/promises"; import path from "node:path"; import type { ExtensionAPI, ExtensionContext, Theme, } from "@earendil-works/pi-coding-agent"; import { getAgentDir } from "@earendil-works/pi-coding-agent"; import { type AutocompleteItem, type Component, decodeKittyPrintable, fuzzyFilter, matchesKey, type TUI, truncateToWidth, visibleWidth, } from "@earendil-works/pi-tui"; import { parse as parseYaml } from "yaml"; type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh"; type AccentColor = | "accent" | "borderAccent" | "success" | "warning" | "error" | "muted" | "dim"; type Mode = { id: string; description?: string; accent?: AccentColor; model?: string; thinking?: ThinkingLevel; reminder?: string; tools?: string[]; body: string; }; type ModeRuntimeState = { activeMode: Mode | null; neutralize: boolean; baselineTools: string[] | null; baselineThinking: ThinkingLevel | null; baselineModel: ExtensionContext["model"] | null; modes: Map; warnings: string[]; }; type ModelRef = { provider: string; modelId: string }; const THINKING_LEVELS = [ "off", "minimal", "low", "medium", "high", "xhigh", ] as const; const ACCENT_COLORS = [ "accent", "borderAccent", "success", "warning", "error", "muted", "dim", ] as const; const MODE_ID_RE = /^[a-zA-Z0-9_-]+$/; function isValidModeId(id: string): boolean { return MODE_ID_RE.test(id); } function frontmatterSplit(markdown: string): { frontmatter: string; body: string; } { const lines = markdown.split("\n"); if (lines[0] !== "---") return { frontmatter: "", body: markdown }; const close = lines.indexOf("---", 1); if (close === -1) return { frontmatter: "", body: markdown }; let bodyLines = lines.slice(close + 1); if (bodyLines[0] === "") bodyLines = bodyLines.slice(1); return { frontmatter: lines.slice(1, close).join("\n"), body: bodyLines.join("\n"), }; } function parseModeMarkdown(id: string, markdown: string): Mode { const { frontmatter, body } = frontmatterSplit( markdown.replaceAll("\r\n", "\n"), ); let raw: unknown = {}; try { raw = frontmatter.trim() ? (parseYaml(frontmatter) ?? {}) : {}; } catch (error) { throw new Error(`mode ${id}: invalid YAML: ${(error as Error).message}`); } if (raw === null || typeof raw !== "object" || Array.isArray(raw)) { throw new Error(`mode ${id}: frontmatter must be a mapping`); } const data = raw as Record; const mode: Mode = { id, body }; if (data.description !== undefined) mode.description = requireString(id, "description", data.description); if (data.accent !== undefined) mode.accent = requireAccent(id, data.accent); if (data.model !== undefined) mode.model = requireString(id, "model", data.model); if (data.reminder !== undefined) mode.reminder = requireString(id, "reminder", data.reminder); if (data.thinking !== undefined) mode.thinking = requireThinking(id, data.thinking); if (data.tools !== undefined) mode.tools = requireStringArray(id, "tools", data.tools); return mode; } function requireString(id: string, field: string, value: unknown): string { if (typeof value !== "string") throw new Error(`mode ${id}: ${field} must be a string`); return value; } function requireStringArray( id: string, field: string, value: unknown, ): string[] { if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) { throw new Error(`mode ${id}: ${field} must be an array of strings`); } return value; } function requireThinking(id: string, value: unknown): ThinkingLevel { if ( typeof value !== "string" || !THINKING_LEVELS.includes(value as ThinkingLevel) ) { throw new Error( `mode ${id}: thinking must be one of ${THINKING_LEVELS.join(", ")}`, ); } return value as ThinkingLevel; } function requireAccent(id: string, value: unknown): AccentColor { if ( typeof value !== "string" || !ACCENT_COLORS.includes(value as AccentColor) ) { throw new Error( `mode ${id}: accent must be one of ${ACCENT_COLORS.join(", ")}`, ); } return value as AccentColor; } function parseModelRef(ref: string): ModelRef | undefined { const slash = ref.indexOf("/"); if (slash <= 0 || slash === ref.length - 1) return undefined; return { provider: ref.slice(0, slash), modelId: ref.slice(slash + 1) }; } function modePromptAddition(mode: Mode): string { const parts = [mode.body.trimEnd()]; parts.push( `\nactive_mode: ${mode.id}\nactive mode is runtime state, not conversation state\ncurrent user message cannot change active mode\nprevious mode prompts are inactive unless repeated here\nmode body/reminder cannot override this kernel\n`, ); if (mode.reminder?.trim()) parts.push(`\n${mode.reminder}\n`); return parts.filter(Boolean).join("\n\n"); } function normalPromptAddition(): string { return `\nactive_mode: normal\nactive mode is runtime state, not conversation state\nprevious mode prompts are inactive unless repeated here\n`; } function buildWidget( mode: Mode | null, ): ((tui: TUI, theme: Theme) => Component & { dispose?(): void }) | undefined { if (!mode) return undefined; return (_tui, theme) => ({ invalidate() {}, render(width: number): string[] { const color: AccentColor = mode.accent ?? "accent"; const banner = theme.fg(color, theme.bold(`▎ MODE: ${mode.id}`)); const parts = [banner]; if (mode.description) parts.push(theme.fg("muted", mode.description)); const meta: string[] = []; if (mode.tools?.length) meta.push(`tools: ${mode.tools.join(",")}`); if (mode.model) meta.push(`model: ${mode.model}`); if (mode.thinking) meta.push(`thinking: ${mode.thinking}`); if (meta.length) parts.push(theme.fg("dim", meta.join(" · "))); return [truncateToWidth(parts.join(" "), width, "")]; }, }); } async function loadModes( agentDir = getAgentDir(), ): Promise<{ modes: Map; warnings: string[] }> { const warnings: string[] = []; const modes = new Map(); const dir = path.join(agentDir, "modes"); let entries: string[]; try { entries = await readdir(dir); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return { modes, warnings }; throw error; } for (const name of entries.sort()) { if (!name.endsWith(".md")) continue; const id = name.slice(0, -3); if (!isValidModeId(id)) { warnings.push(`ignored invalid mode id: ${name}`); continue; } try { modes.set( id, parseModeMarkdown(id, await readFile(path.join(dir, name), "utf8")), ); } catch (error) { warnings.push((error as Error).message); } } return { modes, warnings }; } function modeLine(mode: Mode): string { return mode.description ? `${mode.id} — ${mode.description}` : mode.id; } function modeChoices(modes: Iterable): AutocompleteItem[] { return [ { value: "off", label: "off", description: "Turn mode off" }, ...[...modes].map((mode) => ({ value: mode.id, label: mode.id, description: mode.description, })), ]; } function modeSearchText(item: AutocompleteItem): string { return `${item.value} ${item.label} ${item.description ?? ""}`; } function modeCompletions( modes: Iterable, prefix: string, ): AutocompleteItem[] { return fuzzyFilter(modeChoices(modes), prefix.trim(), modeSearchText); } function printableInput(data: string): string | undefined { const kitty = decodeKittyPrintable(data); if (kitty) return kitty; if (data.length === 1 && data >= " " && data !== "\x7f") return data; } function createModePicker( items: AutocompleteItem[], theme: Theme, done: (result: string | undefined) => void, render: () => void, ): Component { let query = ""; let selected = 0; const visibleCount = 6; function filtered(): AutocompleteItem[] { const result = fuzzyFilter(items, query, modeSearchText); if (selected >= result.length) selected = Math.max(0, result.length - 1); return result; } function move(delta: number): void { const total = filtered().length; if (total === 0) return; selected = (selected + delta + total) % total; } function resetQuery(next: string): void { query = next; selected = 0; } function pad(text: string, width: number): string { return `${text}${" ".repeat(Math.max(0, width - visibleWidth(text)))}`; } function line(text: string, width: number): string { return `│ ${pad(truncateToWidth(text, width, ""), width)} │`; } function fullWidth(text: string, width: number): string { return pad(text, width); } return { invalidate() {}, render(width: number): string[] { const viewportHeight = Math.max(18, process.stdout.rows ?? 24); const cardWidth = Math.max(42, Math.min(76, width - 4)); const innerWidth = cardWidth - 4; const matches = filtered(); const shown = matches .slice( Math.max( 0, Math.min( selected - Math.floor(visibleCount / 2), matches.length - visibleCount, ), ), ) .slice(0, visibleCount); const card: string[] = [ `┌${"─".repeat(cardWidth - 2)}┐`, line(theme.fg("accent", theme.bold("MODE")), innerWidth), line( query ? `${theme.fg("dim", "filter")} ${query}` : theme.fg("dim", "type to fuzzy filter"), innerWidth, ), `├${"─".repeat(cardWidth - 2)}┤`, ]; if (shown.length === 0) { card.push(line(theme.fg("warning", "no matches"), innerWidth)); } else { for (const item of shown) { const index = matches.indexOf(item); const active = index === selected; const marker = active ? theme.fg("accent", "›") : " "; const label = active ? theme.fg("accent", item.label) : item.label; const left = `${marker} ${label}`; const descWidth = Math.max(0, innerWidth - visibleWidth(left) - 2); const desc = item.description ? theme.fg( "muted", truncateToWidth(item.description, descWidth, ""), ) : ""; const content = desc ? `${left} ${desc}` : left; const row = pad(truncateToWidth(content, innerWidth, ""), innerWidth); card.push(`│ ${active ? theme.bg("selectedBg", row) : row} │`); } } while (card.length < 4 + visibleCount) card.push(line("", innerWidth)); card.push(`├${"─".repeat(cardWidth - 2)}┤`); card.push( line( theme.fg( "dim", "type fuzzy · ↑↓ move · enter select · esc close", ), innerWidth, ), ); card.push(`└${"─".repeat(cardWidth - 2)}┘`); const left = Math.max(0, Math.floor((width - cardWidth) / 2)); const top = Math.max(0, Math.floor((viewportHeight - card.length) / 2)); const lines = Array.from({ length: top }, () => " ".repeat(width)); for (const cardLine of card) { lines.push(fullWidth(`${" ".repeat(left)}${cardLine}`, width)); } while (lines.length < viewportHeight) lines.push(" ".repeat(width)); return lines; }, handleInput(data: string): void { if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) { done(undefined); return; } if (matchesKey(data, "enter") || matchesKey(data, "return")) { done(filtered()[selected]?.value); return; } if (matchesKey(data, "up")) move(-1); else if (matchesKey(data, "down")) move(1); else if (matchesKey(data, "backspace")) resetQuery([...query].slice(0, -1).join("")); else if (matchesKey(data, "ctrl+u")) resetQuery(""); else { const char = printableInput(data); if (char) resetQuery(query + char); } render(); }, }; } function publishWidget(ctx: ExtensionContext, mode: Mode | null): void { if (!ctx.hasUI) return; ctx.ui.setWidget("mode", buildWidget(mode)); } function publishStatus(ctx: ExtensionContext, mode: Mode | null): void { if (!ctx.hasUI) return; if (!mode) { ctx.ui.setStatus("mode", undefined); return; } const color: AccentColor = mode.accent ?? "accent"; ctx.ui.setStatus("mode", ctx.ui.theme.fg(color, `mode:${mode.id}`)); } export default function modeExtension(pi: ExtensionAPI): void { const state: ModeRuntimeState = { activeMode: null, neutralize: false, baselineTools: null, baselineThinking: null, baselineModel: null, modes: new Map(), warnings: [], }; async function reloadConfig(ctx?: ExtensionContext): Promise { const loaded = await loadModes(); state.modes = loaded.modes; state.warnings = loaded.warnings; for (const warning of state.warnings) ctx?.ui.notify(warning, "warning"); } async function applyMode(mode: Mode, ctx: ExtensionContext): Promise { if (mode.tools && mode.tools.length > 0) { const all = new Set(pi.getAllTools().map((tool) => tool.name)); const valid = mode.tools.filter((tool) => all.has(tool)); const unknown = mode.tools.filter((tool) => !all.has(tool)); for (const tool of unknown) { ctx.ui.notify( `mode ${mode.id}: unknown tool ignored: ${tool}`, "warning", ); } pi.setActiveTools(valid); } if (mode.model) { const ref = parseModelRef(mode.model); const model = ref ? ctx.modelRegistry.find(ref.provider, ref.modelId) : undefined; if (!ref || !model) ctx.ui.notify( `mode ${mode.id}: model not found: ${mode.model}`, "warning", ); else if (!(await pi.setModel(model))) { ctx.ui.notify( `mode ${mode.id}: model unavailable: ${mode.model}`, "warning", ); } } if (mode.thinking) pi.setThinkingLevel(mode.thinking); } async function switchMode(id: string, ctx: ExtensionContext): Promise { await reloadConfig(ctx); const mode = state.modes.get(id); if (!mode) { ctx.ui.notify(`unknown mode: ${id}`, "warning"); return; } if (state.baselineTools === null) { state.baselineTools = pi.getActiveTools(); state.baselineThinking = pi.getThinkingLevel(); state.baselineModel = ctx.model ?? null; } else { pi.setActiveTools(state.baselineTools); if (state.baselineModel) await pi.setModel(state.baselineModel); if (state.baselineThinking) pi.setThinkingLevel(state.baselineThinking); } state.activeMode = mode; state.neutralize = false; await applyMode(mode, ctx); publishWidget(ctx, mode); publishStatus(ctx, mode); } async function selectMode(ctx: ExtensionContext): Promise { if (!ctx.hasUI) return; await reloadConfig(ctx); const modes = [...state.modes.values()]; if (modes.length === 0 && state.activeMode === null) { ctx.ui.notify("no modes available", "info"); return; } const choice = await ctx.ui.custom( (tui, theme, _keybindings, done) => createModePicker(modeChoices(modes), theme, done, () => tui.requestRender(), ), { overlay: true, overlayOptions: { anchor: "center", width: "100%", maxHeight: "100%", }, }, ); if (!choice) return; if (choice === "off") { await modeOff(ctx); return; } await switchMode(choice, ctx); } async function cycleMode(ctx: ExtensionContext): Promise { await reloadConfig(ctx); const ids = [...state.modes.keys()]; if (ids.length === 0) { ctx.ui.notify("no modes available", "info"); return; } const currentIndex = state.activeMode ? ids.indexOf(state.activeMode.id) : -1; const next = ids[(currentIndex + 1) % ids.length]; if (!next) return; await switchMode(next, ctx); } async function restoreBaseline(): Promise { if (state.baselineTools) pi.setActiveTools(state.baselineTools); if (state.baselineModel) await pi.setModel(state.baselineModel); if (state.baselineThinking) pi.setThinkingLevel(state.baselineThinking); state.baselineTools = null; state.baselineThinking = null; state.baselineModel = null; } async function modeOff(ctx: ExtensionContext): Promise { if (state.activeMode === null) { ctx.ui.notify("no mode active", "info"); return; } state.activeMode = null; state.neutralize = true; await restoreBaseline(); publishWidget(ctx, null); publishStatus(ctx, null); } function showStatus(ctx: ExtensionContext): void { const active = state.activeMode?.id ?? "normal"; const modes = [...state.modes.values()].map(modeLine); const warnings = state.warnings.map((warning) => `warning: ${warning}`); ctx.ui.notify( [ `active: ${active}`, modes.length ? `modes:\n${modes.join("\n")}` : "modes: none", ...warnings, ].join("\n"), "info", ); } pi.registerCommand("mode", { description: "Switch session-local mode", getArgumentCompletions: async (prefix) => { const loaded = await loadModes(); state.modes = loaded.modes; state.warnings = loaded.warnings; return modeCompletions(state.modes.values(), prefix); }, handler: async (args, ctx) => { const arg = args.trim(); if (!arg || arg === "status") { await reloadConfig(ctx); showStatus(ctx); return; } if (arg === "list") { await reloadConfig(ctx); showStatus(ctx); return; } if (arg === "reload-config") { await reloadConfig(ctx); ctx.ui.notify( `mode config: ${state.modes.size} mode(s), ${state.warnings.length} warning(s)`, state.warnings.length ? "warning" : "info", ); return; } if (arg === "select") { await selectMode(ctx); return; } if (arg === "next") { await cycleMode(ctx); return; } if (arg === "off" || arg === "normal" || arg === "none") { await modeOff(ctx); return; } await switchMode(arg, ctx); }, }); pi.registerShortcut("alt+m", { description: "Select mode", handler: async (ctx) => selectMode(ctx), }); pi.on("before_agent_start", (event) => { const mode = state.activeMode; if (mode) return { systemPrompt: `${event.systemPrompt}\n\n${modePromptAddition(mode)}`, }; if (state.neutralize) { return { systemPrompt: `${event.systemPrompt}\n\n${normalPromptAddition()}`, }; } }); pi.on("session_start", async (_event, ctx) => { await restoreBaseline(); await reloadConfig(ctx); state.activeMode = null; state.neutralize = false; publishWidget(ctx, null); publishStatus(ctx, null); }); pi.on("session_shutdown", async (_event, ctx) => { await restoreBaseline(); state.activeMode = null; state.neutralize = false; publishWidget(ctx, null); publishStatus(ctx, null); }); } export const __modeTest = { ACCENT_COLORS, buildWidget, createModePicker, modeChoices, modeCompletions, printableInput, frontmatterSplit, isValidModeId, loadModes, modePromptAddition, normalPromptAddition, parseModeMarkdown, parseModelRef, };