Skip to content

The agent that grows with you

refactor(models): extract validate_requested_model into models_validate with shared verdict/match helpers; drop dead _OPENCODE_KEYLESS_EXTRA_SLUGS

Teknium120aa68922fe
diff --git a/hermes_cli/models.py b/hermes_cli/models.py
index 99d7b023fbb..a80c0cf1dbb 100644
--- a/hermes_cli/models.py
+++ b/hermes_cli/models.py
@@ -23,6 +23,7 @@ if TYPE_CHECKING:
from hermes_cli import __version__ as _HERMES_VERSION
from hermes_cli.urllib_security import open_credentialed_url, url_origin
from utils import atomic_json_write, base_url_host_matches
+from hermes_cli.models_validate import validate_requested_model # noqa: F401 (re-exported)
logger = logging.getLogger(__name__)
@@ -5518,10 +5519,6 @@ def normalize_opencode_model_id(provider_id: Optional[str], model_id: Optional[s
OPENCODE_ZEN_FREE_KEYLESS_PLACEHOLDER = "opencode-zen-free-keyless"
_OPENCODE_ZEN_FREE_BASE_URL = "https://opencode.ai/zen/v1"
-# Free-tier models whose slug does NOT carry the ``-free`` suffix.
-# (big-pickle is OpenCode's rotating free stealth slot.)
-_OPENCODE_KEYLESS_EXTRA_SLUGS = frozenset({"big-pickle"})
-
# Models whose slug carries ``-free`` but are NOT anonymous-servable: they are
# KEYED (Go-subscription) models and must be excluded from the keyless free
# catalog even though the suffix looks free. ox-alpha-free is the Go relay's
@@ -6394,804 +6391,3 @@ def fetch_ollama_cloud_models(
return stale["models"]
return []
-
-
-def validate_requested_model(
- model_name: str,
- provider: Optional[str],
- *,
- api_key: Optional[str] = None,
- base_url: Optional[str] = None,
- api_mode: Optional[str] = None,
- headers: Optional[dict[str, str]] = None,
-) -> dict[str, Any]:
- """Validate a ``/model`` value for the active provider.
-
- 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)
- if normalized == "openrouter" and base_url and not base_url_host_matches(base_url, "openrouter.ai"):
- normalized = "custom"
- requested_for_lookup = requested
- if normalized == "copilot":
- requested_for_lookup = normalize_copilot_model_id(
- requested,
- api_key=api_key,
- ) or requested
-
- if not requested:
- return {
- "accepted": False,
- "persist": False,
- "recognized": False,
- "message": "Model name cannot be empty.",
- }
-
- if normalized == "moa":
- try:
- from hermes_cli.config import load_config
- from hermes_cli.moa_config import normalize_moa_config
-
- cfg = normalize_moa_config(load_config().get("moa") or {})
- if requested in cfg["presets"]:
- return {"accepted": True, "persist": True, "recognized": True, "message": None}
- return {
- "accepted": False, "persist": False, "recognized": False,
- "message": f"MoA preset `{requested}` was not found. Run `hermes moa list`.",
- }
- except Exception as exc:
- return {
- "accepted": False, "persist": False, "recognized": False,
- "message": f"Could not read MoA presets: {exc}",
- }
-
- if any(ch.isspace() for ch in requested):
- return {
- "accepted": False,
- "persist": False,
- "recognized": False,
- "message": "Model names cannot contain spaces.",
- }
-
- # OpenRouter presets are account-scoped configurations, so direct
- # ``@preset/<slug>`` references never appear in the public /v1/models
- # listing. Combined ``<model>@preset/<slug>`` references are also valid;
- # validate their base model normally and preserve the preset suffix if a
- # close match is auto-corrected. OpenRouter validates the preset slug when
- # the inference request is made.
- preset_suffix = ""
-
- def _with_preset_suffix(model_id: str) -> str:
- """Re-attach a preserved ``@preset/<slug>`` suffix after auto-correction."""
- return f"{model_id}{preset_suffix}"
-
- if normalized == "openrouter":
- marker = "@preset/"
- if marker in requested:
- if requested.count(marker) != 1:
- preset_slug = ""
- preset_base = requested
- else:
- preset_base, preset_slug = requested.split(marker, 1)
- if re.fullmatch(r"[A-Za-z0-9._~-]+", preset_slug) is None:
- return {
- "accepted": False,
- "persist": False,
- "recognized": False,
- "message": (
- "OpenRouter preset slugs must be non-empty URL-safe "
- "identifiers using only letters, digits, '.', '_', "
- "'~', or '-'."
- ),
- }
- preset_suffix = f"{marker}{preset_slug}"
- if not preset_base:
- return {
- "accepted": True,
- "persist": True,
- "recognized": False,
- "message": None,
- }
- requested_for_lookup = preset_base
-
- if normalized == "lmstudio":
- from hermes_cli.auth import AuthError
- # Use probe_lmstudio_models so we can distinguish None (unreachable
- # / malformed response) from [] (reachable, but no chat-capable models
- # are loaded). fetch_lmstudio_models collapses both to [].
- try:
- models = probe_lmstudio_models(api_key=api_key, base_url=base_url)
- except AuthError as exc:
- return {
- "accepted": False, "persist": False, "recognized": False,
- "message": (
- f"{exc} Set `LM_API_KEY` (or update it) to match the server's bearer token."
- ),
- }
- if models is None:
- return {
- "accepted": False, "persist": False, "recognized": False,
- "message": f"Could not reach LM Studio's `/api/v1/models` to validate `{requested}`.",
- }
- if not models:
- return {
- "accepted": False, "persist": False, "recognized": False,
- "message": (
- f"LM Studio is reachable but no chat-capable models are loaded. "
- f"Load `{requested}` in LM Studio (Developer tab → Load Model) and try again."
- ),
- }
- if requested_for_lookup in set(models):
- return {"accepted": True, "persist": True, "recognized": True, "message": None}
- return {
- "accepted": False, "persist": False, "recognized": False,
- "message": f"Model `{requested}` was not found in LM Studio's model listing.",
- }
-
- if str(provider or "").strip().lower() == "ollama" and not base_url:
- base_url = _get_ollama_base_url()
- ollama_base_url = base_url
- configured_ollama_base_url = str(
- (
- _get_provider_config_dict("ollama").get("base_url")
- or _get_provider_config_dict("ollama").get("api")
- or _get_provider_config_dict("ollama").get("url")
- or ""
- )
- ).strip()
- configured_headers_allowed = not (
- configured_ollama_base_url
- and not _same_ollama_native_root(ollama_base_url or "", configured_ollama_base_url)
- )
- if headers is not None:
- ollama_headers = {}
- if configured_headers_allowed:
- ollama_headers.update(
- _get_ollama_native_headers(ollama_base_url, api_key=api_key)
- )
- for key in tuple(ollama_headers):
- if key.lower() == "authorization":
- del ollama_headers[key]
- ollama_headers.update(headers)
- caller_has_authorization = any(
- key.lower() == "authorization" for key in headers
- )
- if api_key and not caller_has_authorization:
- for key in tuple(ollama_headers):
- if key.lower() == "authorization":
- del ollama_headers[key]
- ollama_headers["Authorization"] = f"Bearer {api_key}"
- elif configured_headers_allowed:
- ollama_headers = _get_ollama_native_headers(ollama_base_url, api_key=api_key)
- else:
- ollama_headers = {}
- if should_use_ollama_native_catalog(
- provider, ollama_base_url, headers=ollama_headers
- ):
- ollama_models = probe_ollama_local_models(
- ollama_base_url, headers=ollama_headers
- )
- if ollama_models is None:
- # A failed native probe is not authoritative; fall back to the
- # existing OpenAI-compatible catalog before accepting blindly.
- ollama_models = probe_api_models(
- api_key,
- _normalize_openai_base_url(ollama_base_url),
- request_headers=ollama_headers,
- ).get("models")
- if ollama_models is None:
- return {
- "accepted": True,
- "persist": True,
- "recognized": False,
- "message": (
- f"Note: could not reach this Ollama endpoint's `/api/tags` model listing to validate `{requested}`. "
- "Hermes will save the model name, but local Ollama model discovery could not verify it."
- ),
- }
- if requested_for_lookup in set(ollama_models):
- return {
- "accepted": True,
- "persist": True,
- "recognized": True,
- "message": None,
- }
- suggestions = get_close_matches(requested_for_lookup, ollama_models, n=3, cutoff=0.5)
- suggestion_text = ""
- if suggestions:
- suggestion_text = "\n Similar local Ollama models: " + ", ".join(f"`{s}`" for s in suggestions)
- empty_hint = " No models are currently listed by `/api/tags`." if not ollama_models else ""
- return {
- "accepted": True,
- "persist": True,
- "recognized": False,
- "message": (
- f"Note: `{requested}` was not found in this Ollama endpoint's `/api/tags` model listing."
- f"{empty_hint} It may still work if the server supports hidden or aliased models."
- f"{suggestion_text}"
- ),
- }
-
- if normalized == "custom" or normalized.startswith("custom:"):
- # Try probing with correct auth for the api_mode.
- if api_mode == "anthropic_messages":
- probe = probe_api_models(
- api_key,
- base_url,
- api_mode=api_mode,
- request_headers=headers,
- )
- else:
- probe = probe_api_models(
- api_key,
- base_url,
- request_headers=headers,
- )
- api_models = probe.get("models")
- if api_models is not None:
- if requested_for_lookup in set(api_models):
- return {
- "accepted": True,
- "persist": True,
- "recognized": True,
- "message": None,
- }
-
- # Auto-correct if the top match is very similar (e.g. typo)
- auto = get_close_matches(requested_for_lookup, api_models, n=1, cutoff=0.9)
- if auto:
- return {
- "accepted": True,
- "persist": True,
- "recognized": True,
- "corrected_model": auto[0],
- "message": f"Auto-corrected `{requested}` → `{auto[0]}`",
- }
-
- suggestions = get_close_matches(requested, api_models, n=3, cutoff=0.5)
- suggestion_text = ""
- if suggestions:
- suggestion_text = "\n Similar models: " + ", ".join(f"`{s}`" for s in suggestions)
-
- message = (
- f"Note: `{requested}` was not found in this custom endpoint's model listing "
- f"({probe.get('probed_url')}). It may still work if the server supports hidden or aliased models."
- f"{suggestion_text}"
- )
- if probe.get("used_fallback"):
- message += (
- f"\n Endpoint verification succeeded after trying `{probe.get('resolved_base_url')}`. "
- f"Consider saving that as your base URL."
- )
-
- return {
- "accepted": True,
- "persist": True,
- "recognized": False,
- "message": message,
- }
-
- message = (
- f"Note: could not reach this custom endpoint's model listing at `{probe.get('probed_url')}`. "
- f"Hermes will still save `{requested}`, but the endpoint should expose `/models` for verification."
- )
- if api_mode == "anthropic_messages":
- message += (
- "\n Many Anthropic-compatible proxies do not implement the Models API "
- "(GET /v1/models). The model name has been accepted without verification."
- )
- if probe.get("suggested_base_url"):
- message += f"\n If this server expects `/v1`, try base URL: `{probe.get('suggested_base_url')}`"
-
- return {
- "accepted": api_mode == "anthropic_messages",
- "persist": True,
- "recognized": False,
- "message": message,
- }
-
- # Providers with non-standard catalog validation — /v1/models probing is not the right path.
- if normalized in {"openai-codex", "xai-oauth"}:
- try:
- catalog_models = provider_model_ids(normalized)
- except Exception:
- catalog_models = []
- # Ineligible ``-900k`` aliases (e.g. `gpt-5.5-900k`) must be rejected
- # BEFORE the hidden-slug soft-accept below: the suffix is a Hermes
- # picker convention, so an unknown `*-900k` name can never be a real
- # hidden provider slug — soft-accepting one silently runs at 272K on
- # a different model than the user thinks (#92797 review).
- if normalized == "openai-codex":
- from agent.model_metadata import (
- CODEX_CONTEXT_VARIANT_SUFFIX,
- is_codex_context_variant,
- )
- _req_lower = requested_for_lookup.strip().lower()
- if (
- _req_lower.endswith(CODEX_CONTEXT_VARIANT_SUFFIX)
- and requested_for_lookup not in set(catalog_models)
- ):
- if is_codex_context_variant(requested_for_lookup):
- # Valid variant that a stale catalog hasn't synthesized
- # yet. Accept it directly — falling through would let the
- # typo auto-corrector "fix" it to the base slug and
- # silently drop the large-context opt-in.
- return {
- "accepted": True,
- "persist": True,
- "recognized": True,
- "message": None,
- }
- _base_guess = requested_for_lookup[: -len(CODEX_CONTEXT_VARIANT_SUFFIX)]
- return {
- "accepted": False,
- "persist": False,
- "recognized": False,
- "message": (
- f"`{requested}` is not a valid large-context variant — "
- f"`{_base_guess}` enforces the standard 272K window on "
- f"Codex, so no `-900k` option exists for it. Pick the "
- f"base model, or a verified variant from the `/model` "
- f"picker (e.g. `gpt-5.6-sol-900k`)."
- ),
- }
- if catalog_models:
- if requested_for_lookup in set(catalog_models):
- return {
- "accepted": True,
- "persist": True,
- "recognized": True,
- "message": None,
- }
- # Auto-correct if the top match is very similar (e.g. typo)
- auto = get_close_matches(requested_for_lookup, catalog_models, n=1, cutoff=0.9)
- if auto:
- return {
- "accepted": True,
- "persist": True,
- "recognized": True,
- "corrected_model": auto[0],
- "message": f"Auto-corrected `{requested}` → `{auto[0]}`",
- }
- suggestions = get_close_matches(requested_for_lookup, catalog_models, n=3, cutoff=0.5)
- suggestion_text = ""
- if suggestions:
- suggestion_text = "\n Similar models: " + ", ".join(f"`{s}`" for s in suggestions)
- provider_label = "OpenAI Codex" if normalized == "openai-codex" else "xAI Grok OAuth (SuperGrok / Premium+)"
- # Plausibility gate (#45006): the soft-accept (#16172 / #19729) exists
- # for entitlement-gated *hidden* slugs the curated listing hasn't
- # caught up with — but those are always the provider's own family
- # (openai-codex -> gpt-*; xai-oauth -> grok-*). Accepting an
- # unrelated typed name (e.g. `qwen3.5-4b`, `llama-3.1-8b`) here turns
- # what should be an actionable "did you mean --provider <x>?" error
- # into a confusing success that 400s on the next turn. Only soft-
- # accept names that share the provider's family prefix; reject the
- # rest with guidance to pin the right provider.
- _family_prefixes = {
- "openai-codex": ("gpt-", "codex-", "o1", "o3", "o4"),
- "xai-oauth": ("grok-",),
- }.get(normalized, ())
- _lower = requested_for_lookup.strip().lower()
- _plausible = (not _family_prefixes) or any(
- _lower.startswith(p) for p in _family_prefixes
- )
- if not _plausible:
- return {
- "accepted": False,
- "persist": False,
- "recognized": False,
- "message": (
- f"`{requested}` doesn't look like a {provider_label} model "
- f"and isn't in its listing, so it was not accepted. If it "
- f"belongs to another configured provider, switch with "
- f"`--provider <slug>` (or select it from the `/model` "
- f"picker)."
- f"{suggestion_text}"
- ),
- }
- return {
- "accepted": True,
- "persist": True,
- "recognized": False,
- "message": (
- f"Note: `{requested}` was not found in the {provider_label} model listing. "
- "It may still work if your account has access to a newer or hidden model ID."
- f"{suggestion_text}"
- ),
- }
-
- # MiniMax providers don't expose a /models endpoint — validate against
- # the static catalog instead, similar to openai-codex.
- if normalized in {"minimax", "minimax-cn"}:
- try:
- catalog_models = provider_model_ids(normalized)
- except Exception:
- catalog_models = []
- if catalog_models:
- # Case-insensitive lookup (catalog uses mixed case like MiniMax-M2.7)
- catalog_lower = {m.lower(): m for m in catalog_models}
- if requested_for_lookup.lower() in catalog_lower:
- return {
- "accepted": True,
- "persist": True,
- "recognized": True,
- "message": None,
- }
- # Auto-correct close matches (case-insensitive)
- catalog_lower_list = list(catalog_lower.keys())
- auto = get_close_matches(requested_for_lookup.lower(), catalog_lower_list, n=1, cutoff=0.9)
- if auto:
- corrected = catalog_lower[auto[0]]
- return {
- "accepted": True,
- "persist": True,
- "recognized": True,
- "corrected_model": corrected,
- "message": f"Auto-corrected `{requested}` → `{corrected}`",
- }
- suggestions = get_close_matches(requested_for_lookup.lower(), catalog_lower_list, n=3, cutoff=0.5)
- suggestion_text = ""
- if suggestions:
- suggestion_text = "\n Similar models: " + ", ".join(f"`{catalog_lower[s]}`" for s in suggestions)
- return {
- "accepted": True,
- "persist": True,
- "recognized": False,
- "message": (
- f"Note: `{requested}` was not found in the MiniMax catalog."
- f"{suggestion_text}"
- "\n MiniMax does not expose a /models endpoint, so Hermes cannot verify the model name."
- "\n The model may still work if it exists on the server."
- ),
- }
-
- # Native Anthropic provider: /v1/models requires x-api-key (or Bearer for
- # OAuth) plus anthropic-version headers. The generic OpenAI-style probe
- # below uses plain Bearer auth and 401s against Anthropic, so dispatch to
- # the native fetcher which handles both API keys and Claude-Code OAuth
- # tokens. (The api_mode=="anthropic_messages" branch below handles the
- # Messages-API transport case separately.)
- if normalized == "anthropic":
- anthropic_models = _fetch_anthropic_models(
- base_url=base_url or None,
- api_key=api_key or None,
- )
- if anthropic_models is not None:
- if requested_for_lookup in set(anthropic_models):
- return {
- "accepted": True,
- "persist": True,
- "recognized": True,
- "message": None,
- }
- auto = get_close_matches(requested_for_lookup, anthropic_models, n=1, cutoff=0.9)
- if auto:
- return {
- "accepted": True,
- "persist": True,
- "recognized": True,
- "corrected_model": auto[0],
- "message": f"Auto-corrected `{requested}` → `{auto[0]}`",
- }
- suggestions = get_close_matches(requested, anthropic_models, n=3, cutoff=0.5)
- suggestion_text = ""
- if suggestions:
- suggestion_text = "\n Similar models: " + ", ".join(f"`{s}`" for s in suggestions)
- # Accept anyway — Anthropic sometimes gates newer/preview models
- # (e.g. snapshot IDs, early-access releases) behind accounts
- # even though they aren't listed on /v1/models.
- return {
- "accepted": True,
- "persist": True,
- "recognized": False,
- "message": (
- f"Note: `{requested}` was not found in Anthropic's /v1/models listing. "
- f"It may still work if you have early-access or snapshot IDs."
- f"{suggestion_text}"
- ),
- }
- # _fetch_anthropic_models returned None — no token resolvable or
- # network failure. Fall through to the generic warning below.
-
- # Anthropic Messages API: many proxies don't implement /v1/models.
- # Try probing with correct auth; if it fails, accept with a warning.
- if api_mode == "anthropic_messages":
- api_models = fetch_api_models(api_key, base_url, api_mode=api_mode)
- if api_models is not None:
- if requested_for_lookup in set(api_models):
- return {
- "accepted": True,
- "persist": True,
- "recognized": True,
- "message": None,
- }
- auto = get_close_matches(requested_for_lookup, api_models, n=1, cutoff=0.9)
- if auto:
- return {
- "accepted": True,
- "persist": True,
- "recognized": True,
- "corrected_model": auto[0],
- "message": f"Auto-corrected `{requested}` → `{auto[0]}`",
- }
- # Probe failed or model not found — accept anyway (proxy likely
- # doesn't implement the Anthropic Models API).
- return {
- "accepted": True,
- "persist": True,
- "recognized": False,
- "message": (
- f"Note: could not verify `{requested}` against this endpoint's "
- f"model listing. Many Anthropic-compatible proxies do not "
- f"implement GET /v1/models. The model name has been accepted "
- f"without verification."
- ),
- }
-
- # Probe the live API to check if the model actually exists
- api_models = fetch_api_models(api_key, base_url)
-
- if api_models is not None:
- # Gemini's OpenAI-compat /v1beta/openai/models endpoint returns IDs
- # prefixed with "models/" (e.g. "models/gemini-2.5-flash") — native
- # Gemini-API convention. Our curated list and user input both use
- # the bare ID, so a direct set-membership check drops every known
- # Gemini model. Strip the prefix before comparison. See #12532.
- if normalized == "gemini":
- api_models = [
- m[len("models/"):] if isinstance(m, str) and m.startswith("models/") else m
- for m in api_models
- ]
- if requested_for_lookup in set(api_models):
- # API confirmed the model exists
- return {
- "accepted": True,
- "persist": True,
- "recognized": True,
- "message": None,
- }
- # OpenRouter routing variants (":nitro", ":floor", ...) are request-time
- # modifiers, not catalog entries — /models lists only the base id.
- # Validate the BASE against the listing but preserve the suffixed id,
- # and do this BEFORE fuzzy auto-correction: get_close_matches would
- # otherwise "correct" `model:nitro` → `model` and silently strip the
- # user's routing opt-in.
- _variant_base = (
- _openrouter_variant_base(requested_for_lookup)
- if normalized == "openrouter"
- else None
- )
- if _variant_base is not None and _variant_base in set(api_models):
- return {
- "accepted": True,
- "persist": True,
- "recognized": True,
- "message": None,
- }
- else:
- # API responded but model is not listed. Accept anyway —
- # the user may have access to models not shown in the public
- # listing (e.g. Z.AI Pro/Max plans can use glm-5 on coding
- # endpoints even though it's not in /models). Warn but allow.
-
- # Auto-correct if the top match is very similar (e.g. typo)
- auto = get_close_matches(requested_for_lookup, api_models, n=1, cutoff=0.9)
- if auto:
- corrected = _with_preset_suffix(auto[0])
- return {
- "accepted": True,
- "persist": True,
- "recognized": True,
- "corrected_model": corrected,
- "message": f"Auto-corrected `{requested}` → `{corrected}`",
- }
-
- suggestions = get_close_matches(
- requested_for_lookup, api_models, n=3, cutoff=0.5
- )
- suggestion_text = ""
- if suggestions:
- suggestion_text = "\n Similar models: " + ", ".join(f"`{s}`" for s in suggestions)
-
- # Model not in live /v1/models — check the curated catalog
- # before rejecting. Providers may omit models from their live
- # listing that are still valid (stale cache, partial rollout,
- # gated previews). Use the pure-catalog helper (no extra live
- # fetch) so we only accept models Hermes actually ships. (#46850)
- #
- # EXCEPTION: official OpenAI hosts (canonical api.openai.com and
- # the data-residency regional hosts). Their /v1/models listing is
- # access-scoped and authoritative — a model absent from it is one
- # this key CANNOT serve, so the curated soft-accept would
- # manufacture a selection that 400s at first use. Custom
- # OpenAI-compatible proxies keep the fallback (incomplete
- # listings are common there).
- _openai_listing_is_authoritative = False
- if normalized in ("openai", "openai-api"):
- from hermes_cli.providers import is_official_openai_host
-
- _openai_listing_is_authoritative = is_official_openai_host(base_url)
- if not _openai_listing_is_authoritative and _model_in_provider_catalog(
- (_variant_base or requested_for_lookup).lower(),
- _provider_keys(normalized),
- ):
- return {
- "accepted": True,
- "persist": True,
- "recognized": True,
- "message": (
- f"Note: `{requested}` was not found in the live /v1/models listing "
- f"but exists in the curated catalog — accepted."
- ),
- }
-
- # Nous provider: also check the Portal's live
- # /api/nous/recommended-models feed. That feed can list a model
- # (e.g. a newly-promoted free/paid recommendation) before it's
- # been added to the hardcoded _PROVIDER_MODELS["nous"] curated
- # list or the docs-hosted catalog manifest has been rebuilt.
- # `hermes chat` already accepts these models via
- # union_with_portal_free/paid_recommendations() at model-list
- # build time; this mirrors that same source of truth for the
- # per-message /model validation path (messaging platform
- # pickers, /model command), which previously only checked the
- # curated catalog and rejected valid Portal-recommended models.
- if normalized == "nous":
- try:
- portal_payload = fetch_nous_recommended_models(
- _resolve_nous_portal_url()
- )
- portal_model_names = {
- name.lower()
- for tier in ("freeRecommendedModels", "paidRecommendedModels")
- for entry in (portal_payload.get(tier) or [])
- if (name := _extract_model_name(entry))
- }
- except Exception:
- portal_model_names = set()
- if requested_for_lookup.lower() in portal_model_names:
- return {
- "accepted": True,
- "persist": True,
- "recognized": True,
- "message": (
- f"Note: `{requested}` was not found in the live /v1/models "
- f"listing but is a current Nous Portal recommendation — accepted."
- ),
- }
-
- return {
- "accepted": False,
- "persist": False,
- "recognized": False,
- "message": (
- f"Model `{requested}` was not found in this provider's model listing."
- f"{suggestion_text}"
- ),
- }
-
- # api_models is None — couldn't reach API. Accept and persist,
- # but warn so typos don't silently break things.
-
- # Bedrock: use our own discovery instead of HTTP /models endpoint.
- # Bedrock's bedrock-runtime URL doesn't support /models — it uses the
- # AWS SDK control plane (ListFoundationModels + ListInferenceProfiles).
- if normalized == "bedrock":
- try:
- from agent.bedrock_adapter import discover_bedrock_models, resolve_bedrock_runtime_region
- region = resolve_bedrock_runtime_region()
- discovered = discover_bedrock_models(region)
- discovered_ids = {m["id"] for m in discovered}
- if requested in discovered_ids:
- return {
- "accepted": True,
- "persist": True,
- "recognized": True,
- "message": None,
- }
- # Not in discovered list — still accept (user may have custom
- # inference profiles or cross-account access), but warn.
- suggestions = get_close_matches(requested, list(discovered_ids), n=3, cutoff=0.4)
- suggestion_text = ""
- if suggestions:
- suggestion_text = "\n Similar models: " + ", ".join(f"`{s}`" for s in suggestions)
- return {
- "accepted": True,
- "persist": True,
- "recognized": False,
- "message": (
- f"Note: `{requested}` was not found in Bedrock model discovery for {region}. "
- f"It may still work with custom inference profiles or cross-account access."
- f"{suggestion_text}"
- ),
- }
- except Exception:
- pass # Fall through to generic warning
-
- # Static-catalog fallback: when the /models probe was unreachable,
- # validate against the curated list from provider_model_ids() — same
- # pattern as the openai-codex and minimax branches above. This keeps
- # /model switches working in the gateway for providers whose /models
- # endpoint is temporarily unreachable or returns a non-JSON payload.
- # Without this block, validate_requested_model would reject every model
- # on such providers, switch_model() would return success=False, and
- # the gateway would never write to _session_model_overrides.
- provider_label = _PROVIDER_LABELS.get(normalized, normalized)
- try:
- catalog_models = provider_model_ids(normalized)
- except Exception:
- catalog_models = []
-
- if catalog_models:
- catalog_lower = {m.lower(): m for m in catalog_models}
- if requested_for_lookup.lower() in catalog_lower:
- return {
- "accepted": True,
- "persist": True,
- "recognized": True,
- "message": None,
- }
- # OpenRouter routing-variant suffixes: validate the base id against
- # the catalog, keep the suffixed id (same rule as the live-listing
- # path above — variants never appear as catalog entries).
- if normalized == "openrouter":
- _cat_variant_base = _openrouter_variant_base(requested_for_lookup)
- if (
- _cat_variant_base is not None
- and _cat_variant_base.lower() in catalog_lower
- ):
- return {
- "accepted": True,
- "persist": True,
- "recognized": True,
- "message": None,
- }
- catalog_lower_list = list(catalog_lower.keys())
- auto = get_close_matches(
- requested_for_lookup.lower(), catalog_lower_list, n=1, cutoff=0.9
- )
- if auto:
- corrected = catalog_lower[auto[0]]
- corrected_with_suffix = _with_preset_suffix(corrected)
- return {
- "accepted": True,
- "persist": True,
- "recognized": True,
- "corrected_model": corrected_with_suffix,
- "message": (
- f"Auto-corrected `{requested}` → `{corrected_with_suffix}`"
- ),
- }
- suggestions = get_close_matches(
- requested_for_lookup.lower(), catalog_lower_list, n=3, cutoff=0.5
- )
- suggestion_text = ""
- if suggestions:
- suggestion_text = "\n Similar models: " + ", ".join(
- f"`{catalog_lower[s]}`" for s in suggestions
- )
- return {
- "accepted": True,
- "persist": True,
- "recognized": False,
- "message": (
- f"Note: `{requested}` was not found in the {provider_label} curated catalog "
- f"and the /models endpoint was unreachable.{suggestion_text}"
- f"\n The model may still work if it exists on the provider."
- ),
- }
-
- # No catalog available — accept with a warning, matching the comment's
- # stated intent ("Accept and persist, but warn").
- return {
- "accepted": True,
- "persist": True,
- "recognized": False,
- "message": (
- f"Note: could not reach the {provider_label} API to validate `{requested}`. "
- f"If the service isn't down, this model may not be valid."
- ),
- }
diff --git a/hermes_cli/models_validate.py b/hermes_cli/models_validate.py
new file mode 100644
index 00000000000..dc80f1323d5
--- /dev/null
+++ b/hermes_cli/models_validate.py
@@ -0,0 +1,629 @@
+"""Validate a requested ``/model`` value against the active provider's catalog.
+
+Split out of ``hermes_cli.models``; :func:`validate_requested_model` is re-imported there, so
+``hermes_cli.models.validate_requested_model`` keeps resolving. Every catalog fetcher this module
+calls is looked up on ``hermes_cli.models`` at call time (``_m.<name>``), so existing
+``patch("hermes_cli.models.<name>")`` mocks keep intercepting.
+
+Every provider branch returns one of four verdict shapes (see :func:`_verdict`) or ``None`` to
+mean "not decided here — keep walking the ladder". The ladder ORDER is behavior: moa → whitespace
+→ OpenRouter preset parse → LM Studio → Ollama native → custom → codex/xai static → MiniMax →
+Anthropic native → Anthropic Messages → live listing → Bedrock → curated-catalog fallback.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from difflib import get_close_matches
+from typing import Any, Optional
+
+from utils import base_url_host_matches
+
+
+# ── Verdicts ─────────────────────────────────────────────────────────────
+
+def _verdict(accepted: bool, persist: bool, recognized: bool, message: Optional[str],
+ corrected_model: Optional[str] = None) -> dict[str, Any]:
+ """Build the verdict dict. ``corrected_model`` is only present when set (key order matters
+ to nobody, but keep it identical to the historical literals anyway)."""
+ out: dict[str, Any] = {"accepted": accepted, "persist": persist, "recognized": recognized}
+ if corrected_model is not None:
+ out["corrected_model"] = corrected_model
+ out["message"] = message
+ return out
+
+
+def _accept() -> dict[str, Any]:
+ return _verdict(True, True, True, None)
+
+
+def _reject(message: str) -> dict[str, Any]:
+ return _verdict(False, False, False, message)
+
+
+def _soft_accept(message: Optional[str]) -> dict[str, Any]:
+ """Accept + persist an unrecognized name, with a warning."""
+ return _verdict(True, True, False, message)
+
+
+def _corrected(requested: str, corrected: str) -> dict[str, Any]:
+ return _verdict(True, True, True, f"Auto-corrected `{requested}` → `{corrected}`",
+ corrected_model=corrected)
+
+
+# ── Catalog matching ─────────────────────────────────────────────────────
+
+@dataclass
+class _Match:
+ exact: bool = False
+ corrected: Optional[str] = None
+ suggestion_text: str = ""
+
+
+def _match_in_catalog(
+ query: str,
+ candidates,
+ *,
+ case_insensitive: bool = False,
+ auto_correct: bool = True,
+ suggest_query: Optional[str] = None,
+ suggest_cutoff: float = 0.5,
+ suggest_label: str = "Similar models",
+) -> _Match:
+ """The shared ladder: exact membership → typo auto-correct (cutoff .9) → suggestion text.
+
+ ``case_insensitive`` matches on lower-cased ids and maps results back to the catalog's
+ spelling (MiniMax ships mixed-case ids). ``suggest_query`` overrides the string the
+ suggestion search uses (some branches search on the raw request, not the lookup form).
+ """
+ candidates = list(candidates)
+ if case_insensitive:
+ display = {c.lower(): c for c in candidates}
+ pool = list(display)
+ query = query.lower()
+ suggest_query = query if suggest_query is None else suggest_query.lower()
+ else:
+ display = None
+ pool = candidates
+ suggest_query = query if suggest_query is None else suggest_query
+
+ def _show(cid: str) -> str:
+ return display[cid] if display is not None else cid
+
+ if query in set(pool):
+ return _Match(exact=True)
+ if auto_correct:
+ auto = get_close_matches(query, pool, n=1, cutoff=0.9)
+ if auto:
+ return _Match(corrected=_show(auto[0]))
+ suggestions = get_close_matches(suggest_query, pool, n=3, cutoff=suggest_cutoff)
+ text = ""
+ if suggestions:
+ text = f"\n {suggest_label}: " + ", ".join(f"`{_show(s)}`" for s in suggestions)
+ return _Match(suggestion_text=text)
+
+
+# ── Request context ──────────────────────────────────────────────────────
+
+@dataclass
+class _Request:
+ requested: str
+ lookup: str # id used for catalog membership (copilot-normalized / preset base)
+ provider: Optional[str] # raw caller value (Ollama checks look at this, not ``normalized``)
+ normalized: str
+ api_key: Optional[str]
+ base_url: Optional[str]
+ api_mode: Optional[str]
+ headers: Optional[dict[str, str]]
+ preset_suffix: str = ""
+
+ def with_preset_suffix(self, model_id: str) -> str:
+ """Re-attach a preserved ``@preset/<slug>`` suffix after auto-correction."""
+ return f"{model_id}{self.preset_suffix}"
+
+
+# ── Provider branches (None = not decided here) ─────────────────────────
+
+def _validate_moa(requested: str) -> dict[str, Any]:
+ try:
+ from hermes_cli.config import load_config
+ from hermes_cli.moa_config import normalize_moa_config
+
+ cfg = normalize_moa_config(load_config().get("moa") or {})
+ if requested in cfg["presets"]:
+ return _accept()
+ return _reject(f"MoA preset `{requested}` was not found. Run `hermes moa list`.")
+ except Exception as exc:
+ return _reject(f"Could not read MoA presets: {exc}")
+
+
+def _parse_openrouter_preset(req: _Request) -> Optional[dict[str, Any]]:
+ """OpenRouter presets are account-scoped, so ``@preset/<slug>`` never appears in the public
+ /v1/models listing. A bare preset is accepted unverified; ``<model>@preset/<slug>`` validates
+ the base model and preserves the suffix through auto-correction. OpenRouter validates the slug
+ at request time."""
+ marker = "@preset/"
+ if marker not in req.requested:
+ return None
+ if req.requested.count(marker) != 1:
+ preset_slug, preset_base = "", req.requested
+ else:
+ preset_base, preset_slug = req.requested.split(marker, 1)
+ if re.fullmatch(r"[A-Za-z0-9._~-]+", preset_slug) is None:
+ return _reject(
+ "OpenRouter preset slugs must be non-empty URL-safe "
+ "identifiers using only letters, digits, '.', '_', "
+ "'~', or '-'."
+ )
+ req.preset_suffix = f"{marker}{preset_slug}"
+ if not preset_base:
+ return _soft_accept(None)
+ req.lookup = preset_base
+ return None
+
+
+def _validate_lmstudio(req: _Request) -> dict[str, Any]:
+ from hermes_cli import models as _m
+ from hermes_cli.auth import AuthError
+
+ # probe_lmstudio_models distinguishes None (unreachable / malformed) from [] (reachable,
+ # nothing chat-capable loaded); fetch_lmstudio_models collapses both to [].
+ try:
+ models = _m.probe_lmstudio_models(api_key=req.api_key, base_url=req.base_url)
+ except AuthError as exc:
+ return _reject(f"{exc} Set `LM_API_KEY` (or update it) to match the server's bearer token.")
+ if models is None:
+ return _reject(f"Could not reach LM Studio's `/api/v1/models` to validate `{req.requested}`.")
+ if not models:
+ return _reject(
+ f"LM Studio is reachable but no chat-capable models are loaded. "
+ f"Load `{req.requested}` in LM Studio (Developer tab → Load Model) and try again."
+ )
+ if req.lookup in set(models):
+ return _accept()
+ return _reject(f"Model `{req.requested}` was not found in LM Studio's model listing.")
+
+
+def _ollama_probe_headers(req: _Request) -> dict[str, str]:
+ """Headers for the Ollama native probe.
+
+ Configured ``providers.ollama.extra_headers`` are only applied when the probed endpoint is
+ the configured one (never leak them to a different host). Caller headers win; a caller
+ ``api_key`` becomes the Authorization header unless the caller already sent one.
+ """
+ from hermes_cli import models as _m
+
+ cfg = _m._get_provider_config_dict("ollama")
+ configured_base = str(cfg.get("base_url") or cfg.get("api") or cfg.get("url") or "").strip()
+ configured_allowed = not (
+ configured_base and not _m._same_ollama_native_root(req.base_url or "", configured_base)
+ )
+ if req.headers is None:
+ return _m._get_ollama_native_headers(req.base_url, api_key=req.api_key) if configured_allowed else {}
+ out: dict[str, str] = {}
+ if configured_allowed:
+ out.update(_m._get_ollama_native_headers(req.base_url, api_key=req.api_key))
+ for key in tuple(out):
+ if key.lower() == "authorization":
+ del out[key]
+ out.update(req.headers)
+ caller_has_authorization = any(key.lower() == "authorization" for key in req.headers)
+ if req.api_key and not caller_has_authorization:
+ for key in tuple(out):
+ if key.lower() == "authorization":
+ del out[key]
+ out["Authorization"] = f"Bearer {req.api_key}"
+ return out
+
+
+def _validate_ollama_native(req: _Request) -> Optional[dict[str, Any]]:
+ """Runs for EVERY provider: the native ``/api/tags`` catalog is used whenever the endpoint
+ looks like a local Ollama server. Also resolves ``base_url`` for the raw ``ollama`` provider,
+ which later branches (custom) rely on."""
+ from hermes_cli import models as _m
+
+ if str(req.provider or "").strip().lower() == "ollama" and not req.base_url:
+ req.base_url = _m._get_ollama_base_url()
+ headers = _ollama_probe_headers(req)
+ if not _m.should_use_ollama_native_catalog(req.provider, req.base_url, headers=headers):
+ return None
+ models = _m.probe_ollama_local_models(req.base_url, headers=headers)
+ if models is None:
+ # A failed native probe is not authoritative; fall back to the OpenAI-compatible
+ # catalog before accepting blindly.
+ models = _m.probe_api_models(
+ req.api_key,
+ _m._normalize_openai_base_url(req.base_url),
+ request_headers=headers,
+ ).get("models")
+ if models is None:
+ return _soft_accept(
+ f"Note: could not reach this Ollama endpoint's `/api/tags` model listing to validate `{req.requested}`. "
+ "Hermes will save the model name, but local Ollama model discovery could not verify it."
+ )
+ match = _match_in_catalog(req.lookup, models, auto_correct=False,
+ suggest_label="Similar local Ollama models")
+ if match.exact:
+ return _accept()
+ empty_hint = " No models are currently listed by `/api/tags`." if not models else ""
+ return _soft_accept(
+ f"Note: `{req.requested}` was not found in this Ollama endpoint's `/api/tags` model listing."
+ f"{empty_hint} It may still work if the server supports hidden or aliased models."
+ f"{match.suggestion_text}"
+ )
+
+
+def _validate_custom(req: _Request) -> dict[str, Any]:
+ from hermes_cli import models as _m
+
+ # Probe with the auth shape the api_mode expects.
+ if req.api_mode == "anthropic_messages":
+ probe = _m.probe_api_models(req.api_key, req.base_url, api_mode=req.api_mode,
+ request_headers=req.headers)
+ else:
+ probe = _m.probe_api_models(req.api_key, req.base_url, request_headers=req.headers)
+ api_models = probe.get("models")
+ if api_models is not None:
+ match = _match_in_catalog(req.lookup, api_models, suggest_query=req.requested)
+ if match.exact:
+ return _accept()
+ if match.corrected:
+ return _corrected(req.requested, match.corrected)
+ message = (
+ f"Note: `{req.requested}` was not found in this custom endpoint's model listing "
+ f"({probe.get('probed_url')}). It may still work if the server supports hidden or aliased models."
+ f"{match.suggestion_text}"
+ )
+ if probe.get("used_fallback"):
+ message += (
+ f"\n Endpoint verification succeeded after trying `{probe.get('resolved_base_url')}`. "
+ f"Consider saving that as your base URL."
+ )
+ return _soft_accept(message)
+
+ message = (
+ f"Note: could not reach this custom endpoint's model listing at `{probe.get('probed_url')}`. "
+ f"Hermes will still save `{req.requested}`, but the endpoint should expose `/models` for verification."
+ )
+ if req.api_mode == "anthropic_messages":
+ message += (
+ "\n Many Anthropic-compatible proxies do not implement the Models API "
+ "(GET /v1/models). The model name has been accepted without verification."
+ )
+ if probe.get("suggested_base_url"):
+ message += f"\n If this server expects `/v1`, try base URL: `{probe.get('suggested_base_url')}`"
+ # Anthropic-style proxies routinely lack /v1/models, so only they are accepted unverified.
+ return _verdict(req.api_mode == "anthropic_messages", True, False, message)
+
+
+def _static_catalog(normalized: str) -> list[str]:
+ from hermes_cli import models as _m
+
+ try:
+ return _m.provider_model_ids(normalized)
+ except Exception:
+ return []
+
+
+_STATIC_FAMILY_PREFIXES = {
+ "openai-codex": ("gpt-", "codex-", "o1", "o3", "o4"),
+ "xai-oauth": ("grok-",),
+}
+_STATIC_LABELS = {"openai-codex": "OpenAI Codex", "xai-oauth": "xAI Grok OAuth (SuperGrok / Premium+)"}
+
+
+def _validate_static_catalog(req: _Request) -> Optional[dict[str, Any]]:
+ """openai-codex / xai-oauth: no /v1/models probing — validate against the curated catalog.
+ Returns None (fall through) when the catalog is empty."""
+ catalog = _static_catalog(req.normalized)
+ if req.normalized == "openai-codex":
+ from agent.model_metadata import CODEX_CONTEXT_VARIANT_SUFFIX, is_codex_context_variant
+
+ # Ineligible ``-900k`` aliases must be rejected BEFORE the hidden-slug soft-accept:
+ # the suffix is a Hermes picker convention, so an unknown `*-900k` can never be a real
+ # hidden provider slug — soft-accepting one silently runs at 272K on a different model.
+ if req.lookup.strip().lower().endswith(CODEX_CONTEXT_VARIANT_SUFFIX) and req.lookup not in set(catalog):
+ if is_codex_context_variant(req.lookup):
+ # Valid variant a stale catalog hasn't synthesized yet. Accept directly — the typo
+ # auto-corrector would otherwise "fix" it to the base slug and drop the opt-in.
+ return _accept()
+ base_guess = req.lookup[: -len(CODEX_CONTEXT_VARIANT_SUFFIX)]
+ return _reject(
+ f"`{req.requested}` is not a valid large-context variant — "
+ f"`{base_guess}` enforces the standard 272K window on "
+ f"Codex, so no `-900k` option exists for it. Pick the "
+ f"base model, or a verified variant from the `/model` "
+ f"picker (e.g. `gpt-5.6-sol-900k`)."
+ )
+ if not catalog:
+ return None
+ match = _match_in_catalog(req.lookup, catalog)
+ if match.exact:
+ return _accept()
+ if match.corrected:
+ return _corrected(req.requested, match.corrected)
+ label = _STATIC_LABELS[req.normalized]
+ # Plausibility gate: the soft-accept exists for entitlement-gated *hidden* slugs the curated
+ # listing hasn't caught up with — always the provider's own family (gpt-* / grok-*). An
+ # unrelated name (`qwen3.5-4b`) would turn an actionable "did you mean --provider <x>?" into
+ # a confusing success that 400s on the next turn, so reject it with guidance instead.
+ prefixes = _STATIC_FAMILY_PREFIXES.get(req.normalized, ())
+ lower = req.lookup.strip().lower()
+ if prefixes and not any(lower.startswith(p) for p in prefixes):
+ return _reject(
+ f"`{req.requested}` doesn't look like a {label} model "
+ f"and isn't in its listing, so it was not accepted. If it "
+ f"belongs to another configured provider, switch with "
+ f"`--provider <slug>` (or select it from the `/model` "
+ f"picker)."
+ f"{match.suggestion_text}"
+ )
+ return _soft_accept(
+ f"Note: `{req.requested}` was not found in the {label} model listing. "
+ "It may still work if your account has access to a newer or hidden model ID."
+ f"{match.suggestion_text}"
+ )
+
+
+def _validate_minimax(req: _Request) -> Optional[dict[str, Any]]:
+ """MiniMax has no /models endpoint — static catalog, case-insensitive (ids like MiniMax-M2.7).
+ Returns None when the catalog is empty."""
+ catalog = _static_catalog(req.normalized)
+ if not catalog:
+ return None
+ match = _match_in_catalog(req.lookup, catalog, case_insensitive=True)
+ if match.exact:
+ return _accept()
+ if match.corrected:
+ return _corrected(req.requested, match.corrected)
+ return _soft_accept(
+ f"Note: `{req.requested}` was not found in the MiniMax catalog."
+ f"{match.suggestion_text}"
+ "\n MiniMax does not expose a /models endpoint, so Hermes cannot verify the model name."
+ "\n The model may still work if it exists on the server."
+ )
+
+
+def _validate_anthropic(req: _Request) -> Optional[dict[str, Any]]:
+ """Native Anthropic: /v1/models needs x-api-key (or OAuth Bearer) + anthropic-version, so the
+ generic Bearer probe 401s — use the native fetcher. Returns None (fall through to the generic
+ ladder) when no token is resolvable or the network failed."""
+ from hermes_cli import models as _m
+
+ models = _m._fetch_anthropic_models(base_url=req.base_url or None, api_key=req.api_key or None)
+ if models is None:
+ return None
+ match = _match_in_catalog(req.lookup, models, suggest_query=req.requested)
+ if match.exact:
+ return _accept()
+ if match.corrected:
+ return _corrected(req.requested, match.corrected)
+ # Accept anyway — Anthropic gates newer/preview models (snapshot IDs, early access) behind
+ # accounts even though they aren't listed on /v1/models.
+ return _soft_accept(
+ f"Note: `{req.requested}` was not found in Anthropic's /v1/models listing. "
+ f"It may still work if you have early-access or snapshot IDs."
+ f"{match.suggestion_text}"
+ )
+
+
+def _validate_anthropic_messages(req: _Request) -> dict[str, Any]:
+ """Anthropic Messages transport: many proxies don't implement /v1/models — probe, and accept
+ with a warning when the probe fails or the model isn't listed."""
+ from hermes_cli import models as _m
+
+ models = _m.fetch_api_models(req.api_key, req.base_url, api_mode=req.api_mode)
+ if models is not None:
+ match = _match_in_catalog(req.lookup, models)
+ if match.exact:
+ return _accept()
+ if match.corrected:
+ return _corrected(req.requested, match.corrected)
+ return _soft_accept(
+ f"Note: could not verify `{req.requested}` against this endpoint's "
+ f"model listing. Many Anthropic-compatible proxies do not "
+ f"implement GET /v1/models. The model name has been accepted "
+ f"without verification."
+ )
+
+
+def _nous_portal_recommended_names() -> set[str]:
+ """Lower-cased ids from the Portal's live recommended-models feed (empty on any failure)."""
+ from hermes_cli import models as _m
+
+ try:
+ payload = _m.fetch_nous_recommended_models(_m._resolve_nous_portal_url())
+ return {
+ name.lower()
+ for tier in ("freeRecommendedModels", "paidRecommendedModels")
+ for entry in (payload.get(tier) or [])
+ if (name := _m._extract_model_name(entry))
+ }
+ except Exception:
+ return set()
+
+
+def _validate_live_listing(req: _Request) -> Optional[dict[str, Any]]:
+ """Generic live /v1/models probe. Returns None when the API was unreachable (the caller then
+ tries Bedrock discovery / the curated catalog)."""
+ from hermes_cli import models as _m
+
+ api_models = _m.fetch_api_models(req.api_key, req.base_url)
+ if api_models is None:
+ return None
+ if req.normalized == "gemini":
+ # Gemini's OpenAI-compat listing prefixes ids with "models/"; curated list and user
+ # input use the bare id, so strip before comparing.
+ api_models = [
+ m[len("models/"):] if isinstance(m, str) and m.startswith("models/") else m
+ for m in api_models
+ ]
+ match = _match_in_catalog(req.lookup, api_models)
+ if match.exact:
+ return _accept()
+ # OpenRouter routing variants (":nitro", ":floor", ...) are request-time modifiers, not
+ # catalog entries — validate the BASE but keep the suffixed id. Must run BEFORE fuzzy
+ # auto-correction, which would otherwise "correct" `model:nitro` → `model` and silently
+ # strip the routing opt-in.
+ variant_base = _m._openrouter_variant_base(req.lookup) if req.normalized == "openrouter" else None
+ if variant_base is not None and variant_base in set(api_models):
+ return _accept()
+ # Listed but not found: the account may reach models absent from the public listing
+ # (e.g. Z.AI Pro/Max plans use glm-5 on coding endpoints) — warn but allow where plausible.
+ if match.corrected:
+ corrected = req.with_preset_suffix(match.corrected)
+ return _corrected(req.requested, corrected)
+ # Curated-catalog soft-accept: providers omit valid models from live listings (stale cache,
+ # partial rollout, gated previews). EXCEPTION: official OpenAI hosts (canonical + data-
+ # residency regional) — their listing is access-scoped and authoritative, so an absent model
+ # is one this key CANNOT serve; a soft-accept would 400 at first use. Custom OpenAI-compatible
+ # proxies keep the fallback.
+ listing_authoritative = False
+ if req.normalized in ("openai", "openai-api"):
+ from hermes_cli.providers import is_official_openai_host
+
+ listing_authoritative = is_official_openai_host(req.base_url)
+ if not listing_authoritative and _m._model_in_provider_catalog(
+ (variant_base or req.lookup).lower(), _m._provider_keys(req.normalized)
+ ):
+ return _verdict(True, True, True,
+ f"Note: `{req.requested}` was not found in the live /v1/models listing "
+ f"but exists in the curated catalog — accepted.")
+ # Nous: the Portal's recommended-models feed can list a model before the curated list or the
+ # docs-hosted manifest catches up; `hermes chat` already accepts those at model-list build
+ # time, so mirror that source of truth for per-message /model validation.
+ if req.normalized == "nous" and req.lookup.lower() in _nous_portal_recommended_names():
+ return _verdict(True, True, True,
+ f"Note: `{req.requested}` was not found in the live /v1/models "
+ f"listing but is a current Nous Portal recommendation — accepted.")
+ return _reject(
+ f"Model `{req.requested}` was not found in this provider's model listing."
+ f"{match.suggestion_text}"
+ )
+
+
+def _validate_bedrock(req: _Request) -> Optional[dict[str, Any]]:
+ """Bedrock's runtime URL has no /models; discovery goes through the AWS control plane
+ (ListFoundationModels + ListInferenceProfiles). Any failure falls through (None)."""
+ try:
+ from agent.bedrock_adapter import discover_bedrock_models, resolve_bedrock_runtime_region
+
+ region = resolve_bedrock_runtime_region()
+ discovered_ids = {m["id"] for m in discover_bedrock_models(region)}
+ match = _match_in_catalog(req.requested, list(discovered_ids), auto_correct=False,
+ suggest_cutoff=0.4)
+ if match.exact:
+ return _accept()
+ # Still accept (custom inference profiles / cross-account access), but warn.
+ return _soft_accept(
+ f"Note: `{req.requested}` was not found in Bedrock model discovery for {region}. "
+ f"It may still work with custom inference profiles or cross-account access."
+ f"{match.suggestion_text}"
+ )
+ except Exception:
+ return None
+
+
+def _validate_catalog_fallback(req: _Request) -> dict[str, Any]:
+ """The /models probe was unreachable: validate against the curated ``provider_model_ids()``
+ list so gateway /model switches keep working while a provider's endpoint is down (otherwise
+ switch_model() would fail and the gateway never writes the session override). No catalog at
+ all → accept with a warning."""
+ from hermes_cli import models as _m
+
+ label = _m._PROVIDER_LABELS.get(req.normalized, req.normalized)
+ catalog = _static_catalog(req.normalized)
+ if not catalog:
+ return _soft_accept(
+ f"Note: could not reach the {label} API to validate `{req.requested}`. "
+ f"If the service isn't down, this model may not be valid."
+ )
+ match = _match_in_catalog(req.lookup, catalog, case_insensitive=True)
+ if match.exact:
+ return _accept()
+ # Same OpenRouter routing-variant rule as the live-listing path.
+ if req.normalized == "openrouter":
+ variant_base = _m._openrouter_variant_base(req.lookup)
+ if variant_base is not None and variant_base.lower() in {m.lower() for m in catalog}:
+ return _accept()
+ if match.corrected:
+ corrected = req.with_preset_suffix(match.corrected)
+ return _corrected(req.requested, corrected)
+ return _soft_accept(
+ f"Note: `{req.requested}` was not found in the {label} curated catalog "
+ f"and the /models endpoint was unreachable.{match.suggestion_text}"
+ f"\n The model may still work if it exists on the provider."
+ )
+
+
+# ── Orchestrator ─────────────────────────────────────────────────────────
+
+def validate_requested_model(
+ model_name: str,
+ provider: Optional[str],
+ *,
+ api_key: Optional[str] = None,
+ base_url: Optional[str] = None,
+ api_mode: Optional[str] = None,
+ headers: Optional[dict[str, str]] = None,
+) -> dict[str, Any]:
+ """Validate a ``/model`` value for the active provider.
+
+ 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 (- corrected_model: when a typo
+ was auto-corrected).
+ """
+ from hermes_cli import models as _m
+
+ requested = (model_name or "").strip()
+ normalized = _m.normalize_provider(provider)
+ if normalized == "openrouter" and base_url and not base_url_host_matches(base_url, "openrouter.ai"):
+ normalized = "custom"
+ lookup = requested
+ if normalized == "copilot":
+ lookup = _m.normalize_copilot_model_id(requested, api_key=api_key) or requested
+
+ if not requested:
+ return _reject("Model name cannot be empty.")
+ if normalized == "moa":
+ return _validate_moa(requested)
+ if any(ch.isspace() for ch in requested):
+ return _reject("Model names cannot contain spaces.")
+
+ req = _Request(requested, lookup, provider, normalized, api_key, base_url, api_mode, headers)
+ if normalized == "openrouter":
+ verdict = _parse_openrouter_preset(req)
+ if verdict is not None:
+ return verdict
+ if normalized == "lmstudio":
+ return _validate_lmstudio(req)
+ verdict = _validate_ollama_native(req)
+ if verdict is not None:
+ return verdict
+ if normalized == "custom" or normalized.startswith("custom:"):
+ return _validate_custom(req)
+ if normalized in {"openai-codex", "xai-oauth"}:
+ verdict = _validate_static_catalog(req)
+ if verdict is not None:
+ return verdict
+ if normalized in {"minimax", "minimax-cn"}:
+ verdict = _validate_minimax(req)
+ if verdict is not None:
+ return verdict
+ if normalized == "anthropic":
+ verdict = _validate_anthropic(req)
+ if verdict is not None:
+ return verdict
+ if api_mode == "anthropic_messages":
+ return _validate_anthropic_messages(req)
+ verdict = _validate_live_listing(req)
+ if verdict is not None:
+ return verdict
+ # API unreachable — accept and persist, but warn so typos don't silently break things.
+ if normalized == "bedrock":
+ verdict = _validate_bedrock(req)
+ if verdict is not None:
+ return verdict
+ return _validate_catalog_fallback(req)