From 12ed9ad222164fed637615115dfad547308abb8d Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:49:15 +0000 Subject: [PATCH 1/2] fix(agent): run on_response_received when resumed history holds SDK models A live turn stores the SDK's pydantic function_call item in conversation state. The resume path only matched dict-like history items, so with an in-memory state accessor the caller's function_call_output skipped the tool's on_response_received hook and output validation and was sent to the model unchanged. Read history and output items through their dumped form so both representations match. --- src/openrouter_agent/tool_executor.py | 18 ++-- tests/unit/test_hitl_model_history.py | 134 ++++++++++++++++++++++++++ 2 files changed, 144 insertions(+), 8 deletions(-) create mode 100644 tests/unit/test_hitl_model_history.py diff --git a/src/openrouter_agent/tool_executor.py b/src/openrouter_agent/tool_executor.py index 93617a9..4e24042 100644 --- a/src/openrouter_agent/tool_executor.py +++ b/src/openrouter_agent/tool_executor.py @@ -2,7 +2,7 @@ from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence -from ._utils import is_content_array, json_dumps, json_loads_maybe, maybe_await, schema_to_json_schema, validate_schema +from ._utils import dump, is_content_array, json_dumps, json_loads_maybe, maybe_await, schema_to_json_schema, validate_schema from .tool_context import ToolContextStore, build_tool_execute_context from .tool_types import ( ParsedToolCall, @@ -203,15 +203,17 @@ async def apply_on_response_received_hooks( if not tools: return input_items items = input_items if isinstance(input_items, list) else [input_items] + # Items echoed back from a live turn are SDK pydantic models, not dicts. + as_mappings = [item if isinstance(item, Mapping) else dump(item) for item in items] call_names: Dict[str, str] = {} - for item in items: - if isinstance(item, Mapping) and item.get("type") == "function_call": - call_names[str(item.get("callId") or item.get("call_id") or item.get("id"))] = str(item.get("name", "")) + for entry in as_mappings: + if isinstance(entry, Mapping) and entry.get("type") == "function_call": + call_names[str(entry.get("callId") or entry.get("call_id") or entry.get("id"))] = str(entry.get("name", "")) rewritten: List[Any] = [] changed = False - for item in items: + for original, item in zip(items, as_mappings, strict=True): if not (isinstance(item, Mapping) and item.get("type") == "function_call_output"): - rewritten.append(item) + rewritten.append(original) continue call_id = str(item.get("callId") or item.get("call_id") or "") name = call_names.get(call_id) @@ -224,7 +226,7 @@ async def apply_on_response_received_hooks( None, ) if tool is None: - rewritten.append(item) + rewritten.append(original) continue hook = get_tool_function(tool).get("on_response_received") ctx = build_tool_execute_context(tool, turn_context, context_store, shared_context_schema) @@ -233,7 +235,7 @@ async def apply_on_response_received_hooks( if not hook: try: validate_schema(get_tool_function(tool).get("output_schema"), raw) - rewritten.append(item) + rewritten.append(original) continue except Exception as exc: new_item["output"] = json_dumps({"error": str(exc), "originalOutput": raw}) diff --git a/tests/unit/test_hitl_model_history.py b/tests/unit/test_hitl_model_history.py new file mode 100644 index 0000000..9088931 --- /dev/null +++ b/tests/unit/test_hitl_model_history.py @@ -0,0 +1,134 @@ +"""HITL resume must find the original call when history holds SDK models. + +A live turn stores the generated SDK's pydantic `OutputFunctionCallItem` in +conversation state. Resuming from that in-memory state must still run the +tool's `on_response_received` hook (and output validation) on the caller's +`function_call_output`, exactly as it does after a serialize/deserialize +round trip turns the history into dicts. +""" + +from __future__ import annotations + +import json +from typing import Any, Dict, List + +import httpx +from openrouter.components import OutputFunctionCallItem + +from openrouter_agent import OpenRouter, call_model, tool +from openrouter_agent.tool_executor import apply_on_response_received_hooks +from tests._fixtures import MemoryStateAccessor + +PRIVATE = "reviewer-only-note" + + +def _response(response_id: str, output: List[Dict[str, Any]]) -> Dict[str, Any]: + return { + "id": response_id, + "object": "response", + "created_at": 0, + "completed_at": 0, + "status": "completed", + "model": "test/model", + "error": None, + "incomplete_details": None, + "instructions": None, + "metadata": None, + "frequency_penalty": None, + "presence_penalty": None, + "temperature": None, + "top_p": None, + "tool_choice": "auto", + "tools": [], + "parallel_tool_calls": False, + "output": output, + } + + +def _review_tool(calls: List[Any]) -> Any: + def strip_private(raw: Any, _ctx: Any) -> Dict[str, Any]: + calls.append(raw) + return {"decision": raw["decision"]} + + return tool( + name="review", + input_schema=dict, + output_schema=dict, + on_tool_called=lambda _args, _ctx: None, + on_response_received=strip_private, + ) + + +def _output_item() -> Dict[str, Any]: + return { + "type": "function_call_output", + "callId": "call_1", + "output": json.dumps({"decision": "approved", "private": PRIVATE}), + } + + +async def test_hook_runs_for_pydantic_function_call_in_history() -> None: + calls: List[Any] = [] + historical = OutputFunctionCallItem( + type="function_call", id="fc_1", call_id="call_1", name="review", arguments="{}", status="completed" + ) + hooked = await apply_on_response_received_hooks([historical, _output_item()], [_review_tool(calls)]) + + assert hooked[0] is historical + assert len(calls) == 1 + assert json.loads(hooked[1]["output"]) == {"decision": "approved"} + + +async def test_in_memory_hitl_resume_sends_hook_output_not_raw_output() -> None: + requests: List[Dict[str, Any]] = [] + first = _response( + "resp_1", + [ + { + "type": "function_call", + "id": "fc_1", + "call_id": "call_1", + "name": "review", + "arguments": "{}", + "status": "completed", + } + ], + ) + second = _response( + "resp_2", + [ + { + "type": "message", + "id": "msg_2", + "role": "assistant", + "status": "completed", + "content": [{"type": "output_text", "text": "done", "annotations": []}], + } + ], + ) + + def handle(request: httpx.Request) -> httpx.Response: + requests.append(json.loads(request.content)) + event = {"type": "response.completed", "sequence_number": 1, "response": first if len(requests) == 1 else second} + return httpx.Response( + 200, headers={"content-type": "text/event-stream"}, content=f"data: {json.dumps(event)}\n\n".encode() + ) + + calls: List[Any] = [] + review = _review_tool(calls) + accessor = MemoryStateAccessor() + async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as http_client: + client = OpenRouter(api_key="test", server_url="http://127.0.0.1:9", async_client=http_client) + await call_model(client, {"model": "test/model", "input": "go", "tools": [review], "state": accessor}).get_response() + assert accessor.stored is not None and accessor.stored.status == "awaiting_hitl" + assert any(isinstance(item, OutputFunctionCallItem) for item in accessor.stored.messages) + + await call_model( + client, {"model": "test/model", "input": [_output_item()], "tools": [review], "state": accessor} + ).get_response() + + assert len(requests) == 2 + sent = [item for item in requests[1]["input"] if item.get("type") == "function_call_output"] + assert len(calls) == 1 + assert [json.loads(item["output"]) for item in sent] == [{"decision": "approved"}] + assert PRIVATE not in json.dumps(requests[1]) From 5fe371586fb2f50d05372aa4e38458c58af45e71 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:50:11 +0000 Subject: [PATCH 2/2] style: ruff format --- src/openrouter_agent/tool_executor.py | 10 +++++++++- tests/unit/test_hitl_model_history.py | 10 ++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/openrouter_agent/tool_executor.py b/src/openrouter_agent/tool_executor.py index 4e24042..7107d39 100644 --- a/src/openrouter_agent/tool_executor.py +++ b/src/openrouter_agent/tool_executor.py @@ -2,7 +2,15 @@ from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence -from ._utils import dump, is_content_array, json_dumps, json_loads_maybe, maybe_await, schema_to_json_schema, validate_schema +from ._utils import ( + dump, + is_content_array, + json_dumps, + json_loads_maybe, + maybe_await, + schema_to_json_schema, + validate_schema, +) from .tool_context import ToolContextStore, build_tool_execute_context from .tool_types import ( ParsedToolCall, diff --git a/tests/unit/test_hitl_model_history.py b/tests/unit/test_hitl_model_history.py index 9088931..a1c8a51 100644 --- a/tests/unit/test_hitl_model_history.py +++ b/tests/unit/test_hitl_model_history.py @@ -109,7 +109,11 @@ async def test_in_memory_hitl_resume_sends_hook_output_not_raw_output() -> None: def handle(request: httpx.Request) -> httpx.Response: requests.append(json.loads(request.content)) - event = {"type": "response.completed", "sequence_number": 1, "response": first if len(requests) == 1 else second} + event = { + "type": "response.completed", + "sequence_number": 1, + "response": first if len(requests) == 1 else second, + } return httpx.Response( 200, headers={"content-type": "text/event-stream"}, content=f"data: {json.dumps(event)}\n\n".encode() ) @@ -119,7 +123,9 @@ def handle(request: httpx.Request) -> httpx.Response: accessor = MemoryStateAccessor() async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as http_client: client = OpenRouter(api_key="test", server_url="http://127.0.0.1:9", async_client=http_client) - await call_model(client, {"model": "test/model", "input": "go", "tools": [review], "state": accessor}).get_response() + await call_model( + client, {"model": "test/model", "input": "go", "tools": [review], "state": accessor} + ).get_response() assert accessor.stored is not None and accessor.stored.status == "awaiting_hitl" assert any(isinstance(item, OutputFunctionCallItem) for item in accessor.stored.messages)