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: 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 } return protocol.ClaudeAccountList{}, errors.New("unknown Claude account operation " + operation) } // 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 }