The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
fix(langchain): preserve model-generated tool calls in HITL tool call edits and add notice to ToolMessage (#40463)
ccurme5bf6a15466ca
diff --git a/libs/langchain_v1/langchain/agents/factory.py b/libs/langchain_v1/langchain/agents/factory.pyindex c01479ad84..0810bdc4b4 100644--- a/libs/langchain_v1/langchain/agents/factory.py+++ b/libs/langchain_v1/langchain/agents/factory.py@@ -2017,11 +2017,17 @@ def _make_tools_to_model_edge(# 2. Exit condition: All executed tools have return_direct=True# Filter to only client-side tools (provider tools are not in tool_node)- client_side_tool_calls = [- c for c in last_ai_message.tool_calls if c["name"] in tool_node.tools_by_name+ # Prefer tool name from ToolMessage due to redirects (e.g., from HITL)+ executed_by_id = {+ t.tool_call_id: t.name for t in tool_messages if t.name in tool_node.tools_by_name+ }+ executed_names = [+ name+ for c in last_ai_message.tool_calls+ if (name := executed_by_id.get(c["id"] or "", c["name"])) in tool_node.tools_by_name]- if client_side_tool_calls and all(- tool_node.tools_by_name[c["name"]].return_direct for c in client_side_tool_calls+ if executed_names and all(+ tool_node.tools_by_name[name].return_direct for name in executed_names):return end_destinationdiff --git a/libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py b/libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.pyindex ebdfb2ddbc..9584b645b2 100644--- a/libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py+++ b/libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py@@ -2,29 +2,43 @@from __future__ import annotations-from typing import TYPE_CHECKING, Any, Literal, Protocol+import json+from dataclasses import replace+from typing import TYPE_CHECKING, Annotated, Any, Literal, Protocol, castfrom langchain_core.messages import AIMessage, ToolCall, ToolMessagefrom langgraph.config import get_configfrom langgraph.prebuilt.tool_node import ToolRuntime-from langgraph.types import interrupt+from langgraph.types import Command, interruptfrom typing_extensions import NotRequired, TypedDictfrom langchain.agents.middleware.types import (AgentMiddleware,AgentState,ContextT,+ PrivateStateAttr,ResponseT,StateT,ToolCallRequest,)if TYPE_CHECKING:- from collections.abc import Callable+ from collections.abc import Awaitable, Callablefrom langgraph.runtime import Runtime+_EDITED_TOOL_CALLS_KEY = "hitl_edited_tool_calls"+"""State key mapping tool call ID to the reviewer's replacement for it."""++_EDIT_NOTICE = (+ "Note: a human reviewer replaced this tool call before it ran. The call recorded in "+ "your message is the one you produced, not the one that executed. This was "+ "intentional and authorized. Do not re-issue your original call."+)+"""Default text prepended to the result of a tool call a reviewer edited."""++class Action(TypedDict):"""Represents an action with a name and args."""@@ -216,14 +230,24 @@ class InterruptOnConfig(TypedDict):"""+class _HumanInTheLoopState(AgentState[ResponseT]):+ """State schema for `HumanInTheLoopMiddleware`."""++ hitl_edited_tool_calls: NotRequired[Annotated[dict[str, Action], PrivateStateAttr]]+ """Track tool call edits from `after_model`, so they can be used by `wrap_tool_call`."""++class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT, ResponseT]):"""Human in the loop middleware."""+ state_schema = _HumanInTheLoopState # type: ignore[assignment]+def __init__(self,interrupt_on: dict[str, bool | InterruptOnConfig],*,description_prefix: str = "Tool execution requires approval",+ edit_notice: str | None = _EDIT_NOTICE,) -> None:"""Initialize the human in the loop middleware.@@ -249,6 +273,8 @@ class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT, ResponseT]):requested.Not used if a tool has a `description` in its `InterruptOnConfig`.+ edit_notice: Text prepended to the result of a tool call a reviewer replaced+ via an `edit` decision. Pass `None` to add nothing.Raises:ValueError: If a tool's `InterruptOnConfig` does not have a non-empty@@ -257,6 +283,7 @@ class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT, ResponseT]):dropped, disabling the approval gate for that tool."""super().__init__()+ self.edit_notice = edit_noticeresolved_configs: dict[str, InterruptOnConfig] = {}for tool_name, tool_config in interrupt_on.items():if isinstance(tool_config, bool):@@ -326,16 +353,9 @@ class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT, ResponseT]):if decision["type"] == "approve" and "approve" in allowed_decisions:return tool_call, Noneif decision["type"] == "edit" and "edit" in allowed_decisions:- edited_action = decision["edited_action"]- return (- ToolCall(- type="tool_call",- name=edited_action["name"],- args=edited_action["args"],- id=tool_call["id"],- ),- None,- )+ # Keep the model's own call in the message; `wrap_tool_call` substitutes the+ # reviewer's at execution time.+ return tool_call, Noneif decision["type"] == "reject" and "reject" in allowed_decisions:reason = decision.get("message")content = (@@ -444,8 +464,11 @@ class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT, ResponseT]):review_configs.append(review_config)interrupt_indices.append(idx)- # If no interrupts needed, return early+ # If no interrupts needed, return early, dropping any earlier turn's edits so+ # they cannot be applied to this turn's tool calls.if not action_requests:+ if state.get(_EDITED_TOOL_CALLS_KEY):+ return {_EDITED_TOOL_CALLS_KEY: {}}return None# Create single HITLRequest with all actions and configs@@ -468,6 +491,7 @@ class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT, ResponseT]):# Process decisions and rebuild tool calls in original orderrevised_tool_calls: list[ToolCall] = []artificial_tool_messages: list[ToolMessage] = []+ edited_tool_calls: dict[str, Action] = {}decision_idx = 0for idx, tool_call in enumerate(last_ai_msg.tool_calls):@@ -482,6 +506,8 @@ class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT, ResponseT]):)if revised_tool_call is not None:revised_tool_calls.append(revised_tool_call)+ if decision["type"] == "edit" and (edited_id := revised_tool_call.get("id")):+ edited_tool_calls[edited_id] = decision["edited_action"]if tool_message:artificial_tool_messages.append(tool_message)else:@@ -491,7 +517,12 @@ class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT, ResponseT]):# Update the AI message to only include approved tool callslast_ai_msg.tool_calls = revised_tool_calls- return {"messages": [last_ai_msg, *artificial_tool_messages]}+ # `wrap_tool_call` reads this back to substitute and annotate the call. Always+ # written, so an earlier turn's edits cannot survive into this one.+ return {+ "messages": [last_ai_msg, *artificial_tool_messages],+ _EDITED_TOOL_CALLS_KEY: edited_tool_calls,+ }async def aafter_model(self, state: AgentState[Any], runtime: Runtime[ContextT]@@ -506,3 +537,144 @@ class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT, ResponseT]):Updated message with the revised tool calls."""return self.after_model(state, runtime)++ def _reviewer_edit(self, request: ToolCallRequest) -> Action | None:+ """The reviewer's replacement for this call, if an `edit` decision replaced it."""+ tool_call_id = request.tool_call.get("id")+ if not tool_call_id:+ return None+ edited = request.state.get(_EDITED_TOOL_CALLS_KEY) or {}+ if tool_call_id in edited:+ return cast("Action", edited[tool_call_id])+ return None++ def _apply_edit(self, request: ToolCallRequest, executed: Action) -> ToolCallRequest:+ """Point the request at the reviewer's call, resolving a redirected tool.++ Raises:+ ValueError: If the reviewer named a tool the agent does not have.+ """+ tool_call: ToolCall = {+ **request.tool_call,+ "name": executed["name"],+ "args": executed["args"],+ }+ if executed["name"] == request.tool_call["name"]:+ return request.override(tool_call=tool_call)++ # `tool_call["name"]` and `tool` must stay in agreement.+ available = request.runtime.tools+ tool = next((t for t in available if t.name == executed["name"]), None)+ if tool is None:+ names = ", ".join(sorted(t.name for t in available))+ msg = (+ f"Reviewer edited tool call {request.tool_call['id']!r} to "+ f"{executed['name']!r}, which is not an available tool. "+ f"Available tools: {names}."+ )+ raise ValueError(msg)+ return request.override(tool_call=tool_call, tool=tool)++ def _notice(self, executed: Action, *, has_content: bool) -> str:+ """The notice text, stating the call that actually ran."""+ notice = (+ f"{self.edit_notice} Executed instead: {executed['name']} with arguments "+ f"{json.dumps(executed['args'], default=str)}."+ )+ return f"{notice}\n\nTool response:" if has_content else notice++ def _prepend_notice(self, message: ToolMessage, executed: Action) -> ToolMessage:+ """Return `message` with the reviewer-edit notice prepended to its content."""+ if not self.edit_notice:+ return message+ edit_notice = self._notice(executed, has_content=bool(message.content))++ content: str | list[str | dict[Any, Any]]+ if isinstance(message.content, str):+ if edit_notice in message.content:+ return message+ separator = "\n" if message.content else ""+ content = f"{edit_notice}{separator}{message.content}"+ else:+ if any(edit_notice in str(block) for block in message.content):+ return message+ # Match the surrounding block shape; providers may reject mixed lists.+ notice: str | dict[Any, Any] = (+ edit_notice+ if message.content and all(isinstance(b, str) for b in message.content)+ else {"type": "text", "text": edit_notice}+ )+ content = [notice, *message.content]++ return message.model_copy(update={"content": content})++ def _annotate_edited_result(+ self,+ result: ToolMessage | Command[Any],+ request: ToolCallRequest,+ executed: Action | None,+ ) -> ToolMessage | Command[Any]:+ """Tell the model a reviewer replaced the call, and with what."""+ if not self.edit_notice or executed is None:+ return result++ if isinstance(result, ToolMessage):+ return self._prepend_notice(result, executed)++ # A `Command` carries the `ToolMessage` in its state update.+ if not isinstance(result, Command) or not isinstance(result.update, dict):+ return result+ messages = result.update.get("messages")+ if not isinstance(messages, list):+ return result+ tool_call_id = request.tool_call.get("id")+ return replace(+ result,+ update={+ **result.update,+ "messages": [+ self._prepend_notice(message, executed)+ if isinstance(message, ToolMessage) and message.tool_call_id == tool_call_id+ else message+ for message in messages+ ],+ },+ )++ def wrap_tool_call(+ self,+ request: ToolCallRequest,+ handler: Callable[[ToolCallRequest], ToolMessage | Command[Any]],+ ) -> ToolMessage | Command[Any]:+ """Prepend reviewer-edit guidance to the result of an edited tool call.++ Args:+ request: The tool call request being executed.+ handler: Callable that executes the tool.++ Returns:+ The tool result, with a note prepended when a reviewer edited the call.+ """+ executed = self._reviewer_edit(request)+ if executed is not None:+ request = self._apply_edit(request, executed)+ return self._annotate_edited_result(handler(request), request, executed)++ async def awrap_tool_call(+ self,+ request: ToolCallRequest,+ handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]],+ ) -> ToolMessage | Command[Any]:+ """Async variant of `wrap_tool_call`.++ Args:+ request: The tool call request being executed.+ handler: Awaitable callable that executes the tool.++ Returns:+ The tool result, with a note prepended when a reviewer edited the call.+ """+ executed = self._reviewer_edit(request)+ if executed is not None:+ request = self._apply_edit(request, executed)+ return self._annotate_edited_result(await handler(request), request, executed)diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_human_in_the_loop.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_human_in_the_loop.pyindex 522153adcc..9dd94fdb6f 100644--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_human_in_the_loop.py+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_human_in_the_loop.py@@ -1,24 +1,36 @@import re-from typing import Any+from types import SimpleNamespace+from typing import TYPE_CHECKING, Anyfrom unittest.mock import patchimport pytestfrom langchain_core.messages import AIMessage, HumanMessage, ToolCall, ToolMessagefrom langchain_core.tools import toolfrom langgraph.checkpoint.memory import InMemorySaver-from langgraph.prebuilt.tool_node import ToolRuntime+from langgraph.prebuilt.tool_node import ToolNode, ToolRuntimefrom langgraph.runtime import Runtimefrom langgraph.types import Command-from langchain.agents.factory import create_agent+from langchain.agents.factory import _make_tools_to_model_edge, create_agentfrom langchain.agents.middleware import InterruptOnConfigfrom langchain.agents.middleware.human_in_the_loop import (+ _EDIT_NOTICE,+ _EDITED_TOOL_CALLS_KEY,Action,HumanInTheLoopMiddleware,+ _HumanInTheLoopState,)from langchain.agents.middleware.types import AgentState, ToolCallRequestfrom tests.unit_tests.agents.model import FakeToolCallingModel+if TYPE_CHECKING:+ from langchain_core.runnables import RunnableConfig++_EXPECTED_NOTICE = (+ f'{_EDIT_NOTICE} Executed instead: write_file_tool with arguments {{"content": "edited"}}.'+)+_EXPECTED_NOTICE_WITH_CONTENT = f"{_EXPECTED_NOTICE}\n\nTool response:"+def test_human_in_the_loop_middleware_initialization() -> None:"""Test HumanInTheLoopMiddleware initialization."""@@ -145,8 +157,11 @@ def test_human_in_the_loop_middleware_single_tool_edit() -> None:assert result is not Noneassert "messages" in resultassert len(result["messages"]) == 1- assert result["messages"][0].tool_calls[0]["args"] == {"input": "edited"}+ assert result["messages"][0].tool_calls[0]["args"] == {"input": "test"}assert result["messages"][0].tool_calls[0]["id"] == "1" # ID should be preserved+ assert result[_EDITED_TOOL_CALLS_KEY] == {+ "1": {"name": "test_tool", "args": {"input": "edited"}}+ }def test_human_in_the_loop_middleware_single_tool_rejection_reason() -> None:@@ -514,10 +529,11 @@ def test_human_in_the_loop_middleware_multiple_tools_edit_responses() -> None:assert len(result["messages"]) == 1updated_ai_message = result["messages"][0]- assert updated_ai_message.tool_calls[0]["args"] == {"location": "New York"}+ assert updated_ai_message.tool_calls[0]["args"] == {"location": "San Francisco"}assert updated_ai_message.tool_calls[0]["id"] == "1" # ID preserved- assert updated_ai_message.tool_calls[1]["args"] == {"location": "New York"}+ assert updated_ai_message.tool_calls[1]["args"] == {"location": "San Francisco"}assert updated_ai_message.tool_calls[1]["id"] == "2" # ID preserved+ assert result[_EDITED_TOOL_CALLS_KEY]["1"]["args"] == {"location": "New York"}def test_human_in_the_loop_middleware_edit_with_modified_args() -> None:@@ -554,10 +570,13 @@ def test_human_in_the_loop_middleware_edit_with_modified_args() -> None:assert "messages" in resultassert len(result["messages"]) == 1- # Should have modified args+ # The model's own call is preserved; the reviewer's is recorded for execution.updated_ai_message = result["messages"][0]- assert updated_ai_message.tool_calls[0]["args"] == {"input": "modified"}+ assert updated_ai_message.tool_calls[0]["args"] == {"input": "test"}assert updated_ai_message.tool_calls[0]["id"] == "1" # ID preserved+ assert result[_EDITED_TOOL_CALLS_KEY] == {+ "1": {"name": "test_tool", "args": {"input": "modified"}}+ }def test_human_in_the_loop_middleware_unknown_response_type() -> None:@@ -749,7 +768,8 @@ def test_human_in_the_loop_middleware_boolean_configs() -> None:assert result is not Noneassert "messages" in resultassert len(result["messages"]) == 1- assert result["messages"][0].tool_calls[0]["args"] == {"input": "edited"}+ assert result["messages"][0].tool_calls[0]["args"] == {"input": "test"}+ assert result[_EDITED_TOOL_CALLS_KEY]["1"]["args"] == {"input": "edited"}middleware = HumanInTheLoopMiddleware(interrupt_on={"test_tool": False})@@ -958,7 +978,8 @@ def test_human_in_the_loop_middleware_preserves_order_with_edits() -> None:assert updated_ai_message.tool_calls[0]["name"] == "tool_a"assert updated_ai_message.tool_calls[0]["args"] == {"val": 1}assert updated_ai_message.tool_calls[1]["name"] == "tool_b"- assert updated_ai_message.tool_calls[1]["args"] == {"val": 200} # Edited+ assert updated_ai_message.tool_calls[1]["args"] == {"val": 2} # model's own+ assert result[_EDITED_TOOL_CALLS_KEY]["id_b"]["args"] == {"val": 200} # reviewer'sassert updated_ai_message.tool_calls[1]["id"] == "id_b" # ID preservedassert updated_ai_message.tool_calls[2]["name"] == "tool_c"assert updated_ai_message.tool_calls[2]["args"] == {"val": 3}@@ -1128,3 +1149,645 @@ def test_when_predicate_receives_correct_args() -> None:assert req.runtime.state is stateassert req.runtime.context is runtime.contextassert req.runtime.store is runtime.store+++def test_human_in_the_loop_middleware_edit_annotates_tool_result() -> None:+ """An edited call runs the reviewer's args and its result is attributed to them."""+ executed: list[dict[str, Any]] = []++ @tool+ def write_file_tool(path: str, content: str) -> str:+ """Write content to a file."""+ executed.append({"path": path, "content": content})+ return f"File written to {path}"++ model = FakeToolCallingModel(+ tool_calls=[+ [+ ToolCall(+ name="write_file_tool",+ args={"path": "notes.txt", "content": "Hello, world!"},+ id="1",+ )+ ],+ [],+ ]+ )+ agent = create_agent(+ model=model,+ tools=[write_file_tool],+ middleware=[+ HumanInTheLoopMiddleware(+ interrupt_on={"write_file_tool": {"allowed_decisions": ["approve", "edit"]}}+ )+ ],+ checkpointer=InMemorySaver(),+ )+ config: RunnableConfig = {"configurable": {"thread_id": "edit-annotates-result"}}++ interrupted = agent.invoke(+ {"messages": [HumanMessage("Write notes.txt with 'Hello, world!'")]}, config+ )+ assert "__interrupt__" in interrupted++ final = agent.invoke(+ Command(+ resume={+ "decisions": [+ {+ "type": "edit",+ "edited_action": {+ "name": "write_file_tool",+ "args": {"path": "notes.txt", "content": "reviewer value"},+ },+ }+ ]+ }+ ),+ config,+ )++ assert executed == [{"path": "notes.txt", "content": "reviewer value"}]++ tool_messages = [m for m in final["messages"] if isinstance(m, ToolMessage)]+ assert len(tool_messages) == 1+ content = tool_messages[0].content+ assert isinstance(content, str)+ assert content.endswith("File written to notes.txt")+ assert _EDIT_NOTICE in content+ # The original, untrusted args must not be echoed back.+ assert "Hello, world!" not in content+ assert "__interrupt__" not in final+ _assert_tool_messages_are_paired(final["messages"])+++def test_human_in_the_loop_middleware_approve_does_not_annotate() -> None:+ """An approved call was the model's own, so its result must not be annotated."""++ @tool+ def write_file_tool(path: str, content: str) -> str:+ """Write content to a file."""+ return f"File written to {path} ({len(content)} chars)"++ model = FakeToolCallingModel(+ tool_calls=[+ [ToolCall(name="write_file_tool", args={"path": "/p", "content": "c"}, id="1")],+ [],+ ]+ )+ agent = create_agent(+ model=model,+ tools=[write_file_tool],+ middleware=[+ HumanInTheLoopMiddleware(+ interrupt_on={"write_file_tool": {"allowed_decisions": ["approve", "edit"]}}+ )+ ],+ checkpointer=InMemorySaver(),+ )+ config: RunnableConfig = {"configurable": {"thread_id": "approve-no-annotation"}}+ agent.invoke({"messages": [HumanMessage("write it")]}, config)+ final = agent.invoke(Command(resume={"decisions": [{"type": "approve"}]}), config)++ tool_messages = [m for m in final["messages"] if isinstance(m, ToolMessage)]+ assert tool_messages[0].content == "File written to /p (1 chars)"+++def _edited_request(tool_call_id: str = "1") -> ToolCallRequest:+ """A `ToolCallRequest` whose call a reviewer edited."""+ ai_message = AIMessage(+ content="",+ tool_calls=[{"name": "write_file_tool", "args": {"content": "edited"}, "id": tool_call_id}],+ )+ return ToolCallRequest(+ tool_call=ToolCall(name="write_file_tool", args={"content": "edited"}, id=tool_call_id),+ tool=None,+ state=_HumanInTheLoopState[Any](+ messages=[HumanMessage("go"), ai_message],+ hitl_edited_tool_calls={+ tool_call_id: Action(name="write_file_tool", args={"content": "edited"})+ },+ ),+ runtime=None, # type: ignore[arg-type]+ )+++ ("tool_output", "expected_notice_block"),+ [+ (+ [{"type": "text", "text": "wrote it"}],+ {"type": "text", "text": _EXPECTED_NOTICE_WITH_CONTENT},+ ),+ (+ [{"type": "text", "text": "a"}, {"type": "image_url", "image_url": {"url": "u"}}],+ {"type": "text", "text": _EXPECTED_NOTICE_WITH_CONTENT},+ ),+ (["wrote it"], _EXPECTED_NOTICE_WITH_CONTENT),+ ([], {"type": "text", "text": _EXPECTED_NOTICE}), # no label without content+ ],+ ids=["text-block", "mixed-blocks", "plain-strings", "empty"],+)+def test_human_in_the_loop_middleware_edit_annotates_list_content(+ tool_output: list[Any], expected_notice_block: Any+) -> None:+ """Block-content results are annotated, preserving existing blocks and their shape."""+ middleware = HumanInTheLoopMiddleware(+ interrupt_on={"write_file_tool": {"allowed_decisions": ["edit"]}}+ )+ result = ToolMessage(content=tool_output, tool_call_id="1", name="write_file_tool")++ annotated = middleware.wrap_tool_call(_edited_request(), lambda _: result)++ assert isinstance(annotated, ToolMessage)+ assert annotated.content == [expected_notice_block, *tool_output]+++def test_human_in_the_loop_middleware_edit_annotates_command_result() -> None:+ """A `Command` result has its own `ToolMessage` annotated, leaving others intact."""+ middleware = HumanInTheLoopMiddleware(+ interrupt_on={"write_file_tool": {"allowed_decisions": ["edit"]}}+ )+ unrelated = ToolMessage(content="other", tool_call_id="99", name="other_tool")+ command: Command[Any] = Command(+ update={+ "messages": [+ ToolMessage(content="wrote it", tool_call_id="1", name="write_file_tool"),+ unrelated,+ ],+ "some_state_key": "preserved",+ }+ )++ result = middleware.wrap_tool_call(_edited_request(), lambda _: command)++ assert isinstance(result, Command)+ assert isinstance(result.update, dict)+ assert result.update["some_state_key"] == "preserved"+ annotated, passthrough = result.update["messages"]+ assert annotated.content == f"{_EXPECTED_NOTICE_WITH_CONTENT}\nwrote it"+ assert passthrough.content == "other"+++def test_human_in_the_loop_middleware_edit_notice_is_not_duplicated() -> None:+ """The notice is idempotent; retry middleware may re-invoke the handler."""+ middleware = HumanInTheLoopMiddleware(+ interrupt_on={"write_file_tool": {"allowed_decisions": ["edit"]}}+ )+ request = _edited_request()+ once = middleware.wrap_tool_call(+ request, lambda _: ToolMessage(content="wrote it", tool_call_id="1")+ )+ assert isinstance(once, ToolMessage)+ twice = middleware.wrap_tool_call(request, lambda _: once)++ assert isinstance(twice, ToolMessage)+ assert twice.content == once.content+ assert twice.content.count(_EDIT_NOTICE) == 1+++async def test_human_in_the_loop_middleware_edit_annotates_async() -> None:+ """`awrap_tool_call` must behave identically to the sync hook."""+ middleware = HumanInTheLoopMiddleware(+ interrupt_on={"write_file_tool": {"allowed_decisions": ["edit"]}}+ )++ async def handler(_: ToolCallRequest) -> ToolMessage:+ return ToolMessage(content="wrote it", tool_call_id="1", name="write_file_tool")++ result = await middleware.awrap_tool_call(_edited_request(), handler)++ assert isinstance(result, ToolMessage)+ assert result.content == f"{_EXPECTED_NOTICE_WITH_CONTENT}\nwrote it"+++def test_human_in_the_loop_middleware_edit_notice_is_customizable() -> None:+ """`edit_notice` replaces the default text."""+ middleware = HumanInTheLoopMiddleware(+ interrupt_on={"write_file_tool": {"allowed_decisions": ["edit"]}},+ edit_notice="Operator overrode these args.",+ )++ result = middleware.wrap_tool_call(+ _edited_request(), lambda _: ToolMessage(content="wrote it", tool_call_id="1")+ )++ assert isinstance(result, ToolMessage)+ assert isinstance(result.content, str)+ assert result.content.startswith("Operator overrode these args.")+ assert _EDIT_NOTICE not in result.content+++ "tool_output",+ ["wrote it", [{"type": "text", "text": "wrote it"}]],+ ids=["string", "blocks"],+)+def test_human_in_the_loop_middleware_edit_notice_can_be_disabled(tool_output: Any) -> None:+ """`edit_notice=None` leaves results untouched for both content shapes."""+ middleware = HumanInTheLoopMiddleware(+ interrupt_on={"write_file_tool": {"allowed_decisions": ["edit"]}},+ edit_notice=None,+ )++ result = middleware.wrap_tool_call(+ _edited_request(), lambda _: ToolMessage(content=tool_output, tool_call_id="1")+ )++ assert isinstance(result, ToolMessage)+ assert result.content == tool_output+++def test_human_in_the_loop_middleware_edit_executes_reviewers_call() -> None:+ """The reviewer's args run while the model's own call stays in the message."""+ executed: list[dict[str, Any]] = []++ @tool+ def write_file_tool(path: str, content: str) -> str:+ """Write content to a file."""+ executed.append({"path": path, "content": content})+ return f"File written to {path}"++ model = FakeToolCallingModel(+ tool_calls=[+ [+ ToolCall(+ name="write_file_tool", args={"path": "notes.txt", "content": "mine"}, id="1"+ )+ ],+ [],+ ]+ )+ agent = create_agent(+ model=model,+ tools=[write_file_tool],+ middleware=[+ HumanInTheLoopMiddleware(+ interrupt_on={"write_file_tool": {"allowed_decisions": ["approve", "edit"]}}+ )+ ],+ checkpointer=InMemorySaver(),+ )+ config: RunnableConfig = {"configurable": {"thread_id": "executes-reviewer-call"}}+ agent.invoke({"messages": [HumanMessage("write it")]}, config)+ final = agent.invoke(+ Command(+ resume={+ "decisions": [+ {+ "type": "edit",+ "edited_action": {+ "name": "write_file_tool",+ "args": {"path": "notes.txt", "content": "reviewers"},+ },+ }+ ]+ }+ ),+ config,+ )++ assert executed == [{"path": "notes.txt", "content": "reviewers"}]+ ai_message = next(m for m in final["messages"] if isinstance(m, AIMessage) and m.tool_calls)+ assert ai_message.tool_calls[0]["args"] == {"path": "notes.txt", "content": "mine"}+ tool_message = next(m for m in final["messages"] if isinstance(m, ToolMessage))+ assert "reviewers" in tool_message.content+ _assert_tool_messages_are_paired(final["messages"])+++def test_human_in_the_loop_middleware_edit_can_redirect_to_another_tool() -> None:+ """A reviewer may redirect the call to a different tool."""+ executed: list[str] = []++ @tool+ def send_email(to: str) -> str:+ """Send an email."""+ executed.append("send_email")+ return f"sent to {to}"++ @tool+ def draft_email(to: str) -> str:+ """Draft an email."""+ executed.append("draft_email")+ return f"drafted to {to}"++ model = FakeToolCallingModel(+ tool_calls=[[ToolCall(name="send_email", args={"to": "[email protected]"}, id="1")], []]+ )+ agent = create_agent(+ model=model,+ tools=[send_email, draft_email],+ middleware=[+ HumanInTheLoopMiddleware(+ interrupt_on={"send_email": {"allowed_decisions": ["approve", "edit"]}}+ )+ ],+ checkpointer=InMemorySaver(),+ )+ config: RunnableConfig = {"configurable": {"thread_id": "edit-redirects-tool"}}+ agent.invoke({"messages": [HumanMessage("send it")]}, config)+ final = agent.invoke(+ Command(+ resume={+ "decisions": [+ {+ "type": "edit",+ "edited_action": {"name": "draft_email", "args": {"to": "[email protected]"}},+ }+ ]+ }+ ),+ config,+ )++ assert executed == ["draft_email"]+ ai_message = next(m for m in final["messages"] if isinstance(m, AIMessage) and m.tool_calls)+ assert ai_message.tool_calls[0]["name"] == "send_email"+ tool_message = next(m for m in final["messages"] if isinstance(m, ToolMessage))+ assert "drafted" in tool_message.content+ assert "draft_email" in tool_message.content # the notice names what ran+++ ("requested", "replacement", "expected_turns_after_tool"),+ [("direct_tool", "normal_tool", 1), ("normal_tool", "direct_tool", 0)],+ ids=["direct-to-normal", "normal-to-direct"],+)+def test_human_in_the_loop_middleware_edit_routes_on_executed_tool(+ requested: str, replacement: str, expected_turns_after_tool: int+) -> None:+ """`return_direct` termination must follow the tool that ran, not the one requested."""++ @tool(return_direct=True)+ def direct_tool(x: str) -> str:+ """Return directly."""+ return f"direct {x}"++ @tool+ def normal_tool(x: str) -> str:+ """Do not return directly."""+ return f"normal {x}"++ model = FakeToolCallingModel(+ tool_calls=[[ToolCall(name=requested, args={"x": "1"}, id="1")], []]+ )+ agent = create_agent(+ model=model,+ tools=[direct_tool, normal_tool],+ middleware=[+ HumanInTheLoopMiddleware(+ interrupt_on={requested: {"allowed_decisions": ["approve", "edit"]}}+ )+ ],+ checkpointer=InMemorySaver(),+ )+ config: RunnableConfig = {"configurable": {"thread_id": f"route-{requested}-{replacement}"}}+ agent.invoke({"messages": [HumanMessage("go")]}, config)+ final = agent.invoke(+ Command(+ resume={+ "decisions": [+ {"type": "edit", "edited_action": {"name": replacement, "args": {"x": "1"}}}+ ]+ }+ ),+ config,+ )++ tool_idx = max(i for i, m in enumerate(final["messages"]) if isinstance(m, ToolMessage))+ model_turns = sum(isinstance(m, AIMessage) for m in final["messages"][tool_idx + 1 :])+ assert model_turns == expected_turns_after_tool+++def test_human_in_the_loop_middleware_edit_to_unknown_tool_raises() -> None:+ """A reviewer naming a tool the agent does not have fails loudly."""+ middleware = HumanInTheLoopMiddleware(+ interrupt_on={"write_file_tool": {"allowed_decisions": ["edit"]}}+ )++ @tool+ def write_file_tool(content: str) -> str:+ """Write content."""+ return f"wrote {len(content)} chars"++ ai_message = AIMessage(+ content="",+ tool_calls=[{"name": "write_file_tool", "args": {"content": "x"}, "id": "1"}],+ )+ request = ToolCallRequest(+ tool_call=ToolCall(name="write_file_tool", args={"content": "x"}, id="1"),+ tool=write_file_tool,+ state=_HumanInTheLoopState[Any](+ messages=[HumanMessage("go"), ai_message],+ hitl_edited_tool_calls={"1": Action(name="nope", args={"content": "y"})},+ ),+ runtime=SimpleNamespace(tools=[write_file_tool]), # type: ignore[arg-type]+ )++ with pytest.raises(ValueError, match="not an available tool"):+ middleware.wrap_tool_call(+ request, lambda _: ToolMessage(content="wrote it", tool_call_id="1")+ )+++def test_a_turn_that_resolves_no_decisions_clears_the_previous_turns_edits() -> None:+ """A recorded edit does not outlive the turn that recorded it.++ State is not scoped to a message the way `response_metadata` was, and providers are+ not required to keep tool call IDs unique across turns. `after_model` therefore+ drops the previous turn's edits the moment it reaches a turn with nothing to review,+ so a reused ID cannot pull an earlier edit onto a call that never went to a human.+ """+ middleware = HumanInTheLoopMiddleware(interrupt_on={"write_file_tool": True})+ state = _HumanInTheLoopState[Any](+ messages=[+ HumanMessage("go"),+ AIMessage(+ content="",+ tool_calls=[{"name": "read_file_tool", "args": {"path": "p"}, "id": "1"}],+ ),+ ],+ hitl_edited_tool_calls={"1": Action(name="write_file_tool", args={"content": "reviewer"})},+ )++ assert middleware.after_model(state, Runtime()) == {_EDITED_TOOL_CALLS_KEY: {}}+++def test_a_turn_with_nothing_recorded_does_not_write_state() -> None:+ """The clear is only issued when there is something to clear."""+ middleware = HumanInTheLoopMiddleware(interrupt_on={"write_file_tool": True})+ state = _HumanInTheLoopState[Any](+ messages=[+ HumanMessage("go"),+ AIMessage(+ content="",+ tool_calls=[{"name": "read_file_tool", "args": {"path": "p"}, "id": "1"}],+ ),+ ],+ )++ assert middleware.after_model(state, Runtime()) is None+++def test_reused_tool_call_id_does_not_replay_a_previous_turns_edit() -> None:+ """End to end: a later call reusing an edited call's ID runs the model's own args."""+ executed: list[tuple[str, str]] = []++ @tool+ def write_file_tool(path: str, content: str) -> str:+ """Write content to a file."""+ executed.append(("write", content))+ return f"File written to {path}"++ @tool+ def read_file_tool(path: str) -> str:+ """Read a file."""+ executed.append(("read", path))+ return f"Contents of {path}"++ model = FakeToolCallingModel(+ tool_calls=[+ [ToolCall(name="write_file_tool", args={"path": "a.txt", "content": "model"}, id="1")],+ # The same ID on a tool that is not gated, so this turn reviews nothing.+ [ToolCall(name="read_file_tool", args={"path": "b.txt"}, id="1")],+ [],+ ]+ )+ agent = create_agent(+ model=model,+ tools=[write_file_tool, read_file_tool],+ middleware=[HumanInTheLoopMiddleware(interrupt_on={"write_file_tool": True})],+ checkpointer=InMemorySaver(),+ )+ config: RunnableConfig = {"configurable": {"thread_id": "reused-tool-call-id"}}++ agent.invoke({"messages": [HumanMessage("write it, then read it")]}, config)+ final = agent.invoke(+ Command(+ resume={+ "decisions": [+ {+ "type": "edit",+ "edited_action": {+ "name": "write_file_tool",+ "args": {"path": "a.txt", "content": "reviewer"},+ },+ }+ ]+ }+ ),+ config,+ )++ assert executed == [("write", "reviewer"), ("read", "b.txt")]+ read_result = [m for m in final["messages"] if isinstance(m, ToolMessage)][-1]+ # The read was never edited, so its result carries no notice.+ assert read_result.content == "Contents of b.txt"+++def test_recorded_edit_survives_a_later_tightening_of_allowed_decisions() -> None:+ """A completed decision is honored as recorded, even under a stricter config.++ `allowed_decisions` governs what a reviewer may decide at review time. Re-checking+ it at execution time would not deny the edit: the only thing left to run would be+ the model's original call, which is precisely what the reviewer declined.+ """+ middleware = HumanInTheLoopMiddleware(+ interrupt_on={"send_email_tool": {"allowed_decisions": ["approve", "reject"]}}+ )++ @tool+ def send_email_tool(to: str) -> str:+ """Send an email."""+ return f"sent to {to}"++ @tool+ def draft_email_tool(to: str) -> str:+ """Draft an email without sending it."""+ return f"drafted to {to}"++ # Recorded while `edit` was still permitted; the config has since been tightened.+ ai_message = AIMessage(+ content="",+ tool_calls=[{"name": "send_email_tool", "args": {"to": "[email protected]"}, "id": "1"}],+ )+ request = ToolCallRequest(+ tool_call=ToolCall(name="send_email_tool", args={"to": "[email protected]"}, id="1"),+ tool=send_email_tool,+ state=_HumanInTheLoopState[Any](+ messages=[HumanMessage("go"), ai_message],+ hitl_edited_tool_calls={"1": Action(name="draft_email_tool", args={"to": "[email protected]"})},+ ),+ runtime=SimpleNamespace(tools=[send_email_tool, draft_email_tool]), # type: ignore[arg-type]+ )++ executed: list[ToolCallRequest] = []++ def handler(req: ToolCallRequest) -> ToolMessage:+ executed.append(req)+ assert req.tool is not None+ return ToolMessage(content=req.tool.invoke(req.tool_call["args"]), tool_call_id="1")++ result = middleware.wrap_tool_call(request, handler)++ # The reviewer's replacement runs; the declined original never does.+ assert [req.tool_call["name"] for req in executed] == ["draft_email_tool"]+ assert executed[0].tool is draft_email_tool+ assert isinstance(result, ToolMessage)+ assert "drafted to [email protected]" in result.content+ assert "draft_email_tool" in result.content # the notice names what ran+++async def test_async_turn_that_resolves_no_decisions_clears_the_previous_turns_edits() -> None:+ """`aafter_model` drops the previous turn's edits too."""+ middleware = HumanInTheLoopMiddleware(interrupt_on={"write_file_tool": True})+ state = _HumanInTheLoopState[Any](+ messages=[+ HumanMessage("go"),+ AIMessage(+ content="",+ tool_calls=[{"name": "read_file_tool", "args": {"path": "p"}, "id": "1"}],+ ),+ ],+ hitl_edited_tool_calls={"1": Action(name="write_file_tool", args={"content": "reviewer"})},+ )++ assert await middleware.aafter_model(state, Runtime()) == {_EDITED_TOOL_CALLS_KEY: {}}+++def test_return_direct_routing_keeps_calls_with_unnamed_results() -> None:+ """A result without a usable name must still participate in the return-direct check."""++ @tool(return_direct=True)+ def direct_tool(x: str) -> str:+ """Return directly."""+ return f"direct {x}"++ @tool+ def normal_tool(x: str) -> str:+ """Do not return directly."""+ return f"normal {x}"++ node = ToolNode([direct_tool, normal_tool])+ edge = _make_tools_to_model_edge(+ tool_node=node,+ model_destination="MODEL",+ structured_output_tools={},+ end_destination="END",+ )+ ai_message = AIMessage(+ "",+ tool_calls=[+ {"name": "direct_tool", "args": {"x": "1"}, "id": "1", "type": "tool_call"},+ {"name": "normal_tool", "args": {"x": "2"}, "id": "2", "type": "tool_call"},+ ],+ )+ messages = [+ HumanMessage("go"),+ ai_message,+ ToolMessage(content="direct result", tool_call_id="1", name="direct_tool"),+ # A tool or middleware may omit `name`; the call must not drop out of the check.+ ToolMessage(content="normal result", tool_call_id="2"),+ ]++ assert edge({"messages": messages}) == "MODEL"