Commit Graph
44 Commits
Author SHA1 Message Date
yetone 8c733bb362 gateway: a bare JSON error line in an event stream is the vendor's error
zRain (Discord #feedback, Windows, v0.1.3039/v0.1.3041) asked
antigravity/gemini-4-argon high. Code Assist answered 200
text/event-stream, a few thinking events, then ended the body with

  {"error":{"code":400,"message":"Request contains an invalid argument.","status":"INVALID_ARGUMENT"}}

on a line of its own, no "data:" before it. readSSEAlive and the
passthrough sniffer skip any line that is no SSE field, so the stream
ended with no finishReason and the agent was told "Antigravity: the
reply ended before it was complete" instead of Google's 400.

- sse_bare.go: bareErrors hands such a line (Google's shape, a list
  of one, pretty-printed over several lines, OpenAI's {"error":…},
  Anthropic's {"type":"error"}) on as the data event it means. Every
  other line goes byte for byte, a line under way at once; only a line
  starting { or [ waits for its end (held up to 1MB). eventStream wraps
  the body with it (passthrough, translated stream and whole reply,
  continuation, search), and readSSEAlive wraps every other reader.
- codeassist.go and carriedError take the status the error names
  (namedStatus, #4855), so a whole reply's error goes out at 400.
- continuation.go notes that status for routing (namedStatusHeader);
  refusal events and Antigravity's own turning away are left as they
  were.
- gateway.go: a reply broken off by an error frame that names a 4xx
  retryable() calls the request's fault rests nobody, as that 400 does
  before the 200.

Plugins: antigravity-cloak only rewrites the request, reads no stream,
so nothing to change there.

Run (mote, at this tree on a9b1877cf):
- go test -run 'TestBareError|TestAntigravityBareError|TestGeminiRelayBareError'
  ./internal/gateway: ok
- go test -run 'Gemini|Antigravity|Stream|Cut|Carried|ErrorReply|Rest|Relay|Late|Named|Passthrough|SSE|Continu|CodeAssist|Plugin'
  ./internal/gateway: ok (251s)
- gofmt -l; go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet
  ./internal/gateway; go build ./...: clean

Broken by hand:
- the new tests on a9b1877cf with bareErrors as identity: every case
  red, the whole reply 502 "Antigravity: the reply ended before it was
  complete" (the reporter's words), the stream with no error, the
  relayed Gemini stream without the error event.
- without the gateway.go rule (the status noted only), the three
  stream=true cases rest antigravity@u for 60s.

Not tried: a real Antigravity account (the reply can't be made to
happen on demand); the reporter's own thinking events (not sent, the
fixture's are in Google's shape, the error line is theirs byte for
byte); the Windows box. chat/anthropic/responses decoders still take
their status from filterRefused only; carriedError covers the shapes
they share.
2026-11-05 18:36:31 +08:00
ggbdpq 8daab00a2e gateway: a completion call Antigravity's model wrote into its text goes out of the history, the answer it repeated staying (#5091)
What changed
- buildCodeAssistSent (internal/gateway/codeassist.go) hands an Antigravity
  request's history through dropPseudoCalls (internal/gateway/textcalls.go).
- dropPseudoCalls rewrites a model turn only when nothing structured is in
  it, a whole call written out in its text is there — of a tool the request
  offers, its arguments readable by the readers Chat replies already go
  through (<tool_call>'s JSON and pairs, an invoke with its parameters),
  closed — and the text after it says the call's result again, up to
  punctuation, spacing and case. The turn then goes upstream as that text
  without the call. msgs is not changed: a fallback builds from the same
  request.

Why
- #5091 (Phoenix12580): gemini-4-argon deep in a long session wrote the
  completion call it meant into its reply's text — the report's two-sided
  SSE capture shows every part Google returned is text, none a
  functionCall — so the client ran nothing and read the call's arguments
  as the answer's lead. The turn came back in the history as that text,
  and every later turn read its own wrapper back and wrote the next one
  the same way; clearing such turns from the history restored normal
  calls in the report's own controlled try.

Not changed
- A reply that carries its call as text still streams as it came: the
  report asks for no call read out of a live reply, and none is made.
- The gemini and vertex requests keep their histories as they came; the
  report is the Antigravity route.
- A wrapper the readers can't read — a call:default_api: whose arguments
  textArgs refuses, a shape with none of the marks, a call example inside
  a code fence — stays in the history; the report's conditions are kept
  to what can be checked.
- No receive-side counter is added: the reply's decoder has no logger of
  its own, and the shapes it reads are the report's own open question.

Run
- TestAntigravityPseudoCallOutOfHistory
  (internal/gateway/textcalls_pseudo_test.go): red before the change, the
  wrapper, the split-block and the invoke cases each failing with the call
  still in the turn, green after, and red again with the ag wiring taken
  back out of buildCodeAssistSent
- go test -tags nogui -count=1 -run 'TestAntigravityPseudoCallOutOfHistory|TestCodeAssist|TestTextCall|TestTextWritten' ./internal/gateway/: ok 5.016s
- go test -race -tags nogui -count=1 -run 'TestAntigravityPseudoCall|TestCodeAssistTextCalls|TestTextWrittenCall|TestTextCalls' ./internal/gateway/: ok 2.952s
- go test -tags nogui -count=1 -timeout 25m ./internal/gateway/: ok 600.353s
- gofmt -l internal/gateway/codeassist.go internal/gateway/textcalls.go
  internal/gateway/textcalls_pseudo_test.go: empty
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
  ./...: clean
- go build, GOOS=linux go build -tags nogui, GOOS=windows go build: ok

Reviewed and ported (on origin/main 1b0340fdb, cherry-picked clean):
- Read: only the Antigravity envelope (ag) is rewritten, only model
  turns with no structured part, only a whole closed call of an offered
  tool whose result the text after it repeats; r.Messages is untouched,
  and the rewrite is the same on every request, so the history prefix
  stays stable. Nothing is added to the prompt.
- mote: TestAntigravityPseudoCallOutOfHistory green. With codeassist.go
  and textcalls.go put back to main it is red on the wrapper, the
  split-block and the invoke cases ("the pseudo call stayed in the
  turn sent to Antigravity: ...").
- mote: go test -tags nogui -timeout 45m ./internal/gateway ok (1009s);
  vet darwin/linux/windows ok; gofmt -l clean.
Not tried: a real Antigravity long session; the reporter's own
controlled replay is the evidence that clearing such turns helps.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
Generated-by: GLM-5.3-Flash (ZCode)
2026-11-05 18:31:17 +08:00
yetone 2d04fe73dd gateway: Antigravity's tool enums go without a blank value (#5235)
Google's Schema proto refuses a blank enum value, so a tool whose enum
holds "" turned every tool-bearing Antigravity turn away with 400
"enum[N]: cannot be empty". Portainer's StatusMessage.operationStatus
(enum ["processing","warning","error",""] under allOf) did it for
ikunbots' dsh session, reported on X.

plainSchema now leaves blank (whitespace-only) values out of a string
enum, and leaves the enum out when nothing else is in it; a blank const
gives no enum. A number in an enum still drops it whole, as before.

Run (mote): go test ./internal/gateway -run
'PlainSchema|Antigravity|CodeAssist|GeminiSchema' ok;
TestPlainSchemaDropsBlankEnumValues red on origin/main's codeassist.go
(the "" went through), green with this. gofmt clean.
Not tried: a real Antigravity request with the reporter's Portainer
tools. Not changed: Vertex's chat path (geminiSchemaShapes), which
relays JSON Schema enums as they come; whether Vertex refuses a blank
value too is unknown.
2026-11-05 00:37:01 +08:00
ggbdpq 6e1e3af9e3 gateway: an Antigravity schema's array always says its items, tuple or not (#2826)
What changed
- plainSchema (internal/gateway/codeassist.go) now leaves every array
  schema with an items object, at any depth:
  - a tuple's items (an array, draft 07) collapses to its first member
    that says anything;
  - an array whose members were said in prefixItems — dropped by the
    subset — takes that tuple's first meaningful member as its items;
  - an array that still has none gets items {"type":"string"}.

Why
- Google requires items on every schema of type array. Claude Code's
  tools (ArtifactData's query.where) say an array of arrays in JSON
  Schema 2020-12 tuples, and stripping prefixItems left the inner array
  with none, so Antigravity turned the whole request away with 400
  "tools[0].function_declarations[3].parameters.properties[query].
  properties[where].items.items: missing field". plainSchema is the
  Antigravity path only: Gemini CLI and Vertex take the schema as it
  came, and no other vendor path strips tuples.

Run
- go test -tags nogui -count=1 -run 'TestPlainSchema|TestCodeAssist|TestAntigravity' ./internal/gateway/: ok (TestPlainSchemaArrayAlwaysHasItems red on 1a3b9268 before the fix, green after)
- go test -tags nogui -count=1 ./internal/gateway/: ok 327.237s
- go test -race -tags nogui -count=1 -run 'TestPlainSchema' ./internal/gateway/: ok 2.143s
- gofmt -l internal/gateway/: empty; go vet -tags nogui on darwin/linux/windows: clean
- go build -tags nogui ./..., GOOS=linux, GOOS=windows: ok

Generated-by: GLM-5.3-Flash (ZCode)

Run (rebased onto 9ae79122, upstream/main 10-27): upstream's b28e5ffd
(plugins#375) fixes the same missing-items hole its own way — every array
left with no items gets items {}, which its A/B against Google answered
200 with — and adds the Google schema-400 fall-through to the next member
(fallback.go shapeWords). The fallback here takes upstream's empty object
in place of a string-typed one, and the two default-expecting test rows
with it; the tuple collapse and the prefixItems recovery above the
fallback stay, as upstream's check only fires when items is nil and takes
none of them. TestPlainSchemaArrayAlwaysHasItems and upstream's
TestPlainSchemaArraysAllHaveItems / TestAntigravityArrayGetsItems all
green on the merged tree.

Run (rebased onto e156fdd03, upstream/main 11-02): upstream's abaf2c4e8
(#4561) makes plainSchema resolve local $refs and gives walk a path
argument, and f2ae7bdec judges a self-reference by whole segments;
neither touches the array fallback. firstSays rides before the new walk,
and the prefixItems recovery walks its member at path+"/items" as the
new signature asks. On this tree: TestPlainSchemaArrayAlwaysHasItems red
on clean main (2 of its 4 rows), green with the fix, red again with the
fix ablated; gofmt and go vet -tags nogui clean.

Generated-by: GLM-5.3-Flash (ZCode)

Generated-by: GLM-5.3-Flash (ZCode)

Landed from ggbdpq's branch (patch posted on the issue; sha256/patch-id
checked against the issue) by yetone, rebased on origin/main 2026-11-03.
Run at the pushed tree, on mote (macOS): go test -tags nogui -count=1 of
internal/gateway with -run over this batch's tests and their families
(PlainSchema, Antigravity, AutoMode, WebP, ClaudeTUI, NativeRelay,
Namespace, Grok, Zed, Codex, ClinePass, rewrite) ok; -race -count=3 of
the new tests ok; GOOS=linux and GOOS=windows go vet of internal/gateway
and gofmt -l clean. The full gateway-and-importers run, started at an
earlier base, was still running at the push; its reds get issues.
Changed in review: main already gives an array with no items {}
(b28e5ffd, plugins#375), so the reported prefixItems case already
answered 200. Taking the tuple's first member as items told the model
every item of ArtifactData's [field, op, value] is a string. A tuple
(prefixItems, or draft 07's items array) is now said once only when
every member that says something is alike; members that differ are
any item ({}). What this adds over main is the draft 07 items array,
which went to Google as an array, and alike members kept typed.
Broken by hand: codeassist.go reverted, TestPlainSchemaArrayAlwaysHasItems
red; restored, green. The draft 07 tuple fixture is made up, not a
reporter's tool; not tried against Antigravity itself.
2026-11-03 02:27:57 +08:00
yetone 2503520f82 codexcat: each Codex model takes official Codex's own instructions for it (#3759, #4008, #4783)
Every magpie model in Codex's catalog (model_catalog_json) carried
gpt-5.2-codex_prompt.md ("You are Codex, based on GPT-5"), so a magpie
GPT-6 model, the auto group's included, ran on a GPT-5.2-era prompt while
official Codex sends GPT-6's own template. magpie still writes no words of
its own into the prompt and leaves the identity line alone: each entry now
takes the text official Codex sends that model, word for word.

- A model's slug (the id's last segment) is matched as Codex 0.166
  matches one (longest prefix of an official slug): first in the entries
  the user's ChatGPT account handed this Codex (models_cache.json), whose
  base_instructions and model_messages go over as sent; then in Codex
  rust-v0.166.0's bundled models.json (instructions_template only, as an
  older Codex may not read 0.166's model_messages), embedded as
  codex_instructions.json.
- Any other model, and a routing group, takes Codex's prompt for a model
  it doesn't know (models-manager/prompt.md, model_info_from_slug), which
  replaces codex_prompt.md: that is what official Codex sends it.
- ownEntry with no base_instructions, and internal/provider's
  codexInstructions fallback, take the same official text.
- testdata holds Codex's models.json and prompt.md at rust-v0.166.0;
  TestBundledIsCodexOwn fails when the embedded copies drift from them.
- GET /v1/codex/models (a remote Codex's model_catalog_url): entries are
  now ~21 KB, so Codex before 0.166's 1 MiB cap holds about 48 of them
  (was ~125). Codex 0.166 reads the catalog whole (models_endpoint.rs
  passes no body limit), and it sends ?client_version=, so the cap now
  applies only to a Codex below 0.166 or one that doesn't say
  (codexReadsWholeCatalog). docs/reference.md says so.
- docs/subsystems/agent-wiring.md: a "Codex instructions" row. The
  Antigravity cloak's comment no longer calls the GPT-5 prompt magpie's.

Run (mote's disk is full, 100% with other sessions' runs, so on WSL
magpie-desktop through wsl-run):
- go test ./internal/codexcat/: ok. go vet -tags nogui ./... and
  GOOS=windows go vet ./...: ok. gofmt -l: clean.
- go test -tags nogui -count=1 -timeout 45m codexcat, provider, agent,
  gui, gateway (every package that imports codexcat): codexcat, provider,
  gui ok. agent: TestGrokInstalled and TestOmpDetectedWithPiDir red, the
  same at origin/main 276c806db on the same box (#3548, #4033: WSL binfmt
  and install detection). gateway: TestCodexCatalogFitsCodexsLimit and
  TestCodexCatalogKeepsTheKeysUsedModelsFirst red from this change (the
  1 MiB cap, fixed above; both ok after, with every TestCodexCatalog*,
  TestCodexListed*, TestCodexApp*), and TestUnroutedHeldReportSaved, red
  only in the full run, ok alone here and at origin/main (#4300).
- Real Codex 0.166.0 (npm) in a sandbox HOME/CODEX_HOME, model_catalog_json
  from this codexcat, against a fake Responses gateway on 127.0.0.1:38611
  capturing each request: 0.166 sends the instructions as the first
  developer message (no top-level instructions). For magpie/gpt-6-astra it
  equals gpt-6-astra's instructions_template in Codex's models.json, byte
  for byte; for magpie/deepseek-v4-pro it equals prompt.md.

- After rebasing on origin/main 9da9bfabd: go vet (linux, windows) of
  codexcat, gateway, provider ok; codexcat ok; -run
  "Codex|Antigravity|Grok" in gateway and provider ok. Then rebased
  onto 546cdbde6 (7 commits in redact, gateway translation and a GUI
  test, none in codexcat or the Codex catalog) and not run again.

Broken by hand:
- The cap held for every client_version: both catalog tests FAIL (47
  listed for 0.166.0, 0.167.0-alpha.1 and 1.0.0).
- Old codex_prompt.md and Prompt everywhere: TestBundledIsCodexOwn,
  TestThirdPartyModelsTakeCodexOwnInstructions (all 7 slugs started "You
  are Codex, based on GPT-5"), TestThirdPartyModelsTakeCachedEntry,
  TestOwnEntryInstructions and TestCodexCatalogKeepsOwnEntries FAIL.
- The same real Codex run on origin/main's codexcat: both models' first
  developer message is the 7.5K GPT-5 prompt, differing from the official
  text at byte 15 (astra) and 8 (deepseek).

Not tried:
- GOOS=darwin go vet (needs mote, full).
- Reading the bundled catalog from the user's installed Codex binary;
  the snapshot is 0.166's, and a Codex release with new templates needs
  testdata and codex_instructions.json refreshed.
- An Antigravity account with Codex's unknown-model prompt ("You are a
  coding agent running in the Codex CLI"): the cloak breaks only the
  GPT-5 identity lines tried before.
- A remote Codex below 0.166 with many models through a gateway key: it
  lists fewer than before; the used ones FitOwn moves into the first 100
  can fall past the 48 that fit.
- A real ChatGPT account's models_cache.json entries (tested with a
  fixture cache).
2026-11-01 22:30:51 +08:00
yetone f2ae7bdecc gateway: plainSchema judges a self-reference by whole segments (#4561 review)
The previous commit's selfRef took a $ref as a self-reference when the
walk's path began with the ref's pointer as a string. So
"#/properties/a" inside /properties/ab, a sibling, was cut down to
{"type":"object"} instead of being resolved. A self-reference is now
the pointer itself or one of its containers: path == ref, or path
begins with ref + "/".

A "#/…" pointer that names nothing where it points also falls back to
its last segment as a $defs or definitions name again, as every ref did
before pointers were walked ("#/components/schemas/Mode" with Mode in
$defs).

TestPlainSchemaSelfRefBySegment covers both.

Broken by hand: selfRef and localRef back to the previous commit, test
kept. Red: "inner" and "mode" both go out as {"type":"object"}.

Not tried: a real Antigravity request with dsh's tool schema. The
fix is in the flattening, and the gateway tests send the result
through a fake upstream.

Run (on mote, through mote-run):
- Full `go test -tags nogui -count=1 -timeout 45m ./...` with this stack
  on c30d3b7b6: 82 packages ok. internal/gui was red only on
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514, SearchAll from
  b09349d17) and TestColdTurnsTaken (#4510). Both are filed, and neither
  touches this stack.
- Rebased onto 29d0ab39f, which changed internal/gateway since then:
  gofmt -l, go vet (darwin, GOOS=linux -tags nogui, GOOS=windows) and
  go test -count=1 ./internal/gateway ./internal/usage ./internal/provider
  ./internal/sessions all ok at the pushed head. go build ./... ok for
  darwin, linux (nogui) and windows.
- go test -race of the gateway tests this stack adds or touches, on
  the stack at fb29cd30f: ok.
2026-10-31 23:35:27 +08:00
ggbdpq abaf2c4e8f gateway: plainSchema resolves a $ref into properties (#4561)
A $ref that points inside the schema ("#/properties/func/properties/
triggers/items", as dsh's tool parameters carry one) is a local JSON
pointer like a "#/$defs/x" one, but plainSchema read a ref only by its
$defs or definitions name: the pointer's last segment named nothing
there, and the field it stood for went out as a bare {type: object} on
the Antigravity path, the tool losing that field's shape.

Any local pointer is resolved now, where it names; a self-reference —
a ref to the site or one of its containers — stops at the target's
type alone, as the plugin's googleSchema has it.

A test with the error's path fails on the old code.

Reviewed and applied from #4561 (ggbdpq, branch head ab39ddcbc; the
patch's SHA-256 matches the issue). A review fix follows in the next
commit: selfRef matched a pointer as a string prefix.

Broken by hand: plainSchema back at main with the test kept, and
TestPlainSchemaResolvesPointerIntoProperties fails ("again" goes out as a
bare {"type":"object"}).

Run (on mote, through mote-run):
- Full `go test -tags nogui -count=1 -timeout 45m ./...` with this stack
  on c30d3b7b6: 82 packages ok. internal/gui was red only on
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514, SearchAll from
  b09349d17) and TestColdTurnsTaken (#4510). Both are filed, and neither
  touches this stack.
- Rebased onto 29d0ab39f, which changed internal/gateway since then:
  gofmt -l, go vet (darwin, GOOS=linux -tags nogui, GOOS=windows) and
  go test -count=1 ./internal/gateway ./internal/usage ./internal/provider
  ./internal/sessions all ok at the pushed head. go build ./... ok for
  darwin, linux (nogui) and windows.
- go test -race of the gateway tests this stack adds or touches, on
  the stack at fb29cd30f: ok.
2026-10-31 23:35:27 +08:00
yetone 7e0fe83d4b provider: Listed as works for signed-in accounts and plugins (zeewell on X)
zeewell asked to list SuperGrok's grok/grok-4.6@500k as grok-4.6, and
Cursor, Devin and WorkBuddy models (all plugins) under ids of their own.
v0.1.2345's "Listed as" took ids only for key/relay providers
(takesModelIDs was p.Account == nil).

Why the restriction was there: the wire rewrite (Settings.Wires) turns
the request body's model back into the own id, but some code reads the
model by the vendor's id before that and got the listed one:
- plugin model lookup (pluginModel: the plugin's APIs, tiers, prices);
- the Claude subscription run (--model given to Claude Code);
- Code Assist/Antigravity variant choice (codeAssistBody, SentNameOnIn);
- account plan lists (fallback's Account.Lists, effort Levels/Tiers,
  AccountServes);
- moveModelRefs refused a provider with no providers.json entry, which
  is every plugin and account provider until a pick is set.
Each now translates with OwnModelID / the provider's ModelIDs, so the
upstream request still carries the vendor's or plugin's own id. Only a
decide-only provider refuses an id. The GUI box already follows
TakesModelIDs, so no GUI file changed.

Tests (red on the old code, each fix reverted by hand one at a time):
- TestModelIDRefused, TestModelIDAtAnAccount (takesModelIDs,
  AccountServes, SentNameOnIn);
- TestLocalModelIDAtAPlugin (Bun fake plugin: /v1/models, upstream
  path, X-Plugin-Model, body, usage; red on pluginModel and on
  moveModelRefs);
- TestLocalModelIDAtAnAntigravityAccount (codeAssistBody);
- TestLocalModelIDAtAClaudeAccount (claude got --model my-sonnet);
- antigravity pool test (fallback Lists, Levels).

Run on mote: gofmt clean; go vet darwin/linux/windows ok; go test
-tags nogui -count=1 -timeout 45m on internal/provider, gateway, cli,
gui, settings, access, usage, plugin: all ok except internal/gui's
TestSettingsSaveKeepsWhatItDoesNotSend (SearchAll), red on main since
b09349d17 and filed as #4514. After rebasing on 140efc8f7 (nothing new
under provider/gateway) the ModelID/LocalModelID/Antigravity tests
ran again: ok.

Real accounts, sandbox HOME, dev build on 127.0.0.1:3486: magpie model
id set grok/grok-4.6@500k -> grok-4.6, grok/grok-4.5@500k -> g45big,
cursor/composer-2.5 -> my-composer, devin/swe-2 -> my-swe,
workbuddy/deepseek-v4.1-flash -> ds-flash. /v1/models listed the new
ids. Requests for grok/grok-4.6, grok/g45big, cursor/my-composer and
devin/my-swe each answered 200 "pong", served as the vendor's id
(grok-4.5-build for g45big); usage records the listed id as model.
Plugin tokens were not rotated (no diff with live).

Not tried: WorkBuddy's real request (its own sign-in answers 401,
unrelated); the GUI box not clicked; no full ./... suite, no GUI suite
(no GUI file touched).
2026-10-31 18:38:31 +08:00
yetone b1a1b950fe routing: the classifier asks its model not to think (tangtang969 on X)
"classifier的模型调用可以加上不带思考的参数么?提速效果比较好". A routing
group's classifier (and its effort question) asked its model for the
least level on its list, and nothing at all when the list was unknown,
so a relay's reasoning model thought at its vendor's default before
answering a number.

Now classifyEffort asks for none, reasoning off, and each wire fits it
with the code that already fits a client's none:
- Chat/Responses: a model with none gets none; one without gets its
  lowest (fitFor: low, minimal), as before; one whose levels aren't
  known gets none (as auto mode's classifier does, fitAutoModeClassifier).
- Anthropic: thinking {"type":"disabled"}; Opus 5.5, which refuses it,
  still has it left out (thinkingOffAsTaken).
- Gemini API / Code Assist 2.5: thinkingConfig.thinkingBudget is the
  off budget (0 for Flash and Flash-Lite, 128 for Pro, as Vertex already
  did) where a Chat none went as low's 4096. Gemini 3 is unchanged (low).
- A model the user marked as taking no reasoning ask (Reasonless) is
  sent none at all; a routing group as classifier is left as before.
- An upstream that turns the effort away (unknown reasoning_effort
  field, or the level) is asked again without it and remembered
  (askLeast), so the classifier keeps answering.
The Image recognition model keeps its old least-level rule
(leastEffort); only the classifier changed.

Run (mote-run, this tree on origin/main 90518de26, rebased onto
d83823d26, which touches internal/agent only):
- go test ./internal/gateway -run 'TestClassifierAsksThinkingOff|
  TestClassifierThinkingAsEachVendorTakes|TestVisionEffortUnchangedByClassifier|
  TestIntent|Classif|TestAdaptiveOnly|Vertex|Gemini|Think|Decide|Effort': ok
- go test ./internal/gateway -run 'CodeAssist|Codeassist|Antigravity|
  GeminiCLI|Gemini|AIStudio|Auto|Rule|Group|Vision|Search|Reason|Off': ok
- go vet ./internal/gateway on darwin, linux, windows; gofmt -l clean.
Broken by hand: classifyEffort back to the least level and the 2.5
off budget turned off: TestClassifierAsksThinkingOff (anthropic, gemini
2.5 flash, unknown chat), TestIntentClassifierEffort and the 2.5 Pro case
go red. Before askLeast, the "effort turned away" case was red (the
classifier failed on a relay refusing reasoning_effort).
Not tried: a real vendor account; the whole internal/gateway package
and full suite (running after the push). On Anthropic, the old body for
claude-sonnet-4-5 had no thinking at max_tokens 2048, so that model
wasn't thinking before either; the change there is the explicit
disabled.
2026-10-31 16:38:58 +08:00
wrke1990andggbdpq 024393fbb9 gateway: a Codex mode switch keeps its developer role on a translated Responses turn (#2532)
Refs yetone/magpie#2532 (the Responses-to-Responses translation case).
An offered web_search can select translation even for a Responses upstream.
Keep system/developer items in place instead of lifting initial Plan
instructions and demoting a later Default update to a user reminder.
Other APIs and the Claude bridge retain their existing cache mapping.
Update the gateway routing reference and cover search continuation rounds.

Verification on macOS arm64 with Go 1.26.10, isolated HOME and pinned caches:
- New tests on unmodified cc04ce68c1 plus
  test changes fail with real assertions in
  TestResponsesInstructionRolesThroughSearch (developer/system),
  TestResponsesInstructionsOtherAPIsUnchanged and
  TestCodexSearchAnsweredOnResponses.
- Those patched tests, TestCodexLaterDeveloperMessageKeepsTheSystem and
  TestSearchOfferedStaysOnTheClientsAPI pass, also with -race.
- gofmt and diff checks pass.
- Native, Linux/nogui and Windows vet and builds pass.
- go test -tags nogui ./... fails in the unchanged internal/agent package:
  TestRunningNeedsNoPs cannot find its sleep 314.159 process. The complete
  internal/gateway suite passes (427.556s), as do the other packages.
- The patched executable against an isolated local capture upstream keeps
  Plan and Default as developer messages in minimal and full histories
  with web_search offered; real configuration hashes remain unchanged.
Not run: paid real-upstream acceptance, native Linux/Windows runtime tests,
or browser GUI tests (no GUI assets changed).

The unrelated agent failure was traced to macOS pgrep returning exit 3,
"Regular expression evaluation error (illegal byte sequence)", under the
inherited locale. The same local sleep process is found with LC_ALL=C.
TestRunningNeedsNoPs fails 20/20 under -race with the inherited locale and
passes 20/20 with LC_ALL=C (3.848s). No agent code or timeout was changed.
A full-suite recheck with LC_ALL=C is running at commit time; retain the
initial failure and publish as a draft until that recheck completes.

Adapted when landing: a blank line before the next heading in
docs/subsystems/gateway-routing.md. Cherry-picked by ggbdpq (gua2100).

Review and run record (landed by the maintainer's agent; gua2100 brought
both fixes from Discord, rebased onto main):
- External code, read line by line: no network, dependency, workflow or
  credential change; Codex base_instructions/identity untouched.
- Base origin/main d99e213f5. Full checks on mote (macOS, Go 1.26.8,
  sandbox HOME) at 31f025634, whose tree is the one pushed (only messages reworded since): gofmt, go vet darwin, linux,
  windows, builds for all three: rc=0. go test -tags nogui -count=1
  -timeout 45m ./...: 79 packages ok, internal/gateway ok (855s); two reds
  in untouched packages, both filed before: internal/plugin
  TestGatewayHookMixedPiPackage (#2865, "starting plugins: context deadline
  exceeded") and internal/update TestRelaunchOpenTriedAgain (#3881). Run
  alone at the same tree both pass (plugin 97s; update -count=3).
- Broken by hand: the #3739 regex reverted, so both Kimi tests fail (400
  handed back). The #2532 product files reverted (six files), so all three
  tests fail. The mergeTurns role guard removed fails (5 input messages,
  want 7).
- Real binary on mote, sandbox HOME, a fake upstream that records requests:
  at d99e213f5, wrke1990's literal #2532 body sends Plan in instructions
  and Default as a user <system-reminder>; at HEAD both developer items
  keep their role and place. #3739's curl body (and zfsdream96's ZCode
  shape, output_config effort max, no thinking) is a 400 at d99e213f5; at
  HEAD it is a 200 after one retry without thinking, and the next
  request goes without disabled.
- Rebased onto fa427216a (responses.go stream deltas, landed meanwhile;
  no conflict). At the rebased pushed tree: gofmt, go vet and
  go test -count=1 ./internal/gateway ok (580s) on mote. The full suite
  was not rerun after that rebase.
- Not covered: the search reroute's re-parse when a fallback changes
  whether the target is Responses (breaking it leaves the tests green;
  no route found that reaches it). Not tried: the real Kimi Code
  endpoint and its kimi-code-cn preset (a custom Anthropic provider with
  Kimi's literal 400 was used), a real Codex session against a paid
  upstream, Windows/Linux runtime. #3739's second symptom (k3 losing
  thinking when output_config.effort is asked) is not addressed.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-30 21:38:00 +08:00
JoeyWu-tech ed9d849a21 gateway: a Gemini client's imageConfig reaches every Gemini upstream (#3820)
GuoJinguang (#3820): a Gemini client's generateContent asking a
gemini-*-image-preview model for generationConfig.imageConfig
{"imageSize":"4K"} drew 1024x1024 through magpie, where the same
request straight to their relay drew 4096x4096. The picture came, at
the model's default size, and nothing said the size had been dropped.

parseGemini didn't read imageConfig, so wherever magpie builds a Gemini
client's request again it was gone: a request asked for one body to a
Gemini API that isn't Vertex AI (always translated, since attempt asks
a Gemini API streamGenerateContent and reads the stream back into one
body), and every request to Code Assist or Antigravity, which go in
their envelope. A streamed request to a Gemini API, and a Gemini
client's request to Vertex AI, streamed or not, is relayed as it came
(passthrough) and kept it.

The reporter's request went to the relay's chat completions instead.
Their provider has a Chat URL beside its Gemini one, and attempt turns
relay off for a Gemini request asked for one body without ownAPI, so
it goes to the first API usable gives: Chat, as Speaks puts a custom
provider's Gemini last. That default is meant (uaSetup in
user_agent_test.go: "Gemini's own wire, which a provider on Chat too
isn't asked on"), and Chat has no field for imageConfig.

Now parseGemini keeps generationConfig.imageConfig as the client sent
it (Request.ImageConfig, raw as Metadata and ClientMetadata are, so
Vertex AI's own fields beside imageSize and aspectRatio go on too), and
buildCodeAssistSent, which every translation to a Gemini API goes
through, writes it into generationConfig: the Gemini API (buildGemini),
Vertex AI (buildVertex), and Code Assist and Antigravity in their
envelope. A request that asked for none is sent none. Chat, Responses
and Messages are left as they were: I found no vendor documenting a
field for it there, so none is made up. gateway-routing.md says where
imageConfig goes.

At a provider with both URLs, a request asked for one body reaches the
Gemini URL, and its imageConfig with it, when the user picks Gemini as
the API the model is asked on in the provider editor (SetModelAPI,
tested below). The next commit sends one that carries imageConfig
there by default.

Left as on main, each in its own issue:
- a Gemini client's image request to a provider with no Gemini URL
  (the Google Gemini preset's OpenAI-compatible endpoint, OpenRouter,
  another magpie, a relay saved with a Chat URL alone) carries no
  imageConfig, asks no modalities, and reads no image back from chat
  (#3935);
- /v1/images/generations and /v1/images/edits send a size to a Gemini
  image model as an aspect ratio only (drawGemini, drawChat), and to
  Code Assist only in words (drawCodeAssist), so nothing above 1K can
  be asked there; a Gemini client's request never takes that path
  (#3936);
- the rest of what a translated Gemini request drops: safetySettings,
  topK, seed, responseModalities, and the newer responseFormat
  (Google's next spelling of the same ask), among the fields
  parseGemini doesn't read (#3937).

This commit's tree (2b421ece, on origin/main 0c17aac2) wasn't run on
its own. It is 85b532c6 rebased, with the same internal/ patch-id and
the same gateway-routing.md line, which applied as is. Its two tests
ran at the next commit's tree, -count=5 and -race -count=5, and in the
full suite there. What was run for 85b532c6, at tree de27856c on
origin/main f8cd964a, the same code (not this tree), with go1.26.8,
linux/amd64, Linux 5.15, outside graftcp, umask 077:
- TestGeminiImageConfigReachesTheGeminiAPI, new: a fake relay records
  each request. Five generationConfigs (imageSize 4K, the reporter's;
  aspectRatio 16:9 and imageSize 2K beside a thinkingConfig; the
  snake_case image_config; none; temperature alone), at a provider
  with the Gemini URL alone (generateContent and streamed), with a Chat
  URL too (streamed), and with a Chat URL too and the model's API set
  to Gemini (generateContent): 4 of 4 subtests ok
- TestGeminiImageConfigReachesCodeAssist, new: the same five to an
  Antigravity sign-in's gemini-3.1-flash-image, generateContent and
  streamed, read in request.generationConfig: ok
- both on f8cd964a, the test file alone: red. The Gemini URL alone and
  the set-to-Gemini subtests, 3 asks each: "asked {...}:
  /v1beta/models/gemini-3-pro-image-preview:streamGenerateContent was
  sent "": ...", no imageConfig; Code Assist, both methods, 3 asks
  each: "sent "": ..."; the two streamed subtests pass, the relay
  having kept it
- broken by hand in a scratch worktree at that tree, each alone:
  - parseGemini not reading it: the same 12 lines red
  - buildCodeAssistSent not writing it: the same 12 lines red
  - buildCodeAssistSent writing it when none was asked: 8 lines red,
    "asked for none: ... was sent null" and "sent null"
- both, -race -count=5: ok
- go test -tags nogui -count=1 -timeout 45m -v ./internal/gateway,
  Bun 1.4.2: 5402 passed with their subtests, 3 skipped, 1 red,
  TestPluginToldWhereTheAgentWorks (#3675)
- tools/vetset.sh: gofmt -l clean; vet for linux, windows and darwin
  with -tags nogui, windows vet, and the three builds exit 0; untagged
  linux vet and build exit 1 at pkg-config (no GTK headers here)
- the full suite ran once, at 44a63bd5's tree; de27856c is covered by
  the gateway package and the vet set above

Not tried: the reporter's relay, or any real Gemini API, Vertex AI or
Antigravity image model; the upstreams are fakes that record the body.
Whether a relay's Gemini API passes imageConfig on to Google is the
relay's.

Landed by yetone in a batch of Coffemon's patches from the issues.
What was run, go1.26.8, on origin/main cc81ad4ea, then again at
70a0c387c (gofmt, the three vets, the changed tests, umask 077):
- mote (macOS 27): gofmt -l clean; go vet, GOOS=linux go vet -tags
  nogui and GOOS=windows go vet ./...: ok. edit and testenv at umask
  077; agent, provider, library and gateway with an empty .git above
  TMPDIR; davsync, imagemcp, plugin, library, edit, testenv whole; the
  changed tests in agent, provider, gateway and gui; the timing tests
  -count=10 (gateway, davsync, imagemcp) and -count=5 (agent): all ok.
  TestCoreScriptBudget ok: core 1,536,751 of 1,537,034, app.js
  1,312,975 of 1,315,316, no budget raised.
- Red on the old code: on origin/main, TestWriteAtomicReadOnlyHardLink
  at umask 077 and two Reasonix tests under an empty .git; on Linux
  (wsl-run) TestProgram at umask 077 with the old program.go. With
  each fix's code taken back to main's, the Gemini imageConfig tests,
  TestPluginToldWhereTheAgentWorks, TestSkillRepoTraced,
  TestTaggedHooksAlone, TestMainURL/TestMainView and update-auto,
  plugin-github-hooks, plugins-more-discover, plugin-namesake were
  red. Broken by hand: claudeKeyed always true (both
  OwnEndpointNeverAsked tests red), claudeAsk a no-op
  (TestClaudeFirstWriteAsksTheProxy red), GitAt taking any .git folder
  (the three TestGitOnDisk tests red).
- GUI: 123 files (plugins*, update-*, panel/tray/start/context, i18n,
  gui-zh-tw/ja/de and every file that evals app.js parts) in WebKit on
  Linux (wsl-run). 11 files had reds (click-scroll, panel-fold,
  plugin-card-update, plugin-github, plugin-move*, segs-glide,
  tray-totals, update-*), and run again side by side they fail the
  same on origin/main d80d75f30 (79 pass, 26 fail here; 78 and 27
  there). They are click-scroll guards ("the click must not scroll
  the page"), varying by language from run to run (#4385).
  copilot-ghe's route-after-close red is #1949, seen on main 244d80e23
  too. In Chromium on mote, Chromium segfaulted partway through files
  (#4125): context-map, context-scroll-end and context-tune fail the
  same on origin/main 0911a65e7, so the batch's own files
  (plugin-namesake, update-auto, plugins-more-discover,
  plugin-github-hooks) ran in Chromium on Linux: 62 of 62.
- Full suite (go test -tags nogui -count=1 -timeout 45m ./..., mote)
  at 472a0608f (on 70a0c387c): every package ok but internal/gateway,
  whose five reds were #4362's (Antigravity turned-away and
  TestCodexSpentGrokFailingIsTold), fixed on main in d80d75f30. After
  the rebase on 244d80e23 the five pass, and gofmt, the three vets
  and the targeted runs above were run again: ok. In Linux the
  sign-in, copilot, plugin-github*, plugins-more-discover,
  plugin-namesake, plugin-gateway, update-auto, quota-refresh-order
  and i18n files ran in both engines: 475 pass, 4 fail (copilot-ghe
  #1949, plugin-github's click scroll, both red on main too).
- Rebased again on c7171a256, over its budget fix e94bf7a08: gofmt, vet of
  gui, gateway, provider and plugin, TestCoreScriptBudget (core
  1,536,265 of 1,536,586 with the batch's last commit, statusTErr and settingsErr), the Gemini,
  GitOnDisk and plugin tests, and in Linux both engines i18n-keys,
  update-mirror, plugin-namesake, plugins-more-discover,
  plugin-github-hooks and update-auto (138 of 138): ok.
Not tried: the whole GUI suite (mote's WebKit wouldn't launch and its
Chromium segfaulted, #4125); macOS WebKit; the real app's window.
2026-10-30 15:53:22 +08:00
yetone e2b7233499 draw: a plugin's Gemini image model draws on generateContent through its fetch
XYenon (magpie-google-ai-studio, Discord) asked how a plugin's image
models reach /v1/images/generations and /v1/images/edits. A plugin's
model on Gemini's API (@ai-sdk/google) that says it gives images
(capabilities.output.image / modalities.output), or is named for them,
is now a drawer: Drawers lists it, and draw sends it to drawCodeAssist
(pluginDrawsGemini), as a Google sign-in's image models are drawn. That
asks generateContent with responseModalities ["TEXT","IMAGE"] through
the plugin's fetch, an edit's pictures as inlineData, and reads the
pictures from the answer. Request.draws asks for the IMAGE modality of
a model not named for images. Imagen (catalog.ImagesAPI, :predict) is
left out. The OpenAI-compatible plugin path (SenseNova) is unchanged.

Test: TestGeminiPluginDraws (fake plugin $FAKE_GEMINI_DRAWS: a model
named for images, one that only says it gives them, an Imagen).
Broken by hand: with the old draw.go the drawers are empty (red); with
the old codeassist.go the declared-only model is sent no
responseModalities (red).

Run on mote: gofmt -l clean; go vet ./internal/gateway ./internal/provider
./internal/plugin for darwin, linux (-tags nogui) and windows; go test
-count=1 -timeout 45m ./internal/gateway ./internal/plugin
./internal/provider ok at this commit on its first base 172e65c80
(gateway 515s, plugin 104s, provider 104s), and ok again with the next
two commits on top, rebased on abd94e0b1 (tree 7b8456f88: gateway 504s,
plugin 265s, provider 95s; vet for the three systems there too).
Not tried: a real Google AI Studio account through XYenon's plugin.
2026-10-29 22:54:06 +08:00
yetone 4db65681c1 library: a skill named in another script goes by its folder's name, so every one is listed
tnt1223 on Discord: Library › Skills listed 16 skills for
https://github.com/asdfgh1445/ctf-super-hub, which has 35 (one folder each
at the top, 35 SKILL.md in its recursive tree, not truncated).

Cause: the listing found all 35, but nameFor made each SKILL.md's `name`
fit for a file name by dropping everything outside ASCII. "CTF•密码学" and
ten more became "CTF", "Strix•RCE 测试" and nine more "Strix", "头脑风暴"
nothing, and unhiddenFirst lists skills of the same name once, so 35
became 16. Not a depth limit, cap, pagination or truncated tree: the probe
downloads the tarball and walks it; a truncated tree and GitHub's rate
limit are already said (skilltree.go, fetch).

Fix: a declared name that would lose a letter or digit (another script)
or comes out empty goes by its folder's name, which a repository keeps
apart. An ASCII name goes as before ("My Skill" is still My-Skill), so a
skill installed from one is still the library's. A skill at a
repository's top now falls back to the repository's name (srcFolder),
not the temporary download folder; candidates takes that name from each
caller (probe, Group again, CC Switch origin, new-skill check).

Tests: TestSkillsNamedInAnotherScriptAllListed probes and installs from a
fake of the repository built from its real tree (35 folders, front matter
names as written at 7715719); TestSkillNameFallsBackToFolderOnlyWhenLettersAreLost
and TestSkillAtTheTopNamedInAnotherScript cover the rule and the top
folder. No network.

Run:
- mote: go vet ./internal/library; GOOS=linux and GOOS=windows go vet
  -tags nogui ./internal/library; gofmt -l internal docs (empty);
  go test ./internal/library -run 'TestSkillsNamedInAnotherScript|
  TestSkillNameFallsBack|TestSkillAtTheTop|TestRepoWithAPlugin|Probe|
  CCSwitch|Regroup|NewSkill|From' -count=1: ok.
- wsl-run (magpie-desktop): go test -tags nogui ./internal/library
  -timeout 45m -count=1: ok 94.9s.
- Live, sandbox HOME (the package's TestMain/testenv), a throwaway test
  calling ProbeSkills("https://github.com/asdfgh1445/ctf-super-hub")
  against the real GitHub: 35 candidates, each named by its folder,
  nothing left out. Not committed.

Broken by hand: nameFor using the declared name whenever it isn't empty
(the old rule): TestSkillsNamedInAnotherScriptAllListed lists 16 with
names CTF/Strix/..., and the rule test fails on "CTF•密码学" and
"Café notes". Restored, green.

Not tried: the full ./... suite (mote at load ~350 from other runs; only
internal/library changed); the GUI suite (no app.js change); Windows test
run; installing the real repository's skills into a real agent. Not
changed: two different skills declaring the same ASCII name in folders of
different names are still listed once, as copies of one skill are
(unhiddenFirst).
2026-10-29 14:38:13 +08:00
yetone efb55b5c92 gateway: a schema's own type and properties beside a oneOf reach Antigravity (#4046)
Cause: plainSchema, which cuts a tool's schema down to the subset
Antigravity's function declarations take, read any node with an anyOf or
oneOf as its first branch that isn't null, and threw away everything the
node said itself. Philo's rg tool is an object with pattern and cursor
and a root oneOf of presence rules ({"required":["pattern"],"not":
{"required":["cursor"]}}, …). That first branch has no type, so the tool
went out as {"type":"string"} with no properties, and Claude on
Antigravity answered 400 "tools.4.custom.input_schema.type: Input should
be 'object'". The same held for such a node under a property, and allOf
lost a member's required when it had no properties of its own, or when
the node had a required list already.

Fix: a node that has its own type (other than only null), properties or
items beside an anyOf/oneOf keeps them, and the union is folded in
(foldUnion): a null branch makes it nullable; on an object, a field only
branches declare joins its properties, and a field every non-null branch
requires is required. The rest of a branch (which fields go together, a
"not") is dropped: Antigravity's subset has no union or not, Claude
there refuses a union at the root, and the client still checks a call
against its own schema. So rg goes as an object with pattern and cursor
and no required, which every valid call satisfies. A union with nothing
of its own beside it is still its first non-null branch, as before.
allOf now keeps every member's required (read before the member is
walked) beside the node's own.

Siblings: plainSchema is the only converter that flattens a union to one
branch. buildCodeAssist calls it for Antigravity only; Gemini API and
Code Assist get parametersJsonSchema as it came. provider.ObjectRoot
(objectSchema for Anthropic, the fold for xAI and the upstreams that
refuse a root union) already keeps the root's properties and passes over
constraint-only branches; TestObjectSchemaRootOneOfKeepsObject pins that
for this schema. geminiToolTypes and the Kimi/DeepSeek walkers only add
types or rewrite patterns. The community plugins have no schema
converter.

Tests: TestAntigravityRootOneOfKeepsObject is the issue's own test, and
TestAntigravityChatToolRootOneOfKeepsObject takes the reporter's route
(parseChat -> buildCodeAssist(..., "antigravity")). Both were red on
origin/main 7fe98c2af with {"type":"string"}. TestPlainSchemaUnionKeepsOwnShape
covers root and nested oneOf, anyOf and allOf, allOf beside oneOf,
fields from branches, required from every branch, a typed scalar, and a
bare union still read as its first branch.

Run on mote, at the tree origin/main 7fe98c2af plus this change:
- gofmt -l: clean
- go vet ./... for darwin, GOOS=linux and GOOS=windows: ok (darwin, linux, windows)
- go test -tags nogui -timeout 45m -count=1 ./internal/gateway: ok, 480.6s

Broken by hand, each red and then restored: the fold turned off (the
two #4046 tests and 8 table cases red, back to {"type":"string"}); the
required every branch shares ignored (3 cases red); allOf members'
required not read (2 cases red).

Rebased onto 44e1fec3a afterwards (two commits: a gateway upload test
and Routing GUI files, nothing this change touches); gofmt and the
tests above ran again at the rebased head.

Not tried: a live Antigravity request with a real account; the
reporter's failing request wasn't captured, so this is checked against
the converter, not the upstream. Not run: the full ./... suite or the
GUI suite (no GUI change).

Reported by imuxin (牧心), who found the cause and wrote the
reproduction test.
2026-10-28 18:41:18 +08:00
yetone d71362afcd gateway: a Gemini tool schema with items is an array, not its enum's string, and Antigravity gets items only on arrays (ferock)
ferock on Discord: Claude Code, model group/gemini-3-8-flash on a local
magpie whose group is served by a remote magpie's Antigravity, 400
"Remote magpie: Antigravity: GenerateContentRequest.tools[0].
function_declarations[19].parameters.properties[display].items: field
predicate failed: $type == Type.ARRAY". It worked in the morning and
broke after updating. The tool's literal schema wasn't posted, and no
Claude Code 2.1.311 built-in has a display property with items (searched
the binary), so it is an MCP tool of theirs.

Cause: geminiToolTypes (68ee4117a, v0.1.1624, 10-27 01:26) runs in
forwardOnce for any body whose model names Gemini, the local magpie's
forward to a remote magpie included. geminiSchemaType typed an untyped
schema from its enum/const values before its keywords, so
{"items":{...},"enum":["a","b"]} went on as type "string" with items
beside it. The remote's plainSchema kept the explicit type and the
items, and Google refused the whole turn. Before 68ee4117a the same node
reached plainSchema untyped and was inferred an array.

- geminiSchemaType: an object's or array's keywords (properties, items
  and the rest, keywordType, split out of schemaTypes unchanged) decide
  before enum/const values.
- plainSchema (the remote's Antigravity side, so a local magpie from
  before is served too): items/minItems/maxItems are kept only on an
  array and properties/required/min-maxProperties/propertyOrdering only
  on an object, as JSON Schema reads them; of a type list it takes the
  type its items or properties are for (["string","array"] with items is
  an array, not a string with items).
- docs/subsystems/gateway-routing.md says both.
- Sibling not changed: kimiSchemaType/collectUntypedEnums still type
  such a node from its enum; whether Kimi refuses items on a string is
  unknown, filed as #3867.

Tests (antigravity_display_items_test.go): the shape the error points to
(an untyped display with items and a string enum, plus properties with a
const) through geminiToolTypes, and through parseAnthropic +
buildCodeAssist(antigravity) as Claude Code sent it, as this version's
local passes it on, and as an older local passes it on (display typed
"string", type lists, a string with object/array keywords); every node
sent has items only as an array and properties only as an object.

Run, in a worktree at origin/main 32ea16c5a:
- go test -tags nogui ./internal/gateway -run 'CodeAssist|Codeassist|
  Gemini|Schema|Antigravity|Kimi|Plain|Grok|OneOf|Tool|Vertex|Google|
  Shape|Enum' -count=1: ok (60s)
- gofmt -l internal/gateway: clean; go vet -tags nogui (darwin),
  GOOS=linux go vet -tags nogui, GOOS=windows go vet on internal/gateway:
  clean
Broken by hand: gemini_schema.go back to origin/main,
TestGeminiToolTypesItemsBeforeEnum and TestAntigravityItemsOnlyOnArrays
FAIL (display typed "string"); codeassist.go back to origin/main,
TestAntigravityItemsOnlyOnArrays FAILs (items, minItems, properties on
type "string").

Not tried: the reporter's literal tool schema (not posted; the fixture is
the shape the error and the update point to), a real Antigravity
account, and a real two-magpie setup. Not run: the whole gateway
package or ./... (another session's full internal/gateway run was on the
machine, load ~60-75).
2026-10-27 16:34:19 +08:00
yetone 1885c607e2 gateway: Antigravity answers Codex's switched threads and Hermes' old persona with no setup
Antigravity answers some agents' system prompts with a fake 429 "Resource
has been exhausted", whatever quota is left. Jodiezzzzzz on X (10-27): a
Codex thread begun on GPT-5.x and switched to an Antigravity model got 429
again and again. zgoodz on X: "antigravity在Hermes里一样429". v0.1.1625
told the Codex case as a 400 with "start a new chat", which isn't zero
setup.

What Google matches, each tried on a real Antigravity account on 10-27
(in the system instruction, any case):
- "x-anthropic-billing-header:" (Claude Code)
- "built on Anthropic's Claude Agent SDK" ("running within the Claude
  Agent SDK" goes through)
- "You are Codex, an agent based on GPT-5" / "..., a coding agent based
  on GPT-5"
- new: "Hermes Agent, an intelligent AI assistant created by Nous
  Research", Hermes' earlier default SOUL.md, kept by anyone who edited
  their SOUL.md. Hermes' current default ("You are Hermes Agent, built by
  Nous Research") goes through.
Each goes through with a zero-width space after its first letter.
"Y​ou are Hermes Agent, an intelligent..." still fails, so the
break goes inside the matched phrase itself.

Now codeAssistBody puts that zero-width space into each matched line
(antigravityCloak), in the system instruction only, and only for an
Antigravity account. Gemini CLI's account on the same envelope, and
every other provider and protocol, get the prompt as the agent wrote
it. The text added names nothing; it is one U+200B per line.
`magpie provider set antigravity prompt=as-written` (PromptAsWritten,
kept through Save/withPicks and the GUI's save) turns it off. Then the
v0.1.1625/#2156 fallback stands: a 400 with a hint (now one for Hermes
too, in the Routing page's five languages) and Antigravity skipped for
6h in a group.

Default-on, as the community antigravity-cloak middleware's README
says, changes what Google is sent so a request it means to refuse goes
through. That may be against Antigravity's terms. The owner asked for
it ("破解过 antigravity 提示词让其可以在别的 agent 中使用"), and it is
scoped to Antigravity accounts with an off switch.

Run at this tree (rebased on origin/main):
- go test -count=1 -timeout 45m ./internal/gateway/ ./internal/provider/
  ./internal/cli/ ./internal/gui/: gateway, cli and gui ok; provider
  died in TestUnreadLoginsWriteErrorsKeepCredentials ("close of synctest
  channel from outside bubble" in filememo.Forget), #3632, red on main
  since 091153bf; with -skip of that test, provider ok.
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok. go build: ok.
- GUI (node --test, Playwright 1.62, chromium and webkit):
  routing-ag-turned-away, i18n-keys, gui-ja, gui-de, gui-zh-tw,
  routing-js, panel-routing: 45 pass, 0 fail.
- Broken by hand: with the cloak skipped, TestAntigravityAnswersHermes
  AndCodexByDefault and TestOnlyAntigravityIsSentThePromptBrokenUp go
  red; without withPicks' line, "prompt=as-written isn't kept".
- Real account, sandbox HOME with only the Antigravity login copied,
  this build on 127.0.0.1:3496:
  - real Hermes Agent (AIAgent, sandbox SOUL.md = the old persona plus
    one line): "OK", 200. With prompt=as-written: 400 with the Hermes
    hint. Back on default: 200.
  - real Codex 0.162.1: a thread begun on gpt-5.5 (against a local
    fake Responses server), then `codex exec resume <id> -m
    antigravity/gemini-3-flash` through this build: "OK". With
    prompt=as-written: 400 with the Codex hint.
  - a synthetic switched Codex Responses thread, with and without
    web_search: 200.
  - opencode, droid, kimi, pi, gemini-cli, qwen, crush, goose, amp and
    openclaw identity sentences: never refused, as written.
Not tried: Claude models on Antigravity (the sandbox account's Claude
quota is spent, so the Claude Code lines were checked on Gemini 3
Flash only); other agents' whole prompts, only their identity lines;
the Windows box; the whole GUI suite.

The plugins repo's antigravity-cloak 0.1.2 adds the Hermes line for
magpies before this one.
2026-10-27 04:16:20 +08:00
yetone b5d17b26e0 gateway: Antigravity's 429 to Codex's GPT-5 prompt says why and rests nothing, on the web-search path too (Jodiezzzzzz on X)
From Codex, every call to antigravity/claude-opus-5-5 failed with
"exceeded retry limit, last status: 429" while dsh worked on the same
account. The call was an agent_created_thread, and the vendor said
"Resource has been exhausted (e.g. check quota)".

Cause: a Codex thread begun on a GPT-5.x model keeps "You are Codex, an
agent based on GPT-5..." as its first developer message after /model,
resume -m or a fork, and magpie lifts it into systemInstruction.
Antigravity answers that line with a fake 429, whatever quota is left,
as it does Claude Code's (#666). Codex also sends a web_search tool every
turn, so for an Antigravity model magpie serves search itself (translate
-> searchReply -> askTranslated), and that path passed the bare 429 back:
no hint, no 400, so Codex retried to its limit.

- antigravityTurnsCodexAway: the two Codex GPT-5 opening lines count as
  a turned-away prompt; antigravityHint picks the Codex hint for them.
- antigravityRound wraps the search path's ask, so its 429 and an
  in-stream refusal get the same 400, hint and no rest as translate's.
- antigravityForeseen returns the hint, so a group skips Antigravity for
  the next 6h saying which prompt.
- The Routing page shows the new hint (routing/client.js HINTS) in en,
  zh, zh-TW, ja and de.
- Rest: none. The refusal is about the prompt, not the account (Fail
  "prompt"); a second account answers the same.

Plugins: middleware-antigravity-cloak 0.1.1 (plugins a52d1b3) breaks
the two Codex lines with U+200B. Its body says "npm had 0.1.0": wrong,
the package is not on npm; dist had 0.1.0 and now has 0.1.1 (6fd1438).
No mover applies.

Real account (owner's Antigravity, sandbox HOME copy, gateway built from
this branch) and real Codex 0.162.1:
- codex exec resume <a gpt-5.5 thread> -m antigravity/gemini-3-flash:
  before, 429 retried to "exceeded retry limit"; after, one request and a
  400 with the Codex hint; route try (429, prompt), no rest.
- A new Codex chat on the same model: 200.
- The two lines with U+200B after the first letter: 200; whole: 400.

Broken by hand:
- antigravityTurnsCodexAway returning false: the Codex tests go red
  (Codex got 429; the group's skip doesn't say why).
- The antigravityRound wrap removed: the search=true subtests go red
  ("Codex got 429").

Run:
- go test -count=1 -timeout 45m ./internal/gateway/: ok (476s, at
  865df2472; main's next three commits touch only GUI files).
- go test -count=1 -timeout 45m ./internal/gui/: ok (230s, at the pushed tree on a6d7e02c7).
- gofmt -l: clean; go vet ./internal/gateway/ for darwin, linux, windows.
- GUI, chromium and webkit: routing-ag-turned-away, i18n-keys, gui-ja,
  gui-de, gui-zh-tw, routing-wb-refused, routing-blocked 41/41; at the
  pushed tree routing-ag-turned-away, i18n-keys, routing-steps-cap and routing-js 34/34.
- Rebased on b9ab17231 (routing client.js): routing-ag-turned-away,
  i18n-keys, routing-free-seat 45/46, the red webkit zh-TW `.rt-day`
  click timeout at load 163 (#3781's class); routing-ag-turned-away
  alone 20/20 after. go test -run 'Budget|I18n|Hint|Routing' on
  internal/gui and internal/gateway: ok.
- Rebased again on 68ee4117a (gateway: gemini_schema, unrouted,
  masking wait): gofmt, vet x3, and go test -run
  'Antigravity|CodeAssist|Search|Gemini|Unrouted|Masking|Translate|Continu'
  ./internal/gateway/ ok; the whole package was not run again at this
  tree.
- Under load 89-150: TestTrayCellClickReleasedPanel killed at 20s
  (#2645), routing-js webkit zh (#3774), panel-routing and
  routing-zcode-blocked webkit zh click timeouts (#3781). All pass alone.

Not tried: Claude Opus itself (the sandbox account's free-tier Claude
quota was spent while probing, so gemini-3-flash stood in; the prompt
check is model-blind); the cloak installed in a running magpie; the
Windows box; the full GUI suite.
2026-10-27 01:33:53 +08:00
yetone b28e5ffd81 gateway: an array with no items goes to Antigravity with items {}, and Google's schema 400 falls through (plugins#375)
gcq909893267 (plugins#375): Claude Desktop's own MCP tools __batch and
__guide declare an array property with no items ("batch":{"type":
"array"}). plainSchema passed it through, and Google turned the whole
turn away: 400 "GenerateContentRequest.tools[0].function_declarations
[17].parameters.properties[batch].items: missing field". The group's
next member was never asked.

- plainSchema (codeassist.go): every node it writes that is type array
  with no items gets items {}, which Google takes (the reporter's A/B:
  {} and {"type":"string"} both 200). Its walk is the one every nested
  place goes through (properties, items, anyOf/oneOf members, allOf,
  $ref into $defs/definitions, a type list with null), so the check at
  the end of a node covers all of them.
- Siblings: plainSchema is the only Gemini-side schema cleaner. Gemini
  CLI's Code Assist and Vertex AI / a custom Gemini API go through the
  same buildCodeAssistSent but send parametersJsonSchema, full JSON
  Schema, where an array with no items is valid; gemini.go's jsonSchema
  is the other direction (a Gemini client's schema read in). Left as
  they are.
- Fall-through: a 400 that points at a function declaration's
  parameters (function_declarations[N].parameters) is now in
  shapeWords, so shapeRefused/retryable read it as the request's shape
  on that vendor: the next member is asked once, and the member doesn't
  rest (Fail "shape", Rest nil), as OpenCode Go's "schema exceeds the
  maximum nesting depth" (#1870). Not resting is right: the account is
  fine and the same request fails the same on every Antigravity
  account; the reporter's same tools answered 200 on a non-antigravity
  member. A declaration's name or the contents are not matched. A
  shape refusal still tries the same provider's next account first, as
  every shape refusal does now; not changed here.

Tests (antigravity_array_items_test.go), fixtures from the reporter's
literal request and error line:
- TestAntigravityArrayGetsItems: the reproduction through
  buildCodeAssist(antigravity); both declarations carry items {}.
- TestPlainSchemaArraysAllHaveItems: nested arrays under each keyword
  get items {}, an array with items keeps them, a non-array gets none.
- TestGroupFailsOverGoogleSchema400: a group's first member answering
  Google's 400 hands it to the second, Fail shape, no rest; plus a
  shapeRefused table (Google's both wordings, the agent-facing wrapped
  form; a function name and contents error, and a 500, are not).

Run: go test ./internal/gateway/ -run 'CodeAssist|Codeassist|Gemini|
Schema|Antigravity|Shape|FailsOver|Fallback|Region|Retryable|Refus|
Vertex|Plain|Google' ok (307 tests, 31s); gofmt -l clean; go vet,
GOOS=linux go vet -tags nogui, GOOS=windows go vet on internal/gateway
clean.
Broken by hand: codeassist.go reverted, the first two tests FAIL
(declaration 0 parameters.properties.batch: {"type":"array"}); fallback.go
reverted, TestGroupFailsOverGoogleSchema400 FAILs (a 1, b 0).
Not tried: a real Antigravity account (the reporter's own A/B shows
items {} answers 200); the full go test ./... suite; Gemini CLI and
Vertex AI with an items-less array against the real APIs.
2026-10-25 15:56:16 +08:00
yetoneandggbdpq 919c8b934a gateway: a second answer to one call is dropped on the way to Gemini and Responses (#2262, ggbdpq)
A client that answers one tool call twice sent Google a call turn with
more functionResponses than functionCalls, which Google refuses with 400,
along with every later turn of the conversation. The Chat and Messages
builds already keep the first answer (pairToolMessages, pairToolBlocks).
The Gemini build (buildCodeAssistSent: Google sign-in, Vertex, a custom
Gemini provider) and the Responses build (buildResponses) now leave the
second one out before they build, with the images it carried
(dropSecondAnswers). A call made again under the same id takes an answer
of its own, and the request itself is left as it was, since a fallback
builds from it again.

This differs from the issue's patch. It dedups across the whole history in
pairFunctionTurns, keyed by id, or by name when there is no id. Keying by
name drops a real answer to a second call of the same function. Keying by
id ignores a call made again under that id. The patch also left the
duplicate's images in the turn and didn't cover Responses. Also fixed:
parseGemini matched a functionResponse with no id to the latest call of
that name, so two calls of one function were both answered as the second.
Each now goes to the first call of that name still unanswered.
pairToolItems (relayed Codex bodies) already keeps one answer per call and
is unchanged.

Run:
- gofmt -l, go vet (darwin -tags nogui, GOOS=linux -tags nogui,
  GOOS=windows): clean.
- go test -tags nogui -p 4 -timeout 40m ./... with the other three
  commits of this push: see the last one's body.

Broken by hand: TestGeminiDropsASecondAnswer,
TestSecondAnswerDroppedWithItsImages and
TestGeminiClientUnnamedCallsAnsweredInOrder fail on the code before this.

Not tried: against Google's or a Responses upstream's real API.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-15 09:36:25 +08:00
yetone eb7199e120 gui: Routing is a plugin's page, its script, style and words in plugins/routing (P2)
P2 of docs/subsystems/plugin-runtime.md, the third page after Sessions
and Library.

- routing.js and routing.css move to assets/plugins/routing/ (client.js,
  routing.css). Its part's html is the page's head and boxes that were
  index.html's <main id="view-routing">; the rest is drawn by
  routingPage, run at mount since it builds on app.js. It keeps itself
  after that as it did (its own hidden, the language, focus), so its
  hooks are dirty and discard, a routing group being edited, which
  show() and the window's close ask through magpie.call:
  window.routingDirty and discardRouting are gone.
- plugins/routing: Essential, Requires window and gateway, in use while
  the user has a routing group (not Auto, not Hidden), since the page is
  where it is edited. The gateway routes the same with it off.
- With it off, what leads to the page goes too: the nav and panel tabs
  and the panel's section (data-feature="routing"), the guide's Open
  Routing, Providers' "Make a routing group of …", the Usage list's
  View routing and its time as a link, the context card's Latest
  request. A panel left on its Routing tab shows Agents.
- What other pages use of it stays on window: openRoute (context.js),
  kindName, swapWhy, routedWhy (Usage's Requests), newGroupWith
  (Providers), panelRoutingShown (the panel).
- The 505 strings only Routing says move from i18n.js to
  plugins/routing/i18n.js (4 languages); i18n.js 17048 → 15032 lines.
  The plugin's own name and line stay in i18n.js: the Plugins page
  says them with the plugin off (TestBuiltinsTranslated).
- Tests and comments that named routing.js name the new path (gateway's
  antigravity_rest and loop_guard, codeassist.go, usage.go,
  web_compress, group_member_info, assets_revalidate, font-cascade,
  win-fonts, three routing-*.test.cjs). builtins.test.cjs and
  builtins_test.go count seven built-ins and switch Routing off: its
  tabs go, the page shown stays.
- docs: plugin-runtime.md, gui-shell.md, gateway-routing.md.

Run, first on origin/main 3ec45e715, then after rebasing onto af27b70b4
(main's routing.js, css, app.js and i18n.js changes since were carried
into the moved files; its new Routing words, as the rules' conditions,
are in the plugin's i18n.js):
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.
- go test -count=1 ./internal/gui ./internal/gateway ./internal/usage
  ./internal/pluginrt ./plugins/...: ok (gateway 1800s under load,
  -timeout 45m; gui with -skip TestMainWindowCorners, #1936).
- All 193 GUI test files, 3 at a time at load ~250, Chromium and WebKit,
  at the Usage commit on 743fcc035: 185 and 186 green. Every red run
  alone here and on a just-fetched origin/main c524bc018:
  - the same on main: routing-model-rest (#2115), routing-wb-restricted
    (#1905), usage-agents-hide (11 of 16 in both, #2211), usage-fold
    (#2163: 12 of 14 here, 9 of 14 on main over 7 runs, the same 4px),
    quota-count-wrap and quota-name-translated in WebKit (#2228);
  - red only under load, green alone on both: routing-flood (#2215),
    routing-log-icons, usage-ledger (#2211), and three plugin-* files
    whose tree was rebased under them mid-run.
- days-fit, failed-open, side-calls and burst-speed, red on main after
  cf455ebd5, are fixed before this commit (#2134, d692b2548).
2026-10-15 01:32:12 +08:00
yetone a4d580fa24 gateway: a group skips Antigravity for the system prompt it just turned away (#2156)
Antigravity answers Claude Code's and the Agent SDK's system prompt (the
x-anthropic-billing-header line, "built on Anthropic's Claude Agent SDK")
with 429 "Resource has been exhausted" whatever quota is left (#666).
magpie already tells it as prompt_turned_away, rests nobody and hands it
on, but each Claude Desktop turn in a group waited on the same refusal
first (#2156: 429 in 1073ms, then cursor/composer-2.5 200).

Now, once Antigravity has turned such a request away (any of the three
paths that set holdWriter.turnedAway), for agForeseeing (6h) after, the
candidate loop skips an Antigravity candidate for a request that carries
the line, when someone is left after it (antigravityForeseen). The skip
goes in Fallback with the hint, sets `other` as the asked path does, and
changes no account state. The last one left is still asked and told the
400 with the hint. A request without the line (titles, Codex) still goes.
An old refusal foresees nothing, so a block Google lifts is noticed. The
lines are still neither rewritten nor hidden (#666). The stamp is per
Server, in memory.

TestAntigravityTurnedAwayRestsNobody's "asked first again" half now
checks it with a turn without the line, since one with it is foreseen.

Run:
- TestAntigravityTurnedAwayIsForeseen: fails with the skip turned off
  ("Antigravity was asked again for the prompt it just turned away"),
  passes with it; TestAntigravity* -count=3 green.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows ok.
- go test -tags nogui ./... in a sandbox HOME at load average 140-220:
  everything green except 10m timeouts in agent, cli, gateway, library,
  provider and TestSetAnswersWhileDevinAndProvidersHang (#1375, noted
  there); those six packages rerun with -timeout 45m: all ok.
Not tried: the skip against the real Antigravity account (the refusal
itself was reproduced with a real account before: 400 with the line,
200 without), nor Windows/Claude Desktop as the reporter uses. No GUI
change.
2026-10-14 18:41:56 +08:00
yetone 52be997b39 gateway: Gemini 4 and later are told a thinking level, at the level asked (#2083)
Gemini 4 Argon turns every thinkingBudget away with a 400 ("Thinking
budget is not supported for this model. Use thinking level instead."),
and magpie sent it one: thinkingConfig gave a level only to ids starting
gemini-3 (and gemini-pro-agent), so a gemini-4-* id on a provider that
speaks Gemini's own API (the reporter's google-vertex catalog, a custom
gemini= base) got a budget on every request.

geminiGeneration reads the generation from the id (gemini-N, after a
models/ prefix too); 3 and later are told a level. Medium goes as medium
on a later generation as it does on Flash: Argon lists low, medium and
high, and the effort is already fitted to the model's levels (fitFor). An
id naming no generation (gemini-flash-latest, an alias) is 0 and keeps
its budget, as before. The Chat path (aiStudioThinking) already gave a
budget only to gemini-2, and Vertex's vertexThinking is unchanged.

Run:
- TestGeminiLaterGenerationsToldALevel: a fake Gemini upstream that
  answers a budget on gemini-4* with the reporter's literal 400; Argon
  low/medium/high on /v1/chat/completions and /v1/responses, 3.8 Flash,
  3 Pro medium (high, as before), 2.5 Flash (budget 24000). FAILs on the
  old code with Argon's 400 on both routes; FAILs with "thinkingLevel
  high, want medium" when only the medium case is reverted.
- TestGeminiGeneration (id table).
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows on
  internal/gateway; go test -tags nogui ./internal/gateway/.

Not tried: a real Gemini 4 Argon request (no AI Studio or Vertex key on
this machine). A magpie alias that names no generation but is wired to a
Gemini 4 model still gets a budget.
2026-10-14 15:34:16 +08:00
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