Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
providers: a vendor's keys saved a provider each are one provider with those keys
yetone5b4dec58e47d
diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.mdindex 659fb9b0f..4d80bd13b 100644--- a/docs/subsystems/providers-accounts.md+++ b/docs/subsystems/providers-accounts.md@@ -29,6 +29,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi| Model picks | `Models` are the models the user picked for agents; none means the vendor's list, up to 24 (`Exposed`), unless the user chose Select none (`NoModels`, `magpie provider models <id> none`): then none of its models is served, not to agents, not to any routing group (auto groups included), not by a `provider/model` id, not as a classifier, while its balance and usage are still read (`ServesNone`, #1818). The editor's serves control names it Usage only, beside Vendor's list and Picked only, and the card says "usage only" (#2068); Picked only from there picks the models the vendor's list serves, to unpick from. A file without `noModels` reads as before, and a pick clears it. `Save` keeps beside new picks the models listed then (`PickedFrom`, `listedWith`), and the same picks saved again keep it. When the picks held every model listed then, one the vendor lists since is served first beside them (`withNewlyListed`, `Picks`); one listed then and left unpicked stays out. Picks saved before `PickedFrom` was kept are taken to hold every model when they hold every one released up to the newest of them (models.dev's `release_date`), so a Claude account whose user picked them all is served Haiku 5.5 (wakaka). The editor and the TUI start from `Picks`, so a later Save keeps the new model. While some picks are set aside (the list is known to be short), a save with new picks keeps the models the earlier `PickedFrom` had beside those listed now, so a model the user saw and left unpicked isn't new when that list has it again; a list short of no pick is taken as it is. A pick a list fetched again stops listing (`Refetch`, `KeepListsFresh`, and a plugin's hourly `KeepPluginsListed`) leaves `Models` for `Delisted` (`dropGonePicks`), not served, and goes back among the picks when a later list has it (`relistPicks`): Our Free Model's plugin lists its account channels' models only once its service has read them after a restart, and its free pools only while they answer, so each magpie update had its user pick every model again (多喝热水 on Discord). Every save keeps `Delisted` but for what it picks again (`delistedWith`); Select none clears it. A provider whose every pick is in `Delisted` serves none of its models (`waitsForPicks`), not the vendor's list. `KeepPluginsListed` asks again after `relistSoon` (5 minutes) when a list left a pick out. `TestPluginPicksComeBackWithTheirList`, `TestEveryPickDelistedServesNone` and `TestRelayPicksComeBackWithTheirList` cover it. | [`models.go`](../../internal/provider/models.go), [`provider.go`](../../internal/provider/provider.go) || List schedule and rules | A provider of the user's own (not an account, a plugin's or a decision-only one) can set `RefreshEvery` (`magpie provider refresh-every <id> 6h`, or 1d, or off, at least 10m) and `AutoInclude` (`magpie provider auto-include <id> 'gpt-*' 're:claude-.*'`, or none; a glob with `*`, or `re:` matching the whole id, both in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter); a plain id is refused) (#2135). The gateway (`magpie serve` or the app) looks each minute and fetches a list once `Fetched` is that old, through the same `Refetch` as Fetch models (`KeepListsFresh`); a failed fetch waits `min(every, 15m)`. `RefetchTaking` adds to the picks a model the fetch newly lists that a rule matches (`takeMatching`), starting from what is served now (`Exposed`), so nothing served is taken away and a model the user unticks stays out (it is not new to the next fetch). Setting the rules takes the current list's matches. Every save that doesn't set them keeps them, the window's editor among them; the editor has no fields for them yet. A Remote magpie with no `RefreshEvery` is fetched every 10m (`RemoteMagpieEvery`, `RefreshSchedule`), so a model the other magpie lists later (ZCode's GLM-5.3-Trial once its plugin read the gift, 6igsteven on Discord) is served without Fetch models; `off` set on it is kept as `"off"` and asks it only when told (`TestRemoteMagpieListFollowsTheOtherMagpie`). | [`autolist.go`](../../internal/provider/autolist.go), [`models.go`](../../internal/provider/models.go), [`providers_cli.go`](../../internal/cli/providers_cli.go) || Keys | Several keys per provider. Requests go to the first key that is on; the gateway moves on when it is out or rate limited. `Key` stays the first, so other code reads it as before. A key can be made for one protocol (`KeyProtocol`). A key made for a protocol its provider has no URL for is skipped (`perKeyBarred`); when every key is, the provider is still tried whole on the URLs it has, and the candidate carries `noURL` so it isn't quiet: Routing's row (`Weighed.NoURL`) says "key set to {api} only, no {api} URL · sent on the others", and the editor's key row shows a "No {api} URL" chip (`keyLacksURL`; #1702, `TestKeyForAProtocolWithNoURLIsSaid`, `key-nourl.test.cjs`). A key's value can be replaced in place (`ReplaceKey`, #1869: a key rotated at the vendor): it keeps its name, place, protocol, weight and on or off, and what was set for it by its fingerprint (`AccountModels`, `AccountProxies`, `AccountConcurrency`) and the gateway keys held to it (`access.ReplaceAccount`) move to the new one; the GUI's `keys/replace` also lifts its rests (`UnrestAll`). Its past requests stay under the old fingerprint, by the same name. A provider may hold thousands of keys (@NetRozee on X: a thousand froze magpie). Nothing goes over its keys once for each key: `KeysOn` drops a repeat by a set, a row's rest keys come from `RestKeys` (whether several are on, found once), and whether each key serves a model from `Serving`, which reads the lists once and keeps each model's keys as a set until the lists are read anew (`keyLists`). `KeysListed` and `ListsRead` count them for the tests (`TestProviderInfoListsKeysOnce`, `TestPerKeyReadsListsOnce`). A provider's keys have their balances, plans and remote limits read `keyReadsAtOnce` (8) at a time (`keySlots`); other providers' beside them. The editor's per-key proxy lines fold as its Accounts list does (`proxyLines`, `provider-many-keys-proxy.test.cjs`). Asking a key's models (`fetchPerKey`) still goes one key after another. | [`keys.go`](../../internal/provider/keys.go) |+| A key a provider | One vendor's keys saved a provider each — an app that keeps an entry a key, as CC Switch does, imported (yuluo_yx on X: "NVIDIA #001" to "#600" at one address, "Mistral #0001"…) — are folded into one provider with those keys (`FoldCopies` at start-up, `foldAdded` after `ImportFromApps`): hundreds of copies listed every model hundreds of times in every agent's picker and found group, and 3,000 made `/api/state` 86 MB. At start-up only copies by name are folded: a base name and that name with a number after it (`copyBase`: " #12", or `freeName`'s " 2"), one at least numbered; an import folds what it added whatever their names. Either way they must be alike in all but their key (`foldShape`: the provider with its id, name, keys and on/off left out), what the settings say of their models (`modelPrefs`) and where they are named (`foldRefs`: Visible, the agents' picked, hidden and ordered models, the groups, the providers falling back to them), so one key shown to one agent and another to another stays apart. Not folded: a subscription's, a hidden one, one without a key, Vertex, one with a StepFun sign-in of its own. The first on, in the providers' order, takes the rest in; its name becomes the base and its key is named its old name. Each other is a key in order, named its name, off if it was off (all off: the provider is off, its keys on); its id goes in `Was`, so its calls count with the provider by their key (`ProviderKeyID` is the key's fingerprint, unchanged) and a model picked by the old id still reaches it. Group members, rules, weights and fallbacks naming them name the provider once; their per-model settings and fetched lists go; balance and window history kept by their id moves to their key's name (`foldHistories`). A providers.json that doesn't parse is left alone. It runs at every start and writes nothing when there is nothing to fold. `TestFoldCopies`, `TestFoldCopiesIntoOneOn`, `TestFoldCopiesUnreadable`, `TestImportFoldsAKeyAnEntry`. | [`fold.go`](../../internal/provider/fold.go), [`importapps.go`](../../internal/provider/importapps.go), [`main.go`](../../internal/cli/main.go) || A key's plan | A vendor whose plans take keys of their own (`PresetDef.KeyPlans`: zhipu, zai, stepfun, stepfun-cn, xiaomi, baidu-qianfan, tencent-cloud, huaweicloud, volcengine, siliconflow) lets each key say which of the preset's Regions it is for (`KeyAccount.Plan`, `Provider.KeyPlan` for the first; yckonnnn on X: a Volcengine pay-as-you-go key and an Agent Plan key in one provider). No plan, or the provider's own, is the provider's plan, as every key was before, and is stored as none (`SetKeyPlan`, the GUI's `keys/plan`). `WithKey` moves a key's copy to its plan's endpoints (`atKeyPlan`: chat, Responses, Anthropic, decide, key page, docs and catalog; a provider at a host of its own, a mirror or a test's fake vendor, keeps that host) and marks it a key's view (`keyView`), so nothing judges plans on it again. Only when the keys in use are on more than one plan (`PlansMixed`) does anything differ: the model list is each key's plan's (`fetch` goes to `fetchPerKey`; a plan with no list of its own, `planOnly`, is its preset list without a request, so Ark's Coding and Agent Plans ask nothing while pay as you go asks `/api/v3/models` with its own key); plan media (`planMedia`) are every plan's; each key serves its plan's models alone (`PlanServing`, read by the gateway's `perKeyBarred`; a model set for the key in `AccountModels` it serves); plan windows (`PlanQuotas`), Volcengine's and Tencent Cloud's access-key windows (`planViews`) and balances (`balance.go`) are read at each key's plan. Volcengine's keys carry nothing that says their plan, so none is guessed; Xiaomi's `tp-`, Tencent's `sk-tp-`, MiniMax's `sk-cp-` and Bailian's `sk-sp-` prefixes are documented in code but not used to set a plan. The editor's key row has a plan chip (`planPicker`, the app's own menu) while the provider has several keys or the key has a plan. Not done: a gateway key held to some keys of a mixed provider's video (`videoAsker`) may pick another key's plan; a mixed provider whose own plan has no balance source while a key's plan has is not read; StepFun's plan windows are a sign-in per site, unchanged. `TestKeyPlanEndpoints`, `TestKeyPlanServing`, `TestKeyPlanOldConfigsUnchanged`, `TestSetKeyPlan`, `TestKeyPlanModelList`, `TestKeyPlanViews`, `key-plan.test.cjs`. | [`key_plans.go`](../../internal/provider/key_plans.go), [`keys.go`](../../internal/provider/keys.go), [`models.go`](../../internal/provider/models.go) || Google Vertex AI | `google-vertex` (`VertexPreset`, `IsVertex`) is a provider of the user's own with no key. `Provider.Vertex` holds `project`, `location` (`global`, `us`, `eu` or a region; `global` when empty), `credentials` (a file; empty for Application Default Credentials) and `impersonate` (a service account's email). Save refuses a key given it, then normalizes them (`Normal`) and checks each (`check`); `normalize` clears the four URLs and any key put in `providers.json` by hand, which stands in for neither a token nor a project and leaves the provider as found savable, so the provider's one address is `vertexBase`, `https://<host>/v1/projects/<project>/locations/<location>`, its host following the location (`vertexHost`). It speaks Gemini alone (`Speaks`, `Base`). It is `Ready` once that address can be made, never from a key or an account; until then the app, `magpie providers` and the TUI say it needs a project, and `magpie provider <id>` says how to give it one. `hasEndpoint` counts it as a provider of the user's own, not a subscription's picks. An import link naming it is refused (`ParseImport`): its project and credentials are the user's own, which no link hands over. `Sign` refuses any other address and sets the bearer token before the user's `Headers`; `AuthHeaders` gives it no key header. Its models are its location's (`vertexModels`, in `planModels`): the preset has `NoList`, because Vertex AI has no list that says what a location serves. The lists are in the [reference](../reference.md#google-vertex-ai). | [`vertex.go`](../../internal/provider/vertex.go), [`provider.go`](../../internal/provider/provider.go), [`account.go`](../../internal/provider/account.go), [`rename.go`](../../internal/provider/rename.go), [`models.go`](../../internal/provider/models.go), [`importurl.go`](../../internal/provider/importurl.go) || Vertex AI tokens | `vertexCredentialsFile` finds the credentials as Google's libraries find Application Default Credentials: the provider's `credentials`, else the file `GOOGLE_APPLICATION_CREDENTIALS` names, else `application_default_credentials.json` in gcloud's folder (`CLOUDSDK_CONFIG`, else `~/.config/gcloud`, `%APPDATA%\gcloud` on Windows); a `~/` that starts any of them is the home. `mint` reads three kinds: `authorized_user` (a refresh-token grant), `service_account` (an RS256 JWT, RFC 7523: `signed`) and gcloud's `impersonated_service_account`, whose `source_credentials` are minted and traded at IAM Credentials, along its `delegates`, for the account its `service_account_impersonation_url` names (`impersonationURL`: the token never goes to that URL's host). With `impersonate` set, the token those give is traded at IAM Credentials' `generateAccessToken` for a `cloud-platform` token of that account's, as gcloud's `--impersonate-service-account` does (`impersonateFor`); the credentials' account needs `roles/iam.serviceAccountTokenCreator` on it, which the 403 names. `vertexTokens` keeps one token per file and impersonated account, in memory only; requests made together mint it once, and those that waited through a mint that failed are given its error rather than each minting in turn (`mints`, `failed`). A mint cut short because its own request was given up on fails none of them: the next one mints. It is minted again within `vertexRefreshLead` (5 minutes) of expiry, or when the file's size or modification time has changed (gcloud signed in again). One mint, every exchange included, gets `vertexMintWait` (30 seconds). The file is only read. | [`vertex.go`](../../internal/provider/vertex.go), [`signin.go`](../../internal/provider/signin.go) |@@ -263,6 +264,7 @@ go test -tags nogui ./internal/provider -run 'TestClaudeSwitchTakesTheAccountsPrgo test -tags nogui ./internal/plugin -run TestPluginSignInProxynode --test internal/gui/tests/signin-proxy.test.cjs internal/gui/tests/signin-close.test.cjsgo test -tags nogui ./internal/provider -run 'TestAccount|TestImport|TestCodex|TestGroup|TestQuota|TestLogin|TestSignIn|TestSeveralKeys|TestKeyProtocol|TestSetKeyWeight|TestReadSub2APIKeyLimits|TestSub2APIKeyLimitsOnItsCard|TestKeyAllowance|TestPlanKeyAllowance|TestPayAsYouGoKeyAskedSeldom|TestClaudeAccountToldRenewed|TestPluginAccountToldRenewed|TestAllowancesReadOnlyWhenAsked|TestAllowancesReadByThemselvesByDefault|TestKeyReadsOnlyWhenAsked|TestAtAddress|TestProviderAtAddress|TestAddressOf'+go test -tags nogui ./internal/provider -run 'TestFoldCopies|TestImportFoldsAKeyAnEntry'go test -tags nogui ./internal/provider ./internal/gateway ./internal/gui -run 'TestRestKeysIsRestKey|TestKeysOnDropsRepeats|TestServingReadsListsOnce|TestKeyReadsEightAtOnce|TestKeySlots|TestPerKeyReadsListsOnce|TestProviderInfoListsKeysOnce'node --test internal/gui/tests/provider-many-keys.test.cjs internal/gui/tests/provider-many-keys-proxy.test.cjsgo test -tags nogui ./internal/provider -run 'TestCapHeld|TestCapReached|TestWindowCapHeld|TestSetWindowCap'diff --git a/internal/cli/main.go b/internal/cli/main.goindex ddde18717..c5a18a686 100644--- a/internal/cli/main.go+++ b/internal/cli/main.go@@ -241,6 +241,11 @@ var startUp = func() {if _, err := pluginrt.Refresh(); err != nil {fmt.Fprintf(os.Stderr, "magpie: plugins.yml: %v\n", err)}+ // a vendor's keys saved a provider each ("NVIDIA #001"…) are one+ // provider with those keys, before anything lists them+ if _, err := provider.FoldCopies(); err != nil {+ fmt.Fprintf(os.Stderr, "magpie: providers.json: %v\n", err)+ }// the providers and settings read once for every agent's fields, which// the moves below look at (a write among them reads them again)release := provider.Hold()diff --git a/internal/provider/fold.go b/internal/provider/fold.gonew file mode 100644index 000000000..1b5347684--- /dev/null+++ b/internal/provider/fold.go@@ -0,0 +1,581 @@+package provider++// One vendor's keys, each saved as a provider of its own (yuluo_yx on X:+// "NVIDIA #001" to "NVIDIA #600" at integrate.api.nvidia.com, "Mistral+// #0001"… at api.mistral.ai, brought in from another app that keeps an+// entry per key) are one provider with that many keys: its Providers row+// is one row, its models are listed once in every agent's picker and in+// the routing groups magpie finds, and requests go over the keys as the+// provider's Routing says. Hundreds of copies made every agent's list+// hundreds of times as long: /api/state was 86 MB for 3,000 keys.+//+// Folded are only providers alike in everything but their key: the same+// address, models and settings, and what the user said of their models.+// The fold keeps what each one was: its id goes on the provider that took+// it in (Was), so its calls are counted with it, per key, and an agent+// still set to a model by the old id reaches it; its name is its key's+// name; one that was off is a key that is off; the keys follow the order+// the providers were in.++import (+ "bytes"+ "encoding/json"+ "errors"+ "os"+ "reflect"+ "regexp"+ "slices"+ "strconv"+ "strings"+ "time"++ "github.com/yetone/magpie/internal/catalog"+ "github.com/yetone/magpie/internal/settings"+)++// numbered is a name with a number after it that tells copies apart:+// "NVIDIA #595", "Mistral #0001", or "NVIDIA NIM 2" as freeName names a+// second one alike.+var (+ numberedHash = regexp.MustCompile(`^(.*\S)\s*#\s*\d+$`)+ numberedSpace = regexp.MustCompile(`^(.*\S) (\d+)$`)+)++// copyBase is the name a numbered copy is a copy of, and whether name is+// numbered at all.+func copyBase(name string) (string, bool) {+ name = strings.TrimSpace(name)+ if m := numberedHash.FindStringSubmatch(name); m != nil {+ return m[1], true+ }+ if m := numberedSpace.FindStringSubmatch(name); m != nil {+ if n, err := strconv.Atoi(m[2]); err == nil && n >= 2 {+ return m[1], true+ }+ }+ return name, false+}++// foldable is whether p can be folded with another: a provider of a key+// at an address of the user's, not a subscription's, a hidden one or one+// with a StepFun sign-in of its own (kept by its id).+func foldable(p Provider, stepfun map[string]stepfunSession) bool {+ if p.Account != nil || p.Hidden || p.Key == "" || !hasEndpoint(p) || p.IsVertex() {+ return false+ }+ if slices.Contains(accountIDs, p.ID) || subscriptionID(p.ID) || p.ID == "magpie" {+ return false+ }+ _, signed := stepfun[p.ID]+ return !signed+}++// foldShape is p as providers.json has it with what tells one key's copy+// from another's left out: its id, name, keys and whether it is on. Two+// providers fold only when their shapes and their model settings (prefs)+// are the same.+func foldShape(p Provider, prefs string) string {+ p.ID, p.Name, p.Was, p.Gave = "", "", nil, nil+ p.Key, p.KeyName, p.Keys, p.KeyProtocol, p.KeyWeight, p.KeyPlan = "", "", nil, "", 0, ""+ p.Off = false+ b, err := json.Marshal(p)+ if err != nil {+ return ""+ }+ return string(b) + "\x00" + prefs+}++// modelPrefs is what the user said of id's models, in every per-model map+// of the settings, by the model's id without the provider's: two copies+// alike have the same.+func modelPrefs(s *settings.Settings, id string) string {+ var out []string+ settings.PerModelKeys(s, func(name string, m reflect.Value) {+ if !m.IsValid() || m.Kind() != reflect.Map {+ return+ }+ for _, k := range m.MapKeys() {+ rest, ok := strings.CutPrefix(k.String(), id+"/")+ if !ok {+ continue+ }+ v, _ := json.Marshal(m.MapIndex(k).Interface())+ out = append(out, name+"\x01"+rest+"\x01"+string(v))+ }+ })+ slices.Sort(out)+ return strings.Join(out, "\x02")+}++// foldRefs is, by provider id, where the providers' list and the settings+// name it, each place with the model it names there and without the id:+// the agents shown it (Visible), the models picked, hidden or ordered for+// an agent, the groups' members and what they say of them, and the+// providers that fall back to it. Two copies named in different places+// are told apart by the user — one key for this agent, another for that —+// and are not folded; named in the same, they fold, and each place names+// the one they went into once.+func foldRefs(f file, s *settings.Settings) map[string][]string {+ out := map[string][]string{}+ note := func(where, ref string) {+ r := strings.TrimPrefix(ref, "magpie/")+ id, model, ok := strings.Cut(r, "/")+ if !ok {+ id, model = r, ""+ }+ if id == "" || id == "group" {+ return+ }+ out[id] = append(out[id], where+"\x01"+model)+ }+ for a, names := range s.Visible {+ for _, n := range names {+ note("visible\x01"+a, n)+ }+ }+ lists := map[string]map[string][]string{"hidden": s.HiddenModels, "picked": s.PickedModels, "ordered": s.OrderedModels, "fast": s.FastPicks, "ultra": s.UltraPicks}+ for name, l := range lists {+ for a, ids := range l {+ for _, id := range ids {+ note(name+"\x01"+a, id)+ }+ }+ }+ for _, g := range f.Groups {+ at := "group\x01" + g.ID + "\x01"+ for _, m := range g.Members {+ note(at+"member", m)+ }+ for _, m := range g.Fast {+ note(at+"fast", m)+ }+ for _, m := range g.Off {+ note(at+"off", m)+ }+ for m, w := range g.Weights {+ note(at+"weight"+strconv.Itoa(w), m)+ }+ if g.Pick != "" {+ note(at+"pick", g.Pick)+ }+ if g.Classifier != "" {+ note(at+"classifier", g.Classifier)+ }+ for i := range g.Rules {+ r := g.Rules[i]+ r.MapUses(func(u string) string { note(at+"rule"+strconv.Itoa(i), u); return u })+ }+ }+ for _, p := range f.Providers {+ for _, fb := range p.Fallback {+ note("fallback\x01"+p.ID, fb)+ }+ }+ for id := range out {+ slices.Sort(out[id])+ }+ return out+}++// FoldCopies folds the providers that are copies of one, a key each+// (see above), as providers.json has them now. Run at start-up, so a+// user who has them already (from an import before this) finds them+// folded. It answers how many providers were folded into others. A+// providers.json that can't be read is left alone.+func FoldCopies() (int, error) {+ return foldWhere(func(ps []Provider) [][]int { return copiesByName(ps) })+}++// foldAdded folds the providers with ids among added that are alike but+// for their keys, whatever their names: what one import brought in at+// once, an entry a key, as CC Switch keeps them.+func foldAdded(added []string) (int, error) {+ if len(added) < 2 {+ return 0, nil+ }+ in := map[string]bool{}+ for _, id := range added {+ in[id] = true+ }+ return foldWhere(func(ps []Provider) [][]int {+ var at []int+ for i, p := range ps {+ if in[p.ID] {+ at = append(at, i)+ }+ }+ return [][]int{at}+ })+}++// copiesByName is the providers of ps that may be copies of one another,+// by the name they are copies of: those whose name is the same but for a+// number after it, one at least numbered.+func copiesByName(ps []Provider) [][]int {+ byBase := map[string][]int{}+ numbered := map[string]bool{}+ var bases []string+ for i, p := range ps {+ base, num := copyBase(p.Name)+ k := strings.ToLower(base)+ if _, ok := byBase[k]; !ok {+ bases = append(bases, k)+ }+ byBase[k] = append(byBase[k], i)+ numbered[k] = numbered[k] || num+ }+ var out [][]int+ for _, k := range bases {+ if numbered[k] && len(byBase[k]) > 1 {+ out = append(out, byBase[k])+ }+ }+ return out+}++// foldWhere folds, among each set of providers candidates names (indexes+// into providers.json's list in the order the user put them), those alike+// but for their keys into the first of them that is on.+func foldWhere(candidates func([]Provider) [][]int) (int, error) {+ // read from its last good generation, the file is the user's to mend:+ // a fold would write that generation over it+ if b, err := os.ReadFile(Path()); err == nil && !validProviders(b) {+ return 0, &unreadableError{Path(), errors.New("it doesn't parse")}+ }+ f, err := read()+ if err != nil {+ return 0, err+ }+ if len(f.Providers) < 2 {+ return 0, nil+ }+ ps := ordered(slices.Clone(f.Providers), f.Order)+ stepfunMu.Lock()+ stepfun := loadStepFun()+ stepfunMu.Unlock()+ s := settings.Load()+ refs := foldRefs(f, &s)++ // each set of copies alike, by its shape, in the order of ps+ var folds [][]int+ for _, set := range candidates(ps) {+ byShape := map[string][]int{}+ var shapes []string+ for _, i := range set {+ p := ps[i]+ if !foldable(p, stepfun) {+ continue+ }+ sh := foldShape(p, modelPrefs(&s, p.ID)+"\x00"+strings.Join(refs[p.ID], "\x02"))+ if sh == "" {+ continue+ }+ if _, ok := byShape[sh]; !ok {+ shapes = append(shapes, sh)+ }+ byShape[sh] = append(byShape[sh], i)+ }+ for _, sh := range shapes {+ if len(byShape[sh]) > 1 {+ folds = append(folds, byShape[sh])+ }+ }+ }+ if len(folds) == 0 {+ return 0, nil+ }++ now := time.Now()+ gone := map[string]string{} // a folded provider's id → the one it went into+ into := map[string]Provider{}+ for _, set := range folds {+ p, ids := foldSet(ps, set)+ into[p.ID] = p+ for _, id := range ids {+ gone[id] = p.ID+ }+ }+ // providers.json's list as it was, the folded ones out and each that+ // took them in where it was+ kept := f.Providers[:0:0]+ for _, p := range f.Providers {+ if _, ok := gone[p.ID]; ok {+ continue+ }+ if q, ok := into[p.ID]; ok {+ p = q+ }+ kept = append(kept, p)+ }+ f.Providers = kept+ // a name another provider has already stays the copy's own+ names := map[string]int{}+ for _, p := range f.Providers {+ names[strings.ToLower(p.Name)]+++ }+ for j, p := range f.Providers {+ if _, ok := into[p.ID]; ok && names[strings.ToLower(p.Name)] > 1 && p.KeyName != "" {+ if i := slices.IndexFunc(ps, func(q Provider) bool { return q.ID == p.ID }); i >= 0 && ps[i].Name != p.Name {+ f.Providers[j].Name = ps[i].Name+ }+ }+ }+ // an id one of them gave away before is the one's that has it now+ for id := range gone {+ giveID(f.Providers, slices.IndexFunc(f.Providers, func(p Provider) bool { return p.ID == gone[id] }), id, now)+ }+ to := func(id string) string {+ if t, ok := gone[id]; ok {+ return t+ }+ return id+ }+ ref := func(m string) string { return foldedRef(m, to) }+ f.Order = compact(mapEach(f.Order, to))+ for j := range f.Providers {+ f.Providers[j].Fallback = compact(mapEach(f.Providers[j].Fallback, ref))+ }+ for j := range f.Groups {+ g := &f.Groups[j]+ g.Members = compact(mapEach(g.Members, ref))+ for k := range g.Rules {+ g.Rules[k].MapUses(ref)+ }+ g.Fast = compact(mapEach(g.Fast, ref))+ g.Off = compact(mapEach(g.Off, ref))+ g.Weights = renamedWeights(g.Weights, ref)+ g.Classifier = ref(g.Classifier)+ g.Pick = ref(g.Pick)+ }+ if err := store(f); err != nil {+ return 0, err+ }+ for id := range gone {+ // the list last fetched for it is the one it went into's+ _ = os.Remove(catalog.LivePath(id))+ _ = os.Remove(catalog.LivePath(decisionsID(id)))+ }+ foldSettings(&s, gone, ref)+ foldHistories(folds, ps)+ return len(gone), nil+}++// foldSet is the provider the copies ps[set…] fold into — the first of+// them that is on, or the first when none is — with every key of the+// others after its own in their order, and the ids of the others.+func foldSet(ps []Provider, set []int) (Provider, []string) {+ head := set[0]+ for _, i := range set {+ if !ps[i].Off {+ head = i+ break+ }+ }+ allOff := ps[head].Off+ p := ps[head].clone()+ // "NVIDIA #001"'s key is named so, and the provider is NVIDIA, when+ // every copy's name is NVIDIA's+ base, _ := copyBase(p.Name)+ same := base != ""+ for _, i := range set {+ b, _ := copyBase(ps[i].Name)+ same = same && strings.EqualFold(b, base)+ }+ if same && base != p.Name {+ if p.KeyName == "" {+ p.KeyName = p.Name+ }+ p.Name = base+ }+ have := map[string]bool{p.Key: true}+ for _, k := range p.Keys {+ have[k.Key] = true+ }+ var ids []string+ for _, i := range set {+ if i == head {+ continue+ }+ q := ps[i]+ ids = append(ids, q.ID)+ p.Was = append(p.Was, q.ID)+ p.Was = append(p.Was, q.Was...)+ p.Gave = append(p.Gave, q.Gave...)+ off := q.Off && !allOff+ first := KeyAccount{Name: cmpOr(q.KeyName, q.Name), Key: q.Key, Off: off, Protocol: q.KeyProtocol, Weight: q.KeyWeight, Plan: q.KeyPlan}+ for _, k := range append([]KeyAccount{first}, q.Keys...) {+ if k.Key == "" || have[k.Key] {+ continue+ }+ have[k.Key] = true+ k.Off = k.Off || off+ p.Keys = append(p.Keys, k)+ }+ }+ p.Was = compact(p.Was)+ return p, ids+}++func cmpOr(a, b string) string {+ if a != "" {+ return a+ }+ return b+}++// foldedRef is a model id ("provider/model", "magpie/provider/model")+// with its provider as to names it now.+func foldedRef(ref string, to func(string) string) string {+ pre, rest := "", ref+ if r, ok := strings.CutPrefix(ref, "magpie/"); ok {+ pre, rest = "magpie/", r+ }+ id, m, ok := strings.Cut(rest, "/")+ if !ok {+ return ref+ }+ if t := to(id); t != id {+ return pre + t + "/" + m+ }+ return ref+}++func mapEach(xs []string, f func(string) string) []string {+ if xs == nil {+ return nil+ }+ out := make([]string, len(xs))+ for i, x := range xs {+ out[i] = f(x)+ }+ return out+}++// compact is xs with each repeat after the first left out.+func compact(xs []string) []string {+ if len(xs) < 2 {+ return xs+ }+ seen := make(map[string]bool, len(xs))+ out := xs[:0:0]+ for _, x := range xs {+ if !seen[x] {+ seen[x] = true+ out = append(out, x)+ }+ }+ return out+}++// foldSettings moves what the settings say by a folded provider's id to+// the one it went into. Its per-model preferences were the same as that+// one's (foldShape), so they go; a picker's lists of models and an agent's+// providers name the one it went into, once.+func foldSettings(s *settings.Settings, gone map[string]string, ref func(string) string) {+ before, _ := json.Marshal(s)+ settings.PerModelKeys(s, func(_ string, m reflect.Value) {+ if !m.IsValid() || m.Kind() != reflect.Map {+ return+ }+ for _, k := range m.MapKeys() {+ id, _, ok := strings.Cut(k.String(), "/")+ if _, folded := gone[id]; ok && folded {+ m.SetMapIndex(k, reflect.Value{})+ }+ }+ })+ for _, lists := range []map[string][]string{s.HiddenModels, s.PickedModels, s.OrderedModels, s.FastPicks, s.UltraPicks} {+ for k, ids := range lists {+ lists[k] = compact(mapEach(ids, ref))+ }+ }+ for a, names := range s.Visible {+ s.Visible[a] = compact(mapEach(names, func(n string) string {+ if t, ok := gone[strings.ToLower(n)]; ok {+ return t+ }+ return ref(n)+ }))+ }+ if after, _ := json.Marshal(s); !bytes.Equal(before, after) {+ _ = settings.Save(*s)+ }+}++// foldHistories moves the balances and windows kept for each folded+// provider's key, kept by the provider's id while it had one key, to the+// key's name on the one it went into, where they are read now.+func foldHistories(folds [][]int, ps []Provider) {+ moves := map[string]string{} // a folded key's provider id → "into|key name"+ for _, set := range folds {+ p, _ := foldSet(ps, set)+ if src, ok := balanceSourceOf(p); ok && src.token != "" {+ // a balance asked with a token of the account's is the+ // provider's, kept by its id alone, whichever key asks+ continue+ }+ for _, i := range set {+ q := ps[i]+ name := cmpOr(q.KeyName, q.Name)+ if q.ID == p.ID {+ name = cmpOr(p.KeyName, Mask(p.Key))+ }+ moves[q.ID] = quotaHistKey(p.ID, name)+ }+ }+ // "id|" is a provider's with one key, "id||sign" one of its lines of a+ // balance in several currencies+ moved := func(k string) (string, bool) {+ id, rest, ok := strings.Cut(k, "|")+ if !ok {+ return "", false+ }+ user, sign, signed := strings.Cut(rest, "|")+ to, ok := moves[id]+ if !ok || user != "" {+ return "", false+ }+ if signed {+ return to + "|" + sign, true+ }+ return to, true+ }+ balanceHistMu.Lock()+ if _, err := os.Stat(balanceHistPath()); err == nil {+ h := readBalanceHist()+ changed := false+ for k, pts := range h {+ if to, ok := moved(k); ok {+ delete(h, k)+ h[to] = append(h[to], pts...)+ changed = true+ }+ }+ if changed {+ writeBalanceHist(h)+ }+ }+ balanceHistMu.Unlock()+ quotaHistMu.Lock()+ if _, err := os.Stat(quotaHistPath()); err == nil {+ h := readQuotaHist()+ changed := false+ for k, lines := range h {+ if to, ok := moved(k); ok {+ delete(h, k)+ if h[to] == nil {+ h[to] = lines+ } else {+ for w, pts := range lines {+ h[to][w] = append(h[to][w], pts...)+ }+ }+ changed = true+ }+ }+ if changed {+ writeQuotaHist(h)+ }+ }+ quotaHistMu.Unlock()+}diff --git a/internal/provider/fold_test.go b/internal/provider/fold_test.gonew file mode 100644index 000000000..0ce9db7bf--- /dev/null+++ b/internal/provider/fold_test.go@@ -0,0 +1,187 @@+package provider++import (+ "os"+ "path/filepath"+ "slices"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/settings"+)++func foldHome(t *testing.T) string {+ t.Helper()+ isolate(t)+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)+ t.Setenv("APPDATA", filepath.Join(home, "AppData", "Roaming"))+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))+ t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))+ t.Setenv("XDG_DATA_HOME", filepath.Join(home, ".local", "share"))+ return home+}++// nvidiaCopy is one of yuluo_yx's "NVIDIA #NNN": NVIDIA's preset with a+// key of its own, saved a provider each.+func nvidiaCopy(id, name, key string) Provider {+ return Provider{ID: id, Name: name, Key: key, Preset: "nvidia", Icon: "nvidia-color", Catalog: "nvidia",+ Chat: "https://integrate.api.nvidia.com/v1", Models: []string{"z-ai/glm-5.3", "deepseek-ai/deepseek-v4"}}+}++func saveAll(t *testing.T, ps ...Provider) {+ t.Helper()+ for _, p := range ps {+ if err := Save(p); err != nil {+ t.Fatal(err)+ }+ }+}++func TestFoldCopies(t *testing.T) {+ foldHome(t)+ two := nvidiaCopy("nvidia-2", "NVIDIA #002", "nvapi-2")+ two.Off = true+ other := nvidiaCopy("nvidia-4", "NVIDIA #004", "nvapi-4")+ other.Models = []string{"z-ai/glm-5.3"} // a list of its own: kept apart+ shown := nvidiaCopy("nvidia-5", "NVIDIA #005", "nvapi-5")+ saveAll(t, nvidiaCopy("nvidia", "NVIDIA #001", "nvapi-1"), two, nvidiaCopy("nvidia-3", "NVIDIA #003", "nvapi-3"), other, shown,+ // named by the user, alike but for the key: not copies+ Provider{ID: "relay", Name: "Home relay", Key: "a", Chat: "https://relay.example.com/v1", Models: []string{"m"}},+ Provider{ID: "relay-2", Name: "Work relay", Key: "b", Chat: "https://relay.example.com/v1", Models: []string{"m"}},+ Provider{ID: "mistral", Name: "Mistral #0001", Key: "m1", Chat: "https://api.mistral.ai/v1", Models: []string{"mistral-large"}},+ Provider{ID: "mistral-2", Name: "Mistral #0002", Key: "m2", Chat: "https://api.mistral.ai/v1", Models: []string{"mistral-large"}},+ )+ if err := SaveGroup(Group{ID: "top", Name: "Top", Members: []string{"nvidia/z-ai/glm-5.3", "nvidia-2/z-ai/glm-5.3", "nvidia-3/z-ai/glm-5.3", "nvidia-4/z-ai/glm-5.3"},+ Weights: map[string]int{"nvidia/z-ai/glm-5.3": 3, "nvidia-2/z-ai/glm-5.3": 3, "nvidia-3/z-ai/glm-5.3": 3}}); err != nil {+ t.Fatal(err)+ }+ s := settings.Load()+ // one copy shown to Codex alone is told apart by the user+ s.Visible = map[string][]string{"codex": {"nvidia-5"}}+ s.ModelNames = map[string]string{"nvidia/z-ai/glm-5.3": "GLM", "nvidia-2/z-ai/glm-5.3": "GLM", "nvidia-3/z-ai/glm-5.3": "GLM",+ "nvidia-4/z-ai/glm-5.3": "GLM", "nvidia-5/z-ai/glm-5.3": "GLM"}+ if err := settings.Save(s); err != nil {+ t.Fatal(err)+ }+ balanceHistMu.Lock()+ writeBalanceHist(balanceHist{"nvidia-2|": {{At: time.Now(), Amount: 5}}, "nvidia|": {{At: time.Now(), Amount: 7}}})+ balanceHistMu.Unlock()++ n, err := FoldCopies()+ if err != nil || n != 3 {+ t.Fatalf("folded %d: %v", n, err)+ }+ ps := load().Providers+ var ids []string+ for _, p := range ps {+ ids = append(ids, p.ID)+ }+ if !slices.Equal(ids, []string{"nvidia", "nvidia-4", "nvidia-5", "relay", "relay-2", "mistral"}) {+ t.Fatalf("providers %v", ids)+ }+ p, _ := Find("nvidia")+ if p.Name != "NVIDIA" || p.KeyName != "NVIDIA #001" || p.Key != "nvapi-1" || p.Off {+ t.Fatalf("folded into %+v", p)+ }+ want := []KeyAccount{{Name: "NVIDIA #002", Key: "nvapi-2", Off: true}, {Name: "NVIDIA #003", Key: "nvapi-3"}}+ if !slices.Equal(p.Keys, want) {+ t.Fatalf("keys %+v", p.Keys)+ }+ // its calls are counted with the one it went into, by its key+ if r := UsageRenames(); r.Of("nvidia-2", time.Now()) != "nvidia" || r.Of("nvidia-3", time.Now()) != "nvidia" {+ t.Fatalf("usage of the folded: %q", r.Of("nvidia-2", time.Now()))+ }+ // an agent still set to the old id reaches it+ if q, m, ok := Resolve("nvidia-3/z-ai/glm-5.3"); !ok || q.ID != "nvidia" || m != "z-ai/glm-5.3" {+ t.Fatalf("resolve %v %q %v", q.ID, m, ok)+ }+ if m, _ := Find("mistral"); m.Name != "Mistral" || len(m.Keys) != 1 || m.Keys[0].Name != "Mistral #0002" {+ t.Fatalf("mistral %+v", m)+ }+ g, _, _ := FindGroup("group/top")+ if !slices.Equal(g.Members, []string{"nvidia/z-ai/glm-5.3", "nvidia-4/z-ai/glm-5.3"}) || g.Weights["nvidia/z-ai/glm-5.3"] != 3 || len(g.Weights) != 1 {+ t.Fatalf("group %+v %v", g.Members, g.Weights)+ }+ s = settings.Load()+ if _, ok := s.ModelNames["nvidia-2/z-ai/glm-5.3"]; ok || s.ModelNames["nvidia/z-ai/glm-5.3"] != "GLM" || s.ModelNames["nvidia-5/z-ai/glm-5.3"] != "GLM" {+ t.Fatalf("model names %v", s.ModelNames)+ }+ h := readBalanceHist()+ if len(h["nvidia|nvidia #002"]) != 1 || len(h["nvidia|nvidia #001"]) != 1 || h["nvidia-2|"] != nil {+ t.Fatalf("balance history %v", h)+ }++ // once is enough+ if n, err := FoldCopies(); n != 0 || err != nil {+ t.Fatalf("again: %d %v", n, err)+ }+}++// The first that is on takes the others in: off, the first is a key that+// is off, and the provider stays on.+func TestFoldCopiesIntoOneOn(t *testing.T) {+ foldHome(t)+ one := nvidiaCopy("nvidia", "NVIDIA #001", "nvapi-1")+ one.Off = true+ saveAll(t, one, nvidiaCopy("nvidia-2", "NVIDIA #002", "nvapi-2"))+ if n, err := FoldCopies(); n != 1 || err != nil {+ t.Fatalf("%d %v", n, err)+ }+ p, err := Find("nvidia-2")+ if err != nil || p.Off || p.Name != "NVIDIA" || !slices.Equal(p.Keys, []KeyAccount{{Name: "NVIDIA #001", Key: "nvapi-1", Off: true}}) {+ t.Fatalf("%+v %v", p, err)+ }+ if q, _ := Find("nvidia"); q.ID != "nvidia-2" {+ t.Fatalf("old id reaches %q", q.ID)+ }+}++// A providers.json that can't be read is never written over.+func TestFoldCopiesUnreadable(t *testing.T) {+ foldHome(t)+ saveAll(t, nvidiaCopy("nvidia", "NVIDIA #001", "nvapi-1"), nvidiaCopy("nvidia-2", "NVIDIA #002", "nvapi-2"))+ b, _ := os.ReadFile(Path())+ bad := append(slices.Clone(b[:len(b)/2]), '}')+ if err := os.WriteFile(Path(), bad, 0o600); err != nil {+ t.Fatal(err)+ }+ if n, err := FoldCopies(); n != 0 || err == nil {+ t.Fatalf("%d %v", n, err)+ }+ if got, _ := os.ReadFile(Path()); string(got) != string(bad) {+ t.Fatal("written over")+ }+}++// An app that keeps an entry a key (CC Switch) brings in one provider+// with those keys, whatever the entries are called.+func TestImportFoldsAKeyAnEntry(t *testing.T) {+ home := foldHome(t)+ sqliteFixture(t, filepath.Join(home, ".cc-switch", "cc-switch.db"),+ `CREATE TABLE providers (id TEXT, app_type TEXT, name TEXT, settings_config TEXT, website_url TEXT, category TEXT, created_at INTEGER, sort_index INTEGER, PRIMARY KEY (id, app_type))`,+ `INSERT INTO providers VALUES ('a','claude','Relay #1','{"env":{"ANTHROPIC_BASE_URL":"https://relay.example.com","ANTHROPIC_AUTH_TOKEN":"sk-a","ANTHROPIC_MODEL":"claude-sonnet-5"}}','','custom',1,0)`,+ `INSERT INTO providers VALUES ('b','claude','Relay #2','{"env":{"ANTHROPIC_BASE_URL":"https://relay.example.com","ANTHROPIC_AUTH_TOKEN":"sk-b","ANTHROPIC_MODEL":"claude-sonnet-5"}}','','custom',2,1)`,+ `INSERT INTO providers VALUES ('c','claude','spare','{"env":{"ANTHROPIC_BASE_URL":"https://relay.example.com","ANTHROPIC_AUTH_TOKEN":"sk-c","ANTHROPIC_MODEL":"claude-sonnet-5"}}','','custom',3,2)`,+ `INSERT INTO providers VALUES ('d','claude','Other','{"env":{"ANTHROPIC_BASE_URL":"https://other.example.com","ANTHROPIC_AUTH_TOKEN":"sk-d","ANTHROPIC_MODEL":"claude-sonnet-5"}}','','custom',4,3)`,+ )+ var picks []AppPick+ for _, r := range []string{"claude/a", "claude/b", "claude/c", "claude/d"} {+ picks = append(picks, AppPick{Source: "cc-switch", Ref: r})+ }+ if added, err := ImportFromApps(picks); err != nil || len(added) != 4 {+ t.Fatalf("%v %v", added, err)+ }+ ps := load().Providers+ if len(ps) != 2 {+ t.Fatalf("%d providers: %+v", len(ps), ps)+ }+ p := ps[0]+ if p.Key != "sk-a" || len(p.Keys) != 2 || p.Keys[0].Key != "sk-b" || p.Keys[0].Name != "Relay #2" || p.Keys[1].Key != "sk-c" || p.Keys[1].Name != "spare" {+ t.Fatalf("%+v", p)+ }+ if ps[1].Key != "sk-d" || len(ps[1].Keys) != 0 {+ t.Fatalf("other %+v", ps[1])+ }+}diff --git a/internal/provider/importapps.go b/internal/provider/importapps.goindex 7fbe2d319..4198c8485 100644--- a/internal/provider/importapps.go+++ b/internal/provider/importapps.go@@ -123,13 +123,21 @@ func importSources(asked bool) []AppSource {}// ImportFromApps adds what the user picked, reading the sources again so-// keys never pass through the window. It answers the names added.-func ImportFromApps(picks []AppPick) ([]string, error) {+// keys never pass through the window. It answers the names added. The+// providers it adds alike but for their keys — an app that keeps an entry+// a key, as CC Switch does, gives hundreds — are one provider with those+// keys (see foldAdded).+func ImportFromApps(picks []AppPick) (added []string, err error) {sources := map[string]AppSource{}for _, s := range ImportSources() {sources[s.ID] = s}- var added []string+ var ids []string+ defer func() {+ if _, ferr := foldAdded(ids); ferr != nil && err == nil {+ err = ferr+ }+ }()for _, pk := range picks {var it *AppImportfor i, x := range sources[pk.Source].Items {@@ -204,6 +212,7 @@ func ImportFromApps(picks []AppPick) ([]string, error) {if err := Save(p); err != nil {return added, errorf("%s: %v", p.Name, err)}+ ids = append(ids, p.ID)added = append(added, p.Name)}return added, nil