store

package
v0.26.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package store persists the accounts ccdad manages.

Identity has four axes and three roles. uuid is the durable primary key: it survives an email change and a reordering, and it is what --json and exports carry. idx is a display ordinal for typing and for TUI hotkeys, numbered within a provider and therefore not unique on its own -- Account.Ref is the spelling that names exactly one account. email is the human label and may legitimately repeat across organizations. alias is an optional user handle.

idx is deliberately NOT a key. cswap keys its slots by number and has to move backups, aliases and session directories every time two accounts swap places; keying on uuid removes that whole class of migration work.

Index

Constants

View Source
const (
	ClaudePrefix = "c"
	CodexPrefix  = "x"
)

ClaudePrefix and CodexPrefix scope a display ordinal to its provider.

One character each, so a reference stays as short to type as the bare number it replaces. Codex takes 'x' rather than the initial it shares with nothing: 'c' is already Claude's, and a prefix that has to be looked up is a prefix nobody types.

They are lowercase because that is what a user types, and ValidateAlias refuses an alias of this shape for the same reason it refuses an all-digit one -- two axes that spell the same token must not name two accounts.

View Source
const ProfileRetryInterval = 15 * time.Minute

ProfileRetryInterval bounds retries across daemon ticks, restarts and CLI refreshes. Quota endpoint backoff does not apply to the profile endpoint.

View Source
const ProfileTTL = 24 * time.Hour

ProfileTTL is how long a profile reading stands before a poll spends a request re-reading it.

The number is COPIED from Claude Code rather than chosen. Its own cached profile is considered current while `Date.now()-profileFetchedAt < XH`, and `XH=86400000` in 2.1.246 -- one day. Picking a different figure here would mean the two programs re-read the same endpoint on different schedules for the same account, which is a second poller nobody asked for.

Variables

View Source
var (
	// ErrLockBusy means another process held the store lock for longer than
	// LockTimeout. It is a sentinel so a caller can tell contention — retry
	// later — from a filesystem that cannot lock at all.
	ErrLockBusy = errors.New("another process is holding the ccdad store")
	// ErrLocksUnsupported means this filesystem cannot do locks: ENOLCK on an
	// NFS or CIFS mount with no lock daemon, or a GOOS gofrs/flock has no
	// implementation for.
	//
	// It is a refusal, never a silent proceed. Writing anyway would be exactly
	// the lost-account race this lock exists to close, silently, on the one
	// class of machine where it is most likely to happen — a home directory on
	// a network mount is shared, so it is the case with the most writers.
	ErrLocksUnsupported = errors.New("this filesystem does not support locks")
)
View Source
var (
	// ErrNotFound means no account matched the reference.
	ErrNotFound = errors.New("no such account")
	// ErrAmbiguous means more than one account matched.
	ErrAmbiguous = errors.New("that reference matches more than one account")
	// ErrBadAlias means an alias failed validation.
	ErrBadAlias = errors.New("invalid alias")
	// ErrAliasTaken means the alias is well-formed but another account holds
	// it. It is separate from ErrBadAlias so a caller does not answer a
	// collision with advice about the charset.
	ErrAliasTaken = errors.New("alias already in use")
)
View Source
var ErrInterrupted = errors.New("interrupted")

ErrInterrupted means a signal arrived while a store transaction was writing.

It is a sentinel for two readers. internal/cli maps it to ExitInterrupted, so an interrupted `ccdad import` exits 130 like every other Ctrl-C in this binary rather than 1; and a caller that wants to distinguish "the user stopped this" from "the disk failed" has something to match on. Both messages wrapping it say which side of the commit the signal landed on, because the answer to "is my change saved" is opposite on the two sides.

View Source
var ErrNoCredentials = errors.New("no stored credentials")

ErrNoCredentials says this account has no credential file at all, as opposed to one this store could not READ. A caller about to REPLACE that file has to tell the two apart: nothing is at stake in the first case, and in the second what it is about to overwrite may hold the only copy of a secret.

View Source
var ErrNoProvider = errors.New("account has no provider")

ErrNoProvider is an account handed to Add with no provider on it. See add.

View Source
var ErrProviderMismatch = errors.New("that uuid is stored under a different provider")

ErrProviderMismatch is a re-add of a stored uuid under the other provider.

View Source
var ErrProviderMissing = errors.New("accounts.toml: row without a recognized provider; " +
	"restore each row's provider key, or set the document's version back to 1")

ErrProviderMissing is a row whose provider ccdad cannot make out. The wire text used to name only one cause -- a version-2 row missing the key -- but load reaches the same branch for a version-1 row carrying a value neither "claude" nor "codex", which is a different document and a different mistake; the text is version-agnostic now so it stops naming the wrong one.

