Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
providers: a key may be for another plan of its vendor, sent to that plan's endpoints
yetone6e6aba51c8d4
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex 5837fd6f6..ff245ca5a 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -151,6 +151,7 @@ recorded as a prediction failure (`noPrediction`).- The order of the steps a request's accounts go through, how much the accounts' own order (*Make first*) counts under each routing, and how often an allowance is read are described for users in [How magpie picks an account](../reference.md#how-magpie-picks-an-account). Smart compares renewals window by window, biggest first, each truncated to the hour (`weighRouted`), so the order decides only when every window falls in the same hour. A window's renewal is its reset, or, when what it has left runs out sooner or it has no reset, that moment (`Limit.RunsOut`, from `QuotaWindow.RunsOutAt`; `Allowance.Renewal`): the WorkBuddy plugin (0.1.14) sends it on its Credits window as the soonest end of a package with credits left (cdredfox on X). Only Smart reads it; Weekly pace, the 90%/98% tiers and rests go by the window's share and reset as before. A row on the Routing page says the share used (the fullest window's, `Allowance.For`) with when that same window renews (`Allowance.Fullest`, the trace's `usedRenews`), not the biggest window's: a Factory account 32% into its week and 16% into its month reads "32% used · renews in 3 days" while Smart still ranks it by its month (#1778). A route from before `usedRenews` says when only for an account of one window. Affinity keeps a conversation on an account at 90–97%: only `SpentShareOf` (98%, 100% In order) stops it (`affine`), while the 90% tier (`lowShare`) orders only conversations nobody has answered.- A turn's end is told to the app for the "Task done alert" notification (itieniu on X, `turndone.go`). The trace follows each agent session's turn (`turns`, keyed by agent and session): a request is of the turn unless it has a `Kind` or is a Claude Code subagent's (`agentTurnOf`), and its reply is scanned on the way to the agent for a tool call in any wire format (`toolScan`, a JSON value such as `"type":"tool_use"` or `"finish_reason":"tool_calls"`, never a key or text). The turn is done when no request of it is going, the last reply was whole, under 400 and called no tool, and nothing more came for `turnQuiet` (4s); a session idle past `turnStale` (30m) starts over. Only a turn that ran at least `settings.TurnDoneAlert` seconds is told (`TurnDone`, set by the GUI; nil under `magpie serve`, so nothing is followed). The ChatGPT backend path (`codexBackend`) is followed the same way. `TestTurnDoneSaidAtTheTurnsEnd`, `TestTurnDoneCodexBackend`, `TestToolScan`, `turn-done.test.cjs`.- A resting candidate is tried last (`restLast`). Of the resting candidates, a request asks only the one whose rest ends soonest, the first in order on a tie (`probeOne`, #1799). The others aren't asked by that request, so a member that is down isn't asked by every request its rest was meant to spare it from, and a group that is down whole takes one upstream request per request, not one per member. Every ready candidate is still asked in its order. A lone candidate is tried even while it rests, because there is no other. The trace still lists every member, the resting ones with their rest. Only rests are read, and a failure about the request's content or its model rests no member (a model refusal rests only `restID`), so neither leaves a member out. The same applies in `count_tokens`, embeddings and rerank, image accounts and a group's System One decision models. A Codex reset (`autoReset`) still looks over every candidate. This is like AxonHub's error-aware load balancing: the rest and its backoff are the penalty that decays, and the member back soonest is the one asked to show it is back. Keys out of their allowance aren't asked even so, not even the one back soonest or a lone one (#1772: four Ollama Cloud keys out for the week, each asked again and refused on every request). The refusal given again says when they are asked again on this magpie's clock with its offset (`heldClock`: "20:12 UTC+8", "Oct 16 09:00 UTC+8"), as do the gateway's other held errors (a capped window, a spent searcher or describer): its reader may be a Remote magpie's user on another clock. When every candidate left is a key (not a subscription account, whose resets `autoReset` may spend) resting out of quota or credit after a 429 or 402, none is asked. The first one's refusal is given again (`quotaHeld`, its words kept in the rest's `said`), saying when it is asked again. A key whose rest magpie guessed the length of, the vendor and the user naming no time (`creditRest`, or `quotaRest` with no `Provider.OwnQuotaRest`), is held so only once it was refused so twice in a row (`Rest.first`): a single refusal may be a moment's, and the next request, the agent's retry first, asks it again (zoecats on Discord: a local aggregator said 429 `insufficient_quota` "quota exhausted" for the moment it switched upstreams, and every request was answered from its rest of 15 or 30 minutes, which only the provider's "Rests" switch, `LimitRestOff`, let through before). Held, it is asked again a minute on (`Rest.askAt`, `fallbackCooldown`), once, and held again if refused (`Rest.asksAt`); a time the vendor named, or the user set, holds it from the first refusal to then. The rest itself stays as long as before, so the order still passes it over for a candidate that is ready. The last key left rests too when it is refused so, as the keys before it do. Any 429 that reaches the agent without a vendor `Retry-After`, while every candidate tried is resting, carries one: the seconds until the first of them is asked again (`soonestBack`, by `asksAt`), none after a key's first refusal. `TestRetryAfterALimitIsAsked`, `TestHeldLimitAskedAgainInAMinute`. A quota refusal with no word of when it is back rests `quotaRest` (15 minutes), or the provider's own `quotaRest` in minutes (`Provider.QuotaRestFor`, at most `MaxQuotaRest`, 8 days; `magpie provider quota-rest <id> 7d`), or until the time of day the user said its allowance comes back (`QuotaResetAt`, `Provider.OwnQuotaRest`; `magpie provider quota-rest <id> until 08:00`, or `until 00:00+08:00` on the vendor's clock; #2008, a free tier's "today's free-model token quota"). Whichever of the two was set last counts. A time the vendor names stands over it, and so does its `Retry-After`, unless that was more than `longestWait` (an hour) and so cut to it while the user's own rest is longer: then the user's stands (`TestQuotaRestsUntilTheTimeOfDaySet`). A key listed in `keys` as well as in `key` is one candidate (`KeysOn`), not asked twice. `TestAllRestingAnswersFromRest`, `TestOwnQuotaRest`, `TestQuotaHeldOnlyForKeysOutOfAllowance`, `TestFirstKeyListedTwiceAskedOnce`.+- A provider whose keys are on different plans (`KeyAccount.Plan`, `PlansMixed`; yckonnnn on X) sends each key to its plan's endpoints: every key path takes its copy through `WithKey`, which moves it there (`atKeyPlan`), on the first try and on a failover alike. `perKeyBarred` leaves out a key whose plan's list lacks the model (`PlanServing`: a pay-as-you-go model id at the Agent Plan's endpoint only answers 404), not shown in the trace; only when no key's plan has it are those keys asked. Embeddings and drawing go through the same `perKeyBarred` and `WithKey`; a video started on a mixed provider names its key in the task id (`videoStart.onKey`, `keyMark`) so its poll goes to that key's plan. `TestKeyPlansEachToItsOwnEndpoint`.- A subscription's account whose own model list lacks the model (`Account.Lists`: an Antigravity account's `fetchAvailableModels`, a plugin account's `models`) isn't planned while another of its accounts lists it (`perKeyBarred`'s `left`, `planned.unlisted`, the Routing page's "unlisted, skipped"). It is the next asked when every account of the subscription that lists the model has been asked and one refused it as a model it doesn't serve (`unservedTry`: `modelRefused`, or Code Assist's 404 NOT_FOUND, `codeAssistModelMissing`), before any later member or fallback (`unlistedNext`, `askUnlisted` moves its row from the route's left to its order after the one that refused). A list is fetched once and can be stale: 01huadalang's Gemini 4 was served by one Antigravity account of several, and the one whose list named it refused it with a 404 the agent got while the other could answer. The one that refused rests for that model alone. Not for another refusal (a 403, a quota), a request pinned to an account, a native compaction sealed to one, or a conversation kept strictly on one; a gateway key held to some accounts narrows the unlisted ones too (`allowedCandidates`). `TestUnlistedAccountAskedAfterModelRefused`, `TestUnlistedAccountNotAskedForOtherRefusals`.- A member whose model is known to take less than the request isn't asked it (`roomy` in [`fallback.go`](../../internal/gateway/fallback.go), in `serve` after the rules, affinity, the image filter and `pinTo`, before `probeOne`; dgqyushen on Discord: OpenCode Zen's free DeepSeek V4.1 Flash, 200K, first in a group and a 1M subscription of it second). It is a check before sending, not a retry: the request's tokens are estimated as the overflow fall-over does (`estimate`, bytes/4 over text, tool arguments and schemas), and a candidate whose window (`windowOf`: the provider's `Contexts`, the catalog, `ContextOf`) is known and no larger is left out of the candidates and of the trace's order. Asked, such a member only refuses, and a refusal that doesn't say why, for a request short of `tooLongUnsaid`'s 1.2 margin, reached the agent as the vendor's error while the next member had room; it also spent a request against the member's limits. A conversation kept on a member by affinity moves once it outgrows it. Nothing is left out when its window isn't known, when the body doesn't parse, when only one model is among the candidates, or when no candidate holds the request: then the first is asked, and its overflow reaches the agent as one, to compact (`withRoom`, `failOverflow` and `tooLongUnsaid` stay for the window the estimate misses, which counts low on code and high on CJK text). A body shorter than four bytes per token of the least window isn't parsed. `count_tokens` (a count on the group's first member, not a send) and System One's decision models (short decision text) don't go through it. Those left out are the last resort: when the last candidate with room fails out of its allowance or credit (`failQuota`/`failCredit`), nothing before it having failed otherwise (`other`), and no account is pinned, the ones left out that aren't resting are asked after all, their rows added to the trace's order, and the one that failed rests as one before the last does. Its overflow tells the agent to compact, where the 429 only told it to wait for an allowance hours away (Kai on Discord: both Claude accounts spent until the next day, the Claude provider's Fallback a Codex model of 272K under a longer conversation, never asked). Another failure (a busy vendor, a bad key) still reaches the agent as it was, the small one not asked. The Routing page shows a member left out and not asked only by its absence from the route's order. `TestMemberTooSmallIsNotAsked`, `TestMemberTooSmallIsTheLastResort`, `TestClaudeAccountsSpentFallBackToCodex`, `TestConversationOutgrowingItsMemberMoves`, `TestRoomyLeavesWhatItCantJudge`.- Routing decides who goes first only when nobody has answered the conversation yet. Affinity keeps the answerer while its cache is worth it. Auto mode keeps it across turns while the last reply read from the cache and wrote to it at least `cacheWorth` (1024) tokens between them (the usage's `CacheRead` plus `CacheWrite`, passed to `answered`) and the cache isn't cold (`cacheCold`, 5 minutes). Past 5 minutes it stays while the vendor said it keeps at least `cacheWorth` tokens of the conversation for an hour (`hourCache`, #2302): a reply with Anthropic's 1-hour writes (`cache_creation.ephemeral_1h_input_tokens`, the usage's `CacheWrite1h`, as Claude Code asks of a subscription) keeps what it read plus those for `cacheHour`, a later reply on the same account and model that reads all of it starts the hour again, and one that reads less (moved, compacted) drops it. The stick keeps it on disk too (`cacheHour`, `cacheHourAt`), and a group's rules keep the turn's effort the same hour (`keepsEffort`). Vendors that report no 1-hour write are unchanged. `TestAffinityKeepsAnHourCachePastFiveMinutes`, `TestHourCacheAfter`. What was written counts: a first turn reads nothing and writes the whole prompt (Anthropic's `cache_creation_input_tokens`), and the second turn stays to read it rather than moving as `no-cache` and building it again elsewhere (vilicvane on Discord). The stick keeps both, on disk too (`affinity.json`'s `cacheWrite`, absent in a file from before and read as 0, so such a stick is judged by its read alone), and the trace's `Affinity.CacheWrite` lets the Routing page say what was read and what was written. A vendor that keeps a prompt cached without reporting it (OpenAI's automatic prefix cache, Gemini) says neither of a turn that read none, so the prompt that turn was sent (the usage's `Input`) stands for the write and its second turn stays too; a reply that reports no usage at all counts as no cache, as before. `TestAffinityKeepsACacheJustWritten`, `TestAffinityKeepsACacheTheVendorKeptSilently`, `routing-affinity-cache-write.test.cjs`.diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.mdindex 0f5ad5faa..659fb9b0f 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'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) || Amazon Bedrock Mantle | `bedrock-mantle` ("Amazon Bedrock (Mantle)", @marktoown on X) is a vendor preset beside the runtime's `bedrock`, with the same Bedrock API key and seventeen regions of its own (`mantleRegions`: the `bedrock-mantle.{region}.api.aws` hosts that answered on 2026-10-16). Chat completions and Responses are at `/v1`, Messages at `/anthropic`; unlike the runtime it lists its models (`GET /v1/models`; `NoList` stays the runtime's alone). Its OpenAI APIs serve each model under one of two prefixes: OpenAI's closed GPTs and xAI's Grok under `/openai/v1`, the rest under `/v1` (`MantleBase`, used by the gateway and the provider test's `tinyBody`). `IsBedrockMantle` is the preset or a provider added at a Mantle host (`mantleHost`), and `IsBedrock` includes it, so every Bedrock rule holds there too: Claude on Messages alone, the key as `x-api-key` alone, `max_completion_tokens`, no metadata, no Priority. A provider added at a Mantle address is given the APIs it wasn't (`mantleEndpoints`, in `normalize`), and a chat or Responses URL given at `/openai/v1` is moved to `/v1`, where the list is. | [`presets.go`](../../internal/provider/presets.go), [`provider.go`](../../internal/provider/provider.go), [`test.go`](../../internal/provider/test.go) |diff --git a/internal/backup/backup.go b/internal/backup/backup.goindex e1b7ce633..4dc2353be 100644--- a/internal/backup/backup.go+++ b/internal/backup/backup.go@@ -247,7 +247,7 @@ func Collect(keys bool, app string) (Bundle, error) {func Secret(name string) bool { return provider.SecretHeader(name) }func withoutKeys(p provider.Provider) provider.Provider {- p.Key, p.KeyName, p.Keys, p.KeyProtocol, p.KeyWeight = "", "", nil, "", 0+ p.Key, p.KeyName, p.Keys, p.KeyProtocol, p.KeyWeight, p.KeyPlan = "", "", nil, "", 0, ""p.BalanceToken = ""p.AccessKeyID, p.SecretAccessKey = "", ""if len(p.Headers) > 0 {diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.goindex b39b5500f..e7acc505b 100644--- a/internal/gateway/fallback.go+++ b/internal/gateway/fallback.go@@ -239,7 +239,12 @@ func perKeyBarred(p provider.Provider, model string, from provider.Protocol) (ou}keys := p.KeysOn()serves := p.Serving(model) // the lists read once, not once a key (@NetRozee on X)- var unlisted []candidate+ // a key on a plan of its own whose models leave this one out+ // (KeyAccount.Plan): the Agent Plan's key is never sent the pay as+ // you go's deepseek-v4-1-flash-261017, while a key whose plan has it+ // can take it (yckonnnn on X)+ planHas := p.PlanServing(model)+ var unlisted, planless []candidatevar noURL provider.Protocolfor i, k := range keys {q := p.WithKey(k)@@ -257,6 +262,10 @@ func perKeyBarred(p provider.Provider, model string, from provider.Protocol) (oubarred = append(barred, candidate{p: q, model: model, rest: rest, rank: i})continue}+ if !planHas(k) {+ planless = append(planless, candidate{p: q, model: model, rest: rest, rank: i})+ continue+ }if !serves(k) {// the vendor lists the model to another key onlyunlisted = append(unlisted, candidate{p: q, model: model, rest: rest, rank: i})@@ -267,6 +276,13 @@ func perKeyBarred(p provider.Provider, model string, from provider.Protocol) (ouif len(out) == 0 {out, unlisted = unlisted, nil // no key lists it: try them all the same}+ if len(out) == 0 {+ // no key's plan has it as magpie knows the plans: a model the+ // vendor added since, tried on them all the same. Else a key+ // whose plan lacks it is never asked, not even after the others+ // refused it: its endpoint has no such model either+ out = planless+ }if len(out) == 0 && len(barred) > 0 {return nil, nil, nil, barred}diff --git a/internal/gateway/key_plans_test.go b/internal/gateway/key_plans_test.gonew file mode 100644index 000000000..af221e6ec--- /dev/null+++ b/internal/gateway/key_plans_test.go@@ -0,0 +1,112 @@+package gateway++import (+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/provider"+)++// yckonnnn on X: Volcengine's pay as you go and its Agent Plan, a key of+// each in one provider. Each key is taken only at its own plan's+// endpoints, so each request with it goes there: on the first try, on+// a failover to it, and for a model only its plan has.+func TestKeyPlansEachToItsOwnEndpoint(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_CACHE_HOME", t.TempDir())+ restingUntil.Lock()+ restingUntil.m, restingUntil.note = map[string]time.Time{}, map[string]Rest{}+ restingUntil.Unlock()+ routed.Lock()+ routed.failures = map[string]int{}+ routed.Unlock()+ home := map[string]string{"k-coding": "/api/coding/v3", "k-api": "/api/v3", "k-agent": "/api/plan/v3"}+ var mu sync.Mutex+ var seen []string+ limited := map[string]bool{}+ up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")+ w.Header().Set("Content-Type", "application/json")+ if strings.HasSuffix(r.URL.Path, "/models") {+ io.WriteString(w, `{"data":[{"id":"kimi-k3"},{"id":"deepseek-v3-250324"}]}`)+ return+ }+ var req struct {+ Model string `json:"model"`+ }+ json.NewDecoder(r.Body).Decode(&req)+ mu.Lock()+ seen = append(seen, key+" "+strings.TrimSuffix(r.URL.Path, "/chat/completions")+" "+req.Model)+ lim := limited[key]+ mu.Unlock()+ // Ark answers a key at another plan's endpoint as unknown+ if strings.TrimSuffix(r.URL.Path, "/chat/completions") != home[key] {+ w.WriteHeader(401)+ io.WriteString(w, `{"error":{"code":"AuthenticationError","message":"the API key is invalid"}}`)+ return+ }+ if lim {+ w.WriteHeader(429)+ io.WriteString(w, `{"error":{"message":"rate limited"}}`)+ return+ }+ io.WriteString(w, `{"id":"from-`+key+`","choices":[]}`)+ }))+ defer up.Close()+ p := provider.Provider{ID: "volc", Name: "Volc", Preset: "volcengine",+ Chat: up.URL + "/api/coding/v3", Responses: up.URL + "/api/coding/v3", Anthropic: up.URL + "/api/coding",+ Models: []string{"kimi-k3", "deepseek-v3-250324"},+ Key: "k-coding", KeyName: "Coding",+ Keys: []provider.KeyAccount{{Name: "API", Key: "k-api", Plan: "api"}, {Name: "Agent", Key: "k-agent", Plan: "agent"}}}+ if err := provider.Save(p); err != nil {+ t.Fatal(err)+ }+ s := New()+ send := func(model string) (int, string, []string) {+ mu.Lock()+ seen = nil+ mu.Unlock()+ rec := httptest.NewRecorder()+ body := `{"model":"volc/` + model + `","messages":[{"role":"user","content":"hi"}]}`+ s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(body)))+ mu.Lock()+ defer mu.Unlock()+ return rec.Code, rec.Body.String(), append([]string(nil), seen...)+ }+ // the plan's own key, at the plan's endpoint+ if code, body, tried := send("kimi-k3"); code != 200 || !strings.Contains(body, "from-k-coding") || strings.Join(tried, ",") != "k-coding /api/coding/v3 kimi-k3" {+ t.Fatalf("first: %d %s, tried %v", code, body, tried)+ }+ // a model pay as you go alone has: its key alone, at /api/v3+ if code, body, tried := send("deepseek-v3-250324"); code != 200 || !strings.Contains(body, "from-k-api") || strings.Join(tried, ",") != "k-api /api/v3 deepseek-v3-250324" {+ t.Fatalf("pay-as-you-go model: %d %s, tried %v", code, body, tried)+ }+ // failover: the Coding Plan key limited, the next key at its own endpoint+ mu.Lock()+ limited["k-coding"] = true+ mu.Unlock()+ if code, body, tried := send("kimi-k3"); code != 200 || !strings.Contains(body, "from-k-api") ||+ strings.Join(tried, ",") != "k-coding /api/coding/v3 kimi-k3,k-api /api/v3 kimi-k3" {+ t.Fatalf("failover: %d %s, tried %v", code, body, tried)+ }+ // and on to the Agent Plan's+ mu.Lock()+ limited["k-api"] = true+ mu.Unlock()+ code, body, tried := send("kimi-k3")+ if code != 200 || !strings.Contains(body, "from-k-agent") {+ t.Fatalf("second failover: %d %s, tried %v", code, body, tried)+ }+ for _, x := range tried {+ f := strings.Fields(x)+ if home[f[0]] != f[1] {+ t.Errorf("key %s sent to %s", f[0], f[1])+ }+ }+}diff --git a/internal/gateway/video.go b/internal/gateway/video.goindex d8fc823d2..827a753e9 100644--- a/internal/gateway/video.go+++ b/internal/gateway/video.go@@ -559,6 +559,14 @@ func videoMaker(id string) (p provider.Provider, vendorID string, started time.Tif ferr != nil || !drawsGrok(*found) && !found.IsRemoteMagpie() && len(found.PlanVideos()) == 0 {return p, "", started, fmt.Errorf("no provider %q makes videos here", pid)}+ if found.Account == nil && found.PlansMixed() {+ // asked on the key that started it, at its plan's endpoint+ q, ok := markedKey(*found, by)+ if !ok {+ return p, "", started, fmt.Errorf("this video was started with a key of %s that is no longer on: turn it back on to get the video", found.Name)+ }+ return q, vendorID, started, nil+ }if signer(*found) != by {return p, "", started, fmt.Errorf("this video was started with another %s account than the one signed in now: sign back in to it to get the video", found.Name)}@@ -787,7 +795,7 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) {fail(code, msg)return}- b, remote, custom, field := v.answer, v.remote, v.custom, v.field+ b, remote, custom, field, onKey := v.answer, v.remote, v.custom, v.field, v.onKeycall.Millis, call.Status = time.Since(start).Milliseconds(), codevar started map[string]anytheirs := ""@@ -824,7 +832,11 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) {writeJSON(w, 200, obj)return}- writeJSON(w, 200, videoObject(videoID(p, theirs, start), p.ID+"/"+model, start, videoState{}, f))+ id := videoID(p, theirs, start)+ if onKey {+ id = strings.TrimSuffix(id, "."+signer(p)) + "." + keyMark(p)+ }+ writeJSON(w, 200, videoObject(id, p.ID+"/"+model, start, videoState{}, f))}// videoStart is how starting a video on one model went: the key or@@ -836,6 +848,9 @@ type videoStart struct {remote, custom boolasked bool // a vendor was asked: what it answered is recordedunfit bool // the model makes no videos: none was asked+ // onKey: started on one of keys on plans of their own, which its id+ // names (keyMark) to be asked after on, at that plan's endpoint+ onKey bool}// startVideo starts f's video on p's model: at another magpie's videos@@ -846,6 +861,7 @@ func (s *Server) startVideo(ctx context.Context, r *http.Request, p provider.Pro// the provider's other keys to start the video on, when the first// says it doesn't serve the modelvar keys []candidate+ onKey := falseif !p.IsRemoteMagpie() && filmsCustom(p, model) {// at a provider's own videos API: sent on the first key a chat// for the model would go to (#1657), never one whose own list of@@ -856,6 +872,16 @@ func (s *Server) startVideo(ctx context.Context, r *http.Request, p provider.Proreturn videoStart{p: p}, code, errors.New(msg)}p, keys = cs[0].p, cs[1:]+ } else if !p.IsRemoteMagpie() && p.PlansMixed() {+ // keys on plans of their own (KeyAccount.Plan): sent on a key+ // whose plan makes the model, the Agent Plan's Seedance on the+ // Agent Plan's key, never a pay-as-you-go key beside it+ cs, code, msg := s.onKeys(r, p, model, f.Model)+ if code != 0 {+ return videoStart{p: p}, code, errors.New(msg)+ }+ p = cs[0].p+ onKey = true} else if keyWho, held := accountHolds(r); held {// held to some accounts (#905): sent on a key the calling key may// use, of those in use — not the provider's first alone, which a@@ -865,7 +891,7 @@ func (s *Server) startVideo(ctx context.Context, r *http.Request, p provider.Proreturn videoStart{p: p}, 403, errors.New(keyAccountsError(keyWho, f.Model))}}- v := videoStart{p: p, remote: p.IsRemoteMagpie()}+ v := videoStart{p: p, remote: p.IsRemoteMagpie(), onKey: onKey}v.custom = !v.remote && filmsCustom(p, model)volcengine := p.Preset == "volcengine" && slices.ContainsFunc(p.PlanVideos(), func(m catalog.Model) bool { return m.ID == model })// any grok-imagine-video*, not only those listed: the vendor's newer ones work before magpie names themdiff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.jsindex b07a43663..dc1b4246e 100644--- a/internal/gui/assets/app.js+++ b/internal/gui/assets/app.js@@ -14145,6 +14145,8 @@ function renderKeyAccounts(p) {if (k.on && several) row.append(keyWeight(p, k, weightOf(k), weights));const proto = protoPicker(p, k.protocol, (v) => accountAction("keys/protocol", { id: p.id, ref: k.id, protocol: v }));if (proto) row.append(proto);+ const plan = planPicker(p, k, several);+ if (plan) row.append(plan);// set to a protocol the provider has no URL for (#1702): the gateway// can't send it there, so the row says so rather than the request// quietly going out on another URL@@ -14419,22 +14421,36 @@ function protoPicker(p, value, onChange) {value = value || "";const have = ["anthropic", "chat", "responses"].filter((x) => p[x]);if (have.length < 2 && !value) return null;- const opts = PROTO_OPTS.filter((o) => !o.v || have.includes(o.v) || o.v === value);- const pill = el("button", "proto" + (value ? " set" : ""));+ return pickPill(PROTO_OPTS.filter((o) => !o.v || have.includes(o.v) || o.v === value), value, "", "Some relays give out a key per protocol. Set it here and the gateway sends each request to the key that fits: Claude models to the Anthropic key, GPT models to the OpenAI one.", undefined, onChange);+}++// planPicker is the key row's plan badge, for a vendor whose plans take+// keys of their own (keyPlans): each key goes to its plan's endpoints.+function planPicker(p, k, several) {+ const pr = providers.presets.find((x) => x.id === p.preset), rs = pr?.keyPlans && pr.regions;+ if (!(rs?.length > 1) || (!several && !k.plan)) return null;+ const own = (regionAt(pr, p) || rs[0]).id;+ return pickPill(rs.map((r) => ({ v: r.id, pill: r.name, name: r.name, note: (r.chat || r.anthropic || "").replace(/^https?:\/\//, "") })), rs.some((r) => r.id === k.plan) ? k.plan : own, own,+ "The plan this key is for: its requests go to that plan's endpoints, and it is asked only for that plan's models.", "Plan this key is for", (v) => accountAction("keys/plan", { id: p.id, ref: k.id, plan: v === own ? "" : v }));+}++// pickPill is a key row's badge of one of opts, set when not dflt; a+// click drops the menu of them.+function pickPill(opts, value, dflt, title, head, onChange) {+ const pill = el("button", "proto");pill.type = "button";- pill.title = t("Some relays give out a key per protocol. Set it here and the gateway sends each request to the key that fits: Claude models to the Anthropic key, GPT models to the OpenAI one.");- const paint = () => pill.replaceChildren(el("span", "", t(PROTO_OPTS.find((o) => o.v === value).pill)), svg(CHEV, 11, 1.6));+ pill.title = t(title);+ const paint = () => {+ pill.classList.toggle("set", value !== dflt);+ pill.replaceChildren(el("span", "", t(opts.find((o) => o.v === value).pill)), svg(CHEV, 11, 1.6));+ };paint();pill.onclick = (e) => {e.stopPropagation();if (pill.classList.contains("open")) return closeProtoMenu();openProtoMenu(pill, opts, value, (v) => {- if (v === value) return;- value = v;- pill.classList.toggle("set", !!v);- paint();- onChange(v);- });+ if (v !== value) { value = v; paint(); onChange(v); }+ }, head);};return pill;}diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.jsindex 51b337735..51c91d9ee 100644--- a/internal/gui/assets/i18n.js+++ b/internal/gui/assets/i18n.js@@ -1628,6 +1628,8 @@ const I18N = {"Stop using this key": "停用这个密钥","Any protocol": "任意协议","Protocol this key speaks": "这个密钥可用的协议",+ "Plan this key is for": "这个密钥所属的套餐",+ "The plan this key is for: its requests go to that plan's endpoints, and it is asked only for that plan's models.": "这个密钥所属的套餐:它的请求发往该套餐的地址,也只用它请求该套餐的模型。","Used on every endpoint": "所有端点都可以用","Messages API · Claude Code, Claude": "Messages API · Claude Code、Claude 模型","OpenAI API · GPT models, most agents": "OpenAI API · GPT 模型、大多数 agent",@@ -5593,6 +5595,8 @@ const I18N = {"Stop using this key": "停用這個金鑰","Any protocol": "任意協議","Protocol this key speaks": "這個金鑰可用的協議",+ "Plan this key is for": "這個金鑰所屬的方案",+ "The plan this key is for: its requests go to that plan's endpoints, and it is asked only for that plan's models.": "這個金鑰所屬的方案:它的請求送往該方案的位址,也只用它請求該方案的模型。","Used on every endpoint": "所有端點都可以用","Messages API · Claude Code, Claude": "Messages API · Claude Code、Claude 模型","OpenAI API · GPT models, most agents": "OpenAI API · GPT 模型、大多數 agent",@@ -9535,6 +9539,8 @@ const I18N = {"Stop using this key": "このキーの使用を停止","Any protocol": "任意のプロトコル","Protocol this key speaks": "このキーが対応するプロトコル",+ "Plan this key is for": "このキーのプラン",+ "The plan this key is for: its requests go to that plan's endpoints, and it is asked only for that plan's models.": "このキーのプラン:リクエストはそのプランのエンドポイントに送られ、そのプランのモデルにだけ使われます。","Used on every endpoint": "すべてのエンドポイントで使用","Messages API · Claude Code, Claude": "Messages API · Claude Code、Claude","OpenAI API · GPT models, most agents": "OpenAI API · GPT モデル、ほとんどのエージェント",@@ -13507,6 +13513,8 @@ const I18N = {"Stop using this key": "Diesen Schlüssel nicht mehr verwenden","Any protocol": "Beliebiges Protokoll","Protocol this key speaks": "Protokoll dieses Schlüssels",+ "Plan this key is for": "Tarif dieses Schlüssels",+ "The plan this key is for: its requests go to that plan's endpoints, and it is asked only for that plan's models.": "Der Tarif dieses Schlüssels: Seine Anfragen gehen an die Endpunkte dieses Tarifs, und er wird nur für dessen Modelle gefragt.","Used on every endpoint": "Wird an jedem Endpunkt verwendet","Messages API · Claude Code, Claude": "Messages API · Claude Code, Claude","OpenAI API · GPT models, most agents": "OpenAI API · GPT-Modelle, die meisten Agenten",diff --git a/internal/gui/providers.go b/internal/gui/providers.goindex 7e8dc0337..1e28c11c1 100644--- a/internal/gui/providers.go+++ b/internal/gui/providers.go@@ -1645,7 +1645,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {in.Contexts = old.Contexts // a save that doesn't say}if in.Key == old.Key {- in.KeyName, in.KeyProtocol, in.KeyWeight = old.KeyName, old.KeyProtocol, old.KeyWeight+ in.KeyName, in.KeyProtocol, in.KeyWeight, in.KeyPlan = old.KeyName, old.KeyProtocol, old.KeyWeight, old.KeyPlan}// what the editor doesn't show, set from the CLI or the// TUI, is kept: its tag, website and key page, and on a@@ -2123,6 +2123,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {Refs []stringProtocol provider.ProtocolWeight int+ Plan string}var added, had, removed intif err := json.NewDecoder(r.Body).Decode(&in); err != nil {@@ -2141,6 +2142,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) {err = provider.SetKeyProtocol(in.ID, in.Ref, in.Protocol)case "weight":err = provider.SetKeyWeight(in.ID, in.Ref, in.Weight)+ case "plan":+ // the plan a key is for (KeyAccount.Plan): its endpoints and+ // its models are that plan's+ err = provider.SetKeyPlan(in.ID, in.Ref, in.Plan)case "use":err = provider.UseKey(in.ID, in.Ref)case "remove":@@ -2167,8 +2172,8 @@ func providerRoutes(mux *http.ServeMux, w Windows) {// models a key sees is known only from its own list, and an off// key's isn't asked (#76), so until then a relay that hands out a// key per group would send the key nothing, or everything- if a := r.PathValue("action"); a == "add" || a == "import" || a == "on" {- if p, err := provider.Find(in.ID); err == nil && p.Ready() && len(p.KeysOn()) > 1 {+ if a := r.PathValue("action"); a == "add" || a == "import" || a == "on" || a == "plan" {+ if p, err := provider.Find(in.ID); err == nil && p.Ready() && (len(p.KeysOn()) > 1 || a == "plan") {ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)p.Fetch(ctx)cancel()@@ -2362,7 +2367,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {// project is.func typed(p, in provider.Provider, proxy *string, insecureTLS *bool) provider.Provider {if k := strings.TrimSpace(in.Key); k != "" && k != p.Key {- p.Key, p.KeyName, p.KeyProtocol, p.KeyWeight = k, "", "", 0+ p.Key, p.KeyName, p.KeyProtocol, p.KeyWeight, p.KeyPlan = k, "", "", 0, ""}if v := in.Vertex.Normal(); v != nil && p.IsVertex() && v.Project != "" {p.Vertex = vdiff --git a/internal/gui/tests/key-plan.test.cjs b/internal/gui/tests/key-plan.test.cjsnew file mode 100644index 000000000..111670aa3--- /dev/null+++ b/internal/gui/tests/key-plan.test.cjs@@ -0,0 +1,148 @@+// Run with Node's test runner and Playwright on the module path; see README.md.+// yckonnnn on X: Volcengine's pay as you go and its Agent Plan, a key of+// each in one provider. Each key row of a vendor whose plans take keys of+// their own (keyPlans) has a plan chip saying which plan it is for; a+// click opens the app's own menu of the plans, and a pick saves it+// (keys/plan), the provider's own plan as none. A key alone on the+// provider's plan, and a provider whose keys are on one plan, have no+// chip. A click scrolls nothing, nothing runs off a 420px window. In+// every language, Chromium and WebKit.+const assert = require("node:assert/strict");+const fs = require("node:fs/promises");+const path = require("node:path");+const { test } = require("node:test");+const { chromium, webkit } = require("playwright");++const assets = path.resolve(__dirname, "../assets");+const ark = "https://ark.cn-beijing.volces.com";+const preset = {+ id: "volcengine", name: "Volcengine Ark", icon: "volcengine-color", kind: "vendor", keyPlans: true, regionLabel: "Plan",+ chat: ark + "/api/coding/v3", responses: ark + "/api/coding/v3", anthropic: ark + "/api/coding",+ regions: [+ { id: "coding", name: "Coding Plan", chat: ark + "/api/coding/v3", responses: ark + "/api/coding/v3", anthropic: ark + "/api/coding" },+ { id: "agent", name: "Agent Plan", chat: ark + "/api/plan/v3", responses: ark + "/api/plan/v3", anthropic: ark + "/api/plan" },+ { id: "api", name: "Pay as you go", chat: ark + "/api/v3", responses: ark + "/api/v3" },+ ],+};+const volc = (keys) => ({+ id: "volc", name: "Volc", preset: "volcengine", icon: "volcengine-color", chat: ark + "/api/coding/v3", responses: ark + "/api/coding/v3", anthropic: ark + "/api/coding", catalog: "",+ models: [{ id: "kimi-k3", name: "", on: true }], agents: [], fallback: [], headers: {}, routing: "",+ key: { set: true, masked: "sk-…one" }, balanceToken: { takes: false, set: false }, proxy: "",+ keyList: keys,+});+const relay = {+ id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "",+ models: [{ id: "gpt-5.5", name: "", on: true }], agents: [], fallback: [], headers: {}, routing: "",+ key: { set: true, masked: "sk-…r1" }, balanceToken: { takes: false, set: false }, proxy: "",+ keyList: [{ id: "rrrrrrrrr1", name: "r1", masked: "sk-…r1", on: true, active: true, plan: "api" }, { id: "rrrrrrrrr2", name: "r2", masked: "sk-…r2", on: true }],+};++function serve(lang, st) {+ return async (request) => {+ const url = new URL(request.request().url());+ const json = (data) => request.fulfill({ json: data });+ const list = () => ({ providers: [volc(st.keys), relay], presets: [preset], excluded: [], gateway: { running: true, window: true } });+ if (url.pathname === "/boot.js") return request.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });+ if (url.pathname === "/wails/runtime.js") return request.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });+ if (url.pathname === "/api/state") return json({ agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } });+ if (url.pathname === "/api/providers") return json(list());+ if (url.pathname === "/api/keys/plan") {+ const body = request.request().postDataJSON();+ st.posts.push(body);+ st.keys = st.keys.map((k) => (k.id === body.ref ? { ...k, plan: body.plan || undefined } : k));+ return json(list());+ }+ if (url.pathname === "/api/gateway/trace") {+ if (url.searchParams.get("wait")) return new Promise(() => {});+ return json({ mine: true, now: new Date().toISOString(), seq: 0, totals: { requests: 0 }, routes: [] });+ }+ if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });+ if (url.pathname === "/api/groups") return json({ groups: [] });+ if (url.pathname === "/api/plugins") return json({ plugins: [] });+ if (url.pathname.startsWith("/api/")) return json({});+ const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);+ const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];+ await request.fulfill({ body: await fs.readFile(file).catch(() => ""), contentType });+ };+}++async function open(t, engine, lang, width, keys) {+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));+ t.after(() => browser.close());+ const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage();+ page.setDefaultTimeout(5000);+ const errors = [];+ page.on("pageerror", (e) => errors.push(e.message));+ const st = { keys, posts: [] };+ await page.route("**/*", serve(lang, st));+ await page.goto("http://magpie.test/?view=providers");+ const say = (key) => page.evaluate(([lang, key]) => (lang !== "en" && I18N[lang]?.[key]) || key, [lang, key]);+ return { page, errors, say, st };+}++const sideways = (page) => page.evaluate(() => document.documentElement.scrollWidth > innerWidth);+const scrolled = (page) => page.evaluate(() => [window.scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop > 0).map((e) => `${e.className}:${e.scrollTop}`)].join(" "));+const three = () => [+ { id: "aaaaaaaaaa", name: "coding", masked: "sk-…one", on: true, active: true },+ { id: "bbbbbbbbbb", name: "payg", masked: "sk-…two", on: true, plan: "api" },+ { id: "cccccccccc", name: "agent", masked: "sk-…three", on: true, plan: "agent" },+];++for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {+ for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {+ for (const width of [420, 1000]) {+ test(`${engine} ${lang} ${width}px: each key says its plan, and a pick saves it`, async (t) => {+ const { page, errors, say, st } = await open(t, engine, lang, width, three());+ await page.locator(".row.provider", { hasText: "Volc" }).first().click();+ const row = (id) => page.locator(`.editor .accts.keys .acc[data-account-id="${id}"]`);+ await row("aaaaaaaaaa").waitFor();+ const names = {};+ for (const r of preset.regions) names[r.id] = await say(r.name);+ for (const [id, plan] of [["aaaaaaaaaa", "coding"], ["bbbbbbbbbb", "api"], ["cccccccccc", "agent"]]) {+ // a key on the provider's own plan shows its chip on hover, as Any protocol does+ await row(id).hover();+ const c = row(id).locator("button.proto").filter({ hasText: names[plan] });+ assert.equal(await c.count(), 1, `${id}: no chip saying ${names[plan]}`);+ assert.equal(await c.getAttribute("title"), await say("The plan this key is for: its requests go to that plan's endpoints, and it is asked only for that plan's models."));+ const box = await c.boundingBox();+ assert.ok(box && box.x >= 0 && box.x + box.width <= width, `the chip runs off the window: ${JSON.stringify(box)}`);+ }+ // the coding key moved to the Agent Plan+ const c = row("aaaaaaaaaa").locator("button.proto").filter({ hasText: names.coding });+ await c.scrollIntoViewIfNeeded();+ await row("aaaaaaaaaa").hover();+ const sc = await scrolled(page);+ await c.click();+ const menu = page.locator(".proto-menu");+ await menu.waitFor();+ assert.equal((await menu.locator(".pm-head").textContent()).trim(), await say("Plan this key is for"));+ assert.equal(await menu.locator(".pm-item").count(), 3);+ assert.equal(await scrolled(page), sc, "a click scrolled");+ const mb = await menu.boundingBox();+ assert.ok(mb.x >= 0 && mb.x + mb.width <= width, `the menu runs off the window: ${JSON.stringify(mb)}`);+ await menu.locator(".pm-item", { hasText: names.agent }).click();+ await page.waitForFunction(() => !document.querySelector(".proto-menu"));+ await row("aaaaaaaaaa").locator("button.proto").filter({ hasText: names.agent }).waitFor();+ assert.deepEqual(st.posts, [{ id: "volc", ref: "aaaaaaaaaa", plan: "agent" }]);+ // the agent key back to the provider's own plan: saved as none+ await row("cccccccccc").locator("button.proto").filter({ hasText: names.agent }).click();+ await page.locator(".proto-menu .pm-item", { hasText: names.coding }).click();+ await row("cccccccccc").locator("button.proto:not(.set)").filter({ hasText: names.coding }).waitFor({ state: "attached" });+ assert.deepEqual(st.posts[1], { id: "volc", ref: "cccccccccc", plan: "" });+ assert.equal(await sideways(page), false, "the page scrolls sideways");+ assert.deepEqual(errors, []);+ });+ }+ }+ test(`${engine}: no chip for one key on the provider's plan, nor a preset of one plan`, async (t) => {+ const { page, errors } = await open(t, engine, "en", 420, [{ id: "aaaaaaaaaa", name: "coding", masked: "sk-…one", on: true, active: true }]);+ await page.locator(".row.provider", { hasText: "Volc" }).first().click();+ await page.locator(`.editor .accts.keys .acc[data-account-id="aaaaaaaaaa"]`).waitFor();+ assert.equal(await page.locator(".editor .accts.keys button.proto", { hasText: "Coding Plan" }).count(), 0);+ await page.goto("http://magpie.test/?view=providers");+ await page.locator(".row.provider", { hasText: "Relay" }).first().click();+ await page.locator(`.editor .accts.keys .acc[data-account-id="rrrrrrrrr1"]`).waitFor();+ assert.equal(await page.locator(".editor .accts.keys button.proto", { hasText: "Pay as you go" }).count(), 0);+ assert.deepEqual(errors, []);+ });+}diff --git a/internal/provider/balance.go b/internal/provider/balance.goindex a55962093..c3d22fb64 100644--- a/internal/provider/balance.go+++ b/internal/provider/balance.go@@ -1465,12 +1465,14 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota {if first == "" {first = Mask(p.Key)}- jobs = append(jobs, job{p, first})+ // each key asked at its own plan's host (KeyAccount.Plan):+ // SiliconFlow's China key and its international one+ jobs = append(jobs, job{p.atKeyPlan(p.KeyPlan), first})for _, k := range p.Keys {if k.Off || k.Key == "" || k.Key == p.Key {continue}- q := p+ q := p.atKeyPlan(k.Plan)q.Key = k.Keyname := k.Nameif name == "" {diff --git a/internal/provider/keep_secrets.go b/internal/provider/keep_secrets.goindex ceda646fa..eb374d5ae 100644--- a/internal/provider/keep_secrets.go+++ b/internal/provider/keep_secrets.go@@ -23,7 +23,7 @@ func SecretHeader(name string) bool { return secretHeader.MatchString(name) }// is another account's, whose access key this one's isn't.func KeepSecrets(in, here Provider, keyless bool) Provider {if keyless {- in.Key, in.KeyName, in.Keys, in.KeyProtocol, in.KeyWeight = here.Key, here.KeyName, here.Keys, here.KeyProtocol, here.KeyWeight+ in.Key, in.KeyName, in.Keys, in.KeyProtocol, in.KeyWeight, in.KeyPlan = here.Key, here.KeyName, here.Keys, here.KeyProtocol, here.KeyWeight, here.KeyPlan// the headers a copy without keys left out, in a map of its own:// in's may be shared with the list it came incloned := falsediff --git a/internal/provider/key_plans.go b/internal/provider/key_plans.gonew file mode 100644index 000000000..a5acf0a1d--- /dev/null+++ b/internal/provider/key_plans.go@@ -0,0 +1,215 @@+package provider++// A vendor may sell its plans and its pay as you go on keys of their own,+// each taken only at its own endpoints: Volcengine's Coding Plan at+// /api/coding, its Agent Plan at /api/plan, its pay as you go at /api/v3+// (yckonnnn on X, with one key of each in one provider). A key of such a+// preset (PresetDef.KeyPlans) may say which of its Regions it is for+// (KeyAccount.Plan, Provider.KeyPlan for the first): its requests go to+// that plan's endpoints, it is asked only for that plan's models, its+// model list is that plan's, and its windows and balance are read where+// that plan's are. A key that says none is on the provider's own plan, as+// every key was before.++import (+ "net/url"+ "strings"+)++// keyRegion is the region of p's preset a key's plan names, and the+// region p sits at; nil for a key on p's own plan, or a preset whose keys+// are all on one.+func (p Provider) keyRegion(plan string) (pr *PresetDef, r, cur *Region) {+ if plan == "" {+ return nil, nil, nil+ }+ pr = Preset(p.Preset)+ if pr == nil || !pr.KeyPlans {+ return nil, nil, nil+ }+ for i := range pr.Regions {+ if pr.Regions[i].ID == plan {+ r = &pr.Regions[i]+ }+ }+ if r == nil {+ return nil, nil, nil // a plan the preset no longer has: the provider's+ }+ cur = p.regionOf(pr)+ if cur != nil && cur.ID == r.ID {+ return nil, nil, nil+ }+ return pr, r, cur+}++// atKeyPlan is p at the endpoints of the plan a key is for (its Region),+// with that plan's key page, docs and catalog; p as it is for a key on its+// own plan. A provider asked at another host than its preset's (a mirror,+// a test's fake vendor) is asked at that host on the other plan too.+func (p Provider) atKeyPlan(plan string) Provider {+ pr, r, cur := p.keyRegion(plan)+ if r == nil {+ return p+ }+ host := p.ownHost(cur)+ p.atRegionOf(pr, *r)+ if host != "" {+ for _, u := range []*string{&p.Chat, &p.Responses, &p.Anthropic} {+ *u = rehost(*u, host)+ }+ }+ return p+}++// ownHost is the scheme and host p is asked at when they aren't its+// region's own, "" when they are.+func (p Provider) ownHost(cur *Region) string {+ if cur == nil {+ return ""+ }+ for _, e := range [][2]string{{p.Chat, cur.Chat}, {p.Responses, cur.Responses}, {p.Anthropic, cur.Anthropic}} {+ if e[0] == "" || e[1] == "" {+ continue+ }+ a, err1 := url.Parse(e[0])+ b, err2 := url.Parse(e[1])+ if err1 != nil || err2 != nil || strings.EqualFold(a.Host, b.Host) {+ return ""+ }+ return a.Scheme + "://" + a.Host+ }+ return ""+}++// rehost is raw at host (scheme://host) instead of its own.+func rehost(raw, host string) string {+ if raw == "" {+ return ""+ }+ u, err := url.Parse(raw)+ if err != nil {+ return raw+ }+ h, err := url.Parse(host)+ if err != nil {+ return raw+ }+ u.Scheme, u.Host = h.Scheme, h.Host+ return u.String()+}++// PlansMixed reports whether p's keys in use are on more than one of its+// preset's plans (KeyAccount.Plan).+func (p Provider) PlansMixed() bool { return p.plansMixed() }++// plansMixed reports whether a key of p in use is for another plan than+// p's own: only then do its keys differ in endpoints and models. Read+// from the keys themselves, not KeysOn, which a test counts per request.+func (p Provider) plansMixed() bool {+ if p.Key == "" || p.keyView {+ return false+ }+ pr := Preset(p.Preset)+ if pr == nil || !pr.KeyPlans {+ return false+ }+ if _, r, _ := p.keyRegion(p.KeyPlan); r != nil {+ return true+ }+ for _, k := range p.Keys {+ if k.Off || k.Key == "" || k.Key == p.Key {+ continue+ }+ if _, r, _ := p.keyRegion(k.Plan); r != nil {+ return true+ }+ }+ return false+}++// planList is the models a plan has as the preset says, for a key at it:+// its region's own, or the preset's for a preset that lists nothing at a+// region that doesn't list either; with its embedding, drawing and video+// models. nil when the plan's models are its vendor's list's to say.+func (p Provider) planList() []string {+ pr := Preset(p.Preset)+ if pr == nil {+ return nil+ }+ r := p.regionOf(pr)+ if r == nil {+ return nil+ }+ var out []string+ switch {+ case r.Models != nil:+ out = append(out, r.Models...)+ case pr.NoList && !r.Lists:+ out = append(out, pr.Models...)+ }+ for _, l := range [][]string{r.Embeddings, r.Drawers, r.Videos} {+ out = append(out, l...)+ }+ return out+}++// PlanServing is, for each of p's keys, whether the plan that key is for+// can serve model: false only when p's keys are on different plans+// (KeyAccount.Plan) and the key's plan names its models and leaves this+// one out — a pay-as-you-go model id sent to the Agent Plan's endpoint+// only answers 404. A model the user set the key to serve+// (AccountModels) it serves. Every key serves when p's keys are on one+// plan, as before.+func (p Provider) PlanServing(model string) func(KeyAccount) bool {+ if !p.plansMixed() {+ return func(KeyAccount) bool { return true }+ }+ lists := map[string][]string{} // each plan's, found once+ return func(k KeyAccount) bool {+ if m, ok := p.AccountModels[keyID(k.Key)]; ok && containsFold(m, model) {+ return true+ }+ l, ok := lists[k.Plan]+ if !ok {+ l = p.atKeyPlan(k.Plan).planList()+ lists[k.Plan] = l+ }+ return l == nil || containsFold(l, model)+ }+}++func containsFold(l []string, s string) bool {+ for _, x := range l {+ if strings.EqualFold(x, s) {+ return true+ }+ }+ return false+}++// planViews is each provider of ps once for each plan its keys in use are+// on, at that plan's endpoints, with those keys alone: a plan's windows+// read with an access key (Volcengine's, Tencent Cloud's) are read for+// each plan a provider has a key of.+func planViews(ps []Provider) []Provider {+ var out []Provider+ for _, p := range ps {+ if !p.plansMixed() {+ out = append(out, p)+ continue+ }+ at := map[string]int{}+ for _, k := range p.KeysOn() {+ q := p.atKeyPlan(k.Plan)+ if i, ok := at[q.Chat+" "+q.Anthropic]; ok {+ out[i].Keys = append(out[i].Keys, k)+ continue+ }+ at[q.Chat+" "+q.Anthropic] = len(out)+ q.setFirst(k)+ q.Keys = nil+ out = append(out, q)+ }+ }+ return out+}diff --git a/internal/provider/key_plans_test.go b/internal/provider/key_plans_test.gonew file mode 100644index 000000000..009b4f324--- /dev/null+++ b/internal/provider/key_plans_test.go@@ -0,0 +1,227 @@+package provider++import (+ "context"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "testing"+)++func keyPlanHome(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))+ t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))+}++// volcMixed is yckonnnn's provider (on X): Volcengine at its Coding Plan,+// with a pay-as-you-go key and an Agent Plan key beside the plan's own.+func volcMixed() Provider {+ pr := Preset("volcengine")+ return Provider{ID: "volc", Name: "Volc", Preset: "volcengine", Chat: pr.Chat, Responses: pr.Responses, Anthropic: pr.Anthropic,+ Key: "k-coding", Keys: []KeyAccount{{Key: "k-api", Plan: "api"}, {Key: "k-agent", Plan: "agent"}}}+}++// Each key goes to its own plan's endpoints, on every protocol; a key that+// names no plan stays on the provider's.+func TestKeyPlanEndpoints(t *testing.T) {+ p := volcMixed()+ if !p.PlansMixed() {+ t.Fatal("keys on three plans read as one")+ }+ for _, c := range []struct{ key, chat, responses, anthropic string }{+ {"k-coding", "https://ark.cn-beijing.volces.com/api/coding/v3", "https://ark.cn-beijing.volces.com/api/coding/v3", "https://ark.cn-beijing.volces.com/api/coding"},+ {"k-api", "https://ark.cn-beijing.volces.com/api/v3", "https://ark.cn-beijing.volces.com/api/v3", ""},+ {"k-agent", "https://ark.cn-beijing.volces.com/api/plan/v3", "https://ark.cn-beijing.volces.com/api/plan/v3", "https://ark.cn-beijing.volces.com/api/plan"},+ } {+ var k KeyAccount+ for _, x := range p.KeysOn() {+ if x.Key == c.key {+ k = x+ }+ }+ q := p.WithKey(k)+ if q.Chat != c.chat || q.Responses != c.responses || q.Anthropic != c.anthropic {+ t.Errorf("%s at %q %q %q", c.key, q.Chat, q.Responses, q.Anthropic)+ }+ if q.PlansMixed() {+ t.Errorf("%s: one key's copy judged mixed again", c.key)+ }+ }+ // at a host of its own (a mirror, a fake vendor) each plan is asked there+ p.Chat, p.Responses, p.Anthropic = "http://127.0.0.1:9/api/coding/v3", "http://127.0.0.1:9/api/coding/v3", "http://127.0.0.1:9/api/coding"+ if q := p.WithKey(p.Keys[1]); q.Chat != "http://127.0.0.1:9/api/plan/v3" || q.Anthropic != "http://127.0.0.1:9/api/plan" {+ t.Errorf("agent key at its own host: %q %q", q.Chat, q.Anthropic)+ }+}++// A model only one plan has goes only to that plan's key; one every plan+// has goes to every key; a model the user set a key to serve it serves.+func TestKeyPlanServing(t *testing.T) {+ p := volcMixed()+ serves := func(model string) string {+ f := p.PlanServing(model)+ var on []string+ for _, k := range p.KeysOn() {+ if f(k) {+ on = append(on, k.Key)+ }+ }+ return strings.Join(on, ",")+ }+ for model, want := range map[string]string{+ "deepseek-v3-250324": "k-api", // pay as you go's alone+ "doubao-seedance-2.0": "k-api,k-agent", // Agent Plan's video, and the open list+ "kimi-k3": "k-coding,k-api,k-agent", // every plan+ "Kimi-K3": "k-coding,k-api,k-agent",+ } {+ if got := serves(model); got != want {+ t.Errorf("%s: %s, want %s", model, got, want)+ }+ }+ p.AccountModels = map[string][]string{keyID("k-coding"): {"deepseek-v3-250324"}}+ if got := serves("deepseek-v3-250324"); got != "k-coding,k-api" {+ t.Errorf("a key set to serve a model: %s", got)+ }+}++// Old configs are as they were: keys that name no plan, a plan that is the+// provider's own, a plan the preset doesn't have, or a preset whose keys+// are all on one plan.+func TestKeyPlanOldConfigsUnchanged(t *testing.T) {+ keyPlanHome(t)+ for name, p := range map[string]Provider{+ "no plans": func() Provider { p := volcMixed(); p.Keys[0].Plan, p.Keys[1].Plan = "", ""; return p }(),+ "own plan": func() Provider {+ p := volcMixed()+ p.KeyPlan, p.Keys[0].Plan, p.Keys[1].Plan = "coding", "coding", "coding"+ return p+ }(),+ "gone": func() Provider { p := volcMixed(); p.Keys[0].Plan, p.Keys[1].Plan = "lite", "pro"; return p }(),+ "one plan": {ID: "q", Name: "Q", Preset: "qwen", Chat: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1", Key: "a", Keys: []KeyAccount{{Key: "b", Plan: "api"}}},+ } {+ if p.PlansMixed() {+ t.Errorf("%s: mixed", name)+ }+ for _, k := range p.KeysOn() {+ if q := p.WithKey(k); q.Chat != p.Chat || q.Anthropic != p.Anthropic {+ t.Errorf("%s: key %s moved to %q", name, k.Key, q.Chat)+ }+ if !p.PlanServing("deepseek-v3-250324")(k) {+ t.Errorf("%s: key %s barred", name, k.Key)+ }+ }+ if got := planViews([]Provider{p}); len(got) != 1 || got[0].Key != p.Key || len(got[0].Keys) != len(p.Keys) {+ t.Errorf("%s: views %+v", name, got)+ }+ }+ // a saved provider that names no plan is written as before+ p := volcMixed()+ p.Keys[0].Plan, p.Keys[1].Plan = "", ""+ if err := Save(p); err != nil {+ t.Fatal(err)+ }+ b, err := os.ReadFile(Path())+ if err != nil {+ t.Fatal(err)+ }+ if strings.Contains(string(b), `"plan"`) || strings.Contains(string(b), `"keyPlan"`) {+ t.Errorf("a plan written for keys that name none:\n%s", b)+ }+}++// SetKeyPlan keeps the provider's own plan as none, refuses a plan the+// preset doesn't have and a preset whose keys are on one plan.+func TestSetKeyPlan(t *testing.T) {+ keyPlanHome(t)+ p := volcMixed()+ p.Keys[0].Plan, p.Keys[1].Plan = "", ""+ if err := Save(p); err != nil {+ t.Fatal(err)+ }+ if err := SetKeyPlan("volc", keyID("k-api"), "api"); err != nil {+ t.Fatal(err)+ }+ if err := SetKeyPlan("volc", keyID("k-coding"), "agent"); err != nil {+ t.Fatal(err)+ }+ if err := SetKeyPlan("volc", keyID("k-agent"), "coding"); err != nil {+ t.Fatal(err)+ }+ got, err := Find("volc")+ if err != nil {+ t.Fatal(err)+ }+ if got.KeyPlan != "agent" || got.Keys[0].Plan != "api" || got.Keys[1].Plan != "" {+ t.Fatalf("plans %q %q %q", got.KeyPlan, got.Keys[0].Plan, got.Keys[1].Plan)+ }+ if l := got.KeyList(); l[0].Plan != "agent" || l[1].Plan != "api" {+ t.Errorf("KeyList %+v", l)+ }+ if err := SetKeyPlan("volc", keyID("k-api"), "nope"); err == nil {+ t.Error("a plan the preset doesn't have")+ }+ if err := Save(Provider{ID: "q", Name: "Q", Preset: "qwen", Chat: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1", Key: "a"}); err != nil {+ t.Fatal(err)+ }+ if err := SetKeyPlan("q", keyID("a"), "api"); err == nil {+ t.Error("a plan for a preset whose keys are on one")+ }+}++// A provider of keys on mixed plans lists each key's plan: the Coding+// Plan's models as the preset says, without asking (its /models is Ark's+// general catalog), pay as you go's from its own /models with its key.+func TestKeyPlanModelList(t *testing.T) {+ keyPlanHome(t)+ var mu sync.Mutex+ var asked []string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ mu.Lock()+ asked = append(asked, r.Header.Get("Authorization")+" "+r.URL.Path)+ mu.Unlock()+ _, _ = w.Write([]byte(`{"data":[{"id":"deepseek-v3-250324"},{"id":"kimi-k3"}]}`))+ }))+ defer srv.Close()+ p := Provider{ID: "volc", Name: "Volc", Preset: "volcengine", Chat: srv.URL + "/api/coding/v3", Responses: srv.URL + "/api/coding/v3", Anthropic: srv.URL + "/api/coding",+ Key: "k-coding", Keys: []KeyAccount{{Key: "k-api", Plan: "api"}}}+ ms, err := p.fetch(context.Background())+ if err != nil {+ t.Fatal(err)+ }+ if strings.Join(asked, ",") != "Bearer k-api /api/v3/models" {+ t.Fatalf("asked %v", asked)+ }+ have := map[string]bool{}+ for _, m := range ms {+ have[m.ID] = true+ }+ if !have["deepseek-v3-250324"] || !have["ark-code-latest"] || !have["kimi-k3"] {+ t.Fatalf("models %v", have)+ }+ if p.Serves(p.first(), "deepseek-v3-250324") || !p.Serves(p.Keys[0], "deepseek-v3-250324") {+ t.Error("pay as you go's model served by the Coding Plan key")+ }+ if !p.Serves(p.first(), "kimi-k3") || !p.Serves(p.Keys[0], "kimi-k3") {+ t.Error("a model both plans have")+ }+}++// Each plan a provider has keys of is its own view, with those keys alone,+// at that plan's endpoints: windows read per plan.+func TestKeyPlanViews(t *testing.T) {+ v := planViews([]Provider{volcMixed()})+ if len(v) != 3 {+ t.Fatalf("%d views", len(v))+ }+ for i, want := range []string{"k-coding /api/coding/v3", "k-api /api/v3", "k-agent /api/plan/v3"} {+ if got := v[i].Key + " " + strings.TrimPrefix(v[i].Chat, "https://ark.cn-beijing.volces.com"); got != want || len(v[i].Keys) != 0 {+ t.Errorf("view %d: %s (%d more keys), want %s", i, got, len(v[i].Keys), want)+ }+ }+}diff --git a/internal/provider/keys.go b/internal/provider/keys.goindex 79a321c4d..97cb515bd 100644--- a/internal/provider/keys.go+++ b/internal/provider/keys.go@@ -13,6 +13,7 @@ import ("encoding/hex""errors""fmt"+ "slices""strings""sync""sync/atomic"@@ -31,6 +32,11 @@ type KeyAccount struct {// routing is Weighted (#841): one with 3 takes three for every one a// key with 1 takes. None, or 0, counts as 1.Weight int `json:"weight,omitempty"`+ // Plan, on a preset whose plans are sold on keys of their own+ // (PresetDef.KeyPlans), is the id of the Region the key is for: its+ // requests go to that plan's endpoints, and it is asked only for that+ // plan's models. Empty is the provider's own plan, as before.+ Plan string `json:"plan,omitempty"`}// KeyInfo describes one of a provider's keys without giving it away.@@ -43,6 +49,7 @@ type KeyInfo struct {Protocol Protocol `json:"protocol,omitempty"` // the only one it works withWeight int `json:"weight,omitempty"` // its share when routing is Weighted+ Plan string `json:"plan,omitempty"` // its plan's region id, "" for the provider's// Rest is why the gateway passes it over now, after a failure, and// until when; nil while it takes requests.@@ -102,10 +109,10 @@ func KeyID(key string) string { return keyID(key) }func (p Provider) KeyList() []KeyInfo {var out []KeyInfoif p.Key != "" {- out = append(out, KeyInfo{ID: keyID(p.Key), Name: p.KeyName, Masked: Mask(p.Key), Active: true, On: true, Protocol: p.KeyProtocol, Weight: p.KeyWeight})+ out = append(out, KeyInfo{ID: keyID(p.Key), Name: p.KeyName, Masked: Mask(p.Key), Active: true, On: true, Protocol: p.KeyProtocol, Weight: p.KeyWeight, Plan: p.KeyPlan})}for _, k := range p.Keys {- out = append(out, KeyInfo{ID: keyID(k.Key), Name: k.Name, Masked: Mask(k.Key), On: !k.Off, Protocol: k.Protocol, Weight: k.Weight})+ out = append(out, KeyInfo{ID: keyID(k.Key), Name: k.Name, Masked: Mask(k.Key), On: !k.Off, Protocol: k.Protocol, Weight: k.Weight, Plan: k.Plan})}return out}@@ -296,11 +303,11 @@ func (s *keySlots) take(ctx context.Context, id string) (release func()) {// first is the first key as a KeyAccount, and setFirst makes k the first.func (p *Provider) first() KeyAccount {- return KeyAccount{Name: p.KeyName, Key: p.Key, Protocol: p.KeyProtocol, Weight: p.KeyWeight}+ return KeyAccount{Name: p.KeyName, Key: p.Key, Protocol: p.KeyProtocol, Weight: p.KeyWeight, Plan: p.KeyPlan}}func (p *Provider) setFirst(k KeyAccount) {- p.Key, p.KeyName, p.KeyProtocol, p.KeyWeight = k.Key, k.Name, k.Protocol, k.Weight+ p.Key, p.KeyName, p.KeyProtocol, p.KeyWeight, p.KeyPlan = k.Key, k.Name, k.Protocol, k.Weight, k.Plan}func keyProtocolOK(proto Protocol) error {@@ -332,6 +339,41 @@ func SetKeyProtocol(id, keyRef string, proto Protocol) error {return Save(*p)}+// SetKeyPlan says which of the preset's plans (a Region's id) a key is+// for; empty is the provider's own. Its requests then go to that plan's+// endpoints, with that plan's models (WithKey).+func SetKeyPlan(id, keyRef, plan string) error {+ p, err := Find(id)+ if err != nil {+ return err+ }+ plan = strings.TrimSpace(plan)+ if plan != "" {+ pr := Preset(p.Preset)+ if pr == nil || !pr.KeyPlans {+ return fmt.Errorf("%s's keys are all on one plan", p.Name)+ }+ if !slices.ContainsFunc(pr.Regions, func(r Region) bool { return r.ID == plan }) {+ return fmt.Errorf("%s has no plan %q", pr.Name, plan)+ }+ // the provider's own plan is kept as none: the key follows the+ // provider when its plan is changed in the editor+ if r := p.regionOf(pr); r != nil && r.ID == plan {+ plan = ""+ }+ }+ i, ok := findKey(p, keyRef)+ if !ok {+ return fmt.Errorf("%s has no such key", p.Name)+ }+ if i < 0 {+ p.KeyPlan = plan+ } else {+ p.Keys[i].Plan = plan+ }+ return Save(*p)+}+// MaxKeyWeight is the most a key's weight can be.const MaxKeyWeight = 1000@@ -363,10 +405,14 @@ func SetKeyWeight(id, keyRef string, weight int) error {// WeightOf is the key's weight as Weighted routing counts it: 1 when none.func (k KeyAccount) WeightOf() int { return max(k.Weight, 1) }-// WithKey is p using key k: its endpoints narrowed to k's protocol when k-// has one. It has none left when p doesn't serve that protocol.+// WithKey is p using key k: at k's plan's endpoints when k is for a plan+// of its own (KeyAccount.Plan), and its endpoints narrowed to k's+// protocol when k has one. It has none left when p doesn't serve that+// protocol.func (p Provider) WithKey(k KeyAccount) Provider {- p.Key, p.KeyName, p.KeyProtocol, p.KeyWeight = k.Key, k.Name, k.Protocol, k.Weight+ p.Key, p.KeyName, p.KeyProtocol, p.KeyWeight, p.KeyPlan = k.Key, k.Name, k.Protocol, k.Weight, k.Plan+ p = p.atKeyPlan(k.Plan)+ p.keyView = trueif k.Protocol != "" {for _, pr := range Protocols {if pr != k.Protocol {diff --git a/internal/provider/models.go b/internal/provider/models.goindex fc75252a8..3d17fa5de 100644--- a/internal/provider/models.go+++ b/internal/provider/models.go@@ -172,7 +172,9 @@ func (p Provider) lists() bool {return false}pr := Preset(p.Preset)- return p.Account != nil || pr == nil || !pr.NoList || strings.TrimSpace(p.ModelsURL) != "" || p.listRegion(pr)+ // keys on plans of their own each have a list (fetchPerKey), the+ // plans' own and the pay as you go's+ return p.Account != nil || pr == nil || !pr.NoList || strings.TrimSpace(p.ModelsURL) != "" || p.listRegion(pr) || p.plansMixed()}// listsRead counts liveAll's reads (ListsRead).@@ -374,9 +376,15 @@ func (p Provider) fetch(ctx context.Context) ([]catalog.Model, error) {// a vendor with no list to ask (Bedrock's runtime): the preset's// models are it, unless the user said where one is or the provider// sits at a region that serves one after all- if pr := Preset(p.Preset); pr != nil && pr.NoList && strings.TrimSpace(p.ModelsURL) == "" && !p.listRegion(pr) {+ if pr := Preset(p.Preset); pr != nil && pr.NoList && strings.TrimSpace(p.ModelsURL) == "" && !p.listRegion(pr) && !p.plansMixed() {return catalog.Chat(p.planModels(nil)), nil}+ // keys on plans of their own (KeyAccount.Plan): each key's plan's+ // list, at its own endpoints, merged and marked with the keys that+ // see each model, as keys of one plan whose lists differ are+ if p.plansMixed() {+ return p.fetchPerKey(ctx, p.KeysOn())+ }// Cline's plan and free models, from the list its own clients take// theirs from; the API's list has neither, and is asked if that failsif p.IsCline() && strings.TrimSpace(p.ModelsURL) == "" {@@ -967,6 +975,17 @@ func (p Provider) keepDeadSides(dead []string, answered []side) (kept []catalog.return kept, out}+// planOnly is the models of the plan p is at, when it is one of a preset+// that lists nothing at a region that doesn't either: its models are the+// plan's, and no list is asked for.+func (p Provider) planOnly() ([]catalog.Model, bool) {+ pr := Preset(p.Preset)+ if pr == nil || !pr.NoList || strings.TrimSpace(p.ModelsURL) != "" || p.listRegion(pr) {+ return nil, false+ }+ return p.planModels(nil), true+}+// listRegion reports whether the provider sits at one of its preset's// regions that serves a model list although the preset as a whole has// none (Region.Lists): Qianfan's pay as you go at the v2 root answers@@ -1114,14 +1133,24 @@ func (p Provider) planMedia(ids func(*Region) []string, draws, films bool) []catif pr == nil {return nil}- r := p.regionOf(pr)- if r == nil {- return nil+ // keys on plans of their own (KeyAccount.Plan): each plan's, once+ views := []Provider{p}+ if p.plansMixed() {+ views = planViews(views)}- models := ids(r)- out := make([]catalog.Model, 0, len(models))- for _, id := range models {- out = append(out, catalog.Model{ID: id, Name: id, Provider: p.ID, Draws: draws, Films: films})+ var out []catalog.Model+ seen := map[string]bool{}+ for _, v := range views {+ r := v.regionOf(pr)+ if r == nil {+ continue+ }+ for _, id := range ids(r) {+ if !seen[id] {+ seen[id] = true+ out = append(out, catalog.Model{ID: id, Name: id, Provider: p.ID, Draws: draws, Films: films})+ }+ }}return out}@@ -1217,7 +1246,15 @@ func (p Provider) fetchPerKey(ctx context.Context, keys []KeyAccount) ([]catalogfor _, k := range keys {id := keyID(k.Key)q := p.WithKey(k)- l, err := q.fetchOne(ctx)+ var l fetched+ var err error+ if ms, ok := q.planOnly(); ok {+ // a key at a plan with no list to ask (Volcengine's Agent+ // Plan beside its pay as you go): the plan's models, unasked+ l = fetched{models: ms, base: cmp.Or(q.Base(Chat), q.Base(Anthropic))}+ } else {+ l, err = q.fetchOne(ctx)+ }if err != nil {lastErr = errif oldOf == nil {diff --git a/internal/provider/planquota.go b/internal/provider/planquota.goindex 476e5d6fd..f2ae827c5 100644--- a/internal/provider/planquota.go+++ b/internal/provider/planquota.go@@ -655,26 +655,28 @@ func PlanQuotas(ctx context.Context) []SubscriptionQuota {if p.Hidden || p.Off || p.Account != nil || p.Key == "" {continue}- src, ok := planQuotaSourceOf(p)- if !ok {- continue- }- keys := []string{p.Key}- names := []string{p.KeyName}+ keys := []KeyAccount{p.first()}for _, k := range p.Keys {if !k.Off && k.Key != "" && k.Key != p.Key {- keys, names = append(keys, k.Key), append(names, k.Name)+ keys = append(keys, k)}}- for i, k := range keys {+ for _, k := range keys {+ // each key told at its own plan's source: a GLM Coding Plan+ // key beside a pay-as-you-go one (KeyAccount.Plan)+ q := p.atKeyPlan(k.Plan)+ src, ok := planQuotaSourceOf(q)+ if !ok {+ continue+ }user := ""if len(keys) > 1 {- if user = names[i]; user == "" {- user = Mask(k)+ if user = k.Name; user == "" {+ user = Mask(k.Key)}}if wantsCard(ctx, p.ID, user) {- jobs = append(jobs, job{p, src, k, user})+ jobs = append(jobs, job{q, src, k.Key, user})}}}diff --git a/internal/provider/presets.go b/internal/provider/presets.goindex e969f2ea8..04080ae85 100644--- a/internal/provider/presets.go+++ b/internal/provider/presets.go@@ -41,6 +41,12 @@ type PresetDef struct {Regions []Region `json:"regions,omitempty"` // base-URL choices (a relay's regional endpoints, a vendor's plans)// RegionLabel names what the Regions choose between, "Region" if unset.RegionLabel string `json:"regionLabel,omitempty"`+ // KeyPlans: each key may be on a Region of its own (KeyAccount.Plan),+ // a vendor whose plans and pay as you go are sold on keys of their own+ // that only their own endpoints take (Volcengine's Coding and Agent+ // Plans beside its pay as you go, yckonnnn on X). Not a relay's+ // regions, where one key works at all of them.+ KeyPlans bool `json:"keyPlans,omitempty"`// HeaderHints name optional request headers the vendor documents, which// the editor offers to add; their values are the user's to fill in.HeaderHints []string `json:"headerHints,omitempty"`@@ -170,14 +176,14 @@ var presets = []PresetDef{// sent to the pay-as-you-go one is told it has no balance. The plan// serves the Responses API at /api/v1 as well: its tool pages give// it for Codex, wire_api = "responses" (#306)- RegionLabel: "Plan", Regions: []Region{+ RegionLabel: "Plan", KeyPlans: true, Regions: []Region{{ID: "api", Name: "Pay as you go", Chat: "https://open.bigmodel.cn/api/paas/v4", Anthropic: "https://open.bigmodel.cn/api/anthropic"},{ID: "coding", Name: "Coding Plan", Chat: "https://open.bigmodel.cn/api/coding/paas/v4", Responses: "https://open.bigmodel.cn/api/v1", Anthropic: "https://open.bigmodel.cn/api/anthropic"},}},{ID: "zai", Name: "Z.ai", Icon: "zai", Kind: KindVendor, Catalog: "zhipuai",Chat: "https://api.z.ai/api/paas/v4", Anthropic: "https://api.z.ai/api/anthropic",Website: "https://z.ai", KeysURL: "https://z.ai/manage-apikey/apikey-list",- RegionLabel: "Plan", Regions: []Region{+ RegionLabel: "Plan", KeyPlans: true, Regions: []Region{{ID: "api", Name: "Pay as you go", Chat: "https://api.z.ai/api/paas/v4", Anthropic: "https://api.z.ai/api/anthropic"},{ID: "coding", Name: "Coding Plan", Chat: "https://api.z.ai/api/coding/paas/v4", Responses: "https://api.z.ai/api/v1", Anthropic: "https://api.z.ai/api/anthropic"},}},@@ -192,14 +198,14 @@ var presets = []PresetDef{{ID: "stepfun", Name: "StepFun", Icon: "stepfun-color", Kind: KindVendor, Catalog: "stepfun-ai-step-plan, stepfun-ai",Chat: "https://api.stepfun.ai/step_plan/v1", Anthropic: "https://api.stepfun.ai/step_plan",Website: "https://platform.stepfun.ai", KeysURL: "https://platform.stepfun.ai/interface-key",- RegionLabel: "Plan", Regions: []Region{+ RegionLabel: "Plan", KeyPlans: true, Regions: []Region{{ID: "plan", Name: "Step Plan", Chat: "https://api.stepfun.ai/step_plan/v1", Anthropic: "https://api.stepfun.ai/step_plan"},{ID: "api", Name: "Pay as you go", Chat: "https://api.stepfun.ai/v1", Anthropic: "https://api.stepfun.ai"},}},{ID: "stepfun-cn", Name: "StepFun (China)", Icon: "stepfun-color", Kind: KindVendor, Catalog: "stepfun-step-plan, stepfun",Chat: "https://api.stepfun.com/step_plan/v1", Anthropic: "https://api.stepfun.com/step_plan",Website: "https://platform.stepfun.com", KeysURL: "https://platform.stepfun.com/interface-key",- RegionLabel: "Plan", Regions: []Region{+ RegionLabel: "Plan", KeyPlans: true, Regions: []Region{{ID: "plan", Name: "Step Plan", Chat: "https://api.stepfun.com/step_plan/v1", Anthropic: "https://api.stepfun.com/step_plan"},{ID: "api", Name: "Pay as you go", Chat: "https://api.stepfun.com/v1", Anthropic: "https://api.stepfun.com"},}},@@ -215,7 +221,7 @@ var presets = []PresetDef{Chat: "https://token-plan-cn.xiaomimimo.com/v1", Responses: "https://token-plan-cn.xiaomimimo.com/v1", Anthropic: "https://token-plan-cn.xiaomimimo.com/anthropic",Note: "Token Plan · pay as you go",Website: "https://platform.xiaomimimo.com", KeysURL: "https://platform.xiaomimimo.com/token-plan",- Regions: []Region{+ KeyPlans: true, Regions: []Region{{ID: "plan-cn", Name: "Plan · China", Chat: "https://token-plan-cn.xiaomimimo.com/v1", Responses: "https://token-plan-cn.xiaomimimo.com/v1", Anthropic: "https://token-plan-cn.xiaomimimo.com/anthropic", Catalog: "xiaomi-token-plan-cn, xiaomi"},{ID: "plan-sgp", Name: "Plan · Singapore", Chat: "https://token-plan-sgp.xiaomimimo.com/v1", Responses: "https://token-plan-sgp.xiaomimimo.com/v1", Anthropic: "https://token-plan-sgp.xiaomimimo.com/anthropic", Catalog: "xiaomi-token-plan-sgp, xiaomi"},{ID: "plan-ams", Name: "Plan · Europe", Chat: "https://token-plan-ams.xiaomimimo.com/v1", Responses: "https://token-plan-ams.xiaomimimo.com/v1", Anthropic: "https://token-plan-ams.xiaomimimo.com/anthropic", Catalog: "xiaomi-token-plan-ams, xiaomi"},@@ -232,7 +238,7 @@ var presets = []PresetDef{Chat: "https://qianfan.baidubce.com/v2/tokenplan/personal", Responses: "https://qianfan.baidubce.com/v2/tokenplan/personal", Anthropic: "https://qianfan.baidubce.com/anthropic/tokenplan/personal",Note: "Token Plan · pay as you go",Website: "https://cloud.baidu.com/doc/qianfan/s/Dmrabu8b6", KeysURL: "https://console.bce.baidu.com/qianfan/resource/token-plan",- RegionLabel: "Plan", Regions: []Region{+ RegionLabel: "Plan", KeyPlans: true, Regions: []Region{{ID: "personal", Name: "Token Plan Personal", Chat: "https://qianfan.baidubce.com/v2/tokenplan/personal", Responses: "https://qianfan.baidubce.com/v2/tokenplan/personal", Anthropic: "https://qianfan.baidubce.com/anthropic/tokenplan/personal"},{ID: "team", Name: "Token Plan Enterprise", Chat: "https://qianfan.baidubce.com/v2/tokenplan/team", Responses: "https://qianfan.baidubce.com/v2/tokenplan/team", Anthropic: "https://qianfan.baidubce.com/anthropic/tokenplan/team"},{ID: "api", Name: "Pay as you go", Chat: "https://qianfan.baidubce.com/v2", Responses: "https://qianfan.baidubce.com/v2", Anthropic: "https://qianfan.baidubce.com/anthropic",@@ -268,7 +274,7 @@ var presets = []PresetDef{Chat: "https://api.lkeap.cloud.tencent.com/plan/v3", Anthropic: "https://api.lkeap.cloud.tencent.com/plan/anthropic",Note: "Token Plan · pay as you go",Website: "https://cloud.tencent.com/document/product/1823/130060", KeysURL: "https://console.cloud.tencent.com/tokenhub/tokenplan",- Regions: []Region{+ KeyPlans: true, Regions: []Region{{ID: "plan", Name: "Plan · China", Chat: "https://api.lkeap.cloud.tencent.com/plan/v3", Anthropic: "https://api.lkeap.cloud.tencent.com/plan/anthropic",Website: "https://cloud.tencent.com/document/product/1823/130060", KeysURL: "https://console.cloud.tencent.com/tokenhub/tokenplan",Models: []string{"tc-code-latest", "glm-5.3", "glm-5.3-flash", "glm-5.2", "glm-5.1", "glm-5", "kimi-k3", "kimi-k2.7-code",@@ -296,7 +302,7 @@ var presets = []PresetDef{Chat: "https://api.modelarts-maas.com/plan/v2", Anthropic: "https://api.modelarts-maas.com/plan/anthropic",Note: "Token Plan · 西南-贵阳一",Website: "https://support.huaweicloud.com/Token-plan-maas/tokenplan-maas-0001.html", KeysURL: "https://console.huaweicloud.com/modelarts/?#/model-studio/authmanage",- RegionLabel: "Plan", Regions: []Region{+ RegionLabel: "Plan", KeyPlans: true, Regions: []Region{{ID: "plan", Name: "Token Plan", Chat: "https://api.modelarts-maas.com/plan/v2", Anthropic: "https://api.modelarts-maas.com/plan/anthropic"},{ID: "api", Name: "Pay as you go", Chat: "https://api.modelarts-maas.com/openai/v1", Anthropic: "https://api.modelarts-maas.com/anthropic"},},@@ -314,7 +320,7 @@ var presets = []PresetDef{Chat: "https://ark.cn-beijing.volces.com/api/coding/v3", Responses: "https://ark.cn-beijing.volces.com/api/coding/v3", Anthropic: "https://ark.cn-beijing.volces.com/api/coding",Note: "火山方舟 · Coding / Agent Plan",Website: "https://www.volcengine.com/docs/82379/1925114", KeysURL: "https://ark.volcengine.com/region:cn-beijing/apikey",- RegionLabel: "Plan", Regions: []Region{+ RegionLabel: "Plan", KeyPlans: true, Regions: []Region{{ID: "coding", Name: "Coding Plan", Chat: "https://ark.cn-beijing.volces.com/api/coding/v3", Responses: "https://ark.cn-beijing.volces.com/api/coding/v3", Anthropic: "https://ark.cn-beijing.volces.com/api/coding",Models: []string{"ark-code-latest", "doubao-seed-evolving", "doubao-seed-2.1-pro", "doubao-seed-2.1-lite", "doubao-seed-2.1-turbo","doubao-seed-2.0-mini", "minimax-m3", "glm-5.3", "glm-5.3-flash", "deepseek-v4.1-flash", "deepseek-v4-flash", "deepseek-v4-pro",@@ -496,7 +502,7 @@ var presets = []PresetDef{Chat: "https://api.siliconflow.cn/v1",Website: "https://cloud.siliconflow.cn", KeysURL: "https://cloud.siliconflow.cn/account/ak",// the international site is another account, keys and balance (in $)- Regions: []Region{+ KeyPlans: true, Regions: []Region{{ID: "cn", Name: "China", Chat: "https://api.siliconflow.cn/v1"},{ID: "intl", Name: "Global", Chat: "https://api.siliconflow.com/v1",Website: "https://cloud.siliconflow.com", KeysURL: "https://cloud.siliconflow.com/account/ak"},diff --git a/internal/provider/provider.go b/internal/provider/provider.goindex c68b0f008..995594684 100644--- a/internal/provider/provider.go+++ b/internal/provider/provider.go@@ -80,6 +80,8 @@ type Provider struct {KeyProtocol Protocol `json:"keyProtocol,omitempty"`// KeyWeight is the first key's weight (see KeyAccount.Weight).KeyWeight int `json:"keyWeight,omitempty"`+ // KeyPlan is the first key's plan (see KeyAccount.Plan).+ KeyPlan string `json:"keyPlan,omitempty"`// Base URLs, one per protocol the vendor serves natively. magpie appends// the usual paths: chat/responses bases end in /v1 (OpenAI style),@@ -437,6 +439,10 @@ type Provider struct {// Account is set when the provider is an agent the user signed in to// (see account.go); it is derived, never stored.Account *Account `json:"-"`++ // keyView is set on p.WithKey(k): p as that one key is asked with,+ // at its plan, whose keys no longer tell plans apart (plansMixed)+ keyView bool}type file struct {@@ -1026,7 +1032,7 @@ func AddCopy(p Provider, from string) (string, error) {return "", fmt.Errorf("%s is a signed-in account, which can't be copied", src.Name)}if p.Key == "" {- p.Key, p.KeyName, p.KeyProtocol, p.KeyWeight = src.Key, src.KeyName, src.KeyProtocol, src.KeyWeight+ p.Key, p.KeyName, p.KeyProtocol, p.KeyWeight, p.KeyPlan = src.Key, src.KeyName, src.KeyProtocol, src.KeyWeight, src.KeyPlanp.Keys = slices.Clone(src.Keys)p.Routing, p.Sink, p.Affinity = src.Routing, src.Sink, src.Affinity}@@ -1269,7 +1275,7 @@ func normalize(p Provider) Provider {// in for neither that token nor a project, and the provider as// found still savesp.Chat, p.Responses, p.Anthropic, p.Gemini, p.Decide = "", "", "", "", ""- p.Key, p.KeyName, p.Keys, p.KeyProtocol, p.KeyWeight = "", "", nil, "", 0+ p.Key, p.KeyName, p.Keys, p.KeyProtocol, p.KeyWeight, p.KeyPlan = "", "", nil, "", 0, ""}p.remoteMagpieEndpoints()for _, u := range []*string{&p.Chat, &p.Responses, &p.Anthropic, &p.Gemini, &p.Decide, &p.Website, &p.KeysURL} {diff --git a/internal/provider/tencent_usage.go b/internal/provider/tencent_usage.goindex 2dc61e6df..3c043628e 100644--- a/internal/provider/tencent_usage.go+++ b/internal/provider/tencent_usage.go@@ -102,7 +102,7 @@ func tencentPlanQuotas(ctx context.Context) []SubscriptionQuota {var jobs []jobkeyed := map[string]bool{}var keyless []job- for _, p := range All() {+ for _, p := range planViews(All()) {if p.Hidden || p.Off {continue}diff --git a/internal/provider/volcengine_usage.go b/internal/provider/volcengine_usage.goindex 365537d9e..13dfd4c79 100644--- a/internal/provider/volcengine_usage.go+++ b/internal/provider/volcengine_usage.go@@ -101,7 +101,7 @@ func volcPlanQuotas(ctx context.Context) []SubscriptionQuota {var jobs []jobkeyed := map[string]bool{} // the plans a provider has the access key forvar keyless []job- for _, p := range All() {+ for _, p := range planViews(All()) {if p.Hidden || p.Off {continue}