The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): keep a named provider's identity only while its entry serves the session's endpoint
yoniebans0bc8789d9a28
diff --git a/gateway/run_turn_prepare.py b/gateway/run_turn_prepare.pyindex 7d2b3ecf5af..36de190dcaa 100644--- a/gateway/run_turn_prepare.py+++ b/gateway/run_turn_prepare.py@@ -258,21 +258,11 @@ class GatewayTurnPrepareMixin:model = getattr(agent, "model", None)if not model:return- adapter_provider = str(getattr(agent, "provider", "") or "").strip()- requested_provider = str(getattr(agent, "requested_provider", "") or "").strip()- provider = adapter_provider- if adapter_provider.lower() == "custom":- if requested_provider.lower() not in {"", "custom", "auto"}:- provider = requested_provider- else:- try:- from hermes_cli.runtime_provider import canonical_custom_identity- provider = canonical_custom_identity(- base_url=str(getattr(agent, "base_url", "") or ""), model=model) or provider- except Exception:- logger.debug("custom provider identity lookup failed", exc_info=True)+ from hermes_cli.runtime_provider_custom import session_provider_identityruntime = {- "provider": provider,+ "provider": session_provider_identity(getattr(agent, "provider", None),+ getattr(agent, "requested_provider", None),+ getattr(agent, "base_url", None), model),"base_url": getattr(agent, "base_url", None),"api_mode": getattr(agent, "api_mode", None),}diff --git a/gateway/session_local_inventory.py b/gateway/session_local_inventory.pyindex 1a942ccec7c..f2e98622841 100644--- a/gateway/session_local_inventory.py+++ b/gateway/session_local_inventory.py@@ -127,6 +127,12 @@ def _cli_skills():return grouped+def _session_provider(view, config=None):+ from hermes_cli.runtime_provider_custom import session_provider_identity+ return session_provider_identity(getattr(view, "provider", None), getattr(view, "requested_provider", None),+ getattr(view, "base_url", None), getattr(view, "model", None), config=config)++def session_inventory(authority, policy, agent, cwd):"""Main's banner/status fields for one session. Each section degrades to main's empty value onits own, so one failing builder never blanks the others (main wrapped each in ``suppress``)."""@@ -139,12 +145,7 @@ def session_inventory(authority, policy, agent, cwd):config = policy.config(authority, secrets=False) if policy is not None else {}if agent is not None:from agent.voice_turn_route import session_runtime_view- view = session_runtime_view(agent)- provider = str(getattr(view, "provider", "") or "")- requested = str(getattr(view, "requested_provider", "") or "").strip()- if provider.lower() == "custom" and requested.lower() not in {"", "custom", "auto"}:- provider = requested- info["provider"] = provider+ info["provider"] = _session_provider(session_runtime_view(agent), config if policy is not None else None)info["tools"] = _grouped(getattr(agent, "tools", None))info["system_prompt"] = getattr(agent, "_cached_system_prompt", "") or ""compressor = getattr(agent, "context_compressor", None)@@ -211,12 +212,7 @@ def agent_inventory(agent) -> dict:info: dict = {}with contextlib.suppress(Exception):from agent.voice_turn_route import session_runtime_view- view = session_runtime_view(agent)- provider = str(getattr(view, "provider", "") or "")- requested = str(getattr(view, "requested_provider", "") or "").strip()- if provider.lower() == "custom" and requested.lower() not in {"", "custom", "auto"}:- provider = requested- info["provider"] = provider+ info["provider"] = _session_provider(session_runtime_view(agent))with contextlib.suppress(Exception):info["tools"] = _grouped(getattr(agent, "tools", None))info["system_prompt"] = getattr(agent, "_cached_system_prompt", "") or ""diff --git a/hermes_cli/runtime_provider_custom.py b/hermes_cli/runtime_provider_custom.pyindex 39fa42b1552..821de6e27c0 100644--- a/hermes_cli/runtime_provider_custom.py+++ b/hermes_cli/runtime_provider_custom.py@@ -400,6 +400,22 @@ def canonical_custom_identity(*, base_url: Optional[str] = None, config_providerreturn identity or custom_provider_slug(candidate_norm)+def session_provider_identity(provider: Any, requested_provider: Any, base_url: Any, model: Any = None, *,+ config: Optional[dict[str, Any]] = None) -> str:+ """A session's identity: the requested entry while it still serves ``base_url`` (an edited entry would+ pair its new key with the old endpoint on resume), else the endpoint's entry, else the adapter."""+ adapter = _clean(provider)+ if adapter.lower() != "custom":+ return adapter+ requested = _clean(requested_provider)+ url = _normalize_base_url_for_match(base_url)+ if url and requested.lower() not in {"", "custom", "auto"}:+ entry = _get_named_custom_provider(requested, config=config, resolve_credentials=False)+ if entry and _normalize_base_url_for_match(_entry_url(entry)) == url:+ return requested+ return canonical_custom_identity(base_url=_clean(base_url) or None, model=_clean(model) or None) or adapter++def is_routable_provider(provider: Optional[str]) -> bool:"""Whether a provider name currently resolves to a routable route. Empty/None/``auto`` isvacuously routable (agent build falls back to the configured default). Bare ``custom`` is thediff --git a/tests/gateway/test_named_custom_provider_session_identity.py b/tests/gateway/test_named_custom_provider_session_identity.pyindex 7ec5a661f01..055a7d6be88 100644--- a/tests/gateway/test_named_custom_provider_session_identity.py+++ b/tests/gateway/test_named_custom_provider_session_identity.py@@ -96,11 +96,15 @@ def test_bare_custom_sync_uses_canonical_endpoint_fallback(tmp_path, monkeypatchdef test_tui_runtime_config_and_session_info_keep_requested_custom_slug(monkeypatch):+ from hermes_cli.config import atomic_config_write, get_config_path+ from hermes_constants import get_hermes_home++ atomic_config_write(get_config_path(), CONFIG)agent = _agent()monkeypatch.setattr("tui_gateway.server._load_approval_mode", lambda: "manual")config = _runtime_model_config(agent)assert config["provider"] == "custom:beta"- info = _session_info(agent, {"agent": agent, "session_key": "s1"})+ info = _session_info(agent, {"agent": agent, "session_key": "s1", "profile_home": str(get_hermes_home())})assert info["provider"] == "custom:beta"assert "sk-beta" not in str(config)@@ -121,8 +125,11 @@ async def test_canonical_session_info_snapshot_uses_named_custom_identity(tmp_pafrom gateway.session_local_inventory import snapshot_infofrom tests.gateway.test_surface_admission import _authority+ from hermes_cli.config import atomic_config_write, get_config_path+agent = _agent()authority = await _authority(tmp_path, monkeypatch, lambda _event: "ok")+ atomic_config_write(get_config_path(), CONFIG)authority.runner._cached_agent_for = lambda _route: agentinfo = await snapshot_info(authority, SessionRef("p", "s"))assert info["provider"] == "custom:beta"@@ -203,9 +210,10 @@ def test_tui_runtime_config_does_not_pair_an_edited_entry_key_with_the_old_endpodef test_live_unpersisted_session_reports_the_requested_entry(monkeypatch):"""A built session reattached before its first turn reports the entry it runs, not the adapter class."""from hermes_cli.config import atomic_config_write, get_config_path+ from hermes_constants import get_hermes_homefrom tui_gateway.server import _live_session_identityatomic_config_write(get_config_path(), CONFIG)- session = {"agent": _agent(), "session_key": "not-persisted"}+ session = {"agent": _agent(), "session_key": "not-persisted", "profile_home": str(get_hermes_home())}assert _live_session_identity(session) == ("beta-model", "custom:beta")diff --git a/tui_gateway/agent_factory.py b/tui_gateway/agent_factory.pyindex 17204c2f3a5..829089aa7e6 100644--- a/tui_gateway/agent_factory.py+++ b/tui_gateway/agent_factory.py@@ -187,19 +187,9 @@ def _runtime_model_config(agent, existing: dict | None = None) -> dict:from agent.voice_turn_route import session_runtime_viewagent = session_runtime_view(agent)attr = lambda k: str(getattr(agent, k, "") or "").strip()- model, provider, requested_provider, base_url = (- attr("model"), attr("provider"), attr("requested_provider"), attr("base_url"))- if provider.lower() == "custom":- # ``agent.provider`` is the adapter class for every named custom entry. Keep the- # requested identity when available; endpoint matching is ambiguous when entries share a host.- if requested_provider and requested_provider.lower() not in {"custom", "auto"}:- provider = requested_provider- else:- try:- from hermes_cli.runtime_provider import canonical_custom_identity- provider = canonical_custom_identity(base_url=base_url, model=model or None) or provider- except Exception:- logger.debug("custom provider identity lookup failed", exc_info=True)+ model, base_url = attr("model"), attr("base_url")+ from hermes_cli.runtime_provider_custom import session_provider_identity+ provider = session_provider_identity(attr("provider"), attr("requested_provider"), base_url, model)reasoning_config = getattr(agent, "reasoning_config", None)live = {"model": model, "provider": provider, "base_url": base_url, "api_mode": attr("api_mode"),diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 74587050132..e7f03ed0d8e 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -1508,6 +1508,13 @@ def _turn_started_at(session: dict | None) -> float | None:return float(inflight["started_at"]) if isinstance(inflight, dict) and inflight.get("started_at") else None+def _scoped_session_provider(agent, session: dict) -> str:+ """The entry an agent on the ``custom`` adapter runs, resolved in the session's own profile: clients+ reuse this identity for new chats without the endpoint or key, and callers need not be bound to it."""+ with _profile_build_scope(session.get("profile_home") or _hermes_home):+ return _runtime_model_config(agent).get("provider") or "custom"++def _live_session_identity(session: dict) -> tuple[str, str]:"""``(model, provider)`` the live session actually runs — the same precedence ``_session_info`` reports:a switch queued mid-turn, the metadata mirror, the built agent, the composer override a deferred record@@ -1518,8 +1525,11 @@ def _live_session_identity(session: dict) -> tuple[str, str]:override = session.get("model_override") or {}model = (str(pending.get("display_model") or "").strip() or mirror.get("model")or getattr(agent, "model", "") or override.get("model"))+ agent_provider = getattr(agent, "provider", "")+ if agent_provider == "custom":+ agent_provider = _scoped_session_provider(agent, session)provider = (str(pending.get("display_provider") or "").strip() or mirror.get("provider")- or getattr(agent, "provider", "") or override.get("provider"))+ or agent_provider or override.get("provider"))default = ("", "") if model else _session_default_route(session)return str(model or default[0]), str(provider or default[1])@@ -1571,14 +1581,8 @@ def _session_info(agent, session: dict | None = None) -> dict:pending_model = str(pending_switch.get("display_model") or "").strip()pending_provider = str(pending_switch.get("display_provider") or "").strip()provider = mirror.get("provider", getattr(agent, "provider", ""))- requested_provider = str(getattr(agent, "requested_provider", "") or "").strip()- if provider == "custom" and requested_provider.lower() not in {"", "custom", "auto"}:- provider = requested_providerif provider == "custom" and "provider" not in mirror and agent is not None:- # Clients reuse this identity for new chats without carrying the endpoint or key.- # Broadcast/resume callers need not be bound to this session's profile.- with _profile_build_scope(sess.get("profile_home") or _hermes_home):- provider = _runtime_model_config(agent).get("provider", provider)+ provider = _scoped_session_provider(agent, sess)model = pending_model or mirror.get("model", getattr(agent, "model", ""))# The level the route's entry clamp actually sends (== reasoning_effort when verbatim), so the# Desktop can say "ultra sends max on this route" like `/reasoning` does instead of presenting a