websearch.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. // ============================================================
  2. import { createTestModelSelection } from "./test-model-selection.js";
  3. // Provider-visible WebSearch Wrapper Tests
  4. // ============================================================
  5. import {
  6. SessionEventType,
  7. WebSearchInputJsonSchema,
  8. WebSearchInputSchema,
  9. createSessionId,
  10. type ModelSelection,
  11. } from "@zcode/contracts";
  12. import { describe, expect, it, vi } from "vitest";
  13. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  14. import { registerBuiltInTools } from "../src/tool/handlers/index.js";
  15. import { webSearchToolEntry } from "../src/tool/handlers/websearch.js";
  16. import { buildWebSearchOutput } from "../src/tool/handlers/websearch-results.js";
  17. import { createToolRegistry } from "../src/tool/registry.js";
  18. import { createTestSessionEventStore } from "./test-event-store.js";
  19. import { createTestModelFactory, createTestRuntimeModel } from "./test-runtime-model.js";
  20. const modelSelection: ModelSelection = {
  21. providerId: "deepseek" as never,
  22. modelId: "deepseek-chat" as never,
  23. };
  24. describe("provider-visible WebSearch wrapper", () => {
  25. it("exposes WebSearch schema without unsupported provider-native no-op options", () => {
  26. const properties = WebSearchInputJsonSchema.properties as Record<string, unknown>;
  27. expect(properties.query).toBeDefined();
  28. expect(properties.allowed_domains).toBeDefined();
  29. expect(properties.blocked_domains).toBeDefined();
  30. expect(properties.allowedDomains).toBeUndefined();
  31. expect(properties.blockedDomains).toBeUndefined();
  32. expect(properties.maxUses).toBeUndefined();
  33. expect(properties.searchContextSize).toBeUndefined();
  34. expect(properties.numResults).toBeUndefined();
  35. expect(properties.safeSearch).toBeUndefined();
  36. });
  37. it("validates provider-visible search options", () => {
  38. expect(
  39. WebSearchInputSchema.safeParse({
  40. allowed_domains: ["example.com"],
  41. maxUses: 3,
  42. query: "latest zcode",
  43. }).success,
  44. ).toBe(true);
  45. expect(
  46. WebSearchInputSchema.safeParse({
  47. query: "latest zcode",
  48. searchContextSize: "high",
  49. }).success,
  50. ).toBe(false);
  51. expect(
  52. WebSearchInputSchema.safeParse({
  53. maxUses: 9,
  54. query: "latest zcode",
  55. }).success,
  56. ).toBe(false);
  57. expect(
  58. WebSearchInputSchema.safeParse({
  59. allowed_domains: ["example.com"],
  60. blocked_domains: ["blocked.example"],
  61. query: "latest zcode",
  62. }).success,
  63. ).toBe(false);
  64. expect(
  65. WebSearchInputSchema.safeParse({
  66. allowed_domains: ["https://example.com"],
  67. query: "latest zcode",
  68. }).success,
  69. ).toBe(true);
  70. expect(
  71. WebSearchInputSchema.safeParse({
  72. allowed_domains: Array.from({ length: 21 }, (_, index) => `example-${index}.com`),
  73. query: "latest zcode",
  74. }).success,
  75. ).toBe(true);
  76. });
  77. it("keeps the client-side WebSearch entry metadata aligned with local execution", () => {
  78. expect(webSearchToolEntry.metadata.name).toBe("WebSearch");
  79. expect(webSearchToolEntry.executionMode).toBe("client");
  80. expect(webSearchToolEntry.providerNative).toBeUndefined();
  81. expect(webSearchToolEntry.metadata.readOnly).toBe(true);
  82. expect(webSearchToolEntry.metadata.concurrentSafe).toBe(true);
  83. });
  84. it("describes public WebSearch citation and domain guidance", () => {
  85. const description = webSearchToolEntry.metadata.description;
  86. const instructions = webSearchToolEntry.metadata.modelInstructions?.join("\n") ?? "";
  87. const prompt = `${description}\n${instructions}`;
  88. expect(prompt).toContain("Sources:");
  89. expect(prompt).toContain("markdown links");
  90. expect(prompt).toContain("allowed_domains");
  91. expect(prompt).toContain("blocked_domains");
  92. expect(prompt).toContain("current month");
  93. expect(prompt).toContain("US-only");
  94. });
  95. it("generates the public WebSearch current month from the current clock", async () => {
  96. vi.useFakeTimers();
  97. try {
  98. vi.setSystemTime(new Date(2027, 1, 15, 12, 0, 0));
  99. vi.resetModules();
  100. const { webSearchToolEntry: timedWebSearchToolEntry } =
  101. await import("../src/tool/handlers/websearch.js");
  102. const { createToolRegistry: createTimedToolRegistry } =
  103. await import("../src/tool/registry.js");
  104. const timedRegistry = createTimedToolRegistry();
  105. timedRegistry.register(timedWebSearchToolEntry);
  106. const getProviderDescription = () =>
  107. timedRegistry.toContracts().find((tool) => tool.name === "WebSearch")?.description ?? "";
  108. expect(timedWebSearchToolEntry.metadata.description).toContain(
  109. "The current month is February 2027",
  110. );
  111. expect(timedWebSearchToolEntry.metadata.description).not.toContain("June 2026");
  112. expect(getProviderDescription()).toContain("The current month is February 2027");
  113. vi.setSystemTime(new Date(2027, 2, 15, 12, 0, 0));
  114. expect(timedWebSearchToolEntry.metadata.description).toContain(
  115. "The current month is March 2027",
  116. );
  117. expect(getProviderDescription()).toContain("The current month is March 2027");
  118. } finally {
  119. vi.useRealTimers();
  120. vi.resetModules();
  121. }
  122. });
  123. it("registers WebSearch as a client-side built-in tool", () => {
  124. const registry = createToolRegistry();
  125. registerBuiltInTools(registry, { includeAgent: true });
  126. expect(registry.has("WebSearch")).toBe(true);
  127. expect(registry.has("web_search")).toBe(false);
  128. expect(registry.toContracts()).toContainEqual(
  129. expect.objectContaining({
  130. executionMode: "client",
  131. name: "WebSearch",
  132. providerNative: undefined,
  133. }),
  134. );
  135. });
  136. it("keeps non-execution inventory independent from a model", () => {
  137. const runtime = createRuntime("runtime-websearch-client-wrapper");
  138. const tools = runtime.getTools();
  139. expect(runtime.getToolRegistry().has("WebSearch")).toBe(true);
  140. expect(tools).toContainEqual(
  141. expect.objectContaining({
  142. executionMode: "client",
  143. name: "WebSearch",
  144. providerNative: undefined,
  145. }),
  146. );
  147. expect(tools.some((tool) => tool.name === "web_search")).toBe(false);
  148. });
  149. it("filters execution tools only from the current Active Model property", () => {
  150. const runtime = createRuntime("runtime-websearch-active-model");
  151. const createModel = (supportsNativeWebSearch: boolean) =>
  152. createTestRuntimeModel({
  153. generateText: async () => ({ finishReason: "stop", text: "", usage: {} }),
  154. propertyOverrides: { supportsNativeWebSearch },
  155. });
  156. expect(runtime.getTools(createModel(true)).some((tool) => tool.name === "WebSearch")).toBe(
  157. true,
  158. );
  159. expect(runtime.getTools(createModel(false)).some((tool) => tool.name === "WebSearch")).toBe(
  160. false,
  161. );
  162. });
  163. it("normalizes legacy web_search allowlist aliases to WebSearch", () => {
  164. expect(
  165. createRuntime("runtime-websearch-explore", {
  166. toolset: "explore",
  167. toolAllowlist: ["Read", "Glob", "Grep", "WebSearch"],
  168. })
  169. .getTools()
  170. .some((tool) => tool.name === "WebSearch"),
  171. ).toBe(true);
  172. expect(
  173. createRuntime("runtime-websearch-explore-provider-alias", {
  174. toolset: "explore",
  175. toolAllowlist: ["Read", "Glob", "Grep", "web_search"],
  176. })
  177. .getTools()
  178. .some((tool) => tool.name === "WebSearch"),
  179. ).toBe(true);
  180. expect(
  181. createRuntime("runtime-websearch-explore-deny", {
  182. toolset: "explore",
  183. toolAllowlist: ["Read", "Glob", "Grep"],
  184. })
  185. .getTools()
  186. .some((tool) => tool.name === "WebSearch"),
  187. ).toBe(false);
  188. expect(
  189. createRuntime("runtime-websearch-allowlist-deny", {
  190. toolAllowlist: ["Read"],
  191. })
  192. .getTools()
  193. .some((tool) => tool.name === "WebSearch"),
  194. ).toBe(false);
  195. expect(
  196. createRuntime("runtime-websearch-allowlist-public", {
  197. toolAllowlist: ["WebSearch"],
  198. })
  199. .getTools()
  200. .some((tool) => tool.name === "WebSearch"),
  201. ).toBe(true);
  202. expect(
  203. createRuntime("runtime-websearch-allowlist-provider", {
  204. toolAllowlist: ["web_search"],
  205. })
  206. .getTools()
  207. .some((tool) => tool.name === "WebSearch"),
  208. ).toBe(true);
  209. });
  210. it("runs an internal streaming provider-native web_search request from the WebSearch handler", async () => {
  211. const sessionId = createSessionId("runtime-websearch-handler-side-request");
  212. const eventStore = createTestSessionEventStore();
  213. const requests: any[] = [];
  214. let mainRequestCount = 0;
  215. const runtime = createTestAgentRuntime(
  216. sessionId,
  217. { modelSelection: createTestModelSelection(modelSelection) },
  218. {
  219. eventStore,
  220. modelFactory: createTestModelFactory({
  221. properties: { supportsNativeWebSearch: true },
  222. async generateText(request: any, observation) {
  223. if (observation.invocationContext?.metadata?.querySource === "web_search_tool") {
  224. throw new Error("WebSearch side request must use streamText");
  225. }
  226. mainRequestCount++;
  227. if (mainRequestCount === 1) {
  228. return {
  229. finishReason: "tool-calls",
  230. providerMetadata: undefined,
  231. text: "",
  232. toolCalls: [
  233. {
  234. id: "call_websearch",
  235. input: {
  236. allowed_domains: ["example.com"],
  237. query: "latest zcode",
  238. },
  239. name: "WebSearch",
  240. },
  241. ],
  242. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  243. };
  244. }
  245. return {
  246. finishReason: "stop",
  247. providerMetadata: undefined,
  248. text: "Final answer with sources",
  249. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  250. };
  251. },
  252. async *streamText(request: any, observation) {
  253. requests.push({ observation, request });
  254. if (observation.invocationContext?.metadata?.querySource !== "web_search_tool") {
  255. throw new Error("Unexpected streaming request");
  256. }
  257. yield { type: "start" };
  258. yield { id: "text_1", type: "text_start" };
  259. yield {
  260. id: "text_1",
  261. text: "Search summary from [Example](https://example.com)",
  262. type: "text_delta",
  263. };
  264. yield { id: "text_1", type: "text_end" };
  265. yield {
  266. finishReason: "stop",
  267. providerMetadata: { rawFinishReason: "end_turn" },
  268. type: "finish",
  269. usage: {
  270. inputTokens: 5,
  271. outputTokens: 7,
  272. serverToolUse: { webSearchRequests: 1 },
  273. totalTokens: 12,
  274. },
  275. };
  276. },
  277. } as never),
  278. },
  279. );
  280. await runtime.executeTurn("Search current ZCode info");
  281. const innerRequest = requests.find(
  282. ({ observation }) =>
  283. observation.invocationContext?.metadata?.querySource === "web_search_tool",
  284. )?.request;
  285. expect(innerRequest).toBeDefined();
  286. expect(innerRequest.messages).toEqual([
  287. {
  288. content: "You are an assistant for performing a web search tool use.",
  289. role: "system",
  290. },
  291. { content: "Perform a web search for the query: latest zcode", role: "user" },
  292. ]);
  293. expect(innerRequest.tools.map((tool: any) => tool.name)).toEqual(["web_search"]);
  294. expect(innerRequest.tools[0]).toMatchObject({
  295. executionMode: "providerNative",
  296. providerNative: expect.objectContaining({
  297. args: expect.objectContaining({
  298. allowedDomains: ["example.com"],
  299. maxUses: 8,
  300. }),
  301. logicalName: "WebSearch",
  302. providerToolName: "web_search",
  303. }),
  304. });
  305. expect(innerRequest.tools[0].providerNative.args).not.toHaveProperty("searchContextSize");
  306. expect(innerRequest.toolChoice).toBeUndefined();
  307. expect(innerRequest.options).toEqual({
  308. maxOutputTokens: 4_096,
  309. reasoningLevel: "low",
  310. });
  311. const storedEvents = await eventStore.getEvents(sessionId);
  312. expect(
  313. storedEvents.some(
  314. (event: any) =>
  315. event.type === SessionEventType.ToolCallStarted &&
  316. event.payload?.toolName === "WebSearch",
  317. ),
  318. ).toBe(true);
  319. expect(
  320. storedEvents.some(
  321. (event: any) =>
  322. event.type === SessionEventType.ToolCallResult &&
  323. event.payload?.toolCallId === "call_websearch",
  324. ),
  325. ).toBe(true);
  326. });
  327. it("refreshes provider runtime headers before the WebSearch internal model request", async () => {
  328. const sessionId = createSessionId("runtime-websearch-refresh-runtime-headers");
  329. const eventStore = createTestSessionEventStore();
  330. const startPlanModelSelection: ModelSelection = {
  331. providerId: "account:zai-start-plan" as never,
  332. modelId: "GLM-5.1" as never,
  333. };
  334. const refreshes: string[] = [];
  335. const requests: any[] = [];
  336. let mainRequestCount = 0;
  337. const runtime = createTestAgentRuntime(
  338. sessionId,
  339. { modelSelection: createTestModelSelection(startPlanModelSelection) },
  340. {
  341. eventStore,
  342. providerRuntimeHeadersPort: {
  343. shouldRefreshBeforeModelRequest: ({ providerId }) =>
  344. providerId === "account:zai-start-plan",
  345. async refreshBeforeModelRequest(input) {
  346. refreshes.push(`${input.providerId}:${input.reason}`);
  347. return {
  348. headersApplied: true,
  349. };
  350. },
  351. },
  352. modelFactory: createTestModelFactory({
  353. properties: { supportsNativeWebSearch: true },
  354. async generateText(request: any, observation) {
  355. if (observation.invocationContext?.metadata?.querySource === "web_search_tool") {
  356. throw new Error("WebSearch side request must use streamText");
  357. }
  358. requests.push({ observation, request });
  359. mainRequestCount++;
  360. if (mainRequestCount === 1) {
  361. return {
  362. finishReason: "tool-calls",
  363. providerMetadata: undefined,
  364. text: "",
  365. toolCalls: [
  366. {
  367. id: "call_websearch",
  368. input: { query: "latest zcode" },
  369. name: "WebSearch",
  370. },
  371. ],
  372. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  373. };
  374. }
  375. return {
  376. finishReason: "stop",
  377. providerMetadata: undefined,
  378. text: "Final answer with sources",
  379. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  380. };
  381. },
  382. async *streamText(request: any, observation) {
  383. requests.push({ observation, request });
  384. if (observation.invocationContext?.metadata?.querySource !== "web_search_tool") {
  385. throw new Error("Unexpected streaming request");
  386. }
  387. await observation.invocationContext?.refreshRuntimeHeadersBeforeAttempt?.({
  388. attempt: 1,
  389. abortSignal: request.abortSignal,
  390. providerId: String(observation.model.providerId),
  391. modelId: String(observation.model.modelId),
  392. traceContext: observation.invocationContext.traceContext,
  393. });
  394. yield { type: "start" };
  395. yield { id: "text_1", type: "text_start" };
  396. yield {
  397. id: "text_1",
  398. text: "Search summary from [Example](https://example.com)",
  399. type: "text_delta",
  400. };
  401. yield { id: "text_1", type: "text_end" };
  402. yield {
  403. finishReason: "stop",
  404. providerMetadata: { rawFinishReason: "end_turn" },
  405. type: "finish",
  406. usage: {
  407. inputTokens: 5,
  408. outputTokens: 7,
  409. serverToolUse: { webSearchRequests: 1 },
  410. totalTokens: 12,
  411. },
  412. };
  413. },
  414. } as never),
  415. },
  416. );
  417. await runtime.executeTurn("Search current ZCode info");
  418. const innerRequest = requests.find(
  419. ({ observation }) =>
  420. observation.invocationContext?.metadata?.querySource === "web_search_tool",
  421. );
  422. expect(
  423. typeof innerRequest?.observation.invocationContext?.refreshRuntimeHeadersBeforeAttempt,
  424. ).toBe("function");
  425. expect(refreshes).toEqual(["account:zai-start-plan:model-request"]);
  426. });
  427. it("formats WebSearch tool results with markdown sources reminder", () => {
  428. const text = webSearchToolEntry.formatModelContent?.({
  429. durationMs: 10,
  430. modelUsage: {
  431. inputTokens: 5,
  432. outputTokens: 7,
  433. serverToolUse: { webSearchRequests: 1 },
  434. totalTokens: 12,
  435. },
  436. query: "latest zcode",
  437. results: [{ title: "Example", url: "https://example.com" }],
  438. sources: [],
  439. webSearchRequests: 1,
  440. });
  441. expect(String(text)).toContain('Web search results for query: "latest zcode"');
  442. expect(String(text)).toContain("- [Example](https://example.com)");
  443. expect(String(text)).toContain("markdown hyperlinks");
  444. });
  445. it("extracts typed provider WebSearch results from content wrappers", () => {
  446. const output = buildWebSearchOutput(
  447. { query: "latest zcode" },
  448. {
  449. finishReason: "stop",
  450. model: modelSelection,
  451. providerMetadata: undefined,
  452. text: "",
  453. toolResults: [
  454. {
  455. id: "server_search_1",
  456. name: "web_search",
  457. output: {
  458. content: [
  459. {
  460. title: "Wrapped Example",
  461. type: "web_search_result",
  462. url: "https://example.com/wrapped",
  463. },
  464. ],
  465. },
  466. providerExecuted: true,
  467. },
  468. ],
  469. usage: {
  470. inputTokens: 1,
  471. outputTokens: 1,
  472. totalTokens: 2,
  473. serverToolUse: { webSearchRequests: 1 },
  474. },
  475. },
  476. Date.now(),
  477. );
  478. expect(output.results).toContainEqual({
  479. title: "Wrapped Example",
  480. url: "https://example.com/wrapped",
  481. });
  482. expect(output.sources).toContainEqual({
  483. title: "Wrapped Example",
  484. url: "https://example.com/wrapped",
  485. });
  486. });
  487. it("extracts markdown sources from streaming WebSearch summaries", () => {
  488. const output = buildWebSearchOutput(
  489. { query: "latest zcode" },
  490. {
  491. finishReason: "stop",
  492. model: modelSelection,
  493. providerMetadata: undefined,
  494. text: "Search summary from [Example](https://example.com).",
  495. usage: {
  496. inputTokens: 1,
  497. outputTokens: 1,
  498. totalTokens: 2,
  499. serverToolUse: { webSearchRequests: 1 },
  500. },
  501. },
  502. Date.now(),
  503. );
  504. expect(output.sources).toContainEqual({
  505. title: "Example",
  506. url: "https://example.com",
  507. });
  508. });
  509. });
  510. function createRuntime(
  511. sessionId: string,
  512. config: ConstructorParameters<typeof AgentRuntime>[1] = {},
  513. deps: Partial<ConstructorParameters<typeof AgentRuntime>[2]> = {},
  514. ): AgentRuntime {
  515. return createTestAgentRuntime(
  516. createSessionId(sessionId),
  517. {
  518. modelSelection: createTestModelSelection(modelSelection),
  519. ...config,
  520. },
  521. {
  522. eventStore: createTestSessionEventStore(),
  523. ...deps,
  524. },
  525. );
  526. }