subagent-sync-failure.test.ts 20 KB

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