Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions packages/cli/src/nonInteractiveCli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,57 @@ describe('runNonInteractive', () => {
).toHaveBeenCalled();
});

it('should ignore duplicate provider tool-call ids across rounds', async () => {
Comment thread
YingchaoX marked this conversation as resolved.
Resolved
setupMetricsMock();
vi.mocked(mockConfig.getMaxToolCalls).mockReturnValue(1);
const toolCallEvent: ServerGeminiStreamEvent = {
type: GeminiEventType.ToolCallRequest,
value: {
callId: 'tool-1',
providerCallId: 'tool-1',
name: 'testTool',
args: { arg1: 'value1' },
isClientInitiated: false,
prompt_id: 'prompt-id-dup',
},
};
const toolResponse: Part[] = [{ text: 'Tool response' }];
mockCoreExecuteToolCall.mockResolvedValue({ responseParts: toolResponse });

mockGeminiClient.sendMessageStream
.mockReturnValueOnce(createStreamFromEvents([toolCallEvent]))
.mockReturnValueOnce(createStreamFromEvents([toolCallEvent]))
.mockReturnValueOnce(
createStreamFromEvents([
{ type: GeminiEventType.Content, value: 'Final answer' },
{
type: GeminiEventType.Finished,
value: {
reason: undefined,
usageMetadata: { totalTokenCount: 10 },
},
},
]),
);

await runNonInteractive(
mockConfig,
mockSettings,
'Use a tool',
'prompt-id-dup',
);

expect(mockGeminiClient.sendMessageStream).toHaveBeenCalledTimes(3);
expect(mockCoreExecuteToolCall).toHaveBeenCalledTimes(1);
expect(mockGeminiClient.recordCompletedToolCall).toHaveBeenCalledTimes(1);

const duplicateParts = mockGeminiClient.sendMessageStream.mock.calls[2][0];
expect(duplicateParts[0].functionResponse?.response?.['error']).toContain(
'Duplicate provider tool call id "tool-1"',
);
expect(processStdoutSpy).toHaveBeenCalledWith('Final answer\n');
});

