Skip to content

The agent that grows with you

fix(cli): finalize one-shot Relay sessions (#79471)

Lester Liangc225c4a04e8b
diff --git a/hermes_cli/oneshot.py b/hermes_cli/oneshot.py
index 2457694bee7..b9eb2d48708 100644
--- a/hermes_cli/oneshot.py
+++ b/hermes_cli/oneshot.py
@@ -567,7 +567,7 @@ def _run_agent(
# The try spans agent construction (not just ``chat``) so the store is always closed, even when
# ``AIAgent(...)`` raises — the one-shot exit path hard-exits via os._exit and skips finalizers.
- agent = None
+ agent = relay_session_id = None
try:
agent = AIAgent(
api_key=runtime.get("api_key"),
@@ -598,13 +598,16 @@ def _run_agent(
agent.tool_gen_callback = None
aux_before = _auxiliary_usage(session_db, resume_sid) if ledger else {}
+ # Relay keys the root conversation to the id at turn entry; compression may rotate
+ # agent.session_id mid-turn without opening a second root, so keep the entry id.
+ relay_session_id = getattr(agent, "session_id", None)
result = agent.run_conversation(prompt, conversation_history=conversation_history or None)
if ledger:
_attach_auxiliary_usage(result, session_db, aux_before,
fallback_session_id=agent.session_id or resume_sid)
return (result.get("final_response") or "", result)
finally:
- _close_agent(agent, session_db)
+ _close_agent(agent, session_db, relay_session_id)
def _quietly(what: str, fn) -> None:
@@ -625,7 +628,7 @@ def _linger_for_background_completions() -> None:
process_registry.wait_for_pending_completions(None)
-def _close_agent(agent, session_db) -> None:
+def _close_agent(agent, session_db, relay_session_id=None) -> None:
"""Teardown mirroring gateway/run.py:_cleanup_agent_resources (NOT cli.py:_run_cleanup):
oneshot has no _active_agent_ref and the hard-exit path skips finalizers."""
if agent is not None:
@@ -633,6 +636,14 @@ def _close_agent(agent, session_db) -> None:
# close() kill_all()s the task and the dying parent owns the children's stdout pipes, so
# exiting now destroys in-flight deliveries (e.g. Bot Mode handoff replies).
_quietly("background completion wait", _linger_for_background_completions)
+ if relay_session_id:
+ # run_conversation ends the turn but keeps the Relay root resumable; one-shot has no
+ # next turn and os._exit skips atexit, so close the root (and fire on_session_finalize).
+ from hermes_cli.lifecycle import finalize_session
+
+ _quietly("session finalize", lambda: finalize_session(
+ session_id=relay_session_id, platform=getattr(agent, "platform", None) or "cli",
+ reason="shutdown"))
session_messages = getattr(agent, "_session_messages", None)
memory_args = (session_messages,) if isinstance(session_messages, list) else ()
_quietly("memory/context cleanup", lambda: agent.shutdown_memory_provider(*memory_args))
diff --git a/tests/hermes_cli/test_tui_resume_flow.py b/tests/hermes_cli/test_tui_resume_flow.py
index 545014e2138..3b3272bda79 100644
--- a/tests/hermes_cli/test_tui_resume_flow.py
+++ b/tests/hermes_cli/test_tui_resume_flow.py
@@ -173,6 +173,63 @@ def test_oneshot_wires_session_db_for_recall(monkeypatch):
assert captured["prompt"] == "recall this"
[email protected]("run_fails", [False, True], ids=["success", "failure"])
+def test_oneshot_closes_its_relay_root_before_agent_teardown(monkeypatch, run_fails):
+ """hermes -z hard-exits past atexit, so _run_agent itself must finalize the Relay root it opened:
+ keyed to the id at turn entry (compression may rotate it), on failure too, before agent.close()."""
+ from hermes_cli import lifecycle
+ from hermes_cli.oneshot import _run_agent
+
+ events = []
+
+ class FakeAgent:
+ def __init__(self, **_kwargs):
+ self.session_id = "entry-id"
+ self.platform = "cli"
+ self.suppress_status_output = False
+ self.stream_delta_callback = self.tool_gen_callback = object()
+
+ def run_conversation(self, _prompt, **_kwargs):
+ self.session_id = "compressed-child-id"
+ if run_fails:
+ raise RuntimeError("agent failed")
+ return {"final_response": "ok", "failed": False, "partial": False}
+
+ def shutdown_memory_provider(self, *_args):
+ events.append("memory")
+
+ def close(self):
+ events.append("agent_close")
+
+ def mod(name, **attrs):
+ module = types.ModuleType(name)
+ for key, value in attrs.items():
+ setattr(module, key, value)
+ return module
+
+ monkeypatch.setitem(sys.modules, "run_agent", mod("run_agent", AIAgent=FakeAgent))
+ monkeypatch.setitem(sys.modules, "hermes_state_registry", mod("hermes_state_registry", acquire=lambda db_path=None: None))
+ monkeypatch.setitem(sys.modules, "hermes_cli.config", mod("hermes_cli.config", load_config=lambda: {"model": {"default": "m"}}))
+ monkeypatch.setitem(sys.modules, "hermes_cli.models",
+ mod("hermes_cli.models", detect_provider_for_model=lambda *_a, **_k: None))
+ monkeypatch.setitem(sys.modules, "hermes_cli.runtime_provider", mod(
+ "hermes_cli.runtime_provider",
+ resolve_runtime_with_fallback=lambda _cfg, **_k: ({"api_key": "k", "base_url": "u", "provider": "p",
+ "api_mode": "chat_completions", "credential_pool": None}, None),
+ ))
+ monkeypatch.setitem(sys.modules, "hermes_cli.tools_config",
+ mod("hermes_cli.tools_config", _get_platform_tools=lambda *_a, **_k: set()))
+ monkeypatch.setattr(lifecycle, "finalize_session", lambda **kw: events.append(("finalize", kw)))
+
+ if run_fails:
+ with pytest.raises(RuntimeError, match="agent failed"):
+ _run_agent("finish this")
+ else:
+ assert _run_agent("finish this")[0] == "ok"
+ assert events == [("finalize", {"session_id": "entry-id", "platform": "cli", "reason": "shutdown"}),
+ "memory", "agent_close"]
+
+
def test_launch_tui_exports_model_provider_and_toolsets(monkeypatch, main_mod):
monkeypatch.setenv("HERMES_PYTHON", sys.executable)
captured = {}
diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.md
index 0f48e8cb85d..d4ea6fd0d87 100644
--- a/website/docs/user-guide/features/hooks.md
+++ b/website/docs/user-guide/features/hooks.md
@@ -1023,7 +1023,7 @@ def my_callback(session_id: str | None, platform: str, **kwargs):
| `session_id` | `str` or `None` | The outgoing session ID. May be `None` if no active session existed. |
| `platform` | `str` | `"cli"` or the messaging platform name (`"telegram"`, `"discord"`, etc.). |
-**Fires:** In CLI/TUI teardown and in gateway reset or shutdown paths. Gateway shutdown can finalize without a matching `on_session_reset`.
+**Fires:** In CLI/TUI teardown (including the end of a `hermes -z` one-shot run, success or failure) and in gateway reset or shutdown paths. Gateway shutdown can finalize without a matching `on_session_reset`.
**Return value:** Ignored.