Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
67 changes: 54 additions & 13 deletions src/loop/adapter-google.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const PROXY_TOOL_SET = new Set([
// here or their chunks raw-replay to the client as "real" calls. acp_cache
// had the same gap before this change.
"acp_retire", "acp_restore", "acp_rewrite", "acp_cache",
"acp_retrieve", "acp_rule", "acp_read_original_image",
"bili_compress", "bili_decompress", "bili_search_context", "bili_status",
]);

Expand Down Expand Up @@ -101,35 +102,53 @@ interface FunctionCallBuffer {
}

// A decision per buffered chunk that carried functionCall parts: "keep" = every
// call in it is real (replay verbatim, preserving signatures/ids/order), null =
// only proxy calls (drop — the proxy executes them server-side), or a rewritten
// copy keeping the chunk's other parts plus its real calls.
// call in it is real and needs no signature promotion (replay verbatim,
// preserving signatures/ids/order), null = only proxy calls (drop — the proxy
// executes them server-side), or a rewritten copy keeping the chunk's other
// parts plus its real calls (promoting a stripped proxy call's thoughtSignature
// onto the first surviving real functionCall part when Gemini placed the turn
// signature on the leading proxy call).
function filterRealCallChunk(
parsed: Record<string, unknown>,
realIndexes: Set<number>,
callIndexes: number[],
promoteSig?: { callIndex: number; signature: string },
): "keep" | null | Record<string, unknown> {
const candidates = parsed.candidates as Array<Record<string, unknown>> | undefined;
const parts = (candidates?.[0]?.content as { parts?: GooglePart[] } | undefined)?.parts;
if (!Array.isArray(parts)) return "keep";
let anyReal = false;
let anyProxy = false;
const keep: boolean[] = [];
let sigPromoted = false;
const outParts: GooglePart[] = [];
let call = 0;
for (const part of parts) {
if (part && typeof part === "object" && part.functionCall) {
const real = realIndexes.has(callIndexes[call] ?? -1);
const callIdx = callIndexes[call] ?? -1;
const real = realIndexes.has(callIdx);
call += 1;
keep.push(real);
if (real) anyReal = true;
else anyProxy = true;
if (real) {
anyReal = true;
if (
promoteSig &&
callIdx === promoteSig.callIndex &&
(typeof part.thoughtSignature !== "string" || part.thoughtSignature.length === 0)
) {
outParts.push({ ...part, thoughtSignature: promoteSig.signature });
sigPromoted = true;
} else {
outParts.push(part);
}
} else {
anyProxy = true;
}
} else {
keep.push(true);
outParts.push(part);
}
}
if (!anyProxy) return "keep";
if (!anyProxy && !sigPromoted) return "keep";
if (!anyReal) return null;
return cloneChunk(parsed, { parts: parts.filter((_, i) => keep[i]) });
return cloneChunk(parsed, { parts: outParts });
}

