Files
pipelines/internal/claude/auto_switch.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

221 lines
6.8 KiB
Go

package claude
import (
"context"
"errors"
"sort"
"strings"
"sync"
"time"
"git.a-wan.net/alan/pipelines/internal/claudeaccounts"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Automatic account switching: when a chat's turn is refused for a usage
// limit and its Claude home has another saved account with usage left, the
// home is switched to it (the claude_account_use path, under the same locks)
// so the server can continue the chat there. Switches of one home are
// serialized, so chats refused together switch once.
var (
// ErrAutoSwitchOff is returned when the Claude home's operator turned
// automatic switching off.
ErrAutoSwitchOff = errors.New("automatic Claude account switching is off for this Claude home")
// ErrNoAccountLeft is returned when no other saved account is known to
// have usage left.
ErrNoAccountLeft = errors.New("no other saved Claude account has usage left")
)
// refusalHold is how long a refused account is passed over when neither its
// quota nor the refusal said when its limit resets.
const refusalHold = time.Hour
// AutoSwitch is the outcome of AutoSwitchAccount.
type AutoSwitch struct {
// From is the account that was refused and To the one the home is
// signed in to now.
From, To string
// Switched is false when another refused chat on the same home had
// already switched it to To, which still has usage.
Switched bool
// Usage is To's latest known quota (marked switched when Switched).
Usage *protocol.ChatAccountUsage
}
// AutoSwitchAccount handles one usage-limit refusal: it marks the refused
// account as out of usage and, when the chat's Claude home allows automatic
// switching, signs the home in to the saved account with the lowest known
// usage that is not exhausted (an account with no known quota is still worth
// trying, after those known to have usage). It reports ErrAutoSwitchOff,
// ErrNoAccountLeft or ErrNoConfigDir when nothing is switched.
func (c *Chat) AutoSwitchAccount(ctx context.Context, refusal UsageRefusal) (AutoSwitch, error) {
directory := refusal.Directory
if strings.TrimSpace(directory) == "" {
if s := c.session(refusal.SessionID); s != nil {
s.mu.Lock()
directory = s.directory
s.mu.Unlock()
}
}
configDir, err := c.accountConfigDir(ctx, directory)
if err != nil {
return AutoSwitch{}, err
}
lock := c.autoLock(configDir)
lock.Lock()
defer lock.Unlock()
store := claudeaccounts.Store{ConfigDir: configDir}
if !store.AutoSwitch() {
return AutoSwitch{}, ErrAutoSwitchOff
}
list, err := store.List()
if err != nil {
return AutoSwitch{}, err
}
if list.Active == nil {
return AutoSwitch{}, ErrNoAccountLeft
}
now := time.Now()
from := strings.TrimSpace(refusal.Email)
if from == "" {
from = list.Active.Email
}
c.markRefused(from, organizationOf(list, from), now)
active := *list.Active
if !strings.EqualFold(active.Email, from) && c.usable(active, now) {
// Another chat's refusal already moved the home on.
identity := accountIdentity{key: accountKeyFor(active.Email, active.Organization), plan: active.Plan, email: active.Email, organization: active.Organization}
return AutoSwitch{From: from, To: active.Email, Usage: c.accountUsage(identity)}, nil
}
candidate, ok := c.pickAccount(list, from, now)
if !ok {
return AutoSwitch{}, ErrNoAccountLeft
}
switched, err := c.useAccount(ctx, configDir, store, candidate.Name)
if err != nil {
return AutoSwitch{}, err
}
to := candidate.Email
if switched.Active != nil {
to = switched.Active.Email
}
return AutoSwitch{From: from, To: to, Switched: true, Usage: switched.Usage}, nil
}
func (c *Chat) autoLock(configDir string) *sync.Mutex {
c.autoMu.Lock()
defer c.autoMu.Unlock()
if c.autoLocks == nil {
c.autoLocks = map[string]*sync.Mutex{}
}
lock := c.autoLocks[configDir]
if lock == nil {
lock = &sync.Mutex{}
c.autoLocks[configDir] = lock
}
return lock
}
func organizationOf(list protocol.ClaudeAccountList, email string) string {
if list.Active != nil && strings.EqualFold(list.Active.Email, email) {
return list.Active.Organization
}
for _, account := range list.Accounts {
if strings.EqualFold(account.Email, email) {
return account.Organization
}
}
return ""
}
// markRefused passes over email until its limit resets: the reset a
// rejected rate_limit_event named, else the latest reset of its exhausted
// windows, else refusalHold from now.
func (c *Chat) markRefused(email, organization string, now time.Time) {
if strings.TrimSpace(email) == "" {
return
}
c.quotaMu.Lock()
defer c.quotaMu.Unlock()
if c.rejectedUntil[strings.ToLower(strings.TrimSpace(email))].After(now) {
return
}
until := now.Add(refusalHold)
if quota := c.quotas[accountKeyFor(email, organization)]; quota != nil {
latest := int64(0)
for _, w := range quota.Windows {
if w.UsedPercent >= 100 && w.ResetsAt > now.UnixMilli() && w.ResetsAt > latest {
latest = w.ResetsAt
}
}
if latest > 0 {
until = time.UnixMilli(latest)
}
}
c.noteRejectedLocked(email, until)
}
// usable reports whether account is neither marked refused nor known to be
// out of usage.
func (c *Chat) usable(account protocol.ClaudeAccount, now time.Time) bool {
_, _, ok := c.usageLeft(account, now)
return ok
}
// usageLeft is account's highest current window use (known false when no
// quota is known) and whether it can take a turn now.
func (c *Chat) usageLeft(account protocol.ClaudeAccount, now time.Time) (percent float64, known, ok bool) {
c.quotaMu.Lock()
defer c.quotaMu.Unlock()
if c.rejectedUntil[strings.ToLower(strings.TrimSpace(account.Email))].After(now) {
return 0, false, false
}
quota := c.quotas[accountKeyFor(account.Email, account.Organization)]
if quota == nil || len(quota.Windows) == 0 {
return 0, false, true
}
for _, w := range quota.Windows {
if w.ResetsAt != 0 && w.ResetsAt <= now.UnixMilli() {
continue // reset since it was reported
}
if w.UsedPercent >= 100 {
return w.UsedPercent, true, false
}
if w.UsedPercent > percent {
percent = w.UsedPercent
}
}
return percent, true, true
}
// pickAccount chooses the saved account to switch to after from was refused.
func (c *Chat) pickAccount(list protocol.ClaudeAccountList, from string, now time.Time) (protocol.ClaudeAccount, bool) {
type option struct {
account protocol.ClaudeAccount
percent float64
known bool
}
var options []option
for _, account := range list.Accounts {
if account.Active || !account.Saved || strings.EqualFold(account.Email, from) {
continue
}
percent, known, ok := c.usageLeft(account, now)
if ok {
options = append(options, option{account, percent, known})
}
}
if len(options) == 0 {
return protocol.ClaudeAccount{}, false
}
sort.SliceStable(options, func(i, j int) bool {
a, b := options[i], options[j]
if a.known != b.known {
return a.known
}
return a.percent < b.percent
})
return options[0].account, true
}