Files
metona-ai-desktop/electron/harness/hooks/pre-tool.ts
T
thzxx 3940716dc2
CI / 类型检查 + Lint + 单元测试 (push) Failing after 5m45s
CI / 全量测试 (Electron ABI) (push) Failing after 5m22s
CI / 产物编译验证 (push) Successful in 10m3s
feat: v0.7.0 四阶段全量迭代 — 修复面收口 · 安全纵深 · 架构还债 · 能力演进
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 桥契约
2026-08-27 17:06:58 +08:00

72 lines
2.9 KiB
TypeScript

/**
* Pre-Tool Hooks — 工具执行前钩子
*
* @see docs/生产级通用 AI Agent 智能体桌面应用:完整设计与构建指南.html — 第五章
*/
import type { MetonaToolCall } from '../types';
import type { PolicyEngine } from '../sandbox/permissions';
// v0.6.4 死代码清理:modifiedArgs 参数改写能力已删除 —— 接口预留后从未有任何
// 钩子生产它、引擎也从未消费它,属超前接口。若未来需要参数改写,应重新设计
// (需明确 engine 侧应用点与审计语义),而非保留哑字段。
export interface HookResult {
blocked: boolean;
reason?: string;
}
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 };
}
}