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: detect native Claude subscription auth

Ruben Lütke62ec06bb27d6
diff --git a/jarvis/claude_auth.py b/jarvis/claude_auth.py
index 69a44f9855..fb18ff3fba 100644
--- a/jarvis/claude_auth.py
+++ b/jarvis/claude_auth.py
@@ -2,27 +2,16 @@
Personal Jarvis talks to Anthropic's ``claude`` (Claude Code) CLI in two roles:
-* **Subagent** (heavy-task worker) via the ``claude`` binary using the **Claude
- Max subscription** (``claude`` stores an OAuth bearer in
- ``<config dir>/.credentials.json``, resolved across all candidate config
- dirs by :mod:`jarvis.claude_credentials`; no per-call billing — it runs
- against the plan's included usage).
+* **Jarvis-Agent** (heavy-task worker) via the ``claude`` binary using a Claude
+ subscription login (no per-call API billing).
* **Brain provider** via the Anthropic Messages API using an **Anthropic API key**
(separate, billed per token on the Anthropic account).
-This module reports an honest snapshot of the CLI's own auth state (subscription
-OAuth vs API key), and exposes the connected account email + subscription tier so
-the UI can render "Connected as <email>" exactly like the Codex / Antigravity
-subscription cards. It is the Anthropic sibling of :mod:`jarvis.codex_auth` and
-:mod:`jarvis.google_cli.auth_service`.
-
-Email source: ``claude`` keeps the access bearer (no identity) in the
-credentials file, but the signed-in account identity lives in a SEPARATE
-file, ``.claude.json`` under ``oauthAccount`` (``emailAddress``,
-``displayName``, ``organizationName``) — the sibling ``~/.claude.json`` for
-the default config dir, or inside a custom ``CLAUDE_CONFIG_DIR``. The
-subscription tier (``max`` / ``pro``) is in the credentials file under
-``claudeAiOauth.subscriptionType``.
+The CLI's own ``auth status --json`` command is the primary source of truth.
+That matters cross-platform: current Claude Code stores credentials in the
+macOS Keychain, while Linux, Windows, and older releases may expose a
+``.credentials.json`` file. The file parser remains as a compatibility fallback
+when an older CLI has no auth-status command or the probe cannot run.
Cross-platform (CLOUD.md Rule #1): pure stdlib, ``pathlib``-only, degrades to a
clean "not installed" / "not connected" snapshot on any host where the ``claude``
@@ -37,11 +26,15 @@ account email and subscription tier.
"""
from __future__ import annotations
+import getpass
import json
import logging
import os
+import shutil
import subprocess
import sys
+import time
+from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -63,11 +56,17 @@ _BINARY_CANDIDATES: tuple[str, ...] = ("claude", "claude.cmd", "claude.exe")
# Process-lifetime cache of ``claude --version`` keyed by resolved binary path.
# The version is invariant while the app runs, but a cold Node-shim spawn is the
-# single most expensive part of ``status()``; caching it keeps every later
-# status() a pure file read. A failed probe is cached too, so an absent/hanging
-# claude never re-pays the timeout.
+# single most expensive part of ``status()``; caching it leaves only the short-
+# TTL auth probe on later calls. A failed version probe is cached too, so an
+# absent/hanging Claude install never re-pays that timeout.
_VERSION_CACHE: dict[str, str | None] = {}
_AUTH_LOGIN_CACHE: dict[str, bool] = {}
+_AUTH_LOGOUT_CACHE: dict[str, bool] = {}
+_AUTH_STATUS_CACHE: dict[
+ tuple[str, str, str, str, str], tuple[float, ClaudeCliAuthSnapshot | None]
+] = {}
+_SAFE_MODE_CACHE: dict[tuple[str, ...], bool] = {}
+_AUTH_STATUS_TTL_S = 5.0
def claude_install_command(platform: str | None = None) -> str:
@@ -87,9 +86,12 @@ def claude_install_hint(platform: str | None = None) -> str:
def clear_version_cache() -> None:
- """Drop all cached ``claude --version`` results (tests / after a re-install)."""
+ """Drop cached Claude CLI probes (tests / install or login changes)."""
_VERSION_CACHE.clear()
_AUTH_LOGIN_CACHE.clear()
+ _AUTH_LOGOUT_CACHE.clear()
+ _AUTH_STATUS_CACHE.clear()
+ _SAFE_MODE_CACHE.clear()
# ----------------------------------------------------------------------
@@ -142,6 +144,138 @@ def _subscription_label(sub_type: str | None) -> str:
return f"Claude {sub_type}"
+@dataclass(frozen=True)
+class ClaudeCliAuthSnapshot:
+ """Display-safe result from ``claude auth status --json``.
+
+ The command may include identity metadata, but never returns the OAuth
+ bearer. Keep this type deliberately narrow so callers cannot accidentally
+ turn an auth probe into a credential transport.
+ """
+
+ logged_in: bool
+ auth_method: str | None = None
+ subscription_type: str | None = None
+ api_provider: str | None = None
+ email: str | None = None
+
+
+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:
+ """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.
+ """
+ if os.name != "posix" or os.environ.get("USER"):
+ return None
+ try:
+ user = getpass.getuser().strip()
+ except (OSError, KeyError):
+ return None
+ if not user:
+ return None
+ env = dict(os.environ)
+ env["USER"] = user
+ return env
+
+
+def _parse_cli_auth_status(raw: str) -> ClaudeCliAuthSnapshot | None:
+ """Parse Claude's JSON auth status, tolerating a harmless banner line."""
+ candidates = [raw.strip(), *(line.strip() for line in reversed(raw.splitlines()))]
+ for candidate in candidates:
+ if not candidate:
+ continue
+ try:
+ data = json.loads(candidate)
+ except (TypeError, ValueError):
+ continue
+ if not isinstance(data, dict) or not isinstance(data.get("loggedIn"), bool):
+ continue
+ return ClaudeCliAuthSnapshot(
+ logged_in=data["loggedIn"],
+ auth_method=_optional_text(data.get("authMethod")),
+ subscription_type=_optional_text(data.get("subscriptionType")),
+ api_provider=_optional_text(data.get("apiProvider")),
+ email=_optional_text(data.get("email")),
+ )
+ return None
+
+
+def claude_cli_argv_prefix(binary: str) -> list[str]:
+ """Return a shell-free argv prefix for a resolved Claude CLI binary.
+
+ Windows npm installs expose ``claude.cmd``. Running the adjacent JavaScript
+ entry point through Node avoids ``cmd.exe`` quoting and metacharacter bugs;
+ native binaries and shims on macOS/Linux are invoked directly.
+ """
+ path = Path(binary)
+ node = shutil.which("node") or shutil.which("node.exe")
+ if node:
+ cli_dir = path.resolve().parent
+ for candidate in (
+ cli_dir / "node_modules" / "@anthropic-ai" / "claude-code" / "cli.js",
+ cli_dir / "node_modules" / "@anthropic-ai" / "claude-code" / "cli.mjs",
+ cli_dir / "cli.js",
+ cli_dir / "claude.mjs",
+ ):
+ try:
+ if candidate.is_file():
+ return [node, str(candidate)]
+ except OSError:
+ continue
+ return [binary]
+
+
+def claude_cli_supports_safe_mode(argv_prefix: Sequence[str]) -> bool:
+ """Capability-probe Claude's customization-free, auth-preserving mode.
+
+ ``--safe-mode`` lets a worker keep the user's native login (including the
+ macOS Keychain) while disabling user hooks, plugins, skills, and project
+ instructions. Older CLIs fall back to the isolated-config/token path.
+ """
+ key = tuple(argv_prefix)
+ if key in _SAFE_MODE_CACHE:
+ return _SAFE_MODE_CACHE[key]
+ try:
+ proc = subprocess.run(
+ [*key, "--help"],
+ capture_output=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=4.0,
+ text=True,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ output = f"{proc.stdout or ''}\n{proc.stderr or ''}"
+ supported = proc.returncode == 0 and "--safe-mode" in output
+ except (OSError, subprocess.SubprocessError):
+ supported = False
+ _SAFE_MODE_CACHE[key] = supported
+ return supported
+
+
+def claude_native_auth_env(env: Mapping[str, str]) -> dict[str, str]:
+ """Expose the user's real Claude auth store to a safe-mode subprocess.
+
+ ``build_worker_env`` points ``CLAUDE_CONFIG_DIR`` at a hook-free mission
+ directory for older CLIs. Safe mode itself disables customizations, so a
+ modern CLI instead restores the user's custom config directory (when one is
+ configured) or removes the mission override to use the platform default.
+ """
+ result = dict(env)
+ user_config_dir = os.environ.get("CLAUDE_CONFIG_DIR", "").strip()
+ if user_config_dir:
+ result["CLAUDE_CONFIG_DIR"] = user_config_dir
+ else:
+ result.pop("CLAUDE_CONFIG_DIR", None)
+ return result
+
+
# ----------------------------------------------------------------------
# Status snapshot
# ----------------------------------------------------------------------
@@ -194,7 +328,7 @@ class ClaudeAuthService:
``api_key_present`` is injected by the caller (provider routes already know
whether a stored Anthropic API key exists) so this module stays free of the
- credential-manager import and remains a pure auth-file reader.
+ credential-manager import and never reads or returns a stored API key.
"""
def __init__(
@@ -210,8 +344,6 @@ class ClaudeAuthService:
def _resolve_binary(self) -> str | None:
"""Full path to the ``claude`` binary, or ``None`` when absent."""
- import shutil
-
# A CLI installed AFTER app start (or into a dir the GUI PATH never
# had, e.g. the native installer's ~/.local/bin) must still be found —
# idempotent stat probes, no subprocess.
@@ -237,7 +369,7 @@ class ClaudeAuthService:
return _VERSION_CACHE[binary]
try:
proc = subprocess.run(
- [binary, "--version"],
+ [*self._cli_argv_prefix(binary), "--version"],
capture_output=True,
encoding="utf-8",
errors="replace",
@@ -253,13 +385,56 @@ class ClaudeAuthService:
_VERSION_CACHE[binary] = version
return version
+ def _cli_argv_prefix(self, binary: str) -> list[str]:
+ """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:
+ """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.
+ """
+ prefix = self._cli_argv_prefix(binary)
+ cache_key = (
+ "\0".join(prefix),
+ os.environ.get("CLAUDE_CONFIG_DIR", ""),
+ os.environ.get("HOME", ""),
+ os.environ.get("USERPROFILE", ""),
+ os.environ.get("USER", ""),
+ )
+ now = time.monotonic()
+ cached = _AUTH_STATUS_CACHE.get(cache_key)
+ if cached is not None and now - cached[0] < _AUTH_STATUS_TTL_S:
+ return cached[1]
+ try:
+ proc = subprocess.run(
+ [*prefix, "auth", "status", "--json"],
+ env=_cli_credential_env(),
+ capture_output=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=6.0,
+ text=True,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ snapshot = _parse_cli_auth_status(proc.stdout or "")
+ if snapshot is None:
+ snapshot = _parse_cli_auth_status(proc.stderr or "")
+ except (OSError, subprocess.SubprocessError):
+ snapshot = None
+ _AUTH_STATUS_CACHE[cache_key] = (now, snapshot)
+ return snapshot
+
def _supports_auth_login(self, binary: str) -> bool:
"""Whether this installed CLI exposes the modern ``auth login`` command."""
if binary in _AUTH_LOGIN_CACHE:
return _AUTH_LOGIN_CACHE[binary]
try:
proc = subprocess.run(
- [binary, "auth", "login", "--help"],
+ [*self._cli_argv_prefix(binary), "auth", "login", "--help"],
capture_output=True,
encoding="utf-8",
errors="replace",
@@ -273,14 +448,35 @@ class ClaudeAuthService:
_AUTH_LOGIN_CACHE[binary] = supported
return supported
+ def _supports_auth_logout(self, binary: str) -> bool:
+ """Whether the CLI can remove its own platform-native credentials."""
+ if binary in _AUTH_LOGOUT_CACHE:
+ return _AUTH_LOGOUT_CACHE[binary]
+ try:
+ proc = subprocess.run(
+ [*self._cli_argv_prefix(binary), "auth", "logout", "--help"],
+ capture_output=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=4.0,
+ text=True,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ supported = proc.returncode == 0
+ except (OSError, subprocess.SubprocessError):
+ supported = False
+ _AUTH_LOGOUT_CACHE[binary] = supported
+ return supported
+
def _login_argv(self, binary: str) -> list[str]:
"""Capability-selected login argv, with a first-run fallback for old CLIs."""
+ prefix = self._cli_argv_prefix(binary)
if self._supports_auth_login(binary):
- return [binary, "auth", "login", "--claudeai"]
+ return [*prefix, "auth", "login", "--claudeai"]
# Older Claude Code releases have no auth subcommand. A bare interactive
# start is their documented first-run login flow; passing ``/login`` as
# a positional argv value incorrectly treats it as an initial prompt.
- return [binary]
+ return prefix
def _credentials_path(self) -> Path:
return Path(os.path.expanduser("~/.claude/.credentials.json"))
@@ -345,11 +541,59 @@ class ClaudeAuthService:
)
version = self._probe_version(binary)
+ cli_auth = self._probe_cli_auth(binary)
snapshot = self._oauth_snapshot()
- sub_type = snapshot.subscription_type
+ sub_type = (
+ cli_auth.subscription_type
+ if cli_auth is not None and cli_auth.subscription_type
+ else snapshot.subscription_type
+ )
oauth_expired = snapshot.status == "expired"
- if snapshot.status == "valid":
+ if cli_auth is not None and cli_auth.logged_in:
+ method = (cli_auth.auth_method or "").lower().replace("-", "_")
+ if "api" in method and "key" in method:
+ log.info("claude status: installed=True connected=True mode=api_key")
+ return ClaudeAuthStatus(
+ installed=True,
+ connected=True,
+ mode="api_key",
+ message="Connected via Anthropic API key.",
+ version=version,
+ account_label="Anthropic API key",
+ user_email=cli_auth.email,
+ binary_path=binary,
+ api_key_present=self._api_key_present,
+ )
+
+ file_email, _name = _account_from_claude_json(
+ _read_json(self._identity_path(snapshot.config_dir))
+ )
+ email = cli_auth.email or file_email
+ label = _subscription_label(sub_type)
+ message = f"Connected via {label} ({email})." if email else (
+ f"Connected via {label}."
+ )
+ log.info(
+ "claude status: installed=True connected=True mode=subscription"
+ )
+ return ClaudeAuthStatus(
+ installed=True,
+ connected=True,
+ mode="subscription",
+ message=message,
+ version=version,
+ account_label=label,
+ user_email=email,
+ subscription_type=sub_type,
+ binary_path=binary,
+ api_key_present=self._api_key_present,
+ )
+
+ # Older Claude Code releases have no machine-readable auth command.
+ # Preserve the file-backed path for Linux/Windows and legacy installs,
+ # but never let a stale file override an explicit ``loggedIn: false``.
+ if cli_auth is None and snapshot.status == "valid":
email, _name = _account_from_claude_json(
_read_json(self._identity_path(snapshot.config_dir))
)
@@ -389,7 +633,7 @@ class ClaudeAuthService:
if oauth_expired:
# Honest expired-state (2026-07-06): the bearer exists but died in
# place — presence-only reporting showed a green "Connected via
- # Claude Max" card while every subagent spawn 401'd. The ADVICE
+ # Claude Max" card while every Jarvis-Agent spawn 401'd. The ADVICE
# matters though: a stale ACCESS token refreshes automatically the
# next time `claude` runs — a full re-login is only needed when
# that refresh fails (Windows test-machine confusion 2026-07-18:
@@ -441,33 +685,78 @@ class ClaudeAuthService:
raise FileNotFoundError(
f"Claude CLI is not installed. {claude_install_hint()}"
)
+ modern_login = self._supports_auth_login(binary)
argv = self._login_argv(binary)
log.info("Starting Claude subscription login in an external terminal")
try:
- return launch_interactive_terminal(argv, title="Claude sign-in")
+ launch = launch_interactive_terminal(argv, title="Claude sign-in")
except InteractiveTerminalUnavailable as exc:
- manual = (
- "claude auth login --claudeai" if len(argv) > 1 else "claude"
- )
+ manual = "claude auth login --claudeai" if modern_login else "claude"
raise InteractiveTerminalUnavailable(
f"{exc} Open a terminal and run: {manual}"
) from exc
+ clear_version_cache()
+ try:
+ from jarvis.claude_auth_state import clear_claude_auth_dead
+
+ clear_claude_auth_dead()
+ except Exception: # noqa: BLE001,S110 — optional recovery state
+ pass
+ return launch
def logout_blocking(self) -> tuple[bool, str | None]:
- """Disconnect the Claude subscription login by removing its credentials.
-
- Returns ``(ok, error)``. Removes ONLY ``~/.claude/.credentials.json`` (the
- bearer file) — never ``~/.claude.json``, which holds the user's whole
- Claude Code config + project history. A missing file counts as success
- (already logged out). Deliberately DEFAULT-DIR only: a login owned by
- an external profile manager (custom ``CLAUDE_CONFIG_DIR``) also feeds
- that manager's own live sessions — deleting it here would log those
- out behind the user's back, so the card may keep reporting connected
- after a disconnect on such a host.
+ """Disconnect through the CLI, with an old-release file fallback.
+
+ The CLI owns the platform-specific credential store, including the
+ macOS Keychain. Only when ``auth logout`` is unavailable do we remove
+ the legacy default bearer file; ``~/.claude.json`` is never deleted.
"""
+ binary = self._resolve_binary()
+ if binary is not None and self._supports_auth_logout(binary):
+ try:
+ proc = subprocess.run(
+ [*self._cli_argv_prefix(binary), "auth", "logout"],
+ env=_cli_credential_env(),
+ capture_output=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=15.0,
+ text=True,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ except (OSError, subprocess.SubprocessError) as exc:
+ return False, f"Claude logout could not run: {type(exc).__name__}"
+ if proc.returncode != 0:
+ return False, f"Claude logout failed with exit code {proc.returncode}"
+ clear_version_cache()
+ try:
+ from jarvis.claude_auth_state import clear_claude_auth_dead
+
+ clear_claude_auth_dead()
+ except Exception: # noqa: BLE001,S110 — optional recovery state
+ pass
+ return True, None
+
creds = self._credentials_path()
try:
creds.unlink(missing_ok=True)
+ clear_version_cache()
return True, None
except OSError as exc:
return False, f"could not remove Claude credentials: {exc}"
+
+
+def usable_native_claude_subscription() -> ClaudeAuthStatus | None:
+ """Return a subscription status that a customization-free worker can use.
+
+ A connected native account alone is insufficient: without ``--safe-mode``
+ an older CLI would need Jarvis' isolated config to avoid user hooks, which
+ hides platform-native credentials such as the macOS Keychain. Returning
+ ``None`` makes the worker resolver continue through the legacy token/API-key
+ and cross-family paths.
+ """
+ status = ClaudeAuthService().status()
+ if not (status.connected and status.mode == "subscription"):
+ return None
+ prefix = claude_cli_argv_prefix(status.binary_path)
+ return status if claude_cli_supports_safe_mode(prefix) else None
diff --git a/jarvis/missions/critic/runner.py b/jarvis/missions/critic/runner.py
index 72cddd0f71..a4b9c550a0 100644
--- a/jarvis/missions/critic/runner.py
+++ b/jarvis/missions/critic/runner.py
@@ -1710,13 +1710,21 @@ class CriticRunner:
uses the user's Claude Max subscription instead of the paid
Messages-API path that the Jarvis-Agent worker routes through by default.
"""
+ from jarvis.claude_auth import (
+ claude_cli_supports_safe_mode,
+ claude_native_auth_env,
+ )
from jarvis.missions.workers.claude_direct_worker import (
_resolve_claude_argv_prefix,
)
argv_prefix = _resolve_claude_argv_prefix()
+ safe_mode = await asyncio.to_thread(
+ claude_cli_supports_safe_mode, argv_prefix
+ )
cmd: list[str] = [
*argv_prefix,
+ *(["--safe-mode"] if safe_mode else []),
"--print",
# 2026-05-24 fix: was "--permission-mode plan". Plan mode makes
# claude --print treat the request as a *planning* task and emit
@@ -1742,6 +1750,12 @@ class CriticRunner:
adversarial_reframe,
)
+ spawn_env = dict(env)
+ if safe_mode:
+ # Preserve the platform-native account (macOS Keychain included)
+ # while safe mode disables user hooks/plugins/project settings.
+ spawn_env = claude_native_auth_env(spawn_env)
+
t0 = time.perf_counter()
# Per-mission process containment (AP-10): mirrors ClaudeDirectWorker,
# whose orchestrator wraps the whole spawn in ``async with job:``. A
@@ -1759,7 +1773,7 @@ class CriticRunner:
proc = await create_worker_subprocess(
cmd,
cwd=str(worktree),
- env=env,
+ env=spawn_env,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
diff --git a/jarvis/missions/init.py b/jarvis/missions/init.py
index 23fce24fb6..7c9ef82aea 100644
--- a/jarvis/missions/init.py
+++ b/jarvis/missions/init.py
@@ -505,22 +505,18 @@ def _claude_cli_auth_viable() -> bool:
"""True when the ``claude`` CLI has a REACHABLE auth surface for a worker.
Binary presence alone is NOT viability (2026-07-06 incident): the worker
- runs ``claude --print`` pinned to an isolated CLAUDE_CONFIG_DIR, so its
- ONLY auth surface is the credential Jarvis injects — a live non-expired
- OAuth bearer (``CLAUDE_CODE_OAUTH_TOKEN``) or a classic Anthropic API key.
- An OAuth token that expired in place (nothing refreshes ``~/.claude`` on a
- host whose interactive sessions use a different config dir) is a
- deterministic 401 on every spawn, while ``claude status`` still says
- connected (presence-only check).
-
- Three gates, all cheap and offline:
+ must have one of three executable auth surfaces:
+
1. the process-local ``claude_auth_dead`` flag (a worker PROVED the current
credential dead this session — fingerprinted, so a fresh login/key
re-enables Claude instantly);
- 2. a live, non-expired OAuth login in ``~/.claude/.credentials.json``;
- 3. failing that, a CLASSIC (non-``sk-ant-oat``) stored Anthropic API key —
- a stored ``sk-ant-oat`` is a stale OAuth copy that would be routed to
- the OAuth slot and 401.
+ 2. a live file-backed OAuth bearer for the legacy isolated-config path, or
+ a native CLI account plus the ``--safe-mode`` capability (preserves the
+ macOS Keychain while disabling hooks/plugins);
+ 3. failing that, a classic (non-``sk-ant-oat``) Anthropic API key.
+
+ The CLI probes are tightly timed and process-cached. A probe failure is not
+ fatal: the cross-family worker resolver continues to another usable family.
"""
from jarvis.claude_auth_state import claude_auth_dead, credential_fingerprint
from jarvis.missions.isolation.env import (
@@ -531,6 +527,26 @@ def _claude_cli_auth_viable() -> bool:
if live_claude_oauth_status() == "valid":
token = read_live_claude_oauth_token()
return not claude_auth_dead(current_fingerprint=credential_fingerprint(token))
+
+ try:
+ from jarvis.claude_auth import usable_native_claude_subscription
+
+ status = usable_native_claude_subscription()
+ if status is not None:
+ account_marker = ":".join(
+ (
+ "native-claude-account",
+ status.binary_path,
+ status.user_email or "",
+ status.subscription_type or "",
+ )
+ )
+ return not claude_auth_dead(
+ current_fingerprint=credential_fingerprint(account_marker)
+ )
+ except Exception: # noqa: BLE001,S110 — optional native auth path
+ pass
+
try:
from jarvis.core.config import get_jarvis_agent_secret
@@ -1039,7 +1055,20 @@ async def bootstrap_missions(
)
if live_oat:
anthropic_key = live_oat
- elif anthropic_key and anthropic_key.startswith("sk-ant-oat"):
+ elif live_provider in {"claude", "claude-api"}:
+ # Current macOS Claude Code stores the subscription in Keychain,
+ # so no bearer file exists to inject. When the CLI confirms that
+ # native login and supports auth-preserving safe mode, do not let a
+ # separately stored API key override subscription billing via the
+ # ANTHROPIC_API_KEY environment variable.
+ try:
+ from jarvis.claude_auth import usable_native_claude_subscription
+
+ if usable_native_claude_subscription() is not None:
+ anthropic_key = None
+ except Exception: # noqa: BLE001,S110 — optional native auth path
+ pass
+ if not live_oat and anthropic_key and anthropic_key.startswith("sk-ant-oat"):
# 2026-07-06: no live (non-expired) OAuth login, and the stored
# credential is itself an OAuth bearer — i.e. a STALE copy of a
# login that no longer exists. Injecting it is a guaranteed 401
diff --git a/jarvis/missions/isolation/env.py b/jarvis/missions/isolation/env.py
index 226efee950..ae86087d5d 100644
--- a/jarvis/missions/isolation/env.py
+++ b/jarvis/missions/isolation/env.py
@@ -17,6 +17,7 @@ is no cross-talk between parallel missions.
"""
from __future__ import annotations
+import getpass
import json
import logging
import ntpath
@@ -80,7 +81,8 @@ def _repair_windows_worker_path(
# - SystemRoot: Windows internals; cmd.exe/python.exe need it.
# - TEMP: subprocesses may need to create temporary files.
# - USERPROFILE: claude/codex write their configs under %USERPROFILE%/.claude and .codex.
-# - LOCALAPPDATA: VSCode-Extensions, npm caches, ms-playwright cache liegen dort.
+# - USER/USERNAME: native credential stores can key lookups to the OS account.
+# - LOCALAPPDATA: VSCode extensions, npm caches, and Playwright caches live there.
# - APPDATA: npm-installed CLIs (gemini, claude) resolve their tool/skill bundles
# via %APPDATA%/Roaming/npm. Without this, the `gemini` CLI falls back to a
# stripped-down "generalist" agent that has NO file-writing tools — the worker
@@ -93,6 +95,9 @@ _ALLOWLIST_SYSTEM_VARS: tuple[str, ...] = (
"SystemRoot",
"TEMP",
"USERPROFILE",
+ "USER",
+ "LOGNAME",
+ "USERNAME",
"LOCALAPPDATA",
"APPDATA",
# POSIX (macOS/Linux): claude/codex resolve their credential + config files
@@ -102,6 +107,7 @@ _ALLOWLIST_SYSTEM_VARS: tuple[str, ...] = (
# ~/.codex/auth.json -> auth failure. Harmless on Windows (usually unset).
"HOME",
"XDG_CONFIG_HOME",
+ "TMPDIR",
)
@@ -139,6 +145,17 @@ def build_worker_env(
if value is not None:
env[key] = value
+ # macOS Keychain-backed Claude auth needs the POSIX account name. GUI or
+ # supervisor launchers can provide HOME while omitting USER; derive only
+ # that display-safe OS identity rather than inheriting the full environment.
+ if os.name == "posix" and env.get("HOME") and not env.get("USER"):
+ try:
+ user = getpass.getuser().strip()
+ except (OSError, KeyError):
+ user = ""
+ if user:
+ env["USER"] = user
+
# Fixed defaults — non-negotiable
env["NO_COLOR"] = "1"
env["PYTHONIOENCODING"] = "utf-8"
@@ -185,8 +202,11 @@ def build_worker_env(
# APPROVED missions streamed past it. A non-interactive worker needs ZERO
# plugins/hooks/skills, so the clean config eliminates the hang vector
# entirely (and cross-platform — on Linux/macOS the same hook runs bash
- # directly). Auth then comes from CLAUDE_CODE_OAUTH_TOKEN below (the
- # credentials file lives in the *user's* ~/.claude, not here).
+ # directly). Auth then comes from CLAUDE_CODE_OAUTH_TOKEN below. Newer
+ # Claude Code workers remove this override at spawn time and use
+ # ``--safe-mode``: customizations stay disabled while the native credential
+ # store (including the macOS Keychain) remains visible. Older CLIs retain
+ # this isolated path.
env["CLAUDE_CONFIG_DIR"] = str(_seed_worker_claude_config(run_dir))
# The external `openclaw` CLI reads `<MISSION_STATE_DIR>/openclaw.json` to
# find `agents.defaults.workspace`; without that redirect, file_write/edit
diff --git a/jarvis/missions/workers/claude_direct_worker.py b/jarvis/missions/workers/claude_direct_worker.py
index a644b72cf9..00bda5605d 100644
--- a/jarvis/missions/workers/claude_direct_worker.py
+++ b/jarvis/missions/workers/claude_direct_worker.py
@@ -37,10 +37,10 @@ Spawn discipline mirrors GeminiWorker / SubJarvisWorker:
- ``ANTHROPIC_OAUTH_TOKEN`` + ``ANTHROPIC_API_KEY`` injected by
``_env_builder`` in ``jarvis.missions.init``.
-Authentication: claude CLI reads OAuth tokens from ``~/.claude/.credentials.json``
-in the user's profile. The env-builder copies the bearer to both
-``ANTHROPIC_API_KEY`` and ``ANTHROPIC_OAUTH_TOKEN`` so the binary works
-regardless of which env var the CLI happens to check first.
+Authentication: current Claude Code can retain its platform-native login while
+``--safe-mode`` disables user hooks and plugins. Older releases keep the
+isolated-config path and authenticate through an explicitly injected OAuth
+token or API key.
"""
from __future__ import annotations
@@ -232,23 +232,12 @@ def _resolve_claude_argv_prefix() -> list[str]:
Falls back to the bare shim only when node + mjs aren't both
resolvable.
"""
- node = shutil.which("node") or shutil.which("node.exe")
- if node:
- for name in ("claude.cmd", "claude.exe", "claude"):
- cli = shutil.which(name)
- if not cli:
- continue
- cli_dir = Path(cli).resolve().parent
- for candidate in (
- cli_dir / "node_modules" / "@anthropic-ai" / "claude-code" / "cli.js",
- cli_dir / "node_modules" / "@anthropic-ai" / "claude-code" / "cli.mjs",
- cli_dir / "cli.js",
- cli_dir / "claude.mjs",
- ):
- if candidate.is_file():
- return [node, str(candidate)]
bare = _resolve_claude_binary()
- return [bare] if bare else ["claude"]
+ if bare is None:
+ return ["claude"]
+ from jarvis.claude_auth import claude_cli_argv_prefix
+
+ return claude_cli_argv_prefix(bare)
def _build_mcp_config_args(config_dir: Path, mcp_servers: dict[str, Any] | None) -> list[str]:
@@ -446,8 +435,17 @@ class ClaudeDirectWorker:
# subscription can't reach it (live mission 019ec615, 2026-06-14:
# claude-fable-5 "is currently unavailable").
argv_prefix = _resolve_claude_argv_prefix()
+ from jarvis.claude_auth import (
+ claude_cli_supports_safe_mode,
+ claude_native_auth_env,
+ )
+
+ safe_mode = await asyncio.to_thread(
+ claude_cli_supports_safe_mode, argv_prefix
+ )
cmd: list[str] = [
*argv_prefix,
+ *(["--safe-mode"] if safe_mode else []),
"--print",
"--output-format",
"stream-json",
@@ -488,15 +486,21 @@ class ClaudeDirectWorker:
# gracefully when the host process is in a job that forbids breakaway
# (WinError 5, live mission 019ec602 2026-06-14).
t0 = time.perf_counter()
+ spawn_env = dict(env)
+ if safe_mode:
+ # The native account may live in the macOS Keychain and is scoped
+ # to the user's real config. Safe mode disables customizations
+ # without hiding that credential store. Older CLIs retain the
+ # isolated config plus explicitly injected-token path.
+ spawn_env = claude_native_auth_env(spawn_env)
+ if broker_binding is not None:
+ spawn_env = broker_binding.apply_environment(spawn_env)
+
try:
proc = await create_worker_subprocess(
cmd,
cwd=str(worktree),
- env=(
- broker_binding.apply_environment(env)
- if broker_binding is not None
- else env
- ),
+ env=spawn_env,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
diff --git a/jarvis/ui/web/claude_routes.py b/jarvis/ui/web/claude_routes.py
index a3ddaab9c3..e911038fc4 100644
--- a/jarvis/ui/web/claude_routes.py
+++ b/jarvis/ui/web/claude_routes.py
@@ -1,11 +1,11 @@
"""REST routes for the Claude (Anthropic) subscription connect flow.
-Dual billing, mirror of Codex / Antigravity: the heavy-task subagent runs over
-the **Claude Max subscription** (the ``claude`` CLI's OAuth login in
-``~/.claude/.credentials.json`` — no per-token bill) OR over an **Anthropic API
-key** (billed per token). This module surfaces an honest snapshot of which one is
-live, plus the connected account email + subscription tier, so the Subagent card
-can render "Connected as <email>" exactly like the Codex / Antigravity cards.
+Dual billing, mirror of Codex / Antigravity: the heavy-task Jarvis-Agent runs over
+the **Claude subscription** (the ``claude`` CLI's platform-native login — no
+per-token API bill) OR over an **Anthropic API key** (billed per token). This
+module surfaces an honest snapshot of which one is live, plus the connected
+account email + subscription tier, so the Jarvis-Agent card can render
+"Connected as <email>" exactly like the Codex / Antigravity cards.
This is the Anthropic sibling of ``/api/codex/*``
(:mod:`jarvis.ui.web.provider_routes`) and ``/api/antigravity/*``
@@ -58,7 +58,7 @@ def _service() -> ClaudeAuthService:
@router.get("/claude/status")
async def claude_status() -> dict[str, Any]:
"""Honest snapshot of the Claude login (installed / connected / account)."""
- return _service().status().to_dict()
+ return (await asyncio.to_thread(_service().status)).to_dict()
@router.post("/claude/test")
@@ -77,7 +77,7 @@ async def claude_test() -> dict[str, Any]:
async def claude_login() -> dict[str, Any]:
"""Start the interactive Claude sign-in in a terminal. 409 if no CLI is found."""
service = _service()
- status = service.status()
+ status = await asyncio.to_thread(service.status)
if not status.installed:
raise HTTPException(
status_code=409,
@@ -106,9 +106,9 @@ async def claude_login() -> dict[str, Any]:
@router.post("/claude/logout")
async def claude_logout() -> dict[str, Any]:
- """Disconnect the Claude subscription login (removes the on-disk bearer)."""
+ """Disconnect the Claude subscription through its native CLI credential store."""
service = _service()
- ok, error = service.logout_blocking()
+ ok, error = await asyncio.to_thread(service.logout_blocking)
if not ok:
raise HTTPException(status_code=500, detail=error or "Claude logout failed")
return {"ok": True, "message": "Claude was disconnected"}
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index 66ec43db8e..a581fa854a 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -855,17 +855,26 @@ def _claude_worker_display_label(*, default: str) -> str:
the Claude subscription OAuth login whenever one exists — a degraded
banner blaming the "API-Key" then reads as nonsense to a subscription
user (2026-07-10 report: "I selected the subscription, the key is
- irrelevant"). Presence of ANY OAuth bearer, live or expired-in-place,
- means the user is on the subscription path. Offline + cheap; any probe
- failure keeps the spec label rather than breaking the health check.
+ irrelevant"). The CLI status is authoritative because current macOS
+ releases keep the login in Keychain rather than a plaintext bearer file;
+ the file probe remains only for an expired legacy login. Any failure keeps
+ the spec label rather than breaking the health check.
"""
try:
+ from jarvis.claude_auth import ClaudeAuthService
from jarvis.claude_credentials import freshest_claude_oauth
+ status = ClaudeAuthService().status()
+ subscription_connected = status.connected and status.mode == "subscription"
oauth_status = freshest_claude_oauth().status
except Exception: # noqa: BLE001
+ subscription_connected = False
oauth_status = "absent"
- return "Claude (subscription)" if oauth_status != "absent" else default
+ return (
+ "Claude (subscription)"
+ if subscription_connected or oauth_status != "absent"
+ else default
+ )
def _selected_jarvis_agent_provider(cfg: Any) -> str | None:
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index f421b6c109..f0b58ba6ea 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -985,24 +985,28 @@ class WebServer:
api_key_set = dedicated_key_set or shared_key_set
oauth_connected = False
oauth_stale = False
- # Claude Max users authenticate the subagent via the LIVE OAuth
- # login in ~/.claude/.credentials.json (read by ClaudeDirectWorker),
- # not a stored API key — count that as configured so a fresh
- # Claude-Max user (only ran `claude login`) is not falsely locked.
- # An EXPIRED-in-place access token still counts as a configured
- # login: `claude` refreshes it automatically the next time it
- # runs, so locking the card would tell a logged-in Max user
- # "not connected" (Windows test-machine report 2026-07-18). The
- # spawn-time viability gate keeps re-reading the live file.
+ # Claude subscription auth is owned by the CLI. Its status
+ # command covers platform-native stores such as macOS Keychain;
+ # the legacy bearer-file check only preserves the recoverable
+ # expired state for older Linux/Windows installs.
if mapping.jarvis == "claude-api":
try:
+ from jarvis.claude_auth import ClaudeAuthService
from jarvis.claude_credentials import (
freshest_claude_oauth,
)
+ auth_status = await asyncio.to_thread(
+ ClaudeAuthService().status
+ )
+ oauth_connected = bool(
+ auth_status.connected
+ and auth_status.mode == "subscription"
+ )
snapshot_status = freshest_claude_oauth().status
- oauth_connected = snapshot_status == "valid"
- oauth_stale = snapshot_status == "expired"
+ oauth_stale = (
+ not oauth_connected and snapshot_status == "expired"
+ )
except Exception: # noqa: BLE001
oauth_connected = False
oauth_stale = False
diff --git a/tests/integration/test_jarvis_agent_active_brain.py b/tests/integration/test_jarvis_agent_active_brain.py
index 5ec1d2aee2..a40e26c86c 100644
--- a/tests/integration/test_jarvis_agent_active_brain.py
+++ b/tests/integration/test_jarvis_agent_active_brain.py
@@ -370,12 +370,11 @@ def test_subagent_switch_409_codex_when_not_connected(
assert persisted == []
-# --- Claude Max OAuth as a subagent credential (no API key needed) ---------
-# The ClaudeDirectWorker authenticates via the live Claude Max OAuth login in
-# ~/.claude/.credentials.json (read_live_claude_oauth_token), NOT a stored
-# Anthropic API key. A fresh Claude-Max user who only ran `claude login` must
-# therefore see claude-api unlocked + selectable, mirroring the codex/agy OAuth
-# rows above. Source of the worker auth: missions/init.py::_worker_factory.
+# --- Claude subscription as a Jarvis-Agent credential (no API key needed) ---
+# The CLI status covers platform-native auth (including macOS Keychain), while
+# the bearer-file parser supports older Linux/Windows releases. A user who only
+# signed into Claude must see claude-api unlocked and selectable, mirroring the
+# Codex/Antigravity subscription rows above.
def test_claude_api_row_key_set_via_max_oauth(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -390,13 +389,24 @@ def test_claude_api_row_key_set_via_max_oauth(monkeypatch: pytest.MonkeyPatch) -
def _patch_claude_oauth(monkeypatch: pytest.MonkeyPatch, status: str) -> None:
- """Stub the freshest-login snapshot the claude-api row reads."""
+ """Stub both modern CLI status and the legacy bearer-file fallback."""
from types import SimpleNamespace
+ from jarvis.claude_auth import ClaudeAuthService, ClaudeAuthStatus
+
monkeypatch.setattr(
"jarvis.claude_credentials.freshest_claude_oauth",
lambda **_k: SimpleNamespace(status=status),
)
+ monkeypatch.setattr(
+ ClaudeAuthService,
+ "status",
+ lambda self: ClaudeAuthStatus(
+ installed=True,
+ connected=status == "valid",
+ mode="subscription" if status == "valid" else "unknown",
+ ),
+ )
def test_claude_api_row_locked_without_key_or_oauth(monkeypatch: pytest.MonkeyPatch) -> None:
diff --git a/tests/missions/critic/test_runner_claude_direct.py b/tests/missions/critic/test_runner_claude_direct.py
index 3da8c25daf..f25c8c9744 100644
--- a/tests/missions/critic/test_runner_claude_direct.py
+++ b/tests/missions/critic/test_runner_claude_direct.py
@@ -122,6 +122,7 @@ def _patch_direct(
*,
stdout: str | bytes,
returncode: int = 0,
+ safe_mode: bool = False,
) -> dict[str, Any]:
"""Force the claude-direct branch and capture the spawn call.
@@ -151,6 +152,10 @@ def _patch_direct(
"_resolve_claude_argv_prefix",
lambda: ["claude"],
)
+ monkeypatch.setattr(
+ "jarvis.claude_auth.claude_cli_supports_safe_mode",
+ lambda _prefix: safe_mode,
+ )
async def fake(*args: Any, **kwargs: Any) -> _FakeProc:
captured["argv"] = list(args)
@@ -199,6 +204,40 @@ async def test_claude_direct_path_approves_when_resolver_picks_claude_api(
assert not (tmp_path / "openclaw.json").exists()
+async def test_claude_critic_safe_mode_keeps_native_login_environment(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
+ captured = _patch_direct(
+ monkeypatch,
+ stdout=_valid_verdict_json("approve"),
+ safe_mode=True,
+ )
+ env = {
+ "HOME": "/Users/tester",
+ "USER": "tester",
+ "CLAUDE_CONFIG_DIR": str(tmp_path / "isolated-claude"),
+ }
+
+ verdict = await CriticRunner().run(
+ mission_prompt="Build X",
+ worker_diff="diff",
+ worker_log="log",
+ prior_reflections="",
+ iteration=0,
+ worktree=tmp_path,
+ env=env,
+ )
+
+ assert verdict.verdict == "approve"
+ assert "--safe-mode" in captured["argv"]
+ spawn_env = captured["kwargs"]["env"]
+ assert "CLAUDE_CONFIG_DIR" not in spawn_env
+ assert spawn_env["HOME"] == "/Users/tester"
+ assert spawn_env["USER"] == "tester"
+
+
@pytest.mark.parametrize("provider,foreign_model", [
("grok", "grok-4.3"),
("gemini", "gemini-3.1-pro-preview"),
diff --git a/tests/missions/test_claude_cli_auth_viability.py b/tests/missions/test_claude_cli_auth_viability.py
new file mode 100644
index 0000000000..2e5961cd36
--- /dev/null
+++ b/tests/missions/test_claude_cli_auth_viability.py
@@ -0,0 +1,93 @@
+"""Claude CLI worker viability across native and legacy credential stores."""
+from __future__ import annotations
+
+from collections.abc import Iterator
+
+import pytest
+
+from jarvis import claude_auth_state
+from jarvis.claude_auth import ClaudeAuthService, ClaudeAuthStatus
+from jarvis.missions import init as missions_init
+
+
[email protected](autouse=True)
+def _reset_auth_dead() -> Iterator[None]:
+ claude_auth_state.clear_claude_auth_dead()
+ yield
+ claude_auth_state.clear_claude_auth_dead()
+
+
+def _patch_no_file_or_key(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ "jarvis.missions.isolation.env.live_claude_oauth_status",
+ lambda: "absent",
+ )
+ monkeypatch.setattr(
+ "jarvis.missions.isolation.env.read_live_claude_oauth_token",
+ lambda: None,
+ )
+ monkeypatch.setattr(
+ "jarvis.core.config.get_jarvis_agent_secret",
+ lambda _provider: None,
+ )
+
+
+def test_native_subscription_is_viable_with_safe_mode(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _patch_no_file_or_key(monkeypatch)
+ monkeypatch.setattr(
+ ClaudeAuthService,
+ "status",
+ lambda self: ClaudeAuthStatus(
+ installed=True,
+ connected=True,
+ mode="subscription",
+ binary_path="/opt/claude",
+ user_email="[email protected]",
+ subscription_type="max",
+ ),
+ )
+ monkeypatch.setattr(
+ "jarvis.claude_auth.claude_cli_supports_safe_mode",
+ lambda _prefix: True,
+ )
+
+ assert missions_init._claude_cli_auth_viable() is True
+
+
+def test_native_subscription_without_safe_mode_uses_cross_family_fallback(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _patch_no_file_or_key(monkeypatch)
+ monkeypatch.setattr(
+ ClaudeAuthService,
+ "status",
+ lambda self: ClaudeAuthStatus(
+ installed=True,
+ connected=True,
+ mode="subscription",
+ binary_path="/opt/claude",
+ ),
+ )
+ monkeypatch.setattr(
+ "jarvis.claude_auth.claude_cli_supports_safe_mode",
+ lambda _prefix: False,
+ )
+
+ assert missions_init._claude_cli_auth_viable() is False
+
+
+def test_legacy_file_token_remains_viable_without_cli_status(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ "jarvis.missions.isolation.env.live_claude_oauth_status",
+ lambda: "valid",
+ )
+ monkeypatch.setattr(
+ "jarvis.missions.isolation.env.read_live_claude_oauth_token",
+ lambda: "sk-ant-oat01-test-token",
+ )
+
+ assert missions_init._claude_cli_auth_viable() is True
diff --git a/tests/missions/test_env.py b/tests/missions/test_env.py
index 2b68a224cd..8793aec67e 100644
--- a/tests/missions/test_env.py
+++ b/tests/missions/test_env.py
@@ -1,6 +1,7 @@
"""Tests for build_worker_env — strict allowlist + fixed defaults + optional keys."""
from __future__ import annotations
+import os
from pathlib import Path
from unittest.mock import patch
@@ -514,12 +515,36 @@ def test_home_and_xdg_passed_through_for_posix_auth(tmp_path: Path) -> None:
fake_env = {
"PATH": "/usr/bin:/bin",
"HOME": "/home/jarvis",
+ "USER": "jarvis",
+ "LOGNAME": "jarvis",
"XDG_CONFIG_HOME": "/home/jarvis/.config",
+ "TMPDIR": "/home/jarvis/.tmp",
}
with patch.dict("os.environ", fake_env, clear=True):
env = build_worker_env(run_dir=tmp_path)
assert env["HOME"] == "/home/jarvis"
+ assert env["USER"] == "jarvis"
+ assert env["LOGNAME"] == "jarvis"
assert env["XDG_CONFIG_HOME"] == "/home/jarvis/.config"
+ assert env["TMPDIR"] == "/home/jarvis/.tmp"
+
+
+def test_posix_user_is_derived_when_gui_environment_omits_it(
+ tmp_path: Path,
+) -> None:
+ if os.name != "posix":
+ pytest.skip("POSIX account fallback is not used on Windows")
+ fake_env = {"PATH": "/usr/bin:/bin", "HOME": "/home/jarvis"}
+ with (
+ patch.dict("os.environ", fake_env, clear=True),
+ patch(
+ "jarvis.missions.isolation.env.getpass.getuser",
+ return_value="derived-user",
+ ),
+ ):
+ env = build_worker_env(run_dir=tmp_path)
+
+ assert env["USER"] == "derived-user"
def test_classic_api_key_does_not_set_claude_code_oauth_token(tmp_path: Path) -> None:
diff --git a/tests/missions/workers/test_claude_auth_fallback.py b/tests/missions/workers/test_claude_auth_fallback.py
index 6691eb1a06..034ca050cf 100644
--- a/tests/missions/workers/test_claude_auth_fallback.py
+++ b/tests/missions/workers/test_claude_auth_fallback.py
@@ -160,6 +160,10 @@ def _pin_claude_spawn(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(cdw, "create_worker_subprocess", _fake_exec)
monkeypatch.setattr(cdw, "_resolve_claude_argv_prefix", lambda: ["claude"])
+ monkeypatch.setattr(
+ "jarvis.claude_auth.claude_cli_supports_safe_mode",
+ lambda _prefix: False,
+ )
monkeypatch.setattr(
cdw,
"_resolve_provider_chain",
@@ -252,6 +256,10 @@ async def test_success_clears_claude_auth_dead(
monkeypatch.setattr(cdw, "create_worker_subprocess", _fake_exec)
monkeypatch.setattr(cdw, "_resolve_claude_argv_prefix", lambda: ["claude"])
+ monkeypatch.setattr(
+ "jarvis.claude_auth.claude_cli_supports_safe_mode",
+ lambda _prefix: False,
+ )
monkeypatch.setattr(
cdw,
"_resolve_provider_chain",
diff --git a/tests/missions/workers/test_claude_direct_provider_fallback.py b/tests/missions/workers/test_claude_direct_provider_fallback.py
index 0ec7f6ded2..a6ad036e1b 100644
--- a/tests/missions/workers/test_claude_direct_provider_fallback.py
+++ b/tests/missions/workers/test_claude_direct_provider_fallback.py
@@ -112,6 +112,10 @@ async def test_non_claude_provider_runs_on_claude_not_refused(
cdw, "_resolve_provider_chain",
lambda *a, **k: (_FallbackStep(provider, model),),
)
+ monkeypatch.setattr(
+ "jarvis.claude_auth.claude_cli_supports_safe_mode",
+ lambda _prefix: False,
+ )
captured: dict[str, Any] = {}
@@ -156,6 +160,56 @@ async def test_non_claude_provider_runs_on_claude_not_refused(
assert final.result == "OK"
+async def test_safe_mode_preserves_native_auth_without_loading_user_config(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Modern Claude keeps Keychain auth while safe mode disables customizations."""
+ monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
+ monkeypatch.setattr(
+ cdw,
+ "_resolve_provider_chain",
+ lambda *a, **k: (_FallbackStep("claude-api", "claude-opus-4-8"),),
+ )
+ monkeypatch.setattr(cdw, "_resolve_claude_argv_prefix", lambda: ["claude"])
+ monkeypatch.setattr(
+ "jarvis.claude_auth.claude_cli_supports_safe_mode",
+ lambda _prefix: True,
+ )
+ captured: dict[str, Any] = {}
+
+ async def _fake_exec(*args: Any, **kwargs: Any) -> _OkProc:
+ captured["argv"] = list(args)
+ captured["env"] = dict(kwargs["env"])
+ return _OkProc(_RESULT_LINE)
+
+ monkeypatch.setattr(cdw.asyncio, "create_subprocess_exec", _fake_exec)
+ env = {
+ "HOME": "/Users/tester",
+ "USER": "tester",
+ "CLAUDE_CONFIG_DIR": str(tmp_path / "isolated-claude"),
+ }
+
+ events: list[Any] = []
+ async for event in ClaudeDirectWorker().spawn(
+ "do the task",
+ worktree=tmp_path,
+ env=env,
+ job=_Job(),
+ worker_id="native-auth",
+ log_dir=tmp_path / "logs-native-auth",
+ first_output_timeout_s=5.0,
+ timeout_s=5.0,
+ ):
+ events.append(event)
+
+ assert events[-1].is_error is False
+ assert "--safe-mode" in captured["argv"]
+ assert "CLAUDE_CONFIG_DIR" not in captured["env"]
+ assert captured["env"]["HOME"] == "/Users/tester"
+ assert captured["env"]["USER"] == "tester"
+
+
def test_resolve_claude_model_never_returns_foreign_slug() -> None:
"""_resolve_claude_model must map any non-claude primary to a claude model,
honour a claude-api primary verbatim, and survive a None primary."""
diff --git a/tests/unit/brain/test_section_health.py b/tests/unit/brain/test_section_health.py
index 03ab54f3d4..88b0e22aab 100644
--- a/tests/unit/brain/test_section_health.py
+++ b/tests/unit/brain/test_section_health.py
@@ -229,6 +229,7 @@ class TestSubagentSectionHealth:
import json
from jarvis import claude_credentials
+ from jarvis.claude_auth import ClaudeAuthService, ClaudeAuthStatus
from jarvis.ui.web import provider_routes as pr
(tmp_path / ".credentials.json").write_text(
@@ -245,6 +246,11 @@ class TestSubagentSectionHealth:
monkeypatch.setattr(
claude_credentials, "claude_config_dirs", lambda: [tmp_path]
)
+ monkeypatch.setattr(
+ ClaudeAuthService,
+ "status",
+ lambda self: ClaudeAuthStatus(installed=True, connected=False),
+ )
monkeypatch.setattr(pr, "_worker_usable", lambda p: False)
monkeypatch.setattr(pr, "_worker_flagged_dead", lambda p: True)
monkeypatch.setattr(
@@ -258,12 +264,18 @@ class TestSubagentSectionHealth:
self, monkeypatch, tmp_path
) -> None:
from jarvis import claude_credentials
+ from jarvis.claude_auth import ClaudeAuthService, ClaudeAuthStatus
from jarvis.ui.web import provider_routes as pr
# No OAuth bearer anywhere → the user really is on the API-key path.
monkeypatch.setattr(
claude_credentials, "claude_config_dirs", lambda: [tmp_path]
)
+ monkeypatch.setattr(
+ ClaudeAuthService,
+ "status",
+ lambda self: ClaudeAuthStatus(installed=True, connected=False),
+ )
monkeypatch.setattr(pr, "_worker_usable", lambda p: False)
monkeypatch.setattr(pr, "_worker_flagged_dead", lambda p: True)
monkeypatch.setattr(
diff --git a/tests/unit/test_claude_auth.py b/tests/unit/test_claude_auth.py
index 5de9d61394..fc701f658f 100644
--- a/tests/unit/test_claude_auth.py
+++ b/tests/unit/test_claude_auth.py
@@ -8,6 +8,7 @@ depends on a real ``claude`` install or the user's real credentials.
from __future__ import annotations
import json
+import subprocess
from pathlib import Path
import pytest
@@ -15,7 +16,9 @@ import pytest
from jarvis import claude_auth, claude_credentials
from jarvis.claude_auth import (
ClaudeAuthService,
+ ClaudeCliAuthSnapshot,
_account_from_claude_json,
+ _parse_cli_auth_status,
_subscription_label,
)
@@ -53,6 +56,8 @@ def _service(
)
monkeypatch.setattr(svc, "_resolve_binary", lambda: binary)
monkeypatch.setattr(svc, "_probe_version", lambda _b: "claude 1.2.3")
+ # File-backed cases model an older CLI whose auth-status command is absent.
+ monkeypatch.setattr(svc, "_probe_cli_auth", lambda _b: None)
monkeypatch.setattr(svc, "_credentials_path", lambda: creds_path)
monkeypatch.setattr(svc, "_claude_json_path", lambda: claude_json_path)
return svc
@@ -79,6 +84,32 @@ def test_subscription_label_maps_known_tiers() -> None:
assert _subscription_label(None) == "Claude subscription"
+def test_parse_cli_auth_status_reads_current_claude_shape() -> None:
+ snapshot = _parse_cli_auth_status(
+ json.dumps(
+ {
+ "loggedIn": True,
+ "authMethod": "claude.ai",
+ "subscriptionType": "max",
+ "apiProvider": "firstParty",
+ "email": "[email protected]",
+ }
+ )
+ )
+ assert snapshot == ClaudeCliAuthSnapshot(
+ logged_in=True,
+ auth_method="claude.ai",
+ subscription_type="max",
+ api_provider="firstParty",
+ )
+
+
[email protected]("raw", ["", "not json", "{}", '{"loggedIn": "yes"}'])
+def test_parse_cli_auth_status_rejects_malformed_or_ambiguous_data(raw: str) -> None:
+ assert _parse_cli_auth_status(raw) is None
+
+
# -- status() integration ----------------------------------------------
@@ -99,6 +130,53 @@ def test_status_subscription_with_email(tmp_path, monkeypatch) -> None:
assert "[email protected]" in st.message
+def test_status_uses_native_cli_login_when_no_credentials_file(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Current macOS Claude Code stores OAuth in Keychain, not a JSON file."""
+ svc = _service(tmp_path, monkeypatch, creds=None, claude_json=None)
+ monkeypatch.setattr(
+ svc,
+ "_probe_cli_auth",
+ lambda _b: ClaudeCliAuthSnapshot(
+ logged_in=True,
+ auth_method="claude.ai",
+ subscription_type="max",
+ api_provider="firstParty",
+ ),
+ )
+
+ st = svc.status()
+
+ assert st.connected is True
+ assert st.mode == "subscription"
+ assert st.subscription_type == "max"
+ assert st.user_email == "[email protected]"
+ assert st.account_label == "Claude Max"
+
+
+def test_cli_logged_out_is_authoritative_over_stale_file(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ svc = _service(
+ tmp_path,
+ monkeypatch,
+ creds={"claudeAiOauth": {"accessToken": "sk-ant-oat01-stale"}},
+ claude_json=None,
+ )
+ monkeypatch.setattr(
+ svc,
+ "_probe_cli_auth",
+ lambda _b: ClaudeCliAuthSnapshot(logged_in=False, auth_method="none"),
+ )
+
+ st = svc.status()
+
+ assert st.connected is False
+ assert st.mode == "unknown"
+
+
def test_status_api_key_when_no_oauth(tmp_path, monkeypatch) -> None:
svc = _service(
tmp_path,
@@ -235,6 +313,7 @@ def test_status_connected_via_fresh_profile_when_default_is_stale(
)
monkeypatch.setattr(svc, "_resolve_binary", lambda: "/usr/bin/claude")
monkeypatch.setattr(svc, "_probe_version", lambda _b: "claude 1.2.3")
+ monkeypatch.setattr(svc, "_probe_cli_auth", lambda _b: None)
st = svc.status()
assert st.connected is True
assert st.mode == "subscription"
@@ -361,3 +440,114 @@ def test_start_login_headless_error_includes_manual_recovery(monkeypatch) -> Non
match="claude auth login --claudeai",
):
svc.start_login()
+
+
+def test_cli_auth_probe_accepts_logged_out_json_with_nonzero_exit(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc = ClaudeAuthService()
+ monkeypatch.setattr(svc, "_cli_argv_prefix", lambda _b: ["node", "cli.js"])
+ calls: list[list[str]] = []
+
+ def fake_run(argv, **_kwargs): # noqa: ANN001, ANN003
+ calls.append(list(argv))
+ return subprocess.CompletedProcess(
+ argv,
+ 1,
+ stdout='{"loggedIn":false,"authMethod":"none"}',
+ stderr="",
+ )
+
+ monkeypatch.setattr(claude_auth.subprocess, "run", fake_run)
+
+ snapshot = svc._probe_cli_auth("/opt/claude.cmd")
+
+ assert snapshot == ClaudeCliAuthSnapshot(
+ logged_in=False,
+ auth_method="none",
+ )
+ assert calls == [["node", "cli.js", "auth", "status", "--json"]]
+
+
+def test_safe_mode_capability_probe_is_cached(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls = 0
+
+ def fake_run(argv, **_kwargs): # noqa: ANN001, ANN003
+ nonlocal calls
+ calls += 1
+ return subprocess.CompletedProcess(
+ argv,
+ 0,
+ stdout="Options:\n --safe-mode Disable customizations",
+ stderr="",
+ )
+
+ monkeypatch.setattr(claude_auth.subprocess, "run", fake_run)
+
+ assert claude_auth.claude_cli_supports_safe_mode(["claude"]) is True
+ assert claude_auth.claude_cli_supports_safe_mode(["claude"]) is True
+ assert calls == 1
+
+
+def test_windows_cmd_resolves_to_adjacent_node_entrypoint(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ npm_dir = tmp_path / "npm"
+ cli_script = npm_dir / "node_modules" / "@anthropic-ai" / "claude-code" / "cli.js"
+ cli_script.parent.mkdir(parents=True)
+ cli_script.write_text("// test entrypoint", encoding="utf-8")
+ binary = npm_dir / "claude.cmd"
+ binary.write_text("@echo off", encoding="utf-8")
+ monkeypatch.setattr(
+ claude_auth.shutil,
+ "which",
+ lambda name: "C:/Program Files/nodejs/node.exe" if name == "node" else None,
+ )
+
+ prefix = claude_auth.claude_cli_argv_prefix(str(binary))
+
+ assert prefix == ["C:/Program Files/nodejs/node.exe", str(cli_script)]
+
+
+def test_native_auth_env_restores_custom_profile(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", "/profiles/claude-work")
+
+ result = claude_auth.claude_native_auth_env(
+ {"CLAUDE_CONFIG_DIR": "/mission/isolated", "USER": "tester"}
+ )
+
+ assert result["CLAUDE_CONFIG_DIR"] == "/profiles/claude-work"
+ assert result["USER"] == "tester"
+
+
+def test_native_auth_env_removes_mission_override_for_default_profile(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
+
+ result = claude_auth.claude_native_auth_env(
+ {"CLAUDE_CONFIG_DIR": "/mission/isolated", "USER": "tester"}
+ )
+
+ assert "CLAUDE_CONFIG_DIR" not in result
+
+
+def test_logout_uses_cli_native_credential_store(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc = ClaudeAuthService()
+ monkeypatch.setattr(svc, "_resolve_binary", lambda: "/opt/claude")
+ monkeypatch.setattr(svc, "_supports_auth_logout", lambda _b: True)
+ monkeypatch.setattr(svc, "_cli_argv_prefix", lambda _b: ["/opt/claude"])
+ calls: list[list[str]] = []
+
+ def fake_run(argv, **_kwargs): # noqa: ANN001, ANN003
+ calls.append(list(argv))
+ return subprocess.CompletedProcess(argv, 0, stdout="", stderr="")
+
+ monkeypatch.setattr(claude_auth.subprocess, "run", fake_run)
+
+ assert svc.logout_blocking() == (True, None)
+ assert calls == [["/opt/claude", "auth", "logout"]]