Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.
Shell agent-teamsai-agentai-automationanthropicautonomous-agentawsbusiness-operationsclaudeclaude-codeclaude-code-plugindevopsecommerceinbox-zeroklaviyomarketingmcpmorning-briefingpr-automationshopifyterminal
feat(ops-accounts): gateway skeleton on clean main (#736)
Aurora Capital18cbbe9e8f8d
diff --git a/claude-ops/CHANGELOG.md b/claude-ops/CHANGELOG.mdindex 7e378f45..3eeff771 100644--- a/claude-ops/CHANGELOG.md+++ b/claude-ops/CHANGELOG.md@@ -1,5 +1,6 @@## Unreleased+- ops-accounts-gateway skeleton (:3005 health/auth/grok hop; CLI gateway subcommand)- feat(crs-priority-daemon): dual-mode `backend=crs|local` file seat-state without CRS Docker# Changelogdiff --git a/claude-ops/bin/ops-accounts b/claude-ops/bin/ops-accountsindex 82c4e2e3..781516ad 100755--- a/claude-ops/bin/ops-accounts+++ b/claude-ops/bin/ops-accounts@@ -236,6 +236,50 @@ case "$cmd" inecho "seat-state.mjs missing"; exit 1fi;;++ gateway)+ sub="${1:-status}"+ GW="${ROT}/ops-accounts-gateway.mjs"+ GW_PORT="${OPS_ACCOUNTS_GATEWAY_PORT:-3005}"+ GW_HOST="${OPS_ACCOUNTS_GATEWAY_HOST:-127.0.0.1}"+ case "$sub" in+ status)+ if curl -fsS -m 2 "http://${GW_HOST}:${GW_PORT}/health" 2>/dev/null; then+ echo+ else+ echo "ops-accounts-gateway not listening on ${GW_HOST}:${GW_PORT}"+ echo "start: ops-accounts gateway start"+ [[ -f "$GW" ]] && echo "plugin binary: $GW" || echo "plugin gateway missing"+ exit 1+ fi+ ;;+ start)+ if [[ ! -f "$GW" ]]; then+ echo "missing $GW"; exit 1+ fi+ if curl -fsS -m 1 "http://${GW_HOST}:${GW_PORT}/health" >/dev/null 2>&1; then+ echo "already listening on ${GW_HOST}:${GW_PORT}"+ exit 0+ fi+ nohup node "$GW" >>"${TMPDIR:-/tmp}/ops-accounts-gateway.log" 2>&1 &+ echo "started pid=$! log=${TMPDIR:-/tmp}/ops-accounts-gateway.log url=http://${GW_HOST}:${GW_PORT}"+ echo "migrate: CRS_BASE_URL → OPS_ACCOUNTS_GATEWAY_URL=http://${GW_HOST}:${GW_PORT}"+ ;;+ path)+ echo "$GW"+ ;;+ self-test)+ node "$GW" --self-test+ ;;+ config)+ node "$GW" --print-config+ ;;+ *)+ echo "usage: ops-accounts gateway status|start|path|self-test|config"; exit 2+ ;;+ esac+ ;;+-h|--help|help)cat <<Hops-accounts — multi-provider seats (canonical; /ops:rotate is alias)diff --git a/claude-ops/docs/ops/OPS-ACCOUNTS-GATEWAY.md b/claude-ops/docs/ops/OPS-ACCOUNTS-GATEWAY.mdnew file mode 100644index 00000000..3644a4dc--- /dev/null+++ b/claude-ops/docs/ops/OPS-ACCOUNTS-GATEWAY.md@@ -0,0 +1,59 @@+# ops-accounts-gateway++**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.++## What it does (skeleton)++| Route / job | Backend |+|-------------|---------|+| `GET /health`, `/v1/health` | Local JSON: seat-state path, picked Claude seat, grok proxy URL |+| `GET /v1/models` | Stub model list |+| `GET /accounts` | Schedulable seats from file seat-state (no secrets) |+| `/grok/*`, `/v1/images/*` | Forward to plugin `grok-cli-auth-proxy` (`GROK_PROXY_URL`, default `:31845`) |+| `POST /v1/chat/completions`, `/v1/messages` | Pick schedulable Claude seat; optional `CLAUDE_UPSTREAM_URL` forward; else **501** with seat id until vault OAuth hop lands |+| API key gate | `OPS_ACCOUNTS_GATEWAY_KEY` → Bearer / `x-api-key` / `api-key` (open if unset) |+| State | File seat-state only — **no Redis** |++## What it must not do++- Admin SPA, multi-tenant product UI+- Grafana / Prometheus stack by default+- Require Docker+- Re-implement Grok seat table inside Claude account rows++## CLI++```bash+ops-accounts gateway status|start|path|self-test|config+node scripts/account-rotation/ops-accounts-gateway.mjs --self-test+```++Env: `OPS_ACCOUNTS_GATEWAY_HOST` (127.0.0.1), `OPS_ACCOUNTS_GATEWAY_PORT` (3005),+`OPS_ACCOUNTS_GATEWAY_KEY`, `OPS_ACCOUNTS_STATE_PATH`, `GROK_PROXY_URL`,+`CLAUDE_UPSTREAM_URL`.++## Migration++```+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.++## Build order++1. Dual backend policy + seat-state (**done** in ops-accounts local-backend PR)+2. Plugin Grok proxy (**done**)+3. Gateway skeleton (**this**) — health, auth, grok hop, Claude seat pick + 501+4. Claude vault OAuth hop (next) — wire seat → access token → Anthropic/OpenAI upstream+5. Harness matrix update (`docs/ops` CLI path matrix) — `CRS_BASE_URL` → `OPS_ACCOUNTS_GATEWAY_URL`++## License++If any line is copied from CRS (MIT), keep attribution. Prefer rewrite of the+proxy surface over vendoring the monorepo.diff --git a/claude-ops/scripts/account-rotation/__tests__/ops-accounts-gateway.test.mjs b/claude-ops/scripts/account-rotation/__tests__/ops-accounts-gateway.test.mjsnew file mode 100644index 00000000..bca57684--- /dev/null+++ b/claude-ops/scripts/account-rotation/__tests__/ops-accounts-gateway.test.mjs@@ -0,0 +1,50 @@+/**+ * Unit tests: ops-accounts-gateway classify / seat pick / auth (no listen).+ */+import {+ classifyRoute,+ pickSchedulableSeat,+ authorize,+ extractApiKey,+} from '../ops-accounts-gateway.mjs';++function assert(cond, msg) {+ if (!cond) throw new Error(msg || 'assert failed');+}++assert(classifyRoute('GET', '/health').kind === 'health', 'health');+assert(classifyRoute('GET', '/v1/health').kind === 'health', 'v1 health');+assert(classifyRoute('GET', '/v1/models').kind === 'models', 'models');+assert(classifyRoute('POST', '/grok/v1/chat/completions').kind === 'grok-proxy', 'grok path');+assert(classifyRoute('POST', '/v1/images/generations').kind === 'grok-proxy', 'images → grok');+assert(classifyRoute('POST', '/v1/chat/completions').kind === 'claude', 'chat');+assert(classifyRoute('POST', '/v1/messages').kind === 'claude', 'messages');+assert(classifyRoute('GET', '/v1/unknown-thing').kind === 'openai-passthrough', 'passthrough');+assert(classifyRoute('GET', '/nope').kind === 'unknown', 'unknown');++const state = {+ providers: {+ claude: {+ seats: {+ '[email protected]': { schedulable: false, util5h: 99 },+ '[email protected]': { schedulable: true, util5h: 5 },+ '[email protected]': {+ schedulable: true,+ exhaustedUntil: new Date(Date.now() + 3600_000).toISOString(),+ },+ },+ },+ },+};+const pick = pickSchedulableSeat(state, 'claude');+assert(pick?.email === '[email protected]', `picked ${pick?.email}`);+assert(pickSchedulableSeat({ providers: {} }, 'claude') === null, 'empty');++assert(authorize({ headers: {} }, '').ok === true, 'open');+assert(authorize({ headers: {} }, 'k').ok === false, 'missing');+assert(authorize({ headers: { authorization: 'Bearer k' } }, 'k').ok === true, 'bearer');+assert(authorize({ headers: { 'x-api-key': 'k' } }, 'k').ok === true, 'x-api-key');+assert(authorize({ headers: { authorization: 'Bearer wrong' } }, 'k').ok === false, 'bad');+assert(extractApiKey({ headers: { 'api-key': 'z' } }) === 'z', 'api-key header');++console.log('ops-accounts-gateway.test.mjs: ok');diff --git a/claude-ops/scripts/account-rotation/ops-accounts-gateway.mjs b/claude-ops/scripts/account-rotation/ops-accounts-gateway.mjsnew file mode 100644index 00000000..3f3dbf48--- /dev/null+++ b/claude-ops/scripts/account-rotation/ops-accounts-gateway.mjs@@ -0,0 +1,422 @@+#!/usr/bin/env node+/**+ * ops-accounts-gateway.mjs — thin optional OpenAI-compat gateway (no CRS).+ *+ * Skeleton (Phase D):+ * - GET /health, /v1/health+ * - GET /v1/models (stub inventory)+ * - * /v1/* Grok paths → plugin grok-cli-auth-proxy (:31845)+ * - POST /v1/chat/completions | /v1/messages → Claude seat pick + stub upstream+ * - API key gate via OPS_ACCOUNTS_GATEWAY_KEY (optional in dev)+ *+ * State: file seat-state only. No Redis. No admin SPA.+ *+ * Env:+ * OPS_ACCOUNTS_GATEWAY_PORT default 3005 (CRS-compat port)+ * OPS_ACCOUNTS_GATEWAY_HOST default 127.0.0.1+ * OPS_ACCOUNTS_GATEWAY_KEY if set, require Bearer / x-api-key / api-key+ * OPS_ACCOUNTS_STATE_PATH seat-state.json path+ * GROK_PROXY_URL default http://127.0.0.1:31845+ * CLAUDE_UPSTREAM_URL optional Anthropic-compat base (not required for health)+ *+ * Usage:+ * node ops-accounts-gateway.mjs # listen+ * node ops-accounts-gateway.mjs --self-test # pure checks, exit+ * node ops-accounts-gateway.mjs --print-config+ */+import http from 'http';+import { readFileSync, existsSync } from 'fs';+import { join } from 'path';+import { homedir } from 'os';+import { fileURLToPath } from 'url';++const HOST = process.env.OPS_ACCOUNTS_GATEWAY_HOST || '127.0.0.1';+const PORT = Number(process.env.OPS_ACCOUNTS_GATEWAY_PORT || '3005');+const GATEWAY_KEY = process.env.OPS_ACCOUNTS_GATEWAY_KEY || '';+const GROK_PROXY_URL = (process.env.GROK_PROXY_URL || 'http://127.0.0.1:31845').replace(/\/$/, '');+const CLAUDE_UPSTREAM_URL = (process.env.CLAUDE_UPSTREAM_URL || '').replace(/\/$/, '');+const DATA =+ process.env.CLAUDE_PLUGIN_DATA_DIR || join(homedir(), '.claude', 'plugins', 'data', 'ops-ops-marketplace');+const STATE_PATH =+ process.env.OPS_ACCOUNTS_STATE_PATH || join(DATA, 'account-rotation', 'seat-state.json');++export function loadSeatState(path = STATE_PATH) {+ if (!existsSync(path)) {+ return { version: 1, updatedAt: null, providers: {}, path, missing: true };+ }+ try {+ const raw = JSON.parse(readFileSync(path, 'utf8'));+ return { version: 1, providers: {}, ...raw, path, missing: false };+ } catch (err) {+ return { version: 1, updatedAt: null, providers: {}, path, missing: true, error: String(err) };+ }+}++/** Pick first schedulable seat for provider (stable email sort for determinism). */+export function pickSchedulableSeat(state, provider = 'claude') {+ const seats = state?.providers?.[provider]?.seats || {};+ const emails = Object.keys(seats).sort();+ for (const email of emails) {+ const s = seats[email];+ if (s && s.schedulable === false) continue;+ if (s?.exhaustedUntil) {+ const until = Date.parse(s.exhaustedUntil);+ if (!Number.isNaN(until) && until > Date.now()) continue;+ }+ return { email, seat: s || {} };+ }+ return null;+}++export function classifyRoute(method, urlPath) {+ const path = (urlPath || '/').split('?')[0] || '/';+ if (path === '/health' || path === '/v1/health') return { kind: 'health', path };+ if (path === '/v1/models' || path === '/models') return { kind: 'models', path };+ if (path === '/accounts' || path === '/v1/accounts') return { kind: 'accounts', path };+ // Grok hop: anything mentioning grok, or xAI-shaped image routes often used via CRS+ if (/\/grok(\/|$)/i.test(path) || path.startsWith('/v1/images') || path.startsWith('/images')) {+ return { kind: 'grok-proxy', path };+ }+ if (+ (method === 'POST' || method === 'OPTIONS') &&+ (path === '/v1/chat/completions' ||+ path === '/chat/completions' ||+ path === '/v1/messages' ||+ path === '/messages' ||+ path === '/v1/responses' ||+ path === '/responses')+ ) {+ return { kind: 'claude', path };+ }+ if (path.startsWith('/v1/') || path === '/v1') return { kind: 'openai-passthrough', path };+ return { kind: 'unknown', path };+}++export function extractApiKey(req) {+ const h = req.headers || {};+ const auth = h.authorization || h.Authorization || '';+ if (typeof auth === 'string' && auth.toLowerCase().startsWith('bearer ')) {+ return auth.slice(7).trim();+ }+ const x = h['x-api-key'] || h['api-key'] || h['x-api-key'.toLowerCase()];+ if (typeof x === 'string' && x.trim()) return x.trim();+ return '';+}++export function authorize(req, key = GATEWAY_KEY) {+ if (!key) return { ok: true, reason: 'open' };+ const got = extractApiKey(req);+ if (!got) return { ok: false, reason: 'missing_key' };+ if (got !== key) return { ok: false, reason: 'bad_key' };+ return { ok: true, reason: 'matched' };+}++function sendJson(res, status, body) {+ const raw = JSON.stringify(body);+ res.writeHead(status, {+ 'content-type': 'application/json; charset=utf-8',+ 'content-length': Buffer.byteLength(raw),+ 'cache-control': 'no-store',+ });+ res.end(raw);+}++function readBody(req, limit = 8 * 1024 * 1024) {+ return new Promise((resolve, reject) => {+ const chunks = [];+ let n = 0;+ req.on('data', (c) => {+ n += c.length;+ if (n > limit) {+ reject(new Error('body too large'));+ req.destroy();+ return;+ }+ chunks.push(c);+ });+ req.on('end', () => resolve(Buffer.concat(chunks)));+ req.on('error', reject);+ });+}++async function proxyToGrok(req, res, urlPath) {+ const target = new URL(urlPath, GROK_PROXY_URL);+ // Map CRS-style /grok/v1/... → proxy /v1/...+ let p = target.pathname;+ p = p.replace(/^\/grok(?=\/|$)/i, '');+ if (!p.startsWith('/v1') && p !== '/health' && p !== '/accounts') {+ if (p === '/' || p === '') p = '/health';+ else if (!p.startsWith('/')) p = '/' + p;+ }+ const dest = `${GROK_PROXY_URL}${p}${target.search || ''}`;+ let body = null;+ if (req.method !== 'GET' && req.method !== 'HEAD') {+ body = await readBody(req);+ }+ const headers = { ...req.headers };+ delete headers.host;+ delete headers['content-length'];+ const upstream = await fetch(dest, {+ method: req.method,+ headers,+ body: body && body.length ? body : undefined,+ }).catch((err) => ({ ok: false, status: 502, _err: err }));+ if (upstream._err) {+ sendJson(res, 502, {+ error: {+ message: `grok proxy unreachable at ${GROK_PROXY_URL}: ${upstream._err.message}`,+ type: 'gateway_error',+ },+ });+ return;+ }+ const buf = Buffer.from(await upstream.arrayBuffer());+ const outHeaders = { 'content-type': upstream.headers.get('content-type') || 'application/json' };+ res.writeHead(upstream.status, outHeaders);+ res.end(buf);+}++function handleHealth(res) {+ const state = loadSeatState();+ const claude = pickSchedulableSeat(state, 'claude');+ sendJson(res, 200, {+ ok: true,+ service: 'ops-accounts-gateway',+ version: 1,+ port: PORT,+ seatState: {+ path: state.path,+ missing: !!state.missing,+ updatedAt: state.updatedAt || null,+ claudeSchedulable: claude ? claude.email : null,+ },+ grokProxy: GROK_PROXY_URL,+ claudeUpstream: CLAUDE_UPSTREAM_URL || null,+ apiKeyRequired: Boolean(GATEWAY_KEY),+ mode: 'skeleton',+ });+}++function handleModels(res) {+ sendJson(res, 200, {+ object: 'list',+ data: [+ { id: 'claude-ops-gateway', object: 'model', owned_by: 'ops-accounts' },+ { id: 'grok-via-proxy', object: 'model', owned_by: 'ops-accounts' },+ ],+ });+}++function handleAccounts(res) {+ const state = loadSeatState();+ const out = {};+ for (const [provider, blob] of Object.entries(state.providers || {})) {+ const seats = blob.seats || {};+ out[provider] = Object.fromEntries(+ Object.entries(seats).map(([email, s]) => [+ email,+ {+ schedulable: s.schedulable !== false,+ util5h: s.util5h ?? null,+ util7d: s.util7d ?? null,+ exhaustedUntil: s.exhaustedUntil ?? null,+ },+ ]),+ );+ }+ sendJson(res, 200, {+ backend: 'local-seat-state',+ path: state.path,+ missing: !!state.missing,+ providers: out,+ });+}++async function handleClaude(req, res, route) {+ if (req.method === 'OPTIONS') {+ res.writeHead(204, {+ 'access-control-allow-origin': '*',+ 'access-control-allow-headers': 'authorization, content-type, x-api-key, api-key',+ 'access-control-allow-methods': 'POST, OPTIONS',+ });+ res.end();+ return;+ }+ const state = loadSeatState();+ const picked = pickSchedulableSeat(state, 'claude');+ if (!picked) {+ sendJson(res, 503, {+ error: {+ message:+ 'no schedulable Claude seat in seat-state; run ops-accounts seats import-claude-config or seats set',+ type: 'no_capacity',+ },+ });+ return;+ }+ // Skeleton: do not invent OAuth vault reads here. Either forward to CLAUDE_UPSTREAM_URL+ // (operator-supplied Anthropic-compat) or return 501 with the chosen seat so harnesses+ // can prove routing without CRS.+ let bodyBuf = Buffer.alloc(0);+ try {+ bodyBuf = await readBody(req);+ } catch (err) {+ sendJson(res, 413, { error: { message: String(err.message || err), type: 'payload_error' } });+ return;+ }+ if (CLAUDE_UPSTREAM_URL) {+ const dest = `${CLAUDE_UPSTREAM_URL}${route.path.startsWith('/v1') ? route.path : '/v1' + route.path}`;+ const headers = { ...req.headers, host: undefined };+ delete headers.host;+ const upstream = await fetch(dest, {+ method: 'POST',+ headers,+ body: bodyBuf,+ }).catch((err) => ({ _err: err }));+ if (upstream._err) {+ sendJson(res, 502, {+ error: { message: `claude upstream failed: ${upstream._err.message}`, type: 'gateway_error' },+ });+ return;+ }+ const buf = Buffer.from(await upstream.arrayBuffer());+ res.writeHead(upstream.status, {+ 'content-type': upstream.headers.get('content-type') || 'application/json',+ 'x-ops-accounts-seat': picked.email,+ });+ res.end(buf);+ return;+ }+ sendJson(res, 501, {+ error: {+ message:+ 'ops-accounts-gateway skeleton: Claude vault OAuth hop not wired yet. Seat selected; set CLAUDE_UPSTREAM_URL for temporary forward, or wait for vault hop PR.',+ type: 'not_implemented',+ seat: picked.email,+ route: route.path,+ },+ });+}++export function createServer() {+ return http.createServer(async (req, res) => {+ try {+ const url = new URL(req.url || '/', `http://${HOST}:${PORT}`);+ const route = classifyRoute(req.method || 'GET', url.pathname);++ if (route.kind === 'health') {+ handleHealth(res);+ return;+ }++ const auth = authorize(req);+ if (!auth.ok) {+ sendJson(res, 401, {+ error: { message: `unauthorized (${auth.reason})`, type: 'auth_error' },+ });+ return;+ }++ if (route.kind === 'models') {+ handleModels(res);+ return;+ }+ if (route.kind === 'accounts') {+ handleAccounts(res);+ return;+ }+ if (route.kind === 'grok-proxy') {+ await proxyToGrok(req, res, url.pathname + url.search);+ return;+ }+ if (route.kind === 'claude') {+ await handleClaude(req, res, route);+ return;+ }+ if (route.kind === 'openai-passthrough') {+ sendJson(res, 404, {+ error: {+ message: `no handler for ${route.path} in skeleton gateway (use /v1/chat/completions, /v1/messages, /grok/v1/*, /health)`,+ type: 'not_found',+ },+ });+ return;+ }+ sendJson(res, 404, {+ error: { message: `unknown path ${route.path}`, type: 'not_found' },+ });+ } catch (err) {+ sendJson(res, 500, {+ error: { message: String(err?.message || err), type: 'internal_error' },+ });+ }+ });+}++function selfTest() {+ const routeH = classifyRoute('GET', '/health');+ if (routeH.kind !== 'health') throw new Error('health classify');+ const routeG = classifyRoute('POST', '/grok/v1/chat/completions');+ if (routeG.kind !== 'grok-proxy') throw new Error('grok classify');+ const routeC = classifyRoute('POST', '/v1/chat/completions');+ if (routeC.kind !== 'claude') throw new Error('claude classify');+ const state = {+ providers: {+ claude: {+ seats: {+ '[email protected]': { schedulable: false },+ '[email protected]': { schedulable: true },+ },+ },+ },+ };+ const pick = pickSchedulableSeat(state, 'claude');+ if (!pick || pick.email !== '[email protected]') throw new Error('pick seat');+ const authOpen = authorize({ headers: {} }, '');+ if (!authOpen.ok) throw new Error('open auth');+ const authBad = authorize({ headers: {} }, 'secret');+ if (authBad.ok) throw new Error('should require key');+ const authOk = authorize({ headers: { authorization: 'Bearer secret' } }, 'secret');+ if (!authOk.ok) throw new Error('bearer ok');+ console.log('ops-accounts-gateway self-test: ok');+}++function printConfig() {+ console.log(+ JSON.stringify(+ {+ host: HOST,+ port: PORT,+ statePath: STATE_PATH,+ grokProxy: GROK_PROXY_URL,+ claudeUpstream: CLAUDE_UPSTREAM_URL || null,+ apiKeyRequired: Boolean(GATEWAY_KEY),+ },+ null,+ 2,+ ),+ );+}++function main(argv = process.argv.slice(2)) {+ if (argv.includes('--self-test')) {+ selfTest();+ return;+ }+ if (argv.includes('--print-config')) {+ printConfig();+ return;+ }+ const server = createServer();+ server.listen(PORT, HOST, () => {+ console.log(+ `ops-accounts-gateway listening on http://${HOST}:${PORT} (seat-state=${STATE_PATH}; grok=${GROK_PROXY_URL})`,+ );+ });+}++const isMain =+ process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1];+if (isMain) {+ main();+}