tool-webfetch.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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/core/effect/layer-node"
  7. import { LayerNodePlatform } from "@opencode-ai/core/effect/app-node-platform"
  8. import { PermissionV2 } from "@opencode-ai/core/permission"
  9. import { SessionV2 } from "@opencode-ai/core/session"
  10. import { ToolRegistry } from "@opencode-ai/core/tool/registry"
  11. import { WebFetchTool } from "@opencode-ai/core/tool/webfetch"
  12. import { ToolOutputStore } from "@opencode-ai/core/tool-output-store"
  13. import { makeLocationNode } from "@opencode-ai/core/effect/app-node"
  14. import { testEffect } from "./lib/effect"
  15. import { toolIdentity, executeTool, registerToolPlugin, settleTool, toolDefinitions } from "./lib/tool"
  16. const webFetchToolNode = makeLocationNode({
  17. name: "test/webfetch-tool-plugin",
  18. layer: Layer.effectDiscard(registerToolPlugin(WebFetchTool.Plugin)),
  19. deps: [ToolRegistry.toolsNode, PermissionV2.node, LayerNodePlatform.httpClient],
  20. })
  21. const sessionID = SessionV2.ID.make("ses_webfetch_test")
  22. const requests: Array<{ readonly url: string; readonly headers: Record<string, string> }> = []
  23. const assertions: PermissionV2.AssertInput[] = []
  24. let respond = (_request: HttpClientRequest.HttpClientRequest) =>
  25. Effect.succeed(new Response("hello", { headers: { "content-type": "text/plain" } }))
  26. const http = Layer.succeed(
  27. HttpClient.HttpClient,
  28. HttpClient.make((request) =>
  29. Effect.sync(() => requests.push({ url: request.url, headers: request.headers })).pipe(
  30. Effect.andThen(respond(request)),
  31. Effect.map((response) => HttpClientResponse.fromWeb(request, response)),
  32. ),
  33. ),
  34. )
  35. const permission = Layer.succeed(
  36. PermissionV2.Service,
  37. PermissionV2.Service.of({
  38. assert: (input) => Effect.sync(() => assertions.push(input)),
  39. ask: () => Effect.die("unused"),
  40. reply: () => Effect.die("unused"),
  41. get: () => Effect.die("unused"),
  42. forSession: () => Effect.die("unused"),
  43. list: () => Effect.die("unused"),
  44. }),
  45. )
  46. const toolLayer = (replacements: LayerNode.Replacements = []) =>
  47. AppNodeBuilder.build(LayerNode.group([ToolRegistry.node, ToolRegistry.toolsNode, webFetchToolNode]), [
  48. [PermissionV2.node, permission],
  49. [ToolOutputStore.node, ToolOutputStore.nodeWithoutConfig],
  50. ...replacements,
  51. ])
  52. const it = testEffect(toolLayer([[LayerNodePlatform.httpClient, http]]))
  53. const live = testEffect(toolLayer())
  54. const reset = () => {
  55. requests.length = 0
  56. assertions.length = 0
  57. respond = () => Effect.succeed(new Response("hello", { headers: { "content-type": "text/plain" } }))
  58. }
  59. const call = (input: typeof WebFetchTool.Input.Type, id = "call-webfetch") => ({
  60. sessionID,
  61. ...toolIdentity,
  62. call: { type: "tool-call" as const, id, name: "webfetch", input },
  63. })
  64. describe("WebFetchTool helpers", () => {
  65. test("defaults format and rejects invalid timeout controls", () => {
  66. const decode = Schema.decodeUnknownSync(WebFetchTool.Input)
  67. expect(decode({ url: "https://example.com" })).toEqual({ url: "https://example.com", format: "markdown" })
  68. expect(() => decode({ url: "https://example.com", timeout: 0 })).toThrow()
  69. expect(() => decode({ url: "https://example.com", timeout: WebFetchTool.MAX_TIMEOUT_SECONDS + 1 })).toThrow()
  70. })
  71. test("ports HTML text and markdown conversions without active content", () => {
  72. const html = "<h1>Hello</h1><script>bad()</script><p>world <strong>wide</strong></p><style>.bad {}</style>"
  73. expect(WebFetchTool.extractTextFromHTML(html)).toBe("Helloworld wide")
  74. expect(WebFetchTool.convertHTMLToMarkdown(html)).toBe("# Hello\n\nworld **wide**")
  75. })
  76. })
  77. describe("WebFetchTool registration", () => {
  78. it.effect("registers and fetches an ordinary hostname HTTP URL without rewriting it", () =>
  79. Effect.gen(function* () {
  80. reset()
  81. const registry = yield* ToolRegistry.Service
  82. const url = "http://example.com/public"
  83. expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["webfetch"])
  84. expect(yield* settleTool(registry, call({ url, format: "text", timeout: 4 }))).toEqual({
  85. result: { type: "text", value: "hello" },
  86. output: {
  87. structured: { url, contentType: "text/plain", format: "text", output: "hello" },
  88. content: [{ type: "text", text: "hello" }],
  89. },
  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* ToolRegistry.Service
  101. const url = "http://localhost/private"
  102. expect(yield* executeTool(registry, call({ url, format: "text" }))).toEqual({
  103. type: "text",
  104. value: "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* ToolRegistry.Service
  127. const url = new URL("/redirect", server.url).toString()
  128. expect(yield* executeTool(registry, call({ url, format: "text" }))).toEqual({
  129. type: "text",
  130. value: "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* ToolRegistry.Service
  143. expect(yield* executeTool(registry, call({ url: "file:///etc/passwd", format: "text" }))).toEqual({
  144. type: "error",
  145. value: "Unable to fetch file:///etc/passwd",
  146. })
  147. expect(assertions).toEqual([])
  148. expect(requests).toEqual([])
  149. }),
  150. )
  151. it.effect("converts HTML to requested markdown and text", () =>
  152. Effect.gen(function* () {
  153. reset()
  154. respond = () =>
  155. Effect.succeed(
  156. new Response("<h1>Hello</h1><p>world</p><script>bad()</script>", {
  157. headers: { "content-type": "text/html; charset=utf-8" },
  158. }),
  159. )
  160. const registry = yield* ToolRegistry.Service
  161. expect(yield* executeTool(registry, call({ url: "https://1.1.1.1", format: "markdown" }))).toEqual({
  162. type: "text",
  163. value: "# Hello\n\nworld",
  164. })
  165. expect(yield* executeTool(registry, call({ url: "https://1.1.1.1", format: "text" }))).toEqual({
  166. type: "text",
  167. value: "Helloworld",
  168. })
  169. }),
  170. )
  171. it.effect("returns an error result when HTML-to-Markdown conversion throws", () =>
  172. Effect.gen(function* () {
  173. reset()
  174. respond = () =>
  175. Effect.succeed(
  176. new Response("<div>".repeat(10_000) + "content" + "</div>".repeat(10_000), {
  177. headers: { "content-type": "text/html" },
  178. }),
  179. )
  180. const registry = yield* ToolRegistry.Service
  181. const url = "https://1.1.1.1/deep-html"
  182. expect(yield* executeTool(registry, call({ url, format: "markdown" }))).toEqual({
  183. type: "error",
  184. value: `Unable to fetch ${url}`,
  185. })
  186. }),
  187. )
  188. it.effect("rejects declared and streamed oversized bodies", () =>
  189. Effect.gen(function* () {
  190. reset()
  191. const registry = yield* ToolRegistry.Service
  192. respond = () =>
  193. Effect.succeed(
  194. new Response("small", {
  195. headers: { "content-type": "text/plain", "content-length": String(WebFetchTool.MAX_RESPONSE_BYTES + 1) },
  196. }),
  197. )
  198. expect(yield* executeTool(registry, call({ url: "https://1.1.1.1/declared", format: "text" }))).toEqual({
  199. type: "error",
  200. value: "Unable to fetch https://1.1.1.1/declared",
  201. })
  202. respond = () =>
  203. Effect.succeed(
  204. new Response("x".repeat(WebFetchTool.MAX_RESPONSE_BYTES + 1), { headers: { "content-type": "text/plain" } }),
  205. )
  206. expect(yield* executeTool(registry, call({ url: "https://1.1.1.1/streamed", format: "text" }))).toEqual({
  207. type: "error",
  208. value: "Unable to fetch https://1.1.1.1/streamed",
  209. })
  210. }),
  211. )
  212. it.effect("keeps images and files unsupported until typed settlement can carry attachments", () =>
  213. Effect.gen(function* () {
  214. reset()
  215. const registry = yield* ToolRegistry.Service
  216. respond = () => Effect.succeed(new Response("png", { headers: { "content-type": "image/png" } }))
  217. expect(yield* executeTool(registry, call({ url: "https://1.1.1.1/image", format: "html" }))).toEqual({
  218. type: "error",
  219. value: "Unable to fetch https://1.1.1.1/image",
  220. })
  221. respond = () => Effect.succeed(new Response("pdf", { headers: { "content-type": "application/pdf" } }))
  222. expect(yield* executeTool(registry, call({ url: "https://1.1.1.1/file", format: "html" }))).toEqual({
  223. type: "error",
  224. value: "Unable to fetch https://1.1.1.1/file",
  225. })
  226. }),
  227. )
  228. it.effect("retries Cloudflare challenges with an honest user agent", () =>
  229. Effect.gen(function* () {
  230. reset()
  231. let count = 0
  232. respond = () =>
  233. Effect.succeed(
  234. ++count === 1
  235. ? new Response("challenge", { status: 403, headers: { "cf-mitigated": "challenge" } })
  236. : new Response("ok", { headers: { "content-type": "text/plain" } }),
  237. )
  238. const registry = yield* ToolRegistry.Service
  239. expect(yield* executeTool(registry, call({ url: "https://1.1.1.1", format: "text" }))).toEqual({
  240. type: "text",
  241. value: "ok",
  242. })
  243. expect(requests).toHaveLength(2)
  244. expect(requests[0]?.headers["user-agent"]).toContain("Mozilla/5.0")
  245. expect(requests[1]?.headers["user-agent"]).toBe("opencode")
  246. }),
  247. )
  248. it.effect("times out stalled requests", () =>
  249. Effect.gen(function* () {
  250. reset()
  251. respond = () => Effect.never
  252. const registry = yield* ToolRegistry.Service
  253. const fiber = yield* executeTool(
  254. registry,
  255. call({ url: "https://1.1.1.1/slow", format: "text", timeout: 1 }),
  256. ).pipe(Effect.forkChild)
  257. yield* TestClock.adjust(Duration.seconds(1))
  258. expect(yield* Fiber.join(fiber)).toEqual({ type: "error", value: "Unable to fetch https://1.1.1.1/slow" })
  259. }),
  260. )
  261. })