CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
fix(loop): append after_model_response injects after tool_results
xf gong77743fefd043
diff --git a/cubepi/agent/loop.py b/cubepi/agent/loop.pyindex b662ef4..a7076a9 100644--- a/cubepi/agent/loop.py+++ b/cubepi/agent/loop.py@@ -206,6 +206,9 @@ async def _run_loop(# message_end is deferred until here so that a mutated response# is what gets persisted via Agent._process_event.skip_tool_execution = False+ # Messages injected by after_model_response that must be appended+ # AFTER this turn's tool_results, not immediately (see below).+ deferred_inject_messages: list[Message] = []if after_model_response is not None:turn_action = await after_model_response(message,@@ -225,11 +228,26 @@ async def _run_loop(# Emit message_end now — message reflects any hook mutation.await emit_event(emit, MessageEndEvent(message=message))if turn_action.inject_messages:- for inj in turn_action.inject_messages:- await emit_event(emit, MessageStartEvent(message=inj))- await emit_event(emit, MessageEndEvent(message=inj))- current_context.messages.append(inj)- new_messages.append(inj)+ # When this turn still has tool_calls to execute (the+ # "natural" decision falls through to tool handling+ # below), the tool_results MUST be appended before any+ # injected messages. Otherwise an injected (e.g. user)+ # message lands between an assistant tool_use and its+ # tool_result, which strict Anthropic-style endpoints+ # reject ("tool_use ... without tool_result blocks+ # immediately after"). Defer such injects until after+ # the tool_results are appended.+ _will_execute_tools = turn_action.decision == "natural" and any(+ isinstance(c, ToolCall) for c in message.content+ )+ if _will_execute_tools:+ deferred_inject_messages = list(turn_action.inject_messages)+ else:+ for inj in turn_action.inject_messages:+ await emit_event(emit, MessageStartEvent(message=inj))+ await emit_event(emit, MessageEndEvent(message=inj))+ current_context.messages.append(inj)+ new_messages.append(inj)if turn_action.decision == "stop":await emit_event(emit, TurnEndEvent(message=message, tool_results=[])@@ -276,6 +294,14 @@ async def _run_loop(current_context.messages.append(result)new_messages.append(result)+ # Append messages deferred from after_model_response so they land+ # AFTER the tool_results, preserving tool_use/tool_result adjacency.+ for inj in deferred_inject_messages:+ await emit_event(emit, MessageStartEvent(message=inj))+ await emit_event(emit, MessageEndEvent(message=inj))+ current_context.messages.append(inj)+ new_messages.append(inj)+await emit_event(emit, TurnEndEvent(message=message, tool_results=tool_results))diff --git a/tests/agent/test_loop.py b/tests/agent/test_loop.pyindex c03361e..21120e5 100644--- a/tests/agent/test_loop.py+++ b/tests/agent/test_loop.py@@ -201,6 +201,62 @@ class TestAgentLoop:assert "tool_execution_start" in event_typesassert "tool_execution_end" in event_types+ async def test_after_model_response_inject_lands_after_tool_results(self):+ """Regression: a message injected by after_model_response on a turn that+ still executes tool_calls must be appended AFTER the tool_results, never+ between the assistant tool_use and its tool_result — strict+ Anthropic-style endpoints 400 on tool_use without an immediately+ following tool_result."""+ from cubepi.middleware.base import TurnAction+ from cubepi.providers.base import ToolCall++ tool = make_echo_tool()+ provider = FauxProvider()+ provider.set_responses(+ [+ faux_assistant_message(+ [faux_tool_call("echo", {"value": "hello"}, id="tool-1")],+ stop_reason="tool_use",+ ),+ faux_assistant_message("done"),+ ]+ )++ async def inject_on_toolcall(message, ctx, *, signal=None):+ if any(isinstance(c, ToolCall) for c in message.content):+ return TurnAction(+ inject_messages=[UserMessage(content=[TextContent(text="REMINDER")])]+ )+ return None++ context = AgentContext(system_prompt="", messages=[], tools=[tool])+ result = await run_agent_loop(+ prompts=[make_user_message("echo something")],+ context=context,+ provider=provider,+ model=make_model(),+ convert_to_llm=identity_converter,+ emit=lambda e: None,+ after_model_response=inject_on_toolcall,+ )++ roles = [m.role for m in result]+ tool_use_idx = next(+ i+ for i, m in enumerate(result)+ if m.role == "assistant" and any(isinstance(c, ToolCall) for c in m.content)+ )+ # tool_result must immediately follow the assistant tool_use.+ assert result[tool_use_idx + 1].role == "tool_result", roles+ # the injected reminder must land after the tool_result, not before it.+ reminder_idx = next(+ i+ for i, m in enumerate(result)+ if m.role == "user"+ and any(getattr(c, "text", "") == "REMINDER" for c in m.content)+ )+ assert reminder_idx > tool_use_idx + 1, roles+async def test_should_stop_after_turn(self):tool = make_echo_tool()provider = FauxProvider()