diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 682a966e3..58454894a 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -42,7 +42,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | A remote magpie's service tiers | A remote magpie's `/v1/models` gives each model the `service_tiers` its own Codex is offered on it (`codexTiers` → `codexcat.ServiceTiers`, from the same `CodexCatalog` and `codexcat.Entries` as its `/v1/codex/models`: Fast on a ChatGPT account's GPT model, the tiers of Codex's own entry on a relay's, none on a model it offers none). The local keeps the ids (`catalog.Model.Tiers` → `Entry.Tiers`), `codexListed` hands them on for the remote's models, and `codexcat.Entries` offers them to the local Codex with Codex's own names (`namedTiers`). The gateway sends the tier Codex asks for to a remote magpie as it was asked (`Request.OwnTier`, as for a provider added by its address; dropped and not sent again if refused), and the remote serves it as its own Codex's turn (#1234). A remote from before this sends no tiers, and its models are offered none, as before. The list gives every client the tiers, not only a magpie asking with `X-Magpie-Drawers`: Cindy shows its Fast switch on a model whose `service_tiers` hold `priority` (#1914, `TestModelsListTiersForEveryClient`). | [`codexcat.go`](../../internal/codexcat/codexcat.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`gateway.go`](../../internal/gateway/gateway.go), [`live.go`](../../internal/catalog/live.go) | | An endpoint's catalog | A key's provider with no catalog of its own (none named, none from a preset) is priced from the models.dev catalog whose `api` is one of its endpoints (`EndpointCatalog`, `catalog.AtEndpoint`; a trailing slash and case don't count, and an Anthropic base, kept as its root, is also matched with its `/v1`). Only when exactly one catalog is at that address, and it isn't a plan's (an id with `-plan`, or a `membershipCatalogs` one): a plan lists its membership's $0, and two catalogs at one address can't be told apart. A subscription's account never gets one. A provider at AMD's own endpoint is priced from `amd`, which lists Qwen3.8-27B at $0, a price, where its maker sells no such model and it had none (#2052); a relay's endpoint matches nothing and its model stays unpriced, never priced at a reseller's guess. `magpie model price` names the catalog, and says how to give a price when none is known. | [`models.go`](../../internal/provider/models.go), [`catalog.go`](../../internal/catalog/catalog.go) | | A membership's $0 catalog | models.dev lists every model of Kimi Code's plans (`kimi-code-plan-global`, `kimi-code-plan-cn`) and of Xiaomi MiMo's Token Plans (`xiaomi-token-plan-cn`, `-sgp`, `-ams`) at $0: what the membership charges per token, not what the model costs. `membershipCatalogs` are never read for a price (`priceCatalogs`, `makerPriceCatalogs`), so a Xiaomi MiMo model is priced at `xiaomi`'s list price at every region, and each region of the preset names its own catalog, pay as you go `xiaomi` alone (#1873). A Kimi Code provider's model is priced at the Kimi API model it is (`kimiCodeAPI`, from Kimi Code's docs: k3 and k3-256k are kimi-k3, kimi-for-coding-highspeed is kimi-k2.7-code-highspeed), and kimi-for-coding (K2.8 Preview, not on the API) is unpriced rather than free (#1370). The alias is Kimi Code's alone (`kimiCodePlans`): a relay's own `k3` keeps its own price. A catalog other than these that lists a model at $0 still prices it at $0: models.dev has truly free models (nvidia, modelscope). The Requests list names the API model it was priced as (`PricedNameFor`). | [`models.go`](../../internal/provider/models.go) | -| A key's own windows | A sub2api key given a spending limit per 5 hours, day or 7 days answers its `/v1/usage` with `rate_limits` and no `remaining` (`readSub2APIKeyLimits`). With the Balance URL set to it, the key's card shows them as the windows *5 hours*, *1 day*, *7 days*, in USD, beside a balance field the user wrote; *Check balance* and `magpie provider show` give what its fullest window has left (`Balance`). `KeyAllowance` gives routing the same windows: never waited for, read in the background at most once a minute, a failed read keeping the last, and seeded from the card's last reading (`quotas.json`) after a restart. A key bought as a plan (Kimi Code, GLM Coding Plan and Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code, Ollama Cloud: `planQuotaSourceOf`) gives routing its card's windows the same way (`planKeyWindows`, Zhipu's team quota behind a key with none of its own); the Usage page's read of its card is taken at once (`noteKeyAllowance`), and a key there that turns out pay-as-you-go, with no windows, is asked again only every 30 minutes (`keyNoWindowsAge`). Ollama Cloud's `ollama.com/api/balance` (#1888, `readOllamaPlan`) tells the plan's included allowance as one window in USD, *Month* when its period is a month long, renewing at `period.until`, and Aside while credits bought on top are left; those credits are the key's balance card (`readOllamaCredits`), and a reply that names none has no balance card rather than $0. StepFun's Step Plan is read through a sign-in, not the key, and isn't one of them. Nor are Volcengine Ark's Coding Plan and Agent Plan (#1427): their 5-hour, weekly and monthly windows are told only to the account's access key (`AccessKeyID`, `SecretAccessKey`), asked of `open.volcengineapi.com` (`GetCodingPlanUsage`, `GetAFPUsage`) and signed as Volcengine's own SDK signs (`volcSign`), so they are cards on the Usage page (`volcPlanQuotas` in `PlanQuotas`), never routing's windows. Nor is Tencent Cloud's Token Plan 企业版 (#1574): what a team plan has used of its cycle's credits (专业套餐) or tokens (轻享套餐) is told only to the account's SecretId and SecretKey (kept as `AccessKeyID`, `SecretAccessKey`), asked of `tokenhub.tencentcloudapi.com` (`DescribeTokenPlanList`, `DescribeTokenPlan`, version 2026-03-22) and signed TC3-HMAC-SHA256 (`tc3Sign`), one card per team plan (`tencentPlanQuotas`). | [`sub2api_usage.go`](../../internal/provider/sub2api_usage.go), [`key_allowance.go`](../../internal/provider/key_allowance.go), [`volcengine_usage.go`](../../internal/provider/volcengine_usage.go), [`tencent_usage.go`](../../internal/provider/tencent_usage.go) | +| A key's own windows | A sub2api key given a spending limit per 5 hours, day or 7 days answers its `/v1/usage` with `rate_limits` and no `remaining` (`readSub2APIKeyLimits`). With the Balance URL set to it, the key's card shows them as the windows *5 hours*, *1 day*, *7 days*, in USD, beside a balance field the user wrote; *Check balance* and `magpie provider show` give what its fullest window has left (`Balance`). A Balance URL at an account query left without its token (a sub2api panel's `/api/v1/user/profile`, new-api's `/api/user/self`, after the token was removed) asks the same panel's query for the key instead, the saved URL untouched (`keyQueryOf`, `BalanceQuery`), unless the user's Headers carry an Authorization or Cookie of their own. `KeyAllowance` gives routing the same windows: never waited for, read in the background at most once a minute, a failed read keeping the last, and seeded from the card's last reading (`quotas.json`) after a restart. A key bought as a plan (Kimi Code, GLM Coding Plan and Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code, Ollama Cloud: `planQuotaSourceOf`) gives routing its card's windows the same way (`planKeyWindows`, Zhipu's team quota behind a key with none of its own); the Usage page's read of its card is taken at once (`noteKeyAllowance`), and a key there that turns out pay-as-you-go, with no windows, is asked again only every 30 minutes (`keyNoWindowsAge`). Ollama Cloud's `ollama.com/api/balance` (#1888, `readOllamaPlan`) tells the plan's included allowance as one window in USD, *Month* when its period is a month long, renewing at `period.until`, and Aside while credits bought on top are left; those credits are the key's balance card (`readOllamaCredits`), and a reply that names none has no balance card rather than $0. StepFun's Step Plan is read through a sign-in, not the key, and isn't one of them. Nor are Volcengine Ark's Coding Plan and Agent Plan (#1427): their 5-hour, weekly and monthly windows are told only to the account's access key (`AccessKeyID`, `SecretAccessKey`), asked of `open.volcengineapi.com` (`GetCodingPlanUsage`, `GetAFPUsage`) and signed as Volcengine's own SDK signs (`volcSign`), so they are cards on the Usage page (`volcPlanQuotas` in `PlanQuotas`), never routing's windows. Nor is Tencent Cloud's Token Plan 企业版 (#1574): what a team plan has used of its cycle's credits (专业套餐) or tokens (轻享套餐) is told only to the account's SecretId and SecretKey (kept as `AccessKeyID`, `SecretAccessKey`), asked of `tokenhub.tencentcloudapi.com` (`DescribeTokenPlanList`, `DescribeTokenPlan`, version 2026-03-22) and signed TC3-HMAC-SHA256 (`tc3Sign`), one card per team plan (`tencentPlanQuotas`). | [`sub2api_usage.go`](../../internal/provider/sub2api_usage.go), [`key_allowance.go`](../../internal/provider/key_allowance.go), [`volcengine_usage.go`](../../internal/provider/volcengine_usage.go), [`tencent_usage.go`](../../internal/provider/tencent_usage.go) | | Account names and seats | `AccountNames` (by the account, in lower case, like `AccountCaps`) are names the user gives accounts, set by `SetAccountName` (GUI `provider/accountname`, `magpie accounts alias`); they live in providers.json only, never in a vendor's or plugin's sign-in. A GLM Coding Plan read with a key (`glmPlan`) and a ZCode account (built-in or `zcode-plugin`) whose windows' resets agree are one seat (`seatMatch`, #90/#953), shown once, on the account's card (`seatCards`, used by `quotas`, `Allotted` and `CachedCards`). A match is remembered in `seats.json` beside `quotas.json`: a failed read or a window with no reset yet is unknown and keeps the key's card off while the account is signed in; windows that disagree forget it (#1515). Cards carry `Seat` (the key provider's name, and the key's when it has several) and `Alias` (the user's name, else `Seat`), as `/v1/magpie/quotas`, `magpie quota` and `magpie accounts` do. | [`account_names.go`](../../internal/provider/account_names.go), [`account_seats.go`](../../internal/provider/account_seats.go) | | Last served | `served.json` records when each account, plan or key last answered, shown as `lastServedAt` (#570) on `/v1/magpie/quotas` and on the Usage page's own cards (`Quotas` → `cardsServed`, this computer's cards only, the caches left alone). The Usage page and the tray panel show the last-answered account in full, and a menu bar card that follows the account in use (`codex|*`) takes the one that answered within the last hour, else `InUseLogin`'s guess, else the one that answered last at all (a plugin's accounts, #1516) (`trayInUseCard`; okingkee on X: A spent, B answering, the menu bar stayed on A). `NoteServed` calls `OnServedMoved` when a provider's answers move to another account or key, and `SwitchLogin` after a switch, so the menu bar reads its cards again at once. | [`served.go`](../../internal/provider/served.go), [`trayusage.go`](../../internal/gui/trayusage.go) | | Partners | Services that pay to be listed first in the add sheet, under a heading of their own ("Partners · magpie's sponsors"). The list is `site/partners.js`, served at `usemagpie.ai/api/partners`: a change reaches users with a deploy, not a release. `Partners` never waits: it returns what was fetched last and fetches again behind the call every 6 hours (10 minutes after a failure), keeping the list in `partners.json` in the cache folder. Each entry is checked again on every read (`validPartners`): its own id, never a built-in preset's, a name, an endpoint, https only, at most 12; what only magpie's presets may set (a decision API, no key, a user endpoint) is cleared. Its logo is fetched through `FetchIcon` and kept as an uploaded icon. A partner is a preset to the rest of magpie (`Preset`, `FromPreset`, the editor), and one no longer listed still is to the providers added from it (`Seen`), without the sponsored mark. The window lists a partner in the languages it names (`langs`) only and shows its tagline in the page's language (`notes`, else `en`). `MAGPIE_PARTNERS` points it elsewhere, `off` lists none; tests list none unless they name a list. How often each listed partner was shown, opened (its row, its key page) and added is counted per UTC day (`CountPartner`, capped at 20 of each and 5 adds, kept in `partner-counts.json` in the cache folder) and sent with the next day's stats event as `magpie partner` events (`internal/stats`); nothing is counted with the stats or their usage part off. A listed partner the add sheet (or the TUI's, or `magpie providers presets`) hasn't shown yet is new (`NoticePartners` keeps those shown, as `noticed` in `partners.json`, whatever the stats); the window's add button carries a small dot for it, with its name in the title, until the sheet shows it. | [`partners.go`](../../internal/provider/partners.go), [`partner_events.go`](../../internal/provider/partner_events.go), [`site/partners.js`](../../site/partners.js) | diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index 19df9baca..fee2e634c 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -839,8 +839,10 @@ func showProvider(p provider.Provider) error { ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) if amount, ok, err := provider.Balance(ctx, p); ok { from := "" - if p.BalanceURL != "" { - from = muted.Render(" from " + p.BalanceURL + " " + p.BalancePath) + // where it was asked: a panel's key query when its account query + // has no token left to ask with + if u, field := provider.BalanceQuery(p); u != "" { + from = muted.Render(" from " + u + " " + field) } if err != nil { kv("balance", amber.Render("unavailable")+muted.Render(" "+err.Error())+from) diff --git a/internal/provider/balance.go b/internal/provider/balance.go index e827d94ce..01dd43e5a 100644 --- a/internal/provider/balance.go +++ b/internal/provider/balance.go @@ -40,6 +40,7 @@ type balanceSource struct { // balanceSourceOf is the provider's own endpoint when it named one, else // the one its host is known to have. func balanceSourceOf(p Provider) (balanceSource, bool) { + p = keyQueryOf(p) if p.BalanceURL != "" { path := balancePathOf(p) // a token saved beside it (a new-api relay's access token, its @@ -84,6 +85,7 @@ func balanceSourceOf(p Provider) (balanceSource, bool) { // balancePathOf is the balance field of a provider that named its Balance // URL. func balancePathOf(p Provider) string { + p = keyQueryOf(p) if strings.TrimSpace(p.BalancePath) != "" { return p.BalancePath } @@ -131,6 +133,60 @@ const ( sub2APIKeyUsage = "/v1/usage" ) +// tokenQueries are the account queries that only a balance token can +// ask, each with the same panel's query for a key and the field magpie +// reads from the account's reply when none is given. +var tokenQueries = []struct{ account, key, field string }{ + {sub2APIProfile, sub2APIKeyUsage, "$data.balance"}, + {newAPIUserSelf, newAPIKeyUsage, newAPIQuotaPath}, +} + +// keyQueryOf is p asking its panel's query for a key when its Balance URL +// is an account query left without the token it needs: the token removed +// after the editor's "Use …/api/v1/user/profile" (lx_78654 on Discord), +// where the key could only be refused and the card said "Allowance +// unavailable" for good. The same panel's key query is asked with the key +// instead, its field read as that query's unless the user wrote one of +// their own. The saved URL is left as the user set it; a token pasted +// again asks the account query again. One with an Authorization or Cookie +// header of the user's own still asks it as they set it. +func keyQueryOf(p Provider) Provider { + if p.BalanceURL == "" || strings.TrimSpace(p.BalanceToken) != "" { + return p + } + for k, v := range p.Headers { + if strings.TrimSpace(v) != "" && (strings.EqualFold(k, "Authorization") || strings.EqualFold(k, "Cookie")) { + return p + } + } + u, err := url.Parse(strings.TrimSpace(p.BalanceURL)) + if err != nil || u.Host == "" { + return p + } + path := strings.TrimRight(u.Path, "/") + for _, q := range tokenQueries { + base, ok := strings.CutSuffix(path, q.account) + if !ok { + continue + } + u.Path, u.RawPath, u.RawQuery, u.Fragment = base+q.key, "", "", "" + p.BalanceURL = u.String() + if f := strings.TrimSpace(p.BalancePath); f == q.field { + p.BalancePath = "" + } + return p + } + return p +} + +// BalanceQuery is the Balance URL and field the provider's balance is +// asked at, which differ from the saved ones for an account query left +// without its token (keyQueryOf). +func BalanceQuery(p Provider) (balanceURL, field string) { + p = keyQueryOf(p) + return p.BalanceURL, p.BalancePath +} + // balanceURLPath is a balance URL's path, without a slash at its end. func balanceURLPath(raw string) string { u, err := url.Parse(strings.TrimSpace(raw)) @@ -1069,6 +1125,7 @@ func Balance(ctx context.Context, p Provider) (amount string, ok bool, err error // limits, readSub2APIKeyLimits). func balanceRead(ctx context.Context, p Provider) (amount string, parts []BalancePart, ws []QuotaWindow, ok bool, err error) { ctx = p.Via(ctx) + p = keyQueryOf(p) src, ok := balanceSourceOf(p) if !ok || p.Account != nil || p.Key == "" { return "", nil, nil, false, nil @@ -1156,6 +1213,7 @@ func balanceRead(ctx context.Context, p Provider) (amount string, parts []Balanc // query for a key, whose reply tells the key's own limits when it has // some. func sub2APIKeyLimits(p Provider) bool { + p = keyQueryOf(p) return p.BalanceURL != "" && balanceURLPath(p.BalanceURL) == sub2APIKeyUsage } diff --git a/internal/provider/sub2api_usage_test.go b/internal/provider/sub2api_usage_test.go index 73611355b..850ac3448 100644 --- a/internal/provider/sub2api_usage_test.go +++ b/internal/provider/sub2api_usage_test.go @@ -604,3 +604,115 @@ func TestKeyAllowanceRenewed(t *testing.T) { KeyBalances(context.Background()) tellsSo("its usage reset, read on its card", 2) } + +// A sub2api login JWT added for the account's balance, then removed +// (lx_78654 on Discord): the editor's "Use …/api/v1/user/profile" left +// that URL behind, which the key alone can never ask, so the card said +// "Allowance unavailable" for good. Without the token, the panel's query +// for the key is asked with the key, as a key with no JWT is; the account +// query is asked again once a token is pasted again. new-api's +// /api/user/self, which its editor offers beside it, falls back to +// /api/usage/token the same way. +func TestAccountQueryWithoutTokenAsksTheKey(t *testing.T) { + keyLimitsHome(t) + const jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.c2ln" + var withKey atomic.Int32 // the account queries asked with the key + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + auth := r.Header.Get("Authorization") + switch strings.TrimRight(r.URL.Path, "/") { + case "/api/v1/user/profile": + if auth != "Bearer "+jwt { + withKey.Add(1) + w.WriteHeader(http.StatusUnauthorized) + w.Write([]byte(`{"code":"UNAUTHORIZED","message":"Invalid token"}`)) + return + } + w.Write([]byte(`{"code":0,"message":"success","data":{"id":1,"balance":12.5}}`)) + case "/v1/usage": + if auth != "Bearer sk-one" { + w.WriteHeader(http.StatusUnauthorized) + w.Write([]byte(`{"error":{"type":"authentication_error","message":"Invalid API key"}}`)) + return + } + w.Write([]byte(`{"mode":"unrestricted","isValid":true,"planName":"钱包余额","remaining":7.25,"unit":"USD","balance":7.25}`)) + case "/api/user/self": + withKey.Add(1) + w.WriteHeader(http.StatusUnauthorized) + w.Write([]byte(`{"success":false,"message":"无权进行此操作,未登录且未提供 access token"}`)) + case "/api/usage/token": + if auth != "Bearer sk-one" { + w.WriteHeader(http.StatusUnauthorized) + return + } + w.Write([]byte(`{"code":true,"message":"ok","data":{"object":"token_usage","total_granted":2000000,"total_used":500000,"total_available":1500000,"unlimited_quota":false}}`)) + default: + t.Errorf("asked %s", r.URL.Path) + } + })) + t.Cleanup(srv.Close) + card := func(id string) SubscriptionQuota { + t.Helper() + ForgetBalances() + for _, q := range KeyBalances(context.Background()) { + if q.Provider == id { + return q + } + } + t.Fatalf("no card for %s", id) + return SubscriptionQuota{} + } + // as the editor saves it: the URL and field its "Use" button set + p := Provider{ID: "sub2", Name: "Sub2API", Chat: srv.URL + "/v1", Key: "sk-one", + BalanceURL: srv.URL + "/api/v1/user/profile", BalancePath: "$data.balance", BalanceToken: jwt} + if err := Save(p); err != nil { + t.Fatal(err) + } + if q := card(p.ID); q.Error != "" || q.Balance != "$12.50" { + t.Fatalf("with the JWT: %+v", q) + } + // Remove, and save + p.BalanceToken = "" + if err := Save(p); err != nil { + t.Fatal(err) + } + if q := card(p.ID); q.Error != "" || q.Balance != "$7.25" { + t.Fatalf("the JWT removed: %+v", q) + } + if u, field := BalanceQuery(p); u != srv.URL+"/v1/usage" || field != "" { + t.Fatalf("asked at %q %q", u, field) + } + saved, err := Find(p.ID) + if err != nil || saved.BalanceURL != srv.URL+"/api/v1/user/profile" || saved.BalancePath != "$data.balance" { + t.Fatalf("the saved URL changed: %+v %v", saved, err) + } + // a token pasted again asks the account again + p.BalanceToken = jwt + if err := Save(p); err != nil { + t.Fatal(err) + } + if q := card(p.ID); q.Balance != "$12.50" { + t.Fatalf("the JWT again: %+v", q) + } + + // new-api's account query, its token removed + n := Provider{ID: "newapi", Name: "Relay", Chat: srv.URL + "/v1", Key: "sk-one", + Headers: map[string]string{"New-Api-User": "42"}, BalanceURL: srv.URL + "/api/user/self/", BalancePath: newAPIQuotaPath} + if got, ok, err := Balance(context.Background(), n); err != nil || !ok || got != "$3.00" { + t.Fatalf("new-api without its token: %q %v %v", got, ok, err) + } + // a field of the user's own is theirs + n.BalancePath = "$data.total_used / 500000" + if got, _, err := Balance(context.Background(), n); err != nil || got != "$1.00" { + t.Fatalf("own field: %q %v", got, err) + } + if withKey.Load() != 0 { + t.Fatalf("an account query was asked with the key %d times", withKey.Load()) + } + // one that authenticates the account query by a header of its own + // still asks it as set + n.BalancePath = "" + n.Headers = map[string]string{"Authorization": "tok"} + if _, _, err := Balance(context.Background(), n); err == nil || withKey.Load() != 1 { + t.Fatalf("own Authorization: %v, asked %d", err, withKey.Load()) + } +}