Files
pipelines/internal/claude/quota.go
T
alan 633b5953bb Chat: the server continues a usage-refused Claude chat at the reset
When Claude Code refuses an operator chat's turn for a usage limit and the
server does not continue it on another account, the server now queues a
durable prompt (auto-continue-<refusal id>, sent as Pipelines (automatic))
for a minute after the reset: the refused operator message when the turn
did no work, else "continue". The reset comes from the refusal's text,
else the rejected rate_limit_event. Refusals of turns Claude Code started
itself are handled too, with no client attached; a restarted server or a
device scheduling the same refusal adds nothing. The choice is kept per
Claude home beside auto-switch (or by the server for chats without one),
read and set with chat_auto_continue, on by default.

The app's limit banner now finds the refusal as the latest turn, ignoring
notices, agent reports and activity rows after it, reads and writes the
server's choice, and only schedules its own prompt for older servers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 19:52:03 +00:00

278 lines
8.6 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
until, rejected := rejectedUntil(raw)
if rejected {
s.mu.Lock()
s.noteRejectedResetLocked(until)
s.mu.Unlock()
}
c.quotaMu.Lock()
if rejected {
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})
}