#!/usr/bin/python3
# omarchy:summary=Read and change the registry of Claude, Codex, and Grok subscription accounts
# omarchy:args=<registry|home|homes|list|refresh|begin|register|relogin|recover|use|rename|remove|threshold|link|alert> [provider] [args...]
# omarchy:hidden=true
"""The account registry behind `omarchy agent account`.

An account is a Claude Code, Codex, or Grok login Omarchy keeps a home for.
The login you already have stays where the CLI put it (~/.claude, ~/.codex,
~/.grok) and
is the primary account; added accounts get a home of their own under
~/.local/state/omarchy/agents/accounts/<provider>/<id>/ that holds only that
account's credentials and links everything else back to the primary home, so
conversation history, settings and skills stay one set across accounts.

Each provider's registry is one JSON file beside those homes. It records which
account is active — the one new sessions start as — how switching happens, and
display-safe identity. Tokens never enter it and never leave this process.

Claude sessions all start in ~/.claude, which holds the login of the seated
account; every other Claude login waits in its own home. Switching moves the
chosen login into ~/.claude, and running sessions follow on their next message.
"""

from __future__ import annotations

import base64
import datetime as dt
import fcntl
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
from pathlib import Path
from typing import Any

PROVIDERS = {
  "claude": {
    "name": "Claude",
    "home_env": "CLAUDE_CONFIG_DIR",
    # Everything a session reads or writes that isn't tied to the login. A
    # missing directory is created in the primary home first; a missing file
    # is linked anyway, so whichever account writes it first writes it there.
    "shared_dirs": ["projects", "skills", "agents", "commands", "plugins", "hooks", "themes", "output-styles", "file-history", "todos", "plans"],
    "shared_files": ["settings.json", "CLAUDE.md", "history.jsonl", "keybindings.json"],
    # Keys copied from the primary's ~/.claude.json into a new account's, so a
    # second login keeps MCP servers, folder trust and onboarding choices.
    "carried_keys": ["mcpServers", "projects", "theme", "hasCompletedOnboarding", "lastOnboardingVersion", "editorMode"],
  },
  "codex": {
    "name": "Codex",
    "home_env": "CODEX_HOME",
    "shared_dirs": ["sessions", "archived_sessions", "prompts", "skills", "rules", "plugins"],
    "shared_files": ["config.toml", "AGENTS.md", "history.jsonl", "hooks.json"],
    "carried_keys": [],
  },
  "grok": {
    "name": "Grok",
    "home_env": "GROK_HOME",
    "shared_dirs": ["sessions", "skills", "agents", "plugins", "installed-plugins", "marketplace-cache", "hooks", "memory", "memory-v2", "rules", "commands", "workflows", "personas", "worktrees"],
    "shared_files": ["config.toml", "AGENTS.md", "settings.json", "lsp.json", "pager.toml", "sandbox.toml", "trusted_folders.toml", "statusline.sh", "worktrees.db"],
    "carried_keys": [],
  },
}

DEFAULT_THRESHOLD = 95
# Ids an account can't take because something else already answers to them:
# `use next` cycles, a provider name is read as the provider when it comes
# first, and the menu's Add Account row is `.add`.
RESERVED_IDS = {"next", "add", "claude", "codex", "grok", "primary"}
LOGIN_RECEIPT = ".omarchy-login.json"

# Providers whose running sessions follow a switch: Claude Code re-reads its
# credentials when the file changes, while Codex keeps the account it started as.
SEATED = {"claude"}


class AccountError(Exception):
  pass


# ------------------------------------------------------------------- paths


def state_root() -> Path:
  return Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local" / "state") / "omarchy" / "agents"


def accounts_root() -> Path:
  return state_root() / "accounts"


def registry_path(provider: str) -> Path:
  return accounts_root() / f"{provider}.json"


def usage_record_path(provider: str) -> Path:
  return state_root() / "usage" / f"{provider}.json"


# The primary home is where the CLI keeps a login when nothing tells it
# otherwise. It is deliberately not read from CLAUDE_CONFIG_DIR / CODEX_HOME /
# GROK_HOME:
# those are how an added account is selected, so honoring them here would make
# whichever account launched this command look like the primary.
def primary_home(provider: str) -> Path:
  return Path.home() / f".{provider}"


def account_home(provider: str, account: dict[str, Any]) -> Path:
  home = str(account.get("home") or "")
  return Path(home) if home else primary_home(provider)


# Claude keeps its account file beside the config dir for the default home
# (~/.claude.json) and inside it for any other.
def claude_account_file(home: Path) -> Path:
  if home == primary_home("claude"):
    return Path.home() / ".claude.json"
  return home / ".claude.json"


# Where an account's login waits while another account is seated. The
# primary's login gets a home of its own the first time it's moved out.
def store_home(provider: str, account: dict[str, Any]) -> Path:
  if provider in SEATED and account.get("primary"):
    return accounts_root() / provider / ".primary"
  return account_home(provider, account)


# Where an account's login is right now.
def login_home(provider: str, registry: dict[str, Any], account: dict[str, Any]) -> Path:
  if provider in SEATED:
    return primary_home(provider) if account["id"] == registry["seated"] else store_home(provider, account)
  return account_home(provider, account)


# --------------------------------------------------------------- identity


def read_json(path: Path) -> Any:
  try:
    return json.loads(path.read_text(encoding="utf-8"))
  except Exception:
    return None


def plan_label(tier: str, subscription: str) -> str:
  match = re.search(r"max_(\d+x)", tier or "", re.IGNORECASE)
  if match:
    return "Max " + match.group(1)
  if subscription:
    return subscription[0].upper() + subscription[1:]
  return ""


def jwt_claims(token: str) -> dict[str, Any]:
  try:
    payload = token.split(".")[1]
    payload += "=" * (-len(payload) % 4)
    claims = json.loads(base64.urlsafe_b64decode(payload.encode("ascii")))
    return claims if isinstance(claims, dict) else {}
  except Exception:
    return {}


