Skip to content

The agent that grows with you

fix(gateway): keep an explicit built-in pick off a custom entry named like it

unsupportedpastelsc0c46640f7d7
diff --git a/gateway/session_policy.py b/gateway/session_policy.py
index 9153d29713a..47f36307666 100644
--- a/gateway/session_policy.py
+++ b/gateway/session_policy.py
@@ -420,32 +420,30 @@ def _keeps_profile_route(picked, config):
`deepinfra`, `custom:<name>` for a named entry) is the same route. A block with an endpoint
and no provider (or `auto`) already routes to `custom` there.
"""
- from gateway.session_route_identity import configured_entry_aliases, profile_route_identity, resolved_route
+ from gateway.session_route_identity import profile_route_identity, resolved_route
held_id = profile_route_identity(config)
if held_id == 'auto' or not isinstance(picked, str) or not picked.strip():
return False
- if resolved_route({'provider': picked}, config)[0] == held_id:
- return True
- # A configured entry named like a canonical built-in (`providers: deepseek`) is shadowed by
- # the built-in in raw provider resolution, so the resolver cannot see the pick as the entry
- # (#140107). The entry's own alias set can: a pick spelled with the held entry's key is that
- # entry's route, and freezing it verbatim would pin the session to the built-in instead.
- return picked.strip().lower() in configured_entry_aliases(held_id, config)
+ return resolved_route({'provider': picked}, config)[0] == held_id
-def _frozen_provider_pick(picked, config):
- """The spelling a provider pick is frozen under when it names the profile entry's own endpoint.
+def _with_entry_pick(params, config):
+ """*params* with a provider pick of the held entry's bare config key spelled as its ``custom:<key>``.
- A pick that is one of the held entry's aliases keeps that entry's ``custom:<key>`` identity:
- the raw resolver defers the bare spelling to the canonical built-in, so freezing it as-is
- would pin the session to a different provider than the entry the profile runs (#140107). Any
- other pick is frozen as it came, which is the spelling the caller asked for.
+ A configured entry keyed like a canonical built-in (`providers: deepseek`) is shadowed by the
+ built-in in raw provider resolution, so the bare spelling would route, and be frozen, as a
+ different provider than the entry the profile runs (#140107). Only the held entry's bare key
+ is that entry (Desktop's guard); its display name may be a real built-in, and a pick of that
+ built-in keeps the built-in. Every other pick stays as it came.
"""
- from gateway.session_route_identity import configured_entry_aliases, profile_route_identity
+ from gateway.session_route_identity import configured_entry_key, profile_route_identity
+ picked = params.get('provider')
+ if not isinstance(picked, str):
+ return params
identity = profile_route_identity(config)
- if identity == 'auto' or picked.strip().lower() not in configured_entry_aliases(identity, config):
- return picked
- return identity
+ if identity == 'auto' or picked.strip().lower() != (configured_entry_key(identity, config) or None):
+ return params
+ return {**params, 'provider': identity}
def _apply_launch_overrides(params, config):
@@ -453,7 +451,7 @@ def _apply_launch_overrides(params, config):
from urllib.parse import urlsplit
from hermes_cli.config import resolve_turn_limit
from hermes_constants import parse_reasoning_effort
- params = _without_auto_pick(params)
+ params = _with_entry_pick(_without_auto_pick(params), config)
picks_profile_entry = 'provider' in params and _keeps_profile_route(params['provider'], config)
if 'provider' in params and not picks_profile_entry:
model = config.setdefault('model', {})
@@ -478,10 +476,6 @@ def _apply_launch_overrides(params, config):
if (url.scheme not in {'http', 'https'} or not url.hostname
or url.username or url.password or url.query or url.fragment):
_refuse('base_url', 'must be an http(s) URL without credentials, query or fragment')
- elif picks_profile_entry:
- # The pick is the profile entry's own endpoint under another spelling: freeze the
- # entry's identity, never a spelling the runtime resolves elsewhere (#140107).
- value = _frozen_provider_pick(value, config)
config.setdefault('model', {})[key] = value
bad_flag = next((flag for flag in ('ignore_rules', 'yolo', 'checkpoints', 'accept_hooks', 'pass_session_id',
'follow_profile_config', 'cwd_explicit', 'verbose')
diff --git a/gateway/session_route_identity.py b/gateway/session_route_identity.py
index a2e0dbbc260..aa99536a515 100644
--- a/gateway/session_route_identity.py
+++ b/gateway/session_route_identity.py
@@ -34,18 +34,18 @@ def _canonical(name: str) -> str:
return canonical
-def configured_entry_aliases(identity: str, config: dict) -> frozenset[str]:
- """Every spelling the configured entry behind a route identity accepts, empty when it names none.
+def configured_entry_key(identity: str, config: dict) -> str:
+ """The bare config key of the configured entry behind a ``custom:<key>`` identity, else ``''``.
Raw provider resolution defers a bare name that is a canonical built-in to the built-in, so a
- ``providers:`` entry named ``deepseek`` is reachable only through its ``custom:`` spelling —
- the entry's own alias set is what tells its keys apart from the built-in's head-on name.
+ ``providers:`` entry keyed ``deepseek`` is reachable only through its ``custom:`` spelling. Only
+ that key names the entry: its display name may be a real built-in's slug (``name: OpenRouter``
+ on ``providers.work``), and a pick of that built-in is not this endpoint (#140107).
"""
- entry = _named_entry(str(identity or '').strip().lower(), config)
- if not entry:
- return frozenset()
- from hermes_cli.providers import custom_provider_aliases
- return custom_provider_aliases(str(entry.get('name') or ''), str(entry.get('provider_key') or ''))
+ identity = str(identity or '').strip().lower()
+ if not identity.startswith('custom:') or not _named_entry(identity, config):
+ return ''
+ return identity.split(':', 1)[1].strip()
def profile_route_identity(config: dict) -> str:
diff --git a/tests/gateway/test_session_policy_shadowed_custom_create.py b/tests/gateway/test_session_policy_shadowed_custom_create.py
index 3272676d512..70d51102d04 100644
--- a/tests/gateway/test_session_policy_shadowed_custom_create.py
+++ b/tests/gateway/test_session_policy_shadowed_custom_create.py
@@ -49,3 +49,48 @@ async def test_session_create_with_the_entrys_bare_pick_freezes_its_custom_route
finally:
await connection.close()
authority.db.close()
+
+
[email protected]('key, name, pick, frozen', [
+ # A display name that is a built-in's slug is not the entry's key: the pick is that built-in.
+ ('work', 'OpenRouter', 'openrouter', ('openrouter', None, None)),
+ ('mydeep', 'DeepSeek', 'deepseek', ('deepseek', None, None)),
+ # The held entry's own bare key is that entry, whatever its display name.
+ ('mydeep', 'DeepSeek', 'mydeep', ('custom:mydeep', 'https://private.example/v1', 'PRIVATE_ENTRY_KEY')),
+])
+async def test_only_the_held_entrys_own_key_keeps_its_route(tmp_path, monkeypatch, key, name, pick, frozen):
+ """Desktop supersedes a bare pick only when it is the default ``custom:<key>``'s own key
+ (``customDefaultSupersedesPick``). A pick that merely matches the entry's display name names a
+ real built-in, and freezing the private endpoint and its key pointer for it would send that
+ credential where the user did not pick."""
+ from gateway import run
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ from gateway.session_authority import initialize_session_authority
+ from hermes_state_local import local_receipt
+
+ for var in ('DEEPSEEK_API_KEY', 'OPENROUTER_API_KEY', 'OPENAI_API_KEY'):
+ monkeypatch.delenv(var, raising=False)
+ entry = {'name': name, 'api': 'https://private.example/v1', 'key_env': 'PRIVATE_ENTRY_KEY',
+ 'transport': 'chat_completions', 'default_model': 'private-model'}
+ config = {'platform_toolsets': {'cli': []}, 'providers': {key: entry},
+ 'model': {'default': 'private-model', 'provider': f'custom:{key}',
+ 'base_url': 'https://private.example/v1', 'key_env': 'PRIVATE_ENTRY_KEY'}}
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: json.loads(json.dumps(config)))
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,
+ _cached_agent_for=lambda route: None, _adapter_for_source=lambda source: None)
+ authority = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='first')
+ connection = AuthorityConnection(authority, object(), {'user_id': 'owner'})
+ try:
+ reply = await connection.dispatch({'id': 1, 'method': 'session.create', 'params': {
+ 'request_id': 'desktop-pick', 'source': 'gui', 'cwd': str(tmp_path),
+ 'model': 'picked-model', 'provider': pick}})
+ assert 'error' not in reply, reply
+ policy = local_receipt(authority.db, reply['result']['session_id'])['policy']
+ model = json.loads(policy['config_json'])['model']
+ assert (model.get('provider'), model.get('base_url'), model.get('key_env')) == frozen, model
+ finally:
+ await connection.close()
+ authority.db.close()