Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
gateway: a plugin's try with another candidate after it is told so, and gives way to a queue (#4049)
yetone046093bf7b40
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex 823652fc7..ba3bc7963 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -220,6 +220,7 @@ recorded as a prediction failure (`noPrediction`).- Only an account is held at a usage cap (`capHeld`) or rested out of one model's pool (`pooled`); a key's windows order it and rest it, nothing more.- A rest of one model alone (keyed by `restID`: a pool, a model not served, a paid model beside free ones) names that model in the trace (`Rest.Model`). The Routing page shows it on that model's rows only: the account's other models' rows on the stage, and the account's row under Accounts and keys, don't read as resting. The account's row names the models resting on a line of their own under what it has left, and its Try now lifts their rests. A kept request from before `Rest.Model` has the model on the end of `Rest.Key`, which the page reads the same (`restModel` in `plugins/routing/client.js`, #1960, `routing-model-rest.test.cjs`).- A group member let go for no first content within the group's `FirstToken` (`hw.slow` in [`gateway.go`](../../internal/gateway/gateway.go), 504 "no first token in Ns", `failSlow`) doesn't rest the first time: a long prompt is slow to start anywhere. Slow again on the same account's model with no answer from it in between, and within `slowForget` (30 minutes) of its last slow start, that model rests on that account (`restSlow` in [`routing.go`](../../internal/gateway/routing.go), keyed by `restID`, `Rest.Model` set): a minute from the second time (`slowRests`), doubling each time after, up to the provider's rest cap (`RestCapOr(longestRetry)`), and never for a provider whose cap is off. Its answer clears the count (`servedCandidate`). A request its client cancelled counts nothing, as the cancel is read before `hw.slow`. Before it, each new request asked the stalled member first again and waited out the whole `FirstToken` (小八 on Discord: a WorkBuddy account's kimi-k3-1 and glm-5.3 stalled 58 times on the vendor's per-model token limit, 15 times in 17 minutes in one session). The same model on another account and another model on the same account are asked as before (`TestSlowStartsRestTheModelOnItsAccount`, `TestCanceledSlowStartRestsNothing`; the Routing page's story, `routing-went-on.test.cjs`).+- A plugin's try that isn't the last candidate is sent with `x-magpie-fallback: 1` (`provider.FallbackHeader`, `withFallback`), so a plugin whose vendor queues the request (Qoder's 10605, CodeArts' `queue-status: queued`) answers a `busy` 503 with Retry-After and the queue's reason at once instead of waiting minutes in the queue, and the next is asked; the last candidate isn't told and waits as the vendor's client does ([provider-plugins](provider-plugins.md#whether-another-candidate-follows), `TestPluginToldAnotherFollows`).- A 402 is out of credit, unless it speaks of a usage limit (`usedUpWords`) and nothing of money (`creditWords`, `insufficient_quota`): then it is out of quota, and rests only the model when the account's windows say its pool is the one used up (`pooled`). Factory answers Standard's pool used up with 402 "You've reached your weekly standard usage limit (resets in …). Switch to Droid Core …"; read as credit, it rested the account 30 minutes and its Droid Core models with it (#1979). Both the built-in's windows and the plugin's (Standard's `notModels`, Core's `models`) are held to it. As a quota rest it lasts until the time the refusal names (`resetsAfter`: "resets in 0h 19min", "resets in 2d 3h", held to `longestWritten`), else the window's end, else `quotaRest` or the provider's own `quota-rest`, and is lifted once a reading finds the window renewed (`renewed`), which a credit rest never was (`TestFactoryStandardOutLeavesCore`, `TestPaymentRequiredReadByItsWords`, `TestResetsInWords`). An account whose windows weren't read yet (a start, or a reading that failed) can't tell the model's pool from the account's, so it rests whole, and `narrowWhenRead` waits off the request for a reading (`AwaitAllowance`, up to `allowanceWait`) and moves the rest to the model alone (`restID`, the same end) when the reading says its pool is the one used up; no reading in time, or one that says the whole account, leaves the account's rest, as does a rest lifted or made again meanwhile (#2036; `TestFactoryStandardOutLeavesCore`'s unread case, `TestResetsInWords`). The request itself isn't held for the reading: it has failed over already, and the rest's scope only matters to later requests.- Codex offers its image tool (the `image_gen` namespace, #870) to every magpie provider. When a provider other than a ChatGPT sign-in or openai.com answers a bare 400, `attempt` asks it once more without the tool (`image_tool.go`). This happens both passed through and translated. If that works, the provider is marked unfit for the tool (`tool:image_gen`) and isn't offered it again. If it doesn't, the tool is restored and the 400 stands (#949).- A turn the agent stopped with its tool call still out is replayed by the client with the call and no result, and Google's APIs turn a history whose call turn goes unanswered away with 400, every later turn of the conversation with it. The Gemini build (`buildCodeAssistSent`, which serves a Google sign-in, Vertex AI and a custom provider's Gemini API alike) answers such a call with the synthetic result the chat build pairs an interrupted turn's call with (`pairToolMessages`, #1275), right after the calls (`pairFunctionTurns`, #1560): beside the answers the client sent there, or in a user turn of its own before what the user said, since a turn mixing a `functionResponse` with text is turned away too (#1533); a Claude model on Antigravity gets it in the one tool_result turn. A call with no id counts as answered by a response of its name. A second answer to one call is left out, with the images it carried, before the turns are built (`dropSecondAnswers`, #2262): Google refuses a call turn whose `functionResponse` count differs from its `functionCall` count, and the Chat and Messages builds already keep the first answer. The Responses build (`buildResponses`) leaves it out the same way. A call made again under the same id takes an answer of its own. A Gemini client that keeps no ids answers two calls of one function by name in their order, and each answer goes to its own call (`parseGemini`), not both to the latest. `TestGeminiDropsASecondAnswer`, `TestSecondAnswerDroppedWithItsImages`, `TestGeminiClientUnnamedCallsAnsweredInOrder`.diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.mdindex 86289c82f..f120d03f1 100644--- a/docs/subsystems/provider-plugins.md+++ b/docs/subsystems/provider-plugins.md@@ -111,6 +111,16 @@ Each is left off when it isn't known: no folder said, or a folder not on this co`TestPluginToldWhereTheAgentWorks` ([`plugin_workdir_test.go`](../../internal/gateway/plugin_workdir_test.go)) sends Claude Code's and Codex's captured requests and Pi-style ones from a folder in a repository and one not, through the fake plugin, and checks what the plugin read and that the vendor got neither header.+## Whether another candidate follows++A free model's vendor may queue a request for minutes: Qoder answers its code 10605 and its plugin waits in Qoder's queue as Qoder's client does (up to 4 minutes), CodeArts answers a 429 with `queue-status: queued` and its plugin polls the trace for up to 5 minutes. While another account, provider or routing group member could answer at once, that wait only keeps the agent waiting (axuhere on X: "模型请求正在排队 · 预计等待超过 10 分钟").++So the try loop marks a try that isn't the last candidate (`withFallback` in [`continuation.go`](../../internal/gateway/continuation.go), from `!last` in the loop), and `forwardOnce` sets `x-magpie-fallback: 1` (`provider.FallbackHeader`) on that plugin request; a header the agent sent under that name is dropped first. A plugin told so answers a queued request at once, a 503 with the queue's Retry-After and a message that says the queue (Qoder 0.2.40: "Qoder queued the request for dfmodel (this plan's queue: p3, 3 ahead); try again in 30s"; CodeArts 0.2.3 leaves the queue first). The 503 is `busy`, so the next candidate is asked, the trace shows the try's reason, and the queued one may be asked again in a replan round after its Retry-After. The last candidate is never told, and its plugin waits in the queue as the vendor's client does. `unsaid` in `host.js` takes the header off whatever the plugin sends on. A plugin model's test sends it as well, so a queued model is said at once there too (`probe` in [`test.go`](../../internal/provider/test.go), `TestPluginModelTestSaysQueued`).++`TestPluginToldAnotherFollows` ([`plugin_fallback_test.go`](../../internal/gateway/plugin_fallback_test.go)) sends a group of two members through the fake plugin: the first is told, gives way with a 503, and the second answers untold; a lone model is never told, and the vendor never gets the header.++Trae's plugin doesn't give way yet: Trae.app reads a `queue_info.position` on its own chat stream, but no real queued reply on the `llm_utils_chat` path the plugin uses has been captured, so its queue events stay ignored.+## Two plugins for one provider idThe host runs one plugin per provider id. When two installed plugins have `auth` hooks for the same id, such as a third-party plugin and the user's own copy added by its folder, `auths()` in `host.js` takes the one picked for that id in `plugins.json`'s `prefer` map (provider id → spec). Without a pick it takes the last one in the list, as OpenCode does. Only the serving plugin's `provider.models` hook runs for that id. Every plugin's `config` hook still runs, so another plugin can still add models or a name to `config.provider[id]`.diff --git a/internal/gateway/continuation.go b/internal/gateway/continuation.goindex 8c6c6eb6c..90d78160c 100644--- a/internal/gateway/continuation.go+++ b/internal/gateway/continuation.go@@ -203,6 +203,19 @@ func inGroupTry(ctx context.Context) bool {return v}+// fallbackKey marks a try with another candidate after it: a model's next+// account, provider or group member.+type fallbackKey struct{}++func withFallback(ctx context.Context) context.Context {+ return context.WithValue(ctx, fallbackKey{}, true)+}++func hasFallback(ctx context.Context) bool {+ v, _ := ctx.Value(fallbackKey{}).(bool)+ return v+}+// prefillHow is how the upstream a reply is translated to goes on from// the part of it the client has, sent back as the conversation's last// assistant message: an Anthropic Messages upstream natively, a Chat onediff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.goindex b23b68ce4..e6d2565ff 100644--- a/internal/gateway/gateway.go+++ b/internal/gateway/gateway.go@@ -2950,6 +2950,12 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Proif ultra && from == provider.Anthropic {ctx = withUltra(ctx)}+ if !last {+ // another candidate is asked if this one can't answer+ // now: a plugin whose vendor queues the request says so+ // at once instead of waiting in the queue (FallbackHeader)+ ctx = withFallback(ctx)+ }hw.stop = stopif autoPicks(c) {// the reply names the pick it went as last (#256: it@@ -4424,6 +4430,10 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to providif p.IsPlugin() {req.Header.Set(provider.ConversationHeader, conversationID(in, body))tellWorkPlace(req.Header, to, body)+ req.Header.Del(provider.FallbackHeader)+ if hasFallback(ctx) {+ req.Header.Set(provider.FallbackHeader, "1")+ }}if p.IsRemoteMagpie() {passOnCaller(ctx, req)diff --git a/internal/gateway/plugin_fallback_test.go b/internal/gateway/plugin_fallback_test.gonew file mode 100644index 000000000..1fdc0aa14--- /dev/null+++ b/internal/gateway/plugin_fallback_test.go@@ -0,0 +1,93 @@+package gateway++import (+ "io"+ "net/http"+ "strings"+ "sync"+ "testing"++ "github.com/yetone/magpie/internal/provider"+)++// A plugin is told when another candidate follows its try+// (FallbackHeader), so one whose vendor queues the request answers at once+// and the next is asked, instead of the agent waiting in a free model's+// queue for minutes while another provider could answer (axuhere on X:+// "模型请求正在排队 · 预计等待超过 10 分钟"). The last candidate isn't told,+// and waits as the vendor's own client does; the header never reaches the+// vendor.+func TestPluginToldAnotherFollows(t *testing.T) {+ var mu sync.Mutex+ type seen struct{ path, fallback string }+ var got []seen+ var leaked []string+ pid := besideFake(t, "fakeco", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ io.Copy(io.Discard, r.Body)+ mu.Lock()+ got = append(got, seen{r.URL.Path, r.Header.Get("X-Saw-Fallback")})+ if v := r.Header.Values(provider.FallbackHeader); len(v) > 0 {+ leaked = append(leaked, v...)+ }+ mu.Unlock()+ if r.Header.Get("X-Saw-Fallback") == "1" {+ // as Qoder's plugin answers its queue when told another follows+ w.Header().Set("Content-Type", "application/json")+ w.Header().Set("Retry-After", "30")+ w.WriteHeader(http.StatusServiceUnavailable)+ io.WriteString(w, `{"error":{"message":"queued the request (position 12, about 10 minutes)"}}`)+ return+ }+ w.Header().Set("Content-Type", "text/event-stream")+ if r.URL.Path == "/v1/messages" {+ for _, e := range []string{+ `{"type":"message_start","message":{"id":"m","type":"message","role":"assistant","model":"fake-claude","content":[],"usage":{"input_tokens":1,"output_tokens":0}}}`,+ `{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,+ `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}`,+ `{"type":"content_block_stop","index":0}`,+ `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`,+ `{"type":"message_stop"}`,+ } {+ io.WriteString(w, "data: "+e+"\n\n")+ }+ return+ }+ io.WriteString(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{"role":"assistant","content":"hi"},"finish_reason":null}]}`+"\n\n")+ io.WriteString(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n")+ }))+ if err := provider.SaveGroup(provider.Group{Name: "Queue", Members: []string{pid + "/fake-1", pid + "/fake-claude"}, Routing: provider.Ordered}); err != nil {+ t.Fatal(err)+ }+ take := func() []seen {+ mu.Lock()+ defer mu.Unlock()+ s := got+ got = nil+ return s+ }++ // a group: its first member is told another follows, gives way, and+ // the last answers untold; the trace says why the first didn't+ rt := postProto(t, New(), "/v1/chat/completions", `{"model":"group/queue","messages":[{"role":"user","content":"hi"}]}`)+ sent := take()+ if len(sent) != 2 || sent[0] != (seen{"/v1/chat/completions", "1"}) || sent[1] != (seen{"/v1/messages", ""}) {+ t.Fatalf("the vendor saw %+v; want fake-1 told another follows, then fake-claude untold", sent)+ }+ if len(rt.Tries) < 2 || rt.Tries[0].Status != http.StatusServiceUnavailable || rt.Tries[len(rt.Tries)-1].Status != http.StatusOK {+ t.Fatalf("tries %+v", rt.Tries)+ }+ if !strings.Contains(rt.Tries[0].Error, "queued the request (position 12") {+ t.Fatalf("the first try says %q, not why it gave way", rt.Tries[0].Error)+ }++ // a model of its own, one account: nobody follows, nothing is said+ postProto(t, New(), "/v1/chat/completions", `{"model":"`+pid+`/fake-1","messages":[{"role":"user","content":"hi"}]}`)+ if sent := take(); len(sent) != 1 || sent[0].fallback != "" {+ t.Fatalf("a lone model's plugin was told %+v", sent)+ }+ mu.Lock()+ defer mu.Unlock()+ if len(leaked) > 0 {+ t.Fatalf("the vendor got %s: %q", provider.FallbackHeader, leaked)+ }+}