function dataLine(frame: string): string | null {
Expand Down Expand Up @@ -440,21 +459,43 @@ export function createGoogleAdapter(
}
return;
}
// Gemini attaches thoughtSignature only to the FIRST functionCall
// part in a parallel-call turn. When a stripped proxy call (e.g.
// compress) led the turn and carried that signature, the first
// surviving real functionCall part becomes the turn's leading call
// on client replay and must inherit the signature or Gemini 3/4
// rejects the next turn with 400 INVALID_ARGUMENT (missing
// thought_signature).
let firstRealIdx: number | undefined;
let firstProxySig = "";
for (const [idx, tc] of pending) {
if (realIndexes.has(idx)) {
if (firstRealIdx === undefined && tc.name.length > 0) firstRealIdx = idx;
} else if (firstProxySig.length === 0 && tc.signature.length > 0) {
firstProxySig = tc.signature;
}
}
const firstRealTc = firstRealIdx !== undefined ? pending.get(firstRealIdx) : undefined;
const promoteSig =
firstRealIdx !== undefined && firstRealTc && firstRealTc.signature.length === 0 && firstProxySig.length > 0
? { callIndex: firstRealIdx, signature: firstProxySig }
: undefined;
for (const [idx, tc] of pending) {
if (realIndexes.has(idx) && tc.name.length > 0) {
toolCallsEmitted++;
const sig = tc.signature || (promoteSig?.callIndex === idx ? promoteSig.signature : "");
yield {
kind: "tool_call",
name: tc.name,
callId: tc.id,
arguments: tc.args,
passthrough: true,
...(tc.signature ? { signature: tc.signature } : {}),
...(sig ? { signature: sig } : {}),
} as ParsedStreamEvent;
}
}
for (const { json, parsed, callIndexes } of rawCallChunks) {
const filtered = filterRealCallChunk(parsed, realIndexes, callIndexes);
const filtered = filterRealCallChunk(parsed, realIndexes, callIndexes, promoteSig);
if (filtered === "keep") {
yield { kind: "meta", chunk: Buffer.from(`data: ${json}\n\n`, "utf8") } as ParsedStreamEvent;
} else if (filtered !== null) {
Expand Down
7 changes: 6 additions & 1 deletion src/loop/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1529,8 +1529,13 @@ export async function* runCompressLoop(
coreMessages.push(redactedMsg);
}
}
const roundProxySignature =
ctx.protocol === "google"
? proxyResults.find((p) => typeof p.signature === "string" && p.signature.length > 0)?.signature
: undefined;
for (const pr of proxyResults) {
if (functionCallIds.has(pr.callId)) {
const sig = pr.signature || roundProxySignature;
coreMessages.push({
id: `acp_loop_r${round}_asst_tc_${pr.callId}`,
role: "assistant",
Expand All @@ -1539,7 +1544,7 @@ export async function* runCompressLoop(
toolCallId: pr.callId,
// #3661: guaranteed-valid-JSON replay (see wireArguments); raw model bytes stay in pr.arguments for #156 signatures.
text: pr.wireArguments,
...(ctx.protocol === "google" && pr.signature ? { googleThoughtSignature: pr.signature } : {}),
...(ctx.protocol === "google" && sig ? { googleThoughtSignature: sig } : {}),
});
const toolResultMsg: CoreMessage = {
id: `acp_loop_r${round}_tool_${pr.callId}`,
Expand Down
24 changes: 23 additions & 1 deletion src/stream-google.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ function* rewriteGoogleJsonSteps(body: unknown, ctx: RewriteCtx): Generator<Json
if (!candidate || !content || !Array.isArray(parts)) return body;
let converted = false;
let sawReal = false;
let promotedSignature = "";
const noteParts: string[] = [];
const keptParts: GooglePart[] = [];
// Absorb signature in whole text (m00885): drop only when the request
Expand All @@ -33,6 +34,9 @@ function* rewriteGoogleJsonSteps(body: unknown, ctx: RewriteCtx): Generator<Json
const fc = part.functionCall as { name?: unknown; args?: unknown; id?: unknown } | undefined;
if (fc && typeof fc.name === "string" && isProxyToolFor(fc.name, ctx.session, ctx.config)) {
converted = true;
if (promotedSignature.length === 0 && typeof part.thoughtSignature === "string" && part.thoughtSignature.length > 0) {
promotedSignature = part.thoughtSignature;
}
const args = fc.args !== null && typeof fc.args === "object" ? (fc.args as Record<string, unknown>) : {};
noteParts.push(yield { name: fc.name, args, id: typeof fc.id === "string" ? fc.id : undefined });
continue;
Expand All @@ -53,10 +57,28 @@ function* rewriteGoogleJsonSteps(body: unknown, ctx: RewriteCtx): Generator<Json
if (typeof injection.text === "string") noteParts.push(injection.text);
}
if (!converted) return body;
// Gemini attaches thoughtSignature only to the first functionCall part in a
// parallel-call turn; if a stripped proxy call carried it, promote it onto
// the first surviving real functionCall part so client replay stays signed.
if (sawReal && promotedSignature.length > 0) {
const firstFcIdx = keptParts.findIndex((p) => p && typeof p === "object" && p.functionCall !== undefined);
if (firstFcIdx >= 0) {
const firstFc = keptParts[firstFcIdx]!;
if (typeof firstFc.thoughtSignature !== "string" || firstFc.thoughtSignature.length === 0) {
keptParts[firstFcIdx] = { ...firstFc, thoughtSignature: promotedSignature };
}
}
}
// The tool result is a NEW text part: an existing text part may carry a
// thoughtSignature the client echoes back, and appending to its text would
// leave the signature describing a string that no longer exists.
content.parts = [...keptParts, { text: noteParts.join("\n") }];
const notePart: GooglePart =
!sawReal &&
promotedSignature.length > 0 &&
!keptParts.some((p) => p && typeof p === "object" && typeof p.thoughtSignature === "string" && p.thoughtSignature.length > 0)
? { text: noteParts.join("\n"), thoughtSignature: promotedSignature }
: { text: noteParts.join("\n") };
content.parts = [...keptParts, notePart];
if (!sawReal) {
candidate.finishReason = "STOP";
}
Expand Down
Loading
Loading