tool-search-execution.test.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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("No matching deferred tools found");
  46. const defaultResults = await executor.execute(
  47. { id: "default-count", name: "ToolSearch", input: { query: "lookup" } },
  48. {
  49. toolSearch: {
  50. ...toolSearch,
  51. catalog: Array.from({ length: 6 }, (_, i) => ({ name: `Lookup${i}`, deferred: true })),
  52. },
  53. },
  54. );
  55. expect(defaultResults).toMatchObject({
  56. success: true,
  57. output: { matches: ["Lookup0", "Lookup1", "Lookup2", "Lookup3", "Lookup4"] },
  58. });
  59. const cancelled = await executor.execute(
  60. { id: "cancelled", name: "ToolSearch", input: { query: "select:WebFetch" } },
  61. { toolSearch, signal: AbortSignal.abort() },
  62. );
  63. expect(cancelled.success).toBe(false);
  64. expect(JSON.stringify(cancelled)).not.toContain("tool_reference");
  65. const invalid = await executor.execute(
  66. { id: "invalid", name: "WebFetch", input: {} },
  67. { toolSearch },
  68. );
  69. expect(invalid.success).toBe(false);
  70. expect(invalid.modelContent).toContain('call ToolSearch with query "select:WebFetch"');
  71. });
  72. it("allows a valid undiscovered deferred tool call without recording a search discovery", async () => {
  73. const { executor, fetch } = createExecutionFixture();
  74. const toolSearch: ToolSearchExecutionContext = {
  75. enabled: true,
  76. mode: "native",
  77. discovered: new Set(),
  78. catalog: [{ name: "WebFetch", deferred: true }],
  79. };
  80. const input = { url: "https://example.com/", prompt: "Summarize the page" };
  81. const result = await executor.execute({ id: "direct", name: "WebFetch", input }, { toolSearch });
  82. expect(result).toMatchObject({ success: true });
  83. expect(fetch).toHaveBeenCalledExactlyOnceWith(input, expect.anything());
  84. expect(result.modelContent).toContain("Fetched page");
  85. expect(toolSearch.discovered.size).toBe(0);
  86. expect([
  87. ...collectDiscoveredTools([
  88. {
  89. message: {
  90. role: "assistant",
  91. content: "",
  92. toolCalls: [{ id: "direct", name: "WebFetch", input }],
  93. },
  94. },
  95. {
  96. message: {
  97. role: "tool",
  98. toolCallId: "direct",
  99. toolName: "WebFetch",
  100. content: result.modelContent!,
  101. },
  102. },
  103. ]),
  104. ]).toEqual([]);
  105. });
  106. it("does not suggest searching again when a discovered tool fails input validation", async () => {
  107. const { executor, fetch } = createExecutionFixture();
  108. const result = await executor.execute(
  109. { id: "invalid-discovered", name: "WebFetch", input: {} },
  110. {
  111. toolSearch: {
  112. enabled: true,
  113. mode: "native",
  114. discovered: new Set(["WebFetch"]),
  115. catalog: [{ name: "WebFetch", deferred: true }],
  116. },
  117. },
  118. );
  119. expect(result.success).toBe(false);
  120. expect(result.modelContent).toContain("InputValidationError");
  121. expect(result.modelContent).not.toContain('call ToolSearch with query "select:WebFetch"');
  122. expect(fetch).not.toHaveBeenCalled();
  123. });
  124. it.each(["disabled", "missing"] as const)(
  125. "rejects ToolSearch with %s execution context without producing references",
  126. async (context) => {
  127. const { executor, fetch } = createExecutionFixture();
  128. const result = await executor.execute(
  129. { id: "disabled-search", name: "ToolSearch", input: { query: "select:WebFetch" } },
  130. context === "missing"
  131. ? {}
  132. : {
  133. toolSearch: {
  134. enabled: false,
  135. mode: "off",
  136. discovered: new Set(),
  137. catalog: [{ name: "WebFetch", deferred: true }],
  138. },
  139. },
  140. );
  141. expect(result.success).toBe(false);
  142. expect(result.error?.message).toContain("ToolSearch is not enabled for this request.");
  143. expect(JSON.stringify(result)).not.toContain("tool_reference");
  144. expect(fetch).not.toHaveBeenCalled();
  145. },
  146. );
  147. function createExecutionFixture() {
  148. const registry = createToolRegistry();
  149. const fetch = vi.fn(async () => ({
  150. url: "https://example.com/",
  151. finalUrl: "https://example.com/",
  152. status: 200,
  153. statusText: "OK",
  154. contentType: "text/plain",
  155. bytes: 12,
  156. durationMs: 0,
  157. result: "Fetched page",
  158. cacheHit: false,
  159. redirects: [],
  160. truncated: false,
  161. }));
  162. registry.register(toolSearchToolEntry);
  163. registry.register({ ...webFetchToolEntry, handler: fetch });
  164. const executor = createToolExecutor({
  165. emitEvent: async () => {},
  166. registry,
  167. permissionService: new PermissionService({
  168. ...defaultPermissionConfig,
  169. allowedTools: new Set(["WebFetch"]),
  170. }),
  171. sessionId: createSessionId("search-execution-boundaries"),
  172. turnId: createTurnId("turn"),
  173. });
  174. return { executor, fetch };
  175. }