import assert from "node:assert/strict"; import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; import test, { after } from "node:test"; import type { ThinkingLevel } from "@earendil-works/pi-agent-core"; import { Value } from "typebox/value"; import { InvalidInvocationError, ProjectAgentDeclinedError, prepareInvocation, resolveAgentScope, type PrepareContext, } from "../src/prepare.ts"; import { ChainItem, type AgentScopeValue, type SubagentJobsParamsType, type SubagentParamsType, SubagentJobsParams, SubagentParams, TaskItem, } from "../src/schemas.ts"; interface Confirmation { title: string; message: string; } interface FakeContext extends PrepareContext { confirmations: Confirmation[]; } const tempRoots: string[] = []; after(() => { for (const root of tempRoots) fs.rmSync(root, { recursive: true, force: true }); }); function makeTempRoot(): string { const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-prepare-")); tempRoots.push(root); return root; } function writeAgent(projectDir: string, name: string, description: string, systemPrompt = `You are ${description}.`): string { const agentsDir = path.join(projectDir, ".pi", "agents"); fs.mkdirSync(agentsDir, { recursive: true }); const filePath = path.join(agentsDir, `${name}.md`); fs.writeFileSync(filePath, `---\nname: ${name}\ndescription: ${description}\n---\n${systemPrompt}\n`, "utf-8"); return filePath; } function makeProject(root: string, label: string, agents: Record = { reviewer: `${label} reviewer` }): string { const projectDir = path.join(root, label); fs.mkdirSync(projectDir, { recursive: true }); for (const [name, description] of Object.entries(agents)) { writeAgent(projectDir, name, description); } return projectDir; } function projectAgentsDir(projectDir: string): string { return path.join(projectDir, ".pi", "agents"); } function makeContext(options: { cwd: string; trusted?: boolean; hasUI?: boolean; confirmResult?: boolean | boolean[]; model?: { provider: string; id: string }; thinkingLevel?: ThinkingLevel; }): FakeContext { const confirmations: Confirmation[] = []; const answers = Array.isArray(options.confirmResult) ? [...options.confirmResult] : undefined; const fallback = typeof options.confirmResult === "boolean" ? options.confirmResult : true; return { cwd: options.cwd, model: options.model ?? { provider: "test-provider", id: "test-model" }, thinkingLevel: options.thinkingLevel ?? "medium", hasUI: options.hasUI ?? true, isProjectTrusted: () => options.trusted ?? false, ui: { async confirm(title: string, message: string): Promise { confirmations.push({ title, message }); return answers && answers.length > 0 ? answers.shift()! : fallback; }, }, confirmations, }; } /** Project-scoped request with confirmation off unless a test opts in. */ function projectParams(overrides: Partial = {}): SubagentParamsType { return { agentScope: "project", confirmProjectAgents: false, ...overrides }; } test("single mode resolves the project agent, cwd, and dispatch defaults", async () => { const root = makeTempRoot(); const project = makeProject(root, "project-a"); const ctx = makeContext({ cwd: root, thinkingLevel: "high" }); const prepared = await prepareInvocation( projectParams({ agent: "reviewer", task: "review it", cwd: "project-a" }), ctx, ); assert.equal(prepared.mode, "single"); assert.equal(prepared.agentScope, "project"); assert.equal(prepared.tasks.length, 1); const [task] = prepared.tasks; assert.equal(task.agent.name, "reviewer"); assert.equal(task.agent.source, "project"); assert.equal(task.agent.description, "project-a reviewer"); assert.equal(task.agent.filePath, path.join(projectAgentsDir(project), "reviewer.md")); assert.equal(task.task, "review it"); assert.equal(task.cwd, path.resolve(root, "project-a")); assert.equal(task.step, undefined); assert.equal(prepared.projectAgentsDir, projectAgentsDir(project)); assert.deepEqual(prepared.projectAgentsDirs, [projectAgentsDir(project)]); assert.deepEqual(prepared.dispatchDefaults, { model: "test-provider/test-model", thinkingLevel: "high", }); assert.equal(ctx.confirmations.length, 0); }); test("task cwd defaults to ctx.cwd and relative cwds resolve against it", async () => { const root = makeTempRoot(); const project = makeProject(root, "project-a"); const workspace = path.join(root, "workspace"); fs.mkdirSync(workspace); const defaultCwd = await prepareInvocation( projectParams({ agent: "reviewer", task: "default" }), makeContext({ cwd: project }), ); assert.equal(defaultCwd.tasks[0].cwd, project); const relativeCwd = await prepareInvocation( projectParams({ agent: "reviewer", task: "relative", cwd: path.relative(workspace, project) }), makeContext({ cwd: workspace }), ); assert.equal(relativeCwd.tasks[0].cwd, project); assert.equal(relativeCwd.tasks[0].agent.filePath, path.join(projectAgentsDir(project), "reviewer.md")); }); test("parallel preserves task order and resolves same-named agents from each task's cwd", async () => { const root = makeTempRoot(); const projectA = makeProject(root, "project-a", { reviewer: "Reviewer A" }); const projectB = makeProject(root, "project-b", { reviewer: "Reviewer B" }); const ctx = makeContext({ cwd: root }); const prepared = await prepareInvocation( projectParams({ tasks: [ { agent: "reviewer", task: "first", cwd: "project-a" }, { agent: "reviewer", task: "second", cwd: "project-b" }, ], }), ctx, ); assert.equal(prepared.mode, "parallel"); assert.deepEqual( prepared.tasks.map((task) => task.task), ["first", "second"], ); assert.deepEqual( prepared.tasks.map((task) => task.cwd), [path.resolve(root, "project-a"), path.resolve(root, "project-b")], ); assert.deepEqual( prepared.tasks.map((task) => task.agent.description), ["Reviewer A", "Reviewer B"], ); assert.equal(prepared.tasks[0].agent.filePath, path.join(projectAgentsDir(projectA), "reviewer.md")); assert.equal(prepared.tasks[1].agent.filePath, path.join(projectAgentsDir(projectB), "reviewer.md")); assert.notEqual(prepared.tasks[0].agent.filePath, prepared.tasks[1].agent.filePath); assert.deepEqual( prepared.tasks.map((task) => task.step), [undefined, undefined], ); assert.deepEqual(prepared.projectAgentsDirs, [projectAgentsDir(projectA), projectAgentsDir(projectB)]); assert.equal(prepared.projectAgentsDir, projectAgentsDir(projectA)); assert.equal(ctx.confirmations.length, 0); }); test("parallel accepts exactly eight tasks", async () => { const root = makeTempRoot(); makeProject(root, "project-a"); const tasks = Array.from({ length: 8 }, (_, index) => ({ agent: "reviewer", task: `task ${index + 1}`, cwd: "project-a", })); const prepared = await prepareInvocation(projectParams({ tasks }), makeContext({ cwd: root })); assert.equal(prepared.mode, "parallel"); assert.equal(prepared.tasks.length, 8); assert.deepEqual( prepared.tasks.map((task) => task.task), tasks.map((task) => task.task), ); }); test("chain numbers steps from 1 and preserves {previous} for the manager", async () => { const root = makeTempRoot(); const project = makeProject(root, "project-a"); const nested = path.join(project, "work"); fs.mkdirSync(nested); const ctx = makeContext({ cwd: root }); const prepared = await prepareInvocation( projectParams({ chain: [ { agent: "reviewer", task: "draft", cwd: "project-a" }, { agent: "reviewer", task: "revise {previous}", cwd: "project-a/work" }, ], }), ctx, ); assert.equal(prepared.mode, "chain"); assert.deepEqual( prepared.tasks.map((task) => task.step), [1, 2], ); assert.deepEqual( prepared.tasks.map((task) => task.task), ["draft", "revise {previous}"], ); assert.deepEqual( prepared.tasks.map((task) => task.cwd), [project, nested], ); assert.deepEqual(prepared.projectAgentsDirs, [projectAgentsDir(project)]); assert.equal(ctx.confirmations.length, 0); }); test("rejects missing, partial, and ambiguous modes", async () => { const root = makeTempRoot(); const ctx = makeContext({ cwd: root }); await assert.rejects(prepareInvocation({}, ctx), (error: unknown) => { assert.ok(error instanceof InvalidInvocationError); assert.match(error.message, /exactly one mode/); return true; }); await assert.rejects( prepareInvocation({ agent: "reviewer" }, ctx), (error: unknown) => error instanceof InvalidInvocationError && /nonempty "agent" and "task"/.test(error.message), ); await assert.rejects( prepareInvocation({ agent: "", task: "work" }, ctx), (error: unknown) => error instanceof InvalidInvocationError && /nonempty "agent" and "task"/.test(error.message), ); await assert.rejects( prepareInvocation({ agent: "reviewer", task: "work", tasks: [{ agent: "reviewer", task: "other" }] }, ctx), (error: unknown) => error instanceof InvalidInvocationError && /exactly one mode/.test(error.message), ); await assert.rejects( prepareInvocation( { tasks: [{ agent: "reviewer", task: "one" }], chain: [{ agent: "reviewer", task: "two" }] }, ctx, ), (error: unknown) => error instanceof InvalidInvocationError && /exactly one mode/.test(error.message), ); await assert.rejects( prepareInvocation({ agent: "reviewer", task: "work", chain: [{ agent: "reviewer", task: "two" }] }, ctx), (error: unknown) => error instanceof InvalidInvocationError && /exactly one mode/.test(error.message), ); assert.equal(ctx.confirmations.length, 0); }); test("rejects empty task and chain arrays", async () => { const ctx = makeContext({ cwd: makeTempRoot() }); await assert.rejects( prepareInvocation({ tasks: [] }, ctx), (error: unknown) => error instanceof InvalidInvocationError && /nonempty "tasks"/.test(error.message), ); await assert.rejects( prepareInvocation({ chain: [] }, ctx), (error: unknown) => error instanceof InvalidInvocationError && /nonempty "chain"/.test(error.message), ); assert.equal(ctx.confirmations.length, 0); }); test("rejects more than eight parallel tasks before resolving agents", async () => { const ctx = makeContext({ cwd: makeTempRoot() }); const tasks = Array.from({ length: 9 }, (_, index) => ({ agent: "missing", task: `task ${index + 1}` })); await assert.rejects( prepareInvocation({ tasks }, ctx), (error: unknown) => error instanceof InvalidInvocationError && /Too many parallel tasks \(9\)\. Max is 8\./.test(error.message), ); assert.equal(ctx.confirmations.length, 0); }); test("rejects unknown agents and lists the agents available at that cwd", async () => { const root = makeTempRoot(); makeProject(root, "project-a"); const ctx = makeContext({ cwd: root }); await assert.rejects( prepareInvocation( projectParams({ agent: "ghost", task: "work", cwd: "project-a", confirmProjectAgents: true }), ctx, ), (error: unknown) => { assert.ok(error instanceof InvalidInvocationError); assert.match(error.message, /Unknown agent: "ghost"/); assert.match(error.message, /"reviewer"/); return true; }, ); assert.equal(ctx.confirmations.length, 0); }); test("rejects missing and non-directory cwds", async () => { const root = makeTempRoot(); const file = path.join(root, "not-a-directory.txt"); fs.writeFileSync(file, "file", "utf-8"); const ctx = makeContext({ cwd: root }); await assert.rejects( prepareInvocation(projectParams({ agent: "reviewer", task: "work", cwd: "does-not-exist" }), ctx), (error: unknown) => error instanceof InvalidInvocationError && /does not exist/.test(error.message), ); await assert.rejects( prepareInvocation(projectParams({ agent: "reviewer", task: "work", cwd: "not-a-directory.txt" }), ctx), (error: unknown) => error instanceof InvalidInvocationError && /not a directory/.test(error.message), ); assert.equal(ctx.confirmations.length, 0); }); test("a later invalid task prevents every confirmation prompt", async () => { const root = makeTempRoot(); makeProject(root, "project-a"); makeProject(root, "project-b"); const ctx = makeContext({ cwd: root, confirmResult: true }); await assert.rejects( prepareInvocation( projectParams({ confirmProjectAgents: true, tasks: [ { agent: "reviewer", task: "valid", cwd: "project-a" }, { agent: "ghost", task: "invalid", cwd: "project-b" }, ], }), ctx, ), (error: unknown) => error instanceof InvalidInvocationError && /Unknown agent/.test(error.message), ); assert.equal(ctx.confirmations.length, 0); await assert.rejects( prepareInvocation( projectParams({ confirmProjectAgents: true, tasks: [ { agent: "reviewer", task: "valid", cwd: "project-a" }, { agent: "reviewer", task: "invalid cwd", cwd: "missing" }, ], }), ctx, ), (error: unknown) => error instanceof InvalidInvocationError && /does not exist/.test(error.message), ); assert.equal(ctx.confirmations.length, 0); }); test("confirms every distinct project source once, naming the directory and agents", async () => { const root = makeTempRoot(); const projectA = makeProject(root, "project-a", { reviewer: "Reviewer A", planner: "Planner A" }); const projectB = makeProject(root, "project-b", { reviewer: "Reviewer B" }); const ctx = makeContext({ cwd: root, confirmResult: true }); const prepared = await prepareInvocation( projectParams({ confirmProjectAgents: true, tasks: [ { agent: "reviewer", task: "one", cwd: "project-a" }, { agent: "planner", task: "two", cwd: "project-a" }, { agent: "reviewer", task: "three", cwd: "project-b" }, { agent: "reviewer", task: "four", cwd: "project-a" }, ], }), ctx, ); const dirA = projectAgentsDir(projectA); const dirB = projectAgentsDir(projectB); assert.equal(ctx.confirmations.length, 2); assert.ok(ctx.confirmations[0].message.includes(dirA)); assert.ok(ctx.confirmations[0].message.includes("reviewer")); assert.ok(ctx.confirmations[0].message.includes("planner")); assert.match(ctx.confirmations[0].message, /repo-controlled/); assert.ok(ctx.confirmations[1].message.includes(dirB)); assert.ok(ctx.confirmations[1].message.includes("reviewer")); assert.ok(!ctx.confirmations[1].message.includes(dirA)); assert.match(ctx.confirmations[1].message, /repo-controlled/); assert.deepEqual(prepared.projectAgentsDirs, [dirA, dirB]); assert.equal(prepared.projectAgentsDir, dirA); }); test("project confirmation defaults to enabled", async () => { const root = makeTempRoot(); makeProject(root, "project-a"); const ctx = makeContext({ cwd: root, confirmResult: true }); const prepared = await prepareInvocation( { agentScope: "project", agent: "reviewer", task: "work", cwd: "project-a" }, ctx, ); assert.equal(prepared.tasks.length, 1); assert.equal(ctx.confirmations.length, 1); assert.match(ctx.confirmations[0].message, /repo-controlled/); }); test("refusal throws ProjectAgentDeclinedError naming the source and agents", async () => { const root = makeTempRoot(); const project = makeProject(root, "project-a"); const ctx = makeContext({ cwd: root, confirmResult: false }); await assert.rejects( prepareInvocation( projectParams({ agent: "reviewer", task: "work", cwd: "project-a", confirmProjectAgents: true }), ctx, ), (error: unknown) => { assert.ok(error instanceof ProjectAgentDeclinedError); assert.equal(error.name, "ProjectAgentDeclinedError"); assert.equal(error.directory, projectAgentsDir(project)); assert.deepEqual(error.agents, ["reviewer"]); return true; }, ); assert.equal(ctx.confirmations.length, 1); }); test("refusal on a later source aborts the whole invocation", async () => { const root = makeTempRoot(); makeProject(root, "project-a"); const projectB = makeProject(root, "project-b"); const ctx = makeContext({ cwd: root, confirmResult: [true, false] }); await assert.rejects( prepareInvocation( projectParams({ confirmProjectAgents: true, tasks: [ { agent: "reviewer", task: "one", cwd: "project-a" }, { agent: "reviewer", task: "two", cwd: "project-b" }, ], }), ctx, ), (error: unknown) => { assert.ok(error instanceof ProjectAgentDeclinedError); assert.equal(error.directory, projectAgentsDir(projectB)); return true; }, ); assert.equal(ctx.confirmations.length, 2); }); test("trusted projects, disabled confirmation, and missing UI bypass prompts", async () => { const root = makeTempRoot(); const project = makeProject(root, "project-a"); const trustedCtx = makeContext({ cwd: project, trusted: true }); await prepareInvocation( projectParams({ agent: "reviewer", task: "work", cwd: ".", confirmProjectAgents: true }), trustedCtx, ); assert.equal(trustedCtx.confirmations.length, 0); const disabledCtx = makeContext({ cwd: root }); await prepareInvocation(projectParams({ agent: "reviewer", task: "work", cwd: "project-a" }), disabledCtx); assert.equal(disabledCtx.confirmations.length, 0); const noUiCtx = makeContext({ cwd: root, hasUI: false }); await prepareInvocation( projectParams({ agent: "reviewer", task: "work", cwd: "project-a", confirmProjectAgents: true }), noUiCtx, ); assert.equal(noUiCtx.confirmations.length, 0); }); test("trusted session confirms a different project selected through task cwd", async () => { const root = makeTempRoot(); const local = makeProject(root, "local"); const foreign = makeProject(root, "foreign"); const ctx = makeContext({ cwd: local, trusted: true }); await prepareInvocation(projectParams({ confirmProjectAgents: true, tasks: [ { agent: "reviewer", task: "local", cwd: "." }, { agent: "reviewer", task: "foreign", cwd: foreign }, ], }), ctx); assert.equal(ctx.confirmations.length, 1); assert.match(ctx.confirmations[0].message, new RegExp(projectAgentsDir(foreign))); assert.equal(ctx.confirmations[0].message.includes(projectAgentsDir(local)), false); }); test("dispatch defaults are undefined when the session has no model or thinking level", async () => { const root = makeTempRoot(); makeProject(root, "project-a"); const ctx = { ...makeContext({ cwd: root }), model: undefined, thinkingLevel: undefined }; const prepared = await prepareInvocation( projectParams({ agent: "reviewer", task: "work", cwd: "project-a" }), ctx, ); assert.deepEqual(prepared.dispatchDefaults, { model: undefined, thinkingLevel: undefined }); }); test("agent scope defaults to user", () => { assert.equal(resolveAgentScope(undefined), "user"); assert.equal(resolveAgentScope("user"), "user"); assert.equal(resolveAgentScope("project"), "project"); assert.equal(resolveAgentScope("both"), "both"); assert.equal(resolveAgentScope("team"), "user"); }); test("request schemas accept each mode and reject malformed requests", () => { assert.equal(Value.Check(SubagentParams, { agent: "scout", task: "work" }), true); assert.equal( Value.Check(SubagentParams, { tasks: [ { agent: "scout", task: "one" }, { agent: "scout", task: "two", cwd: "/tmp" }, ], }), true, ); assert.equal(Value.Check(SubagentParams, { chain: [{ agent: "scout", task: "one {previous}" }] }), true); for (const agentScope of ["user", "project", "both"] as const) { assert.equal( Value.Check(SubagentParams, { agent: "scout", task: "work", agentScope, confirmProjectAgents: false }), true, ); } assert.equal(Value.Check(SubagentParams, { agent: "scout", task: "work", agentScope: "team" }), false); assert.equal(Value.Check(SubagentParams, { tasks: [{ agent: "scout" }] }), false); assert.equal(Value.Check(SubagentParams, { chain: [{ task: "no agent" }] }), false); assert.equal(Value.Check(SubagentParams, { tasks: "not an array" }), false); assert.equal(Value.Check(SubagentParams, { agent: "scout", task: "work", confirmProjectAgents: "yes" }), false); assert.equal(Value.Check(TaskItem, { agent: "scout", task: "work" }), true); assert.equal(Value.Check(TaskItem, { agent: "scout", task: "work", cwd: "/tmp" }), true); assert.equal(Value.Check(TaskItem, { agent: "scout" }), false); assert.equal(Value.Check(ChainItem, { agent: "scout", task: "work {previous}" }), true); assert.equal(Value.Check(ChainItem, { task: "work" }), false); }); test("agentScope keeps its literal union type and rejects non-scopes", () => { const scope: AgentScopeValue = "project"; assert.equal(scope, "project"); const params: SubagentParamsType = { agentScope: "both" }; assert.equal(params.agentScope, "both"); // @ts-expect-error agentScope must be one of the literal scope values const invalidScope: AgentScopeValue = "team"; assert.equal(invalidScope, "team"); // @ts-expect-error agentScope must be one of the literal scope values const invalidParams: SubagentParamsType = { agentScope: "team" }; assert.equal(invalidParams.agentScope, "team"); }); test("management union accepts each valid action", () => { const valid: SubagentJobsParamsType[] = [ { action: "list" }, { action: "list", activeOnly: true }, { action: "list", activeOnly: false }, { action: "get", jobId: "job_1" }, { action: "wait", jobId: "job_1" }, { action: "wait", jobId: "job_1", timeoutSeconds: 0.5 }, { action: "wait", jobId: "job_1", timeoutSeconds: 1 }, { action: "wait", jobId: "job_1", timeoutSeconds: 300 }, { action: "cancel", jobId: "job_1" }, ]; for (const params of valid) { assert.equal(Value.Check(SubagentJobsParams, params), true, JSON.stringify(params)); } }); test("management union rejects missing job ids, bad timeouts, and unknown actions", () => { const invalid: unknown[] = [ {}, { action: "get" }, { action: "wait" }, { action: "cancel" }, { action: "get", jobId: 42 }, { action: "wait", jobId: "job_1", timeoutSeconds: 0 }, { action: "wait", jobId: "job_1", timeoutSeconds: -1 }, { action: "wait", jobId: "job_1", timeoutSeconds: 301 }, { action: "wait", jobId: "job_1", timeoutSeconds: "10" }, { action: "explode", jobId: "job_1" }, { action: "list", activeOnly: "yes" }, ]; for (const params of invalid) { assert.equal(Value.Check(SubagentJobsParams, params), false, JSON.stringify(params)); } }); test("management union narrows on its action discriminant", () => { function describe(params: SubagentJobsParamsType): string { switch (params.action) { case "list": return params.activeOnly ? "active" : "all"; case "get": return params.jobId; case "wait": return `${params.jobId}:${params.timeoutSeconds ?? "none"}`; case "cancel": return `cancel ${params.jobId}`; } } assert.equal(describe({ action: "list", activeOnly: true }), "active"); assert.equal(describe({ action: "list" }), "all"); assert.equal(describe({ action: "get", jobId: "job_1" }), "job_1"); assert.equal(describe({ action: "wait", jobId: "job_1" }), "job_1:none"); assert.equal(describe({ action: "wait", jobId: "job_1", timeoutSeconds: 5 }), "job_1:5"); assert.equal(describe({ action: "cancel", jobId: "job_1" }), "cancel job_1"); });