Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(providers): add claude_cli provider for Claude Code subscriptions (#1514)
haibeeb183401804388
diff --git a/docs/agent/CLAUDE_CODE_PROVIDER.md b/docs/agent/CLAUDE_CODE_PROVIDER.mdnew file mode 100644index 000000000..218b91899--- /dev/null+++ b/docs/agent/CLAUDE_CODE_PROVIDER.md@@ -0,0 +1,140 @@+# Claude Code as an LLM Provider++Repowise and Claude Code connect in **two independent directions**. This page+covers one of them; enabling it does not enable the other.++| Direction | What it is | Where to read |+|---|---|---|+| Repowise calls Claude Code | The `claude_cli` **LLM provider**. Repowise runs your local Claude Code CLI to write wiki pages, so a Claude subscription works instead of an API key. | This page |+| Claude Code calls Repowise | The `claude-code` **agent target**. Claude Code gets the repowise MCP tools, so you can ask it about your codebase. | [Integrations](INTEGRATIONS.md) |++## `claude_cli` Provider++Use `claude_cli` when you want page generation to run through your local Claude+Code CLI instead of an `ANTHROPIC_API_KEY`:++```bash+repowise init --provider claude_cli --yes+```++Or for an existing index:++```bash+REPOWISE_PROVIDER=claude_cli repowise generate --unwritten+```++To persist the choice, put it in `.repowise/config.yaml`:++```yaml+provider: claude_cli+model: claude_cli/claude-haiku-4-5+```++### Prerequisites++```bash+# Install Claude Code, then authenticate once:+claude login+```++Any plan that can run `claude -p` works — Pro, Max, Team or Enterprise. Repowise+never sees your credentials: the CLI holds them, and authentication happens out+of band exactly as it does for `codex_cli` and `opencode`.++### What the provider runs++```bash+claude -p --output-format json --model <model> --max-turns 1 \+ --strict-mcp-config --tools "" --system-prompt <system> [--effort <level>]+```++Repowise sends the **user** prompt on stdin (prompts carry file context and can+be large) and passes the **system** prompt via `--system-prompt`, which+*replaces* Claude Code's agent preamble rather than appending to it — repowise's+prompt is the whole instruction set, and the coding-agent framing only competes+with it. Repowise removes the tool catalog and adds a final system instruction+to answer directly in one response. The instruction is necessary even with a+single-turn budget: denying individual tools still lets the model attempt one,+consume that turn, and return `error_max_turns` without any page prose.++It parses the single JSON object from stdout, taking `result` as the page+content and mapping `usage`:++| Claude Code field | Repowise field |+|---|---|+| `usage.input_tokens` | `input_tokens` |+| `usage.output_tokens` | `output_tokens` |+| `usage.cache_read_input_tokens` | `cached_tokens` |+| `usage.cache_creation_input_tokens` | recorded in `usage`, not counted as cached |+| `stop_reason` | normalised `stop_reason` |++`claude_cli/*` models are priced at **$0.00**, because billing is handled by the+subscription rather than per-token API spend. The CLI's own `total_cost_usd` is+still recorded under `usage.reported_cost_usd` for auditing.++### Default model++`claude_cli/claude-haiku-4-5` is the default, matching the `anthropic` provider,+whose docstring calls haiku "ample for doc pages". To choose another:++```bash+repowise init --provider claude_cli --model claude_cli/claude-sonnet-4-6+```++The `claude_cli/` prefix is optional on input — a bare slug works too, and both+round-trip through `.repowise/config.yaml`:++```bash+repowise init --provider claude_cli --model claude-opus-4-6+```++### Concurrency++Each page is a full CLI process, and subscription limits are per account.+Serializing makes a 68-page wiki take about an hour; too much concurrency trips+the account limit and fails the run. The provider bounds itself to **4**+concurrent processes, and `init` caps `--concurrency` at 4 for CLI-backed+providers. Override with:++```bash+REPOWISE_CLAUDE_CLI_CONCURRENCY=2 repowise generate --unwritten+```++That variable raises as well as lowers the limit, so 4 is a default rather than+an enforced ceiling. Going higher is reasonable on a plan with a larger+allowance; it is also the fastest way to trip the account limit mid-run.++Budget roughly **9k output tokens and a few minutes per page**, drawn from the+same limits as your interactive Claude Code sessions. On a large repo, prefer+`--path` to scope a run rather than regenerating everything.++### Reasoning++Claude Code's `--effort` flag maps directly to `low`, `medium`, `high`, `xhigh`,+and `max`; `auto` omits the flag and preserves the CLI default. Repowise's+`off`, `none`, and `minimal` modes have no Claude CLI equivalent, so those are+**warned about and ignored** rather than killing an entire docs run.++## Two things worth knowing++- **`--bare` is never passed.** It looks like the right isolation flag, but it+ documents that "Anthropic auth is strictly `ANTHROPIC_API_KEY` or+ `apiKeyHelper` (OAuth and keychain are never read)" — which would defeat the+ entire point of this provider. Isolation comes from a neutral working+ directory plus `--strict-mcp-config`.+- **The subprocess does not run in your repo.** Claude Code auto-discovers+ `CLAUDE.md` from its working directory, so running inside the repo would inject+ your project's agent instructions into every page's prompt — spending tokens+ and letting repo-specific rules bias documentation prose. The provider runs in+ a fresh empty scratch directory for each call and removes it afterward;+ everything the generator needs is already in the prompt.++## Security++- Uses `asyncio.create_subprocess_exec` — never `shell=True`.+- Model names are validated against `^[a-zA-Z0-9][a-zA-Z0-9._/\-]*$` before they+ reach argv.+- All tools are disabled (`--tools ""`) and `--max-turns 1` is set, so+ the call is a pure completion with no filesystem or network access of its own.+- `--strict-mcp-config` stops the subprocess loading MCP servers from your user+ or project config.diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.pyindex b6d623eb9..5d046e725 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py@@ -335,7 +335,8 @@ def _run_generation_phase(console.print(f" Languages: {', '.join(lang_parts)}")# Warn when a local provider runs with default concurrency- if provider.provider_name in ("ollama", "codex_cli", "opencode") and concurrency > 4:+ local_providers = ("ollama", "codex_cli", "claude_cli", "opencode")+ if provider.provider_name in local_providers and concurrency > 4:console.print(f" [{WARN}]Warning:[/] {provider.provider_name} is a local provider "f"running with concurrency={concurrency}. "@@ -411,7 +412,8 @@ def _run_generation_phase(default=None,help=("LLM provider name (anthropic, openai, openrouter, gemini, "- "deepseek, kimi, ollama, litellm, codex_cli, opencode, edenai, mock)."+ "deepseek, kimi, ollama, litellm, codex_cli, claude_cli, opencode, "+ "edenai, mock)."),)@click.option("--model", default=None, help="Model identifier override.")@@ -827,9 +829,7 @@ def init_command(include_submodules=include_submodules,)if seeded:- console.print(- f"[{OK}]Worktree index seeded successfully. Delegating to update...[/]"- )+ console.print(f"[{OK}]Worktree index seeded successfully. Delegating to update...[/]")from repowise.cli.commands.update_cmd.command import run_updateis_workspace = len(scan.repos) > 1 and not no_workspacediff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.pyindex 8af5627e4..ed031d722 100644--- a/packages/cli/src/repowise/cli/helpers.py+++ b/packages/cli/src/repowise/cli/helpers.py@@ -983,8 +983,10 @@ def resolve_provider("or set ANTHROPIC_API_KEY / OPENAI_API_KEY / OPENROUTER_API_KEY / ""OLLAMA_BASE_URL / GEMINI_API_KEY / GOOGLE_API_KEY / DEEPSEEK_API_KEY / ""KIMI_API_KEY / EDENAI_API_KEY / LITELLM_API_KEY. Use "- "REPOWISE_PROVIDER=codex_cli to use an authenticated Codex CLI "- "subscription, or REPOWISE_PROVIDER=opencode to use opencode."+ "REPOWISE_PROVIDER=claude_cli to use an "+ "authenticated Claude Code subscription, REPOWISE_PROVIDER=codex_cli to use "+ "an authenticated Codex CLI subscription, or REPOWISE_PROVIDER=opencode "+ "to use opencode.")@@ -1091,6 +1093,17 @@ def validate_provider_config(provider_name: str | None = None) -> list[str]:)return warnings+ if provider_name == "claude_cli":+ import shutil++ if not shutil.which("claude"):+ warnings.append(+ "Provider 'claude_cli' requires the Claude Code CLI.\n"+ " Install: https://claude.com/claude-code\n"+ " Setup: run 'claude login' once to authenticate"+ )+ return warnings+if provider_name == "opencode":import shutildiff --git a/packages/cli/src/repowise/cli/ui/provider_selection.py b/packages/cli/src/repowise/cli/ui/provider_selection.pyindex 1a9c74452..ae4f0cda8 100644--- a/packages/cli/src/repowise/cli/ui/provider_selection.py+++ b/packages/cli/src/repowise/cli/ui/provider_selection.py@@ -32,6 +32,7 @@ _PROVIDER_DEFAULTS: dict[str, str] = {"kimi": "kimi-for-coding","edenai": "mistral/mistral-small-latest","codex_cli": "codex_cli/default",+ "claude_cli": "claude_cli/claude-haiku-4-5","opencode": "opencode/default","ollama": "qwen3.5:4b","openrouter": "google/gemini-3.5-flash-lite",@@ -46,6 +47,7 @@ _PROVIDER_ENV: dict[str, str] = {"kimi": "KIMI_API_KEY","edenai": "EDENAI_API_KEY","codex_cli": "__CODEX_CLI__",+ "claude_cli": "__CLAUDE_CLI__","opencode": "__OPENCODE_CLI__","ollama": "OLLAMA_BASE_URL","openrouter": "OPENROUTER_API_KEY",@@ -63,6 +65,7 @@ _PROVIDER_SIGNUP: dict[str, str] = {"kimi": "https://www.kimi.com/code/console","edenai": "https://app.edenai.run/user/register","codex_cli": "https://developers.openai.com/codex/cli",+ "claude_cli": "https://claude.com/claude-code","opencode": "https://opencode.ai","ollama": "https://ollama.com/download","openrouter": "https://openrouter.ai/keys",@@ -76,6 +79,7 @@ _PROVIDER_SIGNUP: dict[str, str] = {_PROVIDER_NOTES: dict[str, str] = {"gemini": "recommended","codex_cli": "uses your Codex CLI login",+ "claude_cli": "uses your Claude Code login","opencode": "uses your opencode CLI setup","ollama": "runs on your machine, no key","litellm": "proxy in front of another provider",@@ -104,6 +108,19 @@ def _detect_codex_cli_status() -> tuple[bool, bool]:return installed, is_codex_logged_in() if installed else False+def _detect_claude_cli_status() -> bool:+ """Return ``True`` if the Claude Code CLI is installed on PATH.++ Login state is not probed: ``claude`` keeps its credentials in a keychain or+ an OAuth token store with no cheap, side-effect-free "am I logged in" query,+ so the readiness signal stops at "installed" and an unauthenticated CLI+ surfaces as a provider error on first use.+ """+ import shutil++ return shutil.which("claude") is not None++def _detect_opencode_status() -> bool:"""Return ``True`` if the opencode CLI is installed on PATH."""import shutil@@ -178,6 +195,9 @@ def _detect_provider_status() -> dict[str, str]:installed, logged_in = _detect_codex_cli_status()if installed and logged_in:status[prov] = "codex CLI"+ elif prov == "claude_cli":+ if _detect_claude_cli_status():+ status[prov] = "claude CLI"elif prov == "opencode":if _detect_opencode_status():status[prov] = "opencode CLI"@@ -203,6 +223,28 @@ def _codex_cli_setup_lines() -> list[str]:]+def _claude_cli_setup_lines() -> list[str]:+ installed = _detect_claude_cli_status()+ lines = [+ " [bold]claude_cli[/bold] uses the Claude Code CLI's own login, so a "+ "Claude subscription works here. No API key here.",+ f" Install: [{BRAND}]https://claude.com/claude-code[/]",+ f" Set up: [{BRAND}]claude login[/]",+ "",+ f" To pick a specific model: [{BRAND}]repowise init --provider claude_cli "+ "--model claude_cli/claude-sonnet-4-6[/]",+ ]+ if not installed:+ lines.extend(+ [+ "",+ f" [{WARN}]claude CLI not found on PATH.[/] Install it and retry, "+ "or select another provider.",+ ]+ )+ return lines++def _opencode_setup_lines() -> list[str]:return [" [bold]opencode[/bold] is a local AI coding CLI that manages its own "@@ -247,6 +289,7 @@ def _ollama_setup_lines() -> list[str]:# interactively, so the picker keeps its own narrower list._LOCAL_PROVIDER_SETUP: dict[str, Callable[[], list[str]]] = {"codex_cli": _codex_cli_setup_lines,+ "claude_cli": _claude_cli_setup_lines,"opencode": _opencode_setup_lines,"ollama": _ollama_setup_lines,}diff --git a/packages/core/src/repowise/core/cost_estimator/pricing.py b/packages/core/src/repowise/core/cost_estimator/pricing.pyindex a02f54ea8..6e01e7f25 100644--- a/packages/core/src/repowise/core/cost_estimator/pricing.py+++ b/packages/core/src/repowise/core/cost_estimator/pricing.py@@ -57,6 +57,7 @@ _COST_TABLE_PREFIX: dict[str, tuple[float, float]] = {"llama": (0.0, 0.0),"mock": (0.0, 0.0),"codex_cli/": (0.0, 0.0),+ "claude_cli/": (0.0, 0.0),"opencode/": (0.0, 0.0),}@@ -67,7 +68,7 @@ def _lookup_cost(model_name: str) -> tuple[float, float]:# OpenRouter/LiteLLM slugs carry a routing prefix (`google/gemini-3.5-flash-lite`)# that hides the model from every entry below, which priced them at zero.# `codex_cli/` and `opencode/` are genuinely free, so they keep their prefixes.- if "/" in lower and not lower.startswith(("codex_cli/", "opencode/")):+ if "/" in lower and not lower.startswith(("codex_cli/", "claude_cli/", "opencode/")):lower = lower.rsplit("/", 1)[-1]if lower in _COST_TABLE_EXACT:return _COST_TABLE_EXACT[lower]diff --git a/packages/core/src/repowise/core/generation/cost_tracker.py b/packages/core/src/repowise/core/generation/cost_tracker.pyindex 4d5eeaf83..60eb620e8 100644--- a/packages/core/src/repowise/core/generation/cost_tracker.py+++ b/packages/core/src/repowise/core/generation/cost_tracker.py@@ -90,12 +90,13 @@ def is_local_model(model: str) -> bool:Both the cost ledger and the savings estimate price these at $0: no dollarschange hands per token. Covers Ollama/LM Studio/llama.cpp model strings and- the agent-CLI passthrough prefixes (``codex_cli/``, ``opencode/``).+ the agent-CLI passthrough prefixes (``codex_cli/``, ``claude_cli/``,+ ``opencode/``)."""return (model == "mock"or model.startswith(_LOCAL_MODEL_PREFIXES)- or model.startswith(("codex_cli/", "opencode/"))+ or model.startswith(("codex_cli/", "claude_cli/", "opencode/"))# Bare Ollama tags carry no prefix — the default is plain `qwen3.5:4b`,# and a `family:size` tag is not a shape any hosted vendor uses.or (":" in model and "/" not in model)diff --git a/packages/core/src/repowise/core/providers/llm/__init__.py b/packages/core/src/repowise/core/providers/llm/__init__.pyindex f21264b0d..993a0abaa 100644--- a/packages/core/src/repowise/core/providers/llm/__init__.py+++ b/packages/core/src/repowise/core/providers/llm/__init__.py@@ -19,6 +19,7 @@ Built-in providers:ollama — local inference (llama3.2, codellama, etc.)litellm — 100+ providers via LiteLLM proxycodex_cli — local authenticated Codex CLI via codex exec+ claude_cli — local authenticated Claude Code CLI via claude -popencode — local opencode CLI via opencode runmock — deterministic test provider"""diff --git a/packages/core/src/repowise/core/providers/llm/claude_cli.py b/packages/core/src/repowise/core/providers/llm/claude_cli.pynew file mode 100644index 000000000..b538fad60--- /dev/null+++ b/packages/core/src/repowise/core/providers/llm/claude_cli.py@@ -0,0 +1,470 @@+"""Claude Code CLI provider for repowise.++Delegates generation to the authenticated local Claude Code CLI via ``claude -p``+(headless / print mode). Intended for users whose Claude subscription (Pro, Max,+Team or Enterprise seat) is already configured by ``claude login``; it needs no+ANTHROPIC_API_KEY.++Security: uses ``asyncio.create_subprocess_exec`` (no shell), validates model+names against a safe character set, disables the CLI's tool catalog, and runs+the subprocess in a temporary scratch directory resolved with+``Path.resolve()``.++Two deliberate differences from the other agent-CLI providers:++- ``--bare`` is never passed. It reads like the right isolation flag, but it+ documents "Anthropic auth is strictly ANTHROPIC_API_KEY or apiKeyHelper (OAuth+ and keychain are never read)", which would defeat the point of this provider.+ Isolation comes from a neutral cwd plus ``--strict-mcp-config``.+- The subprocess deliberately does *not* run in the repo, so this provider is+ absent from ``REPO_PATH_PROVIDERS``. Claude Code auto-discovers CLAUDE.md from+ its working directory, and on a large repo that injects the project's agent+ instructions into every page's prompt -- spending tokens and letting+ repo-specific rules bias documentation prose. Everything the generator wants is+ already in the prompt it passes.+"""++from __future__ import annotations++import asyncio+import contextlib+import json+import os+import re+import shutil+import tempfile+from pathlib import Path+from typing import Any++import structlog++from repowise.core.providers.llm.base import (+ BaseProvider,+ CacheHint,+ GeneratedResponse,+ ProviderError,+ ProviderModelOption,+ normalize_stop_reason,+)+from repowise.core.rate_limiter import RateLimiter+from repowise.core.reasoning import ReasoningMode, normalize_reasoning++log = structlog.get_logger(__name__)++# Matches the anthropic provider's default, whose docstring calls haiku "ample+# for doc pages". Overridable with --model / REPOWISE_MODEL.+_DEFAULT_MODEL = "claude-haiku-4-5"+_LABEL_PREFIX = "claude_cli/"++_MODEL_NAME_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._/\-]*$")++# A process spawn plus a full CLI turn on a prompt that can carry a lot of file+# context. Generous, because too low is not a slow page but no page.+_EXEC_TIMEOUT_SECONDS = 600++# This is a one-shot text generation: the prompt already carries the context.+# Claude Code can still try a denied tool and spend the single turn before it+# emits prose, so both halves matter: remove the tool catalog with ``--tools+# ""`` and tell the model explicitly to answer in one response.+_TOOLLESS_SYSTEM_INSTRUCTION = (+ "You have no tools available for this task. Do not attempt to call tools. "+ "Answer the user directly in a single response."+)++_SUPPORTED_REASONING_MODES: tuple[ReasoningMode, ...] = (+ "auto",+ "low",+ "medium",+ "high",+ "xhigh",+ "max",+)++# Subscription seats are rate limited per account and each call is a full CLI+# process. Serializing turns a 68-page wiki into an hour; too much concurrency+# trips the account limit and fails the run. 4 matches the ceiling init applies+# to the other CLI-backed providers.+#+# The env override is a true override, not a clamp: it can raise the fan-out+# above 4 as well as lower it. Deliberate -- a Max seat can take more than a Pro+# one, and only the operator knows which they have -- but it does mean 4 is a+# default rather than an enforced cap.+_DEFAULT_CONCURRENCY = 4+_CONCURRENCY_ENV = "REPOWISE_CLAUDE_CLI_CONCURRENCY"++_NOT_FOUND_MESSAGE = (+ "Claude Code CLI not found. Install it from https://claude.com/claude-code, "+ "then run 'claude login'."+)+++async def _close_subprocess_transport(proc: asyncio.subprocess.Process) -> None:+ """Close asyncio's subprocess transport before the event loop shuts down."""++ transport = getattr(proc, "_transport", None)+ close = getattr(transport, "close", None)+ if not callable(close):+ return+ with contextlib.suppress(Exception):+ close()+ await asyncio.sleep(0)+++def _resolve_claude_executable() -> str | None:+ return shutil.which("claude")+++def _validate_model_name(model: str) -> None:+ if not _MODEL_NAME_RE.match(model):+ raise ProviderError(+ "claude_cli",+ f"Invalid model name {model!r}. Model names may only contain "+ "alphanumeric characters, dots, hyphens, underscores, and forward slashes.",+ )+++def _normalize_model(model: str | None) -> str:+ """Return the native Claude model slug for *model*.++ Accepts the persisted ``claude_cli/<slug>`` label as well as a bare slug, so+ a value read back out of config.yaml round-trips.+ """+ if not model:+ return _DEFAULT_MODEL+ if model in (_LABEL_PREFIX.rstrip("/"), f"{_LABEL_PREFIX}default"):+ return _DEFAULT_MODEL+ if model.startswith(_LABEL_PREFIX):+ return model.removeprefix(_LABEL_PREFIX) or _DEFAULT_MODEL+ return model+++def _model_label(native_model: str) -> str:+ """Return the persisted attribution label for a Claude CLI model.++ Prefixed so cost estimation prices it at zero (a subscription, not API+ spend) and so a page records which path produced it.+ """+ return f"{_LABEL_PREFIX}{native_model}"+++def _resolve_concurrency() -> int:+ raw = os.environ.get(_CONCURRENCY_ENV, "").strip()+ if not raw:+ return _DEFAULT_CONCURRENCY+ try:+ value = int(raw)+ except ValueError:+ log.warning("claude_cli.concurrency.invalid", value=raw, using=_DEFAULT_CONCURRENCY)+ return _DEFAULT_CONCURRENCY+ return max(1, value)+++def _tail(text: str, max_chars: int = 2_000) -> str:+ text = text.strip()+ if len(text) <= max_chars:+ return text+ return text[-max_chars:]+++def _error_message(stderr: str, stdout: str, returncode: int) -> str:+ for candidate in (_tail(stderr), _tail(stdout)):+ if not candidate:+ continue+ if candidate.lstrip().startswith(("{", "[")):+ continue+ return candidate+ return f"claude -p exited with {returncode}"+++def _payload_failure(payload: dict[str, Any]) -> tuple[str, int | None]:+ """Return the useful Claude error text and its HTTP status, when present."""+ raw_status = payload.get("api_error_status")+ status_code = (+ raw_status if isinstance(raw_status, int) and not isinstance(raw_status, bool) else None+ )+ detail = raw_status or payload.get("subtype") or "unknown error"+ result_text = payload.get("result")+ if isinstance(result_text, str) and result_text.strip():+ detail = f"{detail}: {_tail(result_text, max_chars=500)}"+ return f"claude -p reported failure ({detail}).", status_code+++def _parse_result(stdout: str) -> dict[str, Any]:+ """Parse ``--output-format json`` output, tolerating leading noise.++ The CLI emits a single JSON object, but warnings can precede it on stdout,+ so fall back to a line scan before giving up.+ """+ text = stdout.strip()+ if not text:+ raise ProviderError("claude_cli", "claude -p produced no output.")++ with contextlib.suppress(json.JSONDecodeError):+ parsed = json.loads(text)+ if isinstance(parsed, dict):+ return parsed++ for raw_line in reversed(text.splitlines()):+ line = raw_line.strip()+ if not line.startswith("{"):+ continue+ with contextlib.suppress(json.JSONDecodeError):+ parsed = json.loads(line)+ if isinstance(parsed, dict):+ return parsed++ raise ProviderError(+ "claude_cli",+ f"could not parse claude -p JSON output: {_tail(text, max_chars=500)}",+ )+++class ClaudeCliProvider(BaseProvider):+ """LLM provider backed by ``claude -p`` (Claude Code headless mode).++ Args:+ model: Claude model slug (e.g. ``claude-haiku-4-5``,+ ``claude-sonnet-4-6``). Persisted labels like+ ``claude_cli/claude-haiku-4-5`` are accepted and normalized.+ rate_limiter: Accepted for interface consistency; the provider also+ bounds its own subprocess fan-out.+ """++ # A process spawn plus a full CLI turn: the floor is tens of seconds even for+ # a short prompt, so an interactive caller must budget in minutes or it+ # cancels every call it makes (#1119). Stays under _EXEC_TIMEOUT_SECONDS so+ # the caller gives up before the subprocess does and the error names the real+ # cause.+ interactive_timeout_s: float = 180.0++ def __init__(+ self,+ model: str | None = None,+ rate_limiter: RateLimiter | None = None,+ **_ignored: Any,+ ) -> None:+ claude_cmd = _resolve_claude_executable()+ if not claude_cmd:+ raise ProviderError("claude_cli", _NOT_FOUND_MESSAGE)+ self._claude_cmd = claude_cmd+ self._model = _normalize_model(model)+ _validate_model_name(self._model)+ self._rate_limiter = rate_limiter+ self._semaphore: asyncio.Semaphore | None = None+ self._semaphore_loop: asyncio.AbstractEventLoop | None = None++ @property+ def provider_name(self) -> str:+ return "claude_cli"++ @property+ def model_name(self) -> str:+ return _model_label(self._model)++ def supported_reasoning_modes(self) -> tuple[ReasoningMode, ...]:+ return _SUPPORTED_REASONING_MODES++ def available_model_options(self) -> tuple[ProviderModelOption, ...]:+ # The CLI has no machine-readable model catalog to query, so this is a+ # curated list rather than discovery.+ return (+ ProviderModelOption(+ model=_model_label("claude-haiku-4-5"),+ label="claude-haiku-4-5",+ reasoning_modes=_SUPPORTED_REASONING_MODES,+ recommended=True,+ source="fallback",+ notes="fastest; ample for doc pages",+ ),+ ProviderModelOption(+ model=_model_label("claude-sonnet-4-6"),+ label="claude-sonnet-4-6",+ reasoning_modes=_SUPPORTED_REASONING_MODES,+ source="fallback",+ notes="better prose, slower",+ ),+ ProviderModelOption(+ model=_model_label("claude-opus-4-6"),+ label="claude-opus-4-6",+ reasoning_modes=_SUPPORTED_REASONING_MODES,+ source="fallback",+ notes="highest quality; heaviest on subscription limits",+ ),+ )++ def _get_semaphore(self) -> asyncio.Semaphore:+ loop = asyncio.get_running_loop()+ if self._semaphore_loop is not loop:+ self._semaphore = asyncio.Semaphore(_resolve_concurrency())+ self._semaphore_loop = loop+ return self._semaphore # type: ignore[return-value]++ def _build_command(+ self,+ system_prompt: str,+ *,+ reasoning: ReasoningMode = "auto",+ ) -> list[str]:+ cmd = [+ self._claude_cmd,+ "-p",+ "--output-format",+ "json",+ "--model",+ self._model,+ "--max-turns",+ "1",+ "--strict-mcp-config",+ "--tools",+ "",+ ]+ prompt = system_prompt.strip()+ prompt = (+ f"{prompt}\n\n{_TOOLLESS_SYSTEM_INSTRUCTION}"+ if prompt+ else _TOOLLESS_SYSTEM_INSTRUCTION+ )+ # --system-prompt replaces Claude Code's agent preamble rather than+ # appending to it: repowise's prompt is the whole instruction set, and+ # the coding-agent framing only competes with it.+ cmd.extend(["--system-prompt", prompt])++ mode = normalize_reasoning(reasoning)+ if mode in _SUPPORTED_REASONING_MODES[1:]:+ cmd.extend(["--effort", mode])+ elif mode != "auto":+ # ``off``, ``none`` and ``minimal`` have no Claude CLI equivalent.+ log.warning("claude_cli.reasoning.unsupported", requested=mode, using="auto")+ return cmd++ async def generate(+ self,+ system_prompt: str,+ user_prompt: str,+ max_tokens: int = 4096,+ temperature: float = 0.3,+ request_id: str | None = None,+ reasoning: ReasoningMode = "auto",+ cache_hints: tuple[CacheHint, ...] = (),+ ) -> GeneratedResponse:+ # temperature and max_tokens have no CLI equivalent. The base-class+ # contract says to clip rather than raise, so they are accepted and+ # dropped.+ if self._rate_limiter:+ await self._rate_limiter.acquire(estimated_tokens=max_tokens)++ cmd = self._build_command(system_prompt, reasoning=reasoning)++ log.debug("claude_cli.generate.start", model=self.model_name, request_id=request_id)++ async with self._get_semaphore():+ # One directory per call avoids both CLAUDE.md discovery and state+ # leaking between concurrent pages. TemporaryDirectory removes it+ # after success, failure, timeout, or cancellation.+ with tempfile.TemporaryDirectory(prefix="repowise-claude-cli-") as scratch_dir:+ cwd = str(Path(scratch_dir).resolve())+ try:+ proc = await asyncio.create_subprocess_exec(+ *cmd,+ stdin=asyncio.subprocess.PIPE,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ cwd=cwd,+ )+ except FileNotFoundError as exc:+ raise ProviderError("claude_cli", _NOT_FOUND_MESSAGE) from exc++ try:+ stdout_bytes, stderr_bytes = await asyncio.wait_for(+ proc.communicate(user_prompt.encode("utf-8")),+ timeout=_EXEC_TIMEOUT_SECONDS,+ )+ except asyncio.CancelledError:+ with contextlib.suppress(ProcessLookupError):+ proc.kill()+ with contextlib.suppress(ProcessLookupError):+ await proc.wait()+ raise+ except TimeoutError as exc:+ with contextlib.suppress(ProcessLookupError):+ proc.kill()+ with contextlib.suppress(ProcessLookupError):+ await proc.wait()+ raise ProviderError(+ "claude_cli",+ f"claude -p timed out after {_EXEC_TIMEOUT_SECONDS} seconds.",+ ) from exc+ finally:+ await _close_subprocess_transport(proc)++ stdout = stdout_bytes.decode("utf-8", errors="replace") if stdout_bytes else ""+ stderr = stderr_bytes.decode("utf-8", errors="replace") if stderr_bytes else ""++ payload: dict[str, Any] | None = None+ with contextlib.suppress(ProviderError):+ payload = _parse_result(stdout)++ if proc.returncode != 0:+ if payload is not None and (+ payload.get("is_error") or payload.get("subtype") != "success"+ ):+ message, status_code = _payload_failure(payload)+ raise ProviderError("claude_cli", message, status_code=status_code)+ raise ProviderError(+ "claude_cli",+ _error_message(stderr, stdout, proc.returncode),+ )++ if payload is None:+ payload = _parse_result(stdout)++ if payload.get("is_error") or payload.get("subtype") != "success":+ message, status_code = _payload_failure(payload)+ raise ProviderError("claude_cli", message, status_code=status_code)++ content = payload.get("result")+ if not isinstance(content, str) or not content.strip():+ raise ProviderError("claude_cli", "claude -p succeeded but returned no result text.")++ raw_usage = payload.get("usage")+ usage = raw_usage if isinstance(raw_usage, dict) else {}+ input_tokens = int(usage.get("input_tokens", 0) or 0)+ output_tokens = int(usage.get("output_tokens", 0) or 0)+ # The CLI reports cache reads and creations separately; repowise wants a+ # single "served from cache" number, which is the read half.+ cached_tokens = int(usage.get("cache_read_input_tokens", 0) or 0)+ cache_creation_tokens = int(usage.get("cache_creation_input_tokens", 0) or 0)++ stop_reason, provider_stop_reason = normalize_stop_reason(payload.get("stop_reason"))++ log.debug(+ "claude_cli.generate.done",+ input_tokens=input_tokens,+ output_tokens=output_tokens,+ cached_tokens=cached_tokens,+ request_id=request_id,+ )++ usage_payload = {+ **usage,+ "source": "claude_cli",+ "model": self.model_name,+ "cache_creation_input_tokens": cache_creation_tokens,+ # Recorded for auditing only. Cost is priced at zero in the cost+ # table: this is subscription usage, not API spend.+ "reported_cost_usd": payload.get("total_cost_usd"),+ "num_turns": payload.get("num_turns"),+ "stderr": _tail(stderr, max_chars=1_000) if stderr.strip() else "",+ }+ if not usage:+ usage_payload["estimated"] = True++ return GeneratedResponse(+ content=content,+ input_tokens=input_tokens,+ output_tokens=output_tokens,+ cached_tokens=cached_tokens,+ usage=usage_payload,+ stop_reason=stop_reason,+ provider_stop_reason=provider_stop_reason,+ )diff --git a/packages/core/src/repowise/core/providers/llm/registry.py b/packages/core/src/repowise/core/providers/llm/registry.pyindex 11540b105..c2ca5dc7d 100644--- a/packages/core/src/repowise/core/providers/llm/registry.py+++ b/packages/core/src/repowise/core/providers/llm/registry.py@@ -14,6 +14,7 @@ Built-in providers:- ollama → OllamaProvider- litellm → LiteLLMProvider- codex_cli → CodexCliProvider+ - claude_cli → ClaudeCliProvider- opencode → OpenCodeProvider- mock → MockProvider (testing only)@@ -52,6 +53,7 @@ _BUILTIN_PROVIDERS: dict[str, tuple[str, str]] = {"kimi": ("repowise.core.providers.llm.kimi", "KimiProvider"),"edenai": ("repowise.core.providers.llm.edenai", "EdenAIProvider"),"codex_cli": ("repowise.core.providers.llm.codex_cli", "CodexCliProvider"),+ "claude_cli": ("repowise.core.providers.llm.claude_cli", "ClaudeCliProvider"),"opencode": ("repowise.core.providers.llm.opencode", "OpenCodeProvider"),"mock": ("repowise.core.providers.llm.mock", "MockProvider"),}@@ -93,7 +95,7 @@ PROVIDER_BASE_URL_ENVS: dict[str, tuple[str, ...]] = {# proxy the user secured elsewhere). Resolution must never reject one of these# for a "missing" key, and must never fall through to a different provider# because it could not find one.-KEYLESS_PROVIDERS = frozenset({"codex_cli", "opencode", "ollama", "litellm", "mock"})+KEYLESS_PROVIDERS = frozenset({"codex_cli", "claude_cli", "opencode", "ollama", "litellm", "mock"})# Providers that shell out to a CLI and therefore need to be told which repo# they are reasoning about: they pass it as the subprocess working directory.@@ -305,6 +307,7 @@ def get_provider("edenai": "openai", # edenai uses the openai package"litellm": "litellm","codex_cli": "@openai/codex",+ "claude_cli": "@anthropic-ai/claude-code","opencode": "opencode",}package = _missing.get(name, name)diff --git a/packages/core/src/repowise/core/rate_limiter.py b/packages/core/src/repowise/core/rate_limiter.pyindex 9df5453fb..3818d5577 100644--- a/packages/core/src/repowise/core/rate_limiter.py+++ b/packages/core/src/repowise/core/rate_limiter.py@@ -68,6 +68,10 @@ PROVIDER_DEFAULTS: dict[str, RateLimitConfig] = {"deepseek": RateLimitConfig(requests_per_minute=1_000, tokens_per_minute=5_000_000),"kimi": RateLimitConfig(requests_per_minute=1_000, tokens_per_minute=5_000_000),"edenai": RateLimitConfig(requests_per_minute=1_000, tokens_per_minute=2_000_000),+ # Subscription-backed local CLI: the real ceiling is the account's, and+ # each call is a process, so the provider's own semaphore is the binding+ # limit. Kept loose here so this does not double-throttle it.+ "claude_cli": RateLimitConfig(requests_per_minute=120, tokens_per_minute=2_000_000),}diff --git a/packages/server/src/repowise/server/provider_config.py b/packages/server/src/repowise/server/provider_config.pyindex 2528ff23b..35315d56c 100644--- a/packages/server/src/repowise/server/provider_config.py+++ b/packages/server/src/repowise/server/provider_config.py@@ -129,6 +129,18 @@ PROVIDER_CATALOG: list[dict[str, Any]] = ["env_keys": ["LITELLM_API_KEY"],"requires_key": True,},+ {+ "id": "claude_cli",+ "name": "Claude Code (Local CLI)",+ "default_model": "claude_cli/claude-haiku-4-5",+ "models": [+ "claude_cli/claude-haiku-4-5",+ "claude_cli/claude-sonnet-4-6",+ "claude_cli/claude-opus-4-6",+ ],+ "env_keys": [],+ "requires_key": False,+ },{"id": "opencode","name": "OpenCode (Local CLI)",diff --git a/packages/ui/src/settings/provider-settings.tsx b/packages/ui/src/settings/provider-settings.tsxindex 9f7fb658a..b6642ee13 100644--- a/packages/ui/src/settings/provider-settings.tsx+++ b/packages/ui/src/settings/provider-settings.tsx@@ -43,7 +43,7 @@ export interface ProviderValidationState {/** Providers that authenticate without an API key (local runtimes / CLIs).* For these the key affordance is hidden — only reachability is validated. */-const KEYLESS_PROVIDERS = new Set(["ollama", "opencode", "codex_cli", "mock"]);+const KEYLESS_PROVIDERS = new Set(["ollama", "opencode", "codex_cli", "claude_cli", "mock"]);export interface ProviderSettingsProps {providers: ProviderOption[];diff --git a/packages/web/src/components/settings/provider-section.tsx b/packages/web/src/components/settings/provider-section.tsxindex f712a032f..953685cf6 100644--- a/packages/web/src/components/settings/provider-section.tsx+++ b/packages/web/src/components/settings/provider-section.tsx@@ -19,7 +19,7 @@ import {type SaveState,} from "@repowise-dev/ui/settings";-const PROVIDERS = ["gemini", "openai", "anthropic", "deepseek", "kimi", "edenai", "opencode", "ollama", "litellm", "mock"] as const;+const PROVIDERS = ["gemini", "openai", "anthropic", "deepseek", "kimi", "edenai", "claude_cli", "opencode", "ollama", "litellm", "mock"] as const;const EMBEDDERS = ["mock", "gemini", "openai", "openrouter", "edenai", "ollama"] as const;const MODEL_PLACEHOLDERS: Record<string, string> = {@@ -29,6 +29,7 @@ const MODEL_PLACEHOLDERS: Record<string, string> = {deepseek: "deepseek-v4-flash",kimi: "kimi-for-coding",edenai: "mistral/mistral-small-latest",+ claude_cli: "claude_cli/claude-haiku-4-5",opencode: "opencode/default",ollama: "qwen3.5:4b",litellm: "groq/llama-3.1-70b-versatile",@@ -44,6 +45,7 @@ const PROVIDER_ENV_VARS: Record<string, { vars: string[]; installHint: string }>kimi: { vars: ["KIMI_API_KEY"], installHint: "pip install openai" },edenai: { vars: ["EDENAI_API_KEY"], installHint: "pip install openai" },litellm: { vars: ["LITELLM_*"], installHint: "pip install litellm" },+ claude_cli: { vars: [], installHint: "https://claude.com/claude-code, then: claude login" },opencode: { vars: [], installHint: "curl -fsSL https://opencode.ai/install | bash" },mock: { vars: [], installHint: "No key needed" },};diff --git a/tests/providers/test_registry.py b/tests/providers/test_registry.pyindex af5318ccd..2a5d5446a 100644--- a/tests/providers/test_registry.py+++ b/tests/providers/test_registry.py@@ -117,5 +117,5 @@ class TestCustomProviderRegistration:assert received.get("api_key") == "key-123"def test_builtin_count(self) -> None:- """Sanity check: we have exactly 11 built-in providers."""- assert len(_BUILTIN_PROVIDERS) == 12+ """Sanity check: we have exactly 13 built-in providers."""+ assert len(_BUILTIN_PROVIDERS) == 13diff --git a/tests/unit/cli/test_init_ux.py b/tests/unit/cli/test_init_ux.pyindex 30ae90d1d..cbd58744a 100644--- a/tests/unit/cli/test_init_ux.py+++ b/tests/unit/cli/test_init_ux.py@@ -241,7 +241,12 @@ def test_an_unusable_ollama_url_says_so_instead_of_blaming_the_daemon(def test_the_keyless_providers_get_setup_help_instead_of_a_key_prompt() -> None:"""Ollama used to be registered like a hosted provider, so selecting itasked for an API key it does not have and bounced forever on Enter."""- assert set(provider_selection._LOCAL_PROVIDER_SETUP) == {"codex_cli", "opencode", "ollama"}+ assert set(provider_selection._LOCAL_PROVIDER_SETUP) == {+ "codex_cli",+ "claude_cli",+ "opencode",+ "ollama",+ }for name, lines in provider_selection._LOCAL_PROVIDER_SETUP.items():rendered = "\n".join(lines()).lower()assert rendered.strip(), f"{name} has no setup help"diff --git a/tests/unit/generation/test_cost_pricing.py b/tests/unit/generation/test_cost_pricing.pyindex c44d9078e..1f8469330 100644--- a/tests/unit/generation/test_cost_pricing.py+++ b/tests/unit/generation/test_cost_pricing.py@@ -41,6 +41,16 @@ def test_unknown_model_still_falls_back() -> None:assert get_model_pricing("totally-made-up-model-9000") == _FALLBACK_PRICING+def test_subscription_cli_models_are_zero_cost() -> None:+ """A Claude subscription is not metered API spend in the runtime ledger."""+ for model in (+ "codex_cli/gpt-5.5",+ "claude_cli/claude-haiku-4-5",+ "opencode/anthropic/claude-sonnet-4-6",+ ):+ assert get_model_pricing(model) == {"input": 0.0, "output": 0.0}++def test_dated_opus_variant_prices_at_opus_tier_not_sonnet_fallback() -> None:# An Opus session id the exact table misses (dated / future point release)# must resolve to the Opus tier, not the Sonnet-priced fallback — otherwisediff --git a/tests/unit/server/mcp/test_answer_synthesis_timeout.py b/tests/unit/server/mcp/test_answer_synthesis_timeout.pyindex 2a4f1ad1b..c2fdf1dcf 100644--- a/tests/unit/server/mcp/test_answer_synthesis_timeout.py+++ b/tests/unit/server/mcp/test_answer_synthesis_timeout.py@@ -104,7 +104,7 @@ def test_a_provider_budget_above_the_ceiling_is_clamped(excessive):# --- the regression itself -------------------------------------------------[email protected]("name", ["codex_cli", "opencode"])[email protected]("name", ["codex_cli", "claude_cli", "opencode"])def test_agent_cli_providers_get_more_than_the_old_thirty_seconds(name):"""#1119: 30s cancelled a codex/opencode turn before it could ever return."""cls = _load_provider_class(name)@@ -136,6 +136,7 @@ def test_every_builtin_provider_has_a_deliberate_budget():"ollama": 120.0,"litellm": 120.0,"codex_cli": 180.0,+ "claude_cli": 180.0,"opencode": 180.0,}assert set(expected) == set(_BUILTIN_PROVIDERS), (@@ -147,9 +148,10 @@ def test_every_builtin_provider_has_a_deliberate_budget():def test_agent_cli_budget_stays_under_its_own_subprocess_ceiling():"""The caller must give up before the subprocess does, or the error is wrong."""- from repowise.core.providers.llm import codex_cli, opencode+ from repowise.core.providers.llm import claude_cli, codex_cli, opencodeassert codex_cli.CodexCliProvider.interactive_timeout_s < codex_cli._EXEC_TIMEOUT_SECONDS+ assert claude_cli.ClaudeCliProvider.interactive_timeout_s < claude_cli._EXEC_TIMEOUT_SECONDSassert opencode.OpenCodeProvider.interactive_timeout_s < opencode._EXEC_TIMEOUT_SECONDSdiff --git a/tests/unit/test_providers/test_claude_cli_provider.py b/tests/unit/test_providers/test_claude_cli_provider.pynew file mode 100644index 000000000..4fd6a2193--- /dev/null+++ b/tests/unit/test_providers/test_claude_cli_provider.py@@ -0,0 +1,432 @@+"""Unit tests for ClaudeCliProvider.++All tests mock the Claude Code subprocess; no real ``claude`` calls are made.+"""++from __future__ import annotations++import asyncio+import json+from pathlib import Path+from typing import Any++import pytest++from repowise.core.providers.llm.base import GeneratedResponse, ProviderError+from repowise.core.providers.llm.claude_cli import (+ ClaudeCliProvider,+ _model_label,+ _normalize_model,+ _parse_result,+)+++class FakeProcess:+ def __init__(+ self,+ *,+ returncode: int = 0,+ stdout: str = "",+ stderr: str = "",+ on_communicate: Any | None = None,+ transport: Any | None = None,+ ) -> None:+ self.returncode = returncode+ self._stdout = stdout+ self._stderr = stderr+ self._on_communicate = on_communicate+ self._transport = transport+ self.stdin_input: bytes | None = None+ self.killed = False++ async def communicate(self, input: bytes | None = None) -> tuple[bytes, bytes]:+ self.stdin_input = input+ if self._on_communicate is not None:+ await self._on_communicate()+ return self._stdout.encode("utf-8"), self._stderr.encode("utf-8")++ def kill(self) -> None:+ self.killed = True++ async def wait(self) -> int:+ return self.returncode+++class FakeTransport:+ def __init__(self) -> None:+ self.closed = False++ def close(self) -> None:+ self.closed = True+++def _success_json(text: str = "OK", **overrides: Any) -> str:+ payload: dict[str, Any] = {+ "type": "result",+ "subtype": "success",+ "is_error": False,+ "stop_reason": "end_turn",+ "num_turns": 1,+ "total_cost_usd": 0.0179915,+ "result": text,+ "usage": {+ "input_tokens": 120,+ "output_tokens": 40,+ "cache_read_input_tokens": 30,+ "cache_creation_input_tokens": 7955,+ },+ }+ payload.update(overrides)+ return json.dumps(payload) + "\n"+++def claude_on_path(monkeypatch):+ monkeypatch.setattr("shutil.which", lambda cmd: "/usr/bin/claude" if cmd == "claude" else None)+ return "/usr/bin/claude"+++# ---------------------------------------------------------------------------+# Model naming+# ---------------------------------------------------------------------------+++def test_provider_name_and_default_model(claude_on_path):+ provider = ClaudeCliProvider()+ assert provider.provider_name == "claude_cli"+ assert provider.model_name == "claude_cli/claude-haiku-4-5"+++ ("given", "expected"),+ [+ (None, "claude-haiku-4-5"),+ ("claude-sonnet-4-6", "claude-sonnet-4-6"),+ # A persisted label must round-trip rather than become "claude_cli/claude_cli/...".+ ("claude_cli/claude-sonnet-4-6", "claude-sonnet-4-6"),+ ("claude_cli/default", "claude-haiku-4-5"),+ ],+)+def test_model_normalization_round_trips(given, expected):+ assert _normalize_model(given) == expected+++def test_model_label_is_prefixed(claude_on_path):+ assert _model_label("claude-opus-4-6") == "claude_cli/claude-opus-4-6"+ assert ClaudeCliProvider(model="claude_cli/claude-opus-4-6").model_name == (+ "claude_cli/claude-opus-4-6"+ )+++def test_invalid_model_name_is_rejected(claude_on_path):+ """Model names reach argv, so they are validated against a safe charset."""+ with pytest.raises(ProviderError, match="Invalid model name"):+ ClaudeCliProvider(model="claude; rm -rf /")+++def test_missing_cli_raises(monkeypatch):+ monkeypatch.setattr("shutil.which", lambda _cmd: None)+ with pytest.raises(ProviderError, match="Claude Code CLI not found"):+ ClaudeCliProvider()+++def test_reasoning_modes_match_the_claude_cli_effort_flag(claude_on_path):+ assert ClaudeCliProvider().supported_reasoning_modes() == (+ "auto",+ "low",+ "medium",+ "high",+ "xhigh",+ "max",+ )+++def test_available_model_options_are_labelled(claude_on_path):+ options = ClaudeCliProvider().available_model_options()+ assert [o.model for o in options] == [+ "claude_cli/claude-haiku-4-5",+ "claude_cli/claude-sonnet-4-6",+ "claude_cli/claude-opus-4-6",+ ]+ assert sum(1 for o in options if o.recommended) == 1+ assert all(+ o.reasoning_modes == ClaudeCliProvider().supported_reasoning_modes() for o in options+ )+++# ---------------------------------------------------------------------------+# generate()+# ---------------------------------------------------------------------------+++async def test_generate_success(claude_on_path, monkeypatch):+ proc = FakeProcess(stdout=_success_json("Hello from Claude"), transport=FakeTransport())+ captured: dict[str, Any] = {}++ async def fake_exec(*args, **kwargs):+ captured["args"] = args+ captured["kwargs"] = kwargs+ return proc++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ result = await ClaudeCliProvider(model="claude-sonnet-4-6").generate(+ "system rules", "user context"+ )++ assert isinstance(result, GeneratedResponse)+ assert result.content == "Hello from Claude"+ assert result.input_tokens == 120+ assert result.output_tokens == 40+ # cached_tokens is the *read* half; creations are recorded separately.+ assert result.cached_tokens == 30+ assert result.usage["cache_creation_input_tokens"] == 7955+ assert result.stop_reason == "end_turn"+ assert result.usage["source"] == "claude_cli"+ assert result.usage["model"] == "claude_cli/claude-sonnet-4-6"++ # The user prompt goes on stdin, not argv (prompts are large).+ assert proc.stdin_input == b"user context"++ args = list(captured["args"])+ assert args[0] == claude_on_path+ assert "-p" in args+ assert args[args.index("--model") + 1] == "claude-sonnet-4-6"+ system_prompt = args[args.index("--system-prompt") + 1]+ assert system_prompt.startswith("system rules\n\n")+ assert "You have no tools available" in system_prompt+ assert "single response" in system_prompt+ assert args[args.index("--max-turns") + 1] == "1"+ assert "--strict-mcp-config" in args+ assert args[args.index("--tools") + 1] == ""+ assert "--disallowed-tools" not in args+ # --bare would force ANTHROPIC_API_KEY and never read the OAuth login,+ # defeating the point of this provider.+ assert "--bare" not in args+++async def test_generate_runs_outside_the_repo(claude_on_path, monkeypatch, tmp_path):+ """cwd must not be a repo, or CLAUDE.md is auto-discovered into every prompt."""+ captured: dict[str, Any] = {}++ async def fake_exec(*args, **kwargs):+ captured["kwargs"] = kwargs+ return FakeProcess(stdout=_success_json())++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ await ClaudeCliProvider().generate("sys", "user")++ cwd = captured["kwargs"]["cwd"]+ assert cwd is not None+ assert "repowise-claude-cli-" in str(cwd)+ assert not Path(cwd).exists(), "the per-call scratch directory leaked"++[email protected]("reasoning", ["low", "medium", "high", "xhigh", "max"])+async def test_supported_reasoning_is_passed_as_effort(claude_on_path, monkeypatch, reasoning):+ captured: dict[str, Any] = {}++ async def fake_exec(*args, **_kwargs):+ captured["args"] = args+ return FakeProcess(stdout=_success_json())++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ result = await ClaudeCliProvider().generate("sys", "user", reasoning=reasoning)+ args = list(captured["args"])+ assert result.content == "OK"+ assert args[args.index("--effort") + 1] == reasoning+++async def test_unsupported_reasoning_warns_but_does_not_raise(claude_on_path, monkeypatch):+ """Raising here would kill a whole docs run over a flag the CLI cannot express."""++ captured: dict[str, Any] = {}++ async def fake_exec(*args, **_kwargs):+ captured["args"] = args+ return FakeProcess(stdout=_success_json())++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ result = await ClaudeCliProvider().generate("sys", "user", reasoning="none")+ assert result.content == "OK"+ assert "--effort" not in captured["args"]+++async def test_nonzero_exit_raises_with_stderr(claude_on_path, monkeypatch):+ async def fake_exec(*_args, **_kwargs):+ return FakeProcess(returncode=1, stderr="credit balance too low")++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ with pytest.raises(ProviderError, match="credit balance too low"):+ await ClaudeCliProvider().generate("sys", "user")+++async def test_nonzero_exit_surfaces_json_error_and_http_status(claude_on_path, monkeypatch):+ """Claude writes API failures to stdout as JSON and often leaves stderr empty."""++ async def fake_exec(*_args, **_kwargs):+ return FakeProcess(+ returncode=1,+ stdout=_success_json(+ "There's an issue with the selected model.",+ subtype="error_during_execution",+ is_error=True,+ api_error_status=404,+ ),+ )++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ with pytest.raises(ProviderError, match="selected model") as caught:+ await ClaudeCliProvider().generate("sys", "user")++ assert caught.value.status_code == 404+++async def test_error_subtype_raises(claude_on_path, monkeypatch):+ async def fake_exec(*_args, **_kwargs):+ return FakeProcess(+ stdout=_success_json(+ "", subtype="error_max_turns", is_error=True, api_error_status=None+ )+ )++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ with pytest.raises(ProviderError, match="error_max_turns"):+ await ClaudeCliProvider().generate("sys", "user")+++async def test_empty_result_raises(claude_on_path, monkeypatch):+ async def fake_exec(*_args, **_kwargs):+ return FakeProcess(stdout=_success_json(" "))++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ with pytest.raises(ProviderError, match="no result text"):+ await ClaudeCliProvider().generate("sys", "user")+++async def test_timeout_kills_process_and_raises(claude_on_path, monkeypatch):+ monkeypatch.setattr(+ "repowise.core.providers.llm.claude_cli._EXEC_TIMEOUT_SECONDS",+ 0.01,+ )++ async def on_communicate() -> None:+ await asyncio.sleep(1)++ proc = FakeProcess(stdout="", on_communicate=on_communicate)++ async def fake_exec(*_args, **_kwargs):+ return proc++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ with pytest.raises(ProviderError, match="timed out"):+ await ClaudeCliProvider().generate("sys", "user")++ assert proc.killed+++async def test_cancellation_kills_process(claude_on_path, monkeypatch):+ """The interactive caller cancels at 180s; the 600s CLI must not keep running."""+ started = asyncio.Event()++ async def on_communicate() -> None:+ started.set()+ await asyncio.Event().wait()++ proc = FakeProcess(on_communicate=on_communicate)++ async def fake_exec(*_args, **_kwargs):+ return proc++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ task = asyncio.create_task(ClaudeCliProvider().generate("sys", "user"))+ await started.wait()+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ assert proc.killed+++async def test_transport_is_closed(claude_on_path, monkeypatch):+ transport = FakeTransport()++ async def fake_exec(*_args, **_kwargs):+ return FakeProcess(stdout=_success_json(), transport=transport)++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ await ClaudeCliProvider().generate("sys", "user")+ assert transport.closed+++# ---------------------------------------------------------------------------+# Output parsing+# ---------------------------------------------------------------------------+++def test_parse_result_tolerates_leading_noise():+ noisy = 'warning: something\n{"subtype": "success", "result": "hi"}\n'+ assert _parse_result(noisy)["result"] == "hi"+++def test_parse_result_rejects_unparseable_output():+ with pytest.raises(ProviderError, match="could not parse"):+ _parse_result("not json at all")+++def test_parse_result_rejects_empty_output():+ with pytest.raises(ProviderError, match="no output"):+ _parse_result(" ")+++async def test_missing_usage_is_flagged_estimated(claude_on_path, monkeypatch):+ async def fake_exec(*_args, **_kwargs):+ return FakeProcess(stdout=json.dumps({"subtype": "success", "result": "hi"}) + "\n")++ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)++ result = await ClaudeCliProvider().generate("sys", "user")+ assert result.usage["estimated"] is True+ assert result.input_tokens == 0+ assert result.output_tokens == 0+++# ---------------------------------------------------------------------------+# Registration+# ---------------------------------------------------------------------------+++def test_registered_as_keyless_provider():+ from repowise.core.providers.llm.registry import KEYLESS_PROVIDERS, provider_is_usable++ assert "claude_cli" in KEYLESS_PROVIDERS+ # Keyless: never rejected for a "missing" key.+ assert provider_is_usable("claude_cli", lambda _name: None) is True+++def test_subscription_usage_is_priced_at_zero():+ """A seat is not API spend; the bare `claude` prefixes would price it wrongly."""+ from repowise.core.cost_estimator.pricing import _lookup_cost++ assert _lookup_cost("claude_cli/claude-haiku-4-5") == (0.0, 0.0)+ assert _lookup_cost("claude_cli/claude-opus-4-6") == (0.0, 0.0)+ # The keyed API path is unaffected.+ assert _lookup_cost("claude-haiku-4-5") != (0.0, 0.0)+++def test_resolves_through_the_registry(claude_on_path):+ from repowise.core.providers.llm.registry import get_provider++ provider = get_provider("claude_cli")+ assert provider.provider_name == "claude_cli"+ assert provider.model_name == "claude_cli/claude-haiku-4-5"diff --git a/website/claude-cli.md b/website/claude-cli.mdnew file mode 100644index 000000000..1c356d4c4--- /dev/null+++ b/website/claude-cli.md@@ -0,0 +1,128 @@+---+layout: default+title: Claude Code Provider+nav_order: 5.7+---++# Claude Code Provider+{: .no_toc }++Use Repowise with your Claude subscription via the `claude_cli` LLM provider. No API key — the Claude Code CLI holds the auth.+{: .fs-6 .fw-300 }++---++## Table of contents+{: .no_toc .text-delta }++1. TOC+{:toc}++---++## Quick setup++```bash+# 1. Install Claude Code, then authenticate once+claude login++# 2. Point Repowise at it+repowise init --provider claude_cli --yes+```++Any plan that can run `claude -p` works — Pro, Max, Team or Enterprise.++To use it on an index you already have:++```bash+REPOWISE_PROVIDER=claude_cli repowise generate --unwritten+```++Or persist it in `.repowise/config.yaml`:++```yaml+provider: claude_cli+model: claude_cli/claude-haiku-4-5+```++## Two directions, one name++This page is about Repowise **calling** Claude Code to write your wiki. The+opposite direction — Claude Code calling Repowise's MCP tools to answer questions+about your codebase — is the `claude-code` agent target, set up with+`repowise agents add --target=claude-code`. They are independent; enabling one+does not enable the other.++## Choosing a model++`claude_cli/claude-haiku-4-5` is the default, matching the `anthropic` provider.++```bash+repowise init --provider claude_cli --model claude_cli/claude-sonnet-4-6+```++The `claude_cli/` prefix is optional on input:++```bash+repowise init --provider claude_cli --model claude-opus-4-6+```++| Model | Notes |+|---|---|+| `claude-haiku-4-5` | Fastest, and ample for doc pages. Default. |+| `claude-sonnet-4-6` | Better prose, slower. |+| `claude-opus-4-6` | Highest quality, heaviest on subscription limits. |++## Cost++`claude_cli/*` is priced at **$0.00** in cost estimates and the cost history,+because a subscription is not per-token API spend. The CLI's own reported cost is+kept under `usage.reported_cost_usd` for auditing.++What it does consume is your **subscription rate limits**, the same ones your+interactive Claude Code sessions use. Budget roughly 9k output tokens and a few+minutes per page. A full wiki on a large repo is a real chunk of usage, so scope+runs with `--path` rather than reaching for `--all`:++```bash+repowise generate --path src/api+```++Concurrency defaults to 4 processes. The variable below overrides it in either+direction -- lower it if you are hitting limits, and note that raising it past 4+is allowed but is the quickest way to hit them:++```bash+REPOWISE_CLAUDE_CLI_CONCURRENCY=2 repowise generate --unwritten+```++## Reasoning++Claude Code's `--effort` flag maps directly to Repowise's `low`, `medium`,+`high`, `xhigh`, and `max` reasoning modes. `auto` leaves the flag unset and+uses the CLI default. The unsupported `off`, `none`, and `minimal` modes log a+warning and proceed with the default rather than failing the run.++## Embeddings are separate++Anthropic has no embeddings API, so `claude_cli` cannot serve as an embedder. If+you want semantic search rather than keyword-only, pick an embedder separately:++```bash+repowise init --provider claude_cli --embedder ollama # local, no key+```++Otherwise the index keeps `embedder: mock` and search stays lexical.++## Troubleshooting++**`Claude Code CLI not found`** — `claude` is not on `PATH`. Install it from+[claude.com/claude-code](https://claude.com/claude-code).++**Authentication errors on the first page** — run `claude login`. Readiness+detection stops at "is it installed", because the CLI keeps credentials in a+keychain or OAuth store with no cheap way to probe login state.++**Rate-limit failures partway through a run** — lower+`REPOWISE_CLAUDE_CLI_CONCURRENCY`, or scope the run with `--path`. Completed+pages are kept, so re-running picks up where it stopped with `--unwritten`.