The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): serve the connection card on the session authority
yoniebans204d6abdb682
diff --git a/gateway/local_desktop_ui.py b/gateway/local_desktop_ui.pyindex 81e13d41bf3..c93ee3c94e9 100644--- a/gateway/local_desktop_ui.py+++ b/gateway/local_desktop_ui.py@@ -22,9 +22,10 @@ execution stream, and the process sinks route by the process's ``session_key`` tsession's event stream (a background process outlives the turn that started it). The callbacksare installed per turn on the cached agent and restored with the other turn sinks.-Not bridged here: ``connection_callback`` (the manage_connections card). Its card answers through-the ``connection.respond`` RPC, which the session authority does not serve yet, so installing the-callback would show a card whose buttons go nowhere; the tool keeps its off-desktop result.+Card for ``manage_connections``: ``connection_callback`` publishes ``connection.request`` on the turn,+and each later change of an operation is published as ``connection.update`` on the session that owns+it (looked up by its session key, the route); the card answers through ``connection.respond``+(``gateway/session_connections.py``)."""from __future__ import annotations@@ -37,7 +38,8 @@ logger = logging.getLogger(__name__)# Agent attributes ``wire`` installs for one local-viewer turn (restored by ``local_viewer_events``).CALLBACK_ATTRS = ("read_terminal_callback", "read_preview_callback", "drive_preview_callback",- "read_window_below_callback", "theme_callback", "tour_callback", "setup_beat_callback")+ "read_window_below_callback", "theme_callback", "tour_callback", "setup_beat_callback",+ "connection_callback")# main: tui_gateway/agent_callbacks.py ``_read_block`` budgets and tui_gateway/server.py's preview.act ladder._TERMINAL_READ_TIMEOUT_S = 30@@ -78,6 +80,7 @@ _tour_bridge: dict[str, str] = {}_process_routes: dict[str, tuple] = {}_emitter_installed = False_process_sinks_installed = False+_connection_hook_installed = Falsedef _emit(sid, event, payload) -> None:@@ -130,6 +133,33 @@ def _install_process_sinks() -> None:_process_sinks_installed = True+def _install_connection_hook() -> None:+ """``connection.update`` for an operation opened by one of our turns, on the session that owns it+ (by session key, as for processes); any other operation keeps the hook installed before (the+ sidecar's, for its own sessions)."""+ global _connection_hook_installed+ if _connection_hook_installed:+ return+ from tools.connectors.operation import ConnectionOperation+ previous = ConnectionOperation.on_change++ def on_change(operation, change, snapshot):+ with _lock:+ route = _process_routes.get(operation.session_key)+ live = route[0].sessions.get(route[1]) if route is not None else None+ if live is None:+ if previous is not None:+ previous(operation, change, snapshot)+ return+ from tui_gateway.connector_payload import connector_ui_payload+ payload = {**snapshot, "settled": snapshot.get("settled_at") is not None, **(change or {}),+ "owner": {"type": "session", "session_id": route[1]}}+ live.event_stream.publish(route[1], connector_ui_payload(payload), event_type="connection.update")++ ConnectionOperation.on_change = staticmethod(on_change)+ _connection_hook_installed = True++def _ask_result(turn, agent, method, params, timeout):"""One structured server request; the viewer's ``result`` dict, or None when none answered."""from gateway.session_server_requests import ask_viewer_result@@ -231,6 +261,7 @@ def wire(turn, agent):try:_install_emitter()_install_process_sinks()+ _install_connection_hook()except Exception: # health: allow BLE001 -- the window bridges are optional; the turn must runlogger.warning("Desktop UI sink install failed", exc_info=True)key = str(getattr(turn._ctx, "session_id", "") or owner[1])@@ -247,6 +278,8 @@ def wire(turn, agent):agent.theme_callback = lambda payload: _theme(turn, agent, dict(payload or {}))agent.tour_callback = lambda payload: _tour(turn, agent, dict(payload or {}))agent.setup_beat_callback = lambda payload: _setup_beat(turn, agent, dict(payload or {}))+ # Fire-and-forget like main's: the tool thread waits on its own operation, the card answers by op_id.+ agent.connection_callback = lambda payload: publish("connection.request", dict(payload)) and Nonereturn key, publishdiff --git a/gateway/session_connections.py b/gateway/session_connections.pynew file mode 100644index 00000000000..c8c1d21967e--- /dev/null+++ b/gateway/session_connections.py@@ -0,0 +1,107 @@+"""The ``manage_connections`` card on the session authority: ``connection.respond``, the operation's+``status``/``wake`` and the card's Try again (``connectors.connect`` with ``reconnect``).++The operation lives in ``tools/connectors/live.py`` under the turn's session key and profile; these+handlers look it up through the live session's route, so a card can only drive its own session's+operation. Account-owned calls (the Connectors page) are not the session's and stay on the legacy+handlers (``tui_gateway/methods_connectors.py``).+"""+import asyncio+from functools import partial++from hermes_state_runtime import RuntimeStoreError++METHODS = ('connection.respond', 'connectors.operation.status', 'connectors.operation.wake', 'connectors.connect')+++def session_owned(params) -> bool:+ owner = params.get('owner') if isinstance(params, dict) else None+ return isinstance(owner, dict) and owner.get('type') == 'session'+++def handlers(connection):+ return {method: partial(_handle, connection, method) for method in METHODS}+++def _request(method, params):+ from pydantic import ValidationError+ from tui_gateway.contracts.registry import METHODS as CONTRACTS+ try:+ return CONTRACTS[method].params.model_validate(params)+ except ValidationError as exc:+ raise RuntimeStoreError('invalid_params', detail=str(exc.errors()[0].get('msg', ''))) from exc+++def _view(operation):+ from tui_gateway.connector_payload import connector_ui_payload+ snapshot = operation.snapshot()+ return connector_ui_payload({**snapshot, 'settled': snapshot.get('settled_at') is not None})+++async def _handle(connection, method, _ref, params):+ from gateway.session_busy_controls import authorize+ from gateway.session_contract import SessionRef+ from tools.connectors import live+ request = _request(method, params)+ authority = connection.authority+ ref = SessionRef(authority.profile_id, request.owner.session_id)+ if ref.session_id not in authority.sessions:+ raise RuntimeStoreError('not_found')+ authorize(connection, ref, params, 'session:control' if method != 'connectors.operation.status' else 'session:read')+ route = authority.sessions[ref.session_id].route+ if method == 'connectors.connect':+ operation = live.current(route, profile_home=authority.profile_id)+ else:+ operation = live.get(route, request.op_id, profile_home=authority.profile_id)+ if operation is None:+ raise RuntimeStoreError('unknown_operation', detail='No open connection operation for this session.')+ if method == 'connectors.operation.status':+ return _view(operation)+ if method == 'connectors.operation.wake':+ operation.wake.set()+ return {'status': 'ok'}+ if method == 'connection.respond':+ return await asyncio.to_thread(_respond, operation, request.result)+ return await asyncio.to_thread(_reissue, operation, request)+++def _respond(operation, answer):+ from tools.connectors import live+ from tools.connectors.contract import SettleReason+ from tools.connectors.operation import IllegalTransition+ from tools.connectors.run import apply_answer+ try:+ apply_answer(operation, answer.model_dump_json(exclude_none=True))+ except IllegalTransition as exc:+ raise RuntimeStoreError('invalid_answer', detail='Connection answer is invalid.') from exc+ if not operation.settled and operation.all_resolved:+ operation.settle(SettleReason.all_resolved)+ if operation.settled:+ live.close(operation)+ return {'status': 'ok', 'settled': operation.settled}+++_REISSUE_REFUSALS = {+ 'unknown_target': ('unknown_target', 'No such target on the open operation.'),+ 'mixed_kinds': ('invalid_params', 'One target kind per request.'),+ 'link_still_valid': ('link_still_valid', 'Reopen the stored link.'),+ 'settled': ('reissue_refused', 'The operation has settled.'),+ 'not_allowed': ('reissue_refused', 'This target cannot be run again.'),+}+++def _reissue(operation, request):+ from tools.connectors import run+ if not request.reconnect:+ raise RuntimeStoreError('invalid_params', field='reconnect', detail='The card only re-runs an open target.')+ # A retry naming another account must not re-mint this one.+ for name in request.connectors:+ target = operation.target(name)+ if target is not None and ((request.alias is not None and target.alias != request.alias)+ or request.connection_id not in (None, target.repair_id, target.connection_id)):+ raise RuntimeStoreError('unknown_target', detail='No such target on the open operation.')+ reason = run.reissue(operation, request.connectors)+ if reason is not None:+ refusal, detail = _REISSUE_REFUSALS.get(reason, ('reissue_refused', 'The target cannot be run again.'))+ raise RuntimeStoreError(refusal, detail=detail)+ return _view(operation)diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 1e01a6ee901..767ffddd8bb 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -219,6 +219,8 @@ class AuthorityConnection:handlers['message.react'] = partial(react, self)from gateway.session_clarify_lock import clarify_lockhandlers['clarify.lock'] = partial(clarify_lock, self)+ from gateway.session_connections import handlers as connection_handlers+ handlers.update(connection_handlers(self))from gateway.session_control_actions import controlhandlers['session.control'] = partial(control, self)return handlers@@ -288,12 +290,14 @@ class AuthorityConnection:# launch profile's config into a served secondary's session. Under a single profile# the scope is that profile's own home, so behaviour is unchanged.from gateway.session_authorities import owner_scope+ from gateway.session_connections import METHODS as CONNECTION_METHODS, session_ownedwith owner_scope(self.authority):if method in GROUP_METHODS or method == 'profiles.list':result = await dispatch_group_control(self, method, params)- elif method not in handlers:+ elif method not in handlers or (method in CONNECTION_METHODS and not session_owned(params)):# JSON-RPC's own verdict: clients key compat fallbacks on -32601, and a# 4001 'invalid_params' would read as a bad argument on a method that exists.+ # An account-owned connector call (the Connectors page) keeps its legacy handler.return {'jsonrpc': '2.0', 'id': rid, 'error': {'code': -32601, 'message': f'unknown method: {method}','data': {'reason': 'unknown_method'}}}diff --git a/tests/gateway/test_local_desktop_ui.py b/tests/gateway/test_local_desktop_ui.pyindex ffecb7b1f62..451995975a9 100644--- a/tests/gateway/test_local_desktop_ui.py+++ b/tests/gateway/test_local_desktop_ui.py@@ -51,6 +51,9 @@ def window(monkeypatch):monkeypatch.setattr(local_desktop_ui, "_process_routes", {})monkeypatch.setattr(local_desktop_ui, "_emitter_installed", False)monkeypatch.setattr(local_desktop_ui, "_process_sinks_installed", False)+ monkeypatch.setattr(local_desktop_ui, "_connection_hook_installed", False)+ from tools.connectors.operation import ConnectionOperation+ monkeypatch.setattr(ConnectionOperation, "on_change", None)monkeypatch.setattr(desktop_ui, "_emit", None)monkeypatch.setattr(process_registry, "on_output", None)monkeypatch.setattr(process_registry, "on_close", None)