The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(relay): skip managed execution for empty activation
Alex Fournier68fb2e916099
diff --git a/agent/relay_runtime.py b/agent/relay_runtime.pyindex e90ea9ecb90..bea82f098eb 100644--- a/agent/relay_runtime.py+++ b/agent/relay_runtime.py@@ -147,13 +147,54 @@ def _same_handle(a: Any, b: Any) -> bool:# Process-wide plugin-configuration result shared by every currently hosted profile.-_RelayPluginConfigurationState = Enum("_RelayPluginConfigurationState", "UNINITIALIZED ACTIVE FOREIGN FAILED")+_RelayPluginConfigurationState = Enum(+ "_RelayPluginConfigurationState", "UNINITIALIZED DISABLED ACTIVE FOREIGN FAILED"+)class _RelayPluginConfigurationLoadError(RuntimeError):"""An explicitly selected Relay plugin configuration could not be loaded."""+def _activation_requires_managed_execution(activation: Any) -> bool:+ """Return whether Relay activated any static or dynamic plugin behavior.++ Relay owns the report contract. An unfamiliar report stays fail-safe by+ retaining Hermes managed execution instead of silently bypassing plugins.+ """++ def keep_enabled() -> bool:+ logger.warning(+ "Hermes could not determine whether the Relay activation is empty; keeping managed execution enabled"+ )+ return True++ try:+ report = getattr(activation, "report", None)+ except Exception:+ return keep_enabled()+ if not isinstance(report, dict):+ return keep_enabled()+ resolved = report.get("resolved_config")+ dynamic_plugins = report.get("dynamic_plugins")+ if not isinstance(resolved, dict) or not isinstance(dynamic_plugins, list):+ return keep_enabled()+ components = resolved.get("components")+ if not isinstance(components, list):+ return keep_enabled()+ if components:+ return True+ for plugin in dynamic_plugins:+ if not isinstance(plugin, dict) or "selected" not in plugin:+ return keep_enabled()+ selected = plugin["selected"]+ if not isinstance(selected, bool):+ return keep_enabled()+ if selected:+ return True+ return False++@dataclassclass RelaySession:"""One isolated Relay scope stack owned by a Hermes session."""@@ -242,7 +283,8 @@ class _ProcessRelayPluginConfiguration:def _activate(self, relay: Any) -> _RelayPluginConfigurationState:try:- self._initialize(relay)+ if not self._initialize(relay):+ return _RelayPluginConfigurationState.DISABLEDexcept Exception as exc:self._activation = Noneif _is_relay_host_conflict(exc):@@ -265,14 +307,16 @@ class _ProcessRelayPluginConfiguration:return _RelayPluginConfigurationState.FAILEDreturn None- def _initialize(self, relay: Any) -> None:- """Initialize Relay with its ambient or explicitly selected configuration."""+ def _initialize(self, relay: Any) -> bool:+ """Initialize Relay and report whether the resolved configuration needs managed execution."""config_path = _configured_plugin_inputs()# An explicit file replaces Relay's user file; its system file always remains above either source.activation = _resolve_plugin_awaitable(relay.plugin.initialize({}, additional_plugins_toml=config_path))if activation is None:raise RuntimeError("NeMo Relay plugin initialization returned no activation handle")self._activation = activation+ self._relay = relay+ return _activation_requires_managed_execution(activation)def release(self, owner: Any) -> None:"""Release one host and clear Relay after the final host exits."""diff --git a/tests/agent/test_relay_runtime_plugins.py b/tests/agent/test_relay_runtime_plugins.pyindex 5fecedf4964..d8796d1edda 100644--- a/tests/agent/test_relay_runtime_plugins.py+++ b/tests/agent/test_relay_runtime_plugins.py@@ -20,6 +20,17 @@ HOST_CONFLICT = RuntimeError("plugin initialization")+EMPTY_ACTIVATION_REPORT = {+ "config": {"diagnostics": []},+ "config_paths": [],+ "dynamic_plugins": [],+ "resolved_config": {"components": []},+}+ACTIVE_ACTIVATION_REPORT = {+ **EMPTY_ACTIVATION_REPORT,+ "resolved_config": {"components": [{"kind": "observability", "enabled": True}]},+}+class _FakeRelay:def __init__(@@ -27,10 +38,12 @@ class _FakeRelay:*,initialize_error: Exception | None = None,activation_close_error: Exception | None = None,+ activation_report: Any = ACTIVE_ACTIVATION_REPORT,) -> None:self.events: list[tuple[Any, ...]] = []self.initialize_error = initialize_errorself.activation_close_error = activation_close_error+ self.activation_report = activation_reportself.initialized_from: list[str | None] = []self.ScopeType = SimpleNamespace(Agent="agent")self.plugin = SimpleNamespace(initialize=self._initialize_plugins)@@ -58,9 +71,11 @@ class _FakeRelay:relay = selfclass _Activation:- report = {"config": {"diagnostics": []}, "dynamic_plugins": []}is_active = True+ def __init__(self) -> None:+ self.report = relay.activation_report+async def close(self) -> None:relay.events.append(("plugin.activation.close",))if relay.activation_close_error is not None:@@ -151,11 +166,46 @@ def _reset_runtime():@pytest.fixturedef explicit_static_config(tmp_path, monkeypatch):config = tmp_path / "plugins.toml"- config.write_text("", encoding="utf-8")+ config.write_text(+ "version = 1\n\n"+ "[[components]]\n"+ 'kind = "observability"\n'+ "enabled = true\n\n"+ "[components.config]\n"+ "version = 4\n",+ encoding="utf-8",+ )monkeypatch.setenv(relay_runtime.RELAY_PLUGINS_CONFIG_ENV, str(config))return config+ ("report", "expected"),+ [+ (EMPTY_ACTIVATION_REPORT, False),+ (ACTIVE_ACTIVATION_REPORT, True),+ (+ {+ **EMPTY_ACTIVATION_REPORT,+ "dynamic_plugins": [{"id": "selected", "selected": True}],+ },+ True,+ ),+ (+ {+ **EMPTY_ACTIVATION_REPORT,+ "dynamic_plugins": [{"id": "disabled", "selected": False}],+ },+ False,+ ),+ ({"config": {"diagnostics": []}}, True),+ ],+)+def test_activation_report_controls_managed_execution(report, expected):+ activation = SimpleNamespace(report=report)+ assert relay_runtime._activation_requires_managed_execution(activation) is expected++def test_unset_config_uses_relay_discovery(monkeypatch):monkeypatch.delenv(relay_runtime.RELAY_PLUGINS_CONFIG_ENV, raising=False)relay = _FakeRelay()@@ -180,6 +230,28 @@ def test_unset_config_uses_relay_discovery(monkeypatch):]+def test_empty_ambient_discovery_does_not_enable_managed_execution(monkeypatch):+ monkeypatch.delenv(relay_runtime.RELAY_PLUGINS_CONFIG_ENV, raising=False)+ relay = _FakeRelay(activation_report=EMPTY_ACTIVATION_REPORT)+ host = relay_runtime.RelayRuntime(relay=relay, profile_key="profile")++ try:+ assert not host.managed_execution_enabled()+ assert (+ host._plugin_configuration_state+ is relay_runtime._RelayPluginConfigurationState.DISABLED+ )+ assert relay.initialized_from == [None]+ assert relay.events == [("plugin.initialize", {})]+ finally:+ host.shutdown()++ assert relay.events[-2:] == [+ ("subscribers.flush_async",),+ ("plugin.activation.close",),+ ]++def test_first_profile_ambient_plugin_decision_applies_to_later_profile(tmp_path,monkeypatch,@@ -988,7 +1060,11 @@ def test_real_binding_discovers_user_and_ignores_project_config(host = relay_runtime.RelayRuntime(relay=relay, profile_key="profile")try:- assert host.managed_execution_enabled()+ assert not host.managed_execution_enabled()+ assert (+ host._plugin_configuration_state+ is relay_runtime._RelayPluginConfigurationState.DISABLED+ )report = relay_runtime._PLUGIN_CONFIGURATION._activation.reportconfig_paths = set(report["config_paths"])assert str(user_config) in config_paths@@ -1030,7 +1106,11 @@ def test_real_binding_explicit_config_replaces_user_and_ignores_project(host = relay_runtime.RelayRuntime(relay=relay, profile_key="profile")try:- assert host.managed_execution_enabled()+ assert not host.managed_execution_enabled()+ assert (+ host._plugin_configuration_state+ is relay_runtime._RelayPluginConfigurationState.DISABLED+ )report = relay_runtime._PLUGIN_CONFIGURATION._activation.reportconfig_paths = set(report["config_paths"])assert str(selected_config) in config_pathsdiff --git a/tests/conftest.py b/tests/conftest.pyindex 8312cfcf2d6..59f8b70a8b9 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -495,9 +495,10 @@ _HERMES_BEHAVIORAL_VARS = frozenset({def _hermetic_environment(tmp_path, monkeypatch):"""Blank out all credential/behavioral env vars so local and CI match.- Also redirects HERMES_HOME and XDG_CONFIG_HOME to per-test tempdirs so- code under test cannot read the developer's Hermes or Relay configuration,- and pins TZ/LANG so datetime/locale-sensitive tests are deterministic.+ Also redirects HERMES_HOME to a per-test tempdir so code that reads+ ``~/.hermes/*`` cannot touch the real one, selects an empty Relay user+ configuration, and pins TZ/LANG so datetime/locale-sensitive tests are+ deterministic."""# 1. Blank every credential-shaped env var that's currently set.for name in list(os.environ.keys()):@@ -542,9 +543,12 @@ def _hermetic_environment(tmp_path, monkeypatch):if not HOST_LOCK_DIR_AT_CONFTEST_IMPORT:monkeypatch.delenv("XDG_STATE_HOME", raising=False)monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "gateway-locks"))- fake_xdg_config_home = tmp_path / "xdg_config"- fake_xdg_config_home.mkdir()- monkeypatch.setenv("XDG_CONFIG_HOME", str(fake_xdg_config_home))+ # Relay 0.9 normally discovers the user's XDG plugins.toml. Select an empty+ # per-test user file instead so tests cannot activate a developer's plugins,+ # without changing XDG_CONFIG_HOME for unrelated Hermes code under test.+ relay_plugins = tmp_path / "relay-plugins.toml"+ relay_plugins.write_text("version = 1\n", encoding="utf-8")+ monkeypatch.setenv("HERMES_NEMO_RELAY_PLUGINS_TOML", str(relay_plugins))# Keep the subprocess-surviving isolation marker pointed at THIS test's# home (#82770): children spawned by the test inherit it by default, so# hermes_state's live-DB guard stays armed in them even when the test