tool-search-subagent.test.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. import { expect, it } from "vitest";
  2. import { createSessionId, type Model, type ModelRequest } from "@zcode/contracts";
  3. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  4. import { createTestModelFactory } from "./test-runtime-model.js";
  5. import { createTestSessionEventStore } from "./test-event-store.js";
  6. it.each([
  7. { force: false, childCodingPlan: false, searchAllowed: true, local: true, explore: true },
  8. { force: false, childCodingPlan: false, searchAllowed: true, local: true },
  9. { force: false, childCodingPlan: false, searchAllowed: false, local: true },
  10. { force: false, childCodingPlan: false, searchAllowed: true },
  11. { force: false, childCodingPlan: true, searchAllowed: true },
  12. { force: true, childCodingPlan: false, searchAllowed: true },
  13. { force: true, childCodingPlan: false, searchAllowed: false },
  14. ])(
  15. "uses the child Model, startup override, independent discovery and allowed scope: %j",
  16. async ({ force, childCodingPlan, searchAllowed, local = false, explore = false }) => {
  17. const childRequests: ModelRequest[] = [];
  18. const parentRequests: ModelRequest[] = [];
  19. const childEnabled = (local || force || childCodingPlan) && searchAllowed;
  20. // 内置 Explore 白名单里的 WebFetch/WebSearch/TodoWrite 已常驻,只剩子会话控制通道
  21. // RespondToCoordinator 是 deferred;自定义 profile 用白名单里的 TaskOutput。
  22. const target = explore ? "RespondToCoordinator" : "TaskOutput";
  23. const factory = createTestModelFactory({
  24. async generateText(request, observation) {
  25. const child = observation.invocationContext?.metadata?.querySource === "subagent";
  26. const requests = child ? childRequests : parentRequests;
  27. requests.push(request);
  28. if (!child && requests.length === 1)
  29. return {
  30. text: "",
  31. usage: {},
  32. finishReason: "tool-calls",
  33. toolCalls: [
  34. {
  35. id: "spawn",
  36. name: "Agent",
  37. input: {
  38. description: "Search scoped tools",
  39. prompt: `Discover ${target}`,
  40. subagent_type: explore ? "Explore" : "researcher",
  41. },
  42. },
  43. ],
  44. };
  45. if (child && childEnabled && requests.length === 1)
  46. return {
  47. text: "",
  48. usage: {},
  49. finishReason: "tool-calls",
  50. toolCalls: [
  51. {
  52. id: "child-search",
  53. name: local ? "LocalToolSearch" : "ToolSearch",
  54. input: { query: explore ? `select:${target}` : `select:${target},TodoRead` },
  55. },
  56. ],
  57. };
  58. return { text: "done", usage: {}, finishReason: "stop" };
  59. },
  60. });
  61. const withCapability = (model: Model): Model => ({
  62. ...model,
  63. requestCapabilities: {
  64. toolSearch: {
  65. protocolSupported: true,
  66. defaultEnabled: model.modelId === "child" ? childCodingPlan : true,
  67. },
  68. },
  69. bind: (options) => withCapability(model.bind(options)),
  70. });
  71. const runtime = createTestAgentRuntime(
  72. createSessionId("toolsearch-subagent"),
  73. {
  74. mode: "yolo",
  75. modelStreaming: "off",
  76. titleGeneration: { enabled: false },
  77. toolSearch: { mode: local ? "local" : force ? "native" : "auto" },
  78. modelSelection: { providerId: "test", modelId: "parent" },
  79. // 这些用例按前台 Agent 写成,关闭「Agent 总在后台」开关(07-subagent.md「ZCode 当前实现」)。
  80. subagents: explore
  81. ? { alwaysBackground: false }
  82. : {
  83. alwaysBackground: false,
  84. profiles: [
  85. {
  86. name: "researcher",
  87. description: "Research",
  88. source: "user",
  89. systemPrompt: "Search tools",
  90. modelSelection: { providerId: "test", modelId: "child" },
  91. tools: searchAllowed
  92. ? ["ToolSearch", ...(local ? ["DeferredToolCall"] : []), "TaskOutput"]
  93. : ["TaskOutput"],
  94. },
  95. ],
  96. },
  97. },
  98. {
  99. eventStore: createTestSessionEventStore(),
  100. modelFactory: (input) => withCapability(factory(input)),
  101. },
  102. );
  103. try {
  104. await runtime.executeTurn("Run the researcher.");
  105. expect(childRequests.length).toBe(childEnabled ? 2 : 1);
  106. expect(childRequests[0]?.toolSearchEnabled).toBe(childEnabled && !local);
  107. expect(
  108. childRequests[0]?.tools?.some(
  109. (tool) => tool.name === (local ? "LocalToolSearch" : "ToolSearch"),
  110. ),
  111. ).toBe(childEnabled);
  112. if (childEnabled) {
  113. expect(childRequests[0]?.tools?.some((tool) => tool.name === target)).toBe(false);
  114. if (local) {
  115. expect(childRequests[1]?.tools).toEqual(childRequests[0]?.tools);
  116. expect(JSON.stringify(childRequests[1]?.messages)).toContain("<functions>");
  117. // Local 把发现结果展开成 <functions> 文本,不会出现 "toolName";按定义名核对,
  118. // 作用域外的 TodoRead 不能被展开。
  119. const result = childRequests[1]?.messages.find((message) => message.role === "tool");
  120. const text = (Array.isArray(result?.content) ? result.content : [])
  121. .map((part) => ("text" in part && typeof part.text === "string" ? part.text : ""))
  122. .join("\n");
  123. const loaded = [...text.matchAll(/<function>(.*?)<\/function>/gu)].map(
  124. (match) => (JSON.parse(match[1]!) as { name: string }).name,
  125. );
  126. expect(loaded).toEqual([target]);
  127. } else {
  128. expect(childRequests[1]?.tools?.find((tool) => tool.name === target)?.deferLoading).toBe(
  129. true,
  130. );
  131. expect(
  132. childRequests[1]?.messages.find((message) => message.role === "tool")?.content,
  133. ).toEqual([{ type: "tool_reference", toolName: target }]);
  134. }
  135. } else expect(childRequests[0]?.tools?.some((tool) => tool.name === target)).toBe(true);
  136. // 子会话的发现不回流父会话:父会话末轮工具列表与首轮相同,历史里也没有 Local 展开的定义。
  137. // 只断言 target 不在父会话工具里会在 Local 与 Explore 行恒为真,因此对照整份列表。
  138. expect(parentRequests).toHaveLength(2);
  139. expect(parentRequests[1]?.tools).toEqual(parentRequests[0]?.tools);
  140. expect(JSON.stringify(parentRequests[1]?.messages)).not.toContain("<functions>");
  141. } finally {
  142. await runtime.closeBrowserSession();
  143. }
  144. },
  145. );