websearch.test.ts 19 KB

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