The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): keep tool results keyed on a tool_call's id variant (#55626)
Bartok91a83b1e58839
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 1c89288330f..668e37ae7cb 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -3456,6 +3456,25 @@ def repair_tool_call(agent, tool_name: str) -> str | None:return None+def _tool_call_id_variants(tc: Any) -> set:+ """Return every id a tool result might legitimately match this tool_call on.++ A tool_call can carry both ``call_id`` and ``id`` with different values+ (Responses-API / codex flows), and different code paths key the matching+ ``role="tool"`` result's ``tool_call_id`` off one or the other. Returning+ all non-empty variants lets the sanitizer treat a result matching ANY of+ them as paired, so a valid result is never falsely orphaned and dropped.+ """+ variants: set = set()+ if isinstance(tc, dict):+ candidates = (tc.get("call_id"), tc.get("id"))+ else:+ candidates = (getattr(tc, "call_id", None), getattr(tc, "id", None))+ for c in candidates:+ if isinstance(c, str) and c.strip():+ variants.add(c.strip())+ return variants+# Placeholder substituted for an empty non-final message that would otherwise# make the provider reject the whole request. Kept identical to the stub-@@ -3696,8 +3715,18 @@ def sanitize_api_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]for msg in messages:if msg.get("role") == "assistant":for tc in msg.get("tool_calls") or []:- cid = _ra().AIAgent._get_tool_call_id_static(tc)- if cid:+ # A tool_call may carry BOTH ``call_id`` and ``id`` with+ # DIFFERENT values (e.g. Responses-API / codex tool calls,+ # where ``id`` is a ``fc_...`` response-item id distinct from+ # the ``call_...`` id). ``_get_tool_call_id_static`` returns+ # only the preferred one (``call_id``), but a tool result+ # keyed on the OTHER id would then look orphaned and get+ # dropped + replaced with a bogus "[Result unavailable]"+ # stub — silently eating a perfectly valid tool result+ # (#55626). Register EVERY id variant so a result matching+ # any of them survives. This is purely additive: it can only+ # prevent false drops, never introduce new ones.+ for cid in _tool_call_id_variants(tc):surviving_call_ids.add(cid)result_call_ids: set = set()@@ -3719,26 +3748,37 @@ def sanitize_api_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]len(orphaned_results),)- # 2. Inject stub results for calls whose result was dropped- missing_results = surviving_call_ids - result_call_ids- if missing_results:- patched: List[Dict[str, Any]] = []- for msg in messages:- patched.append(msg)- if msg.get("role") == "assistant":- for tc in msg.get("tool_calls") or []:- cid = _ra().AIAgent._get_tool_call_id_static(tc)- if cid in missing_results:- patched.append({- "role": "tool",- "name": _ra().AIAgent._get_tool_call_name_static(tc),- "content": "[Result unavailable — see context summary above]",- "tool_call_id": cid,- })+ # 2. Inject stub results for calls whose result was dropped.+ # A call is "answered" when ANY of its id variants (call_id/id) has a+ # matching result, so a call answered via its ``id`` (fc_...) is not+ # mistaken for unanswered just because its distinct ``call_id`` has no+ # result of its own (#55626).+ stub_count = 0+ patched: List[Dict[str, Any]] = []+ for msg in messages:+ patched.append(msg)+ if msg.get("role") == "assistant":+ for tc in msg.get("tool_calls") or []:+ variants = _tool_call_id_variants(tc)+ if not variants:+ continue+ if variants & result_call_ids:+ continue # already answered on some id variant+ cid = _ra().AIAgent._get_tool_call_id_static(tc)+ if not cid:+ continue+ patched.append({+ "role": "tool",+ "name": _ra().AIAgent._get_tool_call_name_static(tc),+ "content": "[Result unavailable — see context summary above]",+ "tool_call_id": cid,+ })+ stub_count += 1+ if stub_count:messages = patched_ra().logger.debug("Pre-call sanitizer: added %d stub tool result(s)",- len(missing_results),+ stub_count,)# 3. Deduplicate tool_call_ids. Strict providers (DeepSeek) reject adiff --git a/tests/run_agent/test_run_agent.py b/tests/run_agent/test_run_agent.pyindex 88c18fa12e5..b497a5c1e7e 100644--- a/tests/run_agent/test_run_agent.py+++ b/tests/run_agent/test_run_agent.py@@ -2848,6 +2848,51 @@ class TestHandleMaxIterations:"call_123"]+ def test_api_sanitizer_matches_responses_id_when_result_keyed_on_id(self, agent):+ """Inverse of the call_id case: a tool_call carries BOTH ``id`` (fc_...)+ and a distinct ``call_id``, but the matching result is keyed on ``id``.+ The sanitizer preferred ``call_id`` only, so it treated the valid+ result as orphaned, dropped it, and injected a bogus+ '[Result unavailable ...]' stub — silently eating a real tool result+ (e.g. mnemosyne_recall / cronjob list). The result must survive intact.+ (#55626)"""+ messages = [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "fc_456",+ "call_id": "call_456",+ "type": "function",+ "function": {"name": "mnemosyne_recall", "arguments": "{}"},+ }+ ],+ },+ {"role": "tool", "tool_call_id": "fc_456", "content": '{"results": [1, 2]}'},+ ]++ sanitized = agent._sanitize_api_messages(messages)++ tool_msgs = [m for m in sanitized if m.get("role") == "tool"]+ assert len(tool_msgs) == 1+ assert tool_msgs[0]["tool_call_id"] == "fc_456"+ assert tool_msgs[0]["content"] == '{"results": [1, 2]}'+ assert "Result unavailable" not in tool_msgs[0]["content"]++ def test_api_sanitizer_still_drops_genuinely_orphaned_result(self, agent):+ """The id-variant matching must not weaken orphan removal: a tool result+ whose tool_call_id matches NO assistant tool_call (neither call_id nor+ id) is still dropped. (#55626 regression guard)"""+ messages = [+ {"role": "user", "content": "hi"},+ {"role": "tool", "tool_call_id": "call_nomatch", "content": "orphan"},+ ]++ sanitized = agent._sanitize_api_messages(messages)++ assert all(m.get("role") != "tool" for m in sanitized)+def test_api_sanitizer_repairs_tool_call_with_empty_function_name(self, agent):"""A tool_call with id but empty function.name makes the Responses-APIadapter drop the function_call while keeping its function_call_output,