P0 会话可靠性收口(根治"模型思考着会话就停止"): - P0-1 finish_reason 全链路贯通:DONE 事件与 IterationStep 新增 finishReason,OpenAI 共享 SSE / Anthropic message_delta.stop_reason / Ollama done_reason 三路采集,TRACE 层弃用硬编码 'stop' 记录真值 - P0-2 空响应守卫 + 降级重试:零产出流→可重试错误走退避;思考耗尽输出预算(reasoning-only + length)→自动关闭思考降级重试一次;仍失败→OUTPUT_LENGTH_EXCEEDED 结构化错误 + 故障转移;附带根治 abort 恰逢零工具调用轮被 COMPLETED 抢占的真实缺陷 - P0-3 思考×能力×预算三对齐:DeepSeek/MiMo/Agnes/Ollama 四家 supportsThinking=false 强制不发思考参数;小输出预算告警;设置页联动提示 - P0-4 渲染层可见性:截断/空完成/友好错误三类提示,i18n 全部出层 - P0-5 回归四件套:reasoning-only 终止判定、集成级空闲超时、504 引擎重试归类、思考中 abort→USER_INTERRUPT、P4-2 强制收尾路径 FEAT-1:LLM 设置新增「最大输出上限」——Provider 支持矩阵显隐 + 模型上限钳制提示 + 超限保存警告 + llm.maxTokens 热生效 P1 修复面收口: - 渲染层三缺陷根治:后台会话回放缓冲(2000 条/4MB 有界 + agent:getReplayState + 事件总线)+ abort 双层自愈 + sendMessage 收尾兜底 + 中断卡片清扫 - 工具 abort 信号全覆盖:web_search/web_fetch/http_request/code_search/git 系列/delegate_task 全部接入引擎中断;web_search 时间预算收敛(720s→≤240s);移除伪造 ToolExecutionContext 与死代码 - 安全:本地 Pinned CONNECT 代理根治浏览器通道 DNS rebinding(校验期 IP pinning,可注入 resolver 表测);配置 URL 域名解析深校验(DeepCheckSoftFailure 软失败);SSE 空 error 帧防御修复;Ollama generate/embed AbortSignal.any 合并 - 缺陷清单:UTF-16 BOM 读取、tmp 同毫秒碰撞(nanoid 后缀)、code_search JS 回退参数对称(case_sensitive/前后文独立)、list_directory include_node_modules、崩溃自愈退避(60s 窗 ≥3 次停 reload)、MemoryViewer/Sidebar i18n 收口 P2 能力演进: - 会话回收站:SCHEMA_VERSION 3 + 迁移 10(deleted_at,存在性守卫),软删除/恢复/彻底删除/30 天自动清理(启动+24h),searchMessages 聚合剔除,Sidebar 回收站面板 - 会话回放播放器:sessions:listRecordings/readRecording(白名单+目录边界+20MB 上限),SessionReplayPlayer 时间轴/步进/变速,Trace 面板入口 - electron-updater 自动更新:双轨(手动 feed 比对保留),生产环境启动静默检查 + update:status 广播 + app:updateInstall + LogsSettings UpdatePanel + builder publish 配置 - @ 文件提及:workspace.listFiles/readFileClip(边界/512KB/NUL 拒绝/MEMORY.md 保护),ChatInput Fuse 联想+键盘导航+附件管线注入 - MCP Resources/Prompts 发现:可选能力 try/catch 降级,mcp:listServerContents,MCPSettings 展开视图 - 文档对齐:内部 API 标准 HTML(Adapter 清单补 MiMo/已实现注记/STREAM_RESET/DONE.finishReason/ repetition_truncation 映射);README v0.8.0 亮点表 P3 测试基建: - 新增 4 个测试文件:engine-stream-contract(6)、engine-stream-reliability(4:集成空闲超时/504 重试/思考中 abort/P4-2 强制收尾)、thinking-capability-gate(7)、pinned-proxy(9,含深校验 5)、session-trash(5,DB 域)、use-agent-stream hook 级(5)、agent.test 回放缓冲(2) - 契约更新:orchestrator 被中断 SubAgent success=false(abort 优先级修复语义)、SSE 空 error 帧、UTF-16 正常读取、DeepSeek 未配置思考显式 disabled、迁移矩阵 v2→3 - 弱断言根治:registry WEBP 单向断言、hooks-contracts 自比恒真、memory 空 token 补强 全量验证:typecheck 0 错误 / lint 0 问题 / 系统 Node 2144 通过(301 DB 用例按 ABI 跳过)/ Electron ABI 2445/2445 全量通过 0 跳过
417 lines
14 KiB
TypeScript
417 lines
14 KiB
TypeScript
/**
|
||
* 网络工具共享模块
|
||
*
|
||
* 提供 UA 轮换池、反爬请求头、HTML 转文本、拦截检测、超时 fetch、LRU 缓存等通用能力。
|
||
* web_search 和 web_fetch 共享此模块。
|
||
*
|
||
* @see docs/Agent网络工具通用设计-v2.md — 第 3 章 web_fetch 抓取设计
|
||
*/
|
||
|
||
import { LRUCache } from 'lru-cache';
|
||
import log from 'electron-log';
|
||
|
||
// ===== LRU 缓存 =====
|
||
|
||
/** 搜索结果缓存(200 条,5 分钟 TTL) */
|
||
export const searchCache = new LRUCache<string, Record<string, unknown>>({
|
||
max: 200,
|
||
ttl: 300_000,
|
||
});
|
||
|
||
/** 浏览器回退缓存(100 条,10 分钟 TTL) */
|
||
export const fetchCache = new LRUCache<string, string>({
|
||
max: 100,
|
||
ttl: 600_000,
|
||
});
|
||
|
||
// ===== UA 轮换池 =====
|
||
|
||
export const UA_POOL = [
|
||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
|
||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Edg/131.0.0.0 Safari/537.36',
|
||
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
|
||
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Safari/605.1.15',
|
||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0',
|
||
];
|
||
|
||
export const MOBILE_UA =
|
||
'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1';
|
||
|
||
export const ACCEPT_LANGUAGE_POOL = [
|
||
'zh-CN,zh;q=0.9,en;q=0.8',
|
||
'zh-CN,zh;q=0.9',
|
||
'en-US,en;q=0.9,zh-CN;q=0.8',
|
||
];
|
||
|
||
// ===== 反爬请求头构建 =====
|
||
|
||
export function buildAntiCrawlHeaders(
|
||
url: string,
|
||
attempt: number,
|
||
mobileUA = false,
|
||
): Record<string, string> {
|
||
const uaIdx = attempt % UA_POOL.length;
|
||
const langIdx = attempt % ACCEPT_LANGUAGE_POOL.length;
|
||
const userAgent = mobileUA ? MOBILE_UA : UA_POOL[uaIdx];
|
||
|
||
let origin = '';
|
||
try {
|
||
origin = new URL(url).origin;
|
||
} catch {
|
||
/* ignore */
|
||
}
|
||
|
||
return {
|
||
'User-Agent': userAgent,
|
||
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
|
||
'Accept-Language': ACCEPT_LANGUAGE_POOL[langIdx],
|
||
'Accept-Encoding': 'gzip, deflate, br',
|
||
'Cache-Control': 'no-cache',
|
||
DNT: '1',
|
||
Referer: origin || '',
|
||
'Sec-Fetch-Dest': 'document',
|
||
'Sec-Fetch-Mode': 'navigate',
|
||
'Sec-Fetch-Site': 'none',
|
||
'Sec-Fetch-User': '?1',
|
||
Pragma: 'no-cache',
|
||
};
|
||
}
|
||
|
||
// ===== 超时 fetch =====
|
||
|
||
export async function fetchWithTimeout(
|
||
url: string,
|
||
options: RequestInit = {},
|
||
timeoutMs = 20_000,
|
||
externalSignal?: AbortSignal,
|
||
): Promise<Response> {
|
||
// v0.8.0 P1-2: 合并外部 abort 信号(引擎中断时立即取消,不再跑到自身超时)
|
||
const controller = new AbortController();
|
||
const onExternalAbort = (): void => controller.abort();
|
||
if (externalSignal) {
|
||
if (externalSignal.aborted) controller.abort();
|
||
else externalSignal.addEventListener('abort', onExternalAbort, { once: true });
|
||
}
|
||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||
try {
|
||
return await fetch(url, { ...options, signal: controller.signal });
|
||
} finally {
|
||
clearTimeout(timer);
|
||
if (externalSignal) {
|
||
externalSignal.removeEventListener('abort', onExternalAbort);
|
||
}
|
||
}
|
||
}
|
||
|
||
// ===== URL 标准化(去重用) =====
|
||
|
||
/**
|
||
* H-6 增强: URL 标准化用于搜索结果去重
|
||
*
|
||
* 规范推荐使用 normalize-url 库(@see docs/Agent网络工具通用设计-v2.md §6.1.3),
|
||
* 但当前实现已覆盖核心场景,且避免 ESM-only 依赖兼容性风险,
|
||
* 故在现有基础上增强以下能力(对标 normalize-url 默认行为):
|
||
* 1. 去除追踪参数(utm_*, gclid, fbclid)
|
||
* 2. 强制小写 host
|
||
* 3. 去除尾部斜杠(根路径除外)
|
||
* 4. H-6 新增: 去除默认端口(http→:80, https→:443)
|
||
* 5. H-6 新增: 排序查询参数(避免 ?a=1&b=2 vs ?b=2&a=1 被视为不同 URL)
|
||
*/
|
||
export function normalizeUrl(url: string): string {
|
||
try {
|
||
const u = new URL(url);
|
||
|
||
// 去除追踪参数
|
||
const trackingParams = [
|
||
'utm_source',
|
||
'utm_medium',
|
||
'utm_campaign',
|
||
'utm_term',
|
||
'utm_content',
|
||
'gclid',
|
||
'fbclid',
|
||
];
|
||
for (const p of trackingParams) u.searchParams.delete(p);
|
||
|
||
// H-6 增强: 排序查询参数(确保参数顺序一致,便于去重)
|
||
// searchParams.sort() 原地排序,URLSearchParams 按码点顺序
|
||
u.searchParams.sort();
|
||
|
||
// 去除尾部斜杠(根路径除外)
|
||
let path = u.pathname;
|
||
if (path.length > 1 && path.endsWith('/')) path = path.slice(0, -1);
|
||
|
||
// H-6 增强: 去除默认端口
|
||
// http 默认 :80, https 默认 :443, ws 默认 :80, wss 默认 :443
|
||
const isDefaultPort =
|
||
(u.protocol === 'http:' && u.port === '80') ||
|
||
(u.protocol === 'https:' && u.port === '443') ||
|
||
(u.protocol === 'ws:' && u.port === '80') ||
|
||
(u.protocol === 'wss:' && u.port === '443');
|
||
const portSuffix = isDefaultPort ? '' : u.port ? `:${u.port}` : '';
|
||
|
||
// 强制小写 host
|
||
return `${u.protocol}//${u.hostname.toLowerCase()}${portSuffix}${path}${u.search}${u.hash}`;
|
||
} catch {
|
||
return url;
|
||
}
|
||
}
|
||
|
||
// ===== 拦截页面检测 =====
|
||
|
||
const INTERCEPTION_PATTERNS = [
|
||
/just a moment/i,
|
||
/attention required/i,
|
||
/challenge-platform/i,
|
||
/\.cf-challenge-/i,
|
||
/access denied/i,
|
||
/403 forbidden/i,
|
||
/请启用\s*javascript/i,
|
||
/please enable javascript/i,
|
||
/checking your browser/i,
|
||
/ddos protection/i,
|
||
];
|
||
|
||
export function isInterceptedPage(html: string): boolean {
|
||
if (html.length < 80) return true;
|
||
const lower = html.toLowerCase();
|
||
return INTERCEPTION_PATTERNS.some((p) => p.test(lower));
|
||
}
|
||
|
||
// ===== HTML → 纯文本转换 =====
|
||
|
||
const HTML_ENTITY_MAP: Record<string, string> = {
|
||
' ': ' ',
|
||
'<': '<',
|
||
'>': '>',
|
||
'&': '&',
|
||
'"': '"',
|
||
''': "'",
|
||
'…': '…',
|
||
'—': '—',
|
||
'–': '–',
|
||
'«': '«',
|
||
'»': '»',
|
||
'×': '×',
|
||
'÷': '÷',
|
||
'©': '©',
|
||
'®': '®',
|
||
'™': '™',
|
||
'€': '€',
|
||
'£': '£',
|
||
'¥': '¥',
|
||
'¢': '¢',
|
||
'°': '°',
|
||
};
|
||
|
||
export function htmlToText(html: string): string {
|
||
return (
|
||
html
|
||
// 移除噪声标签及内容
|
||
.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
|
||
.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
|
||
.replace(/<noscript[^>]*>[\s\S]*?<\/noscript>/gi, '')
|
||
.replace(/<nav[^>]*>[\s\S]*?<\/nav>/gi, '')
|
||
.replace(/<header[^>]*>[\s\S]*?<\/header>/gi, '')
|
||
.replace(/<footer[^>]*>[\s\S]*?<\/footer>/gi, '')
|
||
.replace(/<aside[^>]*>[\s\S]*?<\/aside>/gi, '')
|
||
.replace(/<iframe[^>]*>[\s\S]*?<\/iframe>/gi, '')
|
||
.replace(/<svg[^>]*>[\s\S]*?<\/svg>/gi, '')
|
||
// 移除 HTML 注释
|
||
.replace(/<!--[\s\S]*?-->/g, '')
|
||
// 块级标签转换行
|
||
.replace(/<\/?(p|div|h[1-6]|li|tr|blockquote|section|article|pre|br|hr)[^>]*>/gi, '\n')
|
||
// 表格单元格转制表符
|
||
.replace(/<\/?(td|th)[^>]*>/gi, '\t')
|
||
// 移除剩余标签
|
||
.replace(/<[^>]+>/g, '')
|
||
// 解码 HTML 实体
|
||
.replace(/&#(\d+);/g, (_, n) => String.fromCharCode(Number(n)))
|
||
.replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCharCode(parseInt(h, 16)))
|
||
.replace(/&[a-z]+;/gi, (m) => HTML_ENTITY_MAP[m.toLowerCase()] ?? m)
|
||
// 清理空白
|
||
.replace(/\n{3,}/g, '\n\n')
|
||
.replace(/[ \t]+/g, ' ')
|
||
.replace(/^[ \t]+/gm, '')
|
||
.trim()
|
||
);
|
||
}
|
||
|
||
// ===== 流式读取(大文件保护,10MB 上限) =====
|
||
|
||
export async function readBodyWithLimit(
|
||
response: Response,
|
||
maxBytes = 10 * 1024 * 1024,
|
||
): Promise<string> {
|
||
const contentLength = response.headers.get('content-length');
|
||
if (contentLength && parseInt(contentLength) > maxBytes) {
|
||
throw new Error(`Response too large: ${contentLength} bytes (limit: ${maxBytes})`);
|
||
}
|
||
|
||
const reader = response.body?.getReader();
|
||
if (!reader) return '';
|
||
|
||
const chunks: Uint8Array[] = [];
|
||
let totalBytes = 0;
|
||
|
||
try {
|
||
while (true) {
|
||
const { done, value } = await reader.read();
|
||
if (done) break;
|
||
if (value) {
|
||
totalBytes += value.byteLength;
|
||
if (totalBytes > maxBytes) {
|
||
throw new Error(`Response exceeded ${maxBytes} bytes limit`);
|
||
}
|
||
chunks.push(value);
|
||
}
|
||
}
|
||
} finally {
|
||
reader.releaseLock();
|
||
}
|
||
|
||
const decoder = new TextDecoder('utf-8', { fatal: false });
|
||
return decoder.decode(Buffer.concat(chunks));
|
||
}
|
||
|
||
// ===== SearXNG 认证头构建 =====
|
||
|
||
export function buildSearXNGAuthHeaders(authKey: string, authType: string): Record<string, string> {
|
||
if (!authKey) return {};
|
||
if (authType === 'bearer') {
|
||
return { Authorization: `Bearer ${authKey}` };
|
||
}
|
||
if (authType === 'basic') {
|
||
return { Authorization: `Basic ${Buffer.from(authKey).toString('base64')}` };
|
||
}
|
||
return {};
|
||
}
|
||
|
||
// ===== 日志辅助 =====
|
||
|
||
export function logTool(toolName: string, message: string): void {
|
||
log.info(`[Tool:${toolName}] ${message}`);
|
||
}
|
||
|
||
// ===== v0.7.3 P2-2: Agent 浏览器 CORS Origin 回显 =====
|
||
|
||
/**
|
||
* v0.7.4 P2-2 根治: Agent 浏览器 CORS 放行的唯一事实来源。
|
||
*
|
||
* 背景(v0.7.3 P2-2 仍不彻底):旧实现回显任意请求 Origin —— 等价 ACAO:* 且
|
||
* 允许凭据(回显值非 '*' 时浏览器会携带 cookies/localStorage 跨域读取),第三方
|
||
* 页面可借该分区的凭据读取任何被浏览过的跨域资源,比通配 '*' 更宽松。
|
||
*
|
||
* 根治:仅当请求 Origin 与「当前 Agent 正在浏览的页面 Origin」完全一致时才回显。
|
||
* 同源请求本就不需要 CORS(放行无副作用);跨域 Origin(第三方页面借道)一律
|
||
* 返回 null —— 不加 ACAO 头,浏览器保持默认同源策略阻止读取。无 Origin(同源
|
||
* 导航/资源子请求)同样返回 null(原回退 '*' 的语义一并移除——同源请求无需
|
||
* CORS 头即可读取)。
|
||
*
|
||
* @param requestOrigin 请求头 Origin(可能为 undefined / 任意字符串)
|
||
* @param allowedOrigin 当前浏览页面的 origin(如 'https://example.com');null 表示未知
|
||
* @returns 应写入响应的 ACAO 值(单元素数组);null 表示不加 ACAO 头(默认阻止跨域)
|
||
*/
|
||
export function corsAllowOrigin(
|
||
requestOrigin: string | undefined | null,
|
||
allowedOrigin: string | null | undefined,
|
||
): string[] | null {
|
||
const origin = requestOrigin?.trim();
|
||
const allowed = allowedOrigin?.trim();
|
||
if (!origin || !allowed) return null;
|
||
// 大小写不敏感 + 去尾斜杠比较(origin 规范无尾斜杠,防御性处理)
|
||
const normalize = (o: string): string => o.toLowerCase().replace(/\/+$/, '');
|
||
if (normalize(origin) === normalize(allowed)) {
|
||
return [origin];
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/** 从请求头集合中大小写不敏感地提取 Origin 值 */
|
||
export function extractOriginHeader(
|
||
requestHeaders: Record<string, string | string[] | undefined> | undefined,
|
||
): string | undefined {
|
||
if (!requestHeaders) return undefined;
|
||
for (const [key, value] of Object.entries(requestHeaders)) {
|
||
if (key.toLowerCase() === 'origin') {
|
||
return Array.isArray(value) ? value[0] : value;
|
||
}
|
||
}
|
||
return undefined;
|
||
}
|
||
|
||
// ===== v0.6.4 P4-4: HTML → Markdown 转换(web_fetch extract_mode='markdown') =====
|
||
//
|
||
// v0.6.4 收尾:私有 npm 凭据解锁后,按开发规范第一铁律把第一轮的临时自写实现
|
||
// 替换为 turndown(成熟库)。对外函数签名与行为契约保持不变:
|
||
// h1-h6(atx) / 段落 / 链接 / 图片 / strong+em+code 行内 / pre 围栏代码块 /
|
||
// ul('-') 与 ol(数字) 列表(跨空行合并为紧凑形态) / blockquote / hr('---') /
|
||
// 表格等未知块降级为纯文本、<script/style/svg/noscript/iframe> 整体剔除。
|
||
|
||
import TurndownService from 'turndown';
|
||
|
||
const turndown = new TurndownService({
|
||
headingStyle: 'atx',
|
||
bulletListMarker: '-',
|
||
codeBlockStyle: 'fenced',
|
||
emDelimiter: '*',
|
||
});
|
||
|
||
// 噪声节点显式剔除(与 htmlToText 的剥离口径一致)
|
||
turndown.remove(['script', 'style', 'noscript', 'iframe', 'svg']);
|
||
|
||
// hr 输出 GitHub 风格 '---'(turndown 默认 '* * *')
|
||
turndown.addRule('hr-rule', {
|
||
filter: ['hr'],
|
||
replacement: () => '\n\n---\n\n',
|
||
});
|
||
|
||
/** 列表项行判定:'- xxx' 或 '1. xxx'(允许前导空白) */
|
||
const LIST_LINE = /^\s*(?:- |\d+\. )/;
|
||
|
||
/**
|
||
* 紧凑化 + 规范化列表 —— turndown 对松散列表(li 之间带空白文本节点的常见书写)
|
||
* 输出条目间空行,且标记为 '- ' / '1. ' 多空格形态。这里做单趟扫描:
|
||
* 1. 归一化条目标记为紧凑形态('- ' / 'N. ');
|
||
* 2. 仅当"空行两侧都是同一列表的条目行"时移除该空行(绝不吞条目、不影响段落间距)。
|
||
*/
|
||
function collapseListGaps(markdown: string): string {
|
||
const lines = markdown
|
||
.split('\n')
|
||
.map((line) => line.replace(/^(\s*)- {2,}/, '$1- ').replace(/^(\s*\d+\.)\s{2,}/, '$1 '));
|
||
|
||
const isListItem = (l: string | undefined): boolean => (l ?? '').length > 0 && LIST_LINE.test(l!);
|
||
|
||
const out: string[] = [];
|
||
for (let i = 0; i < lines.length; i++) {
|
||
const line = lines[i];
|
||
if (line.trim() === '') {
|
||
const prev = out.length > 0 ? out[out.length - 1] : undefined;
|
||
const next = i + 1 < lines.length ? lines[i + 1] : undefined;
|
||
// 空行夹在两个列表项之间 → 移除;否则保留原始段落间隔
|
||
if (isListItem(prev) && isListItem(next)) continue;
|
||
out.push(line);
|
||
continue;
|
||
}
|
||
out.push(line);
|
||
}
|
||
return out.join('\n');
|
||
}
|
||
|
||
export function htmlToMarkdown(html: string): string {
|
||
if (!html || !html.trim()) return '';
|
||
|
||
let md: string;
|
||
try {
|
||
md = turndown.turndown(html);
|
||
} catch {
|
||
// 极端畸形输入时降级为空串(调用方已具备 Phase1 文本回退能力)
|
||
logTool?.('htmlToMarkdown', 'turndown conversion failed');
|
||
return '';
|
||
}
|
||
|
||
return collapseListGaps(md)
|
||
.replace(/\n{3,}/g, '\n\n')
|
||
.trim();
|
||
}
|