The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): heal bare custom only when unambiguous; pass the live entry to pickers
unsupportedpastelsf6280475f825
diff --git a/gateway/session_config.py b/gateway/session_config.pyindex 13b009d43d1..7e8467c1b39 100644--- a/gateway/session_config.py+++ b/gateway/session_config.py@@ -225,8 +225,10 @@ async def model_options(connection, ref, params):selected = providerif selected == 'custom':from hermes_cli.runtime_provider import canonical_custom_identity+ requested = None if getattr(agent, '_fallback_activated', False) else getattr(+ agent, 'requested_provider', None)selected = canonical_custom_identity(base_url=base_url, config_provider=ctx.current_provider,- model=model) or selected+ model=model, requested=requested) or selectedreturn build_model_options_payload(ctx.with_overrides(current_provider=selected,current_model=model, current_base_url=base_url), **{k: params[k] for k in flags & params.keys()})return await asyncio.to_thread(discover)diff --git a/hermes_cli/runtime_provider_custom.py b/hermes_cli/runtime_provider_custom.pyindex 2123a85040c..1dda7d5c3be 100644--- a/hermes_cli/runtime_provider_custom.py+++ b/hermes_cli/runtime_provider_custom.py@@ -299,30 +299,35 @@ def codex_model_provider_id(requested_provider: str) -> Optional[str]:# ── identity recovery (bare "custom" -> durable ``custom:<name>``) ─────────────────────────-def _find_custom_identity(matches: Callable[[dict[str, Any]], bool],- config: Optional[dict[str, Any]] = None) -> Optional[str]:- """First entry in ``providers:`` then legacy ``custom_providers:`` where ``matches(entry)``+def _custom_identities(matches: Callable[[dict[str, Any]], bool], config: Optional[dict[str, Any]] = None):+ """Every entry in ``providers:`` then legacy ``custom_providers:`` where ``matches(entry)``holds, as its canonical ``custom:<name>`` slug. *config* defaults to the active profile's."""from hermes_cli.config import is_provider_enabledrp = _rp()try:config = rp.load_config() if config is None else configexcept Exception:- return None+ logger.debug("custom provider identity: config unreadable", exc_info=True)+ returnproviders = config.get("providers")if isinstance(providers, dict):for ep_name, entry in providers.items():if isinstance(entry, dict) and is_provider_enabled(entry) and matches(entry):- return custom_provider_slug(str(ep_name), str(ep_name))+ yield custom_provider_slug(str(ep_name), str(ep_name))try:custom_providers = rp.get_compatible_custom_providers(config)except Exception:+ logger.debug("custom provider identity: custom_providers unreadable", exc_info=True)custom_providers = Nonefor entry in custom_providers or []:name = entry.get("name") if isinstance(entry, dict) else Noneif isinstance(name, str) and name.strip() and matches(entry):- return custom_provider_slug(name, str(entry.get("provider_key", "") or ""))- return None+ yield custom_provider_slug(name, str(entry.get("provider_key", "") or ""))+++def _find_custom_identity(matches: Callable[[dict[str, Any]], bool],+ config: Optional[dict[str, Any]] = None) -> Optional[str]:+ return next(_custom_identities(matches, config), None)def find_custom_provider_identity(base_url: str) -> Optional[str]:@@ -360,16 +365,18 @@ def _entry_serves_model(entry: dict[str, Any], target: str) -> bool:def routed_custom_identity(base_url: Optional[str] = None, model: Optional[str] = None,- config: Optional[dict[str, Any]] = None, requested: Optional[str] = None) -> Optional[str]:+ config: Optional[dict[str, Any]] = None, requested: Optional[str] = None,+ guess: bool = True) -> Optional[str]:"""The configured ``custom:<name>`` entry a bare ``custom`` route (the billing class every namedendpoint reports) ran on. The entry the runtime resolved (*requested*) is that route when itsits on *base_url*: entries sharing one relay may list each other's models, so (URL, model) isonly a guess for when no entry is known. Then the entry also serving *model* beats the first one- on that URL; without a URL the model alone names it."""+ on that URL; without a URL the model alone names it. ``guess=False`` (a record of the route that+ ran) names an unknown entry only when it is the one enabled on *base_url*."""url = _route_key(base_url)target = str(model or "").strip().lower()if not url:- return _find_custom_identity(lambda entry: _entry_serves_model(entry, target), config) if target else None+ return _find_custom_identity(lambda entry: _entry_serves_model(entry, target), config) if target and guess else Nonedef on_url(entry: dict[str, Any]) -> bool:return _route_key(_entry_url(entry)) == url@@ -377,21 +384,26 @@ def routed_custom_identity(base_url: Optional[str] = None, model: Optional[str]if requested and _normalize_custom_provider_name(requested) != "custom" else None)if named and on_url(named):return custom_provider_slug(str(named.get("name") or ""), str(named.get("provider_key") or ""))+ if not guess:+ # A bare-custom /model switch keeps the session's key whichever sibling lists the model.+ on = set(_custom_identities(on_url, config))+ return on.pop() if len(on) == 1 else Nonereturn ((target and _find_custom_identity(lambda e: on_url(e) and _entry_serves_model(e, target), config))or _find_custom_identity(on_url, config))def routed_custom_identity_in(home: Any, base_url: Optional[str] = None,model: Optional[str] = None, requested: Optional[str] = None) -> Optional[str]:- """:func:`routed_custom_identity` against the profile at *home*: a session store names entries from- its own profile's config, never the ambient scope's (one gateway serves many profiles)."""+ """The entry a session at *home* ran on (:func:`routed_custom_identity` with ``guess=False``), named+ from its own profile's config, never the ambient scope's (one gateway serves many profiles)."""from hermes_cli.config_effective import load_user_config_effective- return routed_custom_identity(base_url, model, load_user_config_effective(Path(home) / "config.yaml"), requested)+ return routed_custom_identity(base_url, model, load_user_config_effective(Path(home) / "config.yaml"),+ requested, guess=False)-def _endpoint_identity(base_url: str, model: Optional[str] = None, requested: Optional[str] = None) -> Optional[str]:+def _endpoint_identity(base_url: str, requested: Optional[str] = None) -> Optional[str]:"""The menu identity that owns ``base_url``: a configured entry, else the managed server."""- identity = routed_custom_identity(base_url, model, requested=requested)+ identity = routed_custom_identity(base_url, requested=requested)if identity:return identity# The managed server has no custom-provider config entry. Recover its menu key@@ -409,7 +421,8 @@ def canonical_custom_identity(*, base_url: Optional[str] = None, config_providerendpoint first, then the ownership-checked managed server, then a configured model orprovider. Every session persistence/restore path shares this lookup."""rp = _rp()- identity = _endpoint_identity(base_url, model, requested) if base_url else None+ # No model: a sibling listing it is not the entry a bare-custom switch kept (URL-first, as ever).+ identity = _endpoint_identity(base_url, requested) if base_url else Noneif identity:return identityidentity = find_custom_provider_identity_by_model(model) if model else Nonediff --git a/hermes_state_sessions.py b/hermes_state_sessions.pyindex d02ececc619..27afb12d4de 100644--- a/hermes_state_sessions.py+++ b/hermes_state_sessions.py@@ -725,8 +725,8 @@ class SessionSessionsMixin:keys for the TUI/Desktop, ``gateway_runtime`` for the CLI), so a later resume recombines themodel with the provider that serves it (#79536). ``base_url``/``api_mode`` are alwaysreplaced then (``None`` deletes): the previous provider's endpoint must not survive a switch,- or resume sends the new provider's model to the old host; a bare ``custom`` is stored as the- entry it ran on. Callers without provider knowledge leave the stored route untouched."""+ or resume sends the new provider's model to the old host; a bare ``custom`` is stored as its+ entry when unambiguous. Callers without provider knowledge leave the stored route untouched."""# Flush first: a still-queued pre-switch delta applied after this UPDATE would trip the# first_accounted_route overwrite and resurrect the old route.self.flush_token_counts()diff --git a/tests/gateway/test_bare_custom_route_identity.py b/tests/gateway/test_bare_custom_route_identity.pyindex 717df347530..135cc942f2e 100644--- a/tests/gateway/test_bare_custom_route_identity.py+++ b/tests/gateway/test_bare_custom_route_identity.py@@ -52,24 +52,36 @@ def test_a_disabled_sibling_serving_the_model_never_names_the_route():assert routed_custom_identity(RELAY, 'deepseek-v4.1-flash', config) == 'custom:glm'-def test_a_bare_custom_route_is_persisted_as_its_entry(home):+SPLIT_KEYS = {'providers': {name: {**entry, 'key_env': f'{name.upper()}_KEY'}+ for name, entry in SIBLINGS['providers'].items()}}+++def test_a_bare_custom_switch_resumes_on_the_key_that_served_it(home, monkeypatch):from gateway.run_turn_prepare import GatewayTurnPrepareMixin+ from hermes_cli.model_switch import switch_modelfrom hermes_state import SessionDB- (home / 'config.yaml').write_text(json.dumps(SIBLINGS))+ from tui_gateway import server+ monkeypatch.setenv('GLM_KEY', 'glm-key')+ monkeypatch.setenv('DEEPSEEK_KEY', 'deepseek-key')+ (home / 'config.yaml').write_text(json.dumps(SPLIT_KEYS))+ # A glm session (the adapter reports bare ``custom``) runs /model deepseek-v4.1-flash --provider custom.+ switched = switch_model('deepseek-v4.1-flash', 'custom', 'glm-5.3', RELAY, 'glm-key',+ explicit_provider='custom', user_providers=SPLIT_KEYS['providers'])+ assert switched.success and switched.api_key == 'glm-key', switcheddb = SessionDB(db_path=home / 'state.db')try:- for sid in ('switched', 'synced'):- db.create_session(sid, source='cli', model='glm-5.3')- # A /model switch on the gateway persists the resolved provider it got back.- db.update_session_model('switched', 'deepseek-v4.1-flash', 'custom', base_url=RELAY)- # A turn syncs the route its agent ran on, whose provider is the adapter's label.- agent = SimpleNamespace(model='deepseek-v4.1-flash', provider='custom', base_url=RELAY,- api_mode='chat_completions')- runner = SimpleNamespace(_session_db=SimpleNamespace(_db=db))- GatewayTurnPrepareMixin._sync_session_model_from_agent(runner, 'synced', agent)- stored = {sid: json.loads(db.get_session(sid)['model_config']) for sid in ('switched', 'synced')}- assert stored['switched']['provider'] == stored['switched']['gateway_runtime']['provider'] == 'custom:deepseek'- assert stored['synced']['gateway_runtime']['provider'] == 'custom:deepseek'+ db.create_session('s', source='cli', model='glm-5.3')+ db.update_session_model('s', switched.new_model, switched.target_provider, base_url=switched.base_url)+ # The next turn syncs the switched agent, whose requested provider is bare ``custom`` too.+ agent = SimpleNamespace(model=switched.new_model, provider='custom', requested_provider='custom',+ base_url=RELAY, api_mode='chat_completions')+ GatewayTurnPrepareMixin._sync_session_model_from_agent(+ SimpleNamespace(_session_db=SimpleNamespace(_db=db)), 's', agent)+ # Resume reads the stored route back and resolves its credentials.+ overrides = server._stored_session_runtime_overrides(db.get_session('s'))+ _model, runtime = server._resolve_agent_model_runtime(+ overrides['model_override'], overrides.get('provider_override'))+ assert runtime['api_key'] == 'glm-key'finally:db.close()@@ -92,6 +104,21 @@ def test_a_turn_on_a_named_entry_persists_that_entry_not_the_sibling_listing_itsdb.close()[email protected]('requested, model', [('custom:glm', 'deepseek-v4.1-flash'), ('custom:deepseek', 'glm-5.3')],+ ids=['glm-running-the-siblings-model', 'deepseek-running-the-siblings-model'])+async def test_the_model_picker_marks_the_entry_a_session_runs_on_current(home, monkeypatch, requested, model):+ from gateway import session_config+ (home / 'config.yaml').write_text(json.dumps(SIBLINGS))+ agent = SimpleNamespace(model=model, provider='custom', requested_provider=requested, base_url=RELAY)+ connection = SimpleNamespace(authority=SimpleNamespace(profile_id=str(home), agent=lambda ref: agent))+ monkeypatch.setattr(session_config, '_authorize', lambda connection, ref, params: None)+ monkeypatch.setattr('hermes_cli.inventory.build_model_options_payload',+ lambda ctx, **kwargs: {'provider': ctx.current_provider})+ result = await session_config.model_options(connection, SimpleNamespace(session_id='s'), {})+ assert result == {'provider': requested}++@pytest.mark.asyncioasync def test_a_following_session_switches_model_with_an_inline_secret_outside_its_followed_sections(home):from gateway.run_turn_prepare import GatewayTurnPrepareMixindiff --git a/tests/gateway/test_tui_session_reads.py b/tests/gateway/test_tui_session_reads.pyindex 2d4ed39a7eb..62558842972 100644--- a/tests/gateway/test_tui_session_reads.py+++ b/tests/gateway/test_tui_session_reads.py@@ -67,7 +67,8 @@ async def test_tui_status_names_the_custom_entry_a_bare_custom_agent_runs_on(ownf'providers:\n glm: {{api: "{relay}", default_model: glm-5.3}}\n'f' deepseek: {{api: "{relay}", default_model: deepseek-v4.1-flash}}\n')sid = (await owner.call('session.create', request_id='t', source='tui', cwd=str(owner.workdir)))['session_id']- agent = SimpleNamespace(model='deepseek-v4.1-flash', provider='custom', base_url=relay)+ agent = SimpleNamespace(model='deepseek-v4.1-flash', provider='custom', requested_provider='custom:deepseek',+ base_url=relay)owner.authority.runner._cached_agent_for = lambda route: agentassert 'Model: deepseek-v4.1-flash (custom:deepseek)' in await _exec(owner, sid, 'status')diff --git a/tui_gateway/methods_complete_helpers.py b/tui_gateway/methods_complete_helpers.pyindex 1a54c8944ad..9963a055897 100644--- a/tui_gateway/methods_complete_helpers.py+++ b/tui_gateway/methods_complete_helpers.py@@ -136,8 +136,9 @@ def _model_picker_context(agent):if str(provider or "").strip().lower() == "custom":try:from hermes_cli.runtime_provider import canonical_custom_identity- provider = canonical_custom_identity(- base_url=base_url or None, config_provider=ctx.current_provider, model=model or None) or provider+ requested = None if getattr(agent, "_fallback_activated", False) else getattr(agent, "requested_provider", None)+ provider = canonical_custom_identity(base_url=base_url or None, config_provider=ctx.current_provider,+ model=model or None, requested=requested) or providerexcept Exception:logger.debug("custom provider identity recovery failed (model picker)", exc_info=True)return ctx.with_overrides(