diff --git a/docs/reference.md b/docs/reference.md index a224a6615..ad93ab375 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1156,7 +1156,7 @@ relay's `/v1/usage`, its card shows those windows and routing weighs it by them as it does a subscription, resting it till the window renews once the relay says `api key 7天限额已用完` — or till its windows are next read short of full, its limit raised or its usage reset. A key bought as a plan — Kimi Code, GLM Coding Plan -or Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code — is weighed by its +or Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code, Ollama Cloud — is weighed by its plan's windows the same way. With one key or account, the Routing page still shows what it has left. `stays=` is how long a conversation stays with the key or account that answered it: `auto` (the default, while diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 64621b767..c1154d008 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -39,7 +39,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | A remote magpie's prices | A local magpie asks a remote magpie's `/v1/models` with `X-Magpie-Prices` (`PricesHeader`, sent by `listHeaders`). The remote answers each model's `magpie_price`: what its own Usage page counts the model at (`EntryPriceIn`: the price its user set, else its provider's list price at its price rate; a routing group only when every member costs the same). It tells it only to a request from its own computer or one let in with a gateway key (`local` or `sharedWith`); a list that didn't ask gets no prices (a remote request without a valid key never reaches the list: `lanGuard` refuses it). The local keeps the price with the fetched list (`catalog.Model.Price`; a value that isn't a price, or has a negative part, is dropped, the model kept) and uses it as that provider's list price (`ListPrice` → `remotePrice`). A price the local user set (`provider/model`, `provider/*`, `*/model`) still comes first, and the local provider's own price rate still applies on top. A remote from before this sends no field and the models stay priced as before; an older local sends no header and is sent nothing new. The model editor says the greyed price is the other magpie's (`remoteList`). | [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`models.go`](../../internal/provider/models.go), [`gateway.go`](../../internal/gateway/gateway.go) (`models`), [`live.go`](../../internal/catalog/live.go) | | A remote magpie's service tiers | A remote magpie's `/v1/models`, asked with `X-Magpie-Drawers` (`DrawersHeader`), gives each model the `service_tiers` its own Codex is offered on it (`codexTiers` → `codexcat.ServiceTiers`, from the same `CodexCatalog` and `codexcat.Entries` as its `/v1/codex/models`: Fast on a ChatGPT account's GPT model, the tiers of Codex's own entry on a relay's, none on a model it offers none). The local keeps the ids (`catalog.Model.Tiers` → `Entry.Tiers`), `codexListed` hands them on for the remote's models, and `codexcat.Entries` offers them to the local Codex with Codex's own names (`namedTiers`). The gateway sends the tier Codex asks for to a remote magpie as it was asked (`Request.OwnTier`, as for a provider added by its address; dropped and not sent again if refused), and the remote serves it as its own Codex's turn (#1234). A remote from before this sends no tiers, and its models are offered none, as before. | [`codexcat.go`](../../internal/codexcat/codexcat.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`gateway.go`](../../internal/gateway/gateway.go), [`live.go`](../../internal/catalog/live.go) | | A membership's $0 catalog | models.dev lists every model of Kimi Code's plans (`kimi-code-plan-global`, `kimi-code-plan-cn`) and of Xiaomi MiMo's Token Plans (`xiaomi-token-plan-cn`, `-sgp`, `-ams`) at $0: what the membership charges per token, not what the model costs. `membershipCatalogs` are never read for a price (`priceCatalogs`, `makerPriceCatalogs`), so a Xiaomi MiMo model is priced at `xiaomi`'s list price at every region, and each region of the preset names its own catalog, pay as you go `xiaomi` alone (#1873). A Kimi Code provider's model is priced at the Kimi API model it is (`kimiCodeAPI`, from Kimi Code's docs: k3 and k3-256k are kimi-k3, kimi-for-coding-highspeed is kimi-k2.7-code-highspeed), and kimi-for-coding (K2.8 Preview, not on the API) is unpriced rather than free (#1370). The alias is Kimi Code's alone (`kimiCodePlans`): a relay's own `k3` keeps its own price. A catalog other than these that lists a model at $0 still prices it at $0: models.dev has truly free models (nvidia, modelscope). The Requests list names the API model it was priced as (`PricedNameFor`). | [`models.go`](../../internal/provider/models.go) | -| A key's own windows | A sub2api key given a spending limit per 5 hours, day or 7 days answers its `/v1/usage` with `rate_limits` and no `remaining` (`readSub2APIKeyLimits`). With the Balance URL set to it, the key's card shows them as the windows *5 hours*, *1 day*, *7 days*, in USD, beside a balance field the user wrote; *Check balance* and `magpie provider show` give what its fullest window has left (`Balance`). `KeyAllowance` gives routing the same windows: never waited for, read in the background at most once a minute, a failed read keeping the last, and seeded from the card's last reading (`quotas.json`) after a restart. A key bought as a plan (Kimi Code, GLM Coding Plan and Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code: `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`). StepFun's Step Plan is read through a sign-in, not the key, and isn't one of them. Nor are Volcengine Ark's Coding Plan and Agent Plan (#1427): their 5-hour, weekly and monthly windows are told only to the account's access key (`AccessKeyID`, `SecretAccessKey`), asked of `open.volcengineapi.com` (`GetCodingPlanUsage`, `GetAFPUsage`) and signed as Volcengine's own SDK signs (`volcSign`), so they are cards on the Usage page (`volcPlanQuotas` in `PlanQuotas`), never routing's windows. Nor is Tencent Cloud's Token Plan 企业版 (#1574): what a team plan has used of its cycle's credits (专业套餐) or tokens (轻享套餐) is told only to the account's SecretId and SecretKey (kept as `AccessKeyID`, `SecretAccessKey`), asked of `tokenhub.tencentcloudapi.com` (`DescribeTokenPlanList`, `DescribeTokenPlan`, version 2026-03-22) and signed TC3-HMAC-SHA256 (`tc3Sign`), one card per team plan (`tencentPlanQuotas`). | [`sub2api_usage.go`](../../internal/provider/sub2api_usage.go), [`key_allowance.go`](../../internal/provider/key_allowance.go), [`volcengine_usage.go`](../../internal/provider/volcengine_usage.go), [`tencent_usage.go`](../../internal/provider/tencent_usage.go) | +| A key's own windows | A sub2api key given a spending limit per 5 hours, day or 7 days answers its `/v1/usage` with `rate_limits` and no `remaining` (`readSub2APIKeyLimits`). With the Balance URL set to it, the key's card shows them as the windows *5 hours*, *1 day*, *7 days*, in USD, beside a balance field the user wrote; *Check balance* and `magpie provider show` give what its fullest window has left (`Balance`). `KeyAllowance` gives routing the same windows: never waited for, read in the background at most once a minute, a failed read keeping the last, and seeded from the card's last reading (`quotas.json`) after a restart. A key bought as a plan (Kimi Code, GLM Coding Plan and Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code, Ollama Cloud: `planQuotaSourceOf`) gives routing its card's windows the same way (`planKeyWindows`, Zhipu's team quota behind a key with none of its own); the Usage page's read of its card is taken at once (`noteKeyAllowance`), and a key there that turns out pay-as-you-go, with no windows, is asked again only every 30 minutes (`keyNoWindowsAge`). Ollama Cloud's `ollama.com/api/balance` (#1888, `readOllamaPlan`) tells the plan's included allowance as one window in USD, *Month* when its period is a month long, renewing at `period.until`, and Aside while credits bought on top are left; those credits are the key's balance card (`readOllamaCredits`), and a reply that names none has no balance card rather than $0. StepFun's Step Plan is read through a sign-in, not the key, and isn't one of them. Nor are Volcengine Ark's Coding Plan and Agent Plan (#1427): their 5-hour, weekly and monthly windows are told only to the account's access key (`AccessKeyID`, `SecretAccessKey`), asked of `open.volcengineapi.com` (`GetCodingPlanUsage`, `GetAFPUsage`) and signed as Volcengine's own SDK signs (`volcSign`), so they are cards on the Usage page (`volcPlanQuotas` in `PlanQuotas`), never routing's windows. Nor is Tencent Cloud's Token Plan 企业版 (#1574): what a team plan has used of its cycle's credits (专业套餐) or tokens (轻享套餐) is told only to the account's SecretId and SecretKey (kept as `AccessKeyID`, `SecretAccessKey`), asked of `tokenhub.tencentcloudapi.com` (`DescribeTokenPlanList`, `DescribeTokenPlan`, version 2026-03-22) and signed TC3-HMAC-SHA256 (`tc3Sign`), one card per team plan (`tencentPlanQuotas`). | [`sub2api_usage.go`](../../internal/provider/sub2api_usage.go), [`key_allowance.go`](../../internal/provider/key_allowance.go), [`volcengine_usage.go`](../../internal/provider/volcengine_usage.go), [`tencent_usage.go`](../../internal/provider/tencent_usage.go) | | Account names and seats | `AccountNames` (by the account, in lower case, like `AccountCaps`) are names the user gives accounts, set by `SetAccountName` (GUI `provider/accountname`, `magpie accounts alias`); they live in providers.json only, never in a vendor's or plugin's sign-in. A GLM Coding Plan read with a key (`glmPlan`) and a ZCode account (built-in or `zcode-plugin`) whose windows' resets agree are one seat (`seatMatch`, #90/#953), shown once, on the account's card (`seatCards`, used by `quotas`, `Allotted` and `CachedCards`). A match is remembered in `seats.json` beside `quotas.json`: a failed read or a window with no reset yet is unknown and keeps the key's card off while the account is signed in; windows that disagree forget it (#1515). Cards carry `Seat` (the key provider's name, and the key's when it has several) and `Alias` (the user's name, else `Seat`), as `/v1/magpie/quotas`, `magpie quota` and `magpie accounts` do. | [`account_names.go`](../../internal/provider/account_names.go), [`account_seats.go`](../../internal/provider/account_seats.go) | | Last served | `served.json` records when each account, plan or key last answered, shown as `lastServedAt` (#570) on `/v1/magpie/quotas` and on the Usage page's own cards (`Quotas` → `cardsServed`, this computer's cards only, the caches left alone). The Usage page and the tray panel show the last-answered account in full, and a menu bar card that follows the account in use (`codex|*`) takes the one that answered within the last hour, else `InUseLogin`'s guess, else the one that answered last at all (a plugin's accounts, #1516) (`trayInUseCard`; okingkee on X: A spent, B answering, the menu bar stayed on A). `NoteServed` calls `OnServedMoved` when a provider's answers move to another account or key, and `SwitchLogin` after a switch, so the menu bar reads its cards again at once. | [`served.go`](../../internal/provider/served.go), [`trayusage.go`](../../internal/gui/trayusage.go) | | Partners | Services that pay to be listed first in the add sheet, under a heading of their own ("Partners · magpie's sponsors"). The list is `site/partners.js`, served at `usemagpie.ai/api/partners`: a change reaches users with a deploy, not a release. `Partners` never waits: it returns what was fetched last and fetches again behind the call every 6 hours (10 minutes after a failure), keeping the list in `partners.json` in the cache folder. Each entry is checked again on every read (`validPartners`): its own id, never a built-in preset's, a name, an endpoint, https only, at most 12; what only magpie's presets may set (a decision API, no key, a user endpoint) is cleared. Its logo is fetched through `FetchIcon` and kept as an uploaded icon. A partner is a preset to the rest of magpie (`Preset`, `FromPreset`, the editor), and one no longer listed still is to the providers added from it (`Seen`), without the sponsored mark. The window lists a partner in the languages it names (`langs`) only and shows its tagline in the page's language (`notes`, else `en`). `MAGPIE_PARTNERS` points it elsewhere, `off` lists none; tests list none unless they name a list. How often each listed partner was shown, opened (its row, its key page) and added is counted per UTC day (`CountPartner`, capped at 20 of each and 5 adds, kept in `partner-counts.json` in the cache folder) and sent with the next day's stats event as `magpie partner` events (`internal/stats`); nothing is counted with the stats or their usage part off. A listed partner the add sheet (or the TUI's, or `magpie providers presets`) hasn't shown yet is new (`NoticePartners` keeps those shown, as `noticed` in `partners.json`, whatever the stats); the window's add button carries a small dot for it, with its name in the title, until the sheet shows it. | [`partners.go`](../../internal/provider/partners.go), [`partner_events.go`](../../internal/provider/partner_events.go), [`site/partners.js`](../../site/partners.js) | diff --git a/internal/provider/balance.go b/internal/provider/balance.go index ca4a249a9..2b091c7fd 100644 --- a/internal/provider/balance.go +++ b/internal/provider/balance.go @@ -1,7 +1,7 @@ package provider // What is left on an API key, as the vendor's own balance endpoint tells -// it: DeepSeek, Kimi, OpenRouter, SiliconFlow, StepFun, Command Code and AiHubMix are known by their hosts +// it: DeepSeek, Kimi, OpenRouter, SiliconFlow, StepFun, Command Code, Ollama Cloud and AiHubMix are known by their hosts // (AiHubMix tells the whole account's to its access token, BalanceToken); // any other provider can name an endpoint and where the amount sits in its // reply (BalanceURL, BalancePath), the way a relay's own usage query does, @@ -67,6 +67,9 @@ func balanceSourceOf(p Provider) (balanceSource, bool) { return balanceSource{"https://api.stepfun.ai/v1/accounts", readStepFun("$"), "", nil}, true case "api.commandcode.ai": return balanceSource{"https://api.commandcode.ai/alpha/billing/credits", readCommandCode, "", nil}, true + case "ollama.com": + // the credits bought past the plan's allowance (#1888) + return balanceSource{ollamaBalanceURL, readOllamaCredits, "", nil}, true case "aihubmix.com": if p.BalanceToken != "" { return balanceSource{"https://aihubmix.com/api/user/self", readAiHubMixAccount, p.BalanceToken, nil}, true @@ -940,6 +943,9 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { return } amount, parts, ws, _, err := balanceRead(ctx, j.p) + if errors.Is(err, errNoBalance) { + return // a reply with no balance for this key: no card + } if err != nil { q.Error = err.Error() } else { @@ -956,6 +962,7 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota { }() } wg.Wait() + out = slices.DeleteFunc(out, func(q SubscriptionQuota) bool { return q.Provider == "" }) if ctx.Err() == nil { // each balance kept, and drawn over time with its runs-out noteBalanceHistory(out, time.Now()) diff --git a/internal/provider/balance_test.go b/internal/provider/balance_test.go index a0a1c738c..52fc7518b 100644 --- a/internal/provider/balance_test.go +++ b/internal/provider/balance_test.go @@ -92,6 +92,8 @@ func TestBalanceSourceByHost(t *testing.T) { "https://api.commandcode.ai/provider/v1": "https://api.commandcode.ai/alpha/billing/credits", "https://api.stepfun.com/step_plan/v1": "https://api.stepfun.com/v1/accounts", "https://api.stepfun.ai/v1": "https://api.stepfun.ai/v1/accounts", + "https://ollama.com/v1": "https://ollama.com/api/balance", + "http://localhost:11434/v1": "", "https://relay.example.com/v1": "", "https://api.deepseek.com.evil/": "", } { diff --git a/internal/provider/ollama_usage.go b/internal/provider/ollama_usage.go new file mode 100644 index 000000000..c6aa3f373 --- /dev/null +++ b/internal/provider/ollama_usage.go @@ -0,0 +1,114 @@ +package provider + +// Ollama Cloud tells a key its account's money at ollama.com/api/balance +// (#1888): what is left of the plan's included allowance this period, and +// the credits bought on top of it. The allowance is a plan card with one +// window (PlanQuotas), the bought credits a balance card (KeyBalances). + +import ( + "encoding/json" + "errors" + "fmt" + "time" +) + +// ollamaBalanceURL is a var for tests to point at a server of their own. +var ollamaBalanceURL = "https://ollama.com/api/balance" + +// ollamaBalance is the reply: +// +// {"included":{"balance_usd":72.5,"allowance_usd":100, +// "period":{"from":"2026-09-15T09:30:00Z","until":"2026-10-15T09:30:00Z"}}, +// "purchased":{"balance_usd":25.0}} +// +// Each amount is kept as it came, so one left out (a plan with no included +// allowance, an account that never bought credits) is unknown, not $0. +type ollamaBalance struct { + Included *struct { + Balance any `json:"balance_usd"` + Allowance any `json:"allowance_usd"` + Period *struct { + From string `json:"from"` + Until string `json:"until"` + } `json:"period"` + } `json:"included"` + Purchased *struct { + Balance any `json:"balance_usd"` + } `json:"purchased"` +} + +// errNoBalance is a reply that tells no balance for this card to show: not +// a failure to say on one, so the card is left out. +var errNoBalance = errors.New("no balance in the reply") + +func parseOllamaBalance(b []byte) (ollamaBalance, error) { + var r ollamaBalance + if err := json.Unmarshal(b, &r); err != nil { + return r, err + } + return r, nil +} + +// readOllamaPlan is the included allowance as a window: what the period +// has spent of it, in USD, renewing at the period's end. A reply without +// an allowance or without what is left of it has no window, and no card. +// Spending past the allowance draws on the bought credits, so a spent +// allowance with credits left doesn't stop the key (Aside). +func readOllamaPlan(b []byte) (string, []QuotaWindow, error) { + r, err := parseOllamaBalance(b) + if err != nil { + return "", nil, err + } + out := []QuotaWindow{} + in := r.Included + if in == nil { + return "", out, nil + } + allowance, ok1 := number(in.Allowance) + left, ok2 := number(in.Balance) + if !ok1 || !ok2 || allowance <= 0 { + return "", out, nil + } + used := min(allowance, max(0, allowance-left)) + w := QuotaWindow{Name: "Allowance", Amount: used, Limit: allowance, Unit: "USD", + Used: min(100, max(0, used/allowance*100))} + if p := in.Period; p != nil { + until, uerr := time.Parse(time.RFC3339, p.Until) + if uerr == nil { + w.ResetsAt = &until + } + if from, ferr := time.Parse(time.RFC3339, p.From); ferr == nil && uerr == nil && until.After(from) { + w.Span = until.Sub(from) + if d := w.Span.Hours() / 24; d >= 27 && d <= 32 { + w.Name = "Month" + } + } + } + if r.Purchased != nil { + if bought, ok := number(r.Purchased.Balance); ok && bought > 0 { + w.Aside = true + } + } + return "", append(out, w), nil +} + +// readOllamaCredits is the credits bought on top of the plan, in dollars. +// A reply that names none has no balance card: the allowance is the plan +// card's. +func readOllamaCredits(b []byte) (string, error) { + r, err := parseOllamaBalance(b) + if err != nil { + return "", err + } + if r.Purchased == nil { + if r.Included == nil { + return "", fmt.Errorf("Ollama's reply has no included or purchased balance: %s", shapeOf(b)) + } + return "", errNoBalance + } + v, ok := number(r.Purchased.Balance) + if !ok { + return "", errNoBalance + } + return money("$", v), nil +} diff --git a/internal/provider/ollama_usage_test.go b/internal/provider/ollama_usage_test.go new file mode 100644 index 000000000..5600e0daf --- /dev/null +++ b/internal/provider/ollama_usage_test.go @@ -0,0 +1,157 @@ +package provider + +import ( + "context" + "errors" + "math" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +// ollamaProReply is /api/balance for a plan with credits bought on top, +// as #1888 gives it. +const ollamaProReply = `{ + "included": { + "balance_usd": 72.5, + "allowance_usd": 100, + "period": { + "from": "2026-09-15T09:30:00Z", + "until": "2026-10-15T09:30:00Z" + } + }, + "purchased": { + "balance_usd": 25.0 + } +}` + +// The included allowance is a month's window of dollars spent, renewing +// at the period's end; the bought credits are the balance. +func TestReadOllamaBalance(t *testing.T) { + _, ws, err := readOllamaPlan([]byte(ollamaProReply)) + if err != nil || len(ws) != 1 { + t.Fatalf("%v %+v", err, ws) + } + w := ws[0] + until := time.Date(2026, 10, 15, 9, 30, 0, 0, time.UTC) + if w.Name != "Month" || w.Amount != 27.5 || w.Limit != 100 || w.Unit != "USD" || math.Abs(w.Used-27.5) > 1e-9 || + w.Span != 30*24*time.Hour || w.ResetsAt == nil || !w.ResetsAt.Equal(until) { + t.Errorf("allowance: %+v", w) + } + if !w.Aside { + t.Error("a spent allowance with credits bought stops the key") + } + if got, err := readOllamaCredits([]byte(ollamaProReply)); err != nil || got != "$25.00" { + t.Errorf("credits: %q %v", got, err) + } +} + +// What a reply leaves out is unknown, never $0 or used up. +func TestReadOllamaBalanceMissing(t *testing.T) { + window := func(body string) []QuotaWindow { + t.Helper() + _, ws, err := readOllamaPlan([]byte(body)) + if err != nil { + t.Fatalf("%s: %v", body, err) + } + return ws + } + // no credits ever bought: the allowance alone, which stops the key + // when spent, and no balance card + noBought := `{"included":{"balance_usd":0,"allowance_usd":20,"period":{"from":"2026-10-01T00:00:00Z","until":"2026-11-01T00:00:00Z"}}}` + if ws := window(noBought); len(ws) != 1 || ws[0].Used != 100 || ws[0].Aside || ws[0].Name != "Month" { + t.Errorf("no purchased: %+v", ws) + } + if got, err := readOllamaCredits([]byte(noBought)); !errors.Is(err, errNoBalance) { + t.Errorf("no purchased reads as %q %v", got, err) + } + // credits bought and spent: $0, said, and the allowance not aside + if ws := window(`{"included":{"balance_usd":5,"allowance_usd":20,"period":null},"purchased":{"balance_usd":0}}`); len(ws) != 1 || ws[0].Aside { + t.Errorf("credits spent: %+v", ws) + } + if got, err := readOllamaCredits([]byte(`{"included":null,"purchased":{"balance_usd":0}}`)); err != nil || got != "$0.00" { + t.Errorf("$0 bought: %q %v", got, err) + } + // no period: a window with no reset and no span + if ws := window(`{"included":{"balance_usd":"15","allowance_usd":"20","period":null}}`); len(ws) != 1 || ws[0].ResetsAt != nil || + ws[0].Span != 0 || ws[0].Name != "Allowance" || ws[0].Amount != 5 { + t.Errorf("null period: %+v", ws) + } + // a free plan: no allowance, or none of it told, is no window + for _, body := range []string{ + `{"included":null,"purchased":{"balance_usd":0}}`, + `{"included":{"balance_usd":0,"allowance_usd":0,"period":null}}`, + `{"included":{"allowance_usd":20,"period":null}}`, + `{"included":{"balance_usd":3}}`, + `{"purchased":{"balance_usd":4}}`, + `{}`, + } { + if ws := window(body); len(ws) != 0 { + t.Errorf("%s: %+v", body, ws) + } + } + // a reply of neither: said, with its shape, not hidden as no balance + if _, err := readOllamaCredits([]byte(`{"error":"x","balance":1}`)); err == nil || errors.Is(err, errNoBalance) || !strings.Contains(err.Error(), "balance") { + t.Errorf("another shape: %v", err) + } + if _, _, err := readOllamaPlan([]byte(`not json`)); err == nil { + t.Error("a reply that isn't JSON read as no plan") + } +} + +// An Ollama Cloud key's allowance is a plan card and its bought credits a +// balance card, on the Usage page and in magpie quota; a key that bought +// none has no balance card, and a key Ollama refuses says so. +func TestOllamaCloudCards(t *testing.T) { + signIn(t) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/balance" || r.Method != http.MethodGet { + t.Errorf("asked %s %s", r.Method, r.URL.Path) + } + switch r.Header.Get("Authorization") { + case "Bearer ok-pro": + w.Write([]byte(ollamaProReply)) + case "Bearer ok-plain": + w.Write([]byte(`{"included":{"balance_usd":19,"allowance_usd":20,"period":{"from":"2026-10-01T00:00:00Z","until":"2026-11-01T00:00:00Z"}}}`)) + default: + w.WriteHeader(http.StatusUnauthorized) + w.Write([]byte(`{"error":"invalid credentials"}`)) // as ollama.com answers a bad key + } + })) + defer srv.Close() + old := ollamaBalanceURL + ollamaBalanceURL = srv.URL + "/api/balance" + t.Cleanup(func() { ollamaBalanceURL = old }) + if err := Save(Provider{ID: "ollama-cloud", Name: "Ollama Cloud", Icon: "ollama", Chat: "https://ollama.com/v1", Anthropic: "https://ollama.com", + Key: "ok-pro", KeyName: "pro", Keys: []KeyAccount{{Name: "plain", Key: "ok-plain"}, {Name: "bad", Key: "ok-bad"}}}); err != nil { + t.Fatal(err) + } + ctx := context.Background() + plans := map[string]SubscriptionQuota{} + for _, q := range PlanQuotas(ctx) { + if q.Provider == "ollama-cloud" { + plans[q.User] = q + } + } + if q := plans["pro"]; len(q.Windows) != 1 || q.Windows[0].Name != "Month" || q.Windows[0].Amount != 27.5 || q.Error != "" { + t.Errorf("pro's plan: %+v", q) + } + if q := plans["plain"]; len(q.Windows) != 1 || q.Windows[0].Amount != 1 || q.Windows[0].Aside { + t.Errorf("plain's plan: %+v", q) + } + if _, ok := plans["bad"]; ok || len(plans) != 2 { + t.Errorf("plan cards: %+v", plans) + } + var lines []string + for _, q := range KeyBalances(ctx) { + if q.Provider == "ollama-cloud" { + lines = append(lines, q.User+"|"+q.Balance+"|"+q.Error) + } + } + want := `pro|$25.00|,bad||401 Unauthorized: {"error":"invalid credentials"}` + if strings.Join(lines, ",") != want { + t.Errorf("balance cards:\n%s\nwant\n%s", strings.Join(lines, ","), want) + } +} diff --git a/internal/provider/planquota.go b/internal/provider/planquota.go index cf68131c6..09d1f83cc 100644 --- a/internal/provider/planquota.go +++ b/internal/provider/planquota.go @@ -2,7 +2,7 @@ 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, StepFun's Step Plan, Volcengine Ark's Coding and Agent Plans and +// Plan, Ollama Cloud's included allowance, 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 @@ -59,6 +59,10 @@ func planQuotaSourceOf(p Provider) (planQuotaSource, bool) { if u := strings.TrimSuffix(base, "/"); strings.HasSuffix(u, "/zen/go") || strings.Contains(u, "/zen/go/") { return planQuotaSource{"https://opencode.ai/zen/go/v1/usage", true, readOpenCodeGo, true}, true } + case "ollama.com": + // Ollama Cloud's included allowance (#1888); a key with none + // gets no card + return planQuotaSource{ollamaBalanceURL, true, readOllamaPlan, false}, true } } return planQuotaSource{}, false diff --git a/internal/provider/planquota_test.go b/internal/provider/planquota_test.go index c78888a6a..858fd102a 100644 --- a/internal/provider/planquota_test.go +++ b/internal/provider/planquota_test.go @@ -33,6 +33,8 @@ func TestPlanQuotaSource(t *testing.T) { {Provider{Chat: "https://api.minimaxi.com/v1", Anthropic: "https://api.minimaxi.com/anthropic"}, "https://api.minimaxi.com/v1/token_plan/remains", true, false}, {Provider{Anthropic: "https://api.minimax.io/anthropic"}, "https://api.minimax.io/v1/token_plan/remains", true, false}, {Provider{Chat: "https://api.deepseek.com"}, "", false, false}, + {Provider{Chat: "https://ollama.com/v1", Anthropic: "https://ollama.com"}, "https://ollama.com/api/balance", true, false}, + {Provider{Chat: "http://localhost:11434/v1"}, "", false, false}, // a local Ollama } { src, ok := planQuotaSourceOf(c.p) if ok != c.ok || src.url != c.url || src.sure != c.sure {