import * as fs from "node:fs"; import * as path from "node:path"; import { CustomStyleConfig, OFF_STYLES, STYLE_ALIASES, VALID_STYLES, getPreset, resolveStyleKey, type BuiltinStyleName, } from "./presets"; export interface ResolvedConfig { style: string; fullFooter: boolean; custom?: CustomStyleConfig; targetSettingsPath: string; hasLocalOverride: boolean; } export interface RuntimeState { style: string; fullFooter: boolean; custom?: CustomStyleConfig; targetSettingsPath: string; } export interface SettingsPaths { globalPath: string; localPath: string; } export interface BeautifierState { runtime: RuntimeState; rawStatuses: Map; lastRenderedStatus: Map; } export function createBeautifierState(): BeautifierState { return { runtime: { style: "claude", fullFooter: false, targetSettingsPath: "", }, rawStatuses: new Map(), lastRenderedStatus: new Map(), }; } export const defaultBeautifierState: BeautifierState = createBeautifierState(); export const runtime: RuntimeState = defaultBeautifierState.runtime; /** Captured un-beautified status texts keyed by extension name. */ export const rawStatuses = defaultBeautifierState.rawStatuses; export const lastRenderedStatus = defaultBeautifierState.lastRenderedStatus; export function applyConfig( cfg: ResolvedConfig, over?: { style?: string; fullFooter?: boolean; custom?: CustomStyleConfig }, targetRuntime: RuntimeState = runtime ): void { targetRuntime.style = over?.style ?? cfg.style; targetRuntime.fullFooter = over?.fullFooter ?? cfg.fullFooter; targetRuntime.custom = over?.custom ?? cfg.custom; targetRuntime.targetSettingsPath = cfg.targetSettingsPath; } export function resetRuntime(targetRuntime: RuntimeState = runtime): void { targetRuntime.style = "off"; targetRuntime.fullFooter = false; targetRuntime.custom = undefined; } export function isTestEnvironment(): boolean { return ( process.env.NODE_ENV === "test" || process.env.VITEST !== undefined || process.env.NODE_TEST_CONTEXT !== undefined || process.execArgv.some((arg) => arg.includes("test") || arg.includes("vitest")) || process.env.npm_lifecycle_event === "test" ); } export function settingsPaths(cwd?: string): SettingsPaths { const effectiveCwd = cwd || process.cwd(); const home = process.env.HOME || process.env.USERPROFILE || ""; const agentDir = process.env.PI_CODING_AGENT_DIR || process.env.PI_CONFIG_DIR || path.join(home, ".pi", "agent"); return { globalPath: path.join(agentDir, "settings.json"), localPath: path.join(effectiveCwd, ".pi", "settings.json"), }; } export function normalizeStoredStyle(raw: unknown): string | undefined { if (typeof raw !== "string") return undefined; const key = raw.toLowerCase().trim(); if (OFF_STYLES.has(key)) return "off"; if (key in STYLE_ALIASES) return STYLE_ALIASES[key]; return (VALID_STYLES as readonly string[]).includes(key) ? key : undefined; } interface BeautifierBlock { hasKey: boolean; style?: string; fullFooter?: boolean; custom?: CustomStyleConfig; } function readBeautifierBlock(filePath: string): BeautifierBlock { const empty: BeautifierBlock = { hasKey: false }; try { if (!fs.existsSync(filePath)) return empty; const data = JSON.parse(fs.readFileSync(filePath, "utf-8")) as { beautifier?: unknown }; const block = data?.beautifier as Record | undefined; if (!block || typeof block !== "object" || Array.isArray(block)) return empty; const result: BeautifierBlock = { hasKey: true }; const style = normalizeStoredStyle(block.style); if (style) result.style = style; if (typeof block.fullFooter === "boolean") result.fullFooter = block.fullFooter; if (block.custom && typeof block.custom === "object" && !Array.isArray(block.custom)) { result.custom = block.custom as CustomStyleConfig; } return result; } catch { return empty; } } export function loadConfig(cwd?: string): ResolvedConfig { const { globalPath, localPath } = settingsPaths(cwd); const skipGlobal = isTestEnvironment() && cwd === undefined; let style = "claude"; let fullFooter = false; let custom: CustomStyleConfig | undefined; if (!skipGlobal) { const global = readBeautifierBlock(globalPath); if (global.style) style = global.style; if (global.fullFooter !== undefined) fullFooter = global.fullFooter; if (global.custom) custom = global.custom; } const local = readBeautifierBlock(localPath); if (local.style) style = local.style; if (local.fullFooter !== undefined) fullFooter = local.fullFooter; if (local.custom) custom = { ...(custom || {}), ...local.custom }; // Write to project-local settings only if this project already opted into `beautifier`. const targetSettingsPath = local.hasKey ? localPath : globalPath; return { style, fullFooter, custom, targetSettingsPath, hasLocalOverride: local.hasKey }; } export function sanitizeCustomConfig(raw: unknown): CustomStyleConfig | undefined { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined; const obj = raw as Record; // Clamp by code point so surrogate pairs (emoji) are never bisected into U+FFFD. const clampStr = (v: unknown, maxLen = 16): string | undefined => typeof v === "string" ? [...v].slice(0, maxLen).join("") : undefined; const brackets = Array.isArray(obj.brackets) && obj.brackets.length === 2 && typeof obj.brackets[0] === "string" && typeof obj.brackets[1] === "string" ? ([[...obj.brackets[0]].slice(0, 4).join(""), [...obj.brackets[1]].slice(0, 4).join("")] as [ string, string, ]) : undefined; const rawGlyphs = obj.glyphs && typeof obj.glyphs === "object" && !Array.isArray(obj.glyphs) ? (obj.glyphs as Record) : undefined; const glyphs = rawGlyphs ? { success: clampStr(rawGlyphs.success, 4), warning: clampStr(rawGlyphs.warning, 4), error: clampStr(rawGlyphs.error, 4), accent: clampStr(rawGlyphs.accent, 4), } : undefined; return { prefix: clampStr(obj.prefix, 16), suffix: clampStr(obj.suffix, 16), separator: clampStr(obj.separator, 12), brackets, inverse: typeof obj.inverse === "boolean" ? obj.inverse : undefined, padName: typeof obj.padName === "boolean" ? obj.padName : undefined, showTokens: typeof obj.showTokens === "boolean" ? obj.showTokens : undefined, showCost: typeof obj.showCost === "boolean" ? obj.showCost : undefined, glyphs, }; } export function resolveActivePreset( style: string, customCfg?: CustomStyleConfig, customFallback?: CustomStyleConfig, presetFallback: BuiltinStyleName = "claude" ): { styleKey: string; preset: CustomStyleConfig } { const styleKey = resolveStyleKey(style); const preset = styleKey === "custom" ? sanitizeCustomConfig(customCfg) || sanitizeCustomConfig(customFallback) || {} : getPreset(styleKey, undefined, presetFallback); return { styleKey, preset }; } function atomicWriteJson(filePath: string, value: unknown): void { fs.mkdirSync(path.dirname(filePath), { recursive: true }); const tempPath = `${filePath}.tmp.${process.pid}.${Date.now()}`; try { fs.writeFileSync(tempPath, JSON.stringify(value, null, 2), "utf-8"); try { fs.renameSync(tempPath, filePath); } catch { // Windows refuses renameSync over locked files; overwrite in place so existing JSON survives. fs.copyFileSync(tempPath, filePath); } } finally { try { if (fs.existsSync(tempPath)) fs.unlinkSync(tempPath); } catch { // Best-effort temp cleanup } } } export function writeBeautifierSettings( targetPath: string, style: string, fullFooter: boolean, custom?: CustomStyleConfig ): void { let config: Record = {}; if (fs.existsSync(targetPath)) { const parsed = JSON.parse(fs.readFileSync(targetPath, "utf-8")) as unknown; if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) { config = parsed as Record; } } const prev = config.beautifier && typeof config.beautifier === "object" && !Array.isArray(config.beautifier) ? (config.beautifier as Record) : {}; const next: Record = { ...prev, style, fullFooter }; if (custom !== undefined) next.custom = custom; config.beautifier = next; atomicWriteJson(targetPath, config); } export function removeBeautifierSettings(cwd?: string): { removed: string[]; errors: string[] } { const { globalPath, localPath } = settingsPaths(cwd); const removed: string[] = []; const errors: string[] = []; const targets = localPath === globalPath ? [localPath] : [localPath, globalPath]; for (const filePath of targets) { try { if (!fs.existsSync(filePath)) continue; const config = JSON.parse(fs.readFileSync(filePath, "utf-8")) as Record; if (!config || typeof config !== "object" || !("beautifier" in config)) continue; delete config.beautifier; atomicWriteJson(filePath, config); removed.push(filePath); } catch (error) { errors.push(`${filePath}: ${error instanceof Error ? error.message : String(error)}`); } } return { removed, errors }; }