repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/loop/src/loop.ts
RawFile outline
- Site line 35
- SUBCOMMANDS line 37
- GATES_TEMPLATE line 54
- WATCHDOG_MS line 57
- COMPANION line 58
- USER_STOP line 59
- resumable line 61
- formatBudget line 64
- describeRun line 68
- LoopRuntime line 73
- registerLoop line 91
- budgets line 102
- cwd line 102
- resolvePath line 107
- showStatus line 117
- companionState line 162
- open line 190
- clear line 209
- invalidate line 215
- pause line 220
- kick line 231
- launch line 251
- requireIdle line 314
- findRun line 321
- resumableRuns line 334
- start line 347
- status line 376
- item line 404
- reset line 606
- sessionChanged line 622
import { existsSync } from "node:fs";
import type {
ExtensionAPI,
ExtensionContext,
} from "@earendil-works/pi-coding-agent";
import type { AutocompleteItem } from "@earendil-works/pi-tui";
import { type CompanionState, createCompanion } from "./companion.ts";
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,
STATE_PATH_SETTING,
statePathFor,
} from "./settings.ts";
import { type Budgets, LoopStore, type RunRecord } from "./store.ts";
type Site = { url: string; close(): Promise<void> };
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: <id|latest>"],
["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"],
["list", "List persisted runs"],
] as const;
const GATES_TEMPLATE = `[
{ "name": "tests", "command": "npm", "args": ["test"] }
]`;
const WATCHDOG_MS = 2_000;
const COMPANION = "loop-companion";
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<LoopController>;
/** Begin the baseline pass and loop for the run just started or resumed. */
launch(
ctx: ExtensionContext,
toolSignal?: AbortSignal,
): Promise<GatePass | undefined>;
busy(): 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<LoopController> | undefined;
let sessionCtx: ExtensionContext | undefined;
let statePath: string | undefined;
let ui: ExtensionContext["ui"] | undefined;
let lastStatus: string | undefined;
let timer: ReturnType<typeof setTimeout> | undefined;
let watchdog: ReturnType<typeof setInterval> | undefined;
let starting: AbortController | undefined;
let generation = 0;
let guided: { budgets: Budgets; cwd: string } | undefined;
let site: Promise<Site> | undefined;
let tui = false;
let companion = 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 text = !run
? undefined
: run.status === "active"
? `${ICON.loop} ${ICON.gate} ${formatBudget(run.attempts, run.budgets.attempts)} ${ICON.turn} ${formatBudget(run.turns, run.budgets.turns)}${run.pending ? ` ${ICON.pending}` : ""}`
: `${ICON[run.status]} loop ${run.status}`;
ui?.setStatus("loop", text);
const wanted = tui && !!run && run.status !== "stopped";
if (wanted !== companion) {
companion = wanted;
ui?.setWidget(
COMPANION,
wanted
? (host, theme) => createCompanion(host, theme, companionState)
: undefined,
{ placement: "belowEditor" },
);
}
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 companionState = (): CompanionState => {
const run = controller?.status();
if (!run)
return {
status: "stopped",
pending: false,
attempts: 0,
turns: 0,
budgets: { minutes: null, turns: null, attempts: null },
failed: null,
updatedAt: 0,
};
const pass = run.lastPass;
const index = pass?.failedIndex ?? null;
const result = index === null ? undefined : pass?.results[index];
const gate = index === null ? undefined : run.gates[index];
return {
status: run.status,
pending: run.pending,
attempts: run.attempts,
turns: run.turns,
budgets: run.budgets,
failed:
result && gate ? { gate: gateLabel(gate), at: result.endedAt } : null,
updatedAt: run.updatedAt,
};
};
const open = async (ctx: ExtensionContext) => {
ui = ctx.ui;
tui = ctx.mode === "tui";
if (controller) return controller;
opening ??= (async () => {
statePath ??= resolvePath(ctx);
const store = await LoopStore.open(statePath);
const created = new LoopController(store);
created.subscribe(showStatus);
controller = created;
return created;
})();
try {
return await opening;
} finally {
opening = undefined;
}
};
const clear = () => {
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<PromptDetails>(
{ 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<GatePass | undefined> => {
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();
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");
removeEscape = ctx.ui.onTerminalInput((data) => {
if (!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)
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;
}
};
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<RunRecord[]> => {
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 loop = await open(ctx);
const cwd = ctx.cwd;
const owner = generation;
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<typeof parseGates>;
try {
gates = parseGates(raw);
} catch (error) {
throw new Error(`Invalid gates: ${errorMessage(error)}`);
}
requireIdle(ctx);
guided = undefined;
loop.start({ goal, gates, cwd }, budgets);
await launch(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 gates = run.gates
.map((gate, index) => {
const result = pass?.results[index];
const mark = !result
? "·"
: result.exitCode === 0 && !result.error
? "✓"
: "✗";
return `${mark} ${gateLabel(gate)}`;
})
.join(" ");
return `${describeRun(run)}\n${run.reason}\n${gates}${live?.storageError ? `\nstate write failed: ${live.storageError}` : ""}`;
};
pi.registerMessageRenderer<PromptDetails>(PROMPT_TYPE, renderLoopPrompt);
pi.registerCommand("loop", {
description:
"Goal-gated agent loop: start|guide|resume|pause|stop|status|view|list",
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 === "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);
switch (action) {
case "start":
return start(values, ctx);
case "guide": {
requireIdle(ctx);
const budgets = parseBudgets(values);
const loop = await open(ctx);
const unignored = await stateFileUnignored(
pi,
ctx.cwd,
loop.store.path,
);
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 open(ctx);
loop.resume(findRun(loop, values[0]));
dbg?.("run.resume", { outcome: "active" });
await launch(ctx);
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 open(ctx);
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 open(ctx)), "info");
return;
case "view": {
const loop = await open(ctx);
if (!site) {
const pending = import("../site.ts").then(({ startSite }) =>
startSite(loop),
);
site = pending;
pending.catch(() => {
if (site === pending) site = undefined;
});
}
const { url } = await site;
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 open(ctx)).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", () => {
// An independent run during setup must not inherit an unchecked baseline.
if (starting) pause("Another agent run started during loop setup");
});
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;
}
try {
await loop.checkGates(ctx.signal);
} catch (error) {
loop.record("gate_error", { message: errorMessage(error) });
}
if (!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) => {
if (event.aborted && controller?.active) pause("Agent aborted");
});
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<PromptDetails> | undefined)
?.stub;
if (typeof stub !== "string" || message.content === stub) return message;
changed = true;
return { ...message, content: stub };
});
return changed ? { messages } : undefined;
});
const reset = () => {
const closing = site;
site = undefined;
void closing?.then((open) => open.close()).catch(() => undefined);
clear();
invalidate();
controller?.release();
controller?.store.close();
controller = undefined;
statePath = undefined;
guided = undefined;
ui?.setStatus("loop", undefined);
if (companion) ui?.setWidget(COMPANION, undefined);
companion = false;
lastStatus = undefined;
};
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", (_event, ctx) => {
reset();
sessionCtx = ctx;
ui = ctx.ui;
tui = ctx.mode === "tui";
});
pi.on("session_shutdown", () => {
pause("Session shutdown; never auto-resumed");
reset();
sessionCtx = undefined;
});
const runtime: LoopRuntime = {
open,
launch,
busy: () => Boolean(starting) || Boolean(controller?.active),
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);
}