Commit Graph
24 Commits
Author SHA1 Message Date
yetoneandggbdpq cbd379e1b7 gateway: a Gemini request's generationConfig keeps the fields magpie doesn't read (#3937)
parseGemini read a generationConfig of the fields magpie knows —
maxOutputTokens, temperature, topP, stopSequences, the structured output
ones, thinkingConfig, and, since #3820, imageConfig — and
buildCodeAssistSent built one of the same, so a translated request (a
Gemini client's generateContent asked of a Gemini API in one body, and
every request to Code Assist or Antigravity) went upstream without the
rest of what the client asked: topK, seed, candidateCount,
presencePenalty, frequencyPenalty, responseModalities, mediaResolution,
speechConfig, responseFormat (#3937, yinwu01).

The request now carries the keys magpie doesn't read or write
(Request.GenConfig), and one built for an upstream that speaks Gemini's
own API — the Gemini one, and Vertex AI — is sent them beside what magpie
rebuilt, as they were sent, camelCase and all (geminiCamel). A field
magpie sets itself stands: a draw model is still asked for
["TEXT","IMAGE"] whatever the client's own said. Code Assist's and
Antigravity's envelope is sent none of them: their spelling of these
fields isn't documented, and no other API takes Gemini's names.

candidateCount is not carried (changed in the port): magpie reads a
Gemini reply as one answer, and codeAssistDecoder runs every
candidate's parts into it, so a second candidate would be mixed into
the first answer's text. It stays dropped, as before.

Run (mote): go test -tags nogui -count=1 -run
'TestGeminiGenConfig|TestGeminiImageConfig|Gemini|Vertex|CodeAssist'
./internal/gateway/ ok; gofmt -l clean; go vet -tags nogui
./internal/gateway/ clean.
Broken by hand: gemini.go put back to origin/main, both new tests FAIL
(nothing but magpie's own fields reached the relay); candidateCount
taken out of genReadOrBuilt, the reporter's-fields and snake_case cases
FAIL with candidateCount sent.
Not tried: a live Gemini API or Vertex AI key (none here); safetySettings
and cachedContent, top-level fields the issue also names, are still
dropped on a translated request.

Fixes #3937

Generated-by: GLM-5.3-Flash (ZCode)
Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-06 10:04:22 +08:00
ggbdpq 5662c53a02 gateway: a Gemini request's thinkingConfig counts as its effort (#4529)
bodyEffort read a request's reasoning effort for Chat
(reasoning_effort), Responses (reasoning.effort, or its last
configuration_update's) and Anthropic (output_config.effort), and had
no Gemini branch: a request to a Gemini native endpoint
(:generateContent, :streamGenerateContent) that asked its model to
think through generationConfig.thinkingConfig — thinkingLevel, or a
thinkingBudget — recorded no effort at all. The upstream ran at the
strength asked (the reporter's request spent 625 thinking tokens at
thinkingLevel high), but the request list, the usage and a group
rule's effort condition all saw "", where the same client through the
OpenAI-compatible endpoint shows reasoning_effort fine.

parseGemini already reads the same config into r.Effort, through
gThinking.effort (level, else budget as the level it is nearest, -1 as
medium, none for a budget of 0 or includeThoughts alone). The new
geminiBodyEffort reads it the same way — geminiCamel first, as
parseGemini does, since clients send the snake_case spellings too —
and bodyEffort's new Gemini branch returns it. requestEffort and
routeEffort come along, so the route record, the usage and group
rules all see what the client asked for. Nothing sent upstream
changes.

Writing effort back (withBodyEffort) stays without a Gemini branch:
no reporter asked for it, and it would have to fit the level to the
model's own words.

Verification on the branch's base 47173f593, macOS arm64:
- RED before the fix, GREEN after: TestGeminiRequestEffort, new, runs
  requestEffort and parseGemini on the same bodies and asks for the
  same answer — thinkingLevel high, thinking_level LOW, thinkingBudget
  512, thinking_budget 32768, -1, 0, includeThoughts alone, no
  thinkingConfig.
- go test -tags nogui ./... : ok (see the issue comment for the rest).

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

Broken by hand: with the gateway.go and gemini.go hunks reverted,
TestGeminiRequestEffort is red on its level and budget cases
(requestEffort "", want "high", ...). Callers of bodyEffort checked:
withBodyEffort is a no-op for Gemini, and effortOf never returns
none or minimal, so the 5338 branch is never reached for Gemini.
2026-11-01 02:45:01 +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 8eb7f5565b gateway: a translated body lets its built conversation go as it fills (#4004)
marshalBody wrote a translated request's list (Chat's and Anthropic's
messages, Responses' input) an item at a time, but the list itself, the
conversation the builder made, strings joined from the request's parts
among it, stayed held in the body's map until the whole body was
written: at the body's peak it sat beside the written items and the
body. The builder names that list as spent, and each item is set to its
zero value once written. Every caller's map is its own and dropped after
the call (buildChat, buildAnthropic, buildResponses); buildGemini spends
nothing. Keys are checked before anything is spent, so the json.Marshal
fallback for an odd key still sees the whole map.

Measured on mote, TestZZPeak4004-style scratch harness (not committed):
a 45 MiB Codex conversation sent Responses -> Chat through the gateway,
GOGC=10, HeapInuse sampled every 2 ms, 3 runs each:
  base 425a61322: peak 302, 301, 301 MiB (base heap 54 MiB)
  this change:    peak 278, 271, 273 MiB
Live at send is the same, 149 MiB above base (the request, its parse,
the body), as the conversation was garbage by then either way.

Tests: TestMarshalBodyLetsSpentGo (new) writes a list of probes, each
looking whether the item before it was let go, and that a list not
named spent is unchanged. Broken by hand (spend never zeroing): red,
"items [0 1 2 3] were still held when the next was written".
TestMarshalBodyIsJSONMarshal passes with the messages spent.

Run on mote at 425a61322 + this change: GOOS=linux/windows/darwin go
vet -tags nogui ./internal/gateway/: ok; go test -count=1 -timeout 45m
./internal/gateway/: ok (537.8s). Rebased onto f6e7214af, whose only
gateway change is a host in buildChat's inlineThink; at the pushed head:
the three vets again ok, and go test -run 'TestMarshalBody|MiniMax|
Minimax|TestChat|TestResponses|TestAnthropic|Translat' ./internal/gateway/:
ok (31.8s).

Not tried: a real upstream; the bytes sent are the same, which
TestMarshalBodyIsJSONMarshal holds to json.Marshal's.
2026-10-29 02:17:47 +08:00
yetone 0b99b8fbe5 gateway: a translated body is written a message at a time (#4004)
jihuayu's heap profile (#4004, v0.1.1707 on a 2 GiB server) had
json.Marshal and its bytes.growSlice under buildChat as the largest
holders, about 128 MiB together, on 45 MiB Codex requests. json.Marshal
writes the whole body into one buffer that doubles as it fills and then
copies it out, so each grown-out buffer is garbage until the next GC.

marshalBody writes the same bytes: the keys sorted, every value through
json.Marshal, but a list (messages, input items, contents) one item at a
time, into one buffer sized to what they come to. buildChat,
buildResponses, anthropicBody and buildGemini use it. Anything
json.Marshal refuses gets json.Marshal's own answer. A slice's items are
marshalled by address, as json.Marshal reaches them, so a MarshalJSON on
the pointer is still called.

Run on mote at this head:
- TestMarshalBodyIsJSONMarshal: byte-equal to json.Marshal for lists of
  maps and of typed maps, one-item, empty and nil lists, nil, []byte,
  json.RawMessage and lists of it, pointer and value Marshalers, HTML
  characters, U+2028/2029, control characters, escaped keys; NaN, Inf
  and a chan are refused as json.Marshal refuses them.
- TestMarshalBodyAllocatesTwoBodies: a 47 MiB, 170-message body.
  json.Marshal allocated 205 MiB, marshalBody 98 MiB. The bar is 2.5x the
  body (117 MiB), which json.Marshal's 205 fails.
- go vet ./internal/gateway for darwin, linux and windows: ok.
- go test ./internal/gateway -timeout 45m: ok (543s), and again after
  the rebase onto origin/main, at this head: ok (529s).

Real account, on this Mac in a sandbox HOME with only the DeepSeek
provider copied: a streamed Codex-style /v1/responses request with a
function call and a ~100 KB tool output (translated, 36,343 tokens in)
answered about the tool's output and completed. /v1/messages and
/v1/chat/completions also answered 200.

Not tried: a 45 MiB request against a real vendor; the plugin RPC copy
and toolOutput's unquote, which the same profile lists, are separate
changes.
2026-10-28 17:50:17 +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
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
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 173ab71e8b gateway: a Gemini client's thinkingConfig no longer reaches a quiet group member as reasoning_effort (#1253)
withoutReasoningAsk (#950) took the reasoning ask off Chat, Responses and
Anthropic bodies sent to a group member known not to think, and passed a
Gemini-protocol body through as it was. parseGemini then read
generationConfig.thinkingConfig into the request's effort, and the quiet
member was sent reasoning_effort.

It now drops generationConfig.thinkingConfig when it asks to think, by
the same reading parseGemini uses (gThinking.effort: a level, a budget,
-1 as medium), keeping the rest of generationConfig. A budget of 0 is no
ask and stays. A member the user fixed at an effort isn't quiet and is
sent the ask as before.

TestGroupQuietMemberGeminiThinking sends generateContent through
lanGuard(s.Handler()) to a group whose thinking member fails over to a
quiet one, for thinkingLevel, a budget and -1. Without the change it
fails: "the quiet member was sent map[... reasoning_effort:high ...]";
TestWithoutReasoningAsk's new Gemini cases fail too. With it both pass,
and the thinking member and a fixed quiet member still get
reasoning_effort. go test -tags nogui ./internal/gateway passes under a
temp HOME with pinned caches; the three group tests pass with -race
-count=5; go vet and GOOS=linux/windows go vet -tags nogui pass.
2026-10-08 13:58:58 +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 da1fd6cb0c gateway: a Gemini functionResponse's own parts reach the upstream — the image agy's view_file read (#1038, handong66: agy via magpie can't see images, the model makes up what they show)
agy sends the image a tool read inside the function response, as Gemini 3's
multimodal function responses carry it: functionResponse.parts[].inlineData
(under role "model", as agy sends tool results). parseGemini read only id,
name and response, so the parts were dropped before any translation: the
reporter's prompt was 96 tokens instead of 1115 and the model invented the
watermark and subtitle, with a 200 / STOP the client couldn't tell apart.

parseGemini now reads functionResponse.parts (camelCase, and snake_case
through geminiCamel): an image (inlineData or fileData) becomes the tool
result's Images, which every builder already carries — Antigravity/Code
Assist and Factory's Gemini as inlineData right after the functionResponse
in the same turn (the shape top-level images already work in), Anthropic as
tool_result image blocks, Responses as function_call_output input_image,
Chat as the image message after the tool's. A non-image file (a PDF) can't
sit in a tool result, so it follows the result in the same turn instead of
being lost. walkImages now looks inside a Gemini functionResponse's parts
too, so a model that can't see is sent the request with the tool's image
replaced by the omitted note, as for every other surface's tool images.

Tests from the reporter's literal request shape (view_file, call_462432,
response.output + parts[].inlineData; role model and user; camelCase and
snake_case): TestGeminiFunctionResponseImage (parse + Code Assist, Anthropic,
Chat, Responses bodies), TestGeminiFunctionResponseImageReachesUpstream
(/v1beta to a Chat upstream through the gateway), TestGeminiFunctionResponseFile
and TestGeminiFunctionResponseImageIsATools. All four fail without the change
("Images:[]", "the tool's image was not seen"). Not run against a real agy
or Antigravity account.
2026-10-07 00:23:34 +08:00
yetone 86f48071cc gateway: an image or a PDF sent as Gemini's inline_data, or as a Chat Completions file part, reaches the model, and a Gemini stream gets no keepalive comment (#934, handong66)
/v1beta read a part's fields only as camelCase, while Google's API takes
their proto names too (inline_data, mime_type, file_data, function_call,
system_instruction, generation_config…), which agy and raw SDK calls
send: the image was left out, the call still answered 200, and the model
made up what it held. geminiCamel spells a request's fields in camelCase
before anything reads it, keeping the caller's own keys (a call's args, a
result's response, the schemas) as they are.

A Chat Completions {type: file} part (file_data as a data: URL or bare
base64, or a file_id) was dropped; it is now the request's file, which
Antigravity and other Gemini upstreams are given as inline data and the
others are told of ([attachment application/pdf]).

A held stream's keepalive comment went to Gemini clients too, which
agy fails on ("invalid stream chunk: : keepalive"); a Gemini stream gets
none, as geminiEncoder.keepalive already sent none.

TestGeminiSnakeCaseParts, TestGeminiSnakeCaseImageReachesUpstream,
TestChatFilePart and TestHeldGeminiStreamSendsNoComment are new and each
fails without the change. go vet, go build (GOOS=linux nogui, GOOS=windows)
and go test -tags nogui under a temp HOME pass (TestSavedButSignedOutClaudeServed,
in a package this doesn't touch, failed once on a 5s timeout and passes alone).
2026-10-06 01:09:29 +08:00
yetone 154c7e8d96 gateway: a Gemini functionResponse is the user's turn whatever role it came under, so agy's conversations end with the user's turn (#650, pwu4: Antigravity through a remote magpie answered from the second turn "Requests ending with a model turn are not supported") — Antigravity CLI, captured against a stub, sends each tool's result as {"role":"model","parts":[{"functionResponse":…}]} right after the call. parseGemini kept it in an assistant message, so once a turn ran a tool the request ended with the model's turn: straight to Code Assist, or through another magpie over Anthropic Messages (Chat and Responses happened to put it right). A functionResponse now starts a user message of its own, and the parts around it keep their role and order. TestAgyToolResultsAreTheUsers (agy's captured shape, with and without a tool, direct and via Anthropic, Chat and Responses) fails on the old code. go vet, builds (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass. Not tried against real Antigravity. 2026-10-03 15:04:36 +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
Davy 94cadbc34d fix(factory): open other agents' Factory requests as Droid (#519)
* fix(factory): open Anthropic requests with Droid's line

Factory only accepts a subscription request whose body opens as Droid
(#242, #506). Responses and chat completions already do. Anthropic
Messages now puts that line in the first system block, as droid2api
does, and keeps the agent's own prompt after it.

* fix(factory): serve Gemini on Factory's generate route

Every agent already reaches Factory's Claude, GPT and open models:
the gateway translates its own API into the model's, and the body
opens with Droid's line. Gemini was the wire still missing.
droid2api posts those models to /api/llm/g/v1/generate and prepends
the same line to systemInstruction. Factory now does that too.

The models are the ones droid 0.232.0's CLI registry still offers
(gemini-3.1-pro-preview, 3.8/3.7/3.6/3.5 Flash, gemini-3-flash-preview).
2.5 and Gemini 3 Pro Image are availableInCLI false there and stay out.
They are not Droid Core. A streamed Gemini reply comes back in the
client's own API.

TestFactoryFromEveryAgentWire posts Claude Code, Codex, Pi, OpenCode
and Gemini CLI at Claude, GPT, GLM and Gemini. TestFactoryGeminiStreamsToChat
reads a Gemini SSE chunk back as chat completions. Not tried against
a real Factory account.

* fix(factory): open other agents with droid2api's system prompt

droid2api's config.json system_prompt is Droid's line and a blank line,
written in front of the agent's own prompt on Responses, chat, Messages,
and Gemini generate. A body that already opens with the line is unchanged.

* fix(factory): answer non-streaming Gemini clients with JSON

Factory's generate route always returns SSE and droid sends no stream
field. A generateContent call is translated into JSON; a relayed
streamGenerateContent drops stream before it goes upstream. The provider
Test probes generate instead of failing the protocol, and a Gemini model
is tested on that route. The system prompt is joined into the one
systemInstruction part droid sends.

* fix(factory): join Droid's opening with one newline

droid writes the line and one newline in front of the agent's prompt.
The extra blank line from droid2api's system_prompt is dropped.
Anthropic still keeps the line as its own first block.

* fix(factory): send Droid's line alone when there is no prompt

droid joins blocks with "\n", so a request with no system prompt is
the line and nothing after it. Responses, chat and Gemini were
sending the line plus a trailing newline. Anthropic already sent
the line alone.
2026-10-03 03:39:54 +08:00
yetone a97643bcc8 gateway: a translated or relayed stream keeps its client alive while its provider is (#436, congee949: Chat → Responses dropped the upstream's ": keepalive" and Codex hit "idle timeout waiting for SSE" on a live connection) — a reply magpie translates was read event by event and written only when an event had something for the client, so a provider's SSE keepalives, and events with nothing to translate, reached no one, and a reply that thought quietly for five minutes ended in Codex's idle timeout and a retry. Now, whenever the provider is heard from and the client has heard nothing for a second, magpie sends the client a keepalive in its own protocol: response.in_progress again on Responses (Codex's timeout counts events, never a comment — a sandboxed codex 0.159.2 on a fake provider sending only comments timed out, one sending response.in_progress didn't), ping on Anthropic (as Anthropic does; Claude Code's watchdog counts it), an SSE comment on Chat Completions, nothing on Gemini (Google's SDK can't read past one). A provider that sends nothing at all is not covered for, so a dead connection still ends at the client's timeout. A reply relayed from the Claude subscription's bridge, Kiro, Cursor, Devin, search, Qoder, Zed or Command Code is kept alive every 15s while it goes quiet, for up to 5 minutes since its last event. Native passthrough is unchanged, and prompts and headers are unchanged. The routing trace no longer drops a request still going for the 60 finished after it: the oldest finished ones go first, unless more than 120 are going at once. TestTranslatedStreamKeepsClientAlive (the issue's repro: 20ms keepalives, 150ms idle timeout; Chat → Responses, Chat → Anthropic, Responses → Chat), TestRelayKeepsClientAlive and TestTraceKeepsInflight fail without the change; TestTranslatedSilenceStillTimesOut keeps a silent provider uncovered. In a sandbox CODEX_HOME, codex exec through the gateway on a provider sending 6s of keepalives with stream_idle_timeout_ms 2500 answers, and without the change fails with idle timeout waiting for SSE. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass. 2026-10-01 22:36:36 +08:00
Charan Rathore 0b31315a47 gateway: 400 when a required tool choice leaves nothing callable (#169)
* gateway: 400 when a required choice has no callable tools

Added validation to ensure required tool choice is callable.

* gateway: force a single Gemini name only when it survives

Added conditions to ensure tool choice is set correctly based on allowed function names and tool availability.

* gateway: test required-choice allowlist rejection

* gateway: reject an allowlist that filters out every tool in shared parse

Refactor request parsing to handle required tool choices and improve error handling.

* gemini: narrow the required-tools guard to Responses allowed_tools and ANY allowedFunctionNames

Updated the logic for function calling modes to include 'VALIDATED' alongside 'ANY'. Adjusted comments for clarity regarding allowed function declarations.

* gateway: cover required-tool and filtered-empty allowlist rejections
2026-09-29 04:39:49 +08:00
Charan Rathore 42a39fdedf gateway: filter Gemini VALIDATED allowedFunctionNames on translated routes (#170)
* gateway: filter Gemini VALIDATED allowedFunctionNames

Updated function calling logic to accommodate both ANY and VALIDATED modes, allowing for named function declarations.

* gateway: test VALIDATED allowed-name filtering
2026-09-29 04:14:46 +08:00
Charan Rathore 995edc135d gateway: honor allowed-tool subsets from Gemini ANY and Responses allowed_tools (#164)
* gateway: honor Gemini ANY allowedFunctionNames subsets

Add support for allowed function names in ANY requests.

* gateway: honor Responses allowed_tools subsets

* gateway: test Gemini allowedFunctionNames filtering

* gateway: test Responses allowed_tools filtering
2026-09-29 03:38:21 +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 68408d2d00 gateway: a web search a client offers — Claude Code's WebSearch, Codex's web_search, a Chat client's web_search_options, Gemini's googleSearch — is done for every provider, not only the Claude subscription. A provider that searches by itself is asked to (a Codex account and OpenAI/xAI with Responses' web_search, Anthropic's API with web_search_20250305, OpenRouter with its web plugin); any other model — DeepSeek, Kiro, Grok, Cursor, Devin, a relay — is given a web_search tool of magpie's, which the first provider set up that can search answers with a small model of its (the Claude subscription's Haiku, then Codex, Anthropic, OpenAI, OpenRouter), and the model is asked again with what was found: the client sees one reply and no tool call. A request offering search is no longer relayed as is to a provider that would ignore the tool. Tested live: Claude Code → DeepSeek with WebSearch (2 turns), Responses and Chat clients → DeepSeek, Kiro and Grok, with the Claude subscription, Codex and OpenRouter each doing the search 2026-09-27 02:21:49 +08:00
yetone 95c572e91e gateway: a Claude subscription conversation's next turn goes to the Claude Code that had its last, told only what the user said since, so the conversation Claude Code keeps goes on as it began and its cached prompt is read again — each turn started a new run from the whole history in one message, which shared nothing with the cache but Claude Code's own prompt, so every turn wrote some 5.7K tokens to the cache again where it now writes about 100 (a three-turn conversation went from 37% of its input cached to 79%, one with tool calls from 63% to 87%, about 99% past the first call); a run waits for its conversation up to 20 minutes, six at most, and is found again by what the conversation has been so far, else a new one starts as before; and it is set waiting before the reply's last event, which a quick agent answers at once. Anthropic's usage leaves out what the prompt wrote to the cache, and the OpenAI and Gemini counts magpie gave from it did too, so Codex was told a Claude turn of 26K tokens took 2; and an agent that hangs up once the last event is in (Codex does, before the ChatGPT backend closes its end) had its call logged as canceled, 499, though it was answered in full 2026-09-25 11:44:17 +08:00
yetone 402a96c39d Rename dial to magpie, with a magpie for a logo
The product, module path (github.com/yetone/magpie), binaries, env vars
(MAGPIE_ADDR, MAGPIE_DEV_UI, MAGPIE_THEME, MAGPIE_DEBUG), config and cache
folders (~/.config/magpie, ~/.cache/magpie), bundle id (com.yetone.magpie),
gateway provider id and token, and every UI string now say magpie.

On first run magpie copies ~/.config/dial and ~/.cache/dial to the new
folders when they don't exist yet (copy, not move, so a still-running dial
keeps working; the old folders can be deleted by hand later).

The logo is a small round magpie in profile: one path for the header and
the tray, and the app tile adds the white belly and the blue-green tail.
The header mark is drawn in ink rather than the accent colour, which
fought the text in light mode.
2026-09-23 23:55:11 +08:00
yetone 0f96a5fb74 gateway: serve the Gemini API; Gemini CLI can use every catalog model
Gemini CLI only speaks Google's API, so its picker stopped at Google's
models. The gateway now serves /v1beta/models/{model}:generateContent,
:streamGenerateContent (alt=sse), :countTokens and GET /v1beta/models,
translating to whatever the provider speaks: contents/parts, function
calls and responses (ids kept, names matched otherwise), inline images,
thinking config, tool config, structured-output asks, Gemini's uppercase
schema types, and usageMetadata on the way back.

Picking a catalog model for Gemini CLI points GOOGLE_GEMINI_BASE_URL at
the gateway with the gateway token as GEMINI_API_KEY, switches auth to
API key and names the model; a native model or Default puts the earlier
auth, key and model back. The auth pill reads "dial" while routed.

`dial gemini auth …` now resolves a field by its label too.
2026-09-23 14:51:43 +08:00