diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 1542851fa..58e6c5b9f 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -60,6 +60,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 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). 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`). 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). 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) | +| 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 (only this id) is kept. A magpie older than the field sends none, and its models are taken as they were. | [`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) | | 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) | | An endpoint's catalog | A key's provider with no catalog of its own (none named, none from a preset) is priced from the models.dev catalog whose `api` is one of its endpoints (`EndpointCatalog`, `catalog.AtEndpoint`; a trailing slash and case don't count, and an Anthropic base, kept as its root, is also matched with its `/v1`). Only when exactly one catalog is at that address, and it isn't a plan's (an id with `-plan`, or a `membershipCatalogs` one): a plan lists its membership's $0, and two catalogs at one address can't be told apart. A subscription's account never gets one. A provider at AMD's own endpoint is priced from `amd`, which lists Qwen3.8-27B at $0, a price, where its maker sells no such model and it had none (#2052); a relay's endpoint matches nothing and its model stays unpriced, never priced at a reseller's guess. `magpie model price` names the catalog, and says how to give a price when none is known. | [`models.go`](../../internal/provider/models.go), [`catalog.go`](../../internal/catalog/catalog.go) | | The maker's own price | A model priced at its maker (`MakerPrice`, a provider's `ListPrice` after its own catalog, `PricedName`; through `makerListPrice`) is priced at a models.dev provider that lists it as its own (`catalog.MakerPriced`): one whose entry's `canonical_model_id` names it as the maker, or whose id is the maker's with a region (`alibaba-cn`), never a plan's (`-plan`) and never at $0. A maker preset that is such an API is asked first, in preset order, then the other owners by id; only then the maker presets as before (`PricedBy`). A maker preset that resells another lab's model no longer prices it: Mistral's `deepseek-v4-1-flash-1017` at $0.30/$1.20 gave way to DeepSeek's $0.15/$0.60, and a lab that isn't a preset (Meta's `muse-spark`) is priced at all. So a subscription's model (Command Code's, bestony on Discord) is estimated at what its maker charges (`TestMakerPriceIsTheMakersOwn`). A model no maker lists (Kimi K2.5, GLM-5.2 Fast) stays unpriced; the user gives it a price or a same-as model. | [`models.go`](../../internal/provider/models.go), [`catalog.go`](../../internal/catalog/catalog.go) | diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index f44638080..bbc09672a 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -84,6 +84,9 @@ type Model struct { // provider after it (magpie_label): the name Provider in model names // Off has here (ARNO on Discord). Plain string `json:",omitempty"` + // Via, on a model of another magpie's list, is the magpies it passes + // through to its vendor, that one last (magpie_via.go) + Via []string `json:",omitempty"` // Apart, in a list magpie hands Codex, is what tells the model from // another entry Codex's picker would call the same (two providers // named Codex each serving GPT-6.1-Sol, nb5p on Discord): its diff --git a/internal/catalog/live.go b/internal/catalog/live.go index 230e8d384..a31f794ce 100644 --- a/internal/catalog/live.go +++ b/internal/catalog/live.go @@ -633,6 +633,10 @@ func fetchPage(ctx context.Context, url, key string, anthropic bool, headers map if id == "" { continue } + // one that goes from here and comes back (magpie_via.go) + if loops(r.Via) { + continue + } // Another magpie's list is already what its user exposed. Keep // its retrieval models too; a vendor's general list still leaves // out models agents can't chat with. @@ -704,6 +708,7 @@ func fetchPage(ctx context.Context, url, key string, anthropic bool, headers map codexFacts(&m, r, codex) } kimiFacts(&m, r) + m.Via = slices.Clip(r.Via) out = append(out, m) } return out, v.HasMore, v.LastID, nil @@ -781,6 +786,9 @@ type liveModel struct { // its X-Magpie-Prices header: the price its user set, else its list // price. Raw, as an odd value mustn't lose the whole list Price json.RawMessage `json:"magpie_price"` + // the magpies another magpie's model passes through to its vendor, + // itself last (magpie_via.go) + Via []string `json:"magpie_via"` // the protocol family PipeLLM routes the model by: openai, anthropic // or gemini TypeTarget string `json:"type_target"` diff --git a/internal/catalog/magpie_via.go b/internal/catalog/magpie_via.go new file mode 100644 index 000000000..0d2943549 --- /dev/null +++ b/internal/catalog/magpie_via.go @@ -0,0 +1,56 @@ +package catalog + +import ( + "crypto/rand" + "encoding/hex" + "slices" + "sync" +) + +// Two magpies can each be the other's Remote magpie (cdredfox on Discord: +// two computers on one Tailscale network). Each one's list to the other +// had the other's own models in it, under its Remote magpie provider, and +// each fetch, every ten minutes (provider.RemoteMagpieEvery), took a turn +// more of the loop: rem/back/own/m1, then rem/back/rem/back/own/m1, … on +// both computers, without end. Every one of them joined its model's found +// group (auto/), and a request to one went round the loop, masked +// again on each computer each time it came back. +// +// So a magpie's list to another magpie names, of each model, the magpies +// it passes through on its way to its vendor (magpie_via): the one +// listing it, and those its own list had from, each by its Self. A list +// that names this magpie and another along the way is of a model that +// leaves here and comes back: it isn't taken. A magpie pointed at itself +// (the gateway's tests, which serve their remote from one process) is +// this magpie alone, and its list is taken as it was. A list from a +// magpie from before names nothing, and is taken as it was. + +// MaxVia is the most magpies a model's way may pass through before a list +// is taken to loop through a magpie from before magpie_via, which +// stamps none of its own. +const MaxVia = 8 + +// Self is this run of magpie's name in magpie_via: random, made up once a +// run, and told only to a magpie that asks for its list. +var Self = sync.OnceValue(func() string { + b := make([]byte, 8) + rand.Read(b) + return hex.EncodeToString(b) +}) + +// loops reports whether a model another magpie lists by way of via leaves +// this magpie and comes back to it. +func loops(via []string) bool { + if len(via) > MaxVia { + return true + } + self := Self() + return slices.Contains(via, self) && slices.ContainsFunc(via, func(v string) bool { return v != self }) +} + +// ViaHere is the magpie_via a model goes out with in this magpie's list +// to another: the way it came here by, when it came from another magpie, +// then this one. +func ViaHere(came []string) []string { + return append(slices.Clip(came), Self()) +} diff --git a/internal/catalog/magpie_via_test.go b/internal/catalog/magpie_via_test.go new file mode 100644 index 000000000..d23e2e4d0 --- /dev/null +++ b/internal/catalog/magpie_via_test.go @@ -0,0 +1,64 @@ +package catalog + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "slices" + "strings" + "testing" +) + +// Two magpies that are each other's remote (cdredfox on Discord) list +// each other's models back: a model that left this magpie through the +// other, and comes back, is not taken again, so neither list grows a +// level on every fetch. One only through others is kept, with the magpies +// it passes, and so is one through this magpie alone: a remote that is +// this magpie itself. +func TestFetchLeavesOutWhatCameFromHere(t *testing.T) { + self := Self() + long := make([]string, MaxVia+1) + for i := range long { + long[i] = fmt.Sprintf("p%d", i) + } + q := func(via []string) string { + s := make([]string, len(via)) + for i, v := range via { + s[i] = `"` + v + `"` + } + return "[" + strings.Join(s, ",") + "]" + } + srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + fmt.Fprintf(rw, `{"object":"list","data":[ + {"id":"up/m1","magpie_via":["peer"]}, + {"id":"back/own/m1","magpie_via":%s}, + {"id":"own/m2","magpie_via":%s}, + {"id":"far/m3","magpie_via":%s}, + {"id":"old/m4"}]}`, q([]string{self, "peer"}), q([]string{self}), q(long)) + })) + defer srv.Close() + ms, _, err := FetchAt(context.Background(), srv.URL+"/v1", "k", false, nil) + if err != nil { + t.Fatal(err) + } + got := map[string][]string{} + for _, m := range ms { + got[m.ID] = m.Via + } + if _, ok := got["back/own/m1"]; ok { + t.Errorf("a model that went out of this magpie and came back was taken: %v", got) + } + if _, ok := got["far/m3"]; ok { + t.Errorf("a model through more than %d magpies was taken: %v", MaxVia, got) + } + if v, ok := got["up/m1"]; !ok || !slices.Equal(v, []string{"peer"}) { + t.Errorf("up/m1 = %v, %v; want kept through [peer]", v, ok) + } + if v, ok := got["own/m2"]; !ok || !slices.Equal(v, []string{self}) { + t.Errorf("own/m2 = %v, %v; want kept through this magpie", v, ok) + } + if v, ok := got["old/m4"]; !ok || v != nil { + t.Errorf("an older magpie's model = %v, %v; want kept, through nothing said", v, ok) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index ff28b0e26..0a1b385e0 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1428,7 +1428,8 @@ func drawerObjects(r *http.Request) []map[string]any { name := cmp.Or(m.Name, m.ID) o := map[string]any{"id": p.ID + "/" + m.ID, "object": "model", "type": "model", "kind": "image", "created": 0, "owned_by": p.ID, "display_name": name, "magpie_label": name + " · " + p.Name, - "modalities": map[string]any{"input": []string{"text"}, "output": []string{"image"}}} + "modalities": map[string]any{"input": []string{"text"}, "output": []string{"image"}}, + "magpie_via": catalog.ViaHere(m.Via)} if m.Images { o["modalities"] = map[string]any{"input": []string{"text", "image"}, "output": []string{"image"}} } @@ -1456,12 +1457,35 @@ func videomakerObjects(r *http.Request) []map[string]any { name := cmp.Or(m.Name, m.ID) out = append(out, map[string]any{"id": p.ID + "/" + m.ID, "object": "model", "type": "model", "kind": "video", "created": 0, "owned_by": p.ID, "display_name": name, "magpie_label": name + " · " + p.Name, - "modalities": map[string]any{"input": []string{"text", "image"}, "output": []string{"video"}}}) + "modalities": map[string]any{"input": []string{"text", "image"}, "output": []string{"video"}}, + "magpie_via": catalog.ViaHere(m.Via)}) } } return out } +// viaOf is the magpies e's model passes through after this one, as the +// remote magpie serving it listed them; nil for a provider's own model. +// A routing group's are its members' together: a group with a remote +// magpie's group in it (two magpies each the other's remote, each with an +// auto/ group of the model) reaches every magpie that one does (catalog's +// magpie_via.go). +func viaOf(e provider.Entry) []string { + if e.Group == "" { + return e.Provider.RemoteVia(e.Model) + } + _, ms, _ := provider.FindGroup(e.ID) + var via []string + for _, m := range ms { + for _, v := range m.Provider.RemoteVia(m.Model) { + if !slices.Contains(via, v) { + via = append(via, v) + } + } + } + return via +} + // catalogFor is the catalog as the agent asking is shown it. func catalogFor(r *http.Request) []provider.Entry { shown, _ := provider.CatalogFor(agentOf(r)) @@ -1567,6 +1591,10 @@ func (s *Server) models(w http.ResponseWriter, r *http.Request) { if how := webSearchOf(e, searches); how != "" { m["web_search"] = how } + // the magpies it goes through, this one last, so a + // magpie that is this one's remote too doesn't take + // back its own models (catalog's magpie_via.go) + m["magpie_via"] = catalog.ViaHere(viaOf(e)) } if ts := tiers[e.ID]; len(ts) > 0 { m["service_tiers"] = ts @@ -1610,6 +1638,7 @@ func (s *Server) models(w http.ResponseWriter, r *http.Request) { m := modelObject(e) m["kind"], m["magpie_label"] = "decision", labels[i] m["native_endpoints"] = []string{"/v1/systemone"} + m["magpie_via"] = catalog.ViaHere(viaOf(e)) data = append(data, m) } } diff --git a/internal/gateway/remote_magpie_via_test.go b/internal/gateway/remote_magpie_via_test.go new file mode 100644 index 000000000..f56be082c --- /dev/null +++ b/internal/gateway/remote_magpie_via_test.go @@ -0,0 +1,101 @@ +package gateway + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// Two magpies each the other's remote (cdredfox on Discord, 100-200% CPU +// until the remote was off) listed each other's models back, one level +// more on every 10-minute fetch, without end: rem/back/own/m1, then +// rem/back/rem/back/own/m1, each another member of the found auto/ group +// and another trip round the two, masked again on each. The list magpie +// gives another magpie now says which magpies each model passes, this one +// last, a routing group the magpies its members pass, and a model of a +// remote that went out of here comes back no more. +func TestRemoteMagpieListLoopsNoMore(t *testing.T) { + self := catalog.Self() + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, `{"object":"list","data":[]}`) + })) + t.Cleanup(up.Close) + // the other magpie: what it serves of its own, and this magpie's own + // m1, which it has through this one as its remote + peer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"object":"list","data":[ + {"id":"up/m1","object":"model","magpie_via":["peer"]}, + {"id":"back/own/m1","object":"model","magpie_via":["`+self+`","peer"]}]}`) + })) + t.Cleanup(peer.Close) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + if err := provider.Save(provider.Provider{ID: "own", Name: "Own", Key: "k", Models: []string{"m1"}, Chat: up.URL + "/v1"}); err != nil { + t.Fatal(err) + } + if err := catalog.SaveLive("own", up.URL+"/v1", []catalog.Model{{ID: "m1"}}); err != nil { + t.Fatal(err) + } + id, err := provider.Add(provider.Provider{ID: "rem", Name: "Rem", Preset: provider.RemoteMagpiePreset, Chat: strings.TrimPrefix(peer.URL, "http://")}) + if err != nil { + t.Fatal(err) + } + rem, _ := provider.Find(id) + ms, err := rem.Fetch(context.Background()) + if err != nil { + t.Fatal(err) + } + var ids []string + for _, m := range ms { + ids = append(ids, m.ID) + } + if slices.Contains(ids, "back/own/m1") || !slices.Contains(ids, "up/m1") { + t.Fatalf("the remote's list taken = %v; want up/m1 and not this magpie's own model back", ids) + } + + srv := httptest.NewServer(New().Handler()) + t.Cleanup(srv.Close) + req, _ := http.NewRequest(http.MethodGet, srv.URL+"/v1/models", nil) + req.Header.Set(provider.DrawersHeader, "1") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + var list struct { + Data []struct { + ID string `json:"id"` + Via []string `json:"magpie_via"` + } `json:"data"` + } + if err := json.NewDecoder(resp.Body).Decode(&list); err != nil { + t.Fatal(err) + } + via := map[string][]string{} + for _, m := range list.Data { + via[m.ID] = m.Via + } + if v, ok := via["own/m1"]; !ok || !slices.Equal(v, []string{self}) { + t.Errorf("own/m1 is listed through %v, %v; want this magpie (%s) alone; list %v", v, ok, self, via) + } + if v, ok := via["rem/up/m1"]; !ok || !slices.Equal(v, []string{"peer", self}) { + t.Errorf("rem/up/m1 is listed through %v, %v; want [peer %s]; list %v", v, ok, self, via) + } + // the auto/ group of m1 here has the remote's m1 in it, so it reaches + // the other magpie too: listed back to it, it is left out there + if v, ok := via["auto/m1"]; !ok || !slices.Equal(v, []string{"peer", self}) { + t.Errorf("auto/m1 is listed through %v, %v; want [peer %s], its members' magpies and this one; list %v", v, ok, self, via) + } + if _, ok := via["rem/back/own/m1"]; ok { + t.Errorf("this magpie's own model came back through the remote: %v", via) + } +} diff --git a/internal/provider/remote_magpie.go b/internal/provider/remote_magpie.go index 255d4255e..19aeaedbe 100644 --- a/internal/provider/remote_magpie.go +++ b/internal/provider/remote_magpie.go @@ -183,3 +183,18 @@ func (p Provider) RemotePriced(model string) bool { _, ok := p.remotePrice(model) return ok } + +// RemoteVia is the magpies a remote magpie's model passes through to its +// vendor, as its list said, that magpie last (catalog's magpie_via.go); +// nil for another provider's, or a list from a magpie from before. +func (p Provider) RemoteVia(model string) []string { + if !p.IsRemoteMagpie() { + return nil + } + for _, m := range p.liveByID(model) { + if len(m.Via) > 0 { + return m.Via + } + } + return nil +}