When a parallel subagent batch returns mixed results and background receipts, the tool guidelines and receipt text now tell the main agent to decide first: continue with the next phase of work if the finished results already answer what it needs, otherwise end the turn waiting for the pending answers instead of duplicating or preempting the pending subagents' work.
488 lines
16 KiB
TypeScript
488 lines
16 KiB
TypeScript
import { mkdirSync, rmSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
|
import { type AssistantMessage, type AssistantMessageEvent, EventStream, getModel } from "@earendil-works/pi-ai/compat";
|
|
import { Type } from "typebox";
|
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
import { DefaultResourceLoader } from "../src/core/resource-loader.ts";
|
|
import { createAgentSession } from "../src/core/sdk.ts";
|
|
import { SessionManager } from "../src/core/session-manager.ts";
|
|
import { SettingsManager } from "../src/core/settings-manager.ts";
|
|
import { MAX_SUBAGENT_ANSWER_CHARS, selectSubagentTools } from "../src/core/subagent/profiles.ts";
|
|
import { runSubagent, type SubagentHost } from "../src/core/subagent/run.ts";
|
|
import { BACKGROUND_CUT_DELAY_MS, createSubagentTool } from "../src/core/tools/subagent.ts";
|
|
|
|
class MockAssistantStream extends EventStream<AssistantMessageEvent, AssistantMessage> {
|
|
constructor() {
|
|
super(
|
|
(event) => event.type === "done" || event.type === "error",
|
|
(event) => {
|
|
if (event.type === "done") return event.message;
|
|
if (event.type === "error") return event.error;
|
|
throw new Error("Unexpected event type");
|
|
},
|
|
);
|
|
}
|
|
}
|
|
|
|
function assistantMessage(text: string, stopReason: AssistantMessage["stopReason"] = "stop"): AssistantMessage {
|
|
return {
|
|
role: "assistant",
|
|
content: [{ type: "text", text }],
|
|
api: "openai-responses",
|
|
provider: "openai",
|
|
model: "mock",
|
|
usage: {
|
|
input: 0,
|
|
output: 0,
|
|
cacheRead: 0,
|
|
cacheWrite: 0,
|
|
totalTokens: 0,
|
|
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
},
|
|
stopReason,
|
|
timestamp: Date.now(),
|
|
};
|
|
}
|
|
|
|
function toolMessage(name: string): AssistantMessage {
|
|
return {
|
|
...assistantMessage(""),
|
|
content: [{ type: "toolCall", id: `call-${name}`, name, arguments: {} }],
|
|
stopReason: "toolUse",
|
|
};
|
|
}
|
|
|
|
function tool(name: string): AgentTool {
|
|
return {
|
|
name,
|
|
label: name,
|
|
description: `${name} tool`,
|
|
parameters: Type.Object({}),
|
|
execute: async () => ({ content: [{ type: "text", text: name }], details: {} }),
|
|
};
|
|
}
|
|
|
|
function host(streamFn: SubagentHost["streamFn"], tools: AgentTool[] = []): SubagentHost {
|
|
return {
|
|
model: getModel("anthropic", "claude-sonnet-4-5"),
|
|
thinkingLevel: "off",
|
|
streamFn,
|
|
cwd: process.cwd(),
|
|
platform: process.platform,
|
|
convertToLlm: (messages) =>
|
|
messages.filter((message) => message.role !== "system" || message.content !== undefined) as never,
|
|
tools,
|
|
};
|
|
}
|
|
|
|
function done(message: AssistantMessage): MockAssistantStream {
|
|
const stream = new MockAssistantStream();
|
|
const reason =
|
|
message.stopReason === "toolUse" || message.stopReason === "length" || message.stopReason === "deferred"
|
|
? message.stopReason
|
|
: "stop";
|
|
queueMicrotask(() => stream.push({ type: "done", reason, message }));
|
|
return stream;
|
|
}
|
|
|
|
describe("subagent tools", () => {
|
|
it("gives explore only read-only tools and never the subagent tool", () => {
|
|
const tools = ["read", "bash", "grep", "edit", "subagent", "find", "ls"].map(tool);
|
|
expect(selectSubagentTools(tools, "explore").map((item) => item.name)).toEqual(["read", "grep", "find", "ls"]);
|
|
expect(selectSubagentTools(tools, "general").map((item) => item.name)).toEqual([
|
|
"read",
|
|
"bash",
|
|
"grep",
|
|
"edit",
|
|
"find",
|
|
"ls",
|
|
]);
|
|
});
|
|
|
|
it("returns the child final answer and hides the child tool result", async () => {
|
|
let calls = 0;
|
|
const result = await runSubagent({
|
|
description: "auth lookup",
|
|
task: "find the auth code",
|
|
agentType: "general",
|
|
host: host(
|
|
(..._args) => {
|
|
calls += 1;
|
|
return done(calls === 1 ? toolMessage("echo") : assistantMessage("auth is in src/auth.ts"));
|
|
},
|
|
[tool("echo"), tool("subagent")],
|
|
),
|
|
});
|
|
|
|
expect(result.status).toBe("completed");
|
|
expect(result.description).toBe("auth lookup");
|
|
expect(result.text).toBe("auth is in src/auth.ts");
|
|
expect(result.toolUseCount).toBe(1);
|
|
});
|
|
|
|
it("does not give the child the subagent tool", async () => {
|
|
let declared: string[] = [];
|
|
await runSubagent({
|
|
description: "look",
|
|
task: "look",
|
|
agentType: "general",
|
|
host: host(
|
|
(_model, context) => {
|
|
const system = context.messages.find((message) => message.role === "system");
|
|
declared = (system && "toolsAdded" in system ? system.toolsAdded : [])?.map((item) => item.name) ?? [];
|
|
return done(assistantMessage("done"));
|
|
},
|
|
[tool("read"), tool("subagent")],
|
|
),
|
|
});
|
|
expect(declared).toEqual(["read"]);
|
|
});
|
|
|
|
it("sends one stable session id on every child request", async () => {
|
|
const runAndCapture = async () => {
|
|
const sessionIds: Array<string | undefined> = [];
|
|
let calls = 0;
|
|
await runSubagent({
|
|
description: "trace",
|
|
task: "trace",
|
|
agentType: "general",
|
|
host: host(
|
|
(_model, _context, options) => {
|
|
calls += 1;
|
|
sessionIds.push(options?.sessionId);
|
|
return done(calls === 1 ? toolMessage("echo") : assistantMessage("done"));
|
|
},
|
|
[tool("echo")],
|
|
),
|
|
});
|
|
return sessionIds;
|
|
};
|
|
|
|
const first = await runAndCapture();
|
|
const second = await runAndCapture();
|
|
|
|
// Providers such as OpenCode Go reject requests without a session id.
|
|
expect(first).toHaveLength(2);
|
|
expect(first[0]).toBeTruthy();
|
|
expect(first[1]).toBe(first[0]);
|
|
expect(second[0]).toBeTruthy();
|
|
expect(second[0]).not.toBe(first[0]);
|
|
});
|
|
|
|
it("runs past the previous eight-turn cap until the child answers", async () => {
|
|
let calls = 0;
|
|
const result = await runSubagent({
|
|
description: "long run",
|
|
task: "keep going",
|
|
agentType: "general",
|
|
host: host(() => {
|
|
calls += 1;
|
|
return done(calls <= 10 ? toolMessage("echo") : assistantMessage("finally done"));
|
|
}, [tool("echo")]),
|
|
});
|
|
expect(calls).toBe(11);
|
|
expect(result.status).toBe("completed");
|
|
expect(result.text).toBe("finally done");
|
|
expect(result.turnCount).toBe(11);
|
|
expect(result.toolUseCount).toBe(10);
|
|
});
|
|
|
|
it("passes the working directory, platform, and model to the child prompt", async () => {
|
|
let systemPrompt = "";
|
|
await runSubagent({
|
|
description: "environment",
|
|
task: "look",
|
|
agentType: "general",
|
|
host: {
|
|
...host((_model, context) => {
|
|
const system = context.messages.find((message) => message.role === "system");
|
|
systemPrompt = system && "content" in system && typeof system.content === "string" ? system.content : "";
|
|
return done(assistantMessage("done"));
|
|
}),
|
|
cwd: "/tmp/workspace",
|
|
platform: "test-platform",
|
|
},
|
|
});
|
|
expect(systemPrompt).toContain("Working directory: /tmp/workspace");
|
|
expect(systemPrompt).toContain("Platform: test-platform");
|
|
expect(systemPrompt).toContain("Model: anthropic/claude-sonnet-4-5");
|
|
});
|
|
|
|
it("gives project instructions to general children only", async () => {
|
|
const contextFiles = [{ path: "/tmp/AGENTS.md", content: "always write tests" }];
|
|
const capture = async (agentType: "general" | "explore") => {
|
|
let systemPrompt = "";
|
|
await runSubagent({
|
|
description: "capture",
|
|
task: "look",
|
|
agentType,
|
|
host: {
|
|
...host((_model, context) => {
|
|
const system = context.messages.find((message) => message.role === "system");
|
|
systemPrompt =
|
|
system && "content" in system && typeof system.content === "string" ? system.content : "";
|
|
return done(assistantMessage("done"));
|
|
}),
|
|
contextFiles,
|
|
},
|
|
});
|
|
return systemPrompt;
|
|
};
|
|
expect(await capture("general")).toContain("always write tests");
|
|
expect(await capture("explore")).not.toContain("always write tests");
|
|
});
|
|
|
|
it("caps an oversized final answer and flags truncation", async () => {
|
|
const long = "x".repeat(MAX_SUBAGENT_ANSWER_CHARS + 500);
|
|
const result = await runSubagent({
|
|
description: "long",
|
|
task: "long",
|
|
agentType: "general",
|
|
host: host(() => done(assistantMessage(long))),
|
|
});
|
|
expect(result.status).toBe("completed");
|
|
expect(result.truncated).toBe(true);
|
|
expect(result.text).toContain("[... answer truncated, 500 chars omitted]");
|
|
});
|
|
|
|
it("sums the child token usage across all turns", async () => {
|
|
let calls = 0;
|
|
const result = await runSubagent({
|
|
description: "usage",
|
|
task: "usage",
|
|
agentType: "general",
|
|
host: host(() => {
|
|
calls += 1;
|
|
if (calls === 1) return done(toolMessage("echo"));
|
|
return done({
|
|
...assistantMessage("answer"),
|
|
usage: {
|
|
input: 10,
|
|
output: 20,
|
|
cacheRead: 30,
|
|
cacheWrite: 40,
|
|
totalTokens: 100,
|
|
cost: { input: 1, output: 2, cacheRead: 3, cacheWrite: 4, total: 10 },
|
|
},
|
|
});
|
|
}, [tool("echo")]),
|
|
});
|
|
expect(result.usage).toEqual({
|
|
input: 10,
|
|
output: 20,
|
|
cacheRead: 30,
|
|
cacheWrite: 40,
|
|
totalTokens: 100,
|
|
cost: { input: 1, output: 2, cacheRead: 3, cacheWrite: 4, total: 10 },
|
|
});
|
|
});
|
|
|
|
it("aborts the child when the parent signal aborts", async () => {
|
|
const controller = new AbortController();
|
|
let started: () => void = () => {};
|
|
const ready = new Promise<void>((resolve) => {
|
|
started = resolve;
|
|
});
|
|
const pending = runSubagent({
|
|
description: "wait",
|
|
task: "wait",
|
|
agentType: "general",
|
|
signal: controller.signal,
|
|
host: host((_model, _context, options) => {
|
|
const stream = new MockAssistantStream();
|
|
const finish = () => {
|
|
stream.push({
|
|
type: "error",
|
|
reason: "aborted",
|
|
error: {
|
|
...assistantMessage("stopped", "aborted"),
|
|
stopReason: "aborted",
|
|
errorMessage: "aborted",
|
|
},
|
|
});
|
|
};
|
|
options?.signal?.addEventListener("abort", finish, { once: true });
|
|
started();
|
|
return stream;
|
|
}),
|
|
});
|
|
await ready;
|
|
controller.abort();
|
|
await expect(pending).resolves.toMatchObject({ status: "aborted", errorMessage: "aborted" });
|
|
});
|
|
|
|
it("rejects an empty task without calling the model", async () => {
|
|
const result = await runSubagent({
|
|
description: "empty",
|
|
task: " ",
|
|
agentType: "explore",
|
|
host: host(() => {
|
|
throw new Error("model should not be called");
|
|
}),
|
|
});
|
|
expect(result).toMatchObject({ status: "error", errorMessage: "Subagent task is empty." });
|
|
});
|
|
|
|
it("reports running progress as tools execute", async () => {
|
|
let calls = 0;
|
|
const progress: Awaited<ReturnType<typeof runSubagent>>[] = [];
|
|
await runSubagent({
|
|
description: "progress",
|
|
task: "progress",
|
|
agentType: "explore",
|
|
host: host(() => {
|
|
calls += 1;
|
|
return done(calls === 1 ? toolMessage("read") : assistantMessage("done"));
|
|
}, [tool("read")]),
|
|
onProgress: (snapshot) => progress.push(snapshot),
|
|
});
|
|
expect(progress.length).toBeGreaterThan(0);
|
|
expect(progress.every((snapshot) => snapshot.status === "running")).toBe(true);
|
|
const duringTool = progress.find((snapshot) => snapshot.currentTool === "read");
|
|
expect(duringTool).toMatchObject({ currentTool: "read", toolUseCount: 1 });
|
|
expect(progress.some((snapshot) => snapshot.toolUseCount === 1 && snapshot.currentTool === undefined)).toBe(true);
|
|
});
|
|
});
|
|
|
|
describe("subagent tool", () => {
|
|
it("forwards running progress through onUpdate", async () => {
|
|
let calls = 0;
|
|
const updates: Array<{ status?: string; currentTool?: string } | undefined> = [];
|
|
const subagent = createSubagentTool({
|
|
getHost: () =>
|
|
host(() => {
|
|
calls += 1;
|
|
return done(calls === 1 ? toolMessage("read") : assistantMessage("done"));
|
|
}, [tool("read")]),
|
|
});
|
|
await subagent.execute("call", { description: "x", task: "x" }, undefined, (update) => {
|
|
updates.push(update.details as { status?: string; currentTool?: string });
|
|
});
|
|
expect(updates.some((details) => details?.status === "running" && details?.currentTool === "read")).toBe(true);
|
|
});
|
|
|
|
it("reports finished usage to the caller", async () => {
|
|
const recorded: Array<{ provider: string; model: string; totalTokens: number }> = [];
|
|
const subagent = createSubagentTool({
|
|
getHost: () => host(() => done(assistantMessage("done"))),
|
|
recordUsage: (provider, model, usage) => recorded.push({ provider, model, totalTokens: usage.totalTokens }),
|
|
});
|
|
const result = await subagent.execute("call", { description: "x", task: "x" });
|
|
expect(result.details.status).toBe("completed");
|
|
expect(recorded).toEqual([{ provider: "anthropic", model: "claude-sonnet-4-5", totalTokens: 0 }]);
|
|
});
|
|
|
|
it("hands off a still-running sibling so the parent can advance", async () => {
|
|
const delivered: Array<{ status: string; text: string }> = [];
|
|
const recorded: number[] = [];
|
|
const slow = new MockAssistantStream();
|
|
let hostCalls = 0;
|
|
const subagent = createSubagentTool({
|
|
getHost: () => {
|
|
hostCalls += 1;
|
|
if (hostCalls === 1) return host(() => done(assistantMessage("fast answer")));
|
|
return host(() => slow);
|
|
},
|
|
recordUsage: (_provider, _model, usage) => recorded.push(usage.totalTokens),
|
|
background: {
|
|
enabled: () => true,
|
|
deliver: (result) => delivered.push({ status: result.status, text: result.text }),
|
|
},
|
|
});
|
|
|
|
const fast = subagent.execute("call-fast", { description: "fast task", task: "fast" });
|
|
const pending = subagent.execute("call-slow", { description: "slow task", task: "slow" });
|
|
|
|
await expect(fast).resolves.toMatchObject({ details: { status: "completed", text: "fast answer" } });
|
|
await new Promise((resolve) => setTimeout(resolve, BACKGROUND_CUT_DELAY_MS + 50));
|
|
|
|
const receipt = await pending;
|
|
expect(receipt.details).toMatchObject({ status: "running", background: true, description: "slow task" });
|
|
expect((receipt.content[0] as { text: string }).text).toContain("background: true");
|
|
expect((receipt.content[0] as { text: string }).text).toContain(
|
|
"Decide whether the results already returned are enough to start the next phase of work",
|
|
);
|
|
expect(delivered).toEqual([]);
|
|
|
|
slow.push({
|
|
type: "done",
|
|
reason: "stop",
|
|
message: {
|
|
...assistantMessage("slow answer"),
|
|
usage: { ...assistantMessage("").usage, totalTokens: 7 },
|
|
},
|
|
});
|
|
await vi.waitFor(() => expect(delivered).toHaveLength(1));
|
|
expect(delivered[0]).toEqual({ status: "completed", text: "slow answer" });
|
|
expect(recorded).toEqual([0, 7]);
|
|
});
|
|
|
|
it("keeps waiting for siblings when background delivery is disabled", async () => {
|
|
const delivered: string[] = [];
|
|
const slow = new MockAssistantStream();
|
|
let hostCalls = 0;
|
|
const subagent = createSubagentTool({
|
|
getHost: () => {
|
|
hostCalls += 1;
|
|
if (hostCalls === 1) return host(() => done(assistantMessage("fast answer")));
|
|
return host(() => slow);
|
|
},
|
|
background: { enabled: () => false, deliver: (result) => delivered.push(result.text) },
|
|
});
|
|
|
|
const fast = subagent.execute("call-fast", { description: "fast task", task: "fast" });
|
|
const pending = subagent.execute("call-slow", { description: "slow task", task: "slow" });
|
|
|
|
await expect(fast).resolves.toMatchObject({ details: { status: "completed", text: "fast answer" } });
|
|
const settled = vi.fn();
|
|
void pending.then(settled);
|
|
await new Promise((resolve) => setTimeout(resolve, BACKGROUND_CUT_DELAY_MS + 100));
|
|
expect(settled).not.toHaveBeenCalled();
|
|
|
|
slow.push({ type: "done", reason: "stop", message: assistantMessage("slow answer") });
|
|
await expect(pending).resolves.toMatchObject({ details: { status: "completed", text: "slow answer" } });
|
|
expect(delivered).toEqual([]);
|
|
});
|
|
|
|
it("reports an unknown agent without starting a child", async () => {
|
|
const subagent = createSubagentTool({
|
|
getHost: () =>
|
|
host(() => {
|
|
throw new Error("model should not be called");
|
|
}),
|
|
});
|
|
const result = await subagent.execute("call", { description: "x", task: "x", agent: "scout" as "general" });
|
|
expect(result.details.status).toBe("error");
|
|
expect(result.content[0]).toMatchObject({ type: "text" });
|
|
expect((result.content[0] as { text: string }).text).toContain("Unknown subagent");
|
|
});
|
|
|
|
let tempDir: string | undefined;
|
|
afterEach(() => {
|
|
if (tempDir) rmSync(tempDir, { recursive: true, force: true });
|
|
tempDir = undefined;
|
|
});
|
|
|
|
it("is registered and active by default", async () => {
|
|
tempDir = join(tmpdir(), `pi-subagent-${Date.now()}`);
|
|
const agentDir = join(tempDir, "agent");
|
|
mkdirSync(agentDir, { recursive: true });
|
|
const settingsManager = SettingsManager.inMemory();
|
|
const resourceLoader = new DefaultResourceLoader({ cwd: tempDir, agentDir, settingsManager });
|
|
await resourceLoader.reload();
|
|
const { session } = await createAgentSession({
|
|
cwd: tempDir,
|
|
agentDir,
|
|
model: getModel("anthropic", "claude-sonnet-4-5")!,
|
|
settingsManager,
|
|
sessionManager: SessionManager.inMemory(tempDir),
|
|
resourceLoader,
|
|
});
|
|
expect(session.getAllTools().map((item) => item.name)).toContain("subagent");
|
|
expect(session.getActiveToolNames()).toContain("subagent");
|
|
session.dispose();
|
|
});
|
|
});
|