The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hclib): models/runtime — models, inventory, runtime_provider, provider catalog, local_runtime, banner
Teknium3ffd44acd373
diff --git a/hermes_cli/azure_detect.py b/hermes_cli/azure_detect.pyindex 7638ed6aca9..d5e24c2039c 100644--- a/hermes_cli/azure_detect.py+++ b/hermes_cli/azure_detect.py@@ -1,38 +1,8 @@"""Azure Foundry endpoint auto-detection.-Inspect a Microsoft Foundry / Azure OpenAI endpoint to determine:- - API transport (OpenAI-style ``chat_completions`` vs- Anthropic-style ``anthropic_messages``)- - Available models (best effort — Azure does not expose a deployment- listing via the inference API key, but Azure OpenAI v1 endpoints- return the resource's model catalog via ``GET /models``)- - Context length for each discovered/entered model, via the existing- :func:`agent.model_metadata.get_model_context_length` resolver.--Rationale:--Azure has no pure-API-key deployment-listing endpoint — per Microsoft,-deployment enumeration requires ARM management-plane auth. Azure-OpenAI v1 endpoints ``{resource}.openai.azure.com/openai/v1`` do return-a ``/models`` list, but it reflects the resource's *available* models-rather than the user's *deployed* deployment names. In practice it is-still a useful hint — the user picks a familiar model name and we look-up its context length from the catalog.--Authentication modes:- - ``api_key`` (default): the wizard passes an ``api_key`` string; the- probe sends both ``api-key:`` and ``Authorization: Bearer`` headers- so we hit any Azure deployment regardless of which header it expects.- - ``entra_id``: the wizard passes a ``token_provider`` callable from- :mod:`agent.azure_identity_adapter`. The probe mints exactly one- bearer JWT, sends **only** ``Authorization: Bearer <jwt>`` (never- ``api-key:``), and never persists the token. This matches Microsoft's- documented contract for keyless inference.--The detector never crashes on errors (every HTTP call is wrapped in a-broad try/except). Callers get a :class:`DetectionResult` with whatever-information could be gathered, and fall back to manual entry for the-rest.+The detector never crashes on errors (every HTTP call is wrapped in a broad try/except). Callers get+a :class:`DetectionResult` with whatever information could be gathered, and fall back to manual+entry for the rest."""from __future__ import annotations@@ -96,55 +66,40 @@ def _resolve_credential(api_key: Any,) -> tuple[Optional[str], str]:"""Coerce wizard inputs into a (token, mode) pair.- Returns ``(token_or_None, mode)`` where ``mode`` is:- - ``"entra_id"`` when a callable token provider was supplied — the- returned token is a freshly minted bearer JWT, sent ONLY in- ``Authorization: Bearer``.- - ``"api_key"`` when a string key was supplied — the returned token- is the raw API key, sent in BOTH ``api-key:`` and- ``Authorization: Bearer`` headers (preserves the original- broad-compat probe behaviour).- - ``("", "api_key")`` when neither yields a value.-- Bearer minting failures degrade to ``("", "entra_id")`` so the caller- can still report "detection incomplete" rather than crashing.+ Returns ``(token_or_None, mode)`` where ``mode`` is: - ``"entra_id"`` when a callable token+ provider was supplied — the returned token is a freshly minted bearer JWT, sent ONLY in+ ``Authorization: Bearer``."""# Token-provider path (callable wins when both supplied).- if token_provider is not None and callable(token_provider):- try:- token = token_provider()- return (str(token) if token else None), "entra_id"- except Exception as exc:- logger.debug("azure_detect: token_provider failed: %s", exc)- return None, "entra_id"- if callable(api_key) and not isinstance(api_key, str):- try:- token = api_key()- return (str(token) if token else None), "entra_id"- except Exception as exc:- logger.debug("azure_detect: api_key callable failed: %s", exc)- return None, "entra_id"+ for provider, label in ((token_provider, "token_provider"), (api_key, "api_key callable")):+ if callable(provider) and not isinstance(provider, str):+ try:+ token = provider()+ return (str(token) if token else None), "entra_id"+ except Exception as exc:+ logger.debug("azure_detect: %s failed: %s", label, exc)+ return None, "entra_id"# API-key path.if isinstance(api_key, str) and api_key:return api_key, "api_key"return None, "api_key"-def _apply_auth_headers(req: urllib_request.Request,- token: Optional[str],- mode: str) -> None:- """Attach the right auth headers to ``req`` based on credential mode."""- if not token:- return- if mode == "entra_id":- # Bearer-only: do NOT also set api-key, which would log a JWT in- # a header slot intended for static keys.- req.add_header("Authorization", f"Bearer {token}")- else:- # Legacy broad-compat behaviour: send both headers so we land on- # any Azure resource regardless of which it accepts.- req.add_header("api-key", token)+def _authed_request(url: str, api_key: Any, token_provider, *, method: str = "GET",+ data: Optional[bytes] = None) -> urllib_request.Request:+ """Build a request carrying the right auth headers for the credential mode."""+ token, mode = _resolve_credential(api_key, token_provider)+ req = urllib_request.Request(url, method=method, data=data)+ if token:+ if mode != "entra_id":+ # Legacy broad-compat behaviour: send both headers so we land on+ # any Azure resource regardless of which it accepts.+ req.add_header("api-key", token)+ # Bearer-only in entra_id mode: do NOT also set api-key, which would+ # log a JWT in a header slot intended for static keys.req.add_header("Authorization", f"Bearer {token}")+ req.add_header("User-Agent", "hermes-agent/azure-detect")+ return reqdef _http_get_json(url: str,@@ -155,10 +110,7 @@ def _http_get_json(url: str,) -> tuple[int, Optional[dict]]:"""GET a URL with the appropriate auth headers. Return``(status_code, parsed_json_or_None)``. Never raises."""- token, mode = _resolve_credential(api_key, token_provider)- req = urllib_request.Request(url, method="GET")- _apply_auth_headers(req, token, mode)- req.add_header("User-Agent", "hermes-agent/azure-detect")+ req = _authed_request(url, api_key, token_provider)try:with open_credentialed_url(req, timeout=timeout) as resp:body = resp.read()@@ -182,9 +134,9 @@ def _strip_trailing_v1(url: str) -> str:def _looks_like_anthropic_path(url: str) -> bool:- """Return True when the URL's path ends in ``/anthropic`` or- contains a ``/anthropic/`` segment. Used by Azure Foundry- resources that route Claude traffic through a dedicated path."""+ """Return True when the URL's path ends in ``/anthropic`` or contains a ``/anthropic/`` segment.+ Used by Azure Foundry resources that route Claude traffic through a dedicated path.+ """try:parsed = urlparse(url)path = (parsed.path or "").lower().rstrip("/")@@ -215,20 +167,15 @@ def _probe_openai_models(base_url: str,*,token_provider: Optional[Callable[[], str]] = None,) -> tuple[bool, list[str]]:- """Probe ``<base>/models`` for an OpenAI-shaped response.-- Returns ``(ok, models)``. ``ok`` is True iff the endpoint accepted- us as an OpenAI-style caller (200 OK + OpenAI-shaped JSON body).- """+ """Probe ``<base>/models`` for an OpenAI-shaped response."""base_url = base_url.rstrip("/")# Azure OpenAI v1: {resource}.openai.azure.com/openai/v1 — no# api-version required for GA paths, so probe without first.- candidates = [f"{base_url}/models"]# Fallback: explicit api-version for pre-v1 resources- for v in _AZURE_OPENAI_PROBE_API_VERSIONS:- candidates.append(f"{base_url}/models?api-version={v}")-+ candidates = [f"{base_url}/models"] + [+ f"{base_url}/models?api-version={v}" for v in _AZURE_OPENAI_PROBE_API_VERSIONS+ ]for url in candidates:status, body = _http_get_json(url, api_key, token_provider=token_provider)if status == 200 and body is not None:@@ -251,11 +198,9 @@ def _probe_anthropic_messages(base_url: str,*,token_provider: Optional[Callable[[], str]] = None,) -> bool:- """Send a zero-token request to ``<base>/v1/messages`` and check- whether the endpoint at least *recognises* the Anthropic Messages- shape (any 4xx that mentions ``messages`` or ``model``, or a 400- ``invalid_request`` with an Anthropic error shape). Never completes- a real chat.+ """Send a zero-token request to ``<base>/v1/messages`` and check whether the endpoint at least+ *recognises* the Anthropic Messages shape (any 4xx that mentions ``messages`` or ``model``, or a+ 400 ``invalid_request`` with an Anthropic error shape). Never completes a real chat."""base = _strip_trailing_v1(base_url)url = f"{base}/v1/messages?api-version={_AZURE_ANTHROPIC_API_VERSION}"@@ -264,12 +209,9 @@ def _probe_anthropic_messages(base_url: str,"max_tokens": 1,"messages": [{"role": "user", "content": "ping"}],}).encode("utf-8")- req = urllib_request.Request(url, method="POST", data=payload)- token, mode = _resolve_credential(api_key, token_provider)- _apply_auth_headers(req, token, mode)+ req = _authed_request(url, api_key, token_provider, method="POST", data=payload)req.add_header("anthropic-version", "2023-06-01")req.add_header("content-type", "application/json")- req.add_header("User-Agent", "hermes-agent/azure-detect")try:with open_credentialed_url(req, timeout=6.0) as resp:# Should never 200 — "probe" isn't a real deployment. But@@ -303,16 +245,14 @@ def detect(base_url: str,) -> DetectionResult:"""Inspect an Azure endpoint and describe its transport + models.- Call this from the wizard before asking the user to pick an API- mode manually. The caller should treat the returned- :class:`DetectionResult` as *advisory* — if ``api_mode`` is None,- fall back to asking the user.+ Call this from the wizard before asking the user to pick an API mode manually. The caller should+ treat the returned :class:`DetectionResult` as *advisory* — if ``api_mode`` is None, fall back+ to asking the user.- ``api_key`` may be a string (legacy API-key auth — sends both- ``api-key:`` and ``Authorization: Bearer``) or a callable returning- a bearer JWT (Entra ID auth — sends ONLY ``Authorization: Bearer``).- ``token_provider`` is an alternative explicit name for the callable- form; if both are supplied the callable wins.+ ``api_key`` may be a string (legacy API-key auth — sends both ``api-key:`` and ``Authorization:+ Bearer``) or a callable returning a bearer JWT (Entra ID auth — sends ONLY ``Authorization:+ Bearer``). ``token_provider`` is an alternative explicit name for the callable form; if both are+ supplied the callable wins."""result = DetectionResult()@@ -367,16 +307,9 @@ def lookup_context_length(model: str,*,token_provider: Optional[Callable[[], str]] = None,) -> Optional[int]:- """Thin wrapper around :func:`agent.model_metadata.get_model_context_length`- that returns ``None`` when only the fallback default (128k) would- fire, so the wizard can distinguish "we actually know this" from- "we guessed.-- For Entra-ID mode pass a callable as ``api_key`` (or via- ``token_provider=``); the wrapped resolver expects a string, so we- mint one bearer JWT here for the single lookup. The resolver itself- only reads catalog metadata over HTTP — no SDK client is built — so- the minted token is consumed for at most one /models probe.+ """Thin wrapper around :func:`agent.model_metadata.get_model_context_length` that returns ``None``+ when only the fallback default (128k) would fire, so the wizard can distinguish "we actually+ know this" from "we guessed."""model_id = str(model or "").strip()if not model_id:@@ -391,11 +324,10 @@ def lookup_context_length(model: str,# Resolve the credential once. For Entra mode this calls the token# provider; for legacy api_key this is a no-op string pass-through.- token, mode = _resolve_credential(api_key, token_provider)- effective_key = token or ""+ token, _mode = _resolve_credential(api_key, token_provider)try:- n = get_model_context_length(model_id, base_url=base_url, api_key=effective_key)+ n = get_model_context_length(model_id, base_url=base_url, api_key=token or "")except Exception as exc:logger.debug("azure_detect: context length lookup failed: %s", exc)return Nonediff --git a/hermes_cli/banner.py b/hermes_cli/banner.pyindex d69faf1c924..02d7439a821 100644--- a/hermes_cli/banner.py+++ b/hermes_cli/banner.py@@ -1,7 +1,4 @@-"""Welcome banner, ASCII art, skills summary, and update check for the CLI.--Pure display functions with no HermesCLI state dependency.-"""+"""Welcome banner, ASCII art, skills summary, and update check for the CLI."""import jsonimport loggingimport os@@ -40,13 +37,10 @@ def cprint(text: str):"""Print ANSI-colored text through prompt_toolkit's renderer."""from prompt_toolkit import print_formatted_text as _pt_printfrom prompt_toolkit.formatted_text import ANSI as _PT_ANSI- try:- _pt_print(_PT_ANSI(text))- except Exception:- # prompt_toolkit needs a real console. On Windows, a redirected or- # absent stdout (pythonw.exe, CI, `hermes ... > file`) raises- # NoConsoleScreenBufferError from its Win32Output — display helpers- # must never crash the caller over that, so degrade to plain print.+ # prompt_toolkit needs a real console. On Windows, a redirected or absent stdout (pythonw.exe,+ # CI, `hermes ... > file`) raises NoConsoleScreenBufferError from its Win32Output — display+ # helpers must never crash the caller over that, so degrade to plain print.+ if _quiet(lambda: _pt_print(_PT_ANSI(text)) or True) is None:print(text)@@ -54,13 +48,23 @@ def cprint(text: str):# Skin-aware color helpers# =========================================================================-def _skin_color(key: str, fallback: str) -> str:- """Get a color from the active skin, or return fallback."""+def _quiet(fn, default=None):+ """``fn()``, or ``default`` on any exception — for best-effort display inputs."""try:- from hermes_cli.skin_engine import get_active_skin- return get_active_skin().get_color(key, fallback)+ return fn()except Exception:- return fallback+ return default+++def _active_skin():+ """The active skin object, or None when the skin engine is unavailable."""+ from hermes_cli.skin_engine import get_active_skin+ return get_active_skin()+++def _skin_color(key: str, fallback: str) -> str:+ """Get a color from the active skin, or return fallback."""+ return _quiet(lambda: _active_skin().get_color(key, fallback), fallback)# =========================================================================# ASCII Art & Branding# =========================================================================@@ -91,40 +95,53 @@ HERMES_CADUCEUS = """[#CD7F32]⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡀⠀⣀⣀[#B8860B]⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀[/]"""-# =========================================================================# Skills scanning# =========================================================================-_available_skills_cache: Optional[tuple] = None # (result,) once computed+# Per-process caches: ``None`` until computed, then a 1-tuple ``(value,)`` so a computed ``None``+# is distinguishable from "not yet computed". Reset by assigning ``None`` (tests, ``hermes skills``).+_available_skills_cache: Optional[tuple] = None+_git_banner_state_cache: Optional[tuple] = None+_latest_release_cache: Optional[tuple] = None+++_UNCACHED = object() # compute() result that must not be memoized+++def _memo(cache_name: str, compute):+ """Return the cached value under module global ``cache_name``, computing (and storing) it once."""+ cached = globals()[cache_name]+ if cached is not None:+ return cached[0]+ value = compute()+ if value is not _UNCACHED:+ globals()[cache_name] = (value,)+ return valuedef get_available_skills() -> Dict[str, List[str]]:"""Return skills grouped by category, filtered by platform and disabled state.- Delegates to ``_find_all_skills()`` from ``tools/skills_tool`` which already- handles platform gating (``platforms:`` frontmatter) and respects the- user's ``skills.disabled`` config list.-- Cached per-process: this feeds only the startup banner, whose snapshot- is taken once anyway, and the underlying skills-tree walk costs ~100ms.- ``prefetch_banner_data()`` uses the cache to pay that walk off-thread.+ Cached per-process: this feeds only the startup banner, whose snapshot is taken once anyway, and+ the underlying skills-tree walk costs ~100ms. ``prefetch_banner_data()`` uses the cache to pay+ that walk off-thread. A failed scan yields ``{}`` and is not cached."""- global _available_skills_cache- if _available_skills_cache is not None:- return _available_skills_cache[0]- try:+ def _scan():from tools.skills_tool import _find_all_skills- all_skills = _find_all_skills() # already filtered- except Exception:- return {}+ return _find_all_skills() # already filtered- skills_by_category: Dict[str, List[str]] = {}- for skill in all_skills:- category = skill.get("category") or "general"- skills_by_category.setdefault(category, []).append(skill["name"])- _available_skills_cache = (skills_by_category,)- return skills_by_category+ def _compute():+ all_skills = _quiet(_scan)+ if all_skills is None:+ return _UNCACHED+ skills_by_category: Dict[str, List[str]] = {}+ for skill in all_skills:+ skills_by_category.setdefault(skill.get("category") or "general", []).append(skill["name"])+ return skills_by_category++ result = _memo("_available_skills_cache", _compute)+ return {} if result is _UNCACHED else result# =========================================================================@@ -147,62 +164,80 @@ def _canonical_github_remote(url: str | None) -> str:if not url:return ""value = url.strip()- if value.startswith("[email protected]:"):- value = "github.com/" + value[len("[email protected]:"):]- elif value.startswith("ssh://[email protected]/"):- value = "github.com/" + value[len("ssh://[email protected]/"):]+ for ssh_prefix in ("[email protected]:", "ssh://[email protected]/"):+ if value.startswith(ssh_prefix):+ value = "github.com/" + value[len(ssh_prefix):]+ breakelse:parsed = urlparse(value)if parsed.netloc and parsed.path:value = f"{parsed.netloc}{parsed.path}"- value = value.strip().rstrip("/")- if value.endswith(".git"):- value = value[:-4]- return value.lower()+ return value.strip().rstrip("/").removesuffix(".git").lower()-def _is_ssh_remote(url: str | None) -> bool:- if not url:+def _is_official_ssh_remote(url: str | None) -> bool:+ if not url or not url.strip().lower().startswith(("git@", "ssh://")):return False- value = url.strip().lower()- return value.startswith("git@") or value.startswith("ssh://")+ return _canonical_github_remote(url) == _OFFICIAL_REPO_CANONICAL-def _is_official_ssh_remote(url: str | None) -> bool:- return _is_ssh_remote(url) and _canonical_github_remote(url) == _OFFICIAL_REPO_CANONICAL+_GIT_TEXT_KW = {"text": True, "encoding": "utf-8", "errors": "replace"}-def _git_stdout(args: list[str], *, cwd: Path, timeout: int = 5) -> Optional[str]:+def _git_run(+ args: list[str], *, cwd: Optional[Path] = None, timeout: int = 5, text: bool = True, network: bool = False+):+ """Run ``git <args>`` with the shared subprocess boilerplate; None on any exception.++ git output is UTF-8; on Windows ``text=True`` defaults to the ANSI code page and bytes like 0x90+ (3rd byte of 🐛 in a commit subject) crash the stdlib reader thread (#52649), hence the explicit+ encoding. ``network=True`` (ls-remote/fetch) detaches stdin and disables git/GCM prompts so a+ passive update check can never hang on a ``Username for 'https://github.com':`` prompt.+ """+ kwargs: dict = {}+ if network:+ from hermes_cli._subprocess_compat import noninteractive_git_env++ kwargs = {"stdin": subprocess.DEVNULL, "env": noninteractive_git_env()}try:- result = subprocess.run(+ return subprocess.run(["git", *args],capture_output=True,- text=True,- # git output is UTF-8; on Windows text=True defaults to the ANSI- # code page and bytes like 0x90 (3rd byte of 🐛 in a commit- # subject) crash the stdlib reader thread (#52649).- encoding="utf-8",- errors="replace",timeout=timeout,- cwd=str(cwd),+ cwd=str(cwd) if cwd is not None else None,+ **(_GIT_TEXT_KW if text else {}),+ **kwargs,)except Exception:return None- if result.returncode != 0:+++def _git_stdout(args: list[str], *, cwd: Path, timeout: int = 5) -> Optional[str]:+ result = _git_run(args, cwd=cwd, timeout=timeout)+ if result is None or result.returncode != 0:return Nonereturn (result.stdout or "").strip()+def _git_count(args: list[str], *, cwd: Path) -> Optional[int]:+ """``int`` of a successful ``git rev-list --count``-style command, else None.++ Deliberately bypasses ``_git_stdout`` so tests can stub the two layers independently.+ """+ result = _git_run(args, cwd=cwd)+ try:+ if result is not None and result.returncode == 0:+ return int(result.stdout.strip())+ except Exception:+ pass+ return None++def _github_compare_behind(current_rev: str, target_rev: str) -> Optional[int]:"""Exact behind-count via the GitHub compare API for uncountable graphs.- Shallow installer clones and ls-remote-only probes know the two tip SHAs- but have no local history to run ``rev-list --count`` across. GitHub's- ``GET /repos/<owner>/<repo>/compare/<current>...<target>`` knows the full- graph regardless of local clone depth and returns ``ahead_by`` — exactly- the behind count the local graph lost. Unauthenticated, bounded, and- best-effort: any failure (offline, rate limit, diverged/unknown SHAs)- returns None so callers keep the honest UPDATE_AVAILABLE_NO_COUNT.+ Shallow installer clones and ls-remote-only probes know the two tip SHAs but have no local+ history to run ``rev-list --count`` across."""if not (_is_full_sha(current_rev) and _is_full_sha(target_rev)):return None@@ -210,108 +245,84 @@ def _github_compare_behind(current_rev: str, target_rev: str) -> Optional[int]:"https://api.github.com/repos/nousresearch/hermes-agent/"f"compare/{current_rev}...{target_rev}")- try:+ def _fetch():import urllib.request+ # api.github.com 403s requests without a User-Agent.req = urllib.request.Request(- url,- headers={- "Accept": "application/vnd.github+json",- # api.github.com 403s requests without a User-Agent.- "User-Agent": "hermes-cli-update-check",- },+ url, headers={"Accept": "application/vnd.github+json", "User-Agent": "hermes-cli-update-check"},)with urllib.request.urlopen(req, timeout=10) as resp:- payload = json.loads(resp.read().decode("utf-8"))- except Exception:- return None+ return json.loads(resp.read().decode("utf-8"))++ payload = _quiet(_fetch)ahead = payload.get("ahead_by") if isinstance(payload, dict) else Noneif isinstance(ahead, int) and not isinstance(ahead, bool) and ahead >= 0:return aheadreturn None+def _behind_count_or_sentinel(local_rev: str, upstream_rev: str) -> int:+ """Exact behind-count via the compare API, else the honest no-count sentinel.++ ``ahead_by == 0`` with differing tips means the remote tip is reachable from our HEAD — a+ local-ahead checkout, i.e. NOT behind. A local-only HEAD 404s on the API, which safely degrades+ to ``UPDATE_AVAILABLE_NO_COUNT`` — never a fabricated 1.+ """+ counted = _github_compare_behind(local_rev, upstream_rev)+ return counted if counted is not None else UPDATE_AVAILABLE_NO_COUNT+++def _tips_behind(head_rev: Optional[str], target_rev: Optional[str], repo_dir: Optional[Path] = None) -> Optional[int]:+ """Behind-count from two tip SHAs: None if either is unknown, 0 when equal, else count/sentinel.++ With ``repo_dir``, a target that is already an ancestor of HEAD (local-ahead checkout) is 0 too.+ """+ if not head_rev or not target_rev:+ return None+ if head_rev == target_rev:+ return 0+ if repo_dir is not None:+ ancestor = _git_run(["merge-base", "--is-ancestor", target_rev, "HEAD"], cwd=repo_dir, text=False)+ if ancestor is not None and ancestor.returncode == 0:+ return 0+ return _behind_count_or_sentinel(head_rev, target_rev)++def _is_full_sha(value: Optional[str]) -> bool:- return (- isinstance(value, str)- and len(value) == 40- and all(c in "0123456789abcdefABCDEF" for c in value)- )+ return isinstance(value, str) and len(value) == 40 and all(c in "0123456789abcdefABCDEF" for c in value)def _upstream_main_sha() -> Optional[str]:"""Tip SHA of upstream main via HTTPS ls-remote (no auth, no prompts)."""- from hermes_cli._subprocess_compat import noninteractive_git_env-- try:- result = subprocess.run(- ["git", "ls-remote", _UPSTREAM_REPO_URL, "refs/heads/main"],- capture_output=True, text=True, encoding="utf-8", errors="replace",- timeout=10,- stdin=subprocess.DEVNULL,- env=noninteractive_git_env(),- )- except Exception:- return None- if result.returncode != 0 or not result.stdout:+ result = _git_run(["ls-remote", _UPSTREAM_REPO_URL, "refs/heads/main"], timeout=10, network=True)+ if result is None or result.returncode != 0 or not result.stdout:return None- upstream_rev = result.stdout.split()[0]- return upstream_rev or None+ return result.stdout.split()[0] or Nonedef _check_via_rev(local_rev: str) -> Optional[int]:"""Compare an embedded git revision to upstream main via ls-remote.- Returns 0 if up-to-date, the exact behind-count when the GitHub compare- API can recover it, ``UPDATE_AVAILABLE_NO_COUNT`` if behind by an unknown- amount, or ``None`` on failure.+ Returns 0 if up-to-date, the exact behind-count when the GitHub compare API can recover it,+ ``UPDATE_AVAILABLE_NO_COUNT`` if behind by an unknown amount, or ``None`` on failure."""- upstream_rev = _upstream_main_sha()- if not upstream_rev:- return None- if upstream_rev == local_rev:- return 0- # Behind, but ls-remote only knows tip SHAs. Try to recover the exact- # count from the GitHub compare API before falling back to the sentinel.- # ahead_by == 0 with differing tips means the remote tip is reachable from- # our HEAD — a local-ahead checkout, i.e. NOT behind.- counted = _github_compare_behind(local_rev, upstream_rev)- return counted if counted is not None else UPDATE_AVAILABLE_NO_COUNT+ return _tips_behind(local_rev, _upstream_main_sha())def _check_via_local_git(repo_dir: Path) -> Optional[int]:"""Count commits behind origin/main in a local checkout."""- from hermes_cli._subprocess_compat import noninteractive_git_env-origin_url = _git_stdout(["remote", "get-url", "origin"], cwd=repo_dir)if _is_official_ssh_remote(origin_url):head_rev = _git_stdout(["rev-parse", "HEAD"], cwd=repo_dir)if not head_rev:return None- # Passive probe via HTTPS ls-remote (never SSH — no hardware-key- # prompts). Tip SHAs alone can't distinguish "behind" from a local- # carried commit sitting AHEAD of origin/main, and misreporting an- # ahead checkout as behind nudges the user into `hermes update`,- # which can wipe their carried work.- upstream_rev = _upstream_main_sha()- if upstream_rev is None:- return None- if upstream_rev == head_rev:- return 0- # Local-ahead: the remote tip is an ancestor of HEAD. Checked against- # the FRESH upstream SHA (not the possibly stale origin/main tracking- # ref) so a stale ref can't fake an up-to-date report.- ancestor = subprocess.run(- ["git", "merge-base", "--is-ancestor", upstream_rev, "HEAD"],- capture_output=True, timeout=5, cwd=str(repo_dir),- )- if ancestor.returncode == 0:- return 0- # Genuinely behind (or diverged). Recover the exact count via the- # GitHub compare API; a local-only HEAD 404s there, which safely- # degrades to the honest no-count sentinel — never a fabricated 1.- counted = _github_compare_behind(head_rev, upstream_rev)- return counted if counted is not None else UPDATE_AVAILABLE_NO_COUNT+ # Passive probe via HTTPS ls-remote (never SSH — no hardware-key prompts). Tip SHAs alone+ # can't distinguish "behind" from a local carried commit sitting AHEAD of origin/main, and+ # misreporting an ahead checkout as behind nudges the user into `hermes update`, which can+ # wipe their carried work — hence the ancestor check, against the FRESH upstream SHA (not+ # the possibly stale origin/main tracking ref) so a stale ref can't fake an up-to-date report.+ return _tips_behind(head_rev, _upstream_main_sha(), repo_dir)# Installer checkouts are shallow (`git clone --depth 1`). On a shallow# clone the history stops at a single commit, so a plain `git fetch` would@@ -321,45 +332,31 @@ def _check_via_local_git(repo_dir: Path) -> Optional[int]:# --depth 1 to preserve the boundary and compare tip SHAs instead of# counting. Full clones (developers, Docker dev images) keep the exact# count path unchanged. Mirrors the desktop fix in apps/desktop/electron/main.cjs.- shallow = _git_stdout(["rev-parse", "--is-shallow-repository"], cwd=repo_dir)- is_shallow = shallow == "true"-- try:- # Self-heal abandoned git lock files before fetching. A stale- # .git/shallow.lock from a crashed fetch makes the fetch fail, the- # exception below is swallowed, and stale refs get compared against- # HEAD — silently degrading the passive check until a human removes- # the lock (git never self-heals these).+ is_shallow = _git_stdout(["rev-parse", "--is-shallow-repository"], cwd=repo_dir) == "true"++ def _fetch() -> bool:+ # Self-heal abandoned git lock files before fetching. A stale .git/shallow.lock from a+ # crashed fetch makes the fetch fail, the exception is swallowed, and stale refs get+ # compared against HEAD — silently degrading the passive check until a human removes the+ # lock (git never self-heals these). The passive check is also the main tmp_pack GENERATOR+ # on flaky lines (several aborted fetches per day), so it must be the janitor too, or debris+ # accumulates unbounded between manual updates (#93732).from hermes_cli.gitlock import clear_stale_git_locks, clear_stale_tmp_packsclear_stale_git_locks(repo_dir)- # The passive check is the main tmp_pack GENERATOR on flaky lines- # (several aborted fetches per day) — it must also be the janitor,- # or debris accumulates unbounded between manual updates (#93732).clear_stale_tmp_packs(repo_dir)- # Scope the fetch to the one branch the behind-count compares against.- # An unscoped ``git fetch origin`` transfers every remote head (~1,400- # on this repo — measured 3.0 s vs 0.55 s scoped) and can burn the full- # 10 s timeout on slow links. ``cmd_update`` already scopes its fetch- # for the same reason. Modern git updates the ``origin/main`` tracking- # ref on a scoped fetch, so the ``HEAD..origin/main`` count below is- # unaffected; the shallow path compares against FETCH_HEAD, which a- # scoped fetch also updates.- fetch_args = ["git", "fetch", "origin", "main"]- if is_shallow:- fetch_args += ["--depth", "1"]- fetch_args.append("--quiet")- fetch_proc = subprocess.run(- fetch_args,- capture_output=True, timeout=10,- cwd=str(repo_dir),- stdin=subprocess.DEVNULL,- env=noninteractive_git_env(),- )- fetch_ok = fetch_proc.returncode == 0- except Exception:- fetch_ok = False # Offline or timeout — don't use stale refs+ # Scope the fetch to the one branch the behind-count compares against. An unscoped+ # ``git fetch origin`` transfers every remote head (~1,400 on this repo — measured 3.0 s vs+ # 0.55 s scoped) and can burn the full 10 s timeout on slow links. Modern git updates the+ # ``origin/main`` tracking ref on a scoped fetch, so the ``HEAD..origin/main`` count below+ # is unaffected; the shallow path compares against FETCH_HEAD, which a scoped fetch also+ # updates. ``--depth 1`` preserves the shallow boundary.+ fetch_args = ["fetch", "origin", "main", *(["--depth", "1"] if is_shallow else []), "--quiet"]+ fetch_proc = _git_run(fetch_args, cwd=repo_dir, timeout=10, text=False, network=True)+ return fetch_proc is not None and fetch_proc.returncode == 0++ fetch_ok = _quiet(_fetch, False) # Offline or timeout — don't use stale refs# When the fetch fails, the local origin/main tracking ref is stale. It# cannot prove *currentness* (a 0 behind-count may just mean the stale ref@@ -367,67 +364,37 @@ def _check_via_local_git(repo_dir: Path) -> Optional[int]:# evidence an update exists — the ref was good at some point in the past.# Return the positive stale count; return None (inconclusive) otherwise so# the caller doesn't cache a false "up to date". (#82166, review #92578)- if not fetch_ok:- if not is_shallow:- try:- result = subprocess.run(- ["git", "rev-list", "--count", "HEAD..origin/main"],- capture_output=True, text=True, encoding="utf-8", errors="replace",- timeout=5,- cwd=str(repo_dir),- )- if result.returncode == 0:- behind = int(result.stdout.strip())- if behind > 0:- return behind- except Exception:- pass- return None-if is_shallow:- # No history to count across the shallow boundary. `origin/main` may not- # be a tracking ref in a `clone --depth 1`, so prefer FETCH_HEAD (just- # updated by the fetch above) and fall back to origin/main.+ if not fetch_ok:+ return None+ # No history to count across the shallow boundary. `origin/main` may not be a tracking ref+ # in a `clone --depth 1`, so prefer FETCH_HEAD (just updated by the fetch above) and fall+ # back to origin/main. Tips differ but the shallow boundary hides the history between them.head_rev = _git_stdout(["rev-parse", "HEAD"], cwd=repo_dir)target_rev = (_git_stdout(["rev-parse", "FETCH_HEAD"], cwd=repo_dir)or _git_stdout(["rev-parse", "origin/main"], cwd=repo_dir))- if not head_rev or not target_rev:- return None- if head_rev == target_rev:- return 0- # Tips differ but the shallow boundary hides the history between them.- # Recover the exact count from the GitHub compare API when possible- # (ahead_by == 0 means local-ahead ⇒ up to date); otherwise report the- # honest "update available, count unknown" sentinel.- counted = _github_compare_behind(head_rev, target_rev)- return counted if counted is not None else UPDATE_AVAILABLE_NO_COUNT+ return _tips_behind(head_rev, target_rev)- try:- result = subprocess.run(- ["git", "rev-list", "--count", "HEAD..origin/main"],- capture_output=True, text=True, encoding="utf-8", errors="replace",- timeout=5,- cwd=str(repo_dir),- )- if result.returncode == 0:- return int(result.stdout.strip())- except Exception:- pass+ behind = _git_count(["rev-list", "--count", "HEAD..origin/main"], cwd=repo_dir)+ if fetch_ok or (behind is not None and behind > 0):+ return behindreturn None+def _read_json(path: Path) -> Optional[dict]:+ """Parse ``path`` as a JSON object; None when missing, unreadable, or not a dict."""+ blob = _quiet(lambda: json.loads(path.read_text(encoding="utf-8")))+ return blob if isinstance(blob, dict) else None++def check_for_updates() -> Optional[int]:"""Check whether a Hermes update is available.- Two paths: if ``HERMES_REVISION`` is set (nix builds embed it), compare- it to upstream main via ``git ls-remote``. Otherwise look for a local- git checkout and count commits behind ``origin/main``.-- Returns the number of commits behind, ``UPDATE_AVAILABLE_NO_COUNT`` (-1)- if behind but the count is unknown, ``0`` if up-to-date, or ``None`` if- the check failed or doesn't apply. Cached for 6 hours.+ Two paths: if ``HERMES_REVISION`` is set (nix builds embed it), compare it to upstream main via+ ``git ls-remote``. Otherwise look for a local git checkout and count commits behind+ ``origin/main``."""hermes_home = get_hermes_home()cache_file = hermes_home / ".update_check"@@ -440,58 +407,43 @@ def check_for_updates() -> Optional[int]:# on `typeof === 'number' && > 0`) show nothing. The dashboard's REST# `/api/hermes/update/check` endpoint short-circuits docker the same way# (web_server.py); mirror that here so the banner/TUI surfaces agree.- try:+ def _install_method():from hermes_cli.config import detect_install_method, get_project_root- if detect_install_method(get_project_root()) in {"docker", "apt"}:- return None- except Exception:- pass+ return detect_install_method(get_project_root())++ if _quiet(_install_method) in {"docker", "apt"}:+ return None# Read cache — invalidate if the embedded rev OR installed version has# changed since the last check.now = time.time()- try:- if cache_file.exists():- cached = json.loads(cache_file.read_text(encoding="utf-8"))- if (- now - cached.get("ts", 0) < _UPDATE_CHECK_CACHE_SECONDS- and cached.get("rev") == embedded_rev- and cached.get("ver") == VERSION- ):- return cached.get("behind")- except Exception:- pass+ cached = _read_json(cache_file)+ if (+ cached is not None+ and now - cached.get("ts", 0) < _UPDATE_CHECK_CACHE_SECONDS+ and cached.get("rev") == embedded_rev+ and cached.get("ver") == VERSION+ ):+ return cached.get("behind")if embedded_rev:behind = _check_via_rev(embedded_rev)else:- # Prefer the running code's location over the profile-scoped path.- # $HERMES_HOME/hermes-agent/ may be a stale copy from --clone-all;- # Path(__file__) always resolves to the actual installed checkout.- repo_dir = Path(__file__).parent.parent.resolve()- if not (repo_dir / ".git").exists():- repo_dir = hermes_home / "hermes-agent"- if not (repo_dir / ".git").exists():- # No git checkout and no embedded revision — can't determine- # update status. This is the Docker path (already short-circuited- # above) or an unsupported install without a source tree.- behind = None- else:- behind = _check_via_local_git(repo_dir)-- try:- # Don't cache inconclusive results (None). A None means the check- # could not run — typically a failed git fetch. Caching None would- # suppress retries for the full 6-hour cache window, leaving the- # user with a stale "up to date" or no information for hours after- # connectivity is restored (#82166).- if behind is not None:- cache_file.write_text(- json.dumps({"ts": now, "behind": behind, "rev": embedded_rev, "ver": VERSION}),- encoding="utf-8",- )- except Exception:- pass+ # No git checkout and no embedded revision — can't determine update+ # status (the Docker path, already short-circuited above, or an+ # unsupported install without a source tree).+ repo_dir = _resolve_repo_dir()+ behind = _check_via_local_git(repo_dir) if repo_dir is not None else None++ # Don't cache inconclusive results (None). A None means the check could not run — typically a+ # failed git fetch. Caching None would suppress retries for the full 6-hour cache window,+ # leaving the user with a stale "up to date" or no information for hours after connectivity+ # is restored (#82166).+ if behind is not None:+ _quiet(lambda: cache_file.write_text(+ json.dumps({"ts": now, "behind": behind, "rev": embedded_rev, "ver": VERSION}),+ encoding="utf-8",+ ))return behind@@ -499,9 +451,8 @@ def check_for_updates() -> Optional[int]:def _resolve_repo_dir() -> Optional[Path]:"""Return the active Hermes git checkout, or None if this isn't a git install.- Prefers the running code's location over the profile-scoped path- because ``$HERMES_HOME/hermes-agent/`` may be a stale copy carried- over by ``--clone-all``.+ Prefers the running code's location over the profile-scoped path because ``$HERMES_HOME/hermes-+ agent/`` may be a stale copy carried over by ``--clone-all``."""repo_dir = Path(__file__).parent.parent.resolve()if not (repo_dir / ".git").exists():@@ -510,149 +461,59 @@ def _resolve_repo_dir() -> Optional[Path]:return repo_dir if (repo_dir / ".git").exists() else None-def _git_short_hash(repo_dir: Path, rev: str) -> Optional[str]:- """Resolve a git revision to an 8-character short hash."""- try:- result = subprocess.run(- ["git", "rev-parse", "--short=8", rev],- capture_output=True,- text=True,- encoding="utf-8",- errors="replace",- timeout=5,- cwd=str(repo_dir),- )- except Exception:- return None- if result.returncode != 0:- return None- value = (result.stdout or "").strip()- return value or None---_git_banner_state_cache: Optional[tuple] = None # (state_or_None,) once computed--def get_git_banner_state(repo_dir: Optional[Path] = None) -> Optional[dict]:"""Return upstream/local git hashes for the startup banner.- For source installs and dev images this runs ``git rev-parse`` against- the active checkout. When no checkout is available — the canonical case- is the published Docker image, which excludes ``.git`` from the build- context — we fall back to the baked-in build SHA (see- ``hermes_cli/build_info.py``) and return it as a frozen- ``upstream == local`` state with ``ahead=0``. A built image is by- definition pinned to one commit, so "ahead" is always zero and the- banner correctly shows ``· upstream <sha>`` with no carried-commits- annotation.-- Cached per-process (default ``repo_dir`` only): the state costs 2-3 git- subprocesses (~100ms) and the checkout revision cannot change under a- running CLI in a way the banner needs to observe live. The cache also- lets ``prefetch_banner_data()`` pay this cost off-thread before the- banner renders.+ Cached per-process (default ``repo_dir`` only): the state costs 2-3 git subprocesses (~100ms)+ and the checkout revision cannot change under a running CLI in a way the banner needs to observe+ live. The cache also lets ``prefetch_banner_data()`` pay this cost off-thread before the banner+ renders."""- global _git_banner_state_cache- if repo_dir is None and _git_banner_state_cache is not None:- return _git_banner_state_cache[0]- state = _compute_git_banner_state(repo_dir)- if repo_dir is None:- _git_banner_state_cache = (state,)- return state+ if repo_dir is not None:+ return _compute_git_banner_state(repo_dir)+ return _memo("_git_banner_state_cache", _compute_git_banner_state)+++def _baked_banner_state() -> Optional[dict]:+ """Banner state from the baked build SHA (Docker image path), or None."""+ def _baked():+ from hermes_cli.build_info import get_build_sha+ return get_build_sha(short=8)++ baked = _quiet(_baked)+ return {"upstream": baked, "local": baked, "ahead": 0} if baked else Nonedef _compute_git_banner_state(repo_dir: Optional[Path] = None) -> Optional[dict]:repo_dir = repo_dir or _resolve_repo_dir()if repo_dir is None:- # No git checkout — try the baked build SHA (Docker image path).- try:- from hermes_cli.build_info import get_build_sha- baked = get_build_sha(short=8)- if baked:- return {"upstream": baked, "local": baked, "ahead": 0}- except Exception:- pass- return None+ return _baked_banner_state()- upstream = _git_short_hash(repo_dir, "origin/main")- local = _git_short_hash(repo_dir, "HEAD")+ upstream, local = (_git_stdout(["rev-parse", "--short=8", rev], cwd=repo_dir) for rev in ("origin/main", "HEAD"))if not upstream or not local:# Live-git lookup failed (e.g. shallow clone without origin/main).- # Fall back to the baked build SHA if available.- try:- from hermes_cli.build_info import get_build_sha- baked = get_build_sha(short=8)- if baked:- return {"upstream": baked, "local": baked, "ahead": 0}- except Exception:- pass- return None-- ahead = 0- try:- result = subprocess.run(- ["git", "rev-list", "--count", "origin/main..HEAD"],- capture_output=True,- text=True,- encoding="utf-8",- errors="replace",- timeout=5,- cwd=str(repo_dir),- )- if result.returncode == 0:- ahead = int((result.stdout or "0").strip() or "0")- except Exception:- ahead = 0+ return _baked_banner_state()+ ahead = _git_count(["rev-list", "--count", "origin/main..HEAD"], cwd=repo_dir) or 0return {"upstream": upstream, "local": local, "ahead": max(ahead, 0)}_RELEASE_URL_BASE = "https://github.com/NousResearch/hermes-agent/releases/tag"-_latest_release_cache: Optional[tuple] = None # (tag, url) once resolveddef get_latest_release_tag(repo_dir: Optional[Path] = None) -> Optional[tuple]:"""Return ``(tag, release_url)`` for the latest git tag, or None.- Local-only — runs ``git describe --tags --abbrev=0`` against the- Hermes checkout. Cached per-process. Release URL always points at the- canonical NousResearch/hermes-agent repo (forks don't get a link).+ Local-only — runs ``git describe --tags --abbrev=0`` against the Hermes checkout. Cached per-+ process (a miss is cached too). Release URL always points at the canonical+ NousResearch/hermes-agent repo (forks don't get a link)."""- global _latest_release_cache- if _latest_release_cache is not None:- return _latest_release_cache or None+ def _compute():+ rd = repo_dir or _resolve_repo_dir()+ tag = _git_stdout(["describe", "--tags", "--abbrev=0"], cwd=rd, timeout=3) if rd else None+ return (tag, f"{_RELEASE_URL_BASE}/{tag}") if tag else None- repo_dir = repo_dir or _resolve_repo_dir()- if repo_dir is None:- _latest_release_cache = () # falsy sentinel — skip future lookups- return None-- try:- result = subprocess.run(- ["git", "describe", "--tags", "--abbrev=0"],- capture_output=True,- text=True,- encoding="utf-8",- errors="replace",- timeout=3,- cwd=str(repo_dir),- )- except Exception:- _latest_release_cache = ()- return None-- if result.returncode != 0:- _latest_release_cache = ()- return None-- tag = (result.stdout or "").strip()- if not tag:- _latest_release_cache = ()- return None-- url = f"{_RELEASE_URL_BASE}/{tag}"- _latest_release_cache = (tag, url)- return _latest_release_cache+ return _memo("_latest_release_cache", _compute)def format_banner_version_label() -> str:@@ -662,15 +523,11 @@ def format_banner_version_label() -> str:if not state:return base- upstream = state["upstream"]- local = state["local"]+ upstream, local = state["upstream"], state["local"]ahead = int(state.get("ahead") or 0)-if ahead <= 0 or upstream == local:return f"{base} · upstream {upstream}"-- carried_word = "commit" if ahead == 1 else "commits"- return f"{base} · upstream {upstream} · local {local} (+{ahead} carried {carried_word})"+ return f"{base} · upstream {upstream} · local {local} (+{ahead} carried {_plural(ahead, 'commit')})"# =========================================================================@@ -681,14 +538,18 @@ _update_result: Optional[int] = None_update_check_done = threading.Event()+def _daemon(name: Optional[str], target) -> None:+ """Start a daemon thread running ``target`` with any exception swallowed."""+ threading.Thread(target=lambda: _quiet(target), name=name, daemon=True).start()++def prefetch_update_check():"""Kick off update check in a background daemon thread."""def _run():global _update_result_update_result = check_for_updates()_update_check_done.set()- t = threading.Thread(target=_run, daemon=True)- t.start()+ _daemon(None, _run)_banner_data_prefetch_started = False@@ -697,13 +558,10 @@ _banner_data_prefetch_started = Falsedef prefetch_banner_data():"""Warm the banner's subprocess/I/O-heavy inputs in a daemon thread.- ``build_welcome_banner`` needs git state (2-4 ``git rev-parse``/- ``describe`` subprocesses, ~130ms) and the skills index (a skills-tree- rglob, ~110ms). Both are cached per-process by their own modules, so- warming them here while the main thread pays the CPU-bound ``cli`` /- prompt_toolkit imports overlaps subprocess waits and file I/O (which- release the GIL) with import work. Idempotent; failures are irrelevant- because the banner recomputes anything missing.+ Git state (~130ms of subprocesses) and the skills index (~110ms rglob) are cached per-process+ by their own modules, so warming them while the main thread pays the CPU-bound ``cli`` /+ prompt_toolkit imports overlaps GIL-releasing I/O with import work. Idempotent; failures+ don't matter because the banner recomputes anything missing."""global _banner_data_prefetch_startedif _banner_data_prefetch_started:@@ -711,20 +569,10 @@ def prefetch_banner_data():_banner_data_prefetch_started = Truedef _run() -> None:- try:- get_git_banner_state()- except Exception:- pass- try:- get_latest_release_tag()- except Exception:- pass- try:- get_available_skills()- except Exception:- pass-- threading.Thread(target=_run, name="banner-data-prefetch", daemon=True).start()+ for warm in (get_git_banner_state, get_latest_release_tag, get_available_skills):+ _quiet(warm)++ _daemon("banner-data-prefetch", _run)def get_update_result(timeout: float = 0.5) -> Optional[int]:@@ -737,19 +585,16 @@ def _format_update_notice(behind: int) -> str:"""Render the update warning line for a non-zero ``behind`` result."""from hermes_cli.config import get_managed_update_command, recommended_update_commandif behind > 0:- commits_word = "commit" if behind == 1 else "commits"return (- f"[bold yellow]⚠ {behind} {commits_word} behind[/]"+ f"[bold yellow]⚠ {behind} {_plural(behind, 'commit')} behind[/]"f"[dim yellow] — run [bold]{recommended_update_command()}[/bold] to update[/]")# UPDATE_AVAILABLE_NO_COUNT: nix-built hermes; we know an update# exists but not by how much, and we don't know how the user# installed it (nix run, profile, system flake, home-manager).managed_cmd = get_managed_update_command()- line = "[bold yellow]⚠ update available[/]"- if managed_cmd:- line += f"[dim yellow] — run [bold]{managed_cmd}[/bold][/]"- return line+ suffix = f"[dim yellow] — run [bold]{managed_cmd}[/bold][/]" if managed_cmd else ""+ return f"[bold yellow]⚠ update available[/]{suffix}"_deferred_update_notice_started = False@@ -758,8 +603,8 @@ _deferred_update_notice_started = Falsedef _defer_update_notice(console: "Console", max_wait: float = 30.0) -> None:"""Print the update warning once the prefetched check completes.- Used when the banner rendered before the update prefetch finished so- startup never blocks on git/network. Prints at most once per process.+ Used when the banner rendered before the update prefetch finished so startup never blocks on+ git/network. Prints at most once per process."""global _deferred_update_notice_startedif _deferred_update_notice_started:@@ -767,39 +612,27 @@ def _defer_update_notice(console: "Console", max_wait: float = 30.0) -> None:_deferred_update_notice_started = Truedef _wait_and_print() -> None:- try:- if not _update_check_done.wait(timeout=max_wait):- return- behind = _update_result- if behind is None or behind == 0:- return- console.print(_format_update_notice(behind))- except Exception:- pass # never break the session over an update notice+ if _update_check_done.wait(timeout=max_wait) and _update_result:+ console.print(_format_update_notice(_update_result))- threading.Thread(- target=_wait_and_print, name="update-notice", daemon=True- ).start()+ _daemon("update-notice", _wait_and_print) # never break the session over an update notice# =========================================================================# Welcome banner# =========================================================================+def _plural(n: int, word: str) -> str:+ return word if n == 1 else f"{word}s"++def _format_context_length(tokens: int) -> str:"""Format a token count for display (e.g. 128000 → '128K', 1048576 → '1M')."""- if tokens >= 1_000_000:- val = tokens / 1_000_000- rounded = round(val)- if abs(val - rounded) < 0.05:- return f"{rounded}M"- return f"{val:.1f}M"- elif tokens >= 1_000:- val = tokens / 1_000- rounded = round(val)- if abs(val - rounded) < 0.05:- return f"{rounded}K"- return f"{val:.1f}K"+ for unit, div in (("M", 1_000_000), ("K", 1_000)):+ if tokens >= div:+ val = tokens / div+ rounded = round(val)+ return f"{rounded}{unit}" if abs(val - rounded) < 0.05 else f"{val:.1f}{unit}"return str(tokens)@@ -807,11 +640,12 @@ def _display_toolset_name(toolset_name: str) -> str:"""Normalize internal/legacy toolset identifiers for banner display."""if not toolset_name:return "unknown"- return (- toolset_name[:-6]- if toolset_name.endswith("_tools")- else toolset_name- )+ return toolset_name[:-6] if toolset_name.endswith("_tools") else toolset_name+++def _short_label(name: str) -> str:+ """Truncate a model/preset slug to fit the banner's left column."""+ return name[:25] + "..." if len(name) > 28 else name# =========================================================================@@ -838,17 +672,18 @@ def _banner_snapshot_path() -> Path:def banner_snapshot_fingerprint() -> Optional[str]:"""Fingerprint the inputs the banner tool panel depends on."""import hashlib- parts = [f"v{_BANNER_SNAPSHOT_VERSION}"]- try:++ def _inputs():from hermes_cli.config import get_config_path- for p in (get_config_path(), get_hermes_home() / ".env"):- try:- st = p.stat()- parts.append(f"{p.name}:{st.st_mtime_ns}:{st.st_size}")- except OSError:- parts.append(f"{p.name}:absent")- except Exception:+ return (get_config_path(), get_hermes_home() / ".env")++ paths = _quiet(_inputs)+ if paths is None:return None+ parts = [f"v{_BANNER_SNAPSHOT_VERSION}"]+ for p in paths:+ st = _quiet(p.stat)+ parts.append(f"{p.name}:{st.st_mtime_ns}:{st.st_size}" if st else f"{p.name}:absent")# Code checkout: version + git HEAD when available (post-update change).parts.append(str(VERSION))state = get_git_banner_state()@@ -859,24 +694,17 @@ def banner_snapshot_fingerprint() -> Optional[str]:def load_banner_snapshot(enabled_toolsets: List[str] = None) -> Optional[Dict[str, Any]]:"""Return the stored banner snapshot when its fingerprint is current."""- try:- blob = json.loads(_banner_snapshot_path().read_text(encoding="utf-8"))- except Exception:- return None- if not isinstance(blob, dict):+ blob = _read_json(_banner_snapshot_path())+ if blob is None:return Nonefp = banner_snapshot_fingerprint()if not fp or blob.get("fingerprint") != fp:return Noneif blob.get("enabled_toolsets") != sorted(enabled_toolsets or []):return None- tools = blob.get("tools")- toolset_map = blob.get("toolset_map")- availability = blob.get("availability")- if not isinstance(tools, list) or not isinstance(toolset_map, dict) \- or not isinstance(availability, dict):- return None- if not isinstance(blob.get("skills_by_category"), dict):+ if not isinstance(blob.get("tools"), list) or not all(+ isinstance(blob.get(k), dict) for k in ("toolset_map", "availability", "skills_by_category")+ ):return Nonereturn blob@@ -902,32 +730,27 @@ def save_banner_snapshot("toolset_map": toolset_map,"availability": {"unavailable_toolsets": availability.get("unavailable_toolsets", []),- "lazy_tools": list(availability.get("lazy_tools", [])),- "disabled_tools": list(availability.get("disabled_tools", [])),+ **{k: list(availability.get(k, [])) for k in ("lazy_tools", "disabled_tools")},},"skills_by_category": get_available_skills(),}- path = _banner_snapshot_path()- try:- import os as _os- import tempfile as _tempfile+ def _write():+ import tempfile+ path = _banner_snapshot_path()path.parent.mkdir(parents=True, exist_ok=True)- fd, tmp = _tempfile.mkstemp(dir=str(path.parent), prefix=".banner_snap.")- with _os.fdopen(fd, "w", encoding="utf-8") as fh:+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=".banner_snap.")+ with os.fdopen(fd, "w", encoding="utf-8") as fh:json.dump(payload, fh)- _os.replace(tmp, path)- except Exception:- pass+ os.replace(tmp, path)++ _quiet(_write)def compute_toolset_availability(enabled_toolsets: List[str] = None) -> Dict[str, Any]:"""Compute the banner's toolset-availability payload.- Returns ``{"unavailable_toolsets": [...], "lazy_tools": [...],- "disabled_tools": [...]}`` — the exact inputs ``build_welcome_banner``- needs to annotate disabled/lazy tools. Split out so the result can be- snapshotted to disk and replayed on the next launch without importing- ``model_tools`` (see ``load_banner_snapshot``).+ Returns ``{"unavailable_toolsets", "lazy_tools", "disabled_tools"}``. Split out so the result+ can be snapshotted and replayed on the next launch without importing ``model_tools``."""from model_tools import check_tool_availability, TOOLSET_REQUIREMENTS@@ -945,19 +768,12 @@ def compute_toolset_availability(enabled_toolsets: List[str] = None) -> Dict[stritem for item in unavailable_toolsetsif str(item.get("id", item.get("name", ""))) in _enabled_ts]- disabled_tools = set()- # Tools whose toolset has a check_fn are lazy-initialized (e.g. honcho,- # homeassistant) — they show as unavailable at banner time because the- # check hasn't run yet, but they aren't misconfigured.- lazy_tools = set()+ # Tools whose toolset has a check_fn are lazy-initialized (e.g. honcho, homeassistant) — they+ # show as unavailable at banner time because the check hasn't run yet, but aren't misconfigured.+ lazy_tools, disabled_tools = set(), set()for item in unavailable_toolsets:- toolset_name = item.get("name", "")- ts_req = TOOLSET_REQUIREMENTS.get(toolset_name, {})- tools_in_ts = item.get("tools", [])- if ts_req.get("check_fn"):- lazy_tools.update(tools_in_ts)- else:- disabled_tools.update(tools_in_ts)+ is_lazy = TOOLSET_REQUIREMENTS.get(item.get("name", ""), {}).get("check_fn")+ (lazy_tools if is_lazy else disabled_tools).update(item.get("tools", []))return {"unavailable_toolsets": unavailable_toolsets,"lazy_tools": sorted(lazy_tools),@@ -965,6 +781,99 @@ def compute_toolset_availability(enabled_toolsets: List[str] = None) -> Dict[str}+def _mcp_server_line(srv: dict, *, dim: str, text: str) -> str:+ """One banner line for an MCP server status entry."""+ name, transport = srv["name"], srv["transport"]+ if srv["connected"]:+ return f"[dim {dim}]{name}[/] [{text}]({transport})[/] [dim {dim}]—[/] [{text}]{srv['tools']} tool(s)[/]"+ status = "disabled" if srv.get("disabled") else srv.get("status")+ suffix = {+ "disabled": f"[dim {dim}]— disabled[/]",+ "connecting": "[yellow]— connecting[/]",+ "configured": f"[dim {dim}]— configured[/]",+ }.get(status)+ if suffix is not None:+ return f"[dim {dim}]{name}[/] [dim]({transport})[/] {suffix}"+ return f"[red]{name}[/] [dim]({transport})[/] [red]— failed[/]"+++def _truncate_tool_names(tool_names: List[str]) -> List[Optional[str]]:+ """Cut a toolset's tool list to ~42 columns; ``None`` marks the elided tail."""+ if len(", ".join(tool_names)) <= 45:+ return list(tool_names)+ short_names: List[Optional[str]] = []+ length = 0+ for name in tool_names:+ if length + len(name) + 2 > 42:+ short_names.append(None)+ break+ short_names.append(name)+ length += len(name) + 2+ return short_names+++def _pack_skill_names(skill_names: List[str], avail: int) -> str:+ """Join skill names into ``avail`` columns, ending with ``+N more`` when they don't all fit."""+ parts: List[str] = []+ length = 0+ for i, name in enumerate(skill_names):+ needed = (2 if parts else 0) + len(name)+ # Indicator size IF we were to add this skill then stop.+ after = len(skill_names) - (i + 1)+ ind_len = len(f", +{after} more") if after > 0 else 0+ if parts and length + needed + ind_len > avail:+ parts.append(f"+{len(skill_names) - len(parts)} more")+ break+ parts.append(name)+ length += needed+ return ", ".join(parts)+++def _moa_aggregator_label(preset_name: str) -> str:+ """Short aggregator-model label for a MoA preset ("" when the preset has none)."""+ from hermes_cli.config import load_config+ from hermes_cli.moa_config import normalize_moa_config++ preset = normalize_moa_config(load_config().get("moa") or {}).get("presets", {}).get(preset_name)+ model = str(((preset or {}).get("aggregator") or {}).get("model") or "")+ return model.split("/")[-1]+++def _mcp_configured() -> bool:+ """Cheap probe: does config.yaml or the persisted plugin key cache name any MCP server?++ The full ``get_mcp_status()`` path resolves portable plugin MCP servers, which JOINS the in-flight+ background plugin discovery (~100ms on the startup path), so skip it when nothing is configured.+ When either probe can't tell, take the full path.+ """+ def _native():+ from hermes_cli.config import load_config+ return bool((load_config() or {}).get("mcp_servers"))++ def _portable():+ from hermes_cli.plugins import get_portable_mcp_server_names_nowait+ return bool(get_portable_mcp_server_names_nowait())++ return _quiet(_native, True) or _quiet(_portable, True)+++def _probe_mcp_status() -> list:+ from tools.mcp_tool import get_mcp_status+ return get_mcp_status()+++def _codex_runtime_active() -> bool:+ """True when the codex_app_server runtime is active (tool counts then live inside codex)."""+ from hermes_cli.codex_runtime_switch import get_current_runtime+ from hermes_cli.config import load_config+ return get_current_runtime(load_config()) == "codex_app_server"+++def _active_profile_name() -> Optional[str]:+ from hermes_cli.profiles import get_active_profile_name+ return get_active_profile_name()++def build_welcome_banner(console: "Console", model: str, cwd: str,tools: List[dict] = None,enabled_toolsets: List[str] = None,@@ -976,22 +885,9 @@ def build_welcome_banner(console: "Console", model: str, cwd: str,skills_by_category: Dict[str, List[str]] = None):"""Build and print a welcome banner with caduceus on left and info on right.- Args:- console: Rich Console instance.- model: Current model name.- cwd: Current working directory.- tools: List of tool definitions.- enabled_toolsets: List of enabled toolset names.- session_id: Session identifier.- get_toolset_for_tool: Callable to map tool name -> toolset name.- context_length: Model's context window size in tokens.- provider: Active provider id. When ``"moa"``, ``model`` is a MoA- preset name and the banner renders the aggregator instead of a- bare model slug.- availability: Optional precomputed result of- ``compute_toolset_availability`` (e.g. replayed from the banner- snapshot). When provided together with ``get_toolset_for_tool``,- this function performs no ``model_tools`` import at all.+ When ``provider == "moa"``, ``model`` is a MoA preset name and the aggregator is rendered.+ Passing a precomputed ``availability`` together with ``get_toolset_for_tool`` avoids any+ ``model_tools`` import (banner snapshot replay)."""from rich.panel import Panelfrom rich.table import Table@@ -1016,62 +912,39 @@ def build_welcome_banner(console: "Console", model: str, cwd: str,accent = _skin_color("banner_accent", "#FFBF00")dim = _skin_color("banner_dim", "#B8860B")text = _skin_color("banner_text", "#FFF8DC")- session_color = _skin_color("session_border", "#8B8682")# Use skin's custom caduceus art if provided- try:- from hermes_cli.skin_engine import get_active_skin- _bskin = get_active_skin()- _hero = _bskin.banner_hero if hasattr(_bskin, 'banner_hero') and _bskin.banner_hero else HERMES_CADUCEUS- except Exception:- _bskin = None- _hero = HERMES_CADUCEUS- left_lines = ["", _hero, ""]+ _bskin = _quiet(_active_skin)+ left_lines = ["", getattr(_bskin, "banner_hero", None) or HERMES_CADUCEUS, ""]++ def _dim_sep(label: str) -> str:+ return f" [dim {dim}]·[/] [dim {dim}]{label}[/]"++ ctx_str = _dim_sep(f"{_format_context_length(context_length)} context") if context_length else ""+ nous_str = _dim_sep("Nous Research")if (provider or "").strip().lower() == "moa":# MoA virtual provider: ``model`` is a preset name. Show the preset and# its aggregator so the banner is meaningful instead of a bare slug.- preset_name = model- agg_label = ""- try:- from hermes_cli.config import load_config- from hermes_cli.moa_config import normalize_moa_config-- _moa = normalize_moa_config(load_config().get("moa") or {})- _preset = _moa.get("presets", {}).get(preset_name)- if _preset:- _agg = _preset.get("aggregator") or {}- _am = str(_agg.get("model") or "")- agg_label = _am.split("/")[-1] if "/" in _am else _am- except Exception:- agg_label = ""- if len(preset_name) > 28:- preset_name = preset_name[:25] + "..."- agg_str = f" [dim {dim}]·[/] [dim {dim}]agg {agg_label}[/]" if agg_label else ""- ctx_str = f" [dim {dim}]·[/] [dim {dim}]{_format_context_length(context_length)} context[/]" if context_length else ""- left_lines.append(f"[{accent}]MoA: {preset_name}[/]{agg_str}{ctx_str} [dim {dim}]·[/] [dim {dim}]Nous Research[/]")+ agg_label = _quiet(lambda: _moa_aggregator_label(model), "")+ agg_str = _dim_sep(f"agg {agg_label}") if agg_label else ""+ left_lines.append(f"[{accent}]MoA: {_short_label(model)}[/]{agg_str}{ctx_str}{nous_str}")+ elif not (model or "").strip() or (model or "").strip().lower() == "unknown":+ # Unconfigured install: say so in red instead of a blank/"unknown"+ # slug — this is the single clearest place to tell the user what+ # is wrong and how to fix it.+ left_lines.append(+ f"[bold red]no model configured[/] "+ f"[dim {dim}]— run /model or hermes setup[/]"+ )else:- if not (model or "").strip() or (model or "").strip().lower() == "unknown":- # Unconfigured install: say so in red instead of a blank/"unknown"- # slug — this is the single clearest place to tell the user what- # is wrong and how to fix it.- left_lines.append(- f"[bold red]no model configured[/] "- f"[dim {dim}]— run /model or hermes setup[/]"- )- else:- model_short = model.split("/")[-1] if "/" in model else model- if model_short.endswith(".gguf"):- model_short = model_short[:-5]- if len(model_short) > 28:- model_short = model_short[:25] + "..."- ctx_str = f" [dim {dim}]·[/] [dim {dim}]{_format_context_length(context_length)} context[/]" if context_length else ""- left_lines.append(f"[{accent}]{model_short}[/]{ctx_str} [dim {dim}]·[/] [dim {dim}]Nous Research[/]")+ model_short = model.split("/")[-1].removesuffix(".gguf")+ left_lines.append(f"[{accent}]{_short_label(model_short)}[/]{ctx_str}{nous_str}")if os.getenv("HERMES_YOLO_MODE"):left_lines.append(f"[bold red]⚠ YOLO mode[/] [dim {dim}]— all approval prompts bypassed[/]")left_lines.append(f"[dim {dim}]{cwd}[/]")if session_id:- left_lines.append(f"[dim {session_color}]Session: {session_id}[/]")+ left_lines.append(f"[dim {_skin_color('session_border', '#8B8682')}]Session: {session_id}[/]")left_content = "\n".join(left_lines)right_lines = [f"[bold {accent}]Available Tools[/]"]@@ -1083,126 +956,51 @@ def build_welcome_banner(console: "Console", model: str, cwd: str,toolsets_dict.setdefault(toolset, []).append(tool_name)for item in unavailable_toolsets:- toolset_id = item.get("id", item.get("name", "unknown"))- display_name = _display_toolset_name(toolset_id)- if display_name not in toolsets_dict:- toolsets_dict[display_name] = []+ names = toolsets_dict.setdefault(_display_toolset_name(item.get("id", item.get("name", "unknown"))), [])for tool_name in item.get("tools", []):- if tool_name not in toolsets_dict[display_name]:- toolsets_dict[display_name].append(tool_name)+ if tool_name not in names:+ names.append(tool_name)sorted_toolsets = sorted(toolsets_dict.keys())- display_toolsets = sorted_toolsets[:8]- remaining_toolsets = len(sorted_toolsets) - 8-- for toolset in display_toolsets:- tool_names = toolsets_dict[toolset]- colored_names = []- for name in sorted(tool_names):- if name in disabled_tools:- colored_names.append(f"[red]{name}[/]")- elif name in lazy_tools:- colored_names.append(f"[yellow]{name}[/]")- else:- colored_names.append(f"[{text}]{name}[/]")-- tools_str = ", ".join(colored_names)- if len(", ".join(sorted(tool_names))) > 45:- short_names = []- length = 0- for name in sorted(tool_names):- if length + len(name) + 2 > 42:- short_names.append("...")- break- short_names.append(name)- length += len(name) + 2- colored_names = []- for name in short_names:- if name == "...":- colored_names.append("[dim]...[/]")- elif name in disabled_tools:- colored_names.append(f"[red]{name}[/]")- elif name in lazy_tools:- colored_names.append(f"[yellow]{name}[/]")- else:- colored_names.append(f"[{text}]{name}[/]")- tools_str = ", ".join(colored_names)-- right_lines.append(f"[dim {dim}]{toolset}:[/] {tools_str}")-- if remaining_toolsets > 0:- right_lines.append(f"[dim {dim}](and {remaining_toolsets} more toolsets...)[/]")++ def _color_tool(name: Optional[str]) -> str:+ if name is None: # truncation marker+ return "[dim]...[/]"+ if name in disabled_tools:+ return f"[red]{name}[/]"+ if name in lazy_tools:+ return f"[yellow]{name}[/]"+ return f"[{text}]{name}[/]"++ for toolset in sorted_toolsets[:8]:+ tool_names = _truncate_tool_names(sorted(toolsets_dict[toolset]))+ right_lines.append(f"[dim {dim}]{toolset}:[/] {', '.join(_color_tool(n) for n in tool_names)}")++ if len(sorted_toolsets) > 8:+ right_lines.append(f"[dim {dim}](and {len(sorted_toolsets) - 8} more toolsets...)[/]")# MCP Servers section (only if configured). Probe cheaply first: the# full get_mcp_status() path resolves portable plugin MCP servers,# which JOINS the in-flight background plugin discovery (~100ms on the# startup path). When neither config.yaml nor the persisted plugin# key cache mentions any MCP server, skip the section outright.- mcp_status = []- try:- from hermes_cli.config import load_config as _load_cfg- _has_native_mcp = bool((_load_cfg() or {}).get("mcp_servers"))- except Exception:- _has_native_mcp = True # can't tell — take the full path- _has_portable_mcp = False- if not _has_native_mcp:- try:- from hermes_cli.plugins import get_portable_mcp_server_names_nowait- _has_portable_mcp = bool(get_portable_mcp_server_names_nowait())- except Exception:- _has_portable_mcp = True # can't tell — take the full path- if _has_native_mcp or _has_portable_mcp:- try:- from tools.mcp_tool import get_mcp_status- mcp_status = get_mcp_status()- except Exception:- mcp_status = []+ mcp_status = _quiet(_probe_mcp_status, []) if _mcp_configured() else []if mcp_status:- right_lines.append("")- right_lines.append(f"[bold {accent}]MCP Servers[/]")- for srv in mcp_status:- status = srv.get("status")- if srv["connected"]:- right_lines.append(- f"[dim {dim}]{srv['name']}[/] [{text}]({srv['transport']})[/] "- f"[dim {dim}]—[/] [{text}]{srv['tools']} tool(s)[/]"- )- elif srv.get("disabled") or status == "disabled":- right_lines.append(- f"[dim {dim}]{srv['name']}[/] [dim]({srv['transport']})[/] "- f"[dim {dim}]— disabled[/]"- )- elif status == "connecting":- right_lines.append(- f"[dim {dim}]{srv['name']}[/] [dim]({srv['transport']})[/] "- f"[yellow]— connecting[/]"- )- elif status == "configured":- right_lines.append(- f"[dim {dim}]{srv['name']}[/] [dim]({srv['transport']})[/] "- f"[dim {dim}]— configured[/]"- )- else:- right_lines.append(- f"[red]{srv['name']}[/] [dim]({srv['transport']})[/] "- f"[red]— failed[/]"- )+ right_lines += ["", f"[bold {accent}]MCP Servers[/]"]+ right_lines.extend(_mcp_server_line(srv, dim=dim, text=text) for srv in mcp_status)- right_lines.append("")- right_lines.append(f"[bold {accent}]Available Skills[/]")+ right_lines += ["", f"[bold {accent}]Available Skills[/]"]# The skills catalog is only reachable when the `skills` toolset is enabled# (it exposes skill_view / skill_manage). When it's disabled — e.g. a Blank# Slate install — the agent literally cannot load any skill, so advertising# the on-disk catalog here is misleading. Reflect the real state instead._skills_enabled = (not _enabled_ts) or ("skills" in _enabled_ts)- if _skills_enabled:- if skills_by_category is None:- skills_by_category = get_available_skills()- total_skills = sum(len(s) for s in skills_by_category.values())- else:+ if not _skills_enabled:skills_by_category = {}- total_skills = 0+ elif skills_by_category is None:+ skills_by_category = get_available_skills()+ total_skills = sum(len(s) for s in skills_by_category.values())# Dynamically size skills display based on terminal width.# Rich grid with 2 columns; right column gets roughly 60% of terminal.@@ -1213,31 +1011,14 @@ def build_welcome_banner(console: "Console", model: str, cwd: str,right_lines.append(f"[dim {dim}]Skills toolset disabled[/]")elif skills_by_category:for category in sorted(skills_by_category.keys()):- skill_names = sorted(skills_by_category[category])- # Account for "category: " prefix- _prefix_len = len(category) + 2- _avail = max(_right_col_width - _prefix_len, 20)- # Accumulate skills until we run out of space- parts, length = [], 0- for i, name in enumerate(skill_names):- _sep = ", " if parts else ""- _needed = len(_sep) + len(name)- # Estimate indicator size IF we were to add this skill then stop- _after = len(skill_names) - (i + 1) # remaining after adding this- _ind_len = len(f", +{_after} more") if _after > 0 else 0- if parts and length + _needed + _ind_len > _avail:- remaining = len(skill_names) - len(parts)- parts.append(f"+{remaining} more")- break- parts.append(name)- length += _needed- skills_str = ", ".join(parts)+ # Account for the "category: " prefix.+ skills_str = _pack_skill_names(sorted(skills_by_category[category]), max(_right_col_width - len(category) - 2, 20))right_lines.append(f"[dim {dim}]{category}:[/] [{text}]{skills_str}[/]")else:right_lines.append(f"[dim {dim}]No skills installed[/]")right_lines.append("")- mcp_connected = sum(1 for s in mcp_status if s["connected"]) if mcp_status else 0+ mcp_connected = sum(1 for s in mcp_status if s["connected"])summary_parts = [f"{len(tools)} tools", f"{total_skills} skills"]if mcp_connected:summary_parts.append(f"{mcp_connected} MCP servers")@@ -1245,24 +1026,15 @@ def build_welcome_banner(console: "Console", model: str, cwd: str,# Indicate when the codex_app_server runtime is active so users# understand why tool counts may not match what's actually reachable# (codex builds its own tool list inside the spawned subprocess).- try:- from hermes_cli.codex_runtime_switch import get_current_runtime- from hermes_cli.config import load_config as _load_cfg- if get_current_runtime(_load_cfg()) == "codex_app_server":- right_lines.append(- f"[bold {accent}]Runtime:[/] [{text}]codex app-server[/] "- f"[dim {dim}](terminal/file ops/MCP run inside codex)[/]"- )- except Exception:- pass- # Show active profile name when not 'default'- try:- from hermes_cli.profiles import get_active_profile_name- _profile_name = get_active_profile_name()- if _profile_name and _profile_name != "default":- right_lines.append(f"[bold {accent}]Profile:[/] [{text}]{_profile_name}[/]")- except Exception:- pass # Never break the banner over a profiles.py bug+ if _quiet(_codex_runtime_active, False):+ right_lines.append(+ f"[bold {accent}]Runtime:[/] [{text}]codex app-server[/] "+ f"[dim {dim}](terminal/file ops/MCP run inside codex)[/]"+ )+ # Show active profile name when not 'default'. Never break the banner over a profiles.py bug.+ _profile_name = _quiet(_active_profile_name)+ if _profile_name and _profile_name != "default":+ right_lines.append(f"[bold {accent}]Profile:[/] [{text}]{_profile_name}[/]")right_lines.append(f"[dim {dim}]{' · '.join(summary_parts)}[/]")@@ -1273,38 +1045,30 @@ def build_welcome_banner(console: "Console", model: str, cwd: str,# result isn't ready yet, defer the warning line: a daemon thread waits# for the prefetch and prints the same notice above the prompt when it# lands (prompt_toolkit's patch_stdout renders late prints safely).- try:+ def _update_line():behind = get_update_result(timeout=0.05)if behind is None and not _update_check_done.is_set():_defer_update_notice(console)elif behind is not None and behind != 0:right_lines.append(_format_update_notice(behind))- except Exception:- pass # Never break the banner over an update check- right_content = "\n".join(right_lines)- layout_table.add_row(left_content, right_content)+ _quiet(_update_line) # Never break the banner over an update check++ layout_table.add_row(left_content, "\n".join(right_lines))- title_color = _skin_color("banner_title", "#FFD700")- border_color = _skin_color("banner_border", "#CD7F32")version_label = format_banner_version_label()release_info = get_latest_release_tag()if release_info:- _tag, _url = release_info- title_markup = f"[bold {title_color}][link={_url}]{version_label}[/link][/]"- else:- title_markup = f"[bold {title_color}]{version_label}[/]"+ version_label = f"[link={release_info[1]}]{version_label}[/link]"outer_panel = Panel(layout_table,- title=title_markup,- border_style=border_color,+ title=f"[bold {_skin_color('banner_title', '#FFD700')}]{version_label}[/]",+ border_style=_skin_color("banner_border", "#CD7F32"),padding=(0, 2),)console.print()- term_width = shutil.get_terminal_size().columns- if term_width >= 95:- _logo = _bskin.banner_logo if _bskin and hasattr(_bskin, 'banner_logo') and _bskin.banner_logo else HERMES_AGENT_LOGO- console.print(_logo)+ if shutil.get_terminal_size().columns >= 95:+ console.print(getattr(_bskin, "banner_logo", None) or HERMES_AGENT_LOGO)console.print()console.print(outer_panel)diff --git a/hermes_cli/codex_models.py b/hermes_cli/codex_models.pyindex 2b17802d87d..d51b0d18bc3 100644--- a/hermes_cli/codex_models.py+++ b/hermes_cli/codex_models.py@@ -65,39 +65,34 @@ _FORWARD_COMPAT_TEMPLATE_MODELS: List[tuple[str, tuple[str, ...]]] = []+def _dedupe(model_ids) -> List[str]:+ """Order-preserving dedupe."""+ return list(dict.fromkeys(model_ids))++def _add_forward_compat_models(model_ids: List[str]) -> List[str]:"""Add Clawdbot-style synthetic forward-compat Codex models.- If a newer Codex slug isn't returned by live discovery, surface it when an- older compatible template model is present. This mirrors Clawdbot's- synthetic catalog / forward-compat behavior for GPT-5 Codex variants.+ If a newer Codex slug isn't returned by live discovery, surface it when an older compatible+ template model is present. This mirrors Clawdbot's synthetic catalog / forward-compat behavior+ for GPT-5 Codex variants."""- ordered: List[str] = []- seen: set[str] = set()- for model_id in model_ids:- if model_id not in seen:- ordered.append(model_id)- seen.add(model_id)-+ ordered = _dedupe(model_ids)+ seen = set(ordered)for synthetic_model, template_models in _FORWARD_COMPAT_TEMPLATE_MODELS:- if synthetic_model in seen:- continue- if any(template in seen for template in template_models):+ if synthetic_model not in seen and any(template in seen for template in template_models):ordered.append(synthetic_model)seen.add(synthetic_model)-return ordereddef _add_context_variants(model_ids: List[str]) -> List[str]:"""Insert ``-900k`` large-context picker variants after eligible base slugs.- The ChatGPT Codex backend advertises 272K for the gpt-5.4 / gpt-5.6- families but accepts ~911K (live-verified Aug 2026). The base slugs keep- the cheaper advertised 272K limit by default; each verified slug gets an- explicit ``<slug>-900k`` picker entry that opts into the large window.- The suffix is Hermes-side only — it is stripped before the model id hits- the wire (agent/transports/codex.py, agent/auxiliary_client.py).+ The base slugs keep the cheaper advertised 272K limit by default; each verified slug gets an+ explicit ``<slug>-900k`` picker entry that opts into the large window. The suffix is Hermes-side+ only — it is stripped before the model id hits the wire (agent/transports/codex.py,+ agent/auxiliary_client.py)."""from agent.model_metadata import (CODEX_CONTEXT_VARIANT_SUFFIX,@@ -124,16 +119,13 @@ def _finalize_codex_models(model_ids: List[str]) -> List[str]:def _extract_chatgpt_account_id(access_token: str) -> Optional[str]:"""Best-effort extraction of ``chatgpt_account_id`` from the OAuth JWT.- The Codex backend requires the ``ChatGPT-Account-Id`` header for the- per-account catalog. Without it, ``GET /backend-api/codex/models``- returns ``{"models":[]}`` (HTTP 200) — which masquerades as "no- models available" and silently degrades the picker to the curated- fallback list. The request-side path in ``auxiliary_client.py``- already extracts the same claim; this mirrors that logic here so the- probe sees the same catalog the request path will actually use.+ The Codex backend requires the ``ChatGPT-Account-Id`` header for the per-account catalog.+ Without it, ``GET /backend-api/codex/models`` returns ``{"models":[]}`` (HTTP 200) — which+ masquerades as "no models available" and silently degrades the picker to the curated fallback+ list.- Returns ``None`` on any parse error — the probe then degrades- gracefully to the unauthenticated fallback list instead of crashing.+ Returns ``None`` on any parse error — the probe then degrades gracefully to the unauthenticated+ fallback list instead of crashing."""try:parts = access_token.split(".")@@ -151,6 +143,31 @@ def _extract_chatgpt_account_id(access_token: str) -> Optional[str]:return None+def _ranked_slugs(entries: object) -> List[str]:+ """Visible model slugs from a Codex catalog ``models`` list, sorted by (priority, slug), deduped.++ Does not filter on ``supported_in_api``: that flag describes the public OpenAI API, while+ Hermes openai-codex talks to the same OAuth-backed Codex backend as Codex CLI, which still+ accepts slugs marked false there (for example gpt-5.3-codex-spark).+ """+ sortable = []+ for item in entries:+ if not isinstance(item, dict):+ continue+ slug = item.get("slug")+ if not isinstance(slug, str) or not slug.strip():+ continue+ visibility = item.get("visibility")+ if isinstance(visibility, str) and visibility.strip().lower() in {"hide", "hidden"}:+ continue+ priority = item.get("priority")+ rank = int(priority) if isinstance(priority, (int, float)) else 10_000+ sortable.append((rank, slug.strip()))++ sortable.sort()+ return _dedupe(slug for _, slug in sortable)++def _fetch_models_from_api(access_token: str) -> List[str]:"""Fetch available models from the Codex API. Returns visible models sorted by priority."""try:@@ -172,27 +189,7 @@ def _fetch_models_from_api(access_token: str) -> List[str]:logger.debug("Failed to fetch Codex models from API: %s", exc)return []- sortable = []- for item in entries:- if not isinstance(item, dict):- continue- slug = item.get("slug")- if not isinstance(slug, str) or not slug.strip():- continue- slug = slug.strip()- # Codex CLI's catalog uses ``supported_in_api`` for the public OpenAI- # API, not for the OAuth-backed Codex backend that this provider uses.- # Some valid Codex CLI models (for example gpt-5.3-codex-spark) are- # marked false here but are still accepted by the Codex route.- visibility = item.get("visibility", "")- if isinstance(visibility, str) and visibility.strip().lower() in {"hide", "hidden"}:- continue- priority = item.get("priority")- rank = int(priority) if isinstance(priority, (int, float)) else 10_000- sortable.append((rank, slug))-- sortable.sort(key=lambda x: (x[0], x[1]))- return _finalize_codex_models([slug for _, slug in sortable])+ return _finalize_codex_models(_ranked_slugs(entries))def _read_default_model(codex_home: Path) -> Optional[str]:@@ -201,16 +198,12 @@ def _read_default_model(codex_home: Path) -> Optional[str]:return Nonetry:import tomllib- except Exception:- return None- try:+payload = tomllib.loads(config_path.read_text(encoding="utf-8"))except Exception:return Nonemodel = payload.get("model") if isinstance(payload, dict) else None- if isinstance(model, str) and model.strip():- return model.strip()- return None+ return model.strip() if isinstance(model, str) and model.strip() else Nonedef _read_cache_models(codex_home: Path) -> List[str]:@@ -223,42 +216,16 @@ def _read_cache_models(codex_home: Path) -> List[str]:return []entries = raw.get("models") if isinstance(raw, dict) else None- sortable = []- if isinstance(entries, list):- for item in entries:- if not isinstance(item, dict):- continue- slug = item.get("slug")- if not isinstance(slug, str) or not slug.strip():- continue- slug = slug.strip()- # Do not filter on ``supported_in_api`` here. It describes the- # public OpenAI API, while Hermes openai-codex talks to the same- # OAuth-backed Codex backend as Codex CLI.- visibility = item.get("visibility")- if isinstance(visibility, str) and visibility.strip().lower() in {"hide", "hidden"}:- continue- priority = item.get("priority")- rank = int(priority) if isinstance(priority, (int, float)) else 10_000- sortable.append((rank, slug))-- sortable.sort(key=lambda item: (item[0], item[1]))- deduped: List[str] = []- for _, slug in sortable:- if slug not in deduped:- deduped.append(slug)- return deduped+ return _ranked_slugs(entries if isinstance(entries, list) else [])def get_codex_model_ids(access_token: Optional[str] = None) -> List[str]:"""Return available Codex model IDs, trying API first, then local sources.-- Resolution order: API (live, if token provided) > config.toml default >- local cache > hardcoded defaults.++ Resolution order: API (live, if token provided) > config.toml default > local cache > hardcoded+ defaults."""- codex_home_str = os.getenv("CODEX_HOME", "").strip() or str(Path.home() / ".codex")- codex_home = Path(codex_home_str).expanduser()- ordered: List[str] = []+ codex_home = Path(os.getenv("CODEX_HOME", "").strip() or str(Path.home() / ".codex")).expanduser()# Try live API if we have a tokenif access_token:@@ -268,15 +235,8 @@ def get_codex_model_ids(access_token: Optional[str] = None) -> List[str]:# Fall back to local sourcesdefault_model = _read_default_model(codex_home)- if default_model:- ordered.append(default_model)-- for model_id in _read_cache_models(codex_home):- if model_id not in ordered:- ordered.append(model_id)-- for model_id in DEFAULT_CODEX_MODELS:- if model_id not in ordered:- ordered.append(model_id)-- return _finalize_codex_models(ordered)+ return _finalize_codex_models(_dedupe([+ *([default_model] if default_model else []),+ *_read_cache_models(codex_home),+ *DEFAULT_CODEX_MODELS,+ ]))diff --git a/hermes_cli/codex_runtime_plugin_migration.py b/hermes_cli/codex_runtime_plugin_migration.pyindex 4b30d3ebf26..310867762fa 100644--- a/hermes_cli/codex_runtime_plugin_migration.py+++ b/hermes_cli/codex_runtime_plugin_migration.py@@ -1,37 +1,5 @@-"""Migrate Hermes' MCP server config and Codex's installed curated plugins-to the format Codex expects in ~/.codex/config.toml.--When the user enables the codex_app_server runtime, the codex subprocess-runs its own MCP client and its own plugin runtime (Linear, Atlassian,-Asana, plus per-account ChatGPT apps via app/list). For both of those to-be useful, the user's choices need to be visible to codex too. This-module:-- 1. Reads Hermes' YAML and writes equivalent [mcp_servers.<name>]- entries to ~/.codex/config.toml.- 2. Queries codex's `plugin/list` for the openai-curated marketplace- and writes [plugins."<name>@<marketplace>"] entries for any plugin- the user has installed=true on their codex CLI. (This is what- OpenClaw calls "migrate native codex plugins" — the YouTube-video-- worthy bit Pash highlighted: Canva, GitHub, Calendar, Gmail- pre-configured.)- 3. Writes a [permissions] default profile so users on this runtime- don't get an approval prompt on every write attempt.--What translates (MCP servers):- Hermes mcp_servers.<n>.command/args/env → codex stdio transport- Hermes mcp_servers.<n>.url/headers → codex streamable_http transport- Hermes mcp_servers.<n>.timeout → codex tool_timeout_sec- Hermes mcp_servers.<n>.connect_timeout → codex startup_timeout_sec--What does NOT translate (warned + skipped):- Hermes-specific keys (sampling, etc.) — codex's MCP client has no- equivalent. Listed in the per-server skipped[] field of the report.--What's NOT migrated (intentional):- AGENTS.md — codex respects this file natively in its cwd. Hermes' own- AGENTS.md (project-level) is already in the worktree, so codex picks- it up without translation. No code needed.+"""Migrate Hermes' MCP server config and Codex's installed curated plugins to the format Codex expects+in ~/.codex/config.toml."""from __future__ import annotations@@ -127,11 +95,9 @@ _KEYS_DROPPED_WITH_WARNING = {def _translate_one_server(name: str, hermes_cfg: dict) -> tuple[Optional[dict], list[str]]:- """Translate one Hermes MCP server config to the codex inline-table dict- representation. Returns (codex_entry, skipped_keys).-- codex_entry is a dict ready for TOML serialization, or None when the- server can't be translated (e.g. neither command nor url present)."""+ """Translate one Hermes MCP server config to the codex inline-table dict representation. Returns+ (codex_entry, skipped_keys).+ """if not isinstance(hermes_cfg, dict):return None, []@@ -199,8 +165,9 @@ def _translate_one_server(def _format_toml_value(value: Any) -> str:"""Minimal TOML value formatter for the value types we emit.- We only emit strings, numbers, booleans, and tables of those — no nested- arrays of tables. This covers everything codex's MCP schema accepts."""+ We only emit strings, numbers, booleans, and tables of those — no nested arrays of tables. This+ covers everything codex's MCP schema accepts.+ """if isinstance(value, bool):return "true" if value else "false"if isinstance(value, (int, float)):@@ -248,18 +215,11 @@ def render_codex_toml_section(plugins: Optional[list[dict]] = None,default_permission_profile: Optional[str] = None,) -> str:- """Render the managed [mcp_servers.<n>] / [plugins.<id>] / [permissions]- block for ~/.codex/config.toml.-- Args:- servers: dict of MCP server name → translated codex inline-table- plugins: optional list of {name, marketplace, enabled} for native- Codex plugins to enable. (E.g. the Linear / Atlassian / Asana- curated plugins, or per-account ChatGPT apps.)- default_permission_profile: when set, write `[permissions] default`- so the user doesn't get an approval prompt on every write- attempt. Common values: "workspace-write", "read-only",- "full-access".+ """Render the managed [mcp_servers.<n>] / [plugins.<id>] / [permissions] block for+ ~/.codex/config.toml.++ ``default_permission_profile`` (e.g. "workspace-write", "read-only", "full-access") writes+ ``[permissions] default`` so the user is not prompted on every write attempt."""out = [MIGRATION_MARKER]if not servers and not plugins and not default_permission_profile:@@ -307,11 +267,9 @@ def render_codex_toml_section(def _insert_managed_block_at_top_level(user_text: str, managed_block: str) -> str:"""Insert Hermes' managed Codex TOML block while keeping root keys root-scoped.- TOML has no syntax to return to the document root after a table header.- Therefore appending a root key like `default_permissions = ...` after a- user table such as `[features]` actually creates `features.default_permissions`,- which Codex rejects. Insert the managed block before the first table header- so its root keys remain top-level, while preserving user content verbatim.+ TOML has no syntax to return to the document root after a table header. Therefore appending a+ root key like `default_permissions = ...` after a user table such as `[features]` actually+ creates `features.default_permissions`, which Codex rejects."""if not user_text.strip():return managed_block@@ -336,28 +294,16 @@ def _insert_managed_block_at_top_level(user_text: str, managed_block: str) -> stdef _strip_unmanaged_plugin_tables(toml_text: str) -> str:- """Remove ``[plugins."<name>@<marketplace>"]`` tables that live OUTSIDE the- managed block.-- Codex itself writes these tables when the user runs ``codex plugins enable``- directly (i.e. before Hermes' migrate has ever touched the file). When we- later run migrate, ``_query_codex_plugins()`` reports the same plugins via- the live ``plugin/list`` RPC and we re-emit them inside the managed block.- The result without this strip is duplicate ``[plugins."X@Y"]`` table- headers — codex's strict TOML parser then refuses to load the file.-- We own the ``[plugins.*]`` namespace once migrate has run, so dropping any- pre-existing ``[plugins.*]`` tables is safe: ``plugin/list`` is the source- of truth for what's actually installed. The caller is expected to only- invoke this strip when ``plugin/list`` succeeded — otherwise we'd lose- plugins the user installed via ``codex`` without a way to re-emit them.-- Behavior:- * Lines beginning with ``[plugins.`` start a swallow region that ends at- the next non-``[plugins.`` table header or end-of-file.- * Content inside the managed block is untouched (callers should run- ``_strip_existing_managed_block`` first so the managed block has- already been removed when this runs).+ """Remove ``[plugins."<name>@<marketplace>"]`` tables that live OUTSIDE the managed block.++ Codex itself writes these tables when the user runs ``codex plugins enable`` directly (i.e.+ before Hermes' migrate has ever touched the file). When we later run migrate,+ ``_query_codex_plugins()`` reports the same plugins via the live ``plugin/list`` RPC and we re-+ emit them inside the managed block.++ We own the ``[plugins.*]`` namespace once migrate has run, so dropping any pre-existing+ ``[plugins.*]`` tables is safe: ``plugin/list`` is the source of truth for what's actually+ installed."""lines = toml_text.splitlines(keepends=True)out: list[str] = []@@ -384,11 +330,9 @@ def _strip_unmanaged_plugin_tables(toml_text: str) -> str:def _looks_like_table_header(stripped_line: str) -> bool:"""Return True if ``stripped_line`` is a TOML table header.- A header has the shape ``[name]`` or ``[[name]]`` (array-of-tables),- optionally followed by a comment. The closing ``]`` (or ``]]``) must- appear on the same line, and no key-assignment ``=`` can precede it.- This distinguishes real headers from multi-line array continuation- lines that also start with ``[`` after ``lstrip()``.+ A header has the shape ``[name]`` or ``[[name]]`` (array-of-tables), optionally followed by a+ comment. The closing ``]`` (or ``]]``) must appear on the same line, and no key-assignment ``=``+ can precede it."""if not stripped_line.startswith("["):return False@@ -404,16 +348,11 @@ def _looks_like_table_header(stripped_line: str) -> bool:def _strip_existing_managed_block(toml_text: str) -> str:"""Remove any prior managed section so re-runs idempotently replace it.- The managed section is everything between MIGRATION_MARKER (start) and- MIGRATION_END_MARKER (end), inclusive of both markers. User-edited- sections above or below are preserved verbatim.-- Backward compatibility: if the start marker is found but no end marker- follows, we fall back to the heuristic that swallows lines until we- hit a section that's not [mcp_servers.*]/[plugins.*]/[permissions]/- a `default_permissions =` key. This matches what older versions of- this code wrote so re-runs don't break configs from prior Hermes- versions."""+ The managed section spans MIGRATION_MARKER through MIGRATION_END_MARKER inclusive; user text+ outside it is preserved verbatim. If the start marker exists without an end marker (older+ writers), fall back to swallowing lines until a section that is not [mcp_servers.*]/+ [plugins.*]/[permissions]/``default_permissions =``, so prior-version configs still migrate.+ """lines = toml_text.splitlines(keepends=True)out: list[str] = []in_managed = False@@ -453,14 +392,9 @@ def _query_codex_plugins() -> tuple[list[dict], Optional[str]]:"""Query codex's `plugin/list` for installed curated plugins.- Spawns `codex app-server` briefly, sends initialize + plugin/list,- extracts plugins where installed=true. Returns (plugins, error).- Plugins is a list of {name, marketplace, enabled} dicts ready for- render_codex_toml_section().-- On any failure (codex not installed, RPC error, timeout) returns- ([], error_message). Migration treats this as non-fatal — MCP- servers and permissions still write through.+ Spawns ``codex app-server`` briefly, sends initialize + plugin/list and keeps installed=true.+ Returns ``(plugins, error)``; any failure (not installed, RPC error, timeout) yields ``([],+ error)`` and is non-fatal — MCP servers and permissions still write through."""try:from agent.transports.codex_app_server import CodexAppServerClient@@ -531,16 +465,10 @@ def _query_codex_plugins(def _looks_like_test_tempdir(path: str) -> bool:"""Heuristic: does ``path`` look like a pytest/transient tempdir?- pytest tempdirs live under ``pytest-of-<user>/pytest-<n>/`` (created via- ``tmp_path`` / ``tmp_path_factory``) and are reaped between sessions.- macOS routes ``/tmp`` through ``/private/var/folders/<…>/T`` which is- what pytest's tempdir factory uses by default. If a HERMES_HOME pointing- at one of those paths is burned into ``~/.codex/config.toml``, every- codex-routed hermes-tools call fails silently once the directory is GC'd.-- We err on the side of refusing — losing a (very unlikely) real- ``~/.hermes`` symlink that happens to live under ``/private/var/folders``- is much less harmful than silently bricking codex's tool surface.+ pytest tempdirs (``pytest-of-<user>/pytest-<n>/``, on macOS under ``/private/var/folders/…/T``)+ are reaped between sessions; a HERMES_HOME pointing there burned into ``~/.codex/config.toml``+ makes every codex-routed call fail silently once GC'd. Err on refusing: a false positive is far+ less harmful than silently bricking codex's tool surface."""if not path:return False@@ -555,14 +483,10 @@ def _looks_like_test_tempdir(path: str) -> bool:def _build_hermes_tools_mcp_entry() -> dict:- """Build the codex stdio-transport entry that launches Hermes' own- tool surface as an MCP server. Codex's subprocess will call back into- this for browser/web/delegate_task/vision/memory/skills tools.-- The command runs the worktree's Python via the current sys.executable- so a hermes installed under /opt/, /usr/local/, or a venv all work.- HERMES_HOME and PYTHONPATH are passed through so the spawned process- sees the same config + module layout the user is running."""+ """Build the codex stdio-transport entry that launches Hermes' own tool surface as an MCP server.+ Codex's subprocess will call back into this for browser/web/delegate_task/vision/memory/skills+ tools.+ """import sysenv: dict[str, str] = {}@@ -615,31 +539,13 @@ def migrate(default_permission_profile: Optional[str] = ":workspace",expose_hermes_tools: bool = True,) -> MigrationReport:- """Translate Hermes mcp_servers config + Codex curated plugins into- ~/.codex/config.toml.+ """Translate Hermes mcp_servers config + Codex curated plugins into ~/.codex/config.toml.- Args:- hermes_config: full ~/.hermes/config.yaml dict- codex_home: override CODEX_HOME (defaults to ~/.codex)- dry_run: skip the actual write; report what would happen- discover_plugins: when True (default), query `plugin/list` against- the live codex CLI to migrate any installed curated plugins- into [plugins."<name>@<marketplace>"] entries. Set False to- skip the subprocess spawn (for tests or restricted environments).- default_permission_profile: when set (default ":workspace"), write- top-level `default_permissions = "<name>"` so users on this- runtime don't get an approval prompt on every write attempt.- Built-in codex profile names are ":workspace", ":read-only",- ":danger-no-sandbox" (note the leading ":"). Also accepts a- user-defined profile name (no leading ":") that the user has- configured in their own [permissions.<name>] table. Set None- to leave permissions unset and let codex use its compiled-in- default (which is read-only).- expose_hermes_tools: when True (default), register Hermes' own- tool surface (web_search, browser_*, delegate_task, vision,- memory, skills, etc.) as an MCP server in ~/.codex/config.toml- so the codex subprocess can call back into Hermes for tools- codex doesn't have built in. Set False to opt out.+ ``discover_plugins`` spawns the live codex CLI (set False in tests).+ ``default_permission_profile`` (default ":workspace"; built-ins carry a leading ":", user+ profiles do not; None leaves codex's read-only default) avoids an approval prompt on every+ write. ``expose_hermes_tools`` registers Hermes' own tool surface as an MCP server so the codex+ subprocess can call back for tools it lacks."""report = MigrationReport(dry_run=dry_run)codex_home = codex_home or Path.home() / ".codex"diff --git a/hermes_cli/codex_runtime_switch.py b/hermes_cli/codex_runtime_switch.pyindex 06bff58e2e1..18f5224b80f 100644--- a/hermes_cli/codex_runtime_switch.py+++ b/hermes_cli/codex_runtime_switch.py@@ -1,18 +1,12 @@"""Shared logic for the /codex-runtime slash command.-Toggles `model.openai_runtime` between "auto" (= chat_completions, Hermes'-default) and "codex_app_server" (= hand turns to a codex subprocess).--Both CLI (cli.py) and gateway (gateway/run.py) call into this module so the-behavior stays identical across surfaces.--The actual runtime resolution happens in hermes_cli.runtime_provider's-_maybe_apply_codex_app_server_runtime() helper, which reads the persisted-config value. This module just persists the value and reports the change.+Both CLI (cli.py) and gateway (gateway/run.py) call into this module so the behavior stays identical+across surfaces."""from __future__ import annotations+import functoolsimport loggingfrom dataclasses import dataclassfrom typing import Optional@@ -33,16 +27,13 @@ class CodexRuntimeStatus:old_value: Optional[str] = Nonemessage: str = ""requires_new_session: bool = False- codex_binary_ok: bool = True- codex_version: Optional[str] = Nonedef parse_args(arg_string: str) -> tuple[Optional[str], list[str]]:"""Parse the slash-command argument string. Returns (value, errors).- No args → return current state (value=None)- 'auto' / 'codex_app_server' / 'on' / 'off' → return that value- anything else → error+ No args returns the current state (value=None); ``auto``/``codex_app_server``/``on``/``off``+ return that value; anything else is an error."""raw = (arg_string or "").strip().lower()if not raw:@@ -106,27 +97,15 @@ def apply() -> CodexRuntimeStatus:"""Top-level entry point used by both CLI and gateway handlers.- Args:- config: in-memory config dict (will be mutated when new_value is set)- new_value: desired runtime; None means "show current state only"- persist_callback: optional callable taking the mutated config dict- and persisting it to disk. Skipped when None (used by tests).-- Returns: CodexRuntimeStatus describing the outcome.+ ``config`` is mutated in place when ``new_value`` is set (None means show current state+ only). ``persist_callback`` receives the mutated dict to write it to disk; skipped when None+ (tests)."""current = get_current_runtime(config)- # Cache the codex binary check for this apply() call. Subprocess spawn- # is cheap (~50ms for `codex --version`), but we'd otherwise call it up- # to 3 times in the enable path (read-only/state, gate, success message).- # None = not yet checked; (bool, str) = result.- _binary_check: Optional[tuple[bool, Optional[str]]] = None-- def _check_binary_cached() -> tuple[bool, Optional[str]]:- nonlocal _binary_check- if _binary_check is None:- _binary_check = check_codex_binary_ok()- return _binary_check+ # Cache the codex binary check for this apply() call: the enable path+ # would otherwise spawn `codex --version` up to 3 times (state, gate, message).+ _check_binary_cached = functools.cache(check_codex_binary_ok)# Read-only call: just report stateif new_value is None:@@ -140,8 +119,6 @@ def apply(new_value=current,old_value=current,message=msg,- codex_binary_ok=ok,- codex_version=ver if ok else None,)# No-config-change paths. For `auto` we return immediately — disabling@@ -177,8 +154,6 @@ def apply(f"{ver_or_msg or 'codex CLI not available'}\n""Install with: npm i -g @openai/codex"),- codex_binary_ok=False,- codex_version=None,)if not reapplying_enable:@@ -195,12 +170,11 @@ def apply(message=f"updated config in memory but persist failed: {exc}",)- if reapplying_enable:- msg_lines = [- f"openai_runtime already set to {current} — re-applying migration"- ]- else:- msg_lines = [f"openai_runtime: {current} → {new_value}"]+ msg_lines = [+ f"openai_runtime already set to {current} — re-applying migration"+ if reapplying_enable+ else f"openai_runtime: {current} → {new_value}"+ ]if new_value == "codex_app_server":ok, ver = _check_binary_cached()if ok:diff --git a/hermes_cli/fallback_cmd.py b/hermes_cli/fallback_cmd.pyindex 56c9021ccee..3b00430937b 100644--- a/hermes_cli/fallback_cmd.py+++ b/hermes_cli/fallback_cmd.py@@ -1,20 +1,13 @@-"""-hermes fallback — manage the fallback provider chain.--Fallback providers are tried in order when the primary model fails with-rate-limit, overload, or connection errors. See:-https://hermes-agent.nousresearch.com/docs/user-guide/features/fallback-providers--Subcommands:- hermes fallback [list] Show the current fallback chain (default when no subcommand)- hermes fallback add Pick provider + model via the same picker as `hermes model`,- then append the selection to the chain- hermes fallback remove Pick an entry to delete from the chain- hermes fallback clear Remove all fallback entries--Storage: ``fallback_providers`` in ``~/.hermes/config.yaml`` (top-level, list of-``{provider, model, base_url?, api_mode?}`` dicts). The legacy single-dict-``fallback_model`` format is migrated to the new list format on first add.+"""hermes fallback — manage the fallback provider chain.++Fallback providers are tried in order when the primary model fails with rate-limit, overload, or+connection errors. See: https://hermes-agent.nousresearch.com/docs/user-guide/features/fallback-+providers++Subcommands: hermes fallback [list] Show the current fallback chain (default when no subcommand)+hermes fallback add Pick provider + model via the same picker as `hermes model`, then append the+selection to the chain hermes fallback remove Pick an entry to delete from the chain hermes fallback+clear Remove all fallback entries"""from __future__ import annotations@@ -24,6 +17,17 @@ from typing import Any, Dict, List, Optionalfrom hermes_cli.fallback_config import get_fallback_chain+def _identity(entry: Dict[str, Any]):+ """BackendIdentity for a ``{provider, model, base_url?}`` entry."""+ from agent.backend_identity import BackendIdentity++ return BackendIdentity.build(+ provider=entry.get("provider"),+ model=entry.get("model"),+ base_url=entry.get("base_url"),+ )++# ---------------------------------------------------------------------------# Helpers# ---------------------------------------------------------------------------@@ -31,10 +35,10 @@ from hermes_cli.fallback_config import get_fallback_chaindef _read_chain(config: Dict[str, Any]) -> List[Dict[str, Any]]:"""Return the normalized fallback chain as a list of dicts.- Accepts both the new list format (``fallback_providers``) and the legacy- ``fallback_model`` format. When both are present, the effective chain is- merged with ``fallback_providers`` entries kept first. The returned list is- always a fresh copy — callers can mutate without touching the config dict.+ Accepts both the new list format (``fallback_providers``) and the legacy ``fallback_model``+ format. When both are present, the effective chain is merged with ``fallback_providers`` entries+ kept first. The returned list is always a fresh copy — callers can mutate without touching the+ config dict."""return get_fallback_chain(config)@@ -43,17 +47,13 @@ def _write_chain(config: Dict[str, Any], chain: List[Dict[str, Any]]) -> None:"""Persist the chain to ``fallback_providers`` and clear legacy key."""config["fallback_providers"] = chain# Drop the legacy single-dict key on write so there's only one source of truth.- if "fallback_model" in config:- config.pop("fallback_model", None)+ config.pop("fallback_model", None)def _format_entry(entry: Dict[str, Any]) -> str:"""One-line human-readable rendering of a fallback entry."""- provider = entry.get("provider", "?")- model = entry.get("model", "?")base = entry.get("base_url")- suffix = f" [{base}]" if base else ""- return f"{model} (via {provider}){suffix}"+ return f"{entry.get('model', '?')} (via {entry.get('provider', '?')}){f' [{base}]' if base else ''}"def _extract_fallback_from_model_cfg(model_cfg: Any) -> Optional[Dict[str, Any]]:@@ -66,12 +66,10 @@ def _extract_fallback_from_model_cfg(model_cfg: Any) -> Optional[Dict[str, Any]]if not provider or not model:return Noneentry: Dict[str, Any] = {"provider": provider, "model": model}- base_url = (model_cfg.get("base_url") or "").strip()- if base_url:- entry["base_url"] = base_url- api_mode = (model_cfg.get("api_mode") or "").strip()- if api_mode:- entry["api_mode"] = api_mode+ for key in ("base_url", "api_mode"):+ value = (model_cfg.get(key) or "").strip()+ if value:+ entry[key] = valuereturn entry@@ -79,8 +77,7 @@ def _snapshot_auth_active_provider() -> Any:"""Return the current ``active_provider`` in auth.json, or a sentinel if unavailable."""try:from hermes_cli.auth import _load_auth_store- store = _load_auth_store()- return store.get("active_provider")+ return _load_auth_store().get("active_provider")except Exception:return None@@ -104,29 +101,45 @@ def _restore_auth_active_provider(value: Any) -> None:# Subcommand handlers# ----------------------------------------------------------------------------def cmd_fallback_list(args) -> None: # noqa: ARG001- """Print the current fallback chain."""+def _entries(n: int) -> str:+ return f"{n} {'entry' if n == 1 else 'entries'}"+++def _print_chain(heading: str, chain: List[Dict[str, Any]]) -> None:+ print(f" {heading} ({_entries(len(chain))}):")+ for i, entry in enumerate(chain, 1):+ print(f" {i}. {_format_entry(entry)}")+ print()+++def _load_chain(empty_message: str):+ """Load config + chain; print ``empty_message`` block and return ``(config, None)`` when empty."""from hermes_cli.config import load_configconfig = load_config()chain = _read_chain(config)-- print()if not chain:- print(" No fallback providers configured.")print()+ print(empty_message)+ print()+ return config, None+ return config, chain+++def cmd_fallback_list(args) -> None: # noqa: ARG001+ """Print the current fallback chain."""+ config, chain = _load_chain(" No fallback providers configured.")+ if chain is None:print(" Add one with: hermes fallback add")print()return+ print()primary = _describe_primary(config)if primary:print(f" Primary: {primary}")print()- print(f" Fallback chain ({len(chain)} {'entry' if len(chain) == 1 else 'entries'}):")- for i, entry in enumerate(chain, 1):- print(f" {i}. {_format_entry(entry)}")- print()+ _print_chain("Fallback chain", chain)print(" Tried in order when the primary fails (rate-limit, 5xx, connection errors).")print(" Docs: https://hermes-agent.nousresearch.com/docs/user-guide/features/fallback-providers")print()@@ -162,12 +175,15 @@ def cmd_fallback_add(args) -> None:print(" `hermes model` — select the provider + model you want as a fallback.")print()+ def _restore() -> None:+ _restore_model_cfg(model_before)+ _restore_auth_active_provider(active_provider_before)+try:select_provider_and_model(args=args)except SystemExit:# Some provider flows exit on auth failure — restore state and re-raise.- _restore_model_cfg(model_before)- _restore_auth_active_provider(active_provider_before)+ _restore()raise# Read the post-picker state to see what the user selected.@@ -177,8 +193,7 @@ def cmd_fallback_add(args) -> None:new_entry = _extract_fallback_from_model_cfg(model_after)if not new_entry:# Picker didn't complete (user cancelled or flow bailed). Nothing to do.- _restore_model_cfg(model_before)- _restore_auth_active_provider(active_provider_before)+ _restore()print()print(" No fallback added.")return@@ -188,24 +203,12 @@ def cmd_fallback_add(args) -> None:# semantics owned by agent.backend_identity (#54250/#57584/#62984): same# provider+model on a DIFFERENT explicit base_url is a different backend# (multi-endpoint pool) and is a legitimate fallback.- from agent.backend_identity import BackendIdentity, same_deployment+ from agent.backend_identity import same_deployment- new_ident = BackendIdentity.build(- provider=new_entry.get("provider"),- model=new_entry.get("model"),- base_url=new_entry.get("base_url"),- )+ new_ident = _identity(new_entry)primary_entry = _extract_fallback_from_model_cfg(model_before)- if primary_entry and same_deployment(- BackendIdentity.build(- provider=primary_entry.get("provider"),- model=primary_entry.get("model"),- base_url=primary_entry.get("base_url"),- ),- new_ident,- ):- _restore_model_cfg(model_before)- _restore_auth_active_provider(active_provider_before)+ if primary_entry and same_deployment(_identity(primary_entry), new_ident):+ _restore()print()print(f" Selected model matches the current primary ({_format_entry(new_entry)}).")print(" A provider cannot be a fallback for itself — no change.")@@ -215,26 +218,17 @@ def cmd_fallback_add(args) -> None:# to ``fallback_providers``. We deliberately re-load (rather than mutating# ``after_cfg``) because the picker may have touched other top-level keys# (custom_providers, providers credentials) that we want to keep.- _restore_model_cfg(model_before)- _restore_auth_active_provider(active_provider_before)+ _restore()final_cfg = load_config()chain = _read_chain(final_cfg)# Reject exact-duplicate fallback entries (same deployment; a different# explicit base_url is a different endpoint and NOT a duplicate).- for existing in chain:- if same_deployment(- BackendIdentity.build(- provider=existing.get("provider"),- model=existing.get("model"),- base_url=existing.get("base_url"),- ),- new_ident,- ):- print()- print(f" {_format_entry(new_entry)} is already in the fallback chain — skipped.")- return+ if any(same_deployment(_identity(existing), new_ident) for existing in chain):+ print()+ print(f" {_format_entry(new_entry)} is already in the fallback chain — skipped.")+ returnchain.append(new_entry)_write_chain(final_cfg, chain)@@ -242,7 +236,7 @@ def cmd_fallback_add(args) -> None:print()print(f" Added fallback: {_format_entry(new_entry)}")- print(f" Chain is now {len(chain)} {'entry' if len(chain) == 1 else 'entries'} long.")+ print(f" Chain is now {_entries(len(chain))} long.")print()print(" Run `hermes fallback list` to view, or `hermes fallback remove` to delete.")@@ -261,19 +255,13 @@ def _restore_model_cfg(model_before: Any) -> None:def cmd_fallback_remove(args) -> None: # noqa: ARG001"""Pick an entry from the chain and remove it."""- from hermes_cli.config import load_config, save_config+ from hermes_cli.config import save_config- config = load_config()- chain = _read_chain(config)-- if not chain:- print()- print(" No fallback providers configured — nothing to remove.")- print()+ config, chain = _load_chain(" No fallback providers configured — nothing to remove.")+ if chain is None:return- choices = [_format_entry(e) for e in chain]- choices.append("Cancel")+ choices = [_format_entry(e) for e in chain] + ["Cancel"]try:from hermes_cli.setup import _curses_prompt_choice@@ -292,31 +280,20 @@ def cmd_fallback_remove(args) -> None: # noqa: ARG001print()print(f" Removed fallback: {_format_entry(removed)}")- if chain:- print(f" Chain is now {len(chain)} {'entry' if len(chain) == 1 else 'entries'} long.")- else:- print(" Fallback chain is now empty.")+ print(f" Chain is now {_entries(len(chain))} long." if chain else " Fallback chain is now empty.")print()def cmd_fallback_clear(args) -> None: # noqa: ARG001"""Remove all fallback entries (with confirmation)."""- from hermes_cli.config import load_config, save_config-- config = load_config()- chain = _read_chain(config)+ from hermes_cli.config import save_config- if not chain:- print()- print(" No fallback providers configured — nothing to clear.")- print()+ config, chain = _load_chain(" No fallback providers configured — nothing to clear.")+ if chain is None:returnprint()- print(f" Current fallback chain ({len(chain)} {'entry' if len(chain) == 1 else 'entries'}):")- for i, entry in enumerate(chain, 1):- print(f" {i}. {_format_entry(entry)}")- print()+ _print_chain("Current fallback chain", chain)try:resp = input(" Clear all entries? [y/N]: ").strip().lower()except (KeyboardInterrupt, EOFError):@@ -363,15 +340,17 @@ def _numbered_pick(question: str, choices: List[str]) -> Optional[int]:def cmd_fallback(args) -> None:"""Top-level dispatcher for ``hermes fallback [subcommand]``."""sub = getattr(args, "fallback_command", None)- if sub in {None, "", "list", "ls"}:- cmd_fallback_list(args)- elif sub == "add":- cmd_fallback_add(args)- elif sub in {"remove", "rm"}:- cmd_fallback_remove(args)- elif sub == "clear":- cmd_fallback_clear(args)- else:+ handler = _SUBCOMMANDS.get(sub)+ if handler is None:print(f"Unknown fallback subcommand: {sub}")print("Use one of: list, add, remove, clear")raise SystemExit(2)+ handler(args)+++_SUBCOMMANDS = {+ None: cmd_fallback_list, "": cmd_fallback_list, "list": cmd_fallback_list, "ls": cmd_fallback_list,+ "add": cmd_fallback_add,+ "remove": cmd_fallback_remove, "rm": cmd_fallback_remove,+ "clear": cmd_fallback_clear,+}diff --git a/hermes_cli/inventory.py b/hermes_cli/inventory.pyindex f9b0de4d90c..46c9428574e 100644--- a/hermes_cli/inventory.py+++ b/hermes_cli/inventory.py@@ -1,34 +1,5 @@-"""Provider/model inventory context — shared substrate for the dashboard-``/api/model/options``, the TUI ``model.options``/``model.save_key``-JSON-RPC handlers, and the interactive picker.--Before this module the three call-sites each duplicated:--1. The 17-LOC config-slice that pulls ``model.{default,name,provider,base_url}``,- ``providers:``, and ``custom_providers:`` out of ``load_config()``;-2. The call into ``list_authenticated_providers`` with the resulting kwargs;-3. (TUI only) a 45-LOC post-pass that merges authenticated rows with- unconfigured ``CANONICAL_PROVIDERS`` rows and emits ``authenticated``/- ``auth_type``/``key_env``/``warning`` hints for the picker UI.--Consolidating those three steps into one entry point eliminates two bugs-the duplicates were hiding:--- The dashboard read ``cfg.get("custom_providers")`` directly, missing the- v12+ keyed ``providers:`` form (which the TUI handled via- ``get_compatible_custom_providers``).-- The TUI's canonical-merge keyed on ``is_user_defined`` to decide- ordering. Section 3 of ``list_authenticated_providers`` sets- ``is_user_defined=True`` even for canonical slugs that appear in the- ``providers:`` config dict, which silently demoted them to the tail of- the picker. ``_reorder_canonical`` keys on slug membership instead.--Substrate facts (verified May 2026):-- ``list_authenticated_providers`` already populates each row's- ``models`` from the curated catalog (same source as the picker). Do- NOT call ``provider_model_ids()`` per row to "freshen" — that bypasses- curation and pulls in non-agentic models (Nous /models returns ~400- IDs including TTS, embeddings, rerankers, image/video generators).+"""Provider/model inventory context — shared substrate for the dashboard ``/api/model/options``, the+TUI ``model.options``/``model.save_key`` JSON-RPC handlers, and the interactive picker."""from __future__ import annotations@@ -42,9 +13,9 @@ from typing import Any, Optional@dataclass(frozen=True)class ConfigContext:- """Snapshot of the model + provider config every inventory caller- needs. Built once via ``load_picker_context()``; the TUI overlays- live agent state via ``with_overrides()`` before passing through.+ """Snapshot of the model + provider config every inventory caller needs. Built once via+ ``load_picker_context()``; the TUI overlays live agent state via ``with_overrides()`` before+ passing through."""current_provider: str@@ -63,26 +34,23 @@ class ConfigContext:) -> "ConfigContext":"""Return a copy with truthy overrides applied.- Truthy-only because the TUI reads agent attributes that may be- empty strings before an agent is spawned — empties must NOT- clobber the disk-config values.+ Truthy-only because the TUI reads agent attributes that may be empty strings before an agent+ is spawned — empties must NOT clobber the disk-config values."""- kw: dict = {}- if current_provider:- kw["current_provider"] = current_provider- if current_model:- kw["current_model"] = current_model- if current_base_url:- kw["current_base_url"] = current_base_url+ kw = {+ k: v+ for k, v in (+ ("current_provider", current_provider),+ ("current_model", current_model),+ ("current_base_url", current_base_url),+ )+ if v+ }return replace(self, **kw) if kw else selfdef load_picker_context() -> ConfigContext:- """Load the disk-config snapshot every consumer needs.-- Replaces the inline 17-LOC config-slice that ``web_server.py`` and- ``tui_gateway/server.py`` (×2 sites) used to do.- """+ """Load the disk-config snapshot every consumer needs."""from hermes_cli.config import (coerce_provider_id,get_compatible_custom_providers,@@ -114,6 +82,14 @@ def load_picker_context() -> ConfigContext:)+def _slug(row: dict) -> str:+ return str(row.get("slug") or "").strip().lower()+++def _without_slug(rows: list[dict], slug: str) -> list[dict]:+ return [r for r in rows if _slug(r) != slug]++# ─── Public: payload builder ────────────────────────────────────────────@@ -134,60 +110,11 @@ def build_models_payload(for_picker: bool = False,max_models: int | None = None,) -> dict:- """Build the ``{providers, model, provider}`` shape every consumer- needs from a single substrate call.-- Flags:- - ``explicit_only``: keep only providers the user explicitly configured- (current provider, providers from config, or providers backed by- provider-specific env vars). This hides ambient / auto-seeded- credentials from desktop chat pickers.- - ``include_unconfigured``: append ``CANONICAL_PROVIDERS`` rows that- ``list_authenticated_providers`` didn't emit (TUI uses this to show- the full provider universe in the picker).- - ``picker_hints``: add ``authenticated``/``auth_type``/``key_env``/- ``warning`` per row (TUI ``ModelPickerDialog`` shape).- - ``canonical_order``: reorder canonical-slug rows to- ``CANONICAL_PROVIDERS`` declaration order; truly-custom rows go- last (TUI display order).- - ``pricing``: enrich each row with formatted per-model pricing and,- for Nous, ``free_tier``/``unavailable_models`` so the GUI picker can- show $/Mtok columns and gate paid models on free accounts —- mirroring the ``hermes model`` CLI picker. Adds network calls- (pricing fetch + Nous tier check); only set for interactive pickers.- - ``capabilities``: add a per-row ``capabilities`` map- ``{model: {fast, reasoning}}`` so pickers can gate the model-options- controls (fast toggle / reasoning) to what each model actually- supports, instead of offering knobs the backend would reject.- - ``featured``: add a per-row ``featured_models`` list — the newest few- models per lab (by models.dev release_date, ranked within the row's own- models; see ``_FEATURED_PER_LAB``) for aggregator providers that serve- dozens of models across many labs. Pickers default their visible set to- these; the rest of ``models`` stays reachable via search / show-all. Empty- for single-lab providers (callers fall back to top-N). Derived live from- models.dev — no allowlist.- - ``force_fresh_nous_tier``: bypass the short Nous free-tier cache when- selecting Portal-recommended Nous models and applying tier gating. Keep- this false for UI picker opens; explicit auth/model flows can opt in- when they need freshly-purchased credits to show up immediately.- - ``refresh``: bust the per-provider model-id disk cache so every row- re-fetches its live catalog. Set only for an explicit user-triggered- "refresh models" action; normal picker opens leave it false to stay- snappy on the 1h cache.- - ``probe_custom_providers``: allow saved custom/provider endpoints to- run live ``/models`` discovery while building the payload. GUI picker- opens should leave this false unless the user explicitly refreshes; the- row can still render its configured model immediately, and slow/offline- local endpoints no longer block the dialog.- - ``probe_current_custom_provider``: when ``probe_custom_providers`` is- false, still live-probe the current custom endpoint. This keeps normal- GUI/TUI picker opens fast while making the active custom provider's model- list match the classic CLI picker.- - ``for_picker``: interactive-picker visibility. Keeps providers whose- credential pool exists but is entirely rate-limited (exhausted) in the- list. Rate limits are per-model, so a different model under the same- provider may still work; hiding the provider strands the user. Set for- any surface a human is choosing from, not for programmatic resolution.+ """Build the ``{providers, model, provider}`` shape every consumer needs from a single substrate call.++ Flags: - ``explicit_only``: keep only providers the user explicitly configured (current+ provider, providers from config, or providers backed by provider-specific env vars). This hides+ ambient / auto-seeded credentials from desktop chat pickers."""from hermes_cli.model_switch import list_authenticated_providers@@ -214,8 +141,7 @@ def build_models_payload(# through the llamacpp alias -> managed/detected server resolution.local_row = _local_runtime_row(ctx)if local_row is not None:- rows = [r for r in rows if str(r.get("slug", "")).lower() != "llamacpp"]- rows.append(local_row)+ rows = _without_slug(rows, "llamacpp") + [local_row]# A live session on the managed server reports provider "custom"# (the resolution seam's generic label for a raw base_url), which# would otherwise materialize a duplicate "Custom endpoint" row@@ -223,17 +149,17 @@ def build_models_payload(# Local row owns the managed server's identity — drop custom rows# that point at the managed endpoint.if local_row.get("is_current"):+ staged = set(local_row["models"])+def _is_managed_custom(row: dict) -> bool:- if str(row.get("slug", "")).lower() != "custom":- return Falsemodels = {str(m) for m in (row.get("models") or [])}- return bool(models) and models <= set(local_row["models"])+ return _slug(row) == "custom" and bool(models) and models <= stagedrows = [r for r in rows if not _is_managed_custom(r)]moa_row = _moa_provider_row(ctx.current_provider)if moa_row is not None:- rows = [moa_row] + [r for r in rows if str(r.get("slug", "")).lower() != "moa"]+ rows = [moa_row] + _without_slug(rows, "moa")if explicit_only:rows = _filter_explicit_provider_rows(rows, ctx)@@ -248,9 +174,7 @@ def build_models_payload(_local_owns_current = bool(local_row and local_row.get("is_current")and (ctx.current_provider or "").lower() == "custom")if not _local_owns_current:- rows = list(rows) + _append_unconfigured_rows(- rows, ctx, current_only=True- )+ rows = list(rows) + _append_unconfigured_rows(rows, ctx, current_only=True)# --- Deduplicate: remove models from aggregators that overlap with# user-defined providers. When a local proxy (e.g. litellm-proxy)@@ -261,44 +185,10 @@ def build_models_payload(# breaking the call. Filtering at the payload level keeps the# aggregator rows honest: they only show models the user can't get# from a more-specific provider. (#45954)- try:- from hermes_cli.providers import is_routing_aggregator as _is_routing_aggregator- except Exception:- _is_routing_aggregator = None # type: ignore[assignment]-- if _is_routing_aggregator is not None:- user_models: set[str] = set()- for row in rows:- if row.get("is_user_defined"):- user_models.update(m.lower() for m in (row.get("models") or []))- if user_models:- for row in rows:- # A user's own configured provider is never an "aggregator- # duplicate" of itself: user_models is built from these very- # rows, and is_routing_aggregator() reports True for every- # custom:* slug. Without this guard the dedup strips a- # user-defined custom provider's entire model list (all of it- # lives in user_models), emptying its picker row.- if row.get("is_user_defined"):- continue- slug = row.get("slug", "")- # Only strip overlaps from TRUE routing aggregators (OpenRouter,- # custom:* proxies). Flat-namespace resellers (opencode-go /- # opencode-zen) serve every listed model as a first-party model,- # so their rows must keep models that a user's proxy happens to- # share a name with — otherwise a subscription provider's own- # catalog (minimax-m3, glm-5, deepseek-v4-flash, ...) is silently- # gutted in the picker. (#47077)- if not _is_routing_aggregator(slug):- continue- original = row.get("models") or []- filtered = [m for m in original if m.lower() not in user_models]- if len(filtered) < len(original):- row["models"] = filtered- row["total_models"] = len(filtered)+ _strip_aggregator_overlaps(rows)if include_unconfigured:- rows = list(rows) + [r for r in _append_unconfigured_rows(rows, ctx) if str(r.get("slug", "")).lower() != "moa"]+ rows = list(rows) + _without_slug(_append_unconfigured_rows(rows, ctx), "moa")if picker_hints:_apply_picker_hints(rows)if canonical_order:@@ -318,6 +208,37 @@ def build_models_payload(}+def _strip_aggregator_overlaps(rows: list[dict]) -> None:+ """Drop models from TRUE routing aggregators (OpenRouter, custom:* proxies) that a user-defined+ provider also serves, so the picker never lists them under both (#45954).++ A user's own configured provider is never an "aggregator duplicate" of itself: user_models is+ built from these very rows, and is_routing_aggregator() reports True for every custom:* slug —+ without that guard the dedup would empty a user-defined custom provider's row. Flat-namespace+ resellers (opencode-go / opencode-zen) serve every listed model first-party and must keep models+ that a user's proxy happens to share a name with (#47077).+ """+ try:+ from hermes_cli.providers import is_routing_aggregator+ except Exception:+ return++ user_models: set[str] = set()+ for row in rows:+ if row.get("is_user_defined"):+ user_models.update(m.lower() for m in (row.get("models") or []))+ if not user_models:+ return+ for row in rows:+ if row.get("is_user_defined") or not is_routing_aggregator(row.get("slug", "")):+ continue+ original = row.get("models") or []+ filtered = [m for m in original if m.lower() not in user_models]+ if len(filtered) < len(original):+ row["models"] = filtered+ row["total_models"] = len(filtered)++def build_model_options_payload(ctx: ConfigContext,*,@@ -327,13 +248,12 @@ def build_model_options_payload() -> dict:"""Build the shared API-server/dashboard/TUI model-options payload.- This wraps ``build_models_payload`` with the stable picker shape and the- safe custom-provider probe policy used for normal GUI/TUI opens:+ This wraps ``build_models_payload`` with the stable picker shape and the safe custom-provider+ probe policy used for normal GUI/TUI opens:- - normal open: probe only the current custom provider so offline saved- endpoints do not block the picker- - explicit refresh: probe every custom provider while busting the model- cache so live catalogs repopulate fully+ - normal open: probe only the current custom provider so offline saved endpoints do not block+ the picker - explicit refresh: probe every custom provider while busting the model cache so live+ catalogs repopulate fully"""refresh = bool(refresh)return build_models_payload(@@ -363,32 +283,15 @@ def build_aux_picker_rows() -> list[dict]:"""Provider rows for any auxiliary-task picker (vision, compression, …).- THE entry point for every aux picker — present and future. Call this- instead of ``list_authenticated_providers()`` directly.-- Aux pickers kept re-deriving their own kwargs and each one silently- dropped a different slice of the user's configuration. Two independent- contributor PRs landed against the same two call sites for exactly this:- #52642 (user ``providers:`` / ``custom_providers:`` entries never- appeared) and #66624 (providers with an exhausted credential pool were- hidden). Both were per-site kwarg patches, so the next aux picker would- have reintroduced the same gap. Routing through one function makes the- correct behaviour the default that a new caller cannot forget:-- - user-defined ``providers:`` and saved ``custom_providers:`` entries- - ``model_catalog.excluded_providers`` honoured, matching ``/model``- - exhausted-credential-pool providers stay visible (``for_picker``)- - the active custom endpoint is probed, offline saved ones are not, so- the picker never blocks on a dead local server-- The virtual ``moa`` row is excluded: auxiliary tasks must not run the- MoA reference fan-out, and ``auxiliary_client`` unwraps a ``moa``- provider to its aggregator slot anyway (see ``_resolve_auto``), so- offering it here would be a choice silently rewritten behind the user's- back. Mirrors the same filter in ``hermes_cli/moa_cmd.py``.-- Rows are the standard ``list_authenticated_providers`` shape. Pair with- :func:`format_aux_picker_entries` to render them.+ - user-defined ``providers:`` and saved ``custom_providers:`` entries -+ ``model_catalog.excluded_providers`` honoured, matching ``/model`` - exhausted-credential-pool+ providers stay visible (``for_picker``) - the active custom endpoint is probed, offline saved+ ones are not, so the picker never blocks on a dead local server++ The virtual ``moa`` row is excluded: auxiliary tasks must not run the MoA reference fan-out, and+ ``auxiliary_client`` unwraps a ``moa`` provider to its aggregator slot anyway (see+ ``_resolve_auto``), so offering it here would be a choice silently rewritten behind the user's+ back."""ctx = load_picker_context().with_overrides(current_provider=current_provider,@@ -402,7 +305,7 @@ def build_aux_picker_rows(probe_current_custom_provider=True,max_models=max_models,)["providers"]- return [r for r in rows if str(r.get("slug") or "").strip().lower() != "moa"]+ return _without_slug(rows, "moa")def format_aux_picker_entries(@@ -413,14 +316,9 @@ def format_aux_picker_entries() -> list[tuple[str, str, list[str]]]:"""Render aux-picker rows as ``(slug, label, models)`` menu entries.- Owns the label text and the ``← current`` marker so every aux picker- presents providers identically. Callers add their own leading/trailing- entries (``auto``, ``Custom endpoint``, ``Back``) around this list.-- A custom endpoint set via a raw ``base_url`` is "current" only through- that URL — never through a provider slug — so when ``current_base_url``- is set no provider row is marked, matching the pre-existing behaviour of- both call sites.+ A custom endpoint set via a raw ``base_url`` is "current" only through that URL — never through+ a provider slug — so when ``current_base_url`` is set no provider row is marked, matching the+ pre-existing behaviour of both call sites."""entries: list[tuple[str, str, list[str]]] = []current_slug = str(current_provider or "").strip().lower()@@ -442,9 +340,9 @@ def format_aux_picker_entries(def _reasoning_catalog_reader(slug: str):"""Per-model reasoning-capability reader for aggregators that publish one.- Cache-only — building the picker payload must never block on HTTP. A cold- cache warms in the background so the next open is accurate; until then the- model reports no restriction and the UI offers the full scale.+ Cache-only — building the picker payload must never block on HTTP. A cold cache warms in the+ background so the next open is accurate; until then the model reports no restriction and the UI+ offers the full scale."""try:from hermes_cli.models import (@@ -456,37 +354,24 @@ def _reasoning_catalog_reader(slug: str):except Exception:return None- if slug == "nous":- warm_nous_reasoning_caps_async()- return nous_model_reasoning_capabilities- if slug == "openrouter":- warm_openrouter_reasoning_caps_async()- return openrouter_model_reasoning_capabilities- return None+ readers = {+ "nous": (warm_nous_reasoning_caps_async, nous_model_reasoning_capabilities),+ "openrouter": (warm_openrouter_reasoning_caps_async, openrouter_model_reasoning_capabilities),+ }+ if slug not in readers:+ return None+ warm, read = readers[slug]+ warm()+ return readdef _apply_capabilities(rows: list[dict]) -> None:"""Attach a ``{model: {fast, reasoning, ...}}`` map to each provider row.- `fast` mirrors ``model_supports_fast_mode`` (the same gate the runtime- enforces). `reasoning` comes from the models.dev catalog when known and- defaults to True otherwise — the effort dial is broadly accepted and a- no-op on models that ignore it, whereas hiding it from a capable-but-- uncatalogued model is the worse failure.-- Aggregators that publish per-model reasoning detail add- `can_disable_reasoning`, False on reasoning-mandatory routes whose upstream- answers a disable with HTTP 400. Omitted when the catalog doesn't say,- which the UI reads as "no restriction known". Such a catalog also overrides- `reasoning` itself when it reports a route that takes no reasoning- parameter — a definitive negative from the provider actually serving the- model outranks the models.dev inference.-- The catalog's `supported_efforts` list is deliberately NOT forwarded: it- under-reports. The Portal accepts and honors levels a route doesn't- advertise (``z-ai/glm-5.3`` publishes ``max, high, low`` yet serves- ``minimal`` at its lowest thinking), so filtering the picker by that list- would hide levels that demonstrably work.+ ``fast`` mirrors the runtime gate. ``reasoning`` defaults True when the catalog is silent:+ the dial is a no-op on models that ignore it, and hiding it from a capable model is worse.+ A serving aggregator's per-model detail overrides models.dev (adds ``can_disable_reasoning``).+ ``supported_efforts`` is deliberately NOT forwarded -- it under-reports levels that work."""from hermes_cli.models import model_supports_fast_mode@@ -543,20 +428,10 @@ _FEATURED_PER_LAB = 5def _apply_featured(rows: list[dict]) -> None:"""Attach a ``featured_models`` shortlist to each aggregator provider row.- Aggregator providers (nous, openrouter) serve dozens of models across many- labs, so a flat "top-N" default would drop whole labs from the picker.- Instead we surface the ``_FEATURED_PER_LAB`` newest models per lab (the- vendor segment of a ``vendor/model`` id), ranked by models.dev- ``release_date`` among that row's OWN models — never against the current- date, so the choice is stable as models age. Same-date ties (and labs whose- models lack a date) fall back to the row's curated order, which is already- flagship-first, so a lab keeps its headliners rather than an arbitrary slice.-- Derived live from the models.dev catalog already loaded on this path (same- source as pricing/capabilities) — there is no hand-maintained allowlist to- keep in sync. Non-aggregator providers (a single lab, local endpoints,- custom proxies) get an empty list and callers fall back to their existing- top-N behaviour; splitting one lab into a shortlist would just hide models.+ Aggregators serve many labs, so a flat top-N would drop whole labs; instead surface the+ newest ``_FEATURED_PER_LAB`` per vendor, ranked by models.dev ``release_date`` within the+ row's own models (never vs. today, so the choice is stable). Ties fall back to the curated+ flagship-first order. Non-aggregators get an empty list and keep top-N behaviour."""try:from agent.models_dev import get_model_info@@ -602,13 +477,10 @@ def _apply_featured(rows: list[dict]) -> None:def _apply_custom_aliases(rows: list[dict]) -> None:"""Attach the accepted identity set to each user-defined provider row.- A session's ``model.options`` reports the canonical ``custom:<key>``- identity (via ``canonical_custom_identity``), while catalog rows carry- the bare config key as ``slug``. GUI pickers compare the two to decide- which row is active; exact equality never matches for custom providers- (#87035). Exposing ``aliases`` — every current and legacy spelling from- :func:`hermes_cli.providers.custom_provider_aliases` — lets the frontend- do a membership check instead.+ A session's ``model.options`` reports the canonical ``custom:<key>`` identity (via+ ``canonical_custom_identity``), while catalog rows carry the bare config key as ``slug``. GUI+ pickers compare the two to decide which row is active; exact equality never matches for custom+ providers (#87035)."""from hermes_cli.providers import custom_provider_aliases@@ -628,6 +500,28 @@ def _apply_custom_aliases(rows: list[dict]) -> None:# ─── Internal: row post-processing ──────────────────────────────────────+def _provider_auth_hint(slug: str) -> tuple[str, str]:+ """``(auth_type, key_env)`` for a canonical provider (``("api_key", "")`` when unregistered)."""+ from hermes_cli.auth import PROVIDER_REGISTRY++ cfg = PROVIDER_REGISTRY.get(slug)+ auth_type = cfg.auth_type if cfg else "api_key"+ key_env = cfg.api_key_env_vars[0] if (cfg and cfg.api_key_env_vars) else ""+ return auth_type, key_env+++def _canonical_row(entry, cur: str, **extra: Any) -> dict:+ from hermes_cli.models import _PROVIDER_LABELS++ return {+ "slug": entry.slug,+ "name": _PROVIDER_LABELS.get(entry.slug, entry.label),+ "is_current": entry.slug.lower() == cur,+ "is_user_defined": False,+ **extra,+ }++def _append_unconfigured_rows(rows: list[dict],ctx: ConfigContext,@@ -636,13 +530,12 @@ def _append_unconfigured_rows() -> list[dict]:"""Build fallback rows for canonical providers missing from ``rows``.- Most missing canonical providers become empty setup skeletons. The one- exception is the *current* configured provider: if config.yaml still points- at it but credentials are presently unavailable, keep a visible row carrying- the saved model so GUI pickers don't silently snap to some other provider.+ Most missing canonical providers become empty setup skeletons. The one exception is the+ *current* configured provider: if config.yaml still points at it but credentials are presently+ unavailable, keep a visible row carrying the saved model so GUI pickers don't silently snap to+ some other provider."""- from hermes_cli.auth import PROVIDER_REGISTRY- from hermes_cli.models import CANONICAL_PROVIDERS, _PROVIDER_LABELS+ from hermes_cli.models import CANONICAL_PROVIDERSseen = {r["slug"].lower() for r in rows}cur = (ctx.current_provider or "").lower()@@ -654,13 +547,7 @@ def _append_unconfigured_rows(if current_only and entry.slug.lower() != cur:continueif entry.slug.lower() == cur:- cfg = PROVIDER_REGISTRY.get(entry.slug)- auth_type = cfg.auth_type if cfg else "api_key"- key_env = (- cfg.api_key_env_vars[0]- if (cfg and cfg.api_key_env_vars)- else ""- )+ auth_type, key_env = _provider_auth_hint(entry.slug)warning = (f"Configured provider missing usable credentials; paste {key_env} to reactivate. ""Showing the saved model only."@@ -668,47 +555,27 @@ def _append_unconfigured_rows(else "Configured provider is not authenticated; run `hermes model` to reactivate. ""Showing the saved model only.")- extras.append(- {- "slug": entry.slug,- "name": _PROVIDER_LABELS.get(entry.slug, entry.label),- "is_current": True,- "is_user_defined": False,- "models": [cur_model] if cur_model else [],- "total_models": 1 if cur_model else 0,- "source": "configured-current",- "authenticated": False,- "auth_type": auth_type,- "key_env": key_env,- "warning": warning,- }- )+ extras.append(_canonical_row(+ entry, cur,+ models=[cur_model] if cur_model else [],+ total_models=1 if cur_model else 0,+ source="configured-current",+ authenticated=False,+ auth_type=auth_type,+ key_env=key_env,+ warning=warning,+ ))continue- extras.append(- {- "slug": entry.slug,- "name": _PROVIDER_LABELS.get(entry.slug, entry.label),- "is_current": entry.slug.lower() == cur,- "is_user_defined": False,- "models": [],- "total_models": 0,- "source": "canonical",- }- )+ extras.append(_canonical_row(entry, cur, models=[], total_models=0, source="canonical"))return extrasdef _anthropic_oauth_credentials_present() -> bool:"""True when the user explicitly authenticated Anthropic via OAuth.- Two deliberate flows leave no trace in active_provider /- model.provider / API-key env vars: Hermes' own Anthropic device flow- (token in auth.json) and a Claude Code login (~/.claude/.credentials.json).- ``list_authenticated_providers`` already accepts both readers as real- credentials when discovering rows; this mirrors that acceptance so the- desktop explicit-only filter does not silently drop a provider the user- deliberately signed into. Unlike ambient CLI tokens (gh -> copilot),- an OAuth access token only exists after an interactive login.+ Two deliberate flows leave no trace in active_provider / model.provider / API-key env vars:+ Hermes' own Anthropic device flow (token in auth.json) and a Claude Code login+ (~/.claude/.credentials.json)."""try:from agent.anthropic_adapter import (@@ -716,11 +583,10 @@ def _anthropic_oauth_credentials_present() -> bool:read_hermes_oauth_credentials,)- hermes_creds = read_hermes_oauth_credentials() or {}- if hermes_creds.get("accessToken"):- return True- cc_creds = read_claude_code_credentials() or {}- if cc_creds.get("accessToken"):+ if any(+ (read() or {}).get("accessToken")+ for read in (read_hermes_oauth_credentials, read_claude_code_credentials)+ ):return Trueexcept Exception:return False@@ -748,66 +614,57 @@ def _anthropic_oauth_credentials_present() -> bool:def _filter_explicit_provider_rows(rows: list[dict], ctx: ConfigContext) -> list[dict]:"""Keep only rows backed by explicit user configuration.- ``list_authenticated_providers`` intentionally discovers ambient / auto-- seeded credentials (for example GitHub CLI -> Copilot). Desktop chat model- pickers want the narrower subset the user explicitly configured for Hermes.+ ``list_authenticated_providers`` also discovers ambient credentials (e.g. GitHub CLI ->+ Copilot); Desktop chat pickers want only what the user configured for Hermes."""from hermes_cli.auth import is_provider_explicitly_configuredcurrent_slug = str(ctx.current_provider or "").strip().lower()- kept: list[dict] = []- for row in rows:- slug = str(row.get("slug", "")).strip().lower()- if not slug:- continue- if row.get("is_user_defined"):- kept.append(row)- continue- if current_slug and slug == current_slug:- kept.append(row)- continue- if row.get("source") == "local-runtime":++ def _is_explicit(row: dict, slug: str) -> bool:+ if (+ row.get("is_user_defined")+ or (current_slug and slug == current_slug)# Managed local models are explicit configuration by existence:# the user downloaded gigabytes into the machine-scoped models# dir. There is deliberately no config credential to find# (credential is reachability), so without this clause the row# only survives on the profile where Use was last clicked —# every other profile loses local models from its picker.- kept.append(row)- continue+ or row.get("source") == "local-runtime"+ ):+ return Trueif slug == "moa":# MoA is a virtual routing mode, not an independently configured# provider. Hide it from explicit-only pickers unless it is the# current provider (handled above) or the user explicitly wrote an# enabled MoA preset into config.yaml. Use raw config so the# DEFAULT_CONFIG preset does not make every desktop picker show MoA.- if _raw_config_has_enabled_moa_preset():- kept.append(row)- continue- if _provider_is_keyless(slug):+ return _raw_config_has_enabled_moa_preset()+ return (# Keyless providers (opencode-free) require no configuration at# all — there is nothing to "explicitly configure", and hiding# them would defeat their purpose (zero-setup discoverability).- kept.append(row)- continue- if slug == "anthropic" and _anthropic_oauth_credentials_present():+ _provider_is_keyless(slug)# Anthropic OAuth logins (Hermes device flow / Claude Code) are# deliberate sign-ins that leave no trace in active_provider,# model.provider, or API-key env vars. The strict gate below# would drop the row even though list_authenticated_providers# just accepted those same credentials when building it.- kept.append(row)- continue- if _external_process_signed_in(slug):- # External-process providers (copilot-acp) authenticate through- # their own CLI (`copilot login`), which — like the Anthropic- # OAuth case above — leaves no trace in active_provider,- # model.provider, or env vars. Verified CLI credentials are a- # deliberate sign-in; without this the desktop picker drops the- # row the picker-discovery side just accepted.- kept.append(row)- continue- if is_provider_explicitly_configured(slug):+ or (slug == "anthropic" and _anthropic_oauth_credentials_present())+ # External-process providers (copilot-acp) authenticate through their+ # own CLI (`copilot login`) — same class as Anthropic OAuth above:+ # verified CLI credentials are a deliberate sign-in with no trace in+ # active_provider/model.provider/env, so keep the row the+ # picker-discovery side just accepted.+ or _external_process_signed_in(slug)+ or is_provider_explicitly_configured(slug)+ )++ kept: list[dict] = []+ for row in rows:+ slug = str(row.get("slug", "")).strip().lower()+ if slug and _is_explicit(row, slug):kept.append(row)return kept@@ -840,10 +697,10 @@ def _provider_is_keyless(slug: str) -> bool:def _raw_config_has_enabled_moa_preset() -> bool:"""Return True when the user's raw config explicitly enables MoA.- ``load_config()`` includes ``DEFAULT_CONFIG["moa"].presets.default`` for- everyone. Explicit-only model pickers must not treat that default as a user- choice, but they should keep MoA visible once the user has saved at least- one enabled preset (or an older flat MoA config) in their own config.yaml.+ ``load_config()`` includes ``DEFAULT_CONFIG["moa"].presets.default`` for everyone. Explicit-only+ model pickers must not treat that default as a user choice, but they should keep MoA visible+ once the user has saved at least one enabled preset (or an older flat MoA config) in their own+ config.yaml."""try:from hermes_cli.config import read_raw_config@@ -860,14 +717,11 @@ def _raw_config_has_enabled_moa_preset() -> bool:presets = moa.get("presets")if isinstance(presets, dict):- for name, preset in presets.items():- if not str(name or "").strip():- continue- if not isinstance(preset, dict):- return True- if preset.get("enabled", True):- return True- return False+ return any(+ not isinstance(preset, dict) or preset.get("enabled", True)+ for name, preset in presets.items()+ if str(name or "").strip()+ )legacy_keys = {"reference_models",@@ -882,15 +736,7 @@ def _raw_config_has_enabled_moa_preset() -> bool:def _apply_picker_hints(rows: list[dict]) -> None:- """Add ``authenticated``/``auth_type``/``key_env``/``warning`` per row.-- Mutates ``rows`` in-place. Rows already from- ``list_authenticated_providers`` are marked ``authenticated=True``;- the unconfigured skeleton rows from ``_append_unconfigured_rows`` get- the picker's setup-hint shape.- """- from hermes_cli.auth import PROVIDER_REGISTRY-+ """Add ``authenticated``/``auth_type``/``key_env``/``warning`` per row."""for row in rows:if "authenticated" in row:continue@@ -903,13 +749,7 @@ def _apply_picker_hints(rows: list[dict]) -> None:row["authenticated"] = not is_skeletonif not is_skeleton or row.get("is_user_defined"):continue- cfg = PROVIDER_REGISTRY.get(row["slug"])- auth_type = cfg.auth_type if cfg else "api_key"- key_env = (- cfg.api_key_env_vars[0]- if (cfg and cfg.api_key_env_vars)- else ""- )+ auth_type, key_env = _provider_auth_hint(row["slug"])row["auth_type"] = auth_typerow["key_env"] = key_envrow["warning"] = (@@ -920,14 +760,11 @@ def _apply_picker_hints(rows: list[dict]) -> None:def _reorder_canonical(rows: list[dict]) -> list[dict]:- """Canonical slugs in ``CANONICAL_PROVIDERS`` declaration order;- truly-custom rows last.-- Keys on slug membership, NOT ``is_user_defined`` — section 3 of- ``list_authenticated_providers`` sets ``is_user_defined=True`` on- rows from the ``providers:`` config dict even when the slug is- canonical. Keying on the flag would silently demote canonical- providers configured via the new keyed schema.+ """Canonical slugs in ``CANONICAL_PROVIDERS`` declaration order; truly-custom rows last.++ Keys on slug membership, NOT ``is_user_defined``: rows from the ``providers:`` config dict+ carry that flag even for canonical slugs, so keying on it would demote canonical providers+ configured via the keyed schema."""from hermes_cli.models import CANONICAL_PROVIDERS@@ -947,20 +784,11 @@ def _apply_pricing() -> None:"""Enrich each provider row with per-model pricing + Nous tier gating.- Mutates ``rows`` in-place. For every row whose provider supports live- pricing (openrouter / nous / novita) adds::+ row["pricing"] = {model_id: {"input": "$3.00", "output": "$15.00", "cache": "$0.30" | None,+ "free": bool}}- row["pricing"] = {model_id: {"input": "$3.00", "output": "$15.00",- "cache": "$0.30" | None, "free": bool}}-- For Nous additionally adds::-- row["free_tier"] = bool # current account is free-tier- row["unavailable_models"] = [...] # paid models a free user can't pick-- Prices are pre-formatted via ``_format_price_per_mtok`` so the GUI just- renders strings — identical formatting to the CLI picker. All failures- are swallowed (best-effort): a row simply gets no ``pricing`` key.+ row["free_tier"] = bool # current account is free-tier row["unavailable_models"] = [...] # paid+ models a free user can't pick"""from hermes_cli.models import (_format_price_per_mtok,@@ -995,14 +823,12 @@ def _apply_pricing(cache_raw = p.get("input_cache_read", "")inp = _format_price_per_mtok(inp_raw) if inp_raw != "" else ""out = _format_price_per_mtok(out_raw) if out_raw != "" else ""- cache = _format_price_per_mtok(cache_raw) if cache_raw else None- # A model is "free" when both input and output cost nothing.- is_free = inp == "free" and (out == "free" or out == "")entry: dict = {"input": inp,"output": out,- "cache": cache,- "free": is_free,+ "cache": _format_price_per_mtok(cache_raw) if cache_raw else None,+ # A model is "free" when both input and output cost nothing.+ "free": inp == "free" and out in ("free", ""),}# Sale chrome is Nous Portal-only. Other providers (OpenRouter,# Novita, …) never get discount_percent / was_* even if a nested@@ -1016,14 +842,9 @@ def _apply_pricing(if sale is not None:discount_percent, was_prompt_raw, was_out_raw = saleentry["discount_percent"] = discount_percent- if was_prompt_raw != "":- entry["was_input"] = _format_price_per_mtok(- was_prompt_raw- )- if was_out_raw != "":- entry["was_output"] = _format_price_per_mtok(- was_out_raw- )+ for key, was_raw in (("was_input", was_prompt_raw), ("was_output", was_out_raw)):+ if was_raw != "":+ entry[key] = _format_price_per_mtok(was_raw)formatted[mid] = entryif formatted:@@ -1036,13 +857,11 @@ def _apply_pricing(force_fresh=force_fresh_nous_tier)row["free_tier"] = bool(nous_free_tier)- if nous_free_tier:- _selectable, unavailable = partition_nous_models_by_tier(- list(models), raw_pricing, free_tier=True- )- row["unavailable_models"] = unavailable- else:- row["unavailable_models"] = []+ row["unavailable_models"] = (+ partition_nous_models_by_tier(list(models), raw_pricing, free_tier=True)[1]+ if nous_free_tier+ else []+ )except Exception:# Tier detection failed — fail open (no gating) so the user# is never blocked from picking a model.@@ -1053,10 +872,9 @@ def _apply_pricing(def _local_runtime_row(ctx: "ConfigContext") -> dict | None:"""Build the ``llamacpp`` provider row from staged local models.- Present whenever GGUFs are staged in the managed models directory —- downloaded models must be selectable even before the server is running- (selection starts it via the runtime_provider seam / activate flow).- Returns ``None`` when nothing is staged.+ Present whenever GGUFs are staged in the managed models directory — downloaded models must be+ selectable even before the server is running (selection starts it via the runtime_provider seam+ / activate flow). Returns ``None`` when nothing is staged."""try:from hermes_cli.local_runtime.bootstrap import staged_model_ids@@ -1103,9 +921,8 @@ def _local_runtime_row(ctx: "ConfigContext") -> dict | None:def _moa_provider_row(current_provider: str = "") -> dict | None:"""Build the virtual ``moa`` provider row for model pickers.- Shared by the CLI inventory (:func:`build_models_payload`) and the gateway- picker path (:func:`hermes_cli.model_switch.list_picker_providers`) so the- row shape stays in one place. Returns ``None`` when no MoA presets exist.+ Shared by the CLI inventory and the gateway picker path so the row shape lives in one place.+ Returns ``None`` when no MoA presets exist."""try:from hermes_cli.config import load_configdiff --git a/hermes_cli/local_runtime/__init__.py b/hermes_cli/local_runtime/__init__.pyindex 9793970b5f1..31862638401 100644--- a/hermes_cli/local_runtime/__init__.py+++ b/hermes_cli/local_runtime/__init__.py@@ -1,21 +1,9 @@"""Managed llama.cpp runtime.-Hermes downloads, verifies, supervises, and updates one llama-server, and-decides per machine which model build and context window to run. Key-modules:--- ``binaries`` — resolve/download/verify official llama.cpp release zips- into ``$HERMES_HOME/runtimes/llamacpp/<tag>/``.-- ``supervisor``— spawn and supervise one llama-server in router mode;- readiness is a touch generation, never health-200 alone.-- ``detect`` — find an already-running llama-server (external or ours).-- ``estimator`` / ``context_policy`` / ``growth`` — price context memory- per architecture and run the window ladder (zero-spill start, grow- toward native max, compress only at the top).-- ``catalog`` / ``presets`` — the curated model list and the per-model- launch flags that carry policy decisions to the router.--Everything is driven by the ``local_runtime`` section of config.yaml.+- ``binaries`` — resolve/download/verify official llama.cpp release zips into+``$HERMES_HOME/runtimes/llamacpp/<tag>/``. - ``supervisor``— spawn and supervise one llama-server in+router mode; readiness is a touch generation, never health-200 alone. - ``detect`` — find an+already-running llama-server (external or ours)."""from hermes_cli.local_runtime.binaries import ( # noqa: F401diff --git a/hermes_cli/local_runtime/binaries.py b/hermes_cli/local_runtime/binaries.pyindex bcd7d32a1d7..ea67131e2e6 100644--- a/hermes_cli/local_runtime/binaries.py+++ b/hermes_cli/local_runtime/binaries.py@@ -1,15 +1,4 @@-"""Binary acquisition for the managed llama.cpp runtime.--llama.cpp publishes per-tag assets (rolling ``bNNNN`` tags, no semver).-Backends are dlopen'd plugins, so a runtime = CPU/base zip + backend zip-extracted into one directory, plus the cudart runtime zip on Windows CUDA-(end users have no CUDA toolkit). We pin the tag in config, sha256-verify-every download, and keep the previous tag for rollback (N-1).--Layout: ``$HERMES_HOME/runtimes/llamacpp/<tag>/<backend>/<binaries>``-with a ``manifest.json`` recording zips, sha256s, and the verified-llama-server version string.-"""+"""Binary acquisition for the managed llama.cpp runtime."""from __future__ import annotations@@ -25,7 +14,6 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Callable-from hermes_constants import get_hermes_homelogger = logging.getLogger(__name__)@@ -68,12 +56,11 @@ class AssetPlan:def runtimes_root() -> Path:- """Machine-scoped, deliberately NOT profile-scoped. Engine binaries,- presets, and server state describe this machine's hardware and its one- managed server (stable port) — a second profile re-downloading the- engine or fighting over the port would be the bug. Profile-scoped- things (which model is the default, enabled) live in each profile's- config.yaml as ever."""+ """Machine-scoped, deliberately NOT profile-scoped. Engine binaries, presets, and server state+ describe this machine's hardware and its one managed server (stable port) — a second profile+ re-downloading the engine or fighting over the port would be the bug. Profile-scoped things+ (which model is the default, enabled) live in each profile's config.yaml as ever.+ """from hermes_constants import get_default_hermes_rootreturn get_default_hermes_root() / "runtimes" / "llamacpp"@@ -108,9 +95,9 @@ def installed_tags() -> list[str]:def _host_os_arch() -> tuple[str, str]:"""(os, arch) normalized to release-asset vocabulary.- PITFALL: PROCESSOR_ARCHITECTURE lies under x64 emulation on- ARM64 Windows. platform.machine() reads the same env on some Pythons, so- on Windows prefer PROCESSOR_IDENTIFIER's text when present.+ PITFALL: PROCESSOR_ARCHITECTURE lies under x64 emulation on ARM64 Windows. platform.machine()+ reads the same env on some Pythons, so on Windows prefer PROCESSOR_IDENTIFIER's text when+ present."""system = platform.system().lower()os_name = {"windows": "win", "darwin": "macos", "linux": "ubuntu"}.get(system, system)@@ -118,8 +105,8 @@ def _host_os_arch() -> tuple[str, str]:arch = "arm64" if machine in ("arm64", "aarch64") else "x64"if os_name == "win":import os as _os- ident = _os.environ.get("PROCESSOR_IDENTIFIER", "")- if "armv8" in ident.lower() or "arm " in ident.lower():+ ident = _os.environ.get("PROCESSOR_IDENTIFIER", "").lower()+ if "armv8" in ident or "arm " in ident:arch = "arm64"return os_name, arch@@ -140,57 +127,52 @@ def select_backend(gpu_vendor: str | None, os_name: str | None = None) -> str:return "cpu"+# Per-OS (human label, {backend: asset-name templates}). Windows CUDA pairs the+# runtime zip with its cudart zip; ubuntu ships tarballs, win ships zips.+_ASSET_TEMPLATES = {+ "ubuntu": ("linux", {+ "vulkan": ["llama-{tag}-bin-ubuntu-vulkan-{arch}.tar.gz"],+ "hip": ["llama-{tag}-bin-ubuntu-rocm-7.2-{arch}.tar.gz"],+ "cpu": ["llama-{tag}-bin-ubuntu-{arch}.tar.gz"],+ }),+ "win": ("windows", {+ "cuda": ["llama-{tag}-bin-win-cuda-{cuda_ver}-{arch}.zip",+ "cudart-llama-bin-win-cuda-{cuda_ver}-{arch}.zip"],+ "vulkan": ["llama-{tag}-bin-win-vulkan-x64.zip"],+ "hip": ["llama-{tag}-bin-win-hip-radeon-x64.zip"],+ "cpu": ["llama-{tag}-bin-win-cpu-{arch}.zip"],+ }),+}++def resolve_assets(tag: str, backend: str, os_name: str | None = None,arch: str | None = None) -> AssetPlan:"""Compose the asset list for (tag, backend, platform).- Raises BinaryResolutionError for combinations the release does not ship- (a platform/backend pair upstream publishes no artifact for). Callers- fall back down the backend ladder: cuda -> vulkan -> cpu.+ Raises BinaryResolutionError for platform/backend pairs the release ships no artifact for;+ callers fall back down the backend ladder cuda -> vulkan -> cpu."""host_os, host_arch = _host_os_arch()os_name = os_name or host_osarch = arch or host_arch- plan = AssetPlan(tag=tag, backend=backend)-if os_name == "macos":# macOS tarballs are unified (Metal built in).- plan.assets = [f"llama-{tag}-bin-macos-{arch}.tar.gz"]- return plan-- if os_name == "ubuntu":- if backend == "cuda":- # No prebuilt Linux CUDA zips at current tags — Linux CUDA users- # build from source or use vulkan; resolver is honest about it.- raise BinaryResolutionError(- f"no prebuilt linux CUDA asset at {tag}; use vulkan/cpu or a source build")- suffix = {"vulkan": f"vulkan-{arch}", "hip": f"rocm-7.2-{arch}",- "cpu": arch}.get(backend)- if suffix is None:- raise BinaryResolutionError(f"unsupported linux backend {backend}")- plan.assets = [f"llama-{tag}-bin-ubuntu-{suffix}.tar.gz"]- return plan-- if os_name == "win":- if backend == "cuda":- cuda_ver = _WIN_CUDA_VERSION_ARM64 if arch == "arm64" else _WIN_CUDA_VERSION- plan.assets = [- f"llama-{tag}-bin-win-cuda-{cuda_ver}-{arch}.zip",- f"cudart-llama-bin-win-cuda-{cuda_ver}-{arch}.zip",- ]- elif backend == "vulkan":- if arch == "arm64":- raise BinaryResolutionError(f"no win-vulkan-arm64 asset at {tag}")- plan.assets = [f"llama-{tag}-bin-win-vulkan-x64.zip"]- elif backend == "hip":- plan.assets = [f"llama-{tag}-bin-win-hip-radeon-x64.zip"]- elif backend == "cpu":- plan.assets = [f"llama-{tag}-bin-win-cpu-{arch}.zip"]- else:- raise BinaryResolutionError(f"unsupported windows backend {backend}")- return plan-- raise BinaryResolutionError(f"unsupported platform {os_name}-{arch}")+ return AssetPlan(tag, backend, [f"llama-{tag}-bin-macos-{arch}.tar.gz"])+ if os_name not in _ASSET_TEMPLATES:+ raise BinaryResolutionError(f"unsupported platform {os_name}-{arch}")+ if os_name == "ubuntu" and backend == "cuda":+ # No prebuilt Linux CUDA zips at current tags — Linux CUDA users+ # build from source or use vulkan; resolver is honest about it.+ raise BinaryResolutionError(+ f"no prebuilt linux CUDA asset at {tag}; use vulkan/cpu or a source build")+ if os_name == "win" and backend == "vulkan" and arch == "arm64":+ raise BinaryResolutionError(f"no win-vulkan-arm64 asset at {tag}")+ label, templates = _ASSET_TEMPLATES[os_name]+ if backend not in templates:+ raise BinaryResolutionError(f"unsupported {label} backend {backend}")+ cuda_ver = _WIN_CUDA_VERSION_ARM64 if arch == "arm64" else _WIN_CUDA_VERSION+ return AssetPlan(tag, backend, [t.format(tag=tag, arch=arch, cuda_ver=cuda_ver)+ for t in templates[backend]])def _sha256(path: Path) -> str:@@ -227,26 +209,21 @@ def _extract(archive: Path, dest: Path,"""Extract member by member so ``progress(done, total)`` can tick inuncompressed bytes — big archives take real time on laptop disks."""if archive.name.endswith(".zip"):- with zipfile.ZipFile(archive) as z:- members = z.infolist()- total = sum(m.file_size for m in members)- done = 0- for m in members:- z.extract(m, dest)- done += m.file_size- if progress is not None:- progress(done, total)+ opener, list_members, size = zipfile.ZipFile, "infolist", "file_size"+ kwargs = {}else:import tarfile- with tarfile.open(archive) as t:- members = t.getmembers()- total = sum(m.size for m in members)- done = 0- for m in members:- t.extract(m, dest, filter="data")- done += m.size- if progress is not None:- progress(done, total)+ opener, list_members, size = tarfile.open, "getmembers", "size"+ kwargs = {"filter": "data"}+ with opener(archive) as ar:+ members = getattr(ar, list_members)()+ total = sum(getattr(m, size) for m in members)+ done = 0+ for m in members:+ ar.extract(m, dest, **kwargs)+ done += getattr(m, size)+ if progress is not None:+ progress(done, total)def server_binary(install_dir: Path) -> Path:@@ -295,13 +272,10 @@ def ensure_runtime_installed(tag: str, backend: str,progress: "Callable[[str, int, int, str], None] | None" = None) -> Path:"""Idempotent: resolve, download, verify, extract, version-check.- ``expected_sha256`` maps asset name -> hash when the catalog pins them;- without pins the computed hash is recorded in the manifest (trust on- first download, verified on every reinstall).- ``progress(stage, done_bytes, total_bytes, label)`` ticks through the- slow parts — stage is "download" | "extract" | "verify", label is the- asset counter ("1/2") when the plan has several archives.- Returns the install directory containing llama-server.+ ``expected_sha256`` pins hashes per asset when the catalog has them; without pins the computed+ hash is recorded in the manifest (trust on first download, verified on every reinstall).+ ``progress(stage, done, total, label)`` ticks through download/extract/verify. Returns the+ install dir containing llama-server."""plan = resolve_assets(tag, backend)install_dir = plan.install_dirdiff --git a/hermes_cli/local_runtime/bootstrap.py b/hermes_cli/local_runtime/bootstrap.pyindex 79402142ae2..d204b48ee38 100644--- a/hermes_cli/local_runtime/bootstrap.py+++ b/hermes_cli/local_runtime/bootstrap.py@@ -1,25 +1,23 @@-"""Bootstrap for the managed runtime: config -> installed binaries ->-running supervised server.+"""Bootstrap for the managed runtime: config -> installed binaries -> running supervised server.-One public call, ``ensure_local_runtime(config)``, safe to call at any-session start:-- disabled or already-running (state file answers /health) -> no-op-- enabled -> install binaries if missing (idempotent), spawn supervisor+One public call, ``ensure_local_runtime(config)``, safe to call at any session start: - disabled or+already-running (state file answers /health) -> no-op - enabled -> install binaries if missing+(idempotent), spawn supervisor-Kept import-light: callers gate on config before importing this module so-sessions with local_runtime disabled never pay the import.+Kept import-light: callers gate on config before importing this module so sessions with+local_runtime disabled never pay the import."""from __future__ import annotationsimport loggingimport os+import re+import signalimport subprocessimport timefrom pathlib import Path-from hermes_constants import get_hermes_home # noqa: F401 — config paths-from hermes_cli.local_runtime.binaries import runtimes_rootlogger = logging.getLogger(__name__)@@ -28,10 +26,10 @@ _SUPERVISOR = None # process-wide singleton; one router per Hermes processdef _detect_gpu_vendor() -> str | None:- """Best-effort GPU vendor for backend selection. NVIDIA via nvidia-smi- (resolved by the hardware probe's PATH-independent ladder — a stripped- service PATH must not demote an NVIDIA box to vulkan/cpu); anything- else defers to select_backend's fallback ladder."""+ """Best-effort GPU vendor for backend selection. NVIDIA via nvidia-smi (resolved by the hardware+ probe's PATH-independent ladder — a stripped service PATH must not demote an NVIDIA box to+ vulkan/cpu); anything else defers to select_backend's fallback ladder.+ """from hermes_cli.local_runtime.hardware import _nvidia_smi_pathsmi = _nvidia_smi_path()@@ -65,13 +63,10 @@ def assets_dir() -> Path:def staged_models() -> "list[Path]":- """Servable staged models: single-file GGUFs count when present; a- split GGUF counts once, by its first part, and only when EVERY part- is on disk — a mid-download split is not servable and must not- surface anywhere as a model. Continuation parts and assets/ never- count."""- import re-+ """Servable staged models: single-file GGUFs count when present; a split GGUF counts once, by its+ first part, and only when EVERY part is on disk — a mid-download split is not servable and must+ not surface anywhere as a model. Continuation parts and assets/ never count.+ """part = re.compile(r"-(\d{5})-of-(\d{5})\.gguf$")files = sorted(models_dir().glob("*.gguf"))names = {p.name for p in files}@@ -92,8 +87,6 @@ def staged_models() -> "list[Path]":def staged_model_ids() -> "list[str]":- import re-return [re.sub(r"-\d{5}-of-\d{5}$", "", p.stem) for p in staged_models()]@@ -110,21 +103,18 @@ def _presets_stale() -> bool:def _stop_state_server(state: dict) -> None:- """Best-effort stop of the server the state file points at (an- incumbent this process doesn't supervise). The state pid is ours by- contract — the file only ever describes the managed server."""+ """Best-effort stop of the server the state file points at (an incumbent this process doesn't+ supervise). The state pid is ours by contract — the file only ever describes the managed server.+ """from hermes_cli.local_runtime.endpoint import _pid_alive- pid = state.get("pid")try:- pid = int(pid)+ pid = int(state.get("pid"))except (TypeError, ValueError):returnif pid <= 0:returntry:- import signal-os.kill(pid, signal.SIGTERM)except (OSError, ValueError):return@@ -140,16 +130,9 @@ def _stop_state_server(state: dict) -> None:def refresh_local_runtime() -> bool:"""Restart the managed server so it rescans the models directory.- The router's model list is SPAWN-ONLY: a GGUF added after start is- invisible to GET /models and 400s on completion, so anything that- changes the staged set while the server runs must bounce it. Covers- both ownership shapes: a supervised server restarts in-process; an- ADOPTED server (started by a previous backend session — the normal- shape after any restart) is stopped via its state-file pid and- replaced with a supervised boot. Without the adopted branch, every- download/delete in a post-restart session silently no-ops the bounce- and the router serves a stale catalog. Returns False when there is- nothing to refresh (no server anywhere; next boot scans fresh).+ The router's model list is SPAWN-ONLY: a GGUF added after start is invisible to GET /models and+ 400s on completion, so anything that changes the staged set while the server runs must bounce+ it."""global _SUPERVISORtry:@@ -173,13 +156,9 @@ def refresh_local_runtime() -> bool:def ensure_local_runtime(config: dict, force: bool = False) -> "object | None":- """Idempotent boot of the managed runtime. Returns the supervisor (or- None when disabled/unavailable). Never raises into a session start —- failures log and return None; chat falls back to configured providers.-- ``force=True`` skips the enabled gate — used by the explicit "Use this- model" action, where the click IS the opt-in (the caller records it in- config so future boots auto-start).+ """Idempotent boot of the managed runtime. Returns the supervisor (or None when+ disabled/unavailable). Never raises into a session start — failures log and return None; chat+ falls back to configured providers."""global _SUPERVISORsection = (config or {}).get("local_runtime") or {}@@ -216,7 +195,9 @@ def ensure_local_runtime(config: dict, force: bool = False) -> "object | None":try:from hermes_cli.local_runtime.binaries import (+ default_tag,ensure_runtime_installed,+ installed_tags,select_backend,)from hermes_cli.local_runtime.hardware import probe_budget@@ -233,8 +214,6 @@ def ensure_local_runtime(config: dict, force: bool = False) -> "object | None":# endpoint reports the pending update — the download is a deliberate# button click in the pane, not a boot-path surprise (a multi-minute# inline download here is exactly how the onboarding bounce returns).- from hermes_cli.local_runtime.binaries import default_tag, installed_tags-tag = section.get("tag") or default_tag()have = installed_tags()if tag not in have:diff --git a/hermes_cli/local_runtime/capabilities.py b/hermes_cli/local_runtime/capabilities.pyindex b30152fadfd..084d7a190a9 100644--- a/hermes_cli/local_runtime/capabilities.py+++ b/hermes_cli/local_runtime/capabilities.py@@ -1,22 +1,9 @@"""Capability answers for models served by the managed runtime.-Capability lookups (vision, and whatever comes next) consult cloud-shaped-catalogs that have never heard of a local GGUF, so a vision-capable local-model reads as text-only and images detour to an auxiliary cloud model —-the wrong behavior twice over for a local-first user (broken feature, and-a screenshot silently leaving the machine).--The managed runtime can answer from ground truth instead, best source-first:--1. The RUNNING child's /props: llama-server reports a ``modalities`` block- when a vision projector is loaded. The server that will receive the- image says whether it can see — no inference, no catalog.-2. The catalog entry's declared capability (the ``vision`` tag + mmproj- asset) for staged-but-unloaded models: what the model WILL support once- its projector loads beside it.-3. None — not one of ours, or nothing known; the caller falls through to- its other sources.+Capability lookups (vision, and whatever comes next) consult cloud-shaped catalogs that have never+heard of a local GGUF, so a vision-capable local model reads as text-only and images detour to an+auxiliary cloud model — the wrong behavior twice over for a local-first user (broken feature, and a+screenshot silently leaving the machine)."""from __future__ import annotations@@ -27,7 +14,7 @@ import urllib.requestlogger = logging.getLogger(__name__)-_LLAMACPP_ALIASES = frozenset({"llamacpp", "llama.cpp", "llama-cpp"})+from hermes_cli.local_runtime.endpoint import LLAMACPP_ALIASES as _LLAMACPP_ALIASES# Image formats the managed server's decoder actually handles. llama.cpp# decodes with stb_image: PNG/JPEG/GIF/BMP yes, WebP NO — and a WebP part@@ -45,20 +32,20 @@ def is_managed_provider(provider: str, base_url: str = "") -> bool:p = (provider or "").strip().lower()if p in _LLAMACPP_ALIASES:return True- if p == "custom" and base_url:- try:- from hermes_cli.local_runtime.growth import is_managed_endpoint+ if p != "custom" or not base_url:+ return False+ try:+ from hermes_cli.local_runtime.growth import is_managed_endpoint- return is_managed_endpoint(base_url)- except Exception: # noqa: BLE001- return False- return False+ return is_managed_endpoint(base_url)+ except Exception: # noqa: BLE001+ return Falsedef _props_modalities(model_id: str) -> "bool | None":- """Ask the running server whether this loaded child sees images.- None when the server is down, the model isn't loaded, or the build- doesn't report modalities."""+ """Ask the running server whether this loaded child sees images. None when the server is down, the+ model isn't loaded, or the build doesn't report modalities.+ """try:from hermes_cli.local_runtime.endpoint import _state_endpointdiff --git a/hermes_cli/local_runtime/catalog.py b/hermes_cli/local_runtime/catalog.pyindex 715d83c07f7..09beef35f13 100644--- a/hermes_cli/local_runtime/catalog.py+++ b/hermes_cli/local_runtime/catalog.py@@ -1,50 +1,12 @@"""Curated starter catalog for the managed local runtime.-Small and honest: every entry carries the estimator inputs (measured on-real GGUFs) so the picker can price a model BEFORE the user downloads-gigabytes. Once a file is on disk, profile_from_gguf() is the authority-and the catalog numbers are only used for the download decision. Entries-whose base config is gated upstream carry a same-family conservative-prior (commented) — the GGUF header corrects it at load time.--Each model ships ONE build, Q4-class (UD-Q4_K_M where the repo has it,-UD-Q4_K_XL elsewhere). Q4 is the quant class current engines optimize-for and the sweet spot of the size/quality curve, so there is no quant-ladder: headroom buys a bigger context window, never a bigger quant,-and every machine runs the same well-tested build. Below Q4 the quality-loss is too severe to ship as someone's first local-AI experience; the-fit policy prices the build honestly (zero-spill, spilled, or refused by-the physics check).--Validation lifecycle: builds proven end-to-end on real hardware are-marked validated. Day-0 entries ship before that proof (they simply lack-the validated flag) — ensure_model_ready's touch generation still gates-every first load at runtime.--Multi-file models: variants may carry split-GGUF parts (llama-server loads-from the first part; all parts download together). Entries may carry an-mmproj (vision projector) and a speculative-decode draft model — both-download alongside the weights. MTP-integrated models run spec decode-wherever they load; a separate draft model attaches only when the launch-decision spills, where its speedup is largest.--File sizes come from HF LFS metadata and feed the estimator, the fit-pills, and download progress. There is no download-time integrity check-by design: a corrupt or truncated file surfaces as a llama.cpp-load error at first use, and the reachability test catches upstream-re-uploads by size drift before users do.--This is deliberately not a live registry feed: entries are reviewed like a-version bump (the same policy governs vendor recipe ingestion — parsed-data, never executed commands).--Vendor recipes overlay: a per-SKU recipes repo may SUPPLEMENT these-entries where applicable — vendor SKUs only, never the base layer for-other platforms. A recipe may enrich identity (GGUF/quant/sha), perf-hints (-b/-ub, spec-decode), and sampling defaults; it never carries-context/slots/placement/serving flags (the fit policy owns those).-Resolution: exact SKU -> GPU-class bucket -> fit-only. Snapshot-synced,-reviewed like a tag bump.+Small and honest: every entry carries the estimator inputs (measured on real GGUFs) so the picker+can price a model BEFORE the user downloads gigabytes. Once a file is on disk, profile_from_gguf()+is the authority and the catalog numbers are only used for the download decision.++Validation lifecycle: builds proven end-to-end on real hardware are marked validated. Day-0 entries+ship before that proof (they simply lack the validated flag) — ensure_model_ready's touch generation+still gates every first load at runtime."""from __future__ import annotations@@ -73,19 +35,17 @@ from hermes_cli.local_runtime.estimator import (logger = logging.getLogger(__name__)-_GIB = 1 << 30_PART_SUFFIX = re.compile(r"-\d{5}-of-\d{5}$")@dataclass(frozen=True)class AssetFile:- """One downloadable file: repo-relative path and exact bytes (the size- feeds the estimator and the download progress bar; there is no- download-time integrity check by design — a corrupt file surfaces as a- llama.cpp load error). ``local`` overrides the on-disk name (repos- reuse generic names like mmproj-BF16.gguf across models). Non-model- extras live under the models dir's assets/ subdirectory so the router- never lists them."""+ """One downloadable file: repo-relative path and exact bytes (the size feeds the estimator and the+ download progress bar; there is no download-time integrity check by design — a corrupt file+ surfaces as a llama.cpp load error). ``local`` overrides the on-disk name (repos reuse generic+ names like mmproj-BF16.gguf across models). Non-model extras live under the models dir's assets/+ subdirectory so the router never lists them.+ """path: str # repo-relative (may include a subdir)size_bytes: int@@ -116,9 +76,9 @@ class QuantVariant:@propertydef weights_bytes(self) -> int:- """Pre-download weights estimate: GGUF bytes ≈ tensor bytes + a- small header (<2%) — a safe, slightly conservative stand-in until- profile_from_gguf reads the real table."""+ """Pre-download weights estimate: GGUF bytes ≈ tensor bytes + a small header (<2%) — a safe,+ slightly conservative stand-in until profile_from_gguf reads the real table.+ """return self.size_bytes@@ -202,14 +162,12 @@ class VariantChoice:def select_variant(entry: CatalogEntry, budget: HardwareBudget) -> VariantChoice | None:"""Fit the entry's one build (Q4-class) to this machine.- Every entry ships exactly one variant (see the module docstring for- why there is no quant ladder); headroom buys a bigger window, never- a bigger quant. The fit shapes:+ Every entry ships exactly one variant (see the module docstring for why there is no quant+ ladder); headroom buys a bigger window, never a bigger quant. The fit shapes:- - "best-large-window": zero-spills at TARGET_WINDOW- - "best-fits": zero-spills at the 64K floor- - "smallest-fits-spilled": weights spill to host RAM, priced honestly- - None: even spilled, physics refuses (the machine can't run it)+ - "best-large-window": zero-spills at TARGET_WINDOW - "best-fits": zero-spills at the 64K floor+ - "smallest-fits-spilled": weights spill to host RAM, priced honestly - None: even spilled,+ physics refuses (the machine can't run it)"""overhead = (RUNTIME_OVERHEAD_BYTES+ (entry.mmproj.size_bytes if entry.mmproj else 0)@@ -218,17 +176,14 @@ def select_variant(entry: CatalogEntry, budget: HardwareBudget) -> VariantChoicevariant = entry.variants[-1]profile = entry.profile(variant)need = variant.weights_bytes + overhead- if (need + ctx_bytes(profile, min(TARGET_WINDOW, native))- <= budget.usable_vram_bytes):- return VariantChoice(variant=variant, zero_spill=True,- reason_key="best-large-window")+ vram = budget.usable_vram_bytes+ if need + ctx_bytes(profile, min(TARGET_WINDOW, native)) <= vram:+ return VariantChoice(variant, zero_spill=True, reason_key="best-large-window")floor_kv = ctx_bytes(profile, min(FLOOR, native))- if need + floor_kv <= budget.usable_vram_bytes:- return VariantChoice(variant=variant, zero_spill=True,- reason_key="best-fits")- if need + floor_kv <= budget.usable_vram_bytes + budget.ram_available_bytes:- return VariantChoice(variant=variant, zero_spill=False,- reason_key="smallest-fits-spilled")+ if need + floor_kv <= vram:+ return VariantChoice(variant, zero_spill=True, reason_key="best-fits")+ if need + floor_kv <= vram + budget.ram_available_bytes:+ return VariantChoice(variant, zero_spill=False, reason_key="smallest-fits-spilled")return None@@ -277,61 +232,35 @@ def recommended_entry(budget: HardwareBudget,) -> "tuple[CatalogEntry, str] | None":"""The catalog's default pick for THIS machine, with its reason.- Callers pass pre-filtered entries when some are ineligible for- reasons the catalog can't know (engine too old); default is the full- catalog. Returns (entry, reason) — the reason is a key the UI turns- into the Recommended badge's tooltip, so the rationale shown to the- user is the branch that actually fired, never a parallel explanation- that can drift:-- best-quality-resident quality won among resident entries that- clear the pleasant floor- speed-gated-quality same, but the floor eliminated a HIGHER- quality candidate — the exact 'why not the- big model?' a unified-memory owner asks- fastest-resident nothing resident clears the floor; the- quickest resident entry wins- least-painful-spilled nothing runs resident; fastest from host- memory (MoE by construction)-- Returns None only when nothing fits at all.+ Callers pass pre-filtered entries when some are ineligible for reasons the catalog can't know+ (engine too old); default is the full catalog.++ best-quality-resident quality won among resident entries that clear the pleasant floor speed-+ gated-quality same, but the floor eliminated a HIGHER quality candidate — the exact 'why not the+ big model?' a unified-memory owner asks fastest-resident nothing resident clears the floor; the+ quickest resident entry wins least-painful-spilled nothing runs resident; fastest from host+ memory (MoE by construction)"""pool = CATALOG if entries is None else entries- fitting: list[tuple[CatalogEntry, VariantChoice]] = []- for entry in pool:- choice = select_variant(entry, budget)- if choice is not None:- fitting.append((entry, choice))+ fitting = [(e, c) for e in pool if (c := select_variant(e, budget)) is not None]if not fitting:return None+ def speed(t, spilled=False):+ return predicted_decode_tok_s(t[0], t[1].variant, budget, spilled=spilled)+resident = [(e, c) for e, c in fitting if c.zero_spill]- pleasant = [- (e, c) for e, c in resident- if predicted_decode_tok_s(e, c.variant, budget) >= PLEASANT_FLOOR_TOK_S- ]+ pleasant = [t for t in resident if speed(t) >= PLEASANT_FLOOR_TOK_S]if pleasant:pick = max(pleasant, key=lambda t: (t[0].quality, -t[1].variant.size_bytes))[0]floor_gated = any(e.quality > pick.quality for e, _ in resident)- return (pick, "speed-gated-quality" if floor_gated- else "best-quality-resident")+ return (pick, "speed-gated-quality" if floor_gated else "best-quality-resident")if resident:- pick = max(resident,- key=lambda t: predicted_decode_tok_s(t[0], t[1].variant, budget))[0]- return (pick, "fastest-resident")+ return (max(resident, key=speed)[0], "fastest-resident")# Everything spills: take the least painful — fastest predicted decode# from host memory (MoE wins here by construction; a dense spill# streams every weight over the host bus).- pick = max(fitting,- key=lambda t: predicted_decode_tok_s(t[0], t[1].variant, budget,- spilled=True))[0]- return (pick, "least-painful-spilled")---def recommended_id(budget: HardwareBudget,- entries: "tuple[CatalogEntry, ...] | None" = None) -> str | None:- picked = recommended_entry(budget, entries)- return picked[0].id if picked is not None else None+ return (max(fitting, key=lambda t: speed(t, spilled=True))[0], "least-painful-spilled")# ── catalog data: packaged JSON, refreshed from GitHub in memory ─@@ -360,6 +289,18 @@ def _asset_from(d: "dict | None") -> "AssetFile | None":local=d.get("local"))+# Scalar CatalogEntry fields parsed from JSON: key -> (coerce, default);+# a None default means the key is required.+_SCALAR_FIELDS = {+ "n_ctx_train": (int, None), "full_layers": (int, None),+ "recurrent_layers": (int, None), "per_layer_f16": (int, None),+ "swa_layers": (int, 0), "swa_window": (int, 0),+ "moe": (bool, False), "mtp": (bool, False), "mtp_draft_depth": (int, 3),+ "n_vocab": (int, 0), "sampling": (dict, {}), "min_engine": (str, ""),+ "quality": (int, 0), "decode_fraction": (float, 1.0),+}++def _load_catalog(doc: dict) -> "tuple[CatalogEntry, ...]":"""Parse a catalog document into entries. Unknown fields are ignored(newer catalogs stay readable by older apps); a major schema bump is@@ -374,25 +315,13 @@ def _load_catalog(doc: dict) -> "tuple[CatalogEntry, ...]":files=tuple(_asset_from(f) for f in v["files"]),validated=bool(v.get("validated")))for v in m["variants"])+ scalars = {k: coerce(m[k] if default is None else m.get(k, default))+ for k, (coerce, default) in _SCALAR_FIELDS.items()}entries.append(CatalogEntry(id=m["id"], display_name=m["display_name"],description=m["description"], repo=m["repo"], variants=variants,- n_ctx_train=int(m["n_ctx_train"]),- full_layers=int(m["full_layers"]),- recurrent_layers=int(m["recurrent_layers"]),- per_layer_f16=int(m["per_layer_f16"]),- swa_layers=int(m.get("swa_layers", 0)),- swa_window=int(m.get("swa_window", 0)),- moe=bool(m.get("moe")), mtp=bool(m.get("mtp")),- mtp_draft_depth=int(m.get("mtp_draft_depth", 3)),- n_vocab=int(m.get("n_vocab", 0)),- mmproj=_asset_from(m.get("mmproj")),- draft=_asset_from(m.get("draft")),- sampling=dict(m.get("sampling", {})),- min_engine=str(m.get("min_engine", "")),- quality=int(m.get("quality", 0)),- decode_fraction=float(m.get("decode_fraction", 1.0)),- ))+ mmproj=_asset_from(m.get("mmproj")), draft=_asset_from(m.get("draft")),+ **scalars))return tuple(entries)@@ -410,9 +339,10 @@ CATALOG: "tuple[CatalogEntry, ...]" = _packaged_catalog()def refresh_catalog(force: bool = False) -> bool:"""Fetch the current catalog from the repo and swap it in memory.- Best-effort by design: any failure (offline, GitHub down, unreadable- schema) leaves the running catalog untouched and retries after the- TTL. Returns True when a fetched document replaced the catalog."""+ Best-effort by design: any failure (offline, GitHub down, unreadable schema) leaves the running+ catalog untouched and retries after the TTL. Returns True when a fetched document replaced the+ catalog.+ """global CATALOG, _last_refresh_attemptnow = time.monotonic()@@ -435,9 +365,9 @@ def refresh_catalog(force: bool = False) -> bool:def refresh_catalog_soon() -> None:- """TTL-gated background refresh; returns immediately. The caller's- current request serves the catalog it already has — the refresh- lands for the next one."""+ """TTL-gated background refresh; returns immediately. The caller's current request serves the+ catalog it already has — the refresh lands for the next one.+ """if time.monotonic() - _last_refresh_attempt < _REFRESH_TTL_S:returnthreading.Thread(target=refresh_catalog, daemon=True,@@ -448,13 +378,6 @@ def catalog_by_id() -> dict[str, CatalogEntry]:return {entry.id: entry for entry in CATALOG}-def find_variant(entry_id: str, model_id: str) -> QuantVariant | None:- entry = catalog_by_id().get(entry_id)- if entry is None:- return None- return next((v for v in entry.variants if v.model_id == model_id), None)--def find_entry_for_model(model_id: str) -> "tuple[CatalogEntry, QuantVariant] | None":"""Locate the entry + variant that owns a staged model id."""for entry in CATALOG:diff --git a/hermes_cli/local_runtime/context_policy.py b/hermes_cli/local_runtime/context_policy.pyindex 1f08ae354b3..682580f8f71 100644--- a/hermes_cli/local_runtime/context_policy.py+++ b/hermes_cli/local_runtime/context_policy.py@@ -1,35 +1,10 @@"""Context policy — the window ladder for managed local models.-One contract: any model runs at any window up to its native max; hardware-and session depth only change tokens/s. Constants, not knobs — nothing in-this module reads config.--The policy encodes behavior measured on real hardware (llama.cpp,-discrete NVIDIA GPUs on Windows/WDDM, and unified-memory devices):--- Windows never over-allocates VRAM ahead of need. On WDDM, allocating- past residency slows decode roughly 9x even at identical conversation- depth — the driver silently demotes pages instead of failing. Every- window grant therefore re-fits against live memory at grant time.-- Models launch at the largest window that fits entirely in GPU memory- (zero-spill) and grow toward their native max as the session needs- room, at request boundaries only.-- Growth re-prefills the conversation into the larger window. Measured- cost is comparable to save/restore on discrete GPUs, and recurrent or- hybrid-attention models cannot rewind mid-sequence anyway, so- re-prefill is the only mechanism that works for every architecture.-- Every recommended model gets at least a 64K window. When weights alone- exceed VRAM, the fit deliberately spills weights to host RAM to- protect that floor (measured: an explicit context size makes the fit- spill weights and hold the window rather than shrink it).-- Below ~6 tok/s decode, growth stops and compression becomes the- default; deeper context is an explicit per-session choice. The deepest- measured host-spilled configuration bottomed out near this rate.-- Spilled mixture-of-experts configs pin expert/FFN weights to host so- attention and KV stay GPU-resident — measured ~1.75x faster than- spilling layers naively at the same host byte count.-- Speculative decoding (MTP) defaults on only for spilled configs, where- its speedup is largest (measured 1.43x spilled vs 1.35x resident).+One contract: any model runs at any window up to its native max; hardware and session depth only+change tokens/s. Constants, not knobs — nothing in this module reads config.++The policy encodes behavior measured on real hardware (llama.cpp, discrete NVIDIA GPUs on+Windows/WDDM, and unified-memory devices):"""from __future__ import annotations@@ -97,14 +72,10 @@ def initial_window(profile: ModelProfile, budget: HardwareBudget,overhead_bytes: int = 0) -> WindowDecision | PhysicsRefusal:"""The launch decision: largest cheap rung, never below the floor.- Zero-spill rung: weights + ctx + overhead fit usable VRAM entirely.- Bounded-early-cost rung: weights already exceed VRAM; take the largest- rung whose ctx stays <= ~15% of usable VRAM.- Floor everywhere, capped at native.-- ``overhead_bytes``: runtime cost beyond weights+KV (RUNTIME_OVERHEAD- plus the vision projector when one loads). Zero keeps this function- pure physics for decision-table tests; production callers pass it.+ Zero-spill rung: weights + ctx + overhead fit usable VRAM entirely. Bounded-early-cost rung+ (weights already exceed VRAM): largest rung whose ctx stays <= ~15% of usable VRAM. Floor+ everywhere, capped at native. ``overhead_bytes`` is runtime cost beyond weights+KV; zero+ keeps this pure physics for decision-table tests, production callers pass it."""refusal = physics_check(profile, budget, FLOOR, flash_attention=flash_attention)if refusal:@@ -160,23 +131,13 @@ def growth_decision(profile: ModelProfile, budget: HardwareBudget, *,server_idle: bool,flash_attention: bool = True,occupancy_confirmed: bool = False) -> GrowthDecision:- """One growth evaluation, END-OF-TURN ONLY (caller guarantees the turn- boundary; recurrent state cannot rewind mid-sequence).-- Gate ordering:- 1. occupancy (~85%) — nothing to do before the edge;- 2. native cap — the contract tops out at trained context;- 3. idleness — growth re-grants only on an otherwise-idle- server (concurrency design);- 4. speed floor — below it, compression becomes the default and deeper- is an explicit user choice;- 5. re-fit against LIVE free memory (the rung must fit residency- NOW, not at launch time — over-allocation is the slow path).-- ``occupancy_confirmed``: the caller has independently established that- the session is at its window's edge (the agent's compression gate fired- on its own threshold). Skips gate 1 so two separately-derived edge- definitions can't deadlock into compress-before-grow.+ """One growth evaluation, END-OF-TURN ONLY (recurrent state cannot rewind mid-sequence).++ Gate order: occupancy (~85%) → native cap → idleness (growth only on an otherwise-idle+ server) → speed floor (below it compression is the default) → re-fit against LIVE free+ memory (the rung must fit NOW, not at launch). ``occupancy_confirmed`` skips gate 1 when the+ caller's own compression gate already fired, so two edge definitions can't deadlock into+ compress-before-grow."""if not occupancy_confirmed and session_tokens < current_window * _GROW_AT_OCCUPANCY:return GrowthDecision("hold", reason="session below growth occupancy")@@ -211,10 +172,10 @@ def growth_decision(profile: ModelProfile, budget: HardwareBudget, *,def spill_overrides(profile: ModelProfile) -> list[str]:- """-ot placement for spilled configs: expert/FFN weights to host so- attention + KV stay GPU-resident. MoE gets the expert pattern;- hybrids push recurrent-layer FFNs (their n_head_kv==0 layers carry no- KV worth protecting)."""+ """-ot placement for spilled configs: expert/FFN weights to host so attention + KV stay+ GPU-resident. MoE gets the expert pattern; hybrids push recurrent-layer FFNs (their n_head_kv==0+ layers carry no KV worth protecting).+ """if profile.moe:return ["-ot", r"blk\.\d+\.ffn_.*_exps\.weight=CPU"]if profile.recurrent_layer_count:@@ -228,27 +189,10 @@ def launch_args(profile: ModelProfile, decision: WindowDecision, *,mtp_draft_depth: int = 3,uma: bool = False,mtp_prefill: bool = False) -> list[str]:- """Per-model launch flags from a window decision. Explicit -c puts fit- into spill-weights-and-hold-ctx; q8 KV cache wherever flash attention- exists; -ot placement on spilled configs — DISCRETE cards only.-- ``uma``: on unified memory there is no bus to protect tensors from —- "CPU" and "GPU" are the same silicon, and pinning FFN weights to the- host path just forces CPU compute (measured well over 2x slower than- letting the allocator place everything). The discrete- ~1.75x win the -ot pattern encodes does not transfer; a spilled UMA- config runs unpinned.-- MTP and the large prefill microbatch both win, and whether they may- STACK is a fit question, not a rule: backend sampling keeps a- ubatch x vocab x fp32 logits buffer on the GPU and MTP's draft- context doubles it, so the stacked posture costs a few GiB extra at- large vocab. Where it fits, it measures best on both axes (Qwen3.8- Q4 on a 32 GiB card: 93.3 tok/s decode vs 89.5 at ub512, prefill- slightly better too); where it doesn't, ub512 keeps the decode win- without packing the card. ``mtp_prefill`` is that fit verdict —- presets decide it against the priced margin, and ub_logits_bytes()- prices the same choice so the flag and its cost travel together."""+ """Per-model launch flags from a window decision. Explicit -c puts fit into+ spill-weights-and-hold-ctx; q8 KV cache wherever flash attention exists; -ot placement on+ spilled configs — DISCRETE cards only.+ """args = ["-c", str(decision.window)]if mtp_capable:args += ["--spec-type", "draft-mtp",@@ -267,17 +211,10 @@ def launch_args(profile: ModelProfile, decision: WindowDecision, *,def ub_logits_bytes(n_vocab: int, *, mtp_capable: bool,mtp_prefill: bool = False) -> int:- """GPU logits/compute-buffer cost of the microbatch posture chosen by- launch_args, priced from the model's own vocab and calibrated against- measured server RSS (Qwen3.8 Q4, both postures, three windows):-- stacked (MTP + ub2048): ubatch x vocab x fp32 x 1.5 (~2.9 GiB at- 248K vocab; fitted 2.5, rounded up)- decode (MTP + ub512): ubatch x vocab x fp32 x 2 (~1.0 GiB)- plain (ub2048): ubatch x vocab x fp32 (~1.9 GiB)-- Callers add this to RUNTIME_OVERHEAD per model — the flag and its- price travel together or the fit lies."""+ """GPU logits/compute-buffer cost of the microbatch posture chosen by launch_args, priced from the+ model's own vocab and calibrated against measured server RSS (Qwen3.8 Q4, both postures, three+ windows):+ """v = max(0, int(n_vocab))if mtp_capable and mtp_prefill:return int(2048 * v * 4 * 1.5)diff --git a/hermes_cli/local_runtime/detect.py b/hermes_cli/local_runtime/detect.pyindex 02131255eda..376054555ac 100644--- a/hermes_cli/local_runtime/detect.py+++ b/hermes_cli/local_runtime/detect.py@@ -1,9 +1,8 @@"""Detection of running llama-server instances.-Probes well-known local roots and fingerprints genuine llama-server via-/props (build_info + model fields — Ollama and LM Studio answer /v1/models-but not /props). The credential is reachability; detection never needs a-key, but honors one if the probed server requires it (401 -> detected,+Probes well-known local roots and fingerprints genuine llama-server via /props (build_info + model+fields — Ollama and LM Studio answer /v1/models but not /props). The credential is reachability;+detection never needs a key, but honors one if the probed server requires it (401 -> detected,auth_required=True)."""@@ -51,10 +50,8 @@ def probe_port(port: int) -> DetectedServer | None:build = str(props.get("build_info", ""))if not build:return None # answers /props but isn't llama-server- n_ctx = Nonedgs = props.get("default_generation_settings")- if isinstance(dgs, dict):- n_ctx = dgs.get("n_ctx")+ n_ctx = dgs.get("n_ctx") if isinstance(dgs, dict) else Nonemodels_status, models = _get(f"{root}/models")return DetectedServer(base_url=f"{root}/v1",@@ -69,11 +66,7 @@ def probe_port(port: int) -> DetectedServer | None:def detect_server(extra_ports: tuple[int, ...] = ()) -> DetectedServer | None:"""First hit across default + extra ports (managed port, config port)."""- seen = set()- for port in (*DEFAULT_PROBE_PORTS, *extra_ports):- if port in seen:- continue- seen.add(port)+ for port in dict.fromkeys((*DEFAULT_PROBE_PORTS, *extra_ports)):hit = probe_port(port)if hit:return hitdiff --git a/hermes_cli/local_runtime/endpoint.py b/hermes_cli/local_runtime/endpoint.pyindex b80a663d031..01734465bf2 100644--- a/hermes_cli/local_runtime/endpoint.py+++ b/hermes_cli/local_runtime/endpoint.py@@ -1,14 +1,7 @@"""Endpoint resolution for llamacpp-alias requests (provider integration).-The seam between the existing provider mechanism and the managed runtime:-``provider: llamacpp`` with no explicit base_url resolves, in order, to--1. the managed server this Hermes is supervising (state file written by- LlamaServerSupervisor.start, removed on stop, staleness-checked), or-2. a detected external llama-server.--Returns None when neither exists — the caller falls through to the normal-custom-provider path and its own error reporting.+The seam between the existing provider mechanism and the managed runtime: ``provider: llamacpp``+with no explicit base_url resolves, in order, to"""from __future__ import annotations@@ -28,9 +21,8 @@ logger = logging.getLogger(__name__)def _pid_alive(pid: int) -> bool:"""Liveness for the state file's supervisor-child pid.- psutil when available; otherwise fall back to True (optimistic) — on- Windows ``os.kill(pid, 0)`` TERMINATES the process, so it must never be- used as a probe (windows-git-bash interop pitfall).+ psutil when available; otherwise fall back to True (optimistic) — on Windows ``os.kill(pid, 0)``+ TERMINATES the process, so it must never be used as a probe (windows-git-bash interop pitfall)."""if not pid or pid < 0:return False@@ -78,25 +70,16 @@ def _state_endpoint() -> dict | None:# optimistically so readiness probes racing the boot see a configured# provider, not missing credentials. A dead pid is a crashed-without-# cleanup leftover — ignore it so requests don't blackhole.- if pid_ok:- return endpoint- return None+ return endpoint if pid_ok else Nonedef resolve_llamacpp_endpoint(config: dict | None = None,wait_for_boot_s: float = 8.0) -> dict | None:"""Managed-first, detection-second endpoint for llamacpp aliases.- Returns {"base_url", "api_key"} or None. api_key is empty for keyless- external servers (callers substitute the SDK placeholder).-- Boot-race rung: on a fresh backend start there is NO state file yet —- the lifespan boot thread is still spawning the server (config load +- preset generation + spawn ≈ 1-3 s) while the desktop's readiness probe- fires the moment the WebSocket connects. When the runtime is enabled- and installed, a missing endpoint means BOOTING, not unconfigured:- poll briefly for the state file instead of failing the probe (twice- observed as 'no usable credentials' → onboarding on restart).+ Boot-race rung: on a fresh backend start there is NO state file yet — the lifespan boot thread+ is still spawning the server (config load + preset generation + spawn ≈ 1-3 s) while the+ desktop's readiness probe fires the moment the WebSocket connects."""managed = _state_endpoint()if managed:@@ -104,11 +87,8 @@ def resolve_llamacpp_endpoint(config: dict | None = None,from hermes_cli.local_runtime.detect import detect_server- extra = ()- if config:- ports = (config.get("local_runtime") or {}).get("detect_ports") or []- extra = tuple(int(p) for p in ports)- hit = detect_server(extra_ports=extra)+ ports = ((config or {}).get("local_runtime") or {}).get("detect_ports") or []+ hit = detect_server(extra_ports=tuple(int(p) for p in ports))if hit and not hit.auth_required:return {"base_url": hit.base_url, "api_key": ""}@@ -126,33 +106,28 @@ def resolve_llamacpp_endpoint(config: dict | None = None,_KICK_LOCK = threading.Lock()+def _load_config_if_none(config: dict | None) -> dict | None:+ if config is not None:+ return config+ from hermes_cli.config import load_config++ return load_config()++def _kick_managed_boot(config: dict | None) -> None:"""Actively start the managed server when resolution finds it missing.- The wait loop above assumes some OTHER thread is bringing the server- up — true only at backend start (the lifespan boot thread). A router- that dies LATER leaves no boot in flight: the backend process was- killed with the router as part of its tree, or another install took- the stable port and the ownership guard rightly refused it. In those- states the wait just expired and agent init failed with 'no provider- configured', even though the fix is the same idempotent ensure call- the lifespan makes. Kick it here, off-thread (the resolver's wait- stays bounded; ensure's own state checks make a concurrent lifespan- boot harmless) and non-reentrant (racing resolutions kick once).+ The wait loop above assumes some OTHER thread is bringing the server up — true only at backend+ start (the lifespan boot thread)."""if not _KICK_LOCK.acquire(blocking=False):return # a kick is already in flightdef _boot() -> None:try:- cfg = config- if cfg is None:- from hermes_cli.config import load_config-- cfg = load_config()from hermes_cli.local_runtime.bootstrap import ensure_local_runtime- ensure_local_runtime(cfg)+ ensure_local_runtime(_load_config_if_none(config))except Exception: # noqa: BLE001 — best-effort; resolution falls backlogger.warning("on-demand managed-server boot failed", exc_info=True)finally:@@ -164,28 +139,20 @@ def _kick_managed_boot(config: dict | None) -> None:def _boot_in_flight(config: dict | None) -> bool:"""True when the managed runtime is enabled and installed — the state- a lifespan boot thread is (or is about to be) bringing up.- Installed-ness is a verified-manifest scan under runtimes_root(), NOT a- server_binary() call — that helper requires an install_dir argument, and- calling it bare made this gate throw-and-return-False forever, silently- disabling the boot wait (the regression- test had monkeypatched this function instead of exercising it).+ Installed-ness is a verified-manifest scan under runtimes_root(), NOT a bare ``server_binary()``+ call: that helper needs an install_dir, and calling it bare made this gate throw-and-return+ False forever, silently disabling the boot wait."""try:- if config is None:- from hermes_cli.config import load_config-- config = load_config()+ config = _load_config_if_none(config)if not ((config or {}).get("local_runtime") or {}).get("enabled"):return False- import json as _json-from hermes_cli.local_runtime.binaries import runtimes_rootfor manifest in runtimes_root().glob("*/*/manifest.json"):try:- if _json.loads(manifest.read_text(encoding="utf-8")).get("verified_version"):+ if json.loads(manifest.read_text(encoding="utf-8")).get("verified_version"):return Trueexcept (ValueError, OSError):continuediff --git a/hermes_cli/local_runtime/estimator.py b/hermes_cli/local_runtime/estimator.pyindex 6778b88ed45..988a88a2a1c 100644--- a/hermes_cli/local_runtime/estimator.py+++ b/hermes_cli/local_runtime/estimator.py@@ -1,18 +1,7 @@"""Per-layer context-memory estimator + physics check.-The whole-model dense formula misprices 1M-context hybrids by ~100x; the-per-layer walk fixes that, and every column is measured on real GGUFs:--- full-attention layer: linear in T (B1: 144.0 KiB/tok on Qwen3-4B- f16 — formula-exact)-- SWA layer: capped at the sliding window-- recurrent layer (n_head_kv == 0): constant (state is ~context-free)-- q8_0 KV = exactly 34/64 of f16 (holds on CUDA and CPU)-- weights: exact from the tensor table (within 0.01% of the loader)--The estimator is ADVISORY: fit's allocation is authoritative at launch and-the touch generation is ground truth after it. Unknown shapes round UP-(never underestimate memory).+The estimator is ADVISORY: fit's allocation is authoritative at launch and the touch generation is+ground truth after it. Unknown shapes round UP (never underestimate memory)."""from __future__ import annotations@@ -46,9 +35,9 @@ class LayerKind(Enum):@dataclassclass ModelProfile:- """Everything the policy needs, decoupled from GGUF parsing so the- decision-table tests can construct profiles directly (design's- verification plan)."""+ """Everything the policy needs, decoupled from GGUF parsing so the decision-table tests can+ construct profiles directly (design's verification plan).+ """name: strweights_bytes: int@@ -82,11 +71,9 @@ class ModelProfile:class HardwareBudget:"""Memory the physics check may budget against.- Budget-source rule: discrete cards may trust the device query- (measured honest); unified-memory devices must budget from OS free- physical memory minus headroom — their device queries have been- observed off by 3x. Callers construct- this accordingly; the estimator just consumes it.+ Budget-source rule: discrete cards may trust the device query (measured honest); unified-memory+ devices must budget from OS free physical memory minus headroom — their device queries have been+ observed off by 3x. Callers construct this accordingly; the estimator just consumes it."""usable_vram_bytes: int # live free (discrete) / derived (UMA)@@ -138,9 +125,9 @@ def kv_dtype_factor(flash_attention: bool) -> float:def ctx_bytes(profile: ModelProfile, window: int, *,flash_attention: bool = True) -> int:- """Context memory for one window: full layers linear in T, SWA layers- capped at the sliding window, recurrent layers constant. Scaled by- profile.kv_scale (MTP draft context)."""+ """Context memory for one window: full layers linear in T, SWA layers capped at the sliding window,+ recurrent layers constant. Scaled by profile.kv_scale (MTP draft context).+ """factor = kv_dtype_factor(flash_attention)total = 0.0for kind, per_token_f16 in profile.layers:diff --git a/hermes_cli/local_runtime/gguf.py b/hermes_cli/local_runtime/gguf.pyindex a5159b9d566..e73e67dd2d1 100644--- a/hermes_cli/local_runtime/gguf.py+++ b/hermes_cli/local_runtime/gguf.py@@ -1,12 +1,7 @@"""GGUF metadata + tensor-table reader (stdlib only).-Feeds the per-layer context estimator: architecture, layer count, per-layer-KV head counts (0 = recurrent layer — the hybrid discriminator), head dims,-sliding-window config, trained context, and exact weight bytes summed from-the tensor table (validated to within 0.01% of the loader's buffer).--Reads the header only (metadata + tensor infos); never touches tensor data,-so it is fast enough to run at picker time on multi-GB files.+Reads the header only (metadata + tensor infos); never touches tensor data, so it is fast enough to+run at picker time on multi-GB files."""from __future__ import annotations@@ -65,9 +60,9 @@ class GGUFHeader:@propertydef n_vocab(self) -> int:- """Vocabulary size: prices the GPU logits buffers (they scale- ubatch x vocab). vocab_size metadata when present, else the- tokenizer list length."""+ """Vocabulary size: prices the GPU logits buffers (they scale ubatch x vocab). vocab_size+ metadata when present, else the tokenizer list length.+ """v = self._arch_key("vocab_size")if v:return int(v)@@ -82,12 +77,10 @@ class GGUFHeader:def sampling_defaults(self) -> dict:"""Upstream's recommended sampling, when the file carries it.- Model publishers bake general.sampling.* keys into the GGUF- (llama-server reads them as that model's default generation- settings), so the file itself is the source of truth for how its- publisher wants it run — it arrives with the download and updates- with every re-upload, no catalog required. Returned as preset INI- keys; empty when the file carries none.+ Publishers bake ``general.sampling.*`` keys into the GGUF (llama-server reads them as that+ model's defaults), so the file is the source of truth -- it ships with the download and+ updates with every re-upload, no catalog needed. Returned as preset INI keys; empty if+ absent."""ini_key = {"temp": "temp", "temperature": "temp", "top_p": "top-p","top_k": "top-k", "min_p": "min-p",@@ -121,16 +114,12 @@ class GGUFHeader:return int(self._arch_key("full_attention_interval") or 0)def head_counts_kv(self) -> list[int]:- """Per-layer KV head counts; 0 marks a recurrent/linear layer (the- n_head_kv == 0 discriminator).-- Three GGUF shapes, each verified against real files:- - per-layer array (nemotron_h_moe): use as-is;- - scalar + full_attention_interval (qwen35): the scalar applies to- every INTERVAL-th layer (1-indexed: layers where (i+1) % N == 0),- zero elsewhere — pricing all layers as attention was a 4x- overestimate on Qwen3.6-27B;- - plain scalar (dense): broadcast to every layer.+ """Per-layer KV head counts; 0 marks a recurrent/linear layer (n_head_kv == 0).++ Three GGUF shapes: a per-layer array (nemotron_h_moe) is used as-is; a scalar plus+ ``full_attention_interval`` (qwen35) applies to every N-th layer (1-indexed) and is zero+ elsewhere -- pricing all layers as attention was a 4x overestimate; a plain scalar (dense)+ broadcasts to every layer."""v = self._arch_key("attention.head_count_kv")if isinstance(v, list):diff --git a/hermes_cli/local_runtime/growth.py b/hermes_cli/local_runtime/growth.pyindex 484f2ff9f50..43cca00d0bb 100644--- a/hermes_cli/local_runtime/growth.py+++ b/hermes_cli/local_runtime/growth.py@@ -1,20 +1,7 @@"""In-session context growth for the managed llama.cpp runtime.-The live half of the window ladder (context_policy.growth_decision): when a-session reaches the edge of its granted window, Hermes grows the window-toward the model's native max INSTEAD of compressing. Compression becomes-what the design says it is — the move of last resort, once the window is at-native (or the speed floor / physics say stop).--Mechanism: growth is re-prefill. A per-model window-override is persisted, presets regenerate with the bigger window, the-supervised server bounces, and the next request autoloads the model at the-new window and re-prefills the conversation. Nothing about the Hermes-conversation mutates — no prompt-cache or role-alternation risk; the whole-operation is server-side.--Scope guard: only a server THIS process supervises grows. Detected external-servers and other-process supervisors keep their own policies.+Scope guard: only a server THIS process supervises grows. Detected external servers and other-+process supervisors keep their own policies."""from __future__ import annotations@@ -75,13 +62,12 @@ def is_managed_endpoint(base_url: str) -> bool:def maybe_grow_window(model_id: str, *, base_url: str, session_tokens: int,current_window: int,measured_decode_tok_s: float | None = None) -> int | None:- """One growth evaluation + execution. Returns the NEW window when the- ladder granted a bigger one, else None (hold / compress / not ours).+ """One growth evaluation + execution. Returns the NEW window when the ladder granted a bigger+ one, else None (hold / compress / not ours).- The caller sits at a request boundary by construction (the pre-API- compression gate), so re-prefill growth is safe at any call: the next- request rebuilds server state from scratch in the larger window —- nothing rewinds.+ The caller sits at a request boundary by construction (the pre-API compression gate), so+ re-prefill growth is safe at any call: the next request rebuilds server state in the larger+ window — nothing rewinds."""from hermes_cli.local_runtime.bootstrap import (get_supervisor,diff --git a/hermes_cli/local_runtime/hardware.py b/hermes_cli/local_runtime/hardware.pyindex c6a316776d5..0b309f07484 100644--- a/hermes_cli/local_runtime/hardware.py+++ b/hermes_cli/local_runtime/hardware.py@@ -1,27 +1,11 @@"""Live hardware budget probe.-Budget-source rule: discrete cards may trust the device query (measured-honest within rounding); unified-memory devices must budget from OS free-physical memory minus headroom — their device queries have been observed-off by 3x in both directions. The probe classifies the device and-constructs the right HardwareBudget for the estimator.--Vendor probe quirk (WDDM carve-out): on unified-memory NVIDIA devices-under Windows, nvidia-smi answers from the legacy dedicated-VRAM-carve-out — a fraction of the pool the CUDA allocator actually-addresses uniformly at full bandwidth. The CUDA driver API is-the tiebreaker: cuDeviceGetAttribute(INTEGRATED) is the vendor's own-declaration and always wins — 1 budgets unified, 0 stays discrete no-matter what any other number says. Only when the driver API is-unreachable does the engine's --list-devices view apply, and then only-behind two independent conditions no discrete card can meet.--Every probe here must work under a stripped PATH — gateway and service-sessions don't inherit the interactive environment. nvcuda/libcuda load-through the system loader (PATH plays no part), so classification never-depends on PATH; nvidia-smi resolves through an explicit candidate-ladder (PATH first, then the driver's known install locations) and its-absence only softens the live number, never the verdict.+Budget-source rule: discrete cards may trust the device query (measured honest within rounding);+unified-memory devices must budget from OS free physical memory minus headroom — their device+queries have been observed off by 3x in both directions.++Every probe here must work under a stripped PATH — gateway and service sessions don't inherit the+interactive environment."""from __future__ import annotations@@ -81,21 +65,21 @@ _pool_probe_cache: tuple[float, "tuple[int, bool | None] | None"] | None = None_DEVICE_LINE_RE = re.compile(r"CUDA\d+:.*\((\d+)\s*MiB,\s*\d+\s*MiB free\)\s*$")+def _stdout(*argv: str) -> str:+ return subprocess.run(list(argv), capture_output=True, text=True, timeout=5).stdout++def _ram_bytes() -> tuple[int, int]:"""(total, available) physical memory, cross-platform stdlib."""try:import ctypesclass MEMORYSTATUSEX(ctypes.Structure):- _fields_ = [("dwLength", ctypes.c_ulong),- ("dwMemoryLoad", ctypes.c_ulong),- ("ullTotalPhys", ctypes.c_ulonglong),- ("ullAvailPhys", ctypes.c_ulonglong),- ("ullTotalPageFile", ctypes.c_ulonglong),- ("ullAvailPageFile", ctypes.c_ulonglong),- ("ullTotalVirtual", ctypes.c_ulonglong),- ("ullAvailVirtual", ctypes.c_ulonglong),- ("ullAvailExtendedVirtual", ctypes.c_ulonglong)]+ _fields_ = ([("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong)]+ + [(name, ctypes.c_ulonglong) for name in (+ "ullTotalPhys", "ullAvailPhys", "ullTotalPageFile",+ "ullAvailPageFile", "ullTotalVirtual", "ullAvailVirtual",+ "ullAvailExtendedVirtual")])stat = MEMORYSTATUSEX()stat.dwLength = ctypes.sizeof(MEMORYSTATUSEX)@@ -103,48 +87,35 @@ def _ram_bytes() -> tuple[int, int]:return stat.ullTotalPhys, stat.ullAvailPhysexcept (AttributeError, OSError):pass- if sys.platform == "darwin":- # macOS getconf has no _PHYS_PAGES/_AVPHYS_PAGES (exit 64, "no such- # configuration parameter") — the POSIX branch below returns (0, 0)- # and every model reads unavailable. sysctl is the platform truth.- try:- total = int(subprocess.run(- ["/usr/sbin/sysctl", "-n", "hw.memsize"],- capture_output=True, text=True, timeout=5).stdout.strip() or 0)+ try:+ if sys.platform == "darwin":+ # macOS getconf has no _PHYS_PAGES/_AVPHYS_PAGES (exit 64, "no such+ # configuration parameter") — the POSIX branch below returns (0, 0)+ # and every model reads unavailable. sysctl is the platform truth.+ total = int(_stdout("/usr/sbin/sysctl", "-n", "hw.memsize").strip() or 0)if total <= 0:return 0, 0avail = total // 2 # conservative fallbacktry:- out = subprocess.run(["/usr/bin/vm_stat"], capture_output=True,- text=True, timeout=5).stdout+ out = _stdout("/usr/bin/vm_stat")page_m = re.search(r"page size of (\d+)", out)page = int(page_m.group(1)) if page_m else 16384- pages = 0# free + inactive + purgeable ≈ reclaimable-on-demand; the# speculative pool is dropped by the OS under pressure too.- for key in ("Pages free", "Pages inactive", "Pages purgeable",- "Pages speculative"):- m = re.search(rf"{key}:\s+(\d+)\.", out)- if m:- pages += int(m.group(1))+ pages = sum(int(m.group(1)) for key in (+ "Pages free", "Pages inactive", "Pages purgeable", "Pages speculative")+ if (m := re.search(rf"{key}:\s+(\d+)\.", out)))if pages > 0:avail = pages * pageexcept (OSError, ValueError):passreturn total, avail- except (OSError, ValueError):- return 0, 0- # POSIX- try:- page = int(subprocess.run(["getconf", "PAGE_SIZE"], capture_output=True,- text=True, timeout=5).stdout or 4096)- total = int(subprocess.run(["getconf", "_PHYS_PAGES"], capture_output=True,- text=True, timeout=5).stdout or 0) * page+ # POSIX+ page = int(_stdout("getconf", "PAGE_SIZE") or 4096)+ total = int(_stdout("getconf", "_PHYS_PAGES") or 0) * pageavail = total // 2 # conservative when _AVPHYS is unavailabletry:- avail = int(subprocess.run(["getconf", "_AVPHYS_PAGES"],- capture_output=True, text=True,- timeout=5).stdout or 0) * page or avail+ avail = int(_stdout("getconf", "_AVPHYS_PAGES") or 0) * page or availexcept (OSError, ValueError):passreturn total, avail@@ -160,25 +131,23 @@ _smi_path_cache: "tuple[str | None] | None" = Nonedef _nvidia_smi_path() -> str | None:- """Absolute path to nvidia-smi, or None. PATH first (respects user- overrides), then the driver's known install locations on Windows;- on Linux/WSL the PATH lookup is the whole ladder."""+ """Absolute path to nvidia-smi, or None. PATH first (respects user overrides), then the driver's+ known install locations on Windows; on Linux/WSL the PATH lookup is the whole ladder.+ """global _smi_path_cacheif _smi_path_cache is not None:return _smi_path_cache[0]found = shutil.which("nvidia-smi")if found is None and os.name == "nt":windir = os.environ.get("SystemRoot", r"C:\Windows")- for candidate in (+ candidates = (# DCH drivers (every modern install) place it in System32.Path(windir) / "System32" / "nvidia-smi.exe",# Legacy standalone drivers used NVSMI, never on PATH.Path(os.environ.get("ProgramFiles", r"C:\Program Files"))/ "NVIDIA Corporation" / "NVSMI" / "nvidia-smi.exe",- ):- if candidate.exists():- found = str(candidate)- break+ )+ found = next((str(c) for c in candidates if c.exists()), None)_smi_path_cache = (found,)return found@@ -202,12 +171,11 @@ def _nvidia_vram() -> tuple[int, int] | None:def _cuda_driver_pool() -> "tuple[int, bool | None] | None":- """(allocator_total_bytes, integrated_or_None) from the CUDA driver- API, or None when unreachable. ctypes against the driver's own DLL/SO- — no toolkit, no subprocess, ~ms. INTEGRATED is the vendor's own- unified-memory declaration; total is the pool the allocator will- actually hand out (on carve-out devices, several times what- nvidia-smi reports)."""+ """(allocator_total_bytes, integrated_or_None) from the CUDA driver API, or None when unreachable.+ ctypes against the driver's own DLL/SO — no toolkit, no subprocess, ~ms. INTEGRATED is the+ vendor's own unified-memory declaration; total is the pool the allocator will actually hand out+ (on carve-out devices, several times what nvidia-smi reports).+ """import ctypesfor name in ("nvcuda.dll", "libcuda.so.1", "libcuda.so"):@@ -239,10 +207,10 @@ def _cuda_driver_pool() -> "tuple[int, bool | None] | None":def _engine_device_pool() -> "tuple[int, bool | None] | None":- """(engine_total_bytes, None) from the installed runtime's own- --list-devices, or None. The fallback truth source when the driver- API is unreachable: asks the exact binary that will do the- allocating. Carries no integrated verdict — callers must gate it."""+ """(engine_total_bytes, None) from the installed runtime's own --list-devices, or None. The+ fallback truth source when the driver API is unreachable: asks the exact binary that will do the+ allocating. Carries no integrated verdict — callers must gate it.+ """try:from hermes_cli.local_runtime.binaries import (installed_tags,@@ -272,9 +240,9 @@ def _engine_device_pool() -> "tuple[int, bool | None] | None":def _device_pool_view() -> "tuple[int, bool | None] | None":- """Best available allocator-side view, cached: a hit is permanent for- the process, a miss retries after a short TTL (the engine binary can- appear mid-session via a pane install)."""+ """Best available allocator-side view, cached: a hit is permanent for the process, a miss retries+ after a short TTL (the engine binary can appear mid-session via a pane install).+ """global _pool_probe_cachenow = time.monotonic()if _pool_probe_cache is not None:@@ -288,13 +256,10 @@ def _device_pool_view() -> "tuple[int, bool | None] | None":def _unified_pool_bytes(smi_total: int, ram_total: int) -> int | None:"""The real pool size when this NVIDIA device is unified memory behind- a WDDM carve-out, else None (trust nvidia-smi as ever).- The driver's INTEGRATED attribute decides when readable — in BOTH- directions (0 pins discrete even if the numbers look weird; a driver- that declares integrated is believed even at modest pool sizes). Only- an attribute-less view (engine fallback) needs the two numeric gates;- both must hold and no discrete card meets either.+ The driver's INTEGRATED attribute decides in BOTH directions when readable (0 pins discrete+ even if numbers look odd; a declared-integrated driver is believed at modest pool sizes). Only+ the attribute-less engine fallback needs the two numeric gates, both of which must hold."""view = _device_pool_view()if view is None:@@ -310,20 +275,19 @@ def _unified_pool_bytes(smi_total: int, ram_total: int) -> int | None:return None+def _uma_budget(base: int, total: int) -> HardwareBudget:+ usable = max(0, int(base * (1 - _UMA_HEADROOM_FRACTION)))+ return HardwareBudget(usable_vram_bytes=usable, total_device_bytes=total,+ ram_available_bytes=0, uma=True)++def probe_budget(*, planning: bool = False) -> HardwareBudget:"""Construct the budget per the source rules above.- ``planning=False`` (default): LIVE budget — free VRAM right now. The- right input for launch-time fit decisions and growth re-grants.-- ``planning=True``: CAPACITY budget — what this machine can run once- the runtime manages placement (total device memory minus the margin).- The right input for catalog pricing and quant selection: pricing- against live-free while a model is already loaded made every row read- 'larger than your GPU memory' and degraded quant picks to Q2 on a- 32 GiB card. The managed server- unloads/relaunches models itself, so at load time the capacity is- genuinely available.+ ``planning=False``: LIVE budget (free VRAM now) for launch-time fit and growth re-grants.+ ``planning=True``: CAPACITY budget (total minus margin) for catalog pricing and quant selection;+ pricing against live-free while a model was loaded made every row read as too large and+ degraded quant picks. The managed server unloads/relaunches itself, so capacity is real."""ram_total, ram_avail = _ram_bytes()vram = _nvidia_vram()@@ -355,25 +319,17 @@ def probe_budget(*, planning: bool = False) -> HardwareBudget:# Without smi, OS-available alone is the honest floor.live = (vram[1] + ram_avail) if vram else ram_availbase = min(unified, live)- usable = max(0, int(base * (1 - _UMA_HEADROOM_FRACTION)))- return HardwareBudget(usable_vram_bytes=usable,- total_device_bytes=unified,- ram_available_bytes=0, uma=True)+ return _uma_budget(base, unified)if vram is None:# No NVIDIA device visible: Metal/Vulkan/CPU paths budget from RAM# as UMA (Apple Silicon) — conservative for discrete AMD until a# vendor probe lands (E3 hardware).- base = ram_total if planning else ram_avail- usable = max(0, int(base * (1 - _UMA_HEADROOM_FRACTION)))- return HardwareBudget(usable_vram_bytes=usable,- total_device_bytes=ram_total,- ram_available_bytes=0, uma=True)+ return _uma_budget(ram_total if planning else ram_avail, ram_total)total, free = vrammargin = max(_MARGIN_FLOOR, int(total * _MARGIN_FRACTION))- base = total if planning else free- return HardwareBudget(usable_vram_bytes=max(0, base - margin),+ return HardwareBudget(usable_vram_bytes=max(0, (total if planning else free) - margin),total_device_bytes=total,- ram_available_bytes=ram_avail if not planning else ram_total,+ ram_available_bytes=ram_total if planning else ram_avail,uma=False)diff --git a/hermes_cli/local_runtime/hf_browse.py b/hermes_cli/local_runtime/hf_browse.pyindex e554ee1fc4a..d69e1fbc855 100644--- a/hermes_cli/local_runtime/hf_browse.py+++ b/hermes_cli/local_runtime/hf_browse.py@@ -1,19 +1,11 @@"""Browse Hugging Face for GGUF models the user can run.-The curated catalog is the front page; this module is the firehose behind-it — day-0 models not yet in the catalog, community quants,-anything. Three rules keep it safe and honest:--1. Acquisition only. Nothing here serves a model: a browsed download- lands in the machine-scoped models dir and from that moment the- normal machinery owns it — staleness bounce, preset generation from- the real GGUF header, fit policy, placement pills.-2. The fit verdict shown BEFORE download is a rough cut priced from file- size alone (weights dominate; KV/overhead use conservative fill-ins).- After download the GGUF header is the authority, as everywhere.-3. HF is queried directly with short timeouts and a small in-process- cache. No third-party proxy service; if HF rate limits ever bite at- fleet scale, revisit with a caching proxy then.+The curated catalog is the front page; this module is the firehose behind it — day-0 models not yet+in the catalog, community quants, anything. Three rules keep it safe and honest:++1. Acquisition only. Nothing here serves a model: a browsed download lands in the machine-scoped+models dir and from that moment the normal machinery owns it — staleness bounce, preset generation+from the real GGUF header, fit policy, placement pills. 2."""from __future__ import annotations@@ -24,7 +16,7 @@ import reimport timeimport urllib.parseimport urllib.request-from dataclasses import dataclass, field+from dataclasses import dataclass, replacelogger = logging.getLogger(__name__)@@ -87,16 +79,12 @@ def search_models(query: str, limit: int = 20) -> list[HFModelHit]:q = urllib.parse.quote(query.strip())url = (f"{_HF}/api/models?search={q}&filter=gguf&sort=downloads"f"&direction=-1&limit={max(1, min(int(limit), 50))}")- out: list[HFModelHit] = []- for m in _get_json(url):- out.append(HFModelHit(- repo=str(m.get("id", "")),- downloads=int(m.get("downloads") or 0),- likes=int(m.get("likes") or 0),- updated=str(m.get("lastModified") or ""),- gated=bool(m.get("gated")),- ))- return out+ return [HFModelHit(repo=str(m.get("id", "")),+ downloads=int(m.get("downloads") or 0),+ likes=int(m.get("likes") or 0),+ updated=str(m.get("lastModified") or ""),+ gated=bool(m.get("gated")))+ for m in _get_json(url)]def _quant_label(filename: str) -> str:@@ -128,10 +116,8 @@ def repo_files(repo: str) -> list[HFFileGroup]:else:singles.append((path, size))- groups: list[HFFileGroup] = []- for path, size in singles:- groups.append(HFFileGroup(label=_quant_label(path), paths=(path,),- total_bytes=size))+ groups = [HFFileGroup(label=_quant_label(path), paths=(path,), total_bytes=size)+ for path, size in singles]for stem, parts in splits.items():parts.sort()groups.append(HFFileGroup(@@ -143,9 +129,9 @@ def repo_files(repo: str) -> list[HFFileGroup]:def rough_fit(total_bytes: int, budget) -> str:- """Coarse pre-download verdict from file size alone. The GGUF header- refines this after download; bands match the catalog pills' language.- File size ≈ in-memory weights for GGUF (mmap'd as-is)."""+ """Coarse pre-download verdict from file size alone. The GGUF header refines this after download;+ bands match the catalog pills' language. File size ≈ in-memory weights for GGUF (mmap'd as-is).+ """need = total_bytes + _ROUGH_KV_AND_OVERHEADif need <= budget.usable_vram_bytes:return "fits-gpu"@@ -155,7 +141,5 @@ def rough_fit(total_bytes: int, budget) -> str:def priced_repo_files(repo: str, budget) -> list[HFFileGroup]:- from dataclasses import replace-return [replace(g, fit=rough_fit(g.total_bytes, budget))for g in repo_files(repo)]diff --git a/hermes_cli/local_runtime/load_progress.py b/hermes_cli/local_runtime/load_progress.pyindex 379955c6e8c..da86a6ba940 100644--- a/hermes_cli/local_runtime/load_progress.py+++ b/hermes_cli/local_runtime/load_progress.py@@ -1,24 +1,12 @@"""Live model-load progress from the managed llama-server router.-llama-server's child processes emit per-tensor load progress-({stages, current, value}, throttled upstream to ~200ms) which the-router relays ONLY over its /models/sse stream — GET /models carries-just the coarse status string. This module owns one lazy background-watcher on that stream and keeps an in-memory snapshot other code can-poll cheaply:-- get_loading_progress() -> {model_id: {"stage", "value", "percent"}}--"percent" is a composite across stages so a bar doesn't sprint 0->100-once per stage: the text model dominates load time (its weights dwarf-the mmproj/spec extras), so it gets the lion's share of the range and-the extras split the remainder.--The watcher starts on first call, reconnects with backoff (the router-bounces on model download/eject), and never raises into callers — no-router, no state file, or no SSE support (older engines) all read as-"nothing loading". Safe from any process on the machine: the endpoint-comes from the supervisor's machine-scoped state file.+llama-server's child processes emit per-tensor load progress ({stages, current, value}, throttled+upstream to ~200ms) which the router relays ONLY over its /models/sse stream — GET /models carries+just the coarse status string.++The watcher starts on first call, reconnects with backoff (the router bounces on model+download/eject), and never raises into callers — no router, no state file, or no SSE support (older+engines) all read as "nothing loading"."""from __future__ import annotations@@ -58,11 +46,11 @@ def _composite_percent(stages: list[str], current: str, value: float) -> int:def _endpoint() -> "tuple[str, str] | None":"""(base_root, api_key) of the managed router, or None.- Resolved through the endpoint module's ownership-guarded reader, not- a raw state-file read: on the shared stable port, a foreign install's- server answers /health for anyone, and a raw read would attach this- watcher to someone else's SSE stream (or spin on 401s against it).- The guard's dead-pid check is the ownership proof."""+ Resolved through the endpoint module's ownership-guarded reader, not a raw state-file read: on+ the shared stable port a foreign install's server answers /health for anyone, and a raw read+ would attach this watcher to someone else's SSE stream. The dead-pid check is the ownership+ proof.+ """try:from hermes_cli.local_runtime.endpoint import _state_endpoint@@ -160,17 +148,13 @@ def get_loading_progress() -> dict[str, dict]:def get_prefill_progress(model: str) -> "dict | None":- """{"processed": tokens} while the managed server is prompt-processing- for ``model``, or None (idle, decoding, unreachable, or foreign server).-- llama-server's /slots reports ``n_prompt_tokens_processed`` climbing in- real time during prefill, but exposes no total — callers supply their- own denominator (the request's estimated token count). Busiest- processing slot wins when several are active: a parallel small request- (title generation) freezes its counter during decode while a live- prefill keeps climbing past it. One authenticated HTTP call per poll;- every failure reads as "no prefill" — this is garnish, never load-- bearing.+ """{"processed": tokens} while the managed server is prompt-processing for ``model``, or None+ (idle, decoding, unreachable, or foreign server).++ llama-server's /slots exposes ``n_prompt_tokens_processed`` but no total, so callers supply the+ denominator. The busiest processing slot wins: a parallel small request freezes its counter+ during decode while a live prefill keeps climbing. One HTTP call per poll; every failure reads+ as "no prefill" — garnish, never load-bearing."""ep = _endpoint()if ep is None:diff --git a/hermes_cli/local_runtime/presets.py b/hermes_cli/local_runtime/presets.pyindex a5aa96cfa3b..a4008c22a9a 100644--- a/hermes_cli/local_runtime/presets.py+++ b/hermes_cli/local_runtime/presets.py@@ -1,9 +1,5 @@-"""Per-model preset generation (--models-preset INI) — the router-side-carrier for context-policy launch decisions.--The INI shape is what the router itself generates per child: a-[model-id] section whose keys are long-form-llama-server flag names without the leading dashes.+"""Per-model preset generation (--models-preset INI) — the router-side carrier for context-policy+launch decisions."""from __future__ import annotations@@ -69,16 +65,10 @@ def _args_to_keys(args: list[str]) -> dict[str, str]:def generate_presets(models_dir: Path, budget: HardwareBudget,preset_path: Path,mtp_capable: set[str] | None = None) -> list[PresetEntry]:- """Walk the staged models, run the launch decision per model, and- write one INI. Refused models get no section (the router simply won't- have policy for them; the picker surfaces the refusal + smaller-quant- suggestion from the returned entries).-- Catalog-declared companions merge in here: sampling defaults (policy- keys always win), the vision projector when present, and a spec-decode- draft model iff the decision spilled — the rule: speculative- decode is a spill amplifier, so a resident draft accelerates a spilled- main model; a zero-spill model doesn't pay the draft's memory."""+ """Walk the staged models, run the launch decision per model, and write one INI. Refused models get+ no section (the router simply won't have policy for them; the picker surfaces the refusal ++ smaller-quant suggestion from the returned entries).+ """from hermes_cli.local_runtime.bootstrap import assets_dirfrom hermes_cli.local_runtime.catalog import find_entry_for_model@@ -221,9 +211,9 @@ def generate_presets(models_dir: Path, budget: HardwareBudget,def read_preset_decisions(preset_path: Path | None = None) -> dict[str, PresetEntry]:- """The launch decisions the running server was actually given, read- back from the preset INI (the INI is the record — it's what spawned- the children). Missing/unparseable file returns {}."""+ """The launch decisions the running server was actually given, read back from the preset INI (the+ INI is the record — it's what spawned the children). Missing/unparseable file returns {}.+ """import configparserif preset_path is None:diff --git a/hermes_cli/local_runtime/supervisor.py b/hermes_cli/local_runtime/supervisor.pyindex 44f162cf48a..23d2fb258bf 100644--- a/hermes_cli/local_runtime/supervisor.py+++ b/hermes_cli/local_runtime/supervisor.py@@ -1,20 +1,12 @@"""Supervision of one llama-server in router mode.-The router process is ours (restart with backoff on crash); router children-are its problem — child failures surface via GET /models exit_code, never-auto-retried here.--Readiness rules (each learned the hard way on real hardware):-- health-200 is NOT readiness; every readiness claim requires a touch- generation (temp-0, expected token, generous budget, reasoning_content- scanned).-- Always dial 127.0.0.1 — resolving localhost adds ~2s per request on- Windows via IPv6 fallback.-- /metrics is opt-in (--metrics) and carries no KV-usage metric;- idleness = requests_processing == 0 and no slot is_processing.-- The router's LRU eviction has no pin for the primary model: until an- upstream pin exists, keep_primary_loaded re-touches the primary after- any other model load.+The router process is ours (restart with backoff on crash); router children are its problem — child+failures surface via GET /models exit_code, never auto-retried here.++Readiness rules (each learned the hard way on real hardware): - health-200 is NOT readiness; every+readiness claim requires a touch generation (temp-0, expected token, generous budget,+reasoning_content scanned). - Always dial 127.0.0.1 — resolving localhost adds ~2s per request on+Windows via IPv6 fallback."""from __future__ import annotations@@ -60,9 +52,9 @@ _DEFAULT_PORT = 18434def _stable_port() -> int:- """The stable default port, falling back to an ephemeral one only when- something else already listens there (and it isn't a leftover managed- server, which stop() would have cleaned up)."""+ """The stable default port, falling back to an ephemeral one only when something else already+ listens there (and it isn't a leftover managed server, which stop() would have cleaned up).+ """try:with socket.socket() as s:s.bind(("127.0.0.1", _DEFAULT_PORT))@@ -77,12 +69,9 @@ def _stable_port() -> int:def _stable_api_key() -> str:"""One key for the life of the install, persisted beside the runtimes.- Endpoint identity must survive restarts as a UNIT — sessions persist the- resolved base_url + api_key, so a per-boot key strands every resumed- session on HTTP 401 exactly the way a per-boot port would strand them- on connection errors. Rotating it buys nothing: the key exists to stop- other loopback processes free-riding, and it lives on the same disk as- the state file that would leak it. Delete the file to rotate manually.+ Endpoint identity must survive restarts as a UNIT — sessions persist the resolved base_url ++ api_key, so a per-boot key strands every resumed session on HTTP 401 exactly the way a per-boot+ port would strand them on connection errors."""key_path = runtimes_root() / ".api_key"try:@@ -102,16 +91,7 @@ def _stable_api_key() -> str:class LlamaServerSupervisor:- """Own one llama-server router process for the life of a Hermes session.-- Usage::-- sup = LlamaServerSupervisor(install_dir, models_dir)- sup.start() # spawn + wait healthy- sup.ensure_model_ready(name) # load + touch-generate- ... sup.base_url is the /v1 endpoint, sup.api_key its key ...- sup.stop()- """+ """Own one llama-server router process for the life of a Hermes session."""def __init__(self, install_dir: Path, models_dir: Path, *,models_max: int = 4, port: int | None = None,@@ -143,14 +123,20 @@ class LlamaServerSupervisor:def _url(self, route: str) -> str:return f"http://127.0.0.1:{self.port}{route}"- def _request(self, route: str, body: dict | None = None, timeout_s: int = 30) -> dict:+ def _open(self, route: str, body: dict | None = None, timeout_s: int = 30,+ *, json_type: bool = True):+ headers = {"Authorization": f"Bearer {self.api_key}"}+ if json_type:+ headers["Content-Type"] = "application/json"req = urllib.request.Request(self._url(route),data=json.dumps(body).encode() if body is not None else None,- headers={"Content-Type": "application/json",- "Authorization": f"Bearer {self.api_key}"},+ headers=headers,)- with urllib.request.urlopen(req, timeout=timeout_s) as r:+ return urllib.request.urlopen(req, timeout=timeout_s)++ def _request(self, route: str, body: dict | None = None, timeout_s: int = 30) -> dict:+ with self._open(route, body, timeout_s) as r:raw = r.read()return json.loads(raw) if raw else {}@@ -182,9 +168,7 @@ class LlamaServerSupervisor:]if self.preset_path and self.preset_path.exists():cmd += ["--models-preset", str(self.preset_path)]- cmd += [- *self.extra_args,- ]+ cmd += self.extra_argsself.log_path.parent.mkdir(parents=True, exist_ok=True)if self._log_handle is not None:# The crash-restart loop calls _spawn repeatedly; without@@ -279,14 +263,10 @@ class LlamaServerSupervisor:def _terminate_tree(proc: subprocess.Popen) -> None:"""Terminate the router AND its model children.- The router spawns one child llama-server per loaded model, each- holding gigabytes of VRAM. Terminating only the router (on- Windows, TerminateProcess — no signal handlers, no cleanup pass)- orphans those children: the port goes quiet but the weights stay- resident, and the next spawn re-loads models alongside a ghost- still holding the memory. Enumerate children FIRST (the parent- must be alive to walk them), then terminate parent and children- together, escalating to kill for stragglers.+ The router spawns one child llama-server per loaded model, each holding gigabytes of VRAM.+ Terminating only the router (on Windows, TerminateProcess with no cleanup) orphans them: the+ port goes quiet but the weights stay resident. Enumerate children FIRST (the parent must be+ alive to walk them), then terminate all together, escalating to kill for stragglers."""children: list = []try:@@ -315,12 +295,10 @@ class LlamaServerSupervisor:def _reap_orphaned_children(self) -> None:"""Kill model children orphaned by a router crash, before respawn.- A crashed router can't clean up its children, and a dead parent- can't be walked — so match by identity instead: any process- running OUR llama-server binary whose parent is gone is an- orphan of a previous router. Their VRAM must come back before- the new router loads models next to the ghosts. External- llama-servers (different binary path) never match.+ A crashed router can't clean up its children, and a dead parent can't be walked — so match+ by identity instead: any process running OUR llama-server binary whose parent is gone is an+ orphan of a previous router. Their VRAM must come back before the new router loads models+ next to the ghosts."""try:import psutil@@ -350,31 +328,13 @@ class LlamaServerSupervisor:return {m["id"]: m.get("status", {}).get("value", "unknown")for m in data.get("data", [])}- def model_failures(self) -> dict:- """{model_id: exit_code} for children that died — surfaced to the- UI, never auto-retried (design: router children are its problem)."""- data = self._request("/models")- out = {}- for m in data.get("data", []):- status = m.get("status", {})- if status.get("value") == "failed" or status.get("exit_code"):- out[m["id"]] = status.get("exit_code")- return out-def load_model(self, model_id: str, timeout_s: int = 600) -> None:self._request("/models/load", {"model": model_id}, timeout_s=timeout_s)def unload_model(self, model_id: str) -> None:- """Free the child's VRAM now. Route existence verified empirically- on b10290 (POST /models/unload; bogus name -> 400 'model is not- found'). Momentary action: never touches primary_model — the- declaration is durable, an eject is not (residency design).-- Settle before returning: for a few seconds after unload returns,- the router still routes to the dying child and answers chat with- 500 'proxy error: Could not establish connection' (probed on- b10362). Waiting for the model to report unloaded means the next- message autoloads cleanly instead of racing the teardown.+ """Free the child's VRAM now. Route existence verified empirically on b10290 (POST+ /models/unload; bogus name -> 400 'model is not found'). Momentary action: never touches+ primary_model — the declaration is durable, an eject is not (residency design)."""self._request("/models/unload", {"model": model_id}, timeout_s=120)deadline = time.monotonic() + 15@@ -406,10 +366,7 @@ class LlamaServerSupervisor:except Exception: # noqa: BLE001return unloadedfor model_id, status in statuses.items():- if status not in ("loaded", "ready"):- self._idle_since.pop(model_id, None)- continue- if not self.is_idle(model_id):+ if status not in ("loaded", "ready") or not self.is_idle(model_id):self._idle_since.pop(model_id, None)continuefirst_idle = self._idle_since.setdefault(model_id, now)@@ -425,9 +382,9 @@ class LlamaServerSupervisor:return unloadeddef touch_generate(self, model_id: str, timeout_s: int = 300) -> bool:- """The readiness proof. Generous budget + reasoning_content scan —- small token budgets false-fail reasoning models, which spend their- first tokens thinking."""+ """The readiness proof. Generous budget + reasoning_content scan — small token budgets+ false-fail reasoning models, which spend their first tokens thinking.+ """try:resp = self._request("/v1/chat/completions", {"model": model_id,@@ -450,32 +407,13 @@ class LlamaServerSupervisor:self.load_model(model_id, timeout_s=timeout_s)return self.touch_generate(model_id)- def actual_n_ctx(self, model_id: str) -> int | None:- """/props reconciliation: the granted window as the child reports- it — the compressor's budget and the picker's 'running at 87K of- 262K' both read THIS value, never the request (design step 4)."""- try:- props = self._request(f"/props?model={model_id}")- return props.get("default_generation_settings", {}).get("n_ctx")- except Exception: # noqa: BLE001- return None-- def keep_primary_loaded(self) -> None:- """The router's LRU eviction has no pin, so after any other load- re-touch the primary to keep it most-recently-used. Best-effort- under bursty multi-model load — replaced when an upstream pin- exists."""- if self.primary_model and self.models().get(self.primary_model) in (- "loaded", "ready"):- self.touch_generate(self.primary_model, timeout_s=60)-# ── telemetry ────────────────────────────────────────────def is_idle(self, model_id: str | None = None) -> bool:- """No processing requests and no busy slots. Router quirk: /slots- and /metrics are per-child and require ?model= (bare calls 400),- and no KV-usage metric exists. With ``model_id`` checks that one- child; without, every loaded child."""+ """No processing requests and no busy slots. Router quirk: /slots and /metrics are per-child+ and require ?model= (bare calls 400), and no KV-usage metric exists. With ``model_id``+ checks that one child; without, every loaded child.+ """try:if model_id is not None:loaded = [model_id]@@ -486,10 +424,7 @@ class LlamaServerSupervisor:slots = self._request(f"/slots?model={mid}")if any(s.get("is_processing") for s in slots):return False- req = urllib.request.Request(- self._url(f"/metrics?model={mid}"),- headers={"Authorization": f"Bearer {self.api_key}"})- with urllib.request.urlopen(req, timeout=10) as r:+ with self._open(f"/metrics?model={mid}", timeout_s=10, json_type=False) as r:text = r.read().decode()for line in text.splitlines():if line.startswith("llamacpp:requests_processing"):diff --git a/hermes_cli/model_catalog.py b/hermes_cli/model_catalog.pyindex 1e869b746a4..029e2bcd72a 100644--- a/hermes_cli/model_catalog.py+++ b/hermes_cli/model_catalog.py@@ -1,45 +1,13 @@"""Remote model catalog fetcher.-The Hermes docs site hosts a JSON manifest of curated models for providers-we want to update without shipping a release (currently OpenRouter and-Nous Portal). This module fetches, validates, and caches that manifest,-falling back to the in-repo hardcoded lists when the network is unavailable.--Pipeline----------1. ``get_catalog()`` — returns a parsed manifest dict.- - Checks in-process cache (invalidated by TTL).- - Reads disk cache at ``~/.hermes/cache/model_catalog.json``.- - Fetches the master URL if disk cache is stale or missing.- - On any fetch failure, keeps using the stale cache (or empty dict).--2. ``get_curated_openrouter_models()`` / ``get_curated_nous_models()`` —- thin accessors returning the shapes existing callers expect. Each- falls back to the in-repo hardcoded list on any lookup failure.--Schema (version 1)--------------------::-- {- "version": 1,- "updated_at": "2026-04-25T22:00:00Z",- "metadata": {...}, # free-form- "providers": {- "openrouter": {- "metadata": {...}, # free-form- "models": [- {"id": "vendor/model", "description": "recommended",- "metadata": {...}} # free-form, model-level- ]- },- "nous": {...}- }- }--Unknown fields are ignored — extra metadata can be added at either level-without bumping ``version``. ``version`` bumps are reserved for-breaking changes (renaming ``providers``, changing ``models`` shape).+Pipeline -------- 1. ``get_catalog()`` — returns a parsed manifest dict. - Checks in-process cache+(invalidated by TTL). - Reads disk cache at ``~/.hermes/cache/model_catalog.json``. - Fetches the+master URL if disk cache is stale or missing. - On any fetch failure, keeps using the stale cache+(or empty dict).++2. ``get_curated_openrouter_models()`` / ``get_curated_nous_models()`` — thin accessors returning+the shapes existing callers expect. Each falls back to the in-repo hardcoded list on any lookup+failure."""from __future__ import annotations@@ -177,10 +145,9 @@ def _fetch_manifest_with_fallback() -> dict[str, Any] | None:"""Try ``primary_url`` first, then walk ``fallback_urls``.- Returns the first manifest that fetches and validates, or None when- every URL fails. Skips fallback URLs identical to the primary so an- operator who configured the catalog URL to point at the raw GitHub- copy doesn't double-fetch.+ Returns the first manifest that fetches and validates, or None when every URL fails. Skips+ fallback URLs identical to the primary so an operator who configured the catalog URL to point at+ the raw GitHub copy doesn't double-fetch."""data = _fetch_manifest(primary_url, timeout)if data is not None:@@ -289,8 +256,8 @@ def _spawn_catalog_swr_refresh(url: str) -> None:def get_catalog(*, force_refresh: bool = False) -> dict[str, Any]:"""Return the parsed model catalog manifest, or an empty dict on failure.- Callers should treat a missing provider/model as "use the in-repo fallback"- — never raise from this function so the CLI keeps working offline.+ Callers should treat a missing provider/model as "use the in-repo fallback" — never raise from+ this function so the CLI keeps working offline."""global _catalog_cache, _catalog_cache_source_mtime@@ -359,11 +326,9 @@ def refresh_interval_seconds() -> float:def refresh_catalogs() -> bool:"""Force-refresh every remote model catalog the picker reads from.- Fetches the curated manifest, the OpenRouter live list (tool-support /- free-pricing filter) and the Nous Portal recommendations, writing each- to its disk cache so the next ``/model`` open in ANY process on this- machine sees the new lists. Blocking; run it off the event loop.- Returns True when the manifest refresh succeeded.+ Fetches the curated manifest, the OpenRouter live list (tool-support / free-pricing filter) and+ the Nous Portal recommendations, writing each to its disk cache so the next ``/model`` open in+ ANY process on this machine sees the new lists. Blocking; run it off the event loop."""if not _load_catalog_config()["enabled"]:return False@@ -411,11 +376,7 @@ def _get_provider_block(provider: str) -> dict[str, Any] | None:def get_curated_openrouter_models() -> list[tuple[str, str]] | None:- """Return OpenRouter's curated ``[(id, description), ...]`` from the manifest.-- Returns ``None`` when the manifest is unavailable, so callers can fall- back to their hardcoded list.- """+ """Return OpenRouter's curated ``[(id, description), ...]`` from the manifest."""block = _get_provider_block("openrouter")if not block:return None@@ -430,10 +391,7 @@ def get_curated_openrouter_models() -> list[tuple[str, str]] | None:def get_curated_nous_models() -> list[str] | None:- """Return Nous Portal's curated list of model ids from the manifest.-- Returns ``None`` when the manifest is unavailable.- """+ """Return Nous Portal's curated list of model ids from the manifest."""block = _get_provider_block("nous")if not block:return None@@ -460,14 +418,8 @@ def _default_model_from_block(block: dict[str, Any] | None) -> str | None:def get_default_model_from_cache(provider: str) -> str | None:"""Return the catalog's labeled default model for ``provider`` — cache only.- The manifest marks exactly one model entry per provider with- ``"default": true``; that entry is the model Hermes silently lands on when- the user never picked one. This accessor reads ONLY the in-process copy or- the disk cache — it NEVER triggers a network fetch, so it is safe on hot- resolution paths (agent build, gateway session setup) that must stay- network-free. The cache is kept fresh by the picker/`hermes update` paths;- when no cached manifest exists (fresh install, offline), returns None and- the caller falls back to the in-repo constant.+ The manifest marks exactly one model entry per provider with ``"default": true``; that entry is+ the model Hermes silently lands on when the user never picked one."""if _catalog_cache is not None:block = _catalog_cache.get("providers", {}).get(provider)@@ -484,18 +436,13 @@ def get_default_model_from_cache(provider: str) -> str | None:def seed_cache_from_checkout(project_root: "Path | str") -> bool:"""Overwrite the disk cache with the catalog shipped in a local checkout.- ``hermes update`` pulls the latest repo, so the freshly-pulled- ``website/static/api/model-catalog.json`` IS the newest catalog — no- network round-trip needed. Copying it straight over the disk cache keeps- the model picker current even when the remote manifest fetch is bot-gated+ ``hermes update`` pulls the latest repo, so the freshly-pulled ``website/static/api/model-+ catalog.json`` IS the newest catalog — no network round-trip needed. Copying it straight over+ the disk cache keeps the model picker current even when the remote manifest fetch is bot-gatedor the Portal hiccups.- Reads the shipped manifest, validates it against the schema, and writes it- to ``~/.hermes/cache/model_catalog.json`` via the same atomic writer the- network path uses. Returns ``True`` on success, ``False`` if the file is- missing, malformed, or fails validation (caller should treat a ``False``- as non-fatal — the network fetch path still applies on the next picker- open).+ Reads the shipped manifest, validates it against the schema, and writes it to+ ``~/.hermes/cache/model_catalog.json`` via the same atomic writer the network path uses."""src = Path(project_root) / "website" / "static" / "api" / "model-catalog.json"try:diff --git a/hermes_cli/model_cost_guard.py b/hermes_cli/model_cost_guard.pyindex 1ed8835b5b6..16d4f0fd519 100644--- a/hermes_cli/model_cost_guard.py+++ b/hermes_cli/model_cost_guard.py@@ -37,9 +37,7 @@ def _to_decimal(value: object) -> Optional[Decimal]:def _format_money(value: Optional[Decimal]) -> str:- if value is None:- return "unknown"- return f"${value:.2f}/M"+ return "unknown" if value is None else f"${value:.2f}/M"def _pricing_from_model_info(@@ -56,9 +54,7 @@ def _pricing_from_model_info(def _known_models_dev_provider(provider: Optional[str]) -> Optional[str]:normalized = (provider or "").strip().lower()- if not normalized:- return None- return PROVIDER_TO_MODELS_DEV.get(normalized)+ return PROVIDER_TO_MODELS_DEV.get(normalized) if normalized else Nonedef _can_trust_model_info_pricing(@@ -98,8 +94,8 @@ def expensive_model_warning() -> Optional[ExpensiveModelWarning]:"""Return a warning payload when known pricing exceeds safety thresholds.- The guard only triggers when pricing is known. Callers should use this after- model resolution so aliases and provider-specific model IDs have settled.+ The guard only triggers when pricing is known. Callers should use this after model resolution so+ aliases and provider-specific model IDs have settled."""model = (model_name or "").strip()if not model:@@ -112,11 +108,10 @@ def expensive_model_warning(if _can_trust_model_info_pricing(provider, model_info):input_cost, output_cost, source = _pricing_from_model_info(model_info)- if (- input_cost is None- and output_cost is None- and _known_models_dev_provider(provider)- ):+ def _unpriced() -> bool:+ return input_cost is None and output_cost is None++ if _unpriced() and _known_models_dev_provider(provider):try:from agent.models_dev import get_model_info@@ -126,11 +121,7 @@ def expensive_model_warning(except Exception:pass- if (- input_cost is None- and output_cost is None- and _can_trust_pricing_lookup(model, provider=provider, base_url=base_url)- ):+ if _unpriced() and _can_trust_pricing_lookup(model, provider=provider, base_url=base_url):try:from agent.usage_pricing import get_pricing_entry@@ -149,12 +140,8 @@ def expensive_model_warning(is_known_gpt55_pro_confusion = model.lower() == GPT55_PRO_OPENROUTER_ID- over_input = (- input_cost is not None and input_cost > INPUT_COST_WARNING_THRESHOLD- )- over_output = (- output_cost is not None and output_cost > OUTPUT_COST_WARNING_THRESHOLD- )+ over_input = input_cost is not None and input_cost > INPUT_COST_WARNING_THRESHOLD+ over_output = output_cost is not None and output_cost > OUTPUT_COST_WARNING_THRESHOLDif not over_input and not over_output and not is_known_gpt55_pro_confusion:return None@@ -164,10 +151,7 @@ def expensive_model_warning(f"{model} has known pricing above Hermes' safety threshold.",f"Input tokens: {_format_money(input_cost)}",f"Output tokens: {_format_money(output_cost)}",- (- "Threshold: more than $20/M input tokens or more than "- "$100/M output tokens."- ),+ "Threshold: more than $20/M input tokens or more than $100/M output tokens.",]if source:lines.append(f"Pricing source: {source}.")diff --git a/hermes_cli/model_data_policy_guard.py b/hermes_cli/model_data_policy_guard.pyindex 6cb86991dc3..68c04d3e98f 100644--- a/hermes_cli/model_data_policy_guard.py+++ b/hermes_cli/model_data_policy_guard.py@@ -1,22 +1,11 @@"""Data-policy confirmation helpers for model selection surfaces.-Some inference tiers are cheap *because* the vendor trains future models on your-prompts and completions. Selecting one for the low price without realising the-data trade-off is a real footgun. This guard mirrors-``hermes_cli.model_cost_guard`` — it returns a warning payload that the CLI and-web model-selection flows surface as an explicit confirm step.--Why a static table (not a ProviderProfile hook): the guard runs inside core-selection code (``auth.py`` / ``web_server.py``), which never calls into the-active provider profile for a selection-time warning. Keeping the rule set here-also means it renders regardless of which provider plugin happens to be loaded,-and it stays testable without importing arbitrary third-party plugin code into-the selection path.--The status is NOT machine-readable anywhere today: neither models.dev nor the-Meta ``/v1/models`` payload exposes a training/retention flag (verified-2026-08-07). The only reliable signals are the vendor-documented model id and-its anomalously low pricing, so the rule keys on the id.+Some inference tiers are cheap *because* the vendor trains future models on your prompts and+completions. Selecting one for the low price without realising the data trade-off is a real footgun.++Why a static table (not a ProviderProfile hook): the guard runs inside core selection code+(``auth.py`` / ``web_server.py``), which never calls into the active provider profile for a+selection-time warning."""from __future__ import annotations@@ -84,9 +73,9 @@ def data_training_warning() -> Optional[DataTrainingWarning]:"""Return a warning payload when *model_name* selects a data-training tier.- Returns ``None`` when no rule matches (the common case). Callers should run- this after model resolution so aliases / provider-specific ids have settled,- and surface ``.message`` as a confirm prompt.+ Returns ``None`` when no rule matches (the common case). Callers should run this after model+ resolution so aliases / provider-specific ids have settled, and surface ``.message`` as a+ confirm prompt."""model = (model_name or "").strip()if not model:diff --git a/hermes_cli/model_normalize.py b/hermes_cli/model_normalize.pyindex 21d10c5e6fb..0838cb207b5 100644--- a/hermes_cli/model_normalize.py+++ b/hermes_cli/model_normalize.py@@ -1,33 +1,4 @@-"""Per-provider model name normalization.--Different LLM providers expect model identifiers in different formats:--- **Aggregators** (OpenRouter, Nous, AI Gateway, Kilo Code) need- ``vendor/model`` slugs like ``anthropic/claude-sonnet-4.6``.-- **Anthropic** native API expects bare names with dots replaced by- hyphens: ``claude-sonnet-4-6``.-- **Copilot** expects bare names *with* dots preserved:- ``claude-sonnet-4.6``.-- **OpenCode Zen** preserves dots for GPT/GLM/Gemini/Kimi/MiniMax-style- model IDs, but Claude still uses hyphenated native names like- ``claude-sonnet-4-6``.-- **OpenCode Go** preserves dots in model names: ``minimax-m2.7``.-- **DeepSeek** accepts only the first-class V-series IDs- (``deepseek-v4-pro``, ``deepseek-v4-flash``, and any future- ``deepseek-v<N>-*``). The legacy aliases ``deepseek-chat`` and- ``deepseek-reasoner`` were retired on 2026-07-24 and are remapped to- ``deepseek-v4-flash`` (official non-thinking / thinking shims). Older- Hermes revisions folded every non-reasoner input into- ``deepseek-chat``, which on aggregators routes to V3 — so a user- picking V4 Pro was silently downgraded.-- **Custom** and remaining providers pass the name through as-is.--This module centralises that translation so callers can simply write::-- api_model = normalize_model_for_provider(user_input, provider)--Inspired by Clawdbot's ``normalizeAnthropicModelId`` pattern.-"""+"""Per-provider model name normalization."""from __future__ import annotations@@ -172,22 +143,9 @@ _DEEPSEEK_V_SERIES_RE = re.compile(r"^deepseek-v\d+([-.].+)?$")def _normalize_for_deepseek(model_name: str) -> str:"""Map a model input to a DeepSeek-accepted identifier.- Rules:- - Retired aliases ``deepseek-chat`` / ``deepseek-reasoner`` (cut off- 2026-07-24) -> ``deepseek-v4-flash``.- - Already a known canonical (``deepseek-v4-pro``/``deepseek-v4-flash``)- -> pass through.- - Matches the V-series pattern ``deepseek-v<digit>...`` -> pass through- (covers future ``deepseek-v5-*`` and dated variants without a release).- - Contains a reasoner keyword (r1, think, reasoning, cot, reasoner)- -> ``deepseek-v4-flash``.- - Everything else -> ``deepseek-v4-flash``.-- Args:- model_name: The bare model name (vendor prefix already stripped).-- Returns:- A DeepSeek-accepted model identifier.+ Retired aliases ``deepseek-chat``/``deepseek-reasoner`` and known canonicals map as expected;+ anything matching ``deepseek-v<digit>...`` passes through so future V-series ids work without a+ release; reasoner keywords and everything else fall back to ``deepseek-v4-flash``."""bare = _strip_vendor_prefix(model_name).lower()@@ -216,28 +174,14 @@ def _normalize_for_deepseek(model_name: str) -> str:# ---------------------------------------------------------------------------def _strip_vendor_prefix(model_name: str) -> str:- """Remove a ``vendor/`` prefix if present.-- Examples::-- >>> _strip_vendor_prefix("anthropic/claude-sonnet-4.6")- 'claude-sonnet-4.6'- >>> _strip_vendor_prefix("claude-sonnet-4.6")- 'claude-sonnet-4.6'- >>> _strip_vendor_prefix("meta-llama/llama-4-scout")- 'llama-4-scout'- """+ """Remove a ``vendor/`` prefix if present."""if "/" in model_name:return model_name.split("/", 1)[1]return model_namedef _dots_to_hyphens(model_name: str) -> str:- """Replace dots with hyphens in a model name.-- Anthropic's native API uses hyphens where marketing names use dots:- ``claude-sonnet-4.6`` -> ``claude-sonnet-4-6``.- """+ """Replace dots with hyphens in a model name."""return model_name.replace(".", "-")@@ -257,17 +201,10 @@ def _normalize_provider_alias(provider_name: str) -> str:def _strip_matching_provider_prefix(model_name: str, target_provider: str) -> str:"""Strip ``provider/`` only when the prefix matches the target provider.- This prevents arbitrary slash-bearing model IDs from being mangled on- native providers while still repairing manual config values like- ``zai/glm-5.1`` for the ``zai`` provider.-- ``custom`` is a generic bucket for arbitrary user-defined endpoints, not- a vendor identity like ``zai``/``gemini``/``xai``. An alias that merely- *resolves to* ``custom`` (e.g. ``ollama``, via ``_PROVIDER_ALIASES``)- does not mean a ``ollama/`` prefix is redundant -- it may be the actual- routing prefix a proxy in front of the custom endpoint (e.g. LiteLLM)- requires, as in ``ollama/glm-5.2``. Only a literal ``custom/`` prefix --- the bucket's own name -- is treated as redundant here.+ Prevents arbitrary slash-bearing ids from being mangled on native providers while still+ repairing config values like ``zai/glm-5.1`` for ``zai``. ``custom`` is a bucket, not a vendor:+ an alias that merely resolves to it (e.g. ``ollama``) may be a real routing prefix required by a+ proxy such as LiteLLM, so only a literal ``custom/`` prefix is treated as redundant."""if "/" not in model_name:return model_name@@ -289,31 +226,7 @@ def _strip_matching_provider_prefix(model_name: str, target_provider: str) -> stdef detect_vendor(model_name: str) -> Optional[str]:- """Detect the vendor slug from a bare model name.-- Uses the first hyphen-delimited token of the model name to look up- the corresponding vendor in ``_VENDOR_PREFIXES``. Also handles- case-insensitive matching and special patterns.-- Args:- model_name: A model name, optionally already including a- ``vendor/`` prefix. If a prefix is present it is used- directly.-- Returns:- The vendor slug (e.g. ``"anthropic"``, ``"openai"``) or ``None``- if no vendor can be confidently detected.-- Examples::-- >>> detect_vendor("claude-sonnet-4.6")- 'anthropic'- >>> detect_vendor("gpt-5.4-mini")- 'openai'- >>> detect_vendor("anthropic/claude-sonnet-4.6")- 'anthropic'- >>> detect_vendor("my-custom-model")- """+ """Detect the vendor slug from a bare model name."""name = model_name.strip()if not name:return None@@ -341,19 +254,8 @@ def detect_vendor(model_name: str) -> Optional[str]:def _prepend_vendor(model_name: str) -> str:"""Prepend the detected ``vendor/`` prefix if missing.- Used for aggregator providers that require ``vendor/model`` format.- If the name already contains a ``/``, it is returned as-is.- If no vendor can be detected, the name is returned unchanged- (aggregators may still accept it or return an error).-- Examples::-- >>> _prepend_vendor("claude-sonnet-4.6")- 'anthropic/claude-sonnet-4.6'- >>> _prepend_vendor("anthropic/claude-sonnet-4.6")- 'anthropic/claude-sonnet-4.6'- >>> _prepend_vendor("my-custom-thing")- 'my-custom-thing'+ For aggregators that require ``vendor/model``. Names already containing ``/`` or with no+ detectable vendor are returned unchanged (the aggregator may still accept them)."""if "/" in model_name:return model_name@@ -367,18 +269,8 @@ def _prepend_vendor(model_name: str) -> str:def _repair_prefix_from_catalogue(model_name: str, provider: str) -> str:"""Restore a dropped ``vendor/`` prefix using the provider's catalogue.- Unlike :func:`_prepend_vendor`, this never guesses from the model's name- shape — it only repairs a bare id that matches **exactly one** curated- entry for this provider modulo the prefix. That keeps self-hosted models- behind the same provider id (local NIM containers, proxies) untouched,- since they aren't in the catalogue.-- Examples::-- >>> _repair_prefix_from_catalogue("nemotron-3-ultra-550b-a55b", "nvidia")- 'nvidia/nemotron-3-ultra-550b-a55b'- >>> _repair_prefix_from_catalogue("my-local-nim", "nvidia")- 'my-local-nim'+ Unlike :func:`_prepend_vendor`, this never guesses from the model's name shape — it only repairs+ a bare id that matches **exactly one** curated entry for this provider modulo the prefix."""if "/" in model_name:return model_name@@ -404,11 +296,10 @@ def _repair_prefix_from_catalogue(model_name: str, provider: str) -> str:def suggest_prefixed_model_id(provider: str, model_name: str) -> Optional[str]:"""Return the prefixed catalogue id for a bare *model_name*, if unambiguous.- The diagnostic counterpart to :func:`_repair_prefix_from_catalogue`: used- to explain a provider's content-free 404 when the configured id lost its- ``vendor/`` prefix. Returns ``None`` when the name already has a prefix,- the provider has no curated catalogue, or nothing matches — so callers can- stay silent rather than guess (#78796).+ Diagnostic counterpart to :func:`_repair_prefix_from_catalogue`, used to explain a provider's+ content-free 404 when the configured id lost its ``vendor/`` prefix. Returns ``None`` when the+ name already has a prefix, the provider has no catalogue, or nothing matches — so callers stay+ silent rather than guess."""name = (model_name or "").strip()if not name or "/" in name:@@ -428,64 +319,9 @@ def suggest_prefixed_model_id(provider: str, model_name: str) -> Optional[str]:def normalize_model_for_provider(model_input: str, target_provider: str) -> str:"""Translate a model name into the format the target provider's API expects.- This is the primary entry point for model name normalisation. It- accepts any user-facing model identifier and transforms it for the- specific provider that will receive the API call.-- Args:- model_input: The model name as provided by the user or config.- Can be bare (``"claude-sonnet-4.6"``), vendor-prefixed- (``"anthropic/claude-sonnet-4.6"``), or already in native- format (``"claude-sonnet-4-6"``).- target_provider: The canonical Hermes provider id, e.g.- ``"openrouter"``, ``"anthropic"``, ``"copilot"``,- ``"deepseek"``, ``"custom"``. Should already be normalised- via ``hermes_cli.models.normalize_provider()``.-- Returns:- The model identifier string that the target provider's API- expects.-- Raises:- No exceptions -- always returns a best-effort string.-- Examples::-- >>> normalize_model_for_provider("claude-sonnet-4.6", "openrouter")- 'anthropic/claude-sonnet-4.6'-- >>> normalize_model_for_provider("anthropic/claude-sonnet-4.6", "anthropic")- 'claude-sonnet-4-6'-- >>> normalize_model_for_provider("anthropic/claude-sonnet-4.6", "copilot")- 'claude-sonnet-4.6'-- >>> normalize_model_for_provider("openai/gpt-5.4", "copilot")- 'gpt-5.4'-- >>> normalize_model_for_provider("claude-sonnet-4.6", "opencode-zen")- 'claude-sonnet-4-6'-- >>> normalize_model_for_provider("minimax-m2.5-free", "opencode-zen")- 'minimax-m2.5-free'-- >>> normalize_model_for_provider("deepseek-v3", "deepseek")- 'deepseek-v4-flash'-- >>> normalize_model_for_provider("deepseek-r1", "deepseek")- 'deepseek-v4-flash'-- >>> normalize_model_for_provider("deepseek-reasoner", "deepseek")- 'deepseek-v4-flash'-- >>> normalize_model_for_provider("my-model", "custom")- 'my-model'-- >>> normalize_model_for_provider("claude-sonnet-4.6", "zai")- 'claude-sonnet-4.6'-- >>> normalize_model_for_provider("MiMo-V2.5-Pro", "xiaomi")- 'mimo-v2.5-pro'+ Primary entry point for model-name normalisation. Accepts bare, vendor-prefixed or native ids;+ ``target_provider`` should already be normalised via ``normalize_provider()``. Never raises —+ always returns a best-effort string."""name = (model_input or "").strip()if not name:diff --git a/hermes_cli/model_search.py b/hermes_cli/model_search.pyindex 23d3bae14bf..74bb8daa278 100644--- a/hermes_cli/model_search.py+++ b/hermes_cli/model_search.py@@ -1,12 +1,4 @@-"""Picker-only search aliases for model ids.--Wire IDs stay unchanged. Some providers report short or brand-less ids-(Kimi Coding's flagship is literally ``k3``) that users still search for by-the familiar ``kimi-…`` naming of sibling models.--Keep in sync with ``ui-tui/src/lib/model-search-text.ts`` and-``web/src/lib/model-search-text.ts``.-"""+"""Picker-only search aliases for model ids."""from __future__ import annotations@@ -30,11 +22,7 @@ _MODEL_ALIAS_CANONICAL: dict[str, str] = {def model_alias_canonical(model: str) -> str:- """Return the canonical public slug for a bare wire-id alias.-- Identity for ids with no alias entry. Lowercases the input so callers- can use the result directly as a dedup key.- """+ """Return the canonical public slug for a bare wire-id alias."""key = (model or "").strip().lower()return _MODEL_ALIAS_CANONICAL.get(key, key)diff --git a/hermes_cli/model_selection_guards.py b/hermes_cli/model_selection_guards.pyindex 0d886497cb5..8ce700f096f 100644--- a/hermes_cli/model_selection_guards.py+++ b/hermes_cli/model_selection_guards.py@@ -1,21 +1,7 @@"""Unified selection-time guard registry for model switching surfaces.-Hermes has multiple model-selection surfaces (CLI picker, TUI, dashboard,-gateway ``/model``, Telegram/Discord pickers, TUI-gateway RPC). Each of them-previously imported ``model_cost_guard.expensive_model_warning`` directly, so-every new guard class (e.g. the data-training-tier guard) had to be wired into-every surface by hand — and inevitably missed some.--This module is the single evaluation point: ``selection_warnings()`` runs every-registered guard and returns the warnings that fired. Surfaces render the-result with their own confirm UX (stdin prompt, modal, inline keyboard,-``confirm_required`` JSON) — that half stays per-surface; the *evaluation* half-lives here. Adding a guard to ``_GUARDS`` makes it appear on every surface at-once.--Guard modules (``model_cost_guard``, ``model_data_policy_guard``) keep their-public APIs — existing tests and mock patch points remain valid; this module-only aggregates them.+Guard modules (``model_cost_guard``, ``model_data_policy_guard``) keep their public APIs — existing+tests and mock patch points remain valid; this module only aggregates them."""from __future__ import annotations@@ -37,6 +23,23 @@ class SelectionWarning:message: str+def _wrap(kind: str, title: str, warning, model_name: str, provider: Optional[str]):+ """Lift a raw guard payload into a :class:`SelectionWarning` (None passes through).++ Duck-typed access: tests (and future guard payloads) may supply objects carrying only+ ``.message``.+ """+ if warning is None:+ return None+ return SelectionWarning(+ kind=kind,+ title=title,+ model=getattr(warning, "model", model_name),+ provider=getattr(warning, "provider", provider or ""),+ message=warning.message,+ )++def _cost_guard(model_name: str,provider: Optional[str],@@ -47,23 +50,9 @@ def _cost_guard(from hermes_cli.model_cost_guard import expensive_model_warningwarning = expensive_model_warning(- model_name,- provider=provider,- base_url=base_url,- api_key=api_key,- model_info=model_info,- )- if warning is None:- return None- # Duck-typed access: tests (and future guard payloads) may supply objects- # carrying only ``.message``.- return SelectionWarning(- kind="cost",- title="Expensive Model Warning",- model=getattr(warning, "model", model_name),- provider=getattr(warning, "provider", provider or ""),- message=warning.message,+ model_name, provider=provider, base_url=base_url, api_key=api_key, model_info=model_info)+ return _wrap("cost", "Expensive Model Warning", warning, model_name, provider)def _data_policy_guard(@@ -75,28 +64,13 @@ def _data_policy_guard() -> Optional[SelectionWarning]:from hermes_cli.model_data_policy_guard import data_training_warning- warning = data_training_warning(- model_name,- provider=provider,- base_url=base_url,- )- if warning is None:- return None- return SelectionWarning(- kind="data_policy",- title="Data-Training Tier Warning",- model=getattr(warning, "model", model_name),- provider=getattr(warning, "provider", provider or ""),- message=warning.message,- )+ warning = data_training_warning(model_name, provider=provider, base_url=base_url)+ return _wrap("data_policy", "Data-Training Tier Warning", warning, model_name, provider)# Registry, evaluated in order. Add new guard classes here — never at the# individual surfaces.-_GUARDS = (- _cost_guard,- _data_policy_guard,-)+_GUARDS = (_cost_guard, _data_policy_guard)def selection_warnings(@@ -110,15 +84,11 @@ def selection_warnings() -> List[SelectionWarning]:"""Run every registered selection guard and return the warnings that fired.- Returns an empty list in the common case (no guard fired). Callers should- run this after model resolution so aliases / provider-specific ids have- settled, then surface the messages as a confirm step. ``include_kinds``- optionally restricts which guard kinds run (e.g. auth.py's picker only runs- the cost guard when a provider is known, but always runs the data-policy- guard).+ Returns an empty list in the common case (no guard fired). Callers should run this after model+ resolution so aliases / provider-specific ids have settled, then surface the messages as a+ confirm step. ``include_kinds`` optionally restricts which guard kinds run (e.g.- A misbehaving guard must never break model selection: individual guard- exceptions are swallowed.+ A misbehaving guard must never break model selection: individual guard exceptions are swallowed."""wanted = set(include_kinds) if include_kinds is not None else Noneresults: List[SelectionWarning] = []@@ -127,20 +97,16 @@ def selection_warnings(warning = guard(model_name, provider, base_url, api_key, model_info)except Exception:continue- if warning is None:- continue- if wanted is not None and warning.kind not in wanted:- continue- results.append(warning)+ if warning is not None and (wanted is None or warning.kind in wanted):+ results.append(warning)return resultsdef combined_message(warnings: List[SelectionWarning]) -> str:"""Join multiple warnings into one confirm-prompt body.- Surfaces that show a single confirm dialog use this when more than one- guard fires (rare) — one prompt showing both blocks beats two sequential- prompts.+ Used by surfaces with a single confirm dialog when more than one guard fires (rare) — one+ prompt showing both blocks beats two sequential prompts."""return "\n\n".join(w.message for w in warnings)@@ -155,18 +121,12 @@ def combined_selection_warning() -> Optional[SelectionWarning]:"""Drop-in replacement for ``expensive_model_warning`` call sites.- Returns ``None`` when no guard fired, a single :class:`SelectionWarning`- when exactly one fired, or a merged warning (``kind="multiple"``) whose- ``message`` stacks every fired guard. Surfaces that render one confirm- dialog with ``warning.message`` can switch to this without reshaping their- control flow.+ Returns ``None`` when no guard fired, the single :class:`SelectionWarning` when one fired,+ or a merged ``kind="multiple"`` warning stacking every message — so surfaces rendering one+ confirm dialog from ``warning.message`` can switch without reshaping control flow."""warnings = selection_warnings(- model_name,- provider=provider,- base_url=base_url,- api_key=api_key,- model_info=model_info,+ model_name, provider=provider, base_url=base_url, api_key=api_key, model_info=model_info)if not warnings:return Nonediff --git a/hermes_cli/models.py b/hermes_cli/models.pyindex fb8371983cd..99d7b023fbb 100644--- a/hermes_cli/models.py+++ b/hermes_cli/models.py@@ -1,9 +1,4 @@-"""-Canonical model catalogs and lightweight validation helpers.--Add, remove, or reorder entries here — both `hermes setup` and-`hermes` provider-selection will pick up the change automatically.-"""+"""Canonical model catalogs and lightweight validation helpers."""from __future__ import annotations@@ -49,11 +44,10 @@ def _urlopen_model_catalog_request(req: urllib.request.Request, *, timeout: floadef _custom_provider_ssl_context(base_url: str):"""Build an ``ssl.SSLContext`` from a custom provider's TLS settings.- Mirrors the httpx/requests TLS resolution so the urllib ``/models``- discovery probe honors a provider's ``ssl_ca_cert`` / ``ssl_verify``- instead of falling back to the process-wide ``SSL_CERT_FILE`` / certifi- bundle. Returns None when no per-provider TLS override applies, so the- caller keeps urllib's default policy for public/unconfigured endpoints.+ Mirrors the httpx/requests TLS resolution so the urllib ``/models`` probe honors a+ provider's ``ssl_ca_cert`` / ``ssl_verify`` instead of the process-wide+ ``SSL_CERT_FILE``/certifi bundle. Returns None when no per-provider override applies, so the+ caller keeps urllib's default policy."""if not base_url:return None@@ -180,9 +174,9 @@ _ai_gateway_catalog_cache: list[tuple[str, str]] | None = Nonedef _codex_curated_models() -> list[str]:"""Derive the openai-codex curated list from codex_models.py.- Single source of truth: DEFAULT_CODEX_MODELS + forward-compat synthesis.- This keeps the gateway /model picker in sync with the CLI `hermes model`- flow without maintaining a separate static list.+ Single source of truth: DEFAULT_CODEX_MODELS + forward-compat synthesis. This keeps the gateway+ /model picker in sync with the CLI `hermes model` flow without maintaining a separate static+ list."""from hermes_cli.codex_models import DEFAULT_CODEX_MODELS, _finalize_codex_modelsreturn _finalize_codex_models(list(DEFAULT_CODEX_MODELS))@@ -245,8 +239,8 @@ def _xai_finalize_catalog(ids: list[str]) -> list[str]:def _xai_curated_models() -> list[str]:"""Offline curated floor for xAI / xAI OAuth pickers.- Reads $HERMES_HOME/models_dev_cache.json directly (no network). Falls- back to ``_XAI_STATIC_FALLBACK`` when the cache is empty or unreadable.+ Reads $HERMES_HOME/models_dev_cache.json directly (no network). Falls back to+ ``_XAI_STATIC_FALLBACK`` when the cache is empty or unreadable."""try:from agent.models_dev import _load_disk_cache@@ -835,37 +829,6 @@ def _is_model_free(model_id: str, pricing: dict[str, dict[str, str]]) -> bool:return False-# ----------------------------------------------------------------------------# Nous Portal account tier detection-# ----------------------------------------------------------------------------def is_nous_free_tier(account_info: dict[str, Any]) -> bool:- """Return True if the account info indicates a free (unpaid) tier.-- Prefer the Portal's explicit ``paid_service_access.allowed`` entitlement- decision. Legacy payloads fall back to ``subscription.monthly_charge == 0``.- Returns False when both signals are missing or unparseable.- """- paid_access = account_info.get("paid_service_access")- if isinstance(paid_access, dict):- allowed = paid_access.get("allowed")- if isinstance(allowed, bool):- return not allowed- paid = paid_access.get("paid_access")- if isinstance(paid, bool):- return not paid-- sub = account_info.get("subscription")- if not isinstance(sub, dict):- return False- charge = sub.get("monthly_charge")- if charge is None:- return False- try:- return float(charge) == 0- except (TypeError, ValueError):- return False--def partition_nous_models_by_tier(model_ids: list[str],pricing: dict[str, dict[str, str]],@@ -873,10 +836,8 @@ def partition_nous_models_by_tier() -> tuple[list[str], list[str]]:"""Split Nous models into (selectable, unavailable) based on user tier.- For paid-tier users: all models are selectable, none unavailable.-- For free-tier users: only free models are selectable; paid models- are returned as unavailable (shown grayed out in the menu).+ For free-tier users: only free models are selectable; paid models are returned as unavailable+ (shown grayed out in the menu)."""if not free_tier:return (model_ids, [])@@ -903,26 +864,8 @@ def union_with_portal_free_recommendations() -> tuple[list[str], dict[str, dict[str, str]]]:"""Augment curated list + pricing with the Portal's ``freeRecommendedModels``.- The Portal's ``/api/nous/recommended-models`` endpoint advertises which- models are free *right now* — independent of what the in-repo- ``_PROVIDER_MODELS["nous"]`` list happens to contain or whether the- docs-hosted catalog manifest has been rebuilt since the last release.-- For free-tier users this is the source of truth: any model the Portal- flags as free should be selectable, even if the user is running an- older Hermes that doesn't ship that model in its hardcoded curated- list. This function returns an augmented ``(model_ids, pricing)``- pair where:-- * Portal free recommendations missing from ``curated_ids`` are- appended after the curated list (so the in-repo curated models- show first and Portal-only picks follow).- * ``pricing`` gets a synthetic ``{"prompt": "0", "completion": "0"}``- entry for any free recommendation missing from the live pricing- map, so :func:`partition_nous_models_by_tier` keeps it.-- Failures (network, parse, missing field) are silent and degrade to- returning the inputs unchanged.+ * Portal free recommendations missing from ``curated_ids`` are appended after the curated list+ (so the in-repo curated models show first and Portal-only picks follow)."""try:payload = fetch_nous_recommended_models(@@ -969,32 +912,12 @@ def union_with_portal_paid_recommendations() -> tuple[list[str], dict[str, dict[str, str]]]:"""Augment curated list with the Portal's ``paidRecommendedModels``.- Mirror of :func:`union_with_portal_free_recommendations` for paid-tier- users. The Portal's ``/api/nous/recommended-models`` endpoint advertises- which paid models are blessed *right now* — independent of what the- in-repo ``_PROVIDER_MODELS["nous"]`` list happens to contain or whether- the docs-hosted catalog manifest has been rebuilt since the last release.-- For paid-tier users this lets newly-launched paid models surface in the- picker even if the user is running an older Hermes that doesn't ship- them in its hardcoded curated list. This function returns an augmented- ``(model_ids, pricing)`` pair where:-- * Portal paid recommendations missing from ``curated_ids`` are- appended after the curated list (so the in-repo curated models- show first and Portal-only picks follow).- * ``pricing`` is left untouched — we deliberately do NOT synthesize- pricing entries for paid models. Live pricing is fetched separately- via :func:`get_pricing_for_provider`; if the live endpoint hasn't- published pricing yet, the picker shows a blank price column rather- than fabricating numbers. (The free helper synthesizes ``$0`` so- :func:`partition_nous_models_by_tier` keeps free models selectable;- no equivalent gating applies on the paid side, so synthesis would- only mislead the user.)-- Failures (network, parse, missing field) are silent and degrade to- returning the inputs unchanged — never block the picker on a- Portal-side hiccup.+ * Portal paid recommendations missing from ``curated_ids`` are appended after the curated list+ (so the in-repo curated models show first and Portal-only picks follow). * ``pricing`` is left+ untouched — we deliberately do NOT synthesize pricing entries for paid models.++ Failures (network, parse, missing field) are silent and degrade to returning the inputs+ unchanged — never block the picker on a Portal-side hiccup."""try:payload = fetch_nous_recommended_models(@@ -1037,12 +960,11 @@ _free_tier_cache: tuple[bool, float] | None = None # (result, timestamp)def check_nous_free_tier(*, force_fresh: bool = False) -> bool:"""Check if the current Nous Portal user is on a free (unpaid) tier.- Results are cached for ``_FREE_TIER_CACHE_TTL`` seconds to avoid- hitting the Portal API on every call. The cache is short-lived so- that an account upgrade is reflected within a few minutes.+ Results are cached for ``_FREE_TIER_CACHE_TTL`` seconds to avoid hitting the Portal API on every+ call. The cache is short-lived so that an account upgrade is reflected within a few minutes.- Returns True only when entitlement is known to be free. Unknown/error- states return False so this compatibility wrapper does not block users.+ Returns True only when entitlement is known to be free. Unknown/error states return False so+ this compatibility wrapper does not block users."""global _free_tier_cachenow = time.monotonic()@@ -1098,8 +1020,7 @@ def _nous_recommended_disk_path() -> "Path":def _read_nous_recommended_disk(base: str) -> dict[str, Any] | None:"""Return the last-known-good payload for ``base`` from disk, or None.- The disk file is a JSON object keyed by portal base URL so staging and- prod don't collide:+ The disk file is a JSON object keyed by portal base URL so staging and prod don't collide:``{"<base>": {"data": {...}, "ts": <epoch_seconds>}}``."""try:@@ -1119,8 +1040,8 @@ def _read_nous_recommended_disk(base: str) -> dict[str, Any] | None:def _write_nous_recommended_disk(base: str, data: dict[str, Any]) -> None:"""Persist ``data`` as the last-known-good payload for ``base``.- Merges into any existing per-base map, then writes atomically. Failures- are non-fatal (logged at debug) — the in-process cache still works.+ Merges into any existing per-base map, then writes atomically. Failures are non-fatal (logged at+ debug) — the in-process cache still works."""if not data:return@@ -1155,21 +1076,13 @@ def fetch_nous_recommended_models() -> dict[str, Any]:"""Fetch the Nous Portal's curated recommended-models payload.- Hits ``<portal>/api/nous/recommended-models``. The endpoint is public —- no auth is required. Results are cached per portal URL for- ``_NOUS_RECOMMENDED_CACHE_TTL`` seconds in process; pass+ Hits ``<portal>/api/nous/recommended-models``. The endpoint is public — no auth is required.+ Results are cached per portal URL for ``_NOUS_RECOMMENDED_CACHE_TTL`` seconds in process; pass``force_refresh=True`` to bypass the in-process cache.A successful live fetch is also persisted to a per-base disk cache- (``$HERMES_HOME/cache/nous_recommended_cache.json``) as last-known-good.- When the live fetch fails (network, parse, non-2xx) and the in-process- cache is empty, the disk copy is returned instead of ``{}`` — so a- transient Portal hiccup no longer silently drops the free/paid model- recommendations from the picker. Self-heals on the next successful fetch.-- Returns the parsed JSON dict, or ``{}`` only when neither the network nor- any cache layer can supply data. Callers must treat missing/null fields- as "no recommendation" and fall back to their own default.+ (``$HERMES_HOME/cache/nous_recommended_cache.json``) as last-known-good. Self-heals on the next+ successful fetch."""base = (portal_base_url or "https://portal.nousresearch.com").rstrip("/")now = time.monotonic()@@ -1244,24 +1157,9 @@ def get_nous_recommended_aux_model() -> Optional[str]:"""Return the Portal's recommended model name for an auxiliary task.- Picks the best field from the Portal's recommended-models payload:-- * ``vision=True`` → ``paidRecommendedVisionModel`` (paid tier) or- ``freeRecommendedVisionModel`` (free tier)- * ``vision=False`` → ``paidRecommendedCompactionModel`` or- ``freeRecommendedCompactionModel``-- When ``free_tier`` is ``None`` (default) the user's tier is auto-detected- via :func:`check_nous_free_tier`. Pass an explicit bool to bypass the- detection — useful for tests or when the caller already knows the tier.-- For paid-tier users we prefer the paid recommendation but gracefully fall- back to the free recommendation if the Portal returned ``null`` for the- paid field (common during the staged rollout of new paid models).-- Returns ``None`` when every candidate is missing, null, or the fetch- fails — callers should fall back to their own default (currently- ``google/gemini-3-flash-preview``).+ For paid-tier users we prefer the paid recommendation but gracefully fall back to the free+ recommendation if the Portal returned ``null`` for the paid field (common during the staged+ rollout of new paid models)."""base = portal_base_url or _resolve_nous_portal_url()payload = fetch_nous_recommended_models(base, force_refresh=force_refresh)@@ -1422,28 +1320,13 @@ def provider_group_for_slug(slug: str) -> str:def group_providers(slugs):"""Fold a flat ordered slug iterable into picker rows by provider group.- DISPLAY ONLY. Used by every interactive picker (``hermes model``, the- setup wizard, the Telegram ``/model`` keyboard) so grouping is identical- across surfaces.-- Each returned row is a dict::-- {"kind": "single", "slug": <slug>} # ungrouped, or- # 1-member group- {"kind": "group", "group_id": <gid>, "label": <label>,- "description": <desc>, "members": [<slug>, ...]} # 2+ members-- Rules:- * A group row appears at the position of its FIRST present member, in- the input order. Subsequent members fold into that row (and are not- emitted again).- * Member order inside a group follows ``PROVIDER_GROUPS`` declaration,- restricted to the members actually present in ``slugs``.- * A group reduced to a single present member degrades to a ``single``- row — no pointless one-item submenu.- * Slugs not in any group pass through as ``single`` rows, order- preserved.- * Duplicate slugs in the input are ignored after first sight.+ DISPLAY ONLY. Used by every interactive picker (``hermes model``, the setup wizard, the Telegram+ ``/model`` keyboard) so grouping is identical across surfaces.++ Rules: * A group row appears at the position of its FIRST present member, in the input order.+ Subsequent members fold into that row (and are not emitted again). * Member order inside a group+ follows ``PROVIDER_GROUPS`` declaration, restricted to the members actually present in+ ``slugs``."""seen: set[str] = set()# Which present members each group has, in declaration order.@@ -1596,10 +1479,9 @@ PREFERRED_SILENT_DEFAULT_MODEL = "z-ai/glm-5.2"def get_preferred_silent_default_model(provider: str = "openrouter") -> str:"""Return the silent-default model id — catalog label first, constant second.- Reads the ``"default": true`` label from the cached remote catalog- (never hits the network — safe on hot resolution paths), falling back to- :data:`PREFERRED_SILENT_DEFAULT_MODEL` when no cached manifest exists or- the provider block carries no label.+ Reads the ``"default": true`` label from the cached remote catalog (never hits the network —+ safe on hot resolution paths), falling back to :data:`PREFERRED_SILENT_DEFAULT_MODEL` when no+ cached manifest exists or the provider block carries no label."""try:from hermes_cli.model_catalog import get_default_model_from_cache@@ -1614,11 +1496,10 @@ def get_preferred_silent_default_model(provider: str = "openrouter") -> str:def pick_silent_default_model(model_ids: list[str], provider: str = "openrouter") -> str:"""Pick the silent default from an available-models list.- Returns the catalog-labeled default (see- :func:`get_preferred_silent_default_model`) when the list carries it,- else the first entry, else "". Used by every surface that must choose a- model on the user's behalf without an interactive picker (GUI onboarding- recommended-default, empty-model runtime fallback).+ Returns the catalog-labeled default (see :func:`get_preferred_silent_default_model`) when the+ list carries it, else the first entry, else "". Used by every surface that must choose a model+ on the user's behalf without an interactive picker (GUI onboarding recommended-default, empty-+ model runtime fallback)."""preferred = get_preferred_silent_default_model(provider)if preferred in model_ids:@@ -1649,17 +1530,9 @@ _SILENT_DEFAULT_PROVIDERS: frozenset[str] = frozenset({"nous", "openrouter"})def get_default_model_for_provider(provider: str) -> str:"""Return a cost-safe default model for a provider, or "" if unknown.- Used as a NON-INTERACTIVE fallback when a provider is configured but no- model was ever selected (e.g. ``hermes auth add openai-codex`` without- ``hermes model``, or a profile that sets ``provider`` with no ``model``).-- For most providers this is the first entry in ``_PROVIDER_MODELS`` — the- same model the ``hermes model`` picker offers first. For metered aggregators- whose curated list is ordered most-capable-first, that entry is also the- most EXPENSIVE one, so silently defaulting to it is a billing footgun.- Those providers (``_SILENT_DEFAULT_PROVIDERS``) resolve through the- catalog-labeled default instead; a missing model must never auto-escalate- to the flagship.+ Used as a NON-INTERACTIVE fallback when a provider is configured but no model was ever selected+ (e.g. ``hermes auth add openai-codex`` without ``hermes model``, or a profile that sets+ ``provider`` with no ``model``)."""models = _PROVIDER_MODELS.get(provider, [])if provider in _SILENT_DEFAULT_PROVIDERS:@@ -1685,18 +1558,14 @@ def _openrouter_model_is_free(pricing: Any) -> bool:def _openrouter_model_supports_tools(item: Any) -> bool:"""Return True when the model's ``supported_parameters`` advertise tool calling.- hermes-agent is tool-calling-first — every provider path assumes the model- can invoke tools. Models that don't advertise ``tools`` in their- ``supported_parameters`` (e.g. image-only or completion-only models) cannot- be driven by the agent loop and would fail at the first tool call.-- **Permissive when the field is missing.** Some OpenRouter-compatible gateways- (Nous Portal, private mirrors, older catalog snapshots) don't populate- ``supported_parameters`` at all. Treat that as "unknown capability → allow"- so the picker doesn't silently empty for those users. Only hide models- whose ``supported_parameters`` is an explicit list that omits ``tools``.+ hermes-agent is tool-calling-first — every provider path assumes the model can invoke tools.+ Models that don't advertise ``tools`` in their ``supported_parameters`` (e.g. image-only or+ completion-only models) cannot be driven by the agent loop and would fail at the first tool+ call.- Ported from Kilo-Org/kilocode#9068.+ **Permissive when the field is missing.** Some OpenRouter-compatible gateways (Nous Portal,+ private mirrors, older catalog snapshots) don't populate ``supported_parameters`` at all. Treat+ that as "unknown capability → allow" so the picker doesn't silently empty for those users."""if not isinstance(item, dict):return True@@ -1711,23 +1580,8 @@ def parse_openrouter_reasoning_capabilities(item: Any) -> Optional[dict[str, Any"""Normalize one OpenRouter catalog entry's reasoning metadata.OpenRouter's ``/v1/models`` catalog advertises reasoning support two ways:- ``supported_parameters`` contains ``"reasoning"`` when the route accepts- reasoning controls at all, and a top-level ``reasoning`` object may add- detail (``mandatory``, ``supported_efforts``). Per OpenRouter semantics- the top-level object is only trusted after ``supported_parameters``- confirms the route accepts reasoning controls; ``supported_efforts``- omitted/None means every effort is accepted.-- Returns:- ``{"supports_reasoning": True, "supported_efforts": [...] | None,- "mandatory": bool}`` when the entry advertises reasoning controls,- ``{"supports_reasoning": False}`` when it explicitly does not- (``supported_parameters`` is a list omitting ``reasoning``), or- ``None`` when capability can't be determined from the entry- (missing/malformed ``supported_parameters``).-- Ported from PrimeIntellect-ai/prime-agent#1258 (derive reasoning levels- from provider metadata instead of hardcoded model-family lists).+ ``supported_parameters`` contains ``"reasoning"`` when the route accepts reasoning controls at+ all, and a top-level ``reasoning`` object may add detail (``mandatory``, ``supported_efforts``)."""if not isinstance(item, dict):return None@@ -1829,12 +1683,9 @@ def _save_reasoning_caps_disk(def _warm_reasoning_caps_async(refresh) -> None:"""Run *refresh* in a background thread. Fire-and-forget.- Called from hot paths that found the cache cold or the disk copy stale, so- the next call — or, via the disk mirror, the next process — benefits- without this turn ever blocking on HTTP. Callers own the once-per-process- guard; the fetch keeps its own failure TTL. Skipped under pytest, where a- mid-suite background fetch would make cache state, and therefore test- behavior, timing-dependent.+ Called from hot paths that found the cache cold or the disk copy stale, so the next call — or,+ via the disk mirror, the next process — benefits without this turn ever blocking on HTTP.+ Callers own the once-per-process guard; the fetch keeps its own failure TTL."""if os.environ.get("PYTEST_CURRENT_TEST"):return@@ -1846,9 +1697,8 @@ def _warm_reasoning_caps_async(refresh) -> None:def _hydrate_reasoning_caps_from_disk(url: str, refresh):"""The disk copy of *url*'s catalog, queueing *refresh* when it's stale.- A copy past its TTL is still returned — a stale verdict beats no verdict,- and reasoning capabilities change rarely — with a background refresh so- the next run is current.+ A copy past its TTL is still returned — a stale verdict beats no verdict, and reasoning+ capabilities change rarely — with a background refresh so the next run is current."""caps, age = _load_reasoning_caps_disk(url)if caps is None:@@ -1863,10 +1713,9 @@ def _seed_reasoning_caps() -> Optional[dict[str, Optional[dict[str, Any]]]]:"""Parse a ``/v1/models`` ``data`` array and mirror it for *url*.- Takes the payload rather than fetching it, so the picker and pricing- fetches — which pull the same document a capability fetch would — leave the- mirror warm at no network cost. None when the array has no usable entries,- which callers remember as a failure rather than caching as empty.+ Takes the payload rather than fetching it, so picker and pricing fetches (which pull the+ same document) leave the mirror warm at no network cost. Returns None when the array has no+ usable entries, which callers remember as a failure rather than caching as empty."""if not isinstance(items, list):return None@@ -1889,10 +1738,9 @@ def _fetch_reasoning_caps_catalog() -> Optional[dict[str, Optional[dict[str, Any]]]]:"""Fetch one OpenRouter-shaped ``/v1/models`` catalog → per-model caps.- Shared by every aggregator that serves OpenRouter's catalog schema- (OpenRouter itself, Nous Portal). Returns None when the catalog is- unreachable or carries no usable entries, so callers can remember the- failure and fall back rather than caching an empty result.+ Shared by every aggregator serving OpenRouter's catalog schema (OpenRouter, Nous Portal).+ Returns None when the catalog is unreachable or has no usable entries, so callers remember+ the failure and fall back rather than caching an empty result.Sends a User-Agent because the Portal 403s anonymous catalog reads."""@@ -1914,11 +1762,9 @@ def _fetch_openrouter_reasoning_caps() -> Optional[dict[str, Optional[dict[str, Any]]]]:"""Fetch + cache per-model reasoning capabilities from the live catalog.- Returns None (without poisoning the cache) when the catalog is- unreachable so callers can retry later and fall back in the meantime.- Failed fetches are remembered for 60 seconds so hot per-turn callers- don't pay an HTTP round-trip on every call while offline. *force* refetches- past a cache populated from the disk mirror.+ Returns None (without poisoning the cache) when the catalog is unreachable so callers can retry+ later and fall back in the meantime. Failed fetches are remembered for 60 seconds so hot per-+ turn callers don't pay an HTTP round-trip on every call while offline."""global _openrouter_reasoning_caps_cache, _openrouter_reasoning_caps_failed_atif _openrouter_reasoning_caps_cache is not None and not force:@@ -1948,22 +1794,13 @@ def openrouter_model_reasoning_capabilities() -> Optional[dict[str, Any]]:"""Return live-catalog reasoning capabilities for an OpenRouter model.- Tri-state contract for callers deciding whether to emit reasoning- controls:- - dict with ``supports_reasoning: True`` (+ ``supported_efforts``,- ``mandatory``) — the route advertises reasoning controls;- - dict with ``supports_reasoning: False`` — the catalog knows the model- and it does NOT accept reasoning controls (definitive negative);- - ``None`` — unknown: catalog not loaded yet, model not listed- (private/custom route), or entry malformed. Callers should fall back- to their static heuristics rather than treating this as a negative.-- By default this is a CACHE-ONLY lookup — safe on per-request hot paths- (never blocks on HTTP). The cache is populated for free whenever- ``fetch_openrouter_models()`` runs (model picker, setup), from the disk- mirror a previous run left behind, by the non-blocking- ``warm_openrouter_reasoning_caps_async()`` warmer, or by passing- ``allow_fetch=True`` from non-latency-sensitive callers.+ Tri-state contract for callers deciding whether to emit reasoning controls: - dict with+ ``supports_reasoning: True`` (+ ``supported_efforts``, ``mandatory``) — the route advertises+ reasoning controls; - dict with ``supports_reasoning: False`` — the catalog knows the model and+ it does NOT accept reasoning controls (definitive negative); - ``None`` — unknown: catalog not+ loaded yet, model not listed (private/custom route), or entry malformed.++ By default this is a CACHE-ONLY lookup — safe on per-request hot paths (never blocks on HTTP)."""model = str(model_id or "").strip()if not model:@@ -2010,10 +1847,9 @@ _nous_reasoning_caps_failed_at: float | None = Nonedef nous_catalog_url() -> str:"""The Portal ``/v1/models`` URL for the endpoint we actually talk to.- Resolved through the documented ladder rather than pinned to production —- ``NOUS_INFERENCE_BASE_URL`` → resolved credential base → prod — so a- staging profile reads staging's capabilities. Reading prod's would answer- the reasoning-mandatory question for the wrong deployment.+ Resolved through the ladder ``NOUS_INFERENCE_BASE_URL`` → resolved credential base → prod+ rather than pinned to production, so a staging profile reads staging's capabilities; prod's+ would answer the reasoning-mandatory question for the wrong deployment."""return f"{_resolve_nous_pricing_credentials()[1]}/v1/models"@@ -2072,9 +1908,9 @@ _nous_caps_warm_started = Falsedef _nous_caps_cached() -> Optional[dict[str, Optional[dict[str, Any]]]]:"""Cache-only Portal caps: memory, else the disk mirror. Never HTTP.- Guarded to one attempt per process because naming the catalog means- resolving Portal credentials, which can itself reach the network to- refresh a token — far too expensive for a caller that runs every turn.+ Guarded to one attempt per process because naming the catalog means resolving Portal+ credentials, which can itself reach the network to refresh a token — far too expensive for a+ caller that runs every turn."""global _nous_reasoning_caps_cache, _nous_caps_disk_checkedif _nous_reasoning_caps_cache is None and not _nous_caps_disk_checked:@@ -2094,9 +1930,6 @@ def warm_nous_reasoning_caps_async() -> None:_warm_reasoning_caps_async(_refresh_nous_reasoning_caps)-# Canonical low→high ordering used for nearest-level clamping. Kept as an-# alias of the single source of truth in ``agent.reasoning_effort``.-from agent.reasoning_effort import EFFORT_LADDER as _REASONING_EFFORT_ORDERfrom agent.reasoning_effort import clamp_effort as _clamp_effort@@ -2106,15 +1939,11 @@ def clamp_reasoning_effort_to_supported() -> Optional[str]:"""Clamp a requested reasoning effort to a provider's supported levels.- Thin wrapper over the canonical policy in- :func:`agent.reasoning_effort.clamp_effort` (single implementation for- every transport and provider profile): keep a supported level verbatim,- otherwise nearest WEAKER supported level (never silently escalate cost),- weakest supported level when nothing weaker exists, pass through unknown- supported-sets and bespoke level names unchanged.-- Ported from PrimeIntellect-ai/prime-agent#1258's thinking-level-map- normalization.+ Thin wrapper over the canonical policy in :func:`agent.reasoning_effort.clamp_effort` (single+ implementation for every transport and provider profile): keep a supported level verbatim,+ otherwise nearest WEAKER supported level (never silently escalate cost), weakest supported level+ when nothing weaker exists, pass through unknown supported-sets and bespoke level names+ unchanged."""return _clamp_effort(effort, supported_efforts)@@ -2211,10 +2040,9 @@ def model_ids(*, force_refresh: bool = False) -> list[str]:def get_curated_nous_model_ids() -> list[str]:"""Return the curated Nous Portal model-id list.- Prefers the remotely-hosted catalog manifest (published under- ``website/static/api/model-catalog.json``); falls back to the in-repo- snapshot in ``_PROVIDER_MODELS["nous"]`` when the manifest is- unreachable. Always returns a list (never None).+ Prefers the remotely-hosted catalog manifest (published under ``website/static/api/model-+ catalog.json``); falls back to the in-repo snapshot in ``_PROVIDER_MODELS["nous"]`` when the+ manifest is unreachable. Always returns a list (never None)."""try:from hermes_cli.model_catalog import get_curated_nous_models@@ -2313,8 +2141,6 @@ def ai_gateway_model_ids(*, force_refresh: bool = False) -> list[str]:return [mid for mid, _ in fetch_ai_gateway_models(force_refresh=force_refresh)]--# ---------------------------------------------------------------------------# Pricing helpers — fetch live pricing from OpenRouter-compatible /v1/models# ---------------------------------------------------------------------------@@ -2353,9 +2179,9 @@ def _cache_catalog() -> dict[str, dict[str, Any]]:"""Cache a catalog result, giving an empty one an expiry.- *ttl_seconds* expires a non-empty result too. Only a catalog whose contents- depend on server-side state the client cannot observe needs it — an org's- model policy can change while a long-lived process holds the entry.+ *ttl_seconds* expires a non-empty result too. Only a catalog whose contents depend on server-+ side state the client cannot observe needs it — an org's model policy can change while a long-+ lived process holds the entry."""_pricing_cache[cache_key] = resultif result:@@ -2377,9 +2203,9 @@ _PRICING_AUTH_KEY_PREFIX = "\x00auth:"def _pricing_auth_fingerprint(api_key: str | None) -> str:"""Key suffix identifying the credential a catalog was read with.- A governed endpoint answers each token with the catalog its org may reach,- so two credentials cannot share an entry. blake2b for cache-key- fingerprinting only, same rationale as :func:`_custom_endpoint_fingerprint`.+ A governed endpoint answers each token with the catalog its org may reach, so two credentials+ cannot share an entry. blake2b for cache-key fingerprinting only, same rationale as+ :func:`_custom_endpoint_fingerprint`."""if not api_key:return ""@@ -2392,11 +2218,10 @@ def _pricing_auth_fingerprint(api_key: str | None) -> str:def peek_cached_pricing(base_url: str) -> dict[str, dict[str, Any]]:"""Pricing already cached for *base_url*, or ``{}``. Never fetches.- Accepts a ``/v1``-suffixed URL as well as the pre-``/v1`` root the fetchers- key on, and prefers an authenticated catalog. Scans rather than rebuilding a- key, because callers hold a base URL but no credential — newest first, and- skipping expired entries, so a rotated credential does not keep answering- from the catalog its predecessor read.+ Accepts a ``/v1``-suffixed URL as well as the pre-``/v1`` root the fetchers key on, and+ prefers an authenticated catalog. Scans rather than rebuilding a key because callers hold no+ credential — newest first, skipping expired entries, so a rotated credential does not keep+ answering from the catalog its predecessor read."""root = (base_url or "").rstrip("/")if root.endswith("/v1"):@@ -2413,22 +2238,12 @@ def peek_cached_pricing(base_url: str) -> dict[str, dict[str, Any]]:def _format_price_per_mtok(per_token_str: str) -> str:"""Convert a per-token price string to a human-friendly $/Mtok string.- Always uses 2 decimal places so that prices align vertically when- right-justified in a column (the decimal point stays in the same position).-- Sub-cent prices (e.g. deep-discount cache-hit promos) extend precision- instead of collapsing to "$0.00": the smallest decimal place that makes- the value non-zero is found, then one extra digit is kept and trailing- zeros trimmed.-- Examples:- "0.000003" → "$3.00" (per million tokens)- "0.00003" → "$30.00"- "0.00000015" → "$0.15"- "0.0000001" → "$0.10"- "0.00018" → "$180.00"- "0.0000000018" → "$0.0018" (promo: $0.0018/Mtok)- "0" → "free"+ Always uses 2 decimal places so that prices align vertically when right-justified in a column+ (the decimal point stays in the same position).++ Sub-cent prices (e.g. deep-discount cache-hit promos) extend precision instead of collapsing to+ "$0.00": the smallest decimal place that makes the value non-zero is found, then one extra digit+ is kept and trailing zeros trimmed."""try:val = float(per_token_str)@@ -2455,23 +2270,12 @@ def compute_sale_discount() -> tuple[int, str, str] | None:"""Derive sale chrome from gateway ``pricing.original`` when cheaper.- Nous Portal-only feature: callers gate on the provider; this helper only- sees ``original`` because the Nous fetch path opted in via- ``include_sale_original=True``.-- Returns ``(discount_percent, was_prompt_raw, was_completion_raw)`` only when- ``original`` is a dict and the current prompt (fallback: completion) rate- is strictly below the corresponding original. Percent is- ``round((1 - current/original) * 100)`` — never hardcoded, and a discount- that rounds below 1% is treated as no sale (never render "-0%"). Returns- ``None`` when there is no sale (missing/equal/invalid original), so UIs- show normal prices.-- Free / $0 models are a special case: they are always "-100%" sale chrome- (Teknium, Aug 2026 — the picker's discount column should say 100% off- rather than sit blank on free rows). The ``was_*`` raws come from- ``original`` when the gateway serves one and are empty strings otherwise;- callers must skip the "was" segment when both are empty.+ Nous Portal-only feature: callers gate on the provider; this helper only sees ``original``+ because the Nous fetch path opted in via ``include_sale_original=True``.++ Returns ``(discount_percent, was_prompt_raw, was_completion_raw)`` only when ``original`` is a+ dict and the current prompt (fallback: completion) rate is strictly below the corresponding+ original."""def _finite(raw: Any) -> float | None:try:@@ -2547,17 +2351,13 @@ def fetch_models_with_pricing() -> dict[str, dict[str, Any]]:"""Fetch ``/v1/models`` and return ``{model_id: {prompt, completion, ...}}``.- Results are cached per *base_url* and per credential, so repeated calls are- free and one caller's catalog never answers another's read.- Works with any OpenRouter-compatible endpoint (OpenRouter, Nous Portal).-- When *include_sale_original* is true (Nous Portal only) and the gateway- advertises a global discount under ``pricing.original``, those- pre-discount rates are copied through as a nested ``original`` dict so- pickers can show sale chrome. Other providers never opt in — OpenRouter- (and anything else sharing this helper) keeps the legacy- ``{prompt, completion}`` shape even if a response happens to nest- ``original``.+ Results are cached per *base_url* and per credential, so repeated calls are free and one+ caller's catalog never answers another's read. Works with any OpenRouter-compatible endpoint+ (OpenRouter, Nous Portal).++ When *include_sale_original* is true (Nous Portal only) and the gateway advertises a global+ discount under ``pricing.original``, those pre-discount rates are copied through as a nested+ ``original`` dict so pickers can show sale chrome."""url_root = (base_url or "").rstrip("/")cache_key = url_root + _pricing_auth_fingerprint(api_key)@@ -2627,9 +2427,8 @@ def fetch_ai_gateway_pricing() -> dict[str, dict[str, str]]:"""Fetch Vercel AI Gateway /v1/models and return hermes-shaped pricing.- Vercel uses ``input`` / ``output`` field names; hermes's picker expects- ``prompt`` / ``completion``. This translates. Cache read/write field names- already match.+ Vercel uses ``input`` / ``output`` field names; hermes's picker expects ``prompt`` /+ ``completion``. This translates. Cache read/write field names already match."""from hermes_constants import AI_GATEWAY_BASE_URL@@ -2681,23 +2480,11 @@ _DEFAULT_NOUS_INFERENCE_BASE = "https://inference-api.nousresearch.com"def _resolve_nous_pricing_credentials() -> tuple[str, str]:"""Return ``(api_key, base_url)`` for Nous Portal pricing.- The Nous inference ``/v1/models`` endpoint exposes pricing without- authentication, so the api_key is best-effort: when runtime credential- resolution fails (expired refresh token, missing auth.json, etc.) we- still return a usable inference base URL so the picker keeps working- with anonymous pricing data. Free-tier users in particular need this- — pricing drives the free/paid partition, and silently returning empty- pricing because of an auth blip makes the picker look broken ("No free- models currently available").-- Base URL precedence (mirrors runtime credential resolution):- 1. ``NOUS_INFERENCE_BASE_URL`` env override (staging / preview)- 2. Resolved runtime credential ``base_url``- 3. Production default-- Without (1), a staging profile's sale ``pricing.original`` never- reaches the pickers — the anonymous fallback would hit prod, which- has no ``original`` field.+ Base URL precedence (mirrors runtime credential resolution): 1. ``NOUS_INFERENCE_BASE_URL`` env+ override (staging / preview) 2. Resolved runtime credential ``base_url`` 3. Production default++ Without (1), a staging profile's sale ``pricing.original`` never reaches the pickers — the+ anonymous fallback would hit prod, which has no ``original`` field."""env_base = Nonetry:@@ -2730,13 +2517,13 @@ def _resolve_nous_pricing_credentials() -> tuple[str, str]:def nous_policy_allowed_ids(*, force_refresh: bool = False) -> Optional[set[str]]:"""The Nous model ids the caller's org may reach, or ``None`` to not filter.- The gateway omits policy-blocked rows from an authenticated- ``GET /v1/models``, so that response's keys are the reachable set.+ The gateway omits policy-blocked rows from an authenticated ``GET /v1/models``, so that+ response's keys are the reachable set.- ``None`` means "leave the caller's list alone", for the three states that- cannot support narrowing one: no policy (or a token too old to say), an- anonymous read whose catalog is unfiltered, and an empty read, which is a- fetch failure rather than an org that may reach nothing.+ ``None`` means "leave the caller's list alone", for the three states that cannot support+ narrowing one: no policy (or a token too old to say), an anonymous read whose catalog is+ unfiltered, and an empty read, which is a fetch failure rather than an org that may reach+ nothing."""try:from hermes_cli.nous_account import nous_policy_present@@ -2783,12 +2570,10 @@ def restrict_to_nous_policy() -> list[str]:"""*model_ids* narrowed to *allowed*, preserving the caller's order.- A ``None`` or empty *allowed* leaves the list untouched.-- A ``:free`` sibling is kept when its base model is reachable, mirroring the- gateway, which admits a row when any of its requestable ids passes. Prefer- over-listing: that costs a 403 from the authoritative gate, while hiding a- row the gate would serve is unrecoverable from the client.+ A ``:free`` sibling is kept when its base model is reachable, mirroring the gateway, which+ admits a row when any of its requestable ids passes. Prefer over-listing: that costs a 403 from+ the authoritative gate, while hiding a row the gate would serve is unrecoverable from the+ client."""if not allowed:return list(model_ids)@@ -2844,14 +2629,9 @@ def _fireworks_pricing_from_models_dev() -> dict[str, dict[str, str]]:"""Derive Fireworks picker pricing from the models.dev registry cache.- No dedicated network fetch: ``fetch_models_dev()`` already maintains an- in-memory + disk cache (1h TTL) that every picker surface shares, so this- is a pure dict transform on the picker path — no added latency and no- per-render network call. Results are additionally memoized in- ``_pricing_cache`` so repeated menu renders within a process are free.-- models.dev publishes Fireworks costs in USD per 1M tokens; the shared- pricing formatter expects per-token strings, so divide by 1M.+ No dedicated network fetch: ``fetch_models_dev()`` already maintains an in-memory + disk cache+ (1h TTL) that every picker surface shares, so this is a pure dict transform on the picker path —+ no added latency and no per-render network call."""cache_key = "models.dev/fireworks"if not force_refresh:@@ -2895,13 +2675,9 @@ def _fetch_novita_pricing() -> dict[str, dict[str, str]]:"""Fetch pricing from NovitaAI /v1/models.- NovitaAI returns input/output prices per million tokens in units of- 0.0001 USD. Convert them to the per-token strings used by the shared- pricing formatter.-- Results are cached in ``_pricing_cache`` keyed on the resolved base URL,- matching the pattern used by ``fetch_ai_gateway_pricing`` — without this,- every menu render or pricing lookup re-hits the network.+ NovitaAI reports per-million-token prices in units of 0.0001 USD; they are converted to the+ per-token strings the shared pricing formatter expects. Results are cached in+ ``_pricing_cache`` keyed on the resolved base URL so menu renders don't re-hit the network."""api_key = os.getenv("NOVITA_API_KEY", "").strip()if not api_key:@@ -2980,11 +2756,9 @@ def _configured_custom_provider_ids() -> set[str]:def list_available_providers() -> list[dict[str, str]]:"""Return info about all providers the user could use with ``provider:model``.- Each dict has ``id``, ``label``, and ``aliases``.- Checks which providers have valid credentials configured.-- Derives the provider list from :data:`CANONICAL_PROVIDERS` (single- source of truth shared with ``hermes model``, ``/model``, etc.).+ Each dict has ``id``, ``label``, and ``aliases``, plus whether valid credentials are+ configured. Derived from :data:`CANONICAL_PROVIDERS`, the single source of truth shared with+ ``hermes model`` and ``/model``."""# Derive display order from canonical list + customprovider_order = [p.slug for p in CANONICAL_PROVIDERS] + ["custom"]@@ -3024,19 +2798,9 @@ def list_available_providers() -> list[dict[str, str]]:def parse_model_input(raw: str, current_provider: str) -> tuple[str, str]:"""Parse ``/model`` input into ``(provider, model)``.- Supports ``provider:model`` syntax to switch providers at runtime::-- openrouter:anthropic/claude-sonnet-4.5 → ("openrouter", "anthropic/claude-sonnet-4.5")- nous:hermes-3 → ("nous", "hermes-3")- anthropic/claude-sonnet-4.5 → (current_provider, "anthropic/claude-sonnet-4.5")- gpt-5.4 → (current_provider, "gpt-5.4")-- The colon is only treated as a provider delimiter if the left side is a- recognized provider name or alias. This avoids misinterpreting model names- that happen to contain colons (e.g. ``anthropic/claude-3.5-sonnet:beta``).-- Returns ``(provider, model)`` where *provider* is either the explicit- provider from the input or *current_provider* if none was specified.+ The colon is only treated as a provider delimiter if the left side is a recognized provider name+ or alias. This avoids misinterpreting model names that happen to contain colons (e.g.+ ``anthropic/claude-3.5-sonnet:beta``)."""stripped = raw.strip()colon = stripped.find(":")@@ -3121,10 +2885,10 @@ def _normalize_openai_base_url(base_url: Optional[str]) -> str: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.+ 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 = (@@ -3283,10 +3047,10 @@ def probe_ollama_local_models() -> 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.+ 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:@@ -3406,13 +3170,11 @@ def should_use_ollama_native_catalog() -> 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.+ Bare ``ollama`` is normalized to ``custom`` elsewhere so runtime paths share the OpenAI-+ compatible client, but local Ollama's authoritative model list is ``/api/tags``. Use it when+ the caller asked for Ollama explicitly, the base URL matches ``providers.ollama.base_url``,+ or an ambiguous custom URL on Ollama's default port actually serves ``/api/tags``; other+ custom endpoints keep the ``/models`` probe."""requested = str(provider or "").strip().lower()root = _root_for_ollama_native_api(base_url or "")@@ -3508,31 +3270,6 @@ def _anthropic_models_url(base_url: Optional[str] = None) -> str:return endpoint + "/v1/models"-def curated_models_for_provider(- provider: Optional[str],- *,- force_refresh: bool = False,-) -> list[tuple[str, str]]:- """Return ``(model_id, description)`` tuples for a provider's model list.-- Tries to fetch the live model list from the provider's API first,- falling back to the static ``_PROVIDER_MODELS`` catalog if the API- is unreachable.- """- normalized = normalize_provider(provider)- if normalized == "openrouter":- return fetch_openrouter_models(force_refresh=force_refresh)-- # Try live API first (Codex, Nous, etc. all support /models)- live = provider_model_ids(normalized)- if live:- return [(m, "") for m in live]-- # Fallback to static catalog- models = _PROVIDER_MODELS.get(normalized, [])- return [(m, "") for m in models]--def _provider_keys(provider: str) -> set[str]:key = (provider or "").strip().lower()normalized = normalize_provider(provider)@@ -3579,9 +3316,9 @@ _OPENROUTER_VARIANT_SUFFIXES = frozenset({"nitro", "floor", "exacto", "online"})def _openrouter_variant_base(model_id: str) -> Optional[str]:- """Return the base model id when ``model_id`` carries a recognized- OpenRouter routing-variant suffix (e.g. ``x-ai/grok-4:nitro`` →- ``x-ai/grok-4``), else ``None``."""+ """Return the base model id when ``model_id`` carries a recognized OpenRouter routing-variant+ suffix (e.g. ``x-ai/grok-4:nitro`` → ``x-ai/grok-4``), else ``None``.+ """base, sep, suffix = (model_id or "").rpartition(":")if not sep or not base:return None@@ -3672,9 +3409,9 @@ def detect_static_provider_for_model() -> Optional[tuple[str, str]]:"""Auto-detect a provider from static catalogs only.- Returns ``(provider_id, model_name)``. The model name may be remapped- when a static alias or bare provider name resolves to a catalog default.- Returns ``None`` when no confident match is found.+ Returns ``(provider_id, model_name)``; the name may be remapped when a static alias or bare+ provider name resolves to a catalog default. Returns ``None`` when no confident match is+ found."""name = (model_name or "").strip()if not name:@@ -3753,10 +3490,9 @@ def detect_static_provider_for_model(def _configured_provider_ids() -> set[str]:"""Provider ids defined in the user's config ``providers:`` block.- Includes both top-level ids (``ollama``, ``nous``) and ``custom:*``- profile ids. Returns an empty set when config is unreadable — callers- treat that as "no user-defined providers" and fall through to built-in- catalogs only.+ Includes both top-level ids (``ollama``, ``nous``) and ``custom:*`` profile ids. Returns an+ empty set when config is unreadable — callers treat that as "no user-defined providers" and fall+ through to built-in catalogs only."""try:from hermes_cli.config import load_config@@ -3778,19 +3514,12 @@ def _configured_provider_ids() -> set[str]:def _resolve_provider_prefix(model_name: str) -> Optional[tuple[str, str]]:"""Resolve an explicit ``vendor/model`` prefix to a configured provider.- ``nous/deepseek-v4-pro`` or ``ollama/qwen3.5:4b`` should route to the- named provider instead of falling back to the configured default (which- silently sends non-default models to the wrong endpoint, #87189).-- Only vendors the user actually defined in their ``providers:`` config- block (by raw name or alias) are routed here. Built-in vendor prefixes- (``google/gemini-2.5-flash``, ``deepseek/deepseek-chat``) deliberately- stay on the existing catalog / OpenRouter-slug / default-provider path:- those slug forms are aggregator-native, and rerouting them to the vendor- provider would change established provider-switch behavior (see- ``TestDenormalizeProviderSwitch`` in tests/hermes_cli/test_web_server.py).- The returned model is the suffix with the prefix stripped — the target- provider's API expects the bare id.+ ``nous/deepseek-v4-pro`` or ``ollama/qwen3.5:4b`` should route to the named provider instead of+ falling back to the configured default (which silently sends non-default models to the wrong+ endpoint, #87189).++ Only vendors the user actually defined in their ``providers:`` config block (by raw name or+ alias) are routed here."""if "/" not in model_name:return None@@ -3819,14 +3548,8 @@ def detect_provider_for_model() -> Optional[tuple[str, str]]:"""Auto-detect the best provider for a model name.- Returns ``(provider_id, model_name)`` — the model name may be remapped- (e.g. bare ``deepseek-chat`` → ``deepseek/deepseek-chat`` for OpenRouter).- Returns ``None`` when no confident match is found.-- Priority:- 0. Bare provider name → switch to that provider's default model- 1. Direct provider static catalog match- 2. OpenRouter catalog match+ Priority: 0. Bare provider name → switch to that provider's default model 1. Direct provider+ static catalog match 2. OpenRouter catalog match"""name = (model_name or "").strip()if not name:@@ -3863,13 +3586,7 @@ def detect_provider_for_model(def _find_openrouter_slug(model_name: str) -> Optional[str]:- """Find the full OpenRouter model slug for a bare or partial model name.-- Handles:- - Exact match: ``anthropic/claude-opus-4.6`` → as-is- - Bare name: ``deepseek-chat`` → ``deepseek/deepseek-chat``- - Bare name: ``claude-opus-4.6`` → ``anthropic/claude-opus-4.6``- """+ """Find the full OpenRouter model slug for a bare or partial model name."""name_lower = model_name.strip().lower()if not name_lower:return None@@ -3892,9 +3609,8 @@ def _find_openrouter_slug(model_name: str) -> Optional[str]:def normalize_provider(provider: Optional[str]) -> str:"""Normalize provider aliases to Hermes' canonical provider ids.- Note: ``"auto"`` passes through unchanged — use- ``hermes_cli.auth.resolve_provider()`` to resolve it to a concrete- provider based on credentials and environment.+ ``"auto"`` passes through unchanged — use ``hermes_cli.auth.resolve_provider()`` to resolve+ it to a concrete provider from credentials and environment."""normalized = (provider or "openrouter").strip().lower()return _PROVIDER_ALIASES.get(normalized, normalized)@@ -3971,20 +3687,13 @@ def model_supports_fast_mode(model_id: Optional[str]) -> bool:def _is_anthropic_fast_model(model_id: Optional[str]) -> bool:"""Return True if the model accepts the Anthropic Fast Mode ``speed`` param.- This gates the *speed=fast request parameter*, which Anthropic supports- on Opus 4.8 and Opus 5 (research preview, Claude API only). It is- deliberately NOT a general "is this a fast model" check:+ This gates the *speed=fast request parameter*, which Anthropic supports on Opus 4.8 and Opus 5+ (research preview, Claude API only). It is deliberately NOT a general "is this a fast model"+ check:- - Opus 4.6 had fast mode at launch and LOST it (2026-06-29) — the param- is silently ignored (standard speed, standard billing), so exposing a- toggle for it would show users a switch that does nothing.- - Opus 4.7 hard-400s on the parameter.- - Dedicated ``…-fast`` model ids (e.g. OpenRouter's- ``claude-opus-4.8-fast``) select fast inference via the model field- and must not also receive the speed parameter.-- Keep this in lock-step with ``agent.anthropic_adapter._supports_fast_mode``- so the UI never shows a Fast toggle that the runtime would drop.+ - Opus 4.7 hard-400s on the parameter. - Dedicated ``…-fast`` model ids (e.g. OpenRouter's+ ``claude-opus-4.8-fast``) select fast inference via the model field and must not also receive+ the speed parameter."""raw = _strip_vendor_prefix(str(model_id or ""))base = raw.split(":")[0]@@ -3998,11 +3707,7 @@ def _is_anthropic_fast_model(model_id: Optional[str]) -> bool:def _fast_mode_route_supported(model_id: Optional[str], provider: Optional[str], base_url: Optional[str]) -> bool:- """Only the first-party endpoint that bills for fast mode may receive its params.-- OpenRouter, Nous, Copilot, Azure, Bedrock, and custom base_urls either- strip ``service_tier``/``speed`` (charging nothing) or 400 on them.- """+ """Only the first-party endpoint that bills for fast mode may receive its params."""from urllib.parse import urlparsefrom agent.model_metadata import is_grok_46_family@@ -4027,19 +3732,13 @@ def resolve_fast_mode_overrides() -> dict[str, Any] | None:"""Return request_overrides for fast/priority mode, or None if unsupported.- Returns provider-appropriate overrides:- - OpenAI models: ``{"service_tier": "priority"}`` (Priority Processing)- - Anthropic models: ``{"speed": "fast"}`` (Anthropic Fast Mode beta)- - Grok 4.6: ``{"service_tier": "priority"}`` (xAI Priority Processing)-- When ``provider``/``base_url`` are given the result is also gated on the- route (see ``_fast_mode_route_supported``) so proxies never see the- params. This is the single fast-mode gate for static ``/fast fast`` and- the bounded ``auto``/``cold`` windows in ``agent.fast_mode``.+ Returns provider-appropriate overrides: - OpenAI models: ``{"service_tier": "priority"}``+ (Priority Processing) - Anthropic models: ``{"speed": "fast"}`` (Anthropic Fast Mode beta) -+ Grok 4.6: ``{"service_tier": "priority"}`` (xAI Priority Processing)- The overrides are injected into the API request kwargs by- ``build_api_kwargs`` — each API path handles its own keys- (service_tier for OpenAI/Codex, speed for Anthropic Messages).+ When ``provider``/``base_url`` are given the result is also gated on the route (see+ ``_fast_mode_route_supported``) so proxies never see the params. This is the single fast-mode+ gate for static ``/fast fast`` and the bounded ``auto``/``cold`` windows in ``agent.fast_mode``."""if not model_supports_fast_mode(model_id):return None@@ -4192,12 +3891,10 @@ _MODELS_DEV_PREFERRED: frozenset[str] = frozenset({def _model_dedup_key(model_id: str) -> str:"""Case-insensitive dedup key that also folds picker-search aliases.- Some providers serve the same model under both a curated public slug and- a bare live wire id (Kimi Coding Plan lists its flagship as ``k3`` while- the curated catalog carries ``kimi-k3``). Folding through the search-alias- table keeps the curated-first merge from emitting both as separate rows.- The row that survives is the primary list's entry; selection still sends- whichever id the surviving row carries.+ Some providers serve one model under both a curated public slug and a bare live wire id+ (Kimi lists ``k3`` while the curated catalog carries ``kimi-k3``). Folding through the+ search-alias table keeps the curated-first merge from emitting both; the primary list's row+ survives and selection sends whichever id it carries."""key = str(model_id).strip().lower()try:@@ -4210,12 +3907,12 @@ def _model_dedup_key(model_id: str) -> str:def _merge_with_models_dev(provider: str, curated: list[str]) -> list[str]:"""Merge curated list with fresh models.dev entries for a preferred provider.- Returns models.dev entries first (in models.dev order), then any- curated-only entries appended. Preserves case for curated fallbacks- (e.g. ``MiniMax-M2.7``) while trusting models.dev for newer variants.+ Returns models.dev entries first (in models.dev order), then any curated-only entries appended.+ Preserves case for curated fallbacks (e.g. ``MiniMax-M2.7``) while trusting models.dev for newer+ variants.- If models.dev is unreachable or returns nothing, the curated list is- returned unchanged — this is the offline/CI fallback path.+ If models.dev is unreachable or returns nothing, the curated list is returned unchanged — this+ is the offline/CI fallback path."""try:from agent.models_dev import list_agentic_models@@ -4247,12 +3944,9 @@ def _merge_with_models_dev(provider: str, curated: list[str]) -> list[str]:def _openai_discovery_base_url(provider: str) -> str:"""Effective OpenAI endpoint for model discovery.- Mirrors the runtime precedence so discovery probes the SAME endpoint- inference uses: ``$OPENAI_BASE_URL`` (explicit env override) →- ``model.base_url`` from config.yaml when the configured provider matches- → the canonical default. Previously this read the env var only, so a- config-set data-residency host (``us.api.openai.com``) was ignored and- the catalog kept coming from ``api.openai.com``.+ Mirrors the runtime precedence so discovery probes the SAME endpoint inference uses:+ ``$OPENAI_BASE_URL`` (explicit env override) → ``model.base_url`` from config.yaml when the+ configured provider matches → the canonical default."""env_raw = os.getenv("OPENAI_BASE_URL", "").strip().rstrip("/")if env_raw:@@ -4272,11 +3966,9 @@ def _openai_discovery_base_url(provider: str) -> str:def provider_model_ids(provider: Optional[str], *, force_refresh: bool = False) -> list[str]:"""Return the best known model catalog for a provider.- Tries live API endpoints for providers that support them (Codex, Nous),- falling back to static lists. For providers in ``_MODELS_DEV_PREFERRED``- (opencode-go/zen, xiaomi, deepseek, smaller inference providers, etc.),- models.dev entries are merged on top of curated so new models released- on the platform appear in ``/model`` without a Hermes release.+ Tries live API endpoints where supported (Codex, Nous), falling back to static lists. For+ providers in ``_MODELS_DEV_PREFERRED`` models.dev entries are merged on top of curated so+ new platform models appear in ``/model`` without a Hermes release."""requested = str(provider or "").strip().lower()if requested == "ollama":@@ -4627,16 +4319,13 @@ _swr_refresh_lock = threading.Lock()def _spawn_swr_refresh(cache_key: str, refresh_fn=None) -> None:"""Kick a background refresh of *cache_key*'s model-id cache entry.- Fire-and-forget daemon thread; at most one in flight per cache key.- Failures are swallowed — the stale entry stays served until a later- refresh succeeds (same degradation the blocking path already had).+ Fire-and-forget daemon thread; at most one in flight per cache key. Failures are swallowed — the+ stale entry stays served until a later refresh succeeds (same degradation the blocking path+ already had).- ``refresh_fn`` (no-args, returns the fresh cache-entry dict or ``None``)- lets non-slug keys (``custom:<base_url>`` entries from- :func:`cached_fetch_api_models`) reuse the same inflight-dedupe and- thread scaffolding. When omitted, *cache_key* is treated as a- ``PROVIDER_REGISTRY`` slug and refreshed via :func:`provider_model_ids`- (the original behavior).+ ``refresh_fn`` (no-args, returns the fresh cache-entry dict or ``None``) lets non-slug keys+ (``custom:<base_url>`` entries from :func:`cached_fetch_api_models`) reuse the same inflight-+ dedupe and thread scaffolding."""with _swr_refresh_lock:if cache_key in _swr_refresh_inflight:@@ -4689,17 +4378,12 @@ def _provider_models_cache_path() -> Path:def _credential_fingerprint(provider: str) -> str:- """Return a short hash representing the credentials that- ``provider_model_ids(provider)`` would see right now.-- Rotating any of the relevant env vars invalidates the cached entry- for that provider. We hash AT LEAST the api-key + base-url env vars- declared in ``PROVIDER_REGISTRY``. For OAuth-backed providers- (codex, copilot, anthropic-via-claude-code, nous portal), the- relevant tokens live in ``$HERMES_HOME/auth.json`` and external- credential files. Rather than parse every shape, we additionally- fold the mtime of those files into the fingerprint so refreshes- after re-auth bust the cache.+ """Short hash of the credentials ``provider_model_ids(provider)`` would see right now.++ Rotating any relevant env var invalidates that provider's cache entry: the api-key and base-+ url env vars from ``PROVIDER_REGISTRY`` are hashed. OAuth-backed providers keep tokens in+ ``auth.json`` and external credential files, so those files' mtimes are folded in too — re-+ auth busts the cache without parsing every file shape."""import hashlibimport os as _os@@ -4830,10 +4514,9 @@ def _save_provider_models_cache(data: dict) -> None:def update_provider_cache_entry(provider: str, models: list[str]) -> None:"""Thread-safe single-entry update of the provider-models disk cache.- Used by parallel prefetch workers so concurrent fetches don't clobber- each other's writes via read-modify-write races on the shared JSON file.- Each worker loads the latest cache state under the lock, writes its own- entry, and saves — best-effort, silent on any error.+ Used by parallel prefetch workers so concurrent fetches don't clobber each other's writes via+ read-modify-write races on the shared JSON file. Each worker loads the latest cache state under+ the lock, writes its own entry, and saves — best-effort, silent on any error."""try:normalized = normalize_provider(provider) or (provider or "")@@ -4860,8 +4543,8 @@ def cached_provider_model_ids() -> list[str]:"""Disk-cached wrapper around :func:`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).+ Hits the cache when fresh; otherwise calls the live function and persists a non-empty result.+ Always returns a list (never None)."""requested = str(provider or "").strip().lower()normalized = requested if requested == "ollama" else (normalize_provider(provider) or (provider or ""))@@ -4936,9 +4619,8 @@ def cached_provider_model_ids(def clear_provider_models_cache(provider: Optional[str] = None) -> None:"""Drop a single provider's cache entry, or wipe the whole cache.- ``provider=None`` wipes everything; otherwise only that provider's- entry is removed. Used by ``/model --refresh`` and- ``hermes model --refresh``.+ ``provider=None`` wipes everything; otherwise only that provider's entry is removed. Used by+ ``/model --refresh`` and ``hermes model --refresh``."""try:# Native Ollama tags are keyed by root URL rather than provider slug.@@ -4969,11 +4651,8 @@ def clear_provider_models_cache(provider: Optional[str] = None) -> None:def _resolve_anthropic_pool_catalog_credentials() -> tuple[str, str]:"""Return a read-only API-key pool credential for model discovery.- ``resolve_anthropic_token()`` intentionally ignores ``api_key`` pool- entries because its runtime contract is OAuth-oriented. The model catalog- supports regular ``x-api-key`` auth, so it needs a narrow fallback that- preserves the credential's configured endpoint instead of sending a- proxy-scoped key to Anthropic's public host.+ ``resolve_anthropic_token()`` intentionally ignores ``api_key`` pool entries because its runtime+ contract is OAuth-oriented."""try:from agent.credential_pool import AUTH_TYPE_API_KEY@@ -5004,10 +4683,9 @@ def _fetch_anthropic_models() -> Optional[list[str]]:"""Fetch available models from the Anthropic /v1/models endpoint.- Uses resolve_anthropic_token() to find credentials (env vars, OAuth,- or Claude Code auto-discovery) unless api_key is provided explicitly. If- those sources are empty, a read-only API-key credential_pool entry is used.- Returns sorted model IDs or None.+ Uses resolve_anthropic_token() to find credentials (env vars, OAuth, or Claude Code auto-+ discovery) unless api_key is provided explicitly. If those sources are empty, a read-only API-+ key credential_pool entry is used. Returns sorted model IDs or None."""try:from agent.anthropic_adapter import resolve_anthropic_token, _is_oauth_token@@ -5091,11 +4769,7 @@ def _payload_items(payload: Any) -> list[dict[str, Any]]:def copilot_default_headers(*, is_agent_turn: bool = True) -> dict[str, str]:- """Standard headers for Copilot API requests.-- Includes Openai-Intent and x-initiator headers that opencode and the- Copilot CLI send on every request.- """+ """Standard headers for Copilot API requests."""try:from hermes_cli.copilot_auth import copilot_request_headersreturn copilot_request_headers(is_agent_turn=is_agent_turn)@@ -5234,8 +4908,8 @@ _COPILOT_CONTEXT_CACHE_TTL = 3600 # 1 hourdef get_copilot_model_context(model_id: str, api_key: Optional[str] = None) -> Optional[int]:"""Look up max_prompt_tokens for a Copilot model from the live /models API.- Results are cached in-process for 1 hour to avoid repeated API calls.- Returns the token limit or None if not found.+ Results are cached in-process for 1 hour to avoid repeated API calls. Returns the token limit or+ None if not found."""global _copilot_context_cache, _copilot_context_cache_time@@ -5280,11 +4954,9 @@ def _is_github_models_base_url(base_url: Optional[str]) -> bool:def _lmstudio_server_root(base_url: Optional[str]) -> Optional[str]:"""Return the 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.- Returns ``None`` when the base URL is empty/invalid.+ 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."""root = (base_url or "").strip().rstrip("/")for suffix in ("/api/v1", "/api", "/v1"):@@ -5308,11 +4980,7 @@ 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``.-- Returns the ``models`` list of dicts on success, ``None`` on network- errors or malformed responses. Raises ``AuthError`` on HTTP 401/403.- """+ """Fetch the raw model list from LM Studio's ``/api/v1/models``."""server_root = _lmstudio_server_root(base_url)if not server_root:return None@@ -5360,13 +5028,10 @@ def probe_lmstudio_models() -> Optional[list[str]]:"""Probe LM Studio's model listing.- Returns chat-capable model keys on success, including the valid empty-list- case when the server is reachable but has no non-embedding models.- Returns ``None`` on network errors, malformed responses, or empty/invalid- base URLs.-- Raises ``AuthError`` on HTTP 401/403 so callers can surface token issues- separately from reachability problems.+ 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."""raw_models = _lmstudio_fetch_raw_models(api_key=api_key, base_url=base_url, timeout=timeout)if raw_models is None:@@ -5391,13 +5056,10 @@ def fetch_lmstudio_models() -> list[str]:"""Fetch LM Studio chat-capable model keys from native ``/api/v1/models``.- Returns a list of model keys (e.g. ``publisher/model-name``) with embedding- models filtered out. Returns an empty list on network errors, malformed- responses, or empty/invalid base URLs.-- 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 once auth-enabled mode is turned on.+ 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."""models = probe_lmstudio_models(api_key=api_key, base_url=base_url, timeout=timeout)return models or []@@ -5422,9 +5084,9 @@ def ensure_lmstudio_model_loaded() -> Optional[int] | LMStudioLoadResult:"""Ensure ``model`` is loaded and return verified runtime context.- Existing loaded-instance context is authoritative. Cold loads omit- ``context_length`` unless the caller supplied an explicit override; the- returned context must come from LM Studio's echoed or refreshed state.+ Existing loaded-instance context is authoritative. Cold loads omit ``context_length`` unless the+ caller supplied an explicit override; the returned context must come from LM Studio's echoed or+ refreshed state."""def _result(@@ -5542,9 +5204,9 @@ def lmstudio_model_reasoning_options() -> list[str]:"""Return the reasoning ``allowed_options`` LM Studio publishes for ``model``.- Pulls ``capabilities.reasoning.allowed_options`` from ``/api/v1/models``.- Returns ``[]`` when the model is unknown, the endpoint is unreachable,- or the model does not declare a reasoning capability.+ 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."""try:raw_models = _lmstudio_fetch_raw_models(api_key=api_key, base_url=base_url, timeout=timeout)@@ -5575,17 +5237,10 @@ def ollama_model_supports_thinking() -> Optional[bool]:"""Return True if an Ollama (Cloud or local) model advertises ``thinking``.- Probes the native ``/api/show`` endpoint and checks the ``capabilities``- list, which Ollama populates from the model's metadata (e.g.- ``deepseek-v4-pro`` → ``["completion", "tools", "thinking"]`` while- ``gemma3:27b`` → ``["completion", "vision"]``). This is the authoritative- capability source — the OpenAI-compat ``/v1/models`` endpoint omits it.-- Returns:- True — the model declares the ``thinking`` capability.- False — ``/api/show`` succeeded but the model has no ``thinking`` cap.- None — the probe failed (unreachable / non-Ollama / error); the caller- decides the fallback (we treat None as "don't emit").+ 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")."""import httpx@@ -5733,10 +5388,8 @@ def _github_reasoning_efforts_for_model_id(model_id: str) -> list[str]:def _should_use_copilot_responses_api(model_id: str) -> bool:"""Decide whether a Copilot model should use the Responses API.- Replicates opencode's ``shouldUseCopilotResponsesApi`` logic:- GPT-5+ models use Responses API, except ``gpt-5-mini`` which uses- Chat Completions. All non-GPT models (Claude, Gemini, etc.) use- Chat Completions.+ Replicates opencode's ``shouldUseCopilotResponsesApi``: GPT-5+ models use the Responses API+ except ``gpt-5-mini``; all non-GPT models (Claude, Gemini, ...) use Chat Completions."""import re@@ -5755,9 +5408,8 @@ def copilot_model_api_mode() -> str:"""Determine the API mode for a Copilot model.- Uses the model ID pattern (matching opencode's approach) as the- primary signal. Falls back to the catalog's ``supported_endpoints``- only for models not covered by the pattern check.+ Uses the model ID pattern (matching opencode's approach) as the primary signal. Falls back to+ the catalog's ``supported_endpoints`` only for models not covered by the pattern check."""# Fetch the catalog once so normalize + endpoint check share it# (avoids two redundant network calls for non-GPT-5 models).@@ -5800,16 +5452,8 @@ _AZURE_FOUNDRY_RESPONSES_PREFIXES = (def azure_foundry_model_api_mode(model_name: Optional[str]) -> Optional[str]:"""Infer Azure Foundry api_mode from a deployment/model name.- Returns ``"codex_responses"`` when the model name matches a family that- only accepts the Responses API on Azure Foundry (GPT-5.x, codex, o1/o3/o4- reasoning models). Returns ``None`` otherwise — the caller should fall- back to the configured/default api_mode (typically ``chat_completions``)- so GPT-4o, GPT-4 Turbo, Llama, Mistral, etc. keep working.-- Intentionally does NOT return ``anthropic_messages``; Anthropic-style- Azure endpoints are disambiguated by URL (``/anthropic`` suffix) in- ``runtime_provider._detect_api_mode_for_url`` and by the user setting- ``model.api_mode: anthropic_messages`` explicitly.+ Returns ``"codex_responses"`` when the model name matches a family that only accepts the+ Responses API on Azure Foundry (GPT-5.x, codex, o1/o3/o4 reasoning models)."""raw = str(model_name or "").strip().lower()if not raw:@@ -5829,16 +5473,8 @@ def azure_foundry_model_api_mode(model_name: Optional[str]) -> Optional[str]:def opencode_provider_family(provider_id: Optional[str]) -> Optional[str]:"""Resolve a provider id to its OpenCode family, or None.- Returns ``"opencode-zen"`` or ``"opencode-go"`` for the built-in- providers AND for custom providers whose name extends a family slug- (e.g. ``opencode-go-bridge`` pointing at ``https://opencode.ai/zen/go/v1``,- issue #85589). Matching is case-insensitive. Custom family providers- need the same per-model api_mode routing and /v1 base-url normalization- as the built-ins — this predicate is the single owner of that- family-membership question; do not re-implement it inline.-- ``opencode-go`` is checked before ``opencode-zen`` but the two slugs are- not prefixes of each other, so order is cosmetic.+ ``opencode-go`` is checked before ``opencode-zen`` but the two slugs are not prefixes of each+ other, so order is cosmetic."""raw = str(provider_id or "").strip().lower()if not raw:@@ -5901,28 +5537,12 @@ _opencode_free_live_memo: Optional[tuple[float, Optional[list[str]]]] = None_OPENCODE_FREE_LIVE_MEMO_TTL = 300.0 # 5 min; SWR disk cache handles the rest-def is_opencode_zen_free_model(model_id: Optional[str]) -> bool:- """True when ``model_id`` is an OpenCode Zen free-tier slug.-- Matches the ``*-free`` suffix plus the known unsuffixed free slugs- (``big-pickle``). Tolerates provider-prefixed ids- (``opencode-zen/x-preview-f-free``). The Go catalog serves no free- models (verified 2026-08-21), so this identifies the Zen free tier- across the OpenCode family.- """- bare = str(model_id or "").strip().rsplit("/", 1)[-1].lower()- if not bare:- return False- return bare.endswith("-free") or bare in _OPENCODE_KEYLESS_EXTRA_SLUGS--def opencode_zen_free_headers() -> dict:"""Client default_headers for anonymous OpenCode Zen free-tier requests.- ``Authorization: ""`` overrides the OpenAI SDK's ``Bearer <api_key>``- header so the placeholder key never reaches the wire — the Zen relay- accepts anonymous requests for free models but 401s any unknown bearer.- Attribution headers mirror the opencode provider profile.+ ``Authorization: ""`` overrides the OpenAI SDK's ``Bearer <api_key>`` header so the placeholder+ key never reaches the wire — the Zen relay accepts anonymous requests for free models but 401s+ any unknown bearer. Attribution headers mirror the opencode provider profile."""try:from hermes_cli import __version__ as _v@@ -5941,26 +5561,10 @@ def _fetch_opencode_free_models() -> Optional[list[str]]:"""Fetch the live keyless OpenCode Free catalog from the Zen relay.- GETs ``{_OPENCODE_ZEN_FREE_BASE_URL}/models`` ANONYMOUSLY (the free tier- rejects any unrecognized Authorization bearer with 401) and filters the- dump to the anonymous-servable ``*-free`` tier. Returns ``None`` on any- network/auth/parse failure so callers fall back to the curated- ``_PROVIDER_MODELS["opencode-free"]`` floor; an empty filtered result is- treated as a failure for the same reason (a relay with zero free models is- not worth trusting over the floor).-- A short in-process memo (``_OPENCODE_FREE_LIVE_MEMO_TTL``) keeps direct- ``provider_model_ids("opencode-free")`` callers — model validation runs- it several times per resolution — from issuing one blocking network- round-trip each. The picker's cross-process freshness still comes from- the SWR disk cache one layer up; ``force_refresh=True`` (the SWR refresh- path) bypasses and repopulates the memo.-- The Zen ``/models`` dump also lists paid/subscription IDs (e.g. Go- ``ox-alpha-free`` is KEYED despite the suffix), so a bare ``*-free`` suffix- filter is not safe on its own — this mirrors the existing- ``opencode_zen_free_runtime`` contract, which uses membership in the- verified keyless catalog as the routing criterion.+ The Zen ``/models`` dump also lists paid/subscription IDs (e.g. Go ``ox-alpha-free`` is KEYED+ despite the suffix), so a bare ``*-free`` suffix filter is not safe on its own — this mirrors+ the existing ``opencode_zen_free_runtime`` contract, which uses membership in the verified+ keyless catalog as the routing criterion."""import urllib.request@@ -6007,11 +5611,9 @@ def _set_opencode_free_live_memo(ids: Optional[list[str]]) -> None:def _opencode_free_known_model_slugs() -> set[str]:"""Lowercased keyless free-tier slugs known right now — WITHOUT network I/O.- Union of the static ``_PROVIDER_MODELS["opencode-free"]`` floor, the- in-process live memo, and the SWR disk-cache entry. Used by the- ``opencode_zen_free_runtime`` healing path, which runs during model- resolution and must never block on a live fetch. Union (not replacement)- so a stale cache can only widen healing, never silently disable it.+ Union of the static ``_PROVIDER_MODELS["opencode-free"]`` floor, the in-process live memo, and+ the SWR disk-cache entry. Used by the ``opencode_zen_free_runtime`` healing path, which runs+ during model resolution and must never block on a live fetch."""known = {m.lower() for m in _PROVIDER_MODELS.get("opencode-free", [])}memo = _opencode_free_live_memo@@ -6028,23 +5630,15 @@ def _opencode_free_known_model_slugs() -> set[str]:def opencode_zen_free_runtime(provider_id: Optional[str], model_id: Optional[str]) -> Optional[dict]:"""Keyless runtime entry for an OpenCode Zen free-tier model, or None.- Returns a resolve_runtime_provider-shaped dict pinning the request to the- Zen relay with the keyless placeholder whenever:-- - ``provider_id`` is ``opencode-free`` (the dedicated keyless provider —- EVERY model on it routes anonymously; that is the provider's contract), or- - ``provider_id`` is any other OpenCode-family provider and ``model_id``- is in the VERIFIED keyless catalog (``_PROVIDER_MODELS["opencode-free"]``)- — heals a free-model selection made under opencode-zen/opencode-go,- whose keys the free tier rejects.-- Membership, not the ``-free`` suffix, is the heal criterion: the suffix- stopped being a reliable keyless signal when ``ox-alpha-free`` appeared- on the Go relay as a KEYED subscription model (2026-08-21) — suffix-based- healing would have routed it to a Zen relay that doesn't serve it.- Membership means the union of the cached LIVE keyless catalog (in-process- memo / SWR disk cache — never a blocking fetch on this hot path) and the- static floor, so a newly-live free model heals without a release.+ - ``provider_id`` is ``opencode-free`` (the dedicated keyless provider — EVERY model on it+ routes anonymously; that is the provider's contract), or - ``provider_id`` is any other+ OpenCode-family provider and ``model_id`` is in the VERIFIED keyless catalog+ (``_PROVIDER_MODELS["opencode-free"]``) — heals a free-model selection made under opencode-+ zen/opencode-go, whose keys the free tier rejects.++ Membership means the union of the cached LIVE keyless catalog (in-process memo / SWR disk cache+ — never a blocking fetch on this hot path) and the static floor, so a newly-live free model+ heals without a release."""family = opencode_provider_family(provider_id)if family is None:@@ -6071,20 +5665,10 @@ def opencode_zen_free_runtime(provider_id: Optional[str], model_id: Optional[strdef opencode_model_api_mode(provider_id: Optional[str], model_id: Optional[str]) -> str:"""Determine the API mode for an OpenCode Zen / Go model.- OpenCode routes different models behind different API surfaces:-- - GPT-5 / Codex / Grok models on Zen use ``/v1/responses``- - GPT / Grok models on Go (gpt-5.6-luna, grok-4.5) use ``/v1/responses``- - Muse Spark on Go and Zen uses ``/v1/responses`` (chat/completions 503s)- - Claude models on Zen use ``/v1/messages``- - MiniMax and Qwen models on Go use ``/v1/messages``- - GLM / Kimi / DeepSeek / MiMo on Go use ``/v1/chat/completions``- - Qwen models on Zen use ``/v1/messages``- - Other Zen models (Gemini, GLM, Kimi, MiniMax, DeepSeek, etc.) use- ``/v1/chat/completions``-- This follows the published OpenCode docs for Zen and Go endpoints- (https://opencode.ai/docs/zen/ and https://opencode.ai/docs/go/).+ OpenCode routes models behind different surfaces per its Zen/Go docs: GPT/Codex/Grok and+ Muse Spark use ``/v1/responses`` (Muse Spark 503s on chat/completions); Claude and Qwen on+ Zen and MiniMax/Qwen on Go use ``/v1/messages``; everything else uses+ ``/v1/chat/completions``."""family = opencode_provider_family(provider_id)# opencode-free is Zen-hosted (the free tier lives on the Zen relay),@@ -6140,21 +5724,12 @@ def normalize_opencode_base_url() -> str:"""Normalize an OpenCode Zen / Go base URL for the target API mode.- OpenCode's OpenAI-compatible endpoints live under ``/v1`` (the OpenAI SDK- appends ``/chat/completions`` or ``/responses``), while the Anthropic SDK- appends its own ``/v1/messages`` — so anthropic_messages needs the ``/v1``- suffix stripped.-- Crucially this must be SYMMETRIC. The stripped URL gets persisted to- config (``model.base_url``) by the TUI/desktop and gateway after switching- into an anthropic-routed model (e.g. minimax-m2.7 on Go). A later switch- to a chat_completions model (glm, deepseek, kimi) then inherited the- stripped URL and POSTed to ``https://opencode.ai/zen/go/chat/completions``- — a 404 (the marketing site). Re-append ``/v1`` for non-anthropic modes- so previously-stripped URLs heal themselves.-- Only opencode.ai-hosted URLs are re-suffixed; custom proxy overrides via- ``OPENCODE_*_BASE_URL`` are left alone unless they already carry ``/v1``.+ Crucially this must be SYMMETRIC. The stripped URL gets persisted to config (``model.base_url``)+ by the TUI/desktop and gateway after switching into an anthropic-routed model (e.g. minimax-m2.7+ on Go).++ Only opencode.ai-hosted URLs are re-suffixed; custom proxy overrides via ``OPENCODE_*_BASE_URL``+ are left alone unless they already carry ``/v1``."""url = str(base_url or "").strip().rstrip("/")if not url:@@ -6233,10 +5808,9 @@ def probe_api_models() -> dict[str, Any]:"""Probe a ``/models`` endpoint with light URL heuristics.- For ``anthropic_messages`` mode, uses ``x-api-key`` and- ``anthropic-version`` headers (Anthropic's native auth) instead of- ``Authorization: Bearer``. The response shape (``data[].id``) is- identical, so the same parser works for both.+ For ``anthropic_messages`` mode, sends ``x-api-key`` and ``anthropic-version`` headers+ instead of ``Authorization: Bearer``; the response shape (``data[].id``) is identical so one+ parser serves both."""normalized = (base_url or "").strip().rstrip("/")if not normalized:@@ -6368,9 +5942,9 @@ def _fetch_deepinfra_catalog() -> Optional[list[dict]]:"""Fetch the raw DeepInfra catalog list with module-level caching.- The endpoint serves chat + embed + image-gen + tts + stt models in one- response. Authentication is optional but Bearer-attached when available- so user-scoped catalogs (private fine-tunes etc.) are visible.+ The endpoint serves chat, embed, image-gen, TTS and STT models in one response. Auth is+ optional but a Bearer token is attached when available so user-scoped catalogs (private+ fine-tunes) show."""cache_key, url = _deepinfra_catalog_url()if not force_refresh:@@ -6411,15 +5985,10 @@ def _fetch_deepinfra_models_by_tag() -> Optional[list[dict]]:"""Return DeepInfra models whose ``metadata.tags`` includes *tag*.- Each returned item is ``{"id": str, "metadata": dict}`` so callers can- inspect context length, pricing, default dimensions (image-gen),- pricing units (tts ``input_characters``, stt ``input_seconds``), etc.-- For the chat surface, items without any ``tags`` field fall through- to the legacy name-regex exclusion so this keeps working while the- tag rollout (mid-2026) is still in flight.-- Returns ``None`` on network failure.+ Each item is ``{"id", "metadata"}`` so callers can inspect context length, pricing and+ units. For the chat surface, items with no ``tags`` field fall through to the legacy name-+ regex exclusion so this keeps working while the tag rollout is in flight. Returns ``None``+ on network failure."""data = _fetch_deepinfra_catalog(timeout=timeout, force_refresh=force_refresh)if data is None:@@ -6461,10 +6030,9 @@ def _fetch_deepinfra_models() -> Optional[list[str]]:"""Return DeepInfra chat-model ids (tag-aware, regex fallback).- Thin wrapper over :func:`_fetch_deepinfra_models_by_tag` so historical- callers in :func:`provider_model_ids` keep their string-list contract.- Returns ``None`` on network failure, an empty list if the catalog- contains no chat-tagged ids (which would itself be surprising).+ Thin wrapper over :func:`_fetch_deepinfra_models_by_tag` so historical callers in+ :func:`provider_model_ids` keep their string-list contract. Returns ``None`` on network failure,+ an empty list if the catalog contains no chat-tagged ids (which would itself be surprising)."""items = _fetch_deepinfra_models_by_tag("chat", timeout=timeout, force_refresh=force_refresh@@ -6475,12 +6043,7 @@ def _fetch_deepinfra_models(def deepinfra_model_ids(tag: str, *, force_refresh: bool = False) -> list[str]:- """Return DeepInfra model ids carrying surface *tag* (``[]`` on failure).-- Single source of truth for the per-surface model shims (TTS/STT/vision),- replacing the copy-pasted ``import _fetch_deepinfra_models_by_tag → fetch- → [item["id"] …]`` wrapper each of them used to carry.- """+ """Return DeepInfra model ids carrying surface *tag* (``[]`` on failure)."""items = _fetch_deepinfra_models_by_tag(tag, force_refresh=force_refresh)return [item["id"] for item in items] if items else []@@ -6488,10 +6051,8 @@ def deepinfra_model_ids(tag: str, *, force_refresh: bool = False) -> list[str]:def deepinfra_base_url(section: Optional[dict] = None) -> str:"""Resolve the DeepInfra OpenAI-compatible base URL, normalized.- Precedence: config-section ``base_url`` → ``DEEPINFRA_BASE_URL`` env →- default. Always stripped with any trailing slash removed. Single source- of truth for the base-URL chain the TTS/STT/image/video shims each used- to re-code (with subtly divergent normalization).+ Precedence: config-section ``base_url`` → ``DEEPINFRA_BASE_URL`` env → default. Always stripped+ with any trailing slash removed."""candidate = section.get("base_url") if isinstance(section, dict) else Nonevalue = candidate or os.getenv("DEEPINFRA_BASE_URL") or _DEEPINFRA_DEFAULT_BASE_URL@@ -6505,12 +6066,9 @@ def _fetch_deepinfra_pricing() -> dict[str, dict[str, str]]:"""Return picker-shape pricing for DeepInfra chat models.- DeepInfra publishes ``input_tokens`` / ``output_tokens`` /- ``cache_read_tokens`` in $/MTok; the picker expects per-token strings- under ``prompt`` / ``completion`` / ``input_cache_read`` (mirrors the- OpenRouter shape consumed by- :func:`format_model_pricing_table`). Cached via the catalog helper so- repeated picker renders are free.+ DeepInfra publishes ``input_tokens``/``output_tokens``/``cache_read_tokens`` in $/MTok; the+ picker expects per-token strings under ``prompt``/``completion``/``input_cache_read``+ (OpenRouter shape). Cached via the catalog helper so repeated picker renders are free."""items = _fetch_deepinfra_models_by_tag("chat", timeout=timeout, force_refresh=force_refresh@@ -6576,11 +6134,7 @@ def fetch_api_models(api_mode: Optional[str] = None,headers: Optional[dict[str, str]] = None,) -> Optional[list[str]]:- """Fetch the list of available model IDs from the provider's ``/models`` endpoint.-- Returns a list of model ID strings, or ``None`` if the endpoint could not- be reached (network error, timeout, auth failure, etc.).- """+ """Fetch the list of available model IDs from the provider's ``/models`` endpoint."""return probe_api_models(api_key,base_url,@@ -6597,11 +6151,10 @@ def _custom_endpoint_fingerprint() -> str:"""Fingerprint the credentials/wire-shape used to probe a custom endpoint.- Custom OpenAI-compatible endpoints have no ``PROVIDER_REGISTRY`` slug to- key off (unlike ``_credential_fingerprint``), so this hashes exactly the- values callers pass to :func:`fetch_api_models`: a rotated ``api_key``, a- changed ``api_mode``, or an edited ``extra_headers`` block each bust the- cache entry on their own.+ Custom OpenAI-compatible endpoints have no ``PROVIDER_REGISTRY`` slug to key off (unlike+ ``_credential_fingerprint``), so this hashes exactly the values callers pass to+ :func:`fetch_api_models`: a rotated ``api_key``, a changed ``api_mode``, or an edited+ ``extra_headers`` block each bust the cache entry on their own."""import hashlib@@ -6623,10 +6176,9 @@ def _cache_entry_valid() -> "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. Empty model lists are valid only- for callers that explicitly opt into an authoritative empty catalog.+ 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. Empty+ model lists are valid only for callers that explicitly opt into an authoritative empty catalog."""return (isinstance(entry, dict)@@ -6651,22 +6203,9 @@ def cached_fetch_api_models() -> Optional[list[str]]:"""Disk-cached wrapper around :func:`fetch_api_models` for custom endpoints.- Mirrors :func:`cached_provider_model_ids` — including its- stale-while-revalidate tier — but keys ``provider_models_cache.json``- off ``custom:<base_url>`` instead of a ``PROVIDER_REGISTRY`` slug, since- custom endpoints (named ``custom_providers`` rows, bare- ``provider: custom``, and per-endpoint-map entries) have none. Same- stale-beats-nothing fallback policy: a live-fetch failure serves the- last same-fingerprint result rather than an empty list. Returns whatever- :func:`fetch_api_models` would (a list or ``None``); corrupt cache rows- degrade to a live fetch instead of raising.-- ``cache_only`` serves a previously-discovered catalog without touching- the network at all — no live fetch, no background revalidation — and- returns ``None`` when nothing usable is cached. Callers that deliberately- skip live probing for latency reasons (GUI picker opens, which must not- block on a stopped local endpoint) use this so a warm catalog still- reaches the picker instead of collapsing to the config-declared subset.+ Callers that deliberately skip live probing for latency reasons (GUI picker opens, which must+ not block on a stopped local endpoint) use this so a warm catalog still reaches the picker+ instead of collapsing to the config-declared subset."""normalized_url = str(base_url or "").strip().rstrip("/").lower()if not normalized_url:@@ -6736,16 +6275,15 @@ def cached_fetch_api_models(# ----------------------------------------------------------------------------_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.+ 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."""for suffix in (":cloud", "-cloud"):if model_id.endswith(suffix):@@ -6760,11 +6298,7 @@ def _ollama_cloud_cache_path() -> Path:def _load_ollama_cloud_cache(*, ignore_ttl: bool = False) -> Optional[dict]:- """Load cached Ollama Cloud models from disk.-- Args:- ignore_ttl: If True, return data even if the TTL has expired (stale fallback).- """+ """Load cached Ollama Cloud models from disk."""try:cache_path = _ollama_cloud_cache_path()if not cache_path.exists():@@ -6805,11 +6339,9 @@ def fetch_ollama_cloud_models() -> 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)+ 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)."""@@ -6873,17 +6405,11 @@ def validate_requested_model(api_mode: Optional[str] = None,headers: Optional[dict[str, str]] = None,) -> dict[str, Any]:- """- Validate a ``/model`` value for the active provider.-- Performs format checks first, then probes the live API to confirm- the model actually exists.+ """Validate a ``/model`` value for the active provider.- Returns a dict with:- - accepted: whether the CLI should switch to the requested model now- - persist: whether it is safe to save to config- - recognized: whether it matched a known provider catalog- - message: optional warning / guidance for the user+ Returns a dict with: - accepted: whether the CLI should switch to the requested model now -+ persist: whether it is safe to save to config - recognized: whether it matched a known provider+ catalog - message: optional warning / guidance for the user"""requested = (model_name or "").strip()normalized = normalize_provider(provider)diff --git a/hermes_cli/provider_catalog.py b/hermes_cli/provider_catalog.pyindex b7323894d14..d80e3dbe49c 100644--- a/hermes_cli/provider_catalog.py+++ b/hermes_cli/provider_catalog.py@@ -1,36 +1,16 @@"""Unified provider catalog — one source of truth for the provider universe.-The provider list shown by ``hermes model`` (CLI/TUI) and the desktop Settings-→ Providers tabs (Accounts + API keys) **must be the same set**. Historically-they were not: the CLI picker read :data:`hermes_cli.models.CANONICAL_PROVIDERS`-(which auto-extends from ``plugins/model-providers/<name>/``), while the desktop-tabs read separate hand-maintained lists (``_OAUTH_PROVIDER_CATALOG``,-``OPTIONAL_ENV_VARS`` + ``PROVIDER_GROUPS``) that nobody kept in sync. Every-provider added after those lists were written silently went missing from the-GUI — e.g. GitHub Copilot showing up only under "tools", or ``openai-api`` being-configurable from the CLI but not the desktop app.--This module fixes that at the root: it derives ONE descriptor per provider from-the same universe ``hermes model`` renders (``CANONICAL_PROVIDERS``), joining:+The provider list shown by ``hermes model`` (CLI/TUI) and the desktop Settings → Providers tabs+(Accounts + API keys) **must be the same set**. Every provider added after those lists were written+silently went missing from the GUI — e.g.* ``auth_type`` / ``api_key_env_vars`` / ``base_url_env_var`` from- :data:`hermes_cli.auth.PROVIDER_REGISTRY` (credential truth), and-* ``display_name`` / ``description`` / ``signup_url`` from the provider's- :class:`providers.base.ProviderProfile` when one exists, falling back to the- ``CANONICAL_PROVIDERS`` entry's ``label`` / ``tui_desc`` and the- ``OPTIONAL_ENV_VARS`` signup URL otherwise (many profiles leave these blank,- and four canonical providers have no profile at all — lmstudio, openai-api,- tencent-tokenhub, xai-oauth — so the fallbacks are load-bearing).--Each descriptor is tagged with the ``tab`` it belongs on (``keys`` vs-``accounts``) based purely on how the provider authenticates. The desktop-``/api/env`` and ``/api/providers/oauth`` endpoints derive their MEMBERSHIP from-this catalog; the old hand lists are demoted to presentation/override overlays-(bespoke OAuth flow + status resolvers, richer copy, icons, ordering) and no-longer decide which providers exist.--Parity contract (locked by tests): the union of the two tabs equals the-``CANONICAL_PROVIDERS`` universe, i.e. exactly what ``hermes model`` shows.+:data:`hermes_cli.auth.PROVIDER_REGISTRY` (credential truth), and * ``display_name`` /+``description`` / ``signup_url`` from the provider's :class:`providers.base.ProviderProfile` when+one exists, falling back to the ``CANONICAL_PROVIDERS`` entry's ``label`` / ``tui_desc`` and the+``OPTIONAL_ENV_VARS`` signup URL otherwise (many profiles leave these blank, and four canonical+providers have no profile at all — lmstudio, openai-api, tencent-tokenhub, xai-oauth — so the+fallbacks are load-bearing)."""from __future__ import annotations@@ -81,44 +61,39 @@ def _split_env_vars(env_vars: tuple[str, ...]) -> tuple[tuple[str, ...], str]:return keys, base-def provider_catalog() -> list[ProviderDescriptor]:- """Return one descriptor per provider in the ``hermes model`` universe.+def _safe_import(module: str, attr: str, default):+ """Import ``attr`` from ``module``; return ``default`` on ANY failure.- Membership is :data:`CANONICAL_PROVIDERS` (the list the CLI/TUI picker- renders, which auto-extends from provider plugins). Auth + env come from- ``PROVIDER_REGISTRY``; display metadata from ``ProviderProfile`` with- canonical/env fallbacks so providers without a profile (or with blank- profile metadata) still resolve sensibly.+ This module is on the import path of the web server and the CLI, and a+ provider-plugin import error must never blank the whole catalog."""- from hermes_cli.models import CANONICAL_PROVIDERS-- # PROVIDER_REGISTRY / list_providers are imported lazily and defensively:- # this module is on the import path of the web server and the CLI, and we- # never want a provider-plugin import error to blank the whole catalog.try:- from hermes_cli.auth import PROVIDER_REGISTRY+ return getattr(__import__(module, fromlist=[attr]), attr)except Exception:- PROVIDER_REGISTRY = {}+ return default- try:- from providers import list_providers- profiles = {p.name: p for p in list_providers()}- except Exception:- profiles = {}+def provider_catalog() -> list[ProviderDescriptor]:+ """Return one descriptor per provider in the ``hermes model`` universe.- try:- from hermes_cli.config import OPTIONAL_ENV_VARS- except Exception:- OPTIONAL_ENV_VARS = {}+ Membership is :data:`CANONICAL_PROVIDERS` (auto-extended by provider plugins). Auth/env come+ from ``PROVIDER_REGISTRY``; display metadata from ``ProviderProfile`` with canonical/env+ fallbacks so providers without a profile still resolve sensibly.+ """+ from hermes_cli.models import CANONICAL_PROVIDERS+ PROVIDER_REGISTRY = _safe_import("hermes_cli.auth", "PROVIDER_REGISTRY", {})+ OPTIONAL_ENV_VARS = _safe_import("hermes_cli.config", "OPTIONAL_ENV_VARS", {})# Hermes overlays carry auth_type for providers that have no registry/profile# entry of their own — notably the ``moa`` virtual provider (auth_type# "virtual"), which has no real credential and no network endpoint.+ HERMES_OVERLAYS = _safe_import("hermes_cli.providers", "HERMES_OVERLAYS", {})try:- from hermes_cli.providers import HERMES_OVERLAYS+ from providers import list_providers++ profiles = {p.name: p for p in list_providers()}except Exception:- HERMES_OVERLAYS = {}+ profiles = {}out: list[ProviderDescriptor] = []for order, entry in enumerate(CANONICAL_PROVIDERS):@@ -130,33 +105,25 @@ def provider_catalog() -> list[ProviderDescriptor]:# auth_type: registry is authoritative; fall back to profile, then the# Hermes overlay (e.g. moa → "virtual"), then api_key.auth_type = (- (getattr(cfg, "auth_type", "") if cfg else "")- or (getattr(prof, "auth_type", "") if prof else "")- or (getattr(overlay, "auth_type", "") if overlay else "")+ (cfg.auth_type if cfg else "")+ or (prof.auth_type if prof else "")+ or (overlay.auth_type if overlay else "")or "api_key")# Credential env vars: registry first (it already normalizes these),# else derive from the profile's env_vars tuple.- if cfg and getattr(cfg, "api_key_env_vars", ()):+ if cfg and cfg.api_key_env_vars:api_key_vars = tuple(cfg.api_key_env_vars)- base_url_var = getattr(cfg, "base_url_env_var", "") or ""- elif prof and getattr(prof, "env_vars", ()):+ base_url_var = cfg.base_url_env_var or ""+ elif prof and prof.env_vars:api_key_vars, base_url_var = _split_env_vars(tuple(prof.env_vars))else:api_key_vars, base_url_var = (), ""- label = (- (getattr(prof, "display_name", "") if prof else "")- or entry.label- or slug- )- description = (- (getattr(prof, "description", "") if prof else "")- or entry.tui_desc- or label- )- signup_url = (getattr(prof, "signup_url", "") if prof else "") or ""+ label = (prof.display_name if prof else "") or entry.label or slug+ description = (prof.description if prof else "") or entry.tui_desc or label+ signup_url = (prof.signup_url if prof else "") or ""if not signup_url and api_key_vars:info = OPTIONAL_ENV_VARS.get(api_key_vars[0]) or {}signup_url = info.get("url") or ""@@ -175,7 +142,7 @@ def provider_catalog() -> list[ProviderDescriptor]:# Keyless providers (e.g. opencode-free) are served# anonymously: there is no credential to configure, so the# GUI renders no key card and contract tests exempt them.- keyless=bool(getattr(overlay, "keyless", False)),+ keyless=bool(overlay.keyless) if overlay else False,))return outdiff --git a/hermes_cli/providers.py b/hermes_cli/providers.pyindex f3ecd99d221..306e433c896 100644--- a/hermes_cli/providers.py+++ b/hermes_cli/providers.py@@ -1,21 +1,4 @@-"""-Single source of truth for provider identity in Hermes Agent.--Two data sources, merged at runtime:--1. **models.dev catalog** — 109+ providers with base URLs, env vars, display- names, and full model metadata (context, cost, capabilities). This is- the primary database.--2. **Hermes overlays** — transport type, auth patterns, aggregator flags,- and additional env vars that models.dev doesn't track. Small dict,- maintained here.--3. **User config** (``providers:`` section in config.yaml) — user-defined- endpoints and overrides. Merged on top of everything else.--Other modules import from this file. No parallel registries.-"""+"""Single source of truth for provider identity in Hermes Agent."""from __future__ import annotations@@ -45,18 +28,9 @@ class HermesOverlay:HERMES_OVERLAYS: Dict[str, HermesOverlay] = {- "moa": HermesOverlay(- transport="openai_chat",- auth_type="virtual",- base_url_override="moa://local",- ),- "openrouter": HermesOverlay(- transport="openai_chat",- is_aggregator=True,- base_url_env_var="OPENROUTER_BASE_URL",- ),+ "moa": HermesOverlay(auth_type="virtual", base_url_override="moa://local"),+ "openrouter": HermesOverlay(is_aggregator=True, base_url_env_var="OPENROUTER_BASE_URL"),"nous": HermesOverlay(- transport="openai_chat",auth_type="oauth_device_code",base_url_override="https://inference-api.nousresearch.com/v1",),@@ -77,14 +51,11 @@ HERMES_OVERLAYS: Dict[str, HermesOverlay] = {base_url_env_var="XAI_BASE_URL",),"qwen-oauth": HermesOverlay(- transport="openai_chat",auth_type="oauth_external",base_url_override="https://portal.qwen.ai/v1",base_url_env_var="HERMES_QWEN_BASE_URL",),"lmstudio": HermesOverlay(- transport="openai_chat",- auth_type="api_key",extra_env_vars=("LM_API_KEY",),base_url_override="http://127.0.0.1:1234/v1",base_url_env_var="LM_BASE_URL",@@ -95,33 +66,22 @@ HERMES_OVERLAYS: Dict[str, HermesOverlay] = {base_url_override="acp://copilot",base_url_env_var="COPILOT_ACP_BASE_URL",),- "github-copilot": HermesOverlay(- transport="openai_chat",- extra_env_vars=("COPILOT_GITHUB_TOKEN", "GH_TOKEN"),- ),+ "github-copilot": HermesOverlay(extra_env_vars=("COPILOT_GITHUB_TOKEN", "GH_TOKEN")),"anthropic": HermesOverlay(transport="anthropic_messages",extra_env_vars=("ANTHROPIC_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"),),"zai": HermesOverlay(- transport="openai_chat",extra_env_vars=("GLM_API_KEY", "ZAI_API_KEY", "Z_AI_API_KEY"),base_url_env_var="GLM_BASE_URL",),- "kimi-for-coding": HermesOverlay(- transport="openai_chat",- base_url_env_var="KIMI_BASE_URL",- ),+ "kimi-for-coding": HermesOverlay(base_url_env_var="KIMI_BASE_URL"),"stepfun": HermesOverlay(- transport="openai_chat",extra_env_vars=("STEPFUN_API_KEY",),base_url_override="https://api.stepfun.ai/step_plan/v1",base_url_env_var="STEPFUN_BASE_URL",),- "minimax": HermesOverlay(- transport="anthropic_messages",- base_url_env_var="MINIMAX_BASE_URL",- ),+ "minimax": HermesOverlay(transport="anthropic_messages", base_url_env_var="MINIMAX_BASE_URL"),"minimax-oauth": HermesOverlay(transport="anthropic_messages",auth_type="oauth_external",@@ -131,89 +91,46 @@ HERMES_OVERLAYS: Dict[str, HermesOverlay] = {transport="anthropic_messages",base_url_env_var="MINIMAX_CN_BASE_URL",),- "deepseek": HermesOverlay(- transport="openai_chat",- base_url_env_var="DEEPSEEK_BASE_URL",- ),- "alibaba": HermesOverlay(- transport="openai_chat",- base_url_env_var="DASHSCOPE_BASE_URL",- ),- "alibaba-coding-plan": HermesOverlay(- transport="openai_chat",- base_url_env_var="ALIBABA_CODING_PLAN_BASE_URL",- ),- "vercel": HermesOverlay(- transport="openai_chat",- is_aggregator=True,- ),- "opencode": HermesOverlay(- transport="openai_chat",- is_aggregator=True,- base_url_env_var="OPENCODE_ZEN_BASE_URL",- ),- "opencode-go": HermesOverlay(- transport="openai_chat",- is_aggregator=True,- base_url_env_var="OPENCODE_GO_BASE_URL",- ),+ "deepseek": HermesOverlay(base_url_env_var="DEEPSEEK_BASE_URL"),+ "alibaba": HermesOverlay(base_url_env_var="DASHSCOPE_BASE_URL"),+ "alibaba-coding-plan": HermesOverlay(base_url_env_var="ALIBABA_CODING_PLAN_BASE_URL"),+ "vercel": HermesOverlay(is_aggregator=True),+ "opencode": HermesOverlay(is_aggregator=True, base_url_env_var="OPENCODE_ZEN_BASE_URL"),+ "opencode-go": HermesOverlay(is_aggregator=True, base_url_env_var="OPENCODE_GO_BASE_URL"),"opencode-free": HermesOverlay(- transport="openai_chat",is_aggregator=True,base_url_override="https://opencode.ai/zen/v1",keyless=True,),- "kilo": HermesOverlay(- transport="openai_chat",- is_aggregator=True,- base_url_env_var="KILOCODE_BASE_URL",- ),- "huggingface": HermesOverlay(- transport="openai_chat",- is_aggregator=True,- base_url_env_var="HF_BASE_URL",- ),- "novita": HermesOverlay(- transport="openai_chat",- is_aggregator=True,- base_url_env_var="NOVITA_BASE_URL",- ),+ "kilo": HermesOverlay(is_aggregator=True, base_url_env_var="KILOCODE_BASE_URL"),+ "huggingface": HermesOverlay(is_aggregator=True, base_url_env_var="HF_BASE_URL"),+ "novita": HermesOverlay(is_aggregator=True, base_url_env_var="NOVITA_BASE_URL"),"xai": HermesOverlay(transport="codex_responses",base_url_override="https://api.x.ai/v1",base_url_env_var="XAI_BASE_URL",),"nvidia": HermesOverlay(- transport="openai_chat",base_url_override="https://integrate.api.nvidia.com/v1",base_url_env_var="NVIDIA_BASE_URL",),- "xiaomi": HermesOverlay(- transport="openai_chat",- base_url_env_var="XIAOMI_BASE_URL",- ),- "tencent-tokenhub": HermesOverlay(- transport="openai_chat",- base_url_env_var="TOKENHUB_BASE_URL",- ),+ "xiaomi": HermesOverlay(base_url_env_var="XIAOMI_BASE_URL"),+ "tencent-tokenhub": HermesOverlay(base_url_env_var="TOKENHUB_BASE_URL"),"tencent-tokenplan": HermesOverlay(transport="anthropic_messages",base_url_override="https://api.lkeap.cloud.tencent.com/plan/anthropic",base_url_env_var="TOKENPLAN_BASE_URL",),"arcee": HermesOverlay(- transport="openai_chat",base_url_override="https://api.arcee.ai/api/v1",base_url_env_var="ARCEE_BASE_URL",),"gmi": HermesOverlay(- transport="openai_chat",extra_env_vars=("GMI_API_KEY",),base_url_override="https://api.gmi-serving.com/v1",base_url_env_var="GMI_BASE_URL",),"fireworks": HermesOverlay(- transport="openai_chat",extra_env_vars=("FIREWORKS_API_KEY",),base_url_override="https://api.fireworks.ai/inference/v1",),@@ -224,32 +141,23 @@ HERMES_OVERLAYS: Dict[str, HermesOverlay] = {base_url_env_var="ACTUAL_BASE_URL",),"upstage": HermesOverlay(- transport="openai_chat",extra_env_vars=("UPSTAGE_API_KEY",),base_url_override="https://api.upstage.ai/v1",base_url_env_var="UPSTAGE_BASE_URL",),"nebius-token-factory": HermesOverlay(- transport="openai_chat",extra_env_vars=("NEBIUS_API_KEY", "NEBIUS_TOKEN_FACTORY_API_KEY"),base_url_override="https://api.tokenfactory.nebius.com/v1",base_url_env_var="NEBIUS_BASE_URL",),"ollama-cloud": HermesOverlay(- transport="openai_chat",base_url_override="https://ollama.com/v1",base_url_env_var="OLLAMA_BASE_URL",),# Azure Foundry: supports both OpenAI-style and Anthropic-style endpoints.# The transport is determined at runtime from config.yaml model.api_mode.- "azure-foundry": HermesOverlay(- transport="openai_chat", # default; overridden by api_mode in config- base_url_env_var="AZURE_FOUNDRY_BASE_URL",- ),- "bedrock": HermesOverlay(- transport="bedrock_converse",- auth_type="aws_sdk",- ),+ "azure-foundry": HermesOverlay(base_url_env_var="AZURE_FOUNDRY_BASE_URL"), # openai_chat default; api_mode overrides+ "bedrock": HermesOverlay(transport="bedrock_converse", auth_type="aws_sdk"),# Vertex authenticates via OAuth2 (service-account JSON / ADC), not a# static API key or models.dev entry — resolved specially by# agent/vertex_adapter.py, like bedrock's aws_sdk. Without an overlay@@ -259,10 +167,7 @@ HERMES_OVERLAYS: Dict[str, HermesOverlay] = {# custom endpoint instead of "vertex" — losing the provider identity# that _refresh_provider_credentials() needs to re-mint an expired# OAuth2 token on a 401.- "vertex": HermesOverlay(- transport="openai_chat",- auth_type="vertex",- ),+ "vertex": HermesOverlay(auth_type="vertex"),}@@ -289,151 +194,46 @@ class ProviderDef:# Maps human-friendly / legacy names to canonical provider IDs.# Uses models.dev IDs where possible.-ALIASES: Dict[str, str] = {- # openrouter- "openai": "openrouter", # bare "openai" → route through aggregator-- # zai- "glm": "zai",- "z-ai": "zai",- "z.ai": "zai",- "zhipu": "zai",-- # xai- "x-ai": "xai",- "x.ai": "xai",- "grok": "xai",- "grok-oauth": "xai-oauth",- "xai-oauth": "xai-oauth",- "x-ai-oauth": "xai-oauth",- "xai-grok-oauth": "xai-oauth",-- # nvidia- "nim": "nvidia",- "nvidia-nim": "nvidia",- "build-nvidia": "nvidia",- "nemotron": "nvidia",-- # kimi-for-coding (models.dev ID)- "kimi": "kimi-for-coding",- "kimi-coding": "kimi-for-coding",- "kimi-coding-cn": "kimi-for-coding",- "moonshot": "kimi-for-coding",-- # stepfun- "step": "stepfun",- "stepfun-coding-plan": "stepfun",-- # minimax-cn- "minimax-china": "minimax-cn",- "minimax_cn": "minimax-cn",-- # anthropic- "claude": "anthropic",- "claude-code": "anthropic",-- # github-copilot (models.dev ID)- "copilot": "github-copilot",- "github": "github-copilot",- "github-copilot-acp": "copilot-acp",-- # vercel (models.dev ID for AI Gateway)- "ai-gateway": "vercel",- "aigateway": "vercel",- "vercel-ai-gateway": "vercel",-- # opencode (models.dev ID for OpenCode Zen)- "opencode-zen": "opencode",- "zen": "opencode",-- # opencode-go- "go": "opencode-go",- "opencode-go-sub": "opencode-go",-- # opencode-free- "free": "opencode-free",- "opencode_free": "opencode-free",-- # kilo (models.dev ID for KiloCode)- "kilocode": "kilo",- "kilo-code": "kilo",- "kilo-gateway": "kilo",-- # deepseek- "deep-seek": "deepseek",-- # alibaba- "dashscope": "alibaba",- "aliyun": "alibaba",- "qwen": "alibaba",- "alibaba-cloud": "alibaba",- "alibaba_coding": "alibaba-coding-plan",- "alibaba-coding": "alibaba-coding-plan",- "alibaba_coding_plan": "alibaba-coding-plan",-- # huggingface- "hf": "huggingface",- "hugging-face": "huggingface",- "huggingface-hub": "huggingface",-- # novita- "novita-ai": "novita",- "novitaai": "novita",-- # xiaomi- "mimo": "xiaomi",- "xiaomi-mimo": "xiaomi",-- # tencent- "tencent": "tencent-tokenhub",- "tokenhub": "tencent-tokenhub",- "tencent-cloud": "tencent-tokenhub",- "tencentmaas": "tencent-tokenhub",- "tokenplan": "tencent-tokenplan",- "tencent-lkeap": "tencent-tokenplan",-- # bedrock- "aws": "bedrock",- "aws-bedrock": "bedrock",- "amazon-bedrock": "bedrock",- "amazon": "bedrock",-- # arcee- "arcee-ai": "arcee",- "arceeai": "arcee",-- # gmi- "gmi-cloud": "gmi",- "gmicloud": "gmi",-- # fireworks- "fireworks-ai": "fireworks",- "fw": "fireworks",-- # upstage- "solar": "upstage",-- # Actual Computer- "actual-computer": "actual",- "actualcomputer": "actual",- "aci": "actual",- # Nebius Token Factory- "nebius": "nebius-token-factory",- "nebius-tokenfactory": "nebius-token-factory",- "nebius-tf": "nebius-token-factory",- "token-factory": "nebius-token-factory",- "tokenfactory": "nebius-token-factory",-- # Local server aliases → virtual "local" concept (resolved via user config)- "lmstudio": "lmstudio",- "lm-studio": "lmstudio",- "lm_studio": "lmstudio",- "ollama": "custom", # bare "ollama" = local; use "ollama-cloud" for cloud- "vllm": "local",- "llamacpp": "local",- "llama.cpp": "local",- "llama-cpp": "local",+# Aliases grouped by canonical provider id; ``ALIASES`` is the inverted lookup table.+_ALIAS_GROUPS: Dict[str, Tuple[str, ...]] = {+ "openrouter": ("openai",),+ "zai": ("glm", "z-ai", "z.ai", "zhipu"),+ "xai": ("x-ai", "x.ai", "grok"),+ "xai-oauth": ("grok-oauth", "xai-oauth", "x-ai-oauth", "xai-grok-oauth"),+ "nvidia": ("nim", "nvidia-nim", "build-nvidia", "nemotron"),+ "kimi-for-coding": ("kimi", "kimi-coding", "kimi-coding-cn", "moonshot"),+ "stepfun": ("step", "stepfun-coding-plan"),+ "minimax-cn": ("minimax-china", "minimax_cn"),+ "anthropic": ("claude", "claude-code"),+ "github-copilot": ("copilot", "github"),+ "copilot-acp": ("github-copilot-acp",),+ "vercel": ("ai-gateway", "aigateway", "vercel-ai-gateway"),+ "opencode": ("opencode-zen", "zen"),+ "opencode-go": ("go", "opencode-go-sub"),+ "opencode-free": ("free", "opencode_free"),+ "kilo": ("kilocode", "kilo-code", "kilo-gateway"),+ "deepseek": ("deep-seek",),+ "alibaba": ("dashscope", "aliyun", "qwen", "alibaba-cloud"),+ "alibaba-coding-plan": ("alibaba_coding", "alibaba-coding", "alibaba_coding_plan"),+ "huggingface": ("hf", "hugging-face", "huggingface-hub"),+ "novita": ("novita-ai", "novitaai"),+ "xiaomi": ("mimo", "xiaomi-mimo"),+ "tencent-tokenhub": ("tencent", "tokenhub", "tencent-cloud", "tencentmaas"),+ "tencent-tokenplan": ("tokenplan", "tencent-lkeap"),+ "bedrock": ("aws", "aws-bedrock", "amazon-bedrock", "amazon"),+ "arcee": ("arcee-ai", "arceeai"),+ "gmi": ("gmi-cloud", "gmicloud"),+ "fireworks": ("fireworks-ai", "fw"),+ "upstage": ("solar",),+ "actual": ("actual-computer", "actualcomputer", "aci"),+ "nebius-token-factory": (+ "nebius", "nebius-tokenfactory", "nebius-tf", "token-factory", "tokenfactory",+ ),+ "lmstudio": ("lmstudio", "lm-studio", "lm_studio"),+ "custom": ("ollama",),+ "local": ("vllm", "llamacpp", "llama.cpp", "llama-cpp"),}+ALIASES: Dict[str, str] = {alias: canon for canon, aliases in _ALIAS_GROUPS.items() for alias in aliases}# -- Display labels -----------------------------------------------------------@@ -476,11 +276,7 @@ TRANSPORT_TO_API_MODE: Dict[str, str] = {# -- Helper functions ---------------------------------------------------------def normalize_provider(name: str) -> str:- """Resolve aliases and normalise casing to a canonical provider id.-- Returns the canonical id string. Does *not* validate that the id- corresponds to a known provider.- """+ """Resolve aliases and normalise casing to a canonical provider id."""key = name.strip().lower()return ALIASES.get(key, key)@@ -488,16 +284,8 @@ def normalize_provider(name: str) -> str:def get_provider(name: str, *, allow_network: bool = True) -> Optional[ProviderDef]:"""Look up a built-in provider by id or alias.- Resolution order:- 1. Hermes overlays (for providers not in models.dev: nous, openai-codex, etc.)- 2. models.dev catalog + Hermes overlay-- User-defined providers from config.yaml (``providers:`` / ``custom_providers:``)- are resolved by :func:`resolve_provider_full`, which layers ``resolve_user_provider``- and ``resolve_custom_provider`` on top of this function. Callers that need- user-config support should use ``resolve_provider_full`` instead.-- Returns a fully-resolved ProviderDef or None.+ Resolution order: 1. Hermes overlays (for providers not in models.dev: nous, openai-codex, etc.)+ 2. models.dev catalog + Hermes overlay"""canonical = normalize_provider(name)@@ -517,29 +305,21 @@ def get_provider(name: str, *, allow_network: bool = True) -> Optional[ProviderDoverlay = HERMES_OVERLAYS.get(canonical)if mdev_info is not None:- # Merge models.dev + overlay- transport = overlay.transport if overlay else "openai_chat"- is_agg = overlay.is_aggregator if overlay else False- auth = overlay.auth_type if overlay else "api_key"- base_url_env = overlay.base_url_env_var if overlay else ""- base_url_override = overlay.base_url_override if overlay else ""-- # Combine env vars: models.dev env + hermes extra+ # Merge models.dev + overlay (defaults when no overlay); env vars = models.dev + hermes extra+ ov = overlay or HermesOverlay()env_vars = list(mdev_info.env)- if overlay and overlay.extra_env_vars:- for ev in overlay.extra_env_vars:- if ev not in env_vars:- env_vars.append(ev)-+ for ev in ov.extra_env_vars:+ if ev not in env_vars:+ env_vars.append(ev)return ProviderDef(id=canonical,name=mdev_info.name,- transport=transport,+ transport=ov.transport,api_key_env_vars=tuple(env_vars),- base_url=base_url_override or mdev_info.api,- base_url_env_var=base_url_env,- is_aggregator=is_agg,- auth_type=auth,+ base_url=ov.base_url_override or mdev_info.api,+ base_url_env_var=ov.base_url_env_var,+ is_aggregator=ov.is_aggregator,+ auth_type=ov.auth_type,doc=mdev_info.doc,source="models.dev",)@@ -608,8 +388,6 @@ def get_label(provider_id: str) -> str:return canonical--def is_aggregator(provider: str) -> bool:"""Return True when the provider is a multi-model aggregator."""provider_norm = normalize_provider(provider or "")@@ -637,16 +415,11 @@ _FLAT_NAMESPACE_RESELLERS: frozenset[str] = frozenset({def is_routing_aggregator(provider: str) -> bool:- """Return True only for TRUE routing aggregators (e.g. OpenRouter, named- ``custom:*`` proxies) — those that route bare/vendor-slugged model names- to *other* providers' endpoints.-- Distinct from :func:`is_aggregator`, which also reports True for- flat-namespace resellers (opencode-go/zen) whose catalog is entirely- first-party. Use this gate when the question is "would selecting this- model silently re-route the call away from the user's intended provider?"- — i.e. the picker dedup. Resellers answer no: their listed models are- their own, so their rows must not be deduped against user proxies.+ """True only for TRUE routing aggregators (OpenRouter, named ``custom:*`` proxies).++ Unlike ``is_aggregator``, excludes flat-namespace resellers (opencode-go/zen) whose catalog is+ first-party. Use for "would selecting this model silently re-route away from the intended+ provider?" -- i.e. picker dedup; reseller rows must not be deduped against user proxies."""provider_norm = normalize_provider(provider or "")if provider_norm in _FLAT_NAMESPACE_RESELLERS:@@ -657,20 +430,10 @@ def is_routing_aggregator(provider: str) -> bool:def is_official_openai_host(base_url: str) -> bool:"""True when *base_url* points at OpenAI's official API host family.- Matches the canonical host (``api.openai.com``) and OpenAI's documented- data-residency / regional hosts (``us.api.openai.com``,- ``eu.api.openai.com``, and any future ``<region>.api.openai.com``) —- those serve the same API surface with the same transport requirements- and the same access-scoped ``/v1/models`` listing.-Hostname-parsed matching only — never substring — so lookalike hosts- (``api.openai.com.attacker.test``) and path-segment spoofs- (``proxy.test/api.openai.com/v1``) are rejected. A genuine- ``*.api.openai.com`` subdomain requires control of openai.com DNS, so+ (``api.openai.com.attacker.test``) and path-segment spoofs (``proxy.test/api.openai.com/v1``)+ are rejected. A genuine ``*.api.openai.com`` subdomain requires control of openai.com DNS, sothe dot-suffix match does not reopen the #32243 spoofing hole.- Delegates to ``utils.base_url_host_matches``, which owns the- exact-or-dot-suffix hostname contract (userinfo/port stripped,- lowercased, trailing dot removed) — one implementation, not two."""return base_url_host_matches(base_url, "api.openai.com")@@ -678,25 +441,13 @@ def is_official_openai_host(base_url: str) -> bool:def host_mandated_api_mode(base_url: str = "") -> Optional[str]:"""Return the wire protocol a specific endpoint *requires*, or None.- Some hosts only accept one API mode and reject the others outright:- - api.openai.com only accepts the Responses API for its (reasoning)- models when tools + reasoning are in play (chat/completions 400s).- - api.meta.ai only achieves KV-cache hits on /v1/responses with- prompt_cache_retention; /v1/chat/completions returns 0 cached- tokens (measured 0% vs 93-99% on /responses with retention).- - api.router.com (Ramp Router) is Responses-native: per-model- reasoning-effort validation, reasoning summaries, and prompt- caching live on /v1/responses; /v1/chat/completions is only a- minimal compatibility shim translated onto it.- - api.anthropic.com / ``…/anthropic`` suffixes speak native Messages.- - Kimi's ``/coding`` endpoint speaks native Messages.- - AWS Bedrock runtime hosts speak Converse.-- These are *mandatory* — a session carrying a stale api_mode (e.g. a- /model switch that kept the previous provider's ``chat_completions``)- must be overridden to the host's required mode, not merely filled in- when empty. Generic / unknown endpoints return None so an explicitly- configured api_mode on them is never clobbered.+ Some hosts only accept one API mode and reject the others outright: - api.openai.com only+ accepts the Responses API for its (reasoning) models when tools + reasoning are in play+ (chat/completions 400s).++ These are *mandatory* — a session carrying a stale api_mode (e.g. a /model switch that kept the+ previous provider's ``chat_completions``) must be overridden to the host's required mode, not+ merely filled in when empty."""if not base_url:return None@@ -715,36 +466,30 @@ def host_mandated_api_mode(base_url: str = "") -> Optional[str]:# catalog filtering and listing authority.if is_official_openai_host(base_url):return "codex_responses"- # Meta Model API (api.meta.ai) only achieves prompt-cache hits on the- # Responses API with prompt_cache_retention; chat/completions stays- # cache-cold (0% vs 93-99% measured). Exact-hostname match per #32243.- if hostname == "api.meta.ai":- return "codex_responses"- # Ramp Router (api.router.com) is Responses-native: reasoning-effort- # validation, reasoning summaries, and prompt caching live on- # /v1/responses, and /v1/chat/completions is only a minimal- # compatibility shim (docs.router.com/api/endpoint). Exact-hostname- # match per #32243.- if hostname == "api.router.com":+ if hostname in _RESPONSES_NATIVE_HOSTS:return "codex_responses"if hostname.startswith("bedrock-runtime.") and base_url_host_matches(base_url, "amazonaws.com"):return "bedrock_converse"return None+# Exact hostnames (#32243) that are Responses-API-native:+# - api.meta.ai: Meta Model API only achieves prompt-cache hits on the Responses API with+# prompt_cache_retention; chat/completions stays cache-cold (0% vs 93-99% measured).+# - api.router.com: Ramp Router keeps reasoning-effort validation, reasoning summaries and prompt+# caching on /v1/responses; /v1/chat/completions is a minimal shim (docs.router.com/api/endpoint).+_RESPONSES_NATIVE_HOSTS: frozenset[str] = frozenset({"api.meta.ai", "api.router.com"})++def nous_api_mode(model: str = "") -> str:"""Resolve the wire protocol for a Nous Portal model.- Portal serves its ``anthropic/*`` catalog on a native Anthropic Messages- route (``/v1/messages``) alongside the OpenAI-compatible- ``/v1/chat/completions`` used by every other model it proxies. Claude- traffic goes to the native route so it gets Anthropic's own request shape- (inner-block ``cache_control`` breakpoints, thinking blocks) instead of the- OpenAI-wire translation.+ Portal serves its ``anthropic/*`` catalog on a native Anthropic Messages route+ (``/v1/messages``) alongside the OpenAI-compatible ``/v1/chat/completions`` used by every other+ model it proxies.- When *model* is empty/unknown, defaults to ``chat_completions`` — the- historical Nous transport — so callers that don't yet know the model- stay on the safer OpenAI-compatible path.+ When *model* is empty/unknown, defaults to ``chat_completions`` — the historical Nous transport+ — so callers that don't yet know the model stay on the safer OpenAI-compatible path."""if str(model or "").strip().lower().startswith("anthropic/"):return "anthropic_messages"@@ -754,15 +499,10 @@ def nous_api_mode(model: str = "") -> str:def determine_api_mode(provider: str, base_url: str = "", model: str = "") -> str:"""Determine the API mode (wire protocol) for a provider/endpoint.- Resolution order:- 1. Host-mandated mode (special endpoints that only accept one protocol).- 2. Nous Portal dual-wire (model-derived; overlay alone is openai_chat).- 3. Known provider → transport → TRANSPORT_TO_API_MODE.- 4. Direct provider checks (bedrock).- 5. Default: 'chat_completions'.-- *model* is optional but required for dual-wire providers (Nous) whose- transport depends on the catalog id, not just the provider/host.+ Resolution order: 1. Host-mandated mode (special endpoints that only accept one protocol). 2.+ Nous Portal dual-wire (model-derived; overlay alone is openai_chat). 3. Known provider →+ transport → TRANSPORT_TO_API_MODE. 4. Direct provider checks (bedrock). 5. Default:+ 'chat_completions'."""mandated = host_mandated_api_mode(base_url)if mandated is not None:@@ -790,15 +530,7 @@ def determine_api_mode(provider: str, base_url: str = "", model: str = "") -> st# -- Provider from user config ------------------------------------------------def resolve_user_provider(name: str, user_config: Dict[str, Any]) -> Optional[ProviderDef]:- """Resolve a provider from the user's config.yaml ``providers:`` section.-- Args:- name: Provider name as given by the user.- user_config: The ``providers:`` dict from config.yaml.-- Returns:- ProviderDef if found, else None.- """+ """Resolve a provider from the user's config.yaml ``providers:`` section."""if not user_config or not isinstance(user_config, dict):return None@@ -831,10 +563,9 @@ def resolve_user_provider(name: str, user_config: Dict[str, Any]) -> Optional[Prdef custom_provider_slug(display_name: str, provider_key: str = "") -> str:"""Build the stable ``custom:`` identity for a configured provider.- Keyed ``providers:`` entries keep their config key as the durable- identity even when their display name changes. Legacy- ``custom_providers:`` entries have no key, so their normalized display- name remains the identity.+ Keyed ``providers:`` entries use their config key so the identity survives display-name+ changes; legacy ``custom_providers:`` entries have no key, so their normalized display name+ remains the identity."""identity = str(provider_key or "").strip() or str(display_name or "").strip()normalized = identity.lower().replace(" ", "-")@@ -876,7 +607,7 @@ def resolve_custom_provider(# from a prior model-switch bug), fall back to the first custom# provider entry so existing configs self-heal. (GH #17478)bare_custom_fallback = requested == "custom"- first_valid: Optional[Tuple[str, str, Tuple[str, ...], str]] = None+ first_valid: Optional[ProviderDef] = Nonefor entry in custom_providers:if not isinstance(entry, dict):@@ -894,47 +625,27 @@ def resolve_custom_provider(key_env = (entry.get("key_env") or "").strip()provider_key = (entry.get("provider_key") or "").strip()- env_vars: List[str] = []- if key_env:- env_vars.append(key_env)-- # Stash the first valid entry for bare-"custom" fallback- if first_valid is None:- first_valid = (- display_name,- api_url,- tuple(env_vars),- custom_provider_slug(display_name, provider_key),- )-- slug = custom_provider_slug(display_name, provider_key)- if requested not in custom_provider_aliases(display_name, provider_key):- continue-- return ProviderDef(- id=slug,+ pdef = ProviderDef(+ id=custom_provider_slug(display_name, provider_key),name=display_name,transport="openai_chat",- api_key_env_vars=tuple(env_vars),+ api_key_env_vars=(key_env,) if key_env else (),base_url=api_url,is_aggregator=False,auth_type="api_key",source="user-config",)+ # Stash the first valid entry for bare-"custom" fallback+ if first_valid is None:+ first_valid = pdef++ if requested in custom_provider_aliases(display_name, provider_key):+ return pdef+# Self-heal: bare "custom" matched nothing — return first valid entryif bare_custom_fallback and first_valid:- dname, aurl, denv, slug = first_valid- return ProviderDef(- id=slug,- name=dname,- transport="openai_chat",- api_key_env_vars=denv,- base_url=aurl,- is_aggregator=False,- auth_type="api_key",- source="user-config",- )+ return first_validreturn None@@ -944,18 +655,7 @@ def resolve_provider_full(user_providers: Optional[Dict[str, Any]] = None,custom_providers: Optional[List[Dict[str, Any]]] = None,) -> Optional[ProviderDef]:- """Full resolution chain: built-in → models.dev → user config.-- This is the main entry point for --provider flag resolution.-- Args:- name: Provider name or alias.- user_providers: The ``providers:`` dict from config.yaml (optional).- custom_providers: The ``custom_providers:`` list from config.yaml (optional).-- Returns:- ProviderDef if found, else None.- """+ """Full resolution chain: built-in → models.dev → user config."""canonical = normalize_provider(name)raw = name.strip().lower()diff --git a/hermes_cli/runtime_provider.py b/hermes_cli/runtime_provider.pyindex bee78f192ef..2b4378f8582 100644--- a/hermes_cli/runtime_provider.py+++ b/hermes_cli/runtime_provider.py@@ -6,7 +6,8 @@ import loggingimport osimport refrom urllib.parse import urlparse-from typing import Any, Dict, Optional+from dataclasses import dataclass+from typing import Any, Callable, Dict, Optionallogger = logging.getLogger(__name__)@@ -49,15 +50,11 @@ from hermes_cli.providers import is_official_openai_hostdef load_config():"""Late-bound delegate to :func:`hermes_cli.config.load_config`.- Deliberately NOT a module-level ``from hermes_cli.config import- load_config``: this module is often imported lazily (inside functions),- so its first import can happen while a test has- ``hermes_cli.config.load_config`` patched — a from-import would then- bind the MagicMock *permanently*, poisoning every later caller in the- process (the mock's fixed config shadows the real one long after the- patch exits). Delegating at call time keeps both patch targets working:- patching ``hermes_cli.config.load_config`` OR- ``hermes_cli.runtime_provider.load_config`` behaves as expected.+ Deliberately NOT a module-level ``from hermes_cli.config import load_config``: this module is+ often imported lazily (inside functions), so its first import can happen while a test has+ ``hermes_cli.config.load_config`` patched — a from-import would then bind the MagicMock+ *permanently*, poisoning every later caller in the process (the mock's fixed config shadows the+ real one long after the patch exits)."""return _config_mod.load_config()@@ -76,11 +73,10 @@ from utils import base_url_host_matches, base_url_hostname, env_intdef _getenv(name: str, default: str = "") -> str:"""Profile-scoped replacement for ``os.getenv`` on credential/provider reads.- Routes through the secret scope (Workstream A): identical to ``os.getenv``- when multiplexing is off, scope-aware (and fail-closed on an unscoped read)- when on. Genuinely-global vars are handled inside ``get_secret`` and still- read ``os.environ``. Keeps the ``(name, default) -> str`` contract every- call site here already relies on.+ Routes through the secret scope: identical to ``os.getenv`` when multiplexing is off, scope-+ aware (and fail-closed on an unscoped read) when on. Genuinely-global vars are handled+ inside ``get_secret`` and still read ``os.environ``. Keeps the ``(name, default) -> str``+ contract."""val = _get_secret(name, default)return val if val is not None else default@@ -98,10 +94,10 @@ def _loopback_hostname(host: str) -> bool:def _config_base_url_trustworthy_for_bare_custom(cfg_base_url: str, cfg_provider: str) -> bool:"""Decide whether ``model.base_url`` may back bare ``custom`` runtime resolution.- GitHub #14676: the model picker can select Custom while ``model.provider`` still reflects a- previous provider. Reject non-loopback URLs unless the YAML provider is already ``custom``- (or one of the local-server aliases that resolve to ``custom`` — ollama, vllm, llamacpp, …),- so a stale OpenRouter/Z.ai base_url cannot hijack local ``custom`` sessions.+ The model picker can select Custom while ``model.provider`` still reflects a previous+ provider. Non-loopback URLs are rejected unless the YAML provider is already ``custom`` (or+ a local-server alias like ollama/vllm/llamacpp), so a stale OpenRouter/Z.ai base_url cannot+ hijack local ``custom`` sessions."""cfg_provider_norm = (cfg_provider or "").strip().lower()bu = (cfg_base_url or "").strip()@@ -109,73 +105,50 @@ def _config_base_url_trustworthy_for_bare_custom(cfg_base_url: str, cfg_providerreturn Falseif cfg_provider_norm == "custom":return True- # GitHub #27132: provider aliases that resolve to "custom" at runtime- # (ollama, vllm, llamacpp, …) should be trusted the same way "custom"- # is, otherwise a legit LAN/WireGuard ollama endpoint silently falls- # through to OpenRouter.- try:- from hermes_cli.auth import resolve_provider as _resolve_provider-- if _resolve_provider(cfg_provider_norm) == "custom":- return True- except Exception:- pass+ # Aliases resolving to "custom" (ollama, vllm, llamacpp, …) are trusted like "custom",+ # else a legit LAN/WireGuard ollama endpoint silently falls through to OpenRouter (#27132).+ if _resolves_to_custom(cfg_provider_norm):+ return Trueif base_url_host_matches(bu, "openrouter.ai"):return Falsereturn _loopback_hostname(base_url_hostname(bu))+# Hosts that only speak one wire protocol. Mirrors host_mandated_api_mode in+# hermes_cli/providers.py so the runtime resolver stays in lockstep.+# - api.meta.ai: prompt caching only on Responses API (0% on chat/completions).+# - api.router.com (Ramp Router): /v1/chat/completions is a minimal shim;+# reasoning and caching live on /v1/responses.+# - api.anthropic.com: native Messages API (realigns with providers.determine_api_mode).+_HOST_MANDATED_API_MODES = {+ "api.x.ai": "codex_responses",+ "api.meta.ai": "codex_responses",+ "api.actual.inc": "codex_responses",+ "api.router.com": "codex_responses",+ "api.anthropic.com": "anthropic_messages",+}++def _detect_api_mode_for_url(base_url: str) -> Optional[str]:"""Auto-detect api_mode from the resolved base URL.- - Direct api.openai.com endpoints need the Responses API for GPT-5.x- tool calls with reasoning (chat/completions returns 400).- - Direct api.anthropic.com endpoints must use the native Messages- API (``/v1/messages``). Anthropic also exposes an OpenAI-compat- ``/chat/completions`` shim on the same host, but Pro/Max OAuth- subscriptions are only billed against the native Messages route;- hitting the shim accounts against a separate "extra usage" pool- that is empty by default and surfaces as HTTP 400 "You're out of- extra usage." See issue #32243.- - Third-party Anthropic-compatible gateways (MiniMax, Zhipu GLM,- LiteLLM proxies, etc.) conventionally expose the native Anthropic- protocol under a ``/anthropic`` suffix — treat those as- ``anthropic_messages`` transport instead of the default- ``chat_completions``.- - Kimi Code's ``api.kimi.com/coding`` endpoint also speaks the- Anthropic Messages protocol (the /coding route accepts Claude- Code's native request shape).+ - Direct api.openai.com endpoints need the Responses API for GPT-5.x tool calls with reasoning+ (chat/completions returns 400). - Direct api.anthropic.com endpoints must use the native+ Messages API (``/v1/messages``)."""normalized = (base_url or "").strip().lower().rstrip("/")hostname = base_url_hostname(base_url)- if hostname == "api.x.ai":- return "codex_responses"+ # Exact-hostname matches reject lookalike subdomains (api.anthropic.com.attacker.test)+ # and path-segment spoofing (proxy.test/api.anthropic.com/v1) (#32243).+ mandated = _HOST_MANDATED_API_MODES.get(hostname)+ if mandated:+ return mandated# Official OpenAI host family: canonical api.openai.com plus the# data-residency regional hosts (us./eu.api.openai.com). Same API# surface, same Responses-API mandate. Shared predicate — see# providers.is_official_openai_host for the spoof-rejection contract.if is_official_openai_host(base_url):return "codex_responses"- # Meta Model API: prompt caching only on Responses API (0% on- # chat/completions vs 93-99% on /responses with retention). Exact- # hostname per #32243.- if hostname == "api.meta.ai":- return "codex_responses"- if hostname == "api.actual.inc":- return "codex_responses"- # Ramp Router: Responses-native host — /v1/chat/completions is only a- # minimal compatibility shim, while reasoning and caching support live- # on /v1/responses (docs.router.com/api/endpoint). Mirrors the- # host_mandated_api_mode clause in hermes_cli/providers.py so the- # runtime resolver stays in lockstep. Exact hostname per #32243.- if hostname == "api.router.com":- return "codex_responses"- # Direct native Anthropic host: realign with providers.determine_api_mode,- # which already maps this host to anthropic_messages. The exact-hostname- # match rejects lookalike subdomains (api.anthropic.com.attacker.test) and- # path-segment spoofing (proxy.test/api.anthropic.com/v1). (#32243)- if hostname == "api.anthropic.com":- return "anthropic_messages"path = urlparse(normalized).path.rstrip("/")if path.endswith("/anthropic") or path.endswith("/anthropic/v1"):return "anthropic_messages"@@ -187,19 +160,15 @@ def _detect_api_mode_for_url(base_url: str) -> Optional[str]:def _fallback_api_mode(provider: str, base_url: str, model: str = "") -> str:"""Resolve api_mode when no explicit/persisted mode applies.- Precedence: URL detection (host-mandated wire shapes) first, then the- transport the provider overlay itself declares via- ``providers.determine_api_mode`` — which already handles host mandates,- dual-wire providers, and the registry transport map — and only then the+ Precedence: URL detection (host-mandated wire shapes) first, then the transport the provider+ overlay itself declares via ``providers.determine_api_mode`` — which already handles host+ mandates, dual-wire providers, and the registry transport map — and only then the``chat_completions`` default for genuinely unknown providers/endpoints.- Before this helper the runtime paths consulted URL detection ONLY and- silently landed reasoning providers on ``chat_completions`` whenever the- hostname wasn't literally recognized. That is how ``openai-api`` pointed- at OpenAI's data-residency hosts (``us.api.openai.com``) 400'd on every- tool-calling turn: the provider declares ``codex_responses`` but the- declaration was never consulted. Same latent class covered the other- non-chat overlays (MiniMax family, copilot-acp).+ That is how ``openai-api`` pointed at OpenAI's data-residency hosts (``us.api.openai.com``)+ 400'd on every tool-calling turn: the provider declares ``codex_responses`` but the declaration+ was never consulted. Same latent class covered the other non-chat overlays (MiniMax family,+ copilot-acp)."""detected = _detect_api_mode_for_url(base_url)if detected:@@ -212,11 +181,8 @@ def _fallback_api_mode(provider: str, base_url: str, model: str = "") -> str:def _resolve_plain_custom_api_mode(model_cfg: Dict[str, Any], base_url: str) -> str:"""Resolve api_mode for legacy/plain ``provider: custom`` endpoints.- Custom endpoints should stay conservative by default. Only direct OpenAI/xAI- URLs imply Responses API automatically; named custom providers can opt in via- their own ``api_mode`` field. This also prevents a stale persisted- ``model.api_mode: codex_responses`` from forcing generic relays onto the- Responses path after upgrades or /reset.+ Custom endpoints should stay conservative by default. Only direct OpenAI/xAI URLs imply+ Responses API automatically; named custom providers can opt in via their own ``api_mode`` field."""configured_mode = _parse_api_mode(model_cfg.get("api_mode"))# Note: api.meta.ai is handled by _detect_api_mode_for_url (returns codex_responses), so the suppression guard below does not fire for Meta.@@ -235,21 +201,13 @@ def _resolve_plain_custom_api_mode(model_cfg: Dict[str, Any], base_url: str) ->def _host_derived_api_key(base_url: str) -> str:"""Look up `<VENDOR>_API_KEY` in the env, derived from the base URL host.- Examples:- https://api.deepseek.com/v1 → DEEPSEEK_API_KEY- https://api.groq.com/openai/v1 → GROQ_API_KEY- https://api.mistral.ai/v1 → MISTRAL_API_KEY- https://generativelanguage.googleapis.com/v1beta/openai/ → GOOGLEAPIS_API_KEY-- Returns the env value (stripped) or "". Never returns env vars whose names- are already explicitly checked elsewhere — those are handled by their own- host-gated paths (OPENAI/OPENROUTER/OLLAMA).-- The vendor label is the *registrable* portion of the hostname: strip- ``api.`` / ``www.`` prefixes, then take the second-to-last label- (``api.deepseek.com`` → ``deepseek``). Falls back to "" for hostnames- that don't yield a usable vendor label (IPs, loopback, single-label- hosts).+ Returns the env value (stripped) or "". Never returns env vars whose names are already+ explicitly checked elsewhere — those are handled by their own host-gated paths+ (OPENAI/OPENROUTER/OLLAMA).++ The vendor label is the *registrable* portion of the hostname: strip ``api.`` / ``www.``+ prefixes, then take the second-to-last label (``api.deepseek.com`` → ``deepseek``). Falls back+ to "" for hostnames that don't yield a usable vendor label (IPs, loopback, single-label hosts)."""hostname = base_url_hostname(base_url)if not hostname:@@ -266,17 +224,9 @@ def _host_derived_api_key(base_url: str) -> str:labels.pop(0)if len(labels) < 2:return ""- # Take the *registrable* label (second-to-last). For typical provider- # hosts this is what users intuitively call "the vendor":- # deepseek.com → labels[-2] = "deepseek" ✓- # api.groq.com → groq.com → labels[-2] = "groq" ✓- # api.mistral.ai → labels[-2] = "mistral" ✓- # Crucially, lookalike hosts pick the ATTACKER's label, not the spoofed- # vendor:- # api.deepseek.com.attacker.test → labels[-2] = "attacker"- # so DEEPSEEK_API_KEY stays put and the chain falls through to- # no-key-required. This mirrors how `base_url_host_matches` resists the- # same lookalike attack for explicit hosts.+ # Registrable (second-to-last) label = "the vendor" (api.groq.com → groq). Lookalike hosts+ # pick the ATTACKER's label (api.deepseek.com.attacker.test → "attacker"), so DEEPSEEK_API_KEY+ # stays put — mirrors how `base_url_host_matches` resists the same attack for explicit hosts.vendor = labels[-2]# Sanitize to env var charset: A-Z, 0-9, underscore.sanitized = "".join(ch if ch.isalnum() else "_" for ch in vendor).upper()@@ -292,16 +242,13 @@ def _host_derived_api_key(base_url: str) -> str:def _anthropic_base_url_override_ok(base_url: str) -> bool:"""Decide whether a configured ``model.base_url`` may back native Anthropic.- Native ``provider: anthropic`` resolution honors ``model.base_url`` so users- can point at Anthropic-compatible endpoints (official Anthropic/Claude hosts,- Azure Foundry, MiniMax/Zhipu/LiteLLM-style ``/anthropic`` proxies, Kimi's- ``/coding`` route). But a config can carry a *stale* non-Anthropic URL — e.g.- ``provider: anthropic`` left with ``base_url: https://openrouter.ai/api/v1``- after a provider switch — which would route Anthropic OAuth/setup-token- traffic to an OpenAI-compatible aggregator and 404. Ignore those.+ Native ``provider: anthropic`` resolution honors ``model.base_url`` so users can point at+ Anthropic-compatible endpoints (official Anthropic/Claude hosts, Azure Foundry,+ MiniMax/Zhipu/LiteLLM-style ``/anthropic`` proxies, Kimi's ``/coding`` route). But a config can+ carry a *stale* non-Anthropic URL — e.g.- Returns True only when the URL plausibly speaks the Anthropic Messages- protocol; otherwise the caller falls back to ``https://api.anthropic.com``.+ Returns True only when the URL plausibly speaks the Anthropic Messages protocol; otherwise the+ caller falls back to ``https://api.anthropic.com``."""candidate = (base_url or "").strip()if not candidate:@@ -319,11 +266,166 @@ def _anthropic_base_url_override_ok(base_url: str) -> bool:return True# Anthropic-compatible proxies conventionally expose the native Messages# protocol under a ``/anthropic`` suffix, and Kimi under ``/coding`` — same- # signal _detect_api_mode_for_url() uses to pick anthropic_messages.- if _detect_api_mode_for_url(candidate) == "anthropic_messages":- return True- # Bare api.kimi.com without the /coding path is not an Anthropic endpoint.- return False+ # signal _detect_api_mode_for_url() uses to pick anthropic_messages. Bare+ # api.kimi.com without the /coding path is not an Anthropic endpoint.+ return _detect_api_mode_for_url(candidate) == "anthropic_messages"+++_ANTHROPIC_DEFAULT_BASE_URL = "https://api.anthropic.com"+_NO_ANTHROPIC_CREDENTIALS_MSG = (+ "No Anthropic credentials found. Set ANTHROPIC_TOKEN or ANTHROPIC_API_KEY, "+ "run 'claude setup-token', or authenticate with 'claude /login'."+)+++def _runtime(provider: str, api_mode: str, base_url: Any, api_key: Any, **extra: Any) -> Dict[str, Any]:+ """Build a resolved-runtime dict; ``extra`` carries source/requested_provider/provider-specific keys."""+ return {"provider": provider, "api_mode": api_mode, "base_url": base_url, "api_key": api_key, **extra}+++def _cfg_provider(model_cfg: Dict[str, Any]) -> str:+ return str(model_cfg.get("provider") or "").strip().lower()+++def _config_base_url_for_provider(model_cfg: Dict[str, Any], provider: str) -> str:+ """``model.base_url`` (stripped, no trailing slash) only when ``model.provider`` is ``provider``.++ Prevents a stale base_url from a previously selected provider leaking into another one.+ """+ if _cfg_provider(model_cfg) != provider:+ return ""+ return str(model_cfg.get("base_url") or "").strip().rstrip("/")+++def _anthropic_cfg_base_url(model_cfg: Dict[str, Any]) -> str:+ """Config base_url for native Anthropic, or "" when absent/untrustworthy."""+ cfg_base_url = _config_base_url_for_provider(model_cfg, "anthropic")+ return cfg_base_url if _anthropic_base_url_override_ok(cfg_base_url) else ""+++def _resolves_to_custom(name: str) -> bool:+ """True when a provider alias (ollama, vllm, llamacpp, …) resolves to ``custom``."""+ try:+ return auth_mod.resolve_provider(name) == "custom"+ except Exception:+ return False+++def _host_gated_env_key_candidates(base_url: str, *, ollama: bool) -> list:+ """Env API keys gated on their authoritative hosts, then the host-derived ``<VENDOR>_API_KEY``.++ Sending OPENAI_API_KEY / OPENROUTER_API_KEY / OLLAMA_API_KEY to an unrelated endpoint leaks+ credentials (#28660, GHSA-76xc-57q6-vm5m); match on HOST, not substring. ``_host_derived_api_key``+ deliberately skips OLLAMA, so callers that want it opt in via ``ollama``.+ """+ is_openai = base_url_host_matches(base_url, "openai.com") or base_url_host_matches(base_url, "openai.azure.com")+ candidates = []+ if ollama:+ candidates.append(_getenv("OLLAMA_API_KEY", "").strip() if base_url_host_matches(base_url, "ollama.com") else "")+ candidates += [+ _getenv("OPENAI_API_KEY", "").strip() if is_openai else "",+ _getenv("OPENROUTER_API_KEY", "").strip() if base_url_host_matches(base_url, "openrouter.ai") else "",+ _host_derived_api_key(base_url),+ ]+ return candidates+++def _pool_entry_api_key(entry: Any) -> str:+ return getattr(entry, "runtime_api_key", None) or getattr(entry, "access_token", "")+++def _pool_entry_base_url(entry: Any) -> str:+ return getattr(entry, "runtime_base_url", None) or getattr(entry, "base_url", None) or ""+++def _nous_pool_state(entry: Any) -> Dict[str, Any]:+ return {+ "agent_key": getattr(entry, "agent_key", None),+ "agent_key_expires_at": getattr(entry, "agent_key_expires_at", None),+ "scope": getattr(entry, "scope", None),+ }+++def _registry_base_url(provider: str) -> str:+ pconfig = PROVIDER_REGISTRY.get(provider)+ return pconfig.inference_base_url if pconfig else ""+++def _azure_inferred_api_mode(effective_model: str, api_mode: str) -> str:+ """Upgrade api_mode for GPT-5.x / codex / o1-o4 deployments on Azure Foundry.++ Azure rejects /chat/completions on these with 400 "operation unsupported" (see+ ``azure_foundry_model_api_mode``). Skipped when the user explicitly picked anthropic_messages.+ """+ if not effective_model or api_mode == "anthropic_messages":+ return api_mode+ try:+ from hermes_cli.models import azure_foundry_model_api_mode++ inferred = azure_foundry_model_api_mode(effective_model)+ except Exception:+ inferred = None+ return inferred or api_mode+++def _configured_or_fallback_api_mode(+ provider: str,+ model_cfg: Dict[str, Any],+ base_url: str,+ effective_model: Any,+ *,+ opencode_by_model: bool,+) -> str:+ """Persisted ``model.api_mode`` when it belongs to this provider, else URL/transport fallback.++ OpenCode Zen/Go serve both anthropic_messages and chat_completions models, so (when+ ``opencode_by_model``) their mode is always re-derived from the effective model rather than+ the stale persisted api_mode (#16878).+ """+ if opencode_by_model:+ from hermes_cli.models import opencode_provider_family++ if opencode_provider_family(provider) is not None:+ from hermes_cli.models import opencode_model_api_mode++ return opencode_model_api_mode(provider, effective_model)+ configured_mode = _parse_api_mode(model_cfg.get("api_mode"))+ if configured_mode and _provider_supports_explicit_api_mode(provider, _cfg_provider(model_cfg)):+ return configured_mode+ # URL detection first (Anthropic /anthropic suffix, Kimi /coding, official+ # OpenAI hosts / api.x.ai → codex_responses), then the provider's declared transport.+ return _fallback_api_mode(provider, base_url, effective_model)+++def _api_key_provider_api_mode(+ provider: str,+ model_cfg: Dict[str, Any],+ api_key: str,+ base_url: str,+ effective_model: Any,+ *,+ opencode_by_model: bool,+) -> str:+ """api_mode for a registry ``api_key`` provider (explicit and env/config paths)."""+ if provider == "copilot":+ return _copilot_runtime_api_mode(model_cfg, api_key, target_model=effective_model)+ if provider in ("xai", "actual"):+ return "codex_responses"+ return _configured_or_fallback_api_mode(+ provider, model_cfg, base_url, effective_model, opencode_by_model=opencode_by_model+ )+++def _normalize_opencode_runtime_base_url(provider: str, api_mode: str, base_url: str) -> str:+ """OpenCode base URLs end with /v1 for OpenAI-compatible models, but the Anthropic SDK+ prepends its own /v1/messages: strip /v1 for anthropic_messages, re-append otherwise."""+ from hermes_cli.models import opencode_provider_family++ if opencode_provider_family(provider) is None:+ return base_url+ from hermes_cli.models import normalize_opencode_base_url++ return normalize_opencode_base_url(provider, api_mode, base_url)def _auto_detect_local_model(base_url: str) -> str:@@ -384,10 +486,9 @@ def _get_model_config() -> Dict[str, Any]:def _provider_supports_explicit_api_mode(provider: Optional[str], configured_provider: Optional[str] = None) -> bool:"""Check whether a persisted api_mode should be honored for a given provider.- Prevents stale api_mode from a previous provider leaking into a- different one after a model/provider switch. Only applies the- persisted mode when the config's provider matches the runtime- provider (or when no configured provider is recorded).+ Prevents stale api_mode from a previous provider leaking into a different one after a+ model/provider switch. Only applies the persisted mode when the config's provider matches the+ runtime provider (or when no configured provider is recorded)."""normalized_provider = (provider or "").strip().lower()normalized_configured = (configured_provider or "").strip().lower()@@ -409,12 +510,9 @@ def _copilot_runtime_api_mode(if configured_mode and _provider_supports_explicit_api_mode("copilot", configured_provider):return configured_mode- # Use the model being resolved for this runtime, not the persisted global- # default. MoA slots, fallback models, and mid-session model switches all- # resolve credentials for a target model that can differ from config.yaml's- # model.default. If we derive Copilot api_mode from the stale default, a- # Claude/Gemini MoA slot can inherit codex_responses from a GPT-5 default and- # fail with "model ... does not support Responses API".+ # Use the model being resolved, not the persisted default: MoA slots / fallbacks / mid-session+ # switches target a different model, and a Claude slot inheriting codex_responses from a+ # GPT-5 default fails with "model ... does not support Responses API".model_name = str(target_model or model_cfg.get("default") or "").strip()if not model_name:return "chat_completions"@@ -432,11 +530,8 @@ _VALID_API_MODES = {"codex_responses","anthropic_messages","bedrock_converse",- # Optional opt-in: hand the entire turn to a `codex app-server` subprocess- # so terminal/file-ops/patching/sandboxing run inside Codex's own runtime- # instead of Hermes' tool dispatch. Gated behind config key- # `model.openai_runtime == "codex_app_server"` AND provider in- # {"openai", "openai-codex"}. Default is unchanged.+ # Opt-in: hand the whole turn to a `codex app-server` subprocess (Codex's own tool runtime).+ # Gated on `model.openai_runtime == "codex_app_server"` AND provider in {openai, openai-codex}."codex_app_server",}@@ -444,10 +539,9 @@ _VALID_API_MODES = {def _parse_api_mode(raw: Any) -> Optional[str]:"""Validate an api_mode value from config. Returns None if invalid.- Legacy/alias spellings (``openai``, ``anthropic``, ``responses``, …) are- canonicalized via the shared alias map before validation, so configs- written against older releases keep selecting the transport they named- instead of silently falling through to hostname-based detection.+ Legacy/alias spellings (``openai``, ``anthropic``, ``responses``, …) are canonicalized via the+ shared alias map before validation, so configs written against older releases keep selecting the+ transport they named instead of silently falling through to hostname-based detection."""if isinstance(raw, str):from hermes_cli.config import _canonical_api_mode@@ -461,10 +555,9 @@ def _parse_api_mode(raw: Any) -> Optional[str]:def _nous_inference_base_url_override() -> str:"""Return the trusted Nous runtime base URL override, if configured.- Delegates to ``auth._nous_inference_env_override`` so every- ``NOUS_INFERENCE_BASE_URL`` read shares one normalization path- (trailing-slash stripping, blank → empty). The env source is trusted- and intentionally bypasses the network host allowlist there.+ Delegates to ``auth._nous_inference_env_override`` so every ``NOUS_INFERENCE_BASE_URL`` read+ shares one normalization path. The env source is trusted and intentionally bypasses the+ network host allowlist."""return _nous_inference_env_override() or ""@@ -475,16 +568,12 @@ def _maybe_apply_codex_app_server_runtime(api_mode: str,model_cfg: Optional[Dict[str, Any]],) -> str:- """Optional opt-in: rewrite api_mode → "codex_app_server" for OpenAI/Codex- providers when the user has explicitly enabled that runtime via- `model.openai_runtime: codex_app_server` in config.yaml.-- Default behavior is preserved: when the key is unset, "auto", or empty,- this function is a no-op. Only providers in {"openai", "openai-codex"}- are eligible — other providers (anthropic, openrouter, etc.) cannot be- rerouted through codex.+ """Opt-in rewrite of api_mode → "codex_app_server" via ``model.openai_runtime`` in config.yaml.- Returns the (possibly-rewritten) api_mode."""+ No-op when ``model.openai_runtime`` is unset, "auto", or empty. Only ``openai`` and+ ``openai-codex`` are eligible — other providers cannot be rerouted through codex. Returns+ the (possibly rewritten) api_mode.+ """if not model_cfg:return api_modeif provider not in {"openai", "openai-codex"}:@@ -495,6 +584,20 @@ def _maybe_apply_codex_app_server_runtime(return api_mode+# Pool-entry providers whose api_mode is fixed: provider -> (api_mode, default base_url when the+# pool entry carries none). Callables are evaluated lazily (registry lookups). MiniMax OAuth tokens+# are valid only against the Anthropic Messages endpoint, so a stale model.api_mode from a prior+# OpenAI-compatible provider is never honoured for it (it would 404 on /chat/completions).+_POOL_ENTRY_SIMPLE_MODES: Dict[str, tuple] = {+ "openai-codex": ("codex_responses", DEFAULT_CODEX_BASE_URL),+ "xai-oauth": ("codex_responses", DEFAULT_XAI_OAUTH_BASE_URL),+ "qwen-oauth": ("chat_completions", DEFAULT_QWEN_BASE_URL),+ "minimax-oauth": ("anthropic_messages", lambda: _registry_base_url("minimax-oauth")),+ "openrouter": ("chat_completions", OPENROUTER_BASE_URL),+ "xai": ("codex_responses", ""),+}++def _resolve_runtime_from_pool_entry(*,provider: str,@@ -505,50 +608,20 @@ def _resolve_runtime_from_pool_entry(target_model: Optional[str] = None,) -> Dict[str, Any]:model_cfg = model_cfg or _get_model_config()- # When the caller is resolving for a specific target model (e.g. a /model- # mid-session switch), prefer that over the persisted model.default. This- # prevents api_mode being computed from a stale config default that no- # longer matches the model actually being used — the bug that caused- # opencode-zen /v1 to be stripped for chat_completions requests when- # config.default was still a Claude model.+ # Prefer the caller's target model (e.g. /model switch) over the persisted default, else+ # api_mode is computed from a stale default (opencode-zen /v1 stripped while config.default+ # was still a Claude model).effective_model = (target_model or model_cfg.get("default") or "")- base_url = (getattr(entry, "runtime_base_url", None) or getattr(entry, "base_url", None) or "").rstrip("/")- api_key = getattr(entry, "runtime_api_key", None) or getattr(entry, "access_token", "")- api_mode = "chat_completions"- if provider == "openai-codex":- api_mode = "codex_responses"- base_url = base_url or DEFAULT_CODEX_BASE_URL- elif provider == "xai-oauth":- api_mode = "codex_responses"- base_url = base_url or DEFAULT_XAI_OAUTH_BASE_URL- elif provider == "qwen-oauth":- api_mode = "chat_completions"- base_url = base_url or DEFAULT_QWEN_BASE_URL- elif provider == "minimax-oauth":- # MiniMax OAuth tokens are valid only against the Anthropic Messages- # compatible endpoint. Do not honor stale model.api_mode values from a- # prior OpenAI-compatible provider, or the client will hit- # /chat/completions under /anthropic and receive a bare nginx 404.- api_mode = "anthropic_messages"- pconfig = PROVIDER_REGISTRY.get(provider)- base_url = base_url or (pconfig.inference_base_url if pconfig else "")+ base_url = _pool_entry_base_url(entry).rstrip("/")+ api_key = _pool_entry_api_key(entry)+ if provider in _POOL_ENTRY_SIMPLE_MODES:+ api_mode, default_url = _POOL_ENTRY_SIMPLE_MODES[provider]+ base_url = base_url or (default_url() if callable(default_url) else default_url)elif provider == "anthropic":api_mode = "anthropic_messages"- cfg_provider = str(model_cfg.get("provider") or "").strip().lower()- cfg_base_url = ""- if cfg_provider == "anthropic":- cfg_base_url = str(model_cfg.get("base_url") or "").strip().rstrip("/")- if not _anthropic_base_url_override_ok(cfg_base_url):- cfg_base_url = ""- base_url = cfg_base_url or base_url or "https://api.anthropic.com"- elif provider == "openrouter":- base_url = base_url or OPENROUTER_BASE_URL- elif provider == "xai":- api_mode = "codex_responses"+ base_url = _anthropic_cfg_base_url(model_cfg) or base_url or _ANTHROPIC_DEFAULT_BASE_URLelif provider == "nous":- from hermes_cli.providers import nous_api_mode-- api_mode = nous_api_mode(effective_model)+ api_mode = _nous_api_mode(effective_model)base_url = _nous_inference_base_url_override() or base_urlelif provider == "copilot":api_mode = _copilot_runtime_api_mode(@@ -559,70 +632,26 @@ def _resolve_runtime_from_pool_entry(base_url = base_url or PROVIDER_REGISTRY["copilot"].inference_base_urlelif provider == "azure-foundry":# Azure Foundry: read api_mode and base_url from config- cfg_provider = str(model_cfg.get("provider") or "").strip().lower()- if cfg_provider == "azure-foundry":- cfg_base_url = str(model_cfg.get("base_url") or "").strip().rstrip("/")- if cfg_base_url:- base_url = cfg_base_url- configured_mode = _parse_api_mode(model_cfg.get("api_mode"))- if configured_mode:- api_mode = configured_mode- # Model-family inference for GPT-5.x / codex / o1-o4: Azure rejects- # /chat/completions on these with 400 "operation unsupported" — see- # azure_foundry_model_api_mode() for rationale. Skip when the user- # explicitly picked anthropic_messages (Anthropic-style endpoint).- if effective_model and api_mode != "anthropic_messages":- try:- from hermes_cli.models import azure_foundry_model_api_mode-- inferred = azure_foundry_model_api_mode(effective_model)- except Exception:- inferred = None- if inferred:- api_mode = inferred+ api_mode = "chat_completions"+ if _cfg_provider(model_cfg) == "azure-foundry":+ base_url = _config_base_url_for_provider(model_cfg, "azure-foundry") or base_url+ api_mode = _parse_api_mode(model_cfg.get("api_mode")) or api_mode+ api_mode = _azure_inferred_api_mode(effective_model, api_mode)# For Anthropic-style endpoints, strip /v1 suffixif api_mode == "anthropic_messages":base_url = re.sub(r"/v1/?$", "", base_url)else:- configured_provider = str(model_cfg.get("provider") or "").strip().lower()- # Honour model.base_url from config.yaml when the configured provider- # matches this provider — same pattern as the Anthropic branch above.- # Only override when the pool entry has no explicit base_url (i.e. it- # fell back to the hardcoded default). Env var overrides win (#6039).+ # Honour model.base_url only when the pool entry carries no explicit base_url (i.e. it+ # fell back to the registry default). Env var overrides win (#6039).pconfig = PROVIDER_REGISTRY.get(provider)pool_url_is_default = pconfig and base_url.rstrip("/") == pconfig.inference_base_url.rstrip("/")- if configured_provider == provider and pool_url_is_default:- cfg_base_url = str(model_cfg.get("base_url") or "").strip().rstrip("/")- if cfg_base_url:- base_url = cfg_base_url- configured_mode = _parse_api_mode(model_cfg.get("api_mode"))- from hermes_cli.models import opencode_provider_family- if opencode_provider_family(provider) is not None:- # Re-derive api_mode from the effective model rather than the- # persisted api_mode: the opencode providers serve both- # anthropic_messages and chat_completions models, so the previous- # session's mode must not leak across /model switches.- # Refs #16878.- from hermes_cli.models import opencode_model_api_mode- api_mode = opencode_model_api_mode(provider, effective_model)- elif configured_mode and _provider_supports_explicit_api_mode(provider, configured_provider):- api_mode = configured_mode- else:- # URL detection first (Anthropic /anthropic suffix, Kimi /coding,- # official OpenAI hosts → codex_responses, api.x.ai →- # codex_responses), then the provider's own declared transport.- api_mode = _fallback_api_mode(provider, base_url, effective_model)-- # OpenCode base URLs end with /v1 for OpenAI-compatible models, but the- # Anthropic SDK prepends its own /v1/messages to the base_url. Normalize- # symmetrically: strip /v1 for anthropic_messages, re-append it for- # chat_completions / codex_responses (heals a stripped URL persisted to- # model.base_url by an earlier switch into an anthropic-routed model).- from hermes_cli.models import opencode_provider_family- if opencode_provider_family(provider) is not None:- from hermes_cli.models import normalize_opencode_base_url+ if pool_url_is_default:+ base_url = _config_base_url_for_provider(model_cfg, provider) or base_url+ api_mode = _configured_or_fallback_api_mode(+ provider, model_cfg, base_url, effective_model, opencode_by_model=True+ )- base_url = normalize_opencode_base_url(provider, api_mode, base_url)+ base_url = _normalize_opencode_runtime_base_url(provider, api_mode, base_url)# Optional opt-in: route OpenAI/Codex turns through `codex app-server`.# Inert when `model.openai_runtime` is unset or "auto".@@ -633,15 +662,15 @@ def _resolve_runtime_from_pool_entry(if provider == "lmstudio":base_url = auth_mod._normalize_lmstudio_runtime_base_url(base_url)- return {- "provider": provider,- "api_mode": api_mode,- "base_url": base_url,- "api_key": api_key,- "source": getattr(entry, "source", "pool"),- "credential_pool": pool,- "requested_provider": requested_provider,- }+ return _runtime(+ provider,+ api_mode,+ base_url,+ api_key,+ source=getattr(entry, "source", "pool"),+ credential_pool=pool,+ requested_provider=requested_provider,+ )def resolve_requested_provider(requested: Optional[str] = None) -> str:@@ -670,20 +699,12 @@ def _try_resolve_from_custom_pool(provider_name: Optional[str] = None,) -> Optional[Dict[str, Any]]:"""Check if a credential pool exists for a custom endpoint and return a runtime dict if so."""- candidates: list[str] = []- seen = set()-- def _add(key: Optional[str]) -> None:- normalized = str(key or "").strip().lower()- if normalized and normalized not in seen:- seen.add(normalized)- candidates.append(normalized)-try:- for key in custom_provider_pool_key_candidates(base_url, provider_name):- _add(key)+ raw_keys = list(custom_provider_pool_key_candidates(base_url, provider_name))except Exception:- pass+ raw_keys = []+ # Order-preserving dedupe of normalized keys.+ candidates = list(dict.fromkeys(k for k in (str(key or "").strip().lower() for key in raw_keys) if k))if not candidates:return None@@ -695,29 +716,23 @@ def _try_resolve_from_custom_pool(entry = pool.select()if entry is None:continue- pool_api_key = getattr(entry, "runtime_api_key", None) or getattr(entry, "access_token", "")+ pool_api_key = _pool_entry_api_key(entry)if not pool_api_key:continueif not has_usable_secret(pool_api_key) and _loopback_hostname(base_url_hostname(base_url)):- # Legacy configs commonly used short/placeholder keys ('123',- # 'm', ...) for local no-auth services like Ollama -- fine for- # the endpoint itself, but has_usable_secret's 4-char floor- # (added after these configs were written) now rejects them- # here with no migration path. Every OTHER resolution path in- # this file already substitutes "no-key-required" for a- # loopback endpoint with no usable secret (the config-based- # custom_providers fallback a few hundred lines below, and the- # "actual" provider's local-offline exemption further down) --- # this pool path was the one gap (issue #86864).+ # Legacy configs used short placeholder keys ('123', 'm') for local no-auth+ # services; has_usable_secret's later 4-char floor rejects them. Every other+ # resolution path substitutes "no-key-required" for a loopback endpoint with+ # no usable secret — this pool path was the one gap (#86864).pool_api_key = "no-key-required"- return {- "provider": provider_label,- "api_mode": api_mode_override or _detect_api_mode_for_url(base_url) or "chat_completions",- "base_url": base_url,- "api_key": pool_api_key,- "source": f"pool:{pool_key}",- "credential_pool": pool,- }+ return _runtime(+ provider_label,+ api_mode_override or _detect_api_mode_for_url(base_url) or "chat_completions",+ base_url,+ pool_api_key,+ source=f"pool:{pool_key}",+ credential_pool=pool,+ )except Exception:continuereturn None@@ -750,10 +765,9 @@ def _lift_model_capabilities(def _lift_max_output_tokens(entry: Dict[str, Any], result: Dict[str, Any]) -> None:"""Propagate a per-provider output cap onto the resolved runtime dict.- Accepts ``max_output_tokens`` or ``max_tokens`` on a ``custom_providers``- entry so a provider block can pin its own output limit. Gateway and CLI- map this onto ``AIAgent.max_tokens`` only when the top-level- ``model.max_tokens`` isn't set, so the documented global key still wins.+ Accepts ``max_output_tokens`` or ``max_tokens`` on a ``custom_providers`` entry so a provider+ block can pin its own output limit. Gateway and CLI map this onto ``AIAgent.max_tokens`` only+ when the top-level ``model.max_tokens`` isn't set, so the documented global key still wins."""for _k in ("max_output_tokens", "max_tokens"):_v = entry.get(_k)@@ -765,34 +779,50 @@ def _lift_max_output_tokens(entry: Dict[str, Any], result: Dict[str, Any]) -> Nodef _lift_extra_headers(entry: Dict[str, Any], result: Dict[str, Any]) -> None:"""Copy a validated ``extra_headers`` dict from a provider entry.- SECURITY: header values routinely carry credentials (Cloudflare Access- service tokens, proxy auth, custom bearer schemes). Never log them.+ SECURITY: header values routinely carry credentials (Cloudflare Access service tokens, proxy+ auth, custom bearer schemes). Never log them."""extra_headers = normalize_extra_headers(entry.get("extra_headers"))if extra_headers:result["extra_headers"] = extra_headers+def _lift_common_custom_fields(+ entry: Dict[str, Any],+ result: Dict[str, Any],+ *,+ provider_key: str,+ key_env: str,+ api_mode: Optional[str],+) -> None:+ """Copy the optional fields shared by ``providers:`` and legacy ``custom_providers:`` entries."""+ if key_env:+ result["key_env"] = key_env+ if provider_key:+ result["provider_key"] = provider_key+ extra_body = entry.get("extra_body")+ if isinstance(extra_body, dict):+ result["extra_body"] = dict(extra_body)+ _lift_extra_headers(entry, result)+ if api_mode:+ result["api_mode"] = api_mode+ _lift_max_output_tokens(entry, result)+ capabilities = _filter_capabilities(entry.get("capabilities"))+ if capabilities:+ result["capabilities"] = capabilities++def _get_named_custom_provider(requested_provider: str) -> Optional[Dict[str, Any]]:requested_norm = _normalize_custom_provider_name(requested_provider or "")if not requested_norm:return None- # Bare "custom" is normally an incomplete spec — the canonical form is- # "custom:<name>" — and is otherwise owned by the model.base_url "bare- # custom" trust path. BUT a user may literally name a ``providers:`` (or- # legacy ``custom_providers:``) entry "custom" (e.g. ``providers.custom``- # pointing at cliproxy). We used to return None here *before* scanning- # config, so such an entry was never matched and resolution fell through to- # the global default (Codex) — the cause of cron jobs with- # ``provider: "custom"`` failing with ``auth_unavailable: providers=codex``.- # Fall through to the config scan instead; if no entry is literally named- # "custom" it still returns None at the end, preserving the trust path.-- # Raw names should only map to custom providers when they are not already- # valid built-in providers or aliases. Explicit menu keys like- # ``custom:local`` always target the saved custom provider. Bare "custom"- # is exempt from the shadow check — it is not a built-in to defer to.+ # Bare "custom" is normally owned by the model.base_url trust path, but a user may literally+ # name a ``providers:`` entry "custom"; returning None before the config scan made such cron+ # jobs fail with ``auth_unavailable: providers=codex``. So fall through to the scan (still+ # None if no entry is named "custom"). Raw names map to custom providers only when they are+ # not canonical built-ins; explicit ``custom:<name>`` keys always target the saved entry, and+ # bare "custom" is exempt from the shadow check.if requested_norm == "auto":return Noneif requested_norm != "custom" and not requested_norm.startswith("custom:"):@@ -801,14 +831,8 @@ def _get_named_custom_provider(requested_provider: str) -> Optional[Dict[str, Anexcept AuthError:passelse:- # A user-declared ``custom_providers`` entry whose name matches- # only an *alias* (``kimi`` → built-in ``kimi-coding``) is the- # user's intended target — alias rewriting would otherwise hijack- # the request. We only defer to the built-in when the raw name is- # the canonical provider itself (``nous``, ``openrouter``, …) so- # accidentally shadowing a canonical provider still resolves to- # the built-in. See tests/hermes_cli/test_runtime_provider_resolution.py- # ``test_named_custom_provider_does_not_shadow_builtin_provider``.+ # Defer to the built-in only when the raw name IS the canonical provider (``nous``);+ # an entry matching merely an alias (``kimi`` → ``kimi-coding``) is the user's target.if (canonical or "").strip().lower() == requested_norm:return None@@ -821,10 +845,7 @@ def _get_named_custom_provider(requested_provider: str) -> Optional[Dict[str, Anfor ep_name, entry in providers.items():if not isinstance(entry, dict):continue- # Skip providers the user explicitly disabled via- # ``providers.<name>.enabled: false``. They remain in config- # so re-enabling is a one-line edit, but the resolver pretends- # they're not configured.+ # ``providers.<name>.enabled: false`` entries stay in config but are invisible here.if not is_provider_enabled(entry):continue# Resolve the API key from the env var name stored in key_env@@ -850,36 +871,20 @@ def _get_named_custom_provider(requested_provider: str) -> Optional[Dict[str, An"api_key": resolved_api_key,"model": entry.get("default_model", ""),}- provider_key = str(ep_name or "").strip()- if provider_key:- result["provider_key"] = provider_key- if key_env:- result["key_env"] = key_env- extra_body = entry.get("extra_body")- if isinstance(extra_body, dict):- result["extra_body"] = dict(extra_body)- _lift_extra_headers(entry, result)- # Command that PRINTS a credential, for gateways issuing- # short-lived bearers instead of static keys. Propagated- # raw; wrapped in a per-request token provider at- # resolution.+ # Command that PRINTS a short-lived credential; wrapped in a+ # per-request token provider at resolution.key_cmd = str(entry.get("key_cmd", "") or "").strip()if key_cmd:result["key_cmd"] = key_cmd- # The v11→v12 migration writes the API mode under the new- # ``transport`` field, but hand-edited configs may still- # use the legacy ``api_mode`` spelling. Accept both —- # the runtime normaliser ``_normalize_custom_provider_entry``- # already does, so without this lift every migrated config- # silently downgrades codex_responses / anthropic_messages- # providers to chat_completions in the resolved runtime.- api_mode = _parse_api_mode(entry.get("api_mode") or entry.get("transport"))- if api_mode:- result["api_mode"] = api_mode- _lift_max_output_tokens(entry, result)- capabilities = _filter_capabilities(entry.get("capabilities"))- if capabilities:- result["capabilities"] = capabilities+ # v12 migration writes ``transport``; hand-edited configs may still use+ # ``api_mode``. Accept both or migrated configs silently downgrade to+ # chat_completions.+ _lift_common_custom_fields(+ entry, result,+ provider_key=str(ep_name or "").strip(),+ key_env=key_env,+ api_mode=_parse_api_mode(entry.get("api_mode") or entry.get("transport")),+ )return result# Fall back to custom_providers: list (legacy format)@@ -911,25 +916,15 @@ def _get_named_custom_provider(requested_provider: str) -> Optional[Dict[str, An"base_url": base_url.strip(),"api_key": str(entry.get("api_key", "") or "").strip(),}- key_env = str(entry.get("key_env", "") or "").strip()- if key_env:- result["key_env"] = key_env- if provider_key:- result["provider_key"] = provider_key- extra_body = entry.get("extra_body")- if isinstance(extra_body, dict):- result["extra_body"] = dict(extra_body)- _lift_extra_headers(entry, result)- api_mode = _parse_api_mode(entry.get("api_mode"))- if api_mode:- result["api_mode"] = api_modemodel_name = str(entry.get("model", "") or "").strip()if model_name:result["model"] = model_name- _lift_max_output_tokens(entry, result)- capabilities = _filter_capabilities(entry.get("capabilities"))- if capabilities:- result["capabilities"] = capabilities+ _lift_common_custom_fields(+ entry, result,+ provider_key=provider_key,+ key_env=str(entry.get("key_env", "") or "").strip(),+ api_mode=_parse_api_mode(entry.get("api_mode")),+ )return resultreturn None@@ -938,10 +933,9 @@ def _get_named_custom_provider(requested_provider: str) -> Optional[Dict[str, Andef has_named_custom_provider(requested_provider: str) -> bool:"""Return True when config defines a custom provider matching the request.- Thin public wrapper around :func:`_get_named_custom_provider` so other- modules (e.g. the cronjob tool) can decide whether a provider name will- actually resolve to a configured ``providers:`` / ``custom_providers:``- entry — without reaching into a private helper or duplicating the scan.+ Public wrapper around :func:`_get_named_custom_provider` so other modules (e.g. the cronjob+ tool) can check whether a provider name resolves to a configured ``providers:`` /+ ``custom_providers:`` entry without reaching into a private helper."""try:return _get_named_custom_provider(requested_provider) is not None@@ -949,25 +943,9 @@ def has_named_custom_provider(requested_provider: str) -> bool:return False-def find_custom_provider_identity(base_url: str) -> Optional[str]:- """Map an endpoint URL back to its canonical ``custom:<name>`` menu key.-- Returns the ``custom:<normalized-name>`` slug of the first ``providers:``- / ``custom_providers:`` entry whose base_url matches, or ``None`` when no- entry owns the URL.-- Session persistence stores the agent's *resolved* provider, and for every- named custom endpoint that is the literal string ``"custom"`` — the entry- name is lost, and the api_key is deliberately never persisted. The- endpoint URL is the one durable fact that survives the round-trip, so- this reverse lookup lets persist/rebuild paths recover the entry identity- (and with it key_env/api_key/api_mode resolution via- :func:`_get_named_custom_provider`) instead of failing with- ``auth_unavailable`` or silently rebuilding with placeholder credentials.- """- target = _normalize_base_url_for_match(base_url)- if not target:- return None+def _find_custom_identity(matches) -> Optional[str]:+ """Scan ``providers:`` then legacy ``custom_providers:`` for the first entry where+ ``matches(entry)`` holds and return its canonical ``custom:<name>`` slug."""try:config = load_config()except Exception:@@ -976,12 +954,7 @@ def find_custom_provider_identity(base_url: str) -> Optional[str]:providers = config.get("providers")if isinstance(providers, dict):for ep_name, entry in providers.items():- if not isinstance(entry, dict):- continue- entry_url = (- entry.get("api") or entry.get("url") or entry.get("base_url") or ""- )- if _normalize_base_url_for_match(entry_url) == target:+ if isinstance(entry, dict) and matches(entry):return custom_provider_slug(str(ep_name), str(ep_name))try:@@ -994,37 +967,40 @@ def find_custom_provider_identity(base_url: str) -> Optional[str]:name = entry.get("name")if not isinstance(name, str) or not name.strip():continue- if _normalize_base_url_for_match(entry.get("base_url")) == target:- return custom_provider_slug(- name,- str(entry.get("provider_key", "") or ""),- )+ if matches(entry):+ return custom_provider_slug(name, str(entry.get("provider_key", "") or ""))return None+def find_custom_provider_identity(base_url: str) -> Optional[str]:+ """Map an endpoint URL back to its canonical ``custom:<name>`` menu key.++ Session persistence stores the agent's *resolved* provider, and for every named custom endpoint+ that is the literal string ``"custom"`` — the entry name is lost, and the api_key is+ deliberately never persisted.+ """+ target = _normalize_base_url_for_match(base_url)+ if not target:+ return None++ def _entry_owns_url(entry: Dict[str, Any]) -> bool:+ entry_url = entry.get("api") or entry.get("url") or entry.get("base_url") or ""+ return _normalize_base_url_for_match(entry_url) == target++ return _find_custom_identity(_entry_owns_url)++def find_custom_provider_identity_by_model(model: str) -> Optional[str]:"""Map a model id back to the ``custom:<name>`` entry that serves it.- Returns the ``custom:<normalized-name>`` slug of the first ``providers:``- / ``custom_providers:`` entry whose ``model`` / ``default_model`` matches,- or whose ``models`` catalog (dict or list shape) contains the id.- ``None`` when no entry serves the model.-- Companion to :func:`find_custom_provider_identity` (URL reverse-lookup)- for the persistence paths where no base_url survived the round-trip: the- session row always stores the model name, and a custom endpoint's model- ids (e.g. an in-house SFT checkpoint) virtually never collide with- catalog models on built-in providers, so the model is the last durable- fact that can recover the entry identity.+ Companion to :func:`find_custom_provider_identity` (URL reverse-lookup) for the persistence+ paths where no base_url survived the round-trip: the session row always stores the model name,+ and a custom endpoint's model ids (e.g."""target = str(model or "").strip().lower()if not target:return None- try:- config = load_config()- except Exception:- return Nonedef _entry_serves_model(entry: Dict[str, Any]) -> bool:for key in ("model", "default_model"):@@ -1033,9 +1009,7 @@ def find_custom_provider_identity_by_model(model: str) -> Optional[str]:return Truemodels = entry.get("models")if isinstance(models, dict):- return any(- str(mid).strip().lower() == target for mid in models.keys()- )+ return any(str(mid).strip().lower() == target for mid in models)if isinstance(models, list):for item in models:if isinstance(item, str) and item.strip().lower() == target:@@ -1046,31 +1020,7 @@ def find_custom_provider_identity_by_model(model: str) -> Optional[str]:return Truereturn False- providers = config.get("providers")- if isinstance(providers, dict):- for ep_name, entry in providers.items():- if not isinstance(entry, dict):- continue- if _entry_serves_model(entry):- return custom_provider_slug(str(ep_name), str(ep_name))-- try:- custom_providers = get_compatible_custom_providers(config)- except Exception:- custom_providers = None- for entry in custom_providers or []:- if not isinstance(entry, dict):- continue- name = entry.get("name")- if not isinstance(name, str) or not name.strip():- continue- if _entry_serves_model(entry):- return custom_provider_slug(- name,- str(entry.get("provider_key", "") or ""),- )-- return None+ return _find_custom_identity(_entry_serves_model)def canonical_custom_identity(@@ -1081,36 +1031,13 @@ def canonical_custom_identity() -> Optional[str]:"""Recover a routable ``custom:<name>`` identity for a bare custom provider.- The bare string ``"custom"`` is the *resolved billing class* shared by- every named ``providers:`` / ``custom_providers:`` entry — it is NOT a- routable provider identity (``resolve_runtime_provider("custom")`` falls- through to the OpenRouter default URL with no api_key, which surfaces to- the user as "No LLM provider configured").-- Any code path that persists or restores a session's provider override- must run the resolved provider through this helper so a bare ``"custom"``- is upgraded back to its durable ``custom:<name>`` menu key. Three- recovery sources, in priority order:-- 1. ``base_url`` — reverse-lookup the entry that owns the endpoint URL- (the one fact that always survives the persistence round-trip when a- URL was recorded).- 2. ``model`` — reverse-lookup the entry that serves the session's model- (``model``/``default_model``/``models`` catalog). The session row- always stores the model name, so when no base_url survived (the- recurring Desktop/TUI regression vector) the model is the last- session-scoped fact that can recover the entry — and unlike the- config fallback below it stays correct after the user points their- global default at a different provider.- 3. ``config_provider`` — the active ``config.model.provider`` (or its- ``provider``/``HERMES_INFERENCE_PROVIDER`` equivalent). When neither- a base_url nor a model recovered the entry, the configured provider- is the only durable identity left, so fall back to it when it names- a real entry.-- Returns ``custom:<name>`` when a routable identity is recovered, else- ``None`` (caller keeps whatever it had — bare ``"custom"`` only as a last- resort, e.g. a genuine ad-hoc endpoint with no config entry).+ Any code path that persists or restores a session's provider override must run the resolved+ provider through this helper so a bare ``"custom"`` is upgraded back to its durable+ ``custom:<name>`` menu key. Three recovery sources, in priority order:++ 1. ``base_url`` — reverse-lookup the entry that owns the endpoint URL (the one fact that always+ survives the persistence round-trip when a URL was recorded). 2. ``model`` — reverse-lookup the+ entry that serves the session's model (``model``/``default_model``/``models`` catalog). 3."""# 1. Reverse-lookup by endpoint URL.if base_url:@@ -1143,14 +1070,9 @@ def canonical_custom_identity(try:entry = _get_named_custom_provider(candidate)if entry is not None:- # ``candidate`` matched, but it may be the entry's DISPLAY NAME —- # ``_get_named_custom_provider`` accepts either spelling. For a- # keyed ``providers:`` entry the display name is not the durable- # identity, so re-resolve through the endpoint the matched entry- # owns and return the same config-key slug every other path- # returns (7b5a18817). Without this, a display name that differs- # from its key heals to ``custom:<display-name>`` and stops- # matching the persisted identity.+ # ``candidate`` may be the entry's DISPLAY NAME, which is not the durable identity of+ # a keyed ``providers:`` entry — re-resolve via its endpoint so every path returns the+ # same config-key slug (else it heals to ``custom:<display-name>`` and stops matching).identity = find_custom_provider_identity(str(entry.get("base_url") or ""))if identity:return identity@@ -1165,16 +1087,10 @@ def canonical_custom_identity(def is_routable_provider(provider: Optional[str]) -> bool:"""Whether a provider name currently resolves to a routable route.- Empty/None is vacuously routable: agent build falls back to the- configured default instead of failing. A name that resolves through- the full chain (built-in -> user ``providers:`` -> ``custom_providers:``- -> models.dev) is routable; anything else would fail agent init with+ Empty/None is vacuously routable: agent build falls back to the configured default instead of+ failing. A name that resolves through the full chain (built-in -> user ``providers:`` ->+ ``custom_providers:`` -> models.dev) is routable; anything else would fail agent init with"Unknown provider '<name>'".-- Session resume uses this to detect a stale/renamed/removed provider- persisted in an older session snapshot, so recovery can fall back to- the configured default or the model the user picked instead of letting- the agent build die."""name = str(provider or "").strip()if not name or name.lower() == "auto":@@ -1212,6 +1128,32 @@ def _custom_provider_request_overrides(custom_provider: Dict[str, Any]) -> Dict[return {"extra_body": dict(extra_body)}+def _apply_custom_provider_extras(+ custom_provider: Dict[str, Any], target_model: Optional[str], result: Dict[str, Any]+) -> None:+ """Copy model / capabilities / max_output_tokens / extra_headers / request_overrides onto a+ resolved custom runtime.++ An explicit ``target_model`` wins over the provider's configured default (auxiliary slots /+ background-review resolve a concrete model and must not fall back to ``default_model``).+ ``extra_headers`` may carry credentials — NEVER log them.+ """+ model_name = target_model or custom_provider.get("model")+ if model_name:+ result["model"] = model_name+ _lift_model_capabilities(custom_provider, model_name, result)+ if isinstance(custom_provider.get("max_output_tokens"), int):+ result["max_output_tokens"] = custom_provider["max_output_tokens"]+ if custom_provider.get("extra_headers"):+ result["extra_headers"] = dict(custom_provider["extra_headers"])+ request_overrides = _custom_provider_request_overrides(custom_provider)+ if request_overrides:+ result["request_overrides"] = {+ **dict(result.get("request_overrides") or {}),+ **request_overrides,+ }++def _resolve_named_custom_runtime(*,requested_provider: str,@@ -1219,20 +1161,13 @@ def _resolve_named_custom_runtime(explicit_base_url: Optional[str] = None,target_model: Optional[str] = None,) -> Optional[Dict[str, Any]]:- # Bare `provider="custom"` with an explicit base_url (e.g. propagated- # from a `model_aliases:` direct-alias resolution) — build a runtime- # directly so the alias's base_url actually takes effect.- #- # GitHub #27132: provider aliases that resolve to "custom" at runtime- # (ollama, vllm, llamacpp, …) are treated identically here, so a YAML- # `provider: ollama` with a LAN/WireGuard `base_url` doesn't silently- # fall through to OpenRouter.+ # Bare `provider="custom"` with an explicit base_url (e.g. from a `model_aliases:` direct+ # alias) builds a runtime directly so the alias's base_url takes effect. Aliases resolving to+ # "custom" (ollama, vllm, llamacpp, …) are treated identically (#27132).requested_norm = (requested_provider or "").strip().lower()- # Managed llama.cpp runtime: a llamacpp-flavored alias with no explicit- # base_url resolves to the supervised server (or a detected external- # one) before the generic custom fallthrough. Explicit base_url always- # wins — a user pointing at a specific server means that server.+ # Managed llama.cpp runtime: a llamacpp alias with no explicit base_url resolves to the+ # supervised (or detected external) server first. Explicit base_url always wins.if requested_norm in ("llamacpp", "llama.cpp", "llama-cpp") and not explicit_base_url:try:from hermes_cli.local_runtime.endpoint import resolve_llamacpp_endpoint@@ -1241,26 +1176,20 @@ def _resolve_named_custom_runtime(except Exception: # noqa: BLE001 — resolution is best-effortendpoint = Noneif endpoint:- return {- "provider": "custom",- "api_mode": "chat_completions",- "base_url": endpoint["base_url"],- "api_key": (explicit_api_key or "").strip()+ return _runtime(+ "custom",+ "chat_completions",+ endpoint["base_url"],+ (explicit_api_key or "").strip()or endpoint["api_key"] or "no-key-required",- "source": "local-runtime",- "requested_provider": requested_provider,- }- # No server to serve this model. Say so and stop — falling through- # to the generic custom path sends the request to whatever provider- # picks it up (OpenRouter with a placeholder key), and the user's- # "local server is off" surfaces as that provider's baffling- # "401 Invalid API key". The switch's own state picks the message:- # the user who turned the server off gets pointed at the switch,- # anyone else at the setup pane.+ source="local-runtime",+ requested_provider=requested_provider,+ )+ # No server: say so and stop — falling through to the generic custom path surfaces+ # "local server is off" as OpenRouter's baffling "401 Invalid API key". The switch's+ # state picks the message (server off → point at the switch; else the setup pane).try:- from hermes_cli.config import load_config as _load_cfg-- _lr_enabled = bool((_load_cfg().get("local_runtime") or {}).get("enabled"))+ _lr_enabled = bool((load_config().get("local_runtime") or {}).get("enabled"))except Exception: # noqa: BLE001_lr_enabled = Falseif _lr_enabled:@@ -1275,14 +1204,8 @@ def _resolve_named_custom_runtime("model.")- if requested_norm and requested_norm != "custom":- try:- from hermes_cli.auth import resolve_provider as _resolve_provider-- if _resolve_provider(requested_norm) == "custom":- requested_norm = "custom"- except Exception:- pass+ if requested_norm and requested_norm != "custom" and _resolves_to_custom(requested_norm):+ requested_norm = "custom"if requested_norm == "custom" and explicit_base_url:base_url = explicit_base_url.strip().rstrip("/")# Check credential pool first — mirrors the named-custom-provider path@@ -1292,36 +1215,21 @@ def _resolve_named_custom_runtime(if pool_result:pool_result["source"] = "direct-alias"return pool_result- _da_is_openai_url = base_url_host_matches(base_url, "openai.com") or base_url_host_matches(base_url, "openai.azure.com")- _da_is_openrouter = base_url_host_matches(base_url, "openrouter.ai")- _da_is_ollama_url = base_url_host_matches(base_url, "ollama.com")+ # OLLAMA_API_KEY gets its own gate here: without it a `model_aliases:`+ # entry pointing at Ollama Cloud resolved no key at all.api_key_candidates = [(explicit_api_key or "").strip(),- # Gate env key fallbacks on authoritative hosts (#28660)- # OLLAMA_API_KEY needs its own gate here: _host_derived_api_key- # deliberately skips it, expecting an explicit host-matched path- # like this one (GHSA-76xc-57q6-vm5m). Without it a `model_aliases:`- # entry pointing at Ollama Cloud resolved no key at all.- (_getenv("OLLAMA_API_KEY", "").strip() if _da_is_ollama_url else ""),- (_getenv("OPENAI_API_KEY", "").strip() if _da_is_openai_url else ""),- (_getenv("OPENROUTER_API_KEY", "").strip() if _da_is_openrouter else ""),- # Bonus (#28660): derive `<VENDOR>_API_KEY` from the host so users- # who set DEEPSEEK_API_KEY / GROQ_API_KEY / MISTRAL_API_KEY get the- # intuitive match without configuring `custom_providers` first.- _host_derived_api_key(base_url),+ *_host_gated_env_key_candidates(base_url, ollama=True),]- api_key = next(- (c for c in api_key_candidates if has_usable_secret(c)),- "",- ) or "no-key-required"- return {- "provider": "custom",- "api_mode": _detect_api_mode_for_url(base_url) or "chat_completions",- "base_url": base_url,- "api_key": api_key,- "source": "direct-alias",- "requested_provider": requested_provider,- }+ api_key = next((c for c in api_key_candidates if has_usable_secret(c)), "") or "no-key-required"+ return _runtime(+ "custom",+ _detect_api_mode_for_url(base_url) or "chat_completions",+ base_url,+ api_key,+ source="direct-alias",+ requested_provider=requested_provider,+ )custom_provider = _get_named_custom_provider(requested_provider)if not custom_provider:@@ -1342,49 +1250,23 @@ def _resolve_named_custom_runtime(provider_name=custom_provider.get("provider_key") or custom_provider.get("name"),)if pool_result:- # Propagate the model name even when using pooled credentials —- # the pool doesn't know about the custom_providers model field.- # An explicit ``target_model`` wins (same rule as the non-pool path).- model_name = target_model or custom_provider.get("model")- if model_name:- pool_result["model"] = model_name- _lift_model_capabilities(custom_provider, model_name, pool_result)- if isinstance(custom_provider.get("max_output_tokens"), int):- pool_result["max_output_tokens"] = custom_provider["max_output_tokens"]- request_overrides = _custom_provider_request_overrides(custom_provider)- if request_overrides:- pool_result["request_overrides"] = {- **dict(pool_result.get("request_overrides") or {}),- **request_overrides,- }- # Propagate extra_headers so custom-provider auth headers (e.g.- # Cloudflare Access service tokens) still apply with pooled- # credentials. NEVER log the values.- if custom_provider.get("extra_headers"):- pool_result["extra_headers"] = dict(custom_provider["extra_headers"])+ # Propagate the model name / capabilities / headers even when using+ # pooled credentials — the pool doesn't know about the custom_providers+ # fields. An explicit ``target_model`` wins (same rule as the non-pool path).+ _apply_custom_provider_extras(custom_provider, target_model, pool_result)return pool_result- _cp_is_openai_url = base_url_host_matches(base_url, "openai.com") or base_url_host_matches(base_url, "openai.azure.com")- _cp_is_openrouter = base_url_host_matches(base_url, "openrouter.ai")api_key_candidates = [(explicit_api_key or "").strip(),str(custom_provider.get("api_key", "") or "").strip(),_getenv(str(custom_provider.get("key_env", "") or "").strip(), "").strip(),- # Gate provider env keys on their authoritative hosts — sending- # OPENAI_API_KEY to a local-llm endpoint leaks credentials (#28660).- (_getenv("OPENAI_API_KEY", "").strip() if _cp_is_openai_url else ""),- (_getenv("OPENROUTER_API_KEY", "").strip() if _cp_is_openrouter else ""),- # Bonus (#28660): derive `<VENDOR>_API_KEY` from the host as a final- # fallback when key_env wasn't set explicitly.- _host_derived_api_key(base_url),+ *_host_gated_env_key_candidates(base_url, ollama=False),]api_key = next((candidate for candidate in api_key_candidates if has_usable_secret(candidate)), "")- # A ``key_cmd`` credential is minted per request rather than resolved once:- # gateways that issue short-lived bearers would otherwise go stale- # mid-session and 401. Both wire clients already accept a callable api_key- # (the Entra ID contract) and invoke it per request. An explicit --api-key- # still wins — it is the one-off recovery escape hatch.+ # ``key_cmd`` credentials are minted per request (short-lived bearers would go stale+ # mid-session); both wire clients accept a callable api_key (the Entra ID contract).+ # An explicit --api-key still wins as the one-off recovery escape hatch.key_cmd = str(custom_provider.get("key_cmd", "") or "").strip()if key_cmd and not has_usable_secret((explicit_api_key or "").strip()):from agent.command_token_source import build_command_token_provider@@ -1396,56 +1278,28 @@ def _resolve_named_custom_runtime(if token_provider is not None:api_key = token_provider- result = {- "provider": "custom",- "api_mode": custom_provider.get("api_mode")+ result = _runtime(+ "custom",+ custom_provider.get("api_mode")or _detect_api_mode_for_url(base_url)or "chat_completions",- "base_url": base_url,- "api_key": api_key or "no-key-required",- "source": f"custom_provider:{custom_provider.get('name', requested_provider)}",- "requested_provider": requested_provider,- }- # Propagate the model name so callers can override self.model when the- # provider name differs from the actual model string the API expects.- # An explicit ``target_model`` wins over the provider's configured- # default (regression: auxiliary slots / background-review resolve a- # concrete model for a custom provider and must not silently fall back- # to ``default_model``).- if target_model:- result["model"] = target_model- elif custom_provider.get("model"):- result["model"] = custom_provider["model"]- _lift_model_capabilities(- custom_provider, result.get("model"), result+ base_url,+ api_key or "no-key-required",+ source=f"custom_provider:{custom_provider.get('name', requested_provider)}",+ requested_provider=requested_provider,)- if isinstance(custom_provider.get("max_output_tokens"), int):- result["max_output_tokens"] = custom_provider["max_output_tokens"]- # Per-provider extra HTTP headers (proxies, gateways, custom auth).- # Values may carry credentials — NEVER log them.- if custom_provider.get("extra_headers"):- result["extra_headers"] = dict(custom_provider["extra_headers"])- request_overrides = _custom_provider_request_overrides(custom_provider)- if request_overrides:- result["request_overrides"] = request_overrides-- # Custom providers in the OpenCode family (name extends opencode-go/zen,- # or base_url hosted on opencode.ai) serve models behind different API- # surfaces per model — a static api_mode 503s for /v1/responses-only- # models like grok-4.5 (#85589). Re-derive api_mode from the effective- # model and normalize the /v1 suffix, exactly like the built-in- # opencode-zen/go paths do.+ _apply_custom_provider_extras(custom_provider, target_model, result)++ # OpenCode-family custom providers (opencode-go/zen names, or opencode.ai hosts) serve+ # models on different API surfaces — a static api_mode 503s for /v1/responses-only models+ # (#85589). Re-derive api_mode from the model and normalize /v1 like the built-in paths.from hermes_cli.models import opencode_provider_family_oc_family = opencode_provider_family(requested_provider)if _oc_family is None:try:- from utils import base_url_hostname-if base_url_hostname(base_url).lower() == "opencode.ai":- _oc_family = (- "opencode-go" if "/zen/go" in base_url.lower() else "opencode-zen"- )+ _oc_family = "opencode-go" if "/zen/go" in base_url.lower() else "opencode-zen"except Exception:_oc_family = Noneif _oc_family is not None and not custom_provider.get("api_mode"):@@ -1477,27 +1331,16 @@ def _resolve_openrouter_runtime(model_cfg = _get_model_config()cfg_base_url = model_cfg.get("base_url") if isinstance(model_cfg.get("base_url"), str) else ""cfg_provider = model_cfg.get("provider") if isinstance(model_cfg.get("provider"), str) else ""- cfg_api_key = ""- for k in ("api_key", "api"):- v = model_cfg.get(k)- if isinstance(v, str) and v.strip():- cfg_api_key = v.strip()- break+ cfg_api_key = next(+ (v.strip() for v in (model_cfg.get("api_key"), model_cfg.get("api")) if isinstance(v, str) and v.strip()),+ "",+ )requested_norm = (requested_provider or "").strip().lower()cfg_provider = cfg_provider.strip().lower()- # GitHub #27132: provider aliases that resolve to "custom" (ollama,- # vllm, llamacpp, …) follow the same base_url trust + routing rules- # as a bare `provider: custom`. Normalising here keeps every check- # below — `requested_norm == "custom"`, the trust check, the pool- # gate up the stack — alias-aware without duplicating the alias map.- if requested_norm and requested_norm != "custom":- try:- from hermes_cli.auth import resolve_provider as _resolve_provider-- if _resolve_provider(requested_norm) == "custom":- requested_norm = "custom"- except Exception:- pass+ # Aliases resolving to "custom" (ollama, vllm, …) follow bare-custom trust + routing rules;+ # normalising here keeps every check below alias-aware (#27132).+ if requested_norm and requested_norm != "custom" and _resolves_to_custom(requested_norm):+ requested_norm = "custom"env_openrouter_base_url = _getenv("OPENROUTER_BASE_URL", "").strip()env_custom_base_url = _getenv("CUSTOM_BASE_URL", "").strip()@@ -1505,15 +1348,13 @@ def _resolve_openrouter_runtime(# Use config base_url when available and the provider context matches.# OPENAI_BASE_URL env var is no longer consulted — config.yaml is# the single source of truth for endpoint URLs.- use_config_base_url = False- if cfg_base_url.strip() and not explicit_base_url:- if requested_norm == "auto":- if not cfg_provider or cfg_provider == "auto":- use_config_base_url = True- elif requested_norm == "custom" and _config_base_url_trustworthy_for_bare_custom(- cfg_base_url, cfg_provider- ):- use_config_base_url = True+ use_config_base_url = bool(cfg_base_url.strip()) and not explicit_base_url and (+ (requested_norm == "auto" and cfg_provider in ("", "auto"))+ or (+ requested_norm == "custom"+ and _config_base_url_trustworthy_for_bare_custom(cfg_base_url, cfg_provider)+ )+ )base_url = ((explicit_base_url or "").strip()@@ -1523,15 +1364,11 @@ def _resolve_openrouter_runtime(or OPENROUTER_BASE_URL).rstrip("/")- # Choose API key based on whether the resolved base_url targets OpenRouter.- # When hitting OpenRouter, prefer OPENROUTER_API_KEY (issue #289).- # When hitting a custom endpoint (e.g. Z.ai, local LLM), prefer- # OPENAI_API_KEY so the OpenRouter key doesn't leak to an unrelated- # provider (issues #420, #560).+ # OpenRouter endpoints prefer OPENROUTER_API_KEY (#289); custom endpoints must not receive+ # the OpenRouter key (#420, #560)._is_openrouter_url = base_url_host_matches(base_url, "openrouter.ai")- # Also treat explicitly-configured OpenRouter mirrors/proxies as OpenRouter- # for key selection — if the user set OPENROUTER_BASE_URL or requested- # provider=openrouter explicitly, OPENROUTER_API_KEY should still be used.+ # Explicitly-configured OpenRouter mirrors (OPENROUTER_BASE_URL + provider=openrouter)+ # still count as OpenRouter for key selection._is_openrouter_context = _is_openrouter_url or (requested_norm == "openrouter"and (env_openrouter_base_url or base_url == env_openrouter_base_url)@@ -1544,43 +1381,20 @@ def _resolve_openrouter_runtime(_getenv("OPENAI_API_KEY"),]else:- # Custom endpoint: use api_key from config when using config base_url (#1760).- # When the endpoint is Ollama Cloud, check OLLAMA_API_KEY — it's- # the canonical env var for ollama.com authentication. Match on- # HOST, not substring — a custom base_url whose path contains- # "ollama.com" (e.g. http://127.0.0.1/ollama.com/v1) or whose- # hostname is a look-alike (ollama.com.attacker.test) must not- # receive the Ollama credential. See GHSA-76xc-57q6-vm5m.- _is_ollama_url = base_url_host_matches(base_url, "ollama.com")- _is_openai_url = base_url_host_matches(base_url, "openai.com")- _is_openai_azure = base_url_host_matches(base_url, "openai.azure.com")- # Gate each provider key on its own host — sending OPENAI_API_KEY or- # OPENROUTER_API_KEY to an unrelated custom endpoint (DeepSeek, Groq,- # Mistral, …) leaks credentials and causes 401s (issue #28660).- # Mirrors the OLLAMA_API_KEY host-gate added in GHSA-76xc-57q6-vm5m.+ # Custom endpoint: use api_key from config when using config base_url (#1760),+ # then env keys gated on their authoritative hosts (Ollama Cloud, OpenAI,+ # OpenRouter) and the host-derived `<VENDOR>_API_KEY`.api_key_candidates = [explicit_api_key,(cfg_api_key if use_config_base_url else ""),- (_getenv("OLLAMA_API_KEY") if _is_ollama_url else ""),- (_getenv("OPENAI_API_KEY") if (_is_openai_url or _is_openai_azure) else ""),- (_getenv("OPENROUTER_API_KEY") if _is_openrouter_url else ""),- # Bonus (#28660): derive `<VENDOR>_API_KEY` from the host so users- # who set DEEPSEEK_API_KEY / GROQ_API_KEY / MISTRAL_API_KEY get the- # intuitive match. Helper returns "" for IPs/loopback and for env- # vars already handled by the explicit host-gated paths above.- _host_derived_api_key(base_url),+ *_host_gated_env_key_candidates(base_url, ollama=True),]- api_key = next(- (str(candidate or "").strip() for candidate in api_key_candidates if has_usable_secret(candidate)),- "",- )+ api_key = next((str(c or "").strip() for c in api_key_candidates if has_usable_secret(c)), "")source = "explicit" if (explicit_api_key or explicit_base_url) else "env/config"- # When "custom" was explicitly requested, preserve that as the provider- # name instead of silently relabeling to "openrouter" (#2562).- # Also provide a placeholder API key for local servers that don't require- # authentication — the OpenAI SDK requires a non-empty api_key string.+ # Explicit "custom" stays "custom" rather than relabeling to "openrouter" (#2562). Local+ # no-auth servers get a placeholder key — the OpenAI SDK requires a non-empty string.effective_provider = "custom" if requested_norm == "custom" else "openrouter"# For custom endpoints, check if a credential pool exists@@ -1597,17 +1411,17 @@ def _resolve_openrouter_runtime(if effective_provider == "custom" and not api_key and not _is_openrouter_url:api_key = "no-key-required"- return {- "provider": effective_provider,- "api_mode": _resolve_plain_custom_api_mode(model_cfg, base_url)+ return _runtime(+ effective_provider,+ _resolve_plain_custom_api_mode(model_cfg, base_url)if effective_provider == "custom"else _parse_api_mode(model_cfg.get("api_mode"))or _detect_api_mode_for_url(base_url)or "chat_completions",- "base_url": base_url,- "api_key": api_key,- "source": source,- }+ base_url,+ api_key,+ source=source,+ )def _resolve_azure_foundry_runtime(@@ -1620,32 +1434,19 @@ def _resolve_azure_foundry_runtime() -> Dict[str, Any]:"""Resolve an Azure Foundry runtime entry.- Reads ``model.base_url`` + ``model.api_mode`` from config.yaml (or- explicit overrides), pulls the API key from ``.env`` / env var, and- strips a trailing ``/v1`` for Anthropic-style endpoints because the- Anthropic SDK appends ``/v1/messages`` internally.-- When ``model.auth_mode == "entra_id"`` (and the model is OpenAI-style),- the returned ``api_key`` is a zero-arg callable produced by- :func:`agent.azure_identity_adapter.build_token_provider` rather than- a string. Downstream code that constructs an OpenAI SDK client passes- this through unchanged (the SDK accepts ``Callable[[], str]`` for- ``api_key`` and calls it before every request). Code paths that need- a string (logging, manual HTTP probes, header injection) must use the- helpers in ``agent.azure_identity_adapter``.-- Raises :class:`AuthError` when required values are missing.+ Reads ``model.base_url`` + ``model.api_mode`` from config.yaml (or explicit overrides), pulls+ the API key from ``.env`` / env var, and strips a trailing ``/v1`` for Anthropic-style endpoints+ because the Anthropic SDK appends ``/v1/messages`` internally."""explicit_api_key = str(explicit_api_key or "").strip()explicit_base_url_clean = str(explicit_base_url or "").strip().rstrip("/")- cfg_provider = str(model_cfg.get("provider") or "").strip().lower()cfg_base_url = ""cfg_api_mode = "chat_completions"cfg_auth_mode = "api_key"cfg_entra: Dict[str, Any] = {}- if cfg_provider == "azure-foundry":- cfg_base_url = str(model_cfg.get("base_url") or "").strip().rstrip("/")+ if _cfg_provider(model_cfg) == "azure-foundry":+ cfg_base_url = _config_base_url_for_provider(model_cfg, "azure-foundry")cfg_api_mode = _parse_api_mode(model_cfg.get("api_mode")) or "chat_completions"cfg_auth_mode = str(model_cfg.get("auth_mode") or "api_key").strip().lower() or "api_key"_entra = model_cfg.get("entra")@@ -1653,20 +1454,9 @@ def _resolve_azure_foundry_runtime(cfg_entra = _entra# Model-family inference: Azure Foundry deploys GPT-5.x / codex / o1-o4- # reasoning models as Responses-API-only. Calling /chat/completions- # against them returns 400 "The requested operation is unsupported."- # Upgrade api_mode when the model name matches, unless the user has- # explicitly chosen anthropic_messages (Anthropic-style endpoint).+ # reasoning models as Responses-API-only (see _azure_inferred_api_mode).effective_model = str(target_model or model_cfg.get("default") or "").strip()- if effective_model and cfg_api_mode != "anthropic_messages":- try:- from hermes_cli.models import azure_foundry_model_api_mode-- inferred = azure_foundry_model_api_mode(effective_model)- except Exception:- inferred = None- if inferred:- cfg_api_mode = inferred+ cfg_api_mode = _azure_inferred_api_mode(effective_model, cfg_api_mode)env_base_url = _getenv("AZURE_FOUNDRY_BASE_URL", "").strip().rstrip("/")base_url = explicit_base_url_clean or cfg_base_url or env_base_url@@ -1682,19 +1472,9 @@ def _resolve_azure_foundry_runtime(base_url = re.sub(r"/v1/?$", "", base_url)# ── Entra ID (Microsoft Foundry recommended path) ──────────────────- #- # OpenAI-style endpoints use the OpenAI SDK's native callable- # ``api_key=`` contract — the SDK mints a fresh JWT per request- # automatically.- #- # Anthropic-style endpoints (Claude on Foundry) take the callable- # too: :func:`agent.anthropic_adapter.build_anthropic_client`- # detects the callable and constructs an ``httpx.Client`` with a- # request event hook that injects a fresh ``Authorization: Bearer``- # header per request (the Anthropic SDK does not accept callables- # natively). From the runtime resolver's perspective both modes- # are identical — return the callable api_key and let the- # downstream SDK wrapper handle the contract difference.+ # Return a callable api_key that mints a fresh JWT per request: the OpenAI SDK accepts it+ # natively; for Anthropic-style endpoints ``build_anthropic_client`` injects the bearer via an+ # httpx request hook. Both modes look identical from here.if cfg_auth_mode == "entra_id":if explicit_api_key:# User passed --api-key on the CLI while config says entra_id —@@ -1732,21 +1512,20 @@ def _resolve_azure_foundry_runtime(auth_mode = "entra_id"clean_entra = {}- if auth_mode == "entra_id":- configured_scope = str(cfg_entra.get("scope") or "").strip()- if configured_scope:- clean_entra["scope"] = configured_scope-- return {- "provider": "azure-foundry",- "api_mode": cfg_api_mode,- "base_url": base_url,- "api_key": api_key,- "auth_mode": auth_mode,- "entra": clean_entra,- "source": source,- "requested_provider": requested_provider,- }+ configured_scope = str(cfg_entra.get("scope") or "").strip()+ if auth_mode == "entra_id" and configured_scope:+ clean_entra["scope"] = configured_scope++ return _runtime(+ "azure-foundry",+ cfg_api_mode,+ base_url,+ api_key,+ auth_mode=auth_mode,+ entra=clean_entra,+ source=source,+ requested_provider=requested_provider,+ )# ── Static API key (legacy / default) ──────────────────────────────api_key = explicit_api_key@@ -1756,8 +1535,7 @@ def _resolve_azure_foundry_runtime(api_key = get_env_value("AZURE_FOUNDRY_API_KEY") or ""except Exception:api_key = ""- if not api_key:- api_key = _getenv("AZURE_FOUNDRY_API_KEY", "").strip()+ api_key = api_key or _getenv("AZURE_FOUNDRY_API_KEY", "").strip()if not api_key:raise AuthError("Azure Foundry requires an API key. Set AZURE_FOUNDRY_API_KEY in "@@ -1768,15 +1546,15 @@ def _resolve_azure_foundry_runtime()source = "explicit" if (explicit_api_key or explicit_base_url) else "config"- return {- "provider": "azure-foundry",- "api_mode": cfg_api_mode,- "base_url": base_url,- "api_key": api_key,- "auth_mode": "api_key",- "source": source,- "requested_provider": requested_provider,- }+ return _runtime(+ "azure-foundry",+ cfg_api_mode,+ base_url,+ api_key,+ auth_mode="api_key",+ source=source,+ requested_provider=requested_provider,+ )def _resolve_explicit_runtime(@@ -1794,31 +1572,22 @@ def _resolve_explicit_runtime(return Noneif provider == "anthropic":- cfg_provider = str(model_cfg.get("provider") or "").strip().lower()- cfg_base_url = ""- if cfg_provider == "anthropic":- cfg_base_url = str(model_cfg.get("base_url") or "").strip().rstrip("/")- if not _anthropic_base_url_override_ok(cfg_base_url):- cfg_base_url = ""- base_url = explicit_base_url or cfg_base_url or "https://api.anthropic.com"+ base_url = explicit_base_url or _anthropic_cfg_base_url(model_cfg) or _ANTHROPIC_DEFAULT_BASE_URLapi_key = explicit_api_keyif not api_key:from agent.anthropic_adapter import resolve_anthropic_tokenapi_key = resolve_anthropic_token()if not api_key:- raise AuthError(- "No Anthropic credentials found. Set ANTHROPIC_TOKEN or ANTHROPIC_API_KEY, "- "run 'claude setup-token', or authenticate with 'claude /login'."- )- return {- "provider": "anthropic",- "api_mode": "anthropic_messages",- "base_url": base_url,- "api_key": api_key,- "source": "explicit",- "requested_provider": requested_provider,- }+ raise AuthError(_NO_ANTHROPIC_CREDENTIALS_MSG)+ return _runtime(+ "anthropic",+ "anthropic_messages",+ base_url,+ api_key,+ source="explicit",+ requested_provider=requested_provider,+ )if provider == "openai-codex":base_url = explicit_base_url or DEFAULT_CODEX_BASE_URL@@ -1828,21 +1597,18 @@ def _resolve_explicit_runtime(creds = resolve_codex_runtime_credentials()api_key = creds.get("api_key", "")last_refresh = creds.get("last_refresh")- if not explicit_base_url:- base_url = creds.get("base_url", "").rstrip("/") or base_url- return {- "provider": "openai-codex",- "api_mode": "codex_responses",- "base_url": base_url,- "api_key": api_key,- "source": "explicit",- "last_refresh": last_refresh,- "requested_provider": requested_provider,- }+ base_url = explicit_base_url or creds.get("base_url", "").rstrip("/") or base_url+ return _runtime(+ "openai-codex",+ "codex_responses",+ base_url,+ api_key,+ source="explicit",+ last_refresh=last_refresh,+ requested_provider=requested_provider,+ )if provider == "nous":- from hermes_cli.providers import nous_api_mode-state = auth_mod.get_provider_auth_state("nous") or {}base_url = (explicit_base_url@@ -1862,22 +1628,19 @@ def _resolve_explicit_runtime()expires_at = state.get("agent_key_expires_at") or state.get("expires_at")if not api_key:- creds = resolve_nous_runtime_credentials(- timeout_seconds=float(_getenv("HERMES_NOUS_TIMEOUT_SECONDS", "15")),- )+ creds = _resolve_nous_creds()api_key = creds.get("api_key", "")expires_at = creds.get("expires_at")- if not explicit_base_url:- base_url = creds.get("base_url", "").rstrip("/") or base_url- return {- "provider": "nous",- "api_mode": nous_api_mode(target_model or model_cfg.get("default") or ""),- "base_url": base_url,- "api_key": api_key,- "source": "explicit",- "expires_at": expires_at,- "requested_provider": requested_provider,- }+ base_url = explicit_base_url or creds.get("base_url", "").rstrip("/") or base_url+ return _runtime(+ "nous",+ _nous_api_mode(target_model or model_cfg.get("default") or ""),+ base_url,+ api_key,+ source="explicit",+ expires_at=expires_at,+ requested_provider=requested_provider,+ )# Azure Foundry: user-configured endpoint with selectable API modeif provider == "azure-foundry":@@ -1890,16 +1653,13 @@ def _resolve_explicit_runtime(pconfig = PROVIDER_REGISTRY.get(provider)if pconfig and pconfig.auth_type == "api_key":- env_url = ""- if pconfig.base_url_env_var:- env_url = _getenv(pconfig.base_url_env_var, "").strip().rstrip("/")-base_url = explicit_base_urlif not base_url:if provider in {"kimi-coding", "kimi-coding-cn"}:creds = resolve_api_key_provider_credentials(provider)base_url = creds.get("base_url", "").rstrip("/")else:+ env_url = _getenv(pconfig.base_url_env_var, "").strip().rstrip("/") if pconfig.base_url_env_var else ""base_url = env_url or pconfig.inference_base_urlif provider == "actual":@@ -1914,40 +1674,22 @@ def _resolve_explicit_runtime(if provider == "actual":base_url = normalize_actual_base_url(base_url)- api_mode = "chat_completions"- if provider == "copilot":- api_mode = _copilot_runtime_api_mode(- model_cfg,- api_key,- target_model=target_model,- )- elif provider == "xai":- api_mode = "codex_responses"- elif provider == "actual":- api_mode = "codex_responses"- else:- configured_provider = str(model_cfg.get("provider") or "").strip().lower()- configured_mode = _parse_api_mode(model_cfg.get("api_mode"))- if configured_mode and _provider_supports_explicit_api_mode(provider, configured_provider):- api_mode = configured_mode- else:- # URL detection first, then the provider's declared transport- # (fixes regional OpenAI hosts and other non-chat overlays).- api_mode = _fallback_api_mode(- provider, base_url, target_model or model_cfg.get("default", "")- )+ api_mode = _api_key_provider_api_mode(+ provider, model_cfg, api_key, base_url,+ target_model or model_cfg.get("default", ""), opencode_by_model=False,+ )if provider == "actual" and not api_key and is_actual_local_base_url(base_url):api_key = ACTUAL_LOCAL_NOAUTH_PLACEHOLDER- return {- "provider": provider,- "api_mode": api_mode,- "base_url": base_url.rstrip("/"),- "api_key": api_key,- "source": "explicit",- "requested_provider": requested_provider,- }+ return _runtime(+ provider,+ api_mode,+ base_url.rstrip("/"),+ api_key,+ source="explicit",+ requested_provider=requested_provider,+ )return None@@ -1979,6 +1721,53 @@ def _is_external_process_provider(provider: str) -> bool:return profile is not None and getattr(profile, "auth_type", "") == "external_process"+def _resolve_nous_creds() -> Dict[str, Any]:+ return resolve_nous_runtime_credentials(+ timeout_seconds=float(_getenv("HERMES_NOUS_TIMEOUT_SECONDS", "15")),+ )+++def _nous_api_mode(model: str) -> str:+ from hermes_cli.providers import nous_api_mode++ return nous_api_mode(model)+++@dataclass(frozen=True)+class _OAuthRuntimeSpec:+ """Env/auth-store OAuth providers resolved by a single credential call."""++ resolve: Callable[[], Dict[str, Any]]+ api_mode: Any # str, or callable(model) -> str+ default_source: str+ expiry_key: str+ failure_msg: str+ default_base_url: str = ""+++# ``resolve`` entries are late-bound lambdas so tests can monkeypatch the module-level+# ``resolve_*_runtime_credentials`` names.+_OAUTH_RUNTIME_PROVIDERS: Dict[str, _OAuthRuntimeSpec] = {+ "nous": _OAuthRuntimeSpec(+ _resolve_nous_creds, _nous_api_mode, "portal", "expires_at",+ "Auto-detected Nous provider but credentials failed",+ ),+ "openai-codex": _OAuthRuntimeSpec(+ lambda: resolve_codex_runtime_credentials(), "codex_responses", "hermes-auth-store", "last_refresh",+ "Auto-detected Codex provider but credentials failed",+ ),+ "xai-oauth": _OAuthRuntimeSpec(+ lambda: resolve_xai_oauth_runtime_credentials(), "codex_responses", "hermes-auth-store", "last_refresh",+ "Auto-detected xAI OAuth provider but credentials failed",+ default_base_url=DEFAULT_XAI_OAUTH_BASE_URL,+ ),+ "qwen-oauth": _OAuthRuntimeSpec(+ lambda: resolve_qwen_runtime_credentials(), "chat_completions", "qwen-cli", "expires_at_ms",+ "Qwen OAuth credentials failed",+ ),+}++def resolve_runtime_provider(*,requested: Optional[str] = None,@@ -1988,26 +1777,14 @@ def resolve_runtime_provider() -> Dict[str, Any]:"""Resolve runtime provider credentials for agent execution.- target_model: Optional override for model_cfg.get("default") when- computing provider-specific api_mode (e.g. OpenCode Zen/Go where different- models route through different API surfaces). Callers performing an- explicit mid-session model switch should pass the new model here so- api_mode is derived from the model they are switching TO, not the stale- persisted default. Other callers can leave it None to preserve existing- behavior (api_mode derived from config).+ target_model: Optional override for model_cfg.get("default") when computing provider-specific+ api_mode (e.g. OpenCode Zen/Go where different models route through different API surfaces)."""requested_provider = resolve_requested_provider(requested)- # Honour ``providers.<name>.enabled: false`` for BOTH user-defined- # custom providers and the built-in ones (openai / anthropic /- # openrouter / gemini / ...). The earlier ``_get_named_custom_provider``- # gate only covers custom blocks — built-in resolution paths- # (``resolve_provider`` + pool / explicit / generic runtime) walk- # their own short-circuits and would otherwise return stale config- # for a provider the user explicitly turned off.- #- # Fail fast with a typed error so the fallback chain can advance to- # the next provider instead of using a disabled one.+ # Honour ``providers.<name>.enabled: false`` for built-in providers too (the+ # ``_get_named_custom_provider`` gate only covers custom blocks). Fail fast with a typed+ # error so the fallback chain advances instead of using a disabled provider.from hermes_cli.config import is_provider_enabled, load_config_full_cfg = load_config()_provs_cfg = _full_cfg.get("providers") if isinstance(_full_cfg, dict) else None@@ -2020,19 +1797,17 @@ def resolve_runtime_provider()if requested_provider == "moa":- return {- "provider": "moa",- "api_mode": "chat_completions",- "base_url": "moa://local",- "api_key": "moa-virtual-provider",- "source": "moa-virtual-provider",- "requested_provider": requested_provider,- }+ return _runtime(+ "moa",+ "chat_completions",+ "moa://local",+ "moa-virtual-provider",+ source="moa-virtual-provider",+ requested_provider=requested_provider,+ )- # Azure Anthropic short-circuit: when explicitly targeting an Azure endpoint- # with provider="anthropic", bypass _resolve_named_custom_runtime (which would- # return provider="custom" with chat_completions api_mode and no valid key).- # Instead, use the Azure key directly with anthropic_messages api_mode.+ # Azure Anthropic short-circuit: an explicit Azure endpoint with provider="anthropic" must+ # bypass _resolve_named_custom_runtime (which would yield custom/chat_completions/no key)._eff_base = (explicit_base_url or "").strip()if requested_provider == "anthropic" and base_url_host_matches(_eff_base, "azure.com"):_azure_key = (@@ -2040,40 +1815,30 @@ def resolve_runtime_provider(or _getenv("AZURE_ANTHROPIC_KEY", "").strip()or _getenv("ANTHROPIC_API_KEY", "").strip())- return {- "provider": "anthropic",- "api_mode": "anthropic_messages",- "base_url": _eff_base.rstrip("/"),- "api_key": _azure_key,- "source": "azure-explicit",- "requested_provider": requested_provider,- }+ return _runtime(+ "anthropic",+ "anthropic_messages",+ _eff_base.rstrip("/"),+ _azure_key,+ source="azure-explicit",+ requested_provider=requested_provider,+ )- # Azure Foundry: user-configured endpoint with selectable API mode- # (OpenAI-style chat_completions or Anthropic-style anthropic_messages).- # Resolve before the custom-runtime / pool / generic paths so Azure- # config is always picked up from model.base_url + model.api_mode,- # regardless of whether the caller passed explicit_* args.+ # Azure Foundry resolves before the custom-runtime / pool / generic paths so its config is+ # always picked up from model.base_url + model.api_mode, with or without explicit_* args.if requested_provider == "azure-foundry":- azure_runtime = _resolve_azure_foundry_runtime(+ return _resolve_azure_foundry_runtime(requested_provider=requested_provider,model_cfg=_get_model_config(),explicit_api_key=explicit_api_key,explicit_base_url=explicit_base_url,target_model=target_model,)- return azure_runtime-- # Vertex AI: OAuth2-token provider (Gemini via the OpenAI-compatible- # endpoint). Resolve BEFORE the custom-runtime / credential-pool / generic- # paths. The credential *path* (GOOGLE_APPLICATION_CREDENTIALS /- # VERTEX_CREDENTIALS_PATH) must never reach the credential pool or the- # generic api_key resolver — those would treat the file path as a static- # API key. Instead we mint a short-lived OAuth2 access token here and hand- # it to the standard OpenAI client as api_key, with base_url computed from- # the project ID + region. The token is re-minted per call (5-min refresh- # margin) by get_vertex_config(); mid-session expiry is additionally- # recovered on 401 by run_agent._try_refresh_vertex_client_credentials().++ # Vertex AI (OAuth2): resolve BEFORE the pool / generic paths — the credential *path*+ # (GOOGLE_APPLICATION_CREDENTIALS) must never be treated as a static API key. A short-lived+ # token is minted per call by get_vertex_config(); mid-session expiry is recovered on 401 by+ # run_agent._try_refresh_vertex_client_credentials().if requested_provider in ("vertex", "google-vertex", "vertex-ai", "gcp-vertex", "vertexai"):from agent.vertex_adapter import get_vertex_config@@ -2088,14 +1853,14 @@ def resolve_runtime_provider("config.yaml if they aren't embedded in the credentials. ""Run `hermes setup` to install Vertex support.")- return {- "provider": "vertex",- "api_mode": "chat_completions",- "base_url": base_url.rstrip("/"),- "api_key": token,- "source": "vertex-oauth",- "requested_provider": requested_provider,- }+ return _runtime(+ "vertex",+ "chat_completions",+ base_url.rstrip("/"),+ token,+ source="vertex-oauth",+ requested_provider=requested_provider,+ )custom_runtime = _resolve_named_custom_runtime(requested_provider=requested_provider,@@ -2107,34 +1872,20 @@ def resolve_runtime_provider(custom_runtime["requested_provider"] = requested_providerreturn custom_runtime- # If provider is "auto" (or unset) but config.yaml has an explicit base_url- # pointing at a custom/local endpoint (e.g. Ollama at localhost:11434),- # route through the OpenAI-compatible resolver instead of letting- # resolve_provider() pick up an ANTHROPIC_API_KEY or OPENAI_API_KEY from- # the environment and send the request to a cloud API. Fixes #3846.+ # provider "auto"/unset with a config base_url at a custom/local endpoint routes through the+ # OpenAI-compatible resolver, so resolve_provider() cannot pick up an env ANTHROPIC/OPENAI+ # key and send the request to a cloud API (#3846).if not explicit_base_url and not explicit_api_key:model_cfg = _get_model_config()cfg_provider = str(model_cfg.get("provider") or "").strip().lower()cfg_base_url = str(model_cfg.get("base_url") or "").strip()if cfg_base_url and cfg_provider in ("auto", ""):- # Check that base_url isn't one of the well-known cloud API roots- # (OpenRouter, Anthropic, OpenAI). If it's something else (Ollama,- # LM Studio, vLLM, …) we honour it directly. The full detection- # logic lives in _resolve_openrouter_runtime; we just skip the- # resolve_provider() call so env-var credentials don't shadow it.- # Match on HOST, not substring, so a look-alike base_url- # (e.g. http://api.anthropic.com.attacker.test/v1, or one whose- # path merely contains "openai.com") cannot evade the bypass and- # leak a cloud credential. Mirrors the host-gating used for- # API-key selection in _resolve_openrouter_runtime.- _known_cloud_hosts = (- "openrouter.ai",- "anthropic.com",- "openai.com",- )+ # Only non-cloud roots (Ollama, LM Studio, vLLM, …) take the bypass. Match on HOST,+ # not substring, so a look-alike (api.anthropic.com.attacker.test) cannot leak a+ # cloud credential.if not any(base_url_host_matches(cfg_base_url, host)- for host in _known_cloud_hosts+ for host in ("openrouter.ai", "anthropic.com", "openai.com")):runtime = _resolve_openrouter_runtime(requested_provider=requested_provider,@@ -2151,13 +1902,9 @@ def resolve_runtime_provider()model_cfg = _get_model_config()- # OpenCode Zen free tier (*-free slugs, e.g. x-preview-f-free /- # "Ox Alpha"): served ANONYMOUSLY on the Zen relay ONLY. Any bearer the- # relay doesn't recognize is a 401 — and the Go relay doesn't serve the- # free tier at all ("Model x is not supported"), so a valid OpenCode GO- # subscription key still fails. Route free slugs through the keyless Zen- # runtime BEFORE the credential-pool / explicit / api_key paths so they- # work with any OpenCode credential state, including none.+ # OpenCode Zen free tier (*-free slugs) is served ANONYMOUSLY on the Zen relay only: unknown+ # bearers 401 and the Go relay rejects free models. Route free slugs through the keyless Zen+ # runtime BEFORE the pool / explicit / api_key paths.from hermes_cli.models import (opencode_provider_family as _oc_family_fn,opencode_zen_free_runtime as _oc_free_runtime_fn,@@ -2208,26 +1955,13 @@ def resolve_runtime_provider(pool = Noneif pool and pool.has_credentials():entry = pool.select()- pool_api_key = ""- if entry is not None:- pool_api_key = (- getattr(entry, "runtime_api_key", None)- or getattr(entry, "access_token", "")- )- # For Nous, the pool entry's runtime_api_key is the agent_key- # compatibility field. It must be an invoke JWT. The pool doesn't- # refresh it during selection (that would trigger network calls in- # non-runtime contexts like `hermes auth list`). If the key is- # expired/missing, refresh the selected pool entry before falling back- # to singleton auth resolution.+ pool_api_key = _pool_entry_api_key(entry) if entry is not None else ""+ # Nous pool entries carry the agent_key (an invoke JWT) which the pool does not refresh+ # on selection (avoids network calls in `hermes auth list`); refresh it here before+ # falling back to singleton auth resolution.if provider == "nous" and entry is not None:min_ttl = max(60, env_int("HERMES_NOUS_MIN_KEY_TTL_SECONDS", 1800))- nous_state = {- "agent_key": getattr(entry, "agent_key", None),- "agent_key_expires_at": getattr(entry, "agent_key_expires_at", None),- "scope": getattr(entry, "scope", None),- }- if not _agent_key_is_usable(nous_state, min_ttl):+ if not _agent_key_is_usable(_nous_pool_state(entry), min_ttl):logger.debug("Nous pool entry agent_key expired/missing, refreshing selected pool entry")try:refreshed = pool.try_refresh_current()@@ -2236,16 +1970,8 @@ def resolve_runtime_provider(refreshed = Noneif refreshed is not None:entry = refreshed- pool_api_key = (- getattr(entry, "runtime_api_key", None)- or getattr(entry, "access_token", "")- )- nous_state = {- "agent_key": getattr(entry, "agent_key", None),- "agent_key_expires_at": getattr(entry, "agent_key_expires_at", None),- "scope": getattr(entry, "scope", None),- }- if not pool_api_key or not _agent_key_is_usable(nous_state, min_ttl):+ pool_api_key = _pool_entry_api_key(entry)+ if not pool_api_key or not _agent_key_is_usable(_nous_pool_state(entry), min_ttl):logger.debug("Nous pool entry agent_key still unavailable, falling through to runtime resolution")pool_api_key = ""if (@@ -2254,11 +1980,7 @@ def resolve_runtime_provider(and credential_pool_matches_provider(pool,provider,- base_url=(- getattr(entry, "runtime_base_url", None)- or getattr(entry, "base_url", None)- or ""- ),+ base_url=_pool_entry_base_url(entry),)):return _resolve_runtime_from_pool_entry(@@ -2270,145 +1992,76 @@ def resolve_runtime_provider(target_model=target_model,)- if provider == "nous":- try:- from hermes_cli.providers import nous_api_mode-- creds = resolve_nous_runtime_credentials(- timeout_seconds=float(_getenv("HERMES_NOUS_TIMEOUT_SECONDS", "15")),- )- return {- "provider": "nous",- "api_mode": nous_api_mode(target_model or model_cfg.get("default") or ""),- "base_url": creds.get("base_url", "").rstrip("/"),- "api_key": creds.get("api_key", ""),- "source": creds.get("source", "portal"),- "expires_at": creds.get("expires_at"),- "requested_provider": requested_provider,- }- except AuthError:- if requested_provider != "auto":- raise- # Auto-detected Nous but credentials are stale/revoked —- # fall through to env-var providers (e.g. OpenRouter).- logger.info("Auto-detected Nous provider but credentials failed; "- "falling through to next provider.")-- if provider == "openai-codex":+ if provider in _OAUTH_RUNTIME_PROVIDERS:+ spec = _OAUTH_RUNTIME_PROVIDERS[provider]try:- creds = resolve_codex_runtime_credentials()- return {- "provider": "openai-codex",- "api_mode": "codex_responses",- "base_url": creds.get("base_url", "").rstrip("/"),- "api_key": creds.get("api_key", ""),- "source": creds.get("source", "hermes-auth-store"),- "last_refresh": creds.get("last_refresh"),- "requested_provider": requested_provider,- }+ creds = spec.resolve()except AuthError:if requested_provider != "auto":raise- # Auto-detected Codex but credentials are stale/revoked —- # fall through to env-var providers (e.g. OpenRouter).- logger.info("Auto-detected Codex provider but credentials failed; "- "falling through to next provider.")-- if provider == "xai-oauth":- try:- creds = resolve_xai_oauth_runtime_credentials()- return {- "provider": "xai-oauth",- "api_mode": "codex_responses",- "base_url": (creds.get("base_url") or "").rstrip("/") or DEFAULT_XAI_OAUTH_BASE_URL,- "api_key": creds.get("api_key", ""),- "source": creds.get("source", "hermes-auth-store"),- "last_refresh": creds.get("last_refresh"),- "requested_provider": requested_provider,- }- except AuthError:- if requested_provider != "auto":- raise- logger.info("Auto-detected xAI OAuth provider but credentials failed; "- "falling through to next provider.")-- if provider == "qwen-oauth":- try:- creds = resolve_qwen_runtime_credentials()- return {- "provider": "qwen-oauth",- "api_mode": "chat_completions",- "base_url": creds.get("base_url", "").rstrip("/"),- "api_key": creds.get("api_key", ""),- "source": creds.get("source", "qwen-cli"),- "expires_at_ms": creds.get("expires_at_ms"),- "requested_provider": requested_provider,- }- except AuthError:- if requested_provider != "auto":- raise- logger.info("Qwen OAuth credentials failed; "- "falling through to next provider.")+ # Auto-detected but credentials are stale/revoked — fall through+ # to env-var providers (e.g. OpenRouter).+ logger.info("%s; falling through to next provider.", spec.failure_msg)+ else:+ api_mode = spec.api_mode+ if callable(api_mode):+ api_mode = api_mode(target_model or model_cfg.get("default") or "")+ return _runtime(+ provider,+ api_mode,+ (creds.get("base_url") or "").rstrip("/") or spec.default_base_url,+ creds.get("api_key", ""),+ source=creds.get("source", spec.default_source),+ **{spec.expiry_key: creds.get(spec.expiry_key)},+ requested_provider=requested_provider,+ )if provider == "minimax-oauth":pconfig = PROVIDER_REGISTRY.get(provider)if pconfig and pconfig.auth_type == "oauth_minimax":from hermes_cli.auth import resolve_minimax_oauth_runtime_credentialscreds = resolve_minimax_oauth_runtime_credentials()- return {- "provider": provider,- "api_mode": "anthropic_messages",- "base_url": creds["base_url"],- "api_key": creds["api_key"],- "source": creds.get("source", "oauth"),- "requested_provider": requested_provider,- }+ return _runtime(+ provider,+ "anthropic_messages",+ creds["base_url"],+ creds["api_key"],+ source=creds.get("source", "oauth"),+ requested_provider=requested_provider,+ )# External-process providers (an agent CLI driven over stdio, e.g. ACP).# Keyed on the registered provider's auth_type rather than on one name, so a# provider shipped outside this tree lands on the same credential path.if _is_external_process_provider(provider):creds = resolve_external_process_provider_credentials(provider)- return {- "provider": provider,- "api_mode": "chat_completions",- "base_url": creds.get("base_url", "").rstrip("/"),- "api_key": creds.get("api_key", ""),- "command": creds.get("command", ""),- "args": list(creds.get("args") or []),- "source": creds.get("source", "process"),- "requested_provider": requested_provider,- }+ return _runtime(+ provider,+ "chat_completions",+ creds.get("base_url", "").rstrip("/"),+ creds.get("api_key", ""),+ command=creds.get("command", ""),+ args=list(creds.get("args") or []),+ source=creds.get("source", "process"),+ requested_provider=requested_provider,+ )# Anthropic (native Messages API)if provider == "anthropic":# Allow base URL override from config.yaml model.base_url, but only# when the configured provider is anthropic — otherwise a non-Anthropic# base_url (e.g. Codex endpoint) would leak into Anthropic requests.- cfg_provider = str(model_cfg.get("provider") or "").strip().lower()- cfg_base_url = ""- if cfg_provider == "anthropic":- cfg_base_url = (model_cfg.get("base_url") or "").strip().rstrip("/")- if not _anthropic_base_url_override_ok(cfg_base_url):- cfg_base_url = ""- base_url = cfg_base_url or "https://api.anthropic.com"-- # For Microsoft Foundry endpoints, use ANTHROPIC_API_KEY directly —- # Claude Code OAuth tokens (sk-ant-oat01) are not accepted by Azure.- # Azure keys don't start with "sk-ant-" so resolve_anthropic_token()- # would find the Claude Code OAuth token first (priority 3) and return- # that instead, causing 401s. Detect Azure endpoints and use the env- # key directly to bypass the OAuth priority chain.+ cfg_base_url = _anthropic_cfg_base_url(model_cfg)+ base_url = cfg_base_url or _ANTHROPIC_DEFAULT_BASE_URL++ # Microsoft Foundry endpoints reject Claude Code OAuth tokens, which+ # resolve_anthropic_token() would return first — use the env key directly._is_azure_endpoint = base_url_host_matches(base_url, "azure.com") or (cfg_base_url and base_url_host_matches(cfg_base_url, "azure.com"))if _is_azure_endpoint:- # Honor user-specified env var hints on the model config before- # falling back to the built-in AZURE_ANTHROPIC_KEY / ANTHROPIC_API_KEY- # chain. Accept both `key_env` (Hermes canonical — matches the- # custom_providers field name) and `api_key_env` (documented in the- # Azure Foundry guide and read by most Hermes-compatible importers).- # Matches the config.yaml examples in website/docs/guides/azure-foundry.md.+ # Env var hints on the model config first: `key_env` (Hermes canonical) and+ # `api_key_env` (Azure Foundry guide / importers).token = ""for hint_key in ("key_env", "api_key_env"):env_var = str(model_cfg.get(hint_key) or "").strip()@@ -2416,16 +2069,14 @@ def resolve_runtime_provider(token = _getenv(env_var, "").strip()if token:break- # Next: an inline api_key on the model config (useful in multi-profile- # setups that want to avoid env-var juggling).- if not token:- token = str(model_cfg.get("api_key") or "").strip()- # Finally fall back to the historical fixed names.- if not token:- token = (- _getenv("AZURE_ANTHROPIC_KEY", "").strip()- or _getenv("ANTHROPIC_API_KEY", "").strip()- )+ # Then an inline api_key on the model config (multi-profile setups),+ # finally the historical fixed names.+ token = (+ token+ or str(model_cfg.get("api_key") or "").strip()+ or _getenv("AZURE_ANTHROPIC_KEY", "").strip()+ or _getenv("ANTHROPIC_API_KEY", "").strip()+ )if not token:raise AuthError("No Azure Anthropic API key found. Set AZURE_ANTHROPIC_KEY or "@@ -2436,18 +2087,15 @@ def resolve_runtime_provider(from agent.anthropic_adapter import resolve_anthropic_tokentoken = resolve_anthropic_token()if not token:- raise AuthError(- "No Anthropic credentials found. Set ANTHROPIC_TOKEN or ANTHROPIC_API_KEY, "- "run 'claude setup-token', or authenticate with 'claude /login'."- )- return {- "provider": "anthropic",- "api_mode": "anthropic_messages",- "base_url": base_url,- "api_key": token,- "source": "env",- "requested_provider": requested_provider,- }+ raise AuthError(_NO_ANTHROPIC_CREDENTIALS_MSG)+ return _runtime(+ "anthropic",+ "anthropic_messages",+ base_url,+ token,+ source="env",+ requested_provider=requested_provider,+ )# AWS Bedrock (native Converse API via boto3)if provider == "bedrock":@@ -2460,10 +2108,8 @@ def resolve_runtime_provider(bedrock_openai_base_url,resolve_bedrock_bearer_token,)- # When the user explicitly selected bedrock (not auto-detected),- # trust boto3's credential chain — it handles IMDS, ECS task roles,- # Lambda execution roles, SSO, and other implicit sources that our- # env-var check can't detect.+ # Explicitly selected bedrock trusts boto3's credential chain (IMDS, ECS/Lambda roles,+ # SSO) which our env-var check can't detect.is_explicit = requested_provider in {"bedrock", "aws", "aws-bedrock", "amazon-bedrock", "amazon"}if not is_explicit and not has_aws_credentials():raise AuthError(@@ -2489,60 +2135,38 @@ def resolve_runtime_provider("guardrailIdentifier": _gr["guardrail_identifier"],"guardrailVersion": _gr["guardrail_version"],}- if _gr.get("stream_processing_mode"):- guardrail_config["streamProcessingMode"] = _gr["stream_processing_mode"]- if _gr.get("trace"):- guardrail_config["trace"] = _gr["trace"]- # Triple-path routing:- # - OpenAI GPT-5.5 on Bedrock uses Bedrock Mantle's OpenAI Responses- # endpoint (not Converse / bedrock-runtime).- # - Claude models use AnthropicBedrock SDK for prompt caching,- # thinking budgets, and adaptive thinking.- # - Other models use the native Converse API.- #- # Exception: Bearer Token auth (AWS_BEARER_TOKEN_BEDROCK) is NOT- # supported by the AnthropicBedrock SDK (it only does SigV4 signing —- # a bearer-only setup fails at runtime with "could not resolve- # credentials from session"). Route these users through the Converse- # API regardless of model. Ref: #28156.+ for src_key, dst_key in (("stream_processing_mode", "streamProcessingMode"), ("trace", "trace")):+ if _gr.get(src_key):+ guardrail_config[dst_key] = _gr[src_key]+ # Triple-path routing: OpenAI models → Bedrock Mantle's Responses endpoint; Claude →+ # AnthropicBedrock SDK (prompt caching, thinking budgets); others → Converse API.+ # Exception: AWS_BEARER_TOKEN_BEDROCK auth is unsupported by AnthropicBedrock (SigV4+ # only), so bearer users go through Converse regardless of model (#28156)._current_model = str(target_model or model_cfg.get("default") or "").strip()_has_bearer_token = bool(os.environ.get("AWS_BEARER_TOKEN_BEDROCK", "").strip())+ runtime = _runtime(+ "bedrock",+ "bedrock_converse",+ f"https://bedrock-runtime.{region}.amazonaws.com",+ "aws-sdk",+ source=auth_source,+ region=region,+ requested_provider=requested_provider,+ )if is_openai_bedrock_model(_current_model):bearer = resolve_bedrock_bearer_token()- runtime = {- "provider": "bedrock",- "api_mode": "codex_responses",- "base_url": bedrock_openai_base_url(region),- "api_key": bearer or "aws-sdk",- "source": "AWS_BEARER_TOKEN_BEDROCK" if bearer else auth_source,- "region": region,- "model": _current_model,- "bedrock_openai": True,- "requested_provider": requested_provider,- }+ runtime.update(+ api_mode="codex_responses",+ base_url=bedrock_openai_base_url(region),+ api_key=bearer or "aws-sdk",+ source="AWS_BEARER_TOKEN_BEDROCK" if bearer else auth_source,+ model=_current_model,+ bedrock_openai=True,+ )elif is_anthropic_bedrock_model(_current_model) and not _has_bearer_token:# Claude on Bedrock → AnthropicBedrock SDK → anthropic_messages path- runtime = {- "provider": "bedrock",- "api_mode": "anthropic_messages",- "base_url": f"https://bedrock-runtime.{region}.amazonaws.com",- "api_key": "aws-sdk",- "source": auth_source,- "region": region,- "bedrock_anthropic": True, # Signal to use AnthropicBedrock client- "requested_provider": requested_provider,- }- else:- # Non-Claude/OpenAI (Nova, DeepSeek, Llama, GPT-OSS, etc.) → Converse API- runtime = {- "provider": "bedrock",- "api_mode": "bedrock_converse",- "base_url": f"https://bedrock-runtime.{region}.amazonaws.com",- "api_key": "aws-sdk",- "source": auth_source,- "region": region,- "requested_provider": requested_provider,- }+ runtime.update(api_mode="anthropic_messages", bedrock_anthropic=True)+ # else: Non-Claude/OpenAI (Nova, DeepSeek, Llama, GPT-OSS, etc.) → Converse APIif guardrail_config:runtime["guardrail_config"] = guardrail_configreturn runtime@@ -2551,10 +2175,8 @@ def resolve_runtime_provider(pconfig = PROVIDER_REGISTRY.get(provider)if pconfig and pconfig.auth_type == "api_key":creds = resolve_api_key_provider_credentials(provider)- # Actual Computer: a loopback base_url configured in model_cfg (not- # just env) selects the daemon's local offline API, which requires no- # auth. Inject the placeholder BEFORE the usable-secret gate below,- # mirroring the env-driven path inside the credential resolver.+ # Actual Computer: a loopback model_cfg base_url selects the daemon's no-auth local API;+ # inject the placeholder BEFORE the usable-secret gate (mirrors the env-driven path).if provider == "actual" and not has_usable_secret(creds.get("api_key")):_cfg_provider = str(model_cfg.get("provider") or "").strip().lower()_cfg_url = ""@@ -2567,12 +2189,9 @@ def resolve_runtime_provider(creds = dict(creds)creds["api_key"] = ACTUAL_LOCAL_NOAUTH_PLACEHOLDERcreds["source"] = creds.get("source") or "local-offline"- # An explicitly selected API-key provider is authoritative. Returning- # a runtime with an empty key defers failure until the first request and- # can make a later fallback look like a silent provider switch. Fail at- # resolution so callers surface the missing credential (or consult only- # an explicitly configured fallback chain). LM Studio's no-auth path- # supplies a non-empty placeholder in the credential resolver above.+ # An explicitly selected API-key provider is authoritative: an empty key would defer+ # failure to the first request and make a later fallback look like a silent provider+ # switch. LM Studio's no-auth path supplies a placeholder in the credential resolver.if not has_usable_secret(creds.get("api_key")):env_names = ", ".join(pconfig.api_key_env_vars)hint = f" Set {env_names}." if env_names else ""@@ -2581,72 +2200,29 @@ def resolve_runtime_provider(provider=provider,code="missing_api_key",)- # Honour model.base_url from config.yaml when the configured provider- # matches this provider — mirrors the Anthropic path above. Without- # this, users who set model.base_url to e.g. api.minimaxi.com/anthropic- # (China endpoint) still get the hardcoded api.minimax.io default (#6039).- cfg_provider = str(model_cfg.get("provider") or "").strip().lower()- cfg_base_url = ""- if cfg_provider == provider:- cfg_base_url = (model_cfg.get("base_url") or "").strip().rstrip("/")- base_url = cfg_base_url or creds.get("base_url", "").rstrip("/")+ # Honour model.base_url when the configured provider matches (e.g. the+ # api.minimaxi.com China endpoint instead of the hardcoded default, #6039).+ base_url = _config_base_url_for_provider(model_cfg, provider) or creds.get("base_url", "").rstrip("/")if provider == "actual":base_url = normalize_actual_base_url(base_url)- api_mode = "chat_completions"- if provider == "copilot":- api_mode = _copilot_runtime_api_mode(- model_cfg,- creds.get("api_key", ""),- target_model=target_model,- )- elif provider == "xai":- api_mode = "codex_responses"- elif provider == "actual":- api_mode = "codex_responses"- else:- configured_provider = str(model_cfg.get("provider") or "").strip().lower()- # Only honor persisted api_mode when it belongs to the same provider family.- configured_mode = _parse_api_mode(model_cfg.get("api_mode"))- from hermes_cli.models import opencode_provider_family- if opencode_provider_family(provider) is not None:- # opencode-zen/go must always re-derive api_mode from the- # target model (not the stale persisted api_mode), because- # the same provider serves both anthropic_messages- # (e.g. minimax-m2.7) and chat_completions (e.g.- # deepseek-v4-flash) and switching models via /model would- # otherwise carry the previous mode forward, stripping /v1- # from base_url for chat_completions models and 404'ing.- # Refs #16878.- from hermes_cli.models import opencode_model_api_mode- _effective = target_model or model_cfg.get("default", "")- api_mode = opencode_model_api_mode(provider, _effective)- elif configured_mode and _provider_supports_explicit_api_mode(provider, configured_provider):- api_mode = configured_mode- else:- # URL detection first (e.g. https://api.minimax.io/anthropic,- # official OpenAI hosts → codex_responses, api.x.ai →- # codex_responses), then the provider's declared transport.- api_mode = _fallback_api_mode(- provider, base_url, target_model or model_cfg.get("default", "")- )- # Normalize the /v1 suffix for OpenCode by API mode (see comment above).- from hermes_cli.models import opencode_provider_family- if opencode_provider_family(provider) is not None:- from hermes_cli.models import normalize_opencode_base_url- base_url = normalize_opencode_base_url(provider, api_mode, base_url)+ api_mode = _api_key_provider_api_mode(+ provider, model_cfg, creds.get("api_key", ""), base_url,+ target_model or model_cfg.get("default", ""), opencode_by_model=True,+ )+ base_url = _normalize_opencode_runtime_base_url(provider, api_mode, base_url)if provider == "lmstudio":base_url = auth_mod._normalize_lmstudio_runtime_base_url(base_url)api_key = creds.get("api_key", "")if provider == "actual" and not api_key and is_actual_local_base_url(base_url):api_key = ACTUAL_LOCAL_NOAUTH_PLACEHOLDER- return {- "provider": provider,- "api_mode": api_mode,- "base_url": base_url,- "api_key": api_key,- "source": creds.get("source", "env"),- "requested_provider": requested_provider,- }+ return _runtime(+ provider,+ api_mode,+ base_url,+ api_key,+ source=creds.get("source", "env"),+ requested_provider=requested_provider,+ )runtime = _resolve_openrouter_runtime(requested_provider=requested_provider,diff --git a/hermes_cli/xai_retirement.py b/hermes_cli/xai_retirement.pyindex 965cc1b13e2..e6670c16142 100644--- a/hermes_cli/xai_retirement.py+++ b/hermes_cli/xai_retirement.py@@ -1,11 +1,4 @@-"""Detect xAI models retired on May 15, 2026.--Source: https://docs.x.ai/developers/migration/may-15-retirement--Pure logic: walks a Hermes config dict, returns issues for any reference-to a retired xAI model. No I/O, no CLI dependencies — testable in isolation-and reusable from both `hermes doctor` and a future `hermes migrate xai`.-"""+"""Detect xAI models retired on May 15, 2026."""from __future__ import annotationsfrom dataclasses import dataclass@@ -62,12 +55,8 @@ def _looks_like_xai(model_id: Optional[str]) -> bool:def find_retired_xai_refs(config: Dict[str, Any]) -> List[RetirementIssue]:"""Walk all model slots in a Hermes config and return retirement issues.- Slots scanned:- - ``principal.model``- - ``auxiliary.<any>.model`` (introspective — covers future aux slots)- - ``delegation.model``- - ``tts.xai.model``- - ``plugins.image_gen.xai.model``+ Slots scanned: ``principal.model``, ``auxiliary.<any>.model`` (introspective, covers future+ aux slots), ``delegation.model``, ``tts.xai.model``, ``plugins.image_gen.xai.model``."""issues: List[RetirementIssue] = []@@ -86,36 +75,31 @@ def find_retired_xai_refs(config: Dict[str, Any]) -> List[RetirementIssue]:note=entry.get("note"),))+ def _section(*keys: str) -> Optional[Dict[str, Any]]:+ node: Any = config+ for key in keys:+ if not isinstance(node, dict):+ return None+ node = node.get(key)+ return node if isinstance(node, dict) else None+if not isinstance(config, dict):return issues- principal = config.get("principal")- if isinstance(principal, dict):+ principal = _section("principal")+ if principal is not None:_check("principal.model", principal.get("model"))- aux = config.get("auxiliary")- if isinstance(aux, dict):+ aux = _section("auxiliary")+ if aux is not None:for slot_name, slot_cfg in aux.items():if isinstance(slot_cfg, dict):_check(f"auxiliary.{slot_name}.model", slot_cfg.get("model"))- delegation = config.get("delegation")- if isinstance(delegation, dict):- _check("delegation.model", delegation.get("model"))-- tts = config.get("tts")- if isinstance(tts, dict):- tts_xai = tts.get("xai")- if isinstance(tts_xai, dict):- _check("tts.xai.model", tts_xai.get("model"))-- plugins = config.get("plugins")- if isinstance(plugins, dict):- image_gen = plugins.get("image_gen")- if isinstance(image_gen, dict):- ig_xai = image_gen.get("xai")- if isinstance(ig_xai, dict):- _check("plugins.image_gen.xai.model", ig_xai.get("model"))+ for path in (("delegation",), ("tts", "xai"), ("plugins", "image_gen", "xai")):+ section = _section(*path)+ if section is not None:+ _check(".".join(path) + ".model", section.get("model"))return issues@@ -153,11 +137,7 @@ class ApplyResult:def _walk_to_parent(yaml_doc: Any, dotted_path: str) -> "tuple[Any, str]":- """Resolve a dotted slot path to (parent_mapping, leaf_key).-- Example: "auxiliary.vision.model" -> (yaml_doc["auxiliary"]["vision"], "model").- Raises KeyError if any intermediate node is missing or not a mapping.- """+ """Resolve a dotted slot path to (parent_mapping, leaf_key)."""parts = dotted_path.split(".")if len(parts) < 2:raise ValueError(f"Path must have at least one parent: {dotted_path!r}")@@ -176,31 +156,23 @@ def apply_migration() -> ApplyResult:"""Rewrite ``config_path`` in-place so each issue is resolved.- For every issue, the model name is replaced by ``issue.replacement``. If the- issue has ``reasoning_effort`` set (i.e. the migration is from a- ``*-non-reasoning`` variant), a sibling ``reasoning_effort`` key is added- or updated alongside the model.-- Uses ``ruamel.yaml`` round-trip mode so comments, key order, indentation,- and type literals (booleans, ints) are preserved.+ Uses ``ruamel.yaml`` round-trip mode so comments, key order, indentation, and type literals+ (booleans, ints) are preserved.- A backup copy is written to- ``<config_path>.bak-pre-migrate-xai-YYYYMMDD-HHMMSS`` before rewriting,- unless ``backup=False``.+ A backup copy is written to ``<config_path>.bak-pre-migrate-xai-YYYYMMDD-HHMMSS`` before+ rewriting, unless ``backup=False``."""from ruamel.yaml import YAML # local import — avoid hard dep at module loadconfig_path = Path(config_path)if not config_path.exists():raise FileNotFoundError(config_path)+ unchanged = ApplyResult(+ file_path=config_path, backup_path=None, issues_resolved=[], config_changed=False+ )if not issues:- return ApplyResult(- file_path=config_path,- backup_path=None,- issues_resolved=[],- config_changed=False,- )+ return unchangedyaml = YAML(typ="rt")yaml.preserve_quotes = True@@ -208,12 +180,7 @@ def apply_migration(doc = yaml.load(fh)if doc is None:- return ApplyResult(- file_path=config_path,- backup_path=None,- issues_resolved=[],- config_changed=False,- )+ return unchangedresolved: List[RetirementIssue] = []for issue in issues:@@ -228,12 +195,7 @@ def apply_migration(resolved.append(issue)if not resolved:- return ApplyResult(- file_path=config_path,- backup_path=None,- issues_resolved=[],- config_changed=False,- )+ return unchangedbackup_path: Optional[Path] = Noneif backup: