Skip to content

Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.

feat(rotate): standalone captcha cascade; CRS optional (#727)

Aurora Capital929375cae5f6
diff --git a/claude-ops/CHANGELOG.md b/claude-ops/CHANGELOG.md
index b72a68cb..7347e85f 100644
--- a/claude-ops/CHANGELOG.md
+++ b/claude-ops/CHANGELOG.md
@@ -10,6 +10,12 @@
### Added
- **ops-update companions:** step 9 runs `scripts/install-companions.sh` from `plugin-dependencies.json` — co-install/update all **required** companions (`desktop-act`, `gsd`, `gstack` skills-clone, `superpowers`, `feature-dev`). Flag: `--no-companions`.
+- **ops-accounts phase 0 surface:** `skills/ops-accounts` + `bin/ops-accounts` router (status/switch/refresh/reauth) over Claude rotate-magic, grok-rotate/oauth-reauth, and codex-rotate when present.
+
+- **Standalone captcha cascade (no CRS required):** port portable captcha stack into `scripts/account-rotation/` — `captcha-helper.mjs`, `visual-captcha-solver.mjs`, `bright-data-cascade.mjs`, orchestration `captcha-cascade.mjs`, thin `rotate-magic.mjs` entry. Plugin `rotate.mjs` soft-loads the cascade after magic-link verify. Contract: `CAPTCHA-CASCADE.md`. Gap report: `docs/ops/HOST-VS-PLUGIN-ROTATE-GAP.md`.
+- **CRS optional UX:** `/ops:rotate-setup` Step 4.4 detects CRS (PATH / health / `crs.enabled`) and asks install vs standalone rotate-magic (recommended for single/few accounts) vs skip. `/ops:rotate` documents standalone `reauth` and never treats missing CRS as failure. `--standalone` flag on setup.
+- **ops-accounts vision (phase 0):** multi-provider `/ops:accounts` is the north star (Claude/Codex/Grok adapters, refresh+reauth dispatcher). Claude captcha port + CRS-optional are enablers under that contract, not a late rename. `docs/ops/OPS-ACCOUNTS-VISION.md` — future rename ops-rotate → multi-provider ops-accounts; cherry-pick balancer ideas; no fork in this release.
+
- **desktop-act marketplace companion:** `desktop-act` is published in `ops-marketplace` next to `ops` (source `./desktop-act`). Declared as a co-install dependency in `plugin.json` + `plugin-dependencies.json`. `scripts/install-desktop-act-companion.sh` installs via `claude plugin install desktop-act@ops-marketplace` (idempotent). `/ops:setup` and `/ops:update` co-install by default (`desktop_act_co_install`). Launcher resolves `ops-marketplace/desktop-act` before cache clone; default bootstrap repo is Lifecycle-Innovations-Limited/desktop-act.
- **magic-link-autoloop reauth env (portable):** unattended re-auth child now inherits an env-templated headed seat + captcha cascade contract (`reauth-env.mjs`, `CAPTCHA-CASCADE.md`). Defaults: headed display from `CLAUDE_DESKTOP_DISPLAY` / `DESKTOP_ACT_DISPLAY`, visual + desktop-act + VNC layers on when present, 20m rotate timeout, no steal-lock, sticky `SKIP_TOKEN_SOLVERS=1` cleared. Dispatch mode `setup` (default) or `magic-link` via `$CRS_MAGIC_LINK_DISPATCH` / `crs.magicLinkDispatch`. Shell wrapper resolves plugin via `$CLAUDE_PLUGIN_ROOT` (no host hardcodes). Launchd template + `config.example.json` document the knobs.
- **installer (`claude-ops-installer`, v0.1.0):** cross-CLI `npx claude-ops-installer install` — auto-detects Claude Code, Codex, Gemini CLI, OpenClaw, Hermes, and OpenCode, mirrors upstream skills + binstubs into each agent's expected layout, ships with a central `~/.config/claude-ops-installer/config.yaml`, and supports `install` / `update` / `verify` / `doctor` / `uninstall` / `agents` subcommands. One source of truth (the upstream marketplace repo at the pinned ref); per-agent manifest at `~/.cache/claude-ops-installer/manifest.json` enables surgical uninstall. Public-repo clean: no PII, no hardcoded paths, no embedded credentials.
diff --git a/claude-ops/bin/ops-accounts b/claude-ops/bin/ops-accounts
new file mode 100755
index 00000000..32b38cdc
--- /dev/null
+++ b/claude-ops/bin/ops-accounts
@@ -0,0 +1,135 @@
+#!/usr/bin/env bash
+# ops-accounts — multi-provider account status / switch / refresh / reauth router.
+# Phase 0 thin shell: delegates to existing engines (Claude rotate, grok-*, codex).
+# No host hardcodes beyond $HOME; no secrets printed.
+set -euo pipefail
+
+cmd="${1:-status}"
+shift || true
+
+have() { command -v "$1" >/dev/null 2>&1; }
+
+print_claude() {
+ echo "=== Claude ==="
+ local rot="${CLAUDE_PLUGIN_ROOT:-}/scripts/account-rotation"
+ if [[ -z "${CLAUDE_PLUGIN_ROOT:-}" ]]; then
+ # best-effort cache path
+ local c
+ c="$(ls -d "$HOME/.claude/plugins/cache/ops-marketplace/ops"/*/ 2>/dev/null | sort -V | tail -1 || true)"
+ rot="${c}scripts/account-rotation"
+ fi
+ if [[ -f "$rot/rotate.mjs" ]]; then
+ node "$rot/rotate.mjs" --status 2>/dev/null | head -40 || echo "(rotate.mjs --status failed)"
+ else
+ echo "plugin rotate.mjs not found (set CLAUDE_PLUGIN_ROOT or install ops plugin)"
+ fi
+}
+
+print_grok() {
+ echo "=== Grok ==="
+ if have grok-rotate; then
+ grok-rotate status 2>/dev/null || true
+ else
+ echo "grok-rotate not on PATH"
+ fi
+ if have host-token-keepalive; then
+ host-token-keepalive --status --grok-only 2>/dev/null | tail -15 || true
+ fi
+}
+
+print_codex() {
+ echo "=== Codex / OpenAI ==="
+ if have codex-rotate; then
+ codex-rotate status 2>/dev/null | head -30 || echo "(codex-rotate status failed)"
+ else
+ echo "codex-rotate not on PATH (optional)"
+ fi
+}
+
+case "$cmd" in
+ status|"")
+ print_claude
+ echo
+ print_grok
+ echo
+ print_codex
+ ;;
+ switch)
+ provider="${1:-}"
+ target="${2:-}"
+ case "$provider" in
+ grok|xai)
+ if [[ -n "$target" ]]; then
+ # force state to previous index so switch lands on target if ordered — fallback simple switch
+ grok-rotate switch
+ else
+ grok-rotate switch
+ fi
+ grok-rotate status
+ ;;
+ claude)
+ echo "use: /ops:rotate rotate-now [--to email] or node rotate.mjs --rotate"
+ ;;
+ *)
+ echo "usage: ops-accounts switch grok|claude [email]"
+ exit 2
+ ;;
+ esac
+ ;;
+ refresh)
+ provider="${1:-all}"
+ case "$provider" in
+ grok)
+ host-token-keepalive --force --grok-only 2>/dev/null || grok-rotate refresh
+ ;;
+ claude)
+ host-token-keepalive --force --claude-only 2>/dev/null || true
+ ;;
+ all|"")
+ host-token-keepalive --force 2>/dev/null || true
+ ;;
+ *)
+ echo "usage: ops-accounts refresh [all|claude|grok]"
+ exit 2
+ ;;
+ esac
+ ;;
+ reauth)
+ provider="${1:-}"
+ email="${2:-}"
+ case "$provider" in
+ grok|xai)
+ [[ -n "$email" ]] || { echo "usage: ops-accounts reauth grok <email>"; exit 2; }
+ export DISPLAY="${DISPLAY:-:1}"
+ grok-oauth-reauth --email "$email"
+ ;;
+ claude)
+ [[ -n "$email" ]] || { echo "usage: ops-accounts reauth claude <email>"; exit 2; }
+ root="${CLAUDE_PLUGIN_ROOT:-}"
+ if [[ -z "$root" ]]; then
+ root="$(ls -d "$HOME/.claude/plugins/cache/ops-marketplace/ops"/*/ 2>/dev/null | sort -V | tail -1)"
+ fi
+ node "${root}/scripts/account-rotation/rotate-magic.mjs" --to "$email" --force
+ ;;
+ *)
+ echo "usage: ops-accounts reauth grok|claude <email>"
+ exit 2
+ ;;
+ esac
+ ;;
+ -h|--help|help)
+ cat <<H
+ops-accounts — multi-provider seat router (phase 0)
+
+ ops-accounts status
+ ops-accounts switch grok|claude
+ ops-accounts refresh [all|claude|grok]
+ ops-accounts reauth grok <email>
+ ops-accounts reauth claude <email>
+H
+ ;;
+ *)
+ echo "unknown command: $cmd (try help)"
+ exit 2
+ ;;
+esac
diff --git a/claude-ops/docs/ops/HOST-VS-PLUGIN-ROTATE-GAP.md b/claude-ops/docs/ops/HOST-VS-PLUGIN-ROTATE-GAP.md
new file mode 100644
index 00000000..c2572d11
--- /dev/null
+++ b/claude-ops/docs/ops/HOST-VS-PLUGIN-ROTATE-GAP.md
@@ -0,0 +1,149 @@
+# Host vs plugin rotate-magic gap
+
+Snapshot for making **plugin** `scripts/account-rotation/` standalone-capable
+without the box-local host tree `~/.claude/scripts/account-rotation/`.
+
+Public-repo clean: no host emails, IPs, or personal account lists.
+
+## Summary
+
+| Surface | Host (box-local fork) | Plugin (`claude-ops`) |
+|--------|------------------------|------------------------|
+| `rotate.mjs` | ~8981 lines | ~5275 lines (after this pass: soft captcha hooks) |
+| Captcha helper stack | Present (full) | **Ported this pass** |
+| CRS reconcilers / priority | Present (ops + host forks) | Present (portable subset) |
+| Magic-link autoloop + reauth env | Host thicker; plugin has portable `reauth-env.mjs` | Present (PR #723 era) |
+| Production systemd/user units | Still point at **host** path | Templates only (`%h` / `$CLAUDE_PLUGIN_ROOT`) |
+
+**CRS is optional.** Standalone rotate-magic (keychain + `rotate.mjs` /
+`rotate-magic.mjs`) is enough for one or a few accounts. CRS is multi-account
+load balancing / rate-limit spreading for a relay pool.
+
+## Line-count delta (key modules)
+
+| File | Host | Plugin (this branch) | Notes |
+|------|------|----------------------|--------|
+| `rotate.mjs` | 8981 | ~5275 | Host has magic-link-auto depth, OAuth harden, CRS sync, vault safety, captcha call sites throughout |
+| `captcha-helper.mjs` | 1023 | 1023 | Ported; residualAfterWait + multi-provider |
+| `visual-captcha-solver.mjs` | 496 | ~531 | Ported; portable desktop-act resolve + self-contained Gemini check |
+| `bright-data-cascade.mjs` | 296 | 296 | Ported; env-only zones |
+| `captcha-cascade.mjs` | (inlined in host rotate) | ~450 | Orchestration extract + `trySolveCaptchaWall` |
+| `rotate-captcha-soft.mjs` | — | new | Soft-load helpers for rotate |
+| `ensure-rotate-captcha-hooks.mjs` | — | new | Idempotent call-site patcher for public rotate.mjs |
+| `reauth-env.mjs` | missing on host | 135 | Plugin-first portable env |
+| `magic-link-autoloop.mjs` | ~548 | ~277 | Host fork thicker; plugin uses reauth-env |
+| `CAPTCHA-CASCADE.md` | host wording | plugin contract | Plugin is SSOT contract |
+
+Delta `rotate.mjs` ≈ **3.7k lines** still host-only (not a full port this pass).
+
+## Files present only on host (load-bearing or related)
+
+Minimal set operators still lean on from host for unattended reauth:
+
+1. Full inlined captcha call sites across magic-link-auto step loop (host `rotate.mjs`)
+2. `auth-repair.mjs` — 401 repair path used by host utilization
+3. `rotation-vault.mjs` / `rotation-safety.mjs` — vault + process lock hardening
+4. `secrets-bootstrap.mjs` — Doppler/env secret hydrate (host-coupled; not ported)
+5. `virtual-display.mjs` — headed X seat helpers
+6. `magic-link-cleanup.mjs` — gog trash after reauth
+7. `proxy-helper.mjs` / `oauth-proxy-fetch.mjs` — residential egress helpers
+8. `crs-operator.mjs`, `crs-token-refresher.mjs`, host-only CRS ops scripts
+9. One-off captcha debug drivers (`solve-*.mjs`, `click-turnstile*.mjs`, `.tmp-*`) — **not** for port
+10. `refresh-tokens.mjs` — unit `claude-token-refresh.service` still references host
+
+Also host-only (ops noise / personal debug): dozens of `click-*`, `trace-*`,
+`.tmp-*`, account-named captcha solvers — never port.
+
+## Files present only in plugin (or thicker in plugin)
+
+- `reauth-env.mjs`, `setup-account.mjs`, `bulk-setup-token.mjs`
+- `provider-env.mjs` / `provider-router.mjs` (multi-provider direction)
+- `vault-linux.mjs`, credit digest / kapture claim helpers
+- `crs-reconciler-state.mjs`, shell wrappers for reconcilers
+- Public `config.example.json`, launchd templates, install agents
+- `rotate-captcha-soft.mjs`, `ensure-rotate-captcha-hooks.mjs`, `rotate-magic.mjs` ensure-on-start
+
+## What host systemd still points at host path
+
+Do **not** repoint production units in this PR. Observed on a typical box
+(paths use `%h` or absolute host tree):
+
+| Unit | Exec / config points at |
+|------|-------------------------|
+| `claude-rotation-daemon.service` | `%h/.claude/scripts/account-rotation/daemon.mjs` |
+| `claude-account-rotation.service` | host `daemon.mjs` + host WorkingDirectory |
+| `claude-token-refresh.service` | host `refresh-tokens.mjs` |
+| `crs-magic-link-autoloop.service` | host `magic-link-autoloop.sh` |
+| `crs-priority.service` | host `crs-priority-daemon.sh` |
+| `crs-token-feed.service` | host `crs-token-feed.sh` |
+| `crs-bedrock-guard.service` | host `crs-bedrock-guard.mjs` |
+| `crs-egress-failover.service` | host `crs-egress-failover.sh` |
+| Drop-ins `20-crs-config.conf` | `CRS_CONFIG=%h/.claude/scripts/account-rotation/config.json` |
+
+Safe later end-state (not this PR): repoint to
+`$CLAUDE_PLUGIN_ROOT/scripts/account-rotation/…` after cascade parity, then
+archive the host fork.
+
+## Top missing pieces in plugin `rotate.mjs` (vs host)
+
+After this pass, cascade **modules** exist; full host `rotate.mjs` still has:
+
+1. Dense magic-link-auto step loop captcha hooks (OTP re-submit caps, stall PNG thrash guards)
+2. `completeOAuthWithGogMagicLink` / session-reuse paths
+3. `rotation-safety` process lock + deadline wrappers
+4. `auth-repair` on utilization 401
+5. `rotation-vault` dual-backend token read/write
+6. Residential Chrome / PAC / EFG proxy args for reauth browser
+7. `secrets-bootstrap` before solver use
+8. `virtual-display` ensure for headed seats
+9. CRS push helpers (`--sync-crs-all` style)
+10. Stricter OAuth callback / credential race handling
+
+## Minimal port set (standalone plugin rotate-magic)
+
+**Done this pass**
+
+- `captcha-helper.mjs`
+- `visual-captcha-solver.mjs`
+- `bright-data-cascade.mjs`
+- `captcha-cascade.mjs` (orchestration extract + `trySolveCaptchaWall` alias)
+- `rotate-captcha-soft.mjs` soft-load helpers
+- `ensure-rotate-captcha-hooks.mjs` — idempotent patcher that wires:
+ - every `runAuthFlow` step on claude.ai/com when a **blocking** wall is detected
+ - `/oauth/authorize` before Authorize
+ - after inline code/link verify path
+ - (keeps after-magic-link verify in `finishMagicLinkLogin`)
+- `rotate-magic.mjs` runs ensure before spawning `rotate.mjs`
+- Thin `rotate-magic.mjs` entry → `rotate.mjs --magic-link`
+- CRS optional UX in `/ops:rotate-setup` and `/ops:rotate` skills
+- Units: `__tests__/captcha-cascade.test.mjs`, `__tests__/ensure-rotate-captcha-hooks.test.mjs`
+
+**Apply hooks on a checkout**
+
+```bash
+node scripts/account-rotation/ensure-rotate-captcha-hooks.mjs
+# or via magic entry (auto):
+node scripts/account-rotation/rotate-magic.mjs --to [email protected]
+node scripts/account-rotation/__tests__/run-captcha-unit-tests.mjs
+```
+
+**Deferred (follow-up PRs)**
+
+- Full host magic-link-auto depth (OTP re-submit caps, stall PNG thrash guards, session-reuse)
+- Optional `secrets-bootstrap` that is env/credential-store only (no host Doppler hardcodes)
+- `rotation-safety` / vault harden merge
+- Repoint host systemd → plugin (operator change, not automatic)
+
+## How to run standalone (no CRS)
+
+```bash
+export CLAUDE_PLUGIN_ROOT=/path/to/claude-ops
+export CLAUDE_DESKTOP_DISPLAY=:1 # headed reauth seat
+export CLAUDE_ROT_HEADED=1
+# optional solver keys: TWOCAPTCHA_API_KEY, CAPSOLVER_API_KEY, …
+node "$CLAUDE_PLUGIN_ROOT/scripts/account-rotation/rotate-magic.mjs" --to [email protected]
+# or:
+node "$CLAUDE_PLUGIN_ROOT/scripts/account-rotation/rotate.mjs" --setup [email protected] --auto --skip-valid
+```
+
+See `scripts/account-rotation/CAPTCHA-CASCADE.md` and `reauth-env.mjs`.
diff --git a/claude-ops/docs/ops/OPS-ACCOUNTS-VISION.md b/claude-ops/docs/ops/OPS-ACCOUNTS-VISION.md
new file mode 100644
index 00000000..840858a0
--- /dev/null
+++ b/claude-ops/docs/ops/OPS-ACCOUNTS-VISION.md
@@ -0,0 +1,151 @@
+# ops-accounts vision
+
+**Status:** product SSOT for multi-provider account management (not a late add-on).
+
+**Date:** 2026-07-30 (revised same day: multi-provider rotator is **phase 0**)
+
+## Direction
+
+Ship **`/ops:accounts`** (alias `/ops:rotate` for one major version) as the
+**sole** place to register, refresh, reauth, and load-balance paid AI seats:
+
+- Claude Max / Pro
+- OpenAI / Codex
+- Grok (xAI SuperGrok)
+- Extensible adapters later
+
+Ideal box state: **public claude-ops plugin only** — no host forks, no
+provider-specific manual scripts left as the path of record.
+
+| Layer | Role | Required? |
+|-------|------|-----------|
+| **Provider adapter** | Capture + OAuth reauth + token store for one vendor | Yes (one per provider you use) |
+| **Refresh loop** | Proactive access-token refresh while refresh_token lives | Yes |
+| **Reauth dispatcher** | When RT dies: vendor-specific unattended reauth (Claude magic-link, Grok device-code+Google, Codex OAuth) | Yes |
+| **Active-seat / CLI switch** | Which account the interactive CLI uses now | Yes for TUI CLIs |
+| **Load balancer** | Multi-account concurrent pool, 429 cooldown, priority, token feed | Optional (rate-limit / weekly-cap spread) |
+
+CRS remains an **optional** external balancer for Claude (and any path that
+already speaks CRS). It is **not** the multi-provider OAuth engine and must
+not be required for single-seat users.
+
+## Why phase 0 (not phase 3)
+
+Without a multi-provider contract first:
+
+- Grok weekly-cap / dead RT is handled by host-only tools (`grok-rotate`,
+ `grok-oauth-reauth`, `grok-cli-auth-proxy`) outside the plugin skill surface.
+- Claude magic-link autoloop and Grok device reauth never share a dispatcher.
+- “Public plugin only” cutover cannot retire host trees that still own Grok.
+
+So the **north star is ops-accounts**. Claude captcha port and CRS-optional UX
+are **enablers** under that contract, not a separate product that might grow
+multi-provider later.
+
+## Provider matrix (target)
+
+| Provider | Capture / reauth | Token store | Refresh | Unattended reauth | LB path today |
+|----------|------------------|-------------|---------|-------------------|---------------|
+| Claude | magic-link + captcha cascade (`rotate.mjs`) | vault / keychain `Claude-Rotation-*` | `refresh-tokens` + keepalive | `magic-link-autoloop` | CRS optional |
+| Grok | xAI device-code + Google (dcli password/TOTP) | `~/.grok/auth-slots` (later: plugin-managed) | RT refresh in keepalive / proxy | `grok-oauth-reauth` (must become timer + skill) | `grok-cli-auth-proxy` round-robin |
+| Codex | OpenAI OAuth / API key | provider-scoped vault | codex OAuth bridge patterns | adapter TBD | optional |
+
+## Phased plan (revised)
+
+| Phase | Work | Exit criteria |
+|-------|------|----------------|
+| **0** | **ops-accounts contract** — skill surface, provider adapter interface, unified status/switch/refresh/reauth verbs, wire existing Claude + Grok + Codex tools behind it (thin orchestration first, no big rewrite) | `/ops:accounts status` shows all providers; `switch`/`refresh`/`reauth` work for Claude and Grok without knowing host script names |
+| **1** | Close host / plugin Claude rotate gap | Plugin cascade modules; gap doc; host units still host until proven |
+| **2** | CRS optional wire (Claude only) | Detect CRS; install vs standalone; never required for single seat |
+| **3** | Absorb host Grok/Codex scripts into plugin (portable, env-templated) | No load-bearing `~/.local/bin/grok-*` for happy path; timers under plugin installers |
+| **4** | Optional bundled balancer (rebranded cherry-pick, not CRS dump-fork) | Only if wire-optional CRS still hurts multi-Claude users |
+
+**This week’s PRs (#726 companions, #727 captcha/CRS-optional) are phase 1–2
+enablers.** They must not re-label phase 0 as “later design only.”
+
+## Gaps proven live (2026-07-30)
+
+- Active Grok CLI seat stuck on one account while alternates have dead RTs.
+- Claude magic-link autoloop is timer-driven; Grok reauth service is oneshot
+ with **no timer** — not parity.
+- rotate-magic does not speak xAI device-code; CRS does not reauth Grok.
+
+## Risks
+
+| Risk | Mitigation |
+|------|------------|
+| Big-bang rewrite of Claude rotate | Thin adapters over existing engines first |
+| CRS license if forking | Prefer wire-in; cherry-pick only after license review |
+| Host fork drift | Plugin SSOT; host units until phase 3 proof |
+| Secret sprawl | Provider-scoped vault names; never commit secrets |
+| Skill rename churn | Keep `/ops:rotate` alias ≥1 major version |
+
+## Non-goals (immediate)
+
+- Full CRS fork in one PR
+- Deleting host rotate before live parity
+- Hard-requiring CRS for single-account users
+
+## Related
+
+- `docs/ops/HOST-VS-PLUGIN-ROTATE-GAP.md`
+- `scripts/account-rotation/CAPTCHA-CASCADE.md`
+- Host (temporary): `grok-rotate`, `grok-oauth-reauth`, `grok-cli-auth-proxy`, `host-token-keepalive`
+- Skills today: `ops-rotate`, `ops-rotate-setup` → become aliases of `ops-accounts`
+
+## Phase 0 — multi-provider adapter contract (design only)
+
+Target skill surface: **`/ops:accounts`** (alias `/ops:rotate` for ≥1 major version).
+
+### Commands (stable)
+
+| Verb | Meaning |
+|------|---------|
+| `status` | List registered seats per provider + token health (no secrets) |
+| `list` | Same as status, table form |
+| `add` / `register` | Interactive capture into provider vault namespace |
+| `reauth` | Provider-specific reauth (Claude → rotate-magic; Grok → oauth reauth; Codex → session OAuth) |
+| `switch` | Make seat active for that provider’s CLI |
+| `lb` / `crs` | Optional load-balancer plane (Claude CRS today; others later) |
+
+### Adapter interface (plugin-local modules)
+
+Each provider ships a small adapter under `scripts/account-rotation/providers/<id>.mjs`
+(or future `scripts/accounts/providers/`). Minimum exports:
+
+```js
+// providers/<id>.mjs
+export const id = 'claude' | 'codex' | 'grok';
+export const displayName = 'Claude Max';
+/** @returns {Promise<{ok:boolean, seats:Array<{key,label,tokenValid,util?}>, note?:string}>} */
+export async function status(ctx) {}
+/** Capture or refresh vault entry. No secret logging. */
+export async function register(ctx, { emailOrLabel, mode }) {}
+/** Unattended reauth when token dead. May use browser/cascade. */
+export async function reauth(ctx, { key }) {}
+/** Optional: mark seat active for the CLI that reads this provider. */
+export async function switchTo(ctx, { key }) {}
+```
+
+`ctx` carries portable paths only: `pluginRoot`, `dataDir`, `log`, `env` — never host hardcodes.
+
+### Vault namespaces (credential-store service names)
+
+| Provider | Service pattern | Notes |
+|----------|-----------------|-------|
+| Claude | `Claude-Rotation-<key>` + live `Claude Code-credentials` | Existing |
+| Codex | `Codex-Rotation-<key>` (proposed) | Session OAuth; no public remaining API |
+| Grok | `Grok-Rotation-<key>` (proposed) | Absorb host oneshot into plugin adapter |
+
+### Dispatcher
+
+- Shared timer / autoloop dispatches `adapter.reauth` per `needsReauth` flags.
+- Claude path uses `rotate-magic.mjs` + captcha cascade (this PR).
+- CRS / balancer remains **optional** and Claude-scoped until a second provider needs LB.
+
+### Out of scope for phase 0 implementation
+
+- Renaming skills on disk
+- Forking CRS
+- Absorbing every host grok/codex script in one PR
+
diff --git a/claude-ops/scripts/account-rotation/CAPTCHA-CASCADE.md b/claude-ops/scripts/account-rotation/CAPTCHA-CASCADE.md
index 5ad20067..f8d2a025 100644
--- a/claude-ops/scripts/account-rotation/CAPTCHA-CASCADE.md
+++ b/claude-ops/scripts/account-rotation/CAPTCHA-CASCADE.md
@@ -1,20 +1,35 @@
# Captcha cascade (unattended re-auth)
-Contract for **unattended** re-auth owned by `magic-link-autoloop` → `rotate.mjs`.
-No interactive agent session is required. Agents must not spawn parallel
-`rotate.mjs` drivers against the same fleet (they thrash the global `.rotating`
-lock and the reauth browser profile).
+Contract for **unattended** re-auth owned by `magic-link-autoloop` →
+`rotate.mjs` / `rotate-magic.mjs`. No interactive agent session is required.
+Agents must not spawn parallel `rotate.mjs` drivers against the same fleet
+(they thrash the global `.rotating` lock and the reauth browser profile).
+
+**CRS is not required.** Captcha cascade runs in standalone rotate-magic.
## Ownership
| Component | Role |
|-----------|------|
-| `magic-link-autoloop` | Serial, one account per tick; opt-in |
-| `rotate.mjs` | Browser OAuth / magic-link / setup |
-| Captcha helpers (when present in the install) | Solver chain + visual + desktop-act |
+| `magic-link-autoloop` | Serial, one account per tick; opt-in (often CRS-flagged, but not required) |
+| `rotate.mjs` / `rotate-magic.mjs` | Browser OAuth / magic-link / setup |
+| `captcha-helper.mjs` | Token solvers + residential wait (`residualAfterWait`) |
+| `visual-captcha-solver.mjs` | Vision tiles + desktop-act + VNC layers |
+| `bright-data-cascade.mjs` | Optional proxy-aligned solver tiers |
+| `captcha-cascade.mjs` | Post-verify orchestration (`maybeSolvePostVerifyVisualChallenge`, `trySolveCaptchaWall`) |
+| `rotate-captcha-soft.mjs` | Soft-load helpers for rotate |
+| `ensure-rotate-captcha-hooks.mjs` | Idempotent wiring of `trySolveCaptchaWall` into rotate browser walls |
+
+If captcha modules fail to load, the env keys below are harmless no-ops.
+
+## Browser wall call sites (plugin rotate)
+
+`trySolveCaptchaWall(page, reason, log)` is the public soft hook. Wired at:
-If this install's `rotate.mjs` has no captcha helpers, the env keys below are
-harmless no-ops.
+1. Every `runAuthFlow` step when URL is claude.ai/com and a **blocking** wall is detected
+2. `/oauth/authorize` before Authorize clicks
+3. After magic-link / code verify (`finishMagicLinkLogin` + inline path)
+4. `rotate-magic.mjs` runs `ensureRotateCaptchaHooks()` before spawning rotate so checkouts stay patched
## Order (when captcha helpers are present)
@@ -63,6 +78,8 @@ export CLAUDE_ROT_HEADED=1
bash "$CLAUDE_PLUGIN_ROOT/scripts/account-rotation/magic-link-autoloop.sh"
# or one-shot:
node "$CLAUDE_PLUGIN_ROOT/scripts/account-rotation/magic-link-autoloop.mjs"
+# ensure hooks + magic:
+node "$CLAUDE_PLUGIN_ROOT/scripts/account-rotation/rotate-magic.mjs" --to [email protected]
```
## Anti-patterns
diff --git a/claude-ops/scripts/account-rotation/README.md b/claude-ops/scripts/account-rotation/README.md
index 536ae754..a09541ab 100644
--- a/claude-ops/scripts/account-rotation/README.md
+++ b/claude-ops/scripts/account-rotation/README.md
@@ -55,8 +55,27 @@ Each account entry:
| `capacityMultiplier` | no | Override per-account threshold (default 1.0 = standard Max 20x quota). |
| `crsAccountName` | no | CRS admin account name this vault entry maps to (for crs-token-feed / crs-priority). |
+## Standalone rotate-magic (no CRS)
+
+Most users only need **one account at a time** (or a few seats with the keychain
+rotator). That path does **not** require CRS:
+
+```bash
+node "$CLAUDE_PLUGIN_ROOT/scripts/account-rotation/rotate-magic.mjs" --to [email protected]
+# or multi-account OAuth capture:
+node "$CLAUDE_PLUGIN_ROOT/scripts/account-rotation/rotate.mjs" --setup --auto --skip-valid
+```
+
+Unattended captcha cascade (visual → desktop-act → VNC) lives in
+`captcha-helper.mjs`, `visual-captcha-solver.mjs`, `captcha-cascade.mjs`. See
+`CAPTCHA-CASCADE.md`.
+
## CRS pool (optional)
+CRS = multi-account **load balancing / rate-limit spreading** via a relay pool.
+Useful mainly when many accounts share one API endpoint and you hit 429s.
+Skip CRS for single/few-account keychain rotation.
+
If you run [claude-relay-service](https://github.com/anthropics/claude-relay-service) (CRS) alongside the rotator:
1. Add `crsAccountName` on each account (must match the account `name` in the CRS admin UI), or supply `crs.nameByVaultKey` in `config.json`.
@@ -71,6 +90,7 @@ If you run [claude-relay-service](https://github.com/anthropics/claude-relay-ser
Point Claude Code at `http://127.0.0.1:3005/api` (or your `CRS_TUNNEL_LOCAL_PORT`).
See `config.example.json` → `crs` block for all tunables (`policy`, `fileVaultPath`, `containerName`, thresholds).
+Configure via `/ops:rotate-setup` (detects CRS; never required).
## Keychain layout
@@ -86,6 +106,11 @@ Override the keychain account name via `CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT` if you
| File | Purpose |
| --------------------- | ------------------------------------------------------------------------- |
| `rotate.mjs` | Main rotation logic. CLI: `--status`, `--utilization`, `--to`, `--setup`. |
+| `rotate-magic.mjs` | Thin entry → `rotate.mjs --magic-link` (standalone reauth, no CRS). |
+| `captcha-cascade.mjs` | Post-verify captcha orchestration (token + visual + desktop-act + VNC). |
+| `captcha-helper.mjs` | Pluggable token captcha solvers + residential wait. |
+| `visual-captcha-solver.mjs` | Vision tile clicks, desktop-act, VNC layers. |
+| `bright-data-cascade.mjs` | Optional Bright Data proxy tiers for solver IP alignment. |
| `daemon.mjs` | launchd-managed monitor. Polls every 15s, rotates at 80% utilization. |
| `ai-brain.mjs` | Claude Haiku fallback for unexpected OAuth pages. |
| `force-rotate.sh` | Out-of-band rotation when Claude Code is unreachable. |
diff --git a/claude-ops/scripts/account-rotation/__tests__/captcha-cascade.test.mjs b/claude-ops/scripts/account-rotation/__tests__/captcha-cascade.test.mjs
new file mode 100644
index 00000000..f6f8aee2
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/__tests__/captcha-cascade.test.mjs
@@ -0,0 +1,58 @@
+/**
+ * captcha-cascade unit tests (no network, no real browser).
+ */
+import {
+ resolveCaptchaHandoffDir,
+ detectPostVerifyVisualChallenge,
+ captchaHardFailed,
+ tryClearCaptchaWall,
+ maybeSolvePageCaptcha,
+} from '../captcha-cascade.mjs';
+import { trySolveCaptchaWall, detectCaptchaWall, maybeClearCaptchaWall } from '../rotate-captcha-soft.mjs';
+
+function assert(cond, msg) {
+ if (!cond) throw new Error(msg || 'assert failed');
+}
+
+// handoff dir prefers env, then plugin data, never host-only path hardcode
+const d1 = resolveCaptchaHandoffDir({ CLAUDE_ROT_CAPTCHA_HANDOFF_DIR: '/tmp/captcha-handoff-test' });
+assert(d1 === '/tmp/captcha-handoff-test', 'explicit handoff dir');
+const d2 = resolveCaptchaHandoffDir({
+ CLAUDE_PLUGIN_DATA_DIR: '/tmp/plugin-data',
+ HOME: '/tmp/home',
+});
+assert(d2.includes('account-rotation'), 'plugin data handoff under account-rotation');
+assert(d2.startsWith('/tmp/plugin-data'), 'uses CLAUDE_PLUGIN_DATA_DIR');
+
+// empty page → no wall
+const empty = await detectPostVerifyVisualChallenge(null);
+assert(empty.blocking === false && empty.present === false, 'null page not blocking');
+
+// mock page: body text only
+const mockNoWall = {
+ evaluate: async () => 'Enter the verification code we sent',
+};
+const soft = await detectPostVerifyVisualChallenge(mockNoWall);
+assert(soft.blocking === false, 'otp prompt text alone is not a blocking wall');
+
+// mock page with pick/drag prompt
+const mockDrag = {
+ evaluate: async () => 'Please drag the icon to the place where it fits to continue',
+};
+const drag = await detectPostVerifyVisualChallenge(mockDrag);
+assert(drag.blocking === true, 'drag-fit is blocking');
+assert(drag.kind === 'drag-fit', 'kind drag-fit');
+
+// soft helpers
+const pageObj = {};
+assert(captchaHardFailed(pageObj) === false, 'fresh page not hard-failed');
+assert(captchaHardFailed(null) === false, 'null not hard-failed');
+assert((await trySolveCaptchaWall(null, 'unit', () => {})) === false, 'null trySolve');
+assert((await tryClearCaptchaWall(null, 'unit', () => {})) === false, 'null tryClear');
+assert((await maybeClearCaptchaWall(null, 'unit', () => {})) === false, 'null maybeClear alias');
+assert((await maybeSolvePageCaptcha(null, 'unit')) === false, 'null maybeSolvePage');
+
+const softDetect = await detectCaptchaWall(null);
+assert(softDetect.blocking === false, 'soft detect null');
+
+console.log('captcha-cascade.test.mjs: ok');
diff --git a/claude-ops/scripts/account-rotation/__tests__/ensure-rotate-captcha-hooks.test.mjs b/claude-ops/scripts/account-rotation/__tests__/ensure-rotate-captcha-hooks.test.mjs
new file mode 100644
index 00000000..6d1dbd0c
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/__tests__/ensure-rotate-captcha-hooks.test.mjs
@@ -0,0 +1,32 @@
+/**
+ * ensure-rotate-captcha-hooks unit tests (no browser).
+ */
+import { readFileSync, writeFileSync, mkdtempSync, mkdirSync, rmSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { pathToFileURL } from 'url';
+
+function assert(cond, msg) {
+ if (!cond) throw new Error(msg || 'assert failed');
+}
+
+// Live plugin rotate should either already have hooks or be patchable.
+const live = await import('../ensure-rotate-captcha-hooks.mjs');
+const status = live.rotateCaptchaHooksPresent();
+assert(typeof status === 'boolean', 'present returns boolean');
+
+// Dry-run ensure should not throw
+const dry = live.ensureRotateCaptchaHooks({ dryRun: true });
+assert(dry.ok === true, 'dry-run ok');
+assert(typeof dry.changed === 'boolean', 'changed boolean');
+
+// Apply for real (idempotent on this tree)
+const applied = live.ensureRotateCaptchaHooks({ dryRun: false });
+assert(applied.ok === true, 'apply ok');
+assert(live.rotateCaptchaHooksPresent() === true, 'hooks present after ensure');
+
+// Second apply is no-op
+const again = live.ensureRotateCaptchaHooks({ dryRun: false });
+assert(again.ok === true && again.changed === false, 'second ensure no-op');
+
+console.log('ensure-rotate-captcha-hooks.test.mjs: ok');
diff --git a/claude-ops/scripts/account-rotation/__tests__/run-captcha-unit-tests.mjs b/claude-ops/scripts/account-rotation/__tests__/run-captcha-unit-tests.mjs
new file mode 100644
index 00000000..a63d5c7d
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/__tests__/run-captcha-unit-tests.mjs
@@ -0,0 +1,32 @@
+/**
+ * Runs captcha unit suite and applies rotate captcha hooks once.
+ * Usage: node __tests__/run-captcha-unit-tests.mjs
+ */
+import { spawnSync } from 'child_process';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+import { ensureRotateCaptchaHooks } from '../ensure-rotate-captcha-hooks.mjs';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const root = join(__dirname, '..');
+
+const applied = ensureRotateCaptchaHooks();
+console.log('[run] ensure hooks:', JSON.stringify(applied));
+
+const tests = [
+ join(__dirname, 'captcha-cascade.test.mjs'),
+ join(__dirname, 'ensure-rotate-captcha-hooks.test.mjs'),
+ join(__dirname, 'reauth-env.test.mjs'),
+];
+
+let failed = 0;
+for (const t of tests) {
+ const r = spawnSync(process.execPath, [t], { stdio: 'inherit', cwd: root });
+ if (r.status !== 0) {
+ failed++;
+ console.error(`[run] FAIL ${t} status=${r.status}`);
+ } else {
+ console.error(`[run] ok ${t}`);
+ }
+}
+process.exit(failed ? 1 : 0);
diff --git a/claude-ops/scripts/account-rotation/captcha-cascade.mjs b/claude-ops/scripts/account-rotation/captcha-cascade.mjs
new file mode 100644
index 00000000..144a5d7a
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/captcha-cascade.mjs
@@ -0,0 +1,447 @@
+/**
+ * Captcha cascade orchestration for unattended re-auth (rotate-magic).
+ *
+ * Portable extract of host rotate.mjs helpers:
+ * detectPostVerifyVisualChallenge, maybeSolvePageCaptcha,
+ * maybeSolvePostVerifyVisualChallenge, captchaHardFailed, writeCaptchaVncHandoff
+ *
+ * Soft-depends on captcha-helper.mjs + visual-captcha-solver.mjs (same directory).
+ * Callers that lack solver keys still get autonomous visual → desktop-act → VNC.
+ *
+ * No host paths, no account emails. Handoff markers go under
+ * $CLAUDE_PLUGIN_DATA_DIR/account-rotation/screenshots (or XDG data / tmp).
+ *
+ * See CAPTCHA-CASCADE.md.
+ */
+import { mkdirSync, readFileSync, writeFileSync } from 'fs';
+import { join } from 'path';
+import { homedir, tmpdir } from 'os';
+import { solveInteractiveCaptchaVisually, runAutonomousCaptchaCascade } from './visual-captcha-solver.mjs';
+import { solveCaptchaOnPage, captchaSolverAvailable } from './captcha-helper.mjs';
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+const _postVerifyCaptchaAttempts = new WeakMap();
+const _vncHandoffWritten = new WeakSet();
+const _captchaHardFail = new WeakSet();
+
+/** Directory for CAPTCHA_VNC_HANDOFF marker + screenshots (portable). */
+export function resolveCaptchaHandoffDir(env = process.env) {
+ if (env.CLAUDE_ROT_CAPTCHA_HANDOFF_DIR) return env.CLAUDE_ROT_CAPTCHA_HANDOFF_DIR;
+ const data =
+ env.CLAUDE_PLUGIN_DATA_DIR || join(env.HOME || homedir(), '.claude', 'plugins', 'data', 'ops-ops-marketplace');
+ return join(data, 'account-rotation', 'screenshots');
+}
+
+/**
+ * @param {(m: string) => void} [log]
+ */
+export async function maybeSolvePageCaptcha(
+ page,
+ reason = '',
+ { timeoutMs = 180_000, attempt = 0, browserWaitMs, forceSolver, stalled, log = () => {} } = {},
+) {
+ if (!page) return false;
+ try {
+ const result = await solveCaptchaOnPage(page, (message) => log(`[captcha] ${message}`), {
+ timeoutMs,
+ attempt,
+ browserWaitMs,
+ forceSolver,
+ stalled,
+ });
+ if (result.present && !result.solved && !captchaSolverAvailable()) {
+ log(`[captcha] challenge present${reason ? ` (${reason})` : ''} but no solver key`);
+ }
+ if (result.present && !result.solved && captchaSolverAvailable()) {
+ log(`[captcha] present but unsolved${reason ? ` (${reason})` : ''} — visual/interactive wall may need cascade`);
+ }
+ if (result.solved) {
+ log(`[captcha] solved ${result.provider}${reason ? ` (${reason})` : ''}`);
+ await sleep(1500);
+ }
+ return result.solved === true;
+ } catch (e) {
+ log(`[captcha] solve attempt failed: ${String(e.message || e).slice(0, 100)}`);
+ return false;
+ }
+}
+
+/** Post-Verify Cloudflare/hCaptcha visual challenges (pick/drag/image-grid). */
+export async function detectPostVerifyVisualChallenge(page) {
+ if (!page) return { present: false, kind: null, text: '', blocking: false };
+ try {
+ const text = await page
+ .evaluate(() => {
+ const body = (document.body?.innerText || '').replace(/\s+/g, ' ').trim();
+ let extra = '';
+ try {
+ for (const f of document.querySelectorAll('iframe')) {
+ extra += ` ${f.getAttribute('title') || ''} ${f.getAttribute('aria-label') || ''}`;
+ }
+ } catch {
+ /* ignore */
+ }
+ return `${body} ${extra}`.slice(0, 2500);
+ })
+ .catch(() => '');
+ const t = String(text || '');
+ let kind = null;
+ if (/drag the icon to the place where it fits/i.test(t)) kind = 'drag-fit';
+ else if (/pick items that dispense when you squeeze/i.test(t)) kind = 'pick-squeeze';
+ else if (/click on items you would/i.test(t)) kind = 'click-items';
+ else if (/please drag the icon/i.test(t)) kind = 'drag-fit';
+ else if (/\b(select all|pick all|which of these|image challenge)\b/i.test(t) && /hcaptcha|challenge/i.test(t)) {
+ kind = 'image-grid';
+ }
+ const promptKinds = new Set(['drag-fit', 'pick-squeeze', 'click-items', 'image-grid']);
+ if (!kind) {
+ const widget = await page
+ .evaluate(() => {
+ const vw = window.innerWidth || 1280;
+ const vh = window.innerHeight || 900;
+ const hostOf = (src) => {
+ try {
+ return new URL(src, location.href).hostname.toLowerCase();
+ } catch {
+ return '';
+ }
+ };
+ const isHcHost = (h) => h === 'hcaptcha.com' || h.endsWith('.hcaptcha.com');
+ const isCfChallengeHost = (h) =>
+ h === 'challenges.cloudflare.com' || h.endsWith('.challenges.cloudflare.com');
+ const frames = Array.from(document.querySelectorAll('iframe')).map((f) => {
+ const r = f.getBoundingClientRect();
+ const visible =
+ r.width > 0 && r.height > 0 && r.bottom > 8 && r.right > 8 && r.top < vh - 8 && r.left < vw - 8;
+ const src = f.src || '';
+ const host = hostOf(src);
+ return {
+ src,
+ host,
+ w: r.width,
+ h: r.height,
+ x: r.x,
+ y: r.y,
+ title: f.title || '',
+ visible,
+ isHc: isHcHost(host),
+ isCf: isCfChallengeHost(host),
+ isChallenge: /(?:^|[?&#])frame=challenge(?:&|#|$)/i.test(src),
+ };
+ });
+ const largeHc = frames.find((f) => f.visible && f.isHc && f.isChallenge && f.w >= 350 && f.h >= 300);
+ const anyHcChallenge = frames.some((f) => f.visible && f.isHc && f.isChallenge && f.w > 0 && f.h > 0);
+ const anyHcOffscreen = frames.some((f) => !f.visible && f.isHc && f.isChallenge && f.w > 0 && f.h > 0);
+ const hasCf = frames.some((f) => f.visible && f.isCf && f.w >= 200 && f.h >= 50);
+ return {
+ largeHc: !!largeHc,
+ anyHcChallenge,
+ anyHcOffscreen,
+ hasCf,
+ dims: frames
+ .filter((f) => f.isHc || f.isCf || f.host.includes('cloudflare'))
+ .map(
+ (f) =>
+ `${Math.round(f.w)}x${Math.round(f.h)}@${Math.round(f.x)},${Math.round(f.y)}${f.visible ? '' : ':off'}`,
+ )
+ .slice(0, 4),
+ };
+ })
+ .catch(() => ({}));
+ if (widget?.largeHc) kind = 'hcaptcha-challenge-large';
+ else if (widget?.hasCf) kind = 'cf-challenge-frame';
+ else if (widget?.anyHcChallenge || widget?.anyHcOffscreen) {
+ return {
+ present: false,
+ kind: 'hcaptcha-challenge-preload',
+ text: t.slice(0, 200),
+ blocking: false,
+ dims: widget.dims || [],
+ };
+ }
+ }
+ const blocking =
+ !!kind && (promptKinds.has(kind) || kind === 'hcaptcha-challenge-large' || kind === 'cf-challenge-frame');
+ return { present: !!kind, kind, text: t.slice(0, 200), blocking };
+ } catch {
+ return { present: false, kind: null, text: '', blocking: false };
+ }
+}
+
+export function captchaHardFailed(page) {
+ return !!(page && _captchaHardFail.has(page));
+}
+
+/**
+ * Dashboard marker only — not a human task. Autoloop re-dispatches on next tick.
+ * @param {(m: string) => void} [log]
+ */
+export function writeCaptchaVncHandoff(page, visual, reason, log = () => {}) {
+ try {
+ if (page && _vncHandoffWritten.has(page)) {
+ try {
+ const marker = join(resolveCaptchaHandoffDir(), 'CAPTCHA_VNC_HANDOFF.json');
+ // Read-or-skip (no existsSync→read race): missing file throws ENOENT.
+ const prev = JSON.parse(readFileSync(marker, 'utf8'));
+ prev.ts = new Date().toISOString();
+ prev.reason = reason || visual?.kind || prev.reason || 'post-verify';
+ prev.kind = visual?.kind || prev.kind || null;
+ prev.url = page ? String(page.url()).slice(0, 200) : prev.url;
+ writeFileSync(marker, JSON.stringify(prev, null, 2));
+ } catch {
+ /* ignore missing / unreadable marker */
+ }
+ return Promise.resolve(null);
+ }
+ const handoffDir = resolveCaptchaHandoffDir();
+ mkdirSync(handoffDir, { recursive: true });
+ const shotPath = join(handoffDir, `vnc-handoff-captcha-${Date.now()}.png`);
+ const marker = join(handoffDir, 'CAPTCHA_VNC_HANDOFF.json');
+ const payload = {
+ ts: new Date().toISOString(),
+ reason: reason || visual?.kind || 'post-verify',
+ kind: visual?.kind || null,
+ url: page ? String(page.url()).slice(0, 200) : null,
+ screenshot: shotPath,
+ instruction:
+ 'AUTONOMOUS ONLY — not a human task. magic-link-autoloop will re-dispatch this seat on the next tick. Cascade already tried: residential wait → token solvers → visual AI → desktop-act act on CLAUDE_DESKTOP_DISPLAY → VNC computer-use. Marker is for ops dashboards / failStreak. Do not spawn interactive agent reauth drivers (they thrash the global .rotating lock).',
+ };
+ if (page) _vncHandoffWritten.add(page);
+ return page
+ .screenshot({ path: shotPath })
+ .catch(() => {})
+ .then(() => {
+ writeFileSync(marker, JSON.stringify(payload, null, 2));
+ log(`[captcha] VNC handoff marker written: ${marker} shot=${shotPath}`);
+ return marker;
+ });
+ } catch (e) {
+ log(`[captcha] VNC handoff marker failed: ${String(e.message || e).slice(0, 100)}`);
+ return Promise.resolve(null);
+ }
+}
+
+/**
+ * Full post-verify wall handling: residential/token solvers + autonomous cascade.
+ * Returns true only when the blocking wall is actually gone.
+ *
+ * @param {import('playwright').Page} page
+ * @param {string} [reason]
+ * @param {{ log?: (m: string) => void }} [opts]
+ */
+export async function maybeSolvePostVerifyVisualChallenge(page, reason = '', opts = {}) {
+ const log = opts.log || (() => {});
+ if (!page) return false;
+ const visual = await detectPostVerifyVisualChallenge(page);
+ if (visual.present || visual.blocking) {
+ log(`[captcha] post-verify visual challenge detected kind=${visual.kind}${reason ? ` (${reason})` : ''}`);
+ }
+
+ const maxAttempts = Number(
+ process.env.CLAUDE_ROT_CAPTCHA_MAX_ATTEMPTS || (process.env.CLAUDE_ROT_VISUAL_CAPTCHA === '0' ? 2 : 4),
+ );
+ const used = _postVerifyCaptchaAttempts.get(page) || 0;
+
+ const largeInteractive =
+ visual.blocking && (visual.kind === 'hcaptcha-challenge-large' || visual.kind === 'cf-challenge-frame');
+ if (largeInteractive && process.env.CLAUDE_ROT_LARGE_HC_TOKEN_FIRST !== '1') {
+ log(
+ `[captcha] large interactive wall kind=${visual.kind} — autonomous cascade first (set CLAUDE_ROT_LARGE_HC_TOKEN_FIRST=1 to force paid token path first)`,
+ );
+ _postVerifyCaptchaAttempts.set(page, used + 1);
+ try {
+ const escalated = await runAutonomousCaptchaCascade(page, (m) => log(m), {
+ includeVnc: true,
+ display: process.env.CLAUDE_DESKTOP_DISPLAY || process.env.DESKTOP_ACT_DISPLAY || process.env.DISPLAY || ':1',
+ desktopTimeout: Number(process.env.DESKTOP_ACT_CAPTCHA_TIMEOUT || 180),
+ visualRounds: Number(process.env.CLAUDE_ROT_VISUAL_CAPTCHA_ROUNDS || 8),
+ });
+ if (escalated.ok) {
+ await sleep(1500);
+ const still = await detectPostVerifyVisualChallenge(page);
+ if (!still.blocking || escalated.layer === 'visual-ai') {
+ log(
+ `[captcha] autonomous cascade cleared large wall layer=${escalated.layer}${reason ? ` (${reason})` : ''}`,
+ );
+ return true;
+ }
+ log(
+ `[captcha] cascade layer=${escalated.layer} reported ok but large wall still blocking — falling through to token path`,
+ );
+ }
+ } catch (e) {
+ log(`[captcha] large-wall cascade error: ${String(e.message || e).slice(0, 120)}`);
+ }
+ }
+
+ if (used >= maxAttempts) {
+ log(
+ `[captcha] attempt budget exhausted (${used}/${maxAttempts})${reason ? ` (${reason})` : ''} — escalating visual AI → desktop-act → VNC (no human session)`,
+ );
+ if (visual.blocking || visual.present) {
+ try {
+ const escalated = await runAutonomousCaptchaCascade(page, (m) => log(m), {
+ includeVnc: true,
+ display: process.env.CLAUDE_DESKTOP_DISPLAY || process.env.DESKTOP_ACT_DISPLAY || process.env.DISPLAY || ':1',
+ desktopTimeout: Number(process.env.DESKTOP_ACT_CAPTCHA_TIMEOUT || 180),
+ visualRounds: 6,
+ });
+ if (escalated.ok) {
+ await sleep(1500);
+ const still = await detectPostVerifyVisualChallenge(page);
+ if (!still.blocking || escalated.layer === 'visual-ai') {
+ log(`[captcha] autonomous cascade cleared wall layer=${escalated.layer} (budget)`);
+ return true;
+ }
+ log(`[captcha] cascade layer=${escalated.layer} reported ok but page still blocking — treating as uncleared`);
+ }
+ } catch (e) {
+ log(`[captcha] autonomous cascade error: ${String(e.message || e).slice(0, 120)}`);
+ }
+ await writeCaptchaVncHandoff(page, visual, `budget:${reason || visual.kind}`, log);
+ _captchaHardFail.add(page);
+ }
+ return false;
+ }
+
+ _postVerifyCaptchaAttempts.set(page, used + 1);
+ const injected = await maybeSolvePageCaptcha(page, reason || visual.kind || 'post-verify', {
+ timeoutMs: Number(process.env.CLAUDE_ROT_CAPTCHA_TIMEOUT_MS || 180_000),
+ attempt: used + 1,
+ browserWaitMs: Number(process.env.CRS_CAPTCHA_BROWSER_WAIT_MS || 12000),
+ log,
+ });
+
+ let wallCleared = false;
+ if (injected) {
+ for (let i = 0; i < 12; i++) {
+ await sleep(1000);
+ const still = await detectPostVerifyVisualChallenge(page);
+ if (still.blocking) continue;
+
+ const otpStuck = await page
+ .evaluate(() => {
+ const t = (document.body?.innerText || '').replace(/\s+/g, ' ');
+ const hasCode = !!document.querySelector(
+ '#code, [data-testid="code"], input[autocomplete="one-time-code"], input[name="code"]',
+ );
+ const err = /error verifying your code|invalid code|code expired/i.test(t);
+ const otpPrompt = /verification code|enter the code/i.test(t);
+ return { hasCode, err, otpPrompt, stillLogin: String(location.pathname || '').includes('/login') };
+ })
+ .catch(() => ({ hasCode: false, err: false, otpPrompt: false, stillLogin: false }));
+
+ const advanced = await page
+ .evaluate(() => {
+ const path = String(location.pathname || '');
+ const host = String(location.hostname || '');
+ if (path.includes('/oauth/authorize') || path === '/authorize' || path === '/authorize/') return true;
+ if (host === 'localhost' || host === '127.0.0.1') return true;
+ const t = (document.body?.innerText || '').replace(/\s+/g, ' ');
+ if (!path.includes('/login')) {
+ if (/\bAuthorize\b|\bAllow\b|\bApprove\b/i.test(t) && !/verification code/i.test(t)) return true;
+ if (/Select (?:which )?organization/i.test(t)) return true;
+ const hasCode = !!document.querySelector(
+ '#code, [data-testid="code"], input[autocomplete="one-time-code"], input[name="code"]',
+ );
+ if (!hasCode) return true;
+ }
+ return false;
+ })
+ .catch(() => false);
+
+ if (advanced) {
+ wallCleared = true;
+ break;
+ }
+
+ if (visual.blocking) {
+ continue;
+ }
+
+ if (!still.present || still.kind === 'hcaptcha-challenge-preload') {
+ if (otpStuck?.err) break;
+ wallCleared = true;
+ break;
+ }
+ if (!still.blocking && !still.present) {
+ wallCleared = true;
+ break;
+ }
+ }
+ if (!wallCleared) {
+ log(
+ `[captcha] token injected but visual wall still present${reason ? ` (${reason})` : ''} — autonomous cascade (visual → desktop-act → vnc)`,
+ );
+ try {
+ const escalated = await runAutonomousCaptchaCascade(page, (m) => log(m), {
+ includeVnc: used + 1 >= maxAttempts,
+ display: process.env.CLAUDE_DESKTOP_DISPLAY || process.env.DESKTOP_ACT_DISPLAY || process.env.DISPLAY || ':1',
+ desktopTimeout: Number(process.env.DESKTOP_ACT_CAPTCHA_TIMEOUT || 180),
+ visualRounds: 5,
+ });
+ if (escalated.ok) {
+ await sleep(1500);
+ const still = await detectPostVerifyVisualChallenge(page);
+ if (!still.blocking || escalated.layer === 'visual-ai') {
+ log(
+ `[captcha] autonomous cascade cleared wall layer=${escalated.layer} after inject-without-clear${reason ? ` (${reason})` : ''}`,
+ );
+ wallCleared = true;
+ }
+ }
+ } catch (e) {
+ log(`[captcha] autonomous cascade after inject failed: ${String(e.message || e).slice(0, 120)}`);
+ }
+ } else {
+ log(`[captcha] visual wall cleared after inject${reason ? ` (${reason})` : ''}`);
+ }
+ } else if (visual.blocking || visual.present) {
+ log(
+ `[captcha] no token inject${reason ? ` (${reason})` : ''} — autonomous cascade (visual → desktop-act${used + 1 >= maxAttempts ? ' → vnc' : ''})`,
+ );
+ try {
+ const escalated = await runAutonomousCaptchaCascade(page, (m) => log(m), {
+ includeVnc: used + 1 >= maxAttempts,
+ display: process.env.CLAUDE_DESKTOP_DISPLAY || process.env.DESKTOP_ACT_DISPLAY || process.env.DISPLAY || ':1',
+ desktopTimeout: Number(process.env.DESKTOP_ACT_CAPTCHA_TIMEOUT || 180),
+ visualRounds: 5,
+ });
+ if (escalated.ok) {
+ await sleep(1500);
+ const still = await detectPostVerifyVisualChallenge(page);
+ if (!still.blocking || escalated.layer === 'visual-ai') {
+ log(`[captcha] autonomous cascade cleared wall layer=${escalated.layer} (no-inject path)`);
+ wallCleared = true;
+ }
+ }
+ } catch (e) {
+ log(`[captcha] autonomous cascade (no-inject) error: ${String(e.message || e).slice(0, 120)}`);
+ }
+ }
+
+ if (!wallCleared && visual.blocking) {
+ const after = _postVerifyCaptchaAttempts.get(page) || 0;
+ if (after >= maxAttempts) {
+ await writeCaptchaVncHandoff(page, visual, reason || visual.kind, log);
+ _captchaHardFail.add(page);
+ }
+ }
+ return wallCleared;
+}
+
+/**
+ * Soft-load cascade API for rotate.mjs (static re-export convenience).
+ */
+export { solveCaptchaOnPage, captchaSolverAvailable, solveInteractiveCaptchaVisually, runAutonomousCaptchaCascade };
+
+// Also re-export residual wait concept for callers that only import this module
+export async function tryClearCaptchaWall(page, reason = '', log = () => {}) {
+ return maybeSolvePostVerifyVisualChallenge(page, reason, { log });
+}
+
+/** Alias used by rotate soft-hooks and host-port notes (same as tryClearCaptchaWall). */
+export async function trySolveCaptchaWall(page, reason = '', log = () => {}) {
+ return maybeSolvePostVerifyVisualChallenge(page, reason, { log });
+}
diff --git a/claude-ops/scripts/account-rotation/captcha-helper.mjs b/claude-ops/scripts/account-rotation/captcha-helper.mjs
index 3c7dd187..d1cc8d63 100644
--- a/claude-ops/scripts/account-rotation/captcha-helper.mjs
+++ b/claude-ops/scripts/account-rotation/captcha-helper.mjs
@@ -15,9 +15,9 @@
// Solvers remain FALLBACK only (CRS_CAPTCHA_SOLVER_MODE=fallback): residential
// browser wait first (residualAfterWait), then this provider chain.
//
-// Secrets hydrated by secrets-bootstrap.mjs from Doppler claude-ops/prd.
+// Secrets hydrated by secrets-bootstrap.mjs from env / optional secrets bootstrap.
// Optional TWOCAPTCHA_PROXY_* makes 2captcha/rucaptcha solve from a fixed IP.
-// AUR-1978: headed Chrome CDP :9222 is direct AWS egress — proxied tokens are
+// headed Chrome CDP :9222 is direct AWS egress — proxied tokens are
// IP-mismatched by default. Use CLAUDE_ROT_CAPTCHA_FORCE_PROXY=1 to force proxy.
//
// Never throws. Never prints API keys or tokens. Returns structured results.
@@ -164,7 +164,7 @@ export async function captchaSolverAllowed(ctx = {}) {
}
function proxyParams() {
- // AUR-1978 + 2026-07-30: solvers are fallback-only. When used, prefer EFG SOCKS
+ // + 2026-07-30: solvers are fallback-only. When used, prefer EFG SOCKS
// so token IP matches residential PAC browser (not third-party US residential).
const preferEfg =
process.env.CLAUDE_ROT_CAPTCHA_PREFER_EFG_SOCKS === '1' || process.env.CRS_OAUTH_EGRESS === 'efg-socks-reauth-only';
@@ -300,18 +300,26 @@ export async function detectCaptcha(page) {
const frames = Array.from(document.querySelectorAll('iframe'));
let invisibleHc = false;
let hcDomain = null;
+ const hostOf = (src) => {
+ try {
+ return new URL(src, location.href).hostname.toLowerCase();
+ } catch {
+ return '';
+ }
+ };
+ const isHcHost = (h) => h === 'hcaptcha.com' || h.endsWith('.hcaptcha.com');
+ const isCfChallengeHost = (h) => h === 'challenges.cloudflare.com' || h.endsWith('.challenges.cloudflare.com');
for (const f of frames) {
const src = f.getAttribute('src') || '';
- if (src.includes('challenges.cloudflare.com')) {
+ const host = hostOf(src);
+ if (isCfChallengeHost(host)) {
const m = src.match(/[?&](?:sitekey|k)=([^&]+)/);
if (m) return { provider: 'turnstile', sitekey: decodeURIComponent(m[1]), challengePage: true };
const pathMatch = src.match(/(0x[0-9A-Za-z_-]{20,})/);
if (pathMatch) return { provider: 'turnstile', sitekey: pathMatch[1], challengePage: true };
}
- if (src.includes('hcaptcha.com')) {
- try {
- hcDomain = new URL(src).hostname;
- } catch {}
+ if (isHcHost(host)) {
+ hcDomain = host || null;
if (/frame=checkbox-invisible/i.test(src)) invisibleHc = true;
const m = src.match(/[?&](?:sitekey|k)=([^&]+)/);
if (m) {
@@ -327,7 +335,10 @@ export async function detectCaptcha(page) {
const html = document.documentElement?.innerHTML || '';
const skHtml = html.match(/sitekey["'\s:=]+([a-f0-9-]{20,})/i);
if (skHtml) {
- const hasHcFrame = frames.some((f) => /hcaptcha\.com/i.test(f.getAttribute('src') || ''));
+ const hasHcFrame = frames.some((f) => {
+ const h = hostOf(f.getAttribute('src') || '');
+ return isHcHost(h);
+ });
if (hasHcFrame || /hcaptcha/i.test(html)) {
const rq = html.match(/rqdata["'\s:=]+([^"'\s&]{16,})/);
return {
@@ -931,7 +942,7 @@ export async function solveCaptchaOnPage(page, log = () => {}, opts = {}) {
return { solved: false, provider: challenge.provider, present: true };
}
if (challenge.provider === 'hcaptcha') {
- // AUR-2067: do NOT force invisible=true for every hCaptcha. Anthropic's
+ // do NOT force invisible=true for every hCaptcha. Anthropic's
// post-verify pick/drag wall is a large interactive challenge; submitting
// it as invisible yields a token that injects but never clears the wall.
// Default invisible only when detectCaptcha saw checkbox-invisible / size=invisible
@@ -942,7 +953,14 @@ export async function solveCaptchaOnPage(page, log = () => {}, opts = {}) {
const frames = Array.from(document.querySelectorAll('iframe'));
for (const f of frames) {
const src = f.getAttribute('src') || '';
- if (!/hcaptcha\.com/i.test(src) || !/frame=challenge/i.test(src)) continue;
+ let host = '';
+ try {
+ host = new URL(src, location.href).hostname.toLowerCase();
+ } catch {
+ continue;
+ }
+ const isHc = host === 'hcaptcha.com' || host.endsWith('.hcaptcha.com');
+ if (!isHc || !/(?:^|[?&#])frame=challenge(?:&|#|$)/i.test(src)) continue;
const r = f.getBoundingClientRect();
const style = window.getComputedStyle(f);
const visible =
diff --git a/claude-ops/scripts/account-rotation/ensure-rotate-captcha-hooks.mjs b/claude-ops/scripts/account-rotation/ensure-rotate-captcha-hooks.mjs
new file mode 100644
index 00000000..4a531cde
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/ensure-rotate-captcha-hooks.mjs
@@ -0,0 +1,199 @@
+/**
+ * Ensures plugin rotate.mjs has trySolveCaptchaWall call sites at browser walls.
+ * Idempotent. Safe to run from rotate-magic entry or tests.
+ *
+ * Mutates sibling rotate.mjs once when markers are missing.
+ */
+import { readFileSync, writeFileSync, existsSync } from 'fs';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const ROTATE = join(__dirname, 'rotate.mjs');
+
+const MARKER = 'auth-step-${step}'; // template marker after patch
+const MARKER_PLAIN = 'auth-step-'; // simpler detect
+
+export function rotateCaptchaHooksPresent(src = null) {
+ const text = src ?? (existsSync(ROTATE) ? readFileSync(ROTATE, 'utf8') : '');
+ return (
+ text.includes("from './rotate-captcha-soft.mjs'") ||
+ (text.includes('trySolveCaptchaWall') && text.includes('oauth-authorize') && text.includes(MARKER_PLAIN))
+ );
+}
+
+export function ensureRotateCaptchaHooks({ dryRun = false } = {}) {
+ if (!existsSync(ROTATE)) {
+ return { ok: false, reason: 'rotate-missing' };
+ }
+ let text = readFileSync(ROTATE, 'utf8');
+ if (rotateCaptchaHooksPresent(text)) {
+ return { ok: true, changed: false, reason: 'already-present' };
+ }
+
+ // 1) Replace inline soft-load helpers with import from rotate-captcha-soft.mjs
+ const helperRe =
+ /\/\/ Optional captcha cascade[\s\S]*?async function captchaHardFailed\(page\) \{[\s\S]*?\n\}\n\nconst __dirname/;
+ if (helperRe.test(text)) {
+ text = text.replace(
+ helperRe,
+ `// Soft captcha hooks — trySolveCaptchaWall on browser walls (CAPTCHA-CASCADE.md).
+// Helpers live in rotate-captcha-soft.mjs so thin checkouts can omit cascade modules.
+import {
+ trySolveCaptchaWall,
+ maybeClearCaptchaWall,
+ detectCaptchaWall,
+ captchaHardFailed,
+} from './rotate-captcha-soft.mjs';
+
+const __dirname`,
+ );
+ } else if (!text.includes("from './rotate-captcha-soft.mjs'")) {
+ // Fallback: inject import after bg-respawn import
+ const importAnchor = `import { respawnBgSessions } from './bg-respawn.mjs';\n`;
+ if (text.includes(importAnchor)) {
+ text = text.replace(
+ importAnchor,
+ importAnchor +
+ `import {\n trySolveCaptchaWall,\n maybeClearCaptchaWall,\n detectCaptchaWall,\n captchaHardFailed,\n} from './rotate-captcha-soft.mjs';\n`,
+ );
+ }
+ // Strip old helper block if still present (best-effort)
+ text = text.replace(
+ /let _captchaCascade = null;\nasync function loadCaptchaCascade\(\) \{[\s\S]*?async function captchaHardFailed\(page\) \{[\s\S]*?\n\}\n\n/,
+ '',
+ );
+ }
+
+ // 2) Step-loop wall handling
+ if (!text.includes(MARKER_PLAIN + '${step}') && !text.includes('auth-step-')) {
+ const stepNeedle = ` for (let step = 0; step < 20; step++) {
+ await sleep(2500);
+ const url = await driver.currentUrl().catch(() => '');
+ log(\`Step \${step} [\${driver.name}]: \${url.substring(0, 100)}\`);
+
+ // Claude sometimes renders the email login form while preserving the
+`;
+ const stepInsert = ` for (let step = 0; step < 20; step++) {
+ await sleep(2500);
+ const url = await driver.currentUrl().catch(() => '');
+ log(\`Step \${step} [\${driver.name}]: \${url.substring(0, 100)}\`);
+
+ // Browser walls (post-Verify pick/drag hCaptcha / CF): clear before OTP re-submit
+ // or AI-brain thrash. Soft no-op when cascade modules missing.
+ if (driver._page && /claude\\.(ai|com)/i.test(url || '')) {
+ const visualWall = await detectCaptchaWall(driver._page);
+ if (visualWall.blocking) {
+ const cleared = await trySolveCaptchaWall(
+ driver._page,
+ \`auth-step-\${step}:\${visualWall.kind || 'wall'}\`,
+ log,
+ );
+ if (await captchaHardFailed(driver._page)) {
+ log(
+ \`[captcha] aborting: budget exhausted with blocking wall kind=\${visualWall.kind} — see CAPTCHA_VNC_HANDOFF (autoloop retries)\`,
+ );
+ return false;
+ }
+ if (cleared) {
+ log(\`[captcha] step \${step}: wall cleared kind=\${visualWall.kind}\`);
+ if (driver._authUrl) {
+ try {
+ await driver.goto(driver._authUrl);
+ } catch {}
+ await sleep(2000);
+ }
+ stallCount = 0;
+ continue;
+ }
+ } else if (visualWall.kind === 'hcaptcha-challenge-preload') {
+ log('[captcha] preload challenge frame noted (non-blocking)');
+ }
+ }
+
+ // Claude sometimes renders the email login form while preserving the
+`;
+ if (text.includes(stepNeedle)) {
+ text = text.replace(stepNeedle, stepInsert);
+ }
+ }
+
+ // 3) Authorize path
+ if (!text.includes("trySolveCaptchaWall(driver._page, 'oauth-authorize'")) {
+ const authNeedle = ` if (oauthPath.includes('/oauth/authorize') || (oauthPath.endsWith('/authorize') && url.includes('claude'))) {
+ // Magic-link route: we authenticated via a single-use link delivered to
+`;
+ const authInsert = ` if (oauthPath.includes('/oauth/authorize') || (oauthPath.endsWith('/authorize') && url.includes('claude'))) {
+ // Clear captcha wall on authorize (can reappear after session settle).
+ if (driver._page) {
+ await trySolveCaptchaWall(driver._page, 'oauth-authorize', log);
+ if (await captchaHardFailed(driver._page)) {
+ log('[captcha] aborting on /oauth/authorize — budget exhausted');
+ return false;
+ }
+ }
+ // Magic-link route: we authenticated via a single-use link delivered to
+`;
+ if (text.includes(authNeedle)) {
+ text = text.replace(authNeedle, authInsert);
+ }
+ }
+
+ // 4) Inline magic-link verify path
+ if (!text.includes('after-inline-code-verify')) {
+ const inlineNeedle = ` await sleep(4000);
+ // After magic link login, session is now valid — re-navigate to authUrl
+ // so the OAuth flow can complete (org chooser → authorize → callback)
+ if (driver._authUrl) {
+ // For multi-org accounts (same email, multiple workspaces like
+ // user-personal vs user-team), force an explicit org
+ // pick BEFORE hitting /oauth/authorize. Otherwise claude.ai uses
+ // the "last active" org silently, and both sibling vaults end up
+ // holding the same org's token.
+ const isMultiOrg =
+ account.label && account.orgName && account.orgName.toLowerCase() !== account.email.toLowerCase();
+`;
+ const inlineInsert = ` await sleep(4000);
+ // Post-verify captcha wall after inline code/link path (mirrors finishMagicLinkLogin)
+ if (driver._page) {
+ await trySolveCaptchaWall(driver._page, 'after-inline-code-verify', log);
+ if (await captchaHardFailed(driver._page)) {
+ log(
+ '[magic-link] aborting: captcha budget exhausted after inline verify — see CAPTCHA_VNC_HANDOFF',
+ );
+ return false;
+ }
+ }
+ // After magic link login, session is now valid — re-navigate to authUrl
+ // so the OAuth flow can complete (org chooser → authorize → callback)
+ if (driver._authUrl) {
+ // For multi-org accounts (same email, multiple workspaces like
+ // user-personal vs user-team), force an explicit org
+ // pick BEFORE hitting /oauth/authorize. Otherwise claude.ai uses
+ // the "last active" org silently, and both sibling vaults end up
+ // holding the same org's token.
+ const isMultiOrg =
+ account.label && account.orgName && account.orgName.toLowerCase() !== account.email.toLowerCase();
+`;
+ if (text.includes(inlineNeedle)) {
+ text = text.replace(inlineNeedle, inlineInsert);
+ }
+ }
+
+ // Normalize remaining maybeClearCaptchaWall calls
+ text = text.replaceAll('await maybeClearCaptchaWall(', 'await trySolveCaptchaWall(');
+
+ if (dryRun) {
+ return { ok: true, changed: true, dryRun: true, presentAfter: rotateCaptchaHooksPresent(text) };
+ }
+ writeFileSync(ROTATE, text);
+ return { ok: true, changed: true, presentAfter: rotateCaptchaHooksPresent(text) };
+}
+
+// CLI
+const isMain = process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1];
+if (isMain) {
+ const r = ensureRotateCaptchaHooks({ dryRun: process.argv.includes('--dry-run') });
+ console.log(JSON.stringify(r, null, 2));
+ process.exit(r.ok && r.presentAfter !== false ? 0 : 1);
+}
diff --git a/claude-ops/scripts/account-rotation/rotate-captcha-soft.mjs b/claude-ops/scripts/account-rotation/rotate-captcha-soft.mjs
new file mode 100644
index 00000000..c9f7fe2a
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/rotate-captcha-soft.mjs
@@ -0,0 +1,74 @@
+/**
+ * Soft captcha hooks for public rotate.mjs.
+ *
+ * Prefer importing these helpers rather than inlining cascade imports, so
+ * rotate.mjs stays thin when captcha modules are missing (dev checkouts).
+ *
+ * import { trySolveCaptchaWall, detectCaptchaWall, captchaHardFailed } from './rotate-captcha-soft.mjs';
+ * await trySolveCaptchaWall(page, 'auth-step', log);
+ */
+let _captchaCascade = null;
+
+export async function loadCaptchaCascade() {
+ if (_captchaCascade !== null) return _captchaCascade;
+ try {
+ _captchaCascade = await import('./captcha-cascade.mjs');
+ } catch (e) {
+ _captchaCascade = false;
+ try {
+ console.error(`[captcha] cascade modules unavailable: ${String(e.message || e).slice(0, 120)}`);
+ } catch {
+ /* ignore */
+ }
+ }
+ return _captchaCascade;
+}
+
+/**
+ * Clear blocking post-verify / authorize walls when cascade modules exist.
+ * @param {import('playwright').Page|null} page
+ * @param {string} [reason]
+ * @param {(m:string)=>void} [log]
+ * @returns {Promise<boolean>}
+ */
+export async function trySolveCaptchaWall(page, reason = '', log = () => {}) {
+ const mod = await loadCaptchaCascade();
+ if (!mod || !page) return false;
+ try {
+ if (typeof mod.trySolveCaptchaWall === 'function') {
+ return await mod.trySolveCaptchaWall(page, reason, log);
+ }
+ if (typeof mod.tryClearCaptchaWall === 'function') {
+ return await mod.tryClearCaptchaWall(page, reason, log);
+ }
+ return await mod.maybeSolvePostVerifyVisualChallenge(page, reason, { log });
+ } catch (e) {
+ log(`[captcha] cascade error: ${String(e.message || e).slice(0, 120)}`);
+ return false;
+ }
+}
+
+/** @deprecated use trySolveCaptchaWall */
+export const maybeClearCaptchaWall = trySolveCaptchaWall;
+
+export async function detectCaptchaWall(page) {
+ const mod = await loadCaptchaCascade();
+ if (!mod || !page || typeof mod.detectPostVerifyVisualChallenge !== 'function') {
+ return { present: false, kind: null, text: '', blocking: false };
+ }
+ try {
+ return await mod.detectPostVerifyVisualChallenge(page);
+ } catch {
+ return { present: false, kind: null, text: '', blocking: false };
+ }
+}
+
+export async function captchaHardFailed(page) {
+ const mod = await loadCaptchaCascade();
+ if (!mod || !page) return false;
+ try {
+ return mod.captchaHardFailed(page);
+ } catch {
+ return false;
+ }
+}
diff --git a/claude-ops/scripts/account-rotation/rotate-magic.mjs b/claude-ops/scripts/account-rotation/rotate-magic.mjs
new file mode 100755
index 00000000..60a4fd84
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/rotate-magic.mjs
@@ -0,0 +1,57 @@
+#!/usr/bin/env node
+/**
+ * rotate-magic — thin entry for unattended magic-link re-auth.
+ *
+ * SSOT implementation: rotate.mjs --magic-link (plus setup --auto for multi-account).
+ * Ensures captcha wall hooks exist in rotate.mjs, then loads captcha cascade modules
+ * when present (captcha-cascade.mjs / rotate-captcha-soft.mjs).
+ * Does NOT require CRS. Optional CRS reconcilers call this via magic-link-autoloop.
+ *
+ * Usage:
+ * node rotate-magic.mjs --to <email>
+ * node rotate-magic.mjs --to <email> --force
+ * node rotate-magic.mjs --setup --only=<email> --auto --skip-valid
+ *
+ * Env: see CAPTCHA-CASCADE.md and reauth-env.mjs (CLAUDE_DESKTOP_DISPLAY, headed, cascade flags).
+ */
+import { spawn } from 'child_process';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+import { ensureRotateCaptchaHooks } from './ensure-rotate-captcha-hooks.mjs';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const rotate = join(__dirname, 'rotate.mjs');
+const argv = process.argv.slice(2);
+
+// Ensure trySolveCaptchaWall call sites exist in public rotate.mjs (idempotent).
+try {
+ const r = ensureRotateCaptchaHooks();
+ if (r.changed) {
+ console.error(`[rotate-magic] applied captcha wall hooks to rotate.mjs (${r.reason || 'patched'})`);
+ }
+} catch (e) {
+ console.error(`[rotate-magic] captcha hook ensure failed: ${String(e.message || e).slice(0, 120)}`);
+}
+
+// Default to magic-link mode unless caller already chose --setup / --status / etc.
+const hasMode = argv.some(
+ (a) =>
+ a === '--magic-link' ||
+ a === '--setup' ||
+ a === '--status' ||
+ a === '--utilization' ||
+ a === '--capture' ||
+ a === '--audit-billing' ||
+ a.startsWith('--setup'),
+);
+const finalArgv = hasMode ? argv : ['--magic-link', ...argv];
+
+const child = spawn(process.execPath, [rotate, ...finalArgv], {
+ stdio: 'inherit',
+ env: process.env,
+ cwd: process.cwd(),
+});
+child.on('exit', (code, signal) => {
+ if (signal) process.kill(process.pid, signal);
+ process.exit(code ?? 1);
+});
diff --git a/claude-ops/scripts/account-rotation/rotate.mjs b/claude-ops/scripts/account-rotation/rotate.mjs
index f923b6ea..1c1d3f71 100644
--- a/claude-ops/scripts/account-rotation/rotate.mjs
+++ b/claude-ops/scripts/account-rotation/rotate.mjs
@@ -55,6 +55,15 @@ import { destinationUtilHardBlock } from './rotation-policy.mjs';
import { applyAccountLeases, writeLease } from './account-leases.mjs';
import { respawnBgSessions } from './bg-respawn.mjs';
+// Soft captcha hooks — trySolveCaptchaWall on browser walls (CAPTCHA-CASCADE.md).
+// Helpers live in rotate-captcha-soft.mjs so thin checkouts can omit cascade modules.
+import {
+ trySolveCaptchaWall,
+ maybeClearCaptchaWall,
+ detectCaptchaWall,
+ captchaHardFailed,
+} from './rotate-captcha-soft.mjs';
+
const __dirname = dirname(fileURLToPath(import.meta.url));
// Account config lives in the gitignored user data dir (written by
// setup-account.mjs, Rule 0: no real account data in the committed repo).
@@ -2555,6 +2564,16 @@ async function runAuthFlow(driver, account) {
await driver.goto(magicLink);
}
await sleep(4000);
+ // Post-verify captcha wall (pick/drag hCaptcha / CF) — autonomous cascade when modules present
+ if (driver._page) {
+ await trySolveCaptchaWall(driver._page, 'after-initial-code-verify', log);
+ if (await captchaHardFailed(driver._page)) {
+ log(
+ '[magic-link] aborting: captcha budget exhausted with blocking wall — see CAPTCHA_VNC_HANDOFF marker (autoloop will retry)',
+ );
+ return false;
+ }
+ }
// After magic link login, session is now valid — re-navigate to authUrl
// so the OAuth flow can complete (org chooser → authorize → callback)
if (driver._authUrl) {
@@ -2642,6 +2661,34 @@ async function runAuthFlow(driver, account) {
const url = await driver.currentUrl().catch(() => '');
log(`Step ${step} [${driver.name}]: ${url.substring(0, 100)}`);
+ // Browser walls (post-Verify pick/drag hCaptcha / CF): clear before OTP re-submit
+ // or AI-brain thrash. Soft no-op when cascade modules missing.
+ if (driver._page && /claude\.(ai|com)/i.test(url || '')) {
+ const visualWall = await detectCaptchaWall(driver._page);
+ if (visualWall.blocking) {
+ const cleared = await trySolveCaptchaWall(driver._page, `auth-step-${step}:${visualWall.kind || 'wall'}`, log);
+ if (await captchaHardFailed(driver._page)) {
+ log(
+ `[captcha] aborting: budget exhausted with blocking wall kind=${visualWall.kind} — see CAPTCHA_VNC_HANDOFF (autoloop retries)`,
+ );
+ return false;
+ }
+ if (cleared) {
+ log(`[captcha] step ${step}: wall cleared kind=${visualWall.kind}`);
+ if (driver._authUrl) {
+ try {
+ await driver.goto(driver._authUrl);
+ } catch {}
+ await sleep(2000);
+ }
+ stallCount = 0;
+ continue;
+ }
+ } else if (visualWall.kind === 'hcaptcha-challenge-preload') {
+ log('[captcha] preload challenge frame noted (non-blocking)');
+ }
+ }
+
// Claude sometimes renders the email login form while preserving the
// /oauth/authorize URL. Handle known Claude auth prompts before the generic
// stall detector, otherwise AI-brain burns multiple decisions waiting for a
@@ -3027,6 +3074,14 @@ async function runAuthFlow(driver, account) {
oauthPath = new URL(url).pathname;
} catch {}
if (oauthPath.includes('/oauth/authorize') || (oauthPath.endsWith('/authorize') && url.includes('claude'))) {
+ // Clear captcha wall on authorize (can reappear after session settle).
+ if (driver._page) {
+ await trySolveCaptchaWall(driver._page, 'oauth-authorize', log);
+ if (await captchaHardFailed(driver._page)) {
+ log('[captcha] aborting on /oauth/authorize — budget exhausted');
+ return false;
+ }
+ }
// Magic-link route: we authenticated via a single-use link delivered to
// account.email's inbox, so the session on this page is guaranteed to be
// the right account. Skip the readPageText "verify" dance — it failed to
@@ -3185,6 +3240,14 @@ async function runAuthFlow(driver, account) {
await driver.goto(magicLink);
}
await sleep(4000);
+ // Post-verify captcha wall after inline code/link path (mirrors finishMagicLinkLogin)
+ if (driver._page) {
+ await trySolveCaptchaWall(driver._page, 'after-inline-code-verify', log);
+ if (await captchaHardFailed(driver._page)) {
+ log('[magic-link] aborting: captcha budget exhausted after inline verify — see CAPTCHA_VNC_HANDOFF');
+ return false;
+ }
+ }
// After magic link login, session is now valid — re-navigate to authUrl
// so the OAuth flow can complete (org chooser → authorize → callback)
if (driver._authUrl) {
diff --git a/claude-ops/scripts/account-rotation/visual-captcha-solver.mjs b/claude-ops/scripts/account-rotation/visual-captcha-solver.mjs
new file mode 100644
index 00000000..c093b6d2
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/visual-captcha-solver.mjs
@@ -0,0 +1,527 @@
+// visual-captcha-solver.mjs
+// Interactive hCaptcha / Turnstile wall solver via Gemini vision (agy) + Playwright clicks.
+// Used AFTER token inject fails to clear a large pick/drag challenge.
+// Never prints secrets. Fail-soft.
+
+import { writeFileSync, unlinkSync, mkdtempSync, existsSync } from 'fs';
+import { execFile, execFileSync, spawn } from 'child_process';
+import { promisify } from 'util';
+import { join } from 'path';
+import { homedir, tmpdir } from 'os';
+
+const execFileAsync = promisify(execFile);
+
+function sleep(ms) {
+ return new Promise((r) => setTimeout(r, ms));
+}
+
+function agyBin() {
+ if (process.env.CLAUDE_ROTATOR_AGY_BIN) return process.env.CLAUDE_ROTATOR_AGY_BIN;
+ try {
+ return execFileSync('which', ['agy'], {
+ stdio: ['ignore', 'pipe', 'ignore'],
+ timeout: 3000,
+ })
+ .toString()
+ .trim();
+ } catch {
+ return join(homedir(), '.local/bin/agy');
+ }
+}
+
+function geminiModel() {
+ return process.env.CLAUDE_ROTATOR_GEMINI_MODEL || 'Gemini 3.5 Flash (Medium)';
+}
+
+/** True when agy (Gemini CLI) is available. Self-contained — no ai-brain import. */
+let _geminiChecked = null;
+export function geminiAvailable() {
+ if (_geminiChecked !== null) return _geminiChecked;
+ if (process.env.CLAUDE_ROTATOR_DISABLE_GEMINI_BRAIN === '1') {
+ _geminiChecked = false;
+ return false;
+ }
+ try {
+ execFileSync(agyBin(), ['--help'], {
+ stdio: ['ignore', 'ignore', 'ignore'],
+ timeout: 5000,
+ });
+ _geminiChecked = true;
+ } catch {
+ _geminiChecked = false;
+ }
+ return _geminiChecked;
+}
+
+async function visionDecide(screenshotB64, url, log) {
+ if (!geminiAvailable()) {
+ log('[visual-captcha] Gemini/agy unavailable');
+ return null;
+ }
+ let tmpImg = null;
+ const prompt = [
+ 'You are solving an interactive CAPTCHA (hCaptcha pick-images, drag, or Cloudflare checkbox) in a browser screenshot.',
+ `Page URL: ${url}`,
+ '',
+ 'Return ONLY one JSON object (no markdown fences):',
+ '{',
+ ' "done": boolean, // true if challenge already passed / no captcha visible',
+ ' "clicks": [{"x": number, "y": number}], // viewport pixel coords to click (center of each target tile/checkbox)',
+ ' "drag": {"from":{"x":n,"y":n},"to":{"x":n,"y":n}} | null,',
+ ' "click_text": string | null, // optional: visible button text to click after tiles (e.g. "Verify", "Next", "Skip")',
+ ' "reason": string',
+ '}',
+ '',
+ 'Rules:',
+ '- Coordinates are absolute viewport pixels from top-left of the screenshot (same size as image).',
+ '- For "select all images with X": click the CENTER of each matching tile, then click Verify if present.',
+ '- For empty checkbox "I am human" / "Verify you are human": one click on the checkbox square.',
+ '- If a spinner is mid-solve, return done=false, clicks=[], reason=waiting.',
+ '- If captcha is gone and login/email form is visible, done=true.',
+ '- Prefer 1–6 clicks max per round. Do not invent coords outside the image.',
+ ].join('\n');
+
+ try {
+ const dir = mkdtempSync(join(tmpdir(), 'vis-cap-'));
+ tmpImg = join(dir, 'shot.png');
+ writeFileSync(tmpImg, Buffer.from(screenshotB64, 'base64'));
+ const full = `${prompt}\n\nScreenshot: @${tmpImg}`;
+ const { stdout } = await execFileAsync(
+ agyBin(),
+ ['--print', full, '--model', geminiModel(), '--dangerously-skip-permissions'],
+ { timeout: 90_000, maxBuffer: 2_000_000, env: process.env },
+ );
+ const text = (stdout || '').trim();
+ log(`[visual-captcha] vision responded (${text.length} chars)`);
+ const m = text.match(/\{[\s\S]*\}/);
+ if (!m) return null;
+ return JSON.parse(m[0]);
+ } catch (e) {
+ log(`[visual-captcha] vision failed: ${String(e.message || e).slice(0, 140)}`);
+ return null;
+ } finally {
+ if (tmpImg) {
+ try {
+ unlinkSync(tmpImg);
+ } catch {}
+ }
+ }
+}
+
+/**
+ * Interactively clear a large captcha wall using vision + mouse.
+ * @param {import('playwright').Page} page
+ * @param {(m:string)=>void} log
+ * @param {{ maxRounds?: number }} opts
+ * @returns {Promise<boolean>} true if wall appears cleared
+ */
+export async function solveInteractiveCaptchaVisually(page, log = () => {}, opts = {}) {
+ if (!page) return false;
+ if (process.env.CLAUDE_ROT_VISUAL_CAPTCHA === '0') {
+ log('[visual-captcha] disabled via CLAUDE_ROT_VISUAL_CAPTCHA=0');
+ return false;
+ }
+ const maxRounds = Number(opts.maxRounds || process.env.CLAUDE_ROT_VISUAL_CAPTCHA_ROUNDS || 8);
+ const vp = page.viewportSize() || { width: 1440, height: 900 };
+
+ for (let round = 1; round <= maxRounds; round++) {
+ let buf;
+ try {
+ buf = await page.screenshot({ type: 'png', fullPage: false, timeout: 8000 });
+ } catch (e) {
+ log(`[visual-captcha] screenshot failed: ${String(e.message || e).slice(0, 80)}`);
+ return false;
+ }
+ const b64 = Buffer.from(buf).toString('base64');
+ const decision = await visionDecide(b64, page.url(), log);
+ if (!decision) {
+ log(`[visual-captcha] round ${round}: no decision`);
+ continue;
+ }
+ log(
+ `[visual-captcha] round ${round}: done=${!!decision.done} clicks=${(decision.clicks || []).length} reason=${String(decision.reason || '').slice(0, 80)}`,
+ );
+ if (decision.done) return true;
+
+ const clicks = Array.isArray(decision.clicks) ? decision.clicks : [];
+ for (const c of clicks.slice(0, 8)) {
+ const x = Math.max(2, Math.min(vp.width - 2, Number(c.x) || 0));
+ const y = Math.max(2, Math.min(vp.height - 2, Number(c.y) || 0));
+ if (!x || !y) continue;
+ try {
+ await page.mouse.click(x, y, { delay: 40 });
+ await sleep(350 + Math.floor(Math.random() * 200));
+ } catch (e) {
+ log(`[visual-captcha] click failed ${x},${y}: ${String(e.message || e).slice(0, 60)}`);
+ }
+ }
+
+ if (decision.drag?.from && decision.drag?.to) {
+ try {
+ const { from, to } = decision.drag;
+ await page.mouse.move(from.x, from.y);
+ await page.mouse.down();
+ await page.mouse.move(to.x, to.y, { steps: 12 });
+ await page.mouse.up();
+ await sleep(500);
+ } catch {}
+ }
+
+ if (decision.click_text) {
+ try {
+ const t = String(decision.click_text);
+ const btn = page.getByRole('button', { name: new RegExp(t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i') });
+ if ((await btn.count()) > 0) await btn.first().click({ timeout: 3000 });
+ else
+ await page
+ .getByText(t, { exact: false })
+ .first()
+ .click({ timeout: 3000 })
+ .catch(() => {});
+ } catch {}
+ }
+
+ await sleep(1800);
+
+ // Heuristic clear: no large hcaptcha challenge iframe visible
+ try {
+ const still = await page.evaluate(() => {
+ const frames = Array.from(document.querySelectorAll('iframe'));
+ for (const f of frames) {
+ const src = f.getAttribute('src') || '';
+ let host = '';
+ try {
+ host = new URL(src, location.href).hostname.toLowerCase();
+ } catch {
+ continue;
+ }
+ const isHc = host === 'hcaptcha.com' || host.endsWith('.hcaptcha.com');
+ if (!isHc || !/(?:^|[?&#])frame=challenge(?:&|#|$)/i.test(src)) continue;
+ const r = f.getBoundingClientRect();
+ if (r.width >= 200 && r.height >= 200 && r.bottom > 0) return true;
+ }
+ const t = (document.body?.innerText || '').slice(0, 500);
+ if (/select all images|pick the|drag the|i am human|verify you are human/i.test(t)) return true;
+ return false;
+ });
+ if (!still) {
+ log(`[visual-captcha] wall cleared after round ${round}`);
+ return true;
+ }
+ } catch {}
+ }
+ log('[visual-captcha] max rounds exhausted — wall still present');
+ return false;
+}
+
+/**
+ * Fire VNC computer-use agent against Claude VNC (:5902) as last autonomous resort.
+ * Non-blocking optional; returns promise of success boolean.
+ */
+export async function runVncComputerUseCaptcha(log = () => {}, opts = {}) {
+ if (process.env.CLAUDE_ROT_VNC_AGENT === '0') {
+ log('[visual-captcha] VNC agent disabled');
+ return false;
+ }
+ const vncPort = opts.vncPort || process.env.CLAUDE_VNC_PORT || '5902';
+ const password = process.env.VNC_PASSWORD || process.env.CLAUDE_VNC_PASSWORD || process.env.VNC_PASS || '';
+ const project = process.env.VNC_USE_PROJECT || join(homedir(), 'tools/vnc-use');
+ if (!existsSync(join(project, 'pyproject.toml'))) {
+ log('[visual-captcha] vnc-use project missing');
+ return false;
+ }
+ const task =
+ opts.task ||
+ 'On the visible Chrome window: solve any Cloudflare checkbox or hCaptcha image challenge for Claude login. Click the correct tiles, then Verify/Continue. Do not close the browser. Stop when the captcha is gone or a login/email form or success page is visible.';
+ const args = [
+ 'run',
+ '--project',
+ project,
+ 'vnc-use',
+ 'run',
+ '--task',
+ task,
+ '--vnc',
+ `127.0.0.1::${vncPort}`,
+ '--no-hitl',
+ '--step-limit',
+ String(opts.stepLimit || 25),
+ '--timeout',
+ String(opts.timeout || 180),
+ ];
+ if (password) {
+ args.push('--password', password);
+ }
+ // Prefer non-metered if configured; leave MODEL_PROVIDER to env
+ log(`[visual-captcha] starting VNC computer-use on :${vncPort}`);
+ return await new Promise((resolve) => {
+ const child = spawn('uv', args, {
+ env: { ...process.env, CUDA_VISIBLE_DEVICES: '' },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let out = '';
+ child.stdout?.on('data', (d) => {
+ out += d.toString();
+ });
+ child.stderr?.on('data', (d) => {
+ out += d.toString();
+ });
+ const t = setTimeout(
+ () => {
+ try {
+ child.kill('SIGTERM');
+ } catch {}
+ log('[visual-captcha] VNC agent timeout');
+ resolve(false);
+ },
+ (opts.timeout || 180) * 1000 + 5000,
+ );
+ child.on('close', (code) => {
+ clearTimeout(t);
+ log(`[visual-captcha] VNC agent exit=${code} out=${out.slice(-200).replace(/\s+/g, ' ')}`);
+ resolve(code === 0);
+ });
+ });
+}
+
+/**
+ * Resolve desktop-act runner for background rotate-magic.
+ * Prefers the portable stdio CLI (`desktop-act run`); falls back to local captcha wrapper.
+ * No host-specific paths beyond $HOME + XDG cache (same layout every install).
+ */
+function resolveDesktopActRunner() {
+ const home = homedir();
+ const xdg = process.env.XDG_CACHE_HOME || join(home, '.cache');
+ const pluginRoot = process.env.CLAUDE_PLUGIN_ROOT || '';
+ const explicit = process.env.DESKTOP_ACT_CLI || process.env.DESKTOP_ACT_CAPTCHA_BIN || '';
+ let whichCli = '';
+ try {
+ whichCli = execFileSync('which', ['desktop-act'], {
+ stdio: ['ignore', 'pipe', 'ignore'],
+ timeout: 3000,
+ })
+ .toString()
+ .trim();
+ } catch {
+ /* not on PATH */
+ }
+ const candidates = [
+ explicit,
+ whichCli,
+ pluginRoot ? join(pluginRoot, 'desktop-act', 'cli', 'desktop-act') : '',
+ // Sibling plugin next to claude-ops when installed from ops-marketplace monorepo
+ pluginRoot ? join(pluginRoot, '..', 'desktop-act', 'cli', 'desktop-act') : '',
+ join(xdg, 'desktop-act-mcp/src/cli/desktop-act'),
+ join(home, '.cache/desktop-act-mcp/src/cli/desktop-act'),
+ join(home, '.local/bin/desktop-act'),
+ join(home, '.local/bin/desktop-act-captcha-fallback'),
+ ].filter(Boolean);
+ for (const p of candidates) {
+ if (existsSync(p)) {
+ const base = p.split('/').pop() || '';
+ const kind = base === 'desktop-act' || base === 'desktop_act_cli.py' ? 'cli' : 'wrapper';
+ return { path: p, kind };
+ }
+ }
+ return null;
+}
+
+function defaultDesktopDisplay() {
+ // Reauth Chrome (start-reauth-chrome) defaults to DISPLAY=:1 for headed reauth seats.
+ // :2 is the secondary VNC seat — only use if explicitly set.
+ return process.env.CLAUDE_DESKTOP_DISPLAY || process.env.DESKTOP_ACT_DISPLAY || process.env.DISPLAY || ':1';
+}
+
+/**
+ * desktop-act autonomous act() loop on the real X/VNC display where headed Chrome runs.
+ * Called from rotate-magic captcha cascade — no interactive session required.
+ */
+export async function runDesktopActCaptcha(log = () => {}, opts = {}) {
+ if (process.env.CLAUDE_ROT_DESKTOP_ACT === '0') {
+ log('[visual-captcha] desktop-act disabled (CLAUDE_ROT_DESKTOP_ACT=0)');
+ return false;
+ }
+ const runner = resolveDesktopActRunner();
+ if (!runner) {
+ log('[visual-captcha] desktop-act runner missing (install cli/desktop-act or desktop-act-captcha-fallback)');
+ return false;
+ }
+ const display = opts.display || defaultDesktopDisplay();
+ const timeoutSec = Number(opts.timeout || process.env.DESKTOP_ACT_CAPTCHA_TIMEOUT || 180);
+ const maxIter = Number(opts.maxIterations || process.env.DESKTOP_ACT_MAX_ITERATIONS || 25);
+ const goal =
+ opts.goal ||
+ process.env.DESKTOP_ACT_CAPTCHA_GOAL ||
+ [
+ 'Find the headed browser window with a Claude login or captcha challenge.',
+ 'Solve any Cloudflare "verify you are human" checkbox or hCaptcha image/tile challenge.',
+ 'Click correct tiles, then Verify/Next/Continue.',
+ 'Do not close the browser. Stop when captcha is gone or login/OAuth advances.',
+ ].join(' ');
+
+ const home = homedir();
+ const xdg = process.env.XDG_CACHE_HOME || join(home, '.cache');
+ const defaultHome = process.env.DESKTOP_ACT_HOME || join(xdg, 'desktop-act-mcp/src');
+ const defaultVenv = process.env.DESKTOP_ACT_VENV || join(defaultHome, '.venv');
+ const defaultCmd =
+ process.env.DESKTOP_ACT_COMMAND ||
+ (existsSync(join(defaultHome, 'mcp-server/run.sh')) ? join(defaultHome, 'mcp-server/run.sh') : '');
+
+ // Use `act` (not `run`) so we drive the EXISTING headed Chrome display.
+ // `run` would acquire a fresh empty Xvnc pool session and miss the captcha tab.
+ let args;
+ if (runner.kind === 'cli') {
+ // Portable CLI: act() param is max_iterations (not max_steps).
+ args = [
+ 'act',
+ '--goal',
+ goal,
+ '--timeout',
+ String(timeoutSec),
+ '--max-iterations',
+ String(maxIter),
+ '--display',
+ display,
+ ];
+ } else {
+ // Wrapper historically called `run`; pass --no-acquire if supported, else act via env.
+ args = ['--display', display, '--timeout', String(timeoutSec), '--goal', goal, '--mode', 'act'];
+ }
+
+ log(
+ `[visual-captcha] starting desktop-act (${runner.kind}) display=${display} timeout=${timeoutSec}s bin=${runner.path}`,
+ );
+
+ return await new Promise((resolve) => {
+ const child = spawn(runner.path, args, {
+ env: {
+ ...process.env,
+ DISPLAY: display,
+ DESKTOP_ACT_DISPLAY: display,
+ DESKTOP_ACT_HOME: defaultHome,
+ DESKTOP_ACT_VENV: defaultVenv,
+ ...(defaultCmd ? { DESKTOP_ACT_COMMAND: defaultCmd } : {}),
+ PATH: `${join(home, '.local/bin')}:/usr/local/bin:/usr/bin:/bin:${process.env.PATH || ''}`,
+ },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let out = '';
+ child.stdout?.on('data', (d) => {
+ out += d.toString();
+ });
+ child.stderr?.on('data', (d) => {
+ out += d.toString();
+ });
+ const t = setTimeout(
+ () => {
+ try {
+ child.kill('SIGTERM');
+ } catch {}
+ log('[visual-captcha] desktop-act timeout');
+ resolve(false);
+ },
+ timeoutSec * 1000 + 15_000,
+ );
+ child.on('close', (code) => {
+ clearTimeout(t);
+ log(`[visual-captcha] desktop-act exit=${code} tail=${out.slice(-320).replace(/\s+/g, ' ')}`);
+ resolve(code === 0);
+ });
+ });
+}
+
+/**
+ * Full autonomous captcha escalation for rotate-magic (no human session):
+ * 1) Playwright + vision clicks on the live page
+ * 2) desktop-act act() on the headed Chrome display
+ * 3) optional VNC computer-use (last autonomous resort)
+ *
+ * Returns { ok, layer } so rotate can re-detect the wall after each layer.
+ */
+export async function runAutonomousCaptchaCascade(page, log = () => {}, opts = {}) {
+ const includeVnc = opts.includeVnc !== false && process.env.CLAUDE_ROT_VNC_AGENT !== '0';
+ const display = opts.display || defaultDesktopDisplay();
+ const daTimeout = Number(opts.desktopTimeout || process.env.DESKTOP_ACT_CAPTCHA_TIMEOUT || 180);
+
+ if (page && process.env.CLAUDE_ROT_VISUAL_CAPTCHA !== '0') {
+ try {
+ const visOk = await solveInteractiveCaptchaVisually(page, log, {
+ maxRounds: opts.visualRounds || 6,
+ });
+ if (visOk) return { ok: true, layer: 'visual-ai' };
+ } catch (e) {
+ log(`[visual-captcha] cascade visual error: ${String(e.message || e).slice(0, 100)}`);
+ }
+ }
+
+ if (process.env.CLAUDE_ROT_DESKTOP_ACT !== '0') {
+ // Bring the Playwright tab to the front so desktop-act/X11 sees the captcha,
+ // not an unrelated tab on the same DISPLAY.
+ if (page) {
+ try {
+ await page.bringToFront();
+ await page.evaluate(() => {
+ try {
+ window.focus();
+ } catch {}
+ });
+ } catch (e) {
+ log(`[visual-captcha] bringToFront warn: ${String(e.message || e).slice(0, 80)}`);
+ }
+ try {
+ // Best-effort: raise any Chrome window whose title mentions Claude/hCaptcha.
+ execFileSync(
+ 'bash',
+ [
+ '-lc',
+ `DISPLAY=${JSON.stringify(display)} xdotool search --onlyvisible --name 'Claude|hCaptcha|Sign in' windowactivate --sync 2>/dev/null | head -1`,
+ ],
+ { timeout: 4000, stdio: ['ignore', 'pipe', 'ignore'] },
+ );
+ } catch {
+ /* xdotool optional */
+ }
+ }
+ try {
+ const daOk = await runDesktopActCaptcha(log, {
+ display,
+ timeout: daTimeout,
+ maxIterations: opts.maxIterations,
+ goal: opts.goal,
+ });
+ if (daOk) return { ok: true, layer: 'desktop-act' };
+ } catch (e) {
+ log(`[visual-captcha] cascade desktop-act error: ${String(e.message || e).slice(0, 100)}`);
+ }
+ }
+
+ if (includeVnc) {
+ try {
+ const vncOk = await runVncComputerUseCaptcha(log, {
+ vncPort: opts.vncPort || process.env.CLAUDE_VNC_PORT || '5902',
+ timeout: opts.vncTimeout || 120,
+ stepLimit: opts.vncStepLimit || 25,
+ });
+ if (vncOk) return { ok: true, layer: 'vnc-use' };
+ } catch (e) {
+ log(`[visual-captcha] cascade vnc error: ${String(e.message || e).slice(0, 100)}`);
+ }
+ }
+
+ return { ok: false, layer: null };
+}
+
+// CLI: node visual-captcha-solver.mjs --cdp 9223
+if (import.meta.url === `file://${process.argv[1]}` || process.argv[1]?.endsWith('visual-captcha-solver.mjs')) {
+ const cdp = process.argv.includes('--cdp') ? process.argv[process.argv.indexOf('--cdp') + 1] : '9223';
+ const { chromium } = await import('playwright');
+ const browser = await chromium.connectOverCDP(`http://127.0.0.1:${cdp}`);
+ const page = browser.contexts()[0]?.pages()?.[0];
+ if (!page) {
+ console.error('no page');
+ process.exit(2);
+ }
+ const ok = await solveInteractiveCaptchaVisually(page, console.log);
+ console.log(ok ? 'CLEARED' : 'STILL_BLOCKED');
+ process.exit(ok ? 0 : 1);
+}
diff --git a/claude-ops/skills/ops-accounts/SKILL.md b/claude-ops/skills/ops-accounts/SKILL.md
new file mode 100644
index 00000000..b9a17a44
--- /dev/null
+++ b/claude-ops/skills/ops-accounts/SKILL.md
@@ -0,0 +1,67 @@
+---
+name: ops-accounts
+description: Multi-provider AI account manager (Claude, Grok/xAI, Codex). Status, switch, refresh, and reauth behind one skill. Phase 0 thin router over existing engines; /ops:rotate remains a Claude-focused alias.
+argument-hint: '[status|switch|refresh|reauth|list] [provider] [email]'
+allowed-tools:
+ - Bash
+ - Read
+ - AskUserQuestion
+effort: low
+maxTurns: 20
+---
+
+# OPS ► ACCOUNTS (phase 0)
+
+One skill for **all** paid AI seats on the box. Provider engines stay specialized;
+this skill is the **router** and the product surface for “public plugin only.”
+
+| Provider | Engine today | Unattended reauth |
+|----------|--------------|-------------------|
+| Claude | `scripts/account-rotation/rotate.mjs` + `rotate-magic.mjs` | magic-link + captcha cascade |
+| Grok | `grok-rotate`, `grok-oauth-reauth`, `grok-cli-auth-proxy` | xAI device-code + Google (dcli) |
+| Codex | `codex-rotate` if present | OpenAI OAuth bridge patterns |
+
+CRS is **optional** and Claude-oriented (relay LB). It is not required for
+standalone reauth on any provider.
+
+## Subcommands (`$ARGUMENTS`)
+
+| Args | Action |
+|------|--------|
+| (none) / `status` | Cross-provider status (no secrets) |
+| `list` | Same as status (phase 0) |
+| `switch grok` | Next SuperGrok seat (`grok-rotate switch`) |
+| `switch claude` | Point at `/ops:rotate rotate-now` |
+| `refresh` / `refresh all` | `host-token-keepalive --force` |
+| `refresh grok` / `refresh claude` | Provider-scoped keepalive |
+| `reauth grok <email>` | Device-code reauth (dcli password/TOTP) |
+| `reauth claude <email>` | `rotate-magic.mjs --to <email>` |
+
+## How to run
+
+```bash
+# preferred: plugin bin
+"${CLAUDE_PLUGIN_ROOT}/bin/ops-accounts" status
+"${CLAUDE_PLUGIN_ROOT}/bin/ops-accounts" reauth grok <email>
+"${CLAUDE_PLUGIN_ROOT}/bin/ops-accounts" switch grok
+```
+
+If `CLAUDE_PLUGIN_ROOT` is unset, resolve the latest
+`~/.claude/plugins/cache/ops-marketplace/ops/*/`.
+
+## Rules
+
+1. **Never print tokens, cookies, or full vault dumps.**
+2. Prefer the bin router over ad-hoc host paths so cutover can retarget one file.
+3. On weekly-cap / 429 for Grok interactive TUI: `switch grok` after seats are healthy.
+4. On dead refresh_token: `reauth <provider> <email>` — do not claim CRS will fix OAuth.
+5. `/ops:rotate` stays as Claude alias until one major version after rename.
+
+## Phase map
+
+- **0 (this skill):** unified verbs + docs
+- **1–2:** Claude captcha port + CRS optional (enablers)
+- **3:** absorb host `grok-*` into plugin installers/timers
+- **4:** optional bundled LB (not a full CRS fork)
+
+See `docs/ops/OPS-ACCOUNTS-VISION.md`.
diff --git a/claude-ops/skills/ops-rotate-setup/SKILL.md b/claude-ops/skills/ops-rotate-setup/SKILL.md
index 5c8bc7f1..ec7f7d9c 100644
--- a/claude-ops/skills/ops-rotate-setup/SKILL.md
+++ b/claude-ops/skills/ops-rotate-setup/SKILL.md
@@ -1,7 +1,7 @@
---
name: ops-rotate-setup
-description: Interactive OAuth init wizard for the multi-account Claude rotator. Walks through every account in the rotation config and, for any account missing a valid keychain token, delegates to the proven `rotate.mjs` magic-link flow (browser-driver cascade + Gmail polling), which writes the verified OAuth token to `Claude-Rotation-<key>` (key = account label or email, keychain account `$USER`). Re-runnable any time. Standalone alias of the same step inside `/ops:setup`.
-argument-hint: '[--all|--account <email>|--add|--crs]'
+description: Interactive OAuth init wizard for the multi-account Claude rotator. Walks through every account in the rotation config and, for any account missing a valid keychain token, delegates to the proven `rotate.mjs` / `rotate-magic.mjs` magic-link flow (browser-driver cascade + Gmail polling), which writes the verified OAuth token to `Claude-Rotation-<key>` (key = account label or email, keychain account `$USER`). CRS is optional (multi-account load balancing only). Re-runnable any time. Standalone alias of the same step inside `/ops:setup`.
+argument-hint: '[--all|--account <email>|--add|--crs|--standalone]'
allowed-tools:
- Bash
- Read
@@ -179,20 +179,93 @@ Result for <email>:
If success and no more accounts remain, jump to **Step 5**.
+## Step 4.4 — CRS detection (optional enhancement — never required)
+
+**CRS is not required for rotate-magic or the keychain rotator.**
+
+- **Standalone rotate-magic** (recommended for single/few accounts): captures
+ and refreshes one account at a time via `rotate.mjs` / `rotate-magic.mjs`
+ (magic-link + captcha cascade). Enough when you are not spreading load across
+ a large pool.
+- **CRS** (claude-relay-service): multi-account **load balancing / rate-limit
+ spreading** — one relay endpoint, many seats, `schedulable` flags. Useful
+ mainly when you hit 429s with multi-account traffic.
+
+### Detect CRS (env-templated; no host hardcodes)
+
+Run detection before offering install. Any hit = "CRS likely present":
+
+```bash
+CRS_DETECTED=0
+# binary on PATH
+command -v crs >/dev/null 2>&1 && CRS_DETECTED=1
+# common compose / service names (user-space; ignore if missing)
+systemctl --user is-active crs-compose.service >/dev/null 2>&1 && CRS_DETECTED=1
+# config already enabled
+CFG="${USER_CFG:-$HOME/.claude/plugins/data/ops-ops-marketplace/account-rotation-config.json}"
+[[ -f "$CFG" ]] && jq -e '.crs.enabled == true' "$CFG" >/dev/null 2>&1 && CRS_DETECTED=1
+# optional env base URL responds
+CRS_URL="${CRS_BASE_URL:-${CRS_URL:-http://127.0.0.1:3000}}"
+curl -fsS --max-time 2 "$CRS_URL/health" >/dev/null 2>&1 && CRS_DETECTED=1
+echo "CRS_DETECTED=$CRS_DETECTED"
+```
+
+### Branch
+
+**If CRS detected (`CRS_DETECTED=1`)** — offer wire-in as optional enhancement:
+
+```
+CRS looks installed or already configured. Wire ops-rotate to it for multi-account
+rate-limit load balancing? (Not required for standalone rotate-magic.)
+ [Wire CRS] — continue to Step 4.5 (priority daemon + reconcilers)
+ [Standalone] — keychain + rotate-magic only; leave CRS alone
+ [Skip] — neither; finish summary
+ [What is CRS?] — short explainer, then re-ask
+```
+
+**If CRS not detected** — explain + choose path:
+
+```
+CRS (claude-relay-service) was not detected.
+
+What it is: multi-account load balancing / rate-limit spreading across a relay
+pool. Useful mainly when you hit rate limits with many accounts.
+
+Standalone rotate-magic targets one account at a time and is enough for most
+users (single seat or a few seats with the keychain rotator).
+
+ [Use rotate-magic standalone (Recommended for single/few accounts)]
+ [Install CRS] — open CRS install docs / print next steps; do not block OAuth
+ [Skip] — finish without CRS
+```
+
+- **[Use rotate-magic standalone]**: print that OAuth tokens from Steps 3–4 are
+ enough; captcha cascade is in `scripts/account-rotation/CAPTCHA-CASCADE.md`.
+ Jump to **Step 5 — Summary** (CRS lines = not configured). Do **not** run
+ Steps 4.5–4.7 unless the user later passes `--crs`.
+- **[Install CRS]**: print a short pointer to upstream CRS install (docker
+ compose / project README), note that after install they can re-run
+ `/ops:rotate-setup --crs`. Do not hard-fail if they never install. Then offer
+ to continue OAuth summary or exit.
+- **[Skip]**: same as standalone for this wizard — jump to Step 5.
+- **[Wire CRS]** / **[What is CRS?]**: continue into Step 4.5 as today.
+
+`--standalone` argument: force the standalone branch (skip 4.5–4.7).
+`--crs` argument: skip detection ask; jump to Step 4.5 (existing behavior).
+
## Step 4.5 — CRS relay-pool priority daemon (optional)
-If the user runs a **claude-relay-service** (CRS) pool (load-balances Claude
-requests across many accounts at once, exposing a per-account `schedulable`
-flag), offer to install the **priority daemon** that auto-deprioritizes
-near-maxed accounts and re-enables them on recovery. This is independent of the
-keychain rotator above — skip it for keychain-only setups.
+Only when the user chose **Wire CRS** / **Install CRS** completed / `--crs`, or
+detection found CRS and they opted in. Install the **priority daemon** that
+auto-deprioritizes near-maxed accounts and re-enables them on recovery. This is
+independent of the keychain rotator — skip for keychain-only setups.
-`AskUserQuestion`:
+`AskUserQuestion` (if not already answered in 4.4):
```
-Do you run a claude-relay-service (CRS) pool you want auto-prioritized?
+Configure CRS pool auto-prioritization?
[Yes — configure + install] — set base URL + admin creds, install the 120s daemon
- [Not now] — skip (you can run /ops:rotate-setup again later)
+ [Not now] — skip (you can run /ops:rotate-setup --crs later)
[What is this?] — one-paragraph explainer, then re-ask
```
@@ -357,31 +430,35 @@ would be a `rotate.mjs`-internals change, out of scope here.
Config: ~/.claude/plugins/data/ops-ops-marketplace/account-rotation-config.json
Keychain: Claude-Rotation-<key> (account: $USER) · key = label or email
- CRS priority daemon: ✓ installed (every 120s) | ✗ not configured
- CRS 429-cooldown: ✓ installed (every 60s) | ✗ not enabled
- CRS 401-refresher: ✓ installed (every 300s) | ✗ not enabled
- Magic-link autoloop: ✓ installed (every 600s) | ✗ not enabled
+ Mode: standalone rotate-magic | CRS pool wired
+ CRS priority daemon: ✓ installed (every 120s) | ✗ not configured (optional)
+ CRS 429-cooldown: ✓ installed (every 60s) | ✗ not enabled (optional)
+ CRS 401-refresher: ✓ installed (every 300s) | ✗ not enabled (optional)
+ Magic-link autoloop: ✓ installed (every 600s) | ✗ not enabled (optional)
+
+ Standalone reauth (no CRS): node $CLAUDE_PLUGIN_ROOT/scripts/account-rotation/rotate-magic.mjs --to <email>
- To enable automatic rotation, open /plugins → claude-ops → settings and
+ To enable automatic keychain rotation, open /plugins → claude-ops → settings and
toggle "Multi-account Claude rotator" (account_rotation_enabled).
──────────────────────────────────────────────────────
```
-(Show the CRS priority-daemon line only if Step 4.5 ran; show the two Step 4.6
-reconciler lines only if Step 4.6 ran; show the magic-link line only if Step
-4.7 ran. All four CRS daemons are independent of the `account_rotation_enabled`
-toggle — each is gated by its own config flag (`crs.enabled`,
-`crs.cooldownEnabled`, `crs.tokenRefreshEnabled`, `crs.enableMagicLinkRecovery`)
-plus whether its launchd/systemd timer is installed.)
+(Show CRS daemon lines as `not configured (optional)` when Step 4.4 chose
+standalone/skip. Show installed only if 4.5–4.7 ran. All four CRS daemons are
+independent of `account_rotation_enabled` — each is gated by its own config flag
+(`crs.enabled`, `crs.cooldownEnabled`, `crs.tokenRefreshEnabled`,
+`crs.enableMagicLinkRecovery`) plus whether its launchd/systemd timer is
+installed. **Never treat missing CRS as setup failure.**)
Exit. Do NOT auto-enable `account_rotation_enabled` — that decision belongs
to the user, made explicitly through the plugin settings UI.
## Argument handling
-- `--all` (default): full wizard as described above.
+- `--all` (default): full wizard as described above (includes Step 4.4 CRS detection).
- `--account <email>`: skip Step 2; only init the matching account.
- `--add`: skip token check; jump straight to Step 2 add loop, then init.
+- `--standalone`: after OAuth (or immediately if tokens already valid), force standalone rotate-magic path — skip Steps 4.5–4.7.
- `--crs`: jump straight to **Step 4.5** (configure + install the CRS priority daemon), then **Step 4.6** (offer the reconciler add-ons), skipping the keychain-account OAuth steps.
- `--reconcilers`: jump straight to **Step 4.6** (offer/reconfigure the 429-cooldown and 401-refresher reconcilers, then Step 4.7's magic-link autoloop offer) — requires Step 4.5 already configured (`crs.enabled=true`); if not, print the same message as `--crs` needing configuration first and exit.
diff --git a/claude-ops/skills/ops-rotate/SKILL.md b/claude-ops/skills/ops-rotate/SKILL.md
index a3f8eeda..cd86a3bf 100644
--- a/claude-ops/skills/ops-rotate/SKILL.md
+++ b/claude-ops/skills/ops-rotate/SKILL.md
@@ -1,7 +1,7 @@
---
name: ops-rotate
-description: Multi-account Claude Max rotator. Status, manual rotation, account list, add-account wizard, and CRS relay-pool auto-prioritization. Requires account_rotation_enabled=true in plugin settings.
-argument-hint: '[status|rotate-now|list|add-account|crs|crs-tick]'
+description: Multi-account Claude Max rotator. Status, manual rotation, account list, add-account wizard, standalone rotate-magic reauth, and optional CRS relay-pool auto-prioritization. CRS is not required. Requires account_rotation_enabled=true in plugin settings for daemon swap; reauth works without it.
+argument-hint: '[status|rotate-now|list|add-account|reauth|crs|crs-tick]'
allowed-tools:
- Bash
- Read
@@ -25,21 +25,23 @@ Manage the optional multi-account Claude Max rotator. Off by default — flip
| `rotate-now` | Force rotation to the most-cooled candidate (or `--to <email>`) |
| `list` | List every configured account with token state + last util |
| `add-account` | Interactive wizard: collect email, OAuth into rotator vault |
+| `reauth` | Standalone rotate-magic for one email (no CRS): magic-link + captcha |
| `crs` | Show the CRS relay-pool schedulable state + priority-daemon health |
| `crs-tick` | Run one CRS priority tick now (append `--dry-run` to preview, no writes) |
-## Two rotation models
+## Rotation models (CRS is optional)
-This skill manages **two complementary** account-management systems:
+This skill manages **complementary** account systems. **CRS is never required.**
+- **Standalone rotate-magic** (`reauth`, and setup OAuth) — one account at a time.
+ Magic-link + captcha cascade. Enough for single/few accounts. No CRS install.
- **Keychain rotator** (`status`/`rotate-now`/`list`/`add-account`) — for **direct-auth**
sessions. One active claude.ai OAuth token in the keychain at a time; the daemon swaps
to the coolest account when the active one heats up.
-- **CRS priority daemon** (`crs`/`crs-tick`) — for a **claude-relay-service** pool, which
- load-balances across _many_ accounts simultaneously. Instead of swapping one token, it
- toggles each account's `schedulable` flag from live utilization so the relay avoids
- near-maxed accounts and re-enables them on recovery. Off by default; see
- **ops-rotate-setup** to configure + install.
+- **CRS priority daemon** (`crs`/`crs-tick`) — **optional** multi-account load balancing
+ / rate-limit spreading via **claude-relay-service**. Toggles each account's
+ `schedulable` flag from live utilization. Off by default; configure only if you
+ run a CRS pool (see **ops-rotate-setup** Step 4.4 detection).
## Pre-flight (every invocation)
@@ -127,9 +129,32 @@ This is the only mutating subcommand. Walk the user through:
```
6. **Verify.** Run `status` subcommand inline.
+## reauth (standalone rotate-magic — no CRS)
+
+Refresh one account's vault token via magic-link + captcha cascade. Does **not**
+need CRS or `crs.enabled`.
+
+```
+EMAIL="<email>" # required
+node "$ROT_SRC/rotate-magic.mjs" --to "$EMAIL"
+# equivalent:
+# node "$ROT_SRC/rotate.mjs" --magic-link --to "$EMAIL"
+```
+
+Background-friendly; surface the log. Headed display + cascade env:
+`CLAUDE_DESKTOP_DISPLAY`, `CLAUDE_ROT_HEADED=1` (see `CAPTCHA-CASCADE.md`).
+If the user only has one seat, this is the primary recovery path — do not
+push them to install CRS.
+
## crs (relay-pool status)
-Show the claude-relay-service pool's per-account schedulable state + the priority
+**Only if CRS is present.** Detect first (same checks as ops-rotate-setup Step 4.4:
+`command -v crs`, `crs.enabled` in config, `$CRS_BASE_URL/health` or default
+`http://127.0.0.1:3000/health`). If not detected, explain briefly that CRS is
+optional load balancing and suggest `reauth` / `/ops:rotate-setup --standalone`
+instead of failing.
+
+When CRS is available: show the pool's per-account schedulable state + the priority
daemon's health, plus the three optional reconcilers (429-cooldown, 401-refresher,
magic-link-autoloop) if enabled. Read-only.
@@ -160,11 +185,11 @@ CRS POOL (http://127.0.0.1:3000)
magic-link : ✓ running (every 600s) | ✗ not loaded | – not enabled (crs.enableMagicLinkRecovery=false)
```
-If CRS `/health` is unreachable, say so and point to ops-rotate-setup. If the daemon
-isn't loaded but `crs.enabled` is true, suggest `/ops:rotate-setup`. Show the two
-reconciler lines only if their config flag is true — if false, show `– not enabled`
-rather than treating it as a failure (it's an opt-in feature). If a flag is true but
-its daemon isn't loaded, suggest `/ops:rotate-setup --reconcilers`.
+If CRS `/health` is unreachable, say so and point to `/ops:rotate-setup` (optional)
+or standalone `reauth`. If the daemon isn't loaded but `crs.enabled` is true, suggest
+`/ops:rotate-setup --crs`. Show reconciler lines only if their config flag is true —
+if false, show `– not enabled` (opt-in, not a failure). If a flag is true but its
+daemon isn't loaded, suggest `/ops:rotate-setup --reconcilers`.
## crs-tick (run one tick now)