feat: v0.7.3 成本收口 · 状态一致 · 死账清理 — Prompt Cache 根治 + SSRF DNS Pinning + 87 用例扩充全量回归
P1 修复面收口: Prompt Cache 根治(日期/记忆/附件三类易变内容出 system 入用户消息 前置块 user-context.ts, system 跨 run 字节级稳定; Anthropic system 块数组化 + cache_control ephemeral 断言, DeepSeek 自动缓存前缀命中 — 多轮对话输入 token 成本降数量级); 编辑重发/重新生成幽灵 Trace 双侧根治(DB truncateMessagesAfter 同步过滤 metadata.traceSteps + 前端 trimTraceStepsByAnchor 镜像, 严格小于锚点 时间戳, 同毫秒等值判废); sessions:deleteMessage 死通道全链路删除(渲染层零调用 + message_count 漂移面); Ollama vision 能力门控全链路(MetonaModelInfo .supportsVision 贯穿 adapter/IPC/store/UI, model-capabilities.ts 三道判定纯函数, 未知保守放行); 记忆固化节流(consolidation-policy 纯函数: 总开关 + 内容门控 [回答>=200字符或存在成功工具调用] + 会话级 10 分钟频率窗口, 三 memory.* 配置键) P2 安全纵深: SSRF DNS Pinning 关闭 rebinding 窗口(ssrf-guard 重构 resolvePublicAddresses 单源; ssrf-dispatcher 以 undici Agent.connect.lookup 钉死校验 IP, TLS SNI 保持原域名, 一次性 dispatcher 用后即毁; 代理激活显式 退化为仅入口校验); web_fetch 重写手动逐跳重定向循环(每跳先校验后连接, 替代 redirect:follow 内核跟跳的中间跳裸奔, 上限 5 跳); http_request 换用 pinned fetch; web_search 可达性预检加固(私有 URL 零请求 + 不跟跳, 3xx 视为 可达); Agent 浏览器 CORS 通配收紧为 Origin 回显 + Vary: Origin; ConfirmationHook.forgetSession 会话终态清理(会话删除/abort 联动/SubAgent 终结三处接线, 根治 rememberedDecisions 泄漏) P3 架构还债: agent.enableReflection 死配置全链路接线(main→shared→引擎→ Orchestrator→设置开关, REFLECTING 状态真实可达); AgentLoopConfig.timeoutMs 死字段删除; MemoryManager.cleanupExpired 挂入健康检查周期(expires_at 回收 管道真实化); buildSafeEnv 收敛 utils/safe-env.ts 单源(run_command 与 MCP stdio 共用, 终结双实现漂移); Trace 生命周期治理(metadata 只保留最近 20 个 run — keepRecentRuns 纯函数; JSONL 录制启动自动清理保留 200 个 + 设置页 手动清理); SLO/健康快照可视化(app:healthSnapshot IPC + 设置页只读卡片 + 审计链一键校验) P4 能力演进: 会话标题 LLM 自动生成(TitleGenerator — 每会话幂等/并发重入复用 同一 Promise/自定义标题不覆盖/失败静默回退, Sidebar 经 config:changed 实时 刷新); MCP 自动重连(5s/15s/60s 退避最多 3 次, reconnecting 状态机, teardownConnection 内部拆除保留簿记 — 用户断开/开关关闭即时取消, 设置页 显示第 N/3 次); 死循环检测 ABAB 乒乓模式(最近4轮 A→B→A→B 交替判定, 补齐 docs 第五章"两状态反复切换"检测契约); i18n 第三阶段(ChatInput/LLMSettings/ OnboardingWizard/MemoryViewer 主链路文案出层, zh-CN + en-US 双字典补齐) 测试: 737 → 824 用例(+87, 新增 8 个测试文件 + 扩展 3 个)。新覆盖: user-context 分组/空值收缩/拼接契约、context-builder 字节级稳定性、Anthropic cache_control 四态、consolidation-policy 九路判定矩阵、ssrf-dispatcher(pinned lookup/重定向 解析/IP 校验)、forget-session 会话隔离、trace-lifecycle run 淘汰、 trace-trim 严格小于边界、safe-env 净化矩阵、mcp-reconnect 退避状态机 (fake timers)、title-generator 并发重入、SQLite 侧 truncate×TRACE 联动 (Electron ABI)。测试驱动修复: GIT_*/ 注释终止块注释、重连计数被自身重试 前置断开重置(拆 teardownConnection 保留簿记)、TitleGenerator 幂等占位与 并发去重的检查顺序竞态(去重先于幂等) 版本: 0.7.3; README 同步(配置表新增 agent.enableReflection/memory.*/mcp.autoReconnect) 回归: typecheck 双端 0 错误; ESLint 0/0; 系统 Node 771 通过 53 跳过 (better-sqlite3 ABI); Electron ABI 全量 824/824 零跳过
This commit is contained in:
@@ -25,6 +25,8 @@ import type { ToolRegistry } from '../harness/tools/registry';
|
||||
import type { IMetonaTool, ToolExecutionContext } from '../harness/types/metona-tool';
|
||||
import type { MetonaToolDef } from '../harness/types';
|
||||
import { MetonaToolCategory, MetonaRiskLevel } from '../harness/types';
|
||||
// v0.7.3 P3-2: 子进程环境净化收敛到 utils/safe-env.ts 单源(与 run_command 共用)
|
||||
import { buildSafeChildEnv } from '../utils/safe-env';
|
||||
|
||||
// v0.3.0 修复: 安全解析 JSON args,防止数据库中存储了非法 JSON 导致初始化崩溃
|
||||
/** @visibleForTesting 纯函数,供安全表测直接断言 */
|
||||
@@ -97,44 +99,14 @@ export function validateMcpCommand(command: string, args: string[]): void {
|
||||
/**
|
||||
* #6 修复 + 审查修复: 构建安全的子进程环境变量
|
||||
*
|
||||
* 审查修复: 原白名单方案过于激进,剥离了 MCP Server 运行所需的 npm_config_*、代理变量等,
|
||||
* 导致 MCP Server 无法启动。改为黑名单方案:剔除包含敏感后缀的变量,保留其余。
|
||||
*
|
||||
* 注意: GITHUB_TOKEN / SLACK_BOT_TOKEN 等含 _TOKEN 后缀的变量也会被过滤。
|
||||
* v0.7.3 P3-2: 实现收敛到 utils/safe-env.ts(buildSafeChildEnv)——与
|
||||
* run_command 共用同一黑名单(历史双实现已漂移)。MCP 侧无运行时差异注入。
|
||||
* 注意: GITHUB_TOKEN / SLACK_BOT_TOKEN 等含 _TOKEN 后缀的变量会被过滤;
|
||||
* 如果 MCP Server 需要这些凭证,应通过 MCP Server 配置文件传递,而非环境变量。
|
||||
*/
|
||||
/** @visibleForTesting 纯函数,供安全表测直接断言 */
|
||||
export function buildSafeEnv(): Record<string, string> {
|
||||
// 敏感变量后缀黑名单 — 匹配这些后缀的变量不会被传递给子进程
|
||||
const SENSITIVE_SUFFIXES = [
|
||||
'_API_KEY',
|
||||
'_TOKEN',
|
||||
'_SECRET',
|
||||
'_PASSWORD',
|
||||
'_PASSWD',
|
||||
'_CREDENTIAL',
|
||||
'_CREDENTIALS',
|
||||
'_PRIVATE_KEY',
|
||||
];
|
||||
// 敏感变量名黑名单(精确匹配)
|
||||
const SENSITIVE_KEYS = new Set([
|
||||
'DEEPSEEK_API_KEY',
|
||||
'AGNES_API_KEY',
|
||||
'MIMO_API_KEY',
|
||||
'GITEA_PASSWORD',
|
||||
'DATABASE_PASSWORD',
|
||||
]);
|
||||
|
||||
const env: Record<string, string> = {};
|
||||
for (const [key, val] of Object.entries(process.env)) {
|
||||
if (!val) continue;
|
||||
// 跳过敏感变量名
|
||||
if (SENSITIVE_KEYS.has(key)) continue;
|
||||
// 跳过敏感后缀变量
|
||||
if (SENSITIVE_SUFFIXES.some((suffix) => key.toUpperCase().endsWith(suffix))) continue;
|
||||
env[key] = val;
|
||||
}
|
||||
return env;
|
||||
return buildSafeChildEnv();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -171,7 +143,29 @@ export function safeParseHeaders(
|
||||
|
||||
// ===== 类型定义 =====
|
||||
|
||||
export type MCPServerStatus = 'connecting' | 'connected' | 'disconnected' | 'error';
|
||||
export type MCPServerStatus =
|
||||
| 'connecting'
|
||||
| 'connected'
|
||||
| 'disconnected'
|
||||
| 'error'
|
||||
| 'reconnecting';
|
||||
|
||||
// ===== v0.7.3 P4-2: 自动重连策略常量 =====
|
||||
|
||||
/** 最大自动重连次数(超过后停留 error 态,等待用户手动 toggle) */
|
||||
export const MAX_RECONNECT_ATTEMPTS = 3;
|
||||
|
||||
/**
|
||||
* 重连退避间隔(毫秒):5s / 15s / 60s。
|
||||
* 纯函数 nextRetryDelayMs 消费,表测锁定(vitest fake timers 场景)。
|
||||
*/
|
||||
export const RECONNECT_DELAYS_MS = [5_000, 15_000, 60_000] as const;
|
||||
|
||||
/** @visibleForTesting 纯函数 —— 第 attempt 次(1-based)重试前的等待毫秒数 */
|
||||
export function nextRetryDelayMs(attempt: number): number {
|
||||
const idx = Math.min(Math.max(attempt, 1), RECONNECT_DELAYS_MS.length) - 1;
|
||||
return RECONNECT_DELAYS_MS[idx];
|
||||
}
|
||||
|
||||
export interface MCPServerConfig {
|
||||
id: string;
|
||||
@@ -261,6 +255,17 @@ class MCPToolAdapter implements IMetonaTool {
|
||||
|
||||
export class MCPManager {
|
||||
private servers = new Map<string, MCPServerState>();
|
||||
|
||||
// ===== v0.7.3 P4-2: 自动重连状态 =====
|
||||
/** 总开关(mcp.autoReconnect,默认 true;main.ts 启动时注入,配置变更联动) */
|
||||
private autoReconnect = true;
|
||||
/** 各 server 的重连定时器(disconnect/shutdown 时必须清理) */
|
||||
private reconnectTimers = new Map<string, NodeJS.Timeout>();
|
||||
/** 各 server 已尝试的自动重连次数(成功连接后清零) */
|
||||
private reconnectAttempts = new Map<string, number>();
|
||||
/** 待重连的配置快照(重连时从原配置重建连接,避免读 DB 中间态) */
|
||||
private reconnectConfigs = new Map<string, MCPServerConfig>();
|
||||
|
||||
/**
|
||||
* 工具集合变更回调(v0.5.3)
|
||||
*
|
||||
@@ -277,6 +282,93 @@ export class MCPManager {
|
||||
private toolRegistry: ToolRegistry,
|
||||
) {}
|
||||
|
||||
// ===== v0.7.3 P4-2: 自动重连 =====
|
||||
|
||||
/**
|
||||
* 设置自动重连开关(main.ts 启动时按 mcp.autoReconnect 注入;
|
||||
* 配置变更经 shared.ts applyConfigSideEffects 联动)。
|
||||
* 关闭时立即取消所有已排程的重连并清零计数(用户显式意图优先)。
|
||||
*/
|
||||
setAutoReconnect(enabled: boolean): void {
|
||||
this.autoReconnect = enabled;
|
||||
if (!enabled) {
|
||||
this.cancelAllReconnects();
|
||||
}
|
||||
log.debug(`[MCPManager] autoReconnect = ${enabled}`);
|
||||
}
|
||||
|
||||
/** 查询某 server 的重连状态(测试与诊断用) */
|
||||
getReconnectInfo(name: string): { attempts: number; scheduled: boolean } | null {
|
||||
const attempts = this.reconnectAttempts.get(name);
|
||||
const scheduled = this.reconnectTimers.has(name);
|
||||
if (attempts === undefined && !scheduled) return null;
|
||||
return { attempts: attempts ?? 0, scheduled };
|
||||
}
|
||||
|
||||
/** 取消某 server 的重连排程(用户显式断开/移除时调用) */
|
||||
private cancelReconnect(name: string): void {
|
||||
const timer = this.reconnectTimers.get(name);
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
this.reconnectTimers.delete(name);
|
||||
}
|
||||
this.reconnectAttempts.delete(name);
|
||||
this.reconnectConfigs.delete(name);
|
||||
}
|
||||
|
||||
/** 取消全部重连排程(shutdown / 开关关闭时调用) */
|
||||
private cancelAllReconnects(): void {
|
||||
for (const timer of this.reconnectTimers.values()) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
this.reconnectTimers.clear();
|
||||
this.reconnectAttempts.clear();
|
||||
this.reconnectConfigs.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接失败后排程指数退避重连(5s/15s/60s,最多 3 次)。
|
||||
* 状态机进入 'reconnecting'(设置页可见);重试耗尽停留 'error'。
|
||||
* 仅记住传入配置快照 —— 重连时按原配置重建,不读 DB 中间态。
|
||||
*/
|
||||
private scheduleReconnect(name: string, config: MCPServerConfig): void {
|
||||
if (!this.autoReconnect) return;
|
||||
|
||||
const attempts = (this.reconnectAttempts.get(name) ?? 0) + 1;
|
||||
if (attempts > MAX_RECONNECT_ATTEMPTS) {
|
||||
log.warn(
|
||||
`[MCPManager] "${name}" reconnect exhausted (${MAX_RECONNECT_ATTEMPTS} attempts) — staying in error state`,
|
||||
);
|
||||
this.reconnectAttempts.delete(name);
|
||||
this.reconnectConfigs.delete(name);
|
||||
return;
|
||||
}
|
||||
|
||||
this.reconnectAttempts.set(name, attempts);
|
||||
this.reconnectConfigs.set(name, config);
|
||||
const state = this.servers.get(name);
|
||||
if (state) state.status = 'reconnecting';
|
||||
|
||||
const delay = nextRetryDelayMs(attempts);
|
||||
log.info(
|
||||
`[MCPManager] "${name}" reconnect scheduled in ${delay / 1000}s (attempt ${attempts}/${MAX_RECONNECT_ATTEMPTS})`,
|
||||
);
|
||||
const timer = setTimeout(() => {
|
||||
this.reconnectTimers.delete(name);
|
||||
const snapshot = this.reconnectConfigs.get(name);
|
||||
if (!snapshot) return;
|
||||
log.info(
|
||||
`[MCPManager] "${name}" reconnecting (attempt ${attempts}/${MAX_RECONNECT_ATTEMPTS})`,
|
||||
);
|
||||
void this.connectServer(snapshot).catch(() => {
|
||||
/* connectServer 失败路径已自行 scheduleReconnect / 记录状态 */
|
||||
});
|
||||
}, delay);
|
||||
// 定时器不阻塞应用退出
|
||||
timer.unref?.();
|
||||
this.reconnectTimers.set(name, timer);
|
||||
}
|
||||
|
||||
/** 注册工具集合变更回调(main.ts 在 AgentEngineManager 创建后注入) */
|
||||
setOnToolsChanged(callback: () => void): void {
|
||||
this.toolsChangedCallback = callback;
|
||||
@@ -356,10 +448,9 @@ export class MCPManager {
|
||||
async connectServer(config: MCPServerConfig): Promise<void> {
|
||||
const { name } = config;
|
||||
|
||||
// 断开已有连接
|
||||
if (this.servers.has(name)) {
|
||||
await this.disconnectServer(name);
|
||||
}
|
||||
// 断开已有连接(内部拆除 —— 保留重连簿记,否则重试计数被清零、
|
||||
// 退避序列永远停在第 1 次;用户显式断开走 disconnectServer)
|
||||
await this.teardownConnection(name);
|
||||
|
||||
this.servers.set(name, {
|
||||
config,
|
||||
@@ -441,6 +532,15 @@ export class MCPManager {
|
||||
state.connectedAt = Date.now();
|
||||
state.error = undefined;
|
||||
|
||||
// v0.7.3 P4-2: 连接成功 —— 清零重连计数并取消排程
|
||||
this.reconnectAttempts.delete(name);
|
||||
this.reconnectConfigs.delete(name);
|
||||
const pendingTimer = this.reconnectTimers.get(name);
|
||||
if (pendingTimer) {
|
||||
clearTimeout(pendingTimer);
|
||||
this.reconnectTimers.delete(name);
|
||||
}
|
||||
|
||||
// 更新数据库
|
||||
const db = this.getDB();
|
||||
db.prepare(
|
||||
@@ -468,6 +568,9 @@ export class MCPManager {
|
||||
`,
|
||||
).run((error as Error).message, name);
|
||||
|
||||
// v0.7.3 P4-2: 失败后排程指数退避自动重连(开关关闭时 no-op)
|
||||
this.scheduleReconnect(name, config);
|
||||
|
||||
log.error(`MCP server "${name}" connection failed:`, error);
|
||||
throw error;
|
||||
}
|
||||
@@ -476,14 +579,15 @@ export class MCPManager {
|
||||
/**
|
||||
* 断开 MCP Server
|
||||
*/
|
||||
async disconnectServer(name: string): Promise<void> {
|
||||
/**
|
||||
* 内部连接拆除(保留重连簿记)—— connectServer 重连前的清理动作。
|
||||
* 与 disconnectServer 的区别:不清 reconnectAttempts/Timers/Configs,
|
||||
* 否则自动重连的每次重试都会把自己的计数清零(退避序列永远停在第 1 次)。
|
||||
*/
|
||||
private async teardownConnection(name: string): Promise<void> {
|
||||
const state = this.servers.get(name);
|
||||
if (!state) return;
|
||||
|
||||
// 从 ToolRegistry 注销
|
||||
this.toolRegistry.unregisterMCPTools(name);
|
||||
|
||||
// 关闭客户端
|
||||
if (state.client) {
|
||||
try {
|
||||
await state.client.close();
|
||||
@@ -491,13 +595,24 @@ export class MCPManager {
|
||||
// 忽略关闭错误
|
||||
}
|
||||
}
|
||||
|
||||
state.status = 'disconnected';
|
||||
state.client = null;
|
||||
state.tools = [];
|
||||
|
||||
// v0.5.3: 工具集合已变化 — 通知调用方同步引擎(已有引擎需移除失效工具定义)
|
||||
this.notifyToolsChanged();
|
||||
}
|
||||
|
||||
/**
|
||||
* 断开 MCP Server(用户显式语义:取消重连排程 + 拆除连接)
|
||||
*/
|
||||
async disconnectServer(name: string): Promise<void> {
|
||||
// v0.7.3 P4-2: 用户显式断开/移除 —— 取消重连排程(用户意图优先于自动重试)。
|
||||
// 无论是否存在连接态(error/reconnecting 态的 server 也可能被移除)都执行。
|
||||
this.cancelReconnect(name);
|
||||
await this.teardownConnection(name);
|
||||
|
||||
const state = this.servers.get(name);
|
||||
if (state) {
|
||||
state.status = 'disconnected';
|
||||
}
|
||||
|
||||
log.info(`MCP server "${name}" disconnected`);
|
||||
}
|
||||
@@ -601,12 +716,16 @@ export class MCPManager {
|
||||
status: MCPServerStatus;
|
||||
toolCount: number;
|
||||
error?: string;
|
||||
/** v0.7.3 P4-2: reconnecting 状态下的已尝试次数(第 N/3 次排程) */
|
||||
reconnectAttempt?: number;
|
||||
}> {
|
||||
return Array.from(this.servers.values()).map((s) => ({
|
||||
name: s.config.name,
|
||||
status: s.status,
|
||||
toolCount: s.tools.length,
|
||||
error: s.error,
|
||||
reconnectAttempt:
|
||||
s.status === 'reconnecting' ? this.reconnectAttempts.get(s.config.name) : undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -618,6 +737,7 @@ export class MCPManager {
|
||||
status: MCPServerStatus;
|
||||
toolCount: number;
|
||||
error?: string;
|
||||
reconnectAttempt?: number;
|
||||
} | null {
|
||||
const state = this.servers.get(name);
|
||||
if (!state) return null;
|
||||
@@ -626,6 +746,8 @@ export class MCPManager {
|
||||
status: state.status,
|
||||
toolCount: state.tools.length,
|
||||
error: state.error,
|
||||
reconnectAttempt:
|
||||
state.status === 'reconnecting' ? this.reconnectAttempts.get(state.config.name) : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -633,6 +755,8 @@ export class MCPManager {
|
||||
* 关闭所有连接
|
||||
*/
|
||||
async shutdown(): Promise<void> {
|
||||
// v0.7.3 P4-2: 退出前取消全部重连排程(timer 已 unref,此处幂等清理)
|
||||
this.cancelAllReconnects();
|
||||
const names = Array.from(this.servers.keys());
|
||||
await Promise.allSettled(names.map((n) => this.disconnectServer(n)));
|
||||
log.info('MCP Manager shut down');
|
||||
|
||||
Reference in New Issue
Block a user