Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(claude): 工具参数流停滞时保留上游无响应计时 (#6107)
FicoWange5c9a99c4698
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 38171edf5f..65b7d18a77 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@@ -23,7 +23,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import type { AgentDeps, DeviceHostedSession } from '../../base-agent.js';import type { AuthAdapter } from '../../../interfaces/auth-adapter.js';-import type { AgentEvent } from '../../../types/events.js';+import type { AgentEvent, InteractionDecision } from '../../../types/events.js';import type { Logger } from '../../../interfaces/logger.js';import type { ToolLoopReviewer } from '../../shared/tool-loop-review.js';@@ -147,6 +147,8 @@ async function startSessionWithStream(model = 'claude-opus-4-6',toolLoopReviewer?: ToolLoopReviewer,hosted?: { providerId: string; deviceHosted: (workingDir: string) => DeviceHostedSession },+ resumeSessionId?: string,+ remote = false,) {const configDir = await makeTempDir();process.env.CLAUDE_CONFIG_DIR = configDir;@@ -154,24 +156,37 @@ async function startSessionWithStream(const stream = createControlledStream();const fakeQuery = createFakeQuery(stream);+ const acceptedInputs: unknown[] = [];sdkMock.query.mockImplementation((options: unknown) => {const prompt = (options as { prompt?: AsyncIterable<unknown> } | undefined)?.prompt;if (prompt) {void (async () => {try {- for await (const item of prompt) { void item; /* discard — 只对齐 pending 语义 */ }+ for await (const item of prompt) { acceptedInputs.push(item); }} catch { /* end / abort 都算正常收尾 */ }})();}return fakeQuery;});- const agent = new ClaudeCodeAgent(createDeps(toolLoopReviewer));+ const deps = createDeps(toolLoopReviewer);+ let onApprovalRequest: ((params: unknown) => Promise<unknown>) | undefined;+ if (remote) {+ deps.remoteCcQueryFactory = async (options) => {+ onApprovalRequest = options.onApprovalRequest;+ return Object.assign(fakeQuery, {+ send: vi.fn(async (input: unknown) => { acceptedInputs.push(input); }),+ }) as never;+ };+ }+ const agent = new ClaudeCodeAgent(deps);const handle = await agent.startSession({sessionId: 'session-idle-watchdog',model,workingDir,permissionMode: 'acceptEdits',+ ...(remote ? { remoteHostId: 'remote-idle-watchdog' } : {}),+ ...(resumeSessionId ? { resumeSessionId } : {}),...(hosted ? { providerId: hosted.providerId, deviceHosted: hosted.deviceHosted(workingDir) } : {}),});@@ -182,7 +197,44 @@ async function startSessionWithStream(}})();- return { agent, handle, stream, fakeQuery, events, collected };+ return { agent, handle, stream, fakeQuery, events, collected, acceptedInputs, onApprovalRequest };+}++async function startPendingRemoteApproval(kind: 'permission' | 'ask_user_question' | 'plan_review' = 'permission') {+ process.env.XDT_CC_SSE_IDLE_TIMEOUT_MS = '60000';+ const session = await startSessionWithStream(undefined, undefined, undefined, undefined, true);+ let resolveDecision!: (decision: InteractionDecision) => void;+ let rejectDecision!: (reason: Error) => void;+ const resolver = vi.fn(() => new Promise<InteractionDecision>((resolve, reject) => {+ resolveDecision = resolve;+ rejectDecision = reject;+ }));+ session.handle.setInteractionResolver?.(resolver);+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });+ await session.handle.send({ type: 'user', content: 'wait for remote confirmation' });+ session.stream.emit({+ type: 'stream_event',+ event: { type: 'content_block_start', index: 0,+ content_block: { type: 'tool_use', id: 'toolu_remote_approval', name: 'Bash', input: {} } },+ });+ await vi.advanceTimersByTimeAsync(5);+ const approval = session.onApprovalRequest!({+ sessionId: 'session-idle-watchdog', requestId: 'toolu_remote_approval', kind,+ toolName: kind === 'permission' ? 'Bash' : kind === 'plan_review' ? 'ExitPlanMode' : 'AskUserQuestion',+ input: { command: 'rm -rf build' },+ });+ await pumpUntil(() => resolver.mock.calls.length === 1, 'remote approval displayed');+ return {+ ...session, approval, resolveDecision, rejectDecision,+ async cleanup() {+ // Close settles any interaction still pending after a failed assertion.+ session.stream.end();+ await session.handle.close();+ await approval.catch(() => undefined);+ await session.collected;+ vi.useRealTimers();+ },+ };}function successResult(): Record<string, unknown> {@@ -373,6 +425,54 @@ describe('upstream-response-idle watchdog suspend awareness', () => {await collected;});+ it.each([undefined, 'resumed-idle-session'])(+ 'incomplete streamed tool input retains the idle watchdog (resume=%s)',+ async (resumeSessionId) => {+ delete process.env.XDT_CC_SSE_IDLE_TIMEOUT_MS;+ const { handle, stream, events, fakeQuery, collected, acceptedInputs } = await startSessionWithStream(+ undefined, undefined, undefined, resumeSessionId,+ );+ expect((sdkMock.query.mock.calls.at(-1)?.[0] as { options: { resume?: string } }).options.resume)+ .toBe(resumeSessionId);+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });+ await handle.send({ type: 'user', content: 'synthetic tool input stall' });+ stream.emit({+ type: 'stream_event',+ event: { type: 'content_block_start', index: 0,+ content_block: { type: 'tool_use', id: 'toolu_partial', name: 'Bash', input: {} } },+ });+ await vi.advanceTimersByTimeAsync(5);+ stream.emit({+ type: 'stream_event',+ event: { type: 'content_block_delta', index: 0,+ delta: { type: 'input_json_delta', partial_json: '{"command":"' } },+ });+ await vi.advanceTimersByTimeAsync(5);+ await vi.advanceTimersByTimeAsync(29 * 60_000);+ expect(idleTimeoutError(events)).toBeUndefined();+ await vi.advanceTimersByTimeAsync(60_000);+ expect(idleTimeoutError(events)).toBeDefined();+ expect(fakeQuery.interrupt).toHaveBeenCalledTimes(1);+ expect(handle.isTurnRunning?.()).toBe(false);+ expect(acceptedInputs).toHaveLength(1);++ // Acknowledged interruption ends this turn; only an explicit new send runs again.+ stream.emit(successResult());+ await vi.advanceTimersByTimeAsync(5);+ await handle.send({ type: 'user', content: 'next explicit input' });+ expect(handle.isTurnRunning?.()).toBe(true);+ stream.emit(successResult());+ await vi.advanceTimersByTimeAsync(5);+ expect(handle.isTurnRunning?.()).toBe(false);+ expect(fakeQuery.interrupt).toHaveBeenCalledTimes(1);+ expect(acceptedInputs).toHaveLength(2);+ vi.useRealTimers();+ stream.end();+ await handle.close().catch(() => undefined);+ await collected;+ },+ );+it('工具执行期间停表不开火;tool_result 配对完重新起表、走满才开火', async () => {process.env.XDT_CC_SSE_IDLE_TIMEOUT_MS = '120000';const { handle, stream, events, fakeQuery, collected } = await startSessionWithStream();@@ -380,6 +480,25 @@ describe('upstream-response-idle watchdog suspend awareness', () => {vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });await handle.send({ type: 'user', content: 'run a long tool' });+ // Streaming arguments are upstream work. Progress keeps refreshing its budget,+ // even when the total argument-generation duration exceeds that budget.+ stream.emit({+ type: 'stream_event',+ event: { type: 'content_block_start', index: 0,+ content_block: { type: 'tool_use', id: 'toolu_long', name: 'Bash', input: {} } },+ });+ await vi.advanceTimersByTimeAsync(5);+ for (let i = 0; i < 3; i++) {+ await vi.advanceTimersByTimeAsync(60_000);+ stream.emit({+ type: 'stream_event',+ event: { type: 'content_block_delta', index: 0,+ delta: { type: 'input_json_delta', partial_json: i === 0 ? '{"command":"' : 'x' } },+ });+ await vi.advanceTimersByTimeAsync(5);+ expect(fakeQuery.interrupt).not.toHaveBeenCalled();+ }+// assistant 发起 tool_use → ball 交回客户端,watchdog 停表。stream.emit(assistantToolUse('toolu_long'));await vi.advanceTimersByTimeAsync(5);@@ -404,6 +523,152 @@ describe('upstream-response-idle watchdog suspend awareness', () => {await collected;});+ it('permission waiting before a complete assistant message pauses the idle watchdog', async () => {+ process.env.XDT_CC_SSE_IDLE_TIMEOUT_MS = '120000';+ const { handle, stream, events, fakeQuery, collected } = await startSessionWithStream();+ type CanUseTool = (tool: string, input: Record<string, unknown>, opts: { toolUseID: string }) => Promise<unknown>;+ const canUseTool = (sdkMock.query.mock.calls.at(-1)?.[0] as { options: { canUseTool: CanUseTool } }).options.canUseTool;+ const resolver = vi.fn(() => new Promise<never>(() => {}));+ handle.setInteractionResolver?.(resolver);+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });+ try {+ await handle.send({ type: 'user', content: 'wait for confirmation' });+ stream.emit({+ type: 'stream_event',+ event: { type: 'content_block_start', index: 0,+ content_block: { type: 'tool_use', id: 'toolu_approval', name: 'Bash', input: {} } },+ });+ await vi.advanceTimersByTimeAsync(5);+ void canUseTool('Bash', { command: 'rm -rf build' }, { toolUseID: 'toolu_approval' });+ await vi.advanceTimersByTimeAsync(20 * 60_000);+ expect(resolver).toHaveBeenCalledOnce();+ expect(idleTimeoutError(events)).toBeUndefined();+ expect(fakeQuery.interrupt).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ stream.end();+ await handle.close().catch(() => undefined);+ await collected;+ }+ });++ it.each(['permission', 'ask_user_question', 'plan_review'] as const)(+ 'remote %s waiting before a complete assistant pauses idle; allowed tool resumes timing after its result',+ async (kind) => {+ const session = await startPendingRemoteApproval(kind);+ const { handle, stream, events, fakeQuery } = session;+ try {+ await vi.advanceTimersByTimeAsync(90_000); // idle=60s, remote approval deadline=110s+ expect(idleTimeoutError(events)).toBeUndefined();+ expect(fakeQuery.interrupt).not.toHaveBeenCalled();+ session.resolveDecision(kind === 'ask_user_question'+ ? { kind, answers: {} }+ : { kind, behavior: 'allow' });+ await expect(session.approval).resolves.toMatchObject({ kind });+ // Approval proves executable input even if the full assistant is delayed.+ await vi.advanceTimersByTimeAsync(120_000);+ expect(fakeQuery.interrupt).not.toHaveBeenCalled();+ stream.emit(userToolResult('toolu_remote_approval'));+ await pumpUntil(() => events.some(e => e.type === 'tool_result_full'), 'remote result received');+ await vi.advanceTimersByTimeAsync(59_000);+ expect(idleTimeoutError(events)).toBeUndefined();+ await vi.advanceTimersByTimeAsync(1_001);+ expect(idleTimeoutError(events)).toBeDefined();+ expect(fakeQuery.interrupt).toHaveBeenCalledOnce();+ expect(handle.isTurnRunning?.()).toBe(false);+ await handle.send({ type: 'user', content: 'explicit next turn' });+ stream.emit(successResult());+ await pumpUntil(() => handle.isTurnRunning?.() === false, 'next turn finished');+ expect(session.acceptedInputs).toHaveLength(2);+ } finally {+ await session.cleanup();+ }+ },+ );++ it.each(['deny', 'reject', 'timeout'] as const)(+ 'remote approval %s restores the idle budget even without a tool result',+ async (outcome) => {+ const session = await startPendingRemoteApproval();+ try {+ await vi.advanceTimersByTimeAsync(90_000);+ expect(session.fakeQuery.interrupt).not.toHaveBeenCalled();+ if (outcome === 'deny') session.resolveDecision({ kind: 'permission', behavior: 'deny' });+ else if (outcome === 'reject') session.rejectDecision(new Error('fixture resolver failed'));+ else await vi.advanceTimersByTimeAsync(20_000);+ await expect(session.approval).resolves.toMatchObject({ behavior: 'deny' });+ await vi.advanceTimersByTimeAsync(59_000);+ expect(session.fakeQuery.interrupt).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1_001);+ expect(session.fakeQuery.interrupt).toHaveBeenCalledOnce();+ expect(idleTimeoutError(session.events)).toBeDefined();+ } finally {+ await session.cleanup();+ }+ },+ );++ it.each(['allow', 'deny'] as const)(+ 'cancelled remote approval with late %s cannot change the next turn idle budget',+ async (behavior) => {+ const session = await startPendingRemoteApproval();+ try {+ await vi.advanceTimersByTimeAsync(30_000);+ await session.handle.abort();+ expect(session.fakeQuery.interrupt).toHaveBeenCalledOnce();+ await session.handle.send({ type: 'user', content: 'explicit next turn' });+ await vi.advanceTimersByTimeAsync(30_000);+ session.resolveDecision({ kind: 'permission', behavior });+ await session.approval;+ await vi.advanceTimersByTimeAsync(30_001);+ expect(session.fakeQuery.interrupt).toHaveBeenCalledTimes(2);+ expect(idleTimeoutError(session.events)).toBeDefined();+ expect(session.acceptedInputs).toHaveLength(2);+ } finally {+ await session.cleanup();+ }+ },+ );++ it('a cancelled remote denial cannot remove a reused tool id in the next turn', async () => {+ const session = await startPendingRemoteApproval();+ try {+ await session.handle.abort();+ await session.handle.send({ type: 'user', content: 'next turn with a running tool' });+ session.stream.emit(assistantToolUse('toolu_remote_approval'));+ await vi.advanceTimersByTimeAsync(5);+ session.resolveDecision({ kind: 'permission', behavior: 'deny' });+ await session.approval;+ await vi.advanceTimersByTimeAsync(120_000);+ expect(session.fakeQuery.interrupt).toHaveBeenCalledOnce(); // only the explicit Stop+ session.stream.emit(userToolResult('toolu_remote_approval'));+ await pumpUntil(() => session.events.some(e => e.type === 'tool_result_full'), 'next turn tool result');+ await vi.advanceTimersByTimeAsync(60_001);+ expect(session.fakeQuery.interrupt).toHaveBeenCalledTimes(2);+ expect(session.acceptedInputs).toHaveLength(2);+ } finally {+ await session.cleanup();+ }+ });++ it('a remote approval callback throwing releases its idle pause', async () => {+ const session = await startPendingRemoteApproval();+ try {+ session.resolveDecision({ kind: 'permission', behavior: 'deny' });+ await session.approval;+ session.handle.setInteractionResolver?.(() => { throw new Error('fixture synchronous failure'); });+ await expect(session.onApprovalRequest!({+ sessionId: 'session-idle-watchdog', requestId: 'toolu_remote_throws',+ kind: 'ask_user_question', toolName: 'AskUserQuestion', input: {},+ })).rejects.toThrow('fixture synchronous failure');+ await vi.advanceTimersByTimeAsync(60_001);+ expect(session.fakeQuery.interrupt).toHaveBeenCalledOnce();+ expect(idleTimeoutError(session.events)).toBeDefined();+ } finally {+ await session.cleanup();+ }+ });+it('turn 正常结束 → 清表,不再开火', async () => {process.env.XDT_CC_SSE_IDLE_TIMEOUT_MS = '100000';const { handle, stream, events, fakeQuery, collected } = await startSessionWithStream();diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex 4576f0a8d7..793885be70 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -3346,6 +3346,34 @@ export class ClaudeCodeAgent extends BaseAgent {/** 当前分片的起始壁钟时刻;片尾据此识别系统挂起。 */let upstreamResponseIdleSliceStartedAt = 0;const pendingToolIds: Set<string> = new Set();+ async function withRemoteApprovalIdleGuard(+ rawParams: unknown,+ approve: () => Promise<unknown>,+ ): Promise<unknown> {+ // SSH daemon canUseTool bypasses the local callback. Its requestId is the+ // SDK toolUseID: executable input is available even before full assistant.+ const toolUseId = (rawParams as { requestId?: unknown } | null)?.requestId;+ const generation = turnState.generation;+ const tracked = !closed && turnInFlight && typeof toolUseId === 'string' && toolUseId.length > 0;+ if (tracked) {+ pendingToolIds.add(toolUseId);+ clearUpstreamResponseIdle();+ }+ let awaitingToolResult = false;+ try {+ const result = await approve();+ const decision = result as { kind?: string; behavior?: string } | null;+ awaitingToolResult = decision?.behavior === 'allow' || decision?.kind === 'ask_user_question';+ return result;+ } finally {+ // Allowed tools stay protected until tool_result. Denial / failure may+ // never produce one, so resume idle timing. Never re-add a cleared id or+ // let an old approval remove/reset the next turn's pending tools/budget.+ if (!awaitingToolResult && tracked && turnState.generation === generation && pendingToolIds.delete(toolUseId)) {+ armUpstreamResponseIdle();+ }+ }+ }function clearUpstreamResponseIdle(): void {if (upstreamResponseIdleTimer) {clearTimeout(upstreamResponseIdleTimer);@@ -3858,7 +3886,7 @@ export class ClaudeCodeAgent extends BaseAgent {// 同一个 scope key 也必须随注册的 session ctx 走: prompt 段用它读索引// (上方 memoryScopeKey), 远端工具侧不给就会回落到 workdir 键。...((makerMemoryEnabled || opts.makerMemoryScopeKey) ? { makerMemoryScopeKey: memoryScopeKey } : {}),- onApprovalRequest: async (rawParams: unknown) => {+ onApprovalRequest: (rawParams: unknown) => withRemoteApprovalIdleGuard(rawParams, async () => {// 110s timeout — must respond before daemon's 120s server-request timeout.// On timeout, dismiss the pending interaction (clears UI) and reject to// let cc-manager-client return deny to daemon.@@ -4114,7 +4142,7 @@ export class ClaudeCodeAgent extends BaseAgent {? formatPermissionDenial(isSystemPermissionDenialReason(decision.reason) ? 'system' : 'user', decision.reason): decision.reason,};- },+ }),onSubagentModelAccessRequest: async (rawParams: unknown) => {const params = typeof rawParams === 'object' && rawParams !== null? rawParams as Record<string, unknown>@@ -5689,10 +5717,16 @@ export class ClaudeCodeAgent extends BaseAgent {toolName?: unknown,input?: unknown,parentToolUseId?: string,+ inputStreaming?: boolean,) => {- pendingToolIds.add(id);getToolLoopMonitor(parentToolUseId).onToolUse(id, toolName, input);- clearUpstreamResponseIdle();+ // content_block_start precedes input_json_delta: the model still+ // owns the response until the complete tool input is delivered.+ // canUseTool independently pauses the watchdog during approval.+ if (!inputStreaming) {+ pendingToolIds.add(id);+ clearUpstreamResponseIdle();+ }},onToolResultDone: (id: string,diff --git a/packages/maker-core/src/agents/claude-code/translator.ts b/packages/maker-core/src/agents/claude-code/translator.tsindex 0ed1cca7d6..893aef0891 100644--- a/packages/maker-core/src/agents/claude-code/translator.ts+++ b/packages/maker-core/src/agents/claude-code/translator.ts@@ -704,12 +704,14 @@ interface TranslateContext {/*** upstream-response-idle watchdog / loop guard: assistant / stream_event 含 tool_use 时回调。* parentToolUseId 用于隔离并发 subagent;缺省表示顶层 agent。+ * inputStreaming 表示参数尚在流入,不能据此认定工具已执行并暂停上游计时。*/onToolUseStart?: (toolUseId: string,toolName?: unknown,input?: unknown,parentToolUseId?: string,+ inputStreaming?: boolean,) => void;/*** upstream-response-idle watchdog: user 含 tool_result 时出队, 配对 onToolUseStart。@@ -1732,7 +1734,7 @@ function handleStreamEvent(if (!parentToolUseId) observeClaudeTokenSpeed(event, queue, ctx);- // 冗余 add: 防 SDK 顺序契约变化 (stream_event 先于 assistant message yield), Set 幂等。+ // 流式开头先登记工具身份;完整 assistant 消息才表示参数已交付。if (event.type === 'content_block_start') {const cb = event.content_block;if (cb && cb.type === 'text') {@@ -1742,12 +1744,13 @@ function handleStreamEvent(if (cb && cb.type === 'tool_use') {const toolUseId = rememberClaudeToolUseId(ctx, cb.id, cb.name);if (toolUseId) {- // watchdog / loop-guard 仍要立刻拿到 tool id。生成计时要等- // message_delta 或完整 assistant tool_use: content_block_start+ // loop-guard 仍要立刻拿到 tool id;上游 watchdog 等完整 assistant+ // tool_use 或 canUseTool 才停表。生成计时要等 message_delta 或完整+ // assistant tool_use: content_block_start// 早于参数 input_json_delta,这里停表会把参数生成时间从分母抠掉,// 而后续 message_delta 仍把这些 token 加进 outputTokens。if (!parentToolUseId) ctx.rt.mainRequestToolUseIds.add(toolUseId);- ctx.onToolUseStart?.(toolUseId, cb.name, cb.input, parentToolUseId);+ ctx.onToolUseStart?.(toolUseId, cb.name, cb.input, parentToolUseId, true);}}}