Commit Graph
11 Commits
Author SHA1 Message Date
congee949 2d3b33bb78 usage: time tool-only replies only with visible reasoning evidence
Revises #1463 after the hidden-reasoning inflation review. Keep answers separate, retain evidence in routes and cached ledger rows, and exclude sealed or summary-only reasoning even without a token breakdown. Sync the backend and both GUI formulas.

Checked real WorkBuddy DeepSeek, Codex and Claude bridge responses in an isolated HOME; sanitized timings and failures are in docs/verification. Chromium/WebKit speed regressions pass (20 tests, five languages). New edge regressions and loop-order check pass under race repetition. Restoring the old formula or removing the hidden guard fails TestVisibleReasoningSpeed. macOS/Linux/Windows vet/build pass. Full-suite verification is recorded in the issue at this head; inherited proxy/Bun 1.3.14 failures are retained, with clean Bun 1.4.2 rerun in progress. No installed app replacement.

Rebased onto main by yetone (#1463). Conflicts with main's Own/Retried/
Queued/Tries row fields, HandedOn and the Codex speed floors were resolved
by keeping both. The packed row's ReasoningHidden bit was 64, which main
has since given to block_price.go's swapKnown, and main's rowHandedOn took
128, filling the uint8: Flags is now uint16 and ReasoningHidden is bit 512
(rowReasoningHidden; #1874's rowOwnCost took 256), read back in row(). The docs/verification notes and
their sample JSON are left out of the tree; they stay on the contributor's
branch and the issue. Run after the rebase: go test -tags nogui ./internal/usage/
and the gateway's reasoning/speed/TTFT tests, ok.
2026-10-13 06:43:50 +08:00
yetoneandump45nose 1e080cc7e7 gateway: the saved Anthropic-to-Responses body carries the image's detail auto that the commit before it sends (#1474)
TestUpstreamBodiesUnchanged (5feadabe, added after ump45nose's branch)
saved the bytes a vendor gets before input_image carried detail, so it
went red with the fix. Re-saved with UPDATE_UPSTREAM_BODIES=1; the only
byte change is "detail":"auto" on the one input_image.

Run: the two new tests fail on the old responses.go and pass on the new;
openai-python's ResponseInputImageParam (pydantic TypeAdapter) refuses
the old shape with "detail Field required" and takes the new one.

Co-authored-by: ump45nose <52391318+ump45nose@users.noreply.github.com>
2026-10-13 05:09:18 +08:00
yetone 403f3845e2 gateway: Codex's spawn_agent names every model also when Codex hands it to the lead through a tool search, as it does on 0.162 (Gearclickist on Discord)
Gearclickist, after v0.1.1214: the lead still saw only five models for
its subagents. v0.1.1214 (5d33f060b) widened spawn_agent in the request's
tools only. Codex 0.162 doesn't put it there for a model that can search
tools: with supports_search_tool the multi-agent V1 tools are Deferred
(codex-rs rust-v0.162.1 core/src/tools/spec_plan.rs:1475-1479), the lead
calls tool_search, and spawn_agent, with Codex's five
(core/src/agent/child_config.rs:20 MAX_SPAWN_AGENT_MODEL_OVERRIDES = 5,
used in core/src/tools/handlers/multi_agents_spec.rs:830), arrives in a
tool_search_output item in the conversation. Codex resends that item on
every later turn. magpie's /models entries and Codex's own say
supports_search_tool, so this is the usual case, and the fix never fired.

The limit is only in what Codex writes. find_spawn_agent_model_name
(child_config.rs:318) takes any model of the catalog Codex loaded; the
five also appear in its error text (child_config.rs:335).

spawnAgentModels now widens the spawn_agent in each tool_search_output
in input as well as in tools (moreSpawnTools, shared by both). The added
text is unchanged and stays neutral; base_instructions are untouched.
The same output is widened the same way on each turn, so the history
Codex resends stays byte-stable.

Run:
- Real Codex 0.162.1 in a sandbox HOME/CODEX_HOME, wired by a sandbox
  magpie (`magpie codex fake/m1`, gateway on 127.0.0.1:3593) to a fake
  Responses upstream with 40 models that calls tool_search, then
  spawn_agent with model fake/m12.
  - Before: the lead's searched spawn_agent named fake/m1..m5 only.
  - After: it names all 40, Codex's five then the other 35 under the
    added header.
  - Both times Codex accepted fake/m12 and the child's request reached
    the upstream on m12.
  - The same Codex pointed straight at the fake (no magpie) gave the raw
    request saved as testdata/workdir/codex-0.162.1-tool-search.json
    (sandbox paths replaced).
- TestSpawnAgentNamesEveryModelAfterToolSearch (/v1, CodexPath with a
  magpie lead, CodexPath with a ChatGPT lead and V1) fails on the old
  codex_spawn_models.go in all 3 subtests ("doesn't name fake/m6") and
  passes now.
- go test ./internal/gateway -count=1 under a sandbox HOME: ok.
- gofmt -l clean; go vet ./internal/gateway on darwin, GOOS=linux -tags
  nogui, GOOS=windows.

Not run: a real ChatGPT-account lead at CodexPath (covered by the stub
backend test only), the Codex App, and a V2 lead (V2 keeps spawn_agent in
tools, which v0.1.1214 already covers).
2026-10-13 02:32:23 +08:00
yetone 5b87087423 gateway: Qoder's queue (code 10605) is a 503 with Retry-After for users still on the built-in, not "sign in again" (plugins #98)
What changed: qoderFailure (internal/gateway/qoder.go) read every 401/403
as "Qoder: the sign-in lapsed — sign in again". It now reads Qoder's own
code first, whatever the HTTP status, the way Qoder.app's client does
(the QoderErrorCode table in its qoder-agent-sdk worker,
qoder-worker-runtime.obf.mjs) and as @magpie-community/opencode-qoder-auth
0.2.14 does (plugins f573cfd):
- 10605, or a queue state (in "queue" or in the message as JSON) with
  isQueued true or serviceAvailable false: 503 "Qoder is busy for
  <model> (this plan's queue: <tier>); try again in <n>s", with
  Retry-After from retryAfterSeconds rounded up (30s when absent).
- 110, 112-119, 122 (usage or credits used up): 429.
- 406, 416, 430, 80411, 80412, 100400, 100401, 100403 (refusals of the
  request; Qoder's table has no 100402): 400 with Qoder's words.
- 105 or no code on a 401/403: the 401 "sign in again" as before.
Both the HTTP status path (askQoder) and the in-stream statusCodeValue
path (decodeQoder) go through it. Event gets a Wait field for a KError,
and relayStatus's fail and serveQoder's first-round failure send it as
Retry-After (retryAfterOn); askQoderWait is askQoder that also returns
the wait, and askQoder (the round searchRounds uses) wraps it. Zed and
Command Code share relayStatus and never set Wait, so they are
unchanged.

Why: a real Qoder trial account had every chat answered
403 {"code":"10605",...} (Qoder's model queue) and was told to sign in
again, which can't help. The plugin was fixed in 0.2.14 for moved users;
this is the same fix for users still signed in through the built-in. The
built-in never marked an account lapsed from a refused chat (only from a
refused refresh, provider/qoder.go), and now a 10605 doesn't even return
the 401: the gateway's busy() reads the 503 as busy (failOther), so a
group asks it again after the pause, no shorter than its Retry-After
(noteBusy/retryAfter), and the agent gets the Retry-After too.

Run:
- New tests in internal/gateway/qoder_busy_test.go, the fixture
  testdata/qoder_queued_10605.json taken byte for byte from plugins #98:
  TestQoderQueuedIsBusy (serveQoder, HTTP 403 and in-stream 403, stream
  and not: 503, Retry-After 30, the busy words, no "sign in", busy() true,
  retryAfter 30s), TestQoderQueueWait, TestQoderErrorCodes. With the old
  401/403 rule put back at the top of qoderFailure all three FAIL
  ("got 401 ... want 503"); with retryAfterOn made a no-op
  TestQoderQueuedIsBusy FAILs on Retry-After "" in both subtests. Restored,
  they pass.
- go test -tags nogui ./internal/provider ok (458s). go test -tags nogui
  -timeout 40m ./internal/gateway (the default 10m ran out under the
  machine's load): every test passed except TestCodexHeardWithinItsIdleTimeout,
  which failed with the body #1800 already describes (Codex got member
  a's server_is_overloaded under load); it passes 10 of 10 alone
  (-count=10) and is on the Codex passthrough path, which this doesn't
  touch. Noted on #1800.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... ok; go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build ok.
- Not run: the rest of go test ./... (only the two packages touched);
  a real 10605 through the built-in (the queue had reopened when the
  plugin shipped); no Qoder parity test exists in
  internal/gateway/plugin_*_test.go to extend.
2026-10-12 23:06:24 +08:00
yetone 5feadabef6 gateway: a long conversation's request costs about a third of the CPU it did, with the same bytes sent on (#1532, #1654)
The gateway reads one request's body a dozen times or more on its way:
modelOf, streamOf, conversationID, requestEffort, bodyEffort,
walkImages and swapImageBlocks (more than once through a group), turnOf's
parse, promptOf, chatToolNames, thinkingOffUnlessAsked, decodeRequest,
and for Responses pairToolItems, orphanedToolOutputs,
hasSealedAgentMessage and askedTier. Each read took a field or two with
json.Unmarshal, which checks the whole input and then steps through every
byte of every string one call at a time, so each read cost as much as
decoding the whole conversation: 74-77% of a request's CPU in pprof, most
of it checkValid and stateInString.

decodeJSON (fastjson.go) is json.Unmarshal for these reads. It checks the
body once with its own validator (json.Valid's grammar and 10000 depth,
8 string bytes at a time), splits objects and arrays at their members
without decoding them, and decodes only what dst has a place for:
strings, booleans, json.RawMessage (copied, as encoding/json does),
structs, pointers, slices and string-keyed maps by their parts, and
everything else (numbers, interfaces, types that decode themselves) by
encoding/json itself. Whatever it doesn't take on exactly as
json.Unmarshal would goes to json.Unmarshal with dst zeroed: invalid
input, a dst already holding something, an embedded field, a ",string"
option, two fields of one name, a key given twice, a value of the wrong
type. A list or object where dst takes a string (a "string or parts"
read) is answered by json.Unmarshal of its opening and close, which gives
the same error at the same offset without reading the rest. The request
paths' json.Unmarshal calls in gateway.go, decide.go, affinity.go,
image_input.go, textcalls.go, anthropic.go, ir.go, prompt.go, chat.go,
chattidy.go and responses.go, and hasSealedAgentMessage and askedTier,
now call it. Nothing that writes a body changed.

Numbers, M4 Pro under load 10-20 from other sessions, BenchmarkLargeRequest
(new: a 2 MB agent conversation with 30 tools, tool calls and results,
through a fake vendor), 20 requests each:

                    CPU in the request's handler    time per request
                    (pprof, per request)            (ns/op)
  anthropic         154ms -> 45ms                   208-212ms -> 52ms
  anthropic, group  178ms -> 51ms                   249-262ms -> 65-67ms
  chat              122ms -> 35ms                   167-254ms -> 50-54ms
  responses         215ms -> 56ms                   294-452ms -> 70ms

TestLargeRequestEndpoints (64 MB padded bodies): 16.8-17.6s -> 2.9-4.8s
(skipping runs of spaces 8 bytes at a time took its last ~5s).

Tests:
- TestUpstreamBodiesUnchanged sends 18 requests (Anthropic, Chat and
  Responses; direct, through a group, translated to each other protocol,
  with images, thinking, escapes, odd spacing, a repeated key, and four
  2 MB conversations) and compares what the vendor gets with
  testdata/upstream_bodies, recorded on the code before this change
  (all 18 identical; three runs agreed). Breaking decodeJSON's \n
  unescape by hand turns the three translated cases holding one red.
- TestDecodeJSONIsUnmarshal / FuzzDecodeJSON compare decodeJSON with
  json.Unmarshal (dst DeepEqual, error nil-ness) for 19 types shaped like
  the gateway's, and jsonValid with json.Valid, over seeds, every cut
  and a changed byte at every place of each seed, and 2.5 minutes of
  fuzzing (~1.75M inputs). Breaking the validator's control-byte check
  by hand turns it red.
- go test -tags nogui -timeout 40m ./... on this commit rebased onto
  origin/main 498b77fbc, with #1667's fix below it: all 48 packages ok
  (gateway 394s).
gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
./internal/gateway clean.

Not tried: real vendor traffic; Windows and Linux runs (vet only).
2026-10-12 03:28:16 +08:00
yetone cfa280a6c2 provider, gateway, gui: You.com can be added as a search API, with no key for its free search or with a key (#1626, brainsparker)
A model's web search, when no provider can search, goes to the search
APIs the user added; each of them needed a key except a SearXNG of the
user's own. You.com answers with no key too, so it is one a user can
add in one step.

- provider: SearchVendor has KeyOptional (You.com, SearXNG); Ready and
  check let a vendor that has it go with no key. You.com is listed
  between Firecrawl and SearXNG, its keys at you.com/platform.
- gateway: with no key, GET https://api.you.com/v1/agents/search?query=
  &count=6 (YouFreeSearch); with a key, POST https://ydc-index.io/v1/search
  {"query","count"} with X-API-Key, as its API reference says; with a
  base URL of the user's own and no key, GET <url>/v1/agents/search.
  Both replies are read from results.web then results.news: the
  snippets, else the description, and page_age. You.com's errors are a
  code beside a message, so the message is what the user is told (a
  402 "prepaid credit balance has been depleted" is a refused key, the
  next key or API is asked). Its requests carry the User-Agent tag You.com
  asked for, "youdotcom-integration/yetone-magpie", after magpie's own.
- gui: Settings › Web search lets You.com be added with the key empty,
  its placeholder saying so (zh, zh-TW, ja, de).
- cli: magpie search add you [<key>]; the help lists it.

New network addresses: api.you.com (keyless) and ydc-index.io (keyed),
asked only when the user adds You.com, with the search query only.

Checked against the real service on 10-11: a keyless GET to
api.you.com/v1/agents/search answered 200 (testdata/you/free_search.json
is that reply, cut to 3 hits), and a real run through askSearchAPIKeys
returned 6 pages. ydc-index.io/v1/search answered 402 with no key
(testdata/you/keyed_402.json, real bytes) and 403 to a made-up key. The
keyless endpoint isn't in the API reference; You.com's own docs pages for
third-party tools describe it (free, 100 a day per address, no account),
as LiteLLM, ragflow and AnythingLLM use it. you.com/terms bars automated
use of its website and apps, not the API. The keyed request shape is
from its API reference only: no key with credit was tried.

Run: go test -tags nogui . ./internal/gui/ ./internal/provider/
./internal/backup/ green; ./internal/gateway/ green but
TestTurnDoneSaidAtTheTurnsEnd (#1629, fixed in its own commit);
search-api.test.cjs in Chromium and WebKit, en/zh, 980/420px green;
gui-ja, gui-de and i18n-keys green; gofmt -l; go vet -tags nogui for
linux, windows and darwin. The tests make no network request (a stub
RoundTripper). Without the change, TestYouSearch, TestYouKeyOutOfCredit,
TestYouNeedsNoKey and TestSearchCLIYouWithoutKey fail, and with the GUI's
keyOptional check taken out search-api.test.cjs fails in all four
Chromium runs (Add sends nothing).
2026-10-11 22:45:11 +08:00
yetone ae70d8eac8 routing: a group's rule can hold by the folder the agent works in (Cario0x on X)
Cario0x on X asked to route by the project being worked on. A group's rule now has a
"folders" condition: it matches when the request's working folder is one of the listed
folders or inside one. It combines (AND) with the existing conditions: tokens, images,
intent, time, agents and quota.

- gateway/workdir.go reads the folder each agent states in its own request:
  - Claude Code: "Primary working directory", including "(was …)" after a move.
  - Codex: <environment_context><cwd>.
  - Pi: <cwd>.
  - OpenCode: <env> "Working directory".
  The last one stated wins. Assistant text and tool results are ignored. A request
  that states no folder matches no folder rule: unknown, never empty.
- provider/rulefolder.go matches a folder only at a path boundary.
  - ~ is the home folder.
  - C:\x is the same folder as /mnt/c/x, and \\wsl$\Distro\x as /x.
  - Case is ignored on macOS and Windows, and always for a drive.
  - A rule's folder must be a whole path. Pause rules can't have folders.
- The trace's RuleHit.Folder makes the Routing page say "The agent works in …".
- GUI: an "in folder" condition in the group editor, hidden on pause rules. Strings in
  zh, zh-TW, ja and de.
- CLI: `magpie group rule add … folders=~/oss,"~/My Project"`. The TUI shows the
  condition.
- Docs: docs/subsystems/gateway-routing.md and site start.html (en, zh, ja).

Fixtures are real requests from Claude Code 2.1.296, Codex 0.162.0 and Pi 1.1.0, run in
a sandbox from a folder named "a&b <c> 中文" or "My Proj", with the sandbox path
replaced.

Run at this head:
- go test ./... green.
- gofmt -l clean.
- go vet green for darwin, GOOS=linux -tags nogui and GOOS=windows.
- GUI routing-folder.test.cjs: chromium and webkit, en, zh, zh-TW, ja and de, 1100px
  and 390px (no horizontal scroll). It fails on the old routing.js.
- Related routing, group and i18n GUI tests: 85/85.
- Full GUI suite: 5611/5631 under --test-concurrency=6. Rerun alone, every failure
  passes except:
  - skill-install-agents-all (chromium, 420px), which is red on origin/main too: #1554.
  - The menu-scroll track flake, which flakes on main as well: #1550.
- e2e: a sandbox HOME, a dev build and fake upstreams, with real Claude Code 2.1.296
  (`claude -p --model group/fd`).
  - From proj/acme/web, rule 1 matched and the request went to kb.
  - From proj/acme-old, no rule matched and the request went to ka. The trace and UI
    showed the folder.
2026-10-11 10:17:16 +08:00
yetoneandtimonwong ca0867e412 gateway: a Grok model's 2500.0 in a call's arguments reaches the agent as 2500, on every route and protocol, deltas and done alike (#1431, timonwong)
Grok's models (grok-4.6, grok-4.7) write a whole number in a tool call's
arguments with a fraction of zeros. Codex reads exec_command's
yield_time_ms and max_output_tokens as u64/usize and write_stdin's
session_id as i32, though their schemas say "number", and serde turned the
whole call away ("failed to parse function arguments: invalid type:
floating point `2500.0`, expected u64 at line 1 column 77"; `17277.0`,
expected i32), so the turn stopped at its first command. Reported 11 of 11
turns through a sub2api relay in front of grok-4.6 and grok-4.7.

What changed (grok_integral.go):
- grokModel/grokServed: a Grok model is one whose id, as magpie names it
  or as it is sent upstream, has a last `/` segment beginning "grok"
  (relay/grok-4.6, x-ai/grok-4, the plugin's grok-4.7).
- wholeNums: a streaming scanner over the arguments' JSON text. A number
  written with a fraction of zeros and no exponent loses the fraction
  (2500.0 -> 2500, -3.00 -> -3, [1.0,2.0] -> [1,2]). Strings, keys, other
  fractions (2.5, 2.50) and exponents (1.0e3) stay as written. It holds
  only a run of ".0…" until the next byte, so arguments cut into deltas
  anywhere come out the same as whole, and the deltas add up to what the
  done events say.
- Relayed (passthrough): intTidy, beside nsTidy and built like it, on
  Responses (function_call items, argument deltas and done, the completed
  response, a whole reply), Chat (tool_calls deltas and messages) and
  Messages (tool_use input and input_json_delta), streamed or whole. A
  line that carries no call passes as it came. Plugin-served Grok and the
  built-in subscription go through the same passthrough.
- Translated: translate sets Request.Grok; encoder() wraps the client's
  encoder in wholeEncoder (outside usageEncoder) and render() rewrites the
  Result's calls (wholeResult), so every client protocol is covered at
  those two choke points.
- Any other model's reply is relayed byte for byte, as before.
- gateway-routing.md says so, and lists the tests.

Scope, against the reporter's 9fd6855b: that commit rewrote only fields a
tool schema typed "integer" or a fixed list of Codex's (codexInts), only
on Responses, and left deltas as they came, so the deltas disagreed with
the done events, and the list missed Codex's other integers (shell's
timeout_ms, sleep's duration_ms, tool_search's limit, the multi-agent
tools' timeout_ms). Codex's own schemas say "number", and JSON has one number type, so 2500 is the same value as
2500.0 for every client; this drops the zero fraction everywhere in a
Grok model's call arguments instead. Its rollout fixtures are kept
verbatim (testdata/grok_integral_args) and its test helpers adapted.

Tests: TestWholeNumsAnyCut (every split point and byte by byte),
TestGrokCallsGiveCodexIntegers (relayed Responses, streamed with deltas
cut whole, byte by byte and at every '.'/zero, and whole),
TestGrokCallsGiveCodexIntegersTranslated (Chat upstream -> Codex),
TestGrokCallsGiveIntegersOnEveryProtocol (Chat relayed, Messages relayed,
Messages translated from Chat), TestGrokCallsByUpstreamName,
TestGrokPluginCallsGiveCodexIntegers (fake plugin, $FAKE_GROK),
TestOnlyGrokCallsGetIntegers (gpt-5.5 byte for byte on Responses, Chat
and Messages relayed; translated keeps 2500.0), TestGrokModel. Each
recorded case checks that the field Codex's own error names is now an
integer of the Rust type it named, wherever Codex reads the call.
With grokModel forced false, every Grok test fails; with the delta
rewriting turned off (intTidy and wholeEncoder), every streamed case
fails on deltas != done.

Run: gofmt -l (clean); go vet -tags nogui ./... on darwin, GOOS=linux
and GOOS=windows; go build ./... and GOOS=linux/windows -tags nogui
builds; go test -tags nogui ./... under a temp HOME; -race -count=3 on
the new tests. End to end: the built binary (`serve`, sandbox HOME, port
47812) in front of a fake upstream streaming 2500.0 a byte per delta on
Responses and Chat; a client reading /v1/responses and
/v1/chat/completions, streamed and whole, got integers in deltas,
arguments.done, output_item.done, completed and output for grok-4.6
(relayed) and grok-4.7 (translated from Chat), and 2500.0 unchanged for
gpt-5.5. The same client against a binary of the parent commit failed
all 12 Grok checks.

Not verified: a real Grok model or a real Codex turn; Messages and Chat
Grok replies have not been seen in the field; a relayed Messages
tool_use input that is rewritten has its keys re-marshalled in sorted
order; exponent forms (2.5e3) are left as written.

Co-authored-by: timonwong <timon86.wang@gmail.com>
2026-10-10 01:09:31 +08:00
yetone 586f2bce8f context: magpie inspects the context window of every request, session and agent
The gateway reads each request's prompt into its parts (system prompt,
tools and MCP servers, memory, files, tool results, chat), measured
against the model's window and calibrated to the tokens the vendor
counted. Routing shows a request's window as a card: a 400-cell grid by
part, a hover naming what is largest in a cell, and the contents by part.
The Usage page's Context tab scores each agent out of 100 (cache reuse,
how lean it starts, how fast it grows, how reliably it answers), tags it
(lean, cache-friendly, mcp-heavy, compacts, near-full…), and draws each
session's growth with its latest request's card.

Older Safari (15) gets media-query and solid-colour fallbacks for the
card's container queries and color-mix.
2026-10-08 05:36:17 +08:00
forever bed306ae60 gateway: reasoning off reaches Gemini 3 at its lowest level, and Google refusing minimal no longer stops a provider's thoughts (#1062)
* gateway: reasoning off goes to Gemini 3 at its lowest level where it has no minimal, and Google refusing minimal no longer stops the provider's thoughts until restart

With reasoning off, a request to Gemini's OpenAI-compatible API (AI
Studio's, or a proxy in front of it on this machine or the LAN) went with
reasoning_effort minimal, since Gemini 3 can't stop thinking.
gemini-3.8-flash has no minimal: models.dev gives its levels as low,
medium and high, and Google answers minimal with 400 "Thinking level is
unsupported: THINKING_LEVEL_MINIMAL". The message names thinking, so
refusesThinkingConfig took it for thinking_config turned away and marked
that field unfit for the provider. Until magpie restarted, nothing sent to
the provider asked for Gemini's thoughts again, on any model, and a client
that asked to see them got none. The turn itself was asked again with no
reasoning_effort, at the model's default level.

  * Reasoning off goes at the model's lowest level where its levels are
    known and have no minimal, and at minimal where they have it or aren't
    known (Request.OffLevel, geminiOffLevel). gemini-3.8-flash on AI
    Studio goes at low, in one request.
  * Where the levels aren't known (a proxy's own name for the model),
    Google's 400 for minimal is told apart from thinking_config turned
    away (geminiMinimalRefused, which also matches gemini-3.1-pro-preview's
    "thinking_level MINIMAL is not supported by this model" at
    generateContent). It is remembered as the model refusing reasoning off
    (offRefused, as for other vendors), and the model is asked again at its
    lowest level, low when none are known, and so from then on.
    thinking_config is kept, and the next turn that thinks gets the
    model's thoughts.
  * An effort of minimal set on the request, which fitFor keeps where the
    levels aren't known, is turned away the same way and asked again at
    low by the existing offEffort step, with its thinking_config.

Passthrough (a Chat client calling AI Studio itself) is unchanged: it fits
the effort to the model's levels where they're known, and has no retry for
a proxy whose levels aren't.

Tests, with what upstream's gateway gives:
  * TestGeminiThinkingOffAtItsLowest: an Anthropic client's turn with
    thinking disabled, then one thinking at high, then disabled again, to
    a fake Gemini that answers minimal with the 400 above, in its literal
    bytes. With the levels known, the first turn goes at [low]; not known,
    at [minimal low]. Either way the thinking turn then sends
    thinking_config {include_thoughts: true, thinking_level: high} and
    gets a thinking block, and the last turn goes at low in one request.
    Upstream sends [minimal <nil>] both ways.
  * TestAIStudioThinking: "off at its lowest" sends reasoning_effort low.
    Upstream sends minimal.
Each part was also broken on its own, and each break fails a test:
buildChat ignoring OffLevel ("reasoning_effort = "minimal", want "low"",
and [minimal minimal <nil>]), the loop never setting it ([minimal minimal
<nil>] both ways), no check for the refusal of minimal ([minimal <nil>]
with the levels not known), and geminiOffLevel ignoring the refusal
([minimal minimal <nil>]) or the known levels ([minimal low]).

Verified on 443f1cbc: gofmt -l, go vet ./..., go build, GOOS=linux go
build -tags nogui and GOOS=windows go build pass; go test -tags nogui
./... passes, and -race -count=20 on the tests above.

Live, with gemini-3.8-flash through a proxy on this machine in front of
Vertex AI's OpenAI-compatible API, the gateway in a temporary HOME (AI
Studio itself wasn't tried: there was no key for it). Upstream sent the
off turn at minimal, got the 400 and asked again with no
reasoning_effort; the thinking turn after it went as reasoning_effort high
with no thinking_config, and no thoughts came back. With this change the
off turn went at low in one request, the thinking turn with thinking_config
at high, and the last off turn at low. Under a name whose levels aren't
known, the first off turn went minimal, then low, and the next at low at
once. The thoughts reached the client as thinking with the next commit,
which reads how that endpoint marks them.

* gateway: Gemini's thoughts streamed from Vertex AI's OpenAI-compatible API reach the client as thinking, not as the start of the answer

A proxy on this machine or the LAN in front of Gemini is asked for the
model's thoughts as AI Studio is, in thinking_config. In front of Vertex
AI's OpenAI-compatible API, the thoughts don't come in AI Studio's
<thought> tags: each comes in a chunk of its own, the thought as the
delta's content, and the chunk is marked
"extra_content": {"google": {"thought": true}}. chatDecoder read only the
content, so the thoughts were streamed to the client as the first part of
the answer.

  * A chunk marked as a thought is thinking (KThink).

A whole reply from that API carries its thoughts in <think> tags instead.
That isn't changed: the gateway streams from the upstream when it
translates, and a Chat client's own request is passed through as it is.

Tests, with what upstream's gateway gives:
  * TestGeminiThoughtsMarkedInExtraContent: that API's stream for "你好"
    at high with the thoughts asked for, in its literal bytes
    (testdata/vertex_openai_thoughts.sse), to an Anthropic client: a
    thinking block that starts "**Acknowledging Greeting**", then the
    text "你好!很高兴与你交流。请问有什么我可以帮你的吗?". Upstream gives
    thinking "" and the thought at the head of the text.

Verified on 443f1cbc: gofmt -l, go vet ./..., go build, GOOS=linux go
build -tags nogui and GOOS=windows go build pass; go test -tags nogui
./... passes, and -race -count=20 on the tests of this and the previous
commit.

Live, through the proxy and temporary HOME of the previous commit, a turn
thinking at high gave a thinking block of 238 characters, and the answer
apart from it.
2026-10-07 18:51:01 +08:00
yetone 963d8d9d88 gateway: a provider that turns Codex's image tool away with a bare 400 is asked again without it, and isn't offered it again once that works, so a plain chat no longer breaks on it; a ChatGPT sign-in, openai.com and a Codex backend that takes it still get it (#949, cjyrainbow)
Since #870, magpie's provider in Codex's config carries x-openai-actor-authorization, so Codex offers its image_gen namespace tool on every request. A vendor's Responses API that can't take it, a relay's included, answered "bad response status code 400" to "只回复 OK". After a bare 400 (one that names no field or message magpie already knows to drop), a provider other than a ChatGPT sign-in or openai.com is asked once more without the tool. This works both passed through (the namespace) and translated (image_gen__imagegen flat). If the retry answers, the provider is marked unfit for tool:image_gen. If it doesn't, the tool goes back and the vendor's 400 stands, and the cache-key guess runs on the request as it was. The header stays as #870 wrote it.

image_tool_test.go is new. Its fixture is the image_gen tool Codex 0.160.0 sent to a capture server with magpie's provider table and catalog. TestImageToolLeftOutWhereRefused (translated, passed through) fails with the reporter's 400 when gateway.go is reverted, and so does TestImageToolKeptOverAnotherRefusal. TestImageToolKeptForChatGPT fails when the ChatGPT exemption is dropped. docs/subsystems/gateway-routing.md has the rule. go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass.
2026-10-06 03:39:04 +08:00