The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): side-question forks release clients only, never close the shared session
Teknium599a749ae981
diff --git a/agent/background_review.py b/agent/background_review.pyindex 0bd033df96e..64b29082674 100644--- a/agent/background_review.py+++ b/agent/background_review.py@@ -1146,6 +1146,17 @@ def _release_fork_clients(review_agent: Any) -> None:review_agent.release_clients()+def release_cache_parity_fork(parent_agent: Any, fork: Any, *, task: str) -> dict[str, Any]:+ """Teardown for a one-shot :func:`build_cache_parity_fork` caller (``/btw``, plugin side+ questions): attribute the fork's usage to the parent session under ``task``, then release+ only its clients (never ``close()``, which tears down the shared session's terminal sandbox,+ browser and file state). Never raises; returns the usage snapshot."""+ usage = _snapshot_review_usage(fork)+ _record_review_usage_to_parent(parent_agent, usage, task=task)+ _release_fork_clients(fork)+ return usage++def _run_review_fork(agent: Any, messages_snapshot: list[dict], prompt: str, task_cfg: Optional[dict[str, Any]],review_run: Optional[_BackgroundReviewRun], st: _ReviewForkState, review_memory: bool = False,diff --git a/agent/side_question.py b/agent/side_question.pyindex e84640abd26..f7a89619d74 100644--- a/agent/side_question.py+++ b/agent/side_question.py@@ -108,9 +108,7 @@ def _answer_via_fork(parent_agent: Any, question: str, history: Optional[list[di``on_fork(fork)`` publishes the built fork so an owner can interrupt it, and``on_fork(None)`` follows its teardown."""- from agent.background_review import (- _digest_history, _record_review_usage_to_parent, _snapshot_review_usage, build_cache_parity_fork,- )+ from agent.background_review import _digest_history, build_cache_parity_fork, release_cache_parity_forkfrom hermes_cli.plugins import clear_thread_tool_whitelist, set_thread_tool_whitelistfork, _rt, routed = build_cache_parity_fork(parent_agent, _side_question_task_config(),@@ -130,13 +128,7 @@ def _answer_via_fork(parent_agent: Any, question: str, history: Optional[list[direturn answer.strip()finally:clear_thread_tool_whitelist()- # Attribute the fork's usage to the parent session; teardown never raises.- for step in (lambda: _record_review_usage_to_parent(parent_agent, _snapshot_review_usage(fork)),- fork.shutdown_memory_provider, fork.close):- try:- step()- except Exception:- pass+ release_cache_parity_fork(parent_agent, fork, task=SIDE_QUESTION_TASK)if on_fork is not None:on_fork(None)diff --git a/agent/side_question_request.py b/agent/side_question_request.pyindex 1493185ed65..0f23128b027 100644--- a/agent/side_question_request.py+++ b/agent/side_question_request.py@@ -192,21 +192,6 @@ def _answer_text(fork: Any, assistant_message: Any) -> Optional[str]:return fork._strip_think_blocks(text or "").strip() or None-def _teardown(parent: Any, fork: Any, audit: _Audit) -> None:- """Attribute usage to the parent session, then release the fork; never raises."""- from agent.background_review import _record_review_usage_to_parent, _snapshot_review_usage-- def _attribute() -> None:- audit.usage = _snapshot_review_usage(fork)- _record_review_usage_to_parent(parent, audit.usage, task=SIDE_QUESTION_ORIGIN)-- for step in (_attribute, fork.shutdown_memory_provider, fork.close):- try:- step()- except Exception:- logger.debug("side question teardown step failed", exc_info=True)--def _log_audit(audit: _Audit) -> None:usage = audit.usagelogger.info(@@ -227,6 +212,8 @@ def ask_text_only(provider error or an empty / tool-call-only reply. The request parameters (tools, reasoning,max_tokens, tool_choice) are the parent's verbatim: changing any of them changes the cachekey, and an inherited thinking budget 400s against a smaller max_tokens."""+ from agent.background_review import release_cache_parity_fork+audit = _Audit(plugin_id)parent = capture.parent_ref()refusal = "parent_gone" if parent is None else _agent_provider_refusal(parent)@@ -264,5 +251,5 @@ def ask_text_only(if timer is not None:timer.cancel()if fork is not None:- _teardown(parent, fork, audit)+ audit.usage = release_cache_parity_fork(parent, fork, task=SIDE_QUESTION_ORIGIN)_log_audit(audit)diff --git a/tests/agent/test_side_question.py b/tests/agent/test_side_question.pyindex 90f32b0e77c..ed3790d0b74 100644--- a/tests/agent/test_side_question.py+++ b/tests/agent/test_side_question.py@@ -193,4 +193,33 @@ class TestForkPath:assert calls["history"] == history # full snapshot replayed verbatimassert "which file?" in calls["user_message"]assert calls["write_origin"] == "side_question"- assert calls.get("shutdown") and calls.get("closed")++ def test_fork_teardown_leaves_the_sessions_terminal_environment(self):+ """The /btw fork shares the live session's id, which keys its terminal sandbox: a real+ fork's teardown must release clients only, never ``close()`` the session's tool state."""+ from agent.side_question import _answer_via_fork+ from run_agent import AIAgent+ from tools import terminal_tool++ class _Env:+ cleaned = False++ def cleanup(self, **_kwargs):+ _Env.cleaned = True++ with patch("model_tools.get_tool_definitions", return_value=[]), \+ patch("model_tools.check_toolset_requirements", return_value={}), \+ patch("agent.model_metadata.fetch_model_metadata", return_value={}):+ parent = AIAgent(api_key="k", base_url="https://openrouter.ai/api/v1", model="test/model",+ quiet_mode=True, skip_context_files=True, skip_memory=True, session_id="sess-btw")+ parent._cached_system_prompt = "You are helpful."+ env = _Env()+ terminal_tool._active_environments["sess-btw"] = env+ try:+ with patch.object(AIAgent, "run_conversation", return_value={"final_response": "foo.py"}):+ assert _answer_via_fork(parent, "which file?", []) == "foo.py"+ assert terminal_tool._active_environments.get("sess-btw") is env+ assert not _Env.cleaned+ finally:+ terminal_tool._active_environments.pop("sess-btw", None)+diff --git a/tests/agent/test_side_question_request.py b/tests/agent/test_side_question_request.pyindex 460ed889be0..7413c71edba 100644--- a/tests/agent/test_side_question_request.py+++ b/tests/agent/test_side_question_request.py@@ -276,6 +276,63 @@ def test_side_call_writes_only_one_usage_row(provider, issued, tmp_path):assert {p.name: p.read_bytes() for p in memories.iterdir()} == memory_before+def test_side_call_leaves_the_parent_sessions_terminal_environment_alive(provider, issued):+ """The fork shares the parent's session_id, and CLI/gateway key a session's terminal+ sandbox by it: tearing the fork down must not tear down the session's live tool state."""+ from tools import terminal_tool++ class _Env:+ cleaned = False++ def cleanup(self, **_kwargs):+ _Env.cleaned = True++ parent = _make_parent(session_id="sess-env")+ _run_parent_turn(parent, provider, tool_round=False)+ env = _Env()+ terminal_tool._active_environments["sess-env"] = env+ try:+ provider.replies.append(_response("Ask: why 42?", usage=_usage()))+ assert redeem_side_question(issued[-1], SIDE_PROMPT, plugin_id="next-prompt") == "Ask: why 42?"+ assert terminal_tool._active_environments.get("sess-env") is env+ assert not _Env.cleaned+ finally:+ terminal_tool._active_environments.pop("sess-env", None)+++def test_side_call_runs_under_the_turns_profile_and_secret_scope(provider, issued, tmp_path):+ """The plugin redeems from its own thread, where no profile is bound; the request still+ resolves the parent turn's HERMES_HOME and secret scope."""+ from agent.secret_scope import current_secret_scope_home, reset_secret_scope, set_secret_scope+ from hermes_constants import get_hermes_home, reset_hermes_home_override, set_hermes_home_override++ profile_home = tmp_path / "profiles" / "work"+ profile_home.mkdir(parents=True)+ parent = _make_parent()+ home_token = set_hermes_home_override(profile_home)+ scope_token = set_secret_scope({"OPENROUTER_API_KEY": "sk-work"}, profile_home=str(profile_home))+ try:+ _run_parent_turn(parent, provider, tool_round=False)+ finally:+ reset_secret_scope(scope_token)+ reset_hermes_home_override(home_token)++ seen: dict = {}++ def _reply():+ seen.update(home=str(get_hermes_home()), secret_home=current_secret_scope_home())+ return _response("Ask: why 42?", usage=_usage())++ provider.replies.append(_reply)+ answers: list = []+ worker = threading.Thread(+ target=lambda: answers.append(redeem_side_question(issued[-1], SIDE_PROMPT, plugin_id="next-prompt")))+ worker.start()+ worker.join(10)+ assert answers == ["Ask: why 42?"]+ assert seen == {"home": str(profile_home), "secret_home": str(profile_home)}++# ── 4. no recursive post_llm_call ────────────────────────────────────────────────────────