guarded-subagent.test.ts 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. createSessionId,
  4. SessionEventType,
  5. type PermissionBrokerRequest,
  6. type SessionEvent,
  7. } from "@zcode/contracts";
  8. import { createManualPermissionBroker } from "../src/permission/broker.js";
  9. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  10. import { createTestModelFactory } from "./test-runtime-model.js";
  11. import { createTestSessionEventStore } from "./test-event-store.js";
  12. describe("guarded real subagent ingress", () => {
  13. it.each([
  14. ["Explore", false],
  15. ["general-purpose", false],
  16. ["custom", false],
  17. ["general-purpose", true],
  18. ] as const)(
  19. "%s routes a real pending request to its parent (background=%s)",
  20. async (agentType, background) => {
  21. const requests: PermissionBrokerRequest[] = [];
  22. const execute = vi.fn(async () => {
  23. throw new Error("Must not execute");
  24. });
  25. let mainCalls = 0;
  26. let childCalls = 0;
  27. const childModelRequests: string[] = [];
  28. const eventStore = createTestSessionEventStore();
  29. const parentEvents: SessionEvent[] = [];
  30. const broker = createManualPermissionBroker({
  31. onRequest: (request) => {
  32. requests.push(request);
  33. },
  34. });
  35. const sessionId = createSessionId("guarded-parent");
  36. const runtime = createTestAgentRuntime(
  37. sessionId,
  38. {
  39. mode: "guarded",
  40. workingDirectory: "/workspace/guarded-fixture",
  41. bashShellSelection: {
  42. dialect: "posix",
  43. source: "auto-detected",
  44. display: { name: "bash" },
  45. },
  46. subagents: {
  47. profiles: [
  48. {
  49. name: "custom",
  50. description: "custom",
  51. source: "user",
  52. tools: ["Bash"],
  53. systemPrompt: "test",
  54. permissionMode: "bypassPermissions",
  55. },
  56. ],
  57. },
  58. },
  59. {
  60. eventStore,
  61. executionPort: { run: execute },
  62. permissionBroker: {
  63. requestPermission: (request, options) =>
  64. broker.requestPermission(request, { ...options, timeoutMs: 3000 }),
  65. },
  66. modelFactory: createTestModelFactory({
  67. async generateText(request, observation) {
  68. const child =
  69. (observation.invocationContext?.metadata as { querySource?: string })
  70. ?.querySource === "subagent";
  71. const usage = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
  72. if (child) childModelRequests.push(JSON.stringify(request));
  73. if (child && ++childCalls === 1)
  74. return {
  75. finishReason: "tool-calls",
  76. text: "",
  77. usage,
  78. toolCalls: [
  79. { id: "guarded-child-rm", name: "Bash", input: { command: "rm -rf fixture" } },
  80. ],
  81. };
  82. if (!child && ++mainCalls === 1)
  83. return {
  84. finishReason: "tool-calls",
  85. text: "",
  86. usage,
  87. toolCalls: [
  88. {
  89. id: "guarded-agent",
  90. name: "Agent",
  91. input: {
  92. description: "test",
  93. prompt: "test",
  94. subagent_type: agentType,
  95. run_in_background: background,
  96. },
  97. },
  98. ],
  99. };
  100. return { finishReason: "stop", text: "done", usage };
  101. },
  102. }),
  103. },
  104. );
  105. const unsubscribe = runtime.subscribeEvents({
  106. onSessionEvent: (event) => {
  107. if (event.sessionId === sessionId) parentEvents.push(event);
  108. },
  109. });
  110. const turn = runtime.executeTurn("Run the fixture child");
  111. await vi.waitFor(async () => {
  112. expect(requests).toHaveLength(1);
  113. expect(
  114. parentEvents.some((event) => event.type === SessionEventType.PermissionRequested),
  115. ).toBe(true);
  116. });
  117. expect(requests).toHaveLength(1);
  118. expect(requests[0]).toMatchObject({
  119. mode: "guarded",
  120. approvalMode: "user-once",
  121. sessionId,
  122. origin: { kind: "subagent" },
  123. });
  124. expect(execute).not.toHaveBeenCalled();
  125. const id = requests[0]!.requestId;
  126. expect(broker.listPendingRequests()).toHaveLength(1);
  127. expect(broker.resolvePermission(id, { decision: "deny", reason: "test denied" })).toBe(true);
  128. expect(broker.resolvePermission(id, { decision: "allow" })).toBe(false);
  129. await turn;
  130. await vi.waitFor(() =>
  131. expect(childModelRequests.some((request) => request.includes("test denied"))).toBe(true),
  132. );
  133. expect(
  134. parentEvents.filter((event) => event.type === SessionEventType.PermissionResolved),
  135. ).toHaveLength(1);
  136. expect(broker.listPendingRequests()).toEqual([]);
  137. expect(execute).not.toHaveBeenCalled();
  138. unsubscribe();
  139. },
  140. );
  141. });