# Who a home is signed in as, from files the CLI wrote at login. Only
# display-safe fields come out; an empty accountId means nobody is signed in.
def identity(provider: str, home: Path) -> dict[str, str]:
  if provider == "claude":
    account = (read_json(claude_account_file(home)) or {}).get("oauthAccount") or {}
    login = (read_json(home / ".credentials.json") or {}).get("claudeAiOauth") or {}
    return {
      "accountId": str(account.get("accountUuid") or ""),
      "email": str(account.get("emailAddress") or ""),
      "org": str(account.get("organizationName") or ""),
      "plan": plan_label(str(login.get("rateLimitTier") or ""), str(login.get("subscriptionType") or "")),
    }

  if provider == "grok":
    return grok_identity(home)

  auth = read_json(home / "auth.json") or {}
  tokens = auth.get("tokens") or {}
  claims = jwt_claims(str(tokens.get("id_token") or ""))
  openai = claims.get("https://api.openai.com/auth") or {}
  plan = str(openai.get("chatgpt_plan_type") or "")
  return {
    "accountId": str(tokens.get("account_id") or openai.get("chatgpt_account_id") or ""),
    "email": str(claims.get("email") or ""),
    "org": "",
    "plan": plan[0].upper() + plan[1:] if plan else "",
  }


# Grok keeps one login per issuer in auth.json, and the plan only in the
# settings it caches from xAI, as a JSON string inside that file.
def grok_identity(home: Path) -> dict[str, str]:
  auth = read_json(home / "auth.json") or {}
  login = next((v for v in auth.values() if isinstance(v, dict)), {}) if isinstance(auth, dict) else {}
  try:
    settings = json.loads((read_json(home / "settings_cache.json") or {}).get("payload") or "{}").get("settings") or {}
  except Exception:
    settings = {}
  return {
    "accountId": str(login.get("user_id") or ""),
    "email": str(login.get("email") or ""),
    "org": "",
    "plan": str((settings if isinstance(settings, dict) else {}).get("subscription_tier_display") or ""),
  }


# ---------------------------------------------------------------- registry


def slug(label: str) -> str:
  return re.sub(r"[^a-z0-9]+", "-", label.lower()).strip("-")


def empty_registry(provider: str) -> dict[str, Any]:
  seated = {"seated": ""} if provider in SEATED else {}
  return {"active": "main", "threshold": DEFAULT_THRESHOLD, "alert": "", "held": "", "accounts": []} | seated


def primary_entry(provider: str) -> dict[str, Any]:
  entry = {"id": "main", "label": "Main", "home": "", "primary": True}
  entry.update(identity(provider, primary_home(provider)))
  return entry


def normalized(provider: str, data: Any) -> dict[str, Any]:
  registry = empty_registry(provider)
  if isinstance(data, dict):
    registry.update({key: data[key] for key in registry if key in data})
  accounts = [a for a in registry["accounts"] if isinstance(a, dict) and a.get("id")]
  if not any(a.get("primary") for a in accounts):
    accounts.insert(0, primary_entry(provider))
  registry["accounts"] = accounts
  try:
    registry["threshold"] = max(50, min(100, int(registry["threshold"])))
  except Exception:
    registry["threshold"] = DEFAULT_THRESHOLD
  if not find(registry, registry["active"]):
    registry["active"] = accounts[0]["id"]
  # A registry from before seating has the primary's login in ~/.claude.
  if provider in SEATED and not any(a["id"] == registry["seated"] for a in accounts):
    registry["seated"] = next(a for a in accounts if a.get("primary"))["id"]
  return registry


def load(provider: str) -> dict[str, Any]:
  return normalized(provider, read_json(registry_path(provider)))


def save(provider: str, registry: dict[str, Any]) -> None:
  # The usage collectors read the registry file directly, and need to know
  # where each login is to read its token.
  if provider in SEATED:
    for account in registry["accounts"]:
      account["login"] = str(login_home(provider, registry, account))
  path = registry_path(provider)
  path.parent.mkdir(parents=True, exist_ok=True)
  os.chmod(path.parent, 0o700)
  fd, tmp = tempfile.mkstemp(prefix=path.name + ".", dir=str(path.parent))
  try:
    with os.fdopen(fd, "w", encoding="utf-8") as handle:
      json.dump(registry, handle, indent=2)
      handle.write("\n")
    os.chmod(tmp, 0o600)
    os.replace(tmp, path)
  except Exception:
    Path(tmp).unlink(missing_ok=True)
    raise


# Every change is read-modify-write under one lock per provider, so the panel,
# the limit alert run after each usage update, and a command typed at a prompt
# can't interleave and drop each other's edits.
class Locked:
  def __init__(self, provider: str, save_on_exit: bool = True):
    self.provider = provider
    self.save_on_exit = save_on_exit

  def __enter__(self) -> dict[str, Any]:
    accounts_root().mkdir(parents=True, exist_ok=True)
    self.handle = open(accounts_root() / f".{self.provider}.lock", "w")
    fcntl.flock(self.handle, fcntl.LOCK_EX)
    self.registry = load(self.provider)
    return self.registry

  def __exit__(self, kind, value, traceback) -> None:
    try:
      if kind is None and self.save_on_exit:
        save(self.provider, self.registry)
    finally:
      fcntl.flock(self.handle, fcntl.LOCK_UN)
      self.handle.close()


def find(registry: dict[str, Any], account_id: str) -> dict[str, Any] | None:
  for account in registry["accounts"]:
    if account.get("id") == account_id:
      return account
  # `primary` names the login that was there first, whatever it's called now.
  if account_id == "primary":
    for account in registry["accounts"]:
      if account.get("primary"):
        return account
  return None


def active(registry: dict[str, Any]) -> dict[str, Any]:
  return find(registry, registry["active"]) or registry["accounts"][0]


# ------------------------------------------------------------------- homes


# Lay the links that make an added account share everything but its login
# with the primary home. Safe to repeat: an existing link or real file is left
# as it is, so nothing an account wrote for itself is ever replaced.
def link_shared(provider: str, home: Path) -> None:
  spec = PROVIDERS[provider]
  primary = primary_home(provider)
  home.mkdir(parents=True, exist_ok=True)
  os.chmod(home, 0o700)
  for name in spec["shared_dirs"]:
    shared = primary / name
    # A dangling symlink is the person's own setup, such as a dotfiles link
    # whose target hasn't synced yet, so leave it for its target to appear.
    # mkdir would fail on it. A link to a file or a loop still fails here.
    if shared.is_symlink() and not shared.exists():
      try:
        shared.resolve(strict=True)
      except FileNotFoundError:
        continue
    shared.mkdir(parents=True, exist_ok=True)
  for name in spec["shared_dirs"] + spec["shared_files"]:
    target = home / name
    if target.exists() or target.is_symlink():
      continue
    target.symlink_to(primary / name)


