Chat info: account quota per harness (Claude rate_limit_event, Codex account/rateLimits, OpenCode unsupported)
Usage frames carry optional usage.account {harness, source, plan, as_of,
windows[{id,label,used_percent,resets_at}], unsupported}. Claude Code quota
comes from its rate_limit_event stream lines and the initialize account
(plan), shared across chats on the same account. Codex reads
account/rateLimits/read once per connection (re-read when a chat opens after
5 min) and merges account/rateLimits/updated. OpenCode exposes no quota API
and says so. The app's chat info sheet shows an Account usage section with a
progress bar and reset countdown per window, Material and Cupertino.
This commit is contained in:
@@ -102,6 +102,10 @@ type Chat struct {
|
||||
mu sync.Mutex
|
||||
sessions map[string]*session
|
||||
closed bool
|
||||
|
||||
// quotas is the latest rate_limit_event quota per account (see quota.go).
|
||||
quotaMu sync.Mutex
|
||||
quotas map[string]*protocol.ChatAccountUsage
|
||||
}
|
||||
|
||||
func New(ctx context.Context) *Chat {
|
||||
@@ -269,8 +273,10 @@ type session struct {
|
||||
|
||||
usage *protocol.ChatEventFrame
|
||||
compaction *protocol.ChatEventFrame
|
||||
prompts []promptRecord
|
||||
models []protocol.ChatModel
|
||||
// account is the signed-in account the live process reported.
|
||||
account accountIdentity
|
||||
prompts []promptRecord
|
||||
models []protocol.ChatModel
|
||||
|
||||
// model is the requested selection; modelActual is the model the CLI last
|
||||
// reported for a message. appliedModel is what the live process was told.
|
||||
@@ -310,6 +316,9 @@ func (s *session) emit(frame protocol.ChatEventFrame) {
|
||||
}
|
||||
s.mu.Lock()
|
||||
if frame.Kind == protocol.ChatEventUsage && frame.Usage != nil {
|
||||
usage := *frame.Usage
|
||||
usage.Account = s.chat.accountUsage(s.account.key)
|
||||
frame.Usage = &usage
|
||||
s.usage = &frame
|
||||
}
|
||||
if frame.Kind == protocol.ChatEventCompaction && frame.Compaction != nil {
|
||||
@@ -337,7 +346,14 @@ func (s *session) subscribe() chan protocol.ChatEventFrame {
|
||||
s.mu.Lock()
|
||||
s.subs[ch] = struct{}{}
|
||||
if s.usage != nil {
|
||||
ch <- *s.usage
|
||||
// Account quota may have moved since (another chat on the account).
|
||||
frame := *s.usage
|
||||
usage := *frame.Usage
|
||||
usage.Account = s.chat.accountUsage(s.account.key)
|
||||
frame.Usage = &usage
|
||||
ch <- frame
|
||||
} else if account := s.chat.accountUsage(s.account.key); account != nil {
|
||||
ch <- protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventUsage, Usage: &protocol.ChatUsage{Account: account}}
|
||||
}
|
||||
if s.compaction != nil {
|
||||
ch <- *s.compaction
|
||||
|
||||
@@ -121,22 +121,23 @@ func (s *session) spawn(ctx context.Context) (*process, error) {
|
||||
// before any user turn so an approval is never silently denied.
|
||||
initCtx, cancel := context.WithTimeout(ctx, initializeTimeout)
|
||||
defer cancel()
|
||||
models, err := p.initialize(initCtx)
|
||||
models, account, err := p.initialize(initCtx)
|
||||
if err != nil {
|
||||
p.close()
|
||||
return nil, err
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.models = models
|
||||
s.account = account
|
||||
s.lastErr = ""
|
||||
s.mu.Unlock()
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (p *process) initialize(ctx context.Context) ([]protocol.ChatModel, error) {
|
||||
func (p *process) initialize(ctx context.Context) ([]protocol.ChatModel, accountIdentity, error) {
|
||||
raw, err := p.request(ctx, "initialize", map[string]any{"subtype": "initialize"})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("initialize Claude Code: %w%s", err, p.diagnostic())
|
||||
return nil, accountIdentity{}, fmt.Errorf("initialize Claude Code: %w%s", err, p.diagnostic())
|
||||
}
|
||||
var reply struct {
|
||||
Models []struct {
|
||||
@@ -145,9 +146,10 @@ func (p *process) initialize(ctx context.Context) ([]protocol.ChatModel, error)
|
||||
DisplayName string `json:"displayName"`
|
||||
Description string `json:"description"`
|
||||
} `json:"models"`
|
||||
Account json.RawMessage `json:"account"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &reply); err != nil {
|
||||
return nil, errors.New("Claude Code returned an invalid initialize response")
|
||||
return nil, accountIdentity{}, errors.New("Claude Code returned an invalid initialize response")
|
||||
}
|
||||
models := make([]protocol.ChatModel, 0, len(reply.Models))
|
||||
for _, m := range reply.Models {
|
||||
@@ -161,9 +163,9 @@ func (p *process) initialize(ctx context.Context) ([]protocol.ChatModel, error)
|
||||
models = append(models, protocol.ChatModel{ID: m.Value, Provider: Backend, Name: name})
|
||||
}
|
||||
if len(models) == 0 {
|
||||
return nil, errors.New("Claude Code reported no models; check that the CLI is signed in")
|
||||
return nil, accountIdentity{}, errors.New("Claude Code reported no models; check that the CLI is signed in")
|
||||
}
|
||||
return models, nil
|
||||
return models, decodeAccountIdentity(reply.Account), nil
|
||||
}
|
||||
|
||||
// request sends one control request and waits for its control_response.
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"math"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// Account quota comes only from what Claude Code already sends: the
|
||||
// `rate_limit_event` stream-json line (SDKRateLimitEvent, verified against the
|
||||
// installed CLI 2.1.316's message schema) and the `account` object of the
|
||||
// initialize control response. Nothing here starts a request or a model call.
|
||||
//
|
||||
// rate_limit_info carries the currently limiting window at the top level
|
||||
// (rateLimitType, utilization 0-1, resetsAt epoch seconds) and, for
|
||||
// subscription logins, unifiedWindows with every tracked window
|
||||
// (five_hour, seven_day, seven_day_overage_included). The CLI emits a new
|
||||
// event whenever a window's rounded percentage, reset, status or threshold
|
||||
// moves. API-key, Bedrock and Vertex sessions never receive one.
|
||||
|
||||
const quotaHarness = "Claude Code"
|
||||
const quotaSource = "rate_limit_event"
|
||||
|
||||
// accountIdentity is the signed-in account a process reported at initialize.
|
||||
// key is never sent to clients; it only shares quota between sessions.
|
||||
type accountIdentity struct {
|
||||
key string
|
||||
plan string
|
||||
}
|
||||
|
||||
func decodeAccountIdentity(raw json.RawMessage) accountIdentity {
|
||||
var account struct {
|
||||
Email string `json:"email"`
|
||||
Organization string `json:"organization"`
|
||||
SubscriptionType string `json:"subscriptionType"`
|
||||
APIProvider string `json:"apiProvider"`
|
||||
}
|
||||
if len(raw) == 0 || json.Unmarshal(raw, &account) != nil {
|
||||
return accountIdentity{}
|
||||
}
|
||||
key := strings.TrimSpace(account.Email) + "\x00" + strings.TrimSpace(account.Organization) + "\x00" + account.APIProvider
|
||||
if strings.Trim(key, "\x00") == "" {
|
||||
key = ""
|
||||
}
|
||||
return accountIdentity{key: key, plan: strings.TrimSpace(account.SubscriptionType)}
|
||||
}
|
||||
|
||||
type rateLimitWindowInfo struct {
|
||||
Utilization *float64 `json:"utilization"`
|
||||
ResetsAt *float64 `json:"resetsAt"`
|
||||
}
|
||||
|
||||
type rateLimitInfo struct {
|
||||
Status string `json:"status"`
|
||||
ResetsAt *float64 `json:"resetsAt"`
|
||||
RateLimitType string `json:"rateLimitType"`
|
||||
Utilization *float64 `json:"utilization"`
|
||||
UnifiedWindows map[string]*rateLimitWindowInfo `json:"unifiedWindows"`
|
||||
}
|
||||
|
||||
// quotaWindowOrder lists the windows Claude Code names, in display order.
|
||||
var quotaWindowOrder = []struct{ id, label string }{
|
||||
{"five_hour", "5-hour"},
|
||||
{"seven_day", "Weekly"},
|
||||
{"seven_day_opus", "Weekly (Opus)"},
|
||||
{"seven_day_sonnet", "Weekly (Sonnet)"},
|
||||
{"seven_day_overage_included", "Weekly (included)"},
|
||||
}
|
||||
|
||||
func quotaWindowLabel(id string) (string, bool) {
|
||||
for _, w := range quotaWindowOrder {
|
||||
if w.id == id {
|
||||
return w.label, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func quotaWindow(id string, utilization, resetsAt *float64) (protocol.ChatQuotaWindow, bool) {
|
||||
label, ok := quotaWindowLabel(id)
|
||||
if !ok || utilization == nil || math.IsNaN(*utilization) || math.IsInf(*utilization, 0) || *utilization < 0 {
|
||||
return protocol.ChatQuotaWindow{}, false
|
||||
}
|
||||
w := protocol.ChatQuotaWindow{ID: id, Label: label, UsedPercent: math.Round(*utilization*1000) / 10}
|
||||
if resetsAt != nil && *resetsAt > 0 && !math.IsInf(*resetsAt, 0) {
|
||||
w.ResetsAt = int64(*resetsAt * 1000)
|
||||
}
|
||||
return w, true
|
||||
}
|
||||
|
||||
// mergeRateLimit folds one rate_limit_info into previous (which may be nil)
|
||||
// and reports the new snapshot, or nil when the event names no usable window.
|
||||
// Windows the event does not mention keep their last reported value.
|
||||
func mergeRateLimit(previous *protocol.ChatAccountUsage, raw json.RawMessage, plan string, now time.Time) *protocol.ChatAccountUsage {
|
||||
var info rateLimitInfo
|
||||
if len(raw) == 0 || json.Unmarshal(raw, &info) != nil {
|
||||
return nil
|
||||
}
|
||||
windows := map[string]protocol.ChatQuotaWindow{}
|
||||
if previous != nil {
|
||||
for _, w := range previous.Windows {
|
||||
windows[w.ID] = w
|
||||
}
|
||||
}
|
||||
changed := false
|
||||
if w, ok := quotaWindow(info.RateLimitType, info.Utilization, info.ResetsAt); ok {
|
||||
windows[w.ID] = w
|
||||
changed = true
|
||||
}
|
||||
for id, window := range info.UnifiedWindows {
|
||||
if window == nil {
|
||||
continue
|
||||
}
|
||||
if w, ok := quotaWindow(id, window.Utilization, window.ResetsAt); ok {
|
||||
windows[w.ID] = w
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return nil
|
||||
}
|
||||
next := &protocol.ChatAccountUsage{Harness: quotaHarness, Source: quotaSource, Plan: plan, AsOf: now.UnixMilli()}
|
||||
if next.Plan == "" && previous != nil {
|
||||
next.Plan = previous.Plan
|
||||
}
|
||||
for _, entry := range quotaWindowOrder {
|
||||
if w, ok := windows[entry.id]; ok {
|
||||
next.Windows = append(next.Windows, w)
|
||||
}
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
// accountUsage returns a copy of the latest quota for an account key.
|
||||
func (c *Chat) accountUsage(key string) *protocol.ChatAccountUsage {
|
||||
if key == "" {
|
||||
return nil
|
||||
}
|
||||
c.quotaMu.Lock()
|
||||
defer c.quotaMu.Unlock()
|
||||
return c.quotas[key].Clone()
|
||||
}
|
||||
|
||||
// handleRateLimit records a rate_limit_event for the session's account and
|
||||
// republishes the latest usage snapshot, with the new quota, to every session
|
||||
// of that account.
|
||||
func (s *session) handleRateLimit(raw json.RawMessage) {
|
||||
s.mu.Lock()
|
||||
account := s.account
|
||||
s.mu.Unlock()
|
||||
key := account.key
|
||||
if key == "" {
|
||||
// An account the CLI did not identify still belongs to this session.
|
||||
key = "session:" + s.id
|
||||
s.mu.Lock()
|
||||
s.account.key = key
|
||||
s.mu.Unlock()
|
||||
}
|
||||
c := s.chat
|
||||
c.quotaMu.Lock()
|
||||
next := mergeRateLimit(c.quotas[key], raw, account.plan, time.Now())
|
||||
if next == nil {
|
||||
c.quotaMu.Unlock()
|
||||
return
|
||||
}
|
||||
if c.quotas == nil {
|
||||
c.quotas = map[string]*protocol.ChatAccountUsage{}
|
||||
}
|
||||
c.quotas[key] = next
|
||||
c.quotaMu.Unlock()
|
||||
c.mu.Lock()
|
||||
targets := make([]*session, 0, len(c.sessions))
|
||||
for _, other := range c.sessions {
|
||||
targets = append(targets, other)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
if !containsSession(targets, s) {
|
||||
targets = append(targets, s)
|
||||
}
|
||||
for _, target := range targets {
|
||||
target.mu.Lock()
|
||||
same := target.account.key == key
|
||||
target.mu.Unlock()
|
||||
if same {
|
||||
target.republishUsage()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func containsSession(list []*session, s *session) bool {
|
||||
for _, other := range list {
|
||||
if other == s {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// republishUsage emits the retained token snapshot (or an empty one) so the
|
||||
// account quota attached by emit reaches watchers without inventing tokens.
|
||||
func (s *session) republishUsage() {
|
||||
s.mu.Lock()
|
||||
usage := &protocol.ChatUsage{}
|
||||
if s.usage != nil && s.usage.Usage != nil {
|
||||
copy := *s.usage.Usage
|
||||
usage = ©
|
||||
}
|
||||
s.mu.Unlock()
|
||||
s.emit(protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventUsage, Usage: usage})
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// Shaped like Claude Code 2.1.316's SDKRateLimitEvent.rate_limit_info;
|
||||
// the numbers are synthetic.
|
||||
const unifiedRateLimit = `{"status":"allowed_warning","resetsAt":1900000000,"rateLimitType":"seven_day",
|
||||
"utilization":0.8,"isUsingOverage":false,"surpassedThreshold":0.75,
|
||||
"unifiedWindows":{"five_hour":{"utilization":0.125,"resetsAt":1899990000,"status":"allowed"},
|
||||
"seven_day":{"utilization":0.8,"resetsAt":1900000000,"status":"allowed_warning","surpassedThreshold":0.75}}}`
|
||||
|
||||
func TestMergeRateLimitReadsUnifiedWindows(t *testing.T) {
|
||||
now := time.UnixMilli(1_800_000_000_000)
|
||||
got := mergeRateLimit(nil, json.RawMessage(unifiedRateLimit), "max", now)
|
||||
want := &protocol.ChatAccountUsage{
|
||||
Harness: "Claude Code", Source: "rate_limit_event", Plan: "max", AsOf: now.UnixMilli(),
|
||||
Windows: []protocol.ChatQuotaWindow{
|
||||
{ID: "five_hour", Label: "5-hour", UsedPercent: 12.5, ResetsAt: 1_899_990_000_000},
|
||||
{ID: "seven_day", Label: "Weekly", UsedPercent: 80, ResetsAt: 1_900_000_000_000},
|
||||
},
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("merged = %+v\nwant %+v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergeRateLimitKeepsUnmentionedWindowsAndIgnoresStatusOnly(t *testing.T) {
|
||||
now := time.UnixMilli(1_800_000_000_000)
|
||||
first := mergeRateLimit(nil, json.RawMessage(unifiedRateLimit), "pro", now)
|
||||
// A top-level-only event (older CLIs, or no unifiedWindows) updates its window.
|
||||
later := now.Add(time.Minute)
|
||||
next := mergeRateLimit(first, json.RawMessage(`{"status":"allowed","rateLimitType":"five_hour","utilization":0.5,"resetsAt":1899990000}`), "", later)
|
||||
if next == nil || len(next.Windows) != 2 || next.Windows[0].UsedPercent != 50 || next.Windows[1].UsedPercent != 80 {
|
||||
t.Fatalf("merge = %+v", next)
|
||||
}
|
||||
if next.Plan != "pro" || next.AsOf != later.UnixMilli() {
|
||||
t.Fatalf("plan/as_of = %q %d", next.Plan, next.AsOf)
|
||||
}
|
||||
for _, raw := range []string{
|
||||
`{"status":"rejected","rateLimitType":"five_hour"}`, // no utilization: nothing to show
|
||||
`{"status":"allowed","rateLimitType":"overage","utilization":0.2}`,
|
||||
`not json`,
|
||||
} {
|
||||
if got := mergeRateLimit(first, json.RawMessage(raw), "", later); got != nil {
|
||||
t.Fatalf("%s merged into %+v", raw, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeAccountIdentity(t *testing.T) {
|
||||
got := decodeAccountIdentity(json.RawMessage(`{"email":"a@example.invalid","organization":"Org","subscriptionType":"max","apiProvider":"firstParty"}`))
|
||||
if got.key == "" || got.plan != "max" {
|
||||
t.Fatalf("identity = %+v", got)
|
||||
}
|
||||
if empty := decodeAccountIdentity(json.RawMessage(`{}`)); empty.key != "" || empty.plan != "" {
|
||||
t.Fatalf("empty account = %+v", empty)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRateLimitEventReachesEverySessionOfTheAccount(t *testing.T) {
|
||||
t.Setenv("FAKE_CLAUDE_RATE_LIMIT", "1")
|
||||
chat := testChat(t)
|
||||
first := newCreatedChat(t, chat)
|
||||
frames := subscribe(t, chat, first.ID)
|
||||
if err := chat.Prompt(context.Background(), first.ID, "hello"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
quota := waitFrame(t, frames, "account usage", func(frame protocol.ChatEventFrame) bool {
|
||||
return frame.Kind == protocol.ChatEventUsage && frame.Usage != nil && frame.Usage.Account != nil
|
||||
}).Usage.Account
|
||||
if quota.Plan != "max" || len(quota.Windows) != 2 || quota.Windows[0].Label != "5-hour" || quota.Windows[0].UsedPercent != 42 ||
|
||||
quota.Windows[1].Label != "Weekly" || quota.Windows[1].UsedPercent != 73.1 || quota.Windows[1].ResetsAt != 1_900_400_000_000 {
|
||||
t.Fatalf("account usage = %+v", quota)
|
||||
}
|
||||
// The token snapshot that follows still carries the quota.
|
||||
tokens := waitFrame(t, frames, "token usage", func(frame protocol.ChatEventFrame) bool {
|
||||
return frame.Kind == protocol.ChatEventUsage && frame.Usage != nil && frame.Usage.TotalTokens != nil
|
||||
}).Usage
|
||||
if tokens.Account == nil || len(tokens.Account.Windows) != 2 {
|
||||
t.Fatalf("token usage lost the account quota: %+v", tokens)
|
||||
}
|
||||
|
||||
// A second chat on the same account learns the quota once its process
|
||||
// identifies the account, without a turn of its own.
|
||||
second := newCreatedChat(t, chat)
|
||||
s := chat.sessionFor(second.ID, "")
|
||||
if _, err := s.ensureProcess(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
other := subscribe(t, chat, second.ID)
|
||||
replayed := waitFrame(t, other, "replayed account usage", func(frame protocol.ChatEventFrame) bool {
|
||||
return frame.Kind == protocol.ChatEventUsage && frame.Usage != nil && frame.Usage.Account != nil
|
||||
}).Usage
|
||||
if replayed.Scope != "" || replayed.TotalTokens != nil || len(replayed.Account.Windows) != 2 {
|
||||
t.Fatalf("replay invented token usage or lost quota: %+v", replayed)
|
||||
}
|
||||
}
|
||||
+10
@@ -126,6 +126,14 @@ def user_message(text):
|
||||
|
||||
|
||||
def finish(message_id):
|
||||
# Shape of SDKRateLimitEvent in Claude Code 2.1.316 (synthetic numbers).
|
||||
if os.environ.get("FAKE_CLAUDE_RATE_LIMIT"):
|
||||
send({"type": "rate_limit_event", "uuid": "rate-%d" % state["turn"], "session_id": state["session"],
|
||||
"rate_limit_info": {"status": "allowed", "resetsAt": 1900000000, "rateLimitType": "five_hour",
|
||||
"utilization": 0.42, "isUsingOverage": False,
|
||||
"unifiedWindows": {
|
||||
"five_hour": {"utilization": 0.42, "resetsAt": 1900000000, "status": "allowed"},
|
||||
"seven_day": {"utilization": 0.731, "resetsAt": 1900400000}}}})
|
||||
send({"type": "result", "subtype": "success", "is_error": False, "result": "Hello world",
|
||||
"session_id": state["session"], "total_cost_usd": 0.25,
|
||||
"usage": {"input_tokens": 10, "output_tokens": 20}})
|
||||
@@ -160,6 +168,8 @@ def handle(line):
|
||||
{"value": "haiku", "displayName": "Haiku", "description": "Haiku model"},
|
||||
],
|
||||
"commands": [], "agents": [],
|
||||
"account": {"email": "fixture@example.invalid", "organization": "Fixture Org",
|
||||
"subscriptionType": "max", "apiProvider": "firstParty"},
|
||||
})
|
||||
elif subtype == "set_model":
|
||||
state["model"] = request.get("model")
|
||||
|
||||
@@ -38,6 +38,8 @@ type lineEnvelope struct {
|
||||
// a task notification, a reminder); see classifyInjected.
|
||||
Origin json.RawMessage `json:"origin"`
|
||||
IsMeta bool `json:"isMeta"`
|
||||
// RateLimitInfo is the payload of a rate_limit_event line (see quota.go).
|
||||
RateLimitInfo json.RawMessage `json:"rate_limit_info"`
|
||||
}
|
||||
|
||||
type contentBlock struct {
|
||||
@@ -115,6 +117,8 @@ func (s *session) handleLine(p *process, line []byte) {
|
||||
s.handleUser(envelope)
|
||||
case "result":
|
||||
s.handleResult(envelope)
|
||||
case "rate_limit_event":
|
||||
s.handleRateLimit(envelope.RateLimitInfo)
|
||||
case "system":
|
||||
if envelope.Subtype == "task_notification" {
|
||||
s.finishNotifiedTask(line)
|
||||
|
||||
Reference in New Issue
Block a user