tool-search-subagent.test.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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. subagents: explore
  80. ? undefined
  81. : {
  82. profiles: [
  83. {
  84. name: "researcher",
  85. description: "Research",
  86. source: "user",
  87. systemPrompt: "Search tools",
  88. modelSelection: { providerId: "test", modelId: "child" },
  89. tools: searchAllowed
  90. ? ["ToolSearch", ...(local ? ["DeferredToolCall"] : []), "TaskOutput"]
  91. : ["TaskOutput"],
  92. },
  93. ],
  94. },
  95. },
  96. {
  97. eventStore: createTestSessionEventStore(),
  98. modelFactory: (input) => withCapability(factory(input)),
  99. },
  100. );
  101. try {
  102. await runtime.executeTurn("Run the researcher.");
  103. expect(childRequests.length).toBe(childEnabled ? 2 : 1);
  104. expect(childRequests[0]?.toolSearchEnabled).toBe(childEnabled && !local);
  105. expect(
  106. childRequests[0]?.tools?.some(
  107. (tool) => tool.name === (local ? "LocalToolSearch" : "ToolSearch"),
  108. ),
  109. ).toBe(childEnabled);
  110. if (childEnabled) {
  111. expect(childRequests[0]?.tools?.some((tool) => tool.name === target)).toBe(false);
  112. if (local) {
  113. expect(childRequests[1]?.tools).toEqual(childRequests[0]?.tools);
  114. expect(JSON.stringify(childRequests[1]?.messages)).toContain("<functions>");
  115. // Local 把发现结果展开成 <functions> 文本,不会出现 "toolName";按定义名核对,
  116. // 作用域外的 TodoRead 不能被展开。
  117. const result = childRequests[1]?.messages.find((message) => message.role === "tool");
  118. const text = (Array.isArray(result?.content) ? result.content : [])
  119. .map((part) => ("text" in part && typeof part.text === "string" ? part.text : ""))
  120. .join("\n");
  121. const loaded = [...text.matchAll(/<function>(.*?)<\/function>/gu)].map(
  122. (match) => (JSON.parse(match[1]!) as { name: string }).name,
  123. );
  124. expect(loaded).toEqual([target]);
  125. } else {
  126. expect(childRequests[1]?.tools?.find((tool) => tool.name === target)?.deferLoading).toBe(
  127. true,
  128. );
  129. expect(
  130. childRequests[1]?.messages.find((message) => message.role === "tool")?.content,
  131. ).toEqual([{ type: "tool_reference", toolName: target }]);
  132. }
  133. } else expect(childRequests[0]?.tools?.some((tool) => tool.name === target)).toBe(true);
  134. // 子会话的发现不回流父会话:父会话末轮工具列表与首轮相同,历史里也没有 Local 展开的定义。
  135. // 只断言 target 不在父会话工具里会在 Local 与 Explore 行恒为真,因此对照整份列表。
  136. expect(parentRequests).toHaveLength(2);
  137. expect(parentRequests[1]?.tools).toEqual(parentRequests[0]?.tools);
  138. expect(JSON.stringify(parentRequests[1]?.messages)).not.toContain("<functions>");
  139. } finally {
  140. await runtime.closeBrowserSession();
  141. }
  142. },
  143. );