f2eb56c6bbde1300dddc402861b59cd4e45e0215
151
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
86fef947e8 |
gateway: a 200 stream ended with finish_reason "error" fails over (#2471)
What changed: a vendor that ends its 200 stream with finish_reason
"error" - WorkBuddy's and a DeepSeek harness's word for a turn it failed
rather than finished - had the chunk taken for content: the held stream
went to the agent, the try stood as a 200 success, and the group's next
member was never asked. streamEvent now reads the word as the failure it
says, held for the next candidate as an error event before content is;
in the candidate walk the try fails as an empty reply's or a cut-short
summary's does (#1221, #2274): the next is asked, and nobody rests, as
the reply's shape failed, not the account. Content already passed to the
agent can't be taken back, and is not touched.
Run: TestFinishReasonErrorFailsOver (new) red on
|
||
|
|
cfcd6648fc |
gateway: Chinese that says the input is too long is an overflow, Chinese pace words a rate limit (#4420)
A group member answered 400 "内容太长了,请精简输入或开启新对话" once a turn passed ~730K on a model it declares at 1M. tooLongRe's Chinese only matched wordings that name 上下文, so the try was filed as a plain failure that rested the member, and the group's other members were never asked. Reported by MYCF711 (Discord, issue #4420). tooLongRe gets a third line for Chinese that names what was sent (内容, 输入, 文本, 提示词/prompt, 问题, 对话, 消息) beside its length: "…太长/过长/ 超长", "…超过/超出…长度/token/字数", "输入长度/token…超过", and "字数太多/过多". Tied to: the reporter's vendor, z.ai's 1261 "Prompt 超长", iFlytek Spark's 10907 "token数量超过上限。对话历史+问题的字数太多,需要精简 输入". Left out on purpose: bare "超出最大长度" (a field's length), bare "token数量超过上限" (a day's allowance is said so too), "输出过长" (the reply), and "请求体过大" (a 413 byte limit, already handled by status). paceWords gets Chinese pace words (速率, 频繁, 频率, 限流, 并发, 每秒/ 分钟/小时/天/日, 稍后再试/重试), so "内容太长,已达到速率限制" is a rate limit, not a size. rateWords gains 过于频繁/速率 and quotaWords 频繁/速率, so such a 400 is asked of the next account and such a 429 is failRate. Tests: - TestEveryVendorsOverflow: 8 Chinese rows (red on the old code, each). - TestChineseNotTooLong (new): pace-with-size, a field's length, the reply's length, a day's token cap and plain errors aren't overflows; the pace 400 is retryable. - TestChineseInputTooLongGoesToTheNextMember (new): two-member group, the reporter's literal words, raw and \u-escaped: member b answers, failOverflow, nobody rests (red on the old code: a 1, b 0, 400 to the agent). - docs/subsystems/gateway-routing.md names the new wordings. Run (mote, via mote-run, at this tree): - go test ./internal/gateway -count=1 -timeout 45m: ok 500.9s - go vet ./internal/gateway, GOOS=linux and GOOS=windows: clean; gofmt -l clean - Broken by hand: old gateway.go/routing.go/fallback.go with the new tests: all three tests red (11 failures). paceWords alone reverted: TestChineseNotTooLong red on 4 pace messages and the retryable check. Not tried: the reporter's real vendor (unknown which member it is), nor a real z.ai or iFlytek account; the wordings come from their docs. Only internal/gateway was run, not the whole repo; the change is inside that package's classifiers. |
||
|
|
067e4c4846 |
gateway: Raccoon's token wall (user_model_rate_limited) isn't asked again in place (plugins#512)
SenseTime Raccoon answers an account whose token throughput is used up
with 429 {"error":{"code":"user_model_rate_limited","message":"您的模型请
求频率超限,请稍后重试","type":"rate_limit_error"}} and no Retry-After.
Its words read as a short rate limit, so the lone account was asked again
by the same-one retries (passing: 1, 2, 4s) and then by the plain
provider's patience (busy/replan: 2, 4, 8, 16s): eight asks in ~38s,
each one resending the whole ~88k-token request into the bucket it was
waiting on (cycocyco's numbers in plugins#512).
A 429 whose error.code is in wallCodes (only user_model_rate_limited) is
now neither passing nor busy. It still reads as failRate and rests as one
(a minute, doubled each time it comes back, up to 30 min, rateRest), so a
group's next member or the provider's next account is asked, and a lone
one hands the agent the vendor's error after one ask. The code is matched
at error.code only, not as words anywhere in the body. Other rate limits,
the same Chinese words under another code included, are retried as
before. The plugin passes the vendor's body through unchanged, so this is
the place for it.
Run (mote, at this change on origin/main
|
||
|
|
c37b8b6594 |
gateway: a remote magpie's out-of-quota refusal is asked again, not replayed here (zaidu259434 on X)
A routing group on another computer's magpie had one member, Open Design, out of its Coding Plan quota and wallet. This magpie rested that remote model (remoteModelRest) and, through quotaHeld, gave the 402 again on every request until the time it named, never asking the remote. The user moved the group to another vendor there, and Codex here still got "Remote magpie: Open Design: [code=insufficient_balance] ... (out of its allowance: not asked again before 06:19)". The remote magpie routes its own groups and holds its own rests, and what it serves under a name can change there at any moment. A rest from remoteModelRest is now marked (Rest.there), and quotaHeld passes it by: the remote is asked, and answers from its own hold at once, or from what it serves now. The rest still puts the model behind the others in a local group. verifyHeld is unchanged: its hold is a minute, and TestRemoteMagpieVerifyHeldOnTheModel asks for it. Run (on mote, at |
||
|
|
750bd1bb69 |
gateway: Factory's usage policy refusal reaches agents as a refused request, not a failed sign-in
sweanng (Discord #general, ZCode + Factory + GLM 5.3) got Factory's
usage policy refusal shown as "Provider authentication failed"
(reason=auth_failed status=403). The refusal is Factory's own; the label
was wrong. Factory refuses at 403 with code content_policy_rejected. The
Factory plugin (up to 0.1.39) handed it on as a 403 permission_error
with no code, magpie didn't know the code as a refusal, so the 403 went
through as is and the agent read it as an auth failure.
- policyRefusal knows content_policy_rejected (Factory's code, in its
own top-level and error.code shapes and the plugin's), so the existing
refusal path answers every protocol with 400 and its own request
error: Anthropic invalid_request_error, OpenAI chat and Responses
invalid_request_error, Gemini INVALID_ARGUMENT. Not asked again of the
same account; other accounts/members follow the Refusal retries
setting as for any refusal.
- restAfter leaves the account unrested for a policy refusal at 403 too,
not only 400 (it rested "other by backoff" before).
- The refusal note keeps up to 1000 bytes of the vendor's message, not
300: Factory's advice (start a new session or drop the quoted text)
and OpenAI's Daybreak link were cut.
- Factory mover min 0.1.40 (plugins #494, on npm as latest): the plugin
now answers this refusal as a 400 invalid_request_error carrying code
content_policy_rejected; its other 403s stay permission_error.
Siblings checked: Devin's plugin maps its content policy to 400, Qoder's
sensitive codes and Zhipu's 1301 are request errors already; Factory was
the one content refusal sent as a 403.
Run (mote, rebased on origin/main
|
||
|
|
bb3565309d |
gateway: a provider's listed reply headers and the vendor's request ids reach the agent (#4145)
codex-cn (#4145, and smtmsnyw on X: "Magpie代理把我原始模型响应头给吃了"): a relay's X-OneAPI-Request-ID never reached the agent, so a failed or slow call couldn't be matched with the relay's logs. What changes - provider.ReplyHeaders (`replyHeaders` in providers.json, the editor's Advanced > Reply headers, comma-separated): headers of the vendor's reply passed on to the agent, matched whatever their case, saved canonical. Request-Id, X-Request-Id and X-Oneapi-Request-Id go from every provider without being listed (DefaultReplyHeaders): opaque ids, under names magpie sets nothing of its own, and passthrough already passed the first two on a 2xx. Nothing the user set is overridden: the list only adds. - Never passed on, listed or not (ReplyHeaderPassable): Content-*, hop-by-hop and Transfer-Encoding (magpie writes the body it sends), Set-Cookie/Cookie/Authorization/WWW-Authenticate/Proxy-*/API keys, Access-Control-* and Sec-* (would let a page read magpie), Location, HSTS, CSP, Alt-Svc and the like, Retry-After/Cache-Control/Date/ Server/Vary/X-Accel-Buffering (magpie's own), and X-Magpie-* (the gateway reads those as notes of a try). Save refuses such a name (ReplyHeadersOK); the editor says why before the save in every language (replyHeadersOf), its list held to Go's by TestReplyHeadersNeverAsTheProvidersAre; a name written by hand is dropped on read. Where it's applied - One choke point: forward (every model API, relayed or translated, a plugin's fetch, a signed-in account) and retrieveAs (embeddings, audio) tell the reply they return to the try that asked, through the try's context (withReplySink/heardReply). The sink is the try's holdWriter, so a try that fails and is let go takes its vendor's headers with it: a fallback's reply carries the answering provider's alone, and a failure released to the agent carries its own. Only the try's own provider is heard (a side model or searcher isn't); within a try the last reply replaces earlier ones (a refused beta asked again, a Mantle reroute); after the try has its status nothing more is heard (a cut reply's continuation). count_tokens writes them directly, and the passthrough effort-none probe's kept refusal counts as the reply. - Not covered: images and video (#4211), and the Codex backend relay (which copies its reply's headers whole already). A stream whose headers keepAlive sent before the vendor answered (past keepHeldAfter) can't carry them. - Docs: providers-accounts.md (Reply headers row), gateway-routing.md. What was run - New tests: TestReplyHeadersPassedOn (Anthropic relayed and Chat translated x whole and stream x 200 and 400), TestReplyHeadersOfThe- ReplyGiven (429 then fallback to another provider), TestReplyHeadersOnCountTokens, TestReplyHeadersOnEmbeddings (200 and 400), TestReplyHeadersList, TestReplyHeadersNeverAsTheProvidersAre: pass on mote (macOS), on xiaomi-gpu (win-run) and in WSL (wsl-run). - Broken by hand: without the main loop's withReplySink every TestReplyHeadersPassedOn subtest and the fallback test go red (ids ""); with the deny map ignored, Set-Cookie passes and 8 subtests go red; without count_tokens' passReplyHeaders its test goes red. - gofmt -l clean; go vet ./internal/... for darwin, linux (-tags nogui) and windows: ok. - At this commit rebased on |
||
|
|
c3462d5fe8 |
gateway: a held stream gets its 200 after 3s, and a comment every 5s, so a proxy's 10s header cut no longer ends it 499
mrten_95615 (Discord, Windows): Codex through magpie to a relay ended 499
about 10s in once a turn's first token took longer than that. It happened
with a Clash-style app in system-proxy mode, not in TUN mode.
Cause:
- Codex (reqwest, hyper-util Matcher::from_system) sends its request for
127.0.0.1 through the Windows system proxy. ProxyOverride is read only as
IPs/CIDRs, so "127.*;localhost;<local>" doesn't keep it off. This was
checked on xiaomi-gpu with Codex 0.165.0: mihomo logged 127.0.0.1:18431
through the proxy.
- magpie held a stream's headers for up to holdLongest (15s) before
keepAlive sent the 200 and its first `: keepalive`. A proxy that stops
waiting for response headers after about 10s cut the request first, and
Codex's context ended, which shows as 499.
Fix: keepHeldAfter is 3s, not 15s. Once the 200 is out, keepHeldEvery
(5s) is the most a held stream goes without a comment. Another candidate
can still answer in the same stream, and a failure before 3s is still a
status with its Retry-After. gateway-routing.md is updated.
Run:
- TestHeldStreamHeardBeforeAProxyCuts (new) is red on the old code with
"headers 200 after 15.004s" and green after. It is green on mote together
with the keepalive, queue and held tests (-run
'TestHeldStreamHeardBeforeAProxyCuts|TestSilentHeld|Queue|Keepalive|KeptAlive|Held',
ok 68.6s).
- End to end on xiaomi-gpu (Windows 11): Codex 0.165.0 goes through the
system proxy, which is a Go proxy that cuts after 10s without headers,
then magpie serve in a sandbox HOME, then a relay that holds its headers
for 15s.
- Old build: the proxy logged "CUT after 10.001s" on every try, the relay
logged "client gone after ~10s", and Codex kept "Reconnecting... n/5".
- New build: "headers 200 after 3.005s", then done at 15.0s, and Codex
printed pong (exit 0).
- The registry proxy settings were restored afterwards (ProxyEnable 0, no
server or override), and none of the test processes were left running.
- On mote: gofmt -l is clean, and GOOS=windows/linux go vet -tags nogui
./internal/gateway/ is ok.
- On mote: go test -tags nogui -count=1 -timeout 45m ./... is ok except
internal/gui TestCoreScriptBudget (1531531 > 1530861). That is red on
main already, filed as #4133, and is not touched here.
Not tried:
- The reporter's own proxy app. mihomo's HTTP inbound doesn't cut by
default, so which part of their setup cuts at 10s isn't known.
- A proxy that cuts on idle bytes rather than headers, end to end. Only the
test's gap check covers the 5s cadence.
- Why turning the system proxy off didn't help until the app quit.
|
||
|
|
b4267de595 |
gateway: a provider's fallback can be a routing group, routed as the group
01huadalang on Discord: "还有备用模型增加路由组的选择,现在只能选模型". A
provider's Fallback list held models only; a "group/<id>" entry resolved
to the group's first member alone. Now such an entry is served through the
group, as a request to the group would be:
- plan → planPaused: a fallback naming a group (provider.FallbackGroup,
the group as routed, Live) hands its members to planLevel
(planFallbackGroup): the group's own routing, its sink and asides, and
its pause rules (serve passes provider.PausedOut for the agent's folder).
Its trace rows are marked Fallback with the group in Via.
- No loop, each provider/model once a round: a member that is the primary,
a model named earlier, or another fallback group's member is left out
where it comes second. Groups have no fallbacks of their own and a
member's fallbacks are not followed, so nothing leads back. A group that
is gone or off is passed over, as a model none serves is.
- Every sibling that reads p.Fallback now reads a group's members through
provider.FallbackModels: redaction (unredactedRoute: an unmasked
provider with a fallback group holding a remote model is masked),
careful accounts (carefulOf), native compaction, Codex's own turns
(codexFallsBack) and Claude's auto-mode review (claudeReviewed, which
moves from provider.Resolve to ResolveRoute, as the gateway reads
fallbacks).
- CLI: `magpie provider fallback` already took group/<id> (Resolve knows
groups); its usage and error now say so. Pinned by
TestFallbackCmdTakesGroup.
- GUI: the provider editor's Fallback picker lists the routing groups
(providers.gateway.groups) beside the models as chips with the Routing
fan and a muted "routing group" tell; a picked group's row has the same
fan and tell, and a gone one says "No routing group {id} now; it is
skipped". A filter matches a group's name, id and its members'
providers. New strings in zh, zh-TW, ja and de.
- app.js budget raised 187 bytes on main (1,311,922; core 1,531,060), the core's
own editor, no room added; the addition was cut from ~900 bytes first.
- docs/subsystems/gateway-routing.md: the Candidates row says all this.
Not done: a fallback group's turn rules (ruleFor/ruleOver, which can ask
a classifier) are not applied. The plan is made before the primary is
tried, so they would cost a classifier call on every request the primary
answers. Its routing order, sink and pause rules are applied.
Run (at f6e7214af; after the rebase, the last bullet):
- gofmt -l: clean. mote: go build ./...; go vet on the touched packages;
GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...: ok.
- mote: go test -timeout 45m ./...: every package ok except internal/gui:
TestCoreScriptBudget (fixed above, then ok) and ten AppKit window tests
(TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt, TestMainWindowCorners
…) killed at their 30s bars while four other sessions' GUI suites held
mote at load 70-110. Run alone, all ten
pass (TestDockJoinLeadsCommandTab skips) except TestMainWindowCorners,
red at base
|
||
|
|
3627742104 |
gateway: an error read as out of credit moves on at any 4xx (#4095)
mycf_711 (#4095): SuperMagic answered an account with no points left 400 "非常抱歉,当前对话需要调用大模型 / 付费工具,您的可用积分已不足。 您可以点击右上角「用户头像」,通过「充值」通道补充积分…". failure() read it as failCredit (creditWords: 充值), but retryable()'s 400/422 branch asked quotaWords only, which has neither 积分, 不足 nor 充值. So hw.failed() was false: the 400 went to the agent while another account in the order had 6,467 points, and the empty account was never rested. retryable() now takes any 4xx failure() reads as failCredit, after the overflow check, so the two deciders agree on credit at every status (400, 422, and the 4xx outside the always-retried list, 409 say). Sibling: shapeRefused() kept out quotaWords but not creditWords, so a shape refusal saying 请充值 would rest nobody; it now keeps out both. Quota: usedUpWords (failQuota) is a subset of quotaWords, so 400/422 already agreed; a quota word at another 4xx (413's "exceeded the limit" is the request's size) is left alone on purpose. Tests (credit_400_test.go), with the reporter's literal body: TestCreditRefusalIsRetryableAtAnyStatus (400/409/422, raw and as magpie tells it on, plus shapeRefused) and TestCredit400MovesToTheNextAccount (two keys: the empty one 400s, the next answers 200, the empty one rests as credit 400, the next request goes straight past it). docs/subsystems/gateway-routing.md says it. Broken by hand: with the new case disabled and creditWords taken out of shapeRefused, both tests are red (every status not retryable, the shape case rests nobody, the request ends 400 after k-empty alone). Run on mote, at |
||
|
|
3ec25523cb |
provider: a plugin's 401 about the model keeps the account's sign-in (plugins#468)
A plugin that answered "this model isn't available on your plan" with 401
marked the account as needing a new sign-in, and the gateway fails a 401
over to the provider's next account (retryable in fallback.go), so every
account of the provider was marked "sign-in has expired" for credentials
that were fine.
notePluginSignIn now reads a 401 that carries no X-Magpie-Sign-In as
"kept" when its body says the model isn't served (provider.ModelUnserved,
the gateway's unservedWords moved here, read decoded by catalog.Words)
and nothing of a token, key, credential, session or sign-in. Only the
first 64KB is read, and the body goes on whole.
Not changed: the gateway still rests the account under its failure
backoff for that answer; modelRefused still reads only 400/403/404/422 as
the model refused. The guide asks for 403/404 (docs commit).
The 401 bodies the community plugins hold for a sign-in that is gone
(magpie-community/plugins 95fa761, every package's tests), each in the
test's "marks" list and none read as kept (none names a model, which
ModelUnserved needs):
- devin: {"code":"unauthenticated","message":"invalid api key" / "bad key"}
- zed: "unauthorized", "", {"code":"upstream","message":"bad key",...}
- cline: {"error":{"message":"nope"}}, {"success":false,"error":
"unauthorized"}, {"message":"expired"}, "the sign-in lapsed — sign in
again"
- raccoon: "unauthorized", {"code":200003,"message":
"authorization_verify_error"}
- joycode: {"code":401,"msg":"登录票据已失效"}, "private-marker"
- zcode: "", {"code":1001,"msg":"Authorization Token非法"},
{"error":{"message":"token expired or incorrect"}}
- mimo: "", {"code":401}, {"error":{"message":"stale"}},
{"error":{"message":"Invalid API Key"}}
- cursor: "no", "Unauthorized — sign in to Cursor again in magpie",
Connect's ERROR_NOT_LOGGED_IN body
- search1api: {"message":"expired"}
No plugin source builds a 401 whose text names a model.
Run (mote, at this tree): gofmt -l clean; go vet ./..., GOOS=linux go vet
-tags nogui ./..., GOOS=windows go vet ./...; go test -tags nogui
-timeout 45m ./...
(go test -tags nogui -timeout 45m ./... at base
|
||
|
|
df9376592d |
routing: a group's member may offer several reasoning levels for the agent to pick among
Garydesu on X: "能不能让路由组里的模型设置多个可选推理强度,现在只能选一个或者整个 路由组的". A member was one fixed `:effort` or followed the group's levels. A member's suffix may now join several levels with "+", `provider/model:low+xhigh`, kept lowest first, each once. provider.MemberLevels splits it into Member.Levels and leaves Effort empty, so the member isn't fixed; one level is a fixed effort as before. The whole stays the member's id, so rules, fast, off, weights, share and the CLI key it as any member. The gateway fits the agent's ask to the member's own levels (groupLevels returns the candidate's levels first; ofMember, the quiet check and the trace see them), and the group lists them to agents (buildGroupEntries), intersected with the other members' as usual. In the Routing page's group editor the member's reasoning menu has "Several levels…", a menu that stays open with each level ticked or not; a fixed level picked from the first menu replaces the old one as before. i18n in zh, zh-TW, ja, de; CLI help and docs/subsystems/gateway-routing.md say it. Run on mote (mote-run). Rebased on |
||
|
|
25fc92d59a |
fallback: a model unchecked in its provider's list is not a fallback to go to (#3911)
The sibling of the group fix before this: a provider's Fallback list
resolved each entry with Resolve, so a fallback the user unchecked in
its own provider's list was still sent to, while the fallback editor
says "No provider serves {id} now; it is skipped". plan's fallbacks,
and the places that read the same list (carefulOf, native compaction's
carrier check, unredactedRoute, codexFallsBack), now resolve through
provider.ResolveRoute, which skips it. ResolveRoute scans the entries
once for the one model rather than building a map per request.
Test: fallback_unpicked_test.go, plan/m answering 429 with fallbacks
a/x (unchecked) and b/x goes to b and never to a.
Run (mote): red on the previous commit's tree ("from ka", a tried
[ka]); green with this one. Full suite as recorded in the previous
commit, which ran at this tree: 76 packages ok, internal/plugin's
TestGatewayHookMixedPiPackage red at load ~134 (#2865), passing alone.
go vet darwin/linux/windows clean.
Not tried: a real provider with a fallback in the app.
Co-authored-by: timonwong <timon86.wang@gmail.com>
|
||
|
|
e68327b217 |
gateway: an error carried in a 200 fails as its own status would
monater (Discord, #general): an OpenAI-format custom provider answered
gpt-6.1-sol with HTTP 200 carrying "Rate limit reached for gpt-6.1-sol
... on tokens per min (TPM) ... Please try again in 6ms." failure(200, …)
skipped every 429 case and fell to `status < 500 && usedUpWords`
("limit reached"), so the try failed as quota and rested 15 minutes,
shown as "200 quota used up". The same text as a real 429 has been a
rate limit since v0.1.1748.
One classifier: carriedStatus maps a 2xx/3xx body through streamStatus,
the reading already used for an error inside a stream, in failure,
failureOf and restAfterMarked. Words streamStatus doesn't know (its 502)
keep the 200 and read as before. insufficient_quota maps to 402 and
stays credit, as at 429.
Siblings:
- non-streamed 200 whose body is only an error (OpenAI/Gemini
{"error":…}, Anthropic type:error, a failed Responses object):
errorReply, read in holdWriter.settle, fails the try with that status,
so it is retried or handed on instead of going to the agent as an
answer; unheld, the passthrough sniffer books it failed (settleWhole),
so the Requests list shows it red with its words.
- translated route (an Anthropic/Responses/Gemini client to a chat
provider, plugins included): an error event with no status went out as
502 and failed as "other"; it now takes streamStatus's status.
- Streamed passthrough with content then an error (the reporter's path)
is covered by the failureOf/restAfter change.
Not changed: Codex's ChatGPT backend (always streams; its error events
already go through the same failure()), Claude Code's bridgeFailed and
tool_loop's relayStatus (own statuses).
The Requests list needed no change: a row with err is shown failed
(ledFailed_), "200 · <err_type>" with the reason as its tooltip.
Tests (carried_error_test.go, the reporter's literal text): failure and
failureOf at 200 equal 429's for it and for minuteLimitBodies,
restAfter at 200 is a rate limit's minute at 429, errorReply, the
sniffer, and end to end: a chat 200 error body and a Responses failed
object retried as rate and answered, a chat stream with content then
the error resting as rate at 429, and an Anthropic request translated
from a chat stream failing as rate.
Broken by hand: carriedStatus returning the status unchanged turns
the unit, rest and stream tests red (quota, 14m59s, Status 200: the
reported behaviour); errorReply off in settle turns both retried-body
tests red (the error went to the agent as a 200); translate back to
502 turns the translated test red ("other"); settleWhole a no-op
turns the sniffer test red.
Run (mote): go test -tags nogui -timeout 45m ./... at
|
||
|
|
08b02cf18c |
providers: a pool stops at its caps and reads usage again near them (plugins#349)
What was adopted on magpie-community/plugins#349 (1939869736luosi): one
place, in the GUI and the CLI, for a subscription's account pool, and an
opt-in conservative mode.
- Stop at the caps (Provider.CapStop, off by default): once every account
in use is held at its cap, the request is answered 429 rather than going
on to the provider's fallbacks (plan returns restLast). Off, as before.
- Check usage again near a cap (Provider.CapCareful, off by default,
internal/gateway/cap_careful.go): before planning, a capped account's
usage is read again when its reading is over 15s old within 5 points of
a cap, or over 5m old at all; the request waits at most 10s, and a
failed account is asked again at most every 15s. An account whose usage
was never read, whose last read failed, or whose reading is still that
old is then held as one at its cap is (capHold "unread", traced as
Weighed.Unread, named in the 429 with "--careful off"). Generic: it
goes by provider.UsageRead/ReadUsageNow, so every subscription that
reports usage windows (Codex, Claude, plugins) gets it.
- provider: usedCache records each account's read state; a failed read
keeps the last good reading's time. ReadUsageNow no longer reports
false when the read had already finished on the first ask.
- GUI: under the provider's account list, once an account has a cap (or
either is on), two ticks for the above, and a note naming the accounts
in use with no cap ("used to 100% of each window"). Accounts, order and
caps stay where they were in that list. zh, zh-TW, ja, de added.
app.js 1,309,658 within its 1,310,460 budget, unraised: addRow and a
per-row forgetOf replace 3 add-button and 5 Remove-button builds.
- CLI: magpie provider pool <id> [--accounts a,b,…] [--cap percent|off]
[--stop on|off] [--careful on|off] shows and sets the whole pool.
- docs: gateway-routing.md and providers-accounts.md.
Run (mote, before the rebase at
|
||
|
|
b10f43e899 |
gateway: another magpie's key limit rests that magpie whole when relayed, and its marker stays here (#2791)
restAfterMarked reads a failed try's held header, which keepRetry fills from the upstream's reply. keepRetry kept Retry-After and the rate-limit reset headers but not X-Magpie-Limit-Reset (remoteKeyLimitHeader), so a remote magpie's gateway key over its own limit read as that one model's rate limit (remoteModelRest): the model rested alone and the remote's other models were asked into the same refusal. Patch by ggbdpq (#2791): their test and the cause are theirs. Changed from it: the patch whitelisted the raw marker into the held header, and holdWriter passes that header on to the client, so the marker reached the agent and, in a chain, a magpie asking this one, which would rest all of this magpie for one key there. keepRetry now sets an internal note (keyLimitThereHeader) that remoteModelRest reads and holdWriter drops, with answeredThereHeader. The two keepRetry sites that write to the client directly (count_tokens, decide_group) go through keepRetryOut, which drops both notes; answeredThereHeader leaked there before too. Doc sentence in gateway-routing.md. Run (rebased on origin/main): - TestRemoteMagpieKeyLimitRestsTheRemote (theirs): red with the note taken out of keepRetry by hand (rested office/glm/glm-5 and kimi, not office), green now. - TestRemoteMagpieKeyLimitMarkerStaysHere (new): red with the patch's raw marker copy ("the agent's reply carries X-Magpie-Limit-Reset"), and red with keyLimitThereHeader taken out of pass()'s strip list ("carries X-Magpie-Key-Limit-There"), green now. - RemoteMagpie|AnotherMagpie|KeyLimit ok; the whole internal/gateway package (-tags nogui -count=1 -timeout 45m) ok in 476s at fc860f2e6. - gofmt -l clean; go vet ./internal/gateway for darwin, GOOS=windows, GOOS=linux -tags nogui clean. Not tried: two real magpies over a network with a key limit hit. |
||
|
|
47175a68ff |
gateway: an error in a kept-alive stream names the model the agent asked for (#3728)
jilen (#3728): fx asked magpie for codex/gpt-6.1-sol on /v1/chat/completions and showed "system: InvalidChunk: Invalid Chat Completions response at model (event 1).", while the usage log had the vendor's 502, an EOF from chatgpt.com. No stream was saved, but fx's InvalidChunk at event 1 says one had begun: magpie had kept fx alive with the stream's headers and comments, so the failure went as an event of that stream (streamError). The encoder streamError made, from an empty Request, began the message before the error with a Chat chunk whose "model" was "". fx takes a chunk with an empty model for a broken one and stops there, so it never read the error after it. Anthropic's message_start and Responses' response.created, response.in_progress and response.failed went out with an empty model the same way. keptAlive now keeps the model the request names when serve takes it, as magpie spells it there: a flat id (a~m) is its catalog id, a dashed Claude id its dotted one, and Codex's own model through magpie's accounts codex/<model>. An effort the agent put on the model is kept on it (a/m:high), the name it asked by. serve has it from the body it already read for askedAt; on Codex's own sign-in (codexUpstreamOn) it is the model Codex wrote, which its turn already read. Neither reads the body again. streamError begins with that model, from failTo, holdWriter.release and Codex's failWith. Gemini's error names no model, as before. docs/subsystems/gateway-routing.md says so. fx still shows no reason. Its Chat reader ends the stream with ProviderError at an event with an "error" key and keeps nothing of it (src/gateway/chat_completions_protocol.zig:723 in fx 0.0.14, :710 on fx's main e71a663b); only an error status's body reaches its message. So fx says ProviderError where it said InvalidChunk, and the vendor's EOF is in the stream and magpie's usage log, not in fx. Not changed: an error after a reply that already went, a loop cut's (cutLoop), starts a message of its own after the vendor's, under a new id. A model in it wouldn't help, fx stops at the new id: #3792. Nor the error's shape: the encoders still begin a message ahead of it. fx looks for an event's "error" before its id and model, so an error alone would get past it too, but no other agent was tried on one; that is #3792's question as well. What was run (tree 908b9857, on origin/main |
||
|
|
ff16f6c552 |
gateway: a remote magpie's providers are each a vendor of their own to a conversation (fremontdango)
fremontdango on Discord ran two magpies. On the local one, a routing
group held one model from two providers of the remote magpie
(office/first/m, office/second/m). Its conversations were kept as if the
two were one vendor, because both are the one remote-magpie key here
(candidate.who()). The same group made on the remote behaved
differently:
- strict: when the first provider ran out, the conversation failed over
to the second, though strict means it never moves
- session/auto: with the first gone, the "same account, other model"
match kept the conversation on the second as "session", though nothing
of it was cached there
- the second's refusal of the first's sealed reasoning was recorded
against the whole remote, so the first's own seals were then taken out
of requests to it
- a native compaction one sealed went to the other too
There is now a vendor identity for these: candidate.vendor() and
sameVendor(who, model). Behind a remote magpie it is the key plus the
remote's provider, the model id's first part (remoteUpstream). A remote
group is one vendor by its whole id, and a model named without a
provider is the key alone. It is used by:
- affine's widest match
- strictOnly and strictKeep
- unanswered
- refused/withoutRefused
- checkpointReaders (native compaction)
- Codex leadFirst
Lanes, requests a minute and leastHeld's per-model seat stay on who(),
the limits the user set on the key here. Sticks and compaction writers
are stored as before (who plus model), so the sticks saved on disk still
match after the update. Only the local magpie (the one with the group)
needs this version.
Run:
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway: ok
(559s) at 040a4ec29. After rebasing onto
|
||
|
|
6afbe3f304 |
routing: a member too small for the request keeps its row and says why (#3749)
roomy leaves out a member whose model's context window the request is longer than, and the trace dropped it from the order with no word of it: on the Routing page its row went away, and the reason was only an absence. Now the trace lists it in the route's left with Weighed.window set to the window it lacked. Its row stays, faded as a seat held out is, and says "request longer than its 200K window · passed over"; the why list says it is left out because the request is longer than its context window, and is asked only once every one with room is out of its allowance (en, zh, zh-TW, ja, de). When the last resort does ask it, its row moves from left to the order with window cleared, as askUnlisted and unhold move theirs. MYCF711's patch (pr/small-seats) added a Route.Small list and a row map fix. This takes their finding but not the shape: left already carries seats not asked (unlisted, capped, out of credits), so a new flag on Weighed reaches the page, the session copies and the last resort without a second list, and the row map bug they fixed doesn't exist on main. Limit: roomy fills smallW only when the order has one row per candidate (pl.order parallel to the candidates); a member left out otherwise still shows only by its absence, as before. Run: go test ./internal/gateway -run 'Roomy|TooSmall|Small|Window|Trace|Left|Unhold|AutoReset' ok; go test -timeout 45m ./internal/gateway/... ./internal/provider/... at fcf2a5271 plus this change: gateway ok (426s); provider crashed in TestUnreadLoginsWriteErrorsKeepCredentials (synctest close outside bubble, #3632) and with it skipped is ok. gofmt -l clean; GOOS=linux go vet -tags nogui and GOOS=windows go vet of ./internal/gateway clean. go test ./internal/gui -run 'CoreScriptBudget|I18n|Strings|Plugin' ok. tests/routing-small-seat.test.cjs (new), chromium and webkit, en/zh/zh-TW/ja/de at 1100px and 420px: 11/11 each. The routing, panel-routing and i18n GUI files, both engines, concurrency 3, load 40-280 from other sessions: 1468 tests, 1410 pass, 58 fail. The reds are in routing-pause (#3410), routing-rule-effort (#3411), intent-entry (#3408), keys-fold (#1612, #2658), live-patch (#3637), rule-remove (#3094, #3096) and the unfiled ones in #3786, plus seven more files (agent-hue-not-red, columns, order-unknown, rule-remove, levels, ctx-fold, many-keys). Those seven alone, one at a time: 68/81 here, 69/81 on origin/main |
||
|
|
d56c14e953 |
gateway: a single provider's busy or briefly rate-limited reply is waited out, for its own Patience (zoecats)
zoecats on Discord: a request to one provider (not a group) got a local
relay's short 429 straight back in Claude Code once the few same-one
retries were spent. A group would have held the agent and asked again.
A plain provider now takes the group's replan path (patience.go: replan,
pauseAlive, the held writer) once passing's same-one retries are spent:
its accounts take turns as members do, each pause never shorter than the
Retry-After, and a streaming agent gets keepalives past keepHeldAfter.
- Zero-config: unset, it waits singlePatience, PatienceDefault (60s),
counted from when the agent would have had the error.
- The user's value wins: Provider.Patience, the same values as a group's
Patience, set with `magpie provider set <id> patience=2m|off|default`
(at most 4m). The provider editor has no row for it (no new UI), and its
save keeps it. A group the provider is in keeps the group's own.
- Not retried: a Retry-After past the budget, quota/credit/plan limits,
401/403, refusals, response protection, didNotStream, and an agent
that has gone (499, try marked Gone).
- The try is traced with Again alone, so the Routing page tells it as
"tried again in …".
- codexReset (ChatGPT's 503 for a large request) is left out of the
plain-provider replan, so Codex still gets its 503 with advice.
- Codex's own one-account relay (codexUpstreamOn) does not join. It is
relayed outside the candidate loop, and its backend 429 is always the
plan's usage limit (codexBusy never retries one), so the short rate
limit this waits out doesn't arise there. Its overloads keep
lastRetries and then fallbacks.
longestPause became a var so tests can scale it. Tests updated for the
new count (1 + retries + replanRounds when it never clears):
- TestLastOneLeftIsTriedAgain
- TestRateLimitIsWaitedOut
- TestQueuedStreamFailureIsTheStreamsError
- TestOverflowTheVendorDidntSay
New tests, through the server with a fake upstream and injected
durations, waiting on trace state, not a duration:
- TestSingleProviderWaitsOutAShortRateLimit (stream and whole: 200,
keepalive before the answer, asked twice)
- TestSingleProviderPassesALongLimitThrough (an hour, quota, 401)
- TestSingleProviderAgentGoneInTheWait
- TestSingleProviderOwnPatienceWins (off, shorter and longer than the
default)
- TestPatiencePair (cli)
- TestProviderSaveKeepsPatience (gui)
Broken by hand, each red, then restored:
- singlePatience fallback 0 for a plain provider: WaitsOut stream and
whole got 429, and AgentGone never paused.
- replan's budget check off: PassesALongLimitThrough/an_hour, "magpie
waits to ask again".
- pauseAlive's ctx.Done case removed: AgentGone, "route done false
status 0".
- The gateway ignoring Provider.Patience: OwnPatienceWins off, shorter
and longer all red.
- The GUI save not keeping Patience: TestProviderSaveKeepsPatience,
"patience 0 … want -1 kept".
Run in this tree, before the rebase:
- go test ./internal/gateway ./internal/cli ./internal/gui: ok.
- ./internal/provider: ok with -skip TestUnreadLogins. That test crashes
with "close of synctest channel from outside bubble", the known #3632,
in filememo and not touched here.
- gofmt -l: clean.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
vet ./...: all 0.
- go build for darwin, linux (nogui) and windows: ok.
Run again after rebasing on origin/main
|
||
|
|
1360689ef2 |
provider: Served is shared while a request holds the catalog, not copied for each look (#3725)
Served built a fresh copy of the whole catalog on every call: the
unlisted groups' entries plus every provider entry. An Entry is ~1.3KB,
and a request looks at Served from outputLimit, userOutput, askedOutput
and windowIn, so with 12 providers of 20 models each look copied ~380KB
and a request ~800KB, all garbage by the reply.
Served now goes through heldFrom like providerEntries: one slice, built
once while a request holds the catalog and kept across requests until a
file it is built from changes. It is clipped, so a caller's append makes
its own copy and never reaches the next caller. The four gateway loops
take each entry by pointer instead of copying 1.3KB a step. Every
caller of Served (gateway, gui, cli, tui, agent, provider) was read for
writes into the slice or its entries; all only read.
Measured on BenchmarkZZIO (12 providers x 20 models, an 8KB request,
not committed): 1.57MB allocated per request before, 640KB after.
TestServedSharedWhileHeld: under Hold two calls give the same backing
entry, and an append to one doesn't show in the next. Red on the old
code (a new copy each call), green now.
Run at
|
||
|
|
b5d17b26e0 |
gateway: Antigravity's 429 to Codex's GPT-5 prompt says why and rests nothing, on the web-search path too (Jodiezzzzzz on X)
From Codex, every call to antigravity/claude-opus-5-5 failed with "exceeded retry limit, last status: 429" while dsh worked on the same account. The call was an agent_created_thread, and the vendor said "Resource has been exhausted (e.g. check quota)". Cause: a Codex thread begun on a GPT-5.x model keeps "You are Codex, an agent based on GPT-5..." as its first developer message after /model, resume -m or a fork, and magpie lifts it into systemInstruction. Antigravity answers that line with a fake 429, whatever quota is left, as it does Claude Code's (#666). Codex also sends a web_search tool every turn, so for an Antigravity model magpie serves search itself (translate -> searchReply -> askTranslated), and that path passed the bare 429 back: no hint, no 400, so Codex retried to its limit. - antigravityTurnsCodexAway: the two Codex GPT-5 opening lines count as a turned-away prompt; antigravityHint picks the Codex hint for them. - antigravityRound wraps the search path's ask, so its 429 and an in-stream refusal get the same 400, hint and no rest as translate's. - antigravityForeseen returns the hint, so a group skips Antigravity for the next 6h saying which prompt. - The Routing page shows the new hint (routing/client.js HINTS) in en, zh, zh-TW, ja and de. - Rest: none. The refusal is about the prompt, not the account (Fail "prompt"); a second account answers the same. Plugins: middleware-antigravity-cloak 0.1.1 (plugins a52d1b3) breaks the two Codex lines with U+200B. Its body says "npm had 0.1.0": wrong, the package is not on npm; dist had 0.1.0 and now has 0.1.1 (6fd1438). No mover applies. Real account (owner's Antigravity, sandbox HOME copy, gateway built from this branch) and real Codex 0.162.1: - codex exec resume <a gpt-5.5 thread> -m antigravity/gemini-3-flash: before, 429 retried to "exceeded retry limit"; after, one request and a 400 with the Codex hint; route try (429, prompt), no rest. - A new Codex chat on the same model: 200. - The two lines with U+200B after the first letter: 200; whole: 400. Broken by hand: - antigravityTurnsCodexAway returning false: the Codex tests go red (Codex got 429; the group's skip doesn't say why). - The antigravityRound wrap removed: the search=true subtests go red ("Codex got 429"). Run: - go test -count=1 -timeout 45m ./internal/gateway/: ok (476s, at 865df2472; main's next three commits touch only GUI files). - go test -count=1 -timeout 45m ./internal/gui/: ok (230s, at the pushed tree on |
||
|
|
6e6aba51c8 |
providers: a key may be for another plan of its vendor, sent to that plan's endpoints
yckonnnn on X uses Volcengine's pay as you go and its Agent Plan, and wants a key of each in one provider. Each plan takes its own keys at its own endpoints (/api/v3, /api/plan/v3, /api/coding/v3), and every key of a provider went to the provider's one plan, so only one kind worked. A key now may say which of its preset's Regions it is for (KeyAccount.Plan; Provider.KeyPlan for the first key, as KeyProtocol). None, or the provider's own plan, is the provider's plan, stored as none: old configs read and write as before. Presets whose plans take keys of their own (PresetDef.KeyPlans): zhipu, zai, stepfun, stepfun-cn, xiaomi, baidu-qianfan, tencent-cloud, huaweicloud, volcengine, siliconflow. Not: yylx (one key everywhere), bailian-decision (decide only), bedrock and bedrock-mantle (regions of one account). Every reader of the region or a base URL, and what it does now: - WithKey (keys.go): moves the key's copy to its plan (atKeyPlan: Chat, Responses, Anthropic, Decide, KeysURL, Website, Catalog via atRegionOf; a provider at a host of its own keeps that host) and marks it keyView. Every gateway key path goes through it: chat, Responses, Messages, count_tokens, failover, embeddings (serveRetrieval via onKeys), drawing (drawOnAccounts via perKeyBarred), key tests (test.go), key_models.go, gui/groups.go, markedKey. - perKeyBarred (gateway/fallback.go): a key whose plan's list lacks the model (PlanServing) is not asked; only when no key's plan has it. - fetch / fetchPerKey / planOnly (models.go): a mixed provider lists each key's plan, a NoList plan from its preset list with no request, pay as you go from /api/v3/models with its own key. - planMedia (PlanEmbeddings, PlanDrawers, PlanVideos): every plan's. - PlanQuotas (planquota.go): each key read at its own plan's source. - volcPlanQuotas, tencentPlanQuotas: one view per plan (planViews). - KeyBalances (balance.go): each key at its plan's host (SiliconFlow). - startVideo / videoMaker (gateway/video.go): a mixed provider starts on a key whose plan makes the model (onKeys) and names it in the id (keyMark), so the poll goes to that key's plan. - GUI: POST /api/keys/plan (SetKeyPlan, then the lists are read again); the editor keeps KeyPlan with an unchanged first key, typed() clears it with a new one; KeepSecrets, AddCopy, backup's withoutKeys carry it. - app.js: planPicker, a plan chip in each key row (the app's own menu, openProtoMenu, through pickPill, which protoPicker now shares), shown for a KeyPlans preset while the provider has several keys or the key has a plan; i18n zh, zh-TW, ja, de. A key's plan is not guessed from the key: Volcengine's keys carry nothing that says their plan. Xiaomi's tp-, Tencent's sk-tp-, MiniMax's sk-cp- and Bailian's sk-sp- are noted in code but not used. Not done: a gateway key held to some keys (videoAsker) on a mixed provider's video may pick another key; a mixed provider whose own plan has no balance source while a key's plan has one is not read; keys left out for their plan don't show in the Routing trace; StepFun's plan windows are a sign-in per site, unchanged. Credit: yckonnnn on X (tweet 2114657701305487483). Run at this commit on origin/main |
||
|
|
6e96903346 |
codex: auto-review follows the session on a ChatGPT Free plan (cybercaius)
cybercaius on Discord measured codex-auto-review spending a Free
account's allowance ("实测在 free 账号不免费"). magpie left an unset
auto-review to Codex (codex-auto-review), and held such a call by no
usage cap, on #1593's finding that OpenAI counts it in no window; that
was measured on a paid account.
Decision: with nothing picked and Codex signed in to a Free plan (the
ID token's chatgpt_plan_type is "free"), auto-review counts as "Same as
the session", as Codex's other side calls do, so the review stops
spending the free allowance when the session is on one of magpie's
models. On Codex's own model nothing changes (its entries keep OpenAI's
reviewer). A paid plan, or a plan magpie can't read, keeps Codex's pick;
a pick in Settings always wins.
- codexcat.AutoReviewModel is the setting in effect; the plan comes from
provider.CodexSignInPlan (liveLogin, keychain read cached), read once
per model list, and the list tag already re-stamps on auth.json.
- freeOnChatGPT no longer exempts a Free plan's codex-auto-review call
from usage caps (capHeld).
- GUI tooltip says it (en, zh, zh-TW, ja, de); docs updated.
Run at the pushed tree (on origin/main
|
||
|
|
4e5b2ad81c |
gateway: another magpie added by hand rests only the model it refused
lagrangepoint1813 on Discord: Pi on a magpie whose provider is another
computer's magpie got "Remote Magpie: Claude Code: You've hit your
session limit" for every model of it, whichever Pi was switched to.
remoteModelRest rests such a refusal by model (restID) only for the
Remote magpie preset; that magpie was added as an OpenAI-compatible
provider of the user's own name (preset null in providers.json, the
reporter found), so the 429 rested the whole key
(restKey) and quotaHeld answered every model of it from that rest for
the five hours it named. A magpie's reply names the provider that
answered or held it (X-Magpie-Provider), as no vendor's does: keepRetry now notes it as
answeredThereHeader (this magpie writes its own provider into the same
header of its reply, so it can't be read there; the note is kept from
the client), and remoteModelRest reads a refusal carrying it as another
magpie's model's, whatever the provider was added as. A quotaHeld or
verifyHeld answer now names its member too (noteMember), as an asked
one does, so a refusal the other magpie held is read the same. The
key's own limit there (remoteKeyLimitHeader) still rests it whole.
TestAnotherMagpieAddedByHandRestsTheModel (two gateways over HTTP; the
other magpie asking Claude Code, and already holding it): both subtests
red on the old code with the reporter's message, green with this
change; -count=3 with TestRemoteMagpie* and Verify* green. Broken by
hand: reading X-Magpie-Provider straight from the reply header rested
by model everywhere (TestOwnQuotaRest, TestVerifyRefusalRestsTheLastOne,
TestAntigravityQuotaStillRests, TestCodexCompactCutSummaryFailsOver,
TestOpenRouterFreeAccountRateLimitKeepsProviderRest went red, the header
being this magpie's own); without noteMember on the held answer the
held-there subtest stays red.
Run at this head (on origin/main
|
||
|
|
b28e5ffd81 |
gateway: an array with no items goes to Antigravity with items {}, and Google's schema 400 falls through (plugins#375)
gcq909893267 (plugins#375): Claude Desktop's own MCP tools __batch and
__guide declare an array property with no items ("batch":{"type":
"array"}). plainSchema passed it through, and Google turned the whole
turn away: 400 "GenerateContentRequest.tools[0].function_declarations
[17].parameters.properties[batch].items: missing field". The group's
next member was never asked.
- plainSchema (codeassist.go): every node it writes that is type array
with no items gets items {}, which Google takes (the reporter's A/B:
{} and {"type":"string"} both 200). Its walk is the one every nested
place goes through (properties, items, anyOf/oneOf members, allOf,
$ref into $defs/definitions, a type list with null), so the check at
the end of a node covers all of them.
- Siblings: plainSchema is the only Gemini-side schema cleaner. Gemini
CLI's Code Assist and Vertex AI / a custom Gemini API go through the
same buildCodeAssistSent but send parametersJsonSchema, full JSON
Schema, where an array with no items is valid; gemini.go's jsonSchema
is the other direction (a Gemini client's schema read in). Left as
they are.
- Fall-through: a 400 that points at a function declaration's
parameters (function_declarations[N].parameters) is now in
shapeWords, so shapeRefused/retryable read it as the request's shape
on that vendor: the next member is asked once, and the member doesn't
rest (Fail "shape", Rest nil), as OpenCode Go's "schema exceeds the
maximum nesting depth" (#1870). Not resting is right: the account is
fine and the same request fails the same on every Antigravity
account; the reporter's same tools answered 200 on a non-antigravity
member. A declaration's name or the contents are not matched. A
shape refusal still tries the same provider's next account first, as
every shape refusal does now; not changed here.
Tests (antigravity_array_items_test.go), fixtures from the reporter's
literal request and error line:
- TestAntigravityArrayGetsItems: the reproduction through
buildCodeAssist(antigravity); both declarations carry items {}.
- TestPlainSchemaArraysAllHaveItems: nested arrays under each keyword
get items {}, an array with items keeps them, a non-array gets none.
- TestGroupFailsOverGoogleSchema400: a group's first member answering
Google's 400 hands it to the second, Fail shape, no rest; plus a
shapeRefused table (Google's both wordings, the agent-facing wrapped
form; a function name and contents error, and a 500, are not).
Run: go test ./internal/gateway/ -run 'CodeAssist|Codeassist|Gemini|
Schema|Antigravity|Shape|FailsOver|Fallback|Region|Retryable|Refus|
Vertex|Plain|Google' ok (307 tests, 31s); gofmt -l clean; go vet,
GOOS=linux go vet -tags nogui, GOOS=windows go vet on internal/gateway
clean.
Broken by hand: codeassist.go reverted, the first two tests FAIL
(declaration 0 parameters.properties.batch: {"type":"array"}); fallback.go
reverted, TestGroupFailsOverGoogleSchema400 FAILs (a 1, b 0).
Not tried: a real Antigravity account (the reporter's own A/B shows
items {} answers 200); the full go test ./... suite; Gemini CLI and
Vertex AI with an items-less array against the real APIs.
|
||
|
|
be7f174677 |
gateway: a key out of a guessed quota is asked again after one refusal, and held a minute (zoecats)
zoecats (Discord #feedback, 10-25): a local aggregator answers 429 insufficient_quota "quota exhausted" for the moment it switches upstreams, and the agent's retry and every request after it were answered by magpie itself, "out of its allowance: not asked again before …", Retry-After 900. v0.1.1488 ( |
||
|
|
67361b54fb |
routing: Try now from the editor reaches the Routing page, and puts a sunk key back
zoecats (Discord #feedback, 10-25, v0.1.1477): a local aggregator answered
"quota exhausted" while it switched upstreams; Try now in the provider's
editor left Routing showing 429 until magpie restarted.
Cause, in three holders:
- The Routing page kept lifts in its own liftedAt, filled only by its own
Try now. A lift from the editor (or anywhere else) never reached it, and
the kept routes' snapshots went on drawing the rest. The trace now
carries every rest lifted (TraceState.Lifted, from restingUntil.lifted,
kept up to longestMonthly), Unrest/UnrestAll/renewed wake the long-poll
(trace.lifted), and the page leaves out a rest, a sunk key and an
Accounts and keys count that a lift came after.
- With Sink on, a rate-limited key stayed at the back of the order until
restart: Unrest never cleared sunk. unsink(key) now does.
- The gate itself: checked on the old binary in a sandbox HOME (single key
over a fake answering 429 insufficient_quota "quota exhausted"). magpie
rests it 30 min and answers later requests itself ("out of its
allowance: not asked again before …"); Try now with the editor's key
lifted that and the next request reached the upstream (200), on
/v1/chat/completions and /v1/messages, streaming and not. So the stuck
state was the display and the sink, not quotaHeld.
Left alone, filed: #3555 (Try now lifts nothing when another magpie
serves the gateway, unrest 400) and #3556 (the held reply's
Retry-After, 900s here, outlives the lift for an agent that honours it).
Run at this change on its first base,
|
||
|
|
7765f27fcc |
gateway: a model an account refuses goes on to the accounts not listing it yet
01huadalang (Discord): Antigravity with several accounts, only some can
use Gemini 4. The model and its bar showed only after the right account
was made preferred and probed, and a request failed with the preferred
account's error instead of going on to the account that serves it.
st3lland (Discord): on ZCode (plugin) accounts serve different models.
Owner: no manual setting, magpie knows per account and routes.
Two causes:
- perKeyBarred puts an account whose own saved list lacks the model in
pl.unlisted / pl.left (Unlisted) and serve never asked it. So when
the listing accounts refused the model (Antigravity's real 404
NOT_FOUND "Requested entity was not found.", codeAssistModelMissing;
plugins through modelRefused's unservedWords), the agent got that
error even though an account whose list was simply stale serves it.
Now, once every listing account of that subscription/model has been
asked and one refused it as unserved (unservedTry), its unlisted
accounts are asked next, right after it and before any other member
or fallback (unlistedNext, askUnlisted for the trace). The refusing
try rests as before (restAfterMarked, for that model). Not for a
pinned account, a sealed conversation or strict affinity; a gateway
key's account list narrows unlisted too (allowedCandidates). Other
refusals (403 PERMISSION_DENIED, 429 RESOURCE_EXHAUSTED) don't open
the unlisted accounts.
- Antigravity's per-account lists were refreshed only on the first
listing, a probe, a sync or a Refetch, so a model granted later and
its bar (chosenWindows filters by exposed models) stayed hidden. Its
quota reading already fetches fetchAvailableModels per account; now
it saves that account's list (noteAntigravityList) and re-merges the
pooled list from every On account's list when it changed. An Off
account's reading changes nothing.
Other vendors: the unlisted route only opens on the existing unserved
classifiers (Antigravity's 404, plugins' unservedWords), unchanged here;
TestUnlistedAccountNotAskedForOtherRefusals holds that the other real
Antigravity bodies don't open it.
Run (at the rebased head on origin/main
|
||
|
|
6e32942a24 |
gateway: a safety refusal that also says the model is retired retires nothing (#3274, CartethyiaQwQ)
CartethyiaQwQ (#3274) found one more way a safety refusal punished a
provider: serve's retirement check runs on any failed try, and
modelRetired accepts a 400 whose body says the model "is retired", so a
cyber_policy refusal whose message also said so took the model out of
the provider's lists (retired.json) until an answer brought it back.
No real refusal seen so far says it; a boundary case.
- serve: a try settled as a refusal (hw.refused) retires nothing. By
then its body is magpie's note "safety filter: cyber_policy — <the
vendor's message>", text, so policyRefusal can't tell it there.
- modelRetired: a body that is the safety filter's error object
(policyRefusal) is never a retirement, for its other callers too
(modelRefused, which rests the model, and retryable).
The note cuts the vendor's message at 300 characters, so the test's
refusal is short enough to keep the retirement words in it, as a real
one would.
Tests: TestRefusalSayingRetiredRetiresNothing (an OpenAI-compatible
provider answering a 400 cyber_policy refusal saying "The model m1 is
retired." retires nothing; the same words under model_deprecated still
retire), and TestRetiredWords gets three cases.
Broken by hand: without the serve guard, TestRefusalSayingRetiredRetiresNothing
is red ("retired true, want false"); without the modelRetired guard,
TestRetiredWords is red on both refusal cases. A Codex account's
refusal never reached Retire on main, so it was tried only through the
OpenAI-compatible path.
Full suite at 91f777e93 (base
|
||
|
|
efb7cb11d4 |
gateway: a safety refusal said in a stream is a refusal for a client answered whole too, and rests nobody (#3274, CartethyiaQwQ)
CartethyiaQwQ (#3274): Codex's "safety filter: cyber_policy" refusal (the Daybreak note) set healthy accounts aside; two such turns benched a five-account pool for about 17 minutes. Cause: the HTTP 400 cyber_policy is already a refusal (policyRefusal reads its code: next account asked, nobody rests), and so is one said in a stream relayed as a stream. A Codex account is always streamed upstream, so a stream:false Responses, Chat or Messages request is answered from that stream whole. There, a response.failed or error event whose error has a code (cyber_policy) but no invalid_request_error type got no status from the decoder, and the whole path answered it 502 api_error: retried on the same account, then every account asked, each one but the last resting by backoff. A refusal after a few words went to the client as a finished 200 turn, and the failure after it rested the account. Fix, at the decoders and the whole path: - filterRefused (fallback.go): a stream error event refusedCode reads as the safety filter's gets status 400 and Said {"error":{type invalid_request_error, code}}. Used by every decoder that set Code: refusedCode -- Responses (both error sites, after requestRefused), Chat, Anthropic and carriedError. - The whole path (gateway.go) answers a reply the filter cut part way as the refusal, not its words so far, and notes it in refusedHeader, since Anthropic's error shape drops the code that settle reads. - restAfterMarked: a 400 whose error object policyRefusal reads as a refusal rests nobody and counts no failure (By "off", Why refused), as the ZDR refusal does, for any route that reaches it. - docs/subsystems/gateway-routing.md says so. Review of the submitted patch (dc6c695db, not taken as is): it matched `safety filter|cyber_policy|Daybreak access` anywhere in a 400's words, so a 400 that echoes the user's prompt in its message skipped the rest too; its fixture was magpie's own refusedError text, which restAfter is never handed for a 400; and it gated on status 400, while the path that rested (above) answered 502, so it would not have stopped the rests. Its restAfter unit tests' shape is kept in TestRestAfterPolicyRefusal. Run at |
||
|
|
592899467b |
gateway: Gemini's reasoning streams as it comes on the last candidate, so Codex isn't left with nothing for the whole of its thinking (LuckymanJC on Discord)
LuckymanJC and kkgg: through magpie the first turn of a Codex session on a Gemini model was very slow or seemed stalled. Measured with fake upstreams through the gateway (Codex Responses -> Chat DeepSeek, Gemini; OpenCode Chat; Anthropic passthrough), first content came within 1-50ms on every path but one: a Gemini model's reasoning was held even on the last candidate (`|| last && modelFamily(c.model) != ""` left Gemini out), so Codex got nothing at all, not even response.created, until the text began, while Claude's and GPT's has gone as it comes there since iTianbao's report. It was held there for #667, a reply that only reasoned being asked again. That re-ask happens in place in streamTranslated, keeping the reasoning the agent has, so it doesn't need the hold. But with the try passing, emptyRetries counted it as past the request's own re-asks and asked only streamRetries (2) times, and TestGeminiEmptyRepliesAskedAgain (three empty replies running) went red. A held try that went through on its reasoning alone (holdWriter.thoughtThrough) is now asked once more in place (streamRetries+1); a never-answering model still makes at most 4 calls (the test's bound is 6). Tests: TestThinkingStreamsWithNoOneElse gets "gemini" (Gemini upstream) and "chat gemini" cases, to Claude Code and Codex. With the old line restored they go red ("thinking held: first thought only 1.75us before the text"). With emptyRetries' new branch broken by hand (streamRetries+0), TestGeminiEmptyRepliesAskedAgain goes red with "an empty reply"; green with both. Run: go test -run 'TestGeminiEmpty|TestThinkingStreams|TestThinkingHeld|TestUncountedEmpty|TestReasoningLoop' ./internal/gateway: ok. Break check repeated at push: the old `|| last && modelFamily(c.model) != ""` turns TestThinkingStreamsWithNoOneElse/{gemini,chat_gemini}/v1/{messages,responses} red ("thinking held: first thought only 1.458µs before the text"). Full suite (go1.26.8 darwin-arm64, rebased on |
||
|
|
c863904338 |
gateway: Command Code's Zero Data Retention refusal rests nothing and goes to another member (plugins #246)
Command Code plugin 0.1.14 sends x-cmd-zdr: 1 when its Zero Data
Retention switch is on. A model with no ZDR upstream is refused with
the Provider API's 422 (code "cmd_zdr_no_providers") or, on Go, a 400
the plugin makes with type "cmd_zdr_no_providers". The refusal is about
that request's setting, not the model or the account.
Before, on the plugin path (moved commandcode-plan):
- Go's 400 was rewritten with type invalid_request_error, read as the
model unserved (unservedWords), rested commandcode-plan@<acct>/<model>
for a minute, and the account's second key was asked the same thing.
- The 422 went to the agent as api_error, and in a group the next
member was never asked.
- Raw bodies (restAfter, a decision group's decideFailed) read as
modelRefused too.
Now:
- zdrRefused (fallback.go) matches only that code as the error's type
or code, on 400/422. modelRefused and tooLongUnsaid leave it out.
- keepRetry notes it from the vendor's raw body (X-Magpie-ZDR-Refused)
since the Anthropic error shape keeps no code; pass/keepAlive strip
the note.
- The candidate loop skips the provider's mates at the same model
(notMates, they'd be sent the same header), tries the next member,
rests nobody, and returns the refusal alone.
- restAfterMarked and decideFailed rest nothing for it.
- docs/subsystems/gateway-routing.md says so.
Tests (internal/gateway/plugin_zdr_test.go), with the literal bodies
from plugins' zdr.test.mjs:
- TestCommandCodeZDRRefusalRestsNothing (422 and 400, plugin path,
two accounts): alone the agent gets Command Code's words and one
account is asked; group G answers from b over chat and over
/v1/messages; nothing rests; switch off, Command Code answers first.
- TestZDRRefusalIsCommandCodesCodeOnly: the same words without the
code, OpenAI model_not_found, unsupported_api_for_model and the code
named in a message still read as model refusals.
- TestZDRRefusalNeverRests: restAfter with the raw 422/400 and the
noted Anthropic body rests nothing; without the note it rests.
Broken by hand:
- old sources (zdrRefused stubbed false): e2e red in both subtests
("group: 422 ... (commandcode 1, b 0)", "alone: 400 ... (asked 2)"),
classifier table red.
- restAfter guard removed: TestZDRRefusalNeverRests red ("422 ...
rests: {Why:other Status:422 ...").
- loop branch removed: e2e red. keepRetry note removed: e2e red.
Run at this head: gofmt -l (clean); go vet ./...,
GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... (clean);
go test -timeout 45m ./... (go1.26.8, load avg ~300 from other
sessions): every package ok except
- internal/agent, internal/gateway, internal/library: past -timeout
45m (TestClaudeTiers, TestMessageReasoningRefused,
TestProjectServersQoderCodeBuddyDroid running), as #2869;
- internal/gui TestSetAnswersWhileDevinAndProvidersHang (13.8s), #1375;
- internal/plugin TestGatewayHookMixedPiPackage, #2865.
After rebasing on
|
||
|
|
2a27fb8da8 |
gateway: a request's body is looked at for web search without a copy, and not parsed for a provider that searches by itself
attempt() asked searchAsked first, on every relayed request, and only
then whether the provider searches by itself. searchAsked looked for
three words with strings.Contains(string(body), …), each conversion a
copy of the whole body (a 211KB body: ~640KB and ms a request), and a
body offering web_search was then parsed whole: Codex offers it on
every turn, so each relayed Codex turn was parsed only to be told
"Codex searches by itself". searchedForIt now asks what is known of the
provider and model first, and searchAsked looks with bytes.Contains.
The same copy in the siblings that look at an error body
(fallback.passing, patience.busy, routing.failure's insufficient_quota)
goes too. lan.go's and the lower-cased look-ups in gateway.go need the
string they make and are left as they are.
Test: TestSearchAskedLooksCheaply. Broken by hand (string(body) and the
old order put back): red, "a 211KB body with no search in it: 3
allocations, want 0" and "a provider that searches by itself: 29
allocations, the body parsed".
BenchmarkSearchedForIt (211KB Responses body; load average ~450):
codex-asks old 2.55-5.02 ms/op 665KB/op 29-30 allocs/op
new 0.1-1.9 us/op 0B/op 0 allocs/op
other-plain old 1.6-4.8 ms/op 663KB/op 3 allocs/op
new 0.26-1.15 ms/op 0B/op 0 allocs/op
Run: go test ./internal/gateway -run
'TestSearchAskedLooksCheaply|TestWebSearchAskedOfEachAPI|Search|Busy|
Passing|Failure|Credit|Quota' -count 1: ok (140s).
|
||
|
|
b14784c03f |
gateway: a fallback too small for the request is asked once every account with room is out of its allowance (Kai on Discord)
Kai on Discord (0.1.1278): Claude Code to claude/claude-opus-5-5, the
Claude provider's two subscription accounts (Max, Pro) both at their
limit ("resets 5:58am", "resets Oct 18 at 3pm"), its Fallback
codex/gpt-6.1-sol. Routing said the second account's 429 had nobody left
to try, and Claude Code had the 429. The fallback was never in the
route's order.
Cause: roomy (
|
||
|
|
992f288e20 |
gateway: a Chat-only relay that refuses tools with reasoning and none too moves a group on (#2670, JJ-Lin)
JJ-Lin's analysis in #2670 found both causes and gave the mock upstream the tests use. A relay with a Chat URL alone answers tools with reasoning_effort with "use /v1/responses or set reasoning_effort to 'none'", and then refuses none ("Supported values are: 'low', ..."). - forwardTranslated: when none was #176's own and is refused naming the levels, offRefused is still remembered (it is true of the model), but the request isn't asked again at the lowest level (refused the same by the upstream's own word). The tools refusal is the answer. The #176 retry is gated on turnedAway(none) plus a per-request guard, so it can't loop. Before: the first request went [xhigh none low] and every later one [high], with the 400 going to the agent. - passthrough (a chat client's relayed request), the sibling: the same. It used to ask none on every request and hand back the confusing "'none' is not supported" error. - shapeRefused/retryable: a 400/422 that wrongEndpoint reads reaches the group only once the member has tried every API it has a URL for. The next member is now asked once, and this one doesn't rest (failShape). Before, the group stopped on it. - The agent's error still names the Responses URL the provider lacks (wrongAPINote via asksResponses). Reading supported_endpoint_types from /v1/models was left out: wrongAPINote already says what to set, and trying Responses on the Chat base unasked isn't clean. - docs/subsystems/gateway-routing.md says both. Plain chat without tools, and gpt-6-astra (where none is taken) are unchanged; TestToolsEffortNoneTaken pins both ([effort none] -> 200 three times in a row; no-tools [xhigh] -> 200). Tests (internal/gateway/tools_effort_none_test.go, JJ-Lin's mock): - TestToolsEffortNoneRefused: one Server, Codex xhigh/high/high asks [xhigh none], [high], [high]. Each answer is the tools refusal with the Responses-URL note. A chat client gets [high none], [high]. - TestGroupPassesOverToolsRefusedOnChat: group relay -> other. Three requests in a row are all 200 from other, tries[0] is failShape, no rest. Broken by hand: - fallback.go reverted: the group test is red (400 to the agent). - translated restore off: "request 1 asked [xhigh none low]". - passthrough check off: the chat client gets "'none' is not supported". - turnedAway gate off: "request 2 asked [high low]". Without the per-request guard too, it loops forever (seen, killed). Run on origin/main |
||
|
|
bf931f82c3 |
gateway: a Codex conversation compacted natively is held to its account only when native compaction is on, and told why when it can't go there (#2642, #2582)
ScarfQian (#2642, still on v0.1.1279): after a native compaction by one Codex account, routing to another answered 400 "only that key or account can read the compaction it sealed ... switched off, removed, or no longer serves". Three causes, one fix each: - #2582 (Dony2050, ump45nose's patch): one of Codex's own models asked on the backend path through magpie's accounts (codexAccounts) kept the compaction_trigger whatever the codex provider's native compaction setting, so every compaction was sealed by and recorded to one account. It is now decided as a magpie model's is: codexInputAs with nativeCompactionFor("codex/<model>"); off (the default) gives codexCompact's magpie1: summary, which any account reads, and records no writer. Unlike ump45nose's branch, /responses/compact and Codex's own single sign-in relay are left as they were: the legacy endpoint's body has no trigger for codexCompact to answer, and a lone sign-in has no other account to move to. - ggbdpq's fix (0ab41eba0, e1646488d, ported as is): a writer whose own model list has since dropped the model sat in planned.left, out of the candidates, so checkpointReaders never found it and refused although it was on. It is now taken back from planned.unlisted (plan, planLevel and the nested weighted plan), its row moved from left to order. sealedReaders, run before it for a sealed subagent task, narrows unlisted too (sibling). - A request carrying a recorded seal while only Codex's own sign-in is on was relayed as it came (codexAccounts false), so with the writer switched off the one account left was sent it. codexSealedFor routes it through serve, where checkpointReaders holds it to the writer. - checkpointError now says the reason magpie's settings give (checkpointGone: provider removed, account signed out, sign-in lapsed, paused while others are on, switched off, kept from the model in Names & levels, key off or gone, model disabled, or the model/group asked for not routing to it), the fix for that reason, and whether native compaction is on for the writer's provider now. The old catch-all sentence is gone. The seal is still treated as readable only by the account that wrote it, as #1099 and #2271 found; chestnutLeeeee's report that another account read one in a direct canary was not tried here (no real accounts). Tests (fake ChatGPT backend, sandbox HOME, nothing on the network): TestCodexOwnModelCompactionHonoursTheToggle (off: summary, no trigger upstream, no writer; on: native seal kept, writer recorded), TestNativeCompactionWriterGoneSaysWhy (spare switched off, own paused, Names & levels, signed out), ggbdpq's TestNativeCompactionWriterWhoseListLacksTheModel and ...ThroughAGroupWhoseListLacksTheModel. All four are red on |
||
|
|
5b12407e8e |
gateway: a custom tool a Responses upstream turns away is translated, not given back as a 400 (#2656)
DeepSeek's Responses API answers Codex's exec, a custom tool, with 400 "Unsupported custom tool: 'exec'. Only 'apply_patch' is supported." The relay (attempt -> passthrough) sent the tools as they came, so the translation that offers a custom tool as a function and gives its call back as a custom_tool_call never ran, and the 400 matched no word list, so a group's next member wasn't asked either. - passthrough: a 400/422 matching customToolRefusal, on a Responses body that offers a custom tool (tools, a namespace's, an input item's tools), marks the model (customToolRefused) and returns not done. - attempt: then, and on a marked model's later requests with a custom tool, the request is translated on the client's own API (ownAPI), so exec keeps its name and comes back as custom_tool_call. A Codex compaction (keepsCompaction) isn't translated and gets the refusal. - shapeRefused also takes customToolRefusal, so where the refusal does reach a group, the next member is asked and nobody rests. Not scoped to DeepSeek: any Responses relay (key, plugin) that says its custom tools are unsupported is handled the same; an upstream that never refused them still gets them as sent (tested). Tests: custom_tool_test.go, fixture from the reporter's literal error text and request. TestCustomToolTranslatedWhereRefused (stream and not), TestCustomToolRefusalInGroup (reporter's ordered group, next member asked 0 times), TestCustomToolRefusalWordings. Broken by hand: passthrough branch off -> both request tests 400 with the reporter's exact message; attempt pre-skip off -> next turn asked 4 times, not 3; shapeRefused addition off -> Wordings red. Run: - gofmt -l clean; go vet ./... (darwin), GOOS=linux and GOOS=windows go vet -tags nogui ./... clean, at the pushed head. - Full go test -tags nogui -timeout 45m ./... on |
||
|
|
df341e7671 |
gateway: a member that answers a stream request with a whole reply is asked once, not again and again (#2455)
An upstream that answers stream:true with a whole JSON reply (a relay that doesn't speak SSE) fails as a 502 "did not stream". magpie read that 502 as a failure a moment may mend: the same-one retries (passing) asked it twice more, then a group's patience (busy, #1418) kept asking it until the budget was spent. The failure is the same however often it is asked. With production pauses that is about 7 requests and 60s at the default Patience, about 14 at 240s; the test's 1ms pauses let the 12 replan rounds run out first, 15 requests (ggbdpq's correction on the issue). busy() and passing() now leave a body that says didNotStream alone, and the four places that word the error (translate, streamTranslated, askTranslated, holdWriter.settle) share that constant. A group still moves on to the next member, whose API may stream; retryable() is unchanged. Patch by ggbdpq (f9e09ca7), applied on main with the docs sentence placed by hand (the hunk no longer applied). Run: - TestStreamlessMemberIsAskedOnce with both exclusions taken out: FAIL, whole and stream ("asked 15 times"); with only busy()'s: FAIL ("asked 13 times"); with only passing()'s: FAIL ("asked 3 times"). Restored: ok (asked once, the agent gets the 502 naming "did not stream"). - TestStreamlessMemberHandsOnToTheNextMember (b, which streams, answers after a): ok. - TestQuietNotAReplyLastFails, TestPatience*, TestStreamOverflow*, TestCodexOverflowInGroupNotAskedAgain, TestAgentGoneInTheRetryPause, TestRelayInputCap, TestOverflowGoesToAMemberWithRoom: ok. - Full suite, go test -tags nogui -timeout 45m ./... (set -o pipefail, sandbox HOME, load ~350) at 0224e826f (these four commits on |
||
|
|
ae98cda651 |
gateway: an inner group's own Patience waits out its busy members through an outer group (#2410)
serve read Patience only from the group the request named (g.Waits()). planLevel stamped a nested group's FirstToken (#2246) on its candidates but not its Patience, so an inner group's budget was never read through an outer one: an inner 4 min under an outer default gave up at 1 min, and an inner Off was still asked again for 60s. Each candidate carries the innermost Patience that is set on its way down (innerPatience, as innerFirstToken). waitsOf reads it as Group.Waits does, falling back to the asked group's when unset; PatienceOff keeps the member out of replan. replan counts each member's budget from waitFrom and asks again only those with budget left past the pause; the hold on the last failure lasts while any member's may (maxWaits), and the trace's Patience is the member's own. With no nested Patience set, every member's budget is g.Waits(), as before. Patch by ump45nose (61b1c17c); ggbdpq checked it against main on the issue. Review changes: the docs sentence was placed by hand (the docs hunk no longer applied), and the tests' budgets moved from inner 8s / outer 3s to 10s / 4s, so every round's pause ends 2s or more from a budget line (it was 1s from the 3s line), as a timing test leaves room on both sides. Run: - With fallback.go, gateway.go, patience.go and patience_test.go put back to main: TestNestedGroupPatienceThroughOuter FAIL ("a.n=2, want 3 — the inner group's 10s budget was not read"), TestNestedGroupPatienceInnerOff FAIL ("code=529 a.n=13 (want 529, 1 — no replan)"). With replan reading only the fallback budget: ThroughOuter FAIL the same. Restored: ok. - TestNestedGroupPatienceFallsBackToOuter, TestGroupWaitsOut*, TestPatienceIsUsedUp: ok. - Full suite, go test -tags nogui -timeout 45m ./... (set -o pipefail, sandbox HOME, load ~350) at 0224e826f (these four commits on |
||
|
|
440f66701f |
gateway: a 429 for native compaction's one account says the compaction pinned it, not that every account is capped (#2517)
When a conversation was compacted natively, only the key or account that sealed the compaction can read it (#1099), so checkpointReaders keeps the candidates to that one. When that account was at its usage cap, the 429 and the call record said "every account that serves X is held at the usage cap", although the other accounts were never candidates. That sent lm0711 looking at routing modes, which can't change it. checkpointHeld tells this case apart: the plan held only the sealer's account(s), and others were left out for the checkpoint. The error then names the account and its window, says the compaction it sealed is what keeps the conversation there, that routing mode and stays don't change that, and to raise the cap / spend credits or start a new conversation. The record reads "native compaction's account at its usage cap" (or its credits / both variants). cappedError and cappedRecord are unchanged for every other 429; their text is split into heldReasons and heldAdvice so both share it. docs/subsystems/gateway-routing.md says so. Test: TestNativeCompactionWriterAtItsCap seals a checkpoint on one account, caps it, and checks the 429 body and the record. Broken by hand (checkpointHeld returning nil), it fails with the old "every account" text. Run on origin/main |
||
|
|
e243937ca3 |
gateway: a fast pick can be sent as Ultrafast where the account offers it (#1954)
zhenghaowen0967 asked for an agent's fast pick of a ChatGPT model to go as
Codex's Ultrafast without the client asking for it. settings.UltraPicks
holds the agent's fast picks that are set to Ultrafast; each one is in
FastPicks too.
- The gateway marks those candidates `ultra` in fastPick.
- On Chat and Responses, a try sends service_tier "ultrafast".
- From Messages, a try carries withUltra to forwardTranslated, which
sets Request.Ultrafast for the ChatGPT backend.
- In every case, the #1784 check decides the account. One whose list
doesn't offer Ultrafast goes after a mate that does (tierMate). With
no mate left, it is sent priority.
- That check now covers Chat as well as Responses.
- Sibling fix: chat.go dropped a Chat client's own service_tier
"ultrafast" (Fast was false, Ultrafast unset). It now parses as
Responses does.
- provider: SetFastTier (""/priority/ultrafast) behind SetFastPick.
CanUltra and UltraModels say whether one of Codex's accounts lists
Ultrafast on the model. UltraPicks follow a provider rename
(renameModelPrefs) and survive a GUI settings save.
- GUI: an option gets ultraOk/ultra. Where ultraOk is set, the bolt in
the picker steps usual -> Fast -> Ultrafast -> usual, as a camera's
flash button steps its modes. Ultrafast shows two overlapped bolts, in
the row and after the field's model. Tooltips and the status line are
in en, zh, zh-TW, ja and de. POST /api/agent-fast takes `ultra`.
- No `:ultrafast` suffix for routing groups yet.
Tests, each broken by hand and seen red:
- TestUltraPickSentUltrafast covers omp/Responses with no tier asked
(acct-pro:ultrafast), the Pro account out (then acct-plus:priority),
another agent unchanged, opencode/Chat and claude/Messages picks, a
Chat client's own ultrafast, and switching back to Fast or off.
- Red with ultra forced false (4 cases).
- Red without withUltra (claude went priority).
- Red without the chat.go parse (2 cases).
- TestSetFastPick: red without UltraPicks in renameModelPrefs.
- TestSettingsSaveKeepsWhatItDoesNotSend: red without the api.go carry.
- fast-ultra.test.cjs (en zh ja de, window and 440px panel): red (9/9)
without the Ultrafast step.
Run (vet, gofmt, GUI and full suite at base 8b84dc902; the reruns
below at a rebase onto
|
||
|
|
d9e87eb328 |
gateway: clients opt into Claude subscription cache marks and TTLs (#1717)
Problem: Messages clients need control of cache boundaries and TTLs when a Claude subscription answers. Ordinary clients must retain their run identity, prompt and environment. A routing group's API-key member keeps its marks and must not report the subscription bridge's drops. Change: Select client-owned marks only with X-Magpie-Cache-Marks: client. Map system and fresh-history boundaries and the request tail, default missing TTLs to 5m, validate slot and TTL order, and separate opted-in run identities. Retain prefix constraints across live and saved runs. Report unmappable marks only for the Claude subscription try. Bound its selection hold to two seconds and clear the report and hold for a non-Claude fallback. Check ordinary identity bytes without a version-specific hash golden. What was run: Sandbox HOME, nogui: go vet ./... on darwin; gateway vet with GOOS=linux and GOOS=windows; full gateway tests; focused cache and usage tests with -race. gofmt and git diff --check passed. The group probe failed before the fix with tools:1 on the API-key reply in both routing orders and both stream modes. Hand-broken candidate scoping, stale report clearing, keepalive holds and ordinary identity bytes each failed behavior tests. Live, Claude Code on a Claude subscription and an Anthropic API key, through a recording proxy: in a group whose API-key member answers, in either order and both stream modes, the reply has no dropped-mark header and upstream receives the tool mark; a Claude answer reports tools:1; a failed Claude try followed by an API-key answer leaves no report. With a delayed API-key reply, the group's first keepalive came 0.85 s after a direct request's. Without the header, the outgoing request equals one from a gateway built at the same base. No GUI or real Linux/Windows execution. |
||
|
|
0bbb2f3ca4 |
provider, gui, gateway: a thousand keys are listed once and read eight at a time (@NetRozee on X)
@NetRozee on X: "when I add a thousand keys for a custom endpoint magpie
just froze or crash by itself".
Cause. The Providers page asked, for each key, what it rests by
(RestKey), and RestKey listed every key on again (KeysOn), which itself
looked along the list for each key: cubic in the keys. /api/providers
and every /api/keys/* answer, an import too, are drawn through it. The
gateway asked, for each key of every request, whether it serves the
model (Serves), and each asking read the provider's lists again (a
filememo stat, and a read while the file is new) and looked along each
model's key ids. fetchPerKey looked along the lists for each key and
model the same way.
Fix.
- KeysOn drops repeats by a set.
- RestKeys finds once whether several keys are on; providerInfo uses it.
- Serving(model) reads the lists once and answers for each key from sets
(keyLists, made again when the lists are read anew); perKeyBarred and
the test pick use it. Serves is Serving for one key.
- fetchPerKey keeps each model's keys as a set and indexes the old list
by key once; a model kept for a failed key is kept once, as before.
- KeysListed and ListsRead count listings and list reads for the tests.
Behaviour is otherwise the same.
Measured (go test in a sandbox HOME, a custom provider, 50 models):
1000 keys 5000 keys
providerInfo 1.54s -> 7.5ms 2m42.9s -> 18.3ms
providersState 1.65s -> 110ms 2m40.3s -> 146ms
POST /api/keys/import 1.64s -> 82ms 2m44.7s -> 288ms
of one more key
gateway perKey 100.9ms -> 8.2ms (old not run) -> 40ms
(each request)
Tests (counts, not time), each red on the old code by hand:
- TestProviderInfoListsKeysOnce: old 1001 listings for 1000 keys, 11 for
10; new 0 and 0.
- TestPerKeyReadsListsOnce: old 1001 list reads for 1000 keys, 11 for
10; new 1 and 1.
- TestServingReadsListsOnce, TestRestKeysIsRestKey,
TestKeysOnDropsRepeats: same answers as before.
And the vendor reads. KeyBalances, PlanQuotas and remoteKeyCards started a goroutine
for each key and asked the vendor with all of them at once: a thousand
keys were a thousand requests to one relay together, each holding a
connection and its body.
Fix. keySlots holds each provider's reads to keyReadsAtOnce (8); other
providers' keys are read beside them. A read whose context is done goes
on without a slot and fails at once, as before.
Tests:
- TestKeyReadsEightAtOnce: a Command Code provider of 31 keys and a
remote magpie of 31 keys behind a server that holds every request.
Old code (the slots taken out by hand): 31 at once for balances, plans
and remote limits; new: 8, every card still there.
- TestKeySlots: a done context takes no slot; another provider's keys
have their own.
Run: gofmt -l (clean); GOOS=linux and GOOS=windows go vet -tags nogui
./... (clean); go test -tags nogui -count=1 -timeout 45m ./... in a sandbox HOME (GOCACHE, GOMODCACHE pinned) on
|
||
|
|
7e4336e719 |
gateway: an event magpie appends to a cut stream begins after a blank line (#2446)
A passthrough stream cut mid-line got its error event written onto the half-written line, so the client read "event: error" as more of that line's data and never saw the error as an event. ggbdpq's patch (#2446) tracks whether the last write ended a line (passthrough's write, and holdWriter.atLine for cutLoop) and puts a blank line, two newlines when mid-line, before the appended event. The same join could happen to the other event passthrough appends: the finish_reason filled in for a Gemini OpenAI-compatible reply that ended done ( |
||
|
|
a0a4d55ef7 |
gateway: a passed-through reply whose reasoning loops before it says anything is asked again once, and its tries counted (#2436)
lqisgod's five looped replies (pi → WorkBuddy, Chat in and out) each
ended at once with empty tries and status 200. The once-only re-ask of a
reasoning loop (loopReasks) lived only in streamTranslated's onLoop, so a
same-protocol passthrough had holdWriter.reask nil and cutLoop ran on the
first trip. A re-ask that did happen in place wasn't counted in the usage
record's tries either (tries came from route.Tries alone).
Now holdWriter lets such a try go (mayReloop/letGoLoop) when its
reasoning looped, nothing has spoken (loopGuard.spoke: no text or call),
the request has its re-ask left and its context is alive, and either
nothing of the try reached the agent (held bytes dropped, any protocol)
or the agent speaks Chat (bytes written up to the end of the tripping
event, the next try's chunks follow). The fallback loop records the try
as failLoop with reloopedError and asks the same provider again after
retryPause. In-place re-asks add to tries too. An Anthropic or Responses
stream whose reasoning already reached the agent still ends with the
loop error: a second message_start/response.created can't follow. The
plugin host's fetch goes through the same holdWriter
(TestLoopEndsWorkBuddysReply's plugin subtests).
Tests: loop_guard_test.go's chat case now expects 2 asks and an answer;
every passed-through `data:` line is valid JSON; the usage record has
Tries == asks and no error. docs/subsystems/gateway-routing.md updated.
Broken by hand, each red:
- hw.reloop = false (old behaviour): TestLoopEndsTheReplyOnEveryProtocol,
TestLoopEndsWorkBuddysReply, TestReasoningLoopIsAskedAgain fail.
- reasked not added to tries: the same three fail with "usage record's
tries 0, the vendor asked 2 times".
- spoke never set: TestLoopAfterTextIsNotAskedAgain fails.
Run: gofmt -l clean; go vet -tags nogui ./internal/gateway ./internal/usage
with GOOS=darwin, linux, windows ok; go test -run Loop ./internal/gateway ok.
Not tried: a real WorkBuddy account looping (the loop can't be forced).
Full suite: go test -tags nogui -count=1 -timeout 45m ./... on base
|
||
|
|
d98e17808b |
gateway: a refusal that comes as an error ends the try at once, is read across writes after content, and the high-risk message alone is one (#2400, Jichao)
Three gaps Jichao reported, each reproduced on origin/main
|
||
|
|
ad312dfee9 |
zhipu: a 1308 or 1310's reset time, written with no zone, is read as Beijing's, and a held refusal says its time with the offset (Player on Discord)
Player reached a Remote magpie with a GLM Coding Plan key: "Z.ai:
[1308][Usage limit reached for 5 hour. Your limit will reset at 2026-10-15
20:12 (out of its allowance: not asked again before 17:12)". Z.ai's 1308
and 1310 ("Usage limit reached for N hour. Your limit will reset at
YYYY-MM-DD HH:MM:SS", bigmodel.cn "您的限额将在 … 重置") write the time
with no zone. It is UTC+8: code-yeongyu/senpi#3348 has a 1308 received at
2026-09-21T17:17:32Z saying 01:18:11, 39s later as UTC+8 and 8h later as
UTC; kodustech/kodus-ai#2104 and openclaw/openclaw#97764 show the same
zone-less form for 1310. resetsWhen reads only a time with its offset, so
nothing read it: the key rested quotaRest (15 min), the held refusal said
"not asked again before" a quarter-hour on (17:12, this magpie's local
time with no zone), and after it Z.ai was asked and refused again until
20:12 Beijing time.
- routing.go: zhipuResets/resetsZhipu read Zhipu's own words ("Your limit
will reset at", "您的限额将在") then a whole date and a time to the
minute at least, in UTC+8; not when a digit, colon or zone follows
(cut in its seconds, or a zone of its own, which resetsWritten reads).
resetsAt tries it after resetsWritten, so restAfter and keepRetry both
see it, for the built-in key, a relay passing it on, and a Remote
magpie's held refusal.
- heldClock: a held time is given as "20:12 UTC+8" (today) or
"Oct 16 09:00 UTC+8", since its reader may be a Remote magpie's user on
another clock. Siblings: the quota-held 429 (gateway.go), the capped
window error (fallback.go), the spent searcher (search.go) and describer
(vision.go), all of which wrote Local() with no zone.
- docs/subsystems/gateway-routing.md says both.
The "manual weekly reset" was Z.ai's weekly reset card, spent on Z.ai's
site (magpie only counts them,
|
||
|
|
0f398c4895 |
gateway: a group member whose window can't hold the request isn't asked it (dgqyushen on Discord)
dgqyushen on Discord: OpenCode Zen's free DeepSeek V4.1 Flash (200K) first in a group and a 1M DeepSeek subscription second, so that the first 200K go free and past that go to the subscription. The gateway fell over only on a refusal it reads as too long (#700, withRoom/failOverflow, tooLongUnsaid past 1.2x the window). A vendor that refuses a request just past its window without saying why (between 1.0x and 1.2x) reached the agent as that error while the next member had room, and every doomed request spent one against the free tier's limits. roomy (fallback.go), in serve after rules, affinity, the image filter and pinTo and before probeOne, estimates the request as the overflow path does (estimate) and leaves out the candidates whose known window (windowOf: Contexts, the catalog, ContextOf) is no larger, and their order rows with them. It is a check before sending, not a retry. Kept: a window not known, a body that doesn't parse, a single model, and a request no candidate holds (the first is asked, its overflow told to the agent to compact). A conversation stuck to the small member by affinity moves once it outgrows it. count_tokens (a count on the first member) and System One's decision models don't go through serve's candidate path and are left alone; every generation route (middleware, classify, search, vision, codex titles/backend, auto groups) goes through serve. No UI change: a member left out is absent from the route's order. TestPayloadTooLargeOverWindowTriesMemberWithRoom now expects the members too small not to be asked at all (c only, one try). Run: - go test -tags nogui -p 1 ./internal/gateway -run 'TestMemberTooSmallIsNotAsked|TestConversationOutgrowingItsMemberMoves| TestRoomyLeavesWhatItCantJudge|TestPayloadTooLarge': ok - the overflow tests (TestPayloadTooLarge, TestOverflow, TestContextOverflow, TestEveryVendorsOverflow, TestCodexOverflowInGroup, TestStreamOverflow, TestRateLimitNotContextOverflow) with the new ones: ok - gofmt -l clean; go vet ./internal/gateway (darwin); GOOS=linux and GOOS=windows go vet -tags nogui ./...: clean; go build darwin, linux, windows: ok. Broken by hand: the roomy call in serve commented out: TestMemberTooSmallIsNotAsked red (400 "FREE: Invalid request parameters"), TestConversationOutgrowingItsMemberMoves red (free 2, paid 0), TestPayloadTooLargeOverWindowTriesMemberWithRoom red (a 1, c 1, 2 tries); restored, all green. Not run: the whole internal/gateway package (the run failed to build, "no space left on device", the disk at 0 GB free) and the full suite (left to the batch's run). Not tried against the real OpenCode Zen. Known: the estimate is bytes/4, so mostly-CJK text counts high and a member may be passed over a little early. Full suite: SUITE_LINE |
||
|
|
75035fa202 |
gateway: Command Code's bare 400 (a trace id, no reason) hands a group's request to the next member, not ends it (#2313, lqisgod)
Command Code's Provider API answers some requests with
{"message":"invalid request error trace_id: <hex>","type":"invalid_request_error"}:
a 400 (a 422 the week before), no code, no param. retryable() read it as
the request's own fault, so a group stopped there and its later members
were never asked: six requests in a row on lqisgod's wb-flash group, while
the fourth member answered the same ~660K prompt that hour.
What it turns away is the request's size, not the key: lqisgod's A/B on
one agent conversation (~748K tokens of history and tool calls, same bytes
otherwise) answered 200 with max_completion_tokens 64000 and this 400 with
384000, the max output Command Code lists for the model, so history plus
asked-for output is over a limit below the 1M context it lists. Its own
tracker has more of the kind (CommandCodeAI/command-code#960, #976).
Another member whose model has room may take the same request, so it is
asked, as for a shape another API can take.
unsaidWords matches that message alone, as the vendor sends it, wrapped by
a client in front of it, or told on after a provider's name. It goes the
way shapeWords do (shapeRefused, retryable): the next member is asked once,
Command Code doesn't rest, and the last member's error reaches the agent.
No retry of the same member is added. Its overflow ("The input is longer
than the model's context length trace_id: …") and a refusal naming a param
aren't matched. The keyed "commandcode" preset and the moved plan go
through the same gateway decision.
Tested: TestGroupFailsOverCommandCodesBare400 (streamed group request,
reporter's literal body; the 422 and wrapped forms from #960/#952; overflow,
param and longer-message negatives). With fallback.go put back it fails:
"400 ... COMMANDCODE: invalid request error trace_id: ... (a 1, b 0)".
go test -run 'TestGroupFailsOver|Shape' ./internal/gateway passes.
Full suite: SUITE_LINE
|
||
|
|
51d5b8d0b2 |
gateway: a Codex compaction's summary cut short or 429'd halfway fails over and rests the account, and one that keeps failing is held, not asked every 18s (#2274, huangzuomin)
Codex on antigravity/gemini-3.8-flash with context_management's
experimental mode asked magpie for 1169 summaries in 6 hours (8.44M
billed tokens), ending in 502 "compaction: the model wrote no summary".
Cause, in three parts:
- serve's holdWriter let the summary's stream through at its first
words, so Antigravity cutting it short ("the reply ended before it was
complete"), or a 429 "Individual quota reached" after some of it,
reached codexCompact as a 200 with an error: no failover, no rest.
- codexCompact took a summary that ended `incomplete`, or a body with
no response at all, as one.
- Codex's async compaction (codex-rs async_compaction) starts a
background compaction at every step while the conversation is over its
threshold and drops a failed one silently, so the history never
shrank and each step paid for the whole conversation again.
Fix:
- codexCompact marks its request askWhole; serve then holds the summary
stream to its end (holdWriter.wantWhole). A cut, an error event or
`response.incomplete` anywhere in it fails over to the next candidate
like a failure before content and rests the account as that would; a
model that reached its output limit rests nobody.
- With nobody left, the cut/incomplete summary is a 502 saying so, never
the words before the cut.
- compactFails (codex_compact_guard.go): after 3 failed summaries in a
row of one conversation (prompt_cache_key) on one model, each within
5 minutes, the next is answered 400 at once (Codex doesn't retry a
400) naming the last failure, until 5 minutes pass. A summary clears
it; 401/403 aren't counted. Decision: a 400 is the only answer Codex's
remote compaction stops on, and a per-conversation hold costs a user
whose model recovers at most 5 minutes, while the loop cost tokens.
- docs/subsystems/gateway-routing.md says so.
Run (worktree at origin/main
|