kimi: a key's booster wallet is read, and a key spending it isn't rested to the month (#5721)

apple_test_src on X (#5721): a Kimi Code key at 98.85% of its month was
rested until the month renews, while Kimi still served it from its
booster wallet. magpie never read the wallet.

readKimiCode now reads booster_wallet (or boosterWallet). A BOOSTER wallet
with an amount over 0 adds an "Extra usage" row: amountLeft, in cents x 1e6,
in the currency of monthlyChargeLimit, else monthlyUsed, else USD. When
something is left, the plan windows are marked Credits. The gateway's full()
then doesn't count a key on its booster as full at the month's 98%. A 429
quota refusal rests it as any refusal does, not until the month renews.
A wallet that is empty, of another type or missing changes nothing.

Tests: TestReadKimiCodeBooster runs on the reporter's literal body
(testdata/kimi-booster-5721.json, where 0 is left: no Credits) and on the
same body with amountLeft injected (snake and camel case). A GIFT wallet
and amount 0 add nothing. TestKimiKeyOnItsBoosterIsNotRestedToTheMonth:
a key with booster left isn't full and its 429 rests it under 24h; a
spent key is still rested by its window.

Run on mote: gofmt -l clean; GOOS=linux and GOOS=windows go vet of
internal/provider and internal/gateway; go test ./internal/provider
./internal/gateway -count=1 -timeout 45m: both ok (154.9s, 951.7s).
Broken by hand: routing.go reverted turns the gateway test red ("a key
on its booster counts as full at the month's 98%"); dropping the Credits
marking turns the provider test red.
Not tried: a real Kimi key with booster balance left (the reporter's
body has 0 left).
This commit is contained in:
yetone
2026-11-09 05:06:48 +08:00
parent 1a37cc8516
commit aa3d11d5b7
6 changed files with 215 additions and 7 deletions
+45
View File
@@ -0,0 +1,45 @@
package gateway
import (
"net/http"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// A Kimi Code key whose month is at 98.85% goes on on its booster while
// the booster holds money (#5721): a quota refusal rests it the quota rest,
// not until the month renews 17 days on. With the booster used up, the
// month counts as full as before (the rest held to its longest).
func TestKimiKeyOnItsBoosterIsNotRestedToTheMonth(t *testing.T) {
forgetRouting()
now := time.Now()
month := now.Add(17 * 24 * time.Hour)
windows := func(credits bool) provider.Allowance {
return provider.Allowance{
{Name: "5 hours", Used: 0, Resets: now.Add(80 * time.Minute), Span: 5 * time.Hour, Credits: credits},
{Name: "Month", Used: 98.85, Resets: month, Span: 30 * 24 * time.Hour, Credits: credits},
}
}
keyWindows(t, map[string]provider.Allowance{"sk-left": windows(true), "sk-spent": windows(false)})
key := func(k string) candidate {
return candidate{p: provider.Provider{ID: "kimi-code", Key: k}, model: "kimi-for-coding", rest: "kimi-code#" + k}
}
s := &Server{}
refused := []byte(`{"error":{"message":"You've reached your usage limit","type":"rate_limit_error"}}`)
if !key("sk-left").full(now).IsZero() {
t.Fatal("a key on its booster counts as full at the month's 98%")
}
if r := s.restAfter(key("sk-left"), 429, http.Header{}, refused); r.By == "window" || !r.Until.Before(now.Add(24*time.Hour)) {
t.Fatalf("a key on its booster rests %v by %s (%s)", time.Until(r.Until), r.By, r.Why)
}
if !key("sk-spent").full(now).Equal(month) {
t.Fatal("a key with its booster used up isn't full at the month's 98%")
}
if r := s.restAfter(key("sk-spent"), 429, http.Header{}, refused); r.Why != failQuota || r.By != "window" || r.Until.Before(now.Add(7*24*time.Hour)) {
t.Fatalf("a key with its booster used up rests %v by %s (%s)", time.Until(r.Until), r.By, r.Why)
}
}
+4 -2
View File
@@ -1974,10 +1974,12 @@ func (s *Server) rateRest(c candidate, header http.Header, body []byte, sharedPo
// (usedShare), except In order: there an account at 98% is still tried in
// its turn, and one that fails then isn't benched until its week renews
// unless the vendor said it was out (#530). A Codex account that goes on
// on its credits is never: a window used up doesn't stop it (onCredits).
// on its credits is never: a window used up doesn't stop it (onCredits);
// nor is a key whose vendor goes on past its windows on a balance it
// holds (Kimi Code's booster, #5721).
func (c candidate) full(now time.Time) time.Time {
a, _ := c.allowance()
if spendsCredits(c.p, a) {
if spendsCredits(c.p, a) || c.p.Account == nil && a.OnCredits() {
return time.Time{}
}
return a.Full(c.model, provider.SpentShareOf(c.p.Routing), now)
+51 -4
View File
@@ -432,13 +432,16 @@ func KimiCodeSearch(p Provider) string {
// 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.
// weeks or months by its length. A booster wallet (加油包) is its
// balance, beside the windows (kimiBooster).
func readKimiCode(b []byte) (string, []QuotaWindow, error) {
type row map[string]any
var r struct {
Usage row `json:"usage"`
Usages map[string]row `json:"usages"`
Limits []struct {
Usage row `json:"usage"`
Usages map[string]row `json:"usages"`
Booster row `json:"booster_wallet"`
Camel row `json:"boosterWallet"`
Limits []struct {
Window row `json:"window"`
Detail row `json:"detail"`
} `json:"limits"`
@@ -577,9 +580,53 @@ func readKimiCode(b []byte) (string, []QuotaWindow, error) {
if len(out) == 0 {
return "", nil, fmt.Errorf("no usage in the reply")
}
wallet := r.Booster
if len(wallet) == 0 {
wallet = r.Camel
}
if left, unit, ok := kimiBooster(wallet, num); ok {
if left > 0 {
// Kimi goes on past the plan's windows on the booster (#5721):
// one used up doesn't stop the key while it holds money
for i := range out {
out[i].Credits = true
}
}
out = append(out, QuotaWindow{Name: "Extra usage", Balance: &left, Unit: unit, Aside: true})
}
return "", out, nil
}
// kimiBooster reads Kimi Code's booster wallet (加油包, "Extra usage"),
// as kimi-code's parseBoosterWallet does (packages/oauth/src/
// managed-usage.ts): a balance of type BOOSTER whose amount and
// amountLeft are cents times 10^6, amountLeft missing meaning none is
// left; the currency is the monthly limit's or used figure's, else USD.
// left is in the currency's units (yuan); ok is false when there is no
// booster.
func kimiBooster(wallet map[string]any, num func(any) (float64, bool)) (left float64, unit string, ok bool) {
bal, _ := wallet["balance"].(map[string]any)
if bal == nil || bal["type"] != "BOOSTER" {
return 0, "", false
}
if amount, ok := num(bal["amount"]); !ok || amount <= 0 {
return 0, "", false
}
if l, ok := num(bal["amountLeft"]); ok && l > 0 {
left = math.Round(l/1e6) / 100
}
unit = "USD"
for _, k := range []string{"monthlyChargeLimit", "monthlyUsed"} {
if m, _ := wallet[k].(map[string]any); m != nil {
if c, _ := m["currency"].(string); c != "" {
unit = c
break
}
}
}
return left, unit, true
}
// planWindows asks the vendor for the plan key is on and its windows.
func planWindows(ctx context.Context, src planQuotaSource, key string) (plan string, ws []QuotaWindow, err error) {
b, err := planBody(ctx, src, key)
+41
View File
@@ -641,3 +641,44 @@ func TestOpenCodeGoSaysWhyNoWindows(t *testing.T) {
t.Errorf("an unread reply's values are kept out of the error: %q", got)
}
}
// Kimi Code's booster wallet (加油包) is read beside the plan's windows
// (#5721, the reporter's reply of 2026-11-08): its balance shows as Extra
// usage, set aside from routing. With money left, Kimi goes on past the
// plan's windows on it, so each of them is on credits; used up (no
// amountLeft, which kimi-code reads as 0), they are not.
func TestReadKimiCodeBooster(t *testing.T) {
body, err := os.ReadFile("testdata/kimi-booster-5721.json")
if err != nil {
t.Fatal(err)
}
_, ws, err := readKimiCode(body)
if err != nil {
t.Fatal(err)
}
if len(ws) != 3 || ws[0].Name != "5 hours" || ws[0].Used != 0 || ws[0].Credits ||
ws[1].Name != "Month" || math.Abs(ws[1].Used-98.85) > 1e-9 || ws[1].Credits ||
ws[2].Name != "Extra usage" || ws[2].Balance == nil || *ws[2].Balance != 0 || ws[2].Unit != "CNY" || !ws[2].Aside {
t.Fatalf("%+v", ws)
}
left := strings.Replace(string(body), `"amount": "17500000000",`, `"amount": "17500000000", "amountLeft": "5000000000",`, 1)
camel := strings.Replace(left, `"booster_wallet"`, `"boosterWallet"`, 1)
for name, b := range map[string]string{"snake_case": left, "camelCase": camel} {
_, ws, err = readKimiCode([]byte(b))
if err != nil || len(ws) != 3 || !ws[0].Credits || !ws[1].Credits ||
ws[2].Balance == nil || *ws[2].Balance != 50 || ws[2].Unit != "CNY" || ws[2].Credits {
t.Fatalf("%s: %+v %v", name, ws, err)
}
}
// a wallet that isn't a booster, or holds nothing, is no row
for _, b := range []string{
strings.Replace(left, `"type": "BOOSTER"`, `"type": "GIFT"`, 1),
strings.Replace(left, `"amount": "17500000000"`, `"amount": "0"`, 1),
} {
if _, ws, err = readKimiCode([]byte(b)); err != nil || len(ws) != 2 || ws[0].Credits || ws[1].Credits {
t.Fatalf("%+v %v", ws, err)
}
}
}
+3 -1
View File
@@ -83,7 +83,9 @@ type QuotaWindow struct {
// Credits is set on each window of a ChatGPT account that holds
// credits (has_credits with a balance left, or unlimited): using the
// window up doesn't stop it, the vendor spends the credits instead
// (codexGoesOnCredits). Routing reads it (Allowance.OnCredits); kept
// (codexGoesOnCredits); and on each of a Kimi Code key's while its
// booster holds money (kimiBooster). Routing reads it
// (Allowance.OnCredits); kept
// with the reading, so one shown from before still says it.
Credits bool `json:"credits,omitempty"`
// Capped is set, for the GUI only (WithCapped), on a window an
+71
View File
@@ -0,0 +1,71 @@
{
"limits": [
{
"window": {
"duration": 300,
"timeUnit": "TIME_UNIT_MINUTE"
},
"detail": {
"limit": "100",
"remaining": "100",
"resetTime": "2026-11-08T21:37:24.113549Z"
}
}
],
"booster_wallet": {
"id": "<redacted-wallet-id>",
"userId": "<redacted-user-id>",
"balance": {
"id": "<redacted-balance-id>",
"feature": "FEATURE_OMNI",
"type": "BOOSTER",
"amount": "17500000000",
"unit": "UNIT_CURRENCY",
"periodStart": "2026-10-25T08:55:29.957265Z",
"periodEnd": "2126-10-25T08:55:30.957265Z",
"subscriptionId": "00000000-0000-0000-0000-000000000000",
"userId": "<redacted-user-id>",
"createTime": "2026-10-25T08:55:30.957265Z",
"updateTime": "2026-11-07T10:33:45.909322Z",
"domain": "DOMAIN_NEXUS"
},
"status": "STATUS_ACTIVE",
"allowTopup": true,
"topupLimit": {
"currency": "CNY",
"priceInCents": "300000"
},
"autoRefillCharge": {
"currency": "CNY",
"priceInCents": "0"
},
"autoRefillThreshold": {
"currency": "CNY",
"priceInCents": "0"
},
"monthlyChargeLimit": {
"currency": "CNY",
"priceInCents": "10000"
},
"monthlyUsed": {
"currency": "CNY",
"priceInCents": "17500"
},
"createdAt": "2026-10-25T08:55:30.957265Z",
"updatedAt": "2026-10-25T08:55:35.799020Z"
},
"usages": {
"limit_5h": {
"used_ratio": 0,
"reset_time": "2026-11-08T21:37:23Z"
},
"limit_month_total": {
"used_ratio": 0.9885,
"reset_time": "2026-11-25T00:00:00Z"
},
"limit_month_code": {
"used_ratio": 0.9873,
"reset_time": "2026-11-25T00:00:00Z"
}
}
}