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.
Shell agent-teamsai-agentai-automationanthropicautonomous-agentawsbusiness-operationsclaudeclaude-codeclaude-code-plugindevopsecommerceinbox-zeroklaviyomarketingmcpmorning-briefingpr-automationshopifyterminal
ops-accounts: CLIProxyAPI provider adapter + account-rotation automation suite
auroracapitalb322ce48ee45
diff --git a/claude-ops/bin/ops-accounts b/claude-ops/bin/ops-accountsindex ee2be335..dd8dcd60 100755--- a/claude-ops/bin/ops-accounts+++ b/claude-ops/bin/ops-accounts@@ -95,11 +95,54 @@ PYecho "crs_grok_hop: not reachable (optional thin hop)"fi}+# --- CLIProxyAPI backend (optional local multi-provider proxy) ---+# Convention: single static binary + config dir; override via env if relocated.+CLIPROXY_HOME="${CLIPROXYAPI_HOME:-$HOME/Developer/active/cliproxyapi}"+CLIPROXY_PORT="${CLIPROXYAPI_PORT:-8317}"+CLIPROXY_CFG="$CLIPROXY_HOME/config/config.yaml"+CLIPROXY_AUTHDIR="$CLIPROXY_HOME/auths"++cliproxy_alive() {+ curl -fsS -m 2 -o /dev/null "http://127.0.0.1:${CLIPROXY_PORT}/v1/models" 2>/dev/null \+ || curl -fsS -m 2 -o /dev/null "http://127.0.0.1:${CLIPROXY_PORT}/health" 2>/dev/null+}++# count auth files for a provider prefix (no secrets printed)+cliproxy_count() {+ local prefix="$1"+ ls "$CLIPROXY_AUTHDIR/${prefix}"-*.json 2>/dev/null | wc -l | tr -d ' '+}++print_cliproxy() {+ if [[ ! -d "$CLIPROXY_HOME" ]]; then+ echo "cliproxyapi: not installed at \$CLIPROXYAPI_HOME (optional backend)"+ return 1+ fi+ if cliproxy_alive; then+ echo "cliproxyapi: listening on 127.0.0.1:${CLIPROXY_PORT}"+ else+ echo "cliproxyapi: installed but not reachable on :${CLIPROXY_PORT} (launchctl kickstart -k gui/\$(id -u)/com.sam.cliproxyapi)"+ return 1+ fi+ return 0+}+print_codex() {echo "=== Codex / OpenAI ==="+ if print_cliproxy; then+ echo "accounts (auth-dir): $(cliproxy_count codex)"+ fihave codex-rotate && codex-rotate status 2>/dev/null | head -30 || echo "codex-rotate optional"}+print_gemini() {+ echo "=== Gemini / Antigravity ==="+ if print_cliproxy; then+ # Gemini seats are stored as antigravity-*.json (and/or gemini-*.json)+ echo "accounts (auth-dir): $(( $(cliproxy_count antigravity) + $(cliproxy_count gemini) ))"+ fi+}+print_factory() {echo "=== Factory ==="echo "(adapter planned — see docs/ops/OPS-ACCOUNTS-VISION.md)"@@ -115,6 +158,7 @@ case "$cmd" inprint_claude; echoprint_grok; echoprint_codex; echo+ print_gemini; echoprint_factory; echoprint_cursor;;@@ -124,6 +168,16 @@ case "$cmd" inclaude)[[ -f "$ROT/rotate.mjs" ]] && node "$ROT/rotate.mjs" --utilization 2>/dev/null | head -60;;+ codex|gemini|grok-x|xai|kimi)+ # CLIProxyAPI util: per-provider account inventory + last-refresh mtimes (no secrets)+ p="$provider"; [[ "$p" == "xai" || "$p" == "grok-x" ]] && p="xai"+ echo "--- cliproxy util: $p ---"+ if ls "$CLIPROXY_AUTHDIR/${p}"-*.json >/dev/null 2>&1; then+ ls -lt "$CLIPROXY_AUTHDIR/${p}"-*.json | awk '{print $6, $7, $8, $9}'+ else+ echo "no ${p}-*.json auth files in $CLIPROXY_AUTHDIR"+ fi+ ;;grok)curl -fsS -m 3 http://127.0.0.1:31845/accounts 2>/dev/null | python3 -c 'import json,sys;d=json.load(sys.stdin);print(json.dumps({k:d.get(k) for k in ("request_counts","exhausted_seconds_remaining","load_balance","current")}, indent=2))' || echo "proxy util unavailable";;@@ -310,7 +364,7 @@ case "$cmd" inops-accounts — multi-provider seats (canonical; /ops:rotate is alias)status | list- util [all|claude|grok]+ util [all|claude|grok|codex|gemini|xai|kimi]switch claude|grok | rotate-nowrefresh [all|claude|grok]reauth claude <email> | reauth grok <email>diff --git a/claude-ops/docs/ops/OPS-ACCOUNTS-VISION.md b/claude-ops/docs/ops/OPS-ACCOUNTS-VISION.mdindex a70cbaa0..6e7fbcc0 100644--- a/claude-ops/docs/ops/OPS-ACCOUNTS-VISION.md+++ b/claude-ops/docs/ops/OPS-ACCOUNTS-VISION.md@@ -42,6 +42,7 @@ Claude already has (in plugin + optional CRS):| **Claude (Anthropic)** | magic-link + captcha | magic-link-autoloop | 5h/7d | keychain daemon; CRS optional || **Grok (xAI SuperGrok)** | device-code + Google (dcli) | residential cascade (EFG SOCKS → Bright Data residential → ISP → mobile) | weekly / 429 | `grok-cli-auth-proxy` RR; CRS is thin relay only || **OpenAI / Codex** | OAuth / API key | codex OAuth bridge | usage API | `codex-rotate` absorbed |+| **CLIProxyAPI (local multi-provider pool)** | per-provider OAuth login flows (browser/device-code) | proxy-internal token refresh | management API (pool-level) | single static binary + flat-file auth-dir; chosen over sub2api (no Postgres/Redis to maintain). Optional local backend: `providers/cliproxy.mjs` adapter reports auth-dir inventory; `bin/ops-accounts` prints per-provider counts + `util <provider>` views. Env overrides: `CLIPROXYAPI_HOME`, `CLIPROXYAPI_PORT`. || **Factory** | provider OAuth / tokens | native reauth | quota-feed-factory patterns | full adapter || **Cursor** | Cursor account OAuth | browser/device OAuth | plan limits if available | full adapter || **Extensible** | adapter interface | same contract | best-effort | `provider-env` / `provider-router` |diff --git a/claude-ops/scripts/account-rotation/captcha-solve.mjs b/claude-ops/scripts/account-rotation/captcha-solve.mjsnew file mode 100644index 00000000..805fdfa9--- /dev/null+++ b/claude-ops/scripts/account-rotation/captcha-solve.mjs@@ -0,0 +1,169 @@+// captcha-solve.mjs — tiered CAPTCHA solver.+// Tier 1: 2Captcha FunCAPTCHA token (paid solving service)+// Tier 2: Gemini vision via local CLIProxyAPI — screenshot analysis + click/drag execution+import { readFileSync } from 'fs';++const API = 'https://api.2captcha.com';+const sleep = (ms) => new Promise(r => setTimeout(r, ms));++export async function solveFunCaptcha({ pageUrl, publicKey, surl, apiKey, log = console.log }) {+ const task = {+ type: 'FunCaptchaTaskProxyless',+ websiteURL: pageUrl,+ websitePublicKey: publicKey,+ };+ if (surl) task.funcaptchaApiJSSubdomain = surl;++ const create = await fetch(`${API}/createTask`, {+ method: 'POST', headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ clientKey: apiKey, task }),+ }).then(r => r.json());+ if (create.errorId) throw new Error('createTask: ' + (create.errorDescription || create.errorCode));+ const taskId = create.taskId;+ log('2captcha task ' + taskId + ' created — polling');++ const deadline = Date.now() + 180000;+ while (Date.now() < deadline) {+ await sleep(5000);+ const res = await fetch(`${API}/getTaskResult`, {+ method: 'POST', headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ clientKey: apiKey, taskId }),+ }).then(r => r.json());+ if (res.errorId) throw new Error('getTaskResult: ' + (res.errorDescription || res.errorCode));+ if (res.status === 'ready') {+ log('2captcha solved');+ return res.solution.token;+ }+ }+ throw new Error('2captcha timeout (180s)');+}++export async function extractArkoseParams(page) {+ return page.evaluate(() => {+ const out = { publicKey: null, surl: null };+ const ifr = [...document.querySelectorAll('iframe')].map(f => f.src || '');+ const hit = ifr.find(u => /arkoselabs|funcaptcha/i.test(u));+ if (hit) {+ try {+ const u = new URL(hit);+ out.surl = u.origin;+ out.publicKey = u.searchParams.get('pkey') || (u.hash.match(/pkey=([0-9a-f-]+)/i) || [])[1] || null;+ } catch (e) {}+ }+ if (!out.publicKey) {+ const m = document.documentElement.innerHTML.match(/public_key["'\s:=]+([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i);+ if (m) out.publicKey = m[1];+ }+ if (!out.surl) out.surl = 'https://client-api.arkoselabs.com';+ return out;+ });+}++export async function injectFunCaptchaToken(page, token) {+ return page.evaluate((tok) => {+ const results = [];+ for (const el of document.querySelectorAll('input[name="fc-token"], #FunCaptcha-Token')) {+ el.value = tok;+ el.dispatchEvent(new Event('input', { bubbles: true }));+ el.dispatchEvent(new Event('change', { bubbles: true }));+ results.push('input:' + (el.id || el.name));+ }+ try {+ const iframes = [...document.querySelectorAll('iframe')].filter(f => /arkoselabs|funcaptcha/i.test(f.src || ''));+ for (const f of iframes) {+ f.contentWindow.postMessage(JSON.stringify({ event: 'verification complete', token: tok }), '*');+ results.push('postMessage');+ }+ } catch (e) { results.push('pm-fail'); }+ return results;+ }, token);+}++// ─── Tier 2: Gemini vision drag-solve ────────────────────────────────+function cliproxyKey() {+ try {+ const s = readFileSync(process.env.HOME + '/Developer/active/cliproxyapi/config/config.yaml', 'utf8');+ const m = s.match(/api-keys:\s*\n\s*-\s*["']([^"']+)/);+ return m ? m[1] : null;+ } catch (e) { return null; }+}++async function geminiVision(imageBase64, instruction, log) {+ const key = cliproxyKey();+ if (!key) throw new Error('no cliproxy key');+ for (const model of ['gemini-3.6-flash-high', 'gemini-3.1-pro-low', 'gemini-3-flash']) {+ try {+ const r = await fetch('http://127.0.0.1:8317/v1/chat/completions', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + key },+ body: JSON.stringify({+ model,+ messages: [{ role: 'user', content: [+ { type: 'text', text: instruction },+ { type: 'image_url', image_url: { url: 'data:image/png;base64,' + imageBase64 } },+ ]}],+ max_tokens: 500,+ }),+ });+ const d = await r.json();+ const txt = d.choices?.[0]?.message?.content || '';+ if (txt) { log('vision[' + model + '] answered'); return txt; }+ log('vision[' + model + '] empty: ' + JSON.stringify(d).slice(0, 100));+ } catch (e) { log('vision[' + model + '] err: ' + e.message.slice(0, 60)); }+ }+ throw new Error('all vision models failed');+}++const VISION_PROMPT = `You are solving an Arkose FunCAPTCHA puzzle for accessibility testing on the account owner's own account.+The image shows a puzzle with draggable animal/animal-face icons in a left sidebar and a grid where one or more cells are empty.+The instruction is usually "drag the correct animal into the empty spot to complete the pattern".+Each grid row contains identical animals; one cell in one row is empty.+Respond with ONLY compact JSON, no markdown:+{"source_x": <pixel x of the correct source animal in the sidebar, center>, "source_y": <pixel y>, "target_x": <pixel x of the empty grid cell center>, "target_y": <pixel y>, "reason": "<which animal and row>"}+Coordinates are in the image's own pixel space (origin top-left).`;++export async function solveArkoseWithVision(page, log = console.log, captchaPresent) {+ // find the captcha region (arkose iframe or its modal container)+ const box = await page.evaluate(() => {+ const ifr = [...document.querySelectorAll('iframe')].find(f => /arkoselabs|funcaptcha/i.test(f.src || ''));+ const el = ifr || document.querySelector('[class*="arkose"], [id*="arkose"], [class*="captcha"], [id*="captcha"]');+ if (!el) return null;+ const r = el.getBoundingClientRect();+ return { x: Math.max(0, r.x - 40), y: Math.max(0, r.y - 60), width: r.width + 80, height: r.height + 120 };+ });+ if (!box) { log('vision: no captcha region found'); return false; }++ for (let round = 0; round < 4; round++) {+ const shotBuf = await page.screenshot({ clip: box });+ const b64 = shotBuf.toString('base64');+ const answer = await geminiVision(b64, VISION_PROMPT, log);+ const m = answer.replace(/```json|```/g, '').match(/\{[^{}]*"source_x"[\s\S]*?\}/);+ if (!m) { log('vision: unparseable answer: ' + answer.slice(0, 120)); return false; }+ const coords = JSON.parse(m[0]);+ log('vision plan: ' + (coords.reason || '') + ' src(' + coords.source_x + ',' + coords.source_y + ') → tgt(' + coords.target_x + ',' + coords.target_y + ')');++ const sx = box.x + coords.source_x, sy = box.y + coords.source_y;+ const tx = box.x + coords.target_x, ty = box.y + coords.target_y;++ // attempt 1: click source (pick up) then click target (drop) — Arkose "+ Move" UI supports this+ await page.mouse.click(sx, sy);+ await sleep(700);+ await page.mouse.click(tx, ty);+ await sleep(2500);+ if (!(await captchaPresent())) { log('vision solve: cleared via click-place'); return true; }++ // attempt 2: real drag+ await page.mouse.move(sx, sy);+ await page.mouse.down();+ await sleep(200);+ for (let i = 1; i <= 12; i++) {+ await page.mouse.move(sx + (tx - sx) * i / 12, sy + (ty - sy) * i / 12);+ await sleep(40);+ }+ await page.mouse.up();+ await sleep(2500);+ if (!(await captchaPresent())) { log('vision solve: cleared via drag'); return true; }+ log('vision solve round ' + round + ' did not clear — re-analyzing');+ }+ return false;+}diff --git a/claude-ops/scripts/account-rotation/claude-reauth.mjs b/claude-ops/scripts/account-rotation/claude-reauth.mjsnew file mode 100644index 00000000..d78aa3db--- /dev/null+++ b/claude-ops/scripts/account-rotation/claude-reauth.mjs@@ -0,0 +1,131 @@+// claude-reauth.mjs — drive one Claude account reauth via playwright + gog magic-link polling.+// Usage: node claude-reauth.mjs <email> <oauthAuthorizeUrl> [gogInbox]+import { chromium } from 'playwright';+import { execSync } from 'child_process';++const [email, authUrl] = process.argv.slice(2);+if (!email || !authUrl) { console.error('usage: node claude-reauth.mjs <email> <authUrl>'); process.exit(2); }++const sleep = (ms) => new Promise(r => setTimeout(r, ms));+const log = (m) => console.log(`[${new Date().toISOString().slice(11,19)}] ${m}`);++function gogSearch(query) {+ try {+ return execSync(`gog gmail search "${query.replace(/"/g, '\\"')}" --max 5 2>/dev/null`, { timeout: 30000 }).toString();+ } catch { return ''; }+}+function gogRead(id) {+ try { return execSync(`gog gmail read ${id} 2>/dev/null`, { timeout: 30000 }).toString(); } catch { return ''; }+}++async function waitMagicLink(sinceMs, maxWaitMs = 180000) {+ log(`polling gmail for magic link to ${email}...`);+ const linkRe = /https:\/\/claude\.ai\/magic-link#[^\s"'<>)\]}]+/;+ const codeRe = /(?:verification code|code is|code:)\s*[^0-9]{0,10}([0-9]{6})/i;+ while (Date.now() - sinceMs < maxWaitMs) {+ // Magic links arrive from mail.anthropic.com, subject "Your secure link to Claude.ai is here"+ const out = gogSearch(`from:mail.anthropic.com subject:"secure link" to:${email}`);+ const ids = [...out.matchAll(/^\s*(\d+)\s+\d{4}-\d{2}-\d{2}/gm)].map(m => m[1]);+ for (const id of ids) {+ const body = gogRead(id);+ const dateMatch = body.match(/Date:\s*(.+)/);+ if (dateMatch && Date.parse(dateMatch[1]) < sinceMs - 60000) continue; // stale+ const link = body.match(linkRe);+ if (link) return { type: 'link', value: link[0] };+ const code = body.match(codeRe);+ if (code) return { type: 'code', value: code[1] };+ }+ // also search without to: filter (forwards may not preserve to:)+ const out2 = gogSearch('from:mail.anthropic.com subject:"secure link" newer_than:10m');+ const ids2 = [...out2.matchAll(/^\s*(\d+)\s+\d{4}-\d{2}-\d{2}/gm)].map(m => m[1]);+ for (const id of ids2) {+ const body = gogRead(id);+ const dateMatch = body.match(/Date:\s*(.+)/);+ if (dateMatch && Date.parse(dateMatch[1]) < sinceMs - 60000) continue;+ if (!body.toLowerCase().includes(email.toLowerCase())) continue;+ const link = body.match(linkRe);+ if (link) return { type: 'link', value: link[0] };+ const code = body.match(codeRe);+ if (code) return { type: 'code', value: code[1] };+ }+ await sleep(8000);+ }+ return null;+}++const browser = await chromium.launch({ headless: false, args: ['--window-position=100,100', '--window-size=1100,900'] });+const ctx = await browser.newContext();+const page = await ctx.newPage();++log('logging out existing claude.ai session');+await page.goto('https://claude.ai/api/auth/logout', { timeout: 20000 }).catch(() => {});+await sleep(1500);++log('going to claude.ai login');+await page.goto('https://claude.ai/login', { timeout: 30000, waitUntil: 'domcontentloaded' });+await sleep(2500);++// fill email+const emailSel = 'input[type="email"], input[name="email"], input[autocomplete="username"], input[placeholder*="mail" i]';+await page.waitForSelector(emailSel, { timeout: 15000 });+await page.fill(emailSel, email);+log('email filled');+// submit+for (const sel of ['button[type="submit"]', 'button:has-text("Continue")', 'button:has-text("Continue with email")']) {+ try { await page.click(sel, { timeout: 3000 }); log(`clicked ${sel}`); break; } catch {}+}++const since = Date.now();+await sleep(3000);++// Sometimes the page shows a verification-code input instead of "link sent"+let result = null;+const codeInputSel = 'input[inputmode="numeric"], input[autocomplete="one-time-code"], input[name="code"], input[placeholder*="code" i]';+const hasCodeInput = await page.$(codeInputSel);++result = await waitMagicLink(since);+if (!result) { log('FAIL: no magic link/code found in time'); await browser.close(); process.exit(1); }++if (result.type === 'code') {+ log(`got verification code ${result.value}`);+ const inp = await page.$(codeInputSel);+ if (inp) { await inp.fill(result.value); await page.keyboard.press('Enter'); await sleep(4000); }+} else {+ log(`got magic link — navigating`);+ await page.goto(result.value, { timeout: 30000, waitUntil: 'domcontentloaded' }).catch(e => log('link nav warn: ' + e.message.slice(0,80)));+ await sleep(4000);+}++// After login, maybe a displayed verification code appears that must be entered back on the sign-in page.+// Check current state+log('post-login page: ' + page.url().slice(0, 100));++// Now go to the OAuth authorize URL+log('navigating to OAuth authorize URL');+await page.goto(authUrl, { timeout: 30000, waitUntil: 'domcontentloaded' });+await sleep(3000);+log('authorize page: ' + page.url().slice(0, 100) + ' | title=' + await page.title());++// Click Authorize / org selection if present+for (let attempt = 0; attempt < 3; attempt++) {+ if (page.url().includes('localhost:54545')) break;+ for (const sel of ['button:has-text("Authorize")', 'button:has-text("Allow")', 'button[type="submit"]', 'button:has-text("Continue")']) {+ try {+ const b = await page.$(sel);+ if (b) { await b.click({ timeout: 3000 }); log(`clicked ${sel}`); await sleep(3000); break; }+ } catch {}+ }+ if (page.url().includes('localhost:54545')) break;+ await sleep(2000);+}++const finalUrl = page.url();+if (finalUrl.includes('localhost:54545') || finalUrl.includes('127.0.0.1:54545')) {+ log('SUCCESS: callback reached — ' + finalUrl.slice(0, 120));+ await browser.close();+ process.exit(0);+}+log('FAIL: did not reach callback. final=' + finalUrl.slice(0, 120));+await page.screenshot({ path: `/tmp/claude-reauth-${email.replace(/[@.]/g, '_')}.png` }).catch(() => {});+await browser.close();+process.exit(1);diff --git a/claude-ops/scripts/account-rotation/claude-reauth2.mjs b/claude-ops/scripts/account-rotation/claude-reauth2.mjsnew file mode 100644index 00000000..e01a3155--- /dev/null+++ b/claude-ops/scripts/account-rotation/claude-reauth2.mjs@@ -0,0 +1,176 @@+// claude-reauth2.mjs — reauth one Claude account into CLIProxyAPI using:+// playwright (bundled chromium) + existing Google session profile for in-browser Gmail magic-link reading.+// Usage: node claude-reauth2.mjs <claudeEmail> <oauthAuthorizeUrl>+// Env: GOOGLE_LOGIN_PROFILE (default /tmp/google-login-profile-GMAIL_PASS)+import { chromium } from 'playwright';+import { readFileSync } from 'fs';++const [claudeEmail, authUrl] = process.argv.slice(2);+if (!claudeEmail || !authUrl) { console.error('usage: node claude-reauth2.mjs <claudeEmail> <oauthAuthorizeUrl>'); process.exit(2); }+const PROFILE = process.env.GOOGLE_LOGIN_PROFILE || '/tmp/google-login-profile-GMAIL_PASS';++function readKeyFromDotenv(name) {+ try {+ const s = readFileSync(process.env.HOME + '/.env', 'utf8');+ const m = s.match(new RegExp('^' + name + '="?([^"\\n]+)"?', 'm'));+ return m ? m[1] : null;+ } catch (e) { return null; }+}++const sleep = (ms) => new Promise(r => setTimeout(r, ms));+const log = (m) => console.log(`[${new Date().toISOString().slice(11,19)}] ${m}`);+const shot = (p, n) => p.screenshot({ path: `/tmp/reauth2-${n}.png` }).catch(() => {});++const ctx = await chromium.launchPersistentContext(PROFILE, {+ headless: false, args: ['--window-position=100,100', '--window-size=1200,950', '--disable-blink-features=AutomationControlled'], viewport: null,+});+await ctx.addInitScript(() => { Object.defineProperty(navigator, 'webdriver', { get: () => undefined }); });+const page = ctx.pages()[0] || await ctx.newPage();+const sentAt = Date.now();++// ── 1. claude.ai login → send magic link ─────────────────────────────+await page.goto('https://claude.ai/login', { timeout: 45000, waitUntil: 'domcontentloaded' });+await sleep(4000);+// If already logged in as someone, log out first+if (!page.url().includes('/login')) {+ log('existing session at ' + page.url().slice(0, 60) + ' — logging out');+ await page.goto('https://claude.ai/logout', { timeout: 30000 }).catch(() => {});+ await sleep(3000);+ await page.goto('https://claude.ai/login', { timeout: 45000, waitUntil: 'domcontentloaded' });+ await sleep(4000);+}+const emailInput = await page.$('input[type="email"]');+if (!emailInput) { log('FAIL: no email input on login page'); await shot(page, 'noemail'); process.exit(1); }+await emailInput.fill(claudeEmail);+await page.keyboard.press('Enter');+log('magic link requested for ' + claudeEmail);+await sleep(5000);+await shot(page, 'sent');++// ── 2. Gmail tab → extract newest magic link ─────────────────────────+const gmail = await ctx.newPage();+await gmail.goto('https://mail.google.com/mail/u/0/#search/from%3Amail.anthropic.com+subject%3A%22secure+link%22', { timeout: 60000, waitUntil: 'domcontentloaded' });+await sleep(8000);+let magicLink = null;+for (let attempt = 0; attempt < 20 && !magicLink; attempt++) {+ if (attempt > 0) { await gmail.reload({ waitUntil: 'domcontentloaded' }).catch(() => {}); await sleep(7000); }+ // open the top message row+ const rows = await gmail.$$('tr.zA');+ if (!rows.length) { log('gmail: no rows yet (' + attempt + ')'); continue; }+ await rows[0].click().catch(() => {});+ await sleep(4000);+ // extract magic-link href from rendered message+ magicLink = await gmail.evaluate(() => {+ const links = [...document.querySelectorAll('a[href*="claude.ai/magic-link"], a[href*="claude.com/magic-link"]')];+ if (links.length) return links[0].href;+ // fallback: any href containing magic-link token+ const any = [...document.querySelectorAll('a')].find(a => /magic-link/i.test(a.href || ''));+ return any ? any.href : null;+ });+ if (magicLink) {+ // sanity: message must be fresh (< 10 min)+ const timeAttr = await gmail.evaluate(() => {+ const spans = [...document.querySelectorAll('span.g3')];+ return spans.length ? spans[spans.length - 1].getAttribute('title') : null;+ });+ log('gmail: found magic link (msg time: ' + (timeAttr || '?') + ')');+ if (timeAttr) {+ const msgTime = new Date(timeAttr).getTime();+ if (msgTime < sentAt - 60000) { log('stale message — waiting for fresh one'); magicLink = null; }+ }+ }+}+if (!magicLink) { log('FAIL: no magic link found'); await shot(gmail, 'gmail'); process.exit(1); }+log('magic link acquired');++// ── 3. open magic link → Claude session (may hit Arkose CAPTCHA — pause for human) ──+await page.goto(magicLink, { timeout: 45000, waitUntil: 'domcontentloaded' }).catch(e => log('magic nav: ' + e.message.slice(0, 60)));+await sleep(8000);++// CAPTCHA interlock: if Arkose/FunCAPTCHA present, notify user and wait for it to clear+async function captchaPresent() {+ return page.evaluate(() => {+ const ifr = [...document.querySelectorAll('iframe')].some(f => /arkoselabs|funcaptcha|captcha/i.test(f.src || ''));+ const txt = document.body ? /Drag the correct|complete the pattern|verify you are human/i.test(document.body.innerText) : false;+ return ifr || txt;+ }).catch(() => false);+}+if (await captchaPresent()) {+ // 1. try 2Captcha automated solve first+ const apiKey = process.env.TWOCAPTCHA_API_KEY || readKeyFromDotenv('TWOCAPTCHA_API_KEY');+ let solved = false;+ if (apiKey) {+ try {+ const { solveFunCaptcha, extractArkoseParams, injectFunCaptchaToken } = await import('./captcha-solve.mjs');+ const params = await extractArkoseParams(page);+ log('arkose params: pkey=' + (params.publicKey || '?') + ' surl=' + params.surl);+ if (params.publicKey) {+ const token = await solveFunCaptcha({+ pageUrl: 'https://claude.ai/', publicKey: params.publicKey, surl: params.surl, apiKey, log,+ });+ const injected = await injectFunCaptchaToken(page, token);+ log('token injected via: ' + injected.join(','));+ await sleep(6000);+ solved = !(await captchaPresent());+ log(solved ? 'CAPTCHA cleared automatically' : 'token injected but captcha still present');+ }+ } catch (e) { log('2captcha failed: ' + e.message.slice(0, 120)); }+ }+ // 1b. vision tier (Gemini via CLIProxyAPI)+ if (!solved && await captchaPresent()) {+ try {+ const { solveArkoseWithVision } = await import('./captcha-solve.mjs');+ solved = await solveArkoseWithVision(page, log, captchaPresent);+ log(solved ? 'CAPTCHA cleared by vision solver' : 'vision solver did not clear');+ } catch (e) { log('vision solver failed: ' + e.message.slice(0, 120)); }+ }+ // 2. human fallback+ if (!solved && await captchaPresent()) {+ log('CAPTCHA still present — waiting for human solve (' + claudeEmail + ')');+ try {+ const { execSync } = await import('child_process');+ execSync(`osascript -e 'display notification "Solve the Claude CAPTCHA in the automation browser for ${claudeEmail}" with title "Claude reauth — action needed" sound name "Glass"'`);+ execSync(`say "Claude reauth needs you to solve a captcha"`);+ } catch (e) {}+ const deadline = Date.now() + 8 * 60 * 1000;+ while (await captchaPresent()) {+ if (Date.now() > deadline) { log('FAIL: captcha not solved in 8 min'); process.exit(1); }+ await sleep(3000);+ }+ log('captcha cleared by human — continuing');+ }+ await sleep(4000);+}+await shot(page, 'after-magic');+log('post-magic url: ' + page.url().slice(0, 80));++// ── 4. OAuth authorize → callback into CLIProxyAPI ───────────────────+await page.goto(authUrl, { timeout: 45000, waitUntil: 'domcontentloaded' });+await sleep(5000);+await shot(page, 'oauth');+// click authorize/allow if a button is shown+for (const sel of ['button:has-text("Authorize")', 'button:has-text("Allow")', 'button:has-text("Continue")', 'button[type="submit"]']) {+ const b = await page.$(sel);+ if (b && await b.isVisible().catch(() => false)) { await b.click().catch(() => {}); log('clicked ' + sel); break; }+}+await sleep(8000);+// account selector page (claude.ai/login?selectAccount=true) — pick our account+if (page.url().includes('selectAccount')) {+ log('account selector — clicking ' + claudeEmail);+ await page.evaluate((em) => {+ const els = [...document.querySelectorAll('button, a, div[role="button"], li, div')];+ const t = els.find(e => (e.innerText || '').trim().includes(em));+ if (t) t.click();+ }, claudeEmail);+ await sleep(6000);+ // possible authorize button after selection+ for (const sel of ['button:has-text("Authorize")', 'button:has-text("Allow")', 'button:has-text("Continue")']) {+ const b = await page.$(sel);+ if (b && await b.isVisible().catch(() => false)) { await b.click().catch(() => {}); log('clicked ' + sel); break; }+ }+ await sleep(6000);+}+log('final url: ' + page.url().slice(0, 100));+await shot(page, 'final');+console.log('REAUTH_DONE ' + claudeEmail);+await ctx.close();diff --git a/claude-ops/scripts/account-rotation/cursor-cancel.mjs b/claude-ops/scripts/account-rotation/cursor-cancel.mjsnew file mode 100644index 00000000..56e6eb59--- /dev/null+++ b/claude-ops/scripts/account-rotation/cursor-cancel.mjs@@ -0,0 +1,112 @@+// cursor-cancel.mjs — cancel a Cursor subscription via Google SSO + dashboard billing.+// Usage: GOOGLE_CREDS_PATH=... node cursor-cancel.mjs <email> <passKey> [--execute]+// Without --execute: stops before the final confirm (dry run, screenshots only).+import { chromium } from 'playwright';+import { readFileSync } from 'fs';++const [email, passKey, ...flags] = process.argv.slice(2);+const EXECUTE = flags.includes('--execute');+if (!email || !passKey) { console.error('usage: node cursor-cancel.mjs <email> <passKey> [--execute]'); process.exit(2); }++const creds = Object.fromEntries(+ readFileSync(process.env.GOOGLE_CREDS_PATH, 'utf8').split('\n')+ .filter(l => l && !l.startsWith('#'))+ .map(l => { const i = l.indexOf('='); return [l.slice(0, i), l.slice(i + 1)]; })+);+const sleep = (ms) => new Promise(r => setTimeout(r, ms));+const log = (m) => console.log(`[${new Date().toISOString().slice(11,19)}] ${m}`);+const shot = (page, name) => page.screenshot({ path: `/tmp/cursor-cancel-${name}.png`, fullPage: true }).then(() => log('shot: /tmp/cursor-cancel-' + name + '.png')).catch(() => {});++const PROFILE_DIR = `/tmp/google-login-profile-${passKey}`;+const ctx = await chromium.launchPersistentContext(PROFILE_DIR, {+ headless: false,+ args: ['--window-position=100,100', '--window-size=1200,950', '--disable-blink-features=AutomationControlled'],+ viewport: null,+});+await ctx.addInitScript(() => {+ Object.defineProperty(navigator, 'webdriver', { get: () => undefined });+});+const page = ctx.pages()[0] || await ctx.newPage();++// 1. Go to a protected page — Cursor redirects to authenticator.cursor.sh with the SSO buttons+await page.goto('https://cursor.com/settings', { timeout: 45000, waitUntil: 'domcontentloaded' }).catch(() => {});+await sleep(4000);+await shot(page, '01-signin');++// 2. Click Google SSO if present+for (const sel of ['button:has-text("Continue with Google")', 'button:has-text("Google")', 'a:has-text("Continue with Google")', '[data-testid*="google" i]']) {+ const b = await page.$(sel);+ if (b && await b.isVisible().catch(() => false)) {+ await b.click().catch(() => {});+ log('clicked SSO ' + sel);+ break;+ }+}+await sleep(6000);++// 3. If we land on Google chooser, pick the account+const body = await page.evaluate(() => document.body ? document.body.innerText.slice(0, 2000) : '');+if (/Choose an account/i.test(body)) {+ await page.evaluate((em) => {+ const els = [...document.querySelectorAll('div[role="link"], li, div')];+ const t = els.find(e => (e.innerText || '').trim().startsWith(em.split('@')[0]));+ if (t) t.click();+ }, email);+ log('picked google account from chooser');+ await sleep(5000);+}+log('post-SSO url: ' + page.url().slice(0, 100));+await shot(page, '02-post-sso');++// 4. Go to dashboard settings+await page.goto('https://cursor.com/settings', { timeout: 45000, waitUntil: 'domcontentloaded' }).catch(() => {});+await sleep(4500);+log('settings url: ' + page.url().slice(0, 100));+await shot(page, '03-settings');++// 5. Find billing / subscription management+const pageText = await page.evaluate(() => document.body ? document.body.innerText : '');+const planLine = pageText.split('\n').find(l => /pro|business|free|trial|plan/i.test(l) && l.length < 80);+log('plan indicator: ' + (planLine || 'not found').trim());++let clicked = null;+for (const sel of ['a:has-text("Billing")', 'button:has-text("Billing")', 'text=Manage subscription', 'a:has-text("Manage")', 'text=Billing']) {+ const b = await page.$(sel);+ if (b && await b.isVisible().catch(() => false)) {+ await b.click().catch(() => {});+ clicked = sel;+ log('clicked ' + sel);+ await sleep(4000);+ break;+ }+}+await shot(page, '04-billing');++// 6. Cancel button+for (const sel of ['button:has-text("Cancel subscription")', 'button:has-text("Cancel plan")', 'text=Cancel subscription', 'button:has-text("Cancel")']) {+ const b = await page.$(sel);+ if (b && await b.isVisible().catch(() => false)) {+ await b.click().catch(() => {});+ log('clicked ' + sel);+ await sleep(3000);+ break;+ }+}+await shot(page, '05-cancel-dialog');++// 7. Confirm dialog (only with --execute)+const confirm = await page.$('button:has-text("Confirm")') || await page.$('button:has-text("Yes, cancel")') || await page.$('button:has-text("Cancel subscription")');+if (confirm && await confirm.isVisible().catch(() => false)) {+ if (EXECUTE) {+ await confirm.click().catch(() => {});+ log('CONFIRMED cancellation');+ await sleep(4000);+ } else {+ log('DRY RUN — confirm button present but not clicked (pass --execute)');+ }+} else {+ log('no confirm button found');+}+await shot(page, '06-final');+console.log('FINAL_URL=' + page.url());+await ctx.close();diff --git a/claude-ops/scripts/account-rotation/factory-cancel.mjs b/claude-ops/scripts/account-rotation/factory-cancel.mjsnew file mode 100644index 00000000..6f213312--- /dev/null+++ b/claude-ops/scripts/account-rotation/factory-cancel.mjs@@ -0,0 +1,58 @@+// factory-cancel.mjs — log into Factory (Google SSO via existing profile) and reach billing.+// Usage: node factory-cancel.mjs [--execute]+import { chromium } from 'playwright';++const EXECUTE = process.argv.includes('--execute');+const GOOGLE_EMAIL = process.env.FACTORY_GOOGLE_EMAIL;+if (!GOOGLE_EMAIL) { console.error('set FACTORY_GOOGLE_EMAIL'); process.exit(2); }+const sleep = (ms) => new Promise(r => setTimeout(r, ms));+const log = (m) => console.log(`[${new Date().toISOString().slice(11,19)}] ${m}`);+const shot = (p, n) => p.screenshot({ path: `/tmp/factory-${n}.png`, fullPage: true }).then(() => log('shot /tmp/factory-' + n + '.png')).catch(() => {});++const ctx = await chromium.launchPersistentContext('/tmp/google-login-profile-GMAIL_PASS', {+ headless: false, args: ['--window-position=100,100', '--window-size=1200,950', '--disable-blink-features=AutomationControlled'], viewport: null,+});+await ctx.addInitScript(() => { Object.defineProperty(navigator, 'webdriver', { get: () => undefined }); });+const p = ctx.pages()[0] || await ctx.newPage();++async function clickWhenVisible(text, timeout = 15000) {+ const loc = p.getByText(text, { exact: false }).first();+ await loc.waitFor({ state: 'visible', timeout });+ await loc.click();+ log('clicked "' + text + '"');+}++await p.goto('https://app.factory.ai/', { timeout: 45000, waitUntil: 'domcontentloaded' });+await sleep(12000);++// cookies (optional)+try { await clickWhenVisible('AGREE', 4000); } catch (e) { log('no cookie banner'); }+await sleep(1000);++// LOG IN+await clickWhenVisible('LOG IN', 20000);+await sleep(6000);++// Google SSO+await clickWhenVisible('Continue with Google', 20000);+await sleep(8000);++// account chooser (if shown)+const t = await p.evaluate(() => document.body ? document.body.innerText.slice(0, 600) : '');+if (/Choose an account/i.test(t)) {+ await clickWhenVisible(GOOGLE_EMAIL, 10000);+ await sleep(10000);+}+log('URL after SSO: ' + p.url().slice(0, 110));+await shot(p, '10-dashboard');+const dt = await p.evaluate(() => document.body ? document.body.innerText.slice(0, 1500) : '');+log('dashboard text: ' + dt.split('\n').filter(l => l.trim()).slice(0, 25).join(' | '));++// look for settings/billing links+for (const probe of ['Settings', 'Billing', 'Usage', 'Plan', 'Subscription', 'Account']) {+ const loc = p.getByText(probe, { exact: true }).first();+ if (await loc.isVisible().catch(() => false)) log('nav item visible: ' + probe);+}++console.log('FINAL_URL=' + p.url());+await ctx.close();diff --git a/claude-ops/scripts/account-rotation/google-login.mjs b/claude-ops/scripts/account-rotation/google-login.mjsnew file mode 100644index 00000000..01fe1a32--- /dev/null+++ b/claude-ops/scripts/account-rotation/google-login.mjs@@ -0,0 +1,237 @@+// google-login.mjs — reusable Google sign-in via playwright + dcli-sourced creds.+// Usage: node google-login.mjs <email> <targetUrl> [headed=1]+// Prints FINAL_URL=<url> on success, exits 0 when targetUrl reached (or Google auth completed).+import { chromium } from 'playwright';+import { execSync } from 'child_process';+import { readFileSync, writeFileSync } from 'fs';++const [email, targetUrl, passKey] = process.argv.slice(2);+if (!email || !targetUrl || !passKey) { console.error('usage: node google-login.mjs <email> <targetUrl> <passKeyInCredsFile>'); process.exit(2); }++const credsPath = process.env.GOOGLE_CREDS_PATH;+const creds = Object.fromEntries(+ readFileSync(credsPath, 'utf8').split('\n')+ .filter(l => l && !l.startsWith('#'))+ .map(l => { const i = l.indexOf('='); return [l.slice(0, i), l.slice(i + 1)]; })+);+const password = creds[passKey];+if (!password) { console.error('no password for ' + email); process.exit(2); }++const sleep = (ms) => new Promise(r => setTimeout(r, ms));+const log = (m) => console.log(`[${new Date().toISOString().slice(11,19)}] ${m}`);++function freshOtp() {+ const idKey = passKey.replace('_PASS', '_OTP_ID');+ const entryId = creds[idKey];+ const filter = entryId ? `id=${entryId}` : `email=${email}`;+ const out = execSync(`/opt/homebrew/bin/dcli password -o console -f otp '${filter}'`, { timeout: 20000 })+ .toString().replace(/\x1b\[[0-9;]*m/g, '').trim().split('\n');+ const code = out[out.length - 1].trim();+ if (!/^\d{6}$/.test(code)) throw new Error('bad otp from dcli: ' + code.slice(0, 3) + '...');+ return code;+}++export async function googleLogin(page) {+ log('google signin start for ' + email);+ let idleRounds = 0;+ for (let step = 0; step < 25; step++) {+ const url = page.url();+ const onSignin = url.includes('accounts.google.com');+ if (!onSignin && step > 0) {+ log('left google signin flow: ' + url.slice(0, 90));+ return true;+ }+ // email field — v3 signin may nest the input in web components / frames+ let emailInput = null;+ for (const frame of page.frames()) {+ for (const sel of ['input[type="email"]', 'input#identifierId', 'input[name="identifier"]', 'input[aria-label*="mail" i]', 'input[autocomplete="username"]']) {+ emailInput = await frame.$(sel);+ if (emailInput && await emailInput.isVisible().catch(() => false)) break;+ emailInput = null;+ }+ if (emailInput) break;+ }+ if (emailInput) {+ await emailInput.fill(email);+ await page.keyboard.press('Enter');+ log('email submitted');+ idleRounds = 0;+ await sleep(3500);+ continue;+ }+ // password field — same frame-tolerant lookup+ let passInput = null;+ for (const frame of page.frames()) {+ for (const sel of ['input[type="password"]', 'input[name="Passwd"]', 'input[autocomplete="current-password"]']) {+ passInput = await frame.$(sel);+ if (passInput && await passInput.isVisible().catch(() => false)) break;+ passInput = null;+ }+ if (passInput) break;+ }+ if (passInput) {+ await passInput.fill(password);+ await page.keyboard.press('Enter');+ log('password submitted');+ idleRounds = 0;+ globalThis.__pwSubmits = (globalThis.__pwSubmits || 0) + 1;+ await sleep(4000);+ // detect wrong-password / hard errors right after submit (EN + NL)+ const errText = await page.evaluate(() => document.body ? document.body.innerText.slice(0, 1500) : '');+ if (/Wrong password|incorrect password|Couldn.t sign you in|too many|onjuist|verkeerd|fout wachtwoord|Controleer je wachtwoord/i.test(errText)) {+ const stillPwd = await page.$('input[type="password"]');+ if (stillPwd) {+ log('ERROR after password: ' + errText.split('\n').filter(l => /wachtwoord|password|onjuist|verkeerd|sign/i.test(l)).slice(0,3).join(' | '));+ await page.screenshot({ path: `/tmp/google-login-error-${passKey}.png` }).catch(() => {});+ return false;+ }+ }+ if (globalThis.__pwSubmits >= 3) {+ log('password submitted 3x without progress — page says: ' + errText.split('\n').slice(0, 6).join(' | '));+ await page.screenshot({ path: `/tmp/google-login-error-${passKey}.png` }).catch(() => {});+ return false;+ }+ continue;+ }+ // TOTP input page — HIGHEST PRIORITY once visible (must run before chooser handlers,+ // because the TOTP page text itself matches chooser regexes)+ const bodyText = await page.evaluate(() => document.body ? document.body.innerText.slice(0, 3000) : '');+ if (/2-Step Verification|verification code|authenticator/i.test(bodyText)) {+ const otpInput = await page.$('input[type="tel"], input[id*="totp" i], input[autocomplete="one-time-code"], input[type="text"][inputmode="numeric"]');+ if (otpInput && await otpInput.isVisible()) {+ const code = freshOtp();+ await otpInput.fill(code);+ await page.keyboard.press('Enter');+ log('totp submitted');+ idleRounds = 0;+ await sleep(4000);+ continue;+ }+ }+ // passkey/2FA challenge — pick Authenticator TOTP from the options list directly+ if (/passkey|Verifying it.?s you|Security Key|Try another way|Choose how to sign in/i.test(bodyText)) {+ // locate the li by text in DOM, then click via real mouse at its coordinates (Google binds mousedown, not click)+ const box = await page.evaluate(() => {+ const lis = [...document.querySelectorAll('li')];+ const norm = (s) => (s || '').replace(/\s+/g, ' ').trim();+ const target = lis.find(li => /verification code from the Google Authenticator/i.test(norm(li.innerText)))+ || lis.find(li => /Authenticator app/i.test(norm(li.innerText)))+ || lis.find(li => norm(li.innerText) === 'Try another way');+ if (!target) return null;+ const r = target.getBoundingClientRect();+ return { x: r.x + r.width / 2, y: r.y + r.height / 2, label: norm(target.innerText).slice(0, 60) };+ });+ if (box) {+ await page.mouse.move(box.x, box.y);+ await page.mouse.down();+ await sleep(80);+ await page.mouse.up();+ log('challenge list → mouse-clicked "' + box.label + '"');+ idleRounds = 0;+ await sleep(4000);+ continue;+ }+ }+ // "choose an account" page — pick ours (only on the real chooser, not the account pill)+ if (/Choose an account/i.test(bodyText)) {+ const acct = await page.$(`text=${email}`);+ if (acct) {+ await acct.click().catch(() => {});+ log('account chooser clicked');+ idleRounds = 0;+ await sleep(3000);+ continue;+ }+ }+ // consent screens ("Continue" / "Allow")+ let clicked = false;+ for (const sel of ['button:has-text("Continue")', 'button:has-text("Allow")', '#submit_approve_access']) {+ const b = await page.$(sel);+ if (b && await b.isVisible().catch(() => false)) {+ await b.click().catch(() => {});+ log('clicked ' + sel);+ clicked = true;+ idleRounds = 0;+ await sleep(3000);+ break;+ }+ }+ if (!clicked) {+ idleRounds++;+ if (idleRounds >= 3) {+ // nothing actionable for 3 rounds — if we're off accounts.google.com, call it success+ if (!page.url().includes('accounts.google.com')) return true;+ }+ }+ await sleep(2000);+ }+ log('google login flow did not converge; url=' + page.url().slice(0, 100));+ return false;+}++const PROFILE_DIR = process.env.GOOGLE_LOGIN_PROFILE || '/tmp/google-login-profile-' + passKey;+const launchArgs = [+ '--window-position=100,100', '--window-size=1100,900',+ '--disable-blink-features=AutomationControlled',+ '--disable-features=AutomationControlled',+ '--lang=en-US,en',+];+let ctx;+try {+ // Preferred: real Chrome stable (Google accepts it far more often than bundled chromium)+ ctx = await chromium.launchPersistentContext(PROFILE_DIR + '-chrome', {+ headless: false, channel: 'chrome', args: launchArgs, viewport: null, timeout: 15000,+ });+ log('driver: real chrome channel');+} catch (e) {+ log('chrome channel failed (' + e.message.slice(0, 60) + ') — bundled chromium');+ ctx = await chromium.launchPersistentContext(PROFILE_DIR, {+ headless: false, args: launchArgs, viewport: null,+ });+}+await ctx.addInitScript(() => {+ Object.defineProperty(navigator, 'webdriver', { get: () => undefined });+ Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'] });+ Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3] });+ // Hide WebAuthn/passkey support so Google offers password+TOTP instead of passkey-first+ try { delete window.PublicKeyCredential; } catch (e) { window.PublicKeyCredential = undefined; }+ Object.defineProperty(navigator, 'credentials', { get: () => undefined, configurable: true });+});+const page = ctx.pages()[0] || await ctx.newPage();++// Step 1: authenticate at Google directly (email field on first screen)+await page.goto('https://accounts.google.com/signin/v2/identifier?flowName=GlifWebSignIn&flowEntry=ServiceLogin',+ { timeout: 40000, waitUntil: 'domcontentloaded' });+await sleep(3000);++const ok = await googleLogin(page);+if (!ok) {+ log('LOGIN_FAIL at google');+ console.log('FINAL_URL=' + page.url());+ await page.screenshot({ path: `/tmp/google-login-fail.png` }).catch(() => {});+ await ctx.close();+ process.exit(1);+}++// Step 2: now navigate to the real target (Google session is established in this context)+log('google session established — navigating to target ' + targetUrl);+await page.goto(targetUrl, { timeout: 40000, waitUntil: 'domcontentloaded' }).catch(e => log('target nav warn: ' + e.message.slice(0, 80)));+await sleep(4000);++// If the target shows its own "Sign in with Google" button, click it (session exists now)+for (const sel of ['button:has-text("Continue with Google")', 'button:has-text("Sign in with Google")', 'a:has-text("Sign in with Google")']) {+ const b = await page.$(sel);+ if (b && await b.isVisible().catch(() => false)) {+ await b.click().catch(() => {});+ log('clicked target SSO button ' + sel);+ await sleep(5000);+ break;+ }+}++log('LOGIN_OK');+console.log('FINAL_URL=' + page.url());+await page.screenshot({ path: `/tmp/google-login-ok.png` }).catch(() => {});+await sleep(2000);+await ctx.close();+process.exit(0);diff --git a/claude-ops/scripts/ops-accounts/providers/cliproxy.mjs b/claude-ops/scripts/ops-accounts/providers/cliproxy.mjsnew file mode 100644index 00000000..6ed8bb6a--- /dev/null+++ b/claude-ops/scripts/ops-accounts/providers/cliproxy.mjs@@ -0,0 +1,88 @@+/**+ * CLIProxyAPI adapter — reports local multi-provider proxy accounts.+ * Reads the proxy's auth-dir (flat JSON files, one per account) and reports+ * inventory only. No secrets are read into output: file names carry+ * provider+email; token payloads are never printed.+ *+ * Env overrides: CLIPROXYAPI_HOME, CLIPROXYAPI_PORT.+ */+import { existsSync, readdirSync, statSync } from 'fs';+import { join } from 'path';++export const providerId = 'cliproxy';+export const displayName = 'CLIProxyAPI (local multi-provider proxy)';++function authDir(ctx) {+ const home = process.env.CLIPROXYAPI_HOME || join(ctx.home, 'Developer/active/cliproxyapi');+ return join(home, 'auths');+}++function parseFileName(name) {+ // <provider>-<label>.json ; provider prefixes: claude, codex, xai, antigravity, gemini+ const m = name.match(/^([a-z0-9]+)-(.+)\.json$/i);+ if (!m) return null;+ return { backend: m[1], label: m[2] };+}++export async function listAccounts(ctx) {+ const dir = authDir(ctx);+ if (!existsSync(dir)) {+ return [+ {+ provider: providerId,+ accountId: 'cliproxy-not-installed',+ email: null,+ label: 'auth-dir missing',+ tokenState: 'missing',+ active: false,+ utilization: null,+ crs: null,+ lastError: null,+ note: 'CLIProxyAPI not installed (optional backend; set CLIPROXYAPI_HOME)',+ reauth: { status: 'unavailable' },+ },+ ];+ }+ const out = [];+ for (const f of readdirSync(dir)) {+ const p = parseFileName(f);+ if (!p) continue;+ const st = statSync(join(dir, f));+ const email = p.label.includes('@') ? p.label.split('-')[0] : null;+ out.push({+ provider: providerId,+ accountId: `${p.backend}:${p.label}`,+ email,+ label: p.backend,+ tokenState: 'valid', // presence-only check; proxy dropouts surface as request failures+ active: true,+ utilization: null,+ crs: null,+ lastError: null,+ note: `last write ${st.mtime.toISOString()}`,+ reauth: { status: 'manual', note: `cliproxy login flow for ${p.backend}` },+ });+ }+ return out;+}++export async function utilization(ctx) {+ const dir = authDir(ctx);+ if (!existsSync(dir)) return null;+ const counts = {};+ for (const f of readdirSync(dir)) {+ const p = parseFileName(f);+ if (!p) continue;+ counts[p.backend] = (counts[p.backend] || 0) + 1;+ }+ return { accounts_by_backend: counts, note: 'pool-level util comes from the proxy management API (out of scope)' };+}++export async function reauth(_ctx, accountId) {+ const backend = (accountId || '').split(':')[0] || 'claude';+ return {+ ok: false,+ reason: 'manual-browser-flow',+ handoff: `Run the CLIProxyAPI ${backend} login flow (browser) — see SERVICE.md in the proxy dir.`,+ };+}