/** * Lightweight extension state persistence. * Stored under ~/.pi/agent/state/.json */ import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs"; import { join } from "node:path"; import { getAgentDir } from "@mariozechner/pi-coding-agent"; const STATE_DIR = join(getAgentDir(), "state"); function ensure(): void { if (!existsSync(STATE_DIR)) mkdirSync(STATE_DIR, { recursive: true }); } export function loadState(namespace: string, defaults: T): T { const path = join(STATE_DIR, `${namespace}.json`); try { if (!existsSync(path)) return defaults; const raw = readFileSync(path, "utf-8"); return { ...defaults, ...JSON.parse(raw) } as T; } catch { return defaults; } } export function saveState(namespace: string, state: T): void { ensure(); const path = join(STATE_DIR, `${namespace}.json`); try { writeFileSync(path, JSON.stringify(state, null, 2) + "\n", "utf-8"); } catch {} } export function updateState(namespace: string, updates: Partial): void { saveState(namespace, { ...loadState(namespace, {} as T), ...updates }); }