provider: a Command Code plan key's card shows the month's credits as a meter (#2451)
tianxia3111 runs Command Code on the keyed preset with a plan's key. Its
card showed the 5-hour and weekly windows as meters, but the month's
credits only as dollars left ($5.27), with no share of the month. The
cause: billing/credits leaves out the planId, so the key's card couldn't
know the plan's monthly pool. The signed-in subscription's card gets
that pool from billing/subscriptions.
The key's card (planKeyWindows -> cmdKeyWindows) now asks
billing/subscriptions with the same key for the plan. It then makes the
month a "Credits" window beside the other two, through the same
cmdQuotaOf the subscription's card uses ("$4.78 / $10.00" on a Go plan).
- The plan id is kept per key for ten minutes, since
billing/subscriptions takes 15-20 s at times.
- The id read before still counts while the plan can't be read.
- A key whose plan was never read keeps its two windows alone.
- A pay-as-you-go key, with no windows, still gets no card.
planWindows' request and status handling move into planBody, so that
cmdKeyWindows can decode the reply itself; other vendors are unchanged.
Run:
- New TestCommandCodeKeyCardHasCredits uses the reporter's own
billing/credits reply. Its billing/subscriptions reply has the shape
the other Command Code tests use (individual-go-monthly), because the
reporter's plan id isn't known.
- With the new branch disabled by hand, the test went red: two windows,
no plan. With it, green.
- TestKeyQuotasKeepLast now answers billing/subscriptions with 503 and
still sees its two windows.
- gofmt; go vet -tags nogui for darwin, linux and windows.
- Not tried against Command Code's real API: there is no plan key here.
- Full suite (go test -timeout 45m ./..., at f1c91a99c plus this change):
every package ok except internal/gui, red only on
TestPanelJoinsFullScreenSpaces, which is #2450 (macOS 26.2, red on
main before this change).
This commit is contained in:
@@ -46,7 +46,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| 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 plugin's own price | A model no catalog prices (models.dev has no vendor's own model: Devin's SWE-2 and SWE-1.7 Lightning, Cursor's auto, Qoder's efficient) is priced at what its plugin lists it at (`ListPrice` → `pluginListPrice`, `plugin.Model.Cost`, read by `pluginPrice`: an input or output above 0, OpenCode's 0 being none), else at $0 when the plugin says the plan serves it free (`pluginFree`, `plugin.Model.Free`: Devin's Free cost tier, Qoder's and WorkBuddy's x0). Both come after every catalog, so a price a catalog gives is kept over the plugin's. Devin's plugin (0.1.18) lists each paid model at the price Devin's GetCliModelConfigs gives it (input, cached input and output per 1M tokens); a moved Devin user's calls on Devin's own models had no cost on Usage before (太陽と向日葵 on Discord, `TestPluginFreeModelCostsNothing`). A plugin that gives no price and doesn't say free leaves the model unpriced. | [`models.go`](../../internal/provider/models.go), [`plugins.go`](../../internal/provider/plugins.go), [`providers.go`](../../internal/plugin/providers.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. A Balance URL of the user's own is asked with GET, or with POST and no body when the provider's `BalanceMethod` says so (#2368: an endpoint that answers only a POST; the editor's GET/POST beside the URL, `balance.method=` on the command line); any other method is refused before anything is sent (`balanceMethodOf`). `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 platform sign-in, not the key, and isn't one of them: the sign-in is the provider's own, kept by provider id in `stepfun-auth.json` (two StepFun providers on one site can be two accounts, #2384), one card per signed-in provider; a file from before that, kept by site, is given on read to the StepFun providers on that site (`stepfunBySite`), and copies of one sign-in are renewed together. 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. A Balance URL of the user's own is asked with GET, or with POST and no body when the provider's `BalanceMethod` says so (#2368: an endpoint that answers only a POST; the editor's GET/POST beside the URL, `balance.method=` on the command line); any other method is refused before anything is sent (`balanceMethodOf`). `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`). A Command Code plan's key has its month of credits as a *Credits* window beside the 5-hour and weekly ones, as the signed-in subscription's card has (`cmdKeyWindows`, #2451): billing/credits leaves the plan out, so it is the key's billing/subscriptions plan, asked at most every ten minutes and the last one kept while it can't be read; a key whose plan was never read has its two windows alone. 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 platform sign-in, not the key, and isn't one of them: the sign-in is the provider's own, kept by provider id in `stepfun-auth.json` (two StepFun providers on one site can be two accounts, #2384), one card per signed-in provider; a file from before that, kept by site, is given on read to the StepFun providers on that site (`stepfunBySite`), and copies of one sign-in are renewed together. 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) |
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// #2451 (tianxia3111): a Command Code plan's key, on the keyed preset,
|
||||
// showed its 5-hour and weekly windows as meters and the month's credits
|
||||
// only as dollars left ($5.27). billing/credits leaves the plan out, so
|
||||
// the key's card asks billing/subscriptions for it, as the signed-in
|
||||
// subscription's card does, and the month is a meter beside the windows.
|
||||
// The reply is the reporter's own.
|
||||
func TestCommandCodeKeyCardHasCredits(t *testing.T) {
|
||||
var subs atomic.Int32
|
||||
var subsDown atomic.Bool
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Header.Get("X-Host") + r.URL.Path {
|
||||
case "api.commandcode.ai/alpha/billing/credits":
|
||||
w.Write([]byte(`{"credits":{"belowThreshold":false,"creditThreshold":0,"monthlyCredits":5.2207933742,"purchasedCredits":0,"freeCredits":0},
|
||||
"windowLimits":{"limited":true,"exceeded":null,
|
||||
"fiveHour":{"used":0.0866816244,"cap":14,"exceeded":false,"resetAt":4102444800000},
|
||||
"weekly":{"used":0.8971969678,"cap":35,"exceeded":false,"resetAt":4102444800000}},
|
||||
"sandboxAccess":true}`))
|
||||
case "api.commandcode.ai/alpha/billing/subscriptions":
|
||||
subs.Add(1)
|
||||
if subsDown.Load() {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
w.Write([]byte(`{"success":true,"data":{"planId":"individual-go-monthly","status":"active"}}`))
|
||||
default:
|
||||
t.Errorf("asked %s%s", r.Header.Get("X-Host"), r.URL.Path)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
old := http.DefaultClient.Transport
|
||||
http.DefaultClient.Transport = rewrite{srv}
|
||||
t.Cleanup(func() { http.DefaultClient.Transport = old })
|
||||
|
||||
p := Provider{ID: "commandcode", Key: "cmd-2451", Chat: "https://api.commandcode.ai/provider/v1"}
|
||||
src, _ := planQuotaSourceOf(p)
|
||||
plan, ws, _, err := planKeyWindows(context.Background(), p, src, p.Key)
|
||||
if err != nil || plan != "Go" || len(ws) != 3 {
|
||||
t.Fatalf("%v %q %+v", err, plan, ws)
|
||||
}
|
||||
if ws[0].Name != "5 hours" || ws[1].Name != "Weekly" {
|
||||
t.Errorf("windows: %+v", ws)
|
||||
}
|
||||
// Go gives $10 a month; $5.22 of it is left
|
||||
if c := ws[2]; c.Name != "Credits" || c.Display != "$4.78 / $10.00" || c.Used < 47.7 || c.Used > 47.8 {
|
||||
t.Errorf("credits: %+v", c)
|
||||
}
|
||||
|
||||
// the plan is asked again only after ten minutes, and the one read
|
||||
// before stands while it can't be read
|
||||
subsDown.Store(true)
|
||||
if _, ws, _, _ := planKeyWindows(context.Background(), p, src, p.Key); len(ws) != 3 || subs.Load() != 1 {
|
||||
t.Errorf("read again: %d asks, %+v", subs.Load(), ws)
|
||||
}
|
||||
cmdKeyPlans.Lock()
|
||||
seen := cmdKeyPlans.m[p.Key]
|
||||
seen.at = seen.at.Add(-11 * 60e9)
|
||||
cmdKeyPlans.m[p.Key] = seen
|
||||
cmdKeyPlans.Unlock()
|
||||
if plan, ws, _, _ := planKeyWindows(context.Background(), p, src, p.Key); len(ws) != 3 || plan != "Go" || subs.Load() != 2 {
|
||||
t.Errorf("plan unreadable: %d asks, %q %+v", subs.Load(), plan, ws)
|
||||
}
|
||||
|
||||
// a key whose plan was never read has its windows alone
|
||||
q := p
|
||||
q.Key = "cmd-2451-new"
|
||||
if plan, ws, _, err := planKeyWindows(context.Background(), q, src, q.Key); err != nil || plan != "" || len(ws) != 2 {
|
||||
t.Errorf("plan never read: %v %q %+v", err, plan, ws)
|
||||
}
|
||||
}
|
||||
@@ -644,6 +644,54 @@ func cmdSubscription(ctx context.Context, a cmdAuth) (id, plan string, until *ti
|
||||
return "", cmdNoPlan, nil, "", true
|
||||
}
|
||||
|
||||
// cmdKeyWindows is a Command Code key's plan card (#2451): the plan's
|
||||
// 5-hour and weekly windows, and its month of credits as one more, as
|
||||
// the signed-in subscription's card has them. billing/credits leaves the
|
||||
// plan out, so it is the key's subscription's, read at most every ten
|
||||
// minutes (billing/subscriptions takes 15–20 seconds at times), and the
|
||||
// one read before while it can't be read. A key with no windows is a
|
||||
// pay-as-you-go key: no plan, and no card.
|
||||
func cmdKeyWindows(ctx context.Context, src planQuotaSource, key string) (string, []QuotaWindow, error) {
|
||||
b, err := planBody(ctx, src, key)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
var c cmdCredits
|
||||
if err := json.Unmarshal(b, &c); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
if len(cmdWindows(c)) == 0 {
|
||||
return cmdPlanName(c.Credits.PlanID), []QuotaWindow{}, nil
|
||||
}
|
||||
if c.Credits.PlanID == "" {
|
||||
c.Credits.PlanID = cmdKeyPlanID(ctx, key)
|
||||
}
|
||||
q := cmdQuotaOf(SubscriptionQuota{}, c)
|
||||
return q.Plan, q.Windows, nil
|
||||
}
|
||||
|
||||
var cmdKeyPlans = struct {
|
||||
sync.Mutex
|
||||
m map[string]cmdSeen // plan is the subscription's id here
|
||||
}{m: map[string]cmdSeen{}}
|
||||
|
||||
func cmdKeyPlanID(ctx context.Context, key string) string {
|
||||
cmdKeyPlans.Lock()
|
||||
seen, had := cmdKeyPlans.m[key]
|
||||
cmdKeyPlans.Unlock()
|
||||
if had && time.Since(seen.at) < 10*time.Minute {
|
||||
return seen.plan
|
||||
}
|
||||
id, _, _, _, ok := cmdSubscription(ctx, cmdAuth{APIKey: key})
|
||||
if !ok {
|
||||
return seen.plan
|
||||
}
|
||||
cmdKeyPlans.Lock()
|
||||
cmdKeyPlans.m[key] = cmdSeen{id, time.Now()}
|
||||
cmdKeyPlans.Unlock()
|
||||
return id
|
||||
}
|
||||
|
||||
func cmdLoginQuota(ctx context.Context, l Login) SubscriptionQuota {
|
||||
for _, c := range cmdLogins() {
|
||||
if strings.EqualFold(c.User, l.User) {
|
||||
|
||||
@@ -38,6 +38,10 @@ func TestKeyQuotasKeepLast(t *testing.T) {
|
||||
t.Cleanup(restart)
|
||||
var down atomic.Bool
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("X-Host")+r.URL.Path == "api.commandcode.ai/alpha/billing/subscriptions" {
|
||||
w.WriteHeader(http.StatusServiceUnavailable) // the plan not known: its windows alone
|
||||
return
|
||||
}
|
||||
if r.Header.Get("X-Host")+r.URL.Path != "api.commandcode.ai/alpha/billing/credits" {
|
||||
t.Errorf("asked %s%s", r.Header.Get("X-Host"), r.URL.Path)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
|
||||
@@ -136,9 +136,9 @@ func readZhipuPlan(b []byte) (string, []QuotaWindow, error) {
|
||||
}
|
||||
|
||||
// readCommandCodePlan reads a Command Code key's /alpha/billing/credits
|
||||
// (see cmdCredits) for its plan's 5-hour and weekly windows. The dollars
|
||||
// left are the key's balance card's (readCommandCode), so not a window
|
||||
// here as on the signed-in subscription's card.
|
||||
// (see cmdCredits) for its plan's 5-hour and weekly windows. The key's
|
||||
// card is cmdKeyWindows, which adds the month's credits once it knows the
|
||||
// plan.
|
||||
func readCommandCodePlan(b []byte) (string, []QuotaWindow, error) {
|
||||
var c cmdCredits
|
||||
if err := json.Unmarshal(b, &c); err != nil {
|
||||
@@ -487,10 +487,24 @@ func readKimiCode(b []byte) (string, []QuotaWindow, error) {
|
||||
|
||||
// planWindows asks the vendor for the plan key is on and its windows.
|
||||
func planWindows(ctx context.Context, src planQuotaSource, key string) (plan string, ws []QuotaWindow, err error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, src.url, nil)
|
||||
b, err := planBody(ctx, src, key)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
plan, ws, err = src.read(b)
|
||||
if r, ok := err.(zhipuKeyRefusal); ok {
|
||||
err = zhipuRefused(src.url, r)
|
||||
}
|
||||
return plan, ws, err
|
||||
}
|
||||
|
||||
// planBody is the vendor's reply to a key asking for its plan's windows,
|
||||
// or what it said when it refused.
|
||||
func planBody(ctx context.Context, src planQuotaSource, key string) ([]byte, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, src.url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if src.bearer {
|
||||
req.Header.Set("Authorization", "Bearer "+key)
|
||||
} else {
|
||||
@@ -503,7 +517,7 @@ func planWindows(ctx context.Context, src planQuotaSource, key string) (plan str
|
||||
OpenCodeSession(req.Header, src.url)
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
return nil, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
@@ -514,19 +528,15 @@ func planWindows(ctx context.Context, src planQuotaSource, key string) (plan str
|
||||
// they subscribed in, and asks for it by the key's own member and
|
||||
// workspace (zen/go/v1/usage.ts in sst/opencode): a key another
|
||||
// member made, or one from another workspace, has none
|
||||
return "", nil, fmt.Errorf("this key has no OpenCode Go subscription: Go belongs to the member who subscribed, in that workspace, so use a key that member made there (opencode.ai, the workspace's API Keys)")
|
||||
return nil, fmt.Errorf("this key has no OpenCode Go subscription: Go belongs to the member who subscribed, in that workspace, so use a key that member made there (opencode.ai, the workspace's API Keys)")
|
||||
case res.StatusCode == http.StatusUnauthorized && openCode:
|
||||
return "", nil, fmt.Errorf("OpenCode didn't take this key (%s): it was deleted, or is mistyped", vendorSaid(b, res.Status))
|
||||
return nil, fmt.Errorf("OpenCode didn't take this key (%s): it was deleted, or is mistyped", vendorSaid(b, res.Status))
|
||||
case res.StatusCode == http.StatusUnauthorized && zhipuHost(hostOf(src.url)):
|
||||
return "", nil, zhipuRefused(src.url, zhipuKeyRefusal{vendorSaid(b, res.Status)})
|
||||
return nil, zhipuRefused(src.url, zhipuKeyRefusal{vendorSaid(b, res.Status)})
|
||||
case res.StatusCode >= 300:
|
||||
return "", nil, fmt.Errorf("%s", vendorSaid(b, res.Status))
|
||||
return nil, fmt.Errorf("%s", vendorSaid(b, res.Status))
|
||||
}
|
||||
plan, ws, err = src.read(b)
|
||||
if r, ok := err.(zhipuKeyRefusal); ok {
|
||||
err = zhipuRefused(src.url, r)
|
||||
}
|
||||
return plan, ws, err
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// zhipuKeyRefusal is Zhipu or Z.ai refusing a key itself (codes
|
||||
@@ -593,6 +603,10 @@ func vendorSaid(b []byte, status string) string {
|
||||
// a Zhipu or Z.ai key with no plan of its own is a team's, whose windows
|
||||
// are asked with type=2 (zcode_team.go), and team says so.
|
||||
func planKeyWindows(ctx context.Context, p Provider, src planQuotaSource, key string) (plan string, ws []QuotaWindow, team bool, err error) {
|
||||
if hostOf(src.url) == "api.commandcode.ai" {
|
||||
plan, ws, err = cmdKeyWindows(ctx, src, key)
|
||||
return plan, ws, false, err
|
||||
}
|
||||
plan, ws, err = planWindows(ctx, src, key)
|
||||
// a key refused is refused as a team's too
|
||||
if zhipu := strings.HasSuffix(src.url, "/api/monitor/usage/quota/limit"); zhipu && (err != nil || len(ws) == 0) && !zhipuKeyRefusedErr(err) {
|
||||
|
||||
Reference in New Issue
Block a user