Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
gateway: a model an account refuses goes on to the accounts not listing it yet
yetone7765f27fccb5
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex e4590cc4b..7a49a128e 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -125,6 +125,7 @@ recorded as a prediction failure (`noPrediction`).- The order of the steps a request's accounts go through, how much the accounts' own order (*Make first*) counts under each routing, and how often an allowance is read are described for users in [How magpie picks an account](../reference.md#how-magpie-picks-an-account). Smart compares renewals window by window, biggest first, each truncated to the hour (`weighRouted`), so the order decides only when every window falls in the same hour. A window's renewal is its reset, or, when what it has left runs out sooner or it has no reset, that moment (`Limit.RunsOut`, from `QuotaWindow.RunsOutAt`; `Allowance.Renewal`): the WorkBuddy plugin (0.1.14) sends it on its Credits window as the soonest end of a package with credits left (cdredfox on X). Only Smart reads it; Weekly pace, the 90%/98% tiers and rests go by the window's share and reset as before. A row on the Routing page says the share used (the fullest window's, `Allowance.For`) with when that same window renews (`Allowance.Fullest`, the trace's `usedRenews`), not the biggest window's: a Factory account 32% into its week and 16% into its month reads "32% used · renews in 3 days" while Smart still ranks it by its month (#1778). A route from before `usedRenews` says when only for an account of one window. Affinity keeps a conversation on an account at 90–97%: only `SpentShareOf` (98%, 100% In order) stops it (`affine`), while the 90% tier (`lowShare`) orders only conversations nobody has answered.- A turn's end is told to the app for the "Task done alert" notification (itieniu on X, `turndone.go`). The trace follows each agent session's turn (`turns`, keyed by agent and session): a request is of the turn unless it has a `Kind` or is a Claude Code subagent's (`agentTurnOf`), and its reply is scanned on the way to the agent for a tool call in any wire format (`toolScan`, a JSON value such as `"type":"tool_use"` or `"finish_reason":"tool_calls"`, never a key or text). The turn is done when no request of it is going, the last reply was whole, under 400 and called no tool, and nothing more came for `turnQuiet` (4s); a session idle past `turnStale` (30m) starts over. Only a turn that ran at least `settings.TurnDoneAlert` seconds is told (`TurnDone`, set by the GUI; nil under `magpie serve`, so nothing is followed). The ChatGPT backend path (`codexBackend`) is followed the same way. `TestTurnDoneSaidAtTheTurnsEnd`, `TestTurnDoneCodexBackend`, `TestToolScan`, `turn-done.test.cjs`.- A resting candidate is tried last (`restLast`). Of the resting candidates, a request asks only the one whose rest ends soonest, the first in order on a tie (`probeOne`, #1799). The others aren't asked by that request, so a member that is down isn't asked by every request its rest was meant to spare it from, and a group that is down whole takes one upstream request per request, not one per member. Every ready candidate is still asked in its order. A lone candidate is tried even while it rests, because there is no other. The trace still lists every member, the resting ones with their rest. Only rests are read, and a failure about the request's content or its model rests no member (a model refusal rests only `restID`), so neither leaves a member out. The same applies in `count_tokens`, embeddings and rerank, image accounts and a group's System One decision models. A Codex reset (`autoReset`) still looks over every candidate. This is like AxonHub's error-aware load balancing: the rest and its backoff are the penalty that decays, and the member back soonest is the one asked to show it is back. Keys out of their allowance aren't asked even so, not even the one back soonest or a lone one (#1772: four Ollama Cloud keys out for the week, each asked again and refused on every request). The refusal given again says when they are asked again on this magpie's clock with its offset (`heldClock`: "20:12 UTC+8", "Oct 16 09:00 UTC+8"), as do the gateway's other held errors (a capped window, a spent searcher or describer): its reader may be a Remote magpie's user on another clock. When every candidate left is a key (not a subscription account, whose resets `autoReset` may spend) resting out of quota or credit after a 429 or 402, none is asked. The first one's refusal is given again (`quotaHeld`, its words kept in the rest's `said`), saying when it is asked again. The last key left rests too when it is refused so, as the keys before it do. Any 429 that reaches the agent without a vendor `Retry-After`, while every candidate tried is resting, carries one: the seconds until the first of them is back (`soonestBack`). A quota refusal with no word of when it is back rests `quotaRest` (15 minutes), or the provider's own `quotaRest` in minutes (`Provider.QuotaRestFor`, at most `MaxQuotaRest`, 8 days; `magpie provider quota-rest <id> 7d`), or until the time of day the user said its allowance comes back (`QuotaResetAt`, `Provider.OwnQuotaRest`; `magpie provider quota-rest <id> until 08:00`, or `until 00:00+08:00` on the vendor's clock; #2008, a free tier's "today's free-model token quota"). Whichever of the two was set last counts. A time the vendor names stands over it, and so does its `Retry-After`, unless that was more than `longestWait` (an hour) and so cut to it while the user's own rest is longer: then the user's stands (`TestQuotaRestsUntilTheTimeOfDaySet`). A key listed in `keys` as well as in `key` is one candidate (`KeysOn`), not asked twice. `TestAllRestingAnswersFromRest`, `TestOwnQuotaRest`, `TestQuotaHeldOnlyForKeysOutOfAllowance`, `TestFirstKeyListedTwiceAskedOnce`.+- A subscription's account whose own model list lacks the model (`Account.Lists`: an Antigravity account's `fetchAvailableModels`, a plugin account's `models`) isn't planned while another of its accounts lists it (`perKeyBarred`'s `left`, `planned.unlisted`, the Routing page's "unlisted, skipped"). It is the next asked when every account of the subscription that lists the model has been asked and one refused it as a model it doesn't serve (`unservedTry`: `modelRefused`, or Code Assist's 404 NOT_FOUND, `codeAssistModelMissing`), before any later member or fallback (`unlistedNext`, `askUnlisted` moves its row from the route's left to its order after the one that refused). A list is fetched once and can be stale: 01huadalang's Gemini 4 was served by one Antigravity account of several, and the one whose list named it refused it with a 404 the agent got while the other could answer. The one that refused rests for that model alone. Not for another refusal (a 403, a quota), a request pinned to an account, a native compaction sealed to one, or a conversation kept strictly on one; a gateway key held to some accounts narrows the unlisted ones too (`allowedCandidates`). `TestUnlistedAccountAskedAfterModelRefused`, `TestUnlistedAccountNotAskedForOtherRefusals`.- A member whose model is known to take less than the request isn't asked it (`roomy` in [`fallback.go`](../../internal/gateway/fallback.go), in `serve` after the rules, affinity, the image filter and `pinTo`, before `probeOne`; dgqyushen on Discord: OpenCode Zen's free DeepSeek V4.1 Flash, 200K, first in a group and a 1M subscription of it second). It is a check before sending, not a retry: the request's tokens are estimated as the overflow fall-over does (`estimate`, bytes/4 over text, tool arguments and schemas), and a candidate whose window (`windowOf`: the provider's `Contexts`, the catalog, `ContextOf`) is known and no larger is left out of the candidates and of the trace's order. Asked, such a member only refuses, and a refusal that doesn't say why, for a request short of `tooLongUnsaid`'s 1.2 margin, reached the agent as the vendor's error while the next member had room; it also spent a request against the member's limits. A conversation kept on a member by affinity moves once it outgrows it. Nothing is left out when its window isn't known, when the body doesn't parse, when only one model is among the candidates, or when no candidate holds the request: then the first is asked, and its overflow reaches the agent as one, to compact (`withRoom`, `failOverflow` and `tooLongUnsaid` stay for the window the estimate misses, which counts low on code and high on CJK text). A body shorter than four bytes per token of the least window isn't parsed. `count_tokens` (a count on the group's first member, not a send) and System One's decision models (short decision text) don't go through it. Those left out are the last resort: when the last candidate with room fails out of its allowance or credit (`failQuota`/`failCredit`), nothing before it having failed otherwise (`other`), and no account is pinned, the ones left out that aren't resting are asked after all, their rows added to the trace's order, and the one that failed rests as one before the last does. Its overflow tells the agent to compact, where the 429 only told it to wait for an allowance hours away (Kai on Discord: both Claude accounts spent until the next day, the Claude provider's Fallback a Codex model of 272K under a longer conversation, never asked). Another failure (a busy vendor, a bad key) still reaches the agent as it was, the small one not asked. The Routing page shows a member left out and not asked only by its absence from the route's order. `TestMemberTooSmallIsNotAsked`, `TestMemberTooSmallIsTheLastResort`, `TestClaudeAccountsSpentFallBackToCodex`, `TestConversationOutgrowingItsMemberMoves`, `TestRoomyLeavesWhatItCantJudge`.- Routing decides who goes first only when nobody has answered the conversation yet. Affinity keeps the answerer while its cache is worth it. Auto mode keeps it across turns while the last reply read from the cache and wrote to it at least `cacheWorth` (1024) tokens between them (the usage's `CacheRead` plus `CacheWrite`, passed to `answered`) and the cache isn't cold (`cacheCold`, 5 minutes). Past 5 minutes it stays while the vendor said it keeps at least `cacheWorth` tokens of the conversation for an hour (`hourCache`, #2302): a reply with Anthropic's 1-hour writes (`cache_creation.ephemeral_1h_input_tokens`, the usage's `CacheWrite1h`, as Claude Code asks of a subscription) keeps what it read plus those for `cacheHour`, a later reply on the same account and model that reads all of it starts the hour again, and one that reads less (moved, compacted) drops it. The stick keeps it on disk too (`cacheHour`, `cacheHourAt`), and a group's rules keep the turn's effort the same hour (`keepsEffort`). Vendors that report no 1-hour write are unchanged. `TestAffinityKeepsAnHourCachePastFiveMinutes`, `TestHourCacheAfter`. What was written counts: a first turn reads nothing and writes the whole prompt (Anthropic's `cache_creation_input_tokens`), and the second turn stays to read it rather than moving as `no-cache` and building it again elsewhere (vilicvane on Discord). The stick keeps both, on disk too (`affinity.json`'s `cacheWrite`, absent in a file from before and read as 0, so such a stick is judged by its read alone), and the trace's `Affinity.CacheWrite` lets the Routing page say what was read and what was written. A vendor that keeps a prompt cached without reporting it (OpenAI's automatic prefix cache, Gemini) says neither of a turn that read none, so the prompt that turn was sent (the usage's `Input`) stands for the write and its second turn stays too; a reply that reports no usage at all counts as no cache, as before. `TestAffinityKeepsACacheJustWritten`, `TestAffinityKeepsACacheTheVendorKeptSilently`, `routing-affinity-cache-write.test.cjs`.- Strict (`strict`, #1797, miniers) never moves a conversation to another key or account (`who`). Its stick is kept as session's is, and while it is fresh `affine` keeps only the candidates of that `who` (`strictOnly`): its other models stay, so a group's rules still pick among them, but no other account, key or provider is asked, and a resting or spent one is asked anyway. A failure there reaches the agent and rests the account as a non-lone candidate's would (`strictAlone`), so new conversations go elsewhere. Before planning, `strictKeep` takes the stuck account back from what holds new conversations off it: a usage cap (`pl.capped`, `capHeldOnly`), so the conversation goes on past it. An account held for credits it may not spend is answered 429 naming the account and Strict, and nothing reaches the vendor, rather than moved. An account removed, switched off, barred, or not allowed for the calling key is gone, and the conversation moves as under session. The trace says `strict` even with one candidate. `strict_affinity_test.go`, `stays-strict.test.cjs`.diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.mdindex 04909f109..6d7bfc6ed 100644--- a/docs/subsystems/providers-accounts.md+++ b/docs/subsystems/providers-accounts.md@@ -223,6 +223,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.- The account Codex or Claude Code is signed in to can be paused (`SetLoginOn` off, #263) only while another of its accounts is on. The gateway then sends it nothing: Codex's own-model turns go through routing, which passes over it (`OwnPaused`), and a native compaction (`/responses/compact`) goes to the first account on that isn't resting, signed as that account (`compactOn` in [codex_backend.go](../../internal/gateway/codex_backend.go)). The last other account off, the paused one is used again. A switched-off Codex provider is not a pause: Codex's own-model requests still relay on its sign-in as they came.- A switched-off provider (`Off`, #163) stays saved. The gateway says it is off instead of saying the model is unknown.- A subscription switched off (`Off`) or whose account was removed from magpie (`Hidden`) is left alone in the background (`leftAlone` in [`left_alone.go`](../../internal/provider/left_alone.go); Riko on Discord, whose Claude switched off still ran `claude auth status --json` every minute). No CLI is asked who is signed in (`claudeIdentity`, `cliIdentity.get` for Cursor and Devin): what it said last, in memory or `cli-identity.json`, is served, so the account stays listed to switch on again. Nor is its allowance read (`fetchSubscriptionUsage`, `loginUsageAt`), a saved ChatGPT sign-in renewed (`RenewLogins`), the agent's account switched (`NextLogin`), a window warmed (`keepWarm`), its model list fetched (`newDue`), a daily check-in made by the loop (`checkinNow` with `soon` false; a press still checks in), or a Codex reset about to run out read and spent (`SpendExpiringCodexResets`, #2226; `TestExpiringResetLeftAlone`). A Cursor switched off that was never asked who is signed in isn't listed until it is switched on. `TestLeftAloneRunsNoCLI` runs those paths with fake `claude`, `cursor-agent` and `devin` CLIs on PATH and checks none ran. Plugins' model lists (`KeepPluginsListed`) are asked of the plugin host all at once and aren't held back per provider.+- An Antigravity subscription offers the union of its On accounts' models (`antigravityPoolModels` in [`antigravity_pool.go`](../../internal/provider/antigravity_pool.go)), each account's own list kept beside it (`accountModels`, read by `Account.Lists` for routing). The lists are fetched at the first listing, a probe, a sync or a Refetch, and also at each account's quota reading, which asks `fetchAvailableModels` anyway: a reading whose models differ from the account's saved list saves it and merges the pooled list again from every On account's own (`noteAntigravityList`), so a model Google gives one account of several later (01huadalang on Discord: Gemini 4) is offered, routed to and given its bar without that account made preferred or probed. A switched-off account's reading changes nothing. `TestAntigravityQuotaReadingListsNewModels`.- A provider removed or switched off takes its models out of the catalog. [Agent wiring](agent-wiring.md)'s `Reseat` moves agents off them.- A preset marked `NoList` uses its preset model list instead of requesting `/models`, and ignores previously fetched lists, including their protocol and key restrictions, unless the user sets `ModelsURL` or chooses a region marked `Lists`. Each region can carry a different list. Volcengine Ark's Coding Plan and Agent Plan use separate preset lists. Both plans include their embedding model separately from agents' chat-model lists; Agent Plan additionally exposes its image- and video-generation models to Settings → Images; Ark itself refuses video generation on Small and Medium Agent Plans, which include it only in the Large and Max tiers. Models magpie does not yet serve (Agent Plan's speech models) are not advertised. Ark's pay-as-you-go region still fetches its own list. Coding's `/api/coding/v3/models` returns a general Ark catalog instead of the plan's model ids, while Agent's `/api/plan/v3/models` returns 404. [`presets.go`](../../internal/provider/presets.go) defines these choices; `List`, `fetch`, `live`, `planModels`, `PlanEmbeddings`, `PlanDrawers` and `PlanVideos` in [`models.go`](../../internal/provider/models.go) apply them when adding, refreshing and reading cached models. `TestVolcengineModelLists` checks that the plans make no list requests, ignore old cached lists and return their own preset models; pay-as-you-go and an explicit list URL still make requests.- A gateway key held to some accounts (#905) is held to those of the providers its list names: a provider it names no account of, the key uses as it always did. The key's menu says so on each account of such a provider ("Used: no … account is picked"), and its badge's tooltip that a key is kept off a provider by its models (#2077: unticking every Codex account left Codex's models served). The list keeps an account by its stable id — `logins.json`'s `id`, set once written and kept through renames; the agents that keep no logins (and plugins) are known by a hash of the account's name, so an account renamed there drops out of a key's list, holding it closer, never wider. Storing an id for every agent is a larger change, not this one's.diff --git a/internal/gateway/antigravity_unlisted_test.go b/internal/gateway/antigravity_unlisted_test.gonew file mode 100644index 000000000..df8602304--- /dev/null+++ b/internal/gateway/antigravity_unlisted_test.go@@ -0,0 +1,204 @@+package gateway++import (+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "slices"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/access"+ "github.com/yetone/magpie/internal/provider"+)++// unlistedArgon signs in two Antigravity accounts, a and b, with the model+// lists given, fetches them, and answers requests: a refuses Gemini 4 as+// refuse says, everyone else answers. It returns the server, the turn and+// who was asked.+func unlistedArgon(t *testing.T, lists map[string]string, refuse func() (int, string)) (*Server, func(secret ...string) (int, string), func() []string) {+ t.Helper()+ fresh(t)+ var logins []map[string]any+ for _, user := range []string{"[email protected]", "[email protected]"} {+ logins = append(logins, map[string]any{+ "agent": "antigravity", "user": user, "on": true,+ "auth": map[string]any{"access_token": user, "refresh_token": "ref-" + user, "project": "p1",+ "expiry_date": time.Now().Add(time.Hour).UnixMilli()},+ })+ }+ dir := filepath.Dir(provider.Path())+ if err := os.MkdirAll(dir, 0o700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(dir, "logins.json"), mustJSON(logins), 0o600); err != nil {+ t.Fatal(err)+ }+ old := http.DefaultClient+ http.DefaultClient = &http.Client{Transport: countTransport(func(r *http.Request) (*http.Response, error) {+ var body string+ switch {+ case strings.HasSuffix(r.URL.Path, "latest-arm64-mac.yml"):+ body = "version: 2.9.1\n"+ case strings.Contains(r.URL.Path, ":loadCodeAssist"):+ body = `{"currentTier":{"id":"standard-tier"},"cloudaicompanionProject":"p1"}`+ case strings.Contains(r.URL.Path, ":fetchAvailableModels"):+ body = lists[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")]+ default:+ return nil, fmt.Errorf("unexpected request to %s", r.URL)+ }+ return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil+ })}+ t.Cleanup(func() { http.DefaultClient = old })+ p, _ := provider.Find("antigravity")+ if _, err := p.Fetch(t.Context()); err != nil {+ t.Fatal(err)+ }+ var mu sync.Mutex+ var asked []string+ s := New()+ s.client = &http.Client{Transport: countTransport(func(r *http.Request) (*http.Response, error) {+ rec := httptest.NewRecorder()+ who := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")+ b, _ := io.ReadAll(r.Body)+ mu.Lock()+ asked = append(asked, who)+ mu.Unlock()+ if who == "[email protected]" && strings.Contains(string(b), "argon") {+ code, body := refuse()+ rec.Header().Set("Content-Type", "application/json")+ rec.WriteHeader(code)+ io.WriteString(rec, body)+ return rec.Result(), nil+ }+ rec.Header().Set("Content-Type", "text/event-stream")+ io.WriteString(rec, sse(`data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"from `+who+`"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":3}}}`))+ return rec.Result(), nil+ })}+ turn := func(secret ...string) (int, string) {+ body := `{"model":"antigravity/gemini-4-argon","stream":false,"messages":[{"role":"user","content":"hi"}]}`+ rec := httptest.NewRecorder()+ r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(body))+ for _, k := range secret {+ r.Header.Set("Authorization", "Bearer "+k)+ }+ s.Handler().ServeHTTP(rec, r)+ return rec.Code, rec.Body.String()+ }+ whoAsked := func() []string {+ mu.Lock()+ defer mu.Unlock()+ out := slices.Clone(asked)+ asked = nil+ return out+ }+ return s, turn, whoAsked+}++// Antigravity's real refusal of a model the account isn't given (#3027):+// a 404 NOT_FOUND from Code Assist.+const codeAssistNotFound = `{"error":{"code":404,"message":"Requested entity was not found.","status":"NOT_FOUND"}}`++// An account whose list names the model refuses it as one it isn't given,+// and the subscription's other account, whose list was fetched before it+// was given the model, serves it: the request goes on to that account,+// not back to the agent with the first one's 404 (01huadalang on Discord:+// Gemini 4 on one Antigravity account of several). The Routing page has+// it asked, not "unlisted, skipped", and the first rests for that model.+func TestUnlistedAccountAskedAfterModelRefused(t *testing.T) {+ s, turn, asked := unlistedArgon(t, map[string]string{+ "[email protected]": `{"models":{"gemini-3.8-flash":{},"gemini-4-argon":{"displayName":"Gemini 4 Argon"}}}`,+ "[email protected]": `{"models":{"gemini-3.8-flash":{}}}`,+ }, func() (int, string) { return 404, codeAssistNotFound })+ code, out := turn()+ if code != 200 || !strings.Contains(out, "from [email protected]") {+ t.Fatalf("got %d %s, want b's answer", code, out)+ }+ if got := asked(); !slices.Equal(got, []string{"[email protected]", "[email protected]"}) {+ t.Errorf("asked %v, want a then b", got)+ }+ rt := lastRoute(s)+ if !slices.ContainsFunc(rt.Order, func(w Weighed) bool { return w.Who == "[email protected]" && !w.Unlisted }) {+ t.Errorf("b is not in the route's order: %+v", rt.Order)+ }+ if slices.ContainsFunc(rt.Left, func(w Weighed) bool { return w.Who == "[email protected]" }) {+ t.Errorf("b is still left out as unlisted: %+v", rt.Left)+ }+ if n := len(rt.Tries); n != 2 || rt.Tries[0].Rest == nil {+ t.Errorf("tries %+v, want a's rested and b's", rt.Tries)+ }+ // a's other models aren't rested by it+ if _, ok := restOf("antigravity@[email protected]"); ok {+ t.Error("a's refusal of Gemini 4 rested the whole account")+ }+}++// A refusal that isn't about the model (Antigravity's own 403 and 429+// bodies) leaves the accounts whose list lacks it alone, as before: they+// would only refuse it too.+func TestUnlistedAccountNotAskedForOtherRefusals(t *testing.T) {+ for _, c := range []struct {+ name, body string+ code int+ }{+ {"denied", `{"error":{"code":403,"message":"The caller does not have permission","status":"PERMISSION_DENIED"}}`, 403},+ {"capacity", `{"error":{"code":429,"message":"You have exhausted your capacity on this model. Your quota will reset after 3h2m1s.","status":"RESOURCE_EXHAUSTED"}}`, 429},+ } {+ t.Run(c.name, func(t *testing.T) {+ _, turn, asked := unlistedArgon(t, map[string]string{+ "[email protected]": `{"models":{"gemini-3.8-flash":{},"gemini-4-argon":{"displayName":"Gemini 4 Argon"}}}`,+ "[email protected]": `{"models":{"gemini-3.8-flash":{}}}`,+ }, func() (int, string) { return c.code, c.body })+ code, out := turn()+ if code < 400 {+ t.Fatalf("got %d %s, want a's refusal", code, out)+ }+ if slices.Contains(asked(), "[email protected]") {+ t.Error("b, whose list lacks the model, was asked over a refusal not about the model")+ }+ })+ }+}++// A gateway key held to some accounts (#905) isn't given an unlisted+// account it may not use: the refusal reaches its agent, as before.+func TestUnlistedAccountHeldFromKey(t *testing.T) {+ _, turn, asked := unlistedArgon(t, map[string]string{+ "[email protected]": `{"models":{"gemini-3.8-flash":{},"gemini-4-argon":{"displayName":"Gemini 4 Argon"}}}`,+ "[email protected]": `{"models":{"gemini-3.8-flash":{}}}`,+ }, func() (int, string) { return 404, codeAssistNotFound })+ keys, secrets := newCaller(t, "Held")+ if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{"antigravity/[email protected]"}}); err != nil {+ t.Fatal(err)+ }+ if code, out := turn(secrets[0]); code != 404 {+ t.Fatalf("got %d %s, want a's 404", code, out)+ }+ if got := asked(); !slices.Equal(got, []string{"[email protected]"}) {+ t.Errorf("asked %v, want a alone", got)+ }+}++// The unlisted account is asked before the provider's Fallback: it is the+// same model on the same subscription, which the fallback is not.+func TestUnlistedAccountBeforeFallback(t *testing.T) {+ _, turn, asked := unlistedArgon(t, map[string]string{+ "[email protected]": `{"models":{"gemini-3.8-flash":{},"gemini-4-argon":{"displayName":"Gemini 4 Argon"}}}`,+ "[email protected]": `{"models":{"gemini-3.8-flash":{}}}`,+ }, func() (int, string) { return 404, codeAssistNotFound })+ if err := provider.Save(provider.Provider{ID: "antigravity", Fallback: []string{"antigravity/gemini-3.8-flash"}}); err != nil {+ t.Fatal(err)+ }+ code, out := turn()+ if code != 200 || !strings.Contains(out, "from [email protected]") || !strings.Contains(out, "gemini-4-argon") {+ t.Fatalf("got %d %s, want b's Gemini 4", code, out)+ }+ if got := asked(); !slices.Equal(got, []string{"[email protected]", "[email protected]"}) {+ t.Errorf("asked %v, want a then b, the fallback not reached", got)+ }+}diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.goindex 43b34db31..b02d35339 100644--- a/internal/gateway/fallback.go+++ b/internal/gateway/fallback.go@@ -3314,3 +3314,51 @@ func pinTo(want string, cands []candidate, pl planned) ([]candidate, planned, in}return nil, pl, http.StatusNotFound, msg}++// unservedTry says c's try failed as the vendor refusing the model as one+// it doesn't serve the account or key (modelRefused, codeAssistModelMissing):+// what restAfterMarked rests for that model alone.+func unservedTry(c candidate, status int, body []byte) bool {+ return failure(status, body) == failOther && (modelRefused(status, body) || codeAssistModelMissing(c.p, status, body))+}++// unlistedNext takes out of a plan's unlisted accounts (planned.unlisted,+// their rows in ws) those of key, "<provider>/<model>", not resting for the+// model: the next ones asked once the accounts whose own list has the model+// refused it as one they don't serve. The rest are returned too, for+// none to be asked twice.+func unlistedNext(cs []candidate, ws []Weighed, key string) (next []candidate, nextW []Weighed, restCs []candidate, restWs []Weighed) {+ for i, c := range cs {+ _, resting := restingOf(c)+ if c.p.ID+"/"+c.model != key || resting {+ restCs = append(restCs, c)+ if i < len(ws) {+ restWs = append(restWs, ws[i])+ }+ continue+ }+ next = append(next, c)+ if i < len(ws) {+ w := ws[i]+ w.Unlisted = false // asked, after those that list the model+ nextW = append(nextW, w)+ }+ }+ return next, nextW, restCs, restWs+}++// askUnlisted moves the rows of the unlisted accounts asked next (ws) from+// a route's left to its order, after the row of c, the one that refused+// the model: the Routing page has them asked, not "unlisted, skipped".+func askUnlisted(order, left []Weighed, c candidate, ws []Weighed) ([]Weighed, []Weighed) {+ asked := make(map[string]bool, len(ws))+ for _, w := range ws {+ asked[w.ID+"/"+w.Model] = true+ }+ left = slices.DeleteFunc(slices.Clone(left), func(w Weighed) bool { return w.Unlisted && asked[w.ID+"/"+w.Model] })+ at := slices.IndexFunc(order, func(w Weighed) bool { return w.ID == c.rest && w.Model == c.model })+ if at < 0 {+ return append(slices.Clip(order), ws...), left+ }+ return slices.Concat(order[:at+1], ws, order[at+1:]), left+}diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.goindex 3e7b8c4ed..1d78a8107 100644--- a/internal/gateway/gateway.go+++ b/internal/gateway/gateway.go@@ -2351,6 +2351,15 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Provar forbade []forbidden // the plain 403s rested so far (forbiddenAlike)autoReset := resetFirst != nil // a Codex or Claude reset looked at, once a requestcreditsAsked := map[string]bool{} // Codex accounts asked again onto their credits, once each (creditsAgain)+ // the subscription/model pairs an account refused as a model it doesn't+ // serve, for the accounts whose own list lacks it to be asked next+ // (unlistedNext); none for a request pinned to an account, a+ // conversation sealed to one or kept strictly on one+ unservedBy := map[string]bool{}+ unlisted, unlistedW := pl.unlisted, pl.unlistedW+ if pin != "" || checkpoint != nil || aff.Why == "strict" {+ unlisted, unlistedW = nil, nil+ }// what the tries' held streams sent the agent ahead of a reply (#751)kept := &keptAlive{proto: from, told: start}if k := handedOnOf(r); k != nil {@@ -3344,6 +3353,42 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Proi--continue}+ if hw.failed() && !hw.passing && len(unlisted) > 0 && unservedTry(c, hw.code(), hw.errBody()) {+ unservedBy[c.p.ID+"/"+c.model] = true+ }+ if key := c.p.ID + "/" + c.model; unservedBy[key] && hw.failed() && !hw.passing && !hw.turnedAway && !hw.refused && !outgrew &&+ !slices.ContainsFunc(cands[i+1:], func(x candidate) bool { return x.p.ID+"/"+x.model == key }) {+ // every account of the subscription that lists the model has+ // been asked, and one refused it as a model it doesn't serve:+ // its accounts whose own list lacks it are asked next, before+ // any other member, as a list fetched before the account was+ // given the model is stale (01huadalang on Discord: Gemini 4+ // on one Antigravity account of several), rather than the+ // agent told the first one's error. The one that refused+ // rests, for that model alone+ var next []candidate+ var nextW []Weighed+ next, nextW, unlisted, unlistedW = unlistedNext(unlisted, unlistedW, key)+ if len(next) > 0 && last {+ if f := failure(hw.code(), hw.errBody()); other == nil && f != failQuota && f != failCredit {+ other = &Try{Status: call.Status, Error: call.Error}+ }+ rest := s.restAfterMarked(c, hw.code(), hw.header, hw.errBody(), hw.sharedPool)+ try.Fail, try.Rest = rest.Why, &rest+ s.trace.update(tr, func(t *Route) {+ t.Tries[len(t.Tries)-1] = try+ t.Order, t.Left = askUnlisted(t.Order, t.Left, c, nextW)+ })+ skipped = append(skipped, c.label()+": "+call.Error)+ cands = append(cands[:len(cands):len(cands)], next...)+ continue+ }+ if len(next) > 0 {+ // the rest of the order after them; this try is rested below+ cands = slices.Concat(cands[:i+1], next, cands[i+1:])+ s.trace.update(tr, func(t *Route) { t.Order, t.Left = askUnlisted(t.Order, t.Left, c, nextW) })+ }+ }if !last && hw.failed() {if f := failure(hw.code(), hw.errBody()); other == nil && f != failQuota && f != failCredit {other = &Try{Status: call.Status, Error: call.Error}diff --git a/internal/gateway/key_models.go b/internal/gateway/key_models.goindex c22509800..a20af83c0 100644--- a/internal/gateway/key_models.go+++ b/internal/gateway/key_models.go@@ -274,6 +274,16 @@ func allowedCandidates(who access.Identity, cs []candidate, pl planned, members}pl.held = slices.DeleteFunc(slices.Clone(pl.held), gone)pl.capped = slices.DeleteFunc(slices.Clone(pl.capped), gone)+ // nor one whose own list lacks the model, asked once those that list+ // it refused the model (unlistedNext)+ var unlisted []candidate+ var unlistedW []Weighed+ for i, c := range pl.unlisted {+ if !gone(c) {+ unlisted, unlistedW = append(unlisted, c), append(unlistedW, pl.unlistedW[i])+ }+ }+ pl.unlisted, pl.unlistedW = unlisted, unlistedWreturn out, pl, held && len(out) == 0}diff --git a/internal/provider/antigravity_pool.go b/internal/provider/antigravity_pool.goindex dcfdeae03..eb93bcd35 100644--- a/internal/provider/antigravity_pool.go+++ b/internal/provider/antigravity_pool.go@@ -5,6 +5,7 @@ import ("fmt""log""slices"+ "strings""sync""time"@@ -97,3 +98,63 @@ func mergeAntigravityModels(out, ms []catalog.Model) []catalog.Model {}return out}++// antigravityNoted serialises noteAntigravityList's read, merge and save of+// the pooled list, for two accounts' readings at once not to save over+// each other's.+var antigravityNoted sync.Mutex++// noteAntigravityList keeps what an On account's quota reading listed as+// its own list, and the pooled list merged again from every On account's+// own, when the account's models changed: the reading runs for every+// account on its own schedule, and a model the account was given since its+// list was fetched (the first listing, a probe, a sync) was otherwise left+// out of the picker, of routing to it and of its bar until one. Only the+// models' ids are compared, as the reading's list is the one models() makes+// of the same reply.+func noteAntigravityList(user, base string, ms []catalog.Model) {+ if len(ms) == 0 {+ return+ }+ on := false+ var accounts []googleLogin+ for _, l := range googleLogins("antigravity") {+ if l.On {+ accounts = append(accounts, l)+ on = on || strings.EqualFold(l.User, user)+ }+ }+ if !on {+ return+ }+ antigravityNoted.Lock()+ defer antigravityNoted.Unlock()+ key := accountModels("antigravity", user)+ if had, _, ok := catalog.Live(key); ok && sameModelIDs(had, ms) {+ return+ }+ if err := catalog.SaveLive(key, base, ms); err != nil {+ log.Printf("antigravity %s: models listed by its reading not kept: %v", user, err)+ return+ }+ pooled, _, listed := catalog.Live("antigravity")+ if !listed {+ return // not listed yet: the first listing pools every account+ }+ var out []catalog.Model+ for _, l := range accounts {+ own, _, _ := catalog.Live(accountModels("antigravity", l.User))+ out = mergeAntigravityModels(out, own)+ }+ if len(out) == 0 || sameModelIDs(out, pooled) {+ return+ }+ if err := catalog.SaveLive("antigravity", codeAssistDaily, out); err != nil {+ log.Printf("antigravity: pooled models not kept: %v", err)+ }+}++// sameModelIDs says two lists name the same models in the same order.+func sameModelIDs(a, b []catalog.Model) bool {+ return slices.EqualFunc(a, b, func(x, y catalog.Model) bool { return x.ID == y.ID })+}diff --git a/internal/provider/antigravity_quota_list_test.go b/internal/provider/antigravity_quota_list_test.gonew file mode 100644index 000000000..334789dd5--- /dev/null+++ b/internal/provider/antigravity_quota_list_test.go@@ -0,0 +1,104 @@+package provider++import (+ "context"+ "slices"+ "strings"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/catalog"+)++// A model Google gives one Antigravity account after its list was fetched+// (01huadalang on Discord: Gemini 4 on one account of several) joins that+// account's list and the subscription's at the account's next quota+// reading, which asks fetchAvailableModels anyway: no probe, sync or+// account made preferred is needed for the picker, routing or its bar.+// An account switched off changes nothing.+func TestAntigravityQuotaReadingListsNewModels(t *testing.T) {+ replies := map[string]string{+ "project-a": `{"models":{"gemini-3.8-flash":{"quotaInfo":{"remainingFraction":1}},"gemini-4-argon-disabled":{"displayName":"Gemini 4 Argon","disabled":true}}}`,+ "project-b": `{"models":{"gemini-3.8-flash":{"quotaInfo":{"remainingFraction":1}}}}`,+ "project-off": `{"models":{"gemini-3.8-flash":{}}}`,+ }+ f := &fakeGoogle{}+ // the fake holds f.mu while it asks modelsFor+ f.modelsFor = func(body map[string]any) (int, string) {+ project, _ := body["project"].(string)+ return 200, replies[project]+ }+ googleSandbox(t, f)+ for _, user := range []string{"a", "b", "off"} {+ if err := addGoogleLogin("antigravity", user+"@example.com", "", googleAuth{+ AccessToken: user, RefreshToken: "rt-" + user, Project: "project-" + user,+ Expiry: time.Now().Add(time.Hour).UnixMilli(),+ }); err != nil {+ t.Fatal(err)+ }+ }+ if err := switchGoogleLogin("antigravity", "[email protected]"); err != nil {+ t.Fatal(err)+ }+ for user, on := range map[string]bool{"[email protected]": true, "[email protected]": false} {+ if err := setGoogleLoginOn("antigravity", user, on); err != nil {+ t.Fatal(err)+ }+ }+ p, _ := googleAccountOf("antigravity")+ if _, err := p.Fetch(context.Background()); err != nil {+ t.Fatal(err)+ }+ pooled := func() []string {+ ms, _, _ := catalog.Live("antigravity")+ var ids []string+ for _, m := range ms {+ ids = append(ids, m.ID)+ }+ return ids+ }+ if got := pooled(); !slices.Equal(got, []string{"gemini-3.8-flash"}) {+ t.Fatalf("pooled before %v", got)+ }+ read := func(user string) {+ t.Helper()+ for _, l := range googleLogins("antigravity") {+ if l.User == user {+ if q := l.acct.quota(context.Background(), ""); q.Error != "" {+ t.Fatalf("%s's reading: %s", user, q.Error)+ }+ return+ }+ }+ t.Fatalf("no login %s", user)+ }+ // Google gives b Gemini 4, and gives the switched-off account a model+ f.mu.Lock()+ replies["project-b"] = `{"models":{"gemini-3.8-flash":{"quotaInfo":{"remainingFraction":1}},"gemini-4-argon":{"displayName":"Gemini 4 Argon","quotaInfo":{"remainingFraction":0.5}}}}`+ replies["project-off"] = `{"models":{"gemini-3.8-flash":{},"off-only":{}}}`+ f.mu.Unlock()+ read("[email protected]")+ read("[email protected]")+ if got := pooled(); !slices.Equal(got, []string{"gemini-3.8-flash"}) {+ t.Fatalf("pooled after a's and the off account's readings %v", got)+ }+ read("[email protected]")+ if got := pooled(); !slices.Equal(got, []string{"gemini-3.8-flash", "gemini-4-argon"}) {+ t.Fatalf("pooled after b's reading %v, want Gemini 4 in it", got)+ }+ p, _ = googleAccountOf("antigravity")+ if p.Account.Lists("gemini-4-argon") {+ t.Error("a, whose Gemini 4 is disabled, lists it")+ }+ also := p.AlsoOn()+ if len(also) != 1 || !also[0].Account.Lists("gemini-4-argon") {+ t.Error("b's own list lacks Gemini 4 after its reading")+ }+ if ms, _, _ := catalog.Live(accountModels("antigravity", "[email protected]")); slices.ContainsFunc(ms, func(m catalog.Model) bool { return m.ID == "off-only" }) {+ t.Error("a switched-off account's reading kept its list")+ }+ q, _ := Find("antigravity")+ if !slices.ContainsFunc(q.Available(), func(m catalog.Model) bool { return strings.HasPrefix(m.ID, "gemini-4-argon") }) {+ t.Error("Gemini 4 is not offered after b's reading")+ }+}diff --git a/internal/provider/google.go b/internal/provider/google.goindex 3f7bb85eb..f0c9f684f 100644--- a/internal/provider/google.go+++ b/internal/provider/google.go@@ -1114,6 +1114,14 @@ func (g googleAccount) models(ctx context.Context) ([]catalog.Model, error) {}return g.flags(ctx, p.id).offered(preview), nil}+ return g.antigravityList(infos), nil+}++// antigravityList is an Antigravity account's catalog from what its+// fetchAvailableModels listed (models), the fallback list when it listed+// none.+func (g googleAccount) antigravityList(infos []googleModelInfo) []catalog.Model {+ infos = slices.Clone(infos)fallback := g.fallbackModels()names := map[string]string{}for _, m := range fallback {@@ -1145,9 +1153,9 @@ func (g googleAccount) models(ctx context.Context) ([]catalog.Model, error) {out = append(out, m)}if len(out) == 0 {- return fallback, nil+ return fallback}- return out, nil+ return out}func (g googleAccount) fallbackModels() []catalog.Model {@@ -1171,6 +1179,13 @@ func (g googleAccount) quota(ctx context.Context, plan string) SubscriptionQuotaq.Error = err.Error()return q}+ if g.app.agent == "antigravity" && len(infos) > 0 {+ // the reading lists the account's models too: a model Google gave+ // it since its list was fetched joins the account's list and the+ // subscription's, for the picker, routing and its bar, without a+ // probe or a sync (01huadalang on Discord)+ noteAntigravityList(g.user, g.app.base, g.antigravityList(infos))+ }for _, mi := range infos {if mi.remaining < 0 {continue