account

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: AGPL-3.0 Imports: 16 Imported by: 0

README

account

Extra Claude accounts, so sessions can be spread across several subscriptions. An account is a CLAUDE_CONFIG_DIR under <globalDir>/accounts/<name>/, registered in <globalDir>/accounts.json. default is Claude with no override: it is never stored. The package imports nothing from app, ui or session, and runs its subprocesses through an injected executor.

On disk

  • accounts.json (global dir): the extra accounts (name, dir) and the default new sessions preselect.
  • accounts/<name>/ (global dir): each extra account's CLAUDE_CONFIG_DIR, with its own .credentials.json, .claude.json and runtime dirs, and everything else symlinked to the main config dir.

Files

  • registry.go — Registry (LoadRegistry, Reload, Get, Names, Dirs, Env, SetDefault, ValidName): reload-before-save, so a concurrent writer's change is merged, and latched shut (ErrRegistryLoadFailed, Unavailable) when the file fails to load or a loaded entry fails validation. LoadRegistry refuses any entry whose stored Dir is not in filepath.Clean form or does not resolve (resolvedOrClean) to <AccountsDir>/<name>, then canonicalizes every loaded Dir in memory (canonicalizeDirs), so a respelled global dir still loads but the stored spelling never reaches a launch, Sync or Remove. A hand-edited "bring your own directory" entry is out of scope.
  • link.go — Create (Registry.Create, which runs ValidateMainDir before any linking, so the TUI's account-add path is covered too), Sync, ValidateMainDir, Unshared, OwnedDir, Remove. An account's dir symlinks every top-level entry of the main config dir except a deny-list (sharedDenyList, shared): .credentials.json*, .claude.json*, sessions, daemon, daemon.log, session-env, ide, debug, cache, backups, shell-snapshots, statsig, jobs, stats-cache.json, .last-cleanup, and each session's own security_warnings_state_<uuid>.json. So projects/ (transcripts, auto-memory) is shared, and --resume works across accounts. Claude checks a memory write through that link under its resolved path too, which its own memory exemption doesn't cover, so session hands an account session the resolved memory dir (accountMemoryDir). Create seeds the main dir's own projects/ (only when the main dir exists) before linking. Sync links new main-dir entries, never replaces a real file, and reports one that replaced a link as diverged (SyncReport.Diverged). OwnedDir returns filepath.Join(AccountsDir, name), recomputed from the name, and says whether Remove may delete it or only unregister it; Remove and Unshared act only on that path.
  • auth.go — AuthStatus and LoginCmd wrap claude auth; Identity is what auth status reports. LoginCmd hands back a bare interactive *exec.Cmd for tea.ExecProcess or the CLI's own foreground Run(), not a captured Output() call, so it cannot refuse a missing dir itself: both callers os.Stat the dir first and refuse, saying to remove the account and add it again (loom account remove, then add).
  • command.go — account.Command, the one way an account-scoped claude subprocess that captures output is built (AuthStatus, ProbeUsage, and session's roster query session.QueryClaudeRosterEnv): it refuses a missing CLAUDE_CONFIG_DIR up front (ErrAccountDirMissing).
  • usage.go — account.ProbeUsage reads plan usage, polled by the model on gateUsage and expedited when a picker opens: a headless claude -p stream-json run answering the SDK's experimental get_usage control request (skip_behaviors, --setting-sources "", --strict-mcp-config, no model call). TestRealClaude_UsageProbe (opt-in, free) pins its shape. An expired login probes the same as API-key auth (Usage.Available=false), which is why core re-reads auth when an account loses plan access. The probe's working directory becomes a project entry in Claude's own config, so callers pass a deliberate one.
  • users.go — CountUsers and KnownStateDirs answer "is this account in use" read-only, from state.json files.
  • onboard.go — account.EnsureOnboarded: claude auth login stores the credentials and oauthAccount but leaves .claude.json's hasCompletedOnboarding unset, and the interactive CLI runs its onboarding (login screen included) whenever that flag is missing. Every launch on an account calls it (launchEnv(true) in session); it sets the flag only for a logged-in account (oauthAccount or .credentials.json), keeps every other key, and never rewrites a file it can't parse.
  • override.go — CredentialOverrides and ActiveCredentialOverride (below).

Who uses it

  • loom account (internal/cli/account.go) is the CLI over it, a client of the daemon; the model (core/accounts.go, core/usage.go) holds the registry, auth, sync and usage, reloads accounts.json when its stat moves and before every user action that reads it, re-syncs existing accounts in the background (accountsRefreshJob, which applies ValidateMainDir through syncMainDir and logs a refusal once), and publishes it all to the TUI (app/accounts.go).
  • Every real launch resolves an instance's account name to its dir and fails closed; that resolution lives in session.
  • Usage is display-only: a failed probe keeps the last sample, shown dimmed with its age, because nothing acts on it.
  • remove --force on an account a live session still uses can lose a race with that session's own Claude process, which can recreate a bare, unlinked dir right after the delete; a later add of the same name then fails ("already exists") until the leftover dir is cleared by hand.

Credential overrides

account.CredentialOverrides lists ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN and CLAUDE_CODE_OAUTH_TOKEN, the env vars the Claude CLI checks before it reads a config dir's own stored credentials, and ActiveCredentialOverride returns the first one set in its own process's environment. With one set, every account session runs and bills as that credential whatever CLAUDE_CONFIG_DIR loom launches it with, so switching accounts is a no-op the UI can't hide.

  • The process that counts is the daemon, whose environment was frozen when it was spawned: the model reads it (Core.CredentialOverride, a local query answered from AccountsView.CredentialOverride), its usage probes and auth reads inherit it, and every client warns by it, never by its own environment.
  • The TUI's strip leads with "⚠ $VAR set: all accounts use it" (ui.AccountStrip.SetWarning, fed by the app's credentialOverrideWarning), and the Accounts screen shows the same text as a screen-wide notice above its rows while an extra account exists (SettingsOverlay.SetAccountNotice → AccountsManager.SetNotice; hidden with only default, since there is no choice for it to void). loom account add, login and list each print the same warning from their own environment (use and sync don't, since neither runs a session).
  • Agents don't take these variables from the daemon: they inherit ANTHROPIC_*, and the default account's CLAUDE_CONFIG_DIR, from the tmux server's global environment, which is the daemon's only when the daemon started that server. A daemon reusing the user's own tmux server, or the previous daemon's (daemon.TmuxServer), gives its agents that server's environment, while the warning reflects the daemon's.
  • Core's extraAccountAuth (core/accounts.go) leaves an override-caused remote-control block's reason untouched, since no login would fix it, rather than adding the "run loom account login <name>, or Settings → Accounts → l" hint it attaches to every other blocked reason.
  • Separately, core's noteRunningAsAccount checks at boot whether the model's own $CLAUDE_CONFIG_DIR (the daemon's: a daemon spawned from an account's agent pane, say) already resolves inside its accounts dir, and if so records a warning that "default" is actually that account's login, usage and sessions. It holds for the model's whole life, so it is published state (Core.RunningAsAccount, AccountsView.RunningAsAccount) that every client shows.

Tests

testmain_test.go isolates the loom dirs. usage_real_test.go holds the opt-in real-CLI probe; testdata/ holds a recorded get_usage response.

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

View Source
const DefaultName = "default"

DefaultName names the implicit account: Claude with no CLAUDE_CONFIG_DIR override.

Variables

View Source
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.

View Source
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.

View Source
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

func ActiveCredentialOverride() (name string, ok bool)

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

func Binary(program string) string

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

func Command(ctx context.Context, program string, env []string, args ...string) (*exec.Cmd, error)

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

func CountUsers(configDirs []string, name string) (int, error)

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

func EnsureOnboarded(dir string) (bool, error)

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 EnvFor

func EnvFor(dir string) []string

EnvFor returns the environment entry that points Claude at config dir dir.

func KnownStateDirs

func KnownStateDirs() ([]string, error)

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

func LoginCmd(program string, env []string) *exec.Cmd

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

func MainDir(id Identity) string

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

func Unshared(acctDir string) ([]string, error)

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

func ValidName(name string) error

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

func ValidateMainDir(mainDir, accountsDir string) error

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

func AuthStatus(program string, env []string, r internalexec.Executor) (Identity, error)

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

func LoadRegistry(globalDir string) *Registry

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

func Unavailable(err error) *Registry

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

func (r *Registry) AccountsDir() string

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

func (r *Registry) Default() string

Default is the account new sessions preselect: DefaultAccount when it still names a registered account, else DefaultName.

func (*Registry) Dirs

func (r *Registry) Dirs() map[string]string

Dirs maps each extra account's name to its config dir.

func (*Registry) Env

func (r *Registry) Env(name string) ([]string, error)

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) Get

func (r *Registry) Get(name string) (Account, bool)

Get returns the registered account called name.

func (*Registry) HasExtra

func (r *Registry) HasExtra() bool

HasExtra reports whether any account besides DefaultName is registered.

func (*Registry) LoadErr

func (r *Registry) LoadErr() error

LoadErr reports why the registry failed to load, or nil.

func (*Registry) Names

func (r *Registry) Names() []string

Names lists every account: DefaultName first, then registration order.

func (*Registry) OwnedDir

func (r *Registry) OwnedDir(name string) (string, bool)

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

func (r *Registry) Path() string

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

func (r *Registry) Reload() error

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

func (r *Registry) Remove(name string, force bool) (deleted bool, err error)

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

func (r *Registry) SetDefault(name string) error

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.

func (SyncReport) Clone

func (r SyncReport) Clone() SyncReport

Clone deep-copies r's slices.

type UnsharedError

type UnsharedError struct {
	Name    string
	Entries []string
}

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

func ProbeUsage(program string, env []string, cwd string, r internalexec.Executor) (Usage, error)

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.

func (Usage) Clone

func (u Usage) Clone() Usage

Clone deep-copies u: the windows are its own.

type Window

type Window struct {
	// Pct is the share of the window used, 0-100.
	Pct float64
	// ResetsAt is when the window resets; zero when the server gave none.
	ResetsAt time.Time
}

Window is one plan rate-limit window.

func (*Window) Text

func (w *Window) Text(now time.Time) string

Text renders w for display: "64%", or "reset" once ResetsAt has passed (the percentage would describe a window that no longer exists). "" for a nil window.

Jump to

Keyboard shortcuts

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