Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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).

Expand Down Expand Up @@ -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

Expand Down
10 changes: 6 additions & 4 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 使用独立管理密码
Expand Down Expand Up @@ -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` 嵌套)。
Expand Down Expand Up @@ -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

Expand Down
294 changes: 294 additions & 0 deletions cmd/gen-allowances/main.go
Original file line number Diff line number Diff line change
@@ -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
}
Loading
Loading