subagent-sync-failure.test.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. import { describe, expect, it, vi } from "vitest";
  2. import { mkdtemp, readFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { dirname, join } from "node:path";
  5. import {
  6. AgentErrorCode,
  7. CoreErrorType,
  8. SEND_MESSAGE_TOOL_NAME,
  9. SessionEventType,
  10. createSessionEvent,
  11. createSessionId,
  12. createToolCallId,
  13. createTraceId,
  14. createTurnId,
  15. isCoreError,
  16. readAgentFailureHandback,
  17. type Logger,
  18. type SessionEvent,
  19. type SessionId,
  20. } from "@zcode/contracts";
  21. import { createTurnFailureError } from "../src/runtime/helpers/turn-errors.js";
  22. import {
  23. createExploreSubagentPort,
  24. type ExploreSubagentPortOptions,
  25. } from "../src/subagent/runner.js";
  26. import { createErrorResult } from "../src/tool/executor/errors.js";
  27. import { agentToolEntry } from "../src/tool/handlers/agent.js";
  28. import { createRecordingSubagentSessionStore } from "./subagent-test-store.js";
  29. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  30. import { createTestSessionEventStore } from "./test-event-store.js";
  31. import { createTestModelFactory } from "./test-runtime-model.js";
  32. // 回归 2026-11-09:同步子代理跑了几十步后 provider 限流,父模型只收到 429 原文、没有 agentId,
  33. // 无法用 SendMessage 续接。工具调用仍是失败;只给模型的文本附部分报告(有正文时)、agentId 行和 usage。
  34. const PROVIDER_FAILURE = "Provider rate limited the request (HTTP 429)";
  35. const PARTIAL_OUTPUT_NOTE = "Everything below is PARTIAL output recovered from the agent";
  36. const AGENT_ID_LINE =
  37. /agentId: (agent_[\w-]+) \(use SendMessage with to: '\1', summary: '<5-10 word recap>' to continue this agent\)/;
  38. function createFailingChildScenario(childSteps: (step: number) => unknown) {
  39. const sessionId = createSessionId(`runtime-sync-subagent-failure-${crypto.randomUUID()}`);
  40. const eventStore = createTestSessionEventStore();
  41. const parentRequests: any[] = [];
  42. let parentCallCount = 0;
  43. let childCallCount = 0;
  44. const runtime = createTestAgentRuntime(
  45. sessionId,
  46. {
  47. mode: "build",
  48. workingDirectory: "/workspace/project",
  49. // 这些用例按前台 Agent 写成,关闭「Agent 总在后台」开关(07-subagent.md「ZCode 当前实现」)。
  50. subagents: { alwaysBackground: false },
  51. },
  52. {
  53. eventStore,
  54. sessionStore: createRecordingSubagentSessionStore(),
  55. modelFactory: createTestModelFactory({
  56. async generateText(request: any) {
  57. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  58. if (toolNames.includes("Agent")) {
  59. parentRequests.push(request);
  60. parentCallCount++;
  61. if (parentCallCount === 1) {
  62. return {
  63. finishReason: "tool-calls",
  64. providerMetadata: undefined,
  65. text: "",
  66. toolCalls: [
  67. {
  68. id: "call_failing_explore",
  69. name: "Agent",
  70. input: {
  71. description: "Review module",
  72. prompt: "Review the module and report findings.",
  73. subagent_type: "Explore",
  74. },
  75. },
  76. ],
  77. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  78. };
  79. }
  80. return {
  81. finishReason: "stop",
  82. providerMetadata: undefined,
  83. text: "parent saw the failure",
  84. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  85. };
  86. }
  87. childCallCount++;
  88. return childSteps(childCallCount);
  89. },
  90. } as never),
  91. },
  92. );
  93. return { eventStore, parentRequests, runtime, sessionId };
  94. }
  95. function childTodoStep(text: string, id: string) {
  96. return {
  97. finishReason: "tool-calls",
  98. providerMetadata: undefined,
  99. text,
  100. toolCalls: [
  101. {
  102. id,
  103. name: "TodoWrite",
  104. input: {
  105. todos: [{ content: "Review the module", priority: "high", status: "in_progress" }],
  106. },
  107. },
  108. ],
  109. usage: { inputTokens: 3, outputTokens: 4, totalTokens: 7 },
  110. };
  111. }
  112. const FAILED_AGENT_TOOL_CALL = { id: "call_failed_agent", input: {}, name: "Agent" };
  113. // 端口级场景:桩掉 runExploreAgent,直接驱动 runner 的失败分支。
  114. async function runPortChild(
  115. agentId: string,
  116. runExploreAgent: ExploreSubagentPortOptions["runExploreAgent"],
  117. options: Partial<ExploreSubagentPortOptions> = {},
  118. ) {
  119. const port = createExploreSubagentPort({
  120. createAgentId: () => agentId,
  121. outputRootDir: await mkdtemp(join(tmpdir(), "zcode-subagent-sync-failure-")),
  122. async emitParentEvent() {},
  123. runExploreAgent,
  124. ...options,
  125. });
  126. const sessionId = createSessionId(`parent_${agentId}`);
  127. const turnId = createTurnId(`turn_${agentId}`);
  128. const rejection = port
  129. .run({
  130. agentType: "Explore",
  131. description: "Port child",
  132. parentToolCallId: createToolCallId(`call_${agentId}`),
  133. prompt: "Review the module.",
  134. sessionId,
  135. trace: { traceId: createTraceId(), sessionId, turnId },
  136. turnId,
  137. workingDirectory: "/tmp",
  138. workspaceRoot: "/tmp",
  139. })
  140. .then(
  141. () => undefined,
  142. (error: unknown) => error,
  143. );
  144. return { port, rejection };
  145. }
  146. // runPortChild 那个子代理的 SendMessage 续接请求,父会话与 runPortChild 相同。
  147. function continueRequest(agentId: string) {
  148. const sessionId = createSessionId(`parent_${agentId}`);
  149. const turnId = createTurnId(`turn_continue_${agentId}`);
  150. return {
  151. message: "Continue the review.",
  152. parentToolCallId: createToolCallId(`call_continue_${agentId}`),
  153. sessionId,
  154. to: agentId,
  155. trace: { traceId: createTraceId(), sessionId, turnId },
  156. turnId,
  157. workingDirectory: "/tmp",
  158. workspaceRoot: "/tmp",
  159. };
  160. }
  161. function childModelStep(sessionId: SessionId, text: string, toolCallCount: number) {
  162. return createSessionEvent(SessionEventType.ModelComplete, sessionId, {
  163. content: text,
  164. querySource: "subagent",
  165. toolCallCount,
  166. usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 },
  167. });
  168. }
  169. describe("sync subagent failure hand-back", () => {
  170. it("gives the parent model the partial report and agentId while the call stays failed", async () => {
  171. const { eventStore, parentRequests, runtime, sessionId } = createFailingChildScenario(
  172. (step) => {
  173. if (step === 1) return childTodoStep("Interim findings: module A is fine.", "call_todo_1");
  174. if (step === 2) return childTodoStep("", "call_todo_2");
  175. throw new Error(PROVIDER_FAILURE);
  176. },
  177. );
  178. const result = await runtime.executeTurn("Use an explore agent to review the module");
  179. const parentToolMessage = parentRequests[1].messages.find(
  180. (message: any) => message.role === "tool",
  181. );
  182. const modelText = String(parentToolMessage.content);
  183. expect(result.response).toBe("parent saw the failure");
  184. expect(modelText.startsWith(PROVIDER_FAILURE)).toBe(true);
  185. expect(modelText).toContain(PARTIAL_OUTPUT_NOTE);
  186. expect(modelText).toContain("[Subagent hand-back]");
  187. expect(modelText).toContain(" Interim findings: module A is fine.");
  188. expect(modelText).toMatch(AGENT_ID_LINE);
  189. expect(modelText).toContain("<usage>subagent_tokens: 14\ntool_uses: 2\nduration_ms: ");
  190. // 截断说明在原文之后、部分报告之前;agentId 行在部分报告之后。
  191. expect(modelText.indexOf(PARTIAL_OUTPUT_NOTE)).toBeLessThan(
  192. modelText.indexOf("[Subagent hand-back]"),
  193. );
  194. expect(modelText.indexOf("Interim findings")).toBeLessThan(modelText.search(AGENT_ID_LINE));
  195. // UI 与 App 读的错误摘要不变:只有 provider 原文,不带 agentId 和部分报告。
  196. const events = await eventStore.getEvents(sessionId);
  197. const toolError = events.find((event) => event.type === SessionEventType.ToolCallError);
  198. expect((toolError?.payload as any)?.error?.message).toBe(PROVIDER_FAILURE);
  199. expect(JSON.stringify(toolError?.payload)).not.toContain("agentId:");
  200. expect(JSON.stringify(toolError?.payload)).not.toContain("Interim findings");
  201. const stopped = events.find((event) => event.type === SessionEventType.SubagentStopped);
  202. expect((stopped?.payload as any)?.status).toBe("failed");
  203. });
  204. it("still gives the agentId when the child failed before writing any text", async () => {
  205. const { parentRequests, runtime } = createFailingChildScenario(() => {
  206. throw new Error(PROVIDER_FAILURE);
  207. });
  208. await runtime.executeTurn("Use an explore agent to review the module");
  209. const parentToolMessage = parentRequests[1].messages.find(
  210. (message: any) => message.role === "tool",
  211. );
  212. const modelText = String(parentToolMessage.content);
  213. expect(modelText.startsWith(PROVIDER_FAILURE)).toBe(true);
  214. expect(modelText).toMatch(AGENT_ID_LINE);
  215. expect(modelText).toContain("tool_uses: 0");
  216. expect(modelText).not.toContain(PARTIAL_OUTPUT_NOTE);
  217. expect(modelText).not.toContain("[Subagent hand-back]");
  218. });
  219. it("adds no hand-back when the child fails before its session is ready", async () => {
  220. const { rejection } = await runPortChild("agent_pre_ready_failure", async () => {
  221. throw new Error(PROVIDER_FAILURE);
  222. });
  223. const error = await rejection;
  224. expect(error).toBeInstanceOf(Error);
  225. expect(readAgentFailureHandback(error)).toBeUndefined();
  226. expect(agentToolEntry.formatErrorModelContent?.(error)).toBeUndefined();
  227. });
  228. it("keeps the original CoreError, its stack and its UI summary when it attaches the hand-back", async () => {
  229. // 回归评审 P1:曾复制错误再挂数据,Node 的 stack accessor 在复制品上读到 undefined。
  230. const providerError = Object.assign(new Error(PROVIDER_FAILURE), {
  231. code: "model_rate_limited",
  232. name: "AiSdkModelAdapterError",
  233. });
  234. const turnError = createTurnFailureError(providerError, undefined, "Turn execution failed");
  235. const originalStack = turnError.stack;
  236. const uiErrorBefore = createErrorResult(FAILED_AGENT_TOOL_CALL, turnError).error;
  237. const { rejection } = await runPortChild("agent_core_error_failure", async (request) => {
  238. await request.onSessionReady?.();
  239. request.onEvent?.(childModelStep(request.sessionId, "Core error findings.", 1));
  240. throw turnError;
  241. });
  242. const error = await rejection;
  243. expect(error).toBe(turnError);
  244. expect(typeof originalStack).toBe("string");
  245. expect((error as Error).stack).toBe(originalStack);
  246. expect(Object.keys(error as object)).not.toContain("agentFailureHandback");
  247. expect(readAgentFailureHandback(error)).toMatchObject({
  248. agentId: "agent_core_error_failure",
  249. report: "Core error findings.",
  250. totalTokens: 5,
  251. totalToolUseCount: 1,
  252. });
  253. const result = createErrorResult(FAILED_AGENT_TOOL_CALL, error as Error, 0, {
  254. modelNote: agentToolEntry.formatErrorModelContent?.(error),
  255. });
  256. expect(result.error).toEqual(uiErrorBefore);
  257. expect(String(result.modelContent).startsWith(PROVIDER_FAILURE)).toBe(true);
  258. expect(String(result.modelContent)).toContain(" Core error findings.");
  259. });
  260. it("attaches the hand-back to the lifecycle wrapper when the child throws a plain error", async () => {
  261. const { rejection } = await runPortChild("agent_plain_error_failure", async (request) => {
  262. await request.onSessionReady?.();
  263. request.onEvent?.(childModelStep(request.sessionId, "Wrapper findings.", 2));
  264. throw new Error(PROVIDER_FAILURE);
  265. });
  266. const error = await rejection;
  267. expect(isCoreError(error)).toBe(true);
  268. if (!isCoreError(error)) return;
  269. expect(error.type).toBe(CoreErrorType.ToolExecutionFailed);
  270. expect(error.context?.code).toBe(AgentErrorCode.CHILD_RUNTIME_FAILED);
  271. expect(typeof error.stack).toBe("string");
  272. expect(readAgentFailureHandback(error)).toMatchObject({
  273. report: "Wrapper findings.",
  274. totalToolUseCount: 2,
  275. });
  276. const result = createErrorResult(FAILED_AGENT_TOOL_CALL, error, 0, {
  277. modelNote: agentToolEntry.formatErrorModelContent?.(error),
  278. });
  279. expect(result.error?.message).toBe(PROVIDER_FAILURE);
  280. expect(result.error?.stack).toBe(error.stack);
  281. expect(String(result.modelContent)).toContain(PARTIAL_OUTPUT_NOTE);
  282. expect(String(result.modelContent)).toMatch(AGENT_ID_LINE);
  283. });
  284. it("counts billed failed requests and ignores events from other sessions in the hand-back", async () => {
  285. // 回归评审 P3-1 / P3-2:用量口径与同步完成相同,计入已计费的失败请求;
  286. // sink 还会转发其他 session 的事件,只认本 child session 的 step。
  287. const { rejection } = await runPortChild("agent_usage_failure", async (request) => {
  288. await request.onSessionReady?.();
  289. request.onEvent?.(childModelStep(request.sessionId, "Own findings.", 1));
  290. request.onEvent?.(
  291. createSessionEvent(SessionEventType.ModelNetworkStatus, request.sessionId, {
  292. type: "model_request_failed",
  293. usage: { inputTokens: 6, outputTokens: 3, totalTokens: 9 },
  294. }),
  295. );
  296. request.onEvent?.(
  297. childModelStep(createSessionId("sess_other_session"), "Foreign findings.", 4),
  298. );
  299. throw new Error(PROVIDER_FAILURE);
  300. });
  301. const error = await rejection;
  302. expect(readAgentFailureHandback(error)).toMatchObject({
  303. report: "Own findings.",
  304. totalTokens: 14,
  305. totalToolUseCount: 1,
  306. });
  307. });
  308. it("records the provider text, not the turn wrapper, in the failed task and its artifacts", async () => {
  309. // 回归:同步失败分支原来直接读 error.message,child turn 的 wrapper 文字 "Turn execution failed"
  310. // 盖住了 provider 原文,TaskOutput、metadata.json、输出文件和 SubagentStopped 都看不到真实原因。
  311. const events: SessionEvent[] = [];
  312. const { port, rejection } = await runPortChild(
  313. "agent_failure_artifacts",
  314. async (request) => {
  315. await request.onSessionReady?.();
  316. throw createTurnFailureError(
  317. new Error(PROVIDER_FAILURE),
  318. undefined,
  319. "Turn execution failed",
  320. );
  321. },
  322. {
  323. async emitParentEvent(event) {
  324. events.push(event);
  325. },
  326. },
  327. );
  328. await rejection;
  329. const task = await port.getTask?.("agent_failure_artifacts");
  330. expect(task).toMatchObject({ status: "failed", error: PROVIDER_FAILURE });
  331. const outputDir = dirname(task!.outputFile!);
  332. const metadata = JSON.parse(await readFile(join(outputDir, "metadata.json"), "utf8"));
  333. expect(metadata).toMatchObject({ status: "failed", error: PROVIDER_FAILURE });
  334. expect(await readFile(task!.outputFile!, "utf8")).toBe(PROVIDER_FAILURE);
  335. expect(await readFile(join(outputDir, "task.output"), "utf8")).toBe(PROVIDER_FAILURE);
  336. expect(
  337. events.find((event) => event.type === SessionEventType.SubagentStopped)?.payload,
  338. ).toMatchObject({ status: "failed", error: PROVIDER_FAILURE });
  339. });
  340. it("adds no hand-back when the user stops the child", async () => {
  341. let markRunning!: () => void;
  342. const running = new Promise<void>((resolve) => {
  343. markRunning = resolve;
  344. });
  345. const { port, rejection } = await runPortChild(
  346. "agent_user_stopped",
  347. async (request, options) => {
  348. await request.onSessionReady?.();
  349. request.onEvent?.(childModelStep(request.sessionId, "Findings before the stop.", 1));
  350. markRunning();
  351. return new Promise((_, reject) => {
  352. options?.signal?.addEventListener("abort", () => reject(options.signal?.reason), {
  353. once: true,
  354. });
  355. });
  356. },
  357. );
  358. await running;
  359. await port.stopTask?.("agent_user_stopped", { initiator: "user" });
  360. const error = await rejection;
  361. expect(isCoreError(error) && error.type).toBe(CoreErrorType.ToolCancelled);
  362. expect(readAgentFailureHandback(error)).toBeUndefined();
  363. });
  364. it("attaches the hand-back and keeps the timeout type when the inactivity watchdog fails the child", async () => {
  365. const { rejection } = await runPortChild(
  366. "agent_inactive_failure",
  367. async (request) => {
  368. await request.onSessionReady?.();
  369. request.onEvent?.(childModelStep(request.sessionId, "Findings before going quiet.", 1));
  370. return new Promise(() => {});
  371. },
  372. { inactivityTimeoutMs: 20 },
  373. );
  374. const error = await rejection;
  375. expect(isCoreError(error) && error.type).toBe(CoreErrorType.ToolTimeout);
  376. expect(readAgentFailureHandback(error)?.report).toBe("Findings before going quiet.");
  377. expect(agentToolEntry.formatErrorModelContent?.(error)).toMatch(AGENT_ID_LINE);
  378. });
  379. it("refuses SendMessage while the watchdog-failed child is still stopping, then resumes it", async () => {
  380. // 回归:看门狗超时后 task 先记 failed,父模型马上拿到 agentId;child 收到中止后可能还没结束,
  381. // 这时恢复会在同一个 child session 上同时跑两个 runtime。
  382. const prompts: string[] = [];
  383. let releaseFirstRun!: () => void;
  384. const info = vi.fn();
  385. const { port, rejection } = await runPortChild(
  386. "agent_still_stopping",
  387. async (request) => {
  388. prompts.push(request.prompt);
  389. await request.onSessionReady?.();
  390. if (prompts.length > 1) {
  391. return { events: [], response: "Resumed findings.", traceId: "trace_resumed" };
  392. }
  393. // 第一次运行不响应中止,直到测试放行。
  394. await new Promise<void>((resolve) => {
  395. releaseFirstRun = resolve;
  396. });
  397. throw new Error("The aborted run finally stopped");
  398. },
  399. {
  400. inactivityTimeoutMs: 20,
  401. logger: { debug() {}, info, warn() {}, error() {} } as unknown as Logger,
  402. },
  403. );
  404. const error = await rejection;
  405. expect(isCoreError(error) && error.type).toBe(CoreErrorType.ToolTimeout);
  406. const refused = await port.sendMessage!(continueRequest("agent_still_stopping"));
  407. expect(refused).toMatchObject({ status: "failed" });
  408. expect(refused.error).toContain("its previous run is still stopping");
  409. expect(info).toHaveBeenCalledWith(
  410. expect.any(String),
  411. expect.objectContaining({
  412. agentId: "agent_still_stopping",
  413. event: "subagent.send_message.resume_refused",
  414. reason: "previous_run_stopping",
  415. }),
  416. );
  417. expect(prompts).toHaveLength(1);
  418. expect((await port.getTask?.("agent_still_stopping"))?.status).toBe("failed");
  419. releaseFirstRun();
  420. // 桩抛错、执行 promise reject、port 移除运行记录都只经过微任务,等一个宏任务就全部完成。
  421. await new Promise((resolve) => setTimeout(resolve, 0));
  422. const resumed = await port.sendMessage!(continueRequest("agent_still_stopping"));
  423. expect(resumed).toMatchObject({ status: "success", delivery: "resumed_background" });
  424. expect((await port.waitForTask?.("agent_still_stopping"))?.status).toBe("completed");
  425. expect(prompts).toEqual(["Review the module.", "Continue the review."]);
  426. });
  427. it("lets the parent continue the failed child through SendMessage with the handed-back agentId", async () => {
  428. const sessionId = createSessionId(`runtime-sync-subagent-continue-${crypto.randomUUID()}`);
  429. const resumedChildRequests: string[] = [];
  430. const sendMessageResults: string[] = [];
  431. const usage = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
  432. let continuedAgentId = "";
  433. let parentCalls = 0;
  434. let childCalls = 0;
  435. const toolMessageText = (request: any) =>
  436. (request.messages ?? [])
  437. .filter((message: any) => message.role === "tool")
  438. .map((message: any) => String(message.content))
  439. .join("\n");
  440. const runtime = createTestAgentRuntime(
  441. sessionId,
  442. {
  443. mode: "build",
  444. workingDirectory: "/workspace/project",
  445. // 这些用例按前台 Agent 写成,关闭「Agent 总在后台」开关(07-subagent.md「ZCode 当前实现」)。
  446. subagents: { alwaysBackground: false },
  447. },
  448. {
  449. eventStore: createTestSessionEventStore(),
  450. sessionStore: createRecordingSubagentSessionStore(),
  451. modelFactory: createTestModelFactory({
  452. async generateText(request: any, observation: any) {
  453. if (observation.invocationContext?.metadata?.querySource !== "subagent") {
  454. parentCalls++;
  455. if (parentCalls === 1) {
  456. return {
  457. finishReason: "tool-calls",
  458. text: "",
  459. toolCalls: [
  460. {
  461. id: "call_failing_explore",
  462. name: "Agent",
  463. input: {
  464. description: "Review module",
  465. prompt: "Review the module and report findings.",
  466. subagent_type: "Explore",
  467. },
  468. },
  469. ],
  470. usage,
  471. };
  472. }
  473. if (parentCalls === 2) {
  474. // 父模型只能从失败的 Agent 结果里读到 agentId,再用它发 SendMessage。
  475. continuedAgentId = toolMessageText(request).match(AGENT_ID_LINE)?.[1] ?? "";
  476. return {
  477. finishReason: "tool-calls",
  478. text: "",
  479. toolCalls: [
  480. {
  481. id: "call_continue_child",
  482. name: SEND_MESSAGE_TOOL_NAME,
  483. input: {
  484. to: continuedAgentId,
  485. summary: "continue the review",
  486. message: "Continue the review from where you stopped.",
  487. },
  488. },
  489. ],
  490. usage,
  491. };
  492. }
  493. // 只记录紧跟 SendMessage 的这次调用;子代理完成后的后台通知还会再开一轮父会话调用。
  494. if (parentCalls === 3) sendMessageResults.push(toolMessageText(request));
  495. return { finishReason: "stop", text: "parent done", usage };
  496. }
  497. childCalls++;
  498. if (childCalls === 1) {
  499. return childTodoStep("Interim findings: module A is fine.", "call_todo_1");
  500. }
  501. if (childCalls === 2) throw new Error(PROVIDER_FAILURE);
  502. resumedChildRequests.push(JSON.stringify(request.messages));
  503. return { finishReason: "stop", text: "Final review report.", usage };
  504. },
  505. } as never),
  506. },
  507. );
  508. const subagentPort = (runtime as unknown as { subagentPort: any }).subagentPort;
  509. const result = await runtime.executeTurn("Use an explore agent to review the module");
  510. const resumed = await subagentPort.waitForTask(continuedAgentId);
  511. expect(result.response).toBe("parent done");
  512. expect(continuedAgentId).toMatch(/^agent_/);
  513. expect(sendMessageResults.join("\n")).toContain("resumed it in the background");
  514. expect(resumed).toMatchObject({ agentId: continuedAgentId, status: "completed" });
  515. expect(childCalls).toBe(3);
  516. expect(resumedChildRequests[0]).toContain("Interim findings: module A is fine.");
  517. expect(resumedChildRequests[0]).toContain("Continue the review from where you stopped.");
  518. });
  519. });