Skip to content

The agent that grows with you

feat(models): add native Ollama catalog semantics

Vadelma638b72f5efab
diff --git a/hermes_cli/models.py b/hermes_cli/models.py
index 57a779712d4..04311e07616 100644
--- a/hermes_cli/models.py
+++ b/hermes_cli/models.py
@@ -9,6 +9,7 @@ from __future__ import annotations
import copy
import json
+import http.client
import logging
import os
import re
@@ -25,7 +26,7 @@ if TYPE_CHECKING:
from typing import TypeGuard
from hermes_cli import __version__ as _HERMES_VERSION
-from hermes_cli.urllib_security import open_credentialed_url
+from hermes_cli.urllib_security import open_credentialed_url, url_origin
from utils import base_url_host_matches
logger = logging.getLogger(__name__)
@@ -2524,6 +2525,402 @@ def _get_custom_base_url() -> str:
return str(model_cfg.get("base_url", "")).strip()
+def _get_provider_config_dict(provider: str) -> dict[str, Any]:
+ """Return config.yaml providers.<provider>, or an empty dict."""
+ key = str(provider or "").strip()
+ if not key:
+ return {}
+ try:
+ from hermes_cli.config import load_config
+ config = load_config()
+ providers_cfg = config.get("providers", {})
+ if isinstance(providers_cfg, dict):
+ entry = providers_cfg.get(key) or providers_cfg.get(key.lower())
+ if isinstance(entry, dict):
+ return entry
+ except (ImportError, OSError, RuntimeError, TypeError, ValueError, AttributeError):
+ pass
+ return {}
+
+
+def _root_for_ollama_native_api(base_url: str) -> str:
+ """Convert an OpenAI-style Ollama base URL to the native API root."""
+ root = str(base_url or "").strip().rstrip("/")
+ if root.startswith(":"):
+ root = "http://127.0.0.1" + root
+ elif root and "://" not in root:
+ root = "http://" + root
+ for suffix in ("/api/tags", "/v1/models", "/api", "/v1"):
+ if root.endswith(suffix):
+ root = root[: -len(suffix)].rstrip("/")
+ break
+ return root
+
+
+def _normalize_openai_base_url(base_url: Optional[str]) -> str:
+ """Add a usable HTTP scheme without changing an OpenAI API path."""
+ value = str(base_url or "").strip()
+ if value.startswith(":"):
+ return "http://127.0.0.1" + value
+ if value and "://" not in value:
+ return "http://" + value
+ return value
+
+
+def _get_ollama_base_url() -> str:
+ """Resolve the local Ollama-compatible endpoint URL.
+
+ Prefer explicit config under ``providers.ollama.base_url`` because this is
+ how local Ollama-compatible endpoints can be wired without changing the
+ active model provider. Fall back to active ``model.base_url`` only when the
+ active provider is ollama/custom, then to Ollama's local default.
+ """
+ provider_cfg = _get_provider_config_dict("ollama")
+ configured = (
+ provider_cfg.get("base_url", "")
+ or provider_cfg.get("api", "")
+ or provider_cfg.get("url", "")
+ or ""
+ )
+ if configured:
+ return str(configured).strip()
+
+ model_cfg = _get_model_config_dict()
+ model_provider = str(model_cfg.get("provider", "") or "").strip().lower()
+ model_base = str(model_cfg.get("base_url", "") or "").strip()
+ if model_provider == "ollama" and model_base:
+ return model_base
+ if model_provider == "custom" and model_base:
+ # Only reuse the active bare custom endpoint when it is actually
+ # Ollama-compatible. Otherwise a user working against an unrelated
+ # OpenAI-compatible endpoint would make the Ollama picker probe that
+ # endpoint's /api/tags and hide their local Ollama catalog.
+ try:
+ if should_use_ollama_native_catalog("custom", model_base):
+ return model_base
+ except (OSError, RuntimeError, TypeError, ValueError):
+ pass
+
+ env_host = os.getenv("OLLAMA_HOST", "").strip()
+ if env_host:
+ if env_host.startswith(":") and not env_host.startswith("::"):
+ env_host = "127.0.0.1" + env_host
+ elif env_host.startswith("[") and env_host.endswith("]"):
+ env_host = f"{env_host}:11434"
+ elif "://" in env_host:
+ try:
+ parsed = urllib.parse.urlsplit(env_host)
+ if parsed.hostname and parsed.port is None:
+ hostname = parsed.hostname
+ if ":" in hostname and not hostname.startswith("["):
+ hostname = f"[{hostname}]"
+ userinfo = (
+ parsed.netloc.rsplit("@", 1)[0] + "@"
+ if "@" in parsed.netloc
+ else ""
+ )
+ env_host = parsed._replace(
+ netloc=f"{userinfo}{hostname}:11434"
+ ).geturl()
+ except ValueError:
+ pass
+ elif env_host.count(":") > 1 and not env_host.startswith("["):
+ env_host = f"[{env_host}]:11434"
+ elif ":" not in env_host:
+ env_host = f"{env_host}:11434"
+ return env_host
+ return "http://localhost:11434"
+
+
+def _get_ollama_request_headers() -> dict[str, str]:
+ """Return configured headers and credentials for native Ollama requests."""
+ entry = _get_provider_config_dict("ollama")
+ raw = entry.get("extra_headers")
+ try:
+ from hermes_cli.config import normalize_extra_headers
+
+ result = normalize_extra_headers(raw)
+ except (ImportError, OSError, RuntimeError, TypeError, ValueError):
+ result = {}
+
+ api_key = str(entry.get("api_key") or "").strip()
+ if not api_key:
+ key_env = str(
+ entry.get("key_env") or entry.get("api_key_env") or ""
+ ).strip()
+ api_key = os.getenv(key_env, "").strip() if key_env else ""
+ if api_key:
+ if not any(key.lower() == "authorization" for key in result):
+ result["Authorization"] = f"Bearer {api_key}"
+ return result
+
+
+def _get_ollama_native_headers(
+ base_url: Optional[str],
+ *,
+ api_key: Optional[str] = None,
+) -> dict[str, str]:
+ """Resolve Ollama credentials and headers for one endpoint origin."""
+ entry = _get_provider_config_dict("ollama")
+ configured_base = str(
+ entry.get("base_url") or entry.get("api") or entry.get("url") or ""
+ ).strip()
+ explicit_key = str(api_key or "").strip()
+ configured_matches = bool(
+ configured_base
+ and base_url
+ and _same_ollama_native_root(base_url, configured_base)
+ )
+ if not configured_matches and not explicit_key:
+ return {}
+ headers = _get_ollama_request_headers() if configured_matches else {}
+ if explicit_key:
+ # A provider-specific key must not inherit any configured Authorization
+ # variant from the Ollama origin when both share a native root.
+ for key in tuple(headers):
+ if key.lower() == "authorization":
+ del headers[key]
+ headers["Authorization"] = f"Bearer {explicit_key}"
+ return headers
+
+
+_OLLAMA_LOCAL_MODELS_CACHE_TTL: int = 300 # seconds (5 minutes)
+_OLLAMA_LOCAL_MODELS_CACHE: dict[str, tuple[tuple[str, ...], float]] = {}
+_OLLAMA_LOCAL_PROBE_FAILURE_CACHE: dict[str, float] = {}
+_OLLAMA_LOCAL_PROBE_REACHABLE: dict[str, bool] = {}
+_OLLAMA_LOCAL_PROBE_FAILURE_TTL: int = 30
+_OLLAMA_LOCAL_CACHE_MAX_ENTRIES: int = 256
+
+
+def _evict_related_ollama_cache_entries(key: str) -> None:
+ _OLLAMA_LOCAL_MODELS_CACHE.pop(key, None)
+ _OLLAMA_LOCAL_PROBE_REACHABLE.pop(key, None)
+ for failure_key in list(_OLLAMA_LOCAL_PROBE_FAILURE_CACHE):
+ if failure_key == key or failure_key.startswith(f"{key}|timeout:"):
+ _OLLAMA_LOCAL_PROBE_FAILURE_CACHE.pop(failure_key, None)
+
+
+def _remember_ollama_cache(cache: dict[str, Any], key: str, value: Any) -> None:
+ if key not in cache and len(cache) >= _OLLAMA_LOCAL_CACHE_MAX_ENTRIES:
+ oldest_key = next(iter(cache))
+ _evict_related_ollama_cache_entries(
+ oldest_key.split("|timeout:", 1)[0]
+ )
+ cache[key] = value
+
+
+def _ollama_probe_cache_key(root: str, headers: Optional[dict[str, str]]) -> str:
+ cache_key = root
+ if headers:
+ import hashlib
+
+ normalized_headers = sorted(
+ (str(key).lower(), str(value)) for key, value in headers.items()
+ )
+ header_blob = json.dumps(
+ normalized_headers, ensure_ascii=False, separators=(",", ":")
+ ).encode("utf-8", errors="replace")
+ header_fingerprint = hashlib.blake2b(header_blob, digest_size=8).hexdigest()
+ cache_key = f"{root}|headers:{header_fingerprint}"
+ return cache_key
+
+
+def probe_ollama_local_models(
+ base_url: Optional[str] = None,
+ timeout: float = 2.0,
+ headers: Optional[dict[str, str]] = None,
+) -> Optional[list[str]]:
+ """Probe local Ollama-compatible models from native ``/api/tags``.
+
+ Returns ``None`` when the endpoint cannot be reached or returns malformed
+ data, and a list (possibly empty) when ``/api/tags`` was reachable. Stock
+ Ollama exposes its authoritative local model catalog at ``/api/tags``;
+ OpenAI-compatible ``/v1/models`` is not required for local Ollama servers.
+ """
+ root = _root_for_ollama_native_api(base_url or _get_ollama_base_url())
+ if not root:
+ return None
+ cache_key = _ollama_probe_cache_key(root, headers)
+ failure_key = f"{cache_key}|timeout:{float(timeout):.3f}"
+ cached = _OLLAMA_LOCAL_MODELS_CACHE.get(cache_key)
+ if cached is not None:
+ cached_models, cached_at = cached
+ if time.monotonic() - cached_at < _OLLAMA_LOCAL_MODELS_CACHE_TTL:
+ return list(cached_models)
+ failed_at = _OLLAMA_LOCAL_PROBE_FAILURE_CACHE.get(failure_key)
+ if failed_at is not None:
+ if time.monotonic() - failed_at < _OLLAMA_LOCAL_PROBE_FAILURE_TTL:
+ return None
+ _OLLAMA_LOCAL_PROBE_FAILURE_CACHE.pop(failure_key, None)
+
+ try:
+ url = root.rstrip("/") + "/api/tags"
+ request_headers = {"User-Agent": _HERMES_USER_AGENT}
+ request_headers.update(headers or {})
+ req = urllib.request.Request(url, headers=request_headers)
+ with _urlopen_model_catalog_request(req, timeout=timeout) as resp:
+ payload = json.loads(resp.read().decode())
+ except (
+ ValueError,
+ OSError,
+ TimeoutError,
+ http.client.HTTPException,
+ urllib.error.URLError,
+ json.JSONDecodeError,
+ UnicodeDecodeError,
+ ):
+ _remember_ollama_cache(
+ _OLLAMA_LOCAL_PROBE_REACHABLE, cache_key, False
+ )
+ _remember_ollama_cache(
+ _OLLAMA_LOCAL_PROBE_FAILURE_CACHE, failure_key, time.monotonic()
+ )
+ return None
+
+ raw_models = payload.get("models") if isinstance(payload, dict) else None
+ if not isinstance(raw_models, list):
+ _remember_ollama_cache(
+ _OLLAMA_LOCAL_PROBE_REACHABLE, cache_key, False
+ )
+ _remember_ollama_cache(
+ _OLLAMA_LOCAL_PROBE_FAILURE_CACHE, failure_key, time.monotonic()
+ )
+ return None
+
+ models: list[str] = []
+ seen: set[str] = set()
+ for item in raw_models:
+ if isinstance(item, dict):
+ model_id = str(item.get("model") or item.get("name") or "").strip()
+ else:
+ _remember_ollama_cache(
+ _OLLAMA_LOCAL_PROBE_REACHABLE, cache_key, False
+ )
+ _remember_ollama_cache(
+ _OLLAMA_LOCAL_PROBE_FAILURE_CACHE, failure_key, time.monotonic()
+ )
+ return None
+ if not model_id or model_id in seen:
+ continue
+ seen.add(model_id)
+ models.append(model_id)
+ _remember_ollama_cache(_OLLAMA_LOCAL_PROBE_REACHABLE, cache_key, True)
+ _OLLAMA_LOCAL_PROBE_FAILURE_CACHE.pop(failure_key, None)
+ _remember_ollama_cache(
+ _OLLAMA_LOCAL_MODELS_CACHE,
+ cache_key,
+ (tuple(models), time.monotonic()),
+ )
+ return models
+
+
+def fetch_ollama_local_models(
+ base_url: Optional[str] = None,
+ timeout: float = 2.0,
+ headers: Optional[dict[str, str]] = None,
+) -> Optional[list[str]]:
+ """Fetch local Ollama-compatible models, preserving probe failure as ``None``."""
+ return probe_ollama_local_models(base_url, timeout, headers=headers)
+
+
+def _same_ollama_native_root(left: str, right: str) -> bool:
+ """Return True when two Ollama/OpenAI-style base URLs share an API root."""
+ left_root = _root_for_ollama_native_api(left).rstrip("/")
+ right_root = _root_for_ollama_native_api(right).rstrip("/")
+ if not left_root or not right_root:
+ return False
+ try:
+ left_parts = urllib.parse.urlsplit(left_root)
+ right_parts = urllib.parse.urlsplit(right_root)
+ return (
+ url_origin(left_root) == url_origin(right_root)
+ and left_parts.path.rstrip("/") == right_parts.path.rstrip("/")
+ )
+ except (AttributeError, ValueError):
+ return False
+
+
+def should_use_ollama_native_catalog(
+ provider: Optional[str],
+ base_url: Optional[str],
+ headers: Optional[dict[str, str]] = None,
+) -> bool:
+ """Return True when model discovery should use local Ollama ``/api/tags``.
+
+ Bare ``ollama`` is normalized to ``custom`` elsewhere so runtime paths can
+ share the OpenAI-compatible chat client. For model discovery and validation,
+ however, local Ollama's authoritative model list is ``/api/tags``. Use that
+ path when the caller explicitly asked for Ollama, when the base URL matches
+ configured ``providers.ollama.base_url``, or when an ambiguous custom URL on
+ Ollama's default local port actually serves ``/api/tags``. Ordinary custom
+ endpoints stay on the existing OpenAI-compatible ``/models`` probe path.
+ """
+ requested = str(provider or "").strip().lower()
+ root = _root_for_ollama_native_api(base_url or "")
+ if root:
+ try:
+ host = (urllib.parse.urlparse(root).hostname or "").lower()
+ if host == "ollama.com" or host.endswith(".ollama.com"):
+ return False
+ except ValueError:
+ pass
+
+ known_non_local_providers = {
+ "openrouter",
+ "nous",
+ "anthropic",
+ "openai",
+ "openai-codex",
+ "gemini",
+ "ollama-cloud",
+ }
+ if requested in known_non_local_providers:
+ return False
+
+ if requested == "ollama":
+ if not root:
+ return False
+ configured = _get_provider_config_dict("ollama")
+ configured_base = str(
+ configured.get("base_url")
+ or configured.get("api")
+ or configured.get("url")
+ or ""
+ ).strip()
+ if configured_base and not _same_ollama_native_root(root, configured_base):
+ return probe_ollama_local_models(root, timeout=0.5, headers=headers) is not None
+ return True
+
+ provider_cfg = _get_provider_config_dict("ollama")
+ configured_ollama_base_url = str(
+ provider_cfg.get("base_url", "")
+ or provider_cfg.get("api", "")
+ or provider_cfg.get("url", "")
+ or ""
+ ).strip()
+ if configured_ollama_base_url and _same_ollama_native_root(root, configured_ollama_base_url):
+ return True
+
+ if not root:
+ return False
+
+ local_like_providers = {"", "custom", "local", "llamacpp", "llama.cpp", "llama-cpp", "vllm"}
+ if requested not in local_like_providers and not requested.startswith("custom:"):
+ return False
+
+ if requested == "custom:ollama" or requested.endswith("-ollama"):
+ return True
+
+ try:
+ parsed = urllib.parse.urlparse(root)
+ if parsed.port != 11434:
+ return False
+ except ValueError:
+ return False
+
+ return probe_ollama_local_models(root, timeout=0.5, headers=headers) is not None
+
+
def _get_model_config_dict() -> dict[str, Any]:
"""Return the main model config mapping, or an empty dict."""
try:
@@ -2532,7 +2929,7 @@ def _get_model_config_dict() -> dict[str, Any]:
model_cfg = config.get("model", {})
if isinstance(model_cfg, dict):
return model_cfg
- except Exception:
+ except (ImportError, OSError, RuntimeError, TypeError, ValueError, AttributeError):
pass
return {}
@@ -3135,6 +3532,50 @@ def provider_model_ids(provider: Optional[str], *, force_refresh: bool = False)
models.dev entries are merged on top of curated so new models released
on the platform appear in ``/model`` without a Hermes release.
"""
+ requested = str(provider or "").strip().lower()
+ if requested == "ollama":
+ if force_refresh:
+ _OLLAMA_LOCAL_MODELS_CACHE.clear()
+ _OLLAMA_LOCAL_PROBE_FAILURE_CACHE.clear()
+ _OLLAMA_LOCAL_PROBE_REACHABLE.clear()
+ base_url = _get_ollama_base_url()
+ headers = _get_ollama_native_headers(base_url)
+ use_native = should_use_ollama_native_catalog(
+ "ollama", base_url, headers=headers
+ )
+ if use_native:
+ if headers:
+ native_models = fetch_ollama_local_models(base_url, headers=headers)
+ else:
+ native_models = fetch_ollama_local_models(base_url)
+ native_key = _ollama_probe_cache_key(
+ _root_for_ollama_native_api(base_url), headers or None
+ )
+ if native_models or _OLLAMA_LOCAL_PROBE_REACHABLE.get(native_key) is True:
+ return native_models or []
+ else:
+ # Non-native Ollama-compatible endpoints (including Ollama Cloud)
+ # retain the generic OpenAI-compatible catalog path.
+ pass
+ # gateways that expose only OpenAI-style /v1/models.
+ config = _get_provider_config_dict("ollama")
+ fallback_key = str(config.get("api_key") or "").strip()
+ if not fallback_key:
+ key_env = str(config.get("key_env") or "").strip()
+ fallback_key = os.getenv(key_env, "").strip() if key_env else ""
+ fallback_base = _normalize_openai_base_url(
+ config.get("base_url") or base_url
+ )
+ fallback_headers = _get_ollama_native_headers(
+ fallback_base, api_key=fallback_key
+ )
+ fallback_models = fetch_api_models(
+ fallback_key,
+ fallback_base,
+ headers=fallback_headers or None,
+ )
+ return fallback_models or []
+
normalized = normalize_provider(provider)
if normalized == "openrouter":
return model_ids(force_refresh=force_refresh)
@@ -3439,6 +3880,18 @@ def _spawn_swr_refresh(cache_key: str, refresh_fn=None) -> None:
def _default_refresh():
live = provider_model_ids(cache_key, force_refresh=True)
+ if not live and cache_key == "ollama":
+ base_url = _get_ollama_base_url()
+ headers = _get_ollama_native_headers(base_url) or None
+ probe_key = _ollama_probe_cache_key(
+ _root_for_ollama_native_api(base_url), headers
+ )
+ if _OLLAMA_LOCAL_PROBE_REACHABLE.get(probe_key) is True:
+ return {
+ "fp": _credential_fingerprint(cache_key),
+ "at": time.time(),
+ "models": [],
+ }
if not live:
return None
return {
@@ -3498,7 +3951,7 @@ def _credential_fingerprint(provider: str) -> str:
bev = getattr(pcfg, "base_url_env_var", "") or ""
if bev:
parts.append(f"{bev}={_os.environ.get(bev, '')}")
- except Exception:
+ except (ImportError, AttributeError):
pass
# Effective configured endpoint: config.yaml's model.base_url changes the
@@ -3512,6 +3965,28 @@ def _credential_fingerprint(provider: str) -> str:
except Exception:
pass
+ if provider == "ollama":
+ parts.append(f"OLLAMA_HOST={_os.environ.get('OLLAMA_HOST', '')}")
+ provider_cfg = _get_provider_config_dict("ollama")
+ parts.append(
+ "providers.ollama.base_url="
+ f"{provider_cfg.get('base_url', '') or provider_cfg.get('api', '') or provider_cfg.get('url', '')}"
+ )
+ parts.append(f"providers.ollama.api_key={provider_cfg.get('api_key', '')}")
+ key_env = provider_cfg.get("key_env") or provider_cfg.get("api_key_env") or ""
+ parts.append(f"providers.ollama.key_env={key_env}")
+ if key_env:
+ parts.append(f"{key_env}={_os.environ.get(str(key_env), '')}")
+ model_cfg = _get_model_config_dict()
+ parts.append(
+ "model.provider="
+ f"{model_cfg.get('provider', '')}|model.base_url={model_cfg.get('base_url', '')}"
+ )
+ parts.append(
+ "providers.ollama.extra_headers="
+ + json.dumps(provider_cfg.get("extra_headers", {}), sort_keys=True, default=str)
+ )
+
# OAuth / external-file mtimes that change on re-auth
try:
from hermes_constants import get_hermes_home
@@ -3615,20 +4090,27 @@ def cached_provider_model_ids(
Hits the cache when fresh; otherwise calls the live function and
persists a non-empty result. Always returns a list (never None).
"""
- normalized = normalize_provider(provider) or (provider or "")
+ requested = str(provider or "").strip().lower()
+ normalized = requested if requested == "ollama" else (normalize_provider(provider) or (provider or ""))
if not normalized:
return []
+ if normalized == "ollama":
+ ttl_seconds = min(ttl_seconds, _OLLAMA_LOCAL_MODELS_CACHE_TTL)
cache = _load_provider_models_cache()
fp = _credential_fingerprint(normalized)
entry = cache.get(normalized)
now = time.time()
- if not force_refresh and _cache_entry_valid(entry, fp):
+ allow_empty_ollama = normalized == "ollama"
+ if not force_refresh and _cache_entry_valid(entry, fp, allow_empty=allow_empty_ollama):
age = now - entry["at"]
if age < ttl_seconds:
return list(entry["models"])
- if age < _PROVIDER_MODELS_STALE_SERVE_MAX:
+ # Empty native catalogs are authoritative only for the short native
+ # TTL. Re-probe after expiry so newly pulled models become visible;
+ # do not serve an empty row through the generic stale window.
+ if entry["models"] and age < _PROVIDER_MODELS_STALE_SERVE_MAX:
# Stale-while-revalidate: serve the expired entry immediately so
# interactive picker opens never block on serial /v1/models
# round-trips; refresh the cache off-thread for the next open.
@@ -3646,6 +4128,30 @@ def cached_provider_model_ids(
_save_provider_models_cache(cache)
return list(live)
+ if normalized == "ollama":
+ base_url = _get_ollama_base_url()
+ headers = _get_ollama_native_headers(base_url) or None
+ probe_key = _ollama_probe_cache_key(
+ _root_for_ollama_native_api(base_url), headers
+ )
+ if _OLLAMA_LOCAL_PROBE_REACHABLE.get(probe_key) is True:
+ # A reachable empty native catalog is authoritative for the short
+ # native TTL; do not resurrect a stale disk catalog.
+ cache[normalized] = {"fp": fp, "at": now, "models": []}
+ _save_provider_models_cache(cache)
+ return []
+
+ # A failed/non-native probe is not authoritative. Preserve a stale
+ # catalog rather than blanking the picker during a transient outage.
+ if (
+ isinstance(entry, dict)
+ and entry.get("fp") == fp
+ and isinstance(entry.get("models"), list)
+ and entry["models"]
+ ):
+ return list(entry["models"])
+ return []
+
# Live fetch returned nothing. If we have a stale entry with the
# SAME fingerprint, prefer it over an empty result — stale data
# beats no data when the network is flaky.
@@ -3662,15 +4168,26 @@ def clear_provider_models_cache(provider: Optional[str] = None) -> None:
``hermes model --refresh``.
"""
try:
+ # Native Ollama tags are keyed by root URL rather than provider slug.
+ # A targeted refresh for a custom local-Ollama endpoint cannot identify
+ # the right root from the provider name alone, so clear this small
+ # in-process cache on every explicit provider-cache refresh.
+ _OLLAMA_LOCAL_MODELS_CACHE.clear()
+ _OLLAMA_LOCAL_PROBE_FAILURE_CACHE.clear()
+ _OLLAMA_LOCAL_PROBE_REACHABLE.clear()
if provider is None:
path = _provider_models_cache_path()
if path.exists():
path.unlink()
return
cache = _load_provider_models_cache()
- normalized = normalize_provider(provider) or provider or ""
+ requested = str(provider or "").strip().lower()
+ normalized = requested if requested == "ollama" else (normalize_provider(provider) or provider or "")
+ changed = False
if normalized in cache:
del cache[normalized]
+ changed = True
+ if changed:
_save_provider_models_cache(cache)
except Exception:
pass
@@ -5023,18 +5540,24 @@ def _custom_endpoint_fingerprint(
return hashlib.blake2b(blob, digest_size=8).hexdigest()
-def _cache_entry_valid(entry: Any, fp: str) -> "TypeGuard[dict[str, Any]]":
+def _cache_entry_valid(
+ entry: Any,
+ fp: str,
+ *,
+ allow_empty: bool = False,
+) -> "TypeGuard[dict[str, Any]]":
"""True when *entry* is a well-formed cache row for fingerprint *fp*.
Requires a numeric ``at`` so corrupt disk state (hand-edited JSON with
``"at": "yesterday"`` or ``null``) degrades to a cache miss / live fetch
- instead of raising out of the wrapper.
+ instead of raising out of the wrapper. Empty model lists are valid only
+ for callers that explicitly opt into an authoritative empty catalog.
"""
return (
isinstance(entry, dict)
and entry.get("fp") == fp
and isinstance(entry.get("models"), list)
- and bool(entry["models"])
+ and (allow_empty or bool(entry["models"]))
and isinstance(entry.get("at"), (int, float))
and not isinstance(entry.get("at"), bool)
)
@@ -5273,6 +5796,7 @@ def validate_requested_model(
api_key: Optional[str] = None,
base_url: Optional[str] = None,
api_mode: Optional[str] = None,
+ headers: Optional[dict[str, str]] = None,
) -> dict[str, Any]:
"""
Validate a ``/model`` value for the active provider.
@@ -5365,12 +5889,105 @@ def validate_requested_model(
"message": f"Model `{requested}` was not found in LM Studio's model listing.",
}
+ if str(provider or "").strip().lower() == "ollama" and not base_url:
+ base_url = _get_ollama_base_url()
+ ollama_base_url = base_url
+ configured_ollama_base_url = str(
+ (
+ _get_provider_config_dict("ollama").get("base_url")
+ or _get_provider_config_dict("ollama").get("api")
+ or _get_provider_config_dict("ollama").get("url")
+ or ""
+ )
+ ).strip()
+ configured_headers_allowed = not (
+ configured_ollama_base_url
+ and not _same_ollama_native_root(ollama_base_url or "", configured_ollama_base_url)
+ )
+ if headers is not None:
+ ollama_headers = {}
+ if configured_headers_allowed:
+ ollama_headers.update(
+ _get_ollama_native_headers(ollama_base_url, api_key=api_key)
+ )
+ for key in tuple(ollama_headers):
+ if key.lower() == "authorization":
+ del ollama_headers[key]
+ ollama_headers.update(headers)
+ caller_has_authorization = any(
+ key.lower() == "authorization" for key in headers
+ )
+ if api_key and not caller_has_authorization:
+ for key in tuple(ollama_headers):
+ if key.lower() == "authorization":
+ del ollama_headers[key]
+ ollama_headers["Authorization"] = f"Bearer {api_key}"
+ elif configured_headers_allowed:
+ ollama_headers = _get_ollama_native_headers(ollama_base_url, api_key=api_key)
+ else:
+ ollama_headers = {}
+ if should_use_ollama_native_catalog(
+ provider, ollama_base_url, headers=ollama_headers
+ ):
+ ollama_models = probe_ollama_local_models(
+ ollama_base_url, headers=ollama_headers
+ )
+ if ollama_models is None:
+ # A failed native probe is not authoritative; fall back to the
+ # existing OpenAI-compatible catalog before accepting blindly.
+ ollama_models = probe_api_models(
+ api_key,
+ _normalize_openai_base_url(ollama_base_url),
+ request_headers=ollama_headers,
+ ).get("models")
+ if ollama_models is None:
+ return {
+ "accepted": True,
+ "persist": True,
+ "recognized": False,
+ "message": (
+ f"Note: could not reach this Ollama endpoint's `/api/tags` model listing to validate `{requested}`. "
+ "Hermes will save the model name, but local Ollama model discovery could not verify it."
+ ),
+ }
+ if requested_for_lookup in set(ollama_models):
+ return {
+ "accepted": True,
+ "persist": True,
+ "recognized": True,
+ "message": None,
+ }
+ suggestions = get_close_matches(requested_for_lookup, ollama_models, n=3, cutoff=0.5)
+ suggestion_text = ""
+ if suggestions:
+ suggestion_text = "\n Similar local Ollama models: " + ", ".join(f"`{s}`" for s in suggestions)
+ empty_hint = " No models are currently listed by `/api/tags`." if not ollama_models else ""
+ return {
+ "accepted": True,
+ "persist": True,
+ "recognized": False,
+ "message": (
+ f"Note: `{requested}` was not found in this Ollama endpoint's `/api/tags` model listing."
+ f"{empty_hint} It may still work if the server supports hidden or aliased models."
+ f"{suggestion_text}"
+ ),
+ }
+
if normalized == "custom" or normalized.startswith("custom:"):
# Try probing with correct auth for the api_mode.
if api_mode == "anthropic_messages":
- probe = probe_api_models(api_key, base_url, api_mode=api_mode)
+ probe = probe_api_models(
+ api_key,
+ base_url,
+ api_mode=api_mode,
+ request_headers=headers,
+ )
else:
- probe = probe_api_models(api_key, base_url)
+ probe = probe_api_models(
+ api_key,
+ base_url,
+ request_headers=headers,
+ )
api_models = probe.get("models")
if api_models is not None:
if requested_for_lookup in set(api_models):
diff --git a/tests/hermes_cli/test_models.py b/tests/hermes_cli/test_models.py
index db14b3ed3c6..bba81a9eccd 100644
--- a/tests/hermes_cli/test_models.py
+++ b/tests/hermes_cli/test_models.py
@@ -1,5 +1,8 @@
"""Tests for the hermes_cli models module."""
+import json
+from http.server import BaseHTTPRequestHandler, HTTPServer
+from threading import Thread
from unittest.mock import patch, MagicMock
from hermes_cli.nous_account import NousPortalAccountInfo
@@ -448,8 +451,6 @@ class TestClaudeSonnet5InCuratedLists:
assert "claude-sonnet-5" in _PROVIDER_MODELS["anthropic"]
-
-
class TestFormatPricePerMtok:
"""_format_price_per_mtok: sub-cent prices must not collapse to 'free'/'$0.00'."""
@@ -483,3 +484,1001 @@ class TestFormatPricePerMtok:
def test_one_cent_boundary_stays_two_decimals(self):
from hermes_cli.models import _format_price_per_mtok
assert _format_price_per_mtok("0.00000001") == "$0.01"
+
+
+
+ def test_nous_list_includes_sonnet_5(self):
+ from hermes_cli.models import _PROVIDER_MODELS
+ assert "anthropic/claude-sonnet-5" in _PROVIDER_MODELS["nous"]
+
+
+class _FakeOllamaTagsHandler(BaseHTTPRequestHandler):
+ """Serve Ollama-native /api/tags while rejecting OpenAI /v1/models."""
+
+ models_payload = [
+ {"name": "qwen3:1.7b", "model": "qwen3:1.7b"},
+ {"name": "llama3.2:1b", "model": "llama3.2:1b"},
+ ]
+ paths_seen: list[str] = []
+
+ def do_GET(self):
+ type(self).paths_seen.append(self.path)
+ if self.path.rstrip("/") == "/api/tags":
+ body = json.dumps({"models": type(self).models_payload}).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.end_headers()
+ self.wfile.write(body)
+ return
+ if self.path.rstrip("/") == "/v1/models":
+ self.send_response(503)
+ self.end_headers()
+ return
+ self.send_response(404)
+ self.end_headers()
+
+ def log_message(self, format, *args):
+ pass
+
+
+def _start_fake_ollama_server(models=None):
+ _FakeOllamaTagsHandler.models_payload = (
+ models
+ if models is not None
+ else [
+ {"name": "qwen3:1.7b", "model": "qwen3:1.7b"},
+ {"name": "llama3.2:1b", "model": "llama3.2:1b"},
+ ]
+ )
+ _FakeOllamaTagsHandler.paths_seen = []
+ server = HTTPServer(("127.0.0.1", 0), _FakeOllamaTagsHandler)
+ thread = Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ return server, server.server_address[1]
+
+
+class TestLocalOllamaModelDiscovery:
+ def test_provider_model_ids_uses_ollama_api_tags_from_provider_config(self):
+ """Local Ollama discovery should use /api/tags from providers.ollama.base_url."""
+ from hermes_cli.models import provider_model_ids
+
+ server, port = _start_fake_ollama_server()
+ try:
+ with patch(
+ "hermes_cli.config.load_config",
+ return_value={"providers": {"ollama": {"base_url": f"http://127.0.0.1:{port}"}}},
+ ):
+ assert provider_model_ids("ollama", force_refresh=True) == [
+ "qwen3:1.7b",
+ "llama3.2:1b",
+ ]
+ finally:
+ server.shutdown()
+
+ def test_provider_model_ids_ollama_force_refresh_clears_native_tags_cache(self):
+ from hermes_cli.models import provider_model_ids
+
+ server, port = _start_fake_ollama_server(models=[{"name": "old-model"}])
+ try:
+ with patch(
+ "hermes_cli.config.load_config",
+ return_value={"providers": {"ollama": {"base_url": f"http://127.0.0.1:{port}"}}},
+ ):
+ assert provider_model_ids("ollama", force_refresh=True) == ["old-model"]
+ _FakeOllamaTagsHandler.models_payload = [{"name": "new-model"}]
+ assert provider_model_ids("ollama", force_refresh=True) == ["new-model"]
+ finally:
+ server.shutdown()
+
+ def test_native_tags_cache_expires(self, monkeypatch):
+ from hermes_cli.models import fetch_ollama_local_models
+
+ server, port = _start_fake_ollama_server(models=[{"name": "old-model"}])
+ try:
+ base_url = f"http://127.0.0.1:{port}"
+ assert fetch_ollama_local_models(base_url) == ["old-model"]
+ _FakeOllamaTagsHandler.models_payload = [{"name": "new-model"}]
+ root = _models_mod._root_for_ollama_native_api(base_url)
+ cached_models, _ = _models_mod._OLLAMA_LOCAL_MODELS_CACHE[root]
+ _models_mod._OLLAMA_LOCAL_MODELS_CACHE[root] = (cached_models, 0.0)
+ monkeypatch.setattr("hermes_cli.models.time.monotonic", lambda: 301.0)
+ assert fetch_ollama_local_models(base_url) == ["new-model"]
+ finally:
+ server.shutdown()
+
+ def test_ollama_has_no_static_default_model(self):
+ from hermes_cli.models import get_default_model_for_provider
+
+ assert get_default_model_for_provider("ollama") == ""
+
+ def test_fetch_ollama_models_accepts_base_url_without_scheme(self):
+ """OLLAMA_HOST commonly omits http://; discovery should normalize it."""
+ from hermes_cli.models import fetch_ollama_local_models
+
+ server, port = _start_fake_ollama_server(models=[{"name": "qwen2.5:1.5b"}])
+ try:
+ assert fetch_ollama_local_models(f"127.0.0.1:{port}/v1") == ["qwen2.5:1.5b"]
+ finally:
+ server.shutdown()
+
+ def test_fetch_ollama_models_accepts_full_models_url(self):
+ """Pasted OpenAI-style /v1/models URLs should normalize to the native root."""
+ from hermes_cli.models import fetch_ollama_local_models
+
+ server, port = _start_fake_ollama_server(models=[{"name": "qwen2.5:1.5b"}])
+ try:
+ assert fetch_ollama_local_models(f"127.0.0.1:{port}/v1/models") == [
+ "qwen2.5:1.5b"
+ ]
+ finally:
+ server.shutdown()
+ assert "/api/tags" in _FakeOllamaTagsHandler.paths_seen
+ assert "/v1/models/api/tags" not in _FakeOllamaTagsHandler.paths_seen
+
+ def test_runtime_error_from_config_load_does_not_escape_ollama_helpers(self):
+ """Managed-mode config failures should degrade to defaults, not crash pickers."""
+ from hermes_cli.models import _get_ollama_base_url, should_use_ollama_native_catalog
+
+ with patch("hermes_cli.config.load_config", side_effect=RuntimeError("bad home")), patch(
+ "hermes_cli.models.probe_ollama_local_models",
+ return_value=None,
+ ):
+ assert _get_ollama_base_url() == "http://localhost:11434"
+ assert should_use_ollama_native_catalog("custom", "127.0.0.1:11434/v1") is False
+
+ def test_probe_ollama_models_malformed_base_url_returns_none(self):
+ """Malformed user-configured URLs should behave like probe failures, not crashes."""
+ from hermes_cli.models import probe_ollama_local_models
+
+ assert probe_ollama_local_models("http://127.0.0.1:bad-port/v1") is None
+
+ def test_fetch_ollama_models_preserves_probe_failure(self):
+ from hermes_cli.models import fetch_ollama_local_models
+
+ with patch("hermes_cli.models.probe_ollama_local_models", return_value=None):
+ assert fetch_ollama_local_models("http://127.0.0.1:11434") is None
+
+ def test_ollama_port_detection_requires_working_api_tags(self):
+ from hermes_cli.models import should_use_ollama_native_catalog
+
+ with patch("hermes_cli.models.probe_ollama_local_models", return_value=["qwen3:1.7b"]):
+ assert should_use_ollama_native_catalog("custom", "192.168.1.5:11434/v1") is True
+ with patch("hermes_cli.models.probe_ollama_local_models", return_value=None):
+ assert should_use_ollama_native_catalog("custom", "192.168.1.5:11434/v1") is False
+
+ def test_provider_model_ids_ollama_cloud_config_uses_generic_catalog(self):
+ from hermes_cli.models import provider_model_ids
+
+ with patch(
+ "hermes_cli.config.load_config",
+ return_value={
+ "providers": {
+ "ollama": {
+ "base_url": "https://ollama.com/v1",
+ "api_key": "cloud-key",
+ }
+ }
+ },
+ ), patch("hermes_cli.models.fetch_ollama_local_models") as fetch_local, patch(
+ "hermes_cli.models.fetch_api_models",
+ return_value=["qwen3:1.7b"],
+ ) as fetch_generic:
+ assert provider_model_ids("ollama", force_refresh=True) == ["qwen3:1.7b"]
+ fetch_local.assert_not_called()
+ fetch_generic.assert_called_once_with(
+ "cloud-key",
+ "https://ollama.com/v1",
+ headers={"Authorization": "Bearer cloud-key"},
+ )
+
+ def test_native_ollama_catalog_uses_configured_key_env(self, monkeypatch):
+ from hermes_cli.models import _get_ollama_request_headers
+
+ monkeypatch.setenv("TEST_OLLAMA_API_KEY", "env-key")
+ with patch(
+ "hermes_cli.config.load_config",
+ return_value={
+ "providers": {
+ "ollama": {
+ "base_url": "https://ollama.internal/v1",
+ "key_env": "TEST_OLLAMA_API_KEY",
+ }
+ }
+ },
+ ):
+ assert _get_ollama_request_headers() == {
+ "Authorization": "Bearer env-key"
+ }
+
+ def test_native_ollama_catalog_uses_api_key_env_alias(self, monkeypatch):
+ from hermes_cli.models import _get_ollama_request_headers
+
+ monkeypatch.setenv("TEST_OLLAMA_API_KEY_ALIAS", "alias-key")
+ with patch(
+ "hermes_cli.config.load_config",
+ return_value={
+ "providers": {
+ "ollama": {
+ "base_url": "https://ollama.internal/v1",
+ "api_key_env": "TEST_OLLAMA_API_KEY_ALIAS",
+ }
+ }
+ },
+ ):
+ assert _get_ollama_request_headers() == {
+ "Authorization": "Bearer alias-key"
+ }
+
+ def test_provider_model_ids_ignores_active_non_ollama_custom_endpoint(self):
+ from hermes_cli.models import provider_model_ids
+
+ with patch(
+ "hermes_cli.config.load_config",
+ return_value={
+ "model": {
+ "provider": "custom",
+ "base_url": "https://custom.example/v1",
+ }
+ },
+ ), patch(
+ "hermes_cli.models.fetch_ollama_local_models",
+ return_value=["qwen3:1.7b"],
+ ) as fetch_local:
+ assert provider_model_ids("ollama", force_refresh=True) == ["qwen3:1.7b"]
+ fetch_local.assert_called_once_with("http://localhost:11434")
+
+ def test_ollama_cache_fingerprint_does_not_probe_custom_endpoint(self):
+ from hermes_cli.models import _credential_fingerprint
+
+ with patch(
+ "hermes_cli.config.load_config",
+ return_value={
+ "model": {
+ "provider": "custom",
+ "base_url": "http://127.0.0.1:11434/v1",
+ }
+ },
+ ), patch("hermes_cli.models.probe_ollama_local_models") as probe_ollama:
+ assert _credential_fingerprint("ollama")
+ probe_ollama.assert_not_called()
+
+ def test_ollama_cache_fingerprint_changes_when_configured_api_key_changes(self):
+ from hermes_cli.models import _credential_fingerprint
+
+ provider_config = {
+ "base_url": "http://127.0.0.1:11434",
+ "api_key": "ollama-key-a",
+ }
+ with patch(
+ "hermes_cli.config.load_config",
+ return_value={"providers": {"ollama": provider_config}},
+ ):
+ first = _credential_fingerprint("ollama")
+ provider_config["api_key"] = "ollama-key-b"
+ second = _credential_fingerprint("ollama")
+
+ assert first != second
+
+ def test_ollama_cache_fingerprint_changes_when_key_env_value_changes(self, monkeypatch):
+ from hermes_cli.models import _credential_fingerprint
+
+ monkeypatch.setenv("TEST_OLLAMA_API_KEY", "ollama-key-a")
+ with patch(
+ "hermes_cli.config.load_config",
+ return_value={
+ "providers": {
+ "ollama": {
+ "base_url": "http://127.0.0.1:11434",
+ "key_env": "TEST_OLLAMA_API_KEY",
+ }
+ }
+ },
+ ):
+ first = _credential_fingerprint("ollama")
+ monkeypatch.setenv("TEST_OLLAMA_API_KEY", "ollama-key-b")
+ second = _credential_fingerprint("ollama")
+
+ assert first != second
+
+ def test_clear_provider_models_cache_clears_ollama_native_tags_cache(self):
+ import hermes_cli.models as models
+
+ cache = getattr(models, "_OLLAMA_LOCAL_MODELS_CACHE")
+ cache["http://127.0.0.1:11434"] = ("old-model",)
+ models.clear_provider_models_cache("ollama")
+ assert cache == {}
+
+ def test_clear_provider_models_cache_custom_clears_native_tags_cache(self):
+ import hermes_cli.models as models
+
+ cache = getattr(models, "_OLLAMA_LOCAL_MODELS_CACHE")
+ cache["http://127.0.0.1:11434"] = ("old-model",)
+ models.clear_provider_models_cache("custom")
+ assert cache == {}
+
+ def test_clear_provider_models_cache_does_not_remove_custom_disk_cache(self):
+ import hermes_cli.models as models
+
+ disk_cache = {
+ "custom": {"models": ["custom-model"]},
+ "ollama": {"models": ["ollama-model"]},
+ }
+ with patch.object(models, "_load_provider_models_cache", return_value=disk_cache), patch.object(
+ models, "_save_provider_models_cache"
+ ) as save:
+ models.clear_provider_models_cache("ollama")
+ save.assert_called_once_with({"custom": {"models": ["custom-model"]}})
+
+
+ def test_ollama_cloud_urls_do_not_use_native_local_catalog(self):
+ from hermes_cli.models import should_use_ollama_native_catalog
+
+ assert should_use_ollama_native_catalog("ollama-cloud", "https://ollama.com/v1") is False
+ assert should_use_ollama_native_catalog("ollama", "https://ollama.com/v1") is False
+
+ def test_non_ollama_custom_endpoint_uses_generic_catalog_path(self):
+ from hermes_cli.models import should_use_ollama_native_catalog
+
+ assert should_use_ollama_native_catalog("custom", "https://example.test/v1") is False
+ assert should_use_ollama_native_catalog("openrouter", "http://localhost:11434/v1") is False
+
+ def test_picker_user_provider_row_discovers_ollama_api_tags(self):
+ """providers.ollama with only base_url should still show local Ollama models."""
+ from hermes_cli.model_switch import list_authenticated_providers
+
+ server, port = _start_fake_ollama_server()
+ try:
+ rows = list_authenticated_providers(
+ user_providers={"ollama": {"base_url": f"http://127.0.0.1:{port}"}},
+ custom_providers=[],
+ max_models=10,
+ )
+ finally:
+ server.shutdown()
+
+ ollama_row = next(row for row in rows if row["slug"] == "ollama")
+ assert ollama_row["models"] == ["qwen3:1.7b", "llama3.2:1b"]
+ assert ollama_row["total_models"] == 2
+
+ def test_picker_non_ollama_user_provider_uses_configured_ollama_root(self):
+ """A custom-named providers: entry at the configured Ollama root should use /api/tags."""
+ from hermes_cli.model_switch import list_authenticated_providers
+
+ server, port = _start_fake_ollama_server()
+ base_url = f"http://127.0.0.1:{port}/v1"
+ try:
+ with patch(
+ "hermes_cli.config.load_config",
+ return_value={"providers": {"ollama": {"base_url": base_url}}},
+ ):
+ rows = list_authenticated_providers(
+ user_providers={"local-llm": {"base_url": base_url}},
+ custom_providers=[],
+ max_models=10,
+ )
+ finally:
+ server.shutdown()
+
+ row = next(row for row in rows if row["slug"] == "local-llm")
+ assert row["models"] == ["qwen3:1.7b", "llama3.2:1b"]
+ assert "/api/tags" in _FakeOllamaTagsHandler.paths_seen
+ assert "/v1/models" not in _FakeOllamaTagsHandler.paths_seen
+
+ def test_picker_user_provider_verifies_ambiguous_ollama_port(self):
+ """A custom-named providers: entry on :11434 should use /api/tags after verification."""
+ from hermes_cli.model_switch import list_authenticated_providers
+
+ with patch("hermes_cli.config.load_config", return_value={"providers": {}}), patch(
+ "hermes_cli.models.should_use_ollama_native_catalog",
+ return_value=True,
+ ), patch(
+ "hermes_cli.models.fetch_ollama_local_models",
+ return_value=["qwen3:1.7b"],
+ ), patch("hermes_cli.models.fetch_api_models", return_value=[]) as fetch_api:
+ rows = list_authenticated_providers(
+ user_providers={"local-llm": {"base_url": "http://127.0.0.1:11434/v1"}},
+ custom_providers=[],
+ max_models=10,
+ )
+
+ row = next(row for row in rows if row["slug"] == "local-llm")
+ assert row["models"] == ["qwen3:1.7b"]
+ fetch_api.assert_not_called()
+
+ def test_picker_bare_custom_model_config_discovers_ollama_api_tags(self):
+ """The documented model.provider=custom shape should use native tags."""
+ from hermes_cli.model_switch import list_authenticated_providers
+
+ server, port = _start_fake_ollama_server()
+ base_url = f"http://127.0.0.1:{port}/v1"
+ try:
+ with patch(
+ "hermes_cli.config.load_config",
+ return_value={"providers": {"ollama": {"base_url": base_url}}},
+ ):
+ rows = list_authenticated_providers(
+ current_provider="custom",
+ current_base_url=base_url,
+ current_model="qwen3:1.7b",
+ user_providers={},
+ custom_providers=[],
+ probe_custom_providers=False,
+ probe_current_custom_provider=True,
+ max_models=10,
+ )
+ finally:
+ server.shutdown()
+
+ row = next(row for row in rows if row["slug"] == "custom")
+ assert row["models"] == ["qwen3:1.7b", "llama3.2:1b"]
+ assert "/api/tags" in _FakeOllamaTagsHandler.paths_seen
+ assert "/v1/models" not in _FakeOllamaTagsHandler.paths_seen
+
+ def test_named_custom_model_flow_discovers_ollama_api_tags(self):
+ """Interactive named-custom setup should use tags for a local Ollama root."""
+ from hermes_cli.main import _model_flow_named_custom
+
+ server, port = _start_fake_ollama_server()
+ base_url = f"http://127.0.0.1:{port}/v1"
+ config = {"providers": {"ollama": {"base_url": base_url}}}
+ menu_items: list[str] = []
+
+ def cancel_after_capturing_models(_title, items, **_kwargs):
+ menu_items.extend(items)
+ return -1
+
+ try:
+ with patch("hermes_cli.config.load_config", return_value=config), patch(
+ "hermes_cli.config.save_config"
+ ), patch("hermes_cli.auth._save_model_choice"), patch(
+ "hermes_cli.auth.deactivate_provider"
+ ), patch("hermes_cli.main._save_custom_provider"), patch(
+ "hermes_cli.curses_ui.curses_radiolist",
+ side_effect=cancel_after_capturing_models,
+ ), patch("builtins.input", return_value="manual-fallback"), patch(
+ "builtins.print"
+ ):
+ _model_flow_named_custom(
+ config,
+ {"name": "Local Ollama", "base_url": base_url},
+ )
+ finally:
+ server.shutdown()
+
+ assert menu_items == ["qwen3:1.7b", "llama3.2:1b", "Cancel"]
+ assert "/api/tags" in _FakeOllamaTagsHandler.paths_seen
+ assert "/v1/models" not in _FakeOllamaTagsHandler.paths_seen
+
+ def test_named_custom_model_flow_preserves_explicit_ollama_models(self):
+ """An explicit named-custom models list should skip live native tags."""
+ from hermes_cli.main import _model_flow_named_custom
+
+ server, port = _start_fake_ollama_server()
+ base_url = f"http://127.0.0.1:{port}/v1"
+ config = {"providers": {"ollama": {"base_url": base_url}}}
+ menu_items: list[str] = []
+
+ def cancel_after_capturing_models(_title, items, **_kwargs):
+ menu_items.extend(items)
+ return -1
+
+ try:
+ with patch("hermes_cli.config.load_config", return_value=config), patch(
+ "hermes_cli.curses_ui.curses_radiolist",
+ side_effect=cancel_after_capturing_models,
+ ), patch("builtins.print"):
+ _model_flow_named_custom(
+ config,
+ {
+ "name": "Local Ollama",
+ "base_url": base_url,
+ "models": ["curated-only"],
+ },
+ )
+ finally:
+ server.shutdown()
+
+ assert menu_items == ["curated-only", "Cancel"]
+ assert "/api/tags" not in _FakeOllamaTagsHandler.paths_seen
+ assert "/v1/models" not in _FakeOllamaTagsHandler.paths_seen
+
+ def test_picker_user_provider_preserves_explicit_models_for_ollama_root(self):
+ """providers: entries should not replace an explicit model list with /api/tags."""
+ from hermes_cli.model_switch import list_authenticated_providers
+
+ server, port = _start_fake_ollama_server()
+ base_url = f"http://127.0.0.1:{port}/v1"
+ try:
+ with patch(
+ "hermes_cli.config.load_config",
+ return_value={"providers": {"ollama": {"base_url": base_url}}},
+ ):
+ rows = list_authenticated_providers(
+ user_providers={
+ "local-llm": {
+ "base_url": base_url,
+ "api_key": "no-key-required",
+ "models": ["curated-only"],
+ }
+ },
+ custom_providers=[],
+ max_models=10,
+ )
+ finally:
+ server.shutdown()
+
+ row = next(row for row in rows if row["slug"] == "local-llm")
+ assert row["models"] == ["curated-only"]
+ assert "/api/tags" not in _FakeOllamaTagsHandler.paths_seen
+ assert "/v1/models" not in _FakeOllamaTagsHandler.paths_seen
+
+ def test_picker_custom_provider_group_discovers_configured_ollama_root(self):
+ """custom_providers entries with no explicit model list should use /api/tags for Ollama roots."""
+ from hermes_cli.model_switch import list_authenticated_providers
+
+ server, port = _start_fake_ollama_server()
+ base_url = f"http://127.0.0.1:{port}/v1"
+ try:
+ with patch(
+ "hermes_cli.config.load_config",
+ return_value={"providers": {"ollama": {"base_url": base_url}}},
+ ):
+ rows = list_authenticated_providers(
+ user_providers={},
+ custom_providers=[{"name": "Local Ollama", "base_url": base_url}],
+ max_models=10,
+ )
+ finally:
+ server.shutdown()
+
+ row = next(row for row in rows if row["name"] == "Local Ollama")
+ assert row["models"] == ["qwen3:1.7b", "llama3.2:1b"]
+ assert "/api/tags" in _FakeOllamaTagsHandler.paths_seen
+ assert "/v1/models" not in _FakeOllamaTagsHandler.paths_seen
+
+ def test_picker_custom_provider_saved_model_still_discovers_ollama_tags(self):
+ """Singular model: is an active choice, not a native-catalog restriction."""
+ from hermes_cli.model_switch import list_authenticated_providers
+
+ server, port = _start_fake_ollama_server()
+ base_url = f"http://127.0.0.1:{port}/v1"
+ try:
+ with patch(
+ "hermes_cli.config.load_config",
+ return_value={"providers": {"ollama": {"base_url": base_url}}},
+ ):
+ rows = list_authenticated_providers(
+ user_providers={},
+ custom_providers=[
+ {
+ "name": "Local Ollama",
+ "base_url": base_url,
+ "model": "qwen3:1.7b",
+ }
+ ],
+ max_models=10,
+ )
+ finally:
+ server.shutdown()
+
+ row = next(row for row in rows if row["name"] == "Local Ollama")
+ assert row["models"] == ["qwen3:1.7b", "llama3.2:1b"]
+ assert "/api/tags" in _FakeOllamaTagsHandler.paths_seen
+ assert "/v1/models" not in _FakeOllamaTagsHandler.paths_seen
+
+ def test_picker_custom_provider_group_verifies_ambiguous_ollama_port(self):
+ """Generated custom provider slugs should not block verified :11434 /api/tags discovery."""
+ from hermes_cli.model_switch import list_authenticated_providers
+
+ with patch("hermes_cli.config.load_config", return_value={"providers": {}}), patch(
+ "hermes_cli.models.probe_ollama_local_models",
+ return_value=["qwen3:1.7b"],
+ ), patch("hermes_cli.models.fetch_api_models", return_value=[]) as fetch_api:
+ rows = list_authenticated_providers(
+ user_providers={},
+ custom_providers=[{"name": "Local Ollama", "base_url": "http://127.0.0.1:11434/v1"}],
+ max_models=10,
+ )
+
+ row = next(row for row in rows if row["name"] == "Local Ollama")
+ assert row["models"] == ["qwen3:1.7b"]
+ fetch_api.assert_not_called()
+
+ def test_model_validation_uses_ollama_api_tags_for_ollama_provider(self):
+ """`/model` validation for provider=ollama should not probe `/models`."""
+ from hermes_cli.models import validate_requested_model
+
+ server, port = _start_fake_ollama_server()
+ try:
+ result = validate_requested_model(
+ "qwen3:1.7b",
+ "ollama",
+ base_url=f"http://127.0.0.1:{port}",
+ )
+ finally:
+ server.shutdown()
+
+ assert result == {
+ "accepted": True,
+ "persist": True,
+ "recognized": True,
+ "message": None,
+ }
+ assert "/api/tags" in _FakeOllamaTagsHandler.paths_seen
+ assert "/v1/models" not in _FakeOllamaTagsHandler.paths_seen
+
+ def test_model_validation_ollama_cloud_config_does_not_use_local_tags(self):
+ """provider=ollama with a cloud base URL should not fall into local /api/tags."""
+ from hermes_cli.models import validate_requested_model
+
+ with patch(
+ "hermes_cli.config.load_config",
+ return_value={"providers": {"ollama": {"base_url": "https://ollama.com/v1"}}},
+ ), patch("hermes_cli.models.probe_ollama_local_models") as probe_ollama, patch(
+ "hermes_cli.models.probe_api_models",
+ return_value={
+ "models": ["qwen3:1.7b"],
+ "probed_url": "https://ollama.com/v1/models",
+ },
+ ):
+ result = validate_requested_model("qwen3:1.7b", "ollama")
+
+ probe_ollama.assert_not_called()
+ assert result == {
+ "accepted": True,
+ "persist": True,
+ "recognized": True,
+ "message": None,
+ }
+
+ def test_model_validation_uses_ollama_api_tags_for_matching_custom_endpoint(self):
+ """Current-provider `custom` on the configured Ollama URL should use `/api/tags`."""
+ from hermes_cli.models import validate_requested_model
+
+ server, port = _start_fake_ollama_server()
+ base_url = f"http://127.0.0.1:{port}"
+ try:
+ with patch(
+ "hermes_cli.config.load_config",
+ return_value={"providers": {"ollama": {"base_url": base_url}}},
+ ):
+ result = validate_requested_model(
+ "llama3.2:1b",
+ "custom",
+ base_url=base_url,
+ )
+ finally:
+ server.shutdown()
+
+ assert result["accepted"] is True
+ assert result["persist"] is True
+ assert result["recognized"] is True
+ assert result["message"] is None
+ assert "/api/tags" in _FakeOllamaTagsHandler.paths_seen
+ assert "/v1/models" not in _FakeOllamaTagsHandler.paths_seen
+
+ def test_model_validation_empty_ollama_tags_does_not_fall_back_to_models(self):
+ """Reachable but empty /api/tags should not produce a misleading /models warning."""
+ from hermes_cli.models import validate_requested_model
+
+ server, port = _start_fake_ollama_server(models=[])
+ base_url = f"http://127.0.0.1:{port}"
+ try:
+ with patch(
+ "hermes_cli.config.load_config",
+ return_value={"providers": {"ollama": {"base_url": base_url}}},
+ ):
+ result = validate_requested_model(
+ "qwen3:1.7b",
+ "custom",
+ base_url=base_url,
+ )
+ finally:
+ server.shutdown()
+
+ assert result["accepted"] is True
+ assert result["persist"] is True
+ assert result["recognized"] is False
+ assert "/api/tags" in result["message"]
+ assert "/models" not in result["message"]
+ assert "/api/tags" in _FakeOllamaTagsHandler.paths_seen
+ assert "/v1/models" not in _FakeOllamaTagsHandler.paths_seen
+
+ def test_switch_model_on_current_ollama_custom_endpoint_keeps_base_url(self):
+ """Mid-session `/model` on local Ollama must not re-resolve custom to another provider."""
+ from hermes_cli.model_switch import switch_model
+
+ server, port = _start_fake_ollama_server()
+ base_url = f"http://127.0.0.1:{port}"
+ try:
+ with patch(
+ "hermes_cli.config.load_config",
+ return_value={"providers": {"ollama": {"base_url": base_url}}},
+ ), patch(
+ "hermes_cli.model_switch.get_model_info",
+ return_value=None,
+ ):
+ result = switch_model(
+ raw_input="llama3.2:1b",
+ current_provider="custom",
+ current_model="qwen3:1.7b",
+ current_base_url=base_url,
+ current_api_key="no-key-required",
+ user_providers={"ollama": {"base_url": base_url}},
+ custom_providers=[],
+ )
+ finally:
+ server.shutdown()
+
+ assert result.success is True
+ assert result.target_provider == "custom"
+ assert result.new_model == "llama3.2:1b"
+ assert result.base_url == base_url
+ assert result.warning_message == ""
+
+ def test_switch_model_on_non_ollama_custom_endpoint_still_resolves_runtime(self):
+ """The Ollama base-url preservation path must not change ordinary custom endpoints."""
+ from hermes_cli.model_switch import switch_model
+
+ with patch(
+ "hermes_cli.runtime_provider.resolve_runtime_provider",
+ return_value={
+ "api_key": "new-key",
+ "base_url": "https://custom.example/v1",
+ "api_mode": "chat_completions",
+ },
+ ), patch(
+ "hermes_cli.models.validate_requested_model",
+ return_value={
+ "accepted": True,
+ "persist": True,
+ "recognized": True,
+ "message": None,
+ },
+ ), patch(
+ "hermes_cli.model_switch.get_model_info",
+ return_value=None,
+ ):
+ result = switch_model(
+ raw_input="my-model",
+ current_provider="custom",
+ current_model="old-model",
+ current_base_url="https://old-custom.example/v1",
+ current_api_key="old-key",
+ user_providers={},
+ custom_providers=[],
+ )
+
+ assert result.success is True
+ assert result.base_url == "https://custom.example/v1"
+ assert result.api_key == "new-key"
+
+ def test_switch_model_ollama_precheck_runtime_error_falls_back_to_runtime_resolution(self):
+ """A native-catalog precheck failure should not abort ordinary /model switching."""
+ from hermes_cli.model_switch import switch_model
+
+ with patch(
+ "hermes_cli.models.should_use_ollama_native_catalog",
+ side_effect=RuntimeError("config unavailable"),
+ ), patch(
+ "hermes_cli.runtime_provider.resolve_runtime_provider",
+ return_value={
+ "api_key": "new-key",
+ "base_url": "https://custom.example/v1",
+ "api_mode": "chat_completions",
+ },
+ ), patch(
+ "hermes_cli.models.validate_requested_model",
+ return_value={
+ "accepted": True,
+ "persist": True,
+ "recognized": True,
+ "message": None,
+ },
+ ), patch(
+ "hermes_cli.model_switch.get_model_info",
+ return_value=None,
+ ):
+ result = switch_model(
+ raw_input="my-model",
+ current_provider="custom",
+ current_model="old-model",
+ current_base_url="http://127.0.0.1:11434/v1",
+ current_api_key="old-key",
+ user_providers={},
+ custom_providers=[],
+ )
+
+ assert result.success is True
+ assert result.base_url == "https://custom.example/v1"
+ assert result.api_key == "new-key"
+
+ def test_ollama_root_matching_is_case_insensitive_for_hostnames(self):
+ from hermes_cli.models import _same_ollama_native_root
+
+ assert _same_ollama_native_root(
+ "HTTP://OLLAMA.EXAMPLE:11434/v1",
+ "http://ollama.example:11434",
+ ) is True
+
+ def test_ollama_host_environment_forms_are_normalized(self, monkeypatch):
+ from hermes_cli.models import _get_ollama_base_url, _root_for_ollama_native_api
+
+ monkeypatch.setenv("OLLAMA_HOST", "0.0.0.0")
+ assert _root_for_ollama_native_api(_get_ollama_base_url()) == "http://0.0.0.0:11434"
+ monkeypatch.setenv("OLLAMA_HOST", ":22434")
+ assert _root_for_ollama_native_api(_get_ollama_base_url()) == "http://127.0.0.1:22434"
+ monkeypatch.setenv("OLLAMA_HOST", "::1")
+ assert _root_for_ollama_native_api(_get_ollama_base_url()) == "http://[::1]:11434"
+ monkeypatch.setenv("OLLAMA_HOST", "[::1]")
+ assert _root_for_ollama_native_api(_get_ollama_base_url()) == "http://[::1]:11434"
+ monkeypatch.setenv("OLLAMA_HOST", "http://ollama.example")
+ assert _get_ollama_base_url() == "http://ollama.example:11434"
+ monkeypatch.setenv("OLLAMA_HOST", "http://user:[email protected]")
+ assert _get_ollama_base_url() == "http://user:[email protected]:11434"
+ assert _root_for_ollama_native_api("http://ollama.example/api/tags") == "http://ollama.example"
+
+ def test_ollama_failed_probe_is_cached_briefly(self):
+ import hermes_cli.models as models
+
+ models._OLLAMA_LOCAL_MODELS_CACHE.clear()
+ models._OLLAMA_LOCAL_PROBE_FAILURE_CACHE.clear()
+ with patch(
+ "hermes_cli.models._urlopen_model_catalog_request",
+ side_effect=OSError("offline"),
+ ) as request:
+ assert models.probe_ollama_local_models("http://127.0.0.1:19999") is None
+ assert models.probe_ollama_local_models("http://127.0.0.1:19999") is None
+ request.assert_called_once()
+
+ def test_empty_ollama_catalog_does_not_resurrect_stale_disk_models(self):
+ import hermes_cli.models as models
+
+ base_url = "http://127.0.0.1:11434"
+ probe_key = models._ollama_probe_cache_key(base_url, None)
+ models._OLLAMA_LOCAL_PROBE_REACHABLE[probe_key] = True
+ try:
+ with patch.object(
+ models,
+ "_load_provider_models_cache",
+ return_value={"ollama": {"fp": "same", "at": 0, "models": ["stale:model"]}},
+ ), patch.object(models, "_save_provider_models_cache"), patch.object(
+ models, "_credential_fingerprint", return_value="same"
+ ), patch.object(models, "provider_model_ids", return_value=[]), patch.object(
+ models, "_get_ollama_base_url", return_value=base_url
+ ), patch.object(models, "_get_ollama_request_headers", return_value={}):
+ assert models.cached_provider_model_ids("ollama") == []
+ finally:
+ models._OLLAMA_LOCAL_PROBE_REACHABLE.pop(probe_key, None)
+
+ def test_failed_ollama_catalog_preserves_stale_disk_models(self):
+ import hermes_cli.models as models
+
+ base_url = "http://127.0.0.1:11434"
+ probe_key = models._ollama_probe_cache_key(base_url, None)
+ models._OLLAMA_LOCAL_PROBE_REACHABLE[probe_key] = False
+ try:
+ with patch.object(
+ models,
+ "_load_provider_models_cache",
+ return_value={"ollama": {"fp": "same", "at": 0, "models": ["stale:model"]}},
+ ), patch.object(models, "_save_provider_models_cache"), patch.object(
+ models, "_credential_fingerprint", return_value="same"
+ ), patch.object(models, "provider_model_ids", return_value=[]), patch.object(
+ models, "_get_ollama_base_url", return_value=base_url
+ ), patch.object(models, "_get_ollama_request_headers", return_value={}):
+ assert models.cached_provider_model_ids("ollama") == ["stale:model"]
+ finally:
+ models._OLLAMA_LOCAL_PROBE_REACHABLE.pop(probe_key, None)
+
+ def test_ollama_native_request_uses_redirect_safe_catalog_helper(self):
+ import hermes_cli.models as models
+
+ response = MagicMock()
+ response.read.return_value = b'{"models": [{"name": "qwen3:1.7b"}]}'
+ response.__enter__.return_value = response
+ with patch.object(
+ models, "_urlopen_model_catalog_request", return_value=response
+ ) as request:
+ assert models.fetch_ollama_local_models("http://127.0.0.1:11434") == [
+ "qwen3:1.7b"
+ ]
+ request.assert_called_once()
+
+ def test_validation_with_nonmatching_ollama_root_does_not_forward_config_headers(self):
+ import hermes_cli.models as models
+
+ with patch(
+ "hermes_cli.config.load_config",
+ return_value={
+ "providers": {
+ "ollama": {
+ "base_url": "https://ollama.internal/v1",
+ "extra_headers": {"Authorization": "Bearer secret"},
+ }
+ }
+ },
+ ), patch.object(models, "should_use_ollama_native_catalog", return_value=True), patch.object(
+ models, "probe_ollama_local_models", return_value=[]
+ ) as probe:
+ models.validate_requested_model(
+ "qwen3:1.7b",
+ "ollama",
+ base_url="https://other.internal/v1",
+ )
+ assert probe.call_args.kwargs["headers"] == {}
+ models.validate_requested_model(
+ "qwen3:1.7b",
+ "ollama",
+ base_url="https://other.internal/v1",
+ headers={"X-Endpoint-Token": "explicit"},
+ )
+ assert probe.call_args.kwargs["headers"] == {"X-Endpoint-Token": "explicit"}
+
+
+
+ def test_switch_model_direct_ollama_alias_preserves_matching_origin_api_key(self):
+ import hermes_cli.model_switch as model_switch
+
+ base_url = "https://ollama.internal/v1"
+ original_aliases = dict(model_switch.DIRECT_ALIASES)
+ model_switch.DIRECT_ALIASES.clear()
+ model_switch.DIRECT_ALIASES["remote-qwen"] = model_switch.DirectAlias(
+ model="qwen3:1.7b", provider="ollama", base_url=base_url
+ )
+ try:
+ with patch.object(model_switch, "get_model_info", return_value=None), patch(
+ "hermes_cli.models._get_provider_config_dict",
+ return_value={"base_url": base_url, "api_key": "secret"},
+ ) as config_provider, patch(
+ "hermes_cli.models.validate_requested_model",
+ return_value={"accepted": True, "persist": True, "recognized": True, "message": ""},
+ ):
+ result = model_switch.switch_model(
+ raw_input="remote-qwen",
+ current_provider="openrouter",
+ current_model="old-model",
+ current_api_key="stale-other-endpoint-key",
+ user_providers={"ollama": {"base_url": base_url, "api_key": "secret"}},
+ custom_providers=[],
+ )
+ finally:
+ model_switch.DIRECT_ALIASES.clear()
+ model_switch.DIRECT_ALIASES.update(original_aliases)
+
+ assert config_provider.call_args is not None, result
+ assert config_provider.call_args.args == ("ollama",), config_provider.call_args
+ assert result.success is True
+ assert result.api_key == "secret", result
+
+ def test_switch_model_direct_ollama_alias_clears_different_origin_api_key(self):
+ import hermes_cli.model_switch as model_switch
+
+ original_aliases = dict(model_switch.DIRECT_ALIASES)
+ model_switch.DIRECT_ALIASES.clear()
+ model_switch.DIRECT_ALIASES["other-qwen"] = model_switch.DirectAlias(
+ model="qwen3:1.7b", provider="ollama", base_url="https://other.internal/v1"
+ )
+ try:
+ with patch.object(model_switch, "get_model_info", return_value=None), patch(
+ "hermes_cli.models.validate_requested_model",
+ return_value={"accepted": True, "persist": True, "recognized": True, "message": ""},
+ ):
+ result = model_switch.switch_model(
+ raw_input="other-qwen",
+ current_provider="custom",
+ current_model="old-model",
+ user_providers={
+ "ollama": {
+ "base_url": "https://ollama.internal/v1",
+ "api_key": "secret",
+ }
+ },
+ custom_providers=[],
+ )
+ finally:
+ model_switch.DIRECT_ALIASES.clear()
+ model_switch.DIRECT_ALIASES.update(original_aliases)
+
+ assert result.success is True
+ assert result.api_key == "no-key-required"