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:
@@ -15,7 +15,10 @@ import type { IMetonaProviderAdapter, MetonaResponse, MetonaStreamEvent } from '
|
||||
import { MetonaStreamEventType } from '../../types';
|
||||
|
||||
/** 构造 Mock Adapter:sendStream 按脚本产出事件 */
|
||||
function createMockAdapter(scripts: MetonaStreamEvent[][], opts?: { failWith?: Error }): IMetonaProviderAdapter {
|
||||
function createMockAdapter(
|
||||
scripts: MetonaStreamEvent[][],
|
||||
opts?: { failWith?: Error },
|
||||
): IMetonaProviderAdapter {
|
||||
let call = 0;
|
||||
return {
|
||||
providerId: 'mock',
|
||||
@@ -23,12 +26,20 @@ function createMockAdapter(scripts: MetonaStreamEvent[][], opts?: { failWith?: E
|
||||
supportsToolCalling: true,
|
||||
supportsThinking: false,
|
||||
getContextWindow: () => 1_000_000,
|
||||
send: vi.fn(async (): Promise<MetonaResponse> => ({
|
||||
meta: { requestId: 'r_test', provider: 'mock', model: 'mock-model', latencyMs: 1, timestamp: Date.now() },
|
||||
content: 'ok',
|
||||
usage: { inputTokens: 10, outputTokens: 5, totalTokens: 15 },
|
||||
finishReason: 'stop' as never,
|
||||
})),
|
||||
send: vi.fn(
|
||||
async (): Promise<MetonaResponse> => ({
|
||||
meta: {
|
||||
requestId: 'r_test',
|
||||
provider: 'mock',
|
||||
model: 'mock-model',
|
||||
latencyMs: 1,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
content: 'ok',
|
||||
usage: { inputTokens: 10, outputTokens: 5, totalTokens: 15 },
|
||||
finishReason: 'stop' as never,
|
||||
}),
|
||||
),
|
||||
sendStream: vi.fn(async function* (): AsyncIterable<MetonaStreamEvent> {
|
||||
if (opts?.failWith) throw opts.failWith;
|
||||
const script = scripts[call % scripts.length];
|
||||
@@ -42,8 +53,23 @@ function createMockAdapter(scripts: MetonaStreamEvent[][], opts?: { failWith?: E
|
||||
|
||||
function textDoneEvent(text: string): MetonaStreamEvent[] {
|
||||
return [
|
||||
{ type: MetonaStreamEventType.TEXT_DELTA, requestId: 'r1', sessionId: 's1', iteration: 1, seq: 0, timestamp: Date.now(), delta: text },
|
||||
{ type: MetonaStreamEventType.DONE, requestId: 'r1', sessionId: 's1', iteration: 1, seq: 1, timestamp: Date.now() },
|
||||
{
|
||||
type: MetonaStreamEventType.TEXT_DELTA,
|
||||
requestId: 'r1',
|
||||
sessionId: 's1',
|
||||
iteration: 1,
|
||||
seq: 0,
|
||||
timestamp: Date.now(),
|
||||
delta: text,
|
||||
},
|
||||
{
|
||||
type: MetonaStreamEventType.DONE,
|
||||
requestId: 'r1',
|
||||
sessionId: 's1',
|
||||
iteration: 1,
|
||||
seq: 1,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
@@ -51,10 +77,21 @@ function toolCallEvent(name: string, args: Record<string, unknown>): MetonaStrea
|
||||
return [
|
||||
{
|
||||
type: MetonaStreamEventType.TOOL_CALL_COMPLETE,
|
||||
requestId: 'r1', sessionId: 's1', iteration: 1, seq: 0, timestamp: Date.now(),
|
||||
requestId: 'r1',
|
||||
sessionId: 's1',
|
||||
iteration: 1,
|
||||
seq: 0,
|
||||
timestamp: Date.now(),
|
||||
toolCall: { id: 'tc_test', name, args, iteration: 1, timestamp: Date.now() },
|
||||
},
|
||||
{ type: MetonaStreamEventType.DONE, requestId: 'r1', sessionId: 's1', iteration: 1, seq: 1, timestamp: Date.now() },
|
||||
{
|
||||
type: MetonaStreamEventType.DONE,
|
||||
requestId: 'r1',
|
||||
sessionId: 's1',
|
||||
iteration: 1,
|
||||
seq: 1,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
@@ -121,7 +158,9 @@ describe('AgentLoopEngine', () => {
|
||||
});
|
||||
|
||||
it('不可重试错误直接 ERROR(无 fallback 时)', async () => {
|
||||
const adapter = createMockAdapter([], { failWith: Object.assign(new Error('401 unauthorized'), { status: 401 }) });
|
||||
const adapter = createMockAdapter([], {
|
||||
failWith: Object.assign(new Error('401 unauthorized'), { status: 401 }),
|
||||
});
|
||||
const engine = new AgentLoopEngine({ retryCount: 0 }, adapter);
|
||||
const output = await engine.runStream(userMessage, 's1', [], systemPrompt);
|
||||
expect(output.terminationReason).toBe(TerminationReason.ERROR);
|
||||
@@ -129,7 +168,9 @@ describe('AgentLoopEngine', () => {
|
||||
|
||||
it('P1 故障转移:主 Provider 失败后切换到 fallback Provider', async () => {
|
||||
// 主 adapter 每次都失败(401 不可重试)
|
||||
const primary = createMockAdapter([], { failWith: Object.assign(new Error('401 invalid key'), { status: 401 }) });
|
||||
const primary = createMockAdapter([], {
|
||||
failWith: Object.assign(new Error('401 invalid key'), { status: 401 }),
|
||||
});
|
||||
// fallback 正常返回
|
||||
const fallback = createMockAdapter([textDoneEvent('fallback answer')]);
|
||||
|
||||
@@ -151,8 +192,12 @@ describe('AgentLoopEngine', () => {
|
||||
});
|
||||
|
||||
it('P1 故障转移仅触发一次(fallback 也失败不回切)', async () => {
|
||||
const primary = createMockAdapter([], { failWith: Object.assign(new Error('401'), { status: 401 }) });
|
||||
const fallback = createMockAdapter([], { failWith: Object.assign(new Error('500'), { status: 500 }) });
|
||||
const primary = createMockAdapter([], {
|
||||
failWith: Object.assign(new Error('401'), { status: 401 }),
|
||||
});
|
||||
const fallback = createMockAdapter([], {
|
||||
failWith: Object.assign(new Error('500'), { status: 500 }),
|
||||
});
|
||||
|
||||
const engine = new AgentLoopEngine({ retryCount: 0 }, primary);
|
||||
engine.setFallbackAdapter(fallback);
|
||||
@@ -162,3 +207,72 @@ describe('AgentLoopEngine', () => {
|
||||
expect(output.terminationReason).toBe(TerminationReason.ERROR);
|
||||
});
|
||||
});
|
||||
|
||||
// ===== v0.7.3 P4-4 / P3-1: 死循环乒乓检测 + REFLECTING 状态接线 =====
|
||||
|
||||
describe('AgentLoopEngine — 死循环乒乓检测(ABAB,P4-4)', () => {
|
||||
it('最近 4 轮 A→B→A→B 交替(A≠B)触发 DEAD_LOOP(驻留模式抓不住的乒乓)', async () => {
|
||||
const readScript = toolCallEvent('read_file', { file_path: 'x.ts' });
|
||||
const writeScript = toolCallEvent('write_file', { file_path: 'x.ts' });
|
||||
// 1:read 2:write 3:read 4:write ← 第 4 轮 PARSING 时滑窗构成 ABAB
|
||||
const adapter = createMockAdapter([readScript, writeScript, readScript, writeScript]);
|
||||
const engine = new AgentLoopEngine({ maxIterations: 6 }, adapter);
|
||||
const deadLoopEvents: unknown[] = [];
|
||||
engine.on('deadLoop', (d) => deadLoopEvents.push(d));
|
||||
|
||||
const output = await engine.runStream(userMessage, 's1', [], systemPrompt);
|
||||
expect(output.terminationReason).toBe(TerminationReason.DEAD_LOOP);
|
||||
expect(deadLoopEvents.length).toBe(1);
|
||||
});
|
||||
|
||||
it('A→B→C 交替(无重复模式)不误报,按 MAX_ITERATIONS 终止', async () => {
|
||||
const scripts = [
|
||||
toolCallEvent('read_file', { file_path: 'a.ts' }),
|
||||
toolCallEvent('write_file', { file_path: 'a.ts' }),
|
||||
toolCallEvent('lint_code', {}),
|
||||
];
|
||||
const adapter = createMockAdapter(scripts);
|
||||
const engine = new AgentLoopEngine({ maxIterations: 4 }, adapter);
|
||||
const output = await engine.runStream(userMessage, 's1', [], systemPrompt);
|
||||
expect(output.terminationReason).toBe(TerminationReason.MAX_ITERATIONS);
|
||||
});
|
||||
|
||||
it('A→B→B→B 前缀不构成 ABAB(A≠B 约束),由驻留模式在 3 连 B 时接管', async () => {
|
||||
const readScript = toolCallEvent('read_file', { file_path: 'x.ts' });
|
||||
const writeScript = toolCallEvent('write_file', { file_path: 'x.ts' });
|
||||
// 1:read 2:write 3:write 4:write —— 第 4 轮时 ABAB 不成立,但 3 连 write 命中驻留模式
|
||||
const adapter = createMockAdapter([readScript, writeScript, writeScript, writeScript]);
|
||||
const engine = new AgentLoopEngine({ maxIterations: 6 }, adapter);
|
||||
const output = await engine.runStream(userMessage, 's1', [], systemPrompt);
|
||||
expect(output.terminationReason).toBe(TerminationReason.DEAD_LOOP);
|
||||
});
|
||||
});
|
||||
|
||||
describe('AgentLoopEngine — REFLECTING 状态接线(P3-1 enableReflection)', () => {
|
||||
const collectStates = async (config: Record<string, unknown>): Promise<string[]> => {
|
||||
const adapter = createMockAdapter([
|
||||
toolCallEvent('read_file', { file_path: 'a.ts' }),
|
||||
textDoneEvent('done'),
|
||||
]);
|
||||
const engine = new AgentLoopEngine(config as never, adapter);
|
||||
const states: string[] = [];
|
||||
engine.on('stateChange', (d: { state?: string; current?: string }) => {
|
||||
const s = d.state ?? d.current ?? '';
|
||||
if (!states.includes(s)) states.push(s);
|
||||
});
|
||||
await engine.runStream(userMessage, 's1', [], systemPrompt);
|
||||
return states;
|
||||
};
|
||||
|
||||
it('enableReflection=true 时工具执行后进入 REFLECTING 状态', async () => {
|
||||
const states = await collectStates({ maxIterations: 2, enableReflection: true });
|
||||
expect(states).toContain('REFLECTING');
|
||||
expect(states).toContain('EXECUTING');
|
||||
expect(states).toContain('OBSERVING');
|
||||
});
|
||||
|
||||
it('enableReflection=false(默认)时不进入 REFLECTING', async () => {
|
||||
const states = await collectStates({ maxIterations: 2, enableReflection: false });
|
||||
expect(states).not.toContain('REFLECTING');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -50,7 +50,6 @@ class DeadLoopError extends Error {
|
||||
|
||||
const DEFAULT_CONFIG: AgentLoopConfig = {
|
||||
maxIterations: 20,
|
||||
timeoutMs: 120_000,
|
||||
totalTimeoutMs: 600_000,
|
||||
enableReflection: false,
|
||||
compressionThreshold: 0.8,
|
||||
@@ -563,7 +562,7 @@ export class AgentLoopEngine extends EventEmitter {
|
||||
});
|
||||
// 抛出特殊错误,主循环捕获后以 DEAD_LOOP 原因终止
|
||||
throw new DeadLoopError(
|
||||
`Detected a potential infinite loop: the same tool calls were repeated for 3 consecutive iterations. Please refine the approach or provide more specific instructions.`,
|
||||
`Detected a potential infinite loop: the same tool calls were repeated for 3 consecutive iterations, or two alternating call patterns kept cycling (A→B→A→B) without progress. Please refine the approach or provide more specific instructions.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -620,7 +619,11 @@ export class AgentLoopEngine extends EventEmitter {
|
||||
await this.transitionTo(AgentLoopState.OBSERVING);
|
||||
|
||||
// === v0.2.0: REFLECTING 状态 — 观察工具结果,决定是否继续 ===
|
||||
// 如果有工具调用且需要后续推理,进入 REFLECTING 状态
|
||||
// v0.7.3 接线说明:REFLECTING 分支此前依赖 enableReflection 配置,但该配置
|
||||
// 全链路无任何置 true 的路径(死配置)。现由 agent.enableReflection 配置
|
||||
// 真实驱动(main.ts baseConfig → updateConfigAll → 本分支),启用后每轮
|
||||
// 工具执行完毕会经过 REFLECTING 状态:工具结果存在失败时记录告警日志,
|
||||
// 供 SLO 与排障观察(不阻断循环——错误结果已由 CE-2 路径回传模型自愈)。
|
||||
if (this.config.enableReflection && step.toolCalls && step.toolCalls.length > 0) {
|
||||
await this.transitionTo(AgentLoopState.REFLECTING);
|
||||
// 检查工具执行是否有错误,如果有严重错误可以提前终止
|
||||
@@ -1087,9 +1090,13 @@ export class AgentLoopEngine extends EventEmitter {
|
||||
/**
|
||||
* v0.3.0: 死循环检测
|
||||
*
|
||||
* 检测策略:
|
||||
* 将每轮的工具调用序列化为签名字符串,检查最近3轮的签名是否完全相同。
|
||||
* 如果连续3轮使用完全相同的参数调用相同的工具,判定为死循环。
|
||||
* 检测策略(v0.7.3 起双模式):
|
||||
* 1. 驻留模式 — 将每轮的工具调用序列化为签名字符串,检查最近3轮的签名是否完全相同。
|
||||
* 如果连续3轮使用完全相同的参数调用相同的工具,判定为死循环。
|
||||
* 2. 乒乓模式(v0.7.3 新增)— 最近4轮构成 ABAB 交替(r1===r3 && r2===r4 && r1!==r2)。
|
||||
* 典型场景:模型在"读文件 A → 写文件 B"两步之间无限往返(每次读完又改回),
|
||||
* 单步签名各不相同,驻留模式永不命中;docs/Agentic-Loop详解.md 第五章将
|
||||
* "两种状态间反复来回切换、毫无进展"列为必须检测的停滞模式。
|
||||
*
|
||||
* v0.3.0 修复:
|
||||
* - 对 args 的键进行排序,避免 JSON.stringify 键顺序不一致导致漏报
|
||||
@@ -1123,21 +1130,31 @@ export class AgentLoopEngine extends EventEmitter {
|
||||
|
||||
this.toolCallHistory.push(signature);
|
||||
|
||||
// 只保留最近5轮的记录(足够检测3轮重复,同时避免内存增长)
|
||||
// 只保留最近5轮的记录(足够检测3轮重复与4轮乒乓,同时避免内存增长)
|
||||
if (this.toolCallHistory.length > 5) {
|
||||
this.toolCallHistory.shift();
|
||||
}
|
||||
|
||||
// 需要至少3轮数据才能检测
|
||||
if (this.toolCallHistory.length < 3) return false;
|
||||
|
||||
const len = this.toolCallHistory.length;
|
||||
const r1 = this.toolCallHistory[len - 1]; // 当前轮
|
||||
const r2 = this.toolCallHistory[len - 2]; // 上一轮
|
||||
const r3 = this.toolCallHistory[len - 3]; // 上上一轮
|
||||
|
||||
// 连续3轮完全相同 → 死循环
|
||||
return r1 === r2 && r2 === r3;
|
||||
// 模式 1:连续3轮完全相同 → 死循环
|
||||
if (len >= 3) {
|
||||
const r1 = this.toolCallHistory[len - 1]; // 当前轮
|
||||
const r2 = this.toolCallHistory[len - 2]; // 上一轮
|
||||
const r3 = this.toolCallHistory[len - 3]; // 上上一轮
|
||||
if (r1 === r2 && r2 === r3) return true;
|
||||
}
|
||||
|
||||
// 模式 2(v0.7.3):最近4轮 ABAB 交替(A≠B)→ 乒乓死循环
|
||||
if (len >= 4) {
|
||||
const a1 = this.toolCallHistory[len - 4];
|
||||
const b1 = this.toolCallHistory[len - 3];
|
||||
const a2 = this.toolCallHistory[len - 2];
|
||||
const b2 = this.toolCallHistory[len - 1];
|
||||
if (a1 === a2 && b1 === b2 && a1 !== b1) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -60,7 +60,6 @@ export interface TokenUsage {
|
||||
|
||||
export interface AgentLoopConfig {
|
||||
maxIterations: number;
|
||||
timeoutMs: number;
|
||||
totalTimeoutMs: number;
|
||||
enableReflection: boolean;
|
||||
compressionThreshold: number;
|
||||
|
||||
Reference in New Issue
Block a user