def carry_settings(provider: str, home: Path) -> None:
  keys = PROVIDERS[provider]["carried_keys"]
  if not keys:
    return
  source = read_json(claude_account_file(primary_home(provider))) or {}
  path = claude_account_file(home)
  data = read_json(path) or {}
  for key in keys:
    if key in source and key not in data:
      data[key] = source[key]
  fd, tmp = tempfile.mkstemp(prefix=path.name + ".", dir=str(path.parent))
  with os.fdopen(fd, "w", encoding="utf-8") as handle:
    json.dump(data, handle, indent=2)
  os.chmod(tmp, 0o600)
  os.replace(tmp, path)


# A login in progress gets a scratch home beside the real ones. Its receipt
# lets a completed login survive interruption without exposing credentials.
def process_start(pid: int) -> str:
  try:
    # The command name can contain spaces and parentheses.
    return Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[19]
  except (OSError, IndexError):
    return ""


def write_receipt(home: Path, receipt: dict[str, Any]) -> None:
  path = home / LOGIN_RECEIPT
  fd, tmp = tempfile.mkstemp(prefix=LOGIN_RECEIPT, dir=str(home))
  try:
    with os.fdopen(fd, "w", encoding="utf-8") as handle:
      json.dump(receipt, handle)
    os.chmod(tmp, 0o600)
    os.replace(tmp, path)
  finally:
    Path(tmp).unlink(missing_ok=True)


def begin(provider: str, label: str = "", owner: int = 0) -> Path:
  pending = accounts_root() / provider / ".pending"
  pending.mkdir(parents=True, exist_ok=True)
  os.chmod(pending.parent, 0o700)
  home = Path(tempfile.mkdtemp(prefix="login-", dir=str(pending)))
  try:
    link_shared(provider, home)
    write_receipt(home, {"label": label, "owner": owner, "started": process_start(owner) if owner else ""})
  except Exception:
    shutil.rmtree(home, ignore_errors=True)
    raise
  return home


def register(provider: str, label: str, pending: Path) -> dict[str, Any]:
  pending = pending.resolve()
  if pending.parent != (accounts_root() / provider / ".pending").resolve():
    raise AccountError(f"{pending} is not a pending {PROVIDERS[provider]['name']} login")

  found = identity(provider, pending)
  if not found["accountId"] or (provider == "claude" and not (read_json(pending / ".credentials.json") or {}).get("claudeAiOauth")):
    shutil.rmtree(pending, ignore_errors=True)
    raise AccountError(tr("omarchy-i18n agents.loginUnfinished", "The login didn't finish, so no account was added."))

  with Locked(provider, save_on_exit=False) as registry:
    settle(provider, registry)
    # Each home is asked who it is now, not trusted from when it was added: a
    # `claude auth login` run by hand in ~/.claude changes the primary.
    for account in registry["accounts"]:
      account.update(identity(provider, login_home(provider, registry, account)))
    for account in registry["accounts"]:
      if account.get("accountId") == found["accountId"]:
        shutil.rmtree(pending, ignore_errors=True)
        if found["email"]:
          raise AccountError(tr("omarchy-i18n agents.sameAccountEmail", "That's %1 (%2). Try again, and sign in as the other account in the private window.", account["label"], found["email"]))
        raise AccountError(tr("omarchy-i18n agents.sameAccount", "That's %1 (already added). Try again, and sign in as the other account in the private window.", account["label"]))

    label = label.strip() or found["email"].split("@")[0] or "Account"
    account_id = unique_id(provider, registry, label)

    # A failed write goes back to pending for recovery. The receipt also
    # covers abrupt death between moving the home and saving the registry.
    carry_settings(provider, pending)
    home = accounts_root() / provider / account_id
    entry = {"id": account_id, "label": label, "home": str(home), "primary": False}
    entry.update(found)
    receipt = read_json(pending / LOGIN_RECEIPT) or {}
    receipt["entry"] = entry
    write_receipt(pending, receipt)
    pending.rename(home)
    registry["accounts"].append(entry)
    try:
      save(provider, registry)
    except BaseException:
      registry["accounts"].pop()
      home.rename(pending)
      raise
    (home / LOGIN_RECEIPT).unlink(missing_ok=True)
    return entry


def recover_home(provider: str, home: Path) -> dict[str, Any] | None:
  root = accounts_root() / provider
  receipt = read_json(home / LOGIN_RECEIPT)
  if not isinstance(receipt, dict):
    return None
  owner = receipt.get("owner")
  if owner and receipt.get("started") and process_start(owner) == receipt["started"]:
    return None
  # A surviving CLI may still be writing credentials after its parent died.
  if home_in_use(provider, home):
    return None
  if not identity(provider, home)["accountId"]:
    return None
  # Claude writes its identity and credentials separately. An identity
  # alone does not mean the OAuth exchange finished.
  if provider == "claude" and not (read_json(home / ".credentials.json") or {}).get("claudeAiOauth"):
    return None
  if home.parent == root / ".pending":
    try:
      return register(provider, str(receipt.get("label") or ""), home)
    except AccountError:
      # Duplicate and unfinished logins are removed by register itself.
      if home.exists():
        raise
      return None

  # A crash between moving the home and saving the registry is also
  # recoverable: the receipt holds the exact entry prepared before moving.
  with Locked(provider, save_on_exit=False) as registry:
    # Another recovery or removal may have changed the home while we waited.
    receipt = read_json(home / LOGIN_RECEIPT)
    found = identity(provider, home)
    if not home.is_dir() or not isinstance(receipt, dict) or not found["accountId"]:
      return None
    if home_in_use(provider, home):
      return None
    if any(account_home(provider, a) == home for a in registry["accounts"]):
      # A committed account may have been renamed since the crash.
      (home / LOGIN_RECEIPT).unlink(missing_ok=True)
      return None
    entry = receipt.get("entry")
    if not isinstance(entry, dict) or entry.get("home") != str(home) or entry.get("id") != home.name:
      return None
    if any(identity(provider, login_home(provider, registry, a))["accountId"] == found["accountId"] for a in registry["accounts"]):
      # A retry may already have registered this login under another home.
      shutil.rmtree(home)
      return None
    if find(registry, entry["id"]) is not None:
      # Preserve the login, but choose a free name rather than blocking adds.
      entry["id"] = unique_id(provider, registry, entry["label"])
    entry.update(found)
    registry["accounts"].append(entry)
    save(provider, registry)
    (home / LOGIN_RECEIPT).unlink(missing_ok=True)
    return entry