It is loud rather than repaired because the repair would have to guess, and the wrong guess is the expensive one: a Codex row read as Claude reaches the switch that rewrites Claude Code's credentials file. There is also no in-product repair for the shape this leaves a downgraded store in -- every command but `uninstall` refuses until the document is fixed by hand -- which is why the wire text names both ways out.

View Source
var LockTimeout = 5 * time.Second

LockTimeout bounds how long a caller waits for the store lock.

The longest legitimate hold is a switch, which takes Claude Code's three credential locks inside this one; cclink.LockTimeout bounds each of those, so the worst case there is roughly three times that. This is deliberately shorter: a CLI command that cannot get in should say so rather than stall for half a minute, and the caller who lost is the one who can retry cheaply.

It is a var so a test can shrink it and reach the timeout path without an unbounded contention test.

Functions

func AccountsFileAt added in v0.3.0

func AccountsFileAt(root string) string

AccountsFileAt names the document. See CredentialsDirAt.

func CheckVersionAt added in v0.10.0

func CheckVersionAt(root string) error

CheckVersionAt reads a store's document and reports whether this build can use it, WITHOUT creating any part of it.

The daemon runs it at start and every CLI store open reaches the same rule through load. It is never run inside a tick: a document that became unreadable between two ticks is a fact about the machine, and re-deciding it on a cadence would turn one refusal into a log entry per second.

A store that is not there is not a store with a bad version, so it answers nil -- the same reading AccountsAt gives an absent document.

func CredentialsAt added in v0.13.0

func CredentialsAt(root, uuid string) (cclink.Blob, error)

CredentialsAt reads one account's stored keys from a root, without opening the store.

It is the same read Store.Credentials performs, with Open's tree creation, mode tightening and accounts.toml parse left out, for the reason AccountsAt leaves them out: a caller that already resolved the root should not have the store brought into existence, or refused, on its behalf.

The codex proxy is the caller that needed it. It is handed a credential reader once, at daemon start, and reads through it on every forwarded turn. An opened store there would have made an accounts.toml this build cannot parse -- a hand edit, a truncated write, a restored backup -- a refusal to start the daemon at all, and opening per turn would have put a MkdirAll and two chmods on the path of every codex request.

func CredentialsDirAt added in v0.3.0

func CredentialsDirAt(root string) string

CredentialsDirAt and AccountsFileAt name a store's two on-disk parts without resolving, creating or opening anything.

They exist because `ccdad doctor` had no way to say these two paths. It spelled both out itself and recorded why — "store exports no path accessors and opening it would create the tree" — which was the wrong generalisation from a true difficulty: LockPath was already exported, for this exact reason and saying so in its own comment, and what the credentials directory and the document lacked was an accessor of their own rather than a policy against having one. The duplicate is the kind that goes wrong quietly: a diagnostic holding its own copy of a naming rule keeps reporting on a directory the store has stopped using, and answers "nothing is wrong" from it.

func LockPath

func LockPath() (string, error)

LockPath is the store lock's path. `ccdad doctor` reports the layout, so the name lives in one place rather than in a string literal per reader.

func NormalizeAlias

func NormalizeAlias(alias string) string

NormalizeAlias lowercases and trims an alias to its stored form.

func OrphanCredentialsAt added in v0.3.0

func OrphanCredentialsAt(root string) ([]string, error)

OrphanCredentialsAt returns the paths of credential files under root that no account names, sorted.

Such a file is a leak that nothing else on the machine can find. `ccdad list`, `ccdad remove` and doctor's account rows all read accounts.toml, and an orphan is by definition a uuid the document does not carry — so it sits there holding a live refresh token at 0600, indefinitely. rollback narrowed the way they are MADE — it runs from a defer now, and mutate holds SIGINT across the write — but it did not close it, because SIGKILL and a power cut are not closable, and it does nothing at all for a store that already has one, left by an older build or by a reversal whose os.Remove was refused.

It reads under the store lock, unlike AccountsAt, and unlike its own first draft: see the lock paragraph below. A store that is not there still yields no orphans rather than being brought into existence by the probe asking about it. An unreadable accounts.toml is an ERROR rather than an empty answer — "nothing is orphaned", said out of a read that failed, is precisely the reassuring lie the caller exists to remove.

The rule is a file named <uuid>.json, which is credentialPath's rule read backwards, with two departures both of which are about not lying to the caller. The suffix is matched WITHOUT case, on every platform, because macOS and Windows hand credentialPath a file called uuid.JSON when it asks for uuid.json -- so on those a case-sensitive test would skip a credential file the store itself reads -- and because a store is one rsync away from being opened on another platform, which is the argument ValidateUUID's device-name check already makes. And each survivor is os.Stat-ed: ReadDir does not follow symlinks, so a dangling link or a directory named <uuid>.json reads as a file here, and the caller says of everything in this list that it holds a live refresh token at 0600 and can be deleted.

