The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): /status resolves the switched-to model's context window; validator names the missing slug
teknium1de132792f642
diff --git a/gateway/run.py b/gateway/run.pyindex f505eb66ead..7b936a91126 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -2277,9 +2277,19 @@ class _GatewayModelContext:context_source: str-def _resolve_gateway_model_context(model: Optional[str] = None) -> _GatewayModelContext:- """Resolve the configured gateway route and effective context window. Call off-loop (may block)."""- from agent.model_metadata import DEFAULT_FALLBACK_CONTEXT, get_model_context_length+def _resolve_gateway_model_context(+ model: Optional[str] = None, route: Optional[dict] = None,+) -> _GatewayModelContext:+ """Resolve the configured gateway route and effective context window. Call off-loop (may block).++ ``route`` (``provider`` / ``base_url`` / ``api_key`` of a session-only /model switch) replaces the+ default runtime credentials so the window is looked up against the endpoint that actually serves+ ``model``; a ``model.context_length`` pin only survives when that route still matches the config.+ ``context_source`` is ``"default"`` only for a model unknown to the catalog that fell through to+ ``DEFAULT_FALLBACK_CONTEXT`` — a catalog-listed 256K model is ``"detected"``.+ """+ from agent.model_metadata import (+ DEFAULT_CONTEXT_LENGTHS, DEFAULT_FALLBACK_CONTEXT, _longest_key_match, get_model_context_length)resolved_model = model or _resolve_gateway_model()config_context_length = provider = base_url = api_key = custom_providers = Noneconfigured_model = configured_provider = configured_base_url = None@@ -2307,6 +2317,12 @@ def _resolve_gateway_model_context(model: Optional[str] = None) -> _GatewayModeldef _read_runtime() -> None:nonlocal provider, base_url, api_key+ if route is not None:+ # The winning session route only — never the default route's endpoint under its model.+ provider = route.get("provider") or provider+ base_url = route.get("base_url") or None+ api_key = route.get("api_key")+ returnruntime = _resolve_runtime_agent_kwargs()provider = runtime.get("provider") or providerbase_url = runtime.get("base_url") or base_url@@ -2334,8 +2350,10 @@ def _resolve_gateway_model_context(model: Optional[str] = None) -> _GatewayModelresolved_model, base_url=base_url or "", api_key=api_key or "",config_context_length=config_context_length, provider=provider or "",custom_providers=custom_providers)+ fell_through = (context_length == DEFAULT_FALLBACK_CONTEXT+ and _longest_key_match(DEFAULT_CONTEXT_LENGTHS, str(resolved_model).lower()) is None)context_source = ("config" if config_context_length is not None- else "default" if context_length == DEFAULT_FALLBACK_CONTEXT else "detected")+ else "default" if fell_through else "detected")return _GatewayModelContext(model=resolved_model, provider=provider or "", base_url=base_url or "",context_length=context_length, context_source=context_source)diff --git a/gateway/slash_commands_status.py b/gateway/slash_commands_status.pyindex f5de9c59084..b88a909d160 100644--- a/gateway/slash_commands_status.py+++ b/gateway/slash_commands_status.py@@ -84,40 +84,45 @@ def _quiet_sync(call, default=None):def _status_model_route(status_agent, active_override: dict, persisted_route: dict, session_row: dict, session_entry):- """``(model, provider, context_used, context_total)`` for /status.+ """``(model, provider, context_used, context_total, route)`` for /status.Order: live/cached agent route -> active session override -> persisted recent route ->- SessionDB row -> gateway config (only loaded when something is still missing).+ SessionDB row -> gateway config (only loaded when something is still missing). ``route`` carries+ the ``provider`` / ``base_url`` / ``api_key`` of the winning source only, so a later context-window+ lookup queries the endpoint that serves the displayed model (never a losing route's endpoint)."""from gateway.run import _AGENT_PENDING_SENTINEL, _load_gateway_config, _resolve_gateway_modelcontext_used = context_total = 0- routes = []+ routes: list[tuple[str, str, dict]] = []if status_agent is not None and status_agent is not _AGENT_PENDING_SENTINEL:routes.append((_clean_str(getattr(status_agent, "model", "")),- _clean_str(getattr(status_agent, "provider", ""))))+ _clean_str(getattr(status_agent, "provider", "")),+ {"base_url": _clean_str(getattr(status_agent, "base_url", "")),+ "api_key": _clean_str(getattr(status_agent, "api_key", ""))}))ctx = getattr(status_agent, "context_compressor", None)if ctx is not None:context_used = max(0, _int_value(getattr(ctx, "last_prompt_tokens", 0)))context_total = _int_value(getattr(ctx, "context_length", 0))routes.append((_clean_str(active_override.get("model")),- _clean_str(active_override.get("provider"))))+ _clean_str(active_override.get("provider")),+ {"base_url": _clean_str(active_override.get("base_url")),+ "api_key": _clean_str(active_override.get("api_key"))}))routes.append((_clean_str(persisted_route.get("model")),- _clean_str(persisted_route.get("billing_provider"))))- row_route = (_clean_str(session_row.get("model")), _clean_str(session_row.get("billing_provider")))+ _clean_str(persisted_route.get("billing_provider")), {}))+ row_route = (_clean_str(session_row.get("model")), _clean_str(session_row.get("billing_provider")), {})# First fully-resolved (model AND provider) route wins; the SessionDB row is used even if partial.- model_name, provider_name = next((r for r in routes if r[0] and r[1]), row_route)+ model_name, provider_name, route = next((r for r in routes if r[0] and r[1]), row_route)context_used = context_used or _int_value(getattr(session_entry, "last_prompt_tokens", 0))user_config: dict[str, Any] = {}- if not model_name or not provider_name or not context_total:+ if not model_name or not provider_name:user_config = _quiet_sync(_load_gateway_config, {})model_cfg = user_config.get("model", {}) if isinstance(user_config, dict) else {}model_cfg = model_cfg if isinstance(model_cfg, dict) else {}model_name = model_name or _resolve_gateway_model(user_config)provider_name = provider_name or _clean_str(model_cfg.get("provider"))- configured_context = model_cfg.get("context_length")- if not context_total and isinstance(configured_context, int) and configured_context > 0:- context_total = configured_context- return model_name, provider_name, context_used, context_total+ # No raw ``model.context_length`` pin here: the resolver applies it only while the displayed+ # route still matches the configured one (a session /model switch must not inherit it).+ return model_name, provider_name, context_used, context_total, {"provider": provider_name, **route}def _context_compressor_lines(agent, ctx, used: int) -> list[str]:@@ -241,9 +246,16 @@ class GatewayStatusCommandsMixin:status_agent = agent if is_running else self._cached_agent_for(session_key)self._rehydrate_session_model_override(session_key)active_override = self._session_model_override(session_key) or {}- model_name, provider_name, context_used, context_total = _status_model_route(+ model_name, provider_name, context_used, context_total, route = _status_model_route(status_agent, active_override, persisted_route, session_row, session_entry)+ if not context_total and model_name:+ # Same resolver /context uses (off-loop: it can probe /models). A window the resolver only+ # invented (unknown model → DEFAULT_FALLBACK_CONTEXT) stays hidden rather than being shown+ # as a real limit; the occupancy-only line below is honest for that case.+ resolved = await self._resolve_route_context(source, model_name, route)+ if resolved is not None and resolved.context_source != "default":+ context_total = _int_value(resolved.context_length)fields = build_status_fields(session_entry.session_id, None, session_row, title=title, model=model_name, provider=provider_name,@@ -388,14 +400,7 @@ class GatewayStatusCommandsMixin:row = await _quiet(lambda: self._session_db.get_session(session_entry.session_id))model_name = _clean_str(row.get("model", "")) if isinstance(row, dict) else ""if not context_length:- from gateway.run import _profile_runtime_scope, _resolve_gateway_model_context-- def _resolve_nonresident_context():- if getattr(getattr(self, "config", None), "multiplex_profiles", False):- with _profile_runtime_scope(self._resolve_profile_home_for_source(source)):- return _resolve_gateway_model_context(model_name or None)- return _resolve_gateway_model_context(model_name or None)- resolved = await _quiet(lambda: asyncio.to_thread(_resolve_nonresident_context))+ resolved = await self._resolve_route_context(source, model_name)if resolved is not None:model_name = model_name or resolved.modelcontext_length = _int_value(resolved.context_length)@@ -406,6 +411,18 @@ class GatewayStatusCommandsMixin:)return used, context_length, model_name+ async def _resolve_route_context(self, source, model_name: str, route: dict | None = None):+ """``_resolve_gateway_model_context`` for a non-resident session, run off the event loop inside+ the profile serving ``source`` (multiplex). Fail-open: None on any error."""+ from gateway.run import _profile_runtime_scope, _resolve_gateway_model_context++ def _resolve():+ if getattr(getattr(self, "config", None), "multiplex_profiles", False):+ with _profile_runtime_scope(self._resolve_profile_home_for_source(source)):+ return _resolve_gateway_model_context(model_name or None, route)+ return _resolve_gateway_model_context(model_name or None, route)+ return await _quiet(lambda: asyncio.to_thread(_resolve))+async def _handle_agents_command(self, event: MessageEvent) -> str:"""Handle /agents command - list active agents and running tasks."""from gateway.run import _AGENT_PENDING_SENTINELdiff --git a/hermes_cli/models_validate.py b/hermes_cli/models_validate.pyindex a62565a91ed..8eccd07c06f 100644--- a/hermes_cli/models_validate.py+++ b/hermes_cli/models_validate.py@@ -364,16 +364,25 @@ def _validate_anthropic(req: _Request) -> Optional[dict[str, Any]]: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."""+ """Anthropic Messages transport: probe /v1/models and soft-accept either way, but say which+ happened — a proxy that never implemented the listing is a different situation from a reachable+ listing that simply doesn't name the slug (vendors alias ids: ``kimi-k3`` is served as ``k3``)."""from hermes_cli import models as _mmodels = _m.fetch_api_models(req.api_key, req.base_url, api_mode=req.api_mode)- verdict = _match_in_catalog(req.lookup, models).verdict(req) if models is not None else None- return verdict or _soft_accept(- f"Note: could not verify `{req.requested}` against this endpoint's model listing. Many "- "Anthropic-compatible proxies do not implement GET /v1/models. The model name has been accepted "- "without verification."+ if models is None:+ return _soft_accept(+ f"Note: could not verify `{req.requested}` against this endpoint's model listing. Many "+ "Anthropic-compatible proxies do not implement GET /v1/models. The model name has been accepted "+ "without verification."+ )+ # Vendor alias pairs sit below the default 0.5 similarity cutoff (kimi-k3 vs k3 ≈ 0.44).+ match = _match_in_catalog(req.lookup, models, case_insensitive=True, suggest_query=req.requested,+ suggest_cutoff=0.4)+ return match.verdict(req) or _soft_accept(+ f"Note: `{req.requested}` is not named in this endpoint's model listing (it may still serve it "+ f"under an alias).{match.suggestion_text}"+ "\n The model name has been accepted without verification.")diff --git a/tests/gateway/test_status_command.py b/tests/gateway/test_status_command.pyindex 2d2b6881af5..bf40007071a 100644--- a/tests/gateway/test_status_command.py+++ b/tests/gateway/test_status_command.py@@ -245,6 +245,75 @@ async def test_status_command_prefers_rehydrated_session_model_override(tmp_pathdb.close()+def _runner_with_session_override(override: dict, *, last_prompt_tokens: int):+ """Runner whose session has a committed /model override but no resident agent (no compressor)."""+ session_entry = SessionEntry(+ session_key=build_session_key(_make_source()),+ session_id="sess-1",+ created_at=datetime.now(),+ updated_at=datetime.now(),+ platform=Platform.TELEGRAM,+ chat_type="dm",+ )+ session_entry.last_prompt_tokens = last_prompt_tokens+ runner = _make_runner(session_entry)+ runner._session_state(session_entry.session_key).conversation.model_override = override+ return runner+++async def test_status_command_resolves_window_of_session_only_model_switch():+ """After a session-only /model switch with no turn yet, /status must show used / window for the+ switched-to route (looked up against THAT route's endpoint, and never the default route's+ ``model.context_length`` pin) instead of the occupancy-only line (#111436)."""+ override = {"model": "kimi-k3", "provider": "kimi-coding",+ "base_url": "https://api.kimi.com/coding", "api_key": "sk-override"}+ runner = _runner_with_session_override(override, last_prompt_tokens=79_455)+ config = {"model": {"default": "default-model", "provider": "openrouter", "context_length": 80_000}}++ with patch("gateway.run._load_gateway_config", return_value=config), patch(+ "gateway.run._resolve_runtime_agent_kwargs"+ ) as default_runtime, patch(+ "agent.model_metadata.get_model_context_length", return_value=1_048_576+ ) as lookup:+ result = await runner._handle_message(_make_event("/status"))++ assert "**Model:** `kimi-k3` (kimi-coding)" in result+ assert "**Context:** 79,455 / 1,048,576 (8%)" in result+ assert "80,000" not in result+ default_runtime.assert_not_called()+ kwargs = lookup.call_args.kwargs+ assert (kwargs["base_url"], kwargs["api_key"], kwargs["provider"]) == (+ override["base_url"], override["api_key"], "kimi-coding")+ assert kwargs["config_context_length"] is None+++async def test_status_command_keeps_occupancy_only_for_unknown_model_window():+ """A model the resolver cannot size falls to DEFAULT_FALLBACK_CONTEXT; /status must not present+ that invented number as the window (a catalog-listed model of the same size still counts)."""+ from agent.model_metadata import DEFAULT_FALLBACK_CONTEXT++ runner = _runner_with_session_override(+ {"model": "proxy-mystery-model", "provider": "custom:proxy", "base_url": "http://127.0.0.1:1/v1"},+ last_prompt_tokens=4_321,+ )+ with patch("gateway.run._load_gateway_config", return_value={}), patch(+ "agent.model_metadata.get_model_context_length", return_value=DEFAULT_FALLBACK_CONTEXT+ ):+ result = await runner._handle_message(_make_event("/status"))+ assert "**Context:** ~4,321 tokens" in result+ assert f"{DEFAULT_FALLBACK_CONTEXT:,}" not in result++ runner = _runner_with_session_override(+ {"model": "grok-4", "provider": "xai", "base_url": ""}, last_prompt_tokens=4_321)+ with patch("gateway.run._load_gateway_config", return_value={}), patch(+ "agent.model_metadata.get_model_context_length", return_value=DEFAULT_FALLBACK_CONTEXT+ ):+ result = await runner._handle_message(_make_event("/status"))+ assert f"**Context:** 4,321 / {DEFAULT_FALLBACK_CONTEXT:,} (2%)" in result++@pytest.mark.asyncioasync def test_agents_command_reports_active_agents_and_processes(monkeypatch):session_key = build_session_key(_make_source())diff --git a/tests/hermes_cli/test_model_validation.py b/tests/hermes_cli/test_model_validation.pyindex 43c983b8839..2c9a54f3056 100644--- a/tests/hermes_cli/test_model_validation.py+++ b/tests/hermes_cli/test_model_validation.py@@ -827,3 +827,17 @@ class TestValidateCustomUnreachableFallback:assert "was not saved" in result["message"]# A reachable catalog keeps authoritative validation regardless of mode.assert self._validate("my-model", "custom", models=["my-model"], api_mode="chat_completions")["recognized"] is True++ def test_anthropic_messages_reachable_listing_without_slug_is_not_called_unimplemented(self):+ """A listing that answered 200 but lacks the slug must not be described as a proxy that+ 'does not implement GET /v1/models'; it names the alias candidates instead (#111436)."""+ result = self._validate("kimi-k3", "kimi-coding", models=["k3", "k3-turbo"], api_mode="anthropic_messages")+ assert (result["accepted"], result["persist"], result["recognized"]) == (True, True, False)+ assert "do not implement" not in result["message"]+ assert "not named in this endpoint's model listing" in result["message"]+ assert "`k3`" in result["message"]+ # Case-only spelling differences are a match, not a warning.+ assert self._validate("K3", "kimi-coding", models=["k3"], api_mode="anthropic_messages")["recognized"] is True+ # The unreachable-listing wording is unchanged.+ unreachable = self._validate("kimi-k3", "kimi-coding", models=None, api_mode="anthropic_messages")+ assert "do not implement GET /v1/models" in unreachable["message"]