diff --git a/README.md b/README.md index 2be276f..94df848 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ - OpenAI-compatible `POST /v1/chat/completions` (streaming and non-streaming) and `GET /v1/models` - Multiple Command Code accounts with round-robin rotation and automatic failover (`401`/`403`/`429`/5xx), including per-account 429 cooldown - Multiple local client API keys with per-key request and token accounting -- Command Code quota dashboard: 5-hour / weekly / estimated monthly progress bars, credit balances, plan and billing period, refreshed in the background every 5 minutes +- Command Code quota dashboard: 5-hour / weekly / estimated monthly progress bars, credit balances, plan and billing period, refreshed in the background every 5 minutes; a collapsible per-account tracker estimates each boosted model's remaining USD allowance from the official per-model allowance table - Embedded single-file WebUI: usage dashboard, account/key management, model exposure editor, live settings, and log tail - Browser OAuth helper for obtaining a Command Code API key (CLI or WebUI); each OAuth run adds an account - Local bearer-token auth for clients, separate admin password for the WebUI @@ -206,9 +206,11 @@ Security notes: admin authentication is rate limited per source IP (5 failed att The Accounts tab shows each account's Command Code quota, read with the same API key from the undocumented `/alpha/*` endpoints (`whoami`, `billing/credits`, `billing/subscriptions`, `usage/summary`): - **5-hour** and **weekly** bars come straight from the upstream `windowLimits` objects. Bars grade amber at ≥50% used, heavier amber at ≥75%, and red at ≥90%. -- **Monthly** is *derived*: the API exposes no monthly window, so the cap comes from the community CLI's plan mapping (`individual-pro` → 30, `individual-pro-v1` → 80, …), with `used = cap − remaining credits`. It is labelled as estimated; unknown plans fall back to balance-only display. -- Credit balances (monthly remaining / purchased / free), plan name and status, billing-period end, and billing-period totals. +- **Monthly** is *derived*: the API exposes no monthly window, so the cap is the observed allowance, `remaining credits + billing-period spend`. Command Code scales the credit windows and the monthly allowance per model, so this follows the model actually in use instead of a hardcoded dollar figure. When the usage aggregate is unavailable the UI falls back to the community CLI's plan mapping (`individual-pro` → 30, `individual-pro-v1` → 80, …). +- Credit balances (monthly remaining / purchased / free), plan name and status, billing-period end, and billing-period totals. Every bar and balance is labelled in **plan credits**, the unit the API reports, never in USD. +- Command Code grants a credit pool per plan and scales it per model. On GOAT with DeepSeek V4.1 Flash the pool is 70 credits, split into a 14-credit 5-hour window, a 35-credit weekly window, and the 70-credit monthly allowance — 0.7× the advertised $20 / $50 / $100, so 35 credits/week is roughly $50 of list-price DeepSeek V4.1 Flash usage. A bar at 100% therefore means the plan's real window limit, not a smaller dollar cap. Other plans and models report their own caps; nothing is hardcoded here. - A per-account **refresh quota** button and a **refresh all** button (which returns immediately and refreshes in the background). +- Each card has a collapsible **Boosted allowance** tracker. Command Code publishes a monthly allowance per model (the "boosted usage" deals), all charged from the same credit pool, so one model's dollars per credit differ from another's. The table shows, per boosted model, its advertised allowance, the multiplier against the plan's credit pool, and the remaining USD allowance derived from the account's remaining credits; the summary line also estimates the 5-hour and weekly windows. The catalog is captured from the Command Code pricing docs (`internal/app/allowances.json`, generated by `go generate ./internal/app`) and embedded in the binary - no network call, no configuration. These USD figures are **estimates** labelled `est`; the credit numbers remain authoritative, and plans without a published per-model table (Provider, Ultra, Max) show no tracker. Quota refresh runs once shortly after startup and every 5 minutes afterwards; the latest snapshot is cached in `usage.json` so it survives restarts. A failed query keeps the last successful snapshot and only records the error and check time. These endpoints come from [commandcode-usage](https://github.com/MAXeaglet/commandcode-usage); they are unofficial, so the parser tolerates field drift (camelCase or snake_case, epoch seconds / milliseconds / ISO timestamps, flat or `data`-wrapped responses). @@ -241,7 +243,7 @@ GET /admin/api/oauth/status POST /admin/api/oauth/cancel ``` -`GET /admin/api/accounts` includes a nested `quota` object per account; `GET /admin/api/overview` includes a `quotas` summary (`synced`, `exceeded`, `low_balance`, `last_checked_at`). +`GET /admin/api/accounts` includes a nested `quota` object per account and a `boosted` object (`plan`, `pool_credits`, `standard_usd`, `standard_models`, `models[]` with `allowance_usd` / `factor` / `remaining_usd` / `five_hour_usd` / `weekly_usd`, plus the catalog source and capture date); `GET /admin/api/overview` includes a `quotas` summary (`synced`, `exceeded`, `low_balance`, `last_checked_at`). ## HTTP API diff --git a/README.zh-CN.md b/README.zh-CN.md index 6ab1400..e3aee5c 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -9,7 +9,7 @@ - OpenAI 兼容的 `POST /v1/chat/completions`(流式与非流式)与 `GET /v1/models` - 多 Command Code 账号轮询使用,`401`/`403`/`429`/`5xx` 自动故障转移,含账号级 429 冷却 - 多客户端密钥,每把密钥独立统计请求与 token 用量 -- Command Code 额度仪表盘:5 小时 / 本周 / 按月估算进度条、余额、套餐与账期,后台每 5 分钟刷新 +- Command Code 额度仪表盘:5 小时 / 本周 / 按月估算进度条、余额、套餐与账期,后台每 5 分钟刷新;每个账号带可折叠的「提升额度」跟踪器,依据官方各模型额度表估算提升模型的剩余美元额度 - 内嵌单文件 WebUI:用量总览、账号/密钥管理、模型开放编辑器、在线设置、日志查看 - 浏览器 OAuth 助手获取 Command Code API Key(CLI 或 WebUI),每次授权添加一个账号 - 客户端 Bearer Token 鉴权,WebUI 使用独立管理密码 @@ -206,9 +206,11 @@ http://localhost:11434/webui 「账号」页展示每个账号的 Command Code 额度,使用同一个 API Key 读取未公开的 `/alpha/*` 接口(`whoami`、`billing/credits`、`billing/subscriptions`、`usage/summary`): - **5 小时**、**本周**进度条直接来自上游 `windowLimits`;已用 ≥50% 显示黄色、≥75% 深黄、≥90% 红色。 -- **月度**为推算值:接口没有月度窗口对象,上限来自社区 CLI 的套餐映射(`individual-pro` → 30、`individual-pro-v1` → 80 等),已用 = 上限 − 剩余月度额度,界面上标注"按套餐估算";未知套餐仅显示余额。 -- 余额(月度剩余 / 充值 / 免费)、套餐名称与状态、账期结束时间、账期用量统计。 +- **月度**为推算值:接口没有月度窗口对象,上限取实际观察到的额度(剩余月度额度 + 账期已用额度)。Command Code 的积分窗口和月度额度按模型换算,因此这里跟随当前使用的模型,而不是写死的美元上限。账期用量接口不可用时,退回社区 CLI 的套餐映射(`individual-pro` → 30、`individual-pro-v1` → 80 等)。 +- 余额(月度剩余 / 充值 / 免费)、套餐名称与状态、账期结束时间、账期用量统计。进度条与余额一律按接口返回的「积分」显示,不会写成美元。 +- Command Code 按套餐发放积分池,并按模型换算。GOAT 使用 DeepSeek V4.1 Flash 时积分池为 70:5 小时窗口 14、本周窗口 35、月度额度 70,正好是官方宣传的 $20 / $50 / $100 的 0.7 倍。也就是说 35 积分/周约等于 $50 的 DeepSeek V4.1 Flash 原价用量;进度条到 100% 就是套餐真实窗口上限,不是更小的美元上限。其它套餐与模型各自上报自己的上限,这里不做硬编码。 - 账号页提供单账号「刷新额度」与「刷新全部额度」按钮(后者立即返回,后台刷新)。 +- 每张卡片带可折叠的**提升额度**跟踪器。Command Code 按模型公布月度额度(官方「提升用量」活动),但都从同一个积分池扣费,因此不同模型的「每积分对应多少美元」并不相同。表格列出每个提升模型的官方额度、相对积分池的倍率,以及按账号剩余积分换算的剩余美元额度;摘要行还给出 5 小时 / 本周窗口的估算。额度表抓取自 Command Code 定价文档并内嵌进二进制(`internal/app/allowances.json`,用 `go generate ./internal/app` 生成),不联网、无需配置。这些美元数字都是**估算**(标 `est`),积分数字仍然权威;Provider、Ultra、Max 等没有公开逐模型额度表的套餐不显示该跟踪器。 额度会在启动后不久自动刷新一次,之后每 5 分钟刷新一次,快照缓存在 `usage.json` 中,重启后仍然保留。查询失败时保留上一次成功的数据,只更新错误与查询时间。接口路径取自 [commandcode-usage](https://github.com/MAXeaglet/commandcode-usage),属未公开接口,解析层兼容字段漂移(camelCase / snake_case、秒 / 毫秒 / ISO 时间、顶层或 `data` 嵌套)。 @@ -241,7 +243,7 @@ GET /admin/api/oauth/status POST /admin/api/oauth/cancel ``` -`GET /admin/api/accounts` 每个账号带嵌套 `quota` 对象;`GET /admin/api/overview` 带 `quotas` 汇总(`synced`、`exceeded`、`low_balance`、`last_checked_at`)。 +`GET /admin/api/accounts` 每个账号带嵌套 `quota` 对象和 `boosted` 对象(`plan`、`pool_credits`、`standard_usd`、`standard_models`、`models[]`:`allowance_usd` / `factor` / `remaining_usd` / `five_hour_usd` / `weekly_usd`,以及额度表来源与抓取日期);`GET /admin/api/overview` 带 `quotas` 汇总(`synced`、`exceeded`、`low_balance`、`last_checked_at`)。 ## HTTP API diff --git a/cmd/gen-allowances/main.go b/cmd/gen-allowances/main.go new file mode 100644 index 0000000..9ff261f --- /dev/null +++ b/cmd/gen-allowances/main.go @@ -0,0 +1,294 @@ +// Command gen-allowances regenerates internal/app/allowances.json from the +// public Command Code pricing page. +// +// The page is a Next.js app: its RSC payload carries the model catalog as plain +// JSON, including the per-plan USD allowances ("boosted usage") we track. This +// command fetches that payload, keeps the fields the app reads, and writes a +// compact catalog with one JSON object per line. The result is still a single +// valid JSON document, so the app keeps using encoding/json, while a change to +// one model touches exactly one line in review. +// +// Run it with: +// +// go generate ./internal/app +// +// The command needs network access and is never run at build time; the +// checked-in file keeps builds hermetic and offline. +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "net/http" + "os" + "reflect" + "sort" + "strings" + "time" +) + +const sourceURL = "https://commandcode.ai/docs/resources/pricing-limits" + +// upstreamModel is the part of the page's model object this catalog needs. +type upstreamModel struct { + ID string `json:"id"` + Name string `json:"name"` + Category string `json:"category"` + PlanAllowanceUSD map[string]float64 `json:"planAllowanceUsd"` +} + +// catalogModel is the on-disk row. Field order is the order written to the file. +type catalogModel struct { + ID string `json:"id"` + Name string `json:"name"` + Category string `json:"category"` + Go float64 `json:"go"` + Goat float64 `json:"goat"` + Pro float64 `json:"pro"` +} + +type catalogFile struct { + Source string `json:"source"` + Captured string `json:"captured"` + Models []catalogModel `json:"models"` +} + +func main() { + out := flag.String("out", "allowances.json", "output file") + flag.Parse() + if err := run(*out); err != nil { + fmt.Fprintf(os.Stderr, "gen-allowances: %v\n", err) + os.Exit(1) + } +} + +func run(out string) error { + body, err := fetch(sourceURL) + if err != nil { + return err + } + models, err := catalogFrom(body) + if err != nil { + return err + } + // The page lists models newest first, which reshuffles often. Sorting by id + // keeps regeneration deterministic and makes a new model a one-line diff. + sort.Slice(models, func(i, j int) bool { return models[i].ID < models[j].ID }) + + if unchanged(out, models) { + fmt.Printf("%s: upstream unchanged, left as is\n", out) + return nil + } + + data, err := render(models, time.Now().UTC().Format("2006-01-02")) + if err != nil { + return err + } + if err := os.WriteFile(out, data, 0o644); err != nil { + return err + } + fmt.Printf("%s: wrote %d models\n", out, len(models)) + return nil +} + +func fetch(url string) ([]byte, error) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return nil, err + } + // The RSC payload is a fraction of the rendered HTML and needs no scraping. + req.Header.Set("RSC", "1") + req.Header.Set("User-Agent", "cmdcode2api-gen-allowances/1") + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("GET %s: %s", url, resp.Status) + } + return io.ReadAll(io.LimitReader(resp.Body, 8<<20)) +} + +// catalogFrom pulls the model catalog out of the RSC payload. The payload is +// not JSON itself, but the "models" property is a JSON array, which we locate +// and decode on its own. +func catalogFrom(body []byte) ([]catalogModel, error) { + raw, err := findModelsArray(body) + if err != nil { + return nil, err + } + var upstream []upstreamModel + if err := json.Unmarshal(raw, &upstream); err != nil { + return nil, fmt.Errorf("decode models: %w", err) + } + if len(upstream) < 50 { + return nil, fmt.Errorf("decoded only %d models, refusing to overwrite (page layout changed?)", len(upstream)) + } + return modelsFrom(upstream) +} + +// modelsFrom validates the decoded catalog and keeps the fields the app reads. +func modelsFrom(upstream []upstreamModel) ([]catalogModel, error) { + seen := make(map[string]bool, len(upstream)) + models := make([]catalogModel, 0, len(upstream)) + for _, m := range upstream { + id := strings.TrimSpace(m.ID) + name := strings.TrimSpace(m.Name) + category := strings.TrimSpace(m.Category) + if id == "" || name == "" || category == "" { + return nil, fmt.Errorf("model %q has a missing id, name, or category", m.ID) + } + if seen[id] { + return nil, fmt.Errorf("duplicate model id %q", id) + } + seen[id] = true + + goUSD, ok := m.PlanAllowanceUSD["go"] + if !ok { + return nil, fmt.Errorf("model %q has no go allowance", id) + } + goatUSD, ok := m.PlanAllowanceUSD["goat"] + if !ok { + return nil, fmt.Errorf("model %q has no goat allowance", id) + } + proUSD, ok := m.PlanAllowanceUSD["pro"] + if !ok { + return nil, fmt.Errorf("model %q has no pro allowance", id) + } + models = append(models, catalogModel{ + ID: id, + Name: name, + Category: category, + Go: goUSD, + Goat: goatUSD, + Pro: proUSD, + }) + } + return models, nil +} + +// findModelsArray returns the first "models" value that looks like the catalog: +// a JSON array whose entries carry per-plan allowances. +func findModelsArray(body []byte) ([]byte, error) { + needle := []byte(`"models"`) + for off := 0; ; { + i := bytes.Index(body[off:], needle) + if i < 0 { + return nil, errors.New(`no "models" array in the response; the page layout changed`) + } + i += off + j := i + len(needle) + j = skipSpace(body, j) + if j < len(body) && body[j] == ':' { + j = skipSpace(body, j+1) + if j < len(body) && body[j] == '[' { + if arr, err := jsonArrayAt(body, j); err == nil { + var probe []upstreamModel + if json.Unmarshal(arr, &probe) == nil && len(probe) > 0 && probe[0].PlanAllowanceUSD != nil { + return arr, nil + } + } + } + } + off = i + len(needle) + } +} + +// jsonArrayAt returns the balanced JSON array starting at body[start]. +func jsonArrayAt(body []byte, start int) ([]byte, error) { + if start < 0 || start >= len(body) || body[start] != '[' { + return nil, errors.New("not a JSON array") + } + depth := 0 + inString, escaped := false, false + for i := start; i < len(body); i++ { + c := body[i] + if inString { + switch { + case escaped: + escaped = false + case c == '\\': + escaped = true + case c == '"': + inString = false + } + continue + } + switch c { + case '"': + inString = true + case '[': + depth++ + case ']': + depth-- + if depth == 0 { + return body[start : i+1], nil + } + } + } + return nil, errors.New("unterminated JSON array") +} + +func skipSpace(body []byte, i int) int { + for i < len(body) { + switch body[i] { + case ' ', '\t', '\n', '\r': + i++ + default: + return i + } + } + return i +} + +// unchanged reports whether the checked-in file already holds exactly this +// catalog, so a regeneration with no upstream changes leaves the file and its +// capture date alone. +func unchanged(path string, models []catalogModel) bool { + data, err := os.ReadFile(path) + if err != nil { + return false + } + var old catalogFile + if json.Unmarshal(data, &old) != nil { + return false + } + return old.Source == sourceURL && old.Captured != "" && reflect.DeepEqual(old.Models, models) +} + +func render(models []catalogModel, captured string) ([]byte, error) { + var b bytes.Buffer + b.WriteString(`{"source":`) + quotedSource, err := json.Marshal(sourceURL) + if err != nil { + return nil, err + } + b.Write(quotedSource) + b.WriteString(`,"captured":"`) + b.WriteString(captured) + b.WriteString(`","models":[`) + b.WriteByte('\n') + for i, m := range models { + line, err := json.Marshal(m) + if err != nil { + return nil, err + } + b.Write(line) + if i != len(models)-1 { + b.WriteByte(',') + } + b.WriteByte('\n') + } + b.WriteString("]}\n") + return b.Bytes(), nil +} diff --git a/cmd/gen-allowances/main_test.go b/cmd/gen-allowances/main_test.go new file mode 100644 index 0000000..18fa667 --- /dev/null +++ b/cmd/gen-allowances/main_test.go @@ -0,0 +1,77 @@ +package main + +import ( + "encoding/json" + "fmt" + "strings" + "testing" +) + +func TestJSONArrayAt(t *testing.T) { + body := []byte(`xx[{"name":"a]b","nested":[1,2],"quote":"say \"hi\""},{"id":"c"}]yy`) + got, err := jsonArrayAt(body, 2) + if err != nil { + t.Fatalf("jsonArrayAt: %v", err) + } + if want := `[{"name":"a]b","nested":[1,2],"quote":"say \"hi\""},{"id":"c"}]`; string(got) != want { + t.Fatalf("jsonArrayAt = %s, want %s", got, want) + } +} + +func TestFindModelsArraySkipsUnrelatedKeys(t *testing.T) { + body := []byte(`{"models":{"count":2},"meta":{"models":[{"id":"decoy"}]},` + + `"data":{"models":[{"id":"a","name":"A","category":"opensource","planAllowanceUsd":{"go":6,"goat":20,"pro":30}}]}}`) + got, err := findModelsArray(body) + if err != nil { + t.Fatalf("findModelsArray: %v", err) + } + var models []upstreamModel + if err := json.Unmarshal(got, &models); err != nil { + t.Fatalf("decoded array is not valid JSON: %v", err) + } + if len(models) != 1 || models[0].ID != "a" { + t.Fatalf("got %+v, want the catalog entry", models) + } +} + +func TestCatalogFromKeepsPlanAllowances(t *testing.T) { + body := catalogPayload(t, 60) + models, err := catalogFrom(body) + if err != nil { + t.Fatalf("catalogFrom: %v", err) + } + if len(models) != 60 { + t.Fatalf("got %d models, want 60", len(models)) + } + first := models[0] + if first.ID != "model-00" || first.Name != "Model 00" || first.Category != "opensource" { + t.Fatalf("unexpected first row: %+v", first) + } + if first.Go != 6 || first.Goat != 20 || first.Pro != 30 { + t.Fatalf("unexpected allowances: %+v", first) + } +} + +func TestCatalogFromRejectsMissingAllowance(t *testing.T) { + upstream := []upstreamModel{ + {ID: "x", Name: "X", Category: "opensource", PlanAllowanceUSD: map[string]float64{"go": 6, "goat": 20}}, + } + if _, err := modelsFrom(upstream); err == nil { + t.Fatal("modelsFrom accepted a model without a pro allowance") + } +} + +// catalogPayload builds an RSC-shaped body with n valid models. +func catalogPayload(t *testing.T, n int) []byte { + t.Helper() + var b strings.Builder + b.WriteString(`1:{"models":[`) + for i := 0; i < n; i++ { + if i > 0 { + b.WriteByte(',') + } + b.WriteString(fmt.Sprintf(`{"id":"model-%02d","name":"Model %02d","category":"opensource","planAllowanceUsd":{"go":6,"goat":20,"pro":30}}`, i, i)) + } + b.WriteString(`]}`) + return []byte(b.String()) +} diff --git a/internal/app/admin.go b/internal/app/admin.go index 0354404..bdf0477 100644 --- a/internal/app/admin.go +++ b/internal/app/admin.go @@ -65,7 +65,8 @@ func subtleConstantTimeEqual(a, b string) bool { type adminAccount struct { AccountView UsageSnapshotEntry - Quota *QuotaSnapshot `json:"quota,omitempty"` + Quota *QuotaSnapshot `json:"quota,omitempty"` + Boosted *BoostedView `json:"boosted,omitempty"` } // localizeQuotaSnapshot returns a shallow copy of snap with the user-facing @@ -93,10 +94,12 @@ func adminAccountViews(pool *AccountPool, usage *UsageTracker, r *http.Request) views := pool.Views() out := make([]adminAccount, 0, len(views)) for _, v := range views { + snap := localizeQuotaSnapshot(i18n.FromRequest(r), usage.Quota(v.ID)) out = append(out, adminAccount{ AccountView: v, UsageSnapshotEntry: usage.AccountUsage(v.ID), - Quota: localizeQuotaSnapshot(i18n.FromRequest(r), usage.Quota(v.ID)), + Quota: snap, + Boosted: BoostedFor(snap), }) } return out @@ -227,7 +230,8 @@ func handleAdminAccountAdd(pool *AccountPool, cfg *Config, usage *UsageTracker, // stays fast; the UI picks the snapshot up on its next poll. quotas.RefreshAsync(acct) log.Printf("account %q added via webui", acct.Name) - writeAdminJSON(w, 201, adminAccount{AccountView: acct.View(), UsageSnapshotEntry: usage.AccountUsage(acct.ID), Quota: usage.Quota(acct.ID)}) + snap := localizeQuotaSnapshot(i18n.FromRequest(r), usage.Quota(acct.ID)) + writeAdminJSON(w, 201, adminAccount{AccountView: acct.View(), UsageSnapshotEntry: usage.AccountUsage(acct.ID), Quota: snap, Boosted: BoostedFor(snap)}) } } @@ -275,7 +279,8 @@ func handleAdminAccountPatch(pool *AccountPool, cfg *Config, usage *UsageTracker if keyChanged && quotas != nil { quotas.RefreshAsync(acct) } - writeAdminJSON(w, 200, adminAccount{AccountView: acct.View(), UsageSnapshotEntry: usage.AccountUsage(id), Quota: usage.Quota(id)}) + snap := localizeQuotaSnapshot(i18n.FromRequest(r), usage.Quota(id)) + writeAdminJSON(w, 200, adminAccount{AccountView: acct.View(), UsageSnapshotEntry: usage.AccountUsage(id), Quota: snap, Boosted: BoostedFor(snap)}) } } @@ -309,7 +314,8 @@ func handleAdminAccountQuotaRefresh(pool *AccountPool, usage *UsageTracker, quot return } quotas.RefreshAccount(r.Context(), acct) - writeAdminJSON(w, 200, adminAccount{AccountView: acct.View(), UsageSnapshotEntry: usage.AccountUsage(acct.ID), Quota: localizeQuotaSnapshot(i18n.FromRequest(r), usage.Quota(acct.ID))}) + snap := localizeQuotaSnapshot(i18n.FromRequest(r), usage.Quota(acct.ID)) + writeAdminJSON(w, 200, adminAccount{AccountView: acct.View(), UsageSnapshotEntry: usage.AccountUsage(acct.ID), Quota: snap, Boosted: BoostedFor(snap)}) } } diff --git a/internal/app/allowances.json b/internal/app/allowances.json new file mode 100644 index 0000000..53f33d8 --- /dev/null +++ b/internal/app/allowances.json @@ -0,0 +1,101 @@ +{"source":"https://commandcode.ai/docs/resources/pricing-limits","captured":"2026-11-16","models":[ +{"id":"claude-fable-5","name":"Claude Fable 5","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"claude-fable-5-1","name":"Claude Fable 5.1","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"claude-fable-5-2","name":"Claude Fable 5.2","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"claude-haiku-4-5","name":"Claude Haiku 4.5","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"claude-haiku-5-5","name":"Claude Haiku 5.5","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"claude-opus-4-7","name":"Claude Opus 4.7","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"claude-opus-4-8","name":"Claude Opus 4.8","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"claude-opus-5","name":"Claude Opus 5","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"claude-opus-5-5","name":"Claude Opus 5.5","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"claude-sonnet-4-6","name":"Claude Sonnet 4.6","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"claude-sonnet-5","name":"Claude Sonnet 5","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"claude-sonnet-5-5","name":"Claude Sonnet 5.5","category":"opensource","go":6,"goat":10,"pro":20}, +{"id":"deepseek-v4-flash","name":"DeepSeek V4 Flash (latest)","category":"opensource","go":6,"goat":60,"pro":70}, +{"id":"deepseek-v4-flash-fast","name":"DeepSeek V4 Flash Fast","category":"opensource","go":8,"goat":20,"pro":30}, +{"id":"deepseek-v4-flash-vision-exp","name":"DeepSeek V4 Flash Vision (exp)","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"deepseek-v4-pro","name":"DeepSeek V4 Pro (latest)","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"deepseek-v4.1-flash","name":"DeepSeek V4.1 Flash (latest)","category":"opensource","go":10,"goat":100,"pro":110}, +{"id":"deepseek-v4.1-flash-fast","name":"DeepSeek V4.1 Flash Fast (latest)","category":"opensource","go":6,"goat":60,"pro":70}, +{"id":"deepseek-v4.1-flash-ultrafast","name":"DeepSeek V4.1 Flash Ultrafast","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"fugu-ultra","name":"Fugu Ultra","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"gemini-3.1-flash-lite","name":"Gemini 3.1 Flash Lite","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"gemini-3.5-flash","name":"Gemini 3.5 Flash","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"gemini-3.5-flash-lite","name":"Gemini 3.5 Flash Lite","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"gemini-3.6-flash","name":"Gemini 3.6 Flash","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"gemini-3.7-flash","name":"Gemini 3.7 Flash","category":"opensource","go":6,"goat":40,"pro":50}, +{"id":"gemini-3.8-flash","name":"Gemini 3.8 Flash","category":"opensource","go":6,"goat":40,"pro":50}, +{"id":"gemini-4-argon","name":"Gemini 4 Argon","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"gemini-4-carbon","name":"Gemini 4 Carbon","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"glm-5","name":"GLM-5","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"glm-5.1","name":"GLM-5.1","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"glm-5.2","name":"GLM-5.2","category":"opensource","go":10,"goat":70,"pro":80}, +{"id":"glm-5.2-fast","name":"GLM-5.2 Fast","category":"opensource","go":9,"goat":20,"pro":30}, +{"id":"glm-5.3","name":"GLM-5.3","category":"opensource","go":10,"goat":70,"pro":80}, +{"id":"glm-5.3-flash","name":"GLM-5.3 Flash","category":"opensource","go":10,"goat":100,"pro":110}, +{"id":"glm-5.3-flashx","name":"GLM-5.3 FlashX","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"gpt-5.3-codex","name":"GPT-5.3 Codex","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"gpt-5.4","name":"GPT-5.4","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"gpt-5.4-mini","name":"GPT-5.4 Mini","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"gpt-5.5","name":"GPT-5.5","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"gpt-5.6-luna","name":"GPT-5.6 Luna","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"gpt-5.6-sol","name":"GPT-5.6 Sol","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"gpt-5.6-terra","name":"GPT-5.6 Terra","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"gpt-6-astra","name":"GPT-6 Astra","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"gpt-6-luna","name":"GPT-6 Luna","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"gpt-6-sol","name":"GPT-6 Sol","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"gpt-6.1-sol","name":"GPT-6.1 Sol","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"gpt-6.1-terra","name":"GPT-6.1 Terra","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"grok-4.5","name":"Grok 4.5","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"grok-4.6","name":"Grok 4.6","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"grok-4.7","name":"Grok 4.7","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"inkling","name":"Inkling","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"inkling-small","name":"Inkling Small","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"kimi-k2.5","name":"Kimi K2.5","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"kimi-k2.6","name":"Kimi K2.6","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"kimi-k2.7-code","name":"Kimi K2.7 Code","category":"opensource","go":9,"goat":60,"pro":70}, +{"id":"kimi-k2.7-code-highspeed","name":"Kimi K2.7 Code HighSpeed","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"kimi-k3","name":"Kimi K3","category":"opensource","go":8,"goat":20,"pro":30}, +{"id":"kimi-k3.1-pro","name":"Kimi K3.1 Pro","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"ling-3.1-flash","name":"Ling 3.1 Flash","category":"opensource","go":6,"goat":100,"pro":110}, +{"id":"ling-3.1-flash-1019","name":"Ling 3.1 Flash 1019","category":"opensource","go":6,"goat":100,"pro":110}, +{"id":"longcat-2.0","name":"LongCat 2.0","category":"opensource","go":10,"goat":50,"pro":60}, +{"id":"mimo-v2.6-flash","name":"MiMo V2.6 Flash","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"mimo-v2.6-pro","name":"MiMo V2.6 Pro","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"mimo-v2.6-pro-ultraspeed","name":"MiMo V2.6 Pro UltraSpeed","category":"opensource","go":6,"goat":10,"pro":20}, +{"id":"minimax-m2.5","name":"MiniMax M2.5","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"minimax-m2.7","name":"MiniMax M2.7","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"minimax-m3","name":"MiniMax M3","category":"opensource","go":8,"goat":47,"pro":57}, +{"id":"minimax-m3.1-flash","name":"MiniMax M3.1 Flash","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"mistral-large-4","name":"Mistral Large 4","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"muse-ember","name":"Muse Ember","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"muse-spark-1.1","name":"Muse Spark 1.1","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"muse-spark-1.2","name":"Muse Spark 1.2","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"muse-spark-1.2-contributor","name":"Muse Spark 1.2 Contributor","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"muse-spark-1.3","name":"Muse Spark 1.3","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"muse-spark-1.3-contributor","name":"Muse Spark 1.3 Contributor","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"muse-spark-open","name":"Muse Spark Open","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"muse-wonder-1.0","name":"Muse Wonder","category":"premium","go":6,"goat":20,"pro":20}, +{"id":"nemotron-3-ultra","name":"Nemotron 3 Ultra","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"nemotron-3.5-super-vl","name":"Nemotron 3.5 Super VL","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"ornith-1.5-122b","name":"Ornith 1.5 122B","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"qwen-3.6-max","name":"Qwen 3.6 Max Preview","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"qwen-3.6-plus","name":"Qwen 3.6 Plus","category":"opensource","go":10,"goat":33,"pro":43}, +{"id":"qwen-3.7-flash","name":"Qwen 3.7 Flash","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"qwen-3.7-max","name":"Qwen 3.7 Max","category":"opensource","go":10,"goat":33,"pro":43}, +{"id":"qwen-3.7-plus","name":"Qwen 3.7 Plus","category":"opensource","go":10,"goat":33,"pro":43}, +{"id":"qwen-3.8-27b","name":"Qwen 3.8 27B","category":"opensource","go":10,"goat":70,"pro":80}, +{"id":"qwen-3.8-flash","name":"Qwen 3.8 Flash","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"qwen-3.8-max","name":"Qwen 3.8 Max","category":"opensource","go":7,"goat":20,"pro":30}, +{"id":"qwen-3.8-max-0902","name":"Qwen 3.8 Max 0902","category":"opensource","go":7,"goat":20,"pro":30}, +{"id":"qwen-3.8-max-prime","name":"Qwen 3.8 Max Prime","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"qwen-3.8-omni-flash","name":"Qwen 3.8 Omni Flash","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"qwen-4-max","name":"Qwen 4 Max","category":"opensource","go":6,"goat":15,"pro":25}, +{"id":"step-3.5-flash","name":"Step 3.5 Flash","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"step-3.7-flash","name":"Step 3.7 Flash","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"step-5-preview","name":"Step 5 Preview","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"tencent/hy3-paid","name":"Tencent Hy3","category":"opensource","go":10,"goat":70,"pro":80}, +{"id":"tencent/hy4-preview","name":"Tencent Hy4 Preview","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"typesafe/jev","name":"Jev","category":"opensource","go":6,"goat":20,"pro":30}, +{"id":"typesafe/jev-1.14.0","name":"Jev 1.14.0","category":"opensource","go":6,"goat":20,"pro":30} +]} diff --git a/internal/app/boosted.go b/internal/app/boosted.go new file mode 100644 index 0000000..ae5aabe --- /dev/null +++ b/internal/app/boosted.go @@ -0,0 +1,287 @@ +package app + +import ( + _ "embed" + "encoding/json" + "sort" + "strings" + "sync" +) + +// Command Code publishes a per-model monthly allowance per plan (the "boosted +// usage" deals). The pool is charged in plan credits, so one model's dollars +// per credit differ from another's: GOAT grants a 70-credit pool and, on +// DeepSeek V4.1 Flash, a $100 allowance (1 credit buys $1.43 of usage). +// allowances.json is captured from the docs model catalog; it is reference +// data, not configuration, and the upstream credit numbers stay authoritative. +// Regenerate it with `go generate ./internal/app`. +// +//go:generate go run ../../cmd/gen-allowances -out allowances.json +//go:embed allowances.json +var allowancesJSON []byte + +// allowanceTable is the captured catalog plus the per-plan standard allowance. +type allowanceTable struct { + Source string `json:"source"` + Captured string `json:"captured"` + Models []struct { + ID string `json:"id"` + Name string `json:"name"` + Category string `json:"category"` + Go float64 `json:"go"` + Goat float64 `json:"goat"` + Pro float64 `json:"pro"` + } `json:"models"` +} + +// allowanceEntry is one model's monthly allowance for the plan in use. +type allowanceEntry struct { + ID string + Name string + Category string + Go float64 + Goat float64 + Pro float64 +} + +// standardAllowance is the allowance shared by the plan's non-boosted models. +// Anything above it is a boosted allowance worth showing to the operator. +var standardAllowance = map[string]float64{"go": 6, "goat": 20, "pro": 30} + +var ( + allowanceOnce sync.Once + allowanceIndex map[string]allowanceEntry +) + +// BoostedModelView is one model's remaining allowance, expressed both in plan +// credits (authoritative) and in the model's own USD allowance (derived). +type BoostedModelView struct { + ID string `json:"id"` + Name string `json:"name"` + AllowanceUSD float64 `json:"allowance_usd"` + Factor float64 `json:"factor"` + RemainingUSD float64 `json:"remaining_usd"` + FiveHourUSD *float64 `json:"five_hour_usd,omitempty"` + WeeklyUSD *float64 `json:"weekly_usd,omitempty"` +} + +// BoostedView is the per-account boosted-allowance tracker. Models lists the +// boosted models of the account's plan, highest allowance first. StandardUSD is +// the plan's baseline per-model allowance and StandardModels how many catalog +// models sit at that baseline, so the UI can summarise without dumping them. +type BoostedView struct { + Plan string `json:"plan"` + PoolCredits float64 `json:"pool_credits"` + StandardUSD float64 `json:"standard_usd"` + Standard int `json:"standard_models"` + Models []BoostedModelView `json:"models"` + SourceURL string `json:"source_url"` + SourceDate string `json:"source_captured"` +} + +func initAllowances() { + allowanceOnce.Do(func() { + allowanceIndex = map[string]allowanceEntry{} + var table allowanceTable + if err := json.Unmarshal(allowancesJSON, &table); err != nil { + return + } + for _, m := range table.Models { + entry := allowanceEntry{ID: m.ID, Name: m.Name, Category: m.Category, Go: m.Go, Goat: m.Goat, Pro: m.Pro} + for _, key := range []string{normalizeModelID(m.ID), normalizeModelID(m.Name)} { + if key == "" { + continue + } + if _, taken := allowanceIndex[key]; !taken { + allowanceIndex[key] = entry + } + } + allowanceIndex["#"+m.ID] = entry + allowanceSourceURL = table.Source + allowanceSourceDate = table.Captured + } + }) +} + +var ( + allowanceSourceURL string + allowanceSourceDate string +) + +// normalizeModelID makes provider-prefixed gateway ids ("deepseek/deepseek-v4.1- +// flash", "Qwen/Qwen3.8-Max-0902") and catalog ids ("deepseek-v4.1-flash") +// comparable: lowercase, namespace removed, punctuation dropped. +func normalizeModelID(id string) string { + id = strings.ToLower(strings.TrimSpace(id)) + if i := strings.LastIndex(id, "/"); i >= 0 { + id = id[i+1:] + } + var b strings.Builder + for _, r := range id { + switch { + case r >= 'a' && r <= 'z', r >= '0' && r <= '9': + b.WriteRune(r) + } + } + return b.String() +} + +// allowanceFor resolves a gateway model id to its catalog entry. Exact id and +// display-name matches win; a catalog id that is a prefix of the gateway id +// covers date-stamped variants such as claude-haiku-4-5-20251001. +func allowanceFor(modelID string) (allowanceEntry, bool) { + initAllowances() + if len(allowanceIndex) == 0 { + return allowanceEntry{}, false + } + key := normalizeModelID(modelID) + if entry, ok := allowanceIndex[key]; ok { + return entry, true + } + raw := strings.ToLower(strings.TrimSpace(modelID)) + if entry, ok := allowanceIndex["#"+raw]; ok { + return entry, true + } + best := "" + var bestEntry allowanceEntry + for candidate, entry := range allowanceIndex { + if strings.HasPrefix(candidate, "#") || candidate == "" || !strings.HasPrefix(key, candidate) { + continue + } + if len(candidate) > len(best) { + best, bestEntry = candidate, entry + } + } + if best == "" { + return allowanceEntry{}, false + } + return bestEntry, true +} + +// planTier maps a planId to the catalog's plan column. Provider/Ultra/Max plans +// have no per-model table here, so they fall through to no tracker. +func planTier(planID string) string { + id := strings.ToLower(strings.ReplaceAll(strings.TrimSpace(planID), "_", "-")) + switch { + case strings.HasPrefix(id, "individual-provider"): + return "" + case strings.HasPrefix(id, "individual-goat"): + return "goat" + case strings.HasPrefix(id, "individual-go"): + return "go" + case strings.HasPrefix(id, "individual-pro"): + return "pro" + } + return "" +} + +func allowanceForTier(entry allowanceEntry, tier string) float64 { + switch tier { + case "go": + return entry.Go + case "goat": + return entry.Goat + case "pro": + return entry.Pro + } + return 0 +} + +// BoostedFor derives the boosted-model tracker from a cached quota snapshot. +// The credit numbers come from upstream; only the USD conversion uses the +// captured catalog, and it is labelled as an estimate in the UI. A nil result +// means the plan has no per-model allowance table (Provider, Max, unknown) or +// the snapshot lacks the pool and remaining balance. +func BoostedFor(snap *QuotaSnapshot) *BoostedView { + if snap == nil || snap.Plan == nil || snap.Plan.MonthlyCredits == nil || snap.MonthlyCredits == nil { + return nil + } + // Without the usage aggregate the pool is only the community CLI's static + // estimate (100 credits for GOAT) rather than the observed allowance + // (70), which would skew every factor by ~30%. Show no tracker instead of + // a wrong one. + if snap.Usage == nil { + return nil + } + tier := planTier(snap.Plan.PlanID) + if tier == "" { + return nil + } + pool := *snap.Plan.MonthlyCredits + remaining := *snap.MonthlyCredits + if pool <= 0 || remaining < 0 { + return nil + } + if remaining > pool { + remaining = pool + } + standard, ok := standardAllowance[tier] + if !ok { + return nil + } + + initAllowances() + view := &BoostedView{ + Plan: tier, + PoolCredits: pool, + StandardUSD: standard, + SourceURL: allowanceSourceURL, + SourceDate: allowanceSourceDate, + } + seen := map[string]bool{} + for _, entry := range allowanceIndex { + if strings.HasPrefix(entry.ID, "#") || seen[entry.ID] { + continue + } + seen[entry.ID] = true + allowance := allowanceForTier(entry, tier) + if allowance <= 0 { + continue + } + if allowance <= standard { + if allowance == standard { + view.Standard++ + } + continue + } + factor := allowance / pool + model := BoostedModelView{ + ID: entry.ID, + Name: cleanModelName(entry.Name), + AllowanceUSD: allowance, + Factor: factor, + RemainingUSD: remaining * factor, + } + model.FiveHourUSD = windowUSD(snap.FiveHour, factor) + model.WeeklyUSD = windowUSD(snap.Weekly, factor) + view.Models = append(view.Models, model) + } + sort.Slice(view.Models, func(i, j int) bool { + if view.Models[i].AllowanceUSD != view.Models[j].AllowanceUSD { + return view.Models[i].AllowanceUSD > view.Models[j].AllowanceUSD + } + return view.Models[i].Name < view.Models[j].Name + }) + if len(view.Models) == 0 { + return nil + } + return view +} + +// windowUSD converts a window's remaining credits to the model's USD allowance. +func windowUSD(w *QuotaWindow, factor float64) *float64 { + if w == nil || w.Cap <= 0 { + return nil + } + left := w.Cap - w.Used + if left < 0 { + left = 0 + } + v := left * factor + return &v +} + +// cleanModelName drops the "(latest)" suffix the catalog adds to current ids. +func cleanModelName(name string) string { + return strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(name), "(latest)")) +} diff --git a/internal/app/boosted_test.go b/internal/app/boosted_test.go new file mode 100644 index 0000000..5ceed93 --- /dev/null +++ b/internal/app/boosted_test.go @@ -0,0 +1,192 @@ +package app + +import ( + "math" + "testing" +) + +func approx(t *testing.T, got, want float64, label string) { + t.Helper() + if math.Abs(got-want) > 0.01 { + t.Fatalf("%s = %v, want %v", label, got, want) + } +} + +// A GOAT account on DeepSeek V4.1 Flash: 70.014-credit pool, $100 allowance, +// 35 credits weekly. The weekly window is spent, so its USD remainder is zero +// while the monthly remainder converts to roughly $50. +func TestBoostedForGoat(t *testing.T) { + snap := &QuotaSnapshot{ + MonthlyCredits: floatPtr(34.9968542434), + Usage: &QuotaUsage{TotalCredits: 35.01748727819996}, + FiveHour: &QuotaWindow{Used: 0.4058471802, Cap: 14}, + Weekly: &QuotaWindow{Used: 35.0031457566, Cap: 35}, + Plan: &QuotaPlan{ + PlanID: "individual-goat", + Name: "GOAT", + MonthlyCredits: floatPtr(70.01434152159996), + }, + } + view := BoostedFor(snap) + if view == nil { + t.Fatal("BoostedFor returned nil for a GOAT snapshot") + } + if view.Plan != "goat" || view.StandardUSD != 20 { + t.Fatalf("plan/standard = %q/%v, want goat/20", view.Plan, view.StandardUSD) + } + if view.Standard <= 0 { + t.Fatalf("standard model count = %d, want > 0", view.Standard) + } + if len(view.Models) == 0 { + t.Fatal("no boosted models") + } + + var deepseek *BoostedModelView + for i := range view.Models { + if view.Models[i].ID == "deepseek-v4.1-flash" { + deepseek = &view.Models[i] + } + } + if deepseek == nil { + t.Fatal("deepseek-v4.1-flash missing from the boosted list") + } + approx(t, deepseek.AllowanceUSD, 100, "allowance") + approx(t, deepseek.Factor, 100.0/70.01434152159996, "factor") + approx(t, deepseek.RemainingUSD, 49.985, "remaining USD") + if deepseek.FiveHourUSD == nil { + t.Fatal("five-hour USD missing") + } + approx(t, *deepseek.FiveHourUSD, 19.417, "five-hour USD") + if deepseek.WeeklyUSD == nil || *deepseek.WeeklyUSD != 0 { + t.Fatalf("weekly USD = %v, want 0 for a spent window", deepseek.WeeklyUSD) + } + + // Highest allowance first. + for i := 1; i < len(view.Models); i++ { + if view.Models[i-1].AllowanceUSD < view.Models[i].AllowanceUSD { + t.Fatalf("models not sorted by allowance at %d", i) + } + } + // Standard and reduced models stay out of the boosted list. + for _, m := range view.Models { + if m.AllowanceUSD <= view.StandardUSD { + t.Fatalf("%s has allowance %v, not above standard %v", m.ID, m.AllowanceUSD, view.StandardUSD) + } + } +} + +// A Go account: 10-credit pool, standard allowance $6, boosted models up to $10. +func TestBoostedForGoPlan(t *testing.T) { + snap := &QuotaSnapshot{ + MonthlyCredits: floatPtr(3.815053954), + Usage: &QuotaUsage{TotalCredits: 6.189325638}, + Plan: &QuotaPlan{ + PlanID: "individual-go-v1", + Name: "Go", + MonthlyCredits: floatPtr(10.004379592), + }, + } + view := BoostedFor(snap) + if view == nil { + t.Fatal("BoostedFor returned nil for a Go snapshot") + } + if view.StandardUSD != 6 { + t.Fatalf("standard = %v, want 6", view.StandardUSD) + } + for _, m := range view.Models { + if m.ID == "deepseek-v4.1-flash" { + approx(t, m.AllowanceUSD, 10, "go allowance") + approx(t, m.RemainingUSD, 3.813, "go remaining USD") + return + } + } + t.Fatal("deepseek-v4.1-flash missing from the Go boosted list") +} + +// A remaining balance above the observed pool (carried or bonus credits) must +// not push a model's estimate past its own allowance. +func TestBoostedForClampsRemaining(t *testing.T) { + snap := &QuotaSnapshot{ + MonthlyCredits: floatPtr(90), + Usage: &QuotaUsage{TotalCredits: 10}, + Plan: &QuotaPlan{PlanID: "individual-goat", Name: "GOAT", MonthlyCredits: floatPtr(70)}, + } + view := BoostedFor(snap) + if view == nil { + t.Fatal("BoostedFor returned nil") + } + top := view.Models[0] + approx(t, top.RemainingUSD, top.AllowanceUSD, "clamped remaining") +} + +// Plans without a per-model allowance table, or snapshots without the numbers +// the conversion needs, produce no tracker at all. +func TestBoostedForSkipsUnknownPlans(t *testing.T) { + cases := map[string]*QuotaSnapshot{ + "nil snapshot": nil, + "no plan": { + MonthlyCredits: floatPtr(10), + }, + "provider plan": { + MonthlyCredits: floatPtr(10), + Plan: &QuotaPlan{PlanID: "individual-provider", MonthlyCredits: floatPtr(15)}, + }, + "max plan": { + MonthlyCredits: floatPtr(100), + Plan: &QuotaPlan{PlanID: "individual-max", MonthlyCredits: floatPtr(150)}, + }, + "unknown plan": { + MonthlyCredits: floatPtr(10), + Plan: &QuotaPlan{PlanID: "individual-mystery", MonthlyCredits: floatPtr(10)}, + }, + "no pool": { + MonthlyCredits: floatPtr(10), + Plan: &QuotaPlan{PlanID: "individual-goat"}, + }, + "no remaining": { + Plan: &QuotaPlan{PlanID: "individual-goat", MonthlyCredits: floatPtr(70)}, + }, + // Without the usage aggregate the pool is only the static plan estimate + // (100 for GOAT), so the conversion must be skipped, not guessed. + "no usage aggregate": { + MonthlyCredits: floatPtr(34), + Plan: &QuotaPlan{PlanID: "individual-goat", Name: "GOAT", MonthlyCredits: floatPtr(100)}, + }, + "zero pool": { + MonthlyCredits: floatPtr(0), + Plan: &QuotaPlan{PlanID: "individual-goat", MonthlyCredits: floatPtr(0)}, + }, + } + for name, snap := range cases { + if view := BoostedFor(snap); view != nil { + t.Fatalf("%s: expected nil, got %+v", name, view) + } + } +} + +// Gateway ids carry provider namespaces and date stamps, the catalog does not. +func TestAllowanceLookup(t *testing.T) { + cases := []struct { + modelID string + wantID string + }{ + {"deepseek/deepseek-v4.1-flash", "deepseek-v4.1-flash"}, + {"z-ai/glm-5.3-flash", "glm-5.3-flash"}, + {"inclusionai/ling-3.1-flash", "ling-3.1-flash"}, + {"Qwen/Qwen3.8-Max-0902", "qwen-3.8-max-0902"}, + {"MiniMaxAI/MiniMax-M2.5", "minimax-m2.5"}, + {"claude-haiku-4-5-20251001", "claude-haiku-4-5"}, + } + for _, tc := range cases { + entry, ok := allowanceFor(tc.modelID) + if !ok { + t.Fatalf("%s: not found", tc.modelID) + } + if entry.ID != tc.wantID { + t.Fatalf("%s: matched %s, want %s", tc.modelID, entry.ID, tc.wantID) + } + } + if _, ok := allowanceFor("not/a-real-model"); ok { + t.Fatal("unknown model matched an allowance entry") + } +} diff --git a/internal/app/quota.go b/internal/app/quota.go index f5a0d42..cc50246 100644 --- a/internal/app/quota.go +++ b/internal/app/quota.go @@ -36,9 +36,10 @@ type QuotaWindow struct { } // QuotaPlan is the account's subscription and billing period. MonthlyCredits is -// the plan's estimated monthly cap: the API exposes no monthly window object, -// so the cap is derived from the plan mapping and is nil for unknown plans, -// in which case the UI falls back to balance-only display. +// the plan's allowance for the model in use: the API exposes no monthly window +// object, so it is derived from the remaining balance plus the billing-period +// spend, falling back to the plan mapping estimate only when the usage +// aggregate is unavailable. When nil the UI falls back to balance-only display. type QuotaPlan struct { PlanID string `json:"plan_id,omitempty"` Name string `json:"name,omitempty"` @@ -99,22 +100,20 @@ func (q *QuotaSnapshot) Blocked() bool { // ====== plan mapping ====== +// planSpec is the fallback plan metadata used when the upstream balance or +// usage aggregates are unavailable. MonthlyCredits is only an estimate: the +// real allowance is derived from the upstream remaining balance plus the +// billing-period spend, because it varies with the model in use. type planSpec struct { Name string MonthlyCredits float64 - // FiveHourCredits and WeeklyCredits override the upstream rolling caps when - // non-zero. The upstream endpoint scales its windows from the base - // per-model allowance, so for models whose allowance exceeds that base it - // reports caps lower than the plan's published limits. - FiveHourCredits float64 - WeeklyCredits float64 } // knownPlans mirrors the community CLI's planId mapping. Unknown plans are // reported by ID with no monthly cap, so the UI hides the derived monthly bar. var knownPlans = map[string]planSpec{ "individual-go": {Name: "Go", MonthlyCredits: 10}, - "individual-goat": {Name: "GOAT", MonthlyCredits: 100, FiveHourCredits: 20, WeeklyCredits: 50}, + "individual-goat": {Name: "GOAT", MonthlyCredits: 100}, "individual-pro": {Name: "Pro", MonthlyCredits: 30}, "individual-pro-v1": {Name: "Pro", MonthlyCredits: 80}, "individual-provider": {Name: "Provider", MonthlyCredits: 15}, @@ -319,41 +318,21 @@ func buildQuotaPlan(planID string, data map[string]any) *QuotaPlan { return plan } -// applyPlanWindows replaces the upstream rolling caps with the plan's published -// limits. The upstream caps are derived from a base per-model allowance, so -// they under-report plans or models with a higher allowance. -func applyPlanWindows(snap *QuotaSnapshot) { - if snap == nil || snap.Plan == nil { +// applyPlanAllowance replaces the plan's static estimate with the allowance +// actually observed by the upstream: monthlyCredits is the remaining balance, +// so remaining plus billing-period spend is the allowance for the model in use. +// GOAT reports 14/35 credit windows on a $70-allowance model and the same +// windows scaled up on a $100-allowance model, so a hardcoded dollar cap would +// misreport one of them. Without usage data the estimate is kept. +func applyPlanAllowance(snap *QuotaSnapshot) { + if snap == nil || snap.Plan == nil || snap.MonthlyCredits == nil || snap.Usage == nil { return } - spec, ok := planInfo(snap.Plan.PlanID) - if !ok { + allowance := *snap.MonthlyCredits + snap.Usage.TotalCredits + if allowance <= 0 { return } - if spec.FiveHourCredits > 0 && snap.FiveHour != nil { - snap.FiveHour.Cap = spec.FiveHourCredits - } - if spec.WeeklyCredits > 0 && snap.Weekly != nil { - snap.Weekly.Cap = spec.WeeklyCredits - } -} - -// applyPlanRemaining rewrites the upstream monthly balance for plans whose -// published allowance is higher than the upstream base allowance. The -// remaining figure becomes the plan cap minus the billing-period spend. -func applyPlanRemaining(snap *QuotaSnapshot) { - if snap == nil || snap.Plan == nil || snap.Plan.MonthlyCredits == nil || snap.Usage == nil { - return - } - spec, ok := planInfo(snap.Plan.PlanID) - if !ok || (spec.FiveHourCredits == 0 && spec.WeeklyCredits == 0) { - return - } - remaining := *snap.Plan.MonthlyCredits - snap.Usage.TotalCredits - if remaining < 0 { - remaining = 0 - } - snap.MonthlyCredits = &remaining + snap.Plan.MonthlyCredits = &allowance } func parseQuotaUsage(raw map[string]any) *QuotaUsage { @@ -512,7 +491,6 @@ func fetchQuotaSnapshot(ctx context.Context, client *http.Client, baseURL, apiKe snap.Plan = buildQuotaPlan(planID, data) } } - applyPlanWindows(snap) // 4. usage/summary → billing-period aggregates. if usageResp, err := quotaGet(ctx, client, base+"/alpha/usage/summary", apiKey); err != nil { @@ -524,7 +502,7 @@ func fetchQuotaSnapshot(ctx context.Context, client *http.Client, baseURL, apiKe } snap.Usage = parseQuotaUsage(root) } - applyPlanRemaining(snap) + applyPlanAllowance(snap) if len(failures) > 0 { snap.Failures = failures diff --git a/internal/app/quota_test.go b/internal/app/quota_test.go index d1eb87d..a0e55e1 100644 --- a/internal/app/quota_test.go +++ b/internal/app/quota_test.go @@ -151,8 +151,10 @@ func TestFetchQuotaSnapshotHappyPath(t *testing.T) { if !snap.Limited || snap.Exceeded != "weekly" { t.Fatalf("limit flags = limited:%v exceeded:%q", snap.Limited, snap.Exceeded) } + // The cap is the observed allowance (remaining 12.5 + spend 8.5), not the + // plan mapping estimate. if snap.Plan == nil || snap.Plan.PlanID != "individual-pro-v1" || snap.Plan.Name != "Pro" || - snap.Plan.MonthlyCredits == nil || *snap.Plan.MonthlyCredits != 80 || + snap.Plan.MonthlyCredits == nil || *snap.Plan.MonthlyCredits != 21 || snap.Plan.Status != "active" || !snap.Plan.CancelAtPeriodEnd || snap.Plan.CurrentPeriodEnd == nil { t.Fatalf("plan = %+v", snap.Plan) } @@ -188,12 +190,12 @@ func TestFetchQuotaSnapshotHappyPath(t *testing.T) { } } -func TestFetchQuotaSnapshotAppliesPlanWindowCaps(t *testing.T) { +func TestFetchQuotaSnapshotKeepsUpstreamWindowCaps(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch r.URL.Path { case "/alpha/billing/credits": - fmt.Fprint(w, `{"credits":{"monthlyCredits":70,"planId":"individual-goat"},"windowLimits":{"limited":true,"fiveHour":{"used":5,"cap":14},"weekly":{"used":40,"cap":35,"exceeded":true}}}`) + fmt.Fprint(w, `{"credits":{"monthlyCredits":60,"planId":"individual-goat"},"windowLimits":{"limited":true,"fiveHour":{"used":5,"cap":14},"weekly":{"used":35,"cap":35,"exceeded":true}}}`) case "/alpha/billing/subscriptions": fmt.Fprint(w, `{"data":{"planId":"individual-goat","status":"active"}}`) case "/alpha/usage/summary": @@ -208,17 +210,21 @@ func TestFetchQuotaSnapshotAppliesPlanWindowCaps(t *testing.T) { if err != nil { t.Fatalf("fetch failed: %v", err) } - if snap.Plan == nil || snap.Plan.MonthlyCredits == nil || *snap.Plan.MonthlyCredits != 100 { - t.Fatalf("GOAT plan = %+v", snap.Plan) + // The upstream allowance is per-model, so the plan cap must be derived from + // remaining + spend instead of a static dollar figure. + if snap.Plan == nil || snap.Plan.MonthlyCredits == nil || *snap.Plan.MonthlyCredits != 70 { + t.Fatalf("GOAT plan = %+v, want a derived 70 credit allowance", snap.Plan) } - if snap.FiveHour == nil || snap.FiveHour.Cap != 20 { - t.Fatalf("GOAT five hour window = %+v", snap.FiveHour) + // Credit windows come from the upstream untouched. + if snap.FiveHour == nil || snap.FiveHour.Cap != 14 { + t.Fatalf("GOAT five hour window = %+v, want the upstream cap 14", snap.FiveHour) } - if snap.Weekly == nil || snap.Weekly.Cap != 50 || !snap.Weekly.Exceeded { - t.Fatalf("GOAT weekly window = %+v", snap.Weekly) + if snap.Weekly == nil || snap.Weekly.Cap != 35 || !snap.Weekly.Exceeded { + t.Fatalf("GOAT weekly window = %+v, want the upstream cap 35", snap.Weekly) } - if snap.MonthlyCredits == nil || *snap.MonthlyCredits != 90 { - t.Fatalf("GOAT remaining credits = %v, want 90", snap.MonthlyCredits) + // The remaining balance is the upstream value; it must not be rewritten. + if snap.MonthlyCredits == nil || *snap.MonthlyCredits != 60 { + t.Fatalf("GOAT remaining credits = %v, want the upstream 60", snap.MonthlyCredits) } } @@ -253,7 +259,9 @@ func TestFetchQuotaSnapshotSnakeCaseAndNested(t *testing.T) { if snap.Weekly == nil || snap.Weekly.Used != 1 || snap.Weekly.Cap != 20 || !snap.Weekly.Exceeded { t.Fatalf("weekly window = %+v", snap.Weekly) } - if snap.Plan == nil || snap.Plan.Name != "unknown-plan" || snap.Plan.MonthlyCredits != nil { + // Unknown plans still get an observed allowance: remaining 12.5 + spend 0.3. + if snap.Plan == nil || snap.Plan.Name != "unknown-plan" || snap.Plan.MonthlyCredits == nil || + *snap.Plan.MonthlyCredits < 12.8-1e-9 || *snap.Plan.MonthlyCredits > 12.8+1e-9 { t.Fatalf("unknown plan = %+v", snap.Plan) } if snap.Plan.CurrentPeriodEnd == nil || snap.Plan.CurrentPeriodEnd.UTC().Year() != 2030 {