Files
metona-ai-desktop/electron/harness/hooks/confirmation-hook.ts
T
thzxx 3c5aea8fb7 feat: 升级至 v0.2.1 — 流式渲染修复、安全增强、工具自动执行
流式渲染修复:
- runId 机制防止 abort 后旧流事件污染新 run
- run lock 防止并发 run 污染引擎状态
- abort race 提前退出工具执行等待
- TERMINATED 状态通过 stateChange 发射
- tool_call_delta 流式参数拼接 + pending 占位替换
- 首轮卡片创建路径统一,traceStep 按 ID 精确匹配
- compressed 事件转发为 toast 通知

安全增强:
- ConfirmationHook 支持持久化自动执行(跨会话)
- 设置面板新增自动执行工具管理 UI
- SandboxManager 双重安全校验 fail-closed
- 审计日志链式哈希防篡改
- PromptInjectionDefender 中文注入标记清理
- scanCode 28 模式 + base64/$() 检测
- validatePath realpathSync 防符号链接逃逸
- code-search 使用 execFile 防命令注入

新增工具:
- file_editor、code_search、task_manager、diff_viewer

其他:
- Agent Loop 加 PARSING/REFLECTING 状态 + 指数退避重试
- MemoryManager TF-IDF 语义检索
- run_command Windows 中文编码修复(chcp 65001)
- 版本号 0.2.0 → 0.2.1
2026-07-12 12:54:52 +08:00

223 lines
7.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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<string, unknown>;
riskLevel: string;
reason: string;
}
export class ConfirmationHook implements PreToolHook {
/** 需要确认的风险等级 */
private static REQUIRES_CONFIRMATION = ['high', 'critical'];
/** 工具定义缓存(由外部设置) */
private toolDefs = new Map<string, MetonaToolDef>();
/** 用户选择记忆(同一会话内不再重复询问) */
private rememberedDecisions = new Map<string, boolean>();
/** 持久化自动执行的工具集合(从 ConfigService 加载,跨会话生效) */
private autoExecuteTools = new Set<string>();
/** 等待确认的 Promise 解析器 */
private pendingConfirmations = new Map<string, { resolve: (v: boolean) => 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<HookResult> {
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<boolean> {
return new Promise<boolean>((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();
}
}