provider: Kimi Code's month read however /usages tells it, on every route

lidazi2016 (Discord) still saw no monthly limit on v0.1.2023 with a Kimi
Code China API key: the card had 5h and 7 days only. 296f66a74 read the
month from usages.limit_month_total alone. Other ways Kimi tells it went
unread:

- the membership of 2026-09 sends limit_5h and limit_month_code with no
  total (GCMP's kimiUsage.ts); limit_month_code is now the month when
  limit_month_total isn't there;
- a share under its camelCase name (limitMonthTotal, usedRatio,
  resetTime) and a reset as epoch seconds or milliseconds (EchoBird's
  fixture);
- a limits[] window counted in TIME_UNIT_WEEK or TIME_UNIT_MONTH, which
  was "Allowance" with no length.

Every way to add a Kimi Code key reaches the same reader through
planQuotaSourceOf: the kimi-code-cn and kimi-code presets, a provider of
the user's own at https://api.kimi.com/coding (Anthropic base alone), and
an OpenCode auth.json import (kimi-code-plan-cn / -global). There is no
Kimi Code sign-in in magpie. TestPlanQuotasKimiCodeMonthEveryRoute saves
one of each and checks each card's month through PlanQuotas.

Probed with the owner's kimi-code-cn key (read only): GET
api.kimi.com/coding/v1/usages answers 200 {} for that lapsed membership,
so it says nothing about an active one. token-monitor reads the Kimi
console's monthly pool from the kimi.com web API
(MembershipService/GetSubscriptionStats subscriptionBalance) with the
web sign-in's token, not the key; if /usages doesn't carry the month for
an API key, this change can't show it, and that web route is not added.

Run (mote, at this tree rebased on origin/main 4534561f6; also ran at bb3565309 before the rebase):
- go test -tags nogui -count=1 -timeout 45m ./internal/provider/: ok
- go vet ./internal/provider/ for darwin, GOOS=linux and GOOS=windows: ok
- gofmt -l internal/provider/: empty

Broken by hand: the old planquota.go with these tests is red in all
three TestReadKimiCodeMonthEveryWay cases, the week-and-month case, and
all four routes of TestPlanQuotasKimiCodeMonthEveryRoute.

Not tried: a real active Kimi Code China or global key; the reporter's
own /usages reply has not been seen.
This commit is contained in:
yetone
2026-10-29 17:23:44 +08:00
parent b64ec9d64f
commit cf3a2cc838
2 changed files with 157 additions and 21 deletions
+57 -20
View File
@@ -413,9 +413,14 @@ func KimiCodeSearch(p Provider) string {
// "usages":{"limit_5h":{"used_ratio":0.4372,"reset_time":"…"},
// "limit_7d":{…},"limit_month_total":{…},"limit_month_code":{…}}
//
// limit_month_total is the month's allowance; limit_month_code is the
// share of it code has used, no allowance of its own, so it isn't shown.
// A window told both ways is taken from usages, as kimi-code does.
// limit_month_total is the month's allowance. limit_month_code is code's
// share of it (kimi-code) or, on the membership of 2026-09, the coding
// allowance itself with no total beside it (GCMP's kimiUsage.ts), so it
// is the month only when limit_month_total isn't there. A window told
// both ways is taken from usages, as kimi-code does. Each share is read
// under its camelCase name too, a reset as text or epoch seconds or
// milliseconds (EchoBird's fixture), and a limits[] window counted in
// weeks or months by its length.
func readKimiCode(b []byte) (string, []QuotaWindow, error) {
type row map[string]any
var r struct {
@@ -439,6 +444,25 @@ func readKimiCode(b []byte) (string, []QuotaWindow, error) {
}
return 0, false
}
// a reset as RFC 3339 text or as epoch seconds or milliseconds, under
// either spelling of its name
resetOf := func(d row) *time.Time {
for _, k := range []string{"resetTime", "resetAt", "reset_at", "reset_time"} {
if s, _ := d[k].(string); s != "" {
if t, err := time.Parse(time.RFC3339Nano, s); err == nil {
return &t
}
}
if n, ok := num(d[k]); ok && n > 0 {
t := time.Unix(int64(n), 0)
if n > 1e11 {
t = time.UnixMilli(int64(n))
}
return &t
}
}
return nil
}
window := func(d row, name string, span time.Duration) (QuotaWindow, bool) {
limit, ok := num(d["limit"])
if !ok || limit <= 0 {
@@ -453,14 +477,7 @@ func readKimiCode(b []byte) (string, []QuotaWindow, error) {
used = limit - left
}
w := QuotaWindow{Name: name, Span: span, Used: max(0, min(100, used/limit*100))}
for _, k := range []string{"resetTime", "resetAt", "reset_at", "reset_time"} {
if s, _ := d[k].(string); s != "" {
if t, err := time.Parse(time.RFC3339Nano, s); err == nil {
w.ResetsAt = &t
break
}
}
}
w.ResetsAt = resetOf(d)
return w, true
}
out := []QuotaWindow{}
@@ -479,9 +496,15 @@ func readKimiCode(b []byte) (string, []QuotaWindow, error) {
span = time.Duration(n) * time.Hour
case strings.Contains(unit, "DAY"):
span = time.Duration(n) * 24 * time.Hour
case strings.Contains(unit, "WEEK"):
span = time.Duration(n) * 7 * 24 * time.Hour
case strings.Contains(unit, "MONTH"):
span = time.Duration(n) * 30 * 24 * time.Hour
}
name := "Allowance"
switch {
case span == 30*24*time.Hour:
name = "Month"
case span > 24*time.Hour && span%(24*time.Hour) == 0:
name = fmt.Sprintf("%d days", span/(24*time.Hour))
case span >= time.Hour && span%time.Hour == 0:
@@ -500,19 +523,21 @@ func readKimiCode(b []byte) (string, []QuotaWindow, error) {
for _, k := range []struct {
key, name string
span time.Duration
}{{"limit_5h", "5 hours", 5 * time.Hour}, {"limit_7d", "7 days", 7 * 24 * time.Hour}, {"limit_month_total", "Month", 30 * 24 * time.Hour}} {
}{{"limit_5h", "5 hours", 5 * time.Hour}, {"limit_7d", "7 days", 7 * 24 * time.Hour},
{"limit_month_total", "Month", 30 * 24 * time.Hour}, {"limit_month_code", "Month", 30 * 24 * time.Hour}} {
d := r.Usages[k.key]
if d == nil {
d = r.Usages[camel(k.key)]
}
ratio, ok := num(d["used_ratio"])
if d == nil || !ok || math.IsNaN(ratio) || math.IsInf(ratio, 0) {
if !ok {
ratio, ok = num(d["usedRatio"])
}
if d == nil || !ok || math.IsNaN(ratio) || math.IsInf(ratio, 0) ||
slices.ContainsFunc(shares, func(s QuotaWindow) bool { return s.Span == k.span }) {
continue
}
w := QuotaWindow{Name: k.name, Span: k.span, Used: max(0, min(100, ratio*100))}
if s, _ := d["reset_time"].(string); s != "" {
if t, err := time.Parse(time.RFC3339Nano, s); err == nil {
w.ResetsAt = &t
}
}
shares = append(shares, w)
shares = append(shares, QuotaWindow{Name: k.name, Span: k.span, Used: max(0, min(100, ratio*100)), ResetsAt: resetOf(d)})
}
if len(shares) > 0 {
out = slices.DeleteFunc(out, func(w QuotaWindow) bool {
@@ -898,3 +923,15 @@ func zhipuKeyTeamAt(ctx context.Context, root, quotaURL, key string, team *Zhipu
_, ws, err := readZhipuPlan(b)
return "GLM Coding Team", ws, err
}
// camel spells a snake_case name in camelCase: limit_month_total is
// limitMonthTotal.
func camel(s string) string {
parts := strings.Split(s, "_")
for i := 1; i < len(parts); i++ {
if parts[i] != "" {
parts[i] = strings.ToUpper(parts[i][:1]) + parts[i][1:]
}
}
return strings.Join(parts, "")
}
+100 -1
View File
@@ -6,6 +6,7 @@ import (
"math"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
@@ -438,7 +439,7 @@ func TestReadKimiCode(t *testing.T) {
// body is a live reply of 2026-09-23 (narumiruna/pi-extensions#1390): no
// weekly usage, the 5h window told both ways. The second has every
// window kimi-code reads (managed-usage.ts); each is taken from usages,
// limit_month_code shown not at all.
// limit_month_code not shown beside limit_month_total.
func TestReadKimiCodeMonth(t *testing.T) {
_, ws, err := readKimiCode([]byte(`{
"limits": [
@@ -482,6 +483,104 @@ func TestReadKimiCodeMonth(t *testing.T) {
}
}
// The month however Kimi tells it (lidazi2016 on Discord, still no month
// on v0.1.2023 with a Kimi Code China key): the membership of 2026-09
// sends limit_5h and limit_month_code with no total (GCMP's
// kimiUsage.ts), a share may come in camelCase with its reset in epoch
// milliseconds (EchoBird's fixture), and a counted window may be a
// month or a week long.
func TestReadKimiCodeMonthEveryWay(t *testing.T) {
for _, c := range []struct{ name, body string }{
{"code share only", `{"usages":{"limit_5h":{"used_ratio":0.25,"reset_time":"2026-10-29T11:25:00Z"},
"limit_month_code":{"used_ratio":0.5,"reset_time":"2026-11-17T00:00:00Z"}}}`},
{"camelCase", `{"usages":{"limit5h":{"usedRatio":0.25,"resetTime":"2026-10-29T11:25:00Z"},
"limitMonthTotal":{"usedRatio":"0.5","resetTime":1794873600000}}}`},
{"counted", `{"limits":[{"window":{"duration":300,"timeUnit":"TIME_UNIT_MINUTE"},"detail":{"limit":"100","used":"25","resetTime":"2026-10-29T11:25:00Z"}},
{"window":{"duration":1,"timeUnit":"TIME_UNIT_MONTH"},"detail":{"limit":"100","remaining":"50","resetTime":1794873600}}]}`},
} {
_, ws, err := readKimiCode([]byte(c.body))
if err != nil || len(ws) != 2 || ws[0].Name != "5 hours" || ws[0].Used != 25 || ws[0].ResetsAt == nil ||
ws[1].Name != "Month" || ws[1].Used != 50 || ws[1].Span != 30*24*time.Hour ||
ws[1].ResetsAt == nil || ws[1].ResetsAt.UTC().Day() != 17 || ws[1].ResetsAt.UTC().Month() != time.November {
t.Errorf("%s: %+v %v", c.name, ws, err)
}
}
// a counted week is the week, beside the month the shares tell
_, ws, err := readKimiCode([]byte(`{"limits":[{"window":{"duration":1,"timeUnit":"TIME_UNIT_WEEK"},"detail":{"limit":10,"used":4}}],
"usages":{"limit_month_total":{"used_ratio":0.1},"limit_month_code":{"used_ratio":0.05}}}`))
if err != nil || len(ws) != 2 || ws[0].Name != "7 days" || ws[0].Used != 40 || ws[1].Name != "Month" || math.Abs(ws[1].Used-10) > 1e-9 {
t.Errorf("week and month: %+v %v", ws, err)
}
}
// Every way a Kimi Code key is added shows the month Kimi tells: the
// China and global presets, a provider of its own at the Anthropic base
// alone, and a key imported from OpenCode's auth.json. Each card is read
// from /usages on its own host with its own key.
func TestPlanQuotasKimiCodeMonthEveryRoute(t *testing.T) {
isolate(t)
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
t.Setenv("XDG_DATA_HOME", filepath.Join(h, ".local", "share"))
t.Setenv("PATH", h)
for _, v := range agentenv.Vars {
t.Setenv(v, "")
}
month := `{"limits":[{"window":{"duration":300,"timeUnit":"TIME_UNIT_MINUTE"},"detail":{"limit":"100","used":"11","resetTime":"2026-10-29T11:25:00Z"}}],
"usages":{"limit_5h":{"used_ratio":0.11,"reset_time":"2026-10-29T11:25:00Z"},"limit_month_code":{"used_ratio":0.3,"reset_time":"2026-11-17T00:00:00Z"}}}`
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Header.Get("X-Host") + r.URL.Path + " " + r.Header.Get("Authorization") {
case "api.kimi.com/coding/v1/usages Bearer sk-kimi-cn",
"api.kimi.ai/coding/v1/usages Bearer sk-kimi-global",
"api.kimi.com/coding/v1/usages Bearer sk-kimi-own",
"api.kimi.com/coding/v1/usages Bearer sk-kimi-oc":
w.Write([]byte(month))
default:
t.Errorf("asked %s%s with %q", r.Header.Get("X-Host"), r.URL.Path, r.Header.Get("Authorization"))
w.WriteHeader(http.StatusUnauthorized)
}
}))
defer srv.Close()
old := http.DefaultClient.Transport
http.DefaultClient.Transport = rewrite{srv}
t.Cleanup(func() { http.DefaultClient.Transport = old })
auth := filepath.Join(h, "auth.json")
if err := os.WriteFile(auth, []byte(`{"kimi-code-plan-cn":{"type":"api","key":"sk-kimi-oc"}}`), 0o600); err != nil {
t.Fatal(err)
}
items, err := readOpenCodeAuth(auth)
if err != nil || len(items) != 1 || items[0].Skip != "" {
t.Fatalf("OpenCode import: %+v %v", items, err)
}
oc := items[0].Provider
oc.ID = "kimi-oc"
for _, p := range []Provider{
FromPresetKey(t, "kimi-code-cn", "sk-kimi-cn"),
FromPresetKey(t, "kimi-code", "sk-kimi-global"),
{ID: "kimi-own", Name: "My Kimi", Anthropic: "https://api.kimi.com/coding/", Key: "sk-kimi-own"},
oc,
} {
if err := Save(p); err != nil {
t.Fatal(err)
}
}
got := map[string]SubscriptionQuota{}
for _, q := range PlanQuotas(context.Background()) {
got[q.Provider] = q
}
for _, id := range []string{"kimi-code-cn", "kimi-code", "kimi-own", "kimi-oc"} {
q := got[id]
if len(q.Windows) != 2 || q.Windows[0].Name != "5 hours" || q.Windows[1].Name != "Month" ||
math.Abs(q.Windows[1].Used-30) > 1e-9 || q.Windows[1].ResetsAt == nil {
t.Errorf("%s: %+v", id, q)
}
}
}
// An OpenCode Go key whose windows can't be read says why, with the way
// out (sakulalalalalal on X: three Go keys, each "Allowance unavailable"
// and nothing more). The bodies are OpenCode's own, as zen/go/v1/usage