|
| 1 | +/** |
| 2 | + * web-fetch.ts — Fetch URL content and extract readable text. |
| 3 | + * |
| 4 | + * Fetches a URL and extracts its readable text content. |
| 5 | + * Handles HTML (strips tags), plain text, JSON, and binary content types. |
| 6 | + */ |
| 7 | + |
| 8 | +import type { ToolDefinition, ToolContext } from "../agent.js"; |
| 9 | +import type { Environment } from "../env/environment.js"; |
| 10 | + |
| 11 | +interface WebFetchParams { |
| 12 | + /** URL to fetch. */ |
| 13 | + url: string; |
| 14 | + /** Maximum content length to return in characters (default: 50000). */ |
| 15 | + max_length?: number; |
| 16 | +} |
| 17 | + |
| 18 | +/** |
| 19 | + * Strip HTML tags and extract readable text. |
| 20 | + * |
| 21 | + * Uses regex-based approach (no external dependencies): |
| 22 | + * - Removes script and style blocks |
| 23 | + * - Converts block elements to newlines |
| 24 | + * - Strips all HTML tags |
| 25 | + * - Decodes basic HTML entities |
| 26 | + * - Collapses multiple blank lines |
| 27 | + */ |
| 28 | +function stripHtml(html: string): string { |
| 29 | + return html |
| 30 | + .replace(/<script[\s\S]*?<\/script>/gi, "") |
| 31 | + .replace(/<style[\s\S]*?<\/style>/gi, "") |
| 32 | + .replace(/<br\s*\/?>/gi, "\n") |
| 33 | + .replace(/<\/(p|div|li|h[1-6]|tr|blockquote)>/gi, "\n") |
| 34 | + .replace(/<[^>]+>/g, "") |
| 35 | + .replace(/&/g, "&") |
| 36 | + .replace(/</g, "<") |
| 37 | + .replace(/>/g, ">") |
| 38 | + .replace(/"/g, '"') |
| 39 | + .replace(/'/g, "'") |
| 40 | + .replace(/ /g, " ") |
| 41 | + .replace(/\n{3,}/g, "\n\n") |
| 42 | + .trim(); |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | + * Web fetch tool — fetches URL and extracts readable text. |
| 47 | + * |
| 48 | + * Validates URL format, fetches with 30s timeout, extracts text based on content-type. |
| 49 | + */ |
| 50 | +export const webFetch: ToolDefinition<WebFetchParams> = { |
| 51 | + description: "Fetch a URL and extract its readable text content.", |
| 52 | + |
| 53 | + parameters: { |
| 54 | + type: "object", |
| 55 | + properties: { |
| 56 | + url: { |
| 57 | + type: "string", |
| 58 | + description: "The URL to fetch content from.", |
| 59 | + }, |
| 60 | + max_length: { |
| 61 | + type: "number", |
| 62 | + description: "Maximum content length in characters (default: 50000).", |
| 63 | + }, |
| 64 | + }, |
| 65 | + required: ["url"], |
| 66 | + }, |
| 67 | + |
| 68 | + async execute(params: WebFetchParams, context: ToolContext): Promise<string> { |
| 69 | + return await webFetchWithEnv(params, context.env); |
| 70 | + }, |
| 71 | +}; |
| 72 | + |
| 73 | +export async function webFetchWithEnv( |
| 74 | + params: WebFetchParams, |
| 75 | + env: Environment |
| 76 | +): Promise<string> { |
| 77 | + const { url, max_length = 50000 } = params; |
| 78 | + |
| 79 | + // Validate URL format |
| 80 | + if (!url.startsWith("http://") && !url.startsWith("https://")) { |
| 81 | + throw new Error("Invalid URL: must start with http:// or https://"); |
| 82 | + } |
| 83 | + |
| 84 | + // Set up timeout with AbortController |
| 85 | + const controller = new AbortController(); |
| 86 | + const timeoutId = env.process.setTimeout(() => controller.abort(), 30000); |
| 87 | + |
| 88 | + try { |
| 89 | + // Fetch the URL |
| 90 | + const response = await env.http.fetch(url, { signal: controller.signal }); |
| 91 | + |
| 92 | + // Check for non-2xx status |
| 93 | + if (!response.ok) { |
| 94 | + throw new Error(`HTTP ${response.status} fetching ${url}`); |
| 95 | + } |
| 96 | + |
| 97 | + // Get content-type header |
| 98 | + const contentType = response.headers.get("content-type") || ""; |
| 99 | + |
| 100 | + // Read response body as text |
| 101 | + const text = await response.text(); |
| 102 | + |
| 103 | + let extractedText: string; |
| 104 | + |
| 105 | + // Handle different content types |
| 106 | + if (contentType.includes("text/html")) { |
| 107 | + // Strip HTML tags |
| 108 | + extractedText = stripHtml(text); |
| 109 | + } else if ( |
| 110 | + contentType.includes("text/plain") || |
| 111 | + contentType.includes("text/markdown") || |
| 112 | + contentType.includes("application/json") |
| 113 | + ) { |
| 114 | + // Return raw text |
| 115 | + extractedText = text; |
| 116 | + } else if (contentType.startsWith("text/")) { |
| 117 | + // Other text types - return raw |
| 118 | + extractedText = text; |
| 119 | + } else { |
| 120 | + // Binary content |
| 121 | + return `Binary content (${contentType}), cannot extract text`; |
| 122 | + } |
| 123 | + |
| 124 | + // Truncate if necessary |
| 125 | + if (extractedText.length > max_length) { |
| 126 | + return extractedText.slice(0, max_length) + `\n\n[Truncated at ${max_length} characters]`; |
| 127 | + } |
| 128 | + |
| 129 | + return extractedText; |
| 130 | + } catch (error) { |
| 131 | + // Handle AbortError (timeout) |
| 132 | + if ((error as Error).name === "AbortError") { |
| 133 | + throw new Error(`Timeout fetching ${url} after 30s`); |
| 134 | + } |
| 135 | + |
| 136 | + // Handle other network errors |
| 137 | + if (error instanceof Error) { |
| 138 | + // Re-throw if it's already one of our formatted errors |
| 139 | + if (error.message.startsWith("HTTP ") || error.message.startsWith("Invalid URL")) { |
| 140 | + throw error; |
| 141 | + } |
| 142 | + throw new Error(`Failed to fetch ${url}: ${error.message}`); |
| 143 | + } |
| 144 | + |
| 145 | + throw error; |
| 146 | + } finally { |
| 147 | + env.process.clearTimeout(timeoutId); |
| 148 | + } |
| 149 | +} |
0 commit comments