The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): dedupe URL-suffix stripping, api-key lookup and LM Studio entry helpers in models_local
Teknium1cf91f6e1382
diff --git a/hermes_cli/models_local.py b/hermes_cli/models_local.pyindex 1ec9b48ad71..51819a1f046 100644--- a/hermes_cli/models_local.py+++ b/hermes_cli/models_local.py@@ -1,15 +1,15 @@"""Local / self-hosted model servers.Ollama (native ``/api/tags`` probe, request headers, base-url resolution), LM Studio-(``/api/v1/models``, load-on-demand), and Ollama Cloud (live + models.dev merged catalog with a-disk cache).--Split out of ``hermes_cli.models``; every moved name is re-imported there, so-``hermes_cli.models.<name>`` keeps resolving (and monkeypatching) as before.+(``/api/v1/models``, load-on-demand) and Ollama Cloud (live + models.dev merged catalog with a+disk cache). Split out of ``hermes_cli.models``, which re-imports every name; origin helpers are+looked up on ``hermes_cli.models`` at call time so ``patch("hermes_cli.models.<name>")`` mocks+keep intercepting."""from __future__ import annotations+import hashlibimport http.clientimport jsonimport logging@@ -25,18 +25,14 @@ from hermes_cli.urllib_security import url_origin# Log-record parity with the origin module.logger = logging.getLogger("hermes_cli.models")+_OLLAMA_DEFAULT_PORT = 11434-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"):++def _strip_suffixes(root: str, suffixes: tuple[str, ...]) -> str:+ """Drop the first matching path suffix (and any trailing slash) from *root*."""+ for suffix in suffixes:if root.endswith(suffix):- root = root[: -len(suffix)].rstrip("/")- break+ return root[: -len(suffix)].rstrip("/")return root@@ -50,6 +46,16 @@ def _normalize_openai_base_url(base_url: Optional[str]) -> str:return value+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+ return _strip_suffixes(root, ("/api/tags", "/v1/models", "/api", "/v1"))++def _configured_ollama_base_url() -> str:"""``providers.ollama.base_url`` (legacy keys ``api`` / ``url``), or ``""``."""from hermes_cli.models import _get_provider_config_dict@@ -58,13 +64,39 @@ def _configured_ollama_base_url() -> str:return str(cfg.get("base_url") or cfg.get("api") or cfg.get("url") or "").strip()+def _ollama_host_from_env(env_host: str) -> str:+ """Apply Ollama's own ``OLLAMA_HOST`` defaulting rules (port 11434, IPv6 bracketing)."""+ port = _OLLAMA_DEFAULT_PORT+ if env_host.startswith(":") and not env_host.startswith("::"):+ return "127.0.0.1" + env_host+ if env_host.startswith("[") and env_host.endswith("]"):+ return f"{env_host}:{port}"+ if "://" 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 ""+ return parsed._replace(netloc=f"{userinfo}{hostname}:{port}").geturl()+ except ValueError:+ pass+ return env_host+ if env_host.count(":") > 1 and not env_host.startswith("["):+ return f"[{env_host}]:{port}"+ if ":" not in env_host:+ return f"{env_host}:{port}"+ return env_host++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.+ Precedence: explicit ``providers.ollama.base_url`` (wires local endpoints without changing the+ active provider) → active ``model.base_url`` when the active provider is ollama, or custom AND+ the endpoint actually serves ``/api/tags`` (otherwise the picker would probe an unrelated+ endpoint and hide the local catalog) → ``OLLAMA_HOST`` → Ollama's local default."""from hermes_cli.models import _get_model_config_dict, should_use_ollama_native_catalogconfigured = _configured_ollama_base_url()@@ -77,9 +109,6 @@ def _get_ollama_base_url() -> str:if model_provider == "ollama" and model_base:return model_baseif model_provider == "custom" and model_base:- # Only reuse the active bare custom endpoint when it is actually Ollama-compatible;- # otherwise the Ollama picker would probe an unrelated endpoint's /api/tags and hide the- # local Ollama catalog.try:if should_use_ollama_native_catalog("custom", model_base):return model_base@@ -88,51 +117,37 @@ def _get_ollama_base_url() -> str: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 _ollama_host_from_env(env_host)return "http://localhost:11434"+def _api_key_from_provider_config(entry: dict, *env_keys: str) -> str:+ """``api_key`` from a provider config block, else the env var named by the first set *env_keys*."""+ api_key = str(entry.get("api_key") or "").strip()+ if api_key:+ return api_key+ key_env = str(next((entry.get(k) for k in env_keys if entry.get(k)), "") or "").strip()+ return os.getenv(key_env, "").strip() if key_env else ""+++def _drop_authorization(headers: dict[str, str]) -> None:+ for key in tuple(headers):+ if key.lower() == "authorization":+ del headers[key]++def _get_ollama_request_headers() -> dict[str, str]:"""Return configured headers and credentials for native Ollama requests."""from hermes_cli.models import _get_provider_config_dictentry = _get_provider_config_dict("ollama")- raw = entry.get("extra_headers")try:from hermes_cli.config import normalize_extra_headers- result = normalize_extra_headers(raw)+ result = normalize_extra_headers(entry.get("extra_headers"))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 ""+ api_key = _api_key_from_provider_config(entry, "key_env", "api_key_env")if api_key and not any(key.lower() == "authorization" for key in result):result["Authorization"] = f"Bearer {api_key}"return result@@ -143,7 +158,11 @@ def _get_ollama_native_headers(*,api_key: Optional[str] = None,) -> dict[str, str]:- """Resolve Ollama credentials and headers for one endpoint origin."""+ """Resolve Ollama credentials and headers for one endpoint origin.++ Configured headers apply only when *base_url* shares the configured Ollama root; an explicit+ *api_key* replaces any configured Authorization variant rather than inheriting it.+ """from hermes_cli.models import _get_ollama_request_headersconfigured_base = _configured_ollama_base_url()explicit_key = str(api_key or "").strip()@@ -152,11 +171,7 @@ def _get_ollama_native_headers(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]+ _drop_authorization(headers)headers["Authorization"] = f"Bearer {explicit_key}"return headers@@ -168,8 +183,6 @@ _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@@ -183,27 +196,16 @@ def _evict_related_ollama_cache_entries(key: str) -> 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]- )+ _evict_related_ollama_cache_entries(next(iter(cache)).split("|timeout:", 1)[0])cache[key] = valuedef _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+ if not headers:+ return root+ 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")+ return f"{root}|headers:{hashlib.blake2b(header_blob, digest_size=8).hexdigest()}"def _parse_ollama_tags(payload: Any) -> Optional[list[str]]:@@ -212,13 +214,11 @@ def _parse_ollama_tags(payload: Any) -> Optional[list[str]]:if not isinstance(raw_models, list):return Nonemodels: list[str] = []- seen: set[str] = set()for item in raw_models:if not isinstance(item, dict):return Nonemodel_id = str(item.get("model") or item.get("name") or "").strip()- if model_id and model_id not in seen:- seen.add(model_id)+ if model_id and model_id not in models:models.append(model_id)if raw_models and not models:return None@@ -233,9 +233,8 @@ def probe_ollama_local_models("""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.+ (possibly empty) when ``/api/tags`` was reachable — Ollama's authoritative local catalog+ (``/v1/models`` is not required for local servers)."""from hermes_cli.models import _HERMES_USER_AGENT, _get_ollama_base_url, _urlopen_model_catalog_requestroot = _root_for_ollama_native_api(base_url or _get_ollama_base_url())@@ -244,33 +243,25 @@ def probe_ollama_local_models(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)+ if cached is not None and time.monotonic() - cached[1] < _OLLAMA_LOCAL_MODELS_CACHE_TTL:+ return list(cached[0])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)- def _unreachable() -> None:- _remember_ollama_cache(_OLLAMA_LOCAL_PROBE_REACHABLE, cache_key, False)- _remember_ollama_cache(_OLLAMA_LOCAL_PROBE_FAILURE_CACHE, failure_key, time.monotonic())-try:request_headers = {"User-Agent": _HERMES_USER_AGENT, **(headers or {})}req = urllib.request.Request(root.rstrip("/") + "/api/tags", headers=request_headers)with _urlopen_model_catalog_request(req, timeout=timeout) as resp:- payload = json.loads(resp.read().decode())+ models = _parse_ollama_tags(json.loads(resp.read().decode()))except (ValueError, OSError, TimeoutError, http.client.HTTPException, urllib.error.URLError,json.JSONDecodeError, UnicodeDecodeError):- _unreachable()- return None-- models = _parse_ollama_tags(payload)+ models = Noneif models is None:- _unreachable()+ _remember_ollama_cache(_OLLAMA_LOCAL_PROBE_REACHABLE, cache_key, False)+ _remember_ollama_cache(_OLLAMA_LOCAL_PROBE_FAILURE_CACHE, failure_key, time.monotonic())return None_remember_ollama_cache(_OLLAMA_LOCAL_PROBE_REACHABLE, cache_key, True)_OLLAMA_LOCAL_PROBE_FAILURE_CACHE.pop(failure_key, None)@@ -305,6 +296,10 @@ def _same_ollama_native_root(left: str, right: str) -> bool:return False+_NEVER_OLLAMA_PROVIDERS = frozenset({"openrouter", "nous", "anthropic", "openai", "openai-codex", "gemini", "ollama-cloud"})+_LOCAL_LIKE_PROVIDERS = frozenset({"", "custom", "local", "llamacpp", "llama.cpp", "llama-cpp", "vllm"})++def should_use_ollama_native_catalog(provider: Optional[str],base_url: Optional[str],@@ -329,7 +324,7 @@ def should_use_ollama_native_catalog(except ValueError:pass- if requested in {"openrouter", "nous", "anthropic", "openai", "openai-codex", "gemini", "ollama-cloud"}:+ if requested in _NEVER_OLLAMA_PROVIDERS:return Falseconfigured_base = _configured_ollama_base_url()@@ -346,16 +341,14 @@ def should_use_ollama_native_catalog(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:"):+ if requested not in _LOCAL_LIKE_PROVIDERS and not requested.startswith("custom:"):return Falseif requested == "custom:ollama" or requested.endswith("-ollama"):return Truetry:- parsed = urllib.parse.urlparse(root)- if parsed.port != 11434:+ if urllib.parse.urlparse(root).port != _OLLAMA_DEFAULT_PORT:return Falseexcept ValueError:return False@@ -365,7 +358,8 @@ def should_use_ollama_native_catalog(def _ollama_local_catalog(force_refresh: bool) -> list[str]:"""Catalog for the raw ``ollama`` provider: native ``/api/tags`` when the endpoint is a real- Ollama server, else the OpenAI-style ``/v1/models`` of the configured gateway."""+ Ollama server, else the OpenAI-style ``/v1/models`` of the configured gateway (incl. Ollama+ Cloud)."""from hermes_cli.models import _get_ollama_base_url, _get_ollama_native_headers, _get_provider_config_dict, fetch_api_models, fetch_ollama_local_models, should_use_ollama_native_catalogif force_refresh:_OLLAMA_LOCAL_MODELS_CACHE.clear()@@ -381,31 +375,20 @@ def _ollama_local_catalog(force_refresh: bool) -> list[str]: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 []- # Non-native Ollama-compatible endpoints (incl. Ollama Cloud) and gateways exposing 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_key = _api_key_from_provider_config(config, "key_env")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)return fetch_api_models(fallback_key, fallback_base, headers=fallback_headers or None) or []def _lmstudio_server_root(base_url: Optional[str]) -> Optional[str]:- """Return the LM Studio server root for native ``/api/v1`` endpoints.+ """LM Studio server root for native ``/api/v1`` endpoints.- Users commonly copy either the OpenAI-compatible runtime URL (``.../v1``) or the native API- prefix (``.../api`` / ``.../api/v1``). Native probes append ``/api/v1/...`` themselves, so- normalize all accepted forms back to the bare server root to avoid ``/api/api/v1`` requests.+ Users paste either the OpenAI runtime URL (``.../v1``) or the native prefix (``.../api`` /+ ``.../api/v1``); native probes append ``/api/v1/...`` themselves, so strip all accepted forms."""- root = (base_url or "").strip().rstrip("/")- for suffix in ("/api/v1", "/api", "/v1"):- if root.endswith(suffix):- root = root[: -len(suffix)].rstrip("/")- break- return root or None+ return _strip_suffixes((base_url or "").strip().rstrip("/"), ("/api/v1", "/api", "/v1")) or Nonedef _lmstudio_request_headers(api_key: Optional[str] = None) -> dict:@@ -423,14 +406,16 @@ def _lmstudio_fetch_raw_models(base_url: Optional[str] = None,timeout: float = 5.0,) -> Optional[list[dict]]:- """Fetch the raw model list from LM Studio's ``/api/v1/models``."""+ """Fetch the raw model list from LM Studio's ``/api/v1/models``.++ None on network errors / malformed payloads; raises ``AuthError`` on HTTP 401/403.+ """from hermes_cli.models import _urlopen_model_catalog_requestserver_root = _lmstudio_server_root(base_url)if not server_root:return None- headers = _lmstudio_request_headers(api_key)- request = urllib.request.Request(server_root + "/api/v1/models", headers=headers)+ request = urllib.request.Request(server_root + "/api/v1/models", headers=_lmstudio_request_headers(api_key))try:with _urlopen_model_catalog_request(request, timeout=timeout) as resp:payload = json.loads(resp.read().decode())@@ -455,6 +440,22 @@ def _lmstudio_fetch_raw_models(return raw_models+def _lmstudio_raw_models_or_none(api_key, base_url, timeout) -> Optional[list[dict]]:+ """``_lmstudio_fetch_raw_models`` with every failure (incl. AuthError) collapsed to None."""+ from hermes_cli.models import _lmstudio_fetch_raw_models+ try:+ return _lmstudio_fetch_raw_models(api_key=api_key, base_url=base_url, timeout=timeout)+ except Exception:+ return None+++def _lmstudio_entry_for(raw_models: list, model: str) -> Optional[dict]:+ for raw in raw_models:+ if isinstance(raw, dict) and (raw.get("key") == model or raw.get("id") == model):+ return raw+ return None++def probe_lmstudio_models(api_key: Optional[str] = None,base_url: Optional[str] = None,@@ -462,10 +463,9 @@ def probe_lmstudio_models() -> Optional[list[str]]:"""Probe LM Studio's model listing.- Returns chat-capable model keys, including a valid empty list when the server is reachable- but has no non-embedding models; returns ``None`` on network errors, malformed responses, or- bad base URLs. Raises ``AuthError`` on HTTP 401/403 so token issues surface separately from- reachability.+ Returns chat-capable model keys — a valid empty list when the server is reachable but has no+ non-embedding models; ``None`` on network errors, malformed responses, or bad base URLs.+ Raises ``AuthError`` on HTTP 401/403 so token issues surface separately from reachability."""from hermes_cli.models import _lmstudio_fetch_raw_modelsraw_models = _lmstudio_fetch_raw_models(api_key=api_key, base_url=base_url, timeout=timeout)@@ -474,9 +474,7 @@ def probe_lmstudio_models(keys: list[str] = []for raw in raw_models:- if not isinstance(raw, dict):- continue- if str(raw.get("type") or "").strip().lower() == "embedding":+ if not isinstance(raw, dict) or str(raw.get("type") or "").strip().lower() == "embedding":continuekey = str(raw.get("key") or raw.get("id") or "").strip()if key and key not in keys:@@ -489,16 +487,10 @@ def fetch_lmstudio_models(base_url: Optional[str] = None,timeout: float = 5.0,) -> list[str]:- """Fetch LM Studio chat-capable model keys from native ``/api/v1/models``.-- Embedding models are filtered out; network errors, malformed responses, and bad base URLs- yield an empty list. Raises ``AuthError`` on HTTP 401/403 so callers can distinguish a- missing or wrong ``LM_API_KEY`` from an unreachable server — the most common LM Studio- support case.- """+ """LM Studio chat-capable model keys; ``[]`` when unreachable/malformed. Raises ``AuthError`` on+ HTTP 401/403 so callers can tell a wrong ``LM_API_KEY`` from an unreachable server."""from hermes_cli.models import probe_lmstudio_models- models = probe_lmstudio_models(api_key=api_key, base_url=base_url, timeout=timeout)- return models or []+ return probe_lmstudio_models(api_key=api_key, base_url=base_url, timeout=timeout) or []class LMStudioLoadResult(NamedTuple):@@ -509,6 +501,25 @@ class LMStudioLoadResult(NamedTuple):rejected: bool = False+def _positive_int(value: Any) -> Optional[int]:+ if isinstance(value, int) and not isinstance(value, bool) and value > 0:+ return value+ return None+++def _lmstudio_loaded_context(entry: Optional[dict]) -> Optional[int]:+ """First positive ``loaded_instances[*].config.context_length`` of a model entry."""+ instances = entry.get("loaded_instances") if entry is not None else None+ if not isinstance(instances, list):+ return None+ for instance in instances:+ config = instance.get("config") if isinstance(instance, dict) else None+ parsed = _positive_int(config.get("context_length") if isinstance(config, dict) else None)+ if parsed is not None:+ return parsed+ return None++def ensure_lmstudio_model_loaded(model: str,base_url: Optional[str],@@ -524,40 +535,12 @@ def ensure_lmstudio_model_loaded(caller supplied an explicit override; the returned context must come from LM Studio's echoed orrefreshed state."""- from hermes_cli.models import _lmstudio_fetch_raw_models, _urlopen_model_catalog_request-- def _result(- context_length: Optional[int],- *,- load_attempted: bool = False,- rejected: bool = False,- ) -> Optional[int] | LMStudioLoadResult:+ from hermes_cli.models import _urlopen_model_catalog_request++ def _result(context_length: Optional[int], *, load_attempted: bool = False, rejected: bool = False):value = LMStudioLoadResult(context_length, load_attempted, rejected)return value if return_load_result else context_length- def _positive_int(value: Any) -> Optional[int]:- if isinstance(value, int) and not isinstance(value, bool) and value > 0:- return value- return None-- def _loaded_context(entry: dict) -> Optional[int]:- instances = entry.get("loaded_instances")- if not isinstance(instances, list):- return None- for instance in instances:- config = instance.get("config") if isinstance(instance, dict) else None- context = config.get("context_length") if isinstance(config, dict) else None- parsed = _positive_int(context)- if parsed is not None:- return parsed- return None-- def _find_entry(raw_models: list[dict]) -> Optional[dict]:- for raw in raw_models:- if isinstance(raw, dict) and (raw.get("key") == model or raw.get("id") == model):- return raw- return None-server_root = _lmstudio_server_root(base_url)if not server_root:return _result(None)@@ -566,16 +549,8 @@ def ensure_lmstudio_model_loaded(if target_context_length is not None and explicit_context is None:return _result(None)- headers = _lmstudio_request_headers(api_key)-- try:- raw_models = _lmstudio_fetch_raw_models(api_key=api_key, base_url=base_url, timeout=10)- except Exception:- raw_models = None- if raw_models is None:- return _result(None)-- target_entry = _find_entry(raw_models)+ raw_models = _lmstudio_raw_models_or_none(api_key, base_url, 10)+ target_entry = _lmstudio_entry_for(raw_models, model) if raw_models is not None else Noneif target_entry is None:return _result(None)@@ -583,7 +558,7 @@ def ensure_lmstudio_model_loaded(if explicit_context is not None and max_ctx is not None and explicit_context > max_ctx:return _result(None, rejected=True)- current_context = _loaded_context(target_entry)+ current_context = _lmstudio_loaded_context(target_entry)if current_context is not None:return _result(current_context)@@ -594,13 +569,11 @@ def ensure_lmstudio_model_loaded(load_payload: dict[str, Any] = {"model": model, "echo_load_config": True}if explicit_context is not None:load_payload["context_length"] = explicit_context- body = json.dumps(load_payload).encode()- load_headers = dict(headers)- load_headers["Content-Type"] = "application/json"+ load_headers = {**_lmstudio_request_headers(api_key), "Content-Type": "application/json"}try:load_request = urllib.request.Request(server_root + "/api/v1/models/load",- data=body,+ data=json.dumps(load_payload).encode(),headers=load_headers,method="POST",)@@ -614,23 +587,14 @@ def ensure_lmstudio_model_loaded(except Exception:response_payload = Noneload_config = response_payload.get("load_config") if isinstance(response_payload, dict) else None- applied_context = (- _positive_int(load_config.get("context_length"))- if isinstance(load_config, dict)- else None- )+ applied_context = _positive_int(load_config.get("context_length")) if isinstance(load_config, dict) else Noneif applied_context is not None:return _result(applied_context, load_attempted=True)- try:- refreshed_models = _lmstudio_fetch_raw_models(api_key=api_key, base_url=base_url, timeout=10)- except Exception:- refreshed_models = None+ refreshed_models = _lmstudio_raw_models_or_none(api_key, base_url, 10)if refreshed_models is None:return _result(None, load_attempted=True)- refreshed_entry = _find_entry(refreshed_models)- refreshed_context = _loaded_context(refreshed_entry) if refreshed_entry is not None else None- return _result(refreshed_context, load_attempted=True)+ return _result(_lmstudio_loaded_context(_lmstudio_entry_for(refreshed_models, model)), load_attempted=True)def lmstudio_model_reasoning_options(@@ -639,31 +603,16 @@ def lmstudio_model_reasoning_options(api_key: Optional[str] = None,timeout: float = 5.0,) -> list[str]:- """Return the reasoning ``allowed_options`` LM Studio publishes for ``model``.-- Reads ``capabilities.reasoning.allowed_options`` from ``/api/v1/models``; returns ``[]``- when the model is unknown, the endpoint is unreachable, or no reasoning capability is- declared.- """- from hermes_cli.models import _lmstudio_fetch_raw_models- try:- raw_models = _lmstudio_fetch_raw_models(api_key=api_key, base_url=base_url, timeout=timeout)- except Exception:- raw_models = None- if not raw_models:- return []-- for raw in raw_models:- if not isinstance(raw, dict):- continue- if raw.get("key") != model and raw.get("id") != model:- continue- caps = raw.get("capabilities")- reasoning = caps.get("reasoning") if isinstance(caps, dict) else None- opts = reasoning.get("allowed_options") if isinstance(reasoning, dict) else None- if isinstance(opts, list):- return [str(o).strip().lower() for o in opts if isinstance(o, str)]+ """Reasoning ``allowed_options`` LM Studio publishes for ``model`` under+ ``capabilities.reasoning`` in ``/api/v1/models``; ``[]`` when unknown, unreachable, or absent."""+ raw = _lmstudio_entry_for(_lmstudio_raw_models_or_none(api_key, base_url, timeout) or [], model)+ if raw is None:return []+ caps = raw.get("capabilities")+ reasoning = caps.get("reasoning") if isinstance(caps, dict) else None+ opts = reasoning.get("allowed_options") if isinstance(reasoning, dict) else None+ if isinstance(opts, list):+ return [str(o).strip().lower() for o in opts if isinstance(o, str)]return []@@ -673,28 +622,23 @@ def ollama_model_supports_thinking(api_key: Optional[str] = None,timeout: float = 5.0,) -> Optional[bool]:- """Return True if an Ollama (Cloud or local) model advertises ``thinking``.+ """Tri-state: True if an Ollama (Cloud or local) model advertises ``thinking``.- Probes native ``/api/show`` and checks ``capabilities`` — the authoritative source, since- the OpenAI-compat ``/v1/models`` endpoint omits it. Tri-state: True when ``thinking`` is- declared, False when the probe succeeded without it, None when the probe failed so the- caller picks the fallback (treated as "don't emit").+ Probes native ``/api/show`` ``capabilities`` — the authoritative source, since OpenAI-compat+ ``/v1/models`` omits it. False when the probe succeeded without it; None when the probe failed+ so the caller picks the fallback (treated as "don't emit")."""import httpxserver_url = (base_url or "").strip().rstrip("/")if server_url.endswith("/v1"):server_url = server_url[:-3]- if not server_url:- return None-bare_model = _strip_ollama_cloud_suffix((model or "").strip())- if not bare_model:+ if not server_url or not bare_model:return Nonetoken = str(api_key or "").strip()headers = {"Authorization": f"Bearer {token}"} if token else {}-try:with httpx.Client(timeout=timeout, headers=headers) as client:resp = client.post(f"{server_url}/api/show", json={"name": bare_model})@@ -712,12 +656,8 @@ _OLLAMA_CLOUD_CACHE_TTL = 3600 # 1 hourdef _strip_ollama_cloud_suffix(model_id: str) -> str:- """Strip :cloud / -cloud suffixes that models.dev appends to Ollama Cloud IDs.-- The live API uses clean IDs (e.g. 'kimi-k2.6') while models.dev sometimes returns them as- 'kimi-k2.6:cloud'. Normalising before the dedup merge prevents duplicate entries in the merged- model list.- """+ """Strip the ``:cloud`` / ``-cloud`` suffix models.dev appends to Ollama Cloud IDs (the live+ API uses bare ids), so the dedup merge does not produce duplicates."""for suffix in (":cloud", "-cloud"):if model_id.endswith(suffix):return model_id[: -len(suffix)]@@ -725,7 +665,6 @@ def _strip_ollama_cloud_suffix(model_id: str) -> str:def _ollama_cloud_cache_path() -> Path:- """Return the path for the Ollama Cloud model cache."""from hermes_constants import get_hermes_homereturn get_hermes_home() / "ollama_cloud_models_cache.json"@@ -764,34 +703,22 @@ def fetch_ollama_cloud_models(*,force_refresh: bool = False,) -> list[str]:- """Fetch Ollama Cloud models by merging live API + models.dev, with disk cache.-- Resolution order: 1. Disk cache (if fresh, < 1 hour, and not force_refresh) 2. Live- ``/v1/models`` endpoint (primary — freshest source) 3. models.dev registry (secondary — fills- gaps for unlisted models) 4. Merge: live models first, then models.dev additions (deduped)-- Returns a list of model IDs (never None — empty list on total failure).- """+ """Ollama Cloud models: fresh disk cache (< 1h, unless force_refresh) → live ``/v1/models``+ (freshest) merged with models.dev additions (deduped, live first) → stale cache → ``[]``.+ Never None."""from hermes_cli.models import fetch_api_models- # 1. Check disk cacheif not force_refresh:cached = _load_ollama_cloud_cache()if cached is not None:return cached["models"]- # 2. Live API probe- if not api_key:- api_key = os.getenv("OLLAMA_API_KEY", "")- if not base_url:- base_url = os.getenv("OLLAMA_BASE_URL", "") or "https://ollama.com/v1"+ api_key = api_key or os.getenv("OLLAMA_API_KEY", "")+ base_url = base_url or os.getenv("OLLAMA_BASE_URL", "") or "https://ollama.com/v1"live_models: list[str] = []if api_key:- result = fetch_api_models(api_key, base_url, timeout=8.0)- if result:- live_models = result+ live_models = fetch_api_models(api_key, base_url, timeout=8.0) or []- # 3. models.dev registrymdev_models: list[str] = []try:from agent.models_dev import list_agentic_models@@ -799,26 +726,13 @@ def fetch_ollama_cloud_models(except Exception:pass- # 4. Merge: live first, then models.dev additions (deduped, order-preserving)- if live_models or mdev_models:- seen: set[str] = set()- merged: list[str] = []- for m in live_models:- if m and m not in seen:- seen.add(m)- merged.append(m)- for m in mdev_models:- normalized = _strip_ollama_cloud_suffix(m)- if normalized and normalized not in seen:- seen.add(normalized)- merged.append(normalized)- if merged:- _save_ollama_cloud_cache(merged)- return merged-- # Total failure — return stale cache if available (ignore TTL)- stale = _load_ollama_cloud_cache(ignore_ttl=True)- if stale is not None:- return stale["models"]+ merged: list[str] = []+ for m in [*live_models, *(_strip_ollama_cloud_suffix(m) for m in mdev_models)]:+ if m and m not in merged:+ merged.append(m)+ if merged:+ _save_ollama_cloud_cache(merged)+ return merged- return []+ stale = _load_ollama_cloud_cache(ignore_ttl=True)+ return stale["models"] if stale is not None else []