Files
pipelines/internal/claude/quota.go
T
alan ed9072b79a Claude accounts: switch a chat refused for usage to another saved account and continue it
When Claude Code refuses an operator chat's turn for a usage limit, the
server marks the refused account until its reset and, if the chat's Claude
home allows it (claude_account_auto_switch / `pipelines claude-account auto
on|off`, on by default, kept in pipelines-accounts/settings.json), switches
the home to the saved account with the most usage left through the
claude_account_use path. Switches of one home are serialized, so chats
refused together switch once. Each refused chat gets one queued prompt,
marked as sent automatically, that asks the agent to check it is on track
before continuing; the app's auto-continue-at-reset prompt for the refusal is
removed (and refused if it arrives later), and the operator gets a
low-priority notification.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 00:23:43 +00:00

272 lines
8.5 KiB
Go

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. email
// and organization name the account to the operator (usage.account).
type accountIdentity struct {
key string
plan string
email string
organization 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),
email: strings.TrimSpace(account.Email),
organization: strings.TrimSpace(account.Organization),
}
}
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"`
// Extra usage ("overage"): paid usage credits past the subscription
// limits. Claude Code reports whether they would be accepted, whether
// they are in use and why they are off; nothing here applies them.
OverageStatus string `json:"overageStatus"`
OverageResetsAt *float64 `json:"overageResetsAt"`
OverageDisabledReason string `json:"overageDisabledReason"`
IsUsingOverage *bool `json:"isUsingOverage"`
OverageInUse *bool `json:"overageInUse"`
}
// extraUsage is the event's overage state, or nil when it names none.
func (info rateLimitInfo) extraUsage() *protocol.ChatExtraUsage {
if info.OverageStatus == "" && info.OverageDisabledReason == "" {
return nil
}
inUse := (info.IsUsingOverage != nil && *info.IsUsingOverage) ||
(info.OverageInUse != nil && *info.OverageInUse)
extra := &protocol.ChatExtraUsage{
Status: info.OverageStatus,
InUse: inUse,
DisabledReason: info.OverageDisabledReason,
}
if at := info.OverageResetsAt; at != nil && *at > 0 && !math.IsInf(*at, 0) {
extra.ResetsAt = int64(*at * 1000)
}
return extra
}
// 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
}
}
// Overage news alone updates a report that already has windows.
extra := info.extraUsage()
if extra != nil && previous != nil {
changed = true
}
if !changed {
return nil
}
next := &protocol.ChatAccountUsage{Harness: quotaHarness, Source: quotaSource, Plan: plan, AsOf: now.UnixMilli()}
if previous != nil {
if next.Plan == "" {
next.Plan = previous.Plan
}
// A switch stays recorded: the refusal it cleared is still in the
// transcript.
next.SwitchedAt = previous.SwitchedAt
if extra == nil && previous.ExtraUsage != nil {
kept := *previous.ExtraUsage
extra = &kept
}
}
next.ExtraUsage = extra
for _, entry := range quotaWindowOrder {
if w, ok := windows[entry.id]; ok {
next.Windows = append(next.Windows, w)
}
}
return next
}
// 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()
if until, ok := rejectedUntil(raw); ok {
c.noteRejectedLocked(account.email, until)
}
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()
}
}
}
// rejectedUntil reports when a rejected rate_limit_event's limit resets: a
// refusal the account cannot draw extra usage past.
func rejectedUntil(raw json.RawMessage) (time.Time, bool) {
var info rateLimitInfo
if len(raw) == 0 || json.Unmarshal(raw, &info) != nil || info.Status != "rejected" {
return time.Time{}, false
}
if extra := info.extraUsage(); extra != nil && extra.InUse {
return time.Time{}, false
}
if info.ResetsAt == nil || *info.ResetsAt <= 0 || math.IsInf(*info.ResetsAt, 0) {
return time.Time{}, false
}
return time.UnixMilli(int64(*info.ResetsAt * 1000)), true
}
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 = &copy
}
s.mu.Unlock()
s.emit(protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventUsage, Usage: usage})
}