Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
73 changes: 73 additions & 0 deletions packages/core/src/core/geminiChat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1721,6 +1721,79 @@ describe('GeminiChat', async () => {
}
});

it('recovers JSON-serialized tool calls emitted as text', async () => {
vi.spyOn(Date, 'now').mockReturnValue(456);
vi.mocked(mockConfig.getToolRegistry).mockReturnValue({
getTool: vi.fn((name: string) =>
name === 'agent' ? ({ name } as unknown) : undefined,
),
} as unknown as ReturnType<Config['getToolRegistry']>);
const leakedJson = JSON.stringify([
{
name: 'agent',
prompt: 'inspect the failing tests',
subagent_type: 'general-purpose',
run_in_background: true,
},
]);
vi.mocked(mockContentGenerator.generateContentStream).mockResolvedValue(
(async function* () {
yield {
candidates: [
{
content: {
role: 'model',
parts: [{ text: leakedJson }],
},
finishReason: 'STOP',
},
],
} as unknown as GenerateContentResponse;
})(),
);

const stream = await chat.sendMessageStream(
'test-model',
{ message: 'dispatch agents' },
'prompt-id-json-tool-leak',
);
const events: StreamEvent[] = [];
for await (const event of stream) events.push(event);

const emittedParts = events.flatMap((event) =>
event.type === StreamEventType.CHUNK
? (event.value.candidates?.[0]?.content?.parts ?? [])
: [],
);
expect(emittedParts.some((part) => part.text === leakedJson)).toBe(false);
expect(emittedParts).toContainEqual({
functionCall: {
id: 'json-recovered-0-456',
name: 'agent',
args: {
prompt: 'inspect the failing tests',
subagent_type: 'general-purpose',
run_in_background: true,
},
},
});

const modelTurn = chat.getHistory()[1]!;
expect(modelTurn.parts).toEqual([
{
functionCall: {
id: 'json-recovered-0-456',
name: 'agent',
args: {
prompt: 'inspect the failing tests',
subagent_type: 'general-purpose',
run_in_background: true,
},
},
},
]);
});

