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}) }