Skip to content

The agent that grows with you

refactor(hermes_cli): backends/custom — fold candidate lists, message literals; drop always-None provider_name conditional

Tekniumc9268741521f
diff --git a/hermes_cli/runtime_provider.py b/hermes_cli/runtime_provider.py
index 031823b1f9f..63317c01d75 100644
--- a/hermes_cli/runtime_provider.py
+++ b/hermes_cli/runtime_provider.py
@@ -240,10 +240,8 @@ def _maybe_apply_codex_app_server_runtime(*, provider: str, api_mode: str, model
# ── base_url / credential helpers ──────────────────────────────────────────────────────────
_ANTHROPIC_DEFAULT_BASE_URL = "https://api.anthropic.com"
-_NO_ANTHROPIC_CREDENTIALS_MSG = (
- "No Anthropic credentials found. Set ANTHROPIC_TOKEN or ANTHROPIC_API_KEY, "
- "run 'claude setup-token', or authenticate with 'claude /login'."
-)
+_NO_ANTHROPIC_CREDENTIALS_MSG = ("No Anthropic credentials found. Set ANTHROPIC_TOKEN or ANTHROPIC_API_KEY, "
+ "run 'claude setup-token', or authenticate with 'claude /login'.")
def _runtime(provider: str, api_mode: str, base_url: Any, api_key: Any, **extra: Any) -> Dict[str, Any]:
@@ -745,11 +743,9 @@ def _anthropic_env_runtime(requested_provider: str, model_cfg: Dict[str, Any]) -
if base_url_host_matches(base_url, "azure.com") or (cfg_base_url and base_url_host_matches(cfg_base_url, "azure.com")):
token = _azure_anthropic_env_key(model_cfg)
if not token:
- raise AuthError(
- "No Azure Anthropic API key found. Set AZURE_ANTHROPIC_KEY or "
- "ANTHROPIC_API_KEY, or point key_env/api_key_env in your "
- "config.yaml model section at a custom env var."
- )
+ raise AuthError("No Azure Anthropic API key found. Set AZURE_ANTHROPIC_KEY or "
+ "ANTHROPIC_API_KEY, or point key_env/api_key_env in your "
+ "config.yaml model section at a custom env var.")
else:
token = _anthropic_token_or_raise()
return _runtime("anthropic", "anthropic_messages", base_url, token, source="env", requested_provider=requested_provider)
@@ -792,10 +788,8 @@ def _raise_if_provider_disabled(requested_provider: str) -> None:
provs_cfg = full_cfg.get("providers") if isinstance(full_cfg, dict) else None
block = provs_cfg.get(requested_provider) if isinstance(provs_cfg, dict) else None
if isinstance(block, dict) and not _config_mod.is_provider_enabled(block):
- raise ValueError(
- f"provider {requested_provider!r} is disabled in config "
- f"(providers.{requested_provider}.enabled: false)"
- )
+ raise ValueError(f"provider {requested_provider!r} is disabled in config "
+ f"(providers.{requested_provider}.enabled: false)")
def _resolve_vertex_runtime(requested_provider: str) -> Dict[str, Any]:
@@ -805,15 +799,13 @@ def _resolve_vertex_runtime(requested_provider: str) -> Dict[str, Any]:
from agent.vertex_adapter import get_vertex_config
token, base_url = get_vertex_config()
if not token or not base_url:
- raise AuthError(
- "Vertex AI credentials could not be resolved. Vertex uses "
- "OAuth2 (not a static API key): provide a service-account JSON "
- "via GOOGLE_APPLICATION_CREDENTIALS (or VERTEX_CREDENTIALS_PATH) "
- "in ~/.hermes/.env, or run 'gcloud auth application-default "
- "login' for ADC. Set the GCP project/region under vertex: in "
- "config.yaml if they aren't embedded in the credentials. "
- "Run `hermes setup` to install Vertex support."
- )
+ raise AuthError("Vertex AI credentials could not be resolved. Vertex uses "
+ "OAuth2 (not a static API key): provide a service-account JSON "
+ "via GOOGLE_APPLICATION_CREDENTIALS (or VERTEX_CREDENTIALS_PATH) "
+ "in ~/.hermes/.env, or run 'gcloud auth application-default "
+ "login' for ADC. Set the GCP project/region under vertex: in "
+ "config.yaml if they aren't embedded in the credentials. "
+ "Run `hermes setup` to install Vertex support.")
return _runtime("vertex", "chat_completions", base_url.rstrip("/"), token, source="vertex-oauth", requested_provider=requested_provider)
diff --git a/hermes_cli/runtime_provider_backends.py b/hermes_cli/runtime_provider_backends.py
index a69baa083e6..400d4bc2044 100644
--- a/hermes_cli/runtime_provider_backends.py
+++ b/hermes_cli/runtime_provider_backends.py
@@ -120,12 +120,9 @@ def _resolve_openrouter_runtime(
rp = _rp()
model_cfg = rp._get_model_config()
cfg_base_url = model_cfg.get("base_url") if isinstance(model_cfg.get("base_url"), str) else ""
- cfg_provider = model_cfg.get("provider") if isinstance(model_cfg.get("provider"), str) else ""
- cfg_api_key = next(
- (v.strip() for v in (model_cfg.get("api_key"), model_cfg.get("api")) if isinstance(v, str) and v.strip()), ""
- )
+ cfg_provider = (model_cfg.get("provider") if isinstance(model_cfg.get("provider"), str) else "").strip().lower()
+ cfg_api_key = next((v.strip() for v in (model_cfg.get("api_key"), model_cfg.get("api")) if isinstance(v, str) and v.strip()), "")
requested_norm = (requested_provider or "").strip().lower()
- cfg_provider = cfg_provider.strip().lower()
# Aliases resolving to "custom" (ollama, vllm, …) follow bare-custom trust + routing rules.
if requested_norm and requested_norm != "custom" and rp._resolves_to_custom(requested_norm):
requested_norm = "custom"
@@ -135,29 +132,20 @@ def _resolve_openrouter_runtime(
(requested_norm == "auto" and cfg_provider in ("", "auto"))
or (requested_norm == "custom" and rp._config_base_url_trustworthy_for_bare_custom(cfg_base_url, cfg_provider))
)
- base_url = (
- (explicit_base_url or "").strip()
- or env_custom_base_url
- or (cfg_base_url.strip() if use_config_base_url else "")
- or env_openrouter_base_url
- or OPENROUTER_BASE_URL
- ).rstrip("/")
+ base_url = ((explicit_base_url or "").strip() or env_custom_base_url or (cfg_base_url.strip() if use_config_base_url else "")
+ or env_openrouter_base_url or OPENROUTER_BASE_URL).rstrip("/")
is_openrouter_url = base_url_host_matches(base_url, "openrouter.ai")
# Explicitly-configured OpenRouter mirrors (OPENROUTER_BASE_URL + provider=openrouter) still
# count as OpenRouter for key selection.
is_openrouter_context = is_openrouter_url or (
- requested_norm == "openrouter"
- and (env_openrouter_base_url or base_url == env_openrouter_base_url)
+ requested_norm == "openrouter" and (env_openrouter_base_url or base_url == env_openrouter_base_url)
and base_url == (env_openrouter_base_url or "").rstrip("/")
)
if is_openrouter_context:
candidates = [explicit_api_key, rp._getenv("OPENROUTER_API_KEY"), rp._getenv("OPENAI_API_KEY")]
else:
- candidates = [
- explicit_api_key,
- (cfg_api_key if use_config_base_url else ""),
- *rp._host_gated_env_key_candidates(base_url, ollama=True),
- ]
+ candidates = [explicit_api_key, (cfg_api_key if use_config_base_url else ""),
+ *rp._host_gated_env_key_candidates(base_url, ollama=True)]
api_key = next((str(c or "").strip() for c in candidates if rp.has_usable_secret(c)), "")
source = "explicit" if (explicit_api_key or explicit_base_url) else "env/config"
cfg_api_mode = rp._parse_api_mode(model_cfg.get("api_mode"))
@@ -166,11 +154,7 @@ def _resolve_openrouter_runtime(
return rp._runtime("openrouter", cfg_api_mode or rp._detect_api_mode_for_url(base_url) or "chat_completions", base_url,
api_key, source=source)
if base_url:
- # provider_name makes pool lookup prefer name match over base_url (fixes credential
- # mix-ups when multiple custom providers share a base_url).
- pool_result = rp._try_resolve_from_custom_pool(
- base_url, "custom", cfg_api_mode, provider_name=requested_provider if requested_norm != "custom" else None
- )
+ pool_result = rp._try_resolve_from_custom_pool(base_url, "custom", cfg_api_mode, provider_name=None)
if pool_result:
return pool_result
# Local no-auth servers get a placeholder key — the OpenAI SDK requires a non-empty string.
diff --git a/hermes_cli/runtime_provider_custom.py b/hermes_cli/runtime_provider_custom.py
index adc43c3a808..0e6d31e4f3a 100644
--- a/hermes_cli/runtime_provider_custom.py
+++ b/hermes_cli/runtime_provider_custom.py
@@ -134,10 +134,8 @@ def _match_new_style_provider(requested_norm: str, providers: Dict[str, Any]) ->
base_url = _entry_url(entry)
if not base_url:
continue
- result: Dict[str, Any] = {
- "name": entry.get("name", ep_name), "base_url": base_url.strip(),
- "api_key": api_key or _clean(entry.get("api_key", "")), "model": entry.get("default_model", ""),
- }
+ result: Dict[str, Any] = {"name": entry.get("name", ep_name), "base_url": base_url.strip(),
+ "api_key": api_key or _clean(entry.get("api_key", "")), "model": entry.get("default_model", "")}
# Command that PRINTS a short-lived credential; wrapped in a per-request token provider.
key_cmd = _clean(entry.get("key_cmd", ""))
if key_cmd:
@@ -185,16 +183,12 @@ def _get_named_custom_provider(requested_provider: str) -> Optional[Dict[str, An
if found:
return found
if isinstance(config.get("custom_providers"), dict):
- logger.warning(
- "custom_providers in config.yaml is a dict, not a list. "
- "Each entry must be prefixed with '-' in YAML. "
- "Run 'hermes doctor' for details."
- )
+ logger.warning("custom_providers in config.yaml is a dict, not a list. "
+ "Each entry must be prefixed with '-' in YAML. "
+ "Run 'hermes doctor' for details.")
return None
custom_providers = rp.get_compatible_custom_providers(config)
- if not custom_providers:
- return None
- return _match_legacy_custom_provider(requested_norm, custom_providers)
+ return _match_legacy_custom_provider(requested_norm, custom_providers) if custom_providers else None
def has_named_custom_provider(requested_provider: str) -> bool:
@@ -418,16 +412,12 @@ def _resolve_llamacpp_runtime(requested_provider: str, explicit_api_key: Optiona
except Exception: # noqa: BLE001
enabled = False
if enabled:
- raise ValueError(
- "The local model server isn't running. It may still be "
- "starting — try again in a moment, or check Settings → "
- "Providers → Local models."
- )
- raise ValueError(
- "The local model server is turned off. Turn it back on in "
- "Settings → Providers → Local models, or switch to another "
- "model."
- )
+ raise ValueError("The local model server isn't running. It may still be "
+ "starting — try again in a moment, or check Settings → "
+ "Providers → Local models.")
+ raise ValueError("The local model server is turned off. Turn it back on in "
+ "Settings → Providers → Local models, or switch to another "
+ "model.")
def _custom_runtime(rp, base_url: str, api_key: Any, api_mode: Optional[str], **extra: Any) -> Dict[str, Any]:
@@ -524,9 +514,7 @@ def _resolve_named_custom_runtime(*, requested_provider: str, explicit_api_key:
family = _opencode_family_for_custom(requested_provider, base_url)
if family is not None and not custom_provider.get("api_mode"):
from hermes_cli.models import normalize_opencode_base_url, opencode_model_api_mode
- effective_model = str(
- target_model or custom_provider.get("model") or rp._get_model_config().get("default") or ""
- ).strip()
+ effective_model = str(target_model or custom_provider.get("model") or rp._get_model_config().get("default") or "").strip()
if effective_model:
result["api_mode"] = opencode_model_api_mode(family, effective_model)
result["base_url"] = normalize_opencode_base_url(family, result["api_mode"], result["base_url"])