it('should handle error during tool execution and should send error back to the model', async () => {
setupMetricsMock();
const toolCallEvent: ServerGeminiStreamEvent = {
Expand Down
43 changes: 36 additions & 7 deletions packages/cli/src/nonInteractiveCli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
TeamEventType,
ApprovalMode,
ToolConfirmationOutcome,
createDuplicateProviderToolCallResponse,
} from '@qwen-code/qwen-code-core';
import type { Content, Part, PartListUnion } from '@google/genai';
import type { CLIUserMessage, PermissionMode } from './nonInteractive/types.js';
Expand Down Expand Up @@ -737,11 +738,35 @@ export async function runNonInteractive(
* helper returns (main-turn → emitStructuredSuccess(); drain-turn
* → return so the post-drain code emits success).
*/
const handledProviderToolCallIds = new Set<string>();

const processToolCallBatch = async (
batchRequests: ToolCallRequestInfo[],
setModelOverride: (override: string | undefined) => void,
): Promise<Part[]> => {
const toolResponseParts: Part[] = [];
const respondedCallIds = new Set<string>();
const executableBatchRequests: ToolCallRequestInfo[] = [];
const duplicatePendingResponses: Part[] = [];

for (const requestInfo of batchRequests) {
if (!requestInfo.providerCallId) {
executableBatchRequests.push(requestInfo);
continue;
}

if (!handledProviderToolCallIds.has(requestInfo.providerCallId)) {
handledProviderToolCallIds.add(requestInfo.providerCallId);
executableBatchRequests.push(requestInfo);
continue;
}

const toolResponse =
createDuplicateProviderToolCallResponse(requestInfo);
respondedCallIds.add(requestInfo.callId);
adapter.emitToolResult(requestInfo, toolResponse);
duplicatePendingResponses.push(...toolResponse.responseParts);
}

// Pre-scan: when --json-schema is active and the model emitted
// a `structured_output` call alongside other tools in the same
Expand All @@ -750,16 +775,20 @@ export async function runNonInteractive(
// suppress every non-structured sibling. See the multi-shape
// examples in the main loop's prior comment for the
// [bad/good/side-effect] permutations.
let requestsToExecute = batchRequests;
if (
let requestsToExecute = executableBatchRequests;
const structuredOutputActive =
config.getJsonSchema() &&
batchRequests.some((r) => r.name === ToolNames.STRUCTURED_OUTPUT)
) {
requestsToExecute = batchRequests.filter(
executableBatchRequests.some(
(r) => r.name === ToolNames.STRUCTURED_OUTPUT,
);
if (structuredOutputActive) {
Comment thread
YingchaoX marked this conversation as resolved.
Resolved
requestsToExecute = executableBatchRequests.filter(
(r) => r.name === ToolNames.STRUCTURED_OUTPUT,
);
} else {
toolResponseParts.push(...duplicatePendingResponses);
}
const executedCallIds = new Set<string>();
const executedCallIds = new Set(respondedCallIds);

for (const requestInfo of requestsToExecute) {
executedCallIds.add(requestInfo.callId);
Expand Down Expand Up @@ -886,7 +915,7 @@ export async function runNonInteractive(
// emitted event log pairs every tool_use with a tool_result
// AND the retry-turn payload (when reached) doesn't leave
// Anthropic / OpenAI staring at unpaired tool_use blocks.
const unexecutedCalls = batchRequests.filter(
const unexecutedCalls = executableBatchRequests.filter(
(r) => !executedCallIds.has(r.callId),
);
if (unexecutedCalls.length > 0) {
Expand Down
60 changes: 58 additions & 2 deletions packages/core/src/agents/runtime/agent-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ import {
runWithRuntimeContentGenerator,
type RuntimeContentGeneratorView,
} from './agent-context.js';
import { type ToolCallRequestInfo } from '../../core/turn.js';
import {
createDuplicateProviderToolCallResponse,
type ToolCallRequestInfo,
} from '../../core/turn.js';
import {
CoreToolScheduler,
type ToolCall,
Expand Down Expand Up @@ -654,6 +657,7 @@ export class AgentCore {
let turnCounter = 0;
let finalText = '';
let terminateMode: AgentTerminateMode | null = null;
const handledProviderToolCallIds = new Set<string>();

while (true) {
// Check abort before starting a new round — prevents unnecessary API
Expand Down Expand Up @@ -815,6 +819,7 @@ export class AgentCore {
toolsList,
currentResponseId,
wasOutputTruncated,
handledProviderToolCallIds,
);

const externalInputs = this.drainExternalInputs(options);
Expand Down Expand Up @@ -1090,6 +1095,7 @@ export class AgentCore {
toolsList: FunctionDeclaration[],
responseId?: string,
wasOutputTruncated = false,
handledProviderToolCallIds = new Set<string>(),
): Promise<Content[]> {
const toolResponseParts: Part[] = [];

Expand All @@ -1100,9 +1106,58 @@ export class AgentCore {
const authorizedCalls: FunctionCall[] = [];
for (const fc of functionCalls) {
const callId = fc.id ?? `${fc.name}-${Date.now()}`;
const providerCallId = fc.id;
const toolName = String(fc.name);

Comment thread
YingchaoX marked this conversation as resolved.
Resolved
if (providerCallId) {
if (handledProviderToolCallIds.has(providerCallId)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] Zero debug logging when a duplicate provider tool call is detected and suppressed. If a model repeatedly emits the same tool-call ID, the only observability is via emitted events — no log trail exists in --debug output or log files. This makes production debugging at 3 AM difficult.

Consider adding a debug log at the detection point:

this.runtimeContext.getDebugLogger()?.debug(
  `[processFunctionCalls] Suppressing duplicate provider tool-call id: ${providerCallId} (tool: ${toolName}, round: ${currentRound})`,
);

Same applies to the CLI path in nonInteractiveCli.ts (around line 763) using debugLogger.debug(...).

— qwen3.7-max via Qwen Code /review

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 0972eeaed: duplicate suppression now logs debug messages in AgentCore and in the non-interactive path. I also added the same lightweight debug log to the new TUI pre-schedule suppression path so all three execution entrypoints leave a trace when a provider id is ignored.

const args = (fc.args ?? {}) as Record<string, unknown>;
const request: ToolCallRequestInfo = {
callId,
Comment thread
YingchaoX marked this conversation as resolved.
Resolved
providerCallId,
name: toolName,
args,
isClientInitiated: true,
prompt_id: promptId,
response_id: responseId,
wasOutputTruncated,
};
const response = createDuplicateProviderToolCallResponse(request);
const errorMessage = response.error?.message;
const eventCallId = `${callId}:duplicate:${currentRound}:${toolResponseParts.length}`;

Comment thread
YingchaoX marked this conversation as resolved.
Resolved
this.eventEmitter?.emit(AgentEventType.TOOL_CALL, {
subagentId: this.subagentId,
round: currentRound,
callId: eventCallId,
name: toolName,
args,
description: errorMessage,
isOutputMarkdown: false,
timestamp: Date.now(),
} as AgentToolCallEvent);

this.eventEmitter?.emit(AgentEventType.TOOL_RESULT, {
subagentId: this.subagentId,
round: currentRound,
callId: eventCallId,
name: toolName,
success: false,
error: errorMessage,
responseParts: response.responseParts,
resultDisplay: response.resultDisplay,
durationMs: 0,
timestamp: Date.now(),
} as AgentToolResultEvent);

toolResponseParts.push(...response.responseParts);
Comment thread
YingchaoX marked this conversation as resolved.
Resolved
this.recordToolCallStats(toolName, false, 0, errorMessage);
continue;
}
handledProviderToolCallIds.add(providerCallId);
}

if (!allowedToolNames.has(fc.name)) {
const toolName = String(fc.name);
const errorMessage = `Tool "${toolName}" not found. Tools must use the exact names provided.`;

// Emit TOOL_CALL event for visibility
Expand Down Expand Up @@ -1338,6 +1393,7 @@ export class AgentCore {
const args = (fc.args ?? {}) as Record<string, unknown>;
const request: ToolCallRequestInfo = {
callId,
...(fc.id ? { providerCallId: fc.id } : {}),
name: toolName,
args,
isClientInitiated: true,
Expand Down
103 changes: 103 additions & 0 deletions packages/core/src/agents/runtime/agent-headless.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1030,6 +1030,109 @@ describe('subagent.ts', () => {

expect(scope.getTerminateMode()).toBe(AgentTerminateMode.GOAL);
});

it('should ignore duplicate provider tool-call ids across rounds', async () => {
const listFilesToolDef: FunctionDeclaration = {
name: 'list_files',
description: 'Lists files',
parameters: { type: Type.OBJECT, properties: {} },
};

const { config } = await createMockConfig({
getFunctionDeclarationsFiltered: vi
.fn()
.mockReturnValue([listFilesToolDef]),
getTool: vi.fn().mockReturnValue(undefined),
});
const toolConfig: ToolConfig = { tools: ['list_files'] };

mockSendMessageStream.mockImplementation(
createMockStream([
[
{
id: 'call_1',
name: 'list_files',
args: { path: '.' },
},
],
[
{
id: 'call_1',
name: 'list_files',
args: { path: '.' },
},
],
'stop',
]),
);

const listFilesInvocation = {
params: { path: '.' },
getDescription: vi.fn().mockReturnValue('List files'),
toolLocations: vi.fn().mockReturnValue([]),
getDefaultPermission: vi.fn().mockResolvedValue('allow'),
execute: vi.fn().mockResolvedValue({
llmContent: 'file1.txt\nfile2.ts',
returnDisplay: 'Listed 2 files',
}),
};
const listFilesTool = {
name: 'list_files',
displayName: 'List Files',
description: 'List files in directory',
kind: 'READ' as const,
schema: listFilesToolDef,
build: vi.fn().mockImplementation(() => listFilesInvocation),
canUpdateOutput: false,
isOutputMarkdown: true,
} as unknown as AnyDeclarativeTool;
vi.mocked(
(config.getToolRegistry() as unknown as ToolRegistry).getTool,
).mockImplementation((name: string) =>
name === 'list_files' ? listFilesTool : undefined,
);

const toolCallEvents: AgentToolCallEvent[] = [];
const toolResultEvents: AgentToolResultEvent[] = [];
const eventEmitter = new AgentEventEmitter();
eventEmitter.on(AgentEventType.TOOL_CALL, (event: unknown) => {
toolCallEvents.push(event as AgentToolCallEvent);
});
eventEmitter.on(AgentEventType.TOOL_RESULT, (event: unknown) => {
toolResultEvents.push(event as AgentToolResultEvent);
});

const scope = await AgentHeadless.create(
'test-agent',
config,
promptConfig,
defaultModelConfig,
defaultRunConfig,
toolConfig,
eventEmitter,
);

await scope.execute(new ContextState());

expect(listFilesInvocation.execute).toHaveBeenCalledTimes(1);
expect(toolCallEvents).toHaveLength(2);
expect(toolResultEvents).toHaveLength(2);
expect(toolCallEvents[0].callId).toBe('call_1');
expect(toolResultEvents[0].callId).toBe('call_1');
expect(toolCallEvents[1].callId).toMatch(/^call_1:duplicate:/);
expect(toolResultEvents[1].callId).toBe(toolCallEvents[1].callId);
expect(toolResultEvents[1].error).toContain(
'Duplicate provider tool call id "call_1"',
);

const thirdCallArgs = mockSendMessageStream.mock.calls[2][1];
const parts = thirdCallArgs.message as Part[];
expect(parts[0].functionResponse?.id).toBe('call_1');
expect(parts[0].functionResponse?.response?.['error']).toContain(
'Duplicate provider tool call id "call_1"',
);
expect(scope.getTerminateMode()).toBe(AgentTerminateMode.GOAL);
});
});

describe('execute - Termination and Recovery', () => {
Expand Down
Loading
Loading