Skip to content

The agent that grows with you

refactor(gateway): build the owner WebSocket target in one helper

Teknium6b616486c158
diff --git a/agent/runtime_session_store.py b/agent/runtime_session_store.py
index c53e07a53e1..94e1ee49c88 100644
--- a/agent/runtime_session_store.py
+++ b/agent/runtime_session_store.py
@@ -51,7 +51,7 @@ class WorkerRPC:
self.endpoint = None
def __call__(self, method, **params):
- from hermes_cli.gateway_client import _session_ticket
+ from hermes_cli.gateway_client import _session_ticket, gateway_ws_target
from hermes_cli.gateway_runtime_discovery import query_identify
from websockets.sync.client import connect
try:
@@ -75,9 +75,9 @@ class WorkerRPC:
raise WorkerPersistenceError('synchronous_self_rpc')
ticket = _session_ticket(self.home, endpoint,
purpose='interactive' if method == 'worker.register' else 'worker-adoption')
- url = endpoint.api_origin.replace('https:', 'wss:').replace('http:', 'ws:') + '/api/ws'
+ url, protocols = gateway_ws_target(endpoint, ticket)
# The owner is loopback, like connect_gateway's peer: an inherited HTTPS_PROXY must not carry it.
- with connect(url, subprotocols=['hermes-gateway-v1', 'hermes-gateway-ticket.' + ticket],
+ with connect(url, subprotocols=protocols,
open_timeout=5, close_timeout=1, max_size=8 * 1024 * 1024, proxy=None) as ws:
ws.send(json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': method, 'params': params}))
import time
diff --git a/gateway/session_a2a.py b/gateway/session_a2a.py
index 243edc6cd56..651660e9c98 100644
--- a/gateway/session_a2a.py
+++ b/gateway/session_a2a.py
@@ -114,7 +114,8 @@ async def forward(connection, params):
async def forward_to_owner(home, *, agent, tenant, peer, context_id, input_id, text, timeout):
"""Transport-only caller; a timeout never cancels or re-identifies accepted work."""
- from hermes_cli.gateway_client import GatewayClient, GatewayClientError, _session_ticket
+ from hermes_cli.gateway_client import (GATEWAY_WS_PROTOCOL, GatewayClient, GatewayClientError,
+ _session_ticket, gateway_ws_target)
from hermes_cli.gateway_runtime import ensure_gateway_runtime
from websockets.asyncio.client import connect
home = await asyncio.to_thread(Path(home).resolve)
@@ -123,12 +124,11 @@ async def forward_to_owner(home, *, agent, tenant, peer, context_id, input_id, t
if ready.state != 'ready' or ready.endpoint is None:
raise GatewayClientError(f'gateway_{ready.state}:{ready.reason_code or "not_ready"}')
ticket = await asyncio.to_thread(_session_ticket, home, ready.endpoint)
- url = ready.endpoint.api_origin.replace('https:', 'wss:').replace('http:', 'ws:') + '/api/ws'
- protocols = ['hermes-gateway-v1', 'hermes-gateway-ticket.' + ticket]
+ url, protocols = gateway_ws_target(ready.endpoint, ticket)
# Loopback authority dial: never through HTTP(S)_PROXY (websockets>=14 honours it by default).
async with connect(url, subprotocols=protocols, open_timeout=10, max_size=8 * 1024 * 1024,
proxy=None) as ws:
- if ws.subprotocol != protocols[0]:
+ if ws.subprotocol != GATEWAY_WS_PROTOCOL:
raise GatewayClientError('gateway_protocol_mismatch')
async with GatewayClient(ws) as client:
params = dict(agent=agent, tenant=tenant, peer=peer, context_id=context_id, input_id=input_id, text=text)
diff --git a/hermes_cli/gateway_client.py b/hermes_cli/gateway_client.py
index 893c6a103d5..7d0b5c20858 100644
--- a/hermes_cli/gateway_client.py
+++ b/hermes_cli/gateway_client.py
@@ -8,6 +8,20 @@ import os
from pathlib import Path
import time
+# The owner's protocol name; session_contract is dependency-free (no config/plugins load).
+from gateway.session_contract import CANONICAL_GATEWAY_PROTOCOL as GATEWAY_WS_PROTOCOL
+
+GATEWAY_WS_TICKET_PREFIX = "hermes-gateway-ticket."
+
+
+def gateway_ws_target(endpoint, ticket):
+ """``(url, subprotocols)`` for dialing the owner's canonical WebSocket with a session ticket.
+
+ The owner accepts exactly one ticket subprotocol beside ``GATEWAY_WS_PROTOCOL`` and echoes the
+ latter; callers check ``ws.subprotocol == GATEWAY_WS_PROTOCOL`` after the upgrade."""
+ url = endpoint.api_origin.replace("https:", "wss:").replace("http:", "ws:") + "/api/ws"
+ return url, [GATEWAY_WS_PROTOCOL, GATEWAY_WS_TICKET_PREFIX + ticket]
+
class GatewayClientError(ValueError):
pass
@@ -131,15 +145,14 @@ async def connect_gateway():
raise GatewayClientError(f"Gateway {result.state}: {result.reason_code or 'not_ready'}{detail}")
endpoint = result.endpoint
ticket = await asyncio.to_thread(_session_ticket, home, endpoint)
- url = endpoint.api_origin.replace("https:", "wss:").replace("http:", "ws:") + "/api/ws"
- protocols = ["hermes-gateway-v1", "hermes-gateway-ticket." + ticket]
+ url, protocols = gateway_ws_target(endpoint, ticket)
try:
# The gateway is a loopback (or explicitly named) peer, never something to route through the
# user's HTTP(S) proxy; websockets>=14 reads HTTP_PROXY/HTTPS_PROXY by default and a proxy that
# cannot reach 127.0.0.1 turns every launch into a 10 s open timeout.
async with connect(url, subprotocols=protocols, open_timeout=10, max_size=8 * 1024 * 1024,
proxy=None) as ws:
- if protocols and ws.subprotocol != "hermes-gateway-v1":
+ if protocols and ws.subprotocol != GATEWAY_WS_PROTOCOL:
raise GatewayClientError("Gateway protocol mismatch; update/restart required")
async with GatewayClient(ws) as client:
yield client
diff --git a/tests/hermes_cli/test_gateway_client_ws_target.py b/tests/hermes_cli/test_gateway_client_ws_target.py
new file mode 100644
index 00000000000..16244c0c1bf
--- /dev/null
+++ b/tests/hermes_cli/test_gateway_client_ws_target.py
@@ -0,0 +1,11 @@
+"""Every owner dial (viewer, worker RPC, A2A forward, bot delivery, Ink bootstrap) builds the same target."""
+from types import SimpleNamespace
+
+from hermes_cli.gateway_client import GATEWAY_WS_PROTOCOL, gateway_ws_target
+
+
+def test_gateway_ws_target_maps_scheme_and_carries_one_ticket_protocol():
+ assert gateway_ws_target(SimpleNamespace(api_origin='http://127.0.0.1:9'), 't1') == (
+ 'ws://127.0.0.1:9/api/ws', [GATEWAY_WS_PROTOCOL, 'hermes-gateway-ticket.t1'])
+ url, protocols = gateway_ws_target(SimpleNamespace(api_origin='https://owner.local'), 't2')
+ assert url == 'wss://owner.local/api/ws' and protocols[0] == 'hermes-gateway-v1'
diff --git a/tools/bot_live_delivery.py b/tools/bot_live_delivery.py
index 65aff261a89..aa6dc26b585 100644
--- a/tools/bot_live_delivery.py
+++ b/tools/bot_live_delivery.py
@@ -65,7 +65,7 @@ def authority_delivery(home, params):
"""Call only this home's already-running authority; never start a fallback."""
import asyncio
from hermes_cli.gateway_runtime import discover_gateway_endpoint
- from hermes_cli.gateway_client import GatewayClient, _session_ticket
+ from hermes_cli.gateway_client import GATEWAY_WS_PROTOCOL, GatewayClient, _session_ticket, gateway_ws_target
from websockets.asyncio.client import connect
home = Path(home).resolve()
@@ -76,11 +76,10 @@ def authority_delivery(home, params):
raise ValueError('profile authority is not ready')
endpoint = discovery.endpoint
ticket = await asyncio.to_thread(_session_ticket, home, endpoint)
- url = endpoint.api_origin.replace('http:', 'ws:').replace('https:', 'wss:') + '/api/ws'
+ url, protocols = gateway_ws_target(endpoint, ticket)
# Loopback authority dial: never through HTTP(S)_PROXY (websockets>=14 honours it by default).
- async with connect(url, subprotocols=['hermes-gateway-v1', 'hermes-gateway-ticket.' + ticket],
- open_timeout=10, proxy=None) as ws:
- if ws.subprotocol != 'hermes-gateway-v1':
+ async with connect(url, subprotocols=protocols, open_timeout=10, proxy=None) as ws:
+ if ws.subprotocol != GATEWAY_WS_PROTOCOL:
raise ValueError('authority protocol mismatch')
async with GatewayClient(ws) as client:
return await client.rpc('bot_relay.deliver', **params)
diff --git a/ui-tui/scripts/gateway_bootstrap.py b/ui-tui/scripts/gateway_bootstrap.py
index 42d64b90b58..339d8e96459 100644
--- a/ui-tui/scripts/gateway_bootstrap.py
+++ b/ui-tui/scripts/gateway_bootstrap.py
@@ -45,8 +45,9 @@ def bootstrap(start: bool) -> dict:
or grant.get("profile_id") != endpoint.profile_id
or not isinstance(grant.get("ticket"), str)):
raise RuntimeError("gateway private bootstrap rejected")
- return {"url": endpoint.api_origin.replace("http", "ws", 1) + "/api/ws",
- "protocols": ["hermes-gateway-v1", "hermes-gateway-ticket." + grant["ticket"]],
+ from hermes_cli.gateway_client import gateway_ws_target
+ url, protocols = gateway_ws_target(endpoint, grant["ticket"])
+ return {"url": url, "protocols": protocols,
"profile_id": endpoint.profile_id, "instance_id": endpoint.instance_id}