import { existsSync, readFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; function looksLikeAgentDir(dir: string): boolean { return ( existsSync(join(dir, "settings.json")) && (existsSync(join(dir, "packages")) || existsSync(join(dir, "rules")) || existsSync(join(dir, "themes")) || existsSync(join(dir, "auth.json"))) ); } function findAgentDirFrom(startDir: string): string | null { let current = resolve(startDir); while (true) { if (looksLikeAgentDir(current)) return current; const parent = dirname(current); if (parent === current) return null; current = parent; } } export function getAgentDir(): string { const envDir = process.env.PI_AGENT_DIR; if (envDir && looksLikeAgentDir(resolve(envDir))) { return resolve(envDir); } const moduleDir = dirname(fileURLToPath(import.meta.url)); const discovered = findAgentDirFrom(moduleDir); if (discovered) return discovered; const home = process.env.HOME; if (home) { const fallback = join(home, ".pi", "agent"); if (looksLikeAgentDir(fallback)) return fallback; } throw new Error("Unable to resolve Pi agent directory"); } export function getAgentPath(...segments: string[]): string { return join(getAgentDir(), ...segments); } export function readJsonFile(path: string, fallback: T): T { try { if (!existsSync(path)) return fallback; return JSON.parse(readFileSync(path, "utf8")) as T; } catch { return fallback; } }