P1 修复面收口: v0.6.3 截断自愈推全量(Anthropic/Ollama/非流式/引擎兜底); SSE 上游错误帧检测进重试通道; clearMessages 摘要游标根治; truncateResult 内联图片白名单统一; 前端四 bug(确认弹窗锁死/MemoryViewer/ Virtuoso Footer/abort 尾部过滤) + reasoning 缓冲跨迭代污染; 托盘通知过滤与新建会话死链接线 P2 安全纵深: MCP 审批闭环(ConfirmationHook×PolicyEngine 联动+重名拒注册); SSRF 收敛 ssrf-guard 共享模块 (web_fetch 双通道校验+重定向终态复检); Electron 加固(preload CJS 化→sandbox:true/CSP/权限白名单/will-navigate); run_command cmd.exe 白名单通道元字符守门; diff_viewer 10MB 预检; Anthropic thinking 预算下限; Agnes 思考显式关闭 P3 架构还债: OpenAICompatibleAdapter 中间基类收敛四家样板; 错误分类单轨化(删 mapError/getFetchSignal, 超时显式 ETIMEDOUT); PRAGMA user_version 迁移版本化; 死代码清理专项(cn.ts/SHORTCUTS/ContextMenu 分支/ getWindowState/modifiedArgs/sandbox 空壳); i18next 引入; a11y 第一轮; SearXNG 页批量草稿模型统一 P4 能力演进: Ollama pull 可取消/capabilities 探测/num_ctx 实测缓存; UpdateService feed 比对式自动更新 (app:updateCheck IPC + StatusBar 入口); MiMo providerOptions(web_search 服务端工具/strict JSON); web_fetch extract_mode=markdown(turndown); network.proxyUrl 全局代理(Chromium sessions+undici dispatcher) 测试: 264 → 507 用例(Electron ABI 全绿零跳过), 覆盖引擎压缩管线/重试竞速/MEMORY.md 闸门/file_editor 五操作/ filesystem 七工具实体夹具/git 真实仓库/SSE 错误帧/全线截断自愈/Provider 请求形态矩阵/SSRF 表测/钩子分级矩阵/ OutputValidator 全量/SLO 指标/MCP 安全纯函数/task_manager 链路/渲染层纯域/i18n 桥契约
354 lines
13 KiB
TypeScript
354 lines
13 KiB
TypeScript
/**
|
||
* web_fetch — 网页抓取工具
|
||
*
|
||
* 三阶段回退策略:
|
||
* Phase 1: HTTP 抓取(UA 轮换 + 反爬请求头 + 指数退避重试 + 拦截检测)
|
||
* Phase 2: 内容过短自动升级(< 200 字符 → 浏览器渲染)
|
||
* Phase 3: 浏览器回退(共享 BrowserWindowManager + JS 渲染 + 内容提取)
|
||
*
|
||
* 浏览器回退使用与 web_browser 相同的 BrowserWindowManager 单例,
|
||
* 避免创建多个独立浏览器窗口,支持窗口复用。
|
||
*
|
||
* @see docs/Agent网络工具通用设计-v2.md — 第 3 章 web_fetch 抓取设计
|
||
*/
|
||
|
||
import type { IMetonaTool, ToolExecutionContext } from '../../types/metona-tool';
|
||
import type { MetonaToolDef } from '../../../harness/types';
|
||
import { MetonaToolCategory, MetonaRiskLevel } from '../../../harness/types';
|
||
import {
|
||
fetchCache,
|
||
buildAntiCrawlHeaders,
|
||
fetchWithTimeout,
|
||
htmlToText,
|
||
isInterceptedPage,
|
||
readBodyWithLimit,
|
||
logTool,
|
||
// v0.6.4 P4-4: 内置 HTML→Markdown 转换(extract_mode='markdown')
|
||
htmlToMarkdown,
|
||
} from './network-utils';
|
||
import { getBrowserManager } from './browser';
|
||
// v0.6.4 P2-2 根治安全不对称:web_fetch 此前完全没有 SSRF 校验(仅协议检查)且
|
||
// requiresPermission:false —— LLM 可直接抓取 http://127.0.0.1:<port>、
|
||
// http://169.254.169.254/latest/meta-data 等内网/云元数据地址,浏览器回退通道
|
||
// 同样可达内网。现复用共享 ssrf-guard 模块(与 http_request 同源同行为):
|
||
// 入口校验 + HTTP 重定向终态 URL 复检(堵 redirect:'follow' 绕道内网的口子)。
|
||
import { validateSSRF } from './ssrf-guard';
|
||
|
||
// ===== 跳过重试的状态码 =====
|
||
|
||
const SKIP_RETRY_STATUS = new Set([403, 429, 502, 503]);
|
||
|
||
// ===== WebFetchTool =====
|
||
|
||
export class WebFetchTool implements IMetonaTool {
|
||
readonly definition: MetonaToolDef = {
|
||
name: 'web_fetch',
|
||
description:
|
||
'Fetch a web page and convert to plain text. Uses a three-phase fallback strategy: HTTP fetch with anti-crawl headers → SPA auto-upgrade → browser rendering. Handles Cloudflare interception, JavaScript-rendered pages, and large files (10MB limit).',
|
||
parameters: {
|
||
type: 'object',
|
||
properties: {
|
||
url: { type: 'string', description: 'Target URL (http/https only)' },
|
||
// H-3/H-4 修复: 补齐规范要求的 max_chars 和 extract_mode 参数
|
||
// @see docs/Agent网络工具通用设计-v2.md — 第 3 章 web_fetch 抓取设计
|
||
max_chars: {
|
||
type: 'number',
|
||
description: 'Maximum characters to return (default 50000, truncated with notice)',
|
||
},
|
||
extract_mode: {
|
||
type: 'string',
|
||
enum: ['text', 'html', 'markdown'],
|
||
description:
|
||
'Content extraction mode: "text"=plain text (default), "html"=cleaned HTML with scripts/styles removed, "markdown"=structured Markdown (headings/links/code/lists)',
|
||
},
|
||
mobile_ua: { type: 'boolean', description: 'Use mobile User-Agent (default false)' },
|
||
retry: {
|
||
type: 'boolean',
|
||
description: 'Enable retry with exponential backoff (default true)',
|
||
},
|
||
},
|
||
required: ['url'],
|
||
},
|
||
category: MetonaToolCategory.NETWORK,
|
||
riskLevel: MetonaRiskLevel.LOW,
|
||
requiresPermission: false,
|
||
// v0.6.2: 120s → 240s — v0.6.1 浏览器回退串行化后,web_search 并发 3 个回退
|
||
// 排队最坏 ~127.5s(每个 30s load + 2.5s 渲染 + 10s eval),旧值 120s 会让
|
||
// 排队末位的抓取在队列等待中被工具超时杀掉(表现为抓取不稳定)。
|
||
timeoutMs: 240_000,
|
||
};
|
||
|
||
async execute(args: Record<string, unknown>, _context: ToolExecutionContext): Promise<unknown> {
|
||
const url = args.url as string;
|
||
const mobileUA = (args.mobile_ua as boolean) ?? false;
|
||
const enableRetry = (args.retry as boolean) ?? true;
|
||
// H-3/H-4 修复: 读取 max_chars 和 extract_mode 参数
|
||
const maxChars = (args.max_chars as number) ?? 50_000;
|
||
const extractMode = ((args.extract_mode as string) ?? 'text') as 'text' | 'html' | 'markdown';
|
||
|
||
if (!url || !/^https?:\/\//i.test(url)) {
|
||
return { url, content: '', success: false, error: 'URL must start with http:// or https://' };
|
||
}
|
||
|
||
// v0.6.4 P2-2: SSRF 校验 —— 覆盖 Phase1 HTTP 与 Phase3 浏览器两条通道的入口。
|
||
// 协议白名单 / 私有段 IP / 云元数据地址一律拒绝。
|
||
try {
|
||
await validateSSRF(url);
|
||
} catch (ssrfErr) {
|
||
logTool('web_fetch', `SSRF blocked: ${(ssrfErr as Error).message}`);
|
||
return { url, content: '', success: false, error: (ssrfErr as Error).message };
|
||
}
|
||
|
||
// v0.6.4 P2-2: 缓存键携带 extract_mode —— 原实现 html/text 共用同一 URL 键,
|
||
// 先请求 text 再请求 html 会命中 text 缓存,把纯文本冒充"清理后的 HTML"返回
|
||
const cacheKey = `${extractMode}:${url}`;
|
||
const cached = fetchCache.get(cacheKey);
|
||
if (cached) {
|
||
logTool('web_fetch', `Cache hit: ${url} [${extractMode}]`);
|
||
return this.buildSuccess(url, cached, 'cache', maxChars);
|
||
}
|
||
|
||
logTool('web_fetch', `Fetching: ${url}`);
|
||
|
||
// ===== Phase 1: HTTP 抓取 =====
|
||
const phase1Result = await this.httpFetch(url, mobileUA, enableRetry);
|
||
|
||
if (phase1Result.success && !phase1Result.intercepted) {
|
||
// 根据 extract_mode 选择返回内容:'html' 模式返回清理后的 HTML,'text' 模式返回纯文本
|
||
// v0.6.4 P4-4: markdown 模式在 Phase1 的清理后 HTML 上做结构化转换;
|
||
// 浏览器回退通道产出纯文本,降级为 text 语义(回退产物不做二次包装)。
|
||
const phase1Content =
|
||
extractMode === 'html'
|
||
? phase1Result.html
|
||
: extractMode === 'markdown'
|
||
? htmlToMarkdown(phase1Result.html)
|
||
: phase1Result.text;
|
||
|
||
// 内容过短检测 → Phase 2 升级(仅对 text 模式生效,html 模式不升级)
|
||
if (extractMode === 'text' && phase1Content.length < 200) {
|
||
logTool(
|
||
'web_fetch',
|
||
`Phase 2: Content too short (${phase1Content.length} chars), upgrading to browser`,
|
||
);
|
||
const browserResult = await this.browserFetch(url);
|
||
if (browserResult) {
|
||
return this.buildSuccess(url, browserResult, 'browser', maxChars);
|
||
}
|
||
}
|
||
// 写入缓存(缓存键已含模式:text/markdown 可缓存,html 不缓存以避免模式混淆)
|
||
if (extractMode !== 'html') {
|
||
fetchCache.set(cacheKey, phase1Content);
|
||
}
|
||
return this.buildSuccess(url, phase1Content, 'http', maxChars, extractMode);
|
||
}
|
||
|
||
// ===== Phase 3: 浏览器回退 =====
|
||
// v0.6.4 P2-2: SSRF 阻断的请求禁止进入浏览器回退(否则等于借 Chromium 绕过校验)
|
||
if (phase1Result.blocked) {
|
||
return {
|
||
url,
|
||
content: '',
|
||
success: false,
|
||
error: phase1Result.reason,
|
||
};
|
||
}
|
||
logTool('web_fetch', `Phase 3: Falling back to browser (${phase1Result.reason})`);
|
||
const browserResult = await this.browserFetch(url);
|
||
if (browserResult) {
|
||
return this.buildSuccess(url, browserResult, 'browser', maxChars);
|
||
}
|
||
|
||
// 全部失败
|
||
return {
|
||
url,
|
||
content: '',
|
||
success: false,
|
||
error: `All phases failed. HTTP: ${phase1Result.reason}. Browser fallback also failed.`,
|
||
};
|
||
}
|
||
|
||
// ===== Phase 1: HTTP 抓取 =====
|
||
|
||
private async httpFetch(
|
||
url: string,
|
||
mobileUA: boolean,
|
||
enableRetry: boolean,
|
||
): Promise<{
|
||
success: boolean;
|
||
html: string;
|
||
text: string;
|
||
intercepted: boolean;
|
||
reason: string;
|
||
/** v0.6.4 P2-2: true=被 SSRF 防护阻断 —— execute() 必须立即失败返回,禁止进入浏览器回退 */
|
||
blocked?: boolean;
|
||
}> {
|
||
const maxRetries = enableRetry ? 3 : 1;
|
||
const backoffBase = 2_000;
|
||
|
||
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
||
try {
|
||
const headers = buildAntiCrawlHeaders(url, attempt, mobileUA);
|
||
const response = await fetchWithTimeout(url, { headers, redirect: 'follow' }, 20_000);
|
||
|
||
// v0.6.4 P2-2: 重定向终态复检 —— redirect:'follow' 下 fetch 可能跟随跳转
|
||
// 到与入口校验不同的目标;SSRF 校验 initial URL 后再对 response.url(终态)
|
||
// 复检,堵住"外网跳内网"绕道。终态指向私有地址时按拦截处理转入浏览器通道
|
||
// 也会被浏览器侧域名校验拒绝。
|
||
if (response.url && response.url !== url) {
|
||
try {
|
||
await validateSSRF(response.url);
|
||
} catch (ssrfErr) {
|
||
return {
|
||
success: false,
|
||
html: '',
|
||
text: '',
|
||
intercepted: false,
|
||
blocked: true,
|
||
reason: `Redirect target blocked by SSRF guard: ${(ssrfErr as Error).message}`,
|
||
};
|
||
}
|
||
}
|
||
|
||
// 跳过重试的状态码 → 直接进入浏览器回退
|
||
if (SKIP_RETRY_STATUS.has(response.status)) {
|
||
return {
|
||
success: false,
|
||
html: '',
|
||
text: '',
|
||
intercepted: true,
|
||
reason: `HTTP ${response.status}`,
|
||
};
|
||
}
|
||
|
||
if (!response.ok) {
|
||
// 5xx 可重试
|
||
if (response.status >= 500 && attempt < maxRetries - 1) {
|
||
await this.sleep(
|
||
backoffBase * Math.pow(2, attempt) + Math.random() * backoffBase * 0.6,
|
||
);
|
||
continue;
|
||
}
|
||
return {
|
||
success: false,
|
||
html: '',
|
||
text: '',
|
||
intercepted: false,
|
||
reason: `HTTP ${response.status} ${response.statusText}`,
|
||
};
|
||
}
|
||
|
||
// 读取正文(10MB 限制)
|
||
const html = await readBodyWithLimit(response, 10 * 1024 * 1024);
|
||
|
||
// 拦截检测
|
||
if (isInterceptedPage(html)) {
|
||
return {
|
||
success: false,
|
||
html: '',
|
||
text: '',
|
||
intercepted: true,
|
||
reason: 'Intercepted page detected',
|
||
};
|
||
}
|
||
|
||
// HTML → 纯文本
|
||
const text = htmlToText(html);
|
||
// H-3/H-4 修复: 同时保留原始 HTML,供 extract_mode='html' 使用
|
||
return { success: true, html, text, intercepted: false, reason: '' };
|
||
} catch (err) {
|
||
const errorMsg = (err as Error).message;
|
||
if (attempt < maxRetries - 1) {
|
||
logTool('web_fetch', `Attempt ${attempt + 1} failed: ${errorMsg}, retrying...`);
|
||
await this.sleep(backoffBase * Math.pow(2, attempt) + Math.random() * backoffBase * 0.6);
|
||
continue;
|
||
}
|
||
return { success: false, html: '', text: '', intercepted: false, reason: errorMsg };
|
||
}
|
||
}
|
||
|
||
return {
|
||
success: false,
|
||
html: '',
|
||
text: '',
|
||
intercepted: false,
|
||
reason: 'All retries exhausted',
|
||
};
|
||
}
|
||
|
||
// ===== Phase 2/3: 浏览器回退(使用共享 BrowserWindowManager 单例) =====
|
||
|
||
private async browserFetch(url: string): Promise<string | null> {
|
||
// 查缓存(浏览器阶段产出的是纯文本,与 text 模式同键)
|
||
const cached = fetchCache.get(`text:${url}`);
|
||
if (cached) {
|
||
logTool('web_fetch', 'Browser cache hit');
|
||
return cached;
|
||
}
|
||
|
||
try {
|
||
// 崩溃修复: 走 manager.fetchPageText(内部串行化完整的 open→等待→evaluate 序列)。
|
||
// 原实现直接 open/evaluate 共享单例 —— web_search 并行抓取触发多个回退同时进入时,
|
||
// 后到者销毁前者的窗口(ERR_ABORTED ×3 = 应用崩溃 ×3,见 manager 注释)。
|
||
const text = await getBrowserManager().fetchPageText(url);
|
||
|
||
if (text && text.trim().length >= 80) {
|
||
// 拦截检测(浏览器渲染后仍可能是验证码挑战页)
|
||
if (isInterceptedPage(text)) {
|
||
logTool('web_fetch', `Browser fetch detected intercepted page: ${url}`);
|
||
return null;
|
||
}
|
||
|
||
// 内容大小限制(与 HTTP 阶段一致,防止超大页面耗尽上下文)
|
||
const MAX_BROWSER_TEXT = 500_000; // 500K chars
|
||
const safeText =
|
||
text.length > MAX_BROWSER_TEXT
|
||
? text.slice(0, MAX_BROWSER_TEXT) + '\n\n[... content truncated ...]'
|
||
: text;
|
||
|
||
// 写缓存
|
||
fetchCache.set(`text:${url}`, safeText);
|
||
logTool('web_fetch', `Browser fetch success: ${safeText.length} chars`);
|
||
return safeText;
|
||
}
|
||
|
||
return null;
|
||
} catch (err) {
|
||
logTool('web_fetch', `Browser fetch failed: ${(err as Error).message}`);
|
||
return null;
|
||
}
|
||
// 注意:不关闭窗口 — manager 是单例,窗口由 web_browser 或 cleanupBrowser 管理
|
||
}
|
||
|
||
// ===== 辅助方法 =====
|
||
|
||
private buildSuccess(
|
||
url: string,
|
||
text: string,
|
||
method: string,
|
||
maxChars?: number,
|
||
extractMode?: 'text' | 'html' | 'markdown',
|
||
): unknown {
|
||
// H-3/H-4 修复: 应用 max_chars 截断,防止过长内容消耗过多 token
|
||
let content = text;
|
||
let truncated = false;
|
||
if (maxChars !== undefined && maxChars > 0 && text.length > maxChars) {
|
||
content = text.slice(0, maxChars) + `\n\n[... content truncated at ${maxChars} chars ...]`;
|
||
truncated = true;
|
||
}
|
||
return {
|
||
url,
|
||
content,
|
||
success: true,
|
||
method,
|
||
length: content.length,
|
||
original_length: text.length,
|
||
truncated,
|
||
extract_mode: extractMode ?? 'text',
|
||
};
|
||
}
|
||
|
||
private sleep(ms: number): Promise<void> {
|
||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||
}
|
||
}
|