Skip to content

The agent that grows with you

fix(models): allow spaces in self-hosted and user-configured model ids

brooklyn!5bc1761cf1e5
diff --git a/hermes_cli/cli_model_switch_mixin.py b/hermes_cli/cli_model_switch_mixin.py
index 0e78ee66836..e297926b51a 100644
--- a/hermes_cli/cli_model_switch_mixin.py
+++ b/hermes_cli/cli_model_switch_mixin.py
@@ -723,6 +723,9 @@ class CLIModelSwitchMixin:
model_list = cached_provider_model_ids(provider_data["slug"]) or model_list
except Exception:
pass
+ from hermes_cli.models_validate import offered_model_ids
+ model_list = offered_model_ids(
+ model_list, provider_data.get("slug"), provider_data.get("api_url"))
state.update(
stage="model", provider_data=provider_data, model_list=model_list,
selected=0, filter="", _filtered_pairs=None)
diff --git a/hermes_cli/inventory.py b/hermes_cli/inventory.py
index c30338d346d..a5f414be9ef 100644
--- a/hermes_cli/inventory.py
+++ b/hermes_cli/inventory.py
@@ -158,6 +158,9 @@ def build_models_payload(
if featured:
_apply_featured(rows, metadata_config=metadata_config)
_apply_custom_aliases(rows)
+ from hermes_cli.models_validate import drop_unofferable_model_ids
+
+ drop_unofferable_model_ids(rows)
return {"providers": rows, "model": ctx.current_model, "provider": ctx.current_provider}
diff --git a/hermes_cli/model_switch_providers.py b/hermes_cli/model_switch_providers.py
index 05fa5b5f420..35b4f5d379a 100644
--- a/hermes_cli/model_switch_providers.py
+++ b/hermes_cli/model_switch_providers.py
@@ -1343,4 +1343,7 @@ def list_picker_providers(
is_custom_endpoint = bool(p.get("is_user_defined")) and bool(p.get("api_url"))
if p.get("models") or is_custom_endpoint:
filtered.append(p)
+ from hermes_cli.models_validate import drop_unofferable_model_ids
+
+ drop_unofferable_model_ids(filtered)
return filtered
diff --git a/hermes_cli/models_validate.py b/hermes_cli/models_validate.py
index a6aaf06ac0a..662a860f576 100644
--- a/hermes_cli/models_validate.py
+++ b/hermes_cli/models_validate.py
@@ -121,11 +121,143 @@ def _validate_moa(req: _Request) -> dict[str, Any]:
def _reject_whitespace(req: _Request) -> Optional[dict[str, Any]]:
- if any(ch.isspace() for ch in req.requested):
+ # Cloud catalogs never contain spaces. Self-hosted servers and a user-configured
+ # base_url do (VLLM "My Custom Model", a local router's "Go reasoning"). The
+ # step stays here — later branches must not see a cloud id the catalog cannot serve.
+ if any(ch.isspace() for ch in req.requested) and not _whitespace_allowed(req):
return _reject("Model names cannot contain spaces.")
return None
+_SELF_HOSTED_PROVIDERS = frozenset({
+ "lmstudio", "ollama", "local", "vllm", "llamacpp", "llama.cpp", "llama-cpp",
+})
+
+
+def _provider_token(provider: Optional[str]) -> str:
+ return str(provider or "").strip().lower()
+
+
+def _is_self_hosted_provider(provider: Optional[str]) -> bool:
+ """Local servers and the custom endpoint bucket, including aliases that normalize to it."""
+ raw = _provider_token(provider)
+ if not raw:
+ return False
+ if raw == "custom" or raw.startswith("custom:"):
+ return True
+ from hermes_cli import models as _m
+
+ normalized = _m.normalize_provider(raw)
+ if normalized == "custom" or normalized.startswith("custom:"):
+ return True
+ return raw in _SELF_HOSTED_PROVIDERS or normalized in _SELF_HOSTED_PROVIDERS
+
+
+def _non_public_host(host: str) -> bool:
+ """Loopback, LAN, and single-label hosts are a user's endpoint, never a vendor catalog."""
+ host = (host or "").lower().rstrip(".")
+ if not host or host in {"localhost", "127.0.0.1", "::1", "0.0.0.0"} or host.endswith(".localhost"):
+ return bool(host)
+ if host.endswith((".local", ".lan", ".internal", ".home", ".localdomain")):
+ return True
+ if "." not in host:
+ return True
+ parts = host.split(".")
+ if len(parts) == 4 and all(part.isdigit() for part in parts):
+ octets = [int(part) for part in parts]
+ if octets[0] in {10, 127} or (octets[0] == 192 and octets[1] == 168):
+ return True
+ if octets[0] == 172 and 16 <= octets[1] <= 31:
+ return True
+ return False
+
+
+def _stock_host(provider: str) -> str:
+ """Vendor host for *provider*, offline. Empty when this install cannot name one.
+
+ ``get_provider`` can answer with a different id (``openai`` → the OpenRouter
+ overlay when models.dev is cold). A foreign row is not this provider's stock
+ endpoint — using it would exempt the real cloud host.
+ """
+ from hermes_cli.providers import get_provider
+ from utils import base_url_hostname
+
+ token = _provider_token(provider)
+ if not token:
+ return ""
+ try:
+ pdef = get_provider(token, allow_network=False)
+ except Exception:
+ return ""
+ if pdef is None or _provider_token(pdef.id) != token:
+ return ""
+ return base_url_hostname(pdef.base_url or "")
+
+
+def provider_allows_model_whitespace(provider: Optional[str], base_url: Optional[str] = None) -> bool:
+ """True when a spaced id is a real selection, not a cloud-catalog typo.
+
+ Self-hosted providers always qualify. A base_url qualifies when the user
+ configured it: a non-public host, or a public host that is not this
+ provider's own stock endpoint. A public host with no stock to compare
+ against stays rejected, so a cloud URL cannot slip through a cold catalog.
+ """
+ if _is_self_hosted_provider(provider):
+ return True
+ url = str(base_url or "").strip()
+ if not url:
+ return False
+ from utils import base_url_hostname
+
+ host = base_url_hostname(url)
+ if not host:
+ return False
+ if _non_public_host(host):
+ return True
+ raw = _provider_token(provider)
+ from hermes_cli import models as _m
+
+ normalized = _m.normalize_provider(raw) if raw else ""
+ stock = _stock_host(normalized or raw)
+ return bool(stock) and host != stock
+
+
+def _whitespace_allowed(req: _Request) -> bool:
+ # The openrouter→custom rewrite lives on ``normalized``; aliases live on the raw value.
+ if _is_self_hosted_provider(req.normalized) or _is_self_hosted_provider(req.provider):
+ return True
+ return provider_allows_model_whitespace(req.provider or req.normalized, req.base_url)
+
+
+def offered_model_ids(models, provider: Optional[str], base_url: Optional[str] = None) -> list:
+ """Ids a picker may show. Drops whitespace the validator will refuse; keeps the rest."""
+ ids = list(models or [])
+ if provider_allows_model_whitespace(provider, base_url):
+ return ids
+ return [model_id for model_id in ids if not (isinstance(model_id, str) and any(ch.isspace() for ch in model_id))]
+
+
+def drop_unofferable_model_ids(rows: list) -> None:
+ """In-place: picker rows must not offer an id ``validate_requested_model`` will refuse for whitespace."""
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ provider = row.get("slug")
+ base_url = row.get("api_url") or row.get("base_url")
+ models = row.get("models")
+ if isinstance(models, list):
+ filtered = offered_model_ids(models, provider, base_url)
+ removed = len(models) - len(filtered)
+ if removed:
+ row["models"] = filtered
+ total = row.get("total_models")
+ if isinstance(total, int):
+ row["total_models"] = max(0, total - removed)
+ featured = row.get("featured_models")
+ if isinstance(featured, list):
+ row["featured_models"] = offered_model_ids(featured, provider, base_url)
+
+
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
@@ -617,7 +749,8 @@ def _for(*providers: str) -> Callable[[_Request], bool]:
# (gate, branch): the branch runs when the gate passes; the first non-None verdict wins. ORDER IS
-# BEHAVIOR: moa → whitespace → OpenRouter preset parse → LM Studio → Ollama native → custom →
+# BEHAVIOR: moa → whitespace (skipped only for self-hosted providers and a user-configured
+# base_url) → OpenRouter preset parse → LM Studio → Ollama native → custom →
# codex/xai static → MiniMax → managed local (staged library) → Anthropic native →
# Anthropic Messages → external process → live listing → Bedrock → curated-catalog fallback (always decides).
_LADDER: tuple[tuple[Callable[[_Request], bool], Callable[[_Request], Optional[dict[str, Any]]]], ...] = (
diff --git a/tests/hermes_cli/test_model_validation.py b/tests/hermes_cli/test_model_validation.py
index b6597246347..9e0a2c5cf2c 100644
--- a/tests/hermes_cli/test_model_validation.py
+++ b/tests/hermes_cli/test_model_validation.py
@@ -822,3 +822,115 @@ class TestProfileCatalogAuthoritative:
"other-vendor/model-a", "relay-owned-catalog", api_key="k")
assert result["accepted"] is True
assert result["recognized"] is True
+
+
+# -- validate — whitespace in self-hosted / user-configured ids --------------
+
+def _spaces_message(result) -> bool:
+ return "spaces" in (result.get("message") or "")
+
+
+class TestModelIdWhitespace:
+ """Cloud catalogs reject whitespace. Self-hosted providers and a user-configured
+ base_url may serve ids that contain it. The picker must not offer an id this
+ validator will refuse."""
+
+ def test_cloud_providers_reject_whitespace(self):
+ for provider, model in (
+ ("anthropic", "claude opus"),
+ ("openrouter", "anthropic/claude opus"),
+ ("openai", "gpt 5.4"),
+ ):
+ result = _validate(model, provider=provider)
+ assert result["accepted"] is False
+ assert result["persist"] is False
+ assert result["message"] == "Model names cannot contain spaces."
+
+ def test_cloud_stock_base_url_still_rejects_whitespace(self):
+ for provider, base_url in (
+ ("anthropic", "https://api.anthropic.com"),
+ ("openai", "https://api.openai.com/v1"),
+ ("openrouter", "https://openrouter.ai/api/v1"),
+ ):
+ result = _validate("claude opus", provider=provider, base_url=base_url)
+ assert result["accepted"] is False, provider
+ assert _spaces_message(result), provider
+
+ def test_custom_provider_accepts_listed_id_with_spaces(self):
+ result = _validate(
+ "My Custom Model", provider="custom", api_models=["My Custom Model"],
+ base_url="http://127.0.0.1:8000/v1")
+ assert result["accepted"] is True
+ assert result["recognized"] is True
+ assert result["persist"] is True
+
+ def test_named_custom_endpoint_accepts_listed_id_with_spaces(self):
+ result = _validate(
+ "Go reasoning", provider="custom:omniroute", api_models=["Go reasoning"],
+ base_url="http://127.0.0.1:20128/v1")
+ assert result["accepted"] is True
+ assert result["recognized"] is True
+
+ def test_self_hosted_aliases_accept_listed_ids_with_whitespace(self):
+ for provider in ("vllm", "ollama", "llamacpp", "local", "lmstudio"):
+ model = "Meta Llama 3.1 8B"
+ if provider == "lmstudio":
+ with patch("hermes_cli.models_local.probe_lmstudio_models", return_value=[model]):
+ result = validate_requested_model(model, provider)
+ else:
+ result = _validate(
+ model, provider=provider, api_models=[model],
+ base_url="http://127.0.0.1:8000/v1")
+ assert result["accepted"] is True, provider
+ assert not _spaces_message(result), provider
+
+ def test_user_configured_base_url_accepts_listed_id_with_spaces(self):
+ """A router with its own slug is not ``custom``; the base_url is the exemption."""
+ result = _validate(
+ "Go reasoning", provider="omniroute", api_models=["Go reasoning"],
+ base_url="http://127.0.0.1:20128/v1", api_key="sk-test")
+ assert result["accepted"] is True
+ assert result["recognized"] is True
+ assert not _spaces_message(result)
+
+ def test_tab_in_cloud_id_is_still_rejected(self):
+ result = _validate("claude\topus", provider="anthropic")
+ assert result["accepted"] is False
+ assert result["message"] == "Model names cannot contain spaces."
+
+
+def test_picker_payload_omits_ids_the_validator_rejects_for_whitespace():
+ """Desktop model.options is this payload. A cloud row must not offer a spaced id;
+ a self-hosted row and a user-configured base_url row must keep theirs."""
+ from hermes_cli.inventory import ConfigContext, build_models_payload
+
+ rows = [
+ {
+ "slug": "anthropic", "name": "Anthropic", "is_current": False,
+ "is_user_defined": False, "models": ["claude-opus-4.6", "claude opus"],
+ "total_models": 2, "source": "curated",
+ },
+ {
+ "slug": "omniroute", "name": "OmniRoute", "is_current": False,
+ "is_user_defined": True, "models": ["Go reasoning", "plain-id"],
+ "total_models": 2, "source": "user-config",
+ "api_url": "http://127.0.0.1:20128/v1",
+ },
+ {
+ "slug": "lmstudio", "name": "LM Studio", "is_current": False,
+ "is_user_defined": False, "models": ["Meta Llama 3.1 8B"],
+ "total_models": 1, "source": "local",
+ },
+ ]
+ ctx = ConfigContext(
+ current_provider="anthropic", current_model="claude-opus-4.6",
+ current_base_url="", user_providers={}, custom_providers=[])
+ with patch("hermes_cli.model_switch.list_authenticated_providers", return_value=rows), \
+ patch("hermes_cli.inventory._local_runtime_row", return_value=None), \
+ patch("hermes_cli.inventory._moa_provider_row", return_value=None):
+ payload = build_models_payload(ctx)
+ by_slug = {row["slug"]: row["models"] for row in payload["providers"]}
+ assert "claude opus" not in by_slug["anthropic"]
+ assert "claude-opus-4.6" in by_slug["anthropic"]
+ assert "Go reasoning" in by_slug["omniroute"]
+ assert "Meta Llama 3.1 8B" in by_slug["lmstudio"]