webfetch.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. export * as WebFetchTool from "./webfetch"
  2. import { ToolFailure } from "@opencode-ai/llm"
  3. import { Duration, Effect, Layer, Schema } from "effect"
  4. import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
  5. import { Parser } from "htmlparser2"
  6. import TurndownService from "turndown"
  7. import { makeLocationNode } from "../effect/app-node"
  8. import { LayerNodePlatform } from "../effect/app-node-platform"
  9. import { PermissionV2 } from "../permission"
  10. import { collectBoundedResponseBody } from "./http-body"
  11. import { ToolRegistry } from "./registry"
  12. import { Tool } from "./tool"
  13. import { Tools } from "./tools"
  14. export const name = "webfetch"
  15. export const MAX_RESPONSE_BYTES = 5 * 1024 * 1024
  16. export const DEFAULT_TIMEOUT_SECONDS = 30
  17. export const MAX_TIMEOUT_SECONDS = 120
  18. export const description = `Fetch content from an HTTP or HTTPS URL and return it as text, markdown, or HTML. Markdown is the default.
  19. Use a more targeted tool when one is available. This tool is read-only. Large text results may be replaced with a preview while the complete output is retained in managed storage.`
  20. const Timeout = Schema.Number.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(MAX_TIMEOUT_SECONDS))
  21. export const Input = Schema.Struct({
  22. url: Schema.String.annotate({ description: "The HTTP or HTTPS URL to fetch content from" }),
  23. format: Schema.Literals(["text", "markdown", "html"])
  24. .annotate({ description: "The format to return the content in. Defaults to markdown." })
  25. .pipe(Schema.withDecodingDefault(Effect.succeed("markdown" as const))),
  26. timeout: Timeout.pipe(Schema.optional).annotate({
  27. description: `Optional timeout in seconds (maximum: ${MAX_TIMEOUT_SECONDS})`,
  28. }),
  29. })
  30. const Output = Schema.Struct({
  31. url: Schema.String,
  32. contentType: Schema.String,
  33. format: Input.fields.format,
  34. output: Schema.String,
  35. })
  36. type Format = (typeof Input.Type)["format"]
  37. const acceptHeader = (format: Format) => {
  38. switch (format) {
  39. case "markdown":
  40. return "text/markdown;q=1.0, text/x-markdown;q=0.9, text/plain;q=0.8, text/html;q=0.7, */*;q=0.1"
  41. case "text":
  42. return "text/plain;q=1.0, text/markdown;q=0.9, text/html;q=0.8, */*;q=0.1"
  43. case "html":
  44. return "text/html;q=1.0, application/xhtml+xml;q=0.9, text/plain;q=0.8, text/markdown;q=0.7, */*;q=0.1"
  45. }
  46. return "*/*"
  47. }
  48. const headers = (format: Format, userAgent: string) => ({
  49. "User-Agent": userAgent,
  50. Accept: acceptHeader(format),
  51. "Accept-Language": "en-US,en;q=0.9",
  52. })
  53. const browserUserAgent =
  54. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36"
  55. const isCloudflareChallenge = (error: unknown) => {
  56. if (!error || typeof error !== "object" || !("reason" in error)) return false
  57. const reason = error.reason
  58. if (
  59. !reason ||
  60. typeof reason !== "object" ||
  61. !("_tag" in reason) ||
  62. reason._tag !== "StatusCodeError" ||
  63. !("response" in reason)
  64. )
  65. return false
  66. const response = reason.response as HttpClientResponse.HttpClientResponse
  67. return response.status === 403 && response.headers["cf-mitigated"] === "challenge"
  68. }
  69. const request = (url: string, format: Format, userAgent = browserUserAgent) =>
  70. HttpClientRequest.get(url).pipe(HttpClientRequest.setHeaders(headers(format, userAgent)))
  71. const assertHttpUrl = (url: URL) => {
  72. if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("URL must use http:// or https://")
  73. }
  74. const execute = (http: HttpClient.HttpClient, url: string, format: Format, userAgent = browserUserAgent) =>
  75. http.execute(request(url, format, userAgent)).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk))
  76. const collectBody = (response: HttpClientResponse.HttpClientResponse) =>
  77. collectBoundedResponseBody(
  78. response,
  79. MAX_RESPONSE_BYTES,
  80. () => new Error(`Response too large (exceeds ${MAX_RESPONSE_BYTES} byte limit)`),
  81. )
  82. const mimeFrom = (contentType: string) => contentType.split(";", 1)[0]?.trim().toLowerCase() ?? ""
  83. const isImageAttachment = (mime: string) =>
  84. mime.startsWith("image/") && mime !== "image/svg+xml" && mime !== "image/vnd.fastbidsheet"
  85. const isTextualMime = (mime: string) =>
  86. !mime ||
  87. mime.startsWith("text/") ||
  88. mime === "application/json" ||
  89. mime.endsWith("+json") ||
  90. mime === "application/xml" ||
  91. mime.endsWith("+xml") ||
  92. mime === "application/javascript" ||
  93. mime === "application/x-javascript"
  94. const convert = (content: string, contentType: string, format: Format) => {
  95. if (!contentType.includes("text/html")) return content
  96. if (format === "markdown") return convertHTMLToMarkdown(content)
  97. if (format === "text") return extractTextFromHTML(content)
  98. return content
  99. }
  100. const layer = Layer.effectDiscard(
  101. Effect.gen(function* () {
  102. const tools = yield* Tools.Service
  103. const http = yield* HttpClient.HttpClient
  104. const permission = yield* PermissionV2.Service
  105. yield* tools
  106. .register({
  107. [name]: Tool.make({
  108. description,
  109. input: Input,
  110. output: Output,
  111. toModelOutput: ({ output }) => [{ type: "text", text: output.output }],
  112. execute: (input, context) =>
  113. Effect.gen(function* () {
  114. yield* Effect.try({
  115. try: () => assertHttpUrl(new URL(input.url)),
  116. catch: (error) => error,
  117. })
  118. yield* permission.assert({
  119. action: name,
  120. resources: [input.url],
  121. save: ["*"],
  122. metadata: input,
  123. sessionID: context.sessionID,
  124. agent: context.agent,
  125. source: { type: "tool", messageID: context.assistantMessageID, callID: context.toolCallID },
  126. })
  127. const { body, contentType } = yield* Effect.gen(function* () {
  128. const response = yield* execute(http, input.url, input.format).pipe(
  129. Effect.catchIf(isCloudflareChallenge, () => execute(http, input.url, input.format, "opencode")),
  130. )
  131. const contentType = response.headers["content-type"] || ""
  132. const mime = mimeFrom(contentType)
  133. if (isImageAttachment(mime))
  134. return yield* Effect.fail(new Error(`Unsupported fetched image content type: ${mime}`))
  135. if (!isTextualMime(mime))
  136. return yield* Effect.fail(new Error(`Unsupported fetched file content type: ${mime}`))
  137. return { body: yield* collectBody(response), contentType }
  138. }).pipe(
  139. Effect.timeoutOrElse({
  140. duration: Duration.seconds(input.timeout ?? DEFAULT_TIMEOUT_SECONDS),
  141. orElse: () => Effect.fail(new Error("Request timed out")),
  142. }),
  143. )
  144. const content = new TextDecoder().decode(body)
  145. const output = yield* Effect.try({
  146. try: () => convert(content, contentType, input.format),
  147. catch: (error) => error,
  148. })
  149. return {
  150. url: input.url,
  151. contentType,
  152. format: input.format,
  153. output,
  154. }
  155. }).pipe(Effect.mapError(() => new ToolFailure({ message: `Unable to fetch ${input.url}` }))),
  156. }),
  157. })
  158. .pipe(Effect.orDie)
  159. }),
  160. )
  161. export const node = makeLocationNode({
  162. name: "tool/webfetch",
  163. layer,
  164. deps: [ToolRegistry.node, PermissionV2.node, LayerNodePlatform.httpClient],
  165. })
  166. export function extractTextFromHTML(html: string) {
  167. let text = ""
  168. let skipDepth = 0
  169. const parser = new Parser({
  170. onopentag(name) {
  171. if (skipDepth > 0 || ["script", "style", "noscript", "iframe", "object", "embed"].includes(name)) skipDepth++
  172. },
  173. ontext(input) {
  174. if (skipDepth === 0) text += input
  175. },
  176. onclosetag() {
  177. if (skipDepth > 0) skipDepth--
  178. },
  179. })
  180. parser.write(html)
  181. parser.end()
  182. return text.trim()
  183. }
  184. export function convertHTMLToMarkdown(html: string) {
  185. const turndown = new TurndownService({
  186. headingStyle: "atx",
  187. hr: "---",
  188. bulletListMarker: "-",
  189. codeBlockStyle: "fenced",
  190. emDelimiter: "*",
  191. })
  192. turndown.remove(["script", "style", "meta", "link"])
  193. return turndown.turndown(html)
  194. }