Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(brain): add the Anthropic subscription brain
Ruben Lütkec10b3264f8b6
diff --git a/jarvis/plugins/brain/claude_cli.py b/jarvis/plugins/brain/claude_cli.pynew file mode 100644index 0000000000..73fb2ac9c8--- /dev/null+++ b/jarvis/plugins/brain/claude_cli.py@@ -0,0 +1,356 @@+"""Anthropic subscription brain — drives the ``claude`` CLI in print mode.++Jarvis already spends two subscriptions this way: ChatGPT through ``codex exec``+and Google through the Gemini CLI. Anthropic was the gap. The only Anthropic+brain was ``claude-api``, billed per token, so a user whose sole Anthropic+credential is a Claude plan could not spend it on brain work at all — and the+Agentic IDE's prompt composer, which needs a capable model or nothing, fell back+to its deterministic regex prompt on every single instruction for them.++This is deliberately NOT a voice-tier brain. Measured 2026-07-26 on a warm+machine: 10-12 s for a trivial prompt (essentially all process start-up) and+26.6 s for a real structured brief on the fastest model. Either number would+destroy a spoken turn. It exists for callers that are already waiting seconds+and whose OUTPUT is the product rather than a step towards it — and any caller+wiring this up needs a deadline well clear of 30 s, not the 45 s that sufficed+when only API providers wrote briefs.++Two shapes, one provider, chosen by the caller through ``structured_prompts``:++* **Conversational** (default) — a light "answer in a sentence or three" wrapper+ with the recent turns, mirroring the Codex sibling. The heavy router system+ prompt is dropped on purpose: it is large, tool-heavy, and misleading for a+ read-only CLI call.+* **Structured** — the caller's ``system`` IS the contract, so it rides in+ ``--system-prompt`` and the payload goes to stdin untouched. Claude Code takes+ a real system prompt, which makes this cleaner here than in the siblings that+ have to flatten everything into one blob.++Getting that choice wrong is the failure mode worth guarding: a structured+caller served conversationally gets three fluent sentences that read like a+valid result. Nobody inspects an answer that looks fine.+"""+from __future__ import annotations++import asyncio+import logging+import shutil+import sys+import tempfile+import time+from collections.abc import AsyncIterator+from contextlib import suppress++from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS+from jarvis.core.protocols import BrainDelta, BrainRequest++from .cli_prompt_context import (+ extract_reply_language_directive,+ render_cli_standing_instructions,+ render_structured_prompt,+)++log = logging.getLogger(__name__)++# Hard cap for a single turn. Higher than the Codex sibling's 90 s because this+# provider's whole reason to exist is long-form work a caller is waiting on;+# callers with a tighter budget pass their own ``cli_timeout_s``.+_CLI_TIMEOUT_S: float = 120.0++# How often the run loop yields an empty delta while waiting. The caller's+# no-progress watchdog resets on any delta, so a silent 20 s await would look+# like a stalled provider and lose the turn to a fallback (the Codex sibling hit+# exactly that).+_TICK_S: float = 3.0++# Binary name with Windows shim variants. ``shutil.which`` honours PATHEXT, so+# the bare name usually resolves; the variants cover installs where only the+# ``.cmd`` shim is on PATH.+_BINARY_CANDIDATES: tuple[str, ...] = ("claude", "claude.cmd", "claude.exe")++# Tools refused on this path. The brain answers in text; it must not be able to+# touch the filesystem or run commands even if a prompt talks it into trying.+# Read-only tools are deliberately left available: a caller may legitimately ask+# the model to look something up, and forbidding those buys nothing.+_DISALLOWED_TOOLS: tuple[str, ...] = ("Bash", "Edit", "Write", "NotebookEdit")++_CLI_SYSTEM = (+ "You are Jarvis, a concise and friendly voice assistant. Answer the user's "+ "message directly in one to three short sentences. Reply in plain text only "+ "— do not run any commands, do not read or edit files, do not use tools."+)++# How many recent turns ride along on the conversational path. Every token is+# slow here, so older history is dropped rather than paid for.+_CONVO_TURNS = 6+++def _resolve_claude_binary() -> str | None:+ """On-PATH ``claude`` binary (Windows shim variants included), or None."""+ for name in _BINARY_CANDIDATES:+ path = shutil.which(name)+ if path:+ return path+ return None+++def _claude_subscription_connected() -> bool:+ """True when a Claude subscription login is present. Never raises.++ Best-effort by design: this runs for every candidate the resolver considers,+ and a probe that raised would kill a turn that should merely have skipped one+ provider. A missing CLI, an unreadable credential store, or a host with no+ keychain all degrade to False.+ """+ try:+ from jarvis.claude_auth import ClaudeAuthService++ status = ClaudeAuthService().status()+ return bool(getattr(status, "connected", False))+ except Exception: # noqa: BLE001 - a probe degrades, never raises+ log.debug("claude-cli: subscription probe failed", exc_info=True)+ return False+++class ClaudeCliBrain:+ """Brain backed by the Claude CLI running on a subscription login."""++ name: str = "claude-cli"+ context_window: int = 200_000+ # Static capability flags stay at the honest value for THIS path: the print+ # -mode CLI hands us text, never tool calls, and never sees an image. A+ # hopeful True here would have BrainManager route a tool turn or a+ # Computer-Use screenshot to a brain that cannot serve it (AP-21).+ supports_tools: bool = False+ supports_vision: bool = False++ def __init__(+ self,+ model: str | None = None,+ structured_prompts: bool = False,+ cli_timeout_s: float | None = None,+ ) -> None:+ # No model default: an unset model means "the CLI's own default for this+ # account's plan". Hardcoding an id here would break every user whose+ # plan does not carry it (AP-21).+ self._model = (model or "").strip() or None+ self._structured_prompts = bool(structured_prompts)+ try:+ budget = float(cli_timeout_s) if cli_timeout_s is not None else 0.0+ except (TypeError, ValueError):+ budget = 0.0+ self.cli_timeout_s = budget if budget > 0 else _CLI_TIMEOUT_S++ # ---- capabilities -------------------------------------------------++ def can_call_tools(self) -> bool:+ """Runtime tool-calling capability — always False on this path.++ The caller (``BrainManager``) uses this to delegate a tool turn to a+ genuinely tool-capable provider instead of letting a text-only brain+ confabulate a refusal that reads like "the model chose no tool".+ """+ return False++ @staticmethod+ def subscription_connected() -> bool:+ """Whether this provider's subscription login is usable right now.++ The resolver asks the provider class rather than importing an auth+ service per family, so a subscription brain added later answers for+ itself with no resolver edit.+ """+ return _claude_subscription_connected()++ # ---- invocation ----------------------------------------------------++ def build_invocation(self, req: BrainRequest) -> tuple[list[str], str]:+ """The argv and the stdin payload for one turn.++ Pure and public because this pair — not the subprocess plumbing — is+ what decides whether the answer comes back in the right shape, and that+ is the property worth testing directly.+ """+ binary = _resolve_claude_binary() or "claude"+ argv: list[str] = [binary, "-p", "--output-format", "text"]+ if self._model:+ argv += ["--model", self._model]+ argv += ["--disallowed-tools", *_DISALLOWED_TOOLS]++ if self._structured_prompts:+ system = str(getattr(req, "system", "") or "").strip()+ if system:+ argv += ["--system-prompt", system]+ # The contract already rides in argv; sending it on stdin too+ # would duplicate it and dilute the payload it governs.+ payload = "\n\n".join(+ str(message.content).strip()+ for message in (req.messages or ())+ if getattr(message, "role", "") in ("system", "user")+ and isinstance(getattr(message, "content", None), str)+ and str(message.content).strip()+ )+ return argv, payload or render_structured_prompt(req)+ return argv, render_structured_prompt(req)++ lines: list[str] = [_CLI_SYSTEM, ""]+ prefs = render_cli_standing_instructions(req.system)+ convo = [+ message+ for message in req.messages+ if getattr(message, "role", None) in ("user", "assistant")+ and isinstance(getattr(message, "content", None), str)+ ][-_CONVO_TURNS:]+ for message in convo:+ speaker = "User" if message.role == "user" else "Assistant"+ lines.append(f"{speaker}: {message.content}")+ if prefs:+ lines.extend(["", prefs])+ # The reply-language directive rides LAST (highest recency) so the CLI+ # model answers in the turn's resolved language instead of anchoring to+ # the persona's own language — the sibling bug of 2026-06-21.+ directive = extract_reply_language_directive(req.system)+ if directive:+ lines.extend(["", directive])+ lines.append("Assistant:")+ return argv, "\n".join(lines)++ # ---- run loop ------------------------------------------------------++ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:+ """Run one CLI turn on the subscription and yield its answer."""+ if _resolve_claude_binary() is None:+ raise RuntimeError(+ "Claude CLI not found — install it from https://claude.ai/download "+ "and run 'claude' once to sign in."+ )++ argv, prompt = self.build_invocation(req)+ # A throwaway working directory: this brain answers questions and has no+ # business seeing, or being trusted in, the user's repository.+ workdir = tempfile.mkdtemp(prefix="jarvis-claude-brain-")+ creationflags = NO_WINDOW_CREATIONFLAGS if sys.platform == "win32" else 0++ log.info(+ "claude-cli: spawning print-mode turn (model=%s, structured=%s, "+ "prompt=%d chars)",+ self._model or "<cli default>",+ self._structured_prompts,+ len(prompt),+ )++ t0 = time.monotonic()+ try:+ proc = await asyncio.create_subprocess_exec(+ *argv,+ cwd=workdir,+ stdin=asyncio.subprocess.PIPE,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ creationflags=creationflags,+ )+ except (FileNotFoundError, OSError) as exc:+ shutil.rmtree(workdir, ignore_errors=True)+ log.warning("claude-cli: spawn failed: %s", exc)+ raise RuntimeError(f"Claude CLI could not be launched: {exc}") from exc++ try:+ assert proc.stdin is not None # noqa: S101 - PIPE is always present+ proc.stdin.write(prompt.encode("utf-8"))+ await proc.stdin.drain()+ proc.stdin.close()+ except (BrokenPipeError, ConnectionResetError):+ # The CLI died before reading; the empty-answer path below reports it+ # with whatever stderr explains, which beats a bare pipe error.+ pass++ comm_task = asyncio.create_task(proc.communicate())+ deadline = t0 + self.cli_timeout_s+ stdout_bytes = b""+ stderr_bytes = b""++ async def _kill() -> None:+ if not comm_task.done():+ comm_task.cancel()+ pid = getattr(proc, "pid", None)+ if sys.platform == "win32" and isinstance(pid, int) and pid > 0:+ # The Node shim spawns children; killing only the shim leaves+ # them running and holding the pipes open.+ with suppress(Exception): # noqa: BLE001+ killer = await asyncio.create_subprocess_exec(+ "taskkill",+ "/PID",+ str(pid),+ "/T",+ "/F",+ stdout=asyncio.subprocess.DEVNULL,+ stderr=asyncio.subprocess.DEVNULL,+ creationflags=creationflags,+ )+ await asyncio.wait_for(killer.wait(), timeout=3.0)+ with suppress(OSError):+ proc.kill()+ with suppress(Exception): # noqa: BLE001+ await asyncio.wait_for(proc.wait(), timeout=3.0)+ with suppress(asyncio.CancelledError, Exception):+ await comm_task++ try:+ while True:+ slice_timeout = min(_TICK_S, deadline - time.monotonic())+ if slice_timeout <= 0:+ raise TimeoutError+ done, _pending = await asyncio.wait({comm_task}, timeout=slice_timeout)+ if done:+ stdout_bytes, stderr_bytes = comm_task.result()+ break+ # Empty progress tick: nothing visible, but it keeps the caller's+ # no-progress deadline alive through the cold start.+ yield BrainDelta(content="")+ except asyncio.CancelledError:+ await _kill()+ log.info("claude-cli: cancelled (killed)")+ raise+ except TimeoutError as exc:+ await _kill()+ log.warning(+ "claude-cli: no answer within %.0fs (killed)", self.cli_timeout_s+ )+ raise RuntimeError(+ f"Claude CLI did not answer within {self.cli_timeout_s:.0f}s."+ ) from exc+ finally:+ shutil.rmtree(workdir, ignore_errors=True)++ answer = stdout_bytes.decode("utf-8", errors="replace").strip()+ elapsed = time.monotonic() - t0+ if not answer:+ detail = stderr_bytes.decode("utf-8", errors="replace").strip()[:300]+ log.warning(+ "claude-cli: empty answer after %.1fs rc=%s detail=%s",+ elapsed,+ proc.returncode,+ detail[:200],+ )+ raise RuntimeError(+ "Claude CLI returned no answer" + (f": {detail}" if detail else ".")+ )++ log.info(+ "claude-cli turn ok: %d chars in %.1fs on the subscription",+ len(answer),+ elapsed,+ )+ yield BrainDelta(content=answer)+ yield BrainDelta(finish_reason="stop")++ def estimate_cost(self, req: BrainRequest) -> float:+ """Zero: this path bills against a subscription, not per token.++ Reporting a per-token estimate here would make cost-aware callers avoid+ the one provider that costs them nothing extra.+ """+ return 0.0+++__all__ = ["ClaudeCliBrain"]diff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.pyindex cb29bdc9b6..d6e24ec49f 100644--- a/jarvis/ui/web/provider_spec.py+++ b/jarvis/ui/web/provider_spec.py@@ -11,7 +11,7 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Literal-AuthMode = Literal["api_key", "codex", "antigravity", "none"]+AuthMode = Literal["api_key", "codex", "antigravity", "claude_cli", "none"]Tier = Literal["brain", "tts", "stt", "realtime"]# How using a provider is billed. Derived from auth_mode (never branched on a# provider name — see provider_billing): an API key bills per token on an API@@ -92,7 +92,8 @@ def provider_billing(spec: ProviderSpec) -> Billing:"""How using *spec* is billed — capability-driven, never name-branched(multi-provider mandate, AP-21).- * a subscription-login provider (``codex``/``antigravity``) that ALSO carries+ * a subscription-login provider (``codex``/``antigravity``/``claude-cli``)+ that ALSO carriesan API-key slot → ``"subscription_or_api"`` (a plan login OR per-token key);one with no key slot → ``"subscription"``. The distinction is the presenceof ``secret_keys``, not the provider name — so adding a key slot to either@@ -100,7 +101,7 @@ def provider_billing(spec: ProviderSpec) -> Billing:* ``none`` → ``"local"`` — no credential, runs on-device.* everything else (``api_key``) → ``"api"`` — pay per token on an API account."""- if spec.auth_mode in ("antigravity", "codex"):+ if spec.auth_mode in ("antigravity", "codex", "claude_cli"):return "subscription_or_api" if spec.secret_keys else "subscription"if spec.auth_mode == "none":return "local"@@ -253,6 +254,33 @@ PROVIDERS: tuple[ProviderSpec, ...] = ("API key to bill per token instead."),),+ # ── Brain: Anthropic subscription via the official Claude CLI ──+ # Sibling of the Codex/Antigravity subscription paths: spends a Claude plan+ # login instead of a per-token Anthropic key. No secret_keys slot — the+ # per-token path for this family already exists as ``claude-api``, and+ # duplicating it here would present the same key twice.+ #+ # ``brain_switchable=False`` is not a formality: process start-up alone is+ # ~10-12 s, which would destroy a spoken turn, so this must never become an+ # install's main conversational brain.+ ProviderSpec(+ id="claude-cli",+ label="Claude (Anthropic subscription)",+ tier="brain",+ auth_mode="claude_cli",+ secret_keys=(),+ dashboard_url=None,+ login_cli=("claude", "/login"),+ install_hint="curl -fsSL https://claude.ai/install.sh | bash",+ credential_path_hint="~/.claude/.credentials.json",+ brain_switchable=False,+ signup_url="https://claude.ai",+ credential_help=(+ "Write Agentic IDE task briefs over your Claude subscription via the "+ "Claude Code CLI — sign in below, no API key needed. Too slow to "+ "start for spoken replies, so it is not offered as a voice brain."+ ),+ ),ProviderSpec(id="nvidia",label="NVIDIA NIM",diff --git a/pyproject.toml b/pyproject.tomlindex b37200d028..b5304d12e6 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -415,6 +415,10 @@ openai = "jarvis.plugins.brain.openai:OpenAIBrain"gemini = "jarvis.plugins.brain.gemini:GeminiBrain"codex = "jarvis.plugins.brain.codex:CodexBrain"antigravity = "jarvis.plugins.brain.antigravity:AntigravityBrain"+# Anthropic subscription (Claude CLI, print mode). Sibling of codex/antigravity:+# spends a plan login instead of a per-token key. Too slow to start (~10-12 s)+# for a voice tier; it serves callers whose OUTPUT is the product.+claude-cli = "jarvis.plugins.brain.claude_cli:ClaudeCliBrain"grok = "jarvis.plugins.brain.grok:GrokBrain"# Keyless LOCAL providers (2026-07-25, local-first mandate): both talk to# self-hosted servers and are deliberately absent fromdiff --git a/tests/unit/plugins/brain/test_claude_cli_brain.py b/tests/unit/plugins/brain/test_claude_cli_brain.pynew file mode 100644index 0000000000..e86bbba238--- /dev/null+++ b/tests/unit/plugins/brain/test_claude_cli_brain.py@@ -0,0 +1,104 @@+"""ClaudeCliBrain — the Anthropic subscription (CLI) brain.++The invocation builder is pure on purpose: what this brain gets wrong is not+"the subprocess failed" but "the answer came back in the wrong SHAPE", and shape+is decided entirely by argv plus the stdin payload. Testing that pair directly+catches the failure that matters without spawning a CLI.+"""+from __future__ import annotations++import pytest++from jarvis.core.protocols import BrainMessage, BrainRequest+from jarvis.plugins.brain.claude_cli import ClaudeCliBrain+++def _req(system: str = "CONTRACT", user: str = "payload") -> BrainRequest:+ return BrainRequest(+ messages=(BrainMessage(role="user", content=user),),+ system=system,+ max_tokens=8000,+ stream=True,+ )+++def test_structured_mode_forwards_the_system_contract_verbatim() -> None:+ """A structured caller's system prompt IS the product and must survive.++ Without this the CLI wrapper replaces the contract with "answer in one to+ three short sentences", which returns a plausible non-brief — the invisible+ degradation this whole provider exists to avoid.+ """+ brain = ClaudeCliBrain(structured_prompts=True)+ argv, prompt = brain.build_invocation(_req(system="WRITE A BRIEF", user="do X"))+ assert "WRITE A BRIEF" in " ".join(argv) or "WRITE A BRIEF" in prompt+ assert "do X" in prompt+++def test_conversational_mode_does_not_leak_the_router_prompt() -> None:+ """A voice turn stays short and never carries the heavy tool prompt."""+ brain = ClaudeCliBrain(structured_prompts=False)+ _argv, prompt = brain.build_invocation(+ _req(system="ROUTER PROMPT WITH TOOLS", user="hello")+ )+ assert "ROUTER PROMPT WITH TOOLS" not in prompt+ assert "hello" in prompt+++def test_invocation_disables_tools_and_pins_print_mode() -> None:+ """The brain answers; it must not be able to edit files or run commands."""+ brain = ClaudeCliBrain(structured_prompts=True)+ argv, _prompt = brain.build_invocation(_req())+ assert "-p" in argv or "--print" in argv+ joined = " ".join(argv)+ assert "--disallowed-tools" in joined or "--allowed-tools" in joined+++def test_model_is_only_passed_when_configured() -> None:+ """No model id is hardcoded (AP-21) — the CLI's own default wins."""+ default_argv, _ = ClaudeCliBrain().build_invocation(_req())+ assert "--model" not in default_argv+ pinned_argv, _ = ClaudeCliBrain(model="haiku").build_invocation(_req())+ assert "--model" in pinned_argv+ assert "haiku" in pinned_argv+++def test_cli_timeout_override_is_honoured() -> None:+ """A slow background caller may buy more time than the voice-tier cap."""+ assert ClaudeCliBrain(cli_timeout_s=300).cli_timeout_s == pytest.approx(300.0)+ assert ClaudeCliBrain().cli_timeout_s > 0+ # A nonsense value falls back to the default rather than disabling the cap.+ assert ClaudeCliBrain(cli_timeout_s=0).cli_timeout_s > 0+ assert ClaudeCliBrain(cli_timeout_s="nonsense").cli_timeout_s > 0 # type: ignore[arg-type]+++def test_tool_turns_are_refused_not_confabulated() -> None:+ """The CLI path cannot emit tool calls; saying so lets the manager delegate."""+ assert ClaudeCliBrain().can_call_tools() is False+ assert ClaudeCliBrain().supports_vision is False+++def test_subscription_probe_never_raises(monkeypatch: pytest.MonkeyPatch) -> None:+ """The resolver calls this on every candidate; an exception there would kill+ a turn that should merely have skipped one provider."""++ def _explode() -> object:+ raise OSError("no keychain on this host")++ monkeypatch.setattr(+ "jarvis.claude_auth.ClaudeAuthService", lambda *a, **k: _explode()+ )+ assert ClaudeCliBrain.subscription_connected() is False+++async def test_complete_raises_a_clear_error_when_the_cli_is_absent(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A headless host with no CLI gets an actionable message, never a hang."""+ monkeypatch.setattr(+ "jarvis.plugins.brain.claude_cli._resolve_claude_binary", lambda: None+ )+ brain = ClaudeCliBrain(structured_prompts=True)+ with pytest.raises(RuntimeError, match="Claude CLI"):+ async for _delta in brain.complete(_req()):+ pass