From 7b69b22a76cb355dd3ee6ab81075307f3f3f74df Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 26 Sep 2026 17:22:00 +0800 Subject: [PATCH] =?UTF-8?q?quota:=20what=20is=20left=20of=20every=20subscr?= =?UTF-8?q?iption,=20plan=20and=20key=20balance,=20for=20scripts=20and=20a?= =?UTF-8?q?gents=20=E2=80=94=20magpie=20quota=20[]=20[--json]=20?= =?UTF-8?q?prints=20each=20window's=20use=20and=20remaining=20percent=20an?= =?UTF-8?q?d=20when=20it=20starts=20again,=20and=20each=20key's=20balance;?= =?UTF-8?q?=20the=20gateway=20answers=20the=20same=20at=20GET=20/v1/magpie?= =?UTF-8?q?/quotas=20(only=20to=20this=20machine,=20as=20it=20names=20the?= =?UTF-8?q?=20accounts),=20so=20an=20agent=20can=20pick=20where=20to=20sen?= =?UTF-8?q?d=20its=20work=20(#85)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- accounts_cli.go | 8 +--- internal/gateway/gateway.go | 18 ++++++- internal/gui/usage.go | 7 +-- internal/provider/quotas.go | 75 +++++++++++++++++++++++++++++ main.go | 3 ++ quota_cli.go | 94 +++++++++++++++++++++++++++++++++++++ 6 files changed, 191 insertions(+), 14 deletions(-) create mode 100644 internal/provider/quotas.go create mode 100644 quota_cli.go diff --git a/accounts_cli.go b/accounts_cli.go index 1e8e2077e..07964acef 100644 --- a/accounts_cli.go +++ b/accounts_cli.go @@ -161,13 +161,7 @@ type accountRow struct { Lapsed string `json:"lapsed,omitempty"` // its sign-in has to be made again } -type quotaSpan struct { - Name string `json:"name"` - Used float64 `json:"used"` // percent - Remaining float64 `json:"remaining"` // percent - ResetsAt *time.Time `json:"resetsAt,omitempty"` - Display string `json:"display,omitempty"` -} +type quotaSpan = provider.QuotaSpan // accountRows asks each agent's accounts for their allowance at once; what // was asked less than a minute ago comes from magpie's cache. diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 69c7e1078..e661c627e 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -168,6 +168,7 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("GET /v1/models", s.models) mux.HandleFunc("GET /models", s.models) mux.HandleFunc("GET /v1/models/{id}", s.model) + mux.HandleFunc("GET /v1/magpie/quotas", s.quotas) mux.HandleFunc("POST /v1/chat/completions", s.handle(provider.Chat)) mux.HandleFunc("POST /chat/completions", s.handle(provider.Chat)) mux.HandleFunc("POST /v1/responses", s.handle(provider.Responses)) @@ -187,7 +188,22 @@ func (s *Server) Handler() http.Handler { func (s *Server) info(w http.ResponseWriter, r *http.Request) { writeJSON(w, 200, map[string]any{"name": "magpie", "version": Version, "models": len(provider.Catalog()), - "apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1beta/models/{model}:generateContent"}}) + "apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1beta/models/{model}:generateContent", "/v1/magpie/quotas"}}) +} + +// quotas is what is left of every subscription, plan and key magpie has, +// for an agent choosing where to send its work (magpie quota --json is the +// same). It names the accounts and their balances, so it answers only on +// this machine, when the gateway listens beyond it too. +func (s *Server) quotas(w http.ResponseWriter, r *http.Request) { + host, _, _ := net.SplitHostPort(r.RemoteAddr) + if ip := net.ParseIP(host); ip == nil || !ip.IsLoopback() { + writeError(w, provider.Chat, http.StatusForbidden, "magpie's quotas are only told to this machine") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second) + defer cancel() + writeJSON(w, 200, map[string]any{"object": "list", "data": provider.QuotaReport(ctx, time.Now())}) } func modelObject(e provider.Entry) map[string]any { diff --git a/internal/gui/usage.go b/internal/gui/usage.go index 015847f85..534ef3fc6 100644 --- a/internal/gui/usage.go +++ b/internal/gui/usage.go @@ -73,11 +73,6 @@ func usageRoutes(mux *http.ServeMux) { mux.HandleFunc("GET /api/usage/quotas", func(rw http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second) defer cancel() - balances := make(chan []provider.SubscriptionQuota, 1) - plans := make(chan []provider.SubscriptionQuota, 1) - go func() { balances <- provider.KeyBalances(ctx) }() - go func() { plans <- provider.PlanQuotas(ctx) }() - out := append(provider.SubscriptionUsage(ctx), <-plans...) - writeJSON(rw, append(out, <-balances...)) + writeJSON(rw, provider.Quotas(ctx)) }) } diff --git a/internal/provider/quotas.go b/internal/provider/quotas.go new file mode 100644 index 000000000..473e4501c --- /dev/null +++ b/internal/provider/quotas.go @@ -0,0 +1,75 @@ +package provider + +import ( + "context" + "time" +) + +// Quotas is what is left everywhere magpie can ask: the signed-in +// subscriptions' windows, the plans bought with a key, and the keys' +// balances, as the Usage page shows them. The vendors are asked at once; +// what doesn't answer before ctx ends comes back with an error. +func Quotas(ctx context.Context) []SubscriptionQuota { + subs, plans, balances := quotas(ctx) + return append(append(subs, plans...), balances...) +} + +func quotas(ctx context.Context) (subs, plans, balances []SubscriptionQuota) { + b := make(chan []SubscriptionQuota, 1) + p := make(chan []SubscriptionQuota, 1) + go func() { b <- KeyBalances(ctx) }() + go func() { p <- PlanQuotas(ctx) }() + subs = SubscriptionUsage(ctx) + return subs, <-p, <-b +} + +// Quota is one account's or key's allowance as magpie quota --json and +// the gateway's GET /v1/magpie/quotas tell it, for an agent choosing +// where to send its work: Provider is the first part of the models' +// ids (provider/model) for a key's plan or balance, the agent for a +// subscription. +type Quota struct { + Provider string `json:"provider"` + Name string `json:"name"` + Kind string `json:"kind"` // subscription, plan (bought with a key) or balance (a key's money) + Plan string `json:"plan,omitempty"` + User string `json:"user,omitempty"` + Windows []QuotaSpan `json:"windows"` + Balance string `json:"balance,omitempty"` + Error string `json:"error,omitempty"` +} + +// QuotaSpan is one window of an allowance: how much of it is used and +// left, in percent, and when it starts again. +type QuotaSpan struct { + Name string `json:"name"` + Used float64 `json:"used"` + Remaining float64 `json:"remaining"` + ResetsAt *time.Time `json:"resetsAt,omitempty"` + Display string `json:"display,omitempty"` // the vendor's own count, "1.2k / 3k" +} + +// QuotaReport is Quotas as Quota, the reset times made absolute from now. +func QuotaReport(ctx context.Context, now time.Time) []Quota { + subs, plans, balances := quotas(ctx) + out := []Quota{} + for _, g := range []struct { + kind string + qs []SubscriptionQuota + }{{"subscription", subs}, {"plan", plans}, {"balance", balances}} { + for _, q := range g.qs { + r := Quota{Provider: q.Provider, Name: q.Name, Kind: g.kind, Plan: q.Plan, User: q.User, + Windows: []QuotaSpan{}, Balance: q.Balance, Error: q.Error} + for _, w := range q.Windows { + s := QuotaSpan{Name: w.Name, Used: w.Used, Remaining: max(0, 100-w.Used), ResetsAt: w.ResetsAt, Display: w.Display} + if s.ResetsAt == nil && w.ResetSecs > 0 { + t := now.Add(time.Duration(w.ResetSecs) * time.Second) + s.ResetsAt = &t + } + r.Windows = append(r.Windows, s) + } + out = append(out, r) + } + } + return out +} diff --git a/main.go b/main.go index 070adf127..254bd05dc 100644 --- a/main.go +++ b/main.go @@ -67,6 +67,7 @@ const usage = `magpie — one place to pick every agent's model magpie serve run the gateway alone (the app runs it too) magpie usage [today|7d|30d|all] tokens and cost per agent and model (30d) + magpie quota [] [--json] what is left of every subscription, plan and key balance magpie sync refresh the model catalog and vendor model lists magpie agents list every supported agent magpie update [check] install the newest release (check: only say if there is one) @@ -170,6 +171,8 @@ func run(args []string) error { return accountsCmd(args) case "usage": return usageCmd(args) + case "quota", "quotas": + return quotaCmd(args) case "update": return updateCmd(args) case "library", "lib": diff --git a/quota_cli.go b/quota_cli.go new file mode 100644 index 000000000..592306ab4 --- /dev/null +++ b/quota_cli.go @@ -0,0 +1,94 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +const quotaUsage = `usage: magpie quota […] [--json] + 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` + +// quotaCmd: magpie quota […] [--json] +func quotaCmd(args []string) error { + 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) + } + } + 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.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 +} + +// 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 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 +}