The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): normalize the final staged tool batch by effective id
unsupportedpastels3f3ae12c4ab3
diff --git a/agent/message_sanitization.py b/agent/message_sanitization.pyindex 853fed61483..e4c29fdcc6c 100644--- a/agent/message_sanitization.py+++ b/agent/message_sanitization.py@@ -580,8 +580,9 @@ def normalize_provider_tool_call_ids(tool_calls: list) -> list:"""if len(tool_calls or []) < 2:return tool_calls- ids = [(_tc_field(tc, "call_id") or _tc_field(tc, "id") or "") for tc in tool_calls]- if not all(isinstance(raw, str) and raw.split("|", 1)[0].startswith(_PROVIDER_TOOL_ID_PREFIXES) for raw in ids):+ # Gate on the effective id serialization and result pairing use (stripped, blank call_id+ # falls back to id), not on raw fields.+ if not all(coalesce_tool_call_id(tc).startswith(_PROVIDER_TOOL_ID_PREFIXES) for tc in tool_calls):return tool_callslogger.warning("Normalized provider-minted parallel tool-call ids for replay compatibility")for tc in tool_calls:@@ -591,7 +592,8 @@ def normalize_provider_tool_call_ids(tool_calls: list) -> list:value = _tc_field(tc, key)if not isinstance(value, str):continue- primary, sep, item = value.partition("|")+ primary, sep, item = value.strip().partition("|")+ primary = primary.strip()if not primary.startswith(_PROVIDER_TOOL_ID_PREFIXES):continue# surrogatepass: provider JSON can carry lone surrogates; strict utf-8 would raise,diff --git a/agent/turn_tool_round.py b/agent/turn_tool_round.pyindex e089d47a76c..2b26df672b6 100644--- a/agent/turn_tool_round.py+++ b/agent/turn_tool_round.py@@ -13,7 +13,7 @@ import loggingfrom typing import Any, Dict, Optional, Tuplefrom agent.message_metadata import append_message-from agent.message_sanitization import coalesce_tool_call_id+from agent.message_sanitization import coalesce_tool_call_id, normalize_provider_tool_call_idsfrom agent.turn_preflight import compress_after_tool_resultsfrom agent.turn_tool_validation import validate_tool_calls@@ -94,6 +94,9 @@ def run_tool_round(assistant_message.tool_calls = agent._deduplicate_tool_calls(agent._cap_delegate_task_calls(assistant_message.tool_calls))+ # Filtering can turn a mixed batch into an all-provider one; re-check the final batch+ # before it is staged (idempotent for already-normalized ids).+ normalize_provider_tool_call_ids(assistant_message.tool_calls)# Mixed batch: the assistant message keeps EVERY emitted call (each tool_call needs a# matching result) while only valid ones dispatch.diff --git a/tests/agent/test_provider_id_mint_normalization.py b/tests/agent/test_provider_id_mint_normalization.pyindex 3c6f4a160a8..5a9e7d599de 100644--- a/tests/agent/test_provider_id_mint_normalization.py+++ b/tests/agent/test_provider_id_mint_normalization.py@@ -82,6 +82,60 @@ def test_response_item_half_survives_when_only_id_is_composite(keys):assert len({row["id"] for row in stored}) == 2+def _padded(calls):+ calls[0].id = " chatcmpl-tool-a"+++def _blank_call_id(calls):+ calls[0].call_id = " "+++def _mixed_until_dedup(calls):+ # Mixed at validation; dedup then drops call_c, leaving an all-provider batch.+ calls.append(_tool_call("call_c", "a"))++[email protected]("shape", [None, _padded, _blank_call_id, _mixed_until_dedup],+ ids=["plain", "padded", "blank_call_id", "mixed_until_dedup"])+def test_final_staged_batch_never_reaches_wire_all_provider_prefixed(shape, monkeypatch):+ import agent.turn_tool_round as round_module+ from agent.transports.chat_completions import ChatCompletionsTransport++ class _Staged(Exception):+ pass++ staged = []++ def _capture(agent, *, assistant_message, **kwargs):+ staged.extend(assistant_message.tool_calls)+ raise _Staged++ monkeypatch.setattr(round_module, "stage_tool_call_message", _capture)+ agent = _agent()+ agent.quiet_mode, agent.verbose_logging = True, False+ calls = [_tool_call("chatcmpl-tool-a", "a"), _tool_call("chatcmpl-tool-b", "b")]+ if shape:+ shape(calls)+ with pytest.raises(_Staged):+ round_module.run_tool_round(+ agent, assistant_message=SimpleNamespace(content="", tool_calls=calls), finish_reason="tool_calls",+ messages=[], conversation_history=[], api_call_count=1, effective_task_id="t", user_message="read",+ system_message="", active_system_prompt="", compression_attempts=0, max_compression_attempts=1,+ final_response=None, failed=False, _turn_exit_reason=None, truncated_tool_call_retries=0,+ current_turn_user_idx=0,+ )+ rows = [_assistant_tool_call_dict(agent, tc, i) for i, tc in enumerate(staged)]+ wire = ChatCompletionsTransport().convert_messages([+ {"role": "assistant", "content": "", "tool_calls": rows},+ *[{"role": "tool", "tool_call_id": AIAgent._get_tool_call_id_static(tc), "content": "ok"} for tc in staged],+ ])+ ids = [c["id"] for c in wire[0]["tool_calls"]]++ assert len(ids) == 2+ assert ids == [m["tool_call_id"] for m in wire[1:]]+ assert not any(i.startswith("chatcmpl-tool-") for i in ids), ids++def test_unencodable_provider_ids_do_not_crash_and_stay_distinct():raw = ["chatcmpl-tool-\ud800", "chatcmpl-tool-?"]ids = [row["id"] for row in _mint([_tool_call(i, n) for n, i in enumerate(raw)])]