From b2908a574fa68bccb2bc3e401234b76ffc57b02f Mon Sep 17 00:00:00 2001 From: 0x33a Date: Mon, 16 Nov 2026 09:28:01 +0000 Subject: [PATCH] build(allowances): vendor the catalog from commandcode-catalog Move the scraper out of the app: commandcode-catalog now owns the docs parsing and publishes catalog.json weekly. The app vendors a validated snapshot for go:embed, so builds stay offline and a bad upstream deploy cannot affect a released binary. go generate ./internal/app now runs cmd/vendor-allowances, which checks the schema and model invariants before replacing the snapshot. The vendored copy picks up tencent/hy4-flash. --- README.md | 2 +- README.zh-CN.md | 2 +- cmd/gen-allowances/main.go | 294 ----------------------------- cmd/gen-allowances/main_test.go | 77 -------- cmd/vendor-allowances/main.go | 166 ++++++++++++++++ cmd/vendor-allowances/main_test.go | 115 +++++++++++ internal/app/allowances.json | 3 +- internal/app/boosted.go | 9 +- 8 files changed, 290 insertions(+), 378 deletions(-) delete mode 100644 cmd/gen-allowances/main.go delete mode 100644 cmd/gen-allowances/main_test.go create mode 100644 cmd/vendor-allowances/main.go create mode 100644 cmd/vendor-allowances/main_test.go diff --git a/README.md b/README.md index e031eb7..cbef7d4 100644 --- a/README.md +++ b/README.md @@ -212,7 +212,7 @@ The Accounts tab shows each account's Command Code quota, read with the same API - 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. +- 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 vendored from [commandcode-catalog](https://github.com/peach0x33a/commandcode-catalog) (`internal/app/allowances.json`, refreshed with `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). diff --git a/README.zh-CN.md b/README.zh-CN.md index 306318f..7e035ca 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -212,7 +212,7 @@ http://localhost:11434/webui - 余额(月度剩余 / 充值 / 免费)、套餐名称与状态、账期结束时间、账期用量统计。进度条与余额一律按接口返回的「积分」显示,不会写成美元。 - 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 等没有公开逐模型额度表的套餐不显示该跟踪器。 +- 每张卡片带可折叠的**提升额度**跟踪器。Command Code 按模型公布月度额度(官方「提升用量」活动),但都从同一个积分池扣费,因此不同模型的「每积分对应多少美元」并不相同。表格列出每个提升模型的官方额度、相对积分池的倍率,以及按账号剩余积分换算的剩余美元额度;摘要行还给出 5 小时 / 本周窗口的估算。额度表从 [commandcode-catalog](https://github.com/peach0x33a/commandcode-catalog) 同步到 `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` 嵌套)。 diff --git a/cmd/gen-allowances/main.go b/cmd/gen-allowances/main.go deleted file mode 100644 index 9ff261f..0000000 --- a/cmd/gen-allowances/main.go +++ /dev/null @@ -1,294 +0,0 @@ -// 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 deleted file mode 100644 index 18fa667..0000000 --- a/cmd/gen-allowances/main_test.go +++ /dev/null @@ -1,77 +0,0 @@ -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/cmd/vendor-allowances/main.go b/cmd/vendor-allowances/main.go new file mode 100644 index 0000000..1692e3e --- /dev/null +++ b/cmd/vendor-allowances/main.go @@ -0,0 +1,166 @@ +// Command vendor-allowances replaces internal/app/allowances.json with the +// catalog published by the commandcode-catalog repository. +// +// That repository generates the catalog from the Command Code pricing page. The +// app vendors a copy so builds stay offline and a bad upstream deploy cannot +// affect an already-released binary; only the catalog's schema is trusted at +// vendoring time. +// +// Run it with: +// +// go generate ./internal/app +package main + +import ( + "bytes" + "context" + "encoding/json" + "flag" + "fmt" + "io" + "net/http" + "os" + "time" +) + +const ( + catalogURL = "https://raw.githubusercontent.com/peach0x33a/commandcode-catalog/main/catalog.json" + schemaVersion = 1 + minModels = 50 +) + +// 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 { + Schema int `json:"schema"` + Source string `json:"source"` + Captured string `json:"captured"` + Models []catalogModel `json:"models"` +} + +func main() { + out := flag.String("out", "allowances.json", "output file") + url := flag.String("url", catalogURL, "catalog URL") + flag.Parse() + if err := run(*url, *out); err != nil { + fmt.Fprintf(os.Stderr, "vendor-allowances: %v\n", err) + os.Exit(1) + } +} + +func run(url, out string) error { + data, err := fetch(url) + if err != nil { + return err + } + catalog, err := validate(data) + if err != nil { + return fmt.Errorf("%s: %w", url, err) + } + if len(data) == 0 || data[len(data)-1] != '\n' { + data = append(data, '\n') + } + + // The published file is already the compact one-object-per-line document the + // app embeds, so keep it verbatim; only the trailing newline is normalized. + if old, err := os.ReadFile(out); err == nil && bytes.Equal(old, data) { + fmt.Printf("%s: up to date (%d models, captured %s)\n", out, len(catalog.Models), catalog.Captured) + return nil + } + + tmp := out + ".tmp" + if err := os.WriteFile(tmp, data, 0o644); err != nil { + return err + } + if err := os.Rename(tmp, out); err != nil { + return err + } + fmt.Printf("%s: vendored %d models (captured %s)\n", out, len(catalog.Models), catalog.Captured) + return nil +} + +// fetch retries transient transport failures; a cold connection to the raw host +// occasionally dies on the first try. +func fetch(url string) ([]byte, error) { + var lastErr error + for attempt := 0; attempt < 3; attempt++ { + if attempt > 0 { + time.Sleep(time.Duration(attempt) * time.Second) + } + data, err := fetchOnce(url) + if err == nil { + return data, nil + } + lastErr = err + } + return nil, fmt.Errorf("GET %s: %w", url, lastErr) +} + +func fetchOnce(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 + } + req.Header.Set("User-Agent", "cmdcode2api-vendor-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("unexpected status %s", resp.Status) + } + return io.ReadAll(io.LimitReader(resp.Body, 8<<20)) +} + +// validate checks the published catalog before it is allowed into the binary. +// It is deliberately strict: keeping the previous snapshot is always better than +// embedding a malformed or silently changed one. +func validate(data []byte) (*catalogFile, error) { + var c catalogFile + if err := json.Unmarshal(data, &c); err != nil { + return nil, fmt.Errorf("decode catalog: %w", err) + } + if c.Schema < 1 { + return nil, fmt.Errorf("catalog has no schema version") + } + if c.Schema > schemaVersion { + return nil, fmt.Errorf("catalog schema %d is newer than the supported schema %d; upgrade the binary", c.Schema, schemaVersion) + } + if c.Source == "" { + return nil, fmt.Errorf("catalog has no source") + } + if _, err := time.Parse("2006-01-02", c.Captured); err != nil { + return nil, fmt.Errorf("catalog captured date %q is not YYYY-MM-DD", c.Captured) + } + if len(c.Models) < minModels { + return nil, fmt.Errorf("catalog has only %d models, expected at least %d", len(c.Models), minModels) + } + + seen := make(map[string]bool, len(c.Models)) + for _, m := range c.Models { + if m.ID == "" || m.Name == "" || m.Category == "" { + return nil, fmt.Errorf("model %q has a missing id, name, or category", m.ID) + } + if seen[m.ID] { + return nil, fmt.Errorf("duplicate model id %q", m.ID) + } + seen[m.ID] = true + if m.Go <= 0 || m.Goat <= 0 || m.Pro <= 0 { + return nil, fmt.Errorf("model %q has a non-positive allowance", m.ID) + } + } + return &c, nil +} diff --git a/cmd/vendor-allowances/main_test.go b/cmd/vendor-allowances/main_test.go new file mode 100644 index 0000000..8ba3437 --- /dev/null +++ b/cmd/vendor-allowances/main_test.go @@ -0,0 +1,115 @@ +package main + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestRunVendorsAndLeavesUnchangedFileAlone(t *testing.T) { + payload := catalogPayload(t, 60) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, payload) + })) + defer srv.Close() + + out := filepath.Join(t.TempDir(), "allowances.json") + if err := run(srv.URL, out); err != nil { + t.Fatalf("run: %v", err) + } + first, err := os.ReadFile(out) + if err != nil { + t.Fatalf("read vendored file: %v", err) + } + if want := payload + "\n"; string(first) != want { + t.Fatalf("vendored file = %q, want %q", first, want) + } + + old := time.Unix(1000, 0) + if err := os.Chtimes(out, old, old); err != nil { + t.Fatalf("Chtimes: %v", err) + } + if err := run(srv.URL, out); err != nil { + t.Fatalf("second run: %v", err) + } + info, err := os.Stat(out) + if err != nil { + t.Fatalf("stat: %v", err) + } + if !info.ModTime().Equal(old) { + t.Fatal("run rewrote an unchanged file") + } +} + +func TestRunRejectsNewerSchema(t *testing.T) { + payload := strings.Replace(catalogPayload(t, 60), `"schema":1`, `"schema":2`, 1) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, payload) + })) + defer srv.Close() + + out := filepath.Join(t.TempDir(), "allowances.json") + err := run(srv.URL, out) + if err == nil || !strings.Contains(err.Error(), "newer") { + t.Fatalf("run error = %v, want a schema mismatch", err) + } + if _, statErr := os.Stat(out); !os.IsNotExist(statErr) { + t.Fatal("run wrote a file after rejecting the catalog") + } +} + +func TestValidateRejectsDuplicateID(t *testing.T) { + c := decodeCatalog(t, catalogPayload(t, 60)) + c.Models[1].ID = c.Models[0].ID + data, err := json.Marshal(c) + if err != nil { + t.Fatalf("marshal: %v", err) + } + if _, err := validate(data); err == nil || !strings.Contains(err.Error(), "duplicate") { + t.Fatalf("validate error = %v, want a duplicate id error", err) + } +} + +func TestValidateRejectsNonPositiveAllowance(t *testing.T) { + c := decodeCatalog(t, catalogPayload(t, 60)) + c.Models[0].Pro = 0 + data, err := json.Marshal(c) + if err != nil { + t.Fatalf("marshal: %v", err) + } + if _, err := validate(data); err == nil || !strings.Contains(err.Error(), "non-positive") { + t.Fatalf("validate error = %v, want a non-positive allowance error", err) + } +} + +func decodeCatalog(t *testing.T, data string) catalogFile { + t.Helper() + var c catalogFile + if err := json.Unmarshal([]byte(data), &c); err != nil { + t.Fatalf("decode catalog fixture: %v", err) + } + return c +} + +// catalogPayload builds a catalog document with n valid models and no trailing +// newline, so run must add one. +func catalogPayload(t *testing.T, n int) string { + t.Helper() + var b strings.Builder + b.WriteString(`{"schema":1,"source":"https://example.test/docs","captured":"2026-11-16","models":[`) + for i := 0; i < n; i++ { + if i > 0 { + b.WriteByte(',') + } + fmt.Fprintf(&b, `{"id":"model-%02d","name":"Model %02d","category":"opensource","go":6,"goat":20,"pro":30}`, i, i) + } + b.WriteString("]}") + return b.String() +} diff --git a/internal/app/allowances.json b/internal/app/allowances.json index 53f33d8..71d4d62 100644 --- a/internal/app/allowances.json +++ b/internal/app/allowances.json @@ -1,4 +1,4 @@ -{"source":"https://commandcode.ai/docs/resources/pricing-limits","captured":"2026-11-16","models":[ +{"schema":1,"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}, @@ -95,6 +95,7 @@ {"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-flash","name":"Tencent Hy4 Flash","category":"opensource","go":6,"goat":15,"pro":25}, {"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 index ae5aabe..d076aae 100644 --- a/internal/app/boosted.go +++ b/internal/app/boosted.go @@ -12,11 +12,12 @@ import ( // 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`. +// allowances.json is vendored from the commandcode-catalog repository, which +// captures the docs model catalog; it is reference data, not configuration, and +// the upstream credit numbers stay authoritative. Refresh it with +// `go generate ./internal/app`. // -//go:generate go run ../../cmd/gen-allowances -out allowances.json +//go:generate go run ../../cmd/vendor-allowances -out allowances.json //go:embed allowances.json var allowancesJSON []byte