Skip to content
Merged
4 changes: 3 additions & 1 deletion open-sse/executors/antigravity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -661,7 +661,9 @@ export class AntigravityExecutor extends BaseExecutor {
if (typeof p.text === "string" && p.text === "") return false;
if (p.functionCall && !p.functionCall.name) return false;

return !p.thought && (hasFunctionCall || !p.thoughtSignature);
// Only strip if it's NOT our bypass sentinel.
// Antigravity models (like Gemini) need this sentinel to bypass 400 errors.
return !p.thought && (hasFunctionCall || !p.thoughtSignature || p.thoughtSignature === "skip_thought_signature_validator");
}) || [];
return { ...c, role, parts };
}) || [];
Expand Down
59 changes: 14 additions & 45 deletions open-sse/translator/request/openai-to-gemini.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,8 @@ type GeminiToolNameOptions = {
// Gemini API DOES use `id` for Gemini 3+ signature matching, so this is scoped to
// the vertex provider only.
stripFunctionCallId?: boolean;
/** Only Antigravity/Gemini CLI support the thoughtSignature field. Standard Gemini rejects it with 400. */
supportsSignatureBypass?: boolean;
};

// Vertex AI (and Vertex Partner models) reject the OpenAI-style `id` field inside
Expand Down Expand Up @@ -234,7 +236,8 @@ function escapeHistoricalContextContent(value: string): string {

function buildHistoricalToolResultContext(name: string, response: unknown): string {
const source = escapeHistoricalContextAttribute(name || "unknown");
const rawResult = typeof response === "string" ? response : stringifyHistoricalToolArguments(response);
const rawResult =
typeof response === "string" ? response : stringifyHistoricalToolArguments(response);
const result = escapeHistoricalContextContent(rawResult);
return [
`<previous_tool_result_context source="${source}">`,
Expand Down Expand Up @@ -414,20 +417,6 @@ function openaiToGeminiBase(
if (!fn) continue;

const signatureForToolCall = resolvedSignatures.get(id);
if (!signatureForToolCall && contextualizeSignaturelessToolResponses) {
if (!toolCallIds.includes(id)) toolCallIds.push(id);
}
if (!signatureForToolCall && stringifySignaturelessToolCalls) {
const args = fn.arguments || "{}";
parts.push({
text: buildInertHistoricalToolCallText(fn.name, args),
});
continue;
}
if (!signatureForToolCall && signaturelessToolCallMode === "context") {
continue;
}

const args = tryParseJSON(fn.arguments || "{}");
const embeddedThoughtSignature = shouldUseEmbeddedSignature
? firstPersistedSignature || signatureForToolCall
Expand All @@ -438,18 +427,22 @@ function openaiToGeminiBase(
}

// Gemini expects the signature on the functionCall part itself.
// If we are in a mode where missing signatures cause 400s (and we couldn't find one),
// safely default to the bypass string to protect against 400s.
const finalSignature =
embeddedThoughtSignature ||
(toolNameOptions.supportsSignatureBypass && signaturelessToolCallMode !== "text"
? "skip_thought_signature_validator"
: undefined);
parts.push({
...(embeddedThoughtSignature ? { thoughtSignature: embeddedThoughtSignature } : {}),
...(finalSignature ? { thoughtSignature: finalSignature } : {}),
functionCall: {
...(toolNameOptions.stripFunctionCallId ? {} : { id: id }),
name: sanitizeToolName(fn.name),
args: args,
},
});

if (!contextualizeSignaturelessToolResponses || signatureForToolCall) {
toolCallIds.push(id);
}
toolCallIds.push(id);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

With the removal of the signatureless tool call evasion/text-context logic, the variables stringifySignaturelessToolCalls and contextualizeSignaturelessToolResponses (defined earlier in this function) are now unused/dead code. Additionally, hasSignaturelessTextResponses is redundant because toolCallIds now unconditionally contains all tool call IDs, making hasActualResponses equivalent to just checking toolCallIds.some((fid) => toolResponses[fid]). These unused variables and redundant checks should be cleaned up to maintain code readability and avoid dead code.

}

if (parts.length > 0) {
Expand All @@ -470,7 +463,6 @@ function openaiToGeminiBase(
const toolParts: GeminiPart[] = [];
for (const fid of toolCallIds) {
if (!toolResponses[fid]) continue;
if (contextualizeSignaturelessToolResponses && !resolvedSignatures.has(fid)) continue;

let name = tcID2Name[fid];
if (!name) {
Expand Down Expand Up @@ -503,30 +495,6 @@ function openaiToGeminiBase(
});
}

if (contextualizeSignaturelessToolResponses) {
// Signature-less historical tool responses are represented as text
// so strict Gemini/Antigravity endpoints don't reject them as native
// functionResponse parts missing a matching thoughtSignature.
// In context mode the matching historical functionCall is omitted,
// avoiding pseudo tool-call records that Gemini Flash can repeat as
// the visible final answer.
for (const tc of toolCalls) {
const id = tc.id as string;
if (tc.type !== "function" || !id) continue;
if (!resolvedSignatures.has(id) && toolResponses[id]) {
const fn = tc.function as { name?: string } | undefined;
const name = tcID2Name[id] || fn?.name || "unknown";
const resp = toolResponses[id];
toolParts.push({
text:
signaturelessToolCallMode === "text"
? buildInertHistoricalToolResponseText(name, resp)
: buildHistoricalToolResultContext(name, resp),
});
}
}
}

if (toolParts.length > 0) {
result.contents.push({ role: "user", parts: toolParts });
}
Expand Down Expand Up @@ -636,6 +604,7 @@ export function openaiToGeminiCLIRequest(
functionResponseShape: options.functionResponseShape,
signatureNamespace: options.signatureNamespace,
signaturelessToolCallMode: options.signaturelessToolCallMode,
supportsSignatureBypass: true,
});
}

Expand Down
4 changes: 3 additions & 1 deletion open-sse/utils/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,9 @@ export async function parseUpstreamError(response: Response, provider: string |

// Try parse as JSON
try {
const json = JSON.parse(text);
const parsed = JSON.parse(text);
// Handle array responses (e.g., from some Gemini APIs)
const json = (Array.isArray(parsed) && parsed.length > 0 ? parsed[0] : parsed) || {};
message = json.error?.message || json.message || json.error || text;
errorCode = json.error?.code || json.code;
errorType = json.error?.type || json.type;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@
import test from "node:test";
import assert from "node:assert/strict";

const { openaiToGeminiRequest } = await import(
"../../open-sse/translator/request/openai-to-gemini.ts"
);
const { openaiToGeminiRequest } =
await import("../../open-sse/translator/request/openai-to-gemini.ts");

function translateToGemini(messages, tools) {
return openaiToGeminiRequest(
Expand Down Expand Up @@ -90,7 +89,7 @@ test("T43: functionCall parts do NOT get a fake thoughtSignature injected", () =
assert.equal(
functionCallParts[0].thoughtSignature,
undefined,
"functionCall parts must NOT have a fake thoughtSignature injected"
"functionCall parts must NOT have a fake thoughtSignature injected (standard Gemini)"
);
});

Expand Down Expand Up @@ -135,7 +134,7 @@ test("T43: client-provided thoughtSignature is ignored in default enabled cache
assert.equal(
functionCallParts[0].thoughtSignature,
undefined,
"Client-provided thoughtSignature should be ignored in enabled cache mode"
"Client-provided thoughtSignature should be ignored in enabled cache mode (standard Gemini)"
);
});

Expand Down
36 changes: 36 additions & 0 deletions tests/unit/t44-antigravity-thought-signature-preserved.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,39 @@ test("T44: Antigravity still strips standalone thoughtSignature without tool cal

assert.deepEqual(transformed.request.contents[0].parts, [{ text: "plain text" }]);
});

test("T44: Antigravity preserves skip_thought_signature_validator bypass sentinel", async () => {
const executor = new AntigravityExecutor();
const transformed = await executor.transformRequest(
"gemini-3-flash",
{
request: {
contents: [
{
role: "model",
parts: [
{ thoughtSignature: "skip_thought_signature_validator" },
{
functionCall: {
id: "call_2",
name: "default_api:bash",
args: { command: "ls" },
},
},
],
},
],
tools: [{ functionDeclarations: [{ name: "default_api:bash" }] }],
},
},
true,
{ projectId: "test-project" }
);

const parts = transformed.request.contents[0].parts;
assert.equal(
parts.some((part) => part.thoughtSignature === "skip_thought_signature_validator"),
true,
"executor MUST NOT scrub the skip_thought_signature_validator bypass sentinel"
);
});
78 changes: 27 additions & 51 deletions tests/unit/translator-openai-to-gemini.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -688,34 +688,28 @@ test("OpenAI -> Antigravity Gemini omits signature-less historical tool calls an
false,
"signature-less historical call must not use executable textual tool-call markers"
);
// With skip_thought_signature_validator bypass, functionCall IS emitted natively
assert.equal(
modelTurn?.parts.some((part) => part.functionCall) ?? false,
false,
"signature-less historical call must not be emitted as native functionCall"
true,
"signature-less historical call MUST be emitted as native functionCall (bypass applied)"
);
assert.equal(
modelTurn?.parts.some((part) => part.thoughtSignature === "skip_thought_signature_validator") ?? false,
true,
"the bypass sentinel must be injected as thoughtSignature"
);

const toolTurn = result.request.contents.find(
(content) =>
content.role === "user" &&
content.parts.some(
(part) =>
typeof part.text === "string" &&
part.text.includes('<previous_tool_result_context source="default_api:todowrite_ide">') &&
part.text.includes("[]")
)
);
assert.ok(toolTurn, "expected signature-less tool response to be preserved as safe context");
assert.equal(
toolTurn.parts.some(
(part) => typeof part.text === "string" && part.text.includes("[Tool response:")
),
false,
"signature-less historical response must not use executable textual tool-response markers"
content.parts.some((part) => part.functionResponse)
);
assert.ok(toolTurn, "expected signature-less tool response to be preserved as native functionResponse (bypass applied)");
assert.equal(
toolTurn.parts.some((part) => part.functionResponse),
false,
"signature-less historical response must not be emitted as native functionResponse"
true,
"signature-less historical response MUST be emitted as native functionResponse (bypass applied)"
);
});

Expand Down Expand Up @@ -757,33 +751,20 @@ test("OpenAI -> Antigravity preserves multiple signature-less historical tool re
{ projectId: "proj-antigravity-gemini" } as any
);

const text = JSON.stringify(result.request.contents);
assert.equal(
text.includes("Historical tool-call record only"),
false,
"signature-less calls must not be emitted as visible historical text"
// With skip_thought_signature_validator bypass: native functionCall + functionResponse expected
const modelTurn = result.request.contents.find(
(c) => c.role === "model" && c.parts.some((p) => p.functionCall)
);
assert.ok(modelTurn, "expected native functionCall turns");
assert.equal(
text.includes("Tool arguments JSON"),
false,
"signature-less call arguments must not be emitted as visible text"
);
assert.ok(
text.includes('<previous_tool_result_context source=\\"terminal\\">'),
"expected signature-less responses as safe context"
);
assert.ok(
text.includes("data/db.json: No such file"),
"expected first signature-less tool response as context"
);
assert.ok(
text.includes("storage.sqlite"),
"expected second signature-less tool response as context"
modelTurn.parts.filter((p) => p.functionCall).length,
2,
"expected 2 functionCall parts"
);
assert.equal(
result.request.contents.some((content) => content.parts.some((part) => part.functionResponse)),
false,
"signature-less historical responses must not be emitted as native functionResponse"
result.request.contents.some((c) => c.parts.some((p) => p.functionResponse)),
true,
"signature-less historical responses MUST be emitted as native functionResponse (bypass applied)"
);
});

Expand Down Expand Up @@ -860,17 +841,12 @@ test("OpenAI -> Antigravity escapes signature-less tool response context content
{ projectId: "proj-antigravity-gemini" } as any
);

const text = JSON.stringify(result.request.contents);
assert.ok(text.includes("reader&quot;&gt;&lt;x&gt;"), "source attribute must be escaped");
assert.ok(
text.includes("before &lt;/previous_tool_result_context&gt;&lt;evil&gt; after"),
"context content must escape tag-like tool output"
);
assert.equal(
text.includes("before </previous_tool_result_context><evil> after"),
false,
"raw context-closing content must not be emitted"
// With skip_thought_signature_validator bypass: native functionResponse is emitted
// The legacy XML escaping is no longer needed since we send native functionResponse
const toolResponseTurn = result.request.contents.find(
(c) => c.role === "user" && c.parts.some((p) => p.functionResponse)
);
assert.ok(toolResponseTurn, "expected native functionResponse turn");
Comment on lines +844 to +849

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Since the legacy XML escaping assertions have been removed and replaced with a check for native functionResponse emission, the test name at line 817 ('OpenAI -> Antigravity escapes signature-less tool response context content') is now misleading. It should be renamed to accurately describe the new test behavior, e.g., 'OpenAI -> Antigravity emits native functionResponse instead of escaped XML context for signature-less tool responses'.

});

test("OpenAI -> Antigravity maps Claude-family models to Gemini-compatible schema", () => {
Expand Down