def recover(provider: str) -> list[dict[str, Any]]:
  recovered = []
  root = accounts_root() / provider
  candidates = sorted((root / ".pending").glob("login-*")) + sorted(root.glob("*/"))
  for home in candidates:
    try:
      entry = recover_home(provider, home)
      if entry is not None:
        recovered.append(entry)
    except (AccountError, OSError) as error:
      # Keep the receipt for another attempt; one failed candidate must not
      # prevent other accounts and providers from refreshing.
      print(f"Could not recover {provider} account {home.name}: {error}", file=sys.stderr)
  return recovered


# The id an account answers to, from its label. It can't clash with another
# account, a routing keyword, or a home left under that name by an account
# that has since been renamed.
def unique_id(provider: str, registry: dict[str, Any], label: str, keep: dict[str, Any] | None = None) -> str:
  base = slug(label) or "account"
  account_id, n = base, 2
  while True:
    taken = find(registry, account_id)
    if account_id not in RESERVED_IDS and (taken is None or taken is keep):
      if keep is not None or not (accounts_root() / provider / account_id).exists():
        return account_id
    account_id, n = f"{base}-{n}", n + 1


# A new label, and the id that follows from it. The home stays where it is:
# sessions already running in it hold that path.
def rename(provider: str, target: str, label: str) -> dict[str, Any]:
  label = label.strip()
  if not label:
    raise AccountError("Give the account a name")
  with Locked(provider) as registry:
    account = find(registry, target)
    if not account:
      raise AccountError(f"No {PROVIDERS[provider]['name']} account named {target}")
    new_id = unique_id(provider, registry, label, keep=account)
    if not account.get("primary") and not account.get("home"):
      account["home"] = str(account_home(provider, account))
    if registry["active"] == account["id"]:
      registry["active"] = new_id
    if registry["held"] == account["id"]:
      registry["held"] = new_id
    if registry.get("seated") == account["id"]:
      registry["seated"] = new_id
    registry["alert"] = ""
    account["id"] = new_id
    account["label"] = label
    return dict(account)


# Save who each home is signed in as now. A login run in a home, through the
# panel or the CLI, changes it, and the usage records take their names and
# emails from here.
def refresh(provider: str) -> None:
  recover(provider)
  with Locked(provider) as registry:
    settle(provider, registry)
    for account in registry["accounts"]:
      account.update(identity(provider, login_home(provider, registry, account)))


# Makes an account active and, for Claude, moves its login into ~/.claude so
# running sessions follow; says whether they did, and what held them back.
def use(provider: str, target: str) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]:
  with Locked(provider) as registry:
    settle(provider, registry)
    previous = active(registry)
    if target == "next":
      ids = [a["id"] for a in registry["accounts"]]
      target = ids[(ids.index(previous["id"]) + 1) % len(ids)]
    account = find(registry, target)
    if not account:
      raise AccountError(f"No {PROVIDERS[provider]['name']} account named {target}")
    registry["active"] = account["id"]
    registry["alert"] = ""
    # Every caller is a person choosing, so nothing is said about how full it is.
    registry["held"] = account["id"]
    followed = follow(provider, registry, account)
    if provider in SEATED:
      if not followed["seated"]:
        prepare_store(provider, account)
    elif not account.get("primary"):
      link_shared(provider, account_home(provider, account))
    return previous, account, followed


# The processes started in this home, other than this one. Moving or removing
# its login would pull it out from under them, which must never happen.
def home_users(provider: str, home: Path) -> list[int]:
  wanted = f"{PROVIDERS[provider]['home_env']}=".encode()
  resolved = home.resolve()
  users = []
  for environ in Path("/proc").glob("[0-9]*/environ"):
    pid = int(environ.parent.name)
    if pid == os.getpid():
      continue
    try:
      entries = environ.read_bytes().split(b"\0")
    except OSError:
      continue
    for entry in entries:
      if entry.startswith(wanted) and Path(entry[len(wanted):].decode(errors="replace")).resolve() == resolved:
        users.append(pid)
        break
  return users


# The CLI's processes started as the primary, which name no home: they're
# found by the program they run instead.
def primary_users(provider: str) -> list[int]:
  wanted = f"{PROVIDERS[provider]['home_env']}=".encode()
  users = []
  for cmdline in Path("/proc").glob("[0-9]*/cmdline"):
    pid = int(cmdline.parent.name)
    if pid == os.getpid():
      continue
    try:
      args = cmdline.read_bytes().split(b"\0")[:2]
      entries = (cmdline.parent / "environ").read_bytes().split(b"\0")
    except OSError:
      continue
    if not any(arg and Path(arg.decode(errors="replace")).stem == provider for arg in args):
      continue
    if any(entry.startswith(wanted) and len(entry) > len(wanted) for entry in entries):
      continue
    users.append(pid)
  return users


def home_in_use(provider: str, home: Path) -> bool:
  return bool(home_users(provider, home))


# ----------------------------------------------------------------- seating


def label_of(account: dict[str, Any]) -> str:
  return str(account.get("label") or account["id"])


def oauth(home: Path) -> dict[str, Any]:
  login = (read_json(home / ".credentials.json") or {}).get("claudeAiOauth")
  return login if isinstance(login, dict) else {}


def has_login(home: Path) -> bool:
  return bool(oauth(home))


# An account's own home, ready to hold its login or start a session in. The
# primary's is made the first time it's needed, with the primary's settings.
def prepare_store(provider: str, account: dict[str, Any]) -> Path:
  home = store_home(provider, account)
  fresh = not home.exists()
  link_shared(provider, home)
  if fresh:
    carry_settings(provider, home)
  return home


# Claude Code's own lock directories, each stale once its mtime is that old: a
# refresh holds <home>/.oauth_refresh.lock and <home>.lock, a config write ~/.claude.json.lock.
def claude_locks(homes: list[Path]) -> list[tuple[Path, float]]:
  locks = []
  for home in dict.fromkeys(homes):
    locks += [(home / ".oauth_refresh.lock", 60), (Path(f"{home.resolve()}.lock"), 60)]
  return locks + [(Path(f"{claude_account_file(primary_home('claude'))}.lock"), 10)]


class LockDirs:
  def __init__(self, locks: list[tuple[Path, float]], wait: float = 15):
    self.locks = locks
    self.wait = wait
    self.held: list[Path] = []

  def __enter__(self) -> None:
    deadline = time.monotonic() + self.wait
    try:
      for path, stale in self.locks:
        while True:
          try:
            path.mkdir()
            self.held.append(path)
            break
          except FileExistsError:
            pass
          try:
            if time.time() - path.stat().st_mtime > stale:
              path.rmdir()
              continue
          except FileNotFoundError:
            continue
          except OSError:
            pass
          if time.monotonic() > deadline:
            raise AccountError("A Claude session is renewing its sign-in. Try again in a moment.")
          time.sleep(0.2)
    except BaseException:
      self.__exit__(None, None, None)
      raise

  def __exit__(self, kind, value, traceback) -> None:
    for path in reversed(self.held):
      try:
        path.rmdir()
      except OSError:
        pass
    self.held = []


