/** * ============================================================ * src/tools/webfetch.ts —— WebFetch 工具(获取 URL 内容) * ------------------------------------------------------------ * 获取 URL → HTML 转 Markdown * * 输入: * url 必填,要获取内容的 URL * snapshot_id / offset / max_chars / query 用于稳定续读与搜索 * prompt 可选,旧版兼容字段,运行时忽略 * * 输出: * 完整快照引用、字符范围、下一段游标与本次正文窗口 * * 流程: * 1. URL 验证(合法格式、2000字符以内、无凭据) * 2. fetch(保持 HTTP(S) 协议,超时 60s) * 3. 检测跨 host 重定向,返回提示而非自动跟随 * 4. HTML → Markdown(turndown);非 HTML 原样返回 * 5. 完整正文保存为本机会话快照,按字符游标读取或搜索 * ============================================================ */ import { z } from 'zod'; import type { Tool, ToolResult, ToolCallContext } from '../../types.js'; import { DEFAULT_MAX_RESULT_SIZE_CHARS } from '../types.js'; import { toToolParameters } from '../../utils/zodToJson.js'; import { isPreapprovedDomain } from './preapproved.js'; import { readHttpBody } from '../shared/httpBody.js'; import { loadPageSnapshot, savePageSnapshot, pageSnapshotPath, pageWindow, type PageSnapshot } from './pageSnapshot.js'; // ---------------- 1. 常量 ---------------- const MAX_URL_LENGTH = 2000; const FETCH_TIMEOUT_MS = 60_000; const MAX_HTTP_CONTENT_LENGTH = 10 * 1024 * 1024; const MAX_REDIRECTS = 10; // ---------------- 2. LRU 缓存 ---------------- type CacheEntry = { bytes: number; code: number; codeText: string; content: string; contentType: string; fetchedAt: number; }; const URL_CACHE = new Map(); const CACHE_TTL_MS = 15 * 60 * 1000; const MAX_CACHE_SIZE_BYTES = 50 * 1024 * 1024; function cleanCache(): void { const now = Date.now(); let totalSize = 0; const entries: Array<{ url: string; entry: CacheEntry; size: number }> = []; for (const [url, entry] of URL_CACHE) { if (now - entry.fetchedAt > CACHE_TTL_MS) { URL_CACHE.delete(url); continue; } const size = entry.bytes; totalSize += size; entries.push({ url, entry, size }); } if (totalSize > MAX_CACHE_SIZE_BYTES) { entries.sort((a, b) => a.entry.fetchedAt - b.entry.fetchedAt); for (const { url, size } of entries) { URL_CACHE.delete(url); totalSize -= size; if (totalSize <= MAX_CACHE_SIZE_BYTES * 0.8) break; } } } // ---------------- 3. Zod 输入 schema ---------------- const inputSchema = z.object({ url: z.string().url().max(MAX_URL_LENGTH).regex(/^https?:\/\//i).describe('要获取内容的 HTTP(S) URL,不包含用户名或密码。'), snapshot_id: z.string().regex(/^[a-f0-9]{64}$/).optional().describe('续读时使用上次返回的快照 ID,保证读取同一版本。'), offset: z.number().int().nonnegative().optional().describe('0-based UTF-16 字符位置;使用 next_offset 续读,不是行号。'), max_chars: z.number().int().min(1000).max(1_000_000).optional().describe('本次正文字符预算,Runtime 按剩余上下文收紧。'), query: z.string().min(1).max(500).optional().describe('在完整快照中从 offset 开始查找精确文本(区分大小写,非正则),返回命中处正文。'), /** @deprecated Accepted for callers compiled against the legacy contract. */ prompt: z.string().optional(), }); type WebFetchInput = z.infer; // Model-visible snapshot contract. WebFetch returns the page body and does not run a // hidden extraction model; the runtime schema still accepts legacy `prompt`. const parameters = toToolParameters(inputSchema.omit({ prompt: true })); // ---------------- 4. Description ---------------- const description = '读取已知 HTTP(S) URL 的静态文本并保存会话快照(拒绝 HTTP 206 部分响应),HTML 转 Markdown;结果仅为窗口,使用 snapshot_id + next_offset 续读,query 在全文中精确搜索,max_chars 可扩大读取预算。不要重复读取同一窗口或声称已读未展示部分。不执行 JavaScript、不继承登录态。PDF/图片用 Download 后 Read;动态页面用 WebBrowser。'; // ---------------- 5. 辅助函数 ---------------- // ---------------- 6. call() 实现 ---------------- /** 验证 URL */ function validateURL(url: string): { ok: true; parsed: URL } | { ok: false; error: string } { if (url.length > MAX_URL_LENGTH) { return { ok: false, error: `URL 太长(最大 ${MAX_URL_LENGTH} 字符)` }; } let parsed: URL; try { parsed = new URL(url); } catch { return { ok: false, error: `无效的 URL 格式` }; } if (parsed.username || parsed.password) { return { ok: false, error: `URL 不能包含用户名或密码` }; } if (!['http:', 'https:'].includes(parsed.protocol)) return { ok: false, error: '仅支持 HTTP(S) URL' }; return { ok: true, parsed }; } /** 获取 URL 内容(返回 HTML 字符串或重定向信息) */ async function fetchURL( url: string, signal: AbortSignal, depth = 0, ): Promise< | { type: 'success'; content: string; bytes: number; code: number; codeText: string; contentType: string } | { type: 'redirect'; originalUrl: string; redirectUrl: string; statusCode: number } | { type: 'error'; error: string } > { const validated = validateURL(url); if (!validated.ok) return { type: 'error', error: validated.error }; const targetUrl = url; const combinedSignal = AbortSignal.any([signal, AbortSignal.timeout(FETCH_TIMEOUT_MS)]); let response: Response; try { response = await fetch(targetUrl, { signal: combinedSignal, redirect: 'manual', headers: { Accept: 'text/markdown, text/html, */*', 'User-Agent': 'minimal-agent/1.0', }, }); } catch (e) { if (signal?.aborted) return { type: 'error', error: '请求被中断' }; return { type: 'error', error: `网络请求失败:${(e as Error).message}` }; } const code = response.status; const codeText = response.statusText; const contentType = (response.headers.get('content-type') ?? '').toLowerCase(); const location = response.headers.get('location'); if (location && [301, 302, 303, 307, 308].includes(code)) { void response.body?.cancel().catch(() => undefined); const redirectUrl = new URL(location, targetUrl).toString(); const originalHost = new URL(url).hostname; const redirectHost = new URL(redirectUrl).hostname; const stripWww = (h: string) => h.replace(/^www\./, ''); if (stripWww(originalHost) !== stripWww(redirectHost)) { return { type: 'redirect', originalUrl: url, redirectUrl, statusCode: code, }; } if (depth >= MAX_REDIRECTS) { return { type: 'error', error: `重定向循环超过限制(最多 ${MAX_REDIRECTS} 次)` }; } return fetchURL(redirectUrl, signal, depth + 1); } if (code === 206) { void response.body?.cancel().catch(() => undefined); return { type: 'error', error: 'HTTP 206:服务端只返回部分正文,无法建立完整网页快照。' }; } if (code < 200 || code >= 300) { void response.body?.cancel().catch(() => undefined); return { type: 'error', error: `HTTP ${code} ${codeText}:${targetUrl}` }; } if (/application\/pdf|^(?:image|audio|video)\/|application\/octet-stream/i.test(contentType)) { void response.body?.cancel().catch(() => undefined); return { type: 'error', error: `这是 ${contentType} 资源,请用 Download 保存后通过 Read 读取。` }; } // Enforce the existing byte budget during streaming, not after allocation. let rawBuffer: Buffer; try { rawBuffer = await readHttpBody(response, MAX_HTTP_CONTENT_LENGTH, combinedSignal); } catch (e) { return { type: 'error', error: `读取响应体失败:${(e as Error).message}` }; } if (rawBuffer.byteLength > MAX_HTTP_CONTENT_LENGTH) { return { type: 'error', error: `内容太大(${rawBuffer.byteLength} bytes,超过 ${MAX_HTTP_CONTENT_LENGTH})` }; } // 解码 let content: string; try { const decoder = new TextDecoder('utf-8', { fatal: false }); content = decoder.decode(rawBuffer); } catch (e) { return { type: 'error', error: `解码失败:${(e as Error).message}` }; } return { type: 'success', content, bytes: rawBuffer.byteLength, code, codeText, contentType }; } /** HTML 转 Markdown */ async function htmlToMarkdown(html: string): Promise { // 动态 import turndown(~1.4MB,按需加载) const TurndownService = (await import('turndown')).default; const td = new TurndownService(); return td.turndown(html); } // ---------------- 6. call() 实现 ---------------- async function call( input: WebFetchInput, signal?: AbortSignal, context: ToolCallContext = {}, ): Promise { if (signal?.aborted) return { ok: false, error: '请求被中断' }; const valid = validateURL(input.url); if (!valid.ok) return { ok: false, error: valid.error }; if ((input.offset ?? 0) > 0 && !input.snapshot_id) return { ok: false, error: '续读需要 snapshot_id;先读取 URL 获取稳定快照,避免拼接不同版本。' }; const budget = context.reserveReadChars?.(input.max_chars) ?? input.max_chars ?? DEFAULT_MAX_RESULT_SIZE_CHARS; if (budget < 1000) return { ok: false, error: '本批读取预算已用完,请处理已有结果或压缩上下文后续读。' }; try { let page: PageSnapshot; let status = ''; if (input.snapshot_id) { page = await loadPageSnapshot(input.snapshot_id, input.url, context); } else { const cached = URL_CACHE.get(input.url); const hit = cached && Date.now() - cached.fetchedAt <= CACHE_TTL_MS; const fetched = hit ? { type: 'success' as const, ...cached } : await fetchURL(input.url, signal ?? new AbortController().signal); if (fetched.type === 'error') return { ok: false, error: fetched.error }; if (fetched.type === 'redirect') return { ok: true, content: `【重定向检测】\n原始 URL: ${fetched.originalUrl}\n重定向到: ${fetched.redirectUrl}\n状态: ${fetched.statusCode}\n请使用重定向后的 URL 再次调用 WebFetch 工具。` }; const fetchedAt = hit ? cached.fetchedAt : Date.now(); if (!hit) { URL_CACHE.set(input.url, { ...fetched, fetchedAt }); cleanCache(); } let text = fetched.content; let format = 'text'; if (fetched.contentType.includes('text/html')) { try { text = await htmlToMarkdown(text); format = 'markdown'; } catch { format = 'raw-html (正文转换失败,保留原始 HTML)'; } } page = { url: input.url, text, format, fetchedAt }; status = `状态: ${fetched.code} ${fetched.codeText}${hit ? ' (缓存命中)' : ''}\n`; } signal?.throwIfAborted(); const snapshot = input.snapshot_id ? { id: input.snapshot_id, path: pageSnapshotPath(input.snapshot_id, context) } : await savePageSnapshot(page, context); signal?.throwIfAborted(); const window = pageWindow(page.text, input.offset ?? 0, budget, input.query); const domain = isPreapprovedDomain(valid.parsed.hostname) ? '[网络访问:预批准域名]' : '[网络访问:普通域名;请按来源本身评估证据质量]'; return { ok: true, policy: { highValue: true, reclaimable: false, boundedWindow: true, archiveRef: snapshot.path, originalChars: page.text.length }, content: `【WebFetch 结果】 URL: ${page.url} ${status}${domain} snapshot_id: ${snapshot.id} snapshot_complete: true (完整抓取正文,不代表动态页面内容完整) format: ${page.format} total_chars: ${page.text.length} range: [${window.start}, ${window.end}) next_offset: ${window.next ?? 'null'} 完整正文文件: ${snapshot.path} ${window.found ? '' : '未找到指定文本(精确匹配,区分大小写)。\n'}--- 内容 --- ${window.text}` }; } catch (error) { return { ok: false, error: `网页快照读取失败:${(error as Error).message}。未返回不完整正文;请重试原 URL 或检查本地存储。` }; } } // ---------------- 7. 导出 ---------------- export const webfetchTool: Tool = { name: 'WebFetch', description, inputSchema, parameters, isReadOnly: true, isConcurrencySafe: true, maxResultSizeChars: 1_010_000, interruptBehavior: () => 'cancel', call, callWithContext: (input, signal, context) => call(input, signal, context), };