webfetch.ts 5.2 KB

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