usage: Kimi Code's plan windows (its /usages, the 5-hour and weekly allowances) show on the Usage page like the GLM Coding Plan's; the Used / Left toggle sits under an Allowances heading above the subscription cards, away from the period's list-price total it never changed, and a balance says why it is only what is left

This commit is contained in:
yetone
2026-09-27 11:45:47 +08:00
parent 6f792a3739
commit 097f399fc1
6 changed files with 144 additions and 5 deletions
+1
View File
@@ -654,6 +654,7 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
.gw .url code { color: var(--fg-2); font-size: 11px; }
.gw .url:hover code { color: var(--fg); }
#view-gateway .row-head, #view-usage .row-head { margin: 14px 0 6px; padding: 0 2px; }
#view-usage .row-head.quota-head { margin: 6px 0 6px; }
#view-gateway .row-head .note { font-size: 11px; color: var(--faint); }
/* the connect card: label column, then the value with a copy button */
+5 -1
View File
@@ -3614,7 +3614,10 @@ function renderQuotas() {
renderPanelQuota();
const subscriptions = $("#subscriptionUsage");
subscriptions.replaceChildren();
// used or left: only there when some card has a window to read
// the allowances' own heading, apart from the period's cost: used or
// left turns their meters, and is only there when some card has one (a
// balance is only ever what is left)
$("#quotaHead").hidden = !!quotas && !quotas.length;
const mode = $("#quotaMode");
mode.hidden = !quotas?.some((q) => !q.balance && !q.error && q.windows?.length);
if (!mode.hidden) {
@@ -3735,6 +3738,7 @@ function panelQuotaRow(q) {
function quotaWindows(sub) {
if (sub.balance) {
const b = el("div", "quota-balance");
b.title = t("What is left on the account: the vendor tells only this, so Used / Left leaves it as it is");
b.append(el("span", "", t("Balance")), el("b", "", sub.balance));
return b;
}
+3
View File
@@ -342,6 +342,8 @@ const I18N = {
"Balance field": "余额字段",
"Where the amount is in the reply, e.g. data.balance; it can be a sum with + - * / and brackets, e.g. data.total / 500000 or (1 - credits.used / 70) %; \"$\" in front adds the sign, \"%\" after it shows a percent; several, each with a label, go apart by \";\", e.g. 5h: a.used / a.cap %; $credits.left": "金额在返回 JSON 中的位置,例如 data.balance;可以用 + - * / 和括号算,例如 data.total / 500000 或 (1 - credits.used / 70) %;前面加 \"$\" 显示币种符号,后面加 \"%\" 显示为百分比;多个金额用 \";\" 隔开,各自可加标签,例如 5h: a.used / a.cap %; $credits.left",
"Balance": "余额",
"Allowances": "额度",
"What is left on the account: the vendor tells only this, so Used / Left leaves it as it is": "账户里剩下的金额:供应商只提供这个数,所以「已用 / 剩余」不会改变它",
"Headers": "请求头",
"Extra HTTP headers sent to the vendor, applied after auth. For gateways that need a private scheme.": "发送给供应商的额外 HTTP 请求头,在鉴权之后应用。适用于需要私有鉴权方案的网关。",
"Header-Name": "请求头名称",
@@ -501,6 +503,7 @@ const I18N = {
"At each model's list price on models.dev": "按 models.dev 上各模型的标价计算",
"no price for these models": "这些模型没有价格信息",
"5 hours": "5 小时",
"24 hours": "24 小时",
"MCP · Month": "MCP · 本月",
"this key has no OpenCode Go subscription": "这个 Key 没有订阅 OpenCode Go",
"7 days · Opus": "7 天 · Opus",
+5 -1
View File
@@ -85,9 +85,13 @@
<div class="usage-head">
<div class="segs" id="period"></div>
<span class="grow"></span>
<div class="segs" id="quotaMode" hidden></div>
<span class="usage-cost" id="usageCost"></span>
</div>
<div class="row-head quota-head" id="quotaHead" hidden>
<span class="label" data-t>Allowances</span>
<span class="grow"></span>
<div class="segs" id="quotaMode" hidden></div>
</div>
<section class="subscription-usage" id="subscriptionUsage"></section>
<section class="stats" id="stats"></section>
<section class="chart" id="chart"></section>
+111 -3
View File
@@ -1,7 +1,7 @@
package provider
// A plan bought with an API key — Zhipu's GLM Coding Plan (and Z.ai's), and
// OpenCode Go — has windows of allowance like a subscription's, which the
// A plan bought with an API key — Zhipu's GLM Coding Plan (and Z.ai's),
// Kimi Code and OpenCode Go — has windows of allowance like a subscription's, which the
// vendor tells to the key: the Usage page shows them beside the
// subscriptions'.
@@ -11,6 +11,7 @@ import (
"fmt"
"io"
"net/http"
"strconv"
"strings"
"sync"
"time"
@@ -35,6 +36,10 @@ func planQuotaSourceOf(p Provider) (planQuotaSource, bool) {
return planQuotaSource{"https://open.bigmodel.cn/api/monitor/usage/quota/limit", false, readZhipuPlan, coding}, true
case "api.z.ai":
return planQuotaSource{"https://api.z.ai/api/monitor/usage/quota/limit", false, readZhipuPlan, coding}, true
case "api.kimi.com", "api.kimi.ai":
if strings.Contains(base, "/coding") {
return planQuotaSource{strings.TrimSuffix(kimiCodeBase(base), "/") + "/usages", true, readKimiCode, true}, true
}
case "opencode.ai":
if u := strings.TrimSuffix(base, "/"); strings.HasSuffix(u, "/zen/go") || strings.Contains(u, "/zen/go/") {
return planQuotaSource{"https://opencode.ai/zen/go/v1/usage", true, readOpenCodeGo, true}, true
@@ -143,6 +148,109 @@ func readOpenCodeGo(b []byte) (string, []QuotaWindow, error) {
return "", out, nil
}
// kimiCodeBase is Kimi Code's OpenAI endpoint, /coding/v1, for either of
// the provider's (its Anthropic one is /coding).
func kimiCodeBase(base string) string {
u := strings.TrimSuffix(base, "/")
if strings.HasSuffix(u, "/coding") {
return u + "/v1"
}
return u
}
// readKimiCode reads Kimi Code's /usages, as kimi-cli's /usage does:
//
// {"usage":{"limit":"100","used":"12","resetTime":"2026-09-30T05:24:18.44Z"},
// "limits":[{"window":{"duration":300,"timeUnit":"TIME_UNIT_MINUTE"},
// "detail":{"limit":"100","remaining":"88","resetTime":"…"}}]}
//
// usage is the week's allowance, each of limits a shorter window; the
// numbers come as strings or numbers, used or what remains.
func readKimiCode(b []byte) (string, []QuotaWindow, error) {
type row map[string]any
var r struct {
Usage row `json:"usage"`
Limits []struct {
Window row `json:"window"`
Detail row `json:"detail"`
} `json:"limits"`
}
if err := json.Unmarshal(b, &r); err != nil {
return "", nil, err
}
num := func(v any) (float64, bool) {
switch x := v.(type) {
case float64:
return x, true
case string:
f, err := strconv.ParseFloat(strings.TrimSpace(x), 64)
return f, err == nil
}
return 0, false
}
window := func(d row, name string, span time.Duration) (QuotaWindow, bool) {
limit, ok := num(d["limit"])
if !ok || limit <= 0 {
return QuotaWindow{}, false
}
used, ok := num(d["used"])
if !ok {
left, ok := num(d["remaining"])
if !ok {
return QuotaWindow{}, false
}
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
}
}
}
return w, true
}
out := []QuotaWindow{}
for _, l := range r.Limits {
d := l.Detail
if d == nil {
d = l.Window
}
n, _ := num(l.Window["duration"])
unit, _ := l.Window["timeUnit"].(string)
var span time.Duration
switch {
case strings.Contains(unit, "MINUTE"):
span = time.Duration(n) * time.Minute
case strings.Contains(unit, "HOUR"):
span = time.Duration(n) * time.Hour
case strings.Contains(unit, "DAY"):
span = time.Duration(n) * 24 * time.Hour
}
name := "Allowance"
switch {
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:
name = fmt.Sprintf("%d hours", span/time.Hour)
case span > 0:
name = fmt.Sprintf("%d minutes", span/time.Minute)
}
if w, ok := window(d, name, span); ok {
out = append(out, w)
}
}
if w, ok := window(r.Usage, "7 days", 7*24*time.Hour); ok {
out = append(out, w)
}
if len(out) == 0 {
return "", nil, fmt.Errorf("no usage in the reply")
}
return "", out, nil
}
// 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) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, src.url, nil)
@@ -163,7 +271,7 @@ func planWindows(ctx context.Context, src planQuotaSource, key string) (plan str
defer res.Body.Close()
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
switch {
case res.StatusCode == http.StatusForbidden && src.bearer:
case res.StatusCode == http.StatusForbidden && strings.Contains(src.url, "opencode.ai"):
return "", nil, fmt.Errorf("this key has no OpenCode Go subscription")
case res.StatusCode >= 300:
return "", nil, fmt.Errorf("%s", res.Status)
+19
View File
@@ -22,6 +22,8 @@ func TestPlanQuotaSource(t *testing.T) {
{Provider{Chat: "https://opencode.ai/zen/go/v1", Anthropic: "https://opencode.ai/zen/go"}, "https://opencode.ai/zen/go/v1/usage", true, true},
{Provider{Anthropic: "https://opencode.ai/zen/go"}, "https://opencode.ai/zen/go/v1/usage", true, true},
{Provider{Chat: "https://opencode.ai/zen/v1"}, "", false, false}, // Zen is pay as you go
{Provider{Chat: "https://api.kimi.com/coding/v1", Anthropic: "https://api.kimi.com/coding"}, "https://api.kimi.com/coding/v1/usages", true, true},
{Provider{Anthropic: "https://api.kimi.ai/coding/"}, "https://api.kimi.ai/coding/v1/usages", true, true},
{Provider{Chat: "https://api.deepseek.com"}, "", false, false},
} {
src, ok := planQuotaSourceOf(c.p)
@@ -175,3 +177,20 @@ func TestPlanQuotas(t *testing.T) {
t.Errorf("go: %+v", q)
}
}
func TestReadKimiCode(t *testing.T) {
_, ws, err := readKimiCode([]byte(`{"usage":{"limit":"100","used":"12","resetTime":"2026-09-30T05:24:18.443553353Z"},
"limits":[{"window":{"duration":300,"timeUnit":"TIME_UNIT_MINUTE"},"detail":{"limit":"50","remaining":"40","resetTime":"2026-09-27T09:00:00Z"}},
{"window":{"duration":1,"timeUnit":"TIME_UNIT_DAY"},"detail":{"limit":200,"used":200}}]}`))
if err != nil {
t.Fatal(err)
}
if len(ws) != 3 || ws[0].Name != "5 hours" || ws[0].Used != 20 || ws[0].Span != 5*time.Hour || ws[0].ResetsAt == nil ||
ws[1].Name != "24 hours" || ws[1].Used != 100 || ws[1].ResetsAt != nil ||
ws[2].Name != "7 days" || ws[2].Used != 12 || ws[2].ResetsAt == nil || ws[2].ResetsAt.Day() != 30 {
t.Fatalf("%+v", ws)
}
if _, _, err := readKimiCode([]byte(`{"error":{"message":"bad key"}}`)); err == nil {
t.Fatal("nothing read")
}
}