mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 16:07:33 +00:00
fix(kimi): parse new monthly quota plan and clear absent window snapshots
Kimi For Coding now ships two response shapes: - Legacy plans: limits[].detail (5h counts) + top-level usage (weekly pool). - New plans (Go/Plus/Pro): usages.limit_5h / limit_7d / limit_month_total / limit_month_code reported as used_ratio (0-1) with reset_time. There is no top-level usage block, so the monthly pool was never parsed and the monthly quota was invisible in the account list. parseKimiUsageTiers now understands usages.* (used_ratio x100, monthly takes the larger of total/code with the earlier reset), keeps the legacy usage block as a fallback, and prefers usages.limit_7d over legacy weekly counts so weekly is not emitted twice. Snapshot writes also stopped clearing windows that disappear from the response: extra updates are JSONB merges, so not writing a window keeps its previous value forever. After a plan change the old weekly percentage froze (observed 13 days) and the account page kept showing an expired 7D window. Callers now write explicit nils for absent 5h/weekly/monthly windows. cnQuotaHasMonthlyWindow includes Kimi so threshold pre-pause and the 429 cooldown snapshot consider the monthly window too.
This commit is contained in:
1 parent
530c5e3a4f
commit
c54ebd4f12
3 files changed
+199
-6
No files matched your search
@@ -375,9 +375,15 @@ func cnProviderThresholdCandidates(account *Account, provider string) []*account
|
||||
return candidates
|
||||
}
|
||||
|
||||
// cnQuotaHasMonthlyWindow 报告供应商的额度快照是否含月度窗口(OpenCode Go、Command Code)。
|
||||
// cnQuotaHasMonthlyWindow 报告供应商的额度快照是否含月度窗口(OpenCode Go、
|
||||
// Command Code 与 Kimi 新套餐)。
|
||||
func cnQuotaHasMonthlyWindow(provider string) bool {
|
||||
return provider == PlatformOpenCodeGo || provider == PlatformCommandCode
|
||||
switch provider {
|
||||
case PlatformOpenCodeGo, PlatformCommandCode, PlatformKimi:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func cnThresholdCandidate(extra map[string]any, provider, window string) *accountSchedulingThresholdCandidate {
|
||||
|
||||
@@ -272,6 +272,11 @@ func (s *CNProviderQuotaService) queryUsageForAccount(ctx context.Context, accou
|
||||
result.CredentialValid = true
|
||||
|
||||
updates := cnQuotaExtraUpdates(provider, tiers, now)
|
||||
// 只对 5h/weekly/monthly 三档通吃的供应商清理缺席窗口;Command Code 与
|
||||
// Cline 走各自的取舍(抓取失败时保留月度),不在这里处理。
|
||||
if provider == PlatformKimi || provider == PlatformZhipu || provider == PlatformMiniMax || provider == PlatformOpenCodeGo {
|
||||
clearAbsentCNQuotaWindows(provider, tiers, updates)
|
||||
}
|
||||
if err := s.accountRepo.UpdateExtra(ctx, account.ID, updates); err != nil {
|
||||
slog.Warn("cn_quota_persist_failed", "account_id", account.ID, "provider", provider, "error", err)
|
||||
} else {
|
||||
@@ -379,13 +384,22 @@ func zhipuQuotaHost(baseURL string) string {
|
||||
|
||||
// parseKimiUsageTiers 解析 Kimi For Coding 的 /usages 响应。
|
||||
//
|
||||
// - limits[].detail.{limit,remaining,resetTime} → 5h 窗口(取首个 detail)
|
||||
// - usage.{limit,remaining,resetTime} → 周窗口
|
||||
// Kimi 目前并存两种套餐形态:
|
||||
//
|
||||
// utilization = (limit-remaining)/limit*100。
|
||||
// - 老套餐(5h + 7d):limits[].detail.{limit,remaining,resetTime} → 5h
|
||||
// (取首个 detail),顶层 usage.{limit,remaining,resetTime} → 周窗口,
|
||||
// utilization = (limit-remaining)/limit*100。
|
||||
// - 新套餐(5h + 月度):不再有顶层 usage,改由 usages.limit_5h /
|
||||
// usages.limit_7d / usages.limit_month_total / usages.limit_month_code
|
||||
// 以 used_ratio(0-1)+ reset_time 上报。月度 total 与 code 任一耗尽都会
|
||||
// 限流,因此 monthly 取两者较大用量、较早重置时间。
|
||||
//
|
||||
// 两者同时出现时 used_ratio 优先(比 counts 更贴近官方口径),顶层 usage 仅兜底;
|
||||
// usages.limit_5h 只在 limits[] 没有 detail 时补位,避免重复产出 5h 档。
|
||||
func parseKimiUsageTiers(body []byte) []CNQuotaTier {
|
||||
var tiers []CNQuotaTier
|
||||
|
||||
hasFiveHour := false
|
||||
if limits := gjson.GetBytes(body, "limits"); limits.IsArray() {
|
||||
limits.ForEach(func(_, item gjson.Result) bool {
|
||||
detail := item.Get("detail")
|
||||
@@ -407,11 +421,21 @@ func parseKimiUsageTiers(body []byte) []CNQuotaTier {
|
||||
UsedPercent: util,
|
||||
ResetAt: cnNormalizeResetTime(detail.Get("resetTime").Value()),
|
||||
})
|
||||
hasFiveHour = true
|
||||
return false // 取首个 detail 作为 5h 窗口
|
||||
})
|
||||
}
|
||||
if !hasFiveHour {
|
||||
if tier, ok := kimiUsedRatioTier(body, "limit_5h", "5h"); ok {
|
||||
tiers = append(tiers, tier)
|
||||
hasFiveHour = true
|
||||
}
|
||||
}
|
||||
|
||||
if usage := gjson.GetBytes(body, "usage"); usage.Exists() {
|
||||
// 周窗口:usages.limit_7d 优先,顶层 usage(老套餐单数)兜底。
|
||||
if tier, ok := kimiUsedRatioTier(body, "limit_7d", "weekly"); ok {
|
||||
tiers = append(tiers, tier)
|
||||
} else if usage := gjson.GetBytes(body, "usage"); usage.Exists() {
|
||||
limit, _ := cnParseF64(usage.Get("limit").Value())
|
||||
remaining, _ := cnParseF64(usage.Get("remaining").Value())
|
||||
used := limit - remaining
|
||||
@@ -429,9 +453,53 @@ func parseKimiUsageTiers(body []byte) []CNQuotaTier {
|
||||
})
|
||||
}
|
||||
|
||||
// 月度限额(新套餐):total 与 code 任一耗尽都会限流 → 取较大用量;
|
||||
// 重置时间取较早者(先恢复可用额度,避免过度停调)。
|
||||
total, hasTotal := kimiUsedRatioTier(body, "limit_month_total", "monthly")
|
||||
code, hasCode := kimiUsedRatioTier(body, "limit_month_code", "monthly")
|
||||
if hasTotal || hasCode {
|
||||
monthly := CNQuotaTier{Window: "monthly"}
|
||||
if hasTotal {
|
||||
monthly = total
|
||||
}
|
||||
if hasCode && (!hasTotal || code.UsedPercent > monthly.UsedPercent) {
|
||||
monthly.UsedPercent = code.UsedPercent
|
||||
}
|
||||
if hasTotal && hasCode && code.ResetAt != "" &&
|
||||
(monthly.ResetAt == "" || code.ResetAt < monthly.ResetAt) {
|
||||
monthly.ResetAt = code.ResetAt
|
||||
}
|
||||
tiers = append(tiers, monthly)
|
||||
}
|
||||
|
||||
return tiers
|
||||
}
|
||||
|
||||
// kimiUsedRatioTier 解析 usages.<key>.{used_ratio,reset_time} 为窗口档位。
|
||||
// used_ratio 是 0-1 比例,输出换算为百分比;键缺失或不可解析返回 false。
|
||||
func kimiUsedRatioTier(body []byte, key, window string) (CNQuotaTier, bool) {
|
||||
node := gjson.GetBytes(body, "usages."+key)
|
||||
if !node.Exists() {
|
||||
return CNQuotaTier{}, false
|
||||
}
|
||||
ratioNode := node.Get("used_ratio")
|
||||
if !ratioNode.Exists() {
|
||||
return CNQuotaTier{}, false
|
||||
}
|
||||
ratio, ok := cnParseF64(ratioNode.Value())
|
||||
if !ok {
|
||||
return CNQuotaTier{}, false
|
||||
}
|
||||
if ratio < 0 {
|
||||
ratio = 0
|
||||
}
|
||||
return CNQuotaTier{
|
||||
Window: window,
|
||||
UsedPercent: ratio * 100,
|
||||
ResetAt: cnNormalizeResetTime(node.Get("reset_time").Value()),
|
||||
}, true
|
||||
}
|
||||
|
||||
// parseMiniMaxUsageTiers 解析 MiniMax Token Plan / Coding Plan remains 响应。
|
||||
//
|
||||
// 只取 model_name == "general"(编程套餐),跳过 video。字段是剩余百分比,
|
||||
@@ -671,6 +739,35 @@ func cnQuotaExtraUpdates(provider string, tiers []CNQuotaTier, now time.Time) ma
|
||||
return updates
|
||||
}
|
||||
|
||||
// clearAbsentCNQuotaWindows 把本次探测缺席的窗口显式写 nil(JSONB 合并语义下等于
|
||||
// 移除按键):账号 extra 的更新走 `extra || $1`,只"不写"会保留旧值。上游改套餐
|
||||
// (Kimi 老套餐 7d → 新套餐月度)后旧窗口不再上报,不清理就会把切换前的用量永久
|
||||
// 冻结在快照里(生产实测冻结 13 天,列表一直显示过期的 7D 用量)。
|
||||
//
|
||||
// 仅供 5h/weekly/monthly 三档通吃的供应商调用;Command Code / Cline 有自己的
|
||||
// 取舍(周期端点抓取失败时保留月度值),不在此列。
|
||||
func clearAbsentCNQuotaWindows(provider string, tiers []CNQuotaTier, updates map[string]any) {
|
||||
present := make(map[string]CNQuotaTier, len(tiers))
|
||||
for _, tier := range tiers {
|
||||
present[tier.Window] = tier
|
||||
}
|
||||
for _, window := range []struct{ name, used, reset string }{
|
||||
{"5h", cnExtraSuffix5hUsed, cnExtraSuffix5hReset},
|
||||
{"weekly", cnExtraSuffixWeeklyUsed, cnExtraSuffixWeeklyReset},
|
||||
{"monthly", cnExtraSuffixMonthlyUsed, cnExtraSuffixMonthlyReset},
|
||||
} {
|
||||
tier, ok := present[window.name]
|
||||
if !ok {
|
||||
updates[cnExtraKey(provider, window.used)] = nil
|
||||
updates[cnExtraKey(provider, window.reset)] = nil
|
||||
continue
|
||||
}
|
||||
if tier.ResetAt == "" {
|
||||
updates[cnExtraKey(provider, window.reset)] = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// parseOpenCodeGoUsageTiers 解析 OpenCode Go GET /usage 响应。
|
||||
//
|
||||
// 结构对齐 cc-switch extractor:
|
||||
|
||||
@@ -107,6 +107,72 @@ func TestParseKimiUsageTiers_LimitZero(t *testing.T) {
|
||||
require.InDelta(t, 0.0, tiers[0].UsedPercent, 1e-9)
|
||||
}
|
||||
|
||||
// TestParseKimiUsageTiers_MonthlyPlan 新套餐形态(5h + 月度限额):不再有顶层
|
||||
// usage,改由 usages.limit_5h / limit_month_total / limit_month_code 以
|
||||
// used_ratio(0-1)+ reset_time 上报。monthly 取两条月度键的较大用量 + 较早重置。
|
||||
func TestParseKimiUsageTiers_MonthlyPlan(t *testing.T) {
|
||||
t.Parallel()
|
||||
body := []byte(`{
|
||||
"limits": [{
|
||||
"window": {"duration": 300, "timeUnit": "TIME_UNIT_MINUTE"},
|
||||
"detail": {"limit": "100", "used": "10", "remaining": "90", "resetTime": "2026-11-13T16:10:29.523075Z"}
|
||||
}],
|
||||
"usages": {
|
||||
"limit_5h": {"used_ratio": 0.0982, "reset_time": "2026-11-13T16:10:28Z"},
|
||||
"limit_month_total": {"used_ratio": 0.6564, "reset_time": "2026-11-26T00:00:00Z"},
|
||||
"limit_month_code": {"used_ratio": 0.6252, "reset_time": "2026-11-26T00:00:00Z"}
|
||||
}
|
||||
}`)
|
||||
tiers := parseKimiUsageTiers(body)
|
||||
require.Len(t, tiers, 2, "新套餐应为 5h + monthly,且不得产出已废弃的 weekly")
|
||||
|
||||
require.Equal(t, "5h", tiers[0].Window)
|
||||
require.InDelta(t, 10.0, tiers[0].UsedPercent, 1e-9, "5h 用 limits[].detail 的绝对计数")
|
||||
require.Equal(t, "2026-11-13T16:10:29Z", tiers[0].ResetAt)
|
||||
|
||||
require.Equal(t, "monthly", tiers[1].Window)
|
||||
require.InDelta(t, 65.64, tiers[1].UsedPercent, 1e-9, "used_ratio 0-1 换算为百分比")
|
||||
require.Equal(t, "2026-11-26T00:00:00Z", tiers[1].ResetAt)
|
||||
}
|
||||
|
||||
// TestParseKimiUsageTiers_MonthlyPicksMaxUsage total/code 任一耗尽都会限流:
|
||||
// monthly 取较大用量;重置时间取较早者(先恢复额度,避免过度停调)。
|
||||
func TestParseKimiUsageTiers_MonthlyPicksMaxUsage(t *testing.T) {
|
||||
t.Parallel()
|
||||
body := []byte(`{"usages":{
|
||||
"limit_month_total":{"used_ratio":0.4,"reset_time":"2026-11-26T00:00:00Z"},
|
||||
"limit_month_code":{"used_ratio":0.9,"reset_time":"2026-11-20T00:00:00Z"}}}`)
|
||||
tiers := parseKimiUsageTiers(body)
|
||||
require.Len(t, tiers, 1)
|
||||
require.Equal(t, "monthly", tiers[0].Window)
|
||||
require.InDelta(t, 90.0, tiers[0].UsedPercent, 1e-9)
|
||||
require.Equal(t, "2026-11-20T00:00:00Z", tiers[0].ResetAt)
|
||||
|
||||
onlyCode := parseKimiUsageTiers([]byte(`{"usages":{"limit_month_code":{"used_ratio":0.5,"reset_time":"2026-11-20T00:00:00Z"}}}`))
|
||||
require.Len(t, onlyCode, 1)
|
||||
require.Equal(t, "monthly", onlyCode[0].Window)
|
||||
require.InDelta(t, 50.0, onlyCode[0].UsedPercent, 1e-9)
|
||||
}
|
||||
|
||||
// TestParseKimiUsageTiers_LegacyWithUsedRatio 老套餐(顶层 usage)同时携带
|
||||
// usages.limit_7d 时,weekly 以 used_ratio 为准、不重复产出 weekly 档。
|
||||
func TestParseKimiUsageTiers_LegacyWithUsedRatio(t *testing.T) {
|
||||
t.Parallel()
|
||||
body := []byte(`{
|
||||
"usage": {"limit": "100", "remaining": "80", "resetTime": "2026-10-07T05:04:39.713183Z"},
|
||||
"usages": {
|
||||
"limit_5h": {"used_ratio": 0, "reset_time": "2026-10-04T11:04:38Z"},
|
||||
"limit_7d": {"used_ratio": 0.203912, "reset_time": "2026-10-07T05:04:38Z"}
|
||||
}
|
||||
}`)
|
||||
tiers := parseKimiUsageTiers(body)
|
||||
require.Len(t, tiers, 2)
|
||||
require.Equal(t, "5h", tiers[0].Window)
|
||||
require.Equal(t, "weekly", tiers[1].Window)
|
||||
require.InDelta(t, 20.3912, tiers[1].UsedPercent, 1e-9)
|
||||
require.Equal(t, "2026-10-07T05:04:38Z", tiers[1].ResetAt)
|
||||
}
|
||||
|
||||
// TestParseZhipuTokenTiers_UnitClassification 显式 unit(3=5h / 6=weekly)优先分类,
|
||||
// 不能被 reset 时间排序覆盖(周期末尾周窗口会更早重置)。
|
||||
func TestParseZhipuTokenTiers_UnitClassification(t *testing.T) {
|
||||
@@ -231,6 +297,30 @@ func TestCNQuotaExtraUpdates(t *testing.T) {
|
||||
require.Equal(t, now.Format(time.RFC3339), updates["kimi_usage_updated_at"])
|
||||
}
|
||||
|
||||
// 缺席窗口必须显式写 nil:extra 走 JSONB 合并(`extra || $1`),只"不写"会保留
|
||||
// 旧值。Kimi 老套餐 → 新套餐(月度)切换后 weekly 不再上报,不清理就会把切换前
|
||||
// 的用量永久冻结在快照里(生产实测冻结 13 天)。
|
||||
func TestCNQuotaExtraUpdatesClearsAbsentWindows(t *testing.T) {
|
||||
t.Parallel()
|
||||
now := time.Date(2026, 11, 13, 0, 0, 0, 0, time.UTC)
|
||||
tiers := []CNQuotaTier{
|
||||
{Window: "5h", UsedPercent: 10, ResetAt: "2026-11-13T16:10:29Z"},
|
||||
{Window: "monthly", UsedPercent: 65.64, ResetAt: "2026-11-26T00:00:00Z"},
|
||||
}
|
||||
updates := cnQuotaExtraUpdates(PlatformKimi, tiers, now)
|
||||
clearAbsentCNQuotaWindows(PlatformKimi, tiers, updates)
|
||||
|
||||
value, present := updates["kimi_weekly_used_percent"]
|
||||
require.True(t, present, "缺席的 weekly 必须显式出现在更新里")
|
||||
require.Nil(t, value)
|
||||
_, resetPresent := updates["kimi_weekly_reset_at"]
|
||||
require.True(t, resetPresent)
|
||||
|
||||
require.Equal(t, 10.0, updates["kimi_5h_used_percent"])
|
||||
require.Equal(t, 65.64, updates["kimi_monthly_used_percent"])
|
||||
require.Equal(t, "2026-11-26T00:00:00Z", updates["kimi_monthly_reset_at"])
|
||||
}
|
||||
|
||||
func TestParseOpenCodeGoUsageTiers(t *testing.T) {
|
||||
t.Parallel()
|
||||
body := []byte(`{
|
||||
|
||||
Reference in new issue
Block a user