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(rotation): portable unattended reauth env for magic-link-autoloop

auroracapital2132acdcc4aa
diff --git a/claude-ops/CHANGELOG.md b/claude-ops/CHANGELOG.md
index 5bf2db86..824d7d93 100644
--- a/claude-ops/CHANGELOG.md
+++ b/claude-ops/CHANGELOG.md
@@ -4,6 +4,7 @@
### Added
+- **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.
- **ops-desk (new skill):** `/ops:ops-desk` desk sweep — fans out read-only context agents (batched, Workflow tool) over the owner's open decisions/drafts/payments/sign-offs and returns a ranked, ready-to-approve action queue worked down under the per-draft outbound gate. Complements `/ops:ops-inbox`.
diff --git a/claude-ops/scripts/account-rotation/CAPTCHA-CASCADE.md b/claude-ops/scripts/account-rotation/CAPTCHA-CASCADE.md
new file mode 100644
index 00000000..5ad20067
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/CAPTCHA-CASCADE.md
@@ -0,0 +1,73 @@
+# 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).
+
+## 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 |
+
+If this install's `rotate.mjs` has no captcha helpers, the env keys below are
+harmless no-ops.
+
+## Order (when captcha helpers are present)
+
+1. Residential / browser wait (`CRS_CAPTCHA_BROWSER_WAIT_MS`)
+2. **Large interactive** walls (visible hCaptcha challenge / CF frame): prefer
+ autonomous cascade first (paid token inject rarely clears pick/drag).
+ Override with `CLAUDE_ROT_LARGE_HC_TOKEN_FIRST=1` only when debugging.
+3. Token solvers (2captcha / CapSolver / …) when keys are configured
+4. Autonomous cascade (`runAutonomousCaptchaCascade` when implemented):
+ - Playwright + vision tile clicks
+ - **desktop-act** `act` (not pool `run`) on `CLAUDE_DESKTOP_DISPLAY`
+ - VNC computer-use as last autonomous layer
+5. Dashboard marker file only if all layers fail — **not** a human handoff.
+ The autoloop re-dispatches after `magicLinkRetryCooldownMs`.
+
+## Env (all optional; defaults in `reauth-env.mjs` / `magic-link-autoloop.sh`)
+
+| Variable | Default | Meaning |
+|----------|---------|---------|
+| `CLAUDE_DESKTOP_DISPLAY` | `:1` | X display of headed reauth Chrome |
+| `DESKTOP_ACT_DISPLAY` | same | desktop-act seat |
+| `CLAUDE_ROT_HEADED` | `1` | Headed browser (required for most walls) |
+| `CLAUDE_ROT_VISUAL_CAPTCHA` | `1` | Vision tile layer |
+| `CLAUDE_ROT_DESKTOP_ACT` | `1` | desktop-act `act` layer |
+| `CLAUDE_ROT_VNC_AGENT` | `1` | Last-resort VNC computer-use |
+| `CLAUDE_ROT_CAPTCHA_MAX_ATTEMPTS` | `4` | Per-page solver budget |
+| `CRS_CAPTCHA_BROWSER_WAIT_MS` | `8000` | Residential wait before paid solvers |
+| `CLAUDE_ROT_SKIP_TOKEN_SOLVERS` | `0` | Debug only; autoloop clears sticky `1` |
+| `CRS_MAGIC_LINK_DISPATCH` | `setup` | `setup` or `magic-link` |
+| `CRS_MAGIC_LINK_ROTATE_TIMEOUT_MS` | `1200000` | Child wall-clock (20m) |
+| `DESKTOP_ACT_CLI` | auto | Path to desktop-act CLI if not on `PATH` |
+| `DESKTOP_ACT_HOME` / `DESKTOP_ACT_VENV` | — | Optional install roots |
+| `CLAUDE_PLUGIN_ROOT` | installer | Plugin root (never hardcode) |
+| `CLAUDE_PLUGIN_DATA_DIR` | installer | Plugin data root |
+
+## Background run
+
+```bash
+export CLAUDE_PLUGIN_ROOT=/path/to/claude-ops # or rely on installer
+export CRS_ENABLE_MAGIC_LINK=1
+export CLAUDE_DESKTOP_DISPLAY=:1
+export CLAUDE_ROT_HEADED=1
+# optional: forks with magic-link + captcha cascade in rotate.mjs
+# export CRS_MAGIC_LINK_DISPATCH=magic-link
+
+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"
+```
+
+## Anti-patterns
+
+- Spawning multiple agent sessions each running `rotate.mjs --magic-link --to …`
+- Leaving `CLAUDE_ROT_SKIP_TOKEN_SOLVERS=1` in the unit environment permanently
+- Pointing desktop-act at a **pool** display while reauth Chrome is on another seat
+- Treating captcha markers as "page a human" instead of autoloop retry
diff --git a/claude-ops/scripts/account-rotation/__tests__/reauth-env.test.mjs b/claude-ops/scripts/account-rotation/__tests__/reauth-env.test.mjs
new file mode 100644
index 00000000..8ba8b437
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/__tests__/reauth-env.test.mjs
@@ -0,0 +1,60 @@
+/**
+ * Portable reauth-env unit tests (no network, no real accounts).
+ */
+import {
+ resolveReauthDisplay,
+ resolveReauthPath,
+ buildReauthChildEnv,
+ resolveReauthTimeoutMs,
+ reauthOutputLooksSuccessful,
+} from '../reauth-env.mjs';
+
+function assert(cond, msg) {
+ if (!cond) throw new Error(msg || 'assert failed');
+}
+
+// display priority
+assert(resolveReauthDisplay({}) === ':1', 'default display');
+assert(resolveReauthDisplay({ CLAUDE_DESKTOP_DISPLAY: ':3' }) === ':3', 'desktop display wins');
+assert(
+ resolveReauthDisplay({ DISPLAY: ':9', CLAUDE_DESKTOP_DISPLAY: ':2' }) === ':2',
+ 'CLAUDE_DESKTOP_DISPLAY over DISPLAY',
+);
+
+// path includes home .local/bin when HOME set
+const p = resolveReauthPath({ HOME: '/tmp/fakehome', PATH: '/usr/bin' });
+assert(p.includes('/tmp/fakehome/.local/bin'), 'local bin first');
+assert(p.includes('/usr/bin'), 'keeps system path');
+
+// child env
+const env = buildReauthChildEnv({
+ env: {
+ HOME: '/tmp/fakehome',
+ PATH: '/usr/bin',
+ CLAUDE_DESKTOP_DISPLAY: ':5',
+ },
+ crs: {},
+});
+assert(env.CLAUDE_ROT_HEADED === '1', 'headed default');
+assert(env.CLAUDE_DESKTOP_DISPLAY === ':5', 'seat');
+assert(env.DESKTOP_ACT_DISPLAY === ':5', 'desktop-act seat');
+assert(env.CLAUDE_ROT_STEAL_LOCK === '0', 'no steal');
+assert(env.CLAUDE_ROT_SKIP_TOKEN_SOLVERS === '0', 'solvers on');
+assert(env.CRS_MAGIC_LINK_DISPATCH === 'setup', 'default dispatch');
+
+const magic = buildReauthChildEnv({
+ env: { CRS_MAGIC_LINK_DISPATCH: 'magic-link', HOME: '/tmp/x', PATH: '/bin' },
+});
+assert(magic.CRS_MAGIC_LINK_DISPATCH === 'magic-link', 'dispatch override');
+
+// timeout
+assert(resolveReauthTimeoutMs({}) === 20 * 60_000, 'default 20m');
+assert(resolveReauthTimeoutMs({ CRS_MAGIC_LINK_ROTATE_TIMEOUT_MS: '90000' }) === 90000, 'env timeout');
+
+// success markers
+assert(reauthOutputLooksSuccessful('{"ok": true}'), 'json ok');
+assert(reauthOutputLooksSuccessful('Saved token to vault: [email protected]'), 'vault save');
+assert(!reauthOutputLooksSuccessful('FATAL: boom'), 'fatal');
+assert(!reauthOutputLooksSuccessful('Timed out waiting for login email'), 'timeout fail');
+
+console.log('reauth-env.test.mjs: ok');
diff --git a/claude-ops/scripts/account-rotation/config.example.json b/claude-ops/scripts/account-rotation/config.example.json
index c059927c..0657f57f 100644
--- a/claude-ops/scripts/account-rotation/config.example.json
+++ b/claude-ops/scripts/account-rotation/config.example.json
@@ -67,8 +67,14 @@
"tokenRefreshWindowMs": 1800000,
"_tokenRefreshWindowMs_note": "Refresh an account's token once it's within this many ms of expiry (default 30m).",
"enableMagicLinkRecovery": false,
- "_enableMagicLinkRecovery_note": "Off by default (or $CRS_ENABLE_MAGIC_LINK=1). Turns on magic-link-autoloop.mjs, which dispatches an UNATTENDED browser-based re-auth (rotate.mjs --setup --auto) for ONE account per tick that crs-401-refresher.mjs (or, if that's disabled, a direct vault check) has flagged as needing reauth — i.e. a confirmed dead refresh_token, not just an expiring one. Serial, single-flight, and skips entirely if a manual rotation is already in progress. Uses the same Gmail-via-gog flow /ops:rotate-setup already uses; nothing account-specific is hardcoded. Leave off if you'd rather a human always handles re-auth.",
+ "_enableMagicLinkRecovery_note": "Off by default (or $CRS_ENABLE_MAGIC_LINK=1). Turns on magic-link-autoloop.mjs, which dispatches an UNATTENDED browser-based re-auth for ONE account per tick that crs-401-refresher.mjs (or, if that's disabled, a direct vault check) has flagged as needing reauth — i.e. a confirmed dead refresh_token, not just an expiring one. Serial, single-flight, and skips entirely if a rotation is already in progress. Nothing account-specific is hardcoded. Leave off if re-auth should always be manual.",
"magicLinkRetryCooldownMs": 21600000,
- "_magicLinkRetryCooldownMs_note": "Minimum time between unattended retry attempts for the SAME account, success or failure, so a persistently-broken account isn't retried in a tight loop (default 6h)."
+ "_magicLinkRetryCooldownMs_note": "Minimum time between unattended retry attempts for the SAME account, success or failure, so a persistently-broken account isn't retried in a tight loop (default 6h).",
+ "magicLinkDispatch": "setup",
+ "_magicLinkDispatch_note": "How magic-link-autoloop invokes rotate.mjs. `setup` (default) = `--setup --only=<key> --auto --skip-valid`. `magic-link` = `--magic-link --force --allow-exhausted --to <key>` for installs whose rotate.mjs implements that path. Override with $CRS_MAGIC_LINK_DISPATCH.",
+ "magicLinkHeaded": true,
+ "_magicLinkHeaded_note": "Pass CLAUDE_ROT_HEADED=1 to the rotate child (default true). Interactive captcha walls need a headed browser on CLAUDE_DESKTOP_DISPLAY. Override with $CLAUDE_ROT_HEADED=0 only for pure headless experiments.",
+ "magicLinkRotateTimeoutMs": 1200000,
+ "_magicLinkRotateTimeoutMs_note": "Wall-clock ms before the autoloop kills a stuck rotate child (default 20m). Override with $CRS_MAGIC_LINK_ROTATE_TIMEOUT_MS. Captcha cascade (visual + desktop-act) needs more room than a pure token refresh."
}
}
diff --git a/claude-ops/scripts/account-rotation/magic-link-autoloop.mjs b/claude-ops/scripts/account-rotation/magic-link-autoloop.mjs
index c9b7c95c..6f745f1f 100644
--- a/claude-ops/scripts/account-rotation/magic-link-autoloop.mjs
+++ b/claude-ops/scripts/account-rotation/magic-link-autoloop.mjs
@@ -4,51 +4,42 @@
*
* Fills a gap crs-401-refresher.mjs deliberately leaves for a human: when an
* account's refresh_token is confirmed dead (not just expiring), the
- * refresher flags it needs-reauth and stops — someone has to log back in.
- * This reconciler, if enabled, takes that one further step: it dispatches
- * `rotate.mjs --setup --only=<key> --auto --skip-valid` (the same generic,
- * already-Gmail-via-`gog` setup flow `/ops:rotate-setup` uses) for ONE
- * needs-reauth account per tick, serially, with a per-account cooldown so a
- * genuinely broken account isn't retried in a tight loop.
+ * refresher flags it needs-reauth and stops. This reconciler, if enabled,
+ * dispatches ONE unattended browser re-auth per tick (serial, single-flight).
*
* OPT-IN. Does nothing (exits 0) unless crs.enableMagicLinkRecovery is true
* (or $CRS_ENABLE_MAGIC_LINK=1) — installing this plugin never silently
* starts unattended re-auth attempts.
*
- * Provider note: this reconciler's own logic (candidate detection, locking,
- * cooldowns) has no email-provider dependency at all — it only decides WHICH
- * account to retry and WHEN. The actual email polling happens inside
- * rotate.mjs's setup flow, which is Gmail-via-`gog` today. Making THAT
- * provider-agnostic (e.g. IMAP) is a rotate.mjs-internals change, tracked
- * separately (see AUR-1555) — this reconciler will pick up such a change for
- * free once it lands, since it only calls rotate.mjs's public --setup
- * interface and never touches its internals.
+ * Dispatch modes ($CRS_MAGIC_LINK_DISPATCH / crs.magicLinkDispatch):
+ * setup (default) — `rotate.mjs --setup --only=<key> --auto --skip-valid`
+ * magic-link — `rotate.mjs --magic-link --force --allow-exhausted --to <key>`
+ * (for forks that wire magic-link + captcha cascade in rotate.mjs)
*
- * Concurrency (hard rules, ported from a documented incident where two
- * autoloop ticks raced the same account's browser session):
+ * Concurrency (hard rules):
* 1. Single-flight lock (crs-reconciler-state.mjs) — one tick fleet-wide.
* 2. Exactly ONE account per tick, always serial.
- * 3. Skips the tick entirely (no error) if rotate.mjs's own .rotating lock
- * is held — never contends with a live manual rotation.
+ * 3. Skips the tick entirely if rotate.mjs's own .rotating lock is held —
+ * never contends with a live rotation. Agents must not spawn parallel
+ * rotate.mjs drivers for the same fleet.
*
- * CONFIG (config.json "crs" block; every key overridable by env — see
- * config.example.json for the full annotated schema):
- * enableMagicLinkRecovery default false — must be true (or
- * $CRS_ENABLE_MAGIC_LINK=1) to do anything.
- * magicLinkRetryCooldownMs default 21600000 (6h) — minimum time between
- * retry attempts for the SAME account, success
- * or failure, so a persistently-broken account
- * doesn't get hammered.
+ * Captcha / headed env: see reauth-env.mjs + CAPTCHA-CASCADE.md. All seat
+ * paths are env-templated (CLAUDE_DESKTOP_DISPLAY, DESKTOP_ACT_*, etc.).
*
- * CLI: (none)=one tick · --dry-run=log the candidate, don't dispatch · --status
+ * CLI: (none)=one tick · --dry-run · --status
*/
import { spawn } from 'child_process';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
-import { homedir, platform } from 'os';
+import { homedir } from 'os';
import { existsSync, readFileSync } from 'fs';
import { loadRotationConfig, buildCrsNameMaps, crsFileVaultPath } from './crs-pool-config.mjs';
import { loadJsonState, saveJsonStateAtomic, withOwnStateLock } from './crs-reconciler-state.mjs';
+import {
+ buildReauthChildEnv,
+ resolveReauthTimeoutMs,
+ reauthOutputLooksSuccessful,
+} from './reauth-env.mjs';
const __dirname = dirname(fileURLToPath(import.meta.url));
const args = new Set(process.argv.slice(2));
@@ -60,7 +51,9 @@ const ENABLED = process.env.CRS_ENABLE_MAGIC_LINK === '1' || C.enableMagicLinkRe
const RETRY_COOLDOWN_MS = Number(
process.env.CRS_MAGIC_LINK_RETRY_COOLDOWN_MS ?? C.magicLinkRetryCooldownMs ?? 21_600_000,
);
-const ROTATE_TIMEOUT_MS = Number(process.env.CRS_MAGIC_LINK_ROTATE_TIMEOUT_MS ?? 12 * 60_000);
+const ROTATE_TIMEOUT_MS = resolveReauthTimeoutMs(process.env, C);
+const DISPATCH =
+ process.env.CRS_MAGIC_LINK_DISPATCH || C.magicLinkDispatch || 'setup';
function expandHome(p) {
if (!p) return p;
@@ -68,8 +61,10 @@ function expandHome(p) {
}
const DEFAULT_DATA_DIR =
- process.env.CLAUDE_PLUGIN_DATA_DIR || join(homedir(), '.claude', 'plugins', 'data', 'ops-ops-marketplace');
-const STATE_DIR = expandHome(process.env.CRS_STATE_DIR || C.stateDir) || join(DEFAULT_DATA_DIR, 'account-rotation');
+ process.env.CLAUDE_PLUGIN_DATA_DIR ||
+ join(homedir(), '.claude', 'plugins', 'data', 'ops-ops-marketplace');
+const STATE_DIR =
+ expandHome(process.env.CRS_STATE_DIR || C.stateDir) || join(DEFAULT_DATA_DIR, 'account-rotation');
const STATE_PATH = join(STATE_DIR, 'crs-magic-link-state.json');
const REFRESHER_STATE_PATH = join(STATE_DIR, 'crs-401-state.json');
const ROTATE_SCRIPT = join(__dirname, 'rotate.mjs');
@@ -89,12 +84,19 @@ function pidAlive(pid) {
}
}
-/** rotate.mjs owns this lock file for any live manual/scripted rotation — never contend with it. */
+/** rotate.mjs owns this lock file for any live rotation — never contend with it. */
function rotatingLockBusy() {
if (!existsSync(ROTATING_LOCK)) return false;
try {
- const raw = readFileSync(ROTATING_LOCK, 'utf8').trim().split(/\s+/);
- const pid = parseInt(raw[1] || raw[raw.length - 1] || '0', 10) || 0;
+ const raw = readFileSync(ROTATING_LOCK, 'utf8').trim();
+ // Support both "pid …" plain text and JSON {"pid":N}
+ let pid = 0;
+ if (raw.startsWith('{')) {
+ pid = parseInt(JSON.parse(raw)?.pid || '0', 10) || 0;
+ } else {
+ const parts = raw.split(/\s+/);
+ pid = parseInt(parts[1] || parts[parts.length - 1] || '0', 10) || 0;
+ }
return pidAlive(pid);
} catch {
return false;
@@ -111,7 +113,7 @@ function needsReauthKeysFromRefresher() {
return out;
}
-/** Fallback candidate source when crs-401-refresher isn't enabled: vault expiry, generic. */
+/** Fallback when crs-401-refresher isn't enabled: vault missing refresh_token. */
function needsReauthKeysFromVault(vaultKeys) {
const cfg = loadRotationConfig();
const vaultPath = crsFileVaultPath(cfg) || join(homedir(), '.claude', '.credentials.json');
@@ -154,13 +156,33 @@ function pickCandidate(now, state) {
return eligible[0];
}
-function spawnRotateSetup(vaultKey) {
+function buildRotateArgs(vaultKey) {
+ const mode = String(DISPATCH).toLowerCase();
+ if (mode === 'magic-link' || mode === 'magic_link' || mode === 'magic') {
+ return [
+ ROTATE_SCRIPT,
+ '--magic-link',
+ '--force',
+ '--allow-exhausted',
+ '--to',
+ vaultKey,
+ ];
+ }
+ // Default public path
+ return [ROTATE_SCRIPT, '--setup', `--only=${vaultKey}`, '--auto', '--skip-valid'];
+}
+
+function spawnRotate(vaultKey) {
return new Promise((resolve) => {
- const args = [ROTATE_SCRIPT, '--setup', `--only=${vaultKey}`, '--auto', '--skip-valid'];
- log(`spawn: node ${args.join(' ')}`);
- const child = spawn(process.execPath, args, {
+ const rotateArgs = buildRotateArgs(vaultKey);
+ log(`spawn: node ${rotateArgs.join(' ')} (dispatch=${DISPATCH})`);
+ const child = spawn(process.execPath, rotateArgs, {
cwd: __dirname,
stdio: ['ignore', 'pipe', 'pipe'],
+ env: {
+ ...process.env,
+ ...buildReauthChildEnv({ env: process.env, crs: C }),
+ },
});
let out = '';
child.stdout.on('data', (d) => {
@@ -170,10 +192,15 @@ function spawnRotateSetup(vaultKey) {
out += d.toString();
});
const timer = setTimeout(() => {
- log(`timeout — killing rotate.mjs setup for ${vaultKey}`);
+ log(`timeout — killing rotate.mjs for ${vaultKey} after ${ROTATE_TIMEOUT_MS}ms`);
try {
child.kill('SIGTERM');
} catch {}
+ setTimeout(() => {
+ try {
+ child.kill('SIGKILL');
+ } catch {}
+ }, 5000);
}, ROTATE_TIMEOUT_MS);
child.on('exit', (code) => {
clearTimeout(timer);
@@ -200,24 +227,26 @@ async function tick() {
}
if (DRY) {
- log(`[dry-run] would dispatch rotate.mjs --setup for ${candidate}`);
+ log(`[dry-run] would dispatch rotate.mjs for ${candidate} (dispatch=${DISPATCH})`);
return { dispatched: false, candidate };
}
state[candidate] = { ...(state[candidate] || {}), lastAttemptAt: now };
saveJsonStateAtomic(STATE_PATH, state);
- const { code, out } = await spawnRotateSetup(candidate);
- const ok = code === 0 && /"ok"\s*:\s*true/i.test(out);
+ const { code, out } = await spawnRotate(candidate);
+ const contended = /Rotation in progress/i.test(out) && !/FATAL:/i.test(out);
+ const ok = code === 0 && reauthOutputLooksSuccessful(out) && !contended;
state[candidate] = {
...(state[candidate] || {}),
lastAttemptAt: now,
lastCode: code,
lastOkAt: ok ? now : state[candidate]?.lastOkAt,
+ lastFailClass: ok ? undefined : contended ? 'contended' : 'rotate-fail',
};
saveJsonStateAtomic(STATE_PATH, state);
- log(`done ${candidate} exit=${code} ok=${ok}`);
- return { dispatched: true, candidate, ok };
+ log(`done ${candidate} exit=${code} ok=${ok}${contended ? ' class=contended' : ''}`);
+ return { dispatched: true, candidate, ok, contended };
},
log,
);
@@ -229,7 +258,9 @@ async function tick() {
function printStatus() {
const state = loadJsonState(STATE_PATH, log);
const rows = Object.entries(state);
- console.log(`enabled=${ENABLED} retryCooldownMs=${RETRY_COOLDOWN_MS} stateDir=${STATE_DIR}`);
+ console.log(
+ `enabled=${ENABLED} dispatch=${DISPATCH} retryCooldownMs=${RETRY_COOLDOWN_MS} timeoutMs=${ROTATE_TIMEOUT_MS} stateDir=${STATE_DIR}`,
+ );
if (!rows.length) {
console.log('(no attempts recorded yet)');
return;
diff --git a/claude-ops/scripts/account-rotation/magic-link-autoloop.sh b/claude-ops/scripts/account-rotation/magic-link-autoloop.sh
index da0528d2..8696b77d 100755
--- a/claude-ops/scripts/account-rotation/magic-link-autoloop.sh
+++ b/claude-ops/scripts/account-rotation/magic-link-autoloop.sh
@@ -1,22 +1,57 @@
-#!/bin/bash
+#!/usr/bin/env bash
# magic-link-autoloop.sh — single-flight wrapper for magic-link-autoloop.mjs.
-# Invoked once-per-tick by launchd/systemd (recommended: every 600s — this
-# reconciler dispatches a real unattended re-auth attempt per tick, so it
-# should stay infrequent relative to magicLinkRetryCooldownMs).
+# Invoked by launchd/systemd (recommended: every 600s).
+#
+# Portable: resolves the plugin via $CLAUDE_PLUGIN_ROOT (installer sets this)
+# or relative to this script. No host-specific paths.
set -uo pipefail
-source "$HOME/.claude/scripts/lib/once.sh" 2>/dev/null || true
-type claude_once >/dev/null 2>&1 && { claude_once magic-link-autoloop 60 || exit 0; }
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "${SCRIPT_DIR}/../.." && pwd)}"
+export CLAUDE_PLUGIN_ROOT="$PLUGIN_ROOT"
-DIR="$HOME/.claude/scripts/account-rotation"
-LOG="$DIR/magic-link-autoloop.log"
-NODE="$(command -v node || echo /opt/homebrew/bin/node)"
+# Optional single-flight helper (present on some installs; no-op if missing)
+# shellcheck disable=SC1091
+source "${HOME:-}/.claude/scripts/lib/once.sh" 2>/dev/null || true
+if type claude_once >/dev/null 2>&1; then
+ claude_once magic-link-autoloop 60 || exit 0
+fi
+
+# Logs live under plugin data dir when available (cross-platform).
+DATA_DIR="${CLAUDE_PLUGIN_DATA_DIR:-${HOME:-}/.claude/plugins/data/ops-ops-marketplace}"
+LOG_DIR="${CRS_LOG_DIR:-$DATA_DIR/logs}"
+mkdir -p "$LOG_DIR" 2>/dev/null || true
+LOG="${MAGIC_LINK_AUTOLOOP_LOG:-$LOG_DIR/magic-link-autoloop.log}"
-export CLAUDE_PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$HOME/.claude/plugins/marketplaces/ops-marketplace/claude-ops}"
+NODE="$(command -v node || true)"
+if [[ -z "$NODE" ]]; then
+ echo "magic-link-autoloop: node is required" >&2
+ exit 1
+fi
+
+# ── Unattended reauth seat (env-templatable; override in unit/plist) ─────────
+export DISPLAY="${DISPLAY:-${CLAUDE_DESKTOP_DISPLAY:-:1}}"
+export CLAUDE_DESKTOP_DISPLAY="${CLAUDE_DESKTOP_DISPLAY:-$DISPLAY}"
+export DESKTOP_ACT_DISPLAY="${DESKTOP_ACT_DISPLAY:-$CLAUDE_DESKTOP_DISPLAY}"
+export CLAUDE_ROT_HEADED="${CLAUDE_ROT_HEADED:-1}"
+export CLAUDE_ROT_FORCE_HEADED="${CLAUDE_ROT_FORCE_HEADED:-1}"
+export CLAUDE_ROT_VISUAL_CAPTCHA="${CLAUDE_ROT_VISUAL_CAPTCHA:-1}"
+export CLAUDE_ROT_DESKTOP_ACT="${CLAUDE_ROT_DESKTOP_ACT:-1}"
+export CLAUDE_ROT_VNC_AGENT="${CLAUDE_ROT_VNC_AGENT:-1}"
+export CLAUDE_ROT_CAPTCHA_MAX_ATTEMPTS="${CLAUDE_ROT_CAPTCHA_MAX_ATTEMPTS:-4}"
+export CRS_CAPTCHA_BROWSER_WAIT_MS="${CRS_CAPTCHA_BROWSER_WAIT_MS:-8000}"
+export CRS_MAGIC_LINK_ROTATE_TIMEOUT_MS="${CRS_MAGIC_LINK_ROTATE_TIMEOUT_MS:-1200000}"
+# Clear sticky one-shot skip flags from interactive debug sessions
+if [[ "${CLAUDE_ROT_SKIP_TOKEN_SOLVERS:-0}" == "1" && "${CLAUDE_ROT_ALLOW_SKIP_TOKEN_SOLVERS:-0}" != "1" ]]; then
+ echo "magic-link-autoloop: clearing CLAUDE_ROT_SKIP_TOKEN_SOLVERS=1 (set CLAUDE_ROT_ALLOW_SKIP_TOKEN_SOLVERS=1 to keep)" >&2
+ export CLAUDE_ROT_SKIP_TOKEN_SOLVERS=0
+fi
-if [ -f "$LOG" ]; then
+if [[ -f "$LOG" ]]; then
LOGSIZE="$(stat -c%s "$LOG" 2>/dev/null || stat -f%z "$LOG" 2>/dev/null || echo 0)"
- [ "$LOGSIZE" -gt 2097152 ] && mv "$LOG" "$LOG.1"
+ if [[ "${LOGSIZE:-0}" -gt 2097152 ]]; then
+ mv "$LOG" "$LOG.1" 2>/dev/null || true
+ fi
fi
-"$NODE" "$DIR/magic-link-autoloop.mjs" >> "$LOG" 2>&1
+exec "$NODE" "$SCRIPT_DIR/magic-link-autoloop.mjs" "$@" >>"$LOG" 2>&1
diff --git a/claude-ops/scripts/account-rotation/reauth-env.mjs b/claude-ops/scripts/account-rotation/reauth-env.mjs
new file mode 100644
index 00000000..20542360
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/reauth-env.mjs
@@ -0,0 +1,142 @@
+/**
+ * Portable env builder for unattended re-auth (magic-link-autoloop → rotate.mjs).
+ *
+ * No host paths, no account emails, no operator names. Everything is driven by
+ * process.env (and optional crs.* config keys). Callers merge the returned
+ * object into child_process.spawn env.
+ *
+ * See CAPTCHA-CASCADE.md for the captcha stack contract.
+ */
+import { join } from 'path';
+import { homedir } from 'os';
+
+/**
+ * Resolve the X display used for headed reauth Chrome + desktop-act.
+ * Prefer explicit reauth seat vars over the ambient DISPLAY of a headless unit.
+ */
+export function resolveReauthDisplay(env = process.env) {
+ return (
+ env.CLAUDE_DESKTOP_DISPLAY ||
+ env.DESKTOP_ACT_DISPLAY ||
+ env.CRS_REAUTH_DISPLAY ||
+ env.DISPLAY ||
+ ':1'
+ );
+}
+
+/**
+ * Build PATH with optional user local bin, without hardcoding a home directory.
+ */
+export function resolveReauthPath(env = process.env) {
+ const home = env.HOME || homedir();
+ const localBin = home ? join(home, '.local', 'bin') : '';
+ const base =
+ env.PATH ||
+ '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin';
+ const parts = [localBin, base].filter(Boolean);
+ // de-dupe while preserving order
+ const seen = new Set();
+ const out = [];
+ for (const chunk of parts.join(':').split(':')) {
+ if (!chunk || seen.has(chunk)) continue;
+ seen.add(chunk);
+ out.push(chunk);
+ }
+ return out.join(':');
+}
+
+/**
+ * @param {object} [opts]
+ * @param {NodeJS.ProcessEnv} [opts.env]
+ * @param {Record<string, unknown>} [opts.crs] optional loadRotationConfig().crs
+ * @returns {NodeJS.ProcessEnv} env fragment to merge into spawn
+ */
+export function buildReauthChildEnv(opts = {}) {
+ const env = opts.env || process.env;
+ const crs = opts.crs || {};
+ const display = resolveReauthDisplay(env);
+
+ // Dispatch mode: public plugin default is rotate --setup; forks may set magic-link.
+ const dispatch =
+ env.CRS_MAGIC_LINK_DISPATCH ||
+ crs.magicLinkDispatch ||
+ 'setup';
+
+ const headed =
+ env.CLAUDE_ROT_HEADED ||
+ (String(crs.magicLinkHeaded ?? '1') === '0' ? '0' : '1');
+
+ const fragment = {
+ CLAUDE_ROTATION_MAGIC_LINK_AUTO: '1',
+ CLAUDE_ROT_STEAL_LOCK: '0',
+ CRS_MAGIC_LINK_DISPATCH: String(dispatch),
+
+ // Seat for headed Chrome + desktop-act (must match reauth browser DISPLAY)
+ DISPLAY: display,
+ CLAUDE_DESKTOP_DISPLAY: display,
+ DESKTOP_ACT_DISPLAY: display,
+
+ // Headed browser is required for interactive captcha walls on most seats
+ CLAUDE_ROT_HEADED: headed,
+ CLAUDE_ROT_FORCE_HEADED:
+ env.CLAUDE_ROT_FORCE_HEADED || (headed === '1' ? '1' : '0'),
+
+ // Captcha cascade (no-op if rotate.mjs lacks captcha helpers)
+ CLAUDE_ROT_VISUAL_CAPTCHA: env.CLAUDE_ROT_VISUAL_CAPTCHA || '1',
+ CLAUDE_ROT_DESKTOP_ACT: env.CLAUDE_ROT_DESKTOP_ACT || '1',
+ CLAUDE_ROT_VNC_AGENT: env.CLAUDE_ROT_VNC_AGENT || '1',
+ CLAUDE_ROT_CAPTCHA_MAX_ATTEMPTS: env.CLAUDE_ROT_CAPTCHA_MAX_ATTEMPTS || '4',
+ CRS_CAPTCHA_BROWSER_WAIT_MS: env.CRS_CAPTCHA_BROWSER_WAIT_MS || '8000',
+ // Never leave a one-shot "skip solvers" flag sticky in the reconciler env
+ CLAUDE_ROT_SKIP_TOKEN_SOLVERS: env.CLAUDE_ROT_SKIP_TOKEN_SOLVERS || '0',
+
+ PATH: resolveReauthPath(env),
+ };
+
+ // Optional desktop-act install roots (portable; only set when provided)
+ for (const key of [
+ 'DESKTOP_ACT_CLI',
+ 'DESKTOP_ACT_HOME',
+ 'DESKTOP_ACT_VENV',
+ 'DESKTOP_ACT_COMMAND',
+ 'DESKTOP_ACT_CAPTCHA_TIMEOUT',
+ 'DESKTOP_ACT_MAX_ITERATIONS',
+ 'CLAUDE_PLUGIN_ROOT',
+ 'CLAUDE_PLUGIN_DATA_DIR',
+ 'CRS_REAUTH_CDP_PORT',
+ ]) {
+ if (env[key]) fragment[key] = env[key];
+ }
+
+ return fragment;
+}
+
+/**
+ * Wall-clock budget for one unattended reauth child.
+ * Longer than a pure token refresh: visual + desktop-act layers need room.
+ */
+export function resolveReauthTimeoutMs(env = process.env, crs = {}) {
+ return Number(
+ env.CRS_MAGIC_LINK_ROTATE_TIMEOUT_MS ??
+ env.CRS_MAGIC_LOOP_ROTATE_TIMEOUT_MS ??
+ crs.magicLinkRotateTimeoutMs ??
+ 20 * 60_000,
+ );
+}
+
+/**
+ * Success markers for unattended reauth stdout (setup JSON or magic-link logs).
+ * Keep provider-agnostic; no account emails.
+ */
+export function reauthOutputLooksSuccessful(out = '') {
+ const text = String(out || '');
+ if (/FATAL:|Authorize button still not clickable|Cloudflare challenge|security verification|Timed out waiting for login email/i.test(text)) {
+ return false;
+ }
+ return (
+ /"ok"\s*:\s*true/i.test(text) ||
+ /authorized|propagat|VERIFIED|OAuth complete|token refreshed|refresh.?ok|Saved token to vault|needsReauth cleared/i.test(
+ text,
+ )
+ );
+}
diff --git a/claude-ops/templates/com.claude-ops.magic-link-autoloop.plist b/claude-ops/templates/com.claude-ops.magic-link-autoloop.plist
index 01d7059f..fc5e91ca 100644
--- a/claude-ops/templates/com.claude-ops.magic-link-autoloop.plist
+++ b/claude-ops/templates/com.claude-ops.magic-link-autoloop.plist
@@ -47,6 +47,23 @@
<string>__HOME__</string>
<key>NODE_NO_WARNINGS</key>
<string>1</string>
+ <!-- Unattended reauth seat (override per host via unit drop-in if needed) -->
+ <key>CLAUDE_ROT_HEADED</key>
+ <string>1</string>
+ <key>CLAUDE_DESKTOP_DISPLAY</key>
+ <string>:1</string>
+ <key>DESKTOP_ACT_DISPLAY</key>
+ <string>:1</string>
+ <key>CLAUDE_ROT_VISUAL_CAPTCHA</key>
+ <string>1</string>
+ <key>CLAUDE_ROT_DESKTOP_ACT</key>
+ <string>1</string>
+ <key>CLAUDE_ROT_VNC_AGENT</key>
+ <string>1</string>
+ <key>CRS_MAGIC_LINK_ROTATE_TIMEOUT_MS</key>
+ <string>1200000</string>
+ <key>CLAUDE_ROT_SKIP_TOKEN_SOLVERS</key>
+ <string>0</string>
</dict>
<key>ProcessType</key>