Skip to content

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.

fix(agent-runtimes): run Claude subscription agents through the official Claude CLI (#856)

Ruben Lütke07367e8c8cf7
diff --git a/docs/agent-runtimes.md b/docs/agent-runtimes.md
index 03c3ae00be..8856f17d82 100644
--- a/docs/agent-runtimes.md
+++ b/docs/agent-runtimes.md
@@ -89,10 +89,10 @@ call with its own provider plugins (`gateway.py`,
(the Agents-tier key wins, as for Dodaios' own agents), a local server with
an address, or Vertex AI on a Google Cloud project without a key. The
runtimes can use the providers listed in `model_map._ENDPOINTS`; a new
- provider plugin needs an entry there too. A way of paying that exists but
- is refused right now (a Claude login whose Extra Usage is off or spent) is
- reported in `access_blocked` on `/api/agent-runtimes` with its reason code,
- so the dialog shows it disabled.
+ provider plugin needs an entry there too. The Claude subscription is
+ offered when Claude Code is installed and signed in to a Claude plan
+ (`claude auth status`); `login_providers` and `access_blocked` on
+ `/api/agent-runtimes` stay empty for older clients.
- **Keys and logins stay in Dodaios.** The runtime gets a per-agent token
(`jrg_…`, process environment only); `SurfaceSecurity` accepts it on
`/api/runtime-gateway/` and nowhere else. Hermes finds it again on session
@@ -133,11 +133,10 @@ call with its own provider plugins (`gateway.py`,
runtimes read as "compress and resend"), 504 `timeout` ("took too long",
not "not reachable"), 503 `provider_unreachable` / `provider_overloaded`,
404 `model_not_found`, 400 `tools_unsupported` / `invalid_tool_schema` /
- `invalid_request`, 401 `provider_auth` / `claude_login_expired`, 429
+ `invalid_request`, 401 `provider_auth`, 409 `claude_cli_only`, 429
`rate_limited` with a cooldown, 502 `provider_error`. Only the codes no
runtime can recover from end the Dodaios turn at once
- (`provider_errors.TERMINAL_CODES`: billing, Extra Usage, refused key or
- login, unknown model, tool refusals, rate limit); an overflow, a timeout or
+ (`provider_errors.TERMINAL_CODES`: billing, refused key, unknown model, tool refusals, rate limit); an overflow, a timeout or
an overloaded provider goes back to the runtime's own retry and
compression.
- **Costs.** Every gateway call is metered into the cost ledger (caller
@@ -172,25 +171,37 @@ call with its own provider plugins (`gateway.py`,
offers (from the account's catalog, no inference), and a `system` or
`developer` input message moves into the instructions, which ChatGPT's
backend requires.
-- **Claude subscription: billed as extra usage.** Claude runs on an
- Anthropic API key when one is saved. Without one, the gateway answers on
- the person's live Claude Code login (read-only: only the Claude CLI renews
- it, so an expired login fails with `claude_login_expired` and says to open
- Claude Code once). Anthropic bills
- a subscription used outside Claude Code as extra usage, not from the plan's
- limits, so the model picker labels that seat "billed as extra usage"
- (`login_providers` on `/api/agent-runtimes`). A Claude login (`sk-ant-oat…`)
- saved in the Anthropic API-key slot is never sent as an API key.
- Measured 2026-10-07: Anthropic serves a subscription to Hermes and
- OpenClaw only from the account's Extra Usage ("Third-party apps now draw
- from your extra usage, not your plan limits", HTTP 400; Sonnet, Opus and
- Fable sometimes answer a bare 429 instead), for every model including
- Haiku. Before the runtime starts, `route_for` reads the account's usage
- report (`/api/oauth/usage`, no inference, cached two minutes) and refuses
- the turn at once when Extra Usage is off or its monthly limit is spent;
- a refusal that still arrives is reported as 402 with the same reason. The
- gateway sends Anthropic the agent's own request; it never presents itself
- as Claude Code.
+- **Claude subscription: only through the official Claude CLI.** Claude
+ runs on an Anthropic API key when one is saved, or on the Claude
+ subscription when the agent is pinned to it or no key is saved
+ (`model_map.uses_claude_cli`). Anthropic bills a Claude login that a
+ third-party app sends to its HTTP API as Extra Usage, never from the plan
+ (measured 2026-10-07), so that login is never sent there and no API key
+ stands in for it. The route (`transport="claude_cli"`) carries no gateway
+ token, no key and no bearer: only which Claude CLI to run and the agent's
+ Claude account directory (`CLAUDE_CONFIG_DIR`; nothing for the platform
+ default). Before the runtime starts, `claude_login` asks that CLI
+ `claude auth status --json` under the runtime's own minimal environment
+ and refuses the turn in plain words when Claude Code is missing or not
+ signed in to a plan. The CLI owns the login and its renewal; Dodaios never
+ reads its credentials. A gateway call for such a seat (a token minted
+ while the agent still ran on its key) is refused with 409
+ `claude_cli_only`. A Claude login (`sk-ant-oat…`) saved in the Anthropic
+ API-key slot is never sent as an API key.
+ - **OpenClaw** runs the model on its bundled `claude-cli` backend
+ (`anthropic/<model>` with `agentRuntime.id: "claude-cli"`), the Claude
+ CLI's directory first on the Gateway's `PATH`; no Dodaios gateway
+ provider is configured. Claude's native tools ask on OpenClaw's
+ plugin-approval channel, which the ACP bridge does not relay, so the
+ chat's stance is applied in the config: Bypass (the agents' default)
+ runs them (`tools.exec.mode: "full"`), any other stance refuses them at
+ once (`"deny"`, never a prompt nobody sees). Dodaios' MCP tools keep
+ their own approvals.
+ - **Hermes** refuses the subscription with the reason. Its only route is
+ an experimental Hermes plugin that runs the Claude CLI as its model
+ provider; installing it changes the Hermes install's dependency
+ environment and its catalog source moved between Hermes 0.21.5 and
+ 0.21.7, so Dodaios does not install it.
`scripts/spikes/agent_runtimes_gateway_e2e.py <runtime> <provider> [model]`
runs two real turns through the gateway (route built by `route_for`, the real
diff --git a/dodaios/agent_chat/catalog.py b/dodaios/agent_chat/catalog.py
index 5e7e91888b..bd4bad3730 100644
--- a/dodaios/agent_chat/catalog.py
+++ b/dodaios/agent_chat/catalog.py
@@ -465,7 +465,7 @@ def offers(surface: str, provider_id: str) -> bool:
#: ``API_KEY_ACCOUNT`` runs on the provider's saved API key.
API_KEY_ACCOUNT: Final[str] = "api-key"
#: ``SUBSCRIPTION_ACCOUNT`` runs on the subscription login even when an API key
-#: is saved too (Hermes / OpenClaw: Claude Code's login, billed as extra usage).
+#: is saved too (Hermes / OpenClaw: only through the official Claude CLI).
SUBSCRIPTION_ACCOUNT: Final[str] = "subscription"
#: Both reserved values: never the id of a real login.
ACCESS_ACCOUNTS: Final[frozenset[str]] = frozenset({API_KEY_ACCOUNT, SUBSCRIPTION_ACCOUNT})
diff --git a/dodaios/agent_chat/runner_acp.py b/dodaios/agent_chat/runner_acp.py
index 7e30afe61e..43c3dd5b00 100644
--- a/dodaios/agent_chat/runner_acp.py
+++ b/dodaios/agent_chat/runner_acp.py
@@ -13,6 +13,7 @@ from __future__ import annotations
import asyncio
import logging
+from concurrent.futures import Future
from pathlib import Path
from typing import Any
@@ -278,13 +279,19 @@ async def plan_runtime_turn(
launch.release()
try:
- failure = gateway.watch_failure(route.api_key or "", effort=session.effort or "")
+ if route.api_key:
+ failure = gateway.watch_failure(route.api_key, effort=session.effort or "")
+ else:
+ # The Claude CLI route: no model call passes through Dodaios'
+ # gateway, so no gateway failure can end this turn.
+ failure = Future()
except BaseException:
release_launch()
raise
def release() -> None:
- gateway.unwatch_failure(route.api_key or "", failure)
+ if route.api_key:
+ gateway.unwatch_failure(route.api_key, failure)
acp = plan.acp if plan is not None else None
if launch.invalidate is not None and (
handle.cancel.is_set()
diff --git a/dodaios/agent_runtimes/gateway.py b/dodaios/agent_runtimes/gateway.py
index a8bb2407d9..34f8d387db 100644
--- a/dodaios/agent_runtimes/gateway.py
+++ b/dodaios/agent_runtimes/gateway.py
@@ -1098,7 +1098,7 @@ def _profile(provider: str, *, temperature_given: bool) -> Any:
)
-def _brain_key(grant: Grant, model: str, login: str | None) -> tuple[str, ...]:
+def _brain_key(grant: Grant, model: str) -> tuple[str, ...]:
"""The cache key: the session, the model and the credential in use.
Blocking (keyring); run in a thread under the key override, so a changed
@@ -1106,42 +1106,49 @@ def _brain_key(grant: Grant, model: str, login: str | None) -> tuple[str, ...]:
"""
import hashlib
- if login:
- material = f"login:{login}"
- else:
- from dodaios.core.config import resolve_provider_endpoint
+ from dodaios.core.config import resolve_provider_endpoint
- try:
- endpoint = resolve_provider_endpoint(grant.provider)
- material = f"{endpoint.base_url or ''}|{endpoint.credential or ''}"
- except Exception as exc: # noqa: BLE001 — no fingerprint just means no reuse
- log.debug(
- "runtime gateway: no credential fingerprint for %s (%s)",
- grant.provider,
- type(exc).__name__,
- )
- material = uuid.uuid4().hex
+ try:
+ endpoint = resolve_provider_endpoint(grant.provider)
+ material = f"{endpoint.base_url or ''}|{endpoint.credential or ''}"
+ except Exception as exc: # noqa: BLE001 — no fingerprint just means no reuse
+ log.debug(
+ "runtime gateway: no credential fingerprint for %s (%s)",
+ grant.provider,
+ type(exc).__name__,
+ )
+ material = uuid.uuid4().hex
digest = hashlib.sha256(material.encode("utf-8")).hexdigest()[:16]
return (grant.agent_id, grant.scope, grant.provider, grant.account_id, model, digest)
-def _new_brain(provider: str, model: str, login: str | None) -> Any:
+def _new_brain(provider: str, model: str) -> Any:
from dodaios.agent_chat.runner_api import build_brain
from dodaios.brain.usage_meter import meter_brain
- if login:
- # No API key: the person's Claude Code login answers, which
- # Anthropic bills as extra usage.
- from dodaios.plugins.brain.claude_api import ClaudeAPIBrain
-
- brain = ClaudeAPIBrain(model=model or None, auth_token=login)
- else:
- brain = build_brain(provider, model)
+ brain = build_brain(provider, model)
# Every call the agent makes lands in the cost ledger, under the caller
# tag of the call.
return meter_brain(brain, provider)
+def claude_cli_only() -> GatewayError:
+ """The answer to a call for an agent on the Claude subscription.
+
+ That subscription runs only through the official Claude CLI (the
+ runtime's own ``claude_cli`` route). Its login is never sent to
+ Anthropic's HTTP API, which bills a third-party app's login as Extra
+ Usage, and an API key never stands in for it.
+ """
+ return GatewayError(
+ "This agent runs on the Claude subscription, which Dodaios uses only through "
+ "Claude Code. Start a new turn so the agent picks that route up. No API key or "
+ "Extra Usage was used.",
+ status=409,
+ code="claude_cli_only",
+ )
+
+
def _acquire_brain(key: tuple[str, ...], factory: Any) -> _BrainSlot:
"""The cached brain for ``key`` (built on first use), marked in use.
@@ -1214,9 +1221,8 @@ async def _deltas(
reset (``ValueError``). The task copies the caller's context, so the
profile the caller set (:func:`_with_profile`) reaches the plugin.
"""
- from dodaios.agent_runtimes.model_map import login_route
- from dodaios.agent_runtimes.provider_errors import login_expired
from dodaios.agent_runtimes import anthropic_history
+ from dodaios.agent_runtimes.model_map import uses_claude_cli
from dodaios.core.config import get_jarvis_agent_secret, override_provider_secrets
from dodaios.costs.ledger import usage_context
from dodaios.costs.model import RUNTIME_CALLER
@@ -1229,22 +1235,18 @@ async def _deltas(
request = anthropic_history.restore(grant, model, request)
async def pump() -> None:
- login: str | None = None
try:
_require_turn(grant, signal)
# A keyring read: never on the event loop.
secret = await asyncio.to_thread(get_jarvis_agent_secret, grant.provider)
overrides = {grant.provider: secret} if secret else {}
with override_provider_secrets(overrides), usage_context(RUNTIME_CALLER):
- on_login, login = await asyncio.to_thread(
- login_route, grant.provider, grant.account_id
- )
- if on_login and not login:
- # Only the Claude CLI renews the login; without it the
- # API-key path would only say "no key".
- raise login_expired()
- key = await asyncio.to_thread(_brain_key, grant, model, login)
- slot = _acquire_brain(key, lambda: _new_brain(grant.provider, model, login))
+ if await asyncio.to_thread(uses_claude_cli, grant.provider, grant.account_id):
+ # A token minted before the agent moved onto the Claude
+ # subscription (its key removed, or pinned since).
+ raise claude_cli_only()
+ key = await asyncio.to_thread(_brain_key, grant, model)
+ slot = _acquire_brain(key, lambda: _new_brain(grant.provider, model))
try:
brain = slot.brain
configure_context = getattr(brain, "set_context_window", None)
@@ -1263,12 +1265,6 @@ async def _deltas(
_release_brain(slot)
await queue.put(_DONE)
except Exception as exc: # noqa: BLE001 — handed to the reader, which reports it
- if login:
- # Anthropic answers a Claude login it will not serve with a
- # bare 429; the account's usage report says why.
- from dodaios.agent_runtimes.provider_errors import explain_login_refusal
-
- exc = await explain_login_refusal(exc, login, model)
await queue.put(exc)
task = asyncio.get_running_loop().create_task(pump())
@@ -1362,7 +1358,8 @@ def _tool_call(index: int, call: dict[str, Any]) -> dict[str, Any]:
async def open_chat_stream(
- grant: Grant, model: str, request: Any, *, temperature_given: bool = True, lease: Any = _UNBOUND,
+ grant: Grant, model: str, request: Any, *, temperature_given: bool = True,
+ lease: Any = _UNBOUND,
) -> AsyncIterator[bytes]:
"""The answer as Chat Completions chunks.
@@ -1459,7 +1456,8 @@ async def _chat_chunks(
async def complete_chat(
- grant: Grant, model: str, request: Any, *, temperature_given: bool = True, lease: Any = _UNBOUND,
+ grant: Grant, model: str, request: Any, *, temperature_given: bool = True,
+ lease: Any = _UNBOUND,
) -> dict[str, Any]:
"""The finished ``chat.completion`` for a runtime that did not ask to stream."""
signal = capture_turn(grant) if lease is _UNBOUND else lease
diff --git a/dodaios/agent_runtimes/hermes.py b/dodaios/agent_runtimes/hermes.py
index c6958693bf..6cd1f6f19d 100644
--- a/dodaios/agent_runtimes/hermes.py
+++ b/dodaios/agent_runtimes/hermes.py
@@ -457,6 +457,7 @@ class HermesRuntime:
return config
async def launch(self, turn: RuntimeTurn) -> RuntimeLaunch:
+ _refuse_claude_cli(turn)
status = await asyncio.to_thread(self.detect, fast=True)
if not status.ready:
raise RuntimeUnavailable(status.problem or "Hermes is not ready.")
@@ -484,6 +485,8 @@ class HermesRuntime:
right now. ``latest_resume`` re-reads the chat's conversation once the
slot is held (a turn may have finished since ``turn`` was built).
"""
+ if turn.route.transport == "claude_cli":
+ return False
status = await asyncio.to_thread(self.detect)
binary = _binary()
if not status.ready or binary is None or self.needs_prepare(status):
@@ -585,6 +588,24 @@ class HermesRuntime:
)
+def _refuse_claude_cli(turn: RuntimeTurn) -> None:
+ """Hermes cannot run an agent on the Claude subscription.
+
+ Its only route there is an experimental Hermes plugin that runs the
+ Claude CLI as its model provider; installing it changes the Hermes
+ install's own dependency environment and its catalog source moves between
+ Hermes releases, so Dodaios does not install it. The subscription is never
+ sent to Anthropic's HTTP API instead (billed as Extra Usage), and no API
+ key stands in for it.
+ """
+ if turn.route.transport == "claude_cli":
+ raise RuntimeUnavailable(
+ "Hermes cannot run on the Claude subscription. Run this agent on OpenClaw "
+ "or as a Dodaios agent, or switch it to an Anthropic API key in its settings. "
+ "No API key or Extra Usage was used."
+ )
+
+
def _restore_key_aliases(base_url: str, api_key: str | None) -> dict[str, str]:
"""The key again under the name Hermes' session restore looks for.
diff --git a/dodaios/agent_runtimes/model_map.py b/dodaios/agent_runtimes/model_map.py
index 49af2cb114..147b30226e 100644
--- a/dodaios/agent_runtimes/model_map.py
+++ b/dodaios/agent_runtimes/model_map.py
@@ -1,6 +1,6 @@
"""Map a society agent's Jarvis provider + model onto an external runtime.
-Every agent on Hermes or OpenClaw reaches its model through Jarvis' own model
+An agent on Hermes or OpenClaw reaches its model through Jarvis' own model
gateway (``gateway.py``): the runtime is configured with one provider —
Jarvis, on the app's loopback server — and a per-agent token in its process
environment (:data:`KEY_ENV_VAR`). Jarvis answers with its own provider
@@ -8,23 +8,31 @@ plugins, so the runtime never holds a vendor key or login and its config is
the same for every provider. API-key and local providers speak Chat
Completions; the ChatGPT subscription (``openai-codex``) speaks Responses.
+The Claude subscription is the one exception (transport ``claude_cli``).
+Anthropic bills a Claude login sent to its HTTP API by a third-party app as
+Extra Usage, never from the plan, so that login is never sent there: the
+runtime runs the official Claude CLI itself (OpenClaw's bundled
+``claude-cli`` backend), and the CLI owns the login and its renewal. The
+route carries only which CLI to run and which Claude account directory it
+reads; no bearer and no API key.
+
This module decides which providers an agent can use right now (a saved key,
a local server with an address, a signed-in subscription) and builds the
-route. Claude runs on an Anthropic API key or, when none is saved, on the
-person's Claude Code login: Anthropic bills a subscription used outside
-Claude Code as extra usage (pay as you go), so the picker says so.
+route. Claude runs on an Anthropic API key, or on the Claude subscription
+when the agent is pinned to it or no key is saved.
"""
from __future__ import annotations
import asyncio
import logging
+import os
from dataclasses import dataclass, replace
from typing import Any, Final, Literal
log = logging.getLogger(__name__)
-Transport = Literal["chat_completions", "anthropic_messages", "responses"]
+Transport = Literal["chat_completions", "anthropic_messages", "responses", "claude_cli"]
#: The environment variable both runtimes read the model key from.
KEY_ENV_VAR: Final[str] = "JARVIS_RUNTIME_API_KEY"
@@ -45,8 +53,8 @@ class _Endpoint:
local_server: bool = False
#: Served by Jarvis' own model gateway on the person's subscription.
subscription: bool = False
- #: Without an API key, the person's Claude Code login answers instead
- #: (billed by Anthropic as extra usage, not from the plan's limits).
+ #: Without an API key (or pinned to it), the person's Claude subscription
+ #: answers instead, through the official Claude CLI only.
claude_login: bool = False
#: May authenticate without a key: Google Cloud Application Default
#: Credentials for a configured project (Vertex AI).
@@ -80,13 +88,21 @@ class ModelRoute:
model: str
base_url: str
transport: Transport
- #: ``None`` for a keyless local server.
+ #: ``None`` for a keyless local server and for the Claude CLI.
api_key: str | None
context_window: int = 32_768
max_output_tokens: int | None = None
+ #: ``claude_cli`` only: the official Claude CLI the runtime runs.
+ claude_binary: str = ""
+ #: ``claude_cli`` only: the environment that selects the agent's Claude
+ #: account (its config directory). Never a credential.
+ claude_env: tuple[tuple[str, str], ...] = ()
def env(self) -> dict[str, str]:
- """The child environment that carries the key (empty when keyless)."""
+ """The child environment: the key (empty when keyless), or for the
+ Claude CLI only the account selection."""
+ if self.transport == "claude_cli":
+ return dict(self.claude_env)
return {KEY_ENV_VAR: self.api_key} if self.api_key else {}
@@ -100,14 +116,77 @@ def subscription_providers() -> frozenset[str]:
return frozenset(name for name, endpoint in _ENDPOINTS.items() if endpoint.subscription)
-def claude_login_token() -> str | None:
- """The live Claude Code login's bearer, or ``None``. Read-only: only the
- Claude CLI redeems the refresh token, so an expired login stays unused
- until Claude Code runs again (a second refresher would break its login)."""
- from dodaios.claude_credentials import freshest_claude_oauth
+@dataclass(frozen=True, slots=True)
+class ClaudeLogin:
+ """A signed-in Claude subscription the official CLI can run on."""
+
+ #: The Claude CLI executable.
+ binary: str
+ #: What selects the account in the CLI's environment (``CLAUDE_CONFIG_DIR``;
+ #: empty for the platform default). Never a credential.
+ env: tuple[tuple[str, str], ...] = ()
+
+
+def _claude_account_env(account_id: str) -> dict[str, str]:
+ """The environment that points the Claude CLI at the agent's account.
- snapshot = freshest_claude_oauth()
- return snapshot.access_token if snapshot.status == "valid" else None
+ ``account_id`` may name a Claude login (``dodaios.agent_accounts``);
+ anything else (``""``, a reserved access value) means the active Claude
+ account. The built-in account adds nothing, so the CLI keeps its platform
+ default (the macOS Keychain, for one) — unless this app itself runs with
+ a ``CLAUDE_CONFIG_DIR``, which a runtime's minimal child environment
+ would otherwise drop.
+ """
+ from dodaios import agent_accounts
+ from dodaios.agent_chat.catalog import ACCESS_ACCOUNTS
+
+ named = account_id if account_id and account_id not in ACCESS_ACCOUNTS else ""
+ account = agent_accounts.resolve(named) if named else agent_accounts.active_account("claude")
+ if account is None or account.platform != "claude":
+ account = agent_accounts.active_account("claude")
+ env = agent_accounts.env_overrides("claude", account.id)
+ inherited = os.environ.get("CLAUDE_CONFIG_DIR", "").strip()
+ if not env and inherited:
+ env = {"CLAUDE_CONFIG_DIR": inherited}
+ return env
+
+
+def claude_login(account_id: str = "") -> ClaudeLogin:
+ """The Claude subscription the agent runs on, checked with the CLI itself.
+
+ Only ``claude auth status`` is asked, under the same minimal environment
+ the runtime gives its CLI: no credential is read and no bearer leaves the
+ CLI. Raises :class:`RouteUnavailable` with the reason in plain words.
+ Blocking (one short process, cached a few seconds).
+ """
+ from dodaios.agent_runtimes.base import child_env
+ from dodaios.claude_auth import (
+ claude_install_hint,
+ cli_login_env,
+ is_subscription_login,
+ native_subscription_login,
+ )
+
+ selection = _claude_account_env(account_id)
+ env = cli_login_env(child_env(selection))
+ binary, login = native_subscription_login(env)
+ if binary is None:
+ raise RouteUnavailable(
+ "This agent runs on the Claude subscription, which Dodaios uses only through "
+ f"Claude Code, and Claude Code is not installed. {claude_install_hint()} "
+ "No API key was used."
+ )
+ if not is_subscription_login(login):
+ raise RouteUnavailable(
+ "This agent runs on the Claude subscription, which Dodaios uses only through "
+ "Claude Code, and Claude Code is not signed in to a Claude plan. Sign in to "
+ "Claude Code (Settings → API keys), or switch the agent to an Anthropic API "
+ "key. No API key was used."
+ )
+ if env.get("USER"):
+ # The CLI's native credential lookup needs it (POSIX).
+ selection.setdefault("USER", env["USER"])
+ return ClaudeLogin(binary=binary, env=tuple(sorted(selection.items())))
def _api_key(provider: str, credential: str | None) -> str | None:
@@ -131,47 +210,34 @@ def _saved_key(provider: str, endpoint: _Endpoint) -> str | None:
return _api_key(provider, resolved.credential)
-def login_route(provider: str, account_id: str = "") -> tuple[bool, str | None]:
- """Whether ``provider`` answers on the person's Claude Code login for
- ``account_id``, and that login's live bearer (``None`` once it expired).
- ``account_id`` may pin the agent to its key or to the login
- (``catalog.ACCESS_ACCOUNTS``); without a pin the API key wins. Blocking
- (keyring)."""
+def uses_claude_cli(provider: str, account_id: str = "") -> bool:
+ """Whether ``provider`` answers on the Claude subscription for
+ ``account_id``, which only the official Claude CLI may use. ``account_id``
+ may pin the agent to its key or to the subscription
+ (``catalog.ACCESS_ACCOUNTS``); without a pin the API key wins. A
+ subscription seat stays one when its login is gone: it is reported as
+ such, never answered on a key. Blocking (keyring)."""
from dodaios.agent_chat.catalog import API_KEY_ACCOUNT, SUBSCRIPTION_ACCOUNT
endpoint = _ENDPOINTS.get(provider)
if endpoint is None or not endpoint.claude_login or account_id == API_KEY_ACCOUNT:
- return False, None
- if account_id != SUBSCRIPTION_ACCOUNT and _saved_key(provider, endpoint) is not None:
- return False, None
- return True, claude_login_token()
-
-
-def login_token_for(provider: str, account_id: str = "") -> str | None:
- """The Claude login ``provider`` answers on, or ``None`` when it runs on
- an API key (or cannot use a login at all). Blocking (keyring)."""
- return login_route(provider, account_id)[1]
-
-
-def login_providers() -> list[str]:
- """Usable providers that answer on a Claude login, not an API key: the
- picker labels them as billed extra usage. Blocking (keyring)."""
- return [name for name in _ENDPOINTS if _login_available(login_token_for(name))]
+ return False
+ return account_id == SUBSCRIPTION_ACCOUNT or _saved_key(provider, endpoint) is None
-def _login_available(token: str | None) -> bool:
- """Use the same cached, non-inference billing check as runtime startup."""
- if not token:
+def _claude_login_ready(account_id: str = "") -> bool:
+ try:
+ claude_login(account_id)
+ except RouteUnavailable: # not installed or not signed in: not offered
return False
- from dodaios.agent_runtimes.provider_errors import login_blocked
-
- return login_blocked(token, "") is None
+ return True
def access_choices() -> dict[str, list[str]]:
- """Per provider that can pay two ways (Claude: API key or Claude Code
- login), the ways that work right now: ``"api"`` and/or ``"subscription"``.
- The "New agent" dialog offers exactly these. Blocking (keyring)."""
+ """Per provider that can pay two ways (Claude: API key or the Claude
+ subscription through Claude Code), the ways that work right now: ``"api"``
+ and/or ``"subscription"``. The "New agent" dialog offers exactly these.
+ Blocking (keyring, ``claude auth status``)."""
choices: dict[str, list[str]] = {}
for name, endpoint in _ENDPOINTS.items():
if not endpoint.claude_login:
@@ -179,33 +245,13 @@ def access_choices() -> dict[str, list[str]]:
found: list[str] = []
if _saved_key(name, endpoint) is not None:
found.append("api")
- if _login_available(claude_login_token()):
+ if _claude_login_ready():
found.append("subscription")
if found:
choices[name] = found
return choices
-def access_blocked() -> dict[str, dict[str, str]]:
- """Per provider that can pay two ways, the ways that exist but are refused
- right now, with the refusal's code: a live Claude Code login whose Extra
- Usage is off (``extra_usage_off``) or spent (``extra_usage_spent``) — the
- only way Anthropic serves a subscription to Hermes and OpenClaw. The
- "New agent" dialog shows such a way disabled with its reason. Blocking
- (keyring, one cached usage GET, no inference)."""
- from dodaios.agent_runtimes.provider_errors import login_blocked
-
- blocked: dict[str, dict[str, str]] = {}
- for name, endpoint in _ENDPOINTS.items():
- if not endpoint.claude_login:
- continue
- token = claude_login_token()
- refusal = login_blocked(token, "") if token else None
- if refusal is not None:
- blocked[name] = {"subscription": refusal.code}
- return blocked
-
-
def supports(provider: str) -> bool:
return provider in _ENDPOINTS
@@ -225,7 +271,6 @@ def usable_providers(config: Any) -> list[str]:
for provider in sorted(_ENDPOINTS, key=lambda name: (not _ENDPOINTS[name].subscription, name)):
try:
_checked_model(config, provider, "probe")
- _check_login_billing(provider, "", "")
except RouteUnavailable: # not connected: the provider is simply not offered
continue
except Exception: # noqa: BLE001 — one unreadable provider must not empty the list
@@ -284,6 +329,12 @@ def _checked_model(config: Any, provider: str, model: str, *, account_id: str =
if not chosen:
raise RouteUnavailable("Choose a ChatGPT model for this agent first.")
return chosen
+ if endpoint.claude_login and uses_claude_cli(provider, account_id):
+ claude_login(account_id)
+ chosen = model.strip() or _default_model(config, provider)
+ if not chosen:
+ raise RouteUnavailable("Choose a Claude model for this agent first.")
+ return chosen
from dodaios.core.config import resolve_provider_endpoint
resolved = resolve_provider_endpoint(
@@ -298,30 +349,18 @@ def _checked_model(config: Any, provider: str, model: str, *, account_id: str =
)
# The Agents-tier key wins over the shared one, exactly as the gateway uses it.
key = _api_key(provider, resolved.credential)
- if endpoint.claude_login:
- from dodaios.agent_chat.catalog import API_KEY_ACCOUNT, SUBSCRIPTION_ACCOUNT
-
- if account_id == API_KEY_ACCOUNT and key is None:
- raise RouteUnavailable(
- "This agent runs on an Anthropic API key, and none is saved. Connect "
- "one in Settings → API keys, or switch the agent to the subscription."
- )
- if account_id == SUBSCRIPTION_ACCOUNT and not claude_login_token():
- raise RouteUnavailable(
- "This agent runs on the Claude Code login, and it is not live. Open "
- "Claude Code once to renew it, or switch the agent to an API key."
- )
- if key is None and endpoint.claude_login and not claude_login_token():
+ if endpoint.claude_login and key is None:
+ # Only an agent pinned to its key gets here without one.
raise RouteUnavailable(
- "Claude needs an Anthropic API key or a live Claude Code login. Connect "
- "one in Settings → API keys, or open Claude Code once to renew its login."
+ "This agent runs on an Anthropic API key, and none is saved. Connect "
+ "one in Settings → API keys, or switch the agent to the subscription."
)
if key is None and endpoint.cloud_project:
from dodaios.core.config import vertex_credential_configured
if vertex_credential_configured():
key = "" # the Cloud project signs the requests (no key)
- if key is None and not endpoint.keyless and not endpoint.claude_login:
+ if key is None and not endpoint.keyless:
raise RouteUnavailable(
f"No API key is saved for {provider}. Connect it in Settings → API keys."
)
@@ -331,18 +370,29 @@ def _checked_model(config: Any, provider: str, model: str, *, account_id: str =
return chosen
-def _check_login_billing(provider: str, model: str, account_id: str) -> None:
- """Fail before the runtime starts when Anthropic will refuse the Claude
- login: it bills third-party apps only as Extra Usage (off or spent here).
- Blocking (keyring, one cached usage GET)."""
- login = login_token_for(provider, account_id)
- if not login:
- return
- from dodaios.agent_runtimes.provider_errors import login_blocked
+def _claude_cli_route(config: Any, provider: str, model: str, account_id: str) -> ModelRoute:
+ """The route of an agent on the Claude subscription: the official CLI,
+ run by the runtime itself. No gateway token: nothing of this agent's can
+ reach Anthropic's HTTP API, which bills a third-party login as Extra Usage."""
+ from dodaios.agent_runtimes.model_limits import resolve_limits
+ from dodaios.brain.model_catalog import ModelCatalog
- refusal = login_blocked(login, model)
- if refusal is not None:
- raise RouteUnavailable(refusal.message)
+ login = claude_login(account_id)
+ chosen = model.strip() or _default_model(config, provider)
+ if not chosen:
+ raise RouteUnavailable("Choose a Claude model for this agent first.")
+ limits = resolve_limits(config, provider, chosen, ModelCatalog().cached_model(provider, chosen))
+ return ModelRoute(
+ provider=provider,
+ model=chosen,
+ base_url="",
+ transport="claude_cli",
+ api_key=None,
+ context_window=limits.context_window,
+ max_output_tokens=limits.max_output_tokens,
+ claude_binary=login.binary,
+ claude_env=login.env,
+ )
def route_for(
@@ -356,9 +406,11 @@ def route_for(
) -> ModelRoute:
"""The agent's route through Jarvis' gateway. Blocking (keyring): call it
in a thread. The token speaks for ``agent_id`` on ``provider`` (and, for
- the subscription, on that Codex ``account_id``)."""
+ the subscription, on that Codex ``account_id``). An agent on the Claude
+ subscription gets the Claude CLI route instead (:func:`_claude_cli_route`)."""
+ if uses_claude_cli(provider, account_id):
+ return _claude_cli_route(config, provider, model, account_id)
chosen = _checked_model(config, provider, model, account_id=account_id)
- _check_login_billing(provider, chosen, account_id)
from dodaios.agent_runtimes import gateway
from dodaios.agent_runtimes.base import home_key
from dodaios.agent_runtimes.model_limits import resolve_limits
@@ -400,6 +452,8 @@ async def prepare_route(
route_for, config, provider, model, agent_id=agent_id, account_id=account_id,
session_id=session_id,
)
+ if route.transport == "claude_cli":
+ return route
assert route.api_key is not None
grant = gateway.verify(route.api_key)
assert grant is not None
diff --git a/dodaios/agent_runtimes/openclaw.py b/dodaios/agent_runtimes/openclaw.py
index e924dfc006..ee0ba091c3 100644
--- a/dodaios/agent_runtimes/openclaw.py
+++ b/dodaios/agent_runtimes/openclaw.py
@@ -572,6 +572,8 @@ class OpenClawRuntime:
# temp-folder log every OpenClaw on the machine appends to.
"logging": {"file": str(home / "state" / "logs" / "openclaw.log")},
}
+ if route.transport == "claude_cli":
+ _use_claude_cli(config, turn)
if turn.mcp_url and turn.control_key:
from dodaios.agent_chat.dodaios_harness import HEADER_NAME
from dodaios.core.branding import MCP_TOOLS_SERVER_NAME
@@ -742,6 +744,14 @@ class OpenClawRuntime:
**({_CONTROL_KEY_ENV: turn.control_key} if turn.control_key else {}),
}
)
+ if turn.route.transport == "claude_cli" and turn.route.claude_binary:
+ # The bundled backend runs `claude` from the Gateway's PATH: the
+ # CLI the subscription was checked with comes first.
+ gateway_env["PATH"] = os.pathsep.join(
+ part for part in (
+ str(Path(turn.route.claude_binary).parent), gateway_env.get("PATH", "")
+ ) if part
+ )
gateway = await self._ensure_gateway(turn, key, home, token, launcher, gateway_env)
def release() -> None:
@@ -1004,6 +1014,32 @@ class OpenClawRuntime:
await self._stop_gateway(gateway)
+def _use_claude_cli(config: dict[str, Any], turn: RuntimeTurn) -> None:
+ """Run the agent on the Claude subscription through OpenClaw's bundled
+ ``claude-cli`` backend (``docs/gateway/cli-backends.md`` of OpenClaw).
+
+ Claude Code owns the login and its renewal; OpenClaw never reads or
+ forwards its token and sends no Anthropic API request. Dodaios' model
+ gateway is not configured at all, so no model call of this agent can
+ reach the HTTP API, which bills a third-party login as Extra Usage.
+
+ Claude's native tools ask for approval on OpenClaw's plugin-approval
+ channel, which the ACP bridge does not relay. So the chat's stance is
+ applied here instead of per call: Bypass runs them, any other stance
+ refuses them at once (``deny`` never prompts, so a turn cannot hang on an
+ approval nobody sees). Dodaios' own MCP tools keep their approvals.
+ """
+ model_ref = f"anthropic/{turn.route.model}"
+ config.pop("models", None)
+ defaults = config["agents"]["defaults"]
+ defaults["model"] = {"primary": model_ref}
+ defaults["models"] = {model_ref: {"agentRuntime": {"id": "claude-cli"}}}
+ tools = config["tools"]
+ tools["exec"]["mode"] = "full" if turn.auto_approve else "deny"
+ if "shell" in turn.denied_native:
+ tools["deny"] = [*tools["deny"], "exec", "process"]
+
+
def prompt_meta(turn: RuntimeTurn) -> dict[str, Any] | None:
"""``session/prompt`` ``_meta``: the agent's thinking level for this prompt.
diff --git a/dodaios/agent_runtimes/provider_errors.py b/dodaios/agent_runtimes/provider_errors.py
index 2b193700e8..9b1eab9306 100644
--- a/dodaios/agent_runtimes/provider_errors.py
+++ b/dodaios/agent_runtimes/provider_errors.py
@@ -1,10 +1,10 @@
"""Why a provider refused a Hermes / OpenClaw model call, in words a person can act on.
A provider's HTTP status alone misleads: OpenAI answers an empty credit
-balance with 429, OpenRouter with 402, and Anthropic refuses a Claude
-subscription used by a third-party app with a 400 or a bare 429
-``rate_limit_error`` while the plan still has room. Each of those reads as "rate limited, try
-again in 30 s" — and no retry will ever succeed. This module tells them apart:
+balance with 429 and OpenRouter with 402. Each of those reads as "rate
+limited, try again in 30 s" — and no retry will ever succeed. This module
+tells them apart (a Claude subscription never reaches a provider's HTTP API
+here: it runs through the official Claude CLI, ``model_map``):
* **No credits / no quota** on a key -> 402 ``billing`` (a runtime does not
retry it; Hermes classifies 402 as billing and stops).
@@ -18,13 +18,6 @@ again in 30 s" — and no retry will ever succeed. This module tells them apart:
* **Model not offered**, **tools not supported**, **tool schema refused** ->
404 ``model_not_found`` / 400 ``tools_unsupported`` / 400
``invalid_tool_schema``: deterministic, so nothing retries them.
-* **Claude subscription**: Anthropic serves a subscription to third-party
- apps such as Hermes and OpenClaw only from the account's Extra Usage
- ("Third-party apps now draw from your extra usage, not your plan limits"),
- answering 400 or a bare 429 otherwise. The account's own usage report
- (``/api/oauth/usage``, the endpoint Claude Code reads; no inference) says
- whether Extra Usage is off or its monthly limit is spent, so a turn can
- fail at once (``login_blocked``) instead of after a runtime start.
Messages never copy the provider's response body; the body is only matched.
:func:`describe` gives a bounded, redacted line for the log, so a failed
@@ -33,13 +26,10 @@ turn can be diagnosed without reproducing it.
from __future__ import annotations
-import asyncio
import logging
import re
from dataclasses import dataclass
-from typing import Any, Final
-
-from dodaios.core.http_pool import SyncHttpClientPool
+from typing import Final
log = logging.getLogger(__name__)
@@ -138,10 +128,7 @@ _TOOL_SCHEMA_PHRASES: Final[tuple[str, ...]] = (
TERMINAL_CODES: Final[frozenset[str]] = frozenset(
{
"billing",
- "extra_usage_off",
- "extra_usage_spent",
"provider_auth",
- "claude_login_expired",
"model_not_found",
"invalid_tool_schema",
"tools_unsupported",
@@ -156,10 +143,6 @@ _SECRET_RE: Final = re.compile(
r"|[Bb]earer\s+[A-Za-z0-9._\-]{10,}|eyJ[A-Za-z0-9._\-]{20,})"
)
-_HTTP_POOL: Final = SyncHttpClientPool(timeout_s=8.0)
-
-_CLAUDE_USAGE_URL: Final[str] = "https://api.anthropic.com/api/oauth/usage"
-_CLAUDE_OAUTH_BETA: Final[str] = "oauth-2025-04-20"
@dataclass(frozen=True, slots=True)
class Refusal:
@@ -246,8 +229,6 @@ def classify(provider: str, exc: BaseException, model: str = "") -> Refusal | No
return exc.refusal
status = _status(exc)
codes, text = _codes_and_text(exc)
- if status in (400, 402, 403, 429) and "extra usage" in text:
- return _extra_usage_off("")
if status == 402 or (
status in (400, 403, 429)
and (codes & _BILLING_CODES or any(phrase in text for phrase in _BILLING_PHRASES))
@@ -373,135 +354,3 @@ def describe(exc: BaseException, limit: int = 400) -> str:
if codes:
parts.append("codes=" + ",".join(sorted(codes)[:4]))
return f"{' '.join(parts)}: {message}"
-
-
-# ------------------------------------------------------------ Claude login
-
-
-def _login_expired() -> Refusal:
- return Refusal(
- 401,
- "claude_login_expired",
- "Anthropic refused the Claude Code login this agent runs on: it expired or was "
- "signed out. Open Claude Code once to renew it, or connect an Anthropic API key "
- "in Settings → API keys.",
- )
-
-
-def login_expired() -> ProviderRefusal:
- """The refusal for an agent routed to a Claude login that is not live."""
- return ProviderRefusal(_login_expired())
-
-
-def _extra_usage_off(model: str) -> Refusal:
- return Refusal(
- 402,
- "extra_usage_off",
- f"Anthropic bills {model or 'Claude'} used by Hermes or OpenClaw on a Claude "
- "subscription as Extra Usage, never from the plan's limits, and Extra Usage "
- "is turned off for this Claude account, so retrying will not help. Turn it "
- "on at claude.ai under Settings → Usage, connect an Anthropic API key, or "
- "choose another provider in the agent's settings.",
- )
-
-
-def _extra_usage_spent(model: str) -> Refusal:
- return Refusal(
- 402,
- "extra_usage_spent",
- "This Claude account's Extra Usage limit for the month is spent, and "
- f"Anthropic bills {model or 'Claude'} used by Hermes or OpenClaw only as "
- "Extra Usage. Raise the limit at claude.ai under Settings → Usage, connect "
- "an Anthropic API key, or choose another provider in the agent's settings.",
- )
-
-
-def login_refusal(usage: Any, model: str) -> Refusal | None:
- """Why Anthropic refuses a Claude-login call from Hermes or OpenClaw.
-
- Anthropic serves a subscription to third-party apps only from the
- account's Extra Usage ("Third-party apps now draw from your extra usage,
- not your plan limits", live 2026-10-07), so the plan's own windows say
- nothing here. ``None`` when the report explains nothing. Pure.
- """
- extra = usage.get("extra_usage") if isinstance(usage, dict) else None
- if not isinstance(extra, dict):
- return None
- if extra.get("is_enabled") is False:
- return _extra_usage_off(model)
- if extra.get("spend_limit_reached") is True:
- return _extra_usage_spent(model)
- return None
-
-
-#: The last usage report per login, so routing does not ask on every turn.
-_REPORTS: dict[str, tuple[float, Any]] = {}
-_REPORT_TTL_S: Final = 120.0
-_REPORT_FAILURE_TTL_S: Final = 10.0
-
-
-def _claude_usage(token: str) -> Any:
- """The login's usage report, or ``None``. Blocking; never logs the token."""
- try:
- response = _HTTP_POOL.client().get(
- _CLAUDE_USAGE_URL,
- headers={
- "Authorization": f"Bearer {token}",
- "anthropic-beta": _CLAUDE_OAUTH_BETA,
- "Accept": "application/json",
- },
- )
- except Exception as exc: # noqa: BLE001 — no report means "no explanation", logged
- log.info("runtime gateway: Claude usage report unavailable (%s)", type(exc).__name__)
- return None
- if response.status_code != 200:
- log.info("runtime gateway: Claude usage report answered %s", response.status_code)
- return None
- try:
- return response.json()
- except ValueError:
- log.info("runtime gateway: Claude usage report was not JSON")
- return None
-
-
-def login_blocked(token: str, model: str) -> Refusal | None:
- """A refusal known before any model call: Extra Usage off or spent.
-
- Blocking (one cached GET, no inference). Lets a turn fail at once with the
- reason instead of starting a runtime that can only be refused.
- """
- import hashlib
- import time
-
- key = hashlib.sha256(token.encode()).hexdigest()
- cached = _REPORTS.get(key)
- ttl = _REPORT_FAILURE_TTL_S if cached is not None and cached[1] is None else _REPORT_TTL_S
- if cached is not None and time.monotonic() - cached[0] < ttl:
- usage = cached[1]
- else:
- usage = _claude_usage(token)
- # Availability is read by several picker lists. A report outage is
- # unknown, not blocked; briefly cache it to avoid repeated timeouts.
- _REPORTS[key] = (time.monotonic(), usage)
- return login_refusal(usage, model)
-
-
-async def explain_login_refusal(exc: BaseException, token: str, model: str) -> BaseException:
- """``exc`` replaced by a :class:`ProviderRefusal` when the account explains it."""
- status = _status(exc)
- if status == 401:
- return login_expired()
- if status not in (400, 402, 403, 429):
- return exc
- _codes, text = _codes_and_text(exc)
- if status in (400, 402, 403) and "extra usage" not in text:
- # A 403 on a login is the login itself; a 400 is an ordinary bad request.
- return login_expired() if status == 403 else exc
- usage = await asyncio.to_thread(_claude_usage, token)
- refusal = login_refusal(usage, model)
- if refusal is None and "extra usage" in text:
- refusal = _extra_usage_off(model)
- if refusal is None:
- return exc
- log.info("runtime gateway: Claude login refused %s (%s)", model, refusal.code)
- return ProviderRefusal(refusal)
diff --git a/dodaios/claude_auth.py b/dodaios/claude_auth.py
index 71a9ff0e5c..e83a7cd8f5 100644
--- a/dodaios/claude_auth.py
+++ b/dodaios/claude_auth.py
@@ -259,22 +259,26 @@ def _optional_text(value: object) -> str | None:
return value.strip() if isinstance(value, str) and value.strip() else None
-def _cli_credential_env() -> dict[str, str] | None:
+def _cli_credential_env(source: Mapping[str, str] | None = None) -> dict[str, str] | None:
"""Supply the POSIX account name native credential lookups require.
GUI launchers normally set ``USER``, but sanitized app environments may not.
- Claude's macOS Keychain lookup treats a missing value as logged out. Returning
- ``None`` preserves normal inheritance when no repair is needed.
+ Claude's macOS Keychain lookup treats a missing value as logged out.
+ ``source`` is the environment the probed CLI runs with (``None`` = this
+ process'). Without a ``source``, ``None`` preserves normal inheritance when
+ no repair is needed.
"""
- if os.name != "posix" or os.environ.get("USER"):
- return None
+ env = dict(source) if source is not None else None
+ current: Mapping[str, str] = env if env is not None else os.environ
+ if os.name != "posix" or current.get("USER"):
+ return env
try:
user = getpass.getuser().strip()
except (OSError, KeyError):
- return None
+ return env
if not user:
- return None
- env = dict(os.environ)
+ return env
+ env = dict(current)
env["USER"] = user
return env
@@ -519,21 +523,30 @@ class ClaudeAuthService:
"""Shell-free invocation prefix (test seam for Windows npm shims)."""
return claude_cli_argv_prefix(binary)
- def _probe_cli_auth(self, binary: str) -> ClaudeCliAuthSnapshot | None:
+ def _probe_cli_auth(
+ self, binary: str, *, env: Mapping[str, str] | None = None
+ ) -> ClaudeCliAuthSnapshot | None:
"""Ask the installed CLI for its native auth state, with a short TTL.
A parsed JSON body is authoritative even when the command exits nonzero
(some CLI releases use that exit status for ``loggedIn: false``). A
missing command, timeout, or malformed body returns ``None`` so older
- releases continue through the on-disk compatibility parser.
+ releases continue through the on-disk compatibility parser. ``env`` is
+ the environment of the process that will use the login (its account
+ directory); ``None`` probes this process' own.
"""
prefix = self._cli_argv_prefix(binary)
+ probe_env = _cli_credential_env(env)
+ account_env: Mapping[str, str] = probe_env if probe_env is not None else os.environ
cache_key = (
"\0".join(prefix),
- os.environ.get("CLAUDE_CONFIG_DIR", ""),
- os.environ.get("HOME", ""),
- os.environ.get("USERPROFILE", ""),
- os.environ.get("USER", ""),
+ account_env.get("CLAUDE_CONFIG_DIR", ""),
+ account_env.get("HOME", ""),
+ account_env.get("USERPROFILE", ""),
+ account_env.get("USER", ""),
+ # A minimal child environment can answer differently from this
+ # process' own (an API key set here, for one).
+ "child" if env is not None else "",
)
now = time.monotonic()
cached = _AUTH_STATUS_CACHE.get(cache_key)
@@ -542,7 +555,7 @@ class ClaudeAuthService:
try:
proc = subprocess.run(
[*prefix, "auth", "status", "--json"],
- env=_cli_credential_env(),
+ env=probe_env,
capture_output=True,
encoding="utf-8",
errors="replace",
@@ -904,6 +917,36 @@ class ClaudeAuthService:
return False, f"could not remove Claude credentials: {exc}"
+def cli_login_env(env: Mapping[str, str]) -> dict[str, str]:
+ """``env`` plus what the CLI's native credential lookup needs (POSIX ``USER``)."""
+ return _cli_credential_env(env) or dict(env)
+
+
+def native_subscription_login(
+ env: Mapping[str, str],
+) -> tuple[str | None, ClaudeCliAuthSnapshot | None]:
+ """The Claude CLI and its own login state for a process started with ``env``.
+
+ ``(None, None)`` when the CLI is not installed. The snapshot is ``None``
+ when the CLI could not say; otherwise it reports whether ``env``'s account
+ is signed in, and how. Only ``claude auth status`` is asked: no credential
+ file is read and no bearer is returned.
+ """
+ service = ClaudeAuthService()
+ binary = service._resolve_binary()
+ if binary is None:
+ return None, None
+ return binary, service._probe_cli_auth(binary, env=env)
+
+
+def is_subscription_login(snapshot: ClaudeCliAuthSnapshot | None) -> bool:
+ """Whether ``snapshot`` is a signed-in Claude plan, not an API-key login."""
+ if snapshot is None or not snapshot.logged_in:
+ return False
+ method = (snapshot.auth_method or "").lower().replace("-", "_")
+ return not ("api" in method and "key" in method)
+
+
def usable_native_claude_subscription() -> ClaudeAuthStatus | None:
"""Return a subscription status that a customization-free worker can use.
diff --git a/dodaios/society/seat_brain.py b/dodaios/society/seat_brain.py
index 6eedebcf70..0e914a9721 100644
--- a/dodaios/society/seat_brain.py
+++ b/dodaios/society/seat_brain.py
@@ -149,18 +149,19 @@ def agent_seat(config: Any, agent: Any) -> Seat:
def _runtime_seat(provider: str, model: str, account: str) -> Seat:
"""The seat of a Hermes / OpenClaw agent: the auth its gateway route uses.
- Jarvis' model gateway answers such an agent on the provider's API key, or
- on the Claude login when the agent is pinned to it or no key is saved
- (``model_map.login_token_for``). ``resolve_runner`` alone would prefer
+ Jarvis' model gateway answers such an agent on the provider's API key;
+ on the Claude subscription (pinned to it, or no key saved:
+ ``model_map.uses_claude_cli``) the runtime runs Claude Code itself.
+ ``resolve_runner`` alone would prefer
Claude Code for an unpinned agent, so its reviews would run on the plan
while its chat bills the key. The login is reachable for a review only
through Claude Code; without it the seat is unavailable, never a key.
"""
from dodaios.agent_chat.catalog import API_KEY_ACCOUNT, SUBSCRIPTION_ACCOUNT
from dodaios.agent_chat.service import resolve_runner
- from dodaios.agent_runtimes.model_map import login_token_for
+ from dodaios.agent_runtimes.model_map import uses_claude_cli
- on_login = login_token_for(provider, account) is not None
+ on_login = uses_claude_cli(provider, account)
pinned = SUBSCRIPTION_ACCOUNT if on_login else API_KEY_ACCOUNT
runner = resolve_runner(provider, surface="society", account_id=pinned)
if on_login and runner in _KEYED_RUNNERS:
diff --git a/dodaios/ui/web/agent_runtime_routes.py b/dodaios/ui/web/agent_runtime_routes.py
index b7f984dbd2..cee3dcafdb 100644
--- a/dodaios/ui/web/agent_runtime_routes.py
+++ b/dodaios/ui/web/agent_runtime_routes.py
@@ -16,9 +16,7 @@ from fastapi import APIRouter, HTTPException, Request
from dodaios.agent_runtimes import RUNTIME_NAMES, manager
from dodaios.agent_runtimes.model_map import (
- access_blocked,
access_choices,
- login_providers,
subscription_providers,
supported_providers,
usable_providers,
@@ -26,10 +24,9 @@ from dodaios.agent_runtimes.model_map import (
router = APIRouter(prefix="/api/agent-runtimes", tags=["agent-runtimes"])
-#: ``[checked_at, providers, login_providers, access_choices, access_blocked]``: the
-#: keyring is read at most every few seconds, since the UI polls this route while an
-#: install runs.
-_USABLE_CACHE: list[Any] = [float("-inf"), [], [], {}, {}]
+#: ``[checked_at, providers, access_choices]``: the keyring is read at most every
+#: few seconds, since the UI polls this route while an install runs.
+_USABLE_CACHE: list[Any] = [float("-inf"), [], {}]
_USABLE_TTL_S = 10.0
@@ -38,13 +35,12 @@ async def list_agent_runtimes(request: Request, refresh: bool = False) -> dict[s
"""Every external runtime: installed, version, ready, problem, setup job,
plus the Dodaios providers an agent on such a runtime can use right now
(``supported_providers``: saved key or local server; ``all_providers``:
- every provider the runtimes can drive once connected; ``login_providers``:
- usable ones that answer on a Claude login, billed as extra usage;
- ``access``: for a provider that can pay two ways, which ways work now —
- ``"api"`` and/or ``"subscription"``; ``access_blocked``: per provider and
- way, the reason code a way is refused right now, e.g.
- ``{"claude-api": {"subscription": "extra_usage_off"}}`` — the dialog shows
- that way disabled with its reason)."""
+ every provider the runtimes can drive once connected; ``access``: for a
+ provider that can pay two ways, which ways work now — ``"api"`` and/or
+ ``"subscription"``). ``login_providers`` (seats billed as Extra Usage) and
+ ``access_blocked`` (a way refused for Extra Usage) stay empty for older
+ clients: the Claude subscription runs only through the official Claude
+ CLI, on the plan, never as Extra Usage."""
now = time.monotonic()
if refresh or now - _USABLE_CACHE[0] > _USABLE_TTL_S:
config = getattr(request.app.state, "config", None)
@@ -56,18 +52,16 @@ async def list_agent_runtimes(request: Request, refresh: bool = False) -> dict[s
_USABLE_CACHE[:] = [
now,
usable,
- await asyncio.to_thread(login_providers),
await asyncio.to_thread(access_choices),
- await asyncio.to_thread(access_blocked),
]
return {
"runtimes": await manager.statuses(refresh=refresh),
"supported_providers": list(_USABLE_CACHE[1]),
"all_providers": sorted(supported_providers()),
"subscription_providers": sorted(subscription_providers()),
- "login_providers": list(_USABLE_CACHE[2]),
- "access": dict(_USABLE_CACHE[3]),
- "access_blocked": dict(_USABLE_CACHE[4]),
+ "login_providers": [],
+ "access": dict(_USABLE_CACHE[2]),
+ "access_blocked": {},
}
diff --git a/tests/fakes/fake_claude_cli.py b/tests/fakes/fake_claude_cli.py
new file mode 100644
index 0000000000..60b99ad976
--- /dev/null
+++ b/tests/fakes/fake_claude_cli.py
@@ -0,0 +1,79 @@
+"""A stand-in for the ``claude`` CLI, for Claude subscription routing tests.
+
+:func:`install` writes a ``claude`` launcher (``claude.cmd`` on Windows) into a
+folder; the launcher runs this file. The fake reads the account it answers
+for from ``$CLAUDE_CONFIG_DIR`` — the only thing a runtime's minimal child
+environment tells the real CLI about the account — so a test can tell which
+account was probed:
+
+* ``auth status --json`` prints ``<CLAUDE_CONFIG_DIR>/fake-auth.json``
+ (``{"loggedIn": false}`` when absent);
+* anything else (a model call) exits 3: these tests never infer.
+
+Every invocation appends its argv as one JSON line to
+``<CLAUDE_CONFIG_DIR>/fake-calls.log``.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from pathlib import Path
+
+SUBSCRIPTION = {"loggedIn": True, "authMethod": "claude.ai", "subscriptionType": "max"}
+API_KEY = {"loggedIn": True, "authMethod": "api_key"}
+LOGGED_OUT = {"loggedIn": False}
+
+
+def install(directory: Path) -> Path:
+ """Write a ``claude`` launcher for this fake into ``directory``."""
+ directory.mkdir(parents=True, exist_ok=True)
+ script = Path(__file__).resolve()
+ if os.name == "nt":
+ launcher = directory / "claude.cmd"
+ launcher.write_text(f'@"{sys.executable}" "{script}" %*\r\n', encoding="utf-8")
+ else:
+ launcher = directory / "claude"
+ launcher.write_text(f'#!/bin/sh\nexec "{sys.executable}" "{script}" "$@"\n')
+ launcher.chmod(0o755)
+ return launcher
+
+
+def sign_in(config_dir: Path, state: dict[str, object]) -> None:
+ """What ``auth status --json`` answers for the account in ``config_dir``."""
+ config_dir.mkdir(parents=True, exist_ok=True)
+ (config_dir / "fake-auth.json").write_text(json.dumps(state), encoding="utf-8")
+
+
+def calls(config_dir: Path) -> list[list[str]]:
+ """Every argv the fake was started with for ``config_dir``'s account."""
+ try:
+ lines = (config_dir / "fake-calls.log").read_text(encoding="utf-8").splitlines()
+ except FileNotFoundError:
+ return []
+ return [json.loads(line) for line in lines if line.strip()]
+
+
+def main(argv: list[str]) -> int:
+ import tempfile
+
+ # Never the person's real ~/.claude: an unset account logs to a temp folder.
+ config_dir = Path(
+ os.environ.get("CLAUDE_CONFIG_DIR") or Path(tempfile.gettempdir()) / "fake-claude-unset"
+ )
+ config_dir.mkdir(parents=True, exist_ok=True)
+ with (config_dir / "fake-calls.log").open("a", encoding="utf-8") as log:
+ log.write(json.dumps(argv) + "\n")
+ if argv[:3] == ["auth", "status", "--json"]:
+ try:
+ print((config_dir / "fake-auth.json").read_text(encoding="utf-8"))
+ except FileNotFoundError:
+ print(json.dumps(LOGGED_OUT))
+ return 0
+ print("fake claude: unexpected invocation", file=sys.stderr)
+ return 3
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/tests/unit/agent_runtimes/test_claude_cli_route.py b/tests/unit/agent_runtimes/test_claude_cli_route.py
new file mode 100644
index 0000000000..4ac15ca535
--- /dev/null
+++ b/tests/unit/agent_runtimes/test_claude_cli_route.py
@@ -0,0 +1,193 @@
+"""An agent on the Claude subscription runs through the official Claude CLI only.
+
+Anthropic bills a Claude login sent to its HTTP API by a third-party app as
+Extra Usage, so the subscription seat never gets a gateway route, a bearer,
+or an API key in its place. The CLI is a fake process (``fake_claude_cli``)
+that answers ``claude auth status --json`` for the account directory it is
+started with, and fails any model call.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from dodaios import claude_auth
+from dodaios.agent_chat.catalog import API_KEY_ACCOUNT, SUBSCRIPTION_ACCOUNT
+from dodaios.agent_runtimes import gateway, model_map
+from dodaios.core import config
+from tests.fakes import fake_claude_cli
+
+_KEY = "sk-ant-api03-" + "fixture"
+
+
+def claude(monkeypatch, tmp_path):
+ """Claude only, no API key, the fake CLI installed; returns the default
+ account's directory (the app's own ``CLAUDE_CONFIG_DIR``)."""
+ monkeypatch.setattr(model_map, "_ENDPOINTS", {"claude-api": model_map._ENDPOINTS["claude-api"]})
+ secrets: dict[str, str | None] = {"key": None}
+ monkeypatch.setattr(config, "get_jarvis_agent_secret", lambda provider: None)
+ monkeypatch.setattr(
+ config, "resolve_provider_endpoint", lambda *args, **kwargs: SimpleNamespace(
+ credential=secrets["key"], base_url="https://api.anthropic.com", via_proxy=False,
+ ),
+ )
+ launcher = fake_claude_cli.install(tmp_path / "bin")
+ monkeypatch.setattr(
+ claude_auth.ClaudeAuthService, "_resolve_binary", lambda self: str(launcher)
+ )
+ claude_auth.clear_version_cache()
+ default = tmp_path / "claude-default"
+ default.mkdir()
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(default))
+ monkeypatch.setattr(gateway, "base_url", lambda: "http://127.0.0.1:1/api/runtime-gateway/v1")
+ gateway.reset()
+ yield SimpleNamespace(default=default, launcher=launcher, secrets=secrets)
+ gateway.reset()
+ claude_auth.clear_version_cache()
+
+
+def test_a_subscription_seat_routes_to_the_cli_never_the_gateway(claude):
+ fake_claude_cli.sign_in(claude.default, fake_claude_cli.SUBSCRIPTION)
+
+ route = model_map.route_for(None, "claude-api", "claude-fixture", agent_id="a1")
+
+ assert route.transport == "claude_cli"
+ assert route.api_key is None and route.base_url == ""
+ assert route.claude_binary == str(claude.launcher)
+ # Only the account selection reaches the runtime: no key, no bearer.
+ env = route.env()
+ assert env["CLAUDE_CONFIG_DIR"] == str(claude.default)
+ assert model_map.KEY_ENV_VAR not in env
+ assert not any("KEY" in name or "TOKEN" in name for name in env)
+ # No gateway token was minted, so nothing can be answered over HTTP.
+ assert gateway._GRANTS == {}
+ # The CLI was only asked whether it is signed in.
+ assert fake_claude_cli.calls(claude.default) == [["auth", "status", "--json"]]
+
+
+def test_pinned_subscription_wins_over_a_saved_key(claude):
+ claude.secrets["key"] = _KEY
+ fake_claude_cli.sign_in(claude.default, fake_claude_cli.SUBSCRIPTION)
+
+ assert model_map.route_for(None, "claude-api", "m", account_id=SUBSCRIPTION_ACCOUNT).transport \
+ == "claude_cli"
+ unpinned = model_map.route_for(None, "claude-api", "m", agent_id="a1")
+ assert unpinned.transport == "chat_completions" and unpinned.api_key != _KEY
+ pinned_key = model_map.route_for(None, "claude-api", "m", account_id=API_KEY_ACCOUNT)
+ assert pinned_key.transport == "chat_completions"
+
+
[email protected]("state", [fake_claude_cli.LOGGED_OUT, fake_claude_cli.API_KEY])
+def test_a_cli_not_signed_in_to_a_plan_is_an_honest_error_never_a_key(claude, state):
+ claude.secrets["key"] = _KEY # a key exists, and must not stand in
+ fake_claude_cli.sign_in(claude.default, state)
+
+ with pytest.raises(model_map.RouteUnavailable, match="not signed in to a Claude plan") as exc:
+ model_map.route_for(None, "claude-api", "m", account_id=SUBSCRIPTION_ACCOUNT)
+ assert "No API key was used" in str(exc.value)
+ assert gateway._GRANTS == {}
+
+
+def test_a_missing_cli_is_an_honest_error(claude, monkeypatch):
+ monkeypatch.setattr(claude_auth.ClaudeAuthService, "_resolve_binary", lambda self: None)
+
+ with pytest.raises(model_map.RouteUnavailable, match="Claude Code is not installed"):
+ model_map.route_for(None, "claude-api", "m", account_id=SUBSCRIPTION_ACCOUNT)
+ assert model_map.usable_providers(None) == []
+ assert model_map.access_choices() == {}
+
+
+def test_a_named_claude_account_is_probed_and_passed_to_the_runtime(claude):
+ from dodaios import agent_accounts
+
+ work = agent_accounts.create_account("claude", "Work")
+ fake_claude_cli.sign_in(work.config_dir, fake_claude_cli.SUBSCRIPTION)
+ # The default account is signed out: only the named one may answer.
+ fake_claude_cli.sign_in(claude.default, fake_claude_cli.LOGGED_OUT)
+
+ route = model_map.route_for(None, "claude-api", "m", account_id=work.id)
+
+ assert route.env()["CLAUDE_CONFIG_DIR"] == str(work.config_dir)
+ assert fake_claude_cli.calls(work.config_dir) == [["auth", "status", "--json"]]
+ assert fake_claude_cli.calls(claude.default) == []
+
+
+def test_pickers_offer_the_subscription_only_when_the_cli_is_signed_in(claude):
+ fake_claude_cli.sign_in(claude.default, fake_claude_cli.SUBSCRIPTION)
+ assert model_map.usable_providers(None) == ["claude-api"]
+ assert model_map.access_choices() == {"claude-api": ["subscription"]}
+
+ claude_auth.clear_version_cache() # forgets the cached auth status too
+ fake_claude_cli.sign_in(claude.default, fake_claude_cli.LOGGED_OUT)
+ claude.secrets["key"] = _KEY
+ assert model_map.access_choices() == {"claude-api": ["api"]}
+
+
+def test_prepare_route_keeps_the_cli_route_out_of_the_gateway(claude):
+ fake_claude_cli.sign_in(claude.default, fake_claude_cli.SUBSCRIPTION)
+
+ route = asyncio.run(model_map.prepare_route(None, "claude-api", "m", agent_id="a1"))
+
+ assert route.transport == "claude_cli" and route.api_key is None
+ assert gateway._GRANTS == {}
+
+
+def test_the_gateway_refuses_a_subscription_seat_instead_of_calling_http(claude, monkeypatch):
+ """A token minted while the agent ran on its key, then the key was removed:
+ the gateway must not answer it on the Claude login (or anything else)."""
+ claude.secrets["key"] = _KEY
+ token = gateway.grant_token("a1", "claude-api", "")
+ claude.secrets["key"] = None
+ built: list[str] = []
+ monkeypatch.setattr(gateway, "_new_brain", lambda provider, model: built.append(provider))
+ from dodaios.core.protocols import BrainRequest
+
+ grant = gateway.verify(token)
+ assert grant is not None
+
+ async def drain() -> None:
+ async for _delta in gateway._deltas(grant, "m", BrainRequest(messages=[])):
+ pass
+
+ with pytest.raises(gateway.GatewayError) as exc:
+ asyncio.run(drain())
+ assert exc.value.code == "claude_cli_only" and exc.value.status == 409
+ assert built == []
+
+
+def test_claude_login_never_reads_a_credential_file(claude, monkeypatch):
+ """The subscription check asks the CLI; it never opens the login itself."""
+ import dodaios.claude_credentials as credentials
+
+ def forbidden(*args, **kwargs):
+ pytest.fail("the Claude login must not be read by Dodaios")
+
+ monkeypatch.setattr(credentials, "freshest_claude_oauth", forbidden)
+ fake_claude_cli.sign_in(claude.default, fake_claude_cli.SUBSCRIPTION)
+
+ model_map.claude_login(SUBSCRIPTION_ACCOUNT)
+
+
+def test_the_fake_cli_launcher_is_a_real_process(tmp_path):
+ """Guard for the fake itself: it answers only ``auth status``."""
+ import subprocess
+
+ launcher = fake_claude_cli.install(tmp_path / "bin")
+ account = tmp_path / "acct"
+ fake_claude_cli.sign_in(account, fake_claude_cli.SUBSCRIPTION)
+ env = {**__import__("os").environ, "CLAUDE_CONFIG_DIR": str(account)}
+ status = subprocess.run(
+ [str(launcher), "auth", "status", "--json"], capture_output=True, text=True, env=env,
+ check=False,
+ )
+ model = subprocess.run(
+ [str(launcher), "-p", "hi"], capture_output=True, text=True, env=env, check=False,
+ )
+ assert '"loggedIn": true' in status.stdout
+ assert model.returncode == 3
+ assert Path(account / "fake-calls.log").is_file()
diff --git a/tests/unit/agent_runtimes/test_claude_cli_runtimes.py b/tests/unit/agent_runtimes/test_claude_cli_runtimes.py
new file mode 100644
index 0000000000..4aed4b3e0c
--- /dev/null
+++ b/tests/unit/agent_runtimes/test_claude_cli_runtimes.py
@@ -0,0 +1,144 @@
+"""What each runtime does with a Claude subscription route (``claude_cli``).
+
+OpenClaw runs it on its bundled ``claude-cli`` backend, with no Dodaios
+gateway provider at all; Hermes has no route there Dodaios installs and says
+so. Neither ever gets a key or a bearer for it.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from dodaios.agent_runtimes.base import RuntimeLaunch, RuntimeTurn, RuntimeUnavailable
+from dodaios.agent_runtimes.hermes import HermesRuntime
+from dodaios.agent_runtimes.model_map import KEY_ENV_VAR, ModelRoute
+from dodaios.agent_runtimes.openclaw import OpenClawRuntime
+
+_TOKEN = "gw-" + "token" # a fake Gateway token
+
+
+def _cli_route(tmp_path: Path) -> ModelRoute:
+ return ModelRoute(
+ provider="claude-api",
+ model="claude-fixture-5",
+ base_url="",
+ transport="claude_cli",
+ api_key=None,
+ claude_binary=str(tmp_path / "bin" / "claude"),
+ claude_env=(("CLAUDE_CONFIG_DIR", str(tmp_path / "acct")),),
+ )
+
+
+def _turn(tmp_path: Path, **overrides) -> RuntimeTurn:
+ values = {
+ "agent_id": "clawd",
+ "agent_name": "Clawd",
+ "session_id": "society:clawd",
+ "workspace": tmp_path,
+ "route": _cli_route(tmp_path),
+ "resume": None,
+ "auto_approve": True,
+ "mcp_url": "http://127.0.0.1:47820/api/control/mcp/",
+ "control_key": "control-key-xyz",
+ }
+ values.update(overrides)
+ return RuntimeTurn(**values)
+
+
+def test_openclaw_runs_the_subscription_on_its_claude_cli_backend(tmp_path):
+ config = OpenClawRuntime().config_for(_turn(tmp_path), port=4321, token=_TOKEN)
+
+ defaults = config["agents"]["defaults"]
+ assert defaults["model"] == {"primary": "anthropic/claude-fixture-5"}
+ assert defaults["models"] == {
+ "anthropic/claude-fixture-5": {"agentRuntime": {"id": "claude-cli"}},
+ }
+ # No provider pointing at Dodaios' gateway (or anywhere else over HTTP).
+ assert "models" not in config
+ text = repr(config)
+ assert KEY_ENV_VAR not in text and "runtime-gateway" not in text
+ # Dodaios' own MCP tools stay available, with their own approvals.
+ assert "mcp" in config
+ assert config["tools"]["exec"]["mode"] == "full"
+
+
+def test_openclaw_without_bypass_refuses_native_tools_instead_of_hanging(tmp_path):
+ ask = OpenClawRuntime().config_for(_turn(tmp_path, auto_approve=False), port=1, token=_TOKEN)
+ no_shell = OpenClawRuntime().config_for(
+ _turn(tmp_path, denied_native=frozenset({"shell"})), port=1, token=_TOKEN,
+ )
+
+ assert ask["tools"]["exec"]["mode"] == "deny"
+ assert {"exec", "process"} <= set(no_shell["tools"]["deny"])
+
+
+def test_an_api_key_route_on_openclaw_is_unchanged(tmp_path):
+ from tests.unit.agent_runtimes.test_runtime_configs import _turn as api_turn
+
+ config = OpenClawRuntime().config_for(api_turn(tmp_path), port=1, token=_TOKEN)
+ assert config["models"]["providers"]
+ assert config["agents"]["defaults"]["model"]["primary"].startswith("jarvis/")
+
+
+def test_the_claude_cli_route_carries_only_the_account_selection(tmp_path):
+ env = _cli_route(tmp_path).env()
+ assert env == {"CLAUDE_CONFIG_DIR": str(tmp_path / "acct")}
+
+
+def test_hermes_refuses_the_subscription_with_the_reason(tmp_path):
+ runtime = HermesRuntime()
+
+ with pytest.raises(RuntimeUnavailable, match="Hermes cannot run on the Claude subscription"):
+ asyncio.run(runtime.launch(_turn(tmp_path)))
+ assert asyncio.run(runtime.warm(_turn(tmp_path))) is False
+
+
+def test_a_cli_turn_plans_without_a_gateway_token(tmp_path, monkeypatch):
+ """The ACP runner watches gateway failures by token; the CLI route has none."""
+ from dodaios.agent_chat import runner_acp
+ from dodaios.agent_runtimes import gateway
+
+ turn = _turn(tmp_path)
+ released: list[str] = []
+
+ class Runtime:
+ label = "OpenClaw"
+
+ async def launch(self, turn: RuntimeTurn) -> RuntimeLaunch:
+ return RuntimeLaunch(
+ argv=["openclaw", "acp"], env={}, cwd=tmp_path, acp_resume=None,
+ release=lambda: released.append("slot"),
+ )
+
+ async def ready(*args):
+ return None
+
+ async def runtime_turn(*args, **kwargs):
+ return turn
+
+ async def agent(agent_id):
+ return SimpleNamespace(agent_id=agent_id)
+
+ monkeypatch.setattr(runner_acp, "driver", lambda name: Runtime())
+ monkeypatch.setattr(runner_acp, "_ready", ready)
+ monkeypatch.setattr(runner_acp, "_runtime_turn", runtime_turn)
+ monkeypatch.setattr(runner_acp, "_agent", agent)
+ gateway.reset()
+ handle = SimpleNamespace(
+ session=SimpleNamespace(session_id="society:clawd", permission_mode="bypass", effort=""),
+ turn_id="t1",
+ cancel=asyncio.Event(),
+ )
+
+ plan = asyncio.run(runner_acp.plan_runtime_turn(
+ handle, "openclaw-cli", prompt="hi", cwd=tmp_path, resume=None, identity=None,
+ ))
+
+ assert not plan.provider_failure.done()
+ assert gateway._FAILURES == {}
+ plan.after_turn()
+ assert released == ["slot"]
diff --git a/tests/unit/agent_runtimes/test_provider_availability.py b/tests/unit/agent_runtimes/test_provider_availability.py
deleted file mode 100644
index 4c2d5ffd7c..0000000000
--- a/tests/unit/agent_runtimes/test_provider_availability.py
+++ /dev/null
@@ -1,113 +0,0 @@
-"""The picker must not offer a login that runtime startup already rejects."""
-
-from types import SimpleNamespace
-
-import pytest
-
-from dodaios.agent_runtimes import model_map, provider_errors
-from dodaios.core import config
-
-
-def claude_only(monkeypatch):
- monkeypatch.setattr(model_map, "_ENDPOINTS", {"claude-api": model_map._ENDPOINTS["claude-api"]})
- monkeypatch.setattr(model_map, "claude_login_token", lambda: "fixture-login")
- monkeypatch.setattr(config, "get_jarvis_agent_secret", lambda provider: None)
- monkeypatch.setattr(
- config, "resolve_provider_endpoint", lambda *args, **kwargs: SimpleNamespace(
- credential=None, base_url="https://api.anthropic.com", via_proxy=False,
- ),
- )
- monkeypatch.setattr(provider_errors, "_REPORTS", {})
-
-
- {"is_enabled": False}, {"is_enabled": True, "spend_limit_reached": True},
-])
-def test_blocked_login_is_absent_from_every_picker_list(claude_only, monkeypatch, extra):
- calls = []
-
- def usage(token):
- calls.append(token)
- return {"extra_usage": extra}
-
- monkeypatch.setattr(provider_errors, "_claude_usage", usage)
- assert model_map.usable_providers(None) == []
- assert model_map.login_providers() == []
- assert model_map.access_choices() == {}
- assert calls == ["fixture-login"]
- with pytest.raises(model_map.RouteUnavailable, match="Extra Usage"):
- model_map.route_for(None, "claude-api", "fixture-model", account_id="subscription")
-
-
-def test_blocked_login_does_not_hide_a_separate_api_key(claude_only, monkeypatch):
- monkeypatch.setattr(config, "get_jarvis_agent_secret", lambda provider: "fixture-api-key")
- monkeypatch.setattr(provider_errors, "_claude_usage", lambda token: {
- "extra_usage": {"is_enabled": False},
- })
- assert model_map.usable_providers(None) == ["claude-api"]
- assert model_map.login_providers() == []
- assert model_map.access_choices() == {"claude-api": ["api"]}
- with pytest.raises(model_map.RouteUnavailable):
- model_map.route_for(None, "claude-api", "fixture-model", account_id="subscription")
-
-
[email protected]("usage", [None, {}, {"extra_usage": {"is_enabled": True}}])
-def test_unknown_or_enabled_usage_does_not_invent_a_block(claude_only, monkeypatch, usage):
- monkeypatch.setattr(provider_errors, "_claude_usage", lambda token: usage)
- assert model_map.usable_providers(None) == ["claude-api"]
- assert model_map.login_providers() == ["claude-api"]
- assert model_map.access_choices() == {"claude-api": ["subscription"]}
-
-
-def test_missing_login_never_requests_usage(claude_only, monkeypatch):
- monkeypatch.setattr(model_map, "claude_login_token", lambda: None)
-
- def unexpected(token):
- pytest.fail("A disconnected account must not request usage")
-
- monkeypatch.setattr(provider_errors, "_claude_usage", unexpected)
- assert model_map.usable_providers(None) == []
- assert model_map.login_providers() == []
- assert model_map.access_choices() == {}
-
-
-def test_usage_outage_is_cached_briefly_and_recovers(claude_only, monkeypatch):
- import time
-
- now = [100.0]
- calls = []
-
- def unavailable(token):
- calls.append(token)
- return None
-
- monkeypatch.setattr(time, "monotonic", lambda: now[0])
- monkeypatch.setattr(provider_errors, "_claude_usage", unavailable)
- assert model_map.usable_providers(None) == ["claude-api"]
- assert model_map.login_providers() == ["claude-api"]
- assert model_map.access_choices() == {"claude-api": ["subscription"]}
- assert calls == ["fixture-login"]
-
- now[0] += 11.0
- monkeypatch.setattr(provider_errors, "_claude_usage", lambda token: {
- "extra_usage": {"is_enabled": False},
- })
- assert model_map.usable_providers(None) == []
-
-
-def test_picker_recovers_after_extra_usage_is_enabled(claude_only, monkeypatch):
- import time
-
- now = [100.0]
- monkeypatch.setattr(time, "monotonic", lambda: now[0])
- monkeypatch.setattr(provider_errors, "_claude_usage", lambda token: {
- "extra_usage": {"is_enabled": False},
- })
- assert model_map.usable_providers(None) == []
- now[0] += 121.0
- monkeypatch.setattr(provider_errors, "_claude_usage", lambda token: {
- "extra_usage": {"is_enabled": True},
- })
- assert model_map.usable_providers(None) == ["claude-api"]
- assert model_map.access_choices() == {"claude-api": ["subscription"]}
diff --git a/tests/unit/agent_runtimes/test_provider_errors.py b/tests/unit/agent_runtimes/test_provider_errors.py
index df18e74b68..b602e0fbc5 100644
--- a/tests/unit/agent_runtimes/test_provider_errors.py
+++ b/tests/unit/agent_runtimes/test_provider_errors.py
@@ -1,10 +1,7 @@
"""Provider refusals a retry cannot fix reach Hermes / OpenClaw as what they are.
Measured live 2026-10-07: an empty OpenAI balance answers 429, OpenRouter 402,
-a stopped local server times out, and Anthropic refuses a Claude subscription
-used by Hermes or OpenClaw with a 400 ("Third-party apps now draw from your
-extra usage, not your plan limits") or a bare 429 while the plan has room.
-All of them used to read as "rate limited, try again in 30 s".
+and a stopped local server times out. All of them used to read as "rate limited, try again in 30 s".
"""
from __future__ import annotations
@@ -15,7 +12,7 @@ from typing import Any
import pytest
from dodaios.agent_runtimes import gateway, provider_errors
-from dodaios.agent_runtimes.provider_errors import classify, login_refusal
+from dodaios.agent_runtimes.provider_errors import classify
class ProviderStatusError(Exception):
@@ -31,15 +28,6 @@ class APITimeoutError(Exception):
"""Named like the SDKs' transport error; the name is the signal."""
-#: A stand-in Claude login bearer (not a credential).
-_BEARER = "login-bearer"
-
-_USAGE_ROOM = {
- "five_hour": {"utilization": 21.0, "resets_at": "2026-10-07T11:09:59+00:00"},
- "seven_day": {"utilization": 54.0, "resets_at": "2026-10-12T12:59:59+00:00"},
-}
-
-
def test_an_empty_openai_balance_is_billing_not_a_rate_limit() -> None:
exc = ProviderStatusError(
429,
@@ -174,8 +162,8 @@ def test_every_provider_failure_gets_an_actionable_status(exc, status, code) ->
def test_only_unrecoverable_failures_end_the_turn() -> None:
- terminal = {"billing", "extra_usage_off", "provider_auth", "claude_login_expired",
- "model_not_found", "invalid_tool_schema", "tools_unsupported", "rate_limited"}
+ terminal = {"billing", "provider_auth", "model_not_found", "invalid_tool_schema",
+ "tools_unsupported", "rate_limited"}
recoverable = {"context_length_exceeded", "timeout", "provider_overloaded",
"provider_error", "invalid_request", "provider_unreachable"}
assert all(provider_errors.is_terminal(code) for code in terminal)
@@ -194,62 +182,6 @@ def test_the_log_line_is_bounded_and_masks_credentials() -> None:
assert len(line) < 520
-def test_extra_usage_off_explains_a_claude_login_refusal() -> None:
- usage = {**_USAGE_ROOM, "extra_usage": {"is_enabled": False, "user_disabled": True}}
- refusal = login_refusal(usage, "claude-sonnet-5-5")
- assert refusal is not None
- assert (refusal.status, refusal.code) == (402, "extra_usage_off")
- assert "claude-sonnet-5-5" in refusal.message
- assert "Extra Usage" in refusal.message
-
-
-def test_a_spent_extra_usage_limit_is_named() -> None:
- usage = {**_USAGE_ROOM, "extra_usage": {"is_enabled": True, "spend_limit_reached": True}}
- refusal = login_refusal(usage, "claude-opus-5-5")
- assert refusal is not None and refusal.code == "extra_usage_spent"
-
-
-def test_anthropics_third_party_wording_is_extra_usage() -> None:
- body = {
- "type": "error",
- "error": {
- "type": "invalid_request_error",
- "message": "Third-party apps now draw from your extra usage, not your plan "
- "limits. Add more at claude.ai/settings/usage and keep going.",
- },
- }
- refusal = classify("claude-api", ProviderStatusError(400, body))
- assert refusal is not None
- assert (refusal.status, refusal.code) == (402, "extra_usage_off")
-
-
-def test_a_plan_window_says_nothing_about_third_party_use() -> None:
- usage = {"five_hour": {"utilization": 100.0}, "extra_usage": {"is_enabled": True}}
- assert login_refusal(usage, "claude-haiku-4-5") is None
-
-
-def test_a_blocked_login_is_known_before_any_model_call(monkeypatch) -> None:
- calls: list[str] = []
-
- def usage(token: str) -> dict[str, Any]:
- calls.append(token)
- return {**_USAGE_ROOM, "extra_usage": {"is_enabled": False}}
-
- monkeypatch.setattr(provider_errors, "_claude_usage", usage)
- monkeypatch.setattr(provider_errors, "_REPORTS", {})
- first = provider_errors.login_blocked(_BEARER, "claude-haiku-4-5")
- second = provider_errors.login_blocked(_BEARER, "claude-haiku-4-5")
- assert first is not None and first.code == "extra_usage_off"
- assert second == first
- assert calls == [_BEARER] # cached: routing asks once, not every turn
-
-
-def test_a_report_without_an_explanation_changes_nothing() -> None:
- usage = {**_USAGE_ROOM, "extra_usage": {"is_enabled": True, "spend_limit_reached": False}}
- assert login_refusal(usage, "claude-sonnet-5-5") is None
- assert login_refusal(None, "claude-sonnet-5-5") is None
-
-
def test_the_gateway_reports_the_refusal_not_a_rate_limit() -> None:
failure = gateway._failure(
"openai", ProviderStatusError(429, {"error": {"code": "insufficient_quota"}})
@@ -257,42 +189,6 @@ def test_the_gateway_reports_the_refusal_not_a_rate_limit() -> None:
assert (failure.status, failure.code) == (402, "billing")
-async def test_a_claude_login_429_is_explained_from_the_usage_report(monkeypatch) -> None:
- """The gateway's own plugin path: login answers, Anthropic says 429."""
- import dodaios.agent_runtimes.model_map as model_map
- import dodaios.core.config as config
- import dodaios.plugins.brain.claude_api as claude_api
- from dodaios.core.protocols import BrainMessage, BrainRequest
-
- class RefusingBrain:
- def __init__(self, model: str | None = None, *, auth_token: str | None = None) -> None:
- assert auth_token == _BEARER
-
- async def complete(self, request: Any) -> AsyncIterator[Any]:
- raise ProviderStatusError(429, {"error": {"type": "rate_limit_error"}})
- yield # pragma: no cover — makes this an async generator
-
- seen: list[str] = []
-
- def usage(token: str) -> dict[str, Any]:
- seen.append(token)
- return {**_USAGE_ROOM, "extra_usage": {"is_enabled": False}}
-
- monkeypatch.setattr(model_map, "login_route", lambda provider, account: (True, _BEARER))
- monkeypatch.setattr(config, "get_jarvis_agent_secret", lambda provider: None)
- monkeypatch.setattr(claude_api, "ClaudeAPIBrain", RefusingBrain)
- monkeypatch.setattr(provider_errors, "_claude_usage", usage)
- grant = gateway.Grant("agent-1", "claude-api", "subscription")
- request = BrainRequest(messages=(BrainMessage("user", "Hi"),), max_tokens=16)
-
- with pytest.raises(provider_errors.ProviderRefusal) as caught:
- async for _ in gateway._deltas(grant, "claude-sonnet-5-5", request):
- pass
- assert seen == [_BEARER]
- failure = gateway._failure("claude-api", caught.value)
- assert (failure.status, failure.code) == (402, "extra_usage_off")
-
-
async def test_a_non_streaming_subscription_answer_keeps_its_output(monkeypatch) -> None:
"""ChatGPT's backend streams the items and completes with an empty output."""
item = {"type": "message", "content": [{"type": "output_text", "text": "ok"}]}
@@ -314,23 +210,6 @@ async def test_a_non_streaming_subscription_answer_keeps_its_output(monkeypatch)
assert answer["output"] == [item]
-def test_a_route_refuses_a_blocked_claude_login_before_the_runtime_starts(monkeypatch) -> None:
- import dodaios.agent_runtimes.model_map as model_map
-
- monkeypatch.setattr(model_map, "login_token_for", lambda provider, account: _BEARER)
- blocked = provider_errors._extra_usage_off
- monkeypatch.setattr(provider_errors, "login_blocked", lambda token, model: blocked(model))
- with pytest.raises(model_map.RouteUnavailable, match="Extra Usage"):
- model_map._check_login_billing("claude-api", "claude-haiku-4-5", "")
-
-
-def test_an_api_key_route_never_reads_the_login(monkeypatch) -> None:
- import dodaios.agent_runtimes.model_map as model_map
-
- monkeypatch.setattr(model_map, "login_token_for", lambda provider, account: None)
- model_map._check_login_billing("claude-api", "claude-haiku-4-5", "api-key")
-
-
def test_a_system_message_moves_into_the_instructions() -> None:
"""ChatGPT's backend refuses system input items (OpenClaw sends one)."""
args = gateway.request_args(
diff --git a/tests/unit/agent_runtimes/test_provider_transport_regressions.py b/tests/unit/agent_runtimes/test_provider_transport_regressions.py
index f79229cc0b..be5c3ba0cb 100644
--- a/tests/unit/agent_runtimes/test_provider_transport_regressions.py
+++ b/tests/unit/agent_runtimes/test_provider_transport_regressions.py
@@ -111,21 +111,22 @@ async def test_gateway_never_marks_unfinished_provider_streams_complete(
assert signal.done()
-async def test_subscription_pin_cannot_fall_back_to_api_key_after_login_expires(
+async def test_subscription_pin_never_reaches_the_http_api_or_a_key(
monkeypatch, isolated_gateway,
):
+ """The Claude subscription runs through the Claude CLI only: the gateway
+ neither sends its login to Anthropic's HTTP API nor answers on the key."""
from dodaios.agent_chat import runner_api
from dodaios.agent_chat.catalog import SUBSCRIPTION_ACCOUNT
- from dodaios.agent_runtimes import model_map
from dodaios.core import config
- monkeypatch.setattr(model_map, "claude_login_token", lambda: None)
monkeypatch.setattr(config, "get_jarvis_agent_secret", lambda provider: "test-api-key")
called = []
monkeypatch.setattr(runner_api, "build_brain", lambda *args: called.append(args))
grant = gateway.Grant("agent", "claude-api", SUBSCRIPTION_ACCOUNT)
- with pytest.raises(Exception, match="Claude Code login"):
+ with pytest.raises(gateway.GatewayError) as refused:
await anext(gateway._deltas(grant, "claude-sonnet-4-6", BrainRequest(messages=())))
+ assert refused.value.code == "claude_cli_only"
assert called == []
@@ -186,7 +187,7 @@ async def test_selected_effort_reaches_api_brain(monkeypatch, isolated_gateway):
yield BrainDelta(content="OK", finish_reason="stop")
monkeypatch.setattr(config, "get_jarvis_agent_secret", lambda provider: None)
- monkeypatch.setattr(model_map, "login_route", lambda *args: (False, None))
+ monkeypatch.setattr(model_map, "uses_claude_cli", lambda *args: False)
monkeypatch.setattr(runner_api, "build_brain", lambda *args: Brain())
token = gateway.grant_token("agent", "ollama", require_active_turn=True)
gateway.watch_failure(token, effort="high")
@@ -283,7 +284,7 @@ async def test_claude_signed_tool_continuation_survives_openai_runtime(
wire.tool_arguments = '{"path":"a"}'
wire.thinking = True
monkeypatch.setattr(config, "get_jarvis_agent_secret", lambda provider: None)
- monkeypatch.setattr(model_map, "login_route", lambda *args: (False, None))
+ monkeypatch.setattr(model_map, "uses_claude_cli", lambda *args: False)
grant = gateway.Grant("agent", "claude-api")
body = {"model": "claude-sonnet-4-6", "messages": [{"role": "user", "content": "Read a"}]}
async with AsyncAnthropic(api_key="test-only", http_client=wire.client()) as client:
diff --git a/tests/unit/agent_runtimes/test_runtime_configs.py b/tests/unit/agent_runtimes/test_runtime_configs.py
index f0d2377abe..7d1bda8d5a 100644
--- a/tests/unit/agent_runtimes/test_runtime_configs.py
+++ b/tests/unit/agent_runtimes/test_runtime_configs.py
@@ -35,12 +35,10 @@ _GATEWAY = "http://127.0.0.1:47821/api/runtime-gateway/v1"
def gateway_up(monkeypatch):
"""Jarvis' gateway is listening, and this machine's Agents-tier keys stay out."""
import dodaios.core.config as config
- from dodaios.agent_runtimes import gateway, provider_errors
+ from dodaios.agent_runtimes import gateway
monkeypatch.setattr(gateway, "base_url", lambda: _GATEWAY)
monkeypatch.setattr(config, "get_jarvis_agent_secret", lambda provider: None)
- monkeypatch.setattr(provider_errors, "_claude_usage", lambda token: None)
- monkeypatch.setattr(provider_errors, "_REPORTS", {})
gateway.reset()
yield gateway
gateway.reset()
@@ -385,90 +383,79 @@ def test_a_rate_limited_route_refuses_before_starting_a_runtime(gateway_up):
route_for(_cfg(), "openai", "m", agent_id="a", session_id="society:a")
-def test_chat_and_routine_routes_have_stable_separate_failure_scopes(gateway_up):
- with override_provider_secrets({"openai": _SECRET}):
- routes = [route_for(_cfg(), "openai", "m", agent_id="a", session_id=sid)
- for sid in ("society:a", "society:a:routine:r1", "society:a:routine:r2")]
- assert routes[0].api_key != routes[1].api_key
- assert routes[1].api_key == routes[2].api_key
-
-
-def test_a_rate_limited_route_refuses_before_starting_a_runtime(gateway_up):
- gateway = gateway_up
- grant = gateway.Grant("a", "openai")
- gateway._report_failure(
- grant, "m", gateway.GatewayError("limited", status=429, retry_after=60), None,
- )
- with override_provider_secrets({"openai": _SECRET}):
- with pytest.raises(RouteUnavailable, match="HTTP 429"):
- route_for(_cfg(), "openai", "m", agent_id="a", session_id="society:a")
-
-
def test_a_missing_key_is_reported_in_plain_words(gateway_up):
with override_provider_secrets({"openrouter": None}), pytest.raises(RouteUnavailable) as err:
route_for(_cfg(), "openrouter", "some/model")
assert "API key" in str(err.value)
-def test_a_claude_login_is_not_an_api_key(gateway_up, monkeypatch):
- import dodaios.agent_runtimes.model_map as model_map
+def _claude_cli(monkeypatch, tmp_path: Path, state: dict) -> Path:
+ """The fake Claude CLI, signed in as ``state`` for the default account."""
+ from dodaios import claude_auth
+ from tests.fakes import fake_claude_cli
- monkeypatch.setattr(model_map, "claude_login_token", lambda: None)
+ launcher = fake_claude_cli.install(tmp_path / "claude-bin")
+ monkeypatch.setattr(
+ claude_auth.ClaudeAuthService, "_resolve_binary", lambda self: str(launcher)
+ )
+ claude_auth.clear_version_cache()
+ account = tmp_path / "claude-account"
+ fake_claude_cli.sign_in(account, state)
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(account))
+ return account
+
+
+def test_a_claude_login_is_not_an_api_key(gateway_up, monkeypatch, tmp_path):
+ from tests.fakes import fake_claude_cli
+
+ _claude_cli(monkeypatch, tmp_path, fake_claude_cli.LOGGED_OUT)
login = "sk-ant-" + "oat01-" + "x" * 20
with override_provider_secrets({"claude-api": login}), pytest.raises(RouteUnavailable):
route_for(_cfg(), "claude-api", "claude-sonnet-5")
with override_provider_secrets({"claude-api": _SECRET}):
assert route_for(_cfg(), "claude-api", "claude-sonnet-5").transport == "chat_completions"
- assert model_map.login_token_for("claude-api") is None
-def test_claude_without_a_key_runs_on_the_claude_code_login(gateway_up, monkeypatch):
- import dodaios.agent_runtimes.model_map as model_map
+def test_claude_without_a_key_runs_on_the_claude_cli(gateway_up, monkeypatch, tmp_path):
+ from tests.fakes import fake_claude_cli
- live = "sk-ant-" + "oat01-" + "y" * 20
- monkeypatch.setattr(model_map, "claude_login_token", lambda: live)
+ account = _claude_cli(monkeypatch, tmp_path, fake_claude_cli.SUBSCRIPTION)
with override_provider_secrets({"claude-api": None}):
route = route_for(_cfg(), "claude-api", "claude-sonnet-5", agent_id="agent-1")
- assert model_map.login_token_for("claude-api") == live
- assert model_map.login_providers() == ["claude-api"]
- # The runtime only ever holds Jarvis' gateway token, never the login.
- assert route.transport == "chat_completions" and route.base_url == _GATEWAY
- assert route.api_key != live
- assert gateway_up.verify(route.api_key or "") == gateway_up.Grant(
- "agent-1", "claude-api", "", require_active_turn=True,
- )
- # Every other provider keeps needing its own key.
- assert model_map.login_token_for("openai") is None
+ # The runtime runs the official CLI: no gateway token, no key, no bearer.
+ assert route.transport == "claude_cli" and route.api_key is None
+ assert route.env()["CLAUDE_CONFIG_DIR"] == str(account)
+ assert set(route.env()) <= {"CLAUDE_CONFIG_DIR", "USER"}
+ assert gateway_up._GRANTS == {}
-def test_an_agent_can_pin_claude_to_the_key_or_the_login(gateway_up, monkeypatch):
- import dodaios.agent_runtimes.model_map as model_map
+def test_an_agent_can_pin_claude_to_the_key_or_the_subscription(gateway_up, monkeypatch, tmp_path):
from dodaios.agent_chat.catalog import API_KEY_ACCOUNT, SUBSCRIPTION_ACCOUNT
+ from dodaios.agent_runtimes import model_map
+ from tests.fakes import fake_claude_cli
- live = "sk-ant-" + "oat01-" + "z" * 20
- monkeypatch.setattr(model_map, "claude_login_token", lambda: live)
+ account = _claude_cli(monkeypatch, tmp_path, fake_claude_cli.SUBSCRIPTION)
with override_provider_secrets({"claude-api": _SECRET}):
# Both ways work: the dialog offers both, the key stays the default.
assert model_map.access_choices() == {"claude-api": ["api", "subscription"]}
- assert model_map.login_token_for("claude-api") is None
- assert model_map.login_token_for("claude-api", API_KEY_ACCOUNT) is None
- assert model_map.login_token_for("claude-api", SUBSCRIPTION_ACCOUNT) == live
+ assert not model_map.uses_claude_cli("claude-api")
+ assert not model_map.uses_claude_cli("claude-api", API_KEY_ACCOUNT)
+ assert model_map.uses_claude_cli("claude-api", SUBSCRIPTION_ACCOUNT)
route = route_for(
_cfg(), "claude-api", "claude-sonnet-5", agent_id="a", account_id=SUBSCRIPTION_ACCOUNT
)
- grant = gateway_up.verify(route.api_key or "")
- assert grant == gateway_up.Grant(
- "a", "claude-api", SUBSCRIPTION_ACCOUNT, require_active_turn=True,
- )
+ assert route.transport == "claude_cli"
with override_provider_secrets({"claude-api": None}):
assert model_map.access_choices() == {"claude-api": ["subscription"]}
- assert model_map.login_token_for("claude-api", API_KEY_ACCOUNT) is None
with pytest.raises(RouteUnavailable, match="API key"):
route_for(_cfg(), "claude-api", "claude-sonnet-5", account_id=API_KEY_ACCOUNT)
- monkeypatch.setattr(model_map, "claude_login_token", lambda: None)
+ fake_claude_cli.sign_in(account, fake_claude_cli.LOGGED_OUT)
+ from dodaios import claude_auth
+
+ claude_auth.clear_version_cache()
with override_provider_secrets({"claude-api": _SECRET}):
assert model_map.access_choices() == {"claude-api": ["api"]}
- with pytest.raises(RouteUnavailable, match="Claude Code login"):
+ with pytest.raises(RouteUnavailable, match="not signed in"):
route_for(_cfg(), "claude-api", "claude-sonnet-5", account_id=SUBSCRIPTION_ACCOUNT)
diff --git a/tests/unit/agent_runtimes/test_runtime_gateway.py b/tests/unit/agent_runtimes/test_runtime_gateway.py
index 5fdca0773a..f4bfe00dd5 100644
--- a/tests/unit/agent_runtimes/test_runtime_gateway.py
+++ b/tests/unit/agent_runtimes/test_runtime_gateway.py
@@ -610,21 +610,30 @@ def test_a_subscription_overflow_mid_stream_keeps_its_code(fake, guarded, monkey
assert failed[0]["response"]["error"]["code"] == "context_length_exceeded"
-async def test_an_expired_claude_login_says_how_to_renew_it(monkeypatch) -> None:
- import dodaios.agent_runtimes.model_map as model_map
+async def test_a_claude_subscription_seat_is_refused_not_billed(monkeypatch) -> None:
+ """No API key saved: the seat is the Claude subscription, which only the
+ Claude CLI may use. The gateway says so instead of sending the login to
+ Anthropic's HTTP API (billed as Extra Usage)."""
import dodaios.core.config as config
- from dodaios.agent_runtimes.provider_errors import ProviderRefusal
+ from dodaios.agent_chat import runner_api
from dodaios.core.protocols import BrainMessage, BrainRequest
- monkeypatch.setattr(model_map, "login_route", lambda provider, account: (True, None))
monkeypatch.setattr(config, "get_jarvis_agent_secret", lambda provider: None)
+ monkeypatch.setattr(
+ config, "resolve_provider_endpoint", lambda *args, **kwargs: SimpleNamespace(
+ credential=None, base_url="https://api.anthropic.com", via_proxy=False,
+ ),
+ )
+ built = []
+ monkeypatch.setattr(runner_api, "build_brain", lambda *args: built.append(args))
request = BrainRequest(messages=(BrainMessage("user", "Hi"),), max_tokens=16)
- with pytest.raises(ProviderRefusal) as caught:
+ with pytest.raises(gateway.GatewayError) as caught:
async for _ in gateway._deltas(gateway.Grant("a", "claude-api"), "claude-x", request):
pass
failure = gateway._failure("claude-api", caught.value)
- assert (failure.status, failure.code) == (401, "claude_login_expired")
- assert "Open Claude Code" in str(failure)
+ assert (failure.status, failure.code) == (409, "claude_cli_only")
+ assert "Claude Code" in str(failure) and "No API key" in str(failure)
+ assert built == []
async def test_a_request_the_subscription_client_refuses_is_a_400_not_a_retry():
diff --git a/tests/unit/agent_runtimes/test_runtime_manager.py b/tests/unit/agent_runtimes/test_runtime_manager.py
index 5941715048..68e1d4c59d 100644
--- a/tests/unit/agent_runtimes/test_runtime_manager.py
+++ b/tests/unit/agent_runtimes/test_runtime_manager.py
@@ -154,11 +154,12 @@ async def test_unknown_runtimes_are_refused(fakes):
def test_routes_list_status_and_start_jobs(fakes, monkeypatch):
- import dodaios.agent_runtimes.model_map as model_map
+ import dodaios.claude_auth as claude_auth
import dodaios.ui.web.agent_runtime_routes as routes
- monkeypatch.setattr(model_map, "claude_login_token", lambda: None)
- routes._USABLE_CACHE[:] = [float("-inf"), [], []]
+ # No Claude Code: no Claude subscription seat.
+ monkeypatch.setattr(claude_auth.ClaudeAuthService, "_resolve_binary", lambda self: None)
+ routes._USABLE_CACHE[:] = [float("-inf"), [], {}]
app = FastAPI()
app.include_router(router)
app.state.config = SimpleNamespace(brain=SimpleNamespace(providers={}))
@@ -263,11 +264,18 @@ def test_the_ensure_route_starts_what_is_needed(unset):
assert body["job"]["kind"] == "install"
-def test_a_claude_login_in_the_api_key_slot_is_not_an_api_key(fakes, monkeypatch):
- import dodaios.agent_runtimes.model_map as model_map
+def test_a_claude_login_in_the_api_key_slot_is_not_an_api_key(fakes, monkeypatch, tmp_path):
+ import dodaios.claude_auth as claude_auth
import dodaios.ui.web.agent_runtime_routes as routes
from dodaios.agent_runtimes.model_map import RouteUnavailable, route_for
+ from tests.fakes import fake_claude_cli
+ launcher = fake_claude_cli.install(tmp_path / "bin")
+ monkeypatch.setattr(
+ claude_auth.ClaudeAuthService, "_resolve_binary", lambda self: str(launcher)
+ )
+ account = tmp_path / "claude-account"
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(account))
config = SimpleNamespace(brain=SimpleNamespace(providers={}))
app = FastAPI()
app.include_router(router)
@@ -275,36 +283,27 @@ def test_a_claude_login_in_the_api_key_slot_is_not_an_api_key(fakes, monkeypatch
login = "sk-ant-" + "oat01-" + "x" * 20
secrets = {"openai": None, "claude-api": login, "openrouter": None, "grok": None,
"nvidia": None, "gemini": None}
- # No live Claude Code login: Claude is not offered.
- monkeypatch.setattr(model_map, "claude_login_token", lambda: None)
- routes._USABLE_CACHE[:] = [float("-inf"), [], []]
+ # Claude Code is not signed in: Claude is not offered, and the login in
+ # the key slot is never used as a key.
+ fake_claude_cli.sign_in(account, fake_claude_cli.LOGGED_OUT)
+ claude_auth.clear_version_cache()
+ routes._USABLE_CACHE[:] = [float("-inf"), [], {}]
with override_provider_secrets(secrets):
body = TestClient(app).get("/api/agent-runtimes").json()
- with pytest.raises(RouteUnavailable, match="Claude Code login"):
+ with pytest.raises(RouteUnavailable, match="not signed in"):
route_for(config, "claude-api", "claude-sonnet-5-5")
assert "claude-api" not in body["supported_providers"]
- assert body["login_providers"] == []
- # A live login: Claude is offered, marked as running on the login.
- import dodaios.agent_runtimes.provider_errors as provider_errors
-
- monkeypatch.setattr(model_map, "claude_login_token", lambda: login)
- monkeypatch.setattr(provider_errors, "_REPORTS", {})
- monkeypatch.setattr(provider_errors, "_claude_usage", lambda token: {})
- routes._USABLE_CACHE[:] = [float("-inf"), [], []]
+ # Signed in to a plan: Claude is offered, on the plan, never as Extra Usage.
+ fake_claude_cli.sign_in(account, fake_claude_cli.SUBSCRIPTION)
+ claude_auth.clear_version_cache()
+ routes._USABLE_CACHE[:] = [float("-inf"), [], {}]
with override_provider_secrets(secrets):
body = TestClient(app).get("/api/agent-runtimes").json()
assert "claude-api" in body["supported_providers"]
- assert body["login_providers"] == ["claude-api"]
+ assert body["access"] == {"claude-api": ["subscription"]}
+ assert body["login_providers"] == []
assert body["access_blocked"] == {}
- # Extra Usage off: the way exists, the dialog shows it disabled with why.
- monkeypatch.setattr(provider_errors, "_REPORTS", {})
- monkeypatch.setattr(
- provider_errors, "_claude_usage", lambda token: {"extra_usage": {"is_enabled": False}}
- )
- routes._USABLE_CACHE[:] = [float("-inf"), [], []]
- with override_provider_secrets(secrets):
- body = TestClient(app).get("/api/agent-runtimes").json()
- assert body["access_blocked"] == {"claude-api": {"subscription": "extra_usage_off"}}
+ claude_auth.clear_version_cache()
# ------------------------------------------------- gate, prepare, rollback
diff --git a/tests/unit/society/test_seat_brain_runtime.py b/tests/unit/society/test_seat_brain_runtime.py
index e62385197c..3d17d32b6d 100644
--- a/tests/unit/society/test_seat_brain_runtime.py
+++ b/tests/unit/society/test_seat_brain_runtime.py
@@ -29,11 +29,11 @@ def claude_code_installed(monkeypatch):
def _login(monkeypatch, *, live: bool) -> list[tuple[str, str]]:
asked: list[tuple[str, str]] = []
- def login_token_for(provider: str, account_id: str = "") -> str | None:
+ def uses_claude_cli(provider: str, account_id: str = "") -> bool:
asked.append((provider, account_id))
- return "sk-ant-oat-test" if live else None
+ return live
- monkeypatch.setattr(model_map, "login_token_for", login_token_for)
+ monkeypatch.setattr(model_map, "uses_claude_cli", uses_claude_cli)
return asked