Skip to content

The agent that grows with you

feat(relay): initialize discovered plugin components

Bryan Bednarskic4ae7f7a3bde
diff --git a/agent/relay_runtime.py b/agent/relay_runtime.py
index 003213d87d2..1fecec69be0 100644
--- a/agent/relay_runtime.py
+++ b/agent/relay_runtime.py
@@ -24,6 +24,7 @@ LOGICAL_LLM_SCOPE = "hermes.logical_llm_call"
RUNTIME_SCHEMA_KEY = "hermes.relay.schema_version"
RUNTIME_SCHEMA_VERSION = "hermes.relay.runtime.v1"
RUNTIME_INSTANCE_KEY = "hermes.relay.runtime_instance"
+RELAY_PLUGINS_EXECUTION_CONSUMER = "hermes.nemo_relay.plugins"
_PROFILE_KEY_CACHE: dict[str, str] = {}
# Bound for native scope lifecycle operations (push/pop/flush) that gate
@@ -199,8 +200,99 @@ def _reset_segments_config_for_tests() -> None:
_SEGMENTS_CONFIG = None
+class _ProcessRelayPluginConfiguration:
+ """Own one Relay plugin configuration across profile-scoped hosts."""
+
+ def __init__(self) -> None:
+ self._lock = threading.RLock()
+ self._owners: set[int] = set()
+ self._active = False
+ self._relay: Any = None
+
+ def acquire(self, owner: Any, relay: Any) -> bool:
+ """Join the process configuration, initializing it for the first host."""
+ owner_id = id(owner)
+ with self._lock:
+ if owner_id in self._owners:
+ return self._active
+ if self._owners:
+ self._owners.add(owner_id)
+ return self._active
+
+ self._owners.add(owner_id)
+ try:
+ plugin_mod = getattr(relay, "plugin", None)
+ initialize = getattr(plugin_mod, "initialize", None)
+ if not callable(initialize):
+ raise RuntimeError(
+ "installed NeMo Relay binding does not expose "
+ "plugin.initialize"
+ )
+ # An empty override delegates file discovery and layering to
+ # Relay: /etc, the nearest .nemo-relay/plugins.toml, then the
+ # user configuration directory.
+ _resolve_plugin_awaitable(initialize({}))
+ except Exception as exc:
+ logger.warning(
+ "Hermes Relay plugin initialization failed: %s",
+ exc,
+ exc_info=True,
+ )
+ return False
+
+ self._active = True
+ self._relay = relay
+ return True
+
+ def release(self, owner: Any) -> None:
+ """Release one host and clear Relay after the final host exits."""
+ owner_id = id(owner)
+ with self._lock:
+ if owner_id not in self._owners:
+ return
+ self._owners.remove(owner_id)
+ if self._owners:
+ return
+ self._clear_active()
+
+ def reset_for_tests(self) -> None:
+ """Clear process-global state left by directly constructed test hosts."""
+ with self._lock:
+ self._owners.clear()
+ self._clear_active()
+
+ def _clear_active(self) -> None:
+ relay = self._relay
+ active = self._active
+ self._active = False
+ self._relay = None
+ if not active or relay is None:
+ return
+ try:
+ flush = getattr(getattr(relay, "subscribers", None), "flush", None)
+ if callable(flush):
+ flush()
+ except Exception:
+ logger.warning(
+ "Hermes Relay plugin subscriber flush failed",
+ exc_info=True,
+ )
+ try:
+ clear = getattr(getattr(relay, "plugin", None), "clear", None)
+ if callable(clear):
+ _resolve_plugin_awaitable(clear())
+ except Exception:
+ logger.warning(
+ "Hermes Relay plugin configuration cleanup failed",
+ exc_info=True,
+ )
+
+
+_PLUGIN_CONFIGURATION = _ProcessRelayPluginConfiguration()
+
+
class RelayRuntime:
- """Own Relay session scopes independently of any exporter or plugin."""
+ """Own Relay session scopes and optional process plugin configuration."""
def __init__(self, relay: Any = None, *, profile_key: str | None = None) -> None:
self.relay = relay or _load_nemo_relay()
@@ -212,6 +304,9 @@ class RelayRuntime:
self._subagent_parent_handles: dict[str, Any] = {}
self._execution_consumers_lock = threading.RLock()
self._execution_consumers: set[str] = set()
+ self._plugin_configuration_registered = True
+ if _PLUGIN_CONFIGURATION.acquire(self, self.relay):
+ self.retain_managed_execution(RELAY_PLUGINS_EXECUTION_CONSUMER)
self._shutdown_registered = True
atexit.register(self.shutdown)
@@ -771,11 +866,15 @@ class RelayRuntime:
)
def shutdown(self) -> None:
- """Close all core-owned Relay session scopes."""
+ """Close core scopes and release process plugin configuration."""
with self._sessions_lock:
session_ids = list(self._sessions)
for session_id in session_ids:
self._safe(self.close_session, {"session_id": session_id})
+ if self._plugin_configuration_registered:
+ self.release_managed_execution(RELAY_PLUGINS_EXECUTION_CONSUMER)
+ _PLUGIN_CONFIGURATION.release(self)
+ self._plugin_configuration_registered = False
if self._shutdown_registered:
try:
atexit.unregister(self.shutdown)
@@ -1611,6 +1710,36 @@ def _load_nemo_relay() -> Any:
return importlib.import_module("nemo_relay")
+def _resolve_plugin_awaitable(value: Any) -> Any:
+ """Resolve Relay's async plugin API from synchronous host construction."""
+ if not inspect.isawaitable(value):
+ return value
+ try:
+ asyncio.get_running_loop()
+ except RuntimeError:
+ return asyncio.run(value)
+
+ result: dict[str, Any] = {}
+ error: dict[str, BaseException] = {}
+
+ def _runner() -> None:
+ try:
+ result["value"] = asyncio.run(value)
+ except BaseException as exc: # pragma: no cover - re-raised below
+ error["exc"] = exc
+
+ thread = threading.Thread(
+ target=_runner,
+ name="hermes-nemo-relay-plugin-init",
+ daemon=True,
+ )
+ thread.start()
+ thread.join()
+ if "exc" in error:
+ raise error["exc"]
+ return result.get("value")
+
+
def _session_id(event: dict[str, Any]) -> str:
return str(event.get("session_id") or "")
@@ -1619,4 +1748,5 @@ def _reset_for_tests() -> None:
"""Reset all profile-scoped Relay hosts for isolated tests."""
SESSION_COORDINATOR._reset_active_turns_for_tests()
HOST_REGISTRY.shutdown_all()
+ _PLUGIN_CONFIGURATION.reset_for_tests()
_PROFILE_KEY_CACHE.clear()
diff --git a/tests/agent/test_relay_runtime_plugins.py b/tests/agent/test_relay_runtime_plugins.py
new file mode 100644
index 00000000000..a4ed126082c
--- /dev/null
+++ b/tests/agent/test_relay_runtime_plugins.py
@@ -0,0 +1,253 @@
+"""Tests for native NeMo Relay plugin configuration ownership."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from agent import relay_runtime
+
+
+class _FakeRelay:
+ def __init__(self, *, initialize_error: Exception | None = None) -> None:
+ self.events: list[tuple[Any, ...]] = []
+ self.initialize_error = initialize_error
+ self.ScopeType = SimpleNamespace(Agent="agent")
+ self.plugin = SimpleNamespace(
+ initialize=self._initialize_plugins,
+ clear=self._clear_plugins,
+ )
+ self.scope = SimpleNamespace(
+ push=self._scope_push,
+ pop=self._scope_pop,
+ )
+ self.subscribers = SimpleNamespace(flush=self._flush)
+
+ def get_scope_stack(self) -> None:
+ return None
+
+ async def _initialize_plugins(self, config: dict[str, Any]) -> dict[str, Any]:
+ self.events.append(("plugin.initialize", config))
+ if self.initialize_error is not None:
+ raise self.initialize_error
+ return {"diagnostics": []}
+
+ def _clear_plugins(self) -> None:
+ self.events.append(("plugin.clear",))
+
+ def _scope_push(self, name: str, scope_type: Any, **kwargs: Any) -> Any:
+ handle = ("scope", name, len(self.events))
+ self.events.append(("scope.push", name, scope_type, kwargs))
+ return handle
+
+ def _scope_pop(self, handle: Any, **kwargs: Any) -> None:
+ self.events.append(("scope.pop", handle, kwargs))
+
+ def _flush(self) -> None:
+ self.events.append(("subscribers.flush",))
+
+
[email protected](autouse=True)
+def _reset_runtime():
+ relay_runtime._reset_for_tests()
+ yield
+ relay_runtime._reset_for_tests()
+
+
+def test_relay_discovers_plugins_before_first_session_scope():
+ relay = _FakeRelay()
+ host = relay_runtime.RelayRuntime(relay=relay, profile_key="profile")
+
+ try:
+ assert host.managed_execution_enabled()
+ host.ensure_session({"session_id": "session"})
+ assert relay.events[0] == ("plugin.initialize", {})
+ assert relay.events[1][0:2] == ("scope.push", relay_runtime.SESSION_SCOPE)
+ finally:
+ host.shutdown()
+
+
+def test_initialization_failure_is_fail_open(caplog):
+ relay = _FakeRelay(initialize_error=RuntimeError("rejected config"))
+
+ with caplog.at_level("WARNING"):
+ host = relay_runtime.RelayRuntime(relay=relay, profile_key="profile")
+
+ try:
+ assert not host.managed_execution_enabled()
+ assert "Hermes Relay plugin initialization failed" in caplog.text
+ finally:
+ host.shutdown()
+
+
+def test_missing_initialize_api_is_fail_open(caplog):
+ relay = _FakeRelay()
+ del relay.plugin.initialize
+
+ with caplog.at_level("WARNING"):
+ host = relay_runtime.RelayRuntime(relay=relay, profile_key="profile")
+
+ try:
+ assert not host.managed_execution_enabled()
+ assert "does not expose plugin.initialize" in caplog.text
+ finally:
+ host.shutdown()
+
+
+def test_two_profile_hosts_initialize_once_and_clear_after_final_shutdown():
+ relay = _FakeRelay()
+ host_a = relay_runtime.RelayRuntime(relay=relay, profile_key="profile-a")
+ host_b = relay_runtime.RelayRuntime(relay=relay, profile_key="profile-b")
+
+ assert relay.events == [("plugin.initialize", {})]
+ assert host_a.managed_execution_enabled()
+ assert host_b.managed_execution_enabled()
+ host_b.ensure_session({"session_id": "profile-b-session"})
+
+ host_a.shutdown()
+ assert ("plugin.clear",) not in relay.events
+
+ host_b.shutdown()
+ assert relay.events[-2:] == [
+ ("subscribers.flush",),
+ ("plugin.clear",),
+ ]
+ assert relay.events.count(("plugin.initialize", {})) == 1
+ assert relay.events.count(("plugin.clear",)) == 1
+ pop_index = next(
+ index for index, event in enumerate(relay.events) if event[0] == "scope.pop"
+ )
+ assert pop_index < relay.events.index(("plugin.clear",))
+
+
+def test_plugin_initialization_inside_running_event_loop():
+ relay = _FakeRelay()
+
+ async def construct_host() -> relay_runtime.RelayRuntime:
+ return relay_runtime.RelayRuntime(relay=relay, profile_key="profile")
+
+ host = asyncio.run(construct_host())
+ try:
+ assert relay.events == [("plugin.initialize", {})]
+ assert host.managed_execution_enabled()
+ finally:
+ host.shutdown()
+
+
+def test_real_binding_discovers_project_config_and_exports_native_activity(
+ tmp_path,
+ monkeypatch,
+):
+ relay = pytest.importorskip("nemo_relay")
+ if getattr(relay, "_native", None) is None:
+ pytest.skip("NeMo Relay native binding is unavailable on this platform")
+ from agent import relay_llm, relay_tools
+
+ project_root = tmp_path / "project"
+ working_directory = project_root / "workspace"
+ config_directory = project_root / ".nemo-relay"
+ atof_dir = tmp_path / "atof"
+ atif_dir = tmp_path / "atif"
+ working_directory.mkdir(parents=True)
+ config_directory.mkdir()
+ (config_directory / "plugins.toml").write_text(
+ f"""
+version = 1
+
+[[components]]
+kind = "observability"
+enabled = true
+
+[components.config]
+version = 2
+
+[components.config.atof]
+enabled = true
+
+[[components.config.atof.sinks]]
+type = "file"
+output_directory = "{atof_dir}"
+filename = "events.jsonl"
+mode = "overwrite"
+
+[components.config.atif]
+enabled = true
+output_directory = "{atif_dir}"
+filename_template = "trajectory-{{session_id}}.json"
+agent_name = "Hermes Native Test"
+agent_version = "test"
+""".strip(),
+ encoding="utf-8",
+ )
+ xdg_config_home = tmp_path / "xdg"
+ xdg_config_home.mkdir()
+ monkeypatch.chdir(working_directory)
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(xdg_config_home))
+ monkeypatch.setattr(relay_runtime, "_load_nemo_relay", lambda: relay)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "profile"))
+ relay.plugin.clear()
+
+ profile_key = relay_runtime.current_profile_key()
+ lease = relay_runtime.SESSION_COORDINATOR.acquire_conversation(
+ profile_key=profile_key,
+ session_id="native-export",
+ platform="cli",
+ model="test-model",
+ )
+ turn = relay_runtime.SESSION_COORDINATOR.begin_turn(
+ lease,
+ turn_id="turn-1",
+ task_id="task-1",
+ )
+ try:
+ assert lease.host.managed_execution_enabled()
+ relay_llm.execute(
+ {"model": "test-model", "messages": []},
+ lambda _request: {
+ "id": "response-1",
+ "model": "test-model",
+ "choices": [
+ {
+ "message": {"role": "assistant", "content": "ok"},
+ "finish_reason": "stop",
+ }
+ ],
+ },
+ session_id="native-export",
+ name="test-provider",
+ model_name="test-model",
+ metadata={
+ "api_mode": "chat_completions",
+ "api_request_id": "request-1",
+ },
+ )
+ relay_tools.execute(
+ "terminal",
+ {"command": "true"},
+ lambda _args: {"output": "ok"},
+ session_id="native-export",
+ metadata={"tool_call_id": "tool-1"},
+ )
+ finally:
+ relay_runtime.SESSION_COORDINATOR.end_turn(turn, outcome="success")
+ relay_runtime.SESSION_COORDINATOR.release_conversation(lease)
+ relay_runtime.SESSION_COORDINATOR.finalize_conversation(
+ profile_key=profile_key,
+ session_id="native-export",
+ )
+ relay_runtime._reset_for_tests()
+
+ assert (atof_dir / "events.jsonl").is_file()
+ trajectories = list(atif_dir.glob("trajectory-*.json"))
+ assert len(trajectories) == 1
+ trajectory = json.loads(trajectories[0].read_text(encoding="utf-8"))
+ observed_categories = {
+ event["category"]
+ for event in trajectory["extra"]["observed_events"]
+ if event["kind"] == "scope"
+ }
+ assert {"agent", "llm", "tool"} <= observed_categories
diff --git a/tests/agent/test_relay_tools.py b/tests/agent/test_relay_tools.py
index 90e88d4d95e..22dec2fe524 100644
--- a/tests/agent/test_relay_tools.py
+++ b/tests/agent/test_relay_tools.py
@@ -43,6 +43,9 @@ def test_tool_adapter_bypasses_relay_without_an_active_consumer(
runtime = relay_runtime.get_runtime()
assert runtime is not None
runtime.release_managed_execution("test.relay_tools")
+ runtime.release_managed_execution(
+ relay_runtime.RELAY_PLUGINS_EXECUTION_CONSUMER
+ )
args = {"command": "pwd"}
monkeypatch.setattr(
@@ -137,4 +140,3 @@ def test_tool_error_is_preserved_from_relay_wrapper_suffix(relay_turn, monkeypat
-