Skip to content

The agent that grows with you

fix(gateway): record the resolved custom entry; map --source desktop client-side

unsupportedpastelsc289426df031
diff --git a/agent/session_source.py b/agent/session_source.py
index 92f7b728eca..d1bd9df4d16 100644
--- a/agent/session_source.py
+++ b/agent/session_source.py
@@ -25,6 +25,12 @@ CLI_FAMILY_SOURCES = frozenset({"cli", ONESHOT_SOURCE})
ATTENDED_SOURCES = UI_TRANSPORT_SOURCES | {"cli", "acp"}
+def create_surface(source: str) -> str:
+ """The ``session.create`` label for a session source: ``desktop`` is the Desktop's platform name for
+ the ``gui`` surface (gateway.session_policy.SURFACES), which the create contract does not list."""
+ return "gui" if source == "desktop" else source
+
+
def session_source_for(platform: Optional[str]) -> str:
source = str(get_session_env("HERMES_SESSION_SOURCE", "") or "").strip()
single_query = get_session_env("HERMES_SINGLE_QUERY_SESSION", "") == "1"
diff --git a/gateway/run_turn_prepare.py b/gateway/run_turn_prepare.py
index ecf9b87a5fb..bbd6125ad25 100644
--- a/gateway/run_turn_prepare.py
+++ b/gateway/run_turn_prepare.py
@@ -277,10 +277,12 @@ class GatewayTurnPrepareMixin:
try:
db = self._session_db._db
if runtime.get("provider") == "custom":
- # The adapter's billing class is shared by every named endpoint: resume needs the entry.
+ # The adapter's billing class is shared by every named endpoint: resume needs the entry,
+ # the one the runtime resolved unless a fallback moved the turn off it.
from hermes_cli.runtime_provider_custom import routed_custom_identity_in
+ requested = None if runtime["fallback_active"] else getattr(agent, "requested_provider", None)
runtime["provider"] = routed_custom_identity_in(
- Path(db.db_path).parent, runtime.get("base_url"), model) or "custom"
+ Path(db.db_path).parent, runtime.get("base_url"), model, requested) or "custom"
row = db.get_session(session_id)
if not row:
return
diff --git a/gateway/session_policy.py b/gateway/session_policy.py
index c7c7a838fe9..a4f72db0ec0 100644
--- a/gateway/session_policy.py
+++ b/gateway/session_policy.py
@@ -89,8 +89,6 @@ _KEEP_STORED_LABEL = frozenset({'tool', 'oneshot'})
STORED_AS_LOCAL = frozenset(SURFACES) - _KEEP_STORED_LABEL
# Routing labels and the accounting placeholder: never a creating surface.
_NOT_A_SURFACE = frozenset({None, '', 'local', 'unknown'})
-# Labels only the gateway mints (session_cron, session_kanban, hosted rooms) -> agent surface.
-GATEWAY_SURFACES = {'cron': 'cron', 'kanban': 'cli', 'bot_room': 'bot_room'}
def created_surface(label):
@@ -424,13 +422,10 @@ def build_policy(params, config, *, private_secrets=None, profile_terminal=True,
if source == 'a2a':
from gateway.session_a2a import build_forward_policy
return build_forward_policy(params, config, private_secrets=private_secrets)
- # ``desktop`` is the Desktop's surface name for the ``gui`` label (SURFACE_GROUPS): one launch.
- source = 'gui' if source == 'desktop' else source
unknown = sorted(set(params) - CREATE_FIELDS)
if unknown or not isinstance(source, str) or source not in SURFACES:
- reserved = isinstance(source, str) and source in GATEWAY_SURFACES
- _refuse(f'params.{unknown[0]}' if unknown else 'source', 'unknown create field' if unknown
- else f'reserved for the gateway: {source!r}' if reserved else f'not a surface: {source!r}')
+ _refuse(f'params.{unknown[0]}' if unknown else 'source',
+ 'unknown create field' if unknown else f'not a surface: {source!r}')
bad_bypass = next((name for name in BYPASS_FIELDS if name in params and type(params[name]) is not bool), None)
if bad_bypass:
_refuse(bad_bypass, 'must be a boolean')
@@ -973,7 +968,7 @@ def restore_policy(data):
try:
policy = LocalSessionPolicy(**data)
from gateway.session_a2a import is_forward_policy
- surfaces = {**SURFACES, **GATEWAY_SURFACES}
+ surfaces = {**SURFACES, 'cron': 'cron', 'kanban': 'cli', 'bot_room': 'bot_room'}
if ((not is_forward_policy(policy) and
(policy.source not in surfaces or policy.platform != surfaces[policy.source]))
or not isinstance(policy.cwd, str) or not Path(policy.cwd).is_absolute()
diff --git a/gateway/session_tui_reads.py b/gateway/session_tui_reads.py
index 669a0820d42..26a642cdf94 100644
--- a/gateway/session_tui_reads.py
+++ b/gateway/session_tui_reads.py
@@ -52,7 +52,8 @@ def _status(authority, ref, live, policy, agent, arg) -> str:
if fields['provider'] == 'custom': # the adapter's billing class: show the entry the session runs on
from hermes_cli.runtime_provider_custom import routed_custom_identity_in
fields['provider'] = routed_custom_identity_in(
- authority.profile_id, getattr(agent, 'base_url', None) or policy.base_url, fields['model']) or 'custom'
+ authority.profile_id, getattr(agent, 'base_url', None) or policy.base_url, fields['model'],
+ getattr(agent, 'requested_provider', None)) or 'custom'
project = server._project_info_for_cwd(policy.cwd)
return '\n'.join([
'Hermes TUI Status', '', *status_lines(fields, 'session_id', 'path'),
diff --git a/hermes_cli/gateway_chat.py b/hermes_cli/gateway_chat.py
index 93ae4013d17..dc1bfab3b72 100644
--- a/hermes_cli/gateway_chat.py
+++ b/hermes_cli/gateway_chat.py
@@ -199,7 +199,8 @@ async def run_gateway_chat(args, emitter=None):
# Finite runs are stored as ``oneshot`` (hidden from human pickers, still CLI history);
# an explicit ``--source`` always wins. A remote gateway predating the label stores ``cli``.
sources = contract.get("sources", [])
- source = getattr(args, "source", None) or ("oneshot" if oneshot and "oneshot" in sources else "cli")
+ from agent.session_source import create_surface
+ source = create_surface(getattr(args, "source", None) or ("oneshot" if oneshot and "oneshot" in sources else "cli"))
if source not in sources:
raise GatewayClientError(f"Gateway does not support source {source!r}")
parameters = contract.get("parameters", [])
diff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.py
index 9a86170a4a0..44399d4eb35 100644
--- a/hermes_cli/gateway_session_store.py
+++ b/hermes_cli/gateway_session_store.py
@@ -162,11 +162,11 @@ class GatewaySessionStore:
"""``session.create`` with the launch policy (and ``title``: the owner's resolve -> create ->
title step); adopts and returns the new session id. ``record_cwd=False`` (``/new``,
``--create-if-missing``) leaves the row's cwd empty, as main's explicit creates did."""
- from agent.session_source import CLI_FAMILY_SOURCES, session_source_for
+ from agent.session_source import CLI_FAMILY_SOURCES, create_surface, session_source_for
params = _creation_policy(launch or {})
params["cwd"] = os.path.realpath(os.getenv("TERMINAL_CWD") or os.getcwd())
# Main's row label: ``cli``, ``oneshot`` for a finite -q/-Q run, or an explicit --source.
- params["source"] = session_source_for("cli")
+ params["source"] = create_surface(session_source_for("cli"))
# Main's row stamp (run_agent._launch_cwd_for_session): this process's cwd (``-w`` never
# chdirs, so the repo root), only for a CLI-family label on a local terminal backend.
local = (os.getenv("TERMINAL_ENV") or "local").strip().lower() in ("", "local")
diff --git a/hermes_cli/runtime_provider_custom.py b/hermes_cli/runtime_provider_custom.py
index 3b99217c64b..2123a85040c 100644
--- a/hermes_cli/runtime_provider_custom.py
+++ b/hermes_cli/runtime_provider_custom.py
@@ -360,10 +360,12 @@ 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) -> Optional[str]:
+ config: Optional[dict[str, Any]] = None, requested: Optional[str] = None) -> Optional[str]:
"""The configured ``custom:<name>`` entry a bare ``custom`` route (the billing class every named
- endpoint reports) ran on. Entries may share one relay base_url, so the entry also serving
- *model* beats the first one on that URL; without a URL the model alone names it."""
+ endpoint reports) ran on. The entry the runtime resolved (*requested*) is that route when it
+ sits on *base_url*: entries sharing one relay may list each other's models, so (URL, model) is
+ only 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."""
url = _route_key(base_url)
target = str(model or "").strip().lower()
if not url:
@@ -371,21 +373,25 @@ def routed_custom_identity(base_url: Optional[str] = None, model: Optional[str]
def on_url(entry: dict[str, Any]) -> bool:
return _route_key(_entry_url(entry)) == url
+ named = (_get_named_custom_provider(requested, config=config, resolve_credentials=False)
+ 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 ""))
return ((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) -> Optional[str]:
+ 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)."""
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"))
+ return routed_custom_identity(base_url, model, load_user_config_effective(Path(home) / "config.yaml"), requested)
-def _endpoint_identity(base_url: str, model: Optional[str] = None) -> Optional[str]:
+def _endpoint_identity(base_url: str, model: Optional[str] = None, 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)
+ identity = routed_custom_identity(base_url, model, requested=requested)
if identity:
return identity
# The managed server has no custom-provider config entry. Recover its menu key
@@ -398,12 +404,12 @@ def _endpoint_identity(base_url: str, model: Optional[str] = None) -> Optional[s
def canonical_custom_identity(*, base_url: Optional[str] = None, config_provider: Optional[str] = None,
- model: Optional[str] = None) -> Optional[str]:
+ model: Optional[str] = None, requested: Optional[str] = None) -> Optional[str]:
"""Recover the durable menu identity for a bare custom provider. Match a configured
endpoint first, then the ownership-checked managed server, then a configured model or
provider. Every session persistence/restore path shares this lookup."""
rp = _rp()
- identity = _endpoint_identity(base_url, model) if base_url else None
+ identity = _endpoint_identity(base_url, model, requested) if base_url else None
if identity:
return identity
identity = find_custom_provider_identity_by_model(model) if model else None
diff --git a/tests/gateway/test_bare_custom_route_identity.py b/tests/gateway/test_bare_custom_route_identity.py
index 189a29cf46c..717df347530 100644
--- a/tests/gateway/test_bare_custom_route_identity.py
+++ b/tests/gateway/test_bare_custom_route_identity.py
@@ -2,7 +2,8 @@
The gateway freezes, persists and syncs the configured ``custom:<name>`` entry it ran on: a launch
pick echoing ``custom`` back, a ``/model`` switch persisting it, and a turn syncing the adapter's
-label. Entries sharing one relay base_url are told apart by the model they serve.
+label. A turn records the entry its runtime resolved; only an unknown entry is told apart from
+siblings on one relay base_url by the model they serve.
Also: a profile-following session's model pick with an inline secret outside the followed
sections, and ``--source desktop``. No endpoint is contacted.
@@ -73,6 +74,24 @@ def test_a_bare_custom_route_is_persisted_as_its_entry(home):
db.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'])
+def test_a_turn_on_a_named_entry_persists_that_entry_not_the_sibling_listing_its_model(home, requested, model):
+ from gateway.run_turn_prepare import GatewayTurnPrepareMixin
+ from hermes_state import SessionDB
+ (home / 'config.yaml').write_text(json.dumps(SIBLINGS))
+ db = SessionDB(db_path=home / 'state.db')
+ try:
+ db.create_session('s', source='cli', model=model)
+ agent = SimpleNamespace(model=model, provider='custom', requested_provider=requested, base_url=RELAY,
+ api_mode='chat_completions')
+ GatewayTurnPrepareMixin._sync_session_model_from_agent(
+ SimpleNamespace(_session_db=SimpleNamespace(_db=db)), 's', agent)
+ assert json.loads(db.get_session('s')['model_config'])['gateway_runtime']['provider'] == requested
+ finally:
+ db.close()
+
+
@pytest.mark.asyncio
async def test_a_following_session_switches_model_with_an_inline_secret_outside_its_followed_sections(home):
from gateway.run_turn_prepare import GatewayTurnPrepareMixin
@@ -98,7 +117,18 @@ async def test_a_following_session_switches_model_with_an_inline_secret_outside_
store.close_all_db_handles()
-def test_source_desktop_launches_the_desktop_surface(tmp_path):
- from gateway.session_policy import build_policy
- policy = build_policy(dict(cwd=str(tmp_path), source='desktop'), {})
- assert (policy.source, policy.platform) == ('gui', 'desktop')
+def test_source_desktop_is_sent_as_the_gui_surface_the_create_contract_lists(monkeypatch):
+ from hermes_cli.gateway_session_store import GatewaySessionStore
+ from tui_gateway.contracts.registry import CANONICAL_METHODS, canonical_param_problems
+ monkeypatch.setenv('HERMES_SESSION_SOURCE', 'desktop')
+ monkeypatch.setenv('HERMES_SESSION_SOURCE_EXPLICIT', '1')
+ sent = {}
+
+ def call(method, **params):
+ if method == 'session.create':
+ sent.update(params)
+ return {'session_create': {'parameters': ['cwd', 'source', 'row_cwd']}, 'stored_session_id': 'sid'}
+ GatewaySessionStore(SimpleNamespace(call=call, state=lambda sid: SimpleNamespace(
+ adopt_snapshot=lambda snapshot: None))).create({})
+ assert sent['source'] == 'gui'
+ assert canonical_param_problems(CANONICAL_METHODS['session.create'], {'request_id': 'r', 'source': 'gui'}) == []
diff --git a/tests/gateway/test_session_policy.py b/tests/gateway/test_session_policy.py
index a84cec642b0..93f2baba691 100644
--- a/tests/gateway/test_session_policy.py
+++ b/tests/gateway/test_session_policy.py
@@ -143,15 +143,6 @@ def test_launch_options_are_frozen_and_validated(tmp_path):
build_policy(dict(cwd=str(tmp_path), **bad), cfg)
-def test_gateway_only_source_is_refused_by_name(tmp_path):
- from gateway.session_policy import build_policy
- from hermes_state_runtime import RuntimeStoreError
- for label in ('kanban', 'cron', 'bot_room'):
- with pytest.raises(RuntimeStoreError) as refused:
- build_policy({'source': label, 'cwd': str(tmp_path)}, {})
- assert (refused.value.field, refused.value.detail) == ('source', f'reserved for the gateway: {label!r}')
-
-
def test_provider_override_drops_the_previous_providers_route(tmp_path):
"""A provider pick is a whole-route change: folding it must not keep the profile's
endpoint/wire-protocol/credential pointers, else the new provider's key is sent to the old
diff --git a/website/docs/developer-guide/gateway-local-sessions.md b/website/docs/developer-guide/gateway-local-sessions.md
index 01c2a3930bb..f8e0fd810cb 100644
--- a/website/docs/developer-guide/gateway-local-sessions.md
+++ b/website/docs/developer-guide/gateway-local-sessions.md
@@ -87,8 +87,6 @@ listener keeps working.
(`gateway.session_policy.SURFACES`). They select the agent platforms `cli`, `tui`,
`desktop`, `acp`, `cli` and `cli`; `tool` (third-party integrations) and `oneshot`
(finite `chat -q` / `-z` runs) keep their own stored label so human pickers hide them.
- `cron`, `kanban` and `bot_room` are minted only by the gateway; a client asking for one
- is refused as `reserved for the gateway`.
The native local routing identity remains server-owned `Platform.LOCAL`; source never
grants messaging/native trust. Default TUI selection folds in `project`; GUI folds in
the client-surface toolsets (`project`, `desktop_ui`, `catalog`). GUI policy is