import type { ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent"; import type { AutocompleteItem } from "@earendil-works/pi-tui"; import { CustomStyleConfig, VALID_STYLES, resolveStyleKey } from "./presets"; import { BeautifierState, applyConfig, defaultBeautifierState, loadConfig, removeBeautifierSettings, resetRuntime, sanitizeCustomConfig, settingsPaths, writeBeautifierSettings, } from "./config"; import { createFooterFactory } from "./footer"; const STYLE_BLURBS: Record<(typeof VALID_STYLES)[number], string> = { claude: "Minimal dots (anchor · ⌖ 3)", stream: "Crisp chevrons (anchor ❯ ⌖ 3)", nord: "Angle brackets (anchor ‹⌖ 3›)", glow: "Inverse pill badges", custom: "Your custom JSON style", off: "Restore native Pi footer & clear settings", }; export const STYLE_MENU: string[] = VALID_STYLES.map( (style) => `${style.padEnd(7)} - ${STYLE_BLURBS[style]}` ); const DEFAULT_CUSTOM_TEMPLATE: CustomStyleConfig = { separator: " · ", glyphs: { success: "●", warning: "○", error: "▲", accent: "◆" }, }; export function getBeautifyCompletions(prefix: string): AutocompleteItem[] | null { const parts = prefix.trimStart().split(/\s+/); const trailingSpace = /\s$/.test(prefix); if (parts.length <= 1 && !trailingSpace) { const query = (parts[0] || "").toLowerCase(); const candidates: AutocompleteItem[] = [ ...VALID_STYLES.map((s) => ({ value: s, label: s, description: STYLE_BLURBS[s] })), { value: "footer", label: "footer", description: "Toggle full 2-line footer on/off" }, { value: "status", label: "status", description: "Switch to status-only mode" }, { value: "info", label: "info", description: "Show current beautifier style and settings path" }, { value: "help", label: "help", description: "Show /beautify usage" }, ]; return candidates.filter((item) => item.value.startsWith(query)); } const first = parts[0]?.toLowerCase() || ""; const secondQuery = (trailingSpace ? "" : parts[1] || "").toLowerCase(); if (first === "custom") { return [{ value: "custom edit", label: "edit", description: "Edit custom JSON in editor" }].filter((i) => i.label.startsWith(secondQuery) ); } if (first === "footer") { return [ { value: "footer on", label: "on", description: "Enable 2-line footer" }, { value: "footer off", label: "off", description: "Disable full footer (status-only)" }, ].filter((i) => i.label.startsWith(secondQuery)); } if ((VALID_STYLES as readonly string[]).includes(first) && first !== "off") { return [ { value: `${first} status`, label: "status", description: "Status badges only" }, { value: `${first} full`, label: "full", description: "Full 2-line footer" }, { value: `${first} --local`, label: "--local", description: "Write to ./.pi/settings.json" }, ].filter((i) => i.label.startsWith(secondQuery)); } return null; } export interface BeautifyAutocompleteProviderLike { triggerCharacters?: string[]; getSuggestions( lines: string[], cursorLine: number, cursorCol: number, options: { signal: AbortSignal; force?: boolean } ): Promise<{ items: AutocompleteItem[]; prefix: string } | null> | { items: AutocompleteItem[]; prefix: string } | null; applyCompletion( lines: string[], cursorLine: number, cursorCol: number, item: AutocompleteItem, prefix: string ): { lines: string[]; cursorLine: number; cursorCol: number }; shouldTriggerFileCompletion?(lines: string[], cursorLine: number, cursorCol: number): boolean; } export function createBeautifyAutocompleteProvider( current: BeautifyAutocompleteProviderLike ): BeautifyAutocompleteProviderLike { return { ...(current.triggerCharacters ? { triggerCharacters: current.triggerCharacters } : {}), async getSuggestions(lines, cursorLine, cursorCol, options) { if (cursorLine === 0 && options.force) { const commandText = (lines[cursorLine] ?? "").slice(0, cursorCol).trimStart(); if (commandText.startsWith("/beautify ")) { const argPrefix = commandText.slice("/beautify ".length); const items = getBeautifyCompletions(argPrefix); if (items && items.length > 0) return { items, prefix: argPrefix }; } } return current.getSuggestions(lines, cursorLine, cursorCol, options); }, applyCompletion(lines, cursorLine, cursorCol, item, prefix) { return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix); }, ...(current.shouldTriggerFileCompletion ? { shouldTriggerFileCompletion: (lines, cursorLine, cursorCol) => current.shouldTriggerFileCompletion!(lines, cursorLine, cursorCol) } : {}), }; } function flushStatusesToHost(ctx: ExtensionContext, state: BeautifierState): void { for (const [key, val] of state.rawStatuses.entries()) { ctx.ui.setStatus(key, val); } } function revertToNative(ctx: ExtensionContext, state: BeautifierState): void { resetRuntime(state.runtime); state.lastRenderedStatus.clear(); flushStatusesToHost(ctx, state); if (typeof ctx.ui.setFooter === "function") { ctx.ui.setFooter(undefined); } const { removed, errors } = removeBeautifierSettings(ctx.cwd || process.cwd()); if (errors.length > 0) { ctx.ui.notify(`Restored native status bar; cleanup failed: ${errors.join("; ")}`, "warning"); } else if (removed.length === 0) { ctx.ui.notify("Restored native Pi status bar.", "info"); } else { ctx.ui.notify(`Restored native Pi status bar and cleaned ${removed.length} settings file(s).`, "info"); } } function applyAndPersist( ctx: ExtensionContext, styleKey: string, isFullFooter: boolean, customCfg: CustomStyleConfig | undefined, forceLocal: boolean, state: BeautifierState ): void { const cwd = ctx.cwd || process.cwd(); const cfg = loadConfig(cwd); const targetPath = forceLocal ? settingsPaths(cwd).localPath : cfg.targetSettingsPath; const resolvedCustom = customCfg ?? cfg.custom; applyConfig(cfg, { style: styleKey, fullFooter: isFullFooter, custom: resolvedCustom }, state.runtime); state.lastRenderedStatus.clear(); let writeError: string | undefined; try { writeBeautifierSettings(targetPath, styleKey, isFullFooter, customCfg); } catch (error) { writeError = error instanceof Error ? error.message : String(error); } if (typeof ctx.ui.setFooter === "function") { ctx.ui.setFooter(isFullFooter ? createFooterFactory(ctx, state) : undefined); } flushStatusesToHost(ctx, state); if (writeError) { ctx.ui.notify(`Style applied for this session, but settings.json failed to save: ${writeError}`, "warning"); return; } ctx.ui.notify( `Status style: ${styleKey} (${isFullFooter ? "full footer" : "status-only"})`, "info" ); } async function handleCustomCommand( ctx: ExtensionContext | ExtensionCommandContext, tokens: string[], forceLocal: boolean, state: BeautifierState ): Promise { const cwd = ctx.cwd || process.cwd(); const cfg = loadConfig(cwd); const existingCustom = state.runtime.custom ?? cfg.custom; const wantsEdit = tokens.includes("edit") || !existingCustom; if (!wantsEdit && existingCustom) { applyAndPersist(ctx, "custom", state.runtime.fullFooter, existingCustom, forceLocal, state); return; } if (typeof ctx.ui.editor !== "function") { ctx.ui.notify("Multi-line editor unavailable; configure `beautifier.custom` in settings.json.", "warning"); return; } const seed = existingCustom ?? DEFAULT_CUSTOM_TEMPLATE; const edited = await ctx.ui.editor("Custom Beautifier JSON", JSON.stringify(seed, null, 2)); if (edited === undefined) return; let parsed: unknown; try { parsed = JSON.parse(edited); } catch (error) { ctx.ui.notify( `Invalid JSON in custom style (${error instanceof Error ? error.message : String(error)}). Kept previous style.`, "warning" ); return; } const unwrapped = parsed && typeof parsed === "object" && !Array.isArray(parsed) && "custom" in parsed ? (parsed as { custom: unknown }).custom : parsed; const sanitized = sanitizeCustomConfig(unwrapped); if (!sanitized) { ctx.ui.notify("Custom config must be a JSON object. Kept previous style.", "warning"); return; } applyAndPersist(ctx, "custom", state.runtime.fullFooter, sanitized, forceLocal, state); } export async function runBeautify( _pi: unknown, args: string | undefined, ctx: ExtensionContext | ExtensionCommandContext, state: BeautifierState = defaultBeautifierState ): Promise { if (!ctx?.hasUI || !ctx.ui) return; const rawTokens = (args || "").trim().split(/\s+/).filter(Boolean); const forceLocal = rawTokens.includes("--local"); const tokens = rawTokens.filter((tok) => tok !== "--local"); const first = (tokens[0] || "").toLowerCase(); const second = (tokens[1] || "").toLowerCase(); if (first === "help" || first === "--help" || first === "-h" || first === "?") { ctx.ui.notify( [ "Usage: /beautify [style|footer|custom|info|off] [status|full] [--local]", `Styles: ${VALID_STYLES.join(", ")}`, "Examples: /beautify, /beautify claude, /beautify nord full, /beautify footer off, /beautify info, /beautify off", ].join("\n"), "info" ); return; } if (first === "info" || first === "show") { const cfg = loadConfig(ctx.cwd || process.cwd()); ctx.ui.notify( [ `Status beautifier: style=${state.runtime.style}, scope=${state.runtime.fullFooter ? "full-footer" : "status-only"}`, `Settings target: ${cfg.targetSettingsPath}`, ].join("\n"), "info" ); return; } if (first === "footer") { const targetFull = second === "off" || second === "status" ? false : second === "on" || second === "full" ? true : !state.runtime.fullFooter; const activeStyle = state.runtime.style === "off" ? "claude" : state.runtime.style; applyAndPersist(ctx, activeStyle, targetFull, undefined, forceLocal, state); return; } if (first === "status" || first === "status-only") { const activeStyle = state.runtime.style === "off" ? "claude" : state.runtime.style; applyAndPersist(ctx, activeStyle, false, undefined, forceLocal, state); return; } if (first === "full" || first === "full-footer") { const activeStyle = state.runtime.style === "off" ? "claude" : state.runtime.style; applyAndPersist(ctx, activeStyle, true, undefined, forceLocal, state); return; } let styleKey: string; let explicit = false; if (first) { const resolved = resolveStyleKey(first); if ((VALID_STYLES as readonly string[]).includes(resolved)) { styleKey = resolved; explicit = true; } } if (!explicit) { const menu = VALID_STYLES.map((s) => { const marker = s === state.runtime.style ? " (current)" : ""; return `${s.padEnd(7)} - ${STYLE_BLURBS[s]}${marker}`; }); const picked = await ctx.ui.select(`Status bar style (current: ${state.runtime.style}):`, menu); if (!picked) return; styleKey = picked.split(" ")[0].trim(); } else { styleKey = resolveStyleKey(first); } if (styleKey === "off") { revertToNative(ctx, state); return; } if (styleKey === "custom") { await handleCustomCommand(ctx, tokens.slice(1), forceLocal, state); return; } let isFullFooter: boolean; if (second === "status" || second === "status-only") { isFullFooter = false; } else if (second === "full" || second === "full-footer") { isFullFooter = true; } else if (explicit) { isFullFooter = state.runtime.fullFooter; } else { const scopeChoice = await ctx.ui.select("Choose scope:", [ "status-only - Beautify extension status badges only (keeps native Pi footer)", "full-footer - Transform full footer (branch, Pi telemetry, folded badges, live spinners)", ]); if (!scopeChoice) return; isFullFooter = scopeChoice.startsWith("full-footer"); } applyAndPersist(ctx, styleKey, isFullFooter, undefined, forceLocal, state); }