webfetch.ts 4.7 KB

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