Skip to content

The agent that grows with you

fix(agent): isolate detached forks from lifecycle hooks

fangliquanflqfeb03196a2ad
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.py
index 70e9a127623..8174d9afca7 100644
--- a/agent/conversation_loop.py
+++ b/agent/conversation_loop.py
@@ -756,15 +756,16 @@ def _restore_or_build_system_prompt(agent, system_message, conversation_history)
# request naming a surface the conversation has left (#104414).
stage_surface_switch_note(agent, agent._cached_system_prompt, conversation_history)
- # Plugin hook: on_session_start — fired once for a brand-new session, not on continuation.
- try:
- from hermes_cli.lifecycle import invoke_hook as _invoke_hook
- _invoke_hook(
- "on_session_start", session_id=agent.session_id, model=agent.model,
- platform=getattr(agent, "platform", None) or "",
- )
- except Exception as exc:
- logger.warning("on_session_start hook failed: %s", exc)
+ # Persistence-disabled forks share their parent's session ID and are not real sessions.
+ if not getattr(agent, "_persist_disabled", False):
+ try:
+ from hermes_cli.lifecycle import invoke_hook as _invoke_hook
+ _invoke_hook(
+ "on_session_start", session_id=agent.session_id, model=agent.model,
+ platform=getattr(agent, "platform", None) or "",
+ )
+ except Exception as exc:
+ logger.warning("on_session_start hook failed: %s", exc)
# Cold-start credits seed (L3) fallback for the first-turn path; TUI/desktop seed at
# session open, so this is idempotent (skips when _credits_state exists). Fail-open.
diff --git a/agent/turn_context.py b/agent/turn_context.py
index 584d75d2113..2ca2edd645a 100644
--- a/agent/turn_context.py
+++ b/agent/turn_context.py
@@ -661,6 +661,8 @@ def _collect_pre_llm_call_context(
"""Run ``pre_llm_call`` plugins; their context is injected into the user message
(never the system prompt). Oversized per-hook context is spilled to disk so a
runaway plugin can't inflate every subsequent turn's prompt."""
+ if getattr(agent, "_persist_disabled", False):
+ return ""
try:
from hermes_cli.lifecycle import invoke_hook as _invoke_hook
_pre_results = _invoke_hook(
diff --git a/agent/turn_finalizer.py b/agent/turn_finalizer.py
index 144a57fa780..12157918179 100644
--- a/agent/turn_finalizer.py
+++ b/agent/turn_finalizer.py
@@ -415,18 +415,19 @@ def _apply_output_hooks(
if isinstance(_hook_result, str) and _hook_result:
pre_transform, final_response, transformed = final_response, _hook_result, True
break
- # post_llm_call (e.g. sync conversation data to an external memory system).
- _invoke_hook_safely(
- "post_llm_call", logger,
- session_id=agent.session_id,
- task_id=effective_task_id,
- turn_id=turn_id,
- user_message=original_user_message,
- assistant_response=final_response,
- conversation_history=list(messages),
- model=agent.model,
- platform=platform,
- )
+ # Detached forks are internal work and must not publish turns under the parent's session ID.
+ if not getattr(agent, "_persist_disabled", False):
+ _invoke_hook_safely(
+ "post_llm_call", logger,
+ session_id=agent.session_id,
+ task_id=effective_task_id,
+ turn_id=turn_id,
+ user_message=original_user_message,
+ assistant_response=final_response,
+ conversation_history=list(messages),
+ model=agent.model,
+ platform=platform,
+ )
return final_response, transformed, pre_transform
diff --git a/tests/agent/test_detached_fork_lifecycle_hooks.py b/tests/agent/test_detached_fork_lifecycle_hooks.py
new file mode 100644
index 00000000000..719d1687681
--- /dev/null
+++ b/tests/agent/test_detached_fork_lifecycle_hooks.py
@@ -0,0 +1,105 @@
+"""Lifecycle-hook isolation for persistence-disabled internal forks."""
+
+import logging
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+from agent.conversation_loop import _restore_or_build_system_prompt
+from agent.turn_context import _collect_pre_llm_call_context
+from agent.turn_finalizer import _apply_output_hooks
+
+
+def _agent(*, persist_disabled: bool):
+ return SimpleNamespace(
+ _cached_system_prompt=None,
+ _parent_session_id=None,
+ _persist_disabled=persist_disabled,
+ _session_db=None,
+ model="test/model",
+ platform="cli",
+ session_id="shared-session",
+ _build_system_prompt=Mock(return_value="system prompt"),
+ )
+
+
+def _apply_hooks(agent):
+ return _apply_output_hooks(
+ agent,
+ "response",
+ logging.getLogger(__name__),
+ platform="cli",
+ effective_task_id="task-1",
+ turn_id="turn-1",
+ original_user_message="hello",
+ messages=[{"role": "user", "content": "hello"}],
+ )
+
+
+def test_persist_disabled_fork_skips_session_and_turn_lifecycle_hooks():
+ agent = _agent(persist_disabled=True)
+
+ with (
+ patch("hermes_cli.lifecycle.invoke_hook") as lifecycle_hook,
+ patch("agent.credits_tracker.seed_credits_at_session_start"),
+ ):
+ _restore_or_build_system_prompt(agent, None, [])
+ context = _collect_pre_llm_call_context(
+ agent,
+ effective_task_id="task-1",
+ turn_id="turn-1",
+ original_user_message="hello",
+ messages=[{"role": "user", "content": "hello"}],
+ conversation_history=None,
+ )
+
+ output_calls = []
+
+ def invoke_output_hook(name, _logger, **_kwargs):
+ output_calls.append(name)
+ return ["transformed"] if name == "transform_llm_output" else []
+
+ with patch("agent.turn_finalizer._invoke_hook_safely", side_effect=invoke_output_hook):
+ response, transformed, _original = _apply_hooks(agent)
+
+ lifecycle_hook.assert_not_called()
+ assert context == ""
+ assert output_calls == ["transform_llm_output"]
+ assert response == "transformed"
+ assert transformed is True
+
+
+def test_persisted_agent_still_fires_session_and_turn_lifecycle_hooks():
+ agent = _agent(persist_disabled=False)
+
+ with (
+ patch("hermes_cli.lifecycle.invoke_hook") as lifecycle_hook,
+ patch("agent.credits_tracker.seed_credits_at_session_start"),
+ ):
+ lifecycle_hook.side_effect = lambda name, **_kwargs: (
+ [{"context": "plugin context"}] if name == "pre_llm_call" else []
+ )
+ _restore_or_build_system_prompt(agent, None, [])
+ context = _collect_pre_llm_call_context(
+ agent,
+ effective_task_id="task-1",
+ turn_id="turn-1",
+ original_user_message="hello",
+ messages=[{"role": "user", "content": "hello"}],
+ conversation_history=None,
+ )
+
+ output_calls = []
+
+ def invoke_output_hook(name, _logger, **_kwargs):
+ output_calls.append(name)
+ return []
+
+ with patch("agent.turn_finalizer._invoke_hook_safely", side_effect=invoke_output_hook):
+ _apply_hooks(agent)
+
+ assert [call.args[0] for call in lifecycle_hook.call_args_list] == [
+ "on_session_start",
+ "pre_llm_call",
+ ]
+ assert context == "plugin context"
+ assert output_calls == ["transform_llm_output", "post_llm_call"]