The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): bind every adapter to the runner at the _create_adapter boundary
Hudsondb639e102352
diff --git a/gateway/platform_registry.py b/gateway/platform_registry.pyindex e639bc838bd..ca818b0921c 100644--- a/gateway/platform_registry.py+++ b/gateway/platform_registry.py@@ -4,10 +4,11 @@ Platform Adapter RegistryAllows platform adapters (built-in and plugin) to self-register so the gatewaycan discover and instantiate them without hardcoded if/elif chains.-Built-in adapters continue to use the existing if/elif in _create_adapter()+Built-in adapters continue to use the existing if/elif in _instantiate_adapter()for now. Plugin adapters register here via PluginContext.register_platform()and are looked up first -- if nothing is found the gateway falls through to-the legacy code path.+the legacy code path. GatewayRunner._create_adapter() wraps both paths and+binds every successful adapter to its runner.Usage (plugin side):diff --git a/gateway/platforms/ADDING_A_PLATFORM.md b/gateway/platforms/ADDING_A_PLATFORM.mdindex 50618aa02f3..9f989133f1f 100644--- a/gateway/platforms/ADDING_A_PLATFORM.md+++ b/gateway/platforms/ADDING_A_PLATFORM.md@@ -174,7 +174,7 @@ Update `get_connected_platforms()` if your platform doesn't use token/api_key## 3. Adapter Factory (`gateway/run.py`)-Add to `_create_adapter()`:+Add to `_instantiate_adapter()`:```pythonelif platform == Platform.YOUR_PLATFORM:@@ -185,6 +185,11 @@ elif platform == Platform.YOUR_PLATFORM:return YourAdapter(config)```+`_create_adapter()` wraps this factory and binds every successful adapter to+its `GatewayRunner`. Do not construct platform adapters in lifecycle call sites;+startup and reconnect must keep using the wrapper so profile routing is wired+before `connect()`.+---## 4. Authorization Maps (`gateway/run.py`)diff --git a/gateway/run.py b/gateway/run.pyindex c1106b13502..c328ff20e20 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -17725,11 +17725,27 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewreturn hashlib.sha256(("hermes-mux:" + token).encode("utf-8")).hexdigest()[:16]def _create_adapter(- self,- platform: Platform,- config: Any+ self,+ platform: Platform,+ config: Any,) -> Optional[BasePlatformAdapter]:- """Create the appropriate adapter for a platform.+ """Create an adapter and bind it to this gateway runner.++ Every lifecycle path — primary/secondary startup and reconnect — goes+ through this method. Keep runner binding here so adapters can resolve+ inbound profile routes before handlers or ``connect()`` run.+ """+ adapter = self._instantiate_adapter(platform, config)+ if adapter is not None:+ adapter.gateway_runner = self+ return adapter++ def _instantiate_adapter(+ self,+ platform: Platform,+ config: Any,+ ) -> Optional[BasePlatformAdapter]:+ """Instantiate the appropriate adapter for a platform.Checks the platform_registry first (plugin adapters), then fallsthrough to the built-in if/elif chain for core platforms.@@ -17750,14 +17766,6 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewif platform_registry.is_registered(platform.value):adapter = platform_registry.create_adapter(platform.value, config)if adapter is not None:- # Inject a back-reference to the gateway runner so every- # adapter can (a) deliver cross-platform admin alerts and- # (b) resolve inbound profile routing through- # ``runner._profile_name_for_source``. Unconditional:- # ``BasePlatformAdapter`` declares ``gateway_runner``, so- # this reaches ALL platforms (not just the ones that- # pre-declared it), making profile routing platform-generic.- adapter.gateway_runner = selfreturn adapter# Registered but failed to instantiate — don't silently fall# through to built-ins (there are none for plugin platforms).@@ -17809,18 +17817,14 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewif not check_api_server_requirements():logger.warning("API Server: aiohttp not installed")return None- adapter = APIServerAdapter(config)- adapter.gateway_runner = self- return adapter+ return APIServerAdapter(config)elif platform == Platform.WEBHOOK:from gateway.platforms.webhook import WebhookAdapter, check_webhook_requirementsif not check_webhook_requirements():logger.warning("Webhook: aiohttp not installed")return None- adapter = WebhookAdapter(config)- adapter.gateway_runner = self # For cross-platform delivery- return adapter+ return WebhookAdapter(config)elif platform == Platform.MSGRAPH_WEBHOOK:from gateway.platforms.msgraph_webhook import (diff --git a/tests/gateway/test_profile_resolution.py b/tests/gateway/test_profile_resolution.pyindex 695b9c7b894..e79e0415cac 100644--- a/tests/gateway/test_profile_resolution.py+++ b/tests/gateway/test_profile_resolution.py@@ -248,6 +248,69 @@ class TestGatewayRunnerInjection:assert hasattr(BasePlatformAdapter, "gateway_runner")assert BasePlatformAdapter.gateway_runner is None+ def test_factory_binds_every_adapter_to_runner(self, monkeypatch):+ """``_create_adapter`` binds the runner regardless of which branch+ built the adapter (plugin registry OR built-in if/elif) — every+ lifecycle path (startup, reconnect, secondary profiles) goes through+ it, so this is the single seam that makes profile_routes reachable+ for built-ins like Signal (#68332 / #70831)."""+ from gateway.config import PlatformConfig++ runner = object.__new__(GatewayRunner)+ adapter = MagicMock(spec=BasePlatformAdapter)+ monkeypatch.setattr(runner, "_instantiate_adapter", lambda platform, config: adapter)+ assert runner._create_adapter(Platform.SIGNAL, PlatformConfig(enabled=True)) is adapter+ assert adapter.gateway_runner is runner+ monkeypatch.setattr(runner, "_instantiate_adapter", lambda platform, config: None)+ assert runner._create_adapter(Platform.SIGNAL, PlatformConfig(enabled=True)) is None++ @pytest.mark.asyncio+ async def test_real_signal_factory_routes_inbound_group_event(self, monkeypatch):+ """A factory-built (built-in) Signal adapter resolves profile_routes+ for a real inbound envelope — fails on main where the Signal branch+ returned a bare ``SignalAdapter(config)`` with no runner."""+ from gateway.config import PlatformConfig++ group_id = "test-signal-route"+ monkeypatch.setenv("SIGNAL_GROUP_ALLOWED_USERS", group_id)+ runner = object.__new__(GatewayRunner)+ runner.config = GatewayConfig(+ multiplex_profiles=True,+ profile_routes=[+ ProfileRoute(name="signal", platform="signal", profile="ops", chat_id=f"group:{group_id}"),+ ],+ )+ adapter = runner._create_adapter(+ Platform.SIGNAL,+ PlatformConfig(enabled=True, extra={"http_url": "http://127.0.0.1:18080", "account": "+15555550123"}),+ )+ assert adapter is not None and adapter.gateway_runner is runner++ captured = {}++ async def capture_event(event):+ captured["event"] = event++ adapter.handle_message = capture_event+ with patch(+ "hermes_cli.profiles.profiles_to_serve",+ return_value=[("default", Path("/profiles/default")), ("ops", Path("/profiles/ops"))],+ ):+ await adapter._handle_envelope({+ "envelope": {+ "sourceNumber": "+15555550124",+ "sourceName": "Test Operator",+ "timestamp": 1700000000000,+ "dataMessage": {+ "message": "diagnose the cluster",+ "groupInfo": {"groupId": group_id, "groupName": "US East 7"},+ },+ },+ })+ source = captured["event"].source+ assert source.profile == "ops"+ assert build_session_key(source, profile=source.profile).startswith("agent:ops:")+# A concrete adapter we can instantiate without the full platform stack.# ``build_source`` only reads ``self.platform`` and ``self.gateway_runner``, so adiff --git a/website/docs/developer-guide/adding-platform-adapters.md b/website/docs/developer-guide/adding-platform-adapters.mdindex 870c6608dd0..9572c684a56 100644--- a/website/docs/developer-guide/adding-platform-adapters.md+++ b/website/docs/developer-guide/adding-platform-adapters.md@@ -637,7 +637,7 @@ Three touchpoints:Six touchpoints:-1. **`_create_adapter()`** — Add an `elif platform == Platform.NEWPLAT:` branch+1. **`_instantiate_adapter()`** — Add an `elif platform == Platform.NEWPLAT:` branch. The `_create_adapter()` wrapper binds every successful adapter to its gateway runner.2. **`_is_user_authorized()` allowed_users map** — `Platform.NEWPLAT: "NEWPLAT_ALLOWED_USERS"`3. **`_is_user_authorized()` allow_all map** — `Platform.NEWPLAT: "NEWPLAT_ALLOW_ALL_USERS"`4. **Early env check `_any_allowlist` tuple** — Add `"NEWPLAT_ALLOWED_USERS"`diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/adding-platform-adapters.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/adding-platform-adapters.mdindex 43bd0b49fe3..b52870e8487 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/adding-platform-adapters.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/adding-platform-adapters.md@@ -537,9 +537,9 @@ await self.handle_message(event)### 4. Gateway Runner(`gateway/run.py`)-五个接触点:+六个接触点:-1. **`_create_adapter()`** — 添加 `elif platform == Platform.NEWPLAT:` 分支+1. **`_instantiate_adapter()`** — 添加 `elif platform == Platform.NEWPLAT:` 分支。`_create_adapter()` 包装器会将每个成功创建的适配器绑定到其网关运行器。2. **`_is_user_authorized()` allowed_users 映射** — `Platform.NEWPLAT: "NEWPLAT_ALLOWED_USERS"`3. **`_is_user_authorized()` allow_all 映射** — `Platform.NEWPLAT: "NEWPLAT_ALLOW_ALL_USERS"`4. **早期环境检查 `_any_allowlist` 元组** — 添加 `"NEWPLAT_ALLOWED_USERS"`