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(bedrock-guard): configurable hook to halt agents billing AWS Bedrock (#595)
Aurora Capitala571fd903673
diff --git a/claude-ops/docs/safety-hooks.md b/claude-ops/docs/safety-hooks.mdindex 1be6f44f..a9840418 100644--- a/claude-ops/docs/safety-hooks.md+++ b/claude-ops/docs/safety-hooks.md@@ -115,3 +115,34 @@ bash claude-ops/tests/test-safety-hooks.sh- [`docs/deploy-fix.md`](deploy-fix.md) — auto-fix subsystem (independent of safety hooks).- [`docs/agents.md`](agents.md) — specialized agent system.- [`docs/INDEX.md`](INDEX.md) — full documentation index.++## 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+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.++**How it knows.** A PreToolUse hook runs as a child of the session's node process,+so it inherits the live `process.env` — including a runtime-injected+`CLAUDE_CODE_USE_BEDROCK=1` (the literal billing flag). That env var *is* the+measurement; there is no false positive. It also honors a daemon-written offender+flag (`/tmp/claude-bedrock-offender-<short-session-id>`) from the watchdog's+network/env measurement.++**Behavior — configurable via `CLAUDE_BEDROCK_GUARD`** (or `~/.claude/bedrock-guard.conf`):++| mode | effect |+|------|--------|+| `block` (default) | Hard-block **every** tool call (exit 2) with a loud `$$$` error. Dismiss only by explicit acknowledgement: run `echo BEDROCK-ACK`. This is the only way to proceed while still on Bedrock (the legitimate no-OAuth last-resort case). |+| `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+error, missing input, or unexpected state allows the tool (a money guard must+never wedge an innocent session).++**Disable / make unrestricted:** set `CLAUDE_BEDROCK_GUARD=off` in the environment,+or `echo off > ~/.claude/bedrock-guard.conf`.diff --git a/claude-ops/hooks/bedrock-billing-guard.mjs b/claude-ops/hooks/bedrock-billing-guard.mjsnew file mode 100644index 00000000..444b43f7--- /dev/null+++ b/claude-ops/hooks/bedrock-billing-guard.mjs@@ -0,0 +1,134 @@+#!/usr/bin/env node+// PreToolUse guard — hard-block any agent MEASURED to be billing AWS Bedrock,+// until it EXPLICITLY acknowledges. Owner directive (2026-06-15): "notify the+// agent with an error hook only dismissable on explicit ok, to the agent that+// is measured to be sending aws bedrock calls or using bedrock tokens."+//+// Why this works: a PreToolUse hook is spawned as a child of the Claude session+// node process, so it INHERITS the session's live process.env — including a+// runtime-injected CLAUDE_CODE_USE_BEDROCK=1 (the literal per-token billing+// flag). That env var IS the measurement: if it's set, this session's model+// calls are hitting metered Bedrock right now. Zero false positives. We also+// honor a daemon-written offender flag (the rotation watchdog's network/env+// measurement) keyed by the short session id, as a second trigger.+//+// Dismiss = EXPLICIT OK: run a Bash command containing the sentinel BEDROCK-ACK.+// The hook recognizes it, records the ack, and stops blocking. This is the only+// way to proceed while still on Bedrock (the legitimate last-resort case where+// zero OAuth headroom exists and the watchdog cannot swap). When OAuth IS+// available the watchdog respawns the session off Bedrock within ~45s and clears+// the flag, so the block lifts on its own — no ack needed for a non-problem.+//+// FAIL-OPEN: any error, missing input, or unexpected state → exit 0 (allow).+// A money guard must never wedge an innocent session.++import { readFileSync, existsSync, writeFileSync } from 'fs';+import { homedir } from 'os';+import { join } from 'path';++function allow() {+ process.exit(0);+}++// ── Configurable mode (claude-ops templatable) ────────────────────────────────+// Decide how strict the guard is. Resolution order (first wins):+// 1. env CLAUDE_BEDROCK_GUARD (block | warn | off)+// 2. ~/.claude/bedrock-guard.conf (single word, same values)+// 3. default → "block" (safe: protect spend by default)+// Modes:+// block — hard-block every tool (exit 2) until explicit `echo BEDROCK-ACK`.+// warn — never block; inject a non-blocking warning into the agent's context.+// off — no-op. For users who intentionally run Bedrock unrestricted.+function guardMode() {+ const norm = (v) => {+ const s = String(v || '')+ .trim()+ .toLowerCase();+ return s === 'off' || s === 'warn' || s === 'block' ? s : '';+ };+ const env = norm(process.env.CLAUDE_BEDROCK_GUARD);+ if (env) return env;+ try {+ const f = norm(readFileSync(join(homedir(), '.claude', 'bedrock-guard.conf'), 'utf8'));+ if (f) return f;+ } catch {}+ return 'block';+}++const MODE = guardMode();+if (MODE === 'off') allow(); // unrestricted Bedrock — guard disabled by config++let input = {};+try {+ input = JSON.parse(readFileSync(0, 'utf8'));+} catch {+ allow(); // no/garbled hook input → never block+}++const sidFull = String((input && input.session_id) || '');+const sid8 = sidFull ? sidFull.slice(0, 8) : '';+const tool = (input && input.tool_name) || '';+const cmd = (input && input.tool_input && (input.tool_input.command || '')) || '';++// ── Is THIS session billing Bedrock? ──────────────────────────────────────────+// (a) own inherited runtime env (authoritative — the actual billing flag), and+// (b) daemon offender flag from the watchdog's measurement (short-id keyed).+const envBedrock = process.env.CLAUDE_CODE_USE_BEDROCK === '1';+const offenderFile = sid8 ? `/tmp/claude-bedrock-offender-${sid8}` : '';+const flagged = !!offenderFile && existsSync(offenderFile);+const onBedrock = envBedrock || flagged;++if (!onBedrock) allow(); // not on metered Bedrock → allow everything, silently++const ackFile = sid8 ? `/tmp/claude-bedrock-ack-${sid8}` : '';++// ── Explicit OK: a Bash call carrying the BEDROCK-ACK sentinel dismisses ───────+if (tool === 'Bash' && /BEDROCK-ACK/.test(cmd)) {+ try {+ if (ackFile) writeFileSync(ackFile, String(Date.now()));+ } catch {}+ allow(); // permit the acknowledging command itself+}++// Already acknowledged this session → allow (agent chose to proceed knowingly).+if (ackFile && existsSync(ackFile)) allow();++// ── Block: loud, money-focused error fed back to the agent on EVERY tool call ──+let detail = '';+try {+ if (flagged) {+ const j = readFileSync(offenderFile, 'utf8').trim();+ if (j) detail = `\nWatchdog measurement: ${j.slice(0, 220)}`;+ }+} catch {}++// warn mode: surface it loudly but never block — just inject context, exit 0.+if (MODE === 'warn') {+ const warn =+ `⚠️💸 BEDROCK BILLING: this session${sid8 ? ` (${sid8})` : ''} is making metered AWS Bedrock ` ++ `model calls (real $$$, not the Max/CRS pool).${detail} The rotation watchdog should swap you ` ++ `to CRS/OAuth shortly. (bedrock-guard mode=warn — not blocking.)`;+ try {+ process.stdout.write(+ JSON.stringify({+ hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: warn },+ }),+ );+ } catch {}+ process.exit(0);+}++// block mode (default): hard-block every tool until explicit acknowledgement.+const msg =+ `🛑🔥 METERED AWS BEDROCK BILLING DETECTED on THIS session${sid8 ? ` (${sid8})` : ''}.\n` ++ `Every model call you make is spending REAL $$$ on AWS Bedrock per-token billing — ` ++ `NOT the free Max/CRS account pool. This is the opposite of intended routing.${detail}\n` ++ `\nALL tool calls are BLOCKED until you acknowledge. The rotation watchdog will normally ` ++ `swap you to CRS/OAuth within ~45s and this clears automatically. If it does NOT clear, ` ++ `there is no OAuth headroom and Bedrock is the only option.\n` ++ `\nTo acknowledge and continue ANYWAY (knowingly on metered Bedrock), run exactly:\n` ++ ` echo BEDROCK-ACK\n` ++ `This error re-fires on every tool call until you acknowledge.`;++process.stderr.write(msg + '\n');+process.exit(2); // PreToolUse: exit 2 → block the tool, stderr becomes the reason to the modeldiff --git a/claude-ops/hooks/hooks.json b/claude-ops/hooks/hooks.jsonindex 0bc08a87..b8b2e663 100644--- a/claude-ops/hooks/hooks.json+++ b/claude-ops/hooks/hooks.json@@ -59,6 +59,16 @@"async": true}]+ },+ {+ "matcher": "*",+ "hooks": [+ {+ "type": "command",+ "command": "node ${CLAUDE_PLUGIN_ROOT}/hooks/bedrock-billing-guard.mjs",+ "timeout": 5+ }+ ]}],"PostToolUse": [diff --git a/claude-ops/scripts/account-rotation/bedrock-watchdog.mjs b/claude-ops/scripts/account-rotation/bedrock-watchdog.mjsindex 2aa5725e..f8182376 100644--- a/claude-ops/scripts/account-rotation/bedrock-watchdog.mjs+++ b/claude-ops/scripts/account-rotation/bedrock-watchdog.mjs@@ -13,7 +13,7 @@// fatal, and the network corroboration layer (scanBedrockNetwork) degrades to// a graceful "unknown" rather than ever false-alarming.-import { readFileSync, readdirSync, existsSync } from 'fs';+import { readFileSync, readdirSync, existsSync, writeFileSync, unlinkSync } from 'fs';import { execFileSync } from 'child_process';import { listLiveBgSessions, doRespawn } from './bg-respawn.mjs';@@ -306,6 +306,31 @@ function buildPpidMap() {return m;}+// ── Per-session offender flag (drives the PreToolUse bedrock-billing-guard) ────+// The guard hook keys off `session_id.slice(0,8)`, which equals the bg-session+// short id (jobId = first 8 hex of the session UUID). Writing this flag makes a+// session MEASURED on Bedrock get a blocking error in its OWN loop (dismissable+// only by explicit `echo BEDROCK-ACK`). Cleared once the session is swapped off.+const OFFENDER_FLAG = (shortId) => `/tmp/claude-bedrock-offender-${shortId}`;+function offenderShortId(sessionId) {+ const s = String(sessionId || '');+ return s ? s.slice(0, 8) : '';+}+function writeOffenderFlag(sessionId, via) {+ const shortId = offenderShortId(sessionId);+ if (!shortId) return;+ try {+ writeFileSync(OFFENDER_FLAG(shortId), `measured via ${via || 'env'} by rotation watchdog — metered AWS Bedrock`);+ } catch {}+}+function clearOffenderFlag(sessionId) {+ const shortId = offenderShortId(sessionId);+ if (!shortId) return;+ try {+ unlinkSync(OFFENDER_FLAG(shortId));+ } catch {}+}+/*** Is this session protected by a hot-swap hold marker?* (touch /tmp/claude-hotswap-hold-<pid> — see memory hotswap-hold-protection)@@ -365,16 +390,24 @@ export function sweepBedrockSessions(config, state, log) {const swappedPids = [];for (const sess of sessions) {+ const bgSession = byPid.get(sess.pid);++ // Flag the MEASURED session so its own PreToolUse bedrock-billing-guard fires+ // (the agent gets a blocking error it must explicitly ack). Written for every+ // measured Bedrock session — including the no-OAuth last-resort case below,+ // where the agent stays on Bedrock and must consciously acknowledge the spend.+ if (bgSession) writeOffenderFlag(bgSession.id, sess.via);+// Is an OAuth account actually available? pickAccountForSession returns// 'bedrock' only when ZERO accounts have a usable token (true last resort).- const sid = sess.sessionId || (byPid.get(sess.pid) && byPid.get(sess.pid).id) || `pid-${sess.pid}`;+ const sid = sess.sessionId || (bgSession && bgSession.id) || `pid-${sess.pid}`;const target = pickAccountForSession(sid, config, state);if (!target || target === 'bedrock') {- // No OAuth headroom anywhere — Bedrock is the legitimate fallback. Leave it.+ // No OAuth headroom anywhere — Bedrock is the legitimate fallback. Leave it+ // (and leave the offender flag so the agent's guard makes it ack the spend).continue;}- const bgSession = byPid.get(sess.pid);if (!bgSession) {// Bedrock claude PID with no resolvable bg-session record — can't respawn// it by id (could be a foreground/--resume host). Log loudly; skip.@@ -408,9 +441,14 @@ export function sweepBedrockSessions(config, state, log) {log(`[bedrock-watchdog] FORCE-swapping ${bgSession.id} (pid ${sess.pid}, status ${bgSession.status}, via ${viaDetail}) Bedrock→OAuth ${target} (no defer — metered)`,);- doRespawn(bgSession, log);- swapped++;- swappedPids.push(sess.pid);+ if (doRespawn(bgSession, log)) {+ // Swapped off Bedrock — clear the offender flag so the respawned (clean)+ // session's guard hook stops blocking. (If the swap fails, the flag stays+ // and the agent must ack.)+ clearOffenderFlag(bgSession.id);+ swapped++;+ swappedPids.push(sess.pid);+ }} catch (e) {log(`[bedrock-watchdog] force-swap of ${bgSession.id} failed: ${e.message?.slice(0, 100)}`);}