import { existsSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { isAbsolute, join, resolve } from "node:path"; import { CONFIG_DIR_NAME, type ExtensionAPI } from "@selesai/code"; import { BRIEF_FILE_NAME, buildObjective, renderBrief } from "./brief.ts"; import { finishRun, readRunState, recordRunStart, runStatePath } from "./finish.ts"; import { runRosterPicker } from "./picker.ts"; import { loadRoster, SECTIONS } from "./roster.ts"; function numberedTasks(root: string): string[] { return readdirSync(root, { withFileTypes: true }) .filter((entry) => entry.isDirectory() && /^\d+-/.test(entry.name)) .map((entry) => entry.name) .sort((a, b) => Number.parseInt(b, 10) - Number.parseInt(a, 10) || a.localeCompare(b)); } function missingTaskFiles(taskDir: string): string[] { return ["plan.md", "todo.md"].filter((name) => { try { return !statSync(join(taskDir, name)).isFile(); } catch { return true; } }); } function resolveTaskDir(cwd: string, argument: string): string { const root = join(cwd, CONFIG_DIR_NAME, "tasks"); if (!argument || /^\d+$/.test(argument)) { const names = numberedTasks(root); const name = argument ? names.find((name) => name.startsWith(`${argument}-`)) : names[0]; if (!name) throw new Error(argument ? `No task directory found for ID ${argument}.` : `No numbered task directories found in ${root}.`); return resolve(root, name); } if (/^\d+-[^/\\]+$/.test(argument)) return resolve(root, argument); return isAbsolute(argument) ? resolve(argument) : resolve(cwd, argument); } export default function implementGoalExtension(pi: ExtensionAPI): void { // Set when goal_complete succeeds for the /implement goal; handled once the turn ends. let finishing: string | undefined; pi.on("tool_execution_end", (event, ctx) => { if (event.toolName !== "goal_complete" || event.isError) return; // pi-goal returns rejections as normal results; only a success starts with "Goal complete:". if (!String(event.result?.content?.[0]?.text ?? "").startsWith("Goal complete:")) return; const statePath = runStatePath(ctx.cwd); const state = statePath ? readRunState(statePath) : undefined; const goal = event.result?.details?.goal; if (statePath && state && typeof goal === "string" && goal.includes(join(state.taskDir, BRIEF_FILE_NAME))) finishing = statePath; }); pi.on("agent_end", async (_event, ctx) => { if (!finishing) return; const statePath = finishing; finishing = undefined; const state = readRunState(statePath); rmSync(statePath, { force: true }); if (!state) return; try { await finishRun(ctx.cwd, state, ctx); } catch (error) { ctx.ui.notify(`Could not finish /implement: ${error instanceof Error ? error.message : String(error)}`, "error"); } }); pi.registerCommand("plan", { description: "Plan a request with the plan-todo skill", handler: async (args, ctx) => { const request = args.trim(); if (!request) { ctx.ui.notify("Usage: /plan ", "warning"); return; } if (!pi.getCommands().some((command) => command.source === "skill" && command.name === "skill:plan-todo")) { ctx.ui.notify("The plan-todo skill is required for /plan.", "error"); return; } if (!ctx.isIdle()) { ctx.ui.notify("Wait for the current response to finish, then run /plan again.", "warning"); return; } await pi.sendUserMessage(`/skill:plan-todo ${request}`, { expandPromptTemplates: true }); }, }); pi.registerCommand("implement", { description: "Implement a planned task under a goal with a model list", getArgumentCompletions: (prefix) => { try { const root = join(process.cwd(), CONFIG_DIR_NAME, "tasks"); const matches = numberedTasks(root) .filter((name) => name.startsWith(prefix) && missingTaskFiles(join(root, name)).length === 0) .map((name) => ({ value: name, label: name })); return matches.length > 0 ? matches : null; } catch { return null; } }, handler: async (args, ctx) => { if (!ctx.isIdle()) { ctx.ui.notify("Wait for the current response to finish, then run /implement again.", "warning"); return; } try { const taskDir = resolveTaskDir(ctx.cwd, args.trim()); const missing = missingTaskFiles(taskDir); if (missing.length > 0) { ctx.ui.notify(`Task directory ${taskDir} is missing ${missing.join(" and ")}.`, "error"); return; } const options = { cwd: ctx.cwd, trusted: ctx.isProjectTrusted() }; let loaded = loadRoster(options); if (loaded && "error" in loaded) { ctx.ui.notify(`Invalid model list at ${loaded.path}: ${loaded.error}`, "error"); return; } if (!loaded) { ctx.ui.notify("A model list is required for /implement. Choose models to continue.", "info"); loaded = await runRosterPicker(ctx, options); if (!loaded) { ctx.ui.notify("Cancelled: /implement needs a model list.", "info"); return; } } const skill = pi.getCommands().find((command) => command.source === "skill" && command.name === "skill:plan-todo-implementer"); const implementerSkillPath = skill?.sourceInfo?.path; if (!implementerSkillPath) { ctx.ui.notify("The plan-todo-implementer skill is required for /implement.", "error"); return; } const roster = loaded.roster; const available = ctx.modelRegistry.getAvailable(); const unavailable = SECTIONS.flatMap((section) => roster.sections[section]) .filter((row) => !available.some((model) => model.provider === row.provider && model.id === row.model)); if (unavailable.length > 0) { ctx.ui.notify(`Saved models currently unavailable: ${unavailable.map((row) => `${row.provider}/${row.model}`).join(", ")}. Proceeding with the saved model list.`, "warning"); } const objective = buildObjective(taskDir); const brief = renderBrief({ taskDir, roster, implementerSkillPath }); const briefPath = join(taskDir, BRIEF_FILE_NAME); if (existsSync(briefPath) && readFileSync(briefPath, "utf8") !== brief) { if (!(await ctx.ui.confirm("Overwrite goal brief?", briefPath))) return; } writeFileSync(briefPath, brief, "utf8"); const start = recordRunStart(ctx.cwd, taskDir); if (start?.dirty) ctx.ui.notify("Uncommitted changes will be part of the squash offered when the goal completes.", "info"); await pi.sendUserMessage(`/goal ${objective}`, { expandPromptTemplates: true }); } catch (error) { ctx.ui.notify(error instanceof Error ? error.message : String(error), "error"); } }, }); pi.registerCommand("implement-models", { description: "Create or edit the model list used by /implement", handler: async (_args, ctx) => { const saved = await runRosterPicker(ctx, { cwd: ctx.cwd, trusted: ctx.isProjectTrusted() }); ctx.ui.notify(saved ? `Saved model list to ${saved.path}.` : "Model list unchanged.", "info"); }, }); }