An always-on second brain you talk to. Voice notes in Telegram → typed, linked knowledge in your Obsidian vault. Runs 24/7 on the Claude subscription you already have.
Python ai-agentsai-automationclaudeclaude-codeebbinghausknowledge-graphllmmemory-systemobsidianpersonal-assistantpkmproductivitypythonsecond-braintelegram-botvoice-assistant
feat(escape-hatch): RouterSession fallback + claude -p guard
smixsb71ef1cb936d
diff --git a/scripts/check-no-claude-p.sh b/scripts/check-no-claude-p.shnew file mode 100755index 0000000..07869d4--- /dev/null+++ b/scripts/check-no-claude-p.sh@@ -0,0 +1,30 @@+#!/bin/bash+# CI / install guard: fail if `claude -p` / `claude --print` is actually+# INVOKED in the hot path. The only allowed use is the escape hatch, marked+# ALLOW-CLAUDE-P. Prose/comments mentioning "claude -p" are ignored — we look+# for real invocations: a "--print" string literal (Python arg list) or a+# `claude ... --print/-p` command on a non-comment shell line.+set -euo pipefail++ROOT="$(cd "$(dirname "$0")/.." && pwd)"++py_hits="$(grep -rn --include='*.py' '"--print"' "$ROOT/src" \+ | grep -v 'ALLOW-CLAUDE-P' || true)"++sh_hits="$(grep -rnE --include='*.sh' \+ '^[^#]*claude[[:space:]]+[^#]*(--print|[[:space:]]-p([[:space:]]|$))' \+ "$ROOT/scripts" \+ | grep -v 'ALLOW-CLAUDE-P' \+ | grep -v 'check-no-claude-p' || true)"++hits="$(printf '%s\n%s' "$py_hits" "$sh_hits" | grep -v '^$' || true)"++if [ -n "$hits" ]; then+ echo "❌ Found a real claude -p / --print invocation outside the escape hatch:"+ echo "$hits"+ echo+ echo "Use the interactive ClaudeSession instead, or mark the line"+ echo "ALLOW-CLAUDE-P if it is genuinely the router escape hatch."+ exit 1+fi+echo "✅ No claude -p invocation in the hot path."diff --git a/scripts/escape-hatch.sh b/scripts/escape-hatch.shnew file mode 100755index 0000000..85994e4--- /dev/null+++ b/scripts/escape-hatch.sh@@ -0,0 +1,51 @@+#!/bin/bash+# Escape hatch: switch d-brain between the interactive session (subscription)+# and router mode (claude -p against an alternate provider) if Anthropic ever+# closes the interactive path. Reversible.+#+# scripts/escape-hatch.sh on # → router mode (needs a SEPARATE API key)+# scripts/escape-hatch.sh off # → interactive (subscription)+# scripts/escape-hatch.sh status+set -euo pipefail++PROJECT_DIR="$(cd "$(dirname "$0")/.." && pwd)"+ENVF="$PROJECT_DIR/.env"+[ -f "$ENVF" ] || { echo "No .env at $ENVF"; exit 1; }++_set_mode() {+ if grep -q '^DBRAIN_MODE=' "$ENVF"; then+ sed -i.bak "s/^DBRAIN_MODE=.*/DBRAIN_MODE=$1/" "$ENVF" && rm -f "$ENVF.bak"+ else+ echo "DBRAIN_MODE=$1" >> "$ENVF"+ fi+}++_restart() {+ systemctl --user restart dbrain-bot.service 2>/dev/null || true+}++case "${1:-status}" in+ on)+ if ! grep -qE '^ANTHROPIC_BASE_URL=.+' "$ENVF" || ! grep -qE '^ANTHROPIC_AUTH_TOKEN=.+' "$ENVF"; then+ echo "❌ Router mode needs ANTHROPIC_BASE_URL and ANTHROPIC_AUTH_TOKEN in .env."+ echo " This must be a SEPARATE billed API key (NOT your subscription)."+ echo " Get one at: https://console.anthropic.com/ (or your provider)."+ exit 1+ fi+ _set_mode router+ echo "🔀 Router mode ON (claude -p via alternate provider). Restarting bot…"+ _restart+ ;;+ off)+ _set_mode interactive+ echo "🟢 Interactive mode (subscription). Restarting bot…"+ _restart+ ;;+ status)+ grep '^DBRAIN_MODE=' "$ENVF" || echo "DBRAIN_MODE=interactive (default)"+ ;;+ *)+ echo "Usage: escape-hatch.sh <on|off|status>"+ exit 1+ ;;+esacdiff --git a/src/d_brain/services/claude_session.py b/src/d_brain/services/claude_session.pyindex 14bdc5f..52c65e9 100644--- a/src/d_brain/services/claude_session.py+++ b/src/d_brain/services/claude_session.py@@ -360,3 +360,76 @@ class ClaudeSession:# timed out: prompt is still physically in the pane → keep inflightreturn AskResult("timeout", detail=f"no reply in {timeout}s")+++class RouterSession:+ """Escape-hatch fallback: route ask() to ``claude -p`` against an+ ALTERNATE provider via ANTHROPIC_BASE_URL.++ Used ONLY when DBRAIN_MODE=router (Anthropic closed the interactive path).+ Kept as a separate class with the same ask() shape so the interactive+ ClaudeSession stays untouched. Requires a SEPARATE billed API key, not the+ subscription OAuth — reusing the subscription token is exactly what+ Anthropic blocks.+ """++ def __init__(+ self,+ *,+ base_url: str,+ auth_token: str,+ work_dir: Path,+ model: str | None = None,+ claude_bin: str = "claude",+ runner: Runner = subprocess.run,+ ) -> None:+ self.base_url = base_url+ self.auth_token = auth_token+ self.work_dir = Path(work_dir)+ self.model = model+ self.claude_bin = claude_bin+ self._runner = runner++ def ask(+ self,+ prompt: str,+ *,+ timeout: float = DEFAULT_TIMEOUT,+ request_id: str | None = None,+ ) -> AskResult:+ env = os.environ.copy()+ env["ANTHROPIC_BASE_URL"] = self.base_url+ env["ANTHROPIC_AUTH_TOKEN"] = self.auth_token+ cmd = [self.claude_bin, "--print"] # ALLOW-CLAUDE-P: escape hatch only+ cmd += ["--dangerously-skip-permissions"]+ if self.model:+ cmd += ["--model", self.model]+ cmd += ["-p", prompt] # ALLOW-CLAUDE-P: escape hatch only+ try:+ proc = self._runner(+ cmd,+ cwd=str(self.work_dir),+ capture_output=True,+ text=True,+ timeout=timeout,+ check=False,+ env=env,+ )+ except subprocess.TimeoutExpired:+ return AskResult("timeout", detail=f"no reply in {timeout}s")+ if proc.returncode != 0:+ return AskResult("error", detail=(proc.stderr or "").strip())+ return AskResult("ok", reply=(proc.stdout or "").strip())++ # No-op lifecycle methods so callers/watchdog treat it like a session.+ def ensure_session(self) -> None:+ return None++ def is_healthy(self) -> bool:+ return True++ def current_state(self) -> PaneState:+ return PaneState.READY++ def force_recover(self) -> bool:+ return Truediff --git a/src/d_brain/services/runtime.py b/src/d_brain/services/runtime.pyindex 60e85af..ac1178e 100644--- a/src/d_brain/services/runtime.py+++ b/src/d_brain/services/runtime.py@@ -11,7 +11,7 @@ import asyncioimport uuidfrom d_brain.config import Settings-from d_brain.services.claude_session import ClaudeSession+from d_brain.services.claude_session import ClaudeSession, RouterSessionfrom d_brain.services.processor import ClaudeProcessor_session: ClaudeSession | None = None@@ -40,20 +40,31 @@ def _persisted_name(settings: Settings) -> str:return name-def get_session(settings: Settings) -> ClaudeSession:+def get_session(settings: Settings):+ """Return the shared session: interactive ClaudeSession, or RouterSession+ when the escape hatch (DBRAIN_MODE=router) is engaged."""global _session- if _session is None:- project_root = settings.vault_path.parent- mcp = project_root / "mcp-config.json"- brain_prompt = project_root / "deploy" / "brain-system.md"- _session = ClaudeSession(- session_name=_persisted_name(settings),+ if _session is not None:+ return _session+ if settings.dbrain_mode == "router":+ _session = RouterSession(+ base_url=settings.anthropic_base_url,+ auth_token=settings.anthropic_auth_token,work_dir=settings.vault_path,- runtime_dir=settings.runtime_dir,- mcp_config=mcp if mcp.exists() else None,- system_prompt_file=brain_prompt if brain_prompt.exists() else None,model=settings.claude_model or None,)+ return _session+ project_root = settings.vault_path.parent+ mcp = project_root / "mcp-config.json"+ brain_prompt = project_root / "deploy" / "brain-system.md"+ _session = ClaudeSession(+ session_name=_persisted_name(settings),+ work_dir=settings.vault_path,+ runtime_dir=settings.runtime_dir,+ mcp_config=mcp if mcp.exists() else None,+ system_prompt_file=brain_prompt if brain_prompt.exists() else None,+ model=settings.claude_model or None,+ )return _sessiondiff --git a/tests/test_claude_session.py b/tests/test_claude_session.pyindex 80c54a0..c4bb873 100644--- a/tests/test_claude_session.py+++ b/tests/test_claude_session.py@@ -255,3 +255,41 @@ def test_kill_sends_kill_session(tmp_path, clock):s = make_session(tmp_path, fake, clock)s.kill()assert "kill-session" in fake.sent_subcommands()+++# ── RouterSession (escape hatch) ──────────────────────────────────────────+++def test_router_session_uses_claude_p_with_provider_env(tmp_path):+ from d_brain.services.claude_session import RouterSession++ captured = {}++ def runner(cmd, **kwargs):+ captured["cmd"] = cmd+ captured["env"] = kwargs.get("env", {})+ return subprocess.CompletedProcess(cmd, 0, stdout="hi there\n", stderr="")++ r = RouterSession(+ base_url="https://provider.example",+ auth_token="secret",+ work_dir=tmp_path,+ runner=runner,+ )+ res = r.ask("hello")+ assert res.ok+ assert res.reply == "hi there"+ assert "--print" in captured["cmd"]+ assert captured["env"]["ANTHROPIC_BASE_URL"] == "https://provider.example"+ assert captured["env"]["ANTHROPIC_AUTH_TOKEN"] == "secret"+++def test_router_session_error_on_nonzero(tmp_path):+ from d_brain.services.claude_session import RouterSession++ def runner(cmd, **kwargs):+ return subprocess.CompletedProcess(cmd, 1, stdout="", stderr="boom")++ r = RouterSession(base_url="u", auth_token="k", work_dir=tmp_path, runner=runner)+ res = r.ask("x")+ assert res.status == "error"diff --git a/tests/test_runtime.py b/tests/test_runtime.pyindex 41713ee..dad6606 100644--- a/tests/test_runtime.py+++ b/tests/test_runtime.py@@ -44,3 +44,16 @@ def test_explicit_session_name_used(tmp_path):rt.reset()s = _settings(tmp_path, brain_session_name="dbrain_fixed")assert rt.get_session(s).session_name == "dbrain_fixed"+++def test_router_mode_returns_router_session(tmp_path):+ from d_brain.services.claude_session import RouterSession++ rt.reset()+ s = _settings(+ tmp_path,+ dbrain_mode="router",+ anthropic_base_url="https://provider.example",+ anthropic_auth_token="key",+ )+ assert isinstance(rt.get_session(s), RouterSession)