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: CRS routing guardrails for Mac/FRA account rotation (#629)

Aurora Capital0ff1f2893c01
diff --git a/claude-ops/bin/claude-stack b/claude-ops/bin/claude-stack
new file mode 100755
index 00000000..ec7f8252
--- /dev/null
+++ b/claude-ops/bin/claude-stack
@@ -0,0 +1,5 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
+exec node "$ROOT/scripts/account-rotation/claude-stack.mjs" "$@"
diff --git a/claude-ops/hooks/bedrock-fallback-guard.mjs b/claude-ops/hooks/bedrock-fallback-guard.mjs
new file mode 100644
index 00000000..5daabbf1
--- /dev/null
+++ b/claude-ops/hooks/bedrock-fallback-guard.mjs
@@ -0,0 +1,40 @@
+#!/usr/bin/env node
+import { routeStatus } from '../scripts/account-rotation/route-state.mjs';
+
+function block(reason) {
+ console.log(
+ JSON.stringify({
+ decision: 'block',
+ reason,
+ }),
+ );
+ process.exit(2);
+}
+
+try {
+ const status = routeStatus();
+ const settings = status.settings;
+ const route = status.state;
+
+ if (settings.mixedProvider) {
+ block(
+ 'Claude routing is unsafe: settings.json has both Bedrock and CRS/OAuth enabled. Run `claude-stack route --mode crs-oauth` or explicitly confirm Bedrock with `claude-stack route --mode bedrock-confirmed --confirm-metered-bedrock --reason "<reason>"`.',
+ );
+ }
+
+ if (settings.bedrock && (route.mode !== 'bedrock-confirmed' || !status.bedrockConfirmationActive)) {
+ block(
+ 'Bedrock fallback blocked. Bedrock is metered AWS usage, and OAuth/CRS is unavailable or not selected. Confirm only for this session with `claude-stack route --mode bedrock-confirmed --reason "<why OAuth is unavailable>" --ttl-minutes 60 --confirm-metered-bedrock`, or restore OAuth with `claude-stack route --mode crs-oauth`.',
+ );
+ }
+
+ if (route.mode === 'fail-closed') {
+ block(
+ `Claude routing is fail-closed: ${route.reason || 'CRS OAuth is unavailable and Bedrock has not been explicitly confirmed'}. Run \`claude-stack doctor --json\` for current CRS/account status.`,
+ );
+ }
+
+ console.log(JSON.stringify({ suppressOutput: true }));
+} catch (e) {
+ block(`Claude routing guard failed closed: ${e.message || String(e)}`);
+}
diff --git a/claude-ops/hooks/hooks.json b/claude-ops/hooks/hooks.json
index b8b2e663..f049af49 100644
--- a/claude-ops/hooks/hooks.json
+++ b/claude-ops/hooks/hooks.json
@@ -3,6 +3,10 @@
"UserPromptSubmit": [
{
"hooks": [
+ {
+ "type": "command",
+ "command": "node ${CLAUDE_PLUGIN_ROOT}/hooks/bedrock-fallback-guard.mjs"
+ },
{
"type": "command",
"command": "bash ${CLAUDE_PLUGIN_ROOT}/bin/ops-inbox-autosync 2>/dev/null || true",
diff --git a/claude-ops/scripts/account-rotation/claude-stack.mjs b/claude-ops/scripts/account-rotation/claude-stack.mjs
new file mode 100644
index 00000000..4d008a45
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/claude-stack.mjs
@@ -0,0 +1,253 @@
+#!/usr/bin/env node
+import { execFileSync } from 'child_process';
+import { existsSync, readFileSync } from 'fs';
+import { join } from 'path';
+import { homedir } from 'os';
+import { applyRouteToSettings, routeStatus, setRouteMode } from './route-state.mjs';
+
+const args = process.argv.slice(2);
+const command = args[0] || 'status';
+
+function has(flag) {
+ return args.includes(flag);
+}
+
+function valueOf(flag, fallback = '') {
+ const idx = args.indexOf(flag);
+ return idx >= 0 ? args[idx + 1] || fallback : fallback;
+}
+
+function printJson(data) {
+ console.log(JSON.stringify(data, null, 2));
+}
+
+function curlOk(url, timeoutSeconds = 3) {
+ try {
+ const code = execFileSync(
+ 'curl',
+ ['-sf', '-o', '/dev/null', '-w', '%{http_code}', '--max-time', String(timeoutSeconds), url],
+ {
+ encoding: 'utf8',
+ timeout: (timeoutSeconds + 2) * 1000,
+ },
+ ).trim();
+ return code === '200';
+ } catch {
+ return false;
+ }
+}
+
+function launchctlStatus(label) {
+ if (process.platform !== 'darwin') return { loaded: false, skipped: 'launchd unavailable on this platform' };
+ try {
+ const out = execFileSync('launchctl', ['print', `gui/${process.getuid()}/${label}`], {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ timeout: 3000,
+ maxBuffer: 512 * 1024,
+ });
+ const pid = out.match(/pid = (\d+)/)?.[1] || null;
+ const lastExitStatus = out.match(/last exit code = (-?\d+)/)?.[1] || null;
+ return { loaded: true, pid, lastExitStatus };
+ } catch (e) {
+ return { loaded: false, error: (e.message || String(e)).slice(0, 160) };
+ }
+}
+
+function systemdUserStatus(unit) {
+ if (process.platform === 'darwin') return { loaded: false, skipped: 'systemd unavailable on this platform' };
+ try {
+ const active = execFileSync('systemctl', ['--user', 'is-active', unit], {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ timeout: 3000,
+ }).trim();
+ const enabled = execFileSync('systemctl', ['--user', 'is-enabled', unit], {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ timeout: 3000,
+ }).trim();
+ return { loaded: true, active, enabled };
+ } catch (e) {
+ return { loaded: false, error: (e.message || String(e)).slice(0, 160) };
+ }
+}
+
+function dockerStatus() {
+ try {
+ execFileSync('docker', ['info'], { stdio: 'pipe', timeout: 5000 });
+ return { ok: true };
+ } catch (e) {
+ return { ok: false, error: (e.message || String(e)).slice(0, 160) };
+ }
+}
+
+function accountRotationStatus() {
+ const statePath = join(homedir(), '.claude', 'scripts', 'account-rotation', 'state.json');
+ try {
+ const state = JSON.parse(readFileSync(statePath, 'utf8'));
+ return {
+ statePath,
+ activeAccount: state.activeAccount || null,
+ accountCount: state.accounts && typeof state.accounts === 'object' ? Object.keys(state.accounts).length : 0,
+ totalRotations: state.totalRotations || 0,
+ };
+ } catch (e) {
+ return { statePath, error: (e.message || String(e)).slice(0, 160) };
+ }
+}
+
+function status() {
+ const route = routeStatus();
+ const crsHealthUrl = route.state.crs?.healthUrl || 'http://127.0.0.1:3000/health';
+ return {
+ ok: !route.settings.mixedProvider,
+ route,
+ crs: {
+ healthUrl: crsHealthUrl,
+ healthy: curlOk(crsHealthUrl),
+ },
+ docker: dockerStatus(),
+ launchd: {
+ accountRotation: launchctlStatus('com.claude-ops.account-rotation'),
+ crsHealthWatch: launchctlStatus('com.claude-ops.crs-health-watch'),
+ crsPriority: launchctlStatus('com.claude-ops.crs-priority'),
+ crsFraTunnel: launchctlStatus('com.claude-ops.crs-fra-tunnel'),
+ opsDaemon: launchctlStatus('com.claude-ops.daemon'),
+ },
+ systemd: {
+ crsCompose: systemdUserStatus('crs-compose.service'),
+ crsTokenFeed: systemdUserStatus('crs-token-feed.service'),
+ crsBedrockGuard: systemdUserStatus('crs-bedrock-guard.service'),
+ crsTokenFeedTimer: systemdUserStatus('crs-token-feed.timer'),
+ crsBedrockGuardTimer: systemdUserStatus('crs-bedrock-guard.timer'),
+ claudeAccountRotation: systemdUserStatus('claude-account-rotation.service'),
+ },
+ accounts: accountRotationStatus(),
+ };
+}
+
+function doctor() {
+ const s = status();
+ const findings = [];
+ const fraPrimary = s.route.state.crs?.authority === 'fra-primary';
+ if (s.route.settings.mixedProvider)
+ findings.push({
+ severity: 'error',
+ code: 'mixed_provider_env',
+ detail: 'settings.json has both Bedrock and CRS/OAuth env',
+ });
+ if (s.route.state.mode === 'crs-oauth' && !s.crs.healthy)
+ findings.push({ severity: 'error', code: 'crs_unhealthy', detail: `${s.crs.healthUrl} is not healthy` });
+ if (s.route.state.mode === 'bedrock-confirmed' && !s.route.bedrockConfirmationActive)
+ findings.push({
+ severity: 'error',
+ code: 'bedrock_confirmation_expired',
+ detail: 'Bedrock route lacks active TTL confirmation',
+ });
+ if (!s.docker.ok) findings.push({ severity: 'warn', code: 'docker_unavailable', detail: s.docker.error });
+ if (process.platform === 'darwin') {
+ if (!fraPrimary && !s.launchd.accountRotation.loaded)
+ findings.push({ severity: 'warn', code: 'account_rotation_not_loaded', detail: s.launchd.accountRotation.error });
+ if (!s.launchd.crsHealthWatch.loaded)
+ findings.push({ severity: 'warn', code: 'crs_health_watch_not_loaded', detail: s.launchd.crsHealthWatch.error });
+ if (fraPrimary && !s.launchd.crsFraTunnel.loaded)
+ findings.push({ severity: 'error', code: 'crs_fra_tunnel_not_loaded', detail: s.launchd.crsFraTunnel.error });
+ } else {
+ if (s.systemd.crsCompose.active !== 'active')
+ findings.push({
+ severity: 'error',
+ code: 'crs_compose_not_active',
+ detail: s.systemd.crsCompose.error || s.systemd.crsCompose.active,
+ });
+ if (s.systemd.crsTokenFeedTimer.active !== 'active')
+ findings.push({
+ severity: 'warn',
+ code: 'crs_token_feed_timer_not_active',
+ detail: s.systemd.crsTokenFeedTimer.error || s.systemd.crsTokenFeedTimer.active,
+ });
+ if (s.systemd.crsBedrockGuardTimer.active !== 'active')
+ findings.push({
+ severity: 'warn',
+ code: 'crs_bedrock_guard_timer_not_active',
+ detail: s.systemd.crsBedrockGuardTimer.error || s.systemd.crsBedrockGuardTimer.active,
+ });
+ if (s.systemd.claudeAccountRotation.active !== 'active')
+ findings.push({
+ severity: 'warn',
+ code: 'claude_account_rotation_not_active',
+ detail: s.systemd.claudeAccountRotation.error || s.systemd.claudeAccountRotation.active,
+ });
+ }
+ return { ...s, ok: findings.every((f) => f.severity !== 'error'), findings };
+}
+
+function opsUpdate() {
+ const candidates = [
+ join(homedir(), '.claude', 'plugins', 'cache', 'ops-marketplace', 'ops', 'latest', 'scripts', 'ops-update.sh'),
+ join(homedir(), '.claude', 'plugins', 'cache', 'ops-marketplace', 'ops-update.sh'),
+ join(homedir(), '.claude', 'scripts', 'ops-merge-tick.sh'),
+ ];
+ const script = candidates.find((p) => existsSync(p));
+ if (!script) {
+ printJson({ ok: false, error: 'no ops-update runner found', candidates });
+ process.exitCode = 1;
+ return;
+ }
+ try {
+ const out = execFileSync(script, [], { encoding: 'utf8', timeout: 30 * 60_000, maxBuffer: 16 * 1024 * 1024 });
+ printJson({ ok: true, script, output: out.slice(-8000) });
+ } catch (e) {
+ printJson({
+ ok: false,
+ script,
+ error: (e.message || String(e)).slice(0, 1000),
+ output: e.stdout?.toString?.().slice(-8000) || '',
+ });
+ process.exitCode = 1;
+ }
+}
+
+try {
+ if (command === 'status') {
+ printJson(status());
+ } else if (command === 'doctor') {
+ const result = doctor();
+ printJson(result);
+ if (!result.ok) process.exitCode = 1;
+ } else if (command === 'route') {
+ const mode = valueOf('--mode');
+ const reason = valueOf('--reason', 'manual');
+ const ttlMinutes = Number.parseInt(valueOf('--ttl-minutes', '60'), 10);
+ const baseUrl = valueOf('--base-url');
+ const healthUrl = valueOf('--health-url');
+ const crs =
+ baseUrl || healthUrl
+ ? {
+ ...routeStatus().state.crs,
+ ...(baseUrl ? { baseUrl } : {}),
+ ...(healthUrl ? { healthUrl } : {}),
+ }
+ : undefined;
+ const state = setRouteMode(mode, {
+ reason,
+ ttlMinutes: Number.isFinite(ttlMinutes) ? ttlMinutes : 60,
+ confirmMetered: has('--confirm-metered-bedrock'),
+ region: valueOf('--region', process.env.AWS_BEDROCK_REGION || 'us-east-1'),
+ updatedBy: 'claude-stack',
+ ...(crs ? { crs } : {}),
+ });
+ printJson({ ok: true, state, settings: routeStatus().settings });
+ } else if (command === 'apply') {
+ applyRouteToSettings();
+ printJson({ ok: true, route: routeStatus() });
+ } else if (command === 'ops-update') {
+ opsUpdate();
+ } else {
+ printJson({ ok: false, error: `unknown command: ${command}` });
+ process.exitCode = 2;
+ }
+} catch (e) {
+ printJson({ ok: false, error: e.message || String(e) });
+ process.exitCode = 1;
+}
diff --git a/claude-ops/scripts/account-rotation/crs-bedrock-guard.mjs b/claude-ops/scripts/account-rotation/crs-bedrock-guard.mjs
new file mode 100644
index 00000000..eb23d244
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/crs-bedrock-guard.mjs
@@ -0,0 +1,116 @@
+#!/usr/bin/env node
+/**
+ * crs-bedrock-guard.mjs — WARN when the CRS relay actually serves via the
+ * bedrock-fallback account (i.e. the OAuth Max pool got exhausted and CRS fell
+ * back to paid AWS Bedrock). App-level signal: polls the bedrock-fallback
+ * account's usage.total.requests and alerts when it climbs.
+ *
+ * Pairs with the network-level bedrock-net-monitor (catches Bedrock from ANY
+ * source). Runs via crs-bedrock-guard.timer (every 5 min).
+ */
+import { readFileSync, writeFileSync, renameSync, appendFileSync, mkdirSync } from 'fs';
+import { execSync, spawnSync } from 'child_process';
+import { join } from 'path';
+
+const HOME = process.env.HOME;
+const CRS = 'http://127.0.0.1:3005';
+const STATE = join(HOME, '.claude', '.crs-bedrock-guard-state.json');
+const ALERT = join(HOME, '.claude', '.bedrock-alert.json');
+const LOGDIR = join(HOME, '.claude', 'logs');
+const LOG = join(LOGDIR, 'bedrock-alerts.log');
+
+function log(m) {
+ try {
+ mkdirSync(LOGDIR, { recursive: true });
+ appendFileSync(LOG, `[${new Date().toISOString()}] [crs-guard] ${m}\n`);
+ } catch {}
+ console.log(m);
+}
+function loadState() {
+ try {
+ return JSON.parse(readFileSync(STATE, 'utf8'));
+ } catch {
+ return {};
+ }
+}
+function saveState(s) {
+ const t = `${STATE}.tmp.${process.pid}`;
+ writeFileSync(t, JSON.stringify(s, null, 2));
+ renameSync(t, STATE);
+}
+
+function alert(payload) {
+ try {
+ const t = `${ALERT}.tmp.${process.pid}`;
+ writeFileSync(t, JSON.stringify(payload, null, 2));
+ renameSync(t, ALERT);
+ } catch {}
+ log(`🚨 ALERT: ${payload.message}`);
+ try {
+ spawnSync('notify-send', ['-u', 'critical', '🚨 CRS→Bedrock fallback', payload.message], { timeout: 3000 });
+ } catch {}
+}
+
+async function main() {
+ let pw = '';
+ try {
+ pw = execSync(
+ `docker inspect crs-claude-relay-1 --format '{{range .Config.Env}}{{println .}}{{end}}' | sed -n 's/^ADMIN_PASSWORD=//p'`,
+ { timeout: 8000 },
+ )
+ .toString()
+ .trim();
+ } catch {}
+ if (!pw) {
+ log('CRS not reachable (no admin pw) — skip');
+ return;
+ }
+ const login = await fetch(`${CRS}/web/auth/login`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ username: 'cradmin', password: pw }),
+ })
+ .then((r) => r.json())
+ .catch(() => ({}));
+ const tok = login.token || login.data?.token;
+ if (!tok) {
+ log('CRS login failed — skip');
+ return;
+ }
+ const resp = await fetch(`${CRS}/admin/bedrock-accounts`, { headers: { Authorization: `Bearer ${tok}` } })
+ .then((r) => r.json())
+ .catch(() => ({}));
+ const accts = resp.data || resp.accounts || resp || [];
+ const be = (Array.isArray(accts) ? accts : []).find((a) => a.platform === 'bedrock' || a.type === 'bedrock');
+ if (!be) {
+ log('no bedrock account registered — skip');
+ return;
+ }
+
+ const totalReq = be.usage?.total?.requests ?? 0;
+ const dailyReq = be.usage?.daily?.requests ?? 0;
+ const dailyCost = be.usage?.daily?.cost ?? 0;
+ const st = loadState();
+ const prev = st.totalRequests ?? 0;
+
+ if (totalReq > prev) {
+ const delta = totalReq - prev;
+ alert({
+ ts: new Date().toISOString(),
+ source: 'crs-pool-fallback',
+ account: be.name,
+ message: `CRS served ${delta} request(s) via AWS Bedrock fallback (OAuth pool was exhausted). total=${totalReq}, today=${dailyReq} req / $${dailyCost}. Check why the 10-account Max pool ran dry.`,
+ deltaRequests: delta,
+ totalRequests: totalReq,
+ dailyRequests: dailyReq,
+ dailyCost,
+ });
+ } else {
+ log(`ok — bedrock total=${totalReq} (no new fallback traffic)`);
+ }
+ saveState({ totalRequests: totalReq, lastCheck: new Date().toISOString() });
+}
+main().catch((e) => {
+ log(`fatal: ${e.message}`);
+ process.exit(1);
+});
diff --git a/claude-ops/scripts/account-rotation/crs-health-watch.mjs b/claude-ops/scripts/account-rotation/crs-health-watch.mjs
new file mode 100644
index 00000000..1037e669
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/crs-health-watch.mjs
@@ -0,0 +1,249 @@
+#!/usr/bin/env node
+// crs-health-watch.mjs — fleet-level CRS failsafe (single tick; launchd-driven).
+//
+// PROBLEM: the global CRS default lives in ~/.claude/settings.json `env`
+// (ANTHROPIC_BASE_URL=CRS + CLAUDE_CODE_OAUTH_TOKEN=cr_…). settings.json env is
+// applied at `claude` startup and OVERRIDES any childEnv a respawn sets — so the
+// per-session health-gate in bg-respawn.mjs CANNOT protect new/respawned sessions
+// when the relay is down: they'd boot with base=CRS pointing at a dead upstream and
+// wedge on connection errors. This watch is the authority over settings.json.
+//
+// POLICY (hysteresis, no flap):
+// • Probe the health URL from claude-routing-state each tick.
+// • DOWN for DOWN_STRIKES consecutive ticks → FALLBACK: strip the two CRS env keys
+// from settings.json (new/respawned sessions go direct keychain auth). Drop a
+// marker so we know we're in fallback.
+// • UP for UP_STRIKES consecutive ticks while in fallback → RESTORE: re-add the two
+// CRS env keys. Clear the marker.
+// • Otherwise hold. State (counters + mode) persisted to crs-health-watch.state.json.
+//
+// It NEVER force-respawns running sessions (avoids thrash). It only flips the global
+// default so the fleet self-heals to direct on the next respawn/new session, and back
+// to CRS once the relay is solidly up. Manual rollback is independent (see status doc).
+//
+// CLI: (none)=tick · --status=print mode+counters+current env state · --restore=force
+// restore CRS env now · --fallback=force fail-closed mode now.
+
+import { readFileSync, writeFileSync, existsSync } from 'fs';
+import { execFileSync } from 'child_process';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+import { homedir } from 'os';
+import { applyRouteToSettings, readRouteState, setRouteMode } from './route-state.mjs';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const args = new Set(process.argv.slice(2));
+
+const SETTINGS = join(homedir(), '.claude', 'settings.json');
+const STATE = join(__dirname, 'crs-health-watch.state.json');
+const MARKER = join(__dirname, 'crs-fallback-active'); // legacy marker present while route is fail-closed
+
+function routeCrsConfig() {
+ try {
+ return readRouteState().crs || {};
+ } catch {
+ return {};
+ }
+}
+
+const ROUTE_CRS = routeCrsConfig();
+const CRS_BASE = process.env.CRS_BASE_URL || ROUTE_CRS.baseUrl || 'http://127.0.0.1:3000/api';
+const HEALTH_URL = process.env.CRS_HEALTH_URL || ROUTE_CRS.healthUrl || CRS_BASE.replace(/\/api\/?$/, '/health');
+const CRS_SMOKE_URL = process.env.CRS_SMOKE_URL || `${CRS_BASE}/v1/messages?beta=true`;
+const CRS_SMOKE_MODEL = process.env.CRS_SMOKE_MODEL || 'claude-sonnet-4-6';
+const DOWN_STRIKES = +(process.env.CRS_DOWN_STRIKES || 3); // ~3 min at 60s tick
+const UP_STRIKES = +(process.env.CRS_UP_STRIKES || 3);
+
+const ts = () => new Date().toISOString().slice(11, 19);
+const log = (m) => console.log(`${ts()} [crs-health-watch] ${m}`);
+
+function readJson(p, d) {
+ try {
+ return JSON.parse(readFileSync(p, 'utf8'));
+ } catch {
+ return d;
+ }
+}
+function loadState() {
+ return readJson(STATE, { down: 0, up: 0, mode: 'crs' });
+}
+function saveState(s) {
+ try {
+ writeFileSync(STATE, JSON.stringify(s, null, 2));
+ } catch (e) {
+ log(`state write failed: ${e.message}`);
+ }
+}
+
+function probe() {
+ try {
+ const code = execFileSync('curl', ['-sf', '-o', '/dev/null', '-w', '%{http_code}', '--max-time', '3', HEALTH_URL], {
+ encoding: 'utf8',
+ timeout: 5000,
+ }).trim();
+ return code === '200';
+ } catch {
+ return false;
+ }
+}
+
+function probeInference() {
+ let key = '';
+ try {
+ key = readFileSync(join(__dirname, '.crkey'), 'utf8').trim();
+ } catch {}
+ if (!key.startsWith('cr_')) return false;
+ const body = JSON.stringify({
+ model: CRS_SMOKE_MODEL,
+ max_tokens: 1,
+ stream: false,
+ messages: [{ role: 'user', content: 'ping' }],
+ });
+ try {
+ const code = execFileSync(
+ 'curl',
+ [
+ '-sS',
+ '-o',
+ '/dev/null',
+ '-w',
+ '%{http_code}',
+ '--max-time',
+ '25',
+ '-H',
+ `Authorization: Bearer ${key}`,
+ '-H',
+ 'Content-Type: application/json',
+ '-H',
+ 'anthropic-version: 2023-06-01',
+ '-d',
+ body,
+ CRS_SMOKE_URL,
+ ],
+ { encoding: 'utf8', timeout: 30_000 },
+ ).trim();
+ // 529 means CRS selected a valid account and reached Anthropic, but the
+ // upstream is temporarily overloaded. That is not a CRS auth/routing fault.
+ return /^2\d\d$/.test(code) || code === '529';
+ } catch {
+ return false;
+ }
+}
+
+function setEnvMode(mode) {
+ try {
+ if (mode === 'direct') {
+ setRouteMode('fail-closed', { reason: 'crs-health-watch: CRS unavailable', updatedBy: 'crs-health-watch' });
+ } else {
+ setRouteMode('crs-oauth', { reason: 'crs-health-watch: CRS recovered', updatedBy: 'crs-health-watch' });
+ }
+ return true;
+ } catch (e) {
+ log(`route/settings write failed: ${e.message}`);
+ return false;
+ }
+}
+
+function currentEnvMode() {
+ const s = readJson(SETTINGS, { env: {} });
+ const base = s.env?.ANTHROPIC_BASE_URL || '';
+ const tok = s.env?.CLAUDE_CODE_OAUTH_TOKEN || '';
+ const bedrock = s.env?.CLAUDE_CODE_USE_BEDROCK || '';
+ if (/127\.0\.0\.1:3000|:3000\/api/.test(base) && tok.startsWith('cr_')) return 'crs';
+ if (bedrock === '1') return 'bedrock';
+ if (!base && !tok) return 'direct';
+ return 'mixed';
+}
+
+function main() {
+ if (args.has('--status')) {
+ const st = loadState();
+ const health = probe();
+ const route = readRouteState();
+ console.log(
+ JSON.stringify(
+ {
+ state: st,
+ routeMode: route.mode,
+ fallbackActive: existsSync(MARKER),
+ settingsEnvMode: currentEnvMode(),
+ healthy: health,
+ inferenceHealthy: health ? probeInference() : false,
+ smokeModel: CRS_SMOKE_MODEL || null,
+ },
+ null,
+ 2,
+ ),
+ );
+ return;
+ }
+ if (args.has('--restore')) {
+ if (probe() && probeInference() && setEnvMode('crs')) {
+ try {
+ execFileSync('rm', ['-f', MARKER]);
+ } catch {}
+ saveState({ down: 0, up: 0, mode: 'crs' });
+ log('FORCED restore → CRS env');
+ } else {
+ setEnvMode('direct');
+ writeFileSync(MARKER, String(Date.now()));
+ saveState({ down: 0, up: 0, mode: 'fail-closed' });
+ log('FORCED restore refused: CRS health or inference smoke failed → fail-closed env');
+ process.exitCode = 1;
+ }
+ return;
+ }
+ if (args.has('--fallback')) {
+ setEnvMode('direct');
+ writeFileSync(MARKER, String(Date.now()));
+ saveState({ down: 0, up: 0, mode: 'fail-closed' });
+ log('FORCED fallback → fail-closed env');
+ return;
+ }
+
+ try {
+ applyRouteToSettings(readRouteState());
+ } catch (e) {
+ log(`route apply skipped: ${e.message}`);
+ }
+
+ const healthOk = probe();
+ const inferenceOk = healthOk ? probeInference() : false;
+ const healthy = healthOk && inferenceOk;
+ const st = loadState();
+ if (healthy) {
+ st.up += 1;
+ st.down = 0;
+ } else {
+ st.down += 1;
+ st.up = 0;
+ }
+ const inFallback = existsSync(MARKER);
+
+ if (!healthy && st.down >= DOWN_STRIKES && !inFallback) {
+ if (setEnvMode('direct')) {
+ writeFileSync(MARKER, String(Date.now()));
+ st.mode = 'fail-closed';
+ log(
+ `CRS DOWN x${st.down} (>=${DOWN_STRIKES}) → FAIL-CLOSED: stripped provider env from settings.json; new/respawned sessions must not silently use direct or Bedrock`,
+ );
+ }
+ } else if (healthy && st.up >= UP_STRIKES && inFallback) {
+ if (setEnvMode('crs')) {
+ try {
+ execFileSync('rm', ['-f', MARKER]);
+ } catch {}
+ st.mode = 'crs';
+ log(
+ `CRS UP x${st.up} (>=${UP_STRIKES}) → RESTORE: re-added CRS env to settings.json; new/respawned sessions route via relay again`,
+ );
+ }
+ } else {
+ log(
+ `tick: health=${healthOk} inference=${inferenceOk} down=${st.down} up=${st.up} fallback=${inFallback} envMode=${currentEnvMode()}`,
+ );
+ }
+ saveState(st);
+}
+
+main();
diff --git a/claude-ops/scripts/account-rotation/crs-token-feed.mjs b/claude-ops/scripts/account-rotation/crs-token-feed.mjs
new file mode 100644
index 00000000..52ffd8f5
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/crs-token-feed.mjs
@@ -0,0 +1,250 @@
+#!/usr/bin/env node
+/**
+ * crs-token-feed.mjs — "rotator feeds CRS" (Linux/EC2).
+ *
+ * The hourly claude-token-refresh.service (refresh-tokens.mjs) is a NO-OP on
+ * Linux (it reads the macOS `security` keychain, which doesn't exist here), and
+ * nothing ever propagated fresh vault tokens into the local claude-relay-service
+ * (CRS) pool — so CRS accounts silently rotted to status=error as their access
+ * tokens expired (CRS stores no refresh tokens: hasRefresh=false on every acct).
+ *
+ * This feeder closes both gaps, contention-tolerantly:
+ * 1. Read each account's token from the Linux file vault (~/.claude/.credentials.json).
+ * 2. If expiring within BUFFER, best-effort OAuth refresh; persist the rotated
+ * refresh_token back to the file vault atomically. On HTTP 400 (refresh
+ * token already rotated by the Mac/daemon — cross-machine contention) we
+ * SKIP quietly — no browser re-auth (doomed headless) — and just propagate
+ * whatever fresh token the vault currently holds.
+ * 3. PUT the fresh claudeAiOauth into the mapped CRS account + reset-status.
+ *
+ * Single refresher-of-record stays the existing pipeline; this is best-effort
+ * top-up + the missing propagation. Runs via crs-token-feed.timer.
+ *
+ * node crs-token-feed.mjs # refresh-if-needed + propagate all
+ * node crs-token-feed.mjs --dry-run # report only
+ * node crs-token-feed.mjs --status # show vault vs CRS state
+ */
+import { readFileSync, writeFileSync, renameSync, appendFileSync } from 'fs';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { execSync } from 'child_process';
+import { foreignActiveKeys } from './account-leases.mjs';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const CONFIG_PATH = join(__dirname, 'config.json');
+const LOG_PATH = join(__dirname, 'rotation.log');
+const FILE_VAULT = join(process.env.HOME || '', '.claude', '.credentials.json');
+const CRS_BASE = process.env.CRS_BASE || 'http://127.0.0.1:3005';
+const CRS_CONTAINER = process.env.CRS_CONTAINER || 'crs-claude-relay-1';
+const CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e';
+const TOKEN_ENDPOINT = 'https://platform.claude.com/v1/oauth/token';
+const BUFFER_MS = 2 * 3_600_000; // refresh if expiring within 2h
+const INTER_DELAY_MS = 1_500;
+const <USER>_EMAIL = process.env.CLAUDE_ROTATOR_<USER>_EMAIL || ['<OWNER_NAME>', 'gmail.com'].join('@');
+
+// vault key (label || email) -> CRS account name
+const CRS_NAME_BY_KEY = {
+ 'chairman@<OWNER_BRAND>.org': 'pool-chairman',
+ '[email protected]': 'canary-support',
+ <OWNER_BRAND>: 'pool-<OWNER_BRAND>-personal',
+ '<OWNER_BRAND>-team': 'pool-<OWNER_BRAND>-team',
+ '<WORK_EMAIL>': 'pool-<OWNER_BRAND>',
+ [<USER>_EMAIL]: 'pool-<USER>',
+ '[email protected]': 'pool-aurora',
+ '<WORK_EMAIL>': 'pool-foundation',
+ 'sponsors@<OWNER_BRAND>.org': 'canary-sponsors',
+ '[email protected]': 'canary-lifecycle',
+};
+
+const args = process.argv.slice(2);
+const DRY = args.includes('--dry-run');
+const STATUS = args.includes('--status');
+
+function log(msg) {
+ const line = `[${new Date().toISOString()}] [crs-feed] ${msg}`;
+ console.log(line);
+ try {
+ appendFileSync(LOG_PATH, line + '\n');
+ } catch {}
+}
+function accountKey(a) {
+ return a.label || a.email;
+}
+function fvLoad() {
+ try {
+ return JSON.parse(readFileSync(FILE_VAULT, 'utf8'));
+ } catch {
+ return {};
+ }
+}
+function fvSave(v) {
+ const t = `${FILE_VAULT}.tmp.${process.pid}`;
+ writeFileSync(t, JSON.stringify(v, null, 2));
+ renameSync(t, FILE_VAULT);
+}
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+async function oauthRefresh(refreshToken) {
+ try {
+ const res = await fetch(TOKEN_ENDPOINT, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ grant_type: 'refresh_token', refresh_token: refreshToken, client_id: CLIENT_ID }),
+ });
+ const body = await res.json().catch(() => ({}));
+ if (res.ok && body.access_token) {
+ return {
+ ok: true,
+ oauth: {
+ accessToken: body.access_token,
+ refreshToken: body.refresh_token || refreshToken,
+ expiresAt: body.expires_in ? Date.now() + body.expires_in * 1000 : Date.now() + 8 * 3_600_000,
+ subscriptionType: body.subscription_type,
+ rateLimitTier: body.rate_limit_tier,
+ },
+ };
+ }
+ return { ok: false, status: res.status, error: body?.error?.message || body?.error?.type || `HTTP ${res.status}` };
+ } catch (e) {
+ return { ok: false, error: e.message };
+ }
+}
+
+async function crsLogin() {
+ let pw = '';
+ try {
+ pw = execSync(
+ `docker inspect ${CRS_CONTAINER} --format '{{range .Config.Env}}{{println .}}{{end}}' | sed -n 's/^ADMIN_PASSWORD=//p'`,
+ { timeout: 8000 },
+ )
+ .toString()
+ .trim();
+ } catch {}
+ if (!pw) return null;
+ try {
+ const r = await fetch(`${CRS_BASE}/web/auth/login`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ username: 'cradmin', password: pw }),
+ }).then((x) => x.json());
+ const tok = r.token || r.data?.token;
+ return tok ? { 'Content-Type': 'application/json', Authorization: `Bearer ${tok}` } : null;
+ } catch {
+ return null;
+ }
+}
+
+async function main() {
+ const config = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
+ const H = await crsLogin();
+ if (!H) {
+ log('CRS login failed (relay down or no admin pw) — aborting');
+ process.exit(1);
+ }
+ const acctsResp = await fetch(`${CRS_BASE}/admin/claude-accounts`, { headers: H }).then((r) => r.json());
+ const byName = Object.fromEntries((acctsResp.data || acctsResp.accounts || acctsResp).map((a) => [a.name, a]));
+ const now = Date.now();
+ // Contention guard: never refresh an account the OTHER host holds the lease on
+ // (refresh tokens are single-use; double-refresh → 400s on the other machine).
+ let foreign = new Set();
+ try {
+ foreign = new Set(foreignActiveKeys());
+ } catch (e) {
+ log(`lease check failed (${e.message}) — proceeding propagate-only`);
+ }
+ if (foreign.size) log(`foreign-leased (refresh-skipped): ${[...foreign].join(', ')}`);
+
+ if (STATUS) {
+ for (const a of config.accounts) {
+ const key = accountKey(a);
+ const crsName = CRS_NAME_BY_KEY[key];
+ const e = fvLoad()[`Claude-Rotation-${key}`]?.claudeAiOauth;
+ const min = e?.expiresAt ? Math.floor((e.expiresAt - now) / 60000) : 'n/a';
+ const crs = byName[crsName];
+ console.log(
+ ` ${key} -> ${crsName || '?'}: vault_min=${min} crs=${crs ? crs.status + '/sched=' + crs.schedulable : 'MISSING'}`,
+ );
+ }
+ return;
+ }
+
+ let refreshed = 0,
+ propagated = 0,
+ skipped = 0,
+ missing = 0;
+ for (let i = 0; i < config.accounts.length; i++) {
+ const a = config.accounts[i];
+ const key = accountKey(a);
+ const crsName = CRS_NAME_BY_KEY[key];
+ if (!crsName || !byName[crsName]) {
+ missing++;
+ continue;
+ }
+ const crs = byName[crsName];
+
+ const vault = fvLoad();
+ const entry = vault[`Claude-Rotation-${key}`]?.claudeAiOauth;
+ if (!entry?.accessToken) {
+ log(`${key}: no vault token — skip`);
+ skipped++;
+ continue;
+ }
+
+ let oauth = entry;
+ const expiring = !oauth.expiresAt || oauth.expiresAt < now + BUFFER_MS;
+ if (expiring && foreign.has(key)) {
+ log(`${key}: expiring but foreign-leased — refresh deferred to owner host, propagating current token`);
+ } else if (expiring && oauth.refreshToken && !DRY) {
+ if (i > 0) await sleep(INTER_DELAY_MS);
+ const r = await oauthRefresh(oauth.refreshToken);
+ if (r.ok) {
+ oauth = { ...oauth, ...r.oauth, scopes: oauth.scopes || [] };
+ vault[`Claude-Rotation-${key}`] = {
+ claudeAiOauth: oauth,
+ mcpOAuth: vault[`Claude-Rotation-${key}`]?.mcpOAuth || {},
+ };
+ fvSave(vault);
+ refreshed++;
+ log(`${key}: refreshed (min_left=${Math.floor((oauth.expiresAt - now) / 60000)})`);
+ } else if (r.status === 400) {
+ log(`${key}: refresh 400 (rotated elsewhere) — propagating existing vault token`);
+ } else {
+ log(`${key}: refresh failed (${r.error}) — propagating existing vault token`);
+ }
+ }
+
+ // propagate whatever fresh token we have (don't push already-expired)
+ if ((oauth.expiresAt || 0) < now + 60_000) {
+ log(`${key}: vault token expired, no refresh — CRS left as-is`);
+ skipped++;
+ continue;
+ }
+ if (DRY) {
+ log(`${key}: [dry] would PUT -> ${crsName}`);
+ continue;
+ }
+ try {
+ const put = await fetch(`${CRS_BASE}/admin/claude-accounts/${crs.id}`, {
+ method: 'PUT',
+ headers: H,
+ body: JSON.stringify({ claudeAiOauth: oauth, schedulable: true }),
+ });
+ if (put.ok) {
+ if (crs.status === 'error')
+ await fetch(`${CRS_BASE}/admin/claude-accounts/${crs.id}/reset-status`, { method: 'POST', headers: H }).catch(
+ () => {},
+ );
+ propagated++;
+ } else {
+ log(`${key}: CRS PUT ${put.status}`);
+ }
+ } catch (e) {
+ log(`${key}: CRS PUT error ${e.message}`);
+ }
+ }
+ log(`feed complete: ${refreshed} refreshed, ${propagated} propagated, ${skipped} skipped, ${missing} unmapped`);
+}
+main().catch((e) => {
+ log(`fatal: ${e.message}`);
+ process.exit(1);
+});
diff --git a/claude-ops/scripts/account-rotation/crs-token-feed.sh b/claude-ops/scripts/account-rotation/crs-token-feed.sh
new file mode 100755
index 00000000..f47124a6
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/crs-token-feed.sh
@@ -0,0 +1,8 @@
+#!/usr/bin/env bash
+# Single-flight wrapper for crs-token-feed.mjs (NEVER STACK rule).
+set -euo pipefail
+source "$HOME/.claude/scripts/lib/once.sh" 2>/dev/null || true
+if command -v claude_once >/dev/null 2>&1; then
+ claude_once crs-token-feed 60 || exit 0
+fi
+exec /usr/bin/node "$HOME/.claude/scripts/account-rotation/crs-token-feed.mjs" "$@"
diff --git a/claude-ops/scripts/account-rotation/route-state.mjs b/claude-ops/scripts/account-rotation/route-state.mjs
new file mode 100644
index 00000000..0242ecae
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/route-state.mjs
@@ -0,0 +1,203 @@
+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'fs';
+import { dirname, join } from 'path';
+import { homedir, hostname } from 'os';
+
+export const ROUTE_MODES = new Set(['crs-oauth', 'bedrock-confirmed', 'fail-closed']);
+
+const STATE_PATH = join(homedir(), '.claude', 'claude-routing-state.json');
+const SETTINGS_PATH = join(homedir(), '.claude', 'settings.json');
+const CRKEY_PATH = join(homedir(), '.claude', 'scripts', 'account-rotation', '.crkey');
+
+const MODEL_KEYS = [
+ 'ANTHROPIC_MODEL',
+ 'ANTHROPIC_SMALL_FAST_MODEL',
+ 'ANTHROPIC_DEFAULT_SONNET_MODEL',
+ 'ANTHROPIC_DEFAULT_HAIKU_MODEL',
+ 'ANTHROPIC_DEFAULT_OPUS_MODEL',
+ 'ANTHROPIC_DEFAULT_FABLE_MODEL',
+];
+
+const BEDROCK_KEYS = ['CLAUDE_CODE_USE_BEDROCK', 'AWS_BEDROCK_REGION'];
+
+const ANTHROPIC_DIRECT_KEYS = ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN'];
+
+function nowIso() {
+ return new Date().toISOString();
+}
+
+function readJson(path, fallback) {
+ try {
+ return JSON.parse(readFileSync(path, 'utf8'));
+ } catch {
+ return fallback;
+ }
+}
+
+function readSettingsEnv() {
+ return readJson(SETTINGS_PATH, { env: {} }).env || {};
+}
+
+function defaultCrsConfig() {
+ const env = readSettingsEnv();
+ const baseUrl = process.env.CRS_BASE_URL || env.ANTHROPIC_BASE_URL || 'http://127.0.0.1:3000/api';
+ const healthUrl = process.env.CRS_HEALTH_URL || baseUrl.replace(/\/api\/?$/, '/health');
+ return {
+ baseUrl,
+ healthUrl,
+ authority: 'fra-primary',
+ };
+}
+
+function writeJsonAtomic(path, data) {
+ mkdirSync(dirname(path), { recursive: true });
+ const tmp = `${path}.tmp.${process.pid}`;
+ writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`);
+ renameSync(tmp, path);
+}
+
+function crKey() {
+ try {
+ return readFileSync(CRKEY_PATH, 'utf8').trim();
+ } catch {
+ return '';
+ }
+}
+
+export function readRouteState() {
+ const state = readJson(STATE_PATH, null);
+ if (!state || !ROUTE_MODES.has(state.mode)) {
+ return {
+ mode: 'crs-oauth',
+ updatedAt: nowIso(),
+ updatedBy: 'default',
+ reason: 'default',
+ bedrockConfirmation: null,
+ crs: defaultCrsConfig(),
+ host: hostname(),
+ };
+ }
+ return state;
+}
+
+export function writeRouteState(next) {
+ const prev = readRouteState();
+ const merged = {
+ ...prev,
+ ...next,
+ updatedAt: nowIso(),
+ host: hostname(),
+ };
+ if (!ROUTE_MODES.has(merged.mode)) {
+ throw new Error(`invalid route mode: ${merged.mode}`);
+ }
+ writeJsonAtomic(STATE_PATH, merged);
+ return merged;
+}
+
+export function bedrockConfirmationActive(state = readRouteState(), at = Date.now()) {
+ const confirmation = state.bedrockConfirmation;
+ if (!confirmation?.confirmedAt || !confirmation?.expiresAt) return false;
+ return Date.parse(confirmation.expiresAt) > at;
+}
+
+export function setRouteMode(mode, options = {}) {
+ if (!ROUTE_MODES.has(mode)) throw new Error(`invalid route mode: ${mode}`);
+ const reason = options.reason || 'manual';
+ const ttlMinutes = Number.isFinite(options.ttlMinutes) ? options.ttlMinutes : 60;
+ const next = {
+ mode,
+ reason,
+ updatedBy: options.updatedBy || process.env.USER || 'unknown',
+ };
+ if (options.crs) next.crs = options.crs;
+ if (mode === 'bedrock-confirmed') {
+ if (!options.confirmMetered) {
+ throw new Error('Bedrock is metered AWS usage; pass confirmMetered=true to activate a TTL-scoped confirmation');
+ }
+ const confirmedAt = nowIso();
+ next.bedrockConfirmation = {
+ confirmedAt,
+ expiresAt: new Date(Date.now() + ttlMinutes * 60_000).toISOString(),
+ reason,
+ confirmedBy: options.updatedBy || process.env.USER || 'unknown',
+ };
+ } else {
+ next.bedrockConfirmation = null;
+ }
+ const prev = readRouteState();
+ const merged = {
+ ...prev,
+ ...next,
+ updatedAt: nowIso(),
+ host: hostname(),
+ };
+ if (!ROUTE_MODES.has(merged.mode)) {
+ throw new Error(`invalid route mode: ${merged.mode}`);
+ }
+ applyRouteToSettings(merged, options);
+ writeJsonAtomic(STATE_PATH, merged);
+ return merged;
+}
+
+export function applyRouteToSettings(state = readRouteState(), options = {}) {
+ const settings = readJson(SETTINGS_PATH, {});
+ const env = settings.env && typeof settings.env === 'object' ? { ...settings.env } : {};
+ for (const key of [...MODEL_KEYS, ...ANTHROPIC_DIRECT_KEYS]) delete env[key];
+ delete settings.model;
+ delete settings.availableModels;
+
+ if (state.mode === 'bedrock-confirmed') {
+ if (!bedrockConfirmationActive(state)) {
+ throw new Error('Bedrock route lacks an active TTL confirmation');
+ }
+ env.CLAUDE_CODE_USE_BEDROCK = '1';
+ env.AWS_BEDROCK_REGION = options.region || env.AWS_REGION || process.env.AWS_BEDROCK_REGION || 'us-east-1';
+ env.AWS_REGION = env.AWS_BEDROCK_REGION;
+ delete env.ANTHROPIC_BASE_URL;
+ delete env.CLAUDE_CODE_OAUTH_TOKEN;
+ } else if (state.mode === 'crs-oauth') {
+ for (const key of BEDROCK_KEYS) delete env[key];
+ env.AWS_REGION = env.AWS_REGION || process.env.AWS_REGION || 'us-east-1';
+ const key = crKey();
+ if (!key.startsWith('cr_')) {
+ throw new Error(`CRS relay key missing or invalid at ${CRKEY_PATH}`);
+ }
+ env.ANTHROPIC_BASE_URL = state.crs?.baseUrl || defaultCrsConfig().baseUrl;
+ env.CLAUDE_CODE_OAUTH_TOKEN = key;
+ } else {
+ for (const key of BEDROCK_KEYS) delete env[key];
+ delete env.ANTHROPIC_BASE_URL;
+ delete env.CLAUDE_CODE_OAUTH_TOKEN;
+ }
+
+ settings.env = env;
+ writeJsonAtomic(SETTINGS_PATH, settings);
+ return settings;
+}
+
+export function settingsRouteSnapshot() {
+ const settings = readJson(SETTINGS_PATH, { env: {} });
+ const env = settings.env || {};
+ const base = String(env.ANTHROPIC_BASE_URL || '');
+ const token = String(env.CLAUDE_CODE_OAUTH_TOKEN || '');
+ const bedrock = env.CLAUDE_CODE_USE_BEDROCK === '1';
+ return {
+ settingsPath: SETTINGS_PATH,
+ bedrock,
+ baseUrl: base || null,
+ tokenKind: token.startsWith('cr_') ? 'crs-relay' : token ? 'other' : 'none',
+ mixedProvider: bedrock && (!!base || !!token),
+ modelOverride: settings.model || null,
+ availableModelsOverride: existsSync(SETTINGS_PATH) && Array.isArray(settings.availableModels),
+ };
+}
+
+export function routeStatus() {
+ const state = readRouteState();
+ return {
+ statePath: STATE_PATH,
+ state,
+ bedrockConfirmationActive: bedrockConfirmationActive(state),
+ settings: settingsRouteSnapshot(),
+ };
+}
diff --git a/claude-ops/scripts/account-rotation/use-bedrock.sh b/claude-ops/scripts/account-rotation/use-bedrock.sh
index bff2e0f1..b86975e0 100755
--- a/claude-ops/scripts/account-rotation/use-bedrock.sh
+++ b/claude-ops/scripts/account-rotation/use-bedrock.sh
@@ -2,12 +2,13 @@
# use-bedrock.sh — switch this shell into Bedrock mode for Claude Code.
# Source me: `source ~/.claude/scripts/account-rotation/use-bedrock.sh`
#
+# Bedrock is metered AWS usage. To persist it, explicitly confirm:
+# CLAUDE_CONFIRM_METERED_BEDROCK=1 source ~/.claude/scripts/account-rotation/use-bedrock.sh
+#
# Sets in current shell + persists to ~/.claude/settings.json env block:
# CLAUDE_CODE_USE_BEDROCK=1
# AWS_BEDROCK_REGION=us-east-1 (override via env before sourcing)
-# ANTHROPIC_MODEL / ANTHROPIC_SMALL_FAST_MODEL — resolved from
-# `aws bedrock list-inference-profiles` (latest Sonnet + Haiku for your region),
-# with pinned fallbacks if AWS CLI fails. BEDROCK_SKIP_RESOLVE=1 forces fallbacks.
+# Model selection is left to Claude Code / the provider default.
#
# Auto-fired by rotate.mjs / daemon when all configured Anthropic Max accounts
# are LIVE-CONFIRMED at >=95% util. Sentinel: ~/.claude/.bedrock-fallback.json.
@@ -15,6 +16,14 @@
_ROT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
+if [[ "${CLAUDE_CONFIRM_METERED_BEDROCK:-}" != "1" ]]; then
+ echo "⛔ Bedrock fallback blocked."
+ echo " Bedrock is metered AWS usage. OAuth/CRS is the preferred route."
+ echo " Reason OAuth is unavailable: ${CLAUDE_BEDROCK_REASON:-not supplied}"
+ echo " To confirm for this short session: CLAUDE_CONFIRM_METERED_BEDROCK=1 source ~/.claude/scripts/account-rotation/use-bedrock.sh"
+ return 2 2>/dev/null || exit 2
+fi
+
export CLAUDE_CODE_USE_BEDROCK=1
export AWS_BEDROCK_REGION="${AWS_BEDROCK_REGION:-us-east-1}"
export AWS_REGION="${AWS_REGION:-$AWS_BEDROCK_REGION}"
@@ -23,58 +32,26 @@ unset ANTHROPIC_API_KEY
unset ANTHROPIC_AUTH_TOKEN
unset ANTHROPIC_BASE_URL
-_RESOLVED=""
-if command -v node >/dev/null 2>&1 && [[ -f "$_ROT_DIR/resolve-bedrock-models.mjs" ]]; then
- _RESOLVED="$(cd "$_ROT_DIR" && node resolve-bedrock-models.mjs 2>/dev/null)" || true
-fi
-
-if [[ -n "$_RESOLVED" ]]; then
- export ANTHROPIC_MODEL="$(python3 -c "import json,sys; d=json.loads(sys.argv[1]); print(d.get('primary',''))" "$_RESOLVED")"
- export ANTHROPIC_SMALL_FAST_MODEL="$(python3 -c "import json,sys; d=json.loads(sys.argv[1]); print(d.get('small',''))" "$_RESOLVED")"
-fi
-if [[ -z "$ANTHROPIC_MODEL" ]]; then
- export ANTHROPIC_MODEL="us.anthropic.claude-sonnet-4-6"
-fi
-if [[ -z "$ANTHROPIC_SMALL_FAST_MODEL" ]]; then
- export ANTHROPIC_SMALL_FAST_MODEL="us.anthropic.claude-haiku-4-5-20251001-v1:0"
-fi
+unset ANTHROPIC_MODEL
+unset ANTHROPIC_SMALL_FAST_MODEL
+unset ANTHROPIC_DEFAULT_SONNET_MODEL
+unset ANTHROPIC_DEFAULT_HAIKU_MODEL
+unset ANTHROPIC_DEFAULT_OPUS_MODEL
+unset ANTHROPIC_DEFAULT_FABLE_MODEL
-_SRC="$(python3 -c "import json,sys; print(json.loads(sys.argv[1]).get('source','?'))" "$_RESOLVED" 2>/dev/null || echo "?")"
+_SRC="claude-default"
-# Persist to ~/.claude/settings.json so NEW Claude Code sessions inherit Bedrock
-# even without sourcing this file. Backs up the prior env block once.
-python3 - "$_SRC" <<'PYEOF'
-import json, os, shutil, sys
-p = os.path.expanduser("~/.claude/settings.json")
-bak = p + ".bak.pre-bedrock"
-try:
- s = json.load(open(p))
-except Exception:
- s = {}
-if not os.path.exists(bak):
- try: shutil.copy(p, bak)
- except Exception: pass
-env = s.setdefault("env", {})
-env["CLAUDE_CODE_USE_BEDROCK"] = "1"
-env["AWS_BEDROCK_REGION"] = os.environ.get("AWS_BEDROCK_REGION", "us-east-1")
-env["AWS_REGION"] = env["AWS_BEDROCK_REGION"]
-env["ANTHROPIC_MODEL"] = os.environ.get("ANTHROPIC_MODEL", "")
-env["ANTHROPIC_SMALL_FAST_MODEL"] = os.environ.get("ANTHROPIC_SMALL_FAST_MODEL", "")
-for k in ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL"):
- env.pop(k, None)
-s.pop("model", None)
-s.pop("availableModels", None)
-with open(p, "w") as f:
- json.dump(s, f, indent=2)
-src = sys.argv[1] if len(sys.argv) > 1 else "?"
-print("✓ settings.json env updated (" + src + "; backup: " + bak + ")")
-PYEOF
+CLAUDE_BEDROCK_REASON="${CLAUDE_BEDROCK_REASON:-manual use-bedrock}" \
+ "$_ROT_DIR/../../../.local/bin/claude-stack" route \
+ --mode bedrock-confirmed \
+ --reason "${CLAUDE_BEDROCK_REASON:-manual use-bedrock}" \
+ --ttl-minutes "${CLAUDE_BEDROCK_CONFIRM_TTL_MINUTES:-60}" \
+ --region "$AWS_BEDROCK_REGION" \
+ --confirm-metered-bedrock >/dev/null || return 1 2>/dev/null || exit 1
echo "✅ Bedrock mode active for this shell + persisted to settings.json"
echo " region : $AWS_BEDROCK_REGION"
-echo " resolve : $_SRC (latest from inference profiles when api)"
-echo " model : $ANTHROPIC_MODEL"
-echo " fast : $ANTHROPIC_SMALL_FAST_MODEL"
+echo " model : Claude Code default"
echo " identity : $(aws sts get-caller-identity --query Arn --output text 2>/dev/null || echo 'aws sts FAILED')"
echo ""
echo " Reload zsh aliases/functions in this shell..."
diff --git a/claude-ops/scripts/account-rotation/use-oauth.sh b/claude-ops/scripts/account-rotation/use-oauth.sh
index 74aaa515..d036a943 100755
--- a/claude-ops/scripts/account-rotation/use-oauth.sh
+++ b/claude-ops/scripts/account-rotation/use-oauth.sh
@@ -1,43 +1,29 @@
#!/bin/bash
-# use-oauth.sh — exit Bedrock mode in this shell, restore Anthropic OAuth defaults.
+# use-oauth.sh — exit Bedrock mode in this shell, restore CRS-backed OAuth defaults.
# Source me: `source ~/.claude/scripts/account-rotation/use-oauth.sh`
#
-# Persists to ~/.claude/settings.json: removes Bedrock + hardcoded model overrides
-# so Claude Code loads the subscription model catalog from the API.
-# OAuth token is read from keychain by Claude Code on next session start.
+# Persists to ~/.claude/settings.json via claude-routing-state:
+# ANTHROPIC_BASE_URL points at CRS and CLAUDE_CODE_OAUTH_TOKEN is the CRS relay token.
unset CLAUDE_CODE_USE_BEDROCK
unset AWS_BEDROCK_REGION
-unset AWS_REGION
unset ANTHROPIC_MODEL
unset ANTHROPIC_SMALL_FAST_MODEL
+unset ANTHROPIC_DEFAULT_SONNET_MODEL
+unset ANTHROPIC_DEFAULT_HAIKU_MODEL
+unset ANTHROPIC_DEFAULT_OPUS_MODEL
+unset ANTHROPIC_DEFAULT_FABLE_MODEL
unset ANTHROPIC_API_KEY
unset ANTHROPIC_AUTH_TOKEN
unset ANTHROPIC_BASE_URL
-python3 - <<'PYEOF'
-import json, os
-p = os.path.expanduser("~/.claude/settings.json")
-try:
- s = json.load(open(p))
-except Exception:
- s = {}
-env = s.setdefault("env", {})
-for k in ("CLAUDE_CODE_USE_BEDROCK", "AWS_BEDROCK_REGION", "AWS_REGION",
- "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL",
- "ANTHROPIC_MODEL", "ANTHROPIC_SMALL_FAST_MODEL"):
- env.pop(k, None)
-s["env"] = env
-s.pop("model", None)
-s.pop("availableModels", None)
-with open(p, "w") as f:
- json.dump(s, f, indent=2)
-print("✓ settings.json env updated (Bedrock + hardcoded models removed)")
-PYEOF
+_ROT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
+"$_ROT_DIR/../../../.local/bin/claude-stack" route --mode crs-oauth --reason oauth-restored >/dev/null || return 1 2>/dev/null || exit 1
ACTIVE=$(python3 -c "import json; print(json.load(open('$HOME/.claude/scripts/account-rotation/state.json')).get('activeAccount',''))" 2>/dev/null)
echo "✅ OAuth mode restored for this shell + persisted to settings.json"
echo " models : (subscription catalog — no hardcoded IDs)"
+echo " route : CRS OAuth"
echo " active account: ${ACTIVE:-(unknown)}"
if [[ -f ~/.claude/.bedrock-fallback.json ]]; then
echo " ⚠ Bedrock sentinel still present — clearing"
diff --git a/claude-ops/scripts/install-crs-fra-tunnel.sh b/claude-ops/scripts/install-crs-fra-tunnel.sh
new file mode 100755
index 00000000..52fd26e0
--- /dev/null
+++ b/claude-ops/scripts/install-crs-fra-tunnel.sh
@@ -0,0 +1,35 @@
+#!/usr/bin/env bash
+# Install the macOS launchd tunnel that forwards local CRS traffic to FRA.
+
+set -euo pipefail
+
+if [[ "$(uname -s)" != "Darwin" ]]; then
+ echo "skip: CRS FRA tunnel is macOS-only (launchd)" >&2
+ exit 0
+fi
+
+PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
+LABEL="com.claude-ops.crs-fra-tunnel"
+TPL="$PLUGIN_ROOT/templates/${LABEL}.plist"
+DEST="$HOME/Library/LaunchAgents/${LABEL}.plist"
+LOG_DIR="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/logs"
+SSH_HOST="${CRS_FRA_SSH_HOST:-fra-direct}"
+LOCAL_PORT="${CRS_FRA_LOCAL_PORT:-3000}"
+REMOTE_PORT="${CRS_FRA_REMOTE_PORT:-3005}"
+
+for f in "$TPL"; do
+ [[ -f "$f" ]] || { echo "error: missing template $f" >&2; exit 1; }
+done
+
+mkdir -p "$(dirname "$DEST")" "$LOG_DIR"
+sed \
+ -e "s|__LOCAL_PORT__|$LOCAL_PORT|g" \
+ -e "s|__REMOTE_PORT__|$REMOTE_PORT|g" \
+ -e "s|__SSH_HOST__|$SSH_HOST|g" \
+ -e "s|__LOG_DIR__|$LOG_DIR|g" \
+ "$TPL" > "$DEST"
+
+launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || true
+launchctl bootstrap "gui/$(id -u)" "$DEST"
+
+echo "✓ installed $LABEL"
diff --git a/claude-ops/scripts/systemd/claude-account-rotation.service b/claude-ops/scripts/systemd/claude-account-rotation.service
new file mode 100644
index 00000000..d6378358
--- /dev/null
+++ b/claude-ops/scripts/systemd/claude-account-rotation.service
@@ -0,0 +1,19 @@
+[Unit]
+Description=Claude account rotation daemon
+After=network-online.target crs-compose.service
+Wants=network-online.target crs-compose.service
+
+[Service]
+Type=simple
+WorkingDirectory=%h/.claude/scripts/account-rotation
+Environment=CLAUDE_ENABLE_FLEET_RECOVERY=0
+Environment=CLAUDE_ENABLE_BG_RESPAWN=0
+Environment=CLAUDE_ENABLE_BG_SESSION_ROUTER=1
+ExecStart=/usr/bin/node %h/.claude/scripts/account-rotation/daemon.mjs
+Restart=always
+RestartSec=30
+StandardOutput=append:%h/.claude/logs/account-rotation.systemd.log
+StandardError=append:%h/.claude/logs/account-rotation.systemd.log
+
+[Install]
+WantedBy=default.target
diff --git a/claude-ops/scripts/systemd/crs-bedrock-guard.service b/claude-ops/scripts/systemd/crs-bedrock-guard.service
new file mode 100644
index 00000000..1bc2d246
--- /dev/null
+++ b/claude-ops/scripts/systemd/crs-bedrock-guard.service
@@ -0,0 +1,10 @@
+[Unit]
+Description=Detect CRS Bedrock fallback traffic
+After=crs-compose.service
+Wants=crs-compose.service
+
+[Service]
+Type=oneshot
+ExecStart=/usr/bin/node %h/.claude/scripts/account-rotation/crs-bedrock-guard.mjs
+StandardOutput=append:%h/.claude/logs/crs-bedrock-guard.systemd.log
+StandardError=append:%h/.claude/logs/crs-bedrock-guard.systemd.log
diff --git a/claude-ops/scripts/systemd/crs-bedrock-guard.timer b/claude-ops/scripts/systemd/crs-bedrock-guard.timer
new file mode 100644
index 00000000..e07e419c
--- /dev/null
+++ b/claude-ops/scripts/systemd/crs-bedrock-guard.timer
@@ -0,0 +1,11 @@
+[Unit]
+Description=Run CRS Bedrock fallback guard periodically
+
+[Timer]
+OnBootSec=3min
+OnUnitActiveSec=5min
+Persistent=true
+Unit=crs-bedrock-guard.service
+
+[Install]
+WantedBy=timers.target
diff --git a/claude-ops/scripts/systemd/crs-compose.service b/claude-ops/scripts/systemd/crs-compose.service
new file mode 100644
index 00000000..76da9f5d
--- /dev/null
+++ b/claude-ops/scripts/systemd/crs-compose.service
@@ -0,0 +1,15 @@
+[Unit]
+Description=Claude Relay Service docker compose stack
+Requires=docker.service
+After=docker.service network-online.target
+
+[Service]
+Type=oneshot
+WorkingDirectory=%h/crs
+ExecStart=/usr/bin/docker compose up -d --remove-orphans
+ExecStop=/usr/bin/docker compose down
+RemainAfterExit=yes
+TimeoutStartSec=120
+
+[Install]
+WantedBy=default.target
diff --git a/claude-ops/scripts/systemd/crs-token-feed.service b/claude-ops/scripts/systemd/crs-token-feed.service
new file mode 100644
index 00000000..14b29484
--- /dev/null
+++ b/claude-ops/scripts/systemd/crs-token-feed.service
@@ -0,0 +1,11 @@
+[Unit]
+Description=Feed fresh Claude OAuth tokens into local CRS
+After=crs-compose.service
+Wants=crs-compose.service
+
+[Service]
+Type=oneshot
+Environment=CRS_BASE=http://127.0.0.1:3005
+ExecStart=%h/.claude/scripts/account-rotation/crs-token-feed.sh
+StandardOutput=append:%h/.claude/logs/crs-token-feed.systemd.log
+StandardError=append:%h/.claude/logs/crs-token-feed.systemd.log
diff --git a/claude-ops/scripts/systemd/crs-token-feed.timer b/claude-ops/scripts/systemd/crs-token-feed.timer
new file mode 100644
index 00000000..591670f2
--- /dev/null
+++ b/claude-ops/scripts/systemd/crs-token-feed.timer
@@ -0,0 +1,11 @@
+[Unit]
+Description=Run CRS token feed periodically
+
+[Timer]
+OnBootSec=2min
+OnUnitActiveSec=5min
+Persistent=true
+Unit=crs-token-feed.service
+
+[Install]
+WantedBy=timers.target
diff --git a/claude-ops/templates/com.claude-ops.crs-fra-tunnel.plist b/claude-ops/templates/com.claude-ops.crs-fra-tunnel.plist
new file mode 100644
index 00000000..750d8ddc
--- /dev/null
+++ b/claude-ops/templates/com.claude-ops.crs-fra-tunnel.plist
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>com.claude-ops.crs-fra-tunnel</string>
+
+ <key>ProgramArguments</key>
+ <array>
+ <string>/usr/bin/ssh</string>
+ <string>-N</string>
+ <string>-o</string>
+ <string>BatchMode=yes</string>
+ <string>-o</string>
+ <string>ExitOnForwardFailure=yes</string>
+ <string>-o</string>
+ <string>ServerAliveInterval=30</string>
+ <string>-o</string>
+ <string>ServerAliveCountMax=3</string>
+ <string>-L</string>
+ <string>127.0.0.1:__LOCAL_PORT__:127.0.0.1:__REMOTE_PORT__</string>
+ <string>__SSH_HOST__</string>
+ </array>
+
+ <key>KeepAlive</key>
+ <true/>
+
+ <key>ThrottleInterval</key>
+ <integer>30</integer>
+
+ <key>RunAtLoad</key>
+ <true/>
+
+ <key>StandardOutPath</key>
+ <string>__LOG_DIR__/crs-fra-tunnel.out.log</string>
+
+ <key>StandardErrorPath</key>
+ <string>__LOG_DIR__/crs-fra-tunnel.err.log</string>
+</dict>
+</plist>