tool-search-builtins.test.ts 6.1 KB

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