Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(providers): declare every LLM provider once, as a ProviderSpec (#3168)

Raghav Chamadiya8be923b10ef6
diff --git a/packages/api-client/src/types/misc.ts b/packages/api-client/src/types/misc.ts
index afe4f92f6..7838812a4 100644
--- a/packages/api-client/src/types/misc.ts
+++ b/packages/api-client/src/types/misc.ts
@@ -27,6 +27,12 @@ export interface ProviderInfo {
models: string[];
default_model: string;
configured: boolean;
+ /** `false` for providers that authenticate without an API key. */
+ requires_key?: boolean;
+ /** Env vars a user sets to make the provider usable. */
+ env_vars?: string[];
+ /** One line on how to install or set it up. */
+ setup_hint?: string;
}
export interface ProvidersResponse {
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py b/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
index 07c22c273..a831ffd0e 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
@@ -998,9 +998,7 @@ class CodexTarget:
answer: the setup path warns when it writes config for a CLI that is
installed and signed out.
"""
- import shutil
-
- return shutil.which("codex") is not None or (Path.home() / ".codex").is_dir()
+ return IDENTITY.is_installed() or (Path.home() / ".codex").is_dir()
def detect(self, repo_path: Path | None = None) -> list[Registration]:
return detect(repo_path)
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py b/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py
index 678b48751..947ba0688 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py
@@ -380,11 +380,9 @@ class CursorTarget:
workspace carrying one is worth configuring even from a machine where
the editor was never installed.
"""
- import shutil
-
if repo_path is not None and (repo_path / ".cursor").is_dir():
return True
- if shutil.which("cursor") is not None:
+ if IDENTITY.is_installed():
return True
return (Path.home() / ".cursor").is_dir()
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/hermes.py b/packages/cli/src/repowise/cli/agent_targets/targets/hermes.py
index 7b534bceb..1ee0ec997 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/hermes.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/hermes.py
@@ -827,9 +827,7 @@ class HermesTarget:
convention two other agents also write, so reading it as evidence the
user has Hermes would pre-tick this agent for anyone using Codex.
"""
- import shutil
-
- if shutil.which("hermes") is not None:
+ if IDENTITY.is_installed():
return True
return hermes_home().is_dir()
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py b/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py
index 5a2309c64..7c4457643 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py
@@ -607,9 +607,7 @@ class OpenCodeTarget:
as evidence the user has OpenCode would make our own output the reason
the agent keeps being offered.
"""
- import shutil
-
- if shutil.which("opencode") is not None:
+ if IDENTITY.is_installed():
return True
return user_config_dir().is_dir()
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py b/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py
index 81a4228ec..190d1b6f7 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py
@@ -286,11 +286,9 @@ class VSCodeTarget:
never installed, because the file is committed and read by whoever
opens the repo next.
"""
- import shutil
-
if repo_path is not None and (repo_path / ".vscode").is_dir():
return True
- if shutil.which("code") is not None:
+ if IDENTITY.is_installed():
return True
home = Path.home()
return any((home / candidate).is_dir() for candidate in (".vscode", ".vscode-server"))
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
index cb23baf4e..de19b1e64 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
@@ -415,8 +415,10 @@ def _run_generation_phase(
console.print(f" Languages: {', '.join(lang_parts)}")
# Warn when a local provider runs with default concurrency
- local_providers = ("ollama", "codex_cli", "claude_cli", "opencode")
- if provider.provider_name in local_providers and concurrency > 4:
+ from repowise.core.providers.llm.specs import PROVIDER_SPECS
+
+ spec = PROVIDER_SPECS.get(provider.provider_name)
+ if spec is not None and spec.local and concurrency > 4:
warn(
f" {provider.provider_name} is a local provider "
f"running with concurrency={concurrency}. "
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
index 53a5eb6fc..cbb0719f0 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/workspace.py
@@ -241,14 +241,17 @@ def _run_workspace_deterministic_generation(
def _workspace_generation_provider_for_repo(provider: Any, repo_path: Path) -> Any:
"""Return a generation provider bound to the current workspace repo.
- The Codex CLI provider shells out ``codex exec --cd <repo>``, so it must be
- re-resolved against each repo's path; all other providers are path-agnostic
- and returned unchanged.
+ A provider that runs its CLI in the repo's directory (``needs_repo_cwd``)
+ is re-resolved against each repo's path; all other providers are
+ path-agnostic and returned unchanged.
"""
+ from repowise.core.providers.llm.specs import PROVIDER_SPECS
- if getattr(provider, "provider_name", None) != "codex_cli":
+ name = getattr(provider, "provider_name", None)
+ spec = PROVIDER_SPECS.get(name) if isinstance(name, str) else None
+ if spec is None or not spec.needs_repo_cwd:
return provider
- return resolve_provider("codex_cli", getattr(provider, "model_name", None), repo_path)
+ return resolve_provider(name, getattr(provider, "model_name", None), repo_path)
@dataclass
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index 69636a21d..c812a008d 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -1035,14 +1035,6 @@ def config_fingerprint(repo_path: Path) -> str:
# ---------------------------------------------------------------------------
-def _is_codex_cli_available() -> bool:
- """Check if the Codex CLI binary is available."""
-
- import shutil
-
- return shutil.which("codex") is not None
-
-
def resolve_provider(
provider_name: str | None,
model: str | None,
@@ -1300,48 +1292,26 @@ def validate_provider_config(provider_name: str | None = None) -> list[str]:
# Required environment variables per provider, read from the registry that
# also drives resolution, so a provider added there is validated here without
- # a second edit. The agent-CLI providers are absent by design: they need no
- # env var, so they are handled by the binary checks below instead.
- from repowise.core.providers.llm.registry import (
- PROVIDER_API_KEY_ENVS,
- provider_required_envs,
- )
+ # a second edit. The agent-CLI providers need no env var; the check for them
+ # is whether their CLI is installed.
+ from repowise.core.agents.identity import identity_for_provider
+ from repowise.core.providers.llm.registry import provider_required_envs
+ from repowise.core.providers.llm.specs import PROVIDER_SPECS
provider_env_vars = {
- name: list(provider_required_envs(name)) for name in (*PROVIDER_API_KEY_ENVS, "ollama")
+ name: list(provider_required_envs(name))
+ for name in PROVIDER_SPECS
+ if provider_required_envs(name)
}
if provider_name:
- if provider_name == "codex_cli":
- if not _is_codex_cli_available():
- warnings.append(
- "Provider 'codex_cli' requires the Codex CLI. "
- "Install it with: npm install -g @openai/codex"
- )
- return warnings
-
- if provider_name == "claude_cli":
- import shutil
-
- if not shutil.which("claude"):
+ agent = identity_for_provider(provider_name)
+ if agent is not None:
+ if not agent.is_installed():
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 shutil
-
- if not shutil.which("opencode"):
- warnings.append(
- "Provider 'opencode' requires the opencode CLI.\n"
- " Install: curl -fsSL https://opencode.ai/install | bash\n"
- " Setup: run 'opencode' once to configure your provider\n"
- " Models: opencode models (list available models)\n"
- " More: https://opencode.ai\n"
- " Usage: repowise init --provider opencode --model opencode/openai/gpt-5"
+ f"Provider '{provider_name}' requires the {agent.display_name} CLI.\n"
+ f" Install: {agent.install_hint}\n"
+ f" Setup: {agent.login_hint}"
)
return warnings
@@ -1350,46 +1320,22 @@ def validate_provider_config(provider_name: str | None = None) -> list[str]:
warnings.append(f"Unknown provider '{provider_name}' - cannot validate configuration")
return warnings
+ # Any one of a provider's env vars satisfies it (GEMINI_API_KEY or
+ # GOOGLE_API_KEY), the same rule resolution applies.
env_vars = provider_env_vars[provider_name]
- missing_vars = []
-
- if provider_name == "gemini":
- # Special case: either GEMINI_API_KEY or GOOGLE_API_KEY
- if not (_is_env_var_set("GEMINI_API_KEY") or _is_env_var_set("GOOGLE_API_KEY")):
- missing_vars = env_vars
- else:
- for var in env_vars:
- if not _is_env_var_set(var):
- missing_vars.append(var)
-
- if missing_vars:
- warnings.append(
- f"Provider '{provider_name}' requires environment variables: {', '.join(missing_vars)}"
- )
+ if not any(_is_env_var_set(var) for var in env_vars):
+ warnings.append(f"Provider '{provider_name}' requires {' or '.join(env_vars)}")
else:
# Check all providers - warn about any that could be configured but are missing keys
for name, env_vars in provider_env_vars.items():
- if name == "gemini":
- if os.environ.get("REPOWISE_PROVIDER") == "gemini" and not (
- _is_env_var_set("GEMINI_API_KEY") or _is_env_var_set("GOOGLE_API_KEY")
- ):
- # Only warn if it looks like they might be trying to use gemini
- warnings.append(
- "Provider 'gemini' requires GEMINI_API_KEY or GOOGLE_API_KEY environment variable"
- )
+ if any(_is_env_var_set(var) for var in env_vars):
continue
-
- missing = [var for var in env_vars if not _is_env_var_set(var)]
- if missing:
- # Only warn if this provider is explicitly requested OR
- # if the env var exists but is invalid (empty)
- env_var_exists = any(_is_env_var_exists(var) for var in env_vars)
- explicitly_requested = os.environ.get("REPOWISE_PROVIDER") == name
-
- if explicitly_requested or env_var_exists:
- warnings.append(
- f"Provider '{name}' requires environment variables: {', '.join(missing)}"
- )
+ # Only warn if this provider is explicitly requested OR
+ # if the env var exists but is invalid (empty)
+ env_var_exists = any(_is_env_var_exists(var) for var in env_vars)
+ explicitly_requested = os.environ.get("REPOWISE_PROVIDER") == name
+ if explicitly_requested or env_var_exists:
+ warnings.append(f"Provider '{name}' requires {' or '.join(env_vars)}")
return warnings
diff --git a/packages/cli/src/repowise/cli/mcp_config.py b/packages/cli/src/repowise/cli/mcp_config.py
index 92c2dc040..aab7e3cc4 100644
--- a/packages/cli/src/repowise/cli/mcp_config.py
+++ b/packages/cli/src/repowise/cli/mcp_config.py
@@ -19,12 +19,13 @@ descriptor file and a registry line.
from __future__ import annotations
-import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
+from repowise.core.agents.identity import CODEX
+
def _looks_transient(path: Path) -> bool:
"""True when *path* lives somewhere that won't survive (temp, uvx cache).
@@ -108,7 +109,7 @@ def generate_mcp_config(repo_path: Path, *, command: str | None = None) -> dict:
def resolve_codex_executable() -> str | None:
"""Return the executable path used to launch Codex, or None if unavailable."""
- return shutil.which("codex")
+ return CODEX.which()
def is_codex_cli_installed() -> bool:
@@ -132,19 +133,7 @@ def is_codex_cli_installed() -> bool:
def is_codex_logged_in() -> bool:
"""Return True when the local Codex CLI reports an authenticated session."""
- codex_cmd = resolve_codex_executable()
- if not codex_cmd or not is_codex_cli_installed():
- return False
- try:
- result = subprocess.run(
- [codex_cmd, "login", "status"],
- capture_output=True,
- text=True,
- timeout=10,
- )
- except (OSError, subprocess.TimeoutExpired):
- return False
- return result.returncode == 0
+ return is_codex_cli_installed() and CODEX.is_logged_in()
# ---------------------------------------------------------------------------
diff --git a/packages/cli/src/repowise/cli/ui/provider_selection.py b/packages/cli/src/repowise/cli/ui/provider_selection.py
index 110070746..bf63f1979 100644
--- a/packages/cli/src/repowise/cli/ui/provider_selection.py
+++ b/packages/cli/src/repowise/cli/ui/provider_selection.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import functools
import os
import re
import socket
@@ -27,72 +28,28 @@ from repowise.cli.ui.openai_compatible import (
from repowise.cli.ui.openai_compatible import (
prompt_setup as _prompt_openai_compatible_setup_values,
)
+from repowise.core.agents.identity import identity_for_provider
from repowise.core.providers.llm.base import ProviderModelOption
+from repowise.core.providers.llm.specs import PROVIDER_SPECS, ProviderSpec
from repowise.core.reasoning import ReasoningMode, normalize_reasoning
# ---------------------------------------------------------------------------
-# Provider metadata — order matters (gemini first = default)
+# Provider metadata, read from the provider specs. Flag-only providers (mock)
+# are not offered; rows follow ``picker_rank`` (gemini first = default).
# ---------------------------------------------------------------------------
+_PICKER_SPECS: dict[str, ProviderSpec] = {
+ spec.name: spec
+ for spec in sorted(PROVIDER_SPECS.values(), key=lambda s: s.picker_rank or 0)
+ if spec.picker_rank is not None
+}
_PROVIDER_DEFAULTS: dict[str, str] = {
- "gemini": "gemini-3.5-flash-lite",
- "openai": "gpt-5.6-luna",
- "anthropic": "claude-haiku-5-5",
- "deepseek": "deepseek-v4-flash",
- "kimi": "kimi-for-coding",
- "edenai": "mistral/mistral-small-latest",
- "codex_cli": "codex_cli/default",
- "claude_cli": "claude_cli/claude-haiku-5-5",
- "opencode": "opencode/default",
- "ollama": "qwen3.5:4b",
- "openrouter": "google/gemini-3.5-flash-lite",
- "litellm": "groq/llama-3.1-70b-versatile",
+ name: spec.default_model for name, spec in _PICKER_SPECS.items()
}
-
+# The env var a key prompt writes. Agent CLIs have none; the picker never
+# prompts for them.
_PROVIDER_ENV: dict[str, str] = {
- "gemini": "GEMINI_API_KEY",
- "openai": "OPENAI_API_KEY",
- "anthropic": "ANTHROPIC_API_KEY",
- "deepseek": "DEEPSEEK_API_KEY",
- "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",
- # The picker iterates this map, so a provider missing here never renders a
- # row no matter what `_PROVIDER_DEFAULTS` says. litellm was in the defaults
- # only, which made it unreachable from init.
- "litellm": "LITELLM_API_KEY",
-}
-
-_PROVIDER_SIGNUP: dict[str, str] = {
- "gemini": "https://aistudio.google.com/apikey",
- "openai": "https://platform.openai.com/api-keys",
- "anthropic": "https://console.anthropic.com/settings/keys",
- "deepseek": "https://platform.deepseek.com/api_keys",
- "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",
- "litellm": "https://docs.litellm.ai/docs/providers",
-}
-
-
-# Short dim suffix on the provider name, saying what this provider is or how it
-# authenticates. The Status column answers "can I pick this right now"; anything
-# provider-specific belongs here so one column keeps one meaning.
-_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",
+ name: spec.required_envs[0] for name, spec in _PICKER_SPECS.items() if spec.required_envs
}
_OLLAMA_DEFAULT_BASE_URL = "http://localhost:11434"
@@ -103,7 +60,7 @@ _OPENAI_DEFAULT_BASE_URL = "https://api.openai.com/v1"
_OPENAI_COMPATIBLE_CHOICE = "openai_compatible"
_PROVIDER_CHOICES = tuple(
choice
- for provider in _PROVIDER_ENV
+ for provider in _PICKER_SPECS
for choice in ((provider, _OPENAI_COMPATIBLE_CHOICE) if provider == "openai" else (provider,))
)
# Enough for a loopback connect; the table renders before any prompt, so a slow
@@ -120,32 +77,16 @@ class ProviderSelection:
reasoning: ReasoningMode = "auto"
-def _detect_codex_cli_status() -> tuple[bool, bool]:
- """Return ``(installed, logged_in)`` for the local Codex CLI."""
- from repowise.cli.mcp_config import is_codex_cli_installed, is_codex_logged_in
+def _agent_cli_status(name: str) -> tuple[bool, bool]:
+ """``(installed, ready)`` for the agent CLI behind provider *name*.
- installed = is_codex_cli_installed()
- 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.
+ Ready means signed in where the CLI can say so cheaply, else installed:
+ an unauthenticated CLI without such a query surfaces 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
-
- return shutil.which("opencode") is not None
+ agent = identity_for_provider(name)
+ if agent is None or not agent.is_installed():
+ return False, False
+ return True, agent.is_logged_in()
def ollama_base_url() -> str:
@@ -209,20 +150,11 @@ def _detect_provider_status() -> dict[str, str]:
status: dict[str, str] = {}
openai_base_url = (os.environ.get("OPENAI_BASE_URL") or "").rstrip("/")
openai_has_key = bool((os.environ.get("OPENAI_API_KEY") or "").strip())
- for prov, env_var in _PROVIDER_ENV.items():
- if prov == "gemini":
- if os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY"):
- status[prov] = env_var
- elif prov == "codex_cli":
- 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"
+ for prov, spec in _PICKER_SPECS.items():
+ env_var = _PROVIDER_ENV.get(prov, "")
+ if spec.agent:
+ if _agent_cli_status(prov)[1]:
+ status[prov] = "agent CLI"
elif prov == "ollama":
if _detect_ollama_status():
status[prov] = ollama_base_url()
@@ -231,61 +163,33 @@ def _detect_provider_status() -> dict[str, str]:
status[prov] = env_var
elif openai_has_key and openai_base_url:
status[_OPENAI_COMPATIBLE_CHOICE] = env_var
- elif os.environ.get(env_var):
+ elif any(os.environ.get(name) for name in spec.api_key_envs):
status[prov] = env_var
return status
-def _codex_cli_setup_lines() -> list[str]:
- installed, _ = _detect_codex_cli_status()
+def _agent_cli_setup_lines(name: str) -> list[str]:
+ agent = identity_for_provider(name)
+ assert agent is not None, name
+ installed, _ = _agent_cli_status(name)
problem = (
- "Codex CLI is not on PATH." if not installed else "Codex CLI is on PATH but not logged in."
+ f"{agent.display_name} CLI is on PATH but not logged in."
+ if installed
+ else f"{agent.display_name} CLI not found on PATH."
)
- return [
- " [bold]codex_cli[/bold] uses the Codex CLI's own session. No API key here.",
- f" Install: [{BRAND}]npm install -g @openai/codex[/]",
- f" Log in: [{BRAND}]codex login[/]",
- "",
- f" [{WARN}]{problem}[/] Set it up and retry, or select another provider.",
- ]
-
-
-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 "
- "models and authentication. No API key here.",
- f" Install: [{BRAND}]curl -fsSL https://opencode.ai/install | bash[/]",
- f" Set up: [{BRAND}]opencode[/] (first run configures your provider)",
- f" Models: [{BRAND}]opencode models[/]",
- "",
- f" To pick a specific model: [{BRAND}]repowise init --provider opencode "
- "--model opencode/deepseek/deepseek-v4-pro[/]",
- "",
- f" [{WARN}]opencode CLI not found on PATH.[/] Install it and retry, "
- "or select another provider.",
+ f" [bold]{name}[/bold] uses the {agent.display_name} CLI's own login. No API key here.",
+ f" Install: [{BRAND}]{agent.install_hint}[/]",
+ f" Set up: [{BRAND}]{agent.login_hint}[/]",
]
+ models = PROVIDER_SPECS[name].models
+ if len(models) > 1:
+ lines += [
+ "",
+ f" To pick a specific model: [{BRAND}]repowise init --provider {name} "
+ f"--model {models[1]}[/]",
+ ]
+ return [*lines, "", f" [{WARN}]{problem}[/] Set it up and retry, or select another provider."]
def _ollama_setup_lines() -> list[str]:
@@ -311,13 +215,14 @@ def _ollama_setup_lines() -> list[str]:
# Providers with no API key to paste: they authenticate out of band or run
# locally, so readiness is a probe and the remedy is a command, never a prompt.
-# ``registry.KEYLESS_PROVIDERS`` is the resolution-side version of this idea; it
-# also holds litellm and mock, which do take a key here and are not offered
-# interactively, so the picker keeps its own narrower list.
+# Narrower than ``KEYLESS_PROVIDERS``: litellm takes a key here and mock is not
+# offered interactively.
_LOCAL_PROVIDER_SETUP: dict[str, Callable[[], list[str]]] = {
- "codex_cli": _codex_cli_setup_lines,
- "claude_cli": _claude_cli_setup_lines,
- "opencode": _opencode_setup_lines,
+ **{
+ name: functools.partial(_agent_cli_setup_lines, name)
+ for name, spec in _PICKER_SPECS.items()
+ if spec.agent
+ },
"ollama": _ollama_setup_lines,
}
@@ -360,7 +265,7 @@ def _interactive_provider_name(
label = "OpenAI-compatible [dim](Custom / local gateway)[/dim]"
default_model = "discover from /models"
else:
- note = _PROVIDER_NOTES.get(prov, "")
+ note = _PICKER_SPECS[prov].note
label = f"{prov} [dim]({note})[/dim]" if note else prov
default_model = _PROVIDER_DEFAULTS.get(runtime_provider, "")
table.add_row(f"[{idx}]", label, status_text, default_model)
@@ -416,7 +321,7 @@ def _interactive_provider_name(
save_key=save_key,
)
env_var = _PROVIDER_ENV[chosen]
- signup_url = _PROVIDER_SIGNUP.get(chosen, "")
+ signup_url = _PICKER_SPECS[chosen].signup_url
console.print()
console.print(f" [bold]{chosen}[/bold] requires [{VALUE}]{env_var}[/].")
if signup_url:
diff --git a/packages/core/src/repowise/core/agents/__init__.py b/packages/core/src/repowise/core/agents/__init__.py
index 63da17258..dd723bee0 100644
--- a/packages/core/src/repowise/core/agents/__init__.py
+++ b/packages/core/src/repowise/core/agents/__init__.py
@@ -20,6 +20,7 @@ from repowise.core.agents.identity import (
all_identities,
display_name_for,
get_identity,
+ identity_for_provider,
identity_for_target_id,
is_agent_slug,
normalize_client_name,
@@ -36,6 +37,7 @@ __all__ = [
"all_identities",
"display_name_for",
"get_identity",
+ "identity_for_provider",
"identity_for_target_id",
"is_agent_slug",
"normalize_client_name",
diff --git a/packages/core/src/repowise/core/agents/identity.py b/packages/core/src/repowise/core/agents/identity.py
index ae3b51ce7..fc3fd90ec 100644
--- a/packages/core/src/repowise/core/agents/identity.py
+++ b/packages/core/src/repowise/core/agents/identity.py
@@ -39,6 +39,8 @@ stored slug is coerced to.
from __future__ import annotations
import re
+import shutil
+import subprocess
import threading
from dataclasses import dataclass, field
@@ -101,6 +103,15 @@ class AgentIdentity:
#: ``derive_tier`` reads them.
hook_adapter: str | None = None
session_adapter: str | None = None
+ #: The agent's command on PATH, when it ships one.
+ executable: str | None = None
+ #: Arguments to ``executable`` that exit 0 only when signed in. Empty when
+ #: the CLI has no cheap, side-effect-free login query.
+ login_check: tuple[str, ...] = ()
+ install_hint: str = ""
+ login_hint: str = ""
+ #: The ``ProviderSpec`` name that drives this agent's CLI for indexing.
+ indexing_provider: str | None = None
def __post_init__(self) -> None:
if not is_agent_slug(self.slug):
@@ -132,6 +143,28 @@ class AgentIdentity:
| set(self.announced_as)
)
+ def which(self) -> str | None:
+ """Path to the agent's executable, or ``None`` when it is not on PATH."""
+ return shutil.which(self.executable) if self.executable else None
+
+ def is_installed(self) -> bool:
+ return self.which() is not None
+
+ def is_logged_in(self) -> bool:
+ """Installed and, where the CLI can say so cheaply, signed in."""
+ command = self.which()
+ if command is None:
+ return False
+ if not self.login_check:
+ return True
+ try:
+ result = subprocess.run(
+ [command, *self.login_check], capture_output=True, text=True, timeout=10
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return False
+ return result.returncode == 0
+
CLAUDE_CODE = AgentIdentity(
slug="claude_code",
@@ -140,17 +173,33 @@ CLAUDE_CODE = AgentIdentity(
announced_as=frozenset({"claude"}),
hook_adapter="claude-code",
session_adapter="claude_code",
+ executable="claude",
+ install_hint="https://claude.com/claude-code",
+ login_hint="claude login",
+ indexing_provider="claude_cli",
)
CODEX = AgentIdentity(
slug="codex",
display_name="Codex CLI",
hook_adapter="codex",
session_adapter="codex",
+ executable="codex",
+ login_check=("login", "status"),
+ install_hint="npm install -g @openai/codex",
+ login_hint="codex login",
+ indexing_provider="codex_cli",
+)
+VSCODE = AgentIdentity(slug="vscode", display_name="VS Code", executable="code")
+CURSOR = AgentIdentity(slug="cursor", display_name="Cursor", executable="cursor")
+OPENCODE = AgentIdentity(
+ slug="opencode",
+ display_name="OpenCode",
+ executable="opencode",
+ install_hint="curl -fsSL https://opencode.ai/install | bash",
+ login_hint="run opencode once to configure your provider",
+ indexing_provider="opencode",
)
-VSCODE = AgentIdentity(slug="vscode", display_name="VS Code")
-CURSOR = AgentIdentity(slug="cursor", display_name="Cursor")
-OPENCODE = AgentIdentity(slug="opencode", display_name="OpenCode")
-HERMES = AgentIdentity(slug="hermes", display_name="Hermes")
+HERMES = AgentIdentity(slug="hermes", display_name="Hermes", executable="hermes")
#: Registered identities, by slug. Order is not load-bearing here — the order
#: agents are *presented* in belongs to the target registry, which is where a
@@ -235,6 +284,14 @@ def slug_for_hook_adapter(name: str | None) -> str:
return UNKNOWN_AGENT
+def identity_for_provider(name: str) -> AgentIdentity | None:
+ """The agent whose CLI the LLM provider *name* drives, if any."""
+ for identity in _REGISTERED.values():
+ if identity.indexing_provider == name:
+ return identity
+ return None
+
+
def identity_for_target_id(target_id: str) -> AgentIdentity | None:
"""The identity behind a ``--target=`` id."""
return get_identity(target_id.replace("-", "_"))
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
index 191bdc1c3..ba7dcd550 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/llm/enrich.py
@@ -150,6 +150,11 @@ def build_enrichment_provider(
import os
from repowise.core.providers import get_provider
+ from repowise.core.providers.llm.registry import (
+ PROVIDER_AUTODETECT_ORDER,
+ provider_credentials_present,
+ provider_kwargs,
+ )
from repowise.core.repo_config import load_repo_config, load_repo_env
cfg = load_repo_config(repo_path)
@@ -161,38 +166,19 @@ def build_enrichment_provider(
name = provider_name or cfg.get("provider")
chosen_model = model or cfg.get("model")
- # Map provider -> the env var carrying its key.
- key_vars = {
- "anthropic": "ANTHROPIC_API_KEY",
- "openai": "OPENAI_API_KEY",
- "openrouter": "OPENROUTER_API_KEY",
- "deepseek": "DEEPSEEK_API_KEY",
- "kimi": "KIMI_API_KEY",
- "gemini": "GEMINI_API_KEY",
- "litellm": "LITELLM_API_KEY",
- }
-
# Auto-detect from whichever key is present when the config names none.
if name is None:
- for candidate, var in key_vars.items():
- if _env(var):
- name = candidate
- break
+ name = next(
+ (c for c in PROVIDER_AUTODETECT_ORDER if provider_credentials_present(c, _env)),
+ None,
+ )
if name is None:
raise ValueError(
"No LLM provider configured for refactoring enrichment. Set "
"'provider' in .repowise/config.yaml or an API key env var."
)
- kwargs: dict[str, Any] = {}
- if chosen_model:
- kwargs["model"] = chosen_model
- key_var = key_vars.get(name)
- if key_var and _env(key_var):
- kwargs["api_key"] = _env(key_var)
- if name == "gemini" and not kwargs.get("api_key") and _env("GOOGLE_API_KEY"):
- kwargs["api_key"] = _env("GOOGLE_API_KEY")
-
+ kwargs = provider_kwargs(name, model=chosen_model, repo_path=repo_path, getenv=_env)
return get_provider(name, **kwargs)
diff --git a/packages/core/src/repowise/core/cost_estimator/pricing.py b/packages/core/src/repowise/core/cost_estimator/pricing.py
index 476828f1c..09e3eb7ef 100644
--- a/packages/core/src/repowise/core/cost_estimator/pricing.py
+++ b/packages/core/src/repowise/core/cost_estimator/pricing.py
@@ -20,6 +20,8 @@ not worth it to move a one-off init estimate by ~10%.
from __future__ import annotations
+from repowise.core.providers.llm.specs import ZERO_COST_MODEL_PREFIXES
+
# Exact-match rates. Per-MTok pricing divided by 1000.
_COST_TABLE_EXACT: dict[str, tuple[float, float]] = {
# OpenAI GPT-5.4 family
@@ -81,9 +83,7 @@ _COST_TABLE_PREFIX: dict[str, tuple[float, float]] = {
"moonshot": (0.0006, 0.0024),
"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),
+ **dict.fromkeys(ZERO_COST_MODEL_PREFIXES, (0.0, 0.0)),
}
@@ -92,8 +92,8 @@ def _lookup_cost(model_name: str) -> tuple[float, float]:
lower = model_name.lower()
# 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/", "claude_cli/", "opencode/")):
+ # The agent-CLI prefixes are genuinely free, so they keep their prefixes.
+ if "/" in lower and not lower.startswith(ZERO_COST_MODEL_PREFIXES):
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.py
index 5d1b7f116..ef8505be0 100644
--- a/packages/core/src/repowise/core/generation/cost_tracker.py
+++ b/packages/core/src/repowise/core/generation/cost_tracker.py
@@ -14,6 +14,8 @@ from typing import Any
import structlog
+from repowise.core.providers.llm.specs import ZERO_COST_MODEL_PREFIXES
+
log = structlog.get_logger(__name__)
# ---------------------------------------------------------------------------
@@ -105,7 +107,7 @@ def is_local_model(model: str) -> bool:
return (
model == "mock"
or model.startswith(_LOCAL_MODEL_PREFIXES)
- or model.startswith(("codex_cli/", "claude_cli/", "opencode/"))
+ or model.startswith(ZERO_COST_MODEL_PREFIXES)
# Bare Ollama tags carry no prefix — the default is plain `qwen3.5:4b`.
# The trailing tag must not be a bare number: Bedrock addresses hosted
# Anthropic models as `anthropic.claude-sonnet-4-5-20250929-v1:0`, and
diff --git a/packages/core/src/repowise/core/providers/llm/agent_cli.py b/packages/core/src/repowise/core/providers/llm/agent_cli.py
index f656c9df7..cd14cfea9 100644
--- a/packages/core/src/repowise/core/providers/llm/agent_cli.py
+++ b/packages/core/src/repowise/core/providers/llm/agent_cli.py
@@ -39,6 +39,7 @@ from typing import Any, ClassVar
import structlog
+from repowise.core.agents.identity import get_identity
from repowise.core.providers.llm._concurrency import resolve_concurrency
from repowise.core.providers.llm.base import (
BaseProvider,
@@ -126,13 +127,14 @@ class AgentCliProvider(BaseProvider):
"""Base for providers backed by a local agent CLI. See the module docstring."""
provider_name: ClassVar[str] # type: ignore[misc]
+ # The agent this CLI belongs to; its identity supplies the executable and
+ # the not-found message, so install facts live in one place.
+ agent_slug: ClassVar[str]
executable_name: ClassVar[str]
# How errors name the invocation, e.g. ``codex exec``.
command_label: ClassVar[str]
concurrency_env: ClassVar[str]
not_found_message: ClassVar[str]
- # Raised when the executable vanishes between lookup and spawn.
- spawn_not_found_message: ClassVar[str | None] = None
# None: the CLI's own config picks the model.
default_model: ClassVar[str | None] = None
validates_model_name: ClassVar[bool] = True
@@ -146,6 +148,18 @@ class AgentCliProvider(BaseProvider):
# the error names the real cause.
interactive_timeout_s: float = 180.0
+ def __init_subclass__(cls, **kwargs: Any) -> None:
+ super().__init_subclass__(**kwargs)
+ agent = get_identity(cls.agent_slug)
+ if agent is None or not agent.executable:
+ raise TypeError(f"{cls.__name__}: no agent executable for {cls.agent_slug!r}")
+ cls.executable_name = agent.executable
+ label = agent.display_name.removesuffix(" CLI")
+ cls.not_found_message = (
+ f"{label} CLI not found. Install it with: {agent.install_hint}, "
+ f"then: {agent.login_hint}."
+ )
+
def __init__(
self,
model: str | None = None,
@@ -281,8 +295,7 @@ class AgentCliProvider(BaseProvider):
env=self.subprocess_env(),
)
except FileNotFoundError as exc:
- message = self.spawn_not_found_message or self.not_found_message
- raise ProviderError(self.provider_name, message) from exc
+ raise ProviderError(self.provider_name, self.not_found_message) from exc
timeout = self.exec_timeout_seconds()
try:
diff --git a/packages/core/src/repowise/core/providers/llm/claude_cli.py b/packages/core/src/repowise/core/providers/llm/claude_cli.py
index fb310c689..2fb757e57 100644
--- a/packages/core/src/repowise/core/providers/llm/claude_cli.py
+++ b/packages/core/src/repowise/core/providers/llm/claude_cli.py
@@ -139,13 +139,9 @@ class ClaudeCliProvider(AgentCliProvider):
"""
provider_name = "claude_cli"
- executable_name = "claude"
+ agent_slug = "claude_code"
command_label = "claude -p"
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'."
- )
default_model = _DEFAULT_MODEL
# Booked under the prefixed label, which prices a seat at $0.00 while
# ``repowise costs`` still shows the run's token volume (#2267).
diff --git a/packages/core/src/repowise/core/providers/llm/codex_cli.py b/packages/core/src/repowise/core/providers/llm/codex_cli.py
index 59380ebee..35faab9c8 100644
--- a/packages/core/src/repowise/core/providers/llm/codex_cli.py
+++ b/packages/core/src/repowise/core/providers/llm/codex_cli.py
@@ -305,10 +305,9 @@ class CodexCliProvider(AgentCliProvider):
"""
provider_name = "codex_cli"
- executable_name = "codex"
+ agent_slug = "codex"
command_label = "codex exec"
concurrency_env = _CONCURRENCY_ENV
- not_found_message = "Codex CLI not found. Install it with: npm install -g @openai/codex"
# No validation: the codex catalog decides, and an unlisted slug is passed through.
validates_model_name = False
diff --git a/packages/core/src/repowise/core/providers/llm/opencode.py b/packages/core/src/repowise/core/providers/llm/opencode.py
index 1b3bfe31f..384f62941 100644
--- a/packages/core/src/repowise/core/providers/llm/opencode.py
+++ b/packages/core/src/repowise/core/providers/llm/opencode.py
@@ -228,24 +228,9 @@ class OpenCodeProvider(AgentCliProvider):
"""
provider_name = "opencode"
- executable_name = "opencode"
+ agent_slug = "opencode"
command_label = "opencode run"
concurrency_env = "REPOWISE_OPENCODE_CONCURRENCY"
- not_found_message = (
- "OpenCode CLI is not installed.\n\n"
- "Installation:\n"
- " curl -fsSL https://opencode.ai/install | bash\n\n"
- "After installing, run 'opencode' once to set up your model provider "
- "and authenticate. No API keys are managed by repowise — opencode "
- "handles all authentication.\n\n"
- "To choose a model:\n"
- " opencode models # list available models\n"
- " repowise init --provider opencode --model opencode/deepseek/deepseek-v4-pro\n\n"
- "More info: https://opencode.ai"
- )
- spawn_not_found_message = (
- "OpenCode CLI not found. Install it with: curl -fsSL https://opencode.ai/install | bash"
- )
error_tail_chars = 1_000
def exec_timeout_seconds(self) -> float:
diff --git a/packages/core/src/repowise/core/providers/llm/registry.py b/packages/core/src/repowise/core/providers/llm/registry.py
index c943fc346..d915f9139 100644
--- a/packages/core/src/repowise/core/providers/llm/registry.py
+++ b/packages/core/src/repowise/core/providers/llm/registry.py
@@ -4,19 +4,7 @@ Provides a single entry point for instantiating any LLM provider by name.
Supports built-in providers and runtime registration of custom providers,
enabling community-contributed providers without forking repowise.
-Built-in providers:
- - anthropic → AnthropicProvider
- - openai → OpenAIProvider
- - openrouter → OpenRouterProvider
- - deepseek → DeepSeekProvider
- - kimi → KimiProvider
- - edenai → EdenAIProvider
- - ollama → OllamaProvider
- - litellm → LiteLLMProvider
- - codex_cli → CodexCliProvider
- - claude_cli → ClaudeCliProvider
- - opencode → OpenCodeProvider
- - mock → MockProvider (testing only)
+Built-in providers are declared once, in :mod:`repowise.core.providers.llm.specs`.
Custom provider registration:
from repowise.core.providers import register_provider
@@ -38,95 +26,57 @@ from pathlib import Path
from typing import Any
from repowise.core.providers.llm.base import BaseProvider
-from repowise.core.rate_limiter import PROVIDER_DEFAULTS, RateLimitConfig, RateLimiter
+from repowise.core.providers.llm.specs import PROVIDER_SPECS
+from repowise.core.rate_limiter import RateLimitConfig, RateLimiter
logger = logging.getLogger(__name__)
-# Map of provider name → (module_path, class_name)
-# Providers are imported lazily to avoid requiring all dependencies at import time.
-# This means `pip install repowise-core` without anthropic installed still works —
-# you just can't use the anthropic provider.
+# Every table below is derived from the provider specs (see specs.py), so a
+# provider is declared once. The names stay importable because the CLI, the
+# MCP server and drift tests read them.
_BUILTIN_PROVIDERS: dict[str, tuple[str, str]] = {
- "anthropic": ("repowise.core.providers.llm.anthropic", "AnthropicProvider"),
- "openai": ("repowise.core.providers.llm.openai", "OpenAIProvider"),
- "openrouter": ("repowise.core.providers.llm.openrouter", "OpenRouterProvider"),
- "gemini": ("repowise.core.providers.llm.gemini", "GeminiProvider"),
- "ollama": ("repowise.core.providers.llm.ollama", "OllamaProvider"),
- "litellm": ("repowise.core.providers.llm.litellm", "LiteLLMProvider"),
- "deepseek": ("repowise.core.providers.llm.deepseek", "DeepSeekProvider"),
- "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"),
+ name: (spec.module_path, spec.class_name) for name, spec in PROVIDER_SPECS.items()
}
-# Which env var carries a provider's API key. One entry per built-in provider
-# that authenticates with a key; keyless providers are absent by construction.
-# The three resolution paths (the CLI's resolve_provider, its
-# validate_provider_config, and the MCP server's get_answer) read this instead
-# of each keeping the copy they used to, which is how the MCP one drifted into
-# #1119. Other modules still carry their own provider->env lists for display
-# and env forwarding; the ones that must agree with resolution are held to this
-# table by drift tests rather than by anybody remembering.
+# Which env var carries a provider's API key; keyless providers are absent.
+# Resolution (the CLI's resolve_provider and validate_provider_config, the MCP
+# server's get_answer) reads this rather than a private copy; the copies are
+# what drifted into #1119.
PROVIDER_API_KEY_ENVS: dict[str, tuple[str, ...]] = {
- "anthropic": ("ANTHROPIC_API_KEY",),
- "openai": ("OPENAI_API_KEY",),
- "openrouter": ("OPENROUTER_API_KEY",),
- "gemini": ("GEMINI_API_KEY", "GOOGLE_API_KEY"), # either one
- "deepseek": ("DEEPSEEK_API_KEY",),
- "kimi": ("KIMI_API_KEY",),
- "edenai": ("EDENAI_API_KEY",),
- "litellm": ("LITELLM_API_KEY",),
+ name: spec.api_key_envs for name, spec in PROVIDER_SPECS.items() if spec.api_key_envs
}
-# Which env var points a provider at a non-default endpoint. Proxies and
-# self-hosted deployments of the OpenAI-compatible providers live here too.
+# Which env var points a provider at a non-default endpoint.
PROVIDER_BASE_URL_ENVS: dict[str, tuple[str, ...]] = {
- "anthropic": ("ANTHROPIC_BASE_URL",),
- "openai": ("OPENAI_BASE_URL",),
- "gemini": ("GEMINI_BASE_URL",),
- "deepseek": ("DEEPSEEK_BASE_URL",),
- "kimi": ("KIMI_BASE_URL",),
- "edenai": ("EDENAI_BASE_URL",),
- "ollama": ("OLLAMA_BASE_URL",),
- "litellm": ("LITELLM_BASE_URL", "LITELLM_API_BASE"),
+ name: spec.base_url_envs for name, spec in PROVIDER_SPECS.items() if spec.base_url_envs
}
-# Providers that can run with no API key at all: they authenticate out of band
-# (an already-logged-in coding-agent CLI) or need no auth (a local model, a
-# 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", "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.
-# Omitting it silently runs the CLI against whatever cwd the host process had,
-# which for an MCP server launched by an editor is not the user's repo.
-REPO_PATH_PROVIDERS = frozenset({"codex_cli", "opencode"})
-
-# Order to try providers in when nothing was configured and we are guessing
-# from whatever credentials the environment happens to carry. This is the CLI's
-# long-standing order, adopted verbatim as the shared one: the MCP server used
-# to auto-detect in a slightly different order (and skipped openrouter
-# entirely), so the same repo could resolve to different models depending on
-# which entry point asked.
-PROVIDER_AUTODETECT_ORDER: tuple[str, ...] = (
- "anthropic",
- "openai",
- "openrouter",
- "ollama",
- "gemini",
- "deepseek",
- "kimi",
- # A provider adding itself appends: autodetect order is de facto precedence,
- # and an unrelated EDENAI_API_KEY in the environment must not silently take
- # over from a provider the user was already resolving to.
- "edenai",
+# Providers that can run with no API key. Resolution must never reject one for
+# a "missing" key, nor fall through to a different provider for want of one.
+KEYLESS_PROVIDERS = frozenset(name for name, spec in PROVIDER_SPECS.items() if spec.keyless)
+
+# Providers that shell out with the repo as their working directory. Omitting
+# the path runs the CLI in whatever cwd the host process had, which for an MCP
+# server launched by an editor is not the user's repo.
+REPO_PATH_PROVIDERS = frozenset(
+ name for name, spec in PROVIDER_SPECS.items() if spec.needs_repo_cwd
+)
+
+# Order to try providers in when nothing was configured. Shared by the CLI and
+# the MCP server so one repo resolves to the same model from either entry point.
+PROVIDER_AUTODETECT_ORDER: tuple[str, ...] = tuple(
+ spec.name
+ for spec in sorted(
+ (s for s in PROVIDER_SPECS.values() if s.autodetect_rank is not None),
+ key=lambda s: s.autodetect_rank,
+ )
)
+# Default rate limit per provider. Absent means no limiter is attached.
+PROVIDER_DEFAULTS: dict[str, RateLimitConfig] = {
+ name: spec.rate_limit for name, spec in PROVIDER_SPECS.items() if spec.rate_limit
+}
+
# An env var set to "" or whitespace means "not set". CI systems and agent
# harnesses declare empty vars routinely (REPOWISE_PROVIDER: "" in a workflow
# matrix), and treating one as a real value resolves a provider that cannot
@@ -183,11 +133,8 @@ def provider_required_envs(name: str) -> tuple[str, ...]:
needs no key but does need somewhere to send the request. Empty for
providers that are self-sufficient (the agent CLIs, mock).
"""
- if name in PROVIDER_API_KEY_ENVS:
- return PROVIDER_API_KEY_ENVS[name]
- if name == "ollama":
- return PROVIDER_BASE_URL_ENVS["ollama"]
- return ()
+ spec = PROVIDER_SPECS.get(name)
+ return spec.required_envs if spec else ()
def provider_credentials_present(name: str, getenv: EnvLookup = os.environ.get) -> bool:
@@ -314,42 +261,27 @@ def get_provider(
if name in _custom_providers:
return _custom_providers[name](**kwargs)
- if name not in _BUILTIN_PROVIDERS:
+ if name not in PROVIDER_SPECS:
available = sorted(set(_BUILTIN_PROVIDERS) | set(_custom_providers))
raise ValueError(f"Unknown provider: {name!r}. Available providers: {available}")
- # Attach rate limiter (skip for mock — tests should run without limits)
- if with_rate_limiter and name not in ("mock", "codex_cli", "opencode"):
- config = rate_limit_config or PROVIDER_DEFAULTS.get(name)
- if config and "rate_limiter" not in kwargs:
- kwargs["rate_limiter"] = RateLimiter(config)
+ spec = PROVIDER_SPECS[name]
+ # A spec without a rate limit (mock, the agent CLIs) never gets one.
+ if with_rate_limiter and spec.rate_limit is not None and "rate_limiter" not in kwargs:
+ kwargs["rate_limiter"] = RateLimiter(rate_limit_config or spec.rate_limit)
- module_path, class_name = _BUILTIN_PROVIDERS[name]
try:
- module = importlib.import_module(module_path)
+ module = importlib.import_module(spec.module_path)
except ImportError as exc:
- # Give a helpful error message naming the missing package
- _missing = {
- "anthropic": "anthropic",
- "openai": "openai",
- "gemini": "google-genai",
- "ollama": "openai", # ollama uses the openai package
- "openrouter": "openai", # openrouter uses the openai package
- "deepseek": "openai", # deepseek uses the openai package
- "kimi": "openai", # kimi uses the openai package
- "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)
+ if not spec.package:
+ raise
+ package = spec.package
raise ImportError(
f"Provider {name!r} requires the '{package}' package. "
f"Install it with: pip install {package}"
) from exc
- cls: type[BaseProvider] = getattr(module, class_name)
+ cls: type[BaseProvider] = getattr(module, spec.class_name)
return cls(**kwargs)
diff --git a/packages/core/src/repowise/core/providers/llm/specs.py b/packages/core/src/repowise/core/providers/llm/specs.py
new file mode 100644
index 000000000..104db8ee3
--- /dev/null
+++ b/packages/core/src/repowise/core/providers/llm/specs.py
@@ -0,0 +1,312 @@
+"""One record per built-in LLM provider, and the tables everyone else derives.
+
+Facts about a provider (which env var holds its key, whether it runs in the
+repo's directory, whether its models cost money, how hard to rate-limit it)
+used to be spelled out again in every module that needed one: the registry,
+the rate limiter, two pricing tables, the server catalog, the init picker,
+doctor's install warnings. Each copy agreed with the others only by hand, and
+several had already drifted. A :class:`ProviderSpec` holds them once; the old
+tables (``KEYLESS_PROVIDERS``, ``PROVIDER_CATALOG`` and so on) are now
+computed from :data:`PROVIDER_SPECS`, so a new provider is one record here.
+
+The agent CLIs (``claude_cli``, ``codex_cli``, ``opencode``) are the one
+place this registry meets the agent registry in
+:mod:`repowise.core.agents.identity`: the spec names the agent slug in
+``agent``, the identity names the provider back in ``indexing_provider``, and
+a test holds the two links to each other. Executable, install and login facts
+belong to the agent and live on the identity. ``agent`` being set is also how
+a consumer tells "needs a local agent CLI on this machine" from a provider
+that only needs network access.
+
+Agent CLIs get no rate limiter (``rate_limit=None``). Each call is a
+subprocess under the provider's own concurrency semaphore, and the account's
+real ceiling is enforced by the CLI itself, so a client-side token bucket only
+double-throttles them.
+
+Declaration order is load-bearing: it is the server catalog's order, and the
+server falls back to the first catalog provider that is usable without a key.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from repowise.core.agents.identity import get_identity
+from repowise.core.rate_limiter import RateLimitConfig
+
+
+@dataclass(frozen=True, slots=True)
+class ProviderSpec:
+ """What the rest of repowise needs to know about one LLM provider."""
+
+ name: str
+ #: ``"module:Class"``, imported only when the provider is requested.
+ impl: str
+ #: Human label for catalogs (the server's settings list).
+ label: str
+ default_model: str
+ #: Models a picker offers before asking the provider for its live list.
+ models: tuple[str, ...] = ()
+ api_key_envs: tuple[str, ...] = ()
+ base_url_envs: tuple[str, ...] = ()
+ #: Runs with no API key: out-of-band login, a local model, or a proxy.
+ keyless: bool = False
+ #: Shells out with the repo as its working directory.
+ needs_repo_cwd: bool = False
+ #: Runs on this machine, so high concurrency can time out.
+ local: bool = False
+ #: Models named ``"<name>/..."`` cost nothing per token.
+ zero_cost: bool = False
+ #: Flood guard; ``None`` attaches no rate limiter.
+ rate_limit: RateLimitConfig | None = None
+ #: Package named when the provider's module fails to import.
+ package: str = ""
+ #: Position in credential auto-detection; ``None`` never auto-detects.
+ autodetect_rank: int | None = None
+ #: The agent slug whose CLI this provider drives.
+ agent: str | None = None
+ #: Row in the init picker, whose first ready row is the default.
+ #: ``None`` means flag-only: left out of the picker and the server catalog.
+ picker_rank: int | None = None
+ #: Short dim note beside the name in the init picker.
+ note: str = ""
+ #: Where to get a key (or the runtime) when the provider is not set up.
+ signup_url: str = ""
+
+ @property
+ def module_path(self) -> str:
+ return self.impl.partition(":")[0]
+
+ @property
+ def class_name(self) -> str:
+ return self.impl.partition(":")[2]
+
+ @property
+ def required_envs(self) -> tuple[str, ...]:
+ """The key, or for a keyless provider with an endpoint, the endpoint."""
+ return self.api_key_envs or (self.base_url_envs if self.keyless else ())
+
+ @property
+ def setup_hint(self) -> str:
+ """One line telling a user how to make this provider usable."""
+ identity = get_identity(self.agent) if self.agent else None
+ if identity is not None:
+ return f"{identity.install_hint}, then: {identity.login_hint}"
+ if not self.api_key_envs and self.signup_url:
+ return self.signup_url
+ return f"pip install {self.package}" if self.package else ""
+
+
+_LLM = "repowise.core.providers.llm"
+
+# Rate limits are FLOOD GUARDS, not throttles. The provider's own 429s are the
+# authoritative signal, and every provider retries them patiently (retry-after
+# aware, see providers/llm/base.py). Values sit near each provider's published
+# upper tiers (2026); low-tier accounts degrade through 429 backoff instead of
+# everyone being pre-emptively slowed. Ollama is local and effectively
+# unlimited, capped only to avoid OOM.
+_SPECS: tuple[ProviderSpec, ...] = (
+ ProviderSpec(
+ name="gemini",
+ picker_rank=0,
+ impl=f"{_LLM}.gemini:GeminiProvider",
+ label="Google Gemini",
+ default_model="gemini-3.5-flash-lite",
+ models=("gemini-3.5-flash-lite", "gemini-3.1-flash-lite", "gemini-3.1-pro-preview"),
+ api_key_envs=("GEMINI_API_KEY", "GOOGLE_API_KEY"),
+ base_url_envs=("GEMINI_BASE_URL",),
+ rate_limit=RateLimitConfig(requests_per_minute=1_000, tokens_per_minute=4_000_000),
+ package="google-genai",
+ autodetect_rank=4,
+ note="recommended",
+ signup_url="https://aistudio.google.com/apikey",
+ ),
+ ProviderSpec(
+ name="anthropic",
+ picker_rank=2,
+ impl=f"{_LLM}.anthropic:AnthropicProvider",
+ label="Anthropic",
+ default_model="claude-haiku-5-5",
+ models=("claude-haiku-5-5", "claude-sonnet-4-6", "claude-opus-4-6"),
+ api_key_envs=("ANTHROPIC_API_KEY",),
+ base_url_envs=("ANTHROPIC_BASE_URL",),
+ rate_limit=RateLimitConfig(requests_per_minute=2_000, tokens_per_minute=1_600_000),
+ package="anthropic",
+ autodetect_rank=0,
+ signup_url="https://console.anthropic.com/settings/keys",
+ ),
+ ProviderSpec(
+ name="openai",
+ picker_rank=1,
+ impl=f"{_LLM}.openai:OpenAIProvider",
+ label="OpenAI",
+ default_model="gpt-5.6-luna",
+ models=("gpt-5.6-luna", "gpt-5.4-nano", "gpt-5.4-mini", "gpt-5.4"),
+ api_key_envs=("OPENAI_API_KEY",),
+ base_url_envs=("OPENAI_BASE_URL",),
+ rate_limit=RateLimitConfig(requests_per_minute=5_000, tokens_per_minute=4_000_000),
+ package="openai",
+ autodetect_rank=1,
+ signup_url="https://platform.openai.com/api-keys",
+ ),
+ ProviderSpec(
+ name="openrouter",
+ picker_rank=10,
+ impl=f"{_LLM}.openrouter:OpenRouterProvider",
+ label="OpenRouter",
+ default_model="google/gemini-3.5-flash-lite",
+ models=(
+ "google/gemini-3.5-flash-lite",
+ "openai/gpt-5.6-luna",
+ "anthropic/claude-haiku-4-5",
+ "anthropic/claude-sonnet-5",
+ ),
+ api_key_envs=("OPENROUTER_API_KEY",),
+ rate_limit=RateLimitConfig(requests_per_minute=1_000, tokens_per_minute=2_000_000),
+ package="openai",
+ autodetect_rank=2,
+ signup_url="https://openrouter.ai/keys",
+ ),
+ ProviderSpec(
+ name="deepseek",
+ picker_rank=3,
+ impl=f"{_LLM}.deepseek:DeepSeekProvider",
+ label="DeepSeek",
+ default_model="deepseek-v4-flash",
+ models=("deepseek-v4-flash", "deepseek-v4-pro"),
+ api_key_envs=("DEEPSEEK_API_KEY",),
+ base_url_envs=("DEEPSEEK_BASE_URL",),
+ rate_limit=RateLimitConfig(requests_per_minute=1_000, tokens_per_minute=5_000_000),
+ package="openai",
+ autodetect_rank=5,
+ signup_url="https://platform.deepseek.com/api_keys",
+ ),
+ ProviderSpec(
+ name="kimi",
+ picker_rank=4,
+ impl=f"{_LLM}.kimi:KimiProvider",
+ label="Kimi",
+ default_model="kimi-for-coding",
+ models=("kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.5", "kimi-k2.6"),
+ api_key_envs=("KIMI_API_KEY",),
+ base_url_envs=("KIMI_BASE_URL",),
+ rate_limit=RateLimitConfig(requests_per_minute=1_000, tokens_per_minute=5_000_000),
+ package="openai",
+ autodetect_rank=6,
+ signup_url="https://www.kimi.com/code/console",
+ ),
+ ProviderSpec(
+ name="edenai",
+ picker_rank=5,
+ impl=f"{_LLM}.edenai:EdenAIProvider",
+ label="Eden AI",
+ default_model="mistral/mistral-small-latest",
+ models=(
+ "mistral/mistral-small-latest",
+ "openai/gpt-4o-mini",
+ "anthropic/claude-haiku-4-5",
+ "google/gemini-2.5-flash",
+ ),
+ api_key_envs=("EDENAI_API_KEY",),
+ base_url_envs=("EDENAI_BASE_URL",),
+ rate_limit=RateLimitConfig(requests_per_minute=1_000, tokens_per_minute=2_000_000),
+ package="openai",
+ # Last on purpose: an unrelated EDENAI_API_KEY in the environment must
+ # not take over from a provider the user was already resolving to.
+ autodetect_rank=7,
+ signup_url="https://app.edenai.run/user/register",
+ ),
+ ProviderSpec(
+ name="ollama",
+ picker_rank=9,
+ impl=f"{_LLM}.ollama:OllamaProvider",
+ label="Ollama (Local)",
+ default_model="qwen3.5:4b",
+ models=("qwen3.5:4b", "qwen3.5:2b", "llama3.2", "qwen2.5-coder"),
+ base_url_envs=("OLLAMA_BASE_URL",),
+ keyless=True,
+ local=True,
+ rate_limit=RateLimitConfig(requests_per_minute=1_000, tokens_per_minute=10_000_000),
+ package="openai",
+ autodetect_rank=3,
+ note="runs on your machine, no key",
+ signup_url="https://ollama.com/download",
+ ),
+ ProviderSpec(
+ name="litellm",
+ picker_rank=11,
+ impl=f"{_LLM}.litellm:LiteLLMProvider",
+ label="LiteLLM",
+ default_model="groq/llama-3.1-70b-versatile",
+ models=("groq/llama-3.1-70b-versatile",),
+ api_key_envs=("LITELLM_API_KEY",),
+ base_url_envs=("LITELLM_BASE_URL", "LITELLM_API_BASE"),
+ keyless=True,
+ rate_limit=RateLimitConfig(requests_per_minute=1_000, tokens_per_minute=2_000_000),
+ package="litellm",
+ note="proxy in front of another provider",
+ signup_url="https://docs.litellm.ai/docs/providers",
+ ),
+ ProviderSpec(
+ name="claude_cli",
+ picker_rank=7,
+ impl=f"{_LLM}.claude_cli:ClaudeCliProvider",
+ label="Claude Code (Local CLI)",
+ default_model="claude_cli/claude-haiku-5-5",
+ models=(
+ "claude_cli/claude-haiku-5-5",
+ "claude_cli/claude-sonnet-4-6",
+ "claude_cli/claude-opus-4-6",
+ ),
+ keyless=True,
+ # Not needs_repo_cwd: it runs in a scratch dir so the repo's CLAUDE.md
+ # stays out of every prompt (see claude_cli.py).
+ local=True,
+ zero_cost=True,
+ agent="claude_code",
+ note="uses your Claude Code login",
+ ),
+ ProviderSpec(
+ name="codex_cli",
+ picker_rank=6,
+ impl=f"{_LLM}.codex_cli:CodexCliProvider",
+ label="Codex (Local CLI)",
+ default_model="codex_cli/default",
+ # The live list comes from the authenticated codex catalog at runtime.
+ models=("codex_cli/default",),
+ keyless=True,
+ needs_repo_cwd=True,
+ local=True,
+ zero_cost=True,
+ agent="codex",
+ note="uses your Codex CLI login",
+ ),
+ ProviderSpec(
+ name="opencode",
+ picker_rank=8,
+ impl=f"{_LLM}.opencode:OpenCodeProvider",
+ label="OpenCode (Local CLI)",
+ default_model="opencode/default",
+ models=("opencode/default", "opencode/openai/gpt-5", "opencode/deepseek/deepseek-v4-pro"),
+ keyless=True,
+ needs_repo_cwd=True,
+ local=True,
+ zero_cost=True,
+ agent="opencode",
+ note="uses your opencode CLI setup",
+ ),
+ ProviderSpec(
+ name="mock",
+ impl=f"{_LLM}.mock:MockProvider",
+ label="Mock",
+ default_model="mock",
+ keyless=True,
+ ),
+)
+
+PROVIDER_SPECS: dict[str, ProviderSpec] = {spec.name: spec for spec in _SPECS}
+
+#: Model-name prefixes that cost nothing per token.
+ZERO_COST_MODEL_PREFIXES: tuple[str, ...] = tuple(
+ f"{spec.name}/" for spec in _SPECS if spec.zero_cost
+)
diff --git a/packages/core/src/repowise/core/rate_limiter.py b/packages/core/src/repowise/core/rate_limiter.py
index 3818d5577..1a470644d 100644
--- a/packages/core/src/repowise/core/rate_limiter.py
+++ b/packages/core/src/repowise/core/rate_limiter.py
@@ -40,39 +40,7 @@ class RateLimitConfig:
tokens_per_minute: int
-# Default rate limit configs for known providers.
-#
-# Philosophy: these are FLOOD GUARDS, not throttles. The provider's own 429
-# responses are the authoritative throttle signal, and every provider retries
-# them patiently (retry-after aware, up to 8 attempts — see providers/llm/
-# base.py). Throttling client-side below the provider's real limits just
-# leaves the API idle: the old openai default (150k TPM ÷ 20k reserved per
-# request) capped doc generation at 7.5 requests/min while Tier-1 already
-# allows 500 RPM. Low-tier accounts degrade gracefully via 429 backoff
-# instead of being pre-emptively slowed for everyone.
-#
-# Values sit near each provider's published upper tiers (2026):
-# - OpenAI Tier 4/5: 30k RPM, 40M+ TPM (mini/nano are 5-10x full models)
-# - Gemini paid Tier 1+: 300+ RPM, 1M+ TPM on flash
-# - Anthropic Tier 4: 4k RPM, 2M ITPM (cached reads don't count)
-# - DeepSeek: no published limits (dynamic, load-based)
-# - OpenRouter: no published RPM/TPM for paid models
-PROVIDER_DEFAULTS: dict[str, RateLimitConfig] = {
- "anthropic": RateLimitConfig(requests_per_minute=2_000, tokens_per_minute=1_600_000),
- "openai": RateLimitConfig(requests_per_minute=5_000, tokens_per_minute=4_000_000),
- "openrouter": RateLimitConfig(requests_per_minute=1_000, tokens_per_minute=2_000_000),
- "gemini": RateLimitConfig(requests_per_minute=1_000, tokens_per_minute=4_000_000),
- # Ollama runs locally — effectively unlimited, but we cap to avoid OOM
- "ollama": RateLimitConfig(requests_per_minute=1_000, tokens_per_minute=10_000_000),
- "litellm": RateLimitConfig(requests_per_minute=1_000, tokens_per_minute=2_000_000),
- "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),
-}
+# Per-provider defaults live on the provider specs (providers/llm/specs.py).
class RateLimiter:
diff --git a/packages/server/src/repowise/server/provider_config.py b/packages/server/src/repowise/server/provider_config.py
index 3f8ee3c51..f26ab8934 100644
--- a/packages/server/src/repowise/server/provider_config.py
+++ b/packages/server/src/repowise/server/provider_config.py
@@ -29,145 +29,30 @@ import os
from pathlib import Path
from typing import Any
+from repowise.core.providers.llm.specs import PROVIDER_SPECS
+
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
-# Provider catalog (hardcoded — add new providers here)
+# Provider catalog, derived from the provider specs. Flag-only providers
+# (mock) are left out. Order matters: auto-detect below takes the first entry
+# that is usable.
# ---------------------------------------------------------------------------
PROVIDER_CATALOG: list[dict[str, Any]] = [
{
- "id": "gemini",
- "name": "Google Gemini",
- "default_model": "gemini-3.5-flash-lite",
- "models": [
- "gemini-3.5-flash-lite",
- "gemini-3.1-flash-lite",
- "gemini-3.1-pro-preview",
- ],
- "env_keys": ["GEMINI_API_KEY", "GOOGLE_API_KEY"],
- "requires_key": True,
- },
- {
- "id": "anthropic",
- "name": "Anthropic",
- "default_model": "claude-haiku-5-5",
- "models": ["claude-haiku-5-5", "claude-sonnet-4-6", "claude-opus-4-6"],
- "env_keys": ["ANTHROPIC_API_KEY"],
- "requires_key": True,
- },
- {
- "id": "openai",
- "name": "OpenAI",
- "default_model": "gpt-5.6-luna",
- "models": ["gpt-5.6-luna", "gpt-5.4-nano", "gpt-5.4-mini", "gpt-5.4"],
- "env_keys": ["OPENAI_API_KEY"],
- "requires_key": True,
- },
- {
- "id": "openrouter",
- "name": "OpenRouter",
- "default_model": "google/gemini-3.5-flash-lite",
- "models": [
- "google/gemini-3.5-flash-lite",
- "openai/gpt-5.6-luna",
- "anthropic/claude-haiku-4-5",
- "anthropic/claude-sonnet-5",
- ],
- "env_keys": ["OPENROUTER_API_KEY"],
- "requires_key": True,
- },
- {
- "id": "deepseek",
- "name": "DeepSeek",
- "default_model": "deepseek-v4-flash",
- "models": ["deepseek-v4-flash", "deepseek-v4-pro"],
- "env_keys": ["DEEPSEEK_API_KEY"],
- "requires_key": True,
- },
- {
- "id": "kimi",
- "name": "Kimi",
- "default_model": "kimi-for-coding",
- "models": [
- "kimi-for-coding",
- "kimi-for-coding-highspeed",
- "kimi-k2.5",
- "kimi-k2.6",
- ],
- "env_keys": ["KIMI_API_KEY"],
- "requires_key": True,
- },
- {
- "id": "edenai",
- "name": "Eden AI",
- "default_model": "mistral/mistral-small-latest",
- "models": [
- "mistral/mistral-small-latest",
- "openai/gpt-4o-mini",
- "anthropic/claude-haiku-4-5",
- "google/gemini-2.5-flash",
- ],
- "env_keys": ["EDENAI_API_KEY"],
- "requires_key": True,
- },
- {
- "id": "ollama",
- "name": "Ollama (Local)",
- "default_model": "qwen3.5:4b",
- "models": ["qwen3.5:4b", "qwen3.5:2b", "llama3.2", "qwen2.5-coder"],
- "env_keys": [],
- "requires_key": False,
- },
- {
- "id": "litellm",
- "name": "LiteLLM",
- "default_model": "groq/llama-3.1-70b-versatile",
- "models": ["groq/llama-3.1-70b-versatile"],
- # Was [] while requires_key stayed True, so _get_key_for_provider had
- # nothing to look at and litellm read as unconfigured no matter what
- # the user had set. The name matches the CLI's own validation map.
- "env_keys": ["LITELLM_API_KEY"],
- "requires_key": True,
- },
- {
- "id": "claude_cli",
- "name": "Claude Code (Local CLI)",
- "default_model": "claude_cli/claude-haiku-5-5",
- "models": [
- "claude_cli/claude-haiku-5-5",
- "claude_cli/claude-sonnet-4-6",
- "claude_cli/claude-opus-4-6",
- ],
- "env_keys": [],
- "requires_key": False,
- },
- {
- "id": "codex_cli",
- "name": "Codex (Local CLI)",
- "default_model": "codex_cli/default",
- "models": [
- # The CLI's model list comes from the authenticated codex catalog
- # at runtime (see core/providers/llm/codex_cli.py), so the static
- # catalog only names the sentinel default; list_provider_status
- # appends the resolved active model when it isn't cataloged.
- "codex_cli/default",
- ],
- "env_keys": [],
- "requires_key": False,
- },
- {
- "id": "opencode",
- "name": "OpenCode (Local CLI)",
- "default_model": "opencode/default",
- "models": [
- "opencode/default",
- "opencode/openai/gpt-5",
- "opencode/deepseek/deepseek-v4-pro",
- ],
- "env_keys": [],
- "requires_key": False,
- },
+ "id": spec.name,
+ "name": spec.label,
+ "default_model": spec.default_model,
+ "models": list(spec.models),
+ "env_keys": list(spec.api_key_envs),
+ "requires_key": bool(spec.api_key_envs),
+ # What a user sets to make it usable, and how to install it.
+ "env_vars": list(spec.required_envs),
+ "setup_hint": spec.setup_hint,
+ }
+ for spec in PROVIDER_SPECS.values()
+ if spec.picker_rank is not None
]
_CATALOG_BY_ID = {p["id"]: p for p in PROVIDER_CATALOG}
@@ -412,6 +297,9 @@ def list_provider_status(
"models": models,
"default_model": p["default_model"],
"configured": configured,
+ "requires_key": p["requires_key"],
+ "env_vars": p["env_vars"],
+ "setup_hint": p["setup_hint"],
}
)
diff --git a/packages/server/src/repowise/server/schemas/ui_helpers.py b/packages/server/src/repowise/server/schemas/ui_helpers.py
index 434650a0d..e753b204e 100644
--- a/packages/server/src/repowise/server/schemas/ui_helpers.py
+++ b/packages/server/src/repowise/server/schemas/ui_helpers.py
@@ -42,6 +42,12 @@ class ProviderEntry(BaseModel):
default_model: str | None = None
#: Has a key, or needs none.
configured: bool = False
+ #: Takes an API key; ``False`` hides the key field.
+ requires_key: bool = True
+ #: Env vars a user sets to make the provider usable.
+ env_vars: list[str] = []
+ #: One line on how to install or set it up.
+ setup_hint: str = ""
class ActiveProviderSelection(BaseModel):
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index b07ef8fa4..62f0e4acc 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -2624,6 +2624,9 @@ export interface ProviderEntry {
models?: string[];
default_model?: string | null;
configured?: boolean;
+ requires_key?: boolean;
+ env_vars?: string[];
+ setup_hint?: string;
}
export interface ProviderStatusResponse {
diff --git a/packages/ui/src/settings/provider-settings.tsx b/packages/ui/src/settings/provider-settings.tsx
index dbea6391f..c500fc950 100644
--- a/packages/ui/src/settings/provider-settings.tsx
+++ b/packages/ui/src/settings/provider-settings.tsx
@@ -32,6 +32,9 @@ export interface ProviderOption {
default_model: string;
/** Whether a usable key is on file (server-computed; never the key itself). */
configured: boolean;
+ /** `false` for local runtimes and CLIs: the key affordance is hidden and
+ * only reachability is validated. */
+ requires_key?: boolean;
}
export type ProviderValidationStatus = "idle" | "testing" | "ok" | "error";
@@ -41,10 +44,6 @@ export interface ProviderValidationState {
error?: string | null;
}
-/** 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", "claude_cli", "mock"]);
-
export interface ProviderSettingsProps {
providers: ProviderOption[];
/** The active provider/model selection for this repo. */
@@ -117,7 +116,7 @@ function ProviderRow({
const [keyDraft, setKeyDraft] = useState("");
const [busy, setBusy] = useState<null | "save" | "remove" | "activate">(null);
- const keyless = KEYLESS_PROVIDERS.has(provider.id);
+ const keyless = provider.requires_key === false;
const status = validation?.status ?? "idle";
async function saveKey() {
diff --git a/packages/web/messages/en.json b/packages/web/messages/en.json
index b7e5381f4..2042781ca 100644
--- a/packages/web/messages/en.json
+++ b/packages/web/messages/en.json
@@ -512,7 +512,8 @@
"embedderHint": "What semantic search is built from. The mock embedder disables it.",
"embedderAria": "Embedder",
"embedderOffNote": "Semantic search is off. Set <code>REPOWISE_EMBEDDER=gemini</code> or <code>REPOWISE_EMBEDDER=openai</code> on the server for real retrieval.",
- "embedderOnNote": "Set <code>{env}</code> on the server."
+ "embedderOnNote": "Set <code>{env}</code> on the server.",
+ "catalogUnavailable": "Could not load the provider list from the server, so only the saved provider is shown."
}
},
"repos": {
diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.json
index bb8019438..768aee1e0 100644
--- a/packages/web/messages/zh-CN.json
+++ b/packages/web/messages/zh-CN.json
@@ -512,7 +512,8 @@
"embedderHint": "语义搜索基于它构建。mock 嵌入模型会禁用语义搜索。",
"embedderAria": "嵌入模型",
"embedderOffNote": "语义搜索已关闭。请在服务端设置 <code>REPOWISE_EMBEDDER=gemini</code> 或 <code>REPOWISE_EMBEDDER=openai</code> 以启用真实检索。",
- "embedderOnNote": "请在服务端设置 <code>{env}</code>。"
+ "embedderOnNote": "请在服务端设置 <code>{env}</code>。",
+ "catalogUnavailable": "无法从服务器加载提供商列表,因此只显示已保存的提供商。"
}
},
"repos": {
diff --git a/packages/web/src/components/settings/provider-section.test.tsx b/packages/web/src/components/settings/provider-section.test.tsx
index 9f9444e06..26b96f86e 100644
--- a/packages/web/src/components/settings/provider-section.test.tsx
+++ b/packages/web/src/components/settings/provider-section.test.tsx
@@ -63,6 +63,7 @@ describe("ProviderSection server provider", () => {
expect(
screen.getByText("Used when you trigger init or sync from this dashboard."),
).toBeTruthy();
+ expect(await screen.findByText(/Could not load the provider list/)).toBeTruthy();
});
});
@@ -145,9 +146,9 @@ describe("ProviderSection provider catalog", () => {
);
});
- it("lets the server's default model beat a stale built-in placeholder", async () => {
- // The local table is a hardcoded guess that has already drifted once. When
- // the server reports a different default, the server is right.
+ it("takes the model placeholder from the server catalog", async () => {
+ // The page keeps no table of its own; the catalog is derived from the
+ // provider specs, so the server's default is the one to show.
mocks.getProviders.mockResolvedValue({
active: { provider: "gemini", model: null },
providers: [{ id: "gemini", name: "Google Gemini", default_model: "gemini-4-pro" }],
@@ -159,7 +160,7 @@ describe("ProviderSection provider catalog", () => {
await waitFor(() => expect(model.placeholder).toBe("gemini-4-pro"));
});
- it("falls back to the built-in placeholder when the catalog has no default", async () => {
+ it("falls back to a generic placeholder when the catalog has no default", async () => {
mocks.getProviders.mockResolvedValue({
active: { provider: "gemini", model: null },
providers: [{ id: "gemini", name: "Google Gemini", default_model: null }],
@@ -168,8 +169,26 @@ describe("ProviderSection provider catalog", () => {
render(<ProviderSection />);
await waitFor(() => expect(mocks.getProviders).toHaveBeenCalledOnce());
- expect(screen.getByLabelText<HTMLInputElement>("Model").placeholder).toBe(
- "gemini-3.5-flash-lite",
- );
+ expect(screen.getByLabelText<HTMLInputElement>("Model").placeholder).toBe("model name");
+ });
+
+ it("shows the env vars and setup hint the catalog carries", async () => {
+ mocks.getProviders.mockResolvedValue({
+ active: { provider: "gemini", model: null },
+ providers: [
+ {
+ id: "gemini",
+ name: "Google Gemini",
+ default_model: "gemini-3.5-flash-lite",
+ env_vars: ["GEMINI_API_KEY", "GOOGLE_API_KEY"],
+ setup_hint: "pip install google-genai",
+ },
+ ],
+ });
+
+ render(<ProviderSection />);
+
+ expect(await screen.findByText("pip install google-genai")).toBeTruthy();
+ expect(screen.getByText(/GEMINI_API_KEY/)).toBeTruthy();
});
});
diff --git a/packages/web/src/components/settings/provider-section.tsx b/packages/web/src/components/settings/provider-section.tsx
index 1672f3c0d..da316c304 100644
--- a/packages/web/src/components/settings/provider-section.tsx
+++ b/packages/web/src/components/settings/provider-section.tsx
@@ -3,6 +3,7 @@
import React, { useEffect, useRef, useState } from "react";
import { config } from "@/lib/config";
import { getProviders } from "@/lib/api/providers";
+import type { ProviderInfo } from "@/lib/api/types";
import { OverviewSection } from "@repowise-dev/ui/overview";
import { Input } from "@repowise-dev/ui/ui/input";
import {
@@ -21,13 +22,6 @@ import {
} from "@repowise-dev/ui/settings";
import { useTranslations } from "next-intl";
-/**
- * Fallback only, for a cold load and for an API that never answers. The server
- * owns the catalog; this is not a second source of truth. It had already
- * drifted -- `codex_cli` and `openrouter` are in the server catalog and were
- * never added here, so neither could be picked from this page.
- */
-const FALLBACK_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;
// Real, registerable providers the server catalog deliberately leaves out.
@@ -36,39 +30,6 @@ const EMBEDDERS = ["mock", "gemini", "openai", "openrouter", "edenai", "ollama"]
// PROVIDER_CATALOG and would otherwise vanish the moment the catalog loads.
const FLAG_ONLY_PROVIDERS = ["mock"] as const;
-const MODEL_PLACEHOLDERS: Record<string, string> = {
- gemini: "gemini-3.5-flash-lite",
- openai: "gpt-5.6-luna",
- anthropic: "claude-haiku-5-5",
- deepseek: "deepseek-v4-flash",
- kimi: "kimi-for-coding",
- edenai: "mistral/mistral-small-latest",
- claude_cli: "claude_cli/claude-haiku-5-5",
- opencode: "opencode/default",
- ollama: "qwen3.5:4b",
- litellm: "groq/llama-3.1-70b-versatile",
- mock: "mock",
-};
-
-const PROVIDER_ENV_VARS: Record<string, { vars: string[]; installHint: string }> = {
- gemini: { vars: ["GEMINI_API_KEY"], installHint: "pip install google-genai" },
- openai: { vars: ["OPENAI_API_KEY"], installHint: "pip install openai" },
- anthropic: { vars: ["ANTHROPIC_API_KEY"], installHint: "pip install anthropic" },
- ollama: { vars: ["OLLAMA_BASE_URL"], installHint: "https://ollama.ai" },
- deepseek: { vars: ["DEEPSEEK_API_KEY"], installHint: "pip install openai" },
- 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" },
- codex_cli: {
- vars: [],
- installHint: "npm install -g @openai/codex, then: codex login",
- },
- openrouter: { vars: ["OPENROUTER_API_KEY"], installHint: "pip install openai" },
- mock: { vars: [], installHint: "No key needed" },
-};
-
const EMBEDDER_ENV_VARS: Record<string, string[]> = {
gemini: ["GEMINI_API_KEY"],
openai: ["OPENAI_API_KEY"],
@@ -94,8 +55,11 @@ export function ProviderSection() {
const [model, setModel] = useState("");
const [embedder, setEmbedder] = useState("mock");
const [serverProvider, setServerProvider] = useState<string | null>(null);
- const [providers, setProviders] = useState<readonly string[]>(FALLBACK_PROVIDERS);
- const [catalogModels, setCatalogModels] = useState<Record<string, string>>({});
+ // The server owns the catalog (it is derived from the provider specs), so
+ // this page keeps no copy of its own; until it loads, only the saved
+ // provider and the flag-only ones are offered.
+ const [catalog, setCatalog] = useState<ProviderInfo[]>([]);
+ const [catalogFailed, setCatalogFailed] = useState(false);
const [saveState, setSaveState] = useState<SaveState>("idle");
const savedTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -109,23 +73,11 @@ export function ProviderSection() {
.then(({ active, providers: catalog }) => {
if (cancelled) return;
setServerProvider(active.provider);
- // Same response already carries the catalog the server resolves
- // against, so the picker can render it instead of a second copy
- // compiled into this file. That copy is how `codex_cli` and
- // `openrouter` came to be selectable everywhere except here.
- const entries = catalog ?? [];
- const ids = entries.map((entry) => entry.id).filter(Boolean);
- if (ids.length) setProviders(ids);
- setCatalogModels(
- Object.fromEntries(
- entries.flatMap((entry) =>
- entry.default_model ? [[entry.id, entry.default_model]] : [],
- ),
- ),
- );
+ setCatalog((catalog ?? []).filter((entry) => entry.id));
})
.catch((error: unknown) => {
console.warn("[settings] Could not load the active server provider", error);
+ if (!cancelled) setCatalogFailed(true);
});
return () => {
cancelled = true;
@@ -166,9 +118,11 @@ export function ProviderSection() {
// verbatim silently takes options away: the flag-only providers never
// appear in it, and a saved provider the server has since stopped
// advertising would leave a blank trigger with nothing to recover with.
- const providerOptions = [...new Set([...providers, ...FLAG_ONLY_PROVIDERS, provider])];
+ const providerOptions = [
+ ...new Set([...catalog.map((entry) => entry.id), ...FLAG_ONLY_PROVIDERS, provider]),
+ ];
- const providerInfo = PROVIDER_ENV_VARS[provider];
+ const providerInfo = catalog.find((entry) => entry.id === provider);
const embedderVars = EMBEDDER_ENV_VARS[embedder] ?? [];
return (
@@ -184,7 +138,7 @@ export function ProviderSection() {
<SettingsRows>
<SettingsRow
label={t("provider.providerLabel")}
- hint={providerInfo?.installHint}
+ hint={providerInfo?.setup_hint || undefined}
>
<div className="space-y-2">
<Select value={provider} onValueChange={handleProviderChange}>
@@ -202,7 +156,12 @@ export function ProviderSection() {
))}
</SelectContent>
</Select>
- {providerInfo && <EnvVarLine vars={providerInfo.vars} />}
+ {providerInfo && <EnvVarLine vars={providerInfo.env_vars ?? []} />}
+ {catalogFailed && (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ {t("provider.catalogUnavailable")}
+ </p>
+ )}
</div>
</SettingsRow>
@@ -213,10 +172,7 @@ export function ProviderSection() {
>
<Input
id="model"
- // Catalog first: it is what the server will actually default to.
- // The local table is the cold-load stand-in, and a stale entry in
- // it winning would reintroduce the drift this catalog read fixes.
- placeholder={catalogModels[provider] ?? MODEL_PLACEHOLDERS[provider] ?? "model name"}
+ placeholder={providerInfo?.default_model || "model name"}
value={model}
onChange={(e) => setModel(e.target.value)}
onBlur={handleModelBlur}
diff --git a/tests/providers/test_rate_limiter.py b/tests/providers/test_rate_limiter.py
index 61416a164..c653cdb21 100644
--- a/tests/providers/test_rate_limiter.py
+++ b/tests/providers/test_rate_limiter.py
@@ -11,7 +11,8 @@ import time
import pytest
-from repowise.core.rate_limiter import PROVIDER_DEFAULTS, RateLimitConfig, RateLimiter
+from repowise.core.providers.llm.registry import PROVIDER_DEFAULTS
+from repowise.core.rate_limiter import RateLimitConfig, RateLimiter
class TestRateLimitConfig:
diff --git a/tests/unit/agents/test_identity.py b/tests/unit/agents/test_identity.py
index 83733b834..fea2038c8 100644
--- a/tests/unit/agents/test_identity.py
+++ b/tests/unit/agents/test_identity.py
@@ -262,3 +262,43 @@ def test_the_shipped_registry_is_the_six_integrated_agents() -> None:
"opencode",
"hermes",
]
+
+
+# ---------------------------------------------------------------------------
+# Install and login facts
+# ---------------------------------------------------------------------------
+
+
+def test_install_check_asks_path_for_the_declared_executable(monkeypatch) -> None:
+ import shutil
+
+ monkeypatch.setattr(shutil, "which", lambda name: f"/bin/{name}" if name == "codex" else None)
+ assert identity.CODEX.is_installed()
+ assert not identity.OPENCODE.is_installed()
+
+
+def test_an_agent_without_an_executable_is_never_installed() -> None:
+ assert not AgentIdentity(slug="zed", display_name="Zed").is_installed()
+
+
+def test_login_runs_the_declared_check_and_reads_the_exit_code(monkeypatch) -> None:
+ import shutil
+ import subprocess
+
+ monkeypatch.setattr(shutil, "which", lambda name: name)
+ calls: list[list[str]] = []
+
+ def fake_run(args: list[str], **_kwargs: object) -> subprocess.CompletedProcess[str]:
+ calls.append(args)
+ return subprocess.CompletedProcess(args, 1, stdout="Logged in", stderr="")
+
+ monkeypatch.setattr(subprocess, "run", fake_run)
+ assert not identity.CODEX.is_logged_in()
+ assert calls == [["codex", "login", "status"]]
+ # No cheap login query: installed is the most this can say.
+ assert identity.CLAUDE_CODE.is_logged_in()
+
+
+def test_identity_for_provider_follows_the_indexing_link() -> None:
+ assert identity.identity_for_provider("codex_cli") is identity.CODEX
+ assert identity.identity_for_provider("anthropic") is None
diff --git a/tests/unit/cli/test_editor_setup.py b/tests/unit/cli/test_editor_setup.py
index 77a5d0261..22c194f9b 100644
--- a/tests/unit/cli/test_editor_setup.py
+++ b/tests/unit/cli/test_editor_setup.py
@@ -1299,6 +1299,31 @@ def test_workspace_generation_rebinds_codex_provider_to_repo(
assert calls == [("codex_cli", "codex_cli/gpt-5.5", tmp_path)]
+def test_workspace_generation_rebinds_opencode_provider_to_repo(
+ tmp_path: Path,
+ monkeypatch: Any,
+) -> None:
+ """opencode also runs in the repo's cwd, so a workspace must rebind it per repo."""
+
+ class FakeProvider:
+ provider_name = "opencode"
+ model_name = "opencode/default"
+
+ rebound = object()
+ calls: list[tuple[str, str, Path]] = []
+
+ def fake_resolve_provider(provider_name: str, model: str, repo_path: Path) -> object:
+ calls.append((provider_name, model, repo_path))
+ return rebound
+
+ monkeypatch.setattr(init_cmd.workspace, "resolve_provider", fake_resolve_provider)
+
+ result = init_cmd.workspace._workspace_generation_provider_for_repo(FakeProvider(), tmp_path)
+
+ assert result is rebound
+ assert calls == [("opencode", "opencode/default", tmp_path)]
+
+
def test_init_command_uses_editor_option_abstraction() -> None:
source = inspect.getsource(init_cmd.init_command.callback) + inspect.getsource(
init_cmd._workspace_init
diff --git a/tests/unit/cli/test_init_ux.py b/tests/unit/cli/test_init_ux.py
index 5c56dc27b..0e8aa194b 100644
--- a/tests/unit/cli/test_init_ux.py
+++ b/tests/unit/cli/test_init_ux.py
@@ -151,16 +151,14 @@ def test_ollama_is_ready_when_the_endpoint_answers(monkeypatch: Any) -> None:
"""It takes no API key, so reachability is the only question worth asking."""
monkeypatch.delenv("OLLAMA_BASE_URL", raising=False)
monkeypatch.setattr(provider_selection, "_detect_ollama_status", lambda: True)
- monkeypatch.setattr(provider_selection, "_detect_codex_cli_status", lambda: (False, False))
- monkeypatch.setattr(provider_selection, "_detect_opencode_status", lambda: False)
+ monkeypatch.setattr(provider_selection, "_agent_cli_status", lambda _name: (False, False))
assert provider_selection._detect_provider_status()["ollama"] == "http://localhost:11434"
def test_ollama_is_not_ready_when_nothing_is_listening(monkeypatch: Any) -> None:
monkeypatch.setattr(provider_selection, "_detect_ollama_status", lambda: False)
- monkeypatch.setattr(provider_selection, "_detect_codex_cli_status", lambda: (False, False))
- monkeypatch.setattr(provider_selection, "_detect_opencode_status", lambda: False)
+ monkeypatch.setattr(provider_selection, "_agent_cli_status", lambda _name: (False, False))
assert "ollama" not in provider_selection._detect_provider_status()
@@ -259,8 +257,7 @@ def test_the_keyless_providers_get_setup_help_instead_of_a_key_prompt() -> None:
def test_selecting_an_unreachable_ollama_never_prompts_for_a_key(monkeypatch: Any) -> None:
console, buf = _console()
monkeypatch.setattr(provider_selection, "_detect_ollama_status", lambda: False)
- monkeypatch.setattr(provider_selection, "_detect_codex_cli_status", lambda: (False, False))
- monkeypatch.setattr(provider_selection, "_detect_opencode_status", lambda: False)
+ monkeypatch.setattr(provider_selection, "_agent_cli_status", lambda _name: (False, False))
def boom(*_args: object, **_kwargs: object) -> str:
raise AssertionError("ollama has no API key to prompt for")
@@ -351,8 +348,7 @@ def test_explicit_openai_setup_prompts_for_url_when_key_is_already_set(
def test_provider_status_separates_official_and_custom_openai(monkeypatch: Any) -> None:
monkeypatch.setenv("OPENAI_API_KEY", "router-secret")
monkeypatch.setenv("OPENAI_BASE_URL", "http://localhost:20128/v1")
- monkeypatch.setattr(provider_selection, "_detect_codex_cli_status", lambda: (False, False))
- monkeypatch.setattr(provider_selection, "_detect_opencode_status", lambda: False)
+ monkeypatch.setattr(provider_selection, "_agent_cli_status", lambda _name: (False, False))
monkeypatch.setattr(provider_selection, "_detect_ollama_status", lambda: False)
custom_status = provider_selection._detect_provider_status()
@@ -370,8 +366,7 @@ def test_official_openai_reuses_key_from_previous_custom_setup(
) -> None:
monkeypatch.setenv("OPENAI_API_KEY", "existing-secret")
monkeypatch.setenv("OPENAI_BASE_URL", "http://localhost:20128/v1")
- monkeypatch.setattr(provider_selection, "_detect_codex_cli_status", lambda: (False, False))
- monkeypatch.setattr(provider_selection, "_detect_opencode_status", lambda: False)
+ monkeypatch.setattr(provider_selection, "_agent_cli_status", lambda _name: (False, False))
monkeypatch.setattr(provider_selection, "_detect_ollama_status", lambda: False)
openai_idx = str(provider_selection._PROVIDER_CHOICES.index("openai") + 1)
monkeypatch.setattr(provider_selection.Prompt, "ask", lambda *_a, **_k: openai_idx)
@@ -507,3 +502,23 @@ def test_custom_gateway_no_save_key_still_persists_endpoint(
env_text = (tmp_path / ".repowise" / ".env").read_text(encoding="utf-8")
assert "OPENAI_BASE_URL=http://localhost:20128/v1" in env_text
assert "OPENAI_API_KEY" not in env_text
+
+
+def test_picker_rows_keep_their_order() -> None:
+ """Row numbers and the pre-selected default (first ready row) follow this
+ order, so reordering the provider specs must not move them."""
+ assert provider_selection._PROVIDER_CHOICES == (
+ "gemini",
+ "openai",
+ "openai_compatible",
+ "anthropic",
+ "deepseek",
+ "kimi",
+ "edenai",
+ "codex_cli",
+ "claude_cli",
+ "opencode",
+ "ollama",
+ "openrouter",
+ "litellm",
+ )
diff --git a/tests/unit/cli/test_ui_codex.py b/tests/unit/cli/test_ui_codex.py
index 5d5f185aa..719d459a2 100644
--- a/tests/unit/cli/test_ui_codex.py
+++ b/tests/unit/cli/test_ui_codex.py
@@ -3,29 +3,18 @@ from __future__ import annotations
from typing import Any
from repowise.cli.ui import provider_selection as ui
+from repowise.core.agents.identity import AgentIdentity
def test_detect_provider_status_requires_codex_login(monkeypatch: Any) -> None:
- monkeypatch.setattr(
- "repowise.cli.mcp_config.is_codex_cli_installed",
- lambda: True,
- )
- monkeypatch.setattr(
- "repowise.cli.mcp_config.is_codex_logged_in",
- lambda: False,
- )
+ monkeypatch.setattr(AgentIdentity, "is_installed", lambda self: True)
+ monkeypatch.setattr(AgentIdentity, "is_logged_in", lambda self: self.slug != "codex")
assert "codex_cli" not in ui._detect_provider_status()
def test_detect_provider_status_accepts_authenticated_codex(monkeypatch: Any) -> None:
- monkeypatch.setattr(
- "repowise.cli.mcp_config.is_codex_cli_installed",
- lambda: True,
- )
- monkeypatch.setattr(
- "repowise.cli.mcp_config.is_codex_logged_in",
- lambda: True,
- )
-
- assert ui._detect_provider_status()["codex_cli"] == "codex CLI"
+ monkeypatch.setattr(AgentIdentity, "is_installed", lambda self: True)
+ monkeypatch.setattr(AgentIdentity, "is_logged_in", lambda self: True)
+
+ assert "codex_cli" in ui._detect_provider_status()
diff --git a/tests/unit/cli/test_ui_reasoning.py b/tests/unit/cli/test_ui_reasoning.py
index c6bf81c74..1259ac409 100644
--- a/tests/unit/cli/test_ui_reasoning.py
+++ b/tests/unit/cli/test_ui_reasoning.py
@@ -82,7 +82,7 @@ def test_interactive_provider_config_select_uses_model_reasoning_options(
monkeypatch.setattr(
provider_selection, "_detect_provider_status", lambda: {"gemini": "GEMINI_API_KEY"}
)
- monkeypatch.setattr(provider_selection, "_detect_codex_cli_status", lambda: (False, False))
+ monkeypatch.setattr(provider_selection, "_agent_cli_status", lambda _name: (False, False))
monkeypatch.setattr(
provider_selection,
"_provider_model_options",
diff --git a/tests/unit/health/test_refactoring_enrich.py b/tests/unit/health/test_refactoring_enrich.py
index 47959791a..dc10fcf37 100644
--- a/tests/unit/health/test_refactoring_enrich.py
+++ b/tests/unit/health/test_refactoring_enrich.py
@@ -401,6 +401,8 @@ def test_build_enrichment_provider_auto_detects_kimi(tmp_path, monkeypatch) -> N
"OPENROUTER_API_KEY",
"DEEPSEEK_API_KEY",
"GEMINI_API_KEY",
+ "GOOGLE_API_KEY",
+ "OLLAMA_BASE_URL",
"LITELLM_API_KEY",
):
monkeypatch.delenv(key, raising=False)
@@ -424,6 +426,22 @@ def test_build_enrichment_provider_auto_detects_kimi(tmp_path, monkeypatch) -> N
}
+def test_build_enrichment_provider_runs_a_repo_cwd_cli_in_the_repo(tmp_path, monkeypatch) -> None:
+ """A configured agent CLI that works in the repo's directory is told which repo."""
+ captured = {}
+
+ def fake_get_provider(name, **kwargs):
+ captured.update(kwargs, name=name)
+ return object()
+
+ monkeypatch.setattr("repowise.core.providers.get_provider", fake_get_provider)
+
+ build_enrichment_provider(tmp_path, provider_name="codex_cli")
+
+ assert captured["name"] == "codex_cli"
+ assert captured["repo_path"] == tmp_path
+
+
def test_validate_extract_method_detects_ccn_drop():
# The original function (high CCN) is the span fed to the model; the
# generated response splits it into a low-CCN residual plus a helper.
diff --git a/tests/unit/server/test_provider_config.py b/tests/unit/server/test_provider_config.py
index 5de642865..33c03e785 100644
--- a/tests/unit/server/test_provider_config.py
+++ b/tests/unit/server/test_provider_config.py
@@ -303,6 +303,20 @@ def test_config_path_defaults_to_home(monkeypatch, tmp_path):
assert pc._config_path() == tmp_path / ".repowise" / "provider_config.json"
+def test_list_provider_status_carries_setup_facts_from_the_specs(clean_env, tmp_path):
+ """The settings UIs render these instead of keeping provider tables."""
+ status = pc.list_provider_status()
+ by_id = {p["id"]: p for p in status["providers"]}
+
+ assert by_id["gemini"]["requires_key"] is True
+ assert by_id["gemini"]["env_vars"] == ["GEMINI_API_KEY", "GOOGLE_API_KEY"]
+ assert by_id["ollama"]["requires_key"] is False
+ assert by_id["ollama"]["env_vars"] == ["OLLAMA_BASE_URL"]
+ assert by_id["codex_cli"]["requires_key"] is False
+ assert "codex login" in by_id["codex_cli"]["setup_hint"]
+ assert "mock" not in by_id
+
+
def test_list_provider_status_never_returns_key_material(clean_env, tmp_path):
repo = _make_repo(
tmp_path / "repo",
@@ -315,6 +329,15 @@ def test_list_provider_status_never_returns_key_material(clean_env, tmp_path):
serialized = repr(status)
assert "super-secret-key" not in serialized
for provider in status["providers"]:
- assert set(provider) == {"id", "name", "models", "default_model", "configured"}
+ assert set(provider) == {
+ "id",
+ "name",
+ "models",
+ "default_model",
+ "configured",
+ "requires_key",
+ "env_vars",
+ "setup_hint",
+ }
assert "key" not in provider
assert "api_key" not in provider
diff --git a/tests/unit/test_providers/test_opencode_provider.py b/tests/unit/test_providers/test_opencode_provider.py
index 0fc4f25c5..b3a7a79d3 100644
--- a/tests/unit/test_providers/test_opencode_provider.py
+++ b/tests/unit/test_providers/test_opencode_provider.py
@@ -180,7 +180,7 @@ def test_invalid_model_name_raises(monkeypatch, tmp_path):
def test_missing_cli_raises(monkeypatch, tmp_path):
monkeypatch.setattr("shutil.which", lambda _cmd: None)
- with pytest.raises(ProviderError, match="OpenCode CLI is not installed"):
+ with pytest.raises(ProviderError, match=r"OpenCode CLI not found.*opencode.ai/install"):
OpenCodeProvider(repo_path=tmp_path)
diff --git a/tests/unit/test_providers/test_provider_env_registry.py b/tests/unit/test_providers/test_provider_env_registry.py
index e326186ae..9f58500a9 100644
--- a/tests/unit/test_providers/test_provider_env_registry.py
+++ b/tests/unit/test_providers/test_provider_env_registry.py
@@ -98,12 +98,10 @@ def test_every_provider_that_can_be_auto_detected_is_in_the_order():
)
-# --- the copies that survive elsewhere -------------------------------------
+# --- the catalogs derived from the specs ------------------------------------
#
-# Two catalogs still list env vars of their own because they carry display
-# metadata this table has no business holding (labels, model lists, signup
-# URLs, CLI sentinels). They are pinned to the registry here rather than left
-# to drift: a mismatch fails, and moving one into the registry is a deletion.
+# The server catalog and the init picker build their tables from the provider
+# specs. These pin the derivation, so a hand-written copy cannot creep back.
def test_server_provider_catalog_agrees_with_the_registry():
diff --git a/tests/unit/test_providers/test_provider_specs.py b/tests/unit/test_providers/test_provider_specs.py
new file mode 100644
index 000000000..fff2371e0
--- /dev/null
+++ b/tests/unit/test_providers/test_provider_specs.py
@@ -0,0 +1,199 @@
+"""The provider specs are the only place a provider is described.
+
+Two contracts. The agent registry and the provider registry name each other
+(``AgentIdentity.indexing_provider`` and ``ProviderSpec.agent``), and the two
+links must agree. And no module outside the registries branches on, or keeps a
+table keyed by, a provider name: that is how the parallel tables this file
+replaced drifted.
+"""
+
+from __future__ import annotations
+
+import ast
+import types
+from pathlib import Path
+
+import pytest
+
+from repowise.core.agents.identity import all_identities, get_identity, identity_for_provider
+from repowise.core.providers.embedding.registry import _BUILTIN_EMBEDDERS
+from repowise.core.providers.llm import registry
+from repowise.core.providers.llm.registry import get_provider
+from repowise.core.providers.llm.specs import PROVIDER_SPECS
+
+_PACKAGES = Path(__file__).parents[3] / "packages"
+
+# --- the link between the two registries -----------------------------------
+
+
+ "agent", [a for a in all_identities() if a.indexing_provider], ids=lambda a: a.slug
+)
+def test_every_indexing_agent_names_a_spec_that_names_it_back(agent):
+ spec = PROVIDER_SPECS.get(agent.indexing_provider)
+ assert spec is not None, f"{agent.slug} names unknown provider {agent.indexing_provider!r}"
+ assert spec.agent == agent.slug
+
+
+ "spec", [s for s in PROVIDER_SPECS.values() if s.agent], ids=lambda s: s.name
+)
+def test_every_agent_spec_names_an_identity_that_names_it_back(spec):
+ agent = get_identity(spec.agent)
+ assert agent is not None, f"{spec.name} names unknown agent {spec.agent!r}"
+ assert agent.indexing_provider == spec.name
+ assert identity_for_provider(spec.name) is agent
+ # The facts the CLI renders when the agent's CLI is missing.
+ assert agent.executable and agent.install_hint and agent.login_hint
+
+
+# --- rate limiting ---------------------------------------------------------
+
+
+ "spec", [s for s in PROVIDER_SPECS.values() if s.agent], ids=lambda s: s.name
+)
+def test_agent_clis_get_no_rate_limiter(spec, monkeypatch):
+ """Concurrency is the only throttle for a subprocess-backed provider."""
+ assert spec.rate_limit is None
+ seen: dict = {}
+
+ class Fake:
+ def __init__(self, **kwargs):
+ seen.update(kwargs)
+
+ fake_module = types.SimpleNamespace(**{spec.class_name: Fake})
+ monkeypatch.setattr(registry.importlib, "import_module", lambda _path: fake_module)
+ get_provider(spec.name)
+ assert "rate_limiter" not in seen
+
+
+# --- no provider-name branches outside the registries ----------------------
+
+#: Every provider name but ``mock``, which is also the default embedder and the
+#: ordinary test-double word that health and dead-code analysis match on.
+_CHECKED = frozenset(PROVIDER_SPECS) - {"mock"}
+
+_EMBEDDERS = frozenset(_BUILTIN_EMBEDDERS)
+
+#: Path (relative to ``packages/``) -> names it may spell, and why.
+_ALLOWED: dict[str, frozenset[str]] = {
+ # ``opencode`` is a ``--target`` id as well as a provider.
+ "cli/src/repowise/cli/agent_targets/registry.py": frozenset({"opencode"}),
+ # Commit-trailer patterns naming the agent that wrote a commit.
+ "core/src/repowise/core/ingestion/git_indexer/agent_provenance.py": frozenset(
+ {"gemini", "opencode"}
+ ),
+ # Price keys are model families (``deepseek-v4``, ``kimi-k2``, ``gemini``).
+ "core/src/repowise/core/cost_estimator/pricing.py": frozenset({"deepseek", "gemini", "kimi"}),
+ # Third-party SDK names found in a scanned repo's imports.
+ "core/src/repowise/core/ingestion/external_systems/classifier.py": frozenset(
+ {"anthropic", "openai"}
+ ),
+ # Behaviour only the OpenAI adapter has: the custom-gateway row and base-url
+ # prompt, and its reasoning budget. Ollama's readiness is a TCP probe.
+ "cli/src/repowise/cli/helpers.py": frozenset({"openai"}),
+ "cli/src/repowise/cli/ui/provider_selection.py": frozenset({"openai", "ollama"}),
+ "server/src/repowise/server/mcp_server/tool_answer/synthesis.py": frozenset({"openai"}),
+ # Embedder surfaces: these literals name embedders, which share spellings.
+ "core/src/repowise/core/providers/embedding/registry.py": _EMBEDDERS,
+ "cli/src/repowise/cli/commands/init_cmd/command.py": _EMBEDDERS,
+ "cli/src/repowise/cli/commands/reindex_cmd.py": _EMBEDDERS,
+ "cli/src/repowise/cli/commands/serve_cmd.py": _EMBEDDERS,
+ "cli/src/repowise/cli/commands/update_cmd/deterministic.py": _EMBEDDERS,
+ "cli/src/repowise/cli/providers/embedders.py": _EMBEDDERS,
+ "cli/src/repowise/cli/providers/keys.py": _EMBEDDERS,
+ "cli/src/repowise/cli/ui/mode_selection.py": _EMBEDDERS,
+ "server/src/repowise/server/app.py": _EMBEDDERS,
+ "server/src/repowise/server/mcp_server/_server.py": _EMBEDDERS,
+}
+
+
+def _is_allowed(path: Path, name: str) -> bool:
+ rel = path.relative_to(_PACKAGES).as_posix()
+ # A provider's own module tags its errors and reports its own name.
+ if rel.startswith("core/src/repowise/core/providers/llm/") and path.stem == name:
+ return True
+ return name in _ALLOWED.get(rel, frozenset())
+
+
+def _name_literals(tree: ast.AST):
+ """Provider-name literals used as a comparison operand, a ``case`` value, a
+ collection element, a dict key or a ``.get()`` key. A bare argument
+ (``get_provider("x")``) is a use, not a branch or a table, and is not
+ flagged."""
+
+ def names(node):
+ if isinstance(node, ast.Constant) and node.value in _CHECKED:
+ yield node
+ elif isinstance(node, (ast.Tuple, ast.List, ast.Set)):
+ for elt in node.elts:
+ yield from names(elt)
+
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Compare):
+ for operand in (node.left, *node.comparators):
+ yield from names(operand)
+ elif isinstance(node, ast.MatchValue):
+ yield from names(node.value)
+ elif isinstance(node, (ast.Tuple, ast.List, ast.Set)):
+ yield from names(node)
+ elif isinstance(node, ast.Dict):
+ for key in node.keys:
+ if key is not None:
+ yield from names(key)
+ elif (
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and node.func.attr == "get"
+ and node.args
+ ):
+ yield from names(node.args[0])
+
+
+def _sources():
+ return sorted(p for p in _PACKAGES.glob("*/src/**/*.py"))
+
+
+def test_no_module_branches_on_a_provider_name():
+ offenders = sorted(
+ {
+ f"{path.relative_to(_PACKAGES).as_posix()}:{node.lineno} {node.value!r}"
+ for path in _sources()
+ for node in _name_literals(ast.parse(path.read_text(encoding="utf-8")))
+ if not _is_allowed(path, node.value)
+ }
+ )
+ assert not offenders, (
+ "provider names spelled outside the registry; read a ProviderSpec field "
+ f"instead: {offenders}"
+ )
+
+
+def test_the_allowlist_has_no_stale_entries():
+ """An entry that no longer matches anything would quietly widen later."""
+ for rel, names in _ALLOWED.items():
+ path = _PACKAGES / rel
+ assert path.is_file(), f"{rel} is gone"
+ found = {node.value for node in _name_literals(ast.parse(path.read_text(encoding="utf-8")))}
+ assert found & names, f"{rel} no longer spells any of {sorted(names)}"
+
+
+ "snippet",
+ [
+ 'x == "codex_cli"',
+ 'x in ("claude_cli", "y")',
+ '{"opencode": 1}',
+ 'd.get("litellm")',
+ 'match x:\n case "kimi":\n pass',
+ ],
+)
+def test_the_guard_sees_each_branch_shape(snippet):
+ assert list(_name_literals(ast.parse(snippet)))
+
+
+def test_the_guard_is_looking_at_real_sources():
+ """A glob that matched nothing, or a name set that emptied, passes vacuously."""
+ assert len(_sources()) > 500
+ assert {"claude_cli", "codex_cli", "opencode", "litellm", "openai"} <= _CHECKED