Documentation
¶
Overview ¶
Package daemon holds the ccswap daemon's API server, client and account importer.
Index ¶
- Constants
- Variables
- func Dial(socketPath string) (*api.ClientWithResponses, error)
- func DropLogin(dir, target string, kc keychain.Store, imported bool)
- func Serve(ctx context.Context, socketPath, lockPath string, core Core) error
- func SweepLogins(home, target string, kc keychain.Store)
- type Core
- type Daemon
- func (d *Daemon) Accounts(context.Context) ([]api.Account, error)
- func (d *Daemon) Activate(ctx context.Context, name string, force bool) (api.Status, error)
- func (d *Daemon) Adopt(ctx context.Context, r api.AdoptRequest) (api.Account, error)
- func (d *Daemon) CancelLogin(_ context.Context, name, id string) error
- func (d *Daemon) FinishLogin(ctx context.Context, name, id, code string) (api.Account, error)
- func (d *Daemon) Import(ctx context.Context, r api.ImportRequest) (api.Account, error)
- func (d *Daemon) InstallUpdate(ctx context.Context) (api.Release, error)
- func (d *Daemon) MigrateCancel(_ context.Context, token string) error
- func (d *Daemon) MigrateCommit(ctx context.Context, token string) error
- func (d *Daemon) MigrateExport(_ context.Context, names []string) (api.MigrateExport, error)
- func (d *Daemon) MigrateImport(ctx context.Context, r api.MigrateImportRequest) (api.MigrateImport, error)
- func (d *Daemon) Patch(_ context.Context, name string, p api.AccountPatch) (api.Account, error)
- func (d *Daemon) Poll(ctx context.Context)
- func (d *Daemon) Refresh(ctx context.Context) error
- func (d *Daemon) RefreshLogin(ctx context.Context, name string) (api.Account, error)
- func (d *Daemon) Remove(_ context.Context, name string) error
- func (d *Daemon) Restart(_ context.Context, bin string) (api.Restart, error)
- func (d *Daemon) Run(ctx context.Context) error
- func (d *Daemon) SetAuto(_ context.Context, on bool) error
- func (d *Daemon) SetLang(_ context.Context, lang string) error
- func (d *Daemon) SetRemote(ctx context.Context, r api.RemoteRequest) error
- func (d *Daemon) SetStrategy(_ context.Context, s api.Strategy) error
- func (d *Daemon) SetThresholds(_ context.Context, t api.Thresholds) (api.Thresholds, error)
- func (d *Daemon) Signal(ctx context.Context, p map[string]any) error
- func (d *Daemon) StartLogin(ctx context.Context, name string, replace bool) (api.LoginLink, error)
- func (d *Daemon) Status(context.Context) (api.Status, error)
- func (d *Daemon) StoredAccounts() []store.Account
- func (d *Daemon) Subscribe() (<-chan struct{}, func())
- func (d *Daemon) UsageRaw(ctx context.Context, name string, maxAge time.Duration) (int, []byte, error)
- func (d *Daemon) UseReset(ctx context.Context, name string, left int) (api.Account, error)
- func (d *Daemon) UseWebCode(_ context.Context, code string) error
- func (d *Daemon) Version() string
- func (d *Daemon) WebCode(context.Context) (api.WebCode, error)
- type Importer
- type Locker
- type Options
Constants ¶
const ExitAlreadyRunning = 3
ExitAlreadyRunning is the exit status of `ccswap daemon run` that finds another daemon; the systemd unit does not restart on it, or it would try again every few seconds for as long as the other runs.
const ExitConfig = 78
ExitConfig is the exit status of `ccswap daemon run` that cannot start from its files and folders: $CCSWAP_HOME is relative, ccswap's folder or the user's home folder cannot be found, ccswap's folder cannot be created or made 0700, it is too long a path for the socket, or config.toml or state.json does not load. Every start fails the same way, so the systemd unit does not restart on it either. It is EX_CONFIG of sysexits.h, which systemd shows as 78/CONFIG.
Variables ¶
var ( // ErrClaudeOwns: the login is the one Claude Code uses, which only Claude Code refreshes. ErrClaudeOwns error = i18n.Err("daemon.claude_owns") // ErrRefreshFailed: Anthropic did not refresh the login, for a reason other than a spent one. ErrRefreshFailed error = i18n.Err("daemon.refresh_failed") )
var ( ErrNotFound = errors.New("account not found") ErrRemoveActive = errors.New("cannot remove the active account") ErrLoginIncomplete = errors.New("login was not completed") ErrActiveAccount = errors.New("this is the active account: re-login it with `claude /login`") ErrInvalidName = errors.New("invalid account name") ErrInvalidThresholds = errors.New("invalid thresholds") ErrInvalidStrategy = errors.New("invalid strategy") ErrInvalidLang = errors.New("invalid language") ErrNoEntry = errors.New("Claude Code has no login") //lint:ignore ST1005 "Claude Code" is a proper noun // ErrInvalidConfigDir: config_dir is not a login dir `ccswap login` made in the ccswap home. ErrInvalidConfigDir = errors.New("config_dir is not a ccswap login directory") )
var ( // ErrLoginGone: no link of the account with that id waits for a code. ErrLoginGone error = i18n.Err("daemon.login_link_gone") // ErrCodeRefused: claude got no login for the code; the link is spent. ErrCodeRefused error = i18n.Err("daemon.code_refused") // ErrEmptyCode: the page sent no code. ErrEmptyCode error = i18n.Err("daemon.code_empty") // ErrLoginFailed: claude auth login did not start, gave no link, or did not answer the code in time. ErrLoginFailed = errors.New("claude auth login failed") // ErrWrongAccount: the sign-in was another account's. ErrWrongAccount = errors.New("another account's login") // ErrLoginPending: a link of the account waits for its code, and the caller may not replace it. ErrLoginPending = errors.New("a login of the account is pending") // ErrLoginCooldown: the account's last start was under loginCooldown ago, and the caller may not replace. ErrLoginCooldown = errors.New("a login of the account started moments ago") )
var ( // ErrMigrateActive: Claude Code uses the account, or holds its login, so it cannot move. ErrMigrateActive = errors.New("the account is in use in Claude Code") // ErrTokensChanged: a login changed since packing, so the bundle may hold a spent token. ErrTokensChanged = errors.New("a login changed since it was packed") // ErrBundleSpent: the bundle's login was used already, so it replaces no login here. ErrBundleSpent = errors.New("the bundle's login was used already") // ErrBundleUnchecked: the bundle's login was not refreshed (Anthropic failed, or no time was left), so it // replaces no login here yet. ErrBundleUnchecked = errors.New("the bundle's login could not be checked") )
The errors that name an account are wrapped in a text that names it.
var ( // ErrExportGone: no export has the token; a restart forgets every export. ErrExportGone error = i18n.Err("daemon.export_gone") // ErrExportDone: the export is committed, so it cannot be cancelled. ErrExportDone error = i18n.Err("daemon.export_done") )
var ( // ErrNoResetCredit: the account has no reset credit left, as ccswap last saw or as Anthropic says. ErrNoResetCredit = errors.New("no reset credit left") // ErrResetChanged: the caller showed another count of reset credits than the daemon has, or another // claim spent the credit first. ErrResetChanged = errors.New("reset credits changed") // ErrNotLimited: Anthropic spends the credit only at a limit. ErrNotLimited = errors.New("not at a limit") // ErrResetCooldown: Anthropic wants a pause between resets. ErrResetCooldown = errors.New("reset cooldown") )
var ( ErrNoUpdate error = i18n.Err("daemon.no_update") ErrUpdating error = i18n.Err("daemon.updating") )
var ErrAlreadyRunning error = i18n.Err("daemon.already_running")
ErrAlreadyRunning: another daemon holds the lock or answers on the socket.
var ErrBadCode error = i18n.Err("daemon.bad_code")
var ErrInvalidRemote = errors.New("invalid remote")
var ErrRestart = errors.New("restart on the updated binary")
ErrRestart: Run stopped because an update replaced the daemon's binary; the caller runs it in its place.
Functions ¶
func Dial ¶
func Dial(socketPath string) (*api.ClientWithResponses, error)
Dial returns the generated API client talking to the daemon over its unix socket. Callers bound each call with a context; the client's own timeout only caps the slowest (mutating) one.
func DropLogin ¶ added in v0.2.0
DropLogin removes a login dir; unless the import succeeded (the importer then deletes them itself) it also deletes any keychain item claude created under the dir's hashed service. A dir that is the live login's (target) is left alone.
func Serve ¶
Serve answers the API on a unix socket until ctx is cancelled, holding the flock on lockPath.
func SweepLogins ¶ added in v0.2.0
SweepLogins drops the login dirs of home left over an hour ago by a killed ccswap login or daemon.
Types ¶
type Core ¶
type Core interface {
Status(ctx context.Context) (api.Status, error)
Accounts(ctx context.Context) ([]api.Account, error)
Import(ctx context.Context, r api.ImportRequest) (api.Account, error)
Adopt(ctx context.Context, r api.AdoptRequest) (api.Account, error)
Patch(ctx context.Context, name string, p api.AccountPatch) (api.Account, error)
Remove(ctx context.Context, name string) error
Activate(ctx context.Context, name string, force bool) (api.Status, error)
SetAuto(ctx context.Context, enabled bool) error
SetThresholds(ctx context.Context, t api.Thresholds) (api.Thresholds, error)
SetStrategy(ctx context.Context, s api.Strategy) error
SetLang(ctx context.Context, lang string) error
SetRemote(ctx context.Context, r api.RemoteRequest) error
// Subscribe nudges the returned channel whenever status or accounts may have changed and
// closes it when the daemon stops.
Subscribe() (changed <-chan struct{}, cancel func())
Refresh(ctx context.Context) error
// RefreshLogin refreshes one account's login in the vault now.
RefreshLogin(ctx context.Context, name string) (api.Account, error)
// UseReset spends one of an account's reset credits, when it has left of them.
UseReset(ctx context.Context, name string, left int) (api.Account, error)
// StartLogin runs claude auth login for an account and returns its sign-in link, replacing a link that
// waits for its code only with replace; FinishLogin hands the link of an id the code the sign-in showed
// and stores the login; CancelLogin drops the link of an id.
StartLogin(ctx context.Context, name string, replace bool) (api.LoginLink, error)
FinishLogin(ctx context.Context, name, id, code string) (api.Account, error)
CancelLogin(ctx context.Context, name, id string) error
Signal(ctx context.Context, payload map[string]any) error
// WebCode mints a one-time code that the TCP listener trades for its admin key; UseWebCode takes
// it, once.
WebCode(ctx context.Context) (api.WebCode, error)
UseWebCode(ctx context.Context, code string) error
// MigrateExport packs accounts into a bundle and freezes them until MigrateCommit removes them here
// or MigrateCancel thaws them; MigrateImport adds the accounts of a bundle. Unix socket only.
MigrateExport(ctx context.Context, names []string) (api.MigrateExport, error)
MigrateCommit(ctx context.Context, token string) error
MigrateCancel(ctx context.Context, token string) error
MigrateImport(ctx context.Context, r api.MigrateImportRequest) (api.MigrateImport, error)
// InstallUpdate installs the newest release over the daemon's binary, then restarts the daemon on it.
InstallUpdate(ctx context.Context) (api.Release, error)
// Restart restarts the daemon on its binary when that binary is bin, which ccswap update replaced.
Restart(ctx context.Context, bin string) (api.Restart, error)
// Version is the build the daemon runs.
Version() string
}
Core is what the API needs from the daemon.
type Daemon ¶
type Daemon struct {
// contains filtered or unexported fields
}
func (*Daemon) Activate ¶
Activate is a manual switch; the switcher's non-fatal warning goes into Status.warning.
func (*Daemon) CancelLogin ¶ added in v0.2.0
CancelLogin drops name's link id and stops its claude, if there is one.
func (*Daemon) FinishLogin ¶ added in v0.2.0
FinishLogin hands the claude of name's link id the code and imports the login it gets. The link is spent either way.
func (*Daemon) InstallUpdate ¶ added in v0.2.0
InstallUpdate installs the newest release over the daemon's binary and stops Run with ErrRestart. It answers once the new binary is in place; an update that fails leaves the old binary and the daemon as they were.
func (*Daemon) MigrateCancel ¶
MigrateCancel drops an export that is not committed, expired or not; its accounts stay and thaw. An unknown token is ErrExportGone, not a success: a restart forgets a commit that landed just before it.
func (*Daemon) MigrateCommit ¶
MigrateCommit removes an export's accounts here once they are checked unchanged since packing; any failure cancels the export instead, so the accounts stay. A repeat commit is a no-op.
func (*Daemon) MigrateExport ¶
MigrateExport packs names into a bundle and freezes them until MigrateCommit removes them, or MigrateCancel, a restart or migrateTTL lifts the freeze. All under the switcher lock, so no refresh or switch lands between packing and freezing; no network call inside.
func (*Daemon) MigrateImport ¶
func (d *Daemon) MigrateImport(ctx context.Context, r api.MigrateImportRequest) (api.MigrateImport, error)
MigrateImport adds the accounts of a bundle, all or none, then refreshes each at once: the bundle's refresh token is spent here, so a second import of the same bundle gets a dead login. A refresh that fails is forced again on each tick until one spends it. An account that replaces one here is refreshed first, before anything is written, so a spent bundle never replaces a working login.
func (*Daemon) Poll ¶
Poll runs one tick: reconcile, refresh vault tokens, fetch usage, auto-switch.
func (*Daemon) Refresh ¶
Refresh runs a tick now (after the running one, if any) that asks the usage of every enabled account that needs no login, except one asked under refreshFloor ago or told to wait by a 429, and returns when it is done.
func (*Daemon) RefreshLogin ¶ added in v0.2.0
RefreshLogin refreshes name's login in the vault now, unless ccswap refreshed it under refreshFloor ago, and returns the account as it is then.
func (*Daemon) Restart ¶ added in v0.2.0
Restart restarts the daemon on its binary as InstallUpdate does, when that binary is bin: ccswap update has just installed a release over it. A daemon that runs another binary carries on and says which.
func (*Daemon) Run ¶
Run serves the API and ticks every PollInterval (and on request) until ctx is cancelled.
func (*Daemon) SetLang ¶
SetLang pins the language of the daemon's messages and notifications in config.toml, or with "" lets its locale pick it, and speaks it from now on.
func (*Daemon) SetRemote ¶
SetRemote checks that url answers to key before keeping either; an empty url turns remote usage off.
func (*Daemon) SetThresholds ¶
func (d *Daemon) SetThresholds(_ context.Context, t api.Thresholds) (api.Thresholds, error)
SetThresholds saves t to config.toml, then switches by it from the next tick, which it requests.
func (*Daemon) Signal ¶
Signal handles a StopFailure hook payload: a subscription limit marks the active account and ticks at once; every other error is ignored.
func (*Daemon) StartLogin ¶ added in v0.2.0
StartLogin runs `claude auth login` for name and returns its link. A link of name that waits for its code makes it ErrLoginPending, unless replace: the new link then replaces it once it is up. Without replace, a start under loginCooldown after name's last one is ErrLoginCooldown.
func (*Daemon) StoredAccounts ¶
func (*Daemon) UsageRaw ¶
func (d *Daemon) UsageRaw(ctx context.Context, name string, maxAge time.Duration) (int, []byte, error)
UsageRaw returns name's upstream usage response, from cache when younger than maxAge, else live, or from the ask of name in flight, waited for; when no live fetch is possible (an idle entry's expired token, no connection) or allowed (a disabled account or one waiting for a login, which ccswap never asks for) the last cached response, however old.
func (*Daemon) UseReset ¶ added in v0.5.0
UseReset spends one of name's reset credits when the daemon has left of them, as the caller showed, then asks the account's usage again. Each claim has an id of its own, as Claude Code's do; only a retry of a claim Anthropic gave no sure answer to names it again, so Anthropic spends one credit for both.
func (*Daemon) UseWebCode ¶
UseWebCode takes a code from WebCode, once and within webCodeTTL. Each code is compared in constant time, so how long a guess takes tells nothing of the codes held.
type Importer ¶
type Importer struct {
KC keychain.Store
Store *store.Store
Profiles switcher.Profiler
Locker Locker
Home string // the ccswap home: login dirs are <Home>/login-*
Target string // Claude Code's entry ccswap switches; never read or deleted here
}
Importer turns a fresh `claude auth login` in a temp config dir into a stored account.
type Options ¶
type Options struct {
Config config.Config
Store *store.Store
KC keychain.Store
API *anthropic.Client
Switcher *switcher.Switcher
Notifier notify.Notifier
Now func() time.Time
Home string // the ccswap home (login dirs, daemon.log)
Socket string // unix socket of the daemon API
Projects string // Claude Code's transcripts, whose writes tell when it last made a request
LockPath string // one daemon per user, whatever CCSWAP_HOME says; default <config.DefaultHome>/daemon.lock
Version string
Host string
Bin string // the binary the daemon runs, which an update replaces
}