|
| 1 | +"""Anthropic Claude Code CLI adapter (``claude -p``, non-interactive / print mode). |
| 2 | +
|
| 3 | +Env vars |
| 4 | +-------- |
| 5 | +CLAUDE_CODE_BIN Optional explicit path to the ``claude`` binary. |
| 6 | + Blank or non-runnable paths are ignored; PATH + fallbacks apply. |
| 7 | +CLAUDE_CODE_MODEL Optional model override (e.g. ``claude-opus-4-7``). |
| 8 | + Unset or empty → omit ``--model``; CLI default applies. |
| 9 | +
|
| 10 | +Auth |
| 11 | +---- |
| 12 | +Claude Code authenticates via ``ANTHROPIC_API_KEY`` (env var) or OAuth credentials |
| 13 | +stored in ``~/.claude/.credentials.json`` after ``claude login``. |
| 14 | +""" |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import os |
| 19 | +import re |
| 20 | +import subprocess |
| 21 | +import sys |
| 22 | +from pathlib import Path |
| 23 | + |
| 24 | +from app.integrations.llm_cli.base import CLIInvocation, CLIProbe |
| 25 | +from app.integrations.llm_cli.binary_resolver import ( |
| 26 | + candidate_binary_names as _candidate_binary_names, |
| 27 | +) |
| 28 | +from app.integrations.llm_cli.binary_resolver import ( |
| 29 | + default_cli_fallback_paths as _default_cli_fallback_paths, |
| 30 | +) |
| 31 | +from app.integrations.llm_cli.binary_resolver import ( |
| 32 | + resolve_cli_binary, |
| 33 | +) |
| 34 | + |
| 35 | +_CLAUDE_VERSION_RE = re.compile(r"(\d+\.\d+\.\d+)") |
| 36 | +# Claude Code's `--version` does config/cache init that can spike past Codex's 3s |
| 37 | +# budget on cold starts or when another claude process holds shared state. |
| 38 | +_PROBE_TIMEOUT_SEC = 8.0 |
| 39 | + |
| 40 | + |
| 41 | +def _parse_semver(text: str) -> str | None: |
| 42 | + m = _CLAUDE_VERSION_RE.search(text) |
| 43 | + return m.group(1) if m else None |
| 44 | + |
| 45 | + |
| 46 | +def _classify_claude_code_auth() -> tuple[bool | None, str]: |
| 47 | + """Return (logged_in, detail) without spawning a subprocess. |
| 48 | +
|
| 49 | + Resolution order: |
| 50 | + 1. ANTHROPIC_API_KEY in env → True (definitive; build() forwards it). |
| 51 | + 2. ~/.claude/.credentials.json present and non-empty → True (OAuth login). |
| 52 | + 3. macOS without either → None: Claude Code stores OAuth in Keychain on |
| 53 | + darwin, so file absence is not proof of no-auth — let invocation reveal. |
| 54 | + 4. Otherwise → False (Linux/Windows: file is the canonical credential store). |
| 55 | + """ |
| 56 | + if os.environ.get("ANTHROPIC_API_KEY", "").strip(): |
| 57 | + return True, "Authenticated via ANTHROPIC_API_KEY." |
| 58 | + creds_path = Path.home() / ".claude" / ".credentials.json" |
| 59 | + try: |
| 60 | + if creds_path.exists() and creds_path.stat().st_size > 2: |
| 61 | + return True, "Authenticated via ~/.claude/.credentials.json (OAuth login)." |
| 62 | + except OSError: |
| 63 | + return None, "Could not read ~/.claude/.credentials.json; auth state unclear." |
| 64 | + if sys.platform == "darwin": |
| 65 | + return None, ( |
| 66 | + "ANTHROPIC_API_KEY not set and ~/.claude/.credentials.json absent; " |
| 67 | + "macOS may use Keychain — auth state unclear, invocation will verify." |
| 68 | + ) |
| 69 | + return ( |
| 70 | + False, |
| 71 | + "Not authenticated. Run: claude login or set ANTHROPIC_API_KEY.", |
| 72 | + ) |
| 73 | + |
| 74 | + |
| 75 | +def _fallback_claude_code_paths() -> list[str]: |
| 76 | + return _default_cli_fallback_paths("claude") |
| 77 | + |
| 78 | + |
| 79 | +class ClaudeCodeAdapter: |
| 80 | + """Non-interactive Claude Code CLI (``claude -p``, print mode, no TTY).""" |
| 81 | + |
| 82 | + name = "claude-code" |
| 83 | + binary_env_key = "CLAUDE_CODE_BIN" |
| 84 | + install_hint = "npm i -g @anthropic-ai/claude-code" |
| 85 | + auth_hint = "Run: claude login or set ANTHROPIC_API_KEY" |
| 86 | + min_version: str | None = None |
| 87 | + default_exec_timeout_sec = 120.0 |
| 88 | + |
| 89 | + def _resolve_binary(self) -> str | None: |
| 90 | + return resolve_cli_binary( |
| 91 | + explicit_env_key="CLAUDE_CODE_BIN", |
| 92 | + binary_names=_candidate_binary_names("claude"), |
| 93 | + fallback_paths=_fallback_claude_code_paths, |
| 94 | + ) |
| 95 | + |
| 96 | + def _probe_binary(self, binary_path: str) -> CLIProbe: |
| 97 | + try: |
| 98 | + ver_proc = subprocess.run( |
| 99 | + [binary_path, "--version"], |
| 100 | + capture_output=True, |
| 101 | + text=True, |
| 102 | + timeout=_PROBE_TIMEOUT_SEC, |
| 103 | + check=False, |
| 104 | + ) |
| 105 | + except (OSError, subprocess.TimeoutExpired) as exc: |
| 106 | + return CLIProbe( |
| 107 | + installed=False, |
| 108 | + version=None, |
| 109 | + logged_in=None, |
| 110 | + bin_path=None, |
| 111 | + detail=f"Could not run `{binary_path} --version`: {exc}", |
| 112 | + ) |
| 113 | + |
| 114 | + if ver_proc.returncode != 0: |
| 115 | + err = (ver_proc.stderr or ver_proc.stdout or "").strip() |
| 116 | + return CLIProbe( |
| 117 | + installed=False, |
| 118 | + version=None, |
| 119 | + logged_in=None, |
| 120 | + bin_path=None, |
| 121 | + detail=f"`{binary_path} --version` failed: {err or 'unknown error'}", |
| 122 | + ) |
| 123 | + |
| 124 | + version = _parse_semver(ver_proc.stdout + ver_proc.stderr) |
| 125 | + logged_in, auth_detail = _classify_claude_code_auth() |
| 126 | + return CLIProbe( |
| 127 | + installed=True, |
| 128 | + version=version, |
| 129 | + logged_in=logged_in, |
| 130 | + bin_path=binary_path, |
| 131 | + detail=auth_detail, |
| 132 | + ) |
| 133 | + |
| 134 | + def detect(self) -> CLIProbe: |
| 135 | + binary = self._resolve_binary() |
| 136 | + if not binary: |
| 137 | + return CLIProbe( |
| 138 | + installed=False, |
| 139 | + version=None, |
| 140 | + logged_in=None, |
| 141 | + bin_path=None, |
| 142 | + detail=( |
| 143 | + "Claude Code CLI not found on PATH or known install locations. " |
| 144 | + f"Install with: {self.install_hint} or set CLAUDE_CODE_BIN." |
| 145 | + ), |
| 146 | + ) |
| 147 | + return self._probe_binary(binary) |
| 148 | + |
| 149 | + def build(self, *, prompt: str, model: str | None, workspace: str) -> CLIInvocation: |
| 150 | + binary = self._resolve_binary() |
| 151 | + if not binary: |
| 152 | + raise RuntimeError( |
| 153 | + f"Claude Code CLI not found. {self.install_hint}" |
| 154 | + " or set CLAUDE_CODE_BIN to the full binary path." |
| 155 | + ) |
| 156 | + |
| 157 | + cwd = workspace or os.getcwd() |
| 158 | + |
| 159 | + argv: list[str] = [ |
| 160 | + binary, |
| 161 | + "-p", |
| 162 | + "--output-format", |
| 163 | + "text", |
| 164 | + ] |
| 165 | + |
| 166 | + resolved_model = (model or "").strip() |
| 167 | + if resolved_model: |
| 168 | + argv.extend(["--model", resolved_model]) |
| 169 | + |
| 170 | + # Forward Anthropic auth vars explicitly rather than relying on a blanket |
| 171 | + # prefix allowlist, so they don't leak into other CLI adapters (e.g. Codex). |
| 172 | + env: dict[str, str] = {"NO_COLOR": "1"} |
| 173 | + for key in ("ANTHROPIC_API_KEY", "ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN"): |
| 174 | + val = os.environ.get(key, "").strip() |
| 175 | + if val: |
| 176 | + env[key] = val |
| 177 | + |
| 178 | + return CLIInvocation( |
| 179 | + argv=tuple(argv), |
| 180 | + stdin=prompt, |
| 181 | + cwd=cwd, |
| 182 | + env=env, |
| 183 | + timeout_sec=self.default_exec_timeout_sec, |
| 184 | + ) |
| 185 | + |
| 186 | + def parse(self, *, stdout: str, stderr: str, returncode: int) -> str: |
| 187 | + del stderr, returncode |
| 188 | + return (stdout or "").strip() |
| 189 | + |
| 190 | + def explain_failure(self, *, stdout: str, stderr: str, returncode: int) -> str: |
| 191 | + err = (stderr or "").strip() |
| 192 | + out = (stdout or "").strip() |
| 193 | + bits = [f"claude -p exited with code {returncode}"] |
| 194 | + if err: |
| 195 | + bits.append(err[:2000]) |
| 196 | + elif out: |
| 197 | + bits.append(out[:2000]) |
| 198 | + return ". ".join(bits) |
0 commit comments