tool-search-execution.test.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. import { expect, it, vi } from "vitest";
  2. import { createSessionId, createTurnId, type ToolSearchExecutionContext } from "@zcode/contracts";
  3. import { createToolExecutor } from "../src/tool/executor.js";
  4. import { createToolRegistry } from "../src/tool/registry.js";
  5. import { toolSearchToolEntry } from "../src/tool/handlers/tool-search.js";
  6. import { webFetchToolEntry } from "../src/tool/handlers/webfetch.js";
  7. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  8. import { collectDiscoveredTools } from "../src/tool/search/history.js";
  9. it("executes concurrent searches only within the request snapshot and cancellation yields no references", async () => {
  10. const registry = createToolRegistry();
  11. const fetch = vi.fn();
  12. registry.register(toolSearchToolEntry);
  13. registry.register({ ...webFetchToolEntry, handler: fetch });
  14. const executor = createToolExecutor({
  15. emitEvent: async () => {},
  16. registry,
  17. permissionService: new PermissionService(defaultPermissionConfig),
  18. sessionId: createSessionId("search-execution"),
  19. turnId: createTurnId("turn"),
  20. });
  21. const toolSearch: ToolSearchExecutionContext = {
  22. enabled: true,
  23. mode: "native",
  24. discovered: new Set(),
  25. catalog: [{ name: "WebFetch", deferred: true }],
  26. };
  27. const results = await executor.executeBatch(
  28. [
  29. { id: "one", name: "ToolSearch", input: { query: "select:WebFetch" } },
  30. { id: "two", name: "ToolSearch", input: { query: "select:WebFetch" } },
  31. ],
  32. { toolSearch },
  33. );
  34. expect(results).toHaveLength(2);
  35. for (const result of results)
  36. expect(result).toMatchObject({
  37. success: true,
  38. modelContent: [{ type: "tool_reference", toolName: "WebFetch" }],
  39. });
  40. expect(fetch).not.toHaveBeenCalled();
  41. const excluded = await executor.execute(
  42. { id: "excluded", name: "ToolSearch", input: { query: "select:WebFetch" } },
  43. { toolSearch: { ...toolSearch, catalog: [] } },
  44. );
  45. expect(excluded.modelContent).toBe(
  46. "No matching deferred tools found. Loaded tools are not searchable here and need no loading. Check your loaded tool list and query; try corrected spelling, alternative names, or broader keywords before concluding a tool is missing.",
  47. );
  48. const defaultResults = await executor.execute(
  49. { id: "default-count", name: "ToolSearch", input: { query: "lookup" } },
  50. {
  51. toolSearch: {
  52. ...toolSearch,
  53. catalog: Array.from({ length: 6 }, (_, i) => ({ name: `Lookup${i}`, deferred: true })),
  54. },
  55. },
  56. );
  57. expect(defaultResults).toMatchObject({
  58. success: true,
  59. output: { matches: ["Lookup0", "Lookup1", "Lookup2", "Lookup3", "Lookup4"] },
  60. });
  61. const cancelled = await executor.execute(
  62. { id: "cancelled", name: "ToolSearch", input: { query: "select:WebFetch" } },
  63. { toolSearch, signal: AbortSignal.abort() },
  64. );
  65. expect(cancelled.success).toBe(false);
  66. expect(JSON.stringify(cancelled)).not.toContain("tool_reference");
  67. const invalid = await executor.execute(
  68. { id: "invalid", name: "WebFetch", input: {} },
  69. { toolSearch },
  70. );
  71. expect(invalid.success).toBe(false);
  72. expect(invalid.modelContent).toContain('call ToolSearch with query "select:WebFetch"');
  73. });
  74. it("allows a valid undiscovered deferred tool call without recording a search discovery", async () => {
  75. const { executor, fetch } = createExecutionFixture();
  76. const toolSearch: ToolSearchExecutionContext = {
  77. enabled: true,
  78. mode: "native",
  79. discovered: new Set(),
  80. catalog: [{ name: "WebFetch", deferred: true }],
  81. };
  82. const input = { url: "https://example.com/", prompt: "Summarize the page" };
  83. const result = await executor.execute({ id: "direct", name: "WebFetch", input }, { toolSearch });
  84. expect(result).toMatchObject({ success: true });
  85. expect(fetch).toHaveBeenCalledExactlyOnceWith(input, expect.anything());
  86. expect(result.modelContent).toContain("Fetched page");
  87. expect(toolSearch.discovered.size).toBe(0);
  88. expect([
  89. ...collectDiscoveredTools([
  90. {
  91. message: {
  92. role: "assistant",
  93. content: "",
  94. toolCalls: [{ id: "direct", name: "WebFetch", input }],
  95. },
  96. },
  97. {
  98. message: {
  99. role: "tool",
  100. toolCallId: "direct",
  101. toolName: "WebFetch",
  102. content: result.modelContent!,
  103. },
  104. },
  105. ]),
  106. ]).toEqual([]);
  107. });
  108. it("does not suggest searching again when a discovered tool fails input validation", async () => {
  109. const { executor, fetch } = createExecutionFixture();
  110. const result = await executor.execute(
  111. { id: "invalid-discovered", name: "WebFetch", input: {} },
  112. {
  113. toolSearch: {
  114. enabled: true,
  115. mode: "native",
  116. discovered: new Set(["WebFetch"]),
  117. catalog: [{ name: "WebFetch", deferred: true }],
  118. },
  119. },
  120. );
  121. expect(result.success).toBe(false);
  122. expect(result.modelContent).toContain("InputValidationError");
  123. expect(result.modelContent).not.toContain('call ToolSearch with query "select:WebFetch"');
  124. expect(fetch).not.toHaveBeenCalled();
  125. });
  126. it.each(["disabled", "missing"] as const)(
  127. "rejects ToolSearch with %s execution context without producing references",
  128. async (context) => {
  129. const { executor, fetch } = createExecutionFixture();
  130. const result = await executor.execute(
  131. { id: "disabled-search", name: "ToolSearch", input: { query: "select:WebFetch" } },
  132. context === "missing"
  133. ? {}
  134. : {
  135. toolSearch: {
  136. enabled: false,
  137. mode: "off",
  138. discovered: new Set(),
  139. catalog: [{ name: "WebFetch", deferred: true }],
  140. },
  141. },
  142. );
  143. expect(result.success).toBe(false);
  144. expect(result.error?.message).toContain("ToolSearch is not enabled for this request.");
  145. expect(JSON.stringify(result)).not.toContain("tool_reference");
  146. expect(fetch).not.toHaveBeenCalled();
  147. },
  148. );
  149. function createExecutionFixture() {
  150. const registry = createToolRegistry();
  151. const fetch = vi.fn(async () => ({
  152. url: "https://example.com/",
  153. finalUrl: "https://example.com/",
  154. status: 200,
  155. statusText: "OK",
  156. contentType: "text/plain",
  157. bytes: 12,
  158. durationMs: 0,
  159. result: "Fetched page",
  160. cacheHit: false,
  161. redirects: [],
  162. truncated: false,
  163. }));
  164. registry.register(toolSearchToolEntry);
  165. registry.register({ ...webFetchToolEntry, handler: fetch });
  166. const executor = createToolExecutor({
  167. emitEvent: async () => {},
  168. registry,
  169. permissionService: new PermissionService({
  170. ...defaultPermissionConfig,
  171. allowedTools: new Set(["WebFetch"]),
  172. }),
  173. sessionId: createSessionId("search-execution-boundaries"),
  174. turnId: createTurnId("turn"),
  175. });
  176. return { executor, fetch };
  177. }