import { execFile } from "node:child_process"; import { relative } from "node:path"; import { promisify } from "node:util"; import { StringEnum } from "@earendil-works/pi-ai"; import { type AgentToolResult, defineTool, type ExtensionAPI, keyHint, type Theme, type ToolRenderResultOptions, } from "@earendil-works/pi-coding-agent"; import { stripTerminalSequences, Text } from "@earendil-works/pi-tui"; import { Type } from "typebox"; import { shortId } from "./controller.ts"; import { dbg } from "./debug.ts"; import { gateLabel, MAX_GATES, parseGates } from "./gates.ts"; import { ICON } from "./icons.ts"; import type { LoopRuntime } from "./loop.ts"; import type { Budgets } from "./store.ts"; export const GUIDE_TYPE = "loop-guide"; const execFileAsync = promisify(execFile); function budgetText(budgets: Budgets): string { const value = (n: number | null, unit: string) => n === null ? `uncapped ${unit}` : `${n} ${unit}`; return `${value(budgets.minutes, "minutes")}, ${value(budgets.turns, "turns")}, ${value(budgets.attempts, "attempts")}`; } /** True only when a complete Git probe confirms the default state file is not ignored. */ export async function stateFileUnignored( cwd: string, statePath: string, ): Promise { const inside = relative(cwd, statePath); if (inside.startsWith("..") || inside === statePath) return false; try { // Node enforces the per-stream cap on Pi 1.4 too; pi.exec does not. await execFileAsync("git", ["check-ignore", "-q", "--", inside], { cwd, timeout: 5_000, maxBuffer: 16 * 1024, killSignal: "SIGKILL", windowsHide: true, }); return false; } catch (error) { // 0 ignored, 1 not ignored, 128 not a repository; overflow has a string code. const result = error as { code?: unknown; killed?: boolean }; return !result.killed && result.code === 1; } } export function guidePrompt( budgets: Budgets, cwd: string, statePath: string, unignored: boolean, ): string { return [ "Loop guide: help the user set up a goal-gated loop run for this project, then start it with loop_begin.", "1. Interview the user briefly, one focused question at a time, until the goal states what must be true when done.", "2. Derive gates from project context: instructions such as AGENTS.md, the task runner surface (for example mise tasks, package scripts, Makefile, justfile), and repository shape. Use the project's own public automation and style.", "3. Each gate is a raw executable with args and optional env and cwd; no shell is implied. Every gate must exit 0 when the goal is met and should fail now. Prefer few, fast, decisive gates, cheapest first.", "4. Show the goal and gates to the user, adjust on feedback, then call loop_begin once. Do not redefine gates later to manufacture a pass.", `Working directory: ${cwd}. Budgets: ${budgetText(budgets)}.`, ...(unignored ? [ `Loop state is stored in ${relative(cwd, statePath)}, which Git does not ignore. It records gate output; ask whether to add it to .gitignore or commit run history deliberately.`, ] : []), ].join("\n"); } /** Compact first sentence of a loop tool result; the rest needs native expansion. */ function renderOutcome(running: string) { return ( result: AgentToolResult, { expanded, isPartial }: ToolRenderResultOptions, theme: Theme, context: { isError: boolean; keyHint?: typeof keyHint }, ): Text => { if (isPartial) return new Text(theme.fg("warning", running), 0, 0); const text = result.content .flatMap((part) => (part.type === "text" ? [part.text] : [])) .join("\n"); const first = text.split(". ", 1)[0] ?? text; const body = theme.fg( context.isError ? "error" : "toolOutput", stripTerminalSequences(expanded ? text : first), ); return new Text( expanded || first === text ? body : `${body} ${(context.keyHint ?? keyHint)("app.tools.expand", "to expand")}`, 0, 0, ); }; } const gateSchema = Type.Object( { name: Type.Optional(Type.String({ description: "Short label" })), command: Type.String({ description: "Executable; no shell" }), args: Type.Optional(Type.Array(Type.String())), env: Type.Optional(Type.Record(Type.String(), Type.String())), cwd: Type.Optional( Type.String({ description: "Relative to the run directory" }), ), }, { additionalProperties: false }, ); export function registerLoopBegin( pi: ExtensionAPI, runtime: LoopRuntime, ): void { pi.registerTool( defineTool({ name: "loop_begin", label: "loop begin", exposure: "model-only", description: "Start the goal-gated loop agreed during /loop guide: runs the baseline gate pass, then Pi keeps prompting until every gate exits 0. Only available while /loop guide is armed.", parameters: Type.Object({ goal: Type.String({ description: "What must be true when done" }), gates: Type.Array(gateSchema, { minItems: 1, maxItems: MAX_GATES }), }), async execute(_id, params, signal, _onUpdate, ctx) { const armed = runtime.guided(); if (!armed) { dbg?.("guide.arm", { outcome: "rejected" }); throw new Error( "loop_begin is only available after the user runs /loop guide", ); } const gates = parseGates(params.gates); const loop = await runtime.open(ctx); if ( !runtime.owns(loop) || runtime.guided() !== armed || signal?.aborted ) throw new Error("Loop session changed or setup cancelled"); const run = loop.start( { goal: params.goal, gates, cwd: armed.cwd }, armed.budgets, ); runtime.disarm(); const pass = await runtime.launch(ctx, signal); const status = loop.status() ?? run; const failed = pass && pass.failedIndex !== null ? pass.results[pass.failedIndex] : undefined; const failedGate = pass && pass.failedIndex !== null ? gates[pass.failedIndex] : undefined; const summary = status.status === "succeeded" ? "Baseline passed: every gate exited 0; the run succeeded." : failed && failedGate ? `Baseline attempt ${pass?.attempt}: gate "${gateLabel(failedGate)}" failed (exit ${failed.exitCode ?? "none"}${failed.error ? `, ${failed.error}` : ""}). The loop is active; keep working toward the goal.` : `Run is ${status.status}: ${status.reason}.`; return { content: [ { type: "text", text: `Loop run ${shortId(run.id)} ${status.status}. ${summary}`, }, ], details: { runId: run.id, status: status.status, gates: gates.map(gateLabel), failedIndex: pass?.failedIndex ?? null, }, }; }, renderCall(args, theme, context) { const goal = typeof args?.goal === "string" ? args.goal : ""; const title = theme.fg( "toolTitle", `${ICON.begin} loop begin ${stripTerminalSequences(goal.split("\n", 1)[0] ?? "").slice(0, 60)}`, ); const gates = Array.isArray(args?.gates) ? args.gates : []; return new Text( context.expanded ? `${title}\n${stripTerminalSequences(goal)}\n${gates .map( (gate, index) => `${index + 1}. ${stripTerminalSequences(JSON.stringify(gate))}`, ) .join("\n")}` : `${title} · ${gates.length} gate(s) ${(context.keyHint ?? keyHint)("app.tools.expand", "to expand")}`, 0, 0, ); }, renderResult: renderOutcome("… running baseline gates"), }), ); } /** Lets the agent pause a blocked run, talk with the human, and resume it. */ export function registerLoopControl( pi: ExtensionAPI, runtime: LoopRuntime, ): void { pi.registerTool( defineTool({ name: "loop_control", label: "loop control", exposure: "model-only", description: "Pause the active goal-gated loop when truly blocked on the human, or resume the paused loop once unblocked. Resume reruns the gates before looping again.", parameters: Type.Object({ action: StringEnum(["pause", "resume"] as const), reason: Type.Optional( Type.String({ description: "Pause only: what you need from the human", }), ), }), async execute(_id, params, signal, _onUpdate, ctx) { const loop = await runtime.open(ctx); if (!runtime.owns(loop) || signal?.aborted) throw new Error("Loop session changed or control cancelled"); if (params.action === "pause") { const run = loop.status(); if (!run || !loop.active) throw new Error("No active loop run to pause"); const reason = params.reason?.trim() || "blocked"; runtime.pauseRun(`Agent paused: ${reason.slice(0, 500)}`); return { content: [ { type: "text", text: `Loop run ${shortId(run.id)} paused. Tell the human what you need; resume with loop_control once unblocked.`, }, ], details: { runId: run.id, status: "paused" }, }; } if (runtime.busy()) throw new Error("A loop run is already active"); const record = runtime.pausedRun(loop); loop.resume(record); dbg?.("run.resume", { outcome: "active" }); const pass = await runtime.launch(ctx, signal); const status = loop.status(); const failed = pass && pass.failedIndex !== null ? record.gates[pass.failedIndex] : undefined; return { content: [ { type: "text", text: `Loop run ${shortId(record.id)} ${status?.status ?? "resumed"}. ${ status?.status === "succeeded" ? "Every gate exited 0." : failed ? `Gate "${gateLabel(failed)}" still fails; keep working toward the goal.` : (status?.reason ?? "") }`, }, ], details: { runId: record.id, status: status?.status ?? null }, }; }, renderCall(args, theme) { const reason = args?.action === "pause" && typeof args.reason === "string" ? ` ${stripTerminalSequences(args.reason).slice(0, 60)}` : ""; return new Text( theme.fg( "toolTitle", `${args?.action === "pause" ? ICON.paused : args?.action === "resume" ? ICON.resume : ICON.loop} loop ${args?.action ?? "control"}${reason}`, ), 0, 0, ); }, renderResult: renderOutcome("… running gates"), }), ); }