cli, gateway: magpie statusline prints the session's model and each account's windows for Claude Code's status line (#1997, kensenzhao)

kensenzhao asked for magpie's routing and quota in Claude Code's status
line. Claude Code runs the statusLine command on every update and cancels
the run that is still going, so the command must answer fast. It must never
make a vendor read.

- `magpie statusline [<provider|account>]` reads Claude Code's statusLine
  JSON from stdin. It prints "→ <served model>" from
  /v1/magpie/route?session=<session_id>, then each subscription account's
  windows ("claude a@x* 5h 62% 7d 41%"). `*` marks the account that served
  last. A window whose reset has passed shows 0%. With the gateway off it
  prints an empty line. Each request times out after 1s.
- /v1/magpie/quotas?kept=1 (provider.KeptQuotaReport) builds the same
  report from the kept cards (CachedCards) and never starts a vendor read.
  The plain endpoint can take up to 12s.
- magpie never writes statusLine into Claude Code's settings. The user
  adds `"statusLine": {"type": "command", "command": "magpie statusline"}`
  themselves (magpie statusline's help, docs/reference.md).

Run: go test -tags nogui ./internal/cli ./internal/provider
./internal/gateway in a sandbox HOME; gofmt -l; go vet natively and with
GOOS=linux and GOOS=windows.

Broken by hand, each went red:
- the CLI asking without kept=1 (TestStatuslineTellsRouteAndEveryAccount);
- dropping the route line (same test);
- KeptQuotaReport calling QuotaReport (TestKeptQuotaReportAsksNobody).

Real use: a built binary against a sandbox gateway on 127.0.0.1:3517.
- kept=1 answered in 0.07s and route in under 1ms.
- `magpie statusline` with Claude-style stdin printed an empty line, since
  the sandbox has no accounts.
- Its ~1.1s wall time matches `magpie version`, so that is process start.
Not tried: real accounts, or the line inside a real Claude Code statusLine.
This commit is contained in:
yetone
2026-10-14 08:26:04 +08:00
parent a5d72a095b
commit 8f03b78069
8 changed files with 341 additions and 0 deletions
+18
View File
@@ -1633,6 +1633,24 @@ subscription account, plan and key that answered a request through the
gateway in the last 30 days, and `last: true` on the latest. It is kept
in `served.json` beside `providers.json`, so a restart keeps it.
`GET /v1/magpie/quotas?kept=1` answers the same list from what magpie last
read, asking no vendor and never waiting for a read, for something that asks
often. `magpie statusline` is built on it for Claude Code's status line
(#1997): Claude Code runs it on every message with the session's JSON on
stdin, and it prints one line, the model the session's latest turn went to
(from `/v1/magpie/route`), then each subscription and plan with its windows'
use, `*` on the one that answered last:
`→ claude/claude-opus-5-5 | claude a@example.com* 5h 62% 7d 41% | claude B 5h 8% 7d 30%`.
The accounts that answered through the gateway in the last 30 days are
shown, every one when none has; `magpie statusline claude` (a provider, or
an account's email, login or name) keeps only those. It works however Claude
Code signs in to the gateway, unlike the `anthropic-ratelimit-*` headers,
which Claude Code reads only while signed in to claude.ai. magpie doesn't
write it into Claude Code's settings, where another status line may be;
add it to `~/.claude/settings.json` yourself:
`"statusLine": {"type": "command", "command": "magpie statusline"}`. With
the gateway not running it prints an empty line.
A gateway key held to a budget, to some models or to some accounts is told
none of this magpie's accounts (#1981): `/v1/magpie/quotas`,
`/v1/magpie/quotas/history`, `/v1/magpie/quotas/cards`,
+2
View File
@@ -49,6 +49,8 @@ func helpFor(args []string) string {
return pluginUsage
case "quota", "quotas":
return quotaUsage
case "statusline":
return statuslineUsage
case "sessions":
return sessionsUsage
case "search":
+3
View File
@@ -121,6 +121,7 @@ const usage = `magpie — one place to pick every agent's model
block until that subscription (any of its accounts) or account has allowance again
magpie quota history [<provider|account>] [--days N] [--json]
each window's readings over time, kept 45 days
magpie statusline [<provider|account>] one line for Claude Code's status line: the session's model and each account's windows
magpie sync refresh the model catalog and vendor model lists
magpie agents list every supported agent
magpie update [check] [--proxy <url>] [--mirror <prefix>]
@@ -360,6 +361,8 @@ func run(args []string) error {
return sessionsCmd(args)
case "quota", "quotas":
return quotaCmd(args)
case "statusline":
return statuslineCmd(args)
case "update":
return updateCmd(args)
case "library", "lib":
+166
View File
@@ -0,0 +1,166 @@
package cli
// magpie statusline: one line for Claude Code's status line (#1997,
// kensenzhao). Claude Code runs the statusLine command on every message,
// hands it the session's JSON on stdin and shows what it prints, however
// Claude Code signs in to the gateway; the anthropic-ratelimit-* headers
// (#1257) reach it only while it is signed in to claude.ai itself, and
// tell only the one account that answered. This asks the running gateway
// for what it already holds — the session's latest route and every
// account's windows as last read (/v1/magpie/quotas?kept=1) — and asks no
// vendor itself, so it never waits on one.
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
const statuslineUsage = `usage: magpie statusline [<provider|account>…]
one line for Claude Code's status line: the model the session's latest turn went
to through magpie, then each subscription and plan magpie has, as last read: its
windows' use ("5h 62% 7d 41%"), * on the one that answered last. Accounts that
answered through magpie in the last 30 days are shown, all of them when none has;
a provider or an account's email, login or name keeps only those.
Claude Code runs it on every message with the session's JSON on stdin; put it in
~/.claude/settings.json yourself (magpie doesn't write it, a status line such as
claude-hud may hold it):
"statusLine": {"type": "command", "command": "magpie statusline"}
It asks the gateway on this computer (Settings' Gateway port, or MAGPIE_ADDR), never
a vendor, and prints nothing when the gateway isn't running.`
// statuslineWait bounds each ask of the gateway: Claude Code shows the line
// only once the command ends.
const statuslineWait = time.Second
// statuslineCmd: magpie statusline [<provider|account>…]
func statuslineCmd(args []string) error {
fmt.Println(statusline(os.Stdin, args[1:], "http://"+settings.GatewayAddr(), time.Now()))
return nil
}
// statusline is the line: "" when the gateway can't be asked.
func statusline(stdin io.Reader, only []string, base string, now time.Time) string {
var in struct {
SessionID string `json:"session_id"`
}
if stdin != nil {
// Claude Code's JSON is small; a terminal's stdin with nothing
// piped in isn't waited on (read only when it is a pipe or file)
if f, ok := stdin.(*os.File); !ok || stdinPiped(f) {
_ = json.NewDecoder(io.LimitReader(stdin, 1<<20)).Decode(&in)
}
}
client := &http.Client{Timeout: statuslineWait}
var quotas struct {
Data []provider.Quota `json:"data"`
}
if !getJSON(client, base+"/v1/magpie/quotas?kept=1", &quotas) {
return ""
}
var parts []string
if in.SessionID != "" {
var route struct {
Route *struct {
Asked string `json:"asked"`
Model string `json:"model"`
} `json:"route"`
}
if getJSON(client, base+"/v1/magpie/route?session="+url.QueryEscape(in.SessionID), &route) && route.Route != nil {
if m := route.Route.Model; m != "" {
parts = append(parts, "→ "+m)
} else if route.Route.Asked != "" {
parts = append(parts, "→ "+route.Route.Asked)
}
}
}
for _, q := range statuslineCards(quotas.Data, only) {
parts = append(parts, statuslineCard(q, now))
}
return strings.Join(parts, " | ")
}
// stdinPiped: f is a pipe or a file, not a terminal waiting for typing.
func stdinPiped(f *os.File) bool {
st, err := f.Stat()
return err == nil && st.Mode()&os.ModeCharDevice == 0
}
func getJSON(c *http.Client, u string, v any) bool {
res, err := c.Get(u)
if err != nil {
return false
}
defer res.Body.Close()
return res.StatusCode == http.StatusOK && json.NewDecoder(res.Body).Decode(v) == nil
}
// statuslineCards are the subscriptions and plans with windows to show:
// those named, else those that answered through magpie lately, else all.
func statuslineCards(qs []provider.Quota, only []string) []provider.Quota {
var withWindows, served []provider.Quota
for _, q := range qs {
if q.Kind == "balance" || len(q.Windows) == 0 {
continue
}
if len(only) > 0 && !statuslineMatches(q, only) {
continue
}
withWindows = append(withWindows, q)
if q.LastServedAt != nil {
served = append(served, q)
}
}
if len(only) == 0 && len(served) > 0 {
return served
}
return withWindows
}
func statuslineMatches(q provider.Quota, only []string) bool {
for _, o := range only {
for _, v := range []string{q.Provider, q.Name, q.User, q.Alias, q.Provider + "/" + q.User} {
if v != "" && strings.EqualFold(v, o) {
return true
}
}
}
return false
}
// statuslineCard is one account: "claude a@x.com* 5h 62% 7d 41%".
func statuslineCard(q provider.Quota, now time.Time) string {
name := q.Provider
switch {
case q.Alias != "":
name += " " + q.Alias
case q.User != "":
name += " " + q.User
}
if q.Last {
name += "*"
}
short := strings.NewReplacer(" hours", "h", " hour", "h", " days", "d", " day", "d", " · ", " ")
cells := []string{name}
for _, w := range q.Windows {
n := short.Replace(w.Name)
switch {
case w.Unlimited:
cells = append(cells, n+" ∞")
case w.ResetsAt != nil && !w.ResetsAt.After(now):
// its window has started again since it was read
cells = append(cells, n+" 0%")
default:
cells = append(cells, fmt.Sprintf("%s %.0f%%", n, w.Used))
}
}
return strings.Join(cells, " ")
}
+98
View File
@@ -0,0 +1,98 @@
package cli
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// What Claude Code hands a statusLine command on stdin (code.claude.com
// docs, "Full JSON schema"), cut to the fields around the one read.
const claudeStatusJSON = `{
"cwd": "/Users/me/work",
"session_id": "6f1d2c3a-9b8e-4a7f-8c1d-2e3f4a5b6c7d",
"session_name": "my-session",
"transcript_path": "/Users/me/.claude/projects/work/6f1d2c3a.jsonl",
"model": {"id": "claude-opus-5-5", "display_name": "Opus"},
"workspace": {"current_dir": "/Users/me/work", "project_dir": "/Users/me/work", "added_dirs": []},
"version": "2.1.296",
"output_style": {"name": "default"},
"cost": {"total_cost_usd": 0.01234, "total_duration_ms": 45000, "total_api_duration_ms": 2300, "total_lines_added": 156, "total_lines_removed": 23},
"context_window": {"total_input_tokens": 15500, "total_output_tokens": 1200, "context_window_size": 200000, "used_percentage": 8, "remaining_percentage": 92},
"exceeds_200k_tokens": false
}`
// statuslineGateway is a gateway answering kept quotas only (a vendor read,
// without kept=1, fails the test) and the session's route.
func statuslineGateway(t *testing.T, now time.Time) *httptest.Server {
t.Helper()
at := func(d time.Duration) *time.Time { x := now.Add(d); return &x }
quotas := []provider.Quota{
{Provider: "claude", Name: "Claude Code", Kind: "subscription", User: "a@example.com", LastServedAt: at(-time.Minute), Last: true,
Windows: []provider.QuotaSpan{{Name: "5 hours", Used: 62, Remaining: 38, ResetsAt: at(2 * time.Hour)}, {Name: "7 days", Used: 41, Remaining: 59, ResetsAt: at(72 * time.Hour)}}},
{Provider: "claude", Name: "Claude Code", Kind: "subscription", User: "b@example.com", Alias: "B", LastServedAt: at(-time.Hour),
Windows: []provider.QuotaSpan{{Name: "5 hours", Used: 8, Remaining: 92, ResetsAt: at(-time.Minute)}, {Name: "7 days", Used: 30, Remaining: 70}}},
{Provider: "codex", Name: "Codex", Kind: "subscription", User: "c@example.com",
Windows: []provider.QuotaSpan{{Name: "5 hours", Used: 10, Remaining: 90}}},
{Provider: "deepseek", Name: "DeepSeek", Kind: "balance", Balance: "¥12.00", LastServedAt: at(-time.Minute), Windows: []provider.QuotaSpan{}},
}
mux := http.NewServeMux()
mux.HandleFunc("GET /v1/magpie/quotas", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("kept") != "1" {
t.Errorf("statusline asked %s: that reads the vendors, not what magpie kept", r.URL)
http.Error(w, "vendor read", 500)
return
}
json.NewEncoder(w).Encode(map[string]any{"object": "list", "data": quotas})
})
mux.HandleFunc("GET /v1/magpie/route", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("session") != "6f1d2c3a-9b8e-4a7f-8c1d-2e3f4a5b6c7d" {
json.NewEncoder(w).Encode(map[string]any{"route": nil})
return
}
json.NewEncoder(w).Encode(map[string]any{"session": r.URL.Query().Get("session"), "seq": 3,
"route": map[string]any{"asked": "smart", "group": "smart", "model": "claude/claude-opus-5-5", "tries": []any{}, "done": true, "status": 200}})
})
s := httptest.NewServer(mux)
t.Cleanup(s.Close)
return s
}
func TestStatuslineTellsRouteAndEveryAccount(t *testing.T) {
now := time.Now()
s := statuslineGateway(t, now)
got := statusline(strings.NewReader(claudeStatusJSON), nil, s.URL, now)
// the session's member, then the two accounts that served lately (the
// codex one that didn't and the balance left out); B's 5 hours started
// again since it was read
want := "→ claude/claude-opus-5-5 | claude a@example.com* 5h 62% 7d 41% | claude B 5h 0% 7d 30%"
if got != want {
t.Fatalf("statusline =\n %q\nwant\n %q", got, want)
}
if got := statusline(strings.NewReader(claudeStatusJSON), []string{"codex"}, s.URL, now); got != "→ claude/claude-opus-5-5 | codex c@example.com 5h 10%" {
t.Fatalf("statusline codex = %q", got)
}
// no session on stdin: the accounts alone
if got := statusline(strings.NewReader(""), []string{"b@example.com"}, s.URL, now); got != "claude B 5h 0% 7d 30%" {
t.Fatalf("statusline without a session = %q", got)
}
}
// A gateway that isn't running is an empty line, at once.
func TestStatuslineGatewayOff(t *testing.T) {
s := httptest.NewServer(http.NotFoundHandler())
base := s.URL
s.Close()
start := time.Now()
if got := statusline(strings.NewReader(claudeStatusJSON), nil, base, time.Now()); got != "" {
t.Fatalf("statusline with the gateway off = %q, want nothing", got)
}
if d := time.Since(start); d > 30*time.Second {
t.Fatalf("statusline took %s with the gateway off", d)
}
}
+6
View File
@@ -623,6 +623,12 @@ func (s *Server) quotas(w http.ResponseWriter, r *http.Request) {
if refuseHeld(w, r, heldRefused) {
return
}
// ?kept=1: what was last read, no vendor asked (magpie statusline,
// run on every message, #1997)
if r.URL.Query().Get("kept") == "1" {
writeJSON(w, 200, map[string]any{"object": "list", "data": provider.KeptQuotaReport(time.Now())})
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())})
+18
View File
@@ -110,6 +110,24 @@ func QuotaReport(ctx context.Context, now time.Time) []Quota {
return withServed(quotaReport(subs, plans, balances, now), LastServed())
}
// KeptQuotaReport is QuotaReport from what was last read (CachedCards),
// asking no vendor: for a status line, which Claude Code runs again on
// every message (#1997), so it must neither wait for a read nor start one.
func KeptQuotaReport(now time.Time) []Quota {
var subs, plans, balances []SubscriptionQuota
for _, q := range CachedCards(now) {
switch q.Kind {
case "plan":
plans = append(plans, q)
case "balance":
balances = append(balances, q)
default:
subs = append(subs, q)
}
}
return withServed(quotaReport(subs, plans, balances, now), LastServed())
}
// quotaReport assembles the cards from readings the tests feed directly.
func quotaReport(subs, plans, balances []SubscriptionQuota, now time.Time) []Quota {
out := []Quota{}
+30
View File
@@ -258,6 +258,36 @@ func TestCachedCardsAskNobody(t *testing.T) {
}
}
// The status line's report (#1997) is the cards as last read, as Quota:
// nothing is read for it, however old they are.
func TestKeptQuotaReportAsksNobody(t *testing.T) {
azureHome(t)
c := &subscriptionUsageCache
c.Lock()
keep, keepAt := c.data, c.at
c.data = []SubscriptionQuota{{Provider: "codex", Name: "Codex", User: "a@x.com", Windows: []QuotaWindow{{Name: "5 hours", Used: 62, ResetSecs: 3600}}}}
c.at = time.Now().Add(-time.Hour)
c.Unlock()
t.Cleanup(func() {
c.Lock()
c.data, c.at = keep, keepAt
c.Unlock()
})
qs := KeptQuotaReport(time.Now())
if len(qs) != 1 || qs[0].Provider != "codex" || qs[0].Kind != "subscription" || len(qs[0].Windows) != 1 || qs[0].Windows[0].Used != 62 || qs[0].Windows[0].ResetsAt == nil {
t.Fatalf("report: %+v", qs)
}
if SubscriptionUsageReading() {
t.Error("the report started a read")
}
c.Lock()
at := c.at
c.Unlock()
if time.Since(at) < 30*time.Minute {
t.Error("the cache was read again")
}
}
// A remote magpie's history comes with its cards' ids.
func TestRemoteQuotaHistories(t *testing.T) {
remoteQuotaHome(t, &fakePeer{})