tool-webfetch.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import { describe, expect, test } from "bun:test"
  2. import { Duration, Effect, Fiber, Layer, Schema } from "effect"
  3. import * as TestClock from "effect/testing/TestClock"
  4. import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
  5. import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
  6. import { LayerNode } from "@opencode-ai/util/effect/layer-node"
  7. import { LayerNodePlatform } from "@opencode-ai/util/effect/app-node-platform"
  8. import { Permission } from "@opencode-ai/core/permission"
  9. import { Session } from "@opencode-ai/core/session"
  10. import { Tool } from "@opencode-ai/core/tool"
  11. import { WebFetchTool } from "@opencode-ai/core/tool/plugin/webfetch"
  12. import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
  13. import { Image } from "@opencode-ai/core/image"
  14. import { testEffect } from "./lib/effect"
  15. import { imagePassthrough } from "./lib/image"
  16. import { toolIdentity, executeTool, registerToolPlugin, toolDefinitions } from "./lib/tool"
  17. const webFetchToolNode = makeLocationNode({
  18. name: "test/webfetch-tool-plugin",
  19. layer: Layer.effectDiscard(registerToolPlugin(WebFetchTool.Plugin)),
  20. deps: [Tool.node, Permission.node, LayerNodePlatform.httpClient],
  21. })
  22. const sessionID = Session.ID.make("ses_webfetch_test")
  23. const requests: Array<{ readonly url: string; readonly headers: Record<string, string> }> = []
  24. const assertions: Permission.AssertInput[] = []
  25. let respond = (_request: HttpClientRequest.HttpClientRequest) =>
  26. Effect.succeed(new Response("hello", { headers: { "content-type": "text/plain" } }))
  27. const http = Layer.succeed(
  28. HttpClient.HttpClient,
  29. HttpClient.make((request) =>
  30. Effect.sync(() => requests.push({ url: request.url, headers: request.headers })).pipe(
  31. Effect.andThen(respond(request)),
  32. Effect.map((response) => HttpClientResponse.fromWeb(request, response)),
  33. ),
  34. ),
  35. )
  36. const permission = Layer.succeed(
  37. Permission.Service,
  38. Permission.Service.of({
  39. assert: (input) => Effect.sync(() => assertions.push(input)),
  40. ask: () => Effect.die("unused"),
  41. reply: () => Effect.die("unused"),
  42. get: () => Effect.die("unused"),
  43. forSession: () => Effect.die("unused"),
  44. list: () => Effect.die("unused"),
  45. }),
  46. )
  47. const toolLayer = (replacements: LayerNode.Replacements = []) =>
  48. AppNodeBuilder.build(LayerNode.group([Tool.node, webFetchToolNode]), [
  49. [Permission.node, permission],
  50. [Image.node, imagePassthrough],
  51. ...replacements,
  52. ])
  53. const it = testEffect(toolLayer([[LayerNodePlatform.httpClient, http]]))
  54. const live = testEffect(toolLayer())
  55. const reset = () => {
  56. requests.length = 0
  57. assertions.length = 0
  58. respond = () => Effect.succeed(new Response("hello", { headers: { "content-type": "text/plain" } }))
  59. }
  60. const call = (input: typeof WebFetchTool.Input.Type, id = "call-webfetch") => ({
  61. sessionID,
  62. ...toolIdentity,
  63. call: { type: "tool-call" as const, id, name: "webfetch", input },
  64. })
  65. describe("WebFetchTool helpers", () => {
  66. test("defaults format and rejects invalid timeout controls", () => {
  67. const decode = Schema.decodeUnknownSync(WebFetchTool.Input)
  68. expect(decode({ url: "https://example.com" })).toEqual({ url: "https://example.com", format: "markdown" })
  69. expect(() => decode({ url: "https://example.com", timeout: 0 })).toThrow()
  70. expect(() => decode({ url: "https://example.com", timeout: WebFetchTool.MAX_TIMEOUT_SECONDS + 1 })).toThrow()
  71. })
  72. test("ports HTML text and markdown conversions without active content", () => {
  73. const html = "<h1>Hello</h1><script>bad()</script><p>world <strong>wide</strong></p><style>.bad {}</style>"
  74. expect(WebFetchTool.extractTextFromHTML(html)).toBe("Helloworld wide")
  75. expect(WebFetchTool.convertHTMLToMarkdown(html)).toBe("# Hello\n\nworld **wide**")
  76. })
  77. })
  78. describe("WebFetchTool registration", () => {
  79. it.effect("registers and fetches an ordinary hostname HTTP URL without rewriting it", () =>
  80. Effect.gen(function* () {
  81. reset()
  82. const registry = yield* Tool.Service
  83. const url = "http://example.com/public"
  84. expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["webfetch", "execute"])
  85. expect(yield* executeTool(registry, call({ url, format: "text", timeout: 4 }))).toEqual({
  86. status: "completed",
  87. output: { url, contentType: "text/plain", format: "text", output: "hello" },
  88. content: [{ type: "text", text: "hello" }],
  89. metadata: { contentType: "text/plain" },
  90. })
  91. expect(assertions).toMatchObject([
  92. { sessionID, action: "webfetch", resources: [url], save: ["*"], metadata: { url, format: "text", timeout: 4 } },
  93. ])
  94. expect(requests).toMatchObject([{ url, headers: { accept: expect.stringContaining("text/plain;q=1.0") } }])
  95. }),
  96. )
  97. it.effect("accepts localhost URLs with the same requested-URL permission check", () =>
  98. Effect.gen(function* () {
  99. reset()
  100. const registry = yield* Tool.Service
  101. const url = "http://localhost/private"
  102. expect(yield* executeTool(registry, call({ url, format: "text" }))).toMatchObject({
  103. status: "completed",
  104. content: [{ type: "text", text: "hello" }],
  105. })
  106. expect(assertions).toMatchObject([
  107. { sessionID, action: "webfetch", resources: [url], save: ["*"], metadata: { url, format: "text" } },
  108. ])
  109. expect(requests.map((request) => request.url)).toEqual([url])
  110. }),
  111. )
  112. live.effect("follows redirects while approving only the requested URL", () =>
  113. Effect.acquireUseRelease(
  114. Effect.sync(() =>
  115. Bun.serve({
  116. port: 0,
  117. fetch: (request) =>
  118. new URL(request.url).pathname === "/redirect"
  119. ? new Response("", { status: 302, headers: { location: "/target" } })
  120. : new Response("redirected", { headers: { "content-type": "text/plain" } }),
  121. }),
  122. ),
  123. (server) =>
  124. Effect.gen(function* () {
  125. reset()
  126. const registry = yield* Tool.Service
  127. const url = new URL("/redirect", server.url).toString()
  128. expect(yield* executeTool(registry, call({ url, format: "text" }))).toMatchObject({
  129. status: "completed",
  130. content: [{ type: "text", text: "redirected" }],
  131. })
  132. expect(assertions).toMatchObject([
  133. { sessionID, action: "webfetch", resources: [url], save: ["*"], metadata: { url, format: "text" } },
  134. ])
  135. }),
  136. (server) => Effect.promise(() => server.stop(true)),
  137. ),
  138. )
  139. it.effect("rejects non-HTTP schemes before permission or transport", () =>
  140. Effect.gen(function* () {
  141. reset()
  142. const registry = yield* Tool.Service
  143. // toSessionError unwraps the "Unable to fetch <url>" ToolFailure to its cause message.
  144. expect(yield* executeTool(registry, call({ url: "file:///etc/passwd", format: "text" }))).toEqual({
  145. status: "error",
  146. error: { type: "unknown", message: "URL must use http:// or https://" },
  147. })
  148. expect(assertions).toEqual([])
  149. expect(requests).toEqual([])
  150. }),
  151. )
  152. it.effect("converts HTML to requested markdown and text", () =>
  153. Effect.gen(function* () {
  154. reset()
  155. respond = () =>
  156. Effect.succeed(
  157. new Response("<h1>Hello</h1><p>world</p><script>bad()</script>", {
  158. headers: { "content-type": "text/html; charset=utf-8" },
  159. }),
  160. )
  161. const registry = yield* Tool.Service
  162. expect(yield* executeTool(registry, call({ url: "https://1.1.1.1", format: "markdown" }))).toMatchObject({
  163. status: "completed",
  164. content: [{ type: "text", text: "# Hello\n\nworld" }],
  165. })
  166. expect(yield* executeTool(registry, call({ url: "https://1.1.1.1", format: "text" }))).toMatchObject({
  167. status: "completed",
  168. content: [{ type: "text", text: "Helloworld" }],
  169. })
  170. }),
  171. )
  172. it.effect("returns an error result when HTML-to-Markdown conversion throws", () =>
  173. Effect.gen(function* () {
  174. reset()
  175. respond = () =>
  176. Effect.succeed(
  177. new Response("<div>".repeat(10_000) + "content" + "</div>".repeat(10_000), {
  178. headers: { "content-type": "text/html" },
  179. }),
  180. )
  181. const registry = yield* Tool.Service
  182. const url = "https://1.1.1.1/deep-html"
  183. expect(yield* executeTool(registry, call({ url, format: "markdown" }))).toMatchObject({
  184. status: "error",
  185. error: { type: "unknown" },
  186. })
  187. }),
  188. )
  189. it.effect("rejects declared and streamed oversized bodies", () =>
  190. Effect.gen(function* () {
  191. reset()
  192. const registry = yield* Tool.Service
  193. respond = () =>
  194. Effect.succeed(
  195. new Response("small", {
  196. headers: { "content-type": "text/plain", "content-length": String(WebFetchTool.MAX_RESPONSE_BYTES + 1) },
  197. }),
  198. )
  199. expect(yield* executeTool(registry, call({ url: "https://1.1.1.1/declared", format: "text" }))).toEqual({
  200. status: "error",
  201. error: {
  202. type: "unknown",
  203. message: `Response too large (exceeds ${WebFetchTool.MAX_RESPONSE_BYTES} byte limit)`,
  204. },
  205. })
  206. respond = () =>
  207. Effect.succeed(
  208. new Response("x".repeat(WebFetchTool.MAX_RESPONSE_BYTES + 1), { headers: { "content-type": "text/plain" } }),
  209. )
  210. expect(yield* executeTool(registry, call({ url: "https://1.1.1.1/streamed", format: "text" }))).toEqual({
  211. status: "error",
  212. error: {
  213. type: "unknown",
  214. message: `Response too large (exceeds ${WebFetchTool.MAX_RESPONSE_BYTES} byte limit)`,
  215. },
  216. })
  217. }),
  218. )
  219. it.effect("keeps images and files unsupported until typed outcomes can carry attachments", () =>
  220. Effect.gen(function* () {
  221. reset()
  222. const registry = yield* Tool.Service
  223. respond = () => Effect.succeed(new Response("png", { headers: { "content-type": "image/png" } }))
  224. expect(yield* executeTool(registry, call({ url: "https://1.1.1.1/image", format: "html" }))).toEqual({
  225. status: "error",
  226. error: { type: "unknown", message: "Unsupported fetched image content type: image/png" },
  227. })
  228. respond = () => Effect.succeed(new Response("pdf", { headers: { "content-type": "application/pdf" } }))
  229. expect(yield* executeTool(registry, call({ url: "https://1.1.1.1/file", format: "html" }))).toEqual({
  230. status: "error",
  231. error: { type: "unknown", message: "Unsupported fetched file content type: application/pdf" },
  232. })
  233. }),
  234. )
  235. it.effect("retries Cloudflare challenges with an honest user agent", () =>
  236. Effect.gen(function* () {
  237. reset()
  238. let count = 0
  239. respond = () =>
  240. Effect.succeed(
  241. ++count === 1
  242. ? new Response("challenge", { status: 403, headers: { "cf-mitigated": "challenge" } })
  243. : new Response("ok", { headers: { "content-type": "text/plain" } }),
  244. )
  245. const registry = yield* Tool.Service
  246. expect(yield* executeTool(registry, call({ url: "https://1.1.1.1", format: "text" }))).toMatchObject({
  247. status: "completed",
  248. content: [{ type: "text", text: "ok" }],
  249. })
  250. expect(requests).toHaveLength(2)
  251. expect(requests[0]?.headers["user-agent"]).toContain("Mozilla/5.0")
  252. expect(requests[1]?.headers["user-agent"]).toBe("opencode")
  253. }),
  254. )
  255. it.effect("times out stalled requests", () =>
  256. Effect.gen(function* () {
  257. reset()
  258. respond = () => Effect.never
  259. const registry = yield* Tool.Service
  260. const fiber = yield* executeTool(
  261. registry,
  262. call({ url: "https://1.1.1.1/slow", format: "text", timeout: 1 }),
  263. ).pipe(Effect.forkChild)
  264. yield* TestClock.adjust(Duration.seconds(1))
  265. expect(yield* Fiber.join(fiber)).toEqual({
  266. status: "error",
  267. error: { type: "unknown", message: "Request timed out" },
  268. })
  269. }),
  270. )
  271. })