Files

75 lines
3.1 KiB
TypeScript

import { readFileSync } from "node:fs";
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
const PROCEDURE_PATH = "/Users/alex/.pi/agent/prompts/finish_audit.md";
const OBJECTIVE = `Audit the current session's changes by following the procedure in ${PROCEDURE_PATH}: launch the fresh-context reviewer fanout it describes, synthesize the three reports, fix the accepted findings, and repeat the fanout until the reviews find no more issues.`;
/** Strip YAML frontmatter from a template file, returning the body. */
function templateBody(path: string): string {
const raw = readFileSync(path, "utf8");
const match = raw.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);
return (match ? raw.slice(match[0].length) : raw).trim();
}
/**
* /finish_audit [goal]
*
* - /finish_audit plain one-shot audit: sends the finish_audit.md
* template body as a user message (same behavior as
* the template alone).
* - /finish_audit goal starts Goal mode via the pi-goal run RPC
* (requires rpc.enabled in pi-goal.json) and runs the
* same procedure on the goal continuation loop.
*
* Extension commands dispatch before prompt templates, so this command
* shadows the finish_audit.md template of the same name.
*/
export default function finishAuditGoalExtension(pi: ExtensionAPI) {
pi.registerCommand("finish_audit", {
description: "Audit the session changes; add 'goal' to run with Goal mode",
getArgumentCompletions: (prefix: string) =>
"goal".startsWith(prefix.trim()) ? [{ value: "goal", label: "goal — run with Goal mode" }] : [],
handler: async (args, ctx) => {
const mode = args.trim().toLowerCase();
if (mode === "goal") {
const runId = `finish-audit-${Date.now()}`;
const channel = `pi-goal:event:${runId}`;
const unsubscribe = pi.events.on(channel, (data: unknown) => {
const event = data as { type?: string; status?: string; error?: { message?: string } };
try {
if (event?.type === "error") {
ctx.ui.notify(`finish_audit goal failed: ${event.error?.message ?? "unknown error"}`, "error");
unsubscribe();
} else if (event?.type === "state" && event.status) {
ctx.ui.notify(`Goal mode started: finish-audit loop (${event.status})`, "info");
unsubscribe();
}
} catch {
// Session was replaced or reloaded; the stale ctx is not an error.
unsubscribe();
}
});
pi.events.emit("pi-goal:start", { runId, objective: OBJECTIVE });
return;
}
if (mode !== "") {
ctx.ui.notify(`Unknown argument '${args.trim()}'. Usage: /finish_audit [goal]`, "error");
return;
}
// Plain one-shot: send the procedure body as a user message.
// expandPromptTemplates stays false so the body is never re-dispatched
// as a command (no recursion on /finish_audit).
pi.sendUserMessage(templateBody(PROCEDURE_PATH), {
deliverAs: "followUp",
expandPromptTemplates: false,
});
},
});
}