import { randomUUID } from "node:crypto"; import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; import { basename, dirname, join, resolve } from "node:path"; import lockfile from "proper-lockfile"; import { getAgentDir } from "@earendil-works/pi-coding-agent"; // Selesai: Store extension settings in the shared user document; retain the old path only for migration. export const GOAL_SETTINGS_FILE = "settings.json"; export const GOAL_SETTINGS_KEY = "goal"; export const LEGACY_GOAL_SETTINGS_FILE = "pi-goal.json"; export type ContinuationLimit = number | null; export interface GoalSettings { retryUsageLimits: boolean; rpc: { enabled: boolean; }; continuationLimits: { automaticTurns: ContinuationLimit; noProgressTurns: ContinuationLimit; }; } export const DEFAULT_GOAL_SETTINGS: GoalSettings = { // Selesai: Retry provider usage limits by default; an explicit false still disables recovery. retryUsageLimits: true, rpc: { enabled: false }, continuationLimits: { automaticTurns: 25, noProgressTurns: 3 }, }; export type GoalSettingsLoadResult = | { kind: "missing"; legacyExperimentalGoals: false } | { kind: "invalid"; reason: string } | { kind: "loaded"; settings: GoalSettings; legacyExperimentalGoals: boolean }; export type GoalSettingsLoadIssue = Extract; interface GoalSettingsSaveFileSystem { mkdirSync: typeof mkdirSync; writeFileSync: typeof writeFileSync; renameSync: typeof renameSync; rmSync: typeof rmSync; } export function normalizeGoalSettings(value: unknown): GoalSettings | undefined { if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined; const retryUsageLimits = Object.hasOwn(value, "retryUsageLimits") ? Reflect.get(value, "retryUsageLimits") : DEFAULT_GOAL_SETTINGS.retryUsageLimits; if (typeof retryUsageLimits !== "boolean") return undefined; const rpcValue = Object.hasOwn(value, "rpc") ? Reflect.get(value, "rpc") : undefined; if (rpcValue !== undefined && (typeof rpcValue !== "object" || rpcValue === null || Array.isArray(rpcValue))) { return undefined; } const rpcEnabled = rpcValue && Object.hasOwn(rpcValue, "enabled") ? Reflect.get(rpcValue, "enabled") : DEFAULT_GOAL_SETTINGS.rpc.enabled; if (typeof rpcEnabled !== "boolean") return undefined; const continuationLimitsValue = Object.hasOwn(value, "continuationLimits") ? Reflect.get(value, "continuationLimits") : undefined; if ( continuationLimitsValue !== undefined && (typeof continuationLimitsValue !== "object" || continuationLimitsValue === null || Array.isArray(continuationLimitsValue)) ) { return undefined; } const automaticTurns = continuationLimitsValue ? normalizeContinuationLimit( Reflect.get(continuationLimitsValue, "automaticTurns"), DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns, ) : DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns; const noProgressTurns = continuationLimitsValue ? normalizeContinuationLimit( Reflect.get(continuationLimitsValue, "noProgressTurns"), DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns, ) : DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns; if (automaticTurns === undefined || noProgressTurns === undefined) return undefined; return { retryUsageLimits, rpc: { enabled: rpcEnabled }, continuationLimits: { automaticTurns, noProgressTurns }, }; } function normalizeContinuationLimit(value: unknown, fallback: ContinuationLimit): ContinuationLimit | undefined { if (value === undefined) return fallback; if (value === null) return null; return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined; } export function saveGoalSettings( settings: GoalSettings, settingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE), overrides: Partial = {}, ) { const normalized = normalizeGoalSettings(settings); if (!normalized) throw new Error("Refusing to save invalid pi-goal settings."); // Selesai: Serialize read/merge/write with the host's settings lock, preserving unrelated keys. withSettingsLock(settingsPath, () => { const document = readSettingsDocument(settingsPath); const existing = document[GOAL_SETTINGS_KEY]; if (Object.hasOwn(document, GOAL_SETTINGS_KEY) && !normalizeGoalSettings(existing)) { throw new Error(`Cannot save invalid settings file: ${settingsPath}: invalid settings shape`); } const raw = ownRecord(existing) ?? {}; const rpc = ownRecord(raw.rpc) ?? {}; const continuationLimits = ownRecord(raw.continuationLimits) ?? {}; document[GOAL_SETTINGS_KEY] = { ...raw, retryUsageLimits: normalized.retryUsageLimits, rpc: { ...rpc, enabled: normalized.rpc.enabled }, continuationLimits: { ...continuationLimits, automaticTurns: normalized.continuationLimits.automaticTurns, noProgressTurns: normalized.continuationLimits.noProgressTurns, }, }; writeSettingsDocument(settingsPath, document, overrides); }); } // Selesai: Match the host's proper-lockfile contention policy (10 attempts, 20 ms, ELOCKED only). function withSettingsLock(settingsPath: string, action: () => T): T { mkdirSync(dirname(settingsPath), { recursive: true }); let release: (() => void) | undefined; for (let attempt = 1; attempt <= 10; attempt++) { try { release = lockfile.lockSync(settingsPath, { realpath: false }); break; } catch (error) { if (!isNodeError(error) || error.code !== "ELOCKED" || attempt === 10) throw error; const start = Date.now(); while (Date.now() - start < 20) { // Sleep synchronously, as the host does. } } } try { return action(); } finally { release?.(); } } // Selesai: Reject malformed shared documents rather than overwriting host settings. function readSettingsDocument(settingsPath: string): Record { try { const parsed = ownRecord(JSON.parse(readFileSync(settingsPath, "utf8"))); if (!parsed) throw new Error("invalid settings shape"); return parsed; } catch (error) { if (isNodeError(error) && error.code === "ENOENT") return {}; throw new Error(`Cannot save invalid settings file: ${settingsPath}: ${formatError(error)}`); } } // Selesai: Atomic shared-document writes keep the existing injectable failure seam. function writeSettingsDocument( settingsPath: string, document: Record, overrides: Partial = {}, ) { const fs = { mkdirSync, writeFileSync, renameSync, rmSync, ...overrides }; const temporaryPath = join(dirname(settingsPath), `.${basename(settingsPath)}.${randomUUID()}.tmp`); try { fs.mkdirSync(dirname(settingsPath), { recursive: true }); fs.writeFileSync(temporaryPath, `${JSON.stringify(document, null, 2)}\n`, { encoding: "utf8", flag: "wx" }); fs.renameSync(temporaryPath, settingsPath); } finally { try { fs.rmSync(temporaryPath, { force: true }); } catch { // Best-effort cleanup must not replace the save result. } } } // Selesai: Only the goal key belongs to this extension; absence means defaults, not invalidity. export function readGoalSettings(settingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE)): GoalSettingsLoadResult { try { const parsed = ownRecord(JSON.parse(readFileSync(settingsPath, "utf8"))); if (!parsed) return { kind: "invalid", reason: `${settingsPath}: invalid settings shape` }; if (!Object.hasOwn(parsed, GOAL_SETTINGS_KEY)) return { kind: "missing", legacyExperimentalGoals: false }; const raw = parsed[GOAL_SETTINGS_KEY]; const settings = normalizeGoalSettings(raw); return settings ? { kind: "loaded", settings, legacyExperimentalGoals: hasLegacyExperimentalGoals(raw) } : { kind: "invalid", reason: `${settingsPath}: invalid settings shape` }; } catch (error: unknown) { if (isNodeError(error) && error.code === "ENOENT") return { kind: "missing", legacyExperimentalGoals: false }; return { kind: "invalid", reason: `${settingsPath}: ${formatError(error)}` }; } } // Selesai: An injected shared path also isolates the default legacy path from the real agent directory. export function migrateGoalSettings( settingsPath = join(getAgentDir(), GOAL_SETTINGS_FILE), legacySettingsPath = join(dirname(settingsPath), LEGACY_GOAL_SETTINGS_FILE), // Selesai: Reuse the save failure seam to verify atomic migration failures safely. overrides: Partial = {}, ): { message: string; level: "info" | "warning" } | undefined { // Selesai: Never migrate a shared document into itself and then delete it. if (resolve(settingsPath) === resolve(legacySettingsPath)) return undefined; try { let raw: unknown; try { raw = JSON.parse(readFileSync(legacySettingsPath, "utf8")); } catch (error) { if (isNodeError(error) && error.code === "ENOENT") return undefined; throw error; } if (!normalizeGoalSettings(raw)) throw new Error("invalid legacy settings shape"); withSettingsLock(settingsPath, () => { const document = readSettingsDocument(settingsPath); // An existing goal key wins; leave the shared document untouched then. if (!Object.hasOwn(document, GOAL_SETTINGS_KEY)) { document[GOAL_SETTINGS_KEY] = raw; writeSettingsDocument(settingsPath, document, overrides); } // Delete only after the shared document has been persisted successfully. rmSync(legacySettingsPath, { force: true }); }); return { message: "pi-goal settings moved to settings.json (goal)", level: "info" }; } catch (error) { return { message: `pi-goal settings migration failed: ${legacySettingsPath} -> ${settingsPath}: ${formatError(error)}`, level: "warning", }; } } function hasLegacyExperimentalGoals(value: unknown) { const experimental = ownRecord(ownRecord(value)?.experimental); return experimental?.goals === true; } function ownRecord(value: unknown): Record | undefined { return value && typeof value === "object" && !Array.isArray(value) ? (value as Record) : undefined; } function isNodeError(error: unknown): error is NodeJS.ErrnoException { return error instanceof Error && "code" in error; } function formatError(error: unknown) { return error instanceof Error ? error.message : String(error); }