安全修复: - 开启 webSecurity(CORS 改为 webRequest 允许清单精确放行 Ollama 地址) - 新增 net-guard SSRF 防护:web_fetch/download_file/browser_open 拦截环回/内网/链路本地地址(DNS 解析后校验) - browser_open 协议白名单(仅 http/https,阻止 file:// 绕过路径安全层) - git 参数注入防护(用户可控参数禁止 - 开头;git add 强制 -- 分隔) - 身份文件保护:SOUL.md/AGENT.md/USER.md 工具只读(防提示注入持久化劫持) - 系统目录硬红线 + 工作空间/白名单不可豁免系统目录 - spawn_task 权限只降不升(封顶于用户设置 subAgentMaxPermission) - 子代理写类工具接入主 Agent 确认管线 + 完整路径沙箱 - toast 改 textContent、HTML 导出 escapeHtml(XSS 修复) - Agent 浏览器改用 memory: 内存分区(退出清空 cookie/storage) 数据层重构: - sql.js 写入改防抖批量落盘(300ms 合并快照 + temp 原子替换 + 退出刷盘) - Schema 迁移改 PRAGMA user_version 顺序迁移数组 - 消息/设置/轨迹批量写(单事务);SearXNG 配置 13 次写合并为 1 次 - 会话摘要查询(getSessionSummaries/searchSessions 单条 SQL)消除 N+1 - 导出改 getAllSessionsData 一次 IPC 取回全部行 Bug 修复: - edit_file 替换符污染($&/$1 被特殊解释导致文件写坏) - truncateToolResult 暴力截断拼接非法 JSON 必然崩溃 - diff 算法 100MB dp 数组 → 前缀/后缀裁剪 + LCS 限额 + 回退 - move_file 跨盘 rename 失败回退 copy+delete - Ctrl+K 快捷键冲突(双注册);全局错误处理器双注册 - ffmpeg stderr 无限累积 + 帧进度 O(n²) 正则 - 搜索可达性预检只取响应头(Range: bytes=0-0) - 备份导出逐字节 base64 拼接(O(n²))改 FileReader - MCP clientInfo 版本硬编码 5.0.0 改真实版本;tools/list 支持 nextCursor 分页 - 看门狗默认值统一为 30 分钟;download_file 超时跟随用户配置 架构改进: - 主进程工具分发注册表 tool-dispatch.ts(消除 switch 硬编码) - agent-engine 拆分 result-formatter.ts / tool-parsing.ts(纯函数) - 文本兜底解析白名单改从注册表派生(补齐 browser_*/diff/spawn_task/mcp_*) - diff 工具默认启用;MODE_TOOLS 单一事实来源(tools-modal 复用) - 记忆系统:条目缓存 + 访问统计(hits/last)持久化 + removeById 按 ID 删除 - 度量历史启动恢复 + Metrics 仪表盘接入 JSON/Prometheus 导出 - 子代理模型下拉框打开设置时刷新(此前从未填充) 死代码清理(约 1400 行): - 删除 context-indexer 整模块、agent-safety 震荡检测/性能报告/依赖图/记忆调优/归档取回 - 删除 context-manager 水印/跳过压缩/自适应窗口/趋势分析/预算分配等未接线函数 - 删除 sanitizeToolArgs(污染 write_file 内容,防注入职责移交主进程安全层) - infra-service 裁剪为全局错误处理器唯一定义 文档对齐: - 新增内置 AGENT.md(工作空间同名文件可覆盖) - README/帮助面板/DEVELOPMENT 移除失实描述(WAL/内部URL拦截/5层防御/并行白名单/Hook 数量) - 工具数量口径统一 33;安全机制表新增 SSRF/身份保护/子代理权限等 9 项 工程化: - Vitest + 34 个单元测试(myers-diff/calculator/net-guard/MEMORY.md 格式) - Gitea Actions CI(typecheck + test + build) - package.json 新增 typecheck/test 脚本
This commit is contained in:
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* Tool Parsing — 模型文本输出的工具调用解析(兜底)
|
||||
* 从 agent-engine.ts 拆分的纯解析模块。
|
||||
*
|
||||
* 覆盖场景:模型未通过原生 tool_calls 字段返回,而是在文本中书写工具调用。
|
||||
* 支持四种格式:Action/Action Input、<tool_call> XML、```json 代码块、函数调用语法。
|
||||
*/
|
||||
|
||||
import { logInfo, logWarn } from './log-service.js';
|
||||
import { TOOL_DEFINITIONS } from './tool-registry.js';
|
||||
import type { ToolCall } from '../types.js';
|
||||
|
||||
/** 工具名白名单:从注册表派生(含 MCP 工具),不再手工维护 */
|
||||
const VALID_TOOL_NAMES: Set<string> = new Set(TOOL_DEFINITIONS.map(d => d.function.name));
|
||||
|
||||
function isValidToolName(name: string): boolean {
|
||||
return VALID_TOOL_NAMES.has(name) || name.startsWith('mcp_');
|
||||
}
|
||||
|
||||
export function parseToolCallsFromText(content: string): ToolCall[] {
|
||||
const calls: ToolCall[] = [];
|
||||
|
||||
// 辅助函数:尝试解析 JSON 参数字符串,容错处理
|
||||
const tryParseArgs = (argsStr: string): Record<string, unknown> | null => {
|
||||
const TICK = String.fromCharCode(96);
|
||||
const tickJson = TICK + TICK + TICK + 'json';
|
||||
const tick3 = TICK + TICK + TICK;
|
||||
try {
|
||||
let cleaned = argsStr.split(tickJson).join('').split(tick3).join('').trim();
|
||||
return JSON.parse(cleaned);
|
||||
} catch {
|
||||
try {
|
||||
let fixed = argsStr
|
||||
.replace(/'/g, '"')
|
||||
.replace(/,\s*}/g, '}')
|
||||
.replace(/,\s*]/g, ']')
|
||||
.split(tickJson).join('')
|
||||
.split(tick3).join('')
|
||||
.trim();
|
||||
return JSON.parse(fixed);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 辅助函数:验证工具名并添加到结果
|
||||
const tryAddCall = (toolName: string, argsStr: string): boolean => {
|
||||
toolName = toolName.trim();
|
||||
if (!isValidToolName(toolName)) return false;
|
||||
const args = tryParseArgs(argsStr);
|
||||
if (!args) {
|
||||
logWarn('文本解析兜底: 工具 ' + toolName + ' 的参数 JSON 解析失败', argsStr.slice(0, 100));
|
||||
return false;
|
||||
}
|
||||
calls.push({ type: 'function', function: { name: toolName, arguments: args } });
|
||||
return true;
|
||||
};
|
||||
|
||||
// ── 格式1: Action/Action Input ──
|
||||
const actionRegex = /\*{0,2}Action:?\*{0,2}\s*(\w+)\s+[\r\n\s]*\*{0,2}Action\s*Input:?\*{0,2}\s*(\{[\s\S]*?\})/gi;
|
||||
let match;
|
||||
while ((match = actionRegex.exec(content)) !== null) {
|
||||
tryAddCall(match[1], match[2]);
|
||||
}
|
||||
|
||||
// ── 格式2: <tool_call> XML 标签 ──
|
||||
const xmlRegex = /<tool_call>\s*([\s\S]*?)<\/tool_call>/gi;
|
||||
while ((match = xmlRegex.exec(content)) !== null) {
|
||||
const inner = match[1].trim().replace(/```json\s*/g, '').replace(/```/g, '').trim();
|
||||
try {
|
||||
const parsed = JSON.parse(inner);
|
||||
const toolName = parsed.name || parsed.function?.name || '';
|
||||
const toolArgs = parsed.arguments || parsed.function?.arguments || parsed.parameters || {};
|
||||
if (toolName && isValidToolName(toolName)) {
|
||||
calls.push({ type: 'function', function: { name: toolName, arguments: toolArgs } });
|
||||
}
|
||||
} catch {
|
||||
// JSON 解析失败,尝试分别提取 name 和 arguments
|
||||
const nameMatch = inner.match(/"name"\s*:\s*"(\w+)"/i);
|
||||
if (nameMatch) {
|
||||
const argsMatch = inner.match(/"arguments"\s*:\s*(\{[\s\S]*\})/i);
|
||||
if (argsMatch) tryAddCall(nameMatch[1], argsMatch[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── 格式3: ```json 代码块中含 "name" 字段 ──
|
||||
const codeBlockRegex = /```(?:json)?\s*(\{[\s\S]*?"name"\s*:\s*"\w+"[\s\S]*?\})\s*```/gi;
|
||||
while ((match = codeBlockRegex.exec(content)) !== null) {
|
||||
const jsonStr = match[1].trim();
|
||||
try {
|
||||
const parsed = JSON.parse(jsonStr);
|
||||
const toolName = parsed.name || '';
|
||||
const toolArgs = parsed.arguments || parsed.parameters || {};
|
||||
if (toolName && isValidToolName(toolName)) {
|
||||
calls.push({ type: 'function', function: { name: toolName, arguments: toolArgs } });
|
||||
}
|
||||
} catch {
|
||||
// 解析失败忽略,其他格式可能匹配
|
||||
}
|
||||
}
|
||||
|
||||
// ── 格式4: 函数调用语法 func_name({"key": "value"}) ──
|
||||
// 使用平衡括号匹配替代 [^}]*,支持嵌套 JSON 如 {"a": {"b": 1}}
|
||||
{
|
||||
const funcCallStart = /\b(\w+)\s*\(\s*\{/g;
|
||||
let fcMatch;
|
||||
while ((fcMatch = funcCallStart.exec(content)) !== null) {
|
||||
const toolName = fcMatch[1];
|
||||
const braceStart = fcMatch.index + fcMatch[0].length - 1; // 指向 '{'
|
||||
// 手动平衡匹配大括号
|
||||
let depth = 0;
|
||||
let endIdx = -1;
|
||||
let inString = false;
|
||||
let escapeNext = false;
|
||||
for (let i = braceStart; i < content.length; i++) {
|
||||
const ch = content[i];
|
||||
if (escapeNext) { escapeNext = false; continue; }
|
||||
if (ch === '\\') { escapeNext = true; continue; }
|
||||
if (ch === '"') { inString = !inString; continue; }
|
||||
if (inString) continue;
|
||||
if (ch === '{') depth++;
|
||||
else if (ch === '}') {
|
||||
depth--;
|
||||
if (depth === 0) { endIdx = i; break; }
|
||||
}
|
||||
}
|
||||
if (endIdx > 0) {
|
||||
const jsonStr = content.slice(braceStart, endIdx + 1);
|
||||
// 检查后面是否有闭合括号
|
||||
const afterClose = content.slice(endIdx + 1).match(/^\s*\)/);
|
||||
if (afterClose) {
|
||||
tryAddCall(toolName, jsonStr);
|
||||
// 移动 regex 位置到匹配结束后
|
||||
funcCallStart.lastIndex = endIdx + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (calls.length > 0) {
|
||||
logInfo('文本解析兜底: 从回复中提取到 ' + calls.length + ' 个工具调用', calls.map(c => c.function.name).join(', '));
|
||||
}
|
||||
|
||||
return calls;
|
||||
}
|
||||
Reference in New Issue
Block a user