4794de398ea8337d223a91e207181c56fcf4ad76
981
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
3a9d73c5c6 |
gateway: a plugin's deferred usage is billed with its step, never told as the prompt
The Cursor plugin collects a tool step's late usage event with the conversation's next step. It used to add it to that step's prompt_tokens, which agents read as how full their context is: pi saw 366940 tokens (181270 + 185670) on a 300k window where 185670 were in use, and compacted. The plugin now reports it apart, as usage.magpie_deferred (yetone/magpie#1053). The gateway parses the field into Usage.Deferred and adds it only where it bills: the usage records (6 sites in serve), the OTel attempt span and route pricing, as a tier before the request's own, so promptCounted still reads the request's own prompt. What a client is told (Usage.chat, the Anthropic encoding) stays the request's own. A reply without the field is handled as before. docs/subsystems/provider-plugins.md describes the field. Verified: go test -tags nogui ./... (50 packages ok, sandbox HOME, caches pinned); gofmt; go vet on darwin, linux (nogui) and windows; go build on the same three. The new tests were broken by hand and each went red: billed() ignoring Deferred, cUsage dropping the field, routeUsage without the tier, Usage.add forgetting it, the decoder ignoring a usage with only a deferred part, the usage records and the OTel span not using billed(). Not tried: a real Cursor account on this checkout; the plugin side was run against real Cursor (composer-2.5, forced late events), where the deferred totals matched the dashboard's events token for token. Picked from geoqiao/magpie cursor-deferred-usage (595d6384c), as PRs here are collaborators-only. Rebased over the service-tier logging (#1784), keeping its TierAsked/TierSent/TierServed beside billed() at the three usage.Record sites, and Usage's Tier beside Deferred. Run on this tree: go test -tags nogui -timeout 40m ./internal/gateway and ./internal/provider (sandbox HOME); gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows. billed() forced to ignore Deferred: 3 tests and 5 subtests of deferred_usage_test.go go red. |
||
|
|
320af98581 |
gateway: an upstream's error in a shape its decoder can't read fails the reply, so Codex tries again (#1933, tensornull)
A translated stream whose upstream said it failed, but not in the shape
its protocol's decoder reads, ended as a completed reply with no output
and zero usage. Codex took that as its turn's end (exit 0, no message)
and never used its stream retry. tensornull's three fixtures, on an
Anthropic provider asked from Codex's Responses:
- {"type":"error","error":"fixture upstream failure"}: decodeAnthropic's
struct wants an object for error, so the event decoded to nothing,
while upstreamEnds counted the type "error" as the reply's end.
- Messages events with their type left out (named only by "event:"):
the decoder read nothing, and upstreamStop's delta.stop_reason still
marked the reply ended.
- A Responses response.failed from the Anthropic endpoint: upstreamEnds
took any protocol's last event, and the Anthropic decoder ignores it.
Now:
- replyEnds (upstream.go) reads a reply's end in the protocol it was
asked in: Anthropic's message_stop, error or a message_delta's
stop_reason; Responses' response.completed/incomplete/failed or error;
Gemini's finishReason; Chat's finish_reason. The other two fixtures no
longer read as whole and end as errEndedShort, a failure the gateway
and the client retry, like the "ping then EOF" control. It replaces
upstreamEnds in both the streaming loop (continuation.go) and the
unstreamed one (gateway.go).
- carriedError: every decoder (Anthropic, Responses, Chat, Code
Assist/Gemini) that can't decode an event still tells an error it
carries ({"error":"…"}, type error, response.failed) as KError with
its words. Siblings found the same way: a Chat upstream's
{"error":"…"} chunk ended a translated reply as completed; a Responses
upstream's string error or a response.failed with no error object
(status failed) did too, read as stop.
- An error event with no message says its type or the event itself,
never "".
One test's fixture changed with it: TestTranslatedEffortLoggedAsSent
served Chat chunks from its Responses upstream, which the Responses
decoder reads as nothing. It "completed" only because a finish_reason
counted as the end, the same empty success this fixes, so it now fails
with errEndedShort. The case gets a Responses reply (responsesHi).
What a whole reply does is unchanged: a valid Messages text reply, and
Claude's empty end_turn (asked of in the report), still complete on the
first ask (TestWellFormedStreamsStillComplete).
Run: the new tests in stream_error_shape_test.go use the report's bytes
(event: lines included). Against origin/main's code (fix reverted, tests
kept) 8 subtests fail: anthropic error string, error object with no
message, events with no type, responses failure on the messages route,
chat error string, both Responses-upstream cases, and the unstreamed
client; the error-object control and the well-formed ones pass on both.
With the fix all pass. go test -tags nogui -timeout 40m ./internal/gateway (sandbox
HOME, caches pinned); gofmt -l; go vet darwin, GOOS=linux -tags nogui,
GOOS=windows. tensornull's reproduce.py against a nogui build of this
tree: error-string now ends response.failed "fixture upstream failure"
after 3 gateway attempts, the same as the error-object control (was
response.completed after 1). Not run: the Codex CLI replay; a Responses
client asking a Responses upstream is passed its bytes as they are, so
that pairing is unchanged.
|
||
|
|
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.
|
||
|
|
52f138448a |
gateway: a model switched fast keeps the client's own Ultrafast ask (#1784, zhenghaowen0967)
What changed: withFast, which sends a candidate in its vendor's fast mode (a fastPick in the agent's picker, or a group member set Fast), wrote service_tier "priority" over whatever the client sent. A client asking for "ultrafast" was sent priority. Now a Chat or Responses body that already asks for "ultrafast" is left as it is. The existing per-account step after it still applies: an account whose model list doesn't offer ultrafast is tried after one that does, and is asked for priority. Why: zhenghaowen0967 reported, on 0.1.1219 with OMP, that gpt-6.1-sol was switched fast for omp (fastPicks.omp) and its ultrafast requests showed no sign of going as ultrafast. With the fast pick on, the request was rewritten to priority before the ultrafast check ran, so it went to the first account (Plus) as priority instead of to the Pro account that offers ultrafast. Test: TestFastPickKeepsTheClientsUltrafast (tier_accounts_test.go). - omp's fast-picked codex/gpt-6-luna, asked on /v1/responses at chatgpt.com (redirected to the fake ChatGPT backend), goes to acct-pro as ultrafast. - With Pro out, it goes acct-pro:ultrafast then acct-plus:priority. - With no tier asked, it goes acct-plus:priority as before. - A Chat body keeps "ultrafast" too. What was run: - With the fix taken out, the test fails the way the report describes: "ultrafast tried acct-plus:priority". - go test -tags nogui -count=1 -run 'Fast|Tier|Ultrafast|Priority' ./internal/gateway passes. - The full gateway package, gofmt and vet are run with the next commit (see its body). |
||
|
|
9492e5db8a |
gateway: a conversation that searched its tools compacts and goes on after the search tool is gone, on a Responses vendor that doesn't know tool_search_call (#1171, tcxp001; #1755, FivePink)
What changed: searchAsFunction turned Codex's tool_search_call and tool_search_output into a function's call and result only while the request offered the tool_search tool. Codex leaves the tool out once nothing deferred is left to find, and its compaction of a magpie model sends no tools at all, but the conversation keeps the earlier searches. Those went as they came, and a vendor that doesn't know the items refused the whole request: Anyrouter's "invalid codex request" on the compaction, Xiaomi MiMo's "input item type 'tool_search_call' is not supported by this gateway phase" on a later turn. They now go as the function's call and result whether or not the search is offered, which is how the same upstream saw them in the turns that offered it. With no search offered, the tools a search found aren't added to the request's tools and the reply isn't read as a search (searchTidy stays off). The ChatGPT backend (a Codex account) still gets the items as Codex sent them. The call-id tests for OpenAI and Responses relays (Lullaby) expected a history-only search sent as tool_search_call with a tsc_ id; it now goes as a function_call, which has no item id to get wrong. Their ctc_ checks are unchanged, and the ChatGPT-backend test keeps the tsc_ expectation (sentToChatGPT). Run: TestSearchHistoryWithoutTheSearch (compaction through CodexPath and a later /v1 turn, each upstream refusing with the reporter's own words) and TestSearchAsFunctionHistoryOnly fail on the old toolsearch.go, the gateway answering 400 with each reporter's error; they pass with the fix, with TestToolSearch*, *CallIDs, TestBareReasoning*, TestAdditionalTools*, TestCodexAsSent*, TestSearchedConversation* and TestSpawnAgentNamesEveryModelAfterToolSearch. Full go test ./internal/gateway/ below in the push record. gofmt -l clean; go vet -tags nogui on darwin, linux and windows. Not tried: Anyrouter or MiMo themselves. |
||
|
|
8e6354714f |
provider: OpenCode Zen's free models answer again, with a session id OpenCode itself could have made (c9cu on Discord)
c9cu (v0.1.1222, Pi, a group routed to OpenCode Zen's muse-spark-1.3-contributor-free on /v1/responses) got 403 FreeTierError "OpenCode's free tier can only be used from within OpenCode" on a setup that worked the day before. Zen now reads x-opencode-session as OpenCode's identifier.ts lays an id out (12 hex of ~(Date.now()*0x1000 + counter), then 14 base62) and refuses one whose counter isn't small. magpie's built-in sent a sha256 of the conversation cut to that shape, so its counter was anything. The zen-free plugin hit the same (#100 on magpie-community/plugins, 0.1.5); the built-in had the same code. Header diff against the real upstream, same request with curl: - magpie's ses_e9283da055b15JwOAra76bwUx4 (hash): 403 on /v1/responses and /v1/chat/completions. - ses_ecc5d8f28ffe9Cy14V8Em7lI2u from a real OpenCode 1.19.0 run, the old opencode/1.18.34 UA unchanged: 200 on /v1/responses. So it is the session, not the UA or the endpoint; muse-spark is still served on Responses (Chat answers 400 ModelProtocolUnsupported, as before). Now (opencode_client.go): - openCodeSession makes a real descending id from the current time and a per-millisecond counter, kept per conversation (the last 1000) so a conversation's turns share one session; one OpenCode could have made is passed on unchanged, a hash-shaped one is not. - x-opencode-request is an ascending msg_ id the same way. - the session also goes in x-opencode-session-id, x-session-affinity and X-Session-Id, as OpenCode's packages/core/src/session/ model-request.ts sends it, and the User-Agent is OpenCode 1.19.0's (opencode/1.19.0 ai-sdk/provider-utils/4.0.23 runtime/bun/1.3.14, the latest on npm, as the plugin captured it). - Kilo's task/session id goes through the same openCodeSession (the Kilo CLI is OpenCode's fork and makes ids the same way). Run: - Through an in-process gateway under a sandbox HOME against the real opencode.ai/zen with the public key: muse-spark-1.3-contributor-free on /v1/responses with reasoning xhigh, streamed and not, big-pickle streamed on Chat, mimo-v2.6-flash-free on Chat: all 200 "pong". The same file on origin/main's code: all 403 FreeTierError, the reporter's message word for word. - TestOpenCodeSessionIsOpenCodes, TestOpenCodeSessionsKeptBounded and TestOpenCodeClientHeaders (now with a real 1.19.0 session) fail with the hash put back by hand. - gofmt -l, go vet (darwin, GOOS=linux, GOOS=windows -tags nogui) on internal/provider and internal/gateway. - go test -tags nogui -count=1 ./... under a temp HOME on base |
||
|
|
488569227e |
zhipu: a GLM Coding Plan key at the pay-as-you-go endpoint is asked again at the plan's, and the provider moves there
@cleverpigo on X: "glm coding plan放在codex/chatgpt里显示余额不足没法用". The editor
showed OpenAI https://open.bigmodel.cn/... red with 429 · 余额不足或无可用资源包,
请充值。 next to a green Anthropic https://open.bigmodel.cn/api/anthropic.
Root cause: the zhipu and zai presets start on their first region, Pay as
you go, whose OpenAI URL is /api/paas/v4. The Anthropic URL is the same in
both regions, and it bills the Coding Plan when the account has one. So a
Coding Plan key left at the default works in Claude Code, while Codex goes
to /api/paas/v4 and Zhipu answers 429 code 1113 (no balance). A provider
made by pasting the paas/v4 URL hits the same wall. Nothing in the key
says which kind it is. LESSONS.md's
|
||
|
|
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
|
||
|
|
1e88598384 |
gateway: a Claude Code test or /usage run that magpie gives up on ends with what it started, npm's node on Windows too (#1894, heng91)
What changed: magpie runs Claude Code one-off for an account's model test (askClaude) and for /usage (claudeUsage, read in the background for each Claude account). Both ran through CommandContext, whose kill on the timeout ends only the process magpie started. On Windows an npm install's claude is claude.cmd: cmd.exe running node, and only cmd.exe was killed, so node went on running with nothing to end it. Elsewhere a CLI that is a wrapper script left its child the same way. Now both run in a proc.Tree (a job on Windows, a session elsewhere), as the Claude subscription's runs do: what is left once the head ends is ended with it, and on Windows the job ends it if magpie exits mid-run. Run: - go test -tags nogui -count=3 -run 'ClaudeRunEnds|WarmClaude|ClaudeUsage|ClaudeTest' ./internal/gateway: ok. New TestClaudeRunEndsWhatItStarted: a script claude that starts a child and hangs; once it has started the child the run is given up on, and the child must be gone. With cmd.Run() put back by hand, both subtests (test, usage) go red with the child running. - gofmt -l; GOOS=linux and GOOS=windows go vet -tags nogui: clean. Not run on the Windows box: the job path is the one subscription runs already use. Not found to be the reporter's processes: magpie's other Claude Code processes are the subscription runs kept for a conversation's next turn (at most 6, at most an hour, by design). Reported-by: heng91 |
||
|
|
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. |
||
|
|
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. |
||
|
|
097479dabb |
gateway: a done route isn't written to disk in a test binary testenv isolated, so a late write can't refill a test's folder as it is removed (#1543)
trace.update runs `go saveRoute(c)` when a route ends. That write runs behind the request that ended the route, under XDG_CONFIG_HOME/magpie. When a test returns, its cleanups run in reverse: the env is put back, then the TempDir is removed. A saveRoute that had already taken its folder was still writing routing/<day>.jsonl into it while RemoveAll ran, which is CI's "TempDir RemoveAll cleanup: .../magpie: directory not empty" for internal/gui TestContextTextAPI (ubuntu 23:15Z and macOS 19:38Z on 10-12). Every package whose tests send a request through gateway.New() has the same writer: gui, tui, agent, davsync. Only the gateway's own TestMain turned it off (keepRoutes = false). The fix is in one shared place: keepsRoutes() is false when MAGPIE_TEST_SANDBOX (testenv.Marker) is set, which testenv.Run/Isolate and the gateway's TestMain set for every test binary. No test outside the gateway reads the routing history back; the gateway already had keepRoutes = false, and only the new test below turns it on. The gateway's two sightings (TestRequestTailAfterOldLimit at |
||
|
|
0c6752dbdf |
gateway: a too-long, shape or retired refusal read its Chinese escaped as \uXXXX too, and the translated thinking re-ask has its test (#1678)
Follow-up to ggbdpq's f16c1f7cd (#1678) after its review. Its four
sites now read wordsOf(body); three more deciders whose word lists hold
Chinese still matched the raw body, and one of its sites had no test:
- overflowed: an escaped 上下文长度超过限制 400 wasn't read as the
conversation too long. It is called from retryable (now decoded) and
from the candidate loop on the held error, so it decodes itself.
- shapeRefused: its negations (the quota and unserved words) missed
escaped Chinese, so a decision group's raw postDecide body that also
said 额度已用完 counted as a shape refusal and rested nobody.
- tooLongUnsaid: an escaped 该模型不支持 400 past the window was told
to the agent as a prompt too long, as its quota and unserved checks
read the raw body.
- forwardTranslated's alwaysThinks site had no test: breaking it left
every test green. TestTranslatedThinkingOffRefused now carries the
escaped #699 refusal.
Run (worktree on origin/main
|
||
|
|
4ed379f116 |
gateway: error words escaped as \uXXXX are read by the other deciders too
What changed: #1669 taught failure(), resetsWritten and the per-model rest's other-models check to read a JSON error whose encoder escapes what isn't ASCII (Python's json.dumps does by default), but the other word-list deciders still matched the raw body: - modelRefused and modelRetired (fallback.go): an escaped 模型不支持 refusal rests the whole key or account (a cooldown, longer on repeats) instead of the model alone (#1235's class), and the escaped quota words of their negation are missed the same way. The candidate loop's restAfterMarked feeds them the vendor's body as it arrived, and the decision group's decideFailed the raw postDecide body; a chat's rewritten error carries the decoded message, which is why the chat path was spared. - retryable (fallback.go): an escaped 额度已用完 on a 400 reads as not retryable, so a decision group returns the error instead of asking its next decision model. - alwaysThinks (gateway.go, both 400 learn-again sites): a vendor's escaped 思考不可关闭 refusal is not asked again with thinking left to the model (#699's class), so the agent sees the 400 every turn. All three now match on wordsOf(body), as failure() already does. Run: - New TestAnthropicPassthroughAlwaysThinksInEscapedChinese sends the escaped refusal through /v1/messages: on the old code 400 after 1 call (the re-ask not taken), with the change 200 after 2. - New TestEscapedWordsReadByTheOtherDeciders: modelRefused(403, escaped 模型不支持) and retryable(400, escaped 额度已用完) are false on the old code, true with it; the same refusals unescaped stay true. - Both fail with the fix stashed, pass restored. go test -tags nogui -count=1 ./internal/gateway: ok. The named tests and the guards they touch (TestAnthropicPassthroughAlwaysThinksInChinese, TestModelNotInPlanRestsTheModelNotTheKey, TestFailureReadsEscapedWords, TestResetsWritten, TestWrittenResetRestsUntilThen) also -race -count=5: ok. go test -tags nogui -count=1 ./... under a temp HOME: ok. gofmt -l internal/ empty. go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: clean but the trayimage_darwin.go cgo -Wenum-conversion warning, as on main. Builds: darwin, linux (-tags nogui), windows. Rebased by yetone onto main, where both learn-again sites ask refusesThinkingOff (anthropic.go, #1465): the decoding moved there. Co-authored-by: yetone <yetoneful@gmail.com> |
||
|
|
a64b3a8d46 |
plugin: a pi provider's message_start tells the prompt's usage pi's start named, so Claude Code's context meter isn't 0 until the turn ends (#1887)
What: pi.js wrote message_start with usageOf() and no argument, so every
field was 0 until message_delta. Claude Code's context meter reads the
usage the assistant message has so far, and a turn interrupted before
message_delta was stored with 0. message_start now carries the vendor's
prompt (input, cache read, cache write) and the output pi's start named
(startUsage): from pi's start event's partial.usage, as the issue
describes, or, as pi-ai's anthropic-messages pushes start before it reads
the vendor's message_start (start's usage is still 0 then), from the
partial message the events after it share. That message is pi's own,
still being written (by the time magpie reads it pi may have pushed the
whole turn), so only its prompt is taken from it, never its output.
message_delta is unchanged: the whole turn's cumulative usage from done.
Siblings, the gateway's translators to Anthropic's stream:
- Gemini / Code Assist (codeassist.go): usageMetadata rides on the first
chunk, but KStart was emitted before reading it. KStart now carries the
prompt (input, cached); output stays 0 there.
- Chat Completions (chat.go): most streams count only at their end, so
nothing to tell; a stream that counts on its first chunk now has its
prompt on KStart.
- Responses: response.created has no usage. Anthropic-to-Anthropic and the
Claude subscription already carry it. Cursor, Kiro, Devin, Qoder,
Command Code send KStart before any usage is known.
Ledger: no double count. The usage sniffer and the collector both take
each field's latest non-zero value (Usage.add replaces, it doesn't sum),
and continuation/search take a try's KStart usage as its own (this =
ev.Usage) and KUsage replaces it. message_delta's input equals
message_start's, which Anthropic's clients also take as the same count.
Run (Go 1.26.8, darwin):
- TestPiPackage with a fake pi stream as the issue's (start with
partial.usage input 11, cache 3/2, output 0, text, done with output 7):
message_start 11/3/2/0, message_delta 11/3/2/7; and pi-ai's order
("late": start with zero usage, then the shared message counted):
message_start 11/3/2/0. Red with message_start back on usageOf(), and
the late case red when only start's usage is read.
- TestPromptUsageOnMessageStart (Gemini, chat counting per chunk, chat
counting at the end): red with codeassist.go and chat.go stashed.
- go test ./internal/plugin and ./internal/gateway in full (-timeout 28m;
the default 10m timed out under load average ~20). The disk filled
during the run (3.7G free, not this change's): every failure was
ENOSPC, and each of them (37 gateway, TestFakePlugin) passed on rerun.
- gofmt -l; go vet for darwin, linux and windows on both packages.
Not tried against a real pi vendor or Claude Code's meter.
Reported-by: guoqchen1001
|
||
|
|
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. |
||
|
|
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.
|
||
|
|
0bb0781ea0 |
gateway: a group with one intent rule is classified by Clef, and one intent is never taken for a level (Versun) (#1325)
With one intent rule and a Clef classifier (@cf/cloudflare/clef or clef-flash), every turn's classification failed. jevBody always asks the "level" choice, whose options are the intents alone, and Workers AI turns away a choice of fewer than two options: 422 "questions: Dictionary should have at least 2 items after validation, not 1". The field it names is misleading: a request of one question is accepted (a lone noul, score, or two-option choice each answered 200). The rule never matched and the turn went down the group's order, with only the trace saying why. Jev accepts a one-option choice, so it went unseen there. One intent is no scale either. jevLevelled asked about it anyway, and Clef Flash called a single kind a level at 0.58; readJev then reads the one-option level answer, so once the 422 is gone the rule would match every message. askJev now asks whether the intents are levels only when there are two or more, and jevBody asks the level question only then: one intent is a topic, a message may be none of it, and "none of these" stands. Two or more intents, and the effort question, are asked as before. Tests: - TestClefOnCloudflare's fake Clef turns away a choice of fewer than two options with Workers AI's real 422 body. Without the jevBody change it fails with the classifier error above. - TestJevLevels adds one intent that Jev calls a level: "none of these" stands, picking it matches the rule, and no levels call is made. Without the askJev change it fails: `one kind picked: ... Intent: ..., 3 calls`. - TestJevOnVercelTypeSafe, TestJevOnVercel and TestJevOnCloudflare check the levels call on the wire (Vercel's noul as a boolean, Cloudflare's account looked up once), so each gets a second intent to keep asking it. Verified on macOS (go1.26.8, temp HOME, Go caches pinned): go vet -tags nogui ./...; go build, GOOS=linux go build -tags nogui, GOOS=windows go build; go test -tags nogui ./...; go test -race -count=20 on the tests above; gofmt -l clean. Against the real Clef: a nogui build in a temp HOME on 127.0.0.1:3499 with a one-intent group and @cf/cloudflare/clef as its classifier. Before, both turns' classifier error is the 422. After, "hi, how are you?" matches at 0.97 and a refactor request is "none of these" at 0.94. |
||
|
|
920d96af55 |
tests: provider, plugin, gateway, codexcat, gui and tui tests pass in any order and on any -count (#1146)
Squashed from wei's #1146, onto main. Each test now starts from state of its own instead of what an earlier test (or an earlier -count run) left: - plugin: changed() counts the OnChange hooks still running; Told waits for them, and Settle ends with Told and UseCached(nil), so a change one test made isn't told in the next and the next test's plugin list isn't read as changed. Only tests call Settle/Told; in production changed() only counts. New TestSettleWaitsForTheHooksItTold and TestSettleForgetsTheFoldersPlugins. - provider: isolate forgets Copilot's state, the plans' quota cards and balances; the warm-up, Cursor sign-in, hold and moved-plugin tests wait for what they started. - gateway: fresh() forgets refused seals, and TestRouting, TestSmartRouting and TestQuotaRestsUntilItsReset start from forgetRouting; codexSignedIn and TestForeignReasoningIsLeftOut start from fresh. - codexcat: XDG_CONFIG_HOME under the test's home. tui: costAt reset. gui: the fake Cursor account no longer outlives its test. cli: Settle. Left out as already on main: the cli_identity keepIdentities switch ( |
||
|
|
43214976f2 |
gateway: a routing history over 200 MB drops a day whole, not just a late route's file beside the day's .gz (waitingsnow) (#1110)
A route done after its day was gzipped goes to a new <day>.jsonl, and
the next prune adds it to the day's .gz (#1057,
|
||
|
|
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> |
||
|
|
a0c00370f9 |
feat: recognize acp-extension-codex as codex (#1256)
* feat: recognize acp-extension-codex as codex * test: cover acp-extension-codex client recognition |
||
|
|
1acdf3a8f9 |
gateway tests: TestUsageIngestTouchesNoLimit stamps its calls now, not a minute ago, so it holds at midnight UTC (#1874)
CI run 38324287356 on
|
||
|
|
fe08c8ddb5 |
gateway: a Claude run started for a tool loop with no history chunks its messages too, so AgentSummary reads the last one's cache (#1716)
#1716 chunked only the history: the messages before historyEnd's split. A conversation with no reply that calls no tool, as a sub-agent's loop of tool calls that Claude Code's AgentSummary asks a summary of with its last results (JinJieBeWater on #1716), has split 0, so it was told in one block and its one mark stayed on the instructions: every such request wrote the whole loop again. Such a conversation now has its every message but the last chunked. A later request with a history is told it wrapped from its first message, so it never matched past the instructions before either. What was run: - TestClaudeToolLoopCachedAcrossNewRuns (new), TestClaudeHistoryCachedAcrossNewRuns, ClaudePrompt*, ClaudeInstructions*: pass. - Broken by hand, each seen red: no split-0 chunking; the last message chunked when it ends a chunk (a 32-message loop); boundaries counted from the end; the mark left on the instructions too; no chunk mark. - Real Max account, claude-haiku-5-5, Claude Code 2.1.296 through a recording proxy, each run started anew with magpie's rendered prompt, a loop of 20 then 24 tool rounds (42 then 50 messages): origin/main: second run read 3,790, wrote 70,764 #1716 alone: second run read 3,791, wrote 70,813 with this: second run read 48,661, wrote 25,993 Grown history (21 then 41 messages) and same history with a new ask are unchanged from #1716 alone (22,348/28,178 and 40,848/9,678). Every request kept to four marks, all 1h. - Not tried: a long turn to answer after a history is still one block, and images count toward Anthropic's 20-block lookback. Co-authored-by: deephbz <13776377+deephbz@users.noreply.github.com> |
||
|
|
96eb536f85 | gateway: a Claude Code run started anew marks its history's last whole chunk of messages, not only the instructions, so a later run for the same conversation reads the history from the cache instead of writing it all again | ||
|
|
8d224796aa |
gateway: an empty reply from Gemini/Antigravity asks the next member and rests no account (#1221)
A reply that said nothing is a failure of the model or request, not the
account: the account doesn't rest (lateRests skips emptyReply), and the
group's other members of the same model, likely to end empty too, are
asked last (matesLast) while the next member is tried.
From PR #1222 by SnowGlow-aww, reviewed at 9037dd84f. Put onto main
|
||
|
|
5b14ebf49a |
gateway: a Claude subscription run is told the user's words after a tool result as theirs, not the tool's (#1878)
JinJieBeWater found that Claude Code's AgentSummary label request ("Describe
your most recent action in 3-5 words. Do not use tools.", sent as a text
block after the sub-agent's last tool_result) reached the inner Claude as
tool output, so it went on with the task instead of answering the label.
Two paths had it:
- renderParts (a run started anew, or a resumed turn) wrote the text right
after the tool's last line. A text or file part after a tool result in the
same message now closes it with "[end of tool result id=…]" and is marked
"[user message]". A result followed by nothing or by another result is
told as before, so existing prompts and their cache prefix don't change.
- match folded the text into the last result, and continueWith handed it to
Claude Code as the MCP result. It no longer folds; saidWithResults takes
the words, and continueWith writes them to Claude Code's stdin as a user
message before handing the results over, waiting for Claude Code's
command_lifecycle "queued" for that uuid (2s at most). Claude Code then
tells its model the message with the result as one the user sent while it
worked, in the same turn.
Going on in the run, rather than starting a new one for such requests, keeps
the cache prefix (#1716/#1717) and #872's mid-turn messages, which use the
same shape. #872's text is now queued as the user's instead of appended to
the result. Words in a message that holds images (pi-ai's "Attached
image(s) from tool result:" captions) still fold into the result, decided by
the message's parts, not its text. A tool whose output says "Do not use
tools." keeps it inside its result. The fork test's fake Claude now models
mid-turn absorption the way Claude Code does.
Run: gofmt -l; go vet on darwin, linux (-tags nogui), windows for
./internal/gateway; go test -tags nogui ./internal/gateway/ -count=1 green;
-race -count=3 on the new tests. Broken by hand, each red: no end marker;
an end marker after every result; the words not passed to continueWith; the
old fold into the result; the words queued after the result is handed over.
Real Claude Code 2.1.296 driven through the gateway in a sandbox HOME
against a local mock of Anthropic: on continuation the next request's
tool_result holds "SOURCE_LAST_LINE" then the "user sent a new message
while you were working" reminder with the label request; on a new run the
prompt holds the closed result and "[user message]".
Not run: the owner's real Claude subscription (its credentials are in the
Keychain, off-limits here), so the real model's answer to the label isn't
seen; Windows tests; the full ./... suite.
|
||
|
|
1502433978 |
gui: a key's value can be changed in place, keeping its name, place and settings, and its rest is lifted (#1869)
A key rotated at its vendor had to be removed and added again, which lost its name, its place in the order, its weight, protocol, models, proxy and concurrency, and any gateway key restricted to it. As decided on #1869, in multi-key mode the row now has a Change key action, with a double-click on the row as a shortcut. - provider.ReplaceKey(id, ref, key) sets the key's new value and moves what providers.json keys by the key's fingerprint (AccountModels, AccountProxies, AccountConcurrency) to the new one. An empty value, an unknown key and a value another key of the provider already holds are refused. The same value is a no-op. - access.ReplaceAccount moves gateway keys' Accounts entries from provider/old to provider/new, under the caller-keys lock. - gateway.Server.UnrestAll lifts a rest key and every per-model rest under it. The GUI's keys/replace lifts the key's rest (provider#key, and the provider's own rest key when it is the only key on), so the new value is asked from the next request. - app.js: a pencil beside the key's copy button opens a password field in place of the masked value. Enter saves, Escape leaves it, and a double-click on the row away from its controls opens it too. The button has its own class (.key-edit) with the copy button's look. - i18n: four strings in zh, zh-TW, ja and de. - providers-accounts.md: ReplaceKey in the Keys table. Past requests keep the old fingerprint in history, under the same name. A rest is lifted only in the gateway this magpie serves. Run: - go test ./internal/gateway ./internal/provider ./internal/access ./internal/gui -count=1: ok. New TestReplaceKeyKeepsItsPlace, TestKeysReplaceKeepsTheKeyAndLiftsItsRest and TestUnrestAllLiftsAKeysModels each fail with their change taken out. - gofmt -l clean; go vet darwin, linux -tags nogui, windows. - key-replace.test.cjs (new): en/zh/zh-TW/ja/de, chromium and webkit, 1100 and 420px. Checks the post, order, note, no sideways scroll, and no scroll on change or on double-click plus Escape. - With key-copy, rest-try-now and key-import: 96/96. - 72 key*/routing*/rest* GUI files at concurrency 6: 863/871. The 8 reds were key-copy, whose button.copy locator matched the pencil; that's why it has its own class now, and key-copy passes. - Under load, about one run in 300 saw the editor body go back to the top after the copy button's double-click, with no script scrolling it. That is #1504 (findings added there). The test checks scroll before that step. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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).
|
||
|
|
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. |
||
|
|
bf60d32bde |
gateway: a key set to a protocol its provider has no URL for is said on Routing and in the editor, not passed over quietly (#1702, edussss)
edussss set a relay key to Responses only on a provider with a Chat URL
and no Responses URL. perKeyBarred skipped the key (no endpoint for its
protocol), every key was skipped, so the provider was tried whole and the
request went out on Chat with nothing saying why. The owner: it shouldn't
fall back quietly.
Requests are still served on the URLs the provider has (so working setups
keep working), but now it is said:
- fallback.go: perKeyBarred remembers the protocol of the first key it
skipped for having no URL, and the whole-provider candidate carries it
as noURL.
- trace.go: Weighed.NoURL, so the Routing page sees it.
- routing.js: the row and the activity line say "key set to {api} only,
no {api} URL · sent on the others".
- app.js/app.css: the editor's key row shows an amber "No {api} URL" chip
(keyLacksURL) with a title that says how to fix it.
- i18n.js: the three strings in zh, zh-TW, ja and de.
- docs/subsystems/providers-accounts.md: the Keys row says so.
Run: go test -run 'TestKeyForAProtocolWithNoURLIsSaid' ./internal/gateway/
(the reporter's case: upstream /v1/chat/completions with k-resp, NoURL
"responses"; with an Any key added it goes to k-any and NoURL is empty);
key-nourl.test.cjs in chromium and webkit, en/zh/zh-TW/ja/de, at 420 and
1000 wide, no click-scroll, no sideways scroll: 40 pass; with i18n-keys,
gui-zh-tw/ja/de, key-copy, key-weight, key-weight-fit, key-import,
routing-key-windows, routing-keys-fold, proto-menu-overflow, nokey-editor
and ledger-protocol: 174 pass, 0 fail.
Broken by hand: without the noURL mark the Go test fails (noURL = "",
want "responses"); with keyLacksURL/noURLWord removed chromium fails 20
of 20.
Not tried: a real relay, or the GUI against a live gateway.
|
||
|
|
016760e520 |
agent: Goose's requests show as Goose on Routing and in Usage, by a key that names it (#1083, EZN7L2C3)
Goose's HTTP client sends no User-Agent (reqwest's default in
crates/goose-providers/src/api_client.rs, checked on block/goose main), and
the custom provider magpie writes for it (custom_providers/magpie.json)
carried the plain gateway key. The gateway tells an agent by its key first,
then its User-Agent, so Goose's requests were "your agent" on Routing and
"other" in Usage. The file now carries agentKeyAt("goose") (magpie-goose on
this machine, the LAN key from a NAT'd WSL distro, as before), the same as
Alma, Hanako, Snow, AstrBot and Prime Agent, which also send no User-Agent.
Goose's Check compares the same key, so a file an older magpie wrote counts
as drift and Sync rewrites it. Goose reads custom_providers at start, so a
running Goose needs a restart (the existing notice says so).
Tests: TestGooseKeyNamesGoose (the key written, an older file's plain key
noticed by Check and replaced by Sync) and TestGooseRunsOnMagpie's key
assertion fail on the old code (Authorization = "Bearer magpie", want
"Bearer magpie-goose"). Breaking only the Check back to the plain key fails
both with "headers.Authorization (magpie.json) was changed". The gateway's
TestGooseAgentByKey records a request with no User-Agent and magpie-goose
as goose's (it passes on the old code: the gateway side already worked; it
guards the path end to end). go test ./internal/agent/ ./internal/gateway/
in a sandbox HOME. Not tried with a real Goose.
|
||
|
|
296b63f8d6 |
usage, gateway: tests for the #1463 rebase: a priced row keeps its reasoning evidence, and a summary after an endpoint fallback stays hidden
Follow-up to congee949's rebased dfc24632 (#1463, streamed reasoning speed). - TestPricedRowKeepsReasoningEvidence: the Requests page reads gateway rows through blockPricer, which sets swapKnown (64) on every row. The patch put ReasoningHidden on bit 64 too; on main that would have read every priced row as hidden, so a tool-only reply with no reasoning, and paced visible reasoning, lost their speed on the Requests tab. The rebase gave ReasoningHidden its own bit (256, Flags widened to uint16); this test prices visible, tool-only and hidden rows, raw and packed, and checks the flag and the speed read back. - TestSummaryAfterEndpointFallbackStaysHidden: a Messages client, a model answered on /responses after /chat/completions said it isn't served there. call.To still reads Chat, so hidesReasoning(call.To) doesn't see the summary; only streamTranslated's summaryUpstream marking does. With no reasoning count the 1500 output tokens were otherwise timed from the first summary delta. Nothing covered that marking before. - reasoning-speed.test.cjs: the "no reasoning: 500 in 5 s" comment had been joined onto the redacted row; put back on its own row. - docs/subsystems/gui-shell.md: the flag bit, the fallback marking, the two tests. Run: go test -tags nogui -count=1 ./internal/usage/ and the gateway's reasoning tests; reasoning-speed.test.cjs in Chromium and WebKit (en, zh, zh-TW, ja, de), 10/10. Broken by hand: rowReasoningHidden = 64 turns TestPricedRowKeepsReasoningEvidence red (visible and tool-only rows read hidden, 0 tok/s); summaryUpstream forced false turns TestSummaryAfterEndpointFallbackStaysHidden red (1500 tokens in 314 ms). Co-authored-by: congee949 <c86474321@gmail.com> |
||
|
|
2d3b33bb78 |
usage: time tool-only replies only with visible reasoning evidence
Revises #1463 after the hidden-reasoning inflation review. Keep answers separate, retain evidence in routes and cached ledger rows, and exclude sealed or summary-only reasoning even without a token breakdown. Sync the backend and both GUI formulas. Checked real WorkBuddy DeepSeek, Codex and Claude bridge responses in an isolated HOME; sanitized timings and failures are in docs/verification. Chromium/WebKit speed regressions pass (20 tests, five languages). New edge regressions and loop-order check pass under race repetition. Restoring the old formula or removing the hidden guard fails TestVisibleReasoningSpeed. macOS/Linux/Windows vet/build pass. Full-suite verification is recorded in the issue at this head; inherited proxy/Bun 1.3.14 failures are retained, with clean Bun 1.4.2 rerun in progress. No installed app replacement. Rebased onto main by yetone (#1463). Conflicts with main's Own/Retried/ Queued/Tries row fields, HandedOn and the Codex speed floors were resolved by keeping both. The packed row's ReasoningHidden bit was 64, which main has since given to block_price.go's swapKnown, and main's rowHandedOn took 128, filling the uint8: Flags is now uint16 and ReasoningHidden is bit 512 (rowReasoningHidden; #1874's rowOwnCost took 256), read back in row(). The docs/verification notes and their sample JSON are left out of the tree; they stay on the contributor's branch and the issue. Run after the rebase: go test -tags nogui ./internal/usage/ and the gateway's reasoning/speed/TTFT tests, ok. |
||
|
|
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> |
||
|
|
e21b1dbc16 |
gateway: a broken tool exchange a Chat or Zed client left is mended for a Messages upstream, as the Chat and Responses paths mend theirs
What changed: buildAnthropic (every request built for a Messages upstream: a Chat or Responses client's conversation translated, Zed's bridge) now runs its messages through pairToolBlocks, as buildChat's pairToolMessages (#554) and the relayed Responses path's pairToolItems (#1341) mend theirs. Anthropic refuses a tool_use the next message's tool_results don't answer ("`tool_use` ids were found without `tool_result` blocks immediately after") and a tool_result naming a call it never saw ("unexpected `tool_use_id` found in `tool_result` blocks"); an interrupted turn leaves the first behind, a client that dropped a call the second. A call left unanswered gets the synthetic result the other paths make; an answer to no call becomes a text block keeping what it said. A well-formed exchange is built exactly as it was (ids in their places, results in the order the client sent, text after them). TestZedToolResultSaysIsError's fixture carried a result for a call the request never made; it asserted the orphan went through as a tool_result, which the cloud refuses. It now goes out as the text it said, and the test says so. Run: - /tmp/sbx.sh test -tags nogui -count=1 -run 'TestMessages' ./internal/gateway/ with the pairing call taken out: 6 FAIL (trace "user assistant(A)", and the end-to-end one 400 "unexpected `tool_use_id` found in `tool_result` blocks"); with it back in, all pass - /tmp/sbx.sh test -tags nogui -count=1 ./internal/gateway/ — ok - gofmt -l (nothing), go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... (the trayimage_darwin.go -Wenum-conversion warning as on main), go build, GOOS=linux go build -tags nogui, GOOS=windows go build Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> |
||
|
|
d4c2512d2d |
usage: apps report their own calls with POST /v1/magpie/usage/requests, backfill included (#1874)
What changed
- POST /v1/magpie/usage/requests (internal/gateway/usage_ingest.go) takes
one record or an array, in usage.jsonl's shape:
- the post may carry up to 5000 records and 32 MiB;
- t, agent, provider, model and rid are required.
Each field is checked: unknown fields, quoted numbers, negative or absurd
counts, a status outside 100-599, a cost over 10000 USD, and a t more
than an hour ahead or before 2000-01-01T00:00:00Z. Any fault refuses the
whole post with a 400 that names error.index and error.param, and nothing
is written. A past t is otherwise taken as given, so history can be
backfilled. The reply gives accepted and skipped counts and each
record's index, rid and status.
- Access: lanGuard's rule (this machine, or another with a key while
shared, behind the Host check). A browser page also needs a key, since
corsGuard lets localhost pages and Origin null through. A held key is
refused.
- usage.IngestReported writes under usage.mu to the same file as
usage.Append. Rows carry source "reported" and no caller key. A rid
already reported is skipped, as is one repeated in the post. The set of
reported rids is read back from the log: one scan after a restart (lines
without the reported mark aren't parsed), then only what was appended.
- Pricing: a record with cost keeps it (Record.OwnCost, the rowOwnCost
flag; packed flags widened to uint16). Otherwise it is priced at
magpie's prices.
- Display:
- SourceReported is a source of its own: RequestPage.Reported,
?via=reported, and Ledger now honours via.
- The Requests tab gains a fourth cell "reported by apps", shown once
there are some, and a "Reported" badge (en, zh, zh-TW, ja, de).
- Nothing live: Record.IsReported keeps reported rows out of:
- a key's budget/spend limit (budget.counts);
- window holds, and the log start that decides whether a window can be
reckoned (logSnapshot.firstOwn);
- gateway sessions and Vias;
- Codex's sealed answers and remembered model.
There is no OTel span, rate limit, rest or alert for them.
- Docs: gateway-sessions.md, reference.md (with a curl), integrating.md,
site integrate.html (en, zh).
Why: the reporter's apps call vendors directly, and their usage (and
history) should show on the Usage page without becoming live traffic.
Run, in a worktree with sandbox HOME and a private GOCACHE
- gofmt -l: clean.
- go vet ./...: darwin, GOOS=linux -tags nogui, and GOOS=windows.
- go test internal/usage, usageapi, budget, gateway, gui: ok.
- -race -count=3 of the new usage/gateway tests: ok.
- GUI with playwright 1.62.0:
- usage-ledger-reported.test.cjs, 26/26 in chromium and webkit (5
languages, 1180 and 420 wide, light and dark);
- usage-ledger*.test.cjs, ledger-*.test.cjs, usage-sum-whole,
usage-unpriced-sum and i18n-keys: all pass.
- Timings with 200k reported rows (47 MB log, darwin):
- 40 posts of 5000 took 0.40 s (worst batch 18 ms);
- the first post after a restart took 0.45 s (rid rescan), a later one
1.6 ms;
- the cold index build took 2.1 s (as for gateway rows);
- page all took 27 ms warm, page 30d 39 ms, all via=reported 0.53 s;
- summary all took 215 ms, 30d 20 ms.
Broken by hand, each went red, then restored
- Go: dedupe against stored rids; the restart scan; CostAt ignoring own
cost; the block pricer overwriting own cost; the Reported split;
fromBrowser's key rule; skipping bad records instead of refusing; the
max-records and body limits; the ingest lock (race); both locks;
firstOwn -> first; the IsReported guards in windowHolds,
buildGatewaySessions, buildVias, budget.counts and loggedAnswers.
- GUI: the fourth cell, the --vias column count and the badge class.
Not shown red on its own: the remote-no-key and evil.example refusals come
from lanGuard and corsGuard before the handler, so breaking only the
handler's own check stays green. The codex_memory guard is not tested
alone: a reported row has no Requested there anyway. Not tried: a real
client against a live gateway, Windows/Linux runs of the tests, the full
GUI suite.
|
||
|
|
84cd81533e |
gateway: the client's comment points at where the ChatGPT backend's HTTP/1.1 rule now lives (#1700)
The previous #1700 commit deleted gateway/codex_http1.go and moved the rule into netproxy.HTTP1, which provider/codex_http1.go sets; the comment on the gateway's client still named the deleted file. Review of #1700 (no other change needed): every Codex request magpie makes goes through a netproxy.Dispatch transport, http.DefaultClient's (codexModels, warmCodex, accountJSON for /wham/usage and the reset credits, consumeCodexReset) or the gateway's s.client (turns, /models); the HTTP/1.1 clone keeps netproxy.Func, or the account's own proxy, and Clone deep-copies TLSClientConfig, so clearing NextProtos there leaves the base transport offering h2 to every other vendor. Run on 7485065d (the cherry-picked #1700, sandbox HOME, private GOCACHE): go test -tags nogui ./internal/netproxy ./internal/provider ./internal/gateway pass; -race on TestDispatchHTTP1, TestWith, TestCodexBackendOwnRequestsOverHTTP1, TestAccountProxy (provider and gateway) and TestCodexBackendOverHTTP1 pass. Broken by hand: with netproxy.HTTP1 left nil, TestCodexBackendOwnRequestsOverHTTP1 fails (all five requests "HTTP/2.0 (h2 offered)") and the gateway's TestCodexBackendOverHTTP1 fails ("asked over HTTP/2.0"); without the NextProtos reset TestDispatchHTTP1 fails ("malformed HTTP response", the server took h2 from the hello). gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean; linux and windows builds. Not reproduced: the reporter's PROTOCOL_ERROR itself. Co-authored-by: appointat <65004114+Appointat@users.noreply.github.com> |
||
|
|
abdc4b113d |
netproxy, provider, gateway: every request to the ChatGPT backend goes over HTTP/1.1, magpie's own too, not only the gateway's turns (#1700)
|
||
|
|
743e330085 |
gateway: a system prompt or message that only quotes a compaction prompt is no longer taken for a compaction; the prompt must lead (#1635, jueda12)
What: compacting() looked for an agent's compaction prompt anywhere in the system prompt (strings.Contains) and its ask anywhere in the last user message. Minis puts the user's memory after its own prompt in every request, so a memory that held Minis's compaction line made every turn of that conversation a "compaction", routed to the compaction rule's model (28 requests in a row in the report, one with 4 tokens of chat). Now: - a compactSystems prompt counts only when it begins within compactLead (2048 bytes) of the system prompt's start: alone, or behind a short lead (Claude Code's billing header and identity line, which its Anthropic system blocks join with no separator, so a line-start check would miss it); - a compactAsks ask counts only when it begins within compactLead of a text part of the last user message (Claude Code 2.1.296 puts its ~420-byte "CRITICAL: Respond with TEXT ONLY" preamble first; Codex and Kimi start the part with it). Minis's END OF CONVERSATION TO COMPACT. follows the whole conversation in one part, so it counts only in a part that opens with Minis's own "Compact this conversation into a context summary:". - Kimi Code's own compaction system prompt (kimi-cli 1.52.0, soul/compaction.py COMPACTION_SYSTEM_PROMPT) is added, so Kimi stays found without relying on the ask's part alone. The approach (a leading window instead of the whole prompt) and the test TestCompactingIgnoresQuotedPromptInSystem are jueda12's. Their sample put the quote ~30 bytes into a short system prompt, which a leading window still takes, and no rule can tell that apart from a short real lead; the test puts the memory behind a long agent prompt, as Minis sends it. Run (go1.26.8, sandbox HOME, private GOCACHE): - the prompts were checked against the installed Claude Code 2.1.296 binary (the hnn preamble, then "Your task is to create a detailed summary…") and kimi-cli 1.52.0's compaction.py (prompt in its own part). - break checks: main's compacting.go -> TestCompactingIgnoresQuotedPromptInSystem FAIL (memory, claude code taken; kimi not taken) and TestCompactingAsksWhereTheAgentPutsThem FAIL (minis marker quoted, ask deep in a paste); leads() without the window -> the same, minus Minis; the Minis opens check dropped -> "minis marker quoted: taken for compacting". Restored: pass, with TestCompacting, TestCompactingMinis, TestRuleCompact, TestCompactionBrokeOffKeepsTheStick. Not run: a real Minis client (the reporter offered to check with the memory that still holds the line). Co-authored-by: jueda12 <180685381+jueda12@users.noreply.github.com> |
||
|
|
df29a511e6 |
gateway: Claude Desktop's model menu names a model as the agents' lists do, by the Provider in model names setting (#1746, marsxxl)
/v1/models for claude-desktop named every model by its own name alone, with its provider's id in parentheses only where two read the same (desktopNames, |
||
|
|
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
|
||
|
|
1e080cc7e7 |
gateway: the saved Anthropic-to-Responses body carries the image's detail auto that the commit before it sends (#1474)
TestUpstreamBodiesUnchanged (
|
||
|
|
bbc7ee0a96 | gateway: an image Claude Code sends to a Responses provider carries detail auto, so a strict upstream (vLLM) no longer refuses it with 400 (#1474, zacharyxz) | ||
|
|
b3805203d8 |
gateway: drawing reads a relay's whole model list for which key serves an image model, and a key's 404 about the model asks the next key (#1657)
What: Provider.Serves now reads a new catalog.LiveAll (the fetched list
with image and video models kept) instead of live(), which drops Draws and
Films models. The draw key loop and the custom video path move on to the
next key when a key answers 404 whose body says the model isn't served
(keyLacksModel = 404 + modelRefused's wording); any other 404 still stops.
Why: wangru8080's analysis on #1657. A relay whose per-key lists name
gpt-image-2 under one key only still had drawing try a key that lacks it:
Serves read a list with the image model filtered out, so every key looked
unlisted, and that key's 404 "Model ... is not supported by any configured
account in this group" ended the loop instead of asking the next key.
Embeddings already move on any error short of the last key.
Run (sandbox HOME, private GOCACHE, worktree at origin/main
|
||
|
|
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
|
||
|
|
dc2e1cc124 |
gateway: MiniMax's and Volcengine Ark's refusals of thinking turned off are asked again with it left to the model (#1141)
thinkingOffUnlessAsked turns thinking off on a Messages request for a
non-Claude model that doesn't mention it (Claude Desktop's model_validation
probe, its health probe, title generation). MiniMax-M3.1-Flash-Preview and
Ark's glm-5.3 / glm-5.3-flash refuse that with 400, in wordings neither
alwaysThinks, mandatoryReasoning nor thinkingOffRefused matched, so the 400
went back to the client and Desktop wouldn't switch to the model.
alwaysThinks now matches the reporters' literal messages, narrowly:
- MiniMax: `requires adaptive thinking; thinking.type="disabled" (including
reasoning.effort=none) is not allowed (2013)`
- Ark: "thinking.type `disabled` is not supported by this model"
Both retry sites use it: the relayed Messages path (withoutThinkingOff,
gateway.go) and the translated Chat/Responses path (thinkingBackOn).
Tests: TestAnthropicPassthroughMiniMaxArkThinkingOffRefused (each vendor's
body: omitted thinking succeeds after one retry without thinking; adaptive
goes once, as sent; another 400 of MiniMax's own 2013 and a near Ark
wording "top_k is not supported by this model" are not retried), and
TestTranslatedThinkingOffRefused now runs the GLM, MiniMax and Ark wordings.
With the regex change reverted both fail (400 handed back). The JSON
envelopes around the reporters' messages are assumed (Anthropic's error
shape); not tried against the live MiniMax or Ark endpoints.
Run (sandbox HOME, private GOCACHE, worktree at origin/main
|
||
|
|
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
|