Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(agents): 补齐工具循环检测,避免正常日志轮询误停 (#4837)

Dash1b4ef81bb483
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts
index b8dc69be67..0aa555fd18 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts
@@ -15,6 +15,13 @@ import {
// 判定单测的核心是**白名单收紧**:自动重试一个确定性失败(认证过期、协议错)会反复
// 烧额度并反复报错,所以只有识别得了的"上游把 turn 打断了"才允许自愈。
describe('isInterruptedTurnError', () => {
+ it('never automatically resumes a detected tool loop, even with network-like text', () => {
+ expect(isInterruptedTurnError({
+ reason: 'tool_use_loop_detected', message: 'Request timed out',
+ toolLoop: { kind: 'rotation', count: 128 },
+ })).toBe(false);
+ expect(isAcceptedTurnContinuationOnlyReason('tool_use_loop_detected')).toBe(false);
+ });
it.each(['bridge_upstream_response_idle_timeout', 'bridge_turn_no_event_timeout'])(
'does not continue a bridge timeout before the user input has executed: %s', (reason) => {
expect(isInterruptedTurnError({ reason, message: 'request timed out' })).toBe(false);
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.md
index e902a1c664..ba506dc60a 100644
--- a/docs/dev-rules/maker-core-and-agent-behavior.md
+++ b/docs/dev-rules/maker-core-and-agent-behavior.md
@@ -11,6 +11,28 @@ Agent 会话的事件流与 prompt 组装中枢,这里的改动会在用户无
[`electron-security-and-process-boundaries.md`](electron-security-and-process-boundaries.md),
Orca 多 Agent 协同另见 [`orca-team-architecture.md`](orca-team-architecture.md)。
+## 工具循环与无响应的分工
+
+工具持续返回但反复原地搜索时,复用
+`agents/shared/loop-guard.ts` 的 `ToolLoopGuard`,不能靠缩短无事件超时处理。
+Claude Code 在原有 per-sidechain 回调里检测所有模型;Pi / Codex 在 `Session` 中配对
+当前产品轮次的 `tool_use` 与 `tool_result_full`,不重复统计结果摘要、后台事件或旧轮次。
+Pi / Codex 的归一事件尚无可靠模型响应批次标识,因此不启用“参数各不相同、同类契约
+错误连续被拒”的重试计数规则,避免把单批并行失败当成多次重试;重复调用检测仍保留。
+Claude Code 沿用既有按批次计数的契约错误规则。
+循环错误沿用 `tool_use_loop_detected` 和既有中断复核,Orca 消费普通终态链路;
+该 reason 不进入 interrupted-turn 自动续跑白名单,避免熔断后立即重复原循环。
+
+短窗口判据保持原样;较长的只读搜索轮转只在最近 128 次读/搜结果至多包含 32 种
+完整调用指纹,且至少 90% 的结果属于重复至少 4 次的指纹时判定。参数与输出都参与
+指纹,不修改实际工具结果;写入或命令结果打断该只读窗口,原生等待工具不计数。
+成功的简单 `tail` / PowerShell `Get-Content -Tail` 日志轮询同样不计数
+(只认字面 `.log` 路径,可串联多个日志读取);
+失败、混合执行、重定向或源文件读取不套用该例外。等待调用不清空普通调用的循环轨迹。
+这仍是有界启发式,不是任意长度循环的证明,也不以没有文件改动作为失败依据。
+回归见 `loop-guard.test.ts`、`session.tool-loop.test.ts` 和 Claude Code 的
+`upstream-idle-watchdog.test.ts`。
+
## 上下文已满时的引擎边界
Claude Code 在同一模型上达到设置页自动压缩阈值且尚未满窗时,由 host 注入 `/compact`;
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/upstream-idle-watchdog.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/upstream-idle-watchdog.test.ts
index 6294abc6cd..cd11ed6f7b 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/upstream-idle-watchdog.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/upstream-idle-watchdog.test.ts
@@ -495,19 +495,19 @@ describe('Claude Code tool-loop guard runtime integration', () => {
expect(result.interruptCalls).toBe(1);
});
- it('未确认的 provider-routed 模型不扩展自动硬中断范围', async () => {
+ it.each(['codex/gpt-5.5', 'google/gemini-3.8-flash', 'kimi/k2.8'])(
+ '%s provider-routed 模型同样检测工具循环', async (model) => {
const result = await runStableAbabLoop(
- await startSessionWithStream('codex/gpt-5.5'),
+ await startSessionWithStream(model),
'run a provider-routed investigation',
'toolu_provider_boundary',
);
- expect(result.loopError).toBeUndefined();
- expect(result.interruptCalls).toBe(0);
+ expect(result.loopError).toMatchObject({ data: { reason: 'tool_use_loop_detected', model } });
+ expect(result.interruptCalls).toBe(1);
});
- it('claude 会话下 provider-routed 模型 sidechain 的稳定 ABAB 循环不触发硬中断', async () => {
- // sidechain 流内消息报的是 SDK 原始 id(无 codex/ 前缀),guard 适用性按它判。
+ it('provider-routed sidechain 同样中断循环并保留真实模型归属', async () => {
const result = await runStableAbabLoop(
await startSessionWithStream('claude-opus-5'),
'delegate the investigation to a codex subagent',
@@ -515,8 +515,8 @@ describe('Claude Code tool-loop guard runtime integration', () => {
{ parentToolUseId: 'toolu_agent_codex', model: 'gpt-5.6-sol' },
);
- expect(result.loopError).toBeUndefined();
- expect(result.interruptCalls).toBe(0);
+ expect(result.loopError).toMatchObject({ data: { reason: 'tool_use_loop_detected', model: 'gpt-5.6-sol' } });
+ expect(result.interruptCalls).toBe(1);
});
it('provider-routed 会话下 claude 模型 sidechain 的稳定 ABAB 循环仍会中断', async () => {
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index f35425403c..9903cd7b0e 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -302,26 +302,6 @@ function isProviderRoutedModel(model: string): boolean {
return !model.startsWith('claude-');
}
-/**
- * 结果感知的硬中断目前覆盖 DeepSeek、原生 Claude 与 xai Grok 系列
- * (Grok 为 2026-08 维护者确认新增:单 turn 在 4 个不同 Grep 里轮转上千次调用的实锤)。
- * 其他 provider-routed 模型需要独立确认产品口径,不能因共用 Claude Code harness
- * 就自动扩大行为。会话级判断用 maker-core 公开 model id(deepseek/…、xai/…);
- * sidechain 的判断来自 SDK 流内的原始 id(可能是裸 deepseek-… / grok-… 形态,
- * 同 toSdkModelString 的双形态),因此按家族前缀匹配,不带 [1m] 的 SDK 改写。
- * grok 家族按 model-providers classification 口径同时认三种形态:xai/(订阅直连)、
- * x-ai/(网关命名空间,toSdkModelString 原样透传)与裸 grok-(sidechain 原始 id)。
- */
-function shouldUseToolLoopGuard(model: string): boolean {
- return (
- model.startsWith('deepseek')
- || model.startsWith('claude-')
- || model.startsWith('xai/')
- || model.startsWith('x-ai/')
- || model.startsWith('grok-')
- );
-}
-
/** URL → host(路由决策日志用,失败返回 undefined,不抛)。 */
function hostOfUrl(url: string | undefined): string | undefined {
if (!url) return undefined;
@@ -2597,14 +2577,12 @@ export class ClaudeCodeAgent extends BaseAgent {
return decision;
});
};
- // guard 桶常驻(每 turn 清空):适用性不再是会话级一票制,而是每个 scope 单独判。
+ // All models share the same detector, with independent per-sidechain history.
const toolLoopGuards = new Map<string | null, ToolLoopGuard>();
/**
- * guard 适用性判定用的模型:sidechain 用该 subagent 的实际模型
+ * 错误归属用的模型:sidechain 用该 subagent 的实际模型
* (Agent 异步回执的 resolvedModel 优先,其次 sidechain 流内消息的 model),
* 两者都未知时回落会话模型(维持旧行为);顶层恒用会话模型。
- * 否则 claude 会话下的 provider-routed subagent 会被越权硬中断,
- * provider-routed 会话下的 claude subagent 反而失去保护(PR #2779 review 指出)。
* runtimeState 声明在后,仅在 forward loop 回调期调用,无 TDZ 风险。
*/
const toolLoopGuardModelForScope = (parentToolUseId?: string): string => {
@@ -2616,8 +2594,7 @@ export class ClaudeCodeAgent extends BaseAgent {
}
return mutableModel;
};
- const getToolLoopGuard = (parentToolUseId?: string): ToolLoopGuard | null => {
- if (!shouldUseToolLoopGuard(toolLoopGuardModelForScope(parentToolUseId))) return null;
+ const getToolLoopGuard = (parentToolUseId?: string): ToolLoopGuard => {
const scopeKey = parentToolUseId ?? null;
let guard = toolLoopGuards.get(scopeKey);
if (!guard) {
@@ -6843,7 +6820,7 @@ export class ClaudeCodeAgent extends BaseAgent {
triggerAutoCompactIfNeeded();
}
}
- // 适用性在 getToolLoopGuard 里按已更新的 mutableModel 逐 scope 判,这里只清状态。
+ // A model change begins a fresh observation history in every scope.
resetToolLoopGuards();
if (exploreInheritCapNeedsRebuild && liveEnv && !opts.remoteHostId) {
applyExploreInheritCapEnv(liveEnv, sdkModel, 'replace');
diff --git a/packages/maker-core/src/agents/shared/loop-guard.test.ts b/packages/maker-core/src/agents/shared/loop-guard.test.ts
index 61b28b21b7..054fc1f73b 100644
--- a/packages/maker-core/src/agents/shared/loop-guard.test.ts
+++ b/packages/maker-core/src/agents/shared/loop-guard.test.ts
@@ -17,6 +17,135 @@ function feed(
}
describe('ToolLoopGuard', () => {
+ it.each([6, 20])('detects long stable read rotations with %i distinct calls', (distinct) => {
+ const guard = new ToolLoopGuard();
+ for (let i = 0; i < 128; i++) {
+ const position = i % distinct;
+ const verdict = feed(guard, String(i), 'grep', { pattern: `symbol-${position}` }, `file-${position}: match`);
+ expect(verdict.kind).toBe(i === 127 ? 'hard' : 'ok');
+ if (i === 127) expect(verdict).toMatchObject({ reason: 'rotation', count: 128 });
+ }
+ });
+
+ it('does not treat changed read results or intervening writes as a stable rotation', () => {
+ for (const mode of ['changing-output', 'write', 'new-input'] as const) {
+ const guard = new ToolLoopGuard();
+ for (let i = 0; i < 512; i++) {
+ if (mode === 'write' && i % 64 === 0) {
+ expect(feed(guard, `write-${i}`, 'edit', { file: `file-${i}` }, 'updated').kind).toBe('ok');
+ }
+ const input = { pattern: `symbol-${mode === 'new-input' ? i : i % 20}` };
+ const output = `match-${mode === 'changing-output' ? i : i % 20}`;
+ expect(feed(guard, `read-${i}`, 'grep', input, output).kind).toBe('ok');
+ }
+ }
+ });
+
+ it('detects a stale search cycle despite occasional output reordering', () => {
+ const guard = new ToolLoopGuard();
+ let verdict: ToolLoopGuardVerdict = { kind: 'ok' };
+ for (let i = 0; i < 128; i++) {
+ verdict = feed(guard, String(i), 'find', { pattern: `file-${i % 20}` },
+ i % 25 === 0 ? `reordered-${i}` : `match-${i % 20}`);
+ }
+ expect(verdict).toMatchObject({ kind: 'hard', reason: 'rotation', count: 128 });
+ });
+
+ it('does not interrupt investigations regularly discovering new inputs', () => {
+ const guard = new ToolLoopGuard();
+ for (let i = 0; i < 512; i++) {
+ const position = i % 8 === 0 ? `new-${i}` : `known-${i % 20}`;
+ expect(feed(guard, String(i), 'grep', { pattern: position }, position).kind).toBe('ok');
+ }
+ });
+
+ it.each(['write_stdin', 'wait', 'sleep', 'subagent'])('keeps %s polling out of loop fingerprints', (name) => {
+ const guard = new ToolLoopGuard();
+ for (let i = 0; i < 150; i++) {
+ expect(feed(guard, String(i), name, { action: 'status' }, 'running').kind).toBe('ok');
+ }
+ });
+
+ it('resets long read evidence on a new turn', () => {
+ const guard = new ToolLoopGuard();
+ for (let turn = 0; turn < 3; turn++) {
+ guard.resetTurn();
+ for (let i = 0; i < 100; i++) {
+ expect(feed(guard, `${turn}-${i}`, 'find', { pattern: `file-${i % 20}` }, `file-${i % 20}`).kind).toBe('ok');
+ }
+ }
+ });
+
+ it.each(['exec', 'Bash', 'bash'])('keeps successful log-tail polling alive through %s', (name) => {
+ const guard = new ToolLoopGuard();
+ const script = 'tail -8 /tmp/unit-gate.log; tail -5 /tmp/publish-gate.log';
+ // Sanitized shape from a completed quota-fix task waiting on the unit gate.
+ const command = name === 'exec' ? `/bin/zsh -lc '${script}'` : script;
+ for (let i = 0; i < 150; i++) {
+ expect(feed(guard, String(i), name, { command }, 'another unit gate is running').kind).toBe('ok');
+ }
+ });
+
+ it.each([
+ ['powershell', String.raw`Get-Content -Tail 8 C:\logs\gate.log`],
+ ['powershell', String.raw`Get-Content -LiteralPath 'C:\Build Logs\gate.log' -Tail 8`],
+ ['exec', String.raw`Get-Content -Tail 8 -Path C:\logs\gate.log; Get-Content C:\logs\other.log -Tail 5`],
+ ['exec', String.raw`C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command "Get-Content -Tail 8 C:\logs\gate.log"`],
+ ['exec', String.raw`"C:\Program Files\PowerShell\7\pwsh.exe" -Command "get-content -literalpath C:\logs\gate.log -tail 8"`],
+ ])('keeps Windows log polling alive through %s', (name, command) => {
+ const guard = new ToolLoopGuard();
+ for (let i = 0; i < 150; i++) {
+ expect(feed(guard, String(i), name, { command }, 'waiting for test gate').kind).toBe('ok');
+ }
+ });
+
+ it.each([
+ String.raw`Get-Content C:\src\source.ts -Tail 8`,
+ String.raw`Get-Content C:\logs\gate.log`,
+ String.raw`Get-Content C:\logs\gate.log -Tail 8; npm test`,
+ String.raw`Get-Content C:\logs\gate.log -Tail 8 > C:\logs\out.log`,
+ String.raw`Get-Content "$env:TEMP\gate.log" -Tail 8`,
+ String.raw`Get-Content C:\logs\gate.log -Tail 8 | Select-String failed`,
+ ])('does not exempt ambiguous or mixed PowerShell: %s', (command) => {
+ const guard = new ToolLoopGuard();
+ let verdict: ToolLoopGuardVerdict = { kind: 'ok' };
+ for (let i = 0; i < 4; i++) verdict = feed(guard, String(i), 'powershell', { command }, 'unchanged');
+ expect(verdict.kind).toBe('hard');
+ });
+
+ it('keeps failing PowerShell log reads in the repeat detector', () => {
+ const guard = new ToolLoopGuard();
+ let verdict: ToolLoopGuardVerdict = { kind: 'ok' };
+ for (let i = 0; i < 4; i++) verdict = feed(guard, String(i), 'powershell',
+ { command: String.raw`Get-Content C:\logs\gate.log -Tail 8` }, 'file not found', true);
+ expect(verdict.kind).toBe('hard');
+ });
+
+ it.each([
+ 'tail -8 source.ts',
+ 'tail -8 /tmp/gate.log; npm test',
+ 'tail -8 /tmp/gate.log > /tmp/output.log',
+ 'tail -8 $(pwd)/gate.log',
+ 'tail -8 /tmp/gate.log | grep failed',
+ ])('does not exempt an ambiguous or mixed shell command: %s', (command) => {
+ const guard = new ToolLoopGuard();
+ let verdict: ToolLoopGuardVerdict = { kind: 'ok' };
+ for (let i = 0; i < 4; i++) verdict = feed(guard, String(i), 'exec', { command }, 'unchanged');
+ expect(verdict.kind).toBe('hard');
+ });
+
+ it('does not exempt failing log polls or erase ordinary loops between successful polls', () => {
+ const failed = new ToolLoopGuard();
+ const ordinary = new ToolLoopGuard();
+ for (let i = 0; i < 4; i++) {
+ const failure = feed(failed, String(i), 'bash', { command: 'tail -8 /tmp/gate.log' }, 'not found', true);
+ const read = feed(ordinary, `read-${i}`, 'read', { path: 'source.ts' }, 'same source');
+ expect(failure.kind).toBe(i === 3 ? 'hard' : 'ok');
+ expect(read.kind).toBe(i === 3 ? 'hard' : 'ok');
+ expect(feed(ordinary, `poll-${i}`, 'exec', { command: 'tail -8 /tmp/gate.log' }, 'waiting').kind).toBe('ok');
+ }
+ });
+
// ── 第 1 层: 连续 name+input+output 完全相同 ──────────────────────────────
it('在连续完全相同达到阈值时判 consecutive', () => {
const g = new ToolLoopGuard(); // consecutiveLimit 默认 4
diff --git a/packages/maker-core/src/agents/shared/loop-guard.ts b/packages/maker-core/src/agents/shared/loop-guard.ts
index dc062327a5..c277f74901 100644
--- a/packages/maker-core/src/agents/shared/loop-guard.ts
+++ b/packages/maker-core/src/agents/shared/loop-guard.ts
@@ -1,8 +1,9 @@
import { createHash, type Hash } from 'node:crypto';
+import { normalizeDisplayCommand } from '@cindy/maker-shared/command-display';
/**
- * 第 1 层(快路径,零误判):连续多少次 name+input+output 完全一字不差,判死循环。
- * output 也参与, 所以只会抓"同工具同参数同输出"的机械重复, 轮询(输出在变)不会误判。
+ * 第 1 层(快路径):连续多少次 name+input+output 完全一字不差,判疑似循环。
+ * 稳定输出本身不能证明死循环,已知等待/轮询形态在下方排除。
*/
const DEFAULT_CONSECUTIVE_LIMIT = 4;
/**
@@ -25,6 +26,15 @@ const DEFAULT_WINDOW_DISTINCT_LIMIT = 2;
const DEFAULT_ROTATION_WINDOW_SIZE = 16;
/** 第 3 层:轮转窗口填满后, distinct 指纹数 ≤ 此值即判循环。 */
const DEFAULT_ROTATION_DISTINCT_LIMIT = 4;
+// Wider investigations need stronger evidence than the short input-only window:
+// 128 completed reads, at most 32 exact name/input/output fingerprints, with
+// >=90% of results in fingerprints seen at least four times. A write/command
+// breaks this observation. The small tolerance admits occasional reordered
+// search output, not a steadily expanding investigation.
+const STABLE_READ_WINDOW_SIZE = 128;
+const STABLE_READ_DISTINCT_LIMIT = 32;
+const STABLE_READ_MIN_REPEATS = 4;
+const READ_ONLY_TOOL_NAMES = new Set(['Read', 'Grep', 'Glob', 'read', 'grep', 'find', 'ls']);
/**
* 第 4 层(契约错误):同一工具连续多少次因**同类参数契约错误**被拒即止损。
* 与 1-3 层互补:那三层按 name+input 指纹抓"重复同一调用",而 malformed 参数每次
@@ -109,7 +119,38 @@ export function classifyToolContractError(
* 不能作为模型死循环证据。它本身不进入指纹,但也不重置普通工具的轨迹,
* 避免模型通过在重复调用间插入轮询来绕过检测。
*/
-const LOOP_GUARD_EXEMPT_TOOL_NAMES = new Set(['TaskOutput']);
+const LOOP_GUARD_EXEMPT_TOOL_NAMES = new Set([
+ 'TaskOutput', 'write_stdin', 'wait', 'sleep',
+ // Codex translator retains the namespace of host dynamic tools.
+ 'dynamic:functions:write_stdin', 'dynamic:functions:wait',
+ 'dynamic:clock:sleep', 'mcp:clock:sleep',
+]);
+
+function isPollingTool(name: string, input: unknown, isError: boolean): boolean {
+ if (LOOP_GUARD_EXEMPT_TOOL_NAMES.has(name)) return true;
+ if (!input || typeof input !== 'object') return false;
+ const record = input as Record<string, unknown>;
+ if (!isError && (name === 'exec' || name === 'Bash' || name === 'bash' || name === 'powershell')) {
+ const command = record.command ?? record.cmd;
+ if (typeof command === 'string') {
+ // Reuse shell-wrapper recognition; this is a polling hint, not permission
+ // analysis. Only simple tail/Get-Content reads of literal .log paths are exempt.
+ // Mixed commands, substitutions, redirects and source-file reads remain
+ // ordinary observations. A failed tail is not evidence of healthy waiting.
+ const script = normalizeDisplayCommand(command) ?? command;
+ const logPath = String.raw`(?:[A-Za-z0-9_./:@%+=,-]+\.log|'[A-Za-z0-9_./ :@%+=,-]+\.log'|"[A-Za-z0-9_./ :@%+=,-]+\.log")`;
+ const tail = new RegExp(String.raw`^(?:/usr/bin/|/bin/)?tail\s+(?:(?:-\d+|-n\s+\d+)\s+)?${logPath}(?:\s+${logPath})*\s*$`);
+ const windowsLogPath = String.raw`(?:[A-Za-z0-9_./\\:@%+=-]+\.log|'[A-Za-z0-9_./\\ :@%+=-]+\.log'|"[A-Za-z0-9_./\\ :@%+=-]+\.log")`;
+ const target = String.raw`(?:(?:-Path|-LiteralPath)\s+)?${windowsLogPath}`;
+ const getContent = new RegExp(String.raw`^Get-Content\s+(?:-Tail\s+\d+\s+${target}|${target}\s+-Tail\s+\d+)\s*$`, 'i');
+ if (script.split(/;|&&/).every(part => tail.test(part.trim()) || getContent.test(part.trim()))) return true;
+ }
+ }
+ // Pi's native subagent status/list calls observe separately running work.
+ if (name !== 'subagent') return false;
+ const action = record.action;
+ return action === 'status' || action === 'list';
+}
interface PendingToolUse {
name: string;
@@ -157,9 +198,9 @@ export type ToolLoopGuardVerdict =
* Result-aware tool loop detector(四层防御)。
*
* 只在非轮询工具结果返回后判断。任一层命中即返回 hard, 由调用方决定如何中断:
- * 1. 连续完全相同(name+input+output)—— 快路径, 零误判;
+ * 1. 连续完全相同(name+input+output)—— 快路径;
* 2. name+input 滑动窗口多样性坍缩 —— 抓 ABAB 交替 / output 易变的重复;
- * 3. 更长窗口的轮转检测 —— 抓 3-4 个调用的 ABCD 轮转(第 2 层 distinct 上限盖不住);
+ * 3. 轮转检测 —— 短窗口抓 3-4 个调用;长窗口只接受反复相同的只读结果;
* 4. 同工具同类契约错误连续被拒 —— 抓 input 各不相同、指纹层抓不到的 malformed 重试。
*
* 不按调用总数或任意长度的重复序列硬中断:仅凭工具 trace 无法区分合法批处理、
@@ -183,6 +224,7 @@ export class ToolLoopGuard {
// 第 2/3 层共用状态: 最近 max(windowSize, rotationWindowSize) 个 name+input 指纹
private callWindow: string[] = [];
+ private stableReadWindow: string[] = [];
// 第 4 层无批次兼容状态: 最近一次契约错误的 name+类别键与连续计数
private lastContractKey: string | null = null;
@@ -229,7 +271,7 @@ export class ToolLoopGuard {
const toolUse = this.pendingToolUses.get(toolUseId);
this.pendingToolUses.delete(toolUseId);
if (!toolUse) return { kind: 'ok' };
- if (LOOP_GUARD_EXEMPT_TOOL_NAMES.has(toolUse.name)) return { kind: 'ok' };
+ if (isPollingTool(toolUse.name, toolUse.input, isError)) return { kind: 'ok' };
// 第 4 层: 同工具同类契约错误连续出现(input 各不相同也计)。放在 1-3 层之前:
// 它的阈值(3)低于第 1 层(4),同 input 的重复契约错误也应更早止损。
@@ -285,6 +327,24 @@ export class ToolLoopGuard {
// 第 1 层: 连续 name+input+output 完全相同
const fullFingerprint = fingerprintToolCall(toolUse.name, toolUse.input, output);
+ if (READ_ONLY_TOOL_NAMES.has(toolUse.name)) {
+ this.stableReadWindow.push(fullFingerprint);
+ if (this.stableReadWindow.length > STABLE_READ_WINDOW_SIZE) this.stableReadWindow.shift();
+ if (this.stableReadWindow.length === STABLE_READ_WINDOW_SIZE) {
+ const counts = new Map<string, number>();
+ for (const fingerprint of this.stableReadWindow) {
+ counts.set(fingerprint, (counts.get(fingerprint) ?? 0) + 1);
+ }
+ const repeated = [...counts.values()].reduce((sum, count) =>
+ sum + (count >= STABLE_READ_MIN_REPEATS ? count : 0), 0);
+ if (counts.size <= STABLE_READ_DISTINCT_LIMIT &&
+ repeated >= Math.ceil(STABLE_READ_WINDOW_SIZE * 0.9)) {
+ return { kind: 'hard', reason: 'rotation', count: STABLE_READ_WINDOW_SIZE, toolName: toolUse.name };
+ }
+ }
+ } else {
+ this.stableReadWindow = [];
+ }
if (fullFingerprint === this.lastFullFingerprint) {
this.consecutiveStreak += 1;
} else {
@@ -347,6 +407,7 @@ export class ToolLoopGuard {
this.lastFullFingerprint = null;
this.consecutiveStreak = 0;
this.callWindow = [];
+ this.stableReadWindow = [];
this.lastContractKey = null;
this.contractStreak = 0;
this.resetContractBatchState();
diff --git a/packages/maker-core/src/session.tool-loop.test.ts b/packages/maker-core/src/session.tool-loop.test.ts
new file mode 100644
index 0000000000..1b17651da1
--- /dev/null
+++ b/packages/maker-core/src/session.tool-loop.test.ts
@@ -0,0 +1,208 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { Session, MANUAL_ABORT_RECOVERY_GRACE_MS } from './session.js';
+import { createAsyncQueue } from './agents/shared/async-queue.js';
+import { createPiTranslateContext, translatePiEvent } from './agents/pi/translator.js';
+import type { AgentSessionHandle } from './agents/base-agent.js';
+import type { AgentEvent, InteractionDecision } from './types/events.js';
+import type { Logger } from './interfaces/logger.js';
+
+const sessions: Session[] = [];
+afterEach(async () => {
+ for (const session of sessions.splice(0)) await session.close();
+ vi.useRealTimers();
+});
+
+function setup(agentKind: 'pi' | 'codex', hangAbort = false) {
+ vi.useFakeTimers();
+ const queue = createAsyncQueue<AgentEvent>();
+ let running = false;
+ const handle = {
+ id: 'native-session', agentKind, model: 'test-model',
+ events: () => queue,
+ send: vi.fn(async () => { running = true; }),
+ abort: vi.fn(async () => {
+ if (hangAbort) return new Promise<void>(() => {});
+ running = false;
+ queue.push({ type: 'done', data: {}, source: agentKind });
+ }),
+ close: vi.fn(async () => { running = false; queue.end(); }),
+ isTurnRunning: () => running,
+ setInteractionResolver() {},
+ } as unknown as AgentSessionHandle;
+ const logger: Logger = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child() { return logger; } };
+ const session = new Session({ id: 'test-session', agentKind, handle, workDir: '/test', capabilities: {} as never, logger });
+ sessions.push(session);
+ const seen: AgentEvent[] = [];
+ session.onEvent((event) => seen.push(event));
+ const tool = async (id: string, extra: Partial<AgentEvent> = {}, name = 'read', input: unknown = { path: 'same.ts' }) => {
+ queue.push({ type: 'tool_use', data: { toolUseId: id, toolName: name, input }, source: agentKind, ...extra });
+ queue.push({ type: 'tool_result_full', data: { toolUseId: id, fullText: 'same result' }, source: agentKind, ...extra });
+ queue.push({ type: 'tool_result', data: { toolUseIds: [id], summary: 'done' }, source: agentKind, ...extra });
+ await vi.advanceTimersByTimeAsync(0);
+ };
+ const errors = () => seen.filter((event) => event.type === 'error');
+ return { queue, session, seen, handle, tool, errors, end: async () => {
+ running = false;
+ queue.push({ type: 'done', data: {}, source: agentKind });
+ await vi.advanceTimersByTimeAsync(0);
+ } };
+}
+
+describe.each(['pi', 'codex'] as const)('%s Session tool loop coverage', (agentKind) => {
+ it('does not interpret one parallel batch of distinct contract failures as retries', async () => {
+ const t = setup(agentKind);
+ await t.session.send('investigate');
+ for (let i = 0; i < 5; i++) t.queue.push({ type: 'tool_use', source: agentKind, data: {
+ toolUseId: `invalid-${i}`, toolName: 'Edit', input: { old_string: `old-${i}`, new_string: `new-${i}` },
+ } });
+ for (const i of [2, 0, 4, 1, 3]) t.queue.push({ type: 'tool_result_full', source: agentKind, data: {
+ toolUseId: `invalid-${i}`, fullText: 'InputValidationError: Missing required parameter file_path', isError: true,
+ } });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(t.errors()).toHaveLength(0);
+ expect(t.handle.abort).not.toHaveBeenCalled();
+ // Conservative contract handling must not disable unchanged read loops.
+ for (let i = 0; i < 4; i++) await t.tool(`read-${i}`);
+ expect(t.errors()).toHaveLength(1);
+ });
+
+ it('detects exec/MCP calls using translated names', async () => {
+ const t = setup(agentKind);
+ await t.session.send('investigate');
+ for (let i = 0; i < 12; i++) {
+ await t.tool(String(i), {}, i % 2 ? 'mcp:search:lookup' : 'exec', { query: 'unchanged' });
+ }
+ expect(t.errors()).toHaveLength(1);
+ expect(t.errors()[0]).toMatchObject({ data: { toolLoop: { kind: 'pingpong', count: 12 } } });
+ });
+
+ it('preserves full results, emits one terminal error with origin, and permits a fresh turn', async () => {
+ const t = setup(agentKind);
+ await t.session.send('investigate', { origin: { kind: 'scheduler', scheduleId: 'schedule-1' } });
+ for (let i = 0; i < 3; i++) await t.tool(String(i));
+ expect(t.errors()).toHaveLength(0);
+ await t.tool('3');
+ expect(t.errors()).toHaveLength(1);
+ expect(t.errors()[0]).toMatchObject({ source: agentKind, turnOrigin: { kind: 'scheduler', scheduleId: 'schedule-1' }, data: {
+ reason: 'tool_use_loop_detected', isTerminal: true, toolLoop: { kind: 'consecutive', count: 4 },
+ } });
+ const errorIndex = t.seen.indexOf(t.errors()[0]);
+ expect(t.seen.slice(0, errorIndex).filter(e => e.type === 'tool_result_full')).toHaveLength(4);
+ expect(t.seen.slice(0, errorIndex).filter(e => e.type === 'tool_result')).toHaveLength(4);
+ expect(t.seen.slice(errorIndex).filter(e => e.type === 'tool_result')).toHaveLength(0);
+ expect(t.handle.abort).toHaveBeenCalledOnce();
+ expect(t.session.getObservedCurrentTurnTerminal().kind).toBe('error');
+ await t.session.send('try a different approach');
+ for (let i = 0; i < 3; i++) await t.tool(`new-${i}`);
+ expect(t.errors()).toHaveLength(1);
+ });
+
+ it.each([false, true])('waits for the matching summary and discards pending verdict on takeover=%s', async (takeover) => {
+ const t = setup(agentKind);
+ await t.session.send('first');
+ const generation = t.session.getTurnGeneration();
+ for (let i = 0; i < 3; i++) await t.tool(String(i));
+ t.queue.push({ type: 'tool_use', source: agentKind, data: { toolUseId: 'last', toolName: 'read', input: { path: 'same.ts' } } });
+ t.queue.push({ type: 'tool_result_full', source: agentKind, data: { toolUseId: 'last', fullText: 'same result' } });
+ t.queue.push({ type: 'tool_result', source: agentKind, data: { toolUseIds: ['unrelated'], summary: 'done' } });
+ t.queue.push({ type: 'tool_result', source: agentKind, turnScope: 'background', data: { toolUseIds: ['last'], summary: 'done' } });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(t.errors()).toHaveLength(0);
+ expect(t.handle.abort).not.toHaveBeenCalled();
+ if (takeover) {
+ await t.end();
+ await t.session.send('second');
+ }
+ t.queue.push({ type: 'tool_result', source: agentKind, sessionTurnGeneration: generation, data: { toolUseIds: ['last'], summary: 'done' } });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(t.errors()).toHaveLength(takeover ? 0 : 1);
+ expect(t.handle.abort).toHaveBeenCalledTimes(takeover ? 0 : 1);
+ if (takeover) {
+ for (let i = 0; i < 4; i++) await t.tool(`new-${i}`);
+ expect(t.errors()).toHaveLength(1);
+ }
+ });
+
+ it('does not count background, old-generation, foreign-instance or duplicate results', async () => {
+ const t = setup(agentKind);
+ await t.session.send('first');
+ const oldGeneration = t.session.getTurnGeneration();
+ await t.end();
+ await t.session.send('second');
+ for (let i = 0; i < 10; i++) {
+ await t.tool(`bg-${i}`, { turnScope: 'background' });
+ await t.tool(`old-${i}`, { sessionTurnGeneration: oldGeneration });
+ await t.tool(`foreign-${i}`, { sessionInstanceId: 'other-instance' });
+ }
+ await t.tool('current');
+ for (let i = 0; i < 10; i++) t.queue.push({ type: 'tool_result_full', data: { toolUseId: 'current', fullText: 'same result' }, source: agentKind });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(t.errors()).toHaveLength(0);
+ expect(t.handle.abort).not.toHaveBeenCalled();
+ });
+
+ it('keeps polling and changing arguments alive', async () => {
+ const t = setup(agentKind);
+ await t.session.send('wait and investigate');
+ for (let i = 0; i < 140; i++) {
+ await t.tool(`poll-${i}`, {}, agentKind === 'codex' ? 'dynamic:functions:write_stdin' : 'write_stdin', { session_id: 12 });
+ await t.tool(`read-${i}`, {}, 'read', { path: `file-${i}.ts` });
+ }
+ expect(t.errors()).toHaveLength(0);
+ });
+
+ it('ignores snapshots and pauses detection while waiting for a person', async () => {
+ const t = setup(agentKind);
+ await t.session.send('investigate');
+ for (let i = 0; i < 8; i++) {
+ t.queue.push({ type: 'tool_use', source: agentKind, data: {
+ toolUseId: `snapshot-${i}`, toolName: 'read', input: {}, runtimeActivity: 'snapshot',
+ } });
+ t.queue.push({ type: 'tool_result_full', source: agentKind, data: {
+ toolUseId: `snapshot-${i}`, fullText: 'same result', runtimeActivity: 'snapshot',
+ } });
+ }
+ let answer!: (decision: InteractionDecision) => void;
+ const pending = t.session.runHostInteraction({
+ kind: 'permission', requestId: 'approval', toolName: 'read', input: {},
+ }, () => new Promise((resolve) => { answer = resolve; }));
+ for (let i = 0; i < 8; i++) await t.tool(`waiting-${i}`);
+ expect(t.errors()).toHaveLength(0);
+ answer({ kind: 'permission', behavior: 'allow' });
+ await pending;
+ for (let i = 0; i < 4; i++) await t.tool(`resumed-${i}`);
+ expect(t.errors()).toHaveLength(1);
+ });
+
+ it('uses existing abort recovery when interrupt never settles', async () => {
+ const t = setup(agentKind, true);
+ await t.session.send('investigate');
+ for (let i = 0; i < 4; i++) await t.tool(String(i));
+ expect(t.errors()).toHaveLength(1);
+ // A paired terminal drains the short error timer but cannot cancel the
+ // independent abort confirmation fallback.
+ t.queue.push({ type: 'done', data: {}, source: agentKind });
+ await vi.advanceTimersByTimeAsync(MANUAL_ABORT_RECOVERY_GRACE_MS + 1);
+ expect(t.handle.close).toHaveBeenCalledOnce();
+ expect(t.session.getStatus()).toBe('closed');
+ });
+});
+
+it('pairs real Pi translator tool events without changing their results', async () => {
+ const t = setup('pi');
+ const logger: Logger = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child() { return logger; } };
+ const context = createPiTranslateContext(logger);
+ await t.session.send('investigate');
+ translatePiEvent({ type: 'agent_start' }, t.queue, context);
+ for (let i = 0; i < 4; i++) {
+ translatePiEvent({ type: 'tool_execution_start', toolCallId: String(i), toolName: 'grep', args: { pattern: 'same' } }, t.queue, context);
+ translatePiEvent({ type: 'tool_execution_end', toolCallId: String(i), toolName: 'grep', result: { content: [{ type: 'text', text: 'file.ts: unchanged' }] }, isError: false }, t.queue, context);
+ await vi.advanceTimersByTimeAsync(0);
+ }
+ expect(t.errors()).toHaveLength(1);
+ expect(t.handle.abort).toHaveBeenCalledOnce();
+ expect(t.seen.slice(0, t.seen.indexOf(t.errors()[0])).filter(e => e.type === 'tool_result')).toHaveLength(4);
+ expect(t.seen.filter(e => e.type === 'tool_result_full').map(e => e.data)).toEqual(
+ Array.from({ length: 4 }, (_, i) => ({ toolUseId: String(i), fullText: 'file.ts: unchanged', isError: false })),
+ );
+});
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index 3da3105591..85b0fecd9e 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -12,6 +12,7 @@
import type { AutoReviewUserIntent } from './agents/shared/auto-review-decision.js';
import { randomUUID } from 'node:crypto';
+import { ToolLoopGuard } from './agents/shared/loop-guard.js';
import type { ReviewableAction } from './agents/shared/auto-review.js';
import type { AutoReviewDecision } from './agents/shared/auto-review-decision.js';
@@ -361,6 +362,8 @@ export type SessionGracefulStopResult =
type TurnControlState = {
generation: number;
+ toolLoopGuard: ToolLoopGuard | null;
+ pendingToolLoop: { toolUseId: string; verdict: Extract<ReturnType<ToolLoopGuard['onToolResult']>, { kind: 'hard' }> } | null;
activeToolIds: Set<string>;
anonymousActiveTools: number;
pendingInteractionToolIds: Map<string, number>;
@@ -2151,6 +2154,16 @@ export class Session {
private beginTurnControl(generation: number): void {
this.turnControlState = {
generation,
+ // Claude owns per-sidechain guards before translation. Pi/Codex share
+ // the same detector here, paired with this product turn's lifecycle.
+ toolLoopGuard: this.agentKind === 'claude-code' ? null : new ToolLoopGuard({
+ // These normalized events do not identify model-response batches.
+ // Distinct malformed calls can belong to one parallel attempt, so do
+ // not enable the retry-count rule without that evidence. Claude keeps
+ // its existing batch-aware contract rule; repetition rules stay active.
+ contractConsecutiveLimit: Number.POSITIVE_INFINITY,
+ }),
+ pendingToolLoop: null,
activeToolIds: new Set(),
anonymousActiveTools: 0,
pendingInteractionToolIds: new Map(),
@@ -2731,6 +2744,59 @@ export class Session {
} else if (isCurrentGeneration && isTurnWatchdogLivenessEvent(event)) {
this.armTurnStallWatchdog();
}
+ // Deliver the completed tool result before the loop error; never discard
+ // evidence or count both full and summary projections of the same result.
+ if (isCurrentGeneration) this.observeToolLoop(event, resolvedGeneration);
+ }
+
+ private observeToolLoop(event: AgentEvent, generation: number): void {
+ if (event.type !== 'tool_use' && event.type !== 'tool_result_full' && event.type !== 'tool_result') return;
+ const control = this.turnControlState;
+ if (!control?.toolLoopGuard || control.generation !== generation ||
+ generation !== this.turnGeneration || this.status !== 'active' || this.closePromise ||
+ event.turnScope === 'background' || event.sessionInstanceId !== this.instanceId ||
+ this.pendingInteractions > 0 || control.gracefulStopState !== 'none') return;
+ const data = event.data && typeof event.data === 'object'
+ ? event.data as Record<string, unknown> : {};
+ if (data.runtimeActivity === 'snapshot') return;
+ if (event.type === 'tool_result') {
+ const pending = control.pendingToolLoop;
+ if (!pending || !Array.isArray(data.toolUseIds) || !data.toolUseIds.includes(pending.toolUseId)) return;
+ control.pendingToolLoop = null;
+ this.interruptToolLoop(pending.verdict, generation);
+ return;
+ }
+ if (typeof data.toolUseId !== 'string' || control.pendingToolLoop) return;
+ if (event.type === 'tool_use') {
+ control.toolLoopGuard.onToolUse(data.toolUseId, data.toolName, data.input);
+ return;
+ }
+ if (event.type !== 'tool_result_full' || typeof data.fullText !== 'string') return;
+ const verdict = control.toolLoopGuard.onToolResult(data.toolUseId, data.fullText, data.isError === true);
+ if (verdict.kind !== 'hard') return;
+ // Both translators enqueue full text before its summary. Let listeners
+ // consume both projections before terminal cleanup clears their pairing.
+ // This belongs to TurnControlState so termination/takeover discards it.
+ control.pendingToolLoop = { toolUseId: data.toolUseId, verdict };
+ }
+
+ private interruptToolLoop(verdict: Extract<ReturnType<ToolLoopGuard['onToolResult']>, { kind: 'hard' }>, generation: number): void {
+ this.fanOutEvent({
+ type: 'error',
+ data: {
+ message: `Repeated tool calls (${verdict.count}) indicate a tool loop; this turn was interrupted. You can send the next message to continue.`,
+ isTerminal: true,
+ reason: 'tool_use_loop_detected',
+ toolLoop: { kind: verdict.reason, count: verdict.count },
+ },
+ source: this.agentKind,
+ });
+ // A listener can synchronously take over. Never interrupt its replacement.
+ if (generation !== this.turnGeneration) return;
+ // abort() already owns confirmation/rebuild fallback; no second watchdog.
+ void this.abort().catch((error) => {
+ this.logger.warn('tool loop interrupt failed', { error: String(error) });
+ });
}
private clearTurnStallWatchdog(refresh = false): void {