The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): serve the connection card with the legacy handlers' policy, errors and resume snapshot
yoniebans756ed9c71767
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex f88164d7d94..89e4f176f1c 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -4930,6 +4930,7 @@ export interface CanonicalSnapshot {pending: CanonicalPendingAdmission[]prompts: CanonicalPendingPrompt[]info: CanonicalSnapshotInfo+ pending_connection?: ConnectionRequestPayload | null}export interface CanonicalPendingAdmission {admission_id: stringdiff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 710a68ce406..bfaccd5abb6 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -10595,6 +10595,17 @@},"info": {"$ref": "#/components/schemas/CanonicalSnapshotInfo"+ },+ "pending_connection": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/ConnectionRequestPayload"+ },+ {+ "type": "null"+ }+ ],+ "default": null}},"required": [diff --git a/gateway/local_desktop_ui.py b/gateway/local_desktop_ui.pyindex c93ee3c94e9..75ca1d38129 100644--- a/gateway/local_desktop_ui.py+++ b/gateway/local_desktop_ui.py@@ -80,7 +80,6 @@ _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:@@ -134,20 +133,18 @@ def _install_process_sinks() -> None: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+ """``connection.update`` for an operation opened by one of our turns, on the session that owns it (same session key and profile, as the sidecar matches its own); any other operation goes to the hook this one wraps (the sidecar's, for its own sessions). Re-wraps whenever another hook replaced it, so install order does not matter."""from tools.connectors.operation import ConnectionOperationprevious = ConnectionOperation.on_change+ if getattr(previous, "_local_desktop_ui", False):+ returndef on_change(operation, change, snapshot):+ from hermes_constants import hermes_home_keywith _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 live is None or hermes_home_key(route[0].profile_id) != operation.profile_key:if previous is not None:previous(operation, change, snapshot)return@@ -156,8 +153,8 @@ def _install_connection_hook() -> None:"owner": {"type": "session", "session_id": route[1]}}live.event_stream.publish(route[1], connector_ui_payload(payload), event_type="connection.update")+ on_change._local_desktop_ui = TrueConnectionOperation.on_change = staticmethod(on_change)- _connection_hook_installed = Truedef _ask_result(turn, agent, method, params, timeout):diff --git a/gateway/session_connections.py b/gateway/session_connections.pyindex c8c1d21967e..196d17ed7e2 100644--- a/gateway/session_connections.py+++ b/gateway/session_connections.py@@ -1,10 +1,6 @@-"""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 ``manage_connections`` card on the session authority: ``connection.respond``, the operation's ``status``/``wake`` and the card's Try again (``connectors.connect`` with ``reconnect``), plus the open card a resume restores (``pending_connection``).-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``).+The operation lives in ``tools/connectors/live.py`` under the turn's session key (the live session's route) and profile, 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``). Refusals keep that file's error shape (``ConnectorRefusal``)."""import asynciofrom functools import partial@@ -13,6 +9,22 @@ from hermes_state_runtime import RuntimeStoreErrorMETHODS = ('connection.respond', 'connectors.operation.status', 'connectors.operation.wake', 'connectors.connect')+_REISSUE_REFUSALS = {+ 'unknown_target': (4004, 'UNKNOWN_TARGET', 'No such target on the open operation.'),+ 'mixed_kinds': (4000, 'INVALID_PARAMS', 'One target kind per request.'),+ 'link_still_valid': (4002, 'LINK_STILL_VALID', 'Reopen the stored link.'),+ 'settled': (4002, 'REISSUE_REFUSED', 'The operation has settled.'),+ 'not_allowed': (4002, 'REISSUE_REFUSED', 'This target cannot be run again.'),+}+++class ConnectorRefusal(RuntimeStoreError):+ """A refusal on the legacy connector handlers' wire shape: their code, their human message, their ``ConnectorErrorReason`` as ``data.reason``."""++ def __init__(self, code, reason, message):+ super().__init__(reason, detail=message)+ self.wire_code, self.wire_message = code, message+def session_owned(params) -> bool:owner = params.get('owner') if isinstance(params, dict) else None@@ -23,13 +35,20 @@ def handlers(connection):return {method: partial(_handle, connection, method) for method in METHODS}+def pending_connection(authority, session_id):+ """The open operation of a live session as its ``connection.request`` payload, or None."""+ from tools.connectors import live+ operation = live.current(authority.sessions[session_id].route, profile_home=authority.profile_id)+ return operation.request_payload() if operation is not None else None++def _request(method, params):from pydantic import ValidationErrorfrom tui_gateway.contracts.registry import METHODS as CONTRACTStry:return CONTRACTS[method].params.model_validate(params)except ValidationError as exc:- raise RuntimeStoreError('invalid_params', detail=str(exc.errors()[0].get('msg', ''))) from exc+ raise ConnectorRefusal(4000, 'INVALID_PARAMS', 'Connector parameters are invalid.') from excdef _view(operation):@@ -45,16 +64,17 @@ async def _handle(connection, method, _ref, params):request = _request(method, params)authority = connection.authorityref = SessionRef(authority.profile_id, request.owner.session_id)+ # Capability before existence, as every authority verb: a refused caller learns nothing about the id.+ authorize(connection, ref, params, 'session:read' if method == 'connectors.operation.status' else 'session:control')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].routeif 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.')+ raise ConnectorRefusal(4004, 'UNKNOWN_OPERATION', 'No open operation with that op_id.')if method == 'connectors.operation.status':return _view(operation)if method == 'connectors.operation.wake':@@ -62,7 +82,7 @@ async def _handle(connection, method, _ref, params):return {'status': 'ok'}if method == 'connection.respond':return await asyncio.to_thread(_respond, operation, request.result)- return await asyncio.to_thread(_reissue, operation, request)+ return await asyncio.to_thread(_retry, authority, ref, operation, request)def _respond(operation, answer):@@ -73,7 +93,7 @@ def _respond(operation, 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+ raise ConnectorRefusal(4002, 'INVALID_ANSWER', 'Connection answer is invalid.') from excif not operation.settled and operation.all_resolved:operation.settle(SettleReason.all_resolved)if operation.settled:@@ -81,27 +101,74 @@ def _respond(operation, answer):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+def _retry(authority, ref, operation, request):+ """The card's Try again, under the session's own context, as the sidecar ran it for its session."""+ from tools.connectors.gateway.errors import GatewayAuthErrorif 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.+ raise ConnectorRefusal(4000, 'INVALID_PARAMS', 'Connector parameters are invalid.')for name in request.connectors:target = operation.target(name)+ # A retry naming another account must not re-mint this one.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)+ raise ConnectorRefusal(4004, 'UNKNOWN_TARGET', 'No such target on the open operation.')+ with _session_context(authority, ref):+ _require_connectors(authority, ref)+ try:+ reason = _reissue(operation, request.connectors)+ except RuntimeStoreError:+ raise+ except GatewayAuthError as exc:+ raise _auth_refusal(exc) from exc+ except Exception as exc: # health: allow BLE001 -- the sidecar's _connector_guard: one named failure+ raise ConnectorRefusal(5034, 'CONNECTOR_REQUEST_FAILED', 'Connector request failed. Try again explicitly.') from excif reason is not None:- refusal, detail = _REISSUE_REFUSALS.get(reason, ('reissue_refused', 'The target cannot be run again.'))- raise RuntimeStoreError(refusal, detail=detail)+ raise ConnectorRefusal(*_REISSUE_REFUSALS.get(reason, (4002, 'REISSUE_REFUSED', 'The target cannot be run again.')))return _view(operation)+++def _reissue(operation, names):+ from tools.connectors import run+ return run.reissue(operation, names)+++def _auth_refusal(exc):+ if exc.code in {'no_access', 'ORG_ACCESS_DENIED'}:+ return ConnectorRefusal(4030, 'ORG_ACCESS_DENIED', 'This account cannot manage connectors for this organization.')+ if exc.status == 401 or exc.code in {'invalid_token', 'INVALID_TOKEN', 'NO_TOKEN'}:+ return ConnectorRefusal(4032, 'NEEDS_NOUS_AUTH', 'Sign in to use connectors.')+ return ConnectorRefusal(4030, 'FORBIDDEN_SCOPE', 'Connector access is not permitted for this account.')+++def _require_connectors(authority, ref):+ """The sidecar's ``_session_connector_gate``: connectors on, and ``manage_connections`` in the session's tools."""+ import model_tools+ from tools.connectors import connectors_available+ enabled, disabled = _session_toolsets(authority, ref)+ if 'manage_connections' not in model_tools._select_tool_names(enabled, disabled, quiet_mode=True) or not connectors_available():+ raise ConnectorRefusal(4031, 'CONNECTORS_UNAVAILABLE', 'Connectors are not available in this session.')+++def _session_toolsets(authority, ref):+ agent = authority.agent(ref)+ if agent is not None:+ return getattr(agent, 'enabled_toolsets', None), getattr(agent, 'disabled_toolsets', None)+ from agent.skill_utils import parse_config_string_list+ from gateway.session_policy import policy_for_source+ from toolsets import session_disabled_toolsets+ policy = policy_for_source(authority.runner, authority.sessions[ref.session_id].source)+ config = policy.config(authority, secrets=False) if policy is not None else {}+ enabled = list(policy.current_toolsets(config)) if policy is not None else None+ disabled = session_disabled_toolsets(parse_config_string_list((config.get('agent') or {}).get('disabled_toolsets')) or None,+ policy.platform if policy is not None else 'cli')+ return enabled, disabled+++def _session_context(authority, ref):+ """The session vars a turn of this session binds (``GatewayRunner._session_env_scope``), so a re-mint carries the turn's caller identity and session key."""+ from gateway.session import SessionContext+ from gateway.session_ancillary import physical_target+ live = authority.sessions[ref.session_id]+ context = SessionContext(source=live.source, connected_platforms=[], home_channels={},+ session_key=live.route, session_id=physical_target(authority, ref))+ return authority.runner._session_env_scope(context)diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 767ffddd8bb..d5d606e5ea9 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -311,8 +311,10 @@ class AuthorityConnection:return {'jsonrpc': '2.0', 'id': rid, 'result': result}except RuntimeStoreError as exc:_log_refusal(getattr(self.actor, 'profile_id', None), method, exc)+ # A connector refusal keeps the legacy handlers' code and message (gateway/session_connections.py).return {'jsonrpc': '2.0', 'id': rid, 'error': {- 'code': 4001, 'message': exc.reason, 'data': _refusal_data(exc)}}+ 'code': getattr(exc, 'wire_code', 4001), 'message': getattr(exc, 'wire_message', exc.reason),+ 'data': _refusal_data(exc)}}except sqlite3.Error as exc:_log_storage_failure(getattr(self.actor, 'profile_id', None), method,params.get('session_id'), exc)@@ -614,6 +616,7 @@ class AuthorityConnection:from gateway.session_policy import policy_for_source, refresh_profile_hooksawait asyncio.to_thread(refresh_profile_hooks, policy_for_source(self.authority.runner, source))info = await snapshot_info(self.authority, snapshot.handle.ref)+ from gateway.session_connections import pending_connectiondisplay = {}if params.get('display_projection'):display['display_messages'] = display_projection(snapshot.history, self.authority.profile_id)@@ -625,7 +628,8 @@ class AuthorityConnection:'subscription_id': snapshot.subscription_id, 'revision': snapshot.handle.revision,'execution_generation': snapshot.handle.execution_generation,'pending': [asdict(r) for r in snapshot.pending],- 'prompts': list(snapshot.prompts), 'info': info}+ 'prompts': list(snapshot.prompts), 'info': info,+ 'pending_connection': pending_connection(self.authority, ref.session_id)}def _spawn_notice(self, ref):"""Low-disk auto-prune question for this viewer, off the resume reply's path."""diff --git a/tests/gateway/test_session_resume_compression_tip.py b/tests/gateway/test_session_resume_compression_tip.pyindex 7713f1b819a..baa8d21c73e 100644--- a/tests/gateway/test_session_resume_compression_tip.py+++ b/tests/gateway/test_session_resume_compression_tip.py@@ -50,7 +50,7 @@ async def test_session_resume_still_remaps_legacy_cli_source(monkeypatch):} if sid == tip_id else None,get_compression_tip=lambda sid: tip_id,),- sessions={owner_id: SimpleNamespace(source=SimpleNamespace(platform=None))},+ sessions={owner_id: SimpleNamespace(source=SimpleNamespace(platform=None), route=f'agent:main:cli:dm:{owner_id}')},authorize=lambda *a, **k: None,attach=AsyncMock(return_value=_attach_snapshot(owner_ref)),)diff --git a/tui_gateway/contracts/canonical_sessions.py b/tui_gateway/contracts/canonical_sessions.pyindex 525dc0c2755..3f49293e79e 100644--- a/tui_gateway/contracts/canonical_sessions.py+++ b/tui_gateway/contracts/canonical_sessions.py@@ -6,6 +6,7 @@ from typing import Literalfrom .base import JsonValue, Params, Resultfrom .common import ProfileParams, TranscriptMessage+from .connectors_operation import ConnectionRequestPayloadfrom .canonical import AdmissionStatus, CanonicalSessionRef, PromptResponseResult, SessionInventoryFieldsfrom .registry import canonical_method@@ -146,6 +147,8 @@ class CanonicalSnapshot(Result):pending: list[CanonicalPendingAdmission]prompts: list[CanonicalPendingPrompt]info: CanonicalSnapshotInfo+ # The open ``manage_connections`` card, so a resume restores it while the tool waits.+ pending_connection: ConnectionRequestPayload | None = Noneclass CanonicalListParams(ProfileParams):