Skip to content

Commit 1f2615e

Browse files
authored
fix(google): enforce response part field contract (#2246)
Co-authored-by: Ingwannu <[email protected]>
1 parent 08cc2ac commit 1f2615e

3 files changed

Lines changed: 176 additions & 9 deletions

File tree

‎src/adapters/google.ts‎

Lines changed: 92 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -409,11 +409,16 @@ function artifactMarkdownUrl(filePath: string): string {
409409
}
410410

411411
interface GoogleResponsePart {
412-
text?: string;
412+
text?: unknown;
413413
thought?: boolean;
414414
thoughtSignature?: string;
415415
thought_signature?: string;
416-
functionCall?: { name: string; args: unknown };
416+
functionCall?: unknown;
417+
}
418+
419+
interface GoogleFunctionCall {
420+
name: string;
421+
args?: unknown;
417422
}
418423

419424
/**
@@ -436,12 +441,24 @@ function googleToolCallMetadataFromPart(
436441
* cannot accidentally expose the same hidden reasoning through different event types.
437442
*/
438443
function googlePartTextEvent(part: GoogleResponsePart): AdapterEvent | undefined {
439-
if (!part.text) return undefined;
444+
// A malformed scalar/object is not text and must not cross the AdapterEvent boundary. Dropping
445+
// only this optional field preserves the rest of the part without inventing assistant output by
446+
// coercion; an empty string keeps its existing no-event behavior.
447+
if (typeof part.text !== "string" || part.text.length === 0) return undefined;
440448
return part.thought === true
441449
? { type: "reasoning_raw_delta", text: part.text }
442450
: { type: "text_delta", text: part.text };
443451
}
444452

453+
interface InvalidGoogleFunctionCallDiagnostic {
454+
reason:
455+
| "function_call_not_object"
456+
| "function_call_name_invalid"
457+
| "function_call_name_blank";
458+
partIndex: number;
459+
valueType: string;
460+
}
461+
445462
interface InvalidGoogleShapeDiagnostic {
446463
reason:
447464
| "candidates_not_array"
@@ -462,6 +479,63 @@ function googleStructuralValueType(value: unknown): string {
462479
return Array.isArray(value) ? "array" : typeof value;
463480
}
464481

482+
/**
483+
* Gemini delivers one complete functionCall per part, so a missing name cannot be repaired by a
484+
* later delta. Validate the whole parts array before observing signatures or emitting content: a
485+
* malformed call must terminate the claimed response rather than enter replay state or reach the
486+
* bridge as a nameless dispatch. Null remains an absence encoding, matching other optional fields.
487+
*/
488+
function diagnoseGoogleFunctionCalls(
489+
parts: readonly GoogleResponsePart[],
490+
): InvalidGoogleFunctionCallDiagnostic | undefined {
491+
for (let partIndex = 0; partIndex < parts.length; partIndex++) {
492+
const functionCall = parts[partIndex]?.functionCall;
493+
if (functionCall === undefined || functionCall === null) continue;
494+
if (!isGoogleRecord(functionCall)) {
495+
return {
496+
reason: "function_call_not_object",
497+
partIndex,
498+
valueType: googleStructuralValueType(functionCall),
499+
};
500+
}
501+
if (typeof functionCall.name !== "string") {
502+
return {
503+
reason: "function_call_name_invalid",
504+
partIndex,
505+
valueType: googleStructuralValueType(functionCall.name),
506+
};
507+
}
508+
if (functionCall.name.trim().length === 0) {
509+
return {
510+
reason: "function_call_name_blank",
511+
partIndex,
512+
valueType: "string",
513+
};
514+
}
515+
}
516+
return undefined;
517+
}
518+
519+
function googleFunctionCall(part: GoogleResponsePart): GoogleFunctionCall | undefined {
520+
const functionCall = part.functionCall;
521+
if (!isGoogleRecord(functionCall) || typeof functionCall.name !== "string") return undefined;
522+
return { name: functionCall.name, args: functionCall.args };
523+
}
524+
525+
function invalidGoogleFunctionCallEvent(
526+
diagnostic: InvalidGoogleFunctionCallDiagnostic,
527+
): Extract<AdapterEvent, { type: "error" }> {
528+
const subject = diagnostic.reason === "function_call_not_object"
529+
? "invalid function call"
530+
: diagnostic.reason === "function_call_name_blank"
531+
? "blank function call name"
532+
: "invalid function call name";
533+
return {
534+
type: "error",
535+
message: `google response contained ${subject} (${diagnostic.reason}; partIndex=${diagnostic.partIndex}; valueType=${diagnostic.valueType}) — cannot dispatch`,
536+
};
537+
}
538+
465539
/**
466540
* A candidate's `content` is claimed model output inside a well-formed frame, so it is governed by
467541
* the #1332 nested-shape rule (fail closed) rather than #1240's root-frame padding rule (skip).
@@ -865,6 +939,11 @@ export function createGoogleAdapter(provider: OcxProviderConfig): ProviderAdapte
865939
return "terminate";
866940
}
867941
parts = rawParts as GoogleResponsePart[];
942+
const invalidFunctionCall = diagnoseGoogleFunctionCalls(parts);
943+
if (invalidFunctionCall) {
944+
yield invalidGoogleFunctionCallEvent(invalidFunctionCall);
945+
return "terminate";
946+
}
868947
}
869948
// Record Gemini thought signatures for the next stateless tool-result turn. Vertex and
870949
// Antigravity use separate model namespaces so opaque provider state cannot cross routes.
@@ -905,18 +984,19 @@ export function createGoogleAdapter(provider: OcxProviderConfig): ProviderAdapte
905984
}
906985
}
907986
}
908-
if (part.functionCall) {
987+
const functionCall = googleFunctionCall(part);
988+
if (functionCall) {
909989
const id = `call_${crypto.randomUUID().slice(0, 8)}`;
910990
toolCallsStarted++;
911991
emittedContentEvent = true;
912-
const restoredName = restoreGoogleToolName(part.functionCall.name);
992+
const restoredName = restoreGoogleToolName(functionCall.name);
913993
yield {
914994
type: "tool_call_start",
915995
id,
916996
name: restoredName,
917997
...googleToolCallMetadataFromPart(part, pendingStreamThoughtSig),
918998
};
919-
yield { type: "tool_call_delta", arguments: JSON.stringify(part.functionCall.args ?? {}) };
999+
yield { type: "tool_call_delta", arguments: JSON.stringify(functionCall.args ?? {}) };
9201000
yield { type: "tool_call_end" };
9211001
}
9221002
}
@@ -1132,6 +1212,8 @@ export function createGoogleAdapter(provider: OcxProviderConfig): ProviderAdapte
11321212
const invalidParts = diagnoseGoogleParts(rawParts);
11331213
if (invalidParts) return finish([invalidGoogleShapeEvent(invalidParts)]);
11341214
const parts = rawParts as GoogleResponsePart[];
1215+
const invalidFunctionCall = diagnoseGoogleFunctionCalls(parts);
1216+
if (invalidFunctionCall) return finish([invalidGoogleFunctionCallEvent(invalidFunctionCall)]);
11351217
// Non-streaming Google-family response: observe thought signatures for the next turn,
11361218
// using the same transport-scoped namespace as the streaming path.
11371219
const replayModel = provider.googleMode === "cloud-code-assist" ? antigravityModel : vertexReplayModel;
@@ -1162,16 +1244,17 @@ export function createGoogleAdapter(provider: OcxProviderConfig): ProviderAdapte
11621244
}
11631245
}
11641246
}
1165-
if (part.functionCall) {
1247+
const functionCall = googleFunctionCall(part);
1248+
if (functionCall) {
11661249
const id = `call_${crypto.randomUUID().slice(0, 8)}`;
11671250
toolCallsStarted++;
11681251
events.push({
11691252
type: "tool_call_start",
11701253
id,
1171-
name: restoreGoogleToolName(part.functionCall.name),
1254+
name: restoreGoogleToolName(functionCall.name),
11721255
...googleToolCallMetadataFromPart(part, pendingThoughtSig),
11731256
});
1174-
events.push({ type: "tool_call_delta", arguments: JSON.stringify(part.functionCall.args ?? {}) });
1257+
events.push({ type: "tool_call_delta", arguments: JSON.stringify(functionCall.args ?? {}) });
11751258
events.push({ type: "tool_call_end" });
11761259
}
11771260
}

‎structure/04_transports-and-sidecars.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -673,6 +673,23 @@ classification, preserving the opaque continuation state independently of displa
673673
- 다른 대안 대신 이 방식을 선택한 이유: Dropping the text loses reasoning replay/display policy input, while duplicated parser rules can drift and exposing marked thoughts violates the provider's visibility boundary.
674674
- 장점, 단점 및 영향: Internal reasoning no longer leaks into normal answers and both transports stay consistent; downstream reasoning policy still decides whether raw reasoning is rendered or only preserved, and malformed non-boolean markers remain ordinary text rather than broadening hidden-content inference.
675675

676+
## Google response-part field boundary
677+
678+
Google-family adapters validate the values inside an otherwise well-formed response part before
679+
they become `AdapterEvent`s. A present `functionCall` must be an object with a nonblank string
680+
`name`; because Gemini delivers that call atomically rather than across deltas, an invalid name is a
681+
terminal protocol error and is never dispatched. A non-string optional `text` value is dropped
682+
without coercion, while the rest of the part and turn continue. Structured `functionCall.args`
683+
remain provider-native and are serialized as before.
684+
685+
[Decision Log]
686+
- 목적과 의도: Keep malformed Google-compatible response fields from violating the internal string-only text and tool-name contract or dispatching an unidentified tool.
687+
- 기존 구현 및 제약 조건: Container validation guaranteed object parts, but truthy string/number/array functionCall values emitted a nameless tool call and truthy non-string text values crossed as text or reasoning events. Gemini supplies a complete call in one part, so there is no later name fragment to await.
688+
- 검토한 주요 대안: Pass malformed values through; coerce them to strings; silently drop every malformed field; terminate the turn for every malformed field; distinguish dispatch identity from optional text.
689+
- 선택한 방식: Prevalidate function calls and terminate on a non-object, non-string, empty, or whitespace name; drop only non-string text; leave arguments untouched.
690+
- 다른 대안 대신 이 방식을 선택한 이유: Passing or coercing can execute the wrong tool or fabricate transcript text, while terminating for optional malformed text discards an otherwise usable response. An invalid call name cannot be recovered or safely ignored once the model selected a tool.
691+
- 장점, 단점 및 영향: Streaming and buffered paths enforce the same AdapterEvent contract and invalid calls cannot enter thought-signature replay. Nonconforming third-party Google-compatible text fields are ignored rather than surfaced, and operators receive a structured terminal error for call identity failures.
692+
676693
## Google tool-call thought-signature replay
677694

678695
Gemini may attach an opaque `thoughtSignature` to a `functionCall` and requires that exact value on

‎tests/google-hardening.test.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,73 @@ describe("google provider hardening", () => {
163163
});
164164
}
165165

166+
// A Google functionCall is delivered atomically in one part, so there is no later delta that
167+
// can repair a missing name. Passing one through violates AdapterEvent's string-name contract
168+
// and lets the bridge attempt to dispatch a call that cannot be identified. Keep streaming and
169+
// buffered parsing fail-closed on the same field shapes (#2233).
170+
const invalidFunctionCallCases: [string, unknown, string][] = [
171+
["a string call", "x", "google response contained invalid function call (function_call_not_object; partIndex=0; valueType=string) — cannot dispatch"],
172+
["a numeric call", 5, "google response contained invalid function call (function_call_not_object; partIndex=0; valueType=number) — cannot dispatch"],
173+
["an array call", [], "google response contained invalid function call (function_call_not_object; partIndex=0; valueType=array) — cannot dispatch"],
174+
["a call without a name", { args: {} }, "google response contained invalid function call name (function_call_name_invalid; partIndex=0; valueType=undefined) — cannot dispatch"],
175+
["a call with a numeric name", { name: 5, args: {} }, "google response contained invalid function call name (function_call_name_invalid; partIndex=0; valueType=number) — cannot dispatch"],
176+
["a call with an empty name", { name: "", args: {} }, "google response contained blank function call name (function_call_name_blank; partIndex=0; valueType=string) — cannot dispatch"],
177+
["a call with a whitespace name", { name: " ", args: {} }, "google response contained blank function call name (function_call_name_blank; partIndex=0; valueType=string) — cannot dispatch"],
178+
];
179+
180+
for (const [label, functionCall, message] of invalidFunctionCallCases) {
181+
test(`${label} is a terminal stream error`, async () => {
182+
const events = await collect(createGoogleAdapter(provider()).parseStream(
183+
sseResponse([{
184+
candidates: [{ content: { parts: [{ functionCall }] }, finishReason: "STOP" }],
185+
}]),
186+
));
187+
188+
expect(events).toEqual([{ type: "error", message }]);
189+
expect(events.some(event => event.type === "done")).toBe(false);
190+
});
191+
192+
test(`${label} is a terminal non-streaming error`, async () => {
193+
const events = await createGoogleAdapter(provider()).parseResponse!(
194+
new Response(JSON.stringify({
195+
candidates: [{ content: { parts: [{ functionCall }] }, finishReason: "STOP" }],
196+
}), { status: 200 }),
197+
);
198+
199+
expect(events).toEqual([{ type: "error", message }]);
200+
expect(events.some(event => event.type === "done")).toBe(false);
201+
});
202+
}
203+
204+
// Text is optional, but when present it must already be a string. Coercing an object or number
205+
// would invent assistant output, while terminating an otherwise valid turn would be harsher than
206+
// the field warrants. Drop only the malformed text field and keep other parts/terminal state.
207+
const nonStringTextParts: [string, Record<string, unknown>][] = [
208+
["numeric text", { text: 5 }],
209+
["object text", { text: { a: 1 } }],
210+
["array text", { text: [1, 2] }],
211+
["numeric thought text", { text: 5, thought: true }],
212+
];
213+
214+
for (const [label, part] of nonStringTextParts) {
215+
test(`${label} is dropped on both response paths`, async () => {
216+
const payload = {
217+
candidates: [{ content: { parts: [part] }, finishReason: "STOP" }],
218+
};
219+
const streamEvents = await collect(createGoogleAdapter(provider()).parseStream(sseResponse([payload])));
220+
const responseEvents = await createGoogleAdapter(provider()).parseResponse!(
221+
new Response(JSON.stringify(payload), { status: 200 }),
222+
);
223+
224+
for (const events of [streamEvents, responseEvents]) {
225+
expect(events.some(event => event.type === "text_delta")).toBe(false);
226+
expect(events.some(event => event.type === "reasoning_raw_delta")).toBe(false);
227+
expect(events.some(event => event.type === "error")).toBe(false);
228+
expect(events.at(-1)?.type).toBe("done");
229+
}
230+
});
231+
}
232+
166233
// `content` itself has the same status as `parts`: claimed output the parser cannot read. The
167234
// one tolerated non-record form is an empty array, which is how a JSON writer with no distinct
168235
// empty-object form spells an empty `content`. A NON-empty array is where the payload used to

0 commit comments

Comments
 (0)