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

161 lines
5.5 KiB
Go

package claude
import (
"context"
"errors"
"log"
"os"
"path/filepath"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/claudeaccounts"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
// Account switching (see internal/claudeaccounts) acts on the Claude Code home
// a chat's directory selects: the CLAUDE_CONFIG_DIR its processes run with.
// ErrNoConfigDir is returned for a chat whose directory selects no Claude
// home of its own.
var ErrNoConfigDir = errors.New("this chat's directory does not set CLAUDE_CONFIG_DIR, so it has no Claude home of its own to switch")
// AccountConfigDir is the CLAUDE_CONFIG_DIR a process started in directory
// runs with: the directory's own environment (direnv, mise) over base.
func AccountConfigDir(ctx context.Context, resolver *workenv.Resolver, directory string, base []string) (string, error) {
env := base
if resolver != nil && strings.TrimSpace(directory) != "" {
env = resolver.Resolve(ctx, directory, base).Apply(base)
}
dir, ok := envValue(env, "CLAUDE_CONFIG_DIR")
dir = strings.TrimSpace(dir)
if !ok || dir == "" || !filepath.IsAbs(dir) {
return "", ErrNoConfigDir
}
return filepath.Clean(dir), nil
}
func (c *Chat) accountConfigDir(ctx context.Context, directory string) (string, error) {
return AccountConfigDir(ctx, c.dirEnv, directory, os.Environ())
}
// accountKeyFor is the quota key decodeAccountIdentity derives from an
// initialize response for a subscription login.
func accountKeyFor(email, organization string) string {
return strings.TrimSpace(email) + "\x00" + strings.TrimSpace(organization) + "\x00" + "firstParty"
}
// ClaudeAccounts runs one claude_account* operation for the chat sessionID in
// directory ("" uses the open session's directory). After a switch every
// open chat on the same Claude home is moved to the new account's quota and
// told so, which clears a usage limit the old account had reached.
func (c *Chat) ClaudeAccounts(ctx context.Context, sessionID, directory, operation, name string) (protocol.ClaudeAccountList, error) {
if strings.TrimSpace(directory) == "" {
if s := c.session(sessionID); s != nil {
s.mu.Lock()
directory = s.directory
s.mu.Unlock()
}
}
configDir, err := c.accountConfigDir(ctx, directory)
if err != nil {
return protocol.ClaudeAccountList{}, err
}
store := claudeaccounts.Store{ConfigDir: configDir}
switch operation {
case protocol.ClaudeAccounts:
return store.List()
case protocol.ClaudeAccountSave:
return store.Save(name)
case protocol.ClaudeAccountRemove:
return store.Remove(name)
case protocol.ClaudeAccountUse:
return c.useAccount(ctx, configDir, store, name)
case protocol.ClaudeAccountAutoSwitch:
switch name {
case "on", "off":
return store.SetAutoSwitch(name == "on")
}
return protocol.ClaudeAccountList{}, errors.New(`automatic switching is "on" or "off"`)
}
return protocol.ClaudeAccountList{}, errors.New("unknown Claude account operation " + operation)
}
// useAccount makes the saved account name configDir's login and moves every
// open chat on that Claude home to it (claude_account_use and the automatic
// switch share it).
func (c *Chat) useAccount(ctx context.Context, configDir string, store claudeaccounts.Store, name string) (protocol.ClaudeAccountList, error) {
list, err := store.Use(name)
if err != nil {
return list, err
}
email, org, plan, ok := store.Identity()
if ok {
account := accountIdentity{key: accountKeyFor(email, org), plan: plan, email: strings.TrimSpace(email), organization: strings.TrimSpace(org)}
list.Usage = c.switchAccount(ctx, configDir, account)
log.Printf("claude account: %s switched to a saved account", configDir)
}
return list, nil
}
// switchAccount records that configDir now signs in as account: its quota
// report is marked switched (an empty one when nothing is known yet), and
// every open session on that Claude home takes the new account and
// republishes its usage, which names it.
func (c *Chat) switchAccount(ctx context.Context, configDir string, account accountIdentity) *protocol.ChatAccountUsage {
key := account.key
now := time.Now().UnixMilli()
c.quotaMu.Lock()
usage := c.quotas[key].Clone()
if usage == nil {
usage = &protocol.ChatAccountUsage{Harness: quotaHarness, Source: "account_switch", Plan: account.plan, AsOf: now}
}
usage.SwitchedAt = now
if c.quotas == nil {
c.quotas = map[string]*protocol.ChatAccountUsage{}
}
c.quotas[key] = usage
c.quotaMu.Unlock()
c.mu.Lock()
sessions := make([]*session, 0, len(c.sessions))
for _, s := range c.sessions {
sessions = append(sessions, s)
}
c.mu.Unlock()
for _, s := range sessions {
s.mu.Lock()
directory := s.directory
s.mu.Unlock()
if dir, err := c.accountConfigDir(ctx, directory); err != nil || dir != configDir {
continue
}
s.mu.Lock()
s.account = account
s.mu.Unlock()
s.republishUsage()
}
return c.accountUsage(account)
}
// accountUsage returns a copy of the latest quota for an account, naming the
// account. With no quota known yet it names the account alone; it is nil when
// neither is known (an API key login reports no email).
func (c *Chat) accountUsage(account accountIdentity) *protocol.ChatAccountUsage {
var usage *protocol.ChatAccountUsage
if account.key != "" {
c.quotaMu.Lock()
usage = c.quotas[account.key].Clone()
c.quotaMu.Unlock()
}
if account.email == "" {
return usage
}
if usage == nil {
usage = &protocol.ChatAccountUsage{Harness: quotaHarness, Source: "initialize", Plan: account.plan}
}
usage.Email, usage.Organization = account.email, account.organization
return usage
}