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): Bedrock + OAuth support for account rotation (#215)

Aurora Capital3dac5564f56d
diff --git a/claude-ops/scripts/account-rotation/README.md b/claude-ops/scripts/account-rotation/README.md
index 55642d20..e00f22e4 100644
--- a/claude-ops/scripts/account-rotation/README.md
+++ b/claude-ops/scripts/account-rotation/README.md
@@ -69,7 +69,7 @@ Override the keychain account name via `CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT` if you
| --------------------- | ---------------------------------------------------------------------- |
| `rotate.mjs` | Main rotation logic. CLI: `--status`, `--utilization`, `--to`, `--setup`. |
| `daemon.mjs` | launchd-managed monitor. Polls every 15s, rotates at 80% utilization. |
-| `ai-brain.mjs` | Claude Haiku fallback for unexpected OAuth pages. |
+| `ai-brain.mjs` | Bedrock stall helper: vision + optional Context7 / web research; billing scrape after OAuth. |
| `force-rotate.sh` | Out-of-band rotation when Claude Code is unreachable. |
| `config.example.json` | Schema reference. Copy to `config.json` and populate. |
diff --git a/claude-ops/scripts/account-rotation/ai-brain.mjs b/claude-ops/scripts/account-rotation/ai-brain.mjs
index 1ffe783e..f66032e4 100644
--- a/claude-ops/scripts/account-rotation/ai-brain.mjs
+++ b/claude-ops/scripts/account-rotation/ai-brain.mjs
@@ -7,65 +7,367 @@
* terms-acceptance wall, workspace admin re-consent, etc.). Sends a PNG
* screenshot + DOM summary to Claude and executes the returned action.
*
+ * Inference: Amazon Bedrock Converse API only (`POST .../model/{modelId}/converse`).
+ * Model IDs follow current AWS Bedrock model cards (e.g. Sonnet 4.6 geo / foundation /
+ * global inference profiles — verified via Context7 against AWS documentation).
+ * Interactive Claude Max OAuth is separate (Claude Code); this module does not use
+ * ANTHROPIC_API_KEY.
+ *
* Safety caps:
* - MAX_DECISIONS per rotation (cost + runaway guard)
* - screenshot ≤ 1.5MB, DOM text ≤ 6KB in the prompt
* - passwords NEVER leave the machine; fill_password uses local dcli
* - abort terminates the flow; never retry on abort
+ * - Optional research: Bedrock text planner may invoke Context7 (npx ctx7) and
+ * web search (DuckDuckGo) before the vision call; disable with CLAUDE_ROTATOR_BRAIN_NO_RESEARCH=1
*/
-import { execFileSync } from 'child_process';
+import { readFileSync } from 'fs';
+import { execFile } from 'child_process';
+import { promisify } from 'util';
+import { join } from 'path';
+import { AwsClient } from 'aws4fetch';
+
+const execFileAsync = promisify(execFile);
-const API_URL = 'https://api.anthropic.com/v1/messages';
-const DEFAULT_MODEL = 'claude-haiku-4-5';
+const BEDROCK_MODEL_DEFAULTS = [
+ 'us.anthropic.claude-sonnet-4-6',
+ 'anthropic.claude-sonnet-4-6',
+ 'global.anthropic.claude-sonnet-4-6',
+ 'us.anthropic.claude-haiku-4-5-20251001-v1:0',
+];
const MAX_DECISIONS = 6;
const REQUEST_TIMEOUT_MS = 30_000;
+const RESEARCH_PLANNER_TIMEOUT_MS = 45_000;
+const CTX7_EXEC_TIMEOUT_MS = 120_000;
+const MAX_RESEARCH_TOOLS = 3;
+const MAX_RESEARCH_APPENDIX_CHARS = 12_000;
+const WEB_SEARCH_USER_AGENT = 'claude-account-rotation-research/1.0';
+
+/** Haiku-first chain for the text-only research planner (cheaper than vision step). */
+function plannerModelChain() {
+ const envModel = process.env.CLAUDE_ROTATOR_BRAIN_PLANNER_MODEL?.trim();
+ const haiku = 'us.anthropic.claude-haiku-4-5-20251001-v1:0';
+ const chain = [];
+ if (envModel) chain.push(envModel);
+ if (!chain.includes(haiku)) chain.push(haiku);
+ for (const id of BEDROCK_MODEL_DEFAULTS) {
+ if (!chain.includes(id)) chain.push(id);
+ }
+ return chain;
+}
+
+function npxCmd() {
+ return process.platform === 'win32' ? 'npx.cmd' : 'npx';
+}
+
+/** Optional override first, then defaults (no legacy Claude 3.x models). */
+function bedrockModelChain() {
+ const envModel = process.env.CLAUDE_ROTATOR_BEDROCK_MODEL?.trim();
+ const chain = [];
+ if (envModel) chain.push(envModel);
+ for (const id of BEDROCK_MODEL_DEFAULTS) {
+ if (!chain.includes(id)) chain.push(id);
+ }
+ return chain;
+}
+
+function toBedrockMessages(messages) {
+ return messages.map((m) => ({
+ role: m.role,
+ content: m.content.map((c) => {
+ if (c.type === 'text') return { text: c.text };
+ if (c.type === 'image') {
+ const b64 = c.source?.data;
+ if (!b64) return { text: '[image omitted]' };
+ return {
+ image: {
+ format: 'png',
+ // ImageSource.bytes: base64-encoded image (Bedrock runtime Converse API).
+ source: { bytes: b64 },
+ },
+ };
+ }
+ return { text: String(c) };
+ }),
+ }));
+}
+
+function extractBedrockText(data) {
+ const blocks = data?.output?.message?.content;
+ if (!Array.isArray(blocks)) return '';
+ return blocks
+ .map((b) => (typeof b?.text === 'string' ? b.text : ''))
+ .join('')
+ .trim();
+}
+
+function resolveAwsCredentials() {
+ const envPath = join(process.env.HOME || '', '.env');
+ let envContent = '';
+ try {
+ envContent = readFileSync(envPath, 'utf8');
+ } catch {}
+
+ const getVal = (key) => {
+ if (process.env[key]) return process.env[key];
+ const m = envContent.match(new RegExp(`^${key}=(.*)$`, 'm'));
+ return m ? m[1].trim() : null;
+ };
+
+ const accessKeyId = getVal('AWS_ACCESS_KEY_ID');
+ const secretAccessKey = getVal('AWS_SECRET_ACCESS_KEY');
+ const region = getVal('AWS_REGION') || 'us-east-1';
+
+ if (accessKeyId && secretAccessKey) {
+ return { accessKeyId, secretAccessKey, region };
+ }
+ return null;
+}
+
+// ── Amazon Bedrock Converse (shared) ─────────────────────────────────────────
+
+/**
+ * @param {ReturnType<typeof toBedrockMessages>} bedrockMessages
+ * @param {{ inferenceConfig?: object, timeoutMs?: number, modelIds?: string[] | null }} options
+ * @returns {Promise<{ ok: boolean, provider: string | null, data: object | null, status: number, modelId?: string }>}
+ */
+async function invokeBedrockConverse(bedrockMessages, log, options = {}) {
+ const inferenceConfig = options.inferenceConfig ?? { maxTokens: 400, temperature: 0 };
+ const timeoutMs = options.timeoutMs ?? REQUEST_TIMEOUT_MS;
+ const modelIds = options.modelIds ?? bedrockModelChain();
+
+ const aws = resolveAwsCredentials();
+ if (!aws) {
+ log('no AWS credentials for Bedrock');
+ return { ok: false, provider: null, data: null, status: 0 };
+ }
+
+ let lastStatus = 0;
+ let lastData = null;
+
+ for (const modelId of modelIds) {
+ log(`Bedrock Converse (${modelId})`);
+ const client = new AwsClient({
+ accessKeyId: aws.accessKeyId,
+ secretAccessKey: aws.secretAccessKey,
+ region: aws.region,
+ service: 'bedrock-runtime',
+ });
+
+ const bedrockUrl = `https://bedrock-runtime.${aws.region}.amazonaws.com/model/${modelId}/converse`;
+
+ try {
+ const res = await client.fetch(bedrockUrl, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ messages: bedrockMessages,
+ inferenceConfig,
+ }),
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ const data = await res.json().catch(() => ({}));
+ lastStatus = res.status;
+ lastData = data;
+ if (res.ok) {
+ return { ok: true, provider: 'bedrock', data, status: res.status, modelId };
+ }
+ const errPeek = JSON.stringify(data?.message || data?.error || data).slice(0, 180);
+ log(`Bedrock (${modelId}) ${res.status}: ${errPeek}`);
+ } catch (e) {
+ log(`Bedrock (${modelId}) error: ${String(e.message || e).slice(0, 160)}`);
+ }
+ }
+
+ return { ok: false, provider: 'bedrock', data: lastData, status: lastStatus };
+}
+
+function extractFirstJsonObject(text) {
+ if (!text) return null;
+ let cleaned = text
+ .trim()
+ .replace(/^```(?:json|JSON)?\s*/i, '')
+ .replace(/```\s*$/i, '')
+ .trim();
+ const m = cleaned.match(/\{[\s\S]*\}/);
+ return m ? m[0] : null;
+}
-// ── Resolve API key from env → Doppler → keychain ────────────────────────────
-function readCommand(argv, timeout = 4000) {
+function parseResearchPlan(text) {
+ const raw = extractFirstJsonObject(text);
+ if (!raw) return null;
try {
- return execFileSync(argv[0], argv.slice(1), {
- timeout,
- stdio: ['ignore', 'pipe', 'ignore'],
- })
- .toString()
- .trim();
+ const j = JSON.parse(raw);
+ if (!j || !Array.isArray(j.tools)) return null;
+ const tools = [];
+ for (const t of j.tools) {
+ if (t?.tool === 'context7') {
+ tools.push({
+ tool: 'context7',
+ libraryName: String(t.libraryName || ''),
+ libraryQuery: String(t.libraryQuery || ''),
+ docsQuery: String(t.docsQuery || ''),
+ });
+ } else if (t?.tool === 'web_search') {
+ tools.push({ tool: 'web_search', query: String(t.query || '') });
+ }
+ }
+ return { tools };
} catch {
+ return null;
+ }
+}
+
+function firstContext7LibraryId(stdout) {
+ const m = stdout.match(/Context7-compatible library ID:\s*(\/[^\s)\]]+)/);
+ if (m) return m[1];
+ for (const line of stdout.split('\n')) {
+ const m2 = line.trim().match(/^(\/[\w.-]+\/[\w.-]+(?:\/[\w.-]+)?)\s*$/);
+ if (m2) return m2[1];
+ }
+ return null;
+}
+
+async function runContext7Tool(spec, log) {
+ const name = String(spec.libraryName || 'documentation')
+ .trim()
+ .slice(0, 120);
+ const libraryQuery = String(spec.libraryQuery || '')
+ .trim()
+ .slice(0, 220);
+ const docsQuery = String(spec.docsQuery || '')
+ .trim()
+ .slice(0, 320);
+ if (!libraryQuery || !docsQuery) return '';
+
+ let libraryOut = '';
+ try {
+ const { stdout } = await execFileAsync(npxCmd(), ['ctx7@latest', 'library', name, libraryQuery], {
+ maxBuffer: 4_000_000,
+ timeout: CTX7_EXEC_TIMEOUT_MS,
+ env: process.env,
+ });
+ libraryOut = stdout || '';
+ } catch (e) {
+ log(`context7 library failed: ${String(e.message || e).slice(0, 100)}`);
return '';
}
+
+ const libId = firstContext7LibraryId(libraryOut);
+ if (!libId) {
+ return `[context7 library — no id parsed]\n${libraryOut.slice(0, 4000)}`;
+ }
+
+ try {
+ const { stdout } = await execFileAsync(npxCmd(), ['ctx7@latest', 'docs', libId, docsQuery], {
+ maxBuffer: 4_000_000,
+ timeout: CTX7_EXEC_TIMEOUT_MS,
+ env: process.env,
+ });
+ return `[context7 ${libId}]\n${(stdout || '').slice(0, 6000)}`;
+ } catch (e) {
+ log(`context7 docs failed: ${String(e.message || e).slice(0, 100)}`);
+ return `[context7 ${libId} — library output only]\n${libraryOut.slice(0, 3000)}`;
+ }
}
-function resolveApiKey() {
- if (process.env.ANTHROPIC_API_KEY?.startsWith('sk-ant-')) {
- return process.env.ANTHROPIC_API_KEY;
+async function runWebSearchTool(query, log) {
+ const q = String(query || '')
+ .trim()
+ .slice(0, 500);
+ if (!q) return '';
+
+ try {
+ const u = new URL('https://api.duckduckgo.com/');
+ u.searchParams.set('q', q);
+ u.searchParams.set('format', 'json');
+ u.searchParams.set('no_html', '1');
+ u.searchParams.set('skip_disambig', '1');
+
+ const res = await fetch(u.toString(), {
+ signal: AbortSignal.timeout(18_000),
+ headers: { Accept: 'application/json', 'User-Agent': WEB_SEARCH_USER_AGENT },
+ });
+ if (!res.ok) {
+ return `[web_search] HTTP ${res.status} for query: ${q}`;
+ }
+ const j = await res.json().catch(() => ({}));
+ const parts = [];
+ if (j.AbstractText) parts.push(String(j.AbstractText));
+ if (j.AbstractURL) parts.push(`Source: ${j.AbstractURL}`);
+ const topics = Array.isArray(j.RelatedTopics) ? j.RelatedTopics.slice(0, 6) : [];
+ for (const t of topics) {
+ if (t && typeof t === 'object' && t.Text) parts.push(String(t.Text));
+ }
+ const body = parts.join('\n\n').slice(0, 4500);
+ return body || `[web_search] No instant answer for: ${q}`;
+ } catch (e) {
+ log(`web_search failed: ${String(e.message || e).slice(0, 80)}`);
+ return '';
}
- // Optional Doppler lookup — set CLAUDE_ROTATOR_DOPPLER_PROJECTS as a
- // comma-separated list of "<project>:<config>" pairs (e.g. "myapp:prd,other:dev").
- const dopplerSpec = process.env.CLAUDE_ROTATOR_DOPPLER_PROJECTS || '';
- const dopplerTargets = dopplerSpec
- .split(',')
- .map((s) => s.trim())
- .filter(Boolean)
- .map((s) => s.split(':'))
- .filter((p) => p.length === 2);
- for (const [project, config] of dopplerTargets) {
- const out = readCommand([
- 'doppler',
- 'secrets',
- 'get',
- 'ANTHROPIC_API_KEY',
- '--project',
- project,
- '--config',
- config,
- '--plain',
- ]);
- if (out.startsWith('sk-ant-')) return out;
+}
+
+async function gatherResearchAppendix({ stallReason, url, domSummary }, log) {
+ if (process.env.CLAUDE_ROTATOR_BRAIN_NO_RESEARCH === '1') return '';
+
+ const dom = (domSummary || '').slice(0, 3500);
+ const planPrompt = [
+ 'You choose research tools BEFORE a vision+automation model picks the next browser action.',
+ 'Flow: Google OAuth and claude.ai login until Claude CLI localhost callback issues a refresh token.',
+ '',
+ `Stall reason: ${stallReason}`,
+ `URL: ${url || '(unknown)'}`,
+ '',
+ 'DOM summary (truncated):',
+ dom || '(empty)',
+ '',
+ 'Return ONLY valid JSON, no markdown fences:',
+ '{ "tools": [ ... ] }',
+ '',
+ 'Each tool is ONE of:',
+ '- { "tool": "context7", "libraryName": "short name for ctx7 library command", "libraryQuery": "disambiguation / ranking query for ctx7 library", "docsQuery": "specific documentation question after library resolves" }',
+ ' Use for library docs: Playwright, OAuth2, Google sign-in, Anthropic, AWS Bedrock, etc.',
+ '- { "tool": "web_search", "query": "focused query for product errors, new UI strings, time-sensitive messages" }',
+ '',
+ 'Rules:',
+ '- If no lookup helps, return { "tools": [] }.',
+ `- At most ${MAX_RESEARCH_TOOLS} tools.`,
+ '- Prefer context7 for API/framework facts; web_search for volatile UI/errors.',
+ ].join('\n');
+
+ const planMessages = toBedrockMessages([{ role: 'user', content: [{ type: 'text', text: planPrompt }] }]);
+
+ const planResult = await invokeBedrockConverse(planMessages, log, {
+ inferenceConfig: { maxTokens: 700, temperature: 0.1 },
+ timeoutMs: RESEARCH_PLANNER_TIMEOUT_MS,
+ modelIds: plannerModelChain(),
+ });
+
+ if (!planResult.ok) {
+ log('research planner failed; continuing without appendix');
+ return '';
}
- // macOS keychain — account name = current OS user (matches rotate.mjs convention)
- const kcAccount = process.env.USER || process.env.LOGNAME || 'claude-ops';
- const kc = readCommand(['security', 'find-generic-password', '-s', 'anthropic-api-key', '-a', kcAccount, '-w'], 2000);
- if (kc.startsWith('sk-ant-')) return kc;
- return null;
+
+ const planText = extractBedrockText(planResult.data || {});
+ const plan = parseResearchPlan(planText);
+ if (!plan?.tools?.length) return '';
+
+ const sections = [];
+ const tools = plan.tools.slice(0, MAX_RESEARCH_TOOLS);
+ for (let i = 0; i < tools.length; i++) {
+ const t = tools[i];
+ if (t.tool === 'context7' && t.libraryName && t.libraryQuery && t.docsQuery) {
+ log(`research [${i + 1}/${tools.length}] context7: ${t.libraryName}`);
+ const out = await runContext7Tool(t, log);
+ if (out) sections.push(out);
+ } else if (t.tool === 'web_search' && t.query.trim()) {
+ log(`research [${i + 1}/${tools.length}] web_search`);
+ const out = await runWebSearchTool(t.query, log);
+ if (out) sections.push(out);
+ }
+ }
+
+ return sections.join('\n\n---\n\n').slice(0, MAX_RESEARCH_APPENDIX_CHARS);
}
// ── Snapshot: screenshot + structured DOM summary ────────────────────────────
@@ -146,7 +448,7 @@ async function snapshotPage(page) {
}
// ── Prompt builder ────────────────────────────────────────────────────────────
-function buildPrompt(snapshot, account, attempt, history, stallReason) {
+function buildPrompt(snapshot, account, attempt, history, stallReason, researchAppendix = '') {
const orgHint = account.orgName
? `Target Claude org/workspace: ${account.orgName}`
: 'Target Claude org/workspace: Personal (default)';
@@ -161,6 +463,13 @@ function buildPrompt(snapshot, account, attempt, history, stallReason) {
'Page snapshot (DOM summary):',
snapshot.domSummary,
'',
+ researchAppendix
+ ? [
+ 'External research (Context7 documentation and/or web search — use to choose the action; do not paste raw URLs into your JSON):',
+ researchAppendix,
+ '',
+ ].join('\n')
+ : '',
history.length
? `Previous AI-brain decisions this rotation:\n${history.map((h, i) => ` ${i + 1}. ${h}`).join('\n')}`
: 'No prior AI-brain decisions yet.',
@@ -186,16 +495,10 @@ function buildPrompt(snapshot, account, attempt, history, stallReason) {
}
function parseActionJson(text) {
- if (!text) return null;
- let cleaned = text.trim();
- cleaned = cleaned
- .replace(/^```(?:json|JSON)?\s*/i, '')
- .replace(/```\s*$/i, '')
- .trim();
- const m = cleaned.match(/\{[\s\S]*\}/);
- if (!m) return null;
+ const raw = extractFirstJsonObject(text);
+ if (!raw) return null;
try {
- return JSON.parse(m[0]);
+ return JSON.parse(raw);
} catch {
return null;
}
@@ -204,17 +507,17 @@ function parseActionJson(text) {
// ── Public: ask Claude what to do ─────────────────────────────────────────────
export async function askAIBrain({ page, account, history, stallReason, logger }) {
const log = logger || ((m) => console.error(`[ai-brain] ${m}`));
- const apiKey = resolveApiKey();
- if (!apiKey) {
- log('no ANTHROPIC_API_KEY available (env, Doppler, keychain all empty)');
- return { action: 'abort', reason: 'no_api_key' };
- }
+
const attempt = history.length + 1;
if (attempt > MAX_DECISIONS) {
return { action: 'abort', reason: `decision_cap_${MAX_DECISIONS}` };
}
const snap = await snapshotPage(page);
- const prompt = buildPrompt(snap, account, attempt, history, stallReason);
+ const researchAppendix = await gatherResearchAppendix(
+ { stallReason, url: snap.url, domSummary: snap.domSummary },
+ log,
+ );
+ const prompt = buildPrompt(snap, account, attempt, history, stallReason, researchAppendix);
const content = [];
if (snap.screenshotB64) {
@@ -229,40 +532,32 @@ export async function askAIBrain({ page, account, history, stallReason, logger }
}
content.push({ type: 'text', text: prompt });
- const model = process.env.CLAUDE_ROTATOR_BRAIN_MODEL || DEFAULT_MODEL;
- log(`asking ${model} (attempt ${attempt}/${MAX_DECISIONS}) — stall: ${stallReason}`);
-
try {
- const res = await fetch(API_URL, {
- method: 'POST',
- headers: {
- 'x-api-key': apiKey,
- 'anthropic-version': '2023-06-01',
- 'content-type': 'application/json',
- },
- body: JSON.stringify({
- model,
- max_tokens: 400,
- messages: [{ role: 'user', content }],
- }),
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
+ const result = await invokeBedrockConverse(toBedrockMessages([{ role: 'user', content }]), log, {
+ inferenceConfig: { maxTokens: 400, temperature: 0 },
+ timeoutMs: REQUEST_TIMEOUT_MS,
});
- const data = await res.json().catch(() => ({}));
- if (!res.ok) {
- const reason = data?.error?.message || data?.error?.type || `http_${res.status}`;
- log(`api error: ${String(reason).slice(0, 160)}`);
+
+ if (!result.ok && result.status === 0) {
+ log('no AWS credentials for Bedrock — cannot run AI brain');
+ return { action: 'abort', reason: 'no_credentials' };
+ }
+
+ if (!result.ok) {
+ const data = result.data || {};
+ const reason = data?.message || data?.error?.message || data?.error?.type || `http_${result.status}`;
+ log(`bedrock error: ${String(reason).slice(0, 160)}`);
return {
action: 'abort',
- reason: `api_error: ${String(reason).slice(0, 80)}`,
+ reason: `bedrock_error: ${String(reason).slice(0, 80)}`,
};
}
- const text = (data?.content || [])
- .map((p) => p?.text || '')
- .join('')
- .trim();
+
+ const text = extractBedrockText(result.data || {});
+
const action = parseActionJson(text);
- if (!action || !action.action) {
- log(`unparseable response: ${text.slice(0, 120)}`);
+ if (!action?.action) {
+ log(`unparseable response from bedrock: ${text.slice(0, 120)}`);
return { action: 'abort', reason: 'unparseable_response' };
}
log(
@@ -278,9 +573,32 @@ export async function askAIBrain({ page, account, history, stallReason, logger }
}
}
+// Code-level URL allowlist — prompt constraints alone are insufficient.
+const GOTO_ALLOWED_HOST_SUFFIXES = [
+ 'claude.ai',
+ 'accounts.google.com',
+ 'myaccount.google.com',
+ 'login.microsoftonline.com',
+];
+
+function isAllowedAIGotoUrl(raw) {
+ let u;
+ try {
+ u = new URL(String(raw));
+ } catch {
+ return false;
+ }
+ if (u.protocol !== 'https:') return false;
+ const host = u.hostname.toLowerCase();
+ for (const suffix of GOTO_ALLOWED_HOST_SUFFIXES) {
+ if (host === suffix || host.endsWith(`.${suffix}`)) return true;
+ }
+ return false;
+}
+
// ── Execute the returned action against the existing driver ──────────────────
export async function executeAIAction(driver, action, { googlePassword } = {}) {
- if (!action || !action.action) return false;
+ if (!action?.action) return false;
try {
switch (action.action) {
case 'click': {
@@ -297,17 +615,7 @@ export async function executeAIAction(driver, action, { googlePassword } = {}) {
return await driver.fillInput(sel, googlePassword);
}
case 'goto': {
- if (!action.url) return false;
- // Code-level URL allowlist — prompt constraints alone are insufficient
- const allowedHosts = ['claude.ai', 'accounts.google.com', 'myaccount.google.com', 'login.microsoftonline.com'];
- try {
- const host = new URL(action.url).hostname;
- if (!allowedHosts.some((d) => host === d || host.endsWith('.' + d))) {
- return false;
- }
- } catch {
- return false;
- }
+ if (!action.url || !isAllowedAIGotoUrl(action.url)) return false;
await driver.goto(action.url);
return true;
}
@@ -315,7 +623,6 @@ export async function executeAIAction(driver, action, { googlePassword } = {}) {
await new Promise((r) => setTimeout(r, 4000));
return true;
}
- case 'abort':
default:
return false;
}
@@ -325,3 +632,155 @@ export async function executeAIAction(driver, action, { googlePassword } = {}) {
}
export const AI_BRAIN_MAX_DECISIONS = MAX_DECISIONS;
+
+// ── Billing-page scraper ──────────────────────────────────────────────────────
+// Navigates the already-authenticated browser to console.anthropic.com/settings/billing
+// and asks Claude (vision + DOM) to extract:
+// { credits_usd, auto_reload_enabled, extra_usage_enabled }
+// Returns the parsed object, or null on any failure. NEVER throws.
+//
+// Used by rotate.mjs immediately after a successful magic-link OAuth, so the
+// scrape happens on the same Chrome session that just authenticated.
+export async function scrapeBillingState(page, logger) {
+ const log = logger || ((m) => console.error(`[billing-scrape] ${m}`));
+ if (!page) {
+ log('no page handle — skipping');
+ return null;
+ }
+
+ // Navigate. The driver may be Playwright Page or Kapture-popup-like; both
+ // expose .goto(). Wrap each step so a single failure doesn't kill the scrape.
+ try {
+ if (typeof page.goto === 'function') {
+ await page.goto('https://console.anthropic.com/settings/billing', {
+ timeout: 20_000,
+ });
+ } else {
+ log('page has no .goto — abort');
+ return null;
+ }
+ } catch (e) {
+ log(`navigate failed: ${String(e.message || e).slice(0, 100)}`);
+ return null;
+ }
+
+ // Settle. Prefer networkidle; fall back to fixed sleep.
+ try {
+ if (typeof page.waitForLoadState === 'function') {
+ await page.waitForLoadState('networkidle', { timeout: 8000 });
+ } else {
+ await new Promise((r) => setTimeout(r, 6000));
+ }
+ } catch {
+ await new Promise((r) => setTimeout(r, 2000));
+ }
+
+ // Extra dwell — billing widget often hydrates after networkidle.
+ await new Promise((r) => setTimeout(r, 2000));
+
+ // Capture screenshot + DOM innerText (full body — credits & toggles are scattered).
+ let screenshotB64 = null;
+ try {
+ const buf = await page.screenshot({
+ type: 'png',
+ fullPage: true,
+ timeout: 8000,
+ });
+ if (buf && buf.length < 1_500_000) {
+ screenshotB64 = Buffer.from(buf).toString('base64');
+ } else if (buf) {
+ // Too big — retry with viewport only
+ const viewBuf = await page.screenshot({ type: 'png', fullPage: false, timeout: 5000 }).catch(() => null);
+ if (viewBuf && viewBuf.length < 1_500_000) {
+ screenshotB64 = Buffer.from(viewBuf).toString('base64');
+ }
+ }
+ } catch (e) {
+ log(`screenshot failed: ${String(e.message || e).slice(0, 80)}`);
+ }
+
+ let domText = '';
+ try {
+ domText = await page.evaluate(() => {
+ const t = document.body?.innerText || '';
+ return t.slice(0, 8000);
+ });
+ } catch {}
+
+ if (!screenshotB64 && !domText) {
+ log('no screenshot, no DOM — abort');
+ return null;
+ }
+
+ const prompt = [
+ 'You are reading the Anthropic Console billing page (console.anthropic.com/settings/billing).',
+ 'Extract the current state of three things and return ONLY one JSON object — no prose, no markdown fences.',
+ '',
+ 'Schema: { "credits_usd": number|null, "auto_reload_enabled": boolean|null, "extra_usage_enabled": boolean|null }',
+ '',
+ 'Field meanings:',
+ "- credits_usd: the prepaid API credit balance currently on the account, in US dollars. Look for labels like 'API credits', 'Credit balance', 'Prepaid credits', '$X.XX'. If multiple credit pots are shown, sum them. If unknown, return null.",
+ "- auto_reload_enabled: true if the page shows that auto-reload / auto-refill / auto-top-up of credits is currently ON. false if it's OFF or shows a 'Set up auto-reload' CTA. null if undeterminable.",
+ "- extra_usage_enabled: true if 'Pay-per-use' / 'Pay as you go' / 'Extra usage' / 'Overage billing' / 'Use credits beyond plan' is currently enabled (toggle ON). false if explicitly OFF. null if undeterminable.",
+ '',
+ 'Be conservative: if you cannot read a value with high confidence, use null for that field rather than guessing.',
+ '',
+ 'DOM TEXT (visible body, may be truncated):',
+ domText || '(no DOM text captured)',
+ ].join('\n');
+
+ const content = [];
+ if (screenshotB64) {
+ content.push({
+ type: 'image',
+ source: {
+ type: 'base64',
+ media_type: 'image/png',
+ data: screenshotB64,
+ },
+ });
+ }
+ content.push({ type: 'text', text: prompt });
+
+ try {
+ const result = await invokeBedrockConverse(toBedrockMessages([{ role: 'user', content }]), log, {
+ inferenceConfig: { maxTokens: 400, temperature: 0 },
+ timeoutMs: REQUEST_TIMEOUT_MS,
+ });
+
+ if (!result.ok && result.status === 0) {
+ log('no AWS credentials for Bedrock — skipping');
+ return null;
+ }
+
+ if (!result.ok) {
+ const data = result.data || {};
+ const reason = data?.message || data?.error?.message || data?.error?.type || `http_${result.status}`;
+ log(`bedrock error: ${String(reason).slice(0, 160)}`);
+ return null;
+ }
+
+ const text = extractBedrockText(result.data || {});
+
+ const parsed = parseActionJson(text);
+ if (!parsed) {
+ log(`unparseable response from bedrock: ${text.slice(0, 120)}`);
+ return null;
+ }
+
+ // Coerce + sanity-check fields. Reject obviously-bogus shapes.
+ const out = {
+ credits_usd:
+ typeof parsed.credits_usd === 'number' && Number.isFinite(parsed.credits_usd) ? parsed.credits_usd : null,
+ auto_reload_enabled: typeof parsed.auto_reload_enabled === 'boolean' ? parsed.auto_reload_enabled : null,
+ extra_usage_enabled: typeof parsed.extra_usage_enabled === 'boolean' ? parsed.extra_usage_enabled : null,
+ };
+ log(
+ `extracted: credits_usd=${out.credits_usd} auto_reload=${out.auto_reload_enabled} extra_usage=${out.extra_usage_enabled}`,
+ );
+ return out;
+ } catch (e) {
+ log(`call failed: ${String(e.message || e).slice(0, 120)}`);
+ return null;
+ }
+}
diff --git a/claude-ops/scripts/account-rotation/claude-settings-mode.mjs b/claude-ops/scripts/account-rotation/claude-settings-mode.mjs
new file mode 100644
index 00000000..754ae502
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/claude-settings-mode.mjs
@@ -0,0 +1,227 @@
+/**
+ * Mutate ~/.claude/settings.json for OAuth vs Bedrock so Claude Code does not
+ * keep stale hardcoded model IDs when switching modes (daemon + rotate paths).
+ *
+ * Bedrock primary + small-fast IDs are resolved from `aws bedrock list-inference-profiles`
+ * when possible (latest Sonnet / Haiku by version rank); falls back to pinned defaults
+ * if AWS CLI fails. Set BEDROCK_SKIP_RESOLVE=1 to force defaults only.
+ */
+
+import { readFileSync, writeFileSync, renameSync } from 'fs';
+import { execFileSync } from 'child_process';
+import { join } from 'path';
+
+function claudeSettingsPath() {
+ return join(process.env.HOME || '', '.claude', 'settings.json');
+}
+
+function readSettings() {
+ try {
+ return JSON.parse(readFileSync(claudeSettingsPath(), 'utf8'));
+ } catch {
+ return {};
+ }
+}
+
+function writeSettingsAtomic(s) {
+ const p = claudeSettingsPath();
+ const tmp = `${p}.tmp.${process.pid}`;
+ writeFileSync(tmp, JSON.stringify(s, null, 2));
+ renameSync(tmp, p);
+}
+
+/** Pinned fallbacks when list-inference-profiles fails or returns nothing. */
+const BEDROCK_PRIMARY_FALLBACK = 'us.anthropic.claude-sonnet-4-6';
+const BEDROCK_SMALL_FALLBACK = 'us.anthropic.claude-haiku-4-5-20251001-v1:0';
+
+/** Map AWS region to preferred cross-region inference profile prefix. */
+export function preferredInferencePrefix(awsRegion) {
+ const r = (awsRegion || 'us-east-1').toLowerCase();
+ if (r.startsWith('us-')) return 'us.';
+ if (r.startsWith('eu-')) return 'eu.';
+ if (r.startsWith('ap-northeast')) return 'jp.';
+ if (r.startsWith('ap-southeast-2')) return 'au.';
+ return 'us.';
+}
+
+function listAllInferenceProfilesSync(region) {
+ const summaries = [];
+ let startingToken;
+ for (;;) {
+ const args = [
+ 'bedrock',
+ 'list-inference-profiles',
+ '--region',
+ region,
+ '--type-equals',
+ 'SYSTEM_DEFINED',
+ '--output',
+ 'json',
+ ];
+ if (startingToken) args.push('--starting-token', startingToken);
+ const out = execFileSync('aws', args, {
+ encoding: 'utf8',
+ maxBuffer: 32 * 1024 * 1024,
+ timeout: 60_000,
+ });
+ const data = JSON.parse(out);
+ summaries.push(...(data.inferenceProfileSummaries || []));
+ startingToken = data.NextToken;
+ if (!startingToken) break;
+ }
+ return summaries;
+}
+
+function rankCompareDesc(ra, rb) {
+ const n = Math.max(ra.length, rb.length);
+ for (let i = 0; i < n; i++) {
+ const a = ra[i] ?? 0;
+ const b = rb[i] ?? 0;
+ if (a !== b) return b - a;
+ }
+ return 0;
+}
+
+function sonnetRank(inferenceProfileId) {
+ const m = inferenceProfileId.match(/\.anthropic\.claude-sonnet-(.+)$/);
+ if (!m) return [-1];
+ const tail = m[1].replace(/-v\d+:\d+$/i, '');
+ // Order matters: `4-20250514` must not match as major-minor (second group YYYYMMDD).
+ let mm = tail.match(/^(\d+)-(\d+)-(\d{8})$/);
+ if (mm) {
+ return [parseInt(mm[1], 10), parseInt(mm[2], 10), parseInt(mm[3], 10)];
+ }
+ mm = tail.match(/^(\d+)-(\d{8})$/);
+ if (mm) return [parseInt(mm[1], 10), 0, parseInt(mm[2], 10)];
+ mm = tail.match(/^(\d+)-(\d+)$/);
+ if (mm) {
+ const second = mm[2];
+ if (/^\d{8}$/.test(second)) {
+ return [parseInt(mm[1], 10), 0, parseInt(second, 10)];
+ }
+ return [parseInt(mm[1], 10), parseInt(second, 10), 0];
+ }
+ return [0, 0, 0];
+}
+
+function haikuRank(inferenceProfileId) {
+ let m = inferenceProfileId.match(/\.anthropic\.claude-haiku-(\d+)-(\d+)-(\d{8})/);
+ if (m) {
+ return [parseInt(m[1], 10), parseInt(m[2], 10), parseInt(m[3], 10)];
+ }
+ m = inferenceProfileId.match(/\.anthropic\.claude-3-5-haiku-(\d{8})/);
+ if (m) return [3, 5, parseInt(m[1], 10)];
+ m = inferenceProfileId.match(/\.anthropic\.claude-3-haiku-(\d{8})/);
+ if (m) return [3, 0, parseInt(m[1], 10)];
+ return [-1, 0, 0];
+}
+
+function isActiveSystem(p) {
+ return p?.type === 'SYSTEM_DEFINED' && p?.status === 'ACTIVE' && p?.inferenceProfileId;
+}
+
+function candidatesWithPrefix(profiles, prefix, predicate) {
+ const active = profiles.filter((p) => isActiveSystem(p) && predicate(p.inferenceProfileId));
+ const pref = active.filter((p) => p.inferenceProfileId.startsWith(prefix));
+ if (pref.length) return pref;
+ const glob = active.filter((p) => p.inferenceProfileId.startsWith('global.'));
+ if (glob.length) return glob;
+ return active;
+}
+
+function pickLatestSonnet(profiles, prefix) {
+ const c = candidatesWithPrefix(profiles, prefix, (id) => id.includes('.anthropic.claude-sonnet-'));
+ if (!c.length) return null;
+ c.sort((x, y) => rankCompareDesc(sonnetRank(x.inferenceProfileId), sonnetRank(y.inferenceProfileId)));
+ return c[0].inferenceProfileId;
+}
+
+function pickLatestHaiku(profiles, prefix) {
+ const c = candidatesWithPrefix(profiles, prefix, (id) => {
+ if (id.includes('.anthropic.claude-haiku-')) return haikuRank(id)[0] >= 0;
+ if (id.includes('.anthropic.claude-3-') && id.includes('haiku')) return true;
+ return false;
+ });
+ if (!c.length) return null;
+ c.sort((x, y) => rankCompareDesc(haikuRank(x.inferenceProfileId), haikuRank(y.inferenceProfileId)));
+ return c[0].inferenceProfileId;
+}
+
+/**
+ * Resolve latest Bedrock inference profile IDs for Claude Code (Sonnet + Haiku).
+ * @param {string} region - AWS region for `list-inference-profiles` (e.g. us-east-1)
+ * @returns {{ primary: string, small: string, source: 'api' | 'fallback', detail?: string }}
+ */
+export function resolveBedrockClaudeModelIds(region = 'us-east-1') {
+ if (process.env.BEDROCK_SKIP_RESOLVE === '1') {
+ return {
+ primary: BEDROCK_PRIMARY_FALLBACK,
+ small: BEDROCK_SMALL_FALLBACK,
+ source: 'fallback',
+ detail: 'BEDROCK_SKIP_RESOLVE',
+ };
+ }
+ try {
+ const profiles = listAllInferenceProfilesSync(region);
+ const prefix = preferredInferencePrefix(region);
+ const primary = pickLatestSonnet(profiles, prefix);
+ const small = pickLatestHaiku(profiles, prefix);
+ if (primary && small) {
+ return { primary, small, source: 'api' };
+ }
+ return {
+ primary: primary || BEDROCK_PRIMARY_FALLBACK,
+ small: small || BEDROCK_SMALL_FALLBACK,
+ source: 'fallback',
+ detail: primary ? 'missing-haiku' : small ? 'missing-sonnet' : 'missing-both',
+ };
+ } catch (e) {
+ return {
+ primary: BEDROCK_PRIMARY_FALLBACK,
+ small: BEDROCK_SMALL_FALLBACK,
+ source: 'fallback',
+ detail: (e.message || String(e)).slice(0, 200),
+ };
+ }
+}
+
+/** Match use-bedrock.sh: Bedrock env + strip top-level model lists (OAuth catalog ids break Bedrock). */
+export function persistBedrockClaudeSettings(region = 'us-east-1') {
+ const { primary, small } = resolveBedrockClaudeModelIds(region);
+ const s = readSettings();
+ const env = s.env && typeof s.env === 'object' ? { ...s.env } : {};
+ env.CLAUDE_CODE_USE_BEDROCK = '1';
+ env.AWS_BEDROCK_REGION = region;
+ env.AWS_REGION = region;
+ env.ANTHROPIC_MODEL = primary;
+ env.ANTHROPIC_SMALL_FAST_MODEL = small;
+ delete env.ANTHROPIC_API_KEY;
+ delete env.ANTHROPIC_AUTH_TOKEN;
+ delete env.ANTHROPIC_BASE_URL;
+ s.env = env;
+ delete s.model;
+ delete s.availableModels;
+ writeSettingsAtomic(s);
+}
+
+/** Match use-oauth.sh: no hardcoded models — Claude Code loads subscription catalog from API. */
+export function clearHardcodedModelsForOAuthClaudeSettings() {
+ const s = readSettings();
+ const env = s.env && typeof s.env === 'object' ? { ...s.env } : {};
+ for (const k of [
+ 'CLAUDE_CODE_USE_BEDROCK',
+ 'AWS_BEDROCK_REGION',
+ 'AWS_REGION',
+ 'ANTHROPIC_API_KEY',
+ 'ANTHROPIC_AUTH_TOKEN',
+ 'ANTHROPIC_BASE_URL',
+ 'ANTHROPIC_MODEL',
+ 'ANTHROPIC_SMALL_FAST_MODEL',
+ ]) {
+ delete env[k];
+ }
+ s.env = env;
+ delete s.model;
+ delete s.availableModels;
+ writeSettingsAtomic(s);
+}
diff --git a/claude-ops/scripts/account-rotation/config.example.json b/claude-ops/scripts/account-rotation/config.example.json
index 5eab5e2a..663c7181 100644
--- a/claude-ops/scripts/account-rotation/config.example.json
+++ b/claude-ops/scripts/account-rotation/config.example.json
@@ -18,7 +18,8 @@
"messagesPerWindow": 900,
"weeklyCapMultiplier": 1.0,
"extraUsageSafetyMargin": 0.75,
- "note": "Max 20x defaults: ~220K tokens / ~900 messages per 5h window. extraUsageSafetyMargin: accounts with paid overage enabled rotate at 75% of their threshold to avoid incurring charges."
+ "destinationMaxUtilPercent": 95,
+ "note": "Max 20x defaults: ~220K tokens / ~900 messages per 5h window. extraUsageSafetyMargin: accounts with paid overage enabled rotate at 75% of their threshold to avoid incurring charges. destinationMaxUtilPercent: refuse to rotate TO accounts with max(5h,7d) util at or above this (default 95). Use 90 if destinations near 95% still hit limits in practice."
},
"toolUseThreshold": 800,
"maxHoursPerAccount": 4,
diff --git a/claude-ops/scripts/account-rotation/daemon.mjs b/claude-ops/scripts/account-rotation/daemon.mjs
index 3ae92013..4eb94380 100644
--- a/claude-ops/scripts/account-rotation/daemon.mjs
+++ b/claude-ops/scripts/account-rotation/daemon.mjs
@@ -10,6 +10,12 @@
*
* Auto-rotates to the most cooled-down account when any threshold is hit.
*
+ * Rotation path: `node rotate.mjs --no-browser --to <key>` only (keychain swap,
+ * no browser). That path does not invoke ai-brain.mjs. Full ai-brain (Bedrock
+ * Converse, stall recovery, optional Context7 + web research, billing scrape)
+ * runs inside `rotate.mjs` when a browser OAuth flow is used — e.g. force-rotate.sh
+ * after fast path fails, `node rotate.mjs --magic-link --force --to …`, or setup --auto.
+ *
* Usage:
* node daemon.mjs # Run in foreground
* node daemon.mjs --bg # Daemonize
@@ -18,6 +24,7 @@
*/
import { readFileSync, writeFileSync, existsSync, unlinkSync, appendFileSync, statSync } from 'fs';
+import { persistBedrockClaudeSettings, clearHardcodedModelsForOAuthClaudeSettings } from './claude-settings-mode.mjs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { execSync, execFileSync, spawn } from 'child_process';
@@ -435,15 +442,153 @@ async function findValidRotationTarget(config, state) {
}
log(`[pre-rotate] ${key}: live util 5h=${live.pct5h.toFixed(0)}% 7d=${live.pct7d.toFixed(0)}% — OK`);
} else {
- log(`[pre-rotate] ${key}: live util query failed — accepting anyway`);
+ // Live query failed (Anthropic 429 or network). DO NOT accept blindly —
+ // that's how we picked an exhausted account and bricked Sam's session.
+ // Fall back to cached util; refuse if cached is unknown OR >=90%.
+ const cached = state.accounts?.[key]?.lastUtilization;
+ const cachedPct = cached?.pct;
+ const cachedAge = cached?.ts ? (now - cached.ts) / 60_000 : Infinity;
+ if (cachedPct == null) {
+ log(`[pre-rotate] ${key}: live query FAILED + no cache — REFUSING`);
+ continue;
+ }
+ if (cachedPct >= 90) {
+ log(
+ `[pre-rotate] ${key}: live query FAILED + cached ${cachedPct.toFixed(0)}% (${cachedAge.toFixed(0)}min old) — REFUSING`,
+ );
+ continue;
+ }
+ if (cachedAge > 30) {
+ log(`[pre-rotate] ${key}: live query FAILED + cache stale (${cachedAge.toFixed(0)}min) — REFUSING (safety)`);
+ continue;
+ }
+ log(
+ `[pre-rotate] ${key}: live query failed but cached ${cachedPct.toFixed(0)}% (${cachedAge.toFixed(0)}min old) — accepting`,
+ );
}
return account;
}
+ // SECOND PASS: strict bar (70%/95%) excluded everyone. Try a relaxed bar
+ // (94%/94%) so we still rotate to "warm but not exhausted" rather than
+ // stalling. Only Bedrock fallback when even the relaxed bar fails.
+ log('[pre-rotate] strict-bar pass empty — trying relaxed (sub-95%) bar');
+ const RELAXED_BAR = 94;
+ for (const account of candidates) {
+ const key = accountKey(account);
+ const tokenJson = readStoredToken(account);
+ if (!tokenJson) continue;
+ const live = await queryLiveUtilization(account);
+ if (!live) continue;
+ const max = Math.max(live.pct5h, live.pct7d);
+ if (max < RELAXED_BAR) {
+ log(`[pre-rotate-relaxed] ${key}: 5h=${live.pct5h.toFixed(0)}% 7d=${live.pct7d.toFixed(0)}% — accepting`);
+ return account;
+ }
+ }
return null; // No valid candidate found
}
+// Exhaustion check across ALL non-active, non-disabled accounts.
+// Two acceptance modes:
+// 1. LIVE-confirmed: every candidate live-queried >= 95% (preferred).
+// 2. CACHED-evidence: when API is throttling us (live fails) BUT every
+// candidate has fresh (<15min) cached util >= 95% AND a recent rate-limit
+// signal exists, we accept cached evidence — refusing to fall back when
+// Anthropic API is dead would just leave Sam stuck.
+async function allCandidatesExhausted(config, state) {
+ const EXHAUSTED_THRESHOLD = 95;
+ const now = Date.now();
+ const activeKey = state.activeAccount;
+ const candidates = config.accounts.filter((a) => accountKey(a) !== activeKey && a.disabled !== true);
+ if (candidates.length === 0) return false;
+
+ let liveOk = true;
+ let allLiveExhausted = true;
+ for (const a of candidates) {
+ const live = await queryLiveUtilization(a);
+ if (!live) {
+ liveOk = false;
+ break;
+ }
+ if (Math.max(live.pct5h, live.pct7d) < EXHAUSTED_THRESHOLD) {
+ allLiveExhausted = false;
+ break;
+ }
+ }
+ if (liveOk && allLiveExhausted) return true;
+
+ // CACHED fallback: only when we have recent rate-limit evidence
+ let recentRateLimit = false;
+ try {
+ if (existsSync(RATE_LIMITS_FILE)) {
+ const rl = JSON.parse(readFileSync(RATE_LIMITS_FILE, 'utf8'));
+ const age = now - new Date(rl.timestamp || rl.ts || 0).getTime();
+ if (age < 5 * 60_000) recentRateLimit = true;
+ }
+ } catch {}
+ if (!recentRateLimit) return false;
+
+ // All cached >=95% AND fresh? Then we're truly stuck.
+ for (const a of candidates) {
+ const cached = state.accounts?.[accountKey(a)]?.lastUtilization;
+ if (!cached?.pct || !cached?.ts) return false;
+ if (now - cached.ts > 15 * 60_000) return false;
+ if (cached.pct < EXHAUSTED_THRESHOLD) return false;
+ }
+ log(
+ '[allCandidatesExhausted] cached-evidence path: live unreachable but cached + rate-limit signal confirm exhaustion',
+ );
+ return true;
+}
+
+// Activate Bedrock fallback from inside daemon. Probes AWS reachability,
+// writes the sentinel + sends a desktop notification. Returns true on success.
+function activateBedrockFallbackFromDaemon(reason) {
+ const region = process.env.AWS_BEDROCK_REGION || 'us-east-1';
+ try {
+ execFileSync('aws', ['sts', 'get-caller-identity', '--output', 'json'], {
+ stdio: 'pipe',
+ timeout: 5000,
+ });
+ execFileSync('aws', ['bedrock', 'list-inference-profiles', '--region', region, '--max-results', '1'], {
+ stdio: 'pipe',
+ timeout: 6000,
+ });
+ } catch (e) {
+ log(`[bedrock-fallback] AWS unreachable: ${(e.message || '').slice(0, 80)}`);
+ notify('Bedrock Fallback FAILED', 'aws sts/bedrock unreachable — manual intervention needed');
+ return false;
+ }
+ try {
+ const sentinel = join(process.env.HOME || '', '.claude', '.bedrock-fallback.json');
+ const payload = {
+ activated_at: new Date().toISOString(),
+ reason,
+ region,
+ available: true,
+ activated_by: 'daemon',
+ };
+ writeFileSync(sentinel, JSON.stringify(payload, null, 2));
+ try {
+ persistBedrockClaudeSettings(region);
+ log(`[bedrock-fallback] settings.json → Bedrock env (${region})`);
+ } catch (e) {
+ log(`[bedrock-fallback] settings persist failed: ${e.message?.slice(0, 80)}`);
+ }
+ log(`[bedrock-fallback] ACTIVATED region=${region} reason=${reason}`);
+ notify(
+ 'Bedrock Fallback Active',
+ `All Anthropic accounts exhausted (live-confirmed) — switched to Bedrock (${region}). New sessions: source use-bedrock.sh`,
+ );
+ return true;
+ } catch (e) {
+ log(`[bedrock-fallback] write error: ${e.message?.slice(0, 80)}`);
+ return false;
+ }
+}
+
async function doRotation(reason) {
const lockFile = join(__dirname, '.rotating');
// Lock format written by rotate.mjs: `<ISO timestamp>\n<pid>`. If the holder
@@ -483,7 +628,14 @@ async function doRotation(reason) {
if (!target) {
log('ROTATION ABORTED: no candidate has a valid or refreshable token');
- notify('Account Rotation', 'ABORTED — all candidate tokens expired/invalid');
+ // Live-confirm exhaustion before flipping to Bedrock — Sam's rule.
+ const exhausted = await allCandidatesExhausted(config, state);
+ if (exhausted) {
+ log('All candidates LIVE-CONFIRMED exhausted (>=95%) — engaging Bedrock fallback');
+ activateBedrockFallbackFromDaemon(`auto_rotation: ${reason}`);
+ } else {
+ notify('Account Rotation', 'ABORTED — all candidate tokens expired/invalid');
+ }
return;
}
@@ -649,6 +801,8 @@ async function mainLoop() {
let lastStatusLog = 0; // periodic status logging
let lastRefreshCheck = 0; // dynamic refresh check
let lastDriftCheck = 0; // cheap vault-based drift detection
+ let lastBedrockRecoveryCheck = 0; // poll for OAuth recovery while sentinel exists
+ let bedrockRecoveryRoundRobin = 0; // round-robin index across accounts
while (true) {
try {
@@ -691,6 +845,59 @@ async function mainLoop() {
// findValidRotationTarget refreshes candidates lazily). Avoids keychain
// churn that was disconnecting HTTP MCP sessions every 5 min.
+ // Bedrock recovery watcher — when the sentinel exists, round-robin
+ // probe ONE account per minute (avoid 429 spam). When any account drops
+ // below 70% util AND has a valid token, delete the sentinel + auto-rotate
+ // keychain to it + notify Sam to exit Bedrock shells.
+ const sentinelPath = join(process.env.HOME || '', '.claude', '.bedrock-fallback.json');
+ if (existsSync(sentinelPath) && Date.now() - lastBedrockRecoveryCheck > 60_000) {
+ lastBedrockRecoveryCheck = Date.now();
+ const allAccts = config.accounts.filter((a) => a.disabled !== true);
+ if (allAccts.length > 0) {
+ const probe = allAccts[bedrockRecoveryRoundRobin % allAccts.length];
+ bedrockRecoveryRoundRobin++;
+ const probeKey = accountKey(probe);
+ const live = await queryLiveUtilization(probe);
+ if (live) {
+ const max = Math.max(live.pct5h, live.pct7d);
+ log(`[bedrock-recovery] probe ${probeKey}: 5h=${live.pct5h.toFixed(0)}% 7d=${live.pct7d.toFixed(0)}%`);
+ // Update cache
+ state.accounts = state.accounts || {};
+ state.accounts[probeKey] = state.accounts[probeKey] || {};
+ state.accounts[probeKey].lastUtilization = { pct: max, reset: null, ts: Date.now() };
+ try {
+ writeFileSync(STATE_PATH, JSON.stringify(state, null, 2));
+ } catch {}
+ if (max < 70) {
+ const tokenJson = readStoredToken(probe);
+ if (tokenJson && !tokenExpired(tokenJson)) {
+ log(`[bedrock-recovery] ${probeKey} cooled to ${max.toFixed(0)}% — exiting Bedrock fallback`);
+ try {
+ unlinkSync(sentinelPath);
+ } catch {}
+ try {
+ clearHardcodedModelsForOAuthClaudeSettings();
+ log('[bedrock-recovery] settings.json → OAuth (hardcoded models cleared)');
+ } catch (e) {
+ log(`[bedrock-recovery] settings clear failed: ${e.message?.slice(0, 80)}`);
+ }
+ notify(
+ 'OAuth Restored',
+ `${probeKey} cooled to ${max.toFixed(0)}% — settings.json cleared for OAuth; Bedrock shells: source use-oauth.sh`,
+ );
+ // Auto-rotate keychain so new sessions pick up the cooled account
+ if (state.activeAccount !== probeKey) {
+ await doRotation(`bedrock-recovery: ${probeKey} cooled to ${max.toFixed(0)}%`);
+ lastRotatedAt = Date.now();
+ }
+ } else {
+ log(`[bedrock-recovery] ${probeKey} cooled but token expired/missing — staying on Bedrock`);
+ }
+ }
+ }
+ }
+ }
+
const { should, reason } = await shouldRotate(config, state);
// Post-rotation blackout: ALL rotation triggers are suppressed for 90s
diff --git a/claude-ops/scripts/account-rotation/force-rotate.sh b/claude-ops/scripts/account-rotation/force-rotate.sh
index 407deab6..08d5fbfc 100755
--- a/claude-ops/scripts/account-rotation/force-rotate.sh
+++ b/claude-ops/scripts/account-rotation/force-rotate.sh
@@ -10,7 +10,8 @@
# Files in this directory:
# rotate.mjs - main rotation logic, holds .rotating lock (PID-tagged)
# daemon.mjs - launchd-managed monitor (com.claude-ops.account-rotation)
-# ai-brain.mjs - Haiku fallback for stuck OAuth pages
+# ai-brain.mjs - Bedrock vision for stuck OAuth; planner may call Context7 (npx ctx7)
+# + DuckDuckGo; optional billing scrape after successful OAuth
# state.json - activeAccount, lastRotation, per-account util snapshots
# config.json - account list, autoRotate toggle
# .rotating - lock file: <ISO ts>\n<pid>; auto-broken if PID dead or >15min
@@ -35,10 +36,14 @@
# up stale links from prior rotation calls (subject is identical for all).
# - Rejects emails older than the poll start (5s clock skew tolerance).
#
+# Daemon auto-rotation uses --no-browser only (no ai-brain). Browser fallback here
+# runs full rotate.mjs OAuth + ai-brain + billing scrape (needs AWS creds for Bedrock;
+# PATH must include npx for Context7 research).
+#
# OAuth stall handling:
# - Authorize button: 6 attempts × 5s = 30s, then escalates to ai-brain
# - General URL stall: 2 stagnant steps -> ai-brain
-# - ai-brain (Haiku) pulls API key from env -> Doppler -> keychain
+# - ai-brain: Bedrock Converse (not API key); optional research via CLAUDE_ROTATOR_* env
# - Max 6 ai-brain decisions per rotation
#
# Recovery from stuck state:
@@ -94,6 +99,16 @@ if [ $# -ge 1 ] && [ -n "${1:-}" ]; then
TARGET_ARG=(--to "$1")
fi
+# Preflight: live-query all accounts and print recommendation BEFORE rotating.
+# Exit code 2 from --recommend = all accounts live-confirmed exhausted.
+echo "→ Preflight: scanning live utilization..."
+node "$DIR/rotate.mjs" --recommend 2>&1 | sed 's/^/ /'
+PREFLIGHT_RC=${PIPESTATUS[0]}
+if [ "$PREFLIGHT_RC" -eq 2 ]; then
+ echo "⚠ All Anthropic accounts live-confirmed at >=95% util."
+ echo " Rotation will trigger Bedrock fallback automatically."
+fi
+
run_with_watchdog() {
# Runs a command in the background with a hard kill after $WATCHDOG_SECONDS.
# Returns the command's exit code, or 124 if the watchdog fired.
@@ -132,12 +147,12 @@ echo ""
node "$DIR/rotate.mjs" --status 2>&1 | head -40
# macOS notification
-osascript -e 'display notification "Account rotated — restart Claude Code session" with title "Claude Rotation"' 2>/dev/null
+osascript -e 'display notification "Account rotated to new keychain entry" with title "Claude Rotation"' 2>/dev/null
echo ""
if [ "$FAST_OK" -eq 1 ]; then
- echo "✅ Done (fast path). Start a new Claude Code session to use the fresh account."
+ echo "✅ Done (fast path). Token swapped in keychain — next request will pick it up."
else
- echo "✅ Done (browser fallback). Start a new Claude Code session to use the fresh account."
+ echo "✅ Done (browser fallback). Token swapped in keychain — next request will pick it up."
fi
echo " (Running sessions may still use the old token — exit and re-enter)"
diff --git a/claude-ops/scripts/account-rotation/resolve-bedrock-models.mjs b/claude-ops/scripts/account-rotation/resolve-bedrock-models.mjs
new file mode 100644
index 00000000..0d82fa17
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/resolve-bedrock-models.mjs
@@ -0,0 +1,11 @@
+#!/usr/bin/env node
+/**
+ * Emit JSON with latest Bedrock inference profile IDs for Claude Code.
+ * Usage: node resolve-bedrock-models.mjs [region]
+ * Env: AWS_BEDROCK_REGION, BEDROCK_SKIP_RESOLVE=1
+ */
+import { resolveBedrockClaudeModelIds } from './claude-settings-mode.mjs';
+
+const region = process.env.AWS_BEDROCK_REGION || process.argv[2] || 'us-east-1';
+
+console.log(JSON.stringify(resolveBedrockClaudeModelIds(region)));
diff --git a/claude-ops/scripts/account-rotation/rotate.mjs b/claude-ops/scripts/account-rotation/rotate.mjs
index f42aa352..810151ee 100644
--- a/claude-ops/scripts/account-rotation/rotate.mjs
+++ b/claude-ops/scripts/account-rotation/rotate.mjs
@@ -24,7 +24,7 @@
* node rotate.mjs --capture # save current active token (print for Dashlane)
* node rotate.mjs --session # also send /login to running iTerm2 session
* node rotate.mjs --magic-link --to <email> # re-auth via email magic link (no Google OAuth)
- * node rotate.mjs --allow-extra-usage # BYPASS extra_usage billing guard (opt-in only)
+ * Note: --allow-extra-usage is ignored if passed (legacy); extra_usage is per-org in Claude console only.
*/
import {
@@ -37,12 +37,13 @@ import {
readdirSync,
renameSync,
} from 'fs';
+import { persistBedrockClaudeSettings } from './claude-settings-mode.mjs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { execSync, execFileSync, spawnSync, spawn } from 'child_process';
import { tmpdir } from 'os';
import { createHmac } from 'node:crypto';
-import { askAIBrain, executeAIAction, AI_BRAIN_MAX_DECISIONS } from './ai-brain.mjs';
+import { askAIBrain, executeAIAction, AI_BRAIN_MAX_DECISIONS, scrapeBillingState } from './ai-brain.mjs';
const __dirname = dirname(fileURLToPath(import.meta.url));
const CONFIG_PATH = join(__dirname, 'config.json');
@@ -211,6 +212,39 @@ function accountKey(a) {
return a.label || a.email;
}
+/** After OAuth completes in the same Playwright session, scrape console billing into state. */
+async function maybeScrapeBillingAfterOAuth(driver, account, log) {
+ if (process.env.CLAUDE_ROTATOR_SKIP_BILLING_SCRAPE === '1') return;
+ const page = driver?._page;
+ if (!page || typeof page.goto !== 'function') return;
+ const key = accountKey(account);
+ try {
+ log(`[billing-scrape] console billing for ${key}...`);
+ const billing = await scrapeBillingState(page, (m) => log(m));
+ if (!billing) return;
+ const state = readState();
+ state.accounts[key] = state.accounts[key] || {};
+ const prev = state.accounts[key].lastBilling || {};
+ state.accounts[key].lastBilling = {
+ ...prev,
+ credits_usd: billing.credits_usd,
+ auto_reload_enabled: billing.auto_reload_enabled,
+ extra_usage_enabled:
+ billing.extra_usage_enabled !== null && billing.extra_usage_enabled !== undefined
+ ? billing.extra_usage_enabled === true
+ : prev.extra_usage_enabled,
+ ts: Date.now(),
+ source: 'console_scrape',
+ };
+ writeState(state);
+ log(
+ `[billing-scrape] merged credits=${billing.credits_usd} auto_reload=${billing.auto_reload_enabled} extra_usage=${billing.extra_usage_enabled}`,
+ );
+ } catch (e) {
+ log(`[billing-scrape] error: ${String(e.message || e).slice(0, 100)}`);
+ }
+}
+
// ── Live utilization query ────────────────────────────────────────────────────
// Query all accounts in parallel — best-effort, uses cached fallback.
@@ -295,21 +329,45 @@ async function queryAllUtilization(config) {
return map;
}
+// Active account is excluded from pickNextAccount pools, so when every *other*
+// account is over the destination utilization cap, pick returns null even though the current
+// session is already on the only healthy Max account.
+function destinationUtilHardBlock(config) {
+ const v = config.rateLimits?.destinationMaxUtilPercent;
+ if (typeof v === 'number' && v > 0 && v <= 100) return v;
+ return 95;
+}
+
+function currentActiveIsOnlyViableTarget(config, state, liveUtil) {
+ const activeKey = state.activeAccount;
+ if (!activeKey) return false;
+ const activeAcc = config.accounts.find((a) => accountKey(a) === activeKey);
+ if (!activeAcc || activeAcc.disabled === true) return false;
+ const key = accountKey(activeAcc);
+ const live = liveUtil[key];
+ const u5 = live?.five_hour_pct;
+ const u7 = live?.seven_day_pct;
+ if (u5 == null || u7 == null) return false;
+ const cap = destinationUtilHardBlock(config);
+ return Math.max(u5, u7) < cap;
+}
+
// liveUtil: optional map from queryAllUtilization() — key → { five_hour_pct, ... }
-function pickNextAccount(config, state, liveUtil = {}, opts = {}) {
+function pickNextAccount(config, state, liveUtil = {}) {
const activeKey = state.activeAccount;
const windowMs = (config.rateLimits?.windowHours || 5) * 3_600_000;
const now = Date.now();
- // Hard block: account has Anthropic-side extra-usage (pay-per-use overage) enabled.
- // Rotating to such an account risks credit-card charges when the weekly cap is hit.
- // Override with opts.allowExtraUsage=true (CLI flag --allow-extra-usage) only when
- // the user has explicitly opted in for this run.
- const allowExtraUsage = opts.allowExtraUsage === true;
+ // extra_usage is informational only — manage pay-per-use per org in the Claude console;
+ // it does not affect who we can rotate to.
function hasExtraUsageEnabled(a) {
const key = accountKey(a);
const live = liveUtil[key];
- return live && live.extra_usage_enabled === true;
+ if (live && live.extra_usage_enabled === true) return true;
+ // Fallback to last-known extra_usage state from state.json
+ const cached = state.accounts?.[key]?.lastBilling?.extra_usage_enabled;
+ if (cached === true) return true;
+ return false;
}
// Check if an account's quota window has been exhausted (local tool-use tracking)
@@ -355,35 +413,36 @@ function pickNextAccount(config, state, liveUtil = {}, opts = {}) {
return null;
}
- // Score: max of (5h, 7d) — an account is only viable if BOTH windows have
- // headroom. Unknown util → 50 (neutral). Lower is better.
+ // Score: max of (5h, 7d) — both windows must be known or we penalize heavily.
+ // Never treat a missing window as 0%: old bug was max(0, null→0)=0, so an account
+ // with live 7d=100% but a transient live miss became "best" pick via stale 5h cache.
function score(a) {
const u5 = getUtil5h(a);
const u7 = getUtil7d(a);
if (u5 === null && u7 === null) return 50;
- return Math.max(u5 ?? 0, u7 ?? 0);
+ if (u5 === null || u7 === null) return 100;
+ return Math.max(u5, u7);
}
- // Log + hard-exclude accounts with extra_usage enabled (pay-per-use overage billing).
- // These are the accounts that silently charge your credit card when the weekly cap
- // is exceeded. Unless --allow-extra-usage was passed, we refuse to rotate to them.
const extraUsageAccounts = config.accounts.filter(hasExtraUsageEnabled);
if (extraUsageAccounts.length > 0) {
log(
`⚠ EXTRA USAGE ENABLED on ${extraUsageAccounts.length} account(s): ${extraUsageAccounts
.map((a) => accountKey(a))
- .join(', ')} — these can incur overage charges. Disable at console.anthropic.com/settings/billing.`,
+ .join(', ')} — overage billing possible; manage per org in console (rotation is not blocked).`,
);
}
- const excludeKey = (a) =>
- a.disabled === true || accountKey(a) === activeKey || (!allowExtraUsage && hasExtraUsageEnabled(a));
+ const excludeKey = (a) => a.disabled === true || accountKey(a) === activeKey;
- // Separate normal and low-priority, excluding current active + extra-usage accounts
+ // Separate normal and low-priority, excluding current active only
const normal = config.accounts.filter((a) => a.priority !== 'low' && !excludeKey(a));
const low = config.accounts.filter((a) => a.priority === 'low' && !excludeKey(a));
- const UTIL_HARD_BLOCK = 90; // Skip accounts at/above this util% if possible
+ // Hard refusal for rotation *destination*: max(5h,7d) must stay below this.
+ // Default 95 (matches EXHAUSTED for Bedrock). Lower with
+ // rateLimits.destinationMaxUtilPercent (e.g. 90) if 90% 5h still feels empty in practice.
+ const UTIL_HARD_BLOCK = destinationUtilHardBlock(config);
for (const pool of [normal, low]) {
const fresh = pool.filter((a) => !isExhausted(a));
@@ -391,12 +450,10 @@ function pickNextAccount(config, state, liveUtil = {}, opts = {}) {
for (const candidates of [fresh, exhausted]) {
const viable = candidates.filter((a) => score(a) < UTIL_HARD_BLOCK);
- const blocked = candidates.filter((a) => score(a) >= UTIL_HARD_BLOCK);
const sorted = [...viable].sort((a, b) => score(a) - score(b));
- const pool2 = sorted.length ? sorted : [...blocked].sort((a, b) => score(a) - score(b));
- if (pool2.length > 0) {
- const best = pool2[0];
+ if (sorted.length > 0) {
+ const best = sorted[0];
const u5 = getUtil5h(best);
const u7 = getUtil7d(best);
const src = liveUtil[accountKey(best)]
@@ -404,19 +461,135 @@ function pickNextAccount(config, state, liveUtil = {}, opts = {}) {
: state.accounts[accountKey(best)]?.lastUtilization
? 'cached'
: 'unknown';
- const utilStr = ` 5h=${u5 ?? '?'}% 7d=${u7 ?? '?'}% [${src}]`;
- if (score(best) >= UTIL_HARD_BLOCK) {
- log(`WARNING: All candidates near limit — rotating to ${accountKey(best)}${utilStr}`);
- } else {
- log(`Picked ${accountKey(best)}${utilStr}`);
- }
+ log(`Picked ${accountKey(best)} 5h=${u5 ?? '?'}% 7d=${u7 ?? '?'}% [${src}]`);
return best;
}
}
}
+ // Already on the only account with API headroom (non-active pool is empty of viable targets).
+ if (activeKey && currentActiveIsOnlyViableTarget(config, state, liveUtil)) {
+ const aa = config.accounts.find((a) => accountKey(a) === activeKey);
+ const u5 = aa ? getUtil5h(aa) : null;
+ const u7 = aa ? getUtil7d(aa) : null;
+ log(
+ `Only viable Max account is already active (${activeKey}, 5h=${u5 ?? '?'}% 7d=${u7 ?? '?'}%) — no rotation target (others exceed ${UTIL_HARD_BLOCK}% max(5h,7d) destination cap or tool-window exhausted).`,
+ );
+ return null;
+ }
+ // All non-active candidates exceed UTIL_HARD_BLOCK — refuse to pick. Caller handles
+ // Bedrock fallback. Sam's rule: never rotate to an account that will
+ // immediately say token-limit-reached.
+ log(
+ `All non-active candidates score ≥${UTIL_HARD_BLOCK}% max(5h,7d) (or pool empty) — refusing to pick (use Bedrock fallback)`,
+ );
return null;
}
+// ── Smart recommend / Bedrock fallback ────────────────────────────────────────
+// "Will immediately say token-limit-reached" guard. Anything at/above this
+// 5h or 7d util is refused as a rotation target.
+const EXHAUSTED_THRESHOLD = 95;
+
+/** True when every non-active account with complete live util is at/above destination cap (no swap target). */
+function allNonActiveLiveConfirmedOverDestinationCap(config, state, liveUtil) {
+ const destCap = destinationUtilHardBlock(config);
+ const activeKey = state.activeAccount;
+ const others = config.accounts.filter((a) => a.disabled !== true && accountKey(a) !== activeKey);
+ if (others.length === 0) return false;
+ let nConfirmed = 0;
+ for (const a of others) {
+ const u = liveUtil[accountKey(a)];
+ if (!u || u.five_hour_pct == null || u.seven_day_pct == null) continue;
+ nConfirmed++;
+ if (Math.max(u.five_hour_pct, u.seven_day_pct) < destCap) return false;
+ }
+ return nConfirmed > 0;
+}
+
+// Returns { pick, allExhausted, allHaveLive, onlyActiveViable, destinationCapStuck } using LIVE util only.
+// allExhausted is true ONLY when every viable candidate has live data AND
+// max(5h,7d) >= EXHAUSTED_THRESHOLD. Per Sam's rule: never assume exhaustion
+// from cached / unknown data — Bedrock fallback must be live-confirmed.
+function recommendAccount(config, state, liveUtil) {
+ const candidates = config.accounts.filter((a) => a.disabled !== true);
+ const pick = pickNextAccount(config, state, liveUtil);
+ const onlyActiveViable = !pick && currentActiveIsOnlyViableTarget(config, state, liveUtil);
+ const allHaveLive =
+ candidates.length > 0 &&
+ candidates.every((a) => {
+ const u = liveUtil[accountKey(a)];
+ return u && u.five_hour_pct != null && u.seven_day_pct != null;
+ });
+ const allExhausted =
+ !onlyActiveViable &&
+ allHaveLive &&
+ candidates.every((a) => {
+ const u = liveUtil[accountKey(a)];
+ return Math.max(u.five_hour_pct, u.seven_day_pct) >= EXHAUSTED_THRESHOLD;
+ });
+ const destinationCapStuck =
+ !pick && !onlyActiveViable && !allExhausted && allNonActiveLiveConfirmedOverDestinationCap(config, state, liveUtil);
+ return { pick, allExhausted, allHaveLive, onlyActiveViable, destinationCapStuck };
+}
+
+// True if AWS Bedrock is reachable (sts + bedrock list).
+function checkBedrockAvailable(region) {
+ const reg = region || process.env.AWS_BEDROCK_REGION || 'us-east-1';
+ try {
+ execFileSync('aws', ['sts', 'get-caller-identity', '--output', 'json'], {
+ stdio: 'pipe',
+ timeout: 5000,
+ });
+ execFileSync('aws', ['bedrock', 'list-inference-profiles', '--region', reg, '--max-results', '1'], {
+ stdio: 'pipe',
+ timeout: 6000,
+ });
+ return { ok: true, region: reg };
+ } catch (e) {
+ return { ok: false, region: reg, error: (e.message || '').slice(0, 120) };
+ }
+}
+
+// Activate Bedrock fallback. Writes a sentinel + prints source instructions.
+// Cannot mutate env of an already-running session — user must start a new
+// one with `source ~/.claude/scripts/account-rotation/use-bedrock.sh`.
+async function activateBedrockFallback(reason) {
+ const region = process.env.AWS_BEDROCK_REGION || 'us-east-1';
+ const result = checkBedrockAvailable(region);
+ const sentinel = join(process.env.HOME || '', '.claude', '.bedrock-fallback.json');
+ const payload = {
+ activated_at: new Date().toISOString(),
+ reason,
+ region,
+ available: result.ok,
+ error: result.error || null,
+ };
+ try {
+ writeFileSync(sentinel, JSON.stringify(payload, null, 2));
+ } catch {}
+ if (result.ok) {
+ try {
+ persistBedrockClaudeSettings(region);
+ log(`✅ settings.json → Bedrock env (${region})`);
+ } catch (e) {
+ log(`⚠ settings.json Bedrock persist failed: ${(e.message || e).toString().slice(0, 120)}`);
+ }
+ log(`✅ BEDROCK FALLBACK ACTIVATED region=${region} reason=${reason}`);
+ notify('Bedrock Fallback Active', `All Anthropic accounts exhausted — switched to Bedrock (${region}).`);
+ console.log('');
+ console.log('━━━ BEDROCK FALLBACK ACTIVE ━━━');
+ console.log(`Reason : ${reason}`);
+ console.log(`Region : ${region}`);
+ console.log('Use it : source ~/.claude/scripts/account-rotation/use-bedrock.sh');
+ console.log(`Clear : rm ${sentinel}`);
+ console.log('');
+ } else {
+ log(`❌ Bedrock fallback FAILED reason=${reason} aws_error=${result.error}`);
+ notify('Bedrock Fallback FAILED', `aws sts/bedrock unreachable in ${region} — manual intervention needed`);
+ }
+ return result.ok;
+}
+
// ── Keychain ─────────────────────────────────────────────────────────────────
function readKeychain(svc = KEYCHAIN_SERVICE, acct = KEYCHAIN_ACCOUNT) {
@@ -1947,8 +2120,8 @@ async function runAuthFlow(driver, account) {
}
log('Authorize button still not clickable after 30s — escalating to ai-brain');
// Fast-path ai-brain escalation: don't wait for stall detector to catch up
- // on the next loop iter. The page is stuck on OAuth authorize and Haiku
- // can usually pick the right org/continue button immediately.
+ // on the next loop iter. The page is stuck on OAuth authorize — Bedrock
+ // vision + optional Context7 / web research picks the next action.
if (aiBrainEnabled && aiBrainHistory.length < AI_BRAIN_MAX_DECISIONS) {
const action = await askAIBrain({
page: driver._page,
@@ -2237,6 +2410,10 @@ async function browserOAuthFallback(account) {
}
success = await runAuthFlow(driver, account);
+ if (success) {
+ await maybeScrapeBillingAfterOAuth(driver, account, log);
+ }
+
if (!success) {
log(`[${driver._driverName}] runAuthFlow returned false — trying next driver`);
failed.add(driver._driverName);
@@ -2453,7 +2630,10 @@ async function refreshRunningSession(rotatedAccount = null, noBrowser = false) {
const url = await driver.currentUrl().catch(() => '');
if (url && (url.includes('oauth') || url.includes('authorize') || url.includes('claude.ai/login'))) {
log(`[session] Detected post-restart OAuth page (${url.substring(0, 60)}) — driving flow`);
- if (rotatedAccount) await runAuthFlow(driver, rotatedAccount);
+ if (rotatedAccount) {
+ const authOk = await runAuthFlow(driver, rotatedAccount);
+ if (authOk) await maybeScrapeBillingAfterOAuth(driver, rotatedAccount, log);
+ }
}
try {
await driver.close?.();
@@ -2474,75 +2654,107 @@ async function rotate(targetEmail, opts = {}) {
const state = readState();
const dryRun = opts.dryRun || false;
- if (!targetEmail) {
- // Query live utilization for all accounts before picking — best-effort, ~2s
- log('Querying live utilization for all accounts...');
- const liveUtil = await queryAllUtilization(config);
- const utilSummary = Object.entries(liveUtil)
- .map(([k, v]) => `${k}:5h=${v.five_hour_pct}%/7d=${v.seven_day_pct}%`)
- .join(', ');
- if (utilSummary) log(`Live util: ${utilSummary}`);
- // Snapshot live data into state for future daemon decisions
- for (const [key, util] of Object.entries(liveUtil)) {
- state.accounts[key] = state.accounts[key] || {};
- state.accounts[key].lastUtilization = {
- pct: util.five_hour_pct,
- reset: util.resets_at_5h ? Math.floor(new Date(util.resets_at_5h).getTime() / 1000) : null,
+ // ALWAYS query live util — needed for picker (no target) AND for
+ // target-validation (with --to). This is the safety net that makes sure
+ // we never rotate to an account that will immediately say "token-limit".
+ log('Querying live utilization for all accounts...');
+ const liveUtil = await queryAllUtilization(config);
+ const utilSummary = Object.entries(liveUtil)
+ .map(([k, v]) => `${k}:5h=${v.five_hour_pct}%/7d=${v.seven_day_pct}%`)
+ .join(', ');
+ if (utilSummary) log(`Live util: ${utilSummary}`);
+ // Snapshot live data into state for future daemon decisions.
+ // Includes BOTH 5h util AND extra_usage_enabled — the latter is sticky-true
+ // so EU accounts stay refused even when subsequent live queries fail.
+ for (const [key, util] of Object.entries(liveUtil)) {
+ state.accounts[key] = state.accounts[key] || {};
+ state.accounts[key].lastUtilization = {
+ pct: util.five_hour_pct,
+ reset: util.resets_at_5h ? Math.floor(new Date(util.resets_at_5h).getTime() / 1000) : null,
+ ts: Date.now(),
+ };
+ if (util.extra_usage_enabled !== null && util.extra_usage_enabled !== undefined) {
+ state.accounts[key].lastBilling = {
+ extra_usage_enabled: util.extra_usage_enabled === true,
+ billing_type: util.billing_type || null,
ts: Date.now(),
};
}
- const next = pickNextAccount(config, state, liveUtil, {
- allowExtraUsage: opts.allowExtraUsage === true,
- });
- if (!next) {
- log('No account available (all excluded — extra_usage enabled?)');
- return false;
- }
- targetEmail = accountKey(next);
}
-
- // Hard safety gate: even when the user passes --to <email> explicitly,
- // refuse to activate a Max account where the Anthropic org has
- // has_extra_usage_enabled=true (overage billing). Requires --allow-extra-usage
- // to bypass.
try {
- if (!opts.allowExtraUsage) {
- const target = config.accounts.find((a) => accountKey(a) === targetEmail || a.email === targetEmail);
- if (target) {
- const tokenJson = readStoredToken(target);
- if (tokenJson) {
- const parsed = JSON.parse(tokenJson);
- const accessToken = parsed?.claudeAiOauth?.accessToken;
- if (accessToken) {
- const res = await fetch('https://api.anthropic.com/api/oauth/profile', {
- method: 'GET',
- headers: {
- Authorization: `Bearer ${accessToken}`,
- 'anthropic-beta': 'oauth-2025-04-20',
- 'Content-Type': 'application/json',
- },
- signal: AbortSignal.timeout(5000),
- });
- if (res.ok) {
- const prof = await res.json();
- const euEnabled = prof?.organization?.has_extra_usage_enabled === true;
- if (euEnabled) {
- log(
- `REFUSED: target ${targetEmail} has extra_usage enabled (pay-per-use). Pass --allow-extra-usage to override.`,
- );
- notify(
- 'Rotation BLOCKED',
- `${targetEmail}: extra_usage enabled — would risk credit-card overage. Disable at console.anthropic.com/settings/billing`,
- );
- return false;
- }
+ writeState(state);
+ } catch {}
+ const bedrockOnExhausted = opts.bedrockOnExhausted !== false; // default ON
+
+ if (!targetEmail) {
+ const { pick, allExhausted, onlyActiveViable, destinationCapStuck } = recommendAccount(config, state, liveUtil);
+ if (!pick) {
+ if (onlyActiveViable) {
+ log('Rotation skipped — already on the only viable Max account (API headroom; other accounts exhausted).');
+ return true;
+ }
+ if (allExhausted || destinationCapStuck) {
+ if (allExhausted) {
+ log('All accounts live-confirmed EXHAUSTED — engaging Bedrock fallback');
+ } else {
+ log(
+ `Every live-confirmed non-active account is ≥${destinationUtilHardBlock(config)}% max(5h,7d) — no rotation target; engaging Bedrock fallback`,
+ );
+ }
+ if (bedrockOnExhausted)
+ await activateBedrockFallback(
+ allExhausted ? 'all_accounts_exhausted_picker_null' : 'destination_cap_no_headroom',
+ );
+ } else {
+ log('No account available (see utilization / query logs above)');
+ }
+ return false;
+ }
+ targetEmail = accountKey(pick);
+ } else {
+ // Target validation: refuse exhausted API targets unless overridden.
+ const targetAcct =
+ config.accounts.find((a) => accountKey(a) === targetEmail) ||
+ config.accounts.find((a) => a.email === targetEmail);
+ if (targetAcct) {
+ const tKey = accountKey(targetAcct);
+ const tu = liveUtil[tKey];
+ const targetExhausted =
+ tu &&
+ tu.five_hour_pct != null &&
+ tu.seven_day_pct != null &&
+ Math.max(tu.five_hour_pct, tu.seven_day_pct) >= EXHAUSTED_THRESHOLD;
+ if (targetExhausted && !opts.allowExhausted) {
+ log(
+ `⚠ --to ${targetEmail} is EXHAUSTED (5h=${tu.five_hour_pct}% 7d=${tu.seven_day_pct}%) — auto-falling back to picker`,
+ );
+ const { pick, allExhausted, onlyActiveViable, destinationCapStuck } = recommendAccount(config, state, liveUtil);
+ if (!pick) {
+ if (onlyActiveViable) {
+ log('Rotation skipped — already on the only viable Max account.');
+ return true;
+ }
+ if (allExhausted || destinationCapStuck) {
+ if (allExhausted) log('No alternative — all accounts exhausted');
+ else {
+ log(
+ `No alternative under destination cap (${destinationUtilHardBlock(config)}%) — engaging Bedrock fallback`,
+ );
}
+ if (bedrockOnExhausted) {
+ await activateBedrockFallback(
+ allExhausted ? 'target_and_all_others_exhausted' : 'destination_cap_after_exhausted_target',
+ );
+ }
+ } else {
+ log('No alternative — see utilization / query logs above');
}
+ return false;
}
+ targetEmail = accountKey(pick);
+ log(`→ Picker chose ${targetEmail} instead`);
}
}
- } catch (e) {
- log(`Extra-usage preflight error (non-fatal): ${e.message?.slice(0, 80)}`);
}
// Find by label first, then by email
@@ -2697,57 +2909,6 @@ async function rotate(targetEmail, opts = {}) {
return false;
}
- // POST-SWAP BILLING SAFETY CHECK
- // The fresh token is now in the active keychain. Query /api/oauth/profile to
- // verify has_extra_usage_enabled=false. If true, revert the swap by restoring
- // the previous account's token — this prevents silent credit-card overages.
- if (!opts.allowExtraUsage && !dryRun) {
- try {
- const freshJson = readKeychain();
- const fresh = JSON.parse(freshJson);
- const freshToken = fresh?.claudeAiOauth?.accessToken;
- if (freshToken) {
- const res = await fetch('https://api.anthropic.com/api/oauth/profile', {
- method: 'GET',
- headers: {
- Authorization: `Bearer ${freshToken}`,
- 'anthropic-beta': 'oauth-2025-04-20',
- 'Content-Type': 'application/json',
- },
- signal: AbortSignal.timeout(5000),
- });
- if (res.ok) {
- const prof = await res.json();
- const euOn = prof?.organization?.has_extra_usage_enabled === true;
- if (euOn) {
- log(`POST-SWAP BLOCK: ${targetEmail} has extra_usage=ON (overage billing). Reverting swap.`);
- notify(
- 'Rotation REVERTED',
- `${targetEmail}: extra_usage enabled — charges would hit your card. Rollback in progress.`,
- );
- // Revert: restore previous account's stored token to active slot
- const prevKey = state.activeAccount;
- const prevAccount = prevKey ? config.accounts.find((a) => accountKey(a) === prevKey) : null;
- if (prevAccount) {
- const prevToken = readStoredToken(prevAccount);
- if (prevToken) {
- writeKeychain(prevToken);
- log(`Reverted keychain to previous account ${prevKey}`);
- }
- }
- return false;
- }
- } else {
- log(
- `POST-SWAP profile check returned ${res.status} — unable to verify extra_usage; proceeding (fail-open for transient errors)`,
- );
- }
- }
- } catch (e) {
- log(`POST-SWAP billing check error (non-fatal): ${e.message?.slice(0, 80)}`);
- }
- }
-
// Verify by reading back what's now in the active keychain
let verified = false;
try {
@@ -3058,14 +3219,10 @@ function showStatus() {
}
} catch {}
- // Determine if the mismatch is expected (rotation just ran, session hasn't reloaded)
- const recentRotation = state.lastRotation ? Date.now() - new Date(state.lastRotation).getTime() < 90_000 : false;
- const mismatch =
- liveEmail &&
- state.activeAccount &&
- !state.activeAccount.startsWith(liveEmail) &&
- !liveEmail.startsWith(state.activeAccount);
- const liveNote = mismatch && recentRotation ? ' (stale session — restart Claude Code to apply)' : '';
+ // Statusline must not depend on Claude Code restart. Token swap is keychain-level;
+ // any live/tracked mismatch is surfaced silently via the two separate lines below —
+ // no prescriptive "restart Claude Code" nag in the statusline.
+ const liveNote = '';
console.log('\n=== Claude Account Rotation ===\n');
console.log(`Live auth: ${liveEmail || 'unknown'}${liveNote}`);
@@ -3212,6 +3369,117 @@ if (args.includes('--setup')) {
console.log(`\n⚠ Disable extra_usage at https://console.anthropic.com/settings/billing for each risky account.`);
}
console.log('');
+} else if (args.includes('--recommend') || args.includes('--pick')) {
+ // Live-query all accounts and print the recommended next account WITHOUT
+ // swapping. Used as preflight by force-rotate.sh / rotate-magic / daemon-log.
+ const config = readConfig();
+ const state = readState();
+ const json = args.includes('--json');
+ if (!json) console.log('Querying live utilization for recommendation...');
+ const liveUtil = await queryAllUtilization(config);
+ const destCap = destinationUtilHardBlock(config);
+ const { pick, allExhausted, allHaveLive, onlyActiveViable, destinationCapStuck } = recommendAccount(
+ config,
+ state,
+ liveUtil,
+ );
+ const accountsOut = {};
+ for (const a of config.accounts) {
+ if (a.disabled === true) continue;
+ const k = accountKey(a);
+ const u = liveUtil[k];
+ if (!u) {
+ accountsOut[k] = { error: 'query_failed' };
+ continue;
+ }
+ const worst = Math.max(u.five_hour_pct ?? 0, u.seven_day_pct ?? 0);
+ accountsOut[k] = {
+ five_hour: u.five_hour_pct,
+ seven_day: u.seven_day_pct,
+ extra_usage: u.extra_usage_enabled,
+ worst,
+ viable: worst < destCap,
+ destination_cap_pct: destCap,
+ resets_at_5h: u.resets_at_5h,
+ };
+ }
+ // Bedrock readiness probe (fast — ~2s), only when needed
+ let bedrock = null;
+ if (allExhausted || destinationCapStuck) {
+ bedrock = checkBedrockAvailable();
+ }
+ const out = {
+ activeAccount: state.activeAccount || null,
+ pick: pick ? accountKey(pick) : null,
+ pick_email: pick ? pick.email : null,
+ allExhausted,
+ allHaveLive,
+ onlyActiveViable,
+ destinationCapStuck,
+ destinationMaxUtilPercent: destCap,
+ bedrock_ready: bedrock ? bedrock.ok : null,
+ bedrock_region: bedrock ? bedrock.region : null,
+ accounts: accountsOut,
+ };
+ if (json) {
+ console.log(JSON.stringify(out, null, 2));
+ } else {
+ console.log('');
+ console.log(
+ `Active: ${out.activeAccount || '(none)'} · rotation targets need max(5h,7d) < ${destCap}% (see rateLimits.destinationMaxUtilPercent; Bedrock exhaustion is still ≥${EXHAUSTED_THRESHOLD}%)`,
+ );
+ for (const [k, v] of Object.entries(accountsOut)) {
+ if (v.error) {
+ console.log(` ❌ ${k}: ${v.error}`);
+ continue;
+ }
+ let icon;
+ if (v.extra_usage === true) icon = '💳';
+ else if (v.worst >= EXHAUSTED_THRESHOLD) icon = '🔴';
+ else if (!v.viable) icon = '🟡';
+ else if (v.worst >= 70) icon = '🟡';
+ else icon = '🟢';
+ const tags = [];
+ if (v.extra_usage === true) tags.push('EU-ON');
+ if (v.worst >= EXHAUSTED_THRESHOLD) tags.push('EXHAUSTED');
+ else if (!v.viable) tags.push(`≥${destCap}%cap`);
+ const tag = tags.length ? ' ' + tags.join(' ') : '';
+ const star = k === out.activeAccount ? ' ◀ active' : '';
+ console.log(` ${icon} ${k}: 5h=${v.five_hour ?? '?'}% 7d=${v.seven_day ?? '?'}%${tag}${star}`);
+ }
+ console.log('');
+ if (allExhausted) {
+ console.log(`⚠ ALL ACCOUNTS EXHAUSTED (live-confirmed, threshold ${EXHAUSTED_THRESHOLD}%)`);
+ if (bedrock?.ok) {
+ console.log(`✅ Bedrock fallback READY in ${bedrock.region}`);
+ console.log(' Next session: source ~/.claude/scripts/account-rotation/use-bedrock.sh');
+ } else {
+ console.log(`❌ Bedrock NOT reachable: ${bedrock?.error || 'unknown'}`);
+ }
+ } else if (destinationCapStuck) {
+ console.log(
+ `⚠ STUCK: every live-confirmed non-active account is ≥${destCap}% — no Max rotation target (Bedrock or lower destinationMaxUtilPercent).`,
+ );
+ if (bedrock?.ok) {
+ console.log(`✅ Bedrock fallback READY in ${bedrock.region}`);
+ console.log(' Next rotation: will activate Bedrock; then source use-bedrock.sh in new shells.');
+ } else {
+ console.log(`❌ Bedrock NOT reachable: ${bedrock?.error || 'unknown'}`);
+ }
+ } else if (out.onlyActiveViable) {
+ console.log(
+ `→ Already optimal: only account under ${destCap}% destination cap is active (${out.activeAccount || '?'}) — stay put.`,
+ );
+ } else if (out.pick) {
+ console.log(`→ Recommended: ${out.pick}`);
+ } else {
+ console.log('→ No viable account (all API-exhausted or missing utilization data)');
+ }
+ console.log('');
+ }
+ // Exit codes: 0 = viable pick available, 2 = Bedrock path (exhausted or destination-cap stuck),
+ // 3 = no viable pick but not confirmed for Bedrock (some queries failed — investigate).
+ process.exit(pick || onlyActiveViable ? 0 : allExhausted || destinationCapStuck ? 2 : 3);
} else if (args.includes('--status')) {
showStatus();
} else if (args.includes('--capture')) {
@@ -3226,7 +3494,8 @@ if (args.includes('--setup')) {
const force = args.includes('--force');
const dryRun = args.includes('--dry-run');
const magicLink = args.includes('--magic-link');
- const allowExtraUsage = args.includes('--allow-extra-usage');
+ const allowExhausted = args.includes('--allow-exhausted');
+ const bedrockOnExhausted = !args.includes('--no-bedrock-fallback');
if (dryRun) log('DRY RUN MODE — no changes will be made');
if (force) {
log('Force mode — bypassing lock and killing any competing rotations');
@@ -3248,7 +3517,8 @@ if (args.includes('--setup')) {
noBrowser,
dryRun,
magicLink,
- allowExtraUsage,
+ allowExhausted,
+ bedrockOnExhausted,
});
process.exit(ok ? 0 : 1);
} catch (err) {
diff --git a/claude-ops/scripts/account-rotation/use-bedrock.sh b/claude-ops/scripts/account-rotation/use-bedrock.sh
new file mode 100755
index 00000000..bff2e0f1
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/use-bedrock.sh
@@ -0,0 +1,83 @@
+#!/bin/bash
+# use-bedrock.sh — switch this shell into Bedrock mode for Claude Code.
+# Source me: `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.
+#
+# Auto-fired by rotate.mjs / daemon when all configured Anthropic Max accounts
+# are LIVE-CONFIRMED at >=95% util. Sentinel: ~/.claude/.bedrock-fallback.json.
+# Back to OAuth: source ~/.claude/scripts/account-rotation/use-oauth.sh
+
+_ROT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
+
+export CLAUDE_CODE_USE_BEDROCK=1
+export AWS_BEDROCK_REGION="${AWS_BEDROCK_REGION:-us-east-1}"
+export AWS_REGION="${AWS_REGION:-$AWS_BEDROCK_REGION}"
+
+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
+
+_SRC="$(python3 -c "import json,sys; print(json.loads(sys.argv[1]).get('source','?'))" "$_RESOLVED" 2>/dev/null || echo "?")"
+
+# 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
+
+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 " 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..."
+[[ -f ~/.zshrc ]] && source ~/.zshrc 2>/dev/null
+echo "✅ Shell reloaded. New \`claude\` sessions will use Bedrock."
+echo " Back to OAuth: source ~/.claude/scripts/account-rotation/use-oauth.sh"
diff --git a/claude-ops/scripts/account-rotation/use-oauth.sh b/claude-ops/scripts/account-rotation/use-oauth.sh
new file mode 100755
index 00000000..74aaa515
--- /dev/null
+++ b/claude-ops/scripts/account-rotation/use-oauth.sh
@@ -0,0 +1,49 @@
+#!/bin/bash
+# use-oauth.sh — exit Bedrock mode in this shell, restore Anthropic 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.
+
+unset CLAUDE_CODE_USE_BEDROCK
+unset AWS_BEDROCK_REGION
+unset AWS_REGION
+unset ANTHROPIC_MODEL
+unset ANTHROPIC_SMALL_FAST_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
+
+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 " active account: ${ACTIVE:-(unknown)}"
+if [[ -f ~/.claude/.bedrock-fallback.json ]]; then
+ echo " ⚠ Bedrock sentinel still present — clearing"
+ rm -f ~/.claude/.bedrock-fallback.json
+fi
+
+echo " Reload zsh aliases/functions in this shell..."
+[[ -f ~/.zshrc ]] && source ~/.zshrc 2>/dev/null
+echo "✅ Shell reloaded. New \`claude\` sessions will use OAuth."
diff --git a/claude-ops/scripts/recap/digest.sh b/claude-ops/scripts/recap/digest.sh
index 4856a829..967afc8d 100755
--- a/claude-ops/scripts/recap/digest.sh
+++ b/claude-ops/scripts/recap/digest.sh
@@ -72,6 +72,15 @@ Produce ONE single line (max 240 chars) describing the CURRENT state of work, we
result=$(printf '%s' "$prompt" | claude -p --model haiku --no-session-persistence --output-format text 2>/dev/null | head -c 260 | LC_ALL=C tr '\n' ' ')
+# Reject Claude error / auth / quota strings — never let them pollute the
+# digest OR the rolling log (which feeds back as PRIOR HEADLINES on next run).
+case "$result" in
+ ""|"Prompt is too long"*|"Error:"*|"error:"*|"API Error"*|"Credit balance"*|"Invalid API"*|"You've hit your limit"*|"You've reached your"*|"Claude AI usage limit"*|"Usage limit"*|"usage limit"*|"Rate limit"*|"rate limit"*|"resets May"*|"resets at"*|"Please try again"*|"Account is restricted"*|"Not logged in"*|*"Please run /login"*|*"run /login"*|"OAuth"*|"oauth"*|"Authentication"*|"authentication"*)
+ printf '[%s] SKIP bad-result: %s\n' "$(date '+%H:%M')" "$result" >> "${LOG}.errors"
+ exit 0
+ ;;
+esac
+
if [ -n "$result" ]; then
printf '%s' "$result" > "$DIGEST"
printf '[%s] %s\n' "$(date '+%H:%M')" "$result" >> "$LOG"
diff --git a/claude-ops/skills/ops-rotate/SKILL.md b/claude-ops/skills/ops-rotate/SKILL.md
index 9ed0b867..11142fa5 100644
--- a/claude-ops/skills/ops-rotate/SKILL.md
+++ b/claude-ops/skills/ops-rotate/SKILL.md
@@ -69,6 +69,8 @@ If user passed an explicit target email (`/ops:rotate rotate-now [email protected]
bash "$ROT_SRC/force-rotate.sh" "${TARGET_EMAIL:-}"
```
+Browser fallback (when fast `--no-browser` fails) runs full OAuth in `rotate.mjs` with **ai-brain** (Bedrock vision, optional Context7 + web research via env) and billing scrape — requires AWS credentials on the machine. Daemon-only rotations stay `--no-browser` and never load ai-brain.
+
Show the trailing status output. Remind the user that running Claude Code sessions hold their own access token until next `/login` or until they exit and re-enter.
## list