Commit Graph
169 Commits
Author SHA1 Message Date
yetone 30869e35a7 usage, gateway: each request's log row says the service tier asked, the one each try was sent at, and the one the vendor said it ran at (#1784, zhenghaowen0967)
What changed
- usage.Record has tier_asked, tier_sent and tier_served, and the CSV gets
  them as its last three columns.
  - tier_asked is the client body's service_tier (Claude's speed fast reads
    "fast").
  - tier_sent is the tier the try's last request actually went out at. It
    is noted in forwardOnce after every rewrite (a fast pick's priority,
    Ultrafast turned to priority on a plan without it, buildResponses
    dropping a tier the host can't take) onto the per-attempt wireAt. So a
    handed-on try's own row has its own tier.
  - tier_served is only what the reply said: service_tier at the top level,
    in response.service_tier, or in an Anthropic usage. It is read by the
    relay sniffer and by both translated readers, and is empty when the
    reply says nothing. It is never filled in from the ask.
- Codex's own relayed sign-in (codex_backend) records the same three.
- /v1/magpie/route: Route.tier (asked), and each Try has tier and
  tierServed. The session route has asked_tier, tier, tier_served and each
  try's tier and tier_served.
- docs/reference.md (CSV columns) and gateway-routing.md describe them.

Why
zhenghaowen0967 asked that a request whose Ultrafast was sent as priority
to an account without it show that in usage, per try, without calling
the served tier confirmed unless the reply says so.

What was run
- TestTierRecordedPerTry. With Pro out, the first try is recorded
  ultrafast, the second priority, and the final record has asked=ultrafast,
  sent=priority and served empty while the fake doesn't echo. With an
  echoing fake, served is what it said ("ultrafast", and "default" when
  none was asked). It also checks the CSV columns, and the Codex relay path
  with priority.
- TestUpstreamTierShapes covers the Chat chunk, Responses
  response.completed, a Responses body, an Anthropic message_start and
  message_delta usage, null, an over-long tier and non-JSON, as well as
  bodyTier per protocol.
- Broke it by hand:
  - with forwardOnce's noteWireTier removed, TestTierRecordedPerTry goes
    red (route tries' tier empty, TierSent empty);
  - with the sniffer's Tier line removed, TestUpstreamTierShapes goes red,
    and so does the Codex relay case of TestTierRecordedPerTry.
- go test -tags nogui ./internal/gateway ./internal/usage ./internal/cli;
  ledger_test's CSV expectations gain the three empty columns.
- gofmt -l; go vet on darwin; GOOS=linux and GOOS=windows go vet -tags
  nogui.

Not done
- The served-tier fixtures are built from the shapes OpenAI and Anthropic
  document, not from saved replies. Whether chatgpt.com's Codex backend
  echoes service_tier wasn't tried against a real account.
- Bridges that don't go through forwardOnce (the Claude subscription,
  Cursor's built-in) leave tier_sent empty.
- There is no price multiplier for priority/ultrafast and no GUI column.
2026-10-13 14:22:53 +08:00
yetone 62390fe92e redact: a masked word is never masked inside tool definitions or schemas, so Codex's apply_patch grammar reaches OpenAI intact (#1911, loveNangua)
What changed: MaskJSON masked custom words as raw substrings in every
string of the request, tool definitions included. A word "pd" turned
apply_patch's Lark rule name update_hunk into u{{TERM_..}}ate_hunk and
OpenAI refused the request with 400 "Invalid lark grammar". Definitions
are now kept by where they sit in the protocol, not by a key's name:
the request's top-level tools, tool_choice, functions, function_call,
toolConfig/tool_config, response_format, text (an object), reasoning,
include, output_format, output_config and generationConfig, and the
tools of a Responses input item of type additional_tools or
tool_search_output. Inside them only "description" strings are still
masked. A "tools" or "text" key in tool-call arguments, a message, a
Gemini part or a Responses message item is masked as before.

Run: go test ./internal/redact/ ./internal/provider/ (ok). The new
tests use Codex 0.162.1's real request (copied from the gateway's
testdata) with the top-level tools and as a Responses Lite
additional_tools item, plus Anthropic/Chat/Responses/Gemini schema
cases and negative cases. With the old json.go both tests fail
(update_hunk masked, every schema case changed). gofmt -l clean; go vet
-tags nogui on darwin, linux and windows. Not tried: a real request to
OpenAI with the word set.
2026-10-13 14:14:59 +08:00
yetone eba7187368 gateway, provider, cli, gui: a group can route By weight, each member's share set beside it (#1910, DD on Discord)
DD asked for weighted round robin as a group routing, next to In turn.
A provider's keys could already route by weight (#841). Groups could not.

What changes:
- provider: Group.Weights maps a member's spelling to its weight, 1 to
  1000. A member left out, or set to 0, weighs 1. SaveGroup accepts
  routing "weight". It also cleans weights the way it cleans fast and
  off: it strips :fast, drops weights of members that are gone and of
  members weighing 1, and refuses a weight below 0 or above 1000.
  Weights follow a member when it is renamed (RenameMember, Rename,
  RenameGroup) and survive Share/Import.
- gateway: planLevel treats each member of a weight-routed group as one
  unit: a model with its keys in its provider's order, or a nested group
  routed its own way. weightedUnits orders the units by smooth WRR on a
  round per group ("group/<id>"), sharing wrrPick with the keys. The
  round's pick goes first and the rest stay in member order for
  failover. A unit whose head is resting leaves the round. When a
  conversation is kept on another member (session/turn/cache/strict),
  the charge moves to that member (wrrSeat, wrrMove).
- cli: routing=weight (also weighted, wrr). weight=<model>=<n>[,...]
  sets weights and keeps the rest; weight= on its own clears them. The
  group view shows "· weight N" for each member.
- tui: By weight is in the group routing list.
- gui: the group editor offers By weight. Each member then shows
  "Weight N · S%", its share among the members that are on. Clicking it
  edits the number in place: Enter or blur keeps it, Escape cancels,
  and a value outside 1 to 1000 shows a warning. The trace header uses
  group wording for a weight-routed group. Strings are added in zh,
  zh-TW, ja and de.
- docs: reference.md, gateway-routing.md, and site start pages in en,
  zh and ja.

Run:
- go test -tags nogui ./internal/provider ./internal/cli ./internal/tui:
  ok.
- ./internal/gateway: ok in 988s with -timeout 45m. The first run hit
  the default 10m timeout at load average ~170. The test running at
  that moment had been running for 2s; it was not a hang.
- go vet -tags nogui on those packages, for darwin, GOOS=linux and
  GOOS=windows: clean. gofmt -l: clean.
- New group-member-weight.test.cjs: 8/8 in Chromium and WebKit, en and
  zh at 1100, en and de at 420. The WebKit de 420 case also passed six
  runs at once.
- gui-zh-tw, gui-ja, gui-de, i18n-keys, routing-*, group-*,
  panel-routing*, settings-groups and agent-model-groups: all green
  except two.
  - routing-steady (WebKit) is #1804. It is red 2/3 alone on origin/main
    e1b70c13d too.
  - routing-save-blank (chromium en) was red under load only, and 3/3
    green alone. The overshoot in its wheel loop is filed as #1924.

Broken by hand, each red, then restored:
- byWeight forced false:
  --- FAIL: TestWeightedGroup (weighted_group_test.go:69 its turn ...)
- cleanWeights call skipped:
  --- FAIL: TestSaveGroupWeights (groupweight_test.go:39 weights map[...
  an/claude-opus-5-5:0 ... oa/gpt-6.1-sol:high:fast:3 ...])
- CLI weight case renamed:
  --- FAIL: TestGroupWeightCLI (unknown field "weight")
- GUI chip not appended: group-member-weight chromium en 1100 timed out
  on the weight button.
- Not red: the test's "moved nothing" check. A scroll forced on click,
  or padding added above, did not turn it red, because the view's own
  scroll guard and scroll anchoring hold the clicked row in place. It
  only shows that the row stays under the pointer.

Not tried: real accounts through a running gateway. The routing is
proven by the plan-level test with synthetic providers only.
2026-10-13 13:10:30 +08:00
yetone 5e5b6a5ac3 provider: every account of a provider keeps its queue, limits and routing, not only the first (#1899)
A second WorkBuddy AI account queued requests for 62s with the provider's
queue wait set to 1s. The gateway takes each candidate's QueueLimit,
QueueWait, LaneLimit (MaxConcurrency) and Routing from the Provider value
it is handed. The account the agent is signed in to comes from All, which
lays the user's saved picks from providers.json over it. The other accounts
on beside it come from AlsoOn. For Claude and Codex, AlsoOn copies p, so they
had the picks. Every other sign-in builds its extra accounts afresh: all
plugin accounts (pluginAlsoOn) and the built-in extras (WorkBuddy, Grok,
Copilot, ZCode, Kiro, Devin, Command Code, Qoder, Zed, Factory, MiMo, the
Gemini sign-ins). They had none of the picks. A few getters (LaneLimit,
RPMLimit, AccountCap, proxy) already fell back to providers.json. The queue,
the provider-wide concurrency and routing did not, so an extra account
waited forever on a full lane.

The overlay All does is now withPicks. AlsoOn calls it on every account it
returns, from p as All has it. This one choke point covers every sign-in's
extra accounts, plugin and built-in, moved or not. The LaneLimit, RPMLimit
and AccountCap comments now say what still reads providers.json, and so
does gateway-routing.md's Limits row.

Tests:
- TestPluginSecondAccountKeepsTheQueue (gateway, fake plugin under bun):
  two accounts, one at once each, a queue of 1 and a wait of 1s, every
  request pinned to the second account. The third request gets 429 "queue
  is full" at once, and the queued one gets 429 "waited" after its second.
  The vendor sees only the second key.
- TestWorkBuddyAI: the second account from AlsoOn has the provider's
  queue 1/1s, MaxRPM 7, Routing ordered and LaneLimit 2.

Broken by hand (AlsoOn returning alsoOn's accounts as they are):
- The gateway test fails at its AlsoOn check. With that check off, it
  fails on "no reply in 10s", which is the reporter's symptom.
- TestWorkBuddyAI fails with "queue 0, wait 0s, rpm 0, routing "", at once 0".

Run (sandbox HOME, private GOCACHE, worktree): gofmt -l; go test -tags
nogui on ./internal/provider, ./internal/gateway, ./internal/gui,
./internal/cli and ./internal/agent; GOOS=linux and GOOS=windows go vet
-tags nogui on internal/provider and internal/gateway. Not tried with a
real WorkBuddy AI account.
2026-10-13 12:34:48 +08:00
yetone 657e48abbf routing: a request whose agent left in the retry pause says it was canceled, not "tried again in 2s" (#1894, heng91)
heng91's relay was unreachable while their proxy was off; magpie answered
the relay's 503 with its short same-one retry (or a group's replan), and
they closed the Claude Code / Codex window in the pause. The gateway
already stopped there: the pause selects on the request's context, the
route ended with 499 and the upstream was asked nothing more. But the
trace never said so: the last try kept only its Again, so the Routing
page's story ended on "... it is tried again in 2.0 s" and the list said
"499 · failed", which reads as the closed session still retrying.

- gateway: the three pauses (the last one left asked again, the same
  after spentAfter, and the group's replan through pauseAlive) mark the
  try whose pause it was `Gone` when the agent leaves in it.
- Routing page: such a try says the agent canceled the request before the
  retry and nobody is asked again (en, zh, zh-TW, ja, de); the request
  list and the outcome label say canceled; the replay's dot goes home.
- docs/subsystems/gateway-routing.md says so.

Reproduced first with a fake upstream (httptest) answering 503 and one
hanging, a real gateway server and a client that disconnects: single
provider, group replan, streamed and not, hang mid-try. In every case the
route ended at once with nothing in flight and the upstream saw no
further request (the hanging one saw its request canceled); only the
trace's last line was wrong. The plugin fetch path already sends the
host an abort on cancel (host.js "abort").

Run:
- TestAgentGoneInTheRetryPause (new, -race): agent leaves in the pause,
  single and group; upstream count stays, route done 499, no try in
  flight, last try Gone. Red with the Gone marking removed (Gone false),
  and red with the pauses ignoring the context (route not done).
- routing-agent-gone.test.cjs (new): Chromium and WebKit, en/zh/ja/de,
  1100 and 420 wide, 16/16; red (0/4) with the story and label change
  reverted.
- go test -tags nogui ./internal/gateway ./internal/gui; routing-*,
  rest-try-now and ledger-retried GUI tests on both engines; gofmt -l;
  GOOS=linux and GOOS=windows go vet -tags nogui on both packages.

Not tried: the reporter's own relay and proxy, or a real Claude Code /
Codex window closed mid-pause.

The one other red in that GUI run, routing-wb-restricted at 420 in
Chromium under the full run (passes alone 3/3), is filed as #1905.
2026-10-13 11:21:28 +08:00
congee949 b6831d83e1 gateway, gui: Codex's thread descriptions go to a model picked in Settings, apart from its titles (#1198, congee949)
Codex asks its own model, through its ChatGPT sign-in, for each thread's
description (thread_description), even while the conversation runs on
magpie's models. Settings › General gets "Codex thread descriptions"
beside "Codex thread titles". It defaults to Codex's own, which sends the
request as Codex sent it, or it can name one of magpie's models or a
routing group. The answer is wrapped as description-only JSON. The titles
setting is untouched. Usage and Routing show these requests under their
own Description purpose. The setting is kept across unrelated Settings
saves. There is no Off yet, because Codex's handling of an empty
description hasn't been checked. This is a first slice of #742.

Squashed from the PR and merged onto current main. Conflicts resolved:
- codex_backend.go: the description branch comes after the title branch,
  ahead of main's subagent pick.
- gateway.go: main's CC Switch #1301 comment above the compaction block is
  kept; the PR had shortened it.
- app.js: the gateway-mode list of hidden rows takes the new row.
- i18n.js and settings_keep_test.go: both sides kept.
- purposes.js: regenerated with go generate ./internal/usage.

Run on the merged tree:
- gofmt -l is clean.
- go vet passes on darwin, linux -tags nogui and windows; the builds on
  all three succeed.
- go test -tags nogui passes for ./internal/gateway, ./internal/gui,
  ./internal/settings and ./internal/usage.
- GUI, chromium and webkit: codex-titles, gateway-mode, purpose-filter,
  routing-purpose-state, gui-de, gui-ja, gui-zh-tw, i18n-keys,
  settings-general/-groups/-sections/-search and click-scroll: 118/118.

Broken by hand: with the description branch removed from codexBackend and
handle, TestCodexDescriptionsSetting, TestCodexDescriptionFallbackOnMagpie
and TestNoDescription fail.

Not tried: a real Codex thread_description request, and whether Codex's
sidebar takes the answer.
2026-10-13 10:13:15 +08:00
yetone 7cc393bcc1 gateway: a relay reading thinking off as effort none, refused naming its levels, is asked with thinking left to the model (#1465)
MengXiangxi's Claude Code auto mode on a Sub2API's gpt-6.1-sol blocked
every action: "Sub2API: gpt-6.1-sol does not support reasoning effort
"none"; use low, medium, high, xhigh or max" (400).

Cause: Claude Code's classifier (and every side query magpie turns
thinking off for, thinkingOffUnlessAsked) goes to Sub2API's Messages API
as it was sent, with thinking {type: disabled}. Sub2API's
anthropicReasoningEffort reads disabled as effort "none", and
ValidateGPT61SolReasoningEffort turns none away for gpt-6.1-sol
(Wei-Shaw/sub2api, backend/internal/pkg/openai/constants.go). magpie's
Anthropic retry for a refused thinking-off knew only the alwaysThinks,
mandatoryReasoning and thinkingOffRefused wordings, so this 400 went to
Claude Code. The refusal is about the model on that relay, not the
account: the same request with thinking left out is taken.

Change:
- refusesThinkingOff (anthropic.go) is the one list of thinking-off
  refusals, now also one turning a quoted "none" away while naming the
  levels taken (effortLevelsNamed && noneQuoted). Both routes use it: a
  relayed Messages request (passthrough) and a request translated to an
  Anthropic endpoint (forwardTranslated, thinkingBackOn).
- The relayed route now remembers the refusal (markUnfit(offRefused),
  the mark the translated route and passthrough effort fitting already
  read) and sends that model's later requests with thinking left to the
  model at once, so the classifier, which asks on every action, doesn't
  pay a 400 round trip each time.
- Chat/Responses routes already retried this wording through
  effortLevelsNamed (reasoning_effort none -> lowest level); unchanged.
- docs/subsystems/gateway-routing.md says so.

Tests: TestSub2APIThinkingOffRefused (the reporter's literal message;
the classifier relayed is refused once, asked again, then sent without
thinking at once, title asks included; a 400 for another level stays the
agent's), TestRefusesThinkingOff, and the Sub2API wording added to
TestTranslatedThinkingOffRefused. Broke the fix by hand twice (the new
clause off; the remembered send off) and watched each go red.

Run: gofmt -l internal/ (clean); go vet ./internal/gateway on darwin,
GOOS=linux -tags nogui, GOOS=windows; go test -tags nogui
./internal/gateway -count=1 -timeout 40m: ok in 669s (load ~40 from
other sessions; an earlier run hit the default 10m timeout under that
load). Not tried against a real Sub2API.
2026-10-13 10:06:12 +08:00
TryWorldandTryWorld 184f9184d3 gateway: a Chat turn's thinking is read in every spelling the client … (#1075)
* gateway: a Chat turn's thinking is read in every spelling the client sends it back in

A client sends the previous assistant turn's thinking back in reasoning_content (DeepSeek's, which OpenCode and most clients send), reasoning (OpenRouter's) or reasoning_details (OpenRouter's structured one). parseChat read only reasoning_content, so a request translated to a non-Chat upstream lost the thinking of every turn sent another way and the model went on without its own reasoning, which a tool-calling session shows from its second turn on. chattidy's passthrough has read all three since mistralThinking (#494); the parse layer never got the same reader.

The assistant branch now reads the thinking through reasoningText, messageReasoning's own reader, in the order the passthrough keeps it: reasoning_content, else reasoning, else reasoning_details' text.

TestParseChatReadsEveryReasoningSpelling (a tool-calling turn per spelling) and TestParseChatTakesTheFirstReasoningSpellingSent fail without the change ("the assistant turn's parts: [{Kind:tool_call ...}]"). go vet -tags nogui ./internal/gateway/..., builds for windows, darwin and linux, and the package's chat/reasoning/thinking tests pass.

* docs: the Chat parse layer reads the thinking's spellings too

The change reads a Chat turn's thinking through messageReasoning and
reasoningText, so parseChat takes the same three spellings the
passthrough has taken since mistralThinking (#494). AGENTS.md asks for the
owning reference to be updated in the same PR, and gateway-routing.md said
nothing of it: its reasoning bullets are about holding a reply's own
reasoning for a failover and about what a translated Responses reply gives
Codex, not about what a client sends back.

A bullet beside the held-reasoning one now records the spellings, the
order they are read in, and the gap that was there: the parse layer read
reasoning_content alone, so a tool-calling session whose client spelled it
another way went on without the model's own reasoning.

---------

Co-authored-by: TryWorld <TryWorld2026@users.noreply.github.com>
2026-10-13 09:41:46 +08:00
yetone fd907c986e gui: every resting key or account can be tried again by hand, on Routing and in the provider's key list (#1869)
A key resting after a 429 with a long Retry-After (a relay's 3600s) came
back only by waiting or a restart, though relays often recover in a
minute or two. The Routing page offered the lift (/api/gateway/unrest,
which already takes any rest key) only to verify and restricted rests.

- routing.js: every resting row with a rest key gets the button: "Try
  now" for quota, rate, retry-after and backoff rests, the old wording for
  verify and restricted. A lifted rest is remembered by key and the time
  it was lifted (liftedAt), so the history re-render, which reuses the
  try's rest, doesn't show it again; a newer rest still shows.
- app.js: "Try now" beside the "resting · back at …" note in a
  provider's key list, posting the key's own rest key; not hover-only.
- i18n: the three new strings in zh, zh-TW, ja and de.
- gateway-routing.md: any rest can be lifted; only the rest ends, the
  backoff count stays.

Run: rest-try-now.test.cjs (new: Routing row with the issue's zx
retry-after rest, key list row; en/zh/zh-TW/ja/de, chromium and webkit,
1100 and 420px; asserts the post, the note gone, no sideways scroll,
reached by wheel, the click doesn't scroll) 40/40, red on the old
app.js/routing.js. 71 key*/routing*/rest* GUI files at concurrency 6:
826/831; the 5 reds (key-balance-card, routing-group-fold) pass alone
and are timing under load (routing-group-fold fixed in the next commit).
go test ./internal/gui passes.
2026-10-13 07:30:06 +08:00
yetone a68d2ac944 gateway: a held stream lets through only text, reasoning or a call, so a 200 that only framed a reply fails over (#1418)
Aliceonly's trace on #1418: sub2api answered 502 "Upstream HTTP/2 stream
failed", then Codex account A answered 200, sent only the frames before a
reply, and failed server_is_overloaded 37s in. Five candidates after it
were never asked, and Codex ended the turn. The stream had been let
through (h.passing), so holdWriter.failed() was false and neither the next
candidate nor a replan was tried.

Two ways a frames-only stream went through:
- streamEvent's default was eventContent: any event it didn't know (and an
  item of a type said() didn't know) counted as the reply begun. Now only
  the events of each protocol that carry text, reasoning, a call or a
  reply's end (replyEvent) count; anything else is eventLead, held as a
  ping is. An unknown item counts only when it is a call or a tool's
  (web_search_call, server_tool_use, mcp_*). A stream that ends well is
  still released whole, so this can only delay, never drop, a reply.
- a reply under a Content-Type that says neither JSON nor a stream, once
  the agent had a stream's headers, went straight through when its first
  bytes were SSE (sseStart -> pass()). It is now held as a stream from
  there and read event by event.

Which event Codex's backend actually sent isn't in the trace; the test
uses a keepalive, response.rate_limits.updated and an unknown item type.

Run: go test ./internal/gateway -count=1, green (428s).
TestFramesThenOverloadedGoesToTheNext (new: 502, then 200 frames + unknown
events + server_is_overloaded, then a third member) and
TestStreamEventUnknownOnlyFrames (new) fail on the old fallback.go: the
overloaded stream reaches the agent and c is never asked.
TestHeldUnsureStreamPasses/KeptAlive now expect the stream held until its
first word, and TestHeldUnsureStreamFailsHeld (new) a failure among held
frames; all fail on the old code. Not tried against the real ChatGPT
backend.
2026-10-13 07:30:06 +08:00
yetone 4a6c81e038 gateway: a group's Patience is waited out in full, not cut at 90s by the round count (#1418)
A group asks its busy members again after pauses of 2s, 4s, 8s, 16s, then
30s, for as long as its Patience lasts, but replanRounds stopped it after
6 rounds: 90s of pauses whatever the group was set to. real-jacket's trace
on #1418 shows patience=240 with replan=6 and ~103s in all. replanRounds
is now 12, a backstop sized so that the pauses alone reach
PatienceLongest (240s) in 11 rounds, and the patience is what ends the
wait. It stays bound by kept.tooQuiet, as before. The longest pause is
now 30 x retryPause (30s in use), so the tests' 1ms retryPause doesn't
grow a 4s pause at round 12.

Run: TestPatienceIsUsedUp (new) counts replan's pauses for 30s to 240s of
patience, and TestReplanRoundsOutlastPatience (new) sums the backstop's
schedule. With replanRounds back at 6, both fail: patience 3m0s and 4m0s
pause 1m30s. go test ./internal/gateway -run
'Overload|Patience|Replan|WaitsOut|Busy|Codex' is green. Not tried
against a real overloaded vendor for 240s.
2026-10-13 07:30:06 +08:00
yetone 3b4063e75e gateway: a 400 for a tool schema past a model's nesting depth goes to the group's next member (#1870)
OpenCode Go answered Claude Code's MCP tools on muse-spark-1.3-contributor
with 400 "JSON schema exceeds the maximum nesting depth of 10 levels", and
group/intent-auto returned it to the agent instead of asking the next
member. shapeWords didn't know the wording, so shapeRefused was false and
the error ended the turn. It now matches "schema exceeds the maximum
(nesting) depth" and "schema ... nesting depth". The schema isn't
truncated, nothing rests, and plain parameter errors ("Field required",
"not a valid type") and a 200 that mentions the depth still don't fail
over.

Run: go test ./internal/gateway -run 'TestGroupFailsOver' -count=1, green.
With the new alternatives removed, TestGroupFailsOverARequestShape fails
on both depth bodies and TestGroupFailsOverASchemaTooDeep gets the 400
back with b never asked (a 1, b 0).
2026-10-13 07:30:06 +08:00
yetone 1a44670302 gateway: a long Codex session full of images is read up to 512 MB, and magpie's 413 says it is magpie's limit and to /compact (#1422, NeoPengZhile)
NeoPengZhile's Codex (signed in to ChatGPT, through /backend-api/codex/
responses) got "413 Payload Too Large: request body exceeds gateway
limit" on all five reconnects in a long session that had read many
images; a new session worked. Codex sends the whole conversation every
turn, screenshots inline as base64, zstd-compressed; magpie's limit is on
the decoded body and was 128 MB, while magpie compresses a ChatGPT turn
again on the way out, so the backend sees about what Codex alone would
send. The message didn't say whose limit it was or what to do.

What changed:
- request_bounds.go: defaultBodyLimit 128 MB -> 512 MB (decoded, which
  also sets the zstd decoder's memory cap). Every route that reads with
  the default gets it, keyLimited's read among them, so a limited key
  isn't held to the old number first. Routes with their own lower limit
  (System One 16 MB, a Claude subscription's 16 MB) keep it.
- overLimit: magpie's own 413 says "request body is over magpie's
  gateway limit of 512 MB (decoded); the provider was not asked".
- gateway.go writeError: the hint added to a 413 now says it is a byte
  limit, not the model's context, and to /compact (Codex, Claude Code) or
  start a new conversation.
- request_bounds_test.go: TestRequestBodyTooLarge uses defaultBodyLimit+1
  in place of a literal 129 MB.
- docs/subsystems/gateway-routing.md says so.

Run: go test ./internal/gateway/ -count=1 (ok, 354s), with the new
TestImageHeavyCodexTurnIsRead (a zstd body of inline images decoding to
136 MB on Codex's backend path, read with the default limits) and
TestOverLimitSaysWhoseAndWhatToDo; go test ./internal/gui/ (ok); go vet
./... on darwin, GOOS=linux -tags nogui and GOOS=windows; gofmt -l.
Broken by hand: the limit back at 128 MB -> TestImageHeavyCodexTurnIsRead
fails with the 413; the old "exceeds gateway limit" message, or the old
hint, -> TestOverLimitSaysWhoseAndWhatToDo fails.
Not tried: the reporter's real session, or how big a turn the ChatGPT
backend itself takes; the test's images repeat, so its wire size is far
smaller than real screenshots'. Peak memory for a turn near 512 MB was
not measured.
2026-10-13 07:07:18 +08:00
yetoneandggbdpq cc93b566e2 gateway: Zed's test still checks is_error true on a real result, beside the mended orphan (#1558)
What changed: d1d45dd3 made TestZedToolResultSaysIsError's toolu_2 result
an orphan turned to text, and its assertion went from [false true] to
[false]: nothing checked any more that a result with is_error true goes
to Zed's cloud with it (yetone/magpie-releases#9). The fixture's
assistant now makes toolu_2's call, so both real results keep [false
true], and a separate toolu_9 result with no call checks the orphan goes
as its text. The pairing tests also check the synthetic result is
is_error, and a new TestMessagesSecondAnswerDropped checks a call answered
twice keeps only its first answer. docs/subsystems/gateway-routing.md gets a bullet for the Messages build's mending, beside the Gemini and Responses ones.

Why: the patch's tests passed with is_error dropped from the synthetic
result and with the second-answer rule removed.

Run (sandbox HOME, private GOCACHE):
- go test -tags nogui -run 'TestMessages|TestZed' ./internal/gateway/: ok
- pairToolBlocks call removed: the six TestMessages tests and
  TestZedToolResultSaysIsError fail ("is_error: [false true false]",
  "what the lost result said is not kept").
- IsError dropped from the synthetic result: TestMessagesUnansweredCall
  GetsSyntheticResult fails. The duplicate's continue removed:
  TestMessagesSecondAnswerDropped fails ("user[A,A]").

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-13 06:43:00 +08:00
yetone 841af36bfc gateway: models the user disabled are refused on every route, and leave every list (#1867)
oxsean asked for one place to turn a model (claude-fable-5) off for good:
not reached by a direct request, an old session, a routing group member,
a fallback, a sub-agent, count_tokens or a decision model.

What changed:
- settings.DisabledModels: patterns, an exact id or a glob (* any run, /
  included; ? one), matched ignoring case against provider/model, the
  bare id and its last segment (provider/disabled.go). Empty by default,
  so nothing changes for anyone who doesn't set it.
- Lists: buildEntries (entriesOff) leaves a disabled model out of the
  catalog, so /v1/models, agents' model files and pickers, Codex's list
  and every group go without it; membersIn skips it as a member, Deciders
  as a decision model; codexModels drops Codex's own disabled slugs and
  codexListTag changes so Codex refetches.
- Requests (gateway/disabled.go): 403 "model <id> is disabled in magpie"
  in each API's error shape, at #882's choke points: serve (idOff),
  perKeyBarred (no candidate: group next member, provider Fallback),
  count_tokens and Gemini :countTokens, serveSystemOne,
  serveDecisionGroup and postDecide, draw/video/embeddings, and
  codexBackend for Codex's own bare models. A group with a member left
  goes on without it; one with none left is refused naming them. A bare
  id the catalog no longer has is refused as disabled, not 404. A Codex
  sub-agent pick onto a disabled model stays on its lead's model.
- An unreadable settings.json is never "none disabled": the list read
  last stays; with none read, every request is refused; nothing is
  written over the file.
- CLI: magpie model disable <model|glob>..., enable ..., disabled
  (list-disabled).
- GUI: Settings > Models > Disabled models: each pattern with the models
  it matches now and Enable; Disable... opens the model picker, which
  also takes a typed glob. Says only requests through magpie are covered.
  POST /api/settings/disabled-models; POST /api/settings keeps the list.
  Strings in zh, zh-TW, ja, de.
- docs/subsystems/gateway-routing.md: Disabled models section.

What was run (worktree at origin/main 091593f7d, private GOCACHE, temp HOME):
- gofmt -l clean; go vet on darwin (touched pkgs), GOOS=linux -tags nogui
  ./..., GOOS=windows ./... clean; go build ./...
- go test -count=1 ./internal/provider ./internal/gateway ./internal/cli
  ./internal/gui ./internal/settings: all ok (gui after adding the field to
  TestSettingsSaveKeepsWhatItDoesNotSend's fixture, which it asked for).
- node --test internal/gui/tests/disabled-models.test.cjs: 16/16 (chromium
  + webkit, en/zh/ja/de, 1100/420); neighbouring Settings > Models tests
  and i18n-keys: 131/131.
- Broken by hand, each turned TestDisabled* red: serve's idOff (404
  instead of 403), perKeyBarred's filter (fallback reached spare), the
  catalog filter (/v1/models and Codex list), countOff (count_tokens 200),
  postDecide's check (decision call went out).
- Not tried with a real vendor account or a real agent.

Ref #1867
2026-10-13 05:34:13 +08:00
yetone 125dad5cbb gateway: a codex provider used only through routing groups keeps the ChatGPT account's own models out of Codex's list (#1602)
With Codex signed in to ChatGPT, Codex asks magpie's /backend-api/codex/models
for its list, and codexModels passes the backend's own models through,
narrowed only by the codex provider's picks (CodexNativePicked) and the
Agents page's hides (CodexNativeHidden, built from Catalog()). A provider
set to "Only through routing groups" (Provider.Unlisted) has none of its
models in Catalog(), so neither filter saw them: all of the account's
models stayed in Codex's picker, and the Agents page had no Codex group to
hide. Every other agent's list is Catalog-based and already left them out.

provider.CodexNativeUnlisted says which of the account's models are kept
out of agents' lists: every one when the codex provider is Unlisted, and by
slug those a group with Unlists names. codexModels drops them (hidden
entries such as codex-auto-review stay, as with picks; a Codex reached for
failover alone keeps them, as it is handed no groups), spawnChoices drops
the same ones from spawn_agent's list, and CodexListTag carries them so
Codex refetches. gateway-routing.md says so.

Test: TestCodexModelListUnlistedForGroups (a group unlisting gpt-5.5 takes
gpt-5.5 alone; the provider Unlisted takes gpt-6-sol and gpt-5.5 and keeps
codex-auto-review; ETag changes; spawn_agent offers neither; own-only keeps
them). With codex_backend.go and codex_spawn_models.go reverted it fails on
all three checks. Not tried with a real ChatGPT sign-in and Codex app.

Run (sandbox HOME, private GOCACHE, worktree at origin/main 97dfed0f3):
gofmt -l; go vet ./... (darwin), GOOS=linux -tags nogui, GOOS=windows;
go build for all three; go test -tags nogui ./internal/gateway
./internal/provider ./internal/catalog ./internal/codexcat: all ok.
2026-10-13 05:05:23 +08:00
yetone 091593f7d3 gateway, gui: a WorkBuddy account the vendor restricted (403 11140) rests 2 hours as restricted, and Routing names the appeal as the way back (#1849)
WorkBuddy answers an account it restricted for unusual activity with
403 {"code":11140,"msg":"request illegal","displayMsg":{"en":"Your
account has been restricted due to unusual activity",...}}. failure()
read it as an unknown failure, so the account rested 1-10 minutes and
was asked again, refused, all day.

What changed:
- provider: WBRestricted knows the refusal by code 11140 (top level,
  data or error; number or string; whole, so 111400 isn't it) or by its
  displayMsg words. wbExplain ends the built-in's error with
  WBRestrictedHint.
- gateway: a new failRestricted ("restricted") rests restrictedRest, 2h:
  one refused request per account per 2h, and a lifted restriction (or a
  misread refusal) comes back the same afternoon; Unrest lifts it at
  once. It is read from the hint in the error (restrictedSaid; both the
  built-in and the plugin translate the vendor's body before failure()
  sees it, so the raw JSON never reaches it in a chat try), or from the
  raw body only for a WorkBuddy candidate (restrictedRefused,
  isWorkBuddy), since another vendor's 11140 is its own. Bare "request
  illegal" is not matched. 11128 stays promptRefused and rests nobody.
  The stale-allowance shortcut skips it, as it does model refusals.
  drawsWorkBuddy now uses isWorkBuddy.
- plugin: @magpie-community/opencode-workbuddy-auth 0.1.17 (plugins
  caf3908) ends the error with the same hint; the mover's min is 0.1.17
  so keepMovedCurrent brings moved users to it.
- gui: Routing labels the try "account restricted by the vendor", says it
  rests because only the vendor lifting it brings it back and to appeal,
  shows the hint translated, and the account's row has "The restriction
  is lifted — try it again" (POST /api/gateway/unrest). en, zh, zh-TW, ja,
  de.
- docs/subsystems/gateway-routing.md says the above.

Run: gofmt -l (clean); go vet darwin, GOOS=linux -tags nogui, GOOS=windows
on gateway, provider, gui; go test ./internal/gateway ./internal/provider
./internal/gui (ok). New Go tests use the reporter's literal body through
the vendor's shape, the built-in's and the plugin's, a string code and the
words alone; another vendor's 11140, a non-WorkBuddy account with the same
body, 11128/14018/111400 not restricted; an e2e through the fake plugin
host where the restricted account is skipped by the next request.
Broken by hand, each went red: rest case removed, restrictedSaid removed,
the match unscoped, the raw match removed, the provider hint removed.
GUI: routing-wb-restricted (chromium and webkit x en/zh/zh-TW/ja/de x
1100/420px, 20 pass), routing-wb-refused, i18n-keys; after the rebase
every GUI test of the Routing page (107 files, both engines): 103 green.
The 4 red ones fail the same in WebKit on origin/main 689edbd6b run
alone and are filed: group-member-info (#1745), routing-sessions
(#1307, #1672), routing-steady (#1804, passed on this head on a rerun),
routing-group-fold's group-of-eight (#1672).
Rebased onto 2c30e5cee (with #1672's test fixes) and run again: vet x3,
go test ./internal/gateway ./internal/provider ok. On the final base
5756651e3 (only GUI assets and READMEs changed since): routing-wb-restricted
20/20, routing-wb-refused, i18n-keys, routing-held-dot, mono-icon-redraw,
routing-sessions 38/38, routing-group-fold 40/40; routing-steady's WebKit
case red again, the flake filed as #1804.
 Not tried against a real restricted account;
plugin users on <0.1.17 rest by minutes until their plugin updates.
2026-10-13 04:32:09 +08:00
yetone 5ca9dc19db usage, gui: a model says how many of its replies were ended for looping (#1858)
#1858 asked for recovery across turns when a model loops. magpie is a
gateway and can't rewind the agent's session, so that is not planned now.
What it can do is let the reader see which model loops. Each reply the loop
guard ends (#1359) is logged with err_type "reply_loop", but Usage only
counted it among the failures.

usage.LoopErrType is now that type (the gateway's loopErrType is it), and
Totals.Loops counts, among the failed requests, those ended for looping. A
handed-on try is still no request. The Overview's model, agent, account
and key rows and the Requests ranking say "{n} looped" beside "{n}
failed", and the ranking's "Other" adds them up. Translated into zh,
zh-TW, ja and de.

Run: TestLoopsCountedPerModel (Overview groups, the ledger sum and
Breakdown; red with the increment removed). go test ./internal/usage
./internal/gateway ./internal/gui; gofmt -l; go vet on darwin, linux
-tags nogui and windows. The new usage-loops.test.cjs ran in chromium and
webkit, 5 languages at 360 and 1100px, 20 pass; it fails 10 of 10 on HEAD~
assets. usage-*, ledger-*, own-requests, i18n-keys and gui-zh-tw/ja/de in
both engines: 565 pass.
Not run: a real looping model through the gateway (the logging path is
unchanged from #1359).
2026-10-13 04:31:07 +08:00
yetone 05ef7bcec7 gateway: Cursor's built-in shows the model a tool's images, in the message after its results (#1861)
Found while checking every translation of a tool's images for #1861.
cursorMessages wrote a tool result's text alone, so an image Codex's
view_image (or any tool) returned never reached a model behind the
Cursor built-in. Cursor's plugin already gets it, since magpie hands it
a Chat body (seeLater: the result says the image follows, and a user
message after the results carries it).

The built-in now does the same: a result with images says
"[The tool returned an image; it follows in the next message.]", and a
user message after the results holds "[From the result of <name> (tool
call <id>):]" and each image as Cursor's image block (cursorImage, the
same block a user's own image already used). gateway-routing.md names
Cursor among the translations.

TestCodexToolImageCursor, from codex-rs 0.162's view_image output, fails
on the old cursor.go and passes now.

Run: gofmt -l; go vet darwin, linux -tags nogui, windows on
internal/gateway; go test -tags nogui ./internal/gateway
./internal/provider (sandbox HOME, ok).
Not tried: a real Cursor account. Whether Cursor's backend shows the
model an image in a user message that follows tool results is taken from
how it takes a user's own image, not seen.
2026-10-13 04:00:57 +08:00
yetone 285e17b061 provider: a moved Kiro shows the model a tool's images, Codex's view_image among them (#1861)
simonsmh (v0.1.1215) saw Codex's view_image and screenshot results come
back empty on a Kiro subscription. magpie hands Kiro's plugin an Anthropic
body whose tool_result holds the image as a base64 image block, but the
plugin (@magpie-community/opencode-kiro-auth up to 0.1.8) read only a
tool_result's text, so the image was dropped and the model was told
"(no output)". #369 had fixed this in the built-in for Claude Code; the
plugin never got it.

Kiro plugin 0.1.9 (magpie-community/plugins 66facac) sends a tool's images
with the userInputMessage that answers the call, latest images only, as
the built-in does. This raises the mover's min to 0.1.9, so
keepMovedCurrent updates every moved user.

tool_images_1861_test.go builds the request from what codex-rs 0.162
sends (FunctionCallOutputContentItem, view_image's input_image data: URL
with detail "high") and checks the handoff to the plugin (the image in
the tool_result, bytes intact) and the built-in Kiro body. Both pass on
the old code too: the bug was in the plugin, whose tool-images.test.mjs
fails 3 of 4 on 0.1.8. gateway-routing.md says how a tool's images reach
the model on each translation.

Run: gofmt -l; go vet darwin, linux -tags nogui, windows on
internal/gateway and internal/provider; go test -tags nogui
./internal/gateway ./internal/provider (sandbox HOME, ok); the plugin's
bun test (1152 pass) and scripts/check.mjs; npm view on
registry.npmjs.org shows 0.1.9.
Not tried: a real Kiro account, or real Codex against it.
2026-10-13 04:00:56 +08:00
yetoneandEdward4226 da085e3f78 gateway: joinToolRuns leaves the model's own step and every call-carrying item in place, and a result written before its call opens no run (#1752, #1822)
What: follow-up to Edward4226's joinToolRuns (previous commit), after review
against Codex rust-v0.162.1 and the code around it.

- An item carrying a call_id is never moved, whatever its type. Before, only
  function_call/custom_tool_call/tool_search_call counted as calls, so a
  local_shell_call (or any call type Codex adds) inside a run was moved after
  results, its own output's among them.
- Before the run's first result, what the model wrote between its own calls
  (reasoning, assistant text, a hosted tool's call) stays where it is. Before,
  [call_a, reasoning, call_b, out_a, out_b] sent the reasoning after the
  results, where it reads as the next step's: DeepSeek, whose step must lead
  with its reasoning (reasonFirst, f4cc7459), would get a step that isn't.
  Anything else there (a subagent's agent_message, a note) still moves after
  the run, so TestGrokGetsAgentMessageAsUser's expectation from the previous
  commit stands.
- A call opens a run only when a result after it answers it. Before, a result
  written before its call (an odd replay) left the run open for the rest of
  the request, and every later message was moved to its end.

Where it happens, checked in Codex's source: prepare_response_items
(core/src/image_preparation.rs) pushes the developer <image_resize_notice>
right after each function_call_output / custom_tool_call_output whose image
it resized, so a batch of two image results has it between them, as #1822's
rollout shows (lines 347-349).

Routes: joinToolRuns sits in attempt before every destination, so the
Responses relay, plugins (relayed through passthrough) and translations all
get it. Translations rebuilt the order themselves for a developer or user
item (the developer one is lifted into the system prompt, user turns merge
and results go first), but an assistant message between two results closed
the chat exchange: pairToolMessages answered the second call with the
synthetic "unavailable" result and sent the real one as user text
(TestTranslatedToolRunKeepsItsRealResults, red without the call site).

Docs: gateway-routing.md says what attempt mends in a Responses request's
tool exchanges (joinToolRuns, orphanedToolOutputs, pairToolItems).

Run:
- TestRelayedCodexImageBatchKeepsItsResultsTogether (#1822's call ids, two
  view_image results, the notice between; the fake answers DeepSeek's "No
  tool output found for tool call …") and TestTranslatedToolRunKeepsItsRealResults
  fail with the call site removed (400 / synthetic result) and pass with it.
  TestJoinToolRunsOnlyMovesWhatBreaksARun fails on the previous commit's
  joinToolRuns (reasoning moved, local_shell_call moved, a request rewritten
  for a result before its call) and passes now.
- go test -tags nogui -count=1 ./internal/gateway/ under a sandbox HOME with
  a private GOCACHE: ok (376s). gofmt -l: nothing. go vet (darwin),
  GOOS=linux go vet -tags nogui, GOOS=windows go vet on ./internal/gateway/:
  clean.
- Real DeepSeek (api.deepseek.com/v1/responses, deepseek-v4-flash), direct:
  a developer note between the two results 400 "No tool output found for
  tool call call_01_x2"; the same note after the results 200. Through a
  sandbox magpie (own HOME, :3591, only the deepseek provider), streamed and
  whole: origin/main's build 400 with that refusal, this build 200. The
  <image_resize_notice> text itself between the results is answered 200 by
  DeepSeek directly, before and after, with text results.

Not tried: OpenCode Go (this account's workspace isn't set to Global
regions, so every request there is refused before the model); the
reporter's image results and full-length history; Volcengine; a real Grok
subscription for the agent_message's new place.

Co-authored-by: Edward4226 <234070868+Edward4226@users.noreply.github.com>
2026-10-13 03:49:32 +08:00
yetone 689edbd6be gateway: a Codex subagent refused for a sealed task is told the task itself is sealed, which fork_turns="none" doesn't change (#1855, hanekoo)
hanekoo's Codex Desktop lead on gpt-6.1-sol (Codex's own ChatGPT sign-in)
spawned a subagent on antigravity/gemini-3.8-flash with fork_turns="none"
and got the sealed-task refusal, which read as if the lead's turns were
the problem and fork_turns="none" should have avoided it.

What Codex rust-v0.162.0-alpha.17.2 sends (read from its source, not the
reporter's bytes, which aren't available): spawn.rs's fork_mode is None
for "none", so no turn of the lead's is copied in. The subagent's task is
spawn_agent's `message` argument; the ChatGPT backend returns it sealed
(the function call's encrypted_function_args), router.rs's direct_source
makes it ToolCallSource::Direct, agent_message_from_tool makes it
AgentMessage::Encrypted, and to_model_input_item writes it as the
agent_message's encrypted_content under the NEW_TASK header. So the one
sealed thing in the subagent's first request is the task itself: there is
nothing magpie can leave out and still give the subagent work, and no
request flag in Codex asks the backend for plaintext arguments. The
refusal stays; it now says why.

- codex_backend.go: sealedTaskItself, added to all three sealedTaskError
  variants (lead unknown / Codex's own sign-in, a relay that sealed it,
  plugins#70's earlier chat provider): what is sealed is the task the
  spawning agent wrote in spawn_agent, and fork_turns="none" keeps only
  the lead's turns out, not the seal. The existing advice (the lead's
  model for the subagent, or a lead not on the ChatGPT backend) stays.
- docs/subsystems/gateway-routing.md: the same, under sealed tasks.
- sealed_fork_none_test.go: the fork_turns="none" first request rebuilt
  from Codex's source (developer + environment_context + the sealed
  NEW_TASK with Task name/Sender lines), a lead first on Codex's own
  sign-in, the subagent on a chat provider. It is refused before the
  provider is asked, with no ciphertext in the reply, and says the task
  itself is sealed whatever fork_turns says.

Run: with the old codex_backend.go put back,
TestSealedTaskWithForkTurnsNoneSaysTheTaskItselfIsSealed fails ("the
refusal doesn't say the task itself is sealed whatever fork_turns
says"); with the change it passes. gofmt -l (empty), go vet / GOOS=linux
-tags nogui / GOOS=windows go vet ./internal/gateway, go build, GOOS=linux
-tags nogui and GOOS=windows go build ./..., go test -tags nogui
./internal/gateway (ok, 353s) under a sandbox HOME with a private GOCACHE.

Not run: the whole `go test ./...` (only the gateway package changed);
no real Codex Desktop or ChatGPT account was used, so the reporter's
bytes are not reproduced; the GUI's sealedKept text is unchanged. The
502 "context canceled" on gpt-6.1-sol in the report is Codex's own
sign-in request most likely cancelled by Codex itself (the client went away), a separate
request, and wasn't chased.
2026-10-13 03:16:13 +08:00
yetone 248a68598c gateway, provider, gui, cli: a key+URL provider may be sent the agent's own User-Agent in place of magpie's (#1851)
Every forward went with User-Agent magpie/<version>. A coding plan that
serves only the agents it names (pi, OpenCode, Claude Code…) knows them by
their User-Agent, so it turned magpie away.

What changed
- provider: PassUserAgent (passUserAgent in providers.json), off by
  default. PassesUserAgent takes it only for a key+URL provider: never a
  signed-in account, a plugin's, or a vendor whose own client magpie goes
  as (OwnClient: OpenCode, Cline, Kilo, another magpie). A copy keeps it.
- gateway: userAgentFor in forwardOnce (chat, Anthropic, Responses,
  Gemini, count_tokens) sends the inbound User-Agent unchanged where the
  provider passes it on. It sends magpie's where it doesn't, where the
  agent sent none, and on magpie's own requests (magpiesOwn: magpie/…,
  magpie-router/vision/search, the image tool's "<client> magpie-image/1",
  which is built from MCP clientInfo, not a User-Agent). magpie never
  invents another client's. The claude-cli/Codex header copies, the
  OpenCode/Cline/Kilo overrides and account signing run after it as
  before, and the user's header.User-Agent is put on at signing, so it
  wins.
- gateway: embeddings, images and videos (retrieveFrom, sendWith,
  remoteVideoContent) now stamp the same for a key+URL provider through
  stampUA, from the caller's User-Agent kept on the request ctx
  (caller.ua, withCaller). Before, they went with Go's default
  (Go-http-client/1.1). Account and remote-magpie paths are untouched.
- cli: `magpie provider set <id> user-agent=agent|magpie`, refused for a
  signed-in account; `magpie provider <id>` shows it.
- gui: the provider editor's User-Agent row, "Send the agent's own
  User-Agent", with an explanation, for a provider with a key only (the
  JSON says ownClient for presets and providers); en/zh/zh-TW/ja/de.
  The TUI only adds presets, so it has no field for this.
- docs: reference.md (provider set) and subsystems/gateway-routing.md.

What was run
- gofmt -l clean; go vet ./... on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- go test -count=1 ./internal/gateway ./internal/provider ./internal/cli
  ./internal/gui: all ok (sandbox HOME, private GOCACHE).
- TestUserAgentPassedOn covers 7 routes (messages, count_tokens, chat,
  responses, gemini, embeddings, images) x off / on / on with no UA / on
  with magpie-router/1 / on with the image tool's UA / the user's header
  with it on and off. TestUserAgentAccountUntouched: a Factory account
  with passUserAgent in providers.json is still asked as factory-cli/.
  Also TestUserAgentClaudeCodeAsBefore, TestUserAgentFor,
  TestPassesUserAgent, TestAddCopyPassUserAgent, TestProviderUserAgentPair.
- Broken by hand, each went red: forwardOnce back to magpie's UA (5
  routes red); stampUA removed from embeddings/draw (both red, seen as
  Go-http-client/1.1); PassesUserAgent ignoring accounts/OwnClient;
  magpiesOwn dropped (the internal UAs leaked on all 7 routes); the GUI
  row shown for OpenCode and Save not posting it.
- provider-user-agent.test.cjs: 60/60 in chromium and webkit, en, zh,
  zh-TW, ja, de, at 900 and 440 wide. The provider/editor/add/i18n GUI
  tests in chromium: 244/244.

Not run
- Not tried against a real coding plan that checks User-Agent, nor with a
  real agent through a live gateway. Videos have no test of their own
  (they go through sendWith, which the images test covers).
- The GUI suite was not run in full; the Windows box was not used.
2026-10-13 02:56:34 +08:00
yetone 50adf78e66 gateway, gui: the web searcher picked in Settings is never handed on to another provider, and one that answered without searching is said so (Gearclickist on Discord)
Cause: Gearclickist picked the Grok subscription's grok-4.7 in Settings ›
Web search. Their grok rows were about 1.3k tokens. That is the size of a
Grok request that ran no search. With the tool and searching, our real
Grok account gives 6k-66k input every time, and /models says
supports_backend_search for all four models. So on their account Grok
answered from what it knew. searchWith read that as "found nothing", and
modelSearch handed the search to the next of Searchers() by rank: Codex's
gpt-6-astra, a pricier subscription model they never picked.

Change:
- modelSearch: a searcher named in Settings gives way to no other
  provider. Its error goes back to the model ("no other provider searches
  in its place"), and webSearch then asks the search APIs, if any are set
  up. Automatic keeps its fallback (#669) with the Routing row that says
  why.
- searchWith tells a reply with no server_tool_use or
  web_search_tool_result (errNotSearched) apart from one that searched and
  named no page (errFoundNothing). CallFor gets notSearched.
- namedFailed/SearcherFailed keep the named searcher's last failed search,
  cleared by its next success or by picking another searcher.
  /api/settings returns it as searchFailed.
- Settings › Web search puts a warning at the start of the row's help
  (before the ellipsis) naming the searcher, when, and why ("answered
  without searching the web, so its account or plan may not offer web
  search"). The help text now says a picked provider is never replaced by
  another provider. The Routing row (kindWhy) says not-searched too.
  zh, zh-TW, ja and de strings added.
- docs/subsystems/gateway-routing.md rewritten for the rule.

Run (worktree on origin/main fd0359233):
- Real Grok account (sandbox, requests only): grok-4.x with the
  web_search tool searched each time (6k-66k input, cache 3456). Without
  it, about 1.3k input, cache 1152, which matches the reporter's rows.
- go test -tags nogui ./internal/gateway ./internal/gui: ok.
- gofmt -l is clean. go vet passes on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- Broken by hand, the tests go red:
  - Dropping the no-handover rule turns TestPickedSearcherIsNotHandedOn
    and TestSearcherFindingNothingGivesWay red.
  - Dropping the !searched check turns the NotSearched assertions red.
  - Reverting app.js/routing.js turns the new searcher-pick and
    search-instead cases red.
- GUI (playwright 1.62.0), chromium and webkit, every language, widths
  560 and 1000: search-instead, searcher-pick, i18n-keys, settings-search,
  provider-search, search-api, search-first and search-mcp all pass,
  except searcher-pick's "search help preserves ellipsis and hover titles"
  on webkit en/ja/de. That case is red on origin/main too (#1745).

Not run or not changed:
- The reporter's own account wasn't reproducible, so why Grok skipped the
  search there isn't known.
- No change to the Grok plugin or the built-in: supports_backend_search
  is true for every model, so reading it wouldn't have caught this case.
- Not tried on Windows or Linux GUI.
2026-10-13 02:30:53 +08:00
yetone 91e7ef56af settings, gateway, gui: a browser extension is listed among the web pages that may call magpie by its origin, chrome-extension://<id> and the like (#1051, SkyAerope on Discord)
What: Settings › Network and sharing › Web pages now takes a browser
extension's origin besides http(s) ones: chrome-extension://<id>
(Chromium, the id 32 letters a-p), moz-extension://<uuid> (Firefox's
Internal UUID) and safari-web-extension://<uuid> (Safari). cleanOrigin
takes only those three schemes, only with an id of that browser's shape,
lower-cased and with a trailing "/" let go; a bare scheme, a wildcard, a
path, a port, user info, a query or another browser's id shape is
refused. The GUI maps the new refusal to the same message, which now
names the extension form, in en/zh/zh-TW/ja/de, and a listed origin
wraps instead of being cut (an extension's runs to 50-60 characters and
was ellipsized at a 440px panel). The 401 a listed caller gets without a
key names extensions too. Docs: gateway-routing.md, the settings field.

Why: an extension without host_permissions (Sider and the like) is held
to CORS; the gateway never answered its preflight, since its origin
couldn't be listed. Nothing else in the access rules changes: corsGuard
treats a listed extension exactly as a listed page (preflight answered,
every call needs an enabled gateway key or gets 401, even on loopback),
an unlisted extension passes with no CORS headers as before (foreignPage
still only judges http/https), and lanGuard's rebound/Host checks, the
allow list and every other route guard are untouched.

The Origin each browser sends was checked, not guessed: real Chromium
(below) sent Origin: chrome-extension://<32 a-p>; Firefox's is
moz-extension://<Internal UUID> (Gotify's and others' CORS docs list
it); Safari's is safari-web-extension://<lowercase uuid>, per Apple's
developer forums (thread 654839), where an Apple engineer notes the uuid
changes on each Safari launch, so a Safari listing lasts until it
restarts (said in the doc). A content script's fetch carries the page's
origin (MDN), so only extension pages, popups and workers are covered.

Run, at 28aac86bc:
- TestCleanExtensionOrigins (good ids, upper case, trailing slash;
  malformed, wildcard, bare scheme, path, port, userinfo, query, swapped
  id shapes) and TestCORSExtensionOrigin (through lanGuard: unlisted
  preflight/request get no CORS headers and the request runs as before;
  listed chrome and moz preflight 204 with the headers; keyed call 200
  with Access-Control-Allow-Origin; keyless or wrong key 401 without
  reaching the vendor; another id still unlisted). Both fail on the old
  origins.go (the extension origin "is not an origin").
- go test ./internal/settings ./internal/gateway ./internal/gui: green.
- gofmt -l clean; go vet ./... darwin, GOOS=linux -tags nogui,
  GOOS=windows: clean.
- GUI: cors-origins (extended: an extension added upper-cased with a
  trailing slash is saved lower-cased and fits the panel, a malformed id
  and chrome-extension://* refused in the page's language), i18n-keys,
  gui-de, gui-ja, gui-zh-tw, allow-ips, lan-docker, chromium and webkit:
  green. cors-origins fails on the old app.js/app.css (the name was cut,
  the extension refusal untranslated).
- Real use: an unpacked MV3 extension with no host_permissions, loaded in
  headless Chromium 1234 (playwright launchPersistentContext,
  --load-extension), fetched a sandbox gateway (lanGuard(New().Handler())
  on 127.0.0.1:3591 under a temp HOME, fake vendor) from its service
  worker and its own page. Not listed: "Failed to fetch" in all four
  cases. Listed (typed upper-case with "/"): with the key, read 200 and
  the vendor's reply; without it, read the 401.

Not tried: Firefox and Safari extensions for real (their origins are from
the sources above), Edge/Brave, and the full magpie serve binary (the
harness ran the gateway's own handler stack, not its background loops).
2026-10-13 01:57:37 +08:00
yetone 60808fd9cf usage, gateway, gui: magpie's own requests are told apart from the agent's, and a classifier on a subscription says it asks it every turn (#1839)
kensenzhao saw a subscription's allowance spent by requests the agent
didn't make: a routing group's classifier, set to a subscription's model,
asks it as every turn begins, and those calls looked like the agent's own.

What changed
- usage.Group has an own share (calls, tokens, cost) of the calls magpie
  made by itself, filled for models, keys and accounts. Record.ByMagpie
  is the test: agent "magpie", or one of its own User-Agents
  (magpie-router/1, magpie-search/1, magpie-vision/1) where the agents
  aren't loaded. The calls still count in the group's totals, as they
  went to the same key or account. A group with none sends no "own".
- The classifier's calls are Kind "routing": callKind marks RouterAgent's
  requests, and the decision model's record (Jev / System One) is written
  with it. A "Routing classifier" purpose names them in the ledger.
- Usage page: magpie's row among the agents and its ledger rows carry a
  "magpie's own" mark; an account's, key's or model's row adds "{n} by
  magpie itself"; an account's card says how many of the period's
  requests were magpie's own, drawn again once the summary arrives after
  the allowances.
- Routing page: /api/groups marks a model a subscription account serves
  (modelRef.Sub, servedRef). Beside a classifier on such a model, or a
  group whose first member is one, the editor says every turn starts
  with a request to that subscription, two when it picks both intent and
  effort in words. A classifier on a key or a free model says nothing.
- New strings in zh, zh-TW, ja and de. The mark is a muted chip with an
  even border all round (no left stripe).

Tests
- TestSummaryCountsMagpiesOwnCallsApart, TestByMagpie (usage).
- TestIntentRoutesATurn and TestJevPicksTheIntent (gateway) now check
  the classifier's records are Kind routing and magpie's own, and the
  agent's records are not.
- TestServedRefSaysASubscription (gui).
- own-requests.test.cjs: Chromium and WebKit, 1100 and 390 wide,
  en/zh/zh-TW/ja/de, the API faked; no click scroll, no sideways page.
- Broken by hand, each turned its test red: addOwn counting nothing;
  callKind's routing case removed; decide.go's Kind blanked; the ledger
  mark, the agents' mark, the "{n} by magpie itself" line, the card's
  line, its redraw after the summary, the Routing hint, its group case
  and modelRef.Sub each removed.

Run: gofmt -l; go vet on darwin, linux -tags nogui and windows; go test
for usage, access, catalog, gui (-tags nogui) and gateway in full; the
GUI tests above, the ledger, routing-intent and translation tests.
Not done: the warmups (warmClaude/askClaude) write no usage record at
all, so they can't be marked; that is left as it was. Not tried with a
real subscription classifier against a live account.
2026-10-13 01:41:50 +08:00
yetone 8653bead72 usage, gui: a usage record and a request's details carry its cache read and cache creation beside in and out (#1839)
kensenzhao asked for usage.jsonl and the Usage page's request details to
carry cache read and cache creation tokens beside input and output.

What changed
- usage.Record's cache_read and cache_write are written on every record,
  0 too (they were omitempty), so a prompt that missed the cache reads as
  that rather than as a record that kept no cache. A record from before
  has neither and reads as 0, as it did. Input still holds neither.
- Every route already filled them; this pins it per wire format:
  Anthropic messages, OpenAI Chat (prompt_tokens_details.cached_tokens and
  DeepSeek's prompt_cache_hit_tokens), Responses
  (input_tokens_details.cached_tokens) and Gemini
  (cachedContentTokenCount), relayed and translated, whole and streamed,
  a plugin's fetch, and the Claude subscription bridge. System One's
  decision calls report no cache and are left as they are.
- A request's details in the ledger have a Tokens row at every width:
  "{i} in · {o} out · {r} cache read · {w} cache creation", plus the
  5-minute/1-hour split when known. Before, the cache showed only as
  "{w} written · {r} read" when non-zero, so a missed cache said nothing.
  That string is gone; the new one is in zh, zh-TW, ja and de.

Prices and quotas: the JSON tag is the only change to the record, so the
cost math (CostAt -> CostSplit reads CacheRead/CacheWrite/CacheWrite1h),
Totals' cache sums, budget's CacheReads and access/limit's token windows
read the same values as before. Checked by reading each and by the usage,
access and catalog tests passing unchanged.

Tests
- TestRecordAlwaysCarriesCacheTokens (usage): 0s written, old records read.
- TestUsageRecordsCacheTokensOnEveryRoute, TestPluginUsageRecordsCacheTokens,
  TestClaudeSubscriptionUsageKeepsCacheTokens (gateway): each wire format,
  whole and streamed.
- ledger-cache-tokens.test.cjs: Chromium and WebKit, 1100 and 390 wide,
  en/zh/zh-TW/ja/de; usage-ledger-detail.test.cjs updated for the row.
- Broken by hand: putting omitempty back and dropping the Tokens row each
  turned its test red. The gateway route tests pin what the routes
  already did; they don't fail on the code before this commit.

Run: gofmt -l; go vet on darwin, linux -tags nogui and windows; go test
for usage, access, catalog, gui (-tags nogui) and gateway in full; the
GUI tests above plus the translation tests. Not run: a real vendor
request to see its cache figures land in usage.jsonl.
2026-10-13 01:41:50 +08:00
yetone d0c587aeed gateway: a tool call a model wrote into the text of a Chat reply asked for whole is made the call it is, as a streamed one is (#1845)
A request with stream:false relayed to a Chat upstream had its reply
mended by chatWhole, which only flattened typed content (#483). The
rescue of calls written into the text (textcalls.go, #823) ran only in
textCallTidy, on a stream. So a DeepSeek reply whose content was its
DSML <|DSML|invoke name="Bash">… reached the client as that text with
finish_reason stop, and the agent ran nothing; the same request
streamed got a real tool_call (#1845, cline-pass/deepseek-v4.1-flash).

chatWhole now gets the request's tool names and, for each choice,
wholeTextCalls reads the content with the streaming parser
(textCallAt + parseTextCalls), so the same formats are taken: Hermes'
<tool_call>, DSML, the half-Hermes <parameter> form (#917) and GLM's
(#906). The text before the first block is kept (null when none), the
tags go, the calls become tool_calls with call_text_ ids and
finish_reason becomes tool_calls. As in the stream: a reply that made
a call itself, a block naming a tool not offered, arguments that can't
be read, or no tools offered leave the reply as it came; tags and
nothing else are dropped. A cheap check (tool_call or DSML in the
bytes, escaped brackets included) keeps other replies byte for byte.
chatWhole is now also used for a whole reply under text/plain or no
type, which eventStream had found isn't a stream; before, only JSON
types were mended.

Routes checked: Chat relayed whole (fixed); a streamed request a vendor
answered whole goes through chatWhole before wholeAsStream (fixed by
the same, tested); Responses and Anthropic translations of a Chat
upstream, streamed and whole, a plugin's, and a Chat request for one
body asked streamed (DashScope) all go through textCallSee already
(tests added). A relayed Responses or Messages upstream's text isn't
read for calls, streamed or whole; unchanged.

Run (Go 1.26.8, sandbox HOME, private GOCACHE):
- New TestTextWrittenCallWhole (the issue's DSML, after text, Go-escaped
  brackets, text/plain, Hermes, #823's junk, #917's param, GLM, wrapped
  invoke, two calls; left as text: no tools, unknown tool, cut short,
  lookalike, empty content, plain; tags only; beside a native call;
  truncated body; empty body), TestTextWrittenCallWholeTranslated, a
  case in TestQuietWholeReplyStreamed and a chat-whole subtest in
  TestPluginTextWrittenCall.
- Broken by hand: chatWhole without names turns 11 subtests of
  TestTextWrittenCallWhole and the TestQuietWholeReplyStreamed case
  red; leaving finish_reason alone turns them red on "finish stop";
  the old JSON-only gate turns the text/plain case red; turning
  textCallSee's rescue off turns the translated and plugin tests red.
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean. go test -tags nogui
  ./internal/gateway in full: ok (363s).
- Real: no ClinePass key here, so the reporter's request went through
  this branch's gateway in a sandbox to DeepSeek's own API
  (deepseek/deepseek-flash), 5 runs each way. One stream:false reply
  in DSML came back as tool_calls Bash {"command":"ls /tmp"},
  finish_reason tool_calls. Other runs the model wrote other markup
  (<|tool▁calls▁begin|>…, <|invoke name="Bash"|>) that neither the
  streamed nor the whole rescue reads, streamed or not; not changed here.

Not run: the full go test ./... (only internal/gateway), Windows and
Linux test runs, ClinePass itself.
2026-10-13 01:26:54 +08:00
yetone 552e974f22 gateway, gui: a classifier that can't say keeps the intent the turn before had, rather than sending the turn to the group's first member (#1826)
What: in ruleFor, when the classifier errs (an error, no answer within
classifyTimeout, an answer that isn't a number, or resting classifyRest
after a failure) and the conversation's turn before had an intent that
is still one of this turn's (Classified.After), the turn keeps it:
Classified.Intent is that intent, the new Classified.Fallback
(json "fallback") is "previous", and Error is kept. With no intent
before, nothing changes: no rule with an intent matches. The Routing
page's classWhy says "… but couldn't — {err} — so the turn keeps
“{intent}”, as turn {prev} was.", in zh, zh-TW, ja and de too.

Why: #1826 section 3: two timeouts in a row (20:54:43, 20:55:20) sent
turns of a known 复杂 conversation to the group's cheap first member.

Not done: persisting turnRules beside the sticks (the issue's idea 3).
After a restart a turn under way still waits for the next turn, with the
stick holding it meanwhile; with the previous commit the stick's key no
longer changes mid-conversation, which was how the reporter lost both.

Run: TestIntentClassifierFailsKeepsThePreviousIntent (down, then resting,
then a conversation with nothing to keep) fails with the fallback line
taken out and passes now; routing-intent-fallback.test.cjs (Chromium and
WebKit, en/zh/zh-TW/ja/de, 1100px and 390px with no sideways scroll)
30/30, and 10 of 15 red on Chromium with the old routing.js;
routing-intent-entry, routing-effort, panel-routing, routing-folder,
i18n-keys and gui-de pass; go test ./internal/gateway -count=1 green
(295s); go test -tags nogui ./internal/gui green; gofmt -l clean; go vet
on darwin (gateway), GOOS=linux -tags nogui ./... and GOOS=windows ./...
clean.
Not tried: a real classifier timing out in a live session.
2026-10-13 00:19:50 +08:00
yetone a1c30b5be9 gateway: a user message the agent wrote alone is no new turn, and routing asks about and keys on the user's own words (#1826)
What: one helper, userWords/userSaid in prompt.go, says what the user
said in a text: it drops <system-reminder …> blocks (now with a source=
attribute too, as ZCode sends) and any text that begins as an agent
writes for the model alone, and keeps only what follows the Codex app's
"## My request (for Codex):". The leads, beside agentsFor: Codex's
<environment_context>, <user_instructions>, <turn_aborted>,
<user_shell_command>, <subagent_notification>; Claude Code's and
ZCode's <task-notification>, <subagent-notification>, agent lists
("Available agent types …", "New agent types are now available …"),
TodoWrite and task-tool nudges, rewind notices; ZCode's
<plugin_reference>; the Codex app's <in-app-browser-context …>. Each
was taken from the clients' own code or a real transcript (Claude Code
2.1.296, ZCode.app's zcode.cjs, Codex CLI 0.162.1, ChatGPT.app).

Everything that asks "did the user say something" now goes by it:
- turnIn: a user message with nothing of the user's (and no image or
  file) begins no turn. After an answer or a tool round it carries the
  turn on (within), so the turn's rule and stick hold and the classifier
  isn't asked; right after the user's own message it leaves that turn as
  it began.
- userText: the classifier is asked about the last user message with
  words of the user's, only those words (it was the last user message,
  ZCode's agent list after the user's plugin question).
- firstWords (ruleKey and the affinity scope): the words of the first
  user message that has any, so an instruction file or notice the agent
  changes beside them no longer moves a conversation to a new key
  mid-turn. A conversation with no words yet keys on its first message
  as before.
- lastUserText (Copilot's Auto, a sibling): the same.
- userSays (the prompt breakdown's turns) is userWords != "".

Why: #1826 (ZCode) and @321sssrt-bit's comment (Codex): a TodoWrite
nudge was classified as a new, harder turn and sent a 常规 turn to the
复杂 member; a task notification or agent list re-classified the turn;
one ZCode session had three firstWords keys, and the turn that lost its
key fell to the group's first member.

Upgrade: a conversation whose first user message held injected text
gets a new key once (its words only), so its stick and turn rule are
looked up afresh on the first request after the upgrade.

Run: user_said_test.go (TestTurnInSkipsWhatTheAgentPutIn,
TestUserTextSkipsWhatTheAgentPutIn, TestFirstWordsAreWhatTheUserSaid,
TestLastUserTextSkipsWhatTheAgentPutIn,
TestIntentHoldsPastWhatTheAgentPutIn end to end through the server,
TestUserSaysPastAReminderWithASource) fails on the old code (all six
red with the five source files put back) and passes now; go test
./internal/gateway -count=1 green (323s); gofmt -l clean; go vet ./...
on darwin, GOOS=linux -tags nogui and GOOS=windows clean.
Not tried: a live ZCode, Claude Code or Codex session against a
group with intent rules; fixtures are the clients' literal strings.
Not done here: persisting turnRules beside the sticks (the issue's
idea 3); the classifier-failure fallback is the next commit.
2026-10-13 00:19:50 +08:00
yetone f4cc7459ea gateway: a DeepSeek step that said something before its call leads with its reasoning, so DeepSeek no longer refuses it with 400 (#1822, #1592, #1687)
Codex through magpie to OpenCode Go's DeepSeek (#1822), and to DeepSeek's
own API (#1592, #1687), was refused now and then with "The `reasoning_text`
in the thinking mode must be passed back to the API".

The cause, checked against api.deepseek.com/v1/responses on 2026-10-12:
DeepSeek reads each step (a run of reasoning, assistant messages and calls
after a user message or tool output) as one assistant message whose
thinking is the item the step starts with. In the current turn (since the
last user message), a step that has a call or follows a tool output must
lead with a reasoning item. [message, reasoning, call] and [output, message]
are refused; [reasoning, message, call] and [output, reasoning, message] are
taken. When a step had no reasoning (another model's turn, a translated
one), magpie inserted its " " reasoning right before the call, which gave
[message, reasoning " ", call]. A step with only a call worked, and only
the current turn is checked, which is why the reporter saw it come and go.

What changed:
- responses.go: withReasoningText and buildResponses now share reasonFirst.
  Each such step leads with reasoning: the step's own first reasoning item
  is moved ahead, otherwise one holding a space is put first. A sealed item
  keeps its id and encrypted_content. A body already in that shape goes
  byte for byte.
- Sibling, the same API family: an assistant reply right after a tool
  result, with no reasoning, is refused too (checked on DeepSeek's Chat and
  Anthropic endpoints). Chat (withReasoningOnToolTurns relayed, buildChat
  translated) now gives such a reply reasoning_content " ". Anthropic
  (withThinkingOnToolTurns) gives it a thinking block. Anthropic takes
  thinking anywhere in the message, so ordering is not an issue there.
- The DeepSeek fakes in the tests now model the real rules. The stricter
  Responses fake also turns TestDeepSeekGroupMemberAfterChatGPT red on the
  old code: its "an assistant note" case is this bug, which the old lenient
  fake hid.
- docs/subsystems/gateway-routing.md: the Responses, Chat and Messages
  replay paragraphs.

What was run:
- New tests: TestDeepSeekStepSaysBeforeItsCall covers the reporter's shape
  across OpenCode Go, DeepSeek and a group, streamed and not. Also
  TestWithReasoningTextLedStepsUnchanged,
  TestTranslatedDeepSeekStepLeadsWithReasoning,
  TestChatReplyAfterToolGetsReasoning and
  TestAnthropicReplyAfterToolGetsThinking. All but the unchanged-body test
  fail on the old code.
- gofmt -l; go vet ./... on darwin, and with -tags nogui on linux and
  windows; go test ./internal/gateway.
- Real API: direct requests to api.deepseek.com (Responses, Chat,
  Anthropic) with the old and new shapes, as listed above.

What wasn't:
- OpenCode Go's own endpoint: the test account is refused with "This Go
  model requires Global regions", an account setting, so its fix rests on
  it relaying DeepSeek's rule unchanged (the reporter's error text is
  DeepSeek's).
- A built magpie end to end against the real API.
- Other thinking vendors (Kimi, GLM) were not checked for the same step
  rule. Their paths are unchanged.
2026-10-13 00:08:23 +08:00
yetone 7d9382db23 gateway, settings: an unreadable settings.json keeps the allow list read last, or lets in only this computer, never every address
Follow-up to 7a9490638. AllowIPs read settings.Load().AllowIPs, and Load
returns the defaults when settings.json can't be read or doesn't parse with
no good backup, so for those requests the allow list read as empty and
every address was let in (fail-open). A failed read is unknown, never
empty (LESSONS.md).

- settings: LoadChecked() returns Load's settings and an error when the
  file is there but can't be read, or doesn't parse with no last good
  generation, the same cases Save already refuses. No file, or an empty
  one, is not an error. Load is unchanged and now goes through the same
  reader.
- gateway: the Settings list is read with LoadChecked. On an unknown read
  the list read last in this process stays in force; with none read yet,
  only loopback and this computer's own addresses pass, and the 403 says
  settings.json in <dir> couldn't be read. Logged once until a read
  succeeds. MAGPIE_ALLOW_IPS is unaffected. AllowIPs returns the list in
  force (the last one read on an unknown read).
- gui: POST /api/settings and POST /api/settings/allowips read with
  LoadChecked and refuse on an unknown read. settings.Save already
  refused to write over such a file, so this didn't write an empty list
  before either; the handlers now refuse before building on defaults.
- docs: reference.md and gateway-routing.md say so.

Run (darwin, sandbox HOME/XDG via the tests' own setup, private GOCACHE):
- gofmt -l on the changed packages: empty.
- go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...: clean.
- go test -count=1 ./internal/settings ./internal/gui ./internal/gateway: ok.
- Broken by hand: allowList reading settings.Load() with no error makes
  TestAllowListUnreadableSettings fail (garbled after a read: 203.0.113.9
  got 200, want 403; never read: remote got 200, want 403 saying
  settings.json). LoadChecked never erroring on a parse failure makes
  TestLoadChecked fail ("garbled with no backup read as good") and the
  gateway test fail at its precondition.
- TestAllowIPsUnreadableSettingsNotSavedOver passes on the old GUI code
  too (Save refused already); it guards that path.

Not run: the Windows box, Linux tests, the GUI Playwright suite (no
assets changed), the full go test ./... . Not covered: an empty
settings.json with no .bak still reads as no list, matching Save, so a
file truncated to zero bytes before any second save opens a freshly
started magpie.
2026-10-12 23:38:50 +08:00
yetone 7639c1d8db gateway, gui: a web search made in place of the picked searcher says in its Routing row which searcher failed or found nothing, and why (Gearclickist on Discord)
Gearclickist picked Grok as the web-search model (代搜). In Codex, a
web_search did go to Grok, but Codex's default search model then searched,
and nothing said why. modelSearch asks the searcher picked in Settings
first. When it errors, or its reply names no page it found, the next of
Searchers() searches in its place (#669, up to three). The first error was
dropped, so the Routing row only showed the model that answered.

Falling back stays. searchingInstead now puts on the search's CallFor the
searcher asked first (instead), whether the user picked it (picked), and
its error (why) or that it found nothing (nothingFound, from a new
errFoundNothing that searchWith and kimiSearch wrap). Routing's kindWhy
says "<grok>, the searcher picked in Settings › Models › Web search,
didn't search for Codex's <model>: <why>. So magpie had <next>, the next
searcher it can use, search in its place." There are 7 new strings, in
zh, zh-TW, ja and de.

Grok itself: magpie's exact search body was sent to real Grok (4 models,
6 queries) through the built-in, and replayed through the plugin. Every
time it answered with pages, so no Grok or plugin cause was found, and
there is no plugin publish or mover min raise. The next time Grok fails
for Gearclickist, the row now names the error.

Run:
- go test ./internal/gateway ./internal/agent -count=1 under a sandbox
  HOME: ok (933s, 720s).
- TestSearchInPlaceOfPickedSaysWhy (found nothing, failed) passes. With
  the searchingInstead call taken out by hand, both subtests go red.
- search-instead.test.cjs: chromium and webkit, en/zh/zh-TW/ja/de, at
  1100 and 520px: 10/10 pass. With kindWhy's new branch turned off by
  hand: red.
- search-mcp, routing-side-calls, provider-search and routing-kind GUI
  tests pass.
- go vet on darwin, GOOS=linux -tags nogui, and GOOS=windows; gofmt -l
  is clean.

Not verified: a real Grok search failing for Gearclickist's account,
since it couldn't be reproduced.
2026-10-12 23:30:08 +08:00
yetone 7a9490638d gateway, gui, settings: an IP / CIDR allow list for the gateway, from MAGPIE_ALLOW_IPS or Settings beside Share on local network (lc on Discord)
What changed: lc runs magpie in Docker on a public host and asked that
only some addresses reach it at all. With a list set, a request from an
address outside it is refused 403 ("magpie answers only the addresses on
its allow list ..., and this request came from <addr>: add it there to
let it in") before its gateway key is looked at, so a leaked key is no use from
elsewhere. No list is as before.
- internal/settings/allowips.go: SplitAllowIPs, ParseAllowIP (an IP or a
  CIDR range, v4 or v6; zones dropped, v4-mapped unmapped), CleanAllowIPs.
  Settings gets AllowIPs (allowIPs).
- internal/gateway/allow.go: MAGPIE_ALLOW_IPS (comma or space separated)
  sets the list in place of Settings'. The address judged is the
  connection's own (r.RemoteAddr); X-Forwarded-For and the rest are never
  believed (magpie has no trusted-proxy list; MAGPIE_TRUST_PROXY never
  reads forwarding headers, and this follows it). Loopback and this
  computer's own interface addresses always pass. An entry that doesn't
  read lets nothing in and is logged once, so a typo never opens magpie
  to every address. lanGuard checks it after the OAuth callback and
  before the rebound-Host and key checks; `magpie web` is wrapped with
  AllowGuard too.
- GUI: Settings > Network shows an "Allowed addresses" row under Share on local
  network when sharing is on, the page is open from another computer, or
  the env var is set (then read-only, saying so). POST
  /api/settings/allowips saves it, refuses it while the env var is set,
  refuses an entry that doesn't read, and refuses a list that would shut
  out the address the page itself is open from (KeepsOut). The generic
  settings save keeps AllowIPs. Strings in zh, zh-TW, ja and de.
- Docs: the Docker page (en, zh, ja) lists MAGPIE_ALLOW_IPS with a note
  that a request from the host itself arrives from the bridge's gateway
  (172.17.0.1), that Docker Desktop and rootless Docker show clients as
  one address of their own, and that behind a proxy every request comes
  from the proxy; docs/reference.md and docs/subsystems/gateway-routing.md
  describe it. The READMEs list no env vars, so they are unchanged.

Why: a gateway key is the only lock on a public host; an allow list keeps
everyone else from even trying it.

Run (machine load average 75-140 from other sessions, so the large
packages ran in slices of their top-level tests, each slice
-timeout 9m, private GOCACHE, sandbox HOME):
- New tests: internal/gateway/allow_test.go TestAllowList (allowed,
  denied, CIDR v4/v6, IPv6 literal, link-local with zone, v4-mapped,
  loopback and own address always in, on the list still needs a key,
  a typo shuts everything out, env over settings), TestAllowListServed
  (a real connection from loopback passes lanGuard under a list naming
  nothing of this computer's; a request from elsewhere is 403 naming its
  address and MAGPIE_ALLOW_IPS), TestKeepsOut; internal/settings/allowips_test.go
  TestCleanAllowIPs; internal/gui/allowips_settings_test.go
  TestAllowIPsSetting; internal/gui/tests/allow-ips.test.cjs (14/14 in
  chromium and webkit, at a 390px panel, en and zh, keys in zh, zh-TW,
  ja and de). Broken by
  hand: with lanGuard's check removed TestAllowList and TestAllowListServed
  FAIL; with KeepsOut skipped TestAllowIPsSetting FAILs; with renderAllow
  not called the GUI test has 5 failures. Restored, all pass.
- internal/gui/settings_keep_test.go gains AllowIPs:
  TestSettingsSaveKeepsWhatItDoesNotSend failed without it, as it should
  for a new field.
- go test -tags nogui: every package ok. internal/gateway (4 slices),
  internal/agent (4), internal/provider (3), internal/gui (2),
  internal/plugin (2), the rest whole. GUI Network-settings test files
  (11) 98/98 and i18n-keys ok, both engines.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... ok; linux and windows builds ok.
- Not tried: a real Docker container on a public host (the bridge note
  is from Docker's docs, not checked here); behind a real reverse proxy.
2026-10-12 23:21:41 +08:00
yetone 908c910931 gateway, gui: Stays: Strict keeps a conversation on the account or key that answered it, even past its cap, and passes its error on rather than moving it (#1797)
miniers asked that a conversation never move to another account: a
move changes the account a vendor sees mid-conversation and loses its
prompt cache. Session affinity keeps the account while it can answer,
then moves on.

The new affinity mode "strict" (Stays: Strict) does what session does
for a new conversation. Once one has an account, strictKeep asks that
account alone (its other models too) and no other account, key or
provider:
- one resting or spent is still asked, and its error (429, 402, 5xx)
  goes to the agent rather than to the next candidate;
- one over a user cap is asked past it (plan's capped candidates,
  capHeldOnly);
- one held for credits answers 429 naming Stays: Strict rather than
  moving;
- one removed, turned off, barred or not allowed for the key counts as
  gone, and the conversation is routed as usual.
A last try that fails verification is not rested for a strict
conversation that had nowhere else to go.

Set in the provider editor and the Routing page's pool row (GUI, all
five languages), `magpie groups ... stays=strict` (strict-session,
never-move), and the TUI ("stays strictly"). Documented in
gateway-routing.md, reference.md and the site's start pages (en, zh,
ja).

Run:
- go test -tags nogui ./internal/gateway (-timeout 30m under load ~150),
  ./internal/provider ./internal/tui ./internal/cli: ok. The three
  TestStrictAffinity* tests fail on the code before this commit (200
  where 429 was expected, acct-2 answering).
- GUI: stays-strict.test.cjs, chromium and webkit, 900 and 560px, en,
  zh, zh-TW, ja, de: 30 of 30. On the assets before this commit it
  fails 15 of 15 in chromium. routing-*.test.cjs pass but for
  routing-steady's webkit 1.69px shift, which fails on the old assets
  too: filed as #1804.
- gofmt -l, go vet (darwin, linux, windows), full go test ./... before
  the push.

Not tried: a real agent conversation held on a real rate-limited
account.

Known and left: planLevel doesn't merge a nested group's sub.held, as
before this commit.
2026-10-12 23:16:54 +08:00
yetone 1b8f674aaf gateway: a WorkBuddy model searches the web with WorkBuddy's own search service, so Claude Code's WebSearch on it gets results (#1798, lemonwater379)
What was wrong: WorkBuddy's models have no search tool of their own.
When magpie had nothing else that searches (no Claude or Codex account,
no search API), canSearchFor was false. magpie then took the
web_search_20250305 server tool out of Claude Code's WebSearch request,
the model answered from nothing, and WebSearch showed no results.
WorkBuddy's own client searches through a service of its plan.
Its CLI's WebSearch tool (WorkBuddy.app's
app.asar.unpacked/cli/dist/codebuddy.js, WEB_SEARCH_API_PATH) sends
POST <site>/agenttool/v1/search with
{"query","type":"text2text","max_results":5}.

What changed:
- search_workbuddy.go: wbSearch asks that service. Provider.Sign
  signs the request as the plan's chats are signed, and Provider.Do
  sends it, so it works the same for the built-in and for a WorkBuddy
  moved onto its plugin (the plugin's fetch signs it, as for
  /v3/config and images). No plugin change is needed.
- searchesOwn includes a WorkBuddy plan, as it does a Kimi Code plan.
  Its own models' searches go there first, before magpie's picked
  searcher and the search APIs. Other providers' models never use it.
  It is off when provider search is off in Settings.
- A {code, msg} refusal (15001 is its search quota) is reported as an
  error, not as an empty result.
- docs/subsystems/gateway-routing.md: new section, tests added to
  Verification.

What was run:
- The real service, read-only, with the owner's desktop sign-in (China
  build) and the plugin's WorkBuddy AI sign-in. Both answered 200 with
  results, including with only the built-in's smaller header set. The
  test fixture is WorkBuddy AI's real reply bytes.
- End to end with the real China-build account: a throwaway program
  (not committed) under a sandbox HOME holding a copy of the desktop
  sign-in. It sent Claude Code's literal WebSearch request through
  gateway.New().Handler() to workbuddy/deepseek-v4.1-flash and got 200
  with one web_search_tool_result block holding real URLs.
- New tests: TestWorkBuddySearchesForItsModels (built-in, Claude Code
  2.1.285's literal request) and TestWorkBuddyPluginSearches (plugin).
- Broken by hand (wbSearches returning false): both go red. The
  built-in test's reply is the model's "I can't search." with no
  web_search_tool_result, which is the reporter's case.
- go test ./internal/gateway -run 'Search|WorkBuddy|Kimi|Vision|Spent|PassesOver'
- gofmt -l, go vet ./... (darwin), GOOS=linux go vet -tags nogui ./...,
  and GOOS=windows go vet ./... are all clean.
- Full go test -timeout 40m ./... in a sandbox HOME at load 66-100:
  47 packages ok. internal/gateway and internal/agent hit the 40m
  package timeout. Gateway also had failures, each filed:
  - TestOTelWaterfall* (#1794, fixed on main since).
  - TestCodexHeardWithinItsIdleTimeout (#1800).
  - TestIntentClassifierGroup (3.17s against a 3s bound, filed as
    #1813).
  All of them pass alone, and go test ./internal/gateway on its own is
  ok (982s).

Not verified: WorkBuddy AI end to end through the gateway (its desktop
sign-in in the sandbox wasn't picked up; the service itself answered).
Not tried through a running magpie app with the plugin installed.
2026-10-12 23:04:29 +08:00
yetone b5d7f0574c gateway: image recognition and web search that magpie picks pass over a model out of its allowance, and ask none when every one is out (#1801, hibaliqya-yonma)
What was wrong: AutoVision (the model that describes images for models
that can't see) and autoSearcher (the model that searches for models
that can't) pick a provider and model before routing runs. They never
looked at routing's allowance state. That state covers accounts barred
at a usage cap, rests for quota or credit, and full key or subscription
windows. Routing then had one candidate and tried it all the same. Each
image or search was sent to the account that had run out and got the
same 429 again, while another provider with allowance sat unused.

What changed:
- fallback.go: spentModel(p, model, from, now). A model is spent when
  every candidate routing would try for it (perKeyBarred) is capped,
  resting for quota or credit, or has a full window (candidate.full,
  model-aware for pools). It also says when the first one is back. A
  rate rest doesn't count.
- search.go: smallModel goes through smallReady, which prefers models
  that aren't spent (pickSmall keeps the old choice among them).
  autoSearcher ranks a searcher with allowance before searchRank.
  modelSearch doesn't ask a spent searcher that magpie picked
  (searcherSpent), tries the others with allowance first, and adds why
  it skipped to its error. A searcher named in Settings is asked as
  before.
- vision.go: AutoVision ranks ready first, then tier and cost. When
  every describer is out it still names one, so seer and Described
  (which tell agents every model takes images) don't flip with a
  window. askVisionWith (gateway and MCP) answers an auto describer
  that is spent with the reason and when it is back, and doesn't call
  upstream. A describer named in Settings is asked as before.
- Image and video generation (AutoDrawer, AutoVideomaker) are left
  as they were.
- docs/subsystems/gateway-routing.md: new section, tests added to
  Verification.

What was run:
- New tests in side_spent_test.go: TestAutoVisionPassesOverOneOut,
  TestAutoVisionTierAmongThoseWithAllowance,
  TestSpentModelAcrossAccounts, TestVisionDoesNotAskSpentDescriber and
  TestSearcherPassesOverOneOut.
- Broken by hand three ways:
  - spentModel returning false: all five go red.
  - Only autoSpent's check in askVisionWith removed:
    TestVisionDoesNotAskSpentDescriber goes red (200 from upstream).
  - Only modelSearch's skip removed: TestSearcherPassesOverOneOut goes
    red.
- go test ./internal/gateway -run 'Search|WorkBuddy|Kimi|Vision|Spent|PassesOver'
- gofmt -l, go vet ./... (darwin), GOOS=linux go vet -tags nogui ./...,
  and GOOS=windows go vet ./... are all clean.
- Full go test -timeout 40m ./... in a sandbox HOME at load 66-100:
  47 packages ok. internal/gateway and internal/agent hit the 40m
  package timeout. Gateway also had failures, each filed:
  - TestOTelWaterfall* (#1794, fixed on main since).
  - TestCodexHeardWithinItsIdleTimeout (#1800).
  - TestIntentClassifierGroup (3.17s against a 3s bound, filed as
    #1813).
  All of them pass alone, and go test ./internal/gateway on its own is
  ok (982s).

Not verified: not tried with a real account that has run out. Windows
was only vetted.
2026-10-12 23:04:29 +08:00
yetone 50eeaae6ce gateway: a turn that names no reply limit is sent the model's own as max_tokens on Anthropic's API, not a flat 16384 (#1792, tensornull)
Anthropic's Messages API needs max_tokens. A request that names none
(Codex's Responses turns, a Chat client's) was always sent 16384, so a
long thinking and tool turn on a Claude-shaped relay hit the limit, and
Codex showed "Incomplete response returned, reason: max_output_tokens".

Now such a request is sent askedOutput(p, model). That is the plain
Served entry's PublishedOutput(), the same number the agents are told:
the user's Max output first, else the vendor's list or models.dev,
within the window. 16384 (defaultMaxTokens) is used only when nobody
knows the limit. A limit the client names still goes as it is. The
thinking budget is still fitted under max_tokens (anthropicBody),
whatever the limit is.

Both places that build an Anthropic body are covered:
forwardTranslated, for every translated route, and serveZed for a Zed
subscription's Claude models.

The provider editor's Max output hint now says this number is also
sent as max_tokens (en, zh, zh-TW, ja, de). docs/reference.md and
docs/subsystems/gateway-routing.md no longer say the gateway never uses
the limit.

Run:
- TestAnthropicMaxTokensIsTheModels covers: the user's 65536 (Responses
  plain and streamed, and Chat), models.dev's 64000, a 500000 limit
  held to the 100000 window, an unknown model at 16384, the client's
  own 1000, and thinking under 8192.
- TestZedClaudeMaxTokensIsTheModels expects 40000 when the client names
  no limit and 1000 when it does.
- Both tests fail on the old code: 16384 where the model's number was
  expected.
- go test ./internal/gateway/ passed (1270s, under load).
- provider-max-output.test.cjs passes 28/28 in chromium and webkit:
  5 languages at 900 and 420px. The hint names max_tokens and
  Anthropic, is translated, and doesn't overflow.
- gofmt -l is clean. go vet passes on darwin, on linux with -tags
  nogui, and on windows.

Not tried against a real Anthropic-compatible relay with a real Codex
session.
2026-10-12 22:44:26 +08:00
yetone 556c01c803 gateway: a provider that refuses auto mode's safeguards is asked again without them and not sent them again, so Copilot's claude-opus-5.5 answers Claude Code (#1756)
Pylogmon's Claude Code on Copilot's claude-opus-5.5 got 400
invalid_request_error "Copilot: safeguards: Extra inputs are not
permitted" on every turn, which magpie labels "request format not
accepted". Their Sonnet worked. Claude Code's auto mode adds a
top-level `safeguards` field for the API's review of its actions.
magpie passes it on to any Claude model (automode.go), and Copilot's
Messages API checks its fields strictly and turns the field away.

The fix uses the existing class for Claude Code's newer fields that a
relay refuses (anthropic_shapes.go: thinking.display, a turn's
output_config). On a 400 naming `safeguards` with "Extra inputs are
not permitted", forward asks again at once without the field and
remembers that the provider refuses it (shapeSafeguards), so later
requests leave it out the first time. Claude Code, finding no
safeguard_results, reviews its actions locally, as it does for every
non-Claude model. The fix sits in forward/forwardOnce, so it reaches
every route to an Anthropic endpoint: relayed and translated
(buildAnthropic), any provider, not only Copilot.

What was run:
- TestSafeguardsRefusedLeftOut (refusal text as the reporter quoted
  it): on the old anthropic_shapes.go the agent gets the same
  "Cop: safeguards: Extra inputs are not permitted" 400; now it gets
  200, asked twice the first time and once after that.
- TestSafeguardsKeptWhereTaken: a provider that takes the field
  still gets it.
- The shapes, system-message and auto mode tests pass.

Not verified: no Copilot account with claude-opus-5.5 was available,
so Copilot's raw error body is assumed. The match is on the words the
reporter quoted, which magpie shows after "Copilot: ".
2026-10-12 22:42:47 +08:00
yetone af7d97fa2f gateway: a Responses provider set codex=as-sent gets Codex's requests as Codex sent them, for a relay that checks they are Codex's own (#1758)
A relay that checks a request is Codex's own answered magpie 400
"Codex 客户端请求特征无效" (10014). magpie fits every Codex request
for a Responses backend that isn't OpenAI's: Responses Lite's
additional_tools item is lifted into tools (#350), the tool search
goes as a function, and OpenAI-only fields such as
stream_options.reasoning_summary_delivery are left out. The reporter
found that the relay takes the request when additional_tools is left
as an input item, and that the lifted shape is what it refuses.

The lifting stays the default, because backends that aren't OpenAI's
refuse additional_tools or silently drop it (#350). A provider can now
opt out: `magpie provider set <id> codex=as-sent` (`codexAsSent` in
providers.json; `codex=default` turns it back off). With it on, a
request from Codex (fromCodex: Codex's User-Agent or originator) goes
as Codex sent it, with only its model name swapped. Codex's own
headers go with it as before. A subscription account is never sent
this way, and the GUI's provider save keeps the setting.

What was run:
- TestCodexAsSent: by default the request is still fitted; with
  codexAsSent the upstream gets exactly what Codex sent, with model
  m1, X-Codex-Turn-Metadata and the Responses Lite header. It fails
  on the old gateway.go and passes now. TestAdditionalTools and the
  gateway's Codex tests pass.

Not verified: not tried against the reporter's relay. Their check
was made by hand outside magpie, so which other fields that relay
looks at is not known. There is no GUI control for the setting
(CLI or providers.json only).
2026-10-12 22:42:47 +08:00
yetone cb40e26ec2 gateway: a refusal's note keeps Anthropic's stop_details category and explanation, on the Routing page's try and in the agent's error (#1768)
jingchangshi's sessions got "claude-opus-5-5 refused this request (safety
filter: refusal) via Claude Code" 19 times, with nothing to say which of
Anthropic's classifier categories (cyber, bio, frontier_llm,
reasoning_extraction, general_harms…) it was. Anthropic sends that in
stop_details beside stop_reason "refusal"; magpie read only stop_reason.

Rather than the separate opt-in JSONL sink the issue proposes, the
category goes where every refused attempt is already recorded: the note
of that try on the Routing page, including a try a later key or group
member answered after, and the error the agent gets when nobody is left.
It is the vendor's own words, so nothing of the user's request is stored
anywhere new.

What changed:
- refusedDetail: "safety filter: refusal (category cyber: <explanation>)",
  the explanation whitespace-folded and cut at 200 characters; a null or
  missing category or explanation adds nothing, an unknown category is
  kept as given. Used for a streamed message_delta and a whole reply.
- stop_details is carried through the IR (Event.StopDetails,
  Result.StopDetails) from an Anthropic upstream's stream and from the
  claude CLI's stream-json (a Claude subscription), and written back into
  an Anthropic client's message_delta or whole reply, as
  safeguard_results already is.

What was run:
- TestRefusalKeepsStopDetails (stream, whole, nulls, absent, unknown
  category, long explanation), TestRefusalCategoryOnTheTry (refused key
  then an answering one: the refused try says "category cyber") and
  TestClaudeSubscriptionRefusalMovesToNextAccount (now with stop_details
  in the CLI's refusal) fail on the old code and pass now; the refusal,
  safeguard and Anthropic tests pass.

Not verified: no real Anthropic refusal with stop_details seen (the
bytes follow Anthropic's documented shape); a Codex or Chat client
served by Claude gets the category on the try only when the hold
writer sees it in its own protocol, which Responses and Chat have no
field for, so their try notes stay "safety filter: …" as before.
2026-10-12 22:42:46 +08:00
yetone ff930886a2 gateway: keys all out of their allowance are answered from their rests with a Retry-After, not asked again on every request, and a key listed twice is asked once (#1772)
A fleet on four Ollama Cloud keys, every one out of its weekly allowance:
each new request asked every key again (the first twice) and answered
429 with no Retry-After, so an agent that waits as told asked again at
once, and the vendor saw four refused requests a turn.

What changed:
- The first key twice: the reporter's providers.json named the first key
  in "keys" as well as "key". KeysOn now lists a key once.
- When every key left for a request rests out of its allowance (a 429 or
  402 that failure() calls quota or credit, keys only), the request is
  answered from the rest without asking: the vendor's own words, "not
  asked again before HH:MM", and Retry-After until the first of them is
  back (quotaHeld, soonestBack). Accounts are left out, so autoReset
  can still spend a reset for them; a 403 or 400 worded as quota is
  asked as before.
- The last key out of its allowance now rests as the ones before it do
  (before, the last one left was never rested), and a 429 the vendor gave
  no Retry-After for gets the soonest rest's end as one.
- A provider can set how long its keys rest when the vendor says nothing
  of when the allowance is back: quotaRest (minutes) in providers.json,
  or `magpie provider quota-rest <id> 7d`; default stays 15 minutes, at
  most 8 days. A time the vendor names (resets_at, Retry-After, a
  window) still wins. A GUI save keeps it.

What was run:
- TestAllRestingAnswersFromRest, TestFirstKeyListedTwiceAskedOnce and
  TestOwnQuotaRest fail on the old code (no Retry-After, keys re-asked;
  "dead-1 dead-1 dead-2 ok-3", the reporter's log); they pass now, with
  TestQuotaHeldOnlyForKeysOutOfAllowance, TestDeadChainWalksEachOnce and
  TestRestMinutes. The mock answers with the reporter's literal 429 body.
- go test -tags nogui ./internal/provider ./internal/gui pass. A gateway
  package run at load ~60 hit its 20m timeout mid-suite with only
  TestMaxRPM* red; those pass 8/8 alone here and on origin/main
  17c12621b (timing under load, filed as #1791).

Not verified: no run against real Ollama Cloud keys; quotaRest has no
field in the provider editor (CLI and providers.json only).
2026-10-12 22:42:46 +08:00
yetone f2400f679b gateway: another model's reasoning_details goes to Kimi as reasoning_content, so a conversation MiMo began is no longer refused 400 on every turn (#1765)
What changed: a Chat request to Kimi (isKimi: the Kimi platform's or a
Kimi Code membership's host or preset) has each message's
reasoning_details left out, its thinking put in reasoning_content when
the message has none (reasoningDetailsAsContent). refusedInMessages also
reads Kimi's own wording, "the <field> at position N", so another
upstream that refuses the field that way (a relay in front of Kimi) is
asked once more without it and marked; the retry and the remembered mark
keep reasoning_details' thinking as reasoning_content too
(withoutMessageReasoning).

Why: Leo-origin's session was answered by MiMo through Command Code,
whose reasoning_details entries carry a stream's index; pi sends them
back, and Kimi Code answered 400 "the reasoning_details at position 2
entry 0 must not contain streaming index" on every turn. Probed against
the real api.kimi.com/coding/v1 on 2026-10-12: Kimi refuses
reasoning_details in every shape tried (with index: "must not contain
streaming index"; reasoning.text, reasoning.summary, reasoning.encrypted,
text, thinking without it: "has an invalid type"), and passes
reasoning_content, reasoning and an empty list through validation.

Run: TestKimiGetsReasoningDetailsAsContent and
TestReasoningDetailsRefusedAtPosition (fake Kimi answering with the
probed bytes) fail on the old gateway.go/chattidy.go: 400 "Kimi Code
(China): the reasoning_details at position 1 entry 0 must not contain
streaming index" after 1 call, the reporter's message, and "400 after 1
calls (want 2)". They pass with the change, as do TestMistral*,
TestMessageReasoning* and the other *Reasoning* tests.

Not verified: a real k3 reply through magpie; the owner's Kimi Code
subscription has lapsed, so the real probe reached only validation
(a valid request got 403 "does not have access"). A 400 magpie doesn't
recognize still ends the request rather than failing over; that is
unchanged.
2026-10-12 22:42:45 +08:00
yetoneandggbdpq c59b808c99 gateway: an MCP request longer than its route takes is refused whole with 413, not run as the part that fit (#1766)
What changed: serveMCP (magpie's own web-search and vision MCP servers)
and the signed-in MCP proxy (/mcp/{name}) read the body through
readMCPBody, which reads one byte past the limit and answers 413 when the
body is longer, or when Content-Length already says so. Before, a plain
io.LimitReader ended at the limit as if the body had, so a valid JSON-RPC
message padded with whitespace past the limit, or followed there by a
second message, was parsed as its prefix and run: an analyze_image call
reached the image model, and the proxy sent the cut body on to the
signed-in server with the user's token. A body exactly at the limit still
works.

Why: #1766 (ggbdpq) reported it for the two own MCP routes with a patch;
the proxy's read was the same shape and is fixed beside them.

Run: TestOwnMCPRejectsOversizedBody (the reporter's test, extended to a
known Content-Length too) and the new TestMCPProxyRejectsOversizedBody
fail on the old search_mcp.go/mcp.go with HTTP 200 instead of 413, the
image model called 1 -> 5 times, and the proxied server seeing the cut
"tools/call"; they pass with the change. TestMCPProxy*, TestVisionMCP*,
TestSearchMCP* pass. Full suite and vets are recorded on the push.

Not done: the GUI's local /api handlers decode JSON through LimitReader
too; they take only the first JSON value whatever the length and are
not reachable by another machine, so they are left as they are.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-12 22:42:44 +08:00
yetone 974aaf7e22 gateway: an account out of credits on a model that costs them still serves its subscription's free models (Creat.wu on Discord)
Creat.wu (WorkBuddy AI) spent the credits on glm-5.3-flash, switched to a
free model, and magpie skipped the account. An out-of-credit refusal
rested the whole account (restKey) for 30 minutes: through the WorkBuddy
plugin, whose `explained` passes 14018 on as insufficient_quota, and on the
built-in, whose raw 429 {"error":{"data":{"code":14018,"msg":"Credits
exhausted…"}}} matched no credit word and was read as a rate limit, the
account benched a minute and longer on repeats.

- provider.PaidBesideFree: the model costs credits while the subscription
  lists others Free (catalog.Model.Free: WorkBuddy's x0.00, Qoder's
  is_free, Cline's free models, Command Code's).
- restAfterMarked: out of credit or quota on such a model rests that model
  alone (restID). A free model the vendor still refuses (WorkBuddy refuses
  0-rate models to an account with no package) rests the account on its
  own refusal, as before.
- brokeWords takes "credits exhausted", so the built-in's 429 is out of
  credit, not a rate limit. A rate limit naming credits in passing stays one.
- The fix is in the gateway, which both moved (plugin) and built-in users
  go through, so no plugin release or mover min is needed.
- docs/subsystems/gateway-routing.md says so, with the tests to run.

Tests: TestCreditsExhaustedIsOutOfCredit (literal 14018 body, raw and as
the plugin passes it) and TestOutOfCreditLeavesFreeModels (fake plugin,
two keys, deepseek-v4-pro answered 429 with the plugin's body, then fake-1
must go to the first key). With the restAfterMarked change taken out the
second fails (fakeco@api key rested 30m for credit); with brokeWords back
as before the first fails (rate, want credit). Both pass with the fix.

Not done: credit windows still count free models in Smart/Pace order and
the 98% affinity stop; the account isn't held out there (Credits has no
reset, so Full is 0), only ordered later. Not tried with a real WorkBuddy
AI account. gofmt, vet and the full suite: see the next commit's body.
2026-10-12 22:33:07 +08:00
yetone 24350a3722 agent, gateway: Claude Code on a model Anthropic doesn't review gets auto mode's server review turned off, so it no longer says magpie isn't eligible (1EFLOPS on X)
1EFLOPS runs Claude Code through magpie on Codex's gpt-6.1-sol. In auto
mode, Claude Code 2.1.296 says "this session isn't eligible because your
requests go through 127.0.0.1:3425 ... ask your gateway to implement
https://code.claude.com/docs/en/auto-mode-classifier-billing".

What the page asks of a gateway: pass the anthropic-beta header
(dangerous-tool-use-2026-09-03), the request's `safeguards` field, and
`safeguard_results` in the reply through unchanged, and leave tool-use ids
alone. The results are verdicts from Anthropic's own safety classifier.
For a gateway that can't provide them, the page's remedy is
CLAUDE_CODE_AUTO_MODE_SERVER=0. Pro, Max and Team plans never see the
notice. In the bundle, Claude Code falls back on server_unsupported,
server_unavailable_disabled or server_no_result, and the notice shows
whenever there's no real verdict. Only that variable removes it.

Per route:
- Claude subscription bridge, Anthropic API key, relays in front of
  Anthropic, Bedrock and Vertex: already pass the beta, `safeguards` and
  `safeguard_results` through (e8cd4bac8, 8c21a4184). This commit doesn't
  change them. serverReview now uses the shared AutoModeReviewed rule
  (adding the subscription account, which never reaches serverReview).
- Codex/OpenAI and every other non-Claude model: magpie can't answer
  honestly. A verdict would be made up, and "unsupported" still shows the
  notice. So magpie answers nothing on Anthropic's behalf. Instead the
  Claude Code wiring writes env.CLAUDE_CODE_AUTO_MODE_SERVER="0" to
  settings.json. It does this only while Claude Code is routed through
  magpie and no model it can reach there is reviewed. That means checking
  the models shown to Claude Code (and Claude Desktop's while Desktop is on
  magpie), a shown group's members, those providers' fallbacks, and the
  models it is set to (claudeReviewed). If any one is reviewed, the
  variable stays unset, because /model can move the session onto it (the
  reason 8c21a4184 didn't write it at all). The value is rewritten on every
  model set and Sync, so adding a Claude provider turns the review back on.
  It is stash-tracked (claude.auto_mode_server): a user's own value is left
  alone, and magpie's goes on Disconnect, reset or a move off magpie.
- T3 Code (sibling): its magpie instance runs Claude Code on the gateway
  through its own environment, so it gets the same "0" by the models it
  lists.
Not covered: Claude Desktop's Code tab while Claude Code itself isn't
routed through magpie. Desktop users are on Pro/Max/Team, which never see
the notice.

Tests (each fails with its part of the change broken by hand):
- TestClaudeAutoModeReview: off on a non-Claude model; on with a Claude
  model shown, in a group or as a fallback; the user's "1" and "0" kept;
  dropped on reset and on a move to Claude Code's own model.
  A group that keeps its models out of the lists (#1783, Unlists) still
  routes to them, so its Claude member counts: members come from what is
  served, not from the catalog.
- TestT3CodeAutoModeReview.
- TestAutoModeReviewedRoutes: subscription, api.anthropic.com, relay,
  Bedrock and Vertex spellings yes; Codex, DeepSeek's Anthropic API,
  openai/gpt-6 and claudette no.
Mutations that went red: skipping group members, skipping fallbacks,
skipping an unlisting group, overwriting the user's value, not dropping it off magpie, always writing
it, the T3 env always or never, and the subscription not counted.

Real Claude Code 2.1.296, sandbox HOME/CLAUDE_CONFIG_DIR, magpie serve on
127.0.0.1:3591 under a scratch HOME, fake upstreams on 3593 (OpenAI Chat)
and 3594 (Anthropic):
- Before, on fakeai/fake-gpt, -p --permission-mode auto: the notice is on
  stderr (2 of 2 fresh config dirs). With the env in settings: none.
- With this build, `magpie claude fakeai/fake-gpt` wrote the "0", and a
  fresh run shows no notice. The same settings without it show the notice.
- `magpie provider add fakeanth anthropic=... models=claude-sonnet-5`:
  Sync took the "0" out. `magpie claude fakeanth/claude-sonnet-5` and a run
  in auto mode: the upstream got the dangerous-tool-use beta and
  `safeguards` on both turns, answered not_flagged in message_delta, and
  there was no notice.
Not tried: the Claude subscription bridge with a real account (its plans
don't see the notice), and a real Codex account (a fake Chat upstream
stood in for it).

Run: gofmt -l; go vet -tags nogui ./... for darwin, linux and windows;
go test -tags nogui ./... in a scratch HOME with the Go caches pinned.
The only red was TestOTelWaterfallIncludesUnbilledFallback, whose first
export was cut before the root span under load. That is #1794, filed
earlier today; this run is noted there. This change doesn't touch OTel.
internal/agent was timed against the unchanged base under the same load
and ran at the same pace.

Re-run after rebasing on origin/main 94aa15397 (load ~100, so not the
whole suite): gofmt -l on the touched files; go vet -tags nogui
./internal/agent ./internal/gateway for darwin, linux and windows;
go test -tags nogui -count=1 ./internal/agent (1381s) and
./internal/gateway (939s), green. Breaking writeReview to never write the
"0" turned TestClaudeAutoModeReview red, and dropping the subscription from
AutoModeReviewed turned TestAutoModeReviewedRoutes red.
2026-10-12 22:25:35 +08:00
yetone 86b2f4d053 provider, gateway, gui: an account whose sign-in its vendor revoked or refused reads as signed out and is passed over, not asked on every request (#1793 ysicing, echo_ts on Discord)
What changed, one fix for the class:

- ChatGPT and the other built-in subscriptions (#1793): ChatGPT answered
  401 token_revoked on every request, request after request (~18 rows in
  the reporter's log), because a refused sign-in was just "other" and
  rested a while, then asked again. Now a 401 whose words say the sign-in
  is gone (provider.SignInRevoked: token_revoked, token_invalidated,
  invalid_grant, refresh_token_reused/invalidated/expired; never
  token_expired, a 403, a 5xx or a network error) marks the account for
  the credential it was sent with (a 12-byte hash of the header, never the
  credential), in logins.json as Refused "revoked:<mark>" plus Lapsed.
  A saved ChatGPT account is refreshed first, as Codex does on a 401; a
  refresh that goes through marks nothing. The routing loop fails it as
  failAuth (next member at once, no rest); forwardOnce answers its later
  requests with magpie's own 401 without asking the vendor; compaction
  on a magpie account (compactOn) picks a marked one last. Signed in anew
  (upsertLogin with another credential, addSideLogin), refreshed, or a
  request served, the mark is gone. Claude, Copilot and plugins keep
  their own marks; a key's provider answering the same words rests as
  before.
- Copilot (echo_ts): a built-in Copilot account whose GitHub token GitHub
  refused (401/403 on the token exchange, the CLI stand-in or the usage
  read) is marked lapsed on its own account (copilot_lapsed.go), unless a
  working CLI stand-in serves; cleared when a token is served or it signs
  in again. 5xx and network errors never mark it.
- GUI: such an account's row says Sign-in required with Sign in again
  (Copilot's on its GHE.com host) and Remove, the reason on its allowance
  line in the user's language (zh, zh-TW, ja, de added); the card says
  Signed out once every account in use is.
- docs/subsystems: providers-accounts "A revoked sign-in", gateway-routing.

What was run (sandbox HOME, caches pinned, worktree only):
- go test -race on the new tests: provider TestSignInRevokedWords,
  TestRevokedSideLoginMarkedTillSignedInAgain, TestRevokedCodexRefreshedFirst,
  TestRevokedSignInLeavesOthersMarks, TestUpsertLoginKeepsRevokedMarkForTheSameSignIn,
  TestCopilot* (7); gateway TestRevokedSignInPassedOverTillSignedInAgain
  (fake ChatGPT backend, zstd, real routing: turn 1 asks acct-1 then
  acct-2, turns 2-4 and after a restart acct-2 only with no rests, after a
  new auth.json acct-1 again and the mark gone),
  TestRevokedSignInNotCompactedOnAgain, TestRevokedWordsFromAKeyRestAsBefore.
- Broken by hand, each turned a test red: the forwardOnce short-circuit,
  the failureOf clause, noteSignIn in codexUpstreamOn, compactOn's skip,
  ServedSignIn, its in-memory delete, the 401-only check, refresh-first,
  upsertLogin's keep and its sameAuth, sideLogins' Lapsed and
  addSideLogin's clear; and the six Copilot breaks. GUI: the signedOut
  and quotaError lines each turn revoked-signin-account red.
- GUI (Chromium and WebKit, 420 and 1100, en/zh/zh-TW/ja/de):
  revoked-signin-account (new), copilot-signed-out-account (new), and the
  account-*, claude-*, codex-*, plugin-*, quota-*, signin-*, routing-*,
  usage-accounts* suites: 1605 pass, 7 fail. Six are WebKit
  routing-group-fold/routing-sessions/routing-steady cases that fail the
  same on a clean 9964535ad run alone (#1672, #1612, #1307, #1804); one,
  signin-proxy Chromium de 380, timed out under load (load ~60-75) and
  passed 2 of 2 after, filed as #1814.
- gofmt; go vet darwin, linux (nogui) and windows; linux and windows
  builds. go test ./...: every package ok but gateway, where
  TestOTelFastRequestTranscriptDiscovery and
  TestOTelWaterfallIncludesUnbilledFallback failed under load (#1794);
  both pass alone, -count=3.

Not verified: no real revoked ChatGPT or Copilot account was tried; the
words come from the reporter's screenshot and OpenAI's documented codes.
Codex's own relayed sign-in (not one of magpie's accounts) isn't marked:
Codex refreshes and signs itself in. The short-circuit in
codexUpstreamOn (compaction on a marked account, reached only when every
account is marked) has no test of its own; plugins are left to their
plugin.
2026-10-12 22:16:17 +08:00
yetone 6c9048db51 gateway: a request asks only the resting member back soonest, not every resting one, so a failing member isn't hammered by each request (#1799, dbydd)
dbydd: a group's routing still goes over its members in order however
they have been failing, and with providers magpie can't read a quota
from, that is close to a DDoS of the ones that are down.

What was there: a failure rests the member (credit 30m, quota till its
reset, rate by Retry-After, anything else 1m doubling to 10m), and one
answer clears it. But restLast only moved resting candidates behind the
ready ones. Once the ready ones failed, every request went on to ask
each resting member in turn, so the rest kept nobody back: in an outage
of the whole group each request went to all N members, and the last one
again on its retries.

Now (probeOne, fallback.go): of the candidates resting, a request asks
only the one whose rest ends soonest (the first in order on a tie), at
its place. Every ready candidate is still asked in the user's order. A
lone candidate is always asked. A group that is down whole takes one
upstream request per request, and the backoff grows with each real
probe instead of each request. The trace still lists every member, the
resting ones with their rest. The same is applied where the other
paths go over candidates: count_tokens, embeddings/rerank, image
accounts (drawOnAccounts) and a group's System One decision models.
Codex autoReset still looks over the whole list (all), so a week used
up on every account still spends a reset.

Default on, no switch: it only reads rests the user's order already
demotes, and only within a rest's cooldown; once a rest ends, the member
is back at its place in the user's order. Each request still makes at
least one real upstream attempt and returns the vendor's own error.
Scoping: only rests are read, and a failure about the request's content
or its model rests no member (failShape, prompt, overflow, refused,
loop, auth, proxy...; a model refusal rests only restID), so neither
leaves a member out.

Borrowed from AxonHub's error-aware load balancing (looplj/axonhub,
docs/zh/guides/load-balance.md, ErrorAware), which dbydd pointed to: a
failed channel's score drops and recovers as its penalty decays, rather
than it being sent every request. magpie's rest and backoff already are
that decaying penalty; asking the one back soonest is how it recovers.
Not taken: a success-rate memory that keeps a member demoted after it
answers. One answer means it serves now, a flaky member already rests at
least a minute per failure, and holding it down past that would
override the user's order beyond a cooldown.

Unchanged: the last candidate still isn't rested by its own failure,
and the Patience rounds (#1418) and retries on the last one re-ask only
candidates already in the trimmed list.

Tests (resting_probe_test.go): TestGroupAsksOneRestingMemberNotEach
(three resting members, minutes apart: only the soonest is asked; with
a ready member, it then the soonest),
TestRetrievalGroupAsksOneRestingMember (embeddings),
TestLoneRestingMemberStillAsked, TestProbeOne. With
probeOne returning its input (the old behaviour), the first two fail:
"resting members asked map[a:1 b:1 c:1]".

TestSystemOneDecisionGroupFailsOver held the old behaviour (all
failing: kb, ka1, ka2 asked, ka2's 503 back); it now wants kb then ka1,
the one rested first, and ka1's 429 back.

Run: gofmt -l (clean); go vet (darwin, GOOS=linux -tags nogui,
GOOS=windows); GOOS=linux -tags nogui and GOOS=windows go build;
go test -tags nogui ./... -timeout 40m under a sandbox HOME at load
average ~100: every package ok but gateway and agent, which hit the 40m
timeout mid-run (TestZenUnsupportedModelLeavesTheListAlone and
TestSnowNoProfiles running, a few seconds in), and plugin, where
TestNPMInfoDeadline hung on its own failed 2s check (filed #1808).
Rerun alone with -timeout 80m: gateway ok (1896s), agent ok (1811s),
plugin ok (746s). Not run: a real upstream outage, the Windows box;
count_tokens and image accounts have no test of their own.
2026-10-12 22:02:03 +08:00
yetone 446bffcac7 gateway, gui: a Routing row's share used renews with its own window, not the biggest one (#1778)
Vigilans' Factory account showed "32% used · renews in 27 days": the
week's 32% beside the month's reset. Allowance.For gives the fullest
window's share and the renewals biggest first, and routing.js paired the
share with renews[0], so for any account of more than one window the row
mixed two windows.

- provider.Allowance.Fullest(model, now): the reset of the window For's
  share is of (the later of two as full; a window whose reset has passed
  counts as empty, as For does).
- The trace's Weighed gains usedRenews (from weighRouted's left.fullest);
  routing.js's usedRenews(w) uses it in both the story rows and the
  account rows, and falls back to renews[0] only for an account of one
  window (a route recorded before this commit).
- Smart's order is unchanged on purpose: it goes by the biggest window,
  and Factory's month holds less than its weeks add up to, so what a week
  leaves isn't lost at the week's reset. docs/reference.md says so, and
  gateway-routing.md names Fullest/usedRenews.

Run:
- go test ./internal/provider ./internal/gateway -run
  'Fullest|UsedRenews|Weigh|Routing|Smart' and the packages whole.
- TestUsedRenewsWithItsOwnWindow fails with left.fullest set to the
  biggest window's reset (broken by hand, then restored).
- routing-key-windows.test.cjs: 44/44 in Chromium and WebKit, all
  languages and widths; it fails on HEAD's routing.js.
- Every routing-*.test.cjs plus panel-routing in both engines: 594/601.
  The 7 WebKit failures are clicks waiting for an element to be "stable"
  under load average ~44, in routing-group-fold (#1612, #1672),
  routing-sessions (#1307) and routing-days-fit. routing-days-fit passes
  run alone. The other two fail the same alone with HEAD's routing.js.

Not tried against a real Factory account: the windows are those the
Factory plugin's limitWindows reports (5h/7d/30d with resetsAt).
2026-10-12 19:38:13 +08:00
yetone 8f2a314cf9 gateway: a ChatGPT account's turn goes zstd-compressed, as Codex's own client sends it (ylorn on X)
ylorn (X, v0.1.1202) sent a text-only gpt-6-luna turn of 1,100,224 bytes
straight to chatgpt.com/backend-api/codex/responses. Sent plain it got 503.
The same turn zstd-compressed (259 B) got 200. magpie decodes Codex's
inbound zstd and sent the backend plain JSON, so the turn got 503 through
magpie too.

What Codex does (openai/codex a9b08151, 2026-10-11):
- codex-rs/core/src/client.rs:1704-1712 responses_request_compression:
  Zstd only with the enable_request_compression feature, a sign-in that
  uses_codex_backend, and the OpenAI provider.
- client.rs:1780: used for the POST /responses stream only.
  /responses/compact and /models go plain.
- codex-rs/features/src/lib.rs:1411-1416: the feature is Stable and on by
  default.
- codex-rs/protocol/src/auth.rs:54-63: uses_codex_backend is true for the
  ChatGPT sign-ins and false for ApiKey and Bedrock.
- codex-rs/codex-api/src/endpoint/responses.rs:130-147 sets it for
  /responses.
- codex-rs/http-client/src/request.rs:196-217 compresses with
  zstd encode_all at level 3, sets Content-Encoding: zstd, and never
  compresses twice.

What changed:
- provider.CodexCompressed compresses a body sent to CodexBase/responses
  with klauspost zstd, already a dependency. It uses SpeedDefault (about
  level 3) and no frame checksum, like libzstd's default. It sets
  Content-Encoding, Body, GetBody and ContentLength to the compressed
  bytes, and returns the wire size.
  - It is called once the body is final and signed: in forwardOnce for a
    codex account, in codexUpstreamOn (the relay) on every try (so a try
    again or a body without an unreadable image is compressed afresh), and
    in warmCodex.
  - Unchanged: /responses/compact, an sk- key's requests to api.openai.com,
    every key provider (even one at the same URL), and a body already
    encoded.
  - The plain body is still what magpie keeps, masks, traces and shows.
- codexDropped (#1628, a2b96139c/8029d98b7) judges "large request" by the
  bytes sent on the wire. A text turn that compresses to a few KB and is
  reset is a small request's 503, not a "MiB" hint asked again. A
  screenshot's random bytes stay past 1 MiB, and those are still asked
  again.
- The gateway and provider TestMains leave turns plain
  (CodexZstdForTests), since their fake backends read the body as JSON.
  The new tests turn it on.
- TestAsksOwnBackendAgreesWithTheGatewayDispatch read any call whose sixth
  letter is upper case (CodexCompressed) as a serveX dispatch. It now
  needs the "serve" prefix. Removing "kiro" from asksOwnBackend still
  turns it red.
- docs/subsystems/gateway-routing.md: the "sent plain JSON" line now names
  this exception.

Tests: internal/gateway/codex_zstd_test.go covers the accounts loop, the
relay (inbound zstd and plain), a try again after a drop, compact and an
API key plain, a key provider at the same URL plain, and a reset judged by
wire bytes. internal/provider/codex_zstd_test.go covers the round trip,
GetBody, Content-Length and the URLs left alone. Broken by hand, each went
red:
- no compression in forwardOnce: Account and AskedAgain
- no compression in the relay: Relayed, AskedAgain and JudgedByBytes
- no account guard: KeyProviderTurnStaysPlain
- compact compressed: CompactAndAPIKeyStayPlain
- the drop judged by len(body): JudgedByTheBytesSent

Real account (the owner's ChatGPT sign-in, gpt-6-luna, 1,100,279 B
text-only body, 391 B zstd):
- Direct to chatgpt.com, twice: plain 200/200, zstd 200/200. ylorn's 503
  did NOT reproduce from here (a2b96139c also saw 0.5-20 MiB served). The
  change rests on the official client's behaviour.
- Through a sandbox magpie (own HOME, :3486) via a byte-counting CONNECT
  proxy:
  - Old build: relay-zstd, relay plain and the account path were 200, 200,
    200, with 3,321,579 B uploaded to chatgpt.com.
  - New build: 200, 200, 200, with 13,362 B uploaded. Each 1.1 MB turn now
    goes as a few KB, as Codex sends it.

Run at origin/main e21ea07e4:
- go test ./... was all ok after the dispatch-test fix. The provider,
  agent and gateway packages were rerun.
- go test -race -count=3 on the new tests.
- gofmt -l is clean.
- go vet: darwin and windows ./... ok. linux ok for the changed packages.
  linux ./... fails the same on clean e21ea07e4 (wails v3's cgo-only Linux
  files, cross-vet from macOS).
2026-10-12 16:09:52 +08:00