ac4af582301a4e8a29245dbba767eba31334ddf9
195
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
40cbdaa7e8 |
provider: an account's window can be capped at a fixed amount of its unit
A window magpie reads with a total and a unit (a day's 1000 credits, a
plan's requests) can now be capped at an amount of that unit, not only
a share: 9won_25273 asked to stop an account at 300 of its day's credits.
- AccountWindowAmounts keeps it per account and window (capId). An
amount and a window's own share replace each other.
- WindowCaps.limitShare turns it into a share of the total for the mark
and NearCap. CapHeld and capReached hold the account once the window's
count reaches the amount (past), and rest it as the percentage cap
does: the next account takes the request. cappedError and the trace
say "has used 300 credits ... past its cap of 300".
- A reading with no total ignores the amount; the account's share
applies.
- GUI: the window meter's menu has one more item, Amount..., typed in
place (provider/windowcap with amount). It shows only on a window
with a unit and total. Strings in zh, zh-TW, ja, de.
- CLI: magpie provider account-cap <id> <account> --window <name>
--amount <n|off>.
Usage outside magpie counts: every cap reads the vendor's own count, so
what the account spent in the vendor's app or on another machine counts
from the next reading on. magpie can only hold back its own requests.
Run, at this head on Linux (wsl-run, magpie-desktop):
- gofmt -l: clean; go vet ./... for linux (-tags nogui) and windows: ok (darwin
vet needs cgo, so it runs with the full suite on mote afterwards)
- go test -run 'Lang|ToolLoop|LoopGuard|Cap|Amount' ./internal/gateway
./internal/provider ./internal/cli: ok (TestWindowAmountCapHeld,
TestSetWindowAmount, TestWindowAmountHoldsTheAccount, the CLI cases)
- GUI window-cap, window-cap-pool, account-cap in chromium and webkit,
420 and 1100 wide, en zh zh-TW ja de: 78 of 78 in each engine. An
earlier webkit run lost the amount test's page once ("Target page,
context or browser has been closed"); it passed in 2 more full-file
runs and 60 of 60 alone
- i18n-keys: only "a plugin's words are its own" red, words that aren't
this change's (#5332, #5426, #5482)
Broken by hand: limitShare ignoring amounts (of < 0): TestWindowAmountCapHeld
and TestWindowAmountHoldsTheAccount go red.
Not tried: the full go test ./... at this head (queued on mote, runs
after); a real account at an amount cap.
iFlytek: 9won's 讯飞 overshoot isn't covered. Loomy's daily window sends
used as a count and amount as what is left (plugins#889); AStudio's
wallets tell a balance only, which no cap can hold (#5770).
Reported-by: 9won_25273 (Discord)
|
||
|
|
e0f6eda641 |
gateway: a probe's reply that thinks its 16 tokens and ends unsaid is answered (plugins#827)
Through a Remote magpie, the plain model test of Open Design's
glm-5.3-flash was red. The model always thinks. It spent the test's 16
tokens on that and ended after content_block_stop, with no message_delta
or message_stop. So:
- translate made it a 502 "ended before it was complete";
- the 502 is busy, so the remote retried it and waited out its 60s
patience;
- the asking magpie had given the remote only 20s (testWait), and said
no answer came.
Each step is now fixed for the class, not for this model:
- A reply whose request was capped at a short probe's worth
(cutVoidTokens, 1024) and that spent some of it, then ended cleanly
with nothing saying it ended, ended at its length (endsAtProbeCap).
- This holds in translate, in streamTranslated and in gathered (a
Responses plugin's stream asked whole becomes response.incomplete at
max_output_tokens).
- It covers Anthropic and Responses upstreams only. Gemini always
ends with a finishReason, so a Gemini stream without one stays a cut
(TestGeminiUpstreamEndedShort, asked for 256, caught a wider first
draft).
- A reply asked for more than 1024, or one that spent nothing, is
still the 502.
- A client may say how long it waits (provider.WaitHeader,
X-Magpie-Wait, in seconds). The gateway then takes no same-one retry
pause and no patience round that would end within clientRoom (10s) of
that wait (keptAlive.outlives), so the client gets the error while it
still waits. Like every X-Magpie- header, it is not sent upstream.
- A model test through a remote magpie waits pluginTestWait (60s), as a
plugin's test does here, and sends that wait as X-Magpie-Wait.
Not changed: a stream relayed as it came (passthrough to an agent of the
same protocol) still gets no end added. That is filed as #5736 and named
in gateway-routing.md.
Run, through mote-run:
- At the pushed tree, rebased on origin/main
|
||
|
|
44d6dd75d1 |
gateway: a subscription's capped or spent turn goes on to the user's group with it in
adorable_piglet on Discord (v0.1.3354): a Codex subscription with a usage
cap set in magpie, first in a routing group with two APIs after it. Past
the cap the Codex app's turns were answered 429 "usage cap reached" and
never reached the APIs; only switching the subscription off in Providers
moved them.
Cause: the Codex app signed in to ChatGPT asks Codex's own model
("gpt-5.5"), never "group/<id>". With a cap on the account,
codexAccounts routes the turn as codex/gpt-5.5, and serve plans the
codex provider and its own Fallback list only. A group that merely has
codex/gpt-5.5 in it was never planned, so with every account held the
answer was cappedError's 429. A request for the group itself was already
routed on past the cap (TestCappedSubscriptionGivesWayInGroup, green on
the old code too). The same gap was on Codex's own sign-in out of its
allowance at OpenAI: codexFallsBack counted the subscription's Fallback
only, so the backend's usage_limit_reached reached Codex.
Fix:
- provider.GroupsAfter(id): the routing groups the user built that have
the model in them and another member to go on to, in the user's order;
auto groups, hidden or switched-off ones are none.
- serve: when every account is held at its cap (pl.capped, no candidate
left, CapStop off), or for a turn codexFallBack handed on, the provider
is planned again with those groups after its own fallbacks
(groupsAfter), each group routed as a request to it is. One place, so
it holds on every protocol (chat, responses, messages, Codex's backend
path), streaming or not, and for plugin-served subscriptions.
- codexFallsBack counts those groups as fallbacks too.
- Stop at the caps (CapStop) still answers 429 (planPaused returns
before any fallback, the groups included).
Tests:
- TestCappedCodexOwnModelGoesToItsGroup: backend path with "gpt-5.5" and
/v1/responses with "codex/gpt-5.5", stream and not; red on origin/main
|
||
|
|
6b7ee4a984 |
routing: every group follows a default for rate limits, slow starts and busy members unless it sets its own
jiezhengj on Discord asked to set the per-group policies once instead of
in each group. The Routing groups page's Settings card, under the list,
now has three rows: Rate limited (keeps its place / goes to the back),
Slow to start (wait / 30 s ... 4 min) and Every member busy (off / 1 min
... 4 min). They are saved in settings.json as groupSink, groupFirstToken
and groupPatience (settings.SetGroupDefaults, POST /api/groups/defaults).
A group follows the default for each value it leaves unset, and its own
value always wins:
- Sinks() is the group's Sink, or else the default unless NoSink, a new
field for an explicit "Keeps its place".
- FirstTokenOr() is the group's own FirstToken (-1, FirstTokenWait, is an
explicit Wait), or else the default. The gateway reads it where it
reads a group's first-token time.
- Waits() reads the default when Patience is 0. 60 is an explicit 1 min.
Groups saved before have 0 and no NoSink, so they follow the default,
which starts at magpie's own (keep its place, wait, 60s). Nothing a user
set changes. The group editor's three rows gain a Default option, on for
a group that sets none, and its hint names the value it follows. Segments
only, with no native select.
Run on mote, at 06b2daeff rebased on origin/main
|
||
|
|
9700dd7cdc |
gateway: ZCode's account-wide 429 (its [1302] label) is a wall, not a moment's rate (#5406)
ZCode's account-wide 429 "[1302][您的账户已达到速率限制,请您控制请求频率][id]" read as a rate limit that passes: the same-one retries (passing) asked it again 1/2/4s apart and a patience's rounds sent the whole request again every 2s..30s — "magpie keeps asking, so the 429 comes back in a loop" (#5406, erlinerd; two further accounts on v0.1.3216). Rested and retried, the 429 came back: no moment clears it. walled now also matches the ZCode plugin's own naming of the refusal, the vendor's three-part label [1302][its words][its request id] (its words whole, a 16-hex id). The next account is asked, or the agent has the error at once, as wallCodes says. Review change: the patch also added the bare code "1302" to wallCodes, for every vendor. Zhipu's own API answers 1302 for a concurrency or minute limit ("并发数过高", or "您的账户已达到速率限制" with no label), which a moment does clear, so a GLM key would have lost its in-place retries. The bare code stays a rate limit that passes; only the label's shape walls. The comment's claim that the 并发数过高 reading "never reaches here" is gone. Two Zhipu bodies are added to the test's "still passes" cases. Run (wsl-run, magpie-desktop, Go 1.26.8): - go test -count=1 -run 'Wall|MinuteLimit|RateLimit|RestRetry|Patience|Busy|FailureReads|PassErrors|Zhipu|ZCode' ./internal/gateway: ok 21.9s - the same Wall|RateLimit|Patience|Busy set with -race: ok - gofmt -l: clean Broken by hand: - main's fallback.go: TestZCodeWallIsNotRetriedInPlace red ("the wall passes: asked again in place", "the wall is busy") on both labelled bodies. - the patch's own fallback.go (bare 1302 in wallCodes): red on both Zhipu bodies ("doesn't pass", "not busy"). Not tried: a real ZCode account's 429, and whether the next account is asked on a live rotation. Reported-by: erlinerd Co-authored-by: ggbdpq <ggbdpq@gmail.com> |
||
|
|
3441035a2e |
routing: a group's member maps the reasoning level asked to the one sent
A Routing group that relays one long task across vendors sent every
member the same effort word, but one vendor's high is another's xhigh
(LuckymanJC on Discord). A member that follows the group may now carry
a map from the level asked to the level sent: Group.EffortMaps, json
effortMaps, keyed by the member's id as Members spells it.
- Default: no map, or a level the map doesn't name, goes as asked, so
every group saved before is unchanged and nothing of the user's is
overridden. A member fixed at an effort (or with several levels) and
a rule's UseEffort still win over the map.
- SaveGroup keeps a map only for a plain member of the group (not
:effort, not :a+b, not group/), drops pairs that send what was
asked, lowercases, and refuses a word that isn't a reasoning level.
- Carried by member rename (groupfast RenameMember and the all-groups
rename), provider rename, fold (and its fingerprint), share/import
and CanonicalRef; on a collision the map already spelled so wins.
- Gateway: the level asked is the suffix's/agent pick, then the turn's
pick, then the request's own (askedLevel: agentEffort, plus none for
an Anthropic request with thinking disabled); the target is sent with
withFixedEffort, fitted to the model's catalog levels unless none, and
the trace's try records mappedFrom. Per candidate, so fallback and
retries send each member its own; count_tokens sends no member effort.
- The group lists a mapped member's own levels plus the map's keys to
agents (mappedLevels in buildGroupEntries).
- GUI: the member's reasoning menu has "Map levels…" (app menus only):
a level asked, then As asked or one of the model's levels. The chip
reads "Mapped reasoning", its title the pairs. Follow the group or a
fixed level drops the map. zh, zh-TW, ja and de.
- docs/subsystems/gateway-routing.md says all of it.
Run (mote, at this tree):
- gofmt -l: clean. go vet (provider, gateway, gui), GOOS=linux go vet
-tags nogui ./..., GOOS=windows go vet ./...: clean.
- go test ./internal/provider/: ok. go test -run
'Effort|Level|Group|Fallback|Rule|Auto|Fixed' ./internal/gateway/: ok.
- node --test group-member-effort-map (30: chromium + webkit, en zh
zh-TW ja de, 1100 and 420px) and group-member-levels: pass;
i18n-en-no-cjk: pass. i18n-keys' "a plugin's words are its own" is
red only for the three words it is red for on origin/main
|
||
|
|
5c5160c940 |
provider: a model's test asks the account or key routing sends it to (#4992)
On a provider with several accounts or keys whose models differ (a magpie-newapi pool, a relay whose keys sit in different groups), "测试模型", the right-click test and the provider's Test asked the first account or key. A model that only another account serves failed (grok-4.7: 503 "no available channel") while real requests were answered, because the gateway's perKeyEvery passes over accounts and keys the user set not to serve the model (AccountModels, #474) and accounts whose own list lacks it. The test path had none of that. Cause: the choice lived in the gateway only (perKeyEvery and accountsOn in gateway/fallback.go), so the test had nothing to share. keySeeing checked the key's list but not AccountModels. Change: - internal/provider/route_accounts.go: AccountsOn, AccountsFor and KeysFor are the routing choice. The code moved there from perKeyEvery and accountsOn, and the gateway's caps are passed in as a held func. - gateway/fallback.go: perKeyEvery and accountsOn call it. They behave as before. - test.go: - testOne (the model test and the right-click test) runs as AccountsFor's first account. A model barred on every account is not asked; it says so. - The provider's Test picks key and model together (testWith), then the account that serves the model (routedTo). - The log row names the account asked (loggedAs). - keySeeing and testModel take keys from KeysFor and AccountServes. - detect.go: detectOne, a sibling, asks each model with keySeeing's key. Before, it asked the endpoint's first key. - Not changed: AskSystemOne's decision model still asks the provider's own account. Tests (internal/provider/test_account_route_test.go), on a two-account fake plugin and a relay that answers one key:model: - TestModelTestAsksTheAccountThatServesIt - TestModelTestPassesAnAccountWhoseListLacksIt - TestProviderTestAsksAnAccountThatServesItsModel - TestModelTestUsesTheKeyServingIt - TestModelTestBarredModelIsNotAsked - TestDetectModelsUsesTheKeyServingIt All six are red on origin/main |
||
|
|
11df525f06 |
gateway: only the vendors seen to hide an overflow have a bare failure told as too long (#5486)
NEKO-CwC asked, after v0.1.3141, why a custom API-key Responses relay's 400/413/422 is still turned into context_length_exceeded when the relay never said so. It shouldn't be. tooLongUnsaid read any provider's 400/413/422 that said nothing of length, for a request 1.2 times past the model's window, as "prompt is too long". That rule came from three vendors' refusals in |
||
|
|
978284dd69 |
gateway: a transport failure or a plain 502 is not told as too long
Filed as #5486. ne9ko9 runs Codex through magpie to a custom OpenAI Responses relay (gpt-6-astra, effort max). Three failures reached Codex as HTTP 400 "prompt is too long: about 385K/404K tokens, more than gpt-6-astra's context window of 272000": a plain 502 "Upstream service temporarily unavailable", a TCP connect timeout (dial tcp … connectex) and a TCP read timeout. Codex took them as context_window_exceeded and ended the turn instead of asking again, although the same session had just been answered at 454K and 474K, and Codex's own window was 828,400. tooLongUnsaid now: - reads a 5xx as an overflow only for Devin (busyOverflows: p.ID or its plugin's host), the vendor |
||
|
|
2e58f85e4a |
gateway: an Antigravity account Google suspended rests as restricted, and the next account serves
Google answers a Code Assist account it suspended with 403
PERMISSION_DENIED "This service has been disabled in this account for
violation of Terms of Service. Please submit an appeal to continue using
this product." Read as an unknown failure, it failed over but rested a
minute, doubling to the ten-minute cap, so the suspended account was
asked again (and refused, a wasted round trip first in line) every ten
minutes for good, and the Routing page said only "failed".
The refusal is about the account, not the model or the request: it is
now failRestricted (googleSuspended, on an Antigravity or Gemini CLI
account, 403, Google's exact words), so it rests restrictedRest (2h) as
"account restricted by the vendor", with the Routing page's lift for an
appeal that went through, and its usage isn't asked again. Unlike
WorkBuddy's and ZCode's risk control, it is not walled off from the
provider's other accounts (riskRefused): the service was disabled
before the request came, so the next account is asked as before.
Run (mote, at this tree on origin/main
|
||
|
|
cf15d79d7f |
gateway: a relay's Gemini refusing a tool's anyOf beside a description hands the request to the group's next member (#5374)
Google's Schema takes an anyOf alone: a tool whose parameters carry a
description beside an anyOf is turned away with "Unable to submit
request because `tool` functionDeclaration `parameters.response` schema
specified other fields alongside any_of. When using any_of, it must be
the only field set." Asked straight, Google points at
function_declarations[N].parameters, which shapeWords reads. A relay
(sub2api, TokenFree) passing Google's words on writes them camel-case,
the field in backticks and no path, so the 400 went back to the client
and the group's later members, a non-Gemini fallback among them, were
never asked (#5374, worksyang, with the two-channel comparison and the
one-line fix).
shapeWords now also reads "schema specified other fields alongside
any_?of" (any_of and anyOf). The next member is asked once and the relay
doesn't rest (failShape), as for every shape refusal. A plain "messages:
field required" and Google's "Invalid function name" 400 stay the
request's.
Run (mote, testenv sandbox HOME):
- TestGroupFailsOverAnAnyOfSchemaRefused with fallback.go put back to
|
||
|
|
c2dd693dac |
gateway: a 451 censorship_blocked refusal asks the group's next member (#5089)
StepFun's safety filter refuses a request with HTTP 451 and an error
object saying {"type":"censorship_blocked"}. filterReasons, the map of
the words a vendor says its filter stopped the reply with, didn't know
the type, so policyRefusal didn't read the 451 as a refusal and
retryable has no 451 of its own: the status went to the agent as it
came, the group's next member unasked, and the try stood as a plain
failure of the account.
The same refusal said in a 200 stream's finish_reason would have been
one, as content_filter is. Now the type is in the map, and the refusal
goes to the next member the way any refusal the vendor names does:
nobody rests, as the filter refusing is about the request, not the
account.
Reviewed and ported: one filterReasons entry, vendor-neutral, and
nobody rests as before. On mote, -run 'Censorship': with the map entry
reverted, red: "TestCensorshipBlocked451FailsOver ... whole: 451" and
"TestCensorshipBlockedIsAPolicyRefusal ... policyRefusal: "", false";
green with it. Whole package: ok (906.6s). Not tried: a real 451 from
StepFun.
Generated-by: GLM-5.3-Flash (ZCode)
Co-authored-by: ggbdpq <ggbdpq@gmail.com>
|
||
|
|
2027bb5a6d |
gateway: a filter's finish code after the reply began asks the group's next member (#5075)
A vendor that answers with a canned refusal line as the content and has its finish_reason "content_filter" follow (#5075: CodeArts's deepseek-v4.1-flash, 10/10 on the same body, 47 tokens out, the line byte-identical) was a try that stood as a success: the line had gone out as content, so the scan's refusal paths were past, only refusedAfter was marked, the group's next member was never asked, and a client that reads finish reasons — Pi's and DeepSeek Harness's mapStopReason, Claude Code — failed the whole turn on it. Another member of the same group answered 620 tokens. refusalAfter now hands the try over (handOffAfter) when the refusal is the vendor's own finish code (eventRefusal), the reply is passing, a candidate stands behind it reading Chat chunks, and no call of the reply has gone by: what of the write went by before the code goes out with the reply, the code, its usage and [DONE] do not, and the next member's chunks follow in the same stream, as a refusal after reasoning is (handOver). The member isn't set aside: the request was refused, not the account (#248). A refusal still held goes through the scan's own paths (flow, handOver) as before; an error event mid-reply stays as it came (#733); an Anthropic or Responses client's stream is numbered and what of it has gone by is untracked, so its refusal keeps going as it came. TestRefusalAfterThinkingAndTextStays becomes TestRefusalAfterThinkingAndTextFailsOver: a Chat client is handed over now, where it ended on the vendor's finish code before. Fixes #5075 Reviewed and ported: composes with #2972 (passthrough holds the end, the hold writer sees the error event). The hand-off is held to Chat streams that sent no tool call (handsOff checks h.calls); that guard had no test, so TestFilterFinishAfterACallStays is added here: a content_filter finish after a tool_call stays with the first member and the call reaches the client. On mote, -run 'Refusal|CannedRefusal|FilterFinish': with the non-test part reverted, red: "TestCannedRefusalFinishFailsOver ... chat: 200" and "TestRefusalAfterThinkingAndTextFailsOver ... 200 (a 1, b 0)"; with the calls guard removed by hand, TestFilterFinishAfterACallStays red; green with the patch. Whole package: ok (906.6s). Not tried: a real vendor's canned refusal (CodeArts, qoder). The refusal text already streamed stays in the client's stream before the next member's answer. Generated-by: GLM-5.3-Flash (ZCode) Co-authored-by: ggbdpq <ggbdpq@gmail.com> |
||
|
|
d45e74d89f |
gateway: a length cut that said nothing is not a completed reply (#2972)
What changed: a Chat reply cut at its length having said nothing — no
text and no call, only thinking, or nothing at all — fails at once, on
the translated paths and on the passthrough Chat→Chat relay, asked
again nowhere: the error in the client's own protocol, a group's next
member asked, nobody rested, and the same one not asked again after a
moment (the void fails the same every ask, as one that didn't stream
does). It fails only past a short probe's worth: a reply that spent no
more than cutVoidTokens, of a request capped at no more, is a probe's
answer — a title's cut is wanted, the response.incomplete it was
(#1466) — and goes as it came. A length cut that said something is
still the truncation it always was.
Why: qoder/dfmodel ended four replies of one dsh turn with 48,000
output tokens each, every one of them reasoning — out == reasoning
exactly each time, 192,000 tokens and 919 seconds for nothing — and dsh
speaks openai-completions while the qoder plugin serves Chat, so all
four were relayed as they came. The relay reads its end now: a stream's
tail is held from the chunk that says why it ended while nothing has
been said in it, and a void fails with the error event in its place, no
finish_reason the agent reads as "continue" having gone out. A reply
asked whole is written once it has ended, for the same verdict. On the
translated paths the check sits beside answersNothing (cutVoidAt,
cutVoid), and holds the end events as the empty reply's already are. The
verdict sits at the reply's end, so a streamed one costs no second read.
What the review asked, and where each landed:
- the reporter's own route: the passthrough Chat→Chat relay fails the
void too, streamed (the error event and [DONE] instead of the finish)
and whole (the error with the status)
- no in-place re-ask: the void's branch is the empty reply's error
without the emptyRetries, and the same-one retries and the patience's
rounds pass it by (cutVoidWords beside didNotStream in passing and
busy), so the upstream is asked once — every test here holds the fix
to that
- a deliberately small max_tokens is no void: the gate is spent past
cutVoidTokens, or the request hadn't capped its reply small
(probeTranslated asks 16, a title less than that)
The repo's own recorded ClinePass stream (16 tokens, all reasoning,
testdata/clinepass_stream.sse) is relayed as it was, on the relay and
translated alike.
Run:
- go test -tags nogui ./internal/gateway/... -count=1: ok
- go test -race -tags nogui ./internal/gateway/ -count=1 (the stream
relays and holds among it): ok
- the five tests of chat_length_nothing_test.go red on the branch's
parent, green here; TestClinePassUpstreamRecorded green before and
after
- gofmt -l clean; go vet clean on darwin, linux, windows
- builds: darwin and windows ok; linux ok for internal/... but the wails
v3 beta 24 module's own linux files (pre-existing, untouched here)
Fixes #2972
Reviewed and ported: rebased on
|
||
|
|
2260390a01 |
gateway: a Gemini thought signature goes back only to the provider that gave it
mimi001234 on Discord: Pi (openai-completions) on auto/gemini-4-argon, a group of google-vertex and google-aistudio-paid. Vertex AI served turns 1 to 14 and signed its calls; on turn 15 it answered 429, the group moved to AI Studio, and magpie replayed Vertex AI's signatures from gemini-signatures/. AI Studio answered every try with 400 "Corrupted thought signature." A signature is the issuing backend's, and only it takes one. - The provider that gave a signature is noted beside it, gemini-signatures/<key>.by (noteSigner, written through temp and rename), wherever a reply is read: decoderFor (every translated path: Chat, Anthropic and Responses clients, plugins, search, continuations) and sigTidy (a Chat relay, and a Gemini client's reply relayed as it came, now only read, in native mode). - Every request is fitted to its provider: ownSignatures in forwardTranslated, chatCallSignatures and geminiBodySignatures in passthrough. Another provider's signature goes as Google's documented skip_thought_signature_validator on a call, and not at all on text. A signature of no known provider (ids from before this change, a note that couldn't be written) goes as before. - A 400 "Invalid/Corrupted thought signature" (signatureRefused) is asked again once without signatures at any upstream Gemini's signatures reach (signaturesReach), relayed too, not only Vertex AI translated; it rests no account (restAfterMarked) and lets a group go on to its next member (shapeRefused). The signer is the provider id, not the account: two accounts of one provider share signatures as before. Run on mote (mote-run), the targeted run and vets at this change on origin/main |
||
|
|
5ee9a18747 |
gateway: magpie's own summary ask keeps its status, so a compaction over the byte cap is summed up locally (#4862)
codexCompact asks a summary through the gateway's own handler (wantsWhole)
and reads a 413 as its cue to fit the conversation, then to sum it up
without a model. That ask was treated like a client's turn:
- with Codex's User-Agent, compactsInStream sent it a 200 and the 413 as
the stream's error, so codexCompact saw no 413 and answered 502 "so
there is no summary" for every compaction over the vendor's cap;
- with any UA, once the fitting tries took past keepHeldAfter (3s: a 40
MB upload asked four times, a slow link, -race on CI) keepAlive sent a
200 and a comment first, and the 413 after it came the same way.
keptAlive.whole (set from wantsWhole) now gets neither a keepalive nor
the in-stream 413. Codex's own turns are unchanged.
|
||
|
|
676b143175 |
gateway: a model refused for the user's region is asked once more, then the agent is told Google's restriction on that model (#5182)
taoxiaoxin (#5182) runs magpie v0.1.2738 with the built-in Antigravity provider, calling it with curl. antigravity/gemini-3.8-flash (upstream gemini-3.8-flash-tiered) answers 400 "User location is not supported for the API use.", while claude-sonnet-4-6 and claude-opus-4-6-thinking on the same accounts answer 200. The refusal is per model and comes from where the user is. A new connection doesn't help, and v0.1.2982 still asked every account and then retried the last two more times. - gateway.go: regionAsked counts region refusals per provider and model within a request. The first one goes on as v0.1.2982 does: the next account, or the same one again, on a new connection, which covers ggdayup's stale-edge case. On a second refusal, the provider's other accounts aren't asked that model (notMates), the last one isn't retried (protected), and another provider or model left is asked. Nobody rests (restAfterMarked, v0.1.2982). - fallback.go: regionNote and explained. The agent gets the vendor's words plus: "Google doesn't serve <model> to requests from the region this one left from: a regional restriction on the model, not on the account, so no account rests for it and the provider's other models may still answer. Use another provider for <model>, or give the provider a proxy in a region Google serves (its Proxy setting)". It is added at the four places that word a failed reply through Provider.Explain (translated stream and non-stream, pass-through, count_tokens). It still goes out as the 400 that SDKs don't retry. - docs/subsystems/gateway-routing.md: the bullet says this. Tests: - TestRegionRefusalOfTheModelEndsAfterOneMoreAsk: one and three accounts, stream and not, every ask refused. Exactly 2 asks, then a 400 that carries Google's words and the note. No account rests and no usage is re-read. - TestRegionNote: Google's and OpenAI's wordings. Nothing is added for another 400, or for a 200 that quotes the words. Run on mote (mote-run): - go test -count=1 -run Region ./internal/gateway/: ok, every #5182 test from |
||
|
|
c32b820a91 |
gateway: a "User location is not supported" refusal rests no account, and the next try goes on a new connection (#5182)
ggdayup (#5182): Antigravity answered 400 "User location is not supported for the API use." on one kept-alive connection. magpie asked every account after it on that same connection, each was refused the same and rested, and the agent got a 400, while a new connection about 12s later was answered. The refusal is about the edge the connection reached, not about the account. - routing.go: restAfterMarked returns Rest{By: "off", Until: now} for regionRefused, as for zdr and offline, so no account rests and no failure is counted. - upstream_transport.go: regionFresh wraps each of upstreamTransport's three transports (any, draws, uploads), so every request through s.client is covered. It reads the first 8KB of each reply with status >= 400. When those match regionWords, closing the body calls CloseIdleConnections, and a pending flag calls it again before the next request. That flag covers an HTTP/2 connection that still carried another stream when the body closed. - fallback.go: passing() asks the last candidate again (lastRetries, after retryPause), on a new connection, so a user with one account is helped too. - docs/subsystems/gateway-routing.md: a bullet saying all of this, including what it doesn't cover. Tests (region_fresh_test.go, with a fake TLS edge that refuses every request on the first connection it sees and answers on any other): - TestRegionRefusalDropsItsConnection uses the real New() client, over h2 and h1. After a region 400 the next request goes on a new connection and gets 200. A plain 400 INVALID_ARGUMENT keeps its connection. - TestAntigravityRegionRefusalAsksTheNextOnANewConnection: two accounts. The second is asked on a new connection and answers, no account rests, and Tries[0].Rest.By is "off". - TestAntigravityRegionRefusalAsksTheLastAgain: one account. It is asked again on a new connection and answers. - TestRegionRefusalRestsNoAccount: Google's and Antigravity's wordings, two turns each. Both accounts are asked both times, with no rest, no failure counted and no usage re-read. A 500 still rests the account. - TestGroupFailsOverARegionRefusal (#1621) now asserts By "off" and no rest. Run on mote (mote-run): - go test -count=1 -run 'Region' ./internal/gateway/: ok. - go test -race -count=3 -run 'Region' ./internal/gateway/: ok (16.5s). - go vet ./internal/gateway/ for darwin, linux (-tags nogui) and windows, and go build ./... for all three: all ok. - gofmt -l: clean. - Full suite: run after the push, see #5182. Broken by hand, one at a time, each with a real FAIL and then restored: - regionFresh not wrapping the body: DropsItsConnection h2 and h1 region, AsksTheNext and AsksTheLast are red (the second request goes on the refused connection, and the turn gets 400). - restAfterMarked's early return removed: AsksTheNext and RestsNoAccount are red (By backoff, Failures 1). - passing()'s region case removed: AsksTheLast is red (the turn gets 400). Not tried: a real Antigravity account in a refused region. Nothing here can reproduce Google's per-edge refusal. Not covered: an HTTP/2 connection busy with another stream at that moment outlives the close until it is idle. The close also drops other vendors' idle connections, which costs one handshake each. A user who really is in a refused region now gets the refusal about 3s later, after the last candidate's retries. |
||
|
|
538026e62b |
gateway: an error frame inside a 200 fails at the status it names (#4855)
mycf_711's wps-lingxi rows read status=200: the plugin's stream already
sent its 200, then wrote {"error":{"message":"灵犀上游返回 AIError:
AI服务异常(上游暂时不可用,可重试)(HTTP 503)",...}}. On main a frame
mid-reply was booked at 200 and rested 60s as "other" with the error
"OK: ...", and one as the first event failed at the 502 the words'
guess gives. Routing never saw the 503 (or AuditFailed's 502).
Now the status an error frame names is what it fails, rests and is
booked at:
- a numeric status or code member, 400-599 (skygunner's patch: held
stream's errOf, errorReply, carriedStatus, and the sniffer's note on
the try's header for a reply already streaming, kept from the client);
- else "(HTTP 503)" / "(HTTP 503)" in the words, 429 and 5xx only, as a
quoted 4xx ("the image link answered (HTTP 404)") may not be the
provider's;
- a mid-reply call is booked at that status in Routing and Usage.
A quoted string code ("429", "1113") is the vendor's own code, not a
status. Words magpie wrote itself (loop guard, empty reply, relooped)
and too-long words name nothing, whatever members they carry: a LAN
peer's loop guard frame carries 502 in its Gemini shape. Such a frame
also no longer rests the route mid-reply (main rested it 60s as
"other" at 200); the model looping is not the provider failing.
Left out of skygunner's patch: streamFailure giving magpie's own Chat
frames a code and status. A peer magpie would read its loop guard frame
as a named 502.
Run (mote, at
|
||
|
|
a1f1810e93 |
gateway: a 400 that only says the request is too long counts as an overflow once it is past half the model's window (#4420, MYCF711)
A group member answered 400 "内容太长了,请精简输入或开启新对话" at ~730K on a model it declares at 1M. |
||
|
|
7818dc316a |
gateway: a relay's Cloudflare 520 to 524 is asked again before the agent sees it, as a 502 or 503 is (vdaoren)
vdaoren on Discord: an API-key provider's 4xx/5xx now and then went
straight to the agent; they asked for retries on chosen status codes.
What a single API-key provider already did: the last one left is asked
again after a failure that passes (passing, fallback.go): 408, 500, 502,
503, 504 and 529 twice (lastRetries), a 429 that is a short rate limit
three times (rateRetries), pauses 1s, 2s, 4s or a Retry-After up to 8s,
then within the provider's patience (singlePatience, 60s by default,
`magpie provider set <id> patience=`) in rounds (busy, patience.go), all
while the reply is held and nothing has gone to the agent. A plan used
up, no balance, a 401, a request the vendor refuses for its content and a
conversation too long are the agent's at once.
What was missing: Cloudflare's own 520 (unknown error), 521 (origin
down), 522 (connection timed out), 523 (origin unreachable) and 524
(timeout), which a relay behind Cloudflare gives now and then, were in
neither list. Such a 5xx moved on to another member in a group, but on a
lone provider it reached the agent after one try. busyStatus now holds
the one list passing and busy read, with 520 to 524 added. No setting:
the default serves it, and patience= already exists for the length.
TestCloudflareErrorIsTriedAgain (retry_test.go): each of 520 to 524, as
Cloudflare words it to an API client ("error code: 520") and as its HTML
page, twice and then 200, is answered 200 after 3 tries; a stream's 524
then an SSE reply reaches the agent with nothing of the 524 in it; a 401
invalid key and a 400 content_policy_violation are tried once.
Broken by hand (busyStatus's list back to 408..529): red, every 52x case
"520 after 1 tries" and the stream "524 after 1 tries"; the 401/400 cases
pass either way.
Run on mote at this tree (base origin/main
|
||
|
|
b61c71448c |
keys: a custom provider's key can be made for its Gemini API (corddis_114)
corddis_114 on Discord has a relay that gives out a key per protocol,
one of them for Gemini ("gemini sk-d…SarG"), and the key row's protocol
menu offered Any, Anthropic, Chat Completions and Responses only. A
custom provider already serves Gemini upstream (its Gemini URL, the
"Gemini compatible" tab, x-goog-api-key, the model list through
FetchGemini, probes), so only the per-key layer lacked it:
- keyProtocolOK takes "gemini"; WithKey leaves a Gemini key the Gemini
URL only and takes the Gemini URL from a key made for another
protocol (it had kept it, so an Anthropic key could be sent to
generateContent).
- keyFit: a gemini* model (modelFamily Gemini) goes to the key made for
Gemini first, the other keys in their order behind it; a GPT model is
never put on the Gemini key (it ranked 0 there before). Claude's rule
is unchanged.
- app.js: Gemini in PROTO_OPTS ("Gemini API (generateContent) · Gemini
CLI, Gemini models"), offered when the provider has a Gemini URL;
keyLacksURL says "No Gemini URL" for a Gemini key without one. The
note in zh, zh-TW, ja and de. The provider-level tabs and Routing's
"keys for Gemini" already had it.
Run on mote (go1.26.8):
- go test -timeout 45m ./internal/provider ./internal/gateway: both ok (provider 229s, gateway 938s).
- TestKeyMadeForGemini, TestKeyProtocolGemini, TestKeysMadeForOneProtocol,
TestKeyForAProtocolWithNoURLIsSaid, TestKeyPoolsByProtocol,
TestCustomGeminiUpstream ok; internal/gui's budget tests ok.
- GUI (node --test, Chromium and WebKit, en/zh/zh-TW/ja/de, 420 and
1000px): key-gemini (new, 40/40), key-nourl, proto-menu-overflow,
key-row-chips-fit, key-plan, key-import, key-weight-fit,
provider-many-keys, provider-gemini, provider-add-gemini,
provider-url-each-api, model-api-gemini, provider-base-api,
routing-keys-fold and i18n-keys ok; the only red in the 360 was
tencent-cloud's region-strip test (#4321, open).
- gofmt -l clean; go vet, GOOS=linux go vet -tags nogui, GOOS=windows
go vet on provider, gateway, gui ok.
Broken by hand: the old fallback.go turns TestKeyMadeForGemini red
(Gemini models went to the Chat or Anthropic key, GPT to the Gemini
one); the old keys.go turns TestKeyProtocolGemini red (unknown
protocol "gemini"), and WithKey keeping p.Gemini turns it red too (the
Anthropic key speaks [anthropic gemini]); the old app.js turns
key-gemini red in all 40.
Not tried: the reporter's relay or any real Gemini-compatible relay;
the real app's editor.
|
||
|
|
083821dc96 |
plugins: a search entry can use the plugin's own sign-in, with its own rests
Asked for by axelburks on Discord. A plugin's search hook entry can name
a provider its own auth hook signs in to, `auth: "<provider id>"`. It then
takes no key. The host picks an account, renews it under `fresh` (the wait
counts within the search's time), runs the hook in `inScope`, and gives it
`ctx.getAuth()`, which returns that account's sign-in. A token the hook saves
with client.auth.set goes to the same account.
The gateway (askSearchSignedIn) asks one account at a time. It takes the
accounts that are on, in the order the provider's model requests take them
(accountsOn, now shared with fallback.go), and puts an account resting from
a search refusal last. A refusal rests only that account's search
(restSearchKey "account <key>"), never its models' rest (restingUntil). Every
attempt gets its own request-log row. An entry without `auth`, or naming a
provider the plugin doesn't sign in to, is a keyed entry as before, with no
getAuth. In Settings → Search, a bound entry shows "Signs in with {name}" in
place of the key field, and the row says whether it is signed in and how
many accounts are on (every language).
Docs: reference.md (with an example), plugin-runtime, plugin-tools and
provider-plugins.
Run on mote at
|
||
|
|
2f726b1f95 |
gateway: a request its vendor's risk control refused isn't sent on to the provider's other accounts (_teamtaylor_)
_teamtaylor_ on Discord: WorkBuddy's risk control spreads across accounts that send the same request, and magpie sent one request on from account to account until its tries ran out, so each account was restricted in turn. The gateway already read the refusal (WorkBuddy's 403 11140 as the plugin words it, provider.WBRestrictedHint; ZCode's 3012, ZCodeRestrictedHint) as failRestricted and rested the account 2h, but the candidate loop then went on to the next candidate, which is usually a sibling account. Now such a refusal (riskRefused: failRestricted and not a remote magpie's) walls the provider off for the rest of the request: its other accounts are dropped from the candidates (elsewhere), from busyNow's replan rounds and from roomy's left-out list (elsewhereWeighed). A group's other provider is still asked; with none left the agent gets the refusal. The last candidate's restricted refusal now rests the account too (before, only a non-last one did). Generic: any plugin ending its error in either hint gets it. The workbuddy plugin needs no change (it does no cross-account retry of its own). Run (on mote, through mote-run): - go test -count=1 -timeout 45m ./internal/gateway: ok (727s), before the rebase onto origin/main |
||
|
|
0a5dc40abc |
gateway: a group's trusted Claude, GPT and Gemini thinking streams as it comes, a refusal or error after it going to the next member (#4166)
A try whose model's vendor may refuse after its reasoning (#248) had its reasoning held while another candidate could answer, whatever the member had answered lately. Through a routing group Claude Code saw a Claude member's thinking only with its text, all at once, and never its "thinking with <effort> effort". waynesguan measured it on one WorkBuddy account: `workbuddy claude-opus-5.5` alone, first thinking at 3.66s; through the group, all 67 thinking deltas with the text at 17.25s. Ported from waynesguan's 71aacaa (on |
||
|
|
a6f5d738fc |
gateway: a group's serial walk has a total budget of 540s (#5113)
Nine members at a 60s first-token wait took 660s, past the 600s a client
waits. The client hung up first and the member it was on was told as the
failure. Nothing bounded the sum of the members' waits.
groupBudget (540s) counts from the walk's start. A member asked with less
left than its FirstToken gets only what is left (holdWriter.budgeted); when
that runs out, or the walk has used the budget, no further member is asked,
the member isn't rested (it was cut short, not slow), and the error is a 504
naming the budget. A client cancel was already read first (nobody blamed),
and is unchanged.
Reported by mycf_711 in #5112; #5113 stays open for the reporter.
Run at the pushed head (rebased on origin/main
|
||
|
|
e41ef6288c |
providers: a spend cap on an API key, per day, month or in all (sparkling_lemur_62868)
sparkling_lemur_62868 on Discord: a team's OpenAI key holds granted credits that other docker services spend from too, and they want magpie to stop at a share of it. Their workaround was two magpies behind a gateway-key limit. What changed - provider: KeySpendCaps on a provider, keyed by the key's fingerprint (key_spend.go): USD over a local calendar day, a local calendar month, or in all since it was set. Since is kept while the cap stays one in all. SetKeySpendCap and ParseSpendCap refuse an amount outside 0 < usd <= 1,000,000 and an unknown period, and leave the saved cap as it was. Subscriptions are refused, since an account has its own usage-window cap. - usage: KeySpent(keyID, start) is what magpie's own calls on the key cost at the Usage page's prices. Turned-away calls and app-reported ones are left out. It reads usage.jsonl once per key and start, keeps the sum for 5 minutes, and Append counts each new call into it (spentNew). A read that a write races is read again. - gateway: perKeyEvery bars a key at its cap (spendHeld) as a usage cap holds an account. The next key serves, then the fallbacks. With none, the reply is 429 "spend cap reached: ..." naming each key, what it spent of which cap, and how to go on. Retry-After is when the soonest period renews; a cap in all gives none. A spend hold is not a usage cap: Stop at the caps and strictKeep don't end at it (capHeldOnly). The trace's barred row carries the cap, the spend and the period. - GUI: a pill on each key's row in the provider editor, for example "$7.50 of $20.00 today". It opens the app's menu (No spend cap, Per day..., Per month..., In all...) and then takes the amount in place, as the lane-limit pill does. A key at its cap gets a line under its row: "At its spend cap · back in ...". Every string is in all five languages. The pill and the line are in keyspend.js, which app.js imports when it draws a key's row, so the core's script budget is not raised. /api/providers' keyList carries spend, and POST provider/keyspendcap sets it. - CLI: magpie provider spend-cap <id> [key [usd [day|month|total]|off]] lists each key's spend and sets or removes a cap. - docs: providers-accounts.md and gateway-routing.md. Caveats, also in the tooltips: - What counts is magpie's priced usage, not OpenAI's bill. - A model with no known price counts $0. - Requests already under way when the cap is reached still finish, so a key can go a little past it. Run on mote at the pre-rebase head ( |
||
|
|
6c08ee13b0 |
gateway: a model asking for earlier reasoning back goes on to the group's next member
EDwinpzy (Discord #feedback, magpie 0.1.2717): Command Code's reflection/beam:free answered a second turn with 400 "Missing required parameter: 'messages[N].reasoning_content'". The 400 wasn't retryable, so a routing group of Beam then Glyph ended at Beam and never asked Glyph. The client's request is whole; it is that model's demand for history it doesn't have, and another member's model may not make it. reasoningBackRefused (thinking_back.go) reads the demand: DeepSeek's "must be passed back" (thinkingBackRefusal) and words that name reasoning_content as missing or required. shapeRefused and retryable take it, so the member fails as a shape refusal (failShape): no rest, the next member is asked once. refuseThinkingBack's refill still runs first, inside forwardOnce. A 400 for a missing 'messages' or 'model' still stops at the first member. The plugin side (commandcode 0.1.22 fills Beam's earlier replies with reasoning_content) ships separately. Tests: TestGroupFailsOverAMissingReasoning (chat and responses routes, the reporter's two-turn shape, his words in the Provider API's error JSON) and TestMissingReasoningIsNotABadRequest. Run on mote: go test -count=1 -timeout 45m ./internal/gateway: every test passes except TestCodexPoolSaysTheClientsVersion, red in a full package run and green alone, already filed as #4807 (another test's Codex identity reaches it); go test ./internal/provider ok; GOOS=linux and GOOS=windows go vet ./internal/gateway ok; gofmt -l clean. After a rebase on |
||
|
|
e8b6c3d357 |
gateway: a webp a vendor can't read is written again as a JPEG, and GLM's word for one fails over (#4732)
Claude Desktop's browser tool answers a screenshot as image/webp, and GLM can't read one: its 400 [1210] "图片输入格式/解析错误" turns the picture away, and its Anthropic-style endpoint says of the same picture 400 [1214] "messages[0].content[0].file必须传入file_id、file_url、 file_data至少之一", having taken it for a file of its own — the two alternating (zhangqingwen204's report). The picture rides in the conversation's history, so every later turn was refused the same way, and the session was stuck; another model or provider of the same conversation fared no better. Now the request is asked again with the picture written again as a JPEG (as PNG when it has transparency), the way a HEIC is (heic.go), and the provider is remembered (unfit, webpRefused) to have every webp of its requests written again before they leave — the session's later turns pay the refusal no more. The words themselves join the shape refusals (shapeRefused, retryable): a request no webp of whose can be written again (one gone as an URL, say) moves to the next member, which may take the picture as it is, and this one doesn't rest. Z.ai's bare "1210", its word for a model that always thinks, is none of this: the family is the double-bracket "[1210][" and "[1214][" forms and the two wordings, read decoded (#1669). Most vendors take webp, so nothing is written again for them until their first refusal says otherwise. Run: go test -tags nogui ./internal/gateway/ Generated-by: GLM-5.3-Flash (ZCode) Landed from ggbdpq's branch (patch posted on the issue; sha256/patch-id checked against the issue) by yetone, rebased on origin/main 2026-11-03. Run at the pushed tree, on mote (macOS): go test -tags nogui -count=1 of internal/gateway with -run over this batch's tests and their families (PlainSchema, Antigravity, AutoMode, WebP, ClaudeTUI, NativeRelay, Namespace, Grok, Zed, Codex, ClinePass, rewrite) ok; -race -count=3 of the new tests ok; GOOS=linux and GOOS=windows go vet of internal/gateway and gofmt -l clean. The full gateway-and-importers run, started at an earlier base, was still running at the push; its reds get issues. Changed in review: the ask-again records the try (failShape) in the route trace, as the serve loop's other ask-agains do. Broken by hand: the serve-loop branch and the pre-send rewrite turned off, TestWebPRefusalHealed red; restored, green. Not tried against GLM. The issue doesn't show the screenshot's media type, so 'Claude Desktop's screenshot is webp' is the reporter's reading, not checked here. |
||
|
|
ad53a23dc8 |
gateway: X-Magpie-Account takes a percent-encoded name (plugins#615)
StockRabbit (magpie-community/plugins#615, Magpie 0.1.2587, Windows): pinning the Fingerprint page to the WorkBuddy account 北冥 failed every sample with "Header 'X-Magpie-Account' has invalid value". A header value is ASCII on the wire and fetch refuses any other, and the gateway matched the header only against the account's user (北冥) or its trace id (workbuddy@北冥/…), so no ASCII form could name that account. pinTo now matches the value as written or percent-decoded (pinnedName: url.PathUnescape, kept only when it decodes to valid UTF-8). The trace's Pinned, the call's error and the 404's "no account %q" name it decoded. gateway.go:2701 is the one place that reads the value; codex_backend.go, codex_relay.go and gateway.go:2523 test only that it is present, so they need nothing. docs/reference.md and the gateway-routing page say how to send such a name. Run at this head (rebased on |
||
|
|
eb3b9376ea |
plugin load: a model listed by another id gets its plugin's load (axelburks)
axelburks on Discord: a plugin reports a model's load through
input.magpie.load by its own model id. A model the user lists in magpie
under another id (Listed as, settings' ModelIDs) showed no load on the
Providers page, and with Busy models last on it was never judged busy;
models whose id wasn't changed worked. The reporter's reading was right:
plugin.ModelLoad keeps the load by the plugin's id and both callers asked
it by the listed one.
Both call sites of plugin.ModelLoad (grep: there are only two) now map the
listed id back through Provider.OwnModelID first:
- internal/gui/providers.go providerInfoWith (models[].load), which
already computed OwnModelID for models[].vendor; it is now read once
and used for both.
- internal/gateway/fallback.go busyOf (restLast's busy ordering and the
trace's busy).
A listed id whose own id is a model@size (grok -> grok-4.7@256k) still
falls back to the model's load inside ModelLoad. The provider-plugins
subsystem page says the lookup is by the plugin's own id.
Tests:
- internal/gui TestModelLoadListedAsAnotherID: a plugin provider with
fast -> big and grok -> grok-4.7@256k listed, loads noted for big,
grok-4.7 and small; models[].load must be 87.4 / 60 / 12 for fast /
grok / small and absent for quiet.
- internal/gateway TestBusyModelListedAsAnotherID: busyOf at 80 judges
fast, grok and big busy, and an unreported model not.
Run at the pushed head on mote (mote-run):
- at base
|
||
|
|
8d7439a1a0 |
gateway: a translated system turn is folded for a Responses upstream, and a relay's "Upstream request failed" 400 fails a group over (#4632)
Two faults, one turn. Claude Code 2.1.296 and later send their
environment as a message with role "system" inside messages
(Request.envInTurns). The Chat and Anthropic builds fold such a message
into the system prompt (responseInstructions); buildResponses wrote the
role as it came, and a relay whose Responses endpoint fronts the ChatGPT
backend — which takes user, assistant and developer alone — answered
every translated turn 400 "Upstream request failed". That 400 matched
none of the wordings that make a 4xx retryable, so the holdWriter held
it as final and the group's second member never ran: the relay's answer
went to the agent, every turn.
What changed: buildResponses folds a translated request's system and
developer messages the way the Chat and Anthropic builds do, keyed on
the read. A Responses client's own instruction items are kept by the
read (#2532) and go where they stood; so do a codex account's, which
its send says as developer ones in place (codexBody — the fold would
move them out of conversation order, so buildFor marks the account's
requests kept). A translated request's system message is the harness's,
so it is said in the instructions, and one after a reply is told as a
user <system-reminder>, as on every other target. A relay's own word
that the provider behind it turned the request away ("sub2api: Upstream
request failed", type upstream_error — the words the Codex compaction
already reads, #866, #1511) joins the wordings that make a 400 or 422
retryable (retryable) and fail a group over (shapeRefused): the next
member is asked, and nobody rests. A 400 that says nothing of the kind
still ends the route, as a bad request would fail on every member
alike.
Run: TestClaudeSystemTurnSaidInTheInstructionsOnResponses and
TestGroupFailsOverARelaysUpstreamFailed, red at upstream/main
|
||
|
|
85e37162e9 |
routing: a route group can be held to chosen accounts (duanckham on X)
duanckham has a personal and a company GPT account, one tool and one gateway, and wants a group's GPT models to spend only the company account (or only his own). A second gateway key doesn't fit: his tool talks to one gateway, and a local agent needs no key at all. Group.Accounts holds a group to some accounts or keys of the providers it names, in a gateway key's form and by the key's rule (#905, Identity.AllowsAccount). The asked group narrows the request's identity (access.Identity.HeldToGroup: the strict intersection with the key's own list; "<provider>/\x00" when they share none), so every gate a key's accounts go through holds the group's too: chat, responses, messages, count_tokens, embeddings, images and video, streamed or not. A group reached inside another, as a member or a fallback, is held in planLevel (hold, Member.Via): its candidates on an excluded account are Held rows with Weighed.HeldBy, which the Routing trace tells. Fallback stays within the group's entries; with every allowed account resting or out the group's usual error comes back, and a key and a group that share no account get a 403 naming the group, nothing asked upstream. SaveGroup resolves each entry (ResolveAccount, shared with the key's CleanAccounts); share and import drop them. A group without accounts is as before. GUI: the group editor's Accounts section, a row per member provider with two or more accounts, "Any of its accounts" until some are ticked in the app menu (openPicker multi). Every save sends accounts, since a save replaces the group. Strings in all five languages. Gateway keys stay as they are: Gateway › "Gateway keys are for other computers … added here once Share on local network is on" already says where, and this case needs none. Run (mote, through mote-run), at cafed0067 on origin/main |
||
|
|
eb7e72cc7f |
gateway: a response.completed with no output and no tokens fails over (#2471)
What changed: a Responses upstream that ends its 200 stream with a
response.completed carrying no output and counting no token - WorkBuddy
AI's account answered Codex's request with created, in_progress,
completed and `output: []` three times running (MurmuredVelpro) - had
the completed event taken for a reply's end: the held stream went to the
agent as a completed turn, the try stood as a 200 success, and the
group's healthy members were never asked. streamEvent now reads a
completed with an empty output and a zero usage as the no reply it is -
the same shape a translated reply that said nothing and counted nothing
has failed as since #2086 (repliesCounted) - and fails the held try for
the group's next candidate, in the candidate walk as an empty reply's
does: nobody rests, as the reply's shape failed, not the account. A
completed that counted a token stays a reply, as Claude's own empty
end_turn does; and an event this reaches is one nothing was said before,
since the hold lets the first content through and reads no event beside
it, so nothing of the try has reached the agent when it fires.
The fields said are what is read: a completed that names neither field
goes as it came, as the streamEvent table pinned it
(TestStreamEventRefusals, which caught the first draft reading an
omitted output as an empty one), and a completed that counted a token
stays a reply.
Run: TestEmptyCompletedFailsOver (new) red on
|
||
|
|
a5a9cdf7be |
gateway: a refused big conversation isn't told again to the Claude subscription's other accounts (Aisiverto on X)
Aisiverto on X: a refused turn of a ~900K-token conversation made magpie switch accounts and send it again, "one user action becomes several expensive requests". In the usage, pairs ~100ms apart: one read the whole conversation from the cache, the other read ~26K and wrote ~877K. The cause: a refusal goes to the next candidate under RefusalRetries (unset: every one left), and matesFirst puts the same model's other accounts first (#248, where a verified account may answer). For a Claude subscription each other account is a new Claude Code told the whole conversation, all of it written to that account's cache again, for a refusal about the content that it most likely gives too. Now, before a Claude subscription account's try, a conversation of retellMost (100K) tokens or more by estimate (tooBigToRetell) leaves the subscription's other accounts out if that account refuses (otherThanClaudeAccounts). Other members are still asked; with none left the refusal is the agent's, and it isn't handed over mid-stream to nobody (handsOver is given last). A smaller conversation goes to the next account as before. The size is measured only when another Claude subscription account is left. gateway-routing.md says so beside RefusalRetries. Run: - TestClaudeSubscriptionBigRefusalNotToldAgain (new; streamed and not): red on the old code (runs "own,tok-spare"), green with the fix, the agent getting the refusal. TestClaudeSubscriptionRefusalMovesToNextAccount (small conversation, spare still asked), TestRefusalRetries* and TestPolicyRefusal* green. - Broken by hand: tooBigToRetell always false, red. - On mote: gofmt -l clean; go vet, GOOS=linux go vet -tags nogui and GOOS=windows go vet of internal/gateway ok; go test -tags nogui -timeout 45m ./internal/gateway: ok (702s). The whole suite ran at the parent commit (its body); this commit touches internal/gateway only. Not tried: - The handsOver change: the test's refusal comes with no reasoning before it, so nothing is handed over, and taking the change out stays green. Not covered by a test. - A large conversation where another member of the group is a Claude subscription of a different provider id: it is left out too, as every Claude subscription account is. - A real Claude refusal on a real account. |
||
|
|
8d8df06399 |
plugin, gateway: a plugin reports its models' load, and busy models can go last (axelburks on Discord)
axelburks (Discord #feedback): an in-house vendor queues requests to
its busy models, and the plugin could only put the load in the model's
name, which changed only when magpie re-read the list.
- A provider plugin calls input.magpie.load(provider, {"<model id>":
0-100 | null}) whenever it likes, from its own timer. host.js
(reportLoad) clamps each number to 0-100, null clears a model, every
other value is dropped, at most 1000 a call, and it returns the count
taken. A provider that isn't a string or loads that isn't an object
throws a TypeError. It goes to Go as an unasked {event:"load"}.
- internal/plugin/load.go keeps each by provider and lowercased model
id. ModelLoad answers unknown once a load is older than LoadFresh
(5 minutes), never idle. model@size falls back to its model.
- The provider editor shows it by the model as a grey ctx badge
("87%", titled "87% busy now, as its plugin says").
- Settings > Network and sharing > Busy models last (settings.BusyLoad,
POST /api/settings/busy-load, Off by default, over 50/70/80/90% or
1-99 by hand): restLast puts a model reported over it behind the
ready candidates, ahead of the resting. The trace row has busy:<load>.
At a new turn affine moves a conversation off it (Why "busy",
busyBehind); within a turn it stays. after, readyForNew and leastHeld
skip it. Unknown load, a lone candidate, or all busy: nothing moves.
- Docs: site plugins page (en, zh, ja) "Model load" section and input
table; docs/subsystems provider-plugins.md and gateway-routing.md.
Run, all on mote via mote-run at a42736807's tree rebased on
origin/main
|
||
|
|
699ddf1524 |
gateway: a Codex account can spend its credits only after every other account, key and fallback (gokoshiki on Discord)
gokoshiki wants a Codex subscription first, then an OpenAI API key, then the subscription's credits. Until now an account at 100% that holds credits either kept its place and spent them there (on) or was held (off). This adds a third way per account, "last": - settings: CodexCreditsLast []string, empty by default, so a setting saved before it keeps its order. provider.CodexCreditsLast, CodexCreditsMode and SetCodexCreditsMode(user, on|last|off); SetCodexCredits(on) still means "in its place" and clears last. - gateway: candidate.creditsLast is true for such an account once a window for the model is used up and it is going on its credits (a call ChatGPT counts in no window stays in its place). restLast orders ready, then resting, then those, and marks Weighed.CreditsLast. restLast runs over the asides too, so such an account goes behind a provider's reserves (Accounts at once, |
||
|
|
2c6b7c0632 |
gateway, provider, gui: Accounts at once keeps the first N accounts taking requests, the others in reserve
01huadalang on Discord (#feedback 1566170404542742740): three ZCode
accounts used at once from one address got the address refused with a
405; two were served. They asked for one account to be used until it
runs out, then the next. Even under "In order", ZCode's maxConcurrency 3
spilled a full lane onto the next account (laneMate) and rests spread
the load, so every account was in use at once.
A provider's MaxAccounts (the editor's Advanced → "Accounts at once",
beside Concurrency; `magpie provider at-once <id> [n|off|default]`) is
how many of its accounts or keys take requests at the same time.
provider.AtOnce() is the user's own value, else what its plugin
declares (maxAccounts on the auth hook or package.json magpie, read by
host.js atOnceOf), else no limit; the user's 0 is no limit over the
plugin's. perKeyBarred keeps the first N in the user's own order
(rank), preferring ones not resting, and keepAtOnce puts the rest after
everything as asides with candidate.reserve (Weighed.Reserve). So in any
routing mode a reserve is asked only once the kept ones failed or rest,
and a kept one that rests gives its seat to the first reserve next time.
Guards: laneMate never spills onto a reserve; a full queue (laneErr)
drops the provider's reserves (dropReserves) and turns the request away
with the 429; session affinity moves a conversation off a reserve once
the kept ones can take it (affine "reserve"; Strict still holds).
Routing says "in reserve · {n} at once" on the row and why in the
request's story. zcode 0.1.40 (plugins 26864ec, on npm) declares 2, and
its mover min is raised to 0.1.40 two commits on.
Known leak, in docs/subsystems/gateway-routing.md: a failure that rests
nobody (a 5xx on one try) still passes that one request to the reserve,
as it does to any next candidate.
Tests: TestAtOnceKeepsFirstInUserOrder (every routing mode, a dragged
order, a resting key handing over its seat), TestAtOnceFullLaneWaitsForTheKept,
TestAtOnceReserveTakesOverAndGivesBack, provider TestAtOnce, plugin
host maxAccounts (hook and package.json), gui TestAtOnceSave, cli
TestAtOnceCmd, provider-at-once.test.cjs (both engines, five languages,
900 and 360px).
Broken by hand, each red then restored: laneMate's reserve guard
removed (FullLane times out); affine's reserve case removed
(ReserveTakesOver answers on k3); keepAtOnce disabled (all three red);
dropReserves disabled (FullLane gets no reply); the Routing row's
reserve branch removed (provider-at-once's Routing test red in all 10
engine/language runs).
Core budget: the field adds ~530 bytes to app.js; the neighbouring
editor comments are cut to fit, so TestCoreScriptBudget passes with no
raise.
Run on mote, Go 1.26.8:
- full suite, -timeout 45m, at a7d4c662d (on origin/main
|
||
|
|
5bfa9f0762 |
gateway: a group's backup gives the conversation back once the member listed ahead of it is ready again (01huadalang on Discord)
01huadalang on Discord, after |
||
|
|
645eb92f3f |
gateway: a refusal after shown thinking goes to the next fallback
yhwangl on X: a request whose content trips a vendor's safety filter after the model streamed its thinking, before any answer, stopped there; the group's next member was never asked, as it is when credit runs out. When a model's reasoning is shown, a try passes on its first thinking event, so a refusal after it was the agent's. Now, for a streamed Anthropic, Chat or Responses request with another member still to ask (handsOver), the try's events go out one by one (passOver) and a refusal or refusal error before any text or tool call hands the request on (handOver): Anthropic's open blocks are closed and the next member's stream is spliced into the same reply (spliceAfter): its message_start or response.created/in_progress/queued are dropped, block indexes or output_index go after those sent, sequence_number goes on. Chat chunks go as they come. Once text or a call has gone, a refusal stays the agent's as before. With no other member nothing changes. A refusal is about the request, so nobody is rested for it. Zhipu's finish_reason "sensitive" and error 1301 (敏感), DashScope's data_inspection_failed and Volcengine Ark's *SensitiveContentDetected are now read as refusals too. Not covered (#4604): Gemini clients; a Responses reasoning item handed over gets no output_item.done and the next completed lists only its own output; A's thinking signature stays in the reply; non-streamed requests. Run (mote, worktree at base |
||
|
|
2cca111764 |
gateway: a 413 byte cap or an overflow tells Codex context_length_exceeded, so it compacts instead of reconnecting 5/5 (celestial_eagle_99230 on Discord)
A Codex user on a DeepSeek model kept getting "stream disconnected
before completion: 1017dp: 413 Request Entity Too Large: a web page,
not an API reply ... (request_too_large)" with "reconnecting 5/5".
The big body took the vendor past keepHeldAfter, so Codex's stream
had begun, and streamError sent response.failed with code
server_error. Codex (codex-api sse/responses_error.rs) reads any code
it doesn't know as Retryable, so it sent the same body five more
times. Each was refused the same way, and nothing compacted.
context_length_exceeded is the one code Codex stops on: it marks the
window full and compacts, and core compact.rs trims the oldest items
for as long as the compaction is refused too.
- streamError: a 413 on the Responses shape is code
context_length_exceeded, for every Responses client. The text still
says request_too_large for pi.
- failTo: Codex reads a 413 told by HTTP status as UnexpectedStatus,
and a 400 context_length_exceeded as InvalidRequest
(api_bridge.rs). Neither compacts. So when Codex (fromCodex, or
Claude Code's Codex plugin) asked for a stream, a byte cap or an
overflow goes to it in a stream even before one began
(keptAlive.compactsInStream). A vendor's own overflow, released
until now, goes this way too. Other clients keep the status they got
before.
- Nothing changes for resting: a 413 still rests nobody, and a group
still tries the next member first.
Tests: codex_byte_cap_test.go. It replays the reporter's nginx page
mid-stream and before the stream, plus a vendor overflow 400, and
checks a non-Codex client keeps its 413. Red on the old code:
TestCodexByteCapInStreamCompacts got "server_error" (the reporter's
exact text), and both TestCodexByteCapBeforeStreamCompacts cases got
a 413 or 400 JSON. TestStreamErrorByteCapInEveryShape now expects
context_length_exceeded for Responses.
Run on mote (mote-run, this tree): go test ./internal/gateway on the
byte-cap, stream-error, overflow, compact and Codex tests: ok. GOOS=linux
and GOOS=windows go vet ./internal/gateway: ok. gofmt -l: clean.
Full suite: mote-run go test -timeout 45m ./... at
|
||
|
|
6585315e32 |
gateway: a DeepSeek member's reasoning streams through once it has answered cleanly three times running (#4512)
|
||
|
|
7e0fe83d4b |
provider: Listed as works for signed-in accounts and plugins (zeewell on X)
zeewell asked to list SuperGrok's grok/grok-4.6@500k as grok-4.6, and Cursor, Devin and WorkBuddy models (all plugins) under ids of their own. v0.1.2345's "Listed as" took ids only for key/relay providers (takesModelIDs was p.Account == nil). Why the restriction was there: the wire rewrite (Settings.Wires) turns the request body's model back into the own id, but some code reads the model by the vendor's id before that and got the listed one: - plugin model lookup (pluginModel: the plugin's APIs, tiers, prices); - the Claude subscription run (--model given to Claude Code); - Code Assist/Antigravity variant choice (codeAssistBody, SentNameOnIn); - account plan lists (fallback's Account.Lists, effort Levels/Tiers, AccountServes); - moveModelRefs refused a provider with no providers.json entry, which is every plugin and account provider until a pick is set. Each now translates with OwnModelID / the provider's ModelIDs, so the upstream request still carries the vendor's or plugin's own id. Only a decide-only provider refuses an id. The GUI box already follows TakesModelIDs, so no GUI file changed. Tests (red on the old code, each fix reverted by hand one at a time): - TestModelIDRefused, TestModelIDAtAnAccount (takesModelIDs, AccountServes, SentNameOnIn); - TestLocalModelIDAtAPlugin (Bun fake plugin: /v1/models, upstream path, X-Plugin-Model, body, usage; red on pluginModel and on moveModelRefs); - TestLocalModelIDAtAnAntigravityAccount (codeAssistBody); - TestLocalModelIDAtAClaudeAccount (claude got --model my-sonnet); - antigravity pool test (fallback Lists, Levels). Run on mote: gofmt clean; go vet darwin/linux/windows ok; go test -tags nogui -count=1 -timeout 45m on internal/provider, gateway, cli, gui, settings, access, usage, plugin: all ok except internal/gui's TestSettingsSaveKeepsWhatItDoesNotSend (SearchAll), red on main since |
||
|
|
c8f199695c |
gateway: DeepSeek's reasoning is held for a refusal after it; WorkBuddy plugin min 0.2.4 (plugins #540)
itspig (plugins #540): deepseek-v4.1-flash on WorkBuddy, through group/tiered, reasoned ~5s, said "Sorry, I can't respond to this question.", and ended finish_reason content_filter with 0 output tokens under a 200. The try was recorded done/200, none of the 15 members behind it was asked, and DeepSeek Harness failed "The model refused to complete the request". Two halves: - workbuddy 0.2.4 (plugins 4883f94) takes the filter's canned line out of a streamed chat that ends content_filter with nothing else said. - refusesAfterThinking now holds DeepSeek's reasoning too (as Claude's, GPT's and Gemini's), only while another candidate could answer: with it let through as it came, a refusal after it could never go to the next member. DeepSeek's own API documents finish_reason content_filter. The cost: in a group with a member behind it, DeepSeek's thinking reaches the agent once its text begins (kept alive meanwhile), as Claude's does; on the last candidate it streams as before. GLM, Kimi and others are unchanged. - The workbuddy mover's min is 0.2.4 (npm view --prefer-online: 0.2.4). Run on mote at this tree: go test ./internal/gateway -run 'TestDeepSeekRefusalAfterThinkingFailsOver|TestThinkingHeldFor| TestRefusalAfterThinkingFailsOver|TestThinkingStreams' ok; go test ./internal/provider ok; gofmt -l clean. The full ./... suite was started at this tree minus the one-line min and is still running; its result goes on plugins #540 (owner rule: tag without waiting). Broken by hand: without the deepseek prefix, TestDeepSeekRefusalAfterThinkingFailsOver/refused goes red (DeepSeek's reasoning reached the agent, b never asked) and TestThinkingHeldFor red for the three DeepSeek ids; /answered stays green. Not tried: a real WorkBuddy refusal (no prompt reproduces it on demand); the upstream's literal chunking isn't in the issue, so the fixture is built from its fields (reasoning, content_filter, 0 tokens). |
||
|
|
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 |