repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by bugabinga
pi/agent/lib/state.ts
Raw/**
* Lightweight extension state persistence.
* Stored under ~/.pi/agent/state/<namespace>.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<T>(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<T extends object>(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<T extends object>(namespace: string, updates: Partial<T>): void {
saveState(namespace, { ...loadState(namespace, {} as T), ...updates });
}