def write_private(path: Path, text: str) -> None:
  # A dotfiles symlink stays a symlink; its target is what's replaced.
  path = path.resolve()
  fd, tmp = tempfile.mkstemp(prefix=path.name + ".", dir=str(path.parent))
  try:
    with os.fdopen(fd, "w", encoding="utf-8") as handle:
      handle.write(text)
    os.chmod(tmp, 0o600)
    os.replace(tmp, path)
  except BaseException:
    Path(tmp).unlink(missing_ok=True)
    raise


# Refuses an account file that exists but doesn't parse: ~/.claude.json holds
# far more than the login, and rewriting it from empty would lose the rest.
def account_config(path: Path) -> dict[str, Any]:
  if not path.exists():
    return {}
  data = read_json(path)
  if not isinstance(data, dict):
    raise AccountError(f"{path} can't be read, so no login was moved.")
  return data


def put_login(home: Path, credentials: str, profile: Any) -> None:
  path = claude_account_file(home)
  config = account_config(path)
  if profile is None:
    config.pop("oauthAccount", None)
  else:
    config["oauthAccount"] = profile
  write_private(home / ".credentials.json", credentials)
  write_private(path, json.dumps(config, indent=2))


# Swaps the target's login into ~/.claude under Claude's locks, so no session
# refreshes mid-move. Returns the processes holding the target's home, which block it.
def seat(provider: str, registry: dict[str, Any], target: dict[str, Any]) -> list[int]:
  if provider not in SEATED or registry["seated"] == target["id"]:
    return []
  source = store_home(provider, target)
  primary = primary_home(provider)
  users = home_users(provider, source)
  if users or not has_login(source):
    return users
  current = find(registry, registry["seated"])
  park = prepare_store(provider, current)
  with LockDirs(claude_locks([primary, source, park])):
    # A session may have started there while the locks were awaited.
    users = home_users(provider, source)
    if users:
      return users
    seated_credentials = (primary / ".credentials.json").read_text(encoding="utf-8") if has_login(primary) else ""
    seated_profile = account_config(claude_account_file(primary)).get("oauthAccount")
    credentials = (source / ".credentials.json").read_text(encoding="utf-8")
    profile = account_config(claude_account_file(source)).get("oauthAccount")
    if seated_credentials:
      put_login(park, seated_credentials, seated_profile)
    try:
      put_login(primary, credentials, profile)
    except BaseException:
      # Half a move would leave ~/.claude's token and profile naming two
      # different accounts. The parked copy is cleared by the next settle.
      if seated_credentials:
        put_login(primary, seated_credentials, seated_profile)
      raise
    users = home_users(provider, source)
    if users:
      if seated_credentials:
        put_login(primary, seated_credentials, seated_profile)
      return users
    registry["seated"] = target["id"]
    save(provider, registry)
    # Only now that ~/.claude has it: a login is kept in one place, since a
    # refresh token works once and a copy left here would die at the next one.
    (source / ".credentials.json").unlink(missing_ok=True)
  return []


# A move cut short leaves ~/.claude's very token in some home as well: that
# account is seated, the copy goes, and ~/.claude takes its profile again.
def settle(provider: str, registry: dict[str, Any]) -> None:
  if provider not in SEATED:
    return
  primary = primary_home(provider)
  login = oauth(primary)
  holder = next((a for a in registry["accounts"] if login and oauth(store_home(provider, a)) == login), None)
  if holder is None:
    return
  store = store_home(provider, holder)
  profile = account_config(claude_account_file(store)).get("oauthAccount")
  path = claude_account_file(primary)
  config = account_config(path)
  if isinstance(profile, dict) and (config.get("oauthAccount") or {}).get("accountUuid") != profile.get("accountUuid"):
    with LockDirs(claude_locks([])):
      config = account_config(path)
      config["oauthAccount"] = profile
      write_private(path, json.dumps(config, indent=2))
  # Saved before the copy goes, since the copy is the only other record of
  # whose token ~/.claude holds, and the command that called this may fail.
  if registry["seated"] != holder["id"]:
    registry["seated"] = holder["id"]
    save(provider, registry)
  if not home_in_use(provider, store):
    (store / ".credentials.json").unlink(missing_ok=True)


# A Claude account signed in again in a scratch home, installed where its login
# lives under the same locks as a move, and only if it's the same account.
def relogin(provider: str, target: str, pending: Path) -> dict[str, Any]:
  pending = pending.resolve()
  if provider not in SEATED or pending.parent != (accounts_root() / provider / ".pending").resolve():
    raise AccountError(f"{pending} is not a pending {PROVIDERS[provider]['name']} login")
  try:
    found = identity(provider, pending)
    if not found["accountId"] or not has_login(pending):
      raise AccountError(tr("omarchy-i18n agents.signInFailed", "The %1 sign-in didn't finish.", PROVIDERS[provider]["name"]))
    with Locked(provider) as registry:
      settle(provider, registry)
      account = find(registry, target)
      if not account:
        raise AccountError(f"No {PROVIDERS[provider]['name']} account named {target}")
      if account.get("accountId") and account["accountId"] != found["accountId"]:
        raise AccountError(tr("omarchy-i18n agents.wrongAccount", "That's %1, not %2. Try again, and sign in as %2.", found["email"] or found["accountId"], label_of(account)))
      home = login_home(provider, registry, account)
      if home != primary_home(provider):
        prepare_store(provider, account)
      with LockDirs(claude_locks([home])):
        put_login(home, (pending / ".credentials.json").read_text(encoding="utf-8"), account_config(claude_account_file(pending)).get("oauthAccount"))
      account.update(identity(provider, home))
      return dict(account)
  finally:
    shutil.rmtree(pending, ignore_errors=True)


def follow(provider: str, registry: dict[str, Any], account: dict[str, Any]) -> dict[str, Any]:
  if provider not in SEATED:
    return {"seated": False, "moved": False, "holders": []}
  before = registry["seated"]
  holders = seat(provider, registry, account)
  running = label_of(find(registry, registry["seated"]))
  return {"seated": registry["seated"] == account["id"], "moved": registry["seated"] != before, "holders": holders, "running": running}


