tool-search-wire.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
  2. import {
  3. buildToolExposure,
  4. buildToolSearchAnnouncement,
  5. } from "../../core/src/tool/search/exposure.js";
  6. import { prepareRuntimeProviderRequest } from "../../core/src/runtime/helpers/runtime-provider-request-messages.js";
  7. import { createToolRegistry } from "../../core/src/tool/registry.js";
  8. import { toolSearchToolEntry } from "../../core/src/tool/handlers/tool-search.js";
  9. import { deferredToolCallEntry } from "../../core/src/tool/handlers/deferred-tool-call.js";
  10. import { taskOutputToolEntry } from "../../core/src/tool/handlers/task-output.js";
  11. import { createTestRuntimeModel } from "../../core/tests/test-runtime-model.js";
  12. import type { RuntimeMessageEntry } from "../../core/src/agent/message-history.js";
  13. import { createAnthropic } from "@ai-sdk/anthropic";
  14. import { generateText } from "ai";
  15. import { expect, it } from "vitest";
  16. import { toAiSdkMessages } from "../src/model/transform.js";
  17. import { toAiSdkTools } from "../src/model/tool-transform.js";
  18. import { toolSearchHeaders } from "../src/model/tool-search.js";
  19. import { createSessionId, type Model } from "@zcode/contracts";
  20. import { createTestAgentRuntime } from "../../core/tests/test-agent-runtime.js";
  21. import { createTestModelFactory } from "../../core/tests/test-runtime-model.js";
  22. import { createTestSessionEventStore } from "../../core/tests/test-event-store.js";
  23. it.each([
  24. { stripMedia: false, large: false },
  25. { stripMedia: true, large: false },
  26. { stripMedia: false, large: true },
  27. { stripMedia: true, large: true },
  28. ])(
  29. "serializes native references and schemas (stripMedia=$stripMedia, large=$large)",
  30. async ({ stripMedia, large }) => {
  31. const names = large
  32. ? Array.from({ length: 2_000 }, (_, i) =>
  33. `mcp__demo__lookup_${String(i).padStart(4, "0")}_`.padEnd(64, "x"),
  34. )
  35. : ["TaskOutput"];
  36. let body: any;
  37. let headers: Headers | undefined;
  38. const provider = createAnthropic({
  39. apiKey: "test",
  40. fetch: async (_url, init) => {
  41. body = JSON.parse(String(init?.body));
  42. headers = new Headers(init?.headers);
  43. return new Response(
  44. JSON.stringify({ error: { type: "invalid_request_error", message: "capture" } }),
  45. { status: 400, headers: { "content-type": "application/json" } },
  46. );
  47. },
  48. });
  49. const options = { stripMedia, providerKind: "anthropic" as const, toolSearchEnabled: true };
  50. await expect(
  51. generateText({
  52. model: provider("test"),
  53. maxRetries: 0,
  54. headers: toolSearchHeaders({ "anthropic-beta": "existing-beta" }, true),
  55. tools: toAiSdkTools(
  56. names.map((name) => ({ name, inputSchema: { type: "object" }, deferLoading: true })),
  57. options,
  58. ),
  59. messages: toAiSdkMessages(
  60. [
  61. {
  62. role: "assistant",
  63. content: "",
  64. toolCalls: [
  65. {
  66. id: "search-1",
  67. name: "ToolSearch",
  68. input: { query: `select:${names.join(",")}` },
  69. },
  70. ],
  71. },
  72. {
  73. role: "tool",
  74. toolCallId: "search-1",
  75. toolName: "ToolSearch",
  76. content: [
  77. { type: "text", text: "before" },
  78. ...names.map((toolName) => ({ type: "tool_reference" as const, toolName })),
  79. { type: "text", text: "after" },
  80. ],
  81. },
  82. ],
  83. options,
  84. ),
  85. }),
  86. ).rejects.toBeDefined();
  87. expect(
  88. body.tools.map((tool: { name: string; defer_loading: boolean }) => ({
  89. name: tool.name,
  90. defer_loading: tool.defer_loading,
  91. })),
  92. ).toEqual(names.map((name) => ({ name, defer_loading: true })));
  93. expect(body.messages[1].content[0].content).toEqual([
  94. { type: "text", text: "before" },
  95. ...names.map((tool_name) => ({ type: "tool_reference", tool_name })),
  96. { type: "text", text: "after" },
  97. ]);
  98. expect(headers?.get("anthropic-beta")).toContain("advanced-tool-use-2025-11-20");
  99. expect(headers?.get("anthropic-beta")).toContain("existing-beta");
  100. },
  101. );
  102. it("keeps one announcement in native Anthropic bodies through continuation and the next input", async () => {
  103. const bodies: Array<{
  104. messages: unknown[];
  105. tools: Array<{ name: string; description: string; input_schema: unknown }>;
  106. }> = [];
  107. const provider = createAnthropic({
  108. apiKey: "test",
  109. fetch: async (_url, init) => {
  110. bodies.push(JSON.parse(String(init?.body)));
  111. return new Response(
  112. JSON.stringify({ error: { type: "invalid_request_error", message: "capture" } }),
  113. { status: 400, headers: { "content-type": "application/json" } },
  114. );
  115. },
  116. });
  117. const factory = createTestModelFactory({
  118. async generateText(request) {
  119. const options = {
  120. providerKind: "anthropic" as const,
  121. toolSearchEnabled: request.toolSearchEnabled,
  122. };
  123. await expect(
  124. generateText({
  125. model: provider("test"),
  126. maxRetries: 0,
  127. headers: toolSearchHeaders(undefined, request.toolSearchEnabled),
  128. tools: toAiSdkTools(request.tools, options),
  129. messages: toAiSdkMessages(request.messages, options),
  130. }),
  131. ).rejects.toBeDefined();
  132. return { text: "response", finishReason: bodies.length <= 3 ? "length" : "stop", usage: {} };
  133. },
  134. });
  135. const wrap = (model: Model): Model => ({
  136. ...model,
  137. requestCapabilities: { toolSearch: { protocolSupported: true, defaultEnabled: true } },
  138. bind: (options) => wrap(model.bind(options)),
  139. });
  140. const runtime = createTestAgentRuntime(
  141. createSessionId("toolsearch-continuation-wire"),
  142. {
  143. toolSearch: { mode: "native" },
  144. modelStreaming: "off",
  145. titleGeneration: { enabled: false },
  146. toolAllowlist: ["ToolSearch", "TaskOutput"],
  147. },
  148. { eventStore: createTestSessionEventStore(), modelFactory: (input) => wrap(factory(input)) },
  149. );
  150. await runtime.executeTurn("start");
  151. await runtime.executeTurn("next input");
  152. expect(bodies).toHaveLength(5);
  153. for (const body of bodies) {
  154. expect(
  155. JSON.stringify(body.messages).split(
  156. "The following deferred tools are now available via ToolSearch.",
  157. ),
  158. ).toHaveLength(2);
  159. expect(body.tools.map((tool) => tool.name)).toEqual(["ToolSearch"]);
  160. expect(body.tools[0]?.description)
  161. .toBe(`Fetches full schema definitions for deferred tools so they can be called.
  162. Deferred tools appear by name in <system-reminder> messages. Until fetched, only the name is known — there is no parameter schema, so the tool cannot be invoked. This tool takes a query, matches it against the deferred tool list, and returns the matched tools' complete JSONSchema definitions inside a <functions> block. Once a tool's schema appears in that result, it is callable exactly like any tool defined at the top of the prompt.
  163. Result format: each matched tool appears as one <function>{"description": "...", "name": "...", "parameters": {...}}</function> line inside the <functions> block — the same encoding as the tool list at the top of this prompt.
  164. Query forms:
  165. Regular expressions are not supported. Use space-separated keywords for broad searches, or "select:<name>[,<name>...]" for exact tool names. Characters such as "|" and ".*" are treated literally. For example, use "shell terminal execute command".
  166. - "select:TaskStop,mcp__byob__browser_navigate" — fetch these exact deferred tools by name
  167. - "notebook jupyter" — keyword search, up to max_results best matches
  168. - "+slack send" — require "slack" in the name, rank by remaining terms`);
  169. expect(body.tools[0]?.input_schema).toMatchObject({
  170. required: ["query", "max_results"],
  171. properties: {
  172. query: {
  173. description:
  174. 'Query to find deferred tools. Use "select:<tool_name>" for direct selection, or keywords to search. Regular expressions are not supported.',
  175. },
  176. max_results: {
  177. description: "Maximum number of results to return (default: 5)",
  178. default: 5,
  179. },
  180. },
  181. });
  182. }
  183. });
  184. it.each(["anthropic", "openai-compatible"] as const)(
  185. "sends only LocalToolSearch on %s wire after native history",
  186. async (providerKind) => {
  187. const registry = createToolRegistry();
  188. [toolSearchToolEntry, deferredToolCallEntry, taskOutputToolEntry].forEach((entry) =>
  189. registry.register(entry),
  190. );
  191. const model = {
  192. ...createTestRuntimeModel({
  193. generateText: async () => ({ text: "", finishReason: "stop", usage: {} }),
  194. }),
  195. requestCapabilities: { toolSearch: { protocolSupported: true, defaultEnabled: true } },
  196. };
  197. const input = { model, registry, tools: registry.toContracts() };
  198. const entries: RuntimeMessageEntry[] = [
  199. buildToolSearchAnnouncement({ ...input, mode: "native", entries: [] })!,
  200. { message: { role: "user", content: "Find a tool" } },
  201. {
  202. message: {
  203. role: "assistant",
  204. content: "",
  205. toolCalls: [{ id: "search", name: "ToolSearch", input: { query: "select:TaskOutput" } }],
  206. },
  207. },
  208. {
  209. message: {
  210. role: "tool",
  211. toolName: "ToolSearch",
  212. toolCallId: "search",
  213. content: [{ type: "tool_reference", toolName: "TaskOutput" }],
  214. },
  215. },
  216. ];
  217. const before = structuredClone(entries);
  218. const { request } = prepareRuntimeProviderRequest(
  219. { config: { toolSearch: { mode: "local" } } },
  220. { ...input, entries },
  221. );
  222. let body: any;
  223. const options = {
  224. apiKey: "fixture",
  225. baseURL: "https://provider.example/v1",
  226. fetch: async (_url: unknown, init?: RequestInit) => {
  227. body = JSON.parse(String(init?.body));
  228. return new Response(
  229. JSON.stringify({ error: { type: "invalid_request_error", message: "capture" } }),
  230. { status: 400, headers: { "content-type": "application/json" } },
  231. );
  232. },
  233. };
  234. const provider =
  235. providerKind === "anthropic"
  236. ? createAnthropic(options)("test")
  237. : createOpenAICompatible({ ...options, name: "fixture" })("test");
  238. const transform = { providerKind, toolSearchEnabled: request.toolSearchEnabled };
  239. await expect(
  240. generateText({
  241. model: provider,
  242. maxRetries: 0,
  243. tools: toAiSdkTools(request.tools, transform),
  244. messages: toAiSdkMessages(request.messages, transform),
  245. }),
  246. ).rejects.toBeDefined();
  247. const names = body.tools.map((tool: any) => tool.name ?? tool.function.name);
  248. expect(names).toEqual(["LocalToolSearch", "DeferredToolCall"]);
  249. const searchTool = body.tools[0].function ?? body.tools[0];
  250. expect(searchTool.description).toContain(
  251. 'Query forms:\nRegular expressions are not supported. Use space-separated keywords for broad searches, or "select:<name>[,<name>...]" for exact tool names. Characters such as "|" and ".*" are treated literally. For example, use "shell terminal execute command".',
  252. );
  253. expect(
  254. (searchTool.input_schema ?? searchTool.parameters).properties.query.description,
  255. ).toContain("Regular expressions are not supported.");
  256. const calls =
  257. providerKind === "anthropic"
  258. ? body.messages
  259. .flatMap((message: any) => message.content)
  260. .filter((block: any) => block.type === "tool_use")
  261. .map((block: any) => block.name)
  262. : body.messages
  263. .flatMap((message: any) => message.tool_calls ?? [])
  264. .map((call: any) => call.function.name);
  265. expect(calls).toEqual(["LocalToolSearch"]);
  266. expect(JSON.stringify(body)).toContain("available via LocalToolSearch.");
  267. expect(JSON.stringify(body)).toContain("<functions>");
  268. expect(JSON.stringify(body)).not.toContain("tool_reference");
  269. expect(JSON.stringify(body)).not.toContain("defer_loading");
  270. expect(entries).toEqual(before);
  271. expect(
  272. buildToolExposure({ ...input, mode: "native", entries }).tools.map((tool) => tool.name),
  273. ).toEqual(["ToolSearch", "TaskOutput"]);
  274. },
  275. );