The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): preserve /steer through turn-budget enforcement
Xipong0fd0db1a8c1d
diff --git a/agent/tool_executor.py b/agent/tool_executor.pyindex f8bf5e6b2e5..61c8c720820 100644--- a/agent/tool_executor.py+++ b/agent/tool_executor.py@@ -1294,12 +1294,10 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effeexcept Exception as cb_err:logging.debug("Tool output risk callback error: %s", cb_err)- # ── Per-tool /steer drain ───────────────────────────────────- # Same as the sequential path: drain between each collected- # result so the steer lands as early as possible.- agent._apply_pending_steer_to_tool_results(messages, 1)-# ── Per-turn aggregate budget enforcement ─────────────────────────+ # Keep /steer pending until the final post-budget drain below. The model+ # cannot observe a partial batch, while an early drain can be discarded+ # when aggregate budget enforcement replaces that tool result.num_tools = len(parsed_calls)if finalize and num_tools > 0:turn_tool_msgs = messages[-num_tools:]@@ -1368,7 +1366,6 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effestage=f"invalid tool arguments {function_name}",):return- agent._apply_pending_steer_to_tool_results(messages, 1)continue# Tool Search unwrap — see execute_tool_calls_concurrent for full@@ -1945,12 +1942,6 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effeexcept Exception as cb_err:logging.debug("Tool output risk callback error: %s", cb_err)- # ── Per-tool /steer drain ───────────────────────────────────- # Drain pending steer BETWEEN individual tool calls so the- # injection lands as soon as a tool finishes — not after the- # entire batch. The model sees it on the next API iteration.- agent._apply_pending_steer_to_tool_results(messages, 1)-if not agent.quiet_mode and getattr(agent, "tool_progress_mode", "all") != "off":if agent.verbose_logging:print(f" ✅ Tool {i} completed in {tool_duration:.2f}s")@@ -1980,6 +1971,9 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effebreak# ── Per-turn aggregate budget enforcement ─────────────────────────+ # Keep /steer pending until the final post-budget drain below. The model+ # only receives this batch after all calls finish, and an early drain can+ # be discarded when aggregate budget enforcement replaces a tool result.num_tools_seq = len(assistant_message.tool_calls)if finalize and num_tools_seq > 0:enforce_turn_budget(messages[-num_tools_seq:], env=get_active_env(effective_task_id), config=_tool_budget)diff --git a/tests/run_agent/test_tool_batch_segmentation.py b/tests/run_agent/test_tool_batch_segmentation.pyindex a5e5e1cabfa..4ac1cf5034b 100644--- a/tests/run_agent/test_tool_batch_segmentation.py+++ b/tests/run_agent/test_tool_batch_segmentation.py@@ -27,6 +27,8 @@ from agent.tool_dispatch_helpers import (_plan_tool_batch_segments,_should_parallelize_tool_batch,)+from agent.prompt_builder import STEER_MARKER_OPEN+from tools.budget_config import BudgetConfigdef _tc(name="web_search", arguments="{}", call_id=None):@@ -313,9 +315,8 @@ class TestSegmentedDispatchIntegration:assert "cancelled" in m["content"] or "skipped" in m["content"]def test_steer_lands_exactly_once_in_mixed_batch(self, agent):- """Steer is drained once (per-tool drains + one dispatcher-level- finalize) — the marker must appear exactly once across the batch,- never duplicated by segment boundaries."""+ """The whole-batch finalizer drains steer once, so the marker cannot+ be duplicated by segment boundaries."""calls = [_tc("web_search", '{"query":"a"}', call_id="s1"),_tc("web_search", '{"query":"b"}', call_id="s2"),@@ -335,6 +336,80 @@ class TestSegmentedDispatchIntegration:hits = [c for c in contents if "focus on the tests" in c]assert len(hits) == 1+ @pytest.mark.parametrize(+ ("calls", "expected_segment_kinds"),+ [+ (+ [+ _tc("web_search", '{"query":"large"}', call_id="parallel-large"),+ _tc("web_search", '{"query":"small"}', call_id="parallel-small"),+ ],+ ["parallel"],+ ),+ (+ [+ _tc("terminal", '{"command":"large"}', call_id="sequential-large"),+ _tc("terminal", '{"command":"small"}', call_id="sequential-small"),+ ],+ ["sequential"],+ ),+ (+ [+ _tc("web_search", '{"query":"large"}', call_id="mixed-large"),+ _tc("web_search", '{"query":"small"}', call_id="mixed-search-small"),+ _tc("terminal", '{"command":"small"}', call_id="mixed-terminal-small"),+ ],+ ["parallel", "sequential"],+ ),+ (+ [+ _tc("web_search", '{"query":"small"}', call_id="mixed-search-first-small"),+ _tc("web_search", '{"query":"small"}', call_id="mixed-search-second-small"),+ _tc("terminal", '{"command":"large"}', call_id="mixed-terminal-large"),+ ],+ ["parallel", "sequential"],+ ),+ ],+ ids=["parallel", "sequential", "mixed-parallel-large", "mixed-sequential-large"],+ )+ def test_steer_survives_turn_budget_in_every_dispatch_path(+ self, agent, calls, expected_segment_kinds+ ):+ """A steer must be appended after aggregate budgeting in direct+ concurrent, direct sequential, and segmented mixed batches.++ The large result forces ``enforce_turn_budget()`` to replace it.+ Before the fix, the per-tool drain consumed the steer first, so that+ replacement silently discarded the canonical marker.+ """+ messages = []+ msg = SimpleNamespace(content="", tool_calls=calls)+ budget = BudgetConfig(+ default_result_size=10_000,+ turn_budget=48,+ preview_size=16,+ )++ assert _kinds(_plan_tool_batch_segments(calls)) == expected_segment_kinds++ def fake_handle(name, args, task_id, **kwargs):+ if kwargs["tool_call_id"].endswith("large"):+ assert agent.steer("preserve this steer after budget enforcement")+ return "L" * 1_000+ return "small"++ with (+ patch("run_agent.handle_function_call", side_effect=fake_handle),+ patch("agent.tool_executor._budget_for_agent", return_value=budget),+ ):+ agent._execute_tool_calls(msg, messages, "task-1")++ large_result_index = next(i for i, call in enumerate(calls) if call.id.endswith("large"))+ assert "Truncated:" in messages[large_result_index]["content"]+ steer_messages = [m for m in messages if STEER_MARKER_OPEN in m["content"]]+ assert steer_messages == [messages[-1]]+ assert "preserve this steer after budget enforcement" in steer_messages[0]["content"]+class TestPathCanonicalization:"""Regression tests for _canonical_path / _extract_parallel_scope_path fixes.