routing: a Claude account is known once it answers — Claude Code's rate_limit_event (Anthropic's anthropic-ratelimit-unified-* headers: the five hours and the week, used and when they renew) is kept as the account's allowance, standing an hour for a usage endpoint that turns magpie away; and one not known yet goes before those known in smart routing, not after them, where it never answered and so was never known
This commit is contained in:
@@ -490,6 +490,8 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
|
||||
// what Claude Code's WebSearch found, on the message that
|
||||
// answers its call
|
||||
ToolUseResult json.RawMessage `json:"tool_use_result"`
|
||||
// what the account has left, as Anthropic told Claude Code
|
||||
RateLimitInfo json.RawMessage `json:"rate_limit_info"`
|
||||
Event struct {
|
||||
Type string `json:"type"`
|
||||
Index int `json:"index"`
|
||||
@@ -518,6 +520,12 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
|
||||
if json.Unmarshal(s.Bytes(), &envelope) != nil {
|
||||
continue
|
||||
}
|
||||
if envelope.Type == "rate_limit_event" {
|
||||
if _, user, ok := strings.Cut(r.owner, "\x00"); ok {
|
||||
provider.NoteClaudeLimits(user, claudeLimits(envelope.RateLimitInfo))
|
||||
}
|
||||
continue
|
||||
}
|
||||
if envelope.Type == "result" {
|
||||
if envelope.IsError {
|
||||
r.emit(Event{Kind: KError, Text: envelope.Result})
|
||||
@@ -619,6 +627,39 @@ type cliUsage struct {
|
||||
|
||||
// plus adds v's counts to u's; only to those u has, when it only updates
|
||||
// what the client was told.
|
||||
// claudeLimits are the allowance windows a rate_limit_event's info tells:
|
||||
// each of its unifiedWindows, and the one it is about, when that says how
|
||||
// much is used or that it turned the request away.
|
||||
func claudeLimits(raw json.RawMessage) []provider.ClaudeLimit {
|
||||
type window struct {
|
||||
Utilization float64 `json:"utilization"`
|
||||
ResetsAt int64 `json:"resetsAt"`
|
||||
}
|
||||
var info struct {
|
||||
Status string `json:"status"`
|
||||
RateLimitType string `json:"rateLimitType"`
|
||||
Utilization *float64 `json:"utilization"`
|
||||
ResetsAt int64 `json:"resetsAt"`
|
||||
UnifiedWindows map[string]window `json:"unifiedWindows"`
|
||||
}
|
||||
if json.Unmarshal(raw, &info) != nil {
|
||||
return nil
|
||||
}
|
||||
var out []provider.ClaudeLimit
|
||||
for kind, w := range info.UnifiedWindows {
|
||||
out = append(out, provider.ClaudeLimit{Kind: kind, Used: w.Utilization, ResetsAt: w.ResetsAt})
|
||||
}
|
||||
if _, told := info.UnifiedWindows[info.RateLimitType]; !told && info.RateLimitType != "" {
|
||||
switch {
|
||||
case info.Utilization != nil:
|
||||
out = append(out, provider.ClaudeLimit{Kind: info.RateLimitType, Used: *info.Utilization, ResetsAt: info.ResetsAt})
|
||||
case info.Status == "rejected":
|
||||
out = append(out, provider.ClaudeLimit{Kind: info.RateLimitType, Used: 1, ResetsAt: info.ResetsAt})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (u Usage) plus(v Usage, only bool) Usage {
|
||||
for _, f := range []struct{ a, b *int }{{&u.Input, &v.Input}, {&u.Output, &v.Output}, {&u.CacheRead, &v.CacheRead}, {&u.CacheWrite, &v.CacheWrite}, {&u.Reasoning, &v.Reasoning}} {
|
||||
if *f.a > 0 || !only {
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -217,3 +218,23 @@ func TestClaudeOwnWebSearchStaysInside(t *testing.T) {
|
||||
t.Fatalf("usage: %+v", usage)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaudeLimits(t *testing.T) {
|
||||
got := claudeLimits(json.RawMessage(`{"status":"allowed","resetsAt":1800000000,"rateLimitType":"five_hour","utilization":0.42,
|
||||
"unifiedWindows":{"five_hour":{"utilization":0.42,"resetsAt":1800000000},"seven_day":{"utilization":0.1,"resetsAt":1800500000}}}`))
|
||||
slices.SortFunc(got, func(a, b provider.ClaudeLimit) int { return strings.Compare(a.Kind, b.Kind) })
|
||||
want := []provider.ClaudeLimit{{Kind: "five_hour", Used: 0.42, ResetsAt: 1800000000}, {Kind: "seven_day", Used: 0.1, ResetsAt: 1800500000}}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("windows: %+v", got)
|
||||
}
|
||||
// without the windows: the one it is about, and one turned away is full
|
||||
if got := claudeLimits(json.RawMessage(`{"status":"allowed_warning","rateLimitType":"seven_day","utilization":0.9,"resetsAt":5}`)); !slices.Equal(got, []provider.ClaudeLimit{{Kind: "seven_day", Used: 0.9, ResetsAt: 5}}) {
|
||||
t.Fatalf("top level: %+v", got)
|
||||
}
|
||||
if got := claudeLimits(json.RawMessage(`{"status":"rejected","rateLimitType":"five_hour","resetsAt":7}`)); !slices.Equal(got, []provider.ClaudeLimit{{Kind: "five_hour", Used: 1, ResetsAt: 7}}) {
|
||||
t.Fatalf("rejected: %+v", got)
|
||||
}
|
||||
if got := claudeLimits(json.RawMessage(`{"status":"allowed"}`)); len(got) != 0 {
|
||||
t.Fatalf("nothing said: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,6 +276,13 @@ type left struct {
|
||||
renews []time.Time
|
||||
}
|
||||
|
||||
// learns: c is a subscription whose allowance isn't known yet, of an agent
|
||||
// that tells it as it answers (Claude Code's rate_limit_event).
|
||||
func learns(c candidate, lefts map[string]left) bool {
|
||||
_, known := lefts[c.rest]
|
||||
return !known && c.p.Account != nil && c.p.Account.Agent == "claude"
|
||||
}
|
||||
|
||||
// weigh orders one provider's candidates as its routing says, and tells
|
||||
// what it went by.
|
||||
func weigh(p provider.Provider, cs []candidate, model string, from provider.Protocol) ([]candidate, weighing) {
|
||||
@@ -324,7 +331,14 @@ func weigh(p provider.Provider, cs []candidate, model string, from provider.Prot
|
||||
fine = append(fine, c)
|
||||
}
|
||||
}
|
||||
// one not known that tells what it has left as it answers goes
|
||||
// first, once: else, kept after those known, it would never answer
|
||||
// and never be known (Anthropic's usage endpoint can turn
|
||||
// magpie away for hours)
|
||||
sort.SliceStable(fine, func(i, j int) bool {
|
||||
if li, lj := learns(fine[i], lefts), learns(fine[j], lefts); li != lj {
|
||||
return li
|
||||
}
|
||||
ri, rj := lefts[fine[i].rest].renews, lefts[fine[j].rest].renews
|
||||
for k := 0; k < len(ri) || k < len(rj); k++ {
|
||||
var a, b time.Time // to the hour, so a few minutes don't reorder
|
||||
|
||||
@@ -196,3 +196,32 @@ func TestSmartRouting(t *testing.T) {
|
||||
t.Fatalf("reset header: %v", d)
|
||||
}
|
||||
}
|
||||
|
||||
// A Claude account whose allowance isn't known goes before those known,
|
||||
// as its answer tells what it has left; one of another agent, after.
|
||||
func TestUnknownClaudeGoesFirst(t *testing.T) {
|
||||
old := allowances
|
||||
defer func() { allowances = old }()
|
||||
now := time.Now()
|
||||
allowances = func(agent string) map[string]provider.Allowance {
|
||||
if agent == "codex" {
|
||||
return map[string]provider.Allowance{"k": {{Used: 10, Resets: now.Add(24 * time.Hour)}}}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
acct := func(agent, user string) candidate {
|
||||
return candidate{p: provider.Provider{Account: &provider.Account{Agent: agent, User: user}}, model: "m", rest: "g#" + user}
|
||||
}
|
||||
p := provider.Provider{ID: "g"}
|
||||
cs := []candidate{acct("codex", "k"), acct("x", "u"), acct("claude", "c")}
|
||||
got, wg := weigh(p, cs, "m", provider.Anthropic)
|
||||
if s := restsOf(got); s != "g#c g#k g#u " {
|
||||
t.Fatalf("order: %s", s)
|
||||
}
|
||||
if w := weighed(got[0], p, wg, false, provider.Anthropic); !w.Learns || w.Known {
|
||||
t.Fatalf("claude: %+v", w)
|
||||
}
|
||||
if w := weighed(got[2], p, wg, false, provider.Anthropic); w.Learns {
|
||||
t.Fatalf("other agent: %+v", w)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,6 +113,7 @@ type Weighed struct {
|
||||
Fallback bool `json:"fallback,omitempty"`
|
||||
Shared bool `json:"shared,omitempty"` // its provider has more than one on
|
||||
Known bool `json:"known,omitempty"` // the vendor said what the account has left
|
||||
Learns bool `json:"learns,omitempty"` // not known, but its answer will tell
|
||||
Used float64 `json:"used"` // share of the allowance counting the model, used
|
||||
Renews []time.Time `json:"renews,omitempty"` // when those windows renew, the biggest first
|
||||
Tokens float64 `json:"tokens,omitempty"` // least used: tokens it served lately
|
||||
@@ -165,6 +166,8 @@ func weighed(c candidate, p provider.Provider, wg weighing, fallback bool, from
|
||||
}
|
||||
if l, ok := wg.lefts[c.rest]; ok {
|
||||
w.Known, w.Used, w.Renews = true, l.used, l.renews
|
||||
} else if wg.lefts != nil {
|
||||
w.Learns = learns(c, wg.lefts)
|
||||
}
|
||||
if wg.tokens != nil {
|
||||
w.Tokens = wg.tokens[c.rest]
|
||||
|
||||
@@ -835,6 +835,8 @@ const I18N = {
|
||||
"{who} is at {n} — all but used up, it answers only when nothing else can.": "{who} 已用 {n}——几乎用尽,只在别的都不行时才用它。",
|
||||
"{who} is at {n} — kept for when the others can't.": "{who} 已用 {n}——留给其他账号都不行的时候。",
|
||||
"{who}: what it has left isn't known yet, so it goes after those known.": "{who}:还不知道它剩多少,所以排在已知的之后。",
|
||||
"{who}: what it has left isn't known yet, and its answer tells, so it goes before those known.": "{who}:还不知道它剩多少,它一回答就知道了,所以排在已知的之前。",
|
||||
"{who} goes first: what it has left isn't known yet, and its answer tells — kept behind those known, it would never answer and never be known.": "{who} 先上:还不知道它剩多少,它一回答就知道了——排在已知的后面,它就永远轮不到、也永远不会知道。",
|
||||
"{who} is left out: its plan doesn't list {model}.": "{who} 不参与:它的套餐不包含 {model}。",
|
||||
"{who} is left out: {name} lists {model} to its other keys, not this one.": "{who} 不参与:{name} 只在它其他 key 的模型列表里列出了 {model},这个 key 的列表里没有。",
|
||||
"{who} is answering…": "{who} 正在回答…",
|
||||
|
||||
@@ -200,6 +200,7 @@
|
||||
return restedTo(t("the others go in their order.")) || t("{who} goes first: keys go in their order, those that suit the request first.", { who: w });
|
||||
}
|
||||
if (f.kind !== "account") return t("{who} goes first.", { who: w });
|
||||
if (f.learns && peers.some((p) => p.known)) return t("{who} goes first: what it has left isn't known yet, and its answer tells — kept behind those known, it would never answer and never be known.", { who: w });
|
||||
if (!f.known && !peers.some((p) => p.known)) return t("The vendor hasn't said yet what these accounts have left, so they go in their order: {who} first.", { who: w });
|
||||
if (group(f) !== "fine") return t("Every account is at 90% or more of its allowance, so the one with the most left goes first: {who}, at {n}.", { who: w, n: pct(f.used) });
|
||||
const next = peers.find((p) => p.known && group(p) === "fine");
|
||||
@@ -231,6 +232,7 @@
|
||||
if (x.rest) out.push(t("{who} is resting — {why}, {when} — so it waits at the back.", { who: who(x), why: `${x.rest.status} · ${failWord(x.rest.why)}`, when: restWhen(x.rest, at(r.time)) }));
|
||||
else if (smart(x) && x.known && group(x) === "spent") out.push(t("{who} is at {n} — all but used up, it answers only when nothing else can.", { who: who(x), n: pct(x.used) }));
|
||||
else if (smart(x) && x.known && group(x) === "low") out.push(t("{who} is at {n} — kept for when the others can't.", { who: who(x), n: pct(x.used) }));
|
||||
else if (smart(x) && x.learns && someKnown) out.push(t("{who}: what it has left isn't known yet, and its answer tells, so it goes before those known.", { who: who(x) }));
|
||||
else if (smart(x) && !x.known && someKnown) out.push(t("{who}: what it has left isn't known yet, so it goes after those known.", { who: who(x) }));
|
||||
}
|
||||
const pooled = r.order.find((x) => !x.aside && x.kind === "key");
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Claude Code tells what an account has left as it answers (its
|
||||
// rate_limit_event, from Anthropic's anthropic-ratelimit-unified-* headers),
|
||||
// so an account whose usage endpoint keeps turning magpie away (429) is
|
||||
// known all the same once it has answered.
|
||||
|
||||
// ClaudeLimit is one allowance window as Claude Code tells it: its kind
|
||||
// (five_hour, seven_day, seven_day_opus, seven_day_sonnet), the share used,
|
||||
// 0–1, and when it renews, in Unix seconds (0 when not said).
|
||||
type ClaudeLimit struct {
|
||||
Kind string
|
||||
Used float64
|
||||
ResetsAt int64
|
||||
}
|
||||
|
||||
// claudeKinds are the windows Claude Code names, as the usage endpoint's
|
||||
// are kept, in that order.
|
||||
var claudeKinds = []struct {
|
||||
kind, name, model string
|
||||
span time.Duration
|
||||
}{
|
||||
{"five_hour", "5 hours", "", 5 * time.Hour},
|
||||
{"seven_day", "7 days", "", 7 * 24 * time.Hour},
|
||||
{"seven_day_opus", "7 days · Opus", "opus", 7 * 24 * time.Hour},
|
||||
{"seven_day_sonnet", "7 days · Sonnet", "sonnet", 7 * 24 * time.Hour},
|
||||
}
|
||||
|
||||
// claudeHeard is how long what Claude Code said as it answered stands in
|
||||
// for the usage endpoint when that fails.
|
||||
const claudeHeard = time.Hour
|
||||
|
||||
// NoteClaudeLimits keeps what Claude Code said of user's allowance as it
|
||||
// answered, in place of the windows of the same names last read, and has
|
||||
// routing weigh the account by it.
|
||||
func NoteClaudeLimits(user string, ls []ClaudeLimit) {
|
||||
var heard []QuotaWindow
|
||||
for _, l := range ls {
|
||||
i := slices.IndexFunc(claudeKinds, func(k struct {
|
||||
kind, name, model string
|
||||
span time.Duration
|
||||
}) bool {
|
||||
return k.kind == l.Kind
|
||||
})
|
||||
if i < 0 {
|
||||
continue
|
||||
}
|
||||
k := claudeKinds[i]
|
||||
w := QuotaWindow{Name: k.name, Used: l.Used * 100, Span: k.span, Model: k.model}
|
||||
if l.ResetsAt > 0 {
|
||||
t := time.Unix(l.ResetsAt, 0)
|
||||
w.ResetsAt = &t
|
||||
}
|
||||
heard = append(heard, w)
|
||||
}
|
||||
if len(heard) == 0 {
|
||||
return
|
||||
}
|
||||
key := strings.ToLower(user)
|
||||
c := &claudeUsage
|
||||
c.Lock()
|
||||
if c.m == nil {
|
||||
c.m = map[string]claudeUsageEntry{}
|
||||
}
|
||||
e := c.m[key]
|
||||
ws := []QuotaWindow{}
|
||||
for _, w := range e.ws {
|
||||
if !slices.ContainsFunc(heard, func(h QuotaWindow) bool { return h.Name == w.Name }) {
|
||||
ws = append(ws, w)
|
||||
}
|
||||
}
|
||||
ws = append(ws, heard...)
|
||||
order := func(w QuotaWindow) int {
|
||||
for i, k := range claudeKinds {
|
||||
if k.name == w.Name {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return len(claudeKinds)
|
||||
}
|
||||
slices.SortStableFunc(ws, func(a, b QuotaWindow) int { return order(a) - order(b) })
|
||||
e.ws, e.at, e.heard = ws, time.Now(), time.Now()
|
||||
c.m[key] = e
|
||||
c.Unlock()
|
||||
StaleAllowance("claude", user)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// What Claude Code says as it answers is the account's allowance, without
|
||||
// the usage endpoint, which keeps the windows it alone tells.
|
||||
func TestNoteClaudeLimits(t *testing.T) {
|
||||
old := claudeBase
|
||||
claudeBase = "http://127.0.0.1:1" // nothing answers there
|
||||
defer func() { claudeBase = old }()
|
||||
reset := time.Now().Add(2 * time.Hour).Truncate(time.Second)
|
||||
claudeUsage.Lock()
|
||||
claudeUsage.m = map[string]claudeUsageEntry{"kev@example.com": {at: time.Now().Add(-time.Hour), ws: []QuotaWindow{
|
||||
{Name: "7 days · Opus", Used: 30, Model: "opus"}, {Name: "5 hours", Used: 5},
|
||||
}}}
|
||||
claudeUsage.Unlock()
|
||||
defer func() { claudeUsage.Lock(); claudeUsage.m = nil; claudeUsage.Unlock() }()
|
||||
|
||||
NoteClaudeLimits("Kev@example.com", []ClaudeLimit{{Kind: "five_hour", Used: 0.42, ResetsAt: reset.Unix()}, {Kind: "seven_day", Used: 0.1}, {Kind: "overage", Used: 1}})
|
||||
ws, err := claudeWindows(context.Background(), "kev@example.com", "tok")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var names []string
|
||||
for _, w := range ws {
|
||||
names = append(names, w.Name)
|
||||
}
|
||||
if len(ws) != 3 || ws[0].Name != "5 hours" || ws[0].Used != 42 || !ws[0].ResetsAt.Equal(reset) || ws[0].Span != 5*time.Hour || ws[1].Name != "7 days" || ws[1].Used != 10 || ws[2].Name != "7 days · Opus" {
|
||||
t.Fatalf("windows: %v %+v", names, ws)
|
||||
}
|
||||
|
||||
// past the cache, the usage endpoint failing leaves what was heard
|
||||
claudeUsage.Lock()
|
||||
e := claudeUsage.m["kev@example.com"]
|
||||
e.at = time.Now().Add(-10 * time.Minute)
|
||||
claudeUsage.m["kev@example.com"] = e
|
||||
claudeUsage.Unlock()
|
||||
if ws, err := claudeWindows(context.Background(), "kev@example.com", "tok"); err != nil || len(ws) != 3 {
|
||||
t.Fatalf("after the endpoint failed: %v %v", ws, err)
|
||||
}
|
||||
// heard long ago, the failure is told
|
||||
claudeUsage.Lock()
|
||||
e.heard = time.Now().Add(-2 * time.Hour)
|
||||
claudeUsage.m["kev@example.com"] = e
|
||||
claudeUsage.Unlock()
|
||||
if _, err := claudeWindows(context.Background(), "kev@example.com", "tok"); err == nil {
|
||||
t.Fatal("an old word hid the endpoint's failure")
|
||||
}
|
||||
}
|
||||
@@ -305,6 +305,7 @@ var claudeUsage struct {
|
||||
type claudeUsageEntry struct {
|
||||
at, retry time.Time
|
||||
ws []QuotaWindow
|
||||
heard time.Time // when Claude Code last told it, answering
|
||||
}
|
||||
|
||||
const claudeUsageTTL = 3 * time.Minute
|
||||
@@ -344,13 +345,16 @@ func claudeWindows(ctx context.Context, user, token string) ([]QuotaWindow, erro
|
||||
return []QuotaWindow{}, claudeLimited(wait)
|
||||
}
|
||||
if err != nil {
|
||||
if e.ws != nil && now.Sub(e.heard) < claudeHeard {
|
||||
return elapsed(e.ws, now), nil // what Claude Code said stands
|
||||
}
|
||||
return ws, err
|
||||
}
|
||||
c.Lock()
|
||||
if c.m == nil {
|
||||
c.m = map[string]claudeUsageEntry{}
|
||||
}
|
||||
c.m[key] = claudeUsageEntry{at: now, ws: ws}
|
||||
c.m[key] = claudeUsageEntry{at: now, ws: ws, heard: e.heard}
|
||||
c.Unlock()
|
||||
return ws, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user