webfetch-tool.test.ts 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  1. import { describe, expect, it, vi, beforeEach } from "vitest";
  2. import {
  3. createModelId,
  4. createModelProviderId,
  5. createHttpClientError,
  6. createSessionId,
  7. createTurnId,
  8. type HttpClientPort,
  9. type HttpClientResponse,
  10. type Model,
  11. type SessionEvent,
  12. } from "@zcode/contracts";
  13. import {
  14. clearWebFetchCacheForTests,
  15. webFetchHandler,
  16. webFetchToolEntry,
  17. } from "../src/tool/handlers/webfetch.js";
  18. import type { ToolExecutionContext } from "../src/tool/types.js";
  19. import { createTestModelFormatProperties } from "./test-runtime-model.js";
  20. const dnsLookupMock = vi.hoisted(() => vi.fn());
  21. vi.mock("node:dns/promises", () => ({
  22. lookup: dnsLookupMock,
  23. }));
  24. describe("WebFetch tool", () => {
  25. beforeEach(() => {
  26. clearWebFetchCacheForTests();
  27. dnsLookupMock.mockReset();
  28. dnsLookupMock.mockRejectedValue(new Error("DNS lookup should not run for WebFetch"));
  29. });
  30. it("upgrades explicit http URLs before fetching and answers with the active model", async () => {
  31. const httpClient = createHttpClient([
  32. response({
  33. body: "<html><body><h1>Install</h1><p>Run <strong>zcode</strong>.</p></body></html>",
  34. url: "https://example.com:12345/docs",
  35. }),
  36. ]);
  37. const model = createTestModel("Use zcode.");
  38. const output = await webFetchHandler(
  39. {
  40. url: "http://example.com:12345/docs",
  41. prompt: "What should I run?",
  42. },
  43. createContext({ httpClient, model }),
  44. );
  45. expect(httpClient.request).toHaveBeenCalledWith(
  46. expect.objectContaining({
  47. headers: {
  48. Accept: "text/markdown, text/html, */*",
  49. "User-Agent": expect.any(String),
  50. },
  51. method: "GET",
  52. redirect: "manual",
  53. timeoutMs: 60_000,
  54. url: "https://example.com:12345/docs",
  55. }),
  56. expect.any(Object),
  57. );
  58. expect(model.generateText).toHaveBeenCalledWith(
  59. expect.objectContaining({
  60. messages: expect.arrayContaining([
  61. expect.objectContaining({
  62. content: expect.stringContaining("# Install"),
  63. role: "user",
  64. }),
  65. ]),
  66. tools: [],
  67. }),
  68. );
  69. const processingRequest = vi.mocked(model.generateText).mock.calls[0]?.[0];
  70. const processingPrompt = processingRequest?.messages
  71. .map((message) => message.content)
  72. .join("\n");
  73. expect(processingPrompt).toContain("Web page content:");
  74. expect(processingPrompt).toContain("---\n# Install");
  75. expect(processingPrompt).toContain("\nWhat should I run?\n");
  76. expect(processingPrompt).toContain(
  77. "Provide a concise response based only on the content above.",
  78. );
  79. expect(processingPrompt).not.toContain(
  80. "IMPORTANT: WebFetch WILL FAIL for authenticated or private URLs.",
  81. );
  82. expect(processingRequest?.options).toEqual({
  83. maxOutputTokens: 4_096,
  84. reasoningLevel: "low",
  85. });
  86. expect(output).toMatchObject({
  87. cacheHit: false,
  88. finalUrl: "https://example.com:12345/docs",
  89. result: "Use zcode.",
  90. truncated: false,
  91. url: "http://example.com:12345/docs",
  92. });
  93. expect(webFetchToolEntry.formatModelContent?.(output)).toBe("Use zcode.");
  94. });
  95. it("rejects local IP literal URLs before any network request", async () => {
  96. const httpClient = createHttpClient([]);
  97. const model = createTestModel("unused");
  98. await expect(
  99. webFetchHandler(
  100. {
  101. url: "http://127.0.0.1:12345/status",
  102. prompt: "Summarize",
  103. },
  104. createContext({ httpClient, model }),
  105. ),
  106. ).rejects.toMatchObject({
  107. context: {
  108. hostname: "127.0.0.1",
  109. webFetchCode: "webfetch_egress_blocked",
  110. },
  111. });
  112. expect(httpClient.request).not.toHaveBeenCalled();
  113. expect(dnsLookupMock).not.toHaveBeenCalled();
  114. expect(model.generateText).not.toHaveBeenCalled();
  115. });
  116. it("fetches hostname URLs without DNS preflight", async () => {
  117. const httpClient = createHttpClient([
  118. response({
  119. body: "hostname content",
  120. contentType: "text/plain",
  121. url: "https://internal.example.com/status",
  122. }),
  123. ]);
  124. const model = createTestModel("hostname answer");
  125. const output = await webFetchHandler(
  126. { url: "https://internal.example.com/status", prompt: "Summarize" },
  127. createContext({ httpClient, model }),
  128. );
  129. expect(output.result).toBe("hostname answer");
  130. expect(dnsLookupMock).not.toHaveBeenCalled();
  131. expect(getContentRequestCalls(httpClient)).toHaveLength(1);
  132. });
  133. it("rejects localhost-style hostnames as invalid URLs before fetching", async () => {
  134. const httpClient = createHttpClient([]);
  135. const model = createTestModel("unused");
  136. await expect(
  137. webFetchHandler(
  138. { url: "https://api.localhost/status", prompt: "Summarize" },
  139. createContext({ httpClient, model }),
  140. ),
  141. ).rejects.toMatchObject({
  142. context: {
  143. hostname: "api.localhost",
  144. webFetchCode: "webfetch_invalid_url",
  145. },
  146. });
  147. expect(dnsLookupMock).not.toHaveBeenCalled();
  148. expect(httpClient.request).not.toHaveBeenCalled();
  149. expect(model.generateText).not.toHaveBeenCalled();
  150. });
  151. it.each([
  152. ["10.0.0.12", "private IPv4"],
  153. ["169.254.169.254", "link-local metadata IPv4"],
  154. ["198.18.0.1", "benchmark IPv4"],
  155. ])("rejects %s %s literal URLs before fetching", async (address) => {
  156. const httpClient = createHttpClient([]);
  157. const model = createTestModel("unused");
  158. await expect(
  159. webFetchHandler(
  160. { url: `https://${address}/status`, prompt: "Summarize" },
  161. createContext({ httpClient, model }),
  162. ),
  163. ).rejects.toMatchObject({
  164. context: {
  165. address,
  166. hostname: address,
  167. webFetchCode: "webfetch_egress_blocked",
  168. },
  169. });
  170. expect(dnsLookupMock).not.toHaveBeenCalled();
  171. expect(httpClient.request).not.toHaveBeenCalled();
  172. expect(model.generateText).not.toHaveBeenCalled();
  173. });
  174. it.each([
  175. ["::1", "loopback IPv6"],
  176. ["64:ff9b::a9fe:a9fe", "DNS64 metadata IPv6"],
  177. ["64:ff9b:1::1", "local-use IPv4/IPv6 translation"],
  178. ["100::1", "IPv6 discard-only"],
  179. ["2001:2::1", "IPv6 benchmarking"],
  180. ["2001:10::1", "ORCHIDv1"],
  181. ["2001:20::1", "ORCHIDv2"],
  182. ])("rejects %s %s literal URLs before fetching", async (address) => {
  183. const httpClient = createHttpClient([]);
  184. const model = createTestModel("unused");
  185. const urlAddress = `[${address}]`;
  186. await expect(
  187. webFetchHandler(
  188. { url: `https://${urlAddress}/status`, prompt: "Summarize" },
  189. createContext({ httpClient, model }),
  190. ),
  191. ).rejects.toMatchObject({
  192. context: {
  193. address,
  194. hostname: address,
  195. webFetchCode: "webfetch_egress_blocked",
  196. },
  197. });
  198. expect(dnsLookupMock).not.toHaveBeenCalled();
  199. expect(httpClient.request).not.toHaveBeenCalled();
  200. expect(model.generateText).not.toHaveBeenCalled();
  201. });
  202. it("allows public IP literal URLs without DNS preflight", async () => {
  203. const httpClient = createHttpClient([
  204. response({
  205. body: "public literal content",
  206. contentType: "text/plain",
  207. url: "https://8.8.8.8/dns",
  208. }),
  209. ]);
  210. const model = createTestModel("public literal answer");
  211. const output = await webFetchHandler(
  212. { url: "https://8.8.8.8/dns", prompt: "Summarize" },
  213. createContext({ httpClient, model }),
  214. );
  215. expect(output.result).toBe("public literal answer");
  216. expect(dnsLookupMock).not.toHaveBeenCalled();
  217. expect(getContentRequestCalls(httpClient)).toHaveLength(1);
  218. });
  219. it("emits network request status events for outbound HTTP", async () => {
  220. const events: SessionEvent[] = [];
  221. const httpClient = createHttpClient([
  222. response({
  223. body: "network content",
  224. contentType: "text/plain",
  225. url: "https://example.com/network",
  226. }),
  227. ]);
  228. const model = createTestModel("network answer");
  229. await webFetchHandler(
  230. { url: "https://example.com/network", prompt: "Summarize" },
  231. createContext({
  232. emitEvent: async (event) => {
  233. events.push(event);
  234. },
  235. httpClient,
  236. model,
  237. }),
  238. );
  239. const payloads = events.map((event) => event.payload as Record<string, unknown>);
  240. expect(events.map((event) => event.type)).toEqual([
  241. "network_request_status",
  242. "network_request_status",
  243. ]);
  244. expect(payloads[0]).toMatchObject({
  245. method: "GET",
  246. source: "http_client",
  247. status: "pending",
  248. toolCallId: "webfetch-call",
  249. toolName: "WebFetch",
  250. url: "https://example.com/network",
  251. });
  252. expect(payloads[1]).toMatchObject({
  253. durationMs: 5,
  254. method: "GET",
  255. source: "http_client",
  256. status: "complete",
  257. statusCode: 200,
  258. toolCallId: "webfetch-call",
  259. toolName: "WebFetch",
  260. url: "https://example.com/network",
  261. });
  262. expect(payloads[0]?.requestId).toBe(payloads[1]?.requestId);
  263. });
  264. it("emits a network error event when WebFetch fails before a response", async () => {
  265. const events: SessionEvent[] = [];
  266. const httpClient: HttpClientPort = {
  267. request: vi.fn<HttpClientPort["request"]>(async () => {
  268. throw new Error("socket down");
  269. }),
  270. };
  271. const model = createTestModel("unused");
  272. await expect(
  273. webFetchHandler(
  274. { url: "https://example.com/error", prompt: "Summarize" },
  275. createContext({
  276. emitEvent: async (event) => {
  277. events.push(event);
  278. },
  279. httpClient,
  280. model,
  281. }),
  282. ),
  283. ).rejects.toThrow("socket down");
  284. const payloads = events.map((event) => event.payload as Record<string, unknown>);
  285. expect(payloads).toHaveLength(2);
  286. expect(payloads[0]).toMatchObject({
  287. status: "pending",
  288. url: "https://example.com/error",
  289. });
  290. expect(payloads[1]).toMatchObject({
  291. error: "socket down",
  292. status: "error",
  293. url: "https://example.com/error",
  294. });
  295. expect(payloads[0]?.requestId).toBe(payloads[1]?.requestId);
  296. });
  297. it("shows a compact connect timeout cause when WebFetch fails before a response", async () => {
  298. const events: SessionEvent[] = [];
  299. const concreteCause = new Error(
  300. "Connect Timeout Error (attempted address: www.bbc.com:443, timeout: 10000ms)",
  301. );
  302. concreteCause.name = "ConnectTimeoutError";
  303. const fetchCause = new TypeError("fetch failed");
  304. Object.defineProperty(fetchCause, "cause", {
  305. configurable: true,
  306. value: concreteCause,
  307. });
  308. const httpClient: HttpClientPort = {
  309. request: vi.fn<HttpClientPort["request"]>(async (request) => {
  310. throw createHttpClientError({
  311. cause: fetchCause,
  312. code: "network_error",
  313. message: "fetch failed",
  314. url: request.url,
  315. });
  316. }),
  317. };
  318. const model = createTestModel("unused");
  319. let thrown: unknown;
  320. try {
  321. await webFetchHandler(
  322. { url: "https://www.bbc.com/sport/football/world-cup", prompt: "Summarize" },
  323. createContext({
  324. emitEvent: async (event) => {
  325. events.push(event);
  326. },
  327. httpClient,
  328. model,
  329. }),
  330. );
  331. } catch (error) {
  332. thrown = error;
  333. }
  334. expect(thrown).toBeInstanceOf(Error);
  335. expect((thrown as Error).message).toBe("Connect Timeout Error (443, timeout 10000ms)");
  336. const payloads = events.map((event) => event.payload as Record<string, unknown>);
  337. expect(payloads[1]).toMatchObject({
  338. error: "Connect Timeout Error (443, timeout 10000ms)",
  339. status: "error",
  340. url: "https://www.bbc.com/sport/football/world-cup",
  341. });
  342. });
  343. it("includes the deepest network error code when a WebFetch request fails", async () => {
  344. const events: SessionEvent[] = [];
  345. const resetCause = Object.assign(new Error("aborted"), { code: "ECONNRESET" });
  346. const httpClient: HttpClientPort = {
  347. request: vi.fn<HttpClientPort["request"]>(async (request) => {
  348. throw createHttpClientError({
  349. cause: resetCause,
  350. code: "proxy_error",
  351. message: "aborted",
  352. url: request.url,
  353. });
  354. }),
  355. };
  356. const model = createTestModel("unused");
  357. let thrown: unknown;
  358. try {
  359. await webFetchHandler(
  360. { url: "https://www.goal.com/en/world-cup/schedule-results", prompt: "Summarize" },
  361. createContext({
  362. emitEvent: async (event) => {
  363. events.push(event);
  364. },
  365. httpClient,
  366. model,
  367. }),
  368. );
  369. } catch (error) {
  370. thrown = error;
  371. }
  372. expect(thrown).toBeInstanceOf(Error);
  373. expect((thrown as Error).message).toBe("aborted (ECONNRESET)");
  374. const payloads = events.map((event) => event.payload as Record<string, unknown>);
  375. expect(payloads[1]).toMatchObject({
  376. error: "aborted (ECONNRESET)",
  377. status: "error",
  378. url: "https://www.goal.com/en/world-cup/schedule-results",
  379. });
  380. });
  381. it("does not retry transient connection resets before failing WebFetch", async () => {
  382. const events: SessionEvent[] = [];
  383. const resetCause = Object.assign(new Error("aborted"), { code: "ECONNRESET" });
  384. const httpClient: HttpClientPort = {
  385. request: vi.fn<HttpClientPort["request"]>(async (request) => {
  386. throw createHttpClientError({
  387. cause: resetCause,
  388. code: "proxy_error",
  389. message: "aborted",
  390. url: request.url,
  391. });
  392. }),
  393. };
  394. const model = createTestModel("unused");
  395. await expect(
  396. webFetchHandler(
  397. {
  398. url: "https://www.flashscore.com/football/world/world-cup-2026/results/",
  399. prompt: "Summarize",
  400. },
  401. createContext({
  402. emitEvent: async (event) => {
  403. events.push(event);
  404. },
  405. httpClient,
  406. model,
  407. }),
  408. ),
  409. ).rejects.toThrow("aborted (ECONNRESET)");
  410. expect(getContentRequestCalls(httpClient)).toHaveLength(1);
  411. expect(model.generateText).not.toHaveBeenCalled();
  412. expect(events.map((event) => (event.payload as Record<string, unknown>).status)).toEqual([
  413. "pending",
  414. "error",
  415. ]);
  416. });
  417. it("reuses cached fetched content while still applying the caller prompt", async () => {
  418. const httpClient = createHttpClient([
  419. response({
  420. body: "# Cached\n\nThe answer is in the page.",
  421. contentType: "text/plain",
  422. url: "https://example.com/cache",
  423. }),
  424. ]);
  425. const model = createTestModel("cached answer");
  426. const context = createContext({ httpClient, model });
  427. const first = await webFetchHandler(
  428. { url: "https://example.com/cache", prompt: "First prompt" },
  429. context,
  430. );
  431. const second = await webFetchHandler(
  432. { url: "https://example.com/cache", prompt: "Second prompt" },
  433. context,
  434. );
  435. expect(getContentRequestCalls(httpClient)).toHaveLength(1);
  436. expect(model.generateText).toHaveBeenCalledTimes(2);
  437. expect(first.cacheHit).toBe(false);
  438. expect(second.cacheHit).toBe(true);
  439. });
  440. it("processes non-preapproved markdown content with the lite model", async () => {
  441. const httpClient = createHttpClient([
  442. response({
  443. body: "# Markdown\n\nThe answer is already readable.",
  444. contentType: "text/markdown",
  445. url: "https://example.com/markdown",
  446. }),
  447. ]);
  448. const model = createTestModel("processed markdown");
  449. const output = await webFetchHandler(
  450. { url: "https://example.com/markdown", prompt: "Summarize" },
  451. createContext({ httpClient, model }),
  452. );
  453. expect(getContentRequestCalls(httpClient)).toHaveLength(1);
  454. expect(model.generateText).toHaveBeenCalledTimes(1);
  455. expect(output).toMatchObject({
  456. cacheHit: false,
  457. contentType: "text/markdown",
  458. finalUrl: "https://example.com/markdown",
  459. result: "processed markdown",
  460. truncated: false,
  461. });
  462. });
  463. it("returns preapproved markdown content directly without invoking the lite model", async () => {
  464. const httpClient = createHttpClient([
  465. response({
  466. body: "# Direct markdown\n\nThe answer is already readable.",
  467. contentType: "text/markdown",
  468. url: "https://docs.python.org/3/",
  469. }),
  470. ]);
  471. const model = createTestModel("unused");
  472. const output = await webFetchHandler(
  473. { url: "https://docs.python.org/3/", prompt: "Summarize" },
  474. createContext({ httpClient, model }),
  475. );
  476. expect(getContentRequestCalls(httpClient)).toHaveLength(1);
  477. expect(model.generateText).not.toHaveBeenCalled();
  478. expect(output).toMatchObject({
  479. cacheHit: false,
  480. contentType: "text/markdown",
  481. finalUrl: "https://docs.python.org/3/",
  482. result: "# Direct markdown\n\nThe answer is already readable.",
  483. truncated: false,
  484. });
  485. });
  486. it("uses the preapproved processing prompt branch when direct markdown return does not apply", async () => {
  487. const httpClient = createHttpClient([
  488. response({
  489. body: "<html><body><h1>Docs</h1><p>Use pathlib.</p></body></html>",
  490. contentType: "text/html",
  491. url: "https://docs.python.org/3/library/pathlib.html",
  492. }),
  493. ]);
  494. const model = createTestModel("pathlib answer");
  495. await webFetchHandler(
  496. { url: "https://docs.python.org/3/library/pathlib.html", prompt: "Summarize" },
  497. createContext({ httpClient, model }),
  498. );
  499. const processingRequest = vi.mocked(model.generateText).mock.calls[0]?.[0];
  500. const processingPrompt = processingRequest?.messages
  501. .map((message) => message.content)
  502. .join("\n");
  503. expect(processingPrompt).toContain(
  504. "Provide a concise response based on the content above. Include relevant details, code examples, and documentation excerpts as needed.",
  505. );
  506. expect(processingPrompt).not.toContain("strict 125-character maximum");
  507. });
  508. it("allows same-host redirects modulo www", async () => {
  509. const httpClient = createHttpClient([
  510. response({
  511. headers: { location: "https://www.example.com/final" },
  512. status: 301,
  513. statusText: "Moved Permanently",
  514. url: "https://example.com/start",
  515. }),
  516. response({
  517. body: "final content",
  518. contentType: "text/plain",
  519. url: "https://www.example.com/final",
  520. }),
  521. ]);
  522. const model = createTestModel("final answer");
  523. const output = await webFetchHandler(
  524. { url: "https://example.com/start", prompt: "Summarize" },
  525. createContext({ httpClient, model }),
  526. );
  527. expect(output.redirects).toEqual([
  528. {
  529. from: "https://example.com/start",
  530. status: 301,
  531. to: "https://www.example.com/final",
  532. },
  533. ]);
  534. expect(output.finalUrl).toBe("https://www.example.com/final");
  535. });
  536. it("returns cross-host redirects as a model-readable tool result", async () => {
  537. const httpClient = createHttpClient([
  538. response({
  539. headers: { location: "https://evil.example/final" },
  540. status: 302,
  541. statusText: "Found",
  542. url: "https://example.com/start",
  543. }),
  544. ]);
  545. const model = createTestModel("unused");
  546. const output = await webFetchHandler(
  547. { url: "https://example.com/start", prompt: "Summarize" },
  548. createContext({ httpClient, model }),
  549. );
  550. expect(getContentRequestCalls(httpClient)).toHaveLength(1);
  551. expect(model.generateText).not.toHaveBeenCalled();
  552. expect(output).toMatchObject({
  553. bytes: expect.any(Number),
  554. contentType: "text/plain",
  555. finalUrl: "https://example.com/start",
  556. redirects: [
  557. {
  558. from: "https://example.com/start",
  559. status: 302,
  560. to: "https://evil.example/final",
  561. },
  562. ],
  563. status: 302,
  564. statusText: "Found",
  565. truncated: false,
  566. url: "https://example.com/start",
  567. });
  568. expect(output.result).toBe(
  569. [
  570. "REDIRECT DETECTED: The URL redirects to a different host.",
  571. "",
  572. "Original URL: https://example.com/start",
  573. "Redirect URL: https://evil.example/final",
  574. "Status: 302 Found",
  575. "",
  576. "To complete your request, I need to fetch content from the redirected URL. Please use WebFetch again with these parameters:",
  577. '- url: "https://evil.example/final"',
  578. '- prompt: "Summarize"',
  579. ].join("\n"),
  580. );
  581. });
  582. it("uses status-code text for redirect outputs when response status text is empty", async () => {
  583. const httpClient = createHttpClient([
  584. response({
  585. headers: { location: "https://evil.example/final" },
  586. status: 302,
  587. statusText: "",
  588. url: "https://example.com/start",
  589. }),
  590. ]);
  591. const model = createTestModel("unused");
  592. const output = await webFetchHandler(
  593. { url: "https://example.com/start", prompt: "Summarize" },
  594. createContext({ httpClient, model }),
  595. );
  596. expect(output.statusText).toBe("Found");
  597. expect(output.result).toContain("Status: 302 Found");
  598. });
  599. it("returns credential redirects as a redacted model-readable tool result", async () => {
  600. const httpClient = createHttpClient([
  601. response({
  602. headers: { location: "https://user:secret@evil.example/final" },
  603. status: 302,
  604. statusText: "Found",
  605. url: "https://example.com/start",
  606. }),
  607. ]);
  608. const model = createTestModel("unused");
  609. const output = await webFetchHandler(
  610. { url: "https://example.com/start", prompt: "Summarize" },
  611. createContext({ httpClient, model }),
  612. );
  613. expect(getContentRequestCalls(httpClient)).toHaveLength(1);
  614. expect(model.generateText).not.toHaveBeenCalled();
  615. expect(output.result).toContain("REDIRECT DETECTED");
  616. expect(output.result).toContain('url: "https://evil.example/final"');
  617. expect(output.result).not.toContain("user:secret");
  618. expect(output.redirects).toEqual([
  619. {
  620. from: "https://example.com/start",
  621. status: 302,
  622. to: "https://evil.example/final",
  623. },
  624. ]);
  625. });
  626. it("returns private-host redirects as a model-readable tool result without fetching them", async () => {
  627. const httpClient = createHttpClient([
  628. response({
  629. headers: { location: "https://localhost/final" },
  630. status: 302,
  631. statusText: "Found",
  632. url: "https://example.com/start",
  633. }),
  634. ]);
  635. const model = createTestModel("unused");
  636. const output = await webFetchHandler(
  637. { url: "https://example.com/start", prompt: "Summarize" },
  638. createContext({ httpClient, model }),
  639. );
  640. expect(getContentRequestCalls(httpClient)).toHaveLength(1);
  641. expect(model.generateText).not.toHaveBeenCalled();
  642. expect(output.result).toContain("REDIRECT DETECTED");
  643. expect(output.result).toContain('url: "https://localhost/final"');
  644. });
  645. it("returns redirect responses with missing Location as HTTP errors", async () => {
  646. const httpClient = createHttpClient([
  647. response({
  648. body: "redirect error body",
  649. status: 302,
  650. statusText: "Found",
  651. url: "https://example.com/start",
  652. }),
  653. ]);
  654. const model = createTestModel("unused");
  655. const output = await webFetchHandler(
  656. { url: "https://example.com/start", prompt: "Summarize" },
  657. createContext({ httpClient, model }),
  658. );
  659. expect(getContentRequestCalls(httpClient)).toHaveLength(1);
  660. expect(model.generateText).not.toHaveBeenCalled();
  661. expect(output).toMatchObject({
  662. bytes: 0,
  663. contentType: "text/plain",
  664. finalUrl: "https://example.com/start",
  665. redirects: [],
  666. status: 302,
  667. statusText: "Found",
  668. truncated: false,
  669. url: "https://example.com/start",
  670. });
  671. expect(output.result).toContain("The server returned HTTP 302 Found.");
  672. expect(output.result).toContain("The response body was not retrieved.");
  673. expect(output.result).not.toContain("redirect error body");
  674. });
  675. it("does not treat non-followable 3xx responses as redirects", async () => {
  676. const httpClient = createHttpClient([
  677. response({
  678. body: "not modified body",
  679. headers: { location: "https://evil.example/final" },
  680. status: 304,
  681. statusText: "Not Modified",
  682. url: "https://example.com/start",
  683. }),
  684. ]);
  685. const model = createTestModel("unused");
  686. const output = await webFetchHandler(
  687. { url: "https://example.com/start", prompt: "Summarize" },
  688. createContext({ httpClient, model }),
  689. );
  690. expect(getContentRequestCalls(httpClient)).toHaveLength(1);
  691. expect(model.generateText).not.toHaveBeenCalled();
  692. expect(output).toMatchObject({
  693. bytes: 0,
  694. finalUrl: "https://example.com/start",
  695. redirects: [],
  696. status: 304,
  697. statusText: "Not Modified",
  698. });
  699. expect(output.result).toContain("The server returned HTTP 304 Not Modified.");
  700. expect(output.result).not.toContain("REDIRECT DETECTED");
  701. expect(output.result).not.toContain("not modified body");
  702. });
  703. it("returns non-2xx responses as HTTP errors without applying the lite model", async () => {
  704. const httpClient = createHttpClient([
  705. response({
  706. body: "not found body",
  707. status: 404,
  708. statusText: "Not Found",
  709. url: "https://example.com/missing",
  710. }),
  711. ]);
  712. const model = createTestModel("unused");
  713. const output = await webFetchHandler(
  714. { url: "https://example.com/missing", prompt: "Summarize" },
  715. createContext({ httpClient, model }),
  716. );
  717. expect(getContentRequestCalls(httpClient)).toHaveLength(1);
  718. expect(model.generateText).not.toHaveBeenCalled();
  719. expect(output).toMatchObject({
  720. bytes: 0,
  721. contentType: "text/plain",
  722. finalUrl: "https://example.com/missing",
  723. redirects: [],
  724. status: 404,
  725. statusText: "Not Found",
  726. truncated: false,
  727. url: "https://example.com/missing",
  728. });
  729. expect(output.result).toContain("The server returned HTTP 404 Not Found.");
  730. expect(output.result).toContain("The response body was not retrieved.");
  731. expect(output.result).not.toContain("not found body");
  732. });
  733. it("uses status-code text for HTTP error outputs when response status text is empty", async () => {
  734. const httpClient = createHttpClient([
  735. response({
  736. body: "not found body",
  737. status: 404,
  738. statusText: "",
  739. url: "https://example.com/missing",
  740. }),
  741. ]);
  742. const model = createTestModel("unused");
  743. const output = await webFetchHandler(
  744. { url: "https://example.com/missing", prompt: "Summarize" },
  745. createContext({ httpClient, model }),
  746. );
  747. expect(output.statusText).toBe("Not Found");
  748. expect(output.result).toContain("The server returned HTTP 404 Not Found.");
  749. });
  750. it("raises an egress-blocked error before generic HTTP error formatting", async () => {
  751. const httpClient = createHttpClient([
  752. response({
  753. body: "blocked body",
  754. headers: { "x-proxy-error": "blocked-by-allowlist" },
  755. status: 403,
  756. statusText: "Forbidden",
  757. url: "https://blocked.example/docs",
  758. }),
  759. ]);
  760. const model = createTestModel("unused");
  761. await expect(
  762. webFetchHandler(
  763. { url: "https://blocked.example/docs", prompt: "Summarize" },
  764. createContext({ httpClient, model }),
  765. ),
  766. ).rejects.toMatchObject({
  767. context: {
  768. domain: "blocked.example",
  769. error_type: "EGRESS_BLOCKED",
  770. webFetchCode: "webfetch_egress_blocked",
  771. },
  772. });
  773. expect(getContentRequestCalls(httpClient)).toHaveLength(1);
  774. expect(model.generateText).not.toHaveBeenCalled();
  775. });
  776. it("maps public egress policy blocks to WebFetch egress errors", async () => {
  777. const events: SessionEvent[] = [];
  778. const httpClient: HttpClientPort = {
  779. request: vi.fn<HttpClientPort["request"]>(async (request) => {
  780. throw createHttpClientError({
  781. code: "egress_blocked",
  782. message:
  783. "HTTP public egress blocked metadata.example because it resolved to 169.254.169.254",
  784. url: request.url,
  785. });
  786. }),
  787. };
  788. const model = createTestModel("unused");
  789. const request = webFetchHandler(
  790. { url: "https://metadata.example/latest", prompt: "Summarize" },
  791. createContext({
  792. emitEvent: async (event) => {
  793. events.push(event);
  794. },
  795. httpClient,
  796. model,
  797. }),
  798. );
  799. await expect(request).rejects.toThrow(
  800. "HTTP public egress blocked metadata.example because it resolved to a non-public address",
  801. );
  802. await expect(request).rejects.toMatchObject({
  803. context: {
  804. domain: "metadata.example",
  805. error_type: "EGRESS_BLOCKED",
  806. webFetchCode: "webfetch_egress_blocked",
  807. },
  808. });
  809. expect(events.map((event) => event.payload as Record<string, unknown>)[1]).toMatchObject({
  810. error:
  811. "HTTP public egress blocked metadata.example because it resolved to a non-public address",
  812. status: "error",
  813. });
  814. expect(model.generateText).not.toHaveBeenCalled();
  815. });
  816. it("rejects local hostnames before any network request", async () => {
  817. const httpClient = createHttpClient([]);
  818. const model = createTestModel("unused");
  819. await expect(
  820. webFetchHandler(
  821. { url: "https://localhost/status", prompt: "Summarize" },
  822. createContext({ httpClient, model }),
  823. ),
  824. ).rejects.toThrow("public hostname");
  825. expect(httpClient.request).not.toHaveBeenCalled();
  826. });
  827. it("rejects URLs longer than the WebFetch runtime limit", async () => {
  828. const httpClient = createHttpClient([]);
  829. const model = createTestModel("unused");
  830. const longUrl = `https://example.com/${"a".repeat(2001)}`;
  831. await expect(
  832. webFetchHandler({ url: longUrl, prompt: "Summarize" }, createContext({ httpClient, model })),
  833. ).rejects.toThrow("URL is too long");
  834. expect(httpClient.request).not.toHaveBeenCalled();
  835. });
  836. it("skips external domain safety preflight and fetches the target URL directly", async () => {
  837. const httpClient = createHttpClient([
  838. response({
  839. body: "target content wins over domain safety service",
  840. contentType: "text/plain",
  841. url: "https://blocked.example/docs",
  842. }),
  843. ]);
  844. const model = createTestModel("target answer");
  845. const output = await webFetchHandler(
  846. { url: "https://blocked.example/docs", prompt: "Summarize" },
  847. createContext({ httpClient, model }),
  848. );
  849. expect(output).toMatchObject({
  850. finalUrl: "https://blocked.example/docs",
  851. result: "target answer",
  852. });
  853. expect(httpClient.request).toHaveBeenCalledTimes(1);
  854. expect(getContentRequestCalls(httpClient)).toHaveLength(1);
  855. expect(getContentRequestCalls(httpClient)[0]?.[0]).toMatchObject({
  856. method: "GET",
  857. url: "https://blocked.example/docs",
  858. });
  859. });
  860. it("does not fail when the old domain safety service is unreachable", async () => {
  861. const httpClient: HttpClientPort = {
  862. request: vi.fn<HttpClientPort["request"]>(async (request) => {
  863. if (request.url !== "https://example.com/docs") {
  864. throw new Error(`unexpected WebFetch request: ${request.url}`);
  865. }
  866. return response({
  867. body: "reachable target",
  868. contentType: "text/plain",
  869. url: request.url,
  870. });
  871. }),
  872. };
  873. const model = createTestModel("reachable answer");
  874. const output = await webFetchHandler(
  875. { url: "https://example.com/docs", prompt: "Summarize" },
  876. createContext({ httpClient, model }),
  877. );
  878. expect(output.result).toBe("reachable answer");
  879. expect(httpClient.request).toHaveBeenCalledTimes(1);
  880. expect(getContentRequestCalls(httpClient)).toHaveLength(1);
  881. });
  882. });
  883. function createContext(options: {
  884. emitEvent?: (event: SessionEvent) => Promise<void>;
  885. httpClient: HttpClientPort;
  886. model: Model;
  887. }): ToolExecutionContext {
  888. const modelSelection = {
  889. modelId: createModelId("test-model"),
  890. providerId: createModelProviderId("test"),
  891. };
  892. return {
  893. abortSignal: new AbortController().signal,
  894. emitEvent: options.emitEvent,
  895. httpClientPort: options.httpClient,
  896. model: options.model,
  897. modelSelection,
  898. sessionId: createSessionId("webfetch"),
  899. toolCallId: "webfetch-call",
  900. traceId: "trace-webfetch" as never,
  901. turnId: createTurnId("webfetch"),
  902. workingDirectory: "/tmp/zcode-webfetch-tool",
  903. workspaceRoot: "/tmp/zcode-webfetch-tool",
  904. };
  905. }
  906. function createHttpClient(responses: HttpClientResponse[]): HttpClientPort {
  907. return {
  908. request: vi.fn<HttpClientPort["request"]>(async () => {
  909. const next = responses.shift();
  910. if (!next) {
  911. throw new Error("No fake WebFetch response was configured");
  912. }
  913. return next;
  914. }),
  915. };
  916. }
  917. type HttpClientRequestCall = Parameters<HttpClientPort["request"]>;
  918. function getContentRequestCalls(httpClient: HttpClientPort): HttpClientRequestCall[] {
  919. return vi.mocked(httpClient.request).mock.calls;
  920. }
  921. function createTestModel(text: string): Model {
  922. const model: Model = {
  923. providerId: createModelProviderId("test"),
  924. modelId: createModelId("test-model"),
  925. properties: {
  926. contextWindow: 200_000,
  927. ...createTestModelFormatProperties(),
  928. supportsToolCall: true,
  929. supportsJsonSchemaOutput: true,
  930. supportsNativeWebSearch: false,
  931. supportsMidConversationSystem: true,
  932. },
  933. optionSpecs: {
  934. reasoningLevel: { values: ["low", "high"] },
  935. maxOutputTokens: { max: 32_000 },
  936. },
  937. options: { maxOutputTokens: 32_000, reasoningLevel: "high" },
  938. bind() {
  939. return this;
  940. },
  941. generateText: vi.fn<Model["generateText"]>(async () => ({
  942. finishReason: "stop",
  943. model: { providerId: model.providerId, modelId: model.modelId },
  944. text,
  945. usage: {},
  946. })),
  947. async *streamText() {
  948. yield { type: "start" };
  949. yield { finishReason: "stop", type: "finish", usage: {} };
  950. },
  951. };
  952. return model;
  953. }
  954. function response(options: {
  955. body?: string;
  956. contentType?: string;
  957. headers?: Record<string, string>;
  958. status?: number;
  959. statusText?: string;
  960. url: string;
  961. }): HttpClientResponse {
  962. const body = new TextEncoder().encode(options.body ?? "");
  963. const headers = {
  964. "content-type": options.contentType ?? "text/html; charset=utf-8",
  965. ...options.headers,
  966. };
  967. return {
  968. body,
  969. bytes: body.byteLength,
  970. durationMs: 5,
  971. headers,
  972. status: options.status ?? 200,
  973. statusText: options.statusText ?? "OK",
  974. url: options.url,
  975. };
  976. }