webfetch.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. import z from "zod"
  2. import { Tool } from "./tool"
  3. import TurndownService from "turndown"
  4. import DESCRIPTION from "./webfetch.txt"
  5. import { abortAfterAny } from "../util/abort"
  6. const MAX_RESPONSE_SIZE = 5 * 1024 * 1024 // 5MB
  7. const DEFAULT_TIMEOUT = 30 * 1000 // 30 seconds
  8. const MAX_TIMEOUT = 120 * 1000 // 2 minutes
  9. export const WebFetchTool = Tool.define("webfetch", {
  10. description: DESCRIPTION,
  11. parameters: z.object({
  12. url: z.string().describe("The URL to fetch content from"),
  13. format: z
  14. .enum(["text", "markdown", "html"])
  15. .default("markdown")
  16. .describe("The format to return the content in (text, markdown, or html). Defaults to markdown."),
  17. timeout: z.number().describe("Optional timeout in seconds (max 120)").optional(),
  18. }),
  19. async execute(params, ctx) {
  20. // Validate URL
  21. if (!params.url.startsWith("http://") && !params.url.startsWith("https://")) {
  22. throw new Error("URL must start with http:// or https://")
  23. }
  24. await ctx.ask({
  25. permission: "webfetch",
  26. patterns: [params.url],
  27. always: ["*"],
  28. metadata: {
  29. url: params.url,
  30. format: params.format,
  31. timeout: params.timeout,
  32. },
  33. })
  34. const timeout = Math.min((params.timeout ?? DEFAULT_TIMEOUT / 1000) * 1000, MAX_TIMEOUT)
  35. const { signal, clearTimeout } = abortAfterAny(timeout, ctx.abort)
  36. // Build Accept header based on requested format with q parameters for fallbacks
  37. let acceptHeader = "*/*"
  38. switch (params.format) {
  39. case "markdown":
  40. acceptHeader = "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. break
  42. case "text":
  43. acceptHeader = "text/plain;q=1.0, text/markdown;q=0.9, text/html;q=0.8, */*;q=0.1"
  44. break
  45. case "html":
  46. acceptHeader = "text/html;q=1.0, application/xhtml+xml;q=0.9, text/plain;q=0.8, text/markdown;q=0.7, */*;q=0.1"
  47. break
  48. default:
  49. acceptHeader =
  50. "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8"
  51. }
  52. const headers = {
  53. "User-Agent":
  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. Accept: acceptHeader,
  56. "Accept-Language": "en-US,en;q=0.9",
  57. }
  58. const initial = await fetch(params.url, { signal, headers })
  59. // Retry with honest UA if blocked by Cloudflare bot detection (TLS fingerprint mismatch)
  60. const response =
  61. initial.status === 403 && initial.headers.get("cf-mitigated") === "challenge"
  62. ? await fetch(params.url, { signal, headers: { ...headers, "User-Agent": "opencode" } })
  63. : initial
  64. clearTimeout()
  65. if (!response.ok) {
  66. throw new Error(`Request failed with status code: ${response.status}`)
  67. }
  68. // Check content length
  69. const contentLength = response.headers.get("content-length")
  70. if (contentLength && parseInt(contentLength) > MAX_RESPONSE_SIZE) {
  71. throw new Error("Response too large (exceeds 5MB limit)")
  72. }
  73. const arrayBuffer = await response.arrayBuffer()
  74. if (arrayBuffer.byteLength > MAX_RESPONSE_SIZE) {
  75. throw new Error("Response too large (exceeds 5MB limit)")
  76. }
  77. const content = new TextDecoder().decode(arrayBuffer)
  78. const contentType = response.headers.get("content-type") || ""
  79. const title = `${params.url} (${contentType})`
  80. // Handle content based on requested format and actual content type
  81. switch (params.format) {
  82. case "markdown":
  83. if (contentType.includes("text/html")) {
  84. const markdown = convertHTMLToMarkdown(content)
  85. return {
  86. output: markdown,
  87. title,
  88. metadata: {},
  89. }
  90. }
  91. return {
  92. output: content,
  93. title,
  94. metadata: {},
  95. }
  96. case "text":
  97. if (contentType.includes("text/html")) {
  98. const text = await extractTextFromHTML(content)
  99. return {
  100. output: text,
  101. title,
  102. metadata: {},
  103. }
  104. }
  105. return {
  106. output: content,
  107. title,
  108. metadata: {},
  109. }
  110. case "html":
  111. return {
  112. output: content,
  113. title,
  114. metadata: {},
  115. }
  116. default:
  117. return {
  118. output: content,
  119. title,
  120. metadata: {},
  121. }
  122. }
  123. },
  124. })
  125. async function extractTextFromHTML(html: string) {
  126. let text = ""
  127. let skipContent = false
  128. const rewriter = new HTMLRewriter()
  129. .on("script, style, noscript, iframe, object, embed", {
  130. element() {
  131. skipContent = true
  132. },
  133. text() {
  134. // Skip text content inside these elements
  135. },
  136. })
  137. .on("*", {
  138. element(element) {
  139. // Reset skip flag when entering other elements
  140. if (!["script", "style", "noscript", "iframe", "object", "embed"].includes(element.tagName)) {
  141. skipContent = false
  142. }
  143. },
  144. text(input) {
  145. if (!skipContent) {
  146. text += input.text
  147. }
  148. },
  149. })
  150. .transform(new Response(html))
  151. await rewriter.text()
  152. return text.trim()
  153. }
  154. function convertHTMLToMarkdown(html: string): string {
  155. const turndownService = new TurndownService({
  156. headingStyle: "atx",
  157. hr: "---",
  158. bulletListMarker: "-",
  159. codeBlockStyle: "fenced",
  160. emDelimiter: "*",
  161. })
  162. turndownService.remove(["script", "style", "meta", "link"])
  163. return turndownService.turndown(html)
  164. }