本次升级基于完整代码审查,修复 Critical/High/Medium/Low 四级共 96 项问题, 并通过返工审计修复 10 项遗留问题,tsc 双端类型检查零错误。 Critical (10/10 完成): - C-4: command.ts 接入 shell-quote 进行 token-level 注入检测,替代原有正则匹配 可防御 r"m" -rf /、$'rm'、$(echo rm) 等字符串拼接绕过 High (11/11 完成): - 竞态保护、Promise.allSettled、AbortController 资源泄漏、IPC 参数校验等 Medium (55/55 完成): - 事务保护、敏感数据脱敏、枚举校验、MUI v9 Stack prop 迁移、 React 组件 cancelled 标志、类型收窄等 Low (20/20 完成): - 辅助方法提取(flushToolCallBuffer/scoreAndPushMemory/tryAddColumn 等) - nanoid 统一替代 Date.now()+Math.random() - confirm() 替换为 MUI Dialog、useMemo 缓存、魔法数字命名化等 返工审计修复 (10/10 完成): - L-11: LogsSettings 残留的原生 confirm()/alert() 全部替换为 MUI Dialog/Alert - M-53: MemoryViewer handleSearch 独立 ref,修复 searching 状态卡死 - M-42: 脱敏短值(length <= 4)泄露修复 - M-47: tasks:update 补全 title/description 类型校验 - L-9: ollama.adapter 非流式路径 nanoid 统一 - M-45: audit:query limit 策略与 memory:listAll 一致化 - SettingsModal handleConfirmRemove 补全 try/catch + loadServers cleanup - L-15: CommandPalette useMemo 补全 sessions 响应式依赖 - useAgentStream 事件类型补全 seq/timestamp 字段 新增依赖: shell-quote + @types/shell-quote 版本号: 0.3.0 -> 0.3.1
160 lines
4.6 KiB
TypeScript
160 lines
4.6 KiB
TypeScript
/**
|
|
* Tool Registry — 工具注册表
|
|
*
|
|
* 管理所有可用工具(内置 + MCP),提供查找、注册、注销功能。
|
|
* 提供 per-tool 超时强制和结果大小限制,防止卡死和上下文溢出。
|
|
*/
|
|
|
|
import type {
|
|
MetonaToolDef,
|
|
MetonaToolCall,
|
|
MetonaToolResult,
|
|
} from '../types';
|
|
import type { IMetonaTool, ToolRegistryEntry, ToolExecutionContext } from '../types/metona-tool';
|
|
|
|
/** 工具返回值最大字符数(约 50KB),超过则截断 */
|
|
const MAX_RESULT_CHARS = 50_000;
|
|
|
|
export class ToolRegistry {
|
|
private tools = new Map<string, ToolRegistryEntry>();
|
|
|
|
/** 注册内置工具 */
|
|
registerBuiltin(tool: IMetonaTool): void {
|
|
this.tools.set(tool.definition.name, {
|
|
tool,
|
|
source: 'builtin',
|
|
enabled: true,
|
|
});
|
|
}
|
|
|
|
/** 注册 MCP 工具 */
|
|
registerMCP(serverName: string, tool: IMetonaTool): void {
|
|
this.tools.set(tool.definition.name, {
|
|
tool,
|
|
source: 'mcp',
|
|
serverName,
|
|
enabled: true,
|
|
});
|
|
}
|
|
|
|
/** 注销 MCP Server 提供的所有工具 */
|
|
unregisterMCPTools(serverName: string): void {
|
|
for (const [name, entry] of this.tools) {
|
|
if (entry.source === 'mcp' && entry.serverName === serverName) {
|
|
this.tools.delete(name);
|
|
}
|
|
}
|
|
}
|
|
|
|
/** 获取工具 */
|
|
get(name: string): IMetonaTool | undefined {
|
|
const entry = this.tools.get(name);
|
|
if (!entry?.enabled) return undefined;
|
|
return entry.tool;
|
|
}
|
|
|
|
/** 列出所有已启用工具的定义 */
|
|
listTools(): MetonaToolDef[] {
|
|
return Array.from(this.tools.values())
|
|
.filter((e) => e.enabled)
|
|
.map((e) => e.tool.definition);
|
|
}
|
|
|
|
/** 列出所有工具定义(含已禁用的,供设置 UI 使用) */
|
|
listAllTools(): Array<MetonaToolDef & { enabled: boolean }> {
|
|
return Array.from(this.tools.values()).map((e) => ({
|
|
...e.tool.definition,
|
|
enabled: e.enabled,
|
|
}));
|
|
}
|
|
|
|
/** 设置工具启用/禁用状态(供 IPC tools:toggle 调用) */
|
|
setToolEnabled(name: string, enabled: boolean): void {
|
|
const entry = this.tools.get(name);
|
|
if (entry) {
|
|
entry.enabled = enabled;
|
|
}
|
|
}
|
|
|
|
/** 执行工具(带超时强制和结果大小限制) */
|
|
async execute(
|
|
toolCall: MetonaToolCall,
|
|
context: ToolExecutionContext,
|
|
): Promise<MetonaToolResult> {
|
|
const tool = this.get(toolCall.name);
|
|
if (!tool) {
|
|
return {
|
|
toolCallId: toolCall.id,
|
|
toolName: toolCall.name,
|
|
result: null,
|
|
success: false,
|
|
error: `Unknown tool: ${toolCall.name}`,
|
|
durationMs: 0,
|
|
timestamp: Date.now(),
|
|
};
|
|
}
|
|
|
|
const startTs = Date.now();
|
|
const timeoutMs = tool.definition.timeoutMs;
|
|
|
|
// M-15 修复: 使用 try/finally 清理 setTimeout,防止事件循环 timer 堆积
|
|
// 工具正常完成时未触发的 timer 会持续占用事件循环 timeoutMs 毫秒
|
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
try {
|
|
// 带超时执行 — 使用 Promise.race 防止工具卡死阻塞 Agent Loop
|
|
const result = await Promise.race([
|
|
tool.execute(toolCall.args, context),
|
|
new Promise<never>((_, reject) => {
|
|
timer = setTimeout(
|
|
() => reject(new Error(`Tool execution timed out after ${timeoutMs}ms`)),
|
|
timeoutMs,
|
|
);
|
|
}),
|
|
]);
|
|
|
|
// 结果大小限制 — 防止过大返回值耗尽 LLM 上下文窗口
|
|
const safeResult = this.truncateResult(result);
|
|
|
|
return {
|
|
toolCallId: toolCall.id,
|
|
toolName: toolCall.name,
|
|
result: safeResult,
|
|
success: true,
|
|
durationMs: Date.now() - startTs,
|
|
timestamp: Date.now(),
|
|
};
|
|
} catch (error) {
|
|
return {
|
|
toolCallId: toolCall.id,
|
|
toolName: toolCall.name,
|
|
result: null,
|
|
success: false,
|
|
error: (error as Error).message,
|
|
durationMs: Date.now() - startTs,
|
|
timestamp: Date.now(),
|
|
};
|
|
} finally {
|
|
// M-15 修复: 无论工具成功或失败,清理 timeout timer
|
|
if (timer) clearTimeout(timer);
|
|
}
|
|
}
|
|
|
|
/** 截断过大的工具返回值,防止 LLM 上下文溢出 */
|
|
private truncateResult(result: unknown): unknown {
|
|
const str = typeof result === 'string' ? result : JSON.stringify(result);
|
|
if (str.length <= MAX_RESULT_CHARS) return result;
|
|
|
|
return {
|
|
_truncated: true,
|
|
_original_size: str.length,
|
|
_preview: str.slice(0, MAX_RESULT_CHARS),
|
|
_message: `Result truncated: original ${str.length} chars exceeds limit ${MAX_RESULT_CHARS}`,
|
|
};
|
|
}
|
|
|
|
/** 获取工具数量 */
|
|
get size(): number {
|
|
return Array.from(this.tools.values()).filter((e) => e.enabled).length;
|
|
}
|
|
}
|