The Stat is also the only thing standing between this and a torn answer over a REMOVE: the listing and the account read are two syscalls, and a concurrent `ccdad remove` completing between them leaves a uuid in neither -- gone from the document and gone from the disk -- which without the Stat is reported as an orphan pointing at nothing.

The lock closes the opposite direction, an ADD or an IMPORT: Store.add writes a credential file before the document names it (store.go's own mutate re-reads accounts.toml inside the lock precisely because of that ordering), so a lockless read here can see the new file and the old document in the same instant and call a credential about to be claimed an orphan -- and doctor's own text for this row says to delete it. Held for the read the same way mutate holds it for a write, that instant cannot be observed: the listing and the document are both from the same committed state, whichever one that is. A root with no store yet -- no lock file's directory to open -- answers what it already did: no orphans rather than a store the probe brought into existence.

Anything else in the directory is not a credential file this store wrote: an interrupted WriteFileAtomic leaves <name>.tmp-* beside its target, and calling that stem a uuid would send the user looking for an account that never existed.

func ProviderPrefix added in v0.20.0

func ProviderPrefix(p provider.ID) string

ProviderPrefix is the ordinal prefix for a provider, and "" for a provider this build does not know. The empty answer is never a reference: Ref on a zero-provider account would spell a bare number, which is exactly the ambiguous form the prefix exists to replace, so callers holding an account off the store -- where load has already refused an unparseable provider -- are the only ones that may print it.

func ValidateAlias

func ValidateAlias(alias string) error

ValidateAlias enforces the alias rules against the NORMALIZED form, so a caller that validates a flag value before touching the store gets the same verdict SetAlias would give it.

Three of the rules are structural rather than cosmetic. An alias may not be purely numeric, because Resolve tries an index first and the two axes would otherwise name different accounts for the same token. An alias may not spell a provider-scoped ordinal either -- "c1", "x12" -- for the same reason and against the same axis: those are what a per-provider index is typed as. An alias may not start with a hyphen, so `ccdad run <ACCT>` can reject a leading-hyphen token as a usage error rather than mistaking a flag for an account.

The ordinal rule is enforced HERE and not in Resolve, which still tries the alias first. An alias of that shape stored by an older build goes on naming the account its owner gave it -- taking a working handle away on upgrade is a worse answer than letting one legacy alias shadow a reference that has a second spelling -- while no new one can be created to shadow anything.

func ValidateUUID

func ValidateUUID(uuid string) error

ValidateUUID refuses anything that could not be an account uuid. The value arrives from the profile endpoint and becomes a path component, so a traversal sequence in it would write a credential file outside the store.

It is exported for the same reason ValidateAlias is: a caller staging many accounts — `ccdad import` — has to be able to reject the whole batch BEFORE the first credential file is written, and the only alternative is re-spelling the rule somewhere it can drift from this one.

func WithStore

func WithStore(fn func(*Store) error) error

WithStore runs fn against the store under the cross-process lock and writes what it changed, once.

This is how a caller makes SEVERAL changes land together. The individual mutators each take the lock themselves, so a caller changing one thing does not need this; a caller importing five accounts does, or an alias collision on the fourth leaves three written and two not, with no rollback.

fn returning an error leaves accounts.toml exactly as it was, and now the credentials directory with it: mutate replays what the transaction wrote there, backwards, through Store.rollback. A batch that fails on the fourth of five accounts — an I/O failure on that credential write, which is what remains once a caller has judged its document up front — leaves neither three accounts in the file nor three credential files beside it. The second was the worse half: a live refresh token that `ccdad status`, `ccdad remove` and `ccdad doctor` could not see, because all three read the file.

One change is deliberately NOT reversed: the content of a credential file the transaction only overwrote. rollback says why, and the cost is real — an account that was already stored can come out of a refused transaction holding credentials it did not have going in.

A batch STOPPED rather than refused is reversed the same way. Ctrl-C partway through `ccdad import` used to be the ordinary way to leave a live refresh token nothing on the machine could find; mutate holds SIGINT for the span of the write, and the error it returns wraps ErrInterrupted so the command exits 130 rather than reporting an I/O failure for something the user cancelled.

Types

type Account

type Account struct {
	// UUID is account.uuid from the profile endpoint. The primary key, and the
	// name of the account's credential file, so it is charset-checked on the
	// way in — see ValidateUUID.
	UUID string `toml:"uuid"`
	// Email labels the account for humans.
	Email string `toml:"email"`
	// Alias is an optional short handle, unique across accounts. Stored in its
	// normalized form; see NormalizeAlias.
	Alias string `toml:"alias,omitempty"`
	// Idx is the 1-based display ordinal WITHIN this account's provider: a
	// fleet of three Claude seats and two Codex ones numbers them 1-3 and 1-2,
	// not 1-5. Stored rather than derived so it is stable across restarts.
	//
	// It is therefore NOT unique across the store. It became per-provider
	// because the account list is drawn in provider sections and a store-wide
	// ordinal interleaves them -- the CLAUDE half numbered 1, 3, 4 and the
	// CODEX half 2, 5 on the same fleet -- which reads as a table that has lost
	// rows, and which made the dashboard cursor jump between the two halves on
	// every keypress because it stepped through the store's order and not the
	// page's.
	//
	// Nothing may look an account up by this alone. Resolve answers a bare
	// number only while exactly one provider claims it, and Ref is the form
	// that always names one account.
	Idx int `toml:"idx"`
	// Kind is how the account is metered. Callers set this one.
	Kind identity.Kind `toml:"-"`
	// KindName is Kind's serialized form, because TOML has no enum. It is
	// maintained by Save, which overwrites it from Kind on every write — a
	// caller that sets only KindName silently loses it.
	KindName string `toml:"kind"`
	// Provider is which service this account belongs to, and it is ONE field
	// rather than the Kind/KindName pair beside it. go-toml round-trips a
	// named string type directly; Kind needs its mirror only because it is a
	// uint8, which TOML cannot spell.
	//
	// It carries NO omitempty, and that is load-bearing. A document that
	// omitted the key for Claude rows would be indistinguishable from one a
	// build that does not know the field rewrote -- and those two need
	// opposite answers: the first is a Claude account, the second may be a
	// Codex one whose provider was dropped. So every row carries the key, and
	// a version-2 row without it is refused; see ErrProviderMissing.
	Provider provider.ID `toml:"provider"`
	// CodexReloginFor is the hash of the refresh token whose grant the token
	// endpoint rejected for good.
	//
	// It is a hash and not a token because this file is 0600-but-plaintext and
	// is what people paste into an issue. It names a TOKEN rather than being a
	// flag, and that is the whole mechanism: an account needs a relogin
	// exactly while this equals the hash of the token it still holds, so a
	// later `ccdad add codex` stores a new one and the mark stops matching.
	// Nothing has to clear it, and no stale mark can survive a re-login.
	CodexReloginFor string `toml:"codex_relogin_for,omitempty"`
	// Tier is organization_type, e.g. claude_max.
	Tier string `toml:"tier,omitempty"`
	// SubscriptionStatus is the last observed Claude subscription state.
	// Empty means this version has not checked it; unknown means the profile omitted it.
	SubscriptionStatus string `toml:"subscription_status,omitempty"`
	// ProfileRetryAt throttles failed profile lookups independently of usage.
	ProfileRetryAt time.Time `toml:"profile_retry_at,omitempty"`
	// RateLimitTier is rate_limit_tier, e.g. default_claude_max_20x.
	RateLimitTier string `toml:"rate_limit_tier,omitempty"`
	// SeatTier is seat_tier, e.g. standard or enterprise_usage_based.
	SeatTier string `toml:"seat_tier,omitempty"`
	// OrganizationUUID is the owning organization, when the profile reported
	// one. The ambiguous-email error names it, so a user with the same address
	// in two organizations can tell the candidates apart.
	OrganizationUUID string `toml:"organization_uuid,omitempty"`
	// ProfileFetchedAt is when the four fields above -- Tier, RateLimitTier,
	// SeatTier and OrganizationUUID -- were last taken from a live
	// /api/oauth/profile response. It exists because their EMPTY value is
	// ambiguous in a way that decides behaviour: SeatTier "" is both "a pro or
	// max seat that reported seat_tier null", which is the correct and final
	// answer for most accounts, and "an account added before this tree read
	// seat_tier at all", which is a hole. Without a stamp the two cannot be
	// told apart, so a backfill would either re-read every account forever or
	// skip the ones that need it.
	//
	// It is stamped ONLY by a profile that actually arrived. A failed lookup
	// leaves it where it was, so an outage costs a retry rather than a day of
	// believing the fields are fresh.
	ProfileFetchedAt time.Time `toml:"profile_fetched_at,omitempty"`
	// OAuthAccountSnapshot is the exact oauthAccount object Claude Code held
	// in ~/.claude.json for this account, captured by ccdad the moment a
	// switch displaced it as the live login. A later switch back restores it
	// verbatim, because reconstructing it from the fields above would drop
	// everything the profile lookup above never asked for -- displayName,
	// billingType, the trial and onboarding flags. Empty for an account
	// ccdad has never switched AWAY from; see switcher.SyncGlobalConfigIdentity.
	OAuthAccountSnapshot string `toml:"oauth_account_snapshot,omitempty"`
	// Disabled holds an account out of auto-rotation while keeping it a valid
	// explicit switch target.
	Disabled bool `toml:"disabled,omitempty"`
	// Elsewhere says another machine's ccdad owns this account, so this one
	// neither ranks it nor polls it.
	//
	// It is a SECOND flag rather than a use of Disabled, and the difference is
	// the one that matters across machines. Disabled is a statement about the
	// account -- do not rotate into this one -- and a disabled account is still
	// polled, because `ccdad switch` can still name it and a named switch wants
	// a fresh reading. Elsewhere is a statement about THIS MACHINE: the account
	// is somebody else's to drive, so a reading taken here buys nothing and
	// spends a budget that is shared with whoever is driving it.
	//
	// Why the flag exists at all: two ccdad installs reading the same accounts
	// rank them with the same pure function and the same uuid tie-break, so they
	// converge on the same target and stack two machines' inference onto one
	// five-hour window while the rest of the pool sits idle. Nothing can
	// coordinate that at runtime -- every lock in this tree and in both
	// reference projects is a local flock -- so the partition has to be declared.
	//
	// The live account is the documented exception on the poll path: an account
	// this machine did not choose can still be the one Claude Code is logged in
	// as, and going blind on the live login is how the engine loses its
	// hysteresis baseline.
	Elsewhere bool `toml:"elsewhere,omitempty"`
	// Primary marks an account whose credits are its ORDINARY metering rather
	// than overage — an enterprise seat billed in credits and nothing else. It
	// is ranked beside the subscription accounts instead of waiting in the
	// last-resort credit pool, and credit.max_auto_spend does not gate it,
	// because a ceiling that defaults to 0 would mean the seat could never be
	// used at all.
	//
	// `ccdad primary` sets it, and identity.PrimaryByDefault also sets it at add
	// time for a seat whose PROFILE already says it has no plan-window
	// entitlement. Typing the command is no longer the only opt-in, and the
	// reason is in that predicate: the ceiling is an opt-in to spending PAST
	// paid quota, and a seat with no quota has none to spend past. Adding such
	// an account is the deliberate act, because nothing else about it is usable.
	// Re-adding an account already in the store keeps whatever this field says
	// rather than recomputing it, so an explicit `ccdad primary <acct> off` is
	// not undone by a re-login; see Store.add.
	Primary bool `toml:"primary,omitempty"`
	// AddedAt is when ccdad first stored this account.
	AddedAt time.Time `toml:"added_at"`
	// Credit is the credit balance kept alongside the classification. An
	// account that is both — a subscription with overage enabled — classifies
	// as Subscription and keeps its credit balance as a SECONDARY axis,
	// because credits are not spent while a subscription window still has
	// room — but the engine still has to know what is there when that window
	// runs out.
	Credit CreditBalance `toml:"credit,omitempty"`
}

Account is one managed Claude Code account.

func AccountsAt added in v0.3.0

func AccountsAt(root string) ([]Account, error)

AccountsAt reads a store's accounts WITHOUT creating any part of it.

Open is the ordinary entry point and it is the wrong one for a diagnostic: it does an MkdirAll and two Chmods, which is right for every caller that is about to write and manufactures the very thing `ccdad doctor` was asked to report on. This is the same read Open performs, with the creation and the mode tightening left out — a store that is not there yields no accounts rather than being brought into existence.

It takes the root rather than resolving one so the caller that already resolved it does not resolve it twice and risk answering about a different directory than the rest of its report.

func Resolve

func Resolve(accounts []Account, ref string) (Account, error)

Resolve maps a user-typed reference to exactly one account.

Order: index, then alias, then provider-scoped index, then email, then uuid prefix. There is no substring or fuzzy matching at any step.

The bare index is FIRST and yet may match twice, which is the shape the per-provider ordinal forced. It is answered by naming both candidates and the two spellings that separate them, never by picking one: the commands that take a reference overwrite a credentials file, and a coin flip between two accounts is the one outcome none of them may have.

func (*Account) AdoptProfile added in v0.9.0

func (a *Account) AdoptProfile(p *identity.Profile, at time.Time)

AdoptProfile writes the fields ONE profile lookup decides, and stamps when it happened. It is the single writer of those fields: `ccdad add claude` and the daemon's poll both reach them through here, so the two cannot drift into disagreeing about which parts of a profile are allowed to land.

IT DELIBERATELY DOES NOT TOUCH Kind. Kind belongs to the USAGE axis -- ApplyUsage revises it through identity.ReclassifyOnUsage, which calls Classify with a nil profile and the real UsageShape. Add-time classification is the mirror image: a real profile and an EMPTY shape, because no usage call has been made yet. Re-running that here would overwrite a classification made on window-and-overage evidence with the guess that preceded it, and it would do so on every poll. The caller that legitimately decides Kind from a profile is `ccdad add claude`, once, and it does that beside this call rather than through it.

An EMPTY field on the wire is written as empty. That is not the same as the nil-profile case its callers reject: a profile that answers seat_tier null is evidence of none -- every pro and max account measured answers exactly that -- and an organization can move a seat off usage-based metering, which has to be able to clear the value.

func (Account) Label

func (a Account) Label() string

Label is the account's best human name: the alias when it has one, else the email, else a short uuid.

func (Account) NeedsRelogin added in v0.10.0

func (a Account) NeedsRelogin(currentRefreshTokenHash string) bool

NeedsRelogin reports whether this account's grant is known dead.

currentRefreshTokenHash is the hash of the token the account holds RIGHT NOW, which the caller reads from the stored credential blob. The comparison is what makes the mark self-clearing: a re-login stores a different token, the hashes stop matching, and the account is eligible again with nothing having been erased.

An empty mark is no mark. An empty current hash is an account with no refresh token to be dead, which is not the same as one whose token was rejected, so it answers false too.

func (Account) ProfileStale added in v0.9.0

func (a Account) ProfileStale(now time.Time) bool

ProfileStale reports whether this account's profile-derived fields are old enough to be worth a request.

The ZERO VALUE READS STALE, and that is the whole point: an account added before ProfileFetchedAt existed carries it, and that account is the one whose SeatTier is missing. A build that treated "never measured" as fresh would leave exactly the broken population unrepaired.

func (Account) Ref added in v0.20.0

func (a Account) Ref() string

Ref is the display ordinal in the spelling that names exactly one account: the provider's prefix and the per-provider number, e.g. "c2" or "x1".

Every surface that prints an ordinal OUTSIDE a table grouped by provider prints this one, and Resolve accepts it. Inside a grouped table the section heading IS the prefix, so the bare number under it is already unambiguous and printing the letter twice would only make the column wider.

It is deliberately typeable rather than pretty: what a table prints is what the next command takes, so a user reading a row can act on it without translating anything.

func (Account) SubscriptionInactive added in v0.22.0

func (a Account) SubscriptionInactive() bool

SubscriptionInactive requires an explicit terminal subscription state. A missing status, a usage error, or a credit-metered seat is not expiry.

func (Account) SubscriptionPending added in v0.22.1

func (a Account) SubscriptionPending() bool

SubscriptionPending means a Claude subscription has not been checked yet. It is held out of rotation without being labeled expired or user-disabled.

func (Account) Unambiguous added in v0.25.0

func (a Account) Unambiguous() string

Unambiguous is Label with the provider and the Ref beside it, e.g. "a@example.com (codex, index x1)": the name a destructive action confirms with.

Label alone is not enough there. One email can be a Claude login and a Codex login at once, and the display index restarts per provider, so "Remove a@example.com?" asks a question whose answer could be either. The shape is add's own "(kind, index c3)" with the provider in the kind's place, because kind is "subscription" for most Claude accounts and says nothing about which.

type CreditBalance

type CreditBalance struct {
	// State is usage.ExtraUsageState's name: enabled, disabled, blocked, or
	// empty for an account no reading has covered yet.
	State string `toml:"state,omitempty"`
	// DisabledReason is the organization's own word for a refusal, kept
	// verbatim because it is what a notification says out loud.
	DisabledReason string `toml:"disabled_reason,omitempty"`
	// Currency is the ISO code the figures below are denominated in, so that a
	// stored 150 is never ambiguous between $150 and ¥150.
	Currency string `toml:"currency,omitempty"`
	// MonthlyLimit is the account's own spend cap, in the MAJOR unit — dollars
	// for USD, the same unit max_auto_spend is written in. The endpoint reports
	// it in the minor unit; usage.ExtraUsage converts, and that conversion
	// happens in exactly one place. Nil means the account sets no cap —
	// unlimited — which is not the same as a cap of zero.
	MonthlyLimit *float64 `toml:"monthly_limit,omitempty"`
	// UsedCredits is what has already been spent, in the same major unit. Nil
	// means it could not be read, and that refuses a switch rather than reading
	// as zero.
	UsedCredits *float64 `toml:"used_credits,omitempty"`
	// ObservedAt is when the reading behind these figures was taken. The zero
	// time means no reading ever has been.
	ObservedAt time.Time `toml:"observed_at,omitempty"`
}

CreditBalance is what a usage reading last said about an account's overage credits.

The two figures are pointers because the credit gate branches on used_credits being nil and fails closed on money: a balance that could not be read must never persist as "$0 spent, full cap available". State is a string rather than a typed enum so that reading an accounts.toml stays free of the usage package; callers turn it back into one with usage.ParseExtraUsageState, which reads anything it does not recognize as unknown.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store is ccdad's account database.

Every mutator runs its read-modify-write under the cross-process lock in lock.go, which is what makes two concurrent ccdad processes safe: the state is re-read inside the lock, so the write is against what the previous holder left rather than against whatever Open happened to see. Reads take no lock — every write is an atomic rename, so a reader sees one whole version of the document or another, never a torn one.

A Store is NOT safe for concurrent use by several goroutines in one process. The lock excludes other processes; it does not serialize this one.

func Open

func Open() (*Store, error)

Open loads the store, creating an empty one if none exists.

func (*Store) Accounts

func (s *Store) Accounts() []Account

Accounts returns the managed accounts in display order.

func (*Store) ActiveUUID

func (s *Store) ActiveUUID() string

ActiveUUID is the last account ccdad activated, or "".

func (*Store) Add

func (s *Store) Add(a Account, creds cclink.Blob) error

Add stores an account and its account-scoped credentials.

Re-adding an existing uuid updates it in place: the fresh login replaces the stored credentials while the alias, the display index and the two per-account flags — disabled and primary, which belong to the user rather than to the login — survive. This is what makes `ccdad add claude` double as re-authentication.

func (*Store) ApplyCodexPlan added in v0.22.0

func (s *Store) ApplyCodexPlan(uuid, plan string, at time.Time) error

ApplyCodexPlan records the tier returned by a successful usage poll. An omitted tier or an older result must not erase a newer observation.

func (*Store) ApplyProfile added in v0.9.0

func (s *Store) ApplyProfile(uuid string, p *identity.Profile, observedAt time.Time) error

ApplyProfile records a fresh profile reading against one stored account. It is the sibling of ApplyUsage and it is deliberately shaped the same way: a reading is required, the account is mutated in the store's own slice, and a missing account is ErrNotFound rather than a silent no-op.

A nil profile is refused rather than ignored, for the reason ApplyUsage refuses a nil snapshot: the caller has a failed lookup on its hands and needs to be told, and writing "no evidence" over four fields that currently hold measured values would turn one unreachable endpoint into a fleet that forgot its tiers.

func (*Store) ApplyUsage

func (s *Store) ApplyUsage(uuid string, snap *usage.Snapshot, observedAt time.Time) error

ApplyUsage records a SUCCESSFUL usage reading against an account: it revises the account's Kind if the reading is evidence, and refreshes the credit balance the account keeps alongside it as a secondary axis.

Taking a non-nil *usage.Snapshot is the whole point of the signature. The Classify calls in `ccdad add` and `add-token` all pass an empty UsageShape, so the window evidence Classify makes primary is never consulted there — and the fix must not be a function that can be handed "no reading" and quietly apply Classify's no-evidence default. A failed poll has nothing to pass here, and passing nil is refused rather than treated as an empty reading.

The read-modify-write runs under the store lock like every other mutator, so the daemon applying a poll result and a CLI adding an account cannot lose each other's write. The nil check happens BEFORE the lock is taken: a caller that has nothing to apply should not make every other writer wait for it.

func (*Store) BeginProfileRefresh added in v0.22.1

func (s *Store) BeginProfileRefresh(uuid string, now time.Time, force bool) (bool, error)

BeginProfileRefresh claims a due lookup under the store lock before any network call. A failed lookup keeps this retry deadline; success clears it.

func (*Store) ClaudeAccounts added in v0.10.0

func (s *Store) ClaudeAccounts() []Account

ClaudeAccounts is CodexAccounts' twin. See it.

func (*Store) CodexAccounts added in v0.10.0

func (s *Store) CodexAccounts() []Account

CodexAccounts and ClaudeAccounts are where every provider-specific path starts.

They are methods rather than a predicate each caller writes, because a caller that wrote its own is a caller that could forget -- and the cost of forgetting is asymmetric: a Codex row that reaches the Claude ranking is a switch that rewrites Claude Code's credentials file for an account that has no Claude login.

func (*Store) Credentials

func (s *Store) Credentials(uuid string) (cclink.Blob, error)

Credentials returns an account's stored account-scoped keys.

func (*Store) Get

func (s *Store) Get(uuid string) (Account, bool)

Get looks an account up by uuid.

func (*Store) Move

func (s *Store) Move(uuid string, position int) (changed bool, err error)

Move puts an account at a 1-based display position WITHIN ITS OWN PROVIDER and renumbers that provider's rest.

Scoped to the provider because the position it sets is the ordinal, and the ordinal is per-provider. The alternative -- a store-wide position -- would let `ccdad move c3 1` land a Claude seat above every Codex one or below them, depending on nothing the caller said, and the number it came to rest at would not be the number they asked for.

So a position past the provider's last account is that provider's last, never the store's, and a Claude account cannot be moved into the Codex block at any position. That is also what keeps the slice grouped, which block, the account lists and the dashboard cursor all depend on.

A position past the end clamps to the end rather than erroring: "put it last" is what a caller who typed a big number meant, and the alternative is making them count. A position below 1 clamps to the front for the same reason — callers that want to refuse 0 as a non-position do so before calling, where they can say so in the user's own terms.

It renumbers rather than reorders-and-sorts. sortAndReindex sorts on the Idx values already stored, so a moved slice handed to it is sorted straight back into the order it started in — which is also what a "just set the new Idx and Save" implementation runs into on the next Open, where two accounts then share an Idx and SliceStable breaks the tie by slice position.

It reports whether the account actually moved, so a caller can spend exit 3 on a move that asked for the position the account already holds.

Every account between the source and the destination changes number, so a script holding an idx from an earlier `ccdad status` now acts on a different account. That is the stability contract in `ccdad --help` — idx is an ordinal, not a key — and move is the command that makes it routine rather than a side effect of removal.

func (*Store) Remove

func (s *Store) Remove(uuid string) error

Remove deletes an account and its stored credentials.

func (*Store) SetActive

func (s *Store) SetActive(uuid string) error

SetActive records which account ccdad last activated.

func (*Store) SetAlias

func (s *Store) SetAlias(uuid, alias string) error

SetAlias assigns a unique alias. An empty alias clears it.

func (*Store) SetCodexReloginFor added in v0.10.0

func (s *Store) SetCodexReloginFor(uuid, expectedHash, mark string) error

SetCodexReloginFor records that this account's grant was refused for good, but only while the account still holds the refused token.

expectedHash is the hash of the token whose refresh was rejected, as the caller saw it. The comparison is against what the store holds NOW, inside the lock, and that is the whole point of the method: without it, a terminal refusal for token A racing a `ccdad add codex` that stored token B would mark an account holding a perfectly good grant as needing a relogin.

A miss is not an error. It means the store moved past the rejected token while the request was in flight, which is the ordinary outcome of a race the user won -- so it writes nothing and reports success.

func (*Store) SetCredentials added in v0.10.0

func (s *Store) SetCredentials(uuid string, creds cclink.Blob) error

SetCredentials replaces one account's credential file, leaving its row alone.

Add cannot stand in for it. Add is the re-authentication path: it re-derives the index, the partition side and the per-account flags, and it refuses a provider change. A token rotation changes the credential file and nothing else, and going through Add would make every rotation run that whole path.

It refuses an account the document does not name, because the alternative is a credential file with no row pointing at it -- exactly the orphan OrphanCredentialsAt exists to report.

func (*Store) SetDisabled

func (s *Store) SetDisabled(uuid string, disabled bool) (changed bool, err error)

SetDisabled holds an account out of auto-rotation, or puts it back, and reports whether that was a change.

Disabled is a policy for the auto engine and NOT a lock: an explicit `ccdad switch <account>` still works on a disabled account, because a user naming an account by hand has said what they want more clearly than the flag has. The bool exists so the caller can spend the exit contract's exit 3 — "the world is already as you asked" — rather than reporting a no-op as an action taken.

func (*Store) SetOAuthAccountSnapshot added in v0.4.1

func (s *Store) SetOAuthAccountSnapshot(uuid string, snapshot json.RawMessage) error

SetOAuthAccountSnapshot records the oauthAccount object Claude Code held for this account in ~/.claude.json at the moment a switch displaced it as the live login. See switcher.SyncGlobalConfigIdentity, the only caller.

func (*Store) SetOwned added in v0.5.0

func (s *Store) SetOwned(uuids []string) (changed int, err error)

SetOwned declares the accounts this machine drives, and reports how many rows changed.

It is transactional over the WHOLE list and not a per-account setter, because the partition is one statement: every uuid named is owned here, every uuid not named belongs to another machine. A per-account toggle would let a user own account 3 on both machines by forgetting to run the other half, which is the failure the flag exists to prevent and is invisible until a five-hour window burns twice as fast.

An empty owned set clears the partition -- this machine owns everything again, the state every store is in before `ccdad own` is first run. It is spelled as the empty set rather than as a separate verb so that "own nothing" cannot be typed by accident: the CLI requires --clear for it.

Every uuid must resolve, and nothing is written unless all of them do. A partial application would leave the machine owning a set the user did not ask for, which is worse than refusing.

func (*Store) SetPrimary added in v0.3.0

func (s *Store) SetPrimary(uuid string, primary bool) (changed bool, err error)

SetPrimary marks an account as metered in credits BY DESIGN, or unmarks it, and reports whether that was a change.

It takes the caller's word and checks nothing about the account's kind. Kind is re-derived from the last profile read on every load, so an account that reads as subscription today can read as credit tomorrow; a store that refused the flag on today's answer would make the setting depend on when it was typed. Looking at the account, and explaining a refusal, belongs where there is a user to explain it to.

The bool is here for the same reason SetDisabled's is: a caller can spend the exit contract's exit 3 — the world is already as you asked — rather than reporting a no-op as an action taken.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL