Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(maker-core): guard grok tool loops and short rotations (#2808)
Lizid2fb52817612
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.tsindex c5bd682f04..6294abc6cd 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@@ -541,6 +541,124 @@ describe('Claude Code tool-loop guard runtime integration', () => {expect(result.interruptCalls).toBe(1);});+ it('xai/grok 会话下 4 个不同 Grep 的 ABCD 轮转在第 16 个结果处中断', async () => {+ const { handle, stream, events, fakeQuery, collected } = await startSessionWithStream(+ 'xai/grok-4.5',+ );++ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });+ try {+ await handle.send({ type: 'user', content: 'find the missing implementation' });++ const greps = [+ 'grep -R "planA" packages',+ 'grep -R "planB" packages',+ 'grep -R "planC" packages',+ 'grep -R "planD" packages',+ ];+ for (let i = 0; i < 16; i += 1) {+ const id = `toolu_grok_rotation_${i}`;+ stream.emit(assistantToolUse(id, greps[i % 4]));+ stream.emit(userToolResult(id, `no result ${i}`));+ }++ await pumpUntil(+ () => events.filter((event) => event.type === 'tool_result_full').length === 16,+ 'grok rotation tool results processed',+ );+ await vi.advanceTimersByTimeAsync(1);++ expect(toolLoopError(events)).toMatchObject({+ type: 'error',+ data: {+ reason: 'tool_use_loop_detected',+ loopKind: 'rotation',+ loopCount: 16,+ model: 'xai/grok-4.5',+ isTerminal: true,+ },+ source: 'claude-code',+ });+ expect(fakeQuery.interrupt).toHaveBeenCalledTimes(1);+ } finally {+ vi.useRealTimers();+ stream.end();+ await handle.close().catch(() => undefined);+ await collected;+ }+ });++ it('x-ai/grok 网关形态会话下 4 个不同 Grep 的 ABCD 轮转同样会被中断', async () => {+ // x-ai/ 是网关侧 grok 命名空间(classification.ts 与 xai/ 分开登记),+ // toSdkModelString 原样透传,顶层会话模型即该形态 —— 不得漏出 guard 覆盖。+ const { handle, stream, events, fakeQuery, collected } = await startSessionWithStream(+ 'x-ai/grok-4.6',+ );++ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });+ try {+ await handle.send({ type: 'user', content: 'find the missing implementation' });++ const greps = [+ 'grep -R "planA" packages',+ 'grep -R "planB" packages',+ 'grep -R "planC" packages',+ 'grep -R "planD" packages',+ ];+ for (let i = 0; i < 16; i += 1) {+ const id = `toolu_gateway_grok_rotation_${i}`;+ stream.emit(assistantToolUse(id, greps[i % 4]));+ stream.emit(userToolResult(id, `no result ${i}`));+ }++ await pumpUntil(+ () => events.filter((event) => event.type === 'tool_result_full').length === 16,+ 'gateway grok rotation tool results processed',+ );+ await vi.advanceTimersByTimeAsync(1);++ expect(toolLoopError(events)).toMatchObject({+ type: 'error',+ data: {+ reason: 'tool_use_loop_detected',+ loopKind: 'rotation',+ loopCount: 16,+ model: 'x-ai/grok-4.6',+ isTerminal: true,+ },+ source: 'claude-code',+ });+ expect(fakeQuery.interrupt).toHaveBeenCalledTimes(1);+ } finally {+ vi.useRealTimers();+ stream.end();+ await handle.close().catch(() => undefined);+ await collected;+ }+ });++ it('claude 会话下裸 id 形态的 grok sidechain 同样受 guard 保护', async () => {+ const result = await runStableAbabLoop(+ await startSessionWithStream('claude-opus-5'),+ 'delegate the investigation to a grok subagent',+ 'toolu_grok_sidechain',+ { parentToolUseId: 'toolu_agent_grok', model: 'grok-4.5' },+ );++ expect(result.loopError).toMatchObject({+ type: 'error',+ data: {+ reason: 'tool_use_loop_detected',+ loopKind: 'pingpong',+ loopCount: 12,+ model: 'grok-4.5',+ isTerminal: true,+ },+ source: 'claude-code',+ });+ expect(result.interruptCalls).toBe(1);+ });+it('deepseek 会话下裸 id 形态的 deepseek sidechain 仍受 guard 保护', async () => {// 流内原始 id 是 deepseek-v4-flash(无 deepseek/ 前缀),家族前缀匹配不得漏判。const result = await runStableAbabLoop(@@ -564,7 +682,7 @@ describe('Claude Code tool-loop guard runtime integration', () => {expect(result.interruptCalls).toBe(1);});- it.each(['deepseek/deepseek-v4-flash', 'claude-opus-5'])(+ it.each(['deepseek/deepseek-v4-flash', 'claude-opus-5', 'xai/grok-4.5'])('%s 真实 SDK 事件流中的 150 次不同调用与空结果可以完成同一个 turn',async (model) => {const { handle, stream, events, fakeQuery, collected } = await startSessionWithStream(model);@@ -590,7 +708,7 @@ describe('Claude Code tool-loop guard runtime integration', () => {},);- it.each(['deepseek/deepseek-v4-flash', 'claude-opus-5'])(+ it.each(['deepseek/deepseek-v4-flash', 'claude-opus-5', 'xai/grok-4.5'])('%s 真实 SDK 事件流中的稳定 TaskOutput 轮询不会中断 turn',async (model) => {const { handle, stream, events, fakeQuery, collected } = await startSessionWithStream(model);diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex e49ac23f0c..34dad0e59d 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -241,14 +241,23 @@ function isProviderRoutedModel(model: string): boolean {}/**- * 结果感知的硬中断目前只覆盖既有 DeepSeek 与原生 Claude 系列。+ * 结果感知的硬中断目前覆盖 DeepSeek、原生 Claude 与 xai Grok 系列+ * (Grok 为 2026-08 维护者确认新增:单 turn 在 4 个不同 Grep 里轮转上千次调用的实锤)。* 其他 provider-routed 模型需要独立确认产品口径,不能因共用 Claude Code harness- * 就自动扩大行为。会话级判断用 maker-core 公开 model id(deepseek/…);sidechain 的- * 判断来自 SDK 流内的原始 id(可能是裸 deepseek-… 形态,同 toSdkModelString 的双形态),- * 因此 DeepSeek 按家族前缀匹配,不带 [1m] 的 SDK 改写。+ * 就自动扩大行为。会话级判断用 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-');+ return (+ model.startsWith('deepseek')+ || model.startsWith('claude-')+ || model.startsWith('xai/')+ || model.startsWith('x-ai/')+ || model.startsWith('grok-')+ );}/** URL → host(路由决策日志用,失败返回 undefined,不抛)。 */diff --git a/packages/maker-core/src/agents/shared/loop-guard.test.ts b/packages/maker-core/src/agents/shared/loop-guard.test.tsindex d1f6664c3a..4dd447e475 100644--- a/packages/maker-core/src/agents/shared/loop-guard.test.ts+++ b/packages/maker-core/src/agents/shared/loop-guard.test.ts@@ -62,6 +62,42 @@ describe('ToolLoopGuard', () => {}});+ // ── 第 3 层: 长窗口轮转(ABCD…) ───────────────────────────────────────────+ it('4 个不同调用轮转(ABCDABCD…)在轮转窗口填满时判 rotation(对应 grok 4-Grep 实锤)', () => {+ const g = new ToolLoopGuard(); // rotationWindowSize 16, rotationDistinct<=4+ const cmds = ['grep -R a', 'grep -R b', 'grep -R c', 'grep -R d'];+ for (let i = 0; i < 16; i += 1) {+ const v = feed(g, `id${i}`, 'Grep', { pattern: cmds[i % 4] }, `hits-${i}`);+ if (i < 15) expect(v.kind).toBe('ok');+ else expect(v).toMatchObject({ kind: 'hard', reason: 'rotation', count: 16, toolName: 'Grep' });+ }+ });++ it('3 个不同调用轮转同样被 rotation 层捕获', () => {+ const g = new ToolLoopGuard();+ for (let i = 0; i < 16; i += 1) {+ const v = feed(g, `id${i}`, 'Bash', { cmd: `check-${i % 3}` }, `o${i}`);+ if (i < 15) expect(v.kind).toBe('ok');+ else expect(v).toMatchObject({ kind: 'hard', reason: 'rotation' });+ }+ });++ it('5 个不同调用轮转不判 rotation(distinct 超过上限,留给更长证据)', () => {+ const g = new ToolLoopGuard();+ for (let i = 0; i < 40; i += 1) {+ expect(feed(g, `id${i}`, 'Bash', { cmd: `probe-${i % 5}` }, `o${i}`).kind).toBe('ok');+ }+ });++ it('轮转中途出现新调用会把窗口 distinct 顶出上限,不误判', () => {+ const g = new ToolLoopGuard();+ for (let i = 0; i < 48; i += 1) {+ // 每 8 次插入一个全新 input:任何 16 连续窗口 distinct ≥ 5+ const input = i % 8 === 7 ? { cmd: `novel-${i}` } : { cmd: `fix-${i % 4}` };+ expect(feed(g, `id${i}`, 'Bash', input, `o${i}`).kind).toBe('ok');+ }+ });+// ── 合法长 turn / 原生轮询工具 ───────────────────────────────────────────it('TaskOutput 状态长期不变仍放行,不会被通用重复判据中断', () => {const g = new ToolLoopGuard();diff --git a/packages/maker-core/src/agents/shared/loop-guard.ts b/packages/maker-core/src/agents/shared/loop-guard.tsindex e76f72eec7..addf5ebb04 100644--- a/packages/maker-core/src/agents/shared/loop-guard.ts+++ b/packages/maker-core/src/agents/shared/loop-guard.ts@@ -15,6 +15,16 @@ const DEFAULT_CONSECUTIVE_LIMIT = 4;const DEFAULT_WINDOW_SIZE = 12;/** 第 2 层:窗口填满后, distinct 指纹数 ≤ 此值即判循环(2 = 一直在 ≤2 种调用里转)。 */const DEFAULT_WINDOW_DISTINCT_LIMIT = 2;+/**+ * 第 3 层(轮转):更长窗口 + 更宽 distinct 上限,抓第 2 层漏掉的 3-4 个调用+ * 轮转(ABCDABCD…)。实锤:xai/grok 单 turn 在 4 个不同 Grep 里轮转一千多次+ * 调用(2026-08),distinct=4 > 2 从第 2 层漏网。16/4 = 每种指纹平均重复 4 次+ * 才判,比直接把第 2 层 distinct 提到 4 的误判面小;连续 16 次调用零新指纹+ * 的合法工作流(纯读排查也会穿插不同参数)实践中几乎不存在。+ */+const DEFAULT_ROTATION_WINDOW_SIZE = 16;+/** 第 3 层:轮转窗口填满后, distinct 指纹数 ≤ 此值即判循环。 */+const DEFAULT_ROTATION_DISTINCT_LIMIT = 4;/*** TaskOutput 是 SDK 明确定义的等待/轮询工具。状态文本不变只代表任务仍在等待,* 不能作为模型死循环证据。它本身不进入指纹,但也不重置普通工具的轨迹,@@ -34,21 +44,26 @@ export interface ToolLoopGuardOptions {windowSize?: number;/** 第 2 层:窗口内 distinct 指纹 ≤ 此值判循环。 */windowDistinctLimit?: number;+ /** 第 3 层:轮转检测的滑动窗口大小。 */+ rotationWindowSize?: number;+ /** 第 3 层:轮转窗口内 distinct 指纹 ≤ 此值判循环。 */+ rotationDistinctLimit?: number;}-/** 命中哪一层判据。consecutive=机械重复 / pingpong=短循环。 */-export type ToolLoopReason = 'consecutive' | 'pingpong';+/** 命中哪一层判据。consecutive=机械重复 / pingpong=短循环 / rotation=3-4 调用轮转。 */+export type ToolLoopReason = 'consecutive' | 'pingpong' | 'rotation';export type ToolLoopGuardVerdict =| { kind: 'ok' }| { kind: 'hard'; reason: ToolLoopReason; count: number; toolName: string };/**- * Result-aware tool loop detector(两层防御)。+ * Result-aware tool loop detector(三层防御)。** 只在非轮询工具结果返回后判断。任一层命中即返回 hard, 由调用方决定如何中断:* 1. 连续完全相同(name+input+output)—— 快路径, 零误判;* 2. name+input 滑动窗口多样性坍缩 —— 抓 ABAB 交替 / output 易变的重复;+ * 3. 更长窗口的轮转检测 —— 抓 3-4 个调用的 ABCD 轮转(第 2 层 distinct 上限盖不住)。** 不按调用总数或任意长度的重复序列硬中断:仅凭工具 trace 无法区分合法批处理、* 稳定状态轮询与死循环,有限窗口也只能移动误判/漏判边界。@@ -59,6 +74,8 @@ export class ToolLoopGuard {readonly consecutiveLimit: number;readonly windowSize: number;readonly windowDistinctLimit: number;+ readonly rotationWindowSize: number;+ readonly rotationDistinctLimit: number;private pendingToolUses = new Map<string, PendingToolUse>();@@ -66,13 +83,15 @@ export class ToolLoopGuard {private lastFullFingerprint: string | null = null;private consecutiveStreak = 0;- // 第 2 层状态: 最近 windowSize 个 name+input 指纹+ // 第 2/3 层共用状态: 最近 max(windowSize, rotationWindowSize) 个 name+input 指纹private callWindow: string[] = [];constructor(options: ToolLoopGuardOptions = {}) {this.consecutiveLimit = options.consecutiveLimit ?? DEFAULT_CONSECUTIVE_LIMIT;this.windowSize = options.windowSize ?? DEFAULT_WINDOW_SIZE;this.windowDistinctLimit = options.windowDistinctLimit ?? DEFAULT_WINDOW_DISTINCT_LIMIT;+ this.rotationWindowSize = options.rotationWindowSize ?? DEFAULT_ROTATION_WINDOW_SIZE;+ this.rotationDistinctLimit = options.rotationDistinctLimit ?? DEFAULT_ROTATION_DISTINCT_LIMIT;}/**@@ -112,17 +131,35 @@ export class ToolLoopGuard {};}- // 第 2 层: name+input 滑动窗口多样性坍缩(指纹不含 output)+ // 第 2/3 层: name+input 滑动窗口多样性坍缩(指纹不含 output)const callFingerprint = fingerprintToolCall(toolUse.name, toolUse.input, null);this.callWindow.push(callFingerprint);- if (this.callWindow.length > this.windowSize) this.callWindow.shift();+ const bufferSize = Math.max(this.windowSize, this.rotationWindowSize);+ if (this.callWindow.length > bufferSize) this.callWindow.shift();++ // 第 2 层: 短窗口 ping-pong(≤2 种调用来回打转)if (this.callWindow.length >= this.windowSize) {- const distinct = new Set(this.callWindow).size;+ const recent = this.callWindow.slice(-this.windowSize);+ const distinct = new Set(recent).size;if (distinct <= this.windowDistinctLimit) {return {kind: 'hard',reason: 'pingpong',- count: this.callWindow.length,+ count: recent.length,+ toolName: toolUse.name,+ };+ }+ }++ // 第 3 层: 长窗口轮转(3-4 种调用 ABCD 轮转,第 2 层 distinct 上限盖不住)+ if (this.callWindow.length >= this.rotationWindowSize) {+ const recent = this.callWindow.slice(-this.rotationWindowSize);+ const distinct = new Set(recent).size;+ if (distinct <= this.rotationDistinctLimit) {+ return {+ kind: 'hard',+ reason: 'rotation',+ count: recent.length,toolName: toolUse.name,};}