subagent-tool-part-identity.test.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import { describe, expect, it } from "vitest";
  2. import { mkdtemp } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { createSessionId, SessionEventType, type SessionId } from "@zcode/contracts";
  6. import { createRecordingSubagentSessionStore } from "./subagent-test-store.js";
  7. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  8. import { createTestSessionEventStore } from "./test-event-store.js";
  9. import { createTestModelFactory } from "./test-runtime-model.js";
  10. // 回归 2026-11-10:子代理事实原来不落盘,父 transcript 里只有模型可见文本的 `agentId:`、`output_file:`
  11. // 行与启动回执前缀。冷加载重建 Agent 行、子会话目录查询、崩溃对账只能从文本里正则查找;同步失败的 part
  12. // 是 error 状态,`agentId:` 行只在 metadata.modelContent 里,冷加载读不到,行身份退回 tool call id、没有
  13. // 子会话入口。现在身份与后台启动事实结构化写进 Agent tool part 的 part.metadata。
  14. const AGENT_CALL_ID = "call_identity_agent";
  15. const usage = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
  16. async function runParentAgentCall(
  17. agentInput: Record<string, unknown>,
  18. child: (parentTurnDone: Promise<void>) => Promise<unknown>,
  19. subagents: { autoBackgroundMs?: number } = {},
  20. ) {
  21. const sessionId = createSessionId(`runtime-agent-part-identity-${crypto.randomUUID()}`);
  22. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-agent-part-identity-"));
  23. const eventStore = createTestSessionEventStore();
  24. const sessionStore = createRecordingSubagentSessionStore();
  25. const parentTurnDone = Promise.withResolvers<void>();
  26. let parentCalls = 0;
  27. const runtime = createTestAgentRuntime(
  28. sessionId,
  29. {
  30. mode: "build",
  31. workingDirectory: "/workspace/project",
  32. // 这些用例按前台 Agent 写成,关闭「Agent 总在后台」开关(07-subagent.md「ZCode 当前实现」)。
  33. subagents: { outputRootDir, alwaysBackground: false, ...subagents },
  34. },
  35. {
  36. eventStore,
  37. sessionStore,
  38. modelFactory: createTestModelFactory({
  39. async generateText(_request: unknown, observation: any) {
  40. if (observation.invocationContext?.metadata?.querySource === "subagent") {
  41. return child(parentTurnDone.promise);
  42. }
  43. parentCalls++;
  44. if (parentCalls > 1) return { finishReason: "stop", text: "parent done", usage };
  45. return {
  46. finishReason: "tool-calls",
  47. text: "",
  48. toolCalls: [{ id: AGENT_CALL_ID, name: "Agent", input: agentInput }],
  49. usage,
  50. };
  51. },
  52. } as never),
  53. },
  54. );
  55. await runtime.executeTurn("Use an agent to review the module");
  56. parentTurnDone.resolve();
  57. await (
  58. runtime as unknown as { subagentPort?: { waitForIdle?: () => Promise<void> } }
  59. ).subagentPort?.waitForIdle?.();
  60. const messages = await sessionStore.messages({ sessionID: sessionId });
  61. // 测试 store 每次保存都追加一份,真实 store 按 part id 覆盖:取最后保存的那份。
  62. const agentPart = messages
  63. .flatMap((message) => message.parts)
  64. .filter((part) => part.type === "tool" && part.callID === AGENT_CALL_ID)
  65. .at(-1);
  66. const spawned = (await eventStore.getEvents(sessionId)).find(
  67. (event) => event.type === SessionEventType.SubagentSpawned,
  68. );
  69. await runtime.close();
  70. return {
  71. agentPart: agentPart as
  72. | { metadata?: Record<string, unknown>; state: { status: string } }
  73. | undefined,
  74. outputDirOf: (agentId: string | undefined) => join(outputRootDir, sessionId, agentId ?? ""),
  75. spawned: spawned?.payload as { agentId?: string; childSessionId?: SessionId } | undefined,
  76. };
  77. }
  78. const reviewInput = {
  79. description: "Review module",
  80. prompt: "Review the module.",
  81. subagent_type: "general-purpose",
  82. };
  83. describe("Agent tool part subagent facts", () => {
  84. it.each([
  85. [
  86. "a completed sync agent",
  87. reviewInput,
  88. async () => ({ finishReason: "stop", text: "Findings: module A is fine.", usage }),
  89. {},
  90. "completed",
  91. false,
  92. ],
  93. [
  94. "a sync agent that failed after its child session was ready",
  95. reviewInput,
  96. async () => {
  97. throw new Error("Provider rate limited the request (HTTP 429)");
  98. },
  99. {},
  100. "error",
  101. false,
  102. ],
  103. [
  104. "a background agent launch",
  105. { ...reviewInput, run_in_background: true },
  106. async () => ({ finishReason: "stop", text: "Background findings.", usage }),
  107. {},
  108. "completed",
  109. true,
  110. ],
  111. [
  112. "a foreground agent moved to the background",
  113. reviewInput,
  114. async (parentTurnDone: Promise<void>) => {
  115. // 父轮结束前 child 不返回:前台等待一定先被自动转后台打断。
  116. await parentTurnDone;
  117. return { finishReason: "stop", text: "Findings after moving.", usage };
  118. },
  119. { autoBackgroundMs: 1 },
  120. "completed",
  121. true,
  122. ],
  123. ] as const)(
  124. "stores the facts on %s",
  125. async (_name, input, child, subagents, partStatus, background) => {
  126. const { agentPart, outputDirOf, spawned } = await runParentAgentCall(input, child, subagents);
  127. expect(agentPart?.state.status).toBe(partStatus);
  128. expect(spawned?.agentId).toMatch(/^agent_/);
  129. // 与 SubagentSpawned 同一份值:两处身份来自 child session 就绪的同一时刻。同步、后台都记下 runner
  130. // 为这次运行定下的输出文件(metadata.json 在同一目录),冷恢复按它找,不按当前存储配置推算。
  131. expect(agentPart?.metadata).toMatchObject({
  132. agentId: spawned?.agentId,
  133. childSessionId: spawned?.childSessionId,
  134. outputFile: join(outputDirOf(spawned?.agentId), "output.txt"),
  135. });
  136. expect(spawned?.childSessionId).toBe(createSessionId(`subagent_${spawned?.agentId}`));
  137. if (background) {
  138. expect(agentPart?.metadata).toMatchObject({ background: true });
  139. } else {
  140. expect(agentPart?.metadata).not.toHaveProperty("background");
  141. }
  142. },
  143. );
  144. it("stores no facts when the agent fails before a child session exists", async () => {
  145. const { agentPart, spawned } = await runParentAgentCall(
  146. { ...reviewInput, subagent_type: "missing-agent-type" },
  147. async () => {
  148. throw new Error("a child must not start");
  149. },
  150. );
  151. expect(agentPart?.state.status).toBe("error");
  152. expect(spawned).toBeUndefined();
  153. expect(agentPart?.metadata).not.toHaveProperty("agentId");
  154. expect(agentPart?.metadata).not.toHaveProperty("childSessionId");
  155. expect(agentPart?.metadata).not.toHaveProperty("outputFile");
  156. });
  157. });