Documentation
¶
Overview ¶
Package account manages the extra Claude Code accounts loom can launch sessions under. Claude Code has no account flag: an account is whatever credentials live in a config dir, and CLAUDE_CONFIG_DIR picks the dir. loom keeps one dir per extra account under <globalDir>/accounts/<name>, links the main config dir's shared entries into it (link.go), and reads each account's identity and plan usage through the claude CLI (auth.go, usage.go). The implicit account "default" is Claude with no override; it is never stored.
No app, ui or session imports. Every subprocess runs through an injected internalexec.Executor.
Index ¶
- Constants
- Variables
- func ActiveCredentialOverride() (name string, ok bool)
- func Binary(program string) string
- func Command(ctx context.Context, program string, env []string, args ...string) (*exec.Cmd, error)
- func CountUsers(configDirs []string, name string) (int, error)
- func EnsureOnboarded(dir string) (bool, error)
- func EnvFor(dir string) []string
- func KnownStateDirs() ([]string, error)
- func LoginCmd(program string, env []string) *exec.Cmd
- func MainDir(id Identity) string
- func Unshared(acctDir string) ([]string, error)
- func ValidName(name string) error
- func ValidateMainDir(mainDir, accountsDir string) error
- type Account
- type Identity
- type Registry
- func (r *Registry) AccountsDir() string
- func (r *Registry) Create(name, mainDir string) (Account, SyncReport, error)
- func (r *Registry) Default() string
- func (r *Registry) Dirs() map[string]string
- func (r *Registry) Env(name string) ([]string, error)
- func (r *Registry) Get(name string) (Account, bool)
- func (r *Registry) HasExtra() bool
- func (r *Registry) LoadErr() error
- func (r *Registry) Names() []string
- func (r *Registry) OwnedDir(name string) (string, bool)
- func (r *Registry) Path() string
- func (r *Registry) Reload() error
- func (r *Registry) Remove(name string, force bool) (deleted bool, err error)
- func (r *Registry) SetDefault(name string) error
- type SyncReport
- type UnsharedError
- type Usage
- type Window
Constants ¶
const DefaultName = "default"
DefaultName names the implicit account: Claude with no CLAUDE_CONFIG_DIR override.
Variables ¶
var CredentialOverrides = []string{"ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"}
CredentialOverrides are environment variables whose credential outranks every config dir's login: the Claude CLI checks these before ever reading a config dir's stored credentials, so with one set in loom's own environment, every account loom launches — regardless of which config dir CLAUDE_CONFIG_DIR points it at — silently runs (and bills) as that one credential instead of its own login. Order matters only in that it picks which name ActiveCredentialOverride reports when more than one is set; the CLI's own precedence among them is not loom's concern here.
var ErrAccountDirMissing = errors.New("account config dir does not exist")
ErrAccountDirMissing means an env's CLAUDE_CONFIG_DIR override names a directory that does not exist. The claude CLI treats a missing config dir as a place to create fresh, logged-out state rather than an error, so running it there — a removed account's dir, say — would silently start a brand new identity instead of reporting the account gone. AuthStatus and ProbeUsage both check for it before running anything.
var ErrRegistryLoadFailed = errors.New("accounts.json failed to load; refusing to overwrite it")
ErrRegistryLoadFailed is returned by every write to a registry whose file failed to load, so a corrupt accounts.json is never overwritten.
Functions ¶
func ActiveCredentialOverride ¶
ActiveCredentialOverride returns the first of CredentialOverrides set to a non-blank value in loom's own environment, and whether one was found. Trimmed, matching the whitespace-only handling the remote-control auth check already does elsewhere, so a stray "export FOO= " can't warn without actually blocking anything. Callers use this to warn before per-account selection would be a no-op: switching CLAUDE_CONFIG_DIR changes nothing while an override is active.
func Binary ¶
Binary is the executable of a program string: its first field. The account commands run the same CLI the sessions launch, so an absolute or Nix store path resolves the same way. Binary itself runs whatever program string it is given — it is the caller's job to gate that on the Claude adapter (session/agent) before reaching here, the same as AuthStatus and ProbeUsage below.
func Command ¶
Command builds the *exec.Cmd for one of the Claude CLI's own subcommands (auth status, agents --json, the headless usage probe, …) run under an account's environment. It centralizes the checks every such caller needs before anything runs: program resolves to a binary, and env's CLAUDE_CONFIG_DIR override, if any, still exists on disk (ErrAccountDirMissing) — the CLI treats a missing config dir as a place to create a fresh, logged-out identity rather than reporting an error, so running it there (a removed account's dir, say) would silently start a new identity instead of failing closed. program is run as-is: the caller must have already gated it on the Claude adapter.
func CountUsers ¶
CountUsers counts the stored sessions that run on account name across the state.json files in configDirs. Read-only: unlike config.LoadStateFrom it never quarantines a corrupt file. A missing file counts zero; an unreadable or corrupt one is an error, because "is this account in use" must not be answered with a guess. A repeated dir counts once.
func EnsureOnboarded ¶
EnsureOnboarded marks a logged-in account's first-run onboarding as done in its <dir>/.claude.json, and reports whether it changed the file.
`claude auth login` stores the credentials (and oauthAccount) but leaves hasCompletedOnboarding unset, and the interactive CLI runs its onboarding whenever that flag is missing. Onboarding includes the login-method screen, so the first session on an account logged in from the CLI asked to log in again (observed on 2.1.281). Loom marks it just before launching on the account.
Only a logged-in account is marked (oauthAccount in .claude.json, or a .credentials.json): a logged-out one needs the onboarding to log in. A missing .claude.json is left alone, and one that doesn't parse as a JSON object is an error and is never overwritten. Every other key is kept.
func KnownStateDirs ¶
KnownStateDirs lists every config dir that can hold sessions: the global dir, LOOM_HOME's when it differs, and each registered workspace's.
func LoginCmd ¶
LoginCmd is `claude auth login` under env. It is an interactive browser flow, so the caller runs it in the foreground terminal: the CLI directly, the TUI through tea.ExecProcess. program is run as-is: the caller must have already gated it on the Claude adapter.
func MainDir ¶
MainDir is the main config dir extra accounts link to, given the default account's identity: the dir `claude auth status` reported, else $CLAUDE_CONFIG_DIR (which the default account inherits), else ~/.claude. "" when none can be found.
func Unshared ¶
Unshared lists acctDir's top-level entries that Sync would link (their name passes shared()) but that are real files or directories rather than symlinks: an entry Sync's link was replaced with (a tool rewriting it atomically, say), or one created directly inside the account — by Claude running under it, typically — before the main dir ever had an entry of that name for Sync to link. Sorted (os.ReadDir's own order). A missing acctDir reports no entries, not an error.
func ValidName ¶
ValidName checks an account name: lowercase letters, digits and dashes, not starting with a dash, at most maxNameLen characters, and not DefaultName. The name becomes a directory name and appears in badges.
func ValidateMainDir ¶
ValidateMainDir checks that mainDir is safe to link accounts from: an absolute path that, once symlinks are resolved, neither lies inside accountsDir (a nested loom running as an account, pointed at its own accounts dir by mistake) nor contains it (mainDir is AccountsDir's own parent or an ancestor further up, which would have Sync link "accounts" itself — the dir a Create using it is about to populate — into every account made under it). Create runs this before touching anything; callers resolving mainDir themselves (the CLI's add and sync, which read it from `claude auth status`) should too, since that resolution can fail closed to "" or point somewhere unsafe.
Types ¶
type Account ¶
type Account struct {
Name string `json:"name"`
// Dir is the account's CLAUDE_CONFIG_DIR.
Dir string `json:"dir"`
}
Account is one registered extra account.
type Identity ¶
type Identity struct {
LoggedIn bool `json:"loggedIn"`
AuthMethod string `json:"authMethod"`
Email string `json:"email"`
OrgName string `json:"orgName"`
Plan string `json:"subscriptionType"`
// ConfigDir is the config dir the CLI resolved. For the default
// account it is the main dir extra accounts link to.
ConfigDir string `json:"configDirectory"`
}
Identity is the subset of `claude auth status` loom reads. Field names match the CLI's JSON (Claude Code 2.1.281).
func AuthStatus ¶
AuthStatus runs `claude auth status` under env and decodes it. A logged out account still prints its JSON (and exits non-zero), so output is decoded whenever there is some. program is run as-is: the caller must have already gated it on the Claude adapter.
type Registry ¶
type Registry struct {
// DefaultAccount is the account new sessions preselect; empty means
// DefaultName.
DefaultAccount string `json:"default,omitempty"`
Accounts []Account `json:"accounts"`
// contains filtered or unexported fields
}
Registry is accounts.json: the extra accounts and which account new sessions preselect. Every mutation reloads the file first and writes it back atomically, so a `loom account` run and a running TUI don't clobber each other (the same reload-before-save rule as config.WorkspaceRegistry).
func LoadRegistry ¶
LoadRegistry reads <globalDir>/accounts.json. A missing file is an empty registry. A file that cannot be read or parsed yields an empty registry whose LoadErr is set and whose writes all fail.
func Unavailable ¶
Unavailable is a registry that could not even be located (no global config dir). It holds no accounts and refuses every write. err is never nil in the returned registry's LoadErr, even when the caller passed nil.
func (*Registry) AccountsDir ¶
AccountsDir is where Create makes account dirs: <globalDir>/accounts.
func (*Registry) Create ¶
func (r *Registry) Create(name, mainDir string) (Account, SyncReport, error)
Create registers a new account called name: it makes the account's config dir under AccountsDir, links mainDir's shared entries into it, and records it. The dir must not exist yet. mainDir is checked by ValidateMainDir. Logging in is the caller's next step.
func (*Registry) Default ¶
Default is the account new sessions preselect: DefaultAccount when it still names a registered account, else DefaultName.
func (*Registry) Env ¶
Env returns the environment entries that run Claude as name: nil for DefaultName (or ""), CLAUDE_CONFIG_DIR for a registered account, and an error for anything else.
func (*Registry) OwnedDir ¶
OwnedDir returns the config dir name is registered under together with whether Remove would actually delete it: only when the account's stored Dir agrees with the canonical <AccountsDir>/name, recomputed here rather than trusted from the stored field — a hand-edited or corrupt registry could point Dir anywhere.
When owned, the returned dir is the canonical path itself — never the stored field, even when filepath.Clean(stored) == canonical as a plain string comparison. A stored value can still resolve somewhere else entirely once the kernel gets it: "<AccountsDir>/lnk/../name" cleans lexically to the canonical path, but if "lnk" is a symlink the kernel resolves it first and only then applies "..", landing wherever the symlink points instead. So Remove and Unshared must only ever act on this return value, never on Get's raw Account.Dir — that is the whole point of routing them through OwnedDir at all.
When not owned, the stored Dir is returned as-is, for display only ("<dir> is not loom's"); nothing may write to or delete it. "" and false when name is not registered.
func (*Registry) Path ¶
Path is the registry's accounts.json, which a long-lived holder can stat to tell whether a Reload is due; "" for an Unavailable registry.
func (*Registry) Reload ¶
Reload re-reads the registry's file into the receiver, replacing its accounts and default with whatever is on disk now. A long-lived holder (the TUI, which loads its registry once at workspace activation) should call this before acting on stale data, so it sees writes a concurrent `loom account` run or another loom process made since. On success it clears LoadErr; on failure it latches LoadErr exactly as LoadRegistry would and returns it, so a Reload that raced a corrupt write leaves the registry refusing further writes rather than silently keeping the old in-memory state. A registry with no file (Unavailable) has nothing to reload and keeps the error that made it unavailable.
func (*Registry) Remove ¶
Remove unregisters name. When OwnedDir reports it owns its config dir, it also deletes that dir: the account's credentials and state plus links into the main dir. RemoveAll deletes the links themselves, never what they point at.
A dir the account does not own (outside AccountsDir, or a stored Dir disagreeing with <AccountsDir>/name) is unregistered but never deleted; deleted reports which happened.
Unless force, an owned dir holding real (non-symlink) entries Unshared would report is left registered and untouched, and Remove returns an *UnsharedError naming them: content that exists nowhere else should not vanish silently. force deletes regardless.
func (*Registry) SetDefault ¶
SetDefault makes name the account new sessions preselect.
type SyncReport ¶
type SyncReport struct {
// Linked lists the entries this run linked.
Linked []string
// Diverged lists entries that are real files or directories in the
// account dir although the main dir has them too: something replaced
// the link (a tool rewriting the file atomically through it, say).
// Sync leaves them alone, since the account's copy may hold the only
// copy of a change.
Diverged []string
// At is when the run started: a client that asked for a sync tells the
// report of its run from an older one (`loom account sync`).
At time.Time
}
SyncReport is what one Sync did. Both lists are sorted.
func Sync ¶
func Sync(acctDir, mainDir string) (SyncReport, error)
Sync links every shared entry of mainDir that acctDir does not have yet. Idempotent. Existing links are left as they are, wherever they point, and a real file or directory is never replaced.
type UnsharedError ¶
type UnsharedError struct {
}
UnsharedError reports that Remove refused to delete an account because it holds real content that is not shared with the main config dir and so exists nowhere else: deleting it without --force would be the only copy lost.
func (*UnsharedError) Error ¶
func (e *UnsharedError) Error() string
type Usage ¶
type Usage struct {
// Available is false when plan limits do not apply — API key, Bedrock
// or Vertex auth — or when the account is logged out entirely:
// get_usage reports the identical shape for both (no plan, no
// windows), so a false Available alone does not tell them apart.
// Callers that need to distinguish "no limits" from "logged out" use
// AuthStatus's LoggedIn instead. The windows are nil either way.
Available bool
// Plan is the subscription ("pro", "max", …); empty for API-key auth.
Plan string
// FiveHour and SevenDay are nil when the server did not report them.
FiveHour, SevenDay *Window
// At is when the probe started. Zero means never probed.
At time.Time
}
Usage is one account's plan usage, from ProbeUsage.
func ProbeUsage ¶
ProbeUsage asks the account's CLI for its plan usage without starting a conversation: a headless `claude -p` over stream-json that answers the one control request on stdin and exits when stdin closes. No model call, no cost. The CLI answers from its own usage snapshot when that is under a minute old, so polling does not hammer the usage endpoint. --setting-sources "" keeps user and project settings, and the plugin hooks they enable, out of the probe (auth is read from the config dir regardless); --strict-mcp-config keeps configured MCP servers from starting; --no-session-persistence writes no transcript. cwd is where the probe runs: pass the account's config dir so no project entry is recorded for an arbitrary directory. program is run as-is: the caller must have already gated it on the Claude adapter.