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): 避免同类工具错误三次后打断正常纠错 (#4976)
DavidShenXD6ef63428b6f4
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.tsindex 8824eea250..2bcfccfdb0 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthIsolatedSandbox.test.ts@@ -553,36 +553,49 @@ describe('dev 沙箱凭证隔离(XDT_ISOLATED_AUTH)', () => {const adapter = new DesktopCodexAuthAdapter();let release!: () => void;const gate = new Promise<void>(resolve => { release = resolve; });+ let entered!: () => void;+ const callbackStarted = new Promise<void>(resolve => { entered = resolve; });const callback = vi.fn(async () => {+ entered();await gate;if (outcome === 'failure') throw new Error('test host retirement failure');});adapter.setOnLoginSuccess(callback);const settled = vi.fn();const login = adapter.triggerLogin({ mode: 'local' }).then(state => { settled(); return state; });- await vi.waitFor(() => expect(callback).toHaveBeenCalledOnce());- expect(settled).not.toHaveBeenCalled();- await expect(adapter.getAccessToken()).resolves.toBe('system-token');- if (outcome === 'owner-change') h.dataOwnerId = 'owner-b';- if (outcome === 'cancel' || outcome === 'cancel-cleanup-failure') adapter.cancelLogin();- if (outcome === 'cancel-cleanup-failure') {- const error = new Error('test disconnect persistence failure');- vi.spyOn(adapter as unknown as { disconnectCodexOAuth(): Promise<void> }, 'disconnectCodexOAuth').mockRejectedValueOnce(error);- const rejected = expect(login).rejects.toBe(error);- release();- await rejected;+ try {+ // Wait for the actual refresh boundary, not vi.waitFor's 1s IO deadline.+ // If login exits without reaching it, fail immediately rather than hang.+ await Promise.race([callbackStarted, login.then(() => {+ throw new Error('Login settled before the runtime refresh callback');+ })]);+ expect(callback).toHaveBeenCalledOnce();expect(settled).not.toHaveBeenCalled();+ await expect(adapter.getAccessToken()).resolves.toBe('system-token');+ if (outcome === 'owner-change') h.dataOwnerId = 'owner-b';+ if (outcome === 'cancel' || outcome === 'cancel-cleanup-failure') adapter.cancelLogin();+ if (outcome === 'cancel-cleanup-failure') {+ const error = new Error('test disconnect persistence failure');+ vi.spyOn(adapter as unknown as { disconnectCodexOAuth(): Promise<void> }, 'disconnectCodexOAuth').mockRejectedValueOnce(error);+ const rejected = expect(login).rejects.toBe(error);+ release();+ await rejected;+ expect(settled).not.toHaveBeenCalled();+ expect(fs.readFileSync(systemAuth)).toEqual(before);+ return;+ }+ release();+ await expect(login).resolves.toMatchObject(outcome === 'owner-change' || outcome === 'cancel'+ ? { authenticated: false, errorReason: 'login_cancelled' }+ : { authenticated: true });+ h.dataOwnerId = 'owner-a';+ await expect(adapter.getAccessToken()).resolves.toBe(outcome === 'cancel' ? null : 'system-token');+ await expect(new DesktopCodexAuthAdapter().getAccessToken()).resolves.toBe(outcome === 'cancel' ? null : 'system-token');expect(fs.readFileSync(systemAuth)).toEqual(before);- return;+ } finally {+ release();+ await login.catch(() => undefined);}- release();- await expect(login).resolves.toMatchObject(outcome === 'owner-change' || outcome === 'cancel'- ? { authenticated: false, errorReason: 'login_cancelled' }- : { authenticated: true });- h.dataOwnerId = 'owner-a';- await expect(adapter.getAccessToken()).resolves.toBe(outcome === 'cancel' ? null : 'system-token');- await expect(new DesktopCodexAuthAdapter().getAccessToken()).resolves.toBe(outcome === 'cancel' ? null : 'system-token');- expect(fs.readFileSync(systemAuth)).toEqual(before);});it.each([false, true])('local reconnect shares native refresh writes instead of copying (existing=%s)', async (existing) => {diff --git a/apps/desktop/src/main/plugin-market/__tests__/sources-cache-lease.test.ts b/apps/desktop/src/main/plugin-market/__tests__/sources-cache-lease.test.tsindex b74f92e827..73311dee0e 100644--- a/apps/desktop/src/main/plugin-market/__tests__/sources-cache-lease.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/sources-cache-lease.test.ts@@ -46,13 +46,6 @@ function makeTree(): { root: string; slot: string; version: string; staging: strreturn { root, slot, version, staging };}-async function waitFor(predicate: () => boolean, attempts = 100): Promise<void> {- for (let i = 0; i < attempts; i += 1) {- if (predicate()) return;- await new Promise((resolve) => setTimeout(resolve, 5));- }-}-/** 给"推迟的删除"留出执行窗口,用于断言它**没有**发生。 */async function settle(): Promise<void> {await new Promise((resolve) => setTimeout(resolve, 20));@@ -72,7 +65,7 @@ describe('cacheLease 删除守卫', () => {expect(fs.existsSync(tree.version)).toBe(true);releaseCachePath(tree.version);- await waitFor(() => !fs.existsSync(tree.version));+ await settleCachePathRemovals(tree.version);expect(fs.existsSync(tree.version)).toBe(false);});@@ -83,7 +76,8 @@ describe('cacheLease 删除守卫', () => {expect(await removeCachePath(tree.slot)).toBe(false);expect(fs.readFileSync(path.join(tree.version, 'file.txt'), 'utf8')).toBe('content');});- await waitFor(() => !fs.existsSync(tree.slot));+ // Lease release starts async rm; await it instead of imposing a disk-speed deadline.+ await settleCachePathRemovals(tree.slot);expect(fs.existsSync(tree.slot)).toBe(false);});@@ -96,7 +90,7 @@ describe('cacheLease 删除守卫', () => {expect(await removeCachePath(sibling)).toBe(false);expect(fs.existsSync(sibling)).toBe(true);});- await waitFor(() => !fs.existsSync(sibling));+ await settleCachePathRemovals(sibling);expect(fs.existsSync(sibling)).toBe(false);});@@ -178,7 +172,7 @@ describe('cacheLease 删除守卫', () => {expect(fs.existsSync(tree.version)).toBe(true);releaseCachePath(tree.version);- await waitFor(() => !fs.existsSync(tree.version));+ await settleCachePathRemovals(tree.version);expect(fs.existsSync(tree.version)).toBe(false);});});diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.mdindex ef885af70f..b3599bc39b 100644--- a/docs/dev-rules/maker-core-and-agent-behavior.md+++ b/docs/dev-rules/maker-core-and-agent-behavior.md@@ -17,9 +17,12 @@ Orca 多 Agent 协同另见 [`orca-team-architecture.md`](orca-team-architecture`agents/shared/loop-guard.ts` 的 `ToolLoopGuard`,不能靠缩短无事件超时处理。Claude Code 在原有 per-sidechain 回调里检测所有模型;Pi / Codex 在 `Session` 中配对当前产品轮次的 `tool_use` 与 `tool_result_full`,不重复统计结果摘要、后台事件或旧轮次。-Pi / Codex 的归一事件尚无可靠模型响应批次标识,因此不启用“参数各不相同、同类契约-错误连续被拒”的重试计数规则,避免把单批并行失败当成多次重试;重复调用检测仍保留。-Claude Code 沿用既有按批次计数的契约错误规则。+三个引擎均关闭“参数各不相同、同类契约错误连续被拒三次即中断”的规则:同类错误+不能证明模型没有在修正调用,Pi / Codex 也尚无可靠模型响应批次标识。运行时沿用+`contractConsecutiveLimit: Number.POSITIVE_INFINITY` 关闭该计数阈值,不新增提醒或自动重试。+完全相同的工具名、参数、输出连续四次仍会中断,短窗口轮转检测也保持不变;不同参数+持续出现同类错误可能多重试几次,这是减少纠错误停的取舍。旧 `contract` 错误的展示+和历史兼容保持不变。循环错误沿用 `tool_use_loop_detected` 和既有中断复核,Orca 消费普通终态链路;该 reason 不进入 interrupted-turn 自动续跑白名单,避免熔断后立即重复原循环。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 cd11ed6f7b..d7f913443c 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@@ -83,7 +83,7 @@ function createControlledStream() {const items: unknown[] = [];let waiter: { resolve: (r: IteratorResult<unknown>) => void; reject: (e: unknown) => void } | null = null;let ended = false;- let failure: unknown = null;+ const failure: unknown = null;function pump(): void {if (!waiter) return;@@ -153,7 +153,7 @@ async function startSessionWithStream(model = 'claude-opus-4-6') {if (prompt) {void (async () => {try {- for await (const _ of prompt) { /* discard — 只对齐 pending 语义 */ }+ for await (const item of prompt) { void item; /* discard — 只对齐 pending 语义 */ }} catch { /* end / abort 都算正常收尾 */ }})();}@@ -418,6 +418,101 @@ describe('upstream-response-idle watchdog suspend awareness', () => {});describe('Claude Code tool-loop guard runtime integration', () => {+ const editErrors = [+ 'The required parameter `file_path` is missing',+ 'String to replace not found in file.',+ 'Found 2 matches of the string to replace, but replace_all is false.',+ 'No changes to make: old_string and new_string are exactly the same.',+ ];++ it.each(editErrors.flatMap(output => [+ { output, parentToolUseId: undefined },+ { output, parentToolUseId: 'toolu_edit_agent' },+ ]))('allows changing Edit inputs after repeated errors: $output, parent=$parentToolUseId', async ({ output, parentToolUseId }) => {+ const { handle, stream, events, fakeQuery, collected } = await startSessionWithStream();+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });+ try {+ await handle.send({ type: 'user', content: 'correct the edit and continue' });+ for (let i = 0; i < 20; i++) {+ const id = `edit-${i}`;+ // Keep the file fixed (or consistently absent for missing-field+ // errors). Each corrected attempt/result is a separate SDK batch.+ stream.emit({+ type: 'assistant', parent_tool_use_id: parentToolUseId ?? null,+ message: { role: 'assistant', content: [{+ type: 'tool_use', id, name: 'Edit',+ input: {+ ...(output === editErrors[0] ? {} : { file_path: 'electron-main.mjs' }),+ old_string: `before-${i}`,+ new_string: output === editErrors[3] ? `before-${i}` : `after-${i}`,+ },+ }] },+ });+ stream.emit({+ type: 'user', parent_tool_use_id: parentToolUseId ?? null,+ message: { role: 'user', content: [{+ type: 'tool_result', tool_use_id: id, content: output, is_error: true,+ }] },+ });+ await pumpUntil(() => events.filter(e => e.type === 'tool_result_full').length === i + 1, 'failed edit delivered');+ expect(toolLoopError(events)).toBeUndefined();+ expect(fakeQuery.interrupt).not.toHaveBeenCalled();+ expect(handle.isTurnRunning?.()).toBe(true);+ }+ expect(events.filter(e => e.type === 'tool_result_full').map(e => e.data)).toEqual(+ Array.from({ length: 20 }, (_, i) => expect.objectContaining({+ toolUseId: `edit-${i}`, fullText: output,+ })),+ );+ stream.emit(successResult());+ await pumpUntil(() => handle.isTurnRunning?.() === false, 'correcting turn completed');+ expect(toolLoopError(events)).toBeUndefined();+ } finally {+ vi.useRealTimers();+ stream.end();+ await handle.close().catch(() => undefined);+ await collected;+ }+ });++ it.each([undefined, 'toolu_edit_agent'])('still interrupts four identical failed edits, parent=%s', async (parentToolUseId) => {+ const { handle, stream, events, fakeQuery, collected } = await startSessionWithStream();+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });+ try {+ await handle.send({ type: 'user', content: 'edit the file' });+ for (let i = 0; i < 4; i++) {+ const id = `same-edit-${i}`;+ stream.emit({+ type: 'assistant', parent_tool_use_id: parentToolUseId ?? null,+ message: { role: 'assistant', content: [{+ type: 'tool_use', id, name: 'Edit',+ input: { file_path: 'electron-main.mjs', old_string: 'same', new_string: 'same' },+ }] },+ });+ stream.emit({+ type: 'user', parent_tool_use_id: parentToolUseId ?? null,+ message: { role: 'user', content: [{+ type: 'tool_result', tool_use_id: id, content: editErrors[3], is_error: true,+ }] },+ });+ await pumpUntil(() => events.filter(e => e.type === 'tool_result_full').length === i + 1, 'identical edit delivered');+ if (i < 3) {+ expect(toolLoopError(events)).toBeUndefined();+ expect(fakeQuery.interrupt).not.toHaveBeenCalled();+ }+ }+ await pumpUntil(() => fakeQuery.interrupt.mock.calls.length === 1, 'identical edit interrupted');+ expect(toolLoopError(events)).toMatchObject({ data: {+ reason: 'tool_use_loop_detected', loopKind: 'consecutive', loopCount: 4,+ } });+ } finally {+ vi.useRealTimers();+ stream.end();+ await handle.close().catch(() => undefined);+ await collected;+ }+ });+it('并发 subagent 的相同调用按 parent 隔离,不会聚合成会话级死循环', async () => {const { handle, stream, events, fakeQuery, collected } = await startSessionWithStream('claude-opus-5',diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex 9903cd7b0e..c1b53d6422 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -2598,7 +2598,12 @@ export class ClaudeCodeAgent extends BaseAgent {const scopeKey = parentToolUseId ?? null;let guard = toolLoopGuards.get(scopeKey);if (!guard) {- guard = new ToolLoopGuard();+ guard = new ToolLoopGuard({+ // Different inputs can be legitimate corrections, even when the+ // tool keeps reporting the same error category. Match Pi/Codex:+ // keep exact repetition/rotation guards, not category-only retries.+ contractConsecutiveLimit: Number.POSITIVE_INFINITY,+ });toolLoopGuards.set(scopeKey, guard);}return guard;diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.tsindex 85b0fecd9e..82a65bb34b 100644--- a/packages/maker-core/src/session.ts+++ b/packages/maker-core/src/session.ts@@ -2159,8 +2159,8 @@ export class Session {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.+ // not enable the retry-count rule without that evidence. Claude also+ // disables category-only retries; repetition rules stay active.contractConsecutiveLimit: Number.POSITIVE_INFINITY,}),pendingToolLoop: null,