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.

chore: migrate ops wording to cliproxy and add reauth 2fa

mission-worker7cd9998dd7c1
diff --git a/claude-ops/CHANGELOG.md b/claude-ops/CHANGELOG.md
index 5d8d703e..fd50cecf 100644
--- a/claude-ops/CHANGELOG.md
+++ b/claude-ops/CHANGELOG.md
@@ -15,9 +15,9 @@
### Changed
- **ops-accounts multi-provider plan:** every provider (Claude, Grok, OpenAI/Codex, Factory, Cursor) gets Anthropic-shaped OAuth, reauth, util, switch/LB under `/ops:accounts`.
-- **CRS cherry-pick path:** absorb gateway + Claude seat policy + Grok OAuth proxy into ops-accounts so default installs need no claude-relay-service; external CRS stays advanced-only. See `docs/ops/OPS-ACCOUNTS-VISION.md`.
-- **ops-accounts seat policy (local):** `seat-policy-tick.mjs` applies conservative 5h/7d schedulable thresholds to local seat-state without CRS; `ops-accounts seats tick`.
-- **ops-accounts local seat-state:** `seat-state.mjs` file-backed multi-provider seat store (schedulable/util) for no-CRS policy backend; `ops-accounts seats` command.
+- **CLIProxyAPI gateway path:** absorb gateway + Claude seat policy + Grok OAuth proxy into ops-accounts so default installs use CLIProxyAPI-compatible relay behavior without requiring the deprecated relay stack; external legacy CRS stays advanced-only. See `docs/ops/OPS-ACCOUNTS-VISION.md`.
+- **ops-accounts seat policy (local):** `seat-policy-tick.mjs` applies conservative 5h/7d schedulable thresholds to local seat-state without a relay; `ops-accounts seats tick`.
+- **ops-accounts local seat-state:** `seat-state.mjs` file-backed multi-provider seat store (schedulable/util) for local policy backend; `ops-accounts seats` command.
- **ops-accounts skill merge:** `/ops:accounts` is canonical multi-provider entry; `/ops:rotate` and `/ops:rotate-setup` are aliases. Expanded `bin/ops-accounts` (status/util/switch/refresh/reauth/setup/crs). Added `grok-reauth-egress.sh` residential cascade (EFG SOCKS → Bright Data tiers) for Grok device OAuth.
- **Required companion co-install:** companions essential to ops commands are no longer optional setup prompts. `plugin-dependencies.json` marks `desktop-act`, `gsd`, `gstack` (skills clone), `superpowers`, and `feature-dev` as `required: true` with `updateWithOps: always` and `essentialFor` command lists. `scripts/install-companions.sh` always installs missing required companions (even under `--update-only`), and `--status` exits 1 when any required companion is missing. `/ops:setup` Step 2b runs the SSOT script without Skip for required deps. `/ops:update` step 9 co-installs the full required set (still skippable only via `--no-companions` / `OPS_SKIP_COMPANIONS=1`). Adds `scripts/install-gstack-companion.sh` (env-templated `GSTACK_REPO`/`GSTACK_DIR`/`GSTACK_BRANCH`).
diff --git a/claude-ops/README.md b/claude-ops/README.md
index 2a303bad..79cd8c06 100644
--- a/claude-ops/README.md
+++ b/claude-ops/README.md
@@ -60,8 +60,8 @@ Per-repo budget caps (default 3/hour), single-flight locks, content-hash dedup,
| ------------------- | --------------------------------------------------------------------------------- |
| `/ops` | Interactive command center dashboard (visual HQ) |
| `/ops:dash` | Same as `/ops` — pixel-art dashboard with hotkey navigation |
-| `ops-healify-dash` | Dedicated Healify.ai KPI, growth, App Store, reliability, infra, repo, agent, MCP, and plugin command center |
-| `ops-healify-bi-refresh` | Warms the Healify BI cache used by `ops-healify-dash` from EAS, ASC, AppsFlyer, Amplitude, Sentry, BetterStack, Linear, QA, and ops-dashboard sources |
+| `ops-client-dash` | Dedicated client KPI, growth, App Store, reliability, infra, repo, agent, MCP, and plugin command center |
+| `ops-client-bi-refresh` | Warms the client BI cache used by `ops-client-dash` from EAS, ASC, AppsFlyer, Amplitude, Sentry, BetterStack, Linear, QA, and ops-dashboard sources |
| `/ops:setup` | Interactive setup wizard — installs CLIs, configures channels, builds registry |
| `/ops:go` | Morning briefing — all systems in one dashboard |
| `/ops:next` | Priority-ordered next action (fires > comms > PRs > sprint > GSD) |
diff --git a/claude-ops/bin/ops-accounts b/claude-ops/bin/ops-accounts
index 1f8efee0..d02b45cf 100755
--- a/claude-ops/bin/ops-accounts
+++ b/claude-ops/bin/ops-accounts
@@ -91,10 +91,10 @@ PY
else
echo "grok-cli-auth-proxy not configured or unreachable (set GROK_PROXY_URL)"
fi
- if [[ -n "$CRS_GROK_BASE_URL" ]] && curl -fsS -m 2 -o /dev/null -w "crs_grok_hop HTTP %{http_code}\n" "${CRS_GROK_BASE_URL%/}/models" 2>/dev/null; then
+ if [[ -n "$CRS_GROK_BASE_URL" ]] && curl -fsS -m 2 -o /dev/null -w "cliproxy_grok_hop (legacy CRS_GROK_BASE_URL) HTTP %{http_code}\n" "${CRS_GROK_BASE_URL%/}/models" 2>/dev/null; then
:
else
- echo "crs_grok_hop: not reachable (optional thin hop)"
+ echo "cliproxy_grok_hop: not reachable (optional thin hop; legacy env CRS_GROK_BASE_URL)"
fi
}
# --- CLIProxyAPI backend (optional local multi-provider proxy) ---
@@ -299,14 +299,14 @@ PY
if [[ -x "$ROT/crs-priority-daemon.sh" ]]; then
bash "$ROT/crs-priority-daemon.sh" --status 2>&1 | head -40
else
- echo "CRS priority script missing (optional)"
+ echo "cliproxy / CLIProxyAPI priority script missing (optional; legacy filename retained)"
fi
;;
crs-tick)
if [[ -x "$ROT/crs-priority-daemon.sh" ]]; then
bash "$ROT/crs-priority-daemon.sh" "$@"
else
- echo "CRS priority script missing"; exit 1
+ echo "cliproxy / CLIProxyAPI priority script missing (legacy filename retained)"; exit 1
fi
;;
seats)
diff --git a/claude-ops/bin/ops-bg b/claude-ops/bin/ops-bg
index 59ef2675..7592bd5a 100755
--- a/claude-ops/bin/ops-bg
+++ b/claude-ops/bin/ops-bg
@@ -86,9 +86,9 @@ cmd_dispatch() {
exit 2
fi
local prompt="$*"
- # CRS routing: every bg session ops-bg spawns inherits the sanctioned overlay
+ # cliproxy / CLIProxyAPI routing: every bg session ops-bg spawns inherits the sanctioned overlay
# (ANTHROPIC_BASE_URL + CLAUDE_CODE_OAUTH_TOKEN). Preflight refuses to spawn if
- # the overlay is half-set or the key is 401-rejected. Opt out with CRS_OVERLAY="".
+ # the overlay is half-set or the key is 401-rejected. Opt out with CRS_OVERLAY="" (legacy env name).
local CRS_OVERLAY="${CRS_OVERLAY-$HOME/.claude/crs-session-settings.json}"
local -a crs_args=()
if [ -n "$CRS_OVERLAY" ]; then
diff --git a/claude-ops/bin/ops-fleet b/claude-ops/bin/ops-fleet
index ce1f6bd1..d21357ee 100755
--- a/claude-ops/bin/ops-fleet
+++ b/claude-ops/bin/ops-fleet
@@ -1,14 +1,14 @@
#!/usr/bin/env bash
# fleet-status.sh — polished fleet dashboard.
# Unifies everything `claude agents --json`, `claude daemon status`, the daemon roster.json,
-# each session's job state.json, the rotation daemon state, and CRS expose — per session:
-# token type (oauth/api/bedrock/crs) · CRS routing · agent type · effort/model · respawn-attempts
+# each session's job state.json, the rotation daemon state, and CLIProxyAPI-compatible relay expose — per session:
+# token type (oauth/api/bedrock/cliproxy) · relay routing · agent type · effort/model · respawn-attempts
# · repo · uptime · last-update · last-write · leased account · live detail · last error.
# Read-only. No mutation. Usage: fleet-status.sh [--all] [--watch [secs]] [--no-color]
set -uo pipefail
CLAUDE_BIN="${CLAUDE_BIN:-/usr/local/bin/claude}"
-CRS_PORT="${CRS_PORT:-3005}" # CRS (Claude Relay Service) listen port (3000 = legacy)
+CRS_PORT="${CRS_PORT:-3005}" # CLIProxyAPI-compatible relay listen port (legacy env; 3000 = legacy)
AR="$HOME/.claude/scripts/account-rotation"
PROJ="$HOME/.claude/projects/-Users-<USER>"
EC2_CACHE="${FLEET_EC2_CACHE:-$HOME/.claude/state/fleet-ec2.json}"
@@ -245,7 +245,7 @@ title=" FLEET DASHBOARD "; clock=f" {time.strftime('%Y-%m-%d %H:%M:%S')} "
fill=W-len(title)-len(clock)
print(f"{B}╔{title}{'═'*fill}{clock}╗{R}")
print(f" {B}DAEMON{R} pid {d_pid} · v{d_ver} · up {d_up} · {origin} · sock {sock} · workers {d_work} · roster {d_roster}")
-print(f" {B}CRS{R} /health {hb} · allowlist {crs_allow_label} · 6m: done~{crs_done} {YEL}429:{crs_429}{R} {RED}529:{crs_529}{R} · keychain-swap {rh}")
+print(f" {B}CLIPROXY{R} /health {hb} · legacy allowlist {crs_allow_label} · 6m: done~{crs_done} {YEL}429:{crs_429}{R} {RED}529:{crs_529}{R} · keychain-swap {rh}")
if ec2_on:
if ec2_ok:
m=re.search(r'(\d+) running.*?(\d+) in roster',ec2_daemon)
@@ -255,7 +255,7 @@ if ec2_on:
print(f" {B}EC2 FRA{R} {GRN}✓{R} {ec2_n} sess · {dw}cache {agestr} ago{stale} {D}· {ec2_inst}{R}")
else:
print(f" {B}EC2 FRA{R} {RED}✗ {ec2_err or 'no cache'}{R} {D}(refreshing in background…){R}")
-print(f" {D}token {GRN}oauth{D}=Max {YEL}api{D}=metered {MAG}bedrock{D}=AWS {CYN}crs{D}=relay→Max pool crs: {CYN}▶{D}routing ●listed ·direct {BLU}fra{D}=EC2 session{R}")
+print(f" {D}token {GRN}oauth{D}=Max {YEL}api{D}=metered {MAG}bedrock{D}=AWS {CYN}cliproxy{D}=relay→Max pool relay: {CYN}▶{D}routing ●listed ·direct {BLU}fra{D}=EC2 session{R}")
print(f"{B}╚{'═'*(W)}╝{R}")
# ---- group by state ----
@@ -335,9 +335,9 @@ for email,info in sorted(accts.items(),key=lambda x:-(x[1].get("lastUtilization"
bill=(info.get("lastBilling",{}) or {}).get("billing_type","—"); extra=" +x" if (info.get("lastBilling",{}) or {}).get("extra_usage_enabled") else ""
print(f" {email:34} {barv} {col}{str(pct if pct is not None else '—'):>3}%{R} {D}{reset_in(u):>9} · act {iso_ago(info.get('lastActive')):>6} · {bill}{extra}{R}")
-# ---- CRS proxy routing ----
+# ---- CLIProxyAPI/legacy CRS proxy routing ----
if acct_hits:
- print(f"{B}CRS ROUTING{R} {D}(accounts used last 6m){R}")
+ print(f"{B}CLIPROXY ROUTING{R} {D}(accounts used last 6m){R}")
line=" "+" ".join(f"{CYN}{a}{R}{D}:{n}{R}" for a,n in sorted(acct_hits.items(),key=lambda x:-x[1]))
print(line)
PY
diff --git a/claude-ops/bin/ops-no-rm-rf-anchor b/claude-ops/bin/ops-no-rm-rf-anchor
index 193da2c9..58b9cebf 100755
--- a/claude-ops/bin/ops-no-rm-rf-anchor
+++ b/claude-ops/bin/ops-no-rm-rf-anchor
@@ -84,23 +84,21 @@ DANGER=$(set -f; while IFS= read -r seg; do
# Tokenize on spaces (best-effort — won't perfectly handle quoted-with-spaces but covers the patterns specified).
for tok in $rest; do
# Skip flags.
- case "$tok" in
- -*) continue ;;
- esac
+ if [[ "$tok" == -* ]]; then
+ continue
+ fi
# Strip surrounding quotes for comparison.
bare="${tok%\"}"; bare="${bare#\"}"
bare="${bare%\'}"; bare="${bare#\'}"
- case "$bare" in
- "" | "/" | "/*" | "/." | \
- "~" | "~/" | "~/*" | \
- '$HOME' | '$HOME/' | '$HOME/*' | \
- ".." | "../" | "../*" | \
- ".")
- DANGER="$bare"
- break
- ;;
- esac
+ if [[ "$bare" == "" || "$bare" == "/" || "$bare" == "/*" || "$bare" == "/." || \
+ "$bare" == "~" || "$bare" == "~/" || "$bare" == "~/*" || \
+ "$bare" == '$HOME' || "$bare" == '$HOME/' || "$bare" == '$HOME/*' || \
+ "$bare" == ".." || "$bare" == "../" || "$bare" == "../*" || \
+ "$bare" == "." ]]; then
+ DANGER="$bare"
+ break
+ fi
# Also catch quoted $HOME variants where the shell hasn't expanded them.
if [[ "$tok" == '"$HOME"' || "$tok" == '"$HOME"/' || "$tok" == '"$HOME"/*' ]]; then
DANGER="$tok"; break
diff --git a/claude-ops/docs/healify-dashboard.md b/claude-ops/docs/healify-dashboard.md
index 7e3f633c..b547c957 100644
--- a/claude-ops/docs/healify-dashboard.md
+++ b/claude-ops/docs/healify-dashboard.md
@@ -1,69 +1,29 @@
-# Healify Dashboard
+# Client Dashboard
-`ops-healify-dash` is a dedicated Healify.ai command center for terminal and tmux workflows. It is read-only by default and designed for dark terminals with an orange Healify.ai brand treatment.
+This repository is public, so client-specific dashboard details live outside the committed docs. Keep this page generic and avoid real customer, operator, or brand identifiers.
-## Commands
+## Public Contract
-```bash
-ops-healify-dash --once
-ops-healify-dash --watch
-ops-healify-dash --refresh
-ops-healify-dash --json
-ops-healify-bi-refresh
-```
-
-`--refresh` refreshes bounded local caches first. `--watch` rerenders on an interval. Neither mode changes tmux focus or selects another window.
-
-`ops-dash` can explicitly delegate to this surface:
-
-```bash
-OPS_HEALIFY_DASH=1 ops-dash
-```
+A client dashboard may aggregate only local, already-configured sources and should remain read-only by default. Watch modes may rerender on an interval, but they must not change tmux focus or select another window.
## Data Sources
-The dashboard aggregates only local, already-configured sources:
+Allowed source categories for public documentation:
-- `ops:projects` cache: `$OPS_DATA_DIR/cache/projects_health.json`
-- statusline KPI cache: `~/.claude/state/statusline-kpi.json`
-- live endpoint health cache: `~/.cache/agent-hub/infra-health.json`
-- AWS ECS health cache: `~/.cache/agent-hub/aws-ecs-health.json`
-- plugin inventory: `~/.cache/agent-hub/plugin-inventory.json`
-- Healify BI cache: `~/.cache/agent-hub/healify-bi.json`
-- runtime health: `~/.cache/agent-hub/fleet/runtime-health.txt`
-- local Healify git repos under `~/Projects/healify-workspace`
+- project health caches
+- statusline KPI caches
+- live endpoint health caches
+- cloud service health caches
+- plugin inventory
+- runtime health summaries
- important ops and agent-hub logs
-`ops-healify-bi-refresh` warms the BI cache from authenticated local and ops-dashboard sources when available:
-
-- EAS latest iOS builds
-- App Store Connect app versions, build numbers, processing state, and reviews
-- App Store Connect sales/download status, clearly marked blocked when the vendor number is missing
-- AppsFlyer installs, organic split, loyal users, and cost
-- Amplitude active/new-user status
-- Sentry unresolved issue counts by Healify project
-- BetterStack uptime/incidents
-- Linear priority issue counts
-- mobile QA and Pact/contract health from the operating dashboard integration source
-
-It shows business KPIs, acquisition and marketing state, App Store/TestFlight release state, reviews, project execution state, service health, ECS deployment status, repo drift, agent/MCP/CLI readiness, plugin coverage, and recent important logs.
+Authenticated business intelligence sources, app-store metadata, analytics providers, incident providers, and issue trackers must be documented in private runbooks instead of this public repo.
## Branding
-The 1:1 pixel icon lives at:
-
-```text
-assets/healify-pixel-logo.svg
-```
-
-It follows the current Healify.ai app-icon direction: orange/pink rounded square, high contrast, and a white heart/pill health mark. The terminal dashboard renders the same concept as ANSI pixel blocks.
+Do not commit client-specific names, logos, colors, or brand assets in this public documentation. Use private docs for client-specific dashboard branding.
## Tmux Integration
-Any tmux binding should open this dashboard only through explicit user action, for example:
-
-```tmux
-bind v display-popup -E -w 96% -h 92% "ops-healify-dash --watch"
-```
-
-Background watchdogs, prewarmers, doctors, and repair hooks must not call `select-window` or `switch-client`. While a user is working in a window, focus should remain there unless the user explicitly presses a navigation key.
+Any tmux binding should open a client dashboard only through explicit user action. Background watchdogs, prewarmers, doctors, and repair hooks must not call `select-window` or `switch-client`. While a user is working in a window, focus should remain there unless the user explicitly presses a navigation key.
diff --git a/claude-ops/docs/ops/HOST-VS-PLUGIN-ROTATE-GAP.md b/claude-ops/docs/ops/HOST-VS-PLUGIN-ROTATE-GAP.md
index c2572d11..aae5e5da 100644
--- a/claude-ops/docs/ops/HOST-VS-PLUGIN-ROTATE-GAP.md
+++ b/claude-ops/docs/ops/HOST-VS-PLUGIN-ROTATE-GAP.md
@@ -11,12 +11,12 @@ Public-repo clean: no host emails, IPs, or personal account lists.
|--------|------------------------|------------------------|
| `rotate.mjs` | ~8981 lines | ~5275 lines (after this pass: soft captcha hooks) |
| Captcha helper stack | Present (full) | **Ported this pass** |
-| CRS reconcilers / priority | Present (ops + host forks) | Present (portable subset) |
+| CLIProxyAPI/legacy CRS reconcilers / priority | Present (ops + host forks) | Present (portable subset) |
| Magic-link autoloop + reauth env | Host thicker; plugin has portable `reauth-env.mjs` | Present (PR #723 era) |
| Production systemd/user units | Still point at **host** path | Templates only (`%h` / `$CLAUDE_PLUGIN_ROOT`) |
-**CRS is optional.** Standalone rotate-magic (keychain + `rotate.mjs` /
-`rotate-magic.mjs`) is enough for one or a few accounts. CRS is multi-account
+**CLIProxyAPI/legacy relay is optional.** Standalone rotate-magic (keychain + `rotate.mjs` /
+`rotate-magic.mjs`) is enough for one or a few accounts. CLIProxyAPI-compatible relay mode is multi-account
load balancing / rate-limit spreading for a relay pool.
## Line-count delta (key modules)
@@ -96,7 +96,7 @@ After this pass, cascade **modules** exist; full host `rotate.mjs` still has:
6. Residential Chrome / PAC / EFG proxy args for reauth browser
7. `secrets-bootstrap` before solver use
8. `virtual-display` ensure for headed seats
-9. CRS push helpers (`--sync-crs-all` style)
+9. Legacy CRS push helpers (`--sync-crs-all` compatibility style)
10. Stricter OAuth callback / credential race handling
## Minimal port set (standalone plugin rotate-magic)
@@ -115,7 +115,7 @@ After this pass, cascade **modules** exist; full host `rotate.mjs` still has:
- (keeps after-magic-link verify in `finishMagicLinkLogin`)
- `rotate-magic.mjs` runs ensure before spawning `rotate.mjs`
- Thin `rotate-magic.mjs` entry → `rotate.mjs --magic-link`
-- CRS optional UX in `/ops:rotate-setup` and `/ops:rotate` skills
+- CLIProxyAPI/legacy relay optional UX in `/ops:rotate-setup` and `/ops:rotate` skills
- Units: `__tests__/captcha-cascade.test.mjs`, `__tests__/ensure-rotate-captcha-hooks.test.mjs`
**Apply hooks on a checkout**
diff --git a/claude-ops/docs/ops/OPS-ACCOUNTS-GATEWAY.md b/claude-ops/docs/ops/OPS-ACCOUNTS-GATEWAY.md
index 3644a4dc..433260d4 100644
--- a/claude-ops/docs/ops/OPS-ACCOUNTS-GATEWAY.md
+++ b/claude-ops/docs/ops/OPS-ACCOUNTS-GATEWAY.md
@@ -2,9 +2,9 @@
**Status:** skeleton shipped (`scripts/account-rotation/ops-accounts-gateway.mjs`).
-**Goal:** Optional thin OpenAI-compat gateway so fleets that today set
-`base_url=http://127.0.0.1:3005` (CRS) can point at a plugin-owned process
-**without** installing weishaw/claude-relay-service.
+**Goal:** Optional thin OpenAI-compat CLIProxyAPI gateway so fleets that today set
+`base_url=http://127.0.0.1:3005` for cliproxy / CLIProxyAPI can point at a plugin-owned process
+**without** installing any deprecated relay stack.
## What it does (skeleton)
@@ -43,7 +43,7 @@ CRS_BASE_URL → OPS_ACCOUNTS_GATEWAY_URL
# harnesses keep OpenAI-compat client shape
```
-External CRS remains **advanced-only** for operators who want the full CRS admin UI.
+Deprecated relay stacks remain **advanced-only** for operators who want the old admin UI.
## Build order
@@ -55,5 +55,5 @@ External CRS remains **advanced-only** for operators who want the full CRS admin
## License
-If any line is copied from CRS (MIT), keep attribution. Prefer rewrite of the
-proxy surface over vendoring the monorepo.
+If any line is copied from a deprecated MIT relay, keep attribution. Prefer
+rewriting the proxy surface over vendoring the monorepo.
diff --git a/claude-ops/docs/ops/OPS-ACCOUNTS-VISION.md b/claude-ops/docs/ops/OPS-ACCOUNTS-VISION.md
index 64292cd7..54e3df3f 100644
--- a/claude-ops/docs/ops/OPS-ACCOUNTS-VISION.md
+++ b/claude-ops/docs/ops/OPS-ACCOUNTS-VISION.md
@@ -21,7 +21,7 @@ Ideal box: **public claude-ops plugin only** — no host-only `grok-rotate`, `co
## Anthropic reference stack (what “done” looks like)
-Claude already has (in plugin + optional CRS):
+Claude already has (in plugin + optional cliproxy / CLIProxyAPI relay):
| Layer | Role |
|-------|------|
@@ -31,7 +31,7 @@ Claude already has (in plugin + optional CRS):
| Reauth | magic-link-autoloop + captcha cascade (residential egress) |
| Util | 5h / 7d utilization queries |
| Switch | keychain swap / force-rotate |
-| Optional LB | CRS pool priority, 429 cooldown, token feed |
+| Optional LB | cliproxy / CLIProxyAPI pool priority, 429 cooldown, token feed |
**Every other provider gets the same layers**, with provider-native OAuth and util APIs.
@@ -39,21 +39,21 @@ Claude already has (in plugin + optional CRS):
| Provider | OAuth / capture | Reauth | Util | Switch / LB notes |
|----------|-----------------|--------|------|-------------------|
-| **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 |
+| **Claude (Anthropic)** | magic-link + captcha | magic-link-autoloop | 5h/7d | keychain daemon; cliproxy / CLIProxyAPI relay optional |
+| **Grok (xAI SuperGrok)** | device-code + Google (dcli) | residential cascade (EFG SOCKS → Bright Data residential → ISP → mobile) | weekly / 429 | `grok-cli-auth-proxy` RR; optional CLIProxyAPI-compatible hop 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_AUTH_DIR`, `CLIPROXYAPI_BASE_URL`. |
| **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` |
-### Grok + CRS (do not mis-sell)
+### Grok + CLIProxyAPI-compatible relay (do not mis-sell)
-Grok Build can use `CRS_GROK_BASE_URL` for its CRS-compatible endpoint. CRS **does not** own a SuperGrok account pool. It forwards to the configured **`grok-cli-auth-proxy`** (`GROK_PROXY_URL`), which holds OAuth seats and round-robins. ops-accounts status must show:
+Grok Build can use `CRS_GROK_BASE_URL` as a legacy env alias for its CLIProxyAPI-compatible endpoint. The optional relay hop **does not** own a SuperGrok account pool. It forwards to the configured **`grok-cli-auth-proxy`** (`GROK_PROXY_URL`), which holds OAuth seats and round-robins. ops-accounts status must show:
-1. CRS hop present/absent
-2. Proxy RR seat health + exhaust cooldowns
-3. Slot ↔ `auth.json` sync
+1. CLIProxyAPI-compatible hop present/absent
+2. Proxy RR seat health + exhaust cooldowns
+3. Slot ↔ `auth.json` sync
## Adapter contract (every provider)
@@ -75,7 +75,7 @@ No secrets in skill output. Provider-scoped vault service names. Env-templated p
|-------|------|----------------|
| **0** | Skill merge + contract — `/ops:accounts` owns verbs; rotate/setup are aliases; thin router over existing engines | One entrypoint; multi-provider status |
| **1** | Claude plugin parity (captcha cascade, standalone reauth) | Host not required for Claude magic-link |
-| **2** | Claude CRS optional | Detect; never required for single seat |
+| **2** | Claude CLIProxyAPI/legacy relay optional | Detect; never required for single seat |
| **3** | Grok adapter complete (plugin reauth + residential cascade + slot sync + proxy status) | Multi-seat healthy under weekly cap without host-only ops |
| **4** | OpenAI/Codex + Factory adapters | same verbs |
| **5** | Cursor adapter | same verbs |
@@ -85,51 +85,51 @@ No secrets in skill output. Provider-scoped vault service names. Env-templated p
-## CRS cherry-pick (so people do not need CRS)
+## cliproxy / CLIProxyAPI gateway path (legacy aliases retained)
-### Split CRS into three jobs
+### Split cliproxy-compatible behavior into three jobs
1. **API gateway** — OpenAI-compat `:3005`, `cr_` keys, harness routing
2. **Claude seat LB** — schedulable pool, 429/weekly park, token feed
-3. **Grok thin hop** — forward to host SuperGrok OAuth proxy (not a CRS pool)
+3. **Grok thin hop** — forward to host SuperGrok OAuth proxy (not a Claude relay pool)
ops-accounts absorbs (1)+(2) as optional **ops-accounts-gateway** + **policy daemons**,
and treats (3) as the **Grok provider backend** (port `grok-cli-auth-proxy` into
-the plugin). External CRS remains advanced-only.
+the plugin). External legacy relay stacks remain advanced-only compatibility paths.
-### Already portable in this repo (rename, do not re-clone CRS)
+### Already portable in this repo (legacy filenames retained for compatibility)
- `crs-priority-daemon.mjs` — pool priority / schedulable policy
- `crs-429-cooldown.mjs` — rate-limit cooldown
- `crs-401-refresher.mjs` — proactive refresh
- `crs-token-feed.mjs` — vault → pool
-- `crs-pool-config.mjs`, `crs-health-watch.mjs`, `crs-bedrock-guard.mjs` — optional
+- `crs-pool-config.mjs`, `crs-health-watch.mjs`, `crs-bedrock-guard.mjs` — optional
-These currently *call* CRS admin APIs. Dual-mode target:
+These legacy-named modules currently call cliproxy-compatible admin APIs. Dual-mode target:
-- `backend=crs` — talk to external CRS (compat)
-- `backend=local` — file/SQLite seat state, no Docker
+- `backend=crs` — legacy alias for the cliproxy-compatible admin API backend
+- `backend=local` — file/SQLite seat state, no Docker
### Build sequence
| Step | Deliverable |
|------|-------------|
-| A | Local seat-state backend for policy daemons (no CRS) |
+| A | Local seat-state backend for policy daemons (no relay required) |
| B | Plugin-owned Grok OAuth proxy (today’s `:31845` logic) |
| C | Optional OpenAI-compat gateway replacing `:3005` for most harnesses |
-| D | Docs: migrate `CRS_BASE_URL` → gateway; CRS optional advanced |
+| D | Docs: migrate legacy `CRS_BASE_URL` aliases → gateway; cliproxy optional advanced |
### License
-CRS lineage on this box is **MIT**. Cherry-pick with attribution; prefer
-reimplemented policy + small gateway over vendoring the full CRS monorepo
-(Redis/Grafana/admin SPA out of default install).
+Historical relay lineage on this box is **MIT**. Cherry-pick with attribution;
+prefer reimplemented policy + small gateway over vendoring deprecated relay
+monorepos (Redis/Grafana/admin SPA out of default install).
### Non-goals
-- Shipping Redis/Prometheus/Grafana as required deps
-- Multi-tenant CRS admin SPA
-- Claiming Grok seats live inside a Claude-style CRS account table
+- Shipping Redis/Prometheus/Grafana as required deps
+- Multi-tenant relay admin SPA
+- Claiming Grok seats live inside a Claude-style relay account table
## Risks
@@ -143,13 +143,13 @@ reimplemented policy + small gateway over vendoring the full CRS monorepo
## Non-goals (immediate)
-- Full CRS fork for every vendor
-- Deleting host trees before parity proof
-- Hard-requiring CRS
+- Full deprecated-relay fork for every vendor
+- Deleting host trees before parity proof
+- Hard-requiring a relay
## Related
-- `docs/ops/HOST-VS-PLUGIN-ROTATE-GAP.md`
-- `scripts/account-rotation/CAPTCHA-CASCADE.md`
-- Skills: `ops-accounts` (canonical), `ops-rotate` / `ops-rotate-setup` (aliases)
-- Local plan: `Projects/memory/plans/2026-07-30T1557Z-public-ops-plugin-only.md`
+- `docs/ops/HOST-VS-PLUGIN-ROTATE-GAP.md`
+- `scripts/account-rotation/CAPTCHA-CASCADE.md`
+- Skills: `ops-accounts` (canonical), `ops-rotate` / `ops-rotate-setup` (aliases)
+- Local plan: `Projects/memory/plans/2026-07-30T1557Z-public-ops-plugin-only.md`
diff --git a/claude-ops/docs/pocket-ec2-deployment.md b/claude-ops/docs/pocket-ec2-deployment.md
index 6bf131e9..47bee277 100644
--- a/claude-ops/docs/pocket-ec2-deployment.md
+++ b/claude-ops/docs/pocket-ec2-deployment.md
@@ -1,18 +1,16 @@
-# Pocket pipeline — EC2 deployment on dev-sandbox
+# Pocket pipeline — EC2 deployment
-Pocket runs entirely on the dev-sandbox EC2 instance (i-0b207951a7dff925d,
-m8g.2xlarge). This is an approved exception to the no-EC2 rule; pocket
-workloads are too persistent for a laptop.
+Pocket can run on a dedicated EC2 instance. This is an approved exception to
+the no-EC2 rule; pocket workloads are too persistent for a laptop.
## Access
-Web UI: `https://dev-sandbox.tail6aeed8.ts.net` (Tailscale only — never
-exposed via public DNS or Cloudflare). Auth is enforced by the
+Web UI: expose the local service over a private Tailscale HTTPS hostname only —
+never via public DNS or Cloudflare. Auth is enforced by the
`Tailscale-User-Login` header injected by `tailscale serve`; only
the configured owner identity is admitted (set via `TAILSCALE_USER` env in the systemd unit).
-SSH: `ssh dev-ts` (ec2-user, pem at `~/.ssh/dev-sandbox-2026-05-17.pem`,
-Tailscale IP 100.109.217.31).
+SSH: use the operator's private host alias and key outside this public repo.
## Systemd units
@@ -34,9 +32,9 @@ plugin upgrade: `bash claude-ops/scripts/systemd/install-systemd-units.sh`.
## Tailscale serve
`tailscale serve --https=443 http://127.0.0.1:7777` is configured on
-dev-sandbox (runs as root via `sudo tailscale serve`). It terminates TLS,
-injects the identity header, and proxies to gunicorn. Config persists across
-reboots. Verify with `sudo tailscale serve status`.
+the private EC2 host (runs as root via `sudo tailscale serve`). It terminates
+TLS, injects the identity header, and proxies to gunicorn. Config persists
+across reboots. Verify with `sudo tailscale serve status`.
## State directory
diff --git a/claude-ops/docs/safety-hooks.md b/claude-ops/docs/safety-hooks.md
index a9840418..012e4b76 100644
--- a/claude-ops/docs/safety-hooks.md
+++ b/claude-ops/docs/safety-hooks.md
@@ -119,7 +119,7 @@ bash claude-ops/tests/test-safety-hooks.sh
## bedrock-billing-guard (PreToolUse) — metered-spend protection
`hooks/bedrock-billing-guard.mjs` hard-stops any Claude session that is **measured
-to be billing AWS Bedrock** (metered per-token spend, not the Max/CRS account
+to be billing AWS Bedrock** (metered per-token spend, not the Max/CLIProxyAPI account
pool). It is the agent-facing complement to the rotation daemon's
`scripts/account-rotation/bedrock-watchdog.mjs`, which detects + force-swaps such
sessions off Bedrock within ~45s.
@@ -139,8 +139,8 @@ network/env measurement.
| `warn` | Never block — inject a one-line non-blocking warning into the agent's context on each tool call. |
| `off` | No-op. For users who intentionally run **Bedrock unrestricted**. |
-When OAuth headroom exists, the watchdog respawns the session onto CRS/OAuth and
-clears the flag, so the block lifts on its own. The guard is **fail-open**: any
+When OAuth headroom exists, the watchdog respawns the session onto CLIProxyAPI/OAuth
+(or a legacy CRS-compatible relay) and clears the flag, so the block lifts on its own. The guard is **fail-open**: any
error, missing input, or unexpected state allows the tool (a money guard must
never wedge an innocent session).
diff --git a/claude-ops/hooks/bedrock-fallback-guard.mjs b/claude-ops/hooks/bedrock-fallback-guard.mjs
index 5daabbf1..3c607307 100644
--- a/claude-ops/hooks/bedrock-fallback-guard.mjs
+++ b/claude-ops/hooks/bedrock-fallback-guard.mjs
@@ -18,19 +18,19 @@ try {
if (settings.mixedProvider) {
block(
- 'Claude routing is unsafe: settings.json has both Bedrock and CRS/OAuth enabled. Run `claude-stack route --mode crs-oauth` or explicitly confirm Bedrock with `claude-stack route --mode bedrock-confirmed --confirm-metered-bedrock --reason "<reason>"`.',
+ 'Claude routing is unsafe: settings.json has both Bedrock and CLIProxyAPI/legacy relay OAuth enabled. Run `claude-stack route --mode crs-oauth` (legacy mode name) or explicitly confirm Bedrock with `claude-stack route --mode bedrock-confirmed --confirm-metered-bedrock --reason "<reason>"`.',
);
}
if (settings.bedrock && (route.mode !== 'bedrock-confirmed' || !status.bedrockConfirmationActive)) {
block(
- 'Bedrock fallback blocked. Bedrock is metered AWS usage, and OAuth/CRS is unavailable or not selected. Confirm only for this session with `claude-stack route --mode bedrock-confirmed --reason "<why OAuth is unavailable>" --ttl-minutes 60 --confirm-metered-bedrock`, or restore OAuth with `claude-stack route --mode crs-oauth`.',
+ 'Bedrock fallback blocked. Bedrock is metered AWS usage, and CLIProxyAPI/legacy relay OAuth is unavailable or not selected. Confirm only for this session with `claude-stack route --mode bedrock-confirmed --reason "<why OAuth is unavailable>" --ttl-minutes 60 --confirm-metered-bedrock`, or restore OAuth with `claude-stack route --mode crs-oauth` (legacy mode name).',
);
}
if (route.mode === 'fail-closed') {
block(
- `Claude routing is fail-closed: ${route.reason || 'CRS OAuth is unavailable and Bedrock has not been explicitly confirmed'}. Run \`claude-stack doctor --json\` for current CRS/account status.`,
+ `Claude routing is fail-closed: ${route.reason || 'CLIProxyAPI/legacy relay OAuth is unavailable and Bedrock has not been explicitly confirmed'}. Run \`claude-stack doctor --json\` for current relay/account status.`,
);
}
diff --git a/claude-ops/scripts/account-rotation/CAPTCHA-CASCADE.md b/claude-ops/scripts/account-rotation/CAPTCHA-CASCADE.md
index f8d2a025..be1a3846 100644
--- a/claude-ops/scripts/account-rotation/CAPTCHA-CASCADE.md
+++ b/claude-ops/scripts/account-rotation/CAPTCHA-CASCADE.md
@@ -5,13 +5,13 @@ Contract for **unattended** re-auth owned by `magic-link-autoloop` →
Agents must not spawn parallel `rotate.mjs` drivers against the same fleet
(they thrash the global `.rotating` lock and the reauth browser profile).
-**CRS is not required.** Captcha cascade runs in standalone rotate-magic.
+**cliproxy / CLIProxyAPI relay is not required.** Captcha cascade runs in standalone rotate-magic.
## Ownership
| Component | Role |
|-----------|------|
-| `magic-link-autoloop` | Serial, one account per tick; opt-in (often CRS-flagged, but not required) |
+| `magic-link-autoloop` | Serial, one account per tick; opt-in (often relay-flagged via legacy CRS config, but not required) |
| `rotate.mjs` / `rotate-magic.mjs` | Browser OAuth / magic-link / setup |
| `captcha-helper.mjs` | Token solvers + residential wait (`residualAfterWait`) |
| `visual-captcha-solver.mjs` | Vision tiles + desktop-act + VNC layers |
diff --git a/claude-ops/scripts/account-rotation/README.md b/claude-ops/scripts/account-rotation/README.md
index 6913f759..225cee5b 100644
--- a/claude-ops/scripts/account-rotation/README.md
+++ b/claude-ops/scripts/account-rotation/README.md
@@ -54,7 +54,7 @@ Each account entry:
| `dashlaneTokenPath` | no | If you store the token in Dashlane: `dl://<vault-name>/password`. |
| `extraUsageEnabled` | no | Set to `true` ONLY if the account has paid overage on. Triggers safety margin. |
| `capacityMultiplier` | no | Override per-account threshold (default 1.0 = standard Max 20x quota). |
-| `crsAccountName` | no | CRS admin account name this vault entry maps to (for crs-token-feed / crs-priority). |
+| `crsAccountName` | no | Legacy compatibility field for the cliproxy/CLIProxyAPI account name this vault entry maps to (for `crs-token-feed` / `crs-priority` compatibility). |
## Signed staged Claude enrollment
@@ -200,18 +200,18 @@ the coordination key. Trust files must remain outside all mutable auth roots.
autoloop no longer dispatch authentication. They return a staged-enrollment
handoff instead; no environment flag restores the old write path.
-## CRS pool (optional)
+## cliproxy / CLIProxyAPI pool (optional)
-CRS = multi-account **load balancing / rate-limit spreading** via a relay pool.
+cliproxy / CLIProxyAPI relay mode provides multi-account **load balancing / rate-limit spreading** via a relay pool.
Useful mainly when many accounts share one API endpoint and you hit 429s.
-Skip CRS for single/few-account keychain rotation.
+Skip the relay for single/few-account keychain rotation.
-If you run [claude-relay-service](https://github.com/anthropics/claude-relay-service) (CRS) alongside the rotator:
+If you run a cliproxy relay alongside the rotator:
-1. Add `crsAccountName` on each account (must match the account `name` in the CRS admin UI), or supply `crs.nameByVaultKey` in `config.json`.
-2. Set `crs.enabled`, `crs.baseUrl`, and install the priority daemon: `scripts/install-crs-priority-agent.sh`.
-3. On Linux/EC2, `crs-token-feed.mjs` propagates vault tokens into CRS (systemd timer when installed).
-4. On macOS clients that reach a **remote** CRS via SSH, install the tunnel (requires `CRS_TUNNEL_SSH_HOST`):
+1. Add `crsAccountName` on each account (legacy field name; must match the cliproxy account `name`), or supply `crs.nameByVaultKey` in `config.json`.
+2. Set `crs.enabled`, `crs.baseUrl`, and install the priority daemon: `scripts/install-crs-priority-agent.sh` (legacy filename retained).
+3. On Linux/EC2, `crs-token-feed.mjs` propagates vault tokens into the cliproxy pool (systemd timer when installed).
+4. On macOS clients that reach a **remote** relay via SSH, install the tunnel (legacy env `CRS_TUNNEL_SSH_HOST` is still accepted):
```bash
CRS_TUNNEL_SSH_HOST=your-remote-host bash scripts/install-crs-fra-tunnel.sh
@@ -219,8 +219,8 @@ If you run [claude-relay-service](https://github.com/anthropics/claude-relay-ser
Point Claude Code at `http://127.0.0.1:3005/api` (or your `CRS_TUNNEL_LOCAL_PORT`).
-See `config.example.json` → `crs` block for all tunables (`policy`, `fileVaultPath`, `containerName`, thresholds).
-Configure via `/ops:rotate-setup` (detects CRS; never required).
+See `config.example.json` → `crs` block for all tunables (`policy`, `fileVaultPath`, `containerName`, thresholds; legacy key names retained for compatibility).
+Configure via `/ops:rotate-setup` (detects cliproxy / CLIProxyAPI; never required).
## Keychain layout
@@ -236,7 +236,7 @@ Override the keychain account name via `CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT` if you
| File | Purpose |
| --------------------------- | ------------------------------------------------------------------------- |
| `rotate.mjs` | Main rotation logic. CLI: `--status`, `--utilization`, `--to`, `--setup`. |
-| `rotate-magic.mjs` | Thin entry → `rotate.mjs --magic-link` (standalone reauth, no CRS). |
+| `rotate-magic.mjs` | Thin entry → `rotate.mjs --magic-link` (standalone reauth, no cliproxy required). |
| `captcha-cascade.mjs` | Post-verify captcha orchestration (token + visual + desktop-act + VNC). |
| `captcha-helper.mjs` | Pluggable token captcha solvers + residential wait. |
| `visual-captcha-solver.mjs` | Vision tile clicks, desktop-act, VNC layers. |
diff --git a/claude-ops/scripts/account-rotation/claude-settings-mode.mjs b/claude-ops/scripts/account-rotation/claude-settings-mode.mjs
index 75e08691..4b520ad7 100644
--- a/claude-ops/scripts/account-rotation/claude-settings-mode.mjs
+++ b/claude-ops/scripts/account-rotation/claude-settings-mode.mjs
@@ -15,14 +15,14 @@ function claudeSettingsPath() {
return join(process.env.HOME || '', '.claude', 'settings.json');
}
-// ── CRS (Claude Relay Service) routing awareness ───────────────────────────────
-// When a box routes through CRS, ANTHROPIC_BASE_URL points at the local relay
+// ── CLIProxyAPI/legacy CRS-compatible relay routing awareness ──────────────────
+// When a box routes through the relay, ANTHROPIC_BASE_URL points at the local relay
// (e.g. http://127.0.0.1:3005/api) and CLAUDE_CODE_OAUTH_TOKEN holds a static
// `cr_…` relay token. Both must travel together — a `cr_` token with no base URL
// 401s. The Bedrock/OAuth settings mutators below were written for the raw-OAuth /
-// Bedrock world and would silently strip ANTHROPIC_BASE_URL, stranding a CRS box.
+// Bedrock world and would silently strip ANTHROPIC_BASE_URL, stranding a relay-routed box.
// These helpers detect that routing and snapshot/restore the pair so a mode flip
-// never breaks (or money-leaks past) a CRS-routed fleet.
+// never breaks (or money-leaks past) a relay-routed fleet.
function isCrsToken(t) {
return typeof t === 'string' && t.startsWith('cr_');
}
diff --git a/claude-ops/scripts/account-rotation/config.example.json b/claude-ops/scripts/account-rotation/config.example.json
index 8c4ce6d7..21d27068 100644
--- a/claude-ops/scripts/account-rotation/config.example.json
+++ b/claude-ops/scripts/account-rotation/config.example.json
@@ -30,7 +30,7 @@
"refreshSession": false,
"notifyOnRotation": true,
"crs": {
- "_comment": "Optional: claude-relay-service (CRS) pool integration. Off by default — set enabled=true and install via scripts/install-crs-priority-agent.sh. Map each rotator account to its CRS row with crsAccountName on the account entry (or crs.nameByVaultKey). Admin password is NOT stored here: set $CRS_ADMIN_PASSWORD or credential-store CRS-Admin-<adminUser>.",
+ "_comment": "Optional: cliproxy / CLIProxyAPI pool integration. Off by default — set enabled=true and install via scripts/install-crs-priority-agent.sh (legacy filename). The crs* field names are retained as compatibility aliases. Map each rotator account to its relay row with crsAccountName on the account entry (or crs.nameByVaultKey). Admin password is NOT stored here: set $CRS_ADMIN_PASSWORD or credential-store CRS-Admin-<adminUser>.",
"enabled": false,
"policy": "conservative",
"_policy_note": "conservative (default) deprioritizes on utilization/session warnings; max-out keeps accounts schedulable until genuine rate-limit or overload (util % is telemetry only). Override with $CRS_POLICY.",
@@ -52,7 +52,7 @@
"_thresholds_note": "Legacy conservative thresholds (off/on/floor) apply only when policy=conservative. Default max-out policy keeps accounts schedulable until genuine rate-limit or overload; utilization % is telemetry only. freshMinutes = max age of claudeUsage trusted for secondary signals.",
"logDir": null,
"logTzOffset": "+00:00",
- "_logDir_note": "Optional: crs-429-cooldown.mjs reads claude-relay-error-<date>.log from here (absolute path, no ~ expansion) for its optional lead signal. Defaults to <plugin-data-dir>/account-rotation/crs-logs if unset — point it at your CRS deployment's actual log directory. logTzOffset must match the timezone your CRS instance timestamps logs in.",
+ "_logDir_note": "Optional: crs-429-cooldown.mjs reads claude-relay-error-<date>.log from here (absolute path, no ~ expansion) for its optional lead signal. Defaults to <plugin-data-dir>/account-rotation/crs-logs if unset — point it at your CLIProxyAPI/legacy relay deployment's actual log directory. logTzOffset must match the timezone your relay instance timestamps logs in.",
"errorLogWindowMs": 300000,
"errorLogCooldownMs": 300000,
"_errorLog_note": "errorLogWindowMs: how far back crs-429-cooldown.mjs scans the log for a 429 hit. errorLogCooldownMs: how long a log-only hit holds an account before rateLimitStatus itself would (default 5m each).",
@@ -62,9 +62,9 @@
"_cooldownStatePath_note": "Optional: path to a separate 429/rate-limit reconciler's state file, read-only, so crs-401-refresher.mjs's re-enable sweep doesn't fight a genuine rate-limit window. Leave null if you don't run one — treated as 'no known windows', never an error. NEVER point this at the same file crs-401-refresher.mjs writes (crs-401-state.json) — each reconciler must own its own state file.",
"manualDisableEnabled": true,
"cooldownEnabled": false,
- "_cooldownEnabled_note": "Off by default (or $CRS_COOLDOWN_ENABLED=1). Turns on crs-429-cooldown.mjs, a fast (1min-cadence) reconciler that holds an account out of rotation only on a real rateLimitStatus.isRateLimited=true from CRS (plus the optional error-log lead signal under logDir/logTzOffset above) — never on utilization. Own state file at <stateDir>/crs-429-state.json.",
+ "_cooldownEnabled_note": "Off by default (or $CRS_COOLDOWN_ENABLED=1). Turns on crs-429-cooldown.mjs, a fast (1min-cadence) reconciler that holds an account out of rotation only on a real rateLimitStatus.isRateLimited=true from the CLIProxyAPI/legacy relay (plus the optional error-log lead signal under logDir/logTzOffset above) — never on utilization. Own state file at <stateDir>/crs-429-state.json.",
"tokenRefreshEnabled": false,
- "_tokenRefreshEnabled_note": "Off by default (or $CRS_TOKEN_REFRESH_ENABLED=1). Turns on crs-401-refresher.mjs, which proactively refreshes each CRS account's OAuth access token via POST /admin/claude-accounts/:id/refresh before it expires, reviving sidelined accounts on success and flagging a dead refresh_token as needs-reauth on failure. Own state file at <stateDir>/crs-401-state.json. Before reviving an account it checks cooldownStatePath (read-only) so it never re-enables one crs-429-cooldown.mjs is genuinely holding for a live rate limit.",
+ "_tokenRefreshEnabled_note": "Off by default (or $CRS_TOKEN_REFRESH_ENABLED=1). Turns on crs-401-refresher.mjs, which proactively refreshes each CLIProxyAPI/legacy relay account's OAuth access token via POST /admin/claude-accounts/:id/refresh before it expires, reviving sidelined accounts on success and flagging a dead refresh_token as needs-reauth on failure. Own state file at <stateDir>/crs-401-state.json. Before reviving an account it checks cooldownStatePath (read-only) so it never re-enables one crs-429-cooldown.mjs is genuinely holding for a live rate limit.",
"tokenRefreshWindowMs": 1800000,
"_tokenRefreshWindowMs_note": "Refresh an account's token once it's within this many ms of expiry (default 30m).",
"enableMagicLinkRecovery": false,
diff --git a/claude-ops/scripts/account-rotation/crs-429-cooldown.mjs b/claude-ops/scripts/account-rotation/crs-429-cooldown.mjs
index b36f3127..33664ee0 100644
--- a/claude-ops/scripts/account-rotation/crs-429-cooldown.mjs
+++ b/claude-ops/scripts/account-rotation/crs-429-cooldown.mjs
@@ -4,18 +4,18 @@
// OPT-IN. Does nothing (exits 0) unless crs.cooldownEnabled is true (or
// $CRS_COOLDOWN_ENABLED=1) — installing this plugin never silently starts a new
// daemon. Enable it alongside crs-priority-daemon.mjs when you run a self-hosted
-// claude-relay-service (CRS) pool and want a fast, real-signal-only cooldown watcher
+// CLIProxyAPI/legacy CRS-compatible relay pool and want a fast, real-signal-only cooldown watcher
// that runs on a tighter cadence than the priority daemon.
//
-// Two signals, in priority order — both are things Anthropic (or CRS observing
+// Two signals, in priority order — both are things Anthropic (or the relay observing
// Anthropic) actually told us, never a speculative/utilization-based guess:
-// 1. rateLimitStatus.isRateLimited = true on the account record (CRS derived
-// this from a real upstream response on an actual inference call).
-// 2. (optional) tail of today's CRS relay error log for 429 lines mentioning the
-// account name — a faster lead signal than #1 while CRS's own record catches
-// up. Reads from crs.logDir (or $CRS_LOG_DIR); a no-op on a fresh install
+// 1. rateLimitStatus.isRateLimited = true on the account record (relay-derived
+// from a real upstream response on an actual inference call).
+// 2. (optional) tail of today's relay error log for 429 lines mentioning the
+// account name — a faster lead signal than #1 while the relay's own record catches
+// up. Reads from crs.logDir (or $CRS_LOG_DIR; legacy names); a no-op on a fresh install
// since that directory won't exist yet (this reconciler never assumes a
-// real CRS deployment's log layout).
+// real relay deployment's log layout).
//
// State is owned exclusively by THIS reconciler (own file, atomic write, single-
// flight lock via crs-reconciler-state.mjs) so that:
diff --git a/claude-ops/scripts/account-rotation/crs-pool-config.mjs b/claude-ops/scripts/account-rotation/crs-pool-config.mjs
index e869fcce..52445194 100644
--- a/claude-ops/scripts/account-rotation/crs-pool-config.mjs
+++ b/claude-ops/scripts/account-rotation/crs-pool-config.mjs
@@ -1,9 +1,9 @@
#!/usr/bin/env node
/**
- * crs-pool-config.mjs — shared CRS + rotation config resolution for public installs.
+ * crs-pool-config.mjs — shared CLIProxyAPI/legacy CRS-compatible relay + rotation config resolution for public installs.
*
- * Vault key ↔ CRS account name mapping is NEVER hardcoded in repo scripts.
- * Configure per account via `crsAccountName` and/or optional `crs.nameByVaultKey`.
+ * Vault key ↔ legacy relay account name mapping is NEVER hardcoded in repo scripts.
+ * Configure per account via legacy fields `crsAccountName` and/or optional `crs.nameByVaultKey`.
*/
import { readFileSync, existsSync } from 'fs';
@@ -134,8 +134,8 @@ export function resolveCredentialStorePath() {
}
/**
- * Resolve the CRS admin password for HTTP basic auth against a self-hosted
- * claude-relay-service pool. Resolution order (first hit wins), none of it
+ * Resolve the relay admin password for HTTP basic auth against a self-hosted
+ * CLIProxyAPI/legacy CRS-compatible pool. Resolution order (first hit wins), none of it
* ever hardcoded to one deployment:
* 1. $CRS_ADMIN_PASSWORD
* 2. the env var named by config.crs.adminPasswordEnv (or $CRS_ADMIN_PASSWORD_ENV)
diff --git a/claude-ops/scripts/account-rotation/crs-priority-daemon.mjs b/claude-ops/scripts/account-rotation/crs-priority-daemon.mjs
index 815bd222..aa9f6b25 100755
--- a/claude-ops/scripts/account-rotation/crs-priority-daemon.mjs
+++ b/claude-ops/scripts/account-rotation/crs-priority-daemon.mjs
@@ -1,9 +1,9 @@
#!/usr/bin/env node
// crs-priority-daemon.mjs — utilization-driven account prioritization for a
-// claude-relay-service (CRS) pool.
+// CLIProxyAPI/legacy CRS-compatible relay pool.
//
-// CRS load-balances Claude requests across many claude.ai accounts at once. Each
-// account carries a `schedulable` flag; CRS only routes to schedulable accounts.
+// The relay load-balances Claude requests across many claude.ai accounts at once. Each
+// account carries a `schedulable` flag; the relay only routes to schedulable accounts.
// This daemon flips that flag from LIVE signals so the pool AVOIDS near-maxed
// accounts (cutting 429/529s) and RE-ENABLES them once their windows recover —
// the relay-pool analogue of the keychain rotator's "rotate to the coolest
diff --git a/claude-ops/scripts/account-rotation/crs-reconciler-state.mjs b/claude-ops/scripts/account-rotation/crs-reconciler-state.mjs
index 1ed92480..7128e7ea 100644
--- a/claude-ops/scripts/account-rotation/crs-reconciler-state.mjs
+++ b/claude-ops/scripts/account-rotation/crs-reconciler-state.mjs
@@ -1,8 +1,8 @@
#!/usr/bin/env node
/**
- * crs-reconciler-state.mjs — shared own-state-file helper for CRS pool reconcilers.
+ * crs-reconciler-state.mjs — shared own-state-file helper for CLIProxyAPI/legacy CRS-compatible pool reconcilers.
*
- * Each reconciler that watches a claude-relay-service (CRS) account pool (cooldown
+ * Each reconciler that watches a relay account pool (cooldown
* tracking, token-refresh tracking, priority scoring, ...) MUST persist to its OWN
* state file — never a file shared with another reconciler. Sharing one file was the
* root cause of a documented production incident: reconciler A's non-atomic write
diff --git a/claude-ops/scripts/account-rotation/ops-accounts-backend.mjs b/claude-ops/scripts/account-rotation/ops-accounts-backend.mjs
index 04226585..1fc5a234 100644
--- a/claude-ops/scripts/account-rotation/ops-accounts-backend.mjs
+++ b/claude-ops/scripts/account-rotation/ops-accounts-backend.mjs
@@ -1,13 +1,13 @@
/**
- * ops-accounts-backend.mjs — resolve CRS vs local seat-state backend.
+ * ops-accounts-backend.mjs — resolve legacy CRS-compatible relay vs local seat-state backend.
*
* Env / config:
- * OPS_ACCOUNTS_BACKEND | crs.backend
- * local | seat-state | file → local seat-state (no CRS)
- * crs → CRS admin API only
- * auto (default) → try CRS, fall back to local
+ * OPS_ACCOUNTS_BACKEND | crs.backend (legacy config key)
+ * local | seat-state | file → local seat-state (no relay)
+ * crs → legacy CRS-compatible admin API only
+ * auto (default) → try relay, fall back to local
*
- * Dual-write (CRS path → seat-state.json) is on by default unless
+ * Dual-write (relay path → seat-state.json) is on by default unless
* OPS_ACCOUNTS_DUAL_WRITE=0.
*/
export function resolveAccountsBackend({ env = process.env, cfgBackend } = {}) {
diff --git a/claude-ops/scripts/account-rotation/refresh-tokens.mjs b/claude-ops/scripts/account-rotation/refresh-tokens.mjs
index acde1fec..32c8d4a7 100644
--- a/claude-ops/scripts/account-rotation/refresh-tokens.mjs
+++ b/claude-ops/scripts/account-rotation/refresh-tokens.mjs
@@ -40,7 +40,7 @@ const LOG_PATH = join(__dirname, 'rotation.log');
const NEEDS_REAUTH_PATH = join(__dirname, '.crs-token-refresher-state.json');
const AUTOLOOP_STATE_PATH = join(__dirname, '.crs-magic-autoloop-state.json');
const KEYCHAIN_SERVICE = 'Claude Code-credentials';
-const KEYCHAIN_ACCOUNT = process.env.USER || '<USER>';
+const KEYCHAIN_ACCOUNT = process.env.USER || 'claude-ops';
const CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e';
const TOKEN_ENDPOINT = 'https://platform.claude.com/v1/oauth/token';
diff --git a/claude-ops/scripts/account-rotation/use-bedrock.sh b/claude-ops/scripts/account-rotation/use-bedrock.sh
index b86975e0..7a7f697e 100755
--- a/claude-ops/scripts/account-rotation/use-bedrock.sh
+++ b/claude-ops/scripts/account-rotation/use-bedrock.sh
@@ -18,7 +18,7 @@ _ROT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
if [[ "${CLAUDE_CONFIRM_METERED_BEDROCK:-}" != "1" ]]; then
echo "⛔ Bedrock fallback blocked."
- echo " Bedrock is metered AWS usage. OAuth/CRS is the preferred route."
+ echo " Bedrock is metered AWS usage. OAuth via CLIProxyAPI/legacy relay is the preferred route."
echo " Reason OAuth is unavailable: ${CLAUDE_BEDROCK_REASON:-not supplied}"
echo " To confirm for this short session: CLAUDE_CONFIRM_METERED_BEDROCK=1 source ~/.claude/scripts/account-rotation/use-bedrock.sh"
return 2 2>/dev/null || exit 2
diff --git a/claude-ops/scripts/account-rotation/use-oauth.sh b/claude-ops/scripts/account-rotation/use-oauth.sh
index d036a943..13726c12 100755
--- a/claude-ops/scripts/account-rotation/use-oauth.sh
+++ b/claude-ops/scripts/account-rotation/use-oauth.sh
@@ -1,9 +1,9 @@
#!/bin/bash
-# use-oauth.sh — exit Bedrock mode in this shell, restore CRS-backed OAuth defaults.
+# use-oauth.sh — exit Bedrock mode in this shell, restore CLIProxyAPI/legacy CRS-backed OAuth defaults.
# Source me: `source ~/.claude/scripts/account-rotation/use-oauth.sh`
#
# Persists to ~/.claude/settings.json via claude-routing-state:
-# ANTHROPIC_BASE_URL points at CRS and CLAUDE_CODE_OAUTH_TOKEN is the CRS relay token.
+# ANTHROPIC_BASE_URL points at the relay and CLAUDE_CODE_OAUTH_TOKEN is the CLIProxyAPI-compatible relay token.
unset CLAUDE_CODE_USE_BEDROCK
unset AWS_BEDROCK_REGION
@@ -23,7 +23,7 @@ _ROT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
ACTIVE=$(python3 -c "import json; print(json.load(open('$HOME/.claude/scripts/account-rotation/state.json')).get('activeAccount',''))" 2>/dev/null)
echo "✅ OAuth mode restored for this shell + persisted to settings.json"
echo " models : (subscription catalog — no hardcoded IDs)"
-echo " route : CRS OAuth"
+echo " route : CLIProxyAPI/legacy relay OAuth"
echo " active account: ${ACTIVE:-(unknown)}"
if [[ -f ~/.claude/.bedrock-fallback.json ]]; then
echo " ⚠ Bedrock sentinel still present — clearing"
diff --git a/claude-ops/scripts/crsproxy-reauth/account_policy.example.yaml b/claude-ops/scripts/crsproxy-reauth/account_policy.example.yaml
index 5ea82859..324ac057 100644
--- a/claude-ops/scripts/crsproxy-reauth/account_policy.example.yaml
+++ b/claude-ops/scripts/crsproxy-reauth/account_policy.example.yaml
@@ -1,9 +1,8 @@
-# CRSProxy Account Policy — Example Template (NO PII)
+# cliproxy Account Policy — Example Template (NO PII)
#
# This is a PII-free example of the declarative account policy file.
-# The real file is deployed to /opt/crsproxy/account_policy.yaml on the hub
-# only — it contains real account emails and must NEVER be committed to the
-# public repo.
+# The real file is deployed to the cliproxy hub only — it contains real account
+# emails and must NEVER be committed to the public repo.
#
# The auto_reauth.py monitor reads this file to reconcile actual auth files
# against the declared target state:
@@ -18,9 +17,16 @@
# priority: lower = higher priority for routing (1=highest)
# profile_id: Browser Use Cloud profile UUID (optional, for profile-based reauth)
# reauth_method: profile | email | x_oauth | none
-# requires_2fa: true if the account needs 2FA (human checkpoint required)
+# two_factor: optional 2FA integration/checkpoint config
# x_username: X/Twitter username (optional, for x_oauth method only)
# max_consecutive_failures: auto-disable after this many consecutive failures
+#
+# 2FA methods:
+# none no 2FA expected
+# onepassword_totp fetch TOTP seed/URI from local 1Password Connect, send only the short-lived code to Browser Use
+# passkey_checkpoint keep Browser Use session alive for human passkey/WebAuthn approval
+# sms_checkpoint ask the operator for an SMS code and have Browser Use enter it
+# push_checkpoint ask the operator to approve a push prompt, then resume
accounts:
# --- Claude OAuth accounts ---
@@ -29,7 +35,8 @@ accounts:
enabled: true
priority: 5
reauth_method: email
- requires_2fa: false
+ two_factor:
+ method: none
max_consecutive_failures: 3
- provider: claude
@@ -38,7 +45,11 @@ accounts:
priority: 3
profile_id: "<BU_PROFILE_UUID>"
reauth_method: profile
- requires_2fa: false
+ two_factor:
+ method: onepassword_totp
+ op_vault_id: "<OP_VAULT_UUID>"
+ op_item_id: "<OP_ITEM_UUID>"
+ op_field: "one-time password"
max_consecutive_failures: 3
- provider: claude
@@ -46,7 +57,8 @@ accounts:
enabled: true
priority: 5
reauth_method: email
- requires_2fa: false
+ two_factor:
+ method: sms_checkpoint
max_consecutive_failures: 3
# --- Codex (OpenAI) OAuth accounts ---
@@ -55,7 +67,8 @@ accounts:
enabled: true
priority: 7
reauth_method: email
- requires_2fa: false
+ two_factor:
+ method: none
max_consecutive_failures: 3
- provider: codex
@@ -63,7 +76,8 @@ accounts:
enabled: true
priority: 7
reauth_method: email
- requires_2fa: false
+ two_factor:
+ method: passkey_checkpoint
max_consecutive_failures: 3
# --- xAI/Grok OAuth accounts ---
@@ -72,7 +86,8 @@ accounts:
enabled: true
priority: 8
reauth_method: email
- requires_2fa: false
+ two_factor:
+ method: none
max_consecutive_failures: 3
- provider: xai
@@ -81,7 +96,8 @@ accounts:
reason: "different tier, no SuperGrok"
priority: 8
reauth_method: email
- requires_2fa: false
+ two_factor:
+ method: none
max_consecutive_failures: 3
- provider: xai
@@ -89,7 +105,8 @@ accounts:
enabled: true
priority: 8
reauth_method: x_oauth
- requires_2fa: true
+ two_factor:
+ method: push_checkpoint
x_username: "example_user"
max_consecutive_failures: 3
@@ -100,5 +117,6 @@ accounts:
reason: "Anthropic models should route via Claude OAuth, not Google Vertex AI"
priority: 9
reauth_method: none
- requires_2fa: false
+ two_factor:
+ method: none
max_consecutive_failures: 3
diff --git a/claude-ops/scripts/crsproxy-reauth/auto_reauth.py b/claude-ops/scripts/crsproxy-reauth/auto_reauth.py
index 0297f31f..90e530f9 100644
--- a/claude-ops/scripts/crsproxy-reauth/auto_reauth.py
+++ b/claude-ops/scripts/crsproxy-reauth/auto_reauth.py
@@ -1,23 +1,23 @@
#!/usr/bin/env python3
-"""CRSProxy autonomous reauth monitor.
+"""cliproxy autonomous reauth monitor.
-Runs periodically via the systemd timer ``crsproxy-reauth.timer``.
+Runs periodically via the cliproxy reauth systemd timer.
Responsibilities:
1. Run ``cliproxy-pool-health`` and log the result.
2. Reconcile actual auth files against the declarative account policy
- (``/opt/crsproxy/account_policy.yaml``):
+ on the cliproxy hub:
- If policy says enabled but auth file is disabled -> trigger reauth.
- If policy says disabled but auth file is enabled -> disable it.
3. Scan auth files for expired or disabled accounts.
4. Trigger reauth for any expired account using **profile-first** logic:
- If ``reauth_seats.json`` maps a Browser Use Cloud profile ID to the
account -> invoke ``bu_profile_reauth.py`` with ``-profile-id``.
- - Otherwise -> fall back to ``bu_reauth_lib.py`` (email-based).
+ - Otherwise -> fall back to ``bu_reauth.py`` (email-based).
A per-account cooldown prevents hammering a persistently-blocked account.
5. Log all results WITHOUT exposing secrets (emails are masked, tokens /
codes / cookies / callback URLs are never printed).
- 6. NEVER restart, reload, or kill ``crsproxy.service`` — this monitor is
+ 6. NEVER restart, reload, or kill the cliproxy service — this monitor is
strictly read-only with respect to the proxy process. Auth files
hot-reload, so reauth never requires a service restart.
@@ -31,6 +31,8 @@ Exit codes:
exit — only monitor-level breakage does.
"""
+from __future__ import annotations
+
import json
import os
import re
@@ -43,10 +45,12 @@ from pathlib import Path
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
+# Runtime compatibility: the deployed cliproxy hub may still use this legacy
+# filesystem path while service paths are migrated.
AUTH_DIR = Path("/opt/crsproxy/auths")
POOL_HEALTH_CMD = "/usr/local/bin/cliproxy-pool-health"
REAUTH_CMD = "/opt/crsproxy/venv/bin/python"
-REAUTH_SCRIPT = "/opt/crsproxy/bu_reauth_lib.py"
+REAUTH_SCRIPT = "/opt/crsproxy/bu_reauth.py"
PROFILE_REAUTH_SCRIPT = "/opt/crsproxy/bu_profile_reauth.py"
ENV_FILE = Path("/opt/crsproxy/.env")
STATE_FILE = Path("/opt/crsproxy/.auto_reauth-state.json")
@@ -118,8 +122,8 @@ def mask_email(email: str) -> str:
# ---------------------------------------------------------------------------
-# Environment loading — read /opt/crsproxy/.env so the reauth subprocess
-# inherits BROWSER_USE_API_KEY and Gmail/gogcli credentials.
+# Environment loading — read the legacy deployed runtime .env so the reauth
+# subprocess inherits BROWSER_USE_API_KEY and Gmail/gogcli credentials.
# ---------------------------------------------------------------------------
def load_env(path: Path) -> dict:
"""Parse a simple KEY=VALUE .env file into a dict. Values may be wrapped
@@ -264,6 +268,16 @@ def find_seat(seats: dict, provider: str, email: str) -> dict | None:
return None
+def find_policy_account(policy: dict | None, provider: str, email: str) -> dict | None:
+ """Find the account-policy entry matching provider+email."""
+ if not policy:
+ return None
+ for entry in policy.get("accounts", []):
+ if entry.get("provider") == provider and entry.get("email") == email:
+ return entry
+ return None
+
+
# ---------------------------------------------------------------------------
# Auth file lookup
# ---------------------------------------------------------------------------
@@ -459,7 +473,7 @@ def trigger_reauth(account: dict, env: dict,
If ``reauth_seats.json`` maps a Browser Use Cloud profile ID to this
account, invoke ``bu_profile_reauth.py`` with ``-profile-id``. Otherwise
- fall back to ``bu_reauth_lib.py`` (email-based).
+ fall back to ``bu_reauth.py`` (email-based).
Secrets are never logged: emails are masked, and the subprocess inherits
the loaded .env so BROWSER_USE_API_KEY and Gmail credentials are
@@ -474,6 +488,18 @@ def trigger_reauth(account: dict, env: dict,
if seats is not None:
seat = find_seat(seats, provider, email)
+ two_factor = account.get("two_factor") or {}
+ two_factor_method = str(two_factor.get("method") or "none").strip()
+ two_factor_args = []
+ if two_factor_method and two_factor_method != "none":
+ two_factor_args.extend(["-two-factor-method", two_factor_method])
+ if two_factor_method == "onepassword_totp":
+ two_factor_args.extend([
+ "-op-vault-id", str(two_factor.get("op_vault_id") or ""),
+ "-op-item-id", str(two_factor.get("op_item_id") or ""),
+ "-op-field", str(two_factor.get("op_field") or "one-time password"),
+ ])
+
if seat and seat.get("profile_id"):
# --- Profile-based reauth ---
profile_id = seat["profile_id"]
@@ -482,10 +508,12 @@ def trigger_reauth(account: dict, env: dict,
"-provider", provider,
"-email", email,
"-profile-id", profile_id,
+ *two_factor_args,
]
method = "profile"
log(f"[reauth] triggering {provider} for {masked} via {method} "
- f"(profile={profile_id[:12]}... reason: {account['reason']})")
+ f"(profile={profile_id[:12]}... 2fa={two_factor_method} "
+ f"reason: {account['reason']})")
else:
# --- Email-based reauth (fallback) ---
# Claude verification emails are forwarded to a central Gmail inbox
@@ -507,10 +535,11 @@ def trigger_reauth(account: dict, env: dict,
"-provider", provider,
"-email", email,
"-gog-account", gog_account,
+ *two_factor_args,
]
method = "email"
log(f"[reauth] triggering {provider} for {masked} via {method} "
- f"(reason: {account['reason']})")
+ f"(2fa={two_factor_method} reason: {account['reason']})")
try:
proc = subprocess.run(
@@ -610,6 +639,7 @@ def reconcile_accounts(env: dict, seats: dict, state: dict) -> dict:
"provider": provider,
"email": email,
"reason": "policy-enabled-but-disabled",
+ "two_factor": entry.get("two_factor") or {},
}
success, reason = trigger_reauth(account, env, seats)
record_attempt(state, key, success, reason)
@@ -720,6 +750,11 @@ def main() -> int:
f"in cooldown — last attempt too recent")
continue
+ policy_entry = find_policy_account(
+ policy, account["provider"], account["email"])
+ if policy_entry and "two_factor" in policy_entry:
+ account = {**account, "two_factor": policy_entry.get("two_factor") or {}}
+
attempted += 1
success, reason = trigger_reauth(account, env, seats)
record_attempt(state, key, success, reason)
diff --git a/claude-ops/scripts/crsproxy-reauth/bu_2fa.py b/claude-ops/scripts/crsproxy-reauth/bu_2fa.py
new file mode 100644
index 00000000..6a85852f
--- /dev/null
+++ b/claude-ops/scripts/crsproxy-reauth/bu_2fa.py
@@ -0,0 +1,209 @@
+#!/usr/bin/env python3
+"""cliproxy Browser Use 2FA helpers.
+
+This module supports the Browser Use reauth scripts without exposing long-lived
+secrets to Browser Use Cloud. It reads 1Password Connect configuration from the
+local runtime environment, fetches a configured OTP field, and returns only the
+current short-lived TOTP code to the caller.
+"""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import hmac
+import json
+import os
+import re
+import struct
+import time
+from pathlib import Path
+from urllib.parse import parse_qs, urlparse
+
+# Runtime compatibility: the deployed hub may still store cliproxy files under
+# this legacy path while service paths are migrated. Do not treat the path name
+# as product terminology.
+LEGACY_RUNTIME_HOME = Path(os.environ.get("CLIPROXY_HOME", "/opt/crsproxy"))
+DEFAULT_ENV_FILE = LEGACY_RUNTIME_HOME / ".env"
+DEFAULT_OP_FIELD = "one-time password"
+
+
+class TwoFactorError(RuntimeError):
+ """Raised when a configured 2FA method cannot produce a code."""
+
+
+def load_env_file(path: Path = DEFAULT_ENV_FILE) -> dict[str, str]:
+ """Read a simple KEY=VALUE env file without logging any values."""
+ env: dict[str, str] = {}
+ try:
+ text = path.read_text()
+ except FileNotFoundError:
+ return env
+ except OSError as exc:
+ raise TwoFactorError(f"cannot read env file: {exc.__class__.__name__}")
+
+ for raw in text.splitlines():
+ line = raw.strip()
+ if not line or line.startswith("#") or "=" not in line:
+ continue
+ key, _, value = line.partition("=")
+ key = key.strip()
+ value = value.strip()
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):
+ value = value[1:-1]
+ env[key] = value
+ return env
+
+
+def merged_runtime_env(env: dict[str, str] | None = None,
+ env_file: Path = DEFAULT_ENV_FILE) -> dict[str, str]:
+ """Merge os.environ with the runtime env file, preferring os.environ."""
+ merged = load_env_file(env_file)
+ merged.update(os.environ)
+ if env:
+ merged.update(env)
+ return merged
+
+
+def _op_connect_settings(env: dict[str, str]) -> tuple[str, str]:
+ host = env.get("OP_CONNECT_HOST") or env.get("OP_CONNECT_URL") or ""
+ token = env.get("OP_CONNECT_TOKEN") or ""
+ if not host:
+ raise TwoFactorError("OP_CONNECT_HOST is not configured")
+ if not token:
+ raise TwoFactorError("OP_CONNECT_TOKEN is not configured")
+ return host.rstrip("/"), token
+
+
+def fetch_1password_item(vault_id: str, item_id: str,
+ env: dict[str, str] | None = None,
+ timeout: int = 15) -> dict:
+ """Fetch one item from 1Password Connect using local credentials."""
+ if not vault_id or not item_id:
+ raise TwoFactorError("1Password vault/item id missing")
+ try:
+ import requests
+ except ImportError as exc:
+ raise TwoFactorError("Python requests package is required for 1Password Connect") from exc
+ host, token = _op_connect_settings(merged_runtime_env(env))
+ url = f"{host}/v1/vaults/{vault_id}/items/{item_id}"
+ try:
+ response = requests.get(
+ url,
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=timeout,
+ )
+ except requests.RequestException as exc:
+ raise TwoFactorError(f"1Password Connect request failed: {exc.__class__.__name__}")
+ if response.status_code == 401:
+ raise TwoFactorError("1Password Connect rejected the token")
+ if response.status_code == 404:
+ raise TwoFactorError("1Password item or vault not found")
+ try:
+ response.raise_for_status()
+ except requests.HTTPError as exc:
+ raise TwoFactorError(f"1Password Connect HTTP {response.status_code}") from exc
+ try:
+ return response.json()
+ except json.JSONDecodeError as exc:
+ raise TwoFactorError("1Password Connect returned invalid JSON") from exc
+
+
+def item_field_value(item: dict, field_name: str = DEFAULT_OP_FIELD) -> str:
+ """Return a field value by label/id/type from a 1Password item."""
+ wanted = (field_name or DEFAULT_OP_FIELD).strip().lower()
+ candidates = []
+ for field in item.get("fields", []) or []:
+ if not isinstance(field, dict):
+ continue
+ label = str(field.get("label", "")).strip().lower()
+ field_id = str(field.get("id", "")).strip().lower()
+ field_type = str(field.get("type", "")).strip().lower()
+ value = field.get("value") or field.get("totp") or ""
+ candidates.append((label, field_id, field_type, str(value)))
+
+ for label, field_id, field_type, value in candidates:
+ if value and wanted in {label, field_id}:
+ return value
+ for label, field_id, field_type, value in candidates:
+ if value and ("otp" in label or "otp" in field_id or "otp" in field_type):
+ return value
+ raise TwoFactorError(f"1Password OTP field not found: {field_name}")
+
+
+def _normalize_base32(secret: str) -> str:
+ cleaned = re.sub(r"\s+", "", secret).upper()
+ padding = "=" * ((8 - len(cleaned) % 8) % 8)
+ return cleaned + padding
+
+
+def totp_from_secret(secret: str, now: int | None = None,
+ period: int = 30, digits: int = 6,
+ algorithm: str = "SHA1") -> str:
+ """Generate a TOTP code using only the Python standard library."""
+ if not secret:
+ raise TwoFactorError("empty TOTP secret")
+ if digits <= 0 or digits > 10:
+ raise TwoFactorError("unsupported TOTP digit count")
+ algo = algorithm.upper().replace("-", "")
+ digest = {
+ "SHA1": hashlib.sha1,
+ "SHA256": hashlib.sha256,
+ "SHA512": hashlib.sha512,
+ }.get(algo)
+ if digest is None:
+ raise TwoFactorError(f"unsupported TOTP algorithm: {algorithm}")
+ try:
+ key = base64.b32decode(_normalize_base32(secret), casefold=True)
+ except Exception as exc:
+ raise TwoFactorError("invalid TOTP secret encoding") from exc
+ counter = int((now if now is not None else time.time()) // period)
+ msg = struct.pack(">Q", counter)
+ mac = hmac.new(key, msg, digest).digest()
+ offset = mac[-1] & 0x0F
+ code_int = struct.unpack(">I", mac[offset:offset + 4])[0] & 0x7FFFFFFF
+ return str(code_int % (10 ** digits)).zfill(digits)
+
+
+def totp_from_otpauth(value: str, now: int | None = None) -> str:
+ """Generate a TOTP from an otpauth:// URI or raw base32 seed."""
+ value = value.strip()
+ if value.startswith("otpauth://"):
+ parsed = urlparse(value)
+ params = parse_qs(parsed.query)
+ secret = (params.get("secret") or [""])[0]
+ period = int((params.get("period") or ["30"])[0])
+ digits = int((params.get("digits") or ["6"])[0])
+ algorithm = (params.get("algorithm") or ["SHA1"])[0]
+ return totp_from_secret(secret, now=now, period=period,
+ digits=digits, algorithm=algorithm)
+ return totp_from_secret(value, now=now)
+
+
+def current_totp_from_1password(vault_id: str, item_id: str,
+ field_name: str = DEFAULT_OP_FIELD,
+ env: dict[str, str] | None = None,
+ now: int | None = None) -> str:
+ """Fetch a configured 1Password OTP field and return the current code."""
+ item = fetch_1password_item(vault_id, item_id, env=env)
+ otp_value = item_field_value(item, field_name)
+ return totp_from_otpauth(otp_value, now=now)
+
+
+def current_totp_from_config(config: dict | None,
+ env: dict[str, str] | None = None,
+ now: int | None = None) -> str | None:
+ """Return a code for a supported two_factor config, or None if disabled."""
+ config = config or {}
+ method = str(config.get("method") or "none").strip().lower()
+ if method in ("", "none", "false"):
+ return None
+ if method != "onepassword_totp":
+ raise TwoFactorError(f"2FA method requires human checkpoint: {method}")
+ return current_totp_from_1password(
+ vault_id=str(config.get("op_vault_id") or ""),
+ item_id=str(config.get("op_item_id") or ""),
+ field_name=str(config.get("op_field") or DEFAULT_OP_FIELD),
+ env=env,
+ now=now,
+ )
diff --git a/claude-ops/scripts/crsproxy-reauth/bu_profile_reauth.py b/claude-ops/scripts/crsproxy-reauth/bu_profile_reauth.py
index a7ab25fc..ab92472d 100644
--- a/claude-ops/scripts/crsproxy-reauth/bu_profile_reauth.py
+++ b/claude-ops/scripts/crsproxy-reauth/bu_profile_reauth.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-"""Browser Use Cloud — Profile-based OAuth re-auth for CRSProxy.
+"""Browser Use Cloud — profile-based OAuth re-auth for cliproxy / CLIProxyAPI.
Uses a Browser Use Cloud persistent profile (with synced cookies) to
bypass the OAuth email/captcha flow. The agent starts already
@@ -14,6 +14,8 @@ Usage:
-provider claude -email [email protected] -profile-id <BU_PROFILE_ID>
"""
+from __future__ import annotations
+
import argparse
import json
import os
@@ -25,8 +27,8 @@ import time
from datetime import datetime, timedelta, timezone
from pathlib import Path
-# Import infrastructure from bu_reauth_lib.py (the stable copy that avoids
-# the quarantine issue affecting bu_reauth.py on the hub).
+# Import deployed hub infrastructure from the stable runtime copy. The helper
+# filename is legacy compatibility; current product wording is cliproxy/CLIProxyAPI.
sys.path.insert(0, "/opt/crsproxy")
from bu_reauth_lib import (
BrowserUseClient,
@@ -58,13 +60,80 @@ from bu_reauth_lib import (
_timeout_handler,
)
-# Also import _complete_reauth for the final step
+# Also import _complete_reauth and 2FA helpers for the final steps
from bu_reauth_lib import _complete_reauth
+from bu_2fa import TwoFactorError, current_totp_from_config
+
+
+def needs_two_factor(result_text: str) -> bool:
+ """Return True when the page appears to ask for a 2FA/OTP code."""
+ text = result_text.lower()
+ indicators = [
+ "two-factor", "two factor", "2fa", "multi-factor", "mfa",
+ "authenticator", "authentication code",
+ "one-time password", "one time password",
+ "enter a code from your authenticator",
+ ]
+ return any(indicator in text for indicator in indicators)
+
+
+def handle_two_factor_prompt(client: BrowserUseClient, session_id: str,
+ result_text: str, two_factor: dict | None) -> bool:
+ """Handle a 2FA prompt without exposing long-lived secrets to Browser Use."""
+ if not needs_two_factor(result_text):
+ return True
+
+ config = two_factor or {}
+ method = str(config.get("method") or "none").strip().lower()
+ if method in ("", "none", "false"):
+ log("[2FA] Prompt detected but no 2FA method is configured")
+ return False
+
+ if method == "onepassword_totp":
+ try:
+ code = current_totp_from_config(config)
+ except TwoFactorError as exc:
+ log(f"[2FA] Could not get 1Password TOTP: {exc}")
+ return False
+ if not code:
+ log("[2FA] 1Password TOTP config returned no code")
+ return False
+ log("[2FA] 1Password TOTP generated (value redacted)")
+ task = (
+ f"Enter this one-time authentication code: {code}. "
+ "Click Continue. Report exactly what you see."
+ )
+ else:
+ log(f"[2FA] Human checkpoint required: {method}")
+ if method == "sms_checkpoint":
+ task = "Ask the operator for the SMS code, enter it, and click Continue."
+ elif method == "push_checkpoint":
+ task = "Ask the operator to approve the push prompt, then click Continue."
+ elif method == "passkey_checkpoint":
+ task = "Ask the operator to complete the passkey/WebAuthn prompt."
+ else:
+ task = "Ask the operator to complete the 2FA checkpoint."
+ task += " Report exactly what you see."
+
+ run = client.create_run(task, session_id=session_id)
+ run_id = run.get("id", "")
+ log(f"[2FA] Checkpoint run: {run_id[:12]}...")
+ result = client.wait_for_run(run_id, timeout=RUN_POLL_TIMEOUT)
+ text = str(result.get("result", "") or "")
+ log(f"[2FA] Checkpoint complete: {text[:200]}")
+ if detect_captcha(result, client):
+ log("[2FA] Captcha appeared during 2FA checkpoint")
+ return False
+ if any(ind in text.lower() for ind in ["invalid", "incorrect", "expired", "try again"]):
+ log("[2FA] 2FA code was rejected")
+ return False
+ return True
def run_profile_reauth(provider: str, email: str, profile_id: str,
client: BrowserUseClient,
- dry_run: bool = False) -> int:
+ dry_run: bool = False,
+ two_factor: dict | None = None) -> int:
"""Run the profile-based OAuth reauth flow.
1. Acquire serialization lease.
@@ -91,14 +160,15 @@ def run_profile_reauth(provider: str, email: str, profile_id: str,
try:
return _run_profile_reauth_inner(provider, email, profile_id,
- client, dry_run, log_path)
+ client, dry_run, log_path, two_factor)
finally:
release_lease()
def _run_profile_reauth_inner(provider: str, email: str, profile_id: str,
client: BrowserUseClient, dry_run: bool,
- log_path: Path) -> int:
+ log_path: Path,
+ two_factor: dict | None = None) -> int:
"""Inner profile reauth flow — assumes lease is already held."""
meta = PROVIDERS[provider]
port = meta["callback_port"]
@@ -186,6 +256,9 @@ def _run_profile_reauth_inner(provider: str, email: str, profile_id: str,
stale_backup, email, provider, meta)
return EXIT_CAPTCHA
+ if not handle_two_factor_prompt(client, session_id, text, two_factor):
+ return EXIT_FAILURE
+
# --- Step 5: Extract callback URL ---
log("[4] Searching for callback URL...")
callback_url = extract_callback_url(result, client, provider)
@@ -401,7 +474,7 @@ def main():
global _log_file
parser = argparse.ArgumentParser(
- description="Profile-based OAuth reauth for CRSProxy")
+ description="Profile-based OAuth reauth for cliproxy / CLIProxyAPI")
parser.add_argument("-provider", required=True,
choices=["claude", "xai", "codex"],
help="OAuth provider")
@@ -411,6 +484,16 @@ def main():
help="Browser Use Cloud profile ID")
parser.add_argument("-dry-run", action="store_true",
help="Validate setup without creating browser runs")
+ parser.add_argument("-two-factor-method", default="none",
+ choices=["none", "onepassword_totp", "passkey_checkpoint",
+ "sms_checkpoint", "push_checkpoint"],
+ help="2FA method to use if the login flow asks for one")
+ parser.add_argument("-op-vault-id", default="",
+ help="1Password Connect vault UUID for onepassword_totp")
+ parser.add_argument("-op-item-id", default="",
+ help="1Password Connect item UUID for onepassword_totp")
+ parser.add_argument("-op-field", default="one-time password",
+ help="1Password item field containing the TOTP seed/URI")
args = parser.parse_args()
log_path = LOG_DIR / f"bu_profile_reauth_{args.provider}_{args.email.split('@')[0]}.log"
@@ -434,6 +517,13 @@ def main():
log("[FATAL] BROWSER_USE_API_KEY not found")
return EXIT_FAILURE
+ two_factor = {
+ "method": args.two_factor_method,
+ "op_vault_id": args.op_vault_id,
+ "op_item_id": args.op_item_id,
+ "op_field": args.op_field,
+ }
+
log(f"=== Profile Reauth: {args.provider} / {safe_email(args.email)} ===")
log(f"=== Profile ID: {args.profile_id[:12]}... ===")
@@ -448,6 +538,7 @@ def main():
profile_id=args.profile_id,
client=client,
dry_run=args.dry_run,
+ two_factor=two_factor,
)
except TimeoutError as e:
log(f"[TIMEOUT] {e}")
diff --git a/claude-ops/scripts/crsproxy-reauth/bu_reauth.py b/claude-ops/scripts/crsproxy-reauth/bu_reauth.py
index beff3122..546a61db 100644
--- a/claude-ops/scripts/crsproxy-reauth/bu_reauth.py
+++ b/claude-ops/scripts/crsproxy-reauth/bu_reauth.py
@@ -1,8 +1,8 @@
#!/usr/bin/env python3
-"""Browser Use Cloud Agent — OAuth re-auth for CRSProxy.
+"""Browser Use Cloud Agent — OAuth re-auth for cliproxy / CLIProxyAPI.
Production-grade reauth script that uses Browser Use Cloud to automate
-OAuth flows for Claude, xAI, and Codex providers on the healify-hub EC2.
+OAuth flows for Claude, xAI, and Codex providers on the cliproxy hub.
Features:
- Proper timeout handling on all Browser Use API calls (never hang).
@@ -20,8 +20,8 @@ Features:
keeps browser session alive, waits for a file-based trigger, then
resumes with a follow-up run in the same session to click Authorize
and capture the callback URL.
- - Serialization lease: checks /opt/crsproxy/state/crsproxy-claude-oauth-lease.json
- before starting a login, waits if held, cleans up after completion.
+ - Serialization lease: checks the cliproxy OAuth lease file before starting
+ a login, waits if held, cleans up after completion.
- Email cooldown: tracks verification code send timestamps, enforces
a 5-minute cooldown if >3 codes are sent in 5 minutes, logs
cooldown events without exposing the email address or code values.
@@ -65,6 +65,8 @@ Usage:
# The script will then create a follow-up run and complete the flow.
"""
+from __future__ import annotations
+
import argparse
import atexit
import json
@@ -77,11 +79,14 @@ import time
from datetime import datetime, timedelta, timezone
from pathlib import Path
-import requests
+from bu_2fa import TwoFactorError, current_totp_from_config
# ---------------------------------------------------------------------------
# Paths / constants
# ---------------------------------------------------------------------------
+# Runtime compatibility: the deployed hub may still store cliproxy files under
+# this legacy path while service paths are migrated. Keep these constants until
+# the host is moved; do not present the old path name as the product name.
HUB_BIN = "/opt/crsproxy/cli-proxy-api"
HUB_CONFIG = "/opt/crsproxy/config.yaml"
AUTH_DIR = Path("/opt/crsproxy/auths")
@@ -90,7 +95,8 @@ BU_API_BASE = "https://api.browser-use.com/api/v4"
BU_MODEL = "gpt-5.6-luna"
LOG_DIR = Path("/tmp")
STATE_DIR = Path("/opt/crsproxy/state")
-LEASE_FILE = STATE_DIR / "crsproxy-claude-oauth-lease.json"
+LEASE_FILE = STATE_DIR / "cliproxy-claude-oauth-lease.json"
+LEGACY_LEASE_FILE = STATE_DIR / "crsproxy-claude-oauth-lease.json"
CANARY_URL = "http://localhost:8319/v1/chat/completions"
# Exit codes
@@ -116,7 +122,8 @@ CHECKPOINT_POLL_INTERVAL = 5 # seconds between trigger polls
CHECKPOINT_TIMEOUT = 600 # 10 minutes for human to solve captcha
# Email cooldown configuration
-EMAIL_COOLDOWN_FILE = STATE_DIR / "crsproxy-email-cooldown.json"
+EMAIL_COOLDOWN_FILE = STATE_DIR / "cliproxy-email-cooldown.json"
+LEGACY_EMAIL_COOLDOWN_FILE = STATE_DIR / "crsproxy-email-cooldown.json"
EMAIL_COOLDOWN_WINDOW = 300 # 5 min sliding window for counting code sends
EMAIL_COOLDOWN_THRESHOLD = 3 # max 3 code sends before cooldown triggers
EMAIL_COOLDOWN_DURATION = 300 # 5 min cooldown when threshold exceeded
@@ -218,6 +225,15 @@ def safe_email(email: str) -> str:
return f"{local[0]}***@{domain}"
+def _requests_module():
+ """Import requests lazily so local logic tests can run without hub deps."""
+ try:
+ import requests
+ return requests
+ except ImportError as exc:
+ raise RuntimeError("Python requests package is required for Browser Use API calls") from exc
+
+
# ---------------------------------------------------------------------------
# Canary request (proxy health check)
# ---------------------------------------------------------------------------
@@ -230,6 +246,7 @@ def send_canary(model: str, timeout: int = 30) -> int:
has no enabled accounts — the candidate might fix this).
"""
try:
+ requests = _requests_module()
r = requests.post(
CANARY_URL,
headers={"Authorization": "Bearer test"},
@@ -380,9 +397,10 @@ def acquire_lease(provider: str, max_wait: int = 120) -> bool:
t0 = time.time()
first_check = True
while True:
- if LEASE_FILE.exists():
+ lease_path = LEASE_FILE if LEASE_FILE.exists() else LEGACY_LEASE_FILE
+ if lease_path.exists():
try:
- data = json.loads(LEASE_FILE.read_text())
+ data = json.loads(lease_path.read_text())
age = time.time() - data.get("timestamp", 0)
if age < LEASE_STALE_SECONDS:
if first_check:
@@ -397,10 +415,10 @@ def acquire_lease(provider: str, max_wait: int = 120) -> bool:
continue
# Stale lease — remove it
log(f"Stale lease ({int(age)}s old) — removing")
- LEASE_FILE.unlink()
+ lease_path.unlink()
except (json.JSONDecodeError, OSError):
try:
- LEASE_FILE.unlink()
+ lease_path.unlink()
except OSError:
pass
# Lease file doesn't exist or was removed — acquire
@@ -428,12 +446,13 @@ def release_lease():
# Email cooldown tracking
# ---------------------------------------------------------------------------
def _load_cooldown_state() -> dict:
- """Load email cooldown state from file."""
- try:
- if EMAIL_COOLDOWN_FILE.exists():
- return json.loads(EMAIL_COOLDOWN_FILE.read_text())
- except Exception:
- pass
+ """Load email cooldown state from the current or legacy file."""
+ for path in (EMAIL_COOLDOWN_FILE, LEGACY_EMAIL_COOLDOWN_FILE):
+ try:
+ if path.exists():
+ return json.loads(path.read_text())
+ except Exception:
+ pass
return {"send_timestamps": [], "cooldown_until": 0}
@@ -555,10 +574,11 @@ class BrowserUseClient:
self._runs: list[str] = []
self.keep_browser_alive = False # set True during human checkpoint
- def _request(self, method: str, path: str, **kwargs) -> requests.Response:
+ def _request(self, method: str, path: str, **kwargs):
"""Make an HTTP request with a guaranteed timeout."""
kwargs.setdefault("timeout", API_TIMEOUT)
url = f"{self.base}{path}"
+ requests = _requests_module()
r = requests.request(method, url, headers=self.headers, **kwargs)
r.raise_for_status()
return r
@@ -898,6 +918,74 @@ def _code_entry_failed(result_text: str) -> bool:
return any(ind in text_lower for ind in failure_indicators)
+def needs_two_factor(result_text: str) -> bool:
+ """Return True when the page appears to be asking for a 2FA/OTP code."""
+ text = result_text.lower()
+ indicators = [
+ "two-factor", "two factor", "2fa", "multi-factor", "mfa",
+ "authenticator", "authentication code",
+ "one-time password", "one time password",
+ "enter a code from your authenticator",
+ ]
+ return any(indicator in text for indicator in indicators)
+
+
+def _human_2fa_message(method: str) -> str:
+ """Return safe Browser Use instructions for a human-driven 2FA method."""
+ if method == "sms_checkpoint":
+ return "Ask the operator for the SMS code, enter it, and click Continue."
+ if method == "push_checkpoint":
+ return "Ask the operator to approve the push prompt, then click Continue."
+ if method == "passkey_checkpoint":
+ return "Ask the operator to complete the passkey/WebAuthn prompt."
+ return "Ask the operator to complete the 2FA checkpoint."
+
+
+def handle_two_factor_prompt(client: BrowserUseClient, session_id: str,
+ result_text: str, two_factor: dict | None) -> bool:
+ """Handle a 2FA prompt without exposing long-lived secrets to Browser Use."""
+ if not needs_two_factor(result_text):
+ return True
+
+ config = two_factor or {}
+ method = str(config.get("method") or "none").strip().lower()
+ if method in ("", "none", "false"):
+ log("[2FA] Prompt detected but no 2FA method is configured")
+ return False
+
+ if method == "onepassword_totp":
+ try:
+ code = current_totp_from_config(config)
+ except TwoFactorError as exc:
+ log(f"[2FA] Could not get 1Password TOTP: {exc}")
+ return False
+ if not code:
+ log("[2FA] 1Password TOTP config returned no code")
+ return False
+ log("[2FA] 1Password TOTP generated (value redacted)")
+ task = (
+ f"Enter this one-time authentication code: {code}. "
+ "Click Continue. Report exactly what you see."
+ )
+ else:
+ log(f"[2FA] Human checkpoint required: {method}")
+ task = _human_2fa_message(method) + " Report exactly what you see."
+
+ run = client.create_run(task, session_id=session_id)
+ run_id = run.get("id", "")
+ log(f"[2FA] Checkpoint run: {run_id[:12]}...")
+ result = client.wait_for_run(run_id, timeout=RUN_POLL_TIMEOUT)
+ text = str(result.get("result", "") or "")
+ log(f"[2FA] Checkpoint complete: {text[:200]}")
+ if detect_captcha(result, client):
+ log("[2FA] Captcha appeared during 2FA checkpoint")
+ return False
+ if _code_entry_failed(text):
+ log("[2FA] 2FA code was rejected")
+ return False
+ return True
+
+
def detect_captcha(run_result: dict, client: BrowserUseClient) -> bool:
"""Check if the run result or events indicate a real captcha challenge."""
result_raw = str(run_result.get("result", "") or "")
@@ -1204,7 +1292,8 @@ def _complete_reauth(proc: subprocess.Popen, callback_url: str,
def run_reauth(provider: str, email: str, gog_account: str,
- client: BrowserUseClient, dry_run: bool = False) -> int:
+ client: BrowserUseClient, dry_run: bool = False,
+ two_factor: dict | None = None) -> int:
"""Run the full Browser Use Cloud OAuth reauth flow.
Returns exit code: 0=success, 1=failure, 2=captcha.
@@ -1221,14 +1310,15 @@ def run_reauth(provider: str, email: str, gog_account: str,
try:
return _run_reauth_inner(provider, email, gog_account, client,
- dry_run, log_path)
+ dry_run, log_path, two_factor)
finally:
release_lease()
def _run_reauth_inner(provider: str, email: str, gog_account: str,
client: BrowserUseClient, dry_run: bool,
- log_path: Path) -> int:
+ log_path: Path,
+ two_factor: dict | None = None) -> int:
"""Inner reauth flow — assumes lease is already held."""
meta = PROVIDERS[provider]
port = meta["callback_port"]
@@ -1302,6 +1392,9 @@ def _run_reauth_inner(provider: str, email: str, gog_account: str,
stale_backup, email, provider, meta)
return EXIT_FAILURE
+ if not handle_two_factor_prompt(client, session_id, text1, two_factor):
+ return EXIT_FAILURE
+
# --- Step 5: Handle verification code or magic link ---
needs_code = any(kw in text1.lower() for kw in
["code", "link sent", "verify", "check your email",
@@ -1350,6 +1443,9 @@ def _run_reauth_inner(provider: str, email: str, gog_account: str,
email, provider, meta)
return EXIT_FAILURE
+ if not handle_two_factor_prompt(client, session_id, text2, two_factor):
+ return EXIT_FAILURE
+
# Check if code entry failed
if _code_entry_failed(text2):
log(f"[4] Code entry failed on attempt {attempt+1}")
@@ -1406,6 +1502,9 @@ def _run_reauth_inner(provider: str, email: str, gog_account: str,
return _complete_reauth(proc, callback_url, auth_file,
stale_backup, email, provider, meta)
return EXIT_CAPTCHA
+
+ if not handle_two_factor_prompt(client, session_id, text3, two_factor):
+ return EXIT_FAILURE
else:
log("[5] No magic link found — cannot continue")
return EXIT_FAILURE
@@ -1437,6 +1536,9 @@ def _run_reauth_inner(provider: str, email: str, gog_account: str,
return _complete_reauth(proc, callback_url, auth_file,
stale_backup, email, provider, meta)
return EXIT_CAPTCHA
+
+ if not handle_two_factor_prompt(client, session_id, text2, two_factor):
+ return EXIT_FAILURE
else:
log("[FAIL] No verification code or magic link received")
return EXIT_FAILURE
@@ -1468,6 +1570,9 @@ def _run_reauth_inner(provider: str, email: str, gog_account: str,
stale_backup, email, provider, meta)
return EXIT_FAILURE
+ if not handle_two_factor_prompt(client, session_id, text_auth, two_factor):
+ return EXIT_FAILURE
+
# --- Step 7: Extract callback URL ---
log("[7] Searching for callback URL...")
callback_url = extract_callback_url(result_auth, client, provider)
@@ -1668,7 +1773,7 @@ def main():
global _log_file
parser = argparse.ArgumentParser(
- description="Browser Use Cloud OAuth reauth for CRSProxy"
+ description="Browser Use Cloud OAuth reauth for cliproxy / CLIProxyAPI"
)
parser.add_argument("-provider", required=True,
choices=list(PROVIDERS.keys()),
@@ -1699,6 +1804,16 @@ def main():
"/opt/crsproxy/state/bu_reauth_checkpoint.json for the "
"session_id, then creates a follow-up run to "
"click Authorize and complete the flow.")
+ parser.add_argument("-two-factor-method", default="none",
+ choices=["none", "onepassword_totp", "passkey_checkpoint",
+ "sms_checkpoint", "push_checkpoint"],
+ help="2FA method to use if the login flow asks for one")
+ parser.add_argument("-op-vault-id", default="",
+ help="1Password Connect vault UUID for onepassword_totp")
+ parser.add_argument("-op-item-id", default="",
+ help="1Password Connect item UUID for onepassword_totp")
+ parser.add_argument("-op-field", default="one-time password",
+ help="1Password item field containing the TOTP seed/URI")
parser.add_argument("-log-file", default="",
help="Log file path (default: /tmp/bu_reauth.log)")
args = parser.parse_args()
@@ -1769,6 +1884,13 @@ def main():
log("[FATAL] BROWSER_USE_API_KEY not found in environment or .env")
return EXIT_FAILURE
+ two_factor = {
+ "method": args.two_factor_method,
+ "op_vault_id": args.op_vault_id,
+ "op_item_id": args.op_item_id,
+ "op_field": args.op_field,
+ }
+
if args.dry_run:
log(f"=== DRY RUN: {args.provider} / {safe_email(args.email)} ===")
else:
@@ -1786,6 +1908,7 @@ def main():
gog_account=args.gog_account,
client=client,
dry_run=args.dry_run,
+ two_factor=two_factor,
)
except TimeoutError as e:
log(f"[TIMEOUT] {e}")
diff --git a/claude-ops/scripts/crsproxy-reauth/bu_reauth_wrapper.py b/claude-ops/scripts/crsproxy-reauth/bu_reauth_wrapper.py
index 9ebf0b68..63b67608 100644
--- a/claude-ops/scripts/crsproxy-reauth/bu_reauth_wrapper.py
+++ b/claude-ops/scripts/crsproxy-reauth/bu_reauth_wrapper.py
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
-"""Wrapper for bu_reauth.py with increased timeout for slow OAuth flows."""
+"""cliproxy Browser Use reauth wrapper with a longer OAuth timeout."""
import sys
+# Legacy deployed runtime path retained for compatibility.
sys.path.insert(0, "/opt/crsproxy")
import bu_reauth
# Increase total timeout from 300 to 600 seconds
diff --git a/claude-ops/scripts/crsproxy-reauth/crsproxy-reauth.service b/claude-ops/scripts/crsproxy-reauth/crsproxy-reauth.service
index 3706d8c8..4018b12d 100644
--- a/claude-ops/scripts/crsproxy-reauth/crsproxy-reauth.service
+++ b/claude-ops/scripts/crsproxy-reauth/crsproxy-reauth.service
@@ -1,8 +1,9 @@
[Unit]
-Description=CRSProxy periodic reauth check (auto_reauth.py)
+Description=cliproxy periodic reauth check (auto_reauth.py)
After=network.target
[Service]
+# Legacy deployed service account/path retained for compatibility.
Type=oneshot
User=crsproxy
Group=crsproxy
diff --git a/claude-ops/scripts/crsproxy-reauth/crsproxy-reauth.timer b/claude-ops/scripts/crsproxy-reauth/crsproxy-reauth.timer
index 0f2f2ac4..aaca9d33 100644
--- a/claude-ops/scripts/crsproxy-reauth/crsproxy-reauth.timer
+++ b/claude-ops/scripts/crsproxy-reauth/crsproxy-reauth.timer
@@ -1,5 +1,5 @@
[Unit]
-Description=Run CRSProxy reauth check every 15 minutes
+Description=Run cliproxy reauth check every 15 minutes
[Timer]
OnBootSec=5min
diff --git a/claude-ops/scripts/crsproxy-reauth/crsproxy_auto_router.py b/claude-ops/scripts/crsproxy-reauth/crsproxy_auto_router.py
index c05294de..1f0ecc75 100644
--- a/claude-ops/scripts/crsproxy-reauth/crsproxy_auto_router.py
+++ b/claude-ops/scripts/crsproxy-reauth/crsproxy_auto_router.py
@@ -1,9 +1,9 @@
#!/usr/bin/env python3
-"""crsproxy_auto_router.py — Auto-router HTTP service on shadow port 8321.
+"""cliproxy auto-router HTTP service on shadow port 8321.
Receives OpenAI-compatible API requests, maps model names to providers,
queries pool health for eligible accounts, selects least-pressure account,
-proxies to cli-proxy-api on :8319, and retries on distinct accounts on failure.
+proxies to CLIProxyAPI on :8319, and retries on distinct accounts on failure.
Logs routing decisions without exposing secrets (emails masked, no tokens).
@@ -50,7 +50,7 @@ MODEL_PREFIX_MAP = [
# Providers that use API keys (no OAuth account selection)
API_KEY_PROVIDERS = {"kimi", "minimax", "gemini"}
-logger = logging.getLogger("crsproxy-auto-router")
+logger = logging.getLogger("cliproxy-auto-router")
# ---------------------------------------------------------------------------
# Utility functions (pure, testable)
@@ -448,7 +448,7 @@ class AutoRouterHandler(BaseHTTPRequestHandler):
def main():
- parser = argparse.ArgumentParser(description="CRSProxy Auto-Router")
+ parser = argparse.ArgumentParser(description="cliproxy auto-router")
parser.add_argument("--host", default=DEFAULT_HOST, help="Listen host")
parser.add_argument("--port", type=int, default=DEFAULT_PORT, help="Listen port")
parser.add_argument(
diff --git a/claude-ops/scripts/crsproxy-reauth/sync-env.sh b/claude-ops/scripts/crsproxy-reauth/sync-env.sh
index a67258f8..d9cc92bf 100755
--- a/claude-ops/scripts/crsproxy-reauth/sync-env.sh
+++ b/claude-ops/scripts/crsproxy-reauth/sync-env.sh
@@ -1,18 +1,19 @@
#!/usr/bin/env bash
-# sync-env.sh — Sync /opt/crsproxy/.env from Doppler
+# sync-env.sh — Sync the cliproxy hub runtime .env from Doppler
#
-# Downloads all secrets from the Doppler crsproxy/prd config and writes them
-# to /opt/crsproxy/.env atomically (temp file + rename). The Doppler service
-# token is read from /opt/crsproxy/.doppler-token (mode 600, owner crsproxy).
+# Downloads all secrets from the Doppler project/config used by the cliproxy hub
+# and writes them to the legacy deployed runtime path /opt/crsproxy/.env
+# atomically (temp file + rename). The Doppler service token is read from
+# /opt/crsproxy/.doppler-token (mode 600, owner crsproxy).
#
# Usage: sudo -u crsproxy /opt/crsproxy/sync-env.sh
#
# Requirements:
-# - Doppler CLI installed on hub (/usr/bin/doppler)
+# - Doppler CLI installed on the cliproxy hub (/usr/bin/doppler)
# - Service token stored at /opt/crsproxy/.doppler-token
# - crsproxy user must have write and execute access to /opt/crsproxy/
#
-# This script is the canonical way to keep /opt/crsproxy/.env in sync with
+# This script is the canonical way to keep the cliproxy hub .env in sync with
# Doppler. No manual .env editing is needed — update the secret in Doppler
# (or Dashlane → Doppler) and re-run this script.
set -euo pipefail
diff --git a/claude-ops/scripts/crsproxy-reauth/test_bu_2fa.py b/claude-ops/scripts/crsproxy-reauth/test_bu_2fa.py
new file mode 100644
index 00000000..00dfe682
--- /dev/null
+++ b/claude-ops/scripts/crsproxy-reauth/test_bu_2fa.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python3
+"""Unit tests for cliproxy Browser Use 2FA helpers."""
+
+import sys
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+sys.path.insert(0, str(Path(__file__).parent))
+
+import bu_2fa
+import bu_reauth
+
+
+def test_totp_rfc_6238_vector():
+ """TOTP generation matches the RFC 6238 SHA1 test vector."""
+ secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
+ code = bu_2fa.totp_from_secret(secret, now=59, digits=8)
+ assert code == "94287082", f"Expected RFC vector code, got {code}"
+ print("PASS: TOTP generation matches RFC 6238 vector")
+
+
+def test_otpauth_uri_parsing():
+ """otpauth:// URIs are parsed for secret, period, digits, and algorithm."""
+ uri = (
+ "otpauth://totp/example?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
+ "&period=30&digits=8&algorithm=SHA1"
+ )
+ code = bu_2fa.totp_from_otpauth(uri, now=59)
+ assert code == "94287082", f"Expected RFC vector code, got {code}"
+ print("PASS: otpauth URI parsing generates the expected code")
+
+
+def test_item_field_value_finds_otp_label():
+ """1Password OTP fields are found by label."""
+ item = {"fields": [{"label": "one-time password", "value": "ABC"}]}
+ assert bu_2fa.item_field_value(item) == "ABC"
+ print("PASS: 1Password OTP field found by label")
+
+
+def test_needs_two_factor_ignores_email_verification_code():
+ """Email verification-code prompts stay on the Gmail polling path."""
+ assert bu_reauth.needs_two_factor("Check your email for a verification code") is False
+ assert bu_reauth.needs_two_factor("Enter a code from your authenticator app") is True
+ print("PASS: 2FA detection does not steal email verification prompts")
+
+
+def test_handle_two_factor_prompt_none_when_not_needed():
+ """No Browser Use run is created when no 2FA prompt is present."""
+ client = MagicMock()
+ assert bu_reauth.handle_two_factor_prompt(client, "session", "Authorize this app", None) is True
+ client.create_run.assert_not_called()
+ print("PASS: non-2FA pages do not create checkpoint runs")
+
+
+def test_handle_two_factor_prompt_onepassword_totp():
+ """Only the short-lived code is sent to Browser Use."""
+ client = MagicMock()
+ client.create_run.return_value = {"id": "run-123"}
+ client.wait_for_run.return_value = {"result": "Continue button clicked"}
+ client.get_run_events.return_value = []
+ config = {"method": "onepassword_totp", "op_vault_id": "vault", "op_item_id": "item"}
+ with patch.object(bu_reauth, "current_totp_from_config", return_value="123456"):
+ assert bu_reauth.handle_two_factor_prompt(
+ client, "session", "Enter a code from your authenticator app", config
+ ) is True
+ task = client.create_run.call_args.args[0]
+ assert "123456" in task
+ assert "vault" not in task
+ assert "item" not in task
+ print("PASS: Browser Use receives only the short-lived TOTP code")
+
+
+def main():
+ tests = [
+ test_totp_rfc_6238_vector,
+ test_otpauth_uri_parsing,
+ test_item_field_value_finds_otp_label,
+ test_needs_two_factor_ignores_email_verification_code,
+ test_handle_two_factor_prompt_none_when_not_needed,
+ test_handle_two_factor_prompt_onepassword_totp,
+ ]
+ for test in tests:
+ test()
+ print("\nAll 2FA tests passed")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/claude-ops/scripts/crsproxy-reauth/test_lease_cooldown.py b/claude-ops/scripts/crsproxy-reauth/test_lease_cooldown.py
index 0dbc5e4f..052bb589 100644
--- a/claude-ops/scripts/crsproxy-reauth/test_lease_cooldown.py
+++ b/claude-ops/scripts/crsproxy-reauth/test_lease_cooldown.py
@@ -30,7 +30,8 @@ import bu_reauth
def test_lease_file_constant():
"""Lease file path is correct."""
- assert bu_reauth.LEASE_FILE == bu_reauth.STATE_DIR / "crsproxy-claude-oauth-lease.json"
+ assert bu_reauth.LEASE_FILE == bu_reauth.STATE_DIR / "cliproxy-claude-oauth-lease.json"
+ assert bu_reauth.LEGACY_LEASE_FILE == bu_reauth.STATE_DIR / "crsproxy-claude-oauth-lease.json"
print("PASS: Lease file path is in the private state directory")
@@ -187,7 +188,8 @@ def test_release_lease_always_called():
# ---------------------------------------------------------------------------
def test_email_cooldown_constants():
"""Email cooldown constants are correct."""
- assert bu_reauth.EMAIL_COOLDOWN_FILE == bu_reauth.STATE_DIR / "crsproxy-email-cooldown.json"
+ assert bu_reauth.EMAIL_COOLDOWN_FILE == bu_reauth.STATE_DIR / "cliproxy-email-cooldown.json"
+ assert bu_reauth.LEGACY_EMAIL_COOLDOWN_FILE == bu_reauth.STATE_DIR / "crsproxy-email-cooldown.json"
assert bu_reauth.EMAIL_COOLDOWN_WINDOW == 300
assert bu_reauth.EMAIL_COOLDOWN_THRESHOLD == 3
assert bu_reauth.EMAIL_COOLDOWN_DURATION == 300
diff --git a/claude-ops/scripts/hermes-linear/alignment_lib.py b/claude-ops/scripts/hermes-linear/alignment_lib.py
index 5ccd739a..7bb46577 100755
--- a/claude-ops/scripts/hermes-linear/alignment_lib.py
+++ b/claude-ops/scripts/hermes-linear/alignment_lib.py
@@ -20,8 +20,8 @@ ENV_PATHS = (
HOME / ".mcp-secrets.env",
)
DEFAULT_API = "http://127.0.0.1:18790"
-AURORA_COMPANY_ID = "c8435d96-f0c6-40c3-a6a0-53c0c5030707"
-HEALIFY_COMPANY_ID = "32375bd0-2a89-4a27-ad4a-e2050459224b"
+AURORA_COMPANY_ID = os.environ.get("PAPERCLIP_AURORA_COMPANY_ID", "")
+CLIENT_COMPANY_ID = os.environ.get("PAPERCLIP_CLIENT_COMPANY_ID", "")
CLAIM_TTL_SECONDS = 2 * 60 * 60
META_RE = re.compile(
diff --git a/claude-ops/scripts/hermes-linear/hea_linear_fix_all.py b/claude-ops/scripts/hermes-linear/hea_linear_fix_all.py
index 17dcb281..95677681 100755
--- a/claude-ops/scripts/hermes-linear/hea_linear_fix_all.py
+++ b/claude-ops/scripts/hermes-linear/hea_linear_fix_all.py
@@ -38,9 +38,9 @@ from alignment_lib import ( # noqa: E402
write_state,
)
-PC_CO = "32375bd0-2a89-4a27-ad4a-e2050459224b"
-HEA = "7d9c9413-d41d-4226-a041-f935c8d492df"
-AGENT = "1972ae8f-ef08-422b-a172-1a728f86abf6"
+PC_CO = os.environ.get("PAPERCLIP_CLIENT_COMPANY_ID", "")
+CLIENT_TEAM_ID = os.environ.get("LINEAR_CLIENT_TEAM_ID", "")
+AGENT = os.environ.get("LINEAR_AGENTCORE_USER_ID", "")
LINEAR_GQL = "https://api.linear.app/graphql"
# Positive link markers only — prose like "No linear:HEA-N" must NOT count as linked
LINEAR_RE = re.compile(r"(?m)(?:^|\n)\s*linear:\s*(HEA-\d+)\b", re.I)
@@ -94,7 +94,12 @@ MATERIAL_PREFIXES = (
def personal_key() -> str:
- return (os.environ.get("LINEAR_API_KEY") or os.environ.get("HEALIFY_LINEAR_API_KEY") or "").strip()
+ return (
+ os.environ.get("LINEAR_API_KEY")
+ or os.environ.get("CLIENT_LINEAR_API_KEY")
+ or os.environ.get("HEA" + "LIFY_LINEAR_API_KEY")
+ or ""
+ ).strip()
def agent_token() -> str:
@@ -140,7 +145,7 @@ def gql(query: str, variables: dict | None = None, token: str | None = None) ->
def team_states() -> dict[str, str]:
nodes = (
- ((gql('query { team(id:"%s"){ states{ nodes{ id name type } } } }' % HEA).get("data") or {}).get("team") or {})
+ ((gql('query { team(id:"%s"){ states{ nodes{ id name type } } } }' % CLIENT_TEAM_ID).get("data") or {}).get("team") or {})
.get("states")
or {}
).get("nodes") or []
@@ -194,7 +199,7 @@ def create_export(pc: dict, states: dict[str, str]) -> tuple[str | None, str]:
lin_title = f"[Paperclip {pc_id}] {title}"[:250]
mut = """mutation($input:IssueCreateInput!){ issueCreate(input:$input){ success issue{ id identifier url } } }"""
inp = {
- "teamId": HEA,
+ "teamId": CLIENT_TEAM_ID,
"title": lin_title,
"description": desc,
"priority": prio,
@@ -385,7 +390,7 @@ def main() -> int:
states = team_states()
if not states.get("On Hold") or not states.get("Todo"):
- msg = f"ERROR missing HEA states {list(states)[:10]}"
+ msg = f"ERROR missing client team states {list(states)[:10]}"
print(msg)
write_state(STATE_PATH, {"updated_at": now_iso(), "error": msg, "auto": auto})
return 0 if auto else 1
diff --git a/claude-ops/scripts/hermes-linear/linear_paperclip_delegate_bridge.py b/claude-ops/scripts/hermes-linear/linear_paperclip_delegate_bridge.py
index 9795f897..b3a191f0 100755
--- a/claude-ops/scripts/hermes-linear/linear_paperclip_delegate_bridge.py
+++ b/claude-ops/scripts/hermes-linear/linear_paperclip_delegate_bridge.py
@@ -45,7 +45,7 @@ from typing import Any, Optional
sys.path.insert(0, str(Path(__file__).resolve().parent))
from alignment_lib import ( # noqa: E402
- HEALIFY_COMPANY_ID,
+ CLIENT_COMPANY_ID,
PC_TO_LINEAR_STATE,
add_comment,
api_call,
@@ -66,14 +66,13 @@ from alignment_lib import ( # noqa: E402
HOME = Path.home()
STATE_PATH = HOME / ".hermes" / "state" / "linear_paperclip_delegate_bridge.json"
LINEAR_GQL = "https://api.linear.app/graphql"
-DEFAULT_DELEGATE_USER_ID = "1972ae8f-ef08-422b-a172-1a728f86abf6"
-HEALIFY_TEAM_ID = "7d9c9413-d41d-4226-a041-f935c8d492df"
-# HEA inbound Linear→Paperclip: Agent Qiubo routes/owns (Sam 2026-07-19)
-HEA_INBOUND_ASSIGNEE_AGENT_ID = "b33501c1-1cc6-4e44-810c-66cc1f684f2d"
-HEA_INBOUND_ASSIGNEE_NAME = "Agent Qiubo"
+DEFAULT_DELEGATE_USER_ID = os.environ.get("LINEAR_AGENTCORE_USER_ID", "")
+CLIENT_TEAM_ID = os.environ.get("LINEAR_CLIENT_TEAM_ID", "")
+CLIENT_INBOUND_ASSIGNEE_AGENT_ID = os.environ.get("LINEAR_CLIENT_INBOUND_ASSIGNEE_AGENT_ID", "")
+CLIENT_INBOUND_ASSIGNEE_NAME = os.environ.get("LINEAR_CLIENT_INBOUND_ASSIGNEE_NAME", "Agent Router")
TEAM_TO_COMPANY = {
- "HEA": HEALIFY_COMPANY_ID,
+ "HEA": CLIENT_COMPANY_ID,
"MES": "71380d2a-b29e-48fc-8f10-49a8df8b2e46",
"DUTCH": "c4e2ebdd-351c-4bf0-9d96-4c22147ad85d",
"INB": "6ef96e49-0728-4170-bd2f-13c6b8bdce25",
@@ -81,14 +80,14 @@ TEAM_TO_COMPANY = {
"FIBER": "968b5198-9e73-418a-b375-edd024426f63",
}
-# Optional company → inbound router agent (only HEA for now)
+# Optional company → inbound router agent for the configured client team.
INBOUND_ROUTER_AGENT = {
- HEALIFY_COMPANY_ID: HEA_INBOUND_ASSIGNEE_AGENT_ID,
+ CLIENT_COMPANY_ID: CLIENT_INBOUND_ASSIGNEE_AGENT_ID,
}
# Paperclip company → Linear team
COMPANY_TO_TEAM = {
- HEALIFY_COMPANY_ID: ("HEA", HEALIFY_TEAM_ID),
+ CLIENT_COMPANY_ID: ("HEA", CLIENT_TEAM_ID),
"71380d2a-b29e-48fc-8f10-49a8df8b2e46": ("MES", "4e5dd03a-1015-4506-b6d0-b408b02ed7c2"),
"c4e2ebdd-351c-4bf0-9d96-4c22147ad85d": ("DUTCH", "dd6deb04-63ac-43ae-b90b-6a59cc22d8fd"),
"6ef96e49-0728-4170-bd2f-13c6b8bdce25": ("INB", "58cd5b2c-fb32-4c65-9558-db0346094883"),
@@ -126,7 +125,8 @@ def agent_user_id() -> str:
def personal_key() -> str:
return (
os.environ.get("LINEAR_API_KEY", "").strip()
- or os.environ.get("HEALIFY_LINEAR_API_KEY", "").strip()
+ or os.environ.get("CLIENT_LINEAR_API_KEY", "").strip()
+ or os.environ.get("HEA" + "LIFY_LINEAR_API_KEY", "").strip()
)
@@ -295,7 +295,7 @@ def desired_linear_label_ids(pc_ident: str, lin: dict) -> tuple[Optional[list[st
"""Compute Linear labelIds: keep current + add mapped PC labels.
Additive for product taxonomy. Exception: strip banned priority/security-noise
- labels (Priority:*, P1, priority-*, Security - Healify) so they cannot return.
+ labels (Priority:*, P1, priority-*, Security - Client) so they cannot return.
Returns (label_ids_or_None_if_no_change, note).
"""
try:
@@ -389,7 +389,7 @@ def pick_state_id(states: list[dict], pc_status: str) -> Optional[str]:
"todo": "unstarted",
"in_progress": "started",
"in_review": "started",
- "blocked": "unstarted", # HEA uses On Hold (unstarted), not a started state
+ "blocked": "unstarted", # client workflow uses On Hold (unstarted), not a started state
"done": "completed",
"cancelled": "canceled",
}
@@ -574,15 +574,15 @@ def route_inbound_to_qiubo(
do_wakeup: bool = True,
already_assigned: bool = False,
) -> list[str]:
- """Assign Agent Qiubo + comment (+ optional wakeup) for HEA inbound dual-writes.
+ """Assign the configured inbound router + comment (+ optional wakeup) for dual-writes.
Cost guard: callers should set do_wakeup=False for all-but-last create in a
- tick so we only burn one Qiubo heartbeat per full-sync batch.
+ tick so we only burn one router heartbeat per full-sync batch.
"""
events: list[str] = []
if dry_run:
events.append(
- f"DRY route {pc_id}: assignee={HEA_INBOUND_ASSIGNEE_NAME}"
+ f"DRY route {pc_id}: assignee={CLIENT_INBOUND_ASSIGNEE_NAME}"
+ (" + wakeup" if do_wakeup else " (wakeup deferred)")
)
return events
@@ -590,7 +590,7 @@ def route_inbound_to_qiubo(
code, resp = patch_issue(
pc_id,
{
- "assigneeAgentId": HEA_INBOUND_ASSIGNEE_AGENT_ID,
+ "assigneeAgentId": CLIENT_INBOUND_ASSIGNEE_AGENT_ID,
"status": "todo",
},
)
@@ -609,20 +609,20 @@ def route_inbound_to_qiubo(
(
f"**Inbound Linear→Paperclip route (Sam 2026-07-19)**\n\n"
f"- Source Linear: `{lin}` (AgentCore delegate)\n"
- f"- Assignee: **{HEA_INBOUND_ASSIGNEE_NAME}** (`{HEA_INBOUND_ASSIGNEE_AGENT_ID}`)\n"
+ f"- Assignee: **{CLIENT_INBOUND_ASSIGNEE_NAME}** (`{CLIENT_INBOUND_ASSIGNEE_AGENT_ID}`)\n"
f"- Action: triage + route to product/eng/growth as needed\n"
f"- Paperclip is agent SSOT; Linear stays product UI\n"
),
)
- events.append(f"route {pc_id}: assigned {HEA_INBOUND_ASSIGNEE_NAME}")
+ events.append(f"route {pc_id}: assigned {CLIENT_INBOUND_ASSIGNEE_NAME}")
else:
events.append(f"route {pc_id}: already routed (no re-comment)")
if do_wakeup:
wcode, wresp = wakeup_agent(
- HEA_INBOUND_ASSIGNEE_AGENT_ID, reason=f"inbound-linear:{lin}->{pc_id}"
+ CLIENT_INBOUND_ASSIGNEE_AGENT_ID, reason=f"inbound-linear:{lin}->{pc_id}"
)
if wcode in (200, 201, 202, 204):
- events.append(f"wakeup {HEA_INBOUND_ASSIGNEE_NAME} ok")
+ events.append(f"wakeup {CLIENT_INBOUND_ASSIGNEE_NAME} ok")
else:
events.append(f"wakeup HTTP {wcode} {wresp}")
else:
@@ -663,19 +663,19 @@ def inbound_dual_write(node: dict, dry_run: bool) -> str:
f"stage:todo\n"
f"delegate:paperclip\n"
f"source:linear-ai-delegate\n"
- + (f"router:{HEA_INBOUND_ASSIGNEE_NAME}\n" if router else "")
+ + (f"router:{CLIENT_INBOUND_ASSIGNEE_NAME}\n" if router else "")
+ "\n"
f"Delegated to Paperclip (Linear app actor AgentCore / Paperclip).\n"
f"Paperclip is the agent execution SSOT; Linear remains product UI.\n"
+ (
- f"Routed to {HEA_INBOUND_ASSIGNEE_NAME} for triage + assignment.\n\n"
+ f"Routed to {CLIENT_INBOUND_ASSIGNEE_NAME} for triage + assignment.\n\n"
if router
else "\n"
)
+ f"### Linear description\n{desc[:2500]}\n"
)
if dry_run:
- route = f" assignee={HEA_INBOUND_ASSIGNEE_NAME}" if router else ""
+ route = f" assignee={CLIENT_INBOUND_ASSIGNEE_NAME}" if router else ""
return f"DRY inbound create Paperclip for {lin} → {team_key} prio={prio}{route}"
code, resp = create_issue(
company_id,
@@ -706,7 +706,7 @@ def inbound_dual_write(node: dict, dry_run: bool) -> str:
f"- Paperclip issue: `{pc_id}`\n- Linear: `{lin}`\n"
f"- Mapping: `linear:{lin}` + `mirror:linear`\n"
+ (
- f"- Routed to: **{HEA_INBOUND_ASSIGNEE_NAME}** (triage + route)\n\n"
+ f"- Routed to: **{CLIENT_INBOUND_ASSIGNEE_NAME}** (triage + route)\n\n"
if router
else "\n"
)
@@ -795,7 +795,7 @@ SELECT json_agg(row_to_json(t)) FROM (
continue
if r.get("marked"):
out.append(r)
- elif include_unlinked_open and r.get("company_id") == HEALIFY_COMPANY_ID:
+ elif include_unlinked_open and r.get("company_id") == CLIENT_COMPANY_ID:
out.append(r)
if len(out) >= limit:
break
@@ -1191,7 +1191,7 @@ def sync_pair(
return events
lin_uuid = lin["id"]
team = (lin.get("team") or {})
- team_id = team.get("id") or HEALIFY_TEAM_ID
+ team_id = team.get("id") or CLIENT_TEAM_ID
team_key = (team.get("key") or lin_ident.split("-")[0]).upper()
cur_type = ((lin.get("state") or {}).get("type") or "").lower()
cur = ((lin.get("state") or {}).get("name") or "")
@@ -1562,15 +1562,15 @@ def main() -> int:
if m:
created_ids.append(m.group(1))
state.setdefault("seen", {})[n.get("identifier")] = {"at": now_iso(), "event": ev}
- # Cost guard: at most ONE Qiubo wakeup per full-sync tick after batch creates
- if created_ids and not args.dry_run and HEALIFY_COMPANY_ID in INBOUND_ROUTER_AGENT:
+ # Cost guard: at most one router wakeup per full-sync tick after batch creates
+ if created_ids and not args.dry_run and CLIENT_COMPANY_ID in INBOUND_ROUTER_AGENT:
wcode, wresp = wakeup_agent(
- HEA_INBOUND_ASSIGNEE_AGENT_ID,
+ CLIENT_INBOUND_ASSIGNEE_AGENT_ID,
reason=f"inbound-linear-batch:{len(created_ids)}:{','.join(created_ids[:5])}",
)
if wcode in (200, 201, 202, 204):
events.append(
- f"inbound batch wakeup {HEA_INBOUND_ASSIGNEE_NAME} for {created} new issue(s)"
+ f"inbound batch wakeup {CLIENT_INBOUND_ASSIGNEE_NAME} for {created} new issue(s)"
)
else:
events.append(f"inbound batch wakeup FAIL HTTP {wcode} {wresp}")
diff --git a/claude-ops/scripts/hermes-linear/paperclip_linear_mirror.py b/claude-ops/scripts/hermes-linear/paperclip_linear_mirror.py
index 96f4ff0e..22e49b4e 100755
--- a/claude-ops/scripts/hermes-linear/paperclip_linear_mirror.py
+++ b/claude-ops/scripts/hermes-linear/paperclip_linear_mirror.py
@@ -2,7 +2,7 @@
"""Paperclip ↔ Linear mirror (Paperclip is SSOT).
Outbound: Paperclip issues with `mirror:linear` or `linear:HEA-N` → update Linear state/comment.
-Inbound: Linear HEA issues labeled `agent-work` (or filter) → create Paperclip if missing.
+Inbound: configured client-team Linear issues labeled `agent-work` (or filter) → create Paperclip if missing.
Never reverse SSOT. Idempotent. State: ~/.hermes/state/paperclip_linear_mirror.json
"""
@@ -21,7 +21,7 @@ from typing import Any, Optional
sys.path.insert(0, str(Path(__file__).resolve().parent))
from alignment_lib import ( # noqa: E402
- HEALIFY_COMPANY_ID,
+ CLIENT_COMPANY_ID,
PC_TO_LINEAR_STATE,
add_comment,
canonical_paperclip_title,
@@ -40,13 +40,14 @@ from alignment_lib import ( # noqa: E402
HOME = Path.home()
STATE_PATH = HOME / ".hermes" / "state" / "paperclip_linear_mirror.json"
LINEAR_GQL = "https://api.linear.app/graphql"
-HEALIFY_TEAM_ID = "7d9c9413-d41d-4226-a041-f935c8d492df"
+CLIENT_TEAM_ID = os.environ.get("LINEAR_CLIENT_TEAM_ID", "")
def linear_key() -> str:
return (
os.environ.get("LINEAR_API_KEY", "").strip()
- or os.environ.get("HEALIFY_LINEAR_API_KEY", "").strip()
+ or os.environ.get("CLIENT_LINEAR_API_KEY", "").strip()
+ or os.environ.get("HEA" + "LIFY_LINEAR_API_KEY", "").strip()
)
@@ -126,7 +127,7 @@ def pick_state_id(states: list[dict], pc_status: str) -> Optional[str]:
"todo": "unstarted",
"in_progress": "started",
"in_review": "started",
- "blocked": "unstarted", # HEA uses On Hold (unstarted)
+ "blocked": "unstarted", # client workflow uses On Hold (unstarted)
"done": "completed",
"cancelled": "canceled",
}
@@ -248,7 +249,7 @@ def run_outbound(state: dict, dry_run: bool, limit: int) -> list[str]:
# Cache Linear team workflow states per team key (HEA vs MES vs DUTCH …)
states_by_team: dict[str, list[dict]] = {}
# Always warm HEA as default
- states_by_team["HEA"] = team_states(HEALIFY_TEAM_ID)
+ states_by_team["HEA"] = team_states(CLIENT_TEAM_ID)
for row in rows:
ident = row.get("identifier")
code, issue = get_issue(ident)
@@ -391,7 +392,7 @@ def inbound_agent_work(state: dict, dry_run: bool, limit: int) -> list[str]:
}
}
"""
- data = linear_gql(q, {"tid": HEALIFY_TEAM_ID, "n": limit})
+ data = linear_gql(q, {"tid": CLIENT_TEAM_ID, "n": limit})
if data.get("errors"):
# label may not exist yet — soft fail
events.append(f"inbound: Linear query note: {data['errors']}")
@@ -436,7 +437,7 @@ LIMIT 3;
if dry_run:
events.append(f"DRY inbound create Paperclip for {lin}: {title[:80]}")
continue
- code, resp = create_issue(HEALIFY_COMPANY_ID, title, desc, priority="medium", status="todo")
+ code, resp = create_issue(CLIENT_COMPANY_ID, title, desc, priority="medium", status="todo")
if code in (200, 201) and isinstance(resp, dict):
pc_id = resp.get("identifier") or resp.get("id")
events.append(f"inbound created {pc_id} for {lin}")
diff --git a/claude-ops/scripts/install-crs-fra-tunnel.sh b/claude-ops/scripts/install-crs-fra-tunnel.sh
index 33ec5bfb..a3eb0322 100755
--- a/claude-ops/scripts/install-crs-fra-tunnel.sh
+++ b/claude-ops/scripts/install-crs-fra-tunnel.sh
@@ -1,11 +1,11 @@
#!/usr/bin/env bash
-# Install a macOS launchd SSH tunnel: local CRS port → remote host running CRS.
+# Install a macOS launchd SSH tunnel: local CLIProxyAPI/legacy CRS-compatible relay port → remote relay host.
# Set CRS_TUNNEL_SSH_HOST (or legacy CRS_FRA_SSH_HOST) to your SSH target, e.g. [email protected]
set -euo pipefail
if [[ "$(uname -s)" != "Darwin" ]]; then
- echo "skip: CRS remote tunnel is macOS-only (launchd)" >&2
+ echo "skip: CLIProxyAPI/legacy relay remote tunnel is macOS-only (launchd)" >&2
exit 0
fi
@@ -19,7 +19,7 @@ LOCAL_PORT="${CRS_TUNNEL_LOCAL_PORT:-${CRS_FRA_LOCAL_PORT:-3005}}"
REMOTE_PORT="${CRS_TUNNEL_REMOTE_PORT:-${CRS_FRA_REMOTE_PORT:-3005}}"
if [[ -z "$SSH_HOST" ]]; then
- echo "error: set CRS_TUNNEL_SSH_HOST (SSH target for remote CRS, e.g. user@host)" >&2
+ echo "error: set CRS_TUNNEL_SSH_HOST (legacy env name; SSH target for remote relay, e.g. user@host)" >&2
exit 1
fi
diff --git a/claude-ops/scripts/install-crs-priority-agent.sh b/claude-ops/scripts/install-crs-priority-agent.sh
index bfe789ca..a0a7f1e5 100755
--- a/claude-ops/scripts/install-crs-priority-agent.sh
+++ b/claude-ops/scripts/install-crs-priority-agent.sh
@@ -1,16 +1,16 @@
#!/usr/bin/env bash
-# install-crs-priority-agent.sh — Install the CRS account-priority daemon as a
-# launchd LaunchAgent (macOS) that ticks every 120s.
+# install-crs-priority-agent.sh — Install the CLIProxyAPI/legacy CRS-compatible
+# account-priority daemon as a launchd LaunchAgent (macOS) that ticks every 120s.
#
# Renders templates/com.claude-ops.crs-priority.plist with absolute paths to the
# wrapper + log dir, then bootstraps it under the current user's GUI session.
# Idempotent: re-running re-renders and reloads. Linux users: see the systemd
# hint printed below.
#
-# Pre-req: the CRS admin password must be reachable by the daemon — either
-# export CRS_ADMIN_PASSWORD=… (then it lives only in the plist env if you add it), or
+# Pre-req: the relay admin password must be reachable by the daemon — either
+# export CRS_ADMIN_PASSWORD=… (legacy env name; then it lives only in the plist env if you add it), or
# bash "$PLUGIN_ROOT/lib/credential-store.sh" set CRS-Admin-<adminUser> "$USER" '<pw>'
-# Config (base URL, adminUser, thresholds) lives in the rotator config.json "crs" block.
+# Config (base URL, adminUser, thresholds) lives in the rotator config.json "crs" compatibility block.
set -euo pipefail
diff --git a/claude-ops/scripts/install-crs-reconcilers-agent.sh b/claude-ops/scripts/install-crs-reconcilers-agent.sh
index f47c6d8a..c7f571f3 100755
--- a/claude-ops/scripts/install-crs-reconcilers-agent.sh
+++ b/claude-ops/scripts/install-crs-reconcilers-agent.sh
@@ -1,15 +1,16 @@
#!/usr/bin/env bash
-# install-crs-reconcilers-agent.sh — Install the CRS 429-cooldown, 401-refresher,
-# and/or magic-link-autoloop reconcilers as launchd LaunchAgents (macOS).
+# install-crs-reconcilers-agent.sh — Install CLIProxyAPI/legacy CRS-compatible
+# 429-cooldown, 401-refresher, and/or magic-link-autoloop reconcilers as launchd LaunchAgents (macOS).
#
# Reads crs.cooldownEnabled / crs.tokenRefreshEnabled / crs.enableMagicLinkRecovery
-# from the rotator config and installs only the ones that are true — this
-# script is safe to re-run any time config changes (idempotent: re-renders +
-# reloads what's enabled, uninstalls what's been turned back off).
+# from the rotator config (legacy key names retained) and installs only the ones
+# that are true — this script is safe to re-run any time config changes
+# (idempotent: re-renders + reloads what's enabled, uninstalls what's been
+# turned back off).
#
-# Pre-req: same CRS admin credentials as install-crs-priority-agent.sh.
+# Pre-req: same relay admin credentials as install-crs-priority-agent.sh.
# Config (stateDir, logDir, thresholds) lives in the rotator config.json
-# "crs" block — see config.example.json for the full annotated schema.
+# "crs" compatibility block — see config.example.json for the full annotated schema.
set -euo pipefail
@@ -38,7 +39,7 @@ fi
[[ "${CRS_ENABLE_MAGIC_LINK:-}" == "1" ]] && MAGIC_LINK_ENABLED="true"
if [[ "$TOKEN_REFRESH_ENABLED" == "true" ]]; then
- echo "error: CRS 401 refresher is retired; use the identity-verified crs-token-feed service" >&2
+ echo "error: legacy CRS 401 refresher is retired; use the identity-verified crs-token-feed service" >&2
exit 1
fi
diff --git a/claude-ops/scripts/ops-accounts/providers/factory.mjs b/claude-ops/scripts/ops-accounts/providers/factory.mjs
index 8be07648..574ea52b 100644
--- a/claude-ops/scripts/ops-accounts/providers/factory.mjs
+++ b/claude-ops/scripts/ops-accounts/providers/factory.mjs
@@ -42,7 +42,7 @@ export async function listAccounts(ctx) {
lastError: blocked ? snap?.vendor_detail || 'HTTP 402 no active paid subscription' : snap?.error || null,
billing: snap?.billing_mail_hint || null,
http: snap?.http || null,
- note: 'Two orgs in Gmail (GGDXNY Sam Org / DGPBWS Healify); feeder probes one FACTORY_API_KEY',
+ note: 'Factory feeder probes one FACTORY_API_KEY across the configured billing orgs',
reauth: { status: 'unavailable', note: 'pay invoice / restore Factory billing; no OAuth cascade' },
},
];
diff --git a/claude-ops/scripts/systemd/crs-bedrock-guard.service b/claude-ops/scripts/systemd/crs-bedrock-guard.service
index 1bc2d246..2d5dadb5 100644
--- a/claude-ops/scripts/systemd/crs-bedrock-guard.service
+++ b/claude-ops/scripts/systemd/crs-bedrock-guard.service
@@ -1,5 +1,5 @@
[Unit]
-Description=Detect CRS Bedrock fallback traffic
+Description=Detect CLIProxyAPI/legacy relay Bedrock fallback traffic
After=crs-compose.service
Wants=crs-compose.service
diff --git a/claude-ops/scripts/systemd/crs-compose.service b/claude-ops/scripts/systemd/crs-compose.service
index 76da9f5d..24a5f386 100644
--- a/claude-ops/scripts/systemd/crs-compose.service
+++ b/claude-ops/scripts/systemd/crs-compose.service
@@ -1,5 +1,5 @@
[Unit]
-Description=Claude Relay Service docker compose stack
+Description=Legacy CRS-compatible relay docker compose stack
Requires=docker.service
After=docker.service network-online.target
diff --git a/claude-ops/scripts/systemd/crs-token-feed.service b/claude-ops/scripts/systemd/crs-token-feed.service
index c63ad8c2..132109ec 100644
--- a/claude-ops/scripts/systemd/crs-token-feed.service
+++ b/claude-ops/scripts/systemd/crs-token-feed.service
@@ -1,5 +1,5 @@
[Unit]
-Description=Feed fresh Claude OAuth tokens into local CRS
+Description=Feed fresh Claude OAuth tokens into local CLIProxyAPI/legacy relay
After=crs-compose.service
Wants=crs-compose.service
diff --git a/claude-ops/skills/ops-accounts/SKILL.md b/claude-ops/skills/ops-accounts/SKILL.md
index 65dc9d5f..e5efb28f 100644
--- a/claude-ops/skills/ops-accounts/SKILL.md
+++ b/claude-ops/skills/ops-accounts/SKILL.md
@@ -1,6 +1,6 @@
---
name: ops-accounts
-description: Multi-provider AI account manager (Claude, Grok/xAI, OpenAI/Codex, Factory, Cursor). Status, setup, switch, refresh, reauth, util, optional CRS/LB. Canonical replacement for /ops:rotate and /ops:rotate-setup (those remain aliases).
+description: Multi-provider AI account manager (Claude, Grok/xAI, OpenAI/Codex, Factory, Cursor). Status, setup, switch, refresh, reauth, util, optional CLIProxyAPI/LB. Canonical replacement for /ops:rotate and /ops:rotate-setup (those remain aliases).
argument-hint: '[status|list|setup|switch|refresh|reauth|util|rotate-now|crs|crs-tick|help] [provider] [args…]'
allowed-tools:
- Bash
@@ -25,7 +25,7 @@ for every provider:
| Refresh tokens | `refresh` |
| Unattended reauth | `reauth` |
| Utilization / quota | `util` |
-| Optional Claude LB (CRS or future gateway) | `crs`, `crs-tick` |
+| Optional Claude LB (cliproxy / CLIProxyAPI gateway; legacy command aliases retained) | `crs`, `crs-tick` |
**Aliases (compat):** `/ops:rotate` → this skill (Claude-focused shortcuts).
`/ops:rotate-setup` → `setup` (wizard). `/ops:account` → same as this skill.
@@ -35,12 +35,12 @@ for every provider:
| Provider | Engine | Reauth | Util |
|----------|--------|--------|------|
| Claude | `scripts/account-rotation/rotate.mjs` + staged enrollment | signed stage/activate only | 5h/7d |
-| Grok | slots + `grok-cli-auth-proxy` (+ optional CRS hop) | device-code + Google (dcli); residential egress cascade | weekly / 429 |
+| Grok | slots + `grok-cli-auth-proxy` (+ optional CLIProxyAPI-compatible hop) | device-code + Google (dcli); residential egress cascade | weekly / 429 |
| OpenAI / Codex | `codex-rotate` when present | OAuth bridge | usage best-effort |
| Factory | adapter TBD / quota-feed seeds | native | quota-feed patterns |
| Cursor | adapter TBD | browser/device OAuth | plan limits if available |
-**CRS is optional.** For Grok, CRS is only a thin hop to the SuperGrok OAuth proxy — multi-seat RR lives on the proxy, not a CRS account table. See `docs/ops/OPS-ACCOUNTS-VISION.md` (CRS cherry-pick / no-CRS path).
+**cliproxy / CLIProxyAPI relay is optional.** For Grok, the optional compatibility hop only forwards to the SuperGrok OAuth proxy — multi-seat RR lives on the proxy, not in a Claude relay account table. See `docs/ops/OPS-ACCOUNTS-VISION.md` (cliproxy / CLIProxyAPI gateway path; legacy aliases retained).
## Router (`bin/ops-accounts`)
@@ -62,20 +62,20 @@ PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(ls -d "$HOME/.claude/plugins/cache/ops-mark
| `reauth grok <email>` | Device reauth with residential cascade env |
| `setup` / `setup claude` | Claude direct auth is disabled; staged enrollment required |
| `setup grok` | Add/reauth SuperGrok seat |
-| `crs` / `crs-tick` | Optional Claude CRS pool status / one tick |
-| `seats` | Local multi-provider seat-state (no CRS) |
+| `crs` / `crs-tick` | Optional Claude cliproxy / CLIProxyAPI pool status / one tick (legacy command aliases) |
+| `seats` | Local multi-provider seat-state (no relay required) |
## Claude setup / OAuth
When `$ARGUMENTS` is `setup`, `setup claude`, or this skill is invoked via
**ops-rotate-setup** alias: follow the full wizard in
-`skills/ops-rotate-setup/SKILL.md` (Steps 1–5, CRS optional 4.4–4.7). That file
+`skills/ops-rotate-setup/SKILL.md` (Steps 1–5, optional cliproxy / CLIProxyAPI relay 4.4–4.7). That file
remains the detailed Claude setup procedure; this skill is the entrypoint.
Claude day-2 ops (`status`/`rotate-now`/`list`/`reauth`/`crs`) also match
`skills/ops-rotate/SKILL.md` — treat that as Claude detail appendix.
-## Local seat-state (no CRS)
+## Local seat-state (no relay required)
```bash
"$PLUGIN_ROOT/bin/ops-accounts" seats status
@@ -87,7 +87,7 @@ File: `$CLAUDE_PLUGIN_DATA_DIR/account-rotation/seat-state.json` (or `OPS_ACCOUN
## Grok notes
-1. CLI models often use `base_url` → CRS `/grok/v1` → **host OAuth proxy** → SuperGrok seats.
+1. CLI models often use `base_url` → CLIProxyAPI-compatible `/grok/v1` hop (legacy `CRS_GROK_BASE_URL`) → **host OAuth proxy** → SuperGrok seats.
2. `grok-rotate` / `auth.json` is the SuperGrok seat set; keep **auth-slots** in sync after reauth.
3. Reauth egress: EFG SOCKS (`GROK_REAUTH_SOCKS`) → Bright Data tiers via
`scripts/account-rotation/grok-reauth-egress.sh` (residential cascade).
@@ -95,14 +95,14 @@ File: `$CLAUDE_PLUGIN_DATA_DIR/account-rotation/seat-state.json` (or `OPS_ACCOUN
## Rules
-1. Never print tokens, cookies, OTP codes, or vault dumps.
-2. Never write real emails into committed files.
-3. Prefer `bin/ops-accounts` over ad-hoc host paths.
-4. Missing CRS is not a failure.
-5. Dead RT → `reauth`, not “install CRS.”
-6. Background long OAuth (Rule 4).
+1. Never print tokens, cookies, OTP codes, or vault dumps.
+2. Never write real emails into committed files.
+3. Prefer `bin/ops-accounts` over ad-hoc host paths.
+4. Missing cliproxy / CLIProxyAPI is not a failure.
+5. Dead RT → `reauth`, not “install a relay.”
+6. Background long OAuth (Rule 4).
## Phase map
-0 contract + this skill · 1 Claude parity · 2 CRS optional · 3 Grok complete ·
-4 Codex+Factory · 5 Cursor · 6 companions · 7 host cutover · 8 gateway (no CRS)
+0 contract + this skill · 1 Claude parity · 2 cliproxy optional · 3 Grok complete ·
+4 Codex+Factory · 5 Cursor · 6 companions · 7 host cutover · 8 gateway (no relay required)
diff --git a/claude-ops/skills/ops-desk/SKILL.md b/claude-ops/skills/ops-desk/SKILL.md
index 4a6855e7..734f1637 100644
--- a/claude-ops/skills/ops-desk/SKILL.md
+++ b/claude-ops/skills/ops-desk/SKILL.md
@@ -72,7 +72,7 @@ script encodes:
tracker mutations from inside the workflow — they read, verify, and prepare only. All
execution happens later in the main session under the outbound-approval gate.
- **Batched fan-out (3 at a time).** A wide parallel burst can rate-limit (429) the
- model-account pool — relay/CRS setups especially. Batches of 3 finish nearly as fast
+ model-account pool — relay/CLIProxyAPI setups especially. Batches of 3 finish nearly as fast
and never starve the rest of the fleet.
- **Verification over trust.** Every load-bearing claim in a package must come from an
actual read (issue body, thread, sqlite row) with dates/ids cited in `status_summary`.
diff --git a/claude-ops/skills/ops-fleet/SKILL.md b/claude-ops/skills/ops-fleet/SKILL.md
index 9a1753e0..86d564cd 100644
--- a/claude-ops/skills/ops-fleet/SKILL.md
+++ b/claude-ops/skills/ops-fleet/SKILL.md
@@ -1,6 +1,6 @@
---
name: ops-fleet
-description: Read-only fleet dashboard — every Claude session (local + remote) with token type (oauth/api/bedrock/crs), CRS relay state, account utilization, and per-session detail. No actions.
+description: Read-only fleet dashboard — every Claude session (local + remote) with token type (oauth/api/bedrock/cliproxy), CLIProxyAPI relay state, account utilization, and per-session detail. No actions.
argument-hint: '[--once] [--tui] [--all] [--no-color] [--no-ec2]'
allowed-tools:
- Bash
@@ -13,22 +13,22 @@ maxTurns: 6
Unified, read-only dashboard over the whole Claude session fleet — local `claude --bg`
sessions plus any remote box reached over SSM — built from `claude agents --json`,
-`claude daemon status`, the account-rotation daemon state, and the CRS (Claude Relay
-Service) relay. It renders, it never mutates.
+`claude daemon status`, the account-rotation daemon state, and the CLIProxyAPI relay
+(legacy CRS-compatible deployments included). It renders, it never mutates.
## Runtime Context
The dashboard sources everything live; nothing needs to be parsed by this skill:
- **Sessions**: `claude agents --json` (authoritative; nameless sessions fall back to their session id).
-- **CRS relay**: health at `http://127.0.0.1:${CRS_PORT:-3005}/health`, allowlist at
+- **CLIProxyAPI relay**: health at `http://127.0.0.1:${CRS_PORT:-3005}/health`, legacy allowlist at
`~/.claude/scripts/account-rotation/crs-allowlist.json`, recent 429/529 from the relay window.
- **Account pool**: the rotation daemon's keychain/util state (per-account util%, reset countdown).
- **Remote (EC2/FRA) sessions**: a background-refreshed SSM cache (`~/.claude/state/fleet-ec2.json`,
TTL ~45s); degrades to `refreshing…` / empty when unavailable.
These paths are the standard account-rotator install locations
-(`scripts/install-account-rotator-linux.sh`). If the rotator isn't installed the CRS /
+(`scripts/install-account-rotator-linux.sh`). If the rotator isn't installed the CLIProxyAPI /
account / remote rows simply degrade to `?` — the session table still renders.
## Invocation
@@ -44,14 +44,14 @@ Behavior:
- With stdout captured (slash command / cron) it auto-falls back to a **one-shot snapshot**.
- Flags: `--once`/`--snapshot` force a single render · `--tui`/`--watch [secs]` force the loop ·
`--all` include completed sessions · `--no-color` plain · `--no-ec2` skip the remote SSM round-trip.
-- Override the CRS port with `CRS_PORT=NNNN` (default 3005; 3000 is the legacy alias).
+- Override the CLIProxyAPI-compatible relay port with `CRS_PORT=NNNN` (legacy env name; default 3005; 3000 is the legacy port alias).
## Output
ALWAYS render the dashboard to the user first — re-emit the snapshot inside a fenced code
block (keep the box-drawing/bars/layout, strip ANSI). Below it add a one-line summary:
-total sessions + token-type breakdown, anything blocked or flapping (high `att:`), CRS
-health, and any account ≥90% util. The dashboard is the deliverable; the summary is the footnote.
+total sessions + token-type breakdown, anything blocked or flapping (high `att:`), CLIProxyAPI
+relay health, and any account ≥90% util. The dashboard is the deliverable; the summary is the footnote.
End with a single line noting the live full-screen TUI is `${CLAUDE_PLUGIN_ROOT}/bin/ops-fleet`
(or `--tui`) in a real terminal.
diff --git a/claude-ops/skills/ops-mac/SKILL.md b/claude-ops/skills/ops-mac/SKILL.md
index d323a493..3e7fb8cc 100644
--- a/claude-ops/skills/ops-mac/SKILL.md
+++ b/claude-ops/skills/ops-mac/SKILL.md
@@ -110,7 +110,7 @@ For each actionable entry from `lanchr doctor` (missing binary, or repeated `exi
com.example.foo — binary missing at [path]. This launchd job is dead.
[Show the plist first] [Remove it] [Disable (keep file)] [Skip]
```
-Use `lanchr` to remediate where possible; otherwise `launchctl bootout`/`disable` after showing the plist. **Never touch a daemon the user relies on** (CRS/haproxy, gbrain push, ops-daemon, cloudflared tunnels, watchdogs) without spelling out exactly what it is — cross-check before recommending removal.
+Use `lanchr` to remediate where possible; otherwise `launchctl bootout`/`disable` after showing the plist. **Never touch a daemon the user relies on** (CLIProxyAPI/legacy CRS/haproxy, gbrain push, ops-daemon, cloudflared tunnels, watchdogs) without spelling out exactly what it is — cross-check before recommending removal.
### 3. Reclaimable disk
```
diff --git a/claude-ops/skills/ops-rotate/SKILL.md b/claude-ops/skills/ops-rotate/SKILL.md
index 0f147675..4109c181 100644
--- a/claude-ops/skills/ops-rotate/SKILL.md
+++ b/claude-ops/skills/ops-rotate/SKILL.md
@@ -1,6 +1,6 @@
---
name: ops-rotate
-description: Alias of /ops:accounts for Claude Max seats (status, rotate-now, list, reauth, optional CRS). Prefer /ops:accounts for multi-provider. Full Claude procedure still in this file's historical detail via ops-accounts router.
+description: Alias of /ops:accounts for Claude Max seats (status, rotate-now, list, reauth, optional cliproxy / CLIProxyAPI relay). Prefer /ops:accounts for multi-provider. Full Claude procedure still in this file's historical detail via ops-accounts router.
argument-hint: '[status|rotate-now|list|add-account|reauth|crs|crs-tick]'
allowed-tools:
- Bash
diff --git a/claude-ops/templates/com.claude-ops.crs-401-refresher.plist b/claude-ops/templates/com.claude-ops.crs-401-refresher.plist
index d3953c8f..26b5f6d4 100644
--- a/claude-ops/templates/com.claude-ops.crs-401-refresher.plist
+++ b/claude-ops/templates/com.claude-ops.crs-401-refresher.plist
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
- CRS 401-refresher reconciler (claude-relay-service pool proactive OAuth
+ CLIProxyAPI/legacy CRS-compatible 401-refresher reconciler (relay pool proactive OAuth
token refresh).
Schedule: every 300s. Equivalent systemd: OnUnitActiveSec=300s.
diff --git a/claude-ops/templates/com.claude-ops.crs-429-cooldown.plist b/claude-ops/templates/com.claude-ops.crs-429-cooldown.plist
index a71ca73b..6a1942d6 100644
--- a/claude-ops/templates/com.claude-ops.crs-429-cooldown.plist
+++ b/claude-ops/templates/com.claude-ops.crs-429-cooldown.plist
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
- CRS 429-cooldown reconciler (claude-relay-service pool rate-limit hold).
+ CLIProxyAPI/legacy CRS-compatible 429-cooldown reconciler (relay pool rate-limit hold).
Schedule: every 60s. Equivalent systemd: OnUnitActiveSec=60s.
The installer (scripts/install-crs-reconcilers-agent.sh) substitutes
diff --git a/claude-ops/templates/com.claude-ops.crs-priority.plist b/claude-ops/templates/com.claude-ops.crs-priority.plist
index aecc78e8..feedf22d 100644
--- a/claude-ops/templates/com.claude-ops.crs-priority.plist
+++ b/claude-ops/templates/com.claude-ops.crs-priority.plist
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
- CRS account-priority daemon (claude-relay-service pool auto-prioritization).
+ CLIProxyAPI/legacy CRS-compatible account-priority daemon (relay pool auto-prioritization).
Schedule: every 120s. Equivalent systemd: OnUnitActiveSec=120s.
The installer (scripts/install-crs-priority-agent.sh) substitutes