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(maker-core): 移除 DeepSeek 单轮工具调用硬上限 (#1238)

Dash04e20018ecb0
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 2aa5296132..92711f2232 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
@@ -141,7 +141,7 @@ async function makeTempDir(): Promise<string> {
return dir;
}
-async function startSessionWithStream() {
+async function startSessionWithStream(model = 'claude-opus-4-6') {
const configDir = await makeTempDir();
process.env.CLAUDE_CONFIG_DIR = configDir;
const workingDir = await makeTempDir();
@@ -163,7 +163,7 @@ async function startSessionWithStream() {
const agent = new ClaudeCodeAgent(createDeps());
const handle = await agent.startSession({
sessionId: 'session-idle-watchdog',
- model: 'claude-opus-4-6',
+ model,
workingDir,
permissionMode: 'acceptEdits',
});
@@ -190,22 +190,39 @@ function successResult(): Record<string, unknown> {
};
}
-function assistantToolUse(id: string): Record<string, unknown> {
+function assistantToolUse(id: string, command = 'sleep 999'): Record<string, unknown> {
return {
type: 'assistant',
message: {
role: 'assistant',
- content: [{ type: 'tool_use', id, name: 'Bash', input: { command: 'sleep 999' } }],
+ content: [{ type: 'tool_use', id, name: 'Bash', input: { command } }],
},
};
}
-function userToolResult(id: string): Record<string, unknown> {
+function assistantTaskOutput(id: string): Record<string, unknown> {
+ return {
+ type: 'assistant',
+ message: {
+ role: 'assistant',
+ content: [
+ {
+ type: 'tool_use',
+ id,
+ name: 'TaskOutput',
+ input: { task_id: 'task-1', block: true, timeout: 30_000 },
+ },
+ ],
+ },
+ };
+}
+
+function userToolResult(id: string, content = 'done'): Record<string, unknown> {
return {
type: 'user',
message: {
role: 'user',
- content: [{ type: 'tool_result', tool_use_id: id, content: 'done' }],
+ content: [{ type: 'tool_result', tool_use_id: id, content }],
},
};
}
@@ -227,6 +244,14 @@ function idleTimeoutError(events: AgentEvent[]): AgentEvent | undefined {
);
}
+function toolLoopError(events: AgentEvent[]): AgentEvent | undefined {
+ return events.find(
+ (e) =>
+ e.type === 'error' &&
+ (e.data as Record<string, unknown> | undefined)?.reason === 'tool_use_loop_detected',
+ );
+}
+
afterEach(async () => {
vi.useRealTimers();
sdkMock.forkSession.mockReset();
@@ -324,3 +349,53 @@ describe('upstream-response-idle watchdog suspend awareness', () => {
await handle.close().catch(() => undefined);
});
});
+
+describe('DeepSeek tool-loop guard runtime integration', () => {
+ it('真实 SDK 事件流中的 150 次不同调用与空结果可以完成同一个 turn', async () => {
+ const { handle, stream, events, fakeQuery } = await startSessionWithStream(
+ 'deepseek/deepseek-v4-flash',
+ );
+
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });
+ await handle.send({ type: 'user', content: 'analyze 150 different projects' });
+
+ for (let i = 0; i < 150; i += 1) {
+ const id = `toolu_project_${i}`;
+ stream.emit(assistantToolUse(id, `read-project-${i}`));
+ stream.emit(userToolResult(id, ''));
+ }
+ stream.emit(successResult());
+
+ await pumpUntil(() => handle.isTurnRunning?.() === false, 'long DeepSeek turn done');
+ expect(toolLoopError(events)).toBeUndefined();
+ expect(fakeQuery.interrupt).not.toHaveBeenCalled();
+
+ vi.useRealTimers();
+ stream.end();
+ await handle.close().catch(() => undefined);
+ });
+
+ it('真实 SDK 事件流中的稳定 TaskOutput 轮询不会中断 turn', async () => {
+ const { handle, stream, events, fakeQuery } = await startSessionWithStream(
+ 'deepseek/deepseek-v4-flash',
+ );
+
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });
+ await handle.send({ type: 'user', content: 'wait for the background task' });
+
+ for (let i = 0; i < 30; i += 1) {
+ const id = `toolu_task_output_${i}`;
+ stream.emit(assistantTaskOutput(id));
+ stream.emit(userToolResult(id, 'still running'));
+ }
+ stream.emit(successResult());
+
+ await pumpUntil(() => handle.isTurnRunning?.() === false, 'TaskOutput polling turn done');
+ expect(toolLoopError(events)).toBeUndefined();
+ expect(fakeQuery.interrupt).not.toHaveBeenCalled();
+
+ vi.useRealTimers();
+ stream.end();
+ await handle.close().catch(() => undefined);
+ });
+});
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index fbe5b40cb4..07b4446d18 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -2864,12 +2864,9 @@ export class ClaudeCodeAgent extends BaseAgent {
if (turnInFlight) {
const verdict = toolLoopGuard?.onToolResult(id, output);
if (verdict?.kind === 'hard') {
- const loopHint =
- verdict.reason === 'consecutive'
- ? `连续 ${verdict.count} 次发起完全相同的 ${verdict.toolName} 调用`
- : verdict.reason === 'pingpong'
- ? `最近 ${verdict.count} 次工具调用一直在极少数几种(含 ${verdict.toolName})之间反复打转`
- : `单轮已累计 ${verdict.count} 次工具调用仍未收敛`;
+ const loopHint = verdict.reason === 'consecutive'
+ ? `连续 ${verdict.count} 次发起完全相同的 ${verdict.toolName} 调用`
+ : `最近 ${verdict.count} 次工具调用一直在极少数几种(含 ${verdict.toolName})之间反复打转`;
// 与 upstream-idle watchdog 同款兜底: tool-loop 中断 = "整个 turn 序列已死",
// bridge counter 归零避免 filter 吞掉本条 error / counter 永久停在 >0。
// 实践上 bridge /compact turn 不用 tool, 该分支难以触发, 归零是防御性一致。
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 dd0a978460..d1f6664c3a 100644
--- a/packages/maker-core/src/agents/shared/loop-guard.test.ts
+++ b/packages/maker-core/src/agents/shared/loop-guard.test.ts
@@ -62,25 +62,95 @@ describe('ToolLoopGuard', () => {
}
});
- it('每次调用都不同(合法长任务)不误判', () => {
+ // ── 合法长 turn / 原生轮询工具 ───────────────────────────────────────────
+ it('TaskOutput 状态长期不变仍放行,不会被通用重复判据中断', () => {
const g = new ToolLoopGuard();
- for (let i = 0; i < 30; i += 1) {
- expect(feed(g, `id${i}`, 'Read', { file: `f${i}.ts` }, 'content').kind).toBe('ok');
+ for (let i = 0; i < 250; i += 1) {
+ expect(
+ feed(
+ g,
+ `id${i}`,
+ 'TaskOutput',
+ { task_id: 'task-1', block: true, timeout: 30_000 },
+ 'still running',
+ ).kind,
+ ).toBe('ok');
}
});
- // ── 第 3 层: 单 turn tool result 硬上限 ───────────────────────────────────
- it('在 turn 内调用总数超硬上限时判 turn-cap(任何形态兜底)', () => {
- // 放宽前两层, 只验证兜底: 每次 input 都不同, 不会触发 consecutive / pingpong
- const g = new ToolLoopGuard({ turnHardCap: 5, windowSize: 1000, consecutiveLimit: 1000 });
- for (let i = 0; i < 5; i += 1) {
- expect(feed(g, `id${i}`, 'Read', { file: `f${i}` }, `o${i}`).kind).toBe('ok');
+ it('TaskOutput 不会隐藏穿插在轮询之间的连续普通工具循环', () => {
+ const g = new ToolLoopGuard();
+ for (let i = 0; i < 4; i += 1) {
+ const ordinary = feed(g, `bash-${i}`, 'Bash', { cmd: 'ls' }, 'same');
+ if (i < 3) expect(ordinary.kind).toBe('ok');
+ else expect(ordinary).toMatchObject({ kind: 'hard', reason: 'consecutive' });
+
+ expect(
+ feed(
+ g,
+ `poll-${i}`,
+ 'TaskOutput',
+ { task_id: 'task-1', block: true, timeout: 30_000 },
+ 'still running',
+ ).kind,
+ ).toBe('ok');
+ }
+ });
+
+ it('TaskOutput 不会隐藏穿插在轮询之间的 ABAB 普通工具循环', () => {
+ const g = new ToolLoopGuard();
+ for (let i = 0; i < 12; i += 1) {
+ const ordinary = feed(
+ g,
+ `ordinary-${i}`,
+ 'Bash',
+ i % 2 === 0 ? { cmd: 'python run.py' } : { cmd: 'p4 sync' },
+ `output-${i}`,
+ );
+ if (i < 11) expect(ordinary.kind).toBe('ok');
+ else expect(ordinary).toMatchObject({ kind: 'hard', reason: 'pingpong' });
+
+ expect(
+ feed(
+ g,
+ `poll-${i}`,
+ 'TaskOutput',
+ { task_id: 'task-1', block: true, timeout: 30_000 },
+ 'still running',
+ ).kind,
+ ).toBe('ok');
+ }
+ });
+
+ it('三十三项固定序列不会被有限窗口冒充为通用硬上限', () => {
+ const g = new ToolLoopGuard();
+ for (let i = 0; i < 198; i += 1) {
+ const position = i % 33;
+ expect(
+ feed(
+ g,
+ `id${i}`,
+ 'Read',
+ { file: `project-${position}.json` },
+ `stable-${position}`,
+ ).kind,
+ ).toBe('ok');
+ }
+ });
+
+ it('参数持续变化时即使结果高度重复也不判 hard', () => {
+ const g = new ToolLoopGuard();
+ for (let i = 0; i < 250; i += 1) {
+ expect(feed(g, `id${i}`, 'Read', { file: `missing-${i}.ts` }, 'not found').kind).toBe('ok');
+ }
+ });
+
+ it('参数持续变化且结果为空或纯空白时也不判 hard', () => {
+ const g = new ToolLoopGuard();
+ for (let i = 0; i < 250; i += 1) {
+ const output = i % 2 === 0 ? '' : ' ';
+ expect(feed(g, `id${i}`, 'Write', { file: `f${i}.ts` }, output).kind).toBe('ok');
}
- expect(feed(g, 'id5', 'Read', { file: 'f5' }, 'o5')).toMatchObject({
- kind: 'hard',
- reason: 'turn-cap',
- count: 6,
- });
});
// ── 配对 / 放行 ───────────────────────────────────────────────────────────
diff --git a/packages/maker-core/src/agents/shared/loop-guard.ts b/packages/maker-core/src/agents/shared/loop-guard.ts
index 49156c306d..e76f72eec7 100644
--- a/packages/maker-core/src/agents/shared/loop-guard.ts
+++ b/packages/maker-core/src/agents/shared/loop-guard.ts
@@ -16,11 +16,11 @@ const DEFAULT_WINDOW_SIZE = 12;
/** 第 2 层:窗口填满后, distinct 指纹数 ≤ 此值即判循环(2 = 一直在 ≤2 种调用里转)。 */
const DEFAULT_WINDOW_DISTINCT_LIMIT = 2;
/**
- * 第 3 层(兜底):单个 user turn 内 tool result 总数硬上限。
- * 不做任何指纹判断, 对一切循环形态有效, 纯粹防止烧爆 context / token。
- * 设得高, 正常复杂任务一个 turn 调几十个工具很常见, 这里只兜"绝不可能是正常行为"。
+ * TaskOutput 是 SDK 明确定义的等待/轮询工具。状态文本不变只代表任务仍在等待,
+ * 不能作为模型死循环证据。它本身不进入指纹,但也不重置普通工具的轨迹,
+ * 避免模型通过在重复调用间插入轮询来绕过检测。
*/
-const DEFAULT_TURN_HARD_CAP = 100;
+const LOOP_GUARD_EXEMPT_TOOL_NAMES = new Set(['TaskOutput']);
interface PendingToolUse {
name: string;
@@ -34,24 +34,24 @@ export interface ToolLoopGuardOptions {
windowSize?: number;
/** 第 2 层:窗口内 distinct 指纹 ≤ 此值判循环。 */
windowDistinctLimit?: number;
- /** 第 3 层:单 turn tool result 总数硬上限。 */
- turnHardCap?: number;
}
-/** 命中哪一层判据。consecutive=机械重复 / pingpong=交替或输出易变的重复 / turn-cap=硬上限兜底。 */
-export type ToolLoopReason = 'consecutive' | 'pingpong' | 'turn-cap';
+/** 命中哪一层判据。consecutive=机械重复 / pingpong=短循环。 */
+export type ToolLoopReason = 'consecutive' | 'pingpong';
export type ToolLoopGuardVerdict =
| { kind: 'ok' }
| { kind: 'hard'; reason: ToolLoopReason; count: number; toolName: string };
/**
- * Result-aware tool loop detector(三层防御)。
+ * Result-aware tool loop detector(两层防御)。
*
- * 只在工具结果返回后计数。三层任一命中即返回 hard, 由调用方决定如何中断:
+ * 只在非轮询工具结果返回后判断。任一层命中即返回 hard, 由调用方决定如何中断:
* 1. 连续完全相同(name+input+output)—— 快路径, 零误判;
* 2. name+input 滑动窗口多样性坍缩 —— 抓 ABAB 交替 / output 易变的重复;
- * 3. 单 turn tool result 硬上限 —— 兜一切形态。
+ *
+ * 不按调用总数或任意长度的重复序列硬中断:仅凭工具 trace 无法区分合法批处理、
+ * 稳定状态轮询与死循环,有限窗口也只能移动误判/漏判边界。
*
* 类本身不依赖 Electron / SDK / provider, 也不做 IO;调用方决定何时启用和如何中断。
*/
@@ -59,7 +59,6 @@ export class ToolLoopGuard {
readonly consecutiveLimit: number;
readonly windowSize: number;
readonly windowDistinctLimit: number;
- readonly turnHardCap: number;
private pendingToolUses = new Map<string, PendingToolUse>();
@@ -70,14 +69,10 @@ export class ToolLoopGuard {
// 第 2 层状态: 最近 windowSize 个 name+input 指纹
private callWindow: string[] = [];
- // 第 3 层状态: 本 turn 已配对的 tool result 数
- private turnToolResultCount = 0;
-
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.turnHardCap = options.turnHardCap ?? DEFAULT_TURN_HARD_CAP;
}
/**
@@ -91,19 +86,14 @@ export class ToolLoopGuard {
}
/**
- * 工具结果到达后配对并按三层判据计数。没有配到完整 tool_use 时直接放行,
+ * 工具结果到达后配对并按两层判据判断。没有配到完整 tool_use 时直接放行,
* 避免用不完整信息误判。
*/
onToolResult(toolUseId: string, output: string): ToolLoopGuardVerdict {
const toolUse = this.pendingToolUses.get(toolUseId);
this.pendingToolUses.delete(toolUseId);
if (!toolUse) return { kind: 'ok' };
-
- // 第 3 层: turn 硬上限(先数, 任何形态兜底)
- this.turnToolResultCount += 1;
- if (this.turnToolResultCount > this.turnHardCap) {
- return { kind: 'hard', reason: 'turn-cap', count: this.turnToolResultCount, toolName: toolUse.name };
- }
+ if (LOOP_GUARD_EXEMPT_TOOL_NAMES.has(toolUse.name)) return { kind: 'ok' };
// 第 1 层: 连续 name+input+output 完全相同
const fullFingerprint = fingerprintToolCall(toolUse.name, toolUse.input, output);
@@ -144,10 +134,13 @@ export class ToolLoopGuard {
/** 每个 user turn 开始时重置, 避免跨 turn 的合法重复被累计。 */
resetTurn(): void {
this.pendingToolUses.clear();
+ this.resetPatternState();
+ }
+
+ private resetPatternState(): void {
this.lastFullFingerprint = null;
this.consecutiveStreak = 0;
this.callWindow = [];
- this.turnToolResultCount = 0;
}
}