oficina / equipo Public

runner: a token check records the rate limit it reports

CheckToken now reads rate_limit_event as a coordinator turn does
(claude.go) and returns the last one seen with its usage rows
(TokenCheck). The Verify wiring in run.go records it like a turn:
Conns.Observe for headroom, Conns.Limit for a rejection, then queues the
usage and asks for a hello so the row hears soon. Nothing new polls:
this is the check that already runs at connect and on Check again, with
the same CLI flags.

The fake CLI's token check answer now carries five_hour and seven_day
windows, and an account whose email starts "spent-" is refused on quota
there. TestHeadlessTokenCheckHeadroom checks both through the real
contained launch and wiring.

Self-review (one pass over this diff):
- Behaviour change, intended: a check refused on quota with a rejected
  rate_limit_event but no api_retry signal used to end errCheckFailed,
  which at connect undid a good token as "This token was rejected". The
  rejected limit is the provider's answer, so it now returns nil and the
  connection is kept, limited until the reported reset.
- A refused token (ErrLoginRequired) records no limit: it is not a
  connection. A check that dies before its result records nothing, as a
  broken turn does.
- At connect the attempt's report says Ready before the hello says
  Limited, so a quota-refused paste shows Ready for one hello. Left.
- Observe can move a never-validated token's state to healthy before
  Validated; candidate() and Held() still hide it until validated, and
  an undone attempt is forgotten. No change needed.
- The fake matches the check by its exact prompt; if tokenCheckPrompt
  changes, the new test fails rather than passing quietly.

Mutations: dropping the Observe call fails the test (windows not kept);
dropping the Limit call fails it (the row is never limited).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev aee9c3559649260d6732de0c217219437c8a57dd parent 577e24c
4 files changed, +155 −24
  • internal/fakeclaude/fake.go +20 −1
  • internal/headless/token_test.go +70 −0
  • internal/runner/thin/run.go +19 −4
  • internal/runner/thin/tokencheck.go +46 −19
