/** * Confirmation Hook — 工具执行前用户确认钩子(v0.2.0 新增) * * 对 requiresPermission=true 或 riskLevel >= HIGH 的工具, * 通过 IPC 请求用户确认后再执行。 * * 支持两种自动执行机制: * 1. 持久化自动执行(跨会话):存储在 ConfigService `tools.{toolName}.autoExecute` * 2. 会话内记忆:同一会话内不再重复询问(rememberDecisions) * * @see docs/生产级通用 AI Agent 智能体桌面应用:完整设计与构建指南.html — 第五章 */ import { BrowserWindow } from 'electron'; import type { MetonaToolCall, MetonaToolDef } from '../types'; import type { PreToolHook, HookResult } from './pre-tool'; import type { ConfigService } from '../../services/config.service'; export interface ConfirmationRequest { toolCallId: string; toolName: string; args: Record; riskLevel: string; reason: string; } export class ConfirmationHook implements PreToolHook { /** 需要确认的风险等级 */ private static REQUIRES_CONFIRMATION = ['high', 'critical']; /** 工具定义缓存(由外部设置) */ private toolDefs = new Map(); /** 用户选择记忆(同一会话内不再重复询问) */ private rememberedDecisions = new Map(); /** 持久化自动执行的工具集合(从 ConfigService 加载,跨会话生效) */ private autoExecuteTools = new Set(); /** 等待确认的 Promise 解析器 */ private pendingConfirmations = new Map void; timer: NodeJS.Timeout; toolName: string }>(); /** 确认超时时间(默认 120 秒) */ private readonly confirmationTimeoutMs = 120_000; constructor( private mainWindow: BrowserWindow | null = null, private configService: ConfigService | null = null, ) { this.loadAutoExecuteList(); } /** 设置主窗口(用于发送 IPC 消息) */ setMainWindow(window: BrowserWindow): void { this.mainWindow = window; } /** * 从 ConfigService 加载已设置为自动执行的工具列表 * 配置键格式:tools.{toolName}.autoExecute = true */ private loadAutoExecuteList(): void { if (!this.configService) return; try { const all = this.configService.getAll(); this.autoExecuteTools.clear(); for (const [key, value] of Object.entries(all)) { // 匹配 tools.{toolName}.autoExecute 键 const match = /^tools\.(.+)\.autoExecute$/.exec(key); if (match && value === true) { this.autoExecuteTools.add(match[1]); } } } catch { // 配置加载失败,忽略(不阻塞启动) } } /** * 设置/取消工具的持久化自动执行 * @param toolName 工具名 * @param enabled true=自动执行(不再询问),false=每次询问 */ setAutoExecute(toolName: string, enabled: boolean): void { const configKey = `tools.${toolName}.autoExecute`; if (this.configService) { this.configService.set(configKey, enabled); } if (enabled) { this.autoExecuteTools.add(toolName); // 自动执行时同步清除会话内"拒绝"记忆(避免冲突) this.rememberedDecisions.delete(toolName); } else { this.autoExecuteTools.delete(toolName); } } /** * 获取当前自动执行的工具列表 */ getAutoExecuteList(): string[] { return Array.from(this.autoExecuteTools); } /** 注入工具定义列表(用于查询风险等级) */ setToolDefs(defs: MetonaToolDef[]): void { this.toolDefs.clear(); for (const def of defs) { this.toolDefs.set(def.name, def); } } /** * 处理用户确认响应(由 IPC handler 调用) * @param remember 会话内记住决定 * @param autoExecute 永久自动执行(持久化) */ resolveConfirmation(toolCallId: string, approved: boolean, remember: boolean, autoExecute: boolean = false): void { const pending = this.pendingConfirmations.get(toolCallId); if (pending) { clearTimeout(pending.timer); pending.resolve(approved); // 永久自动执行(仅当用户批准时才设置) if (autoExecute && approved) { this.setAutoExecute(pending.toolName, true); } // 会话内记忆 if (remember) { this.rememberedDecisions.set(pending.toolName, approved); } this.pendingConfirmations.delete(toolCallId); } } async beforeExecute(toolCall: MetonaToolCall, _sessionId: string): Promise { const def = this.toolDefs.get(toolCall.name); if (!def) { // 未知工具,放行(由 ToolRegistry 处理未知工具错误) return { blocked: false }; } // 检查是否需要确认 const needsConfirmation = def.requiresPermission || ConfirmationHook.REQUIRES_CONFIRMATION.includes(def.riskLevel); if (!needsConfirmation) { return { blocked: false }; } // 优先检查持久化自动执行(跨会话生效) if (this.autoExecuteTools.has(toolCall.name)) { return { blocked: false }; } // 检查是否有记住的决策 const remembered = this.rememberedDecisions.get(toolCall.name); if (remembered !== undefined) { if (remembered) return { blocked: false }; return { blocked: true, reason: `User previously denied tool "${toolCall.name}"` }; } // 如果没有主窗口,安全起见阻止执行 if (!this.mainWindow || this.mainWindow.isDestroyed()) { return { blocked: true, reason: 'Cannot request confirmation: no main window available' }; } // 发送确认请求到渲染进程 const request: ConfirmationRequest = { toolCallId: toolCall.id, toolName: toolCall.name, args: toolCall.args, riskLevel: def.riskLevel, reason: def.requiresPermission ? `Tool "${toolCall.name}" requires permission (risk: ${def.riskLevel})` : `Tool "${toolCall.name}" has high risk level: ${def.riskLevel}`, }; // 等待用户响应(带超时) const approved = await this.waitForConfirmation(request); if (!approved) { return { blocked: true, reason: `User denied execution of tool "${toolCall.name}"` }; } return { blocked: false }; } /** * 等待用户确认(带超时) */ private waitForConfirmation(request: ConfirmationRequest): Promise { return new Promise((resolve) => { // 设置超时 const timer = setTimeout(() => { this.pendingConfirmations.delete(request.toolCallId); resolve(false); // 超时视为拒绝 }, this.confirmationTimeoutMs); this.pendingConfirmations.set(request.toolCallId, { resolve, timer, toolName: request.toolName, }); // 发送确认请求到渲染进程 if (this.mainWindow && !this.mainWindow.isDestroyed()) { this.mainWindow.webContents.send('tool:confirmationRequest', request); } }); } /** * 清理所有等待中的确认(会话结束时调用) */ clearPending(): void { for (const [, pending] of this.pendingConfirmations) { clearTimeout(pending.timer); pending.resolve(false); } this.pendingConfirmations.clear(); } }