Merge branch 'claude-usage-refresh' into main
Refresh Claude usage without a turn; show plan and reading age Claude logins read usage from the CLI's own /api/oauth/usage endpoint hourly and on Check again. Connections rows show the plan (Max plan) and how old each reading is. 403/404 mark usage unavailable for a week or until the token changes; 401 and other errors retry. Protocol 20.
31 files changed,
+822
−45
.rastrillo/budgets.txt+4 −4docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+60 −2internal/equipo/claude_usage_test.go+48 −0internal/equipo/connections_view.go+9 −3internal/equipo/copy.go+1 −0internal/equipo/templates/models.html+1 −1internal/equipo/usage_page.go+13 −6internal/runner/provider/claude_oauth.go+27 −0internal/runner/provider/claude_status_test.go+51 −0internal/runner/provider/login_probe.go+24 −4internal/runner/provider/reading_test.go+2 −2internal/runner/thin/claude_usage.go+152 −0internal/runner/thin/claude_usage_test.go+260 −0internal/runner/thin/conns.go+43 −4internal/runner/thin/link.go+2 −1internal/runner/thin/readings.go+1 −2internal/runner/thin/run.go+6 −2internal/runner/thin/state.go+1 −1internal/wire/assistant_test.go+2 −2internal/wire/claude_usage.go+40 −0internal/wire/claude_usage_test.go+42 −0internal/wire/connections.go+4 −2internal/wire/mixed_protocol_test.go+1 −1internal/wire/models_test.go+1 −1internal/wire/opencode_test.go+1 −1internal/wire/publish_test.go+1 −1internal/wire/runners.go+8 −2internal/wire/runners_test.go+1 −1internal/wire/schedule_test.go+1 −1internal/wire/usage_test.go+1 −1scripts/runner-reference-allowlist.json+14 −0
CI passed — run details
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index ede727ab..9ef687b0 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -14,8 +14,8 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr |
| time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI. |
| time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage. |
| -size internal/equipo 19439 - The instance web layer: pages, handlers, templates and every screen's copy, the Assistant's and the models list included, and provider wiring. Measured 19439 source lines. |
| -size internal/wire 5966 - The runner and person API protocol: every frame, resource and downgrade up to protocol 19 (18 models, 19 the Assistant), one package so Encode sees every type. Measured 5966 source lines. |
| +size internal/equipo 19453 - Web pages, handlers, templates and runtime copy. Connections now shares Usage plan and age labels. Measured 19453 source lines. |
| +size internal/wire 6014 - Runner and person API types stay together for Encode. Protocol 20 adds Claude usage flags and their downgrade. Measured 6014 source lines. |
| size internal/equipotest - 13400 Task 21 repairs historical migration and conversation fixtures after Plan 3. Measured 13024 test lines; the 300s time ceiling is unchanged. |
| time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded); |
| time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s). |
| @@ -26,7 +26,7 @@ time internal/runner/provider/claude 45s Task 5 measured 32.430s for fake CLI se |
| time internal/runner/provider/codex 35s Plan 3 CI repair measured 24.464s for the full package (controller CI 27.908s). |
| time internal/runner/provider/pi 60s The real pinned Pi in bubblewrap against a fake TensorX: probes P1 to P5 (a hundred RPC turns), the hostile repository, and the pinned tree checked whole (about 160 MB); measured 22s locally. |
| time internal/runner/provider/opencode 90s The real pinned OpenCode in bubblewrap against a fake Go: probes, the hostile repository per source, termination, resume; the 260 MB binary hashed per launch. Measured 40s. |
| -size internal/runner/provider 5143 - Provider seams and every launch policy, Pi's and OpenCode's, which share the unexported manifest and pin helpers. The assist launch action added 15. Measured 5143 source lines. |
| +size internal/runner/provider 5190 - Provider policies share manifest and pin helpers. Adds Claude status plan and access to a validated OAuth copy. Measured 5190 source lines. |
| time internal/plan3test 300s Initial cap for combined browser and runner acceptance; measure at both usable stops. |
| @@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full |
| perf GET /releases/* skip Verified runner release file downloads, not browser GET screens. |
| perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen. |
| time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s; |
| -size internal/runner/thin 24005 16312 The thin runner: steps, link, the coordinator and the Assistant, Mac worker, previews, merges, metered models, Research, scheduler, site host, OpenCode. Measured 24005 source, 16312 test lines. |
| +size internal/runner/thin 24200 16572 Runner state, connections and execution share internal helpers. Adds Claude OAuth usage and refusal tests. Measured 24200 source, 16572 test lines. |
| time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes. |
| time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing. |
| time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s). |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index e83b783c..8a5ae658 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -6183,8 +6183,9 @@ records remain unchanged. |
| | `usage.lede` | What can run now, what it costs, and where the tokens went. | Usage S4: the page's lede under the title | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) | |
| | `usage.advice` | Advice | Usage S4: the advice card's label at the top of the page (screen readers) | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) | |
| | `usage.now` | Available now | Usage S4: heading of the availability part | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) | |
| -| `usage.reading.as_of` | as of %s | Usage S4, ruling #7: a Codex reading's age after its meters and on a held step's line; %s is how long ago (2 h ago); Codex refreshes without a model turn | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) | |
| -| `usage.reading.last_reported` | last reported %s | Usage S4, ruling #7: a Claude reading's age; %s is how long ago; Claude reports headroom only on a turn | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) | |
| +| `usage.reading.as_of` | as of %s | Usage S4, ruling #7: a fetched reading's age after its meters and on a held step's line; %s is how long ago (2 h ago); Codex and Claude OAuth usage refresh without a model turn | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) | |
| +| `usage.reading.last_reported` | last reported %s | Usage S4, ruling #7: a Claude reading's age; %s is how long ago; used for Claude turn readings, including older runners | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) | |
| +| `usage.reading.unavailable` | Usage not available for this sign-in | Claude OAuth usage refused with 401, 403 or 404; shown beside any last reading on Connections and Usage | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) | |
| | `usage.reading.none` | Remaining usage not reported | Usage S4: a ready subscription whose provider reported no headroom | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) | |
| | `usage.no_connections` | Nothing is connected yet. | Usage S4: availability with nothing connected; followed by the Add a connection link | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) | |
| | `usage.connect` | Add a connection | Usage S4: link to Add a connection when nothing is connected | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) | |
| @@ -7524,3 +7525,60 @@ coordinator's published, unconfirmed, failed and name-taken lines, the |
| publish step's timeline lines and its stop reasons) in copy review |
| jadya3tfrmkf7t3ym2nqhpgira and approved every one unchanged. Rows |
| above, COPY APPROVED (Paul, 2026-11-12, copy-review jadya3tfrmkf7t3ym2nqhpgira, unchanged); copy.go matches. |
| + |
| + |
| +## Claude usage refresh (2026-11-13) |
| + |
| +Normal Claude OAuth logins now read usage during the hourly local status pass |
| +and on Check again. The same status pass reads the CLI's subscription type. |
| +Connections and Usage share the plan label and reading-age code. Setup-token |
| +connections are excluded. A refused usage endpoint does not revoke the login. |
| + |
| +The pinned Claude Code 2.1.312 binary matches SHA-256 |
| +`4f4178ce41d83e23341ebfbaecdbcf8ea6bf7baea0690025abe49eeec3a5d01d`. |
| +Its /usage loader calls JO at byte 263017232. The plain path is selected at |
| +246565477; the GET is at 246565833; the response schema is at 246583562. |
| +The request uses the existing profile SafeClient, api.anthropic.com only, |
| +and equipo-runner/<version>. Only the status is logged. Full source citations |
| +are in `internal/runner/thin/claude_usage.go`. |
| + |
| +Protocol 20 follows main's 19. Downgrades and the initial hello omit fetched |
| +and unavailable flags. Existing windows, plans and reading times keep their |
| +previous wire representation. Local size allowances increased by the measured |
| +addition; package boundaries and time allowances stay unchanged. |
| + |
| +Tests were written first and failed before implementation. The targeted |
| +runner/provider/wire/page command passed after implementation: |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/runner/thin ./internal/runner/provider ./internal/wire ./internal/equipo -run '^Test(Claude(Usage|StatusPlan|OAuthToken|ConnectionsPlan)|HandshakeHelloWithholds(UsageRefresh|ReadingTimes)|TokenProfile|TokenRejectionSurvivesHourlyCheck|TokenHourlyPassBeforeTheCheck|CodexReadingInProduction|ScheduleRefreshUsesReadingTime|UsagePage|Connections|Encode|Without|Protocol|Spoken|Mixed)' -count=1 |
| +``` |
| + |
| +Mutation checks below each failed with an assertion, then the original code |
| +was restored. The targeted command above passed again after restoration. |
| + |
| +- token-log: DETECTED. `CGO_ENABLED=0 go test ./internal/runner/thin -run ^TestClaudeUsageRefresh$/^200$ -count=1` |
| +- percent-scale: DETECTED. `CGO_ENABLED=0 go test ./internal/runner/thin -run ^TestClaudeUsageRefresh$/^200$ -count=1` |
| +- no-backoff: DETECTED. `CGO_ENABLED=0 go test ./internal/runner/thin -run ^TestClaudeUsageRefresh$/^403$ -count=1` |
| +- ignore-token-change: DETECTED. `CGO_ENABLED=0 go test ./internal/runner/thin -run ^TestClaudeUsageRefresh$/^401$ -count=1` |
| +- no-reading-time: DETECTED. `CGO_ENABLED=0 go test ./internal/runner/thin -run ^TestClaudeUsageRefresh$/^200$ -count=1` |
| +- drop-plan: DETECTED. `CGO_ENABLED=0 go test ./internal/runner/provider -run ^TestClaudeStatusPlan$ -count=1` |
| +- leak-wire-field: DETECTED. `CGO_ENABLED=0 go test ./internal/wire -run ^TestClaudeUsageProtocol20$ -count=1` |
| +- hide-age: DETECTED. `CGO_ENABLED=0 go test ./internal/equipo -run ^TestClaudeConnectionsPlanAndReadingAge$ -count=1` |
| +- stale-on-failure: DETECTED. `CGO_ENABLED=0 go test ./internal/runner/thin -run ^TestClaudeUsageKeepsLastReading$ -count=1` |
| + |
| +`make budget`, `scripts/runner-dead-references.py`, `make lanes-check` and |
| +`make copy-release-check` passed. Hosted CI runs the full suites. No live |
| +provider request, merge or deployment was made during this task. |
| + |
| +COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13): the new unavailable notice |
| +was reviewed for accuracy, plain wording and house style. Existing plan and |
| +age strings are reused. The new string is in the Plan 3 inventory and copy.go. |
| + |
| + |
| +The first hosted run found a numeric HTTP status in the redirect fixture and |
| +budget explanations over 200 bytes. Both were corrected. It also exposed an |
| +existing race in the Codex reading fixture: the probe could stop the fake CLI |
| +after its answer but before its marker write. The fixture now writes its |
| +marker before answering. The failed hosted test is the reproduction; the |
| +same targeted test passes repeatedly after the ordering fix. |
diff --git a/internal/equipo/claude_usage_test.go b/internal/equipo/claude_usage_test.go| new file mode 100644 |
| index 00000000..61bee4cd |
| --- /dev/null |
| +++ b/internal/equipo/claude_usage_test.go |
| @@ -0,0 +1,48 @@ |
| +package equipo |
| + |
| +import ( |
| + "bytes" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +func TestClaudeConnectionsPlanAndReadingAge(t *testing.T) { |
| + cs := usageConns()[:2] |
| + cs[1].Plan = "max" |
| + for _, fetched := range []bool{false, true} { |
| + cs[1].Headroom.Fetched = fetched |
| + v := connectionsPage(wire.Snapshot{Connections: cs}, nil, wire.Preferences{}, "r1", nil, usageNow) |
| + var row connRow |
| + for _, r := range v.Rows { |
| + if r.ID == "cn_cl" { |
| + row = r |
| + } |
| + } |
| + if row.Plan != "Max plan" || row.Age != readingAge(cs[1], usageNow) || row.Age == "" { |
| + t.Fatalf("row %+v", row) |
| + } |
| + if fetched && !strings.HasPrefix(row.Age, "as of ") { |
| + t.Fatal(row.Age) |
| + } |
| + var out bytes.Buffer |
| + if err := pages["models"].ExecuteTemplate(&out, "content", pageData{Models: v}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !strings.Contains(out.String(), "data-reading-age>"+row.Age) { |
| + t.Fatal("reading age missing from HTML") |
| + } |
| + } |
| + cs[1].Headroom.Unavailable = true |
| + usage := usagePage(cs, connLabels(cs, nil), wire.UsageTotals{}, wire.UsageTotals{}, nil, usageNow) |
| + if usage.Plans[1].Plan != "Max plan" || usage.Available[1].Note != "Usage not available for this sign-in" { |
| + t.Fatalf("usage page: %+v", usage) |
| + } |
| + v := connectionsPage(wire.Snapshot{Connections: cs}, nil, wire.Preferences{}, "r1", nil, usageNow) |
| + for _, r := range v.Rows { |
| + if r.ID == "cn_cl" && r.UsageNote != "Usage not available for this sign-in" { |
| + t.Fatalf("note %q", r.UsageNote) |
| + } |
| + } |
| +} |
diff --git a/internal/equipo/connections_view.go b/internal/equipo/connections_view.go| index 0e040418..7bc45284 100644 |
| --- a/internal/equipo/connections_view.go |
| +++ b/internal/equipo/connections_view.go |
| @@ -22,8 +22,8 @@ import ( |
| type connRow struct { |
| // Label is the account the provider named (the success card's); |
| // Tag is the connection's label as every page says it. |
| - ID, Provider, Name, Glyph, Label, Plan string |
| - Tag chat.ConnLabel |
| + ID, Provider, Name, Glyph, Label, Plan, Age string |
| + Tag chat.ConnLabel |
| // Kind is the connection's (token: a pasted setup token); Expires |
| // says when its token expires, Renew asks for a new one near then. |
| Kind, Expires string |
| @@ -190,7 +190,7 @@ func connectionsPage(snap wire.Snapshot, today map[string]int64, prefer wire.Pre |
| } |
| work := workOn(snap, answerable, coord) |
| for _, c := range held { |
| - row := connRow{ID: c.ID, Provider: c.Provider, Name: providerName(c.Provider), Glyph: providerGlyph(c.Provider), Label: c.Label, Tag: chat.LabelOf(labels, c), Plan: c.Plan, Kind: c.Kind, State: c.State, Usage: tokensText(today[c.LocalID]), PreferRevision: prefer.Revision} |
| + row := connRow{ID: c.ID, Provider: c.Provider, Name: providerName(c.Provider), Glyph: providerGlyph(c.Provider), Label: c.Label, Tag: chat.LabelOf(labels, c), Plan: planLabel(c.Plan), Kind: c.Kind, State: c.State, Usage: tokensText(today[c.LocalID]), PreferRevision: prefer.Revision} |
| _, row.UsageTail, _ = strings.Cut(copyText("chat.connections.usage_today"), "%s") |
| if c.State == wire.ConnError { |
| row.State = wire.ConnSignInAgain |
| @@ -203,6 +203,12 @@ func connectionsPage(snap wire.Snapshot, today map[string]int64, prefer wire.Pre |
| row.Meters = append(row.Meters, m) |
| } |
| } |
| + if len(row.Meters) > 0 { |
| + row.Age = readingAge(c, now) |
| + } |
| + if c.Headroom != nil && c.Headroom.Unavailable { |
| + row.UsageNote = copyText("usage.reading.unavailable") |
| + } |
| // The status and a meter do not both say when: the meter does. |
| row.Words = connectionState(c, now, metered) |
| if c.State == wire.ConnLimited && !metered && c.Headroom != nil && c.Headroom.ResetsAt != nil { |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index c5db7f2d..aa05bc73 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -998,6 +998,7 @@ var pageCopy = map[string]string{ |
| "usage.now": "Available now", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) |
| "usage.reading.as_of": "as of %s", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) |
| "usage.reading.last_reported": "last reported %s", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) |
| + "usage.reading.unavailable": "Usage not available for this sign-in", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) |
| "usage.reading.none": "Remaining usage not reported", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) |
| "usage.no_connections": "Nothing is connected yet.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) |
| "usage.connect": "Add a connection", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-12) |
diff --git a/internal/equipo/templates/models.html b/internal/equipo/templates/models.html| index cd3534d9..3bf9979c 100644 |
| --- a/internal/equipo/templates/models.html |
| +++ b/internal/equipo/templates/models.html |
| @@ -81,7 +81,7 @@ |
| {{template "conn-mark" .Provider}} |
| <div equipo-conn-body id="connection-{{.ID}}"> |
| <p equipo-conn-head><span equipo-conn-name>{{.Name}}</span><span equipo-conn-account data-conn-label="{{.Tag.Text}}">{{template "conn-account" .Tag}}{{with .Plan}}, {{.}}{{end}}</span>{{if .Preferred}}<span equipo-conn-pref>{{icon "star"}}{{copy "chat.connections.preferred"}}</span>{{end}}</p> |
| -<p equipo-conn-facts><span equipo-conn-state data-connection-state data-s="{{.State}}"{{with .WordsAt}} title="{{.}}"{{end}}>{{.Words}}</span>{{with .Expires}}<span equipo-conn-expires data-token-expires>{{.}}</span>{{end}}{{range .Meters}}<span equipo-conn-meter data-level="{{.Level}}"{{with .At}} title="{{.}}"{{end}}><span equipo-conn-bar><i data-w="{{.Used}}"></i></span><span>{{.Name}} <b>{{.Used}}%</b>{{with .Resets}}, {{.}}{{end}}</span></span>{{end}}{{with .UsageNote}}<span equipo-conn-usage-note data-usage-note>{{.}}</span>{{end}}</p> |
| +<p equipo-conn-facts><span equipo-conn-state data-connection-state data-s="{{.State}}"{{with .WordsAt}} title="{{.}}"{{end}}>{{.Words}}</span>{{with .Expires}}<span equipo-conn-expires data-token-expires>{{.}}</span>{{end}}{{range .Meters}}<span equipo-conn-meter data-level="{{.Level}}"{{with .At}} title="{{.}}"{{end}}><span equipo-conn-bar><i data-w="{{.Used}}"></i></span><span>{{.Name}} <b>{{.Used}}%</b>{{with .Resets}}, {{.}}{{end}}</span></span>{{end}}{{with .Age}}<span equipo-conn-usage-note data-reading-age>{{.}}</span>{{end}}{{with .UsageNote}}<span equipo-conn-usage-note data-usage-note>{{.}}</span>{{end}}</p> |
| {{if .Metered}}{{template "conn-metered-row" .}}{{end}} |
| {{if .AskEmail}}<details equipo-conn-email data-account-email="{{.ID}}"{{if .AskOpen}} open{{end}}><summary>{{if .Stated}}{{copy "chat.connections.email_change"}}{{else}}{{copy "chat.connections.email_add"}}{{end}}</summary><form method="post" action="/conversation/connections/{{.ID}}/email" equipo-conn-token data-email-form autocomplete="off"><label for="email-{{.ID}}">{{copy "chat.connections.email_ask"}}</label><span equipo-conn-token-row><input rst-input id="email-{{.ID}}" type="email" name="email" maxlength="254" value="{{.Stated}}" autocapitalize="off" spellcheck="false" data-email-field><button rst-btn type="submit" data-email-save>{{copy "form.save"}}</button></span><span equipo-conn-small>{{copy "chat.connections.email_hint"}}</span><span equipo-conn-small data-email-note role="status" hidden data-bad="{{copy "chat.connections.email_bad"}}" data-tone="bad"></span></form></details>{{end}} |
| {{if .Renew}}<div equipo-conn-renew data-token-renew>{{copy "chat.connections.token_renew"}} <form method="post" action="/conversation/connections" data-add-form equipo-inline-form><input type="hidden" name="provider" value="{{.Provider}}"><button equipo-link type="submit" data-renew>{{copy "chat.connections.sign_in_again_action"}}</button></form></div>{{end}} |
diff --git a/internal/equipo/usage_page.go b/internal/equipo/usage_page.go| index a0f6188a..e61df974 100644 |
| --- a/internal/equipo/usage_page.go |
| +++ b/internal/equipo/usage_page.go |
| @@ -77,15 +77,13 @@ type usageRowView struct { |
| ID, Label, Input, Cached, Output, Estimate string |
| } |
| -// readingAge is a reading's age in words: Codex's is refreshed without a |
| -// turn ("as of 2 h ago"), Claude's only when a turn reports it ("as last |
| -// reported 2 h ago"); nothing when the runner did not say when. |
| +// readingAge uses the reading's source and time, never the row update time. |
| func readingAge(c wire.Connection, now time.Time) string { |
| if c.Headroom == nil || c.Headroom.CheckedAt == nil { |
| return "" |
| } |
| key := "usage.reading.as_of" |
| - if c.Provider == wire.ProviderClaude { |
| + if c.Provider == wire.ProviderClaude && !c.Headroom.Fetched { |
| key = "usage.reading.last_reported" |
| } |
| return fmt.Sprintf(copyText(key), ago(now, *c.Headroom.CheckedAt)) |
| @@ -229,8 +227,9 @@ func usagePage(conns []wire.Connection, labels map[string]chat.ConnLabel, totals |
| u.Note = copyText("usage.reading.none") |
| } |
| p := usagePlan{Tag: tag, ID: c.ID, Name: tag.Text, Tokens: fmt.Sprintf(copyText("usage.plan_tokens"), tokenCount(monthly[c.ID].Input+monthly[c.ID].Output))} |
| - if c.Plan != "" { |
| - p.Plan = fmt.Sprintf(copyText("usage.plan"), strings.ToUpper(c.Plan[:1])+c.Plan[1:]) |
| + p.Plan = planLabel(c.Plan) |
| + if c.Headroom != nil && c.Headroom.Unavailable { |
| + u.Note = copyText("usage.reading.unavailable") |
| } |
| v.Plans = append(v.Plans, p) |
| } |
| @@ -337,3 +336,11 @@ func (a *application) usageAdvice(act bool) http.HandlerFunc { |
| }) |
| } |
| } |
| + |
| +// planLabel is shared by Connections and Usage. |
| +func planLabel(plan string) string { |
| + if plan == "" { |
| + return "" |
| + } |
| + return fmt.Sprintf(copyText("usage.plan"), strings.ToUpper(plan[:1])+plan[1:]) |
| +} |
diff --git a/internal/runner/provider/claude_oauth.go b/internal/runner/provider/claude_oauth.go| new file mode 100644 |
| index 00000000..885b29ff |
| --- /dev/null |
| +++ b/internal/runner/provider/claude_oauth.go |
| @@ -0,0 +1,27 @@ |
| +package provider |
| + |
| +import "encoding/json" |
| + |
| +// ClaudeOAuthToken reads only the validated runtime copy, never an ambient |
| +// login or keychain. The caller clears the returned bytes after the request. |
| +func (l *AccountLease) ClaudeOAuthToken() ([]byte, error) { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + if l.closed || l.source.Provider != "claude" || l.source.Token { |
| + return nil, ErrPolicy |
| + } |
| + raw, err := l.runtimeSnapshot() |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer clear(raw) |
| + var v struct { |
| + OAuth struct { |
| + AccessToken string `json:"accessToken"` |
| + } `json:"claudeAiOauth"` |
| + } |
| + if json.Unmarshal(raw, &v) != nil || !ValidToken([]byte(v.OAuth.AccessToken)) { |
| + return nil, ErrPolicy |
| + } |
| + return []byte(v.OAuth.AccessToken), nil |
| +} |
diff --git a/internal/runner/provider/claude_status_test.go b/internal/runner/provider/claude_status_test.go| new file mode 100644 |
| index 00000000..17161022 |
| --- /dev/null |
| +++ b/internal/runner/provider/claude_status_test.go |
| @@ -0,0 +1,51 @@ |
| +package provider |
| + |
| +import ( |
| + "context" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| +) |
| + |
| +func TestClaudeStatusPlan(t *testing.T) { |
| + home := t.TempDir() |
| + bin := filepath.Join(home, "claude") |
| + script := `#!/bin/sh |
| +case "$*" in |
| + '--version') echo '2.1.312 (Claude Code)';; |
| + 'auth login --help') exit 0;; |
| + 'auth status --json') echo '{"loggedIn":true,"authMethod":"claude.ai","email":"a@example.com","subscriptionType":"max"}';; |
| + *) exit 99;; |
| +esac |
| +` |
| + if err := os.WriteFile(bin, []byte(script), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + id, plan, err := ReadClaudeStatus(context.Background(), Binding{Home: home, Provider: "claude"}, LoginOptions{ClaudePath: bin}) |
| + if err != nil || plan != "max" || id.AccountID != "a@example.com" { |
| + t.Fatalf("%+v %q %v", id, plan, err) |
| + } |
| +} |
| + |
| +func TestClaudeOAuthTokenFromLease(t *testing.T) { |
| + b, rules := accountFixture(t) |
| + b.Provider = "claude" |
| + writeFake(t, filepath.Join(b.Home, ".credentials.json"), `{"claudeAiOauth":{"accessToken":"fixture-private"}}`) |
| + l := openFixture(t, b, rules) |
| + token, err := l.ClaudeOAuthToken() |
| + if err != nil || string(token) != "fixture-private" { |
| + t.Fatal("missing lease token", err) |
| + } |
| + clear(token) |
| + // The read must come from the checked runtime copy, not a changed source. |
| + writeFake(t, filepath.Join(b.Home, ".credentials.json"), `{"claudeAiOauth":{"accessToken":"changed-source"}}`) |
| + token, err = l.ClaudeOAuthToken() |
| + if err != nil || string(token) != "fixture-private" { |
| + t.Fatal("read source instead of lease") |
| + } |
| + clear(token) |
| + l.Close() |
| + if _, err = l.ClaudeOAuthToken(); err == nil { |
| + t.Fatal("closed lease exposed token") |
| + } |
| +} |
diff --git a/internal/runner/provider/login_probe.go b/internal/runner/provider/login_probe.go| index d3f4d983..fc9aec2a 100644 |
| --- a/internal/runner/provider/login_probe.go |
| +++ b/internal/runner/provider/login_probe.go |
| @@ -33,7 +33,7 @@ func RefreshLogin(ctx context.Context, b Binding, options LoginOptions) (Identit |
| } |
| func (d *terminalLoginDriver) probe(ctx context.Context, b Binding, refresh bool) (Identity, error) { |
| - return d.probeReading(ctx, b, refresh, nil) |
| + return d.probeReading(ctx, b, refresh, nil, nil) |
| } |
| // ReadCodexLimits is the reading probe for a Codex home (connectors spec |
| @@ -48,7 +48,7 @@ func ReadCodexLimits(ctx context.Context, b Binding, options LoginOptions) (Iden |
| return Identity{}, nil, ErrLoginUnavailable |
| } |
| var limits json.RawMessage |
| - id, err := (&terminalLoginDriver{options: options}).probeReading(ctx, b, false, &limits) |
| + id, err := (&terminalLoginDriver{options: options}).probeReading(ctx, b, false, &limits, nil) |
| if err != nil { |
| return Identity{}, nil, err |
| } |
| @@ -57,7 +57,7 @@ func ReadCodexLimits(ctx context.Context, b Binding, options LoginOptions) (Iden |
| // probeReading is probe, and for a Codex home with limits set, the |
| // account's rate limits read after its identity. |
| -func (d *terminalLoginDriver) probeReading(ctx context.Context, b Binding, refresh bool, limits *json.RawMessage) (Identity, error) { |
| +func (d *terminalLoginDriver) probeReading(ctx context.Context, b Binding, refresh bool, limits *json.RawMessage, plan *string) (Identity, error) { |
| if b.provenance != nil { |
| return Identity{}, ErrPolicy |
| } |
| @@ -103,7 +103,16 @@ func (d *terminalLoginDriver) probeReading(ctx context.Context, b Binding, refre |
| } |
| return Identity{}, ErrLoginUnavailable |
| } |
| - return ClaudeLoginIdentity(out.Bytes()) |
| + id, err := ClaudeLoginIdentity(out.Bytes()) |
| + if err == nil && plan != nil { |
| + var status struct { |
| + SubscriptionType string `json:"subscriptionType"` |
| + } |
| + if json.Unmarshal(out.Bytes(), &status) == nil { |
| + *plan = status.SubscriptionType |
| + } |
| + } |
| + return id, err |
| } |
| if b.Provider != "codex" { |
| return Identity{}, ErrIdentity |
| @@ -257,3 +266,14 @@ func refreshRevoked(raw []byte) bool { |
| } |
| return false |
| } |
| + |
| +// ReadClaudeStatus returns the subscription reported by auth status separately |
| +// from identity: a plan change must never invalidate a connection's identity. |
| +func ReadClaudeStatus(ctx context.Context, b Binding, options LoginOptions) (Identity, string, error) { |
| + if b.Provider != "claude" || b.Token { |
| + return Identity{}, "", ErrPolicy |
| + } |
| + var plan string |
| + id, err := (&terminalLoginDriver{options: options}).probeReading(ctx, b, true, nil, &plan) |
| + return id, plan, err |
| +} |
diff --git a/internal/runner/provider/reading_test.go b/internal/runner/provider/reading_test.go| index 21d8d1c2..d749a883 100644 |
| --- a/internal/runner/provider/reading_test.go |
| +++ b/internal/runner/provider/reading_test.go |
| @@ -35,8 +35,8 @@ echo '{"id":"2","result":{"account":{"type":"chatgpt","email":"fixture@example.i |
| IFS= read -r line |
| case "$line" in *'"account/rateLimits/read"'*) ;; *) echo "$line" > "$HOME/other"; exit 25;; esac |
| echo '{"method":"account/rateLimits/updated","params":{"rateLimits":{}}}' |
| -echo '{"id":"3","result":{"rateLimits":{"primary":{"usedPercent":61,"windowDurationMins":300,"resetsAt":1762941600},"secondary":{"usedPercent":12,"windowDurationMins":10080,"resetsAt":1763287200},"planType":"pro","rateLimitReachedType":null}}}' |
| echo done > "$HOME/read" |
| +echo '{"id":"3","result":{"rateLimits":{"primary":{"usedPercent":61,"windowDurationMins":300,"resetsAt":1762941600},"secondary":{"usedPercent":12,"windowDurationMins":10080,"resetsAt":1763287200},"planType":"pro","rateLimitReachedType":null}}}' |
| IFS= read -r line && echo "$line" > "$HOME/other" |
| exit 0 |
| ` |
| @@ -62,6 +62,6 @@ exit 0 |
| t.Fatalf("the probe sent more: %s", other) |
| } |
| if _, _, err := ReadCodexLimits(context.Background(), Binding{Home: root, Provider: "claude"}, LoginOptions{CodexPath: binary}); err == nil { |
| - t.Fatal("a Claude home was read: Claude has no reading without a turn") |
| + t.Fatal("the Codex probe accepted a Claude home") |
| } |
| } |
diff --git a/internal/runner/thin/claude_usage.go b/internal/runner/thin/claude_usage.go| new file mode 100644 |
| index 00000000..9980edc7 |
| --- /dev/null |
| +++ b/internal/runner/thin/claude_usage.go |
| @@ -0,0 +1,152 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/connect" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// Claude Code 2.1.312, SHA256 claude.ExecutableSHA256, bundled source: |
| +// The /usage loader U calls JO at byte 263017232; JO selects the plain read. |
| +// ce at byte 246565477 selects /api/oauth/usage for the plain read; |
| +// fe at 246565833 calls Gt.get with a 5000 ms timeout and JSON content type. |
| +// Gt at 242750820 calls Hr (242743373); Xm (242741767) selects BASE_API_URL, |
| +// https://api.anthropic.com. DX (242537317) supplies Bearer and anthropic-beta |
| +// oauth-2025-04-20 (_u at 239047067). The schema at 246583562 has nullable utilization (percent) |
| +// and resets_at (ISO time) for five_hour and seven_day windows. |
| +// auth status at 269608610 reports subscriptionType for claude.ai logins. |
| +// The runner uses the profile reader's SafeClient and its own User-Agent. |
| +// No turn, refresh request, redirect, proxy or additional host is involved. |
| +const usagePath = "/api/oauth/usage" |
| + |
| +const usageSchema = ` |
| +CREATE TABLE IF NOT EXISTS conn_usage (id TEXT PRIMARY KEY, mark TEXT NOT NULL, read_at TEXT NOT NULL); |
| +` |
| + |
| +func (p *ProfileReader) readUsage(ctx context.Context, token []byte) (int, *connect.Limit) { |
| + // A release reader cannot send credentials to a configurable origin. |
| + if p.HTTP == nil && p.Origin != ProfileOrigin { |
| + return 0, nil |
| + } |
| + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) |
| + defer cancel() |
| + req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimSuffix(p.Origin, "/")+usagePath, nil) |
| + if err != nil { |
| + return 0, nil |
| + } |
| + req.Header.Set("User-Agent", p.userAgent()) |
| + req.Header.Set("Authorization", "Bearer "+string(token)) |
| + req.Header.Set("anthropic-beta", "oauth-2025-04-20") |
| + req.Header.Set("Content-Type", "application/json") |
| + req.Header.Set("Cache-Control", "no-cache") |
| + res, err := p.client().Do(req) |
| + if err != nil { |
| + return 0, nil |
| + } |
| + defer res.Body.Close() |
| + if res.StatusCode != http.StatusOK { |
| + return res.StatusCode, nil |
| + } |
| + raw, err := io.ReadAll(io.LimitReader(res.Body, maxProfileBytes+1)) |
| + if err != nil || len(raw) > maxProfileBytes { |
| + return res.StatusCode, nil |
| + } |
| + return res.StatusCode, claudeUsage(raw) |
| +} |
| + |
| +func claudeUsage(raw []byte) *connect.Limit { |
| + // Read known windows only; unrelated provider fields have other shapes. |
| + var body map[string]json.RawMessage |
| + if json.Unmarshal(raw, &body) != nil { |
| + return nil |
| + } |
| + h := &wire.Headroom{Fetched: true, Windows: []wire.Window{}} |
| + var used float64 |
| + for _, name := range []string{"five_hour", "seven_day", "seven_day_opus", "seven_day_sonnet"} { |
| + raw, ok := body[name] |
| + if !ok { |
| + continue |
| + } |
| + var w struct { |
| + Utilization *float64 `json:"utilization"` |
| + ResetsAt *time.Time `json:"resets_at"` |
| + } |
| + if json.Unmarshal(raw, &w) != nil { |
| + return nil |
| + } |
| + if w.Utilization == nil { |
| + continue |
| + } |
| + if *w.Utilization < 0 { |
| + return nil |
| + } |
| + minutes := int64(10080) |
| + if name == "five_hour" { |
| + minutes = 300 |
| + } |
| + h.Windows = append(h.Windows, wire.Window{Name: name, UsedPercent: *w.Utilization, Minutes: minutes, ResetsAt: w.ResetsAt}) |
| + used = max(used, *w.Utilization/100) |
| + } |
| + if len(h.Windows) == 0 { |
| + return nil |
| + } |
| + h.Utilization = &used |
| + return &connect.Limit{Headroom: h} |
| +} |
| + |
| +// readClaudeUsage remembers 403/404 refusals for one token for a week; a 401 |
| +// (a stale or revoked token) is retried like a transient error. |
| +func (c *Conns) readClaudeUsage(ctx context.Context, id string, token []byte) { |
| + c.usageMu.Lock() |
| + defer c.usageMu.Unlock() |
| + var mark, at string |
| + err := c.State.db.QueryRowContext(ctx, "SELECT mark, read_at FROM conn_usage WHERE id=?", id).Scan(&mark, &at) |
| + if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| + return |
| + } |
| + tokenMark := profileMark(token) |
| + read, perr := time.Parse(time.RFC3339Nano, at) |
| + if err == nil && mark == tokenMark && perr == nil && c.clock().Before(read.Add(ProfileRetry)) { |
| + return |
| + } |
| + status, l := c.ClaudeUsage.readUsage(ctx, token) |
| + if c.Logger != nil { |
| + c.Logger.Info("claude usage", "status", status) |
| + } |
| + if ctx.Err() != nil { |
| + return |
| + } |
| + if l != nil { |
| + if _, err = c.State.db.ExecContext(ctx, "DELETE FROM conn_usage WHERE id=?", id); err != nil { |
| + return |
| + } |
| + c.Observe(id, *l, "") |
| + c.changed() |
| + return |
| + } |
| + if status != 403 && status != 404 { |
| + return |
| + } |
| + if _, err = c.State.db.ExecContext(ctx, "INSERT INTO conn_usage(id,mark,read_at) VALUES(?,?,?) ON CONFLICT(id) DO UPDATE SET mark=excluded.mark, read_at=excluded.read_at", id, tokenMark, c.clock().UTC().Format(time.RFC3339Nano)); err != nil { |
| + return |
| + } |
| + c.mu.Lock() |
| + cs := c.live[id] |
| + h := wire.Headroom{} |
| + if cs.Headroom != nil { |
| + h = *cs.Headroom |
| + } |
| + h.Unavailable = true |
| + cs.Headroom = &h |
| + c.save(id, cs) |
| + c.mu.Unlock() |
| + c.changed() |
| +} |
diff --git a/internal/runner/thin/claude_usage_test.go b/internal/runner/thin/claude_usage_test.go| new file mode 100644 |
| index 00000000..7ccb7fab |
| --- /dev/null |
| +++ b/internal/runner/thin/claude_usage_test.go |
| @@ -0,0 +1,260 @@ |
| +package thin |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/netip" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/connect" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +func TestClaudeUsageRefresh(t *testing.T) { |
| + for _, status := range []int{200, 401, 403, 404, 500} { |
| + t.Run(fmt.Sprint(status), func(t *testing.T) { |
| + r := newConnectorRig(t) |
| + r.cfg.ScratchRoot = filepath.Join(t.TempDir(), "scratch") |
| + r.conns.Runner = r.cfg |
| + b, _ := r.conns.Binding("codex-1") |
| + b.Provider, b.Family, b.Kind = "claude", "claude", wire.KindSubscription |
| + raw, _ := json.Marshal([]any{b}) |
| + if err := os.WriteFile(r.bindings, raw, 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + identity, _ := json.Marshal(b.ExpectedIdentity) |
| + for name, body := range map[string][]byte{provider.IdentityFile: identity, ".claude.json": []byte(`{"oauthAccount":{"emailAddress":"a@example.com"}}`)} { |
| + if err := os.WriteFile(filepath.Join(r.home, name), body, 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + token := "fixture-usage-bearer-private" |
| + putToken := func() { |
| + t.Helper() |
| + if err := os.WriteFile(filepath.Join(r.home, ".credentials.json"), []byte(`{"claudeAiOauth":{"accessToken":"`+token+`"}}`), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + putToken() |
| + reads := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| + reads++ |
| + if req.Method != "GET" || req.URL.Path != "/api/oauth/usage" || req.URL.RawQuery != "" || req.Header.Get("Authorization") != "Bearer "+token || req.Header.Get("User-Agent") != "equipo-runner/test" || req.Header.Get("anthropic-beta") != "oauth-2025-04-20" { |
| + t.Error("unexpected usage request") |
| + } |
| + w.WriteHeader(status) |
| + if status == 200 { |
| + fmt.Fprint(w, `{"five_hour":{"utilization":12.5,"resets_at":"2026-11-14T14:00:00Z"},"seven_day":{"utilization":2,"resets_at":"2026-11-20T12:00:00Z"},"secret":"body-private"}`) |
| + } else { |
| + fmt.Fprint(w, token+" body-private") |
| + } |
| + })) |
| + defer srv.Close() |
| + at := time.Date(2026, 11, 13, 12, 0, 0, 0, time.UTC) |
| + reader := &ProfileReader{Origin: srv.URL, HTTP: connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil), Version: "test"} |
| + var logs bytes.Buffer |
| + setup := func() { |
| + r.conns.ClaudeUsage = reader |
| + r.conns.ClaudeStatus = func(context.Context, provider.Binding) (provider.Identity, string, error) { |
| + return provider.Identity{AccountID: b.AccountID, ProviderVersion: b.ExpectedIdentity.ProviderVersion}, "max", nil |
| + } |
| + r.conns.now = func() time.Time { return at } |
| + r.conns.Logger = slog.New(slog.NewTextHandler(&logs, nil)) |
| + } |
| + setup() |
| + r.conns.Check(context.Background()) |
| + if reads != 1 { |
| + t.Fatalf("hourly check made %d reads", reads) |
| + } |
| + held := r.conns.Held()[0] |
| + if held.State != wire.ConnHealthy { |
| + t.Fatalf("usage endpoint changed login health: %s", held.State) |
| + } |
| + if held.Plan != "max" { |
| + t.Fatalf("plan %q", held.Plan) |
| + } |
| + if status == 200 { |
| + h := held.Headroom |
| + if h == nil || len(h.Windows) != 2 || h.Windows[0].UsedPercent != 12.5 || h.Windows[1].UsedPercent != 2 || h.CheckedAt == nil || !h.CheckedAt.Equal(at) || !h.Fetched || h.Unavailable { |
| + t.Fatalf("reading %+v", h) |
| + } |
| + if h.Windows[0].Minutes != 300 || h.Windows[1].Minutes != 10080 || h.Windows[0].ResetsAt.Format(time.RFC3339) != "2026-11-14T14:00:00Z" { |
| + t.Fatal("windows changed") |
| + } |
| + } else if status != 500 && status != 401 && (held.Headroom == nil || !held.Headroom.Unavailable || held.Headroom.CheckedAt != nil) { |
| + t.Fatalf("refusal %+v", held.Headroom) |
| + } else if (status == 500 || status == 401) && held.Headroom != nil { |
| + t.Fatalf("%d invented a reading or a refusal", status) |
| + } |
| + // A restart and Check again both respect a refused endpoint's backoff. |
| + r.conns = &Conns{Runner: r.cfg, State: r.state} |
| + setup() |
| + at = at.Add(time.Hour) |
| + r.conns.CheckAgain(context.Background(), b.ID) |
| + denied := status == 403 || status == 404 |
| + want := 2 |
| + if denied { |
| + want = 1 |
| + } |
| + if reads != want { |
| + t.Fatalf("Check again reads %d, want %d", reads, want) |
| + } |
| + token = "fixture-replaced-private" |
| + putToken() |
| + r.conns.Check(context.Background()) |
| + want++ |
| + if reads != want { |
| + t.Fatal("token change did not retry") |
| + } |
| + at = at.Add(7 * 24 * time.Hour) |
| + r.conns.Check(context.Background()) |
| + want++ |
| + if reads != want { |
| + t.Fatal("week did not retry") |
| + } |
| + if strings.Contains(logs.String(), "private") { |
| + t.Fatalf("secret leaked in logs") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestClaudeUsageSkipsSetupToken(t *testing.T) { |
| + r := newProfileRig(t) |
| + r.conns.Runner.ScratchRoot = filepath.Join(t.TempDir(), "scratch") |
| + if err := r.state.recordProfile(context.Background(), r.b.ID, profileMark(r.token), "", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + checks := 0 |
| + r.conns.Refresh = func(context.Context, provider.Binding) (provider.Identity, error) { |
| + checks++ |
| + return r.b.ExpectedIdentity, nil |
| + } |
| + r.conns.ClaudeStatus = func(context.Context, provider.Binding) (provider.Identity, string, error) { |
| + t.Error("setup token treated as login") |
| + return provider.Identity{}, "", nil |
| + } |
| + srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Error("setup-token usage requested") })) |
| + defer srv.Close() |
| + r.conns.ClaudeUsage = &ProfileReader{Origin: srv.URL, HTTP: connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil)} |
| + r.conns.Check(context.Background()) |
| + if checks != 1 { |
| + t.Fatal("local status did not run") |
| + } |
| +} |
| + |
| +func TestClaudeUsageKeepsLastReading(t *testing.T) { |
| + r := newConnectorRig(t) |
| + at := time.Now().UTC() |
| + r.conns.now = func() time.Time { return at } |
| + status := 200 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| + w.WriteHeader(status) |
| + fmt.Fprint(w, `{"seven_day":{"utilization":86,"resets_at":null}}`) |
| + })) |
| + defer srv.Close() |
| + r.conns.ClaudeUsage = &ProfileReader{Origin: srv.URL, HTTP: connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil)} |
| + if err := r.conns.load(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.conns.readClaudeUsage(context.Background(), "codex-1", []byte("fixture")) |
| + original := r.conns.Held()[0].Headroom.CheckedAt |
| + for _, code := range []int{500, 403} { |
| + status = code |
| + at = at.Add(time.Hour) |
| + r.conns.readClaudeUsage(context.Background(), "codex-1", []byte("fixture")) |
| + h := r.conns.Held()[0].Headroom |
| + if h.CheckedAt == nil || !h.CheckedAt.Equal(*original) || len(h.Windows) != 1 || h.Windows[0].UsedPercent != 86 || h.Unavailable != (code == 403) { |
| + t.Fatalf("last reading lost: %+v", h) |
| + } |
| + } |
| + // Turn readings use their own source and preserve the unavailable notice. |
| + l := claudeUsage([]byte(`{"seven_day":{"utilization":90}}`)) |
| + l.Headroom.Fetched = false |
| + r.conns.Observe("codex-1", *l, "") |
| + h := r.conns.Held()[0].Headroom |
| + if h.Fetched || !h.Unavailable { |
| + t.Fatalf("turn source %+v", h) |
| + } |
| + status = 200 |
| + at = at.Add(7 * 24 * time.Hour) |
| + r.conns.readClaudeUsage(context.Background(), "codex-1", []byte("fixture")) |
| + if h := r.conns.Held()[0].Headroom; !h.Fetched || h.Unavailable || !h.CheckedAt.Equal(at) { |
| + t.Fatalf("recovery %+v", h) |
| + } |
| +} |
| + |
| +func TestClaudeUsageUnknownIsNotZero(t *testing.T) { |
| + for _, raw := range []string{`{}`, `null`, `{"five_hour":null}`, `{"five_hour":{"utilization":null}}`, `{"five_hour":{"utilization":-1}}`, `{"five_hour":{"utilization":1,"resets_at":"invalid"}}`, `{"five_hour":{"utilization":"secret"}}`} { |
| + if claudeUsage([]byte(raw)) != nil { |
| + t.Fatalf("invalid reading accepted: %s", raw) |
| + } |
| + } |
| + if l := claudeUsage([]byte(`{"five_hour":{"utilization":0,"resets_at":null},"extra_usage":{"is_enabled":false}}`)); l == nil || len(l.Headroom.Windows) != 1 || l.Headroom.Windows[0].UsedPercent != 0 { |
| + t.Fatal("reported zero lost") |
| + } |
| +} |
| + |
| +func TestHandshakeHelloWithholdsUsageRefresh(t *testing.T) { |
| + hello := func() wire.Hello { |
| + return wire.Hello{Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Versions: map[string]string{"runner": "test", "claude": "2.1.312"}, Connections: []wire.HeldConnection{{LocalID: "cl", Headroom: &wire.Headroom{Fetched: true, Unavailable: true}}}} |
| + } |
| + for _, protocol := range []int{19, 20} { |
| + inst := newFakeInstance(t) |
| + link, _, _, _ := startLinkWith(t, inst.url, &stubCoordinator{}, hello) |
| + c := <-inst.conns |
| + _, raw := read(t, c, wire.FrameHello) |
| + if strings.Contains(string(raw), "fetched") || strings.Contains(string(raw), "unavailable") { |
| + t.Fatal("initial hello leaked fields") |
| + } |
| + welcome, _ := json.Marshal(wire.Frame{ID: "welcome", Type: wire.FrameWelcome, Data: json.RawMessage(fmt.Sprintf(`{"generation":3,"runner_id":"RUNNER1","protocol":%d,"role":"primary"}`, protocol))}) |
| + write(t, c, welcome) |
| + read(t, c, wire.FrameSync) |
| + if protocol == 19 { |
| + link.HelloSoon() |
| + } |
| + _, raw = read(t, c, wire.FrameHello) |
| + for _, field := range []string{"fetched", "unavailable"} { |
| + if strings.Contains(string(raw), field) != (protocol == 20) { |
| + t.Fatalf("%d: %s", protocol, raw) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestClaudeUsageSafeTransport(t *testing.T) { |
| + target := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Error("redirect followed") })) |
| + defer target.Close() |
| + body := "" |
| + src := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if body == "" { |
| + http.Redirect(w, r, target.URL, http.StatusFound) |
| + } else { |
| + fmt.Fprint(w, body) |
| + } |
| + })) |
| + defer src.Close() |
| + p := &ProfileReader{Origin: src.URL, HTTP: connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil)} |
| + if status, l := p.readUsage(context.Background(), []byte("fixture-private")); status != 302 || l != nil { |
| + t.Fatal("redirect returned reading") |
| + } |
| + body = `{"five_hour":{"utilization":1},"padding":"` + strings.Repeat("x", maxProfileBytes) + `"}` |
| + if status, l := p.readUsage(context.Background(), []byte("fixture-private")); status != 200 || l != nil { |
| + t.Fatal("oversized response accepted") |
| + } |
| + // Without the test client a release refuses every other origin. |
| + p.HTTP = nil |
| + if status, l := p.readUsage(context.Background(), []byte("fixture-private")); status != 0 || l != nil { |
| + t.Fatal("release accepted another origin") |
| + } |
| +} |
diff --git a/internal/runner/thin/conns.go b/internal/runner/thin/conns.go| index e103f4dd..5337f072 100644 |
| --- a/internal/runner/thin/conns.go |
| +++ b/internal/runner/thin/conns.go |
| @@ -48,6 +48,10 @@ type Conns struct { |
| // Refresh runs the official CLI in a source home under its lock. |
| Refresh func(context.Context, provider.Binding) (provider.Identity, error) |
| LockWait time.Duration |
| + // ClaudeStatus reads the plan alongside the existing hourly local status. |
| + ClaudeStatus func(context.Context, provider.Binding) (provider.Identity, string, error) |
| + ClaudeUsage *ProfileReader |
| + usageMu sync.Mutex |
| // Verify checks a token connection with a real request (CheckToken); |
| // without it nothing can prove a token, so its state never improves. |
| Verify func(context.Context, runner.AccountBinding) error |
| @@ -60,8 +64,8 @@ type Conns struct { |
| // Reading is a connection's reading probe (rev 3 §2.7: the harness's |
| // cheapest request, never a model turn), which the scheduler runs on |
| // a reading older than fifteen minutes before it decides; nil, none |
| - // (no such request exists for Claude or Codex today), and a reading |
| - // stays as it was last reported. |
| + // and a reading stays as it was last reported. Claude OAuth usage |
| + // refreshes with the local status pass instead. |
| Reading func(context.Context, runner.AccountBinding) (*connect.Limit, error) |
| // Readings is told a connection's reported headroom changed: steps |
| // the scheduler holds look again. |
| @@ -390,7 +394,11 @@ func (c *Conns) Limit(id string, l connect.Limit) time.Time { |
| until, wait := connect.LimitedUntil(l.ResetsAt, cs.CoolOff, c.clock()) |
| cs.State, cs.ResetsAt, cs.CoolOff, cs.Window = wire.ConnLimited, until, wait, l.Window |
| if l.Headroom != nil { |
| - cs.Headroom = c.stamped(l.Headroom) |
| + h := c.stamped(l.Headroom) |
| + if !h.Fetched && cs.Headroom != nil { |
| + h.Unavailable = cs.Headroom.Unavailable |
| + } |
| + cs.Headroom = h |
| } |
| c.save(id, cs) |
| c.mu.Unlock() |
| @@ -417,6 +425,9 @@ func (c *Conns) Observe(id string, l connect.Limit, plan string) { |
| read := false |
| if l.Headroom != nil { |
| h := c.stamped(l.Headroom) |
| + if !h.Fetched && cs.Headroom != nil { |
| + h.Unavailable = cs.Headroom.Unavailable |
| + } |
| read = reported(cs.Headroom) != reported(h) |
| cs.Headroom = h |
| } |
| @@ -637,8 +648,35 @@ func (c *Conns) checkOne(ctx context.Context, b runner.AccountBinding) { |
| direct, err := c.Runner.DirectBinding(b) |
| if err == nil { |
| var lease *provider.AccountLease |
| - lease, err = provider.OpenRuntimeCopy(ctx, direct, c.Refresh, c.LockWait) |
| + refresh := c.Refresh |
| + var plan string |
| + if b.Provider == wire.ProviderClaude && b.Kind != wire.KindToken && c.ClaudeStatus != nil { |
| + refresh = func(ctx context.Context, pb provider.Binding) (provider.Identity, error) { |
| + var id provider.Identity |
| + var e error |
| + id, plan, e = c.ClaudeStatus(ctx, pb) |
| + return id, e |
| + } |
| + } |
| + lease, err = provider.OpenRuntimeCopy(ctx, direct, refresh, c.LockWait) |
| if lease != nil { |
| + if err == nil && b.Provider == wire.ProviderClaude && b.Kind != wire.KindToken { |
| + c.mu.Lock() |
| + cs := c.live[b.ID] |
| + planChanged := cs.Plan != plan |
| + cs.Plan = plan |
| + c.save(b.ID, cs) |
| + c.mu.Unlock() |
| + if planChanged { |
| + c.changed() |
| + } |
| + if c.ClaudeUsage != nil { |
| + if token, e := lease.ClaudeOAuthToken(); e == nil { |
| + c.readClaudeUsage(ctx, b.ID, token) |
| + clear(token) |
| + } |
| + } |
| + } |
| lease.Close() |
| } |
| } |
| @@ -774,4 +812,5 @@ func (c *Conns) Forget(id string) { |
| _, _ = c.State.db.Exec("DELETE FROM conn_state WHERE id=?", id) |
| _, _ = c.State.db.Exec("DELETE FROM conn_validated WHERE id=?", id) |
| _, _ = c.State.db.Exec("DELETE FROM conn_profile WHERE id=?", id) |
| + _, _ = c.State.db.Exec("DELETE FROM conn_usage WHERE id=?", id) |
| } |
diff --git a/internal/runner/thin/link.go b/internal/runner/thin/link.go| index 762dfb0e..e909d286 100644 |
| --- a/internal/runner/thin/link.go |
| +++ b/internal/runner/thin/link.go |
| @@ -519,6 +519,7 @@ func (l *Link) handshake(ctx context.Context, offer int) (*websocket.Conn, *wire |
| // Nor a reading's time, which an instance below protocol 15 refuses |
| // the same way. |
| heldReadings := wire.WithoutReadingTimes(&hello) |
| + heldUsage := wire.WithoutUsageRefresh(&hello) |
| // Nor the sites capability, below protocol 16. |
| heldSites := wire.WithoutSites(&hello) |
| l.mu.Lock() |
| @@ -569,7 +570,7 @@ func (l *Link) handshake(ctx context.Context, offer int) (*websocket.Conn, *wire |
| } |
| l.mu.Lock() |
| l.proto, l.role = min(spoken, offer), role |
| - if held && l.proto >= wire.ProtocolEmptyRepos || heldPreviews && l.proto >= wire.ProtocolExplore || heldResearch && l.proto >= wire.ProtocolResearch || heldReadings && l.proto >= wire.ProtocolReadings || heldSites && l.proto >= wire.ProtocolPublish { |
| + if heldUsage && l.proto >= wire.ProtocolUsageRefresh || held && l.proto >= wire.ProtocolEmptyRepos || heldPreviews && l.proto >= wire.ProtocolExplore || heldResearch && l.proto >= wire.ProtocolResearch || heldReadings && l.proto >= wire.ProtocolReadings || heldSites && l.proto >= wire.ProtocolPublish { |
| l.helloSoon = true |
| } |
| l.mu.Unlock() |
diff --git a/internal/runner/thin/readings.go b/internal/runner/thin/readings.go| index e1bd3bbc..79f458eb 100644 |
| --- a/internal/runner/thin/readings.go |
| +++ b/internal/runner/thin/readings.go |
| @@ -21,8 +21,7 @@ var errNoReading = errors.New("no reading") |
| // refreshed with the app-server's account/rateLimits/read, run as the |
| // hourly refresh runs (the source home under its lock, the login |
| // probe's environment, no namespace and no egress relay, never a thread |
| -// or a turn). Claude has no reading without a model turn: it stays as |
| -// last reported, and so does every other connection (nil, nil). |
| +// or a turn). Claude OAuth usage is read separately by the status check. |
| func CodexReading(c runner.Config, read func(context.Context, provider.Binding) (provider.Identity, json.RawMessage, error), wait time.Duration) func(context.Context, runner.AccountBinding) (*connect.Limit, error) { |
| if read == nil { |
| options := provider.LoginOptions{ClaudePath: c.ClaudePath, CodexPath: c.CodexPath} |
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go| index 65371107..923b1b82 100644 |
| --- a/internal/runner/thin/run.go |
| +++ b/internal/runner/thin/run.go |
| @@ -201,9 +201,13 @@ 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} |
| + conns.ClaudeUsage = o.Claude.Profile |
| + conns.ClaudeStatus = func(ctx context.Context, b provider.Binding) (provider.Identity, string, error) { |
| + return provider.ReadClaudeStatus(ctx, b, provider.LoginOptions{ClaudePath: c.ClaudePath}) |
| + } |
| // A Codex reading older than fifteen minutes is refreshed without a |
| - // model turn before the scheduler decides; Claude's stays as last |
| - // reported (connectors spec rev 3.2 §6). |
| + // model turn before the scheduler decides. Claude usage is read by |
| + // the hourly check and Check again. |
| conns.Reading = CodexReading(c, o.ReadCodexLimits, o.Claude.LockWait) |
| // 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 |
diff --git a/internal/runner/thin/state.go b/internal/runner/thin/state.go| index 46ef06d3..2e8a5308 100644 |
| --- a/internal/runner/thin/state.go |
| +++ b/internal/runner/thin/state.go |
| @@ -56,7 +56,7 @@ func OpenState(ctx context.Context, dir string) (*State, error) { |
| return nil, err |
| } |
| d.SetMaxOpenConns(1) |
| - if _, err = d.ExecContext(ctx, schema+stepSchema+watchSchema+askSchema+connSchema+profileSchema+connectSchema+effectSchema+fileSchema+relaySchema+metered.Schema+researchSchema+scheduleSchema); err != nil { |
| + if _, err = d.ExecContext(ctx, schema+stepSchema+watchSchema+askSchema+connSchema+usageSchema+profileSchema+connectSchema+effectSchema+fileSchema+relaySchema+metered.Schema+researchSchema+scheduleSchema); err != nil { |
| d.Close() |
| return nil, err |
| } |
diff --git a/internal/wire/assistant_test.go b/internal/wire/assistant_test.go| index 72f9f884..85d3894d 100644 |
| --- a/internal/wire/assistant_test.go |
| +++ b/internal/wire/assistant_test.go |
| @@ -44,8 +44,8 @@ func TestAssistantCardJSON(t *testing.T) { |
| } |
| // A runner that speaks 19 or more is spoken to at 19. |
| -func TestSpokenIs19(t *testing.T) { |
| - if wire.Spoken(99) != 19 || wire.ProtocolCurrent != wire.ProtocolAssistant || wire.ProtocolAssistant != wire.Protocol19 { |
| +func TestSpokenIs20(t *testing.T) { |
| + if wire.Spoken(99) != 20 || wire.ProtocolCurrent != wire.ProtocolUsageRefresh || wire.ProtocolAssistant != wire.Protocol19 { |
| t.Fatalf("spoken %d, current %d", wire.Spoken(99), wire.ProtocolCurrent) |
| } |
| } |
diff --git a/internal/wire/claude_usage.go b/internal/wire/claude_usage.go| new file mode 100644 |
| index 00000000..7c7a9dc9 |
| --- /dev/null |
| +++ b/internal/wire/claude_usage.go |
| @@ -0,0 +1,40 @@ |
| +package wire |
| + |
| +import "slices" |
| + |
| +func withoutUsageRefresh(h **Headroom) bool { |
| + if *h == nil || !((*h).Fetched || (*h).Unavailable) { |
| + return false |
| + } |
| + v := **h |
| + v.Fetched, v.Unavailable = false, false |
| + *h = &v |
| + return true |
| +} |
| + |
| +func withoutUsageRefreshConnections(cs *[]HeldConnection) bool { |
| + out := slices.Clone(*cs) |
| + changed := false |
| + for i := range out { |
| + changed = withoutUsageRefresh(&out[i].Headroom) || changed |
| + } |
| + if changed { |
| + *cs = out |
| + } |
| + return changed |
| +} |
| + |
| +// WithoutUsageRefresh keeps the initial hello readable before negotiation. |
| +func WithoutUsageRefresh(h *Hello) bool { return withoutUsageRefreshConnections(&h.Connections) } |
| + |
| +func downgradeUsageRefresh(body any) bool { |
| + switch v := body.(type) { |
| + case *Hello: |
| + return WithoutUsageRefresh(v) |
| + case *Sync: |
| + return withoutUsageRefreshConnections(&v.Connections) |
| + case *ConnectionReport: |
| + return withoutUsageRefresh(&v.Headroom) |
| + } |
| + return false |
| +} |
diff --git a/internal/wire/claude_usage_test.go b/internal/wire/claude_usage_test.go| new file mode 100644 |
| index 00000000..bf6a701e |
| --- /dev/null |
| +++ b/internal/wire/claude_usage_test.go |
| @@ -0,0 +1,42 @@ |
| +package wire_test |
| + |
| +import ( |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +func TestClaudeUsageProtocol20(t *testing.T) { |
| + if wire.ProtocolCurrent != 20 { |
| + t.Fatal(wire.ProtocolCurrent) |
| + } |
| + at := time.Now() |
| + h := &wire.Headroom{CheckedAt: &at, Fetched: true, Unavailable: true} |
| + cs := []wire.HeldConnection{{LocalID: "cl", Headroom: h}} |
| + for kind, body := range map[string]any{wire.FrameHello: wire.Hello{Connections: cs}, wire.FrameSync: wire.Sync{Connections: cs}, wire.FrameConnection: wire.ConnectionReport{Headroom: h}} { |
| + f, err := wire.NewFrame("test", kind, body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, p := range []int{14, 19, 20} { |
| + out, err := wire.Encode(f, p) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, field := range []string{"fetched", "unavailable"} { |
| + if strings.Contains(string(out.Data), `"`+field+`"`) != (p >= 20) { |
| + t.Fatalf("protocol %d: %s", p, out.Data) |
| + } |
| + } |
| + if strings.Contains(string(out.Data), "checked_at") != (p >= 15) { |
| + t.Fatal(string(out.Data)) |
| + } |
| + } |
| + } |
| + hello := wire.Hello{Connections: cs} |
| + if !wire.WithoutUsageRefresh(&hello) || hello.Connections[0].Headroom.Fetched || hello.Connections[0].Headroom.Unavailable || !h.Fetched || !h.Unavailable { |
| + t.Fatal("handshake mutated source or leaked fields") |
| + } |
| +} |
diff --git a/internal/wire/connections.go b/internal/wire/connections.go| index 751a2322..6a3bda93 100644 |
| --- a/internal/wire/connections.go |
| +++ b/internal/wire/connections.go |
| @@ -82,13 +82,15 @@ type Window struct { |
| // 0 to 1 (null when unreported); ResetsAt is when a limited connection |
| // may answer again (null when the provider did not say). CheckedAt is |
| // when the runner took the reading (ProtocolReadings; absent from an |
| -// older runner): Codex's is refreshed without a model turn, Claude's is |
| -// as last reported on a turn. |
| +// older runner). Fetched distinguishes a Claude OAuth read from a turn. |
| type Headroom struct { |
| Utilization *float64 `json:"utilization"` |
| ResetsAt *time.Time `json:"resets_at"` |
| Windows []Window `json:"windows"` |
| CheckedAt *time.Time `json:"checked_at,omitempty"` |
| + // ProtocolUsageRefresh. Unavailable leaves any last reading intact. |
| + Fetched bool `json:"fetched,omitempty"` |
| + Unavailable bool `json:"unavailable,omitempty"` |
| } |
| // ConnectPrompt is what a connecting card shows: Kind is a Prompt* |
diff --git a/internal/wire/mixed_protocol_test.go b/internal/wire/mixed_protocol_test.go| index b6561a1c..bf5058ca 100644 |
| --- a/internal/wire/mixed_protocol_test.go |
| +++ b/internal/wire/mixed_protocol_test.go |
| @@ -15,7 +15,7 @@ import ( |
| // both go out whole; at 11 both are downgraded. The numbers are written |
| // out so that pointing ProtocolResearch back at 12 fails here. |
| func TestEncodeMixedMeteredAndResearch(t *testing.T) { |
| - if wire.ProtocolMetered != wire.Protocol12 || wire.ProtocolResearch != wire.Protocol13 || wire.ProtocolCurrent != wire.Protocol19 { |
| + if wire.ProtocolMetered != wire.Protocol12 || wire.ProtocolResearch != wire.Protocol13 || wire.ProtocolCurrent != wire.Protocol20 { |
| t.Fatalf("metered %d, research %d, current %d", wire.ProtocolMetered, wire.ProtocolResearch, wire.ProtocolCurrent) |
| } |
| metered := wire.HeldConnection{LocalID: "tensorx-1", Person: "p", Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, State: wire.ConnHealthy, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Budget: &wire.Budget{Day: 1, Month: 2, Currency: "USD"}, Spend: &wire.Spend{Currency: "USD"}} |
diff --git a/internal/wire/models_test.go b/internal/wire/models_test.go| index 5636b8c0..31dd52b8 100644 |
| --- a/internal/wire/models_test.go |
| +++ b/internal/wire/models_test.go |
| @@ -94,7 +94,7 @@ func modelsFrames(t *testing.T) map[string]wire.Frame { |
| // protocol is checked because an older step in Encode's chain could |
| // undo a newer one (S5's bug). |
| func TestEncodeBelowProtocol18AgainstFrozenSchemas(t *testing.T) { |
| - if wire.ProtocolModels != wire.Protocol18 || wire.ProtocolCurrent != wire.Protocol19 { |
| + if wire.ProtocolModels != wire.Protocol18 || wire.ProtocolCurrent != wire.Protocol20 { |
| t.Fatalf("models %d, current %d", wire.ProtocolModels, wire.ProtocolCurrent) |
| } |
| fs := modelsFrames(t) |
diff --git a/internal/wire/opencode_test.go b/internal/wire/opencode_test.go| index cc5707aa..752b2985 100644 |
| --- a/internal/wire/opencode_test.go |
| +++ b/internal/wire/opencode_test.go |
| @@ -57,7 +57,7 @@ func providersIn(t *testing.T, raw []byte) (providers, harnesses []string) { |
| // leave hello and sync, its usage rows leave every report, and a connect |
| // or a report about one is refused. At 17 nothing changes. |
| func TestEncodeBelowProtocol17DropsOpenCode(t *testing.T) { |
| - if wire.ProtocolOpenCode != wire.Protocol17 || wire.ProtocolCurrent != wire.Protocol19 { |
| + if wire.ProtocolOpenCode != wire.Protocol17 || wire.ProtocolCurrent != wire.Protocol20 { |
| t.Fatalf("opencode %d, current %d", wire.ProtocolOpenCode, wire.ProtocolCurrent) |
| } |
| budget := &wire.Budget{Day: 1_000_000, Month: 10_000_000, Currency: "USD", Revision: 1} |
diff --git a/internal/wire/publish_test.go b/internal/wire/publish_test.go| index dedfda18..58fbc75f 100644 |
| --- a/internal/wire/publish_test.go |
| +++ b/internal/wire/publish_test.go |
| @@ -17,7 +17,7 @@ import ( |
| // and a hello's sites capability are dropped, so nothing a protocol 15 |
| // peer decodes strictly carries them. |
| func TestEncodeBelowProtocol16DropsPublish(t *testing.T) { |
| - if wire.ProtocolPublish != wire.Protocol16 || wire.ProtocolCurrent != wire.Protocol19 { |
| + if wire.ProtocolPublish != wire.Protocol16 || wire.ProtocolCurrent != wire.Protocol20 { |
| t.Fatalf("publish %d, current %d", wire.ProtocolPublish, wire.ProtocolCurrent) |
| } |
| publish := wire.DispatchCommand{Person: "p", TaskID: "tk", StepID: "s", Attempt: 1, Specialist: wire.SpecialistPublish, Findings: []wire.Finding{}, CandidateSHA: strings.Repeat("e", 40), Publish: &wire.PublishDispatch{App: "site-sample", Into: "main"}} |
diff --git a/internal/wire/runners.go b/internal/wire/runners.go| index d411a084..b4ea6024 100644 |
| --- a/internal/wire/runners.go |
| +++ b/internal/wire/runners.go |
| @@ -45,6 +45,7 @@ const ( |
| Protocol17 = 17 |
| Protocol18 = 18 |
| Protocol19 = 19 |
| + Protocol20 = 20 |
| // ProtocolSpend is the first protocol with a fix round's Feedback and |
| // a usage row's Turns; Encode drops both below it. |
| ProtocolSpend = Protocol3 |
| @@ -145,7 +146,9 @@ const ( |
| // refuses an Assistant message, drops the Assistant's sessions from |
| // sync and drops keep_preview (downgradeAssistant). |
| ProtocolAssistant = Protocol19 |
| - ProtocolCurrent = ProtocolAssistant |
| + // ProtocolUsageRefresh adds fetched readings and usage availability. |
| + ProtocolUsageRefresh = Protocol20 |
| + ProtocolCurrent = ProtocolUsageRefresh |
| ) |
| // Runner roles. A person's first runner is the primary: the coordinator, |
| @@ -554,12 +557,15 @@ func Encode(f Frame, protocol int) (Frame, error) { |
| return Frame{}, err |
| } |
| changed := false |
| + if protocol < ProtocolUsageRefresh { |
| + changed = downgradeUsageRefresh(body) |
| + } |
| if protocol < ProtocolAssistant { |
| dropped, err := downgradeAssistant(body, protocol) |
| if err != nil { |
| return Frame{}, err |
| } |
| - changed = dropped |
| + changed = dropped || changed |
| } |
| if protocol < ProtocolModels { |
| dropped, err := downgradeModels(body, protocol) |
diff --git a/internal/wire/runners_test.go b/internal/wire/runners_test.go| index 18b98b3c..ca2c4d3a 100644 |
| --- a/internal/wire/runners_test.go |
| +++ b/internal/wire/runners_test.go |
| @@ -413,7 +413,7 @@ func TestEncodeBelowProtocol9DropsPreviews(t *testing.T) { |
| if _, err := wire.Encode(d, wire.ProtocolPreview); err != nil { |
| t.Fatal(err) |
| } |
| - if wire.ProtocolCurrent != wire.ProtocolAssistant || wire.ProtocolAssistant != 19 || wire.ProtocolModels != 18 || wire.ProtocolOpenCode != 17 || wire.ProtocolPublish != 16 || wire.ProtocolReadings != 15 || wire.ProtocolScheduler != 14 || wire.ProtocolResearch != 13 || wire.ProtocolMetered != 12 || wire.ProtocolPreviewHost != 11 || wire.ProtocolExplore != 10 || wire.ProtocolPreview != 9 { |
| + if wire.ProtocolCurrent != wire.ProtocolUsageRefresh || wire.ProtocolAssistant != 19 || wire.ProtocolModels != 18 || wire.ProtocolOpenCode != 17 || wire.ProtocolPublish != 16 || wire.ProtocolReadings != 15 || wire.ProtocolScheduler != 14 || wire.ProtocolResearch != 13 || wire.ProtocolMetered != 12 || wire.ProtocolPreviewHost != 11 || wire.ProtocolExplore != 10 || wire.ProtocolPreview != 9 { |
| t.Fatalf("current %d", wire.ProtocolCurrent) |
| } |
| } |
diff --git a/internal/wire/schedule_test.go b/internal/wire/schedule_test.go| index f2f5e4cc..43f63b07 100644 |
| --- a/internal/wire/schedule_test.go |
| +++ b/internal/wire/schedule_test.go |
| @@ -17,7 +17,7 @@ import ( |
| // refused anything that spends, never handed it), and a dispatch loses |
| // its priority, deadline and release; what 13 already had is unchanged. |
| func TestEncodeBelowProtocol14DropsScheduler(t *testing.T) { |
| - if wire.ProtocolScheduler != wire.Protocol14 || wire.ProtocolCurrent != wire.Protocol19 { |
| + if wire.ProtocolScheduler != wire.Protocol14 || wire.ProtocolCurrent != wire.Protocol20 { |
| t.Fatalf("scheduler %d, current %d", wire.ProtocolScheduler, wire.ProtocolCurrent) |
| } |
| by := time.Date(2026, 11, 20, 17, 0, 0, 0, time.UTC) |
diff --git a/internal/wire/usage_test.go b/internal/wire/usage_test.go| index 6be67fff..5858cde6 100644 |
| --- a/internal/wire/usage_test.go |
| +++ b/internal/wire/usage_test.go |
| @@ -44,7 +44,7 @@ func headrooms(t *testing.T, raw []byte) []map[string]json.RawMessage { |
| // decodes strictly against the frozen protocol 14 headroom, and the |
| // caller's own values are untouched; at 15 nothing changes. |
| func TestEncodeBelowProtocol15DropsReadingTimes(t *testing.T) { |
| - if wire.ProtocolReadings != wire.Protocol15 || wire.ProtocolCurrent != wire.Protocol19 { |
| + if wire.ProtocolReadings != wire.Protocol15 || wire.ProtocolCurrent != wire.Protocol20 { |
| t.Fatalf("readings %d, current %d", wire.ProtocolReadings, wire.ProtocolCurrent) |
| } |
| at := time.Date(2026, 11, 12, 9, 58, 0, 0, time.UTC) |
diff --git a/scripts/runner-reference-allowlist.json b/scripts/runner-reference-allowlist.json| index 661ae7b3..cf407170 100644 |
| --- a/scripts/runner-reference-allowlist.json |
| +++ b/scripts/runner-reference-allowlist.json |
| @@ -15538,5 +15538,19 @@ |
| "match": "equipo-runner", |
| "count": 2, |
| "reason": "Ignores a runner binary built in place, so build output is never committed; a path, not a dead reference." |
| + }, |
| + { |
| + "path": "internal/runner/thin/claude_usage_test.go", |
| + "line_sha256": "f825b76c337132f77447485c6b3a489b59c82a31d1e7ccfaa73425b42c86cde3", |
| + "match": "equipo-runner", |
| + "count": 1, |
| + "reason": "Asserts the honest runner User-Agent on a fake OAuth usage request." |
| + }, |
| + { |
| + "path": "docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md", |
| + "line_sha256": "434b549d650a25a0e0d50b19ef0dd4d4ddb91397c4720e55ac4905a2ecf58bca", |
| + "match": "equipo-runner", |
| + "count": 1, |
| + "reason": "Records the runner User-Agent used for the read-only Claude OAuth usage request." |
| } |
| ] |