Files
magpie/quota_cli.go
T
yetone 8117d6f4a9 zcode: a seat on a team's GLM Coding Plan (团队套餐) is signed in, routed and metered as ZCode does it, on BigModel (智谱) as well as Z.ai, and a Zhipu key on a team plan shows its 5-hour and weekly windows and resets (#236 EZN7L2C3: a BigModel team GLM Coding Plan, the sign-in refused it and the usage was never read) — magpie's ZCode sign-in only went to Z.ai and only looked for the account's own coding-plan key, so a member of a team's plan, whose seat lives in a team project, was refused, and a key on a team plan read nothing from /api/monitor/usage/quota/limit. Read from ZCode.app 3.14.3 (host/index.js and config/provider/zcode-builtin.json): the team rules account:{zai|bigmodel}-team-coding-plan use the individual plans' base URLs with no extra inference headers; getCustomerInfo lists the projects, projectType "2" being a team's (isBigModelTeamCodingPlanProject); fetchTeamCodingPlanEntitlement asks /api/biz/team/subscribe/product/querySubscribeDetail (EFFECTIVE + memberGrantStatus VALID usable, UNASSIGNED no seat, EXPIRED run out); ensureBigModelTeamPlanProjectApiKeyWithStatus / copyBigModelTeamPlanProjectApiKeySecret find or create "zcode-team-api-key" (keyType 2) in the team project and copy its secret; createBigModelBizHeaders sends the access token bare in Authorization with bigmodel-organization / bigmodel-project; resolveAccountTeamPlanRuntimeApiKey takes the stored oauth:{family}:access_token (skipping BigModel's when it equals zcodejwttoken); buildQuotaLimitUrl adds type=2 and createBigModelUsageHeaders sends the key with the org/project headers; ZCode keeps the chosen team in ~/.zcode/v2/setting.json providerFamilyConnectionSelections (legacy modelProviderFamilySelectedKeys "team-plan:builtin:…", migrateLegacyAccountConnectionSettings); pollPendingOAuth/startOAuthWithPolling init with {provider:"zai"|"bigmodel"}, BigModel's redirect param being redirect, its token the poll's bigmodel.access_token. Now: the sign-in first asks where the account is — Z.ai or BigModel (智谱) (POST /api/signin takes a site, StartSignInAt, "zcode:bigmodel" too) — and on its site tries the account's own plan, then a team project with a usable seat (a new zcode_team.go: zcodeTeamSignIn keeps the team key, org, project and the biz token, the plan named by its product, "GLM Coding Team" otherwise), then the Start Plan; a team seat not yet granted or a team plan expired is refused saying so ("…has no seat on it yet — ask the team's admin…"), and an account with none of them names both plans and the site's subscribe page. ZCode's own team login is read from its credentials and setting.json (zcodeOwnTeam), its key minted lazily and kept (zcodeTeamKeyOf, retried after a minute, "sign in to ZCode again" when refused). Team requests go to the family's Anthropic base signed with the team key, no ZCode headers, never the Start Plan. Team usage asks bigmodel.cn (or api.z.ai) /api/monitor/usage/quota/limit?type=2 with the key and Authorization, Bigmodel-Organization, Bigmodel-Project, Set-Language, Accept-Language: CREDIT_LIMIT windows, unit 3 "5 hours" and unit 6 weekly, "current / total" when there is no remaining; /api/biz/customer-package-reset/list?targetType=TEAM gives the resets, fiveHourResets and weekResets counted where available is true, the soonest expireTime as until; the plan's end from querySubscribeDetail, Renew off. ResetCredits gains byWindow/fiveHour/weekly and Words(), "2 five-hour resets · 1 weekly reset" in the CLI, TUI and GUI (en and zh), with no "Use a reset" button for them since they are spent on the vendor's page. The Zhipu GLM key provider (planquota.go) falls back to the team query when the personal one fails or has no windows, adding the team headers when a ZCode team login holds that key. Personal accounts, Coding Plan and Start Plan, are routed, signed and metered as before. Tested with a new internal/provider/zcode_team_test.go against a fake bigmodel.cn/Z.ai in a sandbox HOME, no real tokens: a BigModel team sign-in through StartSignIn("zcode:bigmodel") is added (redirect param, plan "GLM Coding Team Pro", key made with keyType 2, org/project kept), its requests at the BigModel base signed with the team key and no ZCode headers, usage 5 hours 42% "420 / 1000" with a 5h span and weekly 10%, the quota headers sent, resets 2 five-hour and 1 weekly until 2026-10-05, plan until 2026-12-31; an unassigned seat is refused with no key made; ZCode's own team login from credentials + setting.json is found and metered while an individual plan stays as it was; the key provider's team fallback. TestPlanQuotas gains the type=2 case; the zcode Start Plan and account tests pass. A new internal/gui/tests/zcode-site.test.cjs, Chromium and WebKit, en and zh: starting ZCode's sign-in asks the site and posts nothing, BigModel posts {agent:"zcode",site:"bigmodel"} and keeps it, and the by-window resets read in both languages; signin-callback, click-scroll and login-import pass. go vet ./internal/..., go build -tags nogui (and GOOS=linux, GOOS=windows) and go test -tags nogui ./... pass (TestUserPath timed out under load and passes alone). Not tried against a real account: BigModel's OAuth sign-in and poll shape, the Set-Language values, customer-package-reset's field formats, querySubscribeDetail on Z.ai, type=2 for a pasted key with no org/project, and the time formats are from ZCode's code, not seen on the wire; not tried in the real Wails window.
2026-09-30 04:15:06 +08:00

205 lines
6.0 KiB
Go

package main
import (
"cmp"
"context"
"encoding/json"
"fmt"
"slices"
"strings"
"time"
"github.com/yetone/magpie/internal/provider"
)
const quotaUsage = `usage: magpie quota [<provider>…] [--json]
magpie quota reset [<codex account>] [--yes]
what is left of every subscription, plan and key magpie has: each window's use and
when it starts again, and each key's balance, asked of the vendors now (or less than
a minute ago). --json is for scripts and agents; the gateway answers the same at
GET http://127.0.0.1:3425/v1/magpie/quotas
A Codex account that holds rate-limit resets says how many; quota reset spends one,
starting the account's current windows again (the one Codex is signed in to unless
named). It can't be undone, so it asks first; --yes doesn't.`
// quotaCmd: magpie quota [<provider>…] [--json]
func quotaCmd(args []string) error {
if len(args) > 1 && args[1] == "reset" {
return quotaResetCmd(args[2:])
}
asJSON := false
var only []string
for _, a := range args[1:] {
switch a {
case "--json", "-j":
asJSON = true
case "help", "-h", "--help":
fmt.Println(quotaUsage)
return nil
default:
only = append(only, strings.ToLower(a))
}
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
qs := []provider.Quota{}
for _, q := range provider.QuotaReport(ctx, time.Now()) {
if len(only) == 0 || quotaMatches(q, only) {
qs = append(qs, q)
}
}
qs, err := withUntold(qs, only)
if err != nil {
return err
}
if asJSON {
b, _ := json.MarshalIndent(qs, "", " ")
fmt.Println(string(b))
return nil
}
if len(qs) == 0 {
if len(only) > 0 {
return fmt.Errorf("no subscription, plan or key balance of %s", strings.Join(only, ", "))
}
fmt.Println(muted.Render("nothing to tell ·"), "a signed-in subscription, a coding plan or a key whose vendor tells its balance shows up here")
return nil
}
width := 0
for _, q := range qs {
width = max(width, len([]rune(quotaTitle(q))))
}
for _, q := range qs {
line := fmt.Sprintf("%-*s %s", width, quotaTitle(q), muted.Render(fmt.Sprintf("%-12s", q.Kind)))
for _, w := range q.Windows {
line += " " + quotaCell(w)
}
if q.Balance != "" {
line += " " + bold.Render(q.Balance) + muted.Render(" left")
}
if q.Resets != nil {
line += " " + resetsCell(q.Resets)
}
if q.Error != "" {
line += " " + muted.Render(q.Error)
}
fmt.Println(line)
}
fmt.Println(faint.Render(" % is how much of a window is used · ↻ when it starts again · --json for scripts, or GET /v1/magpie/quotas on the gateway"))
return nil
}
// resetsCell is a Codex account's rate-limit resets in a line: "↺ 2
// resets until Oct 3 14:30", no date when they don't run out.
func resetsCell(r *provider.ResetCredits) string {
cell := "↺ " + r.Words()
if r.Until != nil {
cell += muted.Render(" until " + provider.ResetClock(*r.Until, time.Now()))
}
return cell
}
// quotaResetCmd: magpie quota reset [<codex account>] [--yes] — spends one
// of the account's rate-limit resets, once the user has said so.
func quotaResetCmd(args []string) error {
yes, user := false, ""
for _, a := range args {
switch a {
case "--yes", "-y":
yes = true
case "help", "-h", "--help":
fmt.Println(quotaUsage)
return nil
default:
if user != "" {
return fmt.Errorf("one account at a time: %s or %s", user, a)
}
user = a
}
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
// what the account holds, and whose it is when none was named
var held *provider.SubscriptionQuota
for _, q := range provider.SubscriptionUsage(ctx) {
if q.Provider == "codex" && (user == "" || strings.EqualFold(q.User, user)) {
held = &q
break
}
}
if held == nil {
if user != "" {
return fmt.Errorf("no Codex account %s", user)
}
return fmt.Errorf("Codex isn't signed in")
}
who := cmp.Or(held.User, "the Codex account")
if held.Resets == nil && held.Error == "" {
return fmt.Errorf("%s holds no rate-limit reset", who)
}
if !yes {
n := "one of its resets"
if held.Resets != nil {
n = "one of its " + plural(held.Resets.Count, "reset")
}
if held.Resets != nil && held.Resets.Until != nil {
n += " (the one that runs out first, " + provider.ResetClock(*held.Resets.Until, time.Now()) + ")"
}
fmt.Printf("Spend %s on %s, starting its current windows again? It can't be undone. [y/N] ", n, who)
line, _ := stdin.ReadString('\n')
if a := strings.ToLower(strings.TrimSpace(line)); a != "y" && a != "yes" {
return fmt.Errorf("nothing spent")
}
}
out, err := provider.UseCodexReset(ctx, held.User)
if err != nil {
return err
}
if out.Code != "reset" {
return fmt.Errorf("%s: %s", who, out.Text())
}
fmt.Println(green.Render("✓"), who+":", out.Text())
return nil
}
// quotaTitle is a quota's line head: its provider, plan and account.
func quotaTitle(q provider.Quota) string {
t := q.Provider
if q.Plan != "" {
t += " · " + q.Plan
}
if s := provider.PlanTerm(q.Until, q.Renew); s != "" {
t += " · " + s
}
if q.User != "" {
t += " · " + q.User
}
return t
}
func quotaMatches(q provider.Quota, only []string) bool {
for _, o := range only {
if strings.EqualFold(q.Provider, o) || strings.EqualFold(q.Name, o) || strings.EqualFold(q.Kind, o) {
return true
}
}
return false
}
// withUntold adds a line for each provider named that told nothing, saying
// why, rather than leaving it out as if it weren't there; a name that is no
// provider at all is an error.
func withUntold(qs []provider.Quota, only []string) ([]provider.Quota, error) {
for _, o := range only {
if o == "subscription" || o == "plan" || o == "balance" || slices.ContainsFunc(qs, func(q provider.Quota) bool { return quotaMatches(q, []string{o}) }) {
continue
}
p, err := provider.Find(o)
if err != nil {
return nil, err
}
qs = append(qs, provider.Quota{Provider: p.ID, Name: p.Name, Kind: "balance", Windows: []provider.QuotaSpan{},
Error: "not configured · no balance endpoint known for it; set Balance URL and Balance field in its editor"})
}
return qs, nil
}