def refuse_in_use(provider: str, home: Path, account: dict[str, Any]) -> None:
  if home_in_use(provider, home):
    raise AccountError(f"A running {PROVIDERS[provider]['name']} session uses {label_of(account)}. Quit it first, then remove the account.")


# Only an account's own directory goes. Its links point into the primary home,
# and rmtree removes a link without following it.
def remove_home(provider: str, home: Path) -> None:
  if home.resolve().parent == (accounts_root() / provider).resolve():
    shutil.rmtree(home, ignore_errors=True)


# The files a login is, in a home of Codex or Grok; Claude's is its
# credentials plus the profile in its account file.
LOGIN_FILES = {"codex": ["auth.json"], "grok": ["auth.json", "settings_cache.json"]}


# Signs a home out here without logging out, which would revoke the sign-in
# everywhere else it's used too.
def forget_login(provider: str, home: Path) -> None:
  if provider == "claude":
    with LockDirs(claude_locks([home])):
      # Read first: an account file that can't be read stops this before the
      # credentials go.
      path = claude_account_file(home)
      config = account_config(path)
      (home / ".credentials.json").unlink(missing_ok=True)
      if config.pop("oauthAccount", None) is not None:
        write_private(path, json.dumps(config, indent=2))
  else:
    for name in LOGIN_FILES[provider]:
      (home / name).unlink(missing_ok=True)


# The primary home is shared by every account, so it stays: the account taking
# over as primary puts its login in it. Returns the homes to delete once the
# registry is saved, so a save that fails leaves every login somewhere a
# retry finds it.
def promote(provider: str, registry: dict[str, Any], old: dict[str, Any], successor: dict[str, Any]) -> list[Path]:
  own = account_home(provider, successor)
  refuse_in_use(provider, own, successor)
  if provider in SEATED:
    # Seated already, so its login is in ~/.claude and the old primary's in
    # the store primaries keep theirs in, which goes with it.
    parked = store_home(provider, old)
    refuse_in_use(provider, parked, old)
    gone = [parked, own]
  else:
    primary = primary_home(provider)
    refuse_in_use(provider, primary, old)
    if primary_users(provider):
      raise AccountError(f"A running {PROVIDERS[provider]['name']} session uses {label_of(old)}. Quit it first, then remove the account.")
    # Copied, not moved: its own home keeps the login until the registry
    # says the primary home holds it.
    for name in LOGIN_FILES[provider]:
      target = (primary / name).resolve()
      if (own / name).exists():
        staged = target.with_name(f".{target.name}.omarchy")
        shutil.copy2(own / name, staged)
        os.replace(staged, target)
      else:
        target.unlink(missing_ok=True)
    gone = [own]
  successor.update({"home": "", "primary": True})
  return gone


# Forgets an account. One that sessions use hands them to another account
# first, the primary hands that role on, and the only one is signed out here.
# The account comes back with `last` saying whether it was the only one.
def remove(provider: str, target: str) -> dict[str, Any]:
  with Locked(provider, save_on_exit=False) as registry:
    settle(provider, registry)
    account = find(registry, target)
    if not account:
      raise AccountError(f"No {PROVIDERS[provider]['name']} account named {target}")
    others = [a for a in registry["accounts"] if a["id"] != account["id"]]
    if not others:
      # The only account is the primary, its login in the primary home.
      home = primary_home(provider)
      forget_login(provider, home)
      account.update(identity(provider, home))
      registry.update({"alert": "", "held": ""})
      save(provider, registry)
      return dict(account, last=True)

    # The account seated in ~/.claude takes over, so no login moves twice;
    # else the primary, else the next one.
    successor = (next((a for a in others if provider in SEATED and a["id"] == registry["seated"]), None)
                 or next((a for a in others if a.get("primary")), None) or others[0])
    if provider in SEATED and registry["seated"] == account["id"]:
      holders = seat(provider, registry, successor)
      if registry["seated"] == account["id"]:
        if holders:
          raise AccountError(f"A running {PROVIDERS[provider]['name']} session uses {label_of(successor)}, so sessions can't move to it. Quit it first, then remove {label_of(account)}.")
        raise AccountError(f"{label_of(successor)} isn't signed in, so sessions can't move to it. Sign it in again first, then remove {label_of(account)}.")

    if account.get("primary"):
      gone = promote(provider, registry, account, successor)
    else:
      home = account_home(provider, account)
      refuse_in_use(provider, home, account)
      gone = [home]
    registry["accounts"] = others
    if registry["active"] == account["id"]:
      registry["active"] = successor["id"]
    registry["alert"] = ""
    if registry["held"] == account["id"]:
      registry["held"] = ""
    save(provider, registry)
    for home in gone:
      remove_home(provider, home)
    return dict(account, last=False)


def set_threshold(provider: str, threshold: str) -> dict[str, Any]:
  with Locked(provider) as registry:
    try:
      registry["threshold"] = max(50, min(100, int(threshold)))
    except ValueError:
      raise AccountError("The threshold is a percentage between 50 and 100")
    registry["alert"] = ""
    return dict(registry)


# ------------------------------------------------------------ limit alerts


def window_open(limit: dict[str, Any], now: dt.datetime) -> bool:
  raw = str(limit.get("resetsAt") or "")
  if not raw:
    return True
  try:
    resets_at = dt.datetime.fromisoformat(raw.replace("Z", "+00:00"))
  except Exception:
    return True
  if resets_at.tzinfo is None:
    resets_at = resets_at.replace(tzinfo=dt.timezone.utc)
  return resets_at > now


# How spent an account is: its fullest window that hasn't reset yet, in
# percent. A window whose reset has passed counts as empty even when the
# numbers are stale, since that's exactly what a reset means. None when
# nothing is known at all.
def peak(limits: Any, now: dt.datetime) -> float | None:
  if not isinstance(limits, list):
    return None
  known = [l for l in limits if isinstance(l, dict) and isinstance(l.get("percent"), (int, float))]
  if not known:
    return None
  open_windows = [float(l["percent"]) * 100 for l in known if window_open(l, now)]
  return max(open_windows) if open_windows else 0.0


def next_reset(limits: Any, now: dt.datetime) -> dt.datetime | None:
  times = []
  for limit in limits if isinstance(limits, list) else []:
    try:
      when = dt.datetime.fromisoformat(str(limit.get("resetsAt") or "").replace("Z", "+00:00"))
    except Exception:
      continue
    if when.tzinfo is None:
      when = when.replace(tzinfo=dt.timezone.utc)
    if when > now:
      times.append(when)
  return min(times) if times else None