it('should succeed when there is finish reason and only thought content (reasoning models)', async () => {
// This test verifies that responses containing only thought/reasoning content
// are accepted as valid.
Expand Down
55 changes: 55 additions & 0 deletions packages/core/src/core/geminiChat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
containsXmlToolCalls,
tryRecoverXmlToolCalls,
} from './xml-tool-call-fallback.js';
import { tryRecoverJsonToolCalls } from './json-tool-call-fallback.js';
import { parseAndFormatApiError } from '../utils/errorParsing.js';
import {
getRateLimitErrorDetails,
Expand Down Expand Up @@ -4068,6 +4069,8 @@ export class GeminiChat {
currentUserTurn?.role === 'user' &&
currentUserTurn.parts?.some((part) => part.functionResponse) === true;
let deferredFinishReason: FinishReason | undefined;
const bufferedJsonTextChunks: GenerateContentResponse[] = [];
let bufferingJsonText = false;
// Captured if the upstream stream throws mid-iteration (typical on weak
// networks: SSE drops between `content_block_stop` of a tool_use and the
// terminal `message_stop`). We still build / record / push a partial
Expand Down Expand Up @@ -4226,6 +4229,19 @@ export class GeminiChat {
}

if (!protocolTextWasSuppressed || !protocolTagDetector.blockingOutput) {
const chunkText = chunk.candidates
?.flatMap((candidate) => candidate.content?.parts ?? [])
.filter((part) => !part.thought && typeof part.text === 'string')
.map((part) => part.text)
.join('');
const chunkStartsJson =
chunkText?.trimStart().startsWith('[') ||
chunkText?.trimStart().startsWith('{');
if (!hasToolCall && (bufferingJsonText || chunkStartsJson)) {

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.

[P1] Buffering can start on a JSON-looking chunk in the middle of a normal answer and then hold every remaining chunk until EOF. It also leaves buffered prefix chunks pending when a later structured function call arrives, so the tool-call/finish chunk is yielded before earlier text. Please restrict detection to the leading response and flush pending chunks in original order before yielding a real structured call.

bufferingJsonText = true;
bufferedJsonTextChunks.push(chunk);
continue;
}
yield chunk;
}
}
Expand Down Expand Up @@ -4347,6 +4363,41 @@ export class GeminiChat {
}
}

if (
streamError === null &&
!hasToolCall &&
hasFinishReason &&
contentText
) {
const toolRegistry = this.config.getToolRegistry();
const recovery = tryRecoverJsonToolCalls(contentText, (name) =>

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.

[P1] This validates against every loaded registry tool rather than the tools actually declared for this request. As a result, ordinary JSON documentation for a registered tool can become a real call even when that tool was deferred, excluded by a subagent allowlist, or the request explicitly used tools: []; in YOLO mode that can execute immediately. Recovery needs a trustworthy intent signal and must be constrained to the current request tool surface; JSON shape alone is not sufficient.

Boolean(toolRegistry.getTool(name)),
);
if (recovery.recovered) {
hasToolCall = true;
for (let i = consolidatedHistoryParts.length - 1; i >= 0; i--) {
if (consolidatedHistoryParts[i]!.text !== undefined) {
consolidatedHistoryParts.splice(i, 1);
}
}
consolidatedHistoryParts.push(...recovery.functionCallParts);
contentText = '';
contentParts = consolidatedHistoryParts;
const syntheticChunk = {
candidates: [
{
content: { role: 'model', parts: recovery.functionCallParts },
},
],
} as GenerateContentResponse;
syncFunctionCallsField(syntheticChunk, recovery.functionCallParts);
recoveredChunk = syntheticChunk;
debugLogger.warn(
`JSON tool call fallback: recovered ${recovery.functionCallParts.length} tool call(s) [${recovery.functionCallParts.map((p) => p.functionCall?.name).join(', ')}] from plain text content`,
);
}
}

if (streamError === null && protocolTagDetector.leaked) {
throw new InvalidStreamError(
'Model response started with leaked protocol tags.',
Expand Down Expand Up @@ -4391,6 +4442,10 @@ export class GeminiChat {

if (recoveredChunk) {
yield recoveredChunk;
} else if (bufferedJsonTextChunks.length > 0) {
for (const chunk of bufferedJsonTextChunks) {
yield chunk;
}
}

// Record assistant turn with raw Content and metadata. Gate matches
Expand Down
103 changes: 103 additions & 0 deletions packages/core/src/core/json-tool-call-fallback.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/

import { describe, expect, it, vi } from 'vitest';
import { tryRecoverJsonToolCalls } from './json-tool-call-fallback.js';

const knownTool = (name: string) => ['agent', 'read_file'].includes(name);

describe('tryRecoverJsonToolCalls', () => {
it('recovers an array of JSON tool calls from plain text', () => {
vi.spyOn(Date, 'now').mockReturnValue(123);

const result = tryRecoverJsonToolCalls(
JSON.stringify([
{
name: 'agent',
prompt: 'inspect the repo',
subagent_type: 'general-purpose',
run_in_background: true,
},
{ name: 'read_file', file_path: 'src/index.ts' },
]),
knownTool,
);

expect(result).toEqual({
recovered: true,
functionCallParts: [
{
functionCall: {
id: 'json-recovered-0-123',
name: 'agent',
args: {
prompt: 'inspect the repo',
subagent_type: 'general-purpose',
run_in_background: true,
},
},
},
{
functionCall: {
id: 'json-recovered-1-123',
name: 'read_file',
args: { file_path: 'src/index.ts' },
},
},
],
});
});

it('recovers a single object with nested args', () => {
const result = tryRecoverJsonToolCalls(
JSON.stringify({
name: 'read_file',
args: { file_path: 'src/index.ts' },
}),
knownTool,
);

expect(result.recovered).toBe(true);
expect(result.functionCallParts[0]?.functionCall?.name).toBe('read_file');
expect(result.functionCallParts[0]?.functionCall?.args).toEqual({
file_path: 'src/index.ts',
});
});

it('rejects unknown tool names', () => {
expect(
tryRecoverJsonToolCalls(
JSON.stringify({ name: 'not_registered', prompt: 'x' }),
knownTool,
),
).toEqual({ recovered: false, functionCallParts: [] });
});

it('rejects ordinary JSON data that is not shaped like a tool call', () => {
expect(
tryRecoverJsonToolCalls(
JSON.stringify([{ name: 'read_file', title: 'example' }]),
knownTool,
),
).toEqual({ recovered: false, functionCallParts: [] });
});

it('is safe against __proto__ argument pollution', () => {
const result = tryRecoverJsonToolCalls(
'{"name":"read_file","file_path":"a.ts","__proto__":{"polluted":true}}',
knownTool,
);

expect(result.recovered).toBe(true);
const args = result.functionCallParts[0]?.functionCall?.args as Record<
string,
unknown
>;
expect(Object.getPrototypeOf(args)).toBeNull();
expect(args['file_path']).toBe('a.ts');
expect((args as Record<string, unknown>)['polluted']).toBeUndefined();
});
});
121 changes: 121 additions & 0 deletions packages/core/src/core/json-tool-call-fallback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/

import type { Part } from '@google/genai';

const TOOL_ARG_KEYS = new Set([
'command',
'content',
'description',
'file_path',
'new_string',
'old_string',
'pattern',
'plan',
'prompt',
'query',
'run_in_background',
'subagent_type',
'todos',
]);

const RESERVED_KEYS = new Set(['id', 'name', 'type']);

type JsonRecord = Record<string, unknown>;

function isRecord(value: unknown): value is JsonRecord {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}

function parseArguments(value: unknown): JsonRecord | null {
if (isRecord(value)) return value;
if (typeof value !== 'string') return null;
const trimmed = value.trim();
if (!trimmed.startsWith('{')) return null;
try {
const parsed = JSON.parse(trimmed);
return isRecord(parsed) ? parsed : null;
} catch {
return null;
}
}

function copyArgs(source: JsonRecord): JsonRecord {
const args = Object.create(null) as JsonRecord;
for (const [key, value] of Object.entries(source)) {
args[key] = value;
}
return args;
}

function extractArgs(call: JsonRecord): JsonRecord | null {
const nestedArgs = parseArguments(call['args'] ?? call['arguments']);
if (nestedArgs && Object.keys(nestedArgs).length > 0) {
return copyArgs(nestedArgs);
}

const argEntries = Object.entries(call).filter(
([key]) => !RESERVED_KEYS.has(key),
);
if (argEntries.length === 0) return null;
if (!argEntries.some(([key]) => TOOL_ARG_KEYS.has(key))) return null;

const args = Object.create(null) as JsonRecord;
for (const [key, value] of argEntries) {
args[key] = value;
}
return args;
}

/**
* Attempts to recover tool calls from JSON content that the model emitted in
* the text channel instead of as structured functionCall parts.
*/
export function tryRecoverJsonToolCalls(
text: string,
isKnownToolName: (name: string) => boolean,
): {
recovered: boolean;
functionCallParts: Part[];
} {
const trimmed = text.trim();
if (!trimmed.startsWith('[') && !trimmed.startsWith('{')) {
return { recovered: false, functionCallParts: [] };
}

let parsed: unknown;
try {
parsed = JSON.parse(trimmed);
} catch {
return { recovered: false, functionCallParts: [] };
}

const calls = Array.isArray(parsed) ? parsed : [parsed];
if (calls.length === 0) return { recovered: false, functionCallParts: [] };

const recovered = calls.map((call) => {
if (!isRecord(call) || typeof call['name'] !== 'string') return null;
const name = call['name'];
if (!isKnownToolName(name)) return null;

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.

[P1] This interprets each item name as the registered tool name, but in #8207 create_node and read_ref are values of the agent call name argument; the intended outer tool is agent. Running the exact reported shape with only agent registered returns recovered: false, so the original leak remains. Please make the regression fixture faithful to the issue and preserve each item name as an argument. Since the text has no trustworthy outer function name, it should not be inferred from this field.

const args = extractArgs(call);
return args ? { name, args } : null;
});

if (recovered.some((call) => call === null)) {
return { recovered: false, functionCallParts: [] };
}

return {
recovered: true,
functionCallParts: recovered.map((toolCall, index) => ({
functionCall: {
id: `json-recovered-${index}-${Date.now()}`,
name: toolCall!.name,
args: toolCall!.args,
},
})),
};
}
Loading