diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 9da6e16ac..1a213ccff 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, 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 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 Mistral key is told its organization's month at `api.mistral.ai/v1/billing/budget`, as Mistral's Vibe CLI reads it (`mistral_plan.go`, dhanyqaz on Discord). The budget is the organization's, so every key of it gets the same `vibe_budget` and `api_budget`; which one a key spends is its kind, asked once a key of `console.mistral.ai/api/vibe/whoami` (`plan_type`). A Vibe key (`chat`) has `vibe_budget` as one *Month* window, a Studio key made in the console (`api`) has `api_budget` as *API · Month*, so the accounts' strip never adds the two; each is in the currency billing names (none when it names none), Aside while pay-as-you-go is on (the budget's own, else the subscription's `vibe_payg_enabled` for Vibe and `payg_enabled` for Studio), with the plan's name from `billing/subscription` (EDU is Student). A key whoami can't place (a failed read, no `plan_type`, Mistral Code's key) or whose budget is 0 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/gui/assets/i18n.js b/internal/gui/assets/i18n.js index bc669b2f6..d54b41d6d 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4376,6 +4376,7 @@ const I18N = { "questions": "次提问", "videos": "个视频", "Video · 24 hours": "视频 · 24 小时", + "API · Month": "API · 本月", "Video · 7 days": "视频 · 7 天", // agents' advice after a change (NOTICES) "Ante reads its catalog at start-up — restart open ante sessions to use this.": "Ante 启动时读取模型目录,需重启已打开的 ante 会话才会生效。", @@ -8998,6 +8999,7 @@ const I18N = { "A new provider with {name}'s project, credentials, headers and models, to change before adding": "新建供應商,沿用 {name} 的專案、憑據、請求頭和模型,新增前可修改", "videos": "個影片", "Video · 24 hours": "影片 · 24 小時", + "API · Month": "API · 本月", "Video · 7 days": "影片 · 7 天", // agents' advice after a change (NOTICES) "Ante reads its catalog at start-up — restart open ante sessions to use this.": "Ante 啟動時讀取模型目錄,需重啟已打開的 ante 會話才會生效。", @@ -13601,6 +13603,7 @@ const I18N = { "questions": "件の質問", "videos": "本", "Video · 24 hours": "動画 · 24 時間", + "API · Month": "API · 今月", "Video · 7 days": "動画 · 7 日", "Menu bar magpie icon": "メニューバーの magpie アイコン", "Pace {n}": "ペース {n}", @@ -18238,6 +18241,7 @@ const I18N = { "questions": "Fragen", "videos": "Videos", "Video · 24 hours": "Video · 24 Stunden", + "API · Month": "API · Monat", "Video · 7 days": "Video · 7 Tage", "Discard unsaved changes? Your changes will be lost.": "Nicht gespeicherte Änderungen verwerfen? Ihre Änderungen gehen verloren.", "This removes the selected item. Continue?": "Das ausgewählte Element wird entfernt. Fortfahren?", diff --git a/internal/gui/tests/usage-merge.test.cjs b/internal/gui/tests/usage-merge.test.cjs index 56bb107e7..af391bb86 100644 --- a/internal/gui/tests/usage-merge.test.cjs +++ b/internal/gui/tests/usage-merge.test.cjs @@ -142,3 +142,19 @@ test("a window held by a longer one used up counts as nothing left", () => { ], now); assert.deepEqual(by(c, "Credits").map((w) => [w.amount, w.limit, w.held]), [[600, 1000, 1]]); }); + +test("a Mistral Studio month never adds up with a Vibe month (dhanyqaz on Discord)", () => { + // the two keys of one Student organization, as magpie reads them: the + // Vibe key's vibe_budget and the Studio key's api_budget, both in USD + const mistral = (user, w) => ({ provider: "mistral", name: "Mistral", user, plan: "Student", windows: [w] }); + const r = merge([ + mistral("Vibe", { name: "Month", amount: 0.64, limit: 150, unit: "USD", used: 0.43 }), + mistral("Studio", { name: "API · Month", amount: 3, limit: 15, unit: "USD", used: 20 }), + ], now); + assert.deepEqual(r.windows, [], "no 'All 2 accounts' figure of 165 USD"); + const two = merge([ + mistral("Vibe", { name: "Month", amount: 0.64, limit: 150, unit: "USD", used: 0.43 }), + mistral("Vibe 2", { name: "Month", amount: 15, limit: 150, unit: "USD", used: 10 }), + ], now); + assert.equal(by(two, "Month")[0].limit, 300, "two Vibe months still add up"); +}); diff --git a/internal/provider/mistral_plan.go b/internal/provider/mistral_plan.go index e9912bc34..b9e9b9436 100644 --- a/internal/provider/mistral_plan.go +++ b/internal/provider/mistral_plan.go @@ -2,8 +2,11 @@ package provider import ( "context" + "crypto/sha256" "encoding/json" + "fmt" "strings" + "sync" "time" ) @@ -14,9 +17,19 @@ import ( // _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. +// +// The budget is the organization's, not the key's: every key of one +// organization is told the same vibe_budget and api_budget. Which of them a +// key spends is the key's kind, which console.mistral.ai's /api/vibe/whoami +// tells (plan_type "chat" for a Vibe key, "api" for a Studio key made in the +// console, "mistral_code"), as Vibe reads it (vibe/setup/auth/whoami.py) and +// reads the budget only of a chat key (_account.py). Reading vibe_budget for +// every key showed a Studio key the Vibe month (dhanyqaz on Discord: 149.36 +// of 150 on both cards, and 298.72 of 300 for the two together). const ( mistralBudgetURL = "https://api.mistral.ai/v1/billing/budget" mistralSubscriptionURL = "https://api.mistral.ai/v1/billing/subscription" + mistralWhoamiURL = "https://console.mistral.ai/api/vibe/whoami" ) // mistralPlanTitles are the plans billing names, as Vibe titles them. @@ -29,41 +42,86 @@ var mistralPlanTitles = map[string]string{ // 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":{…}} +// "payg_enabled":false},"api_budget":{"usage_percentage":3.0, +// "initial_budget":50.0,"currency":"EUR","reset_at":"2026-11-01T00:00:00Z"}} 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"` + Vibe *mistralBudgetDetail `json:"vibe_budget"` + API *mistralBudgetDetail `json:"api_budget"` +} + +type mistralBudgetDetail 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"` } // mistralSubscription: {"plan_name":"INDIVIDUAL","payg_enabled":true, // "vibe_payg_enabled":true,"enterprise":false} type mistralSubscription struct { PlanName string `json:"plan_name"` + PaygEnabled *bool `json:"payg_enabled"` 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) { +// The kinds of key whoami tells, lower-cased as Vibe reads them. +const ( + mistralChatKey = "chat" + mistralAPIKey = "api" +) + +// mistralKeyKinds: what whoami said of a key, by its hash; a key's kind +// doesn't change, so it is asked once. +var mistralKeyKinds sync.Map + +// mistralKeyKind is the key's plan_type, asked of whoami; a reply that +// can't be read is an error, never a kind. +func mistralKeyKind(ctx context.Context, key string) (string, error) { + h := sha256.Sum256([]byte(key)) + if k, ok := mistralKeyKinds.Load(h); ok { + return k.(string), nil + } + b, err := planBody(ctx, planQuotaSource{url: mistralWhoamiURL, bearer: true}, key) + if err != nil { + return "", err + } + var r struct { + PlanType *string `json:"plan_type"` + } + if err := json.Unmarshal(b, &r); err != nil || r.PlanType == nil { + return "", fmt.Errorf("mistral whoami: no plan_type in its reply") + } + k := strings.ToLower(strings.TrimSpace(*r.PlanType)) + mistralKeyKinds.Store(h, k) + return k, nil +} + +// readMistralBudget is a Mistral key's month: what share of the budget +// its kind spends is used (vibe_budget for a Vibe key, api_budget for a +// Studio key), in the currency billing names, and when it resets. A +// budget billing doesn't name, or of 0, has no windows, and no card; a +// currency it doesn't name is left unsaid rather than guessed. 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. The Studio month is "API · Month", so the +// accounts' strip never adds it to a Vibe month. +func readMistralBudget(b []byte, kind string, payg *bool) ([]QuotaWindow, error) { var r mistralBudget if err := json.Unmarshal(b, &r); err != nil { return nil, err } - v := r.Vibe + v, name := r.Vibe, "Month" + if kind == mistralAPIKey { + v, name = r.API, "API · Month" + } else if kind != mistralChatKey { + v = nil + } 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, + w := QuotaWindow{Name: name, 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 @@ -76,26 +134,41 @@ func readMistralBudget(b []byte, payg *bool) ([]QuotaWindow, error) { return []QuotaWindow{w}, nil } +// readMistralPlan is the source's reader without a key to ask whoami +// with: it tells no window, since which budget a key spends is the key's. func readMistralPlan(b []byte) (string, []QuotaWindow, error) { - ws, err := readMistralBudget(b, nil) + 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. +// mistralKeyWindows is readMistralBudget's window for the key's kind, 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. A key +// whose kind whoami doesn't tell has no card read: the organization's +// budget alone doesn't say which of its two it spends. func mistralKeyWindows(ctx context.Context, src planQuotaSource, key string) (string, []QuotaWindow, error) { + kind, err := mistralKeyKind(ctx, key) + if err != nil { + return "", nil, err + } + if kind != mistralChatKey && kind != mistralAPIKey { + return "", []QuotaWindow{}, nil + } b, err := planBody(ctx, src, key) if err != nil { return "", nil, err } - ws, err := readMistralBudget(b, nil) + ws, err := readMistralBudget(b, kind, 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) + payg := sub.VibePaygEnabled + if kind == mistralAPIKey { + payg = sub.PaygEnabled + } + ws, _ = readMistralBudget(b, kind, payg) } name := strings.ToUpper(strings.TrimSpace(sub.PlanName)) plan := mistralPlanTitles[name] diff --git a/internal/provider/mistral_plan_test.go b/internal/provider/mistral_plan_test.go index 5bd584521..f5d82666d 100644 --- a/internal/provider/mistral_plan_test.go +++ b/internal/provider/mistral_plan_test.go @@ -2,6 +2,7 @@ package provider import ( "context" + "crypto/sha256" "crypto/tls" "net" "net/http" @@ -22,11 +23,14 @@ func TestMistralVibeBudget(t *testing.T) { body string } var budget, sub reply + who := reply{200, `{"plan_type":"CHAT","plan_name":"EDU","prompt_switching_to_pro_plan":false}`} 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 "/api/vibe/whoami": + rep = who case "/v1/billing/budget": rep = budget case "/v1/billing/subscription": @@ -60,6 +64,8 @@ func TestMistralVibeBudget(t *testing.T) { plan, ws, _, err := planKeyWindows(context.Background(), p, src, p.Key) return plan, ws, err } + mistralKeyKinds.Clear() + t.Cleanup(mistralKeyKinds.Clear) 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} @@ -76,13 +82,9 @@ func TestMistralVibeBudget(t *testing.T) { 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)) + want := []string{"console.mistral.ai Bearer vibe-key", "api.mistral.ai Bearer vibe-key", "api.mistral.ai Bearer vibe-key"} + if strings.Join(auths, "|") != strings.Join(want, "|") { + t.Errorf("asked %q, want whoami at the console, then the budget and the subscription, the key as a Bearer", auths) } // pay-as-you-go the subscription's alone: billed past the budget @@ -101,6 +103,7 @@ func TestMistralVibeBudget(t *testing.T) { // 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} + // whoami is asked once a key if _, ws, err := read(); err != nil || len(ws) != 0 || len(auths) != 1 { t.Errorf("%s: %+v %v, asked %d", body, ws, err, len(auths)) } @@ -116,3 +119,128 @@ func TestMistralVibeBudget(t *testing.T) { t.Errorf("a member without the permission: %+v %v, want an error, and no card from it unless one was read", ws, err) } } + +// A Studio key (made in console.mistral.ai, whoami's plan_type "API") of +// the same organization is told the same budget body as its Vibe key, and +// spends the api_budget, not the Vibe month (dhanyqaz on Discord: the +// Studio card showed 149.36 / 150 USD, the Vibe key's, on a Student plan +// whose Studio month is 15). Its window is "API · Month", in the +// currency billing names, and never adds up with a Vibe month; a key +// whoami can't place has no card read, and Mistral Code's key none. +func TestMistralStudioBudget(t *testing.T) { + type reply struct { + status int + body string + } + // one organization's budget, as dhanyqaz's two keys are told it + const budget = `{"vibe_budget":{"usage_percentage":0.43,"initial_budget":150.0,"currency":"USD","reset_at":"2026-12-01T00:00:00Z","payg_enabled":false},"api_budget":{"usage_percentage":20.0,"initial_budget":15.0,"currency":"USD","reset_at":"2026-12-01T00:00:00Z"}}` + whos := map[string]reply{ + "Bearer vibe-key": {200, `{"plan_type":"CHAT","plan_name":"EDU"}`}, + "Bearer studio-key": {200, `{"plan_type":"API","plan_name":"FREE","primitive_access_scope":"personal_and_shared"}`}, + "Bearer code-key": {200, `{"plan_type":"MISTRAL_CODE","plan_name":"E"}`}, + "Bearer odd-key": {200, `{"plan_name":"EDU"}`}, + "Bearer down-key": {502, `{"message":"Bad Gateway"}`}, + } + sub := reply{200, `{"plan_name":"EDU","payg_enabled":true,"vibe_payg_enabled":false,"enterprise":false}`} + var asked []string + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + asked = append(asked, r.URL.Path) + var rep reply + switch r.URL.Path { + case "/api/vibe/whoami": + rep = whos[r.Header.Get("Authorization")] + case "/v1/billing/budget": + rep = reply{200, 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 }) + mistralKeyKinds.Clear() + t.Cleanup(mistralKeyKinds.Clear) + + read := func(key string) (string, []QuotaWindow, error) { + asked = nil + p := Provider{ID: "mistral", Chat: "https://api.mistral.ai/v1", Key: key} + src, _ := planQuotaSourceOf(p) + plan, ws, _, err := planKeyWindows(context.Background(), p, src, key) + return plan, ws, err + } + + plan, vibe, err := read("vibe-key") + if err != nil || plan != "Student" || len(vibe) != 1 { + t.Fatalf("vibe key: %q %+v %v", plan, vibe, err) + } + if w := vibe[0]; w.Name != "Month" || w.Limit != 150 || w.Unit != "USD" || w.Aside { + t.Errorf("vibe key's window: %+v", w) + } + + plan, studio, err := read("studio-key") + if err != nil || plan != "Student" || len(studio) != 1 { + t.Fatalf("studio key: %q %+v %v", plan, studio, err) + } + w := studio[0] + if w.Name != "API · Month" || w.Limit != 15 || w.Used != 20 || w.Amount != 3 || w.Unit != "USD" || w.Count(false) != "3 / 15 USD" { + t.Errorf("studio key's window: %+v (%s), want the api_budget, 3 / 15 USD", w, w.Count(false)) + } + if !w.Aside { + t.Error("the organization's payg_enabled is the Studio month's, not vibe_payg_enabled") + } + if w.Name == vibe[0].Name { + t.Error("a Studio month named as the Vibe month adds up with it on the accounts' strip") + } + // whoami asked once a key + if _, _, _ = read("studio-key"); strings.Join(asked, " ") != "/v1/billing/budget /v1/billing/subscription" { + t.Errorf("read again, asked %q, want no second whoami", asked) + } + + // the currency billing names, else none: never one magpie picked + for _, c := range []struct{ body, unit string }{ + {`"currency":"EUR"`, "EUR"}, {`"currency":" eur "`, "EUR"}, {`"currency":""`, ""}, {`"x":1`, ""}, + } { + b := `{"api_budget":{"usage_percentage":10,"initial_budget":15,` + c.body + `}}` + ws, err := readMistralBudget([]byte(b), mistralAPIKey, nil) + if err != nil || len(ws) != 1 || ws[0].Unit != c.unit { + t.Errorf("%s: %+v %v, want unit %q", b, ws, err, c.unit) + } + } + + // no api_budget, or none of it: no card, as a Vibe key with none + for _, b := range []string{`{"vibe_budget":{"usage_percentage":1,"initial_budget":150}}`, `{"vibe_budget":{"usage_percentage":1,"initial_budget":150},"api_budget":{"usage_percentage":0,"initial_budget":0}}`} { + if ws, err := readMistralBudget([]byte(b), mistralAPIKey, nil); err != nil || len(ws) != 0 { + t.Errorf("%s: %+v %v, want no windows", b, ws, err) + } + } + + // Mistral Code's key, and a reply with no plan_type: no card + for _, key := range []string{"code-key", "odd-key"} { + if _, ws, _ := read(key); len(ws) != 0 { + t.Errorf("%s: %+v, want no windows", key, ws) + } + } + if _, _, err := read("odd-key"); err == nil { + t.Error("whoami with no plan_type: want an error, not a kind") + } + // whoami down: unknown, so an error and no budget asked + if _, ws, err := read("down-key"); err == nil || len(ws) != 0 || strings.Join(asked, " ") != "/api/vibe/whoami" { + t.Errorf("whoami down: %+v %v, asked %q", ws, err, asked) + } + if _, ok := mistralKeyKinds.Load(sha256.Sum256([]byte("down-key"))); ok { + t.Error("a failed whoami was kept as the key's kind") + } +}