The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): provider cluster — drop intra-function separator blanks (whitespace-only)
Teknium6740d264f1df
diff --git a/hermes_cli/provider_catalog.py b/hermes_cli/provider_catalog.pyindex eda5631fa36..3b6bdd6c810 100644--- a/hermes_cli/provider_catalog.py+++ b/hermes_cli/provider_catalog.py@@ -69,7 +69,6 @@ def provider_catalog() -> list[ProviderDescriptor]:auto-extended by provider plugins). Auth/env from ``PROVIDER_REGISTRY``; display metadata from``ProviderProfile`` with canonical/env fallbacks so profile-less providers still resolve."""from hermes_cli.models import CANONICAL_PROVIDERS-PROVIDER_REGISTRY = _safe_import("hermes_cli.auth", "PROVIDER_REGISTRY", {})OPTIONAL_ENV_VARS = _safe_import("hermes_cli.config", "OPTIONAL_ENV_VARS", {})# Overlays carry auth_type for providers with no registry/profile entry — notably the ``moa``@@ -77,11 +76,9 @@ def provider_catalog() -> list[ProviderDescriptor]:HERMES_OVERLAYS = _safe_import("hermes_cli.providers", "HERMES_OVERLAYS", {})try:from providers import list_providers-profiles = {p.name: p for p in list_providers()}except Exception:profiles = {}-out: list[ProviderDescriptor] = []for order, entry in enumerate(CANONICAL_PROVIDERS):slug = entry.slugdiff --git a/hermes_cli/providers.py b/hermes_cli/providers.pyindex 8ec9df57004..9115c89f4d8 100644--- a/hermes_cli/providers.py+++ b/hermes_cli/providers.py@@ -201,7 +201,6 @@ def _models_dev_info(canonical: str, allow_network: bool = True):``get_provider_info`` with single-arg lambdas."""try:from agent.models_dev import get_provider_info as _mdev_provider-return _mdev_provider(canonical) if allow_network else _mdev_provider(canonical, allow_network=False)except Exception:return None@@ -216,7 +215,6 @@ def get_provider(name: str, *, allow_network: bool = True) -> Optional[ProviderDcanonical = normalize_provider(name)mdev_info = _models_dev_info(canonical, allow_network)overlay = HERMES_OVERLAYS.get(canonical)-if mdev_info is not None:ov = overlay or HermesOverlay()env_vars = list(mdev_info.env)@@ -228,7 +226,6 @@ def get_provider(name: str, *, allow_network: bool = True) -> Optional[ProviderDbase_url=ov.base_url_override or mdev_info.api, base_url_env_var=ov.base_url_env_var,is_aggregator=ov.is_aggregator, auth_type=ov.auth_type, doc=mdev_info.doc, source="models.dev",)-if overlay is not None:return ProviderDef(id=canonical, name=_LABEL_OVERRIDES.get(canonical, canonical), transport=overlay.transport,@@ -236,7 +233,6 @@ def get_provider(name: str, *, allow_network: bool = True) -> Optional[ProviderDbase_url_env_var=overlay.base_url_env_var, is_aggregator=overlay.is_aggregator,auth_type=overlay.auth_type, source="hermes",)-# Plugin-registered profiles (plugins/model-providers/<name>/) absent from models.dev and# HERMES_OVERLAYS would otherwise be "Unknown provider" in /model, --provider and model-switch# even though the picker lists them. Only profiles with a concrete endpoint resolve here:@@ -245,7 +241,6 @@ def get_provider(name: str, *, allow_network: bool = True) -> Optional[ProviderD# resolve_provider_full's custom step and collapse keyed ``custom:<name>`` ids to bare custom.try:from providers import get_provider_profile as _profile-_prof = _profile(canonical)if _prof is not None and (_prof.base_url or "").strip():_api_mode_to_transport = {v: k for k, v in TRANSPORT_TO_API_MODE.items()}@@ -456,7 +451,6 @@ def _lossy_alias_registry_pdef(raw: str, canonical: str) -> Optional[ProviderDefthrough the built-in chain so overlay transports apply."""try:from hermes_cli.auth import PROVIDER_REGISTRY as _AUTH_PROVIDER_REGISTRY-_pcfg = _AUTH_PROVIDER_REGISTRY.get(raw)if _pcfg is None:return None@@ -477,7 +471,6 @@ def _llamacpp_pdef() -> Optional[ProviderDef]:provider the Local Models 'Use' flow writes to config."""try:from hermes_cli.local_runtime.endpoint import resolve_llamacpp_endpoint-endpoint = resolve_llamacpp_endpoint(wait_for_boot_s=0)except Exception:endpoint = None@@ -503,7 +496,6 @@ def resolve_provider_full("""canonical = normalize_provider(name)raw = name.strip().lower()-if user_providers:user_pdef = resolve_user_provider(raw, user_providers)if user_pdef is not None:diff --git a/hermes_cli/route_identity.py b/hermes_cli/route_identity.pyindex 65c5be808be..3732874d728 100644--- a/hermes_cli/route_identity.py+++ b/hermes_cli/route_identity.py@@ -28,7 +28,6 @@ def normalize_route_base_url(base_url: Any) -> str:port = parsed.portexcept (TypeError, ValueError):return raw-route_host = parsed.netloc.rsplit("@", 1)[-1]if route_host.startswith("[") or ":" in host:host = f"[{host}]"@@ -36,11 +35,9 @@ def normalize_route_base_url(base_url: Any) -> str:host = f"{host}:{port}"if "@" in parsed.netloc:host = f"{parsed.netloc.rsplit('@', 1)[0]}@{host}"-path = parsed.pathif path.endswith("/") and not had_query_delimiter:path = path[:-1]-normalized = urlunsplit((scheme, host, path, parsed.query, ""))if had_query_delimiter and not parsed.query:normalized += "?"@@ -59,7 +56,6 @@ def should_clear_context_pin(return Truetry:from agent.agent_init import _context_route_mismatch-return _context_route_mismatch(configured_base_url, active_base_url, configured_provider, active_provider)except Exception:return True@@ -70,5 +66,4 @@ async def should_clear_context_pin_async(*args: Any) -> bool:event loop — the resolution chain is cache-only (``allow_network=False``) but can still docold-start disk I/O."""import asyncio-return await asyncio.to_thread(should_clear_context_pin, *args)diff --git a/hermes_cli/runtime_provider.py b/hermes_cli/runtime_provider.pyindex 202cd2647f4..47c5cd23ee7 100644--- a/hermes_cli/runtime_provider.py+++ b/hermes_cli/runtime_provider.py@@ -293,7 +293,6 @@ def _anthropic_cfg_base_url(model_cfg: Dict[str, Any]) -> str:def _anthropic_token_or_raise() -> str:from agent.anthropic_adapter import resolve_anthropic_token-token = resolve_anthropic_token()if not token:raise AuthError(_NO_ANTHROPIC_CREDENTIALS_MSG)@@ -382,7 +381,6 @@ def _auto_detect_local_model(base_url: str) -> str:return ""try:import requests-url = base_url.rstrip("/")if not url.endswith("/v1"):url += "/v1"@@ -848,7 +846,6 @@ def _resolve_vertex_runtime(requested_provider: str) -> Dict[str, Any]:treated as a static API key; a short-lived token is minted per call, and mid-session expiry isrecovered on 401 by run_agent._try_refresh_vertex_client_credentials()."""from agent.vertex_adapter import get_vertex_config-token, base_url = get_vertex_config()if not token or not base_url:raise AuthError(@@ -951,11 +948,9 @@ def resolve_runtime_provider((e.g. OpenCode Zen/Go where different models route through different API surfaces)."""requested_provider = resolve_requested_provider(requested)_raise_if_provider_disabled(requested_provider)-runtime = _resolve_requested_shortcuts(requested_provider, explicit_api_key, explicit_base_url, target_model)if runtime:return runtime-runtime = _resolve_named_custom_runtime(requested_provider=requested_provider, explicit_api_key=explicit_api_key,explicit_base_url=explicit_base_url, target_model=target_model,@@ -963,53 +958,41 @@ def resolve_runtime_provider(if runtime:runtime["requested_provider"] = requested_providerreturn runtime-if not explicit_base_url and not explicit_api_key:runtime = _local_endpoint_bypass(requested_provider, explicit_api_key, explicit_base_url)if runtime:return runtime-provider = resolve_provider(requested_provider, explicit_api_key=explicit_api_key, explicit_base_url=explicit_base_url)model_cfg = _get_model_config()-runtime = _opencode_free_runtime(provider, requested_provider, model_cfg, target_model)if runtime is not None:return runtime-runtime = _resolve_explicit_runtime(provider=provider, requested_provider=requested_provider, model_cfg=model_cfg,explicit_api_key=explicit_api_key, explicit_base_url=explicit_base_url, target_model=target_model,)if runtime:return runtime-runtime = _resolve_from_pool(provider, requested_provider, model_cfg, explicit_api_key, explicit_base_url, target_model)if runtime:return runtime-if provider in _OAUTH_RUNTIME_PROVIDERS:runtime = _resolve_oauth_runtime(provider, requested_provider, model_cfg, target_model)if runtime:return runtime-if provider == "minimax-oauth":runtime = _minimax_oauth_runtime(provider, requested_provider)if runtime:return runtime-if _is_external_process_provider(provider):return _resolve_external_process_runtime(provider, requested_provider)-if provider == "anthropic":return _anthropic_env_runtime(requested_provider, model_cfg)-if provider == "bedrock":return _resolve_bedrock_runtime(requested_provider, model_cfg, target_model)-pconfig = PROVIDER_REGISTRY.get(provider)if pconfig and pconfig.auth_type == "api_key":return _api_key_provider_runtime(provider, pconfig, requested_provider, model_cfg, target_model)-return _openrouter_fallback(requested_provider, explicit_api_key, explicit_base_url)diff --git a/hermes_cli/runtime_provider_backends.py b/hermes_cli/runtime_provider_backends.pyindex 28acb1e22e7..aba924a26e0 100644--- a/hermes_cli/runtime_provider_backends.py+++ b/hermes_cli/runtime_provider_backends.py@@ -18,7 +18,6 @@ from utils import base_url_host_matchesdef _rp():import hermes_cli.runtime_provider as origin-return origin@@ -49,7 +48,6 @@ def _azure_foundry_api_key(rp, explicit_api_key: str) -> str:return explicit_api_keytry:from hermes_cli.config import get_env_value-api_key = get_env_value("AZURE_FOUNDRY_API_KEY") or ""except Exception:api_key = ""@@ -75,7 +73,6 @@ def _resolve_azure_foundry_runtime(rp = _rp()explicit_api_key = str(explicit_api_key or "").strip()explicit_base_url_clean = str(explicit_base_url or "").strip().rstrip("/")-cfg_base_url, cfg_api_mode, cfg_auth_mode, cfg_entra = "", "chat_completions", "api_key", {}if rp._cfg_provider(model_cfg) == "azure-foundry":cfg_base_url = rp._config_base_url_for_provider(model_cfg, "azure-foundry")@@ -83,11 +80,9 @@ def _resolve_azure_foundry_runtime(cfg_auth_mode = str(model_cfg.get("auth_mode") or "api_key").strip().lower() or "api_key"if isinstance(model_cfg.get("entra"), dict):cfg_entra = model_cfg["entra"]-# GPT-5.x / codex / o1-o4 deployments are Responses-API-only on Foundry.effective_model = str(target_model or model_cfg.get("default") or "").strip()cfg_api_mode = rp._azure_inferred_api_mode(effective_model, cfg_api_mode)-env_base_url = rp._getenv("AZURE_FOUNDRY_BASE_URL", "").strip().rstrip("/")base_url = explicit_base_url_clean or cfg_base_url or env_base_urlif not base_url:@@ -97,7 +92,6 @@ def _resolve_azure_foundry_runtime()if cfg_api_mode == "anthropic_messages":base_url = re.sub(r"/v1/?$", "", base_url)-if cfg_auth_mode == "entra_id":if explicit_api_key:# --api-key on the CLI while config says entra_id: honour the explicit string@@ -145,7 +139,6 @@ def _resolve_openrouter_runtime(# 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"-env_openrouter_base_url = rp._getenv("OPENROUTER_BASE_URL", "").strip()env_custom_base_url = rp._getenv("CUSTOM_BASE_URL", "").strip()use_config_base_url = bool(cfg_base_url.strip()) and not explicit_base_url and (@@ -159,7 +152,6 @@ def _resolve_openrouter_runtime(or env_openrouter_base_urlor 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.@@ -179,7 +171,6 @@ def _resolve_openrouter_runtime(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"))-# Explicit "custom" stays "custom" rather than relabeling to "openrouter".if requested_norm != "custom":return rp._runtime(@@ -224,7 +215,6 @@ def _resolve_bedrock_runtime(requested_provider: str, model_cfg: Dict[str, Any],resolve_aws_auth_env_var, resolve_bedrock_bearer_token, resolve_bedrock_runtime_region,)from hermes_cli.config import load_config # direct (not the origin delegate), as before-rp = _rp()# Explicitly selected bedrock trusts boto3's credential chain (IMDS, ECS/Lambda roles, SSO)# which the env-var check can't detect.@@ -273,7 +263,6 @@ def _is_external_process_provider(provider: str) -> bool:return Falsetry:from hermes_cli.auth import PROVIDER_REGISTRY-pconfig = PROVIDER_REGISTRY.get(name)if pconfig is not None:return pconfig.auth_type == "external_process"@@ -281,7 +270,6 @@ def _is_external_process_provider(provider: str) -> bool:passtry:from providers import get_provider_profile-profile = get_provider_profile(name)except Exception:return Falsediff --git a/hermes_cli/runtime_provider_custom.py b/hermes_cli/runtime_provider_custom.pyindex d5a556fde39..0dd10f34b8e 100644--- a/hermes_cli/runtime_provider_custom.py+++ b/hermes_cli/runtime_provider_custom.py@@ -25,7 +25,6 @@ _LLAMACPP_ALIASES = ("llamacpp", "llama.cpp", "llama-cpp")def _rp():"""Origin module, late-bound so test patches on ``hermes_cli.runtime_provider.*`` apply."""import hermes_cli.runtime_provider as origin-return origin@@ -129,7 +128,6 @@ def _shadowed_by_builtin(requested_norm: str) -> bool:def _match_new_style_provider(requested_norm: str, providers: Dict[str, Any]) -> Optional[Dict[str, Any]]:"""Scan ``providers:`` (new-style, keyed) for ``requested_norm``."""from hermes_cli.config import is_provider_enabled-rp = _rp()for ep_name, entry in providers.items():# ``providers.<name>.enabled: false`` entries stay in config but are invisible here.@@ -353,7 +351,6 @@ def is_routable_provider(provider: Optional[str]) -> bool:return Falsetry:from hermes_cli.providers import resolve_provider_full-rp = _rp()config = rp.load_config()return resolve_provider_full(name, config.get("providers"), rp.get_compatible_custom_providers(config)) is not None@@ -437,7 +434,6 @@ def _resolve_llamacpp_runtime(requested_provider: str, explicit_api_key: Optionarp = _rp()try:from hermes_cli.local_runtime.endpoint import resolve_llamacpp_endpoint-endpoint = resolve_llamacpp_endpoint()except Exception: # noqa: BLE001 — resolution is best-effortendpoint = None@@ -494,7 +490,6 @@ def _resolve_direct_alias_runtime(def _opencode_family_for_custom(requested_provider: str, base_url: str) -> Optional[str]:"""OpenCode family by provider name, else by opencode.ai host (``/zen/go`` => opencode-go)."""from hermes_cli.models import opencode_provider_family-family = opencode_provider_family(requested_provider)if family is not None:return family@@ -524,14 +519,12 @@ def _resolve_named_custom_runtime(requested_norm = "custom"if requested_norm == "custom" and explicit_base_url:return _resolve_direct_alias_runtime(requested_provider, explicit_api_key, explicit_base_url)-custom_provider = rp._get_named_custom_provider(requested_provider)if not custom_provider:return Nonebase_url = ((explicit_base_url or "").strip() or custom_provider.get("base_url", "")).rstrip("/")if not base_url:return None-pool_result = rp._try_resolve_from_custom_pool(base_url, "custom", custom_provider.get("api_mode"),provider_name=custom_provider.get("provider_key") or custom_provider.get("name"),@@ -540,7 +533,6 @@ def _resolve_named_custom_runtime(# The pool doesn't know the custom_providers fields — propagate them here too._apply_custom_provider_extras(custom_provider, target_model, pool_result)return pool_result-explicit_key = (explicit_api_key or "").strip()candidates = [explicit_key,@@ -549,33 +541,28 @@ def _resolve_named_custom_runtime(*rp._host_gated_env_key_candidates(base_url, ollama=False),]api_key: Any = next((c for c in candidates if rp.has_usable_secret(c)), "")-# ``key_cmd`` credentials are minted per request (short-lived bearers would go stale# mid-session); both wire clients accept a callable api_key (the Entra ID contract). An# explicit --api-key still wins as the one-off recovery escape hatch.key_cmd = _clean(custom_provider.get("key_cmd", ""))if key_cmd and not rp.has_usable_secret(explicit_key):from agent.command_token_source import build_command_token_provider-token_provider = build_command_token_provider(key_cmd, str(custom_provider.get("name", requested_provider) or "custom"))if token_provider is not None:api_key = token_provider-result = _custom_runtime(rp, base_url, api_key, custom_provider.get("api_mode"),source=f"custom_provider:{custom_provider.get('name', requested_provider)}", requested_provider=requested_provider,)_apply_custom_provider_extras(custom_provider, target_model, result)-# OpenCode-family custom providers (opencode-go/zen names, or opencode.ai hosts) serve models# on different API surfaces — a static api_mode 503s for /v1/responses-only models. Re-derive# api_mode from the model and normalize /v1 like the built-in paths.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()