Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
affinity: a Claude Code subagent's answer no longer moves its lead off its account's cache
yetone3b717d5e0d62
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex b88f1456c..c72f5ad0f 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -37,7 +37,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md).| Limits | Each key or account (a candidate's `who()`) has at most `MaxConcurrency` requests out at once (its own `AccountConcurrency` over it); one more waits in its lane's queue, bounded by `QueueLimit` and `QueueWait` and turned away with a 429 past either (`lanes.take`). `MaxRPM` (coeo91 on Discord: OpenRouter's free models take 20 a minute) bounds how many requests it sends the vendor in any rolling 60 seconds (`rpms`), counting each for a second more (`rpmSlack`), since the vendor counts a request when it arrives and the first on a new connection arrives later by its dial: one more waits for room in the minute, in the order they came, after it has its slot and right before it is sent. A wait that would be longer than 2 minutes (or the provider's `QueueWait`, when shorter: `rpmWait`) is turned away at once with a 429 whose `Retry-After` is when the minute has room; nothing rests for it. An agent gone while it waits gives its place back. Every request that reaches the vendor counts: each try of the candidate loop (a retry, the next key, a fallback) waits in `serve`, and the requests a try makes on the way and the gateway's own asks (count_tokens, System One's decisions, embeddings, drawing, Kimi's search) are counted by `rpmTransport` on `s.client` (`metered`, `paidFor`). count_tokens never waits: a candidate with no room is skipped, and the local estimate answers. A full lane or a minute with no room gives way to a ready key or account of the provider or the group (`laneMate`, `ready`); a fallback is never asked for want of either. A plugin's account sends through its own transport, so only its tries are counted, not a plugin's own extra requests. Set in the provider editor (Concurrency, Requests per minute, Queue size, Queue wait) or with `magpie provider account-concurrency`, `queue` and `rpm`; a subscription's are kept with its picks, and every account of it keeps them, those on beside the first as well (`withPicks`, called by `All` and `AlsoOn`; #1899: a second WorkBuddy AI account had none, and queued 62s with the wait set to 1s). | [`concurrency.go`](../../internal/gateway/concurrency.go), [`rpm.go`](../../internal/gateway/rpm.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) || Sink | With `Sink` on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart, or until its rest is lifted by hand (Try now, `Unrest`/`UnrestAll` call `unsink`), which puts it back in its place (`TestTryNowPutsASunkAccountBack`). A group in a group sinks by its own Sink, within its own order (`sinkOwn`, #2255), and the group asked for then sinks the whole by its own; `TestNestedGroupSinksItsOwnOrder`. | [`sink.go`](../../internal/gateway/sink.go) || Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. Volcengine Ark (`isArk`: an `ark.*.volces.com` base, the preset's plans or one added by hand) is asked at `/images/generations` only, as its doc (https://www.volcengine.com/docs/82379/1541523) takes it (`drawArk`): `watermark: false`, since it marks every image otherwise; reference images as JSON `image` (a URL or data URL, an array for several), never a multipart edit; no `n`, so one request per image (`eachDrawing`); no ratio as `size`, so a ratio its doc lists is sent as that ratio's 2K size and any other is a 400 that says to put it in the prompt; no mask, no quality (JL on Discord, `TestArkDrawsWithoutWatermarkOncePerImage`). A routing group named for a drawing or a video (`drawingGroup`: `group/<id>`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). Pause rules and a gateway key's group hold apply as for a chat. A failed drawing rests no member and no key. An account out of quota for the image model (`failure` reads `failQuota`) rests that model on it alone (`restDrawer`, keyed by `restID`), until the reset its refusal names (`resetsAt`: Antigravity's "Your quota will reset after 3h19m30s.") or `quotaRest`, so the next drawing asks the accounts that still have it first (`restLast`), and the account's text models stay in. Antigravity also tells a model's quota used up as a 200 whose stream is the error; `drawCodeAssist` gives such an error the status its words stand for (`saidStatus`: quota or rate 429, credit 402, else 502), as the images API's 200 with no image does, so a spent account hands the drawing to the next one as its 429 does (01huadalang on Discord: a 502 ended the drawing on the spent account; `TestAntigravityDrawingOutOfQuotaInsideTheReplyGoesOn`, `TestAntigravityDrawingQuotaRestsTheImageModel`). `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. An account's own list of models (#474) never bars a ChatGPT account's GPT Image, a Grok subscription's Grok Imagine or a WorkBuddy plan's image models (`listsCantName`): the list is picked from the editor's chat models, which they are never among, so a list kept for some chat models had every drawing refused as "set not to be served by any account" (heyiwei5 on X). A key's list, picked from models that include its image ones, still bars them. `TestCodexDrawsPastAccountModelLists`. A drawing is given Settings → Images → Image generation timeout (`imageTimeout`, 1 to 60 minutes, 5 when unset; neighbads on X: a slow image endpoint needed more) as its context's deadline (`drawTimeout`, `drawWithin`), and so is downloading an image answered as a link (`imageLongest`, never under `ImageLongest`). A drawing's request goes through a transport with no `ResponseHeaderTimeout` (`drawsApart`), since an images API sends its headers only once it has drawn, and every other request keeps `upstreamHeaderWait` (10 minutes). A video's submit, status and download calls keep 5 minutes each (`videoTimeout`). The `magpie mcp image` process, which may not read these settings (WSL), waits on a call up to `callLongest` (two hours and a minute), so it never cuts one the gateway still waits on. `TestLongImageTimeoutLetsASlowVendorFinish`, `TestImageTimeoutSettingReachesTheVendor`, `TestOnlyDrawingsWaitPastTheHeaderWait`. | [`draw.go`](../../internal/gateway/draw.go), [`draw_volcengine.go`](../../internal/gateway/draw_volcengine.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.go) |-| Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. | [`affinity.go`](../../internal/gateway/affinity.go) |+| Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. A conversation is kept by its id (`conversationID`), and a Claude Code subagent's apart from its lead's by `x-claude-code-agent-id` (`stickKey`): Claude Code sends the session's id with its subagents' requests too, and a subagent's answer took the lead's stick over, so the lead's next turn was judged by the subagent's cache and moved to another account, where its whole conversation was written again (slkassinthehood on X, `TestClaudeConversationKeepsItsAccountsCache`). | [`affinity.go`](../../internal/gateway/affinity.go) || One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A provider of the user's set not to check its certificate (`InsecureTLS`, #2383) has it skipped for its own base URLs' hosts alone, through `p.Via` ([Providers and accounts](providers-accounts.md)). Every request to one vendor's host shares one HTTP/2 connection (`upstreamTransport`); one with no frame for 20s is pinged, and dropped when no answer comes within 10s (`netproxy.HTTP2Health`, on `http.DefaultTransport` too), so a connection gone silent without closing (a proxy's way out died, a NAT forgot the flow) fails the requests on it, which move on as a 502 does, and the next request dials a new one. A live vendor answers a ping whatever its streams are doing, so a long wait for a first byte is not cut by it (#2843: a group's requests hung with no first byte until a restart; `TestGroupMovesOnFromSilentHTTP2Connection`). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. An account that only streams (`Account.Stream`: a plugin's, and most subscriptions magpie signs in to) has a request that asked for one body translated, which magpie always asks streamed, except a plugin's on Responses (`gathers`): that is relayed all the same, asked with `stream:true`, and the client given the `response` of the stream's `response.completed` (or `response.incomplete`) as one JSON body (`gathered` in [`gathered.go`](../../internal/gateway/gathered.go); its `output` filled from the stream's `response.output_item.done` items, or else its text, when that event's is empty). So the tools the vendor runs itself, and its response's `tools` and usage details, reach the client (plugins#112: a translation dropped Grok's `x_search`, and Grok answered without searching; `TestGrokPluginNonStreamKeepsHostedTools`). A stream that fails or ends before that event is a 502 (`TestGrokPluginNonStreamEndedShort`), never an empty 200. A Messages request is still translated, its stream having no event that holds the whole reply, and so is a subscription magpie signs in to itself (the ChatGPT backend's, Qoder's): its own code fits its requests. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`; a provider that searches for some of its models only, Command Code's Provider API, lists them in `searchModels` by API, and none count under its `x-cmd-zdr` header, #1590), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`) is remembered in `unfit` until magpie restarts. A Chat API that refuses function tools with reasoning, with no other API to take them to, is asked once more with `reasoning_effort` `none` (#176), unless `none` is known refused (`turnedAway`); `none` refused naming the levels, the tools refusal is the answer, not a retry at the lowest level (#2670). When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. | [`gateway.go`](../../internal/gateway/gateway.go) || Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. `Route.Folder` is the folder the agent says it works in (`workDir`), its last two levels only (`shortFolder`, e.g. `workspace/magpie`), never the full path; a request that says none (a title, a topic check) takes its session's as said last (`trace.sessionFolder`), one without a session id has none (#1068). It is kept in the routing history on disk for as long as the route is (`history.go`: 30 days, 200 MB). The GUI shows it in By session's headings, a request row's tooltip, the stage's agent working in more than one folder, and the tray panel's agent tooltip. | [`trace.go`](../../internal/gateway/trace.go) || Prompt | What each request's prompt held, part by part: the agent's system prompt, tool definitions (an MCP server's tools as one item), instruction files and skills, files its tools read, their other output, and the conversation. `inspectPrompt` reads it from the body as the agent sent it, before translation; `calibrated` scales the estimate to the prompt the vendor counted and sets the window of the model that answered. The route keeps names and sizes only, never the text, so the routing history on disk holds none. For the card's text (masaka on Discord), the trace keeps the last `promptBodies` (10) request bodies in memory only (at most 32 MiB each, 64 MiB together), masked as the vendor got them; for a model let have it unmasked, the masked copy is kept all the same. `PromptText` reads a part's items and their text from that body again (`prompt_text.go`), served to the GUI as `/api/context/text`; once a body is dropped, or magpie quits, its text is gone. It goes on the trace as `Route.Prompt`, with `Route.Conv` naming a conversation that has no session id. The GUI's `/api/context` scores each agent from it (`internal/gui/context.go`). A session's line and its compactions are its own turns': a call with a `Kind`, a Claude Code subagent's (`Route.Sub`, from `x-claude-code-agent-id`), and, in a session whose turns carry tool definitions, a request without any (auto mode's classifier, the title, the quota check) are left out, so a classifier's 40K after a 100K turn is no compaction (`toolSessions`, `TestContextSideCallsAreNoCompaction`). | [`prompt.go`](../../internal/gateway/prompt.go) |diff --git a/internal/gateway/affinity.go b/internal/gateway/affinity.goindex cec23797f..73d09681f 100644--- a/internal/gateway/affinity.go+++ b/internal/gateway/affinity.go@@ -378,7 +378,7 @@ func strictKeep(scope, mode string, in http.Header, body []byte, cs []candidate,return cs, pl, nil}sticks.Lock()- st, had := stickOf(scope + "|" + conversationID(in, body))+ st, had := stickOf(stickKey(scope, in, body))sticks.Unlock()if !had || time.Since(st.at) > stickKeep || slices.ContainsFunc(cs, func(c candidate) bool { return c.who() == st.who }) {return cs, pl, nil@@ -452,6 +452,26 @@ func strictOnly(cs []candidate, pl planned, at int) ([]candidate, planned) {return out, pl}+// stickKey is the conversation a stick is kept for: scope's, by the+// conversation's id, and a Claude Code subagent's apart from its lead's.+// Claude Code sends its session's id with every request of the session,+// its subagents' too, which say only by x-claude-code-agent-id that they+// are one (subagentOf). Under the session's key, a subagent's answer took+// the lead's stick over: the lead's next turn was judged by the cache of+// the subagent's conversation, moved to another account as "no-cache" or+// "cold" or to wherever the subagent had gone, and the lead's whole+// conversation written to that account's cache again (slkassinthehood on+// X: two Pro accounts' 5 hours spent in ten minutes). The lead's key is+// the session's as before, so what is kept of it, and Codex's leadFirst,+// which reads a lead's stick by its thread id, are as they were.+func stickKey(scope string, in http.Header, body []byte) string {+ key := scope + "|" + conversationID(in, body)+ if sub := subOf(in); sub != "" {+ key += "|agent:" + sub+ }+ return key+}+// affine puts first whoever answered the conversation last, while its// affinity says to keep it there. Its turn is counted in written, the body// as the agent wrote it, which the turn's folder is read from too@@ -459,7 +479,7 @@ func strictOnly(cs []candidate, pl planned, at int) ([]candidate, planned) {// it in the masked body parsed the conversation a second time, ~27 MB// more for each 4 MB Codex request in flight.func affine(scope, mode string, rotate bool, in http.Header, from provider.Protocol, body, written []byte, cs []candidate, pl planned) ([]candidate, planned, *Affinity, string) {- key := scope + "|" + conversationID(in, body)+ key := stickKey(scope, in, body)a := &Affinity{Mode: mode}a.Turn, a.Within = turnOf(from, written)sticks.Lock()diff --git a/internal/gateway/claude_cache_account_test.go b/internal/gateway/claude_cache_account_test.gonew file mode 100644index 000000000..4db2ee94a--- /dev/null+++ b/internal/gateway/claude_cache_account_test.go@@ -0,0 +1,147 @@+package gateway++import (+ "encoding/json"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strconv"+ "strings"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/provider"+ "github.com/yetone/magpie/internal/testenv"+)++// claudeCaching has the fake Claude Code of claudeMadeFirst answer on both+// accounts, each healthy, and report its prompt cache as Claude Code's+// stream does for a subscription: the conversation written for an hour.+// A turn whose text holds SMALL reports a small, 5-minute write only.+func claudeCaching(t *testing.T) {+ t.Helper()+ claudeMadeFirst(t, false)+ reset := strconv.FormatInt(time.Now().Add(3*time.Hour).Unix(), 10)+ script := `#!/bin/sh+case "$1" in auth) exit 1;; esac+creds="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/.credentials.json"+if [ "$2" = "/usage" ]; then+ echo '{"type":"result","is_error":false,"result":"Current session: 10% used"}'+ exit 0+fi+n=0+while read -r line; do+ case $line in *'"type":"control_request"'*)+ id=$(printf '%s' "$line" | sed 's/.*"request_id":"\([^"]*\)".*/\1/')+ echo '{"type":"control_response","response":{"subtype":"success","request_id":"'$id'"}}'+ continue ;;+ esac+ n=$((n+1))+ tok=$(grep -o 'tok-[a-z]*' "$creds" | head -1)+ usage='"input_tokens":5,"cache_read_input_tokens":20000,"cache_creation_input_tokens":300000,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":300000}'+ case $line in *SMALL*) usage='"input_tokens":5,"cache_read_input_tokens":0,"cache_creation_input_tokens":300' ;; esac+ echo '{"type":"rate_limit_event","rate_limit_info":{"status":"allowed","rateLimitType":"five_hour","utilization":0.1,"resetsAt":` + reset + `}}'+ echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m","model":"claude-opus-5-5","usage":{'"$usage"'}}}}'+ echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"'$tok' pid '$$' turn '$n'"}}}'+ echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":3}}}'+ echo '{"type":"stream_event","event":{"type":"message_stop"}}'+ echo '{"type":"result","subtype":"success","is_error":false,"result":""}'+done+`+ bin := strings.Split(os.Getenv("PATH"), string(os.PathListSeparator))[0]+ testenv.Program(t, filepath.Join(bin, "claude"), script)+}++// A conversation on one of two Claude accounts goes on on that account, in+// the Claude Code that had its last turn, so Anthropic's cache of it — the+// account's own — is read again rather than the whole conversation written+// on the other account (slkassinthehood on X: two Pro accounts' 5 hours+// spent in ten minutes).+func TestClaudeConversationKeepsItsAccountsCache(t *testing.T) {+ claudeCaching(t)+ restingUntil.Lock()+ restingUntil.m = map[string]time.Time{}+ restingUntil.Unlock()+ p, err := provider.Find("claude")+ if err != nil {+ t.Fatal(err)+ }+ p.Routing = provider.LeastUsed+ if err := provider.Save(*p); err != nil {+ t.Fatal(err)+ }+ s := New()+ t.Cleanup(s.subscription.abortAll)+ h := s.Handler()+ sendAs := func(session, agent, msgs string) string {+ t.Helper()+ body := `{"model":"claude/claude-opus-5-5","max_tokens":100,"tools":[{"name":"read","input_schema":{"type":"object"}}],"messages":` + msgs + `}`+ r := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body))+ r.Header.Set("x-claude-code-session-id", session)+ if agent != "" {+ // as Claude Code marks a subagent's requests; its lead's carry none+ r.Header.Set("x-claude-code-agent-id", agent)+ }+ rec := httptest.NewRecorder()+ h.ServeHTTP(rec, r)+ var res struct {+ Content []struct{ Text string } `json:"content"`+ }+ json.Unmarshal(rec.Body.Bytes(), &res)+ if rec.Code != 200 || len(res.Content) == 0 {+ t.Fatalf("%d %s", rec.Code, rec.Body)+ }+ a := s.trace.routes[len(s.trace.routes)-1].Affinity+ t.Logf("%q affinity %+v", res.Content[0].Text, a)+ return res.Content[0].Text+ }+ send := func(msgs string) string { t.Helper(); return sendAs("s-1", "", msgs) }+ msg := func(role, text string) string { return `{"role":"` + role + `","content":` + strconv.Quote(text) + `}` }+ age := func(d time.Duration) {+ sticks.Lock()+ for k, st := range sticks.m {+ st.at = st.at.Add(-d)+ if !st.hour.at.IsZero() {+ st.hour.at = st.hour.at.Add(-d)+ }+ sticks.m[k] = st+ }+ sticks.Unlock()+ }+ who := func(reply string) string { tok, _, _ := strings.Cut(reply, " pid"); return tok }+ run := func(reply string) string {+ _, rest, _ := strings.Cut(reply, " pid ")+ p, _, _ := strings.Cut(rest, " ")+ return p+ }++ conv := msg("user", "lead: fix the bug")+ first := send(`[` + conv + `]`)+ conv += `,` + msg("assistant", first)+ // a new conversation goes to the account that has served less+ if got := sendAs("s-2", "", `[`+msg("user", "SMALL another session")+`]`); who(got) == who(first) {+ t.Fatalf("a new conversation went to %q, not the less used account", got)+ }+ for i, step := range []struct {+ name string+ do func()+ }{+ {"next turn", func() {}},+ {"after 20 minutes", func() { age(20 * time.Minute) }},+ {"after a sub-agent on the same model and session", func() {+ sendAs("s-1", "agent-1", `[`+msg("user", "SMALL subagent: look around")+`]`)+ }},+ {"after a sub-agent, 20 minutes on", func() {+ sendAs("s-1", "agent-2", `[`+msg("user", "SMALL subagent: look again")+`]`)+ age(20 * time.Minute)+ }},+ } {+ step.do()+ conv += `,` + msg("user", "and "+strconv.Itoa(i))+ got := send(`[` + conv + `]`)+ if who(got) != who(first) || run(got) != run(first) {+ t.Errorf("%s: answered %q, the conversation began as %q: moved off its cache", step.name, got, first)+ }+ conv += `,` + msg("assistant", got)+ }+}