Commit Graph
22 Commits
Author SHA1 Message Date
yetone 320af98581 gateway: an upstream's error in a shape its decoder can't read fails the reply, so Codex tries again (#1933, tensornull)
A translated stream whose upstream said it failed, but not in the shape
its protocol's decoder reads, ended as a completed reply with no output
and zero usage. Codex took that as its turn's end (exit 0, no message)
and never used its stream retry. tensornull's three fixtures, on an
Anthropic provider asked from Codex's Responses:

- {"type":"error","error":"fixture upstream failure"}: decodeAnthropic's
  struct wants an object for error, so the event decoded to nothing,
  while upstreamEnds counted the type "error" as the reply's end.
- Messages events with their type left out (named only by "event:"):
  the decoder read nothing, and upstreamStop's delta.stop_reason still
  marked the reply ended.
- A Responses response.failed from the Anthropic endpoint: upstreamEnds
  took any protocol's last event, and the Anthropic decoder ignores it.

Now:
- replyEnds (upstream.go) reads a reply's end in the protocol it was
  asked in: Anthropic's message_stop, error or a message_delta's
  stop_reason; Responses' response.completed/incomplete/failed or error;
  Gemini's finishReason; Chat's finish_reason. The other two fixtures no
  longer read as whole and end as errEndedShort, a failure the gateway
  and the client retry, like the "ping then EOF" control. It replaces
  upstreamEnds in both the streaming loop (continuation.go) and the
  unstreamed one (gateway.go).
- carriedError: every decoder (Anthropic, Responses, Chat, Code
  Assist/Gemini) that can't decode an event still tells an error it
  carries ({"error":"…"}, type error, response.failed) as KError with
  its words. Siblings found the same way: a Chat upstream's
  {"error":"…"} chunk ended a translated reply as completed; a Responses
  upstream's string error or a response.failed with no error object
  (status failed) did too, read as stop.
- An error event with no message says its type or the event itself,
  never "".

One test's fixture changed with it: TestTranslatedEffortLoggedAsSent
served Chat chunks from its Responses upstream, which the Responses
decoder reads as nothing. It "completed" only because a finish_reason
counted as the end, the same empty success this fixes, so it now fails
with errEndedShort. The case gets a Responses reply (responsesHi).

What a whole reply does is unchanged: a valid Messages text reply, and
Claude's empty end_turn (asked of in the report), still complete on the
first ask (TestWellFormedStreamsStillComplete).

Run: the new tests in stream_error_shape_test.go use the report's bytes
(event: lines included). Against origin/main's code (fix reverted, tests
kept) 8 subtests fail: anthropic error string, error object with no
message, events with no type, responses failure on the messages route,
chat error string, both Responses-upstream cases, and the unstreamed
client; the error-object control and the well-formed ones pass on both.
With the fix all pass. go test -tags nogui -timeout 40m ./internal/gateway (sandbox
HOME, caches pinned); gofmt -l; go vet darwin, GOOS=linux -tags nogui,
GOOS=windows. tensornull's reproduce.py against a nogui build of this
tree: error-string now ends response.failed "fixture upstream failure"
after 3 gateway attempts, the same as the error-object control (was
response.completed after 1). Not run: the Codex CLI replay; a Responses
client asking a Responses upstream is passed its bytes as they are, so
that pairing is unchanged.
2026-10-13 14:48:49 +08:00
yetone a64b3a8d46 plugin: a pi provider's message_start tells the prompt's usage pi's start named, so Claude Code's context meter isn't 0 until the turn ends (#1887)
What: pi.js wrote message_start with usageOf() and no argument, so every
field was 0 until message_delta. Claude Code's context meter reads the
usage the assistant message has so far, and a turn interrupted before
message_delta was stored with 0. message_start now carries the vendor's
prompt (input, cache read, cache write) and the output pi's start named
(startUsage): from pi's start event's partial.usage, as the issue
describes, or, as pi-ai's anthropic-messages pushes start before it reads
the vendor's message_start (start's usage is still 0 then), from the
partial message the events after it share. That message is pi's own,
still being written (by the time magpie reads it pi may have pushed the
whole turn), so only its prompt is taken from it, never its output.
message_delta is unchanged: the whole turn's cumulative usage from done.

Siblings, the gateway's translators to Anthropic's stream:
- Gemini / Code Assist (codeassist.go): usageMetadata rides on the first
  chunk, but KStart was emitted before reading it. KStart now carries the
  prompt (input, cached); output stays 0 there.
- Chat Completions (chat.go): most streams count only at their end, so
  nothing to tell; a stream that counts on its first chunk now has its
  prompt on KStart.
- Responses: response.created has no usage. Anthropic-to-Anthropic and the
  Claude subscription already carry it. Cursor, Kiro, Devin, Qoder,
  Command Code send KStart before any usage is known.

Ledger: no double count. The usage sniffer and the collector both take
each field's latest non-zero value (Usage.add replaces, it doesn't sum),
and continuation/search take a try's KStart usage as its own (this =
ev.Usage) and KUsage replaces it. message_delta's input equals
message_start's, which Anthropic's clients also take as the same count.

Run (Go 1.26.8, darwin):
- TestPiPackage with a fake pi stream as the issue's (start with
  partial.usage input 11, cache 3/2, output 0, text, done with output 7):
  message_start 11/3/2/0, message_delta 11/3/2/7; and pi-ai's order
  ("late": start with zero usage, then the shared message counted):
  message_start 11/3/2/0. Red with message_start back on usageOf(), and
  the late case red when only start's usage is read.
