Files
metona-ai-desktop/electron/harness/hooks/pre-tool.ts
T
thzxx 49c9b25538
CI / 类型检查 + Lint + 单元测试 (push) Failing after 5m25s
CI / 全量测试 (Electron ABI, experimental) (push) Failing after 5m19s
CI / 产物编译验证 (push) Successful in 10m3s
feat: v0.4.1 质量加固版 — 工程化基线 + 安全加固 + 测试补齐 + 体验升级
工程化(从零到一):
- 新增 Gitea Actions CI(debian-latest):类型检查 + Lint + 单元测试 + 产物编译验证
- 新增 husky + lint-staged 预提交钩子(lint-staged + typecheck 门禁)
- 移除坏脚本 test:e2e(无 Playwright 配置必失败);prebuild 改用内置 fs.rmSync
- 依赖清理:移除死依赖 sql.js(2MB)/@playwright/test,@types/shell-quote 移至 devDependencies

安全加固:
- PolicyEngine 频率限制按会话隔离(多会话并发不再互抢配额)
- ConfirmationHook 拒绝记忆加 10 分钟 TTL + 恢复询问入口(新增 2 个 IPC 通道)
- Windows run_command 白名单工具(git/node/npm/npx/pnpm/yarn/tsc)改走 cmd.exe /c + 参数数组执行,收窄 shell 注入面
- web_search 四引擎 HTML 解析迁移 node-html-parser(结构化主层 + 正则降级)

缺陷修复(测试驱动发现):
- mapError 大小写缺陷:网络错误码永远落入 UNKNOWN 无法触发重试
- 搜狗解析器自我过滤:相对链接补全后又被 sogou.com 过滤导致结果全丢
- 百度复合类名重复收录:class="result c-container" 被双重匹配

测试补齐(113 → 194 用例):
- 新增 5 个测试文件:sse-stream / base-adapter / confirmation-hook / ipc-agent 编排链路 / web-search 解析器
- 覆盖 sendMessage 全分支、SSE 流解析、错误映射、确认钩子竞态/超时/批量审批

体验升级:
- OutputValidator 验证结果可见化(VALIDATION 流事件 → 聊天流提示卡)
- SettingsModal 巨型组件拆分(1503 行 → 10 个文件,可独立维护)
- MessageList 接入 react-virtuoso 真虚拟滚动(千条消息恒定开销)
- MCP 新增 streamable HTTP 传输支持(SDK 内置传输 + DB 迁移 6 + UI 双模式)
2026-08-21 13:58:48 +08:00

70 lines
2.6 KiB
TypeScript

/**
* Pre-Tool Hooks — 工具执行前钩子
*
* @see docs/生产级通用 AI Agent 智能体桌面应用:完整设计与构建指南.html — 第五章
*/
import type { MetonaToolCall } from '../types';
import type { PolicyEngine } from '../sandbox/permissions';
export interface HookResult {
blocked: boolean;
reason?: string;
modifiedArgs?: Record<string, unknown>;
}
export interface PreToolHook {
beforeExecute(toolCall: MetonaToolCall, sessionId: string): Promise<HookResult>;
}
/** 权限校验钩子 — 集成 PolicyEngine */
export class PermissionCheckHook implements PreToolHook {
constructor(private policyEngine: PolicyEngine) {}
async beforeExecute(toolCall: MetonaToolCall, sessionId: string): Promise<HookResult> {
// v0.4.1: 透传 sessionId 使频率限制按会话隔离(多会话并发时各自独立配额)
const result = this.policyEngine.checkAuthorization(toolCall.name, toolCall.args, sessionId);
if (!result.authorized) {
return { blocked: true, reason: result.reason };
}
// v0.3.0 修复: 授权成功后记录调用,使频率限制功能生效
// 在授权检查通过后立即记录,即使后续工具执行失败也计入频率
// 这样可以防止通过故意制造错误来绕过频率限制
this.policyEngine.recordCall(toolCall.name, sessionId);
return { blocked: false };
}
}
/** 速率限制钩子 */
export class RateLimitHook implements PreToolHook {
private callCounts = new Map<string, { count: number; resetTime: number }>();
constructor(private maxCallsPerMinute: number = 20) {}
async beforeExecute(toolCall: MetonaToolCall, sessionId: string): Promise<HookResult> {
// 使用 sessionId:toolName 作为 key,实现会话隔离的 per-tool 速率限制
const key = `${sessionId}:${toolCall.name}`;
const now = Date.now();
// v0.3.0 修复: 定期清理过期 entry,避免 Map 随会话累积无限增长
if (this.callCounts.size > 1000) {
for (const [k, v] of this.callCounts) {
if (v.resetTime < now) this.callCounts.delete(k);
}
}
const entry = this.callCounts.get(key);
// L-2 修复: 使用 > 而非 >=,确保窗口到期时正确重置(边界条件)
// 当 resetTime === now 时应视为已到期,进入 else 分支重建 entry
if (entry && entry.resetTime > now) {
if (entry.count >= this.maxCallsPerMinute) {
return { blocked: true, reason: `Rate limit exceeded for tool "${toolCall.name}"` };
}
entry.count++;
} else {
this.callCounts.set(key, { count: 1, resetTime: now + 60_000 });
}
return { blocked: false };
}
}