# When an account over the threshold drops back under it: once every window
# holding it there has reset, which is the latest of those resets. A 10%
# session resetting in an hour doesn't help an account whose weekly window is
# full for six more days. None when a blocking window never says.
def available_at(limits: Any, threshold: float, now: dt.datetime) -> dt.datetime | None:
  latest = None
  for limit in limits if isinstance(limits, list) else []:
    if not isinstance(limit, dict) or not isinstance(limit.get("percent"), (int, float)):
      continue
    if float(limit["percent"]) * 100 < threshold or not window_open(limit, now):
      continue
    try:
      when = dt.datetime.fromisoformat(str(limit.get("resetsAt") or "").replace("Z", "+00:00"))
    except Exception:
      return None
    if when.tzinfo is None:
      when = when.replace(tzinfo=dt.timezone.utc)
    latest = when if latest is None or when > latest else latest
  return latest


def duration(delta: dt.timedelta) -> str:
  minutes = max(1, int(delta.total_seconds() // 60))
  hours, minutes = divmod(minutes, 60)
  days, hours = divmod(hours, 24)
  if days:
    return tr("omarchy-i18n agents.durationDaysHours", "%1d %2h", days, hours)
  if hours:
    return tr("omarchy-i18n battery.durationHoursMinutes", "%1h %2m", hours, minutes)
  return tr("omarchy-i18n battery.durationMinutes", "%1m", minutes)


# The whole alert policy, with no I/O: given the registry and the per
# account limits from the usage record, what should be said. Returns None when
# nothing should, or {"action": "notify"|"exhausted"|"clear", ...}. The
# account never changes here: a notification offers the switch and a person
# takes it.
#
# Only the active account crossing the threshold starts anything. `alert`
# remembers the last thing said, so a shell restart or the next refresh
# doesn't repeat it.
#
# Numbers kept from an earlier check may be out of date, but a parked account's
# sign-in lapses within hours and can't be checked again until a session runs
# in it. So a stale account is still a candidate: among accounts with room, one
# checked just now wins, but room comes first. An account within 15 points of
# the threshold (where the panel starts checking more often) is near its limit
# however fresh its numbers are.
#
# An account chosen by hand is held there however full it is, and nothing is
# offered or announced about it, until a fresh check sees it under the
# threshold again; from then on it is announced like any other.
def decide(registry: dict[str, Any], usage: dict[str, Any], now: dt.datetime, stale: frozenset[str] = frozenset()) -> dict[str, Any] | None:
  threshold = float(registry["threshold"])
  current = active(registry)
  current_peak = peak(usage.get(current["id"]), now)
  if current_peak is None or current_peak < threshold:
    release = current_peak is not None and current["id"] not in stale and bool(registry.get("held"))
    return {"action": "clear", "release": release} if registry.get("alert") or release else None
  if registry.get("held") == current["id"]:
    return None

  candidates = []
  for account in registry["accounts"]:
    if account["id"] == current["id"]:
      continue
    level = peak(usage.get(account["id"]), now)
    if level is None or level >= threshold:
      continue
    reset = next_reset(usage.get(account["id"]), now) or dt.datetime.max.replace(tzinfo=dt.timezone.utc)
    candidates.append((level >= threshold - 15, account["id"] in stale, level, reset, account))
  candidates.sort(key=lambda c: c[:4])

  if candidates:
    _, _, level, _, target = candidates[0]
    alert = f"notify:{current['id']}:{target['id']}"
    if registry.get("alert") == alert:
      return None
    return {"action": "notify", "alert": alert, "from": current, "to": target, "fromPeak": current_peak, "toPeak": level}

  alert = f"exhausted:{current['id']}"
  if registry.get("alert") == alert or len(registry["accounts"]) < 2:
    return None
  # Only when every account is known to be over. One that's signed out or
  # couldn't be checked might have room, so there's nothing honest to say.
  if any(peak(usage.get(a["id"]), now) is None for a in registry["accounts"]):
    return None
  soonest = None
  for account in registry["accounts"]:
    reset = available_at(usage.get(account["id"]), threshold, now)
    if reset and (soonest is None or reset < soonest[0]):
      soonest = (reset, account)
  return {"action": "exhausted", "alert": alert, "from": current, "fromPeak": current_peak, "soonest": soonest}


# Limits per account id. An account nobody is signed in to is left out, so it
# is never a candidate: its cached headroom is no use to a session that can't
# start. One whose token merely expired stays in, since a session refreshes it.
def usage_by_account(provider: str) -> tuple[dict[str, Any], frozenset[str]]:
  record = read_json(usage_record_path(provider)) or {}
  accounts = [
    a for a in record.get("accounts") or []
    if isinstance(a, dict) and a.get("id") and a.get("usageStatusText") != "Waiting for auth"
  ]
  return (
    {str(a["id"]): a.get("limits") for a in accounts},
    frozenset(str(a["id"]) for a in accounts if a.get("stale") is True),
  )


# What a person reads, in the Omarchy language. Each lookup is written as
# "omarchy-i18n <key>", the form the catalog check finds references by, and
# carries its English, which stands in when the lookup can't run (as in tests
# that leave OMARCHY_PATH unset) or the key isn't in the catalog yet.
def tr(lookup: str, english: str, *args: Any) -> str:
  key = lookup.split()[1]
  values = [str(arg) for arg in args]
  try:
    text = subprocess.run(["omarchy-i18n", key, *values], capture_output=True, text=True, check=True).stdout
  except (OSError, subprocess.CalledProcessError):
    text = ""
  if not text or text == key:
    text = english
    for index in range(len(values), 0, -1):
      text = text.replace(f"%{index}", values[index - 1])
  return text


# Carries the agent's own logo, as the sign-in notifications do.
def notify(provider: str, title: str, body: str, action: list[str] | None = None) -> None:
  command = ["omarchy-notification-send", "--app-name", "Omarchy Agents", "-g", "󰚩"]
  try:
    logo = subprocess.run(["omarchy-agent-logo", provider], capture_output=True, text=True, check=True).stdout.strip()
  except (OSError, subprocess.CalledProcessError):
    logo = ""
  if logo:
    command += ["--image", logo]
  command += [title, body]
  if action:
    command += ["--exec"] + action
  subprocess.run(command, check=False)


# A switch held back by sessions running in the account's own home completes
# once they've gone, so running sessions in ~/.claude move to the chosen account.
def catch_up(provider: str, registry: dict[str, Any]) -> None:
  if provider not in SEATED:
    return
  settle(provider, registry)
  target = active(registry)
  if registry["seated"] == target["id"]:
    return
  previous = find(registry, registry["seated"])
  try:
    moved = follow(provider, registry, target)["moved"]
  except AccountError:
    return
  if moved:
    notify(
      provider,
      tr("omarchy-i18n agents.sessionsUse", "%1 sessions now use %2", PROVIDERS[provider]["name"], label_of(target)),
      tr("omarchy-i18n agents.runningCaughtUp", "Running sessions on %1 moved over too.", label_of(previous)),
    )


def alert(provider: str, now: dt.datetime | None = None) -> None:
  now = now or dt.datetime.now(dt.timezone.utc)
  name = PROVIDERS[provider]["name"]
  with Locked(provider) as registry:
    if len(registry["accounts"]) < 2:
      registry["held"] = ""
      return
    catch_up(provider, registry)
    usage, stale = usage_by_account(provider)
    decision = decide(registry, usage, now, stale)
    if decision is None:
      return
    if decision["action"] == "clear":
      registry["alert"] = ""
      if decision["release"]:
        registry["held"] = ""
      return

    registry["alert"] = decision["alert"]
    source = decision["from"]
    threshold = registry["threshold"]
    if decision["action"] == "exhausted":
      soonest = decision["soonest"]
      if soonest:
        body = tr("omarchy-i18n agents.stayingOnUntil", "Staying on %1. %2 resets in %3.", source["label"], soonest[1]["label"], duration(soonest[0] - now))
      else:
        body = tr("omarchy-i18n agents.stayingOn", "Staying on %1.", source["label"])
      notify(provider, tr("omarchy-i18n agents.allOver", "All %1 accounts are over %2%", name, threshold), body)
      return

    target = decision["to"]
    headline = tr("omarchy-i18n agents.atLimit", "%1 is at %2% of a %3 limit", source["label"], round(decision["fromPeak"]), name)
    notify(
      provider,
      headline,
      tr("omarchy-i18n agents.offerSwitch", "%1 is at %2%. Click to switch new sessions to it.", target["label"], round(decision["toPeak"])),
      ["omarchy-agent-account-use", provider, target["id"]],
    )


# --------------------------------------------------------------------- CLI


def provider_arg(args: list[str]) -> str:
  if not args or args[0] not in PROVIDERS:
    raise AccountError("Name a provider: claude, codex, or grok")
  return args[0]


def summary(provider: str, registry: dict[str, Any]) -> dict[str, Any]:
  # Identity is re-read from each home rather than trusted from the registry:
  # a `claude auth login` run by hand in a home changes who it is.
  for account in registry["accounts"]:
    account.update(identity(provider, login_home(provider, registry, account)))
  return {
    "provider": provider,
    "name": PROVIDERS[provider]["name"],
    "active": registry["active"],
    "threshold": registry["threshold"],
    "accounts": [
      {key: account.get(key, "") for key in ("id", "label", "email", "org", "plan", "primary")}
      | {
        "home": str(login_home(provider, registry, account)),
        "active": account["id"] == registry["active"],
        "signedIn": bool(account.get("accountId")),
      }
      for account in registry["accounts"]
    ],
  }


def main(argv: list[str]) -> int:
  if not argv:
    print(__doc__.strip().splitlines()[0], file=sys.stderr)
    return 1
  command, args = argv[0], argv[1:]
  try:
    if command == "registry":
      provider = provider_arg(args)
      print(json.dumps(summary(provider, load(provider))))
    elif command == "list":
      providers = [provider_arg(args)] if args else list(PROVIDERS)
      print(json.dumps([summary(p, load(p)) for p in providers]))
    elif command == "home":
      # Empty for the primary home, so launching there needs no environment
      # at all. A Claude account starts in its own home only while its login
      # couldn't move into ~/.claude.
      provider = provider_arg(args)
      registry = read_json(registry_path(provider))
      if registry:
        registry = normalized(provider, registry)
        account = active(registry)
        if provider in SEATED:
          if account["id"] != registry["seated"]:
            print(store_home(provider, account))
        elif not account.get("primary"):
          print(account_home(provider, account))
    elif command == "homes":
      # Where each account's login is now, for signing it in again there.
      provider = provider_arg(args)
      registry = load(provider)
      for account in registry["accounts"]:
        print("\t".join([account["id"], str(login_home(provider, registry, account)), "1" if account["id"] == registry["active"] else "0", "1" if account.get("primary") else "0"]))
    elif command == "refresh":
      for provider in ([provider_arg(args)] if args else list(PROVIDERS)):
        if registry_path(provider).exists() or (accounts_root() / provider).is_dir():
          refresh(provider)
    elif command == "begin":
      print(begin(provider_arg(args), args[1] if len(args) > 1 else "", int(args[2]) if len(args) > 2 else 0))
    elif command == "recover":
      print(json.dumps(recover(provider_arg(args))))
    elif command == "register":
      provider = provider_arg(args)
      if len(args) < 3:
        raise AccountError("register <provider> <label> <pending-home>")
      print(json.dumps(register(provider, args[1], Path(args[2]))))
    elif command == "use":
      provider = provider_arg(args)
      previous, account, followed = use(provider, args[1] if len(args) > 1 else "next")
      print(json.dumps({"previous": previous, "active": account} | followed))
    elif command == "relogin":
      provider = provider_arg(args)
      if len(args) < 3:
        raise AccountError("relogin <provider> <account> <pending-home>")
      print(json.dumps(relogin(provider, args[1], Path(args[2]))))
    elif command == "remove":
      provider = provider_arg(args)
      if len(args) < 2:
        raise AccountError("remove <provider> <account>")
      print(json.dumps(remove(provider, args[1])))
    elif command == "rename":
      provider = provider_arg(args)
      if len(args) < 3:
        raise AccountError("rename <provider> <account> <label>")
      print(json.dumps(rename(provider, args[1], " ".join(args[2:]))))
    elif command == "threshold":
      provider = provider_arg(args)
      if len(args) < 2:
        raise AccountError("threshold <provider> <percent>")
      set_threshold(provider, args[1])
    elif command == "link":
      provider = provider_arg(args)
      link_shared(provider, Path(args[1]))
    elif command == "alert":
      for provider in ([provider_arg(args)] if args else list(PROVIDERS)):
        if registry_path(provider).exists():
          alert(provider)
    else:
      raise AccountError(f"Unknown command: {command}")
  except (AccountError, OSError) as error:
    print(error, file=sys.stderr)
    return 1
  return 0


if __name__ == "__main__":
  raise SystemExit(main(sys.argv[1:]))
