diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 34122c6a7..64276a8d8 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -71,6 +71,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it, each window with its whole-window estimate (`Holds`/`HoldsWhy`, `usage.WithWindowHolds`, which `quotaReport` reaches through the `ReckonHolds` hook since package provider can't import usage, #2333). A Remote magpie's cards (`GET /v1/magpie/quotas/cards`, `writeCards`) carry the estimate too, for the owner or a key with no limits on what it sees, since the computer reading them has none of the remote's calls to reckon from (linkaww on Discord: a Docker magpie's ChatGPT Pro week showed no whole on the other computer; `TestRemoteMagpieCardsCarryTheirWholes`). A Codex card's estimate counts the calls of a ChatGPT API account (`chatgpt-api`) that is the same ChatGPT account, whose plan limits they share: the tokens of both must name the same `chatgpt_account_id` and `chatgpt_user_id`, never matched by name, so two Team seats of one email stay apart (`SamePlanAccounts` in [`chatgpt_same_plan.go`](../../internal/provider/chatgpt_same_plan.go), jctaoo on Discord, `TestWindowHoldsCountsTheSameChatGPTAccountThroughTheAPI`). Routing weighs such a ChatGPT API account by that Codex account's reading too: `Allowances("chatgpt-api")` gives it the Codex account's allowance (`samePlanAllowances`; tmr11235 on X, `TestChatGPTAPIAllowanceIsTheSameAccountsCodexReading`), so Smart no longer puts it after every known account as unknown; one with no Codex twin stays unknown. A window that has just reset, with too little used to scale (`HoldsLow`, `HoldsNoneRouted`), keeps the account's last whole for that window, marked `holds.prevAt` (the time it was reckoned; the GUI's tooltip says which window it came from, as a past cycle's does) until it tells its own; the last whole per account and window is kept in `window-holds.json` (`carryHolds` in [`window_holds_carry.go`](../../internal/usage/window_holds_carry.go), every provider's, Musikrv77852 on X; `TestWholeKeptAcrossReset`, `quota-holds.test.cjs`). A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). What it has kept includes its own Remote magpies' cards as it last read them (`passedOnCards`, no remote asked), so a chain passes every card on (yuyong_id on Discord: magpie3 → magpie2 → magpie1 showed none of magpie1's Codex at magpie3), named after each magpie (`magpie2/magpie1/codex`, "Codex · magpie1 · magpie2"); the card standing for a remote and its keys' limits stay the reader's own. Each card carries `via`, the `catalog.Self` of each magpie it went through, and a reader leaves out one that loops (`catalog.Loops`, as a model's `magpie_via`). A refresh of such a card is passed to the magpie it came from (`quotaCardsRefresh` takes a card id this magpie has from a remote); a Codex reset is offered on the magpie next door only, and quota history isn't passed on. The status line's kept report (`KeptQuotaReport`) has a remote's cards the same way. A ChatGPT account's card has an *Image generation* row (`WithImageLane`, [`image_lane.go`](../../internal/provider/image_lane.go), `Lane` `images`, Text and Aside so routing, holds and history never see it; hqqqqqqqh on X, #6160): ChatGPT's images have a quota apart from the 5-hour and weekly windows, which `/wham/usage` doesn't tell (`additional_rate_limits` is null). Every reply of the images API, a 200 too, does: `x-codex-active-limit: imagegen_premium` with the window in `x-codex-primary-*` (1440 minutes, `reset-at`), or in the limit's own family (`x-imagegen-premium-primary-*`, as Codex's `parse_all_rate_limits` reads it). The gateway keeps that window per account (`heardCodexImage` in [`codex_image_limits.go`](../../internal/gateway/codex_image_limits.go), from magpie's drawing and from Codex's own relayed `/images/*`; `provider.ImageHeard`), and never takes it for a chat window (`codexHeaderLimits` tells none when the active limit is an image one; #6412, Green14964 on X: the card said "2 minutes" of a 24-hour window). So the row says *Available* with the window's reset, *Used up* when the headers say 100% or while the image model is resting on that account after a refusal (`ImageRest`, the gateway's `restingUntil`, whose time is the refusal's `resets_at`, #2244, else the heard window's reset for a 429 with that window full, not `quotaRest`'s 15 minutes), and *Unknown* before any drawing, never a share or a count (`TestWithImageLaneOnlyReadCodexCards`, `TestCodexImageRowIsTheRefusalsResetTime`, `TestCodexImageRowFromA200sHeaders`, `TestCodexImageRefusalRestsUntilItsWindow`, `codex-image-row.test.cjs`). The window heard lives in memory only, so after a restart the row is *Unknown* until the next drawing. Not done: the count of images made in the window. Each key of a remote-magpie provider also gets a card of its own, under `/~keys`, one section per key (#1547, `remoteKeyCards` in `remote_key_limits.go`): the gateway key's limit as that magpie holds it, read from `GET /v1/magpie/limit` asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus `GatewayKey` (what is left, calls, a cycle of days, used up); a key held to no limit shows `Unlimited`. It is kept for `remoteCardsFor` like the remote's cards and read again by the card's refresh (`?provider=/~keys&user=`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). A remote's Codex card keeps its `Resets` (not a GLM team's, `ByWindow`), and its check-ins are dropped: **Use one…** there goes through `/api/usage/codex-reset` with the card's `provider`, and `UseRemoteCodexReset` asks the remote's `POST /v1/magpie/quotas/codex-reset?user=` with the provider's key (#3850). The remote spends it with `SpendCodexReset`, the same function as the Usage page (`UseCodexResetCard`, then `AwaitAllowance`). The account is always named. A 403 `gateway_key_read_only` is told as a read-only key there, and a 404 as a remote too old. No answer within `RemoteResetWait` says the reset may have been used, and it is never asked again by itself. A remote that holds the key to a budget, models or accounts answers its cards 403 `gateway_key_held` (#1981, `errKeyHeld`): the cards kept from before are dropped, and beside the key's own card the remote's card says it tells this key no quotas, and that on that computer Quotas is turned on for the key and it is let use every model of a provider whose usage it is to see (`errRemoteHeld`; yi_time on Discord saw the remote's Claude vanish from every page with no word). Its owner can let the key be told the cards of what it may use (#2216, `magpie gateway-key quotas on`); the remote then answers those, and 403 held as before when that is none (`writeCards`), so that key shows the same card. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). Each card also carries `routing`, each window's span, the model it alone counts and whether it is aside (`provider.ToldRouting` in `writeCards`), which a window's own json leaves out; the magpie reading them lays them back on the windows (`withRouting` in `keepRemoteCards`), and only such a card is weighed by routing (`provider.RemoteAllowance`, #6708, [gateway routing](gateway-routing.md)). Passed on, the cards keep them, so a third magpie weighs them too. A read the test hook dropped (`ForgetRemoteCardsForTest` moves `remoteCardCache.gen` on) is not kept. Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, `quotasOpened`, #1588) or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. A plugin's window may carry a prepaid wallet's `balance` in its `unit` and no share (`QuotaWindow.Balance`, #3950): the card and `magpie quota` show the figure (`BalanceText`), and routing reads it through `Allowance.Left`. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`quota_asked.go`](../../internal/provider/quota_asked.go) | | A remote magpie's prices | A local magpie asks a remote magpie's `/v1/models` with `X-Magpie-Prices` (`PricesHeader`, sent by `listHeaders`). The remote answers each model's `magpie_price`: what its own Usage page counts the model at (`EntryPriceIn`: the price its user set, else its provider's list price at its price rate; a routing group only when every member costs the same). It tells it only to a request from its own computer or one let in with a gateway key (`local` or `sharedWith`); a list that didn't ask gets no `magpie_price` (a remote request without a valid key never reaches the list: `lanGuard` refuses it); every list told to those callers also carries the same price as OpenRouter's `pricing`, for agents ([gateway routing](gateway-routing.md)). The local keeps the price with the fetched list (`catalog.Model.Price`; a value that isn't a price, or has a negative part, is dropped, the model kept) and uses it as that provider's list price (`ListPrice` → `remotePrice`). A price the local user set (`provider/model`, `provider/*`, `*/model`) still comes first, and the local provider's own price rate still applies on top. A remote from before this sends no field and the models stay priced as before; an older local sends no header and is sent nothing new. The model editor says the greyed price is the other magpie's (`remoteList`). | [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`models.go`](../../internal/provider/models.go), [`gateway.go`](../../internal/gateway/gateway.go) (`models`), [`live.go`](../../internal/catalog/live.go) | | A remote magpie's service tiers | A remote magpie's `/v1/models` gives each model the `service_tiers` its own Codex is offered on it (`codexTiers` → `codexcat.ServiceTiers`, from the same `CodexCatalog` and `codexcat.Entries` as its `/v1/codex/models`: Fast on a ChatGPT account's GPT model, the tiers of Codex's own entry on a relay's, none on a model it offers none). Ultrafast is added where the remote's own key or account offers it (`UltraOn`, read in `CodexTiersWith` with `UltraModels` read once a list): an OpenAI key's or a relay's GPT-6.2 Sol, a ChatGPT account whose plan lists it, and a group with such a member (the gateway asks that member for it and the others for `priority`, `tierMate`). `codexcat.Entries` keeps it beside the Fast it gives a group or a ChatGPT account's model and the tiers it takes from Codex's own catalog (`withTiers`), naming it Ultrafast where that catalog doesn't. Before, only Codex's own catalog could add it, so a remote in Docker, with no Codex beside it, offered Fast alone and the local's GUI never offered Ultrafast on its models (OoopsHh on X, `TestRemoteMagpieOffersUltrafast`). Both ends need it: the remote to list the tier, the local to read it (which it already did). The local keeps the ids (`catalog.Model.Tiers` → `Entry.Tiers`), `codexListed` hands them on for the remote's models, and `codexcat.Entries` offers them to the local Codex with Codex's own names (`namedTiers`). The gateway sends the tier Codex asks for to a remote magpie as it was asked (`Request.OwnTier`, as for a provider added by its address; dropped and not sent again if refused), and the remote serves it as its own Codex's turn (#1234). An agent's picker offers the bolt on a remote's model whose tiers hold `priority` (`provider.CanFast` reads them with `RemoteTiers`; Ultrafast too where they hold `ultrafast`, `UltraOn`), and a fast pick of one goes on with `service_tier` `priority` on the remote's Chat or Responses: an agent on Messages, whose fast is Claude's `speed`, has it turned into the tier the remote offers (`forwardTranslated`), so Claude Code's pick reaches the remote's vendor too (littlekk88 on Discord; `TestRemoteMagpieFastPick`, red without either half). A remote from before this sends no tiers, and its models are offered none, as before. The list gives every client the tiers, not only a magpie asking with `X-Magpie-Drawers`: Cindy shows its Fast switch on a model whose `service_tiers` hold `priority` (#1914, `TestModelsListTiersForEveryClient`). | [`codexcat.go`](../../internal/codexcat/codexcat.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`gateway.go`](../../internal/gateway/gateway.go), [`live.go`](../../internal/catalog/live.go) | +| A remote magpie's best API | A remote magpie's `/v1/models` (`X-Magpie-Drawers`) gives each model `magpie_prefers`, the path it is best asked on there (`provider.PreferredEndpoint`: its provider's `Native`, or a routing group's `GroupAPI`; left out for a model translated anyway or a group on Chat), which `native_endpoints`, in its provider's speaking order with Chat first, doesn't say. The local magpie keeps it as `catalog.Model.Prefers`; `Provider.Native` takes it first for a Remote magpie (`RemotePrefers`), so every agent wired one API per model (Pi, omp, droid, dsh, through `catalog.Model.APIs`) asks a GPT whose OpenAI key or relay is best on Responses there, or a group whose members are, on Responses here too, and the gateway's `usable` translates another API's request to it once (OoopsHh on X: Pi's `openai/*` and `auto/*` on openai-completions turned away effort max). A remote from before says nothing, and its models stay on Chat. `TestRemoteMagpiePrefersResponses`, `TestPiAsksARemoteMagpiesModelWhereItPrefers`. | [`native_endpoints.go`](../../internal/provider/native_endpoints.go), [`remote_magpie.go`](../../internal/provider/remote_magpie.go) | | Two magpies each the other's remote | The list a magpie gives another magpie (`X-Magpie-Drawers`) names, as `magpie_via`, the magpies each model passes through to its vendor, itself last (`catalog.ViaHere`, `viaOf`; a routing group's are its members' together, so a group with the other magpie's own group of the model in it is left out there too). Each process has a random id (`catalog.Self`). A fetched list leaves out a model whose `magpie_via` has this magpie and another one (it went out of here and came back), or more than `MaxVia` (8), so two magpies that are each other's remote no longer list each other's models back one level deeper on every 10-minute fetch, without end, each level another member of the found `auto/` group and another trip round the two (cdredfox on Discord, 100-200% CPU). A remote that is this magpie itself (sync carries a Remote magpie provider to the computer it names, hanslin1666) has its models through this id alone, taken once; one through this id twice or more is left out. Such a remote is found by its own list: a fetch whose models' `magpie_via` ends with this magpie's own `Self` is kept, by provider id and the address it answered at, in `remote-self.json` (`noteSelf`; another lister, or a list with no via, takes it away; an empty list or a failed fetch changes nothing; this computer's own file, never in a backup or a sync). The provider is then left out (`SelfLeftOut` in `On`, `SwitchedOff`, `remoteMagpies`): its models are not listed beside this magpie's own nor in a found group, and a request naming one, an agent's pick sync brought from the other computer, is served here with the remote's id taken off the front (`ThroughSelf` in `Resolve` and `ResolveRoute`), not passed through the gateway again. The Providers row says *This magpie* (greyed while left out) and its editor says why, with **Use it anyway** (`KeepSelf`, `provider/keepself`, `SetKeepSelf`), the user's to set (hanslin1666): kept, it is served as any remote, each request twice through this magpie. `KeepSelf` is this computer's own like `KeepLogin` (`Mirror`, `Restore`, blanked in davsync's `hashes`), since the other computer's copy points at this one, which is not itself (`TestRemoteMagpieThatIsThisOneIsLeftOut`, `TestRemoteSelfRecord`, `remote-self.test.cjs`). Each request passed on to a Remote magpie says how many magpies it went through (`X-Magpie-Hops`, `passOnCaller`); one that arrives having passed `MaxVia` is answered 508 Loop Detected (`withCaller`), read only from a magpie's request and taken off every request as it arrives. A magpie older than the field sends none, and its models are taken as they were. The quota cards a Remote passes on follow the same ways (X on 0.1.3678: A → B → C → A told Kiro and Codex by `remote-B/kiro` and `remote-B/remote-C/remote-A/remote-B/remote-C/kiro`, hours apart, to a Remote enabled for one local model): a card's `via` that names any magpie twice is a loop too, so one that came round after this magpie restarted (its old `Self` is no longer this one's) is left out (`catalog.Loops`), and isn't kept in `remoteCardCache` (`keepRemoteCards`). A Remote's cards are shown, and passed on, only for the providers it is enabled for: the card's provider id must be the provider path of an exposed model there (its id less the last part, or a parent of it, whole parts only: relay/strata enabled tells relay/strata, never relay/kiro; `remoteCardWanted`, `cardWantedFor`, `TestRemoteCardWantedByWholePath`, 748975219 on X), unknown, so all shown, while its list isn't read, and all shown for a Remote set to Select none (it serves no model, its usage is still read; a user on X, 0.1.3929, `TestRemoteSelectNoneStillShowsItsCards`). One subscription account's copies (same provider, same `user`) are one card, the newest complete reading, then the shorter way (`oneCardPerAccount`, in `RemoteCards` and `CachedCards`; a key's cards, whose `user` is a name two keys may share, are not merged) (`TestRemoteCardsFollowEnabledModelsAndDedupe`, `TestLoopsOnARepeatedMagpie`). | [`magpie_via.go`](../../internal/catalog/magpie_via.go), [`live.go`](../../internal/catalog/live.go), [`gateway.go`](../../internal/gateway/gateway.go), [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`remote_self.go`](../../internal/provider/remote_self.go), [`remote_quotas_scope.go`](../../internal/provider/remote_quotas_scope.go) | | A remote magpie that moved | Computer A's router hands it a new address now and then (luckymanjc on Discord), and B's Remote magpie, saved at the old one, reached nothing. When B can't connect to it at all (a dial error, `unconnected`), its list fetch (`fetch` in [`models.go`](../../internal/provider/models.go)) and the gateway's request (`forward` in [`gateway.go`](../../internal/gateway/gateway.go)) call `SeekMoved` ([`remote_moved.go`](../../internal/provider/remote_moved.go)): every address of the old one's /24 and of up to four of B's own private /24s is dialled at A's port (500ms each, 128 at once, `lanNeighbours`). Whatever takes the connection there may be anyone's (a café's network, A switched off), so it is sent neither the key nor the provider's headers until it proves it holds the key (`proves`): B POSTs a nonce of its own and `RemoteKeyID` (the key's sha256, hex) to `RemoteProvePath` (`/v1/magpie/prove`) with no key and no proxy, and checks with `hmac.Equal` that the answer is `RemoteProof`: HMAC-SHA256 under the key of the nonce and the address B dialled. A answers it ([`remote_prove.go`](../../internal/gateway/remote_prove.go)) for an enabled gateway key of that id (`access.ProveSecret`: constant-time compares over every key, then `Check`) at the address the connection reached it on (`http.LocalAddrContextKey`), so a host passing B's nonce on to A elsewhere hands back a proof for A's address, not its own; 404 for a key it hasn't or has turned off. Only an address that proved is asked `/v1/models` with the key, and the first that lists 200 and whose list this magpie didn't make (`magpie_via`) is saved as the provider's address and asked again. A magpie from before the route, one behind a port forward or NAT (it is reached at another address than its own), or one behind a proxy that needs the provider's headers, is not found, and the user types the new address. An address saved, by that look or by the user's edit, is taken at once by a request already under way (le13ure on X: requests kept trying the old address after the edit): the gateway's try loop asks `Readdressed` before each try and moves the candidate onto the saved address, `SeekMoved` hands back the saved address when another caller's look (or the user) saved one within the minute, and a pause between tries (`pauseAlive`, `pauseUntilReaddressed` in [`patience.go`](../../internal/gateway/patience.go)) ends when `store` signals `Edited` and the provider's address changed. Dialling a private or link-local IP literal gives up after 5s (`lanDialCap` in [`lan.go`](../../internal/netproxy/lan.go), through `Dispatch`), where the OS would wait over a minute on an address no one holds (`TestRemoteMagpieSavedElsewhereIsTaken`, `TestRemoteMagpieRetryGoesToTheSavedAddress`, `TestPauseEndsWhenReaddressed`, `TestLANDialGivesUp`). A name or a public address is never looked around, an address the user changed meanwhile stands, and a provider is looked for once a minute at most, callers at once sharing the look (`TestRemoteMagpieKeyGoesToNoNeighbour`: an impostor that lists 200 for anything, one with a proof under another key, one with a garbled proof and one relaying to the real magpie are sent no key or header and not saved, and the real one is; `TestRemoteProof`, `TestRemoteMagpieFoundMoved`, `TestRemoteMagpieNotFoundStays`, `TestRemoteMagpieMovedIsFound`, `TestRemoteProveAnswersOnlyTheKeysHolder`). | | A relay's Codex entries | A provider the user added by its address with a Responses URL may list its models in Codex's own shape (`slug`, `supported_reasoning_levels`, `shell_type`, `base_instructions`: `catalog.CodexEntry`), plainly or when asked with Codex's `client_version`, as sub2api does (ctopsc on Discord: GPT-6.1 Terra was handed models.dev's 922000 window where the relay said 272000). `fetchOne` keeps such a row whole (`catalog.Model.Codex`, with its window, max window and inputs read off it), and when the plain list has none it asks the same URL once more with `client_version` (`codexEntries`): only where the list is fetched (add, key change, Refresh), never per Codex poll. The answer only adds entries to models the plain list has; one that fails or can't be read keeps the last list's entries (failed read = unknown), one that answers plainly says there are none. `codexcat.listedEntry` hands Codex the relay's entry as given, `base_instructions` included, with magpie's slug, name, priority and " via magpie" description; the user's window, compaction, levels and image setting still win (levels keep the relay's descriptions). A saved list from before is enriched at its next Refresh. `TestCodexListedEntry`, `TestCodexListedEntryInPlainList`. | [`codex_entries.go`](../../internal/provider/codex_entries.go), [`live.go`](../../internal/catalog/live.go), [`codexcat.go`](../../internal/codexcat/codexcat.go) | diff --git a/internal/agent/pi_remote_prefers_test.go b/internal/agent/pi_remote_prefers_test.go new file mode 100644 index 000000000..38d47936d --- /dev/null +++ b/internal/agent/pi_remote_prefers_test.go @@ -0,0 +1,59 @@ +package agent + +import ( + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// OoopsHh on X: with another magpie as the provider, Pi's models.json had +// only codex/* on openai-responses (a ChatGPT sign-in's models are listed +// on /v1/responses alone); an OpenAI key's openai/* and a routing group's +// auto/*, best asked on Responses there too, went on openai-completions, +// where the vendor turned away effort max. The remote's list now says the +// API it asks each model on best (magpie_prefers), and every agent that +// asks each model on its own API (Pi, omp, droid, dsh, through +// catalog.Model.APIs) is wired to it. A model best on Chat there, and one +// from a magpie from before that says nothing, stay on Chat. +func TestPiAsksARemoteMagpiesModelWhereItPrefers(t *testing.T) { + syncHome(t) + ids := []string{"openai/gpt-6.2-astra", "group/auto", "kimi/kimi-k3", "old/gpt-6.2-sol"} + if err := provider.Save(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Chat: "http://127.0.0.1:2", Key: "k", Models: ids}); err != nil { + t.Fatal(err) + } + office, err := provider.Find("office") + if err != nil { + t.Fatal(err) + } + efforts := []string{"low", "medium", "high", "xhigh", "max"} + if err := catalog.SaveLive("office", office.Chat, []catalog.Model{ + {ID: "openai/gpt-6.2-astra", Efforts: efforts, APIs: []string{"chat", "responses"}, Prefers: "responses"}, + {ID: "group/auto", Efforts: efforts, Prefers: "responses"}, + {ID: "kimi/kimi-k3", APIs: []string{"chat"}, Prefers: "chat"}, + {ID: "old/gpt-6.2-sol", Efforts: efforts, APIs: []string{"chat", "responses"}}, + }); err != nil { + t.Fatal(err) + } + want := map[string]any{"office/openai/gpt-6.2-astra": "openai-responses", "office/group/auto": "openai-responses", "office/kimi/kimi-k3": nil, "office/old/gpt-6.2-sol": nil} + seen := 0 + for _, m := range magpieModels("pi") { + w, ok := want[m.ID] + if !ok { + continue + } + seen++ + e := piModelJSON(piAsked("pi", m), "http://127.0.0.1:3425", true) + if e["api"] != w { + t.Errorf("%s: api %v, want %v (%v)", m.ID, e["api"], w, e) + } + if w == "openai-responses" { + if l, _ := e["thinkingLevelMap"].(map[string]any); l["max"] != "max" { + t.Errorf("%s: levels %v", m.ID, e["thinkingLevelMap"]) + } + } + } + if seen != len(want) { + t.Fatalf("listed %d of %v", seen, want) + } +} diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index ca377a6fb..4d1d851e2 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -47,6 +47,11 @@ type Model struct { // APIs, when the vendor says, are the APIs the model is served on // ("chat", "responses", "anthropic"); empty is not known. APIs []string `json:",omitempty"` + // Prefers, on a model of another magpie's list, is the API that magpie + // asks it on best (magpie_prefers): "responses" for a GPT its OpenAI + // key or ChatGPT sign-in is best asked on there, or a routing group + // whose members are; "" when it didn't say. + Prefers string `json:",omitempty"` // Endpoints, in magpie's own models for an agent, are the gateway // paths a request for it is relayed on as it is // (provider.NativeEndpoints, /v1/models' native_endpoints); a group's diff --git a/internal/catalog/live.go b/internal/catalog/live.go index 220f04025..e78308959 100644 --- a/internal/catalog/live.go +++ b/internal/catalog/live.go @@ -353,6 +353,9 @@ func Unique(ms []Model) []Model { if len(k.Via) == 0 { k.Via = m.Via } + if k.Prefers == "" { + k.Prefers = m.Prefers + } if k.ImageInput == nil && m.ImageInput != nil { k.ImageInput, k.Images = m.ImageInput, m.Images } @@ -1065,6 +1068,9 @@ func fetchPage(ctx context.Context, url, key string, anthropic bool, headers map } kimiFacts(&m, r) m.Via = slices.Clip(r.Via) + if p := EndpointAPIs([]string{r.Prefers}); len(p) == 1 { + m.Prefers = p[0] + } out = append(out, m) } return out, v.HasMore, v.LastID, nil @@ -1148,6 +1154,11 @@ type liveModel struct { // the magpies another magpie's model passes through to its vendor, // itself last (magpie_via.go) Via []string `json:"magpie_via"` + // the path another magpie asks the model on best (magpie_prefers): its + // provider's own best API for it, or a routing group's + // (provider.PreferredEndpoint), which native_endpoints, in the order + // that magpie's provider speaks them, doesn't tell + Prefers string `json:"magpie_prefers"` // the protocol family PipeLLM routes the model by: openai, anthropic // or gemini TypeTarget string `json:"type_target"` diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index f950a2c8c..198184813 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1866,6 +1866,13 @@ func (s *Server) listModels(w http.ResponseWriter, r *http.Request) { // shows its Fast switch on a model whose tiers hold priority // (#1914). A model with none says nothing tiers := codexTiers(shown) + // each routing group's members, looked up once a list, for + // another magpie's magpie_prefers + var membersOf func(string) []provider.Member + if magpie { + find := provider.FoundOnce(provider.GroupFinder()) + membersOf = func(id string) []provider.Member { _, ms, _ := find(id); return ms } + } // each model by its bare id as well, after the provider/model ids, // when the user asked for it (settings.BareModelIDs): a client // moved from another proxy asks for gpt-5.6-sol (love1sbug on X). @@ -1927,6 +1934,12 @@ func (s *Server) listModels(w http.ResponseWriter, r *http.Request) { // magpies, for one that names its models by it // (provider.UpstreamNames, lcc580 on X) m["magpie_by"] = e.ServedBy() + // the API it is best asked on here, which + // native_endpoints' order doesn't say: that magpie's + // agents are wired to it (OoopsHh on X) + if pe := provider.PreferredEndpoint(e, membersOf); pe != "" { + m["magpie_prefers"] = pe + } } if ts := tiers[e.ID]; len(ts) > 0 { m["service_tiers"] = ts @@ -8385,6 +8398,11 @@ func (s *Server) usable(p provider.Provider, model string) []provider.Protocol { if p.MessagesFirst(model) { sort.SliceStable(out, func(i, j int) bool { return out[i] == provider.Anthropic && out[j] != provider.Anthropic }) } + // a remote magpie's model is translated to the API that magpie asks it + // on best, so it isn't translated there a second time + if pr := p.RemotePrefers(model); pr != "" { + sort.SliceStable(out, func(i, j int) bool { return out[i] == pr && out[j] != pr }) + } if p.IsPlugin() && len(apis) > 1 { // a plugin's model is translated to its own API, the first it // lists: the others its vendor serves it on (Open Design's) take a diff --git a/internal/gateway/remote_magpie_prefers_test.go b/internal/gateway/remote_magpie_prefers_test.go new file mode 100644 index 000000000..054c5869f --- /dev/null +++ b/internal/gateway/remote_magpie_prefers_test.go @@ -0,0 +1,132 @@ +package gateway + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// A remote magpie's list says which API it asks each model on best +// (magpie_prefers), which native_endpoints, in its provider's order with +// Chat first, doesn't: a GPT whose provider there is best on Responses, +// and a routing group whose members are, are asked on Responses here too. +// Without it the magpie that has it as its provider took Chat for both, +// and wired Pi's openai/* and auto/* to openai-completions, where the +// vendor turns away the max effort Responses takes (OoopsHh on X). A model +// best on Chat there stays on Chat. Here the gateway is both computers'. +func TestRemoteMagpiePrefersResponses(t *testing.T) { + var mu sync.Mutex + var vendor, hops []string + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + mu.Lock() + vendor = append(vendor, r.URL.Path) + mu.Unlock() + switch { + case strings.HasSuffix(r.URL.Path, "/chat/completions"): + if strings.Contains(string(b), `"reasoning_effort":"max"`) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + io.WriteString(w, `{"error":{"message":"Unsupported value: 'reasoning_effort' does not support 'max' with this model.","type":"invalid_request_error"}}`) + return + } + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse(`data: {"id":"c1","choices":[{"index":0,"delta":{"content":"hello"}}]}`, + `data: {"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, `data: [DONE]`)) + case strings.HasSuffix(r.URL.Path, "/responses"): + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `data: {"type":"response.created","response":{"id":"r1","model":"gpt-6.2-astra"}}`, + `data: {"type":"response.output_text.delta","delta":"hello"}`, + `data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":7,"output_tokens":1}}}`)) + default: + w.WriteHeader(404) + } + })) + t.Cleanup(up.Close) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + // an OpenAI key at a relay given as its Responses URL, which serves Chat too + if err := provider.Save(provider.Provider{ID: "openai", Name: "OpenAI", Key: "k", Models: []string{"gpt-6.2-astra"}, + Chat: up.URL + "/v1", Responses: up.URL + "/v1", BaseAPI: "responses"}); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "kimi", Name: "Kimi", Key: "k", Models: []string{"kimi-k3"}, Chat: up.URL + "/v1"}); err != nil { + t.Fatal(err) + } + if err := provider.SaveGroup(provider.Group{ID: "auto", Name: "Auto", Members: []string{"openai/gpt-6.2-astra"}}); err != nil { + t.Fatal(err) + } + h := New().Handler() + remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost { + mu.Lock() + hops = append(hops, r.URL.Path) + mu.Unlock() + } + h.ServeHTTP(w, r) + })) + t.Cleanup(remote.Close) + id, err := provider.Add(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Chat: strings.TrimPrefix(remote.URL, "http://")}) + if err != nil { + t.Fatal(err) + } + office, err := provider.Find(id) + if err != nil { + t.Fatal(err) + } + if _, err := office.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + live, _, _ := catalog.Live("office") + prefers := map[string]string{} + for _, m := range live { + prefers[m.ID] = m.Prefers + } + want := map[string]string{"openai/gpt-6.2-astra": "responses", "group/auto": "responses", "kimi/kimi-k3": "chat"} + for m, p := range want { + if prefers[m] != p { + t.Errorf("%s: the remote's list prefers %q, want %q (%v)", m, prefers[m], p, prefers) + } + } + office, _ = provider.Find(id) + for m, p := range map[string]provider.Protocol{"openai/gpt-6.2-astra": provider.Responses, "group/auto": provider.Responses, "kimi/kimi-k3": provider.Chat} { + if n := office.Native(m); n != p { + t.Errorf("%s is best asked on %q here, want %q", m, n, p) + } + } + + calls := []struct{ path, body, hop, vendor string }{ + // Pi on openai-responses, as it is now wired: max goes through + {"/v1/responses", `{"model":"office/openai/gpt-6.2-astra","input":"hi","stream":true,"reasoning":{"effort":"max"}}`, "/v1/responses", "/v1/responses"}, + {"/v1/responses", `{"model":"office/group/auto","input":"hi","stream":true,"reasoning":{"effort":"max"}}`, "/v1/responses", "/v1/responses"}, + // a Messages client's request is turned into the remote's best + // API here, once, not into Chat to go on as Chat + {"/v1/messages", `{"model":"office/openai/gpt-6.2-astra","max_tokens":10,"stream":true,"messages":[{"role":"user","content":"hi"}]}`, "/v1/responses", "/v1/responses"}, + // a model best on Chat there is turned into Chat + {"/v1/messages", `{"model":"office/kimi/kimi-k3","max_tokens":10,"stream":true,"messages":[{"role":"user","content":"hi"}]}`, "/v1/chat/completions", "/v1/chat/completions"}, + } + for _, c := range calls { + mu.Lock() + vendor, hops = nil, nil + mu.Unlock() + code, body := post(t, c.path, c.body) + mu.Lock() + gotHops, gotVendor := slices.Clone(hops), slices.Clone(vendor) + mu.Unlock() + if code != 200 || !strings.Contains(body, "hello") { + t.Fatalf("%s %s: %d %s", c.path, c.body, code, body) + } + if !slices.Equal(gotHops, []string{c.hop}) || !slices.Equal(gotVendor, []string{c.vendor}) { + t.Errorf("%s %s: remote asked on %v, vendor on %v; want %s, %s", c.path, c.body, gotHops, gotVendor, c.hop, c.vendor) + } + } +} diff --git a/internal/provider/native_endpoints.go b/internal/provider/native_endpoints.go index f21085f9f..7af1ace46 100644 --- a/internal/provider/native_endpoints.go +++ b/internal/provider/native_endpoints.go @@ -18,6 +18,22 @@ func NativeEndpoints(e Entry) []string { return endpointsOf(relayed(*e.Provider, e.Model)) } +// PreferredEndpoint is the path a request for the model is best asked on +// (/v1/models' magpie_prefers, for another magpie that has this one as its +// provider): its provider's Native API, or for a routing group the one +// GroupAPI wires an agent to, Responses where its members are best there. +// "" for a model translated anyway, or a group that stays on Chat. +// members is nil when the group's aren't known. +func PreferredEndpoint(e Entry, members func(id string) []Member) string { + if e.Group == "" { + return endpointOf[e.Provider.Native(e.Model)] + } + if members == nil { + return "" + } + return endpointOf[GroupAPI(members(e.ID))] +} + // relayed are the APIs p takes a request for model on as it is, in the // order p speaks them: none for a model every request to is translated // anyway. diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 475e67532..b8d4fc501 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -2379,6 +2379,16 @@ func (p Provider) Native(model string) Protocol { if len(out) == 0 { return "" } + // a remote magpie's own best API for it (magpie_prefers): its list + // names every API the model goes on as it is in the order its provider + // speaks them, Chat first, so a GPT its OpenAI key or ChatGPT sign-in + // serves best on Responses, and a routing group whose members are, + // was asked on Chat here — where OpenAI turns away the max effort + // Responses takes (OoopsHh on X: Pi's openai/* and auto/* on + // openai-completions, codex/* alone on openai-responses) + if pr := p.RemotePrefers(model); pr != "" && slices.Contains(out, pr) { + return pr + } if p.ResponsesFirst(model) && slices.Contains(out, Responses) { return Responses } diff --git a/internal/provider/remote_magpie.go b/internal/provider/remote_magpie.go index 9ed372ddb..d2ac0d1bc 100644 --- a/internal/provider/remote_magpie.go +++ b/internal/provider/remote_magpie.go @@ -196,3 +196,18 @@ func (p Provider) RemoteVia(model string) []string { } return nil } + +// RemotePrefers is the API a remote magpie's list says it asks the model +// on best (magpie_prefers, PreferredEndpoint there); "" for another +// provider's model, or one from a magpie from before it said. +func (p Provider) RemotePrefers(model string) Protocol { + if !p.IsRemoteMagpie() { + return "" + } + for _, m := range p.liveByID(model) { + if m.Prefers != "" { + return Protocol(m.Prefers) + } + } + return "" +}