diff --git a/internal/fakeclaude/fake.go b/internal/fakeclaude/fake.go
index 51edb54c..e43ea226 100644
--- a/internal/fakeclaude/fake.go
+++ b/internal/fakeclaude/fake.go
@@ -745,6 +745,13 @@ func (f *fake) serve(stdin io.Reader, stdout, stderr io.Writer) int {
refuse()
continue
}
+ // The runner's token check is refused on quota for an account
+ // whose email starts "spent-", as for a spent weekly limit.
+ check := prompt == CheckPrompt
+ if check && strings.HasPrefix(accountEmail(), "spent-") {
+ refuse()
+ continue
+ }
// limitnoreset:<email> is a refusal with no reset time reported;
// authrefused:<email> the provider refusing the credential.
if m := noResetWord.FindStringSubmatch(newest); m != nil && m[1] == accountEmail() {
@@ -911,7 +918,15 @@ func (f *fake) serve(stdin io.Reader, stdout, stderr io.Writer) int {
}
f.record(prompt, reply)
emit(map[string]any{"type": "assistant", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"model": f.model, "id": fmt.Sprintf("msg_fake_%d", turn), "type": "message", "role": "assistant", "content": []any{map[string]string{"type": "text", "text": reply}}, "usage": map[string]int{"input_tokens": len(prompt) / 4, "output_tokens": len(reply) / 4}}, "uuid": fmt.Sprintf("assistant-%d", turn)})
- emit(map[string]any{"type": "rate_limit_event", "rate_limit_info": map[string]any{"status": "allowed", "resetsAt": time.Now().Add(100 * time.Hour).Truncate(time.Hour).Unix(), "rateLimitType": "seven_day", "utilization": 0.25}, "uuid": fmt.Sprintf("limit-%d", turn), "session_id": f.session})
+ info := map[string]any{"status": "allowed", "resetsAt": time.Now().Add(100 * time.Hour).Truncate(time.Hour).Unix(), "rateLimitType": "seven_day", "utilization": 0.25}
+ if check {
+ // The check's answer carries the windows, as the CLI's does.
+ info["unifiedWindows"] = map[string]any{
+ "five_hour": map[string]any{"utilization": 0.12, "resetsAt": time.Now().Add(3 * time.Hour).Truncate(time.Hour).Unix(), "status": "allowed"},
+ "seven_day": map[string]any{"utilization": 0.25, "resetsAt": time.Now().Add(100 * time.Hour).Truncate(time.Hour).Unix(), "status": "allowed"},
+ }
+ }
+ emit(map[string]any{"type": "rate_limit_event", "rate_limit_info": info, "uuid": fmt.Sprintf("limit-%d", turn), "session_id": f.session})
failed := strings.Contains(newest, "fail")
subtype := "success"
if failed {
@@ -1054,6 +1069,10 @@ var stepLimitWord = regexp.MustCompile(`\bsteplimit:([^\s|]+@[^\s|]+[a-z])`)
const tokenEnv = "CLAUDE_CODE_OAUTH_TOKEN"
+// CheckPrompt is the runner's token check, word for word (thin's
+// tokenCheckPrompt).
+const CheckPrompt = "Reply with the single word OK."
+
// Token is a setup token the fake accepts, for email ("" for a token
// whose account the CLI does not name). Any other value is refused.
func Token(email string) string {
diff --git a/internal/headless/token_test.go b/internal/headless/token_test.go
index 61114c68..d57bc03d 100644
--- a/internal/headless/token_test.go
+++ b/internal/headless/token_test.go
@@ -6,6 +6,7 @@ import (
"crypto/rand"
"encoding/base64"
"encoding/json"
+ "math"
"os"
"path/filepath"
"strings"
@@ -295,6 +296,75 @@ func TestHeadlessTokenRejected(t *testing.T) {
})
}
+// A token connection's check reads the provider's rate limits as a turn
+// does: a check that reports windows leaves the connection with that
+// headroom on the runner, and one refused on quota leaves it limited
+// until the reset the provider gave, on the runner and on the row. No
+// turn runs on either.
+func TestHeadlessTokenCheckHeadroom(t *testing.T) {
+ env, inst, r := localEnv(t)
+ r.addToken(t, "claude-7", "tok@example.com")
+ r.addToken(t, "claude-8", "spent-tok@example.com")
+ r.only(t, "claude-7", "claude-8")
+ r.start(t)
+ s := open(t, env)
+ s.keep()
+ ids := map[string]string{}
+ s.wait(t, "both rows", time.Minute, func(cv *thintest.Conversation) bool {
+ for _, c := range cv.Connections {
+ ids[c.LocalID] = c.ID
+ }
+ return ids["claude-7"] != "" && ids["claude-8"] != ""
+ })
+ for _, local := range []string{"claude-7", "claude-8"} {
+ if err := env.Client.CheckConnection(s.ctx, ids[local]); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var spent wire.Connection
+ s.wait(t, "the refused check limits its row", 2*time.Minute, func(cv *thintest.Conversation) bool {
+ spent = cv.Connections[ids["claude-8"]]
+ return spent.State == wire.ConnLimited
+ })
+ if spent.Headroom == nil || spent.Headroom.ResetsAt == nil || time.Until(*spent.Headroom.ResetsAt) < 40*time.Hour {
+ t.Fatalf("the limited row has no reported reset: %+v", spent.Headroom)
+ }
+ until(t, "both checks' usage", func() bool {
+ var n int
+ err := inst.DB.Writer().QueryRow("SELECT count(DISTINCT connection) FROM chat_usage WHERE role = 'check'").Scan(&n)
+ return err == nil && n == 2
+ })
+ r.stop(t)
+ st, err := thin.OpenState(context.Background(), r.cfg.StateDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer st.Close()
+ held := map[string]wire.HeldConnection{}
+ for _, h := range (&thin.Conns{Runner: r.cfg, State: st}).Held() {
+ held[h.LocalID] = h
+ }
+ windows := func(h *wire.Headroom) map[string]float64 {
+ out := map[string]float64{}
+ if h != nil {
+ for _, w := range h.Windows {
+ out[w.Name] = math.Round(w.UsedPercent)
+ }
+ }
+ return out
+ }
+ if got := windows(held["claude-7"].Headroom); held["claude-7"].State != wire.ConnHealthy || len(got) != 2 || got["five_hour"] != 12 || got["seven_day"] != 25 {
+ t.Fatalf("the check's windows were not kept: %+v %v", held["claude-7"], got)
+ }
+ if h := held["claude-8"]; h.State != wire.ConnLimited || windows(h.Headroom)["seven_day"] != 100 {
+ t.Fatalf("the refused check did not limit the connection: %+v", h)
+ }
+ var turns int
+ if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_usage WHERE role <> 'check'").Scan(&turns); err != nil || turns != 0 {
+ t.Fatalf("a turn ran: %d %v", turns, err)
+ }
+}
+
// until polls cond (it reads files and rows, which send no events).
func until(t *testing.T, what string, cond func() bool) {
t.Helper()
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go
index 7413aa8c..1b3c3747 100644
--- a/internal/runner/thin/run.go
+++ b/internal/runner/thin/run.go
@@ -167,13 +167,28 @@ func Run(ctx context.Context, c runner.Config, o Options) error {
tools := &bridge{State: state, Link: link, Forge: fg, Clones: clones, Index: index, Logger: o.Logger, SessionRoot: o.Claude.SessionRoot, Activity: link.Activity}
o.Claude.Tools, o.Claude.Catalog = tools.Call, index.Catalog
conns := &Conns{Runner: c, State: state, Logger: o.Logger, Refresh: o.Claude.Refresh, LockWait: o.Claude.LockWait}
- // A token check is a real request; its usage counts like any other.
+ // A token check is a real request; its usage counts like any other,
+ // and the rate limit the provider reported on it is recorded as a
+ // turn's is: headroom, or limited until its reset. Not for a refused
+ // token, which is no connection.
conns.Verify = func(ctx context.Context, b runner.AccountBinding) error {
- rows, err := o.Claude.CheckToken(ctx, b)
- if rerr := state.ReportCheck(context.Background(), rows); rerr != nil && o.Logger != nil {
+ res, err := o.Claude.CheckToken(ctx, b)
+ if res.Seen != nil && !errors.Is(err, provider.ErrLoginRequired) {
+ if res.Seen.Limited {
+ conns.Limit(b.ID, *res.Seen)
+ } else {
+ conns.Observe(b.ID, *res.Seen, "")
+ }
+ }
+ if rerr := state.ReportCheck(context.Background(), res.Rows); rerr != nil && o.Logger != nil {
o.Logger.Warn("token check usage", "err", sanitize(rerr))
}
- link.Notify()
+ if res.Seen != nil {
+ // The headroom goes with the next hello, not the next beat.
+ link.HelloSoon()
+ } else {
+ link.Notify()
+ }
return err
}
engine := &Engine{State: state, Conns: conns, Logger: o.Logger, Emit: link.Delta, Act: link.Activity, Notify: link.Notify, Authorize: link.Confirm, Open: func(person string, b runner.AccountBinding) (Coordinator, error) {
diff --git a/internal/runner/thin/tokencheck.go b/internal/runner/thin/tokencheck.go
index 6e295eea..e12dab5f 100644
--- a/internal/runner/thin/tokencheck.go
+++ b/internal/runner/thin/tokencheck.go
@@ -31,65 +31,78 @@ const (
// stream). It proves nothing about the token.
var errCheckFailed = errors.New("the token check did not finish")
+// TokenCheck is what one check learned: its usage rows, whatever the
+// end, and the last rate limit the provider reported on it (nil: none),
+// read from rate_limit_event as a turn reads it.
+type TokenCheck struct {
+ Rows []wire.Usage
+ Seen *connect.Limit
+}
+
// CheckToken runs one check. nil: the provider answered (a quota refusal
// answers too: the token is good, the account busy). ErrLoginRequired:
-// the provider refused the token. Rows are its usage, whatever the end.
-func (o ClaudeOptions) CheckToken(ctx context.Context, b runner.AccountBinding) ([]wire.Usage, error) {
+// the provider refused the token.
+func (o ClaudeOptions) CheckToken(ctx context.Context, b runner.AccountBinding) (TokenCheck, error) {
+ rows, seen, err := o.checkToken(ctx, b)
+ return TokenCheck{Rows: rows, Seen: seen}, err
+}
+
+func (o ClaudeOptions) checkToken(ctx context.Context, b runner.AccountBinding) ([]wire.Usage, *connect.Limit, error) {
o.defaults()
if b.Provider != wire.ProviderClaude || b.Kind != wire.KindToken || o.Manager == nil {
- return nil, provider.ErrPolicy
+ return nil, nil, provider.ErrPolicy
}
ctx, cancel := context.WithTimeout(ctx, tokenCheckLimit)
defer cancel()
direct, err := o.Runner.DirectBinding(b)
if err != nil {
- return nil, err
+ return nil, nil, err
}
lease, err := provider.OpenRuntimeCopy(ctx, direct, o.Refresh, o.LockWait)
if err != nil {
- return nil, err
+ return nil, nil, err
}
defer lease.Close()
binding := lease.Binding()
scratch, err := os.MkdirTemp(o.Runner.ScratchRoot, "policy-")
if err != nil {
- return nil, err
+ return nil, nil, err
}
defer os.RemoveAll(scratch)
// An empty workspace: the check reads nothing, and calls no tool.
work, err := os.MkdirTemp(o.SessionRoot, "check-")
if err != nil {
- return nil, err
+ return nil, nil, err
}
defer os.RemoveAll(work)
tool, err := openToolSocket(context.Background(), o.Runner.StateDir, func(context.Context, string, string, json.RawMessage) (string, bool) { return toolNoTurn, true })
if err != nil {
- return nil, err
+ return nil, nil, err
}
defer tool.Close()
sel := provider.Selection{ConnectionID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, AccountID: b.AccountID}
in, err := runner.PolicyInputs(ctx, o.Runner, sel, binding, work, "converse", scratch)
if err != nil {
- return nil, err
+ return nil, nil, err
}
session := uuid()
in.Argv = append(in.Argv, "--session-id", session)
policy, err := provider.BuildPolicy(binding, in)
if err != nil {
- return nil, err
+ return nil, nil, err
}
if claude.ExecutableDigest(policy) != o.Digest {
- return nil, provider.ErrVersion
+ return nil, nil, provider.ErrVersion
}
if err = lease.CheckCopy(ctx); err != nil {
- return nil, err
+ return nil, nil, err
}
launch := provider.Launch{ToolSocket: tool.Path, AttemptKey: "check/" + uuid(), Workspace: work, Selection: sel, Binding: binding, Policy: policy}
pctx, kill := context.WithCancel(context.Background())
defer kill()
proc, err := o.Manager.StartRecorded(pctx, launch, in.Argv, nil)
if err != nil {
- return nil, err
+ return nil, nil, err
}
// The namespace is killed at the limit (which ends the reads below)
// and at the end; its exit is observed and its record released before
@@ -112,11 +125,14 @@ func (o ClaudeOptions) CheckToken(ctx context.Context, b runner.AccountBinding)
_, err = proc.Stdin().Write(raw)
}
if err != nil {
- return nil, firstErr(ctx.Err(), errCheckFailed)
+ return nil, nil, firstErr(ctx.Err(), errCheckFailed)
}
scan := bufio.NewScanner(proc.Stdout())
scan.Buffer(make([]byte, 0, 64<<10), claude.MaxFrameBytes)
signal := ""
+ // seen is the last rate limit the provider reported, read as a turn
+ // reads it (claude.go).
+ var seen *connect.Limit
for scan.Scan() {
events, err := claude.Decode(scan.Bytes())
if len(scan.Bytes()) > 0 && err != nil {
@@ -126,6 +142,12 @@ func (o ClaudeOptions) CheckToken(ctx context.Context, b runner.AccountBinding)
if sig := connect.ClaudeSignal(ev.Payload); sig != "" {
signal = sig
}
+ if ev.Kind == "rate_limit_event" {
+ if l, ok := connect.ClaudeRateLimit(ev.Payload); ok {
+ seen = &l
+ }
+ continue
+ }
if ev.Kind != "turn.completed" && ev.Kind != "turn.failed" {
continue
}
@@ -134,17 +156,22 @@ func (o ClaudeOptions) CheckToken(ctx context.Context, b runner.AccountBinding)
if !ok || res.Failed {
outcome = wire.OutcomeFailed
}
+ if outcome == wire.OutcomeFailed && signal == connect.FailQuota && (seen == nil || !seen.Limited) {
+ // Rate-limit retries ran out: quota, no reset reported.
+ seen = &connect.Limit{Limited: true}
+ }
rows := usageRows(connect.ClaudeRows(ev.Payload), b, 1, outcome)
switch {
case signal == connect.FailAuth:
- return rows, provider.ErrLoginRequired
- case outcome == wire.OutcomeReplied, signal == connect.FailQuota:
- return rows, nil
+ return rows, nil, provider.ErrLoginRequired
+ case outcome == wire.OutcomeReplied, signal == connect.FailQuota, seen != nil && seen.Limited:
+ // A rejected rate limit is the provider's answer too.
+ return rows, seen, nil
}
- return rows, errCheckFailed
+ return rows, seen, errCheckFailed
}
}
- return nil, firstErr(ctx.Err(), errCheckFailed)
+ return nil, nil, firstErr(ctx.Err(), errCheckFailed)
}
// ReportCheck queues a check's usage for the instance (durable).