import { existsSync } from "node:fs"; import type { ExtensionAPI, ExtensionContext, } from "@earendil-works/pi-coding-agent"; import type { AutocompleteItem } from "@earendil-works/pi-tui"; import { LoopController, PROMPT_TYPE, type PromptDetails, parseBudgets, shortId, } from "./controller.ts"; import { dbg } from "./debug.ts"; import { errorMessage, type GatePass, gateLabel, parseGates } from "./gates.ts"; import { GUIDE_TYPE, guidePrompt, registerLoopBegin, registerLoopControl, stateFileUnignored, } from "./guide.ts"; import { ICON } from "./icons.ts"; import { openUrl } from "./pi-ext-browser-open.ts"; import { resolveSetting } from "./pi-ext-settings.ts"; import { renderLoopPrompt } from "./render.ts"; import { DEFAULT_STATE_PATH, resolveKitten, STATE_PATH_SETTING, statePathFor, } from "./settings.ts"; import { type Budgets, LoopStore, type RunRecord } from "./store.ts"; import { createLoopWidget } from "./widget.ts"; type Site = { url: string; close(): Promise }; export const SUBCOMMANDS = [ [ "start", "Start a run: [minutes turns attempts], then goal and gates editors", ], [ "guide", "Brainstorm goal and gates with the agent: [minutes turns attempts]", ], ["resume", "Re-arm a paused run: "], ["pause", "Pause the active run"], ["stop", "Stop the active run or a paused run: [id|latest]"], ["status", "Show the active or latest run"], ["view", "Open the local observation site"], ["vixen", "Toggle animation: [on|off]; status always remains visible"], ["list", "List persisted runs"], ["recover", "Offline legacy recovery: ; stop all old Pi instances first"], ] as const; const GATES_TEMPLATE = `[ { "name": "tests", "command": "npm", "args": ["test"] } ]`; const WATCHDOG_MS = 2_000; const PROGRESS = "loop-progress"; const USER_STOP = /^(stop|pause)(\s|[.!]|$)/iu; const resumable = (run: RunRecord) => run.status === "paused" || run.status === "active"; function formatBudget(used: number, limit: number | null) { return limit === null ? `${used}` : `${used}/${limit}`; } export function describeRun(run: RunRecord): string { const firstLine = (run.goal.split("\n", 1)[0] ?? "").slice(0, 80); return `${shortId(run.id)} ${run.status} · attempts ${formatBudget(run.attempts, run.budgets.attempts)} · turns ${formatBudget(run.turns, run.budgets.turns)} · ${firstLine}`; } export type LoopRuntime = { /** Open the project store and controller on first use. */ open(ctx: ExtensionContext): Promise; /** Begin the baseline pass and loop for the run just started or resumed. */ launch( ctx: ExtensionContext, toolSignal?: AbortSignal, ): Promise; busy(): boolean; owns(loop: LoopController): boolean; /** The armed /loop guide session, if any. */ guided(): { budgets: Budgets; cwd: string } | undefined; disarm(): void; /** Pause the active run from inside an agent turn without aborting that turn. */ pauseRun(reason: string): void; /** The paused run to resume: this session's run first, else the newest paused one. */ pausedRun(loop: LoopController): RunRecord; }; export function registerLoop(pi: ExtensionAPI): void { let controller: LoopController | undefined; let opening: Promise | undefined; let sessionCtx: ExtensionContext | undefined; let statePath: string | undefined; let ui: ExtensionContext["ui"] | undefined; let lastStatus: string | undefined; let timer: ReturnType | undefined; let watchdog: ReturnType | undefined; let starting: AbortController | undefined; let generation = 0; let guided: { budgets: Budgets; cwd: string } | undefined; let site: Promise | undefined; let tui = false; let vixen = true; let kitten: boolean | undefined; let mountedVixen = true; let progress = false; let widget: ReturnType | undefined; let baseline = false; let agentRunning = false; const resolvePath = (ctx: ExtensionContext) => { const setting = resolveSetting(pi, ctx, STATE_PATH_SETTING); if (setting.ok) return statePathFor(ctx.cwd, setting.value); ctx.ui.notify( `loop: invalid ${STATE_PATH_SETTING.key} (${setting.source}): ${setting.error}; using ${DEFAULT_STATE_PATH}`, "warning", ); return statePathFor(ctx.cwd, DEFAULT_STATE_PATH); }; const showStatus = () => { const run = controller?.status(); const wanted = tui && !!run; if (wanted !== progress || (wanted && vixen !== mountedVixen)) { progress = wanted; mountedVixen = vixen; ui?.setWidget( PROGRESS, wanted ? (host, theme) => (widget = createLoopWidget( host, theme, () => ({ run: controller?.status() ?? null, baseline, agentRunning, vixen, }), kitten ?? true, )) : undefined, { placement: "aboveEditor" }, ); } widget?.invalidate(); const transition = run ? `${run.id}:${run.status}` : undefined; if (run && transition !== lastStatus && lastStatus?.startsWith(run.id)) { if (run.status === "succeeded") ui?.notify( `${ICON.succeeded} Loop ${shortId(run.id)} succeeded: every gate exited 0`, "info", ); if (run.status === "paused") ui?.notify( `${ICON.paused} Loop ${shortId(run.id)} paused: ${run.reason}`, "warning", ); if ( run.status === "succeeded" || run.status === "paused" || run.status === "stopped" ) dbg?.("run.end", { outcome: run.status, attempt: run.attempts, turns: run.turns, }); } lastStatus = transition; }; const open = async (ctx: ExtensionContext) => { ui = ctx.ui; tui = ctx.mode === "tui"; if (controller) return controller; kitten ??= resolveKitten(pi, ctx); const owner = generation; opening ??= (async () => { statePath ??= resolvePath(ctx); const store = await LoopStore.open(statePath); if (generation !== owner) { store.close(); throw new Error("Loop session changed while opening state"); } const created = new LoopController( store, Date.now, undefined, ctx.sessionManager.getSessionId(), ); created.subscribe(() => { if (controller === created) showStatus(); }); controller = created; return created; })(); const pending = opening; try { return await pending; } finally { if (opening === pending) opening = undefined; } }; const clear = () => { baseline = false; clearTimeout(timer); clearInterval(watchdog); timer = undefined; watchdog = undefined; }; const invalidate = () => { generation++; starting?.abort(); starting = undefined; }; const pause = ( reason: string, ctx?: ExtensionContext, status: "paused" | "stopped" = "paused", ) => { clear(); invalidate(); controller?.interrupt(reason, status); ctx?.abort(); }; const kick = (ctx: ExtensionContext, owner: number) => { if (generation !== owner) return; if (!controller?.active) { clear(); return; } if (controller.pending) return; if (ctx.isIdle() && !ctx.hasPendingMessages()) { const prompt = controller.prompt(); pi.sendMessage( { customType: PROMPT_TYPE, display: true, ...prompt }, { triggerTurn: true }, ); } }; /** * Run the baseline pass, then keep the loop going. From a command the agent is idle and * Escape cancels; from a tool the agent's own signal cancels and its turn continues. */ const launch = async ( ctx: ExtensionContext, toolSignal?: AbortSignal, ): Promise => { const loop = controller; const run = loop?.status(); if (!loop || !run) return undefined; const owner = ++generation; const setup = new AbortController(); if (!toolSignal) starting = setup; const signal = toolSignal ? AbortSignal.any([setup.signal, toolSignal]) : setup.signal; clear(); baseline = true; dbg?.("run.start", { gateCount: run.gates.length, outcome: "active" }); if (run.deadline !== null) { timer = setTimeout( () => { if (generation === owner) pause("Time budget exhausted", ctx); }, Math.max(1, run.deadline - Date.now()), ); timer.unref(); } let removeEscape: (() => void) | undefined; try { // Idle command work has no agent signal; Escape owns the baseline only. if (ctx.mode === "tui" && !toolSignal) { const { matchesKey } = await import("@earendil-works/pi-tui"); if (generation !== owner) return undefined; removeEscape = ctx.ui.onTerminalInput((data) => { if ( generation !== owner || signal.aborted || !matchesKey(data, "escape") ) return undefined; pause("Escape pressed during baseline", ctx); return { consume: true }; }); } let pass: GatePass; try { pass = await loop.checkGates(signal); } catch (error) { if (toolSignal) throw error; if (generation === owner && !signal.aborted) { pause(`Baseline failed: ${errorMessage(error)}`); ctx.ui.notify( `Loop baseline failed: ${errorMessage(error)}`, "error", ); } return undefined; } if (generation !== owner || signal.aborted) return pass; if (!loop.active) { clear(); return pass; } starting = undefined; watchdog = setInterval(() => kick(ctx, owner), WATCHDOG_MS); watchdog.unref(); kick(ctx, owner); return pass; } finally { removeEscape?.(); if (generation === owner && starting === setup) starting = undefined; if (generation === owner && controller === loop) { baseline = false; showStatus(); } } }; // Command dispatch awaits handlers, so baseline must not occupy its queue. const background = (ctx: ExtensionContext) => { const owner = controller; void launch(ctx).catch((error) => { if (controller === owner) ctx.ui.notify(`Loop baseline failed: ${errorMessage(error)}`, "error"); }); }; const recoveryNotice = (run: RunRecord) => `Loop ${run.id} ${run.status}\nOwnership: ${controller?.store.ownership(run.id) ?? "unknown"}\nLast activity: ${new Date(run.updatedAt).toISOString()}\n${run.reason}\nResume: /loop resume ${run.id}\nStop: /loop stop ${run.id}\nInspect: /loop status | /loop view`; const requireIdle = (ctx: ExtensionContext) => { if (!ctx.isIdle() || starting || controller?.active) throw new Error( "Loop commands that start work need an idle agent and no active run", ); }; const findRun = (loop: LoopController, ref: string | undefined) => { if (!ref || ref === "latest") { const run = loop.store.listRuns(200).find(resumable); if (!run) throw new Error("No paused run to use"); return run; } const [match, other] = loop.store.listRuns(2, ref); if (!match) throw new Error(`No run ${ref}`); if (other) throw new Error(`Run id ${ref} is ambiguous`); return match; }; /** Resumable runs for completion; completion never creates the state file. */ const resumableRuns = async (): Promise => { try { let loop = controller; if (!loop && sessionCtx) { statePath ??= resolvePath(sessionCtx); if (existsSync(statePath)) loop = await open(sessionCtx); } return loop?.store.listRuns(20).filter(resumable) ?? []; } catch { return []; } }; const start = async (values: string[], ctx: ExtensionContext) => { requireIdle(ctx); const budgets = parseBudgets(values); if (!ctx.hasUI) throw new Error( "/loop start needs interactive Pi or an RPC client with extension UI", ); const owner = generation; const loop = await open(ctx); if (generation !== owner) return; const cwd = ctx.cwd; const goal = await ctx.ui.editor("Loop goal: what must be true when done?"); if (generation !== owner || !goal?.trim()) return; const raw = await ctx.ui.editor( "Loop gates: JSON array of { name?, command, args?, env?, cwd? }; every gate must exit 0", GATES_TEMPLATE, ); if (generation !== owner || !raw?.trim()) return; let gates: ReturnType; try { gates = parseGates(raw); } catch (error) { throw new Error(`Invalid gates: ${errorMessage(error)}`); } requireIdle(ctx); guided = undefined; loop.start({ goal, gates, cwd }, budgets); background(ctx); }; const status = (loop: LoopController) => { const live = loop.status(); const run = live ?? loop.store.listRuns(1)[0]; if (!run) return "No loop runs yet"; const pass = live?.lastPass ?? (() => { const rows = loop.store .attempts(run.id, 64) .filter((row) => row.attempt === run.attempts); return { results: rows }; })(); const gates = run.gates .map((gate, index) => { const result = pass?.results[index]; const mark = !result ? "·" : result.exitCode === 0 && !result.error ? "✓" : "✗"; return `${mark} ${gateLabel(gate)}`; }) .join(" "); const runningGate = live?.runningGate == null ? undefined : run.gates[live.runningGate]; const running = live?.runningGate == null || !runningGate ? "" : `\nRunning gate ${live.runningGate + 1}: ${gateLabel(runningGate)} · ${Math.max(0, Math.floor((Date.now() - (live.runningSince ?? Date.now())) / 1000))}s\n${JSON.stringify(live.liveOutput)}`; return `${describeRun(run)}\n${recoveryNotice(run)}\n${gates}${running}${live?.storageError ? `\nstate write failed: ${live.storageError}` : ""}`; }; pi.registerMessageRenderer(PROMPT_TYPE, renderLoopPrompt); pi.registerCommand("loop", { description: "Goal-gated agent loop: start|guide|resume|pause|stop|status|view|list|recover|vixen", getArgumentCompletions: async (prefix) => { const words = prefix.split(/\s+/u); const current = words.at(-1) ?? ""; const done = words.slice(0, -1); const item = (value: string, description?: string): AutocompleteItem => ({ value: [...done, value].join(" "), label: value, ...(description ? { description } : {}), }); if (done.length === 0) return SUBCOMMANDS.filter(([name]) => name.startsWith(current)).map( ([name, description]) => item(name, description), ); const [command] = done; if (command === "vixen" && done.length === 1) return ["on", "off"] .filter((value) => value.startsWith(current)) .map((value) => item(value)); if ((command === "start" || command === "guide") && done.length <= 3) return "none".startsWith(current) ? [item("none", "uncapped budget")] : null; if ((command === "resume" || command === "stop") && done.length === 1) { const runs = await resumableRuns(); return [ item("latest", "newest paused run"), ...runs.map((run) => item(shortId(run.id), describeRun(run))), ].filter((entry) => entry.label.startsWith(current)); } return null; }, handler: async (args, ctx) => { ui = ctx.ui; tui = ctx.mode === "tui"; const [action = "status", ...values] = args .trim() .split(/\s+/u) .filter(Boolean); const epoch = generation; const openCurrent = async () => { const loop = await open(ctx); if (generation !== epoch) throw new Error("Loop session changed; command cancelled"); return loop; }; switch (action) { case "vixen": { if ( values.length > 1 || (values[0] !== undefined && values[0] !== "on" && values[0] !== "off") ) throw new Error("Usage: /loop vixen [on|off]"); vixen = values[0] === undefined ? !vixen : values[0] === "on"; showStatus(); ctx.ui.notify( `Loop vixen ${vixen ? "on" : "off"} (current runtime)`, "info", ); return; } case "start": return start(values, ctx); case "guide": { requireIdle(ctx); const budgets = parseBudgets(values); const loop = await openCurrent(); const unignored = await stateFileUnignored(ctx.cwd, loop.store.path); if (generation !== epoch) return; guided = { budgets, cwd: ctx.cwd }; dbg?.("guide.arm", { outcome: "ok", guided: true }); pi.sendMessage( { customType: GUIDE_TYPE, content: guidePrompt( budgets, ctx.cwd, loop.store.path, unignored, ), display: true, }, { triggerTurn: true }, ); return; } case "resume": { requireIdle(ctx); const loop = await openCurrent(); loop.resume(findRun(loop, values[0])); dbg?.("run.resume", { outcome: "active" }); background(ctx); return; } case "recover": { requireIdle(ctx); if (!values[0]) throw new Error( "Use /loop recover after stopping every old Pi instance using this database", ); const loop = await openCurrent(); const run = findRun(loop, values[0]); if (!resumable(run)) throw new Error(`Run ${run.id} is ${run.status}; cannot recover`); const owner = generation; if ( !ctx.hasUI || !(await ctx.ui.confirm( "Offline legacy recovery", "Confirm every old Pi instance using this database is stopped. Old binaries cannot honor ownership locks. Recover paused, without executing gates?", )) ) return; if (generation !== owner) return; loop.store.recoverLegacy(run.id); ctx.ui.notify(recoveryNotice(loop.restore(run)), "warning"); return; } case "pause": case "stop": { if (controller?.active || starting) { pause( `User ${action}`, ctx, action === "stop" ? "stopped" : "paused", ); return; } if (guided && !values[0]) { guided = undefined; ctx.ui.notify("Loop guide disarmed", "info"); return; } if (action === "pause") { ctx.ui.notify("No active loop run", "info"); return; } const loop = await openCurrent(); const run = findRun(loop, values[0]); loop.stopRecord(run); ctx.ui.notify(`Loop ${shortId(run.id)} stopped`, "info"); return; } case "status": ctx.ui.notify(status(await openCurrent()), "info"); return; case "view": { const loop = await openCurrent(); if (!site) { const pending = import("../site.ts").then(({ startSite }) => startSite(loop), ); site = pending; pending.catch(() => { if (site === pending) site = undefined; }); } const { url } = await site; if (generation !== epoch) return; dbg?.("site.open", { outcome: "ok" }); if (ctx.mode === "tui") await openUrl(url, { timeoutMs: 5_000 }).catch(() => undefined); ctx.ui.notify(`Loop site: ${url}`, "info"); return; } case "list": { const runs = (await openCurrent()).store.listRuns(20); ctx.ui.notify( runs.length ? runs.map(describeRun).join("\n") : "No loop runs yet", "info", ); return; } default: throw new Error( `Usage: /loop ${SUBCOMMANDS.map(([name]) => name).join("|")}`, ); } }, }); pi.on("agent_start", () => { agentRunning = true; // An independent run during setup must not inherit an unchecked baseline. if (starting) pause("Another agent run started during loop setup"); showStatus(); }); pi.on("turn_start", (_event, ctx) => { if (controller?.active && !controller.turn()) { clear(); ctx.abort(); } }); // agent_end is awaited while Pi's abort signal is live; settlement only decides. pi.on("agent_end", async (_event, ctx) => { const loop = controller; const owner = loop?.status(); if ( !loop || !owner || owner.status !== "active" || ctx.hasPendingMessages() ) return; if (ctx.signal?.aborted) { pause("Agent aborted"); return; } const epoch = generation; try { await loop.checkGates(ctx.signal); } catch (error) { if (controller === loop && generation === epoch) loop.record("gate_error", { message: errorMessage(error) }); } if (controller === loop && generation === epoch && !loop.active) clear(); }); pi.on("agent_before_settle", (event, ctx) => { const result = controller?.settle(event, ctx.hasPendingMessages()); if (result?.continue) dbg?.("run.continue", { outcome: "active" }); if (controller && !controller.active) clear(); return result; }); pi.on("agent_settled", (event) => { agentRunning = false; if (event.aborted && controller?.active) pause("Agent aborted"); showStatus(); }); pi.on("input", (event, ctx) => { if ( event.source !== "extension" && (controller?.active || starting) && USER_STOP.test(event.text.trim()) ) pause("User stop", ctx); }); // Only the newest loop prompt keeps its gate output; older ones shrink to fixed stubs. pi.on("context", (event) => { let latest = -1; for (const [index, message] of event.messages.entries()) if (message.role === "custom" && message.customType === PROMPT_TYPE) latest = index; if (latest < 0) return undefined; let changed = false; const messages = event.messages.map((message, index) => { if ( index >= latest || message.role !== "custom" || message.customType !== PROMPT_TYPE ) return message; const stub = (message.details as Partial | undefined) ?.stub; if (typeof stub !== "string" || message.content === stub) return message; changed = true; return { ...message, content: stub }; }); return changed ? { messages } : undefined; }); const reset = async () => { const closing = site; site = undefined; void closing?.then((open) => open.close()).catch(() => undefined); clear(); invalidate(); const previous = controller; const released = previous?.release(); controller = undefined; opening = undefined; statePath = undefined; guided = undefined; ui?.setStatus("loop", undefined); widget?.dispose(); widget = undefined; if (progress) ui?.setWidget(PROGRESS, undefined); progress = false; kitten = undefined; agentRunning = false; lastStatus = undefined; await released; previous?.store.close(); }; const sessionChanged = () => pause("Session changed; never auto-resumed"); pi.on("session_before_switch", sessionChanged); pi.on("session_before_fork", sessionChanged); pi.on("session_before_tree", sessionChanged); pi.on("session_start", async (_event, ctx) => { await reset(); sessionCtx = ctx; ui = ctx.ui; tui = ctx.mode === "tui"; kitten = resolveKitten(pi, ctx); const owner = generation; const path = resolvePath(ctx); if (!existsSync(path)) return; try { const loop = await open(ctx); if (generation !== owner) return; const run = loop.store.sessionRun(ctx.sessionManager.getSessionId()); if (run && resumable(run)) { try { ctx.ui.notify(recoveryNotice(loop.restore(run)), "warning"); } catch (error) { ctx.ui.notify( `${recoveryNotice(run)}\n${errorMessage(error)}`, "warning", ); } } else { const other = loop.store.listRuns(20).find(resumable); if (other) ctx.ui.notify( `Run from another or legacy session; not attached.\n${recoveryNotice(other)}`, "warning", ); } } catch (error) { if (generation === owner) ctx.ui.notify(`Loop restore failed: ${errorMessage(error)}`, "error"); } }); pi.on("session_shutdown", async () => { pause("Session shutdown; never auto-resumed"); await reset(); sessionCtx = undefined; }); const runtime: LoopRuntime = { open, launch, busy: () => Boolean(starting) || Boolean(controller?.active), owns: (loop) => controller === loop, guided: () => guided, disarm: () => { guided = undefined; }, pauseRun: (reason) => pause(reason), pausedRun: (loop) => { const current = loop.status(); const record = current?.status === "paused" ? loop.store.getRun(current.id) : undefined; return record ?? findRun(loop, "latest"); }, }; registerLoopBegin(pi, runtime); registerLoopControl(pi, runtime); }