The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): persist /steer as a standalone user message
Albert.Zhoud24810483d3e
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex f097dee742e..7fb69803829 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -3147,9 +3147,25 @@ def _requeue_pending_steer(agent, steer_text: str) -> None:def apply_pending_steer_to_tool_results(agent, messages: list, num_tool_msgs: int) -> None:- """Append pending /steer text to the last ``role:"tool"`` message of this batch (bounded by- ``num_tool_msgs``), marked as user-origin. Modifies existing content only, so role- alternation is preserved."""+ """Persist any pending /steer text as a standalone user message.++ Called at the end of a tool-call batch, before the next API call.++ The steer is emitted as a NEW ``role:"user"`` message appended after the+ last tool result (marker text included), so:++ - the model still sees the self-describing out-of-band marker (same text,+ same provenance semantics);+ - message-role alternation stays legal — ``assistant(tool_calls) → tool →+ user`` is the documented "user jumped in mid-run" pattern that+ ``repair_message_sequence`` deliberately keeps;+ - the appended dict carries no ``_DB_PERSISTED_MARKER`` yet, so the next+ ``_flush_messages_to_session_db`` writes it to the session store — the+ steer text finally becomes part of the durable transcript instead of+ being smeared onto an already-persisted tool row that append-only+ persistence never rewrites (replayed histories then diverge from the+ live request bytes and break the provider prompt cache).+ """if num_tool_msgs <= 0 or not messages:returnsteer_text = agent._drain_pending_steer()@@ -3159,22 +3175,17 @@ def apply_pending_steer_to_tool_results(agent, messages: list, num_tool_msgs: intail = range(len(messages) - 1, max(len(messages) - num_tool_msgs - 1, -1), -1)target = next((messages[j] for j in tail if isinstance(messages[j], dict) and messages[j].get("role") == "tool"), None)if target is None:- # No tool result in this batch (e.g. all skipped by interrupt).+ # No tool result in this batch (e.g. all skipped by interrupt);+ # requeue so the fallback path delivers it as a normal next-turn+ # user message (which persists like any other user turn)._requeue_pending_steer(agent, steer_text)returnmarker = format_steer_marker(steer_text)- existing_content = target.get("content", "")- if isinstance(existing_content, str):- target["content"] = existing_content + marker- else:- # Anthropic multimodal content blocks: preserve them and append a text block.- try:- target["content"] = [*(existing_content or []), {"type": "text", "text": marker.lstrip()}]- except Exception:- # Fall back to string replacement if content shape is unexpected.- target["content"] = f"{existing_content}{marker}"+ # Append a standalone user message instead of rewriting the persisted+ # tool row's content.+ messages.append({"role": "user", "content": marker})_ra().logger.info(- "Delivered /steer to agent after tool batch (%d chars): %s", len(steer_text),+ "Delivered /steer to agent after tool batch (%d chars) as new user message: %s", len(steer_text),steer_text[:120] + ("..." if len(steer_text) > 120 else ""),)diff --git a/tests/run_agent/test_steer.py b/tests/run_agent/test_steer.pyindex 9d50add447f..d0bad3ecca4 100644--- a/tests/run_agent/test_steer.py+++ b/tests/run_agent/test_steer.py@@ -486,7 +486,7 @@ class TestEmptyHiddenAssistantRehealRegression:class TestSteerInjection:- def test_appends_to_last_tool_result(self):+ def test_appends_standalone_user_message_after_tool_results(self):agent = _bare_agent()agent.steer("please also check auth.log")messages = [@@ -496,14 +496,34 @@ class TestSteerInjection:{"role": "tool", "content": "ls output B", "tool_call_id": "b"},]agent._apply_pending_steer_to_tool_results(messages, num_tool_msgs=2)- # The LAST tool result is modified; earlier ones are untouched.+ # Existing tool rows are untouched (append-only persistence contract);+ # the steer becomes a NEW user message at the tail.assert messages[2]["content"] == "ls output A"- assert "ls output B" in messages[3]["content"]- assert STEER_MARKER_OPEN in messages[3]["content"]- assert "please also check auth.log" in messages[3]["content"]+ assert messages[3]["content"] == "ls output B"+ assert messages[-1]["role"] == "user"+ assert STEER_MARKER_OPEN in messages[-1]["content"]+ assert "please also check auth.log" in messages[-1]["content"]+ # Role-alternation pattern: assistant(tool_calls) → tool → user is+ # the documented legal "user jumped in mid-run" shape.# And pending_steer is consumed.assert agent._pending_steer is None+ def test_appended_user_message_is_persistable(self):+ """The appended user dict carries no _DB_PERSISTED_MARKER yet, so the+ next _flush_messages_to_session_db writes it to state.db — the steer+ text lands in the durable transcript (messages.content, role=user)."""+ from agent.context_compressor import _DB_PERSISTED_MARKER++ agent = _bare_agent()+ agent.steer("remember this decision")+ messages = [+ {"role": "assistant", "tool_calls": [{"id": "a"}]},+ {"role": "tool", "content": "output", "tool_call_id": "a"},+ ]+ agent._apply_pending_steer_to_tool_results(messages, num_tool_msgs=1)+ assert messages[-1]["role"] == "user"+ assert _DB_PERSISTED_MARKER not in messages[-1]+def test_no_op_when_no_steer_pending(self):agent = _bare_agent()messages = [@@ -518,20 +538,25 @@ class TestSteerInjection:"""The injection marker must attribute the appended text to the uservia the explicit out-of-band marker (which the system prompt tells themodel to trust) — otherwise the model reads it as untrusted tool output- and refuses it as suspected prompt injection. Cache-safe: it only- rewrites existing tool content, never the message-role sequence.+ and refuses it as suspected prompt injection. Cache-safe: the marker+ is delivered as a NEW user message, never by rewriting existing tool+ content, so the persisted transcript matches the wire bytes."""agent = _bare_agent()agent.steer("stop after next step")messages = [{"role": "tool", "content": "x", "tool_call_id": "1"}]agent._apply_pending_steer_to_tool_results(messages, num_tool_msgs=1)+ assert messages[-1]["role"] == "user"content = messages[-1]["content"]assert STEER_MARKER_OPEN in contentassert "stop after next step" in content+ # The tool row itself is untouched.+ assert messages[0]["content"] == "x"def test_multimodal_content_list_preserved(self):- """Anthropic-style list content should be preserved, with the steer- appended as a text block."""+ """Anthropic-style list content on tool results is left untouched —+ the steer is appended as a standalone user message instead of being+ merged into the content blocks."""agent = _bare_agent()agent.steer("extra note")original_blocks = [{"type": "text", "text": "existing output"}]@@ -539,12 +564,9 @@ class TestSteerInjection:{"role": "tool", "content": list(original_blocks), "tool_call_id": "1"}]agent._apply_pending_steer_to_tool_results(messages, num_tool_msgs=1)- new_content = messages[-1]["content"]- assert isinstance(new_content, list)- assert len(new_content) == 2- assert new_content[0] == {"type": "text", "text": "existing output"}- assert new_content[1]["type"] == "text"- assert "extra note" in new_content[1]["text"]+ assert messages[0]["content"] == original_blocks # untouched+ assert messages[-1]["role"] == "user"+ assert "extra note" in messages[-1]["content"]@@ -728,9 +750,9 @@ class TestLegacyHiddenPlaceholderWireSubstitution:from run_agent import AIAgentwith (- patch("model_tools.get_tool_definitions", return_value=[]),- patch("model_tools.check_toolset_requirements", return_value={}),- patch("agent.process_bootstrap.OpenAI"),+ patch("run_agent.get_tool_definitions", return_value=[]),+ patch("run_agent.check_toolset_requirements", return_value={}),+ patch("run_agent.OpenAI"),):agent = AIAgent(api_key="test-key-1234567890",diff --git a/tests/run_agent/test_tool_batch_segmentation.py b/tests/run_agent/test_tool_batch_segmentation.pyindex ee5b6fe9c1e..87c1644f0d8 100644--- a/tests/run_agent/test_tool_batch_segmentation.py+++ b/tests/run_agent/test_tool_batch_segmentation.py@@ -635,10 +635,12 @@ class TestSegmentedDispatchIntegration:with patch("agent.tool_executor._budget_for_agent", return_value=budget):agent._execute_tool_calls(msg, messages, "task-1")- assert len(messages) == 1+ assert len(messages) == 2_assert_budget_replaced(messages[0]["content"])- assert messages[0]["content"].count(STEER_MARKER_OPEN) == 1- assert "preserve malformed-call steer after budget enforcement" in messages[0]["content"]+ assert STEER_MARKER_OPEN not in messages[0]["content"] # tool row untouched+ assert messages[1]["role"] == "user" # steer = new user msg+ assert messages[1]["content"].count(STEER_MARKER_OPEN) == 1+ assert "preserve malformed-call steer after budget enforcement" in messages[1]["content"]class TestPathCanonicalization: