websearch.test.ts 20 KB

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