diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 5f5c4914c..57feaa171 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -70,7 +70,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Codex's free auto-review | OpenAI made Codex's Auto-review free for users signed in through a ChatGPT account (silverzhou on Discord), so a `codex-auto-review` call through the Codex subscription is priced at nothing (`ListPrice` → `codexReviewFree`, `provider.ChatGPTReviewFree`), not at GPT-5.6 Luna's price (`pricedNames`), and the Requests list names no model it is priced as (`PricedNameFor`). Not on a Free plan, where it spends the allowance (cybercaius), read from the plan Codex is signed in to now; a Codex signed out since counts as a paid plan, as the gateway's caps take it (`freeOnChatGPT`). The same model through an API key, the ChatGPT API subscription or a relay, and a review that followed the session to another model, keep their price; a price the user set wins. Every call is priced as it is read, so rows logged before are free too; the price views' cache keys on each account's plan (`usagePriceCacheKey`). Guarded by `TestAutoReviewFreeOnChatGPTSignIn` and `usage.TestAutoReviewFreeOnChatGPT`. | | A lab's models | models.dev keeps two catalogs: `api.json`, each provider's models with that host's prices, and `models.json`, each lab's models with only what is the model's on every host (name, window, reply limit, thinking, inputs, release), no price. `Sync` keeps the second beside the first as `labs.json` (`LabsPath`, `syncLabs`: best effort, through a rename, a failed fetch keeping the last; a catalog with none beside it is `Stale` once a process, so it comes at the next look). A model only a lab lists, no provider (models.dev took the gated Claude Mythos 5.1 out of anthropic's list in #11327 and kept its lab file), is voted into the same tables as a listed one (`loadGen`, `labs`), so `ContextOf`, `OutputOf`, `NameOf`, `Thinks`, `SeesImages` and every entry built on them know it wherever a vendor's or an account's list has it; a thinking one with no levels takes the levels of the newest of its family a provider gives them (`labKinEfforts`: Mythos 5.1 takes Mythos 5's). A model a provider lists keeps what providers say of it. `catalog.Describe` builds a model from these for a list that names an id alone. `TestLabOnlyModelIsKnown`, `TestLabsLeaveListedModels`, `TestSyncKeepsLabs`, `TestAnthropicKeyGatedModelDescribed` (iebb on Discord). | [`labs.go`](../../internal/catalog/labs.go), [`catalog.go`](../../internal/catalog/catalog.go) | | A Claude account's models | magpie never asks Anthropic with a Claude sign-in, so a Claude account's list is models.dev's anthropic list and what Anthropic told the account's Claude Code beyond it. Claude Code keeps that in its `.claude.json` from its own bootstrap: `additionalModelOptionsCache` (models its /model picker offers beyond its own; a `null` value or a `disabled` one is not a model), `modelAccessCache` (`entitled` per API id) and `additionalModelCostsCache` (Anthropic's prices). `claudeModels` reads the file of Claude Code's own sign-in (`claudeProfilePath`) and of each saved account's directory (`claudeAccountDir`), through `filememo`, and adds each model none of them lists, described by `catalog.Describe` and priced as Anthropic told it. `Account.Lists` for a Claude account goes by its own file (`claudeLists`: the saved directory's, or Claude Code's own when its `oauthAccount` is that account, the one Anthropic answered last): a model it isn't entitled to is out, so routing tries the accounts entitled to a gated model first; with no file, every model is taken to be in, as before. `ListPrice` of a provider whose catalogs include anthropic falls back to that price after every catalog (`claudeCodePrice`). The agent's own Claude Code model picker (`claudeOwn`) offers what `ClaudeCodeModels` gives for the account signed in here; a WSL distro's keeps the catalog's. Not done: a Claude Code that never started on a saved account has no file, so its gated models show only once it has run there. `TestClaudeAccountListsGatedModels`. | [`claude_code_models.go`](../../internal/provider/claude_code_models.go), [`account.go`](../../internal/provider/account.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`claude.go`](../../internal/agent/claude.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`). Kimi Code's `/usages` (`readKimiCode`) is read as kimi-cli and kimi-code read it: the week's `usage` and each `limits[]` window as counts, and the shares in `usages` (`limit_5h`, `limit_7d`, and `limit_month_total` as a *Month* window renewing at its `reset_time`, lidazi2016 on Discord); a window told both ways is the share's, and `limit_month_code`, the part of the month code used, is no window. `TestReadKimiCode`, `TestReadKimiCodeMonth`. 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; the same reply's period end is the Credits window's reset, left off once it has passed (#2454); a key whose plan was never read has its two windows alone. On Go, GOAT and Pro the month is counted in Command Code's usage-value credits, not dollars (GOAT's 70 are $100 of a model like DeepSeek V4.1 Flash, $70 of GLM-5.2), so the window says "28.80 / 70.00 credits" with bought credits as "+ $5.00 extra" beside it; Max, Ultra and Teams Pro keep the CLI's dollar pool, and Provider, pay as you go, has no month (`cmdPlans`, as the plugin since 0.1.20, plugins #556). 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. ModelScope's API-Inference token is told its 魔粒 at the OpenAPI's `modelscope.cn/openapi/v1/magicubes/balance` (`readModelScope`, jiabubu on Discord): `available_balance`, which leaves out what running tasks have frozen, as the balance card; the page's daily list (`/magicubes/transactions`) isn't in the OpenAPI, so what is spent a day is the card's own trend. 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, Mistral: `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`). Kimi Code's `/usages` (`readKimiCode`) is read as kimi-cli and kimi-code read it: the week's `usage` and each `limits[]` window as counts, and the shares in `usages` (`limit_5h`, `limit_7d`, and `limit_month_total` as a *Month* window renewing at its `reset_time`, lidazi2016 on Discord); a window told both ways is the share's, and `limit_month_code`, the part of the month code used, is no window. `TestReadKimiCode`, `TestReadKimiCodeMonth`. 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; the same reply's period end is the Credits window's reset, left off once it has passed (#2454); a key whose plan was never read has its two windows alone. On Go, GOAT and Pro the month is counted in Command Code's usage-value credits, not dollars (GOAT's 70 are $100 of a model like DeepSeek V4.1 Flash, $70 of GLM-5.2), so the window says "28.80 / 70.00 credits" with bought credits as "+ $5.00 extra" beside it; Max, Ultra and Teams Pro keep the CLI's dollar pool, and Provider, pay as you go, has no month (`cmdPlans`, as the plugin since 0.1.20, plugins #556). 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. A Le Chat plan's Vibe key (Pro, Student, Team) is told its month of Mistral Vibe at `api.mistral.ai/v1/billing/budget`, as Mistral's Vibe CLI reads it (`mistral_plan.go`, dhanyqaz on Discord): `vibe_budget` as one *Month* window in its currency, Aside while pay-as-you-go is on, and the plan's name from `billing/subscription` (EDU is Student); a key with no Vibe budget, a la Plateforme key among them, has no card, and Le Chat's own message limits are told nowhere. ModelScope's API-Inference token is told its 魔粒 at the OpenAPI's `modelscope.cn/openapi/v1/magicubes/balance` (`readModelScope`, jiabubu on Discord): `available_balance`, which leaves out what running tasks have frozen, as the balance card; the page's daily list (`/magicubes/transactions`) isn't in the OpenAPI, so what is spent a day is the card's own trend. 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 relay's balance found | A provider added by hand, or from a relay's preset, with a key and no Balance URL, at no host magpie knows a query for, is asked where relays tell a key its balance: the base's origin's `/v1/usage` (sub2api, `$remaining`), then `/api/usage/token` (new-api, `$data.total_available / 500000`), with the key's own auth and headers (`probesBalance`, `probeBalance`). A 200 whose field reads is the query; it is kept in memory for the origins and key for 24 hours and then looked for again, so a relay that moved to other software is not read at a query that now means something else. When the look finds nothing, the old query stays while it turns the key away (401/403, so the card says so) or the relay is down. Finding none is kept for 6 hours (5 minutes when the relay couldn't be reached). Nothing is written to the provider: the card reads the found URL, `BalanceQuery` names it, and the editor shows it under the Balance URL (`BalanceFound`, `balanceFound` in /api/providers and the check's reply; `balfound.js`), with Use to copy it into the fields so a wrong amount can be put right. None found means no card (`errNoBalance`) and, from the editor's check, *No balance at /v1/usage or /api/usage/token*. Never asked: a model vendor's or local server's preset host, this computer, OpenCode and the Cline API (`noProbeHosts`), a plan's windows (`planQuotaSourceOf`). A hand-added yylx.io relay showed no balance until its operator had the user import it again (11-05). | [`balance_probe.go`](../../internal/provider/balance_probe.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 name picks its account wherever the account's own name does (`AccountByName`): the CLI's `accountNamed` (switch, forget, alias), the pool's `--accounts`, and `accountRef` (caps, models, weights, concurrency) after an exact name. It is refused when two accounts have it or it is another account's email or name, so it never picks by guess; `accountRef` then finds no account, as the GUI passes exact names (StringKe in #4532, `TestAccountsAliasPicksTheAccount`). 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 the plugin's, else `Seat`) with `Named` when it is the user's own, which Hide accounts leaves in sight (#3656), as `/v1/magpie/quotas`, `magpie quota` and `magpie accounts` do. Records (a trace's `who`, usage's `ProviderAccount`) keep the vendor's name, the key the user's name is kept by, and every list of them looks the name up as it is shown (`AccountShown`, `AccountShownOf`, `AccountRef.Shown`), so a request from before a rename reads by the new name too: the Routing page's accounts and requests (`userShown` in `plugins/routing/client.js`, from `/api/providers`' `accountNames`), its Several accounts pools (`onOf`), the Usage page's Accounts and the request log's Account filter (`usageapi`), `magpie usage`, and a gateway key's accounts (`AccountNames`, `/api/caller-keys`). Before plugins#310 (a renamed Kiro account read by its old name on every request after) those showed the vendor's name. An account with no name of the user's own goes by the name its plugin's `usage()` gives it (`PluginUserOf`, the `user` of its last read: `loginUsageCache`, else `quotas.json`), else by its id: a Huawei Cloud CodeArts account kept by its IAM id `iam:::user:` reads as the masked phone its card shows (#4416). `AccountShown`, `AccountShownOf` and `AccountLabelOf` (cards' `Alias`, `magpie accounts`, usageapi's Account filter, the quota alert) apply it, and the GUI has it as `/api/providers`' `accountUsers` (`accountShownOf` in app.js: the editor's rows, the per-account proxy lines, Routing's `userShown`, Hide accounts). The id stays the key everything is kept by; nothing stored changes. A read that fails keeps the last good `user`; nothing read yet, or a plugin whose windows are all model pools (not kept in `quotas.json`) after a restart, is its id until the next read. | [`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) | diff --git a/internal/provider/mistral_plan.go b/internal/provider/mistral_plan.go new file mode 100644 index 000000000..e9912bc34 --- /dev/null +++ b/internal/provider/mistral_plan.go @@ -0,0 +1,106 @@ +package provider + +import ( + "context" + "encoding/json" + "strings" + "time" +) + +// Mistral's Le Chat plans (Pro, Student, Team) come with a month of Mistral +// Vibe, which the plan's Vibe key (chat.mistral.ai/code/extensions?focus=key) +// is told at the billing API on api.mistral.ai, as Mistral's own Vibe CLI +// reads it (mistralai/mistral-vibe, vibe/app_server/_billing.py and +// _account.py): GET /v1/billing/budget for the month's budget, and +// GET /v1/billing/subscription for the plan it is on (dhanyqaz on Discord, +// a Student plan). Le Chat's own message limits are told nowhere. +const ( + mistralBudgetURL = "https://api.mistral.ai/v1/billing/budget" + mistralSubscriptionURL = "https://api.mistral.ai/v1/billing/subscription" +) + +// mistralPlanTitles are the plans billing names, as Vibe titles them. +var mistralPlanTitles = map[string]string{ + "FREE": "Free", + "INDIVIDUAL": "Pro", + "EDU": "Student", + "TEAM": "Team", +} + +// mistralBudget: {"vibe_budget":{"usage_percentage":42.5, +// "initial_budget":300.0,"currency":"EUR","reset_at":"2026-11-01T00:00:00Z", +// "payg_enabled":false},"api_budget":{…}} +type mistralBudget struct { + Vibe *struct { + UsagePercentage float64 `json:"usage_percentage"` + InitialBudget float64 `json:"initial_budget"` + Currency string `json:"currency"` + ResetAt string `json:"reset_at"` + PaygEnabled *bool `json:"payg_enabled"` + } `json:"vibe_budget"` +} + +// mistralSubscription: {"plan_name":"INDIVIDUAL","payg_enabled":true, +// "vibe_payg_enabled":true,"enterprise":false} +type mistralSubscription struct { + PlanName string `json:"plan_name"` + VibePaygEnabled *bool `json:"vibe_payg_enabled"` +} + +// readMistralBudget is a Mistral key's Vibe month: what share of the +// budget is used, in the budget's currency, and when it resets. A key with +// no Vibe budget (a la Plateforme key, or none in its plan) has no +// windows, and no card. With pay-as-you-go on (the budget's own, else +// payg, the subscription's), what goes past the budget is billed rather +// than stopped, so the window doesn't stop the models. +func readMistralBudget(b []byte, payg *bool) ([]QuotaWindow, error) { + var r mistralBudget + if err := json.Unmarshal(b, &r); err != nil { + return nil, err + } + v := r.Vibe + if v == nil || v.InitialBudget <= 0 { + return []QuotaWindow{}, nil + } + used := max(0, v.UsagePercentage) + w := QuotaWindow{Name: "Month", Used: min(100, used), Limit: v.InitialBudget, + Amount: v.InitialBudget * used / 100, Unit: strings.ToUpper(strings.TrimSpace(v.Currency))} + if t, err := time.Parse(time.RFC3339, v.ResetAt); err == nil { + w.ResetsAt = &t + w.Span = t.Sub(t.AddDate(0, -1, 0)) + } + if v.PaygEnabled != nil { + payg = v.PaygEnabled + } + w.Aside = payg != nil && *payg + return []QuotaWindow{w}, nil +} + +func readMistralPlan(b []byte) (string, []QuotaWindow, error) { + ws, err := readMistralBudget(b, nil) + return "", ws, err +} + +// mistralKeyWindows is readMistralBudget's window with the plan it is on, +// asked only of a key that has a budget; the card stands without its +// name when billing/subscription can't be read. +func mistralKeyWindows(ctx context.Context, src planQuotaSource, key string) (string, []QuotaWindow, error) { + b, err := planBody(ctx, src, key) + if err != nil { + return "", nil, err + } + ws, err := readMistralBudget(b, nil) + if err != nil || len(ws) == 0 { + return "", ws, err + } + var sub mistralSubscription + if sb, err := planBody(ctx, planQuotaSource{url: mistralSubscriptionURL, bearer: true}, key); err == nil && json.Unmarshal(sb, &sub) == nil { + ws, _ = readMistralBudget(b, sub.VibePaygEnabled) + } + name := strings.ToUpper(strings.TrimSpace(sub.PlanName)) + plan := mistralPlanTitles[name] + if plan == "" { + plan = strings.TrimSpace(sub.PlanName) + } + return plan, ws, nil +} diff --git a/internal/provider/mistral_plan_test.go b/internal/provider/mistral_plan_test.go new file mode 100644 index 000000000..5bd584521 --- /dev/null +++ b/internal/provider/mistral_plan_test.go @@ -0,0 +1,118 @@ +package provider + +import ( + "context" + "crypto/tls" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +// A Le Chat plan's Vibe key (dhanyqaz on Discord, a Student plan) is told +// its month of Vibe at Mistral's billing API, as Vibe reads it: the share +// used in euros, the reset, and the plan's name; a key with no Vibe budget +// has no card, and one refused says what Mistral said. The bodies are +// Vibe's own fixtures (tests/app_server/test_billing.py, test_account.py). +func TestMistralVibeBudget(t *testing.T) { + type reply struct { + status int + body string + } + var budget, sub reply + var auths []string + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + auths = append(auths, r.Host+" "+r.Header.Get("Authorization")) + var rep reply + switch r.URL.Path { + case "/v1/billing/budget": + rep = budget + case "/v1/billing/subscription": + rep = sub + default: + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(rep.status) + w.Write([]byte(rep.body)) + })) + t.Cleanup(srv.Close) + addr := srv.Listener.Addr().String() + old := http.DefaultClient.Transport + http.DefaultClient.Transport = &http.Transport{ + DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) { + return (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, network, addr) + }, + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + } + t.Cleanup(func() { http.DefaultClient.Transport = old }) + + p := Provider{ID: "mistral", Chat: "https://api.mistral.ai/v1", Key: "vibe-key"} + src, ok := planQuotaSourceOf(p) + if !ok || src.url != mistralBudgetURL || src.sure { + t.Fatalf("source: %+v %v, want the budget, not sure", src, ok) + } + read := func() (string, []QuotaWindow, error) { + auths = nil + plan, ws, _, err := planKeyWindows(context.Background(), p, src, p.Key) + return plan, ws, err + } + const vibe = `{"vibe_budget":{"usage_percentage":42.5,"initial_budget":300.0,"currency":"EUR","reset_at":"2026-11-01T00:00:00Z","payg_enabled":false},"api_budget":{"usage_percentage":3.0,"initial_budget":50.0,"currency":"EUR","reset_at":"2026-11-01T00:00:00Z"}}` + + budget = reply{200, vibe} + sub = reply{200, `{"plan_name":"EDU","payg_enabled":true,"vibe_payg_enabled":true,"enterprise":false}`} + plan, ws, err := read() + if err != nil || plan != "Student" || len(ws) != 1 { + t.Fatalf("student: %q %+v %v", plan, ws, err) + } + w := ws[0] + reset := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC) + if w.Name != "Month" || w.Used != 42.5 || w.Limit != 300 || w.Amount != 127.5 || w.Unit != "EUR" || w.ResetsAt == nil || !w.ResetsAt.Equal(reset) || w.Span != 31*24*time.Hour { + t.Errorf("window: %+v", w) + } + if w.Aside { + t.Error("the budget's own payg_enabled false is the window's, over the subscription's") + } + for _, a := range auths { + if a != "api.mistral.ai Bearer vibe-key" { + t.Errorf("asked %q, want api.mistral.ai with the key as a Bearer", a) + } + } + if len(auths) != 2 { + t.Errorf("asked %d times, want the budget and the subscription", len(auths)) + } + + // pay-as-you-go the subscription's alone: billed past the budget + budget = reply{200, `{"vibe_budget":{"usage_percentage":120,"initial_budget":300.0,"currency":"EUR","reset_at":"2026-11-01T00:00:00Z"}}`} + sub = reply{200, `{"plan_name":"INDIVIDUAL","vibe_payg_enabled":true}`} + if plan, ws, err := read(); err != nil || plan != "Pro" || len(ws) != 1 || !ws[0].Aside || ws[0].Used != 100 || ws[0].Amount != 360 { + t.Errorf("pro, payg: %q %+v %v", plan, ws, err) + } + + // the subscription unread: the window stands, with no plan name + budget, sub = reply{200, vibe}, reply{500, `{"message":"boom"}`} + if plan, ws, err := read(); err != nil || plan != "" || len(ws) != 1 || ws[0].Used != 42.5 { + t.Errorf("no subscription: %q %+v %v", plan, ws, err) + } + + // a key with no Vibe budget: no windows, so no card, and nothing more asked + for _, body := range []string{`{"vibe_budget":null,"api_budget":{"usage_percentage":3,"initial_budget":50}}`, `{"vibe_budget":{"usage_percentage":0,"initial_budget":0}}`, `{}`} { + budget = reply{200, body} + if _, ws, err := read(); err != nil || len(ws) != 0 || len(auths) != 1 { + t.Errorf("%s: %+v %v, asked %d", body, ws, err, len(auths)) + } + } + + // refused: Mistral's words + budget = reply{401, `{"message":"Invalid API Key"}`} + if _, _, err := read(); err == nil || !strings.Contains(err.Error(), "Invalid API Key") { + t.Errorf("refused: %v", err) + } + budget = reply{403, `{"message":"Forbidden"}`} + if _, ws, err := read(); err == nil || len(ws) != 0 { + t.Errorf("a member without the permission: %+v %v, want an error, and no card from it unless one was read", ws, err) + } +} diff --git a/internal/provider/planquota.go b/internal/provider/planquota.go index 7459f984b..42d68161d 100644 --- a/internal/provider/planquota.go +++ b/internal/provider/planquota.go @@ -2,7 +2,8 @@ package provider // A plan bought with an API key — Zhipu's GLM Coding Plan (and Z.ai's), // Kimi Code, OpenCode Go, a Command Code plan, MiniMax's Coding (Token) -// Plan, Ollama Cloud's included allowance, StepFun's Step Plan, Volcengine Ark's Coding and Agent Plans and +// Plan, Ollama Cloud's included allowance, a Le Chat plan's month of Mistral +// Vibe, StepFun's Step Plan, Volcengine Ark's Coding and Agent Plans and // Tencent Cloud's Token Plan 企业版 — has windows of allowance like a // subscription's, which the vendor tells to the key (StepFun only to a // sign-in, stepfun_plan.go; Volcengine and Tencent Cloud only to the @@ -68,6 +69,10 @@ func planQuotaSourceOf(p Provider) (planQuotaSource, bool) { // Ollama Cloud's included allowance (#1888); a key with none // gets no card return planQuotaSource{ollamaBalanceURL, true, readOllamaPlan, false}, true + case "api.mistral.ai": + // a Le Chat plan's Vibe key is told its month of Vibe + // (mistral_plan.go); a key with no Vibe budget gets no card + return planQuotaSource{mistralBudgetURL, true, readMistralPlan, false}, true } } return planQuotaSource{}, false @@ -700,6 +705,10 @@ func planKeyWindows(ctx context.Context, p Provider, src planQuotaSource, key st plan, ws, err = cmdKeyWindows(ctx, src, key) return plan, ws, false, err } + if src.url == mistralBudgetURL { + plan, ws, err = mistralKeyWindows(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) {