The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(relay): include cwd in session and turn scopes
Alex Fournier6cc7d54e1ad6
diff --git a/agent/relay_cwd.py b/agent/relay_cwd.pynew file mode 100644index 00000000000..63e978b472d--- /dev/null+++ b/agent/relay_cwd.py@@ -0,0 +1,88 @@+"""Resolve logical working directories for Hermes-owned Relay scopes."""++from __future__ import annotations++import logging+from typing import Any++logger = logging.getLogger(__name__)++_CWD_SENTINELS = frozenset({"", ".", "./", "auto", "cwd"})+++def _clean_cwd(value: Any) -> str:+ if not isinstance(value, str):+ return ""+ value = value.strip()+ return "" if value.lower() in _CWD_SENTINELS else value+++def _recorded_cwd(key: str) -> str:+ if not key:+ return ""+ from tools.terminal_tool import get_session_cwd++ return _clean_cwd(get_session_cwd(key))+++def resolve_relay_scope_cwds(+ agent: Any, task_id: str, session_id: str, platform: str+) -> tuple[str, str]:+ """Return logical ``(session_cwd, turn_cwd)`` for Relay scope input.++ A task may use a worktree distinct from its owning session. Preserve remote paths as+ declared and omit unknown paths instead of substituting the Hermes host's cwd.+ """+ try:+ task_cwd = _recorded_cwd(task_id)+ except Exception:+ logger.debug("Unable to read the Relay turn cwd", exc_info=True)+ task_cwd = ""++ session_cwd = ""+ try:+ from agent.runtime_cwd import scoped_session_cwd++ session_cwd = _clean_cwd(scoped_session_cwd())+ except Exception:+ logger.debug("Unable to read the scoped Relay session cwd", exc_info=True)++ if not session_cwd:+ try:+ from gateway.session_context import get_session_env++ session_key = get_session_env("HERMES_SESSION_KEY", "")+ for key in dict.fromkeys(key for key in (session_key, session_id) if key):+ if recorded := _recorded_cwd(key):+ session_cwd = recorded+ break+ except Exception:+ logger.debug("Unable to read the recorded Relay session cwd", exc_info=True)++ if not session_cwd:+ session_cwd = _clean_cwd(getattr(agent, "session_cwd", None))++ backend = ""+ if not session_cwd:+ try:+ from tools.terminal_scope import terminal_env++ backend = terminal_env("TERMINAL_ENV", "local").strip().lower()+ session_cwd = _clean_cwd(terminal_env("TERMINAL_CWD", ""))+ except Exception:+ logger.debug(+ "Unable to read the configured Relay session cwd", exc_info=True+ )++ if not session_cwd and platform == "cli" and backend in {"", "local"}:+ try:+ from agent.runtime_cwd import resolve_agent_cwd++ session_cwd = _clean_cwd(str(resolve_agent_cwd()))+ except Exception:+ logger.debug("Unable to resolve the local Relay session cwd", exc_info=True)++ turn_cwd = task_cwd or session_cwd+ if platform in {"subagent", "cron"} and task_cwd:+ session_cwd = task_cwd+ return session_cwd or turn_cwd, turn_cwddiff --git a/agent/relay_runtime.py b/agent/relay_runtime.pyindex a204ec5b76b..66ed367e887 100644--- a/agent/relay_runtime.py+++ b/agent/relay_runtime.py@@ -73,6 +73,11 @@ def runtime_metadata(runtime_id: str, **extra: Any) -> dict[str, Any]:return {RUNTIME_SCHEMA_KEY: RUNTIME_SCHEMA_VERSION, RUNTIME_INSTANCE_KEY: runtime_id, **extra}+def _scope_input(cwd: Any = None) -> dict[str, str]:+ """Return Relay scope input for a known logical working directory."""+ return {"cwd": cwd.strip()} if isinstance(cwd, str) and cwd.strip() else {}++def _run_on_daemon_thread(fn: Callable[[], Any], *, name: str, timeout: float | None = None, timeout_message: str = "") -> Any:@@ -154,6 +159,7 @@ class RelaySession:segment_turns: int = 0 # turns completed within the current segmentrotate_pending: bool = False # consumed at next begin_turnclose_pending: bool = False # rotating compaction hit a live turn; end_turn consumes it+ cwd: str = "" # latest logical working directory; reused when a session segment rotatesdef _load_segments_config() -> dict[str, Any]:@@ -387,7 +393,7 @@ class RelayRuntime:scope_metadata["nemo_relay_scope_role"] = "subagent"context = contextvars.Context()args = (self.relay.scope.push, SESSION_SCOPE, self.relay.ScopeType.Agent)- push_kwargs.update(handle=parent_handle, metadata=scope_metadata, input={})+ push_kwargs.update(handle=parent_handle, metadata=scope_metadata, input=_scope_input(session.cwd))try:future = _scope_op_executor().submit(context.run, *args, **push_kwargs)session.handle = future.result(timeout=_SCOPE_OP_TIMEOUT)@@ -398,7 +404,12 @@ class RelayRuntime:session.context = contextdef ensure_session(- self, event: dict[str, Any], *, data: Any = None, metadata: dict[str, Any] | None = None+ self,+ event: dict[str, Any],+ *,+ data: Any = None,+ metadata: dict[str, Any] | None = None,+ cwd: str | None = None,) -> RelaySession | None:"""Return the existing session scope or create it once."""session_id = _session_id(event)@@ -415,6 +426,8 @@ class RelayRuntime:with session.lock:if session.closing:return None+ if isinstance(cwd, str) and cwd.strip():+ session.cwd = cwd.strip()if session.handle is None:self._open_session_scope(session, {**(metadata or {}), **runtime_metadata(self.runtime_id)},@@ -455,7 +468,8 @@ class RelayRuntime:)def register_subagent(- self, event: dict[str, Any], *, metadata: dict[str, Any] | None = None+ self, event: dict[str, Any], *, metadata: dict[str, Any] | None = None,+ cwd: str | None = None,) -> RelaySession | None:"""Open a child Agent scope under its spawning turn when available."""parent_session_id = str(event.get("parent_session_id") or "")@@ -473,7 +487,7 @@ class RelayRuntime:self._subagent_parents[child_session_id] = parent_session_idif parent_handle is not None:self._subagent_parent_handles[child_session_id] = parent_handle- return self.ensure_session({"session_id": child_session_id}, metadata=metadata)+ return self.ensure_session({"session_id": child_session_id}, metadata=metadata, cwd=cwd)def unregister_subagent(self, event: dict[str, Any]) -> None:"""Close a delegated session and forget its parent relationship."""@@ -799,6 +813,7 @@ class ConversationLease:host: RelayHostsession: RelaySession | Noneparent_session_id: str = ""+ turn_cwd: str = ""released: bool = Falsedef live_runtime(self) -> RelayRuntime | None:@@ -898,29 +913,44 @@ class RelaySessionCoordinator:logger.warning("Hermes Relay session initializer failed: %s", name, exc_info=True)def acquire_conversation(- self, *, profile_key: str, session_id: str, platform: str, parent_session_id: str = "", model: str = "",+ self,+ *,+ profile_key: str,+ session_id: str,+ platform: str,+ parent_session_id: str = "",+ model: str = "",+ session_cwd: str | None = None,+ turn_cwd: str | None = None,) -> ConversationLease:host = self.registry.for_profile(profile_key) or NoopRelayRuntime(profile_key, "Relay host creation was disabled")session = Noneif isinstance(host, RelayRuntime):context = {"profile_key": profile_key, "session_id": session_id, "platform": platform,- "parent_session_id": parent_session_id, "model": model,+ "parent_session_id": parent_session_id, "model": model, "cwd": session_cwd,}session = _warn_on_error("conversation initialization", self._open_conversation_session, host, context)+ effective_turn_cwd = (+ _scope_input(turn_cwd).get("cwd") or _scope_input(session_cwd).get("cwd") or ""+ )+ if not effective_turn_cwd and session is not None:+ with session.lock:+ effective_turn_cwd = session.cwdreturn ConversationLease(profile_key=profile_key, session_id=session_id, platform=platform, host=host,- session=session, parent_session_id=parent_session_id,+ session=session, parent_session_id=parent_session_id, turn_cwd=effective_turn_cwd,)def _open_conversation_session(self, host: RelayRuntime, context: dict[str, Any]) -> RelaySession | None:self._prepare_session(host, context)session_id, parent_session_id = context["session_id"], context["parent_session_id"]metadata = {"hermes.execution_surface": context["platform"] or "unknown"}+ cwd = context.get("cwd")if parent_session_id and parent_session_id != session_id:event = {"parent_session_id": parent_session_id, "child_session_id": session_id}- return host.register_subagent(event, metadata=metadata)- return host.ensure_session({"session_id": session_id}, metadata=metadata)+ return host.register_subagent(event, metadata=metadata, cwd=cwd)+ return host.ensure_session({"session_id": session_id}, metadata=metadata, cwd=cwd)def begin_turn(self, lease: ConversationLease, *, turn_id: str, task_id: str) -> RelayTurnContext:if lease.released:@@ -944,7 +974,8 @@ class RelaySessionCoordinator:_warn_on_error("segment rotation", self._maybe_rotate_segment, host, lease.session)turn.handle = _warn_on_error("turn initialization", host.run_in_session, lease.session, host.relay.scope.push,- TURN_SCOPE, host.relay.ScopeType.Function, handle=lease.session.handle, input={},+ TURN_SCOPE, host.relay.ScopeType.Function, handle=lease.session.handle,+ input=_scope_input(lease.turn_cwd),metadata=runtime_metadata(host.runtime_id, **{"hermes.execution_surface": lease.platform or "unknown"}),timeout=_SCOPE_OP_TIMEOUT,)diff --git a/agent/runtime_cwd.py b/agent/runtime_cwd.pyindex b70f084c978..71d49587a28 100644--- a/agent/runtime_cwd.py+++ b/agent/runtime_cwd.py@@ -44,6 +44,16 @@ def clear_session_cwd() -> None:_SESSION_CWD.set("")+def scoped_session_cwd() -> str:+ """Return the current session's declared cwd without local path validation.++ Remote and container paths may not exist on the Hermes host. Callers that only need+ logical workspace identity should preserve the declared value instead of resolving it.+ """+ value = _SESSION_CWD.get()+ return "" if value is _UNSET else str(value).strip()++def scope_terminal_cwd() -> str:"""Scope-aware TERMINAL_CWD value (may be empty) — every cwd consumer reads through this.diff --git a/agent/turn_facade.py b/agent/turn_facade.pyindex acd3bc97ed5..676f7886f7a 100644--- a/agent/turn_facade.py+++ b/agent/turn_facade.py@@ -46,6 +46,7 @@ class TurnFacadeMixin:set_conversation_context,)from agent.prompt_cache_scope import declared_conversation_scope_safe+ from agent.relay_cwd import resolve_relay_scope_cwdsfrom agent.review_idle_queue import QUEUE as _review_queuefrom agent.subagent_lifecycle import bind_subagent_parentfrom agent.interrupt_scope import track_in_interrupt_scope@@ -88,11 +89,16 @@ class TurnFacadeMixin:lease = admission.leaseconversation_history = admission.conversation_history+ relay_session_cwd, relay_turn_cwd = resolve_relay_scope_cwds(+ self, effective_task_id, session_id, task_context["platform"]+ )relay_lease = relay_runtime.SESSION_COORDINATOR.acquire_conversation(profile_key=relay_runtime.current_profile_key(),session_id=task_context["session_id"], platform=task_context["platform"],parent_session_id=relay_parent_session_id,model=str(getattr(self, "model", None) or ""),+ session_cwd=relay_session_cwd,+ turn_cwd=relay_turn_cwd,)relay_turn = relay_runtime.SESSION_COORDINATOR.begin_turn(relay_lease, turn_id=relay_turn_id, task_id=effective_task_iddiff --git a/docs/observability/relay-shared-metrics.md b/docs/observability/relay-shared-metrics.mdindex 23d016659ca..d12024321d9 100644--- a/docs/observability/relay-shared-metrics.md+++ b/docs/observability/relay-shared-metrics.md@@ -94,6 +94,20 @@ Both defaults preserve one session scope for the full session. Rotated spansretain the same `session_id` and add `hermes.session.segment` plus`hermes.session.segment_reason` (`compaction` or `max_turns`).+## Working-Directory Scope Data++When Hermes knows a session or task's logical working directory, its+`hermes.session` and `hermes.turn` start scopes include it as `data.cwd` in+ATOF. A turn running in a task worktree can therefore differ from its owning+session. Unknown directories are omitted, and scope-end data remains reserved+for the outcome.++The working directory is Relay scope input, so it is visible to every enabled+Relay subscriber, not only ATOF. Paths can reveal usernames, repository names,+or mount layouts. Relay does not filter events by working directory; if a path+must not leave the host, use a trusted local collector or do not enable a remote+exporter for that process.+## Process-Wide Plugin Policy and Profile IsolationRelay plugin configuration is a process-level deployment choice, not a Hermesdiff --git a/tests/agent/test_relay_atof_cwd.py b/tests/agent/test_relay_atof_cwd.pynew file mode 100644index 00000000000..041ec0ad706--- /dev/null+++ b/tests/agent/test_relay_atof_cwd.py@@ -0,0 +1,109 @@+"""Hermes scope cwd export through the real NeMo Relay ATOF plugin."""++from __future__ import annotations++import json++import pytest+++def test_run_conversation_exports_session_and_turn_cwds(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_runtime+ from hermes_cli.lifecycle import finalize_session+ from run_agent import AIAgent+ from tools.terminal_tool import clear_session_cwd, record_session_cwd++ hermes_home = tmp_path / "hermes-home"+ session_cwd = tmp_path / "session"+ turn_cwd = tmp_path / "task"+ atof_dir = tmp_path / "atof"+ for directory in (hermes_home, session_cwd, turn_cwd, atof_dir):+ directory.mkdir()++ config = tmp_path / "plugins.toml"+ config.write_text(+ f"""version = 1++[[components]]+kind = "observability"+enabled = true++[components.config]+version = 4++[components.config.atof]+enabled = true++[[components.config.atof.sinks]]+type = "file"+output_directory = {json.dumps(str(atof_dir))}+filename = "events.jsonl"+mode = "overwrite"+""",+ encoding="utf-8",+ )+ session_id = "cwd-e2e-session"+ task_id = "cwd-e2e-task"+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ monkeypatch.setenv(relay_runtime.RELAY_PLUGINS_CONFIG_ENV, str(config))+ monkeypatch.chdir(session_cwd)+ monkeypatch.setattr(+ "agent.conversation_loop.run_conversation",+ lambda *_args, **_kwargs: {"final_response": "ok", "completed": True},+ )++ relay_runtime._reset_for_tests()+ relay.plugin.clear()+ record_session_cwd(task_id, str(turn_cwd))+ agent = None+ try:+ agent = AIAgent(+ api_key="test-key",+ base_url="https://example.invalid/v1",+ provider="openai",+ model="test-model",+ session_id=session_id,+ platform="cli",+ quiet_mode=True,+ skip_context_files=True,+ skip_memory=True,+ disabled_toolsets=["*"],+ )+ result = agent.run_conversation("hello", task_id=task_id)+ assert result["final_response"] == "ok"+ finalize_session(session_id=session_id)+ finally:+ if agent is not None:+ agent.close()+ clear_session_cwd(task_id)+ relay_runtime._reset_for_tests()++ events = [+ json.loads(line)+ for line in (atof_dir / "events.jsonl").read_text(encoding="utf-8").splitlines()+ if line.strip()+ ]++ def only_event(name: str, category: str) -> dict:+ matches = [+ event+ for event in events+ if event.get("name") == name and event.get("scope_category") == category+ ]+ assert len(matches) == 1+ return matches[0]++ session_start = only_event("hermes.session", "start")+ turn_start = only_event("hermes.turn", "start")+ session_end = only_event("hermes.session", "end")+ turn_end = only_event("hermes.turn", "end")++ assert session_start["data"] == {"cwd": str(session_cwd)}+ assert turn_start["data"] == {"cwd": str(turn_cwd)}+ assert turn_start["parent_uuid"] == session_start["uuid"]+ assert "cwd" not in session_end["data"]+ assert "cwd" not in turn_end["data"]diff --git a/tests/agent/test_relay_cwd.py b/tests/agent/test_relay_cwd.pynew file mode 100644index 00000000000..da53e06fda0--- /dev/null+++ b/tests/agent/test_relay_cwd.py@@ -0,0 +1,61 @@+"""Logical working directories attached to Hermes-owned Relay scopes."""++from agent import relay_cwd, runtime_cwd+from tools.terminal_tool import clear_session_cwd, record_session_cwd+++def test_session_context_and_task_record_remain_distinct(monkeypatch):+ token = runtime_cwd.set_session_cwd("/workspace/session")+ record_session_cwd("task-1", "/workspace/task")+ monkeypatch.setattr(+ "gateway.session_context.get_session_env", lambda _name, _default: ""+ )+ try:+ assert relay_cwd.resolve_relay_scope_cwds(+ object(), "task-1", "session-1", "cli"+ ) == ("/workspace/session", "/workspace/task")+ assert relay_cwd.resolve_relay_scope_cwds(+ object(), "task-1", "session-1", "subagent"+ ) == ("/workspace/task", "/workspace/task")+ finally:+ clear_session_cwd("task-1")+ runtime_cwd._SESSION_CWD.reset(token)+++def test_remote_scoped_cwd_is_preserved_without_host_resolution(monkeypatch):+ token = runtime_cwd.set_session_cwd("~/remote-project")+ monkeypatch.setattr("tools.terminal_tool.get_session_cwd", lambda _key: None)+ monkeypatch.setattr(+ runtime_cwd,+ "resolve_agent_cwd",+ lambda: (_ for _ in ()).throw(AssertionError("must not resolve on this host")),+ )+ try:+ assert relay_cwd.resolve_relay_scope_cwds(+ object(), "task-1", "session-1", "gateway"+ ) == ("~/remote-project", "~/remote-project")+ finally:+ runtime_cwd._SESSION_CWD.reset(token)+++def test_gateway_session_key_uses_its_recorded_cwd(monkeypatch):+ token = runtime_cwd.set_session_cwd(None)+ record_session_cwd("gateway-key", "/remote/gateway-workspace")+ monkeypatch.setattr(+ "gateway.session_context.get_session_env",+ lambda name, default: (+ "gateway-key" if name == "HERMES_SESSION_KEY" else default+ ),+ )+ monkeypatch.setattr(+ runtime_cwd,+ "resolve_agent_cwd",+ lambda: (_ for _ in ()).throw(AssertionError("must not resolve on this host")),+ )+ try:+ assert relay_cwd.resolve_relay_scope_cwds(+ object(), "task-1", "session-1", "gateway"+ ) == ("/remote/gateway-workspace", "/remote/gateway-workspace")+ finally:+ clear_session_cwd("gateway-key")+ runtime_cwd._SESSION_CWD.reset(token)diff --git a/tests/agent/test_relay_session_segments.py b/tests/agent/test_relay_session_segments.pyindex 2e778c4d477..92eb0c0772c 100644--- a/tests/agent/test_relay_session_segments.py+++ b/tests/agent/test_relay_session_segments.py@@ -39,7 +39,7 @@ class _FakeScopeModule:def __init__(self, wedge_pop: threading.Event | None = None) -> None:self._wedge = wedge_popself._seq = 0- self.pushes: list[dict[str, Any]] = [] # {name, metadata, handle}+ self.pushes: list[dict[str, Any]] = [] # {name, metadata, handle, input}self.pops: list[_ScopeHandle] = []def push(self, name: str, scope_type: Any, **kwargs: Any) -> _ScopeHandle:@@ -49,6 +49,7 @@ class _FakeScopeModule:"name": name,"metadata": dict(kwargs.get("metadata") or {}),"parent": kwargs.get("handle"),+ "input": dict(kwargs.get("input") or {}),"seq": self._seq,})@@ -143,7 +144,7 @@ def coordinator() -> RelaySessionCoordinator:return RelaySessionCoordinator()-def _acquire(coordinator, runtime, session_id="sess-1"):+def _acquire(coordinator, runtime, session_id="sess-1", **kwargs):class _Registry:def for_profile(self, key):return runtime@@ -154,6 +155,7 @@ def _acquire(coordinator, runtime, session_id="sess-1"):profile_key=runtime.profile_key,session_id=session_id,platform="test",+ **kwargs,)@@ -186,6 +188,33 @@ class TestDefaultsNeverRotate:)+class TestCwdProjection:+ def test_distinct_session_and_turn_cwds_survive_segment_rotation(self, coordinator):+ fake = _FakeRelay()+ runtime = _make_runtime(fake)+ lease = _acquire(+ coordinator, runtime,+ session_cwd="/workspace/session", turn_cwd="/workspace/task",+ )++ turn = coordinator.begin_turn(lease, turn_id="t1", task_id="task1")++ assert _session_pushes(fake)[-1]["input"] == {"cwd": "/workspace/session"}+ assert fake.scope.pushes[-1]["input"] == {"cwd": "/workspace/task"}+ coordinator.end_turn(turn, outcome="success")++ lease = _acquire(+ coordinator, runtime,+ session_cwd="/workspace/moved", turn_cwd="/workspace/next-task",+ )+ runtime.rotate_session_scope(lease.session, reason="compaction")+ turn = coordinator.begin_turn(lease, turn_id="t2", task_id="task2")++ assert _session_pushes(fake)[-1]["input"] == {"cwd": "/workspace/moved"}+ assert fake.scope.pushes[-1]["input"] == {"cwd": "/workspace/next-task"}+ coordinator.end_turn(turn, outcome="success")++class TestCompactionRotation:def test_compaction_rotates_at_next_begin_turn_not_immediately(self, coordinator, monkeypatch