Claude Code sends {role: "system"} messages inside messages: one with the
environment after the first user message, and a notice after every tool
result, which stays in the history. buildContents moved all of them to the
end of systemInstruction. systemInstruction precedes the contents, so every
tool round changed the start of the prompt and Gemini's implicit prefix cache
matched only the tools and the fixed system prompt: in a Claude Code tool loop
on gemini-4-neon cache_read stayed at about 34k tokens of a 100k-200k token
conversation (9.4% of input tokens over 3947 requests).
System messages before the first model turn still go to systemInstruction.
Later ones stay at their position as <system-reminder> text at the end of the
user turn they follow; one that follows a model turn joins the next user turn
after its tool results, so a functionCall is still followed directly by its
functionResponse. System message text is trimmed in both wire forms, since
Claude Code sends the newest one as cache_control blocks and the same message
as a string once it is history.
The Vertex renderer commit let a non-thought part that carries only a
thoughtSignature (an empty text part, or a part with no text key) reach
the text path. On the Vertex path the text-part signature is dropped
since then, so the change has no effect there. On the antigravity
platform it added an empty thinking block for such a part: a stream whose
signature arrives in an empty final part ended [text, thinking("")], and
Claude Code reports an empty result for a turn that ends with a thinking
block. main renders [text].
Failure modes this commit guards against:
- Antigravity (zero options): "Hello world" followed by an empty final
part with a signature, or a part with only a signature, renders an
extra empty thinking block (stream with the signature in its own chunk,
and non-stream).
- Vertex options (marker prefix, text signatures dropped): the output
changes. A scratch probe over 8 part shapes (signature-only part before
text, after text, after thinking, between text and a call, after a
call; signed text; signed image), stream and non-stream, gives the same
bytes before and after this commit. With zero options the same probe
gives the bytes of main.
Changes:
- StreamingProcessor and NonStreamingProcessor: the text branch runs
again only for a part with text or a thought part, as on main.
Tests:
- New TestSignatureOnlyTextPartAddsNoBlock: [text] for both tail shapes,
stream (two chunks) and non-stream, with zero options and with the
Vertex options. The zero-option cases fail on the parent commit.
- TestProcessorsKeepSignatureOnlyPartsAndEmptyToolInput loses its two
signature-only cases and becomes
TestProcessorsKeepEmptyToolInputAndImageSignature.
- TestDropTextSignatures: with the drop off, a trailing empty signed part
now gives [text].
- TestThinkingSignaturePrefixMarksOnlyThinkingBlocks: the carried text
signature now comes from a signed non-empty text part, so the test still
checks that the carrier thinking block gets the prefix.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Gemini 3 and later put a thoughtSignature on the last part of a turn. When
that part is text (or an empty text part, as streaming does), the
antigravity processors emit an empty thinking block after the text only to
carry the signature. A final Vertex turn then ends [text, thinking("")],
and Claude Code reports an empty result for it, because it reads the last
block. Headless callers that read the result get "".
Vertex enforces signatures only on functionCall parts. A missing signature
on a text part causes no error ("The API does not strictly enforce
validation for signatures in non-functionCall parts"), see
https://docs.cloud.google.com/vertex-ai/generative-ai/docs/thought-signatures
So on the Vertex-account path the text-part signature is dropped.
Failure modes this commit guards against:
- A Vertex text turn with a signature on its text part, or in a trailing
empty text part, ends with an empty thinking block (stream and
non-stream).
- An empty thinking block is emitted between text and a function call, or
after a function call, only to carry a text-part signature.
- A real thinking block loses its signature (signature_delta), or loses the
vertex-thought-v1 marker.
- A function call loses tool_use.signature.
- Text is lost or reordered when its signature is dropped.
- The antigravity platform output changes: it must still emit the empty
thinking block with the raw signature.
Changes:
- pkg/antigravity: ResponseTransformOptions.DropTextSignatures and
StreamingProcessor.SetDropTextSignatures. When set, a non-thought text
part is processed without its signature. The zero value keeps today's
output.
- streamGeminiSSEAsClaude takes antigravity.ResponseTransformOptions
instead of the prefix string, so stream and non-stream use one option
set. The antigravity platform passes the zero value.
- G: geminiVertexResponseOptions (the vertex-thought-v1 marker plus
DropTextSignatures) for the Vertex stream and non-stream renderers, the
same switch as the marker.
Tests (go test -tags=unit):
- pkg/antigravity TestDropTextSignatures: 5 cases, stream and non-stream,
drop on and off. Text-part signature, trailing empty part, real thinking
plus signed text, signed text before a function call, and text split
around a signed part. With the drop on, there is no empty thinking
block; thinking and tool_use signatures stay, and the text stays in
order. With it off, the output is today's.
- service TestGeminiCompatForward_VertexTextPartSignatures: a real Forward,
stream and non-stream. A text turn renders [thinking(marker+sig), text
"PROBE_DONE"] with no text signature; a call turn renders [text,
tool_use(SIG_CALL)] with no empty thinking.
- service TestAntigravityClaudeStreamKeepsTextSignatureCarrier: the
antigravity handler still emits [text, thinking] with the raw signature.
- Updated to the new rule: the Vertex render test no longer expects the
trailing SIG_TAIL thinking block after tool_use. The Vertex signature
test now gets its marked signature from a thought part, and checks that
the text-part signature is not sent.
After a switch from Claude to Gemini in the middle of a session, the history
holds thinking blocks with Anthropic signatures. The converter carries any
real thinking signature as thoughtSignature, so Vertex gets a foreign
signature, answers with a signature 400, and Forward retries with the
thinking blocks downgraded. That costs one extra upstream call on every
request for the rest of the session. tool_use.signature is not affected:
Anthropic tool_use blocks carry no signature.
Failure modes this commit guards against:
- A thinking signature from another upstream (no marker) reaches Vertex as
thoughtSignature on a text or functionCall part.
- A thinking signature that the Vertex path emitted no longer round-trips:
the marker reaches Vertex, or the signature is dropped.
- A marker in front of an empty or skip_thought_signature_validator
signature is carried.
- tool_use.signature changes on the Vertex path.
- The Vertex response sends a thinking signature without the marker, or
marks tool_use.signature.
- The signature-error retry rebuilds the request without the rule.
- The antigravity platform changes: its /v1/messages responses and its
compat path (which uses the same converter) must keep raw signatures.
Changes:
- Vertex responses (stream and non-stream) send thinking-block signatures
as "vertex-thought-v1:" + signature. tool_use signatures stay raw.
- pkg/antigravity: StreamingProcessor.SetThinkingSignaturePrefix and
TransformGeminiToClaudeWithOptions(ResponseTransformOptions). The zero
value keeps today's output; the antigravity callers do not set them.
- convertClaudeMessagesToGeminiRequest(body, model, markedThinkingSignatures):
Forward sets it for Vertex accounts, on the first request and on the
signature retry. With it set, a thinking signature is carried only when it
has the marker, and without the marker. Without the marker the block falls
back to today's handling: no signature on text, the dummy on a call.
convertClaudeMessagesToGeminiGenerateContent keeps the old behaviour for
every other caller.
Histories written by the Vertex path before this commit carry unmarked
signatures. They now fall back the same way, which costs only reasoning
continuity on those old turns.
Test changes: three assertions in gemini_messages_vertex_render_test.go now
expect the marker on thinking signatures. tool_use.signature assertions are
unchanged.
New: gemini_messages_vertex_signature_test.go,
pkg/antigravity/thinking_signature_prefix_test.go.
The antigravity response processors, which now also render Vertex
/v1/messages responses, mapped every finish reason except MAX_TOKENS to
end_turn (or tool_use). A blocked or broken turn then looked like a
successful empty answer: Claude Code ends the turn and the run reports
success.
Failure modes this commit guards against:
- SAFETY, PROHIBITED_CONTENT, SPII, BLOCKLIST, IMAGE_SAFETY or RECITATION
ends as end_turn. It is now stop_reason "refusal", in stream and
non-stream.
- A prompt blocked by promptFeedback.blockReason, with no candidates, ends
as end_turn. It is now "refusal".
- MALFORMED_FUNCTION_CALL, UNEXPECTED_TOOL_CALL, TOO_MANY_TOOL_CALLS or
MALFORMED_RESPONSE with no text and no tool_use ends as an empty
end_turn. Thinking blocks do not count as content: with thinking on, a
thought summary comes before almost every invalid call. The stream now
ends with an SSE error event of type api_error, which Claude Code
retries. Non-stream returns ErrMalformedFunctionCall or
ErrInvalidOutputWithoutContent, which callers write as a 502.
- The same reasons after text or a tool call must still end normally
(end_turn, or tool_use after a call). Non-stream MALFORMED_FUNCTION_CALL
with text now gives end_turn too; the antigravity collect path still
fails it before conversion, as before.
- After the error event, no later chunk may emit content, message_delta or
message_stop, and the usage must still be collected for billing.
- STOP, MAX_TOKENS, OTHER and tool calls without a refusal reason keep
their mapping. A refusal reason wins over tool_use.
Only the mapping changes; no safetySettings are added. Effects on the other
antigravity paths:
- Claude, chat-completions and responses non-stream now return 502 for
UNEXPECTED_TOOL_CALL, TOO_MANY_TOOL_CALLS and MALFORMED_RESPONSE without
text or tool calls, where they returned an empty 200 before.
- The chat-completions and responses stream adapters buffer the error event
like the empty end_turn before it, so they still report an empty stream.
- Not mapped, and so still end_turn: MODEL_ARMOR, IMAGE_PROHIBITED_CONTENT,
IMAGE_RECITATION, IMAGE_OTHER, NO_IMAGE and CONTINUATION.
Tests: pkg/antigravity/finish_reason_test.go (stream and non-stream per
reason), gemini_messages_vertex_finish_test.go (Vertex /v1/messages through
Forward).
Vertex accounts (service account JSON and API key) on /v1/messages keep the
Gemini compat request converter and the Vertex transport. Their responses are
now rendered by pkg/antigravity's StreamingProcessor (stream) and
NonStreamingProcessor (non-stream), the same processors that the antigravity
compat path already uses for gemini-* models. Both read plain Vertex
responses with no v1internal wrapper. Other account types keep the compat
emitters unchanged.
Failure modes this commit guards against:
- The client usage carries no cache_read_input_tokens when Vertex reports
cachedContentTokenCount. Claude Code then starts auto-compaction late or
never, and long sessions fail.
- The thoughtSignature of a functionCall part does not reach
tool_use.signature, so the next turn falls back to the dummy signature.
- The signature of a thought part is not sent as a signature_delta.
- A signature that arrives in a final empty text part is lost. Vertex
documents that a stream can return the signature this way. The
antigravity processors had the trailing-signature branch, but processPart
never reached it for an empty text part.
- Non-stream: no thought text (includeThoughts was set for stream only), no
signatures, and a call without args has no input object.
- A text chunk that is a prefix of earlier text is dropped as a duplicate.
- Web search grounding sources (groundingMetadata) never reach the client.
- Billing drifts: the recorded usage must still come from the upstream
usageMetadata (input minus cached, cache read, output plus thoughts, image
output tokens), and image outputs must still be counted.
- An empty upstream stream must fail over before a byte reaches the client.
- A client that leaves before any usage arrives must stay unbilled, as in
the compat stream handler.
- Non-Vertex accounts must keep the compat emitter.
Changes:
- AntigravityGatewayService.handleClaudeStreamingResponse becomes a thin
wrapper around streamGeminiSSEAsClaude(cfg, observeLine). The antigravity
path passes its own config and line observer, so its behaviour does not
change.
- GeminiMessagesCompatService.Forward: for Vertex accounts, the stream is
rendered by streamGeminiSSEAsClaude, and the non-stream body by
antigravity.TransformGeminiToClaude. Model, image and usage observation
per upstream payload stay as in the compat emitters, so billing keeps its
source. includeThoughts is also requested for non-stream calls.
- pkg/antigravity: a tool_use with no args serializes "input": {}, and a part
that carries only a thoughtSignature reaches the trailing-signature path.
An image part keeps today's behaviour.
The non-stream path keeps upstream generateContent, so the existing Vertex
endpoint tests still apply unchanged.
Behaviour changes beyond the fixes:
- The signature-only part fix is in pkg/antigravity, so the antigravity
platform's own Claude responses now also carry such a signature as an
empty thinking block, where it was dropped before.
- Vertex image models on /v1/messages now return generated images as
markdown data-URL text, as the antigravity processors render them. The
compat emitter did not forward images on this endpoint.
Tests: gemini_messages_vertex_render_test.go (Forward with a Vertex API key
account and scripted Vertex chunks), pkg/antigravity/signature_part_test.go.
Add top-level CacheControl to apicompat.AnthropicRequest and inject {"type":"ephemeral"} on Chat Completions to Anthropic API-key forwarding paths for Claude models, respecting explicit client cache_control overrides and null/false opt-out. Also count top-level cache_control objects toward Anthropic's 4-breakpoint limit in enforceCacheControlBlockLimit.
ResponsesToAnthropicRequest defaults max_tokens to 8192 when the
Responses request has no max_output_tokens, and turns any effort above
low into thinking.type=enabled with an effort-derived budget: 10240 for
high, 32768 for xhigh/max. Anthropic requires max_tokens to be greater
than budget_tokens, so every effort above medium was rejected with
"budget_tokens must be less than max_tokens". Codex never sends
max_output_tokens, so its users could not work around it.
After the conversion, raise max_tokens to budget_tokens + 1000 when an
enabled budget does not fit, the same rule and padding the Antigravity
transformer applies in ensureMaxTokensGreaterThanBudget. Requests that
already fit, adaptive thinking, and requests without thinking are
unchanged.
Fixes#6569
The admin "Test" button for web search emulation always showed
"internal error". Manager.TestSearch dropped every provider's error with
a bare `continue` and returned "no available provider", and the handler
passed that plain error to response.ErrorFrom, which maps it to a 500
with the generic message. A wrong key, an exhausted plan, a proxy
failure and an unsaved config all looked the same.
Keep each provider's error in TestSearch and join them when every
provider fails, and return the cause from the handler as a 400, the
same way the SMTP connection test already does. TestSearch is admin
only; the production SearchWithBestProvider path is unchanged.
Refs #7201
Tavily's /search endpoint documents a single credential scheme,
`Authorization: Bearer <key>`, and its official Python/JS SDKs send only
that header. The provider still put the key in an `api_key` body field
and sent no Authorization header, so web search emulation through
Tavily relied on an undocumented contract. Brave and Exa in the same
package already send their keys as headers.
Send the key as a Bearer token and drop it from the request body. The
old unit test only marshalled the request struct and asserted the body
`api_key`, so it locked in the stale contract without exercising
Search(); replace it with a test that drives Search() through a
recording transport and checks the outgoing headers and body.
Refs #7201
Google AI Studio OpenAI-compatible streams send parallel tool calls
without an index, each whole in its own chunk with its own id. A missing
index defaulted to 0, so both calls merged into one item with arguments
like {"cmd":"ls"}{"cmd":"date"} and the stream failed with
invalid tool call arguments (502). Without an index, continue the last
call when the delta has no id or the same id, otherwise open the next
contiguous slot. Indexed streams are unchanged.
Anthropic reports thinking tokens in usage.output_tokens_details.thinking_tokens,
a subset of output_tokens. AnthropicUsage had no such field, so Anthropic
accounts served through /v1/chat/completions and /v1/responses never exposed
reasoning_tokens.
Decode the field, carry it through the stream state and the buffered
ClaudeUsage merge (a reported value, even 0, replaces the previous one), and
emit it as Responses output_tokens_details.reasoning_tokens, which the existing
Responses-to-Chat mapping turns into completion_tokens_details.reasoning_tokens.
Billing is unchanged.
Fixes#9048
Count provider-owned, non-business-limited rows in ops_error_logs per
account (same definition as the ops dashboard) and expose them as
`upstream_errors` on today stats and per-day account usage history.
- Today stats column shows today's upstream errors (highlighted when > 0).
- Usage statistics modal adds an upstream error trend line plus today and
30-day totals; days with only errors are merged into the history.
- Counts are omitted when ops monitoring is disabled so the UI hides them
instead of showing a misleading 0. Failover intermediate attempts are
attributed only to the last failing account.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Build the conflict path by appending to a byte slice instead of ignoring
strings.Builder write results, and discard builder results explicitly in
tests. golangci-lint v2.14.0 (CI version) reports 0 issues.
Refs: GHSA-p3r4-jcm3-2hph
Go's mime parser prefers name*= over name=, so a part declared as
name="model"; name*=UTF-8''prompt is read as prompt by the gateway (no
model candidate reaches the group allowlist) but as model by an upstream
that ignores extended parameters. Reject parts whose Content-Disposition
carries name*, name*0 or name*0*. filename* stays allowed: it is the
standard way to send a non-ASCII file name.
Refs: GHSA-p3r4-jcm3-2hph
A re-audit of ce86c1b30 found, and running code confirmed:
- scanJSONString re-scanned to the closing quote after every escape, so
scanning was quadratic in escapes (200k "\n": 0.56 s; a 10 MB code-like
body: 24 s). It now visits each quote once and counts the backslashes
before it: 6 us and 0.7 ms for the same bodies.
- A multipart body with a JSON preamble (RFC 2046; skipped by Go's
multipart reader) took the JSON branch only, bypassing both the group
allowlist and the multipart duplicate check. A multipart Content-Type
now always runs the multipart check, FromBodyCandidates merges JSON and
multipart candidates, and a body that is both JSON and a form with parts
is rejected as ambiguous. The JSON scan stops after the first top-level
value, matching gjson, so binary file parts are never tokenised.
- LooksLikeJSON now skips every byte <= 0x20 before the first value, as
gjson does.
- Freeform key spaces gained variables, headers, dependentRequired,
dependencies and labels, matched on the decoded name. metadata is no
longer freeform: Antigravity binds metadata.user_id case-insensitively
while sticky sessions read it with gjson.
- Multipart also rejects file parts named model/session, parts without a
parsable name, and parts carrying two Content-Disposition headers, and
counts file and text parts with the same name together.
- WebSocket: passthrough forwards session.update and every other client
event verbatim, and dedicated parsing reads fields from the raw frame
before any re-encode. Both now reject a frame with repeated fields
before reading it.
- The linear-compare limit rises to 32 to cut map churn for mid-sized
objects.
Tests that relied on duplicates passing now assert rejection: a dedicated
WS recovery test that sent two previous_response_id keys, and WS
allowlist cases whose close reason comes from the earlier duplicate check.
Refs: GHSA-p3r4-jcm3-2hph
An independent audit of the conflicting-field fix found, and running code
confirmed, the following. Each is fixed here.
- A JSON body labelled multipart/form-data skipped the check: the JSON
branch was chosen from the Content-Type header, but JSON handlers never
look at it. ConflictingField and FromBodyCandidates now detect JSON by
content. The same header-only branch, and a UTF-8 BOM prefix (stripped by
the handlers' lenient reader), also let a body bypass the group model
allowlist on main; both are closed.
- Identical duplicates passed and the gateway's own sjson rewrites then
split them: reasoning-effort downgrade, model mapping and the fast-policy
service_tier delete only touch the first occurrence. Every repeated member
is now rejected, whatever its value. Multipart rejects repeated scalar
fields (model, n, size, ...) except list fields (name[], image,
image[...], image_url).
- Nested case variants bound case-insensitively by struct-based protocol
conversions ({"reasoning":{"effort":"low","Effort":"xhigh"}}). Members
are now folded at every depth, except inside user-defined key spaces
(JSON Schema properties/$defs, tool arguments, metadata, ...), where id
and ID are distinct and only exact repeats are rejected.
- The recursive walker cost depth x size (1 MB at depth 9990: 1.6 s) and
stored every key as a string (~16x the body). It is replaced by one
linear byte scan with an explicit stack that compares 64-bit hashes
(random per-process seed) of the decoded, folded names: 0.6 ms for the
same body, ~3.7 GB/s on a Claude Code-shaped body. Subtrees deeper than
10000 levels are bracket-counted, so later same-level members are still
checked.
- text_max_body_size no longer bounded what group middleware buffered:
the route-level limit ran after them. The limit is now chosen per route
at group level.
- Body read failures in gateway middleware answered in the OpenAI shape
with a different message than the handlers. They now use the entry
protocol's shape and the handler's "limit is N" message. Rejections
are recorded as ingress reason conflicting_request_fields.
- The middleware strips a leading BOM and restores the body, so composite
routing and handlers parse the bytes that were checked.
Refs: GHSA-p3r4-jcm3-2hph
The first pass checked top-level members and the session object only.
Nested fields drive billing and policy as well: reasoning.effort selects
the reasoning-effort billing multiplier and the group effort ceiling, yet
gjson reads the first occurrence, sjson downgrades only the first, and
map re-encoding keeps the last. {"reasoning":{"effort":"low",
"effort":"xhigh"}} therefore passed admission as low and could be served
as xhigh.
ConflictingField now also walks every nested object, including array
elements, and reports the first member that repeats with a different raw
value by path (reasoning.effort, messages[1].role). Nested names are
compared exactly after unescaping, without case folding, because user
data such as tool JSON Schemas may legitimately carry both id and ID.
Identical duplicates still pass. The walk stops below encoding/json's
10000-level limit and only allocates a path string on conflict
(~660 MB/s, 9 allocs for a 225 KB Claude Code-shaped body).
Responses WebSocket frames now apply the full ConflictingField rule
instead of comparing model candidates only, so service_tier and nested
reasoning.effort conflicts close the connection as on HTTP.
Refs: GHSA-p3r4-jcm3-2hph
A body such as {"model":"cheap",...,"model":"expensive"} was scheduled and
billed under the first model, while paths that decode and re-encode the
body forwarded the last one. gjson returns the first member with a name;
encoding/json keeps the last and matches struct fields case-insensitively.
The group allowlist already validates every model candidate, but billing
did not, and groups without an allowlist had no check at all.
RejectConflictingRequestFields runs on every gateway chain after the
allowlist and before the composite rewrite. It answers 400 when a
top-level JSON member, a member of the session object, or a multipart
model/session field is declared more than once with different values.
Repeated fields with identical values still pass, as they do in the
allowlist. Responses WebSocket frames apply the same rule to their model
candidates on the first frame and on later turns.
The source-level chain assertion in gateway_model_allowlist_test.go is
updated for the new middleware position.
Not covered: repeated non-model members inside WebSocket frames (an
existing test accepts a repeated previous_response_id there), and nested
objects other than session.
Refs: GHSA-p3r4-jcm3-2hph
Co-Authored-By: claude-mythos-5-2 <noreply@anthropic.com>