import type { Role, RoleResult, StartStep, WorkflowMessage } from "@uncaged/nerve-core"; import { cursorAgent, isDryRun, llmExtract } from "@uncaged/nerve-workflow-utils"; import type { LlmProvider } from "@uncaged/nerve-workflow-utils"; import { z } from "zod"; import { resolveRepoCwd } from "../../lib/repo-context.js"; import { threadIdFromStart } from "../../lib/start-meta.js"; import { formatSpawnFailure } from "../../lib/spawn-utils.js"; import { buildPlanPrompt } from "./prompt.js"; export const planMetaSchema = z.object({ ready: z.boolean().describe("true if plan is clear and actionable"), }); export type PlanMeta = z.infer; export type BuildPlanDeps = { provider: LlmProvider; nerveRoot: string; }; export function buildPlanRole({ provider, nerveRoot }: BuildPlanDeps): Role { return async (start: StartStep, messages: WorkflowMessage[]): Promise> => { const cwd = resolveRepoCwd(messages); if (cwd === null) { return { content: "plan cannot run: missing ---SOLVE_ISSUE_REPO--- or ---SOLVE_ISSUE_PARSE--- in thread", meta: { ready: false }, }; } const dry = isDryRun(start); const prompt = buildPlanPrompt({ threadId: threadIdFromStart(start), nerveRoot }); const run = await cursorAgent({ prompt, mode: "ask", model: "auto", cwd, env: null, timeoutMs: 300_000, dryRun: dry, }); if (!run.ok) { return { content: `plan cursor-agent failed: ${formatSpawnFailure(run.error)}`, meta: { ready: false }, }; } const metaR = await llmExtract({ text: run.value, schema: planMetaSchema, provider, dryRun: dry, }); if (!metaR.ok) { return { content: `${run.value}\n\n[meta extract failed]`, meta: { ready: false }, }; } return { content: run.value, meta: metaR.value }; }; }