- TestPromptUsageOnMessageStart (Gemini, chat counting per chunk, chat
  counting at the end): red with codeassist.go and chat.go stashed.
- go test ./internal/plugin and ./internal/gateway in full (-timeout 28m;
  the default 10m timed out under load average ~20). The disk filled
  during the run (3.7G free, not this change's): every failure was
  ENOSPC, and each of them (37 gateway, TestFakePlugin) passed on rerun.
- gofmt -l; go vet for darwin, linux and windows on both packages.
Not tried against a real pi vendor or Claude Code's meter.

Reported-by: guoqchen1001
2026-10-13 10:29:31 +08:00
440fded2dc gateway: a turn stopped with its tool call out is answered on Google's APIs, not refused by them (#1560, ggbdpq)
What changed: a client replaying a conversation whose turn was
interrupted with the tool call still out — the call in the history, no
result for it — had every later turn refused by Google's APIs with 400
"Please ensure that the number of function response parts is equal to
the number of function call parts of the function call turn", the
conversation with it, however it was routed: a Google sign-in (Code
Assist), Vertex AI, a custom provider's Gemini URL (#1346) and a model
pinned to Gemini (9e823ad4) all build on buildCodeAssistSent, which
sent the call as it was. The chat build answers such a call with a
synthetic result (pairToolMessages, #1275) and the Responses relay
pairs its items (pairToolItems); the Gemini build now does the same
(pairFunctionTurns). A history whose every call is answered is built
byte for byte as before.

Changed in review (yetone's session): the patch put the synthetic
functionResponse at the head of the next user turn, which is usually
the user's text ("continue"). Since #1533 (ce11b1801, after the
patch's base) Gemini's build never sends a turn mixing a
functionResponse with text, which Vertex AI answers "Requests ending
with a model turn are not supported". The answer now goes beside the
client's own answers when the next turn holds some, and otherwise in a
user turn of its own before the user's words; a Claude model on
Antigravity keeps the one tool_result turn as #1533 does. A call with no
id is no longer answered twice when the client answered it by name. The
fake upstream now also refuses a mixed turn with Vertex's literal 400,
and TestPairFunctionTurnsShapes pins the four placements.

Run (review): the patch as sent, with the stricter fake, FAILS
TestGeminiInterruptedCallIsAnswered and
TestGeminiMessagesClientInterruptedCall with "Requests ending with a
model turn are not supported"; with the rework they pass, and with the
pairFunctionTurns call removed the three interrupted-call tests FAIL
with Google's literal 400 while TestGeminiAnsweredCallsUnchanged
passes. go test -tags nogui -run
'TestGemini|TestVertex|TestCodeAssist|TestAntigravity|TestAgy|TestPairFunction|TestCompact'
./internal/gateway ok. The full suite, gofmt and the cross-OS vets are
in the series' last commit.

Author's run: the four tests red/green as above; -race -count=20; go
test ./... (all ok but internal/testenv TestOffline, offline machine);
gofmt; go vet on darwin, linux, windows; go build on all three.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Co-authored-by: yetone <yetoneful@gmail.com>
2026-10-11 13:35:56 +08:00
yetoneandump45nose ce11b18015 gateway: Codex compacts on Gemini after a tool's output, no "Requests ending with a model turn" (#1533, yycsyu)
What the user saw: Codex on Google Vertex AI (gemini-3.8-flash) failed
every compaction that came right after a tool's output with
"Google Vertex AI: Requests ending with a model turn are not supported."

Why: codexInput turns compaction_trigger into a user message holding the
compaction prompt; mergeTurns and then buildCodeAssistSent merged it with
the function_call_output's user turn, so Gemini got one user content
holding a functionResponse and text. Vertex answers that with the
"ending with a model turn" 400 although the last role is user; #1533
showed the same history with the two as separate user contents gets 200.

What changed:
- buildCodeAssistSent (every Gemini-shaped request: Vertex AI, Factory's
  Gemini, Gemini CLI's and Antigravity's Code Assist, Google sign-in)
  puts what the user said after tools' responses in a user turn of its
  own, and never merges text into a responses turn or the other way.
  Tools' images stay with their response; parallel calls' responses stay
  in one turn. A Claude model on Antigravity keeps its single tool_result
  turn as before.
- It also never ends contents with the model's turn: a user turn goes
  after it ("Continue.", or compactLastText when an agent compacts with
  the ask in its system prompt). prefillRefusal knows Gemini's wording.
- docs/subsystems/gateway-routing.md says both.

Tests: gemini_model_last_test.go uses #1533's exact Responses request
(read_sample / call_diagnostic_1 / compaction_trigger) on /v1/responses
and Codex's path against a fake Vertex that refuses as the real one did;
with the split disabled it fails with the reporter's exact message, and
TestGeminiToolResponseTurnHoldsNoText fails for all four builders.
ump45nose's fork patch on #1533 (93a2afca) found the same cause and
split the turn on Vertex AI only; this does it for every Gemini builder,
and takes its Anthropic case (a tool_result beside text in one message)
into the end-to-end test, which fails on the old code too.
TestBuildCodeAssistForGemini, TestCodeAssistToolImagesAfterEveryResponse
and TestGeminiHistoryOpeningWithModel held the old one-turn merge (from
637b2458, a choice, not a fix for a report) and now expect the question
in a turn of its own.

Run: go test ./internal/gateway ./internal/provider, the full
go test -tags nogui ./... (queue lock), gofmt -l, go vet -tags nogui for
darwin, linux and windows.
Not tried against real Vertex AI: no Vertex credentials on this machine.

Co-authored-by: ump45nose <52391318+ump45nose@users.noreply.github.com>
2026-10-11 04:33:03 +08:00
wei 5a27b924e2 providers, gateway: Google Vertex AI is a preset, Gemini in the user's own Google Cloud project, signed with their Google credentials rather than a key
Gemini on Vertex AI was reachable only through a proxy of the user's own
in front of Vertex AI's OpenAI-compatible endpoint, added as a custom
provider. The Google Vertex AI preset (google-vertex) asks Vertex AI
itself.

  * The provider holds a project, a location (global when none is given;
    us, eu or a region), an optional credentials file and an optional
    service account to go as (provider.Vertex). It has no key and no
    URL: Save refuses a key, normalize clears a key and the four URLs
    kept by hand, and its one address is
    https://<host>/v1/projects/<project>/locations/<location>, the host
    following the location (vertexHost). It is ready when it has a
    project, never for a key or an account, and an import link can't add
    it.
  * Each request is signed with a Google token (Sign), and the token goes
    to no other address. The credentials are found as Google's libraries
    find Application Default Credentials: the provider's file, else
    GOOGLE_APPLICATION_CREDENTIALS's, else gcloud's
    application_default_credentials.json. A GOOGLE_APPLICATION_CREDENTIALS
    that isn't a full path is an error, not unset, since gcloud's file
    read in its place may be another account's. authorized_user,
    service_account and gcloud's impersonated_service_account are read;
    external_account and another universe are refused by name. With a
    service account set, the token is traded at IAM Credentials'
    generateAccessToken for one of that account's, as gcloud's
    --impersonate-service-account does. Tokens are kept in memory per
    file and account, minted once for requests made together, again 5
    minutes before they expire or when the file changes (gcloud signed
    in again). A mint is given 30 seconds; one that fails fails the
    requests that waited through it too, and a request given up on
    stops waiting. A sign-in Google refuses says the command that makes
    that file again: gcloud's for its own files, impersonating as it
    did.
  * The gateway speaks Gemini to it alone. A Gemini client's request is
    relayed as it came, its thinkingConfig, safetySettings and schema
    with it: streamed to
    publishers/google/models/<model>:streamGenerateContent?alt=sse, or
    asked whole to :generateContent. Every other API's is translated
    (buildVertex), streamed, and read back with thoughts as reasoning,
    never as the answer. The path names a model by its upstream name
    when one is set, as the usage log's endpoint does. Gemini 3 is sent a thinkingLevel fitted to the
    model's levels, 2.5 a thinkingBudget in the model's range, off
    included (Pro's least, as Pro can't stop). A call's thought
    signature goes to the client in its id and comes back on the call;
    a 400 "Invalid thought signature." is asked again with every call
    waved through, for that request, and a 400 refusing minimal is asked
    again at the model's lowest level, kept until restart. Neither is
    tried for another provider.
  * Vertex AI has no list of the models a location serves, so each
    location has the ones it answered with on 2026-10-06: 12 at global,
    6 Flash at us and eu, the 2.5 trio at a region.
  * The preset offers Priority PayGo's and Flex PayGo's request headers
    (HeaderHints). GOOGLE_APPLICATION_CREDENTIALS and CLOUDSDK_CONFIG are
    in agentenv.Vars, so the desktop app takes them from the login shell
    and the tests clear them.

Not read: the metadata server of Compute Engine, Cloud Run and GKE;
workload identity federation; Vertex AI's express-mode API keys. No
quota project is sent.

Reference: docs/subsystems/providers-accounts.md (Google Vertex AI,
Vertex AI tokens, four constraints) and gateway-routing.md (Vertex AI).

Verified: go test ./... (nogui), -race -count=5 on the Vertex tests,
gofmt and vet. A fake Google (token endpoint, IAM Credentials, Vertex
AI) checks each credentials type, the mint shared, bounded and
re-minted, every refusal's advice and that no token reaches another
host. Each of 24 mutations made after review, of the mint, the key
rules, the advice, the upstream path and the retries, fails a test.
Live, against a real project through an impersonated service account,
with magpie in a sandboxed HOME: Chat, Anthropic Messages, Responses and
Gemini clients, streamed and whole, with thinking and with tool calls, a
whole Gemini call and its signature sent back streamed, at global, us
and us-central1, and with Flex PayGo's header. No token was found in its
files or logs afterwards.
2026-10-10 19:21:56 +08:00
wei c45ece36a0 gateway: Code Assist sends the auto mode classifier's reasoning off at low, not high, on a Gemini 3 Flash that lists minimal
fitAutoModeClassifier asks a model to think at its least level (#250). On
a Gemini 3 Flash whose models.dev levels include minimal (gemini-3.5-flash,
3.1-flash-lite, 3-flash-preview), that level is minimal. thinkingConfig
sends minimal only to an Antigravity variant whose id says minimal, and
everything else fell through to high. So the classifier, asked to think
least, went at the most, with 2112 tokens to think and answer in.

Sending minimal instead isn't safe. Gemini CLI's 3.5 Flash goes out as
3.8 Flash where that is rolled out (geminiFlags.wire), and 3.8 Flash has
no minimal: AI Studio answers it with a 400.

Reasoning off (minimal or none) with no variant level now goes at low,
which every Gemini 3 text model lists. An image model may have no low
(3.1 Flash Image has minimal and high), so it still goes at high, as
before. Every other case is unchanged: a variant's own level, low, medium,
high, no effort, and Gemini 2.5's budgets. The comment saying Flash takes
minimal, low, medium and high is corrected. Factory's Gemini route
(buildGemini) builds its request with the same code, and gets the same
change.

TestCodeAssistReasoningOffAtLow sends Claude Code's classifier request
(autoModeAsk) to Gemini CLI's gemini-3.5-flash and to Antigravity's
gemini-3.1-flash-lite, with models.dev's levels. Both go at low. It also
asks an image model at low, which fits to minimal; that goes at high.

  * With the parent's codeassist.go it fails with: the classifier on
    gemini's gemini-3.5-flash: "minimal" at "high", want minimal at low.
    Antigravity's 3.1-flash-lite fails the same way.
  * Without the image check it fails with: gemini-3.1-flash-image asked
    low: at "low", want high.

Verified with the commit before. Not tried live.
2026-10-10 17:54:54 +08:00
yetone d7186e51b9 gateway: Gemini's thoughtSignature stays on the call and text it signed through translation, and goes back instead of the skip value (#1445, XYenon)
What changed: parseGemini keeps a functionCall's and a text part's
thoughtSignature. geminiParts and buildCodeAssistSent write them back; a
later call of a signed step goes without one, and only an unsigned step
or Claude on Antigravity gets skip_thought_signature_validator. The Code
Assist decoder puts a call's signature in its id (signedID, as chat does
since #687) and a text's in KTextSig; the Gemini encoder and renderer
give them to a Gemini client where Gemini put them, with a clean id.
Chat, Messages and Responses renderers leave a signature-only text part
out.

Why: a Gemini client on a Code Assist or translated path had every call's
signature replaced by the skip value and text signatures dropped.

Run: the new tests in reasoning_state_gemini_test.go (Gemini's
documented thought-signature shapes) fail on the old code and pass now; a
Chat client's call id carries the signature back to Google, and no other
API's client gets the text's. gofmt -l; go vet -tags nogui on darwin,
linux and windows; the full internal/gateway tests in a scratch HOME: ok.
Not tried with a real account.
2026-10-10 13:29:45 +08:00
yetone ea1c5d0457 gateway: Antigravity's 429 to a Claude Code / Agent SDK system prompt is the prompt turned away, not a quota, everywhere, and the agent gets 400 (#1425)
Antigravity answers the system prompt of Claude Code and the Claude Agent
SDK (Claude Desktop's chats) with 429 "Resource has been exhausted" at
whatever quota is left (#666). The detail text already said it was not a
quota, but when Antigravity was the last one left (a direct model, the
reporter's case) the route still fell through to failureOf: the try was
counted 额度用尽 on the Routing page and in the account's tally, and the
429 went to the client, so Claude Desktop asked ten times over.

What changed:
- codeassist.go: antigravityTurnedAway(p, system, said) needs the
  Antigravity account, a Claude Code / SDK system prompt and the
  "resource has been exhausted" words. A real quota 429 ("You have
  exhausted your capacity ... reset after ...", QUOTA_EXHAUSTED) stays a
  quota and rests the account as before. turnedAwayStatus = 400 (the
  Anthropic and OpenAI SDKs retry 408, 409, 429 and 5xx, not 400);
  ledger ErrType "prompt_turned_away".
- gateway.go: such a try is failPrompt (was failRefused in a group, and
  failQuota as the last), no rest, no usage re-asked, no passing retry,
  no auto reset. The last one left answers the agent 400 with the
  vendor's words and the hint; in a group the next member is asked, and
  if it fails only on a quota the agent is told the turned-away 400. The
  in-reply (stream error event) form is told the same way.
- continuation.go / translate: the hint is appended to the in-reply form
  too, and the ledger row carries the ErrType.
- routing.js: the hint joins HINTS, so the Routing page shows Antigravity's
  words as "It said: ..." and the explanation on its own line, translated
  in zh, zh-TW, ja and de (i18n.js).

Tests (each fails on the old gateway.go/continuation.go/routing.js):
- TestAntigravityTurnedAwayLastIsNoQuota (stream and not): 400, asked once,
  failPrompt, no rest, ledger 400 prompt_turned_away.
- TestAntigravityTurnedAwayInsideTheReplyLast, TestAntigravityTurnedAwayThenAQuota,
  TestAntigravityQuotaOnAClaudeCodeTurnStaysQuota (scope: a real quota
  429 still rests and reaches the agent as 429),
  TestAntigravityTurnedAwayHintIsTheRoutingPages.
- gui/tests/routing-ag-turned-away.test.cjs: row status word, account
  tally, "It said" line and the hint line, in en/zh/zh-TW/ja/de.
The real-quota fixture's words are from public reports, not captured from
a real account.

Run: gofmt -l internal/ (clean); go vet ./internal/gateway/ and
GOOS=linux / GOOS=windows go vet -tags nogui ./internal/gateway/;
go build ./..., GOOS=linux and GOOS=windows go build -tags nogui ./...;
go test -tags nogui ./internal/gateway/ ./internal/gui/... under a
scratch HOME with pinned caches (ok); GUI node tests (new test,
routing-*, gui-de, gui-ja, gui-zh-tw, i18n-keys) in Chromium and WebKit.
2026-10-09 23:21:41 +08:00
yetone 1bc18b2f4d gateway: a history that opens with the model's turn reaches Gemini and Code Assist after a user turn, so Gemini no longer answers 400 (magpie-community/plugins#45)
An agent's compaction or a cut-down context can leave a history whose
first turn is the assistant's (text, or a tool call). Gemini turns that
away: "Please ensure that function call turn comes immediately after a
user turn or after a function response turn." buildCodeAssistSent, which
Gemini CLI and Antigravity accounts, Factory's generateContent route
(buildGemini) and Zed's Google models all build their contents with, now
puts the user turn "[Continuing from previous AI thoughts...]" before such
a history, as Gemini CLI's own hardenHistory (packages/core/src/utils/
historyHardening.ts, enforceRoleConstraints) does. Histories that open
with the user, and parallel calls split over two assistant messages, go
as before. Chat, Responses and Anthropic upstreams are unchanged.

Verified: TestGeminiHistoryOpeningWithModel fails without the change
(roles model,user, want user,model,user, for codeassist/gemini,
codeassist/antigravity and gemini, with model text and with a model
functionCall first). TestGeminiHistoryOpeningWithUserUnchanged and
TestNonGeminiHistoryOpeningWithModelUntouched pass before and after.
go test -tags nogui ./internal/gateway/... ./internal/zed/... under a temp
HOME with pinned caches; go vet -tags nogui for darwin, linux, windows.
Not tried against a real Gemini or Antigravity account.
2026-10-08 16:24:07 +08:00
yetone 40c5b92a93 gateway: structured output crosses every translation: a Responses text.format or a Chat response_format reaches a Chat, Responses, Messages or Gemini upstream in its own words (frostming on Discord: responses.parse through magpie to OpenRouter came back as plain text)
The IR held a schema only from Anthropic's output_config.format, and only
Messages (and Claude Code's --json-schema) were asked for one. A Responses
request to a provider magpie speaks Chat or Messages to (OpenRouter has no
Responses URL) lost text.format; a Chat request translated to Responses or
Messages lost response_format; an Anthropic schema translated to Chat or
Responses was lost too.

Format (format.go) now carries json_schema (name, description, schema,
strict) or json_object from Responses, Chat, Anthropic and Gemini, and each
builder asks for it in its upstream's field. Where a target can't say it
(json_object on Messages or Claude Code; the vendor bridges Cursor, Devin,
Kiro, Qoder, Command Code, Zed) it is told in the system prompt. An upstream
answering 400/422 naming the field (DeepSeek's "This response_format type is
unavailable now") is asked again with it told in words, and so from then on.
Relayed requests are unchanged.
2026-10-08 10:37:02 +08:00
yetone 71f0541342 gateway: Antigravity's Claude gets a tool turn's images after every tool result, each labelled with the call it came from (@sinswing on X: an image between two functionResponses came back from Google as "tool_use ids were found without tool_result blocks immediately after")
Checked with the owner's real Antigravity account: two Reads that each
return a PNG fail on claude-sonnet-4-6 and claude-opus-4-6-thinking
before, and both answer with each file's own colour after. Gemini on
Antigravity keeps each image beside its response.
2026-10-07 00:44:32 +08:00
TryWorld f1f516cd73 fix(gateway): an account Antigravity turned away doesn't rest (#873)
* fix(gateway): an account Antigravity turned away doesn't rest

A 429 that is Antigravity refusing Claude Code's or its Agent SDK's
system instruction — "Resource has been exhausted (e.g. check quota)"
whatever quota the account has left (#666) — carries the word "quota",
so it was classified failQuota: the account rested 15 minutes and had
its usage asked of Google again, while it answers titles, background
requests and Codex normally.

Carry the fact the error path already works out from —
antigravityTurnsAway(request.System) and the CodeAssist agent, what the
8c652a83 hint is computed from — into the routing decision, the way
sharedPool and refused already carry an upstream routing fact through
error translation. The held attempt is marked on either failure path,
not only on a 429: the refusal also arrives as an in-stream error event,
which skips the 4xx branch and returns 200 while still failing the
attempt, and usedUpWords doesn't look at the status either. Where the
attempt then fails on that mark, the next member is asked first and
restAfterMarked is never called, as for a refusal — nobody rests and
nobody's usage is re-queried.

A 429 that really is the plan used up, with no such system prompt
asking, still rests the account and re-queries its usage, as it did
(#147, #530).

* fix(gateway): only the refusal leaves an Antigravity account alone

The mark was wider than the refusal it describes (yetone's review of
#873): it was set for any status >= 400, and for any failed stream,
whenever the system prompt was Claude Code's. A 500, 503 or 403 on such
a turn was therefore told as a refusal and never set the account aside,
and the account's 4xx handling below it was skipped for those requests.
The mark now goes on the refusal itself: a 429, or an in-stream error
event saying "Resource has been exhausted". The latter needs its own
predicate, since the Code Assist decoder keeps only the error's message
and leaves its status and code out of the event.

Two more of the review:

- the refused attempt now writes a usage.Record, as the hw.refused
  branch it is modelled on does, so these 429s stay in the ledger;
- the member's other Antigravity accounts are asked last rather than
  first, by matesLast, the inverse of matesFirst: they carry the same
  system prompt, so each is turned away just the same, and asking them
  first spent a round-trip apiece before the group reached a member
  that answers.

TestAntigravityTurnedAwayIsOnlyTheRefusal, ...StillLandsInTheLedger
and ...LeavesItsMatesForLast fail on the previous revision of this
branch for each of these reasons.

* fix(gateway): the refusal said inside a reply that isn't streamed

The mark was inside translate's `if stream` block, so a client that
doesn't ask for a stream — and a stream that isn't held — never set it:
the same "Resource has been exhausted" said as an in-stream error event
still rested the account 15 minutes on those requests.

A test for that path first: TestAntigravityTurnedAwaySaidInsideTheReply
drives a 200 that opens with the error event, and pairs it with an error
event of another kind, which still rests the account. The first half
failed on the previous commit for exactly this reason.

Both error paths now go through markAntigravityRefused, which decides
from what the failure said rather than repeating the four conditions at
each return: the Code Assist decoder keeps only the error's message, so
an in-stream refusal is recognised by its text, while a 429 is
recognised by its status as before.
2026-10-05 16:31:11 +08:00
yetone 4e0bf88370 gateway: Gemini on a Google sign-in searches with Google Search and draws with its image models (#757, on Antigravity: gemini-3.8-flash's searches went to the Codex account and spent its allowance, and neither the searcher picker nor the image model picker offered Antigravity's models) — a Google sign-in (Gemini CLI's or Antigravity's, not a plugin's) was never said to search by itself, and buildCodeAssistSent sent no googleSearch, so a Claude Code WebSearch on an Antigravity model was handed to magpie's search, which the searcher magpie picked (Codex first) answered.
Search: Code Assist runs googleSearch for Gemini, but Antigravity turns it down beside function tools (400 "Please enable tool_config.include_server_side_tool_invocations to use Built-in tools with Function calling", tried with that flag in toolConfig too), so searchesFor (searchesItself for one request) says a Google sign-in's Gemini searches by itself for a request without tools; buildCodeAssistSent then sends tools [{"googleSearch":{}}], and codeAssistDecoder reads the candidate's groundingMetadata (webSearchQueries, groundingChunks[].web) as a search the client is told of (Anthropic's server_tool_use + web_search_tool_result), once. A request with tools — every agent's — is given magpie's search tool as before, and its searches go to the conversation's own account first (ownSearcher, as a Kimi Code plan's do): searchWith on its Gemini without tools, so googleSearch runs there and no other subscription is spent. A Google sign-in is also a searcher for other models, last of those magpie picks by itself (rank 5; relays named by hand move to 6), and is offered in Settings → 代搜供应商, with its Gemini models only; the row says such sign-ins search for their own models first. smallModel took every Gemini for a small model ("gemini" has "mini" in it), so the first listed, gemini-pro-agent, searched; it now picks a Flash.

Images: Drawers lists the image models a Google sign-in has (gemini-3.1-flash-image), and draw asks them on Code Assist through the account (drawCodeAssist, askTranslated with the conversation's envelope); buildCodeAssistSent asks an image model for responseModalities ["TEXT","IMAGE"], which a chat with one now gets too. AutoDrawer doesn't pick them by itself (no known price), so nobody's automatic drawer changes.

With the owner's real Antigravity account (a copy of the config, a sandbox gateway): a web_search with no other tool on gemini-3.8-flash-low came back with Google's grounding as web_search_tool_result; with a bash tool beside it the model called magpie's search, which went to antigravity/gemini-3-flash (not Codex) and gave pages; /v1/images/generations with antigravity/gemini-3.1-flash-image drew a 1024x1024 JPEG. TestCodeAssistSearchesWithoutTools, TestCodeAssistDecodesGrounding, TestCodeAssistImageModelAsksForImages and TestSmallModelOfGemini are new; searcher-pick.test.cjs checks the note. go vet, builds (darwin, GOOS=linux, GOOS=windows), go test -tags nogui -count=1 ./... under a temp HOME and the searcher GUI tests (webkit) pass. Not tried with a Gemini CLI sign-in, which takes the same path.
2026-10-04 15:31:23 +08:00
yetone 8c652a83f7 antigravity: its 429 to Claude Code's system prompt says it isn't a quota (#666: Claude Desktop 调用 antigravity 恒定报 429) — Antigravity answers "Resource has been exhausted (e.g. check quota)" to any request whose systemInstruction holds Claude Code's billing line (x-anthropic-billing-header: …) or the Agent SDK's identity line (You are a Claude agent, built on Anthropic's Claude Agent SDK.), on every model (gemini-3.8/3.7 flash, 3.5 flash lite, 2.5 flash, claude-sonnet-4-6, gpt-oss), whatever the quota left, while the same words in a message go through. Claude Desktop's chats run the Agent SDK and carry both, so they always failed, while its title requests (no system prompt) and Codex on the same account answered. Not the session id (magpie already sends request.sessionId as -<uint63>), thinking signatures (never sent back) or the User-Agent. magpie doesn't hide the lines from Google; the gateway now adds to such a 429 that it is no quota and that Antigravity turns away Claude Code's and the Agent SDK's system prompt, so no one chases a quota. Reproduced on the owner's real Antigravity account with Claude Code 2.1.288 through a sandbox gateway (11/11 429; system field removed 200; either line alone 429). TestAntigravityTurnsAwayClaudeCodesSystemPrompt. go vet, builds (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass. 2026-10-03 18:39:29 +08:00
yetone 090f7733ef gateway: Antigravity's Gemini variants think with tools again, and a call the model writes out as text is a call (#636) — a variant id (gemini-3.8-flash-high, the one an effort picks for gemini-3.8-flash) went with includeThoughts but no thinkingLevel since 2baad536, and told no level it all but stopped thinking once the request had tools and gave none of it back, where the -tiered id, sent a level, kept it. A variant is now told the level its id says (Flash minimal/low/medium/high, Pro's minimal as low, xhigh as high), so the id and the level still agree. The Code Assist decoder takes Gemini's namespace off a call's name (default_api:bash → bash), and a call written out in the reply's text, "…imports!call:default_api:bash{command:cat x}", becomes the tool call it meant (arguments as JSON members, <ctrl46>-quoted, or bare key:value), the text before it kept; text that only might start one is held until it is one or isn't, and an unfinished one stays text. Upstream 502/503 were already errors (HTTP status, or an error event mid-stream), not changed. TestCodeAssistAntigravityLevels and TestCodeAssistTextCalls fail without it. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build and go test -tags nogui -count=1 ./... under a temp HOME pass. Not tried against a real Antigravity account. 2026-10-03 13:38:12 +08:00
yetone 9e1e0dbd87 gateway: an image model's picture reaches a Gemini client (#620, tao-bai: antigravity/gemini-3.1-flash-image 返回 parts: []) — through /v1beta generateContent and streamGenerateContent the answer came back with no parts, though candidatesTokenCount (1567) said the image was made. The IR had no event for a picture the model made: codeAssistDecoder (Antigravity, Gemini CLI and Factory's Gemini route) turned functionCall, thought and text parts into events and dropped inlineData, and geminiParts / geminiEncoder had nothing to write it back as. A new KImage event (Name the media type, Text the base64) carries it; the collector keeps it as an Image part, and the Gemini renderer and stream encoder send it as inlineData in its place among the text. A thought image (a draft, thought: true) stays with the reasoning and isn't sent, as before; thought text and signatures are untouched. Chat, Responses and Anthropic clients still don't get the picture (their renderers skip Image parts). TestGeminiImageModelReturnsItsImage (a fake Factory Gemini upstream, generateContent) and TestCodeAssistStreamsImages (Code Assist chunks through the Gemini stream encoder) fail without it with parts: []. Not tried against a real Antigravity account; the image part's thoughtSignature isn't returned to the client, so multi-turn image editing on Gemini 3 image models may still need it. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME pass. 2026-10-03 10:24:30 +08:00
Comic Changandyetone 024f494bc4 Allow provider-specific upstream model names (#280)
A provider may serve a model under an id of its own: namespaced with a
prefix, dated, a `-latest` that is not what models.dev calls it, or simply
a different spelling. magpie sends the name it knows the model by, and the
provider answers that it has no such model.

  magpie model wire relay-b/model-2 vendor-c/model-2-preview
  magpie model wire 'relay-b/*' 'vendor-c/*'
  magpie model wire relay-b/model-2 --reset

A `*` in the **value** stands for the model, so `relay-b/*` set to
`vendor-c/*` sends `vendor-c/model-3` for model-3. A value with no `*` sends
every model of that provider under one name, which is the case where a relay
really does serve them alike. The CLI shows the pattern the way it was
given, with a concrete line for one of the models, so what is in force is
not something you have to imagine. An exact key wins over the provider's.

The canonical id stays canonical. `Entry.Model` is not rewritten: it is the
key automatic routing groups are built from, what `Resolve` returns as the
model's identity, what `GET /models` lists, what an agent asks for, and what
a call is recorded and priced as. The alias goes into the request's model
field and nowhere else — which is the part that was wrong at first.
Handing it to the serializer gave the provider's name to the code that
decides what a request should look like: `buildChat` checks the model for
Gemini compatibility, `buildAnthropic` matches it for adaptive-only and
effort handling, `buildCodeAssist` maps by model. A provider serving a
model under a namespaced id got a request shaped as if it were that other
model. So the request is shaped from the model magpie knows and the field is
rewritten once at the end, with `rewriteModel` — which already existed to
put one provider's own model name in a body and keeps every other byte as
it was.

It has to reach every path. A request the provider understands as it came
is relayed by `passthrough` without being rebuilt, and the Anthropic token
count is asked of the provider directly; both rewrite the field too, so on
a provider speaking the client's own protocol — the common case for a relay
fronting one vendor — the alias still applies.

"Swapped" compared the canonical id with what the vendor's reply named, so
an alias that is not a prefix or a dated variant marked every call swapped.
It compares the name that was actually sent, in the gateway and in the
ledger alike; the ledger reads the map once for the lot, since its rows are
what a reader sets beside a bill. The Codex backend path is left alone: it
sends magpie's own pick and never an alias.

`provider.Test` asked with the canonical id, so a provider that only accepts
the alias reported a failure while its real requests worked. It asks with
the alias now and still reports the canonical id, since that is the one the
user picked.

A blank name was a hole: the setter trimmed what it was given, so a value of
only whitespace was removed on the way in, while the read path would have
used it had anything else written it — a hand-edited file, or a build from
before the trim. Both ends treat a blank as no name now. The key is
checked where it is written rather than in Save, so one hand-edited entry
cannot block every save, and #288's walk moves it on a provider rename
without a line here.

Co-authored-by: yetone <yetoneful@gmail.com>
2026-10-01 13:03:57 +08:00
yetone e4375ce967 gateway: a tool's schema reaches Antigravity with only the keywords it takes (#187: Unknown name "exclusiveMinimum") — Antigravity refuses a request whose function declarations carry a JSON Schema keyword outside its subset, and magpie cut out only the ones it knew of, so zcode's and dsh's tools, whose numbers have exclusiveMinimum, were refused with 400 on every turn. Now each schema keeps only type, description, nullable, enum, properties, required, items, the bounds and pattern, and propertyOrdering, anything else left out; an exclusive bound given as a number becomes the inclusive one when there is none. Tested on a schema with exclusive bounds, format, title, uniqueItems, contains, dependentRequired and not 2026-09-29 12:12:45 +08:00
yetone 504b470f12 gateway: images a tool returned reach a Chat model after the tool messages (charan-rathore in #167: Claude Code's tool_result images were dropped on the way to Chat Completions)
A tool result holding images, as Claude Code's screenshot tools and its Read of a .png send it (an Anthropic tool_result with image blocks) or as a Responses function_call_output with input_image parts, lost its images whenever the request was translated: the result was read as its text only, so a Chat model was told "Read shot.png" and never shown it, and a result that was only an image came through empty. #167 turned such a request away with a 400; now the images go through. The shared request keeps a tool result's images beside its text. Chat's tool messages hold text only, so a tool message says "[The tool returned an image; it follows in the next message.]" after its text, and the images go right after the run of tool messages, each result's labelled with the tool and call it came from ("[From the result of Read (tool call toolu_1):]"), as image_url parts (a data: URL for inline ones). When the user's own message comes next, as Claude Code's system reminder beside a result does, the images open that message rather than being a second user message in a row, which some models' chat templates turn away; otherwise they are a user message of their own, before the assistant's next turn. Tool messages still directly follow the assistant's tool_calls. An Anthropic upstream gets the images inside its tool_result, a Responses one in the function_call_output's output list, Code Assist as inlineData after the functionResponse, as Gemini CLI sends a file it read; Kiro, Cursor and Devin take the text as before. A model that can't see still has each image described in its place before translating, so nothing follows its tool message.

Tested end to end against fake upstreams: Claude Code's tool_use then a tool_result of text and a base64 PNG to a Chat model that sees (with and without the user's text after it), two parallel results with three images (base64 and a URL) giving tool, tool, then one user message with all three labelled, a screenshot from an older turn kept before the assistant's answer, Codex's function_call_output with input_image to Chat, Claude Code to a Responses provider, and a text-only model still given the description in the tool message. The four Chat tests fail without the change. go build, vet and the gateway tests pass; windows and linux (CGO off) build.
2026-09-29 03:44:28 +08:00
yetone 2baad5366c provider: Antigravity's models at several levels are one model with those levels (#150: 统一 Antigravity 模型变体与客户端推理档位的映射) — Antigravity lists gemini-3.7-flash-low, -medium and -high as three models, "Gemini 3.7 Flash (Low)" …, so a client picked a level twice: once in the model, once as its reasoning effort, with no telling which won. Now ids that are one id with an effort word after it (-low, -medium, -high, -extra-low, -minimal, -xhigh) are one model, gemini-3.7-flash "Gemini 3.7 Flash", declaring only the levels there are (low,medium,high; Gemini 3.1 Pro low,high), so Codex, Pi and the rest get reasoning levels for it. The level a variant is at is what Antigravity's name says where each name says a different one (gemini-3.5-flash-extra-low is "(Low)", gemini-3.5-flash-low "(Medium)"), else its id's word; a model only named like another (gemini-3-flash-agent, "Gemini 3.5 Flash (High)"; gemini-pro-agent) or with no sibling (gpt-oss-120b-medium) stays as listed. A request asks for the variant the effort picks, an effort it lacks at the nearest level (xhigh is high; medium on low/high is high); with none asked, the id without a level if Antigravity has one, else high — what Gemini 3 does unasked — else the highest. A variant's request carries no thinkingLevel, so the id and the level can't disagree. An old variant id still works: as named with no effort, and moved to the effort asked for. Saved picks and agents set to a variant (antigravity/gemini-3.7-flash-high) are moved to the family, at that level where the agent's own is unset, as Cursor's are. For Gemini 3 models without variants, medium now goes as medium to Flash (which takes minimal/low/medium/high) and still as high to Pro (low/high). Tested against the list an account's fetchAvailableModels gave (sandbox cache) 2026-09-28 20:10:00 +08:00
e136cf9a27 gateway: Gemini PDF and audio files kept on text-only routes (#95)
* gateway: keep Gemini document and audio file data on text-only routes

* fix(gateway): avoid translating Gemini files as images

* fix(gateway): preserve Gemini files for Code Assist while translating safely

* fix(gateway): retain Gemini file placeholder for Claude subscriptions

---------

Co-authored-by: Instinct Agent <agent@instinct.com>
Co-authored-by: Charan Rathore <charan-rathore@users.noreply.github.com>
2026-09-27 04:24:03 +08:00
yetone 637b2458ee provider + gateway: Google sign-ins — Gemini CLI's and Antigravity's — are subscriptions of magpie's, so any agent can use their models (#4); Gemini CLI's own login in ~/.gemini is read as it is, or an account is signed in from magpie with Google's OAuth, its token refreshed in memory, and each request goes to Code Assist wrapped as the app wraps it, with the project Code Assist set the account up with; Google now serves Gemini CLI's sign-in only to Code Assist Standard and Enterprise, which need a Cloud project, named with magpie accounts project or GOOGLE_CLOUD_PROJECT in ~/.gemini/.env and said so where the account is shown; Google may suspend an Antigravity account used outside Antigravity, so magpie says that and asks before adding one 2026-09-25 15:53:33 +08:00