websearch.test.ts 21 KB

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