tool-search-builtins.test.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. import { expect, it } from "vitest";
  2. import { createSessionId, createTurnId, type Model } from "@zcode/contracts";
  3. import type { RuntimeMessageEntry } from "../src/agent/message-history.js";
  4. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  5. import { prepareRuntimeProviderRequest } from "../src/runtime/helpers/runtime-provider-request-messages.js";
  6. import { createToolExecutor } from "../src/tool/executor.js";
  7. import { builtInTools, registerBuiltInTools } from "../src/tool/handlers/index.js";
  8. import { createToolRegistry } from "../src/tool/registry.js";
  9. import { buildToolSearchAnnouncement } from "../src/tool/search/exposure.js";
  10. import { createTestRuntimeModel } from "./test-runtime-model.js";
  11. const RESIDENT_NAMES = [
  12. "Agent",
  13. "AskUserQuestion",
  14. "Bash",
  15. "Edit",
  16. "Glob",
  17. "Grep",
  18. "Read",
  19. "ReportFindings",
  20. "Skill",
  21. "TodoWrite",
  22. "ToolSearch",
  23. "WebFetch",
  24. "WebSearch",
  25. "Write",
  26. // 只在注入 workflowSubmitPort 的 actor 会话注册;fixture 打开了 includeSubmitResult。
  27. "submit_result",
  28. ];
  29. function fixture(embeddedSearchEnabled = false) {
  30. const registry = createToolRegistry();
  31. registerBuiltInTools(registry, {
  32. includeAgent: true,
  33. includeSkill: true,
  34. includeSendMessage: true,
  35. includeRespondToCoordinator: true,
  36. includeSubmitResult: true,
  37. submitResultSchema: { type: "object", properties: { answer: { type: "string" } } },
  38. includeEscalate: true,
  39. includeWorkflow: true,
  40. includeAutomation: true,
  41. includeOffPeak: true,
  42. includeDynamicWorkflow: true,
  43. includeNodeRepl: true,
  44. includeBrowserUse: true,
  45. embeddedSearchEnabled,
  46. });
  47. const model: Model = {
  48. ...createTestRuntimeModel({
  49. generateText: async () => ({ text: "", finishReason: "stop", usage: {} }),
  50. }),
  51. requestCapabilities: { toolSearch: { protocolSupported: true, defaultEnabled: true } },
  52. };
  53. return { registry, model, tools: registry.toContracts() };
  54. }
  55. it.each([false, true])(
  56. "exposes only resident builtins initially and announces the rest (embedded search: %s)",
  57. (embeddedSearchEnabled) => {
  58. const input = fixture(embeddedSearchEnabled);
  59. const entries: RuntimeMessageEntry[] = [];
  60. const prepared = prepareRuntimeProviderRequest(
  61. { config: { toolSearch: { mode: "auto" } } },
  62. { ...input, entries },
  63. );
  64. const expectedResidents = RESIDENT_NAMES.filter((name) => input.registry.has(name));
  65. expect(prepared.request.toolSearchEnabled).toBe(true);
  66. expect(prepared.request.tools.map((tool) => tool.name).sort()).toEqual(expectedResidents);
  67. expect(prepared.request.tools.every((tool) => tool.deferLoading === undefined)).toBe(true);
  68. const deferredNames = input.tools
  69. .filter((tool) => tool.name !== "DeferredToolCall" && !RESIDENT_NAMES.includes(tool.name))
  70. .map((tool) => tool.name)
  71. .sort();
  72. const announcement = buildToolSearchAnnouncement({ ...input, mode: "native", entries });
  73. expect(announcement?.metadata?.toolSearchAnnouncement).toEqual({
  74. addedNames: deferredNames,
  75. removedNames: [],
  76. readdedNames: [],
  77. });
  78. expect(prepared.toolSearch.catalog.some((tool) => tool.name === "Task")).toBe(false);
  79. // 同时检查静态条目和注册时重建的工厂条目,避免分支覆盖丢掉 metadata。
  80. for (const entry of [
  81. ...builtInTools,
  82. ...input.registry.list().map((name) => input.registry.get(name)!),
  83. ]) {
  84. if (
  85. entry.metadata.name !== "DeferredToolCall" &&
  86. !RESIDENT_NAMES.includes(entry.metadata.name)
  87. ) {
  88. expect(entry.metadata.shouldDefer, entry.metadata.name).toBe(true);
  89. }
  90. }
  91. },
  92. );
  93. it("loads builtin schemas with deferLoading after executing a real ToolSearch", async () => {
  94. const input = fixture();
  95. const prepared = prepareRuntimeProviderRequest(
  96. { config: { toolSearch: { mode: "auto" } } },
  97. { ...input, entries: [] },
  98. );
  99. const names = input.tools
  100. .filter((tool) => tool.name !== "DeferredToolCall" && !RESIDENT_NAMES.includes(tool.name))
  101. .map((tool) => tool.name);
  102. const call = {
  103. id: "builtin-search",
  104. name: "ToolSearch",
  105. input: { query: `select:${names.join(",")}` },
  106. };
  107. const executor = createToolExecutor({
  108. emitEvent: async () => {},
  109. registry: input.registry,
  110. permissionService: new PermissionService(defaultPermissionConfig),
  111. sessionId: createSessionId("builtin-search"),
  112. turnId: createTurnId("turn"),
  113. });
  114. const result = await executor.execute(call, { toolSearch: prepared.toolSearch });
  115. expect(result.success).toBe(true);
  116. expect(result.modelContent).toEqual(
  117. names.map((toolName) => ({ type: "tool_reference", toolName })),
  118. );
  119. const entries: RuntimeMessageEntry[] = [
  120. { message: { role: "assistant", content: "", toolCalls: [call] } },
  121. {
  122. message: {
  123. role: "tool",
  124. toolName: call.name,
  125. toolCallId: call.id,
  126. content: result.modelContent!,
  127. },
  128. },
  129. ];
  130. const next = prepareRuntimeProviderRequest(
  131. { config: { toolSearch: { mode: "auto" } } },
  132. { ...input, entries },
  133. );
  134. expect(next.request.tools).toEqual(
  135. input.tools
  136. .filter((tool) => tool.name !== "DeferredToolCall")
  137. .map((tool) => (RESIDENT_NAMES.includes(tool.name) ? tool : { ...tool, deferLoading: true })),
  138. );
  139. expect(next.request.messages.find((message) => message.role === "tool")?.content).toEqual(
  140. result.modelContent,
  141. );
  142. });
  143. it.each(["provider_disabled", "tool_unavailable"] as const)(
  144. "preserves full builtin schemas when ToolSearch is %s",
  145. (reason) => {
  146. const input = fixture();
  147. if (reason === "provider_disabled") {
  148. input.model = {
  149. ...input.model,
  150. requestCapabilities: { toolSearch: { protocolSupported: true, defaultEnabled: false } },
  151. };
  152. } else {
  153. input.tools = input.tools.filter(
  154. (tool) => tool.name !== "ToolSearch" && tool.name !== "DeferredToolCall",
  155. );
  156. }
  157. const prepared = prepareRuntimeProviderRequest(
  158. { config: { toolSearch: { mode: "off" } } },
  159. { ...input, entries: [] },
  160. );
  161. expect(prepared.request.toolSearchEnabled).toBe(false);
  162. expect(prepared.request.tools).toEqual(
  163. input.tools.filter((tool) => tool.name !== "ToolSearch" && tool.name !== "DeferredToolCall"),
  164. );
  165. expect(buildToolSearchAnnouncement({ ...input, entries: [] })).toBeUndefined();
  166. },
  167. );