package claudeaccounts import ( "encoding/json" "errors" "io/fs" "os" "path/filepath" "git.a-wan.net/alan/pipelines/internal/protocol" ) // settingsFile holds the Claude home's account-switching preferences, beside // the saved slots (a file, so slots() never reads it as an account). const settingsFile = "settings.json" type settings struct { // AutoSwitch is nil until the operator chooses; the default is on. AutoSwitch *bool `json:"auto_switch,omitempty"` // AutoContinue is nil until the operator chooses; the default is on. AutoContinue *bool `json:"auto_continue,omitempty"` } func (s Store) readSettings() settings { var out settings data, err := os.ReadFile(filepath.Join(s.slotsDir(), settingsFile)) if err == nil { _ = json.Unmarshal(data, &out) } return out } // AutoSwitch reports whether a chat on this Claude home that runs out of // usage is switched to another saved account automatically (on by default). func (s Store) AutoSwitch() bool { if on := s.readSettings().AutoSwitch; on != nil { return *on } return true } // SetAutoSwitch records the automatic-switch preference and returns the // accounts list, which reports it. func (s Store) SetAutoSwitch(on bool) (protocol.ClaudeAccountList, error) { if err := s.updateSettings(func(current *settings) { current.AutoSwitch = &on }); err != nil { return protocol.ClaudeAccountList{}, err } return s.List() } // AutoContinue reports whether a chat on this Claude home that a usage limit // refused is continued automatically once the limit resets (on by default). func (s Store) AutoContinue() bool { if on := s.readSettings().AutoContinue; on != nil { return *on } return true } // SetAutoContinue records the auto-continue-at-reset preference. func (s Store) SetAutoContinue(on bool) error { return s.updateSettings(func(current *settings) { current.AutoContinue = &on }) } func (s Store) updateSettings(change func(*settings)) error { if err := s.check(); err != nil { return err } dir := s.slotsDir() if err := os.Mkdir(dir, 0o700); err != nil && !errors.Is(err, fs.ErrExist) { return err } current := s.readSettings() change(¤t) data, err := marshal(current) if err != nil { return err } path := filepath.Join(dir, settingsFile) if err := writeAtomic(path, data, 0o600); err != nil { return err } return os.Chmod(path, 0o600) }