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.

fix(mcp): budget get_answer synthesis per provider, not at a flat 30s (#1124)

Raghav Chamadiyadcc9a399b4f6
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index 1d7bcc614..9fd42dcd9 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -495,6 +495,7 @@ The `.repowise/.env` file is gitignored automatically.
| `REPOWISE_MODEL` | Override model |
| `REPOWISE_DOC_MODEL` | Override the model used for `get_answer` synthesis specifically |
| `REPOWISE_REASONING` | Override `reasoning` (see valid values above) |
+| `REPOWISE_ANSWER_TIMEOUT_S` | Seconds `get_answer` waits for synthesis before giving up. Defaults to a per-provider budget: 60s for the remote API providers, 120s for `ollama` and `litellm`, 180s for `codex_cli` and `opencode`. Raise it if your model is slower than its class suggests, lower it if you would rather an agent fail fast than block. Capped at 600s. Note your MCP client enforces its own tool timeout underneath this one, so setting a value above it produces a client-side error instead of repowise's diagnosable "synthesis exceeded its budget" response |
### Embeddings
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index fc8cdf4e6..26c3b9991 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -647,6 +647,11 @@ def resolve_provider(
4. Auto-detect from API key env vars
"""
from repowise.core.providers import get_provider
+ from repowise.core.providers.llm.registry import (
+ PROVIDER_AUTODETECT_ORDER,
+ provider_credentials_present,
+ provider_kwargs,
+ )
cfg: dict[str, Any] = {}
if repo_path is not None:
@@ -668,21 +673,13 @@ def resolve_provider(
if model is None and cfg.get("model"):
model = cfg["model"]
- def _resolve_base_url(name: str) -> str | None:
- """Return base_url from env or repo config for the provider."""
- env_vars = {
- "anthropic": ["ANTHROPIC_BASE_URL"],
- "openai": ["OPENAI_BASE_URL"],
- "gemini": ["GEMINI_BASE_URL"],
- "deepseek": ["DEEPSEEK_BASE_URL"],
- "kimi": ["KIMI_BASE_URL"],
- "ollama": ["OLLAMA_BASE_URL"],
- "litellm": ["LITELLM_BASE_URL", "LITELLM_API_BASE"],
- }
- for var in env_vars.get(name, []):
- val = os.environ.get(var)
- if val:
- return val
+ def _config_base_url(name: str) -> str | None:
+ """Return a base_url the repo config sets for the provider, if any.
+
+ Env vars are handled by :func:`provider_kwargs` from the shared
+ registry mapping; this covers only the config-file source, which is
+ CLI-specific.
+ """
section = cfg.get(name)
if isinstance(section, dict):
base_url = section.get("base_url")
@@ -690,6 +687,19 @@ def resolve_provider(
return base_url
return None
+ def _build(name: str) -> Any:
+ """Instantiate ``name`` with env-derived kwargs plus config fallbacks."""
+ kwargs = provider_kwargs(name, model=model, repo_path=repo_path)
+ # Applied to any name, as before: openrouter takes a base_url without
+ # having an env var for one, so gating this on the env map would drop a
+ # config value that used to be honored. (A stray `mock: {base_url: …}`
+ # in config.yaml still reaches a constructor that has no such
+ # parameter and raises TypeError. Longstanding, orthogonal to #1119.)
+ config_base_url = _config_base_url(name)
+ if config_base_url:
+ kwargs.setdefault("base_url", config_base_url)
+ return get_provider(name, **kwargs)
+
if provider_name is not None:
# Validate configuration before attempting to create provider
warnings = validate_provider_config(provider_name)
@@ -699,103 +709,15 @@ def resolve_provider(
# For explicit provider requests, we still try to create it
# The provider constructor will fail if the API key is actually required
- kwargs: dict[str, Any] = {}
- if model:
- kwargs["model"] = model
- base_url = _resolve_base_url(provider_name)
- if base_url:
- kwargs["base_url"] = base_url
- if provider_name == "codex_cli" and repo_path is not None:
- kwargs["repo_path"] = repo_path
- if provider_name == "opencode" and repo_path is not None:
- kwargs["repo_path"] = repo_path
-
- # Pass API key from environment if available
- if provider_name == "anthropic" and os.environ.get("ANTHROPIC_API_KEY"):
- kwargs["api_key"] = os.environ["ANTHROPIC_API_KEY"]
- elif provider_name == "openai" and os.environ.get("OPENAI_API_KEY"):
- kwargs["api_key"] = os.environ["OPENAI_API_KEY"]
- elif provider_name == "gemini" and (
- os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")
- ):
- kwargs["api_key"] = os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")
- elif provider_name == "openrouter" and os.environ.get("OPENROUTER_API_KEY"):
- kwargs["api_key"] = os.environ["OPENROUTER_API_KEY"]
- elif provider_name == "deepseek" and os.environ.get("DEEPSEEK_API_KEY"):
- kwargs["api_key"] = os.environ["DEEPSEEK_API_KEY"]
- elif provider_name == "kimi" and os.environ.get("KIMI_API_KEY"):
- kwargs["api_key"] = os.environ["KIMI_API_KEY"]
- elif provider_name == "litellm" and os.environ.get("LITELLM_API_KEY"):
- kwargs["api_key"] = os.environ["LITELLM_API_KEY"]
- elif provider_name == "ollama" and os.environ.get("OLLAMA_BASE_URL"):
- kwargs["base_url"] = os.environ["OLLAMA_BASE_URL"]
-
- return get_provider(provider_name, **kwargs)
-
- # Auto-detect from env vars
- if os.environ.get("ANTHROPIC_API_KEY") and os.environ["ANTHROPIC_API_KEY"].strip():
- kwargs = (
- {"model": model, "api_key": os.environ["ANTHROPIC_API_KEY"]}
- if model
- else {"api_key": os.environ["ANTHROPIC_API_KEY"]}
- )
- base_url = _resolve_base_url("anthropic")
- if base_url:
- kwargs["base_url"] = base_url
- return get_provider("anthropic", **kwargs)
- if os.environ.get("OPENAI_API_KEY") and os.environ["OPENAI_API_KEY"].strip():
- kwargs = (
- {"model": model, "api_key": os.environ["OPENAI_API_KEY"]}
- if model
- else {"api_key": os.environ["OPENAI_API_KEY"]}
- )
- base_url = _resolve_base_url("openai")
- if base_url:
- kwargs["base_url"] = base_url
- return get_provider("openai", **kwargs)
- if os.environ.get("OPENROUTER_API_KEY") and os.environ["OPENROUTER_API_KEY"].strip():
- kwargs = (
- {"model": model, "api_key": os.environ["OPENROUTER_API_KEY"]}
- if model
- else {"api_key": os.environ["OPENROUTER_API_KEY"]}
- )
- return get_provider("openrouter", **kwargs)
- if os.environ.get("OLLAMA_BASE_URL") and os.environ["OLLAMA_BASE_URL"].strip():
- kwargs = (
- {"model": model, "base_url": os.environ["OLLAMA_BASE_URL"]}
- if model
- else {"base_url": os.environ["OLLAMA_BASE_URL"]}
- )
- return get_provider("ollama", **kwargs)
- if (os.environ.get("GEMINI_API_KEY") and os.environ["GEMINI_API_KEY"].strip()) or (
- os.environ.get("GOOGLE_API_KEY") and os.environ["GOOGLE_API_KEY"].strip()
- ):
- api_key = os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")
- kwargs = {"model": model, "api_key": api_key} if model else {"api_key": api_key}
- base_url = _resolve_base_url("gemini")
- if base_url:
- kwargs["base_url"] = base_url
- return get_provider("gemini", **kwargs)
- if os.environ.get("DEEPSEEK_API_KEY") and os.environ["DEEPSEEK_API_KEY"].strip():
- kwargs = (
- {"model": model, "api_key": os.environ["DEEPSEEK_API_KEY"]}
- if model
- else {"api_key": os.environ["DEEPSEEK_API_KEY"]}
- )
- base_url = _resolve_base_url("deepseek")
- if base_url:
- kwargs["base_url"] = base_url
- return get_provider("deepseek", **kwargs)
- if os.environ.get("KIMI_API_KEY") and os.environ["KIMI_API_KEY"].strip():
- kwargs = (
- {"model": model, "api_key": os.environ["KIMI_API_KEY"]}
- if model
- else {"api_key": os.environ["KIMI_API_KEY"]}
- )
- base_url = _resolve_base_url("kimi")
- if base_url:
- kwargs["base_url"] = base_url
- return get_provider("kimi", **kwargs)
+ return _build(provider_name)
+
+ # Auto-detect from whatever credentials the env carries, in the shared
+ # priority order. The per-provider env-var mapping lives in the registry
+ # beside the provider table, so adding a provider wires it into the CLI and
+ # the MCP server at once instead of into whichever copy got remembered.
+ for candidate in PROVIDER_AUTODETECT_ORDER:
+ if provider_credentials_present(candidate):
+ return _build(candidate)
raise click.ClickException(
"No provider configured. Use --provider, set REPOWISE_PROVIDER, "
@@ -888,16 +810,17 @@ def validate_provider_config(provider_name: str | None = None) -> list[str]:
"""Check if environment variable exists (even if empty)."""
return var_name in os.environ
- # Define required environment variables for each provider
+ # 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,
+ )
+
provider_env_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", "GOOGLE_API_KEY"], # Either one
- "ollama": ["OLLAMA_BASE_URL"],
- "litellm": ["LITELLM_API_KEY"], # May need others depending on backend
+ name: list(provider_required_envs(name)) for name in (*PROVIDER_API_KEY_ENVS, "ollama")
}
if provider_name:
diff --git a/packages/core/src/repowise/core/providers/llm/base.py b/packages/core/src/repowise/core/providers/llm/base.py
index 33ff61618..98ebfe970 100644
--- a/packages/core/src/repowise/core/providers/llm/base.py
+++ b/packages/core/src/repowise/core/providers/llm/base.py
@@ -165,6 +165,19 @@ class BaseProvider(ABC):
- Raise RateLimitError on 429 responses after retries are exhausted
"""
+ # Wall-clock ceiling for ONE user-facing generate(), where somebody is
+ # waiting on the answer. Providers slower than a remote API must raise it:
+ # too low is not a slow answer, it is no answer, because the caller cancels
+ # mid-flight (#1119, where every codex_cli synthesis died at a flat 30s).
+ #
+ # 60s, not 30s: a remote API answered a question-shaped prompt in 4.8-8.7s
+ # across the only latency profile we have (n=6, one provider), which is too
+ # thin a sample to price a hard ceiling off, and a reasoning model behind
+ # the same API blows straight through 30s. 60s still sits under the tool
+ # timeout every MCP client imposes, so the extra headroom costs nothing but
+ # a longer wait on calls that were going to fail regardless.
+ interactive_timeout_s: float = 60.0
+
@abstractmethod
async def generate(
self,
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 b715a0b35..de3d9a62f 100644
--- a/packages/core/src/repowise/core/providers/llm/codex_cli.py
+++ b/packages/core/src/repowise/core/providers/llm/codex_cli.py
@@ -351,6 +351,13 @@ class CodexCliProvider(BaseProvider):
serializes subprocess calls by default.
"""
+ # A process spawn plus a full Codex agent turn. The floor is tens of
+ # seconds even for a short prompt, so an interactive caller has to budget
+ # in minutes or it cancels every call it ever makes (#1119). Stays under
+ # _EXEC_TIMEOUT_SECONDS so the caller gives up before the subprocess does
+ # and the error names the real cause.
+ interactive_timeout_s: float = 180.0
+
def __init__(
self,
model: str | None = None,
diff --git a/packages/core/src/repowise/core/providers/llm/litellm.py b/packages/core/src/repowise/core/providers/llm/litellm.py
index 9909ce191..d0566a42e 100644
--- a/packages/core/src/repowise/core/providers/llm/litellm.py
+++ b/packages/core/src/repowise/core/providers/llm/litellm.py
@@ -140,6 +140,10 @@ class LiteLLMProvider(BaseProvider):
rate_limiter: Optional RateLimiter instance.
"""
+ # The backend behind the proxy is unknown and routinely a self-hosted or
+ # local model, so budget for the slow case rather than assume a fast one.
+ interactive_timeout_s: float = 120.0
+
def __init__(
self,
model: str,
diff --git a/packages/core/src/repowise/core/providers/llm/ollama.py b/packages/core/src/repowise/core/providers/llm/ollama.py
index df91e316b..b613fe3bf 100644
--- a/packages/core/src/repowise/core/providers/llm/ollama.py
+++ b/packages/core/src/repowise/core/providers/llm/ollama.py
@@ -142,6 +142,11 @@ class OllamaProvider(BaseProvider):
concurrent requests against a resource-constrained machine).
"""
+ # Generation speed here is the user's own hardware, and a cold model pays
+ # a load from disk on top. Two minutes covers a mid-size local model on a
+ # laptop; the 30s default cancels one before it finishes warming up.
+ interactive_timeout_s: float = 120.0
+
def __init__(
self,
model: str = "llama3.2",
diff --git a/packages/core/src/repowise/core/providers/llm/opencode.py b/packages/core/src/repowise/core/providers/llm/opencode.py
index 0a39f17b2..dccbed33e 100644
--- a/packages/core/src/repowise/core/providers/llm/opencode.py
+++ b/packages/core/src/repowise/core/providers/llm/opencode.py
@@ -45,8 +45,20 @@ _MAX_STDERR_CHARS = 1_000
_MODEL_NAME_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._/\-]*$")
_OPENCODE_READONLY_CONFIG = json.dumps(
- {"permission": {k: "deny" for k in
- ("edit", "bash", "webfetch", "websearch", "external_directory", "doom_loop", "task")}}
+ {
+ "permission": {
+ k: "deny"
+ for k in (
+ "edit",
+ "bash",
+ "webfetch",
+ "websearch",
+ "external_directory",
+ "doom_loop",
+ "task",
+ )
+ }
+ }
)
@@ -159,9 +171,7 @@ def _error_message(stderr: str, stdout: str, returncode: int) -> str:
return f"opencode run exited with {returncode}"
-_MODEL_LINE_RE = re.compile(
- r"^\s*([a-zA-Z0-9][a-zA-Z0-9._\-]*)/([a-zA-Z0-9][a-zA-Z0-9._/\-]*)\s*$"
-)
+_MODEL_LINE_RE = re.compile(r"^\s*([a-zA-Z0-9][a-zA-Z0-9._\-]*)/([a-zA-Z0-9][a-zA-Z0-9._/\-]*)\s*$")
def _parse_models_output(output: str) -> list[str]:
@@ -250,6 +260,12 @@ class OpenCodeProvider(BaseProvider):
rate_limiter: Serializes subprocess calls by default.
"""
+ # `opencode run` spawns a process and drives a whole agent turn, and the
+ # model behind it is whatever the user configured, local ones included.
+ # Minutes, not seconds. Stays under _EXEC_TIMEOUT_SECONDS so the caller
+ # gives up before the subprocess does and the error names the real cause.
+ interactive_timeout_s: float = 180.0
+
def __init__(
self,
model: str | None = None,
diff --git a/packages/core/src/repowise/core/providers/llm/registry.py b/packages/core/src/repowise/core/providers/llm/registry.py
index 7cb4e9053..f223cd0cf 100644
--- a/packages/core/src/repowise/core/providers/llm/registry.py
+++ b/packages/core/src/repowise/core/providers/llm/registry.py
@@ -29,6 +29,7 @@ Custom provider registration:
from __future__ import annotations
import importlib
+import os
from collections.abc import Callable
from typing import Any
@@ -53,6 +54,154 @@ _BUILTIN_PROVIDERS: dict[str, tuple[str, str]] = {
"mock": ("repowise.core.providers.llm.mock", "MockProvider"),
}
+# 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.
+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",),
+ "litellm": ("LITELLM_API_KEY",),
+}
+
+# Which env var points a provider at a non-default endpoint. Proxies and
+# self-hosted deployments of the OpenAI-compatible providers live here too.
+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",),
+ "ollama": ("OLLAMA_BASE_URL",),
+ "litellm": ("LITELLM_BASE_URL", "LITELLM_API_BASE"),
+}
+
+# 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", "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",
+)
+
+# 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
+# possibly authenticate.
+EnvLookup = Callable[[str], "str | None"]
+
+
+def _clean(value: str | None) -> str | None:
+ return value.strip() if value and value.strip() else None
+
+
+def _first_env(names: tuple[str, ...], getenv: EnvLookup) -> str | None:
+ """First non-empty value among ``names``, in order."""
+ for name in names:
+ value = _clean(getenv(name))
+ if value:
+ return value
+ return None
+
+
+def provider_required_envs(name: str) -> tuple[str, ...]:
+ """Env vars without which ``name`` cannot reach a model at all.
+
+ An API key for the remote-API providers; the endpoint for ollama, which
+ 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 ()
+
+
+def provider_credentials_present(name: str, getenv: EnvLookup = os.environ.get) -> bool:
+ """Whether the environment names credentials for ``name`` specifically.
+
+ The question auto-detection asks: did the user put something in the
+ environment that points at *this* provider. False for a provider that
+ needs no env var at all, which is the correct answer here. "Runs without
+ configuration" is not a reason to pick it over what the user configured.
+ """
+ required = provider_required_envs(name)
+ return bool(required) and _first_env(required, getenv) is not None
+
+
+def provider_is_usable(name: str, getenv: EnvLookup = os.environ.get) -> bool:
+ """Whether ``name`` has everything it needs to reach a model.
+
+ The question explicit selection asks. True for the keyless providers
+ unconditionally, because they authenticate out of band: there is no env
+ var to check and so no grounds to reject them. Unknown
+ (runtime-registered) providers are also True, since we know nothing about
+ their requirements and must not veto them.
+ """
+ if name in KEYLESS_PROVIDERS:
+ return True
+ return not provider_required_envs(name) or provider_credentials_present(name, getenv)
+
+
+def provider_kwargs(
+ name: str,
+ *,
+ model: str | None = None,
+ repo_path: Any = None,
+ getenv: EnvLookup = os.environ.get,
+) -> dict[str, Any]:
+ """Constructor kwargs for ``name``, assembled from the environment.
+
+ The single place that knows how a provider name maps onto ``api_key`` /
+ ``base_url`` / ``repo_path`` constructor arguments. ``getenv`` is injected
+ so a caller with its own precedence (the MCP server overlays
+ ``.repowise/.env`` under the process env) reuses this mapping instead of
+ growing a parallel copy. The copies are what drifted into #1119.
+ """
+ kwargs: dict[str, Any] = {}
+ if model:
+ kwargs["model"] = model
+ api_key = _first_env(PROVIDER_API_KEY_ENVS.get(name, ()), getenv)
+ if api_key:
+ kwargs["api_key"] = api_key
+ base_url = _first_env(PROVIDER_BASE_URL_ENVS.get(name, ()), getenv)
+ if base_url:
+ kwargs["base_url"] = base_url
+ if repo_path is not None and name in REPO_PATH_PROVIDERS:
+ kwargs["repo_path"] = repo_path
+ return kwargs
+
+
# Runtime-registered custom providers (factory callables)
_custom_providers: dict[str, Callable[..., BaseProvider]] = {}
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py
index ef3face0f..75b1a1aca 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py
@@ -144,6 +144,7 @@ from repowise.server.mcp_server.tool_answer.symbols import (
from repowise.server.mcp_server.tool_answer.synthesis import (
_hash_question,
_resolve_provider_for_answer,
+ synthesize,
)
_log = logging.getLogger("repowise.mcp.answer")
@@ -558,6 +559,44 @@ def _build_data_shape_payload(grounded: dict, t0: float, repository) -> dict:
return payload
+def _degraded_payload(
+ *,
+ reason: str,
+ note: str,
+ hits: list[dict],
+ fallback_targets: list[str],
+ repository,
+ t0: float,
+) -> dict:
+ """Shape a synthesis-less get_answer response.
+
+ Both ways synthesis can be missing (no provider resolvable, the call
+ failed) return the same payload: retrieval hits the agent can act on, plus
+ a loud marker. ``degraded`` is mirrored into ``_meta`` because consumers
+ read freshness and health signals from there. The failure path used to
+ set only the top-level key, so a caller watching ``_meta`` saw a normal
+ empty answer.
+ """
+ return {
+ "answer": "",
+ "citations": [],
+ "confidence": "low",
+ "degraded": reason,
+ "fallback_targets": fallback_targets,
+ "retrieval": _serialize_hits(hits),
+ "note": note,
+ "_meta": {
+ **_build_meta(
+ timing_ms=(time.perf_counter() - t0) * 1000,
+ hint=_answer_hint("low", len(hits)),
+ repository=repository,
+ targets=fallback_targets,
+ ),
+ "degraded": reason,
+ },
+ }
+
+
@mcp.tool()
async def get_answer(
question: str,
@@ -1117,27 +1156,18 @@ async def get_answer(
"get_answer running WITHOUT synthesis: no LLM provider resolvable "
"(set REPOWISE_PROVIDER + its API key, or any supported API key)."
)
- payload = {
- "answer": "",
- "citations": [],
- "confidence": "low",
- "degraded": "no-llm-provider",
- "fallback_targets": fallback_targets,
- "retrieval": _serialize_hits(hits),
- "note": (
+ return _degraded_payload(
+ reason="no-llm-provider",
+ note=(
"DEGRADED: no LLM provider configured (set REPOWISE_PROVIDER "
"+ API key). "
"Returning retrieval hits only — Read the listed files to answer."
),
- "_meta": _build_meta(
- timing_ms=(time.perf_counter() - t0) * 1000,
- hint=_answer_hint("low", len(hits)),
- repository=repository,
- targets=fallback_targets,
- ),
- }
- payload["_meta"]["degraded"] = "no-llm-provider"
- return payload
+ hits=hits,
+ fallback_targets=fallback_targets,
+ repository=repository,
+ t0=t0,
+ )
# Ambiguous retrieval (always-synthesize): pull real page content across the
# non-dominant top pages so the LLM synthesizes over the actual candidate
@@ -1167,35 +1197,20 @@ async def get_answer(
context=_build_context_block_v2(hits, prelude=prelude, decisions=decisions),
)
- answer_text = ""
- try:
- response = await asyncio.wait_for(
- provider.generate(
- system_prompt=_SYSTEM_PROMPT,
- user_prompt=user_prompt,
- max_tokens=1024,
- temperature=0.2,
- ),
- timeout=30.0,
+ # The call budgets itself against what this provider actually needs. A
+ # remote API answers in single-digit seconds; an agent-CLI subprocess or a
+ # local model needs minutes, and the old flat 30s cancelled every one of
+ # those before it could return (#1119).
+ answer_text, failure_note = await synthesize(provider, _SYSTEM_PROMPT, user_prompt)
+ if failure_note is not None:
+ return _degraded_payload(
+ reason="synthesis-failed",
+ note=failure_note,
+ hits=hits,
+ fallback_targets=fallback_targets,
+ repository=repository,
+ t0=t0,
)
- answer_text = (response.content or "").strip()
- except Exception as exc:
- _log.warning("get_answer LLM call failed: %s", exc)
- return {
- "answer": "",
- "citations": [],
- "confidence": "low",
- "degraded": "synthesis-failed",
- "fallback_targets": fallback_targets,
- "retrieval": _serialize_hits(hits),
- "note": f"DEGRADED: LLM synthesis failed ({type(exc).__name__}). Read the listed files to answer.",
- "_meta": _build_meta(
- timing_ms=(time.perf_counter() - t0) * 1000,
- hint=_answer_hint("low", len(hits)),
- repository=repository,
- targets=fallback_targets,
- ),
- }
citations = [
h["target_path"] for h in hits if h["target_path"] and h["target_path"] in answer_text
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/config.py b/packages/server/src/repowise/server/mcp_server/tool_answer/config.py
index 3fa351249..34bd967f2 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/config.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/config.py
@@ -452,6 +452,12 @@ _STOPWORDS = frozenset(
# gets truncated; the agent can call get_symbol for the full body.
_MAX_RICH_SIG_LINES = 4
+# Synthesis sampling. Answers target 150-400 words (~550 tokens), so the cap is
+# headroom rather than the binding constraint; generation speed is. Temperature
+# is low because the answer must track the retrieved excerpts, not embellish.
+_SYNTHESIS_MAX_TOKENS = 1024
+_SYNTHESIS_TEMPERATURE = 0.2
+
_SYSTEM_PROMPT = (
"You are a code-aware retrieval assistant. You are given a developer "
"question plus excerpts from a project wiki — file summaries, symbol "
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/synthesis.py b/packages/server/src/repowise/server/mcp_server/tool_answer/synthesis.py
index 941c0db2d..6031ff4d5 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/synthesis.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/synthesis.py
@@ -1,21 +1,41 @@
-"""Provider resolution and cache-key hashing for get_answer.
+"""Provider resolution, synthesis budget, and cache-key hashing for get_answer.
Recovers the LLM provider the user configured for ``repowise init`` so the
-MCP server can synthesise without a separate config, and hashes the question
-for the answer cache.
+MCP server can synthesise without a separate config, decides how long one
+synthesis call may take, and hashes the question for the answer cache.
"""
from __future__ import annotations
+import asyncio
import hashlib
import json as _json
import logging
+import math
import os
from pathlib import Path
-from typing import Any
+
+from repowise.server.mcp_server.tool_answer.config import (
+ _SYNTHESIS_MAX_TOKENS,
+ _SYNTHESIS_TEMPERATURE,
+)
_log = logging.getLogger("repowise.mcp.answer")
+# Escape hatch for the per-provider synthesis budget. Seconds, float.
+_TIMEOUT_ENV = "REPOWISE_ANSWER_TIMEOUT_S"
+# Used only if a provider reports no usable budget of its own. Every
+# BaseProvider subclass inherits one, so this covers a runtime-registered
+# provider that does not subclass it, or one that declares nonsense.
+_FALLBACK_TIMEOUT_S = 30.0
+# Ceiling on any budget, however configured. get_answer is a tool an agent
+# blocks on, and every MCP client enforces its own tool timeout underneath
+# this one, so a longer budget cannot produce an answer the client will still
+# accept. It only converts our diagnosable degraded payload into the client's
+# bare transport error. 600s also matches the agent-CLI providers' own
+# subprocess ceiling, past which raising this is inert anyway.
+_MAX_TIMEOUT_S = 600.0
+
def _hash_question(question: str) -> str:
"""Stable SHA-256 of the normalized question. Lowercase + strip + collapse ws."""
@@ -94,16 +114,25 @@ def _load_repo_provider_config(
def _resolve_provider_for_answer(repo_path: Path | None = None):
"""Best-effort provider lookup mirroring cli/helpers.resolve_provider.
- Avoids the click dependency from the cli package. Returns a BaseProvider
- or None if no API key / provider is configured.
+ Avoids the click dependency from the cli package, but shares that
+ function's env-var mapping (``repowise.core.providers.llm.registry``) so
+ the two cannot drift apart. Returns a BaseProvider or None if no API key /
+ provider is configured.
- Resolution order: process env vars first, then ``.repowise/state.json``
- + ``.repowise/.env`` for the active repo. The persisted values are the
- same ones ``repowise init`` and ``repowise update`` use, so get_answer
- follows the user's existing provider choice without a separate config.
+ Resolution order: process env vars first, then ``.repowise/config.yaml``
+ / ``state.json`` + ``.repowise/.env`` for the active repo. The persisted
+ values are the same ones ``repowise init`` and ``repowise update`` use, so
+ get_answer follows the user's existing provider choice without a separate
+ config.
"""
try:
- from repowise.core.providers.llm.registry import get_provider
+ from repowise.core.providers.llm.registry import (
+ PROVIDER_AUTODETECT_ORDER,
+ get_provider,
+ provider_credentials_present,
+ provider_is_usable,
+ provider_kwargs,
+ )
except Exception:
_log.warning("Provider registry import failed", exc_info=True)
return None
@@ -120,29 +149,19 @@ def _resolve_provider_for_answer(repo_path: Path | None = None):
os.environ.get("REPOWISE_DOC_MODEL") or os.environ.get("REPOWISE_MODEL") or persisted_model
)
- def _try(provider_name: str, **kwargs: Any):
+ def _try(provider_name: str, provider_model: str | None):
+ kwargs = provider_kwargs(
+ provider_name,
+ model=provider_model,
+ repo_path=repo_path,
+ getenv=_env,
+ )
try:
return get_provider(provider_name, **kwargs)
except Exception:
_log.warning("get_provider(%s) failed", provider_name, exc_info=True)
return None
- def _resolve_base_url(provider_name: str) -> str | None:
- mapping = {
- "openai": ["OPENAI_BASE_URL"],
- "anthropic": ["ANTHROPIC_BASE_URL"],
- "gemini": ["GEMINI_BASE_URL"],
- "deepseek": ["DEEPSEEK_BASE_URL"],
- "kimi": ["KIMI_BASE_URL"],
- "ollama": ["OLLAMA_BASE_URL"],
- "litellm": ["LITELLM_BASE_URL", "LITELLM_API_BASE"],
- }
- for env_var in mapping.get(provider_name, []):
- val = _env(env_var)
- if val:
- return val
- return None
-
# Explicit selection wins — when its key is actually available. A
# configured/persisted provider whose key is absent must NOT end
# resolution: returning None here made get_answer silently drop to
@@ -150,26 +169,9 @@ def _resolve_provider_for_answer(repo_path: Path | None = None):
# (the auto-detect below was unreachable). Fall through instead, and
# drop the persisted model on the way down — it belongs to the named
# provider and would break a cross-provider fallback call.
- _KEY_ENVS = {
- "anthropic": ("ANTHROPIC_API_KEY",),
- "openai": ("OPENAI_API_KEY",),
- "deepseek": ("DEEPSEEK_API_KEY",),
- "kimi": ("KIMI_API_KEY",),
- "gemini": ("GEMINI_API_KEY", "GOOGLE_API_KEY"),
- }
if name:
- key_envs = _KEY_ENVS.get(name)
- key = next((v for v in map(_env, key_envs or ()) if v), None)
- if key_envs is None or key:
- kw: dict[str, Any] = {}
- if model:
- kw["model"] = model
- if key:
- kw["api_key"] = key
- base_url = _resolve_base_url(name)
- if base_url:
- kw["base_url"] = base_url
- provider = _try(name, **kw)
+ if provider_is_usable(name, _env):
+ provider = _try(name, model)
if provider is not None:
return provider
_log.warning(
@@ -180,50 +182,152 @@ def _resolve_provider_for_answer(repo_path: Path | None = None):
if not (os.environ.get("REPOWISE_DOC_MODEL") or os.environ.get("REPOWISE_MODEL")):
model = None # persisted model was provider-specific
- # Auto-detect from API keys.
- if _env("ANTHROPIC_API_KEY"):
- kw = {"api_key": _env("ANTHROPIC_API_KEY")}
- if model:
- kw["model"] = model
- base_url = _resolve_base_url("anthropic")
- if base_url:
- kw["base_url"] = base_url
- return _try("anthropic", **kw)
- if _env("OPENAI_API_KEY"):
- kw = {"api_key": _env("OPENAI_API_KEY")}
- if model:
- kw["model"] = model
- base_url = _resolve_base_url("openai")
- if base_url:
- kw["base_url"] = base_url
- return _try("openai", **kw)
- if _env("GEMINI_API_KEY") or _env("GOOGLE_API_KEY"):
- kw = {"api_key": _env("GEMINI_API_KEY") or _env("GOOGLE_API_KEY")}
- if model:
- kw["model"] = model
- base_url = _resolve_base_url("gemini")
- if base_url:
- kw["base_url"] = base_url
- return _try("gemini", **kw)
- if _env("OLLAMA_BASE_URL"):
- kw = {"base_url": _env("OLLAMA_BASE_URL")}
- if model:
- kw["model"] = model
- return _try("ollama", **kw)
- if _env("DEEPSEEK_API_KEY"):
- kw = {"api_key": _env("DEEPSEEK_API_KEY")}
- if model:
- kw["model"] = model
- base_url = _resolve_base_url("deepseek")
- if base_url:
- kw["base_url"] = base_url
- return _try("deepseek", **kw)
- if _env("KIMI_API_KEY"):
- kw = {"api_key": _env("KIMI_API_KEY")}
- if model:
- kw["model"] = model
- base_url = _resolve_base_url("kimi")
- if base_url:
- kw["base_url"] = base_url
- return _try("kimi", **kw)
+ # Auto-detect from whatever credentials the environment carries. Only the
+ # keyed providers participate: a keyless one is "usable" everywhere, so
+ # auto-detecting it would hijack every repo that never configured it.
+ for candidate in PROVIDER_AUTODETECT_ORDER:
+ if candidate == name:
+ # Already attempted above with the same credentials. Retrying it
+ # here only differs in dropping the model, which cannot fix the
+ # reasons construction fails (a missing SDK, a rejected key), and
+ # it costs the next candidate its turn.
+ continue
+ if not provider_credentials_present(candidate, _env):
+ continue
+ provider = _try(candidate, model)
+ if provider is not None:
+ return provider
return None
+
+
+def _usable_seconds(value: object) -> float | None:
+ """``value`` as a usable budget in seconds, clamped, or None if unusable.
+
+ Rejects bools (``float(True)`` would be a silent 1-second budget), NaN, and
+ anything non-positive. Infinity is clamped rather than rejected: it means
+ "no limit", and ``asyncio.wait_for`` honours that literally by never firing,
+ which is the one outcome this function exists to prevent.
+ """
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ return None
+ number = float(value)
+ if math.isnan(number) or number <= 0:
+ return None
+ return min(number, _MAX_TIMEOUT_S)
+
+
+def _synthesis_timeout(provider) -> float:
+ """Wall-clock budget for one synthesis call, in seconds.
+
+ Defaults to the provider's own ``interactive_timeout_s``. A remote API
+ answers in seconds, an agent-CLI subprocess or a local model needs minutes,
+ and a single hardcoded number cancels the second group on every call
+ (issue #1119). ``REPOWISE_ANSWER_TIMEOUT_S`` overrides it for the cases no
+ default can predict: a slow proxy, an overloaded self-hosted box, an agent
+ harness that would rather fail fast.
+
+ Every input here is untrusted. The env var is user-typed, and the provider
+ attribute belongs to a possibly runtime-registered class that need not
+ subclass BaseProvider, so a bad value must degrade to a working default
+ rather than raise out of a function whose caller is not expecting it to.
+ """
+ raw = (os.environ.get(_TIMEOUT_ENV) or "").strip()
+ if raw:
+ try:
+ override = _usable_seconds(float(raw))
+ except ValueError:
+ override = None
+ if override is not None:
+ return override
+ _log.warning("Ignoring unusable %s=%r", _TIMEOUT_ENV, raw)
+
+ declared = _usable_seconds(getattr(provider, "interactive_timeout_s", None))
+ return _FALLBACK_TIMEOUT_S if declared is None else declared
+
+
+def _synthesis_failure_note(exc: BaseException, provider, timeout_s: float, timed_out: bool) -> str:
+ """Human-readable ``note`` for a synthesis failure.
+
+ Names the provider and model that failed and, when we cancelled the call,
+ the budget it blew and the knob that raises it. The old note carried only
+ the exception class, which collapsed "your agent CLI needs 90s" and "your
+ key is rate limited" into an identical, unactionable ``TimeoutError``
+ (#1119).
+
+ ``timed_out`` is passed in rather than sniffed off ``exc``: builtin
+ ``TimeoutError`` is an ``OSError`` subclass and is what a bare socket
+ timeout raises, so type-testing would offer "raise your budget" for a
+ connection that died in ten seconds.
+ """
+ who = (
+ f"provider={getattr(provider, 'provider_name', None) or '?'}, "
+ f"model={getattr(provider, 'model_name', None) or '?'}"
+ )
+ if timed_out:
+ headroom = ""
+ if timeout_s < _MAX_TIMEOUT_S:
+ headroom = f" Raise it with {_TIMEOUT_ENV}=<seconds> (your MCP client's own tool timeout still applies), or"
+ return (
+ f"DEGRADED: LLM synthesis exceeded its {timeout_s:g}s budget ({who})."
+ f"{headroom} switch to a faster provider. Read the listed files to "
+ "answer meanwhile."
+ )
+ detail = " ".join(str(exc).split())[:200]
+ suffix = f": {detail}" if detail else ""
+ return (
+ f"DEGRADED: LLM synthesis failed ({type(exc).__name__}{suffix}) "
+ f"[{who}]. Read the listed files to answer."
+ )
+
+
+async def synthesize(provider, system_prompt: str, user_prompt: str) -> tuple[str, str | None]:
+ """Run one synthesis call. Returns ``(answer_text, failure_note)``.
+
+ ``failure_note`` is None on success. Owning the budget, the call and the
+ error message together is what keeps them consistent: the budget that
+ cancelled the call is the number the note quotes, and a caller cannot wire
+ up the call while forgetting the budget (which is how #1119 survived a
+ hardcoded 30s for as long as it did).
+ """
+ timeout_s = _synthesis_timeout(provider)
+
+ async def _generate() -> tuple[object | None, BaseException | None]:
+ """Swallow the provider's own errors so only our deadline escapes.
+
+ Without this, a provider raising builtin ``TimeoutError`` (which is
+ what a bare socket timeout raises, since it subclasses ``OSError``)
+ would be indistinguishable from the deadline we set, and the note would
+ tell the user to raise a budget that had nothing to do with it.
+ """
+ try:
+ return (
+ await provider.generate(
+ system_prompt=system_prompt,
+ user_prompt=user_prompt,
+ max_tokens=_SYNTHESIS_MAX_TOKENS,
+ temperature=_SYNTHESIS_TEMPERATURE,
+ ),
+ None,
+ )
+ except Exception as exc:
+ return None, exc
+
+ timed_out = False
+ try:
+ response, failure = await asyncio.wait_for(_generate(), timeout=timeout_s)
+ except TimeoutError as exc:
+ # Only wait_for can reach here now, so the label is earned.
+ timed_out = True
+ response, failure = None, exc
+ if failure is None:
+ return (getattr(response, "content", None) or "").strip(), None
+
+ _log.warning(
+ "get_answer LLM call failed (provider=%s, model=%s, budget=%.1fs, timed_out=%s): %s",
+ getattr(provider, "provider_name", "?"),
+ getattr(provider, "model_name", "?"),
+ timeout_s,
+ timed_out,
+ failure,
+ )
+ return "", _synthesis_failure_note(failure, provider, timeout_s, timed_out)
diff --git a/packages/server/src/repowise/server/provider_config.py b/packages/server/src/repowise/server/provider_config.py
index 9eb1d8e55..72461b740 100644
--- a/packages/server/src/repowise/server/provider_config.py
+++ b/packages/server/src/repowise/server/provider_config.py
@@ -110,7 +110,10 @@ PROVIDER_CATALOG: list[dict[str, Any]] = [
"name": "LiteLLM",
"default_model": "groq/llama-3.1-70b-versatile",
"models": ["groq/llama-3.1-70b-versatile"],
- "env_keys": [],
+ # 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,
},
{
@@ -175,17 +178,6 @@ def _save_config(config: dict[str, Any]) -> None:
# ---------------------------------------------------------------------------
-_BASE_URL_ENV_VARS = {
- "anthropic": ["ANTHROPIC_BASE_URL"],
- "openai": ["OPENAI_BASE_URL"],
- "gemini": ["GEMINI_BASE_URL"],
- "ollama": ["OLLAMA_BASE_URL"],
- "deepseek": ["DEEPSEEK_BASE_URL"],
- "kimi": ["KIMI_BASE_URL"],
- "litellm": ["LITELLM_BASE_URL", "LITELLM_API_BASE"],
-}
-
-
def _load_repo_context(repo_path: str | Path | None) -> tuple[dict[str, Any], dict[str, str]]:
"""Load a repo's ``config.yaml`` dict and ``.env`` dict for resolution.
@@ -247,8 +239,13 @@ def _get_base_url_for_provider(
local LiteLLM/OpenAI-compatible endpoint configured at init is reused by
chat. The repo ``config.yaml`` may carry it under a per-provider section,
e.g. ``openai: {base_url: http://localhost:4000/v1}``.
+
+ The env-var names come from the provider registry, the same table the CLI
+ and MCP resolvers read, so this cannot drift out of step with them.
"""
- env_vars = _BASE_URL_ENV_VARS.get(provider_id, [])
+ from repowise.core.providers.llm.registry import PROVIDER_BASE_URL_ENVS
+
+ env_vars = PROVIDER_BASE_URL_ENVS.get(provider_id, ())
for env_var in env_vars:
val = os.environ.get(env_var)
if val:
diff --git a/tests/unit/server/mcp/test_answer_synthesis_timeout.py b/tests/unit/server/mcp/test_answer_synthesis_timeout.py
new file mode 100644
index 000000000..f2573a66f
--- /dev/null
+++ b/tests/unit/server/mcp/test_answer_synthesis_timeout.py
@@ -0,0 +1,381 @@
+"""get_answer's synthesis budget and its failure reporting.
+
+Issue #1119: the budget was a hardcoded 30s. Providers that shell out to a
+coding-agent CLI or drive a local model take longer than that on every call, so
+synthesis was cancelled every single time and the user got an empty payload
+whose only clue was the string "TimeoutError". Retrieval looked healthy, which
+sent the diagnosis toward the index instead of the provider.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+from repowise.core.providers.llm.registry import _BUILTIN_PROVIDERS, get_provider
+from repowise.server.mcp_server.tool_answer import synthesis as synthesis_module
+from repowise.server.mcp_server.tool_answer.answer import _degraded_payload
+from repowise.server.mcp_server.tool_answer.config import (
+ _SYNTHESIS_MAX_TOKENS,
+ _SYNTHESIS_TEMPERATURE,
+)
+from repowise.server.mcp_server.tool_answer.synthesis import (
+ _FALLBACK_TIMEOUT_S,
+ _MAX_TIMEOUT_S,
+ _TIMEOUT_ENV,
+ _synthesis_failure_note,
+ _synthesis_timeout,
+ synthesize,
+)
+
+
+class _Provider:
+ """Stand-in for a resolved provider; only the read attributes matter."""
+
+ def __init__(self, budget=None, name="testprov", model="test-model"):
+ if budget is not None:
+ self.interactive_timeout_s = budget
+ self.provider_name = name
+ self.model_name = model
+
+
[email protected](autouse=True)
+def _no_override(monkeypatch):
+ monkeypatch.delenv(_TIMEOUT_ENV, raising=False)
+
+
+# --- budget selection ------------------------------------------------------
+
+
+def test_budget_comes_from_the_provider():
+ assert _synthesis_timeout(_Provider(budget=180.0)) == 180.0
+
+
+def test_provider_without_a_budget_gets_the_fallback():
+ """A runtime-registered provider need not subclass BaseProvider."""
+ assert _synthesis_timeout(_Provider(budget=None)) == _FALLBACK_TIMEOUT_S
+
+
+def test_env_override_beats_the_provider_default(monkeypatch):
+ monkeypatch.setenv(_TIMEOUT_ENV, "5")
+ assert _synthesis_timeout(_Provider(budget=180.0)) == 5.0
+
+
+def test_env_override_may_lower_the_budget_to_fail_fast(monkeypatch):
+ """An agent harness would rather give up early than block on a slow box."""
+ monkeypatch.setenv(_TIMEOUT_ENV, "2.5")
+ assert _synthesis_timeout(_Provider(budget=120.0)) == 2.5
+
+
[email protected]("bad", ["", " ", "abc", "30s", "0", "-1", "nan_but_not", "nan", "-inf"])
+def test_unusable_override_falls_back_to_the_provider_default(monkeypatch, bad):
+ monkeypatch.setenv(_TIMEOUT_ENV, bad)
+ assert _synthesis_timeout(_Provider(budget=180.0)) == 180.0
+
+
[email protected]("huge", ["inf", "1e400", "999999"])
+def test_an_effectively_unbounded_override_is_clamped(monkeypatch, huge):
+ """asyncio.wait_for accepts inf and then never fires, disabling the guard.
+
+ An unbounded budget cannot produce an answer either: the MCP client gives
+ up first, and get_answer blocks until someone kills the server.
+ """
+ monkeypatch.setenv(_TIMEOUT_ENV, huge)
+ assert _synthesis_timeout(_Provider(budget=180.0)) == _MAX_TIMEOUT_S
+
+
[email protected]("junk", ["abc", True, False, object(), -5, 0, float("nan")], ids=repr)
+def test_a_provider_declaring_junk_falls_back_instead_of_raising(junk):
+ """The attribute belongs to a class that need not subclass BaseProvider.
+
+ float("abc") would raise out of a call the caller does not guard, turning
+ a degraded answer into a failed tool call.
+ """
+ assert _synthesis_timeout(_Provider(budget=junk)) == _FALLBACK_TIMEOUT_S
+
+
[email protected]("excessive", [99_999.0, float("inf")])
+def test_a_provider_budget_above_the_ceiling_is_clamped(excessive):
+ assert _synthesis_timeout(_Provider(budget=excessive)) == _MAX_TIMEOUT_S
+
+
+# --- the regression itself -------------------------------------------------
+
+
[email protected]("name", ["codex_cli", "opencode"])
+def test_agent_cli_providers_get_more_than_the_old_thirty_seconds(name):
+ """#1119: 30s cancelled a codex/opencode turn before it could ever return."""
+ cls = _load_provider_class(name)
+ assert cls.interactive_timeout_s > 30.0
+
+
[email protected]("name", ["ollama", "litellm"])
+def test_local_and_proxied_providers_get_more_than_thirty_seconds(name):
+ """Generation speed is the user's own hardware, or an unknown backend."""
+ cls = _load_provider_class(name)
+ assert cls.interactive_timeout_s > 30.0
+
+
+def test_every_builtin_provider_has_a_deliberate_budget():
+ """Adding a provider forces a choice about how slow it is allowed to be.
+
+ Inheriting the remote-API default silently is what this table prevents:
+ that is exactly what codex_cli did, and it is why #1119 existed.
+ """
+ expected = {
+ "anthropic": 60.0,
+ "openai": 60.0,
+ "openrouter": 60.0,
+ "gemini": 60.0,
+ "deepseek": 60.0,
+ "kimi": 60.0,
+ "mock": 60.0,
+ "ollama": 120.0,
+ "litellm": 120.0,
+ "codex_cli": 180.0,
+ "opencode": 180.0,
+ }
+ assert set(expected) == set(_BUILTIN_PROVIDERS), (
+ "a provider was added or removed; decide its interactive budget here"
+ )
+ actual = {name: _load_provider_class(name).interactive_timeout_s for name in expected}
+ assert actual == expected
+
+
+def test_agent_cli_budget_stays_under_its_own_subprocess_ceiling():
+ """The caller must give up before the subprocess does, or the error is wrong."""
+ from repowise.core.providers.llm import codex_cli, opencode
+
+ assert codex_cli.CodexCliProvider.interactive_timeout_s < codex_cli._EXEC_TIMEOUT_SECONDS
+ assert opencode.OpenCodeProvider.interactive_timeout_s < opencode._EXEC_TIMEOUT_SECONDS
+
+
+def _load_provider_class(name: str):
+ import importlib
+
+ module_path, class_name = _BUILTIN_PROVIDERS[name]
+ return getattr(importlib.import_module(module_path), class_name)
+
+
+# --- failure reporting -----------------------------------------------------
+
+
+def test_timeout_note_names_the_budget_the_provider_and_the_escape_hatch():
+ note = _synthesis_failure_note(
+ TimeoutError(),
+ _Provider(budget=180.0, name="codex_cli", model="gpt-5.5"),
+ 180.0,
+ timed_out=True,
+ )
+ assert "180s" in note
+ assert "codex_cli" in note and "gpt-5.5" in note
+ assert _TIMEOUT_ENV in note
+ assert note.startswith("DEGRADED:")
+
+
+def test_timeout_note_warns_that_the_client_has_its_own_timeout():
+ """Raising ours past the client's just swaps a good error for a worse one."""
+ note = _synthesis_failure_note(TimeoutError(), _Provider(), 180.0, timed_out=True)
+ assert "client" in note.lower()
+
+
+def test_timeout_note_stops_advertising_the_knob_once_it_is_maxed():
+ """At the ceiling, "raise it" is advice that cannot be followed."""
+ note = _synthesis_failure_note(TimeoutError(), _Provider(), _MAX_TIMEOUT_S, timed_out=True)
+ assert _TIMEOUT_ENV not in note
+ assert "faster provider" in note
+
+
+def test_non_timeout_note_carries_the_real_error_not_just_its_class():
+ """A 401 and a rate limit used to be indistinguishable from a slow model."""
+ note = _synthesis_failure_note(
+ ValueError("invalid x-api-key"), _Provider(name="anthropic"), 60.0, timed_out=False
+ )
+ assert "ValueError" in note
+ assert "invalid x-api-key" in note
+ assert _TIMEOUT_ENV not in note # raising the budget would not help here
+
+
+def test_note_collapses_and_truncates_a_sprawling_provider_error():
+ note = _synthesis_failure_note(
+ RuntimeError("line one\n\n line two " * 200), _Provider(), 60.0, timed_out=False
+ )
+ assert "\n" not in note
+ assert len(note) < 400
+
+
+def test_note_survives_a_provider_missing_its_identity_attributes():
+ class _Bare:
+ pass
+
+ note = _synthesis_failure_note(TimeoutError(), _Bare(), 60.0, timed_out=True)
+ assert "provider=?" in note and "model=?" in note
+
+
+def test_note_renders_a_whole_number_budget_without_a_trailing_zero():
+ note = _synthesis_failure_note(TimeoutError(), _Provider(), 30.0, timed_out=True)
+ assert "30s" in note and "30.0s" not in note
+
+
+def test_real_provider_instance_reports_its_class_budget():
+ """The attribute survives instantiation through the registry."""
+ provider = get_provider("mock", with_rate_limiter=False)
+ assert _synthesis_timeout(provider) == 60.0
+
+
+# --- the wiring: the budget must reach the actual call ---------------------
+#
+# The tests above pin the ingredients. These pin the dish: revert synthesize()
+# to a hardcoded timeout and they fail. Without them the class attributes are
+# decoration and #1119 can come back while everything still looks fixed.
+
+
+class _SlowProvider:
+ """Takes `duration` seconds to answer, however long the caller allows."""
+
+ provider_name = "slowprov"
+ model_name = "slow-model"
+
+ def __init__(self, duration: float, budget: float):
+ self._duration = duration
+ self.interactive_timeout_s = budget
+ self.calls: list[dict] = []
+
+ async def generate(self, **kwargs):
+ self.calls.append(kwargs)
+ await asyncio.sleep(self._duration)
+ return SimpleNamespace(content=" the answer ")
+
+
+async def test_the_call_is_budgeted_with_the_providers_own_number(monkeypatch):
+ """A codex-class provider must not be cancelled at the remote-API default."""
+ seen: dict = {}
+ real_wait_for = asyncio.wait_for
+
+ async def _spy(coro, timeout):
+ seen["timeout"] = timeout
+ return await real_wait_for(coro, timeout)
+
+ monkeypatch.setattr(synthesis_module.asyncio, "wait_for", _spy)
+
+ provider = _SlowProvider(duration=0, budget=180.0)
+ answer, note = await synthesize(provider, "sys", "user")
+
+ assert seen["timeout"] == 180.0, "the flat 30s is back"
+ assert answer == "the answer"
+ assert note is None
+
+
+async def test_a_provider_slower_than_its_budget_degrades_with_a_useful_note():
+ """The #1119 shape end to end, at 1/1000th the wall clock."""
+ provider = _SlowProvider(duration=5.0, budget=0.01)
+
+ answer, note = await synthesize(provider, "sys", "user")
+
+ assert answer == ""
+ assert note is not None
+ assert "slowprov" in note and "slow-model" in note
+ assert _TIMEOUT_ENV in note
+ assert "budget" in note
+
+
+async def test_the_env_override_reaches_the_call(monkeypatch):
+ seen: dict = {}
+ real_wait_for = asyncio.wait_for
+
+ async def _spy(coro, timeout):
+ seen["timeout"] = timeout
+ return await real_wait_for(coro, timeout)
+
+ monkeypatch.setattr(synthesis_module.asyncio, "wait_for", _spy)
+ monkeypatch.setenv(_TIMEOUT_ENV, "7.5")
+
+ await synthesize(_SlowProvider(duration=0, budget=180.0), "sys", "user")
+ assert seen["timeout"] == 7.5
+
+
+async def test_prompts_and_sampling_are_passed_through_unchanged():
+ provider = _SlowProvider(duration=0, budget=30.0)
+ await synthesize(provider, "the system prompt", "the user prompt")
+
+ assert provider.calls[0] == {
+ "system_prompt": "the system prompt",
+ "user_prompt": "the user prompt",
+ "max_tokens": _SYNTHESIS_MAX_TOKENS,
+ "temperature": _SYNTHESIS_TEMPERATURE,
+ }
+
+
+async def test_a_non_timeout_failure_is_not_reported_as_a_budget_overrun():
+ """A socket timeout IS a builtin TimeoutError, so sniffing the type lies."""
+
+ class _Broken(_SlowProvider):
+ async def generate(self, **kwargs):
+ raise TimeoutError("connection timed out after 3s")
+
+ answer, note = await synthesize(_Broken(duration=0, budget=180.0), "sys", "user")
+
+ assert answer == ""
+ assert "connection timed out after 3s" in note
+ assert "exceeded its" not in note
+ assert _TIMEOUT_ENV not in note
+
+
+async def test_an_empty_completion_is_not_mistaken_for_a_failure():
+ class _Empty(_SlowProvider):
+ async def generate(self, **kwargs):
+ return SimpleNamespace(content=None)
+
+ answer, note = await synthesize(_Empty(duration=0, budget=30.0), "sys", "user")
+ assert answer == ""
+ assert note is None
+
+
+# --- the degraded payload both failure modes share -------------------------
+
+HITS = [{"target_path": "pkg/mod.py", "title": "mod", "summary": "s", "score": 1.0}]
+
+
+def _payload(reason="synthesis-failed", note="DEGRADED: boom"):
+ return _degraded_payload(
+ reason=reason,
+ note=note,
+ hits=HITS,
+ fallback_targets=["pkg/mod.py"],
+ repository=None,
+ t0=0.0,
+ )
+
+
+def test_degraded_reason_is_mirrored_into_meta():
+ """The failure path set only the top-level key, so _meta watchers missed it."""
+ payload = _payload()
+ assert payload["degraded"] == "synthesis-failed"
+ assert payload["_meta"]["degraded"] == "synthesis-failed"
+
+
[email protected]("reason", ["no-llm-provider", "synthesis-failed"])
+def test_both_failure_modes_return_the_same_payload_shape(reason):
+ """An agent should not have to diff key sets to tell why synthesis is missing."""
+ assert set(_payload(reason=reason)) == {
+ "answer",
+ "citations",
+ "confidence",
+ "degraded",
+ "fallback_targets",
+ "retrieval",
+ "note",
+ "_meta",
+ }
+
+
+def test_degraded_payload_still_hands_back_usable_retrieval():
+ """Retrieval succeeded; losing it too would waste the work already done."""
+ payload = _payload()
+ assert payload["answer"] == ""
+ assert payload["confidence"] == "low"
+ assert payload["fallback_targets"] == ["pkg/mod.py"]
+ assert len(payload["retrieval"]) == 1
+ assert payload["retrieval"][0]["path"] == "pkg/mod.py"
diff --git a/tests/unit/server/mcp/test_provider_resolution.py b/tests/unit/server/mcp/test_provider_resolution.py
index 68ce68e9e..dc32fb681 100644
--- a/tests/unit/server/mcp/test_provider_resolution.py
+++ b/tests/unit/server/mcp/test_provider_resolution.py
@@ -21,10 +21,19 @@ from repowise.server.mcp_server.tool_answer.synthesis import (
@pytest.fixture(autouse=True)
def _clean_env(monkeypatch):
- for var in ("REPOWISE_PROVIDER", "REPOWISE_DOC_MODEL", "REPOWISE_MODEL",
- "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY",
- "GOOGLE_API_KEY", "DEEPSEEK_API_KEY", "KIMI_API_KEY",
- "OLLAMA_BASE_URL", "OPENAI_BASE_URL"):
+ for var in (
+ "REPOWISE_PROVIDER",
+ "REPOWISE_DOC_MODEL",
+ "REPOWISE_MODEL",
+ "OPENAI_API_KEY",
+ "ANTHROPIC_API_KEY",
+ "GEMINI_API_KEY",
+ "GOOGLE_API_KEY",
+ "DEEPSEEK_API_KEY",
+ "KIMI_API_KEY",
+ "OLLAMA_BASE_URL",
+ "OPENAI_BASE_URL",
+ ):
monkeypatch.delenv(var, raising=False)
@@ -33,7 +42,8 @@ def _write_repo(tmp_path, *, config=None, state=None):
d.mkdir(parents=True, exist_ok=True)
if config is not None:
(d / "config.yaml").write_text(
- "\n".join(f"{k}: {v}" for k, v in config.items()), encoding="utf-8")
+ "\n".join(f"{k}: {v}" for k, v in config.items()), encoding="utf-8"
+ )
if state is not None:
(d / "state.json").write_text(_json.dumps(state), encoding="utf-8")
return tmp_path
@@ -52,8 +62,11 @@ def test_config_yaml_outranks_state_json(tmp_path):
def test_state_json_still_used_when_config_lacks_provider(tmp_path):
- repo = _write_repo(tmp_path, config={"commit_limit": 200},
- state={"provider": "openai", "model": "gpt-5.4-nano"})
+ repo = _write_repo(
+ tmp_path,
+ config={"commit_limit": 200},
+ state={"provider": "openai", "model": "gpt-5.4-nano"},
+ )
name, model, _ = _load_repo_provider_config(repo)
assert name == "openai"
assert model == "gpt-5.4-nano"
@@ -61,8 +74,7 @@ def test_state_json_still_used_when_config_lacks_provider(tmp_path):
def test_keyless_persisted_provider_falls_back_to_available_key(tmp_path, monkeypatch):
"""gemini persisted, only OPENAI_API_KEY present -> openai provider, not None."""
- repo = _write_repo(tmp_path,
- state={"provider": "gemini", "model": "gemini-3.1-flash"})
+ repo = _write_repo(tmp_path, state={"provider": "gemini", "model": "gemini-3.1-flash"})
monkeypatch.setenv("OPENAI_API_KEY", "sk-test")
provider = _resolve_provider_for_answer(repo)
assert provider is not None
@@ -83,3 +95,87 @@ def test_explicit_env_provider_still_wins(tmp_path, monkeypatch):
provider = _resolve_provider_for_answer(repo)
assert provider is not None
assert getattr(provider, "provider_name", "") == "openai"
+
+
+def _record_get_provider(monkeypatch):
+ """Capture the kwargs resolution hands to the registry."""
+ from repowise.core.providers.llm import registry
+
+ seen: dict = {}
+
+ def _fake(name, **kwargs):
+ seen["name"] = name
+ seen["kwargs"] = kwargs
+ return object()
+
+ monkeypatch.setattr(registry, "get_provider", _fake)
+ return seen
+
+
+def test_agent_cli_provider_is_told_which_repo_to_run_in(tmp_path, monkeypatch):
+ """#1119: codex exec inherited the MCP server's cwd, not the user's repo.
+
+ For a server launched by an editor that is some arbitrary directory, so the
+ CLI reasoned about the wrong tree (when it ran at all).
+ """
+ repo = _write_repo(tmp_path, config={"provider": "codex_cli"})
+ seen = _record_get_provider(monkeypatch)
+
+ assert _resolve_provider_for_answer(repo) is not None
+ assert seen["name"] == "codex_cli"
+ assert seen["kwargs"]["repo_path"] == repo
+
+
+def test_keyless_provider_resolves_without_any_api_key(tmp_path, monkeypatch):
+ """codex_cli authenticates out of band; a missing key is not a reason to skip it."""
+ repo = _write_repo(tmp_path, config={"provider": "opencode"})
+ seen = _record_get_provider(monkeypatch)
+
+ assert _resolve_provider_for_answer(repo) is not None
+ assert seen["name"] == "opencode"
+
+
+def test_repo_path_is_not_forwarded_to_an_http_provider(tmp_path, monkeypatch):
+ """AnthropicProvider has no repo_path parameter; passing it would TypeError."""
+ repo = _write_repo(tmp_path, config={"provider": "anthropic"})
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-test")
+ seen = _record_get_provider(monkeypatch)
+
+ assert _resolve_provider_for_answer(repo) is not None
+ assert "repo_path" not in seen["kwargs"]
+
+
+def test_env_file_key_is_used_when_the_process_env_has_none(tmp_path, monkeypatch):
+ """The MCP server is not launched from the shell that ran `repowise init`."""
+ repo = _write_repo(tmp_path, config={"provider": "openai"})
+ (repo / ".repowise" / ".env").write_text('OPENAI_API_KEY="sk-from-dotenv"', encoding="utf-8")
+ seen = _record_get_provider(monkeypatch)
+
+ assert _resolve_provider_for_answer(repo) is not None
+ assert seen["kwargs"]["api_key"] == "sk-from-dotenv"
+
+
+def test_process_env_key_outranks_the_env_file(tmp_path, monkeypatch):
+ repo = _write_repo(tmp_path, config={"provider": "openai"})
+ (repo / ".repowise" / ".env").write_text("OPENAI_API_KEY=sk-from-dotenv", encoding="utf-8")
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-from-shell")
+ seen = _record_get_provider(monkeypatch)
+
+ assert _resolve_provider_for_answer(repo) is not None
+ assert seen["kwargs"]["api_key"] == "sk-from-shell"
+
+
+def test_autodetect_does_not_pick_a_keyless_provider_out_of_thin_air(tmp_path):
+ """No config, no keys: a keyless provider must not be silently assumed."""
+ repo = _write_repo(tmp_path)
+ assert _resolve_provider_for_answer(repo) is None
+
+
+def test_openrouter_key_alone_now_resolves(tmp_path, monkeypatch):
+ """Auto-detection skipped openrouter entirely, so those users got no synthesis."""
+ repo = _write_repo(tmp_path)
+ monkeypatch.setenv("OPENROUTER_API_KEY", "sk-or-test")
+ seen = _record_get_provider(monkeypatch)
+
+ assert _resolve_provider_for_answer(repo) is not None
+ assert seen["name"] == "openrouter"
diff --git a/tests/unit/test_providers/test_provider_env_registry.py b/tests/unit/test_providers/test_provider_env_registry.py
new file mode 100644
index 000000000..942561aa2
--- /dev/null
+++ b/tests/unit/test_providers/test_provider_env_registry.py
@@ -0,0 +1,223 @@
+"""The shared per-provider environment mapping in the provider registry.
+
+These are the maps the CLI and the MCP server both resolve through. They used
+to be hand-copied into each caller, which is how the MCP server ended up
+resolving a keyless agent-CLI provider without telling it which repo to run in
+(issue #1119). The drift guards below fail when a provider is added to the
+registry table but not wired into the mapping beside it.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.providers.llm.registry import (
+ _BUILTIN_PROVIDERS,
+ KEYLESS_PROVIDERS,
+ PROVIDER_API_KEY_ENVS,
+ PROVIDER_AUTODETECT_ORDER,
+ PROVIDER_BASE_URL_ENVS,
+ REPO_PATH_PROVIDERS,
+ provider_credentials_present,
+ provider_is_usable,
+ provider_kwargs,
+ provider_required_envs,
+)
+
+# --- drift guards ----------------------------------------------------------
+
+
+def test_every_builtin_provider_declares_how_it_authenticates():
+ """A provider either names a key env or is explicitly keyless. No silent third case."""
+ undeclared = {
+ name
+ for name in _BUILTIN_PROVIDERS
+ if name not in PROVIDER_API_KEY_ENVS and name not in KEYLESS_PROVIDERS
+ }
+ assert not undeclared, (
+ f"providers {sorted(undeclared)} are in _BUILTIN_PROVIDERS but declare neither an "
+ "API-key env var nor membership in KEYLESS_PROVIDERS; resolution cannot reason "
+ "about them"
+ )
+
+
+ "mapping",
+ [PROVIDER_API_KEY_ENVS, PROVIDER_BASE_URL_ENVS],
+ ids=["api_key_envs", "base_url_envs"],
+)
+def test_env_maps_only_name_real_providers(mapping):
+ unknown = set(mapping) - set(_BUILTIN_PROVIDERS)
+ assert not unknown, f"env map names providers that do not exist: {sorted(unknown)}"
+
+
+ "collection",
+ [KEYLESS_PROVIDERS, REPO_PATH_PROVIDERS, set(PROVIDER_AUTODETECT_ORDER)],
+ ids=["keyless", "repo_path", "autodetect"],
+)
+def test_provider_sets_only_name_real_providers(collection):
+ unknown = set(collection) - set(_BUILTIN_PROVIDERS)
+ assert not unknown, f"names providers that do not exist: {sorted(unknown)}"
+
+
+def test_autodetect_never_guesses_a_keyless_provider():
+ """Auto-detect picks a provider from credentials the user set.
+
+ A keyless provider is usable in every environment, so including one here
+ would hijack every repo that never asked for it.
+ """
+ for name in PROVIDER_AUTODETECT_ORDER:
+ assert provider_required_envs(name), (
+ f"{name} is in the auto-detect order but needs no env var, so it would "
+ "match unconditionally"
+ )
+
+
+def test_autodetect_order_has_no_duplicates():
+ assert len(PROVIDER_AUTODETECT_ORDER) == len(set(PROVIDER_AUTODETECT_ORDER))
+
+
+def test_every_provider_that_can_be_auto_detected_is_in_the_order():
+ """A keyed provider left out of the tuple is silently unreachable.
+
+ That was the openrouter bug: the MCP server carried a key mapping for it
+ but never listed it among the candidates, so an OPENROUTER_API_KEY-only
+ environment got no synthesis at all.
+ """
+ detectable = {
+ name
+ for name in _BUILTIN_PROVIDERS
+ if provider_required_envs(name) and name not in KEYLESS_PROVIDERS
+ }
+ assert detectable - set(PROVIDER_AUTODETECT_ORDER) == set(), (
+ "these providers have credentials we could detect but are missing from "
+ "PROVIDER_AUTODETECT_ORDER, so auto-detection will never pick them"
+ )
+
+
+# --- the copies that survive elsewhere -------------------------------------
+#
+# 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.
+
+
+def test_server_provider_catalog_agrees_with_the_registry():
+ from repowise.server.provider_config import PROVIDER_CATALOG
+
+ mismatched = {
+ entry["id"]: (entry["env_keys"], list(PROVIDER_API_KEY_ENVS[entry["id"]]))
+ for entry in PROVIDER_CATALOG
+ if entry["id"] in PROVIDER_API_KEY_ENVS
+ and entry["env_keys"] != list(PROVIDER_API_KEY_ENVS[entry["id"]])
+ }
+ assert not mismatched, f"server/provider_config.py disagrees with the registry: {mismatched}"
+
+
+def test_init_picker_env_vars_agree_with_the_registry():
+ from repowise.cli.ui.provider_selection import _PROVIDER_ENV
+
+ mismatched = {
+ name: (env_var, PROVIDER_API_KEY_ENVS[name][0])
+ for name, env_var in _PROVIDER_ENV.items()
+ if name in PROVIDER_API_KEY_ENVS and env_var != PROVIDER_API_KEY_ENVS[name][0]
+ }
+ assert not mismatched, f"cli/ui/provider_selection.py disagrees with the registry: {mismatched}"
+
+
+# --- provider_required_envs ------------------------------------------------
+
+
+def test_required_envs_is_the_api_key_for_keyed_providers():
+ assert provider_required_envs("anthropic") == ("ANTHROPIC_API_KEY",)
+ assert provider_required_envs("gemini") == ("GEMINI_API_KEY", "GOOGLE_API_KEY")
+
+
+def test_required_envs_is_the_endpoint_for_ollama():
+ """ollama takes no key, but it does need somewhere to send the request."""
+ assert provider_required_envs("ollama") == ("OLLAMA_BASE_URL",)
+
+
+def test_required_envs_is_empty_for_the_agent_clis():
+ assert provider_required_envs("codex_cli") == ()
+ assert provider_required_envs("opencode") == ()
+
+
+# --- provider_is_usable vs provider_credentials_present --------------------
+
+
+def test_keyless_provider_is_usable_with_an_empty_environment():
+ """The two questions differ, and this is the case that separates them."""
+ empty = {}.get
+ assert provider_is_usable("codex_cli", empty) is True
+ assert provider_credentials_present("codex_cli", empty) is False
+
+
+def test_keyed_provider_needs_its_key_to_be_usable():
+ env = {"ANTHROPIC_API_KEY": "sk-ant-test"}
+ assert provider_is_usable("anthropic", env.get) is True
+ assert provider_is_usable("anthropic", {}.get) is False
+
+
+def test_either_gemini_key_satisfies_the_requirement():
+ assert provider_credentials_present("gemini", {"GOOGLE_API_KEY": "g"}.get) is True
+ assert provider_credentials_present("gemini", {"GEMINI_API_KEY": "g"}.get) is True
+
+
+def test_blank_env_var_counts_as_unset():
+ """CI matrices declare empty vars routinely; an empty key authenticates nothing."""
+ for blank in ("", " ", "\t"):
+ assert provider_credentials_present("openai", {"OPENAI_API_KEY": blank}.get) is False
+ assert provider_is_usable("openai", {"OPENAI_API_KEY": blank}.get) is False
+
+
+def test_unknown_provider_is_not_vetoed():
+ """A runtime-registered provider has requirements we cannot know."""
+ assert provider_is_usable("some_custom_provider", {}.get) is True
+
+
+# --- provider_kwargs -------------------------------------------------------
+
+
+def test_kwargs_pull_key_and_base_url_from_the_injected_lookup():
+ env = {"OPENAI_API_KEY": "sk-test", "OPENAI_BASE_URL": "https://proxy.internal/v1"}
+ kwargs = provider_kwargs("openai", model="gpt-5.4-nano", getenv=env.get)
+ assert kwargs == {
+ "model": "gpt-5.4-nano",
+ "api_key": "sk-test",
+ "base_url": "https://proxy.internal/v1",
+ }
+
+
+def test_kwargs_omit_absent_values_rather_than_passing_none():
+ assert provider_kwargs("openai", getenv={}.get) == {}
+
+
+def test_kwargs_strip_surrounding_whitespace_and_drop_blanks():
+ env = {"OPENAI_API_KEY": " sk-test ", "OPENAI_BASE_URL": " "}
+ assert provider_kwargs("openai", getenv=env.get) == {"api_key": "sk-test"}
+
+
+def test_gemini_falls_back_to_google_api_key():
+ kwargs = provider_kwargs("gemini", getenv={"GOOGLE_API_KEY": "g-key"}.get)
+ assert kwargs["api_key"] == "g-key"
+
+
+def test_litellm_prefers_base_url_over_api_base():
+ env = {"LITELLM_BASE_URL": "first", "LITELLM_API_BASE": "second"}
+ assert provider_kwargs("litellm", getenv=env.get)["base_url"] == "first"
+
+
+def test_agent_cli_providers_are_told_which_repo_to_run_in():
+ """#1119: without this the CLI runs against the host process cwd."""
+ for name in ("codex_cli", "opencode"):
+ kwargs = provider_kwargs(name, repo_path="/repo", getenv={}.get)
+ assert kwargs["repo_path"] == "/repo"
+
+
+def test_repo_path_is_not_forwarded_to_providers_that_reject_it():
+ """An HTTP provider's constructor has no repo_path parameter."""
+ kwargs = provider_kwargs("anthropic", repo_path="/repo", getenv={"ANTHROPIC_API_KEY": "k"}.get)
+ assert "